xref: /aosp_15_r20/frameworks/av/services/audioflinger/fastpath/StateQueue.h (revision ec779b8e0859a360c3d303172224686826e6e0e1)
1*ec779b8eSAndroid Build Coastguard Worker /*
2*ec779b8eSAndroid Build Coastguard Worker  * Copyright (C) 2012 The Android Open Source Project
3*ec779b8eSAndroid Build Coastguard Worker  *
4*ec779b8eSAndroid Build Coastguard Worker  * Licensed under the Apache License, Version 2.0 (the "License");
5*ec779b8eSAndroid Build Coastguard Worker  * you may not use this file except in compliance with the License.
6*ec779b8eSAndroid Build Coastguard Worker  * You may obtain a copy of the License at
7*ec779b8eSAndroid Build Coastguard Worker  *
8*ec779b8eSAndroid Build Coastguard Worker  *      http://www.apache.org/licenses/LICENSE-2.0
9*ec779b8eSAndroid Build Coastguard Worker  *
10*ec779b8eSAndroid Build Coastguard Worker  * Unless required by applicable law or agreed to in writing, software
11*ec779b8eSAndroid Build Coastguard Worker  * distributed under the License is distributed on an "AS IS" BASIS,
12*ec779b8eSAndroid Build Coastguard Worker  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*ec779b8eSAndroid Build Coastguard Worker  * See the License for the specific language governing permissions and
14*ec779b8eSAndroid Build Coastguard Worker  * limitations under the License.
15*ec779b8eSAndroid Build Coastguard Worker  */
16*ec779b8eSAndroid Build Coastguard Worker 
17*ec779b8eSAndroid Build Coastguard Worker #pragma once
18*ec779b8eSAndroid Build Coastguard Worker 
19*ec779b8eSAndroid Build Coastguard Worker #include <stdatomic.h>
20*ec779b8eSAndroid Build Coastguard Worker 
21*ec779b8eSAndroid Build Coastguard Worker // The state queue template class was originally driven by this use case / requirements:
22*ec779b8eSAndroid Build Coastguard Worker //  There are two threads: a fast mixer, and a normal mixer, and they share state.
23*ec779b8eSAndroid Build Coastguard Worker //  The interesting part of the shared state is a set of active fast tracks,
24*ec779b8eSAndroid Build Coastguard Worker //  and the output HAL configuration (buffer size in frames, sample rate, etc.).
25*ec779b8eSAndroid Build Coastguard Worker //  Fast mixer thread:
26*ec779b8eSAndroid Build Coastguard Worker //      periodic with typical period < 10 ms
27*ec779b8eSAndroid Build Coastguard Worker //      FIFO/RR scheduling policy and a low fixed priority
28*ec779b8eSAndroid Build Coastguard Worker //      ok to block for bounded time using nanosleep() to achieve desired period
29*ec779b8eSAndroid Build Coastguard Worker //      must not block on condition wait, mutex lock, atomic operation spin, I/O, etc.
30*ec779b8eSAndroid Build Coastguard Worker //        under typical operations of mixing, writing, or adding/removing tracks
31*ec779b8eSAndroid Build Coastguard Worker //      ok to block for unbounded time when the output HAL configuration changes,
32*ec779b8eSAndroid Build Coastguard Worker //        and this may result in an audible artifact
33*ec779b8eSAndroid Build Coastguard Worker //      needs read-only access to a recent stable state,
34*ec779b8eSAndroid Build Coastguard Worker //        but not necessarily the most current one
35*ec779b8eSAndroid Build Coastguard Worker //      only allocate and free memory when configuration changes
36*ec779b8eSAndroid Build Coastguard Worker //      avoid conventional logging, as this is a form of I/O and could block
37*ec779b8eSAndroid Build Coastguard Worker //      defer computation to other threads when feasible; for example
38*ec779b8eSAndroid Build Coastguard Worker //        cycle times are collected by fast mixer thread but the floating-point
39*ec779b8eSAndroid Build Coastguard Worker //        statistical calculations on these cycle times are computed by normal mixer
40*ec779b8eSAndroid Build Coastguard Worker //      these requirements also apply to callouts such as AudioBufferProvider and VolumeProvider
41*ec779b8eSAndroid Build Coastguard Worker //  Normal mixer thread:
42*ec779b8eSAndroid Build Coastguard Worker //      periodic with typical period ~20 ms
43*ec779b8eSAndroid Build Coastguard Worker //      SCHED_OTHER scheduling policy and nice priority == urgent audio
44*ec779b8eSAndroid Build Coastguard Worker //      ok to block, but prefer to avoid as much as possible
45*ec779b8eSAndroid Build Coastguard Worker //      needs read/write access to state
46*ec779b8eSAndroid Build Coastguard Worker //  The normal mixer may need to temporarily suspend the fast mixer thread during mode changes.
47*ec779b8eSAndroid Build Coastguard Worker //  It will do this using the state -- one of the fields tells the fast mixer to idle.
48*ec779b8eSAndroid Build Coastguard Worker 
49*ec779b8eSAndroid Build Coastguard Worker // Additional requirements:
50*ec779b8eSAndroid Build Coastguard Worker //  - observer must always be able to poll for and view the latest pushed state; it must never be
51*ec779b8eSAndroid Build Coastguard Worker //    blocked from seeing that state
52*ec779b8eSAndroid Build Coastguard Worker //  - observer does not need to see every state in sequence; it is OK for it to skip states
53*ec779b8eSAndroid Build Coastguard Worker //    [see below for more on this]
54*ec779b8eSAndroid Build Coastguard Worker //  - mutator must always be able to read/modify a state, it must never be blocked from reading or
55*ec779b8eSAndroid Build Coastguard Worker //    modifying state
56*ec779b8eSAndroid Build Coastguard Worker //  - reduce memcpy where possible
57*ec779b8eSAndroid Build Coastguard Worker //  - work well if the observer runs more frequently than the mutator,
58*ec779b8eSAndroid Build Coastguard Worker //    as is the case with fast mixer/normal mixer.
59*ec779b8eSAndroid Build Coastguard Worker // It is not a requirement to work well if the roles were reversed,
60*ec779b8eSAndroid Build Coastguard Worker // and the mutator were to run more frequently than the observer.
61*ec779b8eSAndroid Build Coastguard Worker // In this case, the mutator could get blocked waiting for a slot to fill up for
62*ec779b8eSAndroid Build Coastguard Worker // it to work with. This could be solved somewhat by increasing the depth of the queue, but it would
63*ec779b8eSAndroid Build Coastguard Worker // still limit the mutator to a finite number of changes before it would block.  A future
64*ec779b8eSAndroid Build Coastguard Worker // possibility, not implemented here, would be to allow the mutator to safely overwrite an already
65*ec779b8eSAndroid Build Coastguard Worker // pushed state. This could be done by the mutator overwriting mNext, but then being prepared to
66*ec779b8eSAndroid Build Coastguard Worker // read an mAck which is actually for the earlier mNext (since there is a race).
67*ec779b8eSAndroid Build Coastguard Worker 
68*ec779b8eSAndroid Build Coastguard Worker // Solution:
69*ec779b8eSAndroid Build Coastguard Worker //  Let's call the fast mixer thread the "observer" and normal mixer thread the "mutator".
70*ec779b8eSAndroid Build Coastguard Worker //  We assume there is only a single observer and a single mutator; this is critical.
71*ec779b8eSAndroid Build Coastguard Worker //  Each state is of type <T>, and should contain only POD (Plain Old Data) and raw pointers, as
72*ec779b8eSAndroid Build Coastguard Worker //  memcpy() may be used to copy state, and the destructors are run in unpredictable order.
73*ec779b8eSAndroid Build Coastguard Worker //  The states in chronological order are: previous, current, next, and mutating:
74*ec779b8eSAndroid Build Coastguard Worker //      previous    read-only, observer can compare vs. current to see the subset that changed
75*ec779b8eSAndroid Build Coastguard Worker //      current     read-only, this is the primary state for observer
76*ec779b8eSAndroid Build Coastguard Worker //      next        read-only, when observer is ready to accept a new state it will shift it in:
77*ec779b8eSAndroid Build Coastguard Worker //                      previous = current
78*ec779b8eSAndroid Build Coastguard Worker //                      current = next
79*ec779b8eSAndroid Build Coastguard Worker //                  and the slot formerly used by previous is now available to the mutator.
80*ec779b8eSAndroid Build Coastguard Worker //      mutating    invisible to observer, read/write to mutator
81*ec779b8eSAndroid Build Coastguard Worker //  Initialization is tricky, especially for the observer.  If the observer starts execution
82*ec779b8eSAndroid Build Coastguard Worker //  before the mutator, there are no previous, current, or next states.  And even if the observer
83*ec779b8eSAndroid Build Coastguard Worker //  starts execution after the mutator, there is a next state but no previous or current states.
84*ec779b8eSAndroid Build Coastguard Worker //  To solve this, we'll have the observer idle until there is a next state,
85*ec779b8eSAndroid Build Coastguard Worker //  and it will have to deal with the case where there is no previous state.
86*ec779b8eSAndroid Build Coastguard Worker //  The states are stored in a shared FIFO queue represented using a circular array.
87*ec779b8eSAndroid Build Coastguard Worker //  The observer polls for mutations, and receives a new state pointer after a
88*ec779b8eSAndroid Build Coastguard Worker //  a mutation is pushed onto the queue.  To the observer, the state pointers are
89*ec779b8eSAndroid Build Coastguard Worker //  effectively in random order, that is the observer should not do address
90*ec779b8eSAndroid Build Coastguard Worker //  arithmetic on the state pointers.  However to the mutator, the state pointers
91*ec779b8eSAndroid Build Coastguard Worker //  are in a definite circular order.
92*ec779b8eSAndroid Build Coastguard Worker 
93*ec779b8eSAndroid Build Coastguard Worker #include "Configuration.h"
94*ec779b8eSAndroid Build Coastguard Worker 
95*ec779b8eSAndroid Build Coastguard Worker namespace android {
96*ec779b8eSAndroid Build Coastguard Worker 
97*ec779b8eSAndroid Build Coastguard Worker #ifdef STATE_QUEUE_DUMP
98*ec779b8eSAndroid Build Coastguard Worker // The StateQueueObserverDump and StateQueueMutatorDump keep
99*ec779b8eSAndroid Build Coastguard Worker // a cache of StateQueue statistics that can be logged by dumpsys.
100*ec779b8eSAndroid Build Coastguard Worker // Each individual native word-sized field is accessed atomically.  But the
101*ec779b8eSAndroid Build Coastguard Worker // overall structure is non-atomic, that is there may be an inconsistency between fields.
102*ec779b8eSAndroid Build Coastguard Worker // No barriers or locks are used for either writing or reading.
103*ec779b8eSAndroid Build Coastguard Worker // Only POD types are permitted, and the contents shouldn't be trusted (i.e. do range checks).
104*ec779b8eSAndroid Build Coastguard Worker // It has a different lifetime than the StateQueue, and so it can't be a member of StateQueue.
105*ec779b8eSAndroid Build Coastguard Worker 
106*ec779b8eSAndroid Build Coastguard Worker struct StateQueueObserverDump {
StateQueueObserverDumpStateQueueObserverDump107*ec779b8eSAndroid Build Coastguard Worker     StateQueueObserverDump() : mStateChanges(0) { }
~StateQueueObserverDumpStateQueueObserverDump108*ec779b8eSAndroid Build Coastguard Worker     /*virtual*/ ~StateQueueObserverDump() { }
109*ec779b8eSAndroid Build Coastguard Worker     unsigned    mStateChanges;    // incremented each time poll() detects a state change
110*ec779b8eSAndroid Build Coastguard Worker     void        dump(int fd);
111*ec779b8eSAndroid Build Coastguard Worker };
112*ec779b8eSAndroid Build Coastguard Worker 
113*ec779b8eSAndroid Build Coastguard Worker struct StateQueueMutatorDump {
StateQueueMutatorDumpStateQueueMutatorDump114*ec779b8eSAndroid Build Coastguard Worker     StateQueueMutatorDump() : mPushDirty(0), mPushAck(0), mBlockedSequence(0) { }
~StateQueueMutatorDumpStateQueueMutatorDump115*ec779b8eSAndroid Build Coastguard Worker     /*virtual*/ ~StateQueueMutatorDump() { }
116*ec779b8eSAndroid Build Coastguard Worker     unsigned    mPushDirty;       // incremented each time push() is called with a dirty state
117*ec779b8eSAndroid Build Coastguard Worker     unsigned    mPushAck;         // incremented each time push(BLOCK_UNTIL_ACKED) is called
118*ec779b8eSAndroid Build Coastguard Worker     unsigned    mBlockedSequence; // incremented before and after each time that push()
119*ec779b8eSAndroid Build Coastguard Worker                                   // blocks for more than one PUSH_BLOCK_ACK_NS;
120*ec779b8eSAndroid Build Coastguard Worker                                   // if odd, then mutator is currently blocked inside push()
121*ec779b8eSAndroid Build Coastguard Worker     void        dump(int fd);
122*ec779b8eSAndroid Build Coastguard Worker };
123*ec779b8eSAndroid Build Coastguard Worker #endif
124*ec779b8eSAndroid Build Coastguard Worker 
125*ec779b8eSAndroid Build Coastguard Worker // manages a FIFO queue of states
126*ec779b8eSAndroid Build Coastguard Worker // marking as final to avoid derived classes as there are no virtuals.
127*ec779b8eSAndroid Build Coastguard Worker template<typename T> class StateQueue final {
128*ec779b8eSAndroid Build Coastguard Worker 
129*ec779b8eSAndroid Build Coastguard Worker public:
130*ec779b8eSAndroid Build Coastguard Worker     // Observer APIs
131*ec779b8eSAndroid Build Coastguard Worker 
132*ec779b8eSAndroid Build Coastguard Worker     // Poll for a state change.  Returns a pointer to a read-only state,
133*ec779b8eSAndroid Build Coastguard Worker     // or NULL if the state has not been initialized yet.
134*ec779b8eSAndroid Build Coastguard Worker     // If a new state has not pushed by mutator since the previous poll,
135*ec779b8eSAndroid Build Coastguard Worker     // then the returned pointer will be unchanged.
136*ec779b8eSAndroid Build Coastguard Worker     // The previous state pointer is guaranteed to still be valid;
137*ec779b8eSAndroid Build Coastguard Worker     // this allows the observer to diff the previous and new states.
138*ec779b8eSAndroid Build Coastguard Worker     const T* poll();
139*ec779b8eSAndroid Build Coastguard Worker 
140*ec779b8eSAndroid Build Coastguard Worker     // Mutator APIs
141*ec779b8eSAndroid Build Coastguard Worker 
142*ec779b8eSAndroid Build Coastguard Worker     // Begin a mutation.  Returns a pointer to a read/write state, except the
143*ec779b8eSAndroid Build Coastguard Worker     // first time it is called the state is write-only and _must_ be initialized.
144*ec779b8eSAndroid Build Coastguard Worker     // Mutations cannot be nested.
145*ec779b8eSAndroid Build Coastguard Worker     // If the state is dirty and has not been pushed onto the state queue yet, then
146*ec779b8eSAndroid Build Coastguard Worker     // this new mutation will be squashed together with the previous one.
147*ec779b8eSAndroid Build Coastguard Worker     T*      begin();
148*ec779b8eSAndroid Build Coastguard Worker 
149*ec779b8eSAndroid Build Coastguard Worker     // End the current mutation and indicate whether caller modified the state.
150*ec779b8eSAndroid Build Coastguard Worker     // If didModify is true, then the state is marked dirty (in need of pushing).
151*ec779b8eSAndroid Build Coastguard Worker     // There is no rollback option because modifications are done in place.
152*ec779b8eSAndroid Build Coastguard Worker     // Does not automatically push the new state onto the state queue.
153*ec779b8eSAndroid Build Coastguard Worker     void    end(bool didModify = true);
154*ec779b8eSAndroid Build Coastguard Worker 
155*ec779b8eSAndroid Build Coastguard Worker     // Push a new state, if any, out to the observer via the state queue.
156*ec779b8eSAndroid Build Coastguard Worker     // For BLOCK_NEVER, returns:
157*ec779b8eSAndroid Build Coastguard Worker     //      true if not dirty, or dirty and pushed successfully
158*ec779b8eSAndroid Build Coastguard Worker     //      false if dirty and not pushed because that would block; remains dirty
159*ec779b8eSAndroid Build Coastguard Worker     // For BLOCK_UNTIL_PUSHED and BLOCK_UNTIL_ACKED, always returns true.
160*ec779b8eSAndroid Build Coastguard Worker     // No-op if there are no pending modifications (not dirty), except
161*ec779b8eSAndroid Build Coastguard Worker     //      for BLOCK_UNTIL_ACKED it will wait until a prior push has been acknowledged.
162*ec779b8eSAndroid Build Coastguard Worker     // Must not be called in the middle of a mutation.
163*ec779b8eSAndroid Build Coastguard Worker     enum block_t {
164*ec779b8eSAndroid Build Coastguard Worker         BLOCK_NEVER,        // do not block
165*ec779b8eSAndroid Build Coastguard Worker         BLOCK_UNTIL_PUSHED, // block until there's a slot available for the push
166*ec779b8eSAndroid Build Coastguard Worker         BLOCK_UNTIL_ACKED,  // also block until the push is acknowledged by the observer
167*ec779b8eSAndroid Build Coastguard Worker     };
168*ec779b8eSAndroid Build Coastguard Worker     bool    push(block_t block = BLOCK_NEVER);
169*ec779b8eSAndroid Build Coastguard Worker 
170*ec779b8eSAndroid Build Coastguard Worker     // Return whether the current state is dirty (modified and not pushed).
isDirty()171*ec779b8eSAndroid Build Coastguard Worker     bool    isDirty() const { return mIsDirty; }
172*ec779b8eSAndroid Build Coastguard Worker 
173*ec779b8eSAndroid Build Coastguard Worker #ifdef STATE_QUEUE_DUMP
174*ec779b8eSAndroid Build Coastguard Worker     // Register location of observer dump area
setObserverDump(StateQueueObserverDump * dump)175*ec779b8eSAndroid Build Coastguard Worker     void    setObserverDump(StateQueueObserverDump *dump)
176*ec779b8eSAndroid Build Coastguard Worker             { mObserverDump = dump != NULL ? dump : &mObserverDummyDump; }
177*ec779b8eSAndroid Build Coastguard Worker 
178*ec779b8eSAndroid Build Coastguard Worker     // Register location of mutator dump area
setMutatorDump(StateQueueMutatorDump * dump)179*ec779b8eSAndroid Build Coastguard Worker     void    setMutatorDump(StateQueueMutatorDump *dump)
180*ec779b8eSAndroid Build Coastguard Worker             { mMutatorDump = dump != NULL ? dump : &mMutatorDummyDump; }
181*ec779b8eSAndroid Build Coastguard Worker #endif
182*ec779b8eSAndroid Build Coastguard Worker 
183*ec779b8eSAndroid Build Coastguard Worker private:
184*ec779b8eSAndroid Build Coastguard Worker     static const unsigned kN = 4;       // values < 4 are not supported by this code
185*ec779b8eSAndroid Build Coastguard Worker     T                 mStates[kN];      // written by mutator, read by observer
186*ec779b8eSAndroid Build Coastguard Worker 
187*ec779b8eSAndroid Build Coastguard Worker     // "volatile" is meaningless with SMP, but here it indicates that we're using atomic ops
188*ec779b8eSAndroid Build Coastguard Worker     atomic_uintptr_t  mNext{}; // written by mutator to advance next, read by observer
189*ec779b8eSAndroid Build Coastguard Worker     volatile const T* mAck = nullptr;  // written by observer to acknowledge advance of next,
190*ec779b8eSAndroid Build Coastguard Worker                                        // read by mutator
191*ec779b8eSAndroid Build Coastguard Worker 
192*ec779b8eSAndroid Build Coastguard Worker     // only used by observer
193*ec779b8eSAndroid Build Coastguard Worker     const T*    mCurrent = nullptr;     // most recent value returned by poll()
194*ec779b8eSAndroid Build Coastguard Worker 
195*ec779b8eSAndroid Build Coastguard Worker     // only used by mutator
196*ec779b8eSAndroid Build Coastguard Worker     T*          mMutating{&mStates[0]}; // where updates by mutator are done in place
197*ec779b8eSAndroid Build Coastguard Worker     const T*    mExpecting = nullptr;   // what the mutator expects mAck to be set to
198*ec779b8eSAndroid Build Coastguard Worker     bool        mInMutation = false;    // whether we're currently in the middle of a mutation
199*ec779b8eSAndroid Build Coastguard Worker     bool        mIsDirty = false;       // whether mutating state has been modified since last push
200*ec779b8eSAndroid Build Coastguard Worker     bool        mIsInitialized = false; // whether mutating state has been initialized yet
201*ec779b8eSAndroid Build Coastguard Worker 
202*ec779b8eSAndroid Build Coastguard Worker #ifdef STATE_QUEUE_DUMP
203*ec779b8eSAndroid Build Coastguard Worker     StateQueueObserverDump  mObserverDummyDump; // default area for observer dump if not set
204*ec779b8eSAndroid Build Coastguard Worker     // pointer to active observer dump, always non-nullptr
205*ec779b8eSAndroid Build Coastguard Worker     StateQueueObserverDump* mObserverDump{&mObserverDummyDump};
206*ec779b8eSAndroid Build Coastguard Worker     StateQueueMutatorDump   mMutatorDummyDump;  // default area for mutator dump if not set
207*ec779b8eSAndroid Build Coastguard Worker     // pointer to active mutator dump, always non-nullptr
208*ec779b8eSAndroid Build Coastguard Worker     StateQueueMutatorDump*  mMutatorDump{&mMutatorDummyDump};
209*ec779b8eSAndroid Build Coastguard Worker #endif
210*ec779b8eSAndroid Build Coastguard Worker 
211*ec779b8eSAndroid Build Coastguard Worker };  // class StateQueue
212*ec779b8eSAndroid Build Coastguard Worker 
213*ec779b8eSAndroid Build Coastguard Worker }   // namespace android
214