blob: a0dafddc623be9ca8fc9f3c8d34d2fd316d80d13 [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
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070019import android.annotation.Nullable;
Dianne Hackborn61659e52014-07-09 16:13:01 -070020import android.app.ActivityManager;
Adam Lesinski33dac552015-03-09 15:24:48 -070021import android.bluetooth.BluetoothActivityEnergyInfo;
Adam Lesinski50e47602015-12-04 17:04:54 -080022import android.bluetooth.UidTraffic;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080023import android.content.Context;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070024import android.content.Intent;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070025import android.net.ConnectivityManager;
26import android.net.NetworkStats;
Adam Lesinski33dac552015-03-09 15:24:48 -070027import android.net.wifi.WifiActivityEnergyInfo;
Dianne Hackborn3251b902014-06-20 14:40:53 -070028import android.net.wifi.WifiManager;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070029import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.os.BatteryStats;
Dianne Hackborncd0e3352014-08-07 17:08:09 -070031import android.os.Build;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070032import android.os.FileUtils;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070033import android.os.Handler;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080034import android.os.IBatteryPropertiesRegistrar;
Jeff Brown6f357d32014-01-15 20:40:55 -080035import android.os.Looper;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070036import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.Parcel;
38import android.os.ParcelFormatException;
39import android.os.Parcelable;
Evan Millarc64edde2009-04-18 12:26:32 -070040import android.os.Process;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080041import android.os.RemoteException;
42import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.SystemClock;
Jeff Sharkey418d12d2011-12-13 15:38:03 -080044import android.os.SystemProperties;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070045import android.os.WorkSource;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070046import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080047import android.telephony.ModemActivityInfo;
Amith Yamasanif37447b2009-10-08 18:28:01 -070048import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070049import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070050import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070051import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070052import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070054import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070055import android.util.LongSparseArray;
56import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070057import android.util.MutableInt;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070058import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070060import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080062import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070063import android.util.SparseLongArray;
Dianne Hackbornae384452011-06-28 12:33:48 -070064import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080065import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070066import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
Adam Lesinski98f0d462016-04-19 16:46:20 -070068import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070069import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080070import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070071import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080072import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070073import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080074import com.android.internal.util.XmlUtils;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070075import com.android.server.NetworkManagementSocketTagger;
76import libcore.util.EmptyArray;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080077import org.xmlpull.v1.XmlPullParser;
78import org.xmlpull.v1.XmlPullParserException;
79import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070080
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080081import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import java.io.File;
83import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080084import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import java.io.FileOutputStream;
86import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070087import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010088import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import java.util.ArrayList;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080090import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -070092import java.util.Iterator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import java.util.Map;
Christopher Tate4cee7252010-03-19 14:50:40 -070094import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070095import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
97/**
98 * All information we are collecting about things that can happen that impact
99 * battery life. All times are represented in microseconds except where indicated
100 * otherwise.
101 */
Joe Onoratoabded112016-02-08 16:49:39 -0800102public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800104 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700105 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800106 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700107 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700108 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700109 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700110
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700111 // TODO: remove "tcp" from network methods, since we measure total stats.
112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700114 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
116 // Current on-disk Parcel version
Kweku Adams47db5a82016-12-09 19:04:50 -0800117 private static final int VERSION = 151 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700118
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700119 // Maximum number of items we will record in the history.
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700120 private static final int MAX_HISTORY_ITEMS = 2000;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700121
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700122 // No, really, THIS is the maximum number of items we will record in the history.
123 private static final int MAX_MAX_HISTORY_ITEMS = 3000;
124
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800125 // The maximum number of names wakelocks we will keep track of
126 // per uid; once the limit is reached, we batch the remaining wakelocks
127 // in to one common name.
Dianne Hackbornacc4a122014-08-18 16:33:44 -0700128 private static final int MAX_WAKELOCKS_PER_UID = 100;
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700129
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800130 // Number of transmit power states the Wifi controller can be in.
131 private static final int NUM_WIFI_TX_LEVELS = 1;
132
133 // Number of transmit power states the Bluetooth controller can be in.
134 private static final int NUM_BT_TX_LEVELS = 1;
135
Joe Onoratoabded112016-02-08 16:49:39 -0800136 protected Clocks mClocks;
137
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700138 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700139 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800140 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700142 static final int MSG_UPDATE_WAKELOCKS = 1;
143 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700144 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700145 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700146
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700147 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
148 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
149
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700150 private final KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
Adam Lesinski6832f392015-09-05 18:05:40 -0700151 private KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700152
James Carr3a226052016-07-01 14:49:52 -0700153 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
154 = new KernelMemoryBandwidthStats();
155 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
156 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
157 return mKernelMemoryStats;
158 }
159
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700160 public interface BatteryCallback {
161 public void batteryNeedsCpuUpdate();
162 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700163 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700164 }
165
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700166 public interface PlatformIdleStateCallback {
167 public String getPlatformLowPowerStats();
168 }
169
170 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
171
172
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700173 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800174 public MyHandler(Looper looper) {
175 super(looper, null, true);
176 }
177
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700178 @Override
179 public void handleMessage(Message msg) {
180 BatteryCallback cb = mCallback;
181 switch (msg.what) {
182 case MSG_UPDATE_WAKELOCKS:
Adam Lesinski72478f02015-06-17 15:39:43 -0700183 synchronized (BatteryStatsImpl.this) {
184 updateCpuTimeLocked();
185 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700186 if (cb != null) {
187 cb.batteryNeedsCpuUpdate();
188 }
189 break;
190 case MSG_REPORT_POWER_CHANGE:
191 if (cb != null) {
192 cb.batteryPowerChanged(msg.arg1 != 0);
193 }
194 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700195 case MSG_REPORT_CHARGING:
196 if (cb != null) {
197 final String action;
198 synchronized (BatteryStatsImpl.this) {
199 action = mCharging ? BatteryManager.ACTION_CHARGING
200 : BatteryManager.ACTION_DISCHARGING;
201 }
202 Intent intent = new Intent(action);
203 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
204 cb.batterySendBroadcast(intent);
205 }
206 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700207 }
208 }
209 }
210
Joe Onoratoabded112016-02-08 16:49:39 -0800211 public interface Clocks {
212 public long elapsedRealtime();
213 public long uptimeMillis();
214 }
215
216 public static class SystemClocks implements Clocks {
217 public long elapsedRealtime() {
218 return SystemClock.elapsedRealtime();
219 }
220
221 public long uptimeMillis() {
222 return SystemClock.uptimeMillis();
223 }
224 }
225
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700226 public interface ExternalStatsSync {
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800227 public static final int UPDATE_CPU = 0x01;
228 public static final int UPDATE_WIFI = 0x02;
229 public static final int UPDATE_RADIO = 0x04;
230 public static final int UPDATE_BT = 0x08;
231 public static final int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT;
232
233 void scheduleSync(String reason, int flags);
Adam Lesinski61db88f2015-07-01 15:05:07 -0700234 void scheduleCpuSyncDueToRemovedUid(int uid);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700235 }
236
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700237 public final MyHandler mHandler;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700238 private final ExternalStatsSync mExternalSync;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700239
240 private BatteryCallback mCallback;
241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800243 * Mapping isolated uids to the actual owning app uid.
244 */
245 final SparseIntArray mIsolatedUids = new SparseIntArray();
246
247 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 * The statistics we have collected organized by uids.
249 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800250 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
252 // A set of pools of currently active timers. When a timer is queried, we will divide the
253 // elapsed time by the number of active timers to arrive at that timer's share of the time.
254 // In order to do this, we must refresh each timer whenever the number of active timers
255 // changes.
Adam Lesinskie08af192015-03-25 16:42:59 -0700256 final ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
257 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
258 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700259 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700260 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
261 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
262 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
263 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
264 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
265 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
266 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
267 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700268 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
269 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800270 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700272 // Last partial timers we use for distributing CPU usage.
Adam Lesinskie08af192015-03-25 16:42:59 -0700273 final ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 // These are the objects that will want to do something when the device
276 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800277 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800278
279 // These are the objects that will want to do something when the device
280 // is unplugged from power *and* the screen is off.
281 final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
282
283 // Set to true when we want to distribute CPU across wakelocks for the next
284 // CPU update, even if we aren't currently running wake locks.
285 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700286
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700287 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700288
Dianne Hackborn37de0982014-05-09 09:32:18 -0700289 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800290
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700291 long mHistoryBaseTime;
292 boolean mHaveBatteryLevel = false;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700293 boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700294 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700295
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700296 static final int MAX_HISTORY_BUFFER = 256*1024; // 256KB
297 static final int MAX_MAX_HISTORY_BUFFER = 320*1024; // 320KB
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700298 final Parcel mHistoryBuffer = Parcel.obtain();
299 final HistoryItem mHistoryLastWritten = new HistoryItem();
300 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700301 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700302 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700303 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800304 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800305 int[] mReadHistoryUids;
306 int mReadHistoryChars;
307 int mNextHistoryTagIdx = 0;
308 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700309 int mHistoryBufferLastPos = -1;
310 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700311 int mActiveHistoryStates = 0xffffffff;
312 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700313 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700314 long mTrackRunningHistoryElapsedRealtime = 0;
315 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700316
317 final HistoryItem mHistoryCur = new HistoryItem();
318
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700319 HistoryItem mHistory;
320 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700321 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700322 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700323
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800324 // Used by computeHistoryStepDetails
325 HistoryStepDetails mLastHistoryStepDetails = null;
326 byte mLastHistoryStepLevel = 0;
327 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
328 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
329 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700330
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800331 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700332 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800333 */
334 long mLastStepCpuUserTime;
335 long mCurStepCpuUserTime;
336 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700337 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800338 */
339 long mLastStepCpuSystemTime;
340 long mCurStepCpuSystemTime;
341 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700342 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800343 */
344 long mLastStepStatUserTime;
345 long mLastStepStatSystemTime;
346 long mLastStepStatIOWaitTime;
347 long mLastStepStatIrqTime;
348 long mLastStepStatSoftIrqTime;
349 long mLastStepStatIdleTime;
350 long mCurStepStatUserTime;
351 long mCurStepStatSystemTime;
352 long mCurStepStatIOWaitTime;
353 long mCurStepStatIrqTime;
354 long mCurStepStatSoftIrqTime;
355 long mCurStepStatIdleTime;
356
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700357 private HistoryItem mHistoryIterator;
358 private boolean mReadOverflow;
359 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 int mStartCount;
362
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800363 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700364 String mStartPlatformVersion;
365 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 long mUptime;
368 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 long mRealtime;
370 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700371
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800372 int mWakeLockNesting;
373 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700374 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700375 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800376
Jeff Browne95c3cd2014-05-02 16:59:26 -0700377 int mScreenState = Display.STATE_UNKNOWN;
Evan Millarc64edde2009-04-18 12:26:32 -0700378 StopwatchTimer mScreenOnTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700379
Dianne Hackborn617f8772009-03-31 15:04:46 -0700380 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700381 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700382
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800383 boolean mPretendScreenOff;
384
Jeff Browne95c3cd2014-05-02 16:59:26 -0700385 boolean mInteractive;
386 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700387
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700388 boolean mPowerSaveModeEnabled;
389 StopwatchTimer mPowerSaveModeEnabledTimer;
390
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700391 boolean mDeviceIdling;
392 StopwatchTimer mDeviceIdlingTimer;
393
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700394 boolean mDeviceLightIdling;
395 StopwatchTimer mDeviceLightIdlingTimer;
396
397 int mDeviceIdleMode;
398 long mLastIdleTimeStart;
399 long mLongestLightIdleTime;
400 long mLongestFullIdleTime;
401 StopwatchTimer mDeviceIdleModeLightTimer;
402 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700405 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700406
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700407 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700408 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700409
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700410 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700411 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700412
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700413 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700414 StopwatchTimer mFlashlightOnTimer;
415
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700416 int mCameraOnNesting;
417 StopwatchTimer mCameraOnTimer;
418
Dianne Hackborn627bba72009-03-24 22:32:56 -0700419 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800420 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700421 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800422 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700423
424 StopwatchTimer mPhoneSignalScanningTimer;
425
Dianne Hackborn627bba72009-03-24 22:32:56 -0700426 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700427 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700428 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700429
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800430 final LongSamplingCounter[] mNetworkByteActivityCounters =
431 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
432 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700433 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
434
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800435 /**
436 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
437 */
438 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700439
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800440 /**
441 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
442 */
443 ControllerActivityCounterImpl mBluetoothActivity;
444
445 /**
446 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
447 */
448 ControllerActivityCounterImpl mModemActivity;
449
450 /**
451 * Whether the device supports WiFi controller energy reporting. This is set to true on
452 * the first WiFi energy report. See {@link #mWifiActivity}.
453 */
454 boolean mHasWifiReporting = false;
455
456 /**
457 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
458 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
459 */
460 boolean mHasBluetoothReporting = false;
461
462 /**
463 * Whether the device supports Modem controller energy reporting. This is set to true on
464 * the first Modem energy report. See {@link #mModemActivity}.
465 */
466 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700467
The Android Open Source Project10592532009-03-18 17:39:46 -0700468 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700469 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700470
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700471 boolean mGlobalWifiRunning;
472 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700473
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800474 int mWifiState = -1;
475 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
476
Dianne Hackborn3251b902014-06-20 14:40:53 -0700477 int mWifiSupplState = -1;
478 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
479
480 int mWifiSignalStrengthBin = -1;
481 final StopwatchTimer[] mWifiSignalStrengthsTimer =
482 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
483
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800484 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800485 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
486 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800487
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700488 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700489 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800490 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800491 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700492 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800493 LongSamplingCounter mMobileRadioActiveUnknownTime;
494 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800495
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700496 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 /**
499 * These provide time bases that discount the time the device is plugged
500 * in to power.
501 */
502 boolean mOnBattery;
503 boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700504
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700505 /**
506 * External reporting of whether the device is actually charging.
507 */
508 boolean mCharging = true;
509 int mLastChargingStateLevel;
510
The Android Open Source Project10592532009-03-18 17:39:46 -0700511 /*
512 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
513 */
Evan Millar633a1742009-04-02 16:36:33 -0700514 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700515 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700516 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700517 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700518 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700519 int mLowDischargeAmountSinceCharge;
520 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800521 int mDischargeScreenOnUnplugLevel;
522 int mDischargeScreenOffUnplugLevel;
523 int mDischargeAmountScreenOn;
524 int mDischargeAmountScreenOnSinceCharge;
525 int mDischargeAmountScreenOff;
526 int mDischargeAmountScreenOffSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700527
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700528 private LongSamplingCounter mDischargeScreenOffCounter;
529 private LongSamplingCounter mDischargeCounter;
530
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700531 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700532
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700533 int mInitStepMode = 0;
534 int mCurStepMode = 0;
535 int mModStepMode = 0;
536
Dianne Hackborn260c5022014-04-29 11:23:16 -0700537 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700538 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800539 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
540 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700541 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700542
543 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700544 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800545 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
546 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
547
548 static final int MAX_DAILY_ITEMS = 10;
549
550 long mDailyStartTime = 0;
551 long mNextMinDailyDeadline = 0;
552 long mNextMaxDailyDeadline = 0;
553
554 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700557
Amith Yamasanif37447b2009-10-08 18:28:01 -0700558 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800559 private int mPhoneServiceStateRaw = -1;
560 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700561
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800562 private int mNumConnectivityChange;
563 private int mLoadedNumConnectivityChange;
564 private int mUnpluggedNumConnectivityChange;
565
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700566 private int mEstimatedBatteryCapacity = -1;
567
Adam Lesinski041d9172016-12-12 12:03:56 -0800568 // Last learned capacity reported by BatteryService in
569 // setBatteryState().
570 private int mLastChargeFullUAh = 0;
571
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700572 private final NetworkStats.Entry mTmpNetworkStatsEntry = new NetworkStats.Entry();
573
Adam Lesinskie08af192015-03-25 16:42:59 -0700574 private PowerProfile mPowerProfile;
575
Evan Millarc64edde2009-04-18 12:26:32 -0700576 /*
577 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
578 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700579 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700580
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700581 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700582 return mKernelWakelockStats;
583 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700584
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700585 String mLastWakeupReason = null;
586 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700587 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700588
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700589 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700590 return mWakeupReasonStats;
591 }
592
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700593 @Override
594 public LongCounter getDischargeScreenOffCoulombCounter() {
595 return mDischargeScreenOffCounter;
596 }
597
598 @Override
599 public LongCounter getDischargeCoulombCounter() {
600 return mDischargeCounter;
601 }
602
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700603 @Override
604 public int getEstimatedBatteryCapacity() {
605 return mEstimatedBatteryCapacity;
606 }
607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -0800609 this(new SystemClocks());
610 }
611
612 public BatteryStatsImpl(Clocks clocks) {
613 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700614 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700615 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800616 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700617 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700618 mExternalSync = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700619 mPlatformIdleStateCallback = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700620 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 }
622
Joe Onoratoabded112016-02-08 16:49:39 -0800623 private void init(Clocks clocks) {
624 mClocks = clocks;
625 mMobileNetworkStats = new NetworkStats[] {
626 new NetworkStats(mClocks.elapsedRealtime(), 50),
627 new NetworkStats(mClocks.elapsedRealtime(), 50),
628 new NetworkStats(mClocks.elapsedRealtime(), 50)
629 };
630 mWifiNetworkStats = new NetworkStats[] {
631 new NetworkStats(mClocks.elapsedRealtime(), 50),
632 new NetworkStats(mClocks.elapsedRealtime(), 50),
633 new NetworkStats(mClocks.elapsedRealtime(), 50)
634 };
635 }
636
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800637 public static interface TimeBaseObs {
638 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
639 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
640 }
641
Joe Onoratoabded112016-02-08 16:49:39 -0800642 // methods are protected not private to be VisibleForTesting
643 public static class TimeBase {
644 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800645
Joe Onoratoabded112016-02-08 16:49:39 -0800646 protected long mUptime;
647 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800648
Joe Onoratoabded112016-02-08 16:49:39 -0800649 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800650
Joe Onoratoabded112016-02-08 16:49:39 -0800651 protected long mPastUptime;
652 protected long mUptimeStart;
653 protected long mPastRealtime;
654 protected long mRealtimeStart;
655 protected long mUnpluggedUptime;
656 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800657
658 public void dump(PrintWriter pw, String prefix) {
659 StringBuilder sb = new StringBuilder(128);
660 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
661 sb.setLength(0);
662 sb.append(prefix);
663 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700664 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800665 pw.println(sb.toString());
666 sb.setLength(0);
667 sb.append(prefix);
668 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700669 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800670 pw.println(sb.toString());
671 sb.setLength(0);
672 sb.append(prefix);
673 sb.append("mPastUptime=");
674 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
675 formatTimeMs(sb, mUptimeStart / 1000);
676 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
677 pw.println(sb.toString());
678 sb.setLength(0);
679 sb.append(prefix);
680 sb.append("mPastRealtime=");
681 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
682 formatTimeMs(sb, mRealtimeStart / 1000);
683 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
684 pw.println(sb.toString());
685 }
686
687 public void add(TimeBaseObs observer) {
688 mObservers.add(observer);
689 }
690
691 public void remove(TimeBaseObs observer) {
692 if (!mObservers.remove(observer)) {
693 Slog.wtf(TAG, "Removed unknown observer: " + observer);
694 }
695 }
696
Joe Onoratoabded112016-02-08 16:49:39 -0800697 public boolean hasObserver(TimeBaseObs observer) {
698 return mObservers.contains(observer);
699 }
700
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800701 public void init(long uptime, long realtime) {
702 mRealtime = 0;
703 mUptime = 0;
704 mPastUptime = 0;
705 mPastRealtime = 0;
706 mUptimeStart = uptime;
707 mRealtimeStart = realtime;
708 mUnpluggedUptime = getUptime(mUptimeStart);
709 mUnpluggedRealtime = getRealtime(mRealtimeStart);
710 }
711
712 public void reset(long uptime, long realtime) {
713 if (!mRunning) {
714 mPastUptime = 0;
715 mPastRealtime = 0;
716 } else {
717 mUptimeStart = uptime;
718 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -0800719 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
720 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800721 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -0800722 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800723 mUnpluggedRealtime = getRealtime(realtime);
724 }
725 }
726
727 public long computeUptime(long curTime, int which) {
728 switch (which) {
729 case STATS_SINCE_CHARGED:
730 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800731 case STATS_CURRENT:
732 return getUptime(curTime);
733 case STATS_SINCE_UNPLUGGED:
734 return getUptime(curTime) - mUnpluggedUptime;
735 }
736 return 0;
737 }
738
739 public long computeRealtime(long curTime, int which) {
740 switch (which) {
741 case STATS_SINCE_CHARGED:
742 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800743 case STATS_CURRENT:
744 return getRealtime(curTime);
745 case STATS_SINCE_UNPLUGGED:
746 return getRealtime(curTime) - mUnpluggedRealtime;
747 }
748 return 0;
749 }
750
751 public long getUptime(long curTime) {
752 long time = mPastUptime;
753 if (mRunning) {
754 time += curTime - mUptimeStart;
755 }
756 return time;
757 }
758
759 public long getRealtime(long curTime) {
760 long time = mPastRealtime;
761 if (mRunning) {
762 time += curTime - mRealtimeStart;
763 }
764 return time;
765 }
766
767 public long getUptimeStart() {
768 return mUptimeStart;
769 }
770
771 public long getRealtimeStart() {
772 return mRealtimeStart;
773 }
774
775 public boolean isRunning() {
776 return mRunning;
777 }
778
779 public boolean setRunning(boolean running, long uptime, long realtime) {
780 if (mRunning != running) {
781 mRunning = running;
782 if (running) {
783 mUptimeStart = uptime;
784 mRealtimeStart = realtime;
785 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
786 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
787
788 for (int i = mObservers.size() - 1; i >= 0; i--) {
789 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
790 }
791 } else {
792 mPastUptime += uptime - mUptimeStart;
793 mPastRealtime += realtime - mRealtimeStart;
794
795 long batteryUptime = getUptime(uptime);
796 long batteryRealtime = getRealtime(realtime);
797
798 for (int i = mObservers.size() - 1; i >= 0; i--) {
799 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
800 }
801 }
802 return true;
803 }
804 return false;
805 }
806
807 public void readSummaryFromParcel(Parcel in) {
808 mUptime = in.readLong();
809 mRealtime = in.readLong();
810 }
811
812 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
813 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
814 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
815 }
816
817 public void readFromParcel(Parcel in) {
818 mRunning = false;
819 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800820 mPastUptime = in.readLong();
821 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -0700822 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800823 mPastRealtime = in.readLong();
824 mRealtimeStart = in.readLong();
825 mUnpluggedUptime = in.readLong();
826 mUnpluggedRealtime = in.readLong();
827 }
828
829 public void writeToParcel(Parcel out, long uptime, long realtime) {
830 final long runningUptime = getUptime(uptime);
831 final long runningRealtime = getRealtime(realtime);
832 out.writeLong(mUptime);
833 out.writeLong(runningUptime);
834 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -0700835 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800836 out.writeLong(runningRealtime);
837 out.writeLong(mRealtimeStart);
838 out.writeLong(mUnpluggedUptime);
839 out.writeLong(mUnpluggedRealtime);
840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -0700844 * State for keeping track of counting information.
845 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800846 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -0700847 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800848 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700849 int mLoadedCount;
850 int mLastCount;
851 int mUnpluggedCount;
852 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700853
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800854 Counter(TimeBase timeBase, Parcel in) {
855 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -0700856 mPluggedCount = in.readInt();
857 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700858 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700859 mLastCount = 0;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700860 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800861 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700862 }
863
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800864 Counter(TimeBase timeBase) {
865 mTimeBase = timeBase;
866 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700867 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700868
Dianne Hackborn617f8772009-03-31 15:04:46 -0700869 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700870 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700871 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700872 out.writeInt(mUnpluggedCount);
873 }
874
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800875 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700876 mUnpluggedCount = mPluggedCount;
877 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700878 }
879
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800880 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700881 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700882 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700883
Dianne Hackborn617f8772009-03-31 15:04:46 -0700884 /**
885 * Writes a possibly null Counter to a Parcel.
886 *
887 * @param out the Parcel to be written to.
888 * @param counter a Counter, or null.
889 */
890 public static void writeCounterToParcel(Parcel out, Counter counter) {
891 if (counter == null) {
892 out.writeInt(0); // indicates null
893 return;
894 }
895 out.writeInt(1); // indicates non-null
896
897 counter.writeToParcel(out);
898 }
899
900 @Override
Evan Millarc64edde2009-04-18 12:26:32 -0700901 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -0700902 int val = mCount.get();
903 if (which == STATS_SINCE_UNPLUGGED) {
904 val -= mUnpluggedCount;
905 } else if (which != STATS_SINCE_CHARGED) {
906 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700907 }
908
909 return val;
910 }
911
912 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700913 pw.println(prefix + "mCount=" + mCount.get()
Dianne Hackborn617f8772009-03-31 15:04:46 -0700914 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
915 + " mUnpluggedCount=" + mUnpluggedCount
916 + " mPluggedCount=" + mPluggedCount);
917 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700918
Christopher Tate4cee7252010-03-19 14:50:40 -0700919 void stepAtomic() {
920 mCount.incrementAndGet();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700921 }
922
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700923 /**
924 * Clear state of this counter.
925 */
926 void reset(boolean detachIfReset) {
927 mCount.set(0);
928 mLoadedCount = mLastCount = mPluggedCount = mUnpluggedCount = 0;
929 if (detachIfReset) {
930 detach();
931 }
932 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700933
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700934 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800935 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700936 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700937
Dianne Hackborn617f8772009-03-31 15:04:46 -0700938 void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700939 int count = mCount.get();
940 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700941 }
942
943 void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700944 mLoadedCount = in.readInt();
945 mCount.set(mLoadedCount);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700946 mLastCount = 0;
Christopher Tate4cee7252010-03-19 14:50:40 -0700947 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700948 }
949 }
Amith Yamasanie43530a2009-08-21 13:11:37 -0700950
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700951 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800952 final TimeBase mTimeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700953 long mCount;
954 long mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700955 long mUnpluggedCount;
956 long mPluggedCount;
957
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800958 LongSamplingCounter(TimeBase timeBase, Parcel in) {
959 mTimeBase = timeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700960 mPluggedCount = in.readLong();
961 mCount = mPluggedCount;
962 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700963 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800964 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700965 }
966
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800967 LongSamplingCounter(TimeBase timeBase) {
968 mTimeBase = timeBase;
969 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700970 }
971
972 public void writeToParcel(Parcel out) {
973 out.writeLong(mCount);
974 out.writeLong(mLoadedCount);
975 out.writeLong(mUnpluggedCount);
976 }
977
978 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800979 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700980 mUnpluggedCount = mPluggedCount;
981 mCount = mPluggedCount;
982 }
983
984 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800985 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700986 mPluggedCount = mCount;
987 }
988
989 public long getCountLocked(int which) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700990 long val = mTimeBase.isRunning() ? mCount : mPluggedCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -0700991 if (which == STATS_SINCE_UNPLUGGED) {
992 val -= mUnpluggedCount;
993 } else if (which != STATS_SINCE_CHARGED) {
994 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700995 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700996 return val;
997 }
998
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700999 @Override
1000 public void logState(Printer pw, String prefix) {
1001 pw.println(prefix + "mCount=" + mCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001002 + " mLoadedCount=" + mLoadedCount
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001003 + " mUnpluggedCount=" + mUnpluggedCount
1004 + " mPluggedCount=" + mPluggedCount);
1005 }
1006
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001007 void addCountLocked(long count) {
1008 mCount += count;
1009 }
1010
1011 /**
1012 * Clear state of this counter.
1013 */
1014 void reset(boolean detachIfReset) {
1015 mCount = 0;
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001016 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001017 if (detachIfReset) {
1018 detach();
1019 }
1020 }
1021
1022 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001023 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001024 }
1025
1026 void writeSummaryFromParcelLocked(Parcel out) {
1027 out.writeLong(mCount);
1028 }
1029
1030 void readSummaryFromParcelLocked(Parcel in) {
1031 mLoadedCount = in.readLong();
1032 mCount = mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001033 mUnpluggedCount = mPluggedCount = mLoadedCount;
1034 }
1035 }
1036
Dianne Hackborn617f8772009-03-31 15:04:46 -07001037 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 * State for keeping track of timing information.
1039 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001040 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001041 protected final Clocks mClocks;
1042 protected final int mType;
1043 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001044
Joe Onoratoabded112016-02-08 16:49:39 -08001045 protected int mCount;
1046 protected int mLoadedCount;
1047 protected int mLastCount;
1048 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 // Times are in microseconds for better accuracy when dividing by the
1051 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 /**
1054 * The total time we have accumulated since the start of the original
1055 * boot, to the last time something interesting happened in the
1056 * current run.
1057 */
Joe Onoratoabded112016-02-08 16:49:39 -08001058 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 /**
1061 * The total time we loaded for the previous runs. Subtract this from
1062 * mTotalTime to find the time for the current run of the system.
1063 */
Joe Onoratoabded112016-02-08 16:49:39 -08001064 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 /**
1067 * The run time of the last run of the system, as loaded from the
1068 * saved data.
1069 */
Joe Onoratoabded112016-02-08 16:49:39 -08001070 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 /**
1073 * The value of mTotalTime when unplug() was last called. Subtract
1074 * this from mTotalTime to find the time since the last unplug from
1075 * power.
1076 */
Joe Onoratoabded112016-02-08 16:49:39 -08001077 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001078
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001079 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001080 * The total time this timer has been running until the latest mark has been set.
1081 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1082 */
Joe Onoratoabded112016-02-08 16:49:39 -08001083 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001084
1085 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001086 * Constructs from a parcel.
1087 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001088 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001089 * @param in
1090 */
Joe Onoratoabded112016-02-08 16:49:39 -08001091 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1092 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001094 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 mCount = in.readInt();
1097 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001098 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 mUnpluggedCount = in.readInt();
1100 mTotalTime = in.readLong();
1101 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001102 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001104 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001105 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001106 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
1108
Joe Onoratoabded112016-02-08 16:49:39 -08001109 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1110 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001112 mTimeBase = timeBase;
1113 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 }
Evan Millarc64edde2009-04-18 12:26:32 -07001115
1116 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001117
Evan Millarc64edde2009-04-18 12:26:32 -07001118 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001119
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001120 /**
1121 * Clear state of this timer. Returns true if the timer is inactive
1122 * so can be completely dropped.
1123 */
Joe Onoratoabded112016-02-08 16:49:39 -08001124 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001125 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001126 mCount = mLoadedCount = mLastCount = 0;
1127 if (detachIfReset) {
1128 detach();
1129 }
1130 return true;
1131 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001132
Joe Onoratoabded112016-02-08 16:49:39 -08001133 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001134 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001135 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001136
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001137 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001138 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1139 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001140 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001143 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001146 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
1148
Adam Lesinskie08af192015-03-25 16:42:59 -07001149 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001150 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001152 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 + " old mUnpluggedTime=" + mUnpluggedTime
1154 + " old mUnpluggedCount=" + mUnpluggedCount);
1155 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001156 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001157 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 if (DEBUG && mType < 0) {
1159 Log.v(TAG, "unplug #" + mType
1160 + ": new mUnpluggedTime=" + mUnpluggedTime
1161 + " new mUnpluggedCount=" + mUnpluggedCount);
1162 }
1163 }
1164
Adam Lesinskie08af192015-03-25 16:42:59 -07001165 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001166 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001167 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001168 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001169 + " old mTotalTime=" + mTotalTime);
1170 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001171 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001172 mCount = computeCurrentCountLocked();
1173 if (DEBUG && mType < 0) {
1174 Log.v(TAG, "plug #" + mType
1175 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 }
1177 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 /**
1180 * Writes a possibly null Timer to a Parcel.
1181 *
1182 * @param out the Parcel to be written to.
1183 * @param timer a Timer, or null.
1184 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001185 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 if (timer == null) {
1187 out.writeInt(0); // indicates null
1188 return;
1189 }
1190 out.writeInt(1); // indicates non-null
1191
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001192 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 }
1194
1195 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001196 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001197 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1198 if (which == STATS_SINCE_UNPLUGGED) {
1199 val -= mUnpluggedTime;
1200 } else if (which != STATS_SINCE_CHARGED) {
1201 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 }
1203
1204 return val;
1205 }
1206
1207 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001208 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001209 int val = computeCurrentCountLocked();
1210 if (which == STATS_SINCE_UNPLUGGED) {
1211 val -= mUnpluggedCount;
1212 } else if (which != STATS_SINCE_CHARGED) {
1213 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 }
1215
1216 return val;
1217 }
1218
Adam Lesinskie08af192015-03-25 16:42:59 -07001219 @Override
1220 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1221 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1222 return val - mTimeBeforeMark;
1223 }
1224
1225 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001226 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001227 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1229 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001230 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001232 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001234 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001235
1236
Joe Onoratoabded112016-02-08 16:49:39 -08001237 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001238 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1239 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001240 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001241 }
1242
Joe Onoratoabded112016-02-08 16:49:39 -08001243 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001244 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001245 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001246 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001247 mUnpluggedTime = mTotalTime;
1248 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001249 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001250 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001251
1252 // When reading the summary, we set the mark to be the latest information.
1253 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001254 }
1255 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001256
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001257 /**
1258 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1259 * method. The state of the timer according to its {@link TimeBase} will determine how much
1260 * of the value is recorded.
1261 *
1262 * If the value being recorded resets, {@link #endSample()} can be called in order to
1263 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1264 * between calls, the {@link #endSample()} is automatically called and the new value is
1265 * expected to increase monotonically from that point on.
1266 */
Joe Onoratoabded112016-02-08 16:49:39 -08001267 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001268
Evan Millarc64edde2009-04-18 12:26:32 -07001269 /**
1270 * The most recent reported count from /proc/wakelocks.
1271 */
1272 int mCurrentReportedCount;
1273
1274 /**
1275 * The reported count from /proc/wakelocks when unplug() was last
1276 * called.
1277 */
1278 int mUnpluggedReportedCount;
1279
1280 /**
1281 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001282 */
Evan Millarc64edde2009-04-18 12:26:32 -07001283 long mCurrentReportedTotalTime;
1284
1285
1286 /**
1287 * The reported total_time from /proc/wakelocks when unplug() was last
1288 * called.
1289 */
1290 long mUnpluggedReportedTotalTime;
1291
1292 /**
1293 * Whether we are currently in a discharge cycle.
1294 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001295 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001296
1297 /**
1298 * Whether we are currently recording reported values.
1299 */
1300 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001301
Evan Millarc64edde2009-04-18 12:26:32 -07001302 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001303 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001304 */
1305 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001306
Adam Lesinski98f0d462016-04-19 16:46:20 -07001307 @VisibleForTesting
1308 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001309 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001310 mCurrentReportedCount = in.readInt();
1311 mUnpluggedReportedCount = in.readInt();
1312 mCurrentReportedTotalTime = in.readLong();
1313 mUnpluggedReportedTotalTime = in.readLong();
1314 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001315 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001316 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001317
Adam Lesinski98f0d462016-04-19 16:46:20 -07001318 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001319 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001320 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001321 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001322 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001323 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001324
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001325 /**
1326 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1327 * be less than the values used for a previous invocation.
1328 */
1329 public void endSample() {
1330 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1331 mCount = computeCurrentCountLocked();
1332 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1333 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001334 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001335
Evan Millarc64edde2009-04-18 12:26:32 -07001336 public void setUpdateVersion(int version) {
1337 mUpdateVersion = version;
1338 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001339
Evan Millarc64edde2009-04-18 12:26:32 -07001340 public int getUpdateVersion() {
1341 return mUpdateVersion;
1342 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001343
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001344 /**
1345 * Updates the current recorded values. These are meant to be monotonically increasing
1346 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1347 *
1348 * If the values being recorded have been reset, the monotonically increasing requirement
1349 * will be broken. In this case, {@link #endSample()} is automatically called and
1350 * the total value of totalTime and count are recorded, starting a new monotonically
1351 * increasing sample.
1352 *
1353 * @param totalTime total time of sample in microseconds.
1354 * @param count total number of times the event being sampled occurred.
1355 */
1356 public void update(long totalTime, int count) {
1357 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001358 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001359 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001360 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001361 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001362
1363 mTrackingReportedValues = true;
1364
1365 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1366 endSample();
1367 }
1368
1369 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001370 mCurrentReportedCount = count;
1371 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001372
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001373 /**
1374 * Adds deltaTime and deltaCount to the current sample.
1375 *
1376 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1377 * @param deltaCount additional number of times the event being sampled occurred.
1378 */
1379 public void add(long deltaTime, int deltaCount) {
1380 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001381 }
1382
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001383 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001384 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1385 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001386 if (mTrackingReportedValues) {
1387 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1388 mUnpluggedReportedCount = mCurrentReportedCount;
1389 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001390 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001391 }
1392
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001393 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001394 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1395 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1396 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001397 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001398
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001399 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001400 public void logState(Printer pw, String prefix) {
1401 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001402 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001403 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1404 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1405 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1406 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001407
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001408 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001409 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001410 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001411 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1412 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001413
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001414 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001415 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001416 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001417 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1418 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001419
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001420 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001421 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1422 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001423 out.writeInt(mCurrentReportedCount);
1424 out.writeInt(mUnpluggedReportedCount);
1425 out.writeLong(mCurrentReportedTotalTime);
1426 out.writeLong(mUnpluggedReportedTotalTime);
1427 out.writeInt(mTrackingReportedValues ? 1 : 0);
1428 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001429
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001430 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001431 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001432 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001433 mTrackingReportedValues = false;
1434 mUnpluggedReportedTotalTime = 0;
1435 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001436 return true;
1437 }
Evan Millarc64edde2009-04-18 12:26:32 -07001438 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001439
Evan Millarc64edde2009-04-18 12:26:32 -07001440 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001441 * A timer that increments in batches. It does not run for durations, but just jumps
1442 * for a pre-determined amount.
1443 */
Joe Onoratoabded112016-02-08 16:49:39 -08001444 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001445 final Uid mUid;
1446
1447 /**
1448 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1449 */
1450 long mLastAddedTime;
1451
1452 /**
1453 * The last duration that we added to the timer. This is in microseconds.
1454 */
1455 long mLastAddedDuration;
1456
1457 /**
1458 * Whether we are currently in a discharge cycle.
1459 */
1460 boolean mInDischarge;
1461
Joe Onoratoabded112016-02-08 16:49:39 -08001462 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
1463 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001464 mUid = uid;
1465 mLastAddedTime = in.readLong();
1466 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001467 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001468 }
1469
Joe Onoratoabded112016-02-08 16:49:39 -08001470 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
1471 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001472 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001473 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001474 }
1475
1476 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001477 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1478 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001479 out.writeLong(mLastAddedTime);
1480 out.writeLong(mLastAddedDuration);
1481 }
1482
1483 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001484 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001485 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001486 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001487 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001488 }
1489
1490 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001491 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001492 recomputeLastDuration(elapsedRealtime, false);
1493 mInDischarge = true;
1494 // If we are still within the last added duration, then re-added whatever remains.
1495 if (mLastAddedTime == elapsedRealtime) {
1496 mTotalTime += mLastAddedDuration;
1497 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001498 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001499 }
1500
1501 @Override
1502 public void logState(Printer pw, String prefix) {
1503 super.logState(pw, prefix);
1504 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
1505 + " mLastAddedDuration=" + mLastAddedDuration);
1506 }
1507
1508 private long computeOverage(long curTime) {
1509 if (mLastAddedTime > 0) {
1510 return mLastTime + mLastAddedDuration - curTime;
1511 }
1512 return 0;
1513 }
1514
1515 private void recomputeLastDuration(long curTime, boolean abort) {
1516 final long overage = computeOverage(curTime);
1517 if (overage > 0) {
1518 // Aborting before the duration ran out -- roll back the remaining
1519 // duration. Only do this if currently discharging; otherwise we didn't
1520 // actually add the time.
1521 if (mInDischarge) {
1522 mTotalTime -= overage;
1523 }
1524 if (abort) {
1525 mLastAddedTime = 0;
1526 } else {
1527 mLastAddedTime = curTime;
1528 mLastAddedDuration -= overage;
1529 }
1530 }
1531 }
1532
1533 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08001534 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001535 recomputeLastDuration(now, true);
1536 mLastAddedTime = now;
1537 mLastAddedDuration = durationMillis * 1000;
1538 if (mInDischarge) {
1539 mTotalTime += mLastAddedDuration;
1540 mCount++;
1541 }
1542 }
1543
1544 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08001545 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001546 recomputeLastDuration(now, true);
1547 }
1548
1549 @Override
1550 protected int computeCurrentCountLocked() {
1551 return mCount;
1552 }
1553
1554 @Override
1555 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001556 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001557 if (overage > 0) {
1558 return mTotalTime = overage;
1559 }
1560 return mTotalTime;
1561 }
1562
1563 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001564 public boolean reset(boolean detachIfReset) {
1565 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001566 recomputeLastDuration(now, true);
1567 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001568 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001569 return !stillActive;
1570 }
1571 }
1572
Joe Onorato92fd23f2016-07-25 11:18:42 -07001573
1574 /**
1575 * A StopwatchTimer that also tracks the total and max individual
1576 * time spent active according to the given timebase. Whereas
1577 * StopwatchTimer apportions the time amongst all in the pool,
1578 * the total and max durations are not apportioned.
1579 */
1580 public static class DurationTimer extends StopwatchTimer {
1581 /**
1582 * The time (in ms) that the timer was last acquired or the time base
1583 * last (re-)started. Increasing the nesting depth does not reset this time.
1584 *
1585 * -1 if the timer is currently not running or the time base is not running.
1586 *
1587 * If written to a parcel, the start time is reset, as is mNesting in the base class
1588 * StopwatchTimer.
1589 */
1590 long mStartTimeMs = -1;
1591
1592 /**
Bookatz867c0d72017-03-07 18:23:42 -08001593 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001594 */
1595 long mMaxDurationMs;
1596
1597 /**
Bookatz867c0d72017-03-07 18:23:42 -08001598 * The time (in ms) that that the timer has been active since most recent
1599 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001600 */
1601 long mCurrentDurationMs;
1602
Bookatz867c0d72017-03-07 18:23:42 -08001603 /**
1604 * The total time (in ms) that that the timer has been active since most recent reset()
1605 * prior to the current startRunningLocked. This is the sum of all past currentDurations
1606 * (but not including the present currentDuration) since reset. Not pooled.
1607 */
1608 long mTotalDurationMs;
1609
Joe Onorato92fd23f2016-07-25 11:18:42 -07001610 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
1611 TimeBase timeBase, Parcel in) {
1612 super(clocks, uid, type, timerPool, timeBase, in);
1613 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08001614 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07001615 }
1616
1617 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
1618 TimeBase timeBase) {
1619 super(clocks, uid, type, timerPool, timeBase);
1620 }
1621
1622 @Override
1623 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1624 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08001625 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08001626 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07001627 }
1628
1629 /**
1630 * Write the summary to the parcel.
1631 *
1632 * Since the time base is probably meaningless after we come back, reading
1633 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08001634 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001635 */
1636 @Override
1637 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
1638 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08001639 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08001640 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07001641 }
1642
1643 /**
1644 * Read the summary parcel.
1645 *
1646 * Has the side effect of stopping the timer.
1647 */
1648 @Override
1649 public void readSummaryFromParcelLocked(Parcel in) {
1650 super.readSummaryFromParcelLocked(in);
1651 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08001652 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07001653 mStartTimeMs = -1;
1654 mCurrentDurationMs = 0;
1655 }
1656
1657 /**
1658 * The TimeBase time started (again).
1659 *
1660 * If the timer is also running, store the start time.
1661 */
1662 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
1663 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
1664 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001665 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001666 }
1667 }
1668
1669 /**
1670 * The TimeBase stopped running.
1671 *
1672 * If the timer is running, add the duration into mCurrentDurationMs.
1673 */
1674 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08001675 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
1676 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07001677 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001678 // baseRealtimeUs has already been converted to the timebase's realtime.
1679 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001680 }
1681 mStartTimeMs = -1;
1682 }
1683
1684 @Override
1685 public void logState(Printer pw, String prefix) {
1686 super.logState(pw, prefix);
1687 }
1688
1689 @Override
1690 public void startRunningLocked(long elapsedRealtimeMs) {
1691 super.startRunningLocked(elapsedRealtimeMs);
1692 if (mNesting == 1 && mTimeBase.isRunning()) {
1693 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08001694 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001695 }
1696 }
1697
1698 /**
1699 * Decrements the mNesting ref-count on this timer.
1700 *
1701 * If it actually stopped (mNesting went to 0), then possibly update
1702 * mMaxDuration if the current duration was the longest ever.
1703 */
1704 @Override
1705 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001706 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07001707 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08001708 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001709 if (durationMs > mMaxDurationMs) {
1710 mMaxDurationMs = durationMs;
1711 }
1712 mStartTimeMs = -1;
1713 mCurrentDurationMs = 0;
1714 }
Kweku Adams47db5a82016-12-09 19:04:50 -08001715 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
1716 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
1717 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07001718 }
1719
1720 @Override
1721 public boolean reset(boolean detachIfReset) {
1722 boolean result = super.reset(detachIfReset);
1723 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08001724 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001725 mCurrentDurationMs = 0;
1726 if (mNesting > 0) {
1727 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
1728 } else {
1729 mStartTimeMs = -1;
1730 }
1731 return result;
1732 }
1733
1734 /**
1735 * Returns the max duration that this timer has ever seen.
1736 *
1737 * Note that this time is NOT split between the timers in the timer group that
1738 * this timer is attached to. It is the TOTAL time.
1739 */
1740 @Override
1741 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
1742 if (mNesting > 0) {
1743 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
1744 if (durationMs > mMaxDurationMs) {
1745 return durationMs;
1746 }
1747 }
1748 return mMaxDurationMs;
1749 }
1750
1751 /**
1752 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08001753 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001754 *
1755 * Note that this time is NOT split between the timers in the timer group that
1756 * this timer is attached to. It is the TOTAL time.
1757 */
1758 @Override
1759 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
1760 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08001761 if (mNesting > 0 && mTimeBase.isRunning()) {
1762 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
1763 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001764 }
1765 return durationMs;
1766 }
Bookatz867c0d72017-03-07 18:23:42 -08001767
1768 /**
1769 * Returns the total cumulative duration that this timer has been on since reset().
1770 * If mTimerPool == null, this should be the same
1771 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
1772 *
1773 * Note that this time is NOT split between the timers in the timer group that
1774 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
1775 * the result will not be equivalent to getTotalTimeLocked.
1776 */
1777 @Override
1778 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
1779 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
1780 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07001781 }
1782
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001783 /**
Evan Millarc64edde2009-04-18 12:26:32 -07001784 * State for keeping track of timing information.
1785 */
Joe Onoratoabded112016-02-08 16:49:39 -08001786 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001787 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07001788 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001789
Evan Millarc64edde2009-04-18 12:26:32 -07001790 int mNesting;
1791
Evan Millarc64edde2009-04-18 12:26:32 -07001792 /**
1793 * The last time at which we updated the timer. If mNesting is > 0,
1794 * subtract this from the current battery time to find the amount of
1795 * time we have been running since we last computed an update.
1796 */
1797 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001798
Evan Millarc64edde2009-04-18 12:26:32 -07001799 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001800 * The total time at which the timer was acquired, to determine if it
Evan Millarc64edde2009-04-18 12:26:32 -07001801 * was actually held for an interesting duration.
1802 */
1803 long mAcquireTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001804
Amith Yamasanif37447b2009-10-08 18:28:01 -07001805 long mTimeout;
1806
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001807 /**
1808 * For partial wake locks, keep track of whether we are in the list
1809 * to consume CPU cycles.
1810 */
1811 boolean mInList;
1812
Joe Onoratoabded112016-02-08 16:49:39 -08001813 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001814 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001815 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001816 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07001817 mTimerPool = timerPool;
1818 mUpdateTime = in.readLong();
1819 }
1820
Joe Onoratoabded112016-02-08 16:49:39 -08001821 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001822 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001823 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001824 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07001825 mTimerPool = timerPool;
1826 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001827
Joe Onoratoabded112016-02-08 16:49:39 -08001828 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07001829 mTimeout = timeout;
1830 }
1831
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001832 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1833 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001834 out.writeLong(mUpdateTime);
1835 }
1836
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001837 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001838 if (mNesting > 0) {
1839 if (DEBUG && mType < 0) {
1840 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
1841 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001842 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1843 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07001844 if (DEBUG && mType < 0) {
1845 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
1846 }
1847 }
1848 }
1849
1850 public void logState(Printer pw, String prefix) {
1851 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001852 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 + " mAcquireTime=" + mAcquireTime);
1854 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001855
Joe Onoratoabded112016-02-08 16:49:39 -08001856 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001858 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08001859 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 if (mTimerPool != null) {
1861 // Accumulate time to all currently active timers before adding
1862 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001863 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 // Add this timer to the active pool
1865 mTimerPool.add(this);
1866 }
1867 // Increment the count
1868 mCount++;
1869 mAcquireTime = mTotalTime;
1870 if (DEBUG && mType < 0) {
1871 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
1872 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
1873 + " mAcquireTime=" + mAcquireTime);
1874 }
1875 }
1876 }
1877
Joe Onoratoabded112016-02-08 16:49:39 -08001878 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001879 return mNesting > 0;
1880 }
1881
Joe Onoratoabded112016-02-08 16:49:39 -08001882 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 // Ignore attempt to stop a timer that isn't running
1884 if (mNesting == 0) {
1885 return;
1886 }
1887 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001888 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 if (mTimerPool != null) {
1890 // Accumulate time to all active counters, scaled by the total
1891 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001892 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 // Remove this timer from the active pool
1894 mTimerPool.remove(this);
1895 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 mNesting = 1;
1897 mTotalTime = computeRunTimeLocked(batteryRealtime);
1898 mNesting = 0;
1899 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 if (DEBUG && mType < 0) {
1902 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
1903 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
1904 + " mAcquireTime=" + mAcquireTime);
1905 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 if (mTotalTime == mAcquireTime) {
1908 // If there was no change in the time, then discard this
1909 // count. A somewhat cheezy strategy, but hey.
1910 mCount--;
1911 }
1912 }
1913 }
1914
Joe Onoratoabded112016-02-08 16:49:39 -08001915 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07001916 if (mNesting > 0) {
1917 mNesting = 1;
1918 stopRunningLocked(elapsedRealtimeMs);
1919 }
1920 }
1921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 // Update the total time for all other running Timers with the same type as this Timer
1923 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001924 private static long refreshTimersLocked(long batteryRealtime,
1925 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08001926 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 final int N = pool.size();
1928 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07001929 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 long heldTime = batteryRealtime - t.mUpdateTime;
1931 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08001932 final long myTime = heldTime / N;
1933 if (t == self) {
1934 selfTime = myTime;
1935 }
1936 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
1938 t.mUpdateTime = batteryRealtime;
1939 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08001940 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 }
1942
Evan Millarc64edde2009-04-18 12:26:32 -07001943 @Override
1944 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07001945 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
1946 curBatteryRealtime = mUpdateTime + mTimeout;
1947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 return mTotalTime + (mNesting > 0
1949 ? (curBatteryRealtime - mUpdateTime)
1950 / (mTimerPool != null ? mTimerPool.size() : 1)
1951 : 0);
1952 }
1953
Evan Millarc64edde2009-04-18 12:26:32 -07001954 @Override
1955 protected int computeCurrentCountLocked() {
1956 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 }
1958
Adam Lesinskie08af192015-03-25 16:42:59 -07001959 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001960 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001961 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001962 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001963 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08001964 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001965 }
1966 mAcquireTime = mTotalTime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001967 return canDetach;
1968 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001969
Adam Lesinskie08af192015-03-25 16:42:59 -07001970 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001971 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001972 super.detach();
1973 if (mTimerPool != null) {
1974 mTimerPool.remove(this);
1975 }
1976 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001977
Adam Lesinskie08af192015-03-25 16:42:59 -07001978 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001979 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001980 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 mNesting = 0;
1982 }
Adam Lesinskie08af192015-03-25 16:42:59 -07001983
1984 /**
1985 * Set the mark so that we can query later for the total time the timer has
1986 * accumulated since this point. The timer can be running or not.
1987 *
1988 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
1989 */
1990 public void setMark(long elapsedRealtimeMs) {
1991 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
1992 if (mNesting > 0) {
1993 // We are running.
1994 if (mTimerPool != null) {
1995 refreshTimersLocked(batteryRealtime, mTimerPool, this);
1996 } else {
1997 mTotalTime += batteryRealtime - mUpdateTime;
1998 mUpdateTime = batteryRealtime;
1999 }
2000 }
2001 mTimeBeforeMark = mTotalTime;
2002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002004
Bookatz867c0d72017-03-07 18:23:42 -08002005 /**
2006 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2007 * TimeBase is effectively a subset of the other.
2008 */
2009 public static class DualTimer {
2010 // mMainTimer typically tracks the total time. May be pooled (but since it's a durationTimer,
2011 // it also has the unpooled getTotalDurationMsLocked() for STATS_SINCE_CHARGED).
2012 private final DurationTimer mMainTimer;
2013 // mSubTimer typically tracks only part of the total time, such as background time, as
2014 // determined by a subTimeBase. It is NOT pooled.
2015 private final DurationTimer mSubTimer;
2016
2017 /**
2018 * Creates a DualTimer to hold a mMainTimer and a mSubTimer.
2019 * The mMainTimer is based on the given timeBase and timerPool.
2020 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
2021 * the mMainTimer is.
2022 */
2023 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2024 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
2025 mMainTimer = new DurationTimer(clocks, uid, type, timerPool, timeBase, in);
2026 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2027 }
2028
2029 /**
2030 * Creates a DualTimer to hold a mMainTimer and a mSubTimer.
2031 * The mMainTimer is based on the given timeBase and timerPool.
2032 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
2033 * the mMainTimer is.
2034 */
2035 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2036 TimeBase timeBase, TimeBase subTimeBase) {
2037 mMainTimer = new DurationTimer(clocks, uid, type, timerPool, timeBase);
2038 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2039 }
2040
2041 /** Get the main timer. */
2042 public DurationTimer getMainTimer() {
2043 return mMainTimer;
2044 }
2045
2046 /** Get the secondary timer. */
2047 public DurationTimer getSubTimer() {
2048 return mSubTimer;
2049 }
2050
2051 public void startRunningLocked(long elapsedRealtimeMs) {
2052 mMainTimer.startRunningLocked(elapsedRealtimeMs);
2053 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2054 }
2055
2056 public void stopRunningLocked(long elapsedRealtimeMs) {
2057 mMainTimer.stopRunningLocked(elapsedRealtimeMs);
2058 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2059 }
2060
2061 public void stopAllRunningLocked(long elapsedRealtimeMs) {
2062 mMainTimer.stopAllRunningLocked(elapsedRealtimeMs);
2063 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2064 }
2065
2066 public void setMark(long elapsedRealtimeMs) {
2067 mMainTimer.setMark(elapsedRealtimeMs);
2068 mSubTimer.setMark(elapsedRealtimeMs);
2069 }
2070
2071 public boolean reset(boolean detachIfReset) {
2072 boolean active = false;
2073 active |= !mMainTimer.reset(detachIfReset);
2074 active |= !mSubTimer.reset(detachIfReset);
2075 return !active;
2076 }
2077
2078 public void detach() {
2079 mMainTimer.detach();
2080 mSubTimer.detach();
2081 }
2082
2083 /**
2084 * Writes a possibly null DualTimer to a Parcel.
2085 *
2086 * @param out the Parcel to which to write.
2087 * @param t a DualTimer, or null.
2088 */
2089 public static void writeDualTimerToParcel(Parcel out, DualTimer t, long elapsedRealtimeUs) {
2090 if (t != null) {
2091 out.writeInt(1);
2092 t.writeToParcel(out, elapsedRealtimeUs);
2093 } else {
2094 out.writeInt(0);
2095 }
2096 }
2097
2098 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2099 mMainTimer.writeToParcel(out, elapsedRealtimeUs);
2100 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2101 }
2102
2103 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2104 mMainTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2105 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2106 }
2107
2108 public void readSummaryFromParcelLocked(Parcel in) {
2109 mMainTimer.readSummaryFromParcelLocked(in);
2110 mSubTimer.readSummaryFromParcelLocked(in);
2111 }
2112 }
2113
2114
Dianne Hackbornd953c532014-08-16 18:17:38 -07002115 public abstract class OverflowArrayMap<T> {
2116 private static final String OVERFLOW_NAME = "*overflow*";
2117
Dianne Hackborn657153b2016-07-29 14:54:14 -07002118 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002119 final ArrayMap<String, T> mMap = new ArrayMap<>();
2120 T mCurOverflow;
2121 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002122 long mLastOverflowTime;
2123 long mLastOverflowFinishTime;
2124 long mLastClearTime;
2125 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002126
Dianne Hackborn657153b2016-07-29 14:54:14 -07002127 public OverflowArrayMap(int uid) {
2128 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002129 }
2130
2131 public ArrayMap<String, T> getMap() {
2132 return mMap;
2133 }
2134
2135 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002136 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002137 mMap.clear();
2138 mCurOverflow = null;
2139 mActiveOverflow = null;
2140 }
2141
2142 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002143 if (name == null) {
2144 name = "";
2145 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002146 mMap.put(name, obj);
2147 if (OVERFLOW_NAME.equals(name)) {
2148 mCurOverflow = obj;
2149 }
2150 }
2151
2152 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002153 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002154 if (mActiveOverflow != null) {
2155 if (mActiveOverflow.size() == 0) {
2156 mActiveOverflow = null;
2157 }
2158 }
2159 if (mActiveOverflow == null) {
2160 // There is no currently active overflow, so we should no longer have
2161 // an overflow entry.
2162 if (mMap.containsKey(OVERFLOW_NAME)) {
2163 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2164 + mMap.get(OVERFLOW_NAME));
2165 mMap.remove(OVERFLOW_NAME);
2166 }
2167 mCurOverflow = null;
2168 } else {
2169 // There is currently active overflow, so we should still have an overflow entry.
2170 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2171 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2172 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2173 }
2174 }
2175 }
2176
2177 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002178 if (name == null) {
2179 name = "";
2180 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002181 T obj = mMap.get(name);
2182 if (obj != null) {
2183 return obj;
2184 }
2185
2186 // No object exists for the given name, but do we currently have it
2187 // running as part of the overflow?
2188 if (mActiveOverflow != null) {
2189 MutableInt over = mActiveOverflow.get(name);
2190 if (over != null) {
2191 // We are already actively counting this name in the overflow object.
2192 obj = mCurOverflow;
2193 if (obj == null) {
2194 // Shouldn't be here, but we'll try to recover.
2195 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2196 obj = mCurOverflow = instantiateObject();
2197 mMap.put(OVERFLOW_NAME, obj);
2198 }
2199 over.value++;
2200 return obj;
2201 }
2202 }
2203
2204 // No object exists for given name nor in the overflow; we need to make
2205 // a new one.
2206 final int N = mMap.size();
2207 if (N >= MAX_WAKELOCKS_PER_UID) {
2208 // Went over the limit on number of objects to track; this one goes
2209 // in to the overflow.
2210 obj = mCurOverflow;
2211 if (obj == null) {
2212 // Need to start overflow now...
2213 obj = mCurOverflow = instantiateObject();
2214 mMap.put(OVERFLOW_NAME, obj);
2215 }
2216 if (mActiveOverflow == null) {
2217 mActiveOverflow = new ArrayMap<>();
2218 }
2219 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002220 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002221 return obj;
2222 }
2223
2224 // Normal case where we just need to make a new object.
2225 obj = instantiateObject();
2226 mMap.put(name, obj);
2227 return obj;
2228 }
2229
2230 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002231 if (name == null) {
2232 name = "";
2233 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002234 T obj = mMap.get(name);
2235 if (obj != null) {
2236 return obj;
2237 }
2238
2239 // No object exists for the given name, but do we currently have it
2240 // running as part of the overflow?
2241 if (mActiveOverflow != null) {
2242 MutableInt over = mActiveOverflow.get(name);
2243 if (over != null) {
2244 // We are already actively counting this name in the overflow object.
2245 obj = mCurOverflow;
2246 if (obj != null) {
2247 over.value--;
2248 if (over.value <= 0) {
2249 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002250 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002251 }
2252 return obj;
2253 }
2254 }
2255 }
2256
2257 // Huh, they are stopping an active operation but we can't find one!
2258 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002259 StringBuilder sb = new StringBuilder();
2260 sb.append("Unable to find object for ");
2261 sb.append(name);
2262 sb.append(" in uid ");
2263 sb.append(mUid);
2264 sb.append(" mapsize=");
2265 sb.append(mMap.size());
2266 sb.append(" activeoverflow=");
2267 sb.append(mActiveOverflow);
2268 sb.append(" curoverflow=");
2269 sb.append(mCurOverflow);
2270 long now = SystemClock.elapsedRealtime();
2271 if (mLastOverflowTime != 0) {
2272 sb.append(" lastOverflowTime=");
2273 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2274 }
2275 if (mLastOverflowFinishTime != 0) {
2276 sb.append(" lastOverflowFinishTime=");
2277 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2278 }
2279 if (mLastClearTime != 0) {
2280 sb.append(" lastClearTime=");
2281 TimeUtils.formatDuration(mLastClearTime-now, sb);
2282 }
2283 if (mLastCleanupTime != 0) {
2284 sb.append(" lastCleanupTime=");
2285 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2286 }
2287 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002288 return null;
2289 }
2290
2291 public abstract T instantiateObject();
2292 }
2293
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002294 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2295 implements Parcelable {
2296 private final LongSamplingCounter mIdleTimeMillis;
2297 private final LongSamplingCounter mRxTimeMillis;
2298 private final LongSamplingCounter[] mTxTimeMillis;
2299 private final LongSamplingCounter mPowerDrainMaMs;
2300
2301 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2302 mIdleTimeMillis = new LongSamplingCounter(timeBase);
2303 mRxTimeMillis = new LongSamplingCounter(timeBase);
2304 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2305 for (int i = 0; i < numTxStates; i++) {
2306 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2307 }
2308 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2309 }
2310
2311 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2312 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
2313 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2314 final int recordedTxStates = in.readInt();
2315 if (recordedTxStates != numTxStates) {
2316 throw new ParcelFormatException("inconsistent tx state lengths");
2317 }
2318
2319 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2320 for (int i = 0; i < numTxStates; i++) {
2321 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2322 }
2323 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2324 }
2325
2326 public void readSummaryFromParcel(Parcel in) {
2327 mIdleTimeMillis.readSummaryFromParcelLocked(in);
2328 mRxTimeMillis.readSummaryFromParcelLocked(in);
2329 final int recordedTxStates = in.readInt();
2330 if (recordedTxStates != mTxTimeMillis.length) {
2331 throw new ParcelFormatException("inconsistent tx state lengths");
2332 }
2333 for (LongSamplingCounter counter : mTxTimeMillis) {
2334 counter.readSummaryFromParcelLocked(in);
2335 }
2336 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2337 }
2338
2339 @Override
2340 public int describeContents() {
2341 return 0;
2342 }
2343
2344 public void writeSummaryToParcel(Parcel dest) {
2345 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
2346 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2347 dest.writeInt(mTxTimeMillis.length);
2348 for (LongSamplingCounter counter : mTxTimeMillis) {
2349 counter.writeSummaryFromParcelLocked(dest);
2350 }
2351 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2352 }
2353
2354 @Override
2355 public void writeToParcel(Parcel dest, int flags) {
2356 mIdleTimeMillis.writeToParcel(dest);
2357 mRxTimeMillis.writeToParcel(dest);
2358 dest.writeInt(mTxTimeMillis.length);
2359 for (LongSamplingCounter counter : mTxTimeMillis) {
2360 counter.writeToParcel(dest);
2361 }
2362 mPowerDrainMaMs.writeToParcel(dest);
2363 }
2364
2365 public void reset(boolean detachIfReset) {
2366 mIdleTimeMillis.reset(detachIfReset);
2367 mRxTimeMillis.reset(detachIfReset);
2368 for (LongSamplingCounter counter : mTxTimeMillis) {
2369 counter.reset(detachIfReset);
2370 }
2371 mPowerDrainMaMs.reset(detachIfReset);
2372 }
2373
2374 public void detach() {
2375 mIdleTimeMillis.detach();
2376 mRxTimeMillis.detach();
2377 for (LongSamplingCounter counter : mTxTimeMillis) {
2378 counter.detach();
2379 }
2380 mPowerDrainMaMs.detach();
2381 }
2382
2383 /**
2384 * @return a LongSamplingCounter, measuring time spent in the idle state in
2385 * milliseconds.
2386 */
2387 @Override
2388 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002389 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002390 }
2391
2392 /**
2393 * @return a LongSamplingCounter, measuring time spent in the receive state in
2394 * milliseconds.
2395 */
2396 @Override
2397 public LongSamplingCounter getRxTimeCounter() {
2398 return mRxTimeMillis;
2399 }
2400
2401 /**
2402 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2403 * milliseconds.
2404 */
2405 @Override
2406 public LongSamplingCounter[] getTxTimeCounters() {
2407 return mTxTimeMillis;
2408 }
2409
2410 /**
2411 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2412 */
2413 @Override
2414 public LongSamplingCounter getPowerCounter() {
2415 return mPowerDrainMaMs;
2416 }
2417 }
2418
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002419 /*
2420 * Get the wakeup reason counter, and create a new one if one
2421 * doesn't already exist.
2422 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002423 public SamplingTimer getWakeupReasonTimerLocked(String name) {
2424 SamplingTimer timer = mWakeupReasonStats.get(name);
2425 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002426 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002427 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002428 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002429 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002430 }
2431
Evan Millarc64edde2009-04-18 12:26:32 -07002432 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002433 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07002434 * doesn't already exist.
2435 */
2436 public SamplingTimer getKernelWakelockTimerLocked(String name) {
2437 SamplingTimer kwlt = mKernelWakelockStats.get(name);
2438 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002439 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07002440 mKernelWakelockStats.put(name, kwlt);
2441 }
2442 return kwlt;
2443 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07002444
James Carr3a226052016-07-01 14:49:52 -07002445 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
2446 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
2447 if (kmt == null) {
2448 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2449 mKernelMemoryStats.put(bucket, kmt);
2450 }
2451 return kmt;
2452 }
2453
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002454 private int writeHistoryTag(HistoryTag tag) {
2455 Integer idxObj = mHistoryTagPool.get(tag);
2456 int idx;
2457 if (idxObj != null) {
2458 idx = idxObj;
2459 } else {
2460 idx = mNextHistoryTagIdx;
2461 HistoryTag key = new HistoryTag();
2462 key.setTo(tag);
2463 tag.poolIdx = idx;
2464 mHistoryTagPool.put(key, idx);
2465 mNextHistoryTagIdx++;
2466 mNumHistoryTagChars += key.string.length() + 1;
2467 }
2468 return idx;
2469 }
2470
2471 private void readHistoryTag(int index, HistoryTag tag) {
2472 tag.string = mReadHistoryStrings[index];
2473 tag.uid = mReadHistoryUids[index];
2474 tag.poolIdx = index;
2475 }
2476
Adam Lesinski926969b2016-04-28 17:31:12 -07002477 /*
2478 The history delta format uses flags to denote further data in subsequent ints in the parcel.
2479
2480 There is always the first token, which may contain the delta time, or an indicator of
2481 the length of the time (int or long) following this token.
2482
2483 First token: always present,
2484 31 23 15 7 0
2485 â–ˆ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â–ˆ
2486
2487 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
2488 follows containing the time, and 0x7ffff indicates a long immediately follows with the
2489 delta time.
2490 A: battery level changed and an int follows with battery data.
2491 B: state changed and an int follows with state change data.
2492 C: state2 has changed and an int follows with state2 change data.
2493 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
2494 E: event data has changed and an event struct follows.
2495 F: battery charge in coulombs has changed and an int with the charge follows.
2496 G: state flag denoting that the mobile radio was active.
2497 H: state flag denoting that the wifi radio was active.
2498 I: state flag denoting that a wifi scan occurred.
2499 J: state flag denoting that a wifi full lock was held.
2500 K: state flag denoting that the gps was on.
2501 L: state flag denoting that a wakelock was held.
2502 M: state flag denoting that the cpu was running.
2503
2504 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
2505 with the time delta.
2506
2507 Battery level int: if A in the first token is set,
2508 31 23 15 7 0
2509 â–ˆ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â–ˆ
2510
2511 D: indicates that extra history details follow.
2512 V: the battery voltage.
2513 T: the battery temperature.
2514 L: the battery level (out of 100).
2515
2516 State change int: if B in the first token is set,
2517 31 23 15 7 0
2518 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
2519
2520 A: wifi multicast was on.
2521 B: battery was plugged in.
2522 C: screen was on.
2523 D: phone was scanning for signal.
2524 E: audio was on.
2525 F: a sensor was active.
2526
2527 State2 change int: if C in the first token is set,
2528 31 23 15 7 0
2529 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
2530
2531 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
2532 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
2533 C: a bluetooth scan was active.
2534 D: the camera was active.
2535 E: bluetooth was on.
2536 F: a phone call was active.
2537 G: the device was charging.
2538 H: 2 bits indicating the device-idle (doze) state: off, light, full
2539 I: the flashlight was on.
2540 J: wifi was on.
2541 K: wifi was running.
2542 L: video was playing.
2543 M: power save mode was on.
2544
2545 Wakelock/wakereason struct: if D in the first token is set,
2546 TODO(adamlesinski): describe wakelock/wakereason struct.
2547
2548 Event struct: if E in the first token is set,
2549 TODO(adamlesinski): describe the event struct.
2550
2551 History step details struct: if D in the battery level int is set,
2552 TODO(adamlesinski): describe the history step details struct.
2553
2554 Battery charge int: if F in the first token is set, an int representing the battery charge
2555 in coulombs follows.
2556 */
2557
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002558 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08002559 static final int DELTA_TIME_MASK = 0x7ffff;
2560 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
2561 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
2562 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002563 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002564 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002565 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002566 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08002567 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002568 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002569 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07002570 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002571 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07002572 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002573 // Flag in delta int: contains the battery charge count in uAh.
2574 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002575 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07002576 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08002577
2578 // These are the pieces of battery state that are packed in to the upper bits of
2579 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07002580 // in STATE_BATTERY_MASK.
2581 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08002582 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
2583 static final int STATE_BATTERY_STATUS_SHIFT = 29;
2584 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
2585 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
2586 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
2587 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002588
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002589 // We use the low bit of the battery state int to indicate that we have full details
2590 // from a battery level change.
2591 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
2592
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002593 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002594 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002595 dest.writeInt(DELTA_TIME_ABS);
2596 cur.writeToParcel(dest, 0);
2597 return;
2598 }
2599
2600 final long deltaTime = cur.time - last.time;
2601 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
2602 final int lastStateInt = buildStateInt(last);
2603
2604 int deltaTimeToken;
2605 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
2606 deltaTimeToken = DELTA_TIME_LONG;
2607 } else if (deltaTime >= DELTA_TIME_ABS) {
2608 deltaTimeToken = DELTA_TIME_INT;
2609 } else {
2610 deltaTimeToken = (int)deltaTime;
2611 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002612 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002613 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
2614 ? BATTERY_DELTA_LEVEL_FLAG : 0;
2615 final boolean computeStepDetails = includeStepDetails != 0
2616 || mLastHistoryStepDetails == null;
2617 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002618 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
2619 if (batteryLevelIntChanged) {
2620 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
2621 }
2622 final int stateInt = buildStateInt(cur);
2623 final boolean stateIntChanged = stateInt != lastStateInt;
2624 if (stateIntChanged) {
2625 firstToken |= DELTA_STATE_FLAG;
2626 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002627 final boolean state2IntChanged = cur.states2 != last.states2;
2628 if (state2IntChanged) {
2629 firstToken |= DELTA_STATE2_FLAG;
2630 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002631 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002632 firstToken |= DELTA_WAKELOCK_FLAG;
2633 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002634 if (cur.eventCode != HistoryItem.EVENT_NONE) {
2635 firstToken |= DELTA_EVENT_FLAG;
2636 }
Adam Lesinski926969b2016-04-28 17:31:12 -07002637
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002638 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
2639 if (batteryChargeChanged) {
2640 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07002641 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002642 dest.writeInt(firstToken);
2643 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
2644 + " deltaTime=" + deltaTime);
2645
2646 if (deltaTimeToken >= DELTA_TIME_INT) {
2647 if (deltaTimeToken == DELTA_TIME_INT) {
2648 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
2649 dest.writeInt((int)deltaTime);
2650 } else {
2651 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
2652 dest.writeLong(deltaTime);
2653 }
2654 }
2655 if (batteryLevelIntChanged) {
2656 dest.writeInt(batteryLevelInt);
2657 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
2658 + Integer.toHexString(batteryLevelInt)
2659 + " batteryLevel=" + cur.batteryLevel
2660 + " batteryTemp=" + cur.batteryTemperature
2661 + " batteryVolt=" + (int)cur.batteryVoltage);
2662 }
2663 if (stateIntChanged) {
2664 dest.writeInt(stateInt);
2665 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
2666 + Integer.toHexString(stateInt)
2667 + " batteryStatus=" + cur.batteryStatus
2668 + " batteryHealth=" + cur.batteryHealth
2669 + " batteryPlugType=" + cur.batteryPlugType
2670 + " states=0x" + Integer.toHexString(cur.states));
2671 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002672 if (state2IntChanged) {
2673 dest.writeInt(cur.states2);
2674 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
2675 + Integer.toHexString(cur.states2));
2676 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002677 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
2678 int wakeLockIndex;
2679 int wakeReasonIndex;
2680 if (cur.wakelockTag != null) {
2681 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
2682 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
2683 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
2684 } else {
2685 wakeLockIndex = 0xffff;
2686 }
2687 if (cur.wakeReasonTag != null) {
2688 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
2689 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
2690 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
2691 } else {
2692 wakeReasonIndex = 0xffff;
2693 }
2694 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002695 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002696 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002697 int index = writeHistoryTag(cur.eventTag);
2698 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08002699 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002700 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
2701 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
2702 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002703 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002704 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07002705 if (mPlatformIdleStateCallback != null) {
2706 mCurHistoryStepDetails.statPlatformIdleState =
2707 mPlatformIdleStateCallback.getPlatformLowPowerStats();
2708 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
2709 mCurHistoryStepDetails.statPlatformIdleState);
2710 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002711 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
2712 if (includeStepDetails != 0) {
2713 mCurHistoryStepDetails.writeToParcel(dest);
2714 }
2715 cur.stepDetails = mCurHistoryStepDetails;
2716 mLastHistoryStepDetails = mCurHistoryStepDetails;
2717 } else {
2718 cur.stepDetails = null;
2719 }
2720 if (mLastHistoryStepLevel < cur.batteryLevel) {
2721 mLastHistoryStepDetails = null;
2722 }
2723 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07002724
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002725 if (batteryChargeChanged) {
2726 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
2727 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07002728 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002729 }
2730
2731 private int buildBatteryLevelInt(HistoryItem h) {
2732 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08002733 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
2734 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
2735 }
2736
2737 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
2738 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
2739 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
2740 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002741 }
2742
2743 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08002744 int plugType = 0;
2745 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
2746 plugType = 1;
2747 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
2748 plugType = 2;
2749 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
2750 plugType = 3;
2751 }
2752 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
2753 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
2754 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07002755 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002756 }
2757
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002758 private void computeHistoryStepDetails(final HistoryStepDetails out,
2759 final HistoryStepDetails last) {
2760 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
2761
2762 // Perform a CPU update right after we do this collection, so we have started
2763 // collecting good data for the next step.
2764 requestImmediateCpuUpdate();
2765
2766 if (last == null) {
2767 // We are not generating a delta, so all we need to do is reset the stats
2768 // we will later be doing a delta from.
2769 final int NU = mUidStats.size();
2770 for (int i=0; i<NU; i++) {
2771 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
2772 uid.mLastStepUserTime = uid.mCurStepUserTime;
2773 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
2774 }
2775 mLastStepCpuUserTime = mCurStepCpuUserTime;
2776 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
2777 mLastStepStatUserTime = mCurStepStatUserTime;
2778 mLastStepStatSystemTime = mCurStepStatSystemTime;
2779 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
2780 mLastStepStatIrqTime = mCurStepStatIrqTime;
2781 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
2782 mLastStepStatIdleTime = mCurStepStatIdleTime;
2783 tmp.clear();
2784 return;
2785 }
2786 if (DEBUG) {
2787 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
2788 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
2789 + " irq=" + mLastStepStatIrqTime + " sirq="
2790 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
2791 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
2792 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
2793 + " irq=" + mCurStepStatIrqTime + " sirq="
2794 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
2795 }
2796 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
2797 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
2798 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
2799 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
2800 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
2801 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
2802 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
2803 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
2804 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
2805 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
2806 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
2807 final int NU = mUidStats.size();
2808 for (int i=0; i<NU; i++) {
2809 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
2810 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
2811 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
2812 final int totalTime = totalUTime + totalSTime;
2813 uid.mLastStepUserTime = uid.mCurStepUserTime;
2814 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
2815 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
2816 continue;
2817 }
2818 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
2819 out.appCpuUid3 = uid.mUid;
2820 out.appCpuUTime3 = totalUTime;
2821 out.appCpuSTime3 = totalSTime;
2822 } else {
2823 out.appCpuUid3 = out.appCpuUid2;
2824 out.appCpuUTime3 = out.appCpuUTime2;
2825 out.appCpuSTime3 = out.appCpuSTime2;
2826 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
2827 out.appCpuUid2 = uid.mUid;
2828 out.appCpuUTime2 = totalUTime;
2829 out.appCpuSTime2 = totalSTime;
2830 } else {
2831 out.appCpuUid2 = out.appCpuUid1;
2832 out.appCpuUTime2 = out.appCpuUTime1;
2833 out.appCpuSTime2 = out.appCpuSTime1;
2834 out.appCpuUid1 = uid.mUid;
2835 out.appCpuUTime1 = totalUTime;
2836 out.appCpuSTime1 = totalSTime;
2837 }
2838 }
2839 }
2840 mLastStepCpuUserTime = mCurStepCpuUserTime;
2841 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
2842 mLastStepStatUserTime = mCurStepStatUserTime;
2843 mLastStepStatSystemTime = mCurStepStatSystemTime;
2844 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
2845 mLastStepStatIrqTime = mCurStepStatIrqTime;
2846 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
2847 mLastStepStatIdleTime = mCurStepStatIdleTime;
2848 }
2849
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002850 public void readHistoryDelta(Parcel src, HistoryItem cur) {
2851 int firstToken = src.readInt();
2852 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002853 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002854 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002855 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
2856 + " deltaTimeToken=" + deltaTimeToken);
2857
2858 if (deltaTimeToken < DELTA_TIME_ABS) {
2859 cur.time += deltaTimeToken;
2860 } else if (deltaTimeToken == DELTA_TIME_ABS) {
2861 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002862 cur.numReadInts += 2;
2863 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002864 cur.readFromParcel(src);
2865 return;
2866 } else if (deltaTimeToken == DELTA_TIME_INT) {
2867 int delta = src.readInt();
2868 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002869 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002870 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
2871 } else {
2872 long delta = src.readLong();
2873 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
2874 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002875 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002876 }
2877
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002878 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002879 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002880 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08002881 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002882 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002883 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
2884 + Integer.toHexString(batteryLevelInt)
2885 + " batteryLevel=" + cur.batteryLevel
2886 + " batteryTemp=" + cur.batteryTemperature
2887 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002888 } else {
2889 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002890 }
2891
2892 if ((firstToken&DELTA_STATE_FLAG) != 0) {
2893 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07002894 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08002895 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
2896 & STATE_BATTERY_STATUS_MASK);
2897 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
2898 & STATE_BATTERY_HEALTH_MASK);
2899 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
2900 & STATE_BATTERY_PLUG_MASK);
2901 switch (cur.batteryPlugType) {
2902 case 1:
2903 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
2904 break;
2905 case 2:
2906 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
2907 break;
2908 case 3:
2909 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
2910 break;
2911 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002912 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002913 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
2914 + Integer.toHexString(stateInt)
2915 + " batteryStatus=" + cur.batteryStatus
2916 + " batteryHealth=" + cur.batteryHealth
2917 + " batteryPlugType=" + cur.batteryPlugType
2918 + " states=0x" + Integer.toHexString(cur.states));
2919 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07002920 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002921 }
2922
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002923 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
2924 cur.states2 = src.readInt();
2925 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
2926 + Integer.toHexString(cur.states2));
2927 }
2928
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002929 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002930 int indexes = src.readInt();
2931 int wakeLockIndex = indexes&0xffff;
2932 int wakeReasonIndex = (indexes>>16)&0xffff;
2933 if (wakeLockIndex != 0xffff) {
2934 cur.wakelockTag = cur.localWakelockTag;
2935 readHistoryTag(wakeLockIndex, cur.wakelockTag);
2936 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
2937 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
2938 } else {
2939 cur.wakelockTag = null;
2940 }
2941 if (wakeReasonIndex != 0xffff) {
2942 cur.wakeReasonTag = cur.localWakeReasonTag;
2943 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
2944 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
2945 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
2946 } else {
2947 cur.wakeReasonTag = null;
2948 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002949 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002950 } else {
2951 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002952 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002953 }
2954
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002955 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002956 cur.eventTag = cur.localEventTag;
2957 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08002958 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002959 final int index = ((codeAndIndex>>16)&0xffff);
2960 readHistoryTag(index, cur.eventTag);
2961 cur.numReadInts += 1;
2962 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
2963 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
2964 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002965 } else {
2966 cur.eventCode = HistoryItem.EVENT_NONE;
2967 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002968
2969 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
2970 cur.stepDetails = mReadHistoryStepDetails;
2971 cur.stepDetails.readFromParcel(src);
2972 } else {
2973 cur.stepDetails = null;
2974 }
Adam Lesinski926969b2016-04-28 17:31:12 -07002975
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002976 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
2977 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07002978 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002979 }
2980
Dianne Hackbornfc064132014-06-02 12:42:12 -07002981 @Override
2982 public void commitCurrentHistoryBatchLocked() {
2983 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
2984 }
2985
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002986 void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07002987 if (!mHaveBatteryLevel || !mRecordingHistory) {
2988 return;
2989 }
2990
Dianne Hackborn40c87252014-03-19 16:55:40 -07002991 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07002992 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
2993 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002994 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002995 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002996 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
2997 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002998 + Integer.toHexString(lastDiffStates) + " diff2="
2999 + Integer.toHexString(diffStates2) + " lastDiff2="
3000 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003001 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003002 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003003 && (diffStates2&lastDiffStates2) == 0
3004 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3005 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003006 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003007 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003008 || cur.eventCode == HistoryItem.EVENT_NONE)
3009 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3010 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3011 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3012 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3013 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3014 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003015 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003016 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003017 // as long as no bit has changed both between now and the last entry, as
3018 // well as the last entry and the one before it (so we capture any toggles).
3019 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003020 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3021 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3022 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003023 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003024 // If the last written history had a wakelock tag, we need to retain it.
3025 // Note that the condition above made sure that we aren't in a case where
3026 // both it and the current history item have a wakelock tag.
3027 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003028 cur.wakelockTag = cur.localWakelockTag;
3029 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003030 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003031 // If the last written history had a wake reason tag, we need to retain it.
3032 // Note that the condition above made sure that we aren't in a case where
3033 // both it and the current history item have a wakelock tag.
3034 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003035 cur.wakeReasonTag = cur.localWakeReasonTag;
3036 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003037 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003038 // If the last written history had an event, we need to retain it.
3039 // Note that the condition above made sure that we aren't in a case where
3040 // both it and the current history item have an event.
3041 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003042 cur.eventCode = mHistoryLastWritten.eventCode;
3043 cur.eventTag = cur.localEventTag;
3044 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003045 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003046 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003047 }
3048
Adam Lesinski45489782016-12-15 23:45:17 -08003049 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003050 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003051 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3052 // Clients can't deal with history buffers this large. This only
3053 // really happens when the device is on charger and interacted with
3054 // for long periods of time, like in retail mode. Since the device is
3055 // most likely charged, when unplugged, stats would have reset anyways.
3056 // Reset the stats and mark that we overflowed.
3057 // b/32540341
3058 resetAllStatsLocked();
3059
3060 // Mark that we want to set *OVERFLOW* event and the RESET:START
3061 // events.
3062 recordResetDueToOverflow = true;
3063
3064 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003065 if (!mHistoryOverflow) {
3066 mHistoryOverflow = true;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003067 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
3068 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003069 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003070 }
3071
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003072 // After overflow, we allow various bit-wise states to settle to 0.
3073 boolean writeAnyway = false;
3074 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3075 & mActiveHistoryStates;
3076 if (mHistoryLastWritten.states != curStates) {
3077 // mActiveHistoryStates keeps track of which bits in .states are now being
3078 // forced to 0.
3079 int old = mActiveHistoryStates;
3080 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3081 writeAnyway |= old != mActiveHistoryStates;
3082 }
3083 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3084 & mActiveHistoryStates2;
3085 if (mHistoryLastWritten.states2 != curStates2) {
3086 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3087 // forced to 0.
3088 int old = mActiveHistoryStates2;
3089 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3090 writeAnyway |= old != mActiveHistoryStates2;
3091 }
3092
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003093 // Once we've reached the maximum number of items, we only
3094 // record changes to the battery level and the most interesting states.
3095 // Once we've reached the maximum maximum number of items, we only
3096 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003097 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003098 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003099 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003100 & HistoryItem.MOST_INTERESTING_STATES) == 0
3101 || ((mHistoryLastWritten.states2^cur.states2)
3102 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003103 return;
3104 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003105
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003106 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003107 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003108 }
3109
Adam Lesinski45489782016-12-15 23:45:17 -08003110 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003111 // The history is currently empty; we need it to start with a time stamp.
3112 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003113 if (recordResetDueToOverflow) {
3114 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
3115 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003116 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_RESET, cur);
3117 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003118 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003119 }
3120
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003121 private void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd,
3122 HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003123 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003124 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003125 }
3126 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3127 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003128 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003129 mHistoryLastWritten.states &= mActiveHistoryStates;
3130 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003131 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003132 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003133 cur.wakelockTag = null;
3134 cur.wakeReasonTag = null;
3135 cur.eventCode = HistoryItem.EVENT_NONE;
3136 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003137 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3138 + " now " + mHistoryBuffer.dataPosition()
3139 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003140 }
3141
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003142 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003143 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003144
Dianne Hackborn40c87252014-03-19 16:55:40 -07003145 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003146 if (mTrackRunningHistoryElapsedRealtime != 0) {
3147 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3148 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3149 if (diffUptime < (diffElapsed-20)) {
3150 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3151 mHistoryAddTmp.setTo(mHistoryLastWritten);
3152 mHistoryAddTmp.wakelockTag = null;
3153 mHistoryAddTmp.wakeReasonTag = null;
3154 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3155 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
3156 addHistoryRecordInnerLocked(wakeElapsedTime, uptimeMs, mHistoryAddTmp);
3157 }
3158 }
3159 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3160 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3161 mTrackRunningHistoryUptime = uptimeMs;
3162 addHistoryRecordInnerLocked(elapsedRealtimeMs, uptimeMs, mHistoryCur);
3163 }
3164
3165 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
3166 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003167
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003168 if (!USE_OLD_HISTORY) {
3169 return;
3170 }
3171
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003172 if (!mHaveBatteryLevel || !mRecordingHistory) {
3173 return;
3174 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003175
3176 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003177 // and no states have since the last recorded entry changed and
3178 // are now resetting back to their original value, then just collapse
3179 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003180 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003181 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003182 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3183 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003184 // If the current is the same as the one before, then we no
3185 // longer need the entry.
3186 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003187 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003188 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003189 mHistoryLastEnd.next = null;
3190 mHistoryEnd.next = mHistoryCache;
3191 mHistoryCache = mHistoryEnd;
3192 mHistoryEnd = mHistoryLastEnd;
3193 mHistoryLastEnd = null;
3194 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003195 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3196 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003197 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003198 }
3199 return;
3200 }
3201
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003202 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003203 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003204
3205 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3206 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07003207 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003208 }
3209
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003210 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3211 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003212 // record changes to the battery level and the most interesting states.
3213 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003214 // record changes to the battery level.
3215 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003216 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003217 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003218 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003219 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003220 return;
3221 }
3222 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003223
Dianne Hackborn40c87252014-03-19 16:55:40 -07003224 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003225 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003226
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003227 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003228 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003229 mHistoryCur.eventCode = code;
3230 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3231 mHistoryCur.eventTag.string = name;
3232 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003233 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003234 }
3235
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003236 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003237 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003238 if (rec != null) {
3239 mHistoryCache = rec.next;
3240 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003241 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003242 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003243 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003244
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003245 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003246 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003247
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003248 void addHistoryRecordLocked(HistoryItem rec) {
3249 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003250 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003251 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003252 if (mHistoryEnd != null) {
3253 mHistoryEnd.next = rec;
3254 mHistoryEnd = rec;
3255 } else {
3256 mHistory = mHistoryEnd = rec;
3257 }
3258 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003259
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003260 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003261 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003262 if (USE_OLD_HISTORY) {
3263 if (mHistory != null) {
3264 mHistoryEnd.next = mHistoryCache;
3265 mHistoryCache = mHistory;
3266 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3267 }
3268 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003269 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003270
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003271 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003272 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003273 mTrackRunningHistoryElapsedRealtime = 0;
3274 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003275
3276 mHistoryBuffer.setDataSize(0);
3277 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003278 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003279 mHistoryLastLastWritten.clear();
3280 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003281 mHistoryTagPool.clear();
3282 mNextHistoryTagIdx = 0;
3283 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003284 mHistoryBufferLastPos = -1;
3285 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003286 mActiveHistoryStates = 0xffffffff;
3287 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003288 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003289
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003290 public void updateTimeBasesLocked(boolean unplugged, boolean screenOff, long uptime,
3291 long realtime) {
Bookatz867c0d72017-03-07 18:23:42 -08003292 boolean batteryStatusChanged = mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
3293
3294 if (batteryStatusChanged) {
3295 for (int i=0; i<mUidStats.size(); i++) {
3296 mUidStats.valueAt(i).updateBgTimeBase(uptime, realtime);
3297 }
3298 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07003299
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003300 boolean unpluggedScreenOff = unplugged && screenOff;
3301 if (unpluggedScreenOff != mOnBatteryScreenOffTimeBase.isRunning()) {
3302 updateKernelWakelocksLocked();
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003303 updateBatteryPropertiesLocked();
Adam Lesinski72478f02015-06-17 15:39:43 -07003304 if (DEBUG_ENERGY_CPU) {
3305 Slog.d(TAG, "Updating cpu time because screen is now " +
3306 (unpluggedScreenOff ? "off" : "on"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003307 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003308 updateCpuTimeLocked();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003309 mOnBatteryScreenOffTimeBase.setRunning(unpluggedScreenOff, uptime, realtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 }
3311 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003312
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003313 private void updateBatteryPropertiesLocked() {
3314 try {
3315 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3316 ServiceManager.getService("batteryproperties"));
3317 registrar.scheduleUpdate();
3318 } catch (RemoteException e) {
3319 // Ignore.
3320 }
3321 }
3322
Dianne Hackborn099bc622014-01-22 13:39:16 -08003323 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3324 mIsolatedUids.put(isolatedUid, appUid);
3325 }
3326
Adam Lesinski61db88f2015-07-01 15:05:07 -07003327 /**
3328 * Schedules a read of the latest cpu times before removing the isolated UID.
3329 * @see #removeIsolatedUidLocked(int)
3330 */
3331 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003332 int curUid = mIsolatedUids.get(isolatedUid, -1);
3333 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003334 if (mExternalSync != null) {
3335 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3336 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003337 }
3338 }
3339
Adam Lesinski61db88f2015-07-01 15:05:07 -07003340 /**
3341 * This should only be called after the cpu times have been read.
3342 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3343 */
3344 public void removeIsolatedUidLocked(int isolatedUid) {
3345 mIsolatedUids.delete(isolatedUid);
3346 mKernelUidCpuTimeReader.removeUid(isolatedUid);
3347 }
3348
Dianne Hackborn099bc622014-01-22 13:39:16 -08003349 public int mapUid(int uid) {
3350 int isolated = mIsolatedUids.get(uid, -1);
3351 return isolated > 0 ? isolated : uid;
3352 }
3353
3354 public void noteEventLocked(int code, String name, int uid) {
3355 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003356 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3357 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003358 }
Joe Onoratoabded112016-02-08 16:49:39 -08003359 final long elapsedRealtime = mClocks.elapsedRealtime();
3360 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003361 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003362 }
3363
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003364 boolean ensureStartClockTime(final long currentTime) {
3365 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3366 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3367 // If the start clock time has changed by more than a year, then presumably
3368 // the previous time was completely bogus. So we are going to figure out a
3369 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003370 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003371 return true;
3372 }
3373 return false;
3374 }
3375
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003376 public void noteCurrentTimeChangedLocked() {
3377 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003378 final long elapsedRealtime = mClocks.elapsedRealtime();
3379 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003380 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003381 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003382 }
3383
Dianne Hackborn61659e52014-07-09 16:13:01 -07003384 public void noteProcessStartLocked(String name, int uid) {
3385 uid = mapUid(uid);
3386 if (isOnBattery()) {
3387 Uid u = getUidStatsLocked(uid);
3388 u.getProcessStatsLocked(name).incStartsLocked();
3389 }
3390 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3391 return;
3392 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003393 if (!mRecordAllHistory) {
3394 return;
3395 }
Joe Onoratoabded112016-02-08 16:49:39 -08003396 final long elapsedRealtime = mClocks.elapsedRealtime();
3397 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003398 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3399 }
3400
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003401 public void noteProcessCrashLocked(String name, int uid) {
3402 uid = mapUid(uid);
3403 if (isOnBattery()) {
3404 Uid u = getUidStatsLocked(uid);
3405 u.getProcessStatsLocked(name).incNumCrashesLocked();
3406 }
3407 }
3408
3409 public void noteProcessAnrLocked(String name, int uid) {
3410 uid = mapUid(uid);
3411 if (isOnBattery()) {
3412 Uid u = getUidStatsLocked(uid);
3413 u.getProcessStatsLocked(name).incNumAnrsLocked();
3414 }
3415 }
3416
Dianne Hackborna8d10942015-11-19 17:55:19 -08003417 public void noteUidProcessStateLocked(int uid, int state) {
Dianne Hackborn61659e52014-07-09 16:13:01 -07003418 uid = mapUid(uid);
Dianne Hackborna8d10942015-11-19 17:55:19 -08003419 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003420 }
3421
3422 public void noteProcessFinishLocked(String name, int uid) {
3423 uid = mapUid(uid);
3424 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
3425 return;
3426 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003427 if (!mRecordAllHistory) {
3428 return;
3429 }
Joe Onoratoabded112016-02-08 16:49:39 -08003430 final long elapsedRealtime = mClocks.elapsedRealtime();
3431 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003432 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003433 }
3434
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003435 public void noteSyncStartLocked(String name, int uid) {
3436 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003437 final long elapsedRealtime = mClocks.elapsedRealtime();
3438 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003439 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
3440 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
3441 return;
3442 }
3443 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
3444 }
3445
3446 public void noteSyncFinishLocked(String name, int uid) {
3447 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003448 final long elapsedRealtime = mClocks.elapsedRealtime();
3449 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003450 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
3451 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
3452 return;
3453 }
3454 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
3455 }
3456
3457 public void noteJobStartLocked(String name, int uid) {
3458 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003459 final long elapsedRealtime = mClocks.elapsedRealtime();
3460 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003461 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
3462 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
3463 return;
3464 }
3465 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
3466 }
3467
3468 public void noteJobFinishLocked(String name, int uid) {
3469 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003470 final long elapsedRealtime = mClocks.elapsedRealtime();
3471 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003472 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime);
3473 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
3474 return;
3475 }
3476 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
3477 }
3478
Dianne Hackborn1e383822015-04-10 14:02:33 -07003479 public void noteAlarmStartLocked(String name, int uid) {
3480 if (!mRecordAllHistory) {
3481 return;
3482 }
3483 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003484 final long elapsedRealtime = mClocks.elapsedRealtime();
3485 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e383822015-04-10 14:02:33 -07003486 if (!mActiveEvents.updateState(HistoryItem.EVENT_ALARM_START, name, uid, 0)) {
3487 return;
3488 }
3489 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ALARM_START, name, uid);
3490 }
3491
3492 public void noteAlarmFinishLocked(String name, int uid) {
3493 if (!mRecordAllHistory) {
3494 return;
3495 }
3496 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003497 final long elapsedRealtime = mClocks.elapsedRealtime();
3498 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e383822015-04-10 14:02:33 -07003499 if (!mActiveEvents.updateState(HistoryItem.EVENT_ALARM_FINISH, name, uid, 0)) {
3500 return;
3501 }
3502 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ALARM_FINISH, name, uid);
3503 }
3504
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003505 private void requestWakelockCpuUpdate() {
3506 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) {
3507 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS);
3508 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS);
3509 }
3510 }
3511
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003512 private void requestImmediateCpuUpdate() {
3513 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
3514 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS);
3515 }
3516
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003517 public void setRecordAllHistoryLocked(boolean enabled) {
3518 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003519 if (!enabled) {
3520 // Clear out any existing state.
3521 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003522 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003523 // Record the currently running processes as stopping, now that we are no
3524 // longer tracking them.
3525 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
3526 HistoryItem.EVENT_PROC);
3527 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08003528 long mSecRealtime = mClocks.elapsedRealtime();
3529 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003530 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
3531 SparseIntArray uids = ent.getValue();
3532 for (int j=0; j<uids.size(); j++) {
3533 addHistoryEventLocked(mSecRealtime, mSecUptime,
3534 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
3535 }
3536 }
3537 }
3538 } else {
3539 // Record the currently running processes as starting, now that we are tracking them.
3540 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
3541 HistoryItem.EVENT_PROC);
3542 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08003543 long mSecRealtime = mClocks.elapsedRealtime();
3544 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003545 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
3546 SparseIntArray uids = ent.getValue();
3547 for (int j=0; j<uids.size(); j++) {
3548 addHistoryEventLocked(mSecRealtime, mSecUptime,
3549 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
3550 }
3551 }
3552 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003553 }
3554 }
3555
Dianne Hackborn9a755432014-05-15 17:05:22 -07003556 public void setNoAutoReset(boolean enabled) {
3557 mNoAutoReset = enabled;
3558 }
3559
Amith Yamasani674c9bb2017-02-01 09:45:17 -08003560 public void setPretendScreenOff(boolean pretendScreenOff) {
3561 mPretendScreenOff = pretendScreenOff;
3562 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
3563 }
3564
Dianne Hackborn9a755432014-05-15 17:05:22 -07003565 private String mInitialAcquireWakeName;
3566 private int mInitialAcquireWakeUid = -1;
3567
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003568 public void noteStartWakeLocked(int uid, int pid, String name, String historyName, int type,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003569 boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003570 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003571 if (type == WAKE_TYPE_PARTIAL) {
3572 // Only care about partial wake locks, since full wake locks
3573 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003574 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07003575 if (historyName == null) {
3576 historyName = name;
3577 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003578 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07003579 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
3580 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07003581 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07003582 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07003583 }
3584 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003585 if (mWakeLockNesting == 0) {
3586 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
3587 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
3588 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003589 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003590 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07003591 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003592 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003593 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07003594 } else if (!mWakeLockImportant && !unimportantForLogging
3595 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003596 if (mHistoryLastWritten.wakelockTag != null) {
3597 // We'll try to update the last tag.
3598 mHistoryLastWritten.wakelockTag = null;
3599 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003600 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07003601 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003602 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003603 }
3604 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003605 }
3606 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003607 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003608 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07003609 if (mOnBatteryScreenOffTimeBase.isRunning()) {
3610 // We only update the cpu time when a wake lock is acquired if the screen is off.
3611 // If the screen is on, we don't distribute the power amongst partial wakelocks.
3612 if (DEBUG_ENERGY_CPU) {
3613 Slog.d(TAG, "Updating cpu time because of +wake_lock");
3614 }
3615 requestWakelockCpuUpdate();
3616 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003617 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003618 }
3619 }
3620
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003621 public void noteStopWakeLocked(int uid, int pid, String name, String historyName, int type,
3622 long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003623 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003624 if (type == WAKE_TYPE_PARTIAL) {
3625 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003626 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07003627 if (historyName == null) {
3628 historyName = name;
3629 }
3630 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
3631 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07003632 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07003633 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07003634 }
3635 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003636 if (mWakeLockNesting == 0) {
3637 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
3638 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
3639 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07003640 mInitialAcquireWakeName = null;
3641 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003642 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003643 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003644 }
3645 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07003646 if (mOnBatteryScreenOffTimeBase.isRunning()) {
3647 if (DEBUG_ENERGY_CPU) {
3648 Slog.d(TAG, "Updating cpu time because of -wake_lock");
3649 }
3650 requestWakelockCpuUpdate();
3651 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003652 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003653 }
3654 }
3655
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003656 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
3657 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08003658 final long elapsedRealtime = mClocks.elapsedRealtime();
3659 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003660 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003661 for (int i=0; i<N; i++) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003662 noteStartWakeLocked(ws.get(i), pid, name, historyName, type, unimportantForLogging,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003663 elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003664 }
3665 }
3666
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003667 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
3668 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003669 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08003670 final long elapsedRealtime = mClocks.elapsedRealtime();
3671 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003672 // For correct semantics, we start the need worksources first, so that we won't
3673 // make inappropriate history items as if all wake locks went away and new ones
3674 // appeared. This is okay because tracking of wake locks allows nesting.
Dianne Hackborn40c87252014-03-19 16:55:40 -07003675 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003676 for (int i=0; i<NN; i++) {
3677 noteStartWakeLocked(newWs.get(i), newPid, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003678 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003679 }
3680 final int NO = ws.size();
3681 for (int i=0; i<NO; i++) {
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003682 noteStopWakeLocked(ws.get(i), pid, name, historyName, type, elapsedRealtime, uptime);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003683 }
3684 }
3685
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003686 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
3687 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08003688 final long elapsedRealtime = mClocks.elapsedRealtime();
3689 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003690 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003691 for (int i=0; i<N; i++) {
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003692 noteStopWakeLocked(ws.get(i), pid, name, historyName, type, elapsedRealtime, uptime);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003693 }
3694 }
3695
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003696 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
3697 uid = mapUid(uid);
3698 final long elapsedRealtime = mClocks.elapsedRealtime();
3699 final long uptime = mClocks.uptimeMillis();
3700 if (historyName == null) {
3701 historyName = name;
3702 }
3703 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
3704 0)) {
3705 return;
3706 }
3707 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
3708 historyName, uid);
3709 }
3710
3711 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
3712 uid = mapUid(uid);
3713 final long elapsedRealtime = mClocks.elapsedRealtime();
3714 final long uptime = mClocks.uptimeMillis();
3715 if (historyName == null) {
3716 historyName = name;
3717 }
3718 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
3719 0)) {
3720 return;
3721 }
3722 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
3723 historyName, uid);
3724 }
3725
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003726 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
3727 if (mLastWakeupReason != null) {
3728 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003729 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003730 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003731 mLastWakeupReason = null;
3732 }
3733 }
3734
3735 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08003736 final long elapsedRealtime = mClocks.elapsedRealtime();
3737 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003738 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003739 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003740 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003741 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
3742 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003743 mHistoryCur.wakeReasonTag.uid = 0;
3744 mLastWakeupReason = reason;
3745 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003746 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003747 }
3748
Adam Lesinski72478f02015-06-17 15:39:43 -07003749 public boolean startAddingCpuLocked() {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07003750 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
Adam Lesinski72478f02015-06-17 15:39:43 -07003751 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07003752 }
3753
Adam Lesinski72478f02015-06-17 15:39:43 -07003754 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
3755 int statSystemTime, int statIOWaitTime, int statIrqTime,
3756 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003757 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
3758 + " user=" + statUserTime + " sys=" + statSystemTime
3759 + " io=" + statIOWaitTime + " irq=" + statIrqTime
3760 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
3761 mCurStepCpuUserTime += totalUTime;
3762 mCurStepCpuSystemTime += totalSTime;
3763 mCurStepStatUserTime += statUserTime;
3764 mCurStepStatSystemTime += statSystemTime;
3765 mCurStepStatIOWaitTime += statIOWaitTime;
3766 mCurStepStatIrqTime += statIrqTime;
3767 mCurStepStatSoftIrqTime += statSoftIrqTime;
3768 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07003769 }
3770
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003771 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003772 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003773 Uid u = mUidStats.get(uid);
3774 if (u != null) {
3775 u.mPids.remove(pid);
3776 }
3777 }
3778
3779 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003780 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003781 Uid u = mUidStats.get(uid);
3782 if (u != null) {
3783 Uid.Pid p = u.mPids.get(pid);
3784 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003785 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003786 }
3787 }
3788 return 0;
3789 }
3790
3791 public void reportExcessiveWakeLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003792 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003793 Uid u = mUidStats.get(uid);
3794 if (u != null) {
3795 u.reportExcessiveWakeLocked(proc, overTime, usedTime);
3796 }
3797 }
3798
Dianne Hackborn287952c2010-09-22 22:34:31 -07003799 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003800 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003801 Uid u = mUidStats.get(uid);
3802 if (u != null) {
3803 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
3804 }
3805 }
3806
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003807 int mSensorNesting;
3808
3809 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003810 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003811 final long elapsedRealtime = mClocks.elapsedRealtime();
3812 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003813 if (mSensorNesting == 0) {
3814 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
3815 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
3816 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07003817 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003818 }
3819 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003820 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003821 }
3822
3823 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003824 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003825 final long elapsedRealtime = mClocks.elapsedRealtime();
3826 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003827 mSensorNesting--;
3828 if (mSensorNesting == 0) {
3829 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
3830 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
3831 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07003832 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003833 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003834 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003835 }
3836
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003837 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003838
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003839 public void noteStartGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003840 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003841 final long elapsedRealtime = mClocks.elapsedRealtime();
3842 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003843 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003844 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003845 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
3846 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07003847 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003848 }
3849 mGpsNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003850 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003852
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003853 public void noteStopGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003854 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003855 final long elapsedRealtime = mClocks.elapsedRealtime();
3856 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003857 mGpsNesting--;
3858 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003859 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003860 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
3861 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07003862 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003863 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003864 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003866
Jeff Browne95c3cd2014-05-02 16:59:26 -07003867 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08003868 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08003869
3870 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
3871 // original 4 are mapped to one of the originals.
3872 if (state > MAX_TRACKED_SCREEN_STATE) {
3873 switch (state) {
3874 case Display.STATE_VR:
3875 state = Display.STATE_ON;
3876 break;
3877 default:
3878 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
3879 break;
3880 }
3881 }
3882
Jeff Browne95c3cd2014-05-02 16:59:26 -07003883 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08003884 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07003885 final int oldState = mScreenState;
3886 mScreenState = state;
3887 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
3888 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003889
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003890 if (state != Display.STATE_UNKNOWN) {
3891 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08003892 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
3893 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
3894 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003895 } else {
3896 Slog.wtf(TAG, "Unexpected screen state: " + state);
3897 }
3898 }
3899
Jeff Browne95c3cd2014-05-02 16:59:26 -07003900 if (state == Display.STATE_ON) {
3901 // Screen turning on.
Joe Onoratoabded112016-02-08 16:49:39 -08003902 final long elapsedRealtime = mClocks.elapsedRealtime();
3903 final long uptime = mClocks.uptimeMillis();
Jeff Browne95c3cd2014-05-02 16:59:26 -07003904 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
3905 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
3906 + Integer.toHexString(mHistoryCur.states));
3907 addHistoryRecordLocked(elapsedRealtime, uptime);
3908 mScreenOnTimer.startRunningLocked(elapsedRealtime);
3909 if (mScreenBrightnessBin >= 0) {
3910 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
3911 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003912
Jeff Browne95c3cd2014-05-02 16:59:26 -07003913 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), false,
Joe Onoratoabded112016-02-08 16:49:39 -08003914 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003915
Jeff Browne95c3cd2014-05-02 16:59:26 -07003916 // Fake a wake lock, so we consider the device waked as long
3917 // as the screen is on.
3918 noteStartWakeLocked(-1, -1, "screen", null, WAKE_TYPE_PARTIAL, false,
3919 elapsedRealtime, uptime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003920
Jeff Browne95c3cd2014-05-02 16:59:26 -07003921 // Update discharge amounts.
3922 if (mOnBatteryInternal) {
3923 updateDischargeScreenLevelsLocked(false, true);
3924 }
3925 } else if (oldState == Display.STATE_ON) {
3926 // Screen turning off or dozing.
Joe Onoratoabded112016-02-08 16:49:39 -08003927 final long elapsedRealtime = mClocks.elapsedRealtime();
3928 final long uptime = mClocks.uptimeMillis();
Jeff Browne95c3cd2014-05-02 16:59:26 -07003929 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
3930 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
3931 + Integer.toHexString(mHistoryCur.states));
3932 addHistoryRecordLocked(elapsedRealtime, uptime);
3933 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
3934 if (mScreenBrightnessBin >= 0) {
3935 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
3936 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003937
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003938 noteStopWakeLocked(-1, -1, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07003939 elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003940
Jeff Browne95c3cd2014-05-02 16:59:26 -07003941 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), true,
Joe Onoratoabded112016-02-08 16:49:39 -08003942 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003943
Jeff Browne95c3cd2014-05-02 16:59:26 -07003944 // Update discharge amounts.
3945 if (mOnBatteryInternal) {
3946 updateDischargeScreenLevelsLocked(true, false);
3947 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08003948 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07003949 }
3950 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003951
Dianne Hackborn617f8772009-03-31 15:04:46 -07003952 public void noteScreenBrightnessLocked(int brightness) {
3953 // Bin the brightness.
3954 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
3955 if (bin < 0) bin = 0;
3956 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
3957 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08003958 final long elapsedRealtime = mClocks.elapsedRealtime();
3959 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003960 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
3961 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003962 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
3963 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07003964 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07003965 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07003966 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003967 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07003968 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003969 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07003970 }
3971 mScreenBrightnessBin = bin;
3972 }
3973 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003974
Dianne Hackborn617f8772009-03-31 15:04:46 -07003975 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08003976 if (mOnBatteryInternal) {
3977 uid = mapUid(uid);
3978 getUidStatsLocked(uid).noteUserActivityLocked(event);
3979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003981
Dianne Hackborn280a64e2015-07-13 14:48:08 -07003982 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08003983 final long elapsedRealtime = mClocks.elapsedRealtime();
3984 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07003985 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
3986 reason, reasonUid);
3987 }
3988
Jeff Browne95c3cd2014-05-02 16:59:26 -07003989 public void noteInteractiveLocked(boolean interactive) {
3990 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08003991 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07003992 mInteractive = interactive;
3993 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
3994 if (interactive) {
3995 mInteractiveTimer.startRunningLocked(elapsedRealtime);
3996 } else {
3997 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
3998 }
3999 }
4000 }
4001
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004002 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004003 final long elapsedRealtime = mClocks.elapsedRealtime();
4004 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004005 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4006 extra, type);
4007 mNumConnectivityChange++;
4008 }
4009
Adam Lesinski5f056f62016-07-14 16:56:08 -07004010 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4011 final long uptimeMillis, int uid) {
4012 uid = mapUid(uid);
4013 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4014 uid);
4015 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4016 }
4017
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07004018 public void noteMobileRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004019 final long elapsedRealtime = mClocks.elapsedRealtime();
4020 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004021 if (mMobileRadioPowerState != powerState) {
4022 long realElapsedRealtimeMs;
4023 final boolean active =
4024 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4025 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4026 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004027 if (uid > 0) {
4028 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4029 }
4030
Adam Lesinski9acfd812016-04-19 18:29:50 -07004031 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004032 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4033 } else {
4034 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004035 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004036 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4037 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4038 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004039 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004040 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4041 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4042 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004043 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004044 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4045 }
4046 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4047 + Integer.toHexString(mHistoryCur.states));
4048 addHistoryRecordLocked(elapsedRealtime, uptime);
4049 mMobileRadioPowerState = powerState;
4050 if (active) {
4051 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4052 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4053 } else {
4054 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08004055 updateMobileRadioStateLocked(realElapsedRealtimeMs, null);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004056 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004057 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004058 }
4059 }
4060
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004061 public void notePowerSaveMode(boolean enabled) {
4062 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004063 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4064 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4065 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004066 final long elapsedRealtime = mClocks.elapsedRealtime();
4067 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004068 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004069 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004070 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4071 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004072 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004073 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004074 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004075 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4076 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004077 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004078 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004079 }
4080 addHistoryRecordLocked(elapsedRealtime, uptime);
4081 }
4082 }
4083
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004084 public void noteDeviceIdleModeLocked(int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004085 final long elapsedRealtime = mClocks.elapsedRealtime();
4086 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004087 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004088 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004089 // We don't go out of general idling mode until explicitly taken out of
4090 // device idle through going active or significant motion.
4091 nowIdling = true;
4092 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004093 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4094 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4095 // We don't go out of general light idling mode until explicitly taken out of
4096 // device idle through going active or significant motion.
4097 nowLightIdling = true;
4098 }
4099 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
4100 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
4101 activeReason, activeUid);
4102 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004103 if (mDeviceIdling != nowIdling) {
4104 mDeviceIdling = nowIdling;
4105 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
4106 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
4107 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004108 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004109 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
4110 } else {
4111 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
4112 }
4113 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004114 if (mDeviceLightIdling != nowLightIdling) {
4115 mDeviceLightIdling = nowLightIdling;
4116 if (nowLightIdling) {
4117 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004118 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004119 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004120 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004121 }
4122 if (mDeviceIdleMode != mode) {
4123 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
4124 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
4125 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
4126 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004127 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004128 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
4129 mLastIdleTimeStart = elapsedRealtime;
4130 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
4131 if (lastDuration > mLongestLightIdleTime) {
4132 mLongestLightIdleTime = lastDuration;
4133 }
4134 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004135 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004136 if (lastDuration > mLongestFullIdleTime) {
4137 mLongestFullIdleTime = lastDuration;
4138 }
4139 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
4140 }
4141 if (mode == DEVICE_IDLE_MODE_LIGHT) {
4142 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004143 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004144 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
4145 }
4146 mDeviceIdleMode = mode;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004147 }
4148 }
4149
4150 public void notePackageInstalledLocked(String pkgName, int versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08004151 final long elapsedRealtime = mClocks.elapsedRealtime();
4152 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004153 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
4154 pkgName, versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004155 PackageChange pc = new PackageChange();
4156 pc.mPackageName = pkgName;
4157 pc.mUpdate = true;
4158 pc.mVersionCode = versionCode;
4159 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004160 }
4161
4162 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08004163 final long elapsedRealtime = mClocks.elapsedRealtime();
4164 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004165 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
4166 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004167 PackageChange pc = new PackageChange();
4168 pc.mPackageName = pkgName;
4169 pc.mUpdate = true;
4170 addPackageChange(pc);
4171 }
4172
4173 private void addPackageChange(PackageChange pc) {
4174 if (mDailyPackageChanges == null) {
4175 mDailyPackageChanges = new ArrayList<>();
4176 }
4177 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004178 }
4179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 public void notePhoneOnLocked() {
4181 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004182 final long elapsedRealtime = mClocks.elapsedRealtime();
4183 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004184 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004185 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
4186 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004187 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004189 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 }
4191 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 public void notePhoneOffLocked() {
4194 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004195 final long elapsedRealtime = mClocks.elapsedRealtime();
4196 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004197 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004198 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
4199 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004200 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004202 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203 }
4204 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07004205
Dianne Hackborn3251b902014-06-20 14:40:53 -07004206 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08004207 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08004208 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004209 if (i == except) {
4210 continue;
4211 }
4212 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004213 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004214 }
4215 }
4216 }
4217
Dianne Hackborne4a59512010-12-07 11:08:07 -08004218 private int fixPhoneServiceState(int state, int signalBin) {
4219 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
4220 // In this case we will always be STATE_OUT_OF_SERVICE, so need
4221 // to infer that we are scanning from other data.
4222 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08004223 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004224 state = ServiceState.STATE_IN_SERVICE;
4225 }
4226 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004227
Dianne Hackborne4a59512010-12-07 11:08:07 -08004228 return state;
4229 }
4230
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004231 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004232 boolean scanning = false;
4233 boolean newHistory = false;
4234
4235 mPhoneServiceStateRaw = state;
4236 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004237 mPhoneSignalStrengthBinRaw = strengthBin;
4238
Joe Onoratoabded112016-02-08 16:49:39 -08004239 final long elapsedRealtime = mClocks.elapsedRealtime();
4240 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08004241
4242 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
4243 // In this case we will always be STATE_OUT_OF_SERVICE, so need
4244 // to infer that we are scanning from other data.
4245 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004246 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004247 state = ServiceState.STATE_IN_SERVICE;
4248 }
4249 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004250
4251 // If the phone is powered off, stop all timers.
4252 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004253 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07004254
Dianne Hackborne4a59512010-12-07 11:08:07 -08004255 // If we are in service, make sure the correct signal string timer is running.
4256 } else if (state == ServiceState.STATE_IN_SERVICE) {
4257 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004258
4259 // If we're out of service, we are in the lowest signal strength
4260 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07004261 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004262 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004263 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07004264 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004265 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08004266 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004267 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
4268 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004269 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07004270 }
4271 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004272
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004273 if (!scanning) {
4274 // If we are no longer scanning, then stop the scanning timer.
4275 if (mPhoneSignalScanningTimer.isRunningLocked()) {
4276 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
4277 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
4278 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08004279 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004280 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004281 }
4282 }
4283
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004284 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004285 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
4286 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004287 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004288 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08004289 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004290 mPhoneServiceState = state;
4291 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08004292
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004293 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004294 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004295 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004296 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004297 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004298 if (strengthBin >= 0) {
4299 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004300 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004301 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07004302 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
4303 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004304 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08004305 + Integer.toHexString(mHistoryCur.states));
4306 newHistory = true;
4307 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07004308 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004309 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004310 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08004311 }
4312
4313 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07004314 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004315 }
4316 }
4317
4318 /**
4319 * Telephony stack updates the phone state.
4320 * @param state phone state from ServiceState.getState()
4321 */
4322 public void notePhoneStateLocked(int state, int simState) {
4323 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07004324 }
4325
Wink Savillee9b06d72009-05-18 21:47:50 -07004326 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07004327 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08004328 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08004329 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004330 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004331
Dianne Hackborn627bba72009-03-24 22:32:56 -07004332 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
4333 int bin = DATA_CONNECTION_NONE;
4334 if (hasData) {
4335 switch (dataType) {
4336 case TelephonyManager.NETWORK_TYPE_EDGE:
4337 bin = DATA_CONNECTION_EDGE;
4338 break;
4339 case TelephonyManager.NETWORK_TYPE_GPRS:
4340 bin = DATA_CONNECTION_GPRS;
4341 break;
4342 case TelephonyManager.NETWORK_TYPE_UMTS:
4343 bin = DATA_CONNECTION_UMTS;
4344 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004345 case TelephonyManager.NETWORK_TYPE_CDMA:
4346 bin = DATA_CONNECTION_CDMA;
4347 break;
4348 case TelephonyManager.NETWORK_TYPE_EVDO_0:
4349 bin = DATA_CONNECTION_EVDO_0;
4350 break;
4351 case TelephonyManager.NETWORK_TYPE_EVDO_A:
4352 bin = DATA_CONNECTION_EVDO_A;
4353 break;
4354 case TelephonyManager.NETWORK_TYPE_1xRTT:
4355 bin = DATA_CONNECTION_1xRTT;
4356 break;
4357 case TelephonyManager.NETWORK_TYPE_HSDPA:
4358 bin = DATA_CONNECTION_HSDPA;
4359 break;
4360 case TelephonyManager.NETWORK_TYPE_HSUPA:
4361 bin = DATA_CONNECTION_HSUPA;
4362 break;
4363 case TelephonyManager.NETWORK_TYPE_HSPA:
4364 bin = DATA_CONNECTION_HSPA;
4365 break;
4366 case TelephonyManager.NETWORK_TYPE_IDEN:
4367 bin = DATA_CONNECTION_IDEN;
4368 break;
4369 case TelephonyManager.NETWORK_TYPE_EVDO_B:
4370 bin = DATA_CONNECTION_EVDO_B;
4371 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07004372 case TelephonyManager.NETWORK_TYPE_LTE:
4373 bin = DATA_CONNECTION_LTE;
4374 break;
4375 case TelephonyManager.NETWORK_TYPE_EHRPD:
4376 bin = DATA_CONNECTION_EHRPD;
4377 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08004378 case TelephonyManager.NETWORK_TYPE_HSPAP:
4379 bin = DATA_CONNECTION_HSPAP;
4380 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07004381 default:
4382 bin = DATA_CONNECTION_OTHER;
4383 break;
4384 }
4385 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004386 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004387 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004388 final long elapsedRealtime = mClocks.elapsedRealtime();
4389 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004390 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
4391 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004392 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
4393 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004394 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004395 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004396 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004397 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004398 }
4399 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004400 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004401 }
4402 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004403
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004404 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07004405 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004406 final long elapsedRealtime = mClocks.elapsedRealtime();
4407 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07004408 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004409 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
4410 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004411 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004412 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004413 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004414 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07004415 }
4416 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004417
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004418 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08004419 final long elapsedRealtime = mClocks.elapsedRealtime();
4420 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07004421 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07004422 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004423 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
4424 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004425 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004426 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004427 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004428 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07004429 }
4430 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004431
4432 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004433 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004434 final long elapsedRealtime = mClocks.elapsedRealtime();
4435 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004436 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004437 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004438 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
4439 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004440 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004441 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004442 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004443 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004444 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004445 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004446
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004447 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004448 if (mAudioOnNesting == 0) {
4449 return;
4450 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004451 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004452 final long elapsedRealtime = mClocks.elapsedRealtime();
4453 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004454 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004455 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004456 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
4457 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004458 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004459 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004460 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004461 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004462 }
4463
4464 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004465 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004466 final long elapsedRealtime = mClocks.elapsedRealtime();
4467 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004468 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004469 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004470 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
4471 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004472 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004473 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004474 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004475 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004476 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004477 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004478
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004479 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004480 if (mVideoOnNesting == 0) {
4481 return;
4482 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004483 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004484 final long elapsedRealtime = mClocks.elapsedRealtime();
4485 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004486 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004487 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004488 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
4489 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004490 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004491 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004492 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004493 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004494 }
4495
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004496 public void noteResetAudioLocked() {
4497 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004498 final long elapsedRealtime = mClocks.elapsedRealtime();
4499 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004500 mAudioOnNesting = 0;
4501 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
4502 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
4503 + Integer.toHexString(mHistoryCur.states));
4504 addHistoryRecordLocked(elapsedRealtime, uptime);
4505 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
4506 for (int i=0; i<mUidStats.size(); i++) {
4507 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4508 uid.noteResetAudioLocked(elapsedRealtime);
4509 }
4510 }
4511 }
4512
4513 public void noteResetVideoLocked() {
4514 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004515 final long elapsedRealtime = mClocks.elapsedRealtime();
4516 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004517 mAudioOnNesting = 0;
4518 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
4519 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
4520 + Integer.toHexString(mHistoryCur.states));
4521 addHistoryRecordLocked(elapsedRealtime, uptime);
4522 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
4523 for (int i=0; i<mUidStats.size(); i++) {
4524 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4525 uid.noteResetVideoLocked(elapsedRealtime);
4526 }
4527 }
4528 }
4529
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004530 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004531 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004532 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004533 }
4534
4535 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004536 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004537 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004538 }
4539
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004540 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004541 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004542 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
4543 }
4544
4545 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004546 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004547 getUidStatsLocked(uid).noteVibratorOffLocked();
4548 }
4549
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004550 public void noteFlashlightOnLocked(int uid) {
4551 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004552 final long elapsedRealtime = mClocks.elapsedRealtime();
4553 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004554 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004555 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
4556 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004557 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004558 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004559 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
4560 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004561 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
4562 }
4563
4564 public void noteFlashlightOffLocked(int uid) {
4565 if (mFlashlightOnNesting == 0) {
4566 return;
4567 }
4568 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004569 final long elapsedRealtime = mClocks.elapsedRealtime();
4570 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004571 if (--mFlashlightOnNesting == 0) {
4572 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
4573 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
4574 + Integer.toHexString(mHistoryCur.states2));
4575 addHistoryRecordLocked(elapsedRealtime, uptime);
4576 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
4577 }
4578 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
4579 }
4580
4581 public void noteCameraOnLocked(int uid) {
4582 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004583 final long elapsedRealtime = mClocks.elapsedRealtime();
4584 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004585 if (mCameraOnNesting++ == 0) {
4586 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
4587 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
4588 + Integer.toHexString(mHistoryCur.states2));
4589 addHistoryRecordLocked(elapsedRealtime, uptime);
4590 mCameraOnTimer.startRunningLocked(elapsedRealtime);
4591 }
4592 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
4593 }
4594
4595 public void noteCameraOffLocked(int uid) {
4596 if (mCameraOnNesting == 0) {
4597 return;
4598 }
4599 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004600 final long elapsedRealtime = mClocks.elapsedRealtime();
4601 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004602 if (--mCameraOnNesting == 0) {
4603 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
4604 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
4605 + Integer.toHexString(mHistoryCur.states2));
4606 addHistoryRecordLocked(elapsedRealtime, uptime);
4607 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
4608 }
4609 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
4610 }
4611
4612 public void noteResetCameraLocked() {
4613 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004614 final long elapsedRealtime = mClocks.elapsedRealtime();
4615 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004616 mCameraOnNesting = 0;
4617 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
4618 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
4619 + Integer.toHexString(mHistoryCur.states2));
4620 addHistoryRecordLocked(elapsedRealtime, uptime);
4621 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
4622 for (int i=0; i<mUidStats.size(); i++) {
4623 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4624 uid.noteResetCameraLocked(elapsedRealtime);
4625 }
4626 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004627 }
4628
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004629 public void noteResetFlashlightLocked() {
4630 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004631 final long elapsedRealtime = mClocks.elapsedRealtime();
4632 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004633 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004634 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
4635 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004636 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004637 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004638 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
4639 for (int i=0; i<mUidStats.size(); i++) {
4640 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4641 uid.noteResetFlashlightLocked(elapsedRealtime);
4642 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004643 }
4644 }
4645
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004646 private void noteBluetoothScanStartedLocked(int uid) {
4647 uid = mapUid(uid);
Bookatz867c0d72017-03-07 18:23:42 -08004648 final long elapsedRealtime = mClocks.elapsedRealtime();
4649 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004650 if (mBluetoothScanNesting == 0) {
4651 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
4652 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
4653 + Integer.toHexString(mHistoryCur.states2));
4654 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07004655 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004656 }
4657 mBluetoothScanNesting++;
4658 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime);
4659 }
4660
4661 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws) {
4662 final int N = ws.size();
4663 for (int i = 0; i < N; i++) {
4664 noteBluetoothScanStartedLocked(ws.get(i));
4665 }
4666 }
4667
4668 private void noteBluetoothScanStoppedLocked(int uid) {
4669 uid = mapUid(uid);
Bookatz867c0d72017-03-07 18:23:42 -08004670 final long elapsedRealtime = mClocks.elapsedRealtime();
4671 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004672 mBluetoothScanNesting--;
4673 if (mBluetoothScanNesting == 0) {
4674 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
4675 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
4676 + Integer.toHexString(mHistoryCur.states2));
4677 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07004678 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004679 }
4680 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime);
4681 }
4682
4683 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws) {
4684 final int N = ws.size();
4685 for (int i = 0; i < N; i++) {
4686 noteBluetoothScanStoppedLocked(ws.get(i));
4687 }
4688 }
4689
4690 public void noteResetBluetoothScanLocked() {
4691 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08004692 final long elapsedRealtime = mClocks.elapsedRealtime();
4693 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004694 mBluetoothScanNesting = 0;
4695 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
4696 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
4697 + Integer.toHexString(mHistoryCur.states2));
4698 addHistoryRecordLocked(elapsedRealtime, uptime);
4699 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
4700 for (int i=0; i<mUidStats.size(); i++) {
4701 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4702 uid.noteResetBluetoothScanLocked(elapsedRealtime);
4703 }
4704 }
4705 }
4706
Adam Lesinski5f056f62016-07-14 16:56:08 -07004707 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
4708 final long uptimeMillis, int uid) {
4709 uid = mapUid(uid);
4710 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4711 uid);
4712 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
4713 }
4714
4715 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004716 final long elapsedRealtime = mClocks.elapsedRealtime();
4717 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004718 if (mWifiRadioPowerState != powerState) {
4719 final boolean active =
4720 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4721 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4722 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004723 if (uid > 0) {
4724 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4725 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004726 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
4727 } else {
4728 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
4729 }
4730 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
4731 + Integer.toHexString(mHistoryCur.states));
4732 addHistoryRecordLocked(elapsedRealtime, uptime);
4733 mWifiRadioPowerState = powerState;
4734 }
4735 }
4736
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004737 public void noteWifiRunningLocked(WorkSource ws) {
4738 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08004739 final long elapsedRealtime = mClocks.elapsedRealtime();
4740 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07004741 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004742 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
4743 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004744 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004745 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004746 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004747 int N = ws.size();
4748 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004749 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004750 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004751 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004752 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004753 } else {
4754 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07004755 }
4756 }
4757
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004758 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
4759 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08004760 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004761 int N = oldWs.size();
4762 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004763 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004764 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004765 }
4766 N = newWs.size();
4767 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004768 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004769 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004770 }
4771 } else {
4772 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
4773 }
4774 }
4775
4776 public void noteWifiStoppedLocked(WorkSource ws) {
4777 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08004778 final long elapsedRealtime = mClocks.elapsedRealtime();
4779 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07004780 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004781 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
4782 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004783 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004784 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004785 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004786 int N = ws.size();
4787 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004788 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004789 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004790 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004791 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004792 } else {
4793 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07004794 }
4795 }
4796
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004797 public void noteWifiStateLocked(int wifiState, String accessPoint) {
4798 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
4799 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08004800 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004801 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004802 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004803 }
4804 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004805 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004806 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004807 }
4808 }
4809
Dianne Hackborn3251b902014-06-20 14:40:53 -07004810 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
4811 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
4812 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08004813 final long elapsedRealtime = mClocks.elapsedRealtime();
4814 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07004815 if (mWifiSupplState >= 0) {
4816 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
4817 }
4818 mWifiSupplState = supplState;
4819 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
4820 mHistoryCur.states2 =
4821 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
4822 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
4823 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
4824 + Integer.toHexString(mHistoryCur.states2));
4825 addHistoryRecordLocked(elapsedRealtime, uptime);
4826 }
4827 }
4828
4829 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08004830 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07004831 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
4832 if (i == except) {
4833 continue;
4834 }
4835 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
4836 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
4837 }
4838 }
4839 }
4840
4841 public void noteWifiRssiChangedLocked(int newRssi) {
4842 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
4843 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
4844 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004845 final long elapsedRealtime = mClocks.elapsedRealtime();
4846 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07004847 if (mWifiSignalStrengthBin >= 0) {
4848 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
4849 elapsedRealtime);
4850 }
4851 if (strengthBin >= 0) {
4852 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
4853 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
4854 }
4855 mHistoryCur.states2 =
4856 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
4857 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
4858 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
4859 + Integer.toHexString(mHistoryCur.states2));
4860 addHistoryRecordLocked(elapsedRealtime, uptime);
4861 } else {
4862 stopAllWifiSignalStrengthTimersLocked(-1);
4863 }
4864 mWifiSignalStrengthBin = strengthBin;
4865 }
4866 }
4867
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004868 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004869
The Android Open Source Project10592532009-03-18 17:39:46 -07004870 public void noteFullWifiLockAcquiredLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004871 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004872 final long elapsedRealtime = mClocks.elapsedRealtime();
4873 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004874 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004875 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004876 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
4877 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004878 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004879 }
4880 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004881 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004882 }
4883
4884 public void noteFullWifiLockReleasedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004885 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004886 final long elapsedRealtime = mClocks.elapsedRealtime();
4887 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004888 mWifiFullLockNesting--;
4889 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004890 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004891 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
4892 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004893 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004894 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004895 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004896 }
4897
Nick Pelly6ccaa542012-06-15 15:22:47 -07004898 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004899
Nick Pelly6ccaa542012-06-15 15:22:47 -07004900 public void noteWifiScanStartedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004901 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004902 final long elapsedRealtime = mClocks.elapsedRealtime();
4903 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07004904 if (mWifiScanNesting == 0) {
4905 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
4906 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004907 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004908 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004909 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07004910 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004911 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004912 }
4913
Nick Pelly6ccaa542012-06-15 15:22:47 -07004914 public void noteWifiScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004915 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004916 final long elapsedRealtime = mClocks.elapsedRealtime();
4917 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07004918 mWifiScanNesting--;
4919 if (mWifiScanNesting == 0) {
4920 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
4921 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004922 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004923 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004924 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004925 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004926 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07004927
Robert Greenwalta029ea12013-09-25 16:38:12 -07004928 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004929 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004930 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004931 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07004932 }
4933
4934 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004935 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004936 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004937 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07004938 }
4939
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004940 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004941
Robert Greenwalt5347bd42009-05-13 15:10:16 -07004942 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004943 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004944 final long elapsedRealtime = mClocks.elapsedRealtime();
4945 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004946 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004947 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004948 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
4949 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004950 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004951 }
4952 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004953 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07004954 }
4955
4956 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004957 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004958 final long elapsedRealtime = mClocks.elapsedRealtime();
4959 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004960 mWifiMulticastNesting--;
4961 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004962 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004963 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
4964 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004965 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004966 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004967 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07004968 }
4969
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004970 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
4971 int N = ws.size();
4972 for (int i=0; i<N; i++) {
4973 noteFullWifiLockAcquiredLocked(ws.get(i));
4974 }
4975 }
4976
4977 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
4978 int N = ws.size();
4979 for (int i=0; i<N; i++) {
4980 noteFullWifiLockReleasedLocked(ws.get(i));
4981 }
4982 }
4983
Nick Pelly6ccaa542012-06-15 15:22:47 -07004984 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004985 int N = ws.size();
4986 for (int i=0; i<N; i++) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07004987 noteWifiScanStartedLocked(ws.get(i));
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004988 }
4989 }
4990
Nick Pelly6ccaa542012-06-15 15:22:47 -07004991 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004992 int N = ws.size();
4993 for (int i=0; i<N; i++) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07004994 noteWifiScanStoppedLocked(ws.get(i));
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004995 }
4996 }
4997
Robert Greenwalta029ea12013-09-25 16:38:12 -07004998 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
4999 int N = ws.size();
5000 for (int i=0; i<N; i++) {
5001 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
5002 }
5003 }
5004
5005 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
5006 int N = ws.size();
5007 for (int i=0; i<N; i++) {
5008 noteWifiBatchedScanStoppedLocked(ws.get(i));
5009 }
5010 }
5011
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005012 public void noteWifiMulticastEnabledFromSourceLocked(WorkSource ws) {
5013 int N = ws.size();
5014 for (int i=0; i<N; i++) {
5015 noteWifiMulticastEnabledLocked(ws.get(i));
5016 }
5017 }
5018
5019 public void noteWifiMulticastDisabledFromSourceLocked(WorkSource ws) {
5020 int N = ws.size();
5021 for (int i=0; i<N; i++) {
5022 noteWifiMulticastDisabledLocked(ws.get(i));
5023 }
5024 }
5025
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08005026 private static String[] includeInStringArray(String[] array, String str) {
5027 if (ArrayUtils.indexOf(array, str) >= 0) {
5028 return array;
5029 }
5030 String[] newArray = new String[array.length+1];
5031 System.arraycopy(array, 0, newArray, 0, array.length);
5032 newArray[array.length] = str;
5033 return newArray;
5034 }
5035
5036 private static String[] excludeFromStringArray(String[] array, String str) {
5037 int index = ArrayUtils.indexOf(array, str);
5038 if (index >= 0) {
5039 String[] newArray = new String[array.length-1];
5040 if (index > 0) {
5041 System.arraycopy(array, 0, newArray, 0, index);
5042 }
5043 if (index < array.length-1) {
5044 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
5045 }
5046 return newArray;
5047 }
5048 return array;
5049 }
5050
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07005051 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07005052 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07005053 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08005054 mMobileIfaces = includeInStringArray(mMobileIfaces, iface);
5055 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mMobileIfaces);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07005056 } else {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08005057 mMobileIfaces = excludeFromStringArray(mMobileIfaces, iface);
5058 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mMobileIfaces);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07005059 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005060 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08005061 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
5062 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005063 } else {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08005064 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
5065 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005066 }
5067 }
5068
5069 public void noteNetworkStatsEnabledLocked() {
5070 // During device boot, qtaguid isn't enabled until after the inital
5071 // loading of battery stats. Now that they're enabled, take our initial
5072 // snapshot for future delta calculation.
Joe Onoratoabded112016-02-08 16:49:39 -08005073 updateMobileRadioStateLocked(mClocks.elapsedRealtime(), null);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07005074 updateWifiStateLocked(null);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07005075 }
5076
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005077 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
5078 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005079 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005080
Dianne Hackborn77b987f2014-02-26 16:20:52 -08005081 @Override public int getScreenOnCount(int which) {
5082 return mScreenOnTimer.getCountLocked(which);
5083 }
5084
Dianne Hackborn617f8772009-03-31 15:04:46 -07005085 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005086 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005087 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005088 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005089 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005090
Jeff Browne95c3cd2014-05-02 16:59:26 -07005091 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
5092 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005093 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005094
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005095 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
5096 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005097 }
5098
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005099 @Override public int getPowerSaveModeEnabledCount(int which) {
5100 return mPowerSaveModeEnabledTimer.getCountLocked(which);
5101 }
5102
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005103 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
5104 int which) {
5105 switch (mode) {
5106 case DEVICE_IDLE_MODE_LIGHT:
5107 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005108 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005109 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5110 }
5111 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005112 }
5113
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005114 @Override public int getDeviceIdleModeCount(int mode, int which) {
5115 switch (mode) {
5116 case DEVICE_IDLE_MODE_LIGHT:
5117 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005118 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005119 return mDeviceIdleModeFullTimer.getCountLocked(which);
5120 }
5121 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005122 }
5123
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005124 @Override public long getLongestDeviceIdleModeTime(int mode) {
5125 switch (mode) {
5126 case DEVICE_IDLE_MODE_LIGHT:
5127 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005128 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005129 return mLongestFullIdleTime;
5130 }
5131 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005132 }
5133
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005134 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
5135 switch (mode) {
5136 case DEVICE_IDLE_MODE_LIGHT:
5137 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005138 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005139 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5140 }
5141 return 0;
5142 }
5143
5144 @Override public int getDeviceIdlingCount(int mode, int which) {
5145 switch (mode) {
5146 case DEVICE_IDLE_MODE_LIGHT:
5147 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005148 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005149 return mDeviceIdlingTimer.getCountLocked(which);
5150 }
5151 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005152 }
5153
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005154 @Override public int getNumConnectivityChange(int which) {
5155 int val = mNumConnectivityChange;
5156 if (which == STATS_CURRENT) {
5157 val -= mLoadedNumConnectivityChange;
5158 } else if (which == STATS_SINCE_UNPLUGGED) {
5159 val -= mUnpluggedNumConnectivityChange;
5160 }
5161 return val;
5162 }
5163
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005164 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
5165 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005166 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005167
Dianne Hackborn77b987f2014-02-26 16:20:52 -08005168 @Override public int getPhoneOnCount(int which) {
5169 return mPhoneOnTimer.getCountLocked(which);
5170 }
5171
Dianne Hackborn627bba72009-03-24 22:32:56 -07005172 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005173 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005174 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005175 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005176 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07005177
5178 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005179 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07005180 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005181 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005182 }
5183
Catherine Liufb900812012-07-17 14:12:56 -05005184 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
5185 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005186 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005187
Dianne Hackborn627bba72009-03-24 22:32:56 -07005188 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005189 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005190 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005191 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005192 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005193
Dianne Hackborn617f8772009-03-31 15:04:46 -07005194 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005195 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005196 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005197
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005198 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
5199 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005200 }
5201
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005202 @Override public int getMobileRadioActiveCount(int which) {
5203 return mMobileRadioActiveTimer.getCountLocked(which);
5204 }
5205
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005206 @Override public long getMobileRadioActiveAdjustedTime(int which) {
5207 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
5208 }
5209
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005210 @Override public long getMobileRadioActiveUnknownTime(int which) {
5211 return mMobileRadioActiveUnknownTime.getCountLocked(which);
5212 }
5213
5214 @Override public int getMobileRadioActiveUnknownCount(int which) {
5215 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
5216 }
5217
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005218 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
5219 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07005220 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005221
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005222 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
5223 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005224 }
5225
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005226 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005227 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005228 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005229 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005230 }
5231
5232 @Override public int getWifiStateCount(int wifiState, int which) {
5233 return mWifiStateTimer[wifiState].getCountLocked(which);
5234 }
5235
Dianne Hackborn3251b902014-06-20 14:40:53 -07005236 @Override public long getWifiSupplStateTime(int state,
5237 long elapsedRealtimeUs, int which) {
5238 return mWifiSupplStateTimer[state].getTotalTimeLocked(
5239 elapsedRealtimeUs, which);
5240 }
5241
5242 @Override public int getWifiSupplStateCount(int state, int which) {
5243 return mWifiSupplStateTimer[state].getCountLocked(which);
5244 }
5245
5246 @Override public long getWifiSignalStrengthTime(int strengthBin,
5247 long elapsedRealtimeUs, int which) {
5248 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
5249 elapsedRealtimeUs, which);
5250 }
5251
5252 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
5253 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
5254 }
5255
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005256 @Override
5257 public ControllerActivityCounter getBluetoothControllerActivity() {
5258 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07005259 }
5260
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005261 @Override
5262 public ControllerActivityCounter getWifiControllerActivity() {
5263 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07005264 }
5265
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005266 @Override
5267 public ControllerActivityCounter getModemControllerActivity() {
5268 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07005269 }
5270
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005271 @Override
5272 public boolean hasBluetoothActivityReporting() {
5273 return mHasBluetoothReporting;
5274 }
5275
5276 @Override
5277 public boolean hasWifiActivityReporting() {
5278 return mHasWifiReporting;
5279 }
5280
5281 @Override
5282 public boolean hasModemActivityReporting() {
5283 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07005284 }
5285
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005286 @Override
5287 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005288 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5289 }
5290
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005291 @Override
5292 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005293 return mFlashlightOnTimer.getCountLocked(which);
5294 }
5295
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005296 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005297 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
5298 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5299 }
5300
5301 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005302 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
5303 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5304 }
5305
5306 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08005307 public long getNetworkActivityBytes(int type, int which) {
5308 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
5309 return mNetworkByteActivityCounters[type].getCountLocked(which);
5310 } else {
5311 return 0;
5312 }
5313 }
5314
5315 @Override
5316 public long getNetworkActivityPackets(int type, int which) {
5317 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
5318 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005319 } else {
5320 return 0;
5321 }
5322 }
5323
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08005324 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07005325 final long currentTime = System.currentTimeMillis();
5326 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08005327 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
5328 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07005329 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08005330 return mStartClockTime;
5331 }
5332
Dianne Hackborncd0e3352014-08-07 17:08:09 -07005333 @Override public String getStartPlatformVersion() {
5334 return mStartPlatformVersion;
5335 }
5336
5337 @Override public String getEndPlatformVersion() {
5338 return mEndPlatformVersion;
5339 }
5340
5341 @Override public int getParcelVersion() {
5342 return VERSION;
5343 }
5344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 @Override public boolean getIsOnBattery() {
5346 return mOnBattery;
5347 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
5350 return mUidStats;
5351 }
5352
Adam Lesinski5f056f62016-07-14 16:56:08 -07005353 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
5354 if (timer != null) {
5355 timer.detach();
5356 }
5357 }
5358
5359 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
5360 boolean detachIfReset) {
5361 if (timer != null) {
5362 return timer.reset(detachIfReset);
5363 }
5364 return true;
5365 }
5366
Bookatz867c0d72017-03-07 18:23:42 -08005367 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
5368 if (timer != null) {
5369 return timer.reset(detachIfReset);
5370 }
5371 return true;
5372 }
5373
Adam Lesinski5f056f62016-07-14 16:56:08 -07005374 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
5375 if (counter != null) {
5376 counter.detach();
5377 }
5378 }
5379
5380 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
5381 boolean detachIfReset) {
5382 if (counter != null) {
5383 counter.reset(detachIfReset);
5384 }
5385 }
5386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 /**
5388 * The statistics associated with a particular uid.
5389 */
Joe Onoratoabded112016-02-08 16:49:39 -08005390 public static class Uid extends BatteryStats.Uid {
5391 /**
5392 * BatteryStatsImpl that we are associated with.
5393 */
5394 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005396 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005397
Bookatz867c0d72017-03-07 18:23:42 -08005398 /** TimeBase for when uid is in background and device is on battery. */
5399 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
5400 public final TimeBase mOnBatteryBackgroundTimeBase;
5401
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005402 boolean mWifiRunning;
5403 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005404
The Android Open Source Project10592532009-03-18 17:39:46 -07005405 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07005406 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005407
Nick Pelly6ccaa542012-06-15 15:22:47 -07005408 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08005409 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005410
Dianne Hackborn61659e52014-07-09 16:13:01 -07005411 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07005412 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
5413 StopwatchTimer[] mWifiBatchedScanTimer;
5414
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005415 boolean mWifiMulticastEnabled;
5416 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005417
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005418 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005419 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005420 StopwatchTimer mFlashlightTurnedOnTimer;
5421 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005422 StopwatchTimer mForegroundActivityTimer;
Bookatz867c0d72017-03-07 18:23:42 -08005423 DualTimer mBluetoothScanTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005424
Dianne Hackborna8d10942015-11-19 17:55:19 -08005425 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07005426 StopwatchTimer[] mProcessStateTimer;
5427
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005428 BatchTimer mVibratorOnTimer;
5429
Dianne Hackborn617f8772009-03-31 15:04:46 -07005430 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005431
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08005432 LongSamplingCounter[] mNetworkByteActivityCounters;
5433 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005434 LongSamplingCounter mMobileRadioActiveTime;
5435 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005437 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07005438 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
5439 */
5440 private LongSamplingCounter mMobileRadioApWakeupCount;
5441
5442 /**
5443 * How many times this UID woke up the Application Processor due to a Wifi packet.
5444 */
5445 private LongSamplingCounter mWifiRadioApWakeupCount;
5446
5447 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07005448 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005449 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07005450 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005451 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07005452
5453 /**
5454 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005455 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07005456 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005457 private ControllerActivityCounterImpl mBluetoothControllerActivity;
5458
5459 /**
5460 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
5461 * Can be null if the UID has had no such activity.
5462 */
5463 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07005464
5465 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08005466 * The CPU times we had at the last history details update.
5467 */
5468 long mLastStepUserTime;
5469 long mLastStepSystemTime;
5470 long mCurStepUserTime;
5471 long mCurStepSystemTime;
5472
Joe Onoratoabded112016-02-08 16:49:39 -08005473 LongSamplingCounter mUserCpuTime;
5474 LongSamplingCounter mSystemCpuTime;
5475 LongSamplingCounter mCpuPower;
Adam Lesinski6832f392015-09-05 18:05:40 -07005476 LongSamplingCounter[][] mCpuClusterSpeed;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07005477
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08005478 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 * The statistics we have collected for this uid's wake locks.
5480 */
Joe Onoratoabded112016-02-08 16:49:39 -08005481 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005482
5483 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005484 * The statistics we have collected for this uid's syncs.
5485 */
Joe Onoratoabded112016-02-08 16:49:39 -08005486 final OverflowArrayMap<StopwatchTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005487
5488 /**
5489 * The statistics we have collected for this uid's jobs.
5490 */
Joe Onoratoabded112016-02-08 16:49:39 -08005491 final OverflowArrayMap<StopwatchTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005492
5493 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494 * The statistics we have collected for this uid's sensor activations.
5495 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005496 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497
5498 /**
5499 * The statistics we have collected for this uid's processes.
5500 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005501 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005502
5503 /**
5504 * The statistics we have collected for this uid's processes.
5505 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005506 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005507
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005508 /**
5509 * The transient wake stats we have collected for this uid's pids.
5510 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005511 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005512
Joe Onoratoabded112016-02-08 16:49:39 -08005513 public Uid(BatteryStatsImpl bsi, int uid) {
5514 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08005516
Bookatz867c0d72017-03-07 18:23:42 -08005517 mOnBatteryBackgroundTimeBase = new TimeBase();
5518 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
5519 mBsi.mClocks.elapsedRealtime() * 1000);
5520
Joe Onoratoabded112016-02-08 16:49:39 -08005521 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
5522 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
5523 mCpuPower = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
5524
Dianne Hackborn657153b2016-07-29 14:54:14 -07005525 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005526 @Override public Wakelock instantiateObject() {
5527 return new Wakelock(mBsi, Uid.this);
5528 }
5529 };
Dianne Hackborn657153b2016-07-29 14:54:14 -07005530 mSyncStats = mBsi.new OverflowArrayMap<StopwatchTimer>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005531 @Override public StopwatchTimer instantiateObject() {
5532 return new StopwatchTimer(mBsi.mClocks, Uid.this, SYNC, null,
5533 mBsi.mOnBatteryTimeBase);
5534 }
5535 };
Dianne Hackborn657153b2016-07-29 14:54:14 -07005536 mJobStats = mBsi.new OverflowArrayMap<StopwatchTimer>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005537 @Override public StopwatchTimer instantiateObject() {
5538 return new StopwatchTimer(mBsi.mClocks, Uid.this, JOB, null,
5539 mBsi.mOnBatteryTimeBase);
5540 }
5541 };
5542
5543 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
5544 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
5545 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
5546 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08005547 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
5548 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005549 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08005550 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
5551 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07005552 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 }
5554
5555 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005556 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07005557 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 }
5559
5560 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005561 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07005562 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005563 }
5564
5565 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005566 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07005567 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005568 }
5569
5570 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07005571 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 return mSensorStats;
5573 }
5574
5575 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005576 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 return mProcessStats;
5578 }
5579
5580 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005581 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 return mPackageStats;
5583 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07005584
5585 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 public int getUid() {
5587 return mUid;
5588 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07005589
5590 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005591 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005592 if (!mWifiRunning) {
5593 mWifiRunning = true;
5594 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005595 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
5596 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005597 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005598 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005599 }
5600 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005601
Dianne Hackborn617f8772009-03-31 15:04:46 -07005602 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005603 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005604 if (mWifiRunning) {
5605 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005606 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005607 }
5608 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005609
Dianne Hackborn617f8772009-03-31 15:04:46 -07005610 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005611 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005612 if (!mFullWifiLockOut) {
5613 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005614 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005615 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
5616 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005617 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005618 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005619 }
5620 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005621
The Android Open Source Project10592532009-03-18 17:39:46 -07005622 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005623 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005624 if (mFullWifiLockOut) {
5625 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005626 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005627 }
5628 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005629
The Android Open Source Project10592532009-03-18 17:39:46 -07005630 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005631 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005632 if (!mWifiScanStarted) {
5633 mWifiScanStarted = true;
5634 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08005635 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
5636 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
5637 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005638 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005639 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005640 }
5641 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005642
The Android Open Source Project10592532009-03-18 17:39:46 -07005643 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005644 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005645 if (mWifiScanStarted) {
5646 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005647 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005648 }
5649 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005650
5651 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005652 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07005653 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07005654 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07005655 csph = csph >> 3;
5656 bin++;
5657 }
5658
5659 if (mWifiBatchedScanBinStarted == bin) return;
5660
5661 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
5662 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005663 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005664 }
5665 mWifiBatchedScanBinStarted = bin;
5666 if (mWifiBatchedScanTimer[bin] == null) {
5667 makeWifiBatchedScanBin(bin, null);
5668 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005669 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005670 }
5671
5672 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005673 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07005674 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
5675 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005676 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005677 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
5678 }
5679 }
5680
5681 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005682 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005683 if (!mWifiMulticastEnabled) {
5684 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005685 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005686 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
5687 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005688 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005689 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005690 }
5691 }
5692
5693 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005694 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005695 if (mWifiMulticastEnabled) {
5696 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005697 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005698 }
5699 }
5700
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005701 @Override
5702 public ControllerActivityCounter getWifiControllerActivity() {
5703 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07005704 }
5705
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005706 @Override
5707 public ControllerActivityCounter getBluetoothControllerActivity() {
5708 return mBluetoothControllerActivity;
5709 }
5710
5711 @Override
5712 public ControllerActivityCounter getModemControllerActivity() {
5713 return mModemControllerActivity;
5714 }
5715
5716 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
5717 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005718 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005719 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08005720 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005721 return mWifiControllerActivity;
5722 }
5723
5724 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
5725 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005726 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005727 NUM_BT_TX_LEVELS);
5728 }
5729 return mBluetoothControllerActivity;
5730 }
5731
5732 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
5733 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005734 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005735 ModemActivityInfo.TX_POWER_LEVELS);
5736 }
5737 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08005738 }
5739
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005740 public StopwatchTimer createAudioTurnedOnTimerLocked() {
5741 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005742 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
5743 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005744 }
5745 return mAudioTurnedOnTimer;
5746 }
5747
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005748 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005749 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
5750 }
5751
5752 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
5753 if (mAudioTurnedOnTimer != null) {
5754 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005755 }
5756 }
5757
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005758 public void noteResetAudioLocked(long elapsedRealtimeMs) {
5759 if (mAudioTurnedOnTimer != null) {
5760 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005761 }
5762 }
5763
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005764 public StopwatchTimer createVideoTurnedOnTimerLocked() {
5765 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005766 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
5767 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005768 }
5769 return mVideoTurnedOnTimer;
5770 }
5771
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005772 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005773 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
5774 }
5775
5776 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
5777 if (mVideoTurnedOnTimer != null) {
5778 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005779 }
5780 }
5781
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005782 public void noteResetVideoLocked(long elapsedRealtimeMs) {
5783 if (mVideoTurnedOnTimer != null) {
5784 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005785 }
5786 }
5787
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005788 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
5789 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005790 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
5791 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005792 }
5793 return mFlashlightTurnedOnTimer;
5794 }
5795
5796 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
5797 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
5798 }
5799
5800 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
5801 if (mFlashlightTurnedOnTimer != null) {
5802 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
5803 }
5804 }
5805
5806 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
5807 if (mFlashlightTurnedOnTimer != null) {
5808 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
5809 }
5810 }
5811
5812 public StopwatchTimer createCameraTurnedOnTimerLocked() {
5813 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005814 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
5815 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005816 }
5817 return mCameraTurnedOnTimer;
5818 }
5819
5820 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
5821 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
5822 }
5823
5824 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
5825 if (mCameraTurnedOnTimer != null) {
5826 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
5827 }
5828 }
5829
5830 public void noteResetCameraLocked(long elapsedRealtimeMs) {
5831 if (mCameraTurnedOnTimer != null) {
5832 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
5833 }
5834 }
5835
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005836 public StopwatchTimer createForegroundActivityTimerLocked() {
5837 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005838 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
5839 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005840 }
5841 return mForegroundActivityTimer;
5842 }
5843
Bookatz867c0d72017-03-07 18:23:42 -08005844 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005845 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08005846 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
5847 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
5848 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005849 }
5850 return mBluetoothScanTimer;
5851 }
5852
5853 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs) {
5854 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
5855 }
5856
5857 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs) {
5858 if (mBluetoothScanTimer != null) {
5859 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
5860 }
5861 }
5862
5863 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
5864 if (mBluetoothScanTimer != null) {
5865 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
5866 }
5867 }
5868
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005869 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005870 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005871 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005872 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005873 }
5874
5875 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005876 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005877 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005878 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005879 }
5880 }
5881
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005882 public BatchTimer createVibratorOnTimerLocked() {
5883 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005884 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
5885 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005886 }
5887 return mVibratorOnTimer;
5888 }
5889
5890 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08005891 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005892 }
5893
5894 public void noteVibratorOffLocked() {
5895 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005896 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005897 }
5898 }
5899
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005900 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005901 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005902 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005903 return 0;
5904 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005905 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005906 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005907
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005908 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005909 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005910 if (mFullWifiLockTimer == null) {
5911 return 0;
5912 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005913 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07005914 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005915
5916 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005917 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005918 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005919 return 0;
5920 }
Bookatz867c0d72017-03-07 18:23:42 -08005921 return mWifiScanTimer.getMainTimer().getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07005922 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005923
5924 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07005925 public int getWifiScanCount(int which) {
5926 if (mWifiScanTimer == null) {
5927 return 0;
5928 }
Bookatz867c0d72017-03-07 18:23:42 -08005929 return mWifiScanTimer.getMainTimer().getCountLocked(which);
5930 }
5931
5932 @Override
5933 public int getWifiScanBackgroundCount(int which) {
5934 if (mWifiScanTimer == null) {
5935 return 0;
5936 }
5937 return mWifiScanTimer.getSubTimer().getCountLocked(which);
5938 }
5939
5940 @Override
5941 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
5942 if (mWifiScanTimer == null) {
5943 return 0;
5944 }
5945 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
5946 return mWifiScanTimer.getMainTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
5947 }
5948
5949 @Override
5950 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
5951 if (mWifiScanTimer == null) {
5952 return 0;
5953 }
5954 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
5955 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07005956 }
5957
5958 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005959 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07005960 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
5961 if (mWifiBatchedScanTimer[csphBin] == null) {
5962 return 0;
5963 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005964 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005965 }
5966
5967 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07005968 public int getWifiBatchedScanCount(int csphBin, int which) {
5969 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
5970 if (mWifiBatchedScanTimer[csphBin] == null) {
5971 return 0;
5972 }
5973 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
5974 }
5975
5976 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005977 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005978 if (mWifiMulticastTimer == null) {
5979 return 0;
5980 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005981 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005982 }
5983
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005984 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005985 public Timer getAudioTurnedOnTimer() {
5986 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005987 }
5988
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005989 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005990 public Timer getVideoTurnedOnTimer() {
5991 return mVideoTurnedOnTimer;
5992 }
5993
5994 @Override
5995 public Timer getFlashlightTurnedOnTimer() {
5996 return mFlashlightTurnedOnTimer;
5997 }
5998
5999 @Override
6000 public Timer getCameraTurnedOnTimer() {
6001 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006002 }
6003
Dianne Hackborn617f8772009-03-31 15:04:46 -07006004 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006005 public Timer getForegroundActivityTimer() {
6006 return mForegroundActivityTimer;
6007 }
6008
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006009 @Override
6010 public Timer getBluetoothScanTimer() {
Bookatz867c0d72017-03-07 18:23:42 -08006011 if (mBluetoothScanTimer == null) {
6012 return null;
6013 }
6014 return mBluetoothScanTimer.getMainTimer();
6015 }
6016
6017 @Override
6018 public Timer getBluetoothScanBackgroundTimer() {
6019 if (mBluetoothScanTimer == null) {
6020 return null;
6021 }
6022 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006023 }
6024
Dianne Hackborn61659e52014-07-09 16:13:01 -07006025 void makeProcessState(int i, Parcel in) {
6026 if (i < 0 || i >= NUM_PROCESS_STATE) return;
6027
6028 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006029 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
6030 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006031 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08006032 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
6033 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006034 }
6035 }
6036
6037 @Override
6038 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
6039 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
6040 if (mProcessStateTimer[state] == null) {
6041 return 0;
6042 }
6043 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
6044 }
6045
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006046 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08006047 public Timer getProcessStateTimer(int state) {
6048 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
6049 return mProcessStateTimer[state];
6050 }
6051
6052 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006053 public Timer getVibratorOnTimer() {
6054 return mVibratorOnTimer;
6055 }
6056
6057 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07006058 public void noteUserActivityLocked(int type) {
6059 if (mUserActivityCounters == null) {
6060 initUserActivityLocked();
6061 }
Jeff Browndf693de2012-07-27 12:03:38 -07006062 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
6063 mUserActivityCounters[type].stepAtomic();
6064 } else {
6065 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
6066 new Throwable());
6067 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07006068 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006069
Dianne Hackborn617f8772009-03-31 15:04:46 -07006070 @Override
6071 public boolean hasUserActivity() {
6072 return mUserActivityCounters != null;
6073 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006074
Dianne Hackborn617f8772009-03-31 15:04:46 -07006075 @Override
6076 public int getUserActivityCount(int type, int which) {
6077 if (mUserActivityCounters == null) {
6078 return 0;
6079 }
Evan Millarc64edde2009-04-18 12:26:32 -07006080 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006081 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006082
Robert Greenwalta029ea12013-09-25 16:38:12 -07006083 void makeWifiBatchedScanBin(int i, Parcel in) {
6084 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
6085
Joe Onoratoabded112016-02-08 16:49:39 -08006086 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006087 if (collected == null) {
6088 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08006089 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006090 }
6091 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006092 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
6093 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006094 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08006095 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
6096 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006097 }
6098 }
6099
6100
Dianne Hackborn617f8772009-03-31 15:04:46 -07006101 void initUserActivityLocked() {
6102 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
6103 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08006104 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006105 }
6106 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006107
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006108 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
6109 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006110 initNetworkActivityLocked();
6111 }
6112 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006113 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
6114 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006115 } else {
6116 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
6117 new Throwable());
6118 }
6119 }
6120
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006121 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
6122 if (mNetworkByteActivityCounters == null) {
6123 initNetworkActivityLocked();
6124 }
6125 mMobileRadioActiveTime.addCountLocked(batteryUptime);
6126 mMobileRadioActiveCount.addCountLocked(1);
6127 }
6128
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006129 @Override
6130 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006131 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006132 }
6133
6134 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006135 public long getNetworkActivityBytes(int type, int which) {
6136 if (mNetworkByteActivityCounters != null && type >= 0
6137 && type < mNetworkByteActivityCounters.length) {
6138 return mNetworkByteActivityCounters[type].getCountLocked(which);
6139 } else {
6140 return 0;
6141 }
6142 }
6143
6144 @Override
6145 public long getNetworkActivityPackets(int type, int which) {
6146 if (mNetworkPacketActivityCounters != null && type >= 0
6147 && type < mNetworkPacketActivityCounters.length) {
6148 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006149 } else {
6150 return 0;
6151 }
6152 }
6153
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006154 @Override
6155 public long getMobileRadioActiveTime(int which) {
6156 return mMobileRadioActiveTime != null
6157 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
6158 }
6159
6160 @Override
6161 public int getMobileRadioActiveCount(int which) {
6162 return mMobileRadioActiveCount != null
6163 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
6164 }
6165
Adam Lesinskie08af192015-03-25 16:42:59 -07006166 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006167 public long getUserCpuTimeUs(int which) {
6168 return mUserCpuTime.getCountLocked(which);
6169 }
6170
6171 @Override
6172 public long getSystemCpuTimeUs(int which) {
6173 return mSystemCpuTime.getCountLocked(which);
6174 }
6175
6176 @Override
Adam Lesinskia7a4ccc2015-06-26 17:43:04 -07006177 public long getCpuPowerMaUs(int which) {
6178 return mCpuPower.getCountLocked(which);
6179 }
6180
6181 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07006182 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
6183 if (mCpuClusterSpeed != null) {
6184 if (cluster >= 0 && cluster < mCpuClusterSpeed.length) {
6185 final LongSamplingCounter[] cpuSpeeds = mCpuClusterSpeed[cluster];
6186 if (cpuSpeeds != null) {
6187 if (step >= 0 && step < cpuSpeeds.length) {
6188 final LongSamplingCounter c = cpuSpeeds[step];
6189 if (c != null) {
6190 return c.getCountLocked(which);
6191 }
6192 }
6193 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006194 }
6195 }
6196 return 0;
6197 }
6198
Adam Lesinski5f056f62016-07-14 16:56:08 -07006199 public void noteMobileRadioApWakeupLocked() {
6200 if (mMobileRadioApWakeupCount == null) {
6201 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6202 }
6203 mMobileRadioApWakeupCount.addCountLocked(1);
6204 }
6205
6206 @Override
6207 public long getMobileRadioApWakeupCount(int which) {
6208 if (mMobileRadioApWakeupCount != null) {
6209 return mMobileRadioApWakeupCount.getCountLocked(which);
6210 }
6211 return 0;
6212 }
6213
6214 public void noteWifiRadioApWakeupLocked() {
6215 if (mWifiRadioApWakeupCount == null) {
6216 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6217 }
6218 mWifiRadioApWakeupCount.addCountLocked(1);
6219 }
6220
6221 @Override
6222 public long getWifiRadioApWakeupCount(int which) {
6223 if (mWifiRadioApWakeupCount != null) {
6224 return mWifiRadioApWakeupCount.getCountLocked(which);
6225 }
6226 return 0;
6227 }
6228
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006229 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006230 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
6231 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006232 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08006233 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6234 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006235 }
Joe Onoratoabded112016-02-08 16:49:39 -08006236 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6237 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006239
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006240 /**
6241 * Clear all stats for this uid. Returns true if the uid is completely
6242 * inactive so can be dropped.
6243 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07006244 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6245 public boolean reset() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006246 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006247
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006248 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006249 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006250 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006251 }
6252 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006253 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006254 active |= mFullWifiLockOut;
6255 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006256 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006257 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07006258 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006259 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006260 if (mWifiBatchedScanTimer != null) {
6261 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
6262 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006263 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006264 }
6265 }
6266 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
6267 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006268 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006269 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006270 active |= mWifiMulticastEnabled;
6271 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006272
6273 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
6274 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
6275 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
6276 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
6277 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
6278 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
6279
Dianne Hackborn61659e52014-07-09 16:13:01 -07006280 if (mProcessStateTimer != null) {
6281 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
6282 if (mProcessStateTimer[i] != null) {
6283 active |= !mProcessStateTimer[i].reset(false);
6284 }
6285 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08006286 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006287 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006288 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006289 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006290 mVibratorOnTimer.detach();
6291 mVibratorOnTimer = null;
6292 } else {
6293 active = true;
6294 }
6295 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006296
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006297 if (mUserActivityCounters != null) {
6298 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
6299 mUserActivityCounters[i].reset(false);
6300 }
6301 }
6302
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006303 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006304 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006305 mNetworkByteActivityCounters[i].reset(false);
6306 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006307 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006308 mMobileRadioActiveTime.reset(false);
6309 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006310 }
6311
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006312 if (mWifiControllerActivity != null) {
6313 mWifiControllerActivity.reset(false);
6314 }
Adam Lesinskie08af192015-03-25 16:42:59 -07006315
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07006316 if (mBluetoothControllerActivity != null) {
6317 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006318 }
6319
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07006320 if (mModemControllerActivity != null) {
6321 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07006322 }
6323
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006324 mUserCpuTime.reset(false);
6325 mSystemCpuTime.reset(false);
Adam Lesinskia7a4ccc2015-06-26 17:43:04 -07006326 mCpuPower.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07006327
6328 if (mCpuClusterSpeed != null) {
6329 for (LongSamplingCounter[] speeds : mCpuClusterSpeed) {
6330 if (speeds != null) {
6331 for (LongSamplingCounter speed : speeds) {
6332 if (speed != null) {
6333 speed.reset(false);
6334 }
6335 }
6336 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006337 }
6338 }
6339
Adam Lesinski5f056f62016-07-14 16:56:08 -07006340 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
6341 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
6342
Dianne Hackbornd953c532014-08-16 18:17:38 -07006343 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
6344 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
6345 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006346 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006347 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006348 } else {
6349 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006350 }
6351 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006352 mWakelockStats.cleanup();
6353 final ArrayMap<String, StopwatchTimer> syncStats = mSyncStats.getMap();
6354 for (int is=syncStats.size()-1; is>=0; is--) {
6355 StopwatchTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006356 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006357 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006358 timer.detach();
6359 } else {
6360 active = true;
6361 }
6362 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006363 mSyncStats.cleanup();
6364 final ArrayMap<String, StopwatchTimer> jobStats = mJobStats.getMap();
6365 for (int ij=jobStats.size()-1; ij>=0; ij--) {
6366 StopwatchTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006367 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006368 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006369 timer.detach();
6370 } else {
6371 active = true;
6372 }
6373 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006374 mJobStats.cleanup();
Dianne Hackborn61659e52014-07-09 16:13:01 -07006375 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
6376 Sensor s = mSensorStats.valueAt(ise);
6377 if (s.reset()) {
6378 mSensorStats.removeAt(ise);
6379 } else {
6380 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006381 }
6382 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07006383 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
6384 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08006385 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006386 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08006387 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006388 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006389 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006390 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006391 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006392 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006393 } else {
6394 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006395 }
6396 }
6397 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006398 if (mPackageStats.size() > 0) {
6399 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
6400 while (it.hasNext()) {
6401 Map.Entry<String, Pkg> pkgEntry = it.next();
6402 Pkg p = pkgEntry.getValue();
6403 p.detach();
6404 if (p.mServiceStats.size() > 0) {
6405 Iterator<Map.Entry<String, Pkg.Serv>> it2
6406 = p.mServiceStats.entrySet().iterator();
6407 while (it2.hasNext()) {
6408 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
6409 servEntry.getValue().detach();
6410 }
6411 }
6412 }
6413 mPackageStats.clear();
6414 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006415
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006416 mLastStepUserTime = mLastStepSystemTime = 0;
6417 mCurStepUserTime = mCurStepSystemTime = 0;
6418
Bookatz867c0d72017-03-07 18:23:42 -08006419 mOnBatteryBackgroundTimeBase.reset(mBsi.mClocks.elapsedRealtime() * 1000,
6420 mBsi.mClocks.uptimeMillis() * 1000);
6421
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006422 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006423 if (mWifiRunningTimer != null) {
6424 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006425 }
6426 if (mFullWifiLockTimer != null) {
6427 mFullWifiLockTimer.detach();
6428 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006429 if (mWifiScanTimer != null) {
6430 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006431 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006432 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
6433 if (mWifiBatchedScanTimer[i] != null) {
6434 mWifiBatchedScanTimer[i].detach();
6435 }
6436 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006437 if (mWifiMulticastTimer != null) {
6438 mWifiMulticastTimer.detach();
6439 }
6440 if (mAudioTurnedOnTimer != null) {
6441 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006442 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006443 }
6444 if (mVideoTurnedOnTimer != null) {
6445 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006446 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006447 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006448 if (mFlashlightTurnedOnTimer != null) {
6449 mFlashlightTurnedOnTimer.detach();
6450 mFlashlightTurnedOnTimer = null;
6451 }
6452 if (mCameraTurnedOnTimer != null) {
6453 mCameraTurnedOnTimer.detach();
6454 mCameraTurnedOnTimer = null;
6455 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006456 if (mForegroundActivityTimer != null) {
6457 mForegroundActivityTimer.detach();
6458 mForegroundActivityTimer = null;
6459 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006460 if (mBluetoothScanTimer != null) {
6461 mBluetoothScanTimer.detach();
6462 mBluetoothScanTimer = null;
6463 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006464 if (mUserActivityCounters != null) {
6465 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
6466 mUserActivityCounters[i].detach();
6467 }
6468 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006469 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006470 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006471 mNetworkByteActivityCounters[i].detach();
6472 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006473 }
6474 }
Adam Lesinskie08af192015-03-25 16:42:59 -07006475
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006476 if (mWifiControllerActivity != null) {
6477 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07006478 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006479
6480 if (mBluetoothControllerActivity != null) {
6481 mBluetoothControllerActivity.detach();
6482 }
6483
6484 if (mModemControllerActivity != null) {
6485 mModemControllerActivity.detach();
6486 }
6487
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006488 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006489
6490 mUserCpuTime.detach();
6491 mSystemCpuTime.detach();
Adam Lesinskia7a4ccc2015-06-26 17:43:04 -07006492 mCpuPower.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07006493
6494 if (mCpuClusterSpeed != null) {
6495 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeed) {
6496 if (cpuSpeeds != null) {
6497 for (LongSamplingCounter c : cpuSpeeds) {
6498 if (c != null) {
6499 c.detach();
6500 }
6501 }
6502 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006503 }
6504 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006505
6506 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
6507 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006508 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006509
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006510 return !active;
6511 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006512
Bookatz867c0d72017-03-07 18:23:42 -08006513 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
6514 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
6515
Dianne Hackbornd953c532014-08-16 18:17:38 -07006516 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
6517 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07006518 out.writeInt(NW);
6519 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006520 out.writeString(wakeStats.keyAt(iw));
6521 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006522 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 }
6524
Dianne Hackbornd953c532014-08-16 18:17:38 -07006525 final ArrayMap<String, StopwatchTimer> syncStats = mSyncStats.getMap();
6526 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006527 out.writeInt(NS);
6528 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006529 out.writeString(syncStats.keyAt(is));
6530 StopwatchTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006531 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
6532 }
6533
Dianne Hackbornd953c532014-08-16 18:17:38 -07006534 final ArrayMap<String, StopwatchTimer> jobStats = mJobStats.getMap();
6535 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006536 out.writeInt(NJ);
6537 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006538 out.writeString(jobStats.keyAt(ij));
6539 StopwatchTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006540 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
6541 }
6542
Dianne Hackborn61659e52014-07-09 16:13:01 -07006543 int NSE = mSensorStats.size();
6544 out.writeInt(NSE);
6545 for (int ise=0; ise<NSE; ise++) {
6546 out.writeInt(mSensorStats.keyAt(ise));
6547 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006548 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 }
6550
Dianne Hackborn61659e52014-07-09 16:13:01 -07006551 int NP = mProcessStats.size();
6552 out.writeInt(NP);
6553 for (int ip=0; ip<NP; ip++) {
6554 out.writeString(mProcessStats.keyAt(ip));
6555 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006556 proc.writeToParcelLocked(out);
6557 }
6558
6559 out.writeInt(mPackageStats.size());
6560 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
6561 out.writeString(pkgEntry.getKey());
6562 Uid.Pkg pkg = pkgEntry.getValue();
6563 pkg.writeToParcelLocked(out);
6564 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006565
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006566 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006567 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006568 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006569 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006570 out.writeInt(0);
6571 }
6572 if (mFullWifiLockTimer != null) {
6573 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006574 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006575 } else {
6576 out.writeInt(0);
6577 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006578 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006579 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006580 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006581 } else {
6582 out.writeInt(0);
6583 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006584 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
6585 if (mWifiBatchedScanTimer[i] != null) {
6586 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006587 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006588 } else {
6589 out.writeInt(0);
6590 }
6591 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006592 if (mWifiMulticastTimer != null) {
6593 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006594 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006595 } else {
6596 out.writeInt(0);
6597 }
Adam Lesinskie08af192015-03-25 16:42:59 -07006598
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006599 if (mAudioTurnedOnTimer != null) {
6600 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006601 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006602 } else {
6603 out.writeInt(0);
6604 }
6605 if (mVideoTurnedOnTimer != null) {
6606 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006607 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006608 } else {
6609 out.writeInt(0);
6610 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006611 if (mFlashlightTurnedOnTimer != null) {
6612 out.writeInt(1);
6613 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
6614 } else {
6615 out.writeInt(0);
6616 }
6617 if (mCameraTurnedOnTimer != null) {
6618 out.writeInt(1);
6619 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
6620 } else {
6621 out.writeInt(0);
6622 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006623 if (mForegroundActivityTimer != null) {
6624 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006625 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006626 } else {
6627 out.writeInt(0);
6628 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006629 if (mBluetoothScanTimer != null) {
6630 out.writeInt(1);
6631 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
6632 } else {
6633 out.writeInt(0);
6634 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07006635 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
6636 if (mProcessStateTimer[i] != null) {
6637 out.writeInt(1);
6638 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
6639 } else {
6640 out.writeInt(0);
6641 }
6642 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006643 if (mVibratorOnTimer != null) {
6644 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006645 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006646 } else {
6647 out.writeInt(0);
6648 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006649 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07006650 out.writeInt(1);
6651 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
6652 mUserActivityCounters[i].writeToParcel(out);
6653 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006654 } else {
6655 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006656 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006657 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006658 out.writeInt(1);
6659 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006660 mNetworkByteActivityCounters[i].writeToParcel(out);
6661 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006662 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006663 mMobileRadioActiveTime.writeToParcel(out);
6664 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006665 } else {
6666 out.writeInt(0);
6667 }
Adam Lesinskie08af192015-03-25 16:42:59 -07006668
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006669 if (mWifiControllerActivity != null) {
6670 out.writeInt(1);
6671 mWifiControllerActivity.writeToParcel(out, 0);
6672 } else {
6673 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07006674 }
6675
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006676 if (mBluetoothControllerActivity != null) {
6677 out.writeInt(1);
6678 mBluetoothControllerActivity.writeToParcel(out, 0);
6679 } else {
6680 out.writeInt(0);
6681 }
6682
6683 if (mModemControllerActivity != null) {
6684 out.writeInt(1);
6685 mModemControllerActivity.writeToParcel(out, 0);
6686 } else {
6687 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07006688 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006689
6690 mUserCpuTime.writeToParcel(out);
6691 mSystemCpuTime.writeToParcel(out);
Adam Lesinskia7a4ccc2015-06-26 17:43:04 -07006692 mCpuPower.writeToParcel(out);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006693
Adam Lesinski6832f392015-09-05 18:05:40 -07006694 if (mCpuClusterSpeed != null) {
6695 out.writeInt(1);
6696 out.writeInt(mCpuClusterSpeed.length);
6697 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeed) {
6698 if (cpuSpeeds != null) {
6699 out.writeInt(1);
6700 out.writeInt(cpuSpeeds.length);
6701 for (LongSamplingCounter c : cpuSpeeds) {
6702 if (c != null) {
6703 out.writeInt(1);
6704 c.writeToParcel(out);
6705 } else {
6706 out.writeInt(0);
6707 }
6708 }
6709 } else {
6710 out.writeInt(0);
6711 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006712 }
Adam Lesinski6832f392015-09-05 18:05:40 -07006713 } else {
6714 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006715 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006716
6717 if (mMobileRadioApWakeupCount != null) {
6718 out.writeInt(1);
6719 mMobileRadioApWakeupCount.writeToParcel(out);
6720 } else {
6721 out.writeInt(0);
6722 }
6723
6724 if (mWifiRadioApWakeupCount != null) {
6725 out.writeInt(1);
6726 mWifiRadioApWakeupCount.writeToParcel(out);
6727 } else {
6728 out.writeInt(0);
6729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 }
6731
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006732 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08006733 mOnBatteryBackgroundTimeBase.readFromParcel(in);
6734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 int numWakelocks = in.readInt();
6736 mWakelockStats.clear();
6737 for (int j = 0; j < numWakelocks; j++) {
6738 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08006739 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006740 wakelock.readFromParcelLocked(timeBase, screenOffTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07006741 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006742 }
6743
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006744 int numSyncs = in.readInt();
6745 mSyncStats.clear();
6746 for (int j = 0; j < numSyncs; j++) {
6747 String syncName = in.readString();
6748 if (in.readInt() != 0) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006749 mSyncStats.add(syncName,
Joe Onoratoabded112016-02-08 16:49:39 -08006750 new StopwatchTimer(mBsi.mClocks, Uid.this, SYNC, null, timeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006751 }
6752 }
6753
6754 int numJobs = in.readInt();
6755 mJobStats.clear();
6756 for (int j = 0; j < numJobs; j++) {
6757 String jobName = in.readString();
6758 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006759 mJobStats.add(jobName, new StopwatchTimer(mBsi.mClocks, Uid.this, JOB, null,
6760 timeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006761 }
6762 }
6763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 int numSensors = in.readInt();
6765 mSensorStats.clear();
6766 for (int k = 0; k < numSensors; k++) {
6767 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08006768 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08006769 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
6770 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 mSensorStats.put(sensorNumber, sensor);
6772 }
6773
6774 int numProcs = in.readInt();
6775 mProcessStats.clear();
6776 for (int k = 0; k < numProcs; k++) {
6777 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08006778 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 proc.readFromParcelLocked(in);
6780 mProcessStats.put(processName, proc);
6781 }
6782
6783 int numPkgs = in.readInt();
6784 mPackageStats.clear();
6785 for (int l = 0; l < numPkgs; l++) {
6786 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08006787 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006788 pkg.readFromParcelLocked(in);
6789 mPackageStats.put(packageName, pkg);
6790 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006791
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006792 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006793 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006794 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
6795 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006796 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006797 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006798 }
6799 mFullWifiLockOut = false;
6800 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006801 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
6802 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006803 } else {
6804 mFullWifiLockTimer = null;
6805 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006806 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006807 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08006808 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
6809 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
6810 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006811 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006812 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006813 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006814 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6815 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
6816 if (in.readInt() != 0) {
6817 makeWifiBatchedScanBin(i, in);
6818 } else {
6819 mWifiBatchedScanTimer[i] = null;
6820 }
6821 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006822 mWifiMulticastEnabled = false;
6823 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006824 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
6825 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006826 } else {
6827 mWifiMulticastTimer = null;
6828 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006829 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006830 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
6831 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006832 } else {
6833 mAudioTurnedOnTimer = null;
6834 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006835 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006836 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
6837 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006838 } else {
6839 mVideoTurnedOnTimer = null;
6840 }
6841 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006842 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6843 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006844 } else {
6845 mFlashlightTurnedOnTimer = null;
6846 }
6847 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006848 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
6849 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006850 } else {
6851 mCameraTurnedOnTimer = null;
6852 }
6853 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006854 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6855 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006856 } else {
6857 mForegroundActivityTimer = null;
6858 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006859 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08006860 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
6861 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
6862 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006863 } else {
6864 mBluetoothScanTimer = null;
6865 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08006866 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006867 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
6868 if (in.readInt() != 0) {
6869 makeProcessState(i, in);
6870 } else {
6871 mProcessStateTimer[i] = null;
6872 }
6873 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006874 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006875 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
6876 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006877 } else {
6878 mVibratorOnTimer = null;
6879 }
6880 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07006881 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
6882 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08006883 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006884 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006885 } else {
6886 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07006887 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006888 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006889 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
6890 mNetworkPacketActivityCounters
6891 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006892 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006893 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08006894 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006895 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08006896 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006897 }
Joe Onoratoabded112016-02-08 16:49:39 -08006898 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
6899 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006900 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006901 mNetworkByteActivityCounters = null;
6902 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006903 }
Adam Lesinskie08af192015-03-25 16:42:59 -07006904
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006905 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006906 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006907 NUM_WIFI_TX_LEVELS, in);
6908 } else {
6909 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07006910 }
6911
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006912 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006913 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006914 NUM_BT_TX_LEVELS, in);
6915 } else {
6916 mBluetoothControllerActivity = null;
6917 }
6918
6919 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006920 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006921 ModemActivityInfo.TX_POWER_LEVELS, in);
6922 } else {
6923 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07006924 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006925
Joe Onoratoabded112016-02-08 16:49:39 -08006926 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
6927 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
6928 mCpuPower = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006929
Adam Lesinski6832f392015-09-05 18:05:40 -07006930 if (in.readInt() != 0) {
6931 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08006932 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07006933 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006934 }
Adam Lesinski6832f392015-09-05 18:05:40 -07006935
6936 mCpuClusterSpeed = new LongSamplingCounter[numCpuClusters][];
6937 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
6938 if (in.readInt() != 0) {
6939 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08006940 if (mBsi.mPowerProfile != null &&
6941 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07006942 throw new ParcelFormatException("Incompatible number of cpu speeds");
6943 }
6944
6945 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
6946 mCpuClusterSpeed[cluster] = cpuSpeeds;
6947 for (int speed = 0; speed < numSpeeds; speed++) {
6948 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08006949 cpuSpeeds[speed] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07006950 }
6951 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07006952 } else {
6953 mCpuClusterSpeed[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07006954 }
6955 }
6956 } else {
6957 mCpuClusterSpeed = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006958 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006959
6960 if (in.readInt() != 0) {
6961 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
6962 } else {
6963 mMobileRadioApWakeupCount = null;
6964 }
6965
6966 if (in.readInt() != 0) {
6967 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
6968 } else {
6969 mWifiRadioApWakeupCount = null;
6970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006971 }
6972
6973 /**
6974 * The statistics associated with a particular wake lock.
6975 */
Joe Onoratoabded112016-02-08 16:49:39 -08006976 public static class Wakelock extends BatteryStats.Uid.Wakelock {
6977 /**
6978 * BatteryStatsImpl that we are associated with.
6979 */
6980 protected BatteryStatsImpl mBsi;
6981
6982 /**
6983 * BatteryStatsImpl that we are associated with.
6984 */
6985 protected Uid mUid;
6986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006987 /**
6988 * How long (in ms) this uid has been keeping the device partially awake.
6989 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07006990 DurationTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991
6992 /**
6993 * How long (in ms) this uid has been keeping the device fully awake.
6994 */
Evan Millarc64edde2009-04-18 12:26:32 -07006995 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996
6997 /**
6998 * How long (in ms) this uid has had a window keeping the device awake.
6999 */
Evan Millarc64edde2009-04-18 12:26:32 -07007000 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007001
7002 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007003 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07007004 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007005 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07007006
Joe Onoratoabded112016-02-08 16:49:39 -08007007 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
7008 mBsi = bsi;
7009 mUid = uid;
7010 }
7011
Adam Lesinski9425fe22015-06-19 12:02:13 -07007012 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007013 * Reads a possibly null Timer from a Parcel. The timer is associated with the
7014 * proper timer pool from the given BatteryStatsImpl object.
7015 *
7016 * @param in the Parcel to be read from.
7017 * return a new Timer, or null.
7018 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07007019 private StopwatchTimer readStopwatchTimerFromParcel(int type,
7020 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 if (in.readInt() == 0) {
7022 return null;
7023 }
7024
Joe Onoratoabded112016-02-08 16:49:39 -08007025 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007026 }
7027
Joe Onorato92fd23f2016-07-25 11:18:42 -07007028 /**
7029 * Reads a possibly null Timer from a Parcel. The timer is associated with the
7030 * proper timer pool from the given BatteryStatsImpl object.
7031 *
7032 * @param in the Parcel to be read from.
7033 * return a new Timer, or null.
7034 */
7035 private DurationTimer readDurationTimerFromParcel(int type,
7036 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
7037 if (in.readInt() == 0) {
7038 return null;
7039 }
7040
7041 return new DurationTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
7042 }
7043
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007044 boolean reset() {
7045 boolean wlactive = false;
7046 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007047 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007048 }
7049 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007050 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007051 }
7052 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007053 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007054 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007055 if (mTimerDraw != null) {
7056 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07007057 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007058 if (!wlactive) {
7059 if (mTimerFull != null) {
7060 mTimerFull.detach();
7061 mTimerFull = null;
7062 }
7063 if (mTimerPartial != null) {
7064 mTimerPartial.detach();
7065 mTimerPartial = null;
7066 }
7067 if (mTimerWindow != null) {
7068 mTimerWindow.detach();
7069 mTimerWindow = null;
7070 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007071 if (mTimerDraw != null) {
7072 mTimerDraw.detach();
7073 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07007074 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007075 }
7076 return !wlactive;
7077 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007078
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007079 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07007080 mTimerPartial = readDurationTimerFromParcel(WAKE_TYPE_PARTIAL,
Joe Onoratoabded112016-02-08 16:49:39 -08007081 mBsi.mPartialTimers, screenOffTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07007082 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
7083 mBsi.mFullTimers, timeBase, in);
7084 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
7085 mBsi.mWindowTimers, timeBase, in);
7086 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
7087 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 }
7089
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007090 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
7091 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
7092 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
7093 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007094 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007095 }
7096
7097 @Override
7098 public Timer getWakeTime(int type) {
7099 switch (type) {
7100 case WAKE_TYPE_FULL: return mTimerFull;
7101 case WAKE_TYPE_PARTIAL: return mTimerPartial;
7102 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007103 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007104 default: throw new IllegalArgumentException("type = " + type);
7105 }
7106 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007107
7108 public StopwatchTimer getStopwatchTimer(int type) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007109 switch (type) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07007110 case WAKE_TYPE_PARTIAL: {
7111 DurationTimer t = mTimerPartial;
Dianne Hackbornd953c532014-08-16 18:17:38 -07007112 if (t == null) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07007113 t = new DurationTimer(mBsi.mClocks, mUid, WAKE_TYPE_PARTIAL,
Joe Onoratoabded112016-02-08 16:49:39 -08007114 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackbornd953c532014-08-16 18:17:38 -07007115 mTimerPartial = t;
7116 }
7117 return t;
Joe Onorato92fd23f2016-07-25 11:18:42 -07007118 }
7119 case WAKE_TYPE_FULL: {
7120 StopwatchTimer t = mTimerFull;
Dianne Hackbornd953c532014-08-16 18:17:38 -07007121 if (t == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007122 t = new StopwatchTimer(mBsi.mClocks, mUid, WAKE_TYPE_FULL,
7123 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackbornd953c532014-08-16 18:17:38 -07007124 mTimerFull = t;
7125 }
7126 return t;
Joe Onorato92fd23f2016-07-25 11:18:42 -07007127 }
7128 case WAKE_TYPE_WINDOW: {
7129 StopwatchTimer t = mTimerWindow;
Dianne Hackbornd953c532014-08-16 18:17:38 -07007130 if (t == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007131 t = new StopwatchTimer(mBsi.mClocks, mUid, WAKE_TYPE_WINDOW,
7132 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackbornd953c532014-08-16 18:17:38 -07007133 mTimerWindow = t;
7134 }
7135 return t;
Joe Onorato92fd23f2016-07-25 11:18:42 -07007136 }
7137 case WAKE_TYPE_DRAW: {
7138 StopwatchTimer t = mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07007139 if (t == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007140 t = new StopwatchTimer(mBsi.mClocks, mUid, WAKE_TYPE_DRAW,
7141 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007142 mTimerDraw = t;
Adam Lesinski9425fe22015-06-19 12:02:13 -07007143 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007144 return t;
Joe Onorato92fd23f2016-07-25 11:18:42 -07007145 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007146 default:
7147 throw new IllegalArgumentException("type=" + type);
7148 }
7149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007150 }
7151
Joe Onoratoabded112016-02-08 16:49:39 -08007152 public static class Sensor extends BatteryStats.Uid.Sensor {
7153 /**
7154 * BatteryStatsImpl that we are associated with.
7155 */
7156 protected BatteryStatsImpl mBsi;
7157
7158 /**
Bookatz867c0d72017-03-07 18:23:42 -08007159 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08007160 */
7161 protected Uid mUid;
7162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007163 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08007164 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007165
Joe Onoratoabded112016-02-08 16:49:39 -08007166 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
7167 mBsi = bsi;
7168 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007169 mHandle = handle;
7170 }
7171
Bookatz867c0d72017-03-07 18:23:42 -08007172 private DualTimer readTimersFromParcel(
7173 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007174 if (in.readInt() == 0) {
7175 return null;
7176 }
7177
Joe Onoratoabded112016-02-08 16:49:39 -08007178 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007179 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07007180 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007181 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 }
Bookatz867c0d72017-03-07 18:23:42 -08007183 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007184 }
7185
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007186 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007187 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007188 mTimer = null;
7189 return true;
7190 }
7191 return false;
7192 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007193
Bookatz867c0d72017-03-07 18:23:42 -08007194 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
7195 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 }
7197
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007198 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatz867c0d72017-03-07 18:23:42 -08007199 DualTimer.writeDualTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007200 }
7201
7202 @Override
7203 public Timer getSensorTime() {
Bookatz867c0d72017-03-07 18:23:42 -08007204 if (mTimer == null) {
7205 return null;
7206 }
7207 return mTimer.getMainTimer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007209
7210 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007211 public Timer getSensorBackgroundTime() {
7212 if (mTimer == null) {
7213 return null;
7214 }
7215 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007216 }
7217
7218 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 public int getHandle() {
7220 return mHandle;
7221 }
7222 }
7223
7224 /**
7225 * The statistics associated with a particular process.
7226 */
Joe Onoratoabded112016-02-08 16:49:39 -08007227 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
7228 /**
7229 * BatteryStatsImpl that we are associated with.
7230 */
7231 protected BatteryStatsImpl mBsi;
7232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007233 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07007234 * The name of this process.
7235 */
7236 final String mName;
7237
7238 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08007239 * Remains true until removed from the stats.
7240 */
7241 boolean mActive = true;
7242
7243 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007244 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007245 */
7246 long mUserTime;
7247
7248 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007249 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007250 */
7251 long mSystemTime;
7252
7253 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007254 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007255 */
7256 long mForegroundTime;
7257
7258 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007259 * Number of times the process has been started.
7260 */
7261 int mStarts;
7262
7263 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007264 * Number of times the process has crashed.
7265 */
7266 int mNumCrashes;
7267
7268 /**
7269 * Number of times the process has had an ANR.
7270 */
7271 int mNumAnrs;
7272
7273 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007274 * The amount of user time loaded from a previous save.
7275 */
7276 long mLoadedUserTime;
7277
7278 /**
7279 * The amount of system time loaded from a previous save.
7280 */
7281 long mLoadedSystemTime;
7282
7283 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007284 * The amount of foreground time loaded from a previous save.
7285 */
7286 long mLoadedForegroundTime;
7287
7288 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007289 * The number of times the process has started from a previous save.
7290 */
7291 int mLoadedStarts;
7292
7293 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007294 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007296 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007297
7298 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007299 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007300 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007301 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007302
7303 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007304 * The amount of user time when last unplugged.
7305 */
7306 long mUnpluggedUserTime;
7307
7308 /**
7309 * The amount of system time when last unplugged.
7310 */
7311 long mUnpluggedSystemTime;
7312
7313 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007314 * The amount of foreground time since unplugged.
7315 */
7316 long mUnpluggedForegroundTime;
7317
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007318 /**
7319 * The number of times the process has started before unplugged.
7320 */
7321 int mUnpluggedStarts;
7322
Dianne Hackborn61659e52014-07-09 16:13:01 -07007323 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007324 * Number of times the process has crashed before unplugged.
7325 */
7326 int mUnpluggedNumCrashes;
7327
7328 /**
7329 * Number of times the process has had an ANR before unplugged.
7330 */
7331 int mUnpluggedNumAnrs;
7332
Dianne Hackborn287952c2010-09-22 22:34:31 -07007333 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007334
Joe Onoratoabded112016-02-08 16:49:39 -08007335 public Proc(BatteryStatsImpl bsi, String name) {
7336 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07007337 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08007338 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007339 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07007340
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007341 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 mUnpluggedUserTime = mUserTime;
7343 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007344 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007345 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007346 mUnpluggedNumCrashes = mNumCrashes;
7347 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007348 }
7349
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007350 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007352
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007353 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08007354 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08007355 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007356 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007357
Dianne Hackborn287952c2010-09-22 22:34:31 -07007358 public int countExcessivePowers() {
7359 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007360 }
7361
Dianne Hackborn287952c2010-09-22 22:34:31 -07007362 public ExcessivePower getExcessivePower(int i) {
7363 if (mExcessivePower != null) {
7364 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007365 }
7366 return null;
7367 }
7368
7369 public void addExcessiveWake(long overTime, long usedTime) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07007370 if (mExcessivePower == null) {
7371 mExcessivePower = new ArrayList<ExcessivePower>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007372 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07007373 ExcessivePower ew = new ExcessivePower();
7374 ew.type = ExcessivePower.TYPE_WAKE;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007375 ew.overTime = overTime;
7376 ew.usedTime = usedTime;
Dianne Hackborn287952c2010-09-22 22:34:31 -07007377 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007378 }
7379
Dianne Hackborn287952c2010-09-22 22:34:31 -07007380 public void addExcessiveCpu(long overTime, long usedTime) {
7381 if (mExcessivePower == null) {
7382 mExcessivePower = new ArrayList<ExcessivePower>();
7383 }
7384 ExcessivePower ew = new ExcessivePower();
7385 ew.type = ExcessivePower.TYPE_CPU;
7386 ew.overTime = overTime;
7387 ew.usedTime = usedTime;
7388 mExcessivePower.add(ew);
7389 }
7390
7391 void writeExcessivePowerToParcelLocked(Parcel out) {
7392 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007393 out.writeInt(0);
7394 return;
7395 }
7396
Dianne Hackborn287952c2010-09-22 22:34:31 -07007397 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007398 out.writeInt(N);
7399 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07007400 ExcessivePower ew = mExcessivePower.get(i);
7401 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007402 out.writeLong(ew.overTime);
7403 out.writeLong(ew.usedTime);
7404 }
7405 }
7406
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007407 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007408 final int N = in.readInt();
7409 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07007410 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007411 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007412 }
7413
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08007414 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007415 throw new ParcelFormatException(
7416 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08007417 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07007418
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007419 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007420 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07007421 ExcessivePower ew = new ExcessivePower();
7422 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007423 ew.overTime = in.readLong();
7424 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07007425 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007426 }
7427 }
7428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429 void writeToParcelLocked(Parcel out) {
7430 out.writeLong(mUserTime);
7431 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007432 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007433 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007434 out.writeInt(mNumCrashes);
7435 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007436 out.writeLong(mLoadedUserTime);
7437 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007438 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007439 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007440 out.writeInt(mLoadedNumCrashes);
7441 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007442 out.writeLong(mUnpluggedUserTime);
7443 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007444 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007445 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007446 out.writeInt(mUnpluggedNumCrashes);
7447 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07007448 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007449 }
7450
7451 void readFromParcelLocked(Parcel in) {
7452 mUserTime = in.readLong();
7453 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007454 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007455 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007456 mNumCrashes = in.readInt();
7457 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007458 mLoadedUserTime = in.readLong();
7459 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007460 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007461 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007462 mLoadedNumCrashes = in.readInt();
7463 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007464 mUnpluggedUserTime = in.readLong();
7465 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007466 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007468 mUnpluggedNumCrashes = in.readInt();
7469 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07007470 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007471 }
7472
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007473 public void addCpuTimeLocked(int utime, int stime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474 mUserTime += utime;
7475 mSystemTime += stime;
7476 }
7477
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007478 public void addForegroundTimeLocked(long ttime) {
7479 mForegroundTime += ttime;
7480 }
7481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007482 public void incStartsLocked() {
7483 mStarts++;
7484 }
7485
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007486 public void incNumCrashesLocked() {
7487 mNumCrashes++;
7488 }
7489
7490 public void incNumAnrsLocked() {
7491 mNumAnrs++;
7492 }
7493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007494 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08007495 public boolean isActive() {
7496 return mActive;
7497 }
7498
7499 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007500 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07007501 long val = mUserTime;
7502 if (which == STATS_CURRENT) {
7503 val -= mLoadedUserTime;
7504 } else if (which == STATS_SINCE_UNPLUGGED) {
7505 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 }
7507 return val;
7508 }
7509
7510 @Override
7511 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07007512 long val = mSystemTime;
7513 if (which == STATS_CURRENT) {
7514 val -= mLoadedSystemTime;
7515 } else if (which == STATS_SINCE_UNPLUGGED) {
7516 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007517 }
7518 return val;
7519 }
7520
7521 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007522 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07007523 long val = mForegroundTime;
7524 if (which == STATS_CURRENT) {
7525 val -= mLoadedForegroundTime;
7526 } else if (which == STATS_SINCE_UNPLUGGED) {
7527 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007528 }
7529 return val;
7530 }
7531
7532 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07007534 int val = mStarts;
7535 if (which == STATS_CURRENT) {
7536 val -= mLoadedStarts;
7537 } else if (which == STATS_SINCE_UNPLUGGED) {
7538 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 }
7540 return val;
7541 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07007542
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007543 @Override
7544 public int getNumCrashes(int which) {
7545 int val = mNumCrashes;
7546 if (which == STATS_CURRENT) {
7547 val -= mLoadedNumCrashes;
7548 } else if (which == STATS_SINCE_UNPLUGGED) {
7549 val -= mUnpluggedNumCrashes;
7550 }
7551 return val;
7552 }
7553
7554 @Override
7555 public int getNumAnrs(int which) {
7556 int val = mNumAnrs;
7557 if (which == STATS_CURRENT) {
7558 val -= mLoadedNumAnrs;
7559 } else if (which == STATS_SINCE_UNPLUGGED) {
7560 val -= mUnpluggedNumAnrs;
7561 }
7562 return val;
7563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 }
7565
7566 /**
7567 * The statistics associated with a particular package.
7568 */
Joe Onoratoabded112016-02-08 16:49:39 -08007569 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
7570 /**
7571 * BatteryStatsImpl that we are associated with.
7572 */
7573 protected BatteryStatsImpl mBsi;
7574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007575 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007576 * Number of times wakeup alarms have occurred for this app.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007577 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007578 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007579
7580 /**
7581 * The statics we have collected for this package's services.
7582 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007583 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584
Joe Onoratoabded112016-02-08 16:49:39 -08007585 public Pkg(BatteryStatsImpl bsi) {
7586 mBsi = bsi;
7587 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007589
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007590 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591 }
7592
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007593 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007595
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007596 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08007597 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007598 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007601 int numWA = in.readInt();
7602 mWakeupAlarms.clear();
7603 for (int i=0; i<numWA; i++) {
7604 String tag = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08007605 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007607
7608 int numServs = in.readInt();
7609 mServiceStats.clear();
7610 for (int m = 0; m < numServs; m++) {
7611 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08007612 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 mServiceStats.put(serviceName, serv);
7614
7615 serv.readFromParcelLocked(in);
7616 }
7617 }
7618
7619 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007620 int numWA = mWakeupAlarms.size();
7621 out.writeInt(numWA);
7622 for (int i=0; i<numWA; i++) {
7623 out.writeString(mWakeupAlarms.keyAt(i));
7624 mWakeupAlarms.valueAt(i).writeToParcel(out);
7625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007626
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007627 final int NS = mServiceStats.size();
7628 out.writeInt(NS);
7629 for (int i=0; i<NS; i++) {
7630 out.writeString(mServiceStats.keyAt(i));
7631 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 serv.writeToParcelLocked(out);
7633 }
7634 }
7635
7636 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007637 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
7638 return mWakeupAlarms;
7639 }
7640
7641 public void noteWakeupAlarmLocked(String tag) {
7642 Counter c = mWakeupAlarms.get(tag);
7643 if (c == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007644 c = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007645 mWakeupAlarms.put(tag, c);
7646 }
7647 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007648 }
7649
7650 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007651 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
7652 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653 }
7654
7655 /**
7656 * The statistics associated with a particular service.
7657 */
Joe Onoratoabded112016-02-08 16:49:39 -08007658 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
7659 /**
7660 * BatteryStatsImpl that we are associated with.
7661 */
7662 protected BatteryStatsImpl mBsi;
7663
7664 /**
7665 * The android package in which this service resides.
7666 */
7667 protected Pkg mPkg;
7668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 /**
7670 * Total time (ms in battery uptime) the service has been left started.
7671 */
Joe Onoratoabded112016-02-08 16:49:39 -08007672 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007673
7674 /**
7675 * If service has been started and not yet stopped, this is
7676 * when it was started.
7677 */
Joe Onoratoabded112016-02-08 16:49:39 -08007678 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679
7680 /**
7681 * True if we are currently running.
7682 */
Joe Onoratoabded112016-02-08 16:49:39 -08007683 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007684
7685 /**
7686 * Total number of times startService() has been called.
7687 */
Joe Onoratoabded112016-02-08 16:49:39 -08007688 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689
7690 /**
7691 * Total time (ms in battery uptime) the service has been left launched.
7692 */
Joe Onoratoabded112016-02-08 16:49:39 -08007693 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007694
7695 /**
7696 * If service has been launched and not yet exited, this is
7697 * when it was launched (ms in battery uptime).
7698 */
Joe Onoratoabded112016-02-08 16:49:39 -08007699 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007700
7701 /**
7702 * True if we are currently launched.
7703 */
Joe Onoratoabded112016-02-08 16:49:39 -08007704 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007705
7706 /**
7707 * Total number times the service has been launched.
7708 */
Joe Onoratoabded112016-02-08 16:49:39 -08007709 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710
7711 /**
7712 * The amount of time spent started loaded from a previous save
7713 * (ms in battery uptime).
7714 */
Joe Onoratoabded112016-02-08 16:49:39 -08007715 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716
7717 /**
7718 * The number of starts loaded from a previous save.
7719 */
Joe Onoratoabded112016-02-08 16:49:39 -08007720 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721
7722 /**
7723 * The number of launches loaded from a previous save.
7724 */
Joe Onoratoabded112016-02-08 16:49:39 -08007725 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726
7727 /**
7728 * The amount of time spent started as of the last run (ms
7729 * in battery uptime).
7730 */
Joe Onoratoabded112016-02-08 16:49:39 -08007731 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732
7733 /**
7734 * The number of starts as of the last run.
7735 */
Joe Onoratoabded112016-02-08 16:49:39 -08007736 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737
7738 /**
7739 * The number of launches as of the last run.
7740 */
Joe Onoratoabded112016-02-08 16:49:39 -08007741 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742
7743 /**
7744 * The amount of time spent started when last unplugged (ms
7745 * in battery uptime).
7746 */
Joe Onoratoabded112016-02-08 16:49:39 -08007747 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748
7749 /**
7750 * The number of starts when last unplugged.
7751 */
Joe Onoratoabded112016-02-08 16:49:39 -08007752 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753
7754 /**
7755 * The number of launches when last unplugged.
7756 */
Joe Onoratoabded112016-02-08 16:49:39 -08007757 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007758
Joe Onoratoabded112016-02-08 16:49:39 -08007759 /**
7760 * Construct a Serv. Also adds it to the on-battery time base as a listener.
7761 */
7762 public Serv(BatteryStatsImpl bsi) {
7763 mBsi = bsi;
7764 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007765 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007766
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007767 public void onTimeStarted(long elapsedRealtime, long baseUptime,
7768 long baseRealtime) {
7769 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007770 mUnpluggedStarts = mStarts;
7771 mUnpluggedLaunches = mLaunches;
7772 }
7773
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007774 public void onTimeStopped(long elapsedRealtime, long baseUptime,
7775 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007777
Joe Onoratoabded112016-02-08 16:49:39 -08007778 /**
7779 * Remove this Serv as a listener from the time base.
7780 */
7781 public void detach() {
7782 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007783 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007784
Joe Onoratoabded112016-02-08 16:49:39 -08007785 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 mStartTime = in.readLong();
7787 mRunningSince = in.readLong();
7788 mRunning = in.readInt() != 0;
7789 mStarts = in.readInt();
7790 mLaunchedTime = in.readLong();
7791 mLaunchedSince = in.readLong();
7792 mLaunched = in.readInt() != 0;
7793 mLaunches = in.readInt();
7794 mLoadedStartTime = in.readLong();
7795 mLoadedStarts = in.readInt();
7796 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07007797 mLastStartTime = 0;
7798 mLastStarts = 0;
7799 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 mUnpluggedStartTime = in.readLong();
7801 mUnpluggedStarts = in.readInt();
7802 mUnpluggedLaunches = in.readInt();
7803 }
7804
Joe Onoratoabded112016-02-08 16:49:39 -08007805 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007806 out.writeLong(mStartTime);
7807 out.writeLong(mRunningSince);
7808 out.writeInt(mRunning ? 1 : 0);
7809 out.writeInt(mStarts);
7810 out.writeLong(mLaunchedTime);
7811 out.writeLong(mLaunchedSince);
7812 out.writeInt(mLaunched ? 1 : 0);
7813 out.writeInt(mLaunches);
7814 out.writeLong(mLoadedStartTime);
7815 out.writeInt(mLoadedStarts);
7816 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 out.writeLong(mUnpluggedStartTime);
7818 out.writeInt(mUnpluggedStarts);
7819 out.writeInt(mUnpluggedLaunches);
7820 }
7821
Joe Onoratoabded112016-02-08 16:49:39 -08007822 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 if (!mLaunched) return mLaunchedTime;
7824 return mLaunchedTime + batteryUptime - mLaunchedSince;
7825 }
7826
Joe Onoratoabded112016-02-08 16:49:39 -08007827 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 if (!mRunning) return mStartTime;
7829 return mStartTime + batteryUptime - mRunningSince;
7830 }
7831
7832 public void startLaunchedLocked() {
7833 if (!mLaunched) {
7834 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08007835 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 mLaunched = true;
7837 }
7838 }
7839
7840 public void stopLaunchedLocked() {
7841 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08007842 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 if (time > 0) {
7844 mLaunchedTime += time;
7845 } else {
7846 mLaunches--;
7847 }
7848 mLaunched = false;
7849 }
7850 }
7851
7852 public void startRunningLocked() {
7853 if (!mRunning) {
7854 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08007855 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 mRunning = true;
7857 }
7858 }
7859
7860 public void stopRunningLocked() {
7861 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08007862 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863 if (time > 0) {
7864 mStartTime += time;
7865 } else {
7866 mStarts--;
7867 }
7868 mRunning = false;
7869 }
7870 }
7871
7872 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08007873 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 }
7875
7876 @Override
7877 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07007878 int val = mLaunches;
7879 if (which == STATS_CURRENT) {
7880 val -= mLoadedLaunches;
7881 } else if (which == STATS_SINCE_UNPLUGGED) {
7882 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 return val;
7885 }
7886
7887 @Override
7888 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07007889 long val = getStartTimeToNowLocked(now);
7890 if (which == STATS_CURRENT) {
7891 val -= mLoadedStartTime;
7892 } else if (which == STATS_SINCE_UNPLUGGED) {
7893 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 return val;
7896 }
7897
7898 @Override
7899 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07007900 int val = mStarts;
7901 if (which == STATS_CURRENT) {
7902 val -= mLoadedStarts;
7903 } else if (which == STATS_SINCE_UNPLUGGED) {
7904 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 }
7906
7907 return val;
7908 }
7909 }
7910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007911 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08007912 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007913 }
7914 }
7915
7916 /**
7917 * Retrieve the statistics object for a particular process, creating
7918 * if needed.
7919 */
7920 public Proc getProcessStatsLocked(String name) {
7921 Proc ps = mProcessStats.get(name);
7922 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007923 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 mProcessStats.put(name, ps);
7925 }
7926
7927 return ps;
7928 }
7929
Dianne Hackborna8d10942015-11-19 17:55:19 -08007930 public void updateUidProcessStateLocked(int procState) {
7931 int uidRunningState;
7932 if (procState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
7933 uidRunningState = ActivityManager.PROCESS_STATE_NONEXISTENT;
7934 } else if (procState == ActivityManager.PROCESS_STATE_TOP) {
7935 uidRunningState = PROCESS_STATE_TOP;
7936 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
7937 // Persistent and other foreground states go here.
7938 uidRunningState = PROCESS_STATE_FOREGROUND_SERVICE;
7939 } else if (procState <= ActivityManager.PROCESS_STATE_TOP_SLEEPING) {
7940 uidRunningState = PROCESS_STATE_TOP_SLEEPING;
7941 } else if (procState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
7942 // Persistent and other foreground states go here.
7943 uidRunningState = PROCESS_STATE_FOREGROUND;
7944 } else if (procState <= ActivityManager.PROCESS_STATE_RECEIVER) {
7945 uidRunningState = PROCESS_STATE_BACKGROUND;
Dianne Hackborn61659e52014-07-09 16:13:01 -07007946 } else {
Dianne Hackborna8d10942015-11-19 17:55:19 -08007947 uidRunningState = PROCESS_STATE_CACHED;
Dianne Hackborn61659e52014-07-09 16:13:01 -07007948 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07007949
Dianne Hackborna8d10942015-11-19 17:55:19 -08007950 if (mProcessState == uidRunningState) return;
7951
Bookatz867c0d72017-03-07 18:23:42 -08007952 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
7953 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08007954
7955 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
Bookatz867c0d72017-03-07 18:23:42 -08007956 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborna8d10942015-11-19 17:55:19 -08007957 }
7958 mProcessState = uidRunningState;
7959 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
7960 if (mProcessStateTimer[uidRunningState] == null) {
7961 makeProcessState(uidRunningState, null);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007962 }
Bookatz867c0d72017-03-07 18:23:42 -08007963 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007964 }
Bookatz867c0d72017-03-07 18:23:42 -08007965
7966 updateBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
7967 }
7968
7969 public boolean updateBgTimeBase(long uptimeUs, long realtimeUs) {
7970 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
7971 // also considered to be 'background' for our purposes, because it's not foreground.
7972 boolean isBgAndUnplugged = mBsi.mOnBatteryTimeBase.isRunning()
7973 && mProcessState >= PROCESS_STATE_BACKGROUND;
7974 return mOnBatteryBackgroundTimeBase.setRunning(isBgAndUnplugged, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007975 }
7976
Dianne Hackbornb5e31652010-09-07 12:13:55 -07007977 public SparseArray<? extends Pid> getPidStats() {
7978 return mPids;
7979 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007980
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007981 public Pid getPidStatsLocked(int pid) {
7982 Pid p = mPids.get(pid);
7983 if (p == null) {
7984 p = new Pid();
7985 mPids.put(pid, p);
7986 }
7987 return p;
7988 }
7989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 /**
7991 * Retrieve the statistics object for a particular service, creating
7992 * if needed.
7993 */
7994 public Pkg getPackageStatsLocked(String name) {
7995 Pkg ps = mPackageStats.get(name);
7996 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007997 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 mPackageStats.put(name, ps);
7999 }
8000
8001 return ps;
8002 }
8003
8004 /**
8005 * Retrieve the statistics object for a particular service, creating
8006 * if needed.
8007 */
8008 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
8009 Pkg ps = getPackageStatsLocked(pkg);
8010 Pkg.Serv ss = ps.mServiceStats.get(serv);
8011 if (ss == null) {
8012 ss = ps.newServiceStatsLocked();
8013 ps.mServiceStats.put(serv, ss);
8014 }
8015
8016 return ss;
8017 }
8018
Dianne Hackbornd953c532014-08-16 18:17:38 -07008019 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
8020 StopwatchTimer timer = mSyncStats.instantiateObject();
8021 timer.readSummaryFromParcelLocked(in);
8022 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008023 }
8024
Dianne Hackbornd953c532014-08-16 18:17:38 -07008025 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
8026 StopwatchTimer timer = mJobStats.instantiateObject();
8027 timer.readSummaryFromParcelLocked(in);
8028 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008029 }
8030
Dianne Hackbornd953c532014-08-16 18:17:38 -07008031 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08008032 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008033 mWakelockStats.add(wlName, wl);
8034 if (in.readInt() != 0) {
8035 wl.getStopwatchTimer(WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008036 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008037 if (in.readInt() != 0) {
8038 wl.getStopwatchTimer(WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
8039 }
8040 if (in.readInt() != 0) {
8041 wl.getStopwatchTimer(WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07008043 if (in.readInt() != 0) {
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008044 wl.getStopwatchTimer(WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 }
8047
Bookatz867c0d72017-03-07 18:23:42 -08008048 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 Sensor se = mSensorStats.get(sensor);
8050 if (se == null) {
8051 if (!create) {
8052 return null;
8053 }
Joe Onoratoabded112016-02-08 16:49:39 -08008054 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008055 mSensorStats.put(sensor, se);
8056 }
Bookatz867c0d72017-03-07 18:23:42 -08008057 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008058 if (t != null) {
8059 return t;
8060 }
Joe Onoratoabded112016-02-08 16:49:39 -08008061 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008062 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008063 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008064 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008065 }
Bookatz867c0d72017-03-07 18:23:42 -08008066 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
8067 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008068 se.mTimer = t;
8069 return t;
8070 }
8071
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008072 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008073 StopwatchTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008074 if (t != null) {
8075 t.startRunningLocked(elapsedRealtimeMs);
8076 }
8077 }
8078
8079 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008080 StopwatchTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008081 if (t != null) {
8082 t.stopRunningLocked(elapsedRealtimeMs);
8083 }
8084 }
8085
8086 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07008087 StopwatchTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008088 if (t != null) {
8089 t.startRunningLocked(elapsedRealtimeMs);
8090 }
8091 }
8092
8093 public void noteStopJobLocked(String name, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008094 StopwatchTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008095 if (t != null) {
8096 t.stopRunningLocked(elapsedRealtimeMs);
8097 }
8098 }
8099
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008100 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008101 Wakelock wl = mWakelockStats.startObject(name);
8102 if (wl != null) {
8103 wl.getStopwatchTimer(type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07008105 if (pid >= 0 && type == WAKE_TYPE_PARTIAL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008106 Pid p = getPidStatsLocked(pid);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008107 if (p.mWakeNesting++ == 0) {
8108 p.mWakeStartMs = elapsedRealtimeMs;
Dianne Hackbornb8071d792010-09-09 16:45:15 -07008109 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008111 }
8112
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008113 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008114 Wakelock wl = mWakelockStats.stopObject(name);
8115 if (wl != null) {
8116 wl.getStopwatchTimer(type).stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07008118 if (pid >= 0 && type == WAKE_TYPE_PARTIAL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008119 Pid p = mPids.get(pid);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008120 if (p != null && p.mWakeNesting > 0) {
8121 if (p.mWakeNesting-- == 1) {
8122 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
8123 p.mWakeStartMs = 0;
8124 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008125 }
8126 }
8127 }
8128
8129 public void reportExcessiveWakeLocked(String proc, long overTime, long usedTime) {
8130 Proc p = getProcessStatsLocked(proc);
8131 if (p != null) {
8132 p.addExcessiveWake(overTime, usedTime);
8133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008134 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008135
Dianne Hackborn287952c2010-09-22 22:34:31 -07008136 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
8137 Proc p = getProcessStatsLocked(proc);
8138 if (p != null) {
8139 p.addExcessiveCpu(overTime, usedTime);
8140 }
8141 }
8142
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008143 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008144 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08008145 t.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 }
8147
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008148 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -08008150 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008152 t.stopRunningLocked(elapsedRealtimeMs);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008154 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008155
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008156 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008157 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008159
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008160 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008161 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 }
8163
8164 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08008165 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008166 }
8167 }
8168
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07008169 public BatteryStatsImpl(File systemDir, Handler handler, ExternalStatsSync externalSync) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07008170 this(new SystemClocks(), systemDir, handler, externalSync, null);
8171 }
8172
8173 public BatteryStatsImpl(File systemDir, Handler handler, ExternalStatsSync externalSync,
8174 PlatformIdleStateCallback cb) {
8175 this(new SystemClocks(), systemDir, handler, externalSync, cb);
Joe Onoratoabded112016-02-08 16:49:39 -08008176 }
8177
8178 public BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07008179 ExternalStatsSync externalSync, PlatformIdleStateCallback cb) {
Joe Onoratoabded112016-02-08 16:49:39 -08008180 init(clocks);
8181
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07008182 if (systemDir != null) {
8183 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
8184 new File(systemDir, "batterystats.bin.tmp"));
8185 } else {
8186 mFile = null;
8187 }
8188 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008189 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07008190 mExternalSync = externalSync;
Jeff Brown6f357d32014-01-15 20:40:55 -08008191 mHandler = new MyHandler(handler.getLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -08008193 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008194 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008195 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008196 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07008197 }
Joe Onoratoabded112016-02-08 16:49:39 -08008198 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
8199 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
8200 mOnBatteryTimeBase);
8201 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
8202 mOnBatteryTimeBase);
8203 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
8204 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
8205 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
8206 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
8207 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
8208 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
8209 mOnBatteryTimeBase);
8210 }
8211 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
8212 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07008213 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008214 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008215 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07008216 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008217 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008218 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
8219 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008220 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008221 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
8222 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
8223 NUM_BT_TX_LEVELS);
8224 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
8225 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -08008226 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
8227 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
8228 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07008229 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008230 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
8231 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08008232 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
8233 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08008234 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008235 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -07008236 mOnBatteryTimeBase);
8237 }
Joe Onoratoabded112016-02-08 16:49:39 -08008238 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
8239 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
8240 mOnBatteryTimeBase);
8241 }
8242 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
8243 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
8244 mOnBatteryTimeBase);
8245 }
8246 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
8247 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
8248 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
8249 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
8250 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07008251 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
8252 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008253 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -08008254 long uptime = mClocks.uptimeMillis() * 1000;
8255 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008256 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008257 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -07008258 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008259 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07008260 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -07008261 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07008262 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08008263 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008264 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008265 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07008266 mPlatformIdleStateCallback = cb;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 }
8268
8269 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -08008270 this(new SystemClocks(), p);
8271 }
8272
8273 public BatteryStatsImpl(Clocks clocks, Parcel p) {
8274 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008275 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07008276 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008277 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07008278 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07008279 mExternalSync = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008280 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008281 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07008282 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283 }
8284
Adam Lesinskie08af192015-03-25 16:42:59 -07008285 public void setPowerProfile(PowerProfile profile) {
8286 synchronized (this) {
8287 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -07008288
8289 // We need to initialize the KernelCpuSpeedReaders to read from
8290 // the first cpu of each core. Once we have the PowerProfile, we have access to this
8291 // information.
8292 final int numClusters = mPowerProfile.getNumCpuClusters();
8293 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
8294 int firstCpuOfCluster = 0;
8295 for (int i = 0; i < numClusters; i++) {
8296 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
8297 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
8298 numSpeedSteps);
8299 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
8300 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -07008301
8302 if (mEstimatedBatteryCapacity == -1) {
8303 // Initialize the estimated battery capacity to a known preset one.
8304 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
8305 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008306 }
8307 }
8308
Dianne Hackborn0d903a82010-09-07 23:51:03 -07008309 public void setCallback(BatteryCallback cb) {
8310 mCallback = cb;
8311 }
8312
Amith Yamasanif37447b2009-10-08 18:28:01 -07008313 public void setRadioScanningTimeout(long timeout) {
8314 if (mPhoneSignalScanningTimer != null) {
8315 mPhoneSignalScanningTimer.setTimeout(timeout);
8316 }
8317 }
8318
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008319 public void updateDailyDeadlineLocked() {
8320 // Get the current time.
8321 long currentTime = mDailyStartTime = System.currentTimeMillis();
8322 Calendar calDeadline = Calendar.getInstance();
8323 calDeadline.setTimeInMillis(currentTime);
8324
8325 // Move time up to the next day, ranging from 1am to 3pm.
8326 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
8327 calDeadline.set(Calendar.MILLISECOND, 0);
8328 calDeadline.set(Calendar.SECOND, 0);
8329 calDeadline.set(Calendar.MINUTE, 0);
8330 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
8331 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
8332 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
8333 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
8334 }
8335
8336 public void recordDailyStatsIfNeededLocked(boolean settled) {
8337 long currentTime = System.currentTimeMillis();
8338 if (currentTime >= mNextMaxDailyDeadline) {
8339 recordDailyStatsLocked();
8340 } else if (settled && currentTime >= mNextMinDailyDeadline) {
8341 recordDailyStatsLocked();
8342 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
8343 recordDailyStatsLocked();
8344 }
8345 }
8346
8347 public void recordDailyStatsLocked() {
8348 DailyItem item = new DailyItem();
8349 item.mStartTime = mDailyStartTime;
8350 item.mEndTime = System.currentTimeMillis();
8351 boolean hasData = false;
8352 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
8353 hasData = true;
8354 item.mDischargeSteps = new LevelStepTracker(
8355 mDailyDischargeStepTracker.mNumStepDurations,
8356 mDailyDischargeStepTracker.mStepDurations);
8357 }
8358 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
8359 hasData = true;
8360 item.mChargeSteps = new LevelStepTracker(
8361 mDailyChargeStepTracker.mNumStepDurations,
8362 mDailyChargeStepTracker.mStepDurations);
8363 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07008364 if (mDailyPackageChanges != null) {
8365 hasData = true;
8366 item.mPackageChanges = mDailyPackageChanges;
8367 mDailyPackageChanges = null;
8368 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008369 mDailyDischargeStepTracker.init();
8370 mDailyChargeStepTracker.init();
8371 updateDailyDeadlineLocked();
8372
8373 if (hasData) {
8374 mDailyItems.add(item);
8375 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
8376 mDailyItems.remove(0);
8377 }
8378 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
8379 try {
8380 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01008381 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008382 writeDailyItemsLocked(out);
8383 BackgroundThread.getHandler().post(new Runnable() {
8384 @Override
8385 public void run() {
8386 synchronized (mCheckinFile) {
8387 FileOutputStream stream = null;
8388 try {
8389 stream = mDailyFile.startWrite();
8390 memStream.writeTo(stream);
8391 stream.flush();
8392 FileUtils.sync(stream);
8393 stream.close();
8394 mDailyFile.finishWrite(stream);
8395 } catch (IOException e) {
8396 Slog.w("BatteryStats",
8397 "Error writing battery daily items", e);
8398 mDailyFile.failWrite(stream);
8399 }
8400 }
8401 }
8402 });
8403 } catch (IOException e) {
8404 }
8405 }
8406 }
8407
8408 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
8409 StringBuilder sb = new StringBuilder(64);
8410 out.startDocument(null, true);
8411 out.startTag(null, "daily-items");
8412 for (int i=0; i<mDailyItems.size(); i++) {
8413 final DailyItem dit = mDailyItems.get(i);
8414 out.startTag(null, "item");
8415 out.attribute(null, "start", Long.toString(dit.mStartTime));
8416 out.attribute(null, "end", Long.toString(dit.mEndTime));
8417 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
8418 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07008419 if (dit.mPackageChanges != null) {
8420 for (int j=0; j<dit.mPackageChanges.size(); j++) {
8421 PackageChange pc = dit.mPackageChanges.get(j);
8422 if (pc.mUpdate) {
8423 out.startTag(null, "upd");
8424 out.attribute(null, "pkg", pc.mPackageName);
8425 out.attribute(null, "ver", Integer.toString(pc.mVersionCode));
8426 out.endTag(null, "upd");
8427 } else {
8428 out.startTag(null, "rem");
8429 out.attribute(null, "pkg", pc.mPackageName);
8430 out.endTag(null, "rem");
8431 }
8432 }
8433 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008434 out.endTag(null, "item");
8435 }
8436 out.endTag(null, "daily-items");
8437 out.endDocument();
8438 }
8439
8440 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
8441 StringBuilder tmpBuilder) throws IOException {
8442 if (steps != null) {
8443 out.startTag(null, tag);
8444 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
8445 for (int i=0; i<steps.mNumStepDurations; i++) {
8446 out.startTag(null, "s");
8447 tmpBuilder.setLength(0);
8448 steps.encodeEntryAt(i, tmpBuilder);
8449 out.attribute(null, "v", tmpBuilder.toString());
8450 out.endTag(null, "s");
8451 }
8452 out.endTag(null, tag);
8453 }
8454 }
8455
8456 public void readDailyStatsLocked() {
8457 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
8458 mDailyItems.clear();
8459 FileInputStream stream;
8460 try {
8461 stream = mDailyFile.openRead();
8462 } catch (FileNotFoundException e) {
8463 return;
8464 }
8465 try {
8466 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01008467 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008468 readDailyItemsLocked(parser);
8469 } catch (XmlPullParserException e) {
8470 } finally {
8471 try {
8472 stream.close();
8473 } catch (IOException e) {
8474 }
8475 }
8476 }
8477
8478 private void readDailyItemsLocked(XmlPullParser parser) {
8479 try {
8480 int type;
8481 while ((type = parser.next()) != XmlPullParser.START_TAG
8482 && type != XmlPullParser.END_DOCUMENT) {
8483 ;
8484 }
8485
8486 if (type != XmlPullParser.START_TAG) {
8487 throw new IllegalStateException("no start tag found");
8488 }
8489
8490 int outerDepth = parser.getDepth();
8491 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
8492 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
8493 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
8494 continue;
8495 }
8496
8497 String tagName = parser.getName();
8498 if (tagName.equals("item")) {
8499 readDailyItemTagLocked(parser);
8500 } else {
8501 Slog.w(TAG, "Unknown element under <daily-items>: "
8502 + parser.getName());
8503 XmlUtils.skipCurrentTag(parser);
8504 }
8505 }
8506
8507 } catch (IllegalStateException e) {
8508 Slog.w(TAG, "Failed parsing daily " + e);
8509 } catch (NullPointerException e) {
8510 Slog.w(TAG, "Failed parsing daily " + e);
8511 } catch (NumberFormatException e) {
8512 Slog.w(TAG, "Failed parsing daily " + e);
8513 } catch (XmlPullParserException e) {
8514 Slog.w(TAG, "Failed parsing daily " + e);
8515 } catch (IOException e) {
8516 Slog.w(TAG, "Failed parsing daily " + e);
8517 } catch (IndexOutOfBoundsException e) {
8518 Slog.w(TAG, "Failed parsing daily " + e);
8519 }
8520 }
8521
8522 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
8523 XmlPullParserException, IOException {
8524 DailyItem dit = new DailyItem();
8525 String attr = parser.getAttributeValue(null, "start");
8526 if (attr != null) {
8527 dit.mStartTime = Long.parseLong(attr);
8528 }
8529 attr = parser.getAttributeValue(null, "end");
8530 if (attr != null) {
8531 dit.mEndTime = Long.parseLong(attr);
8532 }
8533 int outerDepth = parser.getDepth();
8534 int type;
8535 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
8536 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
8537 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
8538 continue;
8539 }
8540
8541 String tagName = parser.getName();
8542 if (tagName.equals("dis")) {
8543 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
8544 } else if (tagName.equals("chg")) {
8545 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -07008546 } else if (tagName.equals("upd")) {
8547 if (dit.mPackageChanges == null) {
8548 dit.mPackageChanges = new ArrayList<>();
8549 }
8550 PackageChange pc = new PackageChange();
8551 pc.mUpdate = true;
8552 pc.mPackageName = parser.getAttributeValue(null, "pkg");
8553 String verStr = parser.getAttributeValue(null, "ver");
8554 pc.mVersionCode = verStr != null ? Integer.parseInt(verStr) : 0;
8555 dit.mPackageChanges.add(pc);
8556 XmlUtils.skipCurrentTag(parser);
8557 } else if (tagName.equals("rem")) {
8558 if (dit.mPackageChanges == null) {
8559 dit.mPackageChanges = new ArrayList<>();
8560 }
8561 PackageChange pc = new PackageChange();
8562 pc.mUpdate = false;
8563 pc.mPackageName = parser.getAttributeValue(null, "pkg");
8564 dit.mPackageChanges.add(pc);
8565 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008566 } else {
8567 Slog.w(TAG, "Unknown element under <item>: "
8568 + parser.getName());
8569 XmlUtils.skipCurrentTag(parser);
8570 }
8571 }
8572 mDailyItems.add(dit);
8573 }
8574
8575 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
8576 String tag)
8577 throws NumberFormatException, XmlPullParserException, IOException {
8578 final String numAttr = parser.getAttributeValue(null, "n");
8579 if (numAttr == null) {
8580 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
8581 XmlUtils.skipCurrentTag(parser);
8582 return;
8583 }
8584 final int num = Integer.parseInt(numAttr);
8585 LevelStepTracker steps = new LevelStepTracker(num);
8586 if (isCharge) {
8587 dit.mChargeSteps = steps;
8588 } else {
8589 dit.mDischargeSteps = steps;
8590 }
8591 int i = 0;
8592 int outerDepth = parser.getDepth();
8593 int type;
8594 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
8595 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
8596 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
8597 continue;
8598 }
8599
8600 String tagName = parser.getName();
8601 if ("s".equals(tagName)) {
8602 if (i < num) {
8603 String valueAttr = parser.getAttributeValue(null, "v");
8604 if (valueAttr != null) {
8605 steps.decodeEntryAt(i, valueAttr);
8606 i++;
8607 }
8608 }
8609 } else {
8610 Slog.w(TAG, "Unknown element under <" + tag + ">: "
8611 + parser.getName());
8612 XmlUtils.skipCurrentTag(parser);
8613 }
8614 }
8615 steps.mNumStepDurations = i;
8616 }
8617
8618 @Override
8619 public DailyItem getDailyItemLocked(int daysAgo) {
8620 int index = mDailyItems.size()-1-daysAgo;
8621 return index >= 0 ? mDailyItems.get(index) : null;
8622 }
8623
8624 @Override
8625 public long getCurrentDailyStartTime() {
8626 return mDailyStartTime;
8627 }
8628
8629 @Override
8630 public long getNextMinDailyDeadline() {
8631 return mNextMinDailyDeadline;
8632 }
8633
8634 @Override
8635 public long getNextMaxDailyDeadline() {
8636 return mNextMaxDailyDeadline;
8637 }
8638
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008639 @Override
8640 public boolean startIteratingOldHistoryLocked() {
8641 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
8642 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08008643 if ((mHistoryIterator = mHistory) == null) {
8644 return false;
8645 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008646 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -07008647 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008648 mReadOverflow = false;
8649 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08008650 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07008651 }
8652
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008653 @Override
8654 public boolean getNextOldHistoryLocked(HistoryItem out) {
8655 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
8656 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008657 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -07008658 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008659 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07008660 HistoryItem cur = mHistoryIterator;
8661 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008662 if (!mReadOverflow && !end) {
8663 Slog.w(TAG, "Old history ends before new history!");
8664 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07008665 return false;
8666 }
8667 out.setTo(cur);
8668 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008669 if (!mReadOverflow) {
8670 if (end) {
8671 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -07008672 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07008673 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008674 pw.println("Histories differ!");
8675 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -07008676 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008677 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -07008678 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
8679 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -07008680 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008681 }
8682 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07008683 return true;
8684 }
8685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008687 public void finishIteratingOldHistoryLocked() {
8688 mIteratingHistory = false;
8689 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08008690 mHistoryIterator = null;
8691 }
8692
8693 public int getHistoryTotalSize() {
8694 return MAX_HISTORY_BUFFER;
8695 }
8696
8697 public int getHistoryUsedSize() {
8698 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008699 }
8700
8701 @Override
8702 public boolean startIteratingHistoryLocked() {
8703 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
8704 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08008705 if (mHistoryBuffer.dataSize() <= 0) {
8706 return false;
8707 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008708 mHistoryBuffer.setDataPosition(0);
8709 mReadOverflow = false;
8710 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08008711 mReadHistoryStrings = new String[mHistoryTagPool.size()];
8712 mReadHistoryUids = new int[mHistoryTagPool.size()];
8713 mReadHistoryChars = 0;
8714 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
8715 final HistoryTag tag = ent.getKey();
8716 final int idx = ent.getValue();
8717 mReadHistoryStrings[idx] = tag.string;
8718 mReadHistoryUids[idx] = tag.uid;
8719 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -08008720 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08008721 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008722 }
8723
8724 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08008725 public int getHistoryStringPoolSize() {
8726 return mReadHistoryStrings.length;
8727 }
8728
8729 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08008730 public int getHistoryStringPoolBytes() {
8731 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
8732 // Each string character is 2 bytes.
8733 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
8734 }
8735
8736 @Override
8737 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08008738 return mReadHistoryStrings[index];
8739 }
8740
8741 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08008742 public int getHistoryTagPoolUid(int index) {
8743 return mReadHistoryUids[index];
8744 }
8745
8746 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008747 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -07008748 final int pos = mHistoryBuffer.dataPosition();
8749 if (pos == 0) {
8750 out.clear();
8751 }
8752 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008753 if (end) {
8754 return false;
8755 }
8756
Dianne Hackborn99009ea2014-04-18 16:23:42 -07008757 final long lastRealtime = out.time;
8758 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008759 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -07008760 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
8761 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -07008762 out.currentTime = lastWalltime + (out.time - lastRealtime);
8763 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008764 return true;
8765 }
8766
8767 @Override
8768 public void finishIteratingHistoryLocked() {
8769 mIteratingHistory = false;
8770 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -08008771 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07008772 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008773
Dianne Hackborn32907cf2010-06-10 17:50:20 -07008774 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -07008775 public long getHistoryBaseTime() {
8776 return mHistoryBaseTime;
8777 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008778
Dianne Hackbornb5e31652010-09-07 12:13:55 -07008779 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008780 public int getStartCount() {
8781 return mStartCount;
8782 }
8783
8784 public boolean isOnBattery() {
8785 return mOnBattery;
8786 }
8787
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07008788 public boolean isCharging() {
8789 return mCharging;
8790 }
8791
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008792 public boolean isScreenOn() {
Jeff Browne95c3cd2014-05-02 16:59:26 -07008793 return mScreenState == Display.STATE_ON;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008794 }
8795
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008796 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08008797 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008798 mOnBatteryTimeBase.init(uptime, realtime);
8799 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -07008800 mRealtime = 0;
8801 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008802 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -07008803 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008804 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008805
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08008806 void initDischarge() {
8807 mLowDischargeAmountSinceCharge = 0;
8808 mHighDischargeAmountSinceCharge = 0;
8809 mDischargeAmountScreenOn = 0;
8810 mDischargeAmountScreenOnSinceCharge = 0;
8811 mDischargeAmountScreenOff = 0;
8812 mDischargeAmountScreenOffSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008813 mDischargeStepTracker.init();
8814 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -07008815 mDischargeScreenOffCounter.reset(false);
8816 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08008817 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08008818
8819 public void resetAllStatsCmdLocked() {
8820 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -08008821 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07008822 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -08008823 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08008824 long realtime = mSecRealtime * 1000;
8825 mDischargeStartLevel = mHistoryCur.batteryLevel;
8826 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -07008827 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07008828 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
8829 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008830 mOnBatteryTimeBase.reset(uptime, realtime);
8831 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
8832 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07008833 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08008834 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
8835 mDischargeScreenOffUnplugLevel = 0;
8836 } else {
8837 mDischargeScreenOnUnplugLevel = 0;
8838 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
8839 }
8840 mDischargeAmountScreenOn = 0;
8841 mDischargeAmountScreenOff = 0;
8842 }
Dianne Hackborn40c87252014-03-19 16:55:40 -07008843 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08008844 }
8845
8846 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -07008847 final long uptimeMillis = mClocks.uptimeMillis();
8848 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008849 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -07008850 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008851 mScreenOnTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008852 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008853 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008854 }
Adam Lesinski1a76a622016-06-22 10:28:47 -07008855
8856 if (mPowerProfile != null) {
8857 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
8858 } else {
8859 mEstimatedBatteryCapacity = -1;
8860 }
Jeff Browne95c3cd2014-05-02 16:59:26 -07008861 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07008862 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -07008863 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07008864 mLongestLightIdleTime = 0;
8865 mLongestFullIdleTime = 0;
8866 mDeviceIdleModeLightTimer.reset(false);
8867 mDeviceIdleModeFullTimer.reset(false);
8868 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07008869 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008870 mPhoneOnTimer.reset(false);
8871 mAudioOnTimer.reset(false);
8872 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07008873 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008874 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008875 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -08008876 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008877 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008878 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008879 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008880 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008881 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008882 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008883 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008884 mNetworkByteActivityCounters[i].reset(false);
8885 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008886 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008887 mMobileRadioActiveTimer.reset(false);
8888 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07008889 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008890 mMobileRadioActiveUnknownTime.reset(false);
8891 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008892 mWifiOnTimer.reset(false);
8893 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08008894 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008895 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08008896 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07008897 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
8898 mWifiSupplStateTimer[i].reset(false);
8899 }
8900 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
8901 mWifiSignalStrengthsTimer[i].reset(false);
8902 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008903 mWifiActivity.reset(false);
8904 mBluetoothActivity.reset(false);
8905 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008906 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008907
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008908 for (int i=0; i<mUidStats.size(); i++) {
8909 if (mUidStats.valueAt(i).reset()) {
8910 mUidStats.remove(mUidStats.keyAt(i));
8911 i--;
8912 }
8913 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008914
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008915 if (mKernelWakelockStats.size() > 0) {
8916 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008917 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008918 }
8919 mKernelWakelockStats.clear();
8920 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07008921
James Carr3a226052016-07-01 14:49:52 -07008922 if (mKernelMemoryStats.size() > 0) {
8923 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
8924 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
8925 }
8926 mKernelMemoryStats.clear();
8927 }
8928
Dianne Hackborna1bd7922014-03-21 11:07:11 -07008929 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07008930 for (SamplingTimer timer : mWakeupReasonStats.values()) {
8931 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07008932 }
8933 mWakeupReasonStats.clear();
8934 }
8935
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008936 mLastHistoryStepDetails = null;
8937 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
8938 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
8939 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
8940 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
8941 mLastStepStatUserTime = mCurStepStatUserTime = 0;
8942 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
8943 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
8944 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
8945 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
8946 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
8947
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08008948 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008949
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008950 clearHistoryLocked();
8951 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008952
Dianne Hackborn40c87252014-03-19 16:55:40 -07008953 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08008954 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07008955 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
8956 // Not recording process starts/stops.
8957 continue;
8958 }
Dianne Hackborn37de0982014-05-09 09:32:18 -07008959 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08008960 if (active == null) {
8961 continue;
8962 }
Dianne Hackborn37de0982014-05-09 09:32:18 -07008963 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
8964 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08008965 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -07008966 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
8967 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08008968 }
8969 }
8970 }
8971 }
8972
Dianne Hackborn32de2f62011-03-09 14:03:35 -08008973 void updateDischargeScreenLevelsLocked(boolean oldScreenOn, boolean newScreenOn) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08008974 if (oldScreenOn) {
8975 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
8976 if (diff > 0) {
8977 mDischargeAmountScreenOn += diff;
8978 mDischargeAmountScreenOnSinceCharge += diff;
8979 }
8980 } else {
8981 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
8982 if (diff > 0) {
8983 mDischargeAmountScreenOff += diff;
8984 mDischargeAmountScreenOffSinceCharge += diff;
8985 }
8986 }
8987 if (newScreenOn) {
8988 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
8989 mDischargeScreenOffUnplugLevel = 0;
8990 } else {
8991 mDischargeScreenOnUnplugLevel = 0;
8992 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
8993 }
8994 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07008995
Dianne Hackborna7c837f2014-01-15 16:20:44 -08008996 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08008997 if (mOnBatteryInternal) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07008998 final boolean screenOn = mScreenState == Display.STATE_ON;
8999 updateDischargeScreenLevelsLocked(screenOn, screenOn);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08009000 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -08009001 }
9002
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009003 private String[] mMobileIfaces = EmptyArray.STRING;
9004 private String[] mWifiIfaces = EmptyArray.STRING;
9005
9006 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
9007
9008 private static final int NETWORK_STATS_LAST = 0;
9009 private static final int NETWORK_STATS_NEXT = 1;
9010 private static final int NETWORK_STATS_DELTA = 2;
9011
Joe Onoratoabded112016-02-08 16:49:39 -08009012 private NetworkStats[] mMobileNetworkStats;
9013 private NetworkStats[] mWifiNetworkStats;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009014
9015 /**
9016 * Retrieves the delta of network stats for the given network ifaces. Uses networkStatsBuffer
9017 * as a buffer of NetworkStats objects to cycle through when computing deltas.
9018 */
9019 private NetworkStats getNetworkStatsDeltaLocked(String[] ifaces,
9020 NetworkStats[] networkStatsBuffer)
9021 throws IOException {
9022 if (!SystemProperties.getBoolean(NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED,
9023 false)) {
9024 return null;
9025 }
9026
9027 final NetworkStats stats = mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL,
9028 ifaces, NetworkStats.TAG_NONE, networkStatsBuffer[NETWORK_STATS_NEXT]);
9029 networkStatsBuffer[NETWORK_STATS_DELTA] = NetworkStats.subtract(stats,
9030 networkStatsBuffer[NETWORK_STATS_LAST], null, null,
9031 networkStatsBuffer[NETWORK_STATS_DELTA]);
9032 networkStatsBuffer[NETWORK_STATS_NEXT] = networkStatsBuffer[NETWORK_STATS_LAST];
9033 networkStatsBuffer[NETWORK_STATS_LAST] = stats;
9034 return networkStatsBuffer[NETWORK_STATS_DELTA];
9035 }
9036
9037 /**
9038 * Distribute WiFi energy info and network traffic to apps.
9039 * @param info The energy information from the WiFi controller.
9040 */
9041 public void updateWifiStateLocked(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009042 if (DEBUG_ENERGY) {
9043 Slog.d(TAG, "Updating wifi stats");
9044 }
9045
Joe Onoratoabded112016-02-08 16:49:39 -08009046 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinskie08af192015-03-25 16:42:59 -07009047 NetworkStats delta = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009048 try {
Adam Lesinskie08af192015-03-25 16:42:59 -07009049 if (!ArrayUtils.isEmpty(mWifiIfaces)) {
9050 delta = getNetworkStatsDeltaLocked(mWifiIfaces, mWifiNetworkStats);
9051 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009052 } catch (IOException e) {
9053 Slog.wtf(TAG, "Failed to get wifi network stats", e);
9054 return;
9055 }
9056
9057 if (!mOnBatteryInternal) {
9058 return;
9059 }
9060
Adam Lesinskie08af192015-03-25 16:42:59 -07009061 SparseLongArray rxPackets = new SparseLongArray();
9062 SparseLongArray txPackets = new SparseLongArray();
9063 long totalTxPackets = 0;
9064 long totalRxPackets = 0;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009065 if (delta != null) {
9066 final int size = delta.size();
9067 for (int i = 0; i < size; i++) {
9068 final NetworkStats.Entry entry = delta.getValues(i, mTmpNetworkStatsEntry);
9069
Adam Lesinskie08af192015-03-25 16:42:59 -07009070 if (DEBUG_ENERGY) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009071 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
Adam Lesinskie08af192015-03-25 16:42:59 -07009072 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
9073 + " txPackets=" + entry.txPackets);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009074 }
9075
Adam Lesinski6cca4142016-02-25 18:23:02 -08009076 if (entry.rxBytes == 0 && entry.txBytes == 0) {
9077 // Skip the lookup below since there is no work to do.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009078 continue;
9079 }
9080
9081 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinskiba88e682015-12-08 12:06:55 -08009082 if (entry.rxBytes != 0) {
9083 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
9084 entry.rxPackets);
Amith Yamasani59fe8412017-03-03 16:28:52 -08009085 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
9086 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
9087 entry.rxPackets);
9088 }
Adam Lesinskiba88e682015-12-08 12:06:55 -08009089 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
9090 entry.rxBytes);
9091 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
9092 entry.rxPackets);
Adam Lesinskie08af192015-03-25 16:42:59 -07009093
Adam Lesinskiba88e682015-12-08 12:06:55 -08009094 rxPackets.put(u.getUid(), entry.rxPackets);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009095
Adam Lesinskiba88e682015-12-08 12:06:55 -08009096 // Sum the total number of packets so that the Rx Power can
9097 // be evenly distributed amongst the apps.
9098 totalRxPackets += entry.rxPackets;
9099 }
9100
9101 if (entry.txBytes != 0) {
9102 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
9103 entry.txPackets);
Amith Yamasani59fe8412017-03-03 16:28:52 -08009104 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
9105 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
9106 entry.txPackets);
9107 }
Adam Lesinskiba88e682015-12-08 12:06:55 -08009108 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
9109 entry.txBytes);
9110 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
9111 entry.txPackets);
9112
9113 txPackets.put(u.getUid(), entry.txPackets);
9114
9115 // Sum the total number of packets so that the Tx Power can
9116 // be evenly distributed amongst the apps.
9117 totalTxPackets += entry.txPackets;
9118 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009119 }
9120 }
9121
9122 if (info != null) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009123 mHasWifiReporting = true;
Adam Lesinski17390762015-04-10 13:17:47 -07009124
Adam Lesinskie08af192015-03-25 16:42:59 -07009125 // Measured in mAms
9126 final long txTimeMs = info.getControllerTxTimeMillis();
9127 final long rxTimeMs = info.getControllerRxTimeMillis();
9128 final long idleTimeMs = info.getControllerIdleTimeMillis();
9129 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
9130
9131 long leftOverRxTimeMs = rxTimeMs;
Mitchell Willsf9016492015-07-29 17:47:44 -07009132 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -07009133
9134 if (DEBUG_ENERGY) {
9135 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
9136 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
9137 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
9138 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
9139 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
9140 }
9141
9142 long totalWifiLockTimeMs = 0;
9143 long totalScanTimeMs = 0;
9144
9145 // On the first pass, collect some totals so that we can normalize power
9146 // calculations if we need to.
9147 final int uidStatsSize = mUidStats.size();
9148 for (int i = 0; i < uidStatsSize; i++) {
9149 final Uid uid = mUidStats.valueAt(i);
9150
9151 // Sum the total scan power for all apps.
Bookatz867c0d72017-03-07 18:23:42 -08009152 totalScanTimeMs += uid.mWifiScanTimer.getMainTimer().getTimeSinceMarkLocked(
Adam Lesinskie08af192015-03-25 16:42:59 -07009153 elapsedRealtimeMs * 1000) / 1000;
9154
9155 // Sum the total time holding wifi lock for all apps.
9156 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
9157 elapsedRealtimeMs * 1000) / 1000;
9158 }
9159
9160 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
9161 Slog.d(TAG, " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
9162 + rxTimeMs + " ms). Normalizing scan time.");
9163 }
Mitchell Willsf9016492015-07-29 17:47:44 -07009164 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
9165 Slog.d(TAG, " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
9166 + txTimeMs + " ms). Normalizing scan time.");
9167 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009168
9169 // Actually assign and distribute power usage to apps.
9170 for (int i = 0; i < uidStatsSize; i++) {
9171 final Uid uid = mUidStats.valueAt(i);
9172
Bookatz867c0d72017-03-07 18:23:42 -08009173 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getMainTimer().getTimeSinceMarkLocked(
Adam Lesinskie08af192015-03-25 16:42:59 -07009174 elapsedRealtimeMs * 1000) / 1000;
9175 if (scanTimeSinceMarkMs > 0) {
9176 // Set the new mark so that next time we get new data since this point.
9177 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
9178
Mitchell Willsf9016492015-07-29 17:47:44 -07009179 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
9180 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
9181
9182 // Our total scan time is more than the reported Tx/Rx time.
9183 // This is possible because the cost of a scan is approximate.
9184 // Let's normalize the result so that we evenly blame each app
9185 // scanning.
9186 //
9187 // This means that we may have apps that transmitted/received packets not be
9188 // blamed for this, but this is fine as scans are relatively more expensive.
Adam Lesinskie08af192015-03-25 16:42:59 -07009189 if (totalScanTimeMs > rxTimeMs) {
Mitchell Willsf9016492015-07-29 17:47:44 -07009190 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
9191 totalScanTimeMs;
9192 }
9193 if (totalScanTimeMs > txTimeMs) {
9194 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
9195 totalScanTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -07009196 }
9197
9198 if (DEBUG_ENERGY) {
Mitchell Willsf9016492015-07-29 17:47:44 -07009199 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
9200 + scanRxTimeSinceMarkMs + " ms Tx:"
9201 + scanTxTimeSinceMarkMs + " ms)");
Adam Lesinskie08af192015-03-25 16:42:59 -07009202 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009203
9204 ControllerActivityCounterImpl activityCounter =
9205 uid.getOrCreateWifiControllerActivityLocked();
9206 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
9207 activityCounter.getTxTimeCounters()[0].addCountLocked(scanTxTimeSinceMarkMs);
Mitchell Willsf9016492015-07-29 17:47:44 -07009208 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
9209 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
Adam Lesinskie08af192015-03-25 16:42:59 -07009210 }
9211
9212 // Distribute evenly the power consumed while Idle to each app holding a WiFi
9213 // lock.
9214 final long wifiLockTimeSinceMarkMs = uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
9215 elapsedRealtimeMs * 1000) / 1000;
9216 if (wifiLockTimeSinceMarkMs > 0) {
9217 // Set the new mark so that next time we get new data since this point.
9218 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
9219
9220 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
9221 / totalWifiLockTimeMs;
9222 if (DEBUG_ENERGY) {
9223 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
9224 + myIdleTimeMs + " ms");
9225 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009226 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
9227 .addCountLocked(myIdleTimeMs);
Adam Lesinskie08af192015-03-25 16:42:59 -07009228 }
9229 }
9230
9231 if (DEBUG_ENERGY) {
9232 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
Mitchell Willsf9016492015-07-29 17:47:44 -07009233 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -07009234 }
9235
Mitchell Willsf9016492015-07-29 17:47:44 -07009236 // Distribute the remaining Tx power appropriately between all apps that transmitted
9237 // packets.
Adam Lesinskie08af192015-03-25 16:42:59 -07009238 for (int i = 0; i < txPackets.size(); i++) {
9239 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
Mitchell Willsf9016492015-07-29 17:47:44 -07009240 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs) / totalTxPackets;
Adam Lesinskie08af192015-03-25 16:42:59 -07009241 if (DEBUG_ENERGY) {
9242 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
9243 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009244 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
9245 .addCountLocked(myTxTimeMs);
Adam Lesinskie08af192015-03-25 16:42:59 -07009246 }
9247
9248 // Distribute the remaining Rx power appropriately between all apps that received
9249 // packets.
9250 for (int i = 0; i < rxPackets.size(); i++) {
9251 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
9252 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs) / totalRxPackets;
9253 if (DEBUG_ENERGY) {
9254 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
9255 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009256 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
9257 .addCountLocked(myRxTimeMs);
Adam Lesinskie08af192015-03-25 16:42:59 -07009258 }
9259
9260 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
9261
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009262 // Update WiFi controller stats.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009263 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
9264 mWifiActivity.getTxTimeCounters()[0].addCountLocked(info.getControllerTxTimeMillis());
9265 mWifiActivity.getIdleTimeCounter().addCountLocked(info.getControllerIdleTimeMillis());
Adam Lesinskie08af192015-03-25 16:42:59 -07009266
Adam Lesinski8576cf92015-06-09 12:48:25 -07009267 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
9268 final double opVolt = mPowerProfile.getAveragePower(
9269 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
9270 if (opVolt != 0) {
9271 // We store the power drain as mAms.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009272 mWifiActivity.getPowerCounter().addCountLocked(
Adam Lesinski8576cf92015-06-09 12:48:25 -07009273 (long)(info.getControllerEnergyUsed() / opVolt));
Adam Lesinskie08af192015-03-25 16:42:59 -07009274 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009275 }
9276 }
9277
9278 /**
9279 * Distribute Cell radio energy info and network traffic to apps.
9280 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009281 public void updateMobileRadioStateLocked(final long elapsedRealtimeMs,
9282 final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009283 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009284 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009285 }
9286
Adam Lesinskie08af192015-03-25 16:42:59 -07009287 NetworkStats delta = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009288 try {
Adam Lesinskie08af192015-03-25 16:42:59 -07009289 if (!ArrayUtils.isEmpty(mMobileIfaces)) {
9290 delta = getNetworkStatsDeltaLocked(mMobileIfaces, mMobileNetworkStats);
9291 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009292 } catch (IOException e) {
9293 Slog.wtf(TAG, "Failed to get mobile network stats", e);
9294 return;
9295 }
9296
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009297 if (!mOnBatteryInternal) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009298 return;
9299 }
9300
Adam Lesinskie08af192015-03-25 16:42:59 -07009301 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
9302 elapsedRealtimeMs * 1000);
9303 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009304
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009305 long totalRxPackets = 0;
9306 long totalTxPackets = 0;
9307 if (delta != null) {
9308 final int size = delta.size();
9309 for (int i = 0; i < size; i++) {
9310 final NetworkStats.Entry entry = delta.getValues(i, mTmpNetworkStatsEntry);
Adam Lesinskia4268172016-01-29 12:13:54 -08009311 if (entry.rxPackets == 0 && entry.txPackets == 0) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009312 continue;
9313 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009314
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009315 if (DEBUG_ENERGY) {
9316 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
9317 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
9318 + " txPackets=" + entry.txPackets);
9319 }
9320
9321 totalRxPackets += entry.rxPackets;
9322 totalTxPackets += entry.txPackets;
9323
9324 final Uid u = getUidStatsLocked(mapUid(entry.uid));
9325 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes, entry.rxPackets);
9326 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes, entry.txPackets);
Amith Yamasani59fe8412017-03-03 16:28:52 -08009327 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
9328 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
9329 entry.rxBytes, entry.rxPackets);
9330 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
9331 entry.txBytes, entry.txPackets);
9332 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009333
9334 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
9335 entry.rxBytes);
9336 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
9337 entry.txBytes);
9338 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
9339 entry.rxPackets);
9340 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
9341 entry.txPackets);
Adam Lesinskie08af192015-03-25 16:42:59 -07009342 }
9343
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009344 // Now distribute proportional blame to the apps that did networking.
9345 long totalPackets = totalRxPackets + totalTxPackets;
9346 if (totalPackets > 0) {
9347 for (int i = 0; i < size; i++) {
9348 final NetworkStats.Entry entry = delta.getValues(i, mTmpNetworkStatsEntry);
9349 if (entry.rxPackets == 0 && entry.txPackets == 0) {
9350 continue;
9351 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009352
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009353 final Uid u = getUidStatsLocked(mapUid(entry.uid));
9354
9355 // Distribute total radio active time in to this app.
9356 final long appPackets = entry.rxPackets + entry.txPackets;
9357 final long appRadioTime = (radioTime * appPackets) / totalPackets;
9358 u.noteMobileRadioActiveTimeLocked(appRadioTime);
9359
9360 // Remove this app from the totals, so that we don't lose any time
9361 // due to rounding.
9362 radioTime -= appRadioTime;
9363 totalPackets -= appPackets;
9364
9365 if (activityInfo != null) {
9366 ControllerActivityCounterImpl activityCounter =
9367 u.getOrCreateModemControllerActivityLocked();
Adam Lesinskia4268172016-01-29 12:13:54 -08009368 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009369 final long rxMs = (entry.rxPackets * activityInfo.getRxTimeMillis())
9370 / totalRxPackets;
9371 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
9372 }
9373
Adam Lesinskia4268172016-01-29 12:13:54 -08009374 if (totalTxPackets > 0 && entry.txPackets > 0) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009375 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
9376 long txMs = entry.txPackets * activityInfo.getTxTimeMillis()[lvl];
9377 txMs /= totalTxPackets;
9378 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
9379 }
9380 }
9381 }
9382 }
9383 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009384
9385 if (radioTime > 0) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009386 // Whoops, there is some radio time we can't blame on an app!
9387 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
9388 mMobileRadioActiveUnknownCount.addCountLocked(1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009389 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009390 }
9391
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009392 if (activityInfo != null) {
9393 mHasModemReporting = true;
9394 mModemActivity.getIdleTimeCounter().addCountLocked(activityInfo.getIdleTimeMillis());
9395 mModemActivity.getRxTimeCounter().addCountLocked(activityInfo.getRxTimeMillis());
9396 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
9397 mModemActivity.getTxTimeCounters()[lvl]
9398 .addCountLocked(activityInfo.getTxTimeMillis()[lvl]);
9399 }
9400
9401 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
9402 final double opVolt = mPowerProfile.getAveragePower(
9403 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
9404 if (opVolt != 0) {
9405 // We store the power drain as mAms.
9406 mModemActivity.getPowerCounter().addCountLocked(
9407 (long) (activityInfo.getEnergyUsed() / opVolt));
9408 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009409 }
9410 }
9411
9412 /**
9413 * Distribute Bluetooth energy info and network traffic to apps.
9414 * @param info The energy information from the bluetooth controller.
9415 */
9416 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009417 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -08009418 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009419 }
9420
Adam Lesinski9f55cc72016-01-27 20:42:14 -08009421 if (info == null || !mOnBatteryInternal) {
9422 return;
9423 }
Adam Lesinskie283d332015-04-16 12:29:25 -07009424
Adam Lesinski9f55cc72016-01-27 20:42:14 -08009425 mHasBluetoothReporting = true;
9426
Bookatz867c0d72017-03-07 18:23:42 -08009427 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08009428 final long rxTimeMs = info.getControllerRxTimeMillis();
9429 final long txTimeMs = info.getControllerTxTimeMillis();
9430
9431 if (DEBUG_ENERGY) {
9432 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
9433 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
9434 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
9435 Slog.d(TAG, " Idle Time: " + info.getControllerIdleTimeMillis() + " ms");
9436 }
9437
9438 long totalScanTimeMs = 0;
9439
9440 final int uidCount = mUidStats.size();
9441 for (int i = 0; i < uidCount; i++) {
9442 final Uid u = mUidStats.valueAt(i);
9443 if (u.mBluetoothScanTimer == null) {
9444 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -07009445 }
Adam Lesinski50e47602015-12-04 17:04:54 -08009446
Bookatz867c0d72017-03-07 18:23:42 -08009447 totalScanTimeMs += u.mBluetoothScanTimer.getMainTimer().getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -08009448 elapsedRealtimeMs * 1000) / 1000;
9449 }
9450
9451 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
9452 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
9453
9454 if (DEBUG_ENERGY) {
9455 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
9456 + " TX=" + normalizeScanTxTime);
9457 }
9458
9459 long leftOverRxTimeMs = rxTimeMs;
9460 long leftOverTxTimeMs = txTimeMs;
9461
9462 for (int i = 0; i < uidCount; i++) {
9463 final Uid u = mUidStats.valueAt(i);
9464 if (u.mBluetoothScanTimer == null) {
9465 continue;
9466 }
9467
Bookatz867c0d72017-03-07 18:23:42 -08009468 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getMainTimer().getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -08009469 elapsedRealtimeMs * 1000) / 1000;
9470 if (scanTimeSinceMarkMs > 0) {
9471 // Set the new mark so that next time we get new data since this point.
9472 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
9473
9474 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
9475 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
9476
9477 if (normalizeScanRxTime) {
9478 // Scan time is longer than the total rx time in the controller,
9479 // so distribute the scan time proportionately. This means regular traffic
9480 // will not blamed, but scans are more expensive anyways.
9481 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
9482 }
9483
9484 if (normalizeScanTxTime) {
9485 // Scan time is longer than the total tx time in the controller,
9486 // so distribute the scan time proportionately. This means regular traffic
9487 // will not blamed, but scans are more expensive anyways.
9488 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
9489 }
9490
9491 final ControllerActivityCounterImpl counter =
9492 u.getOrCreateBluetoothControllerActivityLocked();
9493 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
9494 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
9495
9496 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
9497 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
9498 }
9499 }
9500
9501 if (DEBUG_ENERGY) {
9502 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
9503 + " TX=" + leftOverTxTimeMs);
9504 }
9505
9506 //
9507 // Now distribute blame to apps that did bluetooth traffic.
9508 //
9509
9510 long totalTxBytes = 0;
9511 long totalRxBytes = 0;
9512
9513 final UidTraffic[] uidTraffic = info.getUidTraffic();
9514 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
9515 for (int i = 0; i < numUids; i++) {
9516 final UidTraffic traffic = uidTraffic[i];
9517
9518 // Add to the global counters.
9519 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
9520 traffic.getRxBytes());
9521 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
9522 traffic.getTxBytes());
9523
9524 // Add to the UID counters.
9525 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
9526 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
9527 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
9528
9529 // Calculate the total traffic.
9530 totalTxBytes += traffic.getTxBytes();
9531 totalRxBytes += traffic.getRxBytes();
9532 }
9533
9534 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
9535 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Adam Lesinski50e47602015-12-04 17:04:54 -08009536 for (int i = 0; i < numUids; i++) {
9537 final UidTraffic traffic = uidTraffic[i];
9538
Adam Lesinski50e47602015-12-04 17:04:54 -08009539 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -08009540 final ControllerActivityCounterImpl counter =
9541 u.getOrCreateBluetoothControllerActivityLocked();
9542
9543 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
9544 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
9545
9546 if (DEBUG_ENERGY) {
9547 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
9548 + " rx_time=" + timeRxMs);
9549 }
9550 counter.getRxTimeCounter().addCountLocked(timeRxMs);
9551 leftOverRxTimeMs -= timeRxMs;
9552 }
9553
9554 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
9555 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
9556
9557 if (DEBUG_ENERGY) {
9558 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
9559 + " tx_time=" + timeTxMs);
9560 }
9561
9562 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
9563 leftOverTxTimeMs -= timeTxMs;
9564 }
Adam Lesinski50e47602015-12-04 17:04:54 -08009565 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009566 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08009567
9568 mBluetoothActivity.getRxTimeCounter().addCountLocked(
9569 info.getControllerRxTimeMillis());
9570 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(
9571 info.getControllerTxTimeMillis());
9572 mBluetoothActivity.getIdleTimeCounter().addCountLocked(
9573 info.getControllerIdleTimeMillis());
9574
9575 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
9576 final double opVolt = mPowerProfile.getAveragePower(
9577 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
9578 if (opVolt != 0) {
9579 // We store the power drain as mAms.
9580 mBluetoothActivity.getPowerCounter().addCountLocked(
9581 (long) (info.getControllerEnergyUsed() / opVolt));
9582 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009583 }
9584
9585 /**
9586 * Read and distribute kernel wake lock use across apps.
9587 */
9588 public void updateKernelWakelocksLocked() {
9589 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
9590 mTmpWakelockStats);
9591 if (wakelockStats == null) {
9592 // Not crashing might make board bringup easier.
9593 Slog.w(TAG, "Couldn't get kernel wake lock stats");
9594 return;
9595 }
9596
9597 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
9598 String name = ent.getKey();
9599 KernelWakelockStats.Entry kws = ent.getValue();
9600
9601 SamplingTimer kwlt = mKernelWakelockStats.get(name);
9602 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07009603 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009604 mKernelWakelockStats.put(name, kwlt);
9605 }
Adam Lesinskid84ad302016-05-17 18:31:02 -07009606
Adam Lesinski757c6ea2016-04-21 09:55:41 -07009607 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009608 kwlt.setUpdateVersion(kws.mVersion);
9609 }
9610
Adam Lesinskifbabe7d2015-08-03 14:37:38 -07009611 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -07009612 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
9613 // this time.
9614 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
9615 SamplingTimer st = ent.getValue();
9616 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
9617 st.endSample();
9618 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009619 }
9620 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -07009621
Adam Lesinskid84ad302016-05-17 18:31:02 -07009622 // Record whether we've seen a non-zero time (for debugging b/22716723).
9623 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -07009624 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
9625 }
9626
9627 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
9628 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
9629 wakelockStats.kernelWakelockVersion);
9630 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009631 }
9632
Adam Lesinski72478f02015-06-17 15:39:43 -07009633 // We use an anonymous class to access these variables,
9634 // so they can't live on the stack or they'd have to be
9635 // final MutableLong objects (more allocations).
9636 // Used in updateCpuTimeLocked().
9637 long mTempTotalCpuUserTimeUs;
9638 long mTempTotalCpuSystemTimeUs;
9639
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009640 /**
James Carr3a226052016-07-01 14:49:52 -07009641 * Reads the newest memory stats from the kernel.
9642 */
9643 public void updateKernelMemoryBandwidthLocked() {
9644 mKernelMemoryBandwidthStats.updateStats();
9645 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
9646 final int bandwidthEntryCount = bandwidthEntries.size();
9647 int index;
9648 for (int i = 0; i < bandwidthEntryCount; i++) {
9649 SamplingTimer timer;
9650 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
9651 timer = mKernelMemoryStats.valueAt(index);
9652 } else {
9653 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
9654 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
9655 }
9656 timer.update(bandwidthEntries.valueAt(i), 1);
9657 if (DEBUG_MEMORY) {
9658 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
9659 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
9660 mKernelMemoryStats.get(
9661 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
9662 mKernelMemoryStats.size()));
9663 }
9664 }
9665 }
9666
9667 /**
Adam Lesinski72478f02015-06-17 15:39:43 -07009668 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
9669 * and we are on battery with screen off, we give more of the cpu time to those apps holding
9670 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009671 */
Adam Lesinski72478f02015-06-17 15:39:43 -07009672 public void updateCpuTimeLocked() {
Adam Lesinski52290c9c2015-09-21 16:54:52 -07009673 if (mPowerProfile == null) {
9674 return;
9675 }
9676
Adam Lesinski72478f02015-06-17 15:39:43 -07009677 if (DEBUG_ENERGY_CPU) {
9678 Slog.d(TAG, "!Cpu updating!");
9679 }
9680
9681 // Holding a wakelock costs more than just using the cpu.
9682 // Currently, we assign only half the cpu time to an app that is running but
9683 // not holding a wakelock. The apps holding wakelocks get the rest of the blame.
9684 // If no app is holding a wakelock, then the distribution is normal.
9685 final int wakelockWeight = 50;
9686
Adam Lesinski6832f392015-09-05 18:05:40 -07009687 // Read the time spent for each cluster at various cpu frequencies.
9688 final long[][] clusterSpeeds = new long[mKernelCpuSpeedReaders.length][];
9689 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
9690 clusterSpeeds[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
9691 }
Adam Lesinski72478f02015-06-17 15:39:43 -07009692
9693 int numWakelocks = 0;
9694
9695 // Calculate how many wakelocks we have to distribute amongst. The system is excluded.
9696 // Only distribute cpu power to wakelocks if the screen is off and we're on battery.
9697 final int numPartialTimers = mPartialTimers.size();
9698 if (mOnBatteryScreenOffTimeBase.isRunning()) {
9699 for (int i = 0; i < numPartialTimers; i++) {
9700 final StopwatchTimer timer = mPartialTimers.get(i);
9701 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
9702 // Since the collection and blaming of wakelocks can be scheduled to run after
9703 // some delay, the mPartialTimers list may have new entries. We can't blame
9704 // the newly added timer for past cpu time, so we only consider timers that
9705 // were present for one round of collection. Once a timer has gone through
9706 // a round of collection, its mInList field is set to true.
9707 numWakelocks++;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009708 }
Adam Lesinski72478f02015-06-17 15:39:43 -07009709 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009710 }
Adam Lesinski72478f02015-06-17 15:39:43 -07009711
9712 final int numWakelocksF = numWakelocks;
9713 mTempTotalCpuUserTimeUs = 0;
9714 mTempTotalCpuSystemTimeUs = 0;
9715
9716 // Read the CPU data for each UID. This will internally generate a snapshot so next time
9717 // we read, we get a delta. If we are to distribute the cpu time, then do so. Otherwise
9718 // we just ignore the data.
Joe Onoratoabded112016-02-08 16:49:39 -08009719 final long startTimeMs = mClocks.elapsedRealtime();
Adam Lesinski72478f02015-06-17 15:39:43 -07009720 mKernelUidCpuTimeReader.readDelta(!mOnBatteryInternal ? null :
9721 new KernelUidCpuTimeReader.Callback() {
9722 @Override
Adam Lesinskia7a4ccc2015-06-26 17:43:04 -07009723 public void onUidCpuTime(int uid, long userTimeUs, long systemTimeUs,
9724 long powerMaUs) {
Adam Lesinski72478f02015-06-17 15:39:43 -07009725 final Uid u = getUidStatsLocked(mapUid(uid));
9726
9727 // Accumulate the total system and user time.
9728 mTempTotalCpuUserTimeUs += userTimeUs;
9729 mTempTotalCpuSystemTimeUs += systemTimeUs;
9730
9731 StringBuilder sb = null;
9732 if (DEBUG_ENERGY_CPU) {
9733 sb = new StringBuilder();
9734 sb.append(" got time for uid=").append(u.mUid).append(": u=");
9735 TimeUtils.formatDuration(userTimeUs / 1000, sb);
9736 sb.append(" s=");
9737 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
Adam Lesinskia7a4ccc2015-06-26 17:43:04 -07009738 sb.append(" p=").append(powerMaUs / 1000).append("mAms\n");
Adam Lesinski72478f02015-06-17 15:39:43 -07009739 }
9740
9741 if (numWakelocksF > 0) {
9742 // We have wakelocks being held, so only give a portion of the
9743 // time to the process. The rest will be distributed among wakelock
9744 // holders.
9745 userTimeUs = (userTimeUs * wakelockWeight) / 100;
9746 systemTimeUs = (systemTimeUs * wakelockWeight) / 100;
9747 }
9748
9749 if (sb != null) {
9750 sb.append(" adding to uid=").append(u.mUid).append(": u=");
9751 TimeUtils.formatDuration(userTimeUs / 1000, sb);
9752 sb.append(" s=");
9753 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
Adam Lesinskia7a4ccc2015-06-26 17:43:04 -07009754 sb.append(" p=").append(powerMaUs / 1000).append("mAms");
Adam Lesinski72478f02015-06-17 15:39:43 -07009755 Slog.d(TAG, sb.toString());
9756 }
9757
9758 u.mUserCpuTime.addCountLocked(userTimeUs);
9759 u.mSystemCpuTime.addCountLocked(systemTimeUs);
Adam Lesinskia7a4ccc2015-06-26 17:43:04 -07009760 u.mCpuPower.addCountLocked(powerMaUs);
Adam Lesinski72478f02015-06-17 15:39:43 -07009761
9762 // Add the cpu speeds to this UID. These are used as a ratio
9763 // for computing the power this UID used.
Adam Lesinski52290c9c2015-09-21 16:54:52 -07009764 final int numClusters = mPowerProfile.getNumCpuClusters();
9765 if (u.mCpuClusterSpeed == null || u.mCpuClusterSpeed.length !=
9766 numClusters) {
9767 u.mCpuClusterSpeed = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07009768 }
9769
9770 for (int cluster = 0; cluster < clusterSpeeds.length; cluster++) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -07009771 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(
9772 cluster);
9773 if (u.mCpuClusterSpeed[cluster] == null || speedsInCluster !=
9774 u.mCpuClusterSpeed[cluster].length) {
Adam Lesinski6832f392015-09-05 18:05:40 -07009775 u.mCpuClusterSpeed[cluster] =
Adam Lesinski52290c9c2015-09-21 16:54:52 -07009776 new LongSamplingCounter[speedsInCluster];
Adam Lesinski72478f02015-06-17 15:39:43 -07009777 }
Adam Lesinski6832f392015-09-05 18:05:40 -07009778
9779 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeed[cluster];
9780 for (int speed = 0; speed < clusterSpeeds[cluster].length; speed++) {
9781 if (cpuSpeeds[speed] == null) {
9782 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
9783 }
9784 cpuSpeeds[speed].addCountLocked(clusterSpeeds[cluster][speed]);
9785 }
Adam Lesinski72478f02015-06-17 15:39:43 -07009786 }
9787 }
9788 });
9789
Amith Yamasanid2450862017-02-07 15:58:24 -08009790 // TODO: STOPSHIP, remove the "true" below after b/34961340 is fixed
9791 if (DEBUG_ENERGY_CPU || true) {
Joe Onoratoabded112016-02-08 16:49:39 -08009792 Slog.d(TAG, "Reading cpu stats took " + (mClocks.elapsedRealtime() - startTimeMs) +
Adam Lesinski72478f02015-06-17 15:39:43 -07009793 " ms");
9794 }
9795
9796 if (mOnBatteryInternal && numWakelocks > 0) {
9797 // Distribute a portion of the total cpu time to wakelock holders.
9798 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - wakelockWeight)) / 100;
9799 mTempTotalCpuSystemTimeUs =
9800 (mTempTotalCpuSystemTimeUs * (100 - wakelockWeight)) / 100;
9801
9802 for (int i = 0; i < numPartialTimers; i++) {
9803 final StopwatchTimer timer = mPartialTimers.get(i);
9804
9805 // The system does not share any blame, as it is usually holding the wakelock
9806 // on behalf of an app.
9807 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
9808 int userTimeUs = (int) (mTempTotalCpuUserTimeUs / numWakelocks);
9809 int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / numWakelocks);
9810
9811 if (DEBUG_ENERGY_CPU) {
9812 StringBuilder sb = new StringBuilder();
9813 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
9814 .append(": u=");
9815 TimeUtils.formatDuration(userTimeUs / 1000, sb);
9816 sb.append(" s=");
9817 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
9818 Slog.d(TAG, sb.toString());
9819 }
9820
9821 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
9822 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
9823
9824 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Adam Lesinski062e66c2015-07-14 12:02:44 -07009825 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000);
Adam Lesinski72478f02015-06-17 15:39:43 -07009826
9827 mTempTotalCpuUserTimeUs -= userTimeUs;
9828 mTempTotalCpuSystemTimeUs -= systemTimeUs;
9829 numWakelocks--;
9830 }
9831 }
9832
9833 if (mTempTotalCpuUserTimeUs > 0 || mTempTotalCpuSystemTimeUs > 0) {
9834 // Anything left over is given to the system.
9835 if (DEBUG_ENERGY_CPU) {
9836 StringBuilder sb = new StringBuilder();
9837 sb.append(" Distributing lost time to system: u=");
9838 TimeUtils.formatDuration(mTempTotalCpuUserTimeUs / 1000, sb);
9839 sb.append(" s=");
9840 TimeUtils.formatDuration(mTempTotalCpuSystemTimeUs / 1000, sb);
9841 Slog.d(TAG, sb.toString());
9842 }
9843
9844 final Uid u = getUidStatsLocked(Process.SYSTEM_UID);
9845 u.mUserCpuTime.addCountLocked(mTempTotalCpuUserTimeUs);
9846 u.mSystemCpuTime.addCountLocked(mTempTotalCpuSystemTimeUs);
9847
9848 final Uid.Proc proc = u.getProcessStatsLocked("*lost*");
Adam Lesinski062e66c2015-07-14 12:02:44 -07009849 proc.addCpuTimeLocked((int) mTempTotalCpuUserTimeUs / 1000,
9850 (int) mTempTotalCpuSystemTimeUs / 1000);
Adam Lesinski72478f02015-06-17 15:39:43 -07009851 }
9852 }
9853
9854 // See if there is a difference in wakelocks between this collection and the last
9855 // collection.
9856 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
9857 // No difference, so each timer is now considered for the next collection.
9858 for (int i = 0; i < numPartialTimers; i++) {
9859 mPartialTimers.get(i).mInList = true;
9860 }
9861 } else {
9862 // The lists are different, meaning we added (or removed a timer) since the last
9863 // collection.
9864 final int numLastPartialTimers = mLastPartialTimers.size();
9865 for (int i = 0; i < numLastPartialTimers; i++) {
9866 mLastPartialTimers.get(i).mInList = false;
9867 }
9868 mLastPartialTimers.clear();
9869
9870 // Mark the current timers as gone through a collection.
9871 for (int i = 0; i < numPartialTimers; i++) {
9872 final StopwatchTimer timer = mPartialTimers.get(i);
9873 timer.mInList = true;
9874 mLastPartialTimers.add(timer);
9875 }
9876 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009877 }
9878
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07009879 boolean setChargingLocked(boolean charging) {
9880 if (mCharging != charging) {
9881 mCharging = charging;
9882 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07009883 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07009884 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07009885 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07009886 }
9887 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
9888 return true;
9889 }
9890 return false;
9891 }
9892
Dianne Hackborn40c87252014-03-19 16:55:40 -07009893 void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime, final boolean onBattery,
Adam Lesinskif9b20a92016-06-17 17:30:01 -07009894 final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009895 boolean doWrite = false;
9896 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
9897 m.arg1 = onBattery ? 1 : 0;
9898 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009899
Dianne Hackborn40c87252014-03-19 16:55:40 -07009900 final long uptime = mSecUptime * 1000;
9901 final long realtime = mSecRealtime * 1000;
Jeff Browne95c3cd2014-05-02 16:59:26 -07009902 final boolean screenOn = mScreenState == Display.STATE_ON;
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009903 if (onBattery) {
9904 // We will reset our status if we are unplugging after the
9905 // battery was last full, or the level is at 100, or
9906 // we have gone through a significant charge (from a very low
9907 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009908 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -07009909 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009910 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -07009911 || (mDischargeCurrentLevel < 20 && level >= 80)
9912 || (getHighDischargeAmountSinceCharge() >= 200
9913 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -07009914 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -07009915 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -07009916 + " lowAmount=" + getLowDischargeAmountSinceCharge()
9917 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009918 // Before we write, collect a snapshot of the final aggregated
9919 // stats to be reported in the next checkin. Only do this if we have
9920 // a sufficient amount of data to make it interesting.
9921 if (getLowDischargeAmountSinceCharge() >= 20) {
9922 final Parcel parcel = Parcel.obtain();
9923 writeSummaryToParcel(parcel, true);
9924 BackgroundThread.getHandler().post(new Runnable() {
9925 @Override public void run() {
9926 synchronized (mCheckinFile) {
9927 FileOutputStream stream = null;
9928 try {
9929 stream = mCheckinFile.startWrite();
9930 stream.write(parcel.marshall());
9931 stream.flush();
9932 FileUtils.sync(stream);
9933 stream.close();
9934 mCheckinFile.finishWrite(stream);
9935 } catch (IOException e) {
9936 Slog.w("BatteryStats",
9937 "Error writing checkin battery statistics", e);
9938 mCheckinFile.failWrite(stream);
9939 } finally {
9940 parcel.recycle();
9941 }
9942 }
9943 }
9944 });
9945 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009946 doWrite = true;
9947 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -08009948 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -07009949 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -08009950 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -07009951 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009952 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009953 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009954 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009955 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07009956 if (mCharging) {
9957 setChargingLocked(false);
9958 }
9959 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08009960 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -07009961 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -07009962 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009963 mDischargeStepTracker.clearTime();
9964 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009965 mInitStepMode = mCurStepMode;
9966 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -08009967 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009968 mHistoryCur.batteryLevel = (byte)level;
9969 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
9970 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
9971 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009972 if (reset) {
9973 mRecordingHistory = true;
9974 startRecordingHistory(mSecRealtime, mSecUptime, reset);
9975 }
Dianne Hackborn40c87252014-03-19 16:55:40 -07009976 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009977 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Jeff Browne95c3cd2014-05-02 16:59:26 -07009978 if (screenOn) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009979 mDischargeScreenOnUnplugLevel = level;
9980 mDischargeScreenOffUnplugLevel = 0;
9981 } else {
9982 mDischargeScreenOnUnplugLevel = 0;
9983 mDischargeScreenOffUnplugLevel = level;
9984 }
9985 mDischargeAmountScreenOn = 0;
9986 mDischargeAmountScreenOff = 0;
Jeff Browne95c3cd2014-05-02 16:59:26 -07009987 updateTimeBasesLocked(true, !screenOn, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009988 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07009989 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08009990 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -08009991 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009992 mHistoryCur.batteryLevel = (byte)level;
9993 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
9994 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
9995 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07009996 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009997 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009998 if (level < mDischargeUnplugLevel) {
9999 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
10000 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
10001 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070010002 updateDischargeScreenLevelsLocked(screenOn, screenOn);
10003 updateTimeBasesLocked(false, !screenOn, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010004 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070010005 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070010006 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010007 mInitStepMode = mCurStepMode;
10008 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010009 }
10010 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
10011 if (mFile != null) {
10012 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010013 }
10014 }
10015 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010016
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010017 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
10018 boolean reset) {
10019 mRecordingHistory = true;
10020 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn37de0982014-05-09 09:32:18 -070010021 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs,
10022 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010023 mHistoryCur);
10024 mHistoryCur.currentTime = 0;
10025 if (reset) {
10026 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
10027 }
10028 }
10029
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070010030 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
10031 final long uptimeMs) {
10032 if (mRecordingHistory) {
10033 mHistoryCur.currentTime = currentTime;
10034 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_CURRENT_TIME,
10035 mHistoryCur);
10036 mHistoryCur.currentTime = 0;
10037 }
10038 }
10039
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080010040 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
10041 if (mRecordingHistory) {
10042 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080010043 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_SHUTDOWN,
10044 mHistoryCur);
10045 mHistoryCur.currentTime = 0;
10046 }
10047 }
10048
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010049 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010050 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010051 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010052 }
10053 }
10054
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010055 // This should probably be exposed in the API, though it's not critical
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010056 public static final int BATTERY_PLUGGED_NONE = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010057
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010058 public void setBatteryStateLocked(int status, int health, int plugType, int level,
Adam Lesinski041d9172016-12-12 12:03:56 -080010059 int temp, int volt, int chargeUAh, int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070010060 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
10061 temp = Math.max(0, temp);
10062
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010063 final boolean onBattery = plugType == BATTERY_PLUGGED_NONE;
Joe Onoratoabded112016-02-08 16:49:39 -080010064 final long uptime = mClocks.uptimeMillis();
10065 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010066 if (!mHaveBatteryLevel) {
10067 mHaveBatteryLevel = true;
10068 // We start out assuming that the device is plugged in (not
10069 // on battery). If our first report is now that we are indeed
10070 // plugged in, then twiddle our state to correctly reflect that
10071 // since we won't be going through the full setOnBattery().
10072 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070010073 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010074 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070010075 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010076 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070010077 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010078 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010079 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070010080 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010081 mHistoryCur.batteryStatus = (byte)status;
10082 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010083 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010084 mMaxChargeStepLevel = mMinDischargeStepLevel =
10085 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010086 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010087 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
10088 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
10089 }
10090 int oldStatus = mHistoryCur.batteryStatus;
10091 if (onBattery) {
10092 mDischargeCurrentLevel = level;
10093 if (!mRecordingHistory) {
10094 mRecordingHistory = true;
10095 startRecordingHistory(elapsedRealtime, uptime, true);
10096 }
10097 } else if (level < 96) {
10098 if (!mRecordingHistory) {
10099 mRecordingHistory = true;
10100 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010101 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010102 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010103 mCurrentBatteryLevel = level;
10104 if (mDischargePlugLevel < 0) {
10105 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070010106 }
Adam Lesinski926969b2016-04-28 17:31:12 -070010107
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010108 if (onBattery != mOnBattery) {
10109 mHistoryCur.batteryLevel = (byte)level;
10110 mHistoryCur.batteryStatus = (byte)status;
10111 mHistoryCur.batteryHealth = (byte)health;
10112 mHistoryCur.batteryPlugType = (byte)plugType;
10113 mHistoryCur.batteryTemperature = (short)temp;
10114 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010115 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
10116 // Only record discharges
10117 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
10118 mDischargeCounter.addCountLocked(chargeDiff);
10119 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
10120 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070010121 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010122 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010123 } else {
10124 boolean changed = false;
10125 if (mHistoryCur.batteryLevel != level) {
10126 mHistoryCur.batteryLevel = (byte)level;
10127 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070010128
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010129 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
10130 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010131 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070010132 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010133 if (mHistoryCur.batteryStatus != status) {
10134 mHistoryCur.batteryStatus = (byte)status;
10135 changed = true;
10136 }
10137 if (mHistoryCur.batteryHealth != health) {
10138 mHistoryCur.batteryHealth = (byte)health;
10139 changed = true;
10140 }
10141 if (mHistoryCur.batteryPlugType != plugType) {
10142 mHistoryCur.batteryPlugType = (byte)plugType;
10143 changed = true;
10144 }
10145 if (temp >= (mHistoryCur.batteryTemperature+10)
10146 || temp <= (mHistoryCur.batteryTemperature-10)) {
10147 mHistoryCur.batteryTemperature = (short)temp;
10148 changed = true;
10149 }
10150 if (volt > (mHistoryCur.batteryVoltage+20)
10151 || volt < (mHistoryCur.batteryVoltage-20)) {
10152 mHistoryCur.batteryVoltage = (char)volt;
10153 changed = true;
10154 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070010155 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
10156 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010157 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
10158 // Only record discharges
10159 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
10160 mDischargeCounter.addCountLocked(chargeDiff);
10161 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
10162 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070010163 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070010164 changed = true;
10165 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010166 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
10167 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
10168 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
10169 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010170 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010171 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
10172 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
10173 modeBits, elapsedRealtime);
10174 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
10175 modeBits, elapsedRealtime);
10176 mLastDischargeStepLevel = level;
10177 mMinDischargeStepLevel = level;
10178 mInitStepMode = mCurStepMode;
10179 mModStepMode = 0;
10180 }
10181 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010182 if (level >= 90) {
10183 // If the battery level is at least 90%, always consider the device to be
10184 // charging even if it happens to go down a level.
10185 changed |= setChargingLocked(true);
10186 mLastChargeStepLevel = level;
10187 } if (!mCharging) {
10188 if (mLastChargeStepLevel < level) {
10189 // We have not reporting that we are charging, but the level has now
10190 // gone up, so consider the state to be charging.
10191 changed |= setChargingLocked(true);
10192 mLastChargeStepLevel = level;
10193 }
10194 } else {
10195 if (mLastChargeStepLevel > level) {
10196 // We had reported that the device was charging, but here we are with
10197 // power connected and the level going down. Looks like the current
10198 // power supplied isn't enough, so consider the device to now be
10199 // discharging.
10200 changed |= setChargingLocked(false);
10201 mLastChargeStepLevel = level;
10202 }
10203 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010204 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
10205 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
10206 modeBits, elapsedRealtime);
10207 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
10208 modeBits, elapsedRealtime);
10209 mLastChargeStepLevel = level;
10210 mMaxChargeStepLevel = level;
10211 mInitStepMode = mCurStepMode;
10212 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070010213 }
10214 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010215 if (changed) {
10216 addHistoryRecordLocked(elapsedRealtime, uptime);
10217 }
Evan Millarc64edde2009-04-18 12:26:32 -070010218 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010219 if (!onBattery && status == BatteryManager.BATTERY_STATUS_FULL) {
10220 // We don't record history while we are plugged in and fully charged.
10221 // The next time we are unplugged, history will be cleared.
10222 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080010223 }
Adam Lesinski041d9172016-12-12 12:03:56 -080010224
10225 if (differsByMoreThan(chargeFullUAh, mLastChargeFullUAh, 100)) {
10226 mLastChargeFullUAh = chargeFullUAh;
10227 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ESTIMATED_BATTERY_CAP,
10228 "", chargeFullUAh / 1000);
10229 }
10230 }
10231
10232 private static boolean differsByMoreThan(int left, int right, int diff) {
10233 return Math.abs(left - right) > diff;
Adam Lesinski33dac552015-03-09 15:24:48 -070010234 }
10235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010236 public long getAwakeTimeBattery() {
10237 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
10238 }
10239
10240 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080010241 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010242 }
10243
10244 @Override
10245 public long computeUptime(long curTime, int which) {
10246 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010247 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010248 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010249 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010250 }
10251 return 0;
10252 }
10253
10254 @Override
10255 public long computeRealtime(long curTime, int which) {
10256 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010257 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010258 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010259 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010260 }
10261 return 0;
10262 }
10263
10264 @Override
10265 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010266 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010267 }
10268
10269 @Override
10270 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010271 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010272 }
10273
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010274 @Override
10275 public long computeBatteryScreenOffUptime(long curTime, int which) {
10276 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
10277 }
10278
10279 @Override
10280 public long computeBatteryScreenOffRealtime(long curTime, int which) {
10281 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010282 }
10283
Dianne Hackborn260c5022014-04-29 11:23:16 -070010284 private long computeTimePerLevel(long[] steps, int numSteps) {
10285 // For now we'll do a simple average across all steps.
10286 if (numSteps <= 0) {
10287 return -1;
10288 }
10289 long total = 0;
10290 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010291 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070010292 }
10293 return total / numSteps;
10294 /*
10295 long[] buckets = new long[numSteps];
10296 int numBuckets = 0;
10297 int numToAverage = 4;
10298 int i = 0;
10299 while (i < numSteps) {
10300 long totalTime = 0;
10301 int num = 0;
10302 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010303 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070010304 num++;
10305 }
10306 buckets[numBuckets] = totalTime / num;
10307 numBuckets++;
10308 numToAverage *= 2;
10309 i += num;
10310 }
10311 if (numBuckets < 1) {
10312 return -1;
10313 }
10314 long averageTime = buckets[numBuckets-1];
10315 for (i=numBuckets-2; i>=0; i--) {
10316 averageTime = (averageTime + buckets[i]) / 2;
10317 }
10318 return averageTime;
10319 */
10320 }
10321
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010322 @Override
10323 public long computeBatteryTimeRemaining(long curTime) {
10324 if (!mOnBattery) {
10325 return -1;
10326 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070010327 /* Simple implementation just looks at the average discharge per level across the
10328 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010329 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
10330 if (discharge < 2) {
10331 return -1;
10332 }
10333 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
10334 if (duration < 1000*1000) {
10335 return -1;
10336 }
10337 long usPerLevel = duration/discharge;
10338 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070010339 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010340 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070010341 return -1;
10342 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010343 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070010344 if (msPerLevel <= 0) {
10345 return -1;
10346 }
10347 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010348 }
10349
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010350 @Override
10351 public LevelStepTracker getDischargeLevelStepTracker() {
10352 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070010353 }
10354
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010355 @Override
10356 public LevelStepTracker getDailyDischargeLevelStepTracker() {
10357 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070010358 }
10359
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010360 @Override
10361 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070010362 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010363 // Not yet working.
10364 return -1;
10365 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070010366 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010367 int curLevel = mCurrentBatteryLevel;
10368 int plugLevel = mDischargePlugLevel;
10369 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
10370 return -1;
10371 }
10372 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
10373 if (duration < 1000*1000) {
10374 return -1;
10375 }
10376 long usPerLevel = duration/(curLevel-plugLevel);
10377 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070010378 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010379 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070010380 return -1;
10381 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010382 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070010383 if (msPerLevel <= 0) {
10384 return -1;
10385 }
10386 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010387 }
10388
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010389 @Override
10390 public LevelStepTracker getChargeLevelStepTracker() {
10391 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070010392 }
10393
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010394 @Override
10395 public LevelStepTracker getDailyChargeLevelStepTracker() {
10396 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070010397 }
10398
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010399 @Override
10400 public ArrayList<PackageChange> getDailyPackageChanges() {
10401 return mDailyPackageChanges;
10402 }
10403
Joe Onoratoe1acd632016-02-23 13:25:10 -080010404 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080010405 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010406 }
10407
10408 @Override
10409 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010410 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010411 }
10412
10413 @Override
10414 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010415 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010416 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070010417
The Android Open Source Project10592532009-03-18 17:39:46 -070010418 @Override
Evan Millar633a1742009-04-02 16:36:33 -070010419 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070010420 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070010421 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070010422 }
10423 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010424
Evan Millar633a1742009-04-02 16:36:33 -070010425 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010426 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070010427 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010428
The Android Open Source Project10592532009-03-18 17:39:46 -070010429 @Override
Evan Millar633a1742009-04-02 16:36:33 -070010430 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070010431 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070010432 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070010433 }
10434 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010435
Evan Millar633a1742009-04-02 16:36:33 -070010436 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080010437 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070010438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010439
Amith Yamasanie43530a2009-08-21 13:11:37 -070010440 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070010441 public int getLowDischargeAmountSinceCharge() {
10442 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080010443 int val = mLowDischargeAmountSinceCharge;
10444 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
10445 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
10446 }
10447 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070010448 }
10449 }
10450
10451 @Override
10452 public int getHighDischargeAmountSinceCharge() {
10453 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080010454 int val = mHighDischargeAmountSinceCharge;
10455 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
10456 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
10457 }
10458 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070010459 }
10460 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010461
10462 @Override
10463 public int getDischargeAmount(int which) {
10464 int dischargeAmount = which == STATS_SINCE_CHARGED
10465 ? getHighDischargeAmountSinceCharge()
10466 : (getDischargeStartLevel() - getDischargeCurrentLevel());
10467 if (dischargeAmount < 0) {
10468 dischargeAmount = 0;
10469 }
10470 return dischargeAmount;
10471 }
10472
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010473 public int getDischargeAmountScreenOn() {
10474 synchronized(this) {
10475 int val = mDischargeAmountScreenOn;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010476 if (mOnBattery && mScreenState == Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010477 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
10478 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
10479 }
10480 return val;
10481 }
10482 }
10483
10484 public int getDischargeAmountScreenOnSinceCharge() {
10485 synchronized(this) {
10486 int val = mDischargeAmountScreenOnSinceCharge;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010487 if (mOnBattery && mScreenState == Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010488 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
10489 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
10490 }
10491 return val;
10492 }
10493 }
10494
10495 public int getDischargeAmountScreenOff() {
10496 synchronized(this) {
10497 int val = mDischargeAmountScreenOff;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010498 if (mOnBattery && mScreenState != Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010499 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
10500 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
10501 }
10502 return val;
10503 }
10504 }
10505
10506 public int getDischargeAmountScreenOffSinceCharge() {
10507 synchronized(this) {
10508 int val = mDischargeAmountScreenOffSinceCharge;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010509 if (mOnBattery && mScreenState != Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010510 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
10511 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
10512 }
10513 return val;
10514 }
10515 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070010516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010517 /**
10518 * Retrieve the statistics object for a particular uid, creating if needed.
10519 */
10520 public Uid getUidStatsLocked(int uid) {
10521 Uid u = mUidStats.get(uid);
10522 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080010523 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010524 mUidStats.put(uid, u);
10525 }
10526 return u;
10527 }
10528
10529 /**
10530 * Remove the statistics object for a particular uid.
10531 */
10532 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070010533 mKernelUidCpuTimeReader.removeUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010534 mUidStats.remove(uid);
10535 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070010536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010537 /**
10538 * Retrieve the statistics object for a particular process, creating
10539 * if needed.
10540 */
10541 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070010542 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010543 Uid u = getUidStatsLocked(uid);
10544 return u.getProcessStatsLocked(name);
10545 }
10546
10547 /**
10548 * Retrieve the statistics object for a particular process, creating
10549 * if needed.
10550 */
10551 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070010552 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 Uid u = getUidStatsLocked(uid);
10554 return u.getPackageStatsLocked(pkg);
10555 }
10556
10557 /**
10558 * Retrieve the statistics object for a particular service, creating
10559 * if needed.
10560 */
10561 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070010562 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010563 Uid u = getUidStatsLocked(uid);
10564 return u.getServiceStatsLocked(pkg, name);
10565 }
10566
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010567 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080010568 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010569 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010570 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010571 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010572
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010573 Parcel mPendingWrite = null;
10574 final ReentrantLock mWriteLock = new ReentrantLock();
10575
10576 public void writeAsyncLocked() {
10577 writeLocked(false);
10578 }
10579
10580 public void writeSyncLocked() {
10581 writeLocked(true);
10582 }
10583
10584 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010585 if (mFile == null) {
10586 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010587 return;
10588 }
10589
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010590 if (mShuttingDown) {
10591 return;
10592 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010593
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010594 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010595 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080010596 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010597
10598 if (mPendingWrite != null) {
10599 mPendingWrite.recycle();
10600 }
10601 mPendingWrite = out;
10602
10603 if (sync) {
10604 commitPendingDataToDisk();
10605 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010606 BackgroundThread.getHandler().post(new Runnable() {
10607 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010608 commitPendingDataToDisk();
10609 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010610 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010611 }
10612 }
10613
10614 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070010615 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010616 synchronized (this) {
10617 next = mPendingWrite;
10618 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070010619 if (next == null) {
10620 return;
10621 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010622 }
10623
Amith Yamasanid2450862017-02-07 15:58:24 -080010624 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010625 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010626 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010627 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070010629 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010630 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010631 mFile.commit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010632 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010633 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010634 mFile.rollback();
10635 } finally {
10636 next.recycle();
10637 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070010638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 }
10640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010641 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010642 if (mDailyFile != null) {
10643 readDailyStatsLocked();
10644 }
10645
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010646 if (mFile == null) {
10647 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010648 return;
10649 }
10650
10651 mUidStats.clear();
10652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010653 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010654 File file = mFile.chooseForRead();
10655 if (!file.exists()) {
10656 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010657 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010658 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010659
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010660 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010661 Parcel in = Parcel.obtain();
10662 in.unmarshall(raw, 0, raw.length);
10663 in.setDataPosition(0);
10664 stream.close();
10665
10666 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080010667 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010668 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070010669 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010670 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010671
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010672 mEndPlatformVersion = Build.ID;
10673
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010674 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010675 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080010676 final long elapsedRealtime = mClocks.elapsedRealtime();
10677 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010678 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010679 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010680 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010681 addHistoryBufferLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
10682 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070010683 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010684
10685 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010686 }
10687
10688 public int describeContents() {
10689 return 0;
10690 }
10691
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070010692 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070010693 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010694
10695 mHistoryBuffer.setDataSize(0);
10696 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010697 mHistoryTagPool.clear();
10698 mNextHistoryTagIdx = 0;
10699 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010700
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010701 int numTags = in.readInt();
10702 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010703 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010704 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070010705 if (str == null) {
10706 throw new ParcelFormatException("null history tag string");
10707 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010708 int uid = in.readInt();
10709 HistoryTag tag = new HistoryTag();
10710 tag.string = str;
10711 tag.uid = uid;
10712 tag.poolIdx = idx;
10713 mHistoryTagPool.put(tag, idx);
10714 if (idx >= mNextHistoryTagIdx) {
10715 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010716 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010717 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010718 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010719
10720 int bufSize = in.readInt();
10721 int curPos = in.dataPosition();
10722 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070010723 throw new ParcelFormatException("File corrupt: history data buffer too large " +
10724 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010725 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070010726 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
10727 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010728 } else {
10729 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
10730 + " bytes at " + curPos);
10731 mHistoryBuffer.appendFrom(in, curPos, bufSize);
10732 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010733 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010734
Dianne Hackbornae384452011-06-28 12:33:48 -070010735 if (andOldHistory) {
10736 readOldHistory(in);
10737 }
10738
10739 if (DEBUG_HISTORY) {
10740 StringBuilder sb = new StringBuilder(128);
10741 sb.append("****************** OLD mHistoryBaseTime: ");
10742 TimeUtils.formatDuration(mHistoryBaseTime, sb);
10743 Slog.i(TAG, sb.toString());
10744 }
10745 mHistoryBaseTime = historyBaseTime;
10746 if (DEBUG_HISTORY) {
10747 StringBuilder sb = new StringBuilder(128);
10748 sb.append("****************** NEW mHistoryBaseTime: ");
10749 TimeUtils.formatDuration(mHistoryBaseTime, sb);
10750 Slog.i(TAG, sb.toString());
10751 }
10752
10753 // We are just arbitrarily going to insert 1 minute from the sample of
10754 // the last run until samples in this run.
10755 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080010756 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010757 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070010758 if (DEBUG_HISTORY) {
10759 StringBuilder sb = new StringBuilder(128);
10760 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
10761 TimeUtils.formatDuration(mHistoryBaseTime, sb);
10762 Slog.i(TAG, sb.toString());
10763 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070010764 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010765 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010766
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010767 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070010768 if (!USE_OLD_HISTORY) {
10769 return;
10770 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010771 mHistory = mHistoryEnd = mHistoryCache = null;
10772 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070010773 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010774 HistoryItem rec = new HistoryItem(time, in);
10775 addHistoryRecordLocked(rec);
10776 }
10777 }
10778
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010779 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070010780 if (DEBUG_HISTORY) {
10781 StringBuilder sb = new StringBuilder(128);
10782 sb.append("****************** WRITING mHistoryBaseTime: ");
10783 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070010784 sb.append(" mLastHistoryElapsedRealtime: ");
10785 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070010786 Slog.i(TAG, sb.toString());
10787 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010788 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010789 if (!inclData) {
10790 out.writeInt(0);
10791 out.writeInt(0);
10792 return;
10793 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010794 out.writeInt(mHistoryTagPool.size());
10795 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10796 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080010797 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010798 out.writeString(tag.string);
10799 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080010800 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010801 out.writeInt(mHistoryBuffer.dataSize());
10802 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
10803 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
10804 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070010805
10806 if (andOldHistory) {
10807 writeOldHistory(out);
10808 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010809 }
10810
10811 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070010812 if (!USE_OLD_HISTORY) {
10813 return;
10814 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010815 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010816 while (rec != null) {
10817 if (rec.time >= 0) rec.writeToParcel(out, 0);
10818 rec = rec.next;
10819 }
10820 out.writeLong(-1);
10821 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010822
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070010823 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010824 final int version = in.readInt();
10825 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010826 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010827 + ", expected " + VERSION + "; erasing old stats");
10828 return;
10829 }
10830
Dianne Hackbornae384452011-06-28 12:33:48 -070010831 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010834 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010835 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010836 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010837 mStartPlatformVersion = in.readString();
10838 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010839 mOnBatteryTimeBase.readSummaryFromParcel(in);
10840 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010841 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010842 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070010843 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010844 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010845 mEstimatedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070010846 mLowDischargeAmountSinceCharge = in.readInt();
10847 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010848 mDischargeAmountScreenOnSinceCharge = in.readInt();
10849 mDischargeAmountScreenOffSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010850 mDischargeStepTracker.readFromParcel(in);
10851 mChargeStepTracker.readFromParcel(in);
10852 mDailyDischargeStepTracker.readFromParcel(in);
10853 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010854 mDischargeCounter.readSummaryFromParcelLocked(in);
10855 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010856 int NPKG = in.readInt();
10857 if (NPKG > 0) {
10858 mDailyPackageChanges = new ArrayList<>(NPKG);
10859 while (NPKG > 0) {
10860 NPKG--;
10861 PackageChange pc = new PackageChange();
10862 pc.mPackageName = in.readString();
10863 pc.mUpdate = in.readInt() != 0;
10864 pc.mVersionCode = in.readInt();
10865 mDailyPackageChanges.add(pc);
10866 }
10867 } else {
10868 mDailyPackageChanges = null;
10869 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010870 mDailyStartTime = in.readLong();
10871 mNextMinDailyDeadline = in.readLong();
10872 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010874 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010875
Jeff Browne95c3cd2014-05-02 16:59:26 -070010876 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010877 mScreenOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010878 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
10879 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
10880 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070010881 mInteractive = false;
10882 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010883 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010884 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010885 mLongestLightIdleTime = in.readLong();
10886 mLongestFullIdleTime = in.readLong();
10887 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
10888 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
10889 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010890 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010891 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080010892 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070010893 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
10894 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070010895 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010896 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
10897 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
10898 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010899 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010900 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
10901 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010902 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010903 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080010904 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010905 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010906 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010907 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
10908 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070010909 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070010910 mWifiOn = false;
10911 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070010912 mGlobalWifiRunning = false;
10913 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010914 for (int i=0; i<NUM_WIFI_STATES; i++) {
10915 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
10916 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010917 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10918 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
10919 }
10920 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10921 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
10922 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010923 mWifiActivity.readSummaryFromParcel(in);
10924 mBluetoothActivity.readSummaryFromParcel(in);
10925 mModemActivity.readSummaryFromParcel(in);
10926 mHasWifiReporting = in.readInt() != 0;
10927 mHasBluetoothReporting = in.readInt() != 0;
10928 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070010929
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010930 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010931 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010932 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010933 mCameraOnNesting = 0;
10934 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010935 mBluetoothScanNesting = 0;
10936 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010937
Evan Millarc64edde2009-04-18 12:26:32 -070010938 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010939 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070010940 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010941 }
Evan Millarc64edde2009-04-18 12:26:32 -070010942 for (int ikw = 0; ikw < NKW; ikw++) {
10943 if (in.readInt() != 0) {
10944 String kwltName = in.readString();
10945 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
10946 }
10947 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070010948
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010949 int NWR = in.readInt();
10950 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070010951 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010952 }
10953 for (int iwr = 0; iwr < NWR; iwr++) {
10954 if (in.readInt() != 0) {
10955 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010956 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010957 }
10958 }
10959
James Carr3a226052016-07-01 14:49:52 -070010960 int NMS = in.readInt();
10961 for (int ims = 0; ims < NMS; ims++) {
10962 if (in.readInt() != 0) {
10963 long kmstName = in.readLong();
10964 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
10965 }
10966 }
10967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010968 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010969 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070010970 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010972 for (int iu = 0; iu < NU; iu++) {
10973 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080010974 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010975 mUidStats.put(uid, u);
10976
Bookatz867c0d72017-03-07 18:23:42 -080010977 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
10978
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070010979 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010980 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070010981 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010982 }
The Android Open Source Project10592532009-03-18 17:39:46 -070010983 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010984 if (in.readInt() != 0) {
10985 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
10986 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070010987 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010988 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070010989 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010990 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070010991 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
10992 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
10993 if (in.readInt() != 0) {
10994 u.makeWifiBatchedScanBin(i, null);
10995 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
10996 }
10997 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070010998 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010999 if (in.readInt() != 0) {
11000 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
11001 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011002 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080011003 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011004 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011005 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080011006 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
11007 }
11008 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011009 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
11010 }
11011 if (in.readInt() != 0) {
11012 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
11013 }
11014 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070011015 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
11016 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011017 if (in.readInt() != 0) {
11018 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
11019 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080011020 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070011021 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
11022 if (in.readInt() != 0) {
11023 u.makeProcessState(i, null);
11024 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
11025 }
11026 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070011027 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080011028 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011029 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070011030
Dianne Hackborn617f8772009-03-31 15:04:46 -070011031 if (in.readInt() != 0) {
11032 if (u.mUserActivityCounters == null) {
11033 u.initUserActivityLocked();
11034 }
11035 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
11036 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
11037 }
11038 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011039
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011040 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080011041 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011042 u.initNetworkActivityLocked();
11043 }
11044 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080011045 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
11046 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011047 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080011048 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
11049 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011050 }
11051
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011052 u.mUserCpuTime.readSummaryFromParcelLocked(in);
11053 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
Adam Lesinskia7a4ccc2015-06-26 17:43:04 -070011054 u.mCpuPower.readSummaryFromParcelLocked(in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011055
Adam Lesinski6832f392015-09-05 18:05:40 -070011056 if (in.readInt() != 0) {
11057 final int numClusters = in.readInt();
11058 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
11059 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011060 }
Adam Lesinski6832f392015-09-05 18:05:40 -070011061
11062 u.mCpuClusterSpeed = new LongSamplingCounter[numClusters][];
11063 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070011064 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070011065 final int NSB = in.readInt();
11066 if (mPowerProfile != null &&
11067 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
11068 throw new ParcelFormatException("File corrupt: too many speed bins " +
11069 NSB);
11070 }
11071
Adam Lesinski6832f392015-09-05 18:05:40 -070011072 u.mCpuClusterSpeed[cluster] = new LongSamplingCounter[NSB];
11073 for (int speed = 0; speed < NSB; speed++) {
11074 if (in.readInt() != 0) {
11075 u.mCpuClusterSpeed[cluster][speed] = new LongSamplingCounter(
11076 mOnBatteryTimeBase);
11077 u.mCpuClusterSpeed[cluster][speed].readSummaryFromParcelLocked(in);
11078 }
11079 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070011080 } else {
11081 u.mCpuClusterSpeed[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070011082 }
11083 }
11084 } else {
11085 u.mCpuClusterSpeed = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011086 }
11087
Adam Lesinski5f056f62016-07-14 16:56:08 -070011088 if (in.readInt() != 0) {
11089 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
11090 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
11091 } else {
11092 u.mMobileRadioApWakeupCount = null;
11093 }
11094
11095 if (in.readInt() != 0) {
11096 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
11097 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
11098 } else {
11099 u.mWifiRadioApWakeupCount = null;
11100 }
11101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070011103 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011104 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011106 for (int iw = 0; iw < NW; iw++) {
11107 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070011108 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011109 }
11110
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011111 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070011112 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011113 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011114 }
11115 for (int is = 0; is < NS; is++) {
11116 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070011117 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011118 }
11119
11120 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070011121 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011122 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011123 }
11124 for (int ij = 0; ij < NJ; ij++) {
11125 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070011126 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011127 }
11128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011129 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080011130 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011131 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011133 for (int is = 0; is < NP; is++) {
11134 int seNumber = in.readInt();
11135 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080011136 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011137 }
11138 }
11139
11140 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080011141 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011142 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011144 for (int ip = 0; ip < NP; ip++) {
11145 String procName = in.readString();
11146 Uid.Proc p = u.getProcessStatsLocked(procName);
11147 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011148 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070011149 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011150 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080011151 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
11152 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011153 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011154 }
11155
11156 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011157 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011158 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011160 for (int ip = 0; ip < NP; ip++) {
11161 String pkgName = in.readString();
11162 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070011163 final int NWA = in.readInt();
11164 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011165 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070011166 }
11167 p.mWakeupAlarms.clear();
11168 for (int iwa=0; iwa<NWA; iwa++) {
11169 String tag = in.readString();
11170 Counter c = new Counter(mOnBatteryTimeBase);
11171 c.readSummaryFromParcelLocked(in);
11172 p.mWakeupAlarms.put(tag, c);
11173 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011174 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080011175 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011176 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080011177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178 for (int is = 0; is < NS; is++) {
11179 String servName = in.readString();
11180 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
11181 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011182 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011183 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011184 }
11185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011186 }
11187 }
11188
11189 /**
11190 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
11191 * disk. This format does not allow a lossless round-trip.
11192 *
11193 * @param out the Parcel to be written to.
11194 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011195 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080011196 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011197
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070011198 // Pull the clock time. This may update the time and make a new history entry
11199 // if we had originally pulled a time before the RTC was set.
11200 long startClockTime = getStartClockTime();
11201
Joe Onoratoabded112016-02-08 16:49:39 -080011202 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
11203 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204
11205 out.writeInt(VERSION);
11206
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011207 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011209 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011210 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011211 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070011212 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070011213 out.writeString(mStartPlatformVersion);
11214 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011215 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
11216 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011217 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011218 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070011219 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011220 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070011221 out.writeInt(mEstimatedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080011222 out.writeInt(getLowDischargeAmountSinceCharge());
11223 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011224 out.writeInt(getDischargeAmountScreenOnSinceCharge());
11225 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011226 mDischargeStepTracker.writeToParcel(out);
11227 mChargeStepTracker.writeToParcel(out);
11228 mDailyDischargeStepTracker.writeToParcel(out);
11229 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070011230 mDischargeCounter.writeSummaryFromParcelLocked(out);
11231 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070011232 if (mDailyPackageChanges != null) {
11233 final int NPKG = mDailyPackageChanges.size();
11234 out.writeInt(NPKG);
11235 for (int i=0; i<NPKG; i++) {
11236 PackageChange pc = mDailyPackageChanges.get(i);
11237 out.writeString(pc.mPackageName);
11238 out.writeInt(pc.mUpdate ? 1 : 0);
11239 out.writeInt(pc.mVersionCode);
11240 }
11241 } else {
11242 out.writeInt(0);
11243 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011244 out.writeLong(mDailyStartTime);
11245 out.writeLong(mNextMinDailyDeadline);
11246 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011247
11248 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070011249 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011250 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070011251 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070011252 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070011253 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070011254 out.writeLong(mLongestLightIdleTime);
11255 out.writeLong(mLongestFullIdleTime);
11256 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11257 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11258 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070011259 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011260 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080011261 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011262 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070011263 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011264 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070011265 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011266 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070011267 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011268 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080011269 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
11270 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011271 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011272 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11273 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011274 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080011275 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
11276 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011277 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11278 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080011279 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011280 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080011281 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070011282 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
11283 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11284 }
11285 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
11286 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11287 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011288 mWifiActivity.writeSummaryToParcel(out);
11289 mBluetoothActivity.writeSummaryToParcel(out);
11290 mModemActivity.writeSummaryToParcel(out);
11291 out.writeInt(mHasWifiReporting ? 1 : 0);
11292 out.writeInt(mHasBluetoothReporting ? 1 : 0);
11293 out.writeInt(mHasModemReporting ? 1 : 0);
11294
Dianne Hackborn1e01d162014-12-04 17:46:42 -080011295 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070011296 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011297 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011298 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011299
Evan Millarc64edde2009-04-18 12:26:32 -070011300 out.writeInt(mKernelWakelockStats.size());
11301 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11302 Timer kwlt = ent.getValue();
11303 if (kwlt != null) {
11304 out.writeInt(1);
11305 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011306 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11307 } else {
11308 out.writeInt(0);
11309 }
11310 }
11311
11312 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070011313 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
11314 SamplingTimer timer = ent.getValue();
11315 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011316 out.writeInt(1);
11317 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070011318 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070011319 } else {
11320 out.writeInt(0);
11321 }
11322 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011323
James Carr3a226052016-07-01 14:49:52 -070011324 out.writeInt(mKernelMemoryStats.size());
11325 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
11326 Timer kmt = mKernelMemoryStats.valueAt(i);
11327 if (kmt != null) {
11328 out.writeInt(1);
11329 out.writeLong(mKernelMemoryStats.keyAt(i));
11330 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11331 } else {
11332 out.writeInt(0);
11333 }
11334 }
11335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011336 final int NU = mUidStats.size();
11337 out.writeInt(NU);
11338 for (int iu = 0; iu < NU; iu++) {
11339 out.writeInt(mUidStats.keyAt(iu));
11340 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011341
Bookatz867c0d72017-03-07 18:23:42 -080011342 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
11343
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070011344 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011345 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011346 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011347 } else {
11348 out.writeInt(0);
11349 }
11350 if (u.mFullWifiLockTimer != null) {
11351 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011352 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011353 } else {
11354 out.writeInt(0);
11355 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070011356 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011357 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011358 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011359 } else {
11360 out.writeInt(0);
11361 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070011362 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
11363 if (u.mWifiBatchedScanTimer[i] != null) {
11364 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011365 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070011366 } else {
11367 out.writeInt(0);
11368 }
11369 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011370 if (u.mWifiMulticastTimer != null) {
11371 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011372 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011373 } else {
11374 out.writeInt(0);
11375 }
11376 if (u.mAudioTurnedOnTimer != null) {
11377 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011378 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011379 } else {
11380 out.writeInt(0);
11381 }
11382 if (u.mVideoTurnedOnTimer != null) {
11383 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011384 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011385 } else {
11386 out.writeInt(0);
11387 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011388 if (u.mFlashlightTurnedOnTimer != null) {
11389 out.writeInt(1);
11390 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11391 } else {
11392 out.writeInt(0);
11393 }
11394 if (u.mCameraTurnedOnTimer != null) {
11395 out.writeInt(1);
11396 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11397 } else {
11398 out.writeInt(0);
11399 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070011400 if (u.mForegroundActivityTimer != null) {
11401 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011402 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070011403 } else {
11404 out.writeInt(0);
11405 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011406 if (u.mBluetoothScanTimer != null) {
11407 out.writeInt(1);
11408 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11409 } else {
11410 out.writeInt(0);
11411 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070011412 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
11413 if (u.mProcessStateTimer[i] != null) {
11414 out.writeInt(1);
11415 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11416 } else {
11417 out.writeInt(0);
11418 }
11419 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080011420 if (u.mVibratorOnTimer != null) {
11421 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011422 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080011423 } else {
11424 out.writeInt(0);
11425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426
Dianne Hackborn617f8772009-03-31 15:04:46 -070011427 if (u.mUserActivityCounters == null) {
11428 out.writeInt(0);
11429 } else {
11430 out.writeInt(1);
11431 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
11432 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
11433 }
11434 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011435
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080011436 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011437 out.writeInt(0);
11438 } else {
11439 out.writeInt(1);
11440 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080011441 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
11442 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011443 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080011444 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
11445 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011446 }
11447
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011448 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
11449 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
Adam Lesinskia7a4ccc2015-06-26 17:43:04 -070011450 u.mCpuPower.writeSummaryFromParcelLocked(out);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011451
Adam Lesinski6832f392015-09-05 18:05:40 -070011452 if (u.mCpuClusterSpeed != null) {
11453 out.writeInt(1);
11454 out.writeInt(u.mCpuClusterSpeed.length);
11455 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeed) {
11456 if (cpuSpeeds != null) {
11457 out.writeInt(1);
11458 out.writeInt(cpuSpeeds.length);
11459 for (LongSamplingCounter c : cpuSpeeds) {
11460 if (c != null) {
11461 out.writeInt(1);
11462 c.writeSummaryFromParcelLocked(out);
11463 } else {
11464 out.writeInt(0);
11465 }
11466 }
11467 } else {
11468 out.writeInt(0);
11469 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011470 }
Adam Lesinski6832f392015-09-05 18:05:40 -070011471 } else {
11472 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011473 }
11474
Adam Lesinski5f056f62016-07-14 16:56:08 -070011475 if (u.mMobileRadioApWakeupCount != null) {
11476 out.writeInt(1);
11477 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
11478 } else {
11479 out.writeInt(0);
11480 }
11481
11482 if (u.mWifiRadioApWakeupCount != null) {
11483 out.writeInt(1);
11484 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
11485 } else {
11486 out.writeInt(0);
11487 }
11488
Dianne Hackbornd953c532014-08-16 18:17:38 -070011489 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
11490 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011491 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070011492 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070011493 out.writeString(wakeStats.keyAt(iw));
11494 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070011495 if (wl.mTimerFull != null) {
11496 out.writeInt(1);
11497 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11498 } else {
11499 out.writeInt(0);
11500 }
11501 if (wl.mTimerPartial != null) {
11502 out.writeInt(1);
11503 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11504 } else {
11505 out.writeInt(0);
11506 }
11507 if (wl.mTimerWindow != null) {
11508 out.writeInt(1);
11509 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11510 } else {
11511 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011512 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070011513 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070011514 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070011515 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070011516 } else {
11517 out.writeInt(0);
11518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011519 }
11520
Dianne Hackbornd953c532014-08-16 18:17:38 -070011521 final ArrayMap<String, StopwatchTimer> syncStats = u.mSyncStats.getMap();
11522 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011523 out.writeInt(NS);
11524 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070011525 out.writeString(syncStats.keyAt(is));
11526 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011527 }
11528
Dianne Hackbornd953c532014-08-16 18:17:38 -070011529 final ArrayMap<String, StopwatchTimer> jobStats = u.mJobStats.getMap();
11530 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011531 out.writeInt(NJ);
11532 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070011533 out.writeString(jobStats.keyAt(ij));
11534 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011535 }
11536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011537 int NSE = u.mSensorStats.size();
11538 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070011539 for (int ise=0; ise<NSE; ise++) {
11540 out.writeInt(u.mSensorStats.keyAt(ise));
11541 Uid.Sensor se = u.mSensorStats.valueAt(ise);
11542 if (se.mTimer != null) {
11543 out.writeInt(1);
11544 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
11545 } else {
11546 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011547 }
11548 }
11549
11550 int NP = u.mProcessStats.size();
11551 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070011552 for (int ip=0; ip<NP; ip++) {
11553 out.writeString(u.mProcessStats.keyAt(ip));
11554 Uid.Proc ps = u.mProcessStats.valueAt(ip);
11555 out.writeLong(ps.mUserTime);
11556 out.writeLong(ps.mSystemTime);
11557 out.writeLong(ps.mForegroundTime);
11558 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080011559 out.writeInt(ps.mNumCrashes);
11560 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070011561 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011562 }
11563
11564 NP = u.mPackageStats.size();
11565 out.writeInt(NP);
11566 if (NP > 0) {
11567 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
11568 : u.mPackageStats.entrySet()) {
11569 out.writeString(ent.getKey());
11570 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070011571 final int NWA = ps.mWakeupAlarms.size();
11572 out.writeInt(NWA);
11573 for (int iwa=0; iwa<NWA; iwa++) {
11574 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
11575 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
11576 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011577 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011578 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070011579 for (int is=0; is<NS; is++) {
11580 out.writeString(ps.mServiceStats.keyAt(is));
11581 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
11582 long time = ss.getStartTimeToNowLocked(
11583 mOnBatteryTimeBase.getUptime(NOW_SYS));
11584 out.writeLong(time);
11585 out.writeInt(ss.mStarts);
11586 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011587 }
11588 }
11589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011590 }
11591 }
11592
11593 public void readFromParcel(Parcel in) {
11594 readFromParcelLocked(in);
11595 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011597 void readFromParcelLocked(Parcel in) {
11598 int magic = in.readInt();
11599 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011600 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011601 }
11602
Dianne Hackbornae384452011-06-28 12:33:48 -070011603 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011605 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080011606 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070011607 mStartPlatformVersion = in.readString();
11608 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011609 mUptime = in.readLong();
11610 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011611 mRealtime = in.readLong();
11612 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011613 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070011614 mEstimatedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011616 mOnBatteryTimeBase.readFromParcel(in);
11617 mOnBatteryScreenOffTimeBase.readFromParcel(in);
11618
Jeff Browne95c3cd2014-05-02 16:59:26 -070011619 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080011620 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011621 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080011622 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
11623 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011624 }
Dianne Hackborn29325132014-05-21 15:01:03 -070011625 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080011626 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011627 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080011628 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
11629 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070011630 mLongestLightIdleTime = in.readLong();
11631 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080011632 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
11633 mOnBatteryTimeBase, in);
11634 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
11635 mOnBatteryTimeBase, in);
11636 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
11637 mOnBatteryTimeBase, in);
11638 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
11639 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011640 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080011641 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011642 null, mOnBatteryTimeBase, in);
11643 }
Joe Onoratoabded112016-02-08 16:49:39 -080011644 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
11645 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011646 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080011647 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011648 null, mOnBatteryTimeBase, in);
11649 }
11650 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
11651 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
11652 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
11653 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011654 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080011655 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
11656 mOnBatteryTimeBase, in);
11657 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
11658 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011659 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011660 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
11661 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070011662 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011663 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080011664 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011665 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080011666 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
11667 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011668 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080011669 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011670 null, mOnBatteryTimeBase, in);
11671 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070011672 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080011673 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070011674 null, mOnBatteryTimeBase, in);
11675 }
11676 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080011677 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070011678 null, mOnBatteryTimeBase, in);
11679 }
Adam Lesinski33dac552015-03-09 15:24:48 -070011680
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011681 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
11682 NUM_WIFI_TX_LEVELS, in);
11683 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
11684 NUM_BT_TX_LEVELS, in);
11685 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
11686 ModemActivityInfo.TX_POWER_LEVELS, in);
11687 mHasWifiReporting = in.readInt() != 0;
11688 mHasBluetoothReporting = in.readInt() != 0;
11689 mHasModemReporting = in.readInt() != 0;
11690
Dianne Hackborn1e01d162014-12-04 17:46:42 -080011691 mNumConnectivityChange = in.readInt();
11692 mLoadedNumConnectivityChange = in.readInt();
11693 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070011694 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080011695 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070011696 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080011697 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011698 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080011699 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011700 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080011701 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011702 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080011703 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011704 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011705 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070011706 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011707 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011708 mLowDischargeAmountSinceCharge = in.readInt();
11709 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011710 mDischargeAmountScreenOn = in.readInt();
11711 mDischargeAmountScreenOnSinceCharge = in.readInt();
11712 mDischargeAmountScreenOff = in.readInt();
11713 mDischargeAmountScreenOffSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011714 mDischargeStepTracker.readFromParcel(in);
11715 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070011716 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
11717 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 mLastWriteTime = in.readLong();
11719
Evan Millarc64edde2009-04-18 12:26:32 -070011720 mKernelWakelockStats.clear();
11721 int NKW = in.readInt();
11722 for (int ikw = 0; ikw < NKW; ikw++) {
11723 if (in.readInt() != 0) {
11724 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080011725 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070011726 mKernelWakelockStats.put(wakelockName, kwlt);
11727 }
11728 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011729
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011730 mWakeupReasonStats.clear();
11731 int NWR = in.readInt();
11732 for (int iwr = 0; iwr < NWR; iwr++) {
11733 if (in.readInt() != 0) {
11734 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080011735 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070011736 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011737 }
11738 }
11739
James Carr3a226052016-07-01 14:49:52 -070011740 mKernelMemoryStats.clear();
11741 int nmt = in.readInt();
11742 for (int imt = 0; imt < nmt; imt++) {
11743 if (in.readInt() != 0) {
11744 Long bucket = in.readLong();
11745 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
11746 mKernelMemoryStats.put(bucket, kmt);
11747 }
11748 }
11749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011750 mPartialTimers.clear();
11751 mFullTimers.clear();
11752 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070011753 mWifiRunningTimers.clear();
11754 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070011755 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070011756 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070011757 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070011758 mAudioTurnedOnTimers.clear();
11759 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011760 mFlashlightTurnedOnTimers.clear();
11761 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011762
11763 int numUids = in.readInt();
11764 mUidStats.clear();
11765 for (int i = 0; i < numUids; i++) {
11766 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080011767 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011768 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011769 mUidStats.append(uid, u);
11770 }
11771 }
11772
11773 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011774 writeToParcelLocked(out, true, flags);
11775 }
11776
11777 public void writeToParcelWithoutUids(Parcel out, int flags) {
11778 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011779 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011780
11781 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011782 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011783 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011784 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011785
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070011786 // Pull the clock time. This may update the time and make a new history entry
11787 // if we had originally pulled a time before the RTC was set.
11788 long startClockTime = getStartClockTime();
11789
Joe Onoratoabded112016-02-08 16:49:39 -080011790 final long uSecUptime = mClocks.uptimeMillis() * 1000;
11791 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011792 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
11793 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011795 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011796
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011797 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011799 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070011800 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070011801 out.writeString(mStartPlatformVersion);
11802 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011803 out.writeLong(mUptime);
11804 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011805 out.writeLong(mRealtime);
11806 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011807 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070011808 out.writeInt(mEstimatedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011809 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
11810 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
11811
11812 mScreenOnTimer.writeToParcel(out, uSecRealtime);
11813 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
11814 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
11815 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070011816 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070011817 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070011818 out.writeLong(mLongestLightIdleTime);
11819 out.writeLong(mLongestFullIdleTime);
11820 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
11821 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
11822 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070011823 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011824 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
11825 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
11826 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
11827 }
11828 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
11829 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
11830 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
11831 }
11832 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
11833 mNetworkByteActivityCounters[i].writeToParcel(out);
11834 mNetworkPacketActivityCounters[i].writeToParcel(out);
11835 }
11836 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
11837 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011838 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011839 mMobileRadioActiveUnknownTime.writeToParcel(out);
11840 mMobileRadioActiveUnknownCount.writeToParcel(out);
11841 mWifiOnTimer.writeToParcel(out, uSecRealtime);
11842 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
11843 for (int i=0; i<NUM_WIFI_STATES; i++) {
11844 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
11845 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070011846 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
11847 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
11848 }
11849 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
11850 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
11851 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011852 mWifiActivity.writeToParcel(out, 0);
11853 mBluetoothActivity.writeToParcel(out, 0);
11854 mModemActivity.writeToParcel(out, 0);
11855 out.writeInt(mHasWifiReporting ? 1 : 0);
11856 out.writeInt(mHasBluetoothReporting ? 1 : 0);
11857 out.writeInt(mHasModemReporting ? 1 : 0);
11858
Dianne Hackborn1e01d162014-12-04 17:46:42 -080011859 out.writeInt(mNumConnectivityChange);
11860 out.writeInt(mLoadedNumConnectivityChange);
11861 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070011862 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011863 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011864 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011865 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011866 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070011867 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011868 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011869 out.writeInt(mLowDischargeAmountSinceCharge);
11870 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011871 out.writeInt(mDischargeAmountScreenOn);
11872 out.writeInt(mDischargeAmountScreenOnSinceCharge);
11873 out.writeInt(mDischargeAmountScreenOff);
11874 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011875 mDischargeStepTracker.writeToParcel(out);
11876 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070011877 mDischargeCounter.writeToParcel(out);
11878 mDischargeScreenOffCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011879 out.writeLong(mLastWriteTime);
11880
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011881 if (inclUids) {
11882 out.writeInt(mKernelWakelockStats.size());
11883 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11884 SamplingTimer kwlt = ent.getValue();
11885 if (kwlt != null) {
11886 out.writeInt(1);
11887 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011888 kwlt.writeToParcel(out, uSecRealtime);
11889 } else {
11890 out.writeInt(0);
11891 }
11892 }
11893 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070011894 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
11895 SamplingTimer timer = ent.getValue();
11896 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011897 out.writeInt(1);
11898 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070011899 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011900 } else {
11901 out.writeInt(0);
11902 }
Evan Millarc64edde2009-04-18 12:26:32 -070011903 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011904 } else {
11905 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070011906 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070011907
James Carr3a226052016-07-01 14:49:52 -070011908 out.writeInt(mKernelMemoryStats.size());
11909 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
11910 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
11911 if (kmt != null) {
11912 out.writeInt(1);
11913 out.writeLong(mKernelMemoryStats.keyAt(i));
11914 kmt.writeToParcel(out, uSecRealtime);
11915 } else {
11916 out.writeInt(0);
11917 }
11918 }
11919
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011920 if (inclUids) {
11921 int size = mUidStats.size();
11922 out.writeInt(size);
11923 for (int i = 0; i < size; i++) {
11924 out.writeInt(mUidStats.keyAt(i));
11925 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011926
Bookatz867c0d72017-03-07 18:23:42 -080011927 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011928 }
11929 } else {
11930 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011931 }
11932 }
11933
11934 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
11935 new Parcelable.Creator<BatteryStatsImpl>() {
11936 public BatteryStatsImpl createFromParcel(Parcel in) {
11937 return new BatteryStatsImpl(in);
11938 }
11939
11940 public BatteryStatsImpl[] newArray(int size) {
11941 return new BatteryStatsImpl[size];
11942 }
11943 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011944
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011945 public void prepareForDumpLocked() {
11946 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011947 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070011948
11949 // Pull the clock time. This may update the time and make a new history entry
11950 // if we had originally pulled a time before the RTC was set.
11951 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011952 }
11953
Dianne Hackbornc51cf032014-03-02 19:08:15 -080011954 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011955 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011956 pw.println("mOnBatteryTimeBase:");
11957 mOnBatteryTimeBase.dump(pw, " ");
11958 pw.println("mOnBatteryScreenOffTimeBase:");
11959 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070011960 Printer pr = new PrintWriterPrinter(pw);
11961 pr.println("*** Screen timer:");
11962 mScreenOnTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070011963 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070011964 pr.println("*** Screen brightness #" + i + ":");
11965 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070011966 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070011967 pr.println("*** Interactive timer:");
11968 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070011969 pr.println("*** Power save mode timer:");
11970 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070011971 pr.println("*** Device idle mode light timer:");
11972 mDeviceIdleModeLightTimer.logState(pr, " ");
11973 pr.println("*** Device idle mode full timer:");
11974 mDeviceIdleModeFullTimer.logState(pr, " ");
11975 pr.println("*** Device light idling timer:");
11976 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070011977 pr.println("*** Device idling timer:");
11978 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070011979 pr.println("*** Phone timer:");
11980 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080011981 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070011982 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070011983 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070011984 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070011985 pr.println("*** Signal scanning :");
11986 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070011987 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070011988 pr.println("*** Data connection type #" + i + ":");
11989 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070011990 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011991 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080011992 pr.println("*** Mobile network active timer:");
11993 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011994 pr.println("*** Mobile network active adjusted timer:");
11995 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070011996 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070011997 pr.println("*** Wifi timer:");
11998 mWifiOnTimer.logState(pr, " ");
11999 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012000 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080012001 for (int i=0; i<NUM_WIFI_STATES; i++) {
12002 pr.println("*** Wifi state #" + i + ":");
12003 mWifiStateTimer[i].logState(pr, " ");
12004 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012005 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12006 pr.println("*** Wifi suppl state #" + i + ":");
12007 mWifiSupplStateTimer[i].logState(pr, " ");
12008 }
12009 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12010 pr.println("*** Wifi signal strength #" + i + ":");
12011 mWifiSignalStrengthsTimer[i].logState(pr, " ");
12012 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070012013 pr.println("*** Flashlight timer:");
12014 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012015 pr.println("*** Camera timer:");
12016 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012017 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080012018 super.dumpLocked(context, pw, flags, reqUid, histStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012020}