1// 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> 11#include <malloc.h> 12#include <rng.h> 13 14static int do_rng(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]) 15{ 16 size_t n; 17 u8 buf[64]; 18 int devnum; 19 struct udevice *dev; 20 int ret = CMD_RET_SUCCESS, err; 21 22 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 38 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) { 56 printf("No RNG device\n"); 57 return CMD_RET_FAILURE; 58 } 59 60 if (!n) 61 return 0; 62 63 n = min(n, sizeof(buf)); 64 65 err = dm_rng_read(dev, buf, n); 66 if (err) { 67 puts(err == -EINTR ? "Abort\n" : "Reading RNG failed\n"); 68 ret = CMD_RET_FAILURE; 69 } else { 70 print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, buf, n); 71 } 72 73 return ret; 74} 75 76U_BOOT_CMD( 77 rng, 3, 0, do_rng, 78 "print bytes from the hardware random number generator", 79 "list - list all the probed rng devices\n" 80 "rng [dev] [n] - print n random bytes(max 64) read from dev\n" 81); 82