• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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.wm;
18 
19 import android.content.ComponentName;
20 import android.os.Process;
21 import android.service.vr.IPersistentVrStateCallbacks;
22 import android.util.Slog;
23 import android.util.proto.ProtoOutputStream;
24 import android.util.proto.ProtoUtils;
25 
26 import com.android.server.LocalServices;
27 import com.android.server.am.ActivityManagerService;
28 import com.android.server.am.ProcessList;
29 import com.android.server.am.VrControllerProto;
30 import com.android.server.vr.VrManagerInternal;
31 
32 /**
33  * Helper class for {@link ActivityManagerService} responsible for VrMode-related ActivityManager
34  * functionality.
35  *
36  * <p>Specifically, this class is responsible for:
37  * <ul>
38  * <li>Adjusting the scheduling of VR render threads while in VR mode.
39  * <li>Handling ActivityManager calls to set a VR or a 'persistent' VR thread.
40  * <li>Tracking the state of ActivityManagerService's view of VR-related behavior flags.
41  * </ul>
42  *
43  * <p>This is NOT the class that manages the system VR mode lifecycle. The class responsible for
44  * handling everything related to VR mode state changes (e.g. the lifecycles of the associated
45  * VrListenerService, VrStateCallbacks, VR HAL etc.) is VrManagerService.
46  *
47  * <p>This class is exclusively for use by ActivityManagerService. Do not add callbacks or other
48  * functionality to this for things that belong in VrManagerService.
49  */
50 final class VrController {
51     private static final String TAG = "VrController";
52 
53     // VR state flags.
54     private static final int FLAG_NON_VR_MODE = 0;
55     private static final int FLAG_VR_MODE = 1;
56     private static final int FLAG_PERSISTENT_VR_MODE = 2;
57 
58     // Keep the enum lists in sync
59     private static int[] ORIG_ENUMS = new int[] {
60             FLAG_NON_VR_MODE,
61             FLAG_VR_MODE,
62             FLAG_PERSISTENT_VR_MODE,
63     };
64     private static int[] PROTO_ENUMS = new int[] {
65             VrControllerProto.FLAG_NON_VR_MODE,
66             VrControllerProto.FLAG_VR_MODE,
67             VrControllerProto.FLAG_PERSISTENT_VR_MODE,
68     };
69 
70     // Invariants maintained for mVrState
71     //
72     //   Always true:
73     //      - Only a single VR-related thread will have elevated scheduling priorities at a time
74     //        across all threads in all processes (and for all possible running modes).
75     //
76     //   Always true while FLAG_PERSISTENT_VR_MODE is set:
77     //      - An application has set a flag to run in persistent VR mode the next time VR mode is
78     //        entered. The device may or may not be in VR mode.
79     //      - mVrState will contain FLAG_PERSISTENT_VR_MODE
80     //      - An application may set a persistent VR thread that gains elevated scheduling
81     //        priorities via a call to setPersistentVrThread.
82     //      - Calls to set a regular (non-persistent) VR thread via setVrThread will fail, and
83     //        thread that had previously elevated its scheduling priority in this way is returned
84     //        to its normal scheduling priority.
85     //
86     //   Always true while FLAG_VR_MODE is set:
87     //      - The current top application is running in VR mode.
88     //      - mVrState will contain FLAG_VR_MODE
89     //
90     //   While FLAG_VR_MODE is set without FLAG_PERSISTENT_VR_MODE:
91     //      - The current top application may set one of its threads to run at an elevated
92     //        scheduling priority via a call to setVrThread.
93     //
94     //   While FLAG_VR_MODE is set with FLAG_PERSISTENT_VR_MODE:
95     //      - The current top application may NOT set one of its threads to run at an elevated
96     //        scheduling priority via a call to setVrThread (instead, the persistent VR thread will
97     //        be kept if an application has set one).
98     //
99     //   While mVrState == FLAG_NON_VR_MODE:
100     //      - Calls to setVrThread will fail.
101     //      - Calls to setPersistentVrThread will fail.
102     //      - No threads will have elevated scheduling priority for VR.
103     //
104     private int mVrState = FLAG_NON_VR_MODE;
105 
106     // The single VR render thread on the device that is given elevated scheduling priority.
107     private int mVrRenderThreadTid = 0;
108 
109     private final Object mGlobalAmLock;
110 
111     private final IPersistentVrStateCallbacks mPersistentVrModeListener =
112             new IPersistentVrStateCallbacks.Stub() {
113         @Override
114         public void onPersistentVrStateChanged(boolean enabled) {
115             synchronized(mGlobalAmLock) {
116                 // Note: This is the only place where mVrState should have its
117                 // FLAG_PERSISTENT_VR_MODE setting changed.
118                 if (enabled) {
119                     setVrRenderThreadLocked(0, ProcessList.SCHED_GROUP_TOP_APP, true);
120                     mVrState |= FLAG_PERSISTENT_VR_MODE;
121                 } else {
122                     setPersistentVrRenderThreadLocked(0, true);
123                     mVrState &= ~FLAG_PERSISTENT_VR_MODE;
124                 }
125             }
126         }
127     };
128 
129     /**
130      * Create new VrController instance.
131      *
132      * @param globalAmLock the global ActivityManagerService lock.
133      */
VrController(final Object globalAmLock)134     public VrController(final Object globalAmLock) {
135         mGlobalAmLock = globalAmLock;
136     }
137 
138     /**
139      * Called when ActivityManagerService receives its systemReady call during boot.
140      */
onSystemReady()141     public void onSystemReady() {
142         VrManagerInternal vrManagerInternal = LocalServices.getService(VrManagerInternal.class);
143         if (vrManagerInternal != null) {
144             vrManagerInternal.addPersistentVrModeStateListener(mPersistentVrModeListener);
145         }
146     }
147 
148     /**
149      * Called when ActivityManagerService's TOP_APP process has changed.
150      *
151      * <p>Note: This must be called with the global ActivityManagerService lock held.
152      *
153      * @param proc is the WindowProcessController of the process that entered or left the TOP_APP
154      *            scheduling group.
155      */
onTopProcChangedLocked(WindowProcessController proc)156     public void onTopProcChangedLocked(WindowProcessController proc) {
157         final int curSchedGroup = proc.getCurrentSchedulingGroup();
158         if (curSchedGroup == ProcessList.SCHED_GROUP_TOP_APP) {
159             setVrRenderThreadLocked(proc.mVrThreadTid, curSchedGroup, true);
160         } else {
161             if (proc.mVrThreadTid == mVrRenderThreadTid) {
162                 clearVrRenderThreadLocked(true);
163             }
164         }
165     }
166 
167     /**
168      * Called when ActivityManagerService is switching VR mode for the TOP_APP process.
169      *
170      * @param record the ActivityRecord of the activity changing the system VR mode.
171      * @return {@code true} if the VR state changed.
172      */
onVrModeChanged(ActivityRecord record)173     public boolean onVrModeChanged(ActivityRecord record) {
174         // This message means that the top focused activity enabled VR mode (or an activity
175         // that previously set this has become focused).
176         VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
177         if (vrService == null) {
178             // VR mode isn't supported on this device.
179             return false;
180         }
181         boolean vrMode;
182         ComponentName requestedPackage;
183         ComponentName callingPackage;
184         int userId;
185         int processId = -1;
186         boolean changed = false;
187         synchronized (mGlobalAmLock) {
188             vrMode = record.requestedVrComponent != null;
189             requestedPackage = record.requestedVrComponent;
190             userId = record.mUserId;
191             callingPackage = record.info.getComponentName();
192 
193             // Tell the VrController that a VR mode change is requested.
194             changed = changeVrModeLocked(vrMode, record.app);
195 
196             if (record.app != null) {
197                 processId = record.app.getPid();
198             }
199         }
200 
201         // Tell VrManager that a VR mode changed is requested, VrManager will handle
202         // notifying all non-AM dependencies if needed.
203         vrService.setVrMode(vrMode, requestedPackage, userId, processId, callingPackage);
204         return changed;
205     }
206 
207     /**
208      * Called to set an application's VR thread.
209      *
210      * <p>This will fail if the system is not in VR mode, the system has the persistent VR flag set,
211      * or the scheduling group of the thread is not for the current top app.  If this succeeds, any
212      * previous VR thread will be returned to a normal sheduling priority; if this fails, the
213      * scheduling for the previous thread will be unaffected.
214      *
215      * <p>Note: This must be called with the global ActivityManagerService lock and the
216      *     mPidsSelfLocked object locks held.
217      *
218      * @param tid the tid of the thread to set, or 0 to unset the current thread.
219      * @param pid the pid of the process owning the thread to set.
220      * @param proc the WindowProcessController of the process owning the thread to set.
221      */
setVrThreadLocked(int tid, int pid, WindowProcessController proc)222     public void setVrThreadLocked(int tid, int pid, WindowProcessController proc) {
223         if (hasPersistentVrFlagSet()) {
224             Slog.w(TAG, "VR thread cannot be set in persistent VR mode!");
225             return;
226         }
227         if (proc == null) {
228            Slog.w(TAG, "Persistent VR thread not set, calling process doesn't exist!");
229            return;
230         }
231         if (tid != 0) {
232             enforceThreadInProcess(tid, pid);
233         }
234         if (!inVrMode()) {
235             Slog.w(TAG, "VR thread cannot be set when not in VR mode!");
236         } else {
237             setVrRenderThreadLocked(tid, proc.getCurrentSchedulingGroup(), false);
238         }
239         proc.mVrThreadTid = (tid > 0) ? tid : 0;
240     }
241 
242     /**
243      * Called to set an application's persistent VR thread.
244      *
245      * <p>This will fail if the system does not have the persistent VR flag set. If this succeeds,
246      * any previous VR thread will be returned to a normal sheduling priority; if this fails,
247      * the scheduling for the previous thread will be unaffected.
248      *
249      * <p>Note: This must be called with the global ActivityManagerService lock and the
250      *     mPidsSelfLocked object locks held.
251      *
252      * @param tid the tid of the thread to set, or 0 to unset the current thread.
253      * @param pid the pid of the process owning the thread to set.
254      * @param proc the process owning the thread to set.
255      */
setPersistentVrThreadLocked(int tid, int pid, WindowProcessController proc)256     public void setPersistentVrThreadLocked(int tid, int pid, WindowProcessController proc) {
257         if (!hasPersistentVrFlagSet()) {
258             Slog.w(TAG, "Persistent VR thread may only be set in persistent VR mode!");
259             return;
260         }
261         if (proc == null) {
262            Slog.w(TAG, "Persistent VR thread not set, calling process doesn't exist!");
263            return;
264         }
265         if (tid != 0) {
266             enforceThreadInProcess(tid, pid);
267         }
268         setPersistentVrRenderThreadLocked(tid, false);
269     }
270 
271     /**
272      * Return {@code true} when UI features incompatible with VR mode should be disabled.
273      *
274      * <p>Note: This must be called with the global ActivityManagerService lock held.
275      */
shouldDisableNonVrUiLocked()276     public boolean shouldDisableNonVrUiLocked() {
277         return mVrState != FLAG_NON_VR_MODE;
278     }
279 
280     /**
281      * Called when to update this VrController instance's state when the system VR mode is being
282      * changed.
283      *
284      * <p>Note: This must be called with the global ActivityManagerService lock held.
285      *
286      * @param vrMode {@code true} if the system VR mode is being enabled.
287      * @param proc the WindowProcessController of the process enabling the system VR mode.
288      *
289      * @return {@code true} if our state changed.
290      */
changeVrModeLocked(boolean vrMode, WindowProcessController proc)291     private boolean changeVrModeLocked(boolean vrMode, WindowProcessController proc) {
292         final int oldVrState = mVrState;
293 
294         // This is the only place where mVrState should have its FLAG_VR_MODE setting
295         // changed.
296         if (vrMode) {
297             mVrState |= FLAG_VR_MODE;
298         } else {
299             mVrState &= ~FLAG_VR_MODE;
300         }
301 
302         boolean changed = (oldVrState != mVrState);
303 
304         if (changed) {
305             if (proc != null) {
306                 if (proc.mVrThreadTid > 0) {
307                     setVrRenderThreadLocked(
308                             proc.mVrThreadTid, proc.getCurrentSchedulingGroup(), false);
309                 }
310             } else {
311               clearVrRenderThreadLocked(false);
312             }
313         }
314         return changed;
315     }
316 
317     /**
318      * Set the given thread as the new VR thread, and give it special scheduling priority.
319      *
320      * <p>If the current thread is this thread, do nothing. If the current thread is different from
321      * the given thread, the current thread will be returned to a normal scheduling priority.
322      *
323      * @param newTid the tid of the thread to set, or 0 to unset the current thread.
324      * @param suppressLogs {@code true} if any error logging should be disabled.
325      *
326      * @return the tid of the thread configured to run at the scheduling priority for VR
327      *          mode after this call completes (this may be the previous thread).
328      */
updateVrRenderThreadLocked(int newTid, boolean suppressLogs)329     private int updateVrRenderThreadLocked(int newTid, boolean suppressLogs) {
330         if (mVrRenderThreadTid == newTid) {
331             return mVrRenderThreadTid;
332         }
333 
334         if (mVrRenderThreadTid > 0) {
335             ActivityManagerService.scheduleAsRegularPriority(mVrRenderThreadTid, suppressLogs);
336             mVrRenderThreadTid = 0;
337         }
338 
339         if (newTid > 0) {
340             mVrRenderThreadTid = newTid;
341             ActivityManagerService.scheduleAsFifoPriority(mVrRenderThreadTid, suppressLogs);
342         }
343         return mVrRenderThreadTid;
344     }
345 
346     /**
347      * Set special scheduling for the given application persistent VR thread, if allowed.
348      *
349      * <p>This will fail if the system does not have the persistent VR flag set. If this succeeds,
350      * any previous VR thread will be returned to a normal sheduling priority; if this fails,
351      * the scheduling for the previous thread will be unaffected.
352      *
353      * @param newTid the tid of the thread to set, or 0 to unset the current thread.
354      * @param suppressLogs {@code true} if any error logging should be disabled.
355      *
356      * @return the tid of the thread configured to run at the scheduling priority for VR
357      *          mode after this call completes (this may be the previous thread).
358      */
setPersistentVrRenderThreadLocked(int newTid, boolean suppressLogs)359     private int setPersistentVrRenderThreadLocked(int newTid, boolean suppressLogs) {
360        if (!hasPersistentVrFlagSet()) {
361             if (!suppressLogs) {
362                 Slog.w(TAG, "Failed to set persistent VR thread, "
363                         + "system not in persistent VR mode.");
364             }
365             return mVrRenderThreadTid;
366         }
367         return updateVrRenderThreadLocked(newTid, suppressLogs);
368     }
369 
370     /**
371      * Set special scheduling for the given application VR thread, if allowed.
372      *
373      * <p>This will fail if the system is not in VR mode, the system has the persistent VR flag set,
374      * or the scheduling group of the thread is not for the current top app.  If this succeeds, any
375      * previous VR thread will be returned to a normal sheduling priority; if this fails, the
376      * scheduling for the previous thread will be unaffected.
377      *
378      * @param newTid the tid of the thread to set, or 0 to unset the current thread.
379      * @param schedGroup the current scheduling group of the thread to set.
380      * @param suppressLogs {@code true} if any error logging should be disabled.
381      *
382      * @return the tid of the thread configured to run at the scheduling priority for VR
383      *          mode after this call completes (this may be the previous thread).
384      */
setVrRenderThreadLocked(int newTid, int schedGroup, boolean suppressLogs)385     private int setVrRenderThreadLocked(int newTid, int schedGroup, boolean suppressLogs) {
386         boolean inVr = inVrMode();
387         boolean inPersistentVr = hasPersistentVrFlagSet();
388         if (!inVr || inPersistentVr || schedGroup != ProcessList.SCHED_GROUP_TOP_APP) {
389             if (!suppressLogs) {
390                String reason = "caller is not the current top application.";
391                if (!inVr) {
392                    reason = "system not in VR mode.";
393                } else if (inPersistentVr) {
394                    reason = "system in persistent VR mode.";
395                }
396                Slog.w(TAG, "Failed to set VR thread, " + reason);
397             }
398             return mVrRenderThreadTid;
399         }
400         return updateVrRenderThreadLocked(newTid, suppressLogs);
401     }
402 
403     /**
404      * Unset any special scheduling used for the current VR render thread, and return it to normal
405      * scheduling priority.
406      *
407      * @param suppressLogs {@code true} if any error logging should be disabled.
408      */
clearVrRenderThreadLocked(boolean suppressLogs)409     private void clearVrRenderThreadLocked(boolean suppressLogs) {
410         updateVrRenderThreadLocked(0, suppressLogs);
411     }
412 
413     /**
414      * Check that the given tid is running in the process for the given pid, and throw an exception
415      * if not.
416      */
enforceThreadInProcess(int tid, int pid)417     private void enforceThreadInProcess(int tid, int pid) {
418         if (!Process.isThreadInProcess(pid, tid)) {
419             throw new IllegalArgumentException("VR thread does not belong to process");
420         }
421     }
422 
423     /**
424      * True when the system is in VR mode.
425      */
inVrMode()426     private boolean inVrMode() {
427         return (mVrState & FLAG_VR_MODE) != 0;
428     }
429 
430     /**
431      * True when the persistent VR mode flag has been set.
432      *
433      * Note: Currently this does not necessarily mean that the system is in VR mode.
434      */
hasPersistentVrFlagSet()435     private boolean hasPersistentVrFlagSet() {
436         return (mVrState & FLAG_PERSISTENT_VR_MODE) != 0;
437     }
438 
439     @Override
toString()440     public String toString() {
441       return String.format("[VrState=0x%x,VrRenderThreadTid=%d]", mVrState, mVrRenderThreadTid);
442     }
443 
writeToProto(ProtoOutputStream proto, long fieldId)444     void writeToProto(ProtoOutputStream proto, long fieldId) {
445         final long token = proto.start(fieldId);
446         ProtoUtils.writeBitWiseFlagsToProtoEnum(proto, VrControllerProto.VR_MODE,
447                 mVrState, ORIG_ENUMS, PROTO_ENUMS);
448         proto.write(VrControllerProto.RENDER_THREAD_ID, mVrRenderThreadTid);
449         proto.end(token);
450     }
451 }
452