interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / native / kernel / core / entropy.c

93 lines · 2754 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* entropy.c -- RNDR-or-refuse selection logic (see entropy.h). Pure C, no
18 * ck.h services, so the host tests (tests/test_entropy.c) run it against a
19 * mocked RNDR. */
20#include "entropy.h"
21
22static void wipe(uint8_t *p, size_t n)
23{
24 volatile uint8_t *v = p;
25 while (n--) *v++ = 0;
26}
27
28/* One word with the architected bounded retry. 0 ok, else refusal. */
29static int draw(struct ck_rng *r, uint64_t *out)
30{
31 for (uint32_t t = 0; t < CK_RNG_RETRIES; t++) {
32 uint64_t v = 0;
33 if (r->ops->read(r->ops->ctx, &v)) {
34 r->retries += t;
35 if (r->words && v == r->last) return CK_RNG_STUCK;
36 r->last = v;
37 r->words++;
38 *out = v;
39 return CK_RNG_OK;
40 }
41 }
42 return CK_RNG_FAILED;
43}
44
45int ck_rng_probe(struct ck_rng *r, const struct ck_rng_ops *ops)
46{
47 if (!r || !ops || !ops->present || !ops->read) return CK_RNG_EARG;
48 r->ops = ops;
49 r->last = 0;
50 r->words = 0;
51 r->retries = 0;
52 if (!ops->present(ops->ctx)) return r->state = CK_RNG_ABSENT;
53 uint64_t a, b;
54 int rc = draw(r, &a);
55 if (rc == CK_RNG_OK) rc = draw(r, &b);
56 return r->state = rc;
57}
58
59int ck_rng_fill(struct ck_rng *r, void *buf, size_t len)
60{
61 if (!r || (!buf && len)) return CK_RNG_EARG;
62 uint8_t *p = buf;
63 if (r->state != CK_RNG_OK || !r->ops) {
64 if (r->state == CK_RNG_OK) r->state = CK_RNG_UNPROBED;
65 wipe(p, len);
66 return r->state;
67 }
68 size_t i = 0;
69 while (i < len) {
70 uint64_t v;
71 int rc = draw(r, &v);
72 if (rc != CK_RNG_OK) {
73 r->state = rc;
74 wipe(p, len);
75 return rc;
76 }
77 for (unsigned k = 0; k < 8 && i < len; k++) p[i++] = (uint8_t)(v >> (8 * k));
78 v = 0;
79 }
80 return CK_RNG_OK;
81}
82
83const char *ck_rng_reason(int state)
84{
85 switch (state) {
86 case CK_RNG_OK: return "rndr";
87 case CK_RNG_UNPROBED: return "unprobed";
88 case CK_RNG_ABSENT: return "absent";
89 case CK_RNG_FAILED: return "failed";
90 case CK_RNG_STUCK: return "stuck";
91 default: return "bad-argument";
92 }
93}