1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! TRNG (True Random Number Generator) HAL for RP2350
//!
//! This module provides access to the ARM TrustZone True Random Number Generator
//! for generating cryptographically secure random numbers.
//!
//! ## Features
//!
//! - True random number generation using hardware entropy source
//! - 192-bit entropy collection (EHR - Entropy Holding Registers)
//! - Configurable ROSC sample rate
//! - Error detection (Von Neumann, CRNGT, Autocorrelation)
//! - Interrupt support
//!
//! ## Example
//!
//! ```ignore
//! use rp2350::trng::Trng;
//! use rp2350_pac::TRNG;
//!
//! // Obtain the TRNG peripheral from the PAC
//! let trng_peripheral = unsafe { TRNG::steal() };
//! let trng = Trng::init(trng_peripheral);
//!
//! // Generate random u32
//! let random = trng.random_u32().unwrap();
//!
//! // Generate random bytes
//! let mut buffer = [0u8; 16];
//! trng.fill_random(&mut buffer).unwrap();
//!
//! // Or steal after init (unsafe — caller guarantees init happened)
//! let trng = unsafe { Trng::steal() };
//! ```
use core::cell::Cell;
use crate::Steal;
use crate::reset::Resettable;
use rp2350_pac::TRNG;
/// TRNG error types
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
/// Von Neumann error (32 consecutive identical bits)
VonNeumannError,
/// CRNGT error (two consecutive identical 16-bit values)
CrngtError,
/// Autocorrelation test failed
AutocorrError,
/// Timed out waiting for entropy
Timeout,
}
/// TRNG peripheral wrapper
///
/// Provides access to the True Random Number Generator.
///
/// The 192-bit entropy block returned by the hardware is buffered internally,
/// so consecutive small reads (e.g. [`Trng::random_u32`]) do not wait for a
/// fresh 192-bit block each time.
pub struct Trng {
trng: TRNG,
/// Buffered 192-bit entropy block (6 words).
buf: Cell<[u32; 6]>,
/// Number of words remaining in `buf` (0..=6).
remaining: Cell<usize>,
}
impl Trng {
// ========================================================================
// Initialization
// ========================================================================
/// Initialize the TRNG peripheral
///
/// Takes ownership of the [`rp2350_pac::TRNG`] register block, resets the
/// peripheral, configures the ROSC sample rate to its default, enables the
/// random source, and unmasks the EHR-valid interrupt.
///
/// # Arguments
///
/// * `trng` — The PAC-level [`rp2350_pac::TRNG`] peripheral instance.
pub fn init(trng: rp2350_pac::TRNG) -> Self {
// Reset peripheral to ensure clean register state
<rp2350_pac::TRNG as Resettable>::init();
// Reset the TRNG
trng.trng_sw_reset.write_bits(1);
// Wait for reset to complete (bounded)
crate::spin::spin_wait("TRNG software reset", || {
trng.trng_sw_reset.read_bits() == 0
});
// Configure ROSC sample rate (default is fine for most uses)
// sample_cnt1 controls the number of clock cycles between samples
trng.sample_cnt1.write_bits(0xFFFF);
// Enable the random source
trng.rnd_source_enable.set_rnd_src_en();
// Unmask EHR valid interrupt (we poll, but it helps for checking)
trng.rng_imr.clr_ehr_valid_int_mask();
Self {
trng,
buf: Cell::new([0; 6]),
remaining: Cell::new(0),
}
}
/// Obtain a handle to the TRNG hardware peripheral without re-initializing.
///
/// # Safety
///
/// The caller must ensure the TRNG peripheral has already been reset and
/// initialized (e.g. via [`Trng::init`]) before use. Prefer [`Trng::init`]
/// which handles initialization automatically.
#[inline]
pub unsafe fn steal() -> Steal<Self> {
Steal(Self {
trng: unsafe { TRNG::steal() },
buf: Cell::new([0; 6]),
remaining: Cell::new(0),
})
}
/// Get reference to the register block
#[inline]
pub fn regs(&self) -> &rp2350_pac::trng::RegisterBlock {
&self.trng
}
// ========================================================================
// Random Number Generation
// ========================================================================
/// Wait for entropy to be ready
fn wait_for_entropy(&self) -> Result<(), Error> {
let mut spins = 0u32;
loop {
// Check for errors
if self.regs().rng_isr.vn_err() {
self.regs().rng_icr.set_vn_err();
return Err(Error::VonNeumannError);
}
if self.regs().rng_isr.crngt_err() {
self.regs().rng_icr.set_crngt_err();
return Err(Error::CrngtError);
}
if self.regs().rng_isr.autocorr_err() {
self.regs().rng_icr.set_autocorr_err();
return Err(Error::AutocorrError);
}
// Check if entropy is valid
if self.regs().rng_isr.ehr_valid() {
return Ok(());
}
core::hint::spin_loop();
spins += 1;
if spins >= crate::spin::SPIN_TIMEOUT {
return Err(Error::Timeout);
}
}
}
/// Check if entropy is available (non-blocking)
#[inline]
pub fn entropy_available(&self) -> bool {
self.regs().rng_isr.ehr_valid()
}
/// Read the 192-bit entropy holding registers (6 x 32-bit words).
///
/// This bypasses the internal buffer: it reads the hardware registers
/// directly and clears the EHR valid flag. Prefer [`Trng::random_u32`],
/// [`Trng::random_u64`] or [`Trng::fill_random`] for ordinary use.
pub fn read_ehr(&self) -> Result<[u32; 6], Error> {
self.read_hw_ehr()
}
/// Read a fresh 192-bit entropy block from the hardware and clear the
/// EHR valid flag.
fn read_hw_ehr(&self) -> Result<[u32; 6], Error> {
self.wait_for_entropy()?;
let data = [
self.regs().ehr_data0.read_bits(),
self.regs().ehr_data1.read_bits(),
self.regs().ehr_data2.read_bits(),
self.regs().ehr_data3.read_bits(),
self.regs().ehr_data4.read_bits(),
self.regs().ehr_data5.read_bits(),
];
// Clear the EHR valid flag to start collecting new entropy.
self.regs().rng_icr.set_ehr_valid();
Ok(data)
}
/// Refill the internal buffer with a fresh 192-bit entropy block.
fn refill(&self) -> Result<(), Error> {
let data = self.read_hw_ehr()?;
self.buf.set(data);
self.remaining.set(6);
Ok(())
}
/// Take the next 32-bit entropy word, refilling the buffer when empty.
fn next_word(&self) -> Result<u32, Error> {
if self.remaining.get() == 0 {
self.refill()?;
}
let rem = self.remaining.get();
let word = self.buf.get()[6 - rem];
self.remaining.set(rem - 1);
Ok(word)
}
/// Generate a random u32
pub fn random_u32(&self) -> Result<u32, Error> {
self.next_word()
}
/// Generate a random u64
pub fn random_u64(&self) -> Result<u64, Error> {
let lo = self.next_word()?;
let hi = self.next_word()?;
Ok((lo as u64) | ((hi as u64) << 32))
}
/// Fill a buffer with random bytes
pub fn fill_random(&self, buffer: &mut [u8]) -> Result<(), Error> {
let mut offset = 0;
while offset < buffer.len() {
let word = self.next_word()?;
let bytes = word.to_le_bytes();
let n = (buffer.len() - offset).min(4);
buffer[offset..offset + n].copy_from_slice(&bytes[..n]);
offset += n;
}
Ok(())
}
/// Generate a uniformly distributed random number in `[0, max)`.
///
/// Uses Lemire's rejection sampling.
///
/// # Panics
/// Panics if `max == 0`.
pub fn random_range(&self, max: u32) -> Result<u32, Error> {
assert!(max > 0, "max must be non-zero");
let threshold = max.wrapping_neg() % max;
loop {
let r = self.random_u32()?;
if r >= threshold {
return Ok(r % max);
}
}
}
// ========================================================================
// Control
// ========================================================================
/// Enable the random source
#[inline]
pub fn enable(&self) {
self.regs().rnd_source_enable.set_rnd_src_en();
}
/// Disable the random source
#[inline]
pub fn disable(&self) {
self.regs().rnd_source_enable.clr_rnd_src_en();
}
/// Check if the TRNG is busy
#[inline]
pub fn is_busy(&self) -> bool {
self.regs().trng_busy.trng_busy()
}
/// Reset the TRNG
pub fn reset(&self) {
self.regs().trng_sw_reset.write_bits(1);
crate::spin::spin_wait("TRNG software reset", || {
self.regs().trng_sw_reset.read_bits() == 0
});
}
/// Reset the bits counter
#[inline]
pub fn reset_bits_counter(&self) {
self.regs().rst_bits_counter.set_rst_bits_counter();
}
// ========================================================================
// Configuration
// ========================================================================
/// Set the sample count (number of clock cycles between ROSC samples)
#[inline]
pub fn set_sample_count(&self, count: u32) {
self.regs().sample_cnt1.write_bits(count);
}
/// Get the current sample count
#[inline]
pub fn sample_count(&self) -> u32 {
self.regs().sample_cnt1.read_bits()
}
/// Configure the TRNG ROSC length.
///
/// Selects the inverter chain length (0-3) for the ring oscillator.
///
/// # Panics
/// Panics if `length > 3`.
#[inline]
pub fn set_rosc_length(&self, length: u8) {
assert!(length <= 3, "ROSC length must be 0-3");
self.regs().trng_config.write_rnd_src_sel(length as u32);
}
// ========================================================================
// Interrupts
// ========================================================================
/// Enable EHR valid interrupt
#[inline]
pub fn enable_ehr_interrupt(&self) {
self.regs().rng_imr.clr_ehr_valid_int_mask();
}
/// Disable EHR valid interrupt
#[inline]
pub fn disable_ehr_interrupt(&self) {
self.regs().rng_imr.set_ehr_valid_int_mask();
}
/// Enable autocorrelation error interrupt
#[inline]
pub fn enable_autocorr_interrupt(&self) {
self.regs().rng_imr.clr_autocorr_err_int_mask();
}
/// Disable autocorrelation error interrupt
#[inline]
pub fn disable_autocorr_interrupt(&self) {
self.regs().rng_imr.set_autocorr_err_int_mask();
}
/// Enable CRNGT error interrupt
#[inline]
pub fn enable_crngt_interrupt(&self) {
self.regs().rng_imr.clr_crngt_err_int_mask();
}
/// Disable CRNGT error interrupt
#[inline]
pub fn disable_crngt_interrupt(&self) {
self.regs().rng_imr.set_crngt_err_int_mask();
}
/// Enable Von Neumann error interrupt
#[inline]
pub fn enable_vn_interrupt(&self) {
self.regs().rng_imr.clr_vn_err_int_mask();
}
/// Disable Von Neumann error interrupt
#[inline]
pub fn disable_vn_interrupt(&self) {
self.regs().rng_imr.set_vn_err_int_mask();
}
// ========================================================================
// Status
// ========================================================================
/// Check for Von Neumann error
#[inline]
pub fn vn_error(&self) -> bool {
self.regs().rng_isr.vn_err()
}
/// Check for CRNGT error
#[inline]
pub fn crngt_error(&self) -> bool {
self.regs().rng_isr.crngt_err()
}
/// Check for autocorrelation error
#[inline]
pub fn autocorr_error(&self) -> bool {
self.regs().rng_isr.autocorr_err()
}
/// Clear Von Neumann error flag
#[inline]
pub fn clear_vn_error(&self) {
self.regs().rng_icr.set_vn_err();
}
/// Clear CRNGT error flag
#[inline]
pub fn clear_crngt_error(&self) {
self.regs().rng_icr.set_crngt_err();
}
/// Clear EHR valid flag
#[inline]
pub fn clear_ehr_valid(&self) {
self.regs().rng_icr.set_ehr_valid();
}
/// Get the TRNG version
#[inline]
pub fn version(&self) -> u32 {
self.regs().rng_version.read_bits()
}
// ========================================================================
// Statistics
// ========================================================================
/// Get autocorrelation test statistics
#[inline]
pub fn autocorr_statistic(&self) -> u32 {
self.regs().autocorr_statistic.read_bits()
}
}