Software APIs
random_order.c
1
// Copyright lowRISC contributors (OpenTitan project).
2
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
3
// SPDX-License-Identifier: Apache-2.0
4
5
#include "
sw/device/lib/base/random_order.h
"
6
7
#include "
sw/device/lib/base/bitfield.h
"
8
#include "
sw/device/lib/base/hardened.h
"
9
10
void
random_order_init(
random_order_t
*ctx,
size_t
min_len) {
11
ctx->
ctr
= 0;
12
if
(min_len > 0) {
13
ctx->
state
=
random_order_random_word
() % min_len;
14
}
else
{
15
ctx->
state
= 0;
16
}
17
ctx->
max
= min_len;
18
}
19
20
size_t
random_order_len(
const
random_order_t
*ctx) {
return
ctx->
max
; }
21
22
size_t
random_order_advance(
random_order_t
*ctx) {
23
size_t
out = ctx->
state
;
24
// Compute the next value and next value if we overflow max.
25
size_t
next = ctx->
state
+ 1;
26
size_t
next_overflow = next - ctx->
max
;
27
28
// Is next strictly less than max?
29
ct_bool32_t
which = ct_sltu32(next, ctx->
max
);
30
// If yes, choose next, else next_overflow.
31
ctx->
state
= ct_cmov32(which, next, next_overflow);
32
33
ctx->
ctr
= launder32(ctx->
ctr
) + 1;
34
HARDENED_CHECK_LE(ctx->
state
, ctx->
max
);
35
return
out;
36
}
sw
device
lib
base
random_order.c
Return to
OpenTitan Documentation