| /* |
| * Copyright (c) 2020 The Fuchsia Authors |
| * |
| * SPDX-License-Identifier: BSD-3-Clause |
| */ |
| |
| #include <common.h> |
| #include <emmc_storage.h> |
| #include <mmc.h> |
| #include <u-boot/sha256.h> |
| #include <zircon_util.h> |
| |
| #define SHA256_DIGEST_SIZE 32 |
| |
| /* |
| * Generate a default serial number of given size (including null terminator) |
| * based on the eMMC device info. |
| */ |
| int get_default_serial_number(char *sn, size_t size) |
| { |
| if ((sn == NULL) || !size) { |
| return -1; |
| } |
| |
| // Get eMMC device info. |
| struct mmc *mmc = find_mmc_device(STORAGE_DEV_EMMC); |
| if (!mmc) { |
| printf("Cannot find eMMC dev.\n"); |
| return -1; |
| } |
| |
| // The eMMC CID contains a serial number. Hash it to get a default serial number for use |
| // in case a real one isn't available. |
| uint8_t hash[SHA256_DIGEST_SIZE]; |
| sha256_csum_wd((const uchar*)mmc->cid, sizeof mmc->cid, hash, CHUNKSZ_SHA256); |
| |
| int i = SHA256_DIGEST_SIZE - 1; |
| /* if |sn| is too small to fit all hash digest, calc how many can be stored */ |
| if (size < (SHA256_DIGEST_SIZE * 2 + 1)) { |
| i = ((size - 1) / 2) - 1; |
| } |
| |
| static const char hex[] = "0123456789ABCDEF"; |
| int j = 0; |
| for (; i >= 0; i--) { |
| sn[j++] = hex[(hash[i] >> 4) & 0xF]; |
| sn[j++] = hex[hash[i] & 0xF]; |
| } |
| sn[size - 1] = '\0'; |
| |
| return 0; |
| } |