BatteryStatsImpl.java revision 9425fe21c9a8ab894e4a3b12a418564c4349394e
1/* 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 19import android.annotation.Nullable; 20import android.app.ActivityManager; 21import android.bluetooth.BluetoothActivityEnergyInfo; 22import android.content.Context; 23import android.content.Intent; 24import android.net.ConnectivityManager; 25import android.net.NetworkStats; 26import android.net.wifi.WifiActivityEnergyInfo; 27import android.net.wifi.WifiManager; 28import android.os.BadParcelableException; 29import android.os.BatteryManager; 30import android.os.BatteryStats; 31import android.os.Build; 32import android.os.FileUtils; 33import android.os.Handler; 34import android.os.Looper; 35import android.os.Message; 36import android.os.Parcel; 37import android.os.ParcelFormatException; 38import android.os.Parcelable; 39import android.os.Process; 40import android.os.SystemClock; 41import android.os.SystemProperties; 42import android.os.WorkSource; 43import android.telephony.DataConnectionRealTimeInfo; 44import android.telephony.ServiceState; 45import android.telephony.SignalStrength; 46import android.telephony.TelephonyManager; 47import android.text.TextUtils; 48import android.util.ArrayMap; 49import android.util.Log; 50import android.util.LogWriter; 51import android.util.MutableInt; 52import android.util.PrintWriterPrinter; 53import android.util.Printer; 54import android.util.Slog; 55import android.util.SparseArray; 56import android.util.SparseIntArray; 57import android.util.SparseLongArray; 58import android.util.TimeUtils; 59import android.util.Xml; 60import android.view.Display; 61 62import com.android.internal.net.NetworkStatsFactory; 63import com.android.internal.util.ArrayUtils; 64import com.android.internal.util.FastPrintWriter; 65import com.android.internal.util.FastXmlSerializer; 66import com.android.internal.util.JournaledFile; 67import com.android.internal.util.XmlUtils; 68import com.android.server.NetworkManagementSocketTagger; 69import libcore.util.EmptyArray; 70import org.xmlpull.v1.XmlPullParser; 71import org.xmlpull.v1.XmlPullParserException; 72import org.xmlpull.v1.XmlSerializer; 73 74import java.io.ByteArrayOutputStream; 75import java.io.File; 76import java.io.FileInputStream; 77import java.io.FileNotFoundException; 78import java.io.FileOutputStream; 79import java.io.IOException; 80import java.io.PrintWriter; 81import java.nio.charset.StandardCharsets; 82import java.util.ArrayList; 83import java.util.Calendar; 84import java.util.HashMap; 85import java.util.Iterator; 86import java.util.Map; 87import java.util.concurrent.atomic.AtomicInteger; 88import java.util.concurrent.locks.ReentrantLock; 89 90/** 91 * All information we are collecting about things that can happen that impact 92 * battery life. All times are represented in microseconds except where indicated 93 * otherwise. 94 */ 95public final class BatteryStatsImpl extends BatteryStats { 96 private static final String TAG = "BatteryStatsImpl"; 97 private static final boolean DEBUG = false; 98 public static final boolean DEBUG_ENERGY = false; 99 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY || false; 100 private static final boolean DEBUG_HISTORY = false; 101 private static final boolean USE_OLD_HISTORY = false; // for debugging. 102 103 // TODO: remove "tcp" from network methods, since we measure total stats. 104 105 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data 106 private static final int MAGIC = 0xBA757475; // 'BATSTATS' 107 108 // Current on-disk Parcel version 109 private static final int VERSION = 129 + (USE_OLD_HISTORY ? 1000 : 0); 110 111 // Maximum number of items we will record in the history. 112 private static final int MAX_HISTORY_ITEMS = 2000; 113 114 // No, really, THIS is the maximum number of items we will record in the history. 115 private static final int MAX_MAX_HISTORY_ITEMS = 3000; 116 117 // The maximum number of names wakelocks we will keep track of 118 // per uid; once the limit is reached, we batch the remaining wakelocks 119 // in to one common name. 120 private static final int MAX_WAKELOCKS_PER_UID = 100; 121 122 private static int sNumSpeedSteps; 123 124 private final JournaledFile mFile; 125 public final AtomicFile mCheckinFile; 126 public final AtomicFile mDailyFile; 127 128 static final int MSG_UPDATE_WAKELOCKS = 1; 129 static final int MSG_REPORT_POWER_CHANGE = 2; 130 static final int MSG_REPORT_CHARGING = 3; 131 static final long DELAY_UPDATE_WAKELOCKS = 5*1000; 132 133 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader(); 134 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats(); 135 136 private final KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader(); 137 private final KernelCpuSpeedReader mKernelCpuSpeedReader = new KernelCpuSpeedReader(); 138 139 public interface BatteryCallback { 140 public void batteryNeedsCpuUpdate(); 141 public void batteryPowerChanged(boolean onBattery); 142 public void batterySendBroadcast(Intent intent); 143 } 144 145 final class MyHandler extends Handler { 146 public MyHandler(Looper looper) { 147 super(looper, null, true); 148 } 149 150 @Override 151 public void handleMessage(Message msg) { 152 BatteryCallback cb = mCallback; 153 switch (msg.what) { 154 case MSG_UPDATE_WAKELOCKS: 155 synchronized (BatteryStatsImpl.this) { 156 updateCpuTimeLocked(); 157 } 158 if (cb != null) { 159 cb.batteryNeedsCpuUpdate(); 160 } 161 break; 162 case MSG_REPORT_POWER_CHANGE: 163 if (cb != null) { 164 cb.batteryPowerChanged(msg.arg1 != 0); 165 } 166 break; 167 case MSG_REPORT_CHARGING: 168 if (cb != null) { 169 final String action; 170 synchronized (BatteryStatsImpl.this) { 171 action = mCharging ? BatteryManager.ACTION_CHARGING 172 : BatteryManager.ACTION_DISCHARGING; 173 } 174 Intent intent = new Intent(action); 175 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 176 cb.batterySendBroadcast(intent); 177 } 178 break; 179 } 180 } 181 } 182 183 public interface ExternalStatsSync { 184 void scheduleSync(String reason); 185 void scheduleWifiSync(String reason); 186 } 187 188 public final MyHandler mHandler; 189 private final ExternalStatsSync mExternalSync; 190 191 private BatteryCallback mCallback; 192 193 /** 194 * Mapping isolated uids to the actual owning app uid. 195 */ 196 final SparseIntArray mIsolatedUids = new SparseIntArray(); 197 198 /** 199 * The statistics we have collected organized by uids. 200 */ 201 final SparseArray<BatteryStatsImpl.Uid> mUidStats = 202 new SparseArray<BatteryStatsImpl.Uid>(); 203 204 // A set of pools of currently active timers. When a timer is queried, we will divide the 205 // elapsed time by the number of active timers to arrive at that timer's share of the time. 206 // In order to do this, we must refresh each timer whenever the number of active timers 207 // changes. 208 final ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>(); 209 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>(); 210 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>(); 211 final ArrayList<StopwatchTimer> mDozeTimers = new ArrayList<>(); 212 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>(); 213 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>(); 214 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>(); 215 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>(); 216 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>(); 217 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>(); 218 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>(); 219 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>(); 220 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>(); 221 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>(); 222 223 // Last partial timers we use for distributing CPU usage. 224 final ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>(); 225 226 // These are the objects that will want to do something when the device 227 // is unplugged from power. 228 final TimeBase mOnBatteryTimeBase = new TimeBase(); 229 230 // These are the objects that will want to do something when the device 231 // is unplugged from power *and* the screen is off. 232 final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase(); 233 234 // Set to true when we want to distribute CPU across wakelocks for the next 235 // CPU update, even if we aren't currently running wake locks. 236 boolean mDistributeWakelockCpu; 237 238 boolean mShuttingDown; 239 240 final HistoryEventTracker mActiveEvents = new HistoryEventTracker(); 241 242 long mHistoryBaseTime; 243 boolean mHaveBatteryLevel = false; 244 boolean mRecordingHistory = false; 245 int mNumHistoryItems; 246 247 static final int MAX_HISTORY_BUFFER = 256*1024; // 256KB 248 static final int MAX_MAX_HISTORY_BUFFER = 320*1024; // 320KB 249 final Parcel mHistoryBuffer = Parcel.obtain(); 250 final HistoryItem mHistoryLastWritten = new HistoryItem(); 251 final HistoryItem mHistoryLastLastWritten = new HistoryItem(); 252 final HistoryItem mHistoryReadTmp = new HistoryItem(); 253 final HistoryItem mHistoryAddTmp = new HistoryItem(); 254 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>(); 255 String[] mReadHistoryStrings; 256 int[] mReadHistoryUids; 257 int mReadHistoryChars; 258 int mNextHistoryTagIdx = 0; 259 int mNumHistoryTagChars = 0; 260 int mHistoryBufferLastPos = -1; 261 boolean mHistoryOverflow = false; 262 int mActiveHistoryStates = 0xffffffff; 263 int mActiveHistoryStates2 = 0xffffffff; 264 long mLastHistoryElapsedRealtime = 0; 265 long mTrackRunningHistoryElapsedRealtime = 0; 266 long mTrackRunningHistoryUptime = 0; 267 268 final HistoryItem mHistoryCur = new HistoryItem(); 269 270 HistoryItem mHistory; 271 HistoryItem mHistoryEnd; 272 HistoryItem mHistoryLastEnd; 273 HistoryItem mHistoryCache; 274 275 // Used by computeHistoryStepDetails 276 HistoryStepDetails mLastHistoryStepDetails = null; 277 byte mLastHistoryStepLevel = 0; 278 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails(); 279 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails(); 280 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails(); 281 282 /** 283 * Total time (in milliseconds) spent executing in user code. 284 */ 285 long mLastStepCpuUserTime; 286 long mCurStepCpuUserTime; 287 /** 288 * Total time (in milliseconds) spent executing in kernel code. 289 */ 290 long mLastStepCpuSystemTime; 291 long mCurStepCpuSystemTime; 292 /** 293 * Times from /proc/stat (but measured in milliseconds). 294 */ 295 long mLastStepStatUserTime; 296 long mLastStepStatSystemTime; 297 long mLastStepStatIOWaitTime; 298 long mLastStepStatIrqTime; 299 long mLastStepStatSoftIrqTime; 300 long mLastStepStatIdleTime; 301 long mCurStepStatUserTime; 302 long mCurStepStatSystemTime; 303 long mCurStepStatIOWaitTime; 304 long mCurStepStatIrqTime; 305 long mCurStepStatSoftIrqTime; 306 long mCurStepStatIdleTime; 307 308 private HistoryItem mHistoryIterator; 309 private boolean mReadOverflow; 310 private boolean mIteratingHistory; 311 312 int mStartCount; 313 314 long mStartClockTime; 315 String mStartPlatformVersion; 316 String mEndPlatformVersion; 317 318 long mUptime; 319 long mUptimeStart; 320 long mRealtime; 321 long mRealtimeStart; 322 323 int mWakeLockNesting; 324 boolean mWakeLockImportant; 325 public boolean mRecordAllHistory; 326 boolean mNoAutoReset; 327 328 int mScreenState = Display.STATE_UNKNOWN; 329 StopwatchTimer mScreenOnTimer; 330 331 int mScreenBrightnessBin = -1; 332 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS]; 333 334 boolean mInteractive; 335 StopwatchTimer mInteractiveTimer; 336 337 boolean mPowerSaveModeEnabled; 338 StopwatchTimer mPowerSaveModeEnabledTimer; 339 340 boolean mDeviceIdling; 341 StopwatchTimer mDeviceIdlingTimer; 342 343 boolean mDeviceIdleModeEnabled; 344 StopwatchTimer mDeviceIdleModeEnabledTimer; 345 346 boolean mPhoneOn; 347 StopwatchTimer mPhoneOnTimer; 348 349 int mAudioOnNesting; 350 StopwatchTimer mAudioOnTimer; 351 352 int mVideoOnNesting; 353 StopwatchTimer mVideoOnTimer; 354 355 int mFlashlightOnNesting; 356 StopwatchTimer mFlashlightOnTimer; 357 358 int mCameraOnNesting; 359 StopwatchTimer mCameraOnTimer; 360 361 int mPhoneSignalStrengthBin = -1; 362 int mPhoneSignalStrengthBinRaw = -1; 363 final StopwatchTimer[] mPhoneSignalStrengthsTimer = 364 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS]; 365 366 StopwatchTimer mPhoneSignalScanningTimer; 367 368 int mPhoneDataConnectionType = -1; 369 final StopwatchTimer[] mPhoneDataConnectionsTimer = 370 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES]; 371 372 final LongSamplingCounter[] mNetworkByteActivityCounters = 373 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES]; 374 final LongSamplingCounter[] mNetworkPacketActivityCounters = 375 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES]; 376 377 final LongSamplingCounter[] mBluetoothActivityCounters = 378 new LongSamplingCounter[NUM_CONTROLLER_ACTIVITY_TYPES]; 379 380 final LongSamplingCounter[] mWifiActivityCounters = 381 new LongSamplingCounter[NUM_CONTROLLER_ACTIVITY_TYPES]; 382 383 boolean mWifiOn; 384 StopwatchTimer mWifiOnTimer; 385 386 boolean mGlobalWifiRunning; 387 StopwatchTimer mGlobalWifiRunningTimer; 388 389 int mWifiState = -1; 390 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES]; 391 392 int mWifiSupplState = -1; 393 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES]; 394 395 int mWifiSignalStrengthBin = -1; 396 final StopwatchTimer[] mWifiSignalStrengthsTimer = 397 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS]; 398 399 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW; 400 long mMobileRadioActiveStartTime; 401 StopwatchTimer mMobileRadioActiveTimer; 402 StopwatchTimer mMobileRadioActivePerAppTimer; 403 LongSamplingCounter mMobileRadioActiveAdjustedTime; 404 LongSamplingCounter mMobileRadioActiveUnknownTime; 405 LongSamplingCounter mMobileRadioActiveUnknownCount; 406 407 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW; 408 409 /** 410 * These provide time bases that discount the time the device is plugged 411 * in to power. 412 */ 413 boolean mOnBattery; 414 boolean mOnBatteryInternal; 415 416 /** 417 * External reporting of whether the device is actually charging. 418 */ 419 boolean mCharging = true; 420 int mLastChargingStateLevel; 421 422 /* 423 * These keep track of battery levels (1-100) at the last plug event and the last unplug event. 424 */ 425 int mDischargeStartLevel; 426 int mDischargeUnplugLevel; 427 int mDischargePlugLevel; 428 int mDischargeCurrentLevel; 429 int mCurrentBatteryLevel; 430 int mLowDischargeAmountSinceCharge; 431 int mHighDischargeAmountSinceCharge; 432 int mDischargeScreenOnUnplugLevel; 433 int mDischargeScreenOffUnplugLevel; 434 int mDischargeAmountScreenOn; 435 int mDischargeAmountScreenOnSinceCharge; 436 int mDischargeAmountScreenOff; 437 int mDischargeAmountScreenOffSinceCharge; 438 439 static final int MAX_LEVEL_STEPS = 200; 440 441 int mInitStepMode = 0; 442 int mCurStepMode = 0; 443 int mModStepMode = 0; 444 445 int mLastDischargeStepLevel; 446 int mMinDischargeStepLevel; 447 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS); 448 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2); 449 ArrayList<PackageChange> mDailyPackageChanges; 450 451 int mLastChargeStepLevel; 452 int mMaxChargeStepLevel; 453 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS); 454 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2); 455 456 static final int MAX_DAILY_ITEMS = 10; 457 458 long mDailyStartTime = 0; 459 long mNextMinDailyDeadline = 0; 460 long mNextMaxDailyDeadline = 0; 461 462 final ArrayList<DailyItem> mDailyItems = new ArrayList<>(); 463 464 long mLastWriteTime = 0; // Milliseconds 465 466 private int mPhoneServiceState = -1; 467 private int mPhoneServiceStateRaw = -1; 468 private int mPhoneSimStateRaw = -1; 469 470 private int mNumConnectivityChange; 471 private int mLoadedNumConnectivityChange; 472 private int mUnpluggedNumConnectivityChange; 473 474 private final NetworkStats.Entry mTmpNetworkStatsEntry = new NetworkStats.Entry(); 475 476 private PowerProfile mPowerProfile; 477 private boolean mHasWifiEnergyReporting = false; 478 private boolean mHasBluetoothEnergyReporting = false; 479 480 /* 481 * Holds a SamplingTimer associated with each kernel wakelock name being tracked. 482 */ 483 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>(); 484 485 public Map<String, ? extends Timer> getKernelWakelockStats() { 486 return mKernelWakelockStats; 487 } 488 489 String mLastWakeupReason = null; 490 long mLastWakeupUptimeMs = 0; 491 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>(); 492 493 public Map<String, ? extends Timer> getWakeupReasonStats() { 494 return mWakeupReasonStats; 495 } 496 497 public BatteryStatsImpl() { 498 mFile = null; 499 mCheckinFile = null; 500 mDailyFile = null; 501 mHandler = null; 502 mExternalSync = null; 503 clearHistoryLocked(); 504 } 505 506 public static interface TimeBaseObs { 507 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime); 508 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime); 509 } 510 511 static class TimeBase { 512 private final ArrayList<TimeBaseObs> mObservers = new ArrayList<>(); 513 514 private long mUptime; 515 private long mRealtime; 516 517 private boolean mRunning; 518 519 private long mPastUptime; 520 private long mUptimeStart; 521 private long mPastRealtime; 522 private long mRealtimeStart; 523 private long mUnpluggedUptime; 524 private long mUnpluggedRealtime; 525 526 public void dump(PrintWriter pw, String prefix) { 527 StringBuilder sb = new StringBuilder(128); 528 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning); 529 sb.setLength(0); 530 sb.append(prefix); 531 sb.append("mUptime="); 532 formatTimeMs(sb, mUptime / 1000); 533 pw.println(sb.toString()); 534 sb.setLength(0); 535 sb.append(prefix); 536 sb.append("mRealtime="); 537 formatTimeMs(sb, mRealtime / 1000); 538 pw.println(sb.toString()); 539 sb.setLength(0); 540 sb.append(prefix); 541 sb.append("mPastUptime="); 542 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart="); 543 formatTimeMs(sb, mUptimeStart / 1000); 544 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000); 545 pw.println(sb.toString()); 546 sb.setLength(0); 547 sb.append(prefix); 548 sb.append("mPastRealtime="); 549 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart="); 550 formatTimeMs(sb, mRealtimeStart / 1000); 551 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000); 552 pw.println(sb.toString()); 553 } 554 555 public void add(TimeBaseObs observer) { 556 mObservers.add(observer); 557 } 558 559 public void remove(TimeBaseObs observer) { 560 if (!mObservers.remove(observer)) { 561 Slog.wtf(TAG, "Removed unknown observer: " + observer); 562 } 563 } 564 565 public void init(long uptime, long realtime) { 566 mRealtime = 0; 567 mUptime = 0; 568 mPastUptime = 0; 569 mPastRealtime = 0; 570 mUptimeStart = uptime; 571 mRealtimeStart = realtime; 572 mUnpluggedUptime = getUptime(mUptimeStart); 573 mUnpluggedRealtime = getRealtime(mRealtimeStart); 574 } 575 576 public void reset(long uptime, long realtime) { 577 if (!mRunning) { 578 mPastUptime = 0; 579 mPastRealtime = 0; 580 } else { 581 mUptimeStart = uptime; 582 mRealtimeStart = realtime; 583 mUnpluggedUptime = getUptime(uptime); 584 mUnpluggedRealtime = getRealtime(realtime); 585 } 586 } 587 588 public long computeUptime(long curTime, int which) { 589 switch (which) { 590 case STATS_SINCE_CHARGED: 591 return mUptime + getUptime(curTime); 592 case STATS_CURRENT: 593 return getUptime(curTime); 594 case STATS_SINCE_UNPLUGGED: 595 return getUptime(curTime) - mUnpluggedUptime; 596 } 597 return 0; 598 } 599 600 public long computeRealtime(long curTime, int which) { 601 switch (which) { 602 case STATS_SINCE_CHARGED: 603 return mRealtime + getRealtime(curTime); 604 case STATS_CURRENT: 605 return getRealtime(curTime); 606 case STATS_SINCE_UNPLUGGED: 607 return getRealtime(curTime) - mUnpluggedRealtime; 608 } 609 return 0; 610 } 611 612 public long getUptime(long curTime) { 613 long time = mPastUptime; 614 if (mRunning) { 615 time += curTime - mUptimeStart; 616 } 617 return time; 618 } 619 620 public long getRealtime(long curTime) { 621 long time = mPastRealtime; 622 if (mRunning) { 623 time += curTime - mRealtimeStart; 624 } 625 return time; 626 } 627 628 public long getUptimeStart() { 629 return mUptimeStart; 630 } 631 632 public long getRealtimeStart() { 633 return mRealtimeStart; 634 } 635 636 public boolean isRunning() { 637 return mRunning; 638 } 639 640 public boolean setRunning(boolean running, long uptime, long realtime) { 641 if (mRunning != running) { 642 mRunning = running; 643 if (running) { 644 mUptimeStart = uptime; 645 mRealtimeStart = realtime; 646 long batteryUptime = mUnpluggedUptime = getUptime(uptime); 647 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime); 648 649 for (int i = mObservers.size() - 1; i >= 0; i--) { 650 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime); 651 } 652 } else { 653 mPastUptime += uptime - mUptimeStart; 654 mPastRealtime += realtime - mRealtimeStart; 655 656 long batteryUptime = getUptime(uptime); 657 long batteryRealtime = getRealtime(realtime); 658 659 for (int i = mObservers.size() - 1; i >= 0; i--) { 660 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime); 661 } 662 } 663 return true; 664 } 665 return false; 666 } 667 668 public void readSummaryFromParcel(Parcel in) { 669 mUptime = in.readLong(); 670 mRealtime = in.readLong(); 671 } 672 673 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) { 674 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED)); 675 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED)); 676 } 677 678 public void readFromParcel(Parcel in) { 679 mRunning = false; 680 mUptime = in.readLong(); 681 mPastUptime = in.readLong(); 682 mUptimeStart = in.readLong(); 683 mRealtime = in.readLong(); 684 mPastRealtime = in.readLong(); 685 mRealtimeStart = in.readLong(); 686 mUnpluggedUptime = in.readLong(); 687 mUnpluggedRealtime = in.readLong(); 688 } 689 690 public void writeToParcel(Parcel out, long uptime, long realtime) { 691 final long runningUptime = getUptime(uptime); 692 final long runningRealtime = getRealtime(realtime); 693 out.writeLong(mUptime); 694 out.writeLong(runningUptime); 695 out.writeLong(mUptimeStart); 696 out.writeLong(mRealtime); 697 out.writeLong(runningRealtime); 698 out.writeLong(mRealtimeStart); 699 out.writeLong(mUnpluggedUptime); 700 out.writeLong(mUnpluggedRealtime); 701 } 702 } 703 704 /** 705 * State for keeping track of counting information. 706 */ 707 public static class Counter extends BatteryStats.Counter implements TimeBaseObs { 708 final AtomicInteger mCount = new AtomicInteger(); 709 final TimeBase mTimeBase; 710 int mLoadedCount; 711 int mLastCount; 712 int mUnpluggedCount; 713 int mPluggedCount; 714 715 Counter(TimeBase timeBase, Parcel in) { 716 mTimeBase = timeBase; 717 mPluggedCount = in.readInt(); 718 mCount.set(mPluggedCount); 719 mLoadedCount = in.readInt(); 720 mLastCount = 0; 721 mUnpluggedCount = in.readInt(); 722 timeBase.add(this); 723 } 724 725 Counter(TimeBase timeBase) { 726 mTimeBase = timeBase; 727 timeBase.add(this); 728 } 729 730 public void writeToParcel(Parcel out) { 731 out.writeInt(mCount.get()); 732 out.writeInt(mLoadedCount); 733 out.writeInt(mUnpluggedCount); 734 } 735 736 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) { 737 mUnpluggedCount = mPluggedCount; 738 mCount.set(mPluggedCount); 739 } 740 741 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) { 742 mPluggedCount = mCount.get(); 743 } 744 745 /** 746 * Writes a possibly null Counter to a Parcel. 747 * 748 * @param out the Parcel to be written to. 749 * @param counter a Counter, or null. 750 */ 751 public static void writeCounterToParcel(Parcel out, Counter counter) { 752 if (counter == null) { 753 out.writeInt(0); // indicates null 754 return; 755 } 756 out.writeInt(1); // indicates non-null 757 758 counter.writeToParcel(out); 759 } 760 761 @Override 762 public int getCountLocked(int which) { 763 int val = mCount.get(); 764 if (which == STATS_SINCE_UNPLUGGED) { 765 val -= mUnpluggedCount; 766 } else if (which != STATS_SINCE_CHARGED) { 767 val -= mLoadedCount; 768 } 769 770 return val; 771 } 772 773 public void logState(Printer pw, String prefix) { 774 pw.println(prefix + "mCount=" + mCount.get() 775 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount 776 + " mUnpluggedCount=" + mUnpluggedCount 777 + " mPluggedCount=" + mPluggedCount); 778 } 779 780 void stepAtomic() { 781 mCount.incrementAndGet(); 782 } 783 784 /** 785 * Clear state of this counter. 786 */ 787 void reset(boolean detachIfReset) { 788 mCount.set(0); 789 mLoadedCount = mLastCount = mPluggedCount = mUnpluggedCount = 0; 790 if (detachIfReset) { 791 detach(); 792 } 793 } 794 795 void detach() { 796 mTimeBase.remove(this); 797 } 798 799 void writeSummaryFromParcelLocked(Parcel out) { 800 int count = mCount.get(); 801 out.writeInt(count); 802 } 803 804 void readSummaryFromParcelLocked(Parcel in) { 805 mLoadedCount = in.readInt(); 806 mCount.set(mLoadedCount); 807 mLastCount = 0; 808 mUnpluggedCount = mPluggedCount = mLoadedCount; 809 } 810 } 811 812 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs { 813 final TimeBase mTimeBase; 814 long mCount; 815 long mLoadedCount; 816 long mLastCount; 817 long mUnpluggedCount; 818 long mPluggedCount; 819 820 LongSamplingCounter(TimeBase timeBase, Parcel in) { 821 mTimeBase = timeBase; 822 mPluggedCount = in.readLong(); 823 mCount = mPluggedCount; 824 mLoadedCount = in.readLong(); 825 mLastCount = 0; 826 mUnpluggedCount = in.readLong(); 827 timeBase.add(this); 828 } 829 830 LongSamplingCounter(TimeBase timeBase) { 831 mTimeBase = timeBase; 832 timeBase.add(this); 833 } 834 835 public void writeToParcel(Parcel out) { 836 out.writeLong(mCount); 837 out.writeLong(mLoadedCount); 838 out.writeLong(mUnpluggedCount); 839 } 840 841 @Override 842 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) { 843 mUnpluggedCount = mPluggedCount; 844 mCount = mPluggedCount; 845 } 846 847 @Override 848 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) { 849 mPluggedCount = mCount; 850 } 851 852 public long getCountLocked(int which) { 853 long val = mCount; 854 if (which == STATS_SINCE_UNPLUGGED) { 855 val -= mUnpluggedCount; 856 } else if (which != STATS_SINCE_CHARGED) { 857 val -= mLoadedCount; 858 } 859 860 return val; 861 } 862 863 @Override 864 public void logState(Printer pw, String prefix) { 865 pw.println(prefix + "mCount=" + mCount 866 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount 867 + " mUnpluggedCount=" + mUnpluggedCount 868 + " mPluggedCount=" + mPluggedCount); 869 } 870 871 void addCountLocked(long count) { 872 mCount += count; 873 } 874 875 /** 876 * Clear state of this counter. 877 */ 878 void reset(boolean detachIfReset) { 879 mCount = 0; 880 mLoadedCount = mLastCount = mPluggedCount = mUnpluggedCount = 0; 881 if (detachIfReset) { 882 detach(); 883 } 884 } 885 886 void detach() { 887 mTimeBase.remove(this); 888 } 889 890 void writeSummaryFromParcelLocked(Parcel out) { 891 out.writeLong(mCount); 892 } 893 894 void readSummaryFromParcelLocked(Parcel in) { 895 mLoadedCount = in.readLong(); 896 mCount = mLoadedCount; 897 mLastCount = 0; 898 mUnpluggedCount = mPluggedCount = mLoadedCount; 899 } 900 } 901 902 /** 903 * State for keeping track of timing information. 904 */ 905 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs { 906 final int mType; 907 final TimeBase mTimeBase; 908 909 int mCount; 910 int mLoadedCount; 911 int mLastCount; 912 int mUnpluggedCount; 913 914 // Times are in microseconds for better accuracy when dividing by the 915 // lock count, and are in "battery realtime" units. 916 917 /** 918 * The total time we have accumulated since the start of the original 919 * boot, to the last time something interesting happened in the 920 * current run. 921 */ 922 long mTotalTime; 923 924 /** 925 * The total time we loaded for the previous runs. Subtract this from 926 * mTotalTime to find the time for the current run of the system. 927 */ 928 long mLoadedTime; 929 930 /** 931 * The run time of the last run of the system, as loaded from the 932 * saved data. 933 */ 934 long mLastTime; 935 936 /** 937 * The value of mTotalTime when unplug() was last called. Subtract 938 * this from mTotalTime to find the time since the last unplug from 939 * power. 940 */ 941 long mUnpluggedTime; 942 943 /** 944 * The total time this timer has been running until the latest mark has been set. 945 * Subtract this from mTotalTime to get the time spent running since the mark was set. 946 */ 947 long mTimeBeforeMark; 948 949 /** 950 * Constructs from a parcel. 951 * @param type 952 * @param timeBase 953 * @param in 954 */ 955 Timer(int type, TimeBase timeBase, Parcel in) { 956 mType = type; 957 mTimeBase = timeBase; 958 959 mCount = in.readInt(); 960 mLoadedCount = in.readInt(); 961 mLastCount = 0; 962 mUnpluggedCount = in.readInt(); 963 mTotalTime = in.readLong(); 964 mLoadedTime = in.readLong(); 965 mLastTime = 0; 966 mUnpluggedTime = in.readLong(); 967 mTimeBeforeMark = in.readLong(); 968 timeBase.add(this); 969 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime); 970 } 971 972 Timer(int type, TimeBase timeBase) { 973 mType = type; 974 mTimeBase = timeBase; 975 timeBase.add(this); 976 } 977 978 protected abstract long computeRunTimeLocked(long curBatteryRealtime); 979 980 protected abstract int computeCurrentCountLocked(); 981 982 /** 983 * Clear state of this timer. Returns true if the timer is inactive 984 * so can be completely dropped. 985 */ 986 boolean reset(boolean detachIfReset) { 987 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0; 988 mCount = mLoadedCount = mLastCount = 0; 989 if (detachIfReset) { 990 detach(); 991 } 992 return true; 993 } 994 995 void detach() { 996 mTimeBase.remove(this); 997 } 998 999 public void writeToParcel(Parcel out, long elapsedRealtimeUs) { 1000 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime=" 1001 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs))); 1002 out.writeInt(mCount); 1003 out.writeInt(mLoadedCount); 1004 out.writeInt(mUnpluggedCount); 1005 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs))); 1006 out.writeLong(mLoadedTime); 1007 out.writeLong(mUnpluggedTime); 1008 out.writeLong(mTimeBeforeMark); 1009 } 1010 1011 @Override 1012 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) { 1013 if (DEBUG && mType < 0) { 1014 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime 1015 + " old mUnpluggedTime=" + mUnpluggedTime 1016 + " old mUnpluggedCount=" + mUnpluggedCount); 1017 } 1018 mUnpluggedTime = computeRunTimeLocked(baseRealtime); 1019 mUnpluggedCount = mCount; 1020 if (DEBUG && mType < 0) { 1021 Log.v(TAG, "unplug #" + mType 1022 + ": new mUnpluggedTime=" + mUnpluggedTime 1023 + " new mUnpluggedCount=" + mUnpluggedCount); 1024 } 1025 } 1026 1027 @Override 1028 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) { 1029 if (DEBUG && mType < 0) { 1030 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime 1031 + " old mTotalTime=" + mTotalTime); 1032 } 1033 mTotalTime = computeRunTimeLocked(baseRealtime); 1034 mCount = computeCurrentCountLocked(); 1035 if (DEBUG && mType < 0) { 1036 Log.v(TAG, "plug #" + mType 1037 + ": new mTotalTime=" + mTotalTime); 1038 } 1039 } 1040 1041 /** 1042 * Writes a possibly null Timer to a Parcel. 1043 * 1044 * @param out the Parcel to be written to. 1045 * @param timer a Timer, or null. 1046 */ 1047 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) { 1048 if (timer == null) { 1049 out.writeInt(0); // indicates null 1050 return; 1051 } 1052 out.writeInt(1); // indicates non-null 1053 1054 timer.writeToParcel(out, elapsedRealtimeUs); 1055 } 1056 1057 @Override 1058 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) { 1059 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)); 1060 if (which == STATS_SINCE_UNPLUGGED) { 1061 val -= mUnpluggedTime; 1062 } else if (which != STATS_SINCE_CHARGED) { 1063 val -= mLoadedTime; 1064 } 1065 1066 return val; 1067 } 1068 1069 @Override 1070 public int getCountLocked(int which) { 1071 int val = computeCurrentCountLocked(); 1072 if (which == STATS_SINCE_UNPLUGGED) { 1073 val -= mUnpluggedCount; 1074 } else if (which != STATS_SINCE_CHARGED) { 1075 val -= mLoadedCount; 1076 } 1077 1078 return val; 1079 } 1080 1081 @Override 1082 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) { 1083 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)); 1084 return val - mTimeBeforeMark; 1085 } 1086 1087 @Override 1088 public void logState(Printer pw, String prefix) { 1089 pw.println(prefix + "mCount=" + mCount 1090 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount 1091 + " mUnpluggedCount=" + mUnpluggedCount); 1092 pw.println(prefix + "mTotalTime=" + mTotalTime 1093 + " mLoadedTime=" + mLoadedTime); 1094 pw.println(prefix + "mLastTime=" + mLastTime 1095 + " mUnpluggedTime=" + mUnpluggedTime); 1096 } 1097 1098 1099 void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) { 1100 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)); 1101 out.writeLong(runTime); 1102 out.writeInt(mCount); 1103 } 1104 1105 void readSummaryFromParcelLocked(Parcel in) { 1106 // Multiply by 1000 for backwards compatibility 1107 mTotalTime = mLoadedTime = in.readLong(); 1108 mLastTime = 0; 1109 mUnpluggedTime = mTotalTime; 1110 mCount = mLoadedCount = in.readInt(); 1111 mLastCount = 0; 1112 mUnpluggedCount = mCount; 1113 1114 // When reading the summary, we set the mark to be the latest information. 1115 mTimeBeforeMark = mTotalTime; 1116 } 1117 } 1118 1119 public static final class SamplingTimer extends Timer { 1120 1121 /** 1122 * The most recent reported count from /proc/wakelocks. 1123 */ 1124 int mCurrentReportedCount; 1125 1126 /** 1127 * The reported count from /proc/wakelocks when unplug() was last 1128 * called. 1129 */ 1130 int mUnpluggedReportedCount; 1131 1132 /** 1133 * The most recent reported total_time from /proc/wakelocks. 1134 */ 1135 long mCurrentReportedTotalTime; 1136 1137 1138 /** 1139 * The reported total_time from /proc/wakelocks when unplug() was last 1140 * called. 1141 */ 1142 long mUnpluggedReportedTotalTime; 1143 1144 /** 1145 * Whether we are currently in a discharge cycle. 1146 */ 1147 boolean mTimeBaseRunning; 1148 1149 /** 1150 * Whether we are currently recording reported values. 1151 */ 1152 boolean mTrackingReportedValues; 1153 1154 /* 1155 * A sequence counter, incremented once for each update of the stats. 1156 */ 1157 int mUpdateVersion; 1158 1159 SamplingTimer(TimeBase timeBase, Parcel in) { 1160 super(0, timeBase, in); 1161 mCurrentReportedCount = in.readInt(); 1162 mUnpluggedReportedCount = in.readInt(); 1163 mCurrentReportedTotalTime = in.readLong(); 1164 mUnpluggedReportedTotalTime = in.readLong(); 1165 mTrackingReportedValues = in.readInt() == 1; 1166 mTimeBaseRunning = timeBase.isRunning(); 1167 } 1168 1169 SamplingTimer(TimeBase timeBase, boolean trackReportedValues) { 1170 super(0, timeBase); 1171 mTrackingReportedValues = trackReportedValues; 1172 mTimeBaseRunning = timeBase.isRunning(); 1173 } 1174 1175 public void setStale() { 1176 mTrackingReportedValues = false; 1177 mUnpluggedReportedTotalTime = 0; 1178 mUnpluggedReportedCount = 0; 1179 } 1180 1181 public void setUpdateVersion(int version) { 1182 mUpdateVersion = version; 1183 } 1184 1185 public int getUpdateVersion() { 1186 return mUpdateVersion; 1187 } 1188 1189 public void updateCurrentReportedCount(int count) { 1190 if (mTimeBaseRunning && mUnpluggedReportedCount == 0) { 1191 // Updating the reported value for the first time. 1192 mUnpluggedReportedCount = count; 1193 // If we are receiving an update update mTrackingReportedValues; 1194 mTrackingReportedValues = true; 1195 } 1196 mCurrentReportedCount = count; 1197 } 1198 1199 public void addCurrentReportedCount(int delta) { 1200 updateCurrentReportedCount(mCurrentReportedCount + delta); 1201 } 1202 1203 public void updateCurrentReportedTotalTime(long totalTime) { 1204 if (mTimeBaseRunning && mUnpluggedReportedTotalTime == 0) { 1205 // Updating the reported value for the first time. 1206 mUnpluggedReportedTotalTime = totalTime; 1207 // If we are receiving an update update mTrackingReportedValues; 1208 mTrackingReportedValues = true; 1209 } 1210 mCurrentReportedTotalTime = totalTime; 1211 } 1212 1213 public void addCurrentReportedTotalTime(long delta) { 1214 updateCurrentReportedTotalTime(mCurrentReportedTotalTime + delta); 1215 } 1216 1217 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) { 1218 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime); 1219 if (mTrackingReportedValues) { 1220 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime; 1221 mUnpluggedReportedCount = mCurrentReportedCount; 1222 } 1223 mTimeBaseRunning = true; 1224 } 1225 1226 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) { 1227 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime); 1228 mTimeBaseRunning = false; 1229 } 1230 1231 public void logState(Printer pw, String prefix) { 1232 super.logState(pw, prefix); 1233 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount 1234 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount 1235 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime 1236 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime); 1237 } 1238 1239 protected long computeRunTimeLocked(long curBatteryRealtime) { 1240 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues 1241 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0); 1242 } 1243 1244 protected int computeCurrentCountLocked() { 1245 return mCount + (mTimeBaseRunning && mTrackingReportedValues 1246 ? mCurrentReportedCount - mUnpluggedReportedCount : 0); 1247 } 1248 1249 public void writeToParcel(Parcel out, long elapsedRealtimeUs) { 1250 super.writeToParcel(out, elapsedRealtimeUs); 1251 out.writeInt(mCurrentReportedCount); 1252 out.writeInt(mUnpluggedReportedCount); 1253 out.writeLong(mCurrentReportedTotalTime); 1254 out.writeLong(mUnpluggedReportedTotalTime); 1255 out.writeInt(mTrackingReportedValues ? 1 : 0); 1256 } 1257 1258 boolean reset(boolean detachIfReset) { 1259 super.reset(detachIfReset); 1260 setStale(); 1261 return true; 1262 } 1263 1264 void writeSummaryFromParcelLocked(Parcel out, long batteryRealtime) { 1265 super.writeSummaryFromParcelLocked(out, batteryRealtime); 1266 out.writeLong(mCurrentReportedTotalTime); 1267 out.writeInt(mCurrentReportedCount); 1268 out.writeInt(mTrackingReportedValues ? 1 : 0); 1269 } 1270 1271 void readSummaryFromParcelLocked(Parcel in) { 1272 super.readSummaryFromParcelLocked(in); 1273 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = in.readLong(); 1274 mUnpluggedReportedCount = mCurrentReportedCount = in.readInt(); 1275 mTrackingReportedValues = in.readInt() == 1; 1276 } 1277 } 1278 1279 /** 1280 * A timer that increments in batches. It does not run for durations, but just jumps 1281 * for a pre-determined amount. 1282 */ 1283 public static final class BatchTimer extends Timer { 1284 final Uid mUid; 1285 1286 /** 1287 * The last time at which we updated the timer. This is in elapsed realtime microseconds. 1288 */ 1289 long mLastAddedTime; 1290 1291 /** 1292 * The last duration that we added to the timer. This is in microseconds. 1293 */ 1294 long mLastAddedDuration; 1295 1296 /** 1297 * Whether we are currently in a discharge cycle. 1298 */ 1299 boolean mInDischarge; 1300 1301 BatchTimer(Uid uid, int type, TimeBase timeBase, Parcel in) { 1302 super(type, timeBase, in); 1303 mUid = uid; 1304 mLastAddedTime = in.readLong(); 1305 mLastAddedDuration = in.readLong(); 1306 mInDischarge = timeBase.isRunning(); 1307 } 1308 1309 BatchTimer(Uid uid, int type, TimeBase timeBase) { 1310 super(type, timeBase); 1311 mUid = uid; 1312 mInDischarge = timeBase.isRunning(); 1313 } 1314 1315 @Override 1316 public void writeToParcel(Parcel out, long elapsedRealtimeUs) { 1317 super.writeToParcel(out, elapsedRealtimeUs); 1318 out.writeLong(mLastAddedTime); 1319 out.writeLong(mLastAddedDuration); 1320 } 1321 1322 @Override 1323 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) { 1324 recomputeLastDuration(SystemClock.elapsedRealtime() * 1000, false); 1325 mInDischarge = false; 1326 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime); 1327 } 1328 1329 @Override 1330 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) { 1331 recomputeLastDuration(elapsedRealtime, false); 1332 mInDischarge = true; 1333 // If we are still within the last added duration, then re-added whatever remains. 1334 if (mLastAddedTime == elapsedRealtime) { 1335 mTotalTime += mLastAddedDuration; 1336 } 1337 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime); 1338 } 1339 1340 @Override 1341 public void logState(Printer pw, String prefix) { 1342 super.logState(pw, prefix); 1343 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime 1344 + " mLastAddedDuration=" + mLastAddedDuration); 1345 } 1346 1347 private long computeOverage(long curTime) { 1348 if (mLastAddedTime > 0) { 1349 return mLastTime + mLastAddedDuration - curTime; 1350 } 1351 return 0; 1352 } 1353 1354 private void recomputeLastDuration(long curTime, boolean abort) { 1355 final long overage = computeOverage(curTime); 1356 if (overage > 0) { 1357 // Aborting before the duration ran out -- roll back the remaining 1358 // duration. Only do this if currently discharging; otherwise we didn't 1359 // actually add the time. 1360 if (mInDischarge) { 1361 mTotalTime -= overage; 1362 } 1363 if (abort) { 1364 mLastAddedTime = 0; 1365 } else { 1366 mLastAddedTime = curTime; 1367 mLastAddedDuration -= overage; 1368 } 1369 } 1370 } 1371 1372 public void addDuration(BatteryStatsImpl stats, long durationMillis) { 1373 final long now = SystemClock.elapsedRealtime() * 1000; 1374 recomputeLastDuration(now, true); 1375 mLastAddedTime = now; 1376 mLastAddedDuration = durationMillis * 1000; 1377 if (mInDischarge) { 1378 mTotalTime += mLastAddedDuration; 1379 mCount++; 1380 } 1381 } 1382 1383 public void abortLastDuration(BatteryStatsImpl stats) { 1384 final long now = SystemClock.elapsedRealtime() * 1000; 1385 recomputeLastDuration(now, true); 1386 } 1387 1388 @Override 1389 protected int computeCurrentCountLocked() { 1390 return mCount; 1391 } 1392 1393 @Override 1394 protected long computeRunTimeLocked(long curBatteryRealtime) { 1395 final long overage = computeOverage(SystemClock.elapsedRealtime() * 1000); 1396 if (overage > 0) { 1397 return mTotalTime = overage; 1398 } 1399 return mTotalTime; 1400 } 1401 1402 @Override 1403 boolean reset(boolean detachIfReset) { 1404 final long now = SystemClock.elapsedRealtime() * 1000; 1405 recomputeLastDuration(now, true); 1406 boolean stillActive = mLastAddedTime == now; 1407 super.reset(!stillActive && detachIfReset); 1408 return !stillActive; 1409 } 1410 } 1411 1412 /** 1413 * State for keeping track of timing information. 1414 */ 1415 public static final class StopwatchTimer extends Timer { 1416 final Uid mUid; 1417 final ArrayList<StopwatchTimer> mTimerPool; 1418 1419 int mNesting; 1420 1421 /** 1422 * The last time at which we updated the timer. If mNesting is > 0, 1423 * subtract this from the current battery time to find the amount of 1424 * time we have been running since we last computed an update. 1425 */ 1426 long mUpdateTime; 1427 1428 /** 1429 * The total time at which the timer was acquired, to determine if it 1430 * was actually held for an interesting duration. 1431 */ 1432 long mAcquireTime; 1433 1434 long mTimeout; 1435 1436 /** 1437 * For partial wake locks, keep track of whether we are in the list 1438 * to consume CPU cycles. 1439 */ 1440 boolean mInList; 1441 1442 StopwatchTimer(Uid uid, int type, ArrayList<StopwatchTimer> timerPool, 1443 TimeBase timeBase, Parcel in) { 1444 super(type, timeBase, in); 1445 mUid = uid; 1446 mTimerPool = timerPool; 1447 mUpdateTime = in.readLong(); 1448 } 1449 1450 StopwatchTimer(Uid uid, int type, ArrayList<StopwatchTimer> timerPool, 1451 TimeBase timeBase) { 1452 super(type, timeBase); 1453 mUid = uid; 1454 mTimerPool = timerPool; 1455 } 1456 1457 void setTimeout(long timeout) { 1458 mTimeout = timeout; 1459 } 1460 1461 public void writeToParcel(Parcel out, long elapsedRealtimeUs) { 1462 super.writeToParcel(out, elapsedRealtimeUs); 1463 out.writeLong(mUpdateTime); 1464 } 1465 1466 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) { 1467 if (mNesting > 0) { 1468 if (DEBUG && mType < 0) { 1469 Log.v(TAG, "old mUpdateTime=" + mUpdateTime); 1470 } 1471 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime); 1472 mUpdateTime = baseRealtime; 1473 if (DEBUG && mType < 0) { 1474 Log.v(TAG, "new mUpdateTime=" + mUpdateTime); 1475 } 1476 } 1477 } 1478 1479 public void logState(Printer pw, String prefix) { 1480 super.logState(pw, prefix); 1481 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime 1482 + " mAcquireTime=" + mAcquireTime); 1483 } 1484 1485 void startRunningLocked(long elapsedRealtimeMs) { 1486 if (mNesting++ == 0) { 1487 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000); 1488 mUpdateTime = batteryRealtime; 1489 if (mTimerPool != null) { 1490 // Accumulate time to all currently active timers before adding 1491 // this new one to the pool. 1492 refreshTimersLocked(batteryRealtime, mTimerPool, null); 1493 // Add this timer to the active pool 1494 mTimerPool.add(this); 1495 } 1496 // Increment the count 1497 mCount++; 1498 mAcquireTime = mTotalTime; 1499 if (DEBUG && mType < 0) { 1500 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime 1501 + " mTotalTime=" + mTotalTime + " mCount=" + mCount 1502 + " mAcquireTime=" + mAcquireTime); 1503 } 1504 } 1505 } 1506 1507 boolean isRunningLocked() { 1508 return mNesting > 0; 1509 } 1510 1511 void stopRunningLocked(long elapsedRealtimeMs) { 1512 // Ignore attempt to stop a timer that isn't running 1513 if (mNesting == 0) { 1514 return; 1515 } 1516 if (--mNesting == 0) { 1517 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000); 1518 if (mTimerPool != null) { 1519 // Accumulate time to all active counters, scaled by the total 1520 // active in the pool, before taking this one out of the pool. 1521 refreshTimersLocked(batteryRealtime, mTimerPool, null); 1522 // Remove this timer from the active pool 1523 mTimerPool.remove(this); 1524 } else { 1525 mNesting = 1; 1526 mTotalTime = computeRunTimeLocked(batteryRealtime); 1527 mNesting = 0; 1528 } 1529 1530 if (DEBUG && mType < 0) { 1531 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime 1532 + " mTotalTime=" + mTotalTime + " mCount=" + mCount 1533 + " mAcquireTime=" + mAcquireTime); 1534 } 1535 1536 if (mTotalTime == mAcquireTime) { 1537 // If there was no change in the time, then discard this 1538 // count. A somewhat cheezy strategy, but hey. 1539 mCount--; 1540 } 1541 } 1542 } 1543 1544 void stopAllRunningLocked(long elapsedRealtimeMs) { 1545 if (mNesting > 0) { 1546 mNesting = 1; 1547 stopRunningLocked(elapsedRealtimeMs); 1548 } 1549 } 1550 1551 // Update the total time for all other running Timers with the same type as this Timer 1552 // due to a change in timer count 1553 private static long refreshTimersLocked(long batteryRealtime, 1554 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) { 1555 long selfTime = 0; 1556 final int N = pool.size(); 1557 for (int i=N-1; i>= 0; i--) { 1558 final StopwatchTimer t = pool.get(i); 1559 long heldTime = batteryRealtime - t.mUpdateTime; 1560 if (heldTime > 0) { 1561 final long myTime = heldTime / N; 1562 if (t == self) { 1563 selfTime = myTime; 1564 } 1565 t.mTotalTime += myTime; 1566 } 1567 t.mUpdateTime = batteryRealtime; 1568 } 1569 return selfTime; 1570 } 1571 1572 @Override 1573 protected long computeRunTimeLocked(long curBatteryRealtime) { 1574 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) { 1575 curBatteryRealtime = mUpdateTime + mTimeout; 1576 } 1577 return mTotalTime + (mNesting > 0 1578 ? (curBatteryRealtime - mUpdateTime) 1579 / (mTimerPool != null ? mTimerPool.size() : 1) 1580 : 0); 1581 } 1582 1583 @Override 1584 protected int computeCurrentCountLocked() { 1585 return mCount; 1586 } 1587 1588 @Override 1589 boolean reset(boolean detachIfReset) { 1590 boolean canDetach = mNesting <= 0; 1591 super.reset(canDetach && detachIfReset); 1592 if (mNesting > 0) { 1593 mUpdateTime = mTimeBase.getRealtime(SystemClock.elapsedRealtime() * 1000); 1594 } 1595 mAcquireTime = mTotalTime; 1596 return canDetach; 1597 } 1598 1599 @Override 1600 void detach() { 1601 super.detach(); 1602 if (mTimerPool != null) { 1603 mTimerPool.remove(this); 1604 } 1605 } 1606 1607 @Override 1608 void readSummaryFromParcelLocked(Parcel in) { 1609 super.readSummaryFromParcelLocked(in); 1610 mNesting = 0; 1611 } 1612 1613 /** 1614 * Set the mark so that we can query later for the total time the timer has 1615 * accumulated since this point. The timer can be running or not. 1616 * 1617 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds. 1618 */ 1619 public void setMark(long elapsedRealtimeMs) { 1620 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000); 1621 if (mNesting > 0) { 1622 // We are running. 1623 if (mTimerPool != null) { 1624 refreshTimersLocked(batteryRealtime, mTimerPool, this); 1625 } else { 1626 mTotalTime += batteryRealtime - mUpdateTime; 1627 mUpdateTime = batteryRealtime; 1628 } 1629 } 1630 mTimeBeforeMark = mTotalTime; 1631 } 1632 } 1633 1634 public abstract class OverflowArrayMap<T> { 1635 private static final String OVERFLOW_NAME = "*overflow*"; 1636 1637 final ArrayMap<String, T> mMap = new ArrayMap<>(); 1638 T mCurOverflow; 1639 ArrayMap<String, MutableInt> mActiveOverflow; 1640 1641 public OverflowArrayMap() { 1642 } 1643 1644 public ArrayMap<String, T> getMap() { 1645 return mMap; 1646 } 1647 1648 public void clear() { 1649 mMap.clear(); 1650 mCurOverflow = null; 1651 mActiveOverflow = null; 1652 } 1653 1654 public void add(String name, T obj) { 1655 mMap.put(name, obj); 1656 if (OVERFLOW_NAME.equals(name)) { 1657 mCurOverflow = obj; 1658 } 1659 } 1660 1661 public void cleanup() { 1662 if (mActiveOverflow != null) { 1663 if (mActiveOverflow.size() == 0) { 1664 mActiveOverflow = null; 1665 } 1666 } 1667 if (mActiveOverflow == null) { 1668 // There is no currently active overflow, so we should no longer have 1669 // an overflow entry. 1670 if (mMap.containsKey(OVERFLOW_NAME)) { 1671 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry " 1672 + mMap.get(OVERFLOW_NAME)); 1673 mMap.remove(OVERFLOW_NAME); 1674 } 1675 mCurOverflow = null; 1676 } else { 1677 // There is currently active overflow, so we should still have an overflow entry. 1678 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) { 1679 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur=" 1680 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME)); 1681 } 1682 } 1683 } 1684 1685 public T startObject(String name) { 1686 T obj = mMap.get(name); 1687 if (obj != null) { 1688 return obj; 1689 } 1690 1691 // No object exists for the given name, but do we currently have it 1692 // running as part of the overflow? 1693 if (mActiveOverflow != null) { 1694 MutableInt over = mActiveOverflow.get(name); 1695 if (over != null) { 1696 // We are already actively counting this name in the overflow object. 1697 obj = mCurOverflow; 1698 if (obj == null) { 1699 // Shouldn't be here, but we'll try to recover. 1700 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow"); 1701 obj = mCurOverflow = instantiateObject(); 1702 mMap.put(OVERFLOW_NAME, obj); 1703 } 1704 over.value++; 1705 return obj; 1706 } 1707 } 1708 1709 // No object exists for given name nor in the overflow; we need to make 1710 // a new one. 1711 final int N = mMap.size(); 1712 if (N >= MAX_WAKELOCKS_PER_UID) { 1713 // Went over the limit on number of objects to track; this one goes 1714 // in to the overflow. 1715 obj = mCurOverflow; 1716 if (obj == null) { 1717 // Need to start overflow now... 1718 obj = mCurOverflow = instantiateObject(); 1719 mMap.put(OVERFLOW_NAME, obj); 1720 } 1721 if (mActiveOverflow == null) { 1722 mActiveOverflow = new ArrayMap<>(); 1723 } 1724 mActiveOverflow.put(name, new MutableInt(1)); 1725 return obj; 1726 } 1727 1728 // Normal case where we just need to make a new object. 1729 obj = instantiateObject(); 1730 mMap.put(name, obj); 1731 return obj; 1732 } 1733 1734 public T stopObject(String name) { 1735 T obj = mMap.get(name); 1736 if (obj != null) { 1737 return obj; 1738 } 1739 1740 // No object exists for the given name, but do we currently have it 1741 // running as part of the overflow? 1742 if (mActiveOverflow != null) { 1743 MutableInt over = mActiveOverflow.get(name); 1744 if (over != null) { 1745 // We are already actively counting this name in the overflow object. 1746 obj = mCurOverflow; 1747 if (obj != null) { 1748 over.value--; 1749 if (over.value <= 0) { 1750 mActiveOverflow.remove(name); 1751 } 1752 return obj; 1753 } 1754 } 1755 } 1756 1757 // Huh, they are stopping an active operation but we can't find one! 1758 // That's not good. 1759 Slog.wtf(TAG, "Unable to find object for " + name + " mapsize=" 1760 + mMap.size() + " activeoverflow=" + mActiveOverflow 1761 + " curoverflow=" + mCurOverflow); 1762 return null; 1763 } 1764 1765 public abstract T instantiateObject(); 1766 } 1767 1768 /* 1769 * Get the wakeup reason counter, and create a new one if one 1770 * doesn't already exist. 1771 */ 1772 public SamplingTimer getWakeupReasonTimerLocked(String name) { 1773 SamplingTimer timer = mWakeupReasonStats.get(name); 1774 if (timer == null) { 1775 timer = new SamplingTimer(mOnBatteryTimeBase, true); 1776 mWakeupReasonStats.put(name, timer); 1777 } 1778 return timer; 1779 } 1780 1781 /* 1782 * Get the KernelWakelockTimer associated with name, and create a new one if one 1783 * doesn't already exist. 1784 */ 1785 public SamplingTimer getKernelWakelockTimerLocked(String name) { 1786 SamplingTimer kwlt = mKernelWakelockStats.get(name); 1787 if (kwlt == null) { 1788 kwlt = new SamplingTimer(mOnBatteryScreenOffTimeBase, true /* track reported values */); 1789 mKernelWakelockStats.put(name, kwlt); 1790 } 1791 return kwlt; 1792 } 1793 1794 private int writeHistoryTag(HistoryTag tag) { 1795 Integer idxObj = mHistoryTagPool.get(tag); 1796 int idx; 1797 if (idxObj != null) { 1798 idx = idxObj; 1799 } else { 1800 idx = mNextHistoryTagIdx; 1801 HistoryTag key = new HistoryTag(); 1802 key.setTo(tag); 1803 tag.poolIdx = idx; 1804 mHistoryTagPool.put(key, idx); 1805 mNextHistoryTagIdx++; 1806 mNumHistoryTagChars += key.string.length() + 1; 1807 } 1808 return idx; 1809 } 1810 1811 private void readHistoryTag(int index, HistoryTag tag) { 1812 tag.string = mReadHistoryStrings[index]; 1813 tag.uid = mReadHistoryUids[index]; 1814 tag.poolIdx = index; 1815 } 1816 1817 // Part of initial delta int that specifies the time delta. 1818 static final int DELTA_TIME_MASK = 0x7ffff; 1819 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long 1820 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int 1821 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update. 1822 // Flag in delta int: a new battery level int follows. 1823 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000; 1824 // Flag in delta int: a new full state and battery status int follows. 1825 static final int DELTA_STATE_FLAG = 0x00100000; 1826 // Flag in delta int: a new full state2 int follows. 1827 static final int DELTA_STATE2_FLAG = 0x00200000; 1828 // Flag in delta int: contains a wakelock or wakeReason tag. 1829 static final int DELTA_WAKELOCK_FLAG = 0x00400000; 1830 // Flag in delta int: contains an event description. 1831 static final int DELTA_EVENT_FLAG = 0x00800000; 1832 // These upper bits are the frequently changing state bits. 1833 static final int DELTA_STATE_MASK = 0xff000000; 1834 1835 // These are the pieces of battery state that are packed in to the upper bits of 1836 // the state int that have been packed in to the first delta int. They must fit 1837 // in DELTA_STATE_MASK. 1838 static final int STATE_BATTERY_STATUS_MASK = 0x00000007; 1839 static final int STATE_BATTERY_STATUS_SHIFT = 29; 1840 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007; 1841 static final int STATE_BATTERY_HEALTH_SHIFT = 26; 1842 static final int STATE_BATTERY_PLUG_MASK = 0x00000003; 1843 static final int STATE_BATTERY_PLUG_SHIFT = 24; 1844 1845 // We use the low bit of the battery state int to indicate that we have full details 1846 // from a battery level change. 1847 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001; 1848 1849 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) { 1850 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) { 1851 dest.writeInt(DELTA_TIME_ABS); 1852 cur.writeToParcel(dest, 0); 1853 return; 1854 } 1855 1856 final long deltaTime = cur.time - last.time; 1857 final int lastBatteryLevelInt = buildBatteryLevelInt(last); 1858 final int lastStateInt = buildStateInt(last); 1859 1860 int deltaTimeToken; 1861 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) { 1862 deltaTimeToken = DELTA_TIME_LONG; 1863 } else if (deltaTime >= DELTA_TIME_ABS) { 1864 deltaTimeToken = DELTA_TIME_INT; 1865 } else { 1866 deltaTimeToken = (int)deltaTime; 1867 } 1868 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK); 1869 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel 1870 ? BATTERY_DELTA_LEVEL_FLAG : 0; 1871 final boolean computeStepDetails = includeStepDetails != 0 1872 || mLastHistoryStepDetails == null; 1873 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails; 1874 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt; 1875 if (batteryLevelIntChanged) { 1876 firstToken |= DELTA_BATTERY_LEVEL_FLAG; 1877 } 1878 final int stateInt = buildStateInt(cur); 1879 final boolean stateIntChanged = stateInt != lastStateInt; 1880 if (stateIntChanged) { 1881 firstToken |= DELTA_STATE_FLAG; 1882 } 1883 final boolean state2IntChanged = cur.states2 != last.states2; 1884 if (state2IntChanged) { 1885 firstToken |= DELTA_STATE2_FLAG; 1886 } 1887 if (cur.wakelockTag != null || cur.wakeReasonTag != null) { 1888 firstToken |= DELTA_WAKELOCK_FLAG; 1889 } 1890 if (cur.eventCode != HistoryItem.EVENT_NONE) { 1891 firstToken |= DELTA_EVENT_FLAG; 1892 } 1893 dest.writeInt(firstToken); 1894 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken) 1895 + " deltaTime=" + deltaTime); 1896 1897 if (deltaTimeToken >= DELTA_TIME_INT) { 1898 if (deltaTimeToken == DELTA_TIME_INT) { 1899 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime); 1900 dest.writeInt((int)deltaTime); 1901 } else { 1902 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime); 1903 dest.writeLong(deltaTime); 1904 } 1905 } 1906 if (batteryLevelIntChanged) { 1907 dest.writeInt(batteryLevelInt); 1908 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x" 1909 + Integer.toHexString(batteryLevelInt) 1910 + " batteryLevel=" + cur.batteryLevel 1911 + " batteryTemp=" + cur.batteryTemperature 1912 + " batteryVolt=" + (int)cur.batteryVoltage); 1913 } 1914 if (stateIntChanged) { 1915 dest.writeInt(stateInt); 1916 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x" 1917 + Integer.toHexString(stateInt) 1918 + " batteryStatus=" + cur.batteryStatus 1919 + " batteryHealth=" + cur.batteryHealth 1920 + " batteryPlugType=" + cur.batteryPlugType 1921 + " states=0x" + Integer.toHexString(cur.states)); 1922 } 1923 if (state2IntChanged) { 1924 dest.writeInt(cur.states2); 1925 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x" 1926 + Integer.toHexString(cur.states2)); 1927 } 1928 if (cur.wakelockTag != null || cur.wakeReasonTag != null) { 1929 int wakeLockIndex; 1930 int wakeReasonIndex; 1931 if (cur.wakelockTag != null) { 1932 wakeLockIndex = writeHistoryTag(cur.wakelockTag); 1933 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx 1934 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string); 1935 } else { 1936 wakeLockIndex = 0xffff; 1937 } 1938 if (cur.wakeReasonTag != null) { 1939 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag); 1940 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx 1941 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string); 1942 } else { 1943 wakeReasonIndex = 0xffff; 1944 } 1945 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex); 1946 } 1947 if (cur.eventCode != HistoryItem.EVENT_NONE) { 1948 int index = writeHistoryTag(cur.eventTag); 1949 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16); 1950 dest.writeInt(codeAndIndex); 1951 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#" 1952 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":" 1953 + cur.eventTag.string); 1954 } 1955 if (computeStepDetails) { 1956 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails); 1957 if (includeStepDetails != 0) { 1958 mCurHistoryStepDetails.writeToParcel(dest); 1959 } 1960 cur.stepDetails = mCurHistoryStepDetails; 1961 mLastHistoryStepDetails = mCurHistoryStepDetails; 1962 } else { 1963 cur.stepDetails = null; 1964 } 1965 if (mLastHistoryStepLevel < cur.batteryLevel) { 1966 mLastHistoryStepDetails = null; 1967 } 1968 mLastHistoryStepLevel = cur.batteryLevel; 1969 } 1970 1971 private int buildBatteryLevelInt(HistoryItem h) { 1972 return ((((int)h.batteryLevel)<<25)&0xfe000000) 1973 | ((((int)h.batteryTemperature)<<14)&0x01ff8000) 1974 | ((((int)h.batteryVoltage)<<1)&0x00007fff); 1975 } 1976 1977 private int buildStateInt(HistoryItem h) { 1978 int plugType = 0; 1979 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) { 1980 plugType = 1; 1981 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) { 1982 plugType = 2; 1983 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) { 1984 plugType = 3; 1985 } 1986 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT) 1987 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT) 1988 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT) 1989 | (h.states&(~DELTA_STATE_MASK)); 1990 } 1991 1992 private void computeHistoryStepDetails(final HistoryStepDetails out, 1993 final HistoryStepDetails last) { 1994 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out; 1995 1996 // Perform a CPU update right after we do this collection, so we have started 1997 // collecting good data for the next step. 1998 requestImmediateCpuUpdate(); 1999 2000 if (last == null) { 2001 // We are not generating a delta, so all we need to do is reset the stats 2002 // we will later be doing a delta from. 2003 final int NU = mUidStats.size(); 2004 for (int i=0; i<NU; i++) { 2005 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i); 2006 uid.mLastStepUserTime = uid.mCurStepUserTime; 2007 uid.mLastStepSystemTime = uid.mCurStepSystemTime; 2008 } 2009 mLastStepCpuUserTime = mCurStepCpuUserTime; 2010 mLastStepCpuSystemTime = mCurStepCpuSystemTime; 2011 mLastStepStatUserTime = mCurStepStatUserTime; 2012 mLastStepStatSystemTime = mCurStepStatSystemTime; 2013 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime; 2014 mLastStepStatIrqTime = mCurStepStatIrqTime; 2015 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime; 2016 mLastStepStatIdleTime = mCurStepStatIdleTime; 2017 tmp.clear(); 2018 return; 2019 } 2020 if (DEBUG) { 2021 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys=" 2022 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime 2023 + " irq=" + mLastStepStatIrqTime + " sirq=" 2024 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime); 2025 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys=" 2026 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime 2027 + " irq=" + mCurStepStatIrqTime + " sirq=" 2028 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime); 2029 } 2030 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime); 2031 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime); 2032 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime); 2033 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime); 2034 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime); 2035 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime); 2036 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime); 2037 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime); 2038 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1; 2039 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0; 2040 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0; 2041 final int NU = mUidStats.size(); 2042 for (int i=0; i<NU; i++) { 2043 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i); 2044 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime); 2045 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime); 2046 final int totalTime = totalUTime + totalSTime; 2047 uid.mLastStepUserTime = uid.mCurStepUserTime; 2048 uid.mLastStepSystemTime = uid.mCurStepSystemTime; 2049 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) { 2050 continue; 2051 } 2052 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) { 2053 out.appCpuUid3 = uid.mUid; 2054 out.appCpuUTime3 = totalUTime; 2055 out.appCpuSTime3 = totalSTime; 2056 } else { 2057 out.appCpuUid3 = out.appCpuUid2; 2058 out.appCpuUTime3 = out.appCpuUTime2; 2059 out.appCpuSTime3 = out.appCpuSTime2; 2060 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) { 2061 out.appCpuUid2 = uid.mUid; 2062 out.appCpuUTime2 = totalUTime; 2063 out.appCpuSTime2 = totalSTime; 2064 } else { 2065 out.appCpuUid2 = out.appCpuUid1; 2066 out.appCpuUTime2 = out.appCpuUTime1; 2067 out.appCpuSTime2 = out.appCpuSTime1; 2068 out.appCpuUid1 = uid.mUid; 2069 out.appCpuUTime1 = totalUTime; 2070 out.appCpuSTime1 = totalSTime; 2071 } 2072 } 2073 } 2074 mLastStepCpuUserTime = mCurStepCpuUserTime; 2075 mLastStepCpuSystemTime = mCurStepCpuSystemTime; 2076 mLastStepStatUserTime = mCurStepStatUserTime; 2077 mLastStepStatSystemTime = mCurStepStatSystemTime; 2078 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime; 2079 mLastStepStatIrqTime = mCurStepStatIrqTime; 2080 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime; 2081 mLastStepStatIdleTime = mCurStepStatIdleTime; 2082 } 2083 2084 public void readHistoryDelta(Parcel src, HistoryItem cur) { 2085 int firstToken = src.readInt(); 2086 int deltaTimeToken = firstToken&DELTA_TIME_MASK; 2087 cur.cmd = HistoryItem.CMD_UPDATE; 2088 cur.numReadInts = 1; 2089 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken) 2090 + " deltaTimeToken=" + deltaTimeToken); 2091 2092 if (deltaTimeToken < DELTA_TIME_ABS) { 2093 cur.time += deltaTimeToken; 2094 } else if (deltaTimeToken == DELTA_TIME_ABS) { 2095 cur.time = src.readLong(); 2096 cur.numReadInts += 2; 2097 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time); 2098 cur.readFromParcel(src); 2099 return; 2100 } else if (deltaTimeToken == DELTA_TIME_INT) { 2101 int delta = src.readInt(); 2102 cur.time += delta; 2103 cur.numReadInts += 1; 2104 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time); 2105 } else { 2106 long delta = src.readLong(); 2107 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time); 2108 cur.time += delta; 2109 cur.numReadInts += 2; 2110 } 2111 2112 final int batteryLevelInt; 2113 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) { 2114 batteryLevelInt = src.readInt(); 2115 cur.batteryLevel = (byte)((batteryLevelInt>>25)&0x7f); 2116 cur.batteryTemperature = (short)((batteryLevelInt<<7)>>21); 2117 cur.batteryVoltage = (char)(batteryLevelInt&0x3fff); 2118 cur.numReadInts += 1; 2119 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x" 2120 + Integer.toHexString(batteryLevelInt) 2121 + " batteryLevel=" + cur.batteryLevel 2122 + " batteryTemp=" + cur.batteryTemperature 2123 + " batteryVolt=" + (int)cur.batteryVoltage); 2124 } else { 2125 batteryLevelInt = 0; 2126 } 2127 2128 if ((firstToken&DELTA_STATE_FLAG) != 0) { 2129 int stateInt = src.readInt(); 2130 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~DELTA_STATE_MASK)); 2131 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT) 2132 & STATE_BATTERY_STATUS_MASK); 2133 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT) 2134 & STATE_BATTERY_HEALTH_MASK); 2135 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT) 2136 & STATE_BATTERY_PLUG_MASK); 2137 switch (cur.batteryPlugType) { 2138 case 1: 2139 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC; 2140 break; 2141 case 2: 2142 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB; 2143 break; 2144 case 3: 2145 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS; 2146 break; 2147 } 2148 cur.numReadInts += 1; 2149 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x" 2150 + Integer.toHexString(stateInt) 2151 + " batteryStatus=" + cur.batteryStatus 2152 + " batteryHealth=" + cur.batteryHealth 2153 + " batteryPlugType=" + cur.batteryPlugType 2154 + " states=0x" + Integer.toHexString(cur.states)); 2155 } else { 2156 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~DELTA_STATE_MASK)); 2157 } 2158 2159 if ((firstToken&DELTA_STATE2_FLAG) != 0) { 2160 cur.states2 = src.readInt(); 2161 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x" 2162 + Integer.toHexString(cur.states2)); 2163 } 2164 2165 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) { 2166 int indexes = src.readInt(); 2167 int wakeLockIndex = indexes&0xffff; 2168 int wakeReasonIndex = (indexes>>16)&0xffff; 2169 if (wakeLockIndex != 0xffff) { 2170 cur.wakelockTag = cur.localWakelockTag; 2171 readHistoryTag(wakeLockIndex, cur.wakelockTag); 2172 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx 2173 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string); 2174 } else { 2175 cur.wakelockTag = null; 2176 } 2177 if (wakeReasonIndex != 0xffff) { 2178 cur.wakeReasonTag = cur.localWakeReasonTag; 2179 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag); 2180 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx 2181 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string); 2182 } else { 2183 cur.wakeReasonTag = null; 2184 } 2185 cur.numReadInts += 1; 2186 } else { 2187 cur.wakelockTag = null; 2188 cur.wakeReasonTag = null; 2189 } 2190 2191 if ((firstToken&DELTA_EVENT_FLAG) != 0) { 2192 cur.eventTag = cur.localEventTag; 2193 final int codeAndIndex = src.readInt(); 2194 cur.eventCode = (codeAndIndex&0xffff); 2195 final int index = ((codeAndIndex>>16)&0xffff); 2196 readHistoryTag(index, cur.eventTag); 2197 cur.numReadInts += 1; 2198 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#" 2199 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":" 2200 + cur.eventTag.string); 2201 } else { 2202 cur.eventCode = HistoryItem.EVENT_NONE; 2203 } 2204 2205 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) { 2206 cur.stepDetails = mReadHistoryStepDetails; 2207 cur.stepDetails.readFromParcel(src); 2208 } else { 2209 cur.stepDetails = null; 2210 } 2211 } 2212 2213 @Override 2214 public void commitCurrentHistoryBatchLocked() { 2215 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL; 2216 } 2217 2218 void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) { 2219 if (!mHaveBatteryLevel || !mRecordingHistory) { 2220 return; 2221 } 2222 2223 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time; 2224 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates); 2225 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2); 2226 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states; 2227 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2; 2228 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff=" 2229 + Integer.toHexString(diffStates) + " lastDiff=" 2230 + Integer.toHexString(lastDiffStates) + " diff2=" 2231 + Integer.toHexString(diffStates2) + " lastDiff2=" 2232 + Integer.toHexString(lastDiffStates2)); 2233 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE 2234 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0 2235 && (diffStates2&lastDiffStates2) == 0 2236 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null) 2237 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null) 2238 && mHistoryLastWritten.stepDetails == null 2239 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE 2240 || cur.eventCode == HistoryItem.EVENT_NONE) 2241 && mHistoryLastWritten.batteryLevel == cur.batteryLevel 2242 && mHistoryLastWritten.batteryStatus == cur.batteryStatus 2243 && mHistoryLastWritten.batteryHealth == cur.batteryHealth 2244 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType 2245 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature 2246 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) { 2247 // We can merge this new change in with the last one. Merging is 2248 // allowed as long as only the states have changed, and within those states 2249 // as long as no bit has changed both between now and the last entry, as 2250 // well as the last entry and the one before it (so we capture any toggles). 2251 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos); 2252 mHistoryBuffer.setDataSize(mHistoryBufferLastPos); 2253 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos); 2254 mHistoryBufferLastPos = -1; 2255 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime; 2256 // If the last written history had a wakelock tag, we need to retain it. 2257 // Note that the condition above made sure that we aren't in a case where 2258 // both it and the current history item have a wakelock tag. 2259 if (mHistoryLastWritten.wakelockTag != null) { 2260 cur.wakelockTag = cur.localWakelockTag; 2261 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag); 2262 } 2263 // If the last written history had a wake reason tag, we need to retain it. 2264 // Note that the condition above made sure that we aren't in a case where 2265 // both it and the current history item have a wakelock tag. 2266 if (mHistoryLastWritten.wakeReasonTag != null) { 2267 cur.wakeReasonTag = cur.localWakeReasonTag; 2268 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag); 2269 } 2270 // If the last written history had an event, we need to retain it. 2271 // Note that the condition above made sure that we aren't in a case where 2272 // both it and the current history item have an event. 2273 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) { 2274 cur.eventCode = mHistoryLastWritten.eventCode; 2275 cur.eventTag = cur.localEventTag; 2276 cur.eventTag.setTo(mHistoryLastWritten.eventTag); 2277 } 2278 mHistoryLastWritten.setTo(mHistoryLastLastWritten); 2279 } 2280 2281 final int dataSize = mHistoryBuffer.dataSize(); 2282 if (dataSize >= MAX_HISTORY_BUFFER) { 2283 if (!mHistoryOverflow) { 2284 mHistoryOverflow = true; 2285 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur); 2286 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur); 2287 return; 2288 } 2289 2290 // After overflow, we allow various bit-wise states to settle to 0. 2291 boolean writeAnyway = false; 2292 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES 2293 & mActiveHistoryStates; 2294 if (mHistoryLastWritten.states != curStates) { 2295 // mActiveHistoryStates keeps track of which bits in .states are now being 2296 // forced to 0. 2297 int old = mActiveHistoryStates; 2298 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES; 2299 writeAnyway |= old != mActiveHistoryStates; 2300 } 2301 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2 2302 & mActiveHistoryStates2; 2303 if (mHistoryLastWritten.states2 != curStates2) { 2304 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being 2305 // forced to 0. 2306 int old = mActiveHistoryStates2; 2307 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2; 2308 writeAnyway |= old != mActiveHistoryStates2; 2309 } 2310 2311 // Once we've reached the maximum number of items, we only 2312 // record changes to the battery level and the most interesting states. 2313 // Once we've reached the maximum maximum number of items, we only 2314 // record changes to the battery level. 2315 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel && 2316 (dataSize >= MAX_MAX_HISTORY_BUFFER 2317 || ((mHistoryLastWritten.states^cur.states) 2318 & HistoryItem.MOST_INTERESTING_STATES) == 0 2319 || ((mHistoryLastWritten.states2^cur.states2) 2320 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) { 2321 return; 2322 } 2323 2324 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur); 2325 return; 2326 } 2327 2328 if (dataSize == 0) { 2329 // The history is currently empty; we need it to start with a time stamp. 2330 cur.currentTime = System.currentTimeMillis(); 2331 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_RESET, cur); 2332 } 2333 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur); 2334 } 2335 2336 private void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, 2337 HistoryItem cur) { 2338 if (mIteratingHistory) { 2339 throw new IllegalStateException("Can't do this while iterating history!"); 2340 } 2341 mHistoryBufferLastPos = mHistoryBuffer.dataPosition(); 2342 mHistoryLastLastWritten.setTo(mHistoryLastWritten); 2343 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur); 2344 mHistoryLastWritten.states &= mActiveHistoryStates; 2345 mHistoryLastWritten.states2 &= mActiveHistoryStates2; 2346 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten); 2347 mLastHistoryElapsedRealtime = elapsedRealtimeMs; 2348 cur.wakelockTag = null; 2349 cur.wakeReasonTag = null; 2350 cur.eventCode = HistoryItem.EVENT_NONE; 2351 cur.eventTag = null; 2352 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos 2353 + " now " + mHistoryBuffer.dataPosition() 2354 + " size is now " + mHistoryBuffer.dataSize()); 2355 } 2356 2357 int mChangedStates = 0; 2358 int mChangedStates2 = 0; 2359 2360 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) { 2361 if (mTrackRunningHistoryElapsedRealtime != 0) { 2362 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime; 2363 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime; 2364 if (diffUptime < (diffElapsed-20)) { 2365 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime); 2366 mHistoryAddTmp.setTo(mHistoryLastWritten); 2367 mHistoryAddTmp.wakelockTag = null; 2368 mHistoryAddTmp.wakeReasonTag = null; 2369 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE; 2370 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG; 2371 addHistoryRecordInnerLocked(wakeElapsedTime, uptimeMs, mHistoryAddTmp); 2372 } 2373 } 2374 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG; 2375 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs; 2376 mTrackRunningHistoryUptime = uptimeMs; 2377 addHistoryRecordInnerLocked(elapsedRealtimeMs, uptimeMs, mHistoryCur); 2378 } 2379 2380 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) { 2381 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, cur); 2382 2383 if (!USE_OLD_HISTORY) { 2384 return; 2385 } 2386 2387 if (!mHaveBatteryLevel || !mRecordingHistory) { 2388 return; 2389 } 2390 2391 // If the current time is basically the same as the last time, 2392 // and no states have since the last recorded entry changed and 2393 // are now resetting back to their original value, then just collapse 2394 // into one record. 2395 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE 2396 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000) 2397 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0 2398 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) { 2399 // If the current is the same as the one before, then we no 2400 // longer need the entry. 2401 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE 2402 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500) 2403 && mHistoryLastEnd.sameNonEvent(cur)) { 2404 mHistoryLastEnd.next = null; 2405 mHistoryEnd.next = mHistoryCache; 2406 mHistoryCache = mHistoryEnd; 2407 mHistoryEnd = mHistoryLastEnd; 2408 mHistoryLastEnd = null; 2409 } else { 2410 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates); 2411 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2); 2412 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur); 2413 } 2414 return; 2415 } 2416 2417 mChangedStates = 0; 2418 mChangedStates2 = 0; 2419 2420 if (mNumHistoryItems == MAX_HISTORY_ITEMS 2421 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) { 2422 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW); 2423 } 2424 2425 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) { 2426 // Once we've reached the maximum number of items, we only 2427 // record changes to the battery level and the most interesting states. 2428 // Once we've reached the maximum maximum number of items, we only 2429 // record changes to the battery level. 2430 if (mHistoryEnd != null && mHistoryEnd.batteryLevel 2431 == cur.batteryLevel && 2432 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS 2433 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates)) 2434 & HistoryItem.MOST_INTERESTING_STATES) == 0)) { 2435 return; 2436 } 2437 } 2438 2439 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE); 2440 } 2441 2442 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code, 2443 String name, int uid) { 2444 mHistoryCur.eventCode = code; 2445 mHistoryCur.eventTag = mHistoryCur.localEventTag; 2446 mHistoryCur.eventTag.string = name; 2447 mHistoryCur.eventTag.uid = uid; 2448 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs); 2449 } 2450 2451 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) { 2452 HistoryItem rec = mHistoryCache; 2453 if (rec != null) { 2454 mHistoryCache = rec.next; 2455 } else { 2456 rec = new HistoryItem(); 2457 } 2458 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur); 2459 2460 addHistoryRecordLocked(rec); 2461 } 2462 2463 void addHistoryRecordLocked(HistoryItem rec) { 2464 mNumHistoryItems++; 2465 rec.next = null; 2466 mHistoryLastEnd = mHistoryEnd; 2467 if (mHistoryEnd != null) { 2468 mHistoryEnd.next = rec; 2469 mHistoryEnd = rec; 2470 } else { 2471 mHistory = mHistoryEnd = rec; 2472 } 2473 } 2474 2475 void clearHistoryLocked() { 2476 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!"); 2477 if (USE_OLD_HISTORY) { 2478 if (mHistory != null) { 2479 mHistoryEnd.next = mHistoryCache; 2480 mHistoryCache = mHistory; 2481 mHistory = mHistoryLastEnd = mHistoryEnd = null; 2482 } 2483 mNumHistoryItems = 0; 2484 } 2485 2486 mHistoryBaseTime = 0; 2487 mLastHistoryElapsedRealtime = 0; 2488 mTrackRunningHistoryElapsedRealtime = 0; 2489 mTrackRunningHistoryUptime = 0; 2490 2491 mHistoryBuffer.setDataSize(0); 2492 mHistoryBuffer.setDataPosition(0); 2493 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2); 2494 mHistoryLastLastWritten.clear(); 2495 mHistoryLastWritten.clear(); 2496 mHistoryTagPool.clear(); 2497 mNextHistoryTagIdx = 0; 2498 mNumHistoryTagChars = 0; 2499 mHistoryBufferLastPos = -1; 2500 mHistoryOverflow = false; 2501 mActiveHistoryStates = 0xffffffff; 2502 mActiveHistoryStates2 = 0xffffffff; 2503 } 2504 2505 public void updateTimeBasesLocked(boolean unplugged, boolean screenOff, long uptime, 2506 long realtime) { 2507 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime); 2508 2509 boolean unpluggedScreenOff = unplugged && screenOff; 2510 if (unpluggedScreenOff != mOnBatteryScreenOffTimeBase.isRunning()) { 2511 updateKernelWakelocksLocked(); 2512 if (DEBUG_ENERGY_CPU) { 2513 Slog.d(TAG, "Updating cpu time because screen is now " + 2514 (unpluggedScreenOff ? "off" : "on")); 2515 } 2516 updateCpuTimeLocked(); 2517 mOnBatteryScreenOffTimeBase.setRunning(unpluggedScreenOff, uptime, realtime); 2518 } 2519 } 2520 2521 public void addIsolatedUidLocked(int isolatedUid, int appUid) { 2522 mIsolatedUids.put(isolatedUid, appUid); 2523 } 2524 2525 public void removeIsolatedUidLocked(int isolatedUid, int appUid) { 2526 int curUid = mIsolatedUids.get(isolatedUid, -1); 2527 if (curUid == appUid) { 2528 mIsolatedUids.delete(isolatedUid); 2529 } 2530 } 2531 2532 public int mapUid(int uid) { 2533 int isolated = mIsolatedUids.get(uid, -1); 2534 return isolated > 0 ? isolated : uid; 2535 } 2536 2537 public void noteEventLocked(int code, String name, int uid) { 2538 uid = mapUid(uid); 2539 if (!mActiveEvents.updateState(code, name, uid, 0)) { 2540 return; 2541 } 2542 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2543 final long uptime = SystemClock.uptimeMillis(); 2544 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid); 2545 } 2546 2547 public void noteCurrentTimeChangedLocked() { 2548 final long currentTime = System.currentTimeMillis(); 2549 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2550 final long uptime = SystemClock.uptimeMillis(); 2551 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime); 2552 if (isStartClockTimeValid()) { 2553 mStartClockTime = currentTime; 2554 } 2555 } 2556 2557 public void noteProcessStartLocked(String name, int uid) { 2558 uid = mapUid(uid); 2559 if (isOnBattery()) { 2560 Uid u = getUidStatsLocked(uid); 2561 u.getProcessStatsLocked(name).incStartsLocked(); 2562 } 2563 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) { 2564 return; 2565 } 2566 if (!mRecordAllHistory) { 2567 return; 2568 } 2569 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2570 final long uptime = SystemClock.uptimeMillis(); 2571 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid); 2572 } 2573 2574 public void noteProcessCrashLocked(String name, int uid) { 2575 uid = mapUid(uid); 2576 if (isOnBattery()) { 2577 Uid u = getUidStatsLocked(uid); 2578 u.getProcessStatsLocked(name).incNumCrashesLocked(); 2579 } 2580 } 2581 2582 public void noteProcessAnrLocked(String name, int uid) { 2583 uid = mapUid(uid); 2584 if (isOnBattery()) { 2585 Uid u = getUidStatsLocked(uid); 2586 u.getProcessStatsLocked(name).incNumAnrsLocked(); 2587 } 2588 } 2589 2590 public void noteProcessStateLocked(String name, int uid, int state) { 2591 uid = mapUid(uid); 2592 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2593 getUidStatsLocked(uid).updateProcessStateLocked(name, state, elapsedRealtime); 2594 } 2595 2596 public void noteProcessFinishLocked(String name, int uid) { 2597 uid = mapUid(uid); 2598 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) { 2599 return; 2600 } 2601 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2602 final long uptime = SystemClock.uptimeMillis(); 2603 getUidStatsLocked(uid).updateProcessStateLocked(name, Uid.PROCESS_STATE_NONE, 2604 elapsedRealtime); 2605 if (!mRecordAllHistory) { 2606 return; 2607 } 2608 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid); 2609 } 2610 2611 public void noteSyncStartLocked(String name, int uid) { 2612 uid = mapUid(uid); 2613 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2614 final long uptime = SystemClock.uptimeMillis(); 2615 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime); 2616 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) { 2617 return; 2618 } 2619 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid); 2620 } 2621 2622 public void noteSyncFinishLocked(String name, int uid) { 2623 uid = mapUid(uid); 2624 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2625 final long uptime = SystemClock.uptimeMillis(); 2626 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime); 2627 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) { 2628 return; 2629 } 2630 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid); 2631 } 2632 2633 public void noteJobStartLocked(String name, int uid) { 2634 uid = mapUid(uid); 2635 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2636 final long uptime = SystemClock.uptimeMillis(); 2637 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime); 2638 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) { 2639 return; 2640 } 2641 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid); 2642 } 2643 2644 public void noteJobFinishLocked(String name, int uid) { 2645 uid = mapUid(uid); 2646 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2647 final long uptime = SystemClock.uptimeMillis(); 2648 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime); 2649 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) { 2650 return; 2651 } 2652 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid); 2653 } 2654 2655 public void noteAlarmStartLocked(String name, int uid) { 2656 if (!mRecordAllHistory) { 2657 return; 2658 } 2659 uid = mapUid(uid); 2660 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2661 final long uptime = SystemClock.uptimeMillis(); 2662 if (!mActiveEvents.updateState(HistoryItem.EVENT_ALARM_START, name, uid, 0)) { 2663 return; 2664 } 2665 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ALARM_START, name, uid); 2666 } 2667 2668 public void noteAlarmFinishLocked(String name, int uid) { 2669 if (!mRecordAllHistory) { 2670 return; 2671 } 2672 uid = mapUid(uid); 2673 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2674 final long uptime = SystemClock.uptimeMillis(); 2675 if (!mActiveEvents.updateState(HistoryItem.EVENT_ALARM_FINISH, name, uid, 0)) { 2676 return; 2677 } 2678 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ALARM_FINISH, name, uid); 2679 } 2680 2681 private void requestWakelockCpuUpdate() { 2682 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) { 2683 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS); 2684 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS); 2685 } 2686 } 2687 2688 private void requestImmediateCpuUpdate() { 2689 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS); 2690 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS); 2691 } 2692 2693 public void setRecordAllHistoryLocked(boolean enabled) { 2694 mRecordAllHistory = enabled; 2695 if (!enabled) { 2696 // Clear out any existing state. 2697 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK); 2698 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM); 2699 // Record the currently running processes as stopping, now that we are no 2700 // longer tracking them. 2701 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent( 2702 HistoryItem.EVENT_PROC); 2703 if (active != null) { 2704 long mSecRealtime = SystemClock.elapsedRealtime(); 2705 final long mSecUptime = SystemClock.uptimeMillis(); 2706 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) { 2707 SparseIntArray uids = ent.getValue(); 2708 for (int j=0; j<uids.size(); j++) { 2709 addHistoryEventLocked(mSecRealtime, mSecUptime, 2710 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j)); 2711 } 2712 } 2713 } 2714 } else { 2715 // Record the currently running processes as starting, now that we are tracking them. 2716 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent( 2717 HistoryItem.EVENT_PROC); 2718 if (active != null) { 2719 long mSecRealtime = SystemClock.elapsedRealtime(); 2720 final long mSecUptime = SystemClock.uptimeMillis(); 2721 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) { 2722 SparseIntArray uids = ent.getValue(); 2723 for (int j=0; j<uids.size(); j++) { 2724 addHistoryEventLocked(mSecRealtime, mSecUptime, 2725 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j)); 2726 } 2727 } 2728 } 2729 } 2730 } 2731 2732 public void setNoAutoReset(boolean enabled) { 2733 mNoAutoReset = enabled; 2734 } 2735 2736 private String mInitialAcquireWakeName; 2737 private int mInitialAcquireWakeUid = -1; 2738 2739 public void noteStartWakeLocked(int uid, int pid, String name, String historyName, int type, 2740 boolean unimportantForLogging, long elapsedRealtime, long uptime) { 2741 uid = mapUid(uid); 2742 if (type == WAKE_TYPE_PARTIAL) { 2743 // Only care about partial wake locks, since full wake locks 2744 // will be canceled when the user puts the screen to sleep. 2745 aggregateLastWakeupUptimeLocked(uptime); 2746 if (historyName == null) { 2747 historyName = name; 2748 } 2749 if (mRecordAllHistory) { 2750 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName, 2751 uid, 0)) { 2752 addHistoryEventLocked(elapsedRealtime, uptime, 2753 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid); 2754 } 2755 } 2756 if (mWakeLockNesting == 0) { 2757 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG; 2758 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: " 2759 + Integer.toHexString(mHistoryCur.states)); 2760 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag; 2761 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName; 2762 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid; 2763 mWakeLockImportant = !unimportantForLogging; 2764 addHistoryRecordLocked(elapsedRealtime, uptime); 2765 } else if (!mWakeLockImportant && !unimportantForLogging 2766 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) { 2767 if (mHistoryLastWritten.wakelockTag != null) { 2768 // We'll try to update the last tag. 2769 mHistoryLastWritten.wakelockTag = null; 2770 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag; 2771 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName; 2772 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid; 2773 addHistoryRecordLocked(elapsedRealtime, uptime); 2774 } 2775 mWakeLockImportant = true; 2776 } 2777 mWakeLockNesting++; 2778 } 2779 if (uid >= 0) { 2780 if (mOnBatteryScreenOffTimeBase.isRunning()) { 2781 // We only update the cpu time when a wake lock is acquired if the screen is off. 2782 // If the screen is on, we don't distribute the power amongst partial wakelocks. 2783 if (DEBUG_ENERGY_CPU) { 2784 Slog.d(TAG, "Updating cpu time because of +wake_lock"); 2785 } 2786 requestWakelockCpuUpdate(); 2787 } 2788 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime); 2789 } 2790 } 2791 2792 public void noteStopWakeLocked(int uid, int pid, String name, String historyName, int type, 2793 long elapsedRealtime, long uptime) { 2794 uid = mapUid(uid); 2795 if (type == WAKE_TYPE_PARTIAL) { 2796 mWakeLockNesting--; 2797 if (mRecordAllHistory) { 2798 if (historyName == null) { 2799 historyName = name; 2800 } 2801 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, 2802 uid, 0)) { 2803 addHistoryEventLocked(elapsedRealtime, uptime, 2804 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid); 2805 } 2806 } 2807 if (mWakeLockNesting == 0) { 2808 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG; 2809 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: " 2810 + Integer.toHexString(mHistoryCur.states)); 2811 mInitialAcquireWakeName = null; 2812 mInitialAcquireWakeUid = -1; 2813 addHistoryRecordLocked(elapsedRealtime, uptime); 2814 } 2815 } 2816 if (uid >= 0) { 2817 if (mOnBatteryScreenOffTimeBase.isRunning()) { 2818 if (DEBUG_ENERGY_CPU) { 2819 Slog.d(TAG, "Updating cpu time because of -wake_lock"); 2820 } 2821 requestWakelockCpuUpdate(); 2822 } 2823 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime); 2824 } 2825 } 2826 2827 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name, 2828 String historyName, int type, boolean unimportantForLogging) { 2829 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2830 final long uptime = SystemClock.uptimeMillis(); 2831 final int N = ws.size(); 2832 for (int i=0; i<N; i++) { 2833 noteStartWakeLocked(ws.get(i), pid, name, historyName, type, unimportantForLogging, 2834 elapsedRealtime, uptime); 2835 } 2836 } 2837 2838 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name, 2839 String historyName, int type, WorkSource newWs, int newPid, String newName, 2840 String newHistoryName, int newType, boolean newUnimportantForLogging) { 2841 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2842 final long uptime = SystemClock.uptimeMillis(); 2843 // For correct semantics, we start the need worksources first, so that we won't 2844 // make inappropriate history items as if all wake locks went away and new ones 2845 // appeared. This is okay because tracking of wake locks allows nesting. 2846 final int NN = newWs.size(); 2847 for (int i=0; i<NN; i++) { 2848 noteStartWakeLocked(newWs.get(i), newPid, newName, newHistoryName, newType, 2849 newUnimportantForLogging, elapsedRealtime, uptime); 2850 } 2851 final int NO = ws.size(); 2852 for (int i=0; i<NO; i++) { 2853 noteStopWakeLocked(ws.get(i), pid, name, historyName, type, elapsedRealtime, uptime); 2854 } 2855 } 2856 2857 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name, 2858 String historyName, int type) { 2859 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2860 final long uptime = SystemClock.uptimeMillis(); 2861 final int N = ws.size(); 2862 for (int i=0; i<N; i++) { 2863 noteStopWakeLocked(ws.get(i), pid, name, historyName, type, elapsedRealtime, uptime); 2864 } 2865 } 2866 2867 void aggregateLastWakeupUptimeLocked(long uptimeMs) { 2868 if (mLastWakeupReason != null) { 2869 long deltaUptime = uptimeMs - mLastWakeupUptimeMs; 2870 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason); 2871 timer.addCurrentReportedCount(1); 2872 timer.addCurrentReportedTotalTime(deltaUptime * 1000); // time is in microseconds 2873 mLastWakeupReason = null; 2874 } 2875 } 2876 2877 public void noteWakeupReasonLocked(String reason) { 2878 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2879 final long uptime = SystemClock.uptimeMillis(); 2880 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": " 2881 + Integer.toHexString(mHistoryCur.states)); 2882 aggregateLastWakeupUptimeLocked(uptime); 2883 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag; 2884 mHistoryCur.wakeReasonTag.string = reason; 2885 mHistoryCur.wakeReasonTag.uid = 0; 2886 mLastWakeupReason = reason; 2887 mLastWakeupUptimeMs = uptime; 2888 addHistoryRecordLocked(elapsedRealtime, uptime); 2889 } 2890 2891 public boolean startAddingCpuLocked() { 2892 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS); 2893 return mOnBatteryInternal; 2894 } 2895 2896 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime, 2897 int statSystemTime, int statIOWaitTime, int statIrqTime, 2898 int statSoftIrqTime, int statIdleTime) { 2899 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime 2900 + " user=" + statUserTime + " sys=" + statSystemTime 2901 + " io=" + statIOWaitTime + " irq=" + statIrqTime 2902 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime); 2903 mCurStepCpuUserTime += totalUTime; 2904 mCurStepCpuSystemTime += totalSTime; 2905 mCurStepStatUserTime += statUserTime; 2906 mCurStepStatSystemTime += statSystemTime; 2907 mCurStepStatIOWaitTime += statIOWaitTime; 2908 mCurStepStatIrqTime += statIrqTime; 2909 mCurStepStatSoftIrqTime += statSoftIrqTime; 2910 mCurStepStatIdleTime += statIdleTime; 2911 } 2912 2913 public void noteProcessDiedLocked(int uid, int pid) { 2914 uid = mapUid(uid); 2915 Uid u = mUidStats.get(uid); 2916 if (u != null) { 2917 u.mPids.remove(pid); 2918 } 2919 } 2920 2921 public long getProcessWakeTime(int uid, int pid, long realtime) { 2922 uid = mapUid(uid); 2923 Uid u = mUidStats.get(uid); 2924 if (u != null) { 2925 Uid.Pid p = u.mPids.get(pid); 2926 if (p != null) { 2927 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0); 2928 } 2929 } 2930 return 0; 2931 } 2932 2933 public void reportExcessiveWakeLocked(int uid, String proc, long overTime, long usedTime) { 2934 uid = mapUid(uid); 2935 Uid u = mUidStats.get(uid); 2936 if (u != null) { 2937 u.reportExcessiveWakeLocked(proc, overTime, usedTime); 2938 } 2939 } 2940 2941 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) { 2942 uid = mapUid(uid); 2943 Uid u = mUidStats.get(uid); 2944 if (u != null) { 2945 u.reportExcessiveCpuLocked(proc, overTime, usedTime); 2946 } 2947 } 2948 2949 int mSensorNesting; 2950 2951 public void noteStartSensorLocked(int uid, int sensor) { 2952 uid = mapUid(uid); 2953 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2954 final long uptime = SystemClock.uptimeMillis(); 2955 if (mSensorNesting == 0) { 2956 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG; 2957 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: " 2958 + Integer.toHexString(mHistoryCur.states)); 2959 addHistoryRecordLocked(elapsedRealtime, uptime); 2960 } 2961 mSensorNesting++; 2962 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime); 2963 } 2964 2965 public void noteStopSensorLocked(int uid, int sensor) { 2966 uid = mapUid(uid); 2967 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2968 final long uptime = SystemClock.uptimeMillis(); 2969 mSensorNesting--; 2970 if (mSensorNesting == 0) { 2971 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG; 2972 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: " 2973 + Integer.toHexString(mHistoryCur.states)); 2974 addHistoryRecordLocked(elapsedRealtime, uptime); 2975 } 2976 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime); 2977 } 2978 2979 int mGpsNesting; 2980 2981 public void noteStartGpsLocked(int uid) { 2982 uid = mapUid(uid); 2983 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2984 final long uptime = SystemClock.uptimeMillis(); 2985 if (mGpsNesting == 0) { 2986 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG; 2987 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: " 2988 + Integer.toHexString(mHistoryCur.states)); 2989 addHistoryRecordLocked(elapsedRealtime, uptime); 2990 } 2991 mGpsNesting++; 2992 getUidStatsLocked(uid).noteStartGps(elapsedRealtime); 2993 } 2994 2995 public void noteStopGpsLocked(int uid) { 2996 uid = mapUid(uid); 2997 final long elapsedRealtime = SystemClock.elapsedRealtime(); 2998 final long uptime = SystemClock.uptimeMillis(); 2999 mGpsNesting--; 3000 if (mGpsNesting == 0) { 3001 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG; 3002 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: " 3003 + Integer.toHexString(mHistoryCur.states)); 3004 addHistoryRecordLocked(elapsedRealtime, uptime); 3005 } 3006 getUidStatsLocked(uid).noteStopGps(elapsedRealtime); 3007 } 3008 3009 public void noteScreenStateLocked(int state) { 3010 if (mScreenState != state) { 3011 recordDailyStatsIfNeededLocked(true); 3012 final int oldState = mScreenState; 3013 mScreenState = state; 3014 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState) 3015 + ", newState=" + Display.stateToString(state)); 3016 3017 if (state != Display.STATE_UNKNOWN) { 3018 int stepState = state-1; 3019 if (stepState < 4) { 3020 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState; 3021 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_SCREEN_STATE) | stepState; 3022 } else { 3023 Slog.wtf(TAG, "Unexpected screen state: " + state); 3024 } 3025 } 3026 3027 if (state == Display.STATE_ON) { 3028 // Screen turning on. 3029 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3030 final long uptime = SystemClock.uptimeMillis(); 3031 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG; 3032 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: " 3033 + Integer.toHexString(mHistoryCur.states)); 3034 addHistoryRecordLocked(elapsedRealtime, uptime); 3035 mScreenOnTimer.startRunningLocked(elapsedRealtime); 3036 if (mScreenBrightnessBin >= 0) { 3037 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime); 3038 } 3039 3040 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), false, 3041 SystemClock.uptimeMillis() * 1000, elapsedRealtime * 1000); 3042 3043 // Fake a wake lock, so we consider the device waked as long 3044 // as the screen is on. 3045 noteStartWakeLocked(-1, -1, "screen", null, WAKE_TYPE_PARTIAL, false, 3046 elapsedRealtime, uptime); 3047 3048 // Update discharge amounts. 3049 if (mOnBatteryInternal) { 3050 updateDischargeScreenLevelsLocked(false, true); 3051 } 3052 } else if (oldState == Display.STATE_ON) { 3053 // Screen turning off or dozing. 3054 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3055 final long uptime = SystemClock.uptimeMillis(); 3056 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG; 3057 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: " 3058 + Integer.toHexString(mHistoryCur.states)); 3059 addHistoryRecordLocked(elapsedRealtime, uptime); 3060 mScreenOnTimer.stopRunningLocked(elapsedRealtime); 3061 if (mScreenBrightnessBin >= 0) { 3062 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime); 3063 } 3064 3065 noteStopWakeLocked(-1, -1, "screen", "screen", WAKE_TYPE_PARTIAL, 3066 elapsedRealtime, uptime); 3067 3068 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), true, 3069 SystemClock.uptimeMillis() * 1000, elapsedRealtime * 1000); 3070 3071 // Update discharge amounts. 3072 if (mOnBatteryInternal) { 3073 updateDischargeScreenLevelsLocked(true, false); 3074 } 3075 } 3076 } 3077 } 3078 3079 public void noteScreenBrightnessLocked(int brightness) { 3080 // Bin the brightness. 3081 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS); 3082 if (bin < 0) bin = 0; 3083 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1; 3084 if (mScreenBrightnessBin != bin) { 3085 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3086 final long uptime = SystemClock.uptimeMillis(); 3087 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK) 3088 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT); 3089 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: " 3090 + Integer.toHexString(mHistoryCur.states)); 3091 addHistoryRecordLocked(elapsedRealtime, uptime); 3092 if (mScreenState == Display.STATE_ON) { 3093 if (mScreenBrightnessBin >= 0) { 3094 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime); 3095 } 3096 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime); 3097 } 3098 mScreenBrightnessBin = bin; 3099 } 3100 } 3101 3102 public void noteUserActivityLocked(int uid, int event) { 3103 if (mOnBatteryInternal) { 3104 uid = mapUid(uid); 3105 getUidStatsLocked(uid).noteUserActivityLocked(event); 3106 } 3107 } 3108 3109 public void noteInteractiveLocked(boolean interactive) { 3110 if (mInteractive != interactive) { 3111 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3112 mInteractive = interactive; 3113 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive); 3114 if (interactive) { 3115 mInteractiveTimer.startRunningLocked(elapsedRealtime); 3116 } else { 3117 mInteractiveTimer.stopRunningLocked(elapsedRealtime); 3118 } 3119 } 3120 } 3121 3122 public void noteConnectivityChangedLocked(int type, String extra) { 3123 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3124 final long uptime = SystemClock.uptimeMillis(); 3125 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED, 3126 extra, type); 3127 mNumConnectivityChange++; 3128 } 3129 3130 public void noteMobileRadioPowerState(int powerState, long timestampNs) { 3131 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3132 final long uptime = SystemClock.uptimeMillis(); 3133 if (mMobileRadioPowerState != powerState) { 3134 long realElapsedRealtimeMs; 3135 final boolean active = 3136 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM 3137 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH; 3138 if (active) { 3139 mMobileRadioActiveStartTime = realElapsedRealtimeMs = elapsedRealtime; 3140 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG; 3141 } else { 3142 realElapsedRealtimeMs = timestampNs / (1000*1000); 3143 long lastUpdateTimeMs = mMobileRadioActiveStartTime; 3144 if (realElapsedRealtimeMs < lastUpdateTimeMs) { 3145 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs 3146 + " is before start time " + lastUpdateTimeMs); 3147 realElapsedRealtimeMs = elapsedRealtime; 3148 } else if (realElapsedRealtimeMs < elapsedRealtime) { 3149 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime 3150 - realElapsedRealtimeMs); 3151 } 3152 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG; 3153 } 3154 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: " 3155 + Integer.toHexString(mHistoryCur.states)); 3156 addHistoryRecordLocked(elapsedRealtime, uptime); 3157 mMobileRadioPowerState = powerState; 3158 if (active) { 3159 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime); 3160 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime); 3161 } else { 3162 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs); 3163 updateMobileRadioStateLocked(realElapsedRealtimeMs); 3164 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs); 3165 } 3166 } 3167 } 3168 3169 public void notePowerSaveMode(boolean enabled) { 3170 if (mPowerSaveModeEnabled != enabled) { 3171 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0; 3172 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState; 3173 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState; 3174 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3175 final long uptime = SystemClock.uptimeMillis(); 3176 mPowerSaveModeEnabled = enabled; 3177 if (enabled) { 3178 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG; 3179 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: " 3180 + Integer.toHexString(mHistoryCur.states2)); 3181 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime); 3182 } else { 3183 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG; 3184 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: " 3185 + Integer.toHexString(mHistoryCur.states2)); 3186 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime); 3187 } 3188 addHistoryRecordLocked(elapsedRealtime, uptime); 3189 } 3190 } 3191 3192 public void noteDeviceIdleModeLocked(boolean enabled, String activeReason, int activeUid) { 3193 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3194 final long uptime = SystemClock.uptimeMillis(); 3195 boolean nowIdling = enabled; 3196 if (mDeviceIdling && !enabled && activeReason == null) { 3197 // We don't go out of general idling mode until explicitly taken out of 3198 // device idle through going active or significant motion. 3199 nowIdling = true; 3200 } 3201 if (mDeviceIdling != nowIdling) { 3202 mDeviceIdling = nowIdling; 3203 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0; 3204 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState; 3205 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState; 3206 if (enabled) { 3207 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime); 3208 } else { 3209 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime); 3210 } 3211 } 3212 if (mDeviceIdleModeEnabled != enabled) { 3213 mDeviceIdleModeEnabled = enabled; 3214 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE, 3215 activeReason != null ? activeReason : "", activeUid); 3216 if (enabled) { 3217 mHistoryCur.states2 |= HistoryItem.STATE2_DEVICE_IDLE_FLAG; 3218 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode enabled to: " 3219 + Integer.toHexString(mHistoryCur.states2)); 3220 mDeviceIdleModeEnabledTimer.startRunningLocked(elapsedRealtime); 3221 } else { 3222 mHistoryCur.states2 &= ~HistoryItem.STATE2_DEVICE_IDLE_FLAG; 3223 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode disabled to: " 3224 + Integer.toHexString(mHistoryCur.states2)); 3225 mDeviceIdleModeEnabledTimer.stopRunningLocked(elapsedRealtime); 3226 } 3227 addHistoryRecordLocked(elapsedRealtime, uptime); 3228 } 3229 } 3230 3231 public void notePackageInstalledLocked(String pkgName, int versionCode) { 3232 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3233 final long uptime = SystemClock.uptimeMillis(); 3234 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED, 3235 pkgName, versionCode); 3236 PackageChange pc = new PackageChange(); 3237 pc.mPackageName = pkgName; 3238 pc.mUpdate = true; 3239 pc.mVersionCode = versionCode; 3240 addPackageChange(pc); 3241 } 3242 3243 public void notePackageUninstalledLocked(String pkgName) { 3244 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3245 final long uptime = SystemClock.uptimeMillis(); 3246 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED, 3247 pkgName, 0); 3248 PackageChange pc = new PackageChange(); 3249 pc.mPackageName = pkgName; 3250 pc.mUpdate = true; 3251 addPackageChange(pc); 3252 } 3253 3254 private void addPackageChange(PackageChange pc) { 3255 if (mDailyPackageChanges == null) { 3256 mDailyPackageChanges = new ArrayList<>(); 3257 } 3258 mDailyPackageChanges.add(pc); 3259 } 3260 3261 public void notePhoneOnLocked() { 3262 if (!mPhoneOn) { 3263 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3264 final long uptime = SystemClock.uptimeMillis(); 3265 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG; 3266 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: " 3267 + Integer.toHexString(mHistoryCur.states)); 3268 addHistoryRecordLocked(elapsedRealtime, uptime); 3269 mPhoneOn = true; 3270 mPhoneOnTimer.startRunningLocked(elapsedRealtime); 3271 } 3272 } 3273 3274 public void notePhoneOffLocked() { 3275 if (mPhoneOn) { 3276 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3277 final long uptime = SystemClock.uptimeMillis(); 3278 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG; 3279 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: " 3280 + Integer.toHexString(mHistoryCur.states)); 3281 addHistoryRecordLocked(elapsedRealtime, uptime); 3282 mPhoneOn = false; 3283 mPhoneOnTimer.stopRunningLocked(elapsedRealtime); 3284 } 3285 } 3286 3287 void stopAllPhoneSignalStrengthTimersLocked(int except) { 3288 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3289 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) { 3290 if (i == except) { 3291 continue; 3292 } 3293 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) { 3294 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime); 3295 } 3296 } 3297 } 3298 3299 private int fixPhoneServiceState(int state, int signalBin) { 3300 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) { 3301 // In this case we will always be STATE_OUT_OF_SERVICE, so need 3302 // to infer that we are scanning from other data. 3303 if (state == ServiceState.STATE_OUT_OF_SERVICE 3304 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) { 3305 state = ServiceState.STATE_IN_SERVICE; 3306 } 3307 } 3308 3309 return state; 3310 } 3311 3312 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) { 3313 boolean scanning = false; 3314 boolean newHistory = false; 3315 3316 mPhoneServiceStateRaw = state; 3317 mPhoneSimStateRaw = simState; 3318 mPhoneSignalStrengthBinRaw = strengthBin; 3319 3320 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3321 final long uptime = SystemClock.uptimeMillis(); 3322 3323 if (simState == TelephonyManager.SIM_STATE_ABSENT) { 3324 // In this case we will always be STATE_OUT_OF_SERVICE, so need 3325 // to infer that we are scanning from other data. 3326 if (state == ServiceState.STATE_OUT_OF_SERVICE 3327 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) { 3328 state = ServiceState.STATE_IN_SERVICE; 3329 } 3330 } 3331 3332 // If the phone is powered off, stop all timers. 3333 if (state == ServiceState.STATE_POWER_OFF) { 3334 strengthBin = -1; 3335 3336 // If we are in service, make sure the correct signal string timer is running. 3337 } else if (state == ServiceState.STATE_IN_SERVICE) { 3338 // Bin will be changed below. 3339 3340 // If we're out of service, we are in the lowest signal strength 3341 // bin and have the scanning bit set. 3342 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) { 3343 scanning = true; 3344 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN; 3345 if (!mPhoneSignalScanningTimer.isRunningLocked()) { 3346 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG; 3347 newHistory = true; 3348 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: " 3349 + Integer.toHexString(mHistoryCur.states)); 3350 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime); 3351 } 3352 } 3353 3354 if (!scanning) { 3355 // If we are no longer scanning, then stop the scanning timer. 3356 if (mPhoneSignalScanningTimer.isRunningLocked()) { 3357 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG; 3358 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: " 3359 + Integer.toHexString(mHistoryCur.states)); 3360 newHistory = true; 3361 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime); 3362 } 3363 } 3364 3365 if (mPhoneServiceState != state) { 3366 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK) 3367 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT); 3368 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: " 3369 + Integer.toHexString(mHistoryCur.states)); 3370 newHistory = true; 3371 mPhoneServiceState = state; 3372 } 3373 3374 if (mPhoneSignalStrengthBin != strengthBin) { 3375 if (mPhoneSignalStrengthBin >= 0) { 3376 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked( 3377 elapsedRealtime); 3378 } 3379 if (strengthBin >= 0) { 3380 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) { 3381 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime); 3382 } 3383 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK) 3384 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT); 3385 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: " 3386 + Integer.toHexString(mHistoryCur.states)); 3387 newHistory = true; 3388 } else { 3389 stopAllPhoneSignalStrengthTimersLocked(-1); 3390 } 3391 mPhoneSignalStrengthBin = strengthBin; 3392 } 3393 3394 if (newHistory) { 3395 addHistoryRecordLocked(elapsedRealtime, uptime); 3396 } 3397 } 3398 3399 /** 3400 * Telephony stack updates the phone state. 3401 * @param state phone state from ServiceState.getState() 3402 */ 3403 public void notePhoneStateLocked(int state, int simState) { 3404 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw); 3405 } 3406 3407 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) { 3408 // Bin the strength. 3409 int bin = signalStrength.getLevel(); 3410 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin); 3411 } 3412 3413 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) { 3414 int bin = DATA_CONNECTION_NONE; 3415 if (hasData) { 3416 switch (dataType) { 3417 case TelephonyManager.NETWORK_TYPE_EDGE: 3418 bin = DATA_CONNECTION_EDGE; 3419 break; 3420 case TelephonyManager.NETWORK_TYPE_GPRS: 3421 bin = DATA_CONNECTION_GPRS; 3422 break; 3423 case TelephonyManager.NETWORK_TYPE_UMTS: 3424 bin = DATA_CONNECTION_UMTS; 3425 break; 3426 case TelephonyManager.NETWORK_TYPE_CDMA: 3427 bin = DATA_CONNECTION_CDMA; 3428 break; 3429 case TelephonyManager.NETWORK_TYPE_EVDO_0: 3430 bin = DATA_CONNECTION_EVDO_0; 3431 break; 3432 case TelephonyManager.NETWORK_TYPE_EVDO_A: 3433 bin = DATA_CONNECTION_EVDO_A; 3434 break; 3435 case TelephonyManager.NETWORK_TYPE_1xRTT: 3436 bin = DATA_CONNECTION_1xRTT; 3437 break; 3438 case TelephonyManager.NETWORK_TYPE_HSDPA: 3439 bin = DATA_CONNECTION_HSDPA; 3440 break; 3441 case TelephonyManager.NETWORK_TYPE_HSUPA: 3442 bin = DATA_CONNECTION_HSUPA; 3443 break; 3444 case TelephonyManager.NETWORK_TYPE_HSPA: 3445 bin = DATA_CONNECTION_HSPA; 3446 break; 3447 case TelephonyManager.NETWORK_TYPE_IDEN: 3448 bin = DATA_CONNECTION_IDEN; 3449 break; 3450 case TelephonyManager.NETWORK_TYPE_EVDO_B: 3451 bin = DATA_CONNECTION_EVDO_B; 3452 break; 3453 case TelephonyManager.NETWORK_TYPE_LTE: 3454 bin = DATA_CONNECTION_LTE; 3455 break; 3456 case TelephonyManager.NETWORK_TYPE_EHRPD: 3457 bin = DATA_CONNECTION_EHRPD; 3458 break; 3459 case TelephonyManager.NETWORK_TYPE_HSPAP: 3460 bin = DATA_CONNECTION_HSPAP; 3461 break; 3462 default: 3463 bin = DATA_CONNECTION_OTHER; 3464 break; 3465 } 3466 } 3467 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData); 3468 if (mPhoneDataConnectionType != bin) { 3469 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3470 final long uptime = SystemClock.uptimeMillis(); 3471 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK) 3472 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT); 3473 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: " 3474 + Integer.toHexString(mHistoryCur.states)); 3475 addHistoryRecordLocked(elapsedRealtime, uptime); 3476 if (mPhoneDataConnectionType >= 0) { 3477 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked( 3478 elapsedRealtime); 3479 } 3480 mPhoneDataConnectionType = bin; 3481 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime); 3482 } 3483 } 3484 3485 public void noteWifiOnLocked() { 3486 if (!mWifiOn) { 3487 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3488 final long uptime = SystemClock.uptimeMillis(); 3489 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG; 3490 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: " 3491 + Integer.toHexString(mHistoryCur.states)); 3492 addHistoryRecordLocked(elapsedRealtime, uptime); 3493 mWifiOn = true; 3494 mWifiOnTimer.startRunningLocked(elapsedRealtime); 3495 scheduleSyncExternalWifiStatsLocked("wifi-off"); 3496 } 3497 } 3498 3499 public void noteWifiOffLocked() { 3500 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3501 final long uptime = SystemClock.uptimeMillis(); 3502 if (mWifiOn) { 3503 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG; 3504 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: " 3505 + Integer.toHexString(mHistoryCur.states)); 3506 addHistoryRecordLocked(elapsedRealtime, uptime); 3507 mWifiOn = false; 3508 mWifiOnTimer.stopRunningLocked(elapsedRealtime); 3509 scheduleSyncExternalWifiStatsLocked("wifi-on"); 3510 } 3511 } 3512 3513 public void noteAudioOnLocked(int uid) { 3514 uid = mapUid(uid); 3515 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3516 final long uptime = SystemClock.uptimeMillis(); 3517 if (mAudioOnNesting == 0) { 3518 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG; 3519 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: " 3520 + Integer.toHexString(mHistoryCur.states)); 3521 addHistoryRecordLocked(elapsedRealtime, uptime); 3522 mAudioOnTimer.startRunningLocked(elapsedRealtime); 3523 } 3524 mAudioOnNesting++; 3525 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime); 3526 } 3527 3528 public void noteAudioOffLocked(int uid) { 3529 if (mAudioOnNesting == 0) { 3530 return; 3531 } 3532 uid = mapUid(uid); 3533 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3534 final long uptime = SystemClock.uptimeMillis(); 3535 if (--mAudioOnNesting == 0) { 3536 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG; 3537 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: " 3538 + Integer.toHexString(mHistoryCur.states)); 3539 addHistoryRecordLocked(elapsedRealtime, uptime); 3540 mAudioOnTimer.stopRunningLocked(elapsedRealtime); 3541 } 3542 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime); 3543 } 3544 3545 public void noteVideoOnLocked(int uid) { 3546 uid = mapUid(uid); 3547 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3548 final long uptime = SystemClock.uptimeMillis(); 3549 if (mVideoOnNesting == 0) { 3550 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG; 3551 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: " 3552 + Integer.toHexString(mHistoryCur.states)); 3553 addHistoryRecordLocked(elapsedRealtime, uptime); 3554 mVideoOnTimer.startRunningLocked(elapsedRealtime); 3555 } 3556 mVideoOnNesting++; 3557 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime); 3558 } 3559 3560 public void noteVideoOffLocked(int uid) { 3561 if (mVideoOnNesting == 0) { 3562 return; 3563 } 3564 uid = mapUid(uid); 3565 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3566 final long uptime = SystemClock.uptimeMillis(); 3567 if (--mVideoOnNesting == 0) { 3568 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG; 3569 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: " 3570 + Integer.toHexString(mHistoryCur.states)); 3571 addHistoryRecordLocked(elapsedRealtime, uptime); 3572 mVideoOnTimer.stopRunningLocked(elapsedRealtime); 3573 } 3574 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime); 3575 } 3576 3577 public void noteResetAudioLocked() { 3578 if (mAudioOnNesting > 0) { 3579 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3580 final long uptime = SystemClock.uptimeMillis(); 3581 mAudioOnNesting = 0; 3582 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG; 3583 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: " 3584 + Integer.toHexString(mHistoryCur.states)); 3585 addHistoryRecordLocked(elapsedRealtime, uptime); 3586 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime); 3587 for (int i=0; i<mUidStats.size(); i++) { 3588 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i); 3589 uid.noteResetAudioLocked(elapsedRealtime); 3590 } 3591 } 3592 } 3593 3594 public void noteResetVideoLocked() { 3595 if (mVideoOnNesting > 0) { 3596 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3597 final long uptime = SystemClock.uptimeMillis(); 3598 mAudioOnNesting = 0; 3599 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG; 3600 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: " 3601 + Integer.toHexString(mHistoryCur.states)); 3602 addHistoryRecordLocked(elapsedRealtime, uptime); 3603 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime); 3604 for (int i=0; i<mUidStats.size(); i++) { 3605 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i); 3606 uid.noteResetVideoLocked(elapsedRealtime); 3607 } 3608 } 3609 } 3610 3611 public void noteActivityResumedLocked(int uid) { 3612 uid = mapUid(uid); 3613 getUidStatsLocked(uid).noteActivityResumedLocked(SystemClock.elapsedRealtime()); 3614 } 3615 3616 public void noteActivityPausedLocked(int uid) { 3617 uid = mapUid(uid); 3618 getUidStatsLocked(uid).noteActivityPausedLocked(SystemClock.elapsedRealtime()); 3619 } 3620 3621 public void noteVibratorOnLocked(int uid, long durationMillis) { 3622 uid = mapUid(uid); 3623 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis); 3624 } 3625 3626 public void noteVibratorOffLocked(int uid) { 3627 uid = mapUid(uid); 3628 getUidStatsLocked(uid).noteVibratorOffLocked(); 3629 } 3630 3631 public void noteFlashlightOnLocked(int uid) { 3632 uid = mapUid(uid); 3633 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3634 final long uptime = SystemClock.uptimeMillis(); 3635 if (mFlashlightOnNesting++ == 0) { 3636 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG; 3637 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: " 3638 + Integer.toHexString(mHistoryCur.states2)); 3639 addHistoryRecordLocked(elapsedRealtime, uptime); 3640 mFlashlightOnTimer.startRunningLocked(elapsedRealtime); 3641 } 3642 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime); 3643 } 3644 3645 public void noteFlashlightOffLocked(int uid) { 3646 if (mFlashlightOnNesting == 0) { 3647 return; 3648 } 3649 uid = mapUid(uid); 3650 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3651 final long uptime = SystemClock.uptimeMillis(); 3652 if (--mFlashlightOnNesting == 0) { 3653 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG; 3654 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: " 3655 + Integer.toHexString(mHistoryCur.states2)); 3656 addHistoryRecordLocked(elapsedRealtime, uptime); 3657 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime); 3658 } 3659 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime); 3660 } 3661 3662 public void noteCameraOnLocked(int uid) { 3663 uid = mapUid(uid); 3664 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3665 final long uptime = SystemClock.uptimeMillis(); 3666 if (mCameraOnNesting++ == 0) { 3667 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG; 3668 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: " 3669 + Integer.toHexString(mHistoryCur.states2)); 3670 addHistoryRecordLocked(elapsedRealtime, uptime); 3671 mCameraOnTimer.startRunningLocked(elapsedRealtime); 3672 } 3673 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime); 3674 } 3675 3676 public void noteCameraOffLocked(int uid) { 3677 if (mCameraOnNesting == 0) { 3678 return; 3679 } 3680 uid = mapUid(uid); 3681 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3682 final long uptime = SystemClock.uptimeMillis(); 3683 if (--mCameraOnNesting == 0) { 3684 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG; 3685 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: " 3686 + Integer.toHexString(mHistoryCur.states2)); 3687 addHistoryRecordLocked(elapsedRealtime, uptime); 3688 mCameraOnTimer.stopRunningLocked(elapsedRealtime); 3689 } 3690 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime); 3691 } 3692 3693 public void noteResetCameraLocked() { 3694 if (mCameraOnNesting > 0) { 3695 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3696 final long uptime = SystemClock.uptimeMillis(); 3697 mCameraOnNesting = 0; 3698 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG; 3699 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: " 3700 + Integer.toHexString(mHistoryCur.states2)); 3701 addHistoryRecordLocked(elapsedRealtime, uptime); 3702 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime); 3703 for (int i=0; i<mUidStats.size(); i++) { 3704 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i); 3705 uid.noteResetCameraLocked(elapsedRealtime); 3706 } 3707 } 3708 } 3709 3710 public void noteResetFlashlightLocked() { 3711 if (mFlashlightOnNesting > 0) { 3712 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3713 final long uptime = SystemClock.uptimeMillis(); 3714 mFlashlightOnNesting = 0; 3715 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG; 3716 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: " 3717 + Integer.toHexString(mHistoryCur.states2)); 3718 addHistoryRecordLocked(elapsedRealtime, uptime); 3719 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime); 3720 for (int i=0; i<mUidStats.size(); i++) { 3721 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i); 3722 uid.noteResetFlashlightLocked(elapsedRealtime); 3723 } 3724 } 3725 } 3726 3727 public void noteWifiRadioPowerState(int powerState, long timestampNs) { 3728 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3729 final long uptime = SystemClock.uptimeMillis(); 3730 if (mWifiRadioPowerState != powerState) { 3731 final boolean active = 3732 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM 3733 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH; 3734 if (active) { 3735 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG; 3736 } else { 3737 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG; 3738 } 3739 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: " 3740 + Integer.toHexString(mHistoryCur.states)); 3741 addHistoryRecordLocked(elapsedRealtime, uptime); 3742 mWifiRadioPowerState = powerState; 3743 } 3744 } 3745 3746 public void noteWifiRunningLocked(WorkSource ws) { 3747 if (!mGlobalWifiRunning) { 3748 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3749 final long uptime = SystemClock.uptimeMillis(); 3750 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG; 3751 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: " 3752 + Integer.toHexString(mHistoryCur.states)); 3753 addHistoryRecordLocked(elapsedRealtime, uptime); 3754 mGlobalWifiRunning = true; 3755 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime); 3756 int N = ws.size(); 3757 for (int i=0; i<N; i++) { 3758 int uid = mapUid(ws.get(i)); 3759 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime); 3760 } 3761 scheduleSyncExternalWifiStatsLocked("wifi-running"); 3762 } else { 3763 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running"); 3764 } 3765 } 3766 3767 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) { 3768 if (mGlobalWifiRunning) { 3769 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3770 int N = oldWs.size(); 3771 for (int i=0; i<N; i++) { 3772 int uid = mapUid(oldWs.get(i)); 3773 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime); 3774 } 3775 N = newWs.size(); 3776 for (int i=0; i<N; i++) { 3777 int uid = mapUid(newWs.get(i)); 3778 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime); 3779 } 3780 } else { 3781 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running"); 3782 } 3783 } 3784 3785 public void noteWifiStoppedLocked(WorkSource ws) { 3786 if (mGlobalWifiRunning) { 3787 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3788 final long uptime = SystemClock.uptimeMillis(); 3789 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG; 3790 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: " 3791 + Integer.toHexString(mHistoryCur.states)); 3792 addHistoryRecordLocked(elapsedRealtime, uptime); 3793 mGlobalWifiRunning = false; 3794 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime); 3795 int N = ws.size(); 3796 for (int i=0; i<N; i++) { 3797 int uid = mapUid(ws.get(i)); 3798 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime); 3799 } 3800 scheduleSyncExternalWifiStatsLocked("wifi-stopped"); 3801 } else { 3802 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running"); 3803 } 3804 } 3805 3806 public void noteWifiStateLocked(int wifiState, String accessPoint) { 3807 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState); 3808 if (mWifiState != wifiState) { 3809 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3810 if (mWifiState >= 0) { 3811 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime); 3812 } 3813 mWifiState = wifiState; 3814 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime); 3815 scheduleSyncExternalWifiStatsLocked("wifi-state"); 3816 } 3817 } 3818 3819 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) { 3820 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState); 3821 if (mWifiSupplState != supplState) { 3822 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3823 final long uptime = SystemClock.uptimeMillis(); 3824 if (mWifiSupplState >= 0) { 3825 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime); 3826 } 3827 mWifiSupplState = supplState; 3828 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime); 3829 mHistoryCur.states2 = 3830 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK) 3831 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT); 3832 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: " 3833 + Integer.toHexString(mHistoryCur.states2)); 3834 addHistoryRecordLocked(elapsedRealtime, uptime); 3835 } 3836 } 3837 3838 void stopAllWifiSignalStrengthTimersLocked(int except) { 3839 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3840 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) { 3841 if (i == except) { 3842 continue; 3843 } 3844 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) { 3845 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime); 3846 } 3847 } 3848 } 3849 3850 public void noteWifiRssiChangedLocked(int newRssi) { 3851 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS); 3852 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin); 3853 if (mWifiSignalStrengthBin != strengthBin) { 3854 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3855 final long uptime = SystemClock.uptimeMillis(); 3856 if (mWifiSignalStrengthBin >= 0) { 3857 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked( 3858 elapsedRealtime); 3859 } 3860 if (strengthBin >= 0) { 3861 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) { 3862 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime); 3863 } 3864 mHistoryCur.states2 = 3865 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK) 3866 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT); 3867 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: " 3868 + Integer.toHexString(mHistoryCur.states2)); 3869 addHistoryRecordLocked(elapsedRealtime, uptime); 3870 } else { 3871 stopAllWifiSignalStrengthTimersLocked(-1); 3872 } 3873 mWifiSignalStrengthBin = strengthBin; 3874 } 3875 } 3876 3877 int mWifiFullLockNesting = 0; 3878 3879 public void noteFullWifiLockAcquiredLocked(int uid) { 3880 uid = mapUid(uid); 3881 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3882 final long uptime = SystemClock.uptimeMillis(); 3883 if (mWifiFullLockNesting == 0) { 3884 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG; 3885 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: " 3886 + Integer.toHexString(mHistoryCur.states)); 3887 addHistoryRecordLocked(elapsedRealtime, uptime); 3888 } 3889 mWifiFullLockNesting++; 3890 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime); 3891 } 3892 3893 public void noteFullWifiLockReleasedLocked(int uid) { 3894 uid = mapUid(uid); 3895 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3896 final long uptime = SystemClock.uptimeMillis(); 3897 mWifiFullLockNesting--; 3898 if (mWifiFullLockNesting == 0) { 3899 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG; 3900 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: " 3901 + Integer.toHexString(mHistoryCur.states)); 3902 addHistoryRecordLocked(elapsedRealtime, uptime); 3903 } 3904 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime); 3905 } 3906 3907 int mWifiScanNesting = 0; 3908 3909 public void noteWifiScanStartedLocked(int uid) { 3910 uid = mapUid(uid); 3911 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3912 final long uptime = SystemClock.uptimeMillis(); 3913 if (mWifiScanNesting == 0) { 3914 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG; 3915 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: " 3916 + Integer.toHexString(mHistoryCur.states)); 3917 addHistoryRecordLocked(elapsedRealtime, uptime); 3918 } 3919 mWifiScanNesting++; 3920 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime); 3921 } 3922 3923 public void noteWifiScanStoppedLocked(int uid) { 3924 uid = mapUid(uid); 3925 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3926 final long uptime = SystemClock.uptimeMillis(); 3927 mWifiScanNesting--; 3928 if (mWifiScanNesting == 0) { 3929 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG; 3930 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: " 3931 + Integer.toHexString(mHistoryCur.states)); 3932 addHistoryRecordLocked(elapsedRealtime, uptime); 3933 } 3934 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime); 3935 } 3936 3937 public void noteWifiBatchedScanStartedLocked(int uid, int csph) { 3938 uid = mapUid(uid); 3939 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3940 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime); 3941 } 3942 3943 public void noteWifiBatchedScanStoppedLocked(int uid) { 3944 uid = mapUid(uid); 3945 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3946 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime); 3947 } 3948 3949 int mWifiMulticastNesting = 0; 3950 3951 public void noteWifiMulticastEnabledLocked(int uid) { 3952 uid = mapUid(uid); 3953 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3954 final long uptime = SystemClock.uptimeMillis(); 3955 if (mWifiMulticastNesting == 0) { 3956 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG; 3957 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: " 3958 + Integer.toHexString(mHistoryCur.states)); 3959 addHistoryRecordLocked(elapsedRealtime, uptime); 3960 } 3961 mWifiMulticastNesting++; 3962 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime); 3963 } 3964 3965 public void noteWifiMulticastDisabledLocked(int uid) { 3966 uid = mapUid(uid); 3967 final long elapsedRealtime = SystemClock.elapsedRealtime(); 3968 final long uptime = SystemClock.uptimeMillis(); 3969 mWifiMulticastNesting--; 3970 if (mWifiMulticastNesting == 0) { 3971 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG; 3972 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: " 3973 + Integer.toHexString(mHistoryCur.states)); 3974 addHistoryRecordLocked(elapsedRealtime, uptime); 3975 } 3976 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime); 3977 } 3978 3979 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) { 3980 int N = ws.size(); 3981 for (int i=0; i<N; i++) { 3982 noteFullWifiLockAcquiredLocked(ws.get(i)); 3983 } 3984 } 3985 3986 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) { 3987 int N = ws.size(); 3988 for (int i=0; i<N; i++) { 3989 noteFullWifiLockReleasedLocked(ws.get(i)); 3990 } 3991 } 3992 3993 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) { 3994 int N = ws.size(); 3995 for (int i=0; i<N; i++) { 3996 noteWifiScanStartedLocked(ws.get(i)); 3997 } 3998 } 3999 4000 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) { 4001 int N = ws.size(); 4002 for (int i=0; i<N; i++) { 4003 noteWifiScanStoppedLocked(ws.get(i)); 4004 } 4005 } 4006 4007 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) { 4008 int N = ws.size(); 4009 for (int i=0; i<N; i++) { 4010 noteWifiBatchedScanStartedLocked(ws.get(i), csph); 4011 } 4012 } 4013 4014 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) { 4015 int N = ws.size(); 4016 for (int i=0; i<N; i++) { 4017 noteWifiBatchedScanStoppedLocked(ws.get(i)); 4018 } 4019 } 4020 4021 public void noteWifiMulticastEnabledFromSourceLocked(WorkSource ws) { 4022 int N = ws.size(); 4023 for (int i=0; i<N; i++) { 4024 noteWifiMulticastEnabledLocked(ws.get(i)); 4025 } 4026 } 4027 4028 public void noteWifiMulticastDisabledFromSourceLocked(WorkSource ws) { 4029 int N = ws.size(); 4030 for (int i=0; i<N; i++) { 4031 noteWifiMulticastDisabledLocked(ws.get(i)); 4032 } 4033 } 4034 4035 private static String[] includeInStringArray(String[] array, String str) { 4036 if (ArrayUtils.indexOf(array, str) >= 0) { 4037 return array; 4038 } 4039 String[] newArray = new String[array.length+1]; 4040 System.arraycopy(array, 0, newArray, 0, array.length); 4041 newArray[array.length] = str; 4042 return newArray; 4043 } 4044 4045 private static String[] excludeFromStringArray(String[] array, String str) { 4046 int index = ArrayUtils.indexOf(array, str); 4047 if (index >= 0) { 4048 String[] newArray = new String[array.length-1]; 4049 if (index > 0) { 4050 System.arraycopy(array, 0, newArray, 0, index); 4051 } 4052 if (index < array.length-1) { 4053 System.arraycopy(array, index+1, newArray, index, array.length-index-1); 4054 } 4055 return newArray; 4056 } 4057 return array; 4058 } 4059 4060 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) { 4061 if (TextUtils.isEmpty(iface)) return; 4062 if (ConnectivityManager.isNetworkTypeMobile(networkType)) { 4063 mMobileIfaces = includeInStringArray(mMobileIfaces, iface); 4064 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mMobileIfaces); 4065 } else { 4066 mMobileIfaces = excludeFromStringArray(mMobileIfaces, iface); 4067 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mMobileIfaces); 4068 } 4069 if (ConnectivityManager.isNetworkTypeWifi(networkType)) { 4070 mWifiIfaces = includeInStringArray(mWifiIfaces, iface); 4071 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces); 4072 } else { 4073 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface); 4074 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces); 4075 } 4076 } 4077 4078 public void noteNetworkStatsEnabledLocked() { 4079 // During device boot, qtaguid isn't enabled until after the inital 4080 // loading of battery stats. Now that they're enabled, take our initial 4081 // snapshot for future delta calculation. 4082 final long elapsedRealtimeMs = SystemClock.elapsedRealtime(); 4083 updateMobileRadioStateLocked(elapsedRealtimeMs); 4084 updateWifiStateLocked(null); 4085 } 4086 4087 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) { 4088 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4089 } 4090 4091 @Override public int getScreenOnCount(int which) { 4092 return mScreenOnTimer.getCountLocked(which); 4093 } 4094 4095 @Override public long getScreenBrightnessTime(int brightnessBin, 4096 long elapsedRealtimeUs, int which) { 4097 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked( 4098 elapsedRealtimeUs, which); 4099 } 4100 4101 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) { 4102 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4103 } 4104 4105 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) { 4106 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4107 } 4108 4109 @Override public int getPowerSaveModeEnabledCount(int which) { 4110 return mPowerSaveModeEnabledTimer.getCountLocked(which); 4111 } 4112 4113 @Override public long getDeviceIdleModeEnabledTime(long elapsedRealtimeUs, int which) { 4114 return mDeviceIdleModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4115 } 4116 4117 @Override public int getDeviceIdleModeEnabledCount(int which) { 4118 return mDeviceIdleModeEnabledTimer.getCountLocked(which); 4119 } 4120 4121 @Override public long getDeviceIdlingTime(long elapsedRealtimeUs, int which) { 4122 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4123 } 4124 4125 @Override public int getDeviceIdlingCount(int which) { 4126 return mDeviceIdlingTimer.getCountLocked(which); 4127 } 4128 4129 @Override public int getNumConnectivityChange(int which) { 4130 int val = mNumConnectivityChange; 4131 if (which == STATS_CURRENT) { 4132 val -= mLoadedNumConnectivityChange; 4133 } else if (which == STATS_SINCE_UNPLUGGED) { 4134 val -= mUnpluggedNumConnectivityChange; 4135 } 4136 return val; 4137 } 4138 4139 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) { 4140 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4141 } 4142 4143 @Override public int getPhoneOnCount(int which) { 4144 return mPhoneOnTimer.getCountLocked(which); 4145 } 4146 4147 @Override public long getPhoneSignalStrengthTime(int strengthBin, 4148 long elapsedRealtimeUs, int which) { 4149 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked( 4150 elapsedRealtimeUs, which); 4151 } 4152 4153 @Override public long getPhoneSignalScanningTime( 4154 long elapsedRealtimeUs, int which) { 4155 return mPhoneSignalScanningTimer.getTotalTimeLocked( 4156 elapsedRealtimeUs, which); 4157 } 4158 4159 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) { 4160 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which); 4161 } 4162 4163 @Override public long getPhoneDataConnectionTime(int dataType, 4164 long elapsedRealtimeUs, int which) { 4165 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked( 4166 elapsedRealtimeUs, which); 4167 } 4168 4169 @Override public int getPhoneDataConnectionCount(int dataType, int which) { 4170 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which); 4171 } 4172 4173 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) { 4174 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4175 } 4176 4177 @Override public int getMobileRadioActiveCount(int which) { 4178 return mMobileRadioActiveTimer.getCountLocked(which); 4179 } 4180 4181 @Override public long getMobileRadioActiveAdjustedTime(int which) { 4182 return mMobileRadioActiveAdjustedTime.getCountLocked(which); 4183 } 4184 4185 @Override public long getMobileRadioActiveUnknownTime(int which) { 4186 return mMobileRadioActiveUnknownTime.getCountLocked(which); 4187 } 4188 4189 @Override public int getMobileRadioActiveUnknownCount(int which) { 4190 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which); 4191 } 4192 4193 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) { 4194 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4195 } 4196 4197 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) { 4198 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4199 } 4200 4201 @Override public long getWifiStateTime(int wifiState, 4202 long elapsedRealtimeUs, int which) { 4203 return mWifiStateTimer[wifiState].getTotalTimeLocked( 4204 elapsedRealtimeUs, which); 4205 } 4206 4207 @Override public int getWifiStateCount(int wifiState, int which) { 4208 return mWifiStateTimer[wifiState].getCountLocked(which); 4209 } 4210 4211 @Override public long getWifiSupplStateTime(int state, 4212 long elapsedRealtimeUs, int which) { 4213 return mWifiSupplStateTimer[state].getTotalTimeLocked( 4214 elapsedRealtimeUs, which); 4215 } 4216 4217 @Override public int getWifiSupplStateCount(int state, int which) { 4218 return mWifiSupplStateTimer[state].getCountLocked(which); 4219 } 4220 4221 @Override public long getWifiSignalStrengthTime(int strengthBin, 4222 long elapsedRealtimeUs, int which) { 4223 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked( 4224 elapsedRealtimeUs, which); 4225 } 4226 4227 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) { 4228 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which); 4229 } 4230 4231 @Override public boolean hasBluetoothActivityReporting() { 4232 return mHasBluetoothEnergyReporting; 4233 } 4234 4235 @Override public long getBluetoothControllerActivity(int type, int which) { 4236 if (type >= 0 && type < mBluetoothActivityCounters.length) { 4237 return mBluetoothActivityCounters[type].getCountLocked(which); 4238 } 4239 return 0; 4240 } 4241 4242 @Override public boolean hasWifiActivityReporting() { 4243 return mHasWifiEnergyReporting; 4244 } 4245 4246 @Override public long getWifiControllerActivity(int type, int which) { 4247 if (type >= 0 && type < mWifiActivityCounters.length) { 4248 return mWifiActivityCounters[type].getCountLocked(which); 4249 } 4250 return 0; 4251 } 4252 4253 @Override 4254 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) { 4255 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4256 } 4257 4258 @Override 4259 public long getFlashlightOnCount(int which) { 4260 return mFlashlightOnTimer.getCountLocked(which); 4261 } 4262 4263 @Override 4264 public long getCameraOnTime(long elapsedRealtimeUs, int which) { 4265 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4266 } 4267 4268 @Override 4269 public long getNetworkActivityBytes(int type, int which) { 4270 if (type >= 0 && type < mNetworkByteActivityCounters.length) { 4271 return mNetworkByteActivityCounters[type].getCountLocked(which); 4272 } else { 4273 return 0; 4274 } 4275 } 4276 4277 @Override 4278 public long getNetworkActivityPackets(int type, int which) { 4279 if (type >= 0 && type < mNetworkPacketActivityCounters.length) { 4280 return mNetworkPacketActivityCounters[type].getCountLocked(which); 4281 } else { 4282 return 0; 4283 } 4284 } 4285 4286 boolean isStartClockTimeValid() { 4287 return mStartClockTime > 365*24*60*60*1000L; 4288 } 4289 4290 @Override public long getStartClockTime() { 4291 if (!isStartClockTimeValid()) { 4292 // If the last clock time we got was very small, then we hadn't had a real 4293 // time yet, so try to get it again. 4294 mStartClockTime = System.currentTimeMillis(); 4295 if (isStartClockTimeValid()) { 4296 recordCurrentTimeChangeLocked(mStartClockTime, SystemClock.elapsedRealtime(), 4297 SystemClock.uptimeMillis()); 4298 } 4299 } 4300 return mStartClockTime; 4301 } 4302 4303 @Override public String getStartPlatformVersion() { 4304 return mStartPlatformVersion; 4305 } 4306 4307 @Override public String getEndPlatformVersion() { 4308 return mEndPlatformVersion; 4309 } 4310 4311 @Override public int getParcelVersion() { 4312 return VERSION; 4313 } 4314 4315 @Override public boolean getIsOnBattery() { 4316 return mOnBattery; 4317 } 4318 4319 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() { 4320 return mUidStats; 4321 } 4322 4323 /** 4324 * The statistics associated with a particular uid. 4325 */ 4326 public final class Uid extends BatteryStats.Uid { 4327 4328 final int mUid; 4329 4330 boolean mWifiRunning; 4331 StopwatchTimer mWifiRunningTimer; 4332 4333 boolean mFullWifiLockOut; 4334 StopwatchTimer mFullWifiLockTimer; 4335 4336 boolean mWifiScanStarted; 4337 StopwatchTimer mWifiScanTimer; 4338 4339 static final int NO_BATCHED_SCAN_STARTED = -1; 4340 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED; 4341 StopwatchTimer[] mWifiBatchedScanTimer; 4342 4343 boolean mWifiMulticastEnabled; 4344 StopwatchTimer mWifiMulticastTimer; 4345 4346 StopwatchTimer mAudioTurnedOnTimer; 4347 StopwatchTimer mVideoTurnedOnTimer; 4348 StopwatchTimer mFlashlightTurnedOnTimer; 4349 StopwatchTimer mCameraTurnedOnTimer; 4350 4351 4352 StopwatchTimer mForegroundActivityTimer; 4353 4354 static final int PROCESS_STATE_NONE = NUM_PROCESS_STATE; 4355 int mProcessState = PROCESS_STATE_NONE; 4356 StopwatchTimer[] mProcessStateTimer; 4357 4358 BatchTimer mVibratorOnTimer; 4359 4360 Counter[] mUserActivityCounters; 4361 4362 LongSamplingCounter[] mNetworkByteActivityCounters; 4363 LongSamplingCounter[] mNetworkPacketActivityCounters; 4364 LongSamplingCounter mMobileRadioActiveTime; 4365 LongSamplingCounter mMobileRadioActiveCount; 4366 4367 /** 4368 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode. 4369 */ 4370 LongSamplingCounter[] mWifiControllerTime = 4371 new LongSamplingCounter[NUM_CONTROLLER_ACTIVITY_TYPES]; 4372 4373 /** 4374 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode. 4375 */ 4376 LongSamplingCounter[] mBluetoothControllerTime = 4377 new LongSamplingCounter[NUM_CONTROLLER_ACTIVITY_TYPES]; 4378 4379 /** 4380 * The CPU times we had at the last history details update. 4381 */ 4382 long mLastStepUserTime; 4383 long mLastStepSystemTime; 4384 long mCurStepUserTime; 4385 long mCurStepSystemTime; 4386 4387 LongSamplingCounter mUserCpuTime = new LongSamplingCounter(mOnBatteryTimeBase); 4388 LongSamplingCounter mSystemCpuTime = new LongSamplingCounter(mOnBatteryTimeBase); 4389 LongSamplingCounter[] mSpeedBins; 4390 4391 /** 4392 * The statistics we have collected for this uid's wake locks. 4393 */ 4394 final OverflowArrayMap<Wakelock> mWakelockStats = new OverflowArrayMap<Wakelock>() { 4395 @Override public Wakelock instantiateObject() { return new Wakelock(); } 4396 }; 4397 4398 /** 4399 * The statistics we have collected for this uid's syncs. 4400 */ 4401 final OverflowArrayMap<StopwatchTimer> mSyncStats = new OverflowArrayMap<StopwatchTimer>() { 4402 @Override public StopwatchTimer instantiateObject() { 4403 return new StopwatchTimer(Uid.this, SYNC, null, mOnBatteryTimeBase); 4404 } 4405 }; 4406 4407 /** 4408 * The statistics we have collected for this uid's jobs. 4409 */ 4410 final OverflowArrayMap<StopwatchTimer> mJobStats = new OverflowArrayMap<StopwatchTimer>() { 4411 @Override public StopwatchTimer instantiateObject() { 4412 return new StopwatchTimer(Uid.this, JOB, null, mOnBatteryTimeBase); 4413 } 4414 }; 4415 4416 /** 4417 * The statistics we have collected for this uid's sensor activations. 4418 */ 4419 final SparseArray<Sensor> mSensorStats = new SparseArray<>(); 4420 4421 /** 4422 * The statistics we have collected for this uid's processes. 4423 */ 4424 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>(); 4425 4426 /** 4427 * The statistics we have collected for this uid's processes. 4428 */ 4429 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>(); 4430 4431 /** 4432 * The transient wake stats we have collected for this uid's pids. 4433 */ 4434 final SparseArray<Pid> mPids = new SparseArray<>(); 4435 4436 public Uid(int uid) { 4437 mUid = uid; 4438 mWifiRunningTimer = new StopwatchTimer(Uid.this, WIFI_RUNNING, 4439 mWifiRunningTimers, mOnBatteryTimeBase); 4440 mFullWifiLockTimer = new StopwatchTimer(Uid.this, FULL_WIFI_LOCK, 4441 mFullWifiLockTimers, mOnBatteryTimeBase); 4442 mWifiScanTimer = new StopwatchTimer(Uid.this, WIFI_SCAN, 4443 mWifiScanTimers, mOnBatteryTimeBase); 4444 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS]; 4445 mWifiMulticastTimer = new StopwatchTimer(Uid.this, WIFI_MULTICAST_ENABLED, 4446 mWifiMulticastTimers, mOnBatteryTimeBase); 4447 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE]; 4448 mSpeedBins = new LongSamplingCounter[getCpuSpeedSteps()]; 4449 } 4450 4451 @Override 4452 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() { 4453 return mWakelockStats.getMap(); 4454 } 4455 4456 @Override 4457 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() { 4458 return mSyncStats.getMap(); 4459 } 4460 4461 @Override 4462 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() { 4463 return mJobStats.getMap(); 4464 } 4465 4466 @Override 4467 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() { 4468 return mSensorStats; 4469 } 4470 4471 @Override 4472 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() { 4473 return mProcessStats; 4474 } 4475 4476 @Override 4477 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() { 4478 return mPackageStats; 4479 } 4480 4481 @Override 4482 public int getUid() { 4483 return mUid; 4484 } 4485 4486 @Override 4487 public void noteWifiRunningLocked(long elapsedRealtimeMs) { 4488 if (!mWifiRunning) { 4489 mWifiRunning = true; 4490 if (mWifiRunningTimer == null) { 4491 mWifiRunningTimer = new StopwatchTimer(Uid.this, WIFI_RUNNING, 4492 mWifiRunningTimers, mOnBatteryTimeBase); 4493 } 4494 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs); 4495 } 4496 } 4497 4498 @Override 4499 public void noteWifiStoppedLocked(long elapsedRealtimeMs) { 4500 if (mWifiRunning) { 4501 mWifiRunning = false; 4502 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs); 4503 } 4504 } 4505 4506 @Override 4507 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) { 4508 if (!mFullWifiLockOut) { 4509 mFullWifiLockOut = true; 4510 if (mFullWifiLockTimer == null) { 4511 mFullWifiLockTimer = new StopwatchTimer(Uid.this, FULL_WIFI_LOCK, 4512 mFullWifiLockTimers, mOnBatteryTimeBase); 4513 } 4514 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs); 4515 } 4516 } 4517 4518 @Override 4519 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) { 4520 if (mFullWifiLockOut) { 4521 mFullWifiLockOut = false; 4522 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs); 4523 } 4524 } 4525 4526 @Override 4527 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) { 4528 if (!mWifiScanStarted) { 4529 mWifiScanStarted = true; 4530 if (mWifiScanTimer == null) { 4531 mWifiScanTimer = new StopwatchTimer(Uid.this, WIFI_SCAN, 4532 mWifiScanTimers, mOnBatteryTimeBase); 4533 } 4534 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs); 4535 } 4536 } 4537 4538 @Override 4539 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) { 4540 if (mWifiScanStarted) { 4541 mWifiScanStarted = false; 4542 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs); 4543 } 4544 } 4545 4546 @Override 4547 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) { 4548 int bin = 0; 4549 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) { 4550 csph = csph >> 3; 4551 bin++; 4552 } 4553 4554 if (mWifiBatchedScanBinStarted == bin) return; 4555 4556 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) { 4557 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted]. 4558 stopRunningLocked(elapsedRealtimeMs); 4559 } 4560 mWifiBatchedScanBinStarted = bin; 4561 if (mWifiBatchedScanTimer[bin] == null) { 4562 makeWifiBatchedScanBin(bin, null); 4563 } 4564 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs); 4565 } 4566 4567 @Override 4568 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) { 4569 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) { 4570 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted]. 4571 stopRunningLocked(elapsedRealtimeMs); 4572 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED; 4573 } 4574 } 4575 4576 @Override 4577 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) { 4578 if (!mWifiMulticastEnabled) { 4579 mWifiMulticastEnabled = true; 4580 if (mWifiMulticastTimer == null) { 4581 mWifiMulticastTimer = new StopwatchTimer(Uid.this, WIFI_MULTICAST_ENABLED, 4582 mWifiMulticastTimers, mOnBatteryTimeBase); 4583 } 4584 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs); 4585 } 4586 } 4587 4588 @Override 4589 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) { 4590 if (mWifiMulticastEnabled) { 4591 mWifiMulticastEnabled = false; 4592 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs); 4593 } 4594 } 4595 4596 public void noteWifiControllerActivityLocked(int type, long timeMs) { 4597 if (mWifiControllerTime[type] == null) { 4598 mWifiControllerTime[type] = new LongSamplingCounter(mOnBatteryTimeBase); 4599 } 4600 mWifiControllerTime[type].addCountLocked(timeMs); 4601 } 4602 4603 public StopwatchTimer createAudioTurnedOnTimerLocked() { 4604 if (mAudioTurnedOnTimer == null) { 4605 mAudioTurnedOnTimer = new StopwatchTimer(Uid.this, AUDIO_TURNED_ON, 4606 mAudioTurnedOnTimers, mOnBatteryTimeBase); 4607 } 4608 return mAudioTurnedOnTimer; 4609 } 4610 4611 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) { 4612 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs); 4613 } 4614 4615 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) { 4616 if (mAudioTurnedOnTimer != null) { 4617 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs); 4618 } 4619 } 4620 4621 public void noteResetAudioLocked(long elapsedRealtimeMs) { 4622 if (mAudioTurnedOnTimer != null) { 4623 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs); 4624 } 4625 } 4626 4627 public StopwatchTimer createVideoTurnedOnTimerLocked() { 4628 if (mVideoTurnedOnTimer == null) { 4629 mVideoTurnedOnTimer = new StopwatchTimer(Uid.this, VIDEO_TURNED_ON, 4630 mVideoTurnedOnTimers, mOnBatteryTimeBase); 4631 } 4632 return mVideoTurnedOnTimer; 4633 } 4634 4635 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) { 4636 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs); 4637 } 4638 4639 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) { 4640 if (mVideoTurnedOnTimer != null) { 4641 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs); 4642 } 4643 } 4644 4645 public void noteResetVideoLocked(long elapsedRealtimeMs) { 4646 if (mVideoTurnedOnTimer != null) { 4647 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs); 4648 } 4649 } 4650 4651 public StopwatchTimer createFlashlightTurnedOnTimerLocked() { 4652 if (mFlashlightTurnedOnTimer == null) { 4653 mFlashlightTurnedOnTimer = new StopwatchTimer(Uid.this, FLASHLIGHT_TURNED_ON, 4654 mFlashlightTurnedOnTimers, mOnBatteryTimeBase); 4655 } 4656 return mFlashlightTurnedOnTimer; 4657 } 4658 4659 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) { 4660 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs); 4661 } 4662 4663 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) { 4664 if (mFlashlightTurnedOnTimer != null) { 4665 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs); 4666 } 4667 } 4668 4669 public void noteResetFlashlightLocked(long elapsedRealtimeMs) { 4670 if (mFlashlightTurnedOnTimer != null) { 4671 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs); 4672 } 4673 } 4674 4675 public StopwatchTimer createCameraTurnedOnTimerLocked() { 4676 if (mCameraTurnedOnTimer == null) { 4677 mCameraTurnedOnTimer = new StopwatchTimer(Uid.this, CAMERA_TURNED_ON, 4678 mCameraTurnedOnTimers, mOnBatteryTimeBase); 4679 } 4680 return mCameraTurnedOnTimer; 4681 } 4682 4683 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) { 4684 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs); 4685 } 4686 4687 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) { 4688 if (mCameraTurnedOnTimer != null) { 4689 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs); 4690 } 4691 } 4692 4693 public void noteResetCameraLocked(long elapsedRealtimeMs) { 4694 if (mCameraTurnedOnTimer != null) { 4695 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs); 4696 } 4697 } 4698 4699 public StopwatchTimer createForegroundActivityTimerLocked() { 4700 if (mForegroundActivityTimer == null) { 4701 mForegroundActivityTimer = new StopwatchTimer( 4702 Uid.this, FOREGROUND_ACTIVITY, null, mOnBatteryTimeBase); 4703 } 4704 return mForegroundActivityTimer; 4705 } 4706 4707 @Override 4708 public void noteActivityResumedLocked(long elapsedRealtimeMs) { 4709 // We always start, since we want multiple foreground PIDs to nest 4710 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs); 4711 } 4712 4713 @Override 4714 public void noteActivityPausedLocked(long elapsedRealtimeMs) { 4715 if (mForegroundActivityTimer != null) { 4716 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs); 4717 } 4718 } 4719 4720 void updateUidProcessStateLocked(int state, long elapsedRealtimeMs) { 4721 if (mProcessState == state) return; 4722 4723 if (mProcessState != PROCESS_STATE_NONE) { 4724 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs); 4725 } 4726 mProcessState = state; 4727 if (state != PROCESS_STATE_NONE) { 4728 if (mProcessStateTimer[state] == null) { 4729 makeProcessState(state, null); 4730 } 4731 mProcessStateTimer[state].startRunningLocked(elapsedRealtimeMs); 4732 } 4733 } 4734 4735 public BatchTimer createVibratorOnTimerLocked() { 4736 if (mVibratorOnTimer == null) { 4737 mVibratorOnTimer = new BatchTimer(Uid.this, VIBRATOR_ON, mOnBatteryTimeBase); 4738 } 4739 return mVibratorOnTimer; 4740 } 4741 4742 public void noteVibratorOnLocked(long durationMillis) { 4743 createVibratorOnTimerLocked().addDuration(BatteryStatsImpl.this, durationMillis); 4744 } 4745 4746 public void noteVibratorOffLocked() { 4747 if (mVibratorOnTimer != null) { 4748 mVibratorOnTimer.abortLastDuration(BatteryStatsImpl.this); 4749 } 4750 } 4751 4752 @Override 4753 public long getWifiRunningTime(long elapsedRealtimeUs, int which) { 4754 if (mWifiRunningTimer == null) { 4755 return 0; 4756 } 4757 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4758 } 4759 4760 @Override 4761 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) { 4762 if (mFullWifiLockTimer == null) { 4763 return 0; 4764 } 4765 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4766 } 4767 4768 @Override 4769 public long getWifiScanTime(long elapsedRealtimeUs, int which) { 4770 if (mWifiScanTimer == null) { 4771 return 0; 4772 } 4773 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4774 } 4775 4776 @Override 4777 public int getWifiScanCount(int which) { 4778 if (mWifiScanTimer == null) { 4779 return 0; 4780 } 4781 return mWifiScanTimer.getCountLocked(which); 4782 } 4783 4784 @Override 4785 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) { 4786 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0; 4787 if (mWifiBatchedScanTimer[csphBin] == null) { 4788 return 0; 4789 } 4790 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which); 4791 } 4792 4793 @Override 4794 public int getWifiBatchedScanCount(int csphBin, int which) { 4795 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0; 4796 if (mWifiBatchedScanTimer[csphBin] == null) { 4797 return 0; 4798 } 4799 return mWifiBatchedScanTimer[csphBin].getCountLocked(which); 4800 } 4801 4802 @Override 4803 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) { 4804 if (mWifiMulticastTimer == null) { 4805 return 0; 4806 } 4807 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which); 4808 } 4809 4810 @Override 4811 public Timer getAudioTurnedOnTimer() { 4812 return mAudioTurnedOnTimer; 4813 } 4814 4815 @Override 4816 public Timer getVideoTurnedOnTimer() { 4817 return mVideoTurnedOnTimer; 4818 } 4819 4820 @Override 4821 public Timer getFlashlightTurnedOnTimer() { 4822 return mFlashlightTurnedOnTimer; 4823 } 4824 4825 @Override 4826 public Timer getCameraTurnedOnTimer() { 4827 return mCameraTurnedOnTimer; 4828 } 4829 4830 @Override 4831 public Timer getForegroundActivityTimer() { 4832 return mForegroundActivityTimer; 4833 } 4834 4835 void makeProcessState(int i, Parcel in) { 4836 if (i < 0 || i >= NUM_PROCESS_STATE) return; 4837 4838 if (in == null) { 4839 mProcessStateTimer[i] = new StopwatchTimer(this, PROCESS_STATE, null, 4840 mOnBatteryTimeBase); 4841 } else { 4842 mProcessStateTimer[i] = new StopwatchTimer(this, PROCESS_STATE, null, 4843 mOnBatteryTimeBase, in); 4844 } 4845 } 4846 4847 @Override 4848 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) { 4849 if (state < 0 || state >= NUM_PROCESS_STATE) return 0; 4850 if (mProcessStateTimer[state] == null) { 4851 return 0; 4852 } 4853 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which); 4854 } 4855 4856 @Override 4857 public Timer getVibratorOnTimer() { 4858 return mVibratorOnTimer; 4859 } 4860 4861 @Override 4862 public void noteUserActivityLocked(int type) { 4863 if (mUserActivityCounters == null) { 4864 initUserActivityLocked(); 4865 } 4866 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) { 4867 mUserActivityCounters[type].stepAtomic(); 4868 } else { 4869 Slog.w(TAG, "Unknown user activity type " + type + " was specified.", 4870 new Throwable()); 4871 } 4872 } 4873 4874 @Override 4875 public boolean hasUserActivity() { 4876 return mUserActivityCounters != null; 4877 } 4878 4879 @Override 4880 public int getUserActivityCount(int type, int which) { 4881 if (mUserActivityCounters == null) { 4882 return 0; 4883 } 4884 return mUserActivityCounters[type].getCountLocked(which); 4885 } 4886 4887 void makeWifiBatchedScanBin(int i, Parcel in) { 4888 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return; 4889 4890 ArrayList<StopwatchTimer> collected = mWifiBatchedScanTimers.get(i); 4891 if (collected == null) { 4892 collected = new ArrayList<StopwatchTimer>(); 4893 mWifiBatchedScanTimers.put(i, collected); 4894 } 4895 if (in == null) { 4896 mWifiBatchedScanTimer[i] = new StopwatchTimer(this, WIFI_BATCHED_SCAN, collected, 4897 mOnBatteryTimeBase); 4898 } else { 4899 mWifiBatchedScanTimer[i] = new StopwatchTimer(this, WIFI_BATCHED_SCAN, collected, 4900 mOnBatteryTimeBase, in); 4901 } 4902 } 4903 4904 4905 void initUserActivityLocked() { 4906 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES]; 4907 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) { 4908 mUserActivityCounters[i] = new Counter(mOnBatteryTimeBase); 4909 } 4910 } 4911 4912 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) { 4913 if (mNetworkByteActivityCounters == null) { 4914 initNetworkActivityLocked(); 4915 } 4916 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) { 4917 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes); 4918 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets); 4919 } else { 4920 Slog.w(TAG, "Unknown network activity type " + type + " was specified.", 4921 new Throwable()); 4922 } 4923 } 4924 4925 void noteMobileRadioActiveTimeLocked(long batteryUptime) { 4926 if (mNetworkByteActivityCounters == null) { 4927 initNetworkActivityLocked(); 4928 } 4929 mMobileRadioActiveTime.addCountLocked(batteryUptime); 4930 mMobileRadioActiveCount.addCountLocked(1); 4931 } 4932 4933 @Override 4934 public boolean hasNetworkActivity() { 4935 return mNetworkByteActivityCounters != null; 4936 } 4937 4938 @Override 4939 public long getNetworkActivityBytes(int type, int which) { 4940 if (mNetworkByteActivityCounters != null && type >= 0 4941 && type < mNetworkByteActivityCounters.length) { 4942 return mNetworkByteActivityCounters[type].getCountLocked(which); 4943 } else { 4944 return 0; 4945 } 4946 } 4947 4948 @Override 4949 public long getNetworkActivityPackets(int type, int which) { 4950 if (mNetworkPacketActivityCounters != null && type >= 0 4951 && type < mNetworkPacketActivityCounters.length) { 4952 return mNetworkPacketActivityCounters[type].getCountLocked(which); 4953 } else { 4954 return 0; 4955 } 4956 } 4957 4958 @Override 4959 public long getMobileRadioActiveTime(int which) { 4960 return mMobileRadioActiveTime != null 4961 ? mMobileRadioActiveTime.getCountLocked(which) : 0; 4962 } 4963 4964 @Override 4965 public int getMobileRadioActiveCount(int which) { 4966 return mMobileRadioActiveCount != null 4967 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0; 4968 } 4969 4970 @Override 4971 public long getUserCpuTimeUs(int which) { 4972 return mUserCpuTime.getCountLocked(which); 4973 } 4974 4975 @Override 4976 public long getSystemCpuTimeUs(int which) { 4977 return mSystemCpuTime.getCountLocked(which); 4978 } 4979 4980 @Override 4981 public long getTimeAtCpuSpeed(int step, int which) { 4982 if (step >= 0 && step < mSpeedBins.length) { 4983 if (mSpeedBins[step] != null) { 4984 return mSpeedBins[step].getCountLocked(which); 4985 } 4986 } 4987 return 0; 4988 } 4989 4990 @Override 4991 public long getWifiControllerActivity(int type, int which) { 4992 if (type >= 0 && type < NUM_CONTROLLER_ACTIVITY_TYPES && 4993 mWifiControllerTime[type] != null) { 4994 return mWifiControllerTime[type].getCountLocked(which); 4995 } 4996 return 0; 4997 } 4998 4999 void initNetworkActivityLocked() { 5000 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES]; 5001 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES]; 5002 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 5003 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase); 5004 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase); 5005 } 5006 mMobileRadioActiveTime = new LongSamplingCounter(mOnBatteryTimeBase); 5007 mMobileRadioActiveCount = new LongSamplingCounter(mOnBatteryTimeBase); 5008 } 5009 5010 /** 5011 * Clear all stats for this uid. Returns true if the uid is completely 5012 * inactive so can be dropped. 5013 */ 5014 boolean reset() { 5015 boolean active = false; 5016 5017 if (mWifiRunningTimer != null) { 5018 active |= !mWifiRunningTimer.reset(false); 5019 active |= mWifiRunning; 5020 } 5021 if (mFullWifiLockTimer != null) { 5022 active |= !mFullWifiLockTimer.reset(false); 5023 active |= mFullWifiLockOut; 5024 } 5025 if (mWifiScanTimer != null) { 5026 active |= !mWifiScanTimer.reset(false); 5027 active |= mWifiScanStarted; 5028 } 5029 if (mWifiBatchedScanTimer != null) { 5030 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) { 5031 if (mWifiBatchedScanTimer[i] != null) { 5032 active |= !mWifiBatchedScanTimer[i].reset(false); 5033 } 5034 } 5035 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED); 5036 } 5037 if (mWifiMulticastTimer != null) { 5038 active |= !mWifiMulticastTimer.reset(false); 5039 active |= mWifiMulticastEnabled; 5040 } 5041 if (mAudioTurnedOnTimer != null) { 5042 active |= !mAudioTurnedOnTimer.reset(false); 5043 } 5044 if (mVideoTurnedOnTimer != null) { 5045 active |= !mVideoTurnedOnTimer.reset(false); 5046 } 5047 if (mFlashlightTurnedOnTimer != null) { 5048 active |= !mFlashlightTurnedOnTimer.reset(false); 5049 } 5050 if (mCameraTurnedOnTimer != null) { 5051 active |= !mCameraTurnedOnTimer.reset(false); 5052 } 5053 if (mForegroundActivityTimer != null) { 5054 active |= !mForegroundActivityTimer.reset(false); 5055 } 5056 if (mProcessStateTimer != null) { 5057 for (int i = 0; i < NUM_PROCESS_STATE; i++) { 5058 if (mProcessStateTimer[i] != null) { 5059 active |= !mProcessStateTimer[i].reset(false); 5060 } 5061 } 5062 active |= (mProcessState != PROCESS_STATE_NONE); 5063 } 5064 if (mVibratorOnTimer != null) { 5065 if (mVibratorOnTimer.reset(false)) { 5066 mVibratorOnTimer.detach(); 5067 mVibratorOnTimer = null; 5068 } else { 5069 active = true; 5070 } 5071 } 5072 5073 if (mUserActivityCounters != null) { 5074 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) { 5075 mUserActivityCounters[i].reset(false); 5076 } 5077 } 5078 5079 if (mNetworkByteActivityCounters != null) { 5080 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 5081 mNetworkByteActivityCounters[i].reset(false); 5082 mNetworkPacketActivityCounters[i].reset(false); 5083 } 5084 mMobileRadioActiveTime.reset(false); 5085 mMobileRadioActiveCount.reset(false); 5086 } 5087 5088 for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 5089 if (mWifiControllerTime[i] != null) { 5090 mWifiControllerTime[i].reset(false); 5091 } 5092 5093 if (mBluetoothControllerTime[i] != null) { 5094 mBluetoothControllerTime[i].reset(false); 5095 } 5096 } 5097 5098 mUserCpuTime.reset(false); 5099 mSystemCpuTime.reset(false); 5100 for (int i = 0; i < mSpeedBins.length; i++) { 5101 LongSamplingCounter c = mSpeedBins[i]; 5102 if (c != null) { 5103 c.reset(false); 5104 } 5105 } 5106 5107 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap(); 5108 for (int iw=wakeStats.size()-1; iw>=0; iw--) { 5109 Wakelock wl = wakeStats.valueAt(iw); 5110 if (wl.reset()) { 5111 wakeStats.removeAt(iw); 5112 } else { 5113 active = true; 5114 } 5115 } 5116 mWakelockStats.cleanup(); 5117 final ArrayMap<String, StopwatchTimer> syncStats = mSyncStats.getMap(); 5118 for (int is=syncStats.size()-1; is>=0; is--) { 5119 StopwatchTimer timer = syncStats.valueAt(is); 5120 if (timer.reset(false)) { 5121 syncStats.removeAt(is); 5122 timer.detach(); 5123 } else { 5124 active = true; 5125 } 5126 } 5127 mSyncStats.cleanup(); 5128 final ArrayMap<String, StopwatchTimer> jobStats = mJobStats.getMap(); 5129 for (int ij=jobStats.size()-1; ij>=0; ij--) { 5130 StopwatchTimer timer = jobStats.valueAt(ij); 5131 if (timer.reset(false)) { 5132 jobStats.removeAt(ij); 5133 timer.detach(); 5134 } else { 5135 active = true; 5136 } 5137 } 5138 mJobStats.cleanup(); 5139 for (int ise=mSensorStats.size()-1; ise>=0; ise--) { 5140 Sensor s = mSensorStats.valueAt(ise); 5141 if (s.reset()) { 5142 mSensorStats.removeAt(ise); 5143 } else { 5144 active = true; 5145 } 5146 } 5147 for (int ip=mProcessStats.size()-1; ip>=0; ip--) { 5148 Proc proc = mProcessStats.valueAt(ip); 5149 if (proc.mProcessState == PROCESS_STATE_NONE) { 5150 proc.detach(); 5151 mProcessStats.removeAt(ip); 5152 } else { 5153 proc.reset(); 5154 active = true; 5155 } 5156 } 5157 if (mPids.size() > 0) { 5158 for (int i=mPids.size()-1; i>=0; i--) { 5159 Pid pid = mPids.valueAt(i); 5160 if (pid.mWakeNesting > 0) { 5161 active = true; 5162 } else { 5163 mPids.removeAt(i); 5164 } 5165 } 5166 } 5167 if (mPackageStats.size() > 0) { 5168 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator(); 5169 while (it.hasNext()) { 5170 Map.Entry<String, Pkg> pkgEntry = it.next(); 5171 Pkg p = pkgEntry.getValue(); 5172 p.detach(); 5173 if (p.mServiceStats.size() > 0) { 5174 Iterator<Map.Entry<String, Pkg.Serv>> it2 5175 = p.mServiceStats.entrySet().iterator(); 5176 while (it2.hasNext()) { 5177 Map.Entry<String, Pkg.Serv> servEntry = it2.next(); 5178 servEntry.getValue().detach(); 5179 } 5180 } 5181 } 5182 mPackageStats.clear(); 5183 } 5184 5185 mLastStepUserTime = mLastStepSystemTime = 0; 5186 mCurStepUserTime = mCurStepSystemTime = 0; 5187 5188 if (!active) { 5189 if (mWifiRunningTimer != null) { 5190 mWifiRunningTimer.detach(); 5191 } 5192 if (mFullWifiLockTimer != null) { 5193 mFullWifiLockTimer.detach(); 5194 } 5195 if (mWifiScanTimer != null) { 5196 mWifiScanTimer.detach(); 5197 } 5198 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) { 5199 if (mWifiBatchedScanTimer[i] != null) { 5200 mWifiBatchedScanTimer[i].detach(); 5201 } 5202 } 5203 if (mWifiMulticastTimer != null) { 5204 mWifiMulticastTimer.detach(); 5205 } 5206 if (mAudioTurnedOnTimer != null) { 5207 mAudioTurnedOnTimer.detach(); 5208 mAudioTurnedOnTimer = null; 5209 } 5210 if (mVideoTurnedOnTimer != null) { 5211 mVideoTurnedOnTimer.detach(); 5212 mVideoTurnedOnTimer = null; 5213 } 5214 if (mFlashlightTurnedOnTimer != null) { 5215 mFlashlightTurnedOnTimer.detach(); 5216 mFlashlightTurnedOnTimer = null; 5217 } 5218 if (mCameraTurnedOnTimer != null) { 5219 mCameraTurnedOnTimer.detach(); 5220 mCameraTurnedOnTimer = null; 5221 } 5222 if (mForegroundActivityTimer != null) { 5223 mForegroundActivityTimer.detach(); 5224 mForegroundActivityTimer = null; 5225 } 5226 if (mUserActivityCounters != null) { 5227 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) { 5228 mUserActivityCounters[i].detach(); 5229 } 5230 } 5231 if (mNetworkByteActivityCounters != null) { 5232 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 5233 mNetworkByteActivityCounters[i].detach(); 5234 mNetworkPacketActivityCounters[i].detach(); 5235 } 5236 } 5237 5238 for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 5239 if (mWifiControllerTime[i] != null) { 5240 mWifiControllerTime[i].detach(); 5241 } 5242 5243 if (mBluetoothControllerTime[i] != null) { 5244 mBluetoothControllerTime[i].detach(); 5245 } 5246 } 5247 mPids.clear(); 5248 5249 mUserCpuTime.detach(); 5250 mSystemCpuTime.detach(); 5251 for (int i = 0; i < mSpeedBins.length; i++) { 5252 LongSamplingCounter c = mSpeedBins[i]; 5253 if (c != null) { 5254 c.detach(); 5255 } 5256 } 5257 } 5258 5259 return !active; 5260 } 5261 5262 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) { 5263 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap(); 5264 int NW = wakeStats.size(); 5265 out.writeInt(NW); 5266 for (int iw=0; iw<NW; iw++) { 5267 out.writeString(wakeStats.keyAt(iw)); 5268 Uid.Wakelock wakelock = wakeStats.valueAt(iw); 5269 wakelock.writeToParcelLocked(out, elapsedRealtimeUs); 5270 } 5271 5272 final ArrayMap<String, StopwatchTimer> syncStats = mSyncStats.getMap(); 5273 int NS = syncStats.size(); 5274 out.writeInt(NS); 5275 for (int is=0; is<NS; is++) { 5276 out.writeString(syncStats.keyAt(is)); 5277 StopwatchTimer timer = syncStats.valueAt(is); 5278 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs); 5279 } 5280 5281 final ArrayMap<String, StopwatchTimer> jobStats = mJobStats.getMap(); 5282 int NJ = jobStats.size(); 5283 out.writeInt(NJ); 5284 for (int ij=0; ij<NJ; ij++) { 5285 out.writeString(jobStats.keyAt(ij)); 5286 StopwatchTimer timer = jobStats.valueAt(ij); 5287 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs); 5288 } 5289 5290 int NSE = mSensorStats.size(); 5291 out.writeInt(NSE); 5292 for (int ise=0; ise<NSE; ise++) { 5293 out.writeInt(mSensorStats.keyAt(ise)); 5294 Uid.Sensor sensor = mSensorStats.valueAt(ise); 5295 sensor.writeToParcelLocked(out, elapsedRealtimeUs); 5296 } 5297 5298 int NP = mProcessStats.size(); 5299 out.writeInt(NP); 5300 for (int ip=0; ip<NP; ip++) { 5301 out.writeString(mProcessStats.keyAt(ip)); 5302 Uid.Proc proc = mProcessStats.valueAt(ip); 5303 proc.writeToParcelLocked(out); 5304 } 5305 5306 out.writeInt(mPackageStats.size()); 5307 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) { 5308 out.writeString(pkgEntry.getKey()); 5309 Uid.Pkg pkg = pkgEntry.getValue(); 5310 pkg.writeToParcelLocked(out); 5311 } 5312 5313 if (mWifiRunningTimer != null) { 5314 out.writeInt(1); 5315 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs); 5316 } else { 5317 out.writeInt(0); 5318 } 5319 if (mFullWifiLockTimer != null) { 5320 out.writeInt(1); 5321 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs); 5322 } else { 5323 out.writeInt(0); 5324 } 5325 if (mWifiScanTimer != null) { 5326 out.writeInt(1); 5327 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs); 5328 } else { 5329 out.writeInt(0); 5330 } 5331 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) { 5332 if (mWifiBatchedScanTimer[i] != null) { 5333 out.writeInt(1); 5334 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs); 5335 } else { 5336 out.writeInt(0); 5337 } 5338 } 5339 if (mWifiMulticastTimer != null) { 5340 out.writeInt(1); 5341 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs); 5342 } else { 5343 out.writeInt(0); 5344 } 5345 5346 if (mAudioTurnedOnTimer != null) { 5347 out.writeInt(1); 5348 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs); 5349 } else { 5350 out.writeInt(0); 5351 } 5352 if (mVideoTurnedOnTimer != null) { 5353 out.writeInt(1); 5354 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs); 5355 } else { 5356 out.writeInt(0); 5357 } 5358 if (mFlashlightTurnedOnTimer != null) { 5359 out.writeInt(1); 5360 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs); 5361 } else { 5362 out.writeInt(0); 5363 } 5364 if (mCameraTurnedOnTimer != null) { 5365 out.writeInt(1); 5366 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs); 5367 } else { 5368 out.writeInt(0); 5369 } 5370 if (mForegroundActivityTimer != null) { 5371 out.writeInt(1); 5372 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs); 5373 } else { 5374 out.writeInt(0); 5375 } 5376 for (int i = 0; i < NUM_PROCESS_STATE; i++) { 5377 if (mProcessStateTimer[i] != null) { 5378 out.writeInt(1); 5379 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs); 5380 } else { 5381 out.writeInt(0); 5382 } 5383 } 5384 if (mVibratorOnTimer != null) { 5385 out.writeInt(1); 5386 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs); 5387 } else { 5388 out.writeInt(0); 5389 } 5390 if (mUserActivityCounters != null) { 5391 out.writeInt(1); 5392 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) { 5393 mUserActivityCounters[i].writeToParcel(out); 5394 } 5395 } else { 5396 out.writeInt(0); 5397 } 5398 if (mNetworkByteActivityCounters != null) { 5399 out.writeInt(1); 5400 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 5401 mNetworkByteActivityCounters[i].writeToParcel(out); 5402 mNetworkPacketActivityCounters[i].writeToParcel(out); 5403 } 5404 mMobileRadioActiveTime.writeToParcel(out); 5405 mMobileRadioActiveCount.writeToParcel(out); 5406 } else { 5407 out.writeInt(0); 5408 } 5409 5410 for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 5411 if (mWifiControllerTime[i] != null) { 5412 out.writeInt(1); 5413 mWifiControllerTime[i].writeToParcel(out); 5414 } else { 5415 out.writeInt(0); 5416 } 5417 } 5418 5419 for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 5420 if (mBluetoothControllerTime[i] != null) { 5421 out.writeInt(1); 5422 mBluetoothControllerTime[i].writeToParcel(out); 5423 } else { 5424 out.writeInt(0); 5425 } 5426 } 5427 5428 mUserCpuTime.writeToParcel(out); 5429 mSystemCpuTime.writeToParcel(out); 5430 5431 out.writeInt(mSpeedBins.length); 5432 for (int i = 0; i < mSpeedBins.length; i++) { 5433 LongSamplingCounter c = mSpeedBins[i]; 5434 if (c != null) { 5435 out.writeInt(1); 5436 c.writeToParcel(out); 5437 } else { 5438 out.writeInt(0); 5439 } 5440 } 5441 } 5442 5443 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) { 5444 int numWakelocks = in.readInt(); 5445 mWakelockStats.clear(); 5446 for (int j = 0; j < numWakelocks; j++) { 5447 String wakelockName = in.readString(); 5448 Uid.Wakelock wakelock = new Wakelock(); 5449 wakelock.readFromParcelLocked(timeBase, screenOffTimeBase, in); 5450 mWakelockStats.add(wakelockName, wakelock); 5451 } 5452 5453 int numSyncs = in.readInt(); 5454 mSyncStats.clear(); 5455 for (int j = 0; j < numSyncs; j++) { 5456 String syncName = in.readString(); 5457 if (in.readInt() != 0) { 5458 mSyncStats.add(syncName, 5459 new StopwatchTimer(Uid.this, SYNC, null, timeBase, in)); 5460 } 5461 } 5462 5463 int numJobs = in.readInt(); 5464 mJobStats.clear(); 5465 for (int j = 0; j < numJobs; j++) { 5466 String jobName = in.readString(); 5467 if (in.readInt() != 0) { 5468 mJobStats.add(jobName, new StopwatchTimer(Uid.this, JOB, null, timeBase, in)); 5469 } 5470 } 5471 5472 int numSensors = in.readInt(); 5473 mSensorStats.clear(); 5474 for (int k = 0; k < numSensors; k++) { 5475 int sensorNumber = in.readInt(); 5476 Uid.Sensor sensor = new Sensor(sensorNumber); 5477 sensor.readFromParcelLocked(mOnBatteryTimeBase, in); 5478 mSensorStats.put(sensorNumber, sensor); 5479 } 5480 5481 int numProcs = in.readInt(); 5482 mProcessStats.clear(); 5483 for (int k = 0; k < numProcs; k++) { 5484 String processName = in.readString(); 5485 Uid.Proc proc = new Proc(processName); 5486 proc.readFromParcelLocked(in); 5487 mProcessStats.put(processName, proc); 5488 } 5489 5490 int numPkgs = in.readInt(); 5491 mPackageStats.clear(); 5492 for (int l = 0; l < numPkgs; l++) { 5493 String packageName = in.readString(); 5494 Uid.Pkg pkg = new Pkg(); 5495 pkg.readFromParcelLocked(in); 5496 mPackageStats.put(packageName, pkg); 5497 } 5498 5499 mWifiRunning = false; 5500 if (in.readInt() != 0) { 5501 mWifiRunningTimer = new StopwatchTimer(Uid.this, WIFI_RUNNING, 5502 mWifiRunningTimers, mOnBatteryTimeBase, in); 5503 } else { 5504 mWifiRunningTimer = null; 5505 } 5506 mFullWifiLockOut = false; 5507 if (in.readInt() != 0) { 5508 mFullWifiLockTimer = new StopwatchTimer(Uid.this, FULL_WIFI_LOCK, 5509 mFullWifiLockTimers, mOnBatteryTimeBase, in); 5510 } else { 5511 mFullWifiLockTimer = null; 5512 } 5513 mWifiScanStarted = false; 5514 if (in.readInt() != 0) { 5515 mWifiScanTimer = new StopwatchTimer(Uid.this, WIFI_SCAN, 5516 mWifiScanTimers, mOnBatteryTimeBase, in); 5517 } else { 5518 mWifiScanTimer = null; 5519 } 5520 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED; 5521 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) { 5522 if (in.readInt() != 0) { 5523 makeWifiBatchedScanBin(i, in); 5524 } else { 5525 mWifiBatchedScanTimer[i] = null; 5526 } 5527 } 5528 mWifiMulticastEnabled = false; 5529 if (in.readInt() != 0) { 5530 mWifiMulticastTimer = new StopwatchTimer(Uid.this, WIFI_MULTICAST_ENABLED, 5531 mWifiMulticastTimers, mOnBatteryTimeBase, in); 5532 } else { 5533 mWifiMulticastTimer = null; 5534 } 5535 if (in.readInt() != 0) { 5536 mAudioTurnedOnTimer = new StopwatchTimer(Uid.this, AUDIO_TURNED_ON, 5537 mAudioTurnedOnTimers, mOnBatteryTimeBase, in); 5538 } else { 5539 mAudioTurnedOnTimer = null; 5540 } 5541 if (in.readInt() != 0) { 5542 mVideoTurnedOnTimer = new StopwatchTimer(Uid.this, VIDEO_TURNED_ON, 5543 mVideoTurnedOnTimers, mOnBatteryTimeBase, in); 5544 } else { 5545 mVideoTurnedOnTimer = null; 5546 } 5547 if (in.readInt() != 0) { 5548 mFlashlightTurnedOnTimer = new StopwatchTimer(Uid.this, FLASHLIGHT_TURNED_ON, 5549 mFlashlightTurnedOnTimers, mOnBatteryTimeBase, in); 5550 } else { 5551 mFlashlightTurnedOnTimer = null; 5552 } 5553 if (in.readInt() != 0) { 5554 mCameraTurnedOnTimer = new StopwatchTimer(Uid.this, CAMERA_TURNED_ON, 5555 mCameraTurnedOnTimers, mOnBatteryTimeBase, in); 5556 } else { 5557 mCameraTurnedOnTimer = null; 5558 } 5559 if (in.readInt() != 0) { 5560 mForegroundActivityTimer = new StopwatchTimer( 5561 Uid.this, FOREGROUND_ACTIVITY, null, mOnBatteryTimeBase, in); 5562 } else { 5563 mForegroundActivityTimer = null; 5564 } 5565 mProcessState = PROCESS_STATE_NONE; 5566 for (int i = 0; i < NUM_PROCESS_STATE; i++) { 5567 if (in.readInt() != 0) { 5568 makeProcessState(i, in); 5569 } else { 5570 mProcessStateTimer[i] = null; 5571 } 5572 } 5573 if (in.readInt() != 0) { 5574 mVibratorOnTimer = new BatchTimer(Uid.this, VIBRATOR_ON, mOnBatteryTimeBase, in); 5575 } else { 5576 mVibratorOnTimer = null; 5577 } 5578 if (in.readInt() != 0) { 5579 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES]; 5580 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) { 5581 mUserActivityCounters[i] = new Counter(mOnBatteryTimeBase, in); 5582 } 5583 } else { 5584 mUserActivityCounters = null; 5585 } 5586 if (in.readInt() != 0) { 5587 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES]; 5588 mNetworkPacketActivityCounters 5589 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES]; 5590 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 5591 mNetworkByteActivityCounters[i] 5592 = new LongSamplingCounter(mOnBatteryTimeBase, in); 5593 mNetworkPacketActivityCounters[i] 5594 = new LongSamplingCounter(mOnBatteryTimeBase, in); 5595 } 5596 mMobileRadioActiveTime = new LongSamplingCounter(mOnBatteryTimeBase, in); 5597 mMobileRadioActiveCount = new LongSamplingCounter(mOnBatteryTimeBase, in); 5598 } else { 5599 mNetworkByteActivityCounters = null; 5600 mNetworkPacketActivityCounters = null; 5601 } 5602 5603 for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 5604 if (in.readInt() != 0) { 5605 mWifiControllerTime[i] = new LongSamplingCounter(mOnBatteryTimeBase, in); 5606 } else { 5607 mWifiControllerTime[i] = null; 5608 } 5609 } 5610 5611 for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 5612 if (in.readInt() != 0) { 5613 mBluetoothControllerTime[i] = new LongSamplingCounter(mOnBatteryTimeBase, in); 5614 } else { 5615 mBluetoothControllerTime[i] = null; 5616 } 5617 } 5618 5619 mUserCpuTime = new LongSamplingCounter(mOnBatteryTimeBase, in); 5620 mSystemCpuTime = new LongSamplingCounter(mOnBatteryTimeBase, in); 5621 5622 int bins = in.readInt(); 5623 int steps = getCpuSpeedSteps(); 5624 mSpeedBins = new LongSamplingCounter[bins >= steps ? bins : steps]; 5625 for (int i = 0; i < bins; i++) { 5626 if (in.readInt() != 0) { 5627 mSpeedBins[i] = new LongSamplingCounter(mOnBatteryTimeBase, in); 5628 } 5629 } 5630 } 5631 5632 /** 5633 * The statistics associated with a particular wake lock. 5634 */ 5635 public final class Wakelock extends BatteryStats.Uid.Wakelock { 5636 /** 5637 * How long (in ms) this uid has been keeping the device partially awake. 5638 */ 5639 StopwatchTimer mTimerPartial; 5640 5641 /** 5642 * How long (in ms) this uid has been keeping the device fully awake. 5643 */ 5644 StopwatchTimer mTimerFull; 5645 5646 /** 5647 * How long (in ms) this uid has had a window keeping the device awake. 5648 */ 5649 StopwatchTimer mTimerWindow; 5650 5651 /** 5652 * How long (in ms) this uid has had a doze wake lock. 5653 */ 5654 StopwatchTimer mTimerDoze; 5655 5656 /** 5657 * Reads a possibly null Timer from a Parcel. The timer is associated with the 5658 * proper timer pool from the given BatteryStatsImpl object. 5659 * 5660 * @param in the Parcel to be read from. 5661 * return a new Timer, or null. 5662 */ 5663 private StopwatchTimer readTimerFromParcel(int type, ArrayList<StopwatchTimer> pool, 5664 TimeBase timeBase, Parcel in) { 5665 if (in.readInt() == 0) { 5666 return null; 5667 } 5668 5669 return new StopwatchTimer(Uid.this, type, pool, timeBase, in); 5670 } 5671 5672 boolean reset() { 5673 boolean wlactive = false; 5674 if (mTimerFull != null) { 5675 wlactive |= !mTimerFull.reset(false); 5676 } 5677 if (mTimerPartial != null) { 5678 wlactive |= !mTimerPartial.reset(false); 5679 } 5680 if (mTimerWindow != null) { 5681 wlactive |= !mTimerWindow.reset(false); 5682 } 5683 if (mTimerDoze != null) { 5684 wlactive |= !mTimerDoze.reset(false); 5685 } 5686 if (!wlactive) { 5687 if (mTimerFull != null) { 5688 mTimerFull.detach(); 5689 mTimerFull = null; 5690 } 5691 if (mTimerPartial != null) { 5692 mTimerPartial.detach(); 5693 mTimerPartial = null; 5694 } 5695 if (mTimerWindow != null) { 5696 mTimerWindow.detach(); 5697 mTimerWindow = null; 5698 } 5699 if (mTimerDoze != null) { 5700 mTimerDoze.detach(); 5701 mTimerDoze = null; 5702 } 5703 } 5704 return !wlactive; 5705 } 5706 5707 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) { 5708 mTimerPartial = readTimerFromParcel(WAKE_TYPE_PARTIAL, 5709 mPartialTimers, screenOffTimeBase, in); 5710 mTimerFull = readTimerFromParcel(WAKE_TYPE_FULL, mFullTimers, timeBase, in); 5711 mTimerWindow = readTimerFromParcel(WAKE_TYPE_WINDOW, mWindowTimers, timeBase, in); 5712 mTimerDoze = readTimerFromParcel(WAKE_TYPE_DOZE, mDozeTimers, timeBase, in); 5713 } 5714 5715 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) { 5716 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs); 5717 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs); 5718 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs); 5719 Timer.writeTimerToParcel(out, mTimerDoze, elapsedRealtimeUs); 5720 } 5721 5722 @Override 5723 public Timer getWakeTime(int type) { 5724 switch (type) { 5725 case WAKE_TYPE_FULL: return mTimerFull; 5726 case WAKE_TYPE_PARTIAL: return mTimerPartial; 5727 case WAKE_TYPE_WINDOW: return mTimerWindow; 5728 case WAKE_TYPE_DOZE: return mTimerDoze; 5729 default: throw new IllegalArgumentException("type = " + type); 5730 } 5731 } 5732 5733 public StopwatchTimer getStopwatchTimer(int type) { 5734 StopwatchTimer t; 5735 switch (type) { 5736 case WAKE_TYPE_PARTIAL: 5737 t = mTimerPartial; 5738 if (t == null) { 5739 t = new StopwatchTimer(Uid.this, WAKE_TYPE_PARTIAL, 5740 mPartialTimers, mOnBatteryScreenOffTimeBase); 5741 mTimerPartial = t; 5742 } 5743 return t; 5744 case WAKE_TYPE_FULL: 5745 t = mTimerFull; 5746 if (t == null) { 5747 t = new StopwatchTimer(Uid.this, WAKE_TYPE_FULL, 5748 mFullTimers, mOnBatteryTimeBase); 5749 mTimerFull = t; 5750 } 5751 return t; 5752 case WAKE_TYPE_WINDOW: 5753 t = mTimerWindow; 5754 if (t == null) { 5755 t = new StopwatchTimer(Uid.this, WAKE_TYPE_WINDOW, 5756 mWindowTimers, mOnBatteryTimeBase); 5757 mTimerWindow = t; 5758 } 5759 return t; 5760 case WAKE_TYPE_DOZE: 5761 t = mTimerDoze; 5762 if (t == null) { 5763 t = new StopwatchTimer(Uid.this, WAKE_TYPE_DOZE, 5764 mDozeTimers, mOnBatteryTimeBase); 5765 mTimerDoze = t; 5766 } 5767 default: 5768 throw new IllegalArgumentException("type=" + type); 5769 } 5770 } 5771 } 5772 5773 public final class Sensor extends BatteryStats.Uid.Sensor { 5774 final int mHandle; 5775 StopwatchTimer mTimer; 5776 5777 public Sensor(int handle) { 5778 mHandle = handle; 5779 } 5780 5781 private StopwatchTimer readTimerFromParcel(TimeBase timeBase, Parcel in) { 5782 if (in.readInt() == 0) { 5783 return null; 5784 } 5785 5786 ArrayList<StopwatchTimer> pool = mSensorTimers.get(mHandle); 5787 if (pool == null) { 5788 pool = new ArrayList<StopwatchTimer>(); 5789 mSensorTimers.put(mHandle, pool); 5790 } 5791 return new StopwatchTimer(Uid.this, 0, pool, timeBase, in); 5792 } 5793 5794 boolean reset() { 5795 if (mTimer.reset(true)) { 5796 mTimer = null; 5797 return true; 5798 } 5799 return false; 5800 } 5801 5802 void readFromParcelLocked(TimeBase timeBase, Parcel in) { 5803 mTimer = readTimerFromParcel(timeBase, in); 5804 } 5805 5806 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) { 5807 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs); 5808 } 5809 5810 @Override 5811 public Timer getSensorTime() { 5812 return mTimer; 5813 } 5814 5815 @Override 5816 public int getHandle() { 5817 return mHandle; 5818 } 5819 } 5820 5821 /** 5822 * The statistics associated with a particular process. 5823 */ 5824 public final class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs { 5825 /** 5826 * The name of this process. 5827 */ 5828 final String mName; 5829 5830 /** 5831 * Remains true until removed from the stats. 5832 */ 5833 boolean mActive = true; 5834 5835 /** 5836 * Total time (in ms) spent executing in user code. 5837 */ 5838 long mUserTime; 5839 5840 /** 5841 * Total time (in ms) spent executing in kernel code. 5842 */ 5843 long mSystemTime; 5844 5845 /** 5846 * Amount of time (in ms) the process was running in the foreground. 5847 */ 5848 long mForegroundTime; 5849 5850 /** 5851 * Number of times the process has been started. 5852 */ 5853 int mStarts; 5854 5855 /** 5856 * Number of times the process has crashed. 5857 */ 5858 int mNumCrashes; 5859 5860 /** 5861 * Number of times the process has had an ANR. 5862 */ 5863 int mNumAnrs; 5864 5865 /** 5866 * The amount of user time loaded from a previous save. 5867 */ 5868 long mLoadedUserTime; 5869 5870 /** 5871 * The amount of system time loaded from a previous save. 5872 */ 5873 long mLoadedSystemTime; 5874 5875 /** 5876 * The amount of foreground time loaded from a previous save. 5877 */ 5878 long mLoadedForegroundTime; 5879 5880 /** 5881 * The number of times the process has started from a previous save. 5882 */ 5883 int mLoadedStarts; 5884 5885 /** 5886 * Number of times the process has crashed from a previous save. 5887 */ 5888 int mLoadedNumCrashes; 5889 5890 /** 5891 * Number of times the process has had an ANR from a previous save. 5892 */ 5893 int mLoadedNumAnrs; 5894 5895 /** 5896 * The amount of user time when last unplugged. 5897 */ 5898 long mUnpluggedUserTime; 5899 5900 /** 5901 * The amount of system time when last unplugged. 5902 */ 5903 long mUnpluggedSystemTime; 5904 5905 /** 5906 * The amount of foreground time since unplugged. 5907 */ 5908 long mUnpluggedForegroundTime; 5909 5910 /** 5911 * The number of times the process has started before unplugged. 5912 */ 5913 int mUnpluggedStarts; 5914 5915 /** 5916 * Number of times the process has crashed before unplugged. 5917 */ 5918 int mUnpluggedNumCrashes; 5919 5920 /** 5921 * Number of times the process has had an ANR before unplugged. 5922 */ 5923 int mUnpluggedNumAnrs; 5924 5925 /** 5926 * Current process state. 5927 */ 5928 int mProcessState = PROCESS_STATE_NONE; 5929 5930 ArrayList<ExcessivePower> mExcessivePower; 5931 5932 Proc(String name) { 5933 mName = name; 5934 mOnBatteryTimeBase.add(this); 5935 } 5936 5937 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) { 5938 mUnpluggedUserTime = mUserTime; 5939 mUnpluggedSystemTime = mSystemTime; 5940 mUnpluggedForegroundTime = mForegroundTime; 5941 mUnpluggedStarts = mStarts; 5942 mUnpluggedNumCrashes = mNumCrashes; 5943 mUnpluggedNumAnrs = mNumAnrs; 5944 } 5945 5946 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) { 5947 } 5948 5949 void reset() { 5950 mUserTime = mSystemTime = mForegroundTime = 0; 5951 mStarts = mNumCrashes = mNumAnrs = 0; 5952 mLoadedUserTime = mLoadedSystemTime = mLoadedForegroundTime = 0; 5953 mLoadedStarts = mLoadedNumCrashes = mLoadedNumAnrs = 0; 5954 mUnpluggedUserTime = mUnpluggedSystemTime = mUnpluggedForegroundTime = 0; 5955 mUnpluggedStarts = mUnpluggedNumCrashes = mUnpluggedNumAnrs = 0; 5956 mExcessivePower = null; 5957 } 5958 5959 void detach() { 5960 mActive = false; 5961 mOnBatteryTimeBase.remove(this); 5962 } 5963 5964 public int countExcessivePowers() { 5965 return mExcessivePower != null ? mExcessivePower.size() : 0; 5966 } 5967 5968 public ExcessivePower getExcessivePower(int i) { 5969 if (mExcessivePower != null) { 5970 return mExcessivePower.get(i); 5971 } 5972 return null; 5973 } 5974 5975 public void addExcessiveWake(long overTime, long usedTime) { 5976 if (mExcessivePower == null) { 5977 mExcessivePower = new ArrayList<ExcessivePower>(); 5978 } 5979 ExcessivePower ew = new ExcessivePower(); 5980 ew.type = ExcessivePower.TYPE_WAKE; 5981 ew.overTime = overTime; 5982 ew.usedTime = usedTime; 5983 mExcessivePower.add(ew); 5984 } 5985 5986 public void addExcessiveCpu(long overTime, long usedTime) { 5987 if (mExcessivePower == null) { 5988 mExcessivePower = new ArrayList<ExcessivePower>(); 5989 } 5990 ExcessivePower ew = new ExcessivePower(); 5991 ew.type = ExcessivePower.TYPE_CPU; 5992 ew.overTime = overTime; 5993 ew.usedTime = usedTime; 5994 mExcessivePower.add(ew); 5995 } 5996 5997 void writeExcessivePowerToParcelLocked(Parcel out) { 5998 if (mExcessivePower == null) { 5999 out.writeInt(0); 6000 return; 6001 } 6002 6003 final int N = mExcessivePower.size(); 6004 out.writeInt(N); 6005 for (int i=0; i<N; i++) { 6006 ExcessivePower ew = mExcessivePower.get(i); 6007 out.writeInt(ew.type); 6008 out.writeLong(ew.overTime); 6009 out.writeLong(ew.usedTime); 6010 } 6011 } 6012 6013 boolean readExcessivePowerFromParcelLocked(Parcel in) { 6014 final int N = in.readInt(); 6015 if (N == 0) { 6016 mExcessivePower = null; 6017 return true; 6018 } 6019 6020 if (N > 10000) { 6021 Slog.w(TAG, "File corrupt: too many excessive power entries " + N); 6022 return false; 6023 } 6024 6025 mExcessivePower = new ArrayList<ExcessivePower>(); 6026 for (int i=0; i<N; i++) { 6027 ExcessivePower ew = new ExcessivePower(); 6028 ew.type = in.readInt(); 6029 ew.overTime = in.readLong(); 6030 ew.usedTime = in.readLong(); 6031 mExcessivePower.add(ew); 6032 } 6033 return true; 6034 } 6035 6036 void writeToParcelLocked(Parcel out) { 6037 out.writeLong(mUserTime); 6038 out.writeLong(mSystemTime); 6039 out.writeLong(mForegroundTime); 6040 out.writeInt(mStarts); 6041 out.writeInt(mNumCrashes); 6042 out.writeInt(mNumAnrs); 6043 out.writeLong(mLoadedUserTime); 6044 out.writeLong(mLoadedSystemTime); 6045 out.writeLong(mLoadedForegroundTime); 6046 out.writeInt(mLoadedStarts); 6047 out.writeInt(mLoadedNumCrashes); 6048 out.writeInt(mLoadedNumAnrs); 6049 out.writeLong(mUnpluggedUserTime); 6050 out.writeLong(mUnpluggedSystemTime); 6051 out.writeLong(mUnpluggedForegroundTime); 6052 out.writeInt(mUnpluggedStarts); 6053 out.writeInt(mUnpluggedNumCrashes); 6054 out.writeInt(mUnpluggedNumAnrs); 6055 writeExcessivePowerToParcelLocked(out); 6056 } 6057 6058 void readFromParcelLocked(Parcel in) { 6059 mUserTime = in.readLong(); 6060 mSystemTime = in.readLong(); 6061 mForegroundTime = in.readLong(); 6062 mStarts = in.readInt(); 6063 mNumCrashes = in.readInt(); 6064 mNumAnrs = in.readInt(); 6065 mLoadedUserTime = in.readLong(); 6066 mLoadedSystemTime = in.readLong(); 6067 mLoadedForegroundTime = in.readLong(); 6068 mLoadedStarts = in.readInt(); 6069 mLoadedNumCrashes = in.readInt(); 6070 mLoadedNumAnrs = in.readInt(); 6071 mUnpluggedUserTime = in.readLong(); 6072 mUnpluggedSystemTime = in.readLong(); 6073 mUnpluggedForegroundTime = in.readLong(); 6074 mUnpluggedStarts = in.readInt(); 6075 mUnpluggedNumCrashes = in.readInt(); 6076 mUnpluggedNumAnrs = in.readInt(); 6077 readExcessivePowerFromParcelLocked(in); 6078 } 6079 6080 public void addCpuTimeLocked(int utime, int stime) { 6081 mUserTime += utime; 6082 mSystemTime += stime; 6083 } 6084 6085 public void addForegroundTimeLocked(long ttime) { 6086 mForegroundTime += ttime; 6087 } 6088 6089 public void incStartsLocked() { 6090 mStarts++; 6091 } 6092 6093 public void incNumCrashesLocked() { 6094 mNumCrashes++; 6095 } 6096 6097 public void incNumAnrsLocked() { 6098 mNumAnrs++; 6099 } 6100 6101 @Override 6102 public boolean isActive() { 6103 return mActive; 6104 } 6105 6106 @Override 6107 public long getUserTime(int which) { 6108 long val = mUserTime; 6109 if (which == STATS_CURRENT) { 6110 val -= mLoadedUserTime; 6111 } else if (which == STATS_SINCE_UNPLUGGED) { 6112 val -= mUnpluggedUserTime; 6113 } 6114 return val; 6115 } 6116 6117 @Override 6118 public long getSystemTime(int which) { 6119 long val = mSystemTime; 6120 if (which == STATS_CURRENT) { 6121 val -= mLoadedSystemTime; 6122 } else if (which == STATS_SINCE_UNPLUGGED) { 6123 val -= mUnpluggedSystemTime; 6124 } 6125 return val; 6126 } 6127 6128 @Override 6129 public long getForegroundTime(int which) { 6130 long val = mForegroundTime; 6131 if (which == STATS_CURRENT) { 6132 val -= mLoadedForegroundTime; 6133 } else if (which == STATS_SINCE_UNPLUGGED) { 6134 val -= mUnpluggedForegroundTime; 6135 } 6136 return val; 6137 } 6138 6139 @Override 6140 public int getStarts(int which) { 6141 int val = mStarts; 6142 if (which == STATS_CURRENT) { 6143 val -= mLoadedStarts; 6144 } else if (which == STATS_SINCE_UNPLUGGED) { 6145 val -= mUnpluggedStarts; 6146 } 6147 return val; 6148 } 6149 6150 @Override 6151 public int getNumCrashes(int which) { 6152 int val = mNumCrashes; 6153 if (which == STATS_CURRENT) { 6154 val -= mLoadedNumCrashes; 6155 } else if (which == STATS_SINCE_UNPLUGGED) { 6156 val -= mUnpluggedNumCrashes; 6157 } 6158 return val; 6159 } 6160 6161 @Override 6162 public int getNumAnrs(int which) { 6163 int val = mNumAnrs; 6164 if (which == STATS_CURRENT) { 6165 val -= mLoadedNumAnrs; 6166 } else if (which == STATS_SINCE_UNPLUGGED) { 6167 val -= mUnpluggedNumAnrs; 6168 } 6169 return val; 6170 } 6171 } 6172 6173 /** 6174 * The statistics associated with a particular package. 6175 */ 6176 public final class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs { 6177 /** 6178 * Number of times wakeup alarms have occurred for this app. 6179 */ 6180 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>(); 6181 6182 /** 6183 * The statics we have collected for this package's services. 6184 */ 6185 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>(); 6186 6187 Pkg() { 6188 mOnBatteryScreenOffTimeBase.add(this); 6189 } 6190 6191 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) { 6192 } 6193 6194 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) { 6195 } 6196 6197 void detach() { 6198 mOnBatteryScreenOffTimeBase.remove(this); 6199 } 6200 6201 void readFromParcelLocked(Parcel in) { 6202 int numWA = in.readInt(); 6203 mWakeupAlarms.clear(); 6204 for (int i=0; i<numWA; i++) { 6205 String tag = in.readString(); 6206 mWakeupAlarms.put(tag, new Counter(mOnBatteryTimeBase, in)); 6207 } 6208 6209 int numServs = in.readInt(); 6210 mServiceStats.clear(); 6211 for (int m = 0; m < numServs; m++) { 6212 String serviceName = in.readString(); 6213 Uid.Pkg.Serv serv = new Serv(); 6214 mServiceStats.put(serviceName, serv); 6215 6216 serv.readFromParcelLocked(in); 6217 } 6218 } 6219 6220 void writeToParcelLocked(Parcel out) { 6221 int numWA = mWakeupAlarms.size(); 6222 out.writeInt(numWA); 6223 for (int i=0; i<numWA; i++) { 6224 out.writeString(mWakeupAlarms.keyAt(i)); 6225 mWakeupAlarms.valueAt(i).writeToParcel(out); 6226 } 6227 6228 final int NS = mServiceStats.size(); 6229 out.writeInt(NS); 6230 for (int i=0; i<NS; i++) { 6231 out.writeString(mServiceStats.keyAt(i)); 6232 Uid.Pkg.Serv serv = mServiceStats.valueAt(i); 6233 serv.writeToParcelLocked(out); 6234 } 6235 } 6236 6237 @Override 6238 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() { 6239 return mWakeupAlarms; 6240 } 6241 6242 public void noteWakeupAlarmLocked(String tag) { 6243 Counter c = mWakeupAlarms.get(tag); 6244 if (c == null) { 6245 c = new Counter(mOnBatteryTimeBase); 6246 mWakeupAlarms.put(tag, c); 6247 } 6248 c.stepAtomic(); 6249 } 6250 6251 @Override 6252 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() { 6253 return mServiceStats; 6254 } 6255 6256 /** 6257 * The statistics associated with a particular service. 6258 */ 6259 public final class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs { 6260 /** 6261 * Total time (ms in battery uptime) the service has been left started. 6262 */ 6263 long mStartTime; 6264 6265 /** 6266 * If service has been started and not yet stopped, this is 6267 * when it was started. 6268 */ 6269 long mRunningSince; 6270 6271 /** 6272 * True if we are currently running. 6273 */ 6274 boolean mRunning; 6275 6276 /** 6277 * Total number of times startService() has been called. 6278 */ 6279 int mStarts; 6280 6281 /** 6282 * Total time (ms in battery uptime) the service has been left launched. 6283 */ 6284 long mLaunchedTime; 6285 6286 /** 6287 * If service has been launched and not yet exited, this is 6288 * when it was launched (ms in battery uptime). 6289 */ 6290 long mLaunchedSince; 6291 6292 /** 6293 * True if we are currently launched. 6294 */ 6295 boolean mLaunched; 6296 6297 /** 6298 * Total number times the service has been launched. 6299 */ 6300 int mLaunches; 6301 6302 /** 6303 * The amount of time spent started loaded from a previous save 6304 * (ms in battery uptime). 6305 */ 6306 long mLoadedStartTime; 6307 6308 /** 6309 * The number of starts loaded from a previous save. 6310 */ 6311 int mLoadedStarts; 6312 6313 /** 6314 * The number of launches loaded from a previous save. 6315 */ 6316 int mLoadedLaunches; 6317 6318 /** 6319 * The amount of time spent started as of the last run (ms 6320 * in battery uptime). 6321 */ 6322 long mLastStartTime; 6323 6324 /** 6325 * The number of starts as of the last run. 6326 */ 6327 int mLastStarts; 6328 6329 /** 6330 * The number of launches as of the last run. 6331 */ 6332 int mLastLaunches; 6333 6334 /** 6335 * The amount of time spent started when last unplugged (ms 6336 * in battery uptime). 6337 */ 6338 long mUnpluggedStartTime; 6339 6340 /** 6341 * The number of starts when last unplugged. 6342 */ 6343 int mUnpluggedStarts; 6344 6345 /** 6346 * The number of launches when last unplugged. 6347 */ 6348 int mUnpluggedLaunches; 6349 6350 Serv() { 6351 mOnBatteryTimeBase.add(this); 6352 } 6353 6354 public void onTimeStarted(long elapsedRealtime, long baseUptime, 6355 long baseRealtime) { 6356 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime); 6357 mUnpluggedStarts = mStarts; 6358 mUnpluggedLaunches = mLaunches; 6359 } 6360 6361 public void onTimeStopped(long elapsedRealtime, long baseUptime, 6362 long baseRealtime) { 6363 } 6364 6365 void detach() { 6366 mOnBatteryTimeBase.remove(this); 6367 } 6368 6369 void readFromParcelLocked(Parcel in) { 6370 mStartTime = in.readLong(); 6371 mRunningSince = in.readLong(); 6372 mRunning = in.readInt() != 0; 6373 mStarts = in.readInt(); 6374 mLaunchedTime = in.readLong(); 6375 mLaunchedSince = in.readLong(); 6376 mLaunched = in.readInt() != 0; 6377 mLaunches = in.readInt(); 6378 mLoadedStartTime = in.readLong(); 6379 mLoadedStarts = in.readInt(); 6380 mLoadedLaunches = in.readInt(); 6381 mLastStartTime = 0; 6382 mLastStarts = 0; 6383 mLastLaunches = 0; 6384 mUnpluggedStartTime = in.readLong(); 6385 mUnpluggedStarts = in.readInt(); 6386 mUnpluggedLaunches = in.readInt(); 6387 } 6388 6389 void writeToParcelLocked(Parcel out) { 6390 out.writeLong(mStartTime); 6391 out.writeLong(mRunningSince); 6392 out.writeInt(mRunning ? 1 : 0); 6393 out.writeInt(mStarts); 6394 out.writeLong(mLaunchedTime); 6395 out.writeLong(mLaunchedSince); 6396 out.writeInt(mLaunched ? 1 : 0); 6397 out.writeInt(mLaunches); 6398 out.writeLong(mLoadedStartTime); 6399 out.writeInt(mLoadedStarts); 6400 out.writeInt(mLoadedLaunches); 6401 out.writeLong(mUnpluggedStartTime); 6402 out.writeInt(mUnpluggedStarts); 6403 out.writeInt(mUnpluggedLaunches); 6404 } 6405 6406 long getLaunchTimeToNowLocked(long batteryUptime) { 6407 if (!mLaunched) return mLaunchedTime; 6408 return mLaunchedTime + batteryUptime - mLaunchedSince; 6409 } 6410 6411 long getStartTimeToNowLocked(long batteryUptime) { 6412 if (!mRunning) return mStartTime; 6413 return mStartTime + batteryUptime - mRunningSince; 6414 } 6415 6416 public void startLaunchedLocked() { 6417 if (!mLaunched) { 6418 mLaunches++; 6419 mLaunchedSince = getBatteryUptimeLocked(); 6420 mLaunched = true; 6421 } 6422 } 6423 6424 public void stopLaunchedLocked() { 6425 if (mLaunched) { 6426 long time = getBatteryUptimeLocked() - mLaunchedSince; 6427 if (time > 0) { 6428 mLaunchedTime += time; 6429 } else { 6430 mLaunches--; 6431 } 6432 mLaunched = false; 6433 } 6434 } 6435 6436 public void startRunningLocked() { 6437 if (!mRunning) { 6438 mStarts++; 6439 mRunningSince = getBatteryUptimeLocked(); 6440 mRunning = true; 6441 } 6442 } 6443 6444 public void stopRunningLocked() { 6445 if (mRunning) { 6446 long time = getBatteryUptimeLocked() - mRunningSince; 6447 if (time > 0) { 6448 mStartTime += time; 6449 } else { 6450 mStarts--; 6451 } 6452 mRunning = false; 6453 } 6454 } 6455 6456 public BatteryStatsImpl getBatteryStats() { 6457 return BatteryStatsImpl.this; 6458 } 6459 6460 @Override 6461 public int getLaunches(int which) { 6462 int val = mLaunches; 6463 if (which == STATS_CURRENT) { 6464 val -= mLoadedLaunches; 6465 } else if (which == STATS_SINCE_UNPLUGGED) { 6466 val -= mUnpluggedLaunches; 6467 } 6468 return val; 6469 } 6470 6471 @Override 6472 public long getStartTime(long now, int which) { 6473 long val = getStartTimeToNowLocked(now); 6474 if (which == STATS_CURRENT) { 6475 val -= mLoadedStartTime; 6476 } else if (which == STATS_SINCE_UNPLUGGED) { 6477 val -= mUnpluggedStartTime; 6478 } 6479 return val; 6480 } 6481 6482 @Override 6483 public int getStarts(int which) { 6484 int val = mStarts; 6485 if (which == STATS_CURRENT) { 6486 val -= mLoadedStarts; 6487 } else if (which == STATS_SINCE_UNPLUGGED) { 6488 val -= mUnpluggedStarts; 6489 } 6490 6491 return val; 6492 } 6493 } 6494 6495 final Serv newServiceStatsLocked() { 6496 return new Serv(); 6497 } 6498 } 6499 6500 /** 6501 * Retrieve the statistics object for a particular process, creating 6502 * if needed. 6503 */ 6504 public Proc getProcessStatsLocked(String name) { 6505 Proc ps = mProcessStats.get(name); 6506 if (ps == null) { 6507 ps = new Proc(name); 6508 mProcessStats.put(name, ps); 6509 } 6510 6511 return ps; 6512 } 6513 6514 public void updateProcessStateLocked(String procName, int state, long elapsedRealtimeMs) { 6515 int procState; 6516 if (state <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) { 6517 procState = PROCESS_STATE_FOREGROUND; 6518 } else if (state <= ActivityManager.PROCESS_STATE_RECEIVER) { 6519 procState = PROCESS_STATE_ACTIVE; 6520 } else { 6521 procState = PROCESS_STATE_RUNNING; 6522 } 6523 updateRealProcessStateLocked(procName, procState, elapsedRealtimeMs); 6524 } 6525 6526 public void updateRealProcessStateLocked(String procName, int procState, 6527 long elapsedRealtimeMs) { 6528 Proc proc = getProcessStatsLocked(procName); 6529 if (proc.mProcessState != procState) { 6530 boolean changed; 6531 if (procState < proc.mProcessState) { 6532 // Has this process become more important? If so, 6533 // we may need to change the uid if the currrent uid proc state 6534 // is not as important as what we are now setting. 6535 changed = mProcessState > procState; 6536 } else { 6537 // Has this process become less important? If so, 6538 // we may need to change the uid if the current uid proc state 6539 // is the same importance as the old setting. 6540 changed = mProcessState == proc.mProcessState; 6541 } 6542 proc.mProcessState = procState; 6543 if (changed) { 6544 // uid's state may have changed; compute what the new state should be. 6545 int uidProcState = PROCESS_STATE_NONE; 6546 for (int ip=mProcessStats.size()-1; ip>=0; ip--) { 6547 proc = mProcessStats.valueAt(ip); 6548 if (proc.mProcessState < uidProcState) { 6549 uidProcState = proc.mProcessState; 6550 } 6551 } 6552 updateUidProcessStateLocked(uidProcState, elapsedRealtimeMs); 6553 } 6554 } 6555 } 6556 6557 public SparseArray<? extends Pid> getPidStats() { 6558 return mPids; 6559 } 6560 6561 public Pid getPidStatsLocked(int pid) { 6562 Pid p = mPids.get(pid); 6563 if (p == null) { 6564 p = new Pid(); 6565 mPids.put(pid, p); 6566 } 6567 return p; 6568 } 6569 6570 /** 6571 * Retrieve the statistics object for a particular service, creating 6572 * if needed. 6573 */ 6574 public Pkg getPackageStatsLocked(String name) { 6575 Pkg ps = mPackageStats.get(name); 6576 if (ps == null) { 6577 ps = new Pkg(); 6578 mPackageStats.put(name, ps); 6579 } 6580 6581 return ps; 6582 } 6583 6584 /** 6585 * Retrieve the statistics object for a particular service, creating 6586 * if needed. 6587 */ 6588 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) { 6589 Pkg ps = getPackageStatsLocked(pkg); 6590 Pkg.Serv ss = ps.mServiceStats.get(serv); 6591 if (ss == null) { 6592 ss = ps.newServiceStatsLocked(); 6593 ps.mServiceStats.put(serv, ss); 6594 } 6595 6596 return ss; 6597 } 6598 6599 public void readSyncSummaryFromParcelLocked(String name, Parcel in) { 6600 StopwatchTimer timer = mSyncStats.instantiateObject(); 6601 timer.readSummaryFromParcelLocked(in); 6602 mSyncStats.add(name, timer); 6603 } 6604 6605 public void readJobSummaryFromParcelLocked(String name, Parcel in) { 6606 StopwatchTimer timer = mJobStats.instantiateObject(); 6607 timer.readSummaryFromParcelLocked(in); 6608 mJobStats.add(name, timer); 6609 } 6610 6611 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) { 6612 Wakelock wl = new Wakelock(); 6613 mWakelockStats.add(wlName, wl); 6614 if (in.readInt() != 0) { 6615 wl.getStopwatchTimer(WAKE_TYPE_FULL).readSummaryFromParcelLocked(in); 6616 } 6617 if (in.readInt() != 0) { 6618 wl.getStopwatchTimer(WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in); 6619 } 6620 if (in.readInt() != 0) { 6621 wl.getStopwatchTimer(WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in); 6622 } 6623 if (in.readInt() != 0) { 6624 wl.getStopwatchTimer(WAKE_TYPE_DOZE).readSummaryFromParcelLocked(in); 6625 } 6626 } 6627 6628 public StopwatchTimer getSensorTimerLocked(int sensor, boolean create) { 6629 Sensor se = mSensorStats.get(sensor); 6630 if (se == null) { 6631 if (!create) { 6632 return null; 6633 } 6634 se = new Sensor(sensor); 6635 mSensorStats.put(sensor, se); 6636 } 6637 StopwatchTimer t = se.mTimer; 6638 if (t != null) { 6639 return t; 6640 } 6641 ArrayList<StopwatchTimer> timers = mSensorTimers.get(sensor); 6642 if (timers == null) { 6643 timers = new ArrayList<StopwatchTimer>(); 6644 mSensorTimers.put(sensor, timers); 6645 } 6646 t = new StopwatchTimer(Uid.this, BatteryStats.SENSOR, timers, mOnBatteryTimeBase); 6647 se.mTimer = t; 6648 return t; 6649 } 6650 6651 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) { 6652 StopwatchTimer t = mSyncStats.startObject(name); 6653 if (t != null) { 6654 t.startRunningLocked(elapsedRealtimeMs); 6655 } 6656 } 6657 6658 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) { 6659 StopwatchTimer t = mSyncStats.stopObject(name); 6660 if (t != null) { 6661 t.stopRunningLocked(elapsedRealtimeMs); 6662 } 6663 } 6664 6665 public void noteStartJobLocked(String name, long elapsedRealtimeMs) { 6666 StopwatchTimer t = mJobStats.startObject(name); 6667 if (t != null) { 6668 t.startRunningLocked(elapsedRealtimeMs); 6669 } 6670 } 6671 6672 public void noteStopJobLocked(String name, long elapsedRealtimeMs) { 6673 StopwatchTimer t = mJobStats.stopObject(name); 6674 if (t != null) { 6675 t.stopRunningLocked(elapsedRealtimeMs); 6676 } 6677 } 6678 6679 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) { 6680 Wakelock wl = mWakelockStats.startObject(name); 6681 if (wl != null) { 6682 wl.getStopwatchTimer(type).startRunningLocked(elapsedRealtimeMs); 6683 } 6684 if (pid >= 0 && type == WAKE_TYPE_PARTIAL) { 6685 Pid p = getPidStatsLocked(pid); 6686 if (p.mWakeNesting++ == 0) { 6687 p.mWakeStartMs = elapsedRealtimeMs; 6688 } 6689 } 6690 } 6691 6692 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) { 6693 Wakelock wl = mWakelockStats.stopObject(name); 6694 if (wl != null) { 6695 wl.getStopwatchTimer(type).stopRunningLocked(elapsedRealtimeMs); 6696 } 6697 if (pid >= 0 && type == WAKE_TYPE_PARTIAL) { 6698 Pid p = mPids.get(pid); 6699 if (p != null && p.mWakeNesting > 0) { 6700 if (p.mWakeNesting-- == 1) { 6701 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs; 6702 p.mWakeStartMs = 0; 6703 } 6704 } 6705 } 6706 } 6707 6708 public void reportExcessiveWakeLocked(String proc, long overTime, long usedTime) { 6709 Proc p = getProcessStatsLocked(proc); 6710 if (p != null) { 6711 p.addExcessiveWake(overTime, usedTime); 6712 } 6713 } 6714 6715 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) { 6716 Proc p = getProcessStatsLocked(proc); 6717 if (p != null) { 6718 p.addExcessiveCpu(overTime, usedTime); 6719 } 6720 } 6721 6722 public void noteStartSensor(int sensor, long elapsedRealtimeMs) { 6723 StopwatchTimer t = getSensorTimerLocked(sensor, true); 6724 if (t != null) { 6725 t.startRunningLocked(elapsedRealtimeMs); 6726 } 6727 } 6728 6729 public void noteStopSensor(int sensor, long elapsedRealtimeMs) { 6730 // Don't create a timer if one doesn't already exist 6731 StopwatchTimer t = getSensorTimerLocked(sensor, false); 6732 if (t != null) { 6733 t.stopRunningLocked(elapsedRealtimeMs); 6734 } 6735 } 6736 6737 public void noteStartGps(long elapsedRealtimeMs) { 6738 StopwatchTimer t = getSensorTimerLocked(Sensor.GPS, true); 6739 if (t != null) { 6740 t.startRunningLocked(elapsedRealtimeMs); 6741 } 6742 } 6743 6744 public void noteStopGps(long elapsedRealtimeMs) { 6745 StopwatchTimer t = getSensorTimerLocked(Sensor.GPS, false); 6746 if (t != null) { 6747 t.stopRunningLocked(elapsedRealtimeMs); 6748 } 6749 } 6750 6751 public BatteryStatsImpl getBatteryStats() { 6752 return BatteryStatsImpl.this; 6753 } 6754 } 6755 6756 public BatteryStatsImpl(File systemDir, Handler handler, ExternalStatsSync externalSync) { 6757 if (systemDir != null) { 6758 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"), 6759 new File(systemDir, "batterystats.bin.tmp")); 6760 } else { 6761 mFile = null; 6762 } 6763 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin")); 6764 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml")); 6765 mExternalSync = externalSync; 6766 mHandler = new MyHandler(handler.getLooper()); 6767 mStartCount++; 6768 mScreenOnTimer = new StopwatchTimer(null, -1, null, mOnBatteryTimeBase); 6769 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) { 6770 mScreenBrightnessTimer[i] = new StopwatchTimer(null, -100-i, null, mOnBatteryTimeBase); 6771 } 6772 mInteractiveTimer = new StopwatchTimer(null, -10, null, mOnBatteryTimeBase); 6773 mPowerSaveModeEnabledTimer = new StopwatchTimer(null, -2, null, mOnBatteryTimeBase); 6774 mDeviceIdleModeEnabledTimer = new StopwatchTimer(null, -11, null, mOnBatteryTimeBase); 6775 mDeviceIdlingTimer = new StopwatchTimer(null, -12, null, mOnBatteryTimeBase); 6776 mPhoneOnTimer = new StopwatchTimer(null, -3, null, mOnBatteryTimeBase); 6777 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) { 6778 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(null, -200-i, null, 6779 mOnBatteryTimeBase); 6780 } 6781 mPhoneSignalScanningTimer = new StopwatchTimer(null, -200+1, null, mOnBatteryTimeBase); 6782 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) { 6783 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(null, -300-i, null, 6784 mOnBatteryTimeBase); 6785 } 6786 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 6787 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase); 6788 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase); 6789 } 6790 for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 6791 mBluetoothActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase); 6792 mWifiActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase); 6793 } 6794 mMobileRadioActiveTimer = new StopwatchTimer(null, -400, null, mOnBatteryTimeBase); 6795 mMobileRadioActivePerAppTimer = new StopwatchTimer(null, -401, null, mOnBatteryTimeBase); 6796 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase); 6797 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase); 6798 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase); 6799 mWifiOnTimer = new StopwatchTimer(null, -4, null, mOnBatteryTimeBase); 6800 mGlobalWifiRunningTimer = new StopwatchTimer(null, -5, null, mOnBatteryTimeBase); 6801 for (int i=0; i<NUM_WIFI_STATES; i++) { 6802 mWifiStateTimer[i] = new StopwatchTimer(null, -600-i, null, mOnBatteryTimeBase); 6803 } 6804 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) { 6805 mWifiSupplStateTimer[i] = new StopwatchTimer(null, -700-i, null, mOnBatteryTimeBase); 6806 } 6807 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) { 6808 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(null, -800-i, null, 6809 mOnBatteryTimeBase); 6810 } 6811 mAudioOnTimer = new StopwatchTimer(null, -7, null, mOnBatteryTimeBase); 6812 mVideoOnTimer = new StopwatchTimer(null, -8, null, mOnBatteryTimeBase); 6813 mFlashlightOnTimer = new StopwatchTimer(null, -9, null, mOnBatteryTimeBase); 6814 mCameraOnTimer = new StopwatchTimer(null, -13, null, mOnBatteryTimeBase); 6815 mOnBattery = mOnBatteryInternal = false; 6816 long uptime = SystemClock.uptimeMillis() * 1000; 6817 long realtime = SystemClock.elapsedRealtime() * 1000; 6818 initTimes(uptime, realtime); 6819 mStartPlatformVersion = mEndPlatformVersion = Build.ID; 6820 mDischargeStartLevel = 0; 6821 mDischargeUnplugLevel = 0; 6822 mDischargePlugLevel = -1; 6823 mDischargeCurrentLevel = 0; 6824 mCurrentBatteryLevel = 0; 6825 initDischarge(); 6826 clearHistoryLocked(); 6827 updateDailyDeadlineLocked(); 6828 } 6829 6830 public BatteryStatsImpl(Parcel p) { 6831 mFile = null; 6832 mCheckinFile = null; 6833 mDailyFile = null; 6834 mHandler = null; 6835 mExternalSync = null; 6836 clearHistoryLocked(); 6837 readFromParcel(p); 6838 } 6839 6840 public void setPowerProfile(PowerProfile profile) { 6841 synchronized (this) { 6842 mPowerProfile = profile; 6843 } 6844 } 6845 6846 public void setCallback(BatteryCallback cb) { 6847 mCallback = cb; 6848 } 6849 6850 public void setNumSpeedSteps(int steps) { 6851 if (sNumSpeedSteps == 0) sNumSpeedSteps = steps; 6852 } 6853 6854 public void setRadioScanningTimeout(long timeout) { 6855 if (mPhoneSignalScanningTimer != null) { 6856 mPhoneSignalScanningTimer.setTimeout(timeout); 6857 } 6858 } 6859 6860 public void updateDailyDeadlineLocked() { 6861 // Get the current time. 6862 long currentTime = mDailyStartTime = System.currentTimeMillis(); 6863 Calendar calDeadline = Calendar.getInstance(); 6864 calDeadline.setTimeInMillis(currentTime); 6865 6866 // Move time up to the next day, ranging from 1am to 3pm. 6867 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1); 6868 calDeadline.set(Calendar.MILLISECOND, 0); 6869 calDeadline.set(Calendar.SECOND, 0); 6870 calDeadline.set(Calendar.MINUTE, 0); 6871 calDeadline.set(Calendar.HOUR_OF_DAY, 1); 6872 mNextMinDailyDeadline = calDeadline.getTimeInMillis(); 6873 calDeadline.set(Calendar.HOUR_OF_DAY, 3); 6874 mNextMaxDailyDeadline = calDeadline.getTimeInMillis(); 6875 } 6876 6877 public void recordDailyStatsIfNeededLocked(boolean settled) { 6878 long currentTime = System.currentTimeMillis(); 6879 if (currentTime >= mNextMaxDailyDeadline) { 6880 recordDailyStatsLocked(); 6881 } else if (settled && currentTime >= mNextMinDailyDeadline) { 6882 recordDailyStatsLocked(); 6883 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) { 6884 recordDailyStatsLocked(); 6885 } 6886 } 6887 6888 public void recordDailyStatsLocked() { 6889 DailyItem item = new DailyItem(); 6890 item.mStartTime = mDailyStartTime; 6891 item.mEndTime = System.currentTimeMillis(); 6892 boolean hasData = false; 6893 if (mDailyDischargeStepTracker.mNumStepDurations > 0) { 6894 hasData = true; 6895 item.mDischargeSteps = new LevelStepTracker( 6896 mDailyDischargeStepTracker.mNumStepDurations, 6897 mDailyDischargeStepTracker.mStepDurations); 6898 } 6899 if (mDailyChargeStepTracker.mNumStepDurations > 0) { 6900 hasData = true; 6901 item.mChargeSteps = new LevelStepTracker( 6902 mDailyChargeStepTracker.mNumStepDurations, 6903 mDailyChargeStepTracker.mStepDurations); 6904 } 6905 if (mDailyPackageChanges != null) { 6906 hasData = true; 6907 item.mPackageChanges = mDailyPackageChanges; 6908 mDailyPackageChanges = null; 6909 } 6910 mDailyDischargeStepTracker.init(); 6911 mDailyChargeStepTracker.init(); 6912 updateDailyDeadlineLocked(); 6913 6914 if (hasData) { 6915 mDailyItems.add(item); 6916 while (mDailyItems.size() > MAX_DAILY_ITEMS) { 6917 mDailyItems.remove(0); 6918 } 6919 final ByteArrayOutputStream memStream = new ByteArrayOutputStream(); 6920 try { 6921 XmlSerializer out = new FastXmlSerializer(); 6922 out.setOutput(memStream, StandardCharsets.UTF_8.name()); 6923 writeDailyItemsLocked(out); 6924 BackgroundThread.getHandler().post(new Runnable() { 6925 @Override 6926 public void run() { 6927 synchronized (mCheckinFile) { 6928 FileOutputStream stream = null; 6929 try { 6930 stream = mDailyFile.startWrite(); 6931 memStream.writeTo(stream); 6932 stream.flush(); 6933 FileUtils.sync(stream); 6934 stream.close(); 6935 mDailyFile.finishWrite(stream); 6936 } catch (IOException e) { 6937 Slog.w("BatteryStats", 6938 "Error writing battery daily items", e); 6939 mDailyFile.failWrite(stream); 6940 } 6941 } 6942 } 6943 }); 6944 } catch (IOException e) { 6945 } 6946 } 6947 } 6948 6949 private void writeDailyItemsLocked(XmlSerializer out) throws IOException { 6950 StringBuilder sb = new StringBuilder(64); 6951 out.startDocument(null, true); 6952 out.startTag(null, "daily-items"); 6953 for (int i=0; i<mDailyItems.size(); i++) { 6954 final DailyItem dit = mDailyItems.get(i); 6955 out.startTag(null, "item"); 6956 out.attribute(null, "start", Long.toString(dit.mStartTime)); 6957 out.attribute(null, "end", Long.toString(dit.mEndTime)); 6958 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb); 6959 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb); 6960 if (dit.mPackageChanges != null) { 6961 for (int j=0; j<dit.mPackageChanges.size(); j++) { 6962 PackageChange pc = dit.mPackageChanges.get(j); 6963 if (pc.mUpdate) { 6964 out.startTag(null, "upd"); 6965 out.attribute(null, "pkg", pc.mPackageName); 6966 out.attribute(null, "ver", Integer.toString(pc.mVersionCode)); 6967 out.endTag(null, "upd"); 6968 } else { 6969 out.startTag(null, "rem"); 6970 out.attribute(null, "pkg", pc.mPackageName); 6971 out.endTag(null, "rem"); 6972 } 6973 } 6974 } 6975 out.endTag(null, "item"); 6976 } 6977 out.endTag(null, "daily-items"); 6978 out.endDocument(); 6979 } 6980 6981 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps, 6982 StringBuilder tmpBuilder) throws IOException { 6983 if (steps != null) { 6984 out.startTag(null, tag); 6985 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations)); 6986 for (int i=0; i<steps.mNumStepDurations; i++) { 6987 out.startTag(null, "s"); 6988 tmpBuilder.setLength(0); 6989 steps.encodeEntryAt(i, tmpBuilder); 6990 out.attribute(null, "v", tmpBuilder.toString()); 6991 out.endTag(null, "s"); 6992 } 6993 out.endTag(null, tag); 6994 } 6995 } 6996 6997 public void readDailyStatsLocked() { 6998 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile()); 6999 mDailyItems.clear(); 7000 FileInputStream stream; 7001 try { 7002 stream = mDailyFile.openRead(); 7003 } catch (FileNotFoundException e) { 7004 return; 7005 } 7006 try { 7007 XmlPullParser parser = Xml.newPullParser(); 7008 parser.setInput(stream, StandardCharsets.UTF_8.name()); 7009 readDailyItemsLocked(parser); 7010 } catch (XmlPullParserException e) { 7011 } finally { 7012 try { 7013 stream.close(); 7014 } catch (IOException e) { 7015 } 7016 } 7017 } 7018 7019 private void readDailyItemsLocked(XmlPullParser parser) { 7020 try { 7021 int type; 7022 while ((type = parser.next()) != XmlPullParser.START_TAG 7023 && type != XmlPullParser.END_DOCUMENT) { 7024 ; 7025 } 7026 7027 if (type != XmlPullParser.START_TAG) { 7028 throw new IllegalStateException("no start tag found"); 7029 } 7030 7031 int outerDepth = parser.getDepth(); 7032 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 7033 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 7034 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 7035 continue; 7036 } 7037 7038 String tagName = parser.getName(); 7039 if (tagName.equals("item")) { 7040 readDailyItemTagLocked(parser); 7041 } else { 7042 Slog.w(TAG, "Unknown element under <daily-items>: " 7043 + parser.getName()); 7044 XmlUtils.skipCurrentTag(parser); 7045 } 7046 } 7047 7048 } catch (IllegalStateException e) { 7049 Slog.w(TAG, "Failed parsing daily " + e); 7050 } catch (NullPointerException e) { 7051 Slog.w(TAG, "Failed parsing daily " + e); 7052 } catch (NumberFormatException e) { 7053 Slog.w(TAG, "Failed parsing daily " + e); 7054 } catch (XmlPullParserException e) { 7055 Slog.w(TAG, "Failed parsing daily " + e); 7056 } catch (IOException e) { 7057 Slog.w(TAG, "Failed parsing daily " + e); 7058 } catch (IndexOutOfBoundsException e) { 7059 Slog.w(TAG, "Failed parsing daily " + e); 7060 } 7061 } 7062 7063 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException, 7064 XmlPullParserException, IOException { 7065 DailyItem dit = new DailyItem(); 7066 String attr = parser.getAttributeValue(null, "start"); 7067 if (attr != null) { 7068 dit.mStartTime = Long.parseLong(attr); 7069 } 7070 attr = parser.getAttributeValue(null, "end"); 7071 if (attr != null) { 7072 dit.mEndTime = Long.parseLong(attr); 7073 } 7074 int outerDepth = parser.getDepth(); 7075 int type; 7076 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 7077 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 7078 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 7079 continue; 7080 } 7081 7082 String tagName = parser.getName(); 7083 if (tagName.equals("dis")) { 7084 readDailyItemTagDetailsLocked(parser, dit, false, "dis"); 7085 } else if (tagName.equals("chg")) { 7086 readDailyItemTagDetailsLocked(parser, dit, true, "chg"); 7087 } else if (tagName.equals("upd")) { 7088 if (dit.mPackageChanges == null) { 7089 dit.mPackageChanges = new ArrayList<>(); 7090 } 7091 PackageChange pc = new PackageChange(); 7092 pc.mUpdate = true; 7093 pc.mPackageName = parser.getAttributeValue(null, "pkg"); 7094 String verStr = parser.getAttributeValue(null, "ver"); 7095 pc.mVersionCode = verStr != null ? Integer.parseInt(verStr) : 0; 7096 dit.mPackageChanges.add(pc); 7097 XmlUtils.skipCurrentTag(parser); 7098 } else if (tagName.equals("rem")) { 7099 if (dit.mPackageChanges == null) { 7100 dit.mPackageChanges = new ArrayList<>(); 7101 } 7102 PackageChange pc = new PackageChange(); 7103 pc.mUpdate = false; 7104 pc.mPackageName = parser.getAttributeValue(null, "pkg"); 7105 dit.mPackageChanges.add(pc); 7106 XmlUtils.skipCurrentTag(parser); 7107 } else { 7108 Slog.w(TAG, "Unknown element under <item>: " 7109 + parser.getName()); 7110 XmlUtils.skipCurrentTag(parser); 7111 } 7112 } 7113 mDailyItems.add(dit); 7114 } 7115 7116 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge, 7117 String tag) 7118 throws NumberFormatException, XmlPullParserException, IOException { 7119 final String numAttr = parser.getAttributeValue(null, "n"); 7120 if (numAttr == null) { 7121 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription()); 7122 XmlUtils.skipCurrentTag(parser); 7123 return; 7124 } 7125 final int num = Integer.parseInt(numAttr); 7126 LevelStepTracker steps = new LevelStepTracker(num); 7127 if (isCharge) { 7128 dit.mChargeSteps = steps; 7129 } else { 7130 dit.mDischargeSteps = steps; 7131 } 7132 int i = 0; 7133 int outerDepth = parser.getDepth(); 7134 int type; 7135 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 7136 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 7137 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 7138 continue; 7139 } 7140 7141 String tagName = parser.getName(); 7142 if ("s".equals(tagName)) { 7143 if (i < num) { 7144 String valueAttr = parser.getAttributeValue(null, "v"); 7145 if (valueAttr != null) { 7146 steps.decodeEntryAt(i, valueAttr); 7147 i++; 7148 } 7149 } 7150 } else { 7151 Slog.w(TAG, "Unknown element under <" + tag + ">: " 7152 + parser.getName()); 7153 XmlUtils.skipCurrentTag(parser); 7154 } 7155 } 7156 steps.mNumStepDurations = i; 7157 } 7158 7159 @Override 7160 public DailyItem getDailyItemLocked(int daysAgo) { 7161 int index = mDailyItems.size()-1-daysAgo; 7162 return index >= 0 ? mDailyItems.get(index) : null; 7163 } 7164 7165 @Override 7166 public long getCurrentDailyStartTime() { 7167 return mDailyStartTime; 7168 } 7169 7170 @Override 7171 public long getNextMinDailyDeadline() { 7172 return mNextMinDailyDeadline; 7173 } 7174 7175 @Override 7176 public long getNextMaxDailyDeadline() { 7177 return mNextMaxDailyDeadline; 7178 } 7179 7180 @Override 7181 public boolean startIteratingOldHistoryLocked() { 7182 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize() 7183 + " pos=" + mHistoryBuffer.dataPosition()); 7184 if ((mHistoryIterator = mHistory) == null) { 7185 return false; 7186 } 7187 mHistoryBuffer.setDataPosition(0); 7188 mHistoryReadTmp.clear(); 7189 mReadOverflow = false; 7190 mIteratingHistory = true; 7191 return true; 7192 } 7193 7194 @Override 7195 public boolean getNextOldHistoryLocked(HistoryItem out) { 7196 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize(); 7197 if (!end) { 7198 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp); 7199 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW; 7200 } 7201 HistoryItem cur = mHistoryIterator; 7202 if (cur == null) { 7203 if (!mReadOverflow && !end) { 7204 Slog.w(TAG, "Old history ends before new history!"); 7205 } 7206 return false; 7207 } 7208 out.setTo(cur); 7209 mHistoryIterator = cur.next; 7210 if (!mReadOverflow) { 7211 if (end) { 7212 Slog.w(TAG, "New history ends before old history!"); 7213 } else if (!out.same(mHistoryReadTmp)) { 7214 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG)); 7215 pw.println("Histories differ!"); 7216 pw.println("Old history:"); 7217 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true); 7218 pw.println("New history:"); 7219 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false, 7220 true); 7221 pw.flush(); 7222 } 7223 } 7224 return true; 7225 } 7226 7227 @Override 7228 public void finishIteratingOldHistoryLocked() { 7229 mIteratingHistory = false; 7230 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize()); 7231 mHistoryIterator = null; 7232 } 7233 7234 public int getHistoryTotalSize() { 7235 return MAX_HISTORY_BUFFER; 7236 } 7237 7238 public int getHistoryUsedSize() { 7239 return mHistoryBuffer.dataSize(); 7240 } 7241 7242 @Override 7243 public boolean startIteratingHistoryLocked() { 7244 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize() 7245 + " pos=" + mHistoryBuffer.dataPosition()); 7246 if (mHistoryBuffer.dataSize() <= 0) { 7247 return false; 7248 } 7249 mHistoryBuffer.setDataPosition(0); 7250 mReadOverflow = false; 7251 mIteratingHistory = true; 7252 mReadHistoryStrings = new String[mHistoryTagPool.size()]; 7253 mReadHistoryUids = new int[mHistoryTagPool.size()]; 7254 mReadHistoryChars = 0; 7255 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) { 7256 final HistoryTag tag = ent.getKey(); 7257 final int idx = ent.getValue(); 7258 mReadHistoryStrings[idx] = tag.string; 7259 mReadHistoryUids[idx] = tag.uid; 7260 mReadHistoryChars += tag.string.length() + 1; 7261 } 7262 return true; 7263 } 7264 7265 @Override 7266 public int getHistoryStringPoolSize() { 7267 return mReadHistoryStrings.length; 7268 } 7269 7270 @Override 7271 public int getHistoryStringPoolBytes() { 7272 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size 7273 // Each string character is 2 bytes. 7274 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2); 7275 } 7276 7277 @Override 7278 public String getHistoryTagPoolString(int index) { 7279 return mReadHistoryStrings[index]; 7280 } 7281 7282 @Override 7283 public int getHistoryTagPoolUid(int index) { 7284 return mReadHistoryUids[index]; 7285 } 7286 7287 @Override 7288 public boolean getNextHistoryLocked(HistoryItem out) { 7289 final int pos = mHistoryBuffer.dataPosition(); 7290 if (pos == 0) { 7291 out.clear(); 7292 } 7293 boolean end = pos >= mHistoryBuffer.dataSize(); 7294 if (end) { 7295 return false; 7296 } 7297 7298 final long lastRealtime = out.time; 7299 final long lastWalltime = out.currentTime; 7300 readHistoryDelta(mHistoryBuffer, out); 7301 if (out.cmd != HistoryItem.CMD_CURRENT_TIME 7302 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) { 7303 out.currentTime = lastWalltime + (out.time - lastRealtime); 7304 } 7305 return true; 7306 } 7307 7308 @Override 7309 public void finishIteratingHistoryLocked() { 7310 mIteratingHistory = false; 7311 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize()); 7312 mReadHistoryStrings = null; 7313 } 7314 7315 @Override 7316 public long getHistoryBaseTime() { 7317 return mHistoryBaseTime; 7318 } 7319 7320 @Override 7321 public int getStartCount() { 7322 return mStartCount; 7323 } 7324 7325 public boolean isOnBattery() { 7326 return mOnBattery; 7327 } 7328 7329 public boolean isCharging() { 7330 return mCharging; 7331 } 7332 7333 public boolean isScreenOn() { 7334 return mScreenState == Display.STATE_ON; 7335 } 7336 7337 void initTimes(long uptime, long realtime) { 7338 mStartClockTime = System.currentTimeMillis(); 7339 mOnBatteryTimeBase.init(uptime, realtime); 7340 mOnBatteryScreenOffTimeBase.init(uptime, realtime); 7341 mRealtime = 0; 7342 mUptime = 0; 7343 mRealtimeStart = realtime; 7344 mUptimeStart = uptime; 7345 } 7346 7347 void initDischarge() { 7348 mLowDischargeAmountSinceCharge = 0; 7349 mHighDischargeAmountSinceCharge = 0; 7350 mDischargeAmountScreenOn = 0; 7351 mDischargeAmountScreenOnSinceCharge = 0; 7352 mDischargeAmountScreenOff = 0; 7353 mDischargeAmountScreenOffSinceCharge = 0; 7354 mDischargeStepTracker.init(); 7355 mChargeStepTracker.init(); 7356 } 7357 7358 public void resetAllStatsCmdLocked() { 7359 resetAllStatsLocked(); 7360 final long mSecUptime = SystemClock.uptimeMillis(); 7361 long uptime = mSecUptime * 1000; 7362 long mSecRealtime = SystemClock.elapsedRealtime(); 7363 long realtime = mSecRealtime * 1000; 7364 mDischargeStartLevel = mHistoryCur.batteryLevel; 7365 pullPendingStateUpdatesLocked(); 7366 addHistoryRecordLocked(mSecRealtime, mSecUptime); 7367 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel 7368 = mCurrentBatteryLevel = mHistoryCur.batteryLevel; 7369 mOnBatteryTimeBase.reset(uptime, realtime); 7370 mOnBatteryScreenOffTimeBase.reset(uptime, realtime); 7371 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) { 7372 if (mScreenState == Display.STATE_ON) { 7373 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel; 7374 mDischargeScreenOffUnplugLevel = 0; 7375 } else { 7376 mDischargeScreenOnUnplugLevel = 0; 7377 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel; 7378 } 7379 mDischargeAmountScreenOn = 0; 7380 mDischargeAmountScreenOff = 0; 7381 } 7382 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime); 7383 } 7384 7385 private void resetAllStatsLocked() { 7386 mStartCount = 0; 7387 initTimes(SystemClock.uptimeMillis() * 1000, SystemClock.elapsedRealtime() * 1000); 7388 mScreenOnTimer.reset(false); 7389 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) { 7390 mScreenBrightnessTimer[i].reset(false); 7391 } 7392 mInteractiveTimer.reset(false); 7393 mPowerSaveModeEnabledTimer.reset(false); 7394 mDeviceIdleModeEnabledTimer.reset(false); 7395 mDeviceIdlingTimer.reset(false); 7396 mPhoneOnTimer.reset(false); 7397 mAudioOnTimer.reset(false); 7398 mVideoOnTimer.reset(false); 7399 mFlashlightOnTimer.reset(false); 7400 mCameraOnTimer.reset(false); 7401 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) { 7402 mPhoneSignalStrengthsTimer[i].reset(false); 7403 } 7404 mPhoneSignalScanningTimer.reset(false); 7405 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) { 7406 mPhoneDataConnectionsTimer[i].reset(false); 7407 } 7408 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 7409 mNetworkByteActivityCounters[i].reset(false); 7410 mNetworkPacketActivityCounters[i].reset(false); 7411 } 7412 mMobileRadioActiveTimer.reset(false); 7413 mMobileRadioActivePerAppTimer.reset(false); 7414 mMobileRadioActiveAdjustedTime.reset(false); 7415 mMobileRadioActiveUnknownTime.reset(false); 7416 mMobileRadioActiveUnknownCount.reset(false); 7417 mWifiOnTimer.reset(false); 7418 mGlobalWifiRunningTimer.reset(false); 7419 for (int i=0; i<NUM_WIFI_STATES; i++) { 7420 mWifiStateTimer[i].reset(false); 7421 } 7422 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) { 7423 mWifiSupplStateTimer[i].reset(false); 7424 } 7425 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) { 7426 mWifiSignalStrengthsTimer[i].reset(false); 7427 } 7428 for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 7429 mBluetoothActivityCounters[i].reset(false); 7430 mWifiActivityCounters[i].reset(false); 7431 } 7432 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0; 7433 7434 for (int i=0; i<mUidStats.size(); i++) { 7435 if (mUidStats.valueAt(i).reset()) { 7436 mUidStats.remove(mUidStats.keyAt(i)); 7437 i--; 7438 } 7439 } 7440 7441 if (mKernelWakelockStats.size() > 0) { 7442 for (SamplingTimer timer : mKernelWakelockStats.values()) { 7443 mOnBatteryScreenOffTimeBase.remove(timer); 7444 } 7445 mKernelWakelockStats.clear(); 7446 } 7447 7448 if (mWakeupReasonStats.size() > 0) { 7449 for (SamplingTimer timer : mWakeupReasonStats.values()) { 7450 mOnBatteryTimeBase.remove(timer); 7451 } 7452 mWakeupReasonStats.clear(); 7453 } 7454 7455 mLastHistoryStepDetails = null; 7456 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0; 7457 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0; 7458 mLastStepCpuUserTime = mCurStepCpuUserTime = 0; 7459 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0; 7460 mLastStepStatUserTime = mCurStepStatUserTime = 0; 7461 mLastStepStatSystemTime = mCurStepStatSystemTime = 0; 7462 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0; 7463 mLastStepStatIrqTime = mCurStepStatIrqTime = 0; 7464 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0; 7465 mLastStepStatIdleTime = mCurStepStatIdleTime = 0; 7466 7467 initDischarge(); 7468 7469 clearHistoryLocked(); 7470 } 7471 7472 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) { 7473 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) { 7474 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) { 7475 // Not recording process starts/stops. 7476 continue; 7477 } 7478 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i); 7479 if (active == null) { 7480 continue; 7481 } 7482 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) { 7483 SparseIntArray uids = ent.getValue(); 7484 for (int j=0; j<uids.size(); j++) { 7485 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(), 7486 uids.keyAt(j)); 7487 } 7488 } 7489 } 7490 } 7491 7492 void updateDischargeScreenLevelsLocked(boolean oldScreenOn, boolean newScreenOn) { 7493 if (oldScreenOn) { 7494 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel; 7495 if (diff > 0) { 7496 mDischargeAmountScreenOn += diff; 7497 mDischargeAmountScreenOnSinceCharge += diff; 7498 } 7499 } else { 7500 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel; 7501 if (diff > 0) { 7502 mDischargeAmountScreenOff += diff; 7503 mDischargeAmountScreenOffSinceCharge += diff; 7504 } 7505 } 7506 if (newScreenOn) { 7507 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel; 7508 mDischargeScreenOffUnplugLevel = 0; 7509 } else { 7510 mDischargeScreenOnUnplugLevel = 0; 7511 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel; 7512 } 7513 } 7514 7515 public void pullPendingStateUpdatesLocked() { 7516 if (mOnBatteryInternal) { 7517 final boolean screenOn = mScreenState == Display.STATE_ON; 7518 updateDischargeScreenLevelsLocked(screenOn, screenOn); 7519 } 7520 } 7521 7522 private String[] mMobileIfaces = EmptyArray.STRING; 7523 private String[] mWifiIfaces = EmptyArray.STRING; 7524 7525 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory(); 7526 7527 private static final int NETWORK_STATS_LAST = 0; 7528 private static final int NETWORK_STATS_NEXT = 1; 7529 private static final int NETWORK_STATS_DELTA = 2; 7530 7531 private final NetworkStats[] mMobileNetworkStats = new NetworkStats[] { 7532 new NetworkStats(SystemClock.elapsedRealtime(), 50), 7533 new NetworkStats(SystemClock.elapsedRealtime(), 50), 7534 new NetworkStats(SystemClock.elapsedRealtime(), 50) 7535 }; 7536 7537 private final NetworkStats[] mWifiNetworkStats = new NetworkStats[] { 7538 new NetworkStats(SystemClock.elapsedRealtime(), 50), 7539 new NetworkStats(SystemClock.elapsedRealtime(), 50), 7540 new NetworkStats(SystemClock.elapsedRealtime(), 50) 7541 }; 7542 7543 /** 7544 * Retrieves the delta of network stats for the given network ifaces. Uses networkStatsBuffer 7545 * as a buffer of NetworkStats objects to cycle through when computing deltas. 7546 */ 7547 private NetworkStats getNetworkStatsDeltaLocked(String[] ifaces, 7548 NetworkStats[] networkStatsBuffer) 7549 throws IOException { 7550 if (!SystemProperties.getBoolean(NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED, 7551 false)) { 7552 return null; 7553 } 7554 7555 final NetworkStats stats = mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, 7556 ifaces, NetworkStats.TAG_NONE, networkStatsBuffer[NETWORK_STATS_NEXT]); 7557 networkStatsBuffer[NETWORK_STATS_DELTA] = NetworkStats.subtract(stats, 7558 networkStatsBuffer[NETWORK_STATS_LAST], null, null, 7559 networkStatsBuffer[NETWORK_STATS_DELTA]); 7560 networkStatsBuffer[NETWORK_STATS_NEXT] = networkStatsBuffer[NETWORK_STATS_LAST]; 7561 networkStatsBuffer[NETWORK_STATS_LAST] = stats; 7562 return networkStatsBuffer[NETWORK_STATS_DELTA]; 7563 } 7564 7565 /** 7566 * Distribute WiFi energy info and network traffic to apps. 7567 * @param info The energy information from the WiFi controller. 7568 */ 7569 public void updateWifiStateLocked(@Nullable final WifiActivityEnergyInfo info) { 7570 if (DEBUG_ENERGY) { 7571 Slog.d(TAG, "Updating wifi stats"); 7572 } 7573 7574 final long elapsedRealtimeMs = SystemClock.elapsedRealtime(); 7575 NetworkStats delta = null; 7576 try { 7577 if (!ArrayUtils.isEmpty(mWifiIfaces)) { 7578 delta = getNetworkStatsDeltaLocked(mWifiIfaces, mWifiNetworkStats); 7579 } 7580 } catch (IOException e) { 7581 Slog.wtf(TAG, "Failed to get wifi network stats", e); 7582 return; 7583 } 7584 7585 if (!mOnBatteryInternal) { 7586 return; 7587 } 7588 7589 SparseLongArray rxPackets = new SparseLongArray(); 7590 SparseLongArray txPackets = new SparseLongArray(); 7591 long totalTxPackets = 0; 7592 long totalRxPackets = 0; 7593 if (delta != null) { 7594 final int size = delta.size(); 7595 for (int i = 0; i < size; i++) { 7596 final NetworkStats.Entry entry = delta.getValues(i, mTmpNetworkStatsEntry); 7597 7598 if (DEBUG_ENERGY) { 7599 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes 7600 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets 7601 + " txPackets=" + entry.txPackets); 7602 } 7603 7604 if (entry.rxBytes == 0 || entry.txBytes == 0) { 7605 continue; 7606 } 7607 7608 final Uid u = getUidStatsLocked(mapUid(entry.uid)); 7609 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes, 7610 entry.rxPackets); 7611 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes, 7612 entry.txPackets); 7613 rxPackets.put(u.getUid(), entry.rxPackets); 7614 txPackets.put(u.getUid(), entry.txPackets); 7615 7616 // Sum the total number of packets so that the Rx Power and Tx Power can 7617 // be evenly distributed amongst the apps. 7618 totalRxPackets += entry.rxPackets; 7619 totalTxPackets += entry.txPackets; 7620 7621 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked( 7622 entry.rxBytes); 7623 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked( 7624 entry.txBytes); 7625 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked( 7626 entry.rxPackets); 7627 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked( 7628 entry.txPackets); 7629 } 7630 } 7631 7632 if (info != null) { 7633 mHasWifiEnergyReporting = true; 7634 7635 // Measured in mAms 7636 final long txTimeMs = info.getControllerTxTimeMillis(); 7637 final long rxTimeMs = info.getControllerRxTimeMillis(); 7638 final long idleTimeMs = info.getControllerIdleTimeMillis(); 7639 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs; 7640 7641 long leftOverRxTimeMs = rxTimeMs; 7642 7643 if (DEBUG_ENERGY) { 7644 Slog.d(TAG, "------ BEGIN WiFi power blaming ------"); 7645 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms"); 7646 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms"); 7647 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms"); 7648 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms"); 7649 } 7650 7651 long totalWifiLockTimeMs = 0; 7652 long totalScanTimeMs = 0; 7653 7654 // On the first pass, collect some totals so that we can normalize power 7655 // calculations if we need to. 7656 final int uidStatsSize = mUidStats.size(); 7657 for (int i = 0; i < uidStatsSize; i++) { 7658 final Uid uid = mUidStats.valueAt(i); 7659 7660 // Sum the total scan power for all apps. 7661 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked( 7662 elapsedRealtimeMs * 1000) / 1000; 7663 7664 // Sum the total time holding wifi lock for all apps. 7665 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked( 7666 elapsedRealtimeMs * 1000) / 1000; 7667 } 7668 7669 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) { 7670 Slog.d(TAG, " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > " 7671 + rxTimeMs + " ms). Normalizing scan time."); 7672 } 7673 7674 // Actually assign and distribute power usage to apps. 7675 for (int i = 0; i < uidStatsSize; i++) { 7676 final Uid uid = mUidStats.valueAt(i); 7677 7678 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked( 7679 elapsedRealtimeMs * 1000) / 1000; 7680 if (scanTimeSinceMarkMs > 0) { 7681 // Set the new mark so that next time we get new data since this point. 7682 uid.mWifiScanTimer.setMark(elapsedRealtimeMs); 7683 7684 if (totalScanTimeMs > rxTimeMs) { 7685 // Our total scan time is more than the reported Rx time. 7686 // This is possible because the cost of a scan is approximate. 7687 // Let's normalize the result so that we evenly blame each app 7688 // scanning. 7689 // 7690 // This means that we may have apps that received packets not be blamed 7691 // for this, but this is fine as scans are relatively more expensive. 7692 scanTimeSinceMarkMs = (rxTimeMs * scanTimeSinceMarkMs) / totalScanTimeMs; 7693 } 7694 7695 if (DEBUG_ENERGY) { 7696 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": " 7697 + scanTimeSinceMarkMs + " ms)"); 7698 } 7699 uid.noteWifiControllerActivityLocked(CONTROLLER_RX_TIME, scanTimeSinceMarkMs); 7700 leftOverRxTimeMs -= scanTimeSinceMarkMs; 7701 } 7702 7703 // Distribute evenly the power consumed while Idle to each app holding a WiFi 7704 // lock. 7705 final long wifiLockTimeSinceMarkMs = uid.mFullWifiLockTimer.getTimeSinceMarkLocked( 7706 elapsedRealtimeMs * 1000) / 1000; 7707 if (wifiLockTimeSinceMarkMs > 0) { 7708 // Set the new mark so that next time we get new data since this point. 7709 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs); 7710 7711 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs) 7712 / totalWifiLockTimeMs; 7713 if (DEBUG_ENERGY) { 7714 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": " 7715 + myIdleTimeMs + " ms"); 7716 } 7717 uid.noteWifiControllerActivityLocked(CONTROLLER_IDLE_TIME, myIdleTimeMs); 7718 } 7719 } 7720 7721 if (DEBUG_ENERGY) { 7722 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms"); 7723 } 7724 7725 // Distribute the Tx power appropriately between all apps that transmitted packets. 7726 for (int i = 0; i < txPackets.size(); i++) { 7727 final Uid uid = getUidStatsLocked(txPackets.keyAt(i)); 7728 final long myTxTimeMs = (txPackets.valueAt(i) * txTimeMs) / totalTxPackets; 7729 if (DEBUG_ENERGY) { 7730 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms"); 7731 } 7732 uid.noteWifiControllerActivityLocked(CONTROLLER_TX_TIME, myTxTimeMs); 7733 } 7734 7735 // Distribute the remaining Rx power appropriately between all apps that received 7736 // packets. 7737 for (int i = 0; i < rxPackets.size(); i++) { 7738 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i)); 7739 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs) / totalRxPackets; 7740 if (DEBUG_ENERGY) { 7741 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms"); 7742 } 7743 uid.noteWifiControllerActivityLocked(CONTROLLER_RX_TIME, myRxTimeMs); 7744 } 7745 7746 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper. 7747 7748 // Update WiFi controller stats. 7749 mWifiActivityCounters[CONTROLLER_RX_TIME].addCountLocked( 7750 info.getControllerRxTimeMillis()); 7751 mWifiActivityCounters[CONTROLLER_TX_TIME].addCountLocked( 7752 info.getControllerTxTimeMillis()); 7753 mWifiActivityCounters[CONTROLLER_IDLE_TIME].addCountLocked( 7754 info.getControllerIdleTimeMillis()); 7755 7756 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V. 7757 final double opVolt = mPowerProfile.getAveragePower( 7758 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0; 7759 if (opVolt != 0) { 7760 // We store the power drain as mAms. 7761 mWifiActivityCounters[CONTROLLER_POWER_DRAIN].addCountLocked( 7762 (long)(info.getControllerEnergyUsed() / opVolt)); 7763 } 7764 } 7765 } 7766 7767 /** 7768 * Distribute Cell radio energy info and network traffic to apps. 7769 */ 7770 public void updateMobileRadioStateLocked(final long elapsedRealtimeMs) { 7771 if (DEBUG_ENERGY) { 7772 Slog.d(TAG, "Updating mobile radio stats"); 7773 } 7774 7775 NetworkStats delta = null; 7776 try { 7777 if (!ArrayUtils.isEmpty(mMobileIfaces)) { 7778 delta = getNetworkStatsDeltaLocked(mMobileIfaces, mMobileNetworkStats); 7779 } 7780 } catch (IOException e) { 7781 Slog.wtf(TAG, "Failed to get mobile network stats", e); 7782 return; 7783 } 7784 7785 if (delta == null || !mOnBatteryInternal) { 7786 return; 7787 } 7788 7789 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked( 7790 elapsedRealtimeMs * 1000); 7791 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs); 7792 long totalPackets = delta.getTotalPackets(); 7793 7794 final int size = delta.size(); 7795 for (int i = 0; i < size; i++) { 7796 final NetworkStats.Entry entry = delta.getValues(i, mTmpNetworkStatsEntry); 7797 7798 if (entry.rxBytes == 0 || entry.txBytes == 0) { 7799 continue; 7800 } 7801 7802 if (DEBUG_ENERGY) { 7803 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes 7804 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets 7805 + " txPackets=" + entry.txPackets); 7806 } 7807 7808 final Uid u = getUidStatsLocked(mapUid(entry.uid)); 7809 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes, 7810 entry.rxPackets); 7811 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes, 7812 entry.txPackets); 7813 7814 if (radioTime > 0) { 7815 // Distribute total radio active time in to this app. 7816 long appPackets = entry.rxPackets + entry.txPackets; 7817 long appRadioTime = (radioTime*appPackets)/totalPackets; 7818 u.noteMobileRadioActiveTimeLocked(appRadioTime); 7819 // Remove this app from the totals, so that we don't lose any time 7820 // due to rounding. 7821 radioTime -= appRadioTime; 7822 totalPackets -= appPackets; 7823 } 7824 7825 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked( 7826 entry.rxBytes); 7827 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked( 7828 entry.txBytes); 7829 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked( 7830 entry.rxPackets); 7831 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked( 7832 entry.txPackets); 7833 } 7834 7835 if (radioTime > 0) { 7836 // Whoops, there is some radio time we can't blame on an app! 7837 mMobileRadioActiveUnknownTime.addCountLocked(radioTime); 7838 mMobileRadioActiveUnknownCount.addCountLocked(1); 7839 } 7840 } 7841 7842 /** 7843 * Distribute Bluetooth energy info and network traffic to apps. 7844 * @param info The energy information from the bluetooth controller. 7845 */ 7846 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) { 7847 if (DEBUG_ENERGY) { 7848 Slog.d(TAG, "Updating bluetooth stats"); 7849 } 7850 7851 if (info != null && mOnBatteryInternal) { 7852 mHasBluetoothEnergyReporting = true; 7853 mBluetoothActivityCounters[CONTROLLER_RX_TIME].addCountLocked( 7854 info.getControllerRxTimeMillis()); 7855 mBluetoothActivityCounters[CONTROLLER_TX_TIME].addCountLocked( 7856 info.getControllerTxTimeMillis()); 7857 mBluetoothActivityCounters[CONTROLLER_IDLE_TIME].addCountLocked( 7858 info.getControllerIdleTimeMillis()); 7859 7860 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V. 7861 final double opVolt = mPowerProfile.getAveragePower( 7862 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0; 7863 if (opVolt != 0) { 7864 // We store the power drain as mAms. 7865 mBluetoothActivityCounters[CONTROLLER_POWER_DRAIN].addCountLocked( 7866 (long) (info.getControllerEnergyUsed() / opVolt)); 7867 } 7868 } 7869 } 7870 7871 /** 7872 * Read and distribute kernel wake lock use across apps. 7873 */ 7874 public void updateKernelWakelocksLocked() { 7875 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats( 7876 mTmpWakelockStats); 7877 if (wakelockStats == null) { 7878 // Not crashing might make board bringup easier. 7879 Slog.w(TAG, "Couldn't get kernel wake lock stats"); 7880 return; 7881 } 7882 7883 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) { 7884 String name = ent.getKey(); 7885 KernelWakelockStats.Entry kws = ent.getValue(); 7886 7887 SamplingTimer kwlt = mKernelWakelockStats.get(name); 7888 if (kwlt == null) { 7889 kwlt = new SamplingTimer(mOnBatteryScreenOffTimeBase, 7890 true /* track reported val */); 7891 mKernelWakelockStats.put(name, kwlt); 7892 } 7893 kwlt.updateCurrentReportedCount(kws.mCount); 7894 kwlt.updateCurrentReportedTotalTime(kws.mTotalTime); 7895 kwlt.setUpdateVersion(kws.mVersion); 7896 } 7897 7898 if (wakelockStats.size() != mKernelWakelockStats.size()) { 7899 // Set timers to stale if they didn't appear in /proc/wakelocks this time. 7900 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) { 7901 SamplingTimer st = ent.getValue(); 7902 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) { 7903 st.setStale(); 7904 } 7905 } 7906 } 7907 } 7908 7909 // We use an anonymous class to access these variables, 7910 // so they can't live on the stack or they'd have to be 7911 // final MutableLong objects (more allocations). 7912 // Used in updateCpuTimeLocked(). 7913 long mTempTotalCpuUserTimeUs; 7914 long mTempTotalCpuSystemTimeUs; 7915 7916 /** 7917 * Read and distribute CPU usage across apps. If their are partial wakelocks being held 7918 * and we are on battery with screen off, we give more of the cpu time to those apps holding 7919 * wakelocks. If the screen is on, we just assign the actual cpu time an app used. 7920 */ 7921 public void updateCpuTimeLocked() { 7922 if (DEBUG_ENERGY_CPU) { 7923 Slog.d(TAG, "!Cpu updating!"); 7924 } 7925 7926 // Holding a wakelock costs more than just using the cpu. 7927 // Currently, we assign only half the cpu time to an app that is running but 7928 // not holding a wakelock. The apps holding wakelocks get the rest of the blame. 7929 // If no app is holding a wakelock, then the distribution is normal. 7930 final int wakelockWeight = 50; 7931 7932 // Read the time spent at various cpu frequencies. 7933 final int cpuSpeedSteps = getCpuSpeedSteps(); 7934 final long[] cpuSpeeds = mKernelCpuSpeedReader.readDelta(); 7935 7936 int numWakelocks = 0; 7937 7938 // Calculate how many wakelocks we have to distribute amongst. The system is excluded. 7939 // Only distribute cpu power to wakelocks if the screen is off and we're on battery. 7940 final int numPartialTimers = mPartialTimers.size(); 7941 if (mOnBatteryScreenOffTimeBase.isRunning()) { 7942 for (int i = 0; i < numPartialTimers; i++) { 7943 final StopwatchTimer timer = mPartialTimers.get(i); 7944 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) { 7945 // Since the collection and blaming of wakelocks can be scheduled to run after 7946 // some delay, the mPartialTimers list may have new entries. We can't blame 7947 // the newly added timer for past cpu time, so we only consider timers that 7948 // were present for one round of collection. Once a timer has gone through 7949 // a round of collection, its mInList field is set to true. 7950 numWakelocks++; 7951 } 7952 } 7953 } 7954 7955 final int numWakelocksF = numWakelocks; 7956 mTempTotalCpuUserTimeUs = 0; 7957 mTempTotalCpuSystemTimeUs = 0; 7958 7959 // Read the CPU data for each UID. This will internally generate a snapshot so next time 7960 // we read, we get a delta. If we are to distribute the cpu time, then do so. Otherwise 7961 // we just ignore the data. 7962 final long startTimeMs = SystemClock.elapsedRealtime(); 7963 mKernelUidCpuTimeReader.readDelta(!mOnBatteryInternal ? null : 7964 new KernelUidCpuTimeReader.Callback() { 7965 @Override 7966 public void onUidCpuTime(int uid, long userTimeUs, long systemTimeUs) { 7967 final Uid u = getUidStatsLocked(mapUid(uid)); 7968 7969 // Accumulate the total system and user time. 7970 mTempTotalCpuUserTimeUs += userTimeUs; 7971 mTempTotalCpuSystemTimeUs += systemTimeUs; 7972 7973 StringBuilder sb = null; 7974 if (DEBUG_ENERGY_CPU) { 7975 sb = new StringBuilder(); 7976 sb.append(" got time for uid=").append(u.mUid).append(": u="); 7977 TimeUtils.formatDuration(userTimeUs / 1000, sb); 7978 sb.append(" s="); 7979 TimeUtils.formatDuration(systemTimeUs / 1000, sb); 7980 sb.append("\n"); 7981 } 7982 7983 if (numWakelocksF > 0) { 7984 // We have wakelocks being held, so only give a portion of the 7985 // time to the process. The rest will be distributed among wakelock 7986 // holders. 7987 userTimeUs = (userTimeUs * wakelockWeight) / 100; 7988 systemTimeUs = (systemTimeUs * wakelockWeight) / 100; 7989 } 7990 7991 if (sb != null) { 7992 sb.append(" adding to uid=").append(u.mUid).append(": u="); 7993 TimeUtils.formatDuration(userTimeUs / 1000, sb); 7994 sb.append(" s="); 7995 TimeUtils.formatDuration(systemTimeUs / 1000, sb); 7996 Slog.d(TAG, sb.toString()); 7997 } 7998 7999 u.mUserCpuTime.addCountLocked(userTimeUs); 8000 u.mSystemCpuTime.addCountLocked(systemTimeUs); 8001 8002 // Add the cpu speeds to this UID. These are used as a ratio 8003 // for computing the power this UID used. 8004 for (int i = 0; i < cpuSpeedSteps; i++) { 8005 if (u.mSpeedBins[i] == null) { 8006 u.mSpeedBins[i] = new LongSamplingCounter(mOnBatteryTimeBase); 8007 } 8008 u.mSpeedBins[i].addCountLocked(cpuSpeeds[i]); 8009 } 8010 } 8011 }); 8012 8013 if (DEBUG_ENERGY_CPU) { 8014 Slog.d(TAG, "Reading cpu stats took " + (SystemClock.elapsedRealtime() - startTimeMs) + 8015 " ms"); 8016 } 8017 8018 if (mOnBatteryInternal && numWakelocks > 0) { 8019 // Distribute a portion of the total cpu time to wakelock holders. 8020 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - wakelockWeight)) / 100; 8021 mTempTotalCpuSystemTimeUs = 8022 (mTempTotalCpuSystemTimeUs * (100 - wakelockWeight)) / 100; 8023 8024 for (int i = 0; i < numPartialTimers; i++) { 8025 final StopwatchTimer timer = mPartialTimers.get(i); 8026 8027 // The system does not share any blame, as it is usually holding the wakelock 8028 // on behalf of an app. 8029 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) { 8030 int userTimeUs = (int) (mTempTotalCpuUserTimeUs / numWakelocks); 8031 int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / numWakelocks); 8032 8033 if (DEBUG_ENERGY_CPU) { 8034 StringBuilder sb = new StringBuilder(); 8035 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid) 8036 .append(": u="); 8037 TimeUtils.formatDuration(userTimeUs / 1000, sb); 8038 sb.append(" s="); 8039 TimeUtils.formatDuration(systemTimeUs / 1000, sb); 8040 Slog.d(TAG, sb.toString()); 8041 } 8042 8043 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs); 8044 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs); 8045 8046 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*"); 8047 proc.addCpuTimeLocked(userTimeUs, systemTimeUs); 8048 8049 mTempTotalCpuUserTimeUs -= userTimeUs; 8050 mTempTotalCpuSystemTimeUs -= systemTimeUs; 8051 numWakelocks--; 8052 } 8053 } 8054 8055 if (mTempTotalCpuUserTimeUs > 0 || mTempTotalCpuSystemTimeUs > 0) { 8056 // Anything left over is given to the system. 8057 if (DEBUG_ENERGY_CPU) { 8058 StringBuilder sb = new StringBuilder(); 8059 sb.append(" Distributing lost time to system: u="); 8060 TimeUtils.formatDuration(mTempTotalCpuUserTimeUs / 1000, sb); 8061 sb.append(" s="); 8062 TimeUtils.formatDuration(mTempTotalCpuSystemTimeUs / 1000, sb); 8063 Slog.d(TAG, sb.toString()); 8064 } 8065 8066 final Uid u = getUidStatsLocked(Process.SYSTEM_UID); 8067 u.mUserCpuTime.addCountLocked(mTempTotalCpuUserTimeUs); 8068 u.mSystemCpuTime.addCountLocked(mTempTotalCpuSystemTimeUs); 8069 8070 final Uid.Proc proc = u.getProcessStatsLocked("*lost*"); 8071 proc.addCpuTimeLocked((int) mTempTotalCpuUserTimeUs, 8072 (int) mTempTotalCpuSystemTimeUs); 8073 } 8074 } 8075 8076 // See if there is a difference in wakelocks between this collection and the last 8077 // collection. 8078 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) { 8079 // No difference, so each timer is now considered for the next collection. 8080 for (int i = 0; i < numPartialTimers; i++) { 8081 mPartialTimers.get(i).mInList = true; 8082 } 8083 } else { 8084 // The lists are different, meaning we added (or removed a timer) since the last 8085 // collection. 8086 final int numLastPartialTimers = mLastPartialTimers.size(); 8087 for (int i = 0; i < numLastPartialTimers; i++) { 8088 mLastPartialTimers.get(i).mInList = false; 8089 } 8090 mLastPartialTimers.clear(); 8091 8092 // Mark the current timers as gone through a collection. 8093 for (int i = 0; i < numPartialTimers; i++) { 8094 final StopwatchTimer timer = mPartialTimers.get(i); 8095 timer.mInList = true; 8096 mLastPartialTimers.add(timer); 8097 } 8098 } 8099 } 8100 8101 boolean setChargingLocked(boolean charging) { 8102 if (mCharging != charging) { 8103 mCharging = charging; 8104 if (charging) { 8105 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG; 8106 } else { 8107 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG; 8108 } 8109 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING); 8110 return true; 8111 } 8112 return false; 8113 } 8114 8115 void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime, final boolean onBattery, 8116 final int oldStatus, final int level) { 8117 boolean doWrite = false; 8118 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE); 8119 m.arg1 = onBattery ? 1 : 0; 8120 mHandler.sendMessage(m); 8121 8122 final long uptime = mSecUptime * 1000; 8123 final long realtime = mSecRealtime * 1000; 8124 final boolean screenOn = mScreenState == Display.STATE_ON; 8125 if (onBattery) { 8126 // We will reset our status if we are unplugging after the 8127 // battery was last full, or the level is at 100, or 8128 // we have gone through a significant charge (from a very low 8129 // level to a now very high level). 8130 boolean reset = false; 8131 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL 8132 || level >= 90 8133 || (mDischargeCurrentLevel < 20 && level >= 80) 8134 || (getHighDischargeAmountSinceCharge() >= 200 8135 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) { 8136 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus 8137 + " dischargeLevel=" + mDischargeCurrentLevel 8138 + " lowAmount=" + getLowDischargeAmountSinceCharge() 8139 + " highAmount=" + getHighDischargeAmountSinceCharge()); 8140 // Before we write, collect a snapshot of the final aggregated 8141 // stats to be reported in the next checkin. Only do this if we have 8142 // a sufficient amount of data to make it interesting. 8143 if (getLowDischargeAmountSinceCharge() >= 20) { 8144 final Parcel parcel = Parcel.obtain(); 8145 writeSummaryToParcel(parcel, true); 8146 BackgroundThread.getHandler().post(new Runnable() { 8147 @Override public void run() { 8148 synchronized (mCheckinFile) { 8149 FileOutputStream stream = null; 8150 try { 8151 stream = mCheckinFile.startWrite(); 8152 stream.write(parcel.marshall()); 8153 stream.flush(); 8154 FileUtils.sync(stream); 8155 stream.close(); 8156 mCheckinFile.finishWrite(stream); 8157 } catch (IOException e) { 8158 Slog.w("BatteryStats", 8159 "Error writing checkin battery statistics", e); 8160 mCheckinFile.failWrite(stream); 8161 } finally { 8162 parcel.recycle(); 8163 } 8164 } 8165 } 8166 }); 8167 } 8168 doWrite = true; 8169 resetAllStatsLocked(); 8170 mDischargeStartLevel = level; 8171 reset = true; 8172 mDischargeStepTracker.init(); 8173 } 8174 if (mCharging) { 8175 setChargingLocked(false); 8176 } 8177 mLastChargingStateLevel = level; 8178 mOnBattery = mOnBatteryInternal = true; 8179 mLastDischargeStepLevel = level; 8180 mMinDischargeStepLevel = level; 8181 mDischargeStepTracker.clearTime(); 8182 mDailyDischargeStepTracker.clearTime(); 8183 mInitStepMode = mCurStepMode; 8184 mModStepMode = 0; 8185 pullPendingStateUpdatesLocked(); 8186 mHistoryCur.batteryLevel = (byte)level; 8187 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG; 8188 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: " 8189 + Integer.toHexString(mHistoryCur.states)); 8190 if (reset) { 8191 mRecordingHistory = true; 8192 startRecordingHistory(mSecRealtime, mSecUptime, reset); 8193 } 8194 addHistoryRecordLocked(mSecRealtime, mSecUptime); 8195 mDischargeCurrentLevel = mDischargeUnplugLevel = level; 8196 if (screenOn) { 8197 mDischargeScreenOnUnplugLevel = level; 8198 mDischargeScreenOffUnplugLevel = 0; 8199 } else { 8200 mDischargeScreenOnUnplugLevel = 0; 8201 mDischargeScreenOffUnplugLevel = level; 8202 } 8203 mDischargeAmountScreenOn = 0; 8204 mDischargeAmountScreenOff = 0; 8205 updateTimeBasesLocked(true, !screenOn, uptime, realtime); 8206 } else { 8207 mLastChargingStateLevel = level; 8208 mOnBattery = mOnBatteryInternal = false; 8209 pullPendingStateUpdatesLocked(); 8210 mHistoryCur.batteryLevel = (byte)level; 8211 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG; 8212 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: " 8213 + Integer.toHexString(mHistoryCur.states)); 8214 addHistoryRecordLocked(mSecRealtime, mSecUptime); 8215 mDischargeCurrentLevel = mDischargePlugLevel = level; 8216 if (level < mDischargeUnplugLevel) { 8217 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1; 8218 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level; 8219 } 8220 updateDischargeScreenLevelsLocked(screenOn, screenOn); 8221 updateTimeBasesLocked(false, !screenOn, uptime, realtime); 8222 mChargeStepTracker.init(); 8223 mLastChargeStepLevel = level; 8224 mMaxChargeStepLevel = level; 8225 mInitStepMode = mCurStepMode; 8226 mModStepMode = 0; 8227 } 8228 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) { 8229 if (mFile != null) { 8230 writeAsyncLocked(); 8231 } 8232 } 8233 } 8234 8235 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs, 8236 boolean reset) { 8237 mRecordingHistory = true; 8238 mHistoryCur.currentTime = System.currentTimeMillis(); 8239 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, 8240 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME, 8241 mHistoryCur); 8242 mHistoryCur.currentTime = 0; 8243 if (reset) { 8244 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs); 8245 } 8246 } 8247 8248 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs, 8249 final long uptimeMs) { 8250 if (mRecordingHistory) { 8251 mHistoryCur.currentTime = currentTime; 8252 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_CURRENT_TIME, 8253 mHistoryCur); 8254 mHistoryCur.currentTime = 0; 8255 } 8256 } 8257 8258 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) { 8259 if (mRecordingHistory) { 8260 mHistoryCur.currentTime = System.currentTimeMillis(); 8261 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_SHUTDOWN, 8262 mHistoryCur); 8263 mHistoryCur.currentTime = 0; 8264 } 8265 } 8266 8267 private void scheduleSyncExternalStatsLocked(String reason) { 8268 if (mExternalSync != null) { 8269 mExternalSync.scheduleSync(reason); 8270 } 8271 } 8272 8273 private void scheduleSyncExternalWifiStatsLocked(String reason) { 8274 if (mExternalSync != null) { 8275 mExternalSync.scheduleWifiSync(reason); 8276 } 8277 } 8278 8279 // This should probably be exposed in the API, though it's not critical 8280 public static final int BATTERY_PLUGGED_NONE = 0; 8281 8282 public void setBatteryStateLocked(int status, int health, int plugType, int level, 8283 int temp, int volt) { 8284 final boolean onBattery = plugType == BATTERY_PLUGGED_NONE; 8285 final long uptime = SystemClock.uptimeMillis(); 8286 final long elapsedRealtime = SystemClock.elapsedRealtime(); 8287 if (!mHaveBatteryLevel) { 8288 mHaveBatteryLevel = true; 8289 // We start out assuming that the device is plugged in (not 8290 // on battery). If our first report is now that we are indeed 8291 // plugged in, then twiddle our state to correctly reflect that 8292 // since we won't be going through the full setOnBattery(). 8293 if (onBattery == mOnBattery) { 8294 if (onBattery) { 8295 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG; 8296 } else { 8297 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG; 8298 } 8299 } 8300 // Always start out assuming charging, that will be updated later. 8301 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG; 8302 mHistoryCur.batteryStatus = (byte)status; 8303 mHistoryCur.batteryLevel = (byte)level; 8304 mMaxChargeStepLevel = mMinDischargeStepLevel = 8305 mLastChargeStepLevel = mLastDischargeStepLevel = level; 8306 mLastChargingStateLevel = level; 8307 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) { 8308 recordDailyStatsIfNeededLocked(level >= 100 && onBattery); 8309 } 8310 int oldStatus = mHistoryCur.batteryStatus; 8311 if (onBattery) { 8312 mDischargeCurrentLevel = level; 8313 if (!mRecordingHistory) { 8314 mRecordingHistory = true; 8315 startRecordingHistory(elapsedRealtime, uptime, true); 8316 } 8317 } else if (level < 96) { 8318 if (!mRecordingHistory) { 8319 mRecordingHistory = true; 8320 startRecordingHistory(elapsedRealtime, uptime, true); 8321 } 8322 } 8323 mCurrentBatteryLevel = level; 8324 if (mDischargePlugLevel < 0) { 8325 mDischargePlugLevel = level; 8326 } 8327 if (onBattery != mOnBattery) { 8328 mHistoryCur.batteryLevel = (byte)level; 8329 mHistoryCur.batteryStatus = (byte)status; 8330 mHistoryCur.batteryHealth = (byte)health; 8331 mHistoryCur.batteryPlugType = (byte)plugType; 8332 mHistoryCur.batteryTemperature = (short)temp; 8333 mHistoryCur.batteryVoltage = (char)volt; 8334 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level); 8335 } else { 8336 boolean changed = false; 8337 if (mHistoryCur.batteryLevel != level) { 8338 mHistoryCur.batteryLevel = (byte)level; 8339 changed = true; 8340 8341 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record 8342 // which will pull external stats. 8343 scheduleSyncExternalStatsLocked("battery-level"); 8344 } 8345 if (mHistoryCur.batteryStatus != status) { 8346 mHistoryCur.batteryStatus = (byte)status; 8347 changed = true; 8348 } 8349 if (mHistoryCur.batteryHealth != health) { 8350 mHistoryCur.batteryHealth = (byte)health; 8351 changed = true; 8352 } 8353 if (mHistoryCur.batteryPlugType != plugType) { 8354 mHistoryCur.batteryPlugType = (byte)plugType; 8355 changed = true; 8356 } 8357 if (temp >= (mHistoryCur.batteryTemperature+10) 8358 || temp <= (mHistoryCur.batteryTemperature-10)) { 8359 mHistoryCur.batteryTemperature = (short)temp; 8360 changed = true; 8361 } 8362 if (volt > (mHistoryCur.batteryVoltage+20) 8363 || volt < (mHistoryCur.batteryVoltage-20)) { 8364 mHistoryCur.batteryVoltage = (char)volt; 8365 changed = true; 8366 } 8367 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT) 8368 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT) 8369 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT); 8370 if (onBattery) { 8371 changed |= setChargingLocked(false); 8372 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) { 8373 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level, 8374 modeBits, elapsedRealtime); 8375 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level, 8376 modeBits, elapsedRealtime); 8377 mLastDischargeStepLevel = level; 8378 mMinDischargeStepLevel = level; 8379 mInitStepMode = mCurStepMode; 8380 mModStepMode = 0; 8381 } 8382 } else { 8383 if (level >= 90) { 8384 // If the battery level is at least 90%, always consider the device to be 8385 // charging even if it happens to go down a level. 8386 changed |= setChargingLocked(true); 8387 mLastChargeStepLevel = level; 8388 } if (!mCharging) { 8389 if (mLastChargeStepLevel < level) { 8390 // We have not reporting that we are charging, but the level has now 8391 // gone up, so consider the state to be charging. 8392 changed |= setChargingLocked(true); 8393 mLastChargeStepLevel = level; 8394 } 8395 } else { 8396 if (mLastChargeStepLevel > level) { 8397 // We had reported that the device was charging, but here we are with 8398 // power connected and the level going down. Looks like the current 8399 // power supplied isn't enough, so consider the device to now be 8400 // discharging. 8401 changed |= setChargingLocked(false); 8402 mLastChargeStepLevel = level; 8403 } 8404 } 8405 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) { 8406 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel, 8407 modeBits, elapsedRealtime); 8408 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel, 8409 modeBits, elapsedRealtime); 8410 mLastChargeStepLevel = level; 8411 mMaxChargeStepLevel = level; 8412 mInitStepMode = mCurStepMode; 8413 mModStepMode = 0; 8414 } 8415 } 8416 if (changed) { 8417 addHistoryRecordLocked(elapsedRealtime, uptime); 8418 } 8419 } 8420 if (!onBattery && status == BatteryManager.BATTERY_STATUS_FULL) { 8421 // We don't record history while we are plugged in and fully charged. 8422 // The next time we are unplugged, history will be cleared. 8423 mRecordingHistory = DEBUG; 8424 } 8425 } 8426 8427 public long getAwakeTimeBattery() { 8428 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT); 8429 } 8430 8431 public long getAwakeTimePlugged() { 8432 return (SystemClock.uptimeMillis() * 1000) - getAwakeTimeBattery(); 8433 } 8434 8435 @Override 8436 public long computeUptime(long curTime, int which) { 8437 switch (which) { 8438 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart); 8439 case STATS_CURRENT: return (curTime-mUptimeStart); 8440 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart()); 8441 } 8442 return 0; 8443 } 8444 8445 @Override 8446 public long computeRealtime(long curTime, int which) { 8447 switch (which) { 8448 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart); 8449 case STATS_CURRENT: return (curTime-mRealtimeStart); 8450 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart()); 8451 } 8452 return 0; 8453 } 8454 8455 @Override 8456 public long computeBatteryUptime(long curTime, int which) { 8457 return mOnBatteryTimeBase.computeUptime(curTime, which); 8458 } 8459 8460 @Override 8461 public long computeBatteryRealtime(long curTime, int which) { 8462 return mOnBatteryTimeBase.computeRealtime(curTime, which); 8463 } 8464 8465 @Override 8466 public long computeBatteryScreenOffUptime(long curTime, int which) { 8467 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which); 8468 } 8469 8470 @Override 8471 public long computeBatteryScreenOffRealtime(long curTime, int which) { 8472 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which); 8473 } 8474 8475 private long computeTimePerLevel(long[] steps, int numSteps) { 8476 // For now we'll do a simple average across all steps. 8477 if (numSteps <= 0) { 8478 return -1; 8479 } 8480 long total = 0; 8481 for (int i=0; i<numSteps; i++) { 8482 total += steps[i] & STEP_LEVEL_TIME_MASK; 8483 } 8484 return total / numSteps; 8485 /* 8486 long[] buckets = new long[numSteps]; 8487 int numBuckets = 0; 8488 int numToAverage = 4; 8489 int i = 0; 8490 while (i < numSteps) { 8491 long totalTime = 0; 8492 int num = 0; 8493 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) { 8494 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK; 8495 num++; 8496 } 8497 buckets[numBuckets] = totalTime / num; 8498 numBuckets++; 8499 numToAverage *= 2; 8500 i += num; 8501 } 8502 if (numBuckets < 1) { 8503 return -1; 8504 } 8505 long averageTime = buckets[numBuckets-1]; 8506 for (i=numBuckets-2; i>=0; i--) { 8507 averageTime = (averageTime + buckets[i]) / 2; 8508 } 8509 return averageTime; 8510 */ 8511 } 8512 8513 @Override 8514 public long computeBatteryTimeRemaining(long curTime) { 8515 if (!mOnBattery) { 8516 return -1; 8517 } 8518 /* Simple implementation just looks at the average discharge per level across the 8519 entire sample period. 8520 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2; 8521 if (discharge < 2) { 8522 return -1; 8523 } 8524 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED); 8525 if (duration < 1000*1000) { 8526 return -1; 8527 } 8528 long usPerLevel = duration/discharge; 8529 return usPerLevel * mCurrentBatteryLevel; 8530 */ 8531 if (mDischargeStepTracker.mNumStepDurations < 1) { 8532 return -1; 8533 } 8534 long msPerLevel = mDischargeStepTracker.computeTimePerLevel(); 8535 if (msPerLevel <= 0) { 8536 return -1; 8537 } 8538 return (msPerLevel * mCurrentBatteryLevel) * 1000; 8539 } 8540 8541 @Override 8542 public LevelStepTracker getDischargeLevelStepTracker() { 8543 return mDischargeStepTracker; 8544 } 8545 8546 @Override 8547 public LevelStepTracker getDailyDischargeLevelStepTracker() { 8548 return mDailyDischargeStepTracker; 8549 } 8550 8551 @Override 8552 public long computeChargeTimeRemaining(long curTime) { 8553 if (mOnBattery) { 8554 // Not yet working. 8555 return -1; 8556 } 8557 /* Broken 8558 int curLevel = mCurrentBatteryLevel; 8559 int plugLevel = mDischargePlugLevel; 8560 if (plugLevel < 0 || curLevel < (plugLevel+1)) { 8561 return -1; 8562 } 8563 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED); 8564 if (duration < 1000*1000) { 8565 return -1; 8566 } 8567 long usPerLevel = duration/(curLevel-plugLevel); 8568 return usPerLevel * (100-curLevel); 8569 */ 8570 if (mChargeStepTracker.mNumStepDurations < 1) { 8571 return -1; 8572 } 8573 long msPerLevel = mChargeStepTracker.computeTimePerLevel(); 8574 if (msPerLevel <= 0) { 8575 return -1; 8576 } 8577 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000; 8578 } 8579 8580 @Override 8581 public LevelStepTracker getChargeLevelStepTracker() { 8582 return mChargeStepTracker; 8583 } 8584 8585 @Override 8586 public LevelStepTracker getDailyChargeLevelStepTracker() { 8587 return mDailyChargeStepTracker; 8588 } 8589 8590 @Override 8591 public ArrayList<PackageChange> getDailyPackageChanges() { 8592 return mDailyPackageChanges; 8593 } 8594 8595 long getBatteryUptimeLocked() { 8596 return mOnBatteryTimeBase.getUptime(SystemClock.uptimeMillis() * 1000); 8597 } 8598 8599 @Override 8600 public long getBatteryUptime(long curTime) { 8601 return mOnBatteryTimeBase.getUptime(curTime); 8602 } 8603 8604 @Override 8605 public long getBatteryRealtime(long curTime) { 8606 return mOnBatteryTimeBase.getRealtime(curTime); 8607 } 8608 8609 @Override 8610 public int getDischargeStartLevel() { 8611 synchronized(this) { 8612 return getDischargeStartLevelLocked(); 8613 } 8614 } 8615 8616 public int getDischargeStartLevelLocked() { 8617 return mDischargeUnplugLevel; 8618 } 8619 8620 @Override 8621 public int getDischargeCurrentLevel() { 8622 synchronized(this) { 8623 return getDischargeCurrentLevelLocked(); 8624 } 8625 } 8626 8627 public int getDischargeCurrentLevelLocked() { 8628 return mDischargeCurrentLevel; 8629 } 8630 8631 @Override 8632 public int getLowDischargeAmountSinceCharge() { 8633 synchronized(this) { 8634 int val = mLowDischargeAmountSinceCharge; 8635 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) { 8636 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1; 8637 } 8638 return val; 8639 } 8640 } 8641 8642 @Override 8643 public int getHighDischargeAmountSinceCharge() { 8644 synchronized(this) { 8645 int val = mHighDischargeAmountSinceCharge; 8646 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) { 8647 val += mDischargeUnplugLevel-mDischargeCurrentLevel; 8648 } 8649 return val; 8650 } 8651 } 8652 8653 @Override 8654 public int getDischargeAmount(int which) { 8655 int dischargeAmount = which == STATS_SINCE_CHARGED 8656 ? getHighDischargeAmountSinceCharge() 8657 : (getDischargeStartLevel() - getDischargeCurrentLevel()); 8658 if (dischargeAmount < 0) { 8659 dischargeAmount = 0; 8660 } 8661 return dischargeAmount; 8662 } 8663 8664 public int getDischargeAmountScreenOn() { 8665 synchronized(this) { 8666 int val = mDischargeAmountScreenOn; 8667 if (mOnBattery && mScreenState == Display.STATE_ON 8668 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) { 8669 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel; 8670 } 8671 return val; 8672 } 8673 } 8674 8675 public int getDischargeAmountScreenOnSinceCharge() { 8676 synchronized(this) { 8677 int val = mDischargeAmountScreenOnSinceCharge; 8678 if (mOnBattery && mScreenState == Display.STATE_ON 8679 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) { 8680 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel; 8681 } 8682 return val; 8683 } 8684 } 8685 8686 public int getDischargeAmountScreenOff() { 8687 synchronized(this) { 8688 int val = mDischargeAmountScreenOff; 8689 if (mOnBattery && mScreenState != Display.STATE_ON 8690 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) { 8691 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel; 8692 } 8693 return val; 8694 } 8695 } 8696 8697 public int getDischargeAmountScreenOffSinceCharge() { 8698 synchronized(this) { 8699 int val = mDischargeAmountScreenOffSinceCharge; 8700 if (mOnBattery && mScreenState != Display.STATE_ON 8701 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) { 8702 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel; 8703 } 8704 return val; 8705 } 8706 } 8707 8708 @Override 8709 public int getCpuSpeedSteps() { 8710 return sNumSpeedSteps; 8711 } 8712 8713 /** 8714 * Retrieve the statistics object for a particular uid, creating if needed. 8715 */ 8716 public Uid getUidStatsLocked(int uid) { 8717 Uid u = mUidStats.get(uid); 8718 if (u == null) { 8719 u = new Uid(uid); 8720 mUidStats.put(uid, u); 8721 } 8722 return u; 8723 } 8724 8725 /** 8726 * Remove the statistics object for a particular uid. 8727 */ 8728 public void removeUidStatsLocked(int uid) { 8729 mKernelUidCpuTimeReader.removeUid(uid); 8730 mUidStats.remove(uid); 8731 } 8732 8733 /** 8734 * Retrieve the statistics object for a particular process, creating 8735 * if needed. 8736 */ 8737 public Uid.Proc getProcessStatsLocked(int uid, String name) { 8738 uid = mapUid(uid); 8739 Uid u = getUidStatsLocked(uid); 8740 return u.getProcessStatsLocked(name); 8741 } 8742 8743 /** 8744 * Retrieve the statistics object for a particular process, creating 8745 * if needed. 8746 */ 8747 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) { 8748 uid = mapUid(uid); 8749 Uid u = getUidStatsLocked(uid); 8750 return u.getPackageStatsLocked(pkg); 8751 } 8752 8753 /** 8754 * Retrieve the statistics object for a particular service, creating 8755 * if needed. 8756 */ 8757 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) { 8758 uid = mapUid(uid); 8759 Uid u = getUidStatsLocked(uid); 8760 return u.getServiceStatsLocked(pkg, name); 8761 } 8762 8763 public void shutdownLocked() { 8764 recordShutdownLocked(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis()); 8765 writeSyncLocked(); 8766 mShuttingDown = true; 8767 } 8768 8769 Parcel mPendingWrite = null; 8770 final ReentrantLock mWriteLock = new ReentrantLock(); 8771 8772 public void writeAsyncLocked() { 8773 writeLocked(false); 8774 } 8775 8776 public void writeSyncLocked() { 8777 writeLocked(true); 8778 } 8779 8780 void writeLocked(boolean sync) { 8781 if (mFile == null) { 8782 Slog.w("BatteryStats", "writeLocked: no file associated with this instance"); 8783 return; 8784 } 8785 8786 if (mShuttingDown) { 8787 return; 8788 } 8789 8790 Parcel out = Parcel.obtain(); 8791 writeSummaryToParcel(out, true); 8792 mLastWriteTime = SystemClock.elapsedRealtime(); 8793 8794 if (mPendingWrite != null) { 8795 mPendingWrite.recycle(); 8796 } 8797 mPendingWrite = out; 8798 8799 if (sync) { 8800 commitPendingDataToDisk(); 8801 } else { 8802 BackgroundThread.getHandler().post(new Runnable() { 8803 @Override public void run() { 8804 commitPendingDataToDisk(); 8805 } 8806 }); 8807 } 8808 } 8809 8810 public void commitPendingDataToDisk() { 8811 final Parcel next; 8812 synchronized (this) { 8813 next = mPendingWrite; 8814 mPendingWrite = null; 8815 if (next == null) { 8816 return; 8817 } 8818 8819 mWriteLock.lock(); 8820 } 8821 8822 try { 8823 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite()); 8824 stream.write(next.marshall()); 8825 stream.flush(); 8826 FileUtils.sync(stream); 8827 stream.close(); 8828 mFile.commit(); 8829 } catch (IOException e) { 8830 Slog.w("BatteryStats", "Error writing battery statistics", e); 8831 mFile.rollback(); 8832 } finally { 8833 next.recycle(); 8834 mWriteLock.unlock(); 8835 } 8836 } 8837 8838 public void readLocked() { 8839 if (mDailyFile != null) { 8840 readDailyStatsLocked(); 8841 } 8842 8843 if (mFile == null) { 8844 Slog.w("BatteryStats", "readLocked: no file associated with this instance"); 8845 return; 8846 } 8847 8848 mUidStats.clear(); 8849 8850 try { 8851 File file = mFile.chooseForRead(); 8852 if (!file.exists()) { 8853 return; 8854 } 8855 FileInputStream stream = new FileInputStream(file); 8856 8857 byte[] raw = BatteryStatsHelper.readFully(stream); 8858 Parcel in = Parcel.obtain(); 8859 in.unmarshall(raw, 0, raw.length); 8860 in.setDataPosition(0); 8861 stream.close(); 8862 8863 readSummaryFromParcel(in); 8864 } catch(Exception e) { 8865 Slog.e("BatteryStats", "Error reading battery statistics", e); 8866 } 8867 8868 mEndPlatformVersion = Build.ID; 8869 8870 if (mHistoryBuffer.dataPosition() > 0) { 8871 mRecordingHistory = true; 8872 final long elapsedRealtime = SystemClock.elapsedRealtime(); 8873 final long uptime = SystemClock.uptimeMillis(); 8874 if (USE_OLD_HISTORY) { 8875 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur); 8876 } 8877 addHistoryBufferLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur); 8878 startRecordingHistory(elapsedRealtime, uptime, false); 8879 } 8880 8881 recordDailyStatsIfNeededLocked(false); 8882 } 8883 8884 public int describeContents() { 8885 return 0; 8886 } 8887 8888 void readHistory(Parcel in, boolean andOldHistory) { 8889 final long historyBaseTime = in.readLong(); 8890 8891 mHistoryBuffer.setDataSize(0); 8892 mHistoryBuffer.setDataPosition(0); 8893 mHistoryTagPool.clear(); 8894 mNextHistoryTagIdx = 0; 8895 mNumHistoryTagChars = 0; 8896 8897 int numTags = in.readInt(); 8898 for (int i=0; i<numTags; i++) { 8899 int idx = in.readInt(); 8900 String str = in.readString(); 8901 int uid = in.readInt(); 8902 HistoryTag tag = new HistoryTag(); 8903 tag.string = str; 8904 tag.uid = uid; 8905 tag.poolIdx = idx; 8906 mHistoryTagPool.put(tag, idx); 8907 if (idx >= mNextHistoryTagIdx) { 8908 mNextHistoryTagIdx = idx+1; 8909 } 8910 mNumHistoryTagChars += tag.string.length() + 1; 8911 } 8912 8913 int bufSize = in.readInt(); 8914 int curPos = in.dataPosition(); 8915 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) { 8916 Slog.w(TAG, "File corrupt: history data buffer too large " + bufSize); 8917 } else if ((bufSize&~3) != bufSize) { 8918 Slog.w(TAG, "File corrupt: history data buffer not aligned " + bufSize); 8919 } else { 8920 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize 8921 + " bytes at " + curPos); 8922 mHistoryBuffer.appendFrom(in, curPos, bufSize); 8923 in.setDataPosition(curPos + bufSize); 8924 } 8925 8926 if (andOldHistory) { 8927 readOldHistory(in); 8928 } 8929 8930 if (DEBUG_HISTORY) { 8931 StringBuilder sb = new StringBuilder(128); 8932 sb.append("****************** OLD mHistoryBaseTime: "); 8933 TimeUtils.formatDuration(mHistoryBaseTime, sb); 8934 Slog.i(TAG, sb.toString()); 8935 } 8936 mHistoryBaseTime = historyBaseTime; 8937 if (DEBUG_HISTORY) { 8938 StringBuilder sb = new StringBuilder(128); 8939 sb.append("****************** NEW mHistoryBaseTime: "); 8940 TimeUtils.formatDuration(mHistoryBaseTime, sb); 8941 Slog.i(TAG, sb.toString()); 8942 } 8943 8944 // We are just arbitrarily going to insert 1 minute from the sample of 8945 // the last run until samples in this run. 8946 if (mHistoryBaseTime > 0) { 8947 long oldnow = SystemClock.elapsedRealtime(); 8948 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1; 8949 if (DEBUG_HISTORY) { 8950 StringBuilder sb = new StringBuilder(128); 8951 sb.append("****************** ADJUSTED mHistoryBaseTime: "); 8952 TimeUtils.formatDuration(mHistoryBaseTime, sb); 8953 Slog.i(TAG, sb.toString()); 8954 } 8955 } 8956 } 8957 8958 void readOldHistory(Parcel in) { 8959 if (!USE_OLD_HISTORY) { 8960 return; 8961 } 8962 mHistory = mHistoryEnd = mHistoryCache = null; 8963 long time; 8964 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) { 8965 HistoryItem rec = new HistoryItem(time, in); 8966 addHistoryRecordLocked(rec); 8967 } 8968 } 8969 8970 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) { 8971 if (DEBUG_HISTORY) { 8972 StringBuilder sb = new StringBuilder(128); 8973 sb.append("****************** WRITING mHistoryBaseTime: "); 8974 TimeUtils.formatDuration(mHistoryBaseTime, sb); 8975 sb.append(" mLastHistoryElapsedRealtime: "); 8976 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb); 8977 Slog.i(TAG, sb.toString()); 8978 } 8979 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime); 8980 if (!inclData) { 8981 out.writeInt(0); 8982 out.writeInt(0); 8983 return; 8984 } 8985 out.writeInt(mHistoryTagPool.size()); 8986 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) { 8987 HistoryTag tag = ent.getKey(); 8988 out.writeInt(ent.getValue()); 8989 out.writeString(tag.string); 8990 out.writeInt(tag.uid); 8991 } 8992 out.writeInt(mHistoryBuffer.dataSize()); 8993 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: " 8994 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition()); 8995 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize()); 8996 8997 if (andOldHistory) { 8998 writeOldHistory(out); 8999 } 9000 } 9001 9002 void writeOldHistory(Parcel out) { 9003 if (!USE_OLD_HISTORY) { 9004 return; 9005 } 9006 HistoryItem rec = mHistory; 9007 while (rec != null) { 9008 if (rec.time >= 0) rec.writeToParcel(out, 0); 9009 rec = rec.next; 9010 } 9011 out.writeLong(-1); 9012 } 9013 9014 public void readSummaryFromParcel(Parcel in) { 9015 final int version = in.readInt(); 9016 if (version != VERSION) { 9017 Slog.w("BatteryStats", "readFromParcel: version got " + version 9018 + ", expected " + VERSION + "; erasing old stats"); 9019 return; 9020 } 9021 9022 readHistory(in, true); 9023 9024 mStartCount = in.readInt(); 9025 mUptime = in.readLong(); 9026 mRealtime = in.readLong(); 9027 mStartClockTime = in.readLong(); 9028 mStartPlatformVersion = in.readString(); 9029 mEndPlatformVersion = in.readString(); 9030 mOnBatteryTimeBase.readSummaryFromParcel(in); 9031 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in); 9032 mDischargeUnplugLevel = in.readInt(); 9033 mDischargePlugLevel = in.readInt(); 9034 mDischargeCurrentLevel = in.readInt(); 9035 mCurrentBatteryLevel = in.readInt(); 9036 mLowDischargeAmountSinceCharge = in.readInt(); 9037 mHighDischargeAmountSinceCharge = in.readInt(); 9038 mDischargeAmountScreenOnSinceCharge = in.readInt(); 9039 mDischargeAmountScreenOffSinceCharge = in.readInt(); 9040 mDischargeStepTracker.readFromParcel(in); 9041 mChargeStepTracker.readFromParcel(in); 9042 mDailyDischargeStepTracker.readFromParcel(in); 9043 mDailyChargeStepTracker.readFromParcel(in); 9044 int NPKG = in.readInt(); 9045 if (NPKG > 0) { 9046 mDailyPackageChanges = new ArrayList<>(NPKG); 9047 while (NPKG > 0) { 9048 NPKG--; 9049 PackageChange pc = new PackageChange(); 9050 pc.mPackageName = in.readString(); 9051 pc.mUpdate = in.readInt() != 0; 9052 pc.mVersionCode = in.readInt(); 9053 mDailyPackageChanges.add(pc); 9054 } 9055 } else { 9056 mDailyPackageChanges = null; 9057 } 9058 mDailyStartTime = in.readLong(); 9059 mNextMinDailyDeadline = in.readLong(); 9060 mNextMaxDailyDeadline = in.readLong(); 9061 9062 mStartCount++; 9063 9064 mScreenState = Display.STATE_UNKNOWN; 9065 mScreenOnTimer.readSummaryFromParcelLocked(in); 9066 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) { 9067 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in); 9068 } 9069 mInteractive = false; 9070 mInteractiveTimer.readSummaryFromParcelLocked(in); 9071 mPhoneOn = false; 9072 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in); 9073 mDeviceIdleModeEnabledTimer.readSummaryFromParcelLocked(in); 9074 mDeviceIdlingTimer.readSummaryFromParcelLocked(in); 9075 mPhoneOnTimer.readSummaryFromParcelLocked(in); 9076 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) { 9077 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in); 9078 } 9079 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in); 9080 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) { 9081 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in); 9082 } 9083 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 9084 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in); 9085 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in); 9086 } 9087 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW; 9088 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in); 9089 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in); 9090 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in); 9091 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in); 9092 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in); 9093 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW; 9094 mWifiOn = false; 9095 mWifiOnTimer.readSummaryFromParcelLocked(in); 9096 mGlobalWifiRunning = false; 9097 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in); 9098 for (int i=0; i<NUM_WIFI_STATES; i++) { 9099 mWifiStateTimer[i].readSummaryFromParcelLocked(in); 9100 } 9101 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) { 9102 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in); 9103 } 9104 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) { 9105 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in); 9106 } 9107 for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 9108 mBluetoothActivityCounters[i].readSummaryFromParcelLocked(in); 9109 } 9110 for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 9111 mWifiActivityCounters[i].readSummaryFromParcelLocked(in); 9112 } 9113 9114 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt(); 9115 mFlashlightOnNesting = 0; 9116 mFlashlightOnTimer.readSummaryFromParcelLocked(in); 9117 mCameraOnNesting = 0; 9118 mCameraOnTimer.readSummaryFromParcelLocked(in); 9119 9120 int NKW = in.readInt(); 9121 if (NKW > 10000) { 9122 Slog.w(TAG, "File corrupt: too many kernel wake locks " + NKW); 9123 return; 9124 } 9125 for (int ikw = 0; ikw < NKW; ikw++) { 9126 if (in.readInt() != 0) { 9127 String kwltName = in.readString(); 9128 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in); 9129 } 9130 } 9131 9132 int NWR = in.readInt(); 9133 if (NWR > 10000) { 9134 Slog.w(TAG, "File corrupt: too many wakeup reasons " + NWR); 9135 return; 9136 } 9137 for (int iwr = 0; iwr < NWR; iwr++) { 9138 if (in.readInt() != 0) { 9139 String reasonName = in.readString(); 9140 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in); 9141 } 9142 } 9143 9144 sNumSpeedSteps = in.readInt(); 9145 if (sNumSpeedSteps < 0 || sNumSpeedSteps > 100) { 9146 throw new BadParcelableException("Bad speed steps in data: " + sNumSpeedSteps); 9147 } 9148 9149 final int NU = in.readInt(); 9150 if (NU > 10000) { 9151 Slog.w(TAG, "File corrupt: too many uids " + NU); 9152 return; 9153 } 9154 for (int iu = 0; iu < NU; iu++) { 9155 int uid = in.readInt(); 9156 Uid u = new Uid(uid); 9157 mUidStats.put(uid, u); 9158 9159 u.mWifiRunning = false; 9160 if (in.readInt() != 0) { 9161 u.mWifiRunningTimer.readSummaryFromParcelLocked(in); 9162 } 9163 u.mFullWifiLockOut = false; 9164 if (in.readInt() != 0) { 9165 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in); 9166 } 9167 u.mWifiScanStarted = false; 9168 if (in.readInt() != 0) { 9169 u.mWifiScanTimer.readSummaryFromParcelLocked(in); 9170 } 9171 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED; 9172 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) { 9173 if (in.readInt() != 0) { 9174 u.makeWifiBatchedScanBin(i, null); 9175 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in); 9176 } 9177 } 9178 u.mWifiMulticastEnabled = false; 9179 if (in.readInt() != 0) { 9180 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in); 9181 } 9182 if (in.readInt() != 0) { 9183 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in); 9184 } 9185 if (in.readInt() != 0) { 9186 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in); 9187 } 9188 if (in.readInt() != 0) { 9189 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in); 9190 } 9191 if (in.readInt() != 0) { 9192 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in); 9193 } 9194 if (in.readInt() != 0) { 9195 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in); 9196 } 9197 u.mProcessState = Uid.PROCESS_STATE_NONE; 9198 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) { 9199 if (in.readInt() != 0) { 9200 u.makeProcessState(i, null); 9201 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in); 9202 } 9203 } 9204 if (in.readInt() != 0) { 9205 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in); 9206 } 9207 9208 if (in.readInt() != 0) { 9209 if (u.mUserActivityCounters == null) { 9210 u.initUserActivityLocked(); 9211 } 9212 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) { 9213 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in); 9214 } 9215 } 9216 9217 if (in.readInt() != 0) { 9218 if (u.mNetworkByteActivityCounters == null) { 9219 u.initNetworkActivityLocked(); 9220 } 9221 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 9222 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in); 9223 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in); 9224 } 9225 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in); 9226 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in); 9227 } 9228 9229 u.mUserCpuTime.readSummaryFromParcelLocked(in); 9230 u.mSystemCpuTime.readSummaryFromParcelLocked(in); 9231 9232 int NSB = in.readInt(); 9233 if (NSB > 100) { 9234 Slog.w(TAG, "File corrupt: too many speed bins " + NSB); 9235 return; 9236 } 9237 9238 u.mSpeedBins = new LongSamplingCounter[NSB]; 9239 for (int i=0; i<NSB; i++) { 9240 if (in.readInt() != 0) { 9241 u.mSpeedBins[i] = new LongSamplingCounter(mOnBatteryTimeBase); 9242 u.mSpeedBins[i].readSummaryFromParcelLocked(in); 9243 } 9244 } 9245 9246 int NW = in.readInt(); 9247 if (NW > 100) { 9248 Slog.w(TAG, "File corrupt: too many wake locks " + NW); 9249 return; 9250 } 9251 for (int iw = 0; iw < NW; iw++) { 9252 String wlName = in.readString(); 9253 u.readWakeSummaryFromParcelLocked(wlName, in); 9254 } 9255 9256 int NS = in.readInt(); 9257 if (NS > 100) { 9258 Slog.w(TAG, "File corrupt: too many syncs " + NS); 9259 return; 9260 } 9261 for (int is = 0; is < NS; is++) { 9262 String name = in.readString(); 9263 u.readSyncSummaryFromParcelLocked(name, in); 9264 } 9265 9266 int NJ = in.readInt(); 9267 if (NJ > 100) { 9268 Slog.w(TAG, "File corrupt: too many job timers " + NJ); 9269 return; 9270 } 9271 for (int ij = 0; ij < NJ; ij++) { 9272 String name = in.readString(); 9273 u.readJobSummaryFromParcelLocked(name, in); 9274 } 9275 9276 int NP = in.readInt(); 9277 if (NP > 1000) { 9278 Slog.w(TAG, "File corrupt: too many sensors " + NP); 9279 return; 9280 } 9281 for (int is = 0; is < NP; is++) { 9282 int seNumber = in.readInt(); 9283 if (in.readInt() != 0) { 9284 u.getSensorTimerLocked(seNumber, true) 9285 .readSummaryFromParcelLocked(in); 9286 } 9287 } 9288 9289 NP = in.readInt(); 9290 if (NP > 1000) { 9291 Slog.w(TAG, "File corrupt: too many processes " + NP); 9292 return; 9293 } 9294 for (int ip = 0; ip < NP; ip++) { 9295 String procName = in.readString(); 9296 Uid.Proc p = u.getProcessStatsLocked(procName); 9297 p.mUserTime = p.mLoadedUserTime = in.readLong(); 9298 p.mSystemTime = p.mLoadedSystemTime = in.readLong(); 9299 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong(); 9300 p.mStarts = p.mLoadedStarts = in.readInt(); 9301 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt(); 9302 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt(); 9303 if (!p.readExcessivePowerFromParcelLocked(in)) { 9304 return; 9305 } 9306 } 9307 9308 NP = in.readInt(); 9309 if (NP > 10000) { 9310 Slog.w(TAG, "File corrupt: too many packages " + NP); 9311 return; 9312 } 9313 for (int ip = 0; ip < NP; ip++) { 9314 String pkgName = in.readString(); 9315 Uid.Pkg p = u.getPackageStatsLocked(pkgName); 9316 final int NWA = in.readInt(); 9317 if (NWA > 1000) { 9318 Slog.w(TAG, "File corrupt: too many wakeup alarms " + NWA); 9319 return; 9320 } 9321 p.mWakeupAlarms.clear(); 9322 for (int iwa=0; iwa<NWA; iwa++) { 9323 String tag = in.readString(); 9324 Counter c = new Counter(mOnBatteryTimeBase); 9325 c.readSummaryFromParcelLocked(in); 9326 p.mWakeupAlarms.put(tag, c); 9327 } 9328 NS = in.readInt(); 9329 if (NS > 1000) { 9330 Slog.w(TAG, "File corrupt: too many services " + NS); 9331 return; 9332 } 9333 for (int is = 0; is < NS; is++) { 9334 String servName = in.readString(); 9335 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName); 9336 s.mStartTime = s.mLoadedStartTime = in.readLong(); 9337 s.mStarts = s.mLoadedStarts = in.readInt(); 9338 s.mLaunches = s.mLoadedLaunches = in.readInt(); 9339 } 9340 } 9341 } 9342 } 9343 9344 /** 9345 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to 9346 * disk. This format does not allow a lossless round-trip. 9347 * 9348 * @param out the Parcel to be written to. 9349 */ 9350 public void writeSummaryToParcel(Parcel out, boolean inclHistory) { 9351 pullPendingStateUpdatesLocked(); 9352 9353 // Pull the clock time. This may update the time and make a new history entry 9354 // if we had originally pulled a time before the RTC was set. 9355 long startClockTime = getStartClockTime(); 9356 9357 final long NOW_SYS = SystemClock.uptimeMillis() * 1000; 9358 final long NOWREAL_SYS = SystemClock.elapsedRealtime() * 1000; 9359 9360 out.writeInt(VERSION); 9361 9362 writeHistory(out, inclHistory, true); 9363 9364 out.writeInt(mStartCount); 9365 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED)); 9366 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED)); 9367 out.writeLong(startClockTime); 9368 out.writeString(mStartPlatformVersion); 9369 out.writeString(mEndPlatformVersion); 9370 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS); 9371 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS); 9372 out.writeInt(mDischargeUnplugLevel); 9373 out.writeInt(mDischargePlugLevel); 9374 out.writeInt(mDischargeCurrentLevel); 9375 out.writeInt(mCurrentBatteryLevel); 9376 out.writeInt(getLowDischargeAmountSinceCharge()); 9377 out.writeInt(getHighDischargeAmountSinceCharge()); 9378 out.writeInt(getDischargeAmountScreenOnSinceCharge()); 9379 out.writeInt(getDischargeAmountScreenOffSinceCharge()); 9380 mDischargeStepTracker.writeToParcel(out); 9381 mChargeStepTracker.writeToParcel(out); 9382 mDailyDischargeStepTracker.writeToParcel(out); 9383 mDailyChargeStepTracker.writeToParcel(out); 9384 if (mDailyPackageChanges != null) { 9385 final int NPKG = mDailyPackageChanges.size(); 9386 out.writeInt(NPKG); 9387 for (int i=0; i<NPKG; i++) { 9388 PackageChange pc = mDailyPackageChanges.get(i); 9389 out.writeString(pc.mPackageName); 9390 out.writeInt(pc.mUpdate ? 1 : 0); 9391 out.writeInt(pc.mVersionCode); 9392 } 9393 } else { 9394 out.writeInt(0); 9395 } 9396 out.writeLong(mDailyStartTime); 9397 out.writeLong(mNextMinDailyDeadline); 9398 out.writeLong(mNextMaxDailyDeadline); 9399 9400 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9401 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) { 9402 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9403 } 9404 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9405 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9406 mDeviceIdleModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9407 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9408 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9409 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) { 9410 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9411 } 9412 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9413 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) { 9414 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9415 } 9416 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 9417 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out); 9418 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out); 9419 } 9420 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9421 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9422 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out); 9423 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out); 9424 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out); 9425 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9426 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9427 for (int i=0; i<NUM_WIFI_STATES; i++) { 9428 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9429 } 9430 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) { 9431 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9432 } 9433 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) { 9434 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9435 } 9436 for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 9437 mBluetoothActivityCounters[i].writeSummaryFromParcelLocked(out); 9438 } 9439 for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 9440 mWifiActivityCounters[i].writeSummaryFromParcelLocked(out); 9441 } 9442 out.writeInt(mNumConnectivityChange); 9443 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9444 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9445 9446 out.writeInt(mKernelWakelockStats.size()); 9447 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) { 9448 Timer kwlt = ent.getValue(); 9449 if (kwlt != null) { 9450 out.writeInt(1); 9451 out.writeString(ent.getKey()); 9452 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9453 } else { 9454 out.writeInt(0); 9455 } 9456 } 9457 9458 out.writeInt(mWakeupReasonStats.size()); 9459 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) { 9460 SamplingTimer timer = ent.getValue(); 9461 if (timer != null) { 9462 out.writeInt(1); 9463 out.writeString(ent.getKey()); 9464 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9465 } else { 9466 out.writeInt(0); 9467 } 9468 } 9469 9470 out.writeInt(sNumSpeedSteps); 9471 final int NU = mUidStats.size(); 9472 out.writeInt(NU); 9473 for (int iu = 0; iu < NU; iu++) { 9474 out.writeInt(mUidStats.keyAt(iu)); 9475 Uid u = mUidStats.valueAt(iu); 9476 9477 if (u.mWifiRunningTimer != null) { 9478 out.writeInt(1); 9479 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9480 } else { 9481 out.writeInt(0); 9482 } 9483 if (u.mFullWifiLockTimer != null) { 9484 out.writeInt(1); 9485 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9486 } else { 9487 out.writeInt(0); 9488 } 9489 if (u.mWifiScanTimer != null) { 9490 out.writeInt(1); 9491 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9492 } else { 9493 out.writeInt(0); 9494 } 9495 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) { 9496 if (u.mWifiBatchedScanTimer[i] != null) { 9497 out.writeInt(1); 9498 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9499 } else { 9500 out.writeInt(0); 9501 } 9502 } 9503 if (u.mWifiMulticastTimer != null) { 9504 out.writeInt(1); 9505 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9506 } else { 9507 out.writeInt(0); 9508 } 9509 if (u.mAudioTurnedOnTimer != null) { 9510 out.writeInt(1); 9511 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9512 } else { 9513 out.writeInt(0); 9514 } 9515 if (u.mVideoTurnedOnTimer != null) { 9516 out.writeInt(1); 9517 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9518 } else { 9519 out.writeInt(0); 9520 } 9521 if (u.mFlashlightTurnedOnTimer != null) { 9522 out.writeInt(1); 9523 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9524 } else { 9525 out.writeInt(0); 9526 } 9527 if (u.mCameraTurnedOnTimer != null) { 9528 out.writeInt(1); 9529 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9530 } else { 9531 out.writeInt(0); 9532 } 9533 if (u.mForegroundActivityTimer != null) { 9534 out.writeInt(1); 9535 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9536 } else { 9537 out.writeInt(0); 9538 } 9539 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) { 9540 if (u.mProcessStateTimer[i] != null) { 9541 out.writeInt(1); 9542 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9543 } else { 9544 out.writeInt(0); 9545 } 9546 } 9547 if (u.mVibratorOnTimer != null) { 9548 out.writeInt(1); 9549 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9550 } else { 9551 out.writeInt(0); 9552 } 9553 9554 if (u.mUserActivityCounters == null) { 9555 out.writeInt(0); 9556 } else { 9557 out.writeInt(1); 9558 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) { 9559 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out); 9560 } 9561 } 9562 9563 if (u.mNetworkByteActivityCounters == null) { 9564 out.writeInt(0); 9565 } else { 9566 out.writeInt(1); 9567 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 9568 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out); 9569 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out); 9570 } 9571 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out); 9572 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out); 9573 } 9574 9575 u.mUserCpuTime.writeSummaryFromParcelLocked(out); 9576 u.mSystemCpuTime.writeSummaryFromParcelLocked(out); 9577 9578 out.writeInt(u.mSpeedBins.length); 9579 for (int i = 0; i < u.mSpeedBins.length; i++) { 9580 LongSamplingCounter speedBin = u.mSpeedBins[i]; 9581 if (speedBin != null) { 9582 out.writeInt(1); 9583 speedBin.writeSummaryFromParcelLocked(out); 9584 } else { 9585 out.writeInt(0); 9586 } 9587 } 9588 9589 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap(); 9590 int NW = wakeStats.size(); 9591 out.writeInt(NW); 9592 for (int iw=0; iw<NW; iw++) { 9593 out.writeString(wakeStats.keyAt(iw)); 9594 Uid.Wakelock wl = wakeStats.valueAt(iw); 9595 if (wl.mTimerFull != null) { 9596 out.writeInt(1); 9597 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9598 } else { 9599 out.writeInt(0); 9600 } 9601 if (wl.mTimerPartial != null) { 9602 out.writeInt(1); 9603 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9604 } else { 9605 out.writeInt(0); 9606 } 9607 if (wl.mTimerWindow != null) { 9608 out.writeInt(1); 9609 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9610 } else { 9611 out.writeInt(0); 9612 } 9613 if (wl.mTimerDoze != null) { 9614 out.writeInt(1); 9615 wl.mTimerDoze.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9616 } else { 9617 out.writeInt(0); 9618 } 9619 } 9620 9621 final ArrayMap<String, StopwatchTimer> syncStats = u.mSyncStats.getMap(); 9622 int NS = syncStats.size(); 9623 out.writeInt(NS); 9624 for (int is=0; is<NS; is++) { 9625 out.writeString(syncStats.keyAt(is)); 9626 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9627 } 9628 9629 final ArrayMap<String, StopwatchTimer> jobStats = u.mJobStats.getMap(); 9630 int NJ = jobStats.size(); 9631 out.writeInt(NJ); 9632 for (int ij=0; ij<NJ; ij++) { 9633 out.writeString(jobStats.keyAt(ij)); 9634 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9635 } 9636 9637 int NSE = u.mSensorStats.size(); 9638 out.writeInt(NSE); 9639 for (int ise=0; ise<NSE; ise++) { 9640 out.writeInt(u.mSensorStats.keyAt(ise)); 9641 Uid.Sensor se = u.mSensorStats.valueAt(ise); 9642 if (se.mTimer != null) { 9643 out.writeInt(1); 9644 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS); 9645 } else { 9646 out.writeInt(0); 9647 } 9648 } 9649 9650 int NP = u.mProcessStats.size(); 9651 out.writeInt(NP); 9652 for (int ip=0; ip<NP; ip++) { 9653 out.writeString(u.mProcessStats.keyAt(ip)); 9654 Uid.Proc ps = u.mProcessStats.valueAt(ip); 9655 out.writeLong(ps.mUserTime); 9656 out.writeLong(ps.mSystemTime); 9657 out.writeLong(ps.mForegroundTime); 9658 out.writeInt(ps.mStarts); 9659 out.writeInt(ps.mNumCrashes); 9660 out.writeInt(ps.mNumAnrs); 9661 ps.writeExcessivePowerToParcelLocked(out); 9662 } 9663 9664 NP = u.mPackageStats.size(); 9665 out.writeInt(NP); 9666 if (NP > 0) { 9667 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent 9668 : u.mPackageStats.entrySet()) { 9669 out.writeString(ent.getKey()); 9670 Uid.Pkg ps = ent.getValue(); 9671 final int NWA = ps.mWakeupAlarms.size(); 9672 out.writeInt(NWA); 9673 for (int iwa=0; iwa<NWA; iwa++) { 9674 out.writeString(ps.mWakeupAlarms.keyAt(iwa)); 9675 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out); 9676 } 9677 NS = ps.mServiceStats.size(); 9678 out.writeInt(NS); 9679 for (int is=0; is<NS; is++) { 9680 out.writeString(ps.mServiceStats.keyAt(is)); 9681 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is); 9682 long time = ss.getStartTimeToNowLocked( 9683 mOnBatteryTimeBase.getUptime(NOW_SYS)); 9684 out.writeLong(time); 9685 out.writeInt(ss.mStarts); 9686 out.writeInt(ss.mLaunches); 9687 } 9688 } 9689 } 9690 } 9691 } 9692 9693 public void readFromParcel(Parcel in) { 9694 readFromParcelLocked(in); 9695 } 9696 9697 void readFromParcelLocked(Parcel in) { 9698 int magic = in.readInt(); 9699 if (magic != MAGIC) { 9700 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic)); 9701 } 9702 9703 readHistory(in, false); 9704 9705 mStartCount = in.readInt(); 9706 mStartClockTime = in.readLong(); 9707 mStartPlatformVersion = in.readString(); 9708 mEndPlatformVersion = in.readString(); 9709 mUptime = in.readLong(); 9710 mUptimeStart = in.readLong(); 9711 mRealtime = in.readLong(); 9712 mRealtimeStart = in.readLong(); 9713 mOnBattery = in.readInt() != 0; 9714 mOnBatteryInternal = false; // we are no longer really running. 9715 mOnBatteryTimeBase.readFromParcel(in); 9716 mOnBatteryScreenOffTimeBase.readFromParcel(in); 9717 9718 mScreenState = Display.STATE_UNKNOWN; 9719 mScreenOnTimer = new StopwatchTimer(null, -1, null, mOnBatteryTimeBase, in); 9720 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) { 9721 mScreenBrightnessTimer[i] = new StopwatchTimer(null, -100-i, null, mOnBatteryTimeBase, 9722 in); 9723 } 9724 mInteractive = false; 9725 mInteractiveTimer = new StopwatchTimer(null, -10, null, mOnBatteryTimeBase, in); 9726 mPhoneOn = false; 9727 mPowerSaveModeEnabledTimer = new StopwatchTimer(null, -2, null, mOnBatteryTimeBase, in); 9728 mDeviceIdleModeEnabledTimer = new StopwatchTimer(null, -11, null, mOnBatteryTimeBase, in); 9729 mDeviceIdlingTimer = new StopwatchTimer(null, -12, null, mOnBatteryTimeBase, in); 9730 mPhoneOnTimer = new StopwatchTimer(null, -3, null, mOnBatteryTimeBase, in); 9731 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) { 9732 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(null, -200-i, 9733 null, mOnBatteryTimeBase, in); 9734 } 9735 mPhoneSignalScanningTimer = new StopwatchTimer(null, -200+1, null, mOnBatteryTimeBase, in); 9736 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) { 9737 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(null, -300-i, 9738 null, mOnBatteryTimeBase, in); 9739 } 9740 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 9741 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in); 9742 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in); 9743 } 9744 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW; 9745 mMobileRadioActiveTimer = new StopwatchTimer(null, -400, null, mOnBatteryTimeBase, in); 9746 mMobileRadioActivePerAppTimer = new StopwatchTimer(null, -401, null, mOnBatteryTimeBase, 9747 in); 9748 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in); 9749 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in); 9750 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in); 9751 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW; 9752 mWifiOn = false; 9753 mWifiOnTimer = new StopwatchTimer(null, -4, null, mOnBatteryTimeBase, in); 9754 mGlobalWifiRunning = false; 9755 mGlobalWifiRunningTimer = new StopwatchTimer(null, -5, null, mOnBatteryTimeBase, in); 9756 for (int i=0; i<NUM_WIFI_STATES; i++) { 9757 mWifiStateTimer[i] = new StopwatchTimer(null, -600-i, 9758 null, mOnBatteryTimeBase, in); 9759 } 9760 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) { 9761 mWifiSupplStateTimer[i] = new StopwatchTimer(null, -700-i, 9762 null, mOnBatteryTimeBase, in); 9763 } 9764 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) { 9765 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(null, -800-i, 9766 null, mOnBatteryTimeBase, in); 9767 } 9768 for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 9769 mBluetoothActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in); 9770 } 9771 for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 9772 mWifiActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in); 9773 } 9774 9775 mHasWifiEnergyReporting = in.readInt() != 0; 9776 mHasBluetoothEnergyReporting = in.readInt() != 0; 9777 mNumConnectivityChange = in.readInt(); 9778 mLoadedNumConnectivityChange = in.readInt(); 9779 mUnpluggedNumConnectivityChange = in.readInt(); 9780 mAudioOnNesting = 0; 9781 mAudioOnTimer = new StopwatchTimer(null, -7, null, mOnBatteryTimeBase); 9782 mVideoOnNesting = 0; 9783 mVideoOnTimer = new StopwatchTimer(null, -8, null, mOnBatteryTimeBase); 9784 mFlashlightOnNesting = 0; 9785 mFlashlightOnTimer = new StopwatchTimer(null, -9, null, mOnBatteryTimeBase, in); 9786 mCameraOnNesting = 0; 9787 mCameraOnTimer = new StopwatchTimer(null, -13, null, mOnBatteryTimeBase, in); 9788 mDischargeUnplugLevel = in.readInt(); 9789 mDischargePlugLevel = in.readInt(); 9790 mDischargeCurrentLevel = in.readInt(); 9791 mCurrentBatteryLevel = in.readInt(); 9792 mLowDischargeAmountSinceCharge = in.readInt(); 9793 mHighDischargeAmountSinceCharge = in.readInt(); 9794 mDischargeAmountScreenOn = in.readInt(); 9795 mDischargeAmountScreenOnSinceCharge = in.readInt(); 9796 mDischargeAmountScreenOff = in.readInt(); 9797 mDischargeAmountScreenOffSinceCharge = in.readInt(); 9798 mDischargeStepTracker.readFromParcel(in); 9799 mChargeStepTracker.readFromParcel(in); 9800 mLastWriteTime = in.readLong(); 9801 9802 mKernelWakelockStats.clear(); 9803 int NKW = in.readInt(); 9804 for (int ikw = 0; ikw < NKW; ikw++) { 9805 if (in.readInt() != 0) { 9806 String wakelockName = in.readString(); 9807 SamplingTimer kwlt = new SamplingTimer(mOnBatteryScreenOffTimeBase, in); 9808 mKernelWakelockStats.put(wakelockName, kwlt); 9809 } 9810 } 9811 9812 mWakeupReasonStats.clear(); 9813 int NWR = in.readInt(); 9814 for (int iwr = 0; iwr < NWR; iwr++) { 9815 if (in.readInt() != 0) { 9816 String reasonName = in.readString(); 9817 SamplingTimer timer = new SamplingTimer(mOnBatteryTimeBase, in); 9818 mWakeupReasonStats.put(reasonName, timer); 9819 } 9820 } 9821 9822 mPartialTimers.clear(); 9823 mFullTimers.clear(); 9824 mWindowTimers.clear(); 9825 mWifiRunningTimers.clear(); 9826 mFullWifiLockTimers.clear(); 9827 mWifiScanTimers.clear(); 9828 mWifiBatchedScanTimers.clear(); 9829 mWifiMulticastTimers.clear(); 9830 mAudioTurnedOnTimers.clear(); 9831 mVideoTurnedOnTimers.clear(); 9832 mFlashlightTurnedOnTimers.clear(); 9833 mCameraTurnedOnTimers.clear(); 9834 9835 sNumSpeedSteps = in.readInt(); 9836 9837 int numUids = in.readInt(); 9838 mUidStats.clear(); 9839 for (int i = 0; i < numUids; i++) { 9840 int uid = in.readInt(); 9841 Uid u = new Uid(uid); 9842 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in); 9843 mUidStats.append(uid, u); 9844 } 9845 } 9846 9847 public void writeToParcel(Parcel out, int flags) { 9848 writeToParcelLocked(out, true, flags); 9849 } 9850 9851 public void writeToParcelWithoutUids(Parcel out, int flags) { 9852 writeToParcelLocked(out, false, flags); 9853 } 9854 9855 @SuppressWarnings("unused") 9856 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) { 9857 // Need to update with current kernel wake lock counts. 9858 pullPendingStateUpdatesLocked(); 9859 9860 // Pull the clock time. This may update the time and make a new history entry 9861 // if we had originally pulled a time before the RTC was set. 9862 long startClockTime = getStartClockTime(); 9863 9864 final long uSecUptime = SystemClock.uptimeMillis() * 1000; 9865 final long uSecRealtime = SystemClock.elapsedRealtime() * 1000; 9866 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime); 9867 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime); 9868 9869 out.writeInt(MAGIC); 9870 9871 writeHistory(out, true, false); 9872 9873 out.writeInt(mStartCount); 9874 out.writeLong(startClockTime); 9875 out.writeString(mStartPlatformVersion); 9876 out.writeString(mEndPlatformVersion); 9877 out.writeLong(mUptime); 9878 out.writeLong(mUptimeStart); 9879 out.writeLong(mRealtime); 9880 out.writeLong(mRealtimeStart); 9881 out.writeInt(mOnBattery ? 1 : 0); 9882 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime); 9883 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime); 9884 9885 mScreenOnTimer.writeToParcel(out, uSecRealtime); 9886 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) { 9887 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime); 9888 } 9889 mInteractiveTimer.writeToParcel(out, uSecRealtime); 9890 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime); 9891 mDeviceIdleModeEnabledTimer.writeToParcel(out, uSecRealtime); 9892 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime); 9893 mPhoneOnTimer.writeToParcel(out, uSecRealtime); 9894 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) { 9895 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime); 9896 } 9897 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime); 9898 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) { 9899 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime); 9900 } 9901 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) { 9902 mNetworkByteActivityCounters[i].writeToParcel(out); 9903 mNetworkPacketActivityCounters[i].writeToParcel(out); 9904 } 9905 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime); 9906 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime); 9907 mMobileRadioActiveAdjustedTime.writeToParcel(out); 9908 mMobileRadioActiveUnknownTime.writeToParcel(out); 9909 mMobileRadioActiveUnknownCount.writeToParcel(out); 9910 mWifiOnTimer.writeToParcel(out, uSecRealtime); 9911 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime); 9912 for (int i=0; i<NUM_WIFI_STATES; i++) { 9913 mWifiStateTimer[i].writeToParcel(out, uSecRealtime); 9914 } 9915 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) { 9916 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime); 9917 } 9918 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) { 9919 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime); 9920 } 9921 for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 9922 mBluetoothActivityCounters[i].writeToParcel(out); 9923 } 9924 for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) { 9925 mWifiActivityCounters[i].writeToParcel(out); 9926 } 9927 out.writeInt(mHasWifiEnergyReporting ? 1 : 0); 9928 out.writeInt(mHasBluetoothEnergyReporting ? 1 : 0); 9929 out.writeInt(mNumConnectivityChange); 9930 out.writeInt(mLoadedNumConnectivityChange); 9931 out.writeInt(mUnpluggedNumConnectivityChange); 9932 mFlashlightOnTimer.writeToParcel(out, uSecRealtime); 9933 mCameraOnTimer.writeToParcel(out, uSecRealtime); 9934 out.writeInt(mDischargeUnplugLevel); 9935 out.writeInt(mDischargePlugLevel); 9936 out.writeInt(mDischargeCurrentLevel); 9937 out.writeInt(mCurrentBatteryLevel); 9938 out.writeInt(mLowDischargeAmountSinceCharge); 9939 out.writeInt(mHighDischargeAmountSinceCharge); 9940 out.writeInt(mDischargeAmountScreenOn); 9941 out.writeInt(mDischargeAmountScreenOnSinceCharge); 9942 out.writeInt(mDischargeAmountScreenOff); 9943 out.writeInt(mDischargeAmountScreenOffSinceCharge); 9944 mDischargeStepTracker.writeToParcel(out); 9945 mChargeStepTracker.writeToParcel(out); 9946 out.writeLong(mLastWriteTime); 9947 9948 if (inclUids) { 9949 out.writeInt(mKernelWakelockStats.size()); 9950 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) { 9951 SamplingTimer kwlt = ent.getValue(); 9952 if (kwlt != null) { 9953 out.writeInt(1); 9954 out.writeString(ent.getKey()); 9955 kwlt.writeToParcel(out, uSecRealtime); 9956 } else { 9957 out.writeInt(0); 9958 } 9959 } 9960 out.writeInt(mWakeupReasonStats.size()); 9961 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) { 9962 SamplingTimer timer = ent.getValue(); 9963 if (timer != null) { 9964 out.writeInt(1); 9965 out.writeString(ent.getKey()); 9966 timer.writeToParcel(out, uSecRealtime); 9967 } else { 9968 out.writeInt(0); 9969 } 9970 } 9971 } else { 9972 out.writeInt(0); 9973 } 9974 9975 out.writeInt(sNumSpeedSteps); 9976 9977 if (inclUids) { 9978 int size = mUidStats.size(); 9979 out.writeInt(size); 9980 for (int i = 0; i < size; i++) { 9981 out.writeInt(mUidStats.keyAt(i)); 9982 Uid uid = mUidStats.valueAt(i); 9983 9984 uid.writeToParcelLocked(out, uSecRealtime); 9985 } 9986 } else { 9987 out.writeInt(0); 9988 } 9989 } 9990 9991 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR = 9992 new Parcelable.Creator<BatteryStatsImpl>() { 9993 public BatteryStatsImpl createFromParcel(Parcel in) { 9994 return new BatteryStatsImpl(in); 9995 } 9996 9997 public BatteryStatsImpl[] newArray(int size) { 9998 return new BatteryStatsImpl[size]; 9999 } 10000 }; 10001 10002 public void prepareForDumpLocked() { 10003 // Need to retrieve current kernel wake lock stats before printing. 10004 pullPendingStateUpdatesLocked(); 10005 10006 // Pull the clock time. This may update the time and make a new history entry 10007 // if we had originally pulled a time before the RTC was set. 10008 getStartClockTime(); 10009 } 10010 10011 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) { 10012 if (DEBUG) { 10013 pw.println("mOnBatteryTimeBase:"); 10014 mOnBatteryTimeBase.dump(pw, " "); 10015 pw.println("mOnBatteryScreenOffTimeBase:"); 10016 mOnBatteryScreenOffTimeBase.dump(pw, " "); 10017 Printer pr = new PrintWriterPrinter(pw); 10018 pr.println("*** Screen timer:"); 10019 mScreenOnTimer.logState(pr, " "); 10020 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) { 10021 pr.println("*** Screen brightness #" + i + ":"); 10022 mScreenBrightnessTimer[i].logState(pr, " "); 10023 } 10024 pr.println("*** Interactive timer:"); 10025 mInteractiveTimer.logState(pr, " "); 10026 pr.println("*** Power save mode timer:"); 10027 mPowerSaveModeEnabledTimer.logState(pr, " "); 10028 pr.println("*** Device idle mode timer:"); 10029 mDeviceIdleModeEnabledTimer.logState(pr, " "); 10030 pr.println("*** Device idling timer:"); 10031 mDeviceIdlingTimer.logState(pr, " "); 10032 pr.println("*** Phone timer:"); 10033 mPhoneOnTimer.logState(pr, " "); 10034 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) { 10035 pr.println("*** Phone signal strength #" + i + ":"); 10036 mPhoneSignalStrengthsTimer[i].logState(pr, " "); 10037 } 10038 pr.println("*** Signal scanning :"); 10039 mPhoneSignalScanningTimer.logState(pr, " "); 10040 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) { 10041 pr.println("*** Data connection type #" + i + ":"); 10042 mPhoneDataConnectionsTimer[i].logState(pr, " "); 10043 } 10044 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState); 10045 pr.println("*** Mobile network active timer:"); 10046 mMobileRadioActiveTimer.logState(pr, " "); 10047 pr.println("*** Mobile network active adjusted timer:"); 10048 mMobileRadioActiveAdjustedTime.logState(pr, " "); 10049 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState); 10050 pr.println("*** Wifi timer:"); 10051 mWifiOnTimer.logState(pr, " "); 10052 pr.println("*** WifiRunning timer:"); 10053 mGlobalWifiRunningTimer.logState(pr, " "); 10054 for (int i=0; i<NUM_WIFI_STATES; i++) { 10055 pr.println("*** Wifi state #" + i + ":"); 10056 mWifiStateTimer[i].logState(pr, " "); 10057 } 10058 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) { 10059 pr.println("*** Wifi suppl state #" + i + ":"); 10060 mWifiSupplStateTimer[i].logState(pr, " "); 10061 } 10062 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) { 10063 pr.println("*** Wifi signal strength #" + i + ":"); 10064 mWifiSignalStrengthsTimer[i].logState(pr, " "); 10065 } 10066 pr.println("*** Flashlight timer:"); 10067 mFlashlightOnTimer.logState(pr, " "); 10068 pr.println("*** Camera timer:"); 10069 mCameraOnTimer.logState(pr, " "); 10070 } 10071 super.dumpLocked(context, pw, flags, reqUid, histStart); 10072 } 10073} 10074