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