BatteryStatsImpl.java revision 6a8bd7bc13251fe1710cb529d14ee28b0c4ab5d0
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> mDrawTimers = 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 draw wake lock.
5653             */
5654            StopwatchTimer mTimerDraw;
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 (mTimerDraw != null) {
5684                    wlactive |= !mTimerDraw.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 (mTimerDraw != null) {
5700                        mTimerDraw.detach();
5701                        mTimerDraw = 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                mTimerDraw = readTimerFromParcel(WAKE_TYPE_DRAW, mDrawTimers, 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, mTimerDraw, 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_DRAW: return mTimerDraw;
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_DRAW:
5761                        t = mTimerDraw;
5762                        if (t == null) {
5763                            t = new StopwatchTimer(Uid.this, WAKE_TYPE_DRAW,
5764                                    mDrawTimers, mOnBatteryTimeBase);
5765                            mTimerDraw = t;
5766                        }
5767                        return t;
5768                    default:
5769                        throw new IllegalArgumentException("type=" + type);
5770                }
5771            }
5772        }
5773
5774        public final class Sensor extends BatteryStats.Uid.Sensor {
5775            final int mHandle;
5776            StopwatchTimer mTimer;
5777
5778            public Sensor(int handle) {
5779                mHandle = handle;
5780            }
5781
5782            private StopwatchTimer readTimerFromParcel(TimeBase timeBase, Parcel in) {
5783                if (in.readInt() == 0) {
5784                    return null;
5785                }
5786
5787                ArrayList<StopwatchTimer> pool = mSensorTimers.get(mHandle);
5788                if (pool == null) {
5789                    pool = new ArrayList<StopwatchTimer>();
5790                    mSensorTimers.put(mHandle, pool);
5791                }
5792                return new StopwatchTimer(Uid.this, 0, pool, timeBase, in);
5793            }
5794
5795            boolean reset() {
5796                if (mTimer.reset(true)) {
5797                    mTimer = null;
5798                    return true;
5799                }
5800                return false;
5801            }
5802
5803            void readFromParcelLocked(TimeBase timeBase, Parcel in) {
5804                mTimer = readTimerFromParcel(timeBase, in);
5805            }
5806
5807            void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
5808                Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
5809            }
5810
5811            @Override
5812            public Timer getSensorTime() {
5813                return mTimer;
5814            }
5815
5816            @Override
5817            public int getHandle() {
5818                return mHandle;
5819            }
5820        }
5821
5822        /**
5823         * The statistics associated with a particular process.
5824         */
5825        public final class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
5826            /**
5827             * The name of this process.
5828             */
5829            final String mName;
5830
5831            /**
5832             * Remains true until removed from the stats.
5833             */
5834            boolean mActive = true;
5835
5836            /**
5837             * Total time (in ms) spent executing in user code.
5838             */
5839            long mUserTime;
5840
5841            /**
5842             * Total time (in ms) spent executing in kernel code.
5843             */
5844            long mSystemTime;
5845
5846            /**
5847             * Amount of time (in ms) the process was running in the foreground.
5848             */
5849            long mForegroundTime;
5850
5851            /**
5852             * Number of times the process has been started.
5853             */
5854            int mStarts;
5855
5856            /**
5857             * Number of times the process has crashed.
5858             */
5859            int mNumCrashes;
5860
5861            /**
5862             * Number of times the process has had an ANR.
5863             */
5864            int mNumAnrs;
5865
5866            /**
5867             * The amount of user time loaded from a previous save.
5868             */
5869            long mLoadedUserTime;
5870
5871            /**
5872             * The amount of system time loaded from a previous save.
5873             */
5874            long mLoadedSystemTime;
5875
5876            /**
5877             * The amount of foreground time loaded from a previous save.
5878             */
5879            long mLoadedForegroundTime;
5880
5881            /**
5882             * The number of times the process has started from a previous save.
5883             */
5884            int mLoadedStarts;
5885
5886            /**
5887             * Number of times the process has crashed from a previous save.
5888             */
5889            int mLoadedNumCrashes;
5890
5891            /**
5892             * Number of times the process has had an ANR from a previous save.
5893             */
5894            int mLoadedNumAnrs;
5895
5896            /**
5897             * The amount of user time when last unplugged.
5898             */
5899            long mUnpluggedUserTime;
5900
5901            /**
5902             * The amount of system time when last unplugged.
5903             */
5904            long mUnpluggedSystemTime;
5905
5906            /**
5907             * The amount of foreground time since unplugged.
5908             */
5909            long mUnpluggedForegroundTime;
5910
5911            /**
5912             * The number of times the process has started before unplugged.
5913             */
5914            int mUnpluggedStarts;
5915
5916            /**
5917             * Number of times the process has crashed before unplugged.
5918             */
5919            int mUnpluggedNumCrashes;
5920
5921            /**
5922             * Number of times the process has had an ANR before unplugged.
5923             */
5924            int mUnpluggedNumAnrs;
5925
5926            /**
5927             * Current process state.
5928             */
5929            int mProcessState = PROCESS_STATE_NONE;
5930
5931            ArrayList<ExcessivePower> mExcessivePower;
5932
5933            Proc(String name) {
5934                mName = name;
5935                mOnBatteryTimeBase.add(this);
5936            }
5937
5938            public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
5939                mUnpluggedUserTime = mUserTime;
5940                mUnpluggedSystemTime = mSystemTime;
5941                mUnpluggedForegroundTime = mForegroundTime;
5942                mUnpluggedStarts = mStarts;
5943                mUnpluggedNumCrashes = mNumCrashes;
5944                mUnpluggedNumAnrs = mNumAnrs;
5945            }
5946
5947            public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
5948            }
5949
5950            void reset() {
5951                mUserTime = mSystemTime = mForegroundTime = 0;
5952                mStarts = mNumCrashes = mNumAnrs = 0;
5953                mLoadedUserTime = mLoadedSystemTime = mLoadedForegroundTime = 0;
5954                mLoadedStarts = mLoadedNumCrashes = mLoadedNumAnrs = 0;
5955                mUnpluggedUserTime = mUnpluggedSystemTime = mUnpluggedForegroundTime = 0;
5956                mUnpluggedStarts = mUnpluggedNumCrashes = mUnpluggedNumAnrs = 0;
5957                mExcessivePower = null;
5958            }
5959
5960            void detach() {
5961                mActive = false;
5962                mOnBatteryTimeBase.remove(this);
5963            }
5964
5965            public int countExcessivePowers() {
5966                return mExcessivePower != null ? mExcessivePower.size() : 0;
5967            }
5968
5969            public ExcessivePower getExcessivePower(int i) {
5970                if (mExcessivePower != null) {
5971                    return mExcessivePower.get(i);
5972                }
5973                return null;
5974            }
5975
5976            public void addExcessiveWake(long overTime, long usedTime) {
5977                if (mExcessivePower == null) {
5978                    mExcessivePower = new ArrayList<ExcessivePower>();
5979                }
5980                ExcessivePower ew = new ExcessivePower();
5981                ew.type = ExcessivePower.TYPE_WAKE;
5982                ew.overTime = overTime;
5983                ew.usedTime = usedTime;
5984                mExcessivePower.add(ew);
5985            }
5986
5987            public void addExcessiveCpu(long overTime, long usedTime) {
5988                if (mExcessivePower == null) {
5989                    mExcessivePower = new ArrayList<ExcessivePower>();
5990                }
5991                ExcessivePower ew = new ExcessivePower();
5992                ew.type = ExcessivePower.TYPE_CPU;
5993                ew.overTime = overTime;
5994                ew.usedTime = usedTime;
5995                mExcessivePower.add(ew);
5996            }
5997
5998            void writeExcessivePowerToParcelLocked(Parcel out) {
5999                if (mExcessivePower == null) {
6000                    out.writeInt(0);
6001                    return;
6002                }
6003
6004                final int N = mExcessivePower.size();
6005                out.writeInt(N);
6006                for (int i=0; i<N; i++) {
6007                    ExcessivePower ew = mExcessivePower.get(i);
6008                    out.writeInt(ew.type);
6009                    out.writeLong(ew.overTime);
6010                    out.writeLong(ew.usedTime);
6011                }
6012            }
6013
6014            boolean readExcessivePowerFromParcelLocked(Parcel in) {
6015                final int N = in.readInt();
6016                if (N == 0) {
6017                    mExcessivePower = null;
6018                    return true;
6019                }
6020
6021                if (N > 10000) {
6022                    Slog.w(TAG, "File corrupt: too many excessive power entries " + N);
6023                    return false;
6024                }
6025
6026                mExcessivePower = new ArrayList<ExcessivePower>();
6027                for (int i=0; i<N; i++) {
6028                    ExcessivePower ew = new ExcessivePower();
6029                    ew.type = in.readInt();
6030                    ew.overTime = in.readLong();
6031                    ew.usedTime = in.readLong();
6032                    mExcessivePower.add(ew);
6033                }
6034                return true;
6035            }
6036
6037            void writeToParcelLocked(Parcel out) {
6038                out.writeLong(mUserTime);
6039                out.writeLong(mSystemTime);
6040                out.writeLong(mForegroundTime);
6041                out.writeInt(mStarts);
6042                out.writeInt(mNumCrashes);
6043                out.writeInt(mNumAnrs);
6044                out.writeLong(mLoadedUserTime);
6045                out.writeLong(mLoadedSystemTime);
6046                out.writeLong(mLoadedForegroundTime);
6047                out.writeInt(mLoadedStarts);
6048                out.writeInt(mLoadedNumCrashes);
6049                out.writeInt(mLoadedNumAnrs);
6050                out.writeLong(mUnpluggedUserTime);
6051                out.writeLong(mUnpluggedSystemTime);
6052                out.writeLong(mUnpluggedForegroundTime);
6053                out.writeInt(mUnpluggedStarts);
6054                out.writeInt(mUnpluggedNumCrashes);
6055                out.writeInt(mUnpluggedNumAnrs);
6056                writeExcessivePowerToParcelLocked(out);
6057            }
6058
6059            void readFromParcelLocked(Parcel in) {
6060                mUserTime = in.readLong();
6061                mSystemTime = in.readLong();
6062                mForegroundTime = in.readLong();
6063                mStarts = in.readInt();
6064                mNumCrashes = in.readInt();
6065                mNumAnrs = in.readInt();
6066                mLoadedUserTime = in.readLong();
6067                mLoadedSystemTime = in.readLong();
6068                mLoadedForegroundTime = in.readLong();
6069                mLoadedStarts = in.readInt();
6070                mLoadedNumCrashes = in.readInt();
6071                mLoadedNumAnrs = in.readInt();
6072                mUnpluggedUserTime = in.readLong();
6073                mUnpluggedSystemTime = in.readLong();
6074                mUnpluggedForegroundTime = in.readLong();
6075                mUnpluggedStarts = in.readInt();
6076                mUnpluggedNumCrashes = in.readInt();
6077                mUnpluggedNumAnrs = in.readInt();
6078                readExcessivePowerFromParcelLocked(in);
6079            }
6080
6081            public void addCpuTimeLocked(int utime, int stime) {
6082                mUserTime += utime;
6083                mSystemTime += stime;
6084            }
6085
6086            public void addForegroundTimeLocked(long ttime) {
6087                mForegroundTime += ttime;
6088            }
6089
6090            public void incStartsLocked() {
6091                mStarts++;
6092            }
6093
6094            public void incNumCrashesLocked() {
6095                mNumCrashes++;
6096            }
6097
6098            public void incNumAnrsLocked() {
6099                mNumAnrs++;
6100            }
6101
6102            @Override
6103            public boolean isActive() {
6104                return mActive;
6105            }
6106
6107            @Override
6108            public long getUserTime(int which) {
6109                long val = mUserTime;
6110                if (which == STATS_CURRENT) {
6111                    val -= mLoadedUserTime;
6112                } else if (which == STATS_SINCE_UNPLUGGED) {
6113                    val -= mUnpluggedUserTime;
6114                }
6115                return val;
6116            }
6117
6118            @Override
6119            public long getSystemTime(int which) {
6120                long val = mSystemTime;
6121                if (which == STATS_CURRENT) {
6122                    val -= mLoadedSystemTime;
6123                } else if (which == STATS_SINCE_UNPLUGGED) {
6124                    val -= mUnpluggedSystemTime;
6125                }
6126                return val;
6127            }
6128
6129            @Override
6130            public long getForegroundTime(int which) {
6131                long val = mForegroundTime;
6132                if (which == STATS_CURRENT) {
6133                    val -= mLoadedForegroundTime;
6134                } else if (which == STATS_SINCE_UNPLUGGED) {
6135                    val -= mUnpluggedForegroundTime;
6136                }
6137                return val;
6138            }
6139
6140            @Override
6141            public int getStarts(int which) {
6142                int val = mStarts;
6143                if (which == STATS_CURRENT) {
6144                    val -= mLoadedStarts;
6145                } else if (which == STATS_SINCE_UNPLUGGED) {
6146                    val -= mUnpluggedStarts;
6147                }
6148                return val;
6149            }
6150
6151            @Override
6152            public int getNumCrashes(int which) {
6153                int val = mNumCrashes;
6154                if (which == STATS_CURRENT) {
6155                    val -= mLoadedNumCrashes;
6156                } else if (which == STATS_SINCE_UNPLUGGED) {
6157                    val -= mUnpluggedNumCrashes;
6158                }
6159                return val;
6160            }
6161
6162            @Override
6163            public int getNumAnrs(int which) {
6164                int val = mNumAnrs;
6165                if (which == STATS_CURRENT) {
6166                    val -= mLoadedNumAnrs;
6167                } else if (which == STATS_SINCE_UNPLUGGED) {
6168                    val -= mUnpluggedNumAnrs;
6169                }
6170                return val;
6171            }
6172        }
6173
6174        /**
6175         * The statistics associated with a particular package.
6176         */
6177        public final class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
6178            /**
6179             * Number of times wakeup alarms have occurred for this app.
6180             */
6181            ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
6182
6183            /**
6184             * The statics we have collected for this package's services.
6185             */
6186            final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
6187
6188            Pkg() {
6189                mOnBatteryScreenOffTimeBase.add(this);
6190            }
6191
6192            public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
6193            }
6194
6195            public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
6196            }
6197
6198            void detach() {
6199                mOnBatteryScreenOffTimeBase.remove(this);
6200            }
6201
6202            void readFromParcelLocked(Parcel in) {
6203                int numWA = in.readInt();
6204                mWakeupAlarms.clear();
6205                for (int i=0; i<numWA; i++) {
6206                    String tag = in.readString();
6207                    mWakeupAlarms.put(tag, new Counter(mOnBatteryTimeBase, in));
6208                }
6209
6210                int numServs = in.readInt();
6211                mServiceStats.clear();
6212                for (int m = 0; m < numServs; m++) {
6213                    String serviceName = in.readString();
6214                    Uid.Pkg.Serv serv = new Serv();
6215                    mServiceStats.put(serviceName, serv);
6216
6217                    serv.readFromParcelLocked(in);
6218                }
6219            }
6220
6221            void writeToParcelLocked(Parcel out) {
6222                int numWA = mWakeupAlarms.size();
6223                out.writeInt(numWA);
6224                for (int i=0; i<numWA; i++) {
6225                    out.writeString(mWakeupAlarms.keyAt(i));
6226                    mWakeupAlarms.valueAt(i).writeToParcel(out);
6227                }
6228
6229                final int NS = mServiceStats.size();
6230                out.writeInt(NS);
6231                for (int i=0; i<NS; i++) {
6232                    out.writeString(mServiceStats.keyAt(i));
6233                    Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
6234                    serv.writeToParcelLocked(out);
6235                }
6236            }
6237
6238            @Override
6239            public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
6240                return mWakeupAlarms;
6241            }
6242
6243            public void noteWakeupAlarmLocked(String tag) {
6244                Counter c = mWakeupAlarms.get(tag);
6245                if (c == null) {
6246                    c = new Counter(mOnBatteryTimeBase);
6247                    mWakeupAlarms.put(tag, c);
6248                }
6249                c.stepAtomic();
6250            }
6251
6252            @Override
6253            public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
6254                return mServiceStats;
6255            }
6256
6257            /**
6258             * The statistics associated with a particular service.
6259             */
6260            public final class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
6261                /**
6262                 * Total time (ms in battery uptime) the service has been left started.
6263                 */
6264                long mStartTime;
6265
6266                /**
6267                 * If service has been started and not yet stopped, this is
6268                 * when it was started.
6269                 */
6270                long mRunningSince;
6271
6272                /**
6273                 * True if we are currently running.
6274                 */
6275                boolean mRunning;
6276
6277                /**
6278                 * Total number of times startService() has been called.
6279                 */
6280                int mStarts;
6281
6282                /**
6283                 * Total time (ms in battery uptime) the service has been left launched.
6284                 */
6285                long mLaunchedTime;
6286
6287                /**
6288                 * If service has been launched and not yet exited, this is
6289                 * when it was launched (ms in battery uptime).
6290                 */
6291                long mLaunchedSince;
6292
6293                /**
6294                 * True if we are currently launched.
6295                 */
6296                boolean mLaunched;
6297
6298                /**
6299                 * Total number times the service has been launched.
6300                 */
6301                int mLaunches;
6302
6303                /**
6304                 * The amount of time spent started loaded from a previous save
6305                 * (ms in battery uptime).
6306                 */
6307                long mLoadedStartTime;
6308
6309                /**
6310                 * The number of starts loaded from a previous save.
6311                 */
6312                int mLoadedStarts;
6313
6314                /**
6315                 * The number of launches loaded from a previous save.
6316                 */
6317                int mLoadedLaunches;
6318
6319                /**
6320                 * The amount of time spent started as of the last run (ms
6321                 * in battery uptime).
6322                 */
6323                long mLastStartTime;
6324
6325                /**
6326                 * The number of starts as of the last run.
6327                 */
6328                int mLastStarts;
6329
6330                /**
6331                 * The number of launches as of the last run.
6332                 */
6333                int mLastLaunches;
6334
6335                /**
6336                 * The amount of time spent started when last unplugged (ms
6337                 * in battery uptime).
6338                 */
6339                long mUnpluggedStartTime;
6340
6341                /**
6342                 * The number of starts when last unplugged.
6343                 */
6344                int mUnpluggedStarts;
6345
6346                /**
6347                 * The number of launches when last unplugged.
6348                 */
6349                int mUnpluggedLaunches;
6350
6351                Serv() {
6352                    mOnBatteryTimeBase.add(this);
6353                }
6354
6355                public void onTimeStarted(long elapsedRealtime, long baseUptime,
6356                        long baseRealtime) {
6357                    mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
6358                    mUnpluggedStarts = mStarts;
6359                    mUnpluggedLaunches = mLaunches;
6360                }
6361
6362                public void onTimeStopped(long elapsedRealtime, long baseUptime,
6363                        long baseRealtime) {
6364                }
6365
6366                void detach() {
6367                    mOnBatteryTimeBase.remove(this);
6368                }
6369
6370                void readFromParcelLocked(Parcel in) {
6371                    mStartTime = in.readLong();
6372                    mRunningSince = in.readLong();
6373                    mRunning = in.readInt() != 0;
6374                    mStarts = in.readInt();
6375                    mLaunchedTime = in.readLong();
6376                    mLaunchedSince = in.readLong();
6377                    mLaunched = in.readInt() != 0;
6378                    mLaunches = in.readInt();
6379                    mLoadedStartTime = in.readLong();
6380                    mLoadedStarts = in.readInt();
6381                    mLoadedLaunches = in.readInt();
6382                    mLastStartTime = 0;
6383                    mLastStarts = 0;
6384                    mLastLaunches = 0;
6385                    mUnpluggedStartTime = in.readLong();
6386                    mUnpluggedStarts = in.readInt();
6387                    mUnpluggedLaunches = in.readInt();
6388                }
6389
6390                void writeToParcelLocked(Parcel out) {
6391                    out.writeLong(mStartTime);
6392                    out.writeLong(mRunningSince);
6393                    out.writeInt(mRunning ? 1 : 0);
6394                    out.writeInt(mStarts);
6395                    out.writeLong(mLaunchedTime);
6396                    out.writeLong(mLaunchedSince);
6397                    out.writeInt(mLaunched ? 1 : 0);
6398                    out.writeInt(mLaunches);
6399                    out.writeLong(mLoadedStartTime);
6400                    out.writeInt(mLoadedStarts);
6401                    out.writeInt(mLoadedLaunches);
6402                    out.writeLong(mUnpluggedStartTime);
6403                    out.writeInt(mUnpluggedStarts);
6404                    out.writeInt(mUnpluggedLaunches);
6405                }
6406
6407                long getLaunchTimeToNowLocked(long batteryUptime) {
6408                    if (!mLaunched) return mLaunchedTime;
6409                    return mLaunchedTime + batteryUptime - mLaunchedSince;
6410                }
6411
6412                long getStartTimeToNowLocked(long batteryUptime) {
6413                    if (!mRunning) return mStartTime;
6414                    return mStartTime + batteryUptime - mRunningSince;
6415                }
6416
6417                public void startLaunchedLocked() {
6418                    if (!mLaunched) {
6419                        mLaunches++;
6420                        mLaunchedSince = getBatteryUptimeLocked();
6421                        mLaunched = true;
6422                    }
6423                }
6424
6425                public void stopLaunchedLocked() {
6426                    if (mLaunched) {
6427                        long time = getBatteryUptimeLocked() - mLaunchedSince;
6428                        if (time > 0) {
6429                            mLaunchedTime += time;
6430                        } else {
6431                            mLaunches--;
6432                        }
6433                        mLaunched = false;
6434                    }
6435                }
6436
6437                public void startRunningLocked() {
6438                    if (!mRunning) {
6439                        mStarts++;
6440                        mRunningSince = getBatteryUptimeLocked();
6441                        mRunning = true;
6442                    }
6443                }
6444
6445                public void stopRunningLocked() {
6446                    if (mRunning) {
6447                        long time = getBatteryUptimeLocked() - mRunningSince;
6448                        if (time > 0) {
6449                            mStartTime += time;
6450                        } else {
6451                            mStarts--;
6452                        }
6453                        mRunning = false;
6454                    }
6455                }
6456
6457                public BatteryStatsImpl getBatteryStats() {
6458                    return BatteryStatsImpl.this;
6459                }
6460
6461                @Override
6462                public int getLaunches(int which) {
6463                    int val = mLaunches;
6464                    if (which == STATS_CURRENT) {
6465                        val -= mLoadedLaunches;
6466                    } else if (which == STATS_SINCE_UNPLUGGED) {
6467                        val -= mUnpluggedLaunches;
6468                    }
6469                    return val;
6470                }
6471
6472                @Override
6473                public long getStartTime(long now, int which) {
6474                    long val = getStartTimeToNowLocked(now);
6475                    if (which == STATS_CURRENT) {
6476                        val -= mLoadedStartTime;
6477                    } else if (which == STATS_SINCE_UNPLUGGED) {
6478                        val -= mUnpluggedStartTime;
6479                    }
6480                    return val;
6481                }
6482
6483                @Override
6484                public int getStarts(int which) {
6485                    int val = mStarts;
6486                    if (which == STATS_CURRENT) {
6487                        val -= mLoadedStarts;
6488                    } else if (which == STATS_SINCE_UNPLUGGED) {
6489                        val -= mUnpluggedStarts;
6490                    }
6491
6492                    return val;
6493                }
6494            }
6495
6496            final Serv newServiceStatsLocked() {
6497                return new Serv();
6498            }
6499        }
6500
6501        /**
6502         * Retrieve the statistics object for a particular process, creating
6503         * if needed.
6504         */
6505        public Proc getProcessStatsLocked(String name) {
6506            Proc ps = mProcessStats.get(name);
6507            if (ps == null) {
6508                ps = new Proc(name);
6509                mProcessStats.put(name, ps);
6510            }
6511
6512            return ps;
6513        }
6514
6515        public void updateProcessStateLocked(String procName, int state, long elapsedRealtimeMs) {
6516            int procState;
6517            if (state <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
6518                procState = PROCESS_STATE_FOREGROUND;
6519            } else if (state <= ActivityManager.PROCESS_STATE_RECEIVER) {
6520                procState = PROCESS_STATE_ACTIVE;
6521            } else {
6522                procState = PROCESS_STATE_RUNNING;
6523            }
6524            updateRealProcessStateLocked(procName, procState, elapsedRealtimeMs);
6525        }
6526
6527        public void updateRealProcessStateLocked(String procName, int procState,
6528                long elapsedRealtimeMs) {
6529            Proc proc = getProcessStatsLocked(procName);
6530            if (proc.mProcessState != procState) {
6531                boolean changed;
6532                if (procState < proc.mProcessState) {
6533                    // Has this process become more important?  If so,
6534                    // we may need to change the uid if the currrent uid proc state
6535                    // is not as important as what we are now setting.
6536                    changed = mProcessState > procState;
6537                } else {
6538                    // Has this process become less important?  If so,
6539                    // we may need to change the uid if the current uid proc state
6540                    // is the same importance as the old setting.
6541                    changed = mProcessState == proc.mProcessState;
6542                }
6543                proc.mProcessState = procState;
6544                if (changed) {
6545                    // uid's state may have changed; compute what the new state should be.
6546                    int uidProcState = PROCESS_STATE_NONE;
6547                    for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
6548                        proc = mProcessStats.valueAt(ip);
6549                        if (proc.mProcessState < uidProcState) {
6550                            uidProcState = proc.mProcessState;
6551                        }
6552                    }
6553                    updateUidProcessStateLocked(uidProcState, elapsedRealtimeMs);
6554                }
6555            }
6556        }
6557
6558        public SparseArray<? extends Pid> getPidStats() {
6559            return mPids;
6560        }
6561
6562        public Pid getPidStatsLocked(int pid) {
6563            Pid p = mPids.get(pid);
6564            if (p == null) {
6565                p = new Pid();
6566                mPids.put(pid, p);
6567            }
6568            return p;
6569        }
6570
6571        /**
6572         * Retrieve the statistics object for a particular service, creating
6573         * if needed.
6574         */
6575        public Pkg getPackageStatsLocked(String name) {
6576            Pkg ps = mPackageStats.get(name);
6577            if (ps == null) {
6578                ps = new Pkg();
6579                mPackageStats.put(name, ps);
6580            }
6581
6582            return ps;
6583        }
6584
6585        /**
6586         * Retrieve the statistics object for a particular service, creating
6587         * if needed.
6588         */
6589        public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
6590            Pkg ps = getPackageStatsLocked(pkg);
6591            Pkg.Serv ss = ps.mServiceStats.get(serv);
6592            if (ss == null) {
6593                ss = ps.newServiceStatsLocked();
6594                ps.mServiceStats.put(serv, ss);
6595            }
6596
6597            return ss;
6598        }
6599
6600        public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
6601            StopwatchTimer timer = mSyncStats.instantiateObject();
6602            timer.readSummaryFromParcelLocked(in);
6603            mSyncStats.add(name, timer);
6604        }
6605
6606        public void readJobSummaryFromParcelLocked(String name, Parcel in) {
6607            StopwatchTimer timer = mJobStats.instantiateObject();
6608            timer.readSummaryFromParcelLocked(in);
6609            mJobStats.add(name, timer);
6610        }
6611
6612        public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
6613            Wakelock wl = new Wakelock();
6614            mWakelockStats.add(wlName, wl);
6615            if (in.readInt() != 0) {
6616                wl.getStopwatchTimer(WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
6617            }
6618            if (in.readInt() != 0) {
6619                wl.getStopwatchTimer(WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
6620            }
6621            if (in.readInt() != 0) {
6622                wl.getStopwatchTimer(WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
6623            }
6624            if (in.readInt() != 0) {
6625                wl.getStopwatchTimer(WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
6626            }
6627        }
6628
6629        public StopwatchTimer getSensorTimerLocked(int sensor, boolean create) {
6630            Sensor se = mSensorStats.get(sensor);
6631            if (se == null) {
6632                if (!create) {
6633                    return null;
6634                }
6635                se = new Sensor(sensor);
6636                mSensorStats.put(sensor, se);
6637            }
6638            StopwatchTimer t = se.mTimer;
6639            if (t != null) {
6640                return t;
6641            }
6642            ArrayList<StopwatchTimer> timers = mSensorTimers.get(sensor);
6643            if (timers == null) {
6644                timers = new ArrayList<StopwatchTimer>();
6645                mSensorTimers.put(sensor, timers);
6646            }
6647            t = new StopwatchTimer(Uid.this, BatteryStats.SENSOR, timers, mOnBatteryTimeBase);
6648            se.mTimer = t;
6649            return t;
6650        }
6651
6652        public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
6653            StopwatchTimer t = mSyncStats.startObject(name);
6654            if (t != null) {
6655                t.startRunningLocked(elapsedRealtimeMs);
6656            }
6657        }
6658
6659        public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
6660            StopwatchTimer t = mSyncStats.stopObject(name);
6661            if (t != null) {
6662                t.stopRunningLocked(elapsedRealtimeMs);
6663            }
6664        }
6665
6666        public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
6667            StopwatchTimer t = mJobStats.startObject(name);
6668            if (t != null) {
6669                t.startRunningLocked(elapsedRealtimeMs);
6670            }
6671        }
6672
6673        public void noteStopJobLocked(String name, long elapsedRealtimeMs) {
6674            StopwatchTimer t = mJobStats.stopObject(name);
6675            if (t != null) {
6676                t.stopRunningLocked(elapsedRealtimeMs);
6677            }
6678        }
6679
6680        public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
6681            Wakelock wl = mWakelockStats.startObject(name);
6682            if (wl != null) {
6683                wl.getStopwatchTimer(type).startRunningLocked(elapsedRealtimeMs);
6684            }
6685            if (pid >= 0 && type == WAKE_TYPE_PARTIAL) {
6686                Pid p = getPidStatsLocked(pid);
6687                if (p.mWakeNesting++ == 0) {
6688                    p.mWakeStartMs = elapsedRealtimeMs;
6689                }
6690            }
6691        }
6692
6693        public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
6694            Wakelock wl = mWakelockStats.stopObject(name);
6695            if (wl != null) {
6696                wl.getStopwatchTimer(type).stopRunningLocked(elapsedRealtimeMs);
6697            }
6698            if (pid >= 0 && type == WAKE_TYPE_PARTIAL) {
6699                Pid p = mPids.get(pid);
6700                if (p != null && p.mWakeNesting > 0) {
6701                    if (p.mWakeNesting-- == 1) {
6702                        p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
6703                        p.mWakeStartMs = 0;
6704                    }
6705                }
6706            }
6707        }
6708
6709        public void reportExcessiveWakeLocked(String proc, long overTime, long usedTime) {
6710            Proc p = getProcessStatsLocked(proc);
6711            if (p != null) {
6712                p.addExcessiveWake(overTime, usedTime);
6713            }
6714        }
6715
6716        public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
6717            Proc p = getProcessStatsLocked(proc);
6718            if (p != null) {
6719                p.addExcessiveCpu(overTime, usedTime);
6720            }
6721        }
6722
6723        public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
6724            StopwatchTimer t = getSensorTimerLocked(sensor, true);
6725            if (t != null) {
6726                t.startRunningLocked(elapsedRealtimeMs);
6727            }
6728        }
6729
6730        public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
6731            // Don't create a timer if one doesn't already exist
6732            StopwatchTimer t = getSensorTimerLocked(sensor, false);
6733            if (t != null) {
6734                t.stopRunningLocked(elapsedRealtimeMs);
6735            }
6736        }
6737
6738        public void noteStartGps(long elapsedRealtimeMs) {
6739            StopwatchTimer t = getSensorTimerLocked(Sensor.GPS, true);
6740            if (t != null) {
6741                t.startRunningLocked(elapsedRealtimeMs);
6742            }
6743        }
6744
6745        public void noteStopGps(long elapsedRealtimeMs) {
6746            StopwatchTimer t = getSensorTimerLocked(Sensor.GPS, false);
6747            if (t != null) {
6748                t.stopRunningLocked(elapsedRealtimeMs);
6749            }
6750        }
6751
6752        public BatteryStatsImpl getBatteryStats() {
6753            return BatteryStatsImpl.this;
6754        }
6755    }
6756
6757    public BatteryStatsImpl(File systemDir, Handler handler, ExternalStatsSync externalSync) {
6758        if (systemDir != null) {
6759            mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
6760                    new File(systemDir, "batterystats.bin.tmp"));
6761        } else {
6762            mFile = null;
6763        }
6764        mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
6765        mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
6766        mExternalSync = externalSync;
6767        mHandler = new MyHandler(handler.getLooper());
6768        mStartCount++;
6769        mScreenOnTimer = new StopwatchTimer(null, -1, null, mOnBatteryTimeBase);
6770        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
6771            mScreenBrightnessTimer[i] = new StopwatchTimer(null, -100-i, null, mOnBatteryTimeBase);
6772        }
6773        mInteractiveTimer = new StopwatchTimer(null, -10, null, mOnBatteryTimeBase);
6774        mPowerSaveModeEnabledTimer = new StopwatchTimer(null, -2, null, mOnBatteryTimeBase);
6775        mDeviceIdleModeEnabledTimer = new StopwatchTimer(null, -11, null, mOnBatteryTimeBase);
6776        mDeviceIdlingTimer = new StopwatchTimer(null, -12, null, mOnBatteryTimeBase);
6777        mPhoneOnTimer = new StopwatchTimer(null, -3, null, mOnBatteryTimeBase);
6778        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
6779            mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(null, -200-i, null,
6780                    mOnBatteryTimeBase);
6781        }
6782        mPhoneSignalScanningTimer = new StopwatchTimer(null, -200+1, null, mOnBatteryTimeBase);
6783        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
6784            mPhoneDataConnectionsTimer[i] = new StopwatchTimer(null, -300-i, null,
6785                    mOnBatteryTimeBase);
6786        }
6787        for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
6788            mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
6789            mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
6790        }
6791        for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
6792            mBluetoothActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
6793            mWifiActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
6794        }
6795        mMobileRadioActiveTimer = new StopwatchTimer(null, -400, null, mOnBatteryTimeBase);
6796        mMobileRadioActivePerAppTimer = new StopwatchTimer(null, -401, null, mOnBatteryTimeBase);
6797        mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
6798        mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
6799        mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
6800        mWifiOnTimer = new StopwatchTimer(null, -4, null, mOnBatteryTimeBase);
6801        mGlobalWifiRunningTimer = new StopwatchTimer(null, -5, null, mOnBatteryTimeBase);
6802        for (int i=0; i<NUM_WIFI_STATES; i++) {
6803            mWifiStateTimer[i] = new StopwatchTimer(null, -600-i, null, mOnBatteryTimeBase);
6804        }
6805        for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
6806            mWifiSupplStateTimer[i] = new StopwatchTimer(null, -700-i, null, mOnBatteryTimeBase);
6807        }
6808        for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
6809            mWifiSignalStrengthsTimer[i] = new StopwatchTimer(null, -800-i, null,
6810                    mOnBatteryTimeBase);
6811        }
6812        mAudioOnTimer = new StopwatchTimer(null, -7, null, mOnBatteryTimeBase);
6813        mVideoOnTimer = new StopwatchTimer(null, -8, null, mOnBatteryTimeBase);
6814        mFlashlightOnTimer = new StopwatchTimer(null, -9, null, mOnBatteryTimeBase);
6815        mCameraOnTimer = new StopwatchTimer(null, -13, null, mOnBatteryTimeBase);
6816        mOnBattery = mOnBatteryInternal = false;
6817        long uptime = SystemClock.uptimeMillis() * 1000;
6818        long realtime = SystemClock.elapsedRealtime() * 1000;
6819        initTimes(uptime, realtime);
6820        mStartPlatformVersion = mEndPlatformVersion = Build.ID;
6821        mDischargeStartLevel = 0;
6822        mDischargeUnplugLevel = 0;
6823        mDischargePlugLevel = -1;
6824        mDischargeCurrentLevel = 0;
6825        mCurrentBatteryLevel = 0;
6826        initDischarge();
6827        clearHistoryLocked();
6828        updateDailyDeadlineLocked();
6829    }
6830
6831    public BatteryStatsImpl(Parcel p) {
6832        mFile = null;
6833        mCheckinFile = null;
6834        mDailyFile = null;
6835        mHandler = null;
6836        mExternalSync = null;
6837        clearHistoryLocked();
6838        readFromParcel(p);
6839    }
6840
6841    public void setPowerProfile(PowerProfile profile) {
6842        synchronized (this) {
6843            mPowerProfile = profile;
6844        }
6845    }
6846
6847    public void setCallback(BatteryCallback cb) {
6848        mCallback = cb;
6849    }
6850
6851    public void setNumSpeedSteps(int steps) {
6852        if (sNumSpeedSteps == 0) sNumSpeedSteps = steps;
6853    }
6854
6855    public void setRadioScanningTimeout(long timeout) {
6856        if (mPhoneSignalScanningTimer != null) {
6857            mPhoneSignalScanningTimer.setTimeout(timeout);
6858        }
6859    }
6860
6861    public void updateDailyDeadlineLocked() {
6862        // Get the current time.
6863        long currentTime = mDailyStartTime = System.currentTimeMillis();
6864        Calendar calDeadline = Calendar.getInstance();
6865        calDeadline.setTimeInMillis(currentTime);
6866
6867        // Move time up to the next day, ranging from 1am to 3pm.
6868        calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
6869        calDeadline.set(Calendar.MILLISECOND, 0);
6870        calDeadline.set(Calendar.SECOND, 0);
6871        calDeadline.set(Calendar.MINUTE, 0);
6872        calDeadline.set(Calendar.HOUR_OF_DAY, 1);
6873        mNextMinDailyDeadline = calDeadline.getTimeInMillis();
6874        calDeadline.set(Calendar.HOUR_OF_DAY, 3);
6875        mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
6876    }
6877
6878    public void recordDailyStatsIfNeededLocked(boolean settled) {
6879        long currentTime = System.currentTimeMillis();
6880        if (currentTime >= mNextMaxDailyDeadline) {
6881            recordDailyStatsLocked();
6882        } else if (settled && currentTime >= mNextMinDailyDeadline) {
6883            recordDailyStatsLocked();
6884        } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
6885            recordDailyStatsLocked();
6886        }
6887    }
6888
6889    public void recordDailyStatsLocked() {
6890        DailyItem item = new DailyItem();
6891        item.mStartTime = mDailyStartTime;
6892        item.mEndTime = System.currentTimeMillis();
6893        boolean hasData = false;
6894        if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
6895            hasData = true;
6896            item.mDischargeSteps = new LevelStepTracker(
6897                    mDailyDischargeStepTracker.mNumStepDurations,
6898                    mDailyDischargeStepTracker.mStepDurations);
6899        }
6900        if (mDailyChargeStepTracker.mNumStepDurations > 0) {
6901            hasData = true;
6902            item.mChargeSteps = new LevelStepTracker(
6903                    mDailyChargeStepTracker.mNumStepDurations,
6904                    mDailyChargeStepTracker.mStepDurations);
6905        }
6906        if (mDailyPackageChanges != null) {
6907            hasData = true;
6908            item.mPackageChanges = mDailyPackageChanges;
6909            mDailyPackageChanges = null;
6910        }
6911        mDailyDischargeStepTracker.init();
6912        mDailyChargeStepTracker.init();
6913        updateDailyDeadlineLocked();
6914
6915        if (hasData) {
6916            mDailyItems.add(item);
6917            while (mDailyItems.size() > MAX_DAILY_ITEMS) {
6918                mDailyItems.remove(0);
6919            }
6920            final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
6921            try {
6922                XmlSerializer out = new FastXmlSerializer();
6923                out.setOutput(memStream, StandardCharsets.UTF_8.name());
6924                writeDailyItemsLocked(out);
6925                BackgroundThread.getHandler().post(new Runnable() {
6926                    @Override
6927                    public void run() {
6928                        synchronized (mCheckinFile) {
6929                            FileOutputStream stream = null;
6930                            try {
6931                                stream = mDailyFile.startWrite();
6932                                memStream.writeTo(stream);
6933                                stream.flush();
6934                                FileUtils.sync(stream);
6935                                stream.close();
6936                                mDailyFile.finishWrite(stream);
6937                            } catch (IOException e) {
6938                                Slog.w("BatteryStats",
6939                                        "Error writing battery daily items", e);
6940                                mDailyFile.failWrite(stream);
6941                            }
6942                        }
6943                    }
6944                });
6945            } catch (IOException e) {
6946            }
6947        }
6948    }
6949
6950    private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
6951        StringBuilder sb = new StringBuilder(64);
6952        out.startDocument(null, true);
6953        out.startTag(null, "daily-items");
6954        for (int i=0; i<mDailyItems.size(); i++) {
6955            final DailyItem dit = mDailyItems.get(i);
6956            out.startTag(null, "item");
6957            out.attribute(null, "start", Long.toString(dit.mStartTime));
6958            out.attribute(null, "end", Long.toString(dit.mEndTime));
6959            writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
6960            writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
6961            if (dit.mPackageChanges != null) {
6962                for (int j=0; j<dit.mPackageChanges.size(); j++) {
6963                    PackageChange pc = dit.mPackageChanges.get(j);
6964                    if (pc.mUpdate) {
6965                        out.startTag(null, "upd");
6966                        out.attribute(null, "pkg", pc.mPackageName);
6967                        out.attribute(null, "ver", Integer.toString(pc.mVersionCode));
6968                        out.endTag(null, "upd");
6969                    } else {
6970                        out.startTag(null, "rem");
6971                        out.attribute(null, "pkg", pc.mPackageName);
6972                        out.endTag(null, "rem");
6973                    }
6974                }
6975            }
6976            out.endTag(null, "item");
6977        }
6978        out.endTag(null, "daily-items");
6979        out.endDocument();
6980    }
6981
6982    private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
6983            StringBuilder tmpBuilder) throws IOException {
6984        if (steps != null) {
6985            out.startTag(null, tag);
6986            out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
6987            for (int i=0; i<steps.mNumStepDurations; i++) {
6988                out.startTag(null, "s");
6989                tmpBuilder.setLength(0);
6990                steps.encodeEntryAt(i, tmpBuilder);
6991                out.attribute(null, "v", tmpBuilder.toString());
6992                out.endTag(null, "s");
6993            }
6994            out.endTag(null, tag);
6995        }
6996    }
6997
6998    public void readDailyStatsLocked() {
6999        Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
7000        mDailyItems.clear();
7001        FileInputStream stream;
7002        try {
7003            stream = mDailyFile.openRead();
7004        } catch (FileNotFoundException e) {
7005            return;
7006        }
7007        try {
7008            XmlPullParser parser = Xml.newPullParser();
7009            parser.setInput(stream, StandardCharsets.UTF_8.name());
7010            readDailyItemsLocked(parser);
7011        } catch (XmlPullParserException e) {
7012        } finally {
7013            try {
7014                stream.close();
7015            } catch (IOException e) {
7016            }
7017        }
7018    }
7019
7020    private void readDailyItemsLocked(XmlPullParser parser) {
7021        try {
7022            int type;
7023            while ((type = parser.next()) != XmlPullParser.START_TAG
7024                    && type != XmlPullParser.END_DOCUMENT) {
7025                ;
7026            }
7027
7028            if (type != XmlPullParser.START_TAG) {
7029                throw new IllegalStateException("no start tag found");
7030            }
7031
7032            int outerDepth = parser.getDepth();
7033            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
7034                    && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
7035                if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
7036                    continue;
7037                }
7038
7039                String tagName = parser.getName();
7040                if (tagName.equals("item")) {
7041                    readDailyItemTagLocked(parser);
7042                } else {
7043                    Slog.w(TAG, "Unknown element under <daily-items>: "
7044                            + parser.getName());
7045                    XmlUtils.skipCurrentTag(parser);
7046                }
7047            }
7048
7049        } catch (IllegalStateException e) {
7050            Slog.w(TAG, "Failed parsing daily " + e);
7051        } catch (NullPointerException e) {
7052            Slog.w(TAG, "Failed parsing daily " + e);
7053        } catch (NumberFormatException e) {
7054            Slog.w(TAG, "Failed parsing daily " + e);
7055        } catch (XmlPullParserException e) {
7056            Slog.w(TAG, "Failed parsing daily " + e);
7057        } catch (IOException e) {
7058            Slog.w(TAG, "Failed parsing daily " + e);
7059        } catch (IndexOutOfBoundsException e) {
7060            Slog.w(TAG, "Failed parsing daily " + e);
7061        }
7062    }
7063
7064    void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
7065            XmlPullParserException, IOException {
7066        DailyItem dit = new DailyItem();
7067        String attr = parser.getAttributeValue(null, "start");
7068        if (attr != null) {
7069            dit.mStartTime = Long.parseLong(attr);
7070        }
7071        attr = parser.getAttributeValue(null, "end");
7072        if (attr != null) {
7073            dit.mEndTime = Long.parseLong(attr);
7074        }
7075        int outerDepth = parser.getDepth();
7076        int type;
7077        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
7078                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
7079            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
7080                continue;
7081            }
7082
7083            String tagName = parser.getName();
7084            if (tagName.equals("dis")) {
7085                readDailyItemTagDetailsLocked(parser, dit, false, "dis");
7086            } else if (tagName.equals("chg")) {
7087                readDailyItemTagDetailsLocked(parser, dit, true, "chg");
7088            } else if (tagName.equals("upd")) {
7089                if (dit.mPackageChanges == null) {
7090                    dit.mPackageChanges = new ArrayList<>();
7091                }
7092                PackageChange pc = new PackageChange();
7093                pc.mUpdate = true;
7094                pc.mPackageName = parser.getAttributeValue(null, "pkg");
7095                String verStr = parser.getAttributeValue(null, "ver");
7096                pc.mVersionCode = verStr != null ? Integer.parseInt(verStr) : 0;
7097                dit.mPackageChanges.add(pc);
7098                XmlUtils.skipCurrentTag(parser);
7099            } else if (tagName.equals("rem")) {
7100                if (dit.mPackageChanges == null) {
7101                    dit.mPackageChanges = new ArrayList<>();
7102                }
7103                PackageChange pc = new PackageChange();
7104                pc.mUpdate = false;
7105                pc.mPackageName = parser.getAttributeValue(null, "pkg");
7106                dit.mPackageChanges.add(pc);
7107                XmlUtils.skipCurrentTag(parser);
7108            } else {
7109                Slog.w(TAG, "Unknown element under <item>: "
7110                        + parser.getName());
7111                XmlUtils.skipCurrentTag(parser);
7112            }
7113        }
7114        mDailyItems.add(dit);
7115    }
7116
7117    void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
7118            String tag)
7119            throws NumberFormatException, XmlPullParserException, IOException {
7120        final String numAttr = parser.getAttributeValue(null, "n");
7121        if (numAttr == null) {
7122            Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
7123            XmlUtils.skipCurrentTag(parser);
7124            return;
7125        }
7126        final int num = Integer.parseInt(numAttr);
7127        LevelStepTracker steps = new LevelStepTracker(num);
7128        if (isCharge) {
7129            dit.mChargeSteps = steps;
7130        } else {
7131            dit.mDischargeSteps = steps;
7132        }
7133        int i = 0;
7134        int outerDepth = parser.getDepth();
7135        int type;
7136        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
7137                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
7138            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
7139                continue;
7140            }
7141
7142            String tagName = parser.getName();
7143            if ("s".equals(tagName)) {
7144                if (i < num) {
7145                    String valueAttr = parser.getAttributeValue(null, "v");
7146                    if (valueAttr != null) {
7147                        steps.decodeEntryAt(i, valueAttr);
7148                        i++;
7149                    }
7150                }
7151            } else {
7152                Slog.w(TAG, "Unknown element under <" + tag + ">: "
7153                        + parser.getName());
7154                XmlUtils.skipCurrentTag(parser);
7155            }
7156        }
7157        steps.mNumStepDurations = i;
7158    }
7159
7160    @Override
7161    public DailyItem getDailyItemLocked(int daysAgo) {
7162        int index = mDailyItems.size()-1-daysAgo;
7163        return index >= 0 ? mDailyItems.get(index) : null;
7164    }
7165
7166    @Override
7167    public long getCurrentDailyStartTime() {
7168        return mDailyStartTime;
7169    }
7170
7171    @Override
7172    public long getNextMinDailyDeadline() {
7173        return mNextMinDailyDeadline;
7174    }
7175
7176    @Override
7177    public long getNextMaxDailyDeadline() {
7178        return mNextMaxDailyDeadline;
7179    }
7180
7181    @Override
7182    public boolean startIteratingOldHistoryLocked() {
7183        if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
7184                + " pos=" + mHistoryBuffer.dataPosition());
7185        if ((mHistoryIterator = mHistory) == null) {
7186            return false;
7187        }
7188        mHistoryBuffer.setDataPosition(0);
7189        mHistoryReadTmp.clear();
7190        mReadOverflow = false;
7191        mIteratingHistory = true;
7192        return true;
7193    }
7194
7195    @Override
7196    public boolean getNextOldHistoryLocked(HistoryItem out) {
7197        boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
7198        if (!end) {
7199            readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
7200            mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
7201        }
7202        HistoryItem cur = mHistoryIterator;
7203        if (cur == null) {
7204            if (!mReadOverflow && !end) {
7205                Slog.w(TAG, "Old history ends before new history!");
7206            }
7207            return false;
7208        }
7209        out.setTo(cur);
7210        mHistoryIterator = cur.next;
7211        if (!mReadOverflow) {
7212            if (end) {
7213                Slog.w(TAG, "New history ends before old history!");
7214            } else if (!out.same(mHistoryReadTmp)) {
7215                PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
7216                pw.println("Histories differ!");
7217                pw.println("Old history:");
7218                (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
7219                pw.println("New history:");
7220                (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
7221                        true);
7222                pw.flush();
7223            }
7224        }
7225        return true;
7226    }
7227
7228    @Override
7229    public void finishIteratingOldHistoryLocked() {
7230        mIteratingHistory = false;
7231        mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
7232        mHistoryIterator = null;
7233    }
7234
7235    public int getHistoryTotalSize() {
7236        return MAX_HISTORY_BUFFER;
7237    }
7238
7239    public int getHistoryUsedSize() {
7240        return mHistoryBuffer.dataSize();
7241    }
7242
7243    @Override
7244    public boolean startIteratingHistoryLocked() {
7245        if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
7246                + " pos=" + mHistoryBuffer.dataPosition());
7247        if (mHistoryBuffer.dataSize() <= 0) {
7248            return false;
7249        }
7250        mHistoryBuffer.setDataPosition(0);
7251        mReadOverflow = false;
7252        mIteratingHistory = true;
7253        mReadHistoryStrings = new String[mHistoryTagPool.size()];
7254        mReadHistoryUids = new int[mHistoryTagPool.size()];
7255        mReadHistoryChars = 0;
7256        for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
7257            final HistoryTag tag = ent.getKey();
7258            final int idx = ent.getValue();
7259            mReadHistoryStrings[idx] = tag.string;
7260            mReadHistoryUids[idx] = tag.uid;
7261            mReadHistoryChars += tag.string.length() + 1;
7262        }
7263        return true;
7264    }
7265
7266    @Override
7267    public int getHistoryStringPoolSize() {
7268        return mReadHistoryStrings.length;
7269    }
7270
7271    @Override
7272    public int getHistoryStringPoolBytes() {
7273        // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
7274        // Each string character is 2 bytes.
7275        return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
7276    }
7277
7278    @Override
7279    public String getHistoryTagPoolString(int index) {
7280        return mReadHistoryStrings[index];
7281    }
7282
7283    @Override
7284    public int getHistoryTagPoolUid(int index) {
7285        return mReadHistoryUids[index];
7286    }
7287
7288    @Override
7289    public boolean getNextHistoryLocked(HistoryItem out) {
7290        final int pos = mHistoryBuffer.dataPosition();
7291        if (pos == 0) {
7292            out.clear();
7293        }
7294        boolean end = pos >= mHistoryBuffer.dataSize();
7295        if (end) {
7296            return false;
7297        }
7298
7299        final long lastRealtime = out.time;
7300        final long lastWalltime = out.currentTime;
7301        readHistoryDelta(mHistoryBuffer, out);
7302        if (out.cmd != HistoryItem.CMD_CURRENT_TIME
7303                && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
7304            out.currentTime = lastWalltime + (out.time - lastRealtime);
7305        }
7306        return true;
7307    }
7308
7309    @Override
7310    public void finishIteratingHistoryLocked() {
7311        mIteratingHistory = false;
7312        mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
7313        mReadHistoryStrings = null;
7314    }
7315
7316    @Override
7317    public long getHistoryBaseTime() {
7318        return mHistoryBaseTime;
7319    }
7320
7321    @Override
7322    public int getStartCount() {
7323        return mStartCount;
7324    }
7325
7326    public boolean isOnBattery() {
7327        return mOnBattery;
7328    }
7329
7330    public boolean isCharging() {
7331        return mCharging;
7332    }
7333
7334    public boolean isScreenOn() {
7335        return mScreenState == Display.STATE_ON;
7336    }
7337
7338    void initTimes(long uptime, long realtime) {
7339        mStartClockTime = System.currentTimeMillis();
7340        mOnBatteryTimeBase.init(uptime, realtime);
7341        mOnBatteryScreenOffTimeBase.init(uptime, realtime);
7342        mRealtime = 0;
7343        mUptime = 0;
7344        mRealtimeStart = realtime;
7345        mUptimeStart = uptime;
7346    }
7347
7348    void initDischarge() {
7349        mLowDischargeAmountSinceCharge = 0;
7350        mHighDischargeAmountSinceCharge = 0;
7351        mDischargeAmountScreenOn = 0;
7352        mDischargeAmountScreenOnSinceCharge = 0;
7353        mDischargeAmountScreenOff = 0;
7354        mDischargeAmountScreenOffSinceCharge = 0;
7355        mDischargeStepTracker.init();
7356        mChargeStepTracker.init();
7357    }
7358
7359    public void resetAllStatsCmdLocked() {
7360        resetAllStatsLocked();
7361        final long mSecUptime = SystemClock.uptimeMillis();
7362        long uptime = mSecUptime * 1000;
7363        long mSecRealtime = SystemClock.elapsedRealtime();
7364        long realtime = mSecRealtime * 1000;
7365        mDischargeStartLevel = mHistoryCur.batteryLevel;
7366        pullPendingStateUpdatesLocked();
7367        addHistoryRecordLocked(mSecRealtime, mSecUptime);
7368        mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
7369                = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
7370        mOnBatteryTimeBase.reset(uptime, realtime);
7371        mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
7372        if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
7373            if (mScreenState == Display.STATE_ON) {
7374                mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
7375                mDischargeScreenOffUnplugLevel = 0;
7376            } else {
7377                mDischargeScreenOnUnplugLevel = 0;
7378                mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
7379            }
7380            mDischargeAmountScreenOn = 0;
7381            mDischargeAmountScreenOff = 0;
7382        }
7383        initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
7384    }
7385
7386    private void resetAllStatsLocked() {
7387        mStartCount = 0;
7388        initTimes(SystemClock.uptimeMillis() * 1000, SystemClock.elapsedRealtime() * 1000);
7389        mScreenOnTimer.reset(false);
7390        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
7391            mScreenBrightnessTimer[i].reset(false);
7392        }
7393        mInteractiveTimer.reset(false);
7394        mPowerSaveModeEnabledTimer.reset(false);
7395        mDeviceIdleModeEnabledTimer.reset(false);
7396        mDeviceIdlingTimer.reset(false);
7397        mPhoneOnTimer.reset(false);
7398        mAudioOnTimer.reset(false);
7399        mVideoOnTimer.reset(false);
7400        mFlashlightOnTimer.reset(false);
7401        mCameraOnTimer.reset(false);
7402        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
7403            mPhoneSignalStrengthsTimer[i].reset(false);
7404        }
7405        mPhoneSignalScanningTimer.reset(false);
7406        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
7407            mPhoneDataConnectionsTimer[i].reset(false);
7408        }
7409        for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
7410            mNetworkByteActivityCounters[i].reset(false);
7411            mNetworkPacketActivityCounters[i].reset(false);
7412        }
7413        mMobileRadioActiveTimer.reset(false);
7414        mMobileRadioActivePerAppTimer.reset(false);
7415        mMobileRadioActiveAdjustedTime.reset(false);
7416        mMobileRadioActiveUnknownTime.reset(false);
7417        mMobileRadioActiveUnknownCount.reset(false);
7418        mWifiOnTimer.reset(false);
7419        mGlobalWifiRunningTimer.reset(false);
7420        for (int i=0; i<NUM_WIFI_STATES; i++) {
7421            mWifiStateTimer[i].reset(false);
7422        }
7423        for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
7424            mWifiSupplStateTimer[i].reset(false);
7425        }
7426        for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
7427            mWifiSignalStrengthsTimer[i].reset(false);
7428        }
7429        for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
7430            mBluetoothActivityCounters[i].reset(false);
7431            mWifiActivityCounters[i].reset(false);
7432        }
7433        mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
7434
7435        for (int i=0; i<mUidStats.size(); i++) {
7436            if (mUidStats.valueAt(i).reset()) {
7437                mUidStats.remove(mUidStats.keyAt(i));
7438                i--;
7439            }
7440        }
7441
7442        if (mKernelWakelockStats.size() > 0) {
7443            for (SamplingTimer timer : mKernelWakelockStats.values()) {
7444                mOnBatteryScreenOffTimeBase.remove(timer);
7445            }
7446            mKernelWakelockStats.clear();
7447        }
7448
7449        if (mWakeupReasonStats.size() > 0) {
7450            for (SamplingTimer timer : mWakeupReasonStats.values()) {
7451                mOnBatteryTimeBase.remove(timer);
7452            }
7453            mWakeupReasonStats.clear();
7454        }
7455
7456        mLastHistoryStepDetails = null;
7457        mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
7458        mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
7459        mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
7460        mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
7461        mLastStepStatUserTime = mCurStepStatUserTime = 0;
7462        mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
7463        mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
7464        mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
7465        mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
7466        mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
7467
7468        initDischarge();
7469
7470        clearHistoryLocked();
7471    }
7472
7473    private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
7474        for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
7475            if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
7476                // Not recording process starts/stops.
7477                continue;
7478            }
7479            HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
7480            if (active == null) {
7481                continue;
7482            }
7483            for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
7484                SparseIntArray uids = ent.getValue();
7485                for (int j=0; j<uids.size(); j++) {
7486                    addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
7487                            uids.keyAt(j));
7488                }
7489            }
7490        }
7491    }
7492
7493    void updateDischargeScreenLevelsLocked(boolean oldScreenOn, boolean newScreenOn) {
7494        if (oldScreenOn) {
7495            int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
7496            if (diff > 0) {
7497                mDischargeAmountScreenOn += diff;
7498                mDischargeAmountScreenOnSinceCharge += diff;
7499            }
7500        } else {
7501            int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
7502            if (diff > 0) {
7503                mDischargeAmountScreenOff += diff;
7504                mDischargeAmountScreenOffSinceCharge += diff;
7505            }
7506        }
7507        if (newScreenOn) {
7508            mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
7509            mDischargeScreenOffUnplugLevel = 0;
7510        } else {
7511            mDischargeScreenOnUnplugLevel = 0;
7512            mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
7513        }
7514    }
7515
7516    public void pullPendingStateUpdatesLocked() {
7517        if (mOnBatteryInternal) {
7518            final boolean screenOn = mScreenState == Display.STATE_ON;
7519            updateDischargeScreenLevelsLocked(screenOn, screenOn);
7520        }
7521    }
7522
7523    private String[] mMobileIfaces = EmptyArray.STRING;
7524    private String[] mWifiIfaces = EmptyArray.STRING;
7525
7526    private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
7527
7528    private static final int NETWORK_STATS_LAST = 0;
7529    private static final int NETWORK_STATS_NEXT = 1;
7530    private static final int NETWORK_STATS_DELTA = 2;
7531
7532    private final NetworkStats[] mMobileNetworkStats = new NetworkStats[] {
7533            new NetworkStats(SystemClock.elapsedRealtime(), 50),
7534            new NetworkStats(SystemClock.elapsedRealtime(), 50),
7535            new NetworkStats(SystemClock.elapsedRealtime(), 50)
7536    };
7537
7538    private final NetworkStats[] mWifiNetworkStats = new NetworkStats[] {
7539            new NetworkStats(SystemClock.elapsedRealtime(), 50),
7540            new NetworkStats(SystemClock.elapsedRealtime(), 50),
7541            new NetworkStats(SystemClock.elapsedRealtime(), 50)
7542    };
7543
7544    /**
7545     * Retrieves the delta of network stats for the given network ifaces. Uses networkStatsBuffer
7546     * as a buffer of NetworkStats objects to cycle through when computing deltas.
7547     */
7548    private NetworkStats getNetworkStatsDeltaLocked(String[] ifaces,
7549                                                    NetworkStats[] networkStatsBuffer)
7550            throws IOException {
7551        if (!SystemProperties.getBoolean(NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED,
7552                false)) {
7553            return null;
7554        }
7555
7556        final NetworkStats stats = mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL,
7557                ifaces, NetworkStats.TAG_NONE, networkStatsBuffer[NETWORK_STATS_NEXT]);
7558        networkStatsBuffer[NETWORK_STATS_DELTA] = NetworkStats.subtract(stats,
7559                networkStatsBuffer[NETWORK_STATS_LAST], null, null,
7560                networkStatsBuffer[NETWORK_STATS_DELTA]);
7561        networkStatsBuffer[NETWORK_STATS_NEXT] = networkStatsBuffer[NETWORK_STATS_LAST];
7562        networkStatsBuffer[NETWORK_STATS_LAST] = stats;
7563        return networkStatsBuffer[NETWORK_STATS_DELTA];
7564    }
7565
7566    /**
7567     * Distribute WiFi energy info and network traffic to apps.
7568     * @param info The energy information from the WiFi controller.
7569     */
7570    public void updateWifiStateLocked(@Nullable final WifiActivityEnergyInfo info) {
7571        if (DEBUG_ENERGY) {
7572            Slog.d(TAG, "Updating wifi stats");
7573        }
7574
7575        final long elapsedRealtimeMs = SystemClock.elapsedRealtime();
7576        NetworkStats delta = null;
7577        try {
7578            if (!ArrayUtils.isEmpty(mWifiIfaces)) {
7579                delta = getNetworkStatsDeltaLocked(mWifiIfaces, mWifiNetworkStats);
7580            }
7581        } catch (IOException e) {
7582            Slog.wtf(TAG, "Failed to get wifi network stats", e);
7583            return;
7584        }
7585
7586        if (!mOnBatteryInternal) {
7587            return;
7588        }
7589
7590        SparseLongArray rxPackets = new SparseLongArray();
7591        SparseLongArray txPackets = new SparseLongArray();
7592        long totalTxPackets = 0;
7593        long totalRxPackets = 0;
7594        if (delta != null) {
7595            final int size = delta.size();
7596            for (int i = 0; i < size; i++) {
7597                final NetworkStats.Entry entry = delta.getValues(i, mTmpNetworkStatsEntry);
7598
7599                if (DEBUG_ENERGY) {
7600                    Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
7601                            + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
7602                            + " txPackets=" + entry.txPackets);
7603                }
7604
7605                if (entry.rxBytes == 0 || entry.txBytes == 0) {
7606                    continue;
7607                }
7608
7609                final Uid u = getUidStatsLocked(mapUid(entry.uid));
7610                u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
7611                        entry.rxPackets);
7612                u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
7613                        entry.txPackets);
7614                rxPackets.put(u.getUid(), entry.rxPackets);
7615                txPackets.put(u.getUid(), entry.txPackets);
7616
7617                // Sum the total number of packets so that the Rx Power and Tx Power can
7618                // be evenly distributed amongst the apps.
7619                totalRxPackets += entry.rxPackets;
7620                totalTxPackets += entry.txPackets;
7621
7622                mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
7623                        entry.rxBytes);
7624                mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
7625                        entry.txBytes);
7626                mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
7627                        entry.rxPackets);
7628                mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
7629                        entry.txPackets);
7630            }
7631        }
7632
7633        if (info != null) {
7634            mHasWifiEnergyReporting = true;
7635
7636            // Measured in mAms
7637            final long txTimeMs = info.getControllerTxTimeMillis();
7638            final long rxTimeMs = info.getControllerRxTimeMillis();
7639            final long idleTimeMs = info.getControllerIdleTimeMillis();
7640            final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
7641
7642            long leftOverRxTimeMs = rxTimeMs;
7643
7644            if (DEBUG_ENERGY) {
7645                Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
7646                Slog.d(TAG, "  Tx Time:    " + txTimeMs + " ms");
7647                Slog.d(TAG, "  Rx Time:    " + rxTimeMs + " ms");
7648                Slog.d(TAG, "  Idle Time:  " + idleTimeMs + " ms");
7649                Slog.d(TAG, "  Total Time: " + totalTimeMs + " ms");
7650            }
7651
7652            long totalWifiLockTimeMs = 0;
7653            long totalScanTimeMs = 0;
7654
7655            // On the first pass, collect some totals so that we can normalize power
7656            // calculations if we need to.
7657            final int uidStatsSize = mUidStats.size();
7658            for (int i = 0; i < uidStatsSize; i++) {
7659                final Uid uid = mUidStats.valueAt(i);
7660
7661                // Sum the total scan power for all apps.
7662                totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
7663                        elapsedRealtimeMs * 1000) / 1000;
7664
7665                // Sum the total time holding wifi lock for all apps.
7666                totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
7667                        elapsedRealtimeMs * 1000) / 1000;
7668            }
7669
7670            if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
7671                Slog.d(TAG, "  !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
7672                        + rxTimeMs + " ms). Normalizing scan time.");
7673            }
7674
7675            // Actually assign and distribute power usage to apps.
7676            for (int i = 0; i < uidStatsSize; i++) {
7677                final Uid uid = mUidStats.valueAt(i);
7678
7679                long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
7680                        elapsedRealtimeMs * 1000) / 1000;
7681                if (scanTimeSinceMarkMs > 0) {
7682                    // Set the new mark so that next time we get new data since this point.
7683                    uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
7684
7685                    if (totalScanTimeMs > rxTimeMs) {
7686                        // Our total scan time is more than the reported Rx time.
7687                        // This is possible because the cost of a scan is approximate.
7688                        // Let's normalize the result so that we evenly blame each app
7689                        // scanning.
7690                        //
7691                        // This means that we may have apps that received packets not be blamed
7692                        // for this, but this is fine as scans are relatively more expensive.
7693                        scanTimeSinceMarkMs = (rxTimeMs * scanTimeSinceMarkMs) / totalScanTimeMs;
7694                    }
7695
7696                    if (DEBUG_ENERGY) {
7697                        Slog.d(TAG, "  ScanTime for UID " + uid.getUid() + ": "
7698                                + scanTimeSinceMarkMs + " ms)");
7699                    }
7700                    uid.noteWifiControllerActivityLocked(CONTROLLER_RX_TIME, scanTimeSinceMarkMs);
7701                    leftOverRxTimeMs -= scanTimeSinceMarkMs;
7702                }
7703
7704                // Distribute evenly the power consumed while Idle to each app holding a WiFi
7705                // lock.
7706                final long wifiLockTimeSinceMarkMs = uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
7707                        elapsedRealtimeMs * 1000) / 1000;
7708                if (wifiLockTimeSinceMarkMs > 0) {
7709                    // Set the new mark so that next time we get new data since this point.
7710                    uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
7711
7712                    final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
7713                            / totalWifiLockTimeMs;
7714                    if (DEBUG_ENERGY) {
7715                        Slog.d(TAG, "  IdleTime for UID " + uid.getUid() + ": "
7716                                + myIdleTimeMs + " ms");
7717                    }
7718                    uid.noteWifiControllerActivityLocked(CONTROLLER_IDLE_TIME, myIdleTimeMs);
7719                }
7720            }
7721
7722            if (DEBUG_ENERGY) {
7723                Slog.d(TAG, "  New RxPower: " + leftOverRxTimeMs + " ms");
7724            }
7725
7726            // Distribute the Tx power appropriately between all apps that transmitted packets.
7727            for (int i = 0; i < txPackets.size(); i++) {
7728                final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
7729                final long myTxTimeMs = (txPackets.valueAt(i) * txTimeMs) / totalTxPackets;
7730                if (DEBUG_ENERGY) {
7731                    Slog.d(TAG, "  TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
7732                }
7733                uid.noteWifiControllerActivityLocked(CONTROLLER_TX_TIME, myTxTimeMs);
7734            }
7735
7736            // Distribute the remaining Rx power appropriately between all apps that received
7737            // packets.
7738            for (int i = 0; i < rxPackets.size(); i++) {
7739                final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
7740                final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs) / totalRxPackets;
7741                if (DEBUG_ENERGY) {
7742                    Slog.d(TAG, "  RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
7743                }
7744                uid.noteWifiControllerActivityLocked(CONTROLLER_RX_TIME, myRxTimeMs);
7745            }
7746
7747            // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
7748
7749            // Update WiFi controller stats.
7750            mWifiActivityCounters[CONTROLLER_RX_TIME].addCountLocked(
7751                    info.getControllerRxTimeMillis());
7752            mWifiActivityCounters[CONTROLLER_TX_TIME].addCountLocked(
7753                    info.getControllerTxTimeMillis());
7754            mWifiActivityCounters[CONTROLLER_IDLE_TIME].addCountLocked(
7755                    info.getControllerIdleTimeMillis());
7756
7757            // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
7758            final double opVolt = mPowerProfile.getAveragePower(
7759                    PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
7760            if (opVolt != 0) {
7761                // We store the power drain as mAms.
7762                mWifiActivityCounters[CONTROLLER_POWER_DRAIN].addCountLocked(
7763                        (long)(info.getControllerEnergyUsed() / opVolt));
7764            }
7765        }
7766    }
7767
7768    /**
7769     * Distribute Cell radio energy info and network traffic to apps.
7770     */
7771    public void updateMobileRadioStateLocked(final long elapsedRealtimeMs) {
7772        if (DEBUG_ENERGY) {
7773            Slog.d(TAG, "Updating mobile radio stats");
7774        }
7775
7776        NetworkStats delta = null;
7777        try {
7778            if (!ArrayUtils.isEmpty(mMobileIfaces)) {
7779                delta = getNetworkStatsDeltaLocked(mMobileIfaces, mMobileNetworkStats);
7780            }
7781        } catch (IOException e) {
7782            Slog.wtf(TAG, "Failed to get mobile network stats", e);
7783            return;
7784        }
7785
7786        if (delta == null || !mOnBatteryInternal) {
7787            return;
7788        }
7789
7790        long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
7791                elapsedRealtimeMs * 1000);
7792        mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
7793        long totalPackets = delta.getTotalPackets();
7794
7795        final int size = delta.size();
7796        for (int i = 0; i < size; i++) {
7797            final NetworkStats.Entry entry = delta.getValues(i, mTmpNetworkStatsEntry);
7798
7799            if (entry.rxBytes == 0 || entry.txBytes == 0) {
7800                continue;
7801            }
7802
7803            if (DEBUG_ENERGY) {
7804                Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
7805                        + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
7806                        + " txPackets=" + entry.txPackets);
7807            }
7808
7809            final Uid u = getUidStatsLocked(mapUid(entry.uid));
7810            u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
7811                    entry.rxPackets);
7812            u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
7813                    entry.txPackets);
7814
7815            if (radioTime > 0) {
7816                // Distribute total radio active time in to this app.
7817                long appPackets = entry.rxPackets + entry.txPackets;
7818                long appRadioTime = (radioTime*appPackets)/totalPackets;
7819                u.noteMobileRadioActiveTimeLocked(appRadioTime);
7820                // Remove this app from the totals, so that we don't lose any time
7821                // due to rounding.
7822                radioTime -= appRadioTime;
7823                totalPackets -= appPackets;
7824            }
7825
7826            mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
7827                    entry.rxBytes);
7828            mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
7829                    entry.txBytes);
7830            mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
7831                    entry.rxPackets);
7832            mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
7833                    entry.txPackets);
7834        }
7835
7836        if (radioTime > 0) {
7837            // Whoops, there is some radio time we can't blame on an app!
7838            mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
7839            mMobileRadioActiveUnknownCount.addCountLocked(1);
7840        }
7841    }
7842
7843    /**
7844     * Distribute Bluetooth energy info and network traffic to apps.
7845     * @param info The energy information from the bluetooth controller.
7846     */
7847    public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
7848        if (DEBUG_ENERGY) {
7849            Slog.d(TAG, "Updating bluetooth stats");
7850        }
7851
7852        if (info != null && mOnBatteryInternal) {
7853            mHasBluetoothEnergyReporting = true;
7854            mBluetoothActivityCounters[CONTROLLER_RX_TIME].addCountLocked(
7855                    info.getControllerRxTimeMillis());
7856            mBluetoothActivityCounters[CONTROLLER_TX_TIME].addCountLocked(
7857                    info.getControllerTxTimeMillis());
7858            mBluetoothActivityCounters[CONTROLLER_IDLE_TIME].addCountLocked(
7859                    info.getControllerIdleTimeMillis());
7860
7861            // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
7862            final double opVolt = mPowerProfile.getAveragePower(
7863                    PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
7864            if (opVolt != 0) {
7865                // We store the power drain as mAms.
7866                mBluetoothActivityCounters[CONTROLLER_POWER_DRAIN].addCountLocked(
7867                        (long) (info.getControllerEnergyUsed() / opVolt));
7868            }
7869        }
7870    }
7871
7872    /**
7873     * Read and distribute kernel wake lock use across apps.
7874     */
7875    public void updateKernelWakelocksLocked() {
7876        final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
7877                mTmpWakelockStats);
7878        if (wakelockStats == null) {
7879            // Not crashing might make board bringup easier.
7880            Slog.w(TAG, "Couldn't get kernel wake lock stats");
7881            return;
7882        }
7883
7884        for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
7885            String name = ent.getKey();
7886            KernelWakelockStats.Entry kws = ent.getValue();
7887
7888            SamplingTimer kwlt = mKernelWakelockStats.get(name);
7889            if (kwlt == null) {
7890                kwlt = new SamplingTimer(mOnBatteryScreenOffTimeBase,
7891                        true /* track reported val */);
7892                mKernelWakelockStats.put(name, kwlt);
7893            }
7894            kwlt.updateCurrentReportedCount(kws.mCount);
7895            kwlt.updateCurrentReportedTotalTime(kws.mTotalTime);
7896            kwlt.setUpdateVersion(kws.mVersion);
7897        }
7898
7899        if (wakelockStats.size() != mKernelWakelockStats.size()) {
7900            // Set timers to stale if they didn't appear in /proc/wakelocks this time.
7901            for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
7902                SamplingTimer st = ent.getValue();
7903                if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
7904                    st.setStale();
7905                }
7906            }
7907        }
7908    }
7909
7910    // We use an anonymous class to access these variables,
7911    // so they can't live on the stack or they'd have to be
7912    // final MutableLong objects (more allocations).
7913    // Used in updateCpuTimeLocked().
7914    long mTempTotalCpuUserTimeUs;
7915    long mTempTotalCpuSystemTimeUs;
7916
7917    /**
7918     * Read and distribute CPU usage across apps. If their are partial wakelocks being held
7919     * and we are on battery with screen off, we give more of the cpu time to those apps holding
7920     * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
7921     */
7922    public void updateCpuTimeLocked() {
7923        if (DEBUG_ENERGY_CPU) {
7924            Slog.d(TAG, "!Cpu updating!");
7925        }
7926
7927        // Holding a wakelock costs more than just using the cpu.
7928        // Currently, we assign only half the cpu time to an app that is running but
7929        // not holding a wakelock. The apps holding wakelocks get the rest of the blame.
7930        // If no app is holding a wakelock, then the distribution is normal.
7931        final int wakelockWeight = 50;
7932
7933        // Read the time spent at various cpu frequencies.
7934        final int cpuSpeedSteps = getCpuSpeedSteps();
7935        final long[] cpuSpeeds = mKernelCpuSpeedReader.readDelta();
7936
7937        int numWakelocks = 0;
7938
7939        // Calculate how many wakelocks we have to distribute amongst. The system is excluded.
7940        // Only distribute cpu power to wakelocks if the screen is off and we're on battery.
7941        final int numPartialTimers = mPartialTimers.size();
7942        if (mOnBatteryScreenOffTimeBase.isRunning()) {
7943            for (int i = 0; i < numPartialTimers; i++) {
7944                final StopwatchTimer timer = mPartialTimers.get(i);
7945                if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
7946                    // Since the collection and blaming of wakelocks can be scheduled to run after
7947                    // some delay, the mPartialTimers list may have new entries. We can't blame
7948                    // the newly added timer for past cpu time, so we only consider timers that
7949                    // were present for one round of collection. Once a timer has gone through
7950                    // a round of collection, its mInList field is set to true.
7951                    numWakelocks++;
7952                }
7953            }
7954        }
7955
7956        final int numWakelocksF = numWakelocks;
7957        mTempTotalCpuUserTimeUs = 0;
7958        mTempTotalCpuSystemTimeUs = 0;
7959
7960        // Read the CPU data for each UID. This will internally generate a snapshot so next time
7961        // we read, we get a delta. If we are to distribute the cpu time, then do so. Otherwise
7962        // we just ignore the data.
7963        final long startTimeMs = SystemClock.elapsedRealtime();
7964        mKernelUidCpuTimeReader.readDelta(!mOnBatteryInternal ? null :
7965                new KernelUidCpuTimeReader.Callback() {
7966                    @Override
7967                    public void onUidCpuTime(int uid, long userTimeUs, long systemTimeUs) {
7968                        final Uid u = getUidStatsLocked(mapUid(uid));
7969
7970                        // Accumulate the total system and user time.
7971                        mTempTotalCpuUserTimeUs += userTimeUs;
7972                        mTempTotalCpuSystemTimeUs += systemTimeUs;
7973
7974                        StringBuilder sb = null;
7975                        if (DEBUG_ENERGY_CPU) {
7976                            sb = new StringBuilder();
7977                            sb.append("  got time for uid=").append(u.mUid).append(": u=");
7978                            TimeUtils.formatDuration(userTimeUs / 1000, sb);
7979                            sb.append(" s=");
7980                            TimeUtils.formatDuration(systemTimeUs / 1000, sb);
7981                            sb.append("\n");
7982                        }
7983
7984                        if (numWakelocksF > 0) {
7985                            // We have wakelocks being held, so only give a portion of the
7986                            // time to the process. The rest will be distributed among wakelock
7987                            // holders.
7988                            userTimeUs = (userTimeUs * wakelockWeight) / 100;
7989                            systemTimeUs = (systemTimeUs * wakelockWeight) / 100;
7990                        }
7991
7992                        if (sb != null) {
7993                            sb.append("  adding to uid=").append(u.mUid).append(": u=");
7994                            TimeUtils.formatDuration(userTimeUs / 1000, sb);
7995                            sb.append(" s=");
7996                            TimeUtils.formatDuration(systemTimeUs / 1000, sb);
7997                            Slog.d(TAG, sb.toString());
7998                        }
7999
8000                        u.mUserCpuTime.addCountLocked(userTimeUs);
8001                        u.mSystemCpuTime.addCountLocked(systemTimeUs);
8002
8003                        // Add the cpu speeds to this UID. These are used as a ratio
8004                        // for computing the power this UID used.
8005                        for (int i = 0; i < cpuSpeedSteps; i++) {
8006                            if (u.mSpeedBins[i] == null) {
8007                                u.mSpeedBins[i] = new LongSamplingCounter(mOnBatteryTimeBase);
8008                            }
8009                            u.mSpeedBins[i].addCountLocked(cpuSpeeds[i]);
8010                        }
8011                    }
8012                });
8013
8014        if (DEBUG_ENERGY_CPU) {
8015            Slog.d(TAG, "Reading cpu stats took " + (SystemClock.elapsedRealtime() - startTimeMs) +
8016                    " ms");
8017        }
8018
8019        if (mOnBatteryInternal && numWakelocks > 0) {
8020            // Distribute a portion of the total cpu time to wakelock holders.
8021            mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - wakelockWeight)) / 100;
8022            mTempTotalCpuSystemTimeUs =
8023                    (mTempTotalCpuSystemTimeUs * (100 - wakelockWeight)) / 100;
8024
8025            for (int i = 0; i < numPartialTimers; i++) {
8026                final StopwatchTimer timer = mPartialTimers.get(i);
8027
8028                // The system does not share any blame, as it is usually holding the wakelock
8029                // on behalf of an app.
8030                if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
8031                    int userTimeUs = (int) (mTempTotalCpuUserTimeUs / numWakelocks);
8032                    int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / numWakelocks);
8033
8034                    if (DEBUG_ENERGY_CPU) {
8035                        StringBuilder sb = new StringBuilder();
8036                        sb.append("  Distributing wakelock uid=").append(timer.mUid.mUid)
8037                                .append(": u=");
8038                        TimeUtils.formatDuration(userTimeUs / 1000, sb);
8039                        sb.append(" s=");
8040                        TimeUtils.formatDuration(systemTimeUs / 1000, sb);
8041                        Slog.d(TAG, sb.toString());
8042                    }
8043
8044                    timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
8045                    timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
8046
8047                    final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
8048                    proc.addCpuTimeLocked(userTimeUs, systemTimeUs);
8049
8050                    mTempTotalCpuUserTimeUs -= userTimeUs;
8051                    mTempTotalCpuSystemTimeUs -= systemTimeUs;
8052                    numWakelocks--;
8053                }
8054            }
8055
8056            if (mTempTotalCpuUserTimeUs > 0 || mTempTotalCpuSystemTimeUs > 0) {
8057                // Anything left over is given to the system.
8058                if (DEBUG_ENERGY_CPU) {
8059                    StringBuilder sb = new StringBuilder();
8060                    sb.append("  Distributing lost time to system: u=");
8061                    TimeUtils.formatDuration(mTempTotalCpuUserTimeUs / 1000, sb);
8062                    sb.append(" s=");
8063                    TimeUtils.formatDuration(mTempTotalCpuSystemTimeUs / 1000, sb);
8064                    Slog.d(TAG, sb.toString());
8065                }
8066
8067                final Uid u = getUidStatsLocked(Process.SYSTEM_UID);
8068                u.mUserCpuTime.addCountLocked(mTempTotalCpuUserTimeUs);
8069                u.mSystemCpuTime.addCountLocked(mTempTotalCpuSystemTimeUs);
8070
8071                final Uid.Proc proc = u.getProcessStatsLocked("*lost*");
8072                proc.addCpuTimeLocked((int) mTempTotalCpuUserTimeUs,
8073                        (int) mTempTotalCpuSystemTimeUs);
8074            }
8075        }
8076
8077        // See if there is a difference in wakelocks between this collection and the last
8078        // collection.
8079        if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
8080            // No difference, so each timer is now considered for the next collection.
8081            for (int i = 0; i < numPartialTimers; i++) {
8082                mPartialTimers.get(i).mInList = true;
8083            }
8084        } else {
8085            // The lists are different, meaning we added (or removed a timer) since the last
8086            // collection.
8087            final int numLastPartialTimers = mLastPartialTimers.size();
8088            for (int i = 0; i < numLastPartialTimers; i++) {
8089                mLastPartialTimers.get(i).mInList = false;
8090            }
8091            mLastPartialTimers.clear();
8092
8093            // Mark the current timers as gone through a collection.
8094            for (int i = 0; i < numPartialTimers; i++) {
8095                final StopwatchTimer timer = mPartialTimers.get(i);
8096                timer.mInList = true;
8097                mLastPartialTimers.add(timer);
8098            }
8099        }
8100    }
8101
8102    boolean setChargingLocked(boolean charging) {
8103        if (mCharging != charging) {
8104            mCharging = charging;
8105            if (charging) {
8106                mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
8107            } else {
8108                mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
8109            }
8110            mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
8111            return true;
8112        }
8113        return false;
8114    }
8115
8116    void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime, final boolean onBattery,
8117            final int oldStatus, final int level) {
8118        boolean doWrite = false;
8119        Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
8120        m.arg1 = onBattery ? 1 : 0;
8121        mHandler.sendMessage(m);
8122
8123        final long uptime = mSecUptime * 1000;
8124        final long realtime = mSecRealtime * 1000;
8125        final boolean screenOn = mScreenState == Display.STATE_ON;
8126        if (onBattery) {
8127            // We will reset our status if we are unplugging after the
8128            // battery was last full, or the level is at 100, or
8129            // we have gone through a significant charge (from a very low
8130            // level to a now very high level).
8131            boolean reset = false;
8132            if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
8133                    || level >= 90
8134                    || (mDischargeCurrentLevel < 20 && level >= 80)
8135                    || (getHighDischargeAmountSinceCharge() >= 200
8136                            && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
8137                Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
8138                        + " dischargeLevel=" + mDischargeCurrentLevel
8139                        + " lowAmount=" + getLowDischargeAmountSinceCharge()
8140                        + " highAmount=" + getHighDischargeAmountSinceCharge());
8141                // Before we write, collect a snapshot of the final aggregated
8142                // stats to be reported in the next checkin.  Only do this if we have
8143                // a sufficient amount of data to make it interesting.
8144                if (getLowDischargeAmountSinceCharge() >= 20) {
8145                    final Parcel parcel = Parcel.obtain();
8146                    writeSummaryToParcel(parcel, true);
8147                    BackgroundThread.getHandler().post(new Runnable() {
8148                        @Override public void run() {
8149                            synchronized (mCheckinFile) {
8150                                FileOutputStream stream = null;
8151                                try {
8152                                    stream = mCheckinFile.startWrite();
8153                                    stream.write(parcel.marshall());
8154                                    stream.flush();
8155                                    FileUtils.sync(stream);
8156                                    stream.close();
8157                                    mCheckinFile.finishWrite(stream);
8158                                } catch (IOException e) {
8159                                    Slog.w("BatteryStats",
8160                                            "Error writing checkin battery statistics", e);
8161                                    mCheckinFile.failWrite(stream);
8162                                } finally {
8163                                    parcel.recycle();
8164                                }
8165                            }
8166                        }
8167                    });
8168                }
8169                doWrite = true;
8170                resetAllStatsLocked();
8171                mDischargeStartLevel = level;
8172                reset = true;
8173                mDischargeStepTracker.init();
8174            }
8175            if (mCharging) {
8176                setChargingLocked(false);
8177            }
8178            mLastChargingStateLevel = level;
8179            mOnBattery = mOnBatteryInternal = true;
8180            mLastDischargeStepLevel = level;
8181            mMinDischargeStepLevel = level;
8182            mDischargeStepTracker.clearTime();
8183            mDailyDischargeStepTracker.clearTime();
8184            mInitStepMode = mCurStepMode;
8185            mModStepMode = 0;
8186            pullPendingStateUpdatesLocked();
8187            mHistoryCur.batteryLevel = (byte)level;
8188            mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
8189            if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
8190                    + Integer.toHexString(mHistoryCur.states));
8191            if (reset) {
8192                mRecordingHistory = true;
8193                startRecordingHistory(mSecRealtime, mSecUptime, reset);
8194            }
8195            addHistoryRecordLocked(mSecRealtime, mSecUptime);
8196            mDischargeCurrentLevel = mDischargeUnplugLevel = level;
8197            if (screenOn) {
8198                mDischargeScreenOnUnplugLevel = level;
8199                mDischargeScreenOffUnplugLevel = 0;
8200            } else {
8201                mDischargeScreenOnUnplugLevel = 0;
8202                mDischargeScreenOffUnplugLevel = level;
8203            }
8204            mDischargeAmountScreenOn = 0;
8205            mDischargeAmountScreenOff = 0;
8206            updateTimeBasesLocked(true, !screenOn, uptime, realtime);
8207        } else {
8208            mLastChargingStateLevel = level;
8209            mOnBattery = mOnBatteryInternal = false;
8210            pullPendingStateUpdatesLocked();
8211            mHistoryCur.batteryLevel = (byte)level;
8212            mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
8213            if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
8214                    + Integer.toHexString(mHistoryCur.states));
8215            addHistoryRecordLocked(mSecRealtime, mSecUptime);
8216            mDischargeCurrentLevel = mDischargePlugLevel = level;
8217            if (level < mDischargeUnplugLevel) {
8218                mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
8219                mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
8220            }
8221            updateDischargeScreenLevelsLocked(screenOn, screenOn);
8222            updateTimeBasesLocked(false, !screenOn, uptime, realtime);
8223            mChargeStepTracker.init();
8224            mLastChargeStepLevel = level;
8225            mMaxChargeStepLevel = level;
8226            mInitStepMode = mCurStepMode;
8227            mModStepMode = 0;
8228        }
8229        if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
8230            if (mFile != null) {
8231                writeAsyncLocked();
8232            }
8233        }
8234    }
8235
8236    private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
8237            boolean reset) {
8238        mRecordingHistory = true;
8239        mHistoryCur.currentTime = System.currentTimeMillis();
8240        addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs,
8241                reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
8242                mHistoryCur);
8243        mHistoryCur.currentTime = 0;
8244        if (reset) {
8245            initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
8246        }
8247    }
8248
8249    private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
8250            final long uptimeMs) {
8251        if (mRecordingHistory) {
8252            mHistoryCur.currentTime = currentTime;
8253            addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_CURRENT_TIME,
8254                    mHistoryCur);
8255            mHistoryCur.currentTime = 0;
8256        }
8257    }
8258
8259    private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
8260        if (mRecordingHistory) {
8261            mHistoryCur.currentTime = System.currentTimeMillis();
8262            addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_SHUTDOWN,
8263                    mHistoryCur);
8264            mHistoryCur.currentTime = 0;
8265        }
8266    }
8267
8268    private void scheduleSyncExternalStatsLocked(String reason) {
8269        if (mExternalSync != null) {
8270            mExternalSync.scheduleSync(reason);
8271        }
8272    }
8273
8274    private void scheduleSyncExternalWifiStatsLocked(String reason) {
8275        if (mExternalSync != null) {
8276            mExternalSync.scheduleWifiSync(reason);
8277        }
8278    }
8279
8280    // This should probably be exposed in the API, though it's not critical
8281    public static final int BATTERY_PLUGGED_NONE = 0;
8282
8283    public void setBatteryStateLocked(int status, int health, int plugType, int level,
8284            int temp, int volt) {
8285        final boolean onBattery = plugType == BATTERY_PLUGGED_NONE;
8286        final long uptime = SystemClock.uptimeMillis();
8287        final long elapsedRealtime = SystemClock.elapsedRealtime();
8288        if (!mHaveBatteryLevel) {
8289            mHaveBatteryLevel = true;
8290            // We start out assuming that the device is plugged in (not
8291            // on battery).  If our first report is now that we are indeed
8292            // plugged in, then twiddle our state to correctly reflect that
8293            // since we won't be going through the full setOnBattery().
8294            if (onBattery == mOnBattery) {
8295                if (onBattery) {
8296                    mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
8297                } else {
8298                    mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
8299                }
8300            }
8301            // Always start out assuming charging, that will be updated later.
8302            mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
8303            mHistoryCur.batteryStatus = (byte)status;
8304            mHistoryCur.batteryLevel = (byte)level;
8305            mMaxChargeStepLevel = mMinDischargeStepLevel =
8306                    mLastChargeStepLevel = mLastDischargeStepLevel = level;
8307            mLastChargingStateLevel = level;
8308        } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
8309            recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
8310        }
8311        int oldStatus = mHistoryCur.batteryStatus;
8312        if (onBattery) {
8313            mDischargeCurrentLevel = level;
8314            if (!mRecordingHistory) {
8315                mRecordingHistory = true;
8316                startRecordingHistory(elapsedRealtime, uptime, true);
8317            }
8318        } else if (level < 96) {
8319            if (!mRecordingHistory) {
8320                mRecordingHistory = true;
8321                startRecordingHistory(elapsedRealtime, uptime, true);
8322            }
8323        }
8324        mCurrentBatteryLevel = level;
8325        if (mDischargePlugLevel < 0) {
8326            mDischargePlugLevel = level;
8327        }
8328        if (onBattery != mOnBattery) {
8329            mHistoryCur.batteryLevel = (byte)level;
8330            mHistoryCur.batteryStatus = (byte)status;
8331            mHistoryCur.batteryHealth = (byte)health;
8332            mHistoryCur.batteryPlugType = (byte)plugType;
8333            mHistoryCur.batteryTemperature = (short)temp;
8334            mHistoryCur.batteryVoltage = (char)volt;
8335            setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level);
8336        } else {
8337            boolean changed = false;
8338            if (mHistoryCur.batteryLevel != level) {
8339                mHistoryCur.batteryLevel = (byte)level;
8340                changed = true;
8341
8342                // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
8343                // which will pull external stats.
8344                scheduleSyncExternalStatsLocked("battery-level");
8345            }
8346            if (mHistoryCur.batteryStatus != status) {
8347                mHistoryCur.batteryStatus = (byte)status;
8348                changed = true;
8349            }
8350            if (mHistoryCur.batteryHealth != health) {
8351                mHistoryCur.batteryHealth = (byte)health;
8352                changed = true;
8353            }
8354            if (mHistoryCur.batteryPlugType != plugType) {
8355                mHistoryCur.batteryPlugType = (byte)plugType;
8356                changed = true;
8357            }
8358            if (temp >= (mHistoryCur.batteryTemperature+10)
8359                    || temp <= (mHistoryCur.batteryTemperature-10)) {
8360                mHistoryCur.batteryTemperature = (short)temp;
8361                changed = true;
8362            }
8363            if (volt > (mHistoryCur.batteryVoltage+20)
8364                    || volt < (mHistoryCur.batteryVoltage-20)) {
8365                mHistoryCur.batteryVoltage = (char)volt;
8366                changed = true;
8367            }
8368            long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
8369                    | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
8370                    | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
8371            if (onBattery) {
8372                changed |= setChargingLocked(false);
8373                if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
8374                    mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
8375                            modeBits, elapsedRealtime);
8376                    mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
8377                            modeBits, elapsedRealtime);
8378                    mLastDischargeStepLevel = level;
8379                    mMinDischargeStepLevel = level;
8380                    mInitStepMode = mCurStepMode;
8381                    mModStepMode = 0;
8382                }
8383            } else {
8384                if (level >= 90) {
8385                    // If the battery level is at least 90%, always consider the device to be
8386                    // charging even if it happens to go down a level.
8387                    changed |= setChargingLocked(true);
8388                    mLastChargeStepLevel = level;
8389                } if (!mCharging) {
8390                    if (mLastChargeStepLevel < level) {
8391                        // We have not reporting that we are charging, but the level has now
8392                        // gone up, so consider the state to be charging.
8393                        changed |= setChargingLocked(true);
8394                        mLastChargeStepLevel = level;
8395                    }
8396                } else {
8397                    if (mLastChargeStepLevel > level) {
8398                        // We had reported that the device was charging, but here we are with
8399                        // power connected and the level going down.  Looks like the current
8400                        // power supplied isn't enough, so consider the device to now be
8401                        // discharging.
8402                        changed |= setChargingLocked(false);
8403                        mLastChargeStepLevel = level;
8404                    }
8405                }
8406                if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
8407                    mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
8408                            modeBits, elapsedRealtime);
8409                    mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
8410                            modeBits, elapsedRealtime);
8411                    mLastChargeStepLevel = level;
8412                    mMaxChargeStepLevel = level;
8413                    mInitStepMode = mCurStepMode;
8414                    mModStepMode = 0;
8415                }
8416            }
8417            if (changed) {
8418                addHistoryRecordLocked(elapsedRealtime, uptime);
8419            }
8420        }
8421        if (!onBattery && status == BatteryManager.BATTERY_STATUS_FULL) {
8422            // We don't record history while we are plugged in and fully charged.
8423            // The next time we are unplugged, history will be cleared.
8424            mRecordingHistory = DEBUG;
8425        }
8426    }
8427
8428    public long getAwakeTimeBattery() {
8429        return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
8430    }
8431
8432    public long getAwakeTimePlugged() {
8433        return (SystemClock.uptimeMillis() * 1000) - getAwakeTimeBattery();
8434    }
8435
8436    @Override
8437    public long computeUptime(long curTime, int which) {
8438        switch (which) {
8439            case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
8440            case STATS_CURRENT: return (curTime-mUptimeStart);
8441            case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
8442        }
8443        return 0;
8444    }
8445
8446    @Override
8447    public long computeRealtime(long curTime, int which) {
8448        switch (which) {
8449            case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
8450            case STATS_CURRENT: return (curTime-mRealtimeStart);
8451            case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
8452        }
8453        return 0;
8454    }
8455
8456    @Override
8457    public long computeBatteryUptime(long curTime, int which) {
8458        return mOnBatteryTimeBase.computeUptime(curTime, which);
8459    }
8460
8461    @Override
8462    public long computeBatteryRealtime(long curTime, int which) {
8463        return mOnBatteryTimeBase.computeRealtime(curTime, which);
8464    }
8465
8466    @Override
8467    public long computeBatteryScreenOffUptime(long curTime, int which) {
8468        return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
8469    }
8470
8471    @Override
8472    public long computeBatteryScreenOffRealtime(long curTime, int which) {
8473        return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
8474    }
8475
8476    private long computeTimePerLevel(long[] steps, int numSteps) {
8477        // For now we'll do a simple average across all steps.
8478        if (numSteps <= 0) {
8479            return -1;
8480        }
8481        long total = 0;
8482        for (int i=0; i<numSteps; i++) {
8483            total += steps[i] & STEP_LEVEL_TIME_MASK;
8484        }
8485        return total / numSteps;
8486        /*
8487        long[] buckets = new long[numSteps];
8488        int numBuckets = 0;
8489        int numToAverage = 4;
8490        int i = 0;
8491        while (i < numSteps) {
8492            long totalTime = 0;
8493            int num = 0;
8494            for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
8495                totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
8496                num++;
8497            }
8498            buckets[numBuckets] = totalTime / num;
8499            numBuckets++;
8500            numToAverage *= 2;
8501            i += num;
8502        }
8503        if (numBuckets < 1) {
8504            return -1;
8505        }
8506        long averageTime = buckets[numBuckets-1];
8507        for (i=numBuckets-2; i>=0; i--) {
8508            averageTime = (averageTime + buckets[i]) / 2;
8509        }
8510        return averageTime;
8511        */
8512    }
8513
8514    @Override
8515    public long computeBatteryTimeRemaining(long curTime) {
8516        if (!mOnBattery) {
8517            return -1;
8518        }
8519        /* Simple implementation just looks at the average discharge per level across the
8520           entire sample period.
8521        int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
8522        if (discharge < 2) {
8523            return -1;
8524        }
8525        long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
8526        if (duration < 1000*1000) {
8527            return -1;
8528        }
8529        long usPerLevel = duration/discharge;
8530        return usPerLevel * mCurrentBatteryLevel;
8531        */
8532        if (mDischargeStepTracker.mNumStepDurations < 1) {
8533            return -1;
8534        }
8535        long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
8536        if (msPerLevel <= 0) {
8537            return -1;
8538        }
8539        return (msPerLevel * mCurrentBatteryLevel) * 1000;
8540    }
8541
8542    @Override
8543    public LevelStepTracker getDischargeLevelStepTracker() {
8544        return mDischargeStepTracker;
8545    }
8546
8547    @Override
8548    public LevelStepTracker getDailyDischargeLevelStepTracker() {
8549        return mDailyDischargeStepTracker;
8550    }
8551
8552    @Override
8553    public long computeChargeTimeRemaining(long curTime) {
8554        if (mOnBattery) {
8555            // Not yet working.
8556            return -1;
8557        }
8558        /* Broken
8559        int curLevel = mCurrentBatteryLevel;
8560        int plugLevel = mDischargePlugLevel;
8561        if (plugLevel < 0 || curLevel < (plugLevel+1)) {
8562            return -1;
8563        }
8564        long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
8565        if (duration < 1000*1000) {
8566            return -1;
8567        }
8568        long usPerLevel = duration/(curLevel-plugLevel);
8569        return usPerLevel * (100-curLevel);
8570        */
8571        if (mChargeStepTracker.mNumStepDurations < 1) {
8572            return -1;
8573        }
8574        long msPerLevel = mChargeStepTracker.computeTimePerLevel();
8575        if (msPerLevel <= 0) {
8576            return -1;
8577        }
8578        return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
8579    }
8580
8581    @Override
8582    public LevelStepTracker getChargeLevelStepTracker() {
8583        return mChargeStepTracker;
8584    }
8585
8586    @Override
8587    public LevelStepTracker getDailyChargeLevelStepTracker() {
8588        return mDailyChargeStepTracker;
8589    }
8590
8591    @Override
8592    public ArrayList<PackageChange> getDailyPackageChanges() {
8593        return mDailyPackageChanges;
8594    }
8595
8596    long getBatteryUptimeLocked() {
8597        return mOnBatteryTimeBase.getUptime(SystemClock.uptimeMillis() * 1000);
8598    }
8599
8600    @Override
8601    public long getBatteryUptime(long curTime) {
8602        return mOnBatteryTimeBase.getUptime(curTime);
8603    }
8604
8605    @Override
8606    public long getBatteryRealtime(long curTime) {
8607        return mOnBatteryTimeBase.getRealtime(curTime);
8608    }
8609
8610    @Override
8611    public int getDischargeStartLevel() {
8612        synchronized(this) {
8613            return getDischargeStartLevelLocked();
8614        }
8615    }
8616
8617    public int getDischargeStartLevelLocked() {
8618            return mDischargeUnplugLevel;
8619    }
8620
8621    @Override
8622    public int getDischargeCurrentLevel() {
8623        synchronized(this) {
8624            return getDischargeCurrentLevelLocked();
8625        }
8626    }
8627
8628    public int getDischargeCurrentLevelLocked() {
8629        return mDischargeCurrentLevel;
8630    }
8631
8632    @Override
8633    public int getLowDischargeAmountSinceCharge() {
8634        synchronized(this) {
8635            int val = mLowDischargeAmountSinceCharge;
8636            if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
8637                val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
8638            }
8639            return val;
8640        }
8641    }
8642
8643    @Override
8644    public int getHighDischargeAmountSinceCharge() {
8645        synchronized(this) {
8646            int val = mHighDischargeAmountSinceCharge;
8647            if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
8648                val += mDischargeUnplugLevel-mDischargeCurrentLevel;
8649            }
8650            return val;
8651        }
8652    }
8653
8654    @Override
8655    public int getDischargeAmount(int which) {
8656        int dischargeAmount = which == STATS_SINCE_CHARGED
8657                ? getHighDischargeAmountSinceCharge()
8658                : (getDischargeStartLevel() - getDischargeCurrentLevel());
8659        if (dischargeAmount < 0) {
8660            dischargeAmount = 0;
8661        }
8662        return dischargeAmount;
8663    }
8664
8665    public int getDischargeAmountScreenOn() {
8666        synchronized(this) {
8667            int val = mDischargeAmountScreenOn;
8668            if (mOnBattery && mScreenState == Display.STATE_ON
8669                    && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
8670                val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
8671            }
8672            return val;
8673        }
8674    }
8675
8676    public int getDischargeAmountScreenOnSinceCharge() {
8677        synchronized(this) {
8678            int val = mDischargeAmountScreenOnSinceCharge;
8679            if (mOnBattery && mScreenState == Display.STATE_ON
8680                    && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
8681                val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
8682            }
8683            return val;
8684        }
8685    }
8686
8687    public int getDischargeAmountScreenOff() {
8688        synchronized(this) {
8689            int val = mDischargeAmountScreenOff;
8690            if (mOnBattery && mScreenState != Display.STATE_ON
8691                    && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
8692                val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
8693            }
8694            return val;
8695        }
8696    }
8697
8698    public int getDischargeAmountScreenOffSinceCharge() {
8699        synchronized(this) {
8700            int val = mDischargeAmountScreenOffSinceCharge;
8701            if (mOnBattery && mScreenState != Display.STATE_ON
8702                    && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
8703                val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
8704            }
8705            return val;
8706        }
8707    }
8708
8709    @Override
8710    public int getCpuSpeedSteps() {
8711        return sNumSpeedSteps;
8712    }
8713
8714    /**
8715     * Retrieve the statistics object for a particular uid, creating if needed.
8716     */
8717    public Uid getUidStatsLocked(int uid) {
8718        Uid u = mUidStats.get(uid);
8719        if (u == null) {
8720            u = new Uid(uid);
8721            mUidStats.put(uid, u);
8722        }
8723        return u;
8724    }
8725
8726    /**
8727     * Remove the statistics object for a particular uid.
8728     */
8729    public void removeUidStatsLocked(int uid) {
8730        mKernelUidCpuTimeReader.removeUid(uid);
8731        mUidStats.remove(uid);
8732    }
8733
8734    /**
8735     * Retrieve the statistics object for a particular process, creating
8736     * if needed.
8737     */
8738    public Uid.Proc getProcessStatsLocked(int uid, String name) {
8739        uid = mapUid(uid);
8740        Uid u = getUidStatsLocked(uid);
8741        return u.getProcessStatsLocked(name);
8742    }
8743
8744    /**
8745     * Retrieve the statistics object for a particular process, creating
8746     * if needed.
8747     */
8748    public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
8749        uid = mapUid(uid);
8750        Uid u = getUidStatsLocked(uid);
8751        return u.getPackageStatsLocked(pkg);
8752    }
8753
8754    /**
8755     * Retrieve the statistics object for a particular service, creating
8756     * if needed.
8757     */
8758    public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
8759        uid = mapUid(uid);
8760        Uid u = getUidStatsLocked(uid);
8761        return u.getServiceStatsLocked(pkg, name);
8762    }
8763
8764    public void shutdownLocked() {
8765        recordShutdownLocked(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
8766        writeSyncLocked();
8767        mShuttingDown = true;
8768    }
8769
8770    Parcel mPendingWrite = null;
8771    final ReentrantLock mWriteLock = new ReentrantLock();
8772
8773    public void writeAsyncLocked() {
8774        writeLocked(false);
8775    }
8776
8777    public void writeSyncLocked() {
8778        writeLocked(true);
8779    }
8780
8781    void writeLocked(boolean sync) {
8782        if (mFile == null) {
8783            Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
8784            return;
8785        }
8786
8787        if (mShuttingDown) {
8788            return;
8789        }
8790
8791        Parcel out = Parcel.obtain();
8792        writeSummaryToParcel(out, true);
8793        mLastWriteTime = SystemClock.elapsedRealtime();
8794
8795        if (mPendingWrite != null) {
8796            mPendingWrite.recycle();
8797        }
8798        mPendingWrite = out;
8799
8800        if (sync) {
8801            commitPendingDataToDisk();
8802        } else {
8803            BackgroundThread.getHandler().post(new Runnable() {
8804                @Override public void run() {
8805                    commitPendingDataToDisk();
8806                }
8807            });
8808        }
8809    }
8810
8811    public void commitPendingDataToDisk() {
8812        final Parcel next;
8813        synchronized (this) {
8814            next = mPendingWrite;
8815            mPendingWrite = null;
8816            if (next == null) {
8817                return;
8818            }
8819
8820            mWriteLock.lock();
8821        }
8822
8823        try {
8824            FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
8825            stream.write(next.marshall());
8826            stream.flush();
8827            FileUtils.sync(stream);
8828            stream.close();
8829            mFile.commit();
8830        } catch (IOException e) {
8831            Slog.w("BatteryStats", "Error writing battery statistics", e);
8832            mFile.rollback();
8833        } finally {
8834            next.recycle();
8835            mWriteLock.unlock();
8836        }
8837    }
8838
8839    public void readLocked() {
8840        if (mDailyFile != null) {
8841            readDailyStatsLocked();
8842        }
8843
8844        if (mFile == null) {
8845            Slog.w("BatteryStats", "readLocked: no file associated with this instance");
8846            return;
8847        }
8848
8849        mUidStats.clear();
8850
8851        try {
8852            File file = mFile.chooseForRead();
8853            if (!file.exists()) {
8854                return;
8855            }
8856            FileInputStream stream = new FileInputStream(file);
8857
8858            byte[] raw = BatteryStatsHelper.readFully(stream);
8859            Parcel in = Parcel.obtain();
8860            in.unmarshall(raw, 0, raw.length);
8861            in.setDataPosition(0);
8862            stream.close();
8863
8864            readSummaryFromParcel(in);
8865        } catch(Exception e) {
8866            Slog.e("BatteryStats", "Error reading battery statistics", e);
8867        }
8868
8869        mEndPlatformVersion = Build.ID;
8870
8871        if (mHistoryBuffer.dataPosition() > 0) {
8872            mRecordingHistory = true;
8873            final long elapsedRealtime = SystemClock.elapsedRealtime();
8874            final long uptime = SystemClock.uptimeMillis();
8875            if (USE_OLD_HISTORY) {
8876                addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
8877            }
8878            addHistoryBufferLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
8879            startRecordingHistory(elapsedRealtime, uptime, false);
8880        }
8881
8882        recordDailyStatsIfNeededLocked(false);
8883    }
8884
8885    public int describeContents() {
8886        return 0;
8887    }
8888
8889    void readHistory(Parcel in, boolean andOldHistory) {
8890        final long historyBaseTime = in.readLong();
8891
8892        mHistoryBuffer.setDataSize(0);
8893        mHistoryBuffer.setDataPosition(0);
8894        mHistoryTagPool.clear();
8895        mNextHistoryTagIdx = 0;
8896        mNumHistoryTagChars = 0;
8897
8898        int numTags = in.readInt();
8899        for (int i=0; i<numTags; i++) {
8900            int idx = in.readInt();
8901            String str = in.readString();
8902            int uid = in.readInt();
8903            HistoryTag tag = new HistoryTag();
8904            tag.string = str;
8905            tag.uid = uid;
8906            tag.poolIdx = idx;
8907            mHistoryTagPool.put(tag, idx);
8908            if (idx >= mNextHistoryTagIdx) {
8909                mNextHistoryTagIdx = idx+1;
8910            }
8911            mNumHistoryTagChars += tag.string.length() + 1;
8912        }
8913
8914        int bufSize = in.readInt();
8915        int curPos = in.dataPosition();
8916        if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
8917            Slog.w(TAG, "File corrupt: history data buffer too large " + bufSize);
8918        } else if ((bufSize&~3) != bufSize) {
8919            Slog.w(TAG, "File corrupt: history data buffer not aligned " + bufSize);
8920        } else {
8921            if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
8922                    + " bytes at " + curPos);
8923            mHistoryBuffer.appendFrom(in, curPos, bufSize);
8924            in.setDataPosition(curPos + bufSize);
8925        }
8926
8927        if (andOldHistory) {
8928            readOldHistory(in);
8929        }
8930
8931        if (DEBUG_HISTORY) {
8932            StringBuilder sb = new StringBuilder(128);
8933            sb.append("****************** OLD mHistoryBaseTime: ");
8934            TimeUtils.formatDuration(mHistoryBaseTime, sb);
8935            Slog.i(TAG, sb.toString());
8936        }
8937        mHistoryBaseTime = historyBaseTime;
8938        if (DEBUG_HISTORY) {
8939            StringBuilder sb = new StringBuilder(128);
8940            sb.append("****************** NEW mHistoryBaseTime: ");
8941            TimeUtils.formatDuration(mHistoryBaseTime, sb);
8942            Slog.i(TAG, sb.toString());
8943        }
8944
8945        // We are just arbitrarily going to insert 1 minute from the sample of
8946        // the last run until samples in this run.
8947        if (mHistoryBaseTime > 0) {
8948            long oldnow = SystemClock.elapsedRealtime();
8949            mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
8950            if (DEBUG_HISTORY) {
8951                StringBuilder sb = new StringBuilder(128);
8952                sb.append("****************** ADJUSTED mHistoryBaseTime: ");
8953                TimeUtils.formatDuration(mHistoryBaseTime, sb);
8954                Slog.i(TAG, sb.toString());
8955            }
8956        }
8957    }
8958
8959    void readOldHistory(Parcel in) {
8960        if (!USE_OLD_HISTORY) {
8961            return;
8962        }
8963        mHistory = mHistoryEnd = mHistoryCache = null;
8964        long time;
8965        while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
8966            HistoryItem rec = new HistoryItem(time, in);
8967            addHistoryRecordLocked(rec);
8968        }
8969    }
8970
8971    void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
8972        if (DEBUG_HISTORY) {
8973            StringBuilder sb = new StringBuilder(128);
8974            sb.append("****************** WRITING mHistoryBaseTime: ");
8975            TimeUtils.formatDuration(mHistoryBaseTime, sb);
8976            sb.append(" mLastHistoryElapsedRealtime: ");
8977            TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
8978            Slog.i(TAG, sb.toString());
8979        }
8980        out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
8981        if (!inclData) {
8982            out.writeInt(0);
8983            out.writeInt(0);
8984            return;
8985        }
8986        out.writeInt(mHistoryTagPool.size());
8987        for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
8988            HistoryTag tag = ent.getKey();
8989            out.writeInt(ent.getValue());
8990            out.writeString(tag.string);
8991            out.writeInt(tag.uid);
8992        }
8993        out.writeInt(mHistoryBuffer.dataSize());
8994        if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
8995                + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
8996        out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
8997
8998        if (andOldHistory) {
8999            writeOldHistory(out);
9000        }
9001    }
9002
9003    void writeOldHistory(Parcel out) {
9004        if (!USE_OLD_HISTORY) {
9005            return;
9006        }
9007        HistoryItem rec = mHistory;
9008        while (rec != null) {
9009            if (rec.time >= 0) rec.writeToParcel(out, 0);
9010            rec = rec.next;
9011        }
9012        out.writeLong(-1);
9013    }
9014
9015    public void readSummaryFromParcel(Parcel in) {
9016        final int version = in.readInt();
9017        if (version != VERSION) {
9018            Slog.w("BatteryStats", "readFromParcel: version got " + version
9019                + ", expected " + VERSION + "; erasing old stats");
9020            return;
9021        }
9022
9023        readHistory(in, true);
9024
9025        mStartCount = in.readInt();
9026        mUptime = in.readLong();
9027        mRealtime = in.readLong();
9028        mStartClockTime = in.readLong();
9029        mStartPlatformVersion = in.readString();
9030        mEndPlatformVersion = in.readString();
9031        mOnBatteryTimeBase.readSummaryFromParcel(in);
9032        mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
9033        mDischargeUnplugLevel = in.readInt();
9034        mDischargePlugLevel = in.readInt();
9035        mDischargeCurrentLevel = in.readInt();
9036        mCurrentBatteryLevel = in.readInt();
9037        mLowDischargeAmountSinceCharge = in.readInt();
9038        mHighDischargeAmountSinceCharge = in.readInt();
9039        mDischargeAmountScreenOnSinceCharge = in.readInt();
9040        mDischargeAmountScreenOffSinceCharge = in.readInt();
9041        mDischargeStepTracker.readFromParcel(in);
9042        mChargeStepTracker.readFromParcel(in);
9043        mDailyDischargeStepTracker.readFromParcel(in);
9044        mDailyChargeStepTracker.readFromParcel(in);
9045        int NPKG = in.readInt();
9046        if (NPKG > 0) {
9047            mDailyPackageChanges = new ArrayList<>(NPKG);
9048            while (NPKG > 0) {
9049                NPKG--;
9050                PackageChange pc = new PackageChange();
9051                pc.mPackageName = in.readString();
9052                pc.mUpdate = in.readInt() != 0;
9053                pc.mVersionCode = in.readInt();
9054                mDailyPackageChanges.add(pc);
9055            }
9056        } else {
9057            mDailyPackageChanges = null;
9058        }
9059        mDailyStartTime = in.readLong();
9060        mNextMinDailyDeadline = in.readLong();
9061        mNextMaxDailyDeadline = in.readLong();
9062
9063        mStartCount++;
9064
9065        mScreenState = Display.STATE_UNKNOWN;
9066        mScreenOnTimer.readSummaryFromParcelLocked(in);
9067        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
9068            mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
9069        }
9070        mInteractive = false;
9071        mInteractiveTimer.readSummaryFromParcelLocked(in);
9072        mPhoneOn = false;
9073        mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
9074        mDeviceIdleModeEnabledTimer.readSummaryFromParcelLocked(in);
9075        mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
9076        mPhoneOnTimer.readSummaryFromParcelLocked(in);
9077        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
9078            mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
9079        }
9080        mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
9081        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
9082            mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
9083        }
9084        for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
9085            mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
9086            mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
9087        }
9088        mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
9089        mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
9090        mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
9091        mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
9092        mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
9093        mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
9094        mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
9095        mWifiOn = false;
9096        mWifiOnTimer.readSummaryFromParcelLocked(in);
9097        mGlobalWifiRunning = false;
9098        mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
9099        for (int i=0; i<NUM_WIFI_STATES; i++) {
9100            mWifiStateTimer[i].readSummaryFromParcelLocked(in);
9101        }
9102        for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9103            mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
9104        }
9105        for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9106            mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
9107        }
9108        for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
9109            mBluetoothActivityCounters[i].readSummaryFromParcelLocked(in);
9110        }
9111        for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
9112            mWifiActivityCounters[i].readSummaryFromParcelLocked(in);
9113        }
9114
9115        mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
9116        mFlashlightOnNesting = 0;
9117        mFlashlightOnTimer.readSummaryFromParcelLocked(in);
9118        mCameraOnNesting = 0;
9119        mCameraOnTimer.readSummaryFromParcelLocked(in);
9120
9121        int NKW = in.readInt();
9122        if (NKW > 10000) {
9123            Slog.w(TAG, "File corrupt: too many kernel wake locks " + NKW);
9124            return;
9125        }
9126        for (int ikw = 0; ikw < NKW; ikw++) {
9127            if (in.readInt() != 0) {
9128                String kwltName = in.readString();
9129                getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
9130            }
9131        }
9132
9133        int NWR = in.readInt();
9134        if (NWR > 10000) {
9135            Slog.w(TAG, "File corrupt: too many wakeup reasons " + NWR);
9136            return;
9137        }
9138        for (int iwr = 0; iwr < NWR; iwr++) {
9139            if (in.readInt() != 0) {
9140                String reasonName = in.readString();
9141                getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
9142            }
9143        }
9144
9145        sNumSpeedSteps = in.readInt();
9146        if (sNumSpeedSteps < 0 || sNumSpeedSteps > 100) {
9147            throw new BadParcelableException("Bad speed steps in data: " + sNumSpeedSteps);
9148        }
9149
9150        final int NU = in.readInt();
9151        if (NU > 10000) {
9152            Slog.w(TAG, "File corrupt: too many uids " + NU);
9153            return;
9154        }
9155        for (int iu = 0; iu < NU; iu++) {
9156            int uid = in.readInt();
9157            Uid u = new Uid(uid);
9158            mUidStats.put(uid, u);
9159
9160            u.mWifiRunning = false;
9161            if (in.readInt() != 0) {
9162                u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
9163            }
9164            u.mFullWifiLockOut = false;
9165            if (in.readInt() != 0) {
9166                u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
9167            }
9168            u.mWifiScanStarted = false;
9169            if (in.readInt() != 0) {
9170                u.mWifiScanTimer.readSummaryFromParcelLocked(in);
9171            }
9172            u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
9173            for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
9174                if (in.readInt() != 0) {
9175                    u.makeWifiBatchedScanBin(i, null);
9176                    u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
9177                }
9178            }
9179            u.mWifiMulticastEnabled = false;
9180            if (in.readInt() != 0) {
9181                u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
9182            }
9183            if (in.readInt() != 0) {
9184                u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
9185            }
9186            if (in.readInt() != 0) {
9187                u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
9188            }
9189            if (in.readInt() != 0) {
9190                u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
9191            }
9192            if (in.readInt() != 0) {
9193                u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
9194            }
9195            if (in.readInt() != 0) {
9196                u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
9197            }
9198            u.mProcessState = Uid.PROCESS_STATE_NONE;
9199            for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
9200                if (in.readInt() != 0) {
9201                    u.makeProcessState(i, null);
9202                    u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
9203                }
9204            }
9205            if (in.readInt() != 0) {
9206                u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
9207            }
9208
9209            if (in.readInt() != 0) {
9210                if (u.mUserActivityCounters == null) {
9211                    u.initUserActivityLocked();
9212                }
9213                for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
9214                    u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
9215                }
9216            }
9217
9218            if (in.readInt() != 0) {
9219                if (u.mNetworkByteActivityCounters == null) {
9220                    u.initNetworkActivityLocked();
9221                }
9222                for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
9223                    u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
9224                    u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
9225                }
9226                u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
9227                u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
9228            }
9229
9230            u.mUserCpuTime.readSummaryFromParcelLocked(in);
9231            u.mSystemCpuTime.readSummaryFromParcelLocked(in);
9232
9233            int NSB = in.readInt();
9234            if (NSB > 100) {
9235                Slog.w(TAG, "File corrupt: too many speed bins " + NSB);
9236                return;
9237            }
9238
9239            u.mSpeedBins = new LongSamplingCounter[NSB];
9240            for (int i=0; i<NSB; i++) {
9241                if (in.readInt() != 0) {
9242                    u.mSpeedBins[i] = new LongSamplingCounter(mOnBatteryTimeBase);
9243                    u.mSpeedBins[i].readSummaryFromParcelLocked(in);
9244                }
9245            }
9246
9247            int NW = in.readInt();
9248            if (NW > 100) {
9249                Slog.w(TAG, "File corrupt: too many wake locks " + NW);
9250                return;
9251            }
9252            for (int iw = 0; iw < NW; iw++) {
9253                String wlName = in.readString();
9254                u.readWakeSummaryFromParcelLocked(wlName, in);
9255            }
9256
9257            int NS = in.readInt();
9258            if (NS > 100) {
9259                Slog.w(TAG, "File corrupt: too many syncs " + NS);
9260                return;
9261            }
9262            for (int is = 0; is < NS; is++) {
9263                String name = in.readString();
9264                u.readSyncSummaryFromParcelLocked(name, in);
9265            }
9266
9267            int NJ = in.readInt();
9268            if (NJ > 100) {
9269                Slog.w(TAG, "File corrupt: too many job timers " + NJ);
9270                return;
9271            }
9272            for (int ij = 0; ij < NJ; ij++) {
9273                String name = in.readString();
9274                u.readJobSummaryFromParcelLocked(name, in);
9275            }
9276
9277            int NP = in.readInt();
9278            if (NP > 1000) {
9279                Slog.w(TAG, "File corrupt: too many sensors " + NP);
9280                return;
9281            }
9282            for (int is = 0; is < NP; is++) {
9283                int seNumber = in.readInt();
9284                if (in.readInt() != 0) {
9285                    u.getSensorTimerLocked(seNumber, true)
9286                            .readSummaryFromParcelLocked(in);
9287                }
9288            }
9289
9290            NP = in.readInt();
9291            if (NP > 1000) {
9292                Slog.w(TAG, "File corrupt: too many processes " + NP);
9293                return;
9294            }
9295            for (int ip = 0; ip < NP; ip++) {
9296                String procName = in.readString();
9297                Uid.Proc p = u.getProcessStatsLocked(procName);
9298                p.mUserTime = p.mLoadedUserTime = in.readLong();
9299                p.mSystemTime = p.mLoadedSystemTime = in.readLong();
9300                p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
9301                p.mStarts = p.mLoadedStarts = in.readInt();
9302                p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
9303                p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
9304                if (!p.readExcessivePowerFromParcelLocked(in)) {
9305                    return;
9306                }
9307            }
9308
9309            NP = in.readInt();
9310            if (NP > 10000) {
9311                Slog.w(TAG, "File corrupt: too many packages " + NP);
9312                return;
9313            }
9314            for (int ip = 0; ip < NP; ip++) {
9315                String pkgName = in.readString();
9316                Uid.Pkg p = u.getPackageStatsLocked(pkgName);
9317                final int NWA = in.readInt();
9318                if (NWA > 1000) {
9319                    Slog.w(TAG, "File corrupt: too many wakeup alarms " + NWA);
9320                    return;
9321                }
9322                p.mWakeupAlarms.clear();
9323                for (int iwa=0; iwa<NWA; iwa++) {
9324                    String tag = in.readString();
9325                    Counter c = new Counter(mOnBatteryTimeBase);
9326                    c.readSummaryFromParcelLocked(in);
9327                    p.mWakeupAlarms.put(tag, c);
9328                }
9329                NS = in.readInt();
9330                if (NS > 1000) {
9331                    Slog.w(TAG, "File corrupt: too many services " + NS);
9332                    return;
9333                }
9334                for (int is = 0; is < NS; is++) {
9335                    String servName = in.readString();
9336                    Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
9337                    s.mStartTime = s.mLoadedStartTime = in.readLong();
9338                    s.mStarts = s.mLoadedStarts = in.readInt();
9339                    s.mLaunches = s.mLoadedLaunches = in.readInt();
9340                }
9341            }
9342        }
9343    }
9344
9345    /**
9346     * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
9347     * disk.  This format does not allow a lossless round-trip.
9348     *
9349     * @param out the Parcel to be written to.
9350     */
9351    public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
9352        pullPendingStateUpdatesLocked();
9353
9354        // Pull the clock time.  This may update the time and make a new history entry
9355        // if we had originally pulled a time before the RTC was set.
9356        long startClockTime = getStartClockTime();
9357
9358        final long NOW_SYS = SystemClock.uptimeMillis() * 1000;
9359        final long NOWREAL_SYS = SystemClock.elapsedRealtime() * 1000;
9360
9361        out.writeInt(VERSION);
9362
9363        writeHistory(out, inclHistory, true);
9364
9365        out.writeInt(mStartCount);
9366        out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
9367        out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
9368        out.writeLong(startClockTime);
9369        out.writeString(mStartPlatformVersion);
9370        out.writeString(mEndPlatformVersion);
9371        mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
9372        mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
9373        out.writeInt(mDischargeUnplugLevel);
9374        out.writeInt(mDischargePlugLevel);
9375        out.writeInt(mDischargeCurrentLevel);
9376        out.writeInt(mCurrentBatteryLevel);
9377        out.writeInt(getLowDischargeAmountSinceCharge());
9378        out.writeInt(getHighDischargeAmountSinceCharge());
9379        out.writeInt(getDischargeAmountScreenOnSinceCharge());
9380        out.writeInt(getDischargeAmountScreenOffSinceCharge());
9381        mDischargeStepTracker.writeToParcel(out);
9382        mChargeStepTracker.writeToParcel(out);
9383        mDailyDischargeStepTracker.writeToParcel(out);
9384        mDailyChargeStepTracker.writeToParcel(out);
9385        if (mDailyPackageChanges != null) {
9386            final int NPKG = mDailyPackageChanges.size();
9387            out.writeInt(NPKG);
9388            for (int i=0; i<NPKG; i++) {
9389                PackageChange pc = mDailyPackageChanges.get(i);
9390                out.writeString(pc.mPackageName);
9391                out.writeInt(pc.mUpdate ? 1 : 0);
9392                out.writeInt(pc.mVersionCode);
9393            }
9394        } else {
9395            out.writeInt(0);
9396        }
9397        out.writeLong(mDailyStartTime);
9398        out.writeLong(mNextMinDailyDeadline);
9399        out.writeLong(mNextMaxDailyDeadline);
9400
9401        mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9402        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
9403            mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9404        }
9405        mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9406        mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9407        mDeviceIdleModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9408        mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9409        mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9410        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
9411            mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9412        }
9413        mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9414        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
9415            mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9416        }
9417        for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
9418            mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
9419            mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
9420        }
9421        mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9422        mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9423        mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
9424        mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
9425        mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
9426        mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9427        mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9428        for (int i=0; i<NUM_WIFI_STATES; i++) {
9429            mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9430        }
9431        for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9432            mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9433        }
9434        for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9435            mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9436        }
9437        for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
9438            mBluetoothActivityCounters[i].writeSummaryFromParcelLocked(out);
9439        }
9440        for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
9441            mWifiActivityCounters[i].writeSummaryFromParcelLocked(out);
9442        }
9443        out.writeInt(mNumConnectivityChange);
9444        mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9445        mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9446
9447        out.writeInt(mKernelWakelockStats.size());
9448        for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
9449            Timer kwlt = ent.getValue();
9450            if (kwlt != null) {
9451                out.writeInt(1);
9452                out.writeString(ent.getKey());
9453                kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9454            } else {
9455                out.writeInt(0);
9456            }
9457        }
9458
9459        out.writeInt(mWakeupReasonStats.size());
9460        for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
9461            SamplingTimer timer = ent.getValue();
9462            if (timer != null) {
9463                out.writeInt(1);
9464                out.writeString(ent.getKey());
9465                timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9466            } else {
9467                out.writeInt(0);
9468            }
9469        }
9470
9471        out.writeInt(sNumSpeedSteps);
9472        final int NU = mUidStats.size();
9473        out.writeInt(NU);
9474        for (int iu = 0; iu < NU; iu++) {
9475            out.writeInt(mUidStats.keyAt(iu));
9476            Uid u = mUidStats.valueAt(iu);
9477
9478            if (u.mWifiRunningTimer != null) {
9479                out.writeInt(1);
9480                u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9481            } else {
9482                out.writeInt(0);
9483            }
9484            if (u.mFullWifiLockTimer != null) {
9485                out.writeInt(1);
9486                u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9487            } else {
9488                out.writeInt(0);
9489            }
9490            if (u.mWifiScanTimer != null) {
9491                out.writeInt(1);
9492                u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9493            } else {
9494                out.writeInt(0);
9495            }
9496            for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
9497                if (u.mWifiBatchedScanTimer[i] != null) {
9498                    out.writeInt(1);
9499                    u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9500                } else {
9501                    out.writeInt(0);
9502                }
9503            }
9504            if (u.mWifiMulticastTimer != null) {
9505                out.writeInt(1);
9506                u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9507            } else {
9508                out.writeInt(0);
9509            }
9510            if (u.mAudioTurnedOnTimer != null) {
9511                out.writeInt(1);
9512                u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9513            } else {
9514                out.writeInt(0);
9515            }
9516            if (u.mVideoTurnedOnTimer != null) {
9517                out.writeInt(1);
9518                u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9519            } else {
9520                out.writeInt(0);
9521            }
9522            if (u.mFlashlightTurnedOnTimer != null) {
9523                out.writeInt(1);
9524                u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9525            } else {
9526                out.writeInt(0);
9527            }
9528            if (u.mCameraTurnedOnTimer != null) {
9529                out.writeInt(1);
9530                u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9531            } else {
9532                out.writeInt(0);
9533            }
9534            if (u.mForegroundActivityTimer != null) {
9535                out.writeInt(1);
9536                u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9537            } else {
9538                out.writeInt(0);
9539            }
9540            for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
9541                if (u.mProcessStateTimer[i] != null) {
9542                    out.writeInt(1);
9543                    u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9544                } else {
9545                    out.writeInt(0);
9546                }
9547            }
9548            if (u.mVibratorOnTimer != null) {
9549                out.writeInt(1);
9550                u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9551            } else {
9552                out.writeInt(0);
9553            }
9554
9555            if (u.mUserActivityCounters == null) {
9556                out.writeInt(0);
9557            } else {
9558                out.writeInt(1);
9559                for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
9560                    u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
9561                }
9562            }
9563
9564            if (u.mNetworkByteActivityCounters == null) {
9565                out.writeInt(0);
9566            } else {
9567                out.writeInt(1);
9568                for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
9569                    u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
9570                    u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
9571                }
9572                u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
9573                u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
9574            }
9575
9576            u.mUserCpuTime.writeSummaryFromParcelLocked(out);
9577            u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
9578
9579            out.writeInt(u.mSpeedBins.length);
9580            for (int i = 0; i < u.mSpeedBins.length; i++) {
9581                LongSamplingCounter speedBin = u.mSpeedBins[i];
9582                if (speedBin != null) {
9583                    out.writeInt(1);
9584                    speedBin.writeSummaryFromParcelLocked(out);
9585                } else {
9586                    out.writeInt(0);
9587                }
9588            }
9589
9590            final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
9591            int NW = wakeStats.size();
9592            out.writeInt(NW);
9593            for (int iw=0; iw<NW; iw++) {
9594                out.writeString(wakeStats.keyAt(iw));
9595                Uid.Wakelock wl = wakeStats.valueAt(iw);
9596                if (wl.mTimerFull != null) {
9597                    out.writeInt(1);
9598                    wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9599                } else {
9600                    out.writeInt(0);
9601                }
9602                if (wl.mTimerPartial != null) {
9603                    out.writeInt(1);
9604                    wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9605                } else {
9606                    out.writeInt(0);
9607                }
9608                if (wl.mTimerWindow != null) {
9609                    out.writeInt(1);
9610                    wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9611                } else {
9612                    out.writeInt(0);
9613                }
9614                if (wl.mTimerDraw != null) {
9615                    out.writeInt(1);
9616                    wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9617                } else {
9618                    out.writeInt(0);
9619                }
9620            }
9621
9622            final ArrayMap<String, StopwatchTimer> syncStats = u.mSyncStats.getMap();
9623            int NS = syncStats.size();
9624            out.writeInt(NS);
9625            for (int is=0; is<NS; is++) {
9626                out.writeString(syncStats.keyAt(is));
9627                syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9628            }
9629
9630            final ArrayMap<String, StopwatchTimer> jobStats = u.mJobStats.getMap();
9631            int NJ = jobStats.size();
9632            out.writeInt(NJ);
9633            for (int ij=0; ij<NJ; ij++) {
9634                out.writeString(jobStats.keyAt(ij));
9635                jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9636            }
9637
9638            int NSE = u.mSensorStats.size();
9639            out.writeInt(NSE);
9640            for (int ise=0; ise<NSE; ise++) {
9641                out.writeInt(u.mSensorStats.keyAt(ise));
9642                Uid.Sensor se = u.mSensorStats.valueAt(ise);
9643                if (se.mTimer != null) {
9644                    out.writeInt(1);
9645                    se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
9646                } else {
9647                    out.writeInt(0);
9648                }
9649            }
9650
9651            int NP = u.mProcessStats.size();
9652            out.writeInt(NP);
9653            for (int ip=0; ip<NP; ip++) {
9654                out.writeString(u.mProcessStats.keyAt(ip));
9655                Uid.Proc ps = u.mProcessStats.valueAt(ip);
9656                out.writeLong(ps.mUserTime);
9657                out.writeLong(ps.mSystemTime);
9658                out.writeLong(ps.mForegroundTime);
9659                out.writeInt(ps.mStarts);
9660                out.writeInt(ps.mNumCrashes);
9661                out.writeInt(ps.mNumAnrs);
9662                ps.writeExcessivePowerToParcelLocked(out);
9663            }
9664
9665            NP = u.mPackageStats.size();
9666            out.writeInt(NP);
9667            if (NP > 0) {
9668                for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
9669                    : u.mPackageStats.entrySet()) {
9670                    out.writeString(ent.getKey());
9671                    Uid.Pkg ps = ent.getValue();
9672                    final int NWA = ps.mWakeupAlarms.size();
9673                    out.writeInt(NWA);
9674                    for (int iwa=0; iwa<NWA; iwa++) {
9675                        out.writeString(ps.mWakeupAlarms.keyAt(iwa));
9676                        ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
9677                    }
9678                    NS = ps.mServiceStats.size();
9679                    out.writeInt(NS);
9680                    for (int is=0; is<NS; is++) {
9681                        out.writeString(ps.mServiceStats.keyAt(is));
9682                        BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
9683                        long time = ss.getStartTimeToNowLocked(
9684                                mOnBatteryTimeBase.getUptime(NOW_SYS));
9685                        out.writeLong(time);
9686                        out.writeInt(ss.mStarts);
9687                        out.writeInt(ss.mLaunches);
9688                    }
9689                }
9690            }
9691        }
9692    }
9693
9694    public void readFromParcel(Parcel in) {
9695        readFromParcelLocked(in);
9696    }
9697
9698    void readFromParcelLocked(Parcel in) {
9699        int magic = in.readInt();
9700        if (magic != MAGIC) {
9701            throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
9702        }
9703
9704        readHistory(in, false);
9705
9706        mStartCount = in.readInt();
9707        mStartClockTime = in.readLong();
9708        mStartPlatformVersion = in.readString();
9709        mEndPlatformVersion = in.readString();
9710        mUptime = in.readLong();
9711        mUptimeStart = in.readLong();
9712        mRealtime = in.readLong();
9713        mRealtimeStart = in.readLong();
9714        mOnBattery = in.readInt() != 0;
9715        mOnBatteryInternal = false; // we are no longer really running.
9716        mOnBatteryTimeBase.readFromParcel(in);
9717        mOnBatteryScreenOffTimeBase.readFromParcel(in);
9718
9719        mScreenState = Display.STATE_UNKNOWN;
9720        mScreenOnTimer = new StopwatchTimer(null, -1, null, mOnBatteryTimeBase, in);
9721        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
9722            mScreenBrightnessTimer[i] = new StopwatchTimer(null, -100-i, null, mOnBatteryTimeBase,
9723                    in);
9724        }
9725        mInteractive = false;
9726        mInteractiveTimer = new StopwatchTimer(null, -10, null, mOnBatteryTimeBase, in);
9727        mPhoneOn = false;
9728        mPowerSaveModeEnabledTimer = new StopwatchTimer(null, -2, null, mOnBatteryTimeBase, in);
9729        mDeviceIdleModeEnabledTimer = new StopwatchTimer(null, -11, null, mOnBatteryTimeBase, in);
9730        mDeviceIdlingTimer = new StopwatchTimer(null, -12, null, mOnBatteryTimeBase, in);
9731        mPhoneOnTimer = new StopwatchTimer(null, -3, null, mOnBatteryTimeBase, in);
9732        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
9733            mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(null, -200-i,
9734                    null, mOnBatteryTimeBase, in);
9735        }
9736        mPhoneSignalScanningTimer = new StopwatchTimer(null, -200+1, null, mOnBatteryTimeBase, in);
9737        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
9738            mPhoneDataConnectionsTimer[i] = new StopwatchTimer(null, -300-i,
9739                    null, mOnBatteryTimeBase, in);
9740        }
9741        for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
9742            mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
9743            mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
9744        }
9745        mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
9746        mMobileRadioActiveTimer = new StopwatchTimer(null, -400, null, mOnBatteryTimeBase, in);
9747        mMobileRadioActivePerAppTimer = new StopwatchTimer(null, -401, null, mOnBatteryTimeBase,
9748                in);
9749        mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
9750        mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
9751        mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
9752        mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
9753        mWifiOn = false;
9754        mWifiOnTimer = new StopwatchTimer(null, -4, null, mOnBatteryTimeBase, in);
9755        mGlobalWifiRunning = false;
9756        mGlobalWifiRunningTimer = new StopwatchTimer(null, -5, null, mOnBatteryTimeBase, in);
9757        for (int i=0; i<NUM_WIFI_STATES; i++) {
9758            mWifiStateTimer[i] = new StopwatchTimer(null, -600-i,
9759                    null, mOnBatteryTimeBase, in);
9760        }
9761        for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9762            mWifiSupplStateTimer[i] = new StopwatchTimer(null, -700-i,
9763                    null, mOnBatteryTimeBase, in);
9764        }
9765        for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9766            mWifiSignalStrengthsTimer[i] = new StopwatchTimer(null, -800-i,
9767                    null, mOnBatteryTimeBase, in);
9768        }
9769        for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
9770            mBluetoothActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
9771        }
9772        for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
9773            mWifiActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
9774        }
9775
9776        mHasWifiEnergyReporting = in.readInt() != 0;
9777        mHasBluetoothEnergyReporting = in.readInt() != 0;
9778        mNumConnectivityChange = in.readInt();
9779        mLoadedNumConnectivityChange = in.readInt();
9780        mUnpluggedNumConnectivityChange = in.readInt();
9781        mAudioOnNesting = 0;
9782        mAudioOnTimer = new StopwatchTimer(null, -7, null, mOnBatteryTimeBase);
9783        mVideoOnNesting = 0;
9784        mVideoOnTimer = new StopwatchTimer(null, -8, null, mOnBatteryTimeBase);
9785        mFlashlightOnNesting = 0;
9786        mFlashlightOnTimer = new StopwatchTimer(null, -9, null, mOnBatteryTimeBase, in);
9787        mCameraOnNesting = 0;
9788        mCameraOnTimer = new StopwatchTimer(null, -13, null, mOnBatteryTimeBase, in);
9789        mDischargeUnplugLevel = in.readInt();
9790        mDischargePlugLevel = in.readInt();
9791        mDischargeCurrentLevel = in.readInt();
9792        mCurrentBatteryLevel = in.readInt();
9793        mLowDischargeAmountSinceCharge = in.readInt();
9794        mHighDischargeAmountSinceCharge = in.readInt();
9795        mDischargeAmountScreenOn = in.readInt();
9796        mDischargeAmountScreenOnSinceCharge = in.readInt();
9797        mDischargeAmountScreenOff = in.readInt();
9798        mDischargeAmountScreenOffSinceCharge = in.readInt();
9799        mDischargeStepTracker.readFromParcel(in);
9800        mChargeStepTracker.readFromParcel(in);
9801        mLastWriteTime = in.readLong();
9802
9803        mKernelWakelockStats.clear();
9804        int NKW = in.readInt();
9805        for (int ikw = 0; ikw < NKW; ikw++) {
9806            if (in.readInt() != 0) {
9807                String wakelockName = in.readString();
9808                SamplingTimer kwlt = new SamplingTimer(mOnBatteryScreenOffTimeBase, in);
9809                mKernelWakelockStats.put(wakelockName, kwlt);
9810            }
9811        }
9812
9813        mWakeupReasonStats.clear();
9814        int NWR = in.readInt();
9815        for (int iwr = 0; iwr < NWR; iwr++) {
9816            if (in.readInt() != 0) {
9817                String reasonName = in.readString();
9818                SamplingTimer timer = new SamplingTimer(mOnBatteryTimeBase, in);
9819                mWakeupReasonStats.put(reasonName, timer);
9820            }
9821        }
9822
9823        mPartialTimers.clear();
9824        mFullTimers.clear();
9825        mWindowTimers.clear();
9826        mWifiRunningTimers.clear();
9827        mFullWifiLockTimers.clear();
9828        mWifiScanTimers.clear();
9829        mWifiBatchedScanTimers.clear();
9830        mWifiMulticastTimers.clear();
9831        mAudioTurnedOnTimers.clear();
9832        mVideoTurnedOnTimers.clear();
9833        mFlashlightTurnedOnTimers.clear();
9834        mCameraTurnedOnTimers.clear();
9835
9836        sNumSpeedSteps = in.readInt();
9837
9838        int numUids = in.readInt();
9839        mUidStats.clear();
9840        for (int i = 0; i < numUids; i++) {
9841            int uid = in.readInt();
9842            Uid u = new Uid(uid);
9843            u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
9844            mUidStats.append(uid, u);
9845        }
9846    }
9847
9848    public void writeToParcel(Parcel out, int flags) {
9849        writeToParcelLocked(out, true, flags);
9850    }
9851
9852    public void writeToParcelWithoutUids(Parcel out, int flags) {
9853        writeToParcelLocked(out, false, flags);
9854    }
9855
9856    @SuppressWarnings("unused")
9857    void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
9858        // Need to update with current kernel wake lock counts.
9859        pullPendingStateUpdatesLocked();
9860
9861        // Pull the clock time.  This may update the time and make a new history entry
9862        // if we had originally pulled a time before the RTC was set.
9863        long startClockTime = getStartClockTime();
9864
9865        final long uSecUptime = SystemClock.uptimeMillis() * 1000;
9866        final long uSecRealtime = SystemClock.elapsedRealtime() * 1000;
9867        final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
9868        final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
9869
9870        out.writeInt(MAGIC);
9871
9872        writeHistory(out, true, false);
9873
9874        out.writeInt(mStartCount);
9875        out.writeLong(startClockTime);
9876        out.writeString(mStartPlatformVersion);
9877        out.writeString(mEndPlatformVersion);
9878        out.writeLong(mUptime);
9879        out.writeLong(mUptimeStart);
9880        out.writeLong(mRealtime);
9881        out.writeLong(mRealtimeStart);
9882        out.writeInt(mOnBattery ? 1 : 0);
9883        mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
9884        mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
9885
9886        mScreenOnTimer.writeToParcel(out, uSecRealtime);
9887        for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
9888            mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
9889        }
9890        mInteractiveTimer.writeToParcel(out, uSecRealtime);
9891        mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
9892        mDeviceIdleModeEnabledTimer.writeToParcel(out, uSecRealtime);
9893        mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
9894        mPhoneOnTimer.writeToParcel(out, uSecRealtime);
9895        for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
9896            mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
9897        }
9898        mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
9899        for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
9900            mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
9901        }
9902        for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
9903            mNetworkByteActivityCounters[i].writeToParcel(out);
9904            mNetworkPacketActivityCounters[i].writeToParcel(out);
9905        }
9906        mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
9907        mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
9908        mMobileRadioActiveAdjustedTime.writeToParcel(out);
9909        mMobileRadioActiveUnknownTime.writeToParcel(out);
9910        mMobileRadioActiveUnknownCount.writeToParcel(out);
9911        mWifiOnTimer.writeToParcel(out, uSecRealtime);
9912        mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
9913        for (int i=0; i<NUM_WIFI_STATES; i++) {
9914            mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
9915        }
9916        for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9917            mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
9918        }
9919        for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9920            mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
9921        }
9922        for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
9923            mBluetoothActivityCounters[i].writeToParcel(out);
9924        }
9925        for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
9926            mWifiActivityCounters[i].writeToParcel(out);
9927        }
9928        out.writeInt(mHasWifiEnergyReporting ? 1 : 0);
9929        out.writeInt(mHasBluetoothEnergyReporting ? 1 : 0);
9930        out.writeInt(mNumConnectivityChange);
9931        out.writeInt(mLoadedNumConnectivityChange);
9932        out.writeInt(mUnpluggedNumConnectivityChange);
9933        mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
9934        mCameraOnTimer.writeToParcel(out, uSecRealtime);
9935        out.writeInt(mDischargeUnplugLevel);
9936        out.writeInt(mDischargePlugLevel);
9937        out.writeInt(mDischargeCurrentLevel);
9938        out.writeInt(mCurrentBatteryLevel);
9939        out.writeInt(mLowDischargeAmountSinceCharge);
9940        out.writeInt(mHighDischargeAmountSinceCharge);
9941        out.writeInt(mDischargeAmountScreenOn);
9942        out.writeInt(mDischargeAmountScreenOnSinceCharge);
9943        out.writeInt(mDischargeAmountScreenOff);
9944        out.writeInt(mDischargeAmountScreenOffSinceCharge);
9945        mDischargeStepTracker.writeToParcel(out);
9946        mChargeStepTracker.writeToParcel(out);
9947        out.writeLong(mLastWriteTime);
9948
9949        if (inclUids) {
9950            out.writeInt(mKernelWakelockStats.size());
9951            for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
9952                SamplingTimer kwlt = ent.getValue();
9953                if (kwlt != null) {
9954                    out.writeInt(1);
9955                    out.writeString(ent.getKey());
9956                    kwlt.writeToParcel(out, uSecRealtime);
9957                } else {
9958                    out.writeInt(0);
9959                }
9960            }
9961            out.writeInt(mWakeupReasonStats.size());
9962            for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
9963                SamplingTimer timer = ent.getValue();
9964                if (timer != null) {
9965                    out.writeInt(1);
9966                    out.writeString(ent.getKey());
9967                    timer.writeToParcel(out, uSecRealtime);
9968                } else {
9969                    out.writeInt(0);
9970                }
9971            }
9972        } else {
9973            out.writeInt(0);
9974        }
9975
9976        out.writeInt(sNumSpeedSteps);
9977
9978        if (inclUids) {
9979            int size = mUidStats.size();
9980            out.writeInt(size);
9981            for (int i = 0; i < size; i++) {
9982                out.writeInt(mUidStats.keyAt(i));
9983                Uid uid = mUidStats.valueAt(i);
9984
9985                uid.writeToParcelLocked(out, uSecRealtime);
9986            }
9987        } else {
9988            out.writeInt(0);
9989        }
9990    }
9991
9992    public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
9993        new Parcelable.Creator<BatteryStatsImpl>() {
9994        public BatteryStatsImpl createFromParcel(Parcel in) {
9995            return new BatteryStatsImpl(in);
9996        }
9997
9998        public BatteryStatsImpl[] newArray(int size) {
9999            return new BatteryStatsImpl[size];
10000        }
10001    };
10002
10003    public void prepareForDumpLocked() {
10004        // Need to retrieve current kernel wake lock stats before printing.
10005        pullPendingStateUpdatesLocked();
10006
10007        // Pull the clock time.  This may update the time and make a new history entry
10008        // if we had originally pulled a time before the RTC was set.
10009        getStartClockTime();
10010    }
10011
10012    public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
10013        if (DEBUG) {
10014            pw.println("mOnBatteryTimeBase:");
10015            mOnBatteryTimeBase.dump(pw, "  ");
10016            pw.println("mOnBatteryScreenOffTimeBase:");
10017            mOnBatteryScreenOffTimeBase.dump(pw, "  ");
10018            Printer pr = new PrintWriterPrinter(pw);
10019            pr.println("*** Screen timer:");
10020            mScreenOnTimer.logState(pr, "  ");
10021            for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
10022                pr.println("*** Screen brightness #" + i + ":");
10023                mScreenBrightnessTimer[i].logState(pr, "  ");
10024            }
10025            pr.println("*** Interactive timer:");
10026            mInteractiveTimer.logState(pr, "  ");
10027            pr.println("*** Power save mode timer:");
10028            mPowerSaveModeEnabledTimer.logState(pr, "  ");
10029            pr.println("*** Device idle mode timer:");
10030            mDeviceIdleModeEnabledTimer.logState(pr, "  ");
10031            pr.println("*** Device idling timer:");
10032            mDeviceIdlingTimer.logState(pr, "  ");
10033            pr.println("*** Phone timer:");
10034            mPhoneOnTimer.logState(pr, "  ");
10035            for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10036                pr.println("*** Phone signal strength #" + i + ":");
10037                mPhoneSignalStrengthsTimer[i].logState(pr, "  ");
10038            }
10039            pr.println("*** Signal scanning :");
10040            mPhoneSignalScanningTimer.logState(pr, "  ");
10041            for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
10042                pr.println("*** Data connection type #" + i + ":");
10043                mPhoneDataConnectionsTimer[i].logState(pr, "  ");
10044            }
10045            pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
10046            pr.println("*** Mobile network active timer:");
10047            mMobileRadioActiveTimer.logState(pr, "  ");
10048            pr.println("*** Mobile network active adjusted timer:");
10049            mMobileRadioActiveAdjustedTime.logState(pr, "  ");
10050            pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
10051            pr.println("*** Wifi timer:");
10052            mWifiOnTimer.logState(pr, "  ");
10053            pr.println("*** WifiRunning timer:");
10054            mGlobalWifiRunningTimer.logState(pr, "  ");
10055            for (int i=0; i<NUM_WIFI_STATES; i++) {
10056                pr.println("*** Wifi state #" + i + ":");
10057                mWifiStateTimer[i].logState(pr, "  ");
10058            }
10059            for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10060                pr.println("*** Wifi suppl state #" + i + ":");
10061                mWifiSupplStateTimer[i].logState(pr, "  ");
10062            }
10063            for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10064                pr.println("*** Wifi signal strength #" + i + ":");
10065                mWifiSignalStrengthsTimer[i].logState(pr, "  ");
10066            }
10067            pr.println("*** Flashlight timer:");
10068            mFlashlightOnTimer.logState(pr, "  ");
10069            pr.println("*** Camera timer:");
10070            mCameraOnTimer.logState(pr, "  ");
10071        }
10072        super.dumpLocked(context, pw, flags, reqUid, histStart);
10073    }
10074}
10075