• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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 
17 package com.android.server.am;
18 
19 import static android.Manifest.permission.INTERACT_ACROSS_PROFILES;
20 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
21 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
22 import static android.Manifest.permission.MANAGE_USERS;
23 import static android.app.ActivityManager.STOP_USER_ON_SWITCH_DEFAULT;
24 import static android.app.ActivityManager.STOP_USER_ON_SWITCH_TRUE;
25 import static android.app.ActivityManager.StopUserOnSwitch;
26 import static android.app.ActivityManager.USER_OP_ERROR_IS_SYSTEM;
27 import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
28 import static android.app.ActivityManager.USER_OP_IS_CURRENT;
29 import static android.app.ActivityManager.USER_OP_SUCCESS;
30 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
31 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
32 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE;
33 import static android.app.ActivityManagerInternal.ALLOW_PROFILES_OR_NON_FULL;
34 import static android.os.PowerWhitelistManager.REASON_BOOT_COMPLETED;
35 import static android.os.PowerWhitelistManager.REASON_LOCKED_BOOT_COMPLETED;
36 import static android.os.PowerWhitelistManager.TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_ALLOWED;
37 import static android.os.Process.SHELL_UID;
38 import static android.os.Process.SYSTEM_UID;
39 
40 import static com.android.internal.util.FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FRAMEWORK_LOCKED_BOOT_COMPLETED;
41 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
42 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
43 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
44 import static com.android.server.am.ActivityManagerService.MY_PID;
45 import static com.android.server.am.UserState.STATE_BOOTING;
46 import static com.android.server.am.UserState.STATE_RUNNING_LOCKED;
47 import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKED;
48 import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKING;
49 import static com.android.server.pm.UserJourneyLogger.ERROR_CODE_ABORTED;
50 import static com.android.server.pm.UserJourneyLogger.ERROR_CODE_INVALID_SESSION_ID;
51 import static com.android.server.pm.UserJourneyLogger.EVENT_STATE_BEGIN;
52 import static com.android.server.pm.UserJourneyLogger.EVENT_STATE_FINISH;
53 import static com.android.server.pm.UserJourneyLogger.EVENT_STATE_NONE;
54 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_USER_START;
55 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_USER_STOP;
56 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_USER_SWITCH_FG;
57 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_USER_SWITCH_UI;
58 import static com.android.server.pm.UserJourneyLogger.USER_LIFECYCLE_EVENT_UNLOCKED_USER;
59 import static com.android.server.pm.UserJourneyLogger.USER_LIFECYCLE_EVENT_UNLOCKING_USER;
60 import static com.android.server.pm.UserJourneyLogger.USER_LIFECYCLE_EVENT_USER_RUNNING_LOCKED;
61 import static com.android.server.pm.UserManagerInternal.USER_ASSIGNMENT_RESULT_FAILURE;
62 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_BACKGROUND_VISIBLE;
63 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_FOREGROUND;
64 import static com.android.server.pm.UserManagerInternal.userAssignmentResultToString;
65 import static com.android.server.pm.UserManagerInternal.userStartModeToString;
66 
67 import android.annotation.NonNull;
68 import android.annotation.Nullable;
69 import android.annotation.RequiresPermission;
70 import android.annotation.UserIdInt;
71 import android.app.ActivityManager;
72 import android.app.ActivityManagerInternal;
73 import android.app.AppGlobals;
74 import android.app.AppOpsManager;
75 import android.app.BroadcastOptions;
76 import android.app.IStopUserCallback;
77 import android.app.IUserSwitchObserver;
78 import android.app.KeyguardManager;
79 import android.app.admin.DevicePolicyManagerInternal;
80 import android.app.usage.UsageEvents;
81 import android.appwidget.AppWidgetManagerInternal;
82 import android.content.Context;
83 import android.content.IIntentReceiver;
84 import android.content.Intent;
85 import android.content.PermissionChecker;
86 import android.content.pm.IPackageManager;
87 import android.content.pm.PackageManager;
88 import android.content.pm.PackagePartitions;
89 import android.content.pm.UserInfo;
90 import android.content.pm.UserProperties;
91 import android.os.BatteryStats;
92 import android.os.Binder;
93 import android.os.Bundle;
94 import android.os.Debug;
95 import android.os.Handler;
96 import android.os.IBinder;
97 import android.os.IProgressListener;
98 import android.os.IRemoteCallback;
99 import android.os.IUserManager;
100 import android.os.Message;
101 import android.os.PowerWhitelistManager;
102 import android.os.Process;
103 import android.os.RemoteCallbackList;
104 import android.os.RemoteException;
105 import android.os.ServiceManager;
106 import android.os.SystemClock;
107 import android.os.SystemProperties;
108 import android.os.UserHandle;
109 import android.os.UserManager;
110 import android.os.storage.IStorageManager;
111 import android.os.storage.StorageManager;
112 import android.text.TextUtils;
113 import android.text.format.DateUtils;
114 import android.util.ArraySet;
115 import android.util.EventLog;
116 import android.util.IntArray;
117 import android.util.Pair;
118 import android.util.SparseArray;
119 import android.util.SparseIntArray;
120 import android.util.proto.ProtoOutputStream;
121 import android.view.Display;
122 
123 import com.android.internal.R;
124 import com.android.internal.annotations.GuardedBy;
125 import com.android.internal.annotations.VisibleForTesting;
126 import com.android.internal.policy.IKeyguardDismissCallback;
127 import com.android.internal.util.ArrayUtils;
128 import com.android.internal.util.FrameworkStatsLog;
129 import com.android.internal.util.Preconditions;
130 import com.android.internal.widget.LockPatternUtils;
131 import com.android.server.FactoryResetter;
132 import com.android.server.FgThread;
133 import com.android.server.LocalServices;
134 import com.android.server.SystemService.UserCompletedEventType;
135 import com.android.server.SystemServiceManager;
136 import com.android.server.am.UserState.KeyEvictedCallback;
137 import com.android.server.pm.UserJourneyLogger;
138 import com.android.server.pm.UserJourneyLogger.UserJourneySession;
139 import com.android.server.pm.UserManagerInternal;
140 import com.android.server.pm.UserManagerInternal.UserLifecycleListener;
141 import com.android.server.pm.UserManagerInternal.UserStartMode;
142 import com.android.server.pm.UserManagerService;
143 import com.android.server.utils.Slogf;
144 import com.android.server.utils.TimingsTraceAndSlog;
145 import com.android.server.wm.ActivityTaskManagerInternal;
146 import com.android.server.wm.WindowManagerService;
147 
148 import java.io.PrintWriter;
149 import java.util.ArrayList;
150 import java.util.Arrays;
151 import java.util.Iterator;
152 import java.util.List;
153 import java.util.Objects;
154 import java.util.concurrent.CountDownLatch;
155 import java.util.concurrent.TimeUnit;
156 import java.util.concurrent.atomic.AtomicBoolean;
157 import java.util.concurrent.atomic.AtomicInteger;
158 import java.util.function.Consumer;
159 
160 /**
161  * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
162  *
163  * <p>This class use {@link #mLock} to synchronize access to internal state. Methods that require
164  * {@link #mLock} to be held should have "LU" suffix in the name.
165  *
166  * <p><strong>Important:</strong> Synchronized code, i.e. one executed inside a synchronized(mLock)
167  * block or inside LU method, should only access internal state of this class or make calls to
168  * other LU methods. Non-LU method calls or calls to external classes are discouraged as they
169  * may cause lock inversion.
170  */
171 class UserController implements Handler.Callback {
172     private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
173 
174     // Amount of time we wait for observers to handle a user switch before
175     // giving up on them and dismissing the user switching dialog.
176     static final int DEFAULT_USER_SWITCH_TIMEOUT_MS = 3 * 1000;
177 
178     /**
179      * Amount of time we wait for an observer to handle a user switch before we log a warning. This
180      * wait time is per observer.
181      */
182     private static final int LONG_USER_SWITCH_OBSERVER_WARNING_TIME_MS = 500;
183 
184     // ActivityManager thread message constants
185     static final int REPORT_USER_SWITCH_MSG = 10;
186     static final int CONTINUE_USER_SWITCH_MSG = 20;
187     static final int USER_SWITCH_TIMEOUT_MSG = 30;
188     static final int START_PROFILES_MSG = 40;
189     static final int USER_START_MSG = 50;
190     static final int USER_CURRENT_MSG = 60;
191     static final int FOREGROUND_PROFILE_CHANGED_MSG = 70;
192     static final int REPORT_USER_SWITCH_COMPLETE_MSG = 80;
193     static final int USER_SWITCH_CALLBACKS_TIMEOUT_MSG = 90;
194     static final int USER_UNLOCK_MSG = 100;
195     static final int USER_UNLOCKED_MSG = 105;
196     static final int REPORT_LOCKED_BOOT_COMPLETE_MSG = 110;
197     static final int START_USER_SWITCH_FG_MSG = 120;
198     static final int COMPLETE_USER_SWITCH_MSG = 130;
199     static final int USER_COMPLETED_EVENT_MSG = 140;
200 
201     private static final int NO_ARG2 = 0;
202 
203     // Message constant to clear {@link UserJourneySession} from {@link mUserIdToUserJourneyMap} if
204     // the user journey, defined in the UserLifecycleJourneyReported atom for statsd, is not
205     // complete within {@link USER_JOURNEY_TIMEOUT}.
206     static final int CLEAR_USER_JOURNEY_SESSION_MSG = 200;
207     // Wait time for completing the user journey. If a user journey is not complete within this
208     // time, the remaining lifecycle events for the journey would not be logged in statsd.
209     // Timeout set for 90 seconds.
210     private static final int USER_JOURNEY_TIMEOUT_MS = 90_000;
211 
212     // UI thread message constants
213     static final int START_USER_SWITCH_UI_MSG = 1000;
214 
215     /**
216      * If a callback wasn't called within USER_SWITCH_CALLBACKS_TIMEOUT_MS after
217      * {@link #getUserSwitchTimeoutMs}, an error is reported. Usually it indicates a problem in the
218      * observer when it never calls back.
219      */
220     private static final int USER_SWITCH_CALLBACKS_TIMEOUT_MS = 5 * 1000;
221 
222     /**
223      * Amount of time waited for {@link WindowManagerService#dismissKeyguard} callbacks to be
224      * called after dismissing the keyguard.
225      * Otherwise, we should move on to dismiss the dialog {@link #dismissUserSwitchDialog()}
226      * and report user switch is complete {@link #REPORT_USER_SWITCH_COMPLETE_MSG}.
227      */
228     private static final int DISMISS_KEYGUARD_TIMEOUT_MS = 2 * 1000;
229 
230     /**
231      * Time after last scheduleOnUserCompletedEvent() call at which USER_COMPLETED_EVENT_MSG will be
232      * scheduled (although it may fire sooner instead).
233      * When it fires, {@link #reportOnUserCompletedEvent} will be processed.
234      */
235     // TODO(b/197344658): Increase to 10s or 15s once we have a switch-UX-is-done invocation too.
236     private static final int USER_COMPLETED_EVENT_DELAY_MS = 5 * 1000;
237 
238     /**
239      * Maximum number of users we allow to be running at a time, including system user.
240      *
241      * <p>This parameter only affects how many background users will be stopped when switching to a
242      * new user. It has no impact on {@link #startUser(int, boolean)} behavior.
243      *
244      * <p>Note: Current and system user (and their related profiles) are never stopped when
245      * switching users. Due to that, the actual number of running users can exceed mMaxRunningUsers
246      */
247     @GuardedBy("mLock")
248     private int mMaxRunningUsers;
249 
250     // Lock for internal state.
251     private final Object mLock = new Object();
252 
253     private final Injector mInjector;
254     private final Handler mHandler;
255     private final Handler mUiHandler;
256 
257     // Holds the current foreground user's id. Use mLock when updating
258     @GuardedBy("mLock")
259     private volatile int mCurrentUserId = UserHandle.USER_SYSTEM;
260     // Holds the target user's id during a user switch. The value of mCurrentUserId will be updated
261     // once target user goes into the foreground. Use mLock when updating
262     @GuardedBy("mLock")
263     private volatile int mTargetUserId = UserHandle.USER_NULL;
264 
265     /**
266      * Which users have been started, so are allowed to run code.
267      */
268     @GuardedBy("mLock")
269     private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
270 
271     /**
272      * LRU list of history of current users.  Most recently current is at the end.
273      */
274     @GuardedBy("mLock")
275     private final ArrayList<Integer> mUserLru = new ArrayList<>();
276 
277     /**
278      * Constant array of the users that are currently started.
279      */
280     @GuardedBy("mLock")
281     private int[] mStartedUserArray = new int[] { 0 };
282 
283     /**
284      * Contains the current user and its profiles (if any).
285      *
286      * <p><b>NOTE: </b>it lists all profiles, regardless of their running state (i.e., they're in
287      * this list even if not running).
288      */
289     @GuardedBy("mLock")
290     private int[] mCurrentProfileIds = new int[] {};
291 
292     /**
293      * Mapping from each known user ID to the profile group ID it is associated with.
294      */
295     @GuardedBy("mLock")
296     private final SparseIntArray mUserProfileGroupIds = new SparseIntArray();
297 
298     /**
299      * Registered observers of the user switching mechanics.
300      */
301     private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
302             = new RemoteCallbackList<>();
303 
304     @GuardedBy("mLock")
305     private boolean mUserSwitchUiEnabled = true;
306 
307     /**
308      * Currently active user switch callbacks.
309      */
310     @GuardedBy("mLock")
311     private volatile ArraySet<String> mCurWaitingUserSwitchCallbacks;
312 
313     /**
314      * Messages for switching from {@link android.os.UserHandle#SYSTEM}.
315      */
316     @GuardedBy("mLock")
317     private String mSwitchingFromSystemUserMessage;
318 
319     /**
320      * Messages for switching to {@link android.os.UserHandle#SYSTEM}.
321      */
322     @GuardedBy("mLock")
323     private String mSwitchingToSystemUserMessage;
324 
325     /**
326      * Callbacks that are still active after {@link #getUserSwitchTimeoutMs}
327      */
328     @GuardedBy("mLock")
329     private ArraySet<String> mTimeoutUserSwitchCallbacks;
330 
331     private final LockPatternUtils mLockPatternUtils;
332 
333     // TODO(b/266158156): remove this once we improve/refactor the way broadcasts are sent for
334     //  the system user in HSUM.
335     @GuardedBy("mLock")
336     private boolean mIsBroadcastSentForSystemUserStarted;
337 
338     // TODO(b/266158156): remove this once we improve/refactor the way broadcasts are sent for
339     //  the system user in HSUM.
340     @GuardedBy("mLock")
341     private boolean mIsBroadcastSentForSystemUserStarting;
342 
343     volatile boolean mBootCompleted;
344 
345     /**
346      * In this mode, user is always stopped when switched out (unless overridden by the
347      * {@code fw.stop_bg_users_on_switch} system property) but locking of user data is
348      * postponed until total number of unlocked users in the system reaches mMaxRunningUsers.
349      * Once total number of unlocked users reach mMaxRunningUsers, least recently used user
350      * will be locked.
351      */
352     @GuardedBy("mLock")
353     private boolean mDelayUserDataLocking;
354 
355     /**
356      * Users are only allowed to be unlocked after boot complete.
357      */
358     private volatile boolean mAllowUserUnlocking;
359 
360     /**
361      * Keep track of last active users for mDelayUserDataLocking.
362      * The latest stopped user is placed in front while the least recently stopped user in back.
363      */
364     @GuardedBy("mLock")
365     private final ArrayList<Integer> mLastActiveUsers = new ArrayList<>();
366 
367     /**
368      * Map of userId to {@link UserCompletedEventType} event flags, indicating which as-yet-
369      * unreported user-starting events have transpired for the given user.
370      */
371     @GuardedBy("mCompletedEventTypes")
372     private final SparseIntArray mCompletedEventTypes = new SparseIntArray();
373 
374     /**
375      * Sets on {@link #setInitialConfig(boolean, int, boolean)}, which is called by
376      * {@code ActivityManager} when the system is started.
377      *
378      * <p>It's useful to ignore external operations (i.e., originated outside {@code system_server},
379      * like from {@code adb shell am switch-user})) that could happen before such call is made and
380      * the system is ready.
381      */
382     @GuardedBy("mLock")
383     private boolean mInitialized;
384 
385     /**
386      * Defines the behavior of whether the background users should be stopped when the foreground
387      * user is switched.
388      */
389     @GuardedBy("mLock")
390     private @StopUserOnSwitch int mStopUserOnSwitch = STOP_USER_ON_SWITCH_DEFAULT;
391 
392     /** @see #getLastUserUnlockingUptime */
393     private volatile long mLastUserUnlockingUptime = 0;
394 
395     /**
396      * Pending user starts waiting for shutdown step to complete.
397      */
398     @GuardedBy("mLock")
399     private final List<PendingUserStart> mPendingUserStarts = new ArrayList<>();
400 
401     private final UserLifecycleListener mUserLifecycleListener = new UserLifecycleListener() {
402         @Override
403         public void onUserCreated(UserInfo user, Object token) {
404             onUserAdded(user);
405         }
406 
407         @Override
408         public void onUserRemoved(UserInfo user) {
409             UserController.this.onUserRemoved(user.id);
410         }
411     };
412 
UserController(ActivityManagerService service)413     UserController(ActivityManagerService service) {
414         this(new Injector(service));
415     }
416 
417     @VisibleForTesting
UserController(Injector injector)418     UserController(Injector injector) {
419         mInjector = injector;
420         // This should be called early to avoid a null mHandler inside the injector
421         mHandler = mInjector.getHandler(this);
422         mUiHandler = mInjector.getUiHandler(this);
423         // User 0 is the first and only user that runs at boot.
424         final UserState uss = new UserState(UserHandle.SYSTEM);
425         uss.mUnlockProgress.addListener(new UserProgressListener());
426         mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
427         mUserLru.add(UserHandle.USER_SYSTEM);
428         mLockPatternUtils = mInjector.getLockPatternUtils();
429         updateStartedUserArrayLU();
430     }
431 
setInitialConfig(boolean userSwitchUiEnabled, int maxRunningUsers, boolean delayUserDataLocking)432     void setInitialConfig(boolean userSwitchUiEnabled, int maxRunningUsers,
433             boolean delayUserDataLocking) {
434         synchronized (mLock) {
435             mUserSwitchUiEnabled = userSwitchUiEnabled;
436             mMaxRunningUsers = maxRunningUsers;
437             mDelayUserDataLocking = delayUserDataLocking;
438             mInitialized = true;
439         }
440     }
441 
isUserSwitchUiEnabled()442     private boolean isUserSwitchUiEnabled() {
443         synchronized (mLock) {
444             return mUserSwitchUiEnabled;
445         }
446     }
447 
getMaxRunningUsers()448     int getMaxRunningUsers() {
449         synchronized (mLock) {
450             return mMaxRunningUsers;
451         }
452     }
453 
setStopUserOnSwitch(@topUserOnSwitch int value)454     void setStopUserOnSwitch(@StopUserOnSwitch int value) {
455         if (mInjector.checkCallingPermission(android.Manifest.permission.MANAGE_USERS)
456                 == PackageManager.PERMISSION_DENIED && mInjector.checkCallingPermission(
457                 android.Manifest.permission.INTERACT_ACROSS_USERS)
458                 == PackageManager.PERMISSION_DENIED) {
459             throw new SecurityException(
460                     "You either need MANAGE_USERS or INTERACT_ACROSS_USERS permission to "
461                             + "call setStopUserOnSwitch()");
462         }
463 
464         synchronized (mLock) {
465             Slogf.i(TAG, "setStopUserOnSwitch(): %d -> %d", mStopUserOnSwitch, value);
466             mStopUserOnSwitch = value;
467         }
468     }
469 
shouldStopUserOnSwitch()470     private boolean shouldStopUserOnSwitch() {
471         synchronized (mLock) {
472             if (mStopUserOnSwitch != STOP_USER_ON_SWITCH_DEFAULT) {
473                 final boolean value = mStopUserOnSwitch == STOP_USER_ON_SWITCH_TRUE;
474                 Slogf.i(TAG, "shouldStopUserOnSwitch(): returning overridden value (%b)", value);
475                 return value;
476             }
477         }
478         final int property = SystemProperties.getInt("fw.stop_bg_users_on_switch", -1);
479         return property == -1 ? mDelayUserDataLocking : property == 1;
480     }
481 
finishUserSwitch(UserState uss)482     void finishUserSwitch(UserState uss) {
483         // This call holds the AM lock so we post to the handler.
484         mHandler.post(() -> {
485             finishUserBoot(uss);
486             startProfiles();
487             synchronized (mLock) {
488                 stopRunningUsersLU(mMaxRunningUsers);
489             }
490         });
491     }
492 
493     @GuardedBy("mLock")
494     @VisibleForTesting
getRunningUsersLU()495     List<Integer> getRunningUsersLU() {
496         ArrayList<Integer> runningUsers = new ArrayList<>();
497         for (Integer userId : mUserLru) {
498             UserState uss = mStartedUsers.get(userId);
499             if (uss == null) {
500                 // Shouldn't happen, but recover if it does.
501                 continue;
502             }
503             if (uss.state == UserState.STATE_STOPPING
504                     || uss.state == UserState.STATE_SHUTDOWN) {
505                 // This user is already stopping, doesn't count.
506                 continue;
507             }
508             runningUsers.add(userId);
509         }
510         return runningUsers;
511     }
512 
513     @GuardedBy("mLock")
stopRunningUsersLU(int maxRunningUsers)514     private void stopRunningUsersLU(int maxRunningUsers) {
515         List<Integer> currentlyRunning = getRunningUsersLU();
516         Iterator<Integer> iterator = currentlyRunning.iterator();
517         while (currentlyRunning.size() > maxRunningUsers && iterator.hasNext()) {
518             Integer userId = iterator.next();
519             if (userId == UserHandle.USER_SYSTEM || userId == mCurrentUserId) {
520                 // Owner/System user and current user can't be stopped
521                 continue;
522             }
523             // allowDelayedLocking set here as stopping user is done without any explicit request
524             // from outside.
525             if (stopUsersLU(userId, /* force= */ false, /* allowDelayedLocking= */ true,
526                     /* stopUserCallback= */ null, /* keyEvictedCallback= */ null)
527                     == USER_OP_SUCCESS) {
528                 iterator.remove();
529             }
530         }
531     }
532 
533     /**
534      * Returns if more users can be started without stopping currently running users.
535      */
canStartMoreUsers()536     boolean canStartMoreUsers() {
537         synchronized (mLock) {
538             return getRunningUsersLU().size() < mMaxRunningUsers;
539         }
540     }
541 
finishUserBoot(UserState uss)542     private void finishUserBoot(UserState uss) {
543         finishUserBoot(uss, null);
544     }
545 
finishUserBoot(UserState uss, IIntentReceiver resultTo)546     private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
547         final int userId = uss.mHandle.getIdentifier();
548         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_BOOT, userId);
549 
550         synchronized (mLock) {
551             // Bail if we ended up with a stale user
552             if (mStartedUsers.get(userId) != uss) {
553                 return;
554             }
555         }
556 
557         // We always walk through all the user lifecycle states to send
558         // consistent developer events. We step into RUNNING_LOCKED here,
559         // but we might immediately step into RUNNING below if the user
560         // storage is already unlocked.
561         if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
562             mInjector.getUserJourneyLogger()
563                     .logUserLifecycleEvent(userId, USER_LIFECYCLE_EVENT_USER_RUNNING_LOCKED,
564                     EVENT_STATE_NONE);
565             mInjector.getUserManagerInternal().setUserState(userId, uss.state);
566             // Do not report secondary users, runtime restarts or first boot/upgrade
567             if (userId == UserHandle.USER_SYSTEM
568                     && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
569                 final long elapsedTimeMs = SystemClock.elapsedRealtime();
570                 FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
571                         BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FRAMEWORK_LOCKED_BOOT_COMPLETED,
572                         elapsedTimeMs);
573                 final long maxElapsedTimeMs = 120_000;
574                 if (elapsedTimeMs > maxElapsedTimeMs) {
575                     Slogf.wtf("SystemServerTiming",
576                             "finishUserBoot took too long. elapsedTimeMs=" + elapsedTimeMs);
577                 }
578             }
579 
580             if (!mInjector.getUserManager().isPreCreated(userId)) {
581                 mHandler.sendMessage(mHandler.obtainMessage(REPORT_LOCKED_BOOT_COMPLETE_MSG,
582                         userId, 0));
583                 // The "locked boot complete" broadcast for the system user is supposed be sent when
584                 // the device has finished booting.  Normally, that is the same time that the system
585                 // user transitions to RUNNING_LOCKED.  However, in "headless system user mode", the
586                 // system user is explicitly started before the device has finished booting.  In
587                 // that case, we need to wait until onBootComplete() to send the broadcast.
588                 // Similarly, this occurs after a user switch, but in HSUM we switch to the main
589                 // user before boot is complete, so again this should be delayed until
590                 // onBootComplete if boot has not yet completed.
591                 if (mAllowUserUnlocking) {
592                     // ACTION_LOCKED_BOOT_COMPLETED
593                     sendLockedBootCompletedBroadcast(resultTo, userId);
594                 }
595             }
596         }
597 
598         // We need to delay unlocking managed profiles until the parent user
599         // is also unlocked.
600         if (mInjector.getUserManager().isProfile(userId)) {
601             final UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
602             if (parent != null
603                     && isUserRunning(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) {
604                 Slogf.d(TAG, "User " + userId + " (parent " + parent.id
605                         + "): attempting unlock because parent is unlocked");
606                 maybeUnlockUser(userId);
607             } else {
608                 String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id);
609                 Slogf.d(TAG, "User " + userId + " (parent " + parentId
610                         + "): delaying unlock because parent is locked");
611             }
612         } else {
613             maybeUnlockUser(userId);
614         }
615     }
616 
sendLockedBootCompletedBroadcast(IIntentReceiver receiver, @UserIdInt int userId)617     private void sendLockedBootCompletedBroadcast(IIntentReceiver receiver, @UserIdInt int userId) {
618         final Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
619         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
620         intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
621                 | Intent.FLAG_RECEIVER_OFFLOAD
622                 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
623         mInjector.broadcastIntent(intent, null, receiver, 0, null, null,
624                 new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
625                 AppOpsManager.OP_NONE,
626                 getTemporaryAppAllowlistBroadcastOptions(REASON_LOCKED_BOOT_COMPLETED)
627                         .toBundle(), true,
628                 false, MY_PID, SYSTEM_UID,
629                 Binder.getCallingUid(), Binder.getCallingPid(), userId);
630     }
631 
632     /**
633      * Step from {@link UserState#STATE_RUNNING_LOCKED} to
634      * {@link UserState#STATE_RUNNING_UNLOCKING}.
635      */
finishUserUnlocking(final UserState uss)636     private boolean finishUserUnlocking(final UserState uss) {
637         final int userId = uss.mHandle.getIdentifier();
638         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_UNLOCKING, userId);
639         mInjector.getUserJourneyLogger()
640                 .logUserLifecycleEvent(userId, USER_LIFECYCLE_EVENT_UNLOCKING_USER,
641                 EVENT_STATE_BEGIN);
642         // If the user key hasn't been unlocked yet, we cannot proceed.
643         if (!StorageManager.isUserKeyUnlocked(userId)) return false;
644         synchronized (mLock) {
645             // Do not proceed if unexpected state or a stale user
646             if (mStartedUsers.get(userId) != uss || uss.state != STATE_RUNNING_LOCKED) {
647                 return false;
648             }
649         }
650         uss.mUnlockProgress.start();
651 
652         // Prepare app storage before we go any further
653         uss.mUnlockProgress.setProgress(5,
654                     mInjector.getContext().getString(R.string.android_start_title));
655 
656         // Call onBeforeUnlockUser on a worker thread that allows disk I/O
657         FgThread.getHandler().post(() -> {
658             if (!StorageManager.isUserKeyUnlocked(userId)) {
659                 Slogf.w(TAG, "User key got locked unexpectedly, leaving user locked.");
660                 return;
661             }
662 
663             final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
664             t.traceBegin("UM.onBeforeUnlockUser-" + userId);
665             mInjector.getUserManager().onBeforeUnlockUser(userId);
666             t.traceEnd();
667             synchronized (mLock) {
668                 // Do not proceed if unexpected state
669                 if (!uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
670                     return;
671                 }
672             }
673             mInjector.getUserManagerInternal().setUserState(userId, uss.state);
674 
675             uss.mUnlockProgress.setProgress(20);
676 
677             mLastUserUnlockingUptime = SystemClock.uptimeMillis();
678 
679             // Dispatch unlocked to system services; when fully dispatched,
680             // that calls through to the next "unlocked" phase
681             mHandler.obtainMessage(USER_UNLOCK_MSG, userId, 0, uss).sendToTarget();
682         });
683         return true;
684     }
685 
686     /**
687      * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
688      * {@link UserState#STATE_RUNNING_UNLOCKED}.
689      */
finishUserUnlocked(final UserState uss)690     private void finishUserUnlocked(final UserState uss) {
691         final int userId = uss.mHandle.getIdentifier();
692         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_UNLOCKED, userId);
693         // Only keep marching forward if user is actually unlocked
694         if (!StorageManager.isUserKeyUnlocked(userId)) return;
695         synchronized (mLock) {
696             // Bail if we ended up with a stale user
697             if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
698 
699             // Do not proceed if unexpected state
700             if (!uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
701                 return;
702             }
703         }
704         mInjector.getUserManagerInternal().setUserState(userId, uss.state);
705         uss.mUnlockProgress.finish();
706 
707         // Get unaware persistent apps running and start any unaware providers
708         // in already-running apps that are partially aware
709         if (userId == UserHandle.USER_SYSTEM) {
710             mInjector.startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
711         }
712         mInjector.installEncryptionUnawareProviders(userId);
713 
714         if (!mInjector.getUserManager().isPreCreated(userId)) {
715             // Dispatch unlocked to external apps
716             final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
717             unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
718             unlockedIntent.addFlags(
719                     Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
720             mInjector.broadcastIntent(unlockedIntent, null, null, 0, null,
721                     null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
722                     Binder.getCallingUid(), Binder.getCallingPid(), userId);
723         }
724 
725         final UserInfo userInfo = getUserInfo(userId);
726         if (userInfo.isProfile()) {
727             UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
728             if (parent != null) {
729                 // Send PROFILE_ACCESSIBLE broadcast to the parent user if a profile was unlocked
730                 broadcastProfileAccessibleStateChanged(userId, parent.id,
731                         Intent.ACTION_PROFILE_ACCESSIBLE);
732 
733                 //TODO(b/175704931): send ACTION_MANAGED_PROFILE_AVAILABLE
734 
735                 // Also send MANAGED_PROFILE_UNLOCKED broadcast to the parent user
736                 // if a managed profile was unlocked
737                 if (userInfo.isManagedProfile()) {
738                     final Intent profileUnlockedIntent = new Intent(
739                             Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
740                     profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
741                     profileUnlockedIntent.addFlags(
742                             Intent.FLAG_RECEIVER_REGISTERED_ONLY
743                                     | Intent.FLAG_RECEIVER_FOREGROUND);
744                     mInjector.broadcastIntent(profileUnlockedIntent,
745                             null, null, 0, null, null, null, AppOpsManager.OP_NONE,
746                             null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
747                             Binder.getCallingPid(), parent.id);
748                 }
749             }
750         }
751 
752         // Send PRE_BOOT broadcasts if user fingerprint changed; we
753         // purposefully block sending BOOT_COMPLETED until after all
754         // PRE_BOOT receivers are finished to avoid ANR'ing apps
755         final UserInfo info = getUserInfo(userId);
756         if (!Objects.equals(info.lastLoggedInFingerprint, PackagePartitions.FINGERPRINT)
757                 || SystemProperties.getBoolean("persist.pm.mock-upgrade", false)) {
758             // Suppress double notifications for managed profiles that
759             // were unlocked automatically as part of their parent user being
760             // unlocked.  TODO(b/217442918): this code doesn't work correctly.
761             final boolean quiet = info.isManagedProfile();
762             mInjector.sendPreBootBroadcast(userId, quiet,
763                     () -> finishUserUnlockedCompleted(uss));
764         } else {
765             finishUserUnlockedCompleted(uss);
766         }
767     }
768 
finishUserUnlockedCompleted(UserState uss)769     private void finishUserUnlockedCompleted(UserState uss) {
770         final int userId = uss.mHandle.getIdentifier();
771         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_UNLOCKED_COMPLETED, userId);
772         synchronized (mLock) {
773             // Bail if we ended up with a stale user
774             if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
775         }
776         UserInfo userInfo = getUserInfo(userId);
777         if (userInfo == null) {
778             return;
779         }
780         // Only keep marching forward if user is actually unlocked
781         if (!StorageManager.isUserKeyUnlocked(userId)) return;
782 
783         // Remember that we logged in
784         mInjector.getUserManager().onUserLoggedIn(userId);
785 
786         Runnable initializeUser = () -> mInjector.getUserManager().makeInitialized(userInfo.id);
787         if (!userInfo.isInitialized()) {
788             Slogf.d(TAG, "Initializing user #" + userId);
789             if (userInfo.preCreated) {
790                 initializeUser.run();
791             } else if (userId != UserHandle.USER_SYSTEM) {
792                 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
793                 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
794                         | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
795                 mInjector.broadcastIntent(intent, null,
796                         new IIntentReceiver.Stub() {
797                             @Override
798                             public void performReceive(Intent intent, int resultCode,
799                                     String data, Bundle extras, boolean ordered,
800                                     boolean sticky, int sendingUser) {
801                                 // Note: performReceive is called with mService lock held
802                                 initializeUser.run();
803                             }
804                         }, 0, null, null, null, AppOpsManager.OP_NONE,
805                         null, true, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
806                         Binder.getCallingPid(), userId);
807             }
808         }
809 
810         if (userInfo.preCreated) {
811             Slogf.i(TAG, "Stopping pre-created user " + userInfo.toFullString());
812             // Pre-created user was started right after creation so services could properly
813             // intialize it; it should be stopped right away as it's not really a "real" user.
814             stopUser(userInfo.id, /* force= */ true, /* allowDelayedLocking= */ false,
815                     /* stopUserCallback= */ null, /* keyEvictedCallback= */ null);
816             return;
817         }
818 
819         // Spin up app widgets prior to boot-complete, so they can be ready promptly
820         mInjector.startUserWidgets(userId);
821 
822         mHandler.obtainMessage(USER_UNLOCKED_MSG, userId, 0).sendToTarget();
823 
824         Slogf.i(TAG, "Posting BOOT_COMPLETED user #" + userId);
825         // Do not report secondary users, runtime restarts or first boot/upgrade
826         if (userId == UserHandle.USER_SYSTEM
827                 && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
828             final long elapsedTimeMs = SystemClock.elapsedRealtime();
829             FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
830                     FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FRAMEWORK_BOOT_COMPLETED,
831                     elapsedTimeMs);
832         }
833         final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
834         bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
835         bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
836                 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
837                 | Intent.FLAG_RECEIVER_OFFLOAD);
838         // Widget broadcasts are outbound via FgThread, so to guarantee sequencing
839         // we also send the boot_completed broadcast from that thread.
840         final int callingUid = Binder.getCallingUid();
841         final int callingPid = Binder.getCallingPid();
842         FgThread.getHandler().post(() -> {
843             mInjector.broadcastIntent(bootIntent, null,
844                     new IIntentReceiver.Stub() {
845                         @Override
846                         public void performReceive(Intent intent, int resultCode, String data,
847                                 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
848                                         throws RemoteException {
849                             Slogf.i(UserController.TAG, "Finished processing BOOT_COMPLETED for u"
850                                     + userId);
851                             mBootCompleted = true;
852                         }
853                     }, 0, null, null,
854                     new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
855                     AppOpsManager.OP_NONE,
856                     getTemporaryAppAllowlistBroadcastOptions(REASON_BOOT_COMPLETED).toBundle(),
857                     true, false, MY_PID, SYSTEM_UID, callingUid, callingPid, userId);
858         });
859     }
860 
restartUser(final int userId, @UserStartMode int userStartMode)861     int restartUser(final int userId, @UserStartMode int userStartMode) {
862         return stopUser(userId, /* force= */ true, /* allowDelayedLocking= */ false,
863                 /* stopUserCallback= */ null, new KeyEvictedCallback() {
864                     @Override
865                     public void keyEvicted(@UserIdInt int userId) {
866                         // Post to the same handler that this callback is called from to ensure
867                         // the user cleanup is complete before restarting.
868                         mHandler.post(() -> UserController.this.startUser(userId, userStartMode));
869                     }
870                 });
871     }
872 
873     /**
874      * Stops a user only if it's a profile, with a more relaxed permission requirement:
875      * {@link android.Manifest.permission#MANAGE_USERS} or
876      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}.
877      * To be called from ActivityManagerService.
878      * @param userId the id of the user to stop.
879      * @return true if the operation was successful.
880      */
881     boolean stopProfile(final @UserIdInt int userId) {
882         if (mInjector.checkCallingPermission(android.Manifest.permission.MANAGE_USERS)
883                 == PackageManager.PERMISSION_DENIED && mInjector.checkCallingPermission(
884                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
885                 == PackageManager.PERMISSION_DENIED) {
886             throw new SecurityException(
887                     "You either need MANAGE_USERS or INTERACT_ACROSS_USERS_FULL permission to "
888                             + "stop a profile");
889         }
890 
891         final UserInfo userInfo = getUserInfo(userId);
892         if (userInfo == null || !userInfo.isProfile()) {
893             throw new IllegalArgumentException("User " + userId + " is not a profile");
894         }
895 
896         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId);
897         synchronized (mLock) {
898             return stopUsersLU(userId, /* force= */ true, /* allowDelayedLocking= */
899                     false, /* stopUserCallback= */ null, /* keyEvictedCallback= */ null)
900                     == ActivityManager.USER_OP_SUCCESS;
901         }
902     }
903 
904     int stopUser(final int userId, final boolean force, boolean allowDelayedLocking,
905             final IStopUserCallback stopUserCallback, KeyEvictedCallback keyEvictedCallback) {
906         checkCallingPermission(INTERACT_ACROSS_USERS_FULL, "stopUser");
907         Preconditions.checkArgument(userId >= 0, "Invalid user id %d", userId);
908 
909         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId);
910         synchronized (mLock) {
911             return stopUsersLU(userId, force, allowDelayedLocking, stopUserCallback,
912                     keyEvictedCallback);
913         }
914     }
915 
916     /**
917      * Stops the user along with its related users. The method calls
918      * {@link #getUsersToStopLU(int)} to determine the list of users that should be stopped.
919      */
920     @GuardedBy("mLock")
921     private int stopUsersLU(final int userId, boolean force, boolean allowDelayedLocking,
922             final IStopUserCallback stopUserCallback, KeyEvictedCallback keyEvictedCallback) {
923         if (userId == UserHandle.USER_SYSTEM) {
924             return USER_OP_ERROR_IS_SYSTEM;
925         }
926         if (isCurrentUserLU(userId)) {
927             return USER_OP_IS_CURRENT;
928         }
929         int[] usersToStop = getUsersToStopLU(userId);
930         // If one of related users is system or current, no related users should be stopped
931         for (int i = 0; i < usersToStop.length; i++) {
932             int relatedUserId = usersToStop[i];
933             if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLU(relatedUserId)) {
934                 if (DEBUG_MU) {
935                     Slogf.i(TAG, "stopUsersLocked cannot stop related user " + relatedUserId);
936                 }
937                 // We still need to stop the requested user if it's a force stop.
938                 if (force) {
939                     Slogf.i(TAG,
940                             "Force stop user " + userId + ". Related users will not be stopped");
941                     stopSingleUserLU(userId, allowDelayedLocking, stopUserCallback,
942                             keyEvictedCallback);
943                     return USER_OP_SUCCESS;
944                 }
945                 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
946             }
947         }
948         if (DEBUG_MU) Slogf.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
949         for (int userIdToStop : usersToStop) {
950             stopSingleUserLU(userIdToStop, allowDelayedLocking,
951                     userIdToStop == userId ? stopUserCallback : null,
952                     userIdToStop == userId ? keyEvictedCallback : null);
953         }
954         return USER_OP_SUCCESS;
955     }
956 
957     /**
958      * Stops a single User. This can also trigger locking user data out depending on device's
959      * config ({@code mDelayUserDataLocking}) and arguments.
960      * User will be unlocked when
961      * - {@code mDelayUserDataLocking} is not set.
962      * - {@code mDelayUserDataLocking} is set and {@code keyEvictedCallback} is non-null.
963      * -
964      *
965      * @param userId User Id to stop and lock the data.
966      * @param allowDelayedLocking When set, do not lock user after stopping. Locking can happen
967      *                            later when number of unlocked users reaches
968      *                            {@code mMaxRunnngUsers}. Note that this is respected only when
969      *                            {@code mDelayUserDataLocking} is set and {@keyEvictedCallback} is
970      *                            null. Otherwise the user will be locked.
971      * @param stopUserCallback Callback to notify that user has stopped.
972      * @param keyEvictedCallback Callback to notify that user has been unlocked.
973      */
974     @GuardedBy("mLock")
975     private void stopSingleUserLU(final int userId, boolean allowDelayedLocking,
976             final IStopUserCallback stopUserCallback,
977             KeyEvictedCallback keyEvictedCallback) {
978         Slogf.i(TAG, "stopSingleUserLU userId=" + userId);
979         final UserState uss = mStartedUsers.get(userId);
980         if (uss == null) {  // User is not started
981             // If mDelayUserDataLocking is set and allowDelayedLocking is not set, we need to lock
982             // the requested user as the client wants to stop and lock the user. On the other hand,
983             // having keyEvictedCallback set will lead into locking user if mDelayUserDataLocking
984             // is set as that means client wants to lock the user immediately.
985             // If mDelayUserDataLocking is not set, the user was already locked when it was stopped
986             // and no further action is necessary.
987             if (mDelayUserDataLocking) {
988                 if (allowDelayedLocking && keyEvictedCallback != null) {
989                     Slogf.wtf(TAG, "allowDelayedLocking set with KeyEvictedCallback, ignore it"
990                             + " and lock user:" + userId, new RuntimeException());
991                     allowDelayedLocking = false;
992                 }
993                 if (!allowDelayedLocking) {
994                     if (mLastActiveUsers.remove(Integer.valueOf(userId))) {
995                         // should lock the user, user is already gone
996                         final ArrayList<KeyEvictedCallback> keyEvictedCallbacks;
997                         if (keyEvictedCallback != null) {
998                             keyEvictedCallbacks = new ArrayList<>(1);
999                             keyEvictedCallbacks.add(keyEvictedCallback);
1000                         } else {
1001                             keyEvictedCallbacks = null;
1002                         }
1003                         dispatchUserLocking(userId, keyEvictedCallbacks);
1004                     }
1005                 }
1006             }
1007             // We do need to post the stopped callback even though user is already stopped.
1008             if (stopUserCallback != null) {
1009                 mHandler.post(() -> {
1010                     try {
1011                         stopUserCallback.userStopped(userId);
1012                     } catch (RemoteException e) {
1013                     }
1014                 });
1015             }
1016             return;
1017         }
1018 
1019         logUserJourneyBegin(userId, USER_JOURNEY_USER_STOP);
1020 
1021         if (stopUserCallback != null) {
1022             uss.mStopCallbacks.add(stopUserCallback);
1023         }
1024         if (keyEvictedCallback != null) {
1025             uss.mKeyEvictedCallbacks.add(keyEvictedCallback);
1026         }
1027 
1028         if (uss.state != UserState.STATE_STOPPING
1029                 && uss.state != UserState.STATE_SHUTDOWN) {
1030             uss.setState(UserState.STATE_STOPPING);
1031             UserManagerInternal userManagerInternal = mInjector.getUserManagerInternal();
1032             userManagerInternal.setUserState(userId, uss.state);
1033             userManagerInternal.unassignUserFromDisplayOnStop(userId);
1034 
1035             updateStartedUserArrayLU();
1036 
1037             final boolean allowDelayedLockingCopied = allowDelayedLocking;
1038             Runnable finishUserStoppingAsync = () ->
1039                     mHandler.post(() -> finishUserStopping(userId, uss, allowDelayedLockingCopied));
1040 
1041             if (mInjector.getUserManager().isPreCreated(userId)) {
1042                 finishUserStoppingAsync.run();
1043                 return;
1044             }
1045 
1046             // Post to handler to obtain amLock
1047             mHandler.post(() -> {
1048                 // We are going to broadcast ACTION_USER_STOPPING and then
1049                 // once that is done send a final ACTION_SHUTDOWN and then
1050                 // stop the user.
1051                 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
1052                 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1053                 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1054                 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
1055                 // This is the result receiver for the initial stopping broadcast.
1056                 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
1057                     @Override
1058                     public void performReceive(Intent intent, int resultCode, String data,
1059                             Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
1060                         finishUserStoppingAsync.run();
1061                     }
1062                 };
1063 
1064                 // Clear broadcast queue for the user to avoid delivering stale broadcasts
1065                 mInjector.clearBroadcastQueueForUser(userId);
1066                 // Kick things off.
1067                 mInjector.broadcastIntent(stoppingIntent,
1068                         null, stoppingReceiver, 0, null, null,
1069                         new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
1070                         null, true, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
1071                         Binder.getCallingPid(), UserHandle.USER_ALL);
1072             });
1073         }
1074     }
1075 
1076     private void finishUserStopping(final int userId, final UserState uss,
1077             final boolean allowDelayedLocking) {
1078         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_STOPPING, userId);
1079         synchronized (mLock) {
1080             if (uss.state != UserState.STATE_STOPPING) {
1081                 // Whoops, we are being started back up.  Abort, abort!
1082                 UserJourneySession session = mInjector.getUserJourneyLogger()
1083                         .logUserJourneyFinishWithError(-1, getUserInfo(userId),
1084                                 USER_JOURNEY_USER_STOP, ERROR_CODE_ABORTED);
1085                 if (session != null) {
1086                     mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, session);
1087                 } else {
1088                     mInjector.getUserJourneyLogger()
1089                             .logUserJourneyFinishWithError(-1, getUserInfo(userId),
1090                                     USER_JOURNEY_USER_STOP, ERROR_CODE_INVALID_SESSION_ID);
1091                 }
1092                 return;
1093             }
1094             uss.setState(UserState.STATE_SHUTDOWN);
1095         }
1096         mInjector.getUserManagerInternal().setUserState(userId, uss.state);
1097 
1098         mInjector.batteryStatsServiceNoteEvent(
1099                 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
1100                 Integer.toString(userId), userId);
1101         mInjector.getSystemServiceManager().onUserStopping(userId);
1102 
1103         Runnable finishUserStoppedAsync = () ->
1104                 mHandler.post(() -> finishUserStopped(uss, allowDelayedLocking));
1105         if (mInjector.getUserManager().isPreCreated(userId)) {
1106             finishUserStoppedAsync.run();
1107             return;
1108         }
1109 
1110         // Fire the shutdown intent.
1111         final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
1112         // This is the result receiver for the final shutdown broadcast.
1113         final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
1114             @Override
1115             public void performReceive(Intent intent, int resultCode, String data,
1116                     Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
1117                 finishUserStoppedAsync.run();
1118             }
1119         };
1120         mInjector.broadcastIntent(shutdownIntent,
1121                 null, shutdownReceiver, 0, null, null, null,
1122                 AppOpsManager.OP_NONE,
1123                 null, true, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
1124                 Binder.getCallingPid(), userId);
1125     }
1126 
1127     @VisibleForTesting
1128     void finishUserStopped(UserState uss, boolean allowDelayedLocking) {
1129         final int userId = uss.mHandle.getIdentifier();
1130         if (DEBUG_MU) {
1131             Slogf.i(TAG, "finishUserStopped(%d): allowDelayedLocking=%b", userId,
1132                     allowDelayedLocking);
1133         }
1134 
1135         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_STOPPED, userId);
1136         final boolean stopped;
1137         boolean lockUser = true;
1138         final ArrayList<IStopUserCallback> stopCallbacks;
1139         final ArrayList<KeyEvictedCallback> keyEvictedCallbacks;
1140         int userIdToLock = userId;
1141         // Must get a reference to UserInfo before it's removed
1142         final UserInfo userInfo = getUserInfo(userId);
1143         synchronized (mLock) {
1144             stopCallbacks = new ArrayList<>(uss.mStopCallbacks);
1145             keyEvictedCallbacks = new ArrayList<>(uss.mKeyEvictedCallbacks);
1146             if (mStartedUsers.get(userId) != uss || uss.state != UserState.STATE_SHUTDOWN) {
1147                 stopped = false;
1148             } else {
1149                 stopped = true;
1150                 // User can no longer run.
1151                 Slogf.i(TAG, "Removing user state from UserController.mStartedUsers for user #"
1152                         + userId + " as a result of user being stopped");
1153                 mStartedUsers.remove(userId);
1154 
1155                 mUserLru.remove(Integer.valueOf(userId));
1156                 updateStartedUserArrayLU();
1157 
1158                 if (allowDelayedLocking && !keyEvictedCallbacks.isEmpty()) {
1159                     Slogf.wtf(TAG,
1160                             "Delayed locking enabled while KeyEvictedCallbacks not empty, userId:"
1161                                     + userId + " callbacks:" + keyEvictedCallbacks);
1162                     allowDelayedLocking = false;
1163                 }
1164                 userIdToLock = updateUserToLockLU(userId, allowDelayedLocking);
1165                 if (userIdToLock == UserHandle.USER_NULL) {
1166                     lockUser = false;
1167                 }
1168             }
1169         }
1170         if (stopped) {
1171             Slogf.i(TAG, "Removing user state from UserManager.mUserStates for user #" + userId
1172                     + " as a result of user being stopped");
1173             mInjector.getUserManagerInternal().removeUserState(userId);
1174 
1175             mInjector.activityManagerOnUserStopped(userId);
1176             // Clean up all state and processes associated with the user.
1177             // Kill all the processes for the user.
1178             forceStopUser(userId, "finish user");
1179         }
1180 
1181         for (final IStopUserCallback callback : stopCallbacks) {
1182             try {
1183                 if (stopped) callback.userStopped(userId);
1184                 else callback.userStopAborted(userId);
1185             } catch (RemoteException ignored) {
1186             }
1187         }
1188 
1189         if (stopped) {
1190             mInjector.systemServiceManagerOnUserStopped(userId);
1191             mInjector.taskSupervisorRemoveUser(userId);
1192 
1193             // Remove the user if it is ephemeral.
1194             if (userInfo.isEphemeral() && !userInfo.preCreated) {
1195                 mInjector.getUserManager().removeUserEvenWhenDisallowed(userId);
1196             }
1197 
1198             UserJourneySession session = mInjector.getUserJourneyLogger()
1199                     .logUserJourneyFinish(-1, userInfo, USER_JOURNEY_USER_STOP);
1200             if (session != null) {
1201                 mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, session);
1202             }
1203 
1204             if (lockUser) {
1205                 dispatchUserLocking(userIdToLock, keyEvictedCallbacks);
1206             }
1207 
1208             // Resume any existing pending user start,
1209             // which was paused while the SHUTDOWN flow of the user was in progress.
1210             resumePendingUserStarts(userId);
1211         } else {
1212             UserJourneySession session = mInjector.getUserJourneyLogger()
1213                     .finishAndClearIncompleteUserJourney(userId, USER_JOURNEY_USER_STOP);
1214             if (session != null) {
1215                 mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, session);
1216             }
1217         }
1218     }
1219 
1220     /**
1221      * Resume any existing pending user start for the specified userId which was paused
1222      * while the shutdown flow of the user was in progress.
1223      * Remove all the handled user starts from mPendingUserStarts.
1224      * @param userId the id of the user
1225      */
1226     private void resumePendingUserStarts(@UserIdInt int userId) {
1227         synchronized (mLock) {
1228             final List<PendingUserStart> handledUserStarts = new ArrayList<>();
1229 
1230             for (PendingUserStart userStart: mPendingUserStarts) {
1231                 if (userStart.userId == userId) {
1232                     Slogf.i(TAG, "resumePendingUserStart for" + userStart);
1233                     mHandler.post(() -> startUser(userStart.userId,
1234                             userStart.userStartMode, userStart.unlockListener));
1235 
1236                     handledUserStarts.add(userStart);
1237                 }
1238             }
1239             // remove all the pending user starts which are now handled
1240             mPendingUserStarts.removeAll(handledUserStarts);
1241         }
1242     }
1243 
1244 
1245     private void dispatchUserLocking(@UserIdInt int userId,
1246             @Nullable List<KeyEvictedCallback> keyEvictedCallbacks) {
1247         // Evict the user's credential encryption key. Performed on FgThread to make it
1248         // serialized with call to UserManagerService.onBeforeUnlockUser in finishUserUnlocking
1249         // to prevent data corruption.
1250         FgThread.getHandler().post(() -> {
1251             synchronized (mLock) {
1252                 if (mStartedUsers.get(userId) != null) {
1253                     Slogf.w(TAG, "User was restarted, skipping key eviction");
1254                     return;
1255                 }
1256             }
1257             try {
1258                 Slogf.i(TAG, "Locking CE storage for user #" + userId);
1259                 mInjector.getStorageManager().lockUserKey(userId);
1260             } catch (RemoteException re) {
1261                 throw re.rethrowAsRuntimeException();
1262             }
1263             if (keyEvictedCallbacks == null) {
1264                 return;
1265             }
1266             for (int i = 0; i < keyEvictedCallbacks.size(); i++) {
1267                 keyEvictedCallbacks.get(i).keyEvicted(userId);
1268             }
1269         });
1270     }
1271 
1272     /**
1273      * For mDelayUserDataLocking mode, storage once unlocked is kept unlocked.
1274      * Total number of unlocked user storage is limited by mMaxRunningUsers.
1275      * If there are more unlocked users, evict and lock the least recently stopped user and
1276      * lock that user's data. Regardless of the mode, ephemeral user is always locked
1277      * immediately.
1278      *
1279      * @return user id to lock. UserHandler.USER_NULL will be returned if no user should be locked.
1280      */
1281     @GuardedBy("mLock")
1282     private int updateUserToLockLU(@UserIdInt int userId, boolean allowDelayedLocking) {
1283         int userIdToLock = userId;
1284         if (mDelayUserDataLocking && allowDelayedLocking && !getUserInfo(userId).isEphemeral()
1285                 && !hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND, userId)) {
1286             mLastActiveUsers.remove((Integer) userId); // arg should be object, not index
1287             mLastActiveUsers.add(0, userId);
1288             int totalUnlockedUsers = mStartedUsers.size() + mLastActiveUsers.size();
1289             if (totalUnlockedUsers > mMaxRunningUsers) { // should lock a user
1290                 userIdToLock = mLastActiveUsers.get(mLastActiveUsers.size() - 1);
1291                 mLastActiveUsers.remove(mLastActiveUsers.size() - 1);
1292                 Slogf.i(TAG, "finishUserStopped, stopping user:" + userId
1293                         + " lock user:" + userIdToLock);
1294             } else {
1295                 Slogf.i(TAG, "finishUserStopped, user:" + userId + ", skip locking");
1296                 // do not lock
1297                 userIdToLock = UserHandle.USER_NULL;
1298             }
1299         }
1300         return userIdToLock;
1301     }
1302 
1303     /**
1304      * Determines the list of users that should be stopped together with the specified
1305      * {@code userId}. The returned list includes {@code userId}.
1306      */
1307     @GuardedBy("mLock")
1308     private @NonNull int[] getUsersToStopLU(@UserIdInt int userId) {
1309         int startedUsersSize = mStartedUsers.size();
1310         IntArray userIds = new IntArray();
1311         userIds.add(userId);
1312         int userGroupId = mUserProfileGroupIds.get(userId, UserInfo.NO_PROFILE_GROUP_ID);
1313         for (int i = 0; i < startedUsersSize; i++) {
1314             UserState uss = mStartedUsers.valueAt(i);
1315             int startedUserId = uss.mHandle.getIdentifier();
1316             // Skip unrelated users (profileGroupId mismatch)
1317             int startedUserGroupId = mUserProfileGroupIds.get(startedUserId,
1318                     UserInfo.NO_PROFILE_GROUP_ID);
1319             boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
1320                     && (userGroupId == startedUserGroupId);
1321             // userId has already been added
1322             boolean sameUserId = startedUserId == userId;
1323             if (!sameGroup || sameUserId) {
1324                 continue;
1325             }
1326             userIds.add(startedUserId);
1327         }
1328         return userIds.toArray();
1329     }
1330 
1331     private void forceStopUser(@UserIdInt int userId, String reason) {
1332         if (DEBUG_MU) Slogf.i(TAG, "forceStopUser(%d): %s", userId, reason);
1333         mInjector.activityManagerForceStopPackage(userId, reason);
1334         if (mInjector.getUserManager().isPreCreated(userId)) {
1335             // Don't fire intent for precreated.
1336             return;
1337         }
1338         Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
1339         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1340                 | Intent.FLAG_RECEIVER_FOREGROUND);
1341         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1342         mInjector.broadcastIntent(intent,
1343                 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1344                 null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
1345                 Binder.getCallingPid(), UserHandle.USER_ALL);
1346 
1347         // Send PROFILE_INACCESSIBLE broadcast if a profile was stopped
1348         final UserInfo userInfo = getUserInfo(userId);
1349         if (userInfo.isProfile()) {
1350             UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
1351             if (parent != null) {
1352                 broadcastProfileAccessibleStateChanged(userId, parent.id,
1353                         Intent.ACTION_PROFILE_INACCESSIBLE);
1354                 //TODO(b/175704931): send ACTION_MANAGED_PROFILE_UNAVAILABLE
1355             }
1356         }
1357     }
1358 
1359     /**
1360      * Stops the guest or ephemeral user if it has gone to the background.
1361      */
1362     private void stopGuestOrEphemeralUserIfBackground(int oldUserId) {
1363         if (DEBUG_MU) Slogf.i(TAG, "Stop guest or ephemeral user if background: " + oldUserId);
1364         synchronized(mLock) {
1365             UserState oldUss = mStartedUsers.get(oldUserId);
1366             if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId || oldUss == null
1367                     || oldUss.state == UserState.STATE_STOPPING
1368                     || oldUss.state == UserState.STATE_SHUTDOWN) {
1369                 return;
1370             }
1371         }
1372 
1373         UserInfo userInfo = getUserInfo(oldUserId);
1374         if (userInfo.isEphemeral()) {
1375             LocalServices.getService(UserManagerInternal.class).onEphemeralUserStop(oldUserId);
1376         }
1377         if (userInfo.isGuest() || userInfo.isEphemeral()) {
1378             // This is a user to be stopped.
1379             synchronized (mLock) {
1380                 stopUsersLU(oldUserId, /* force= */ true, /* allowDelayedLocking= */ false,
1381                         null, null);
1382             }
1383         }
1384     }
1385 
1386     void scheduleStartProfiles() {
1387         // Parent user transition to RUNNING_UNLOCKING happens on FgThread, so it is busy, there is
1388         // a chance the profile will reach RUNNING_LOCKED while parent is still locked, so no
1389         // attempt will be made to unlock the profile. If we go via FgThread, this will be executed
1390         // after the parent had chance to unlock fully.
1391         FgThread.getHandler().post(() -> {
1392             if (!mHandler.hasMessages(START_PROFILES_MSG)) {
1393                 mHandler.sendMessageDelayed(mHandler.obtainMessage(START_PROFILES_MSG),
1394                         DateUtils.SECOND_IN_MILLIS);
1395             }
1396         });
1397     }
1398 
1399     private void startProfiles() {
1400         int currentUserId = getCurrentUserId();
1401         if (DEBUG_MU) Slogf.i(TAG, "startProfilesLocked");
1402         List<UserInfo> profiles = mInjector.getUserManager().getProfiles(
1403                 currentUserId, false /* enabledOnly */);
1404         List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
1405         for (UserInfo user : profiles) {
1406             if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
1407                     && user.id != currentUserId
1408                     && shouldStartWithParent(user)) {
1409                 profilesToStart.add(user);
1410             }
1411         }
1412         final int profilesToStartSize = profilesToStart.size();
1413         int i = 0;
1414         for (; i < profilesToStartSize && i < (getMaxRunningUsers() - 1); ++i) {
1415             // NOTE: this method is setting the profiles of the current user - which is always
1416             // assigned to the default display
1417             startUser(profilesToStart.get(i).id, USER_START_MODE_BACKGROUND_VISIBLE);
1418         }
1419         if (i < profilesToStartSize) {
1420             Slogf.w(TAG, "More profiles than MAX_RUNNING_USERS");
1421         }
1422     }
1423 
1424     private boolean shouldStartWithParent(UserInfo user) {
1425         final UserProperties properties = getUserProperties(user.id);
1426         DevicePolicyManagerInternal dpmi =
1427                 LocalServices.getService(DevicePolicyManagerInternal.class);
1428         return (properties != null && properties.getStartWithParent())
1429                 && (!user.isQuietModeEnabled() || dpmi.isKeepProfilesRunningEnabled());
1430     }
1431 
1432     /**
1433      * Starts a {@link UserManager#isProfile() profile user}.
1434      *
1435      * <p>To be called from {@link com.android.server.am.ActivityManagerService}.
1436      *
1437      * @param userId the id of the profile user to start.
1438      * @param evenWhenDisabled whether the profile should be started if it's not enabled yet
1439      *        (most callers should pass {@code false}, except when starting the profile while it's
1440      *        being provisioned).
1441      * @param unlockListener listener to be informed when the profile has started and unlocked.
1442      *
1443      * @return {@code true} if the operation was successful.
1444      *
1445      * @throws IllegalArgumentException if the user doesn't exist or is not a profile.
1446      */
1447     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
1448             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL})
1449     boolean startProfile(@UserIdInt int userId, boolean evenWhenDisabled,
1450             @Nullable IProgressListener unlockListener) {
1451         if (mInjector.checkCallingPermission(android.Manifest.permission.MANAGE_USERS)
1452                 == PackageManager.PERMISSION_DENIED && mInjector.checkCallingPermission(
1453                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1454                 == PackageManager.PERMISSION_DENIED) {
1455             throw new SecurityException(
1456                     "You either need MANAGE_USERS or INTERACT_ACROSS_USERS_FULL permission to "
1457                             + "start a profile");
1458         }
1459 
1460         final UserInfo userInfo = getUserInfo(userId);
1461         if (userInfo == null || !userInfo.isProfile()) {
1462             throw new IllegalArgumentException("User " + userId + " is not a profile");
1463         }
1464 
1465         if (!userInfo.isEnabled() && !evenWhenDisabled) {
1466             Slogf.w(TAG, "Cannot start disabled profile #%d", userId);
1467             return false;
1468         }
1469 
1470         return startUserNoChecks(userId, Display.DEFAULT_DISPLAY,
1471                 USER_START_MODE_BACKGROUND_VISIBLE, unlockListener);
1472     }
1473 
1474     @VisibleForTesting
1475     boolean startUser(@UserIdInt int userId, @UserStartMode int userStartMode) {
1476         return startUser(userId, userStartMode, /* unlockListener= */ null);
1477     }
1478 
1479     /**
1480      * Start user, if its not already running.
1481      *
1482      * <p>The user will be brought to the foreground, if {@code userStartMode} parameter is
1483      * set to {@link UserManagerInternal#USER_START_MODE_FOREGROUND}
1484      * When starting the user, multiple intents will be broadcast in the following order:</p>
1485      * <ul>
1486      *     <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user
1487      *     <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing
1488      *     user and all profiles of this user. Sent only if {@code foreground} parameter is
1489      *     {@code false}
1490      *     <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new
1491      *     user and all profiles of this user. Sent only if {@code foreground} parameter is
1492      *     {@code true}
1493      *     <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user.
1494      *     Sent only if {@code foreground} parameter is {@code true}
1495      *     <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers
1496      *     of the new fg user
1497      *     <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of
1498      *     the new user
1499      *     <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user
1500      *     <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the
1501      *     new user. Sent only when the user is booting after a system update.
1502      *     <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the
1503      *     new user. Sent only the first time a user is starting.
1504      *     <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new
1505      *     user. Indicates that the user has finished booting.
1506      * </ul>
1507      *
1508      * @param userId ID of the user to start
1509      * @param userStartMode user starting mode
1510      * @param unlockListener Listener to be informed when the user has started and unlocked.
1511      * @return true if the user has been successfully started
1512      */
1513     boolean startUser(@UserIdInt int userId, @UserStartMode int userStartMode,
1514             @Nullable IProgressListener unlockListener) {
1515         checkCallingPermission(INTERACT_ACROSS_USERS_FULL, "startUser");
1516 
1517         return startUserNoChecks(userId, Display.DEFAULT_DISPLAY, userStartMode, unlockListener);
1518     }
1519 
1520     /**
1521      * Starts a user in background and make it visible in the given display.
1522      *
1523      * <p>This call will trigger the usual "user started" lifecycle events (i.e., `SystemService`
1524      * callbacks and app intents), plus a call to
1525      * {@link UserManagerInternal.UserVisibilityListener#onUserVisibilityChanged(int, boolean)} if
1526      * the user visibility changed. Notice that the visibility change is independent of the user
1527      * workflow state, and they can mismatch in some corner events (for example, if the user was
1528      * already running in the background but not associated with a display, this call for that user
1529      * would not trigger any lifecycle event but would trigger {@code onUserVisibilityChanged}).
1530      *
1531      * <p>See {@link ActivityManager#startUserInBackgroundOnSecondaryDisplay(int, int)} for more
1532      * semantics.
1533      *
1534      * @param userId user to be started
1535      * @param displayId display where the user will be visible
1536      * @param unlockListener Listener to be informed when the user has started and unlocked.
1537      *
1538      * @return whether the user was started
1539      */
1540     boolean startUserVisibleOnDisplay(@UserIdInt int userId, int displayId,
1541             @Nullable IProgressListener unlockListener) {
1542         checkCallingHasOneOfThosePermissions("startUserOnDisplay",
1543                 MANAGE_USERS, INTERACT_ACROSS_USERS);
1544 
1545         try {
1546             return startUserNoChecks(userId, displayId, USER_START_MODE_BACKGROUND_VISIBLE,
1547                     unlockListener);
1548         } catch (RuntimeException e) {
1549             Slogf.e(TAG, "startUserOnSecondaryDisplay(%d, %d) failed: %s", userId, displayId, e);
1550             return false;
1551         }
1552     }
1553 
1554     private boolean startUserNoChecks(@UserIdInt int userId, int displayId,
1555             @UserStartMode int userStartMode, @Nullable IProgressListener unlockListener) {
1556         TimingsTraceAndSlog t = new TimingsTraceAndSlog();
1557 
1558         t.traceBegin("UserController.startUser-" + userId
1559                 + (displayId == Display.DEFAULT_DISPLAY ? "" : "-display-" + displayId)
1560                 + "-" + (userStartMode == USER_START_MODE_FOREGROUND ? "fg" : "bg")
1561                 + "-start-mode-" + userStartMode);
1562         try {
1563             return startUserInternal(userId, displayId, userStartMode, unlockListener, t);
1564         } finally {
1565             t.traceEnd();
1566         }
1567     }
1568 
1569     private boolean startUserInternal(@UserIdInt int userId, int displayId,
1570             @UserStartMode int userStartMode, @Nullable IProgressListener unlockListener,
1571             TimingsTraceAndSlog t) {
1572         if (DEBUG_MU) {
1573             Slogf.i(TAG, "Starting user %d on display %d with mode  %s", userId, displayId,
1574                     userStartModeToString(userStartMode));
1575         }
1576         boolean foreground = userStartMode == USER_START_MODE_FOREGROUND;
1577 
1578         boolean onSecondaryDisplay = displayId != Display.DEFAULT_DISPLAY;
1579         if (onSecondaryDisplay) {
1580             Preconditions.checkArgument(!foreground, "Cannot start user %d in foreground AND "
1581                     + "on secondary display (%d)", userId, displayId);
1582         }
1583         EventLog.writeEvent(EventLogTags.UC_START_USER_INTERNAL, userId, foreground ? 1 : 0,
1584                 displayId);
1585 
1586         final int callingUid = Binder.getCallingUid();
1587         final int callingPid = Binder.getCallingPid();
1588         final long ident = Binder.clearCallingIdentity();
1589         try {
1590             t.traceBegin("getStartedUserState");
1591             final int oldUserId = getCurrentUserId();
1592             if (oldUserId == userId) {
1593                 final UserState state = getStartedUserState(userId);
1594                 if (state == null) {
1595                     Slogf.wtf(TAG, "Current user has no UserState");
1596                     // continue starting.
1597                 } else {
1598                     if (userId == UserHandle.USER_SYSTEM && state.state == STATE_BOOTING) {
1599                         // system user start explicitly requested. should continue starting as it
1600                         // is not in running state.
1601                     } else {
1602                         if (state.state == STATE_RUNNING_UNLOCKED) {
1603                             // We'll skip all later code, so we must tell listener it's already
1604                             // unlocked.
1605                             notifyFinished(userId, unlockListener);
1606                         }
1607                         t.traceEnd(); //getStartedUserState
1608                         return true;
1609                     }
1610                 }
1611             }
1612             t.traceEnd(); //getStartedUserState
1613 
1614             if (foreground) {
1615                 t.traceBegin("clearAllLockedTasks");
1616                 mInjector.clearAllLockedTasks("startUser");
1617                 t.traceEnd();
1618             }
1619 
1620             t.traceBegin("getUserInfo");
1621             final UserInfo userInfo = getUserInfo(userId);
1622             t.traceEnd();
1623 
1624             if (userInfo == null) {
1625                 Slogf.w(TAG, "No user info for user #" + userId);
1626                 return false;
1627             }
1628             if (foreground && userInfo.isProfile()) {
1629                 Slogf.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
1630                 return false;
1631             }
1632 
1633             if ((foreground || onSecondaryDisplay) && userInfo.preCreated) {
1634                 Slogf.w(TAG, "Cannot start pre-created user #" + userId + " in foreground or on "
1635                         + "secondary display");
1636                 return false;
1637             }
1638 
1639             t.traceBegin("assignUserToDisplayOnStart");
1640             int result = mInjector.getUserManagerInternal().assignUserToDisplayOnStart(userId,
1641                     userInfo.profileGroupId, userStartMode, displayId);
1642             t.traceEnd();
1643 
1644             if (result == USER_ASSIGNMENT_RESULT_FAILURE) {
1645                 Slogf.e(TAG, "%s user(%d) / display (%d) assignment failed: %s",
1646                         userStartModeToString(userStartMode), userId, displayId,
1647                         userAssignmentResultToString(result));
1648                 return false;
1649             }
1650 
1651             boolean needStart = false;
1652             boolean updateUmState = false;
1653             UserState uss;
1654 
1655             // If the user we are switching to is not currently started, then
1656             // we need to start it now.
1657             t.traceBegin("updateStartedUserArrayStarting");
1658             synchronized (mLock) {
1659                 uss = mStartedUsers.get(userId);
1660                 if (uss == null) {
1661                     uss = new UserState(UserHandle.of(userId));
1662                     uss.mUnlockProgress.addListener(new UserProgressListener());
1663                     mStartedUsers.put(userId, uss);
1664                     updateStartedUserArrayLU();
1665                     needStart = true;
1666                     updateUmState = true;
1667                 } else if (uss.state == UserState.STATE_SHUTDOWN) {
1668                     Slogf.i(TAG, "User #" + userId
1669                             + " is shutting down - will start after full shutdown");
1670                     mPendingUserStarts.add(new PendingUserStart(userId, userStartMode,
1671                             unlockListener));
1672                     t.traceEnd(); // updateStartedUserArrayStarting
1673                     return true;
1674                 }
1675                 final Integer userIdInt = userId;
1676                 mUserLru.remove(userIdInt);
1677                 mUserLru.add(userIdInt);
1678             }
1679             if (unlockListener != null) {
1680                 uss.mUnlockProgress.addListener(unlockListener);
1681             }
1682             t.traceEnd(); // updateStartedUserArrayStarting
1683 
1684             if (updateUmState) {
1685                 t.traceBegin("setUserState");
1686                 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
1687                 t.traceEnd();
1688             }
1689             t.traceBegin("updateConfigurationAndProfileIds");
1690             if (foreground) {
1691                 // Make sure the old user is no longer considering the display to be on.
1692                 mInjector.reportGlobalUsageEvent(UsageEvents.Event.SCREEN_NON_INTERACTIVE);
1693                 boolean userSwitchUiEnabled;
1694                 synchronized (mLock) {
1695                     mCurrentUserId = userId;
1696                     mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
1697                     userSwitchUiEnabled = mUserSwitchUiEnabled;
1698                 }
1699                 mInjector.updateUserConfiguration();
1700                 // NOTE: updateProfileRelatedCaches() is called on both if and else parts, ideally
1701                 // it should be moved outside, but for now it's not as there are many calls to
1702                 // external components here afterwards
1703                 updateProfileRelatedCaches();
1704                 mInjector.getWindowManager().setCurrentUser(userId);
1705                 mInjector.reportCurWakefulnessUsageEvent();
1706                 // Once the internal notion of the active user has switched, we lock the device
1707                 // with the option to show the user switcher on the keyguard.
1708                 if (userSwitchUiEnabled) {
1709                     mInjector.getWindowManager().setSwitchingUser(true);
1710                     // Only lock if the user has a secure keyguard PIN/Pattern/Pwd
1711                     if (mInjector.getKeyguardManager().isDeviceSecure(userId)) {
1712                         // Make sure the device is locked before moving on with the user switch
1713                         mInjector.lockDeviceNowAndWaitForKeyguardShown();
1714                     }
1715                 }
1716 
1717             } else {
1718                 final Integer currentUserIdInt = mCurrentUserId;
1719                 updateProfileRelatedCaches();
1720                 synchronized (mLock) {
1721                     mUserLru.remove(currentUserIdInt);
1722                     mUserLru.add(currentUserIdInt);
1723                 }
1724             }
1725             t.traceEnd();
1726 
1727             // Make sure user is in the started state.  If it is currently
1728             // stopping, we need to knock that off.
1729             if (uss.state == UserState.STATE_STOPPING) {
1730                 t.traceBegin("updateStateStopping");
1731                 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
1732                 // so we can just fairly silently bring the user back from
1733                 // the almost-dead.
1734                 uss.setState(uss.lastState);
1735                 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
1736                 synchronized (mLock) {
1737                     updateStartedUserArrayLU();
1738                 }
1739                 needStart = true;
1740                 t.traceEnd();
1741             } else if (uss.state == UserState.STATE_SHUTDOWN) {
1742                 t.traceBegin("updateStateShutdown");
1743                 // This means ACTION_SHUTDOWN has been sent, so we will
1744                 // need to treat this as a new boot of the user.
1745                 uss.setState(UserState.STATE_BOOTING);
1746                 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
1747                 synchronized (mLock) {
1748                     updateStartedUserArrayLU();
1749                 }
1750                 needStart = true;
1751                 t.traceEnd();
1752             }
1753 
1754             if (uss.state == UserState.STATE_BOOTING) {
1755                 t.traceBegin("updateStateBooting");
1756                 // Give user manager a chance to propagate user restrictions
1757                 // to other services and prepare app storage
1758                 mInjector.getUserManager().onBeforeStartUser(userId);
1759 
1760                 // Booting up a new user, need to tell system services about it.
1761                 // Note that this is on the same handler as scheduling of broadcasts,
1762                 // which is important because it needs to go first.
1763                 mHandler.sendMessage(mHandler.obtainMessage(USER_START_MSG, userId, NO_ARG2));
1764                 t.traceEnd();
1765             }
1766 
1767             t.traceBegin("sendMessages");
1768             if (foreground) {
1769                 mHandler.sendMessage(mHandler.obtainMessage(USER_CURRENT_MSG, userId, oldUserId));
1770                 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
1771                 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
1772                 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
1773                         oldUserId, userId, uss));
1774                 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
1775                         oldUserId, userId, uss), getUserSwitchTimeoutMs());
1776             }
1777 
1778             if (userInfo.preCreated) {
1779                 needStart = false;
1780             }
1781 
1782             // In most cases, broadcast for the system user starting/started is sent by
1783             // ActivityManagerService#systemReady(). However on some HSUM devices (e.g. tablets)
1784             // the user switches from the system user to a secondary user while running
1785             // ActivityManagerService#systemReady(), thus broadcast is not sent for the system user.
1786             // Therefore we send the broadcast for the system user here as well in HSUM.
1787             // TODO(b/266158156): Improve/refactor the way broadcasts are sent for the system user
1788             // in HSUM. Ideally it'd be best to have one single place that sends this notification.
1789             final boolean isSystemUserInHeadlessMode = (userId == UserHandle.USER_SYSTEM)
1790                     && mInjector.isHeadlessSystemUserMode();
1791             if (needStart || isSystemUserInHeadlessMode) {
1792                 sendUserStartedBroadcast(userId, callingUid, callingPid);
1793             }
1794             t.traceEnd();
1795 
1796             if (foreground) {
1797                 t.traceBegin("moveUserToForeground");
1798                 moveUserToForeground(uss, userId);
1799                 t.traceEnd();
1800             } else {
1801                 t.traceBegin("finishUserBoot");
1802                 finishUserBoot(uss);
1803                 t.traceEnd();
1804             }
1805 
1806             if (needStart || isSystemUserInHeadlessMode) {
1807                 t.traceBegin("sendRestartBroadcast");
1808                 sendUserStartingBroadcast(userId, callingUid, callingPid);
1809                 t.traceEnd();
1810             }
1811         } finally {
1812             Binder.restoreCallingIdentity(ident);
1813         }
1814 
1815         return true;
1816     }
1817 
1818     /**
1819      * Start user, if its not already running, and bring it to foreground.
1820      */
1821     void startUserInForeground(@UserIdInt int targetUserId) {
1822         boolean success = startUser(targetUserId, USER_START_MODE_FOREGROUND);
1823         if (!success) {
1824             mInjector.getWindowManager().setSwitchingUser(false);
1825             mTargetUserId = UserHandle.USER_NULL;
1826             dismissUserSwitchDialog(null);
1827         }
1828     }
1829 
1830     boolean unlockUser(@UserIdInt int userId, @Nullable IProgressListener listener) {
1831         checkCallingPermission(INTERACT_ACROSS_USERS_FULL, "unlockUser");
1832         EventLog.writeEvent(EventLogTags.UC_UNLOCK_USER, userId);
1833         final long binderToken = Binder.clearCallingIdentity();
1834         try {
1835             return maybeUnlockUser(userId, listener);
1836         } finally {
1837             Binder.restoreCallingIdentity(binderToken);
1838         }
1839     }
1840 
1841     private static void notifyFinished(@UserIdInt int userId,
1842             @Nullable IProgressListener listener) {
1843         if (listener == null) return;
1844         try {
1845             listener.onFinished(userId, null);
1846         } catch (RemoteException ignored) {
1847         }
1848     }
1849 
1850     private boolean maybeUnlockUser(@UserIdInt int userId) {
1851         return maybeUnlockUser(userId, null);
1852     }
1853 
1854     /**
1855      * Tries to unlock the given user.
1856      * <p>
1857      * This will succeed only if the user's CE storage key is already unlocked or if the user
1858      * doesn't have a lockscreen credential set.
1859      */
1860     private boolean maybeUnlockUser(@UserIdInt int userId, @Nullable IProgressListener listener) {
1861 
1862         // We cannot allow users to be unlocked before PHASE_BOOT_COMPLETED, for two reasons.
1863         // First, emulated volumes aren't supposed to be used until then; StorageManagerService
1864         // assumes it can reset everything upon reaching PHASE_BOOT_COMPLETED.  Second, on some
1865         // devices the Weaver HAL needed to unlock the user's storage isn't available until sometime
1866         // shortly before PHASE_BOOT_COMPLETED.  The below logic enforces a consistent flow across
1867         // all devices, regardless of their Weaver implementation.
1868         //
1869         // Any unlocks that get delayed by this will be done by onBootComplete() instead.
1870         if (!mAllowUserUnlocking) {
1871             Slogf.i(TAG, "Not unlocking user %d yet because boot hasn't completed", userId);
1872             notifyFinished(userId, listener);
1873             return false;
1874         }
1875 
1876         UserState uss;
1877         if (!StorageManager.isUserKeyUnlocked(userId)) {
1878             // We always want to try to unlock the user key, even if the user is not started yet.
1879             mLockPatternUtils.unlockUserKeyIfUnsecured(userId);
1880         }
1881         synchronized (mLock) {
1882             // Register the given listener to watch for unlock progress
1883             uss = mStartedUsers.get(userId);
1884             if (uss != null) {
1885                 uss.mUnlockProgress.addListener(listener);
1886             }
1887         }
1888         // Bail if user isn't actually running
1889         if (uss == null) {
1890             notifyFinished(userId, listener);
1891             return false;
1892         }
1893 
1894         final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
1895         t.traceBegin("finishUserUnlocking-" + userId);
1896         final boolean finishUserUnlockingResult = finishUserUnlocking(uss);
1897         t.traceEnd();
1898         if (!finishUserUnlockingResult) {
1899             notifyFinished(userId, listener);
1900             return false;
1901         }
1902 
1903         // We just unlocked a user, so let's now attempt to unlock any
1904         // managed profiles under that user.
1905 
1906         // First, get list of userIds. Requires mLock, so we cannot make external calls, e.g. to UMS
1907         int[] userIds;
1908         synchronized (mLock) {
1909             userIds = new int[mStartedUsers.size()];
1910             for (int i = 0; i < userIds.length; i++) {
1911                 userIds[i] = mStartedUsers.keyAt(i);
1912             }
1913         }
1914         for (int testUserId : userIds) {
1915             final UserInfo parent = mInjector.getUserManager().getProfileParent(testUserId);
1916             if (parent != null && parent.id == userId && testUserId != userId) {
1917                 Slogf.d(TAG, "User " + testUserId + " (parent " + parent.id
1918                         + "): attempting unlock because parent was just unlocked");
1919                 maybeUnlockUser(testUserId);
1920             }
1921         }
1922 
1923         return true;
1924     }
1925 
1926     boolean switchUser(final int targetUserId) {
1927         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId);
1928         EventLog.writeEvent(EventLogTags.UC_SWITCH_USER, targetUserId);
1929         int currentUserId = getCurrentUserId();
1930         UserInfo targetUserInfo = getUserInfo(targetUserId);
1931         if (targetUserId == currentUserId) {
1932             Slogf.i(TAG, "user #" + targetUserId + " is already the current user");
1933             return true;
1934         }
1935         if (targetUserInfo == null) {
1936             Slogf.w(TAG, "No user info for user #" + targetUserId);
1937             return false;
1938         }
1939         if (!targetUserInfo.supportsSwitchTo()) {
1940             Slogf.w(TAG, "Cannot switch to User #" + targetUserId + ": not supported");
1941             return false;
1942         }
1943         if (FactoryResetter.isFactoryResetting()) {
1944             Slogf.w(TAG, "Cannot switch to User #" + targetUserId + ": factory reset in progress");
1945             return false;
1946         }
1947         boolean userSwitchUiEnabled;
1948         synchronized (mLock) {
1949             if (!mInitialized) {
1950                 Slogf.e(TAG, "Cannot switch to User #" + targetUserId
1951                         + ": UserController not ready yet");
1952                 return false;
1953             }
1954             mTargetUserId = targetUserId;
1955             userSwitchUiEnabled = mUserSwitchUiEnabled;
1956         }
1957         if (userSwitchUiEnabled) {
1958             UserInfo currentUserInfo = getUserInfo(currentUserId);
1959             Pair<UserInfo, UserInfo> userNames = new Pair<>(currentUserInfo, targetUserInfo);
1960             mUiHandler.removeMessages(START_USER_SWITCH_UI_MSG);
1961             mUiHandler.sendMessage(mUiHandler.obtainMessage(
1962                     START_USER_SWITCH_UI_MSG, userNames));
1963         } else {
1964             sendStartUserSwitchFgMessage(targetUserId);
1965         }
1966         return true;
1967     }
1968 
1969     private void sendStartUserSwitchFgMessage(int targetUserId) {
1970         mHandler.removeMessages(START_USER_SWITCH_FG_MSG);
1971         mHandler.sendMessage(mHandler.obtainMessage(START_USER_SWITCH_FG_MSG, targetUserId, 0));
1972     }
1973 
1974     private void dismissUserSwitchDialog(Runnable onDismissed) {
1975         mUiHandler.post(() -> mInjector.dismissUserSwitchingDialog(onDismissed));
1976     }
1977 
1978     private void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
1979         // The dialog will show and then initiate the user switch by calling startUserInForeground
1980         mInjector.showUserSwitchingDialog(fromToUserPair.first, fromToUserPair.second,
1981                 getSwitchingFromSystemUserMessageUnchecked(),
1982                 getSwitchingToSystemUserMessageUnchecked(),
1983                 /* onShown= */ () -> sendStartUserSwitchFgMessage(fromToUserPair.second.id));
1984     }
1985 
1986     private void dispatchForegroundProfileChanged(@UserIdInt int userId) {
1987         final int observerCount = mUserSwitchObservers.beginBroadcast();
1988         for (int i = 0; i < observerCount; i++) {
1989             try {
1990                 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
1991             } catch (RemoteException e) {
1992                 // Ignore
1993             }
1994         }
1995         mUserSwitchObservers.finishBroadcast();
1996     }
1997 
1998     /** Called on handler thread */
1999     @VisibleForTesting
2000     void dispatchUserSwitchComplete(@UserIdInt int oldUserId, @UserIdInt int newUserId) {
2001         final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2002         t.traceBegin("dispatchUserSwitchComplete-" + newUserId);
2003         mInjector.getWindowManager().setSwitchingUser(false);
2004         final int observerCount = mUserSwitchObservers.beginBroadcast();
2005         for (int i = 0; i < observerCount; i++) {
2006             try {
2007                 t.traceBegin("onUserSwitchComplete-" + newUserId + " #" + i + " "
2008                         + mUserSwitchObservers.getBroadcastCookie(i));
2009                 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
2010                 t.traceEnd();
2011             } catch (RemoteException e) {
2012                 // Ignore
2013             }
2014         }
2015         mUserSwitchObservers.finishBroadcast();
2016         t.traceBegin("sendUserSwitchBroadcasts-" + oldUserId + "-" + newUserId);
2017         sendUserSwitchBroadcasts(oldUserId, newUserId);
2018         t.traceEnd();
2019         t.traceEnd();
2020     }
2021 
2022     private void dispatchLockedBootComplete(@UserIdInt int userId) {
2023         final int observerCount = mUserSwitchObservers.beginBroadcast();
2024         for (int i = 0; i < observerCount; i++) {
2025             try {
2026                 mUserSwitchObservers.getBroadcastItem(i).onLockedBootComplete(userId);
2027             } catch (RemoteException e) {
2028                 // Ignore
2029             }
2030         }
2031         mUserSwitchObservers.finishBroadcast();
2032     }
2033 
2034     private void stopUserOnSwitchIfEnforced(@UserIdInt int oldUserId) {
2035         // Never stop system user
2036         if (oldUserId == UserHandle.USER_SYSTEM) {
2037             return;
2038         }
2039         boolean hasRestriction =
2040                 hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND, oldUserId);
2041         synchronized (mLock) {
2042             // If running in background is disabled or mStopUserOnSwitch mode, stop the user.
2043             boolean disallowRunInBg = hasRestriction || shouldStopUserOnSwitch();
2044             if (!disallowRunInBg) {
2045                 if (DEBUG_MU) {
2046                     Slogf.i(TAG, "stopUserOnSwitchIfEnforced() NOT stopping %d and related users",
2047                             oldUserId);
2048                 }
2049                 return;
2050             }
2051             if (DEBUG_MU) {
2052                 Slogf.i(TAG, "stopUserOnSwitchIfEnforced() stopping %d and related users",
2053                         oldUserId);
2054             }
2055             stopUsersLU(oldUserId, /* force= */ false, /* allowDelayedLocking= */ true,
2056                     null, null);
2057         }
2058     }
2059 
2060     private void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
2061         TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG);
2062         t.traceBegin("timeoutUserSwitch-" + oldUserId + "-to-" + newUserId);
2063         synchronized (mLock) {
2064             Slogf.e(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
2065             mTimeoutUserSwitchCallbacks = mCurWaitingUserSwitchCallbacks;
2066             mHandler.removeMessages(USER_SWITCH_CALLBACKS_TIMEOUT_MSG);
2067             sendContinueUserSwitchLU(uss, oldUserId, newUserId);
2068             // Report observers that never called back (USER_SWITCH_CALLBACKS_TIMEOUT)
2069             mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_CALLBACKS_TIMEOUT_MSG,
2070                     oldUserId, newUserId), USER_SWITCH_CALLBACKS_TIMEOUT_MS);
2071         }
2072         t.traceEnd();
2073     }
2074 
2075     private void timeoutUserSwitchCallbacks(int oldUserId, int newUserId) {
2076         synchronized (mLock) {
2077             if (mTimeoutUserSwitchCallbacks != null && !mTimeoutUserSwitchCallbacks.isEmpty()) {
2078                 Slogf.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId
2079                         + ". Observers that didn't respond: " + mTimeoutUserSwitchCallbacks);
2080                 mTimeoutUserSwitchCallbacks = null;
2081             }
2082         }
2083     }
2084 
2085     @VisibleForTesting
2086     void dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId) {
2087         final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2088         t.traceBegin("dispatchUserSwitch-" + oldUserId + "-to-" + newUserId);
2089 
2090         EventLog.writeEvent(EventLogTags.UC_DISPATCH_USER_SWITCH, oldUserId, newUserId);
2091 
2092         final int observerCount = mUserSwitchObservers.beginBroadcast();
2093         if (observerCount > 0) {
2094             for (int i = 0; i < observerCount; i++) {
2095                 final String name = "#" + i + " " + mUserSwitchObservers.getBroadcastCookie(i);
2096                 t.traceBegin("onBeforeUserSwitching-" + name);
2097                 try {
2098                     mUserSwitchObservers.getBroadcastItem(i).onBeforeUserSwitching(newUserId);
2099                 } catch (RemoteException e) {
2100                     // Ignore
2101                 } finally {
2102                     t.traceEnd();
2103                 }
2104             }
2105             final ArraySet<String> curWaitingUserSwitchCallbacks = new ArraySet<>();
2106             synchronized (mLock) {
2107                 uss.switching = true;
2108                 mCurWaitingUserSwitchCallbacks = curWaitingUserSwitchCallbacks;
2109             }
2110             final AtomicInteger waitingCallbacksCount = new AtomicInteger(observerCount);
2111             final long userSwitchTimeoutMs = getUserSwitchTimeoutMs();
2112             final long dispatchStartedTime = SystemClock.elapsedRealtime();
2113             for (int i = 0; i < observerCount; i++) {
2114                 final long dispatchStartedTimeForObserver = SystemClock.elapsedRealtime();
2115                 try {
2116                     // Prepend with unique prefix to guarantee that keys are unique
2117                     final String name = "#" + i + " " + mUserSwitchObservers.getBroadcastCookie(i);
2118                     synchronized (mLock) {
2119                         curWaitingUserSwitchCallbacks.add(name);
2120                     }
2121                     final IRemoteCallback callback = new IRemoteCallback.Stub() {
2122                         @Override
2123                         public void sendResult(Bundle data) throws RemoteException {
2124                             synchronized (mLock) {
2125                                 long delayForObserver = SystemClock.elapsedRealtime()
2126                                         - dispatchStartedTimeForObserver;
2127                                 if (delayForObserver > LONG_USER_SWITCH_OBSERVER_WARNING_TIME_MS) {
2128                                     Slogf.w(TAG, "User switch slowed down by observer " + name
2129                                             + ": result took " + delayForObserver
2130                                             + " ms to process.");
2131                                 }
2132 
2133                                 long totalDelay = SystemClock.elapsedRealtime()
2134                                         - dispatchStartedTime;
2135                                 if (totalDelay > userSwitchTimeoutMs) {
2136                                     Slogf.e(TAG, "User switch timeout: observer " + name
2137                                             + "'s result was received " + totalDelay
2138                                             + " ms after dispatchUserSwitch.");
2139                                 }
2140 
2141                                 TimingsTraceAndSlog t2 = new TimingsTraceAndSlog(TAG);
2142                                 t2.traceBegin("onUserSwitchingReply-" + name);
2143                                 curWaitingUserSwitchCallbacks.remove(name);
2144                                 // Continue switching if all callbacks have been notified and
2145                                 // user switching session is still valid
2146                                 if (waitingCallbacksCount.decrementAndGet() == 0
2147                                         && (curWaitingUserSwitchCallbacks
2148                                         == mCurWaitingUserSwitchCallbacks)) {
2149                                     sendContinueUserSwitchLU(uss, oldUserId, newUserId);
2150                                 }
2151                                 t2.traceEnd();
2152                             }
2153                         }
2154                     };
2155                     t.traceBegin("onUserSwitching-" + name);
2156                     mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(newUserId, callback);
2157                     t.traceEnd();
2158                 } catch (RemoteException e) {
2159                     // Ignore
2160                 }
2161             }
2162         } else {
2163             synchronized (mLock) {
2164                 sendContinueUserSwitchLU(uss, oldUserId, newUserId);
2165             }
2166         }
2167         mUserSwitchObservers.finishBroadcast();
2168         t.traceEnd(); // end dispatchUserSwitch-
2169     }
2170 
2171     @GuardedBy("mLock")
2172     private void sendContinueUserSwitchLU(UserState uss, int oldUserId, int newUserId) {
2173         TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG);
2174         t.traceBegin("sendContinueUserSwitchLU-" + oldUserId + "-to-" + newUserId);
2175         mCurWaitingUserSwitchCallbacks = null;
2176         mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
2177         mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
2178                 oldUserId, newUserId, uss));
2179         t.traceEnd();
2180     }
2181 
2182     @VisibleForTesting
2183     void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
2184         final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2185         t.traceBegin("continueUserSwitch-" + oldUserId + "-to-" + newUserId);
2186 
2187         EventLog.writeEvent(EventLogTags.UC_CONTINUE_USER_SWITCH, oldUserId, newUserId);
2188 
2189         // Do the keyguard dismiss and dismiss the user switching dialog later
2190         mHandler.removeMessages(COMPLETE_USER_SWITCH_MSG);
2191         mHandler.sendMessage(mHandler.obtainMessage(
2192                 COMPLETE_USER_SWITCH_MSG, oldUserId, newUserId));
2193 
2194         uss.switching = false;
2195         stopGuestOrEphemeralUserIfBackground(oldUserId);
2196         stopUserOnSwitchIfEnforced(oldUserId);
2197 
2198         t.traceEnd(); // end continueUserSwitch
2199     }
2200 
2201     @VisibleForTesting
2202     void completeUserSwitch(int oldUserId, int newUserId) {
2203         final boolean isUserSwitchUiEnabled = isUserSwitchUiEnabled();
2204         // serialize each conditional step
2205         await(
2206                 // STEP 1 - If there is no challenge set, dismiss the keyguard right away
2207                 isUserSwitchUiEnabled && !mInjector.getKeyguardManager().isDeviceSecure(newUserId),
2208                 mInjector::dismissKeyguard,
2209                 () -> await(
2210                         // STEP 2 - If user switch ui was enabled, dismiss user switch dialog
2211                         isUserSwitchUiEnabled,
2212                         this::dismissUserSwitchDialog,
2213                         () -> {
2214                             // STEP 3 - Send REPORT_USER_SWITCH_COMPLETE_MSG to broadcast
2215                             // ACTION_USER_SWITCHED & call UserSwitchObservers.onUserSwitchComplete
2216                             mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
2217                             mHandler.sendMessage(mHandler.obtainMessage(
2218                                     REPORT_USER_SWITCH_COMPLETE_MSG, oldUserId, newUserId));
2219                         }
2220                 ));
2221     }
2222 
2223     private void await(boolean condition, Consumer<Runnable> conditionalStep, Runnable nextStep) {
2224         if (condition) {
2225             conditionalStep.accept(nextStep);
2226         } else {
2227             nextStep.run();
2228         }
2229     }
2230 
2231     private void moveUserToForeground(UserState uss, int newUserId) {
2232         boolean homeInFront = mInjector.taskSupervisorSwitchUser(newUserId, uss);
2233         if (homeInFront) {
2234             mInjector.startHomeActivity(newUserId, "moveUserToForeground");
2235         } else {
2236             mInjector.taskSupervisorResumeFocusedStackTopActivity();
2237         }
2238         EventLogTags.writeAmSwitchUser(newUserId);
2239     }
2240 
2241     // The two methods sendUserStartedBroadcast() and sendUserStartingBroadcast()
2242     // could be merged for better reuse. However, the params they are calling broadcastIntent()
2243     // with are different - resultCode receiver, permissions, ordered, and userId, etc. Therefore,
2244     // we decided to keep two separate methods for better code readability/clarity.
2245     // TODO(b/266158156): Improve/refactor the way broadcasts are sent for the system user
2246     // in HSUM. Ideally it'd be best to have one single place that sends this notification.
2247     /** Sends {@code ACTION_USER_STARTED} broadcast. */
2248     void sendUserStartedBroadcast(@UserIdInt int userId, int callingUid, int callingPid) {
2249         if (userId == UserHandle.USER_SYSTEM) {
2250             synchronized (mLock) {
2251                 // Make sure that the broadcast is sent only once for the system user.
2252                 if (mIsBroadcastSentForSystemUserStarted) {
2253                     return;
2254                 }
2255                 mIsBroadcastSentForSystemUserStarted = true;
2256             }
2257         }
2258         final Intent intent = new Intent(Intent.ACTION_USER_STARTED);
2259         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2260                 | Intent.FLAG_RECEIVER_FOREGROUND);
2261         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2262         mInjector.broadcastIntent(intent, /* resolvedType= */ null, /* resultTo= */ null,
2263                 /* resultCode= */ 0, /* resultData= */ null, /* resultExtras= */ null,
2264                 /* requiredPermissions= */ null, AppOpsManager.OP_NONE, /* bOptions= */ null,
2265                 /* ordered= */ false, /* sticky= */ false, MY_PID, SYSTEM_UID,
2266                 callingUid, callingPid, userId);
2267     }
2268 
2269     /** Sends {@code ACTION_USER_STARTING} broadcast. */
2270     void sendUserStartingBroadcast(@UserIdInt int userId, int callingUid, int callingPid) {
2271         if (userId == UserHandle.USER_SYSTEM) {
2272             synchronized (mLock) {
2273                 // Make sure that the broadcast is sent only once for the system user.
2274                 if (mIsBroadcastSentForSystemUserStarting) {
2275                     return;
2276                 }
2277                 mIsBroadcastSentForSystemUserStarting = true;
2278             }
2279         }
2280         final Intent intent = new Intent(Intent.ACTION_USER_STARTING);
2281         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2282         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2283         mInjector.broadcastIntent(intent, /* resolvedType= */ null,
2284                 new IIntentReceiver.Stub() {
2285                     @Override
2286                     public void performReceive(Intent intent, int resultCode,
2287                             String data, Bundle extras, boolean ordered,
2288                             boolean sticky,
2289                             int sendingUser) throws RemoteException {
2290                     }
2291                 }, /* resultCode= */ 0, /* resultData= */ null, /* resultExtras= */ null,
2292                 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE, /* bOptions= */ null,
2293                 /* ordered= */ true, /* sticky= */ false, MY_PID, SYSTEM_UID,
2294                 callingUid, callingPid, UserHandle.USER_ALL);
2295     }
2296 
2297     void sendUserSwitchBroadcasts(int oldUserId, int newUserId) {
2298         final int callingUid = Binder.getCallingUid();
2299         final int callingPid = Binder.getCallingPid();
2300         final long ident = Binder.clearCallingIdentity();
2301         try {
2302             Intent intent;
2303             if (oldUserId >= 0) {
2304                 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
2305                 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(oldUserId, false);
2306                 int count = profiles.size();
2307                 for (int i = 0; i < count; i++) {
2308                     int profileUserId = profiles.get(i).id;
2309                     intent = new Intent(Intent.ACTION_USER_BACKGROUND);
2310                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2311                             | Intent.FLAG_RECEIVER_FOREGROUND);
2312                     intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
2313                     // Also, add the UserHandle for mainline modules which can't use the @hide
2314                     // EXTRA_USER_HANDLE.
2315                     intent.putExtra(Intent.EXTRA_USER, UserHandle.of(profileUserId));
2316                     mInjector.broadcastIntent(intent,
2317                             null, null, 0, null, null, null, AppOpsManager.OP_NONE,
2318                             null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
2319                             profileUserId);
2320                 }
2321             }
2322             if (newUserId >= 0) {
2323                 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
2324                 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(newUserId, false);
2325                 int count = profiles.size();
2326                 for (int i = 0; i < count; i++) {
2327                     int profileUserId = profiles.get(i).id;
2328                     intent = new Intent(Intent.ACTION_USER_FOREGROUND);
2329                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2330                             | Intent.FLAG_RECEIVER_FOREGROUND);
2331                     intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
2332                     // Also, add the UserHandle for mainline modules which can't use the @hide
2333                     // EXTRA_USER_HANDLE.
2334                     intent.putExtra(Intent.EXTRA_USER, UserHandle.of(profileUserId));
2335                     mInjector.broadcastIntent(intent,
2336                             null, null, 0, null, null, null, AppOpsManager.OP_NONE,
2337                             null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
2338                             profileUserId);
2339                 }
2340                 intent = new Intent(Intent.ACTION_USER_SWITCHED);
2341                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2342                         | Intent.FLAG_RECEIVER_FOREGROUND);
2343                 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
2344                 // Also, add the UserHandle for mainline modules which can't use the @hide
2345                 // EXTRA_USER_HANDLE.
2346                 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(newUserId));
2347                 mInjector.broadcastIntent(intent,
2348                         null, null, 0, null, null,
2349                         new String[] {android.Manifest.permission.MANAGE_USERS},
2350                         AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID, callingUid,
2351                         callingPid, UserHandle.USER_ALL);
2352             }
2353         } finally {
2354             Binder.restoreCallingIdentity(ident);
2355         }
2356     }
2357 
2358     /**
2359      * Broadcasts to the parent user when a profile is started+unlocked/stopped.
2360      * @param userId the id of the profile
2361      * @param parentId the id of the parent user
2362      * @param intentAction either ACTION_PROFILE_ACCESSIBLE or ACTION_PROFILE_INACCESSIBLE
2363      */
2364     private void broadcastProfileAccessibleStateChanged(@UserIdInt int userId,
2365             @UserIdInt int parentId,
2366             String intentAction) {
2367         final Intent intent = new Intent(intentAction);
2368         intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
2369         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2370                 | Intent.FLAG_RECEIVER_FOREGROUND);
2371         mInjector.broadcastIntent(intent, /* resolvedType= */ null, /* resultTo= */
2372                 null, /* resultCode= */ 0, /* resultData= */ null, /* resultExtras= */
2373                 null, /* requiredPermissions= */ null, AppOpsManager.OP_NONE, /* bOptions= */
2374                 null, /* ordered= */ false, /* sticky= */ false, MY_PID, SYSTEM_UID,
2375                 Binder.getCallingUid(), Binder.getCallingPid(), parentId);
2376     }
2377 
2378     int handleIncomingUser(int callingPid, int callingUid, @UserIdInt int userId, boolean allowAll,
2379             int allowMode, String name, String callerPackage) {
2380         final int callingUserId = UserHandle.getUserId(callingUid);
2381         if (callingUserId == userId) {
2382             return userId;
2383         }
2384 
2385         // Note that we may be accessing mCurrentUserId outside of a lock...
2386         // shouldn't be a big deal, if this is being called outside
2387         // of a locked context there is intrinsically a race with
2388         // the value the caller will receive and someone else changing it.
2389         // We assume that USER_CURRENT_OR_SELF will use the current user; later
2390         // we will switch to the calling user if access to the current user fails.
2391         int targetUserId = unsafeConvertIncomingUser(userId);
2392 
2393         if (callingUid != 0 && callingUid != SYSTEM_UID) {
2394             final boolean allow;
2395             final boolean isSameProfileGroup = isSameProfileGroup(callingUserId, targetUserId);
2396             if (mInjector.isCallerRecents(callingUid) && isSameProfileGroup) {
2397                 // If the caller is Recents and the caller has ownership of the profile group,
2398                 // we then allow it to access its profiles.
2399                 allow = true;
2400             } else if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
2401                     callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
2402                 // If the caller has this permission, they always pass go.  And collect $200.
2403                 allow = true;
2404             } else if (allowMode == ALLOW_FULL_ONLY) {
2405                 // We require full access, sucks to be you.
2406                 allow = false;
2407             } else if (canInteractWithAcrossProfilesPermission(
2408                     allowMode, isSameProfileGroup, callingPid, callingUid, callerPackage)) {
2409                 allow = true;
2410             } else if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
2411                     callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
2412                 // If the caller does not have either permission, they are always doomed.
2413                 allow = false;
2414             } else if (allowMode == ALLOW_NON_FULL || allowMode == ALLOW_PROFILES_OR_NON_FULL) {
2415                 // We are blanket allowing non-full access, you lucky caller!
2416                 allow = true;
2417             } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
2418                 // We may or may not allow this depending on whether the two users are
2419                 // in the same profile.
2420                 allow = isSameProfileGroup;
2421             } else {
2422                 throw new IllegalArgumentException("Unknown mode: " + allowMode);
2423             }
2424             if (!allow) {
2425                 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
2426                     // In this case, they would like to just execute as their
2427                     // owner user instead of failing.
2428                     targetUserId = callingUserId;
2429                 } else {
2430                     StringBuilder builder = new StringBuilder(128);
2431                     builder.append("Permission Denial: ");
2432                     builder.append(name);
2433                     if (callerPackage != null) {
2434                         builder.append(" from ");
2435                         builder.append(callerPackage);
2436                     }
2437                     builder.append(" asks to run as user ");
2438                     builder.append(userId);
2439                     builder.append(" but is calling from uid ");
2440                     UserHandle.formatUid(builder, callingUid);
2441                     builder.append("; this requires ");
2442                     builder.append(INTERACT_ACROSS_USERS_FULL);
2443                     if (allowMode != ALLOW_FULL_ONLY) {
2444                         if (allowMode == ALLOW_NON_FULL
2445                                 || allowMode == ALLOW_PROFILES_OR_NON_FULL
2446                                 || (allowMode == ALLOW_NON_FULL_IN_PROFILE && isSameProfileGroup)) {
2447                             builder.append(" or ");
2448                             builder.append(INTERACT_ACROSS_USERS);
2449                         }
2450                         if (isSameProfileGroup && allowMode == ALLOW_PROFILES_OR_NON_FULL) {
2451                             builder.append(" or ");
2452                             builder.append(INTERACT_ACROSS_PROFILES);
2453                         }
2454                     }
2455                     String msg = builder.toString();
2456                     Slogf.w(TAG, msg);
2457                     throw new SecurityException(msg);
2458                 }
2459             }
2460         }
2461         if (!allowAll) {
2462             ensureNotSpecialUser(targetUserId);
2463         }
2464         // Check shell permission
2465         if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
2466             if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
2467                 throw new SecurityException("Shell does not have permission to access user "
2468                         + targetUserId + "\n " + Debug.getCallers(3));
2469             }
2470         }
2471         return targetUserId;
2472     }
2473 
2474     private boolean canInteractWithAcrossProfilesPermission(
2475             int allowMode, boolean isSameProfileGroup, int callingPid, int callingUid,
2476             String callingPackage) {
2477         if (allowMode != ALLOW_PROFILES_OR_NON_FULL) {
2478             return false;
2479         }
2480         if (!isSameProfileGroup) {
2481             return false;
2482         }
2483         return mInjector.checkPermissionForPreflight(INTERACT_ACROSS_PROFILES, callingPid,
2484                 callingUid, callingPackage);
2485     }
2486 
2487     int unsafeConvertIncomingUser(@UserIdInt int userId) {
2488         return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
2489                 ? getCurrentUserId(): userId;
2490     }
2491 
2492     void ensureNotSpecialUser(@UserIdInt int userId) {
2493         if (userId >= 0) {
2494             return;
2495         }
2496         throw new IllegalArgumentException("Call does not support special user #" + userId);
2497     }
2498 
2499     void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
2500         Objects.requireNonNull(name, "Observer name cannot be null");
2501         checkCallingPermission(INTERACT_ACROSS_USERS_FULL, "registerUserSwitchObserver");
2502         mUserSwitchObservers.register(observer, name);
2503     }
2504 
2505     void sendForegroundProfileChanged(@UserIdInt int userId) {
2506         mHandler.removeMessages(FOREGROUND_PROFILE_CHANGED_MSG);
2507         mHandler.obtainMessage(FOREGROUND_PROFILE_CHANGED_MSG, userId, 0).sendToTarget();
2508     }
2509 
2510     void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
2511         mUserSwitchObservers.unregister(observer);
2512     }
2513 
2514     UserState getStartedUserState(@UserIdInt int userId) {
2515         synchronized (mLock) {
2516             return mStartedUsers.get(userId);
2517         }
2518     }
2519 
2520     boolean hasStartedUserState(@UserIdInt int userId) {
2521         synchronized (mLock) {
2522             return mStartedUsers.get(userId) != null;
2523         }
2524     }
2525 
2526     @GuardedBy("mLock")
2527     private void updateStartedUserArrayLU() {
2528         int num = 0;
2529         for (int i = 0; i < mStartedUsers.size(); i++) {
2530             UserState uss = mStartedUsers.valueAt(i);
2531             // This list does not include stopping users.
2532             if (uss.state != UserState.STATE_STOPPING
2533                     && uss.state != UserState.STATE_SHUTDOWN) {
2534                 num++;
2535             }
2536         }
2537         mStartedUserArray = new int[num];
2538         num = 0;
2539         for (int i = 0; i < mStartedUsers.size(); i++) {
2540             UserState uss = mStartedUsers.valueAt(i);
2541             if (uss.state != UserState.STATE_STOPPING
2542                     && uss.state != UserState.STATE_SHUTDOWN) {
2543                 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
2544             }
2545         }
2546     }
2547 
2548     @VisibleForTesting
2549     void setAllowUserUnlocking(boolean allowed) {
2550         mAllowUserUnlocking = allowed;
2551         if (DEBUG_MU) {
2552             Slogf.d(TAG, new Exception(), "setAllowUserUnlocking(%b)", allowed);
2553         }
2554     }
2555 
2556     void onBootComplete(IIntentReceiver resultTo) {
2557         // Now that PHASE_BOOT_COMPLETED has been reached, user unlocking is allowed.
2558         setAllowUserUnlocking(true);
2559 
2560         // Get a copy of mStartedUsers to use outside of lock.
2561         SparseArray<UserState> startedUsers;
2562         synchronized (mLock) {
2563             startedUsers = mStartedUsers.clone();
2564         }
2565         // In non-headless system user mode, call finishUserBoot() to transition the system user
2566         // from the BOOTING state to RUNNING_LOCKED, then to RUNNING_UNLOCKED if possible.
2567         //
2568         // In headless system user mode, additional users may have been started, and all users
2569         // (including the system user) that ever get started are started explicitly.  In this case,
2570         // we should *not* transition users out of the BOOTING state using finishUserBoot(), as that
2571         // doesn't handle issuing the needed onUserStarting() call, and it would just race with an
2572         // explicit start anyway.  We do, however, need to send the "locked boot complete" broadcast
2573         // as that got skipped earlier due to the *device* boot not being complete yet.
2574         // We also need to try to unlock all started users, since until now explicit user starts
2575         // didn't proceed to unlocking, due to it being too early in the device boot.
2576         //
2577         // USER_SYSTEM must be processed first.  It will be first in the array, as its ID is lowest.
2578         Preconditions.checkArgument(startedUsers.keyAt(0) == UserHandle.USER_SYSTEM);
2579         for (int i = 0; i < startedUsers.size(); i++) {
2580             int userId = startedUsers.keyAt(i);
2581             UserState uss = startedUsers.valueAt(i);
2582             if (!mInjector.isHeadlessSystemUserMode()) {
2583                 finishUserBoot(uss, resultTo);
2584             } else {
2585                 sendLockedBootCompletedBroadcast(resultTo, userId);
2586                 maybeUnlockUser(userId);
2587             }
2588         }
2589     }
2590 
2591     void onSystemReady() {
2592         if (DEBUG_MU) {
2593             Slogf.d(TAG, "onSystemReady()");
2594 
2595         }
2596         mInjector.getUserManagerInternal().addUserLifecycleListener(mUserLifecycleListener);
2597         updateProfileRelatedCaches();
2598         mInjector.reportCurWakefulnessUsageEvent();
2599     }
2600 
2601     // TODO(b/266158156): remove this method if initial system user boot logic is refactored?
2602     void onSystemUserStarting() {
2603         if (!mInjector.isHeadlessSystemUserMode()) {
2604             // Don't need to call on HSUM because it will be called when the system user is
2605             // restarted on background
2606             mInjector.onUserStarting(UserHandle.USER_SYSTEM);
2607             mInjector.onSystemUserVisibilityChanged(/* visible= */ true);
2608         }
2609     }
2610 
2611     /**
2612      * Refreshes the internal caches related to user profiles.
2613      *
2614      * <p>It's called every time a user is started.
2615      */
2616     private void updateProfileRelatedCaches() {
2617         final List<UserInfo> profiles = mInjector.getUserManager().getProfiles(getCurrentUserId(),
2618                 /* enabledOnly= */ false);
2619         int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
2620         for (int i = 0; i < currentProfileIds.length; i++) {
2621             currentProfileIds[i] = profiles.get(i).id;
2622         }
2623         final List<UserInfo> users = mInjector.getUserManager().getUsers(false);
2624         synchronized (mLock) {
2625             mCurrentProfileIds = currentProfileIds;
2626 
2627             mUserProfileGroupIds.clear();
2628             for (int i = 0; i < users.size(); i++) {
2629                 UserInfo user = users.get(i);
2630                 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2631                     mUserProfileGroupIds.put(user.id, user.profileGroupId);
2632                 }
2633             }
2634         }
2635     }
2636 
2637     int[] getStartedUserArray() {
2638         synchronized (mLock) {
2639             return mStartedUserArray;
2640         }
2641     }
2642 
2643     boolean isUserRunning(@UserIdInt int userId, int flags) {
2644         UserState state = getStartedUserState(userId);
2645         if (state == null) {
2646             return false;
2647         }
2648         if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
2649             return true;
2650         }
2651         if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
2652             switch (state.state) {
2653                 case UserState.STATE_BOOTING:
2654                 case UserState.STATE_RUNNING_LOCKED:
2655                     return true;
2656                 default:
2657                     return false;
2658             }
2659         }
2660         if ((flags & ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED) != 0) {
2661             switch (state.state) {
2662                 case UserState.STATE_RUNNING_UNLOCKING:
2663                 case UserState.STATE_RUNNING_UNLOCKED:
2664                     return true;
2665                 // In the stopping/shutdown state return unlock state of the user key
2666                 case UserState.STATE_STOPPING:
2667                 case UserState.STATE_SHUTDOWN:
2668                     return StorageManager.isUserKeyUnlocked(userId);
2669                 default:
2670                     return false;
2671             }
2672         }
2673         if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
2674             switch (state.state) {
2675                 case UserState.STATE_RUNNING_UNLOCKED:
2676                     return true;
2677                 // In the stopping/shutdown state return unlock state of the user key
2678                 case UserState.STATE_STOPPING:
2679                 case UserState.STATE_SHUTDOWN:
2680                     return StorageManager.isUserKeyUnlocked(userId);
2681                 default:
2682                     return false;
2683             }
2684         }
2685 
2686         return state.state != UserState.STATE_STOPPING && state.state != UserState.STATE_SHUTDOWN;
2687     }
2688 
2689     /**
2690      * Check if system user is already started. Unlike other user, system user is in STATE_BOOTING
2691      * even if it is not explicitly started. So isUserRunning cannot give the right state
2692      * to check if system user is started or not.
2693      * @return true if system user is started.
2694      */
2695     boolean isSystemUserStarted() {
2696         synchronized (mLock) {
2697             UserState uss = mStartedUsers.get(UserHandle.USER_SYSTEM);
2698             if (uss == null) {
2699                 return false;
2700             }
2701             return uss.state == UserState.STATE_RUNNING_LOCKED
2702                 || uss.state == UserState.STATE_RUNNING_UNLOCKING
2703                 || uss.state == UserState.STATE_RUNNING_UNLOCKED;
2704         }
2705     }
2706 
2707     private void checkGetCurrentUserPermissions() {
2708         if ((mInjector.checkCallingPermission(INTERACT_ACROSS_USERS)
2709                 != PackageManager.PERMISSION_GRANTED) && (
2710                 mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
2711                         != PackageManager.PERMISSION_GRANTED)) {
2712             String msg = "Permission Denial: getCurrentUser() from pid="
2713                     + Binder.getCallingPid()
2714                     + ", uid=" + Binder.getCallingUid()
2715                     + " requires " + INTERACT_ACROSS_USERS;
2716             Slogf.w(TAG, msg);
2717             throw new SecurityException(msg);
2718         }
2719     }
2720 
2721     UserInfo getCurrentUser() {
2722         checkGetCurrentUserPermissions();
2723 
2724         // Optimization - if there is no pending user switch, return user for current id
2725         // (no need to acquire lock because mTargetUserId and mCurrentUserId are volatile)
2726         if (mTargetUserId == UserHandle.USER_NULL) {
2727             return getUserInfo(mCurrentUserId);
2728         }
2729         synchronized (mLock) {
2730             return getCurrentUserLU();
2731         }
2732     }
2733 
2734     /**
2735      * Gets the current user id, but checking that caller has the proper permissions.
2736      */
2737     int getCurrentUserIdChecked() {
2738         checkGetCurrentUserPermissions();
2739 
2740         // Optimization - if there is no pending user switch, return current id
2741         // (no need to acquire lock because mTargetUserId and mCurrentUserId are volatile)
2742         if (mTargetUserId == UserHandle.USER_NULL) {
2743             return mCurrentUserId;
2744         }
2745         return getCurrentOrTargetUserId();
2746     }
2747 
2748     @GuardedBy("mLock")
2749     private UserInfo getCurrentUserLU() {
2750         int userId = getCurrentOrTargetUserIdLU();
2751         return getUserInfo(userId);
2752     }
2753 
2754     int getCurrentOrTargetUserId() {
2755         synchronized (mLock) {
2756             return getCurrentOrTargetUserIdLU();
2757         }
2758     }
2759 
2760     @GuardedBy("mLock")
2761     private int getCurrentOrTargetUserIdLU() {
2762         return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
2763     }
2764 
2765     Pair<Integer, Integer> getCurrentAndTargetUserIds() {
2766         synchronized (mLock) {
2767             return new Pair<>(mCurrentUserId, mTargetUserId);
2768         }
2769     }
2770 
2771     @GuardedBy("mLock")
2772     private int getCurrentUserIdLU() {
2773         return mCurrentUserId;
2774     }
2775 
2776     int getCurrentUserId() {
2777         synchronized (mLock) {
2778             return mCurrentUserId;
2779         }
2780     }
2781 
2782     @GuardedBy("mLock")
2783     private boolean isCurrentUserLU(@UserIdInt int userId) {
2784         return userId == getCurrentOrTargetUserIdLU();
2785     }
2786 
2787     int[] getUsers() {
2788         UserManagerService ums = mInjector.getUserManager();
2789         return ums != null ? ums.getUserIds() : new int[] { 0 };
2790     }
2791 
2792     private UserInfo getUserInfo(@UserIdInt int userId) {
2793         return mInjector.getUserManager().getUserInfo(userId);
2794     }
2795 
2796     private @Nullable UserProperties getUserProperties(@UserIdInt int userId) {
2797         return mInjector.getUserManagerInternal().getUserProperties(userId);
2798     }
2799 
2800     int[] getUserIds() {
2801         return mInjector.getUserManager().getUserIds();
2802     }
2803 
2804     /**
2805      * If {@code userId} is {@link UserHandle#USER_ALL}, then return an array with all running user
2806      * IDs. Otherwise return an array whose only element is the given user id.
2807      *
2808      * It doesn't handle other special user IDs such as {@link UserHandle#USER_CURRENT}.
2809      */
2810     int[] expandUserId(@UserIdInt int userId) {
2811         if (userId != UserHandle.USER_ALL) {
2812             return new int[] {userId};
2813         } else {
2814             return getUsers();
2815         }
2816     }
2817 
2818     boolean exists(@UserIdInt int userId) {
2819         return mInjector.getUserManager().exists(userId);
2820     }
2821 
2822     private void checkCallingPermission(String permission, String methodName) {
2823         checkCallingHasOneOfThosePermissions(methodName, permission);
2824     }
2825 
2826     private void checkCallingHasOneOfThosePermissions(String methodName, String...permissions) {
2827         for (String permission : permissions) {
2828             if (mInjector.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
2829                 return;
2830             }
2831         }
2832         String msg = "Permission denial: " + methodName
2833                 + "() from pid=" + Binder.getCallingPid()
2834                 + ", uid=" + Binder.getCallingUid()
2835                 + " requires "
2836                 + (permissions.length == 1
2837                         ? permissions[0]
2838                         : "one of " + Arrays.toString(permissions));
2839         Slogf.w(TAG, msg);
2840         throw new SecurityException(msg);
2841     }
2842 
2843     private void enforceShellRestriction(String restriction, @UserIdInt int userId) {
2844         if (Binder.getCallingUid() == SHELL_UID) {
2845             if (userId < 0 || hasUserRestriction(restriction, userId)) {
2846                 throw new SecurityException("Shell does not have permission to access user "
2847                         + userId);
2848             }
2849         }
2850     }
2851 
2852     boolean hasUserRestriction(String restriction, @UserIdInt int userId) {
2853         return mInjector.getUserManager().hasUserRestriction(restriction, userId);
2854     }
2855 
2856     boolean isSameProfileGroup(int callingUserId, int targetUserId) {
2857         if (callingUserId == targetUserId) {
2858             return true;
2859         }
2860         synchronized (mLock) {
2861             int callingProfile = mUserProfileGroupIds.get(callingUserId,
2862                     UserInfo.NO_PROFILE_GROUP_ID);
2863             int targetProfile = mUserProfileGroupIds.get(targetUserId,
2864                     UserInfo.NO_PROFILE_GROUP_ID);
2865             return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
2866                     && callingProfile == targetProfile;
2867         }
2868     }
2869 
2870     boolean isUserOrItsParentRunning(@UserIdInt int userId) {
2871         synchronized (mLock) {
2872             if (isUserRunning(userId, 0)) {
2873                 return true;
2874             }
2875             final int parentUserId = mUserProfileGroupIds.get(userId, UserInfo.NO_PROFILE_GROUP_ID);
2876             if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
2877                 return false;
2878             }
2879             return isUserRunning(parentUserId, 0);
2880         }
2881     }
2882 
2883     boolean isCurrentProfile(@UserIdInt int userId) {
2884         synchronized (mLock) {
2885             return ArrayUtils.contains(mCurrentProfileIds, userId);
2886         }
2887     }
2888 
2889     int[] getCurrentProfileIds() {
2890         synchronized (mLock) {
2891             return mCurrentProfileIds;
2892         }
2893     }
2894 
2895     private void onUserAdded(UserInfo user) {
2896         if (!user.isProfile()) {
2897             return;
2898         }
2899         synchronized (mLock) {
2900             if (user.profileGroupId == mCurrentUserId) {
2901                 mCurrentProfileIds = ArrayUtils.appendInt(mCurrentProfileIds, user.id);
2902             }
2903             mUserProfileGroupIds.put(user.id, user.profileGroupId);
2904         }
2905     }
2906 
2907     void onUserRemoved(@UserIdInt int userId) {
2908         synchronized (mLock) {
2909             int size = mUserProfileGroupIds.size();
2910             for (int i = size - 1; i >= 0; i--) {
2911                 if (mUserProfileGroupIds.keyAt(i) == userId
2912                         || mUserProfileGroupIds.valueAt(i) == userId) {
2913                     mUserProfileGroupIds.removeAt(i);
2914 
2915                 }
2916             }
2917             mCurrentProfileIds = ArrayUtils.removeInt(mCurrentProfileIds, userId);
2918         }
2919     }
2920 
2921     /**
2922      * Returns whether the given user requires credential entry at this time. This is used to
2923      * intercept activity launches for locked work apps due to work challenge being triggered
2924      * or when the profile user is yet to be unlocked.
2925      */
2926     protected boolean shouldConfirmCredentials(@UserIdInt int userId) {
2927         if (getStartedUserState(userId) == null) {
2928             return false;
2929         }
2930         final UserProperties properties = getUserProperties(userId);
2931         if (properties == null || !properties.isCredentialShareableWithParent()) {
2932             return false;
2933         }
2934         if (mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
2935             final KeyguardManager km = mInjector.getKeyguardManager();
2936             return km.isDeviceLocked(userId) && km.isDeviceSecure(userId);
2937         } else {
2938             // For unified challenge, need to confirm credential if user is RUNNING_LOCKED.
2939             return isUserRunning(userId, ActivityManager.FLAG_AND_LOCKED);
2940         }
2941     }
2942 
2943     boolean isLockScreenDisabled(@UserIdInt int userId) {
2944         return mLockPatternUtils.isLockScreenDisabled(userId);
2945     }
2946 
2947     void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) {
2948         synchronized (mLock) {
2949             mSwitchingFromSystemUserMessage = switchingFromSystemUserMessage;
2950         }
2951     }
2952 
2953     void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) {
2954         synchronized (mLock) {
2955             mSwitchingToSystemUserMessage = switchingToSystemUserMessage;
2956         }
2957     }
2958 
2959     // Called by AMS, must check permission
2960     String getSwitchingFromSystemUserMessage() {
2961         checkHasManageUsersPermission("getSwitchingFromSystemUserMessage()");
2962 
2963         return getSwitchingFromSystemUserMessageUnchecked();
2964     }
2965 
2966     // Called by AMS, must check permission
2967     String getSwitchingToSystemUserMessage() {
2968         checkHasManageUsersPermission("getSwitchingToSystemUserMessage()");
2969 
2970         return getSwitchingToSystemUserMessageUnchecked();
2971     }
2972 
2973     private String getSwitchingFromSystemUserMessageUnchecked() {
2974         synchronized (mLock) {
2975             return mSwitchingFromSystemUserMessage;
2976         }
2977     }
2978 
2979     private String getSwitchingToSystemUserMessageUnchecked() {
2980         synchronized (mLock) {
2981             return mSwitchingToSystemUserMessage;
2982         }
2983     }
2984 
2985     private void checkHasManageUsersPermission(String operation) {
2986         if (mInjector.checkCallingPermission(
2987                 android.Manifest.permission.MANAGE_USERS) == PackageManager.PERMISSION_DENIED) {
2988             throw new SecurityException(
2989                     "You need MANAGE_USERS permission to call " + operation);
2990         }
2991     }
2992 
2993     void dumpDebug(ProtoOutputStream proto, long fieldId) {
2994         synchronized (mLock) {
2995             long token = proto.start(fieldId);
2996             for (int i = 0; i < mStartedUsers.size(); i++) {
2997                 UserState uss = mStartedUsers.valueAt(i);
2998                 final long uToken = proto.start(UserControllerProto.STARTED_USERS);
2999                 proto.write(UserControllerProto.User.ID, uss.mHandle.getIdentifier());
3000                 uss.dumpDebug(proto, UserControllerProto.User.STATE);
3001                 proto.end(uToken);
3002             }
3003             for (int i = 0; i < mStartedUserArray.length; i++) {
3004                 proto.write(UserControllerProto.STARTED_USER_ARRAY, mStartedUserArray[i]);
3005             }
3006             for (int i = 0; i < mUserLru.size(); i++) {
3007                 proto.write(UserControllerProto.USER_LRU, mUserLru.get(i));
3008             }
3009             if (mUserProfileGroupIds.size() > 0) {
3010                 for (int i = 0; i < mUserProfileGroupIds.size(); i++) {
3011                     final long uToken = proto.start(UserControllerProto.USER_PROFILE_GROUP_IDS);
3012                     proto.write(UserControllerProto.UserProfile.USER,
3013                             mUserProfileGroupIds.keyAt(i));
3014                     proto.write(UserControllerProto.UserProfile.PROFILE,
3015                             mUserProfileGroupIds.valueAt(i));
3016                     proto.end(uToken);
3017                 }
3018             }
3019             proto.write(UserControllerProto.CURRENT_USER, mCurrentUserId);
3020             for (int i = 0; i < mCurrentProfileIds.length; i++) {
3021                 proto.write(UserControllerProto.CURRENT_PROFILES, mCurrentProfileIds[i]);
3022             }
3023             proto.end(token);
3024         }
3025     }
3026 
3027     void dump(PrintWriter pw) {
3028         synchronized (mLock) {
3029             pw.println("  mStartedUsers:");
3030             for (int i = 0; i < mStartedUsers.size(); i++) {
3031                 UserState uss = mStartedUsers.valueAt(i);
3032                 pw.print("    User #");
3033                 pw.print(uss.mHandle.getIdentifier());
3034                 pw.print(": ");
3035                 uss.dump("", pw);
3036             }
3037             pw.print("  mStartedUserArray: [");
3038             for (int i = 0; i < mStartedUserArray.length; i++) {
3039                 if (i > 0)
3040                     pw.print(", ");
3041                 pw.print(mStartedUserArray[i]);
3042             }
3043             pw.println("]");
3044             pw.print("  mUserLru: [");
3045             for (int i = 0; i < mUserLru.size(); i++) {
3046                 if (i > 0)
3047                     pw.print(", ");
3048                 pw.print(mUserLru.get(i));
3049             }
3050             pw.println("]");
3051             if (mUserProfileGroupIds.size() > 0) {
3052                 pw.println("  mUserProfileGroupIds:");
3053                 for (int i=0; i< mUserProfileGroupIds.size(); i++) {
3054                     pw.print("    User #");
3055                     pw.print(mUserProfileGroupIds.keyAt(i));
3056                     pw.print(" -> profile #");
3057                     pw.println(mUserProfileGroupIds.valueAt(i));
3058                 }
3059             }
3060             pw.println("  mCurrentProfileIds:" + Arrays.toString(mCurrentProfileIds));
3061             pw.println("  mCurrentUserId:" + mCurrentUserId);
3062             pw.println("  mTargetUserId:" + mTargetUserId);
3063             pw.println("  mLastActiveUsers:" + mLastActiveUsers);
3064             pw.println("  mDelayUserDataLocking:" + mDelayUserDataLocking);
3065             pw.println("  mAllowUserUnlocking:" + mAllowUserUnlocking);
3066             pw.println("  shouldStopUserOnSwitch():" + shouldStopUserOnSwitch());
3067             pw.println("  mStopUserOnSwitch:" + mStopUserOnSwitch);
3068             pw.println("  mMaxRunningUsers:" + mMaxRunningUsers);
3069             pw.println("  mUserSwitchUiEnabled:" + mUserSwitchUiEnabled);
3070             pw.println("  mInitialized:" + mInitialized);
3071             pw.println("  mIsBroadcastSentForSystemUserStarted:"
3072                     + mIsBroadcastSentForSystemUserStarted);
3073             pw.println("  mIsBroadcastSentForSystemUserStarting:"
3074                     + mIsBroadcastSentForSystemUserStarting);
3075             if (mSwitchingFromSystemUserMessage != null) {
3076                 pw.println("  mSwitchingFromSystemUserMessage: " + mSwitchingFromSystemUserMessage);
3077             }
3078             if (mSwitchingToSystemUserMessage != null) {
3079                 pw.println("  mSwitchingToSystemUserMessage: " + mSwitchingToSystemUserMessage);
3080             }
3081             pw.println("  mLastUserUnlockingUptime: " + mLastUserUnlockingUptime);
3082         }
3083     }
3084 
3085     @Override
3086     public boolean handleMessage(Message msg) {
3087         switch (msg.what) {
3088             case START_USER_SWITCH_FG_MSG:
3089                 logUserJourneyBegin(msg.arg1, USER_JOURNEY_USER_SWITCH_FG);
3090                 startUserInForeground(msg.arg1);
3091                 break;
3092             case REPORT_USER_SWITCH_MSG:
3093                 dispatchUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
3094                 break;
3095             case CONTINUE_USER_SWITCH_MSG:
3096                 continueUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
3097                 break;
3098             case USER_SWITCH_TIMEOUT_MSG:
3099                 timeoutUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
3100                 break;
3101             case USER_SWITCH_CALLBACKS_TIMEOUT_MSG:
3102                 timeoutUserSwitchCallbacks(msg.arg1, msg.arg2);
3103                 break;
3104             case START_PROFILES_MSG:
3105                 startProfiles();
3106                 break;
3107             case USER_START_MSG:
3108                 mInjector.batteryStatsServiceNoteEvent(
3109                         BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
3110                         Integer.toString(msg.arg1), msg.arg1);
3111                 logUserJourneyBegin(msg.arg1, USER_JOURNEY_USER_START);
3112 
3113                 mInjector.onUserStarting(/* userId= */ msg.arg1);
3114                 scheduleOnUserCompletedEvent(msg.arg1,
3115                         UserCompletedEventType.EVENT_TYPE_USER_STARTING,
3116                         USER_COMPLETED_EVENT_DELAY_MS);
3117 
3118                 mInjector.getUserJourneyLogger().logUserJourneyFinish(-1 , getUserInfo(msg.arg1),
3119                         USER_JOURNEY_USER_START);
3120                 break;
3121             case USER_UNLOCK_MSG:
3122                 final int userId = msg.arg1;
3123                 mInjector.getSystemServiceManager().onUserUnlocking(userId);
3124                 // Loads recents on a worker thread that allows disk I/O
3125                 FgThread.getHandler().post(() -> {
3126                     mInjector.loadUserRecents(userId);
3127                 });
3128 
3129                 mInjector.getUserJourneyLogger().logUserLifecycleEvent(msg.arg1,
3130                         USER_LIFECYCLE_EVENT_UNLOCKING_USER, EVENT_STATE_FINISH);
3131                 mInjector.getUserJourneyLogger().logUserLifecycleEvent(msg.arg1,
3132                         USER_LIFECYCLE_EVENT_UNLOCKED_USER, EVENT_STATE_BEGIN);
3133 
3134                 final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3135                 t.traceBegin("finishUserUnlocked-" + userId);
3136                 finishUserUnlocked((UserState) msg.obj);
3137                 t.traceEnd();
3138                 break;
3139             case USER_UNLOCKED_MSG:
3140                 mInjector.getSystemServiceManager().onUserUnlocked(msg.arg1);
3141                 scheduleOnUserCompletedEvent(msg.arg1,
3142                         UserCompletedEventType.EVENT_TYPE_USER_UNLOCKED,
3143                         // If it's the foreground user, we wait longer to let it fully load.
3144                         // Else, there's nothing specific to wait for, so we basically just proceed.
3145                         // (No need to acquire lock to read mCurrentUserId since it is volatile.)
3146                         // TODO: Find something to wait for in the case of a profile.
3147                         mCurrentUserId == msg.arg1 ? USER_COMPLETED_EVENT_DELAY_MS : 1000);
3148                 mInjector.getUserJourneyLogger().logUserLifecycleEvent(msg.arg1,
3149                         USER_LIFECYCLE_EVENT_UNLOCKED_USER, EVENT_STATE_FINISH);
3150                 // Unlocking user is not a journey no need to clear sessionId
3151                 break;
3152             case USER_CURRENT_MSG:
3153                 mInjector.batteryStatsServiceNoteEvent(
3154                         BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH,
3155                         Integer.toString(msg.arg2), msg.arg2);
3156                 mInjector.batteryStatsServiceNoteEvent(
3157                         BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
3158                         Integer.toString(msg.arg1), msg.arg1);
3159 
3160                 mInjector.getSystemServiceManager().onUserSwitching(msg.arg2, msg.arg1);
3161                 scheduleOnUserCompletedEvent(msg.arg1,
3162                         UserCompletedEventType.EVENT_TYPE_USER_SWITCHING,
3163                         USER_COMPLETED_EVENT_DELAY_MS);
3164                 break;
3165             case USER_COMPLETED_EVENT_MSG:
3166                 reportOnUserCompletedEvent((Integer) msg.obj);
3167                 break;
3168             case FOREGROUND_PROFILE_CHANGED_MSG:
3169                 dispatchForegroundProfileChanged(msg.arg1);
3170                 break;
3171             case REPORT_USER_SWITCH_COMPLETE_MSG:
3172                 dispatchUserSwitchComplete(msg.arg1, msg.arg2);
3173                 UserJourneySession session = mInjector.getUserJourneyLogger()
3174                         .logUserSwitchJourneyFinish(msg.arg1, getUserInfo(msg.arg2));
3175                 if (session != null) {
3176                     mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, session);
3177                 }
3178                 break;
3179             case REPORT_LOCKED_BOOT_COMPLETE_MSG:
3180                 dispatchLockedBootComplete(msg.arg1);
3181                 break;
3182             case START_USER_SWITCH_UI_MSG:
3183                 final Pair<UserInfo, UserInfo> fromToUserPair = (Pair<UserInfo, UserInfo>) msg.obj;
3184                 logUserJourneyBegin(fromToUserPair.second.id, USER_JOURNEY_USER_SWITCH_UI);
3185                 showUserSwitchDialog(fromToUserPair);
3186                 break;
3187             case CLEAR_USER_JOURNEY_SESSION_MSG:
3188                 mInjector.getUserJourneyLogger()
3189                         .finishAndClearIncompleteUserJourney(msg.arg1, msg.arg2);
3190                 mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, msg.obj);
3191                 break;
3192             case COMPLETE_USER_SWITCH_MSG:
3193                 completeUserSwitch(msg.arg1, msg.arg2);
3194                 break;
3195         }
3196         return false;
3197     }
3198 
3199     /**
3200      * Schedules {@link SystemServiceManager#onUserCompletedEvent()} with the given
3201      * {@link UserCompletedEventType} event, which will be combined with any other events for that
3202      * user already scheduled.
3203      * If it isn't rescheduled first, it will fire after a delayMs delay.
3204      *
3205      * @param eventType event type flags from {@link UserCompletedEventType} to append to the
3206      *                  schedule. Use 0 to schedule the ssm call without modifying the event types.
3207      */
3208     // TODO(b/197344658): Also call scheduleOnUserCompletedEvent(userId, 0, 0) after switch UX done.
3209     @VisibleForTesting
3210     void scheduleOnUserCompletedEvent(
3211             int userId, @UserCompletedEventType.EventTypesFlag int eventType, int delayMs) {
3212 
3213         if (eventType != 0) {
3214             synchronized (mCompletedEventTypes) {
3215                 mCompletedEventTypes.put(userId, mCompletedEventTypes.get(userId, 0) | eventType);
3216             }
3217         }
3218 
3219         final Object msgObj = userId;
3220         mHandler.removeEqualMessages(USER_COMPLETED_EVENT_MSG, msgObj);
3221         mHandler.sendMessageDelayed(
3222                 mHandler.obtainMessage(USER_COMPLETED_EVENT_MSG, msgObj),
3223                 delayMs);
3224     }
3225 
3226     /**
3227      * Calls {@link SystemServiceManager#onUserCompletedEvent()} for the given user, sending all the
3228      * {@link UserCompletedEventType} events that have been scheduled for it if they are still
3229      * applicable.
3230      *
3231      * Called on the mHandler thread.
3232      */
3233     @VisibleForTesting
3234     void reportOnUserCompletedEvent(Integer userId) {
3235         mHandler.removeEqualMessages(USER_COMPLETED_EVENT_MSG, userId);
3236 
3237         int eventTypes;
3238         synchronized (mCompletedEventTypes) {
3239             eventTypes = mCompletedEventTypes.get(userId, 0);
3240             mCompletedEventTypes.delete(userId);
3241         }
3242 
3243         // Now, remove any eventTypes that are no longer true.
3244         int eligibleEventTypes = 0;
3245         synchronized (mLock) {
3246             final UserState uss = mStartedUsers.get(userId);
3247             if (uss != null && uss.state != UserState.STATE_SHUTDOWN) {
3248                 eligibleEventTypes |= UserCompletedEventType.EVENT_TYPE_USER_STARTING;
3249             }
3250             if (uss != null && uss.state == STATE_RUNNING_UNLOCKED) {
3251                 eligibleEventTypes |= UserCompletedEventType.EVENT_TYPE_USER_UNLOCKED;
3252             }
3253             if (userId == mCurrentUserId) {
3254                 eligibleEventTypes |= UserCompletedEventType.EVENT_TYPE_USER_SWITCHING;
3255             }
3256         }
3257         Slogf.i(TAG, "reportOnUserCompletedEvent(%d): stored=%s, eligible=%s", userId,
3258                 Integer.toBinaryString(eventTypes), Integer.toBinaryString(eligibleEventTypes));
3259         eventTypes &= eligibleEventTypes;
3260 
3261         mInjector.systemServiceManagerOnUserCompletedEvent(userId, eventTypes);
3262     }
3263 
3264     /**
3265      * statsd helper method for logging the start of a user journey via a UserLifecycleEventOccurred
3266      * atom given the originating and targeting users for the journey.
3267      */
3268     private void logUserJourneyBegin(int targetId,
3269             @UserJourneyLogger.UserJourney int journey) {
3270         UserJourneySession oldSession = mInjector.getUserJourneyLogger()
3271                     .finishAndClearIncompleteUserJourney(targetId, journey);
3272         if (oldSession != null) {
3273             if (DEBUG_MU) {
3274                 Slogf.d(TAG,
3275                         "Starting a new journey: " + journey + " with session id: "
3276                                 + oldSession);
3277             }
3278             /*
3279              * User lifecycle journey would be complete when {@code #clearSessionId} is called
3280              * after the last expected lifecycle event for the journey. It may be possible that
3281              * the last event is not called, e.g., user not unlocked after user switching. In such
3282              * cases user journey is cleared after {@link USER_JOURNEY_TIMEOUT}.
3283              */
3284             mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, oldSession);
3285         }
3286         UserJourneySession newSession = mInjector.getUserJourneyLogger()
3287                 .logUserJourneyBegin(targetId, journey);
3288         mHandler.sendMessageDelayed(mHandler.obtainMessage(CLEAR_USER_JOURNEY_SESSION_MSG,
3289                 targetId, /* arg2= */ journey, newSession), USER_JOURNEY_TIMEOUT_MS);
3290 
3291     }
3292 
3293     private BroadcastOptions getTemporaryAppAllowlistBroadcastOptions(
3294             @PowerWhitelistManager.ReasonCode int reasonCode) {
3295         long duration = 10_000;
3296         final ActivityManagerInternal amInternal =
3297                 LocalServices.getService(ActivityManagerInternal.class);
3298         if (amInternal != null) {
3299             duration = amInternal.getBootTimeTempAllowListDuration();
3300         }
3301         final BroadcastOptions bOptions = BroadcastOptions.makeBasic();
3302         bOptions.setTemporaryAppAllowlist(duration,
3303                 TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_ALLOWED, reasonCode, "");
3304         return bOptions;
3305     }
3306 
3307     private static int getUserSwitchTimeoutMs() {
3308         final String userSwitchTimeoutMs = SystemProperties.get(
3309                 "debug.usercontroller.user_switch_timeout_ms");
3310         if (!TextUtils.isEmpty(userSwitchTimeoutMs)) {
3311             try {
3312                 return Integer.parseInt(userSwitchTimeoutMs);
3313             } catch (NumberFormatException ignored) {
3314                 // Ignored.
3315             }
3316         }
3317         return DEFAULT_USER_SWITCH_TIMEOUT_MS;
3318     }
3319 
3320     /**
3321      * Uptime when any user was being unlocked most recently. 0 if no users have been unlocked
3322      * yet. To avoid lock contention (since it's used by OomAdjuster), it's volatile internally.
3323      */
3324     public long getLastUserUnlockingUptime() {
3325         return mLastUserUnlockingUptime;
3326     }
3327 
3328     private static class UserProgressListener extends IProgressListener.Stub {
3329         private volatile long mUnlockStarted;
3330         @Override
3331         public void onStarted(int id, Bundle extras) throws RemoteException {
3332             Slogf.d(TAG, "Started unlocking user " + id);
3333             mUnlockStarted = SystemClock.uptimeMillis();
3334         }
3335 
3336         @Override
3337         public void onProgress(int id, int progress, Bundle extras) throws RemoteException {
3338             Slogf.d(TAG, "Unlocking user " + id + " progress " + progress);
3339         }
3340 
3341         @Override
3342         public void onFinished(int id, Bundle extras) throws RemoteException {
3343             long unlockTime = SystemClock.uptimeMillis() - mUnlockStarted;
3344 
3345             // Report system user unlock time to perf dashboard
3346             if (id == UserHandle.USER_SYSTEM) {
3347                 new TimingsTraceAndSlog().logDuration("SystemUserUnlock", unlockTime);
3348             } else {
3349                 new TimingsTraceAndSlog().logDuration("User" + id + "Unlock", unlockTime);
3350             }
3351         }
3352     }
3353 
3354     /**
3355      * Helper class for keeping track of user starts which are paused while user's
3356      * shutdown is taking place.
3357      */
3358     private static class PendingUserStart {
3359         public final @UserIdInt int userId;
3360         public final @UserStartMode int userStartMode;
3361         public final IProgressListener unlockListener;
3362 
3363         PendingUserStart(int userId, @UserStartMode int userStartMode,
3364                 IProgressListener unlockListener) {
3365             this.userId = userId;
3366             this.userStartMode = userStartMode;
3367             this.unlockListener = unlockListener;
3368         }
3369 
3370         @Override
3371         public String toString() {
3372             return "PendingUserStart{"
3373                     + "userId=" + userId
3374                     + ", userStartMode=" + userStartModeToString(userStartMode)
3375                     + ", unlockListener=" + unlockListener
3376                     + '}';
3377         }
3378     }
3379 
3380     @VisibleForTesting
3381     static class Injector {
3382         private final ActivityManagerService mService;
3383         private UserManagerService mUserManager;
3384         private UserManagerInternal mUserManagerInternal;
3385         private Handler mHandler;
3386         private final Object mUserSwitchingDialogLock = new Object();
3387         @GuardedBy("mUserSwitchingDialogLock")
3388         private UserSwitchingDialog mUserSwitchingDialog;
3389 
3390         Injector(ActivityManagerService service) {
3391             mService = service;
3392         }
3393 
3394         protected Handler getHandler(Handler.Callback callback) {
3395             return mHandler = new Handler(mService.mHandlerThread.getLooper(), callback);
3396         }
3397 
3398         protected Handler getUiHandler(Handler.Callback callback) {
3399             return new Handler(mService.mUiHandler.getLooper(), callback);
3400         }
3401 
3402         protected UserJourneyLogger getUserJourneyLogger() {
3403             return getUserManager().getUserJourneyLogger();
3404         }
3405 
3406         protected Context getContext() {
3407             return mService.mContext;
3408         }
3409 
3410         protected LockPatternUtils getLockPatternUtils() {
3411             return new LockPatternUtils(getContext());
3412         }
3413 
3414         protected int broadcastIntent(Intent intent, String resolvedType,
3415                 IIntentReceiver resultTo, int resultCode, String resultData,
3416                 Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
3417                 boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid,
3418                 int realCallingPid, @UserIdInt int userId) {
3419 
3420             int logUserId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3421             if (logUserId == UserHandle.USER_NULL) {
3422                 logUserId = userId;
3423             }
3424             EventLog.writeEvent(EventLogTags.UC_SEND_USER_BROADCAST, logUserId, intent.getAction());
3425 
3426             // When the modern broadcast stack is enabled, deliver all our
3427             // broadcasts as unordered, since the modern stack has better
3428             // support for sequencing cold-starts, and it supports delivering
3429             // resultTo for non-ordered broadcasts
3430             if (mService.mEnableModernQueue) {
3431                 ordered = false;
3432             }
3433 
3434             // TODO b/64165549 Verify that mLock is not held before calling AMS methods
3435             synchronized (mService) {
3436                 return mService.broadcastIntentLocked(null, null, null, intent, resolvedType,
3437                         resultTo, resultCode, resultData, resultExtras, requiredPermissions, null,
3438                         null, appOp, bOptions, ordered, sticky, callingPid, callingUid,
3439                         realCallingUid, realCallingPid, userId);
3440             }
3441         }
3442 
3443         int checkCallingPermission(String permission) {
3444             return mService.checkCallingPermission(permission);
3445         }
3446 
3447         WindowManagerService getWindowManager() {
3448             return mService.mWindowManager;
3449         }
3450 
3451         ActivityTaskManagerInternal getActivityTaskManagerInternal() {
3452             return mService.mAtmInternal;
3453         }
3454 
3455         void activityManagerOnUserStopped(@UserIdInt int userId) {
3456             LocalServices.getService(ActivityTaskManagerInternal.class).onUserStopped(userId);
3457         }
3458 
3459         void systemServiceManagerOnUserStopped(@UserIdInt int userId) {
3460             getSystemServiceManager().onUserStopped(userId);
3461         }
3462 
3463         void systemServiceManagerOnUserCompletedEvent(@UserIdInt int userId, int eventTypes) {
3464             getSystemServiceManager().onUserCompletedEvent(userId, eventTypes);
3465         }
3466 
3467         protected UserManagerService getUserManager() {
3468             if (mUserManager == null) {
3469                 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
3470                 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
3471             }
3472             return mUserManager;
3473         }
3474 
3475         UserManagerInternal getUserManagerInternal() {
3476             if (mUserManagerInternal == null) {
3477                 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3478             }
3479             return mUserManagerInternal;
3480         }
3481 
3482         KeyguardManager getKeyguardManager() {
3483             return mService.mContext.getSystemService(KeyguardManager.class);
3484         }
3485 
3486         void batteryStatsServiceNoteEvent(int code, String name, int uid) {
3487             mService.mBatteryStatsService.noteEvent(code, name, uid);
3488         }
3489 
3490         boolean isRuntimeRestarted() {
3491             return getSystemServiceManager().isRuntimeRestarted();
3492         }
3493 
3494         SystemServiceManager getSystemServiceManager() {
3495             return mService.mSystemServiceManager;
3496         }
3497 
3498         boolean isFirstBootOrUpgrade() {
3499             IPackageManager pm = AppGlobals.getPackageManager();
3500             try {
3501                 return pm.isFirstBoot() || pm.isDeviceUpgrading();
3502             } catch (RemoteException e) {
3503                 throw e.rethrowFromSystemServer();
3504             }
3505         }
3506 
3507         void sendPreBootBroadcast(@UserIdInt int userId, boolean quiet, final Runnable onFinish) {
3508             EventLog.writeEvent(EventLogTags.UC_SEND_USER_BROADCAST,
3509                     userId, Intent.ACTION_PRE_BOOT_COMPLETED);
3510             new PreBootBroadcaster(mService, userId, null, quiet) {
3511                 @Override
3512                 public void onFinished() {
3513                     onFinish.run();
3514                 }
3515             }.sendNext();
3516         }
3517 
3518         void activityManagerForceStopPackage(@UserIdInt int userId, String reason) {
3519             synchronized (mService) {
3520                 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
3521                         userId, reason);
3522             }
3523         };
3524 
3525         int checkComponentPermission(String permission, int pid, int uid, int owningUid,
3526                 boolean exported) {
3527             return mService.checkComponentPermission(permission, pid, uid, owningUid, exported);
3528         }
3529 
3530         boolean checkPermissionForPreflight(String permission, int pid, int uid, String pkg) {
3531             return  PermissionChecker.PERMISSION_GRANTED
3532                     == PermissionChecker.checkPermissionForPreflight(
3533                             getContext(), permission, pid, uid, pkg);
3534         }
3535 
3536         protected void startHomeActivity(@UserIdInt int userId, String reason) {
3537             mService.mAtmInternal.startHomeActivity(userId, reason);
3538         }
3539 
3540         void startUserWidgets(@UserIdInt int userId) {
3541             AppWidgetManagerInternal awm = LocalServices.getService(AppWidgetManagerInternal.class);
3542             if (awm != null) {
3543                 // Out of band, because this is called during a sequence with
3544                 // sensitive cross-service lock management
3545                 FgThread.getHandler().post(() -> {
3546                     awm.unlockUser(userId);
3547                 });
3548             }
3549         }
3550 
3551         void updateUserConfiguration() {
3552             mService.mAtmInternal.updateUserConfiguration();
3553         }
3554 
3555         void clearBroadcastQueueForUser(@UserIdInt int userId) {
3556             synchronized (mService) {
3557                 mService.clearBroadcastQueueForUserLocked(userId);
3558             }
3559         }
3560 
3561         void loadUserRecents(@UserIdInt int userId) {
3562             mService.mAtmInternal.loadRecentTasksForUser(userId);
3563         }
3564 
3565         void startPersistentApps(int matchFlags) {
3566             mService.startPersistentApps(matchFlags);
3567         }
3568 
3569         void installEncryptionUnawareProviders(@UserIdInt int userId) {
3570             mService.mCpHelper.installEncryptionUnawareProviders(userId);
3571         }
3572 
3573         void dismissUserSwitchingDialog(@Nullable Runnable onDismissed) {
3574             synchronized (mUserSwitchingDialogLock) {
3575                 if (mUserSwitchingDialog != null) {
3576                     mUserSwitchingDialog.dismiss(onDismissed);
3577                     mUserSwitchingDialog = null;
3578                 } else if (onDismissed != null) {
3579                     onDismissed.run();
3580                 }
3581             }
3582         }
3583 
3584         void showUserSwitchingDialog(UserInfo fromUser, UserInfo toUser,
3585                 String switchingFromSystemUserMessage, String switchingToSystemUserMessage,
3586                 @NonNull Runnable onShown) {
3587             if (mService.mContext.getPackageManager()
3588                     .hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
3589                 // config_customUserSwitchUi is set to true on Automotive as CarSystemUI is
3590                 // responsible to show the UI; OEMs should not change that, but if they do, we
3591                 // should at least warn the user...
3592                 Slogf.w(TAG, "Showing user switch dialog on UserController, it could cause a race "
3593                         + "condition if it's shown by CarSystemUI as well");
3594             }
3595             synchronized (mUserSwitchingDialogLock) {
3596                 dismissUserSwitchingDialog(null);
3597                 mUserSwitchingDialog = new UserSwitchingDialog(mService.mContext, fromUser, toUser,
3598                         switchingFromSystemUserMessage, switchingToSystemUserMessage,
3599                         getWindowManager());
3600                 mUserSwitchingDialog.show(onShown);
3601             }
3602         }
3603 
3604         void reportGlobalUsageEvent(int event) {
3605             mService.reportGlobalUsageEvent(event);
3606         }
3607 
3608         void reportCurWakefulnessUsageEvent() {
3609             mService.reportCurWakefulnessUsageEvent();
3610         }
3611 
3612         void taskSupervisorRemoveUser(@UserIdInt int userId) {
3613             mService.mAtmInternal.removeUser(userId);
3614         }
3615 
3616         protected boolean taskSupervisorSwitchUser(@UserIdInt int userId, UserState uss) {
3617             return mService.mAtmInternal.switchUser(userId, uss);
3618         }
3619 
3620         protected void taskSupervisorResumeFocusedStackTopActivity() {
3621             mService.mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
3622         }
3623 
3624         protected void clearAllLockedTasks(String reason) {
3625             mService.mAtmInternal.clearLockedTasks(reason);
3626         }
3627 
3628         boolean isCallerRecents(int callingUid) {
3629             return mService.mAtmInternal.isCallerRecents(callingUid);
3630         }
3631 
3632         protected IStorageManager getStorageManager() {
3633             return IStorageManager.Stub.asInterface(ServiceManager.getService("mount"));
3634         }
3635 
3636         protected void dismissKeyguard(Runnable runnable) {
3637             final AtomicBoolean isFirst = new AtomicBoolean(true);
3638             final Runnable runOnce = () -> {
3639                 if (isFirst.getAndSet(false)) {
3640                     runnable.run();
3641                 }
3642             };
3643 
3644             mHandler.postDelayed(runOnce, DISMISS_KEYGUARD_TIMEOUT_MS);
3645             getWindowManager().dismissKeyguard(new IKeyguardDismissCallback.Stub() {
3646                 @Override
3647                 public void onDismissError() throws RemoteException {
3648                     mHandler.post(runOnce);
3649                 }
3650 
3651                 @Override
3652                 public void onDismissSucceeded() throws RemoteException {
3653                     mHandler.post(runOnce);
3654                 }
3655 
3656                 @Override
3657                 public void onDismissCancelled() throws RemoteException {
3658                     mHandler.post(runOnce);
3659                 }
3660             }, /* message= */ null);
3661         }
3662 
3663         boolean isHeadlessSystemUserMode() {
3664             return UserManager.isHeadlessSystemUserMode();
3665         }
3666 
3667         boolean isUsersOnSecondaryDisplaysEnabled() {
3668             return UserManager.isVisibleBackgroundUsersEnabled();
3669         }
3670 
3671         void onUserStarting(@UserIdInt int userId) {
3672             getSystemServiceManager().onUserStarting(TimingsTraceAndSlog.newAsyncLog(), userId);
3673         }
3674 
3675         void onSystemUserVisibilityChanged(boolean visible) {
3676             getUserManagerInternal().onSystemUserVisibilityChanged(visible);
3677         }
3678 
3679         void lockDeviceNowAndWaitForKeyguardShown() {
3680             if (getWindowManager().isKeyguardLocked()) {
3681                 return;
3682             }
3683 
3684             final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3685             t.traceBegin("lockDeviceNowAndWaitForKeyguardShown");
3686 
3687             final CountDownLatch latch = new CountDownLatch(1);
3688             ActivityTaskManagerInternal.ScreenObserver screenObserver =
3689                     new ActivityTaskManagerInternal.ScreenObserver() {
3690                         @Override
3691                         public void onAwakeStateChanged(boolean isAwake) {
3692 
3693                         }
3694 
3695                         @Override
3696                         public void onKeyguardStateChanged(boolean isShowing) {
3697                             if (isShowing) {
3698                                 latch.countDown();
3699                             }
3700                         }
3701                     };
3702 
3703             getActivityTaskManagerInternal().registerScreenObserver(screenObserver);
3704             getWindowManager().lockDeviceNow();
3705             try {
3706                 if (!latch.await(20, TimeUnit.SECONDS)) {
3707                     throw new RuntimeException("Keyguard is not shown in 20 seconds");
3708                 }
3709             } catch (InterruptedException e) {
3710                 throw new RuntimeException(e);
3711             } finally {
3712                 getActivityTaskManagerInternal().unregisterScreenObserver(screenObserver);
3713                 t.traceEnd();
3714             }
3715         }
3716     }
3717 }
3718