@@ -7,7 +7,7 @@ use core::{
7
7
cell:: UnsafeCell ,
8
8
ffi:: c_void,
9
9
mem:: MaybeUninit ,
10
- sync:: atomic:: { AtomicI32 , Ordering :: Relaxed } ,
10
+ sync:: atomic:: { AtomicI32 , Ordering } ,
11
11
} ;
12
12
13
13
/// For all platforms, we use `/dev/urandom` rather than `/dev/random`.
@@ -41,17 +41,30 @@ fn get_rng_fd() -> Result<libc::c_int, Error> {
41
41
// need to use a different atomic type or make other accomodations. The
42
42
// compiler will let us know if/when that is the case, because the
43
43
// `FD.store(fd)` would fail to compile.
44
+ //
45
+ // The opening of the file, by libc/libstd/etc. may write some unknown
46
+ // state into in-process memory. (Such state may include some sanitizer
47
+ // bookkeeping, or we might be operating in a unikernal-like environment
48
+ // where all the "kernel" file descriptor bookkeeping is done in our
49
+ // process.) `get_fd_locked` stores into FD using `Ordering::Release` to
50
+ // ensure any such state is synchronized. `get_fd` loads from `FD` with
51
+ // `Ordering::Acquire` to synchronize with it.
44
52
static FD : AtomicI32 = AtomicI32 :: new ( FD_UNINIT ) ;
45
53
46
54
fn get_fd ( ) -> Option < libc:: c_int > {
47
- match FD . load ( Relaxed ) {
55
+ match FD . load ( Ordering :: Acquire ) {
48
56
FD_UNINIT => None ,
49
57
val => Some ( val) ,
50
58
}
51
59
}
52
60
53
61
#[ cold]
54
62
fn get_fd_locked ( ) -> Result < libc:: c_int , Error > {
63
+ // This mutex is used to prevent multiple threads from opening file
64
+ // descriptors concurrently, which could run into the limit on the
65
+ // number of open file descriptors. Our goal is to have no more than one
66
+ // file descriptor open, ever.
67
+ //
55
68
// SAFETY: We use the mutex only in this method, and we always unlock it
56
69
// before returning, making sure we don't violate the pthread_mutex_t API.
57
70
static MUTEX : Mutex = Mutex :: new ( ) ;
@@ -68,7 +81,7 @@ fn get_rng_fd() -> Result<libc::c_int, Error> {
68
81
69
82
let fd = open_readonly ( FILE_PATH ) ?;
70
83
debug_assert ! ( fd != FD_UNINIT ) ;
71
- FD . store ( fd, Relaxed ) ;
84
+ FD . store ( fd, Ordering :: Release ) ;
72
85
73
86
Ok ( fd)
74
87
}
0 commit comments