1 /* Copyright (C) 2010 Wildfire Games.
3 * Permission is hereby granted, free of charge, to any person obtaining
4 * a copy of this software and associated documentation files (the
5 * "Software"), to deal in the Software without restriction, including
6 * without limitation the rights to use, copy, modify, merge, publish,
7 * distribute, sublicense, and/or sell copies of the Software, and to
8 * permit persons to whom the Software is furnished to do so, subject to
9 * the following conditions:
11 * The above copyright notice and this permission notice shall be included
12 * in all copies or substantial portions of the Software.
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 * helpers for module initialization/shutdown.
27 #include "precompiled.h"
28 #include "lib/module_init.h"
30 #include "lib/sysdep/cpu.h" // cpu_CAS
32 // not yet initialized, or already shutdown
33 static const ModuleInitState UNINITIALIZED
= 0; // value documented in header
34 // running user callback - concurrent ModuleInit callers must spin
35 static const ModuleInitState BUSY
= ERR::AGAIN
; // never returned
36 // init succeeded; allow shutdown
37 static const ModuleInitState INITIALIZED
= INFO::SKIPPED
;
40 Status
ModuleInit(volatile ModuleInitState
* initState
, Status (*init
)())
44 if(cpu_CAS(initState
, UNINITIALIZED
, BUSY
))
47 *initState
= (ret
== INFO::OK
)? INITIALIZED
: ret
;
52 const ModuleInitState latchedInitState
= *initState
;
53 if(latchedInitState
== UNINITIALIZED
|| latchedInitState
== BUSY
)
59 ENSURE(latchedInitState
== INITIALIZED
|| latchedInitState
< 0);
60 return (Status
)latchedInitState
;
65 Status
ModuleShutdown(volatile ModuleInitState
* initState
, void (*shutdown
)())
69 if(cpu_CAS(initState
, INITIALIZED
, BUSY
))
72 *initState
= UNINITIALIZED
;
77 const ModuleInitState latchedInitState
= *initState
;
78 if(latchedInitState
== INITIALIZED
|| latchedInitState
== BUSY
)
84 if(latchedInitState
== UNINITIALIZED
)
87 ENSURE(latchedInitState
< 0);
88 return (Status
)latchedInitState
;