summaryrefslogtreecommitdiffstats
path: root/service/java/com/android/server/wifi/WifiLockManager.java
blob: e292a84d8a2c5f89b54ea9bd8681fe74e483bb25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.server.wifi;

import android.app.ActivityManager;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.WorkSource;
import android.os.WorkSource.WorkChain;
import android.util.Slog;
import android.util.SparseArray;
import android.util.StatsLog;

import com.android.internal.app.IBatteryStats;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * WifiLockManager maintains the list of wake locks held by different applications.
 */
public class WifiLockManager {
    private static final String TAG = "WifiLockManager";

    private static final int LOW_LATENCY_SUPPORT_UNDEFINED = -1;
    private static final int LOW_LATENCY_NOT_SUPPORTED     =  0;
    private static final int LOW_LATENCY_SUPPORTED         =  1;

    private static final int IGNORE_SCREEN_STATE_MASK = 0x01;
    private static final int IGNORE_WIFI_STATE_MASK   = 0x02;

    private int mLatencyModeSupport = LOW_LATENCY_SUPPORT_UNDEFINED;

    private boolean mVerboseLoggingEnabled = false;

    private final Clock mClock;
    private final Context mContext;
    private final IBatteryStats mBatteryStats;
    private final FrameworkFacade mFrameworkFacade;
    private final ClientModeImpl mClientModeImpl;
    private final ActivityManager mActivityManager;
    private final Handler mHandler;
    private final WifiMetrics mWifiMetrics;
    private final WifiNative mWifiNative;

    private final List<WifiLock> mWifiLocks = new ArrayList<>();
    // map UIDs to their corresponding records (for low-latency locks)
    private final SparseArray<UidRec> mLowLatencyUidWatchList = new SparseArray<>();
    private int mCurrentOpMode;
    private boolean mScreenOn = false;
    private boolean mWifiConnected = false;

    // For shell command support
    private boolean mForceHiPerfMode = false;
    private boolean mForceLowLatencyMode = false;

    // some wifi lock statistics
    private int mFullHighPerfLocksAcquired;
    private int mFullHighPerfLocksReleased;
    private int mFullLowLatencyLocksAcquired;
    private int mFullLowLatencyLocksReleased;
    private long mCurrentSessionStartTimeMs;

    WifiLockManager(Context context, IBatteryStats batteryStats,
            ClientModeImpl clientModeImpl, FrameworkFacade frameworkFacade, Handler handler,
            WifiNative wifiNative, Clock clock, WifiMetrics wifiMetrics) {
        mContext = context;
        mBatteryStats = batteryStats;
        mClientModeImpl = clientModeImpl;
        mFrameworkFacade = frameworkFacade;
        mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        mCurrentOpMode = WifiManager.WIFI_MODE_NO_LOCKS_HELD;
        mWifiNative = wifiNative;
        mHandler = handler;
        mClock = clock;
        mWifiMetrics = wifiMetrics;

        // Register for UID fg/bg transitions
        registerUidImportanceTransitions();
    }

    // Check for conditions to activate high-perf lock
    private boolean canActivateHighPerfLock(int ignoreMask) {
        boolean check = true;

        // Only condition is when Wifi is connected
        if ((ignoreMask & IGNORE_WIFI_STATE_MASK) == 0) {
            check = check && mWifiConnected;
        }

        return check;
    }

    private boolean canActivateHighPerfLock() {
        return canActivateHighPerfLock(0);
    }

    // Check for conditions to activate low-latency lock
    private boolean canActivateLowLatencyLock(int ignoreMask, UidRec uidRec) {
        boolean check = true;

        if ((ignoreMask & IGNORE_WIFI_STATE_MASK) == 0) {
            check = check && mWifiConnected;
        }
        if ((ignoreMask & IGNORE_SCREEN_STATE_MASK) == 0) {
            check = check && mScreenOn;
        }
        if (uidRec != null) {
            check = check && uidRec.mIsFg;
        }

        return check;
    }

