blob: e5ab8681122606f5f403fd64de250627c64769f9 [file] [log] [blame]
Heinrich Schuchardta31a5942019-12-24 22:17:37 +01001// SPDX-License-Identifier: GPL-2.0+
2/*
3 * The 'rng' command prints bytes from the hardware random number generator.
4 *
5 * Copyright (c) 2019, Heinrich Schuchardt <xypron.glpk@gmx.de>
6 */
7#include <common.h>
8#include <command.h>
9#include <dm.h>
10#include <hexdump.h>
Simon Glass9bc15642020-02-03 07:36:16 -070011#include <malloc.h>
Heinrich Schuchardta31a5942019-12-24 22:17:37 +010012#include <rng.h>
13
Simon Glassed38aef2020-05-10 11:40:03 -060014static int do_rng(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
Heinrich Schuchardta31a5942019-12-24 22:17:37 +010015{
Sughosh Ganub746dee2022-07-22 21:32:06 +053016 size_t n;
Sughosh Ganu407ec092022-07-22 21:32:07 +053017 u8 buf[64];
Sughosh Ganub746dee2022-07-22 21:32:06 +053018 int devnum;
Sughosh Ganu407ec092022-07-22 21:32:07 +053019 struct udevice *dev;
Marek BehĂșn5304d5d2024-04-04 09:51:05 +020020 int ret = CMD_RET_SUCCESS, err;
Heinrich Schuchardta31a5942019-12-24 22:17:37 +010021
Weizhao Ouyang168e9472024-03-04 14:42:42 +000022 if (argc == 2 && !strcmp(argv[1], "list")) {
23 int idx = 0;
24
25 uclass_foreach_dev_probe(UCLASS_RNG, dev) {
26 idx++;
27 printf("RNG #%d - %s\n", dev->seq_, dev->name);
28 }
29
30 if (!idx) {
31 log_err("No RNG device\n");
32 return CMD_RET_FAILURE;
33 }
34
35 return CMD_RET_SUCCESS;
36 }
37
Sughosh Ganub746dee2022-07-22 21:32:06 +053038 switch (argc) {
39 case 1:
40 devnum = 0;
41 n = 0x40;
42 break;
43 case 2:
44 devnum = hextoul(argv[1], NULL);
45 n = 0x40;
46 break;
47 case 3:
48 devnum = hextoul(argv[1], NULL);
49 n = hextoul(argv[2], NULL);
50 break;
51 default:
52 return CMD_RET_USAGE;
53 }
54
55 if (uclass_get_device_by_seq(UCLASS_RNG, devnum, &dev) || !dev) {
Heinrich Schuchardta31a5942019-12-24 22:17:37 +010056 printf("No RNG device\n");
57 return CMD_RET_FAILURE;
58 }
59
Sughosh Ganu407ec092022-07-22 21:32:07 +053060 if (!n)
61 return 0;
62
63 n = min(n, sizeof(buf));
Heinrich Schuchardta31a5942019-12-24 22:17:37 +010064
Marek BehĂșn5304d5d2024-04-04 09:51:05 +020065 err = dm_rng_read(dev, buf, n);
66 if (err) {
67 puts(err == -EINTR ? "Abort\n" : "Reading RNG failed\n");
Heinrich Schuchardta31a5942019-12-24 22:17:37 +010068 ret = CMD_RET_FAILURE;
69 } else {
70 print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, buf, n);
71 }
72
Heinrich Schuchardta31a5942019-12-24 22:17:37 +010073 return ret;
74}
75
Heinrich Schuchardta31a5942019-12-24 22:17:37 +010076U_BOOT_CMD(
Sughosh Ganub746dee2022-07-22 21:32:06 +053077 rng, 3, 0, do_rng,
Heinrich Schuchardta31a5942019-12-24 22:17:37 +010078 "print bytes from the hardware random number generator",
Weizhao Ouyang168e9472024-03-04 14:42:42 +000079 "list - list all the probed rng devices\n"
80 "rng [dev] [n] - print n random bytes(max 64) read from dev\n"
Heinrich Schuchardta31a5942019-12-24 22:17:37 +010081);