1 /* 2 * ASPEED OTP (One-Time Programmable) memory 3 * 4 * Copyright (C) 2025 Aspeed 5 * 6 * SPDX-License-Identifier: GPL-2.0-or-later 7 */ 8 9 #include "qemu/osdep.h" 10 #include "qemu/log.h" 11 #include "qapi/error.h" 12 #include "system/block-backend.h" 13 #include "hw/qdev-properties.h" 14 #include "hw/nvram/aspeed_otp.h" 15 16 static uint64_t aspeed_otp_read(void *opaque, hwaddr offset, unsigned size) 17 { 18 AspeedOTPState *s = opaque; 19 uint64_t val = 0; 20 21 memcpy(&val, s->storage + offset, size); 22 23 return val; 24 } 25 26 static void aspeed_otp_write(void *opaque, hwaddr otp_addr, 27 uint64_t val, unsigned size) 28 { 29 AspeedOTPState *s = opaque; 30 31 memcpy(s->storage + otp_addr, &val, size); 32 } 33 34 static bool aspeed_otp_init_storage(AspeedOTPState *s, Error **errp) 35 { 36 uint32_t *p; 37 int i, num; 38 uint64_t perm; 39 40 if (s->blk) { 41 perm = BLK_PERM_CONSISTENT_READ | 42 (blk_supports_write_perm(s->blk) ? BLK_PERM_WRITE : 0); 43 if (blk_set_perm(s->blk, perm, BLK_PERM_ALL, errp) < 0) { 44 return false; 45 } 46 if (blk_pread(s->blk, 0, s->size, s->storage, 0) < 0) { 47 error_setg(errp, "Failed to read the initial flash content"); 48 return false; 49 } 50 } else { 51 num = s->size / sizeof(uint32_t); 52 p = (uint32_t *)s->storage; 53 for (i = 0; i < num; i++) { 54 p[i] = (i % 2 == 0) ? 0x00000000 : 0xFFFFFFFF; 55 } 56 } 57 return true; 58 } 59 60 static const MemoryRegionOps aspeed_otp_ops = { 61 .read = aspeed_otp_read, 62 .write = aspeed_otp_write, 63 .endianness = DEVICE_LITTLE_ENDIAN, 64 .valid.min_access_size = 1, 65 .valid.max_access_size = 4, 66 }; 67 68 static void aspeed_otp_realize(DeviceState *dev, Error **errp) 69 { 70 AspeedOTPState *s = ASPEED_OTP(dev); 71 72 if (s->size == 0) { 73 error_setg(errp, "aspeed.otp: 'size' property must be set"); 74 return; 75 } 76 77 s->storage = blk_blockalign(s->blk, s->size); 78 79 if (!aspeed_otp_init_storage(s, errp)) { 80 return; 81 } 82 83 memory_region_init_io(&s->mmio, OBJECT(dev), &aspeed_otp_ops, 84 s, "aspeed.otp", s->size); 85 address_space_init(&s->as, &s->mmio, NULL); 86 } 87 88 static const Property aspeed_otp_properties[] = { 89 DEFINE_PROP_UINT64("size", AspeedOTPState, size, 0), 90 DEFINE_PROP_DRIVE("drive", AspeedOTPState, blk), 91 }; 92 93 static void aspeed_otp_class_init(ObjectClass *klass, const void *data) 94 { 95 DeviceClass *dc = DEVICE_CLASS(klass); 96 dc->realize = aspeed_otp_realize; 97 device_class_set_props(dc, aspeed_otp_properties); 98 } 99 100 static const TypeInfo aspeed_otp_info = { 101 .name = TYPE_ASPEED_OTP, 102 .parent = TYPE_DEVICE, 103 .instance_size = sizeof(AspeedOTPState), 104 .class_init = aspeed_otp_class_init, 105 }; 106 107 static void aspeed_otp_register_types(void) 108 { 109 type_register_static(&aspeed_otp_info); 110 } 111 112 type_init(aspeed_otp_register_types) 113