    private boolean canActivateLowLatencyLock(int ignoreMask) {
        return canActivateLowLatencyLock(ignoreMask, null);
    }

    private boolean canActivateLowLatencyLock() {
        return canActivateLowLatencyLock(0, null);
    }

    // Detect UIDs going foreground/background
    private void registerUidImportanceTransitions() {
        mActivityManager.addOnUidImportanceListener(new ActivityManager.OnUidImportanceListener() {
            @Override
            public void onUidImportance(final int uid, final int importance) {
                mHandler.post(() -> {
                    UidRec uidRec = mLowLatencyUidWatchList.get(uid);
                    if (uidRec == null) {
                        // Not a uid in the watch list
                        return;
                    }

                    boolean newModeIsFg = (importance
                            == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND);
                    if (uidRec.mIsFg == newModeIsFg) {
                        return; // already at correct state
                    }

                    uidRec.mIsFg = newModeIsFg;
                    updateOpMode();

                    // If conditions for lock activation are met,
                    // then UID either share the blame, or removed from sharing
                    // whether to start or stop the blame based on UID fg/bg state
                    if (canActivateLowLatencyLock()) {
                        setBlameLowLatencyUid(uid, uidRec.mIsFg);
                    }
                });
            }
        }, ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE);
    }

    /**
     * Method allowing a calling app to acquire a Wifi WakeLock in the supplied mode.
     *
     * This method checks that the lock mode is a valid WifiLock mode.
     * @param lockMode int representation of the Wifi WakeLock type.
     * @param tag String passed to WifiManager.WifiLock
     * @param binder IBinder for the calling app
     * @param ws WorkSource of the calling app
     *
     * @return true if the lock was successfully acquired, false if the lockMode was invalid.
     */
    public boolean acquireWifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
        if (!isValidLockMode(lockMode)) {
            throw new IllegalArgumentException("lockMode =" + lockMode);
        }

        // Make a copy of the WorkSource before adding it to the WakeLock
        // This is to make sure worksource value can not be changed by caller
        // after function returns.
        WorkSource newWorkSource = new WorkSource(ws);

        return addLock(new WifiLock(lockMode, tag, binder, newWorkSource));
    }

    /**
     * Method used by applications to release a WiFi Wake lock.
     *
     * @param binder IBinder for the calling app.
     * @return true if the lock was released, false if the caller did not hold any locks
     */
    public boolean releaseWifiLock(IBinder binder) {
        return releaseLock(binder);
    }

    /**
     * Method used to get the strongest lock type currently held by the WifiLockManager.
     *
     * If no locks are held, WifiManager.WIFI_MODE_NO_LOCKS_HELD is returned.
     *
     * @return int representing the currently held (highest power consumption) lock.
     */
    public synchronized int getStrongestLockMode() {
        // If Wifi Client is not connected, then all locks are not effective
        if (!mWifiConnected) {
            return WifiManager.WIFI_MODE_NO_LOCKS_HELD;
        }

        // Check if mode is forced to hi-perf
        if (mForceHiPerfMode) {
            return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
        }

        // Check if mode is forced to low-latency
        if (mForceLowLatencyMode) {
            return WifiManager.WIFI_MODE_FULL_LOW_LATENCY;
        }

        if (mScreenOn && countFgLowLatencyUids() > 0) {
            return WifiManager.WIFI_MODE_FULL_LOW_LATENCY;
        }

        if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
            return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
        }

        return WifiManager.WIFI_MODE_NO_LOCKS_HELD;
    }

    /**
     * Method to create a WorkSource containing all active WifiLock WorkSources.
     */
    public synchronized WorkSource createMergedWorkSource() {
        WorkSource mergedWS = new WorkSource();
        for (WifiLock lock : mWifiLocks) {
            mergedWS.add(lock.getWorkSource());
        }
        return mergedWS;
    }

    /**
     * Method used to update WifiLocks with a new WorkSouce.
     *
     * @param binder IBinder for the calling application.
     * @param ws WorkSource to add to the existing WifiLock(s).
     */
    public synchronized void updateWifiLockWorkSource(IBinder binder, WorkSource ws) {

        // Now check if there is an active lock
        WifiLock wl = findLockByBinder(binder);
        if (wl == null) {
            throw new IllegalArgumentException("Wifi lock not active");
        }

        // Make a copy of the WorkSource before adding it to the WakeLock
        // This is to make sure worksource value can not be changed by caller
        // after function returns.
        WorkSource newWorkSource = new WorkSource(ws);

        if (mVerboseLoggingEnabled) {
            Slog.d(TAG, "updateWifiLockWakeSource: " + wl + ", newWorkSource=" + newWorkSource);
        }

        // Note:
        // Log the acquire before the release to avoid "holes" in the collected data due to
        // an acquire event immediately after a release in the case where newWorkSource and
        // wl.mWorkSource share one or more attribution UIDs. Both batteryStats and statsd
        // can correctly match "nested" acquire / release pairs.
        switch(wl.mMode) {
            case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
                // Shift blame to new worksource if needed
                if (canActivateHighPerfLock()) {
                    setBlameHiPerfWs(newWorkSource, true);
                    setBlameHiPerfWs(wl.mWorkSource, false);
                }
                break;
            case WifiManager.WIFI_MODE_FULL_LOW_LATENCY:
                addWsToLlWatchList(newWorkSource);
                removeWsFromLlWatchList(wl.mWorkSource);
                updateOpMode();
                break;
            default:
                // Do nothing
                break;
        }

        wl.mWorkSource = newWorkSource;
    }

    /**
     * Method Used for shell command support
     *
     * @param isEnabled True to force hi-perf mode, false to leave it up to acquired wifiLocks.
     * @return True for success, false for failure (failure turns forcing mode off)
     */
    public boolean forceHiPerfMode(boolean isEnabled) {
        mForceHiPerfMode = isEnabled;
        mForceLowLatencyMode = false;
        if (!updateOpMode()) {
            Slog.e(TAG, "Failed to force hi-perf mode, returning to normal mode");
            mForceHiPerfMode = false;
            return false;
        }
        return true;
    }

    /**
     * Method Used for shell command support
     *
     * @param isEnabled True to force low-latency mode, false to leave it up to acquired wifiLocks.
     * @return True for success, false for failure (failure turns forcing mode off)
     */
    public boolean forceLowLatencyMode(boolean isEnabled) {
        mForceLowLatencyMode = isEnabled;
        mForceHiPerfMode = false;
        if (!updateOpMode()) {
            Slog.e(TAG, "Failed to force low-latency mode, returning to normal mode");
            mForceLowLatencyMode = false;
            return false;
        }
        return true;
    }

    /**
     * Handler for screen state (on/off) changes
     */
    public void handleScreenStateChanged(boolean screenOn) {
        if (mVerboseLoggingEnabled) {
            Slog.d(TAG, "handleScreenStateChanged: screenOn = " + screenOn);
        }

        mScreenOn = screenOn;

        if (canActivateLowLatencyLock(IGNORE_SCREEN_STATE_MASK)) {
            // Update the running mode
            updateOpMode();
            // Adjust blaming for UIDs in foreground
            setBlameLowLatencyWatchList(screenOn);
        }
    }

    /**
     * Handler for Wifi Client mode state changes
     */
    public void updateWifiClientConnected(boolean isConnected) {
        if (mWifiConnected == isConnected) {
            // No need to take action
            return;
        }
        mWifiConnected = isConnected;

        // Adjust blaming for UIDs in foreground carrying low latency locks
        if (canActivateLowLatencyLock(IGNORE_WIFI_STATE_MASK)) {
            setBlameLowLatencyWatchList(mWifiConnected);
        }

        // Adjust blaming for UIDs carrying high perf locks
        // Note that blaming is adjusted only if needed,
        // since calling this API is reference counted
        if (canActivateHighPerfLock(IGNORE_WIFI_STATE_MASK)) {
            setBlameHiPerfLocks(mWifiConnected);
        }

        updateOpMode();
    }

    private void setBlameHiPerfLocks(boolean shouldBlame) {
        for (WifiLock lock : mWifiLocks) {
            if (lock.mMode == WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
                setBlameHiPerfWs(lock.getWorkSource(), shouldBlame);
            }
        }
    }

    private static boolean isValidLockMode(int lockMode) {
        if (lockMode != WifiManager.WIFI_MODE_FULL
                && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY
                && lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF
                && lockMode != WifiManager.WIFI_MODE_FULL_LOW_LATENCY) {
            return false;
        }
        return true;
    }

    private void addUidToLlWatchList(int uid) {
        UidRec uidRec = mLowLatencyUidWatchList.get(uid);
        if (uidRec != null) {
            uidRec.mLockCount++;
        } else {
            uidRec = new UidRec(uid);
            uidRec.mLockCount = 1;
            mLowLatencyUidWatchList.put(uid, uidRec);

            // Now check if the uid is running in foreground
            if (mFrameworkFacade.isAppForeground(uid)) {
                uidRec.mIsFg = true;
            }

            if (canActivateLowLatencyLock(0, uidRec)) {
                // Share the blame for this uid
                setBlameLowLatencyUid(uid, true);
            }
        }
    }

    private void removeUidFromLlWatchList(int uid) {
        UidRec uidRec = mLowLatencyUidWatchList.get(uid);
        if (uidRec == null) {
            Slog.e(TAG, "Failed to find uid in low-latency watch list");
            return;
        }

        if (uidRec.mLockCount > 0) {
            uidRec.mLockCount--;
        } else {
            Slog.e(TAG, "Error, uid record conatains no locks");
        }
        if (uidRec.mLockCount == 0) {
            mLowLatencyUidWatchList.remove(uid);

            // Remove blame for this UID if it was alerady set
            // Note that blame needs to be stopped only if it was started before
            // to avoid calling the API unnecessarily, since it is reference counted
            if (canActivateLowLatencyLock(0, uidRec)) {
                setBlameLowLatencyUid(uid, false);
            }
        }
    }

    private void addWsToLlWatchList(WorkSource ws) {
        int wsSize = ws.size();
        for (int i = 0; i < wsSize; i++) {
            final int uid = ws.get(i);
            addUidToLlWatchList(uid);
        }

        final List<WorkChain> workChains = ws.getWorkChains();
        if (workChains != null) {
            for (int i = 0; i < workChains.size(); ++i) {
                final WorkChain workChain = workChains.get(i);
                final int uid = workChain.getAttributionUid();
                addUidToLlWatchList(uid);
            }
        }
    }

    private void removeWsFromLlWatchList(WorkSource ws) {
        int wsSize = ws.size();
        for (int i = 0; i < wsSize; i++) {
            final int uid = ws.get(i);
            removeUidFromLlWatchList(uid);
        }

        final List<WorkChain> workChains = ws.getWorkChains();
        if (workChains != null) {
            for (int i = 0; i < workChains.size(); ++i) {
                final WorkChain workChain = workChains.get(i);
                final int uid = workChain.getAttributionUid();
                removeUidFromLlWatchList(uid);
            }
        }
    }

    private synchronized boolean addLock(WifiLock lock) {
        if (mVerboseLoggingEnabled) {
            Slog.d(TAG, "addLock: " + lock);
        }

        if (findLockByBinder(lock.getBinder()) != null) {
            if (mVerboseLoggingEnabled) {
                Slog.d(TAG, "attempted to add a lock when already holding one");
            }
            return false;
        }

        mWifiLocks.add(lock);

        switch(lock.mMode) {
            case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
                ++mFullHighPerfLocksAcquired;
                // Start blaming this worksource if conditions are met
                if (canActivateHighPerfLock()) {
                    setBlameHiPerfWs(lock.mWorkSource, true);
                }
                break;
            case WifiManager.WIFI_MODE_FULL_LOW_LATENCY:
                addWsToLlWatchList(lock.getWorkSource());
                ++mFullLowLatencyLocksAcquired;
                break;
            default:
                // Do nothing
                break;
        }

        // Recalculate the operating mode
        updateOpMode();

        return true;
    }

    private synchronized WifiLock removeLock(IBinder binder) {
        WifiLock lock = findLockByBinder(binder);
        if (lock != null) {
            mWifiLocks.remove(lock);
            lock.unlinkDeathRecipient();
        }
        return lock;
    }

    private synchronized boolean releaseLock(IBinder binder) {
        WifiLock wifiLock = removeLock(binder);
        if (wifiLock == null) {
            // attempting to release a lock that does not exist.
            return false;
        }

        if (mVerboseLoggingEnabled) {
            Slog.d(TAG, "releaseLock: " + wifiLock);
        }

        switch(wifiLock.mMode) {
            case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
                ++mFullHighPerfLocksReleased;
                mWifiMetrics.addWifiLockAcqSession(WifiManager.WIFI_MODE_FULL_HIGH_PERF,
                        mClock.getElapsedSinceBootMillis() - wifiLock.getAcqTimestamp());
                // Stop blaming only if blaming was set before (conditions are met).
                // This is to avoid calling the api unncessarily, since this API is
                // reference counted in batteryStats and statsd
                if (canActivateHighPerfLock()) {
                    setBlameHiPerfWs(wifiLock.mWorkSource, false);
                }
                break;
            case WifiManager.WIFI_MODE_FULL_LOW_LATENCY:
                removeWsFromLlWatchList(wifiLock.getWorkSource());
                ++mFullLowLatencyLocksReleased;
                mWifiMetrics.addWifiLockAcqSession(WifiManager.WIFI_MODE_FULL_LOW_LATENCY,
                        mClock.getElapsedSinceBootMillis() - wifiLock.getAcqTimestamp());
                break;
            default:
                // Do nothing
                break;
        }

        // Recalculate the operating mode
        updateOpMode();

        return true;
    }

    private synchronized boolean updateOpMode() {
        final int newLockMode = getStrongestLockMode();

        if (newLockMode == mCurrentOpMode) {
            // No action is needed
            return true;
        }

        if (mVerboseLoggingEnabled) {
            Slog.d(TAG, "Current opMode: " + mCurrentOpMode + " New LockMode: " + newLockMode);
        }

        // Otherwise, we need to change current mode, first reset it to normal
        switch (mCurrentOpMode) {
            case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
                if (!mClientModeImpl.setPowerSave(true)) {
                    Slog.e(TAG, "Failed to reset the OpMode from hi-perf to Normal");
                    return false;
                }
                mWifiMetrics.addWifiLockActiveSession(WifiManager.WIFI_MODE_FULL_HIGH_PERF,
                        mClock.getElapsedSinceBootMillis() - mCurrentSessionStartTimeMs);
                break;

            case WifiManager.WIFI_MODE_FULL_LOW_LATENCY:
                if (!setLowLatencyMode(false)) {
                    Slog.e(TAG, "Failed to reset the OpMode from low-latency to Normal");
                    return false;
                }
                mWifiMetrics.addWifiLockActiveSession(WifiManager.WIFI_MODE_FULL_LOW_LATENCY,
                        mClock.getElapsedSinceBootMillis() - mCurrentSessionStartTimeMs);
                break;

            case WifiManager.WIFI_MODE_NO_LOCKS_HELD:
            default:
                // No action
                break;
        }

        // Set the current mode, before we attempt to set the new mode
        mCurrentOpMode = WifiManager.WIFI_MODE_NO_LOCKS_HELD;

        // Now switch to the new opMode
        switch (newLockMode) {
            case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
                if (!mClientModeImpl.setPowerSave(false)) {
                    Slog.e(TAG, "Failed to set the OpMode to hi-perf");
                    return false;
                }
                mCurrentSessionStartTimeMs = mClock.getElapsedSinceBootMillis();
                break;

            case WifiManager.WIFI_MODE_FULL_LOW_LATENCY:
                if (!setLowLatencyMode(true)) {
                    Slog.e(TAG, "Failed to set the OpMode to low-latency");
                    return false;
                }
                mCurrentSessionStartTimeMs = mClock.getElapsedSinceBootMillis();
                break;

            case WifiManager.WIFI_MODE_NO_LOCKS_HELD:
                // No action
                break;

            default:
                // Invalid mode, don't change currentOpMode , and exit with error
                Slog.e(TAG, "Invalid new opMode: " + newLockMode);
                return false;
        }

        // Now set the mode to the new value
        mCurrentOpMode = newLockMode;
        return true;
    }

    private int getLowLatencyModeSupport() {
        if (mLatencyModeSupport == LOW_LATENCY_SUPPORT_UNDEFINED) {
            String ifaceName = mWifiNative.getClientInterfaceName();
            if (ifaceName == null) {
                return LOW_LATENCY_SUPPORT_UNDEFINED;
            }

            long supportedFeatures = mWifiNative.getSupportedFeatureSet(ifaceName);
            if (supportedFeatures != 0) {
                if ((supportedFeatures & WifiManager.WIFI_FEATURE_LOW_LATENCY) != 0) {
                    mLatencyModeSupport = LOW_LATENCY_SUPPORTED;
                } else {
                    mLatencyModeSupport = LOW_LATENCY_NOT_SUPPORTED;
                }
            }
        }

        return mLatencyModeSupport;
    }

    private boolean setLowLatencyMode(boolean enabled) {
        int lowLatencySupport = getLowLatencyModeSupport();

        if (lowLatencySupport == LOW_LATENCY_SUPPORT_UNDEFINED) {
            // Support undefined, no action is taken
            return false;
        }

        if (lowLatencySupport == LOW_LATENCY_SUPPORTED) {
            if (!mClientModeImpl.setLowLatencyMode(enabled)) {
                Slog.e(TAG, "Failed to set low latency mode");
                return false;
            }

            if (!mClientModeImpl.setPowerSave(!enabled)) {
                Slog.e(TAG, "Failed to set power save mode");
                // Revert the low latency mode
                mClientModeImpl.setLowLatencyMode(!enabled);
                return false;
            }
        } else if (lowLatencySupport == LOW_LATENCY_NOT_SUPPORTED) {
            // Only set power save mode
            if (!mClientModeImpl.setPowerSave(!enabled)) {
                Slog.e(TAG, "Failed to set power save mode");
                return false;
            }
        }

        return true;
    }

    private synchronized WifiLock findLockByBinder(IBinder binder) {
        for (WifiLock lock : mWifiLocks) {
            if (lock.getBinder() == binder) {
                return lock;
            }
        }
        return null;
    }

    private int countFgLowLatencyUids() {
        int uidCount = 0;
        int listSize = mLowLatencyUidWatchList.size();
        for (int idx = 0; idx < listSize; idx++) {
            UidRec uidRec = mLowLatencyUidWatchList.valueAt(idx);
            if (uidRec.mIsFg) {
                uidCount++;
            }
        }
        return uidCount;
    }

    private void setBlameHiPerfWs(WorkSource ws, boolean shouldBlame) {
        long ident = Binder.clearCallingIdentity();
        try {
            if (shouldBlame) {
                mBatteryStats.noteFullWifiLockAcquiredFromSource(ws);
                StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED, ws,
                        StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON,
                        WifiManager.WIFI_MODE_FULL_HIGH_PERF);
            } else {
                mBatteryStats.noteFullWifiLockReleasedFromSource(ws);
                StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED, ws,
                        StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF,
                        WifiManager.WIFI_MODE_FULL_HIGH_PERF);
            }
        } catch (RemoteException e) {
            // nop
        } finally {
            Binder.restoreCallingIdentity(ident);
        }
    }

    private void setBlameLowLatencyUid(int uid, boolean shouldBlame) {
        long ident = Binder.clearCallingIdentity();
        try {
            if (shouldBlame) {
                mBatteryStats.noteFullWifiLockAcquired(uid);
                StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, uid, null,
                        StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON,
                        WifiManager.WIFI_MODE_FULL_LOW_LATENCY);
            } else {
                mBatteryStats.noteFullWifiLockReleased(uid);
                StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, uid, null,
                        StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF,
                        WifiManager.WIFI_MODE_FULL_LOW_LATENCY);
            }
        } catch (RemoteException e) {
            // nop
        } finally {
            Binder.restoreCallingIdentity(ident);
        }
    }

    private void setBlameLowLatencyWatchList(boolean shouldBlame) {
        for (int idx = 0; idx < mLowLatencyUidWatchList.size(); idx++) {
            UidRec uidRec = mLowLatencyUidWatchList.valueAt(idx);
            // Affect the blame for only UIDs running in foreground
            // UIDs running in the background are already not blamed,
            // and they should remain in that state.
            if (uidRec.mIsFg) {
                setBlameLowLatencyUid(uidRec.mUid, shouldBlame);
            }
        }
    }

    protected void dump(PrintWriter pw) {
        pw.println("Locks acquired: "
                + mFullHighPerfLocksAcquired + " full high perf, "
                + mFullLowLatencyLocksAcquired + " full low latency");
        pw.println("Locks released: "
                + mFullHighPerfLocksReleased + " full high perf, "
                + mFullLowLatencyLocksReleased + " full low latency");

        pw.println();
        pw.println("Locks held:");
        for (WifiLock lock : mWifiLocks) {
            pw.print("    ");
            pw.println(lock);
        }
    }

    protected void enableVerboseLogging(int verbose) {
        if (verbose > 0) {
            mVerboseLoggingEnabled = true;
        } else {
            mVerboseLoggingEnabled = false;
        }
    }

    private class WifiLock implements IBinder.DeathRecipient {
        String mTag;
        int mUid;
        IBinder mBinder;
        int mMode;
        WorkSource mWorkSource;
        long mAcqTimestamp;

        WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
            mTag = tag;
            mBinder = binder;
            mUid = Binder.getCallingUid();
            mMode = lockMode;
            mWorkSource = ws;
            mAcqTimestamp = mClock.getElapsedSinceBootMillis();
            try {
                mBinder.linkToDeath(this, 0);
            } catch (RemoteException e) {
                binderDied();
            }
        }

        protected WorkSource getWorkSource() {
            return mWorkSource;
        }

        protected int getUid() {
            return mUid;
        }

        protected IBinder getBinder() {
            return mBinder;
        }

        protected long getAcqTimestamp() {
            return mAcqTimestamp;
        }

        public void binderDied() {
            releaseLock(mBinder);
        }

        public void unlinkDeathRecipient() {
            mBinder.unlinkToDeath(this, 0);
        }

        public String toString() {
            return "WifiLock{" + this.mTag + " type=" + this.mMode + " uid=" + mUid
                    + " workSource=" + mWorkSource + "}";
        }
    }

    private class UidRec {
        final int mUid;
        // Count of locks owned or co-owned by this UID
        int mLockCount;
        // Is this UID running in foreground
        boolean mIsFg;

        UidRec(int uid) {
            mUid = uid;
        }
    }
}