This commit is contained in:
Linehu
2026-08-29 18:47:54 +08:00
parent 880906edc9
commit cc0fcf26e3
49 changed files with 3705 additions and 3385 deletions
+14 -1
View File
@@ -108,6 +108,8 @@ static u32 g_ready_port = 0xffffffffu;
static ahci_cmd_header *g_cmd_header;
static struct dkm_dma_buffer g_cmd_table;
static struct dkm_dma_buffer g_data;
/* IDENTIFY 读出的用户可寻址扇区数;LBA48 优先,回退 LBA28 */
static u64 g_sector_count;
static u32 pci_read(u8 bus, u8 dev, u8 func, u8 reg) {
return dkm_pci_read(bus, dev, func, reg);
@@ -534,6 +536,17 @@ static int ahci_identify_port(u32 port, const struct dkm_dma_api *dma) {
log_hex("[ahci] IDENTIFY word0=", id[0]);
log_hex("[ahci] IDENTIFY word49=", id[49]);
log_hex("[ahci] IDENTIFY word83=", id[83]);
/* 容量必须在 ahci_read_lba0 复用 data 缓冲区前提取,
* 否则 IDENTIFY 数据被 LBA0 内容覆盖后容量丢失。 */
if ((id[83] & 0x0400u) && (id[103] | id[102] | id[101] | id[100])) {
/* LBA48: word100-103 小端 u16 序列拼接 */
g_sector_count = (u64)id[100] | ((u64)id[101] << 16)
| ((u64)id[102] << 32) | ((u64)id[103] << 48);
} else {
/* LBA28: word60-61 */
g_sector_count = (u64)id[60] | ((u64)id[61] << 16);
}
log_hex("[ahci] IDENTIFY sector_count=", g_sector_count);
ahci_read_lba0(port, hdr, &table, &data);
g_ready_port = port;
g_cmd_header = hdr;
@@ -678,7 +691,7 @@ int driver_init(const struct dkm_kernel_api *api,
struct dkm_block_device_desc desc;
desc.name = "ahci0";
desc.sector_size = 512;
desc.sector_count = 0;
desc.sector_count = g_sector_count;
desc.ctx = 0;
desc.read = ahci_block_read;
desc.write = ahci_block_write;
+1169
View File
@@ -0,0 +1,1169 @@
/* DKM EHCI Driver — USB2 host controller + Mass Storage Class (BOT/SCSI)
*
* Stage 1 optional storage driver, depends on "pci", provides "block".
* Target: Intel 6/7-series EHCI (PCI class 0C/03/20, device 1C2D/1C26)
* and any standard EHCI controller — the USB2 path used on platforms
* without xHCI (e.g. H61/B75 with only EHCI controllers).
*
* Synchronous polling model (no IRQ): async list + QH/TD execution,
* transfer completion detected by polling the QH overlay token.
*
* Pipeline:
* 1. PCI discovery: class=0x0C/03/20
* 2. MMIO mapping: BAR0 via mm_map_mmio / HHDM
* 3. HC init: HCRESET, port power, RUN
* 4. Port scan: reset, wait PED, read speed
* 5. Enumeration: SET_ADDRESS, GET_DESCRIPTOR(dev), SET_CONFIGURATION
* 6. MSC: BOT (CBW/CSW) + SCSI (INQUIRY/RD_CAP/READ10/WRITE10)
* 7. Block provider: register usb2 via kernel_api.block
*/
#include "../dkm_shared.h"
#include "../dkm_instr.h"
DKM_STAT_DECL(ehci_pci_found);
DKM_STAT_DECL(ehci_port_ok);
DKM_STAT_DECL(ehci_msc_found);
DKM_STAT_DECL(ehci_block_reads);
DKM_STAT_DECL(ehci_block_writes);
static const char *const g_depends[] = { "pci" };
static const char *const g_provides[] = { "block" };
__attribute__((visibility("default"), used))
const struct dkm_driver_desc driver_desc = {
.magic = DKM_DRIVER_MAGIC,
.abi_version = DKM_ABI_VERSION,
.desc_size = sizeof(struct dkm_driver_desc),
.name = "ehci",
.version = "0.1.0",
.vendor = "Deshab",
.driver_class = 6, /* DKM_CLASS_STORAGE */
.stage = 1,
.flags = 0,
.priority = 0,
.depends = g_depends,
.depends_count = 1,
.provides = g_provides,
.provides_count = 1,
.min_kernel_abi = 1,
.feature_bits = 0,
.reserved0 = 0,
.reserved1 = 0
};
/* ================================================================
* Constants — EHCI registers, QH/TD, USB protocol
* ================================================================ */
#define EHCI_CLASS_SERIAL 0x0C
#define EHCI_SUBCLASS_USB 0x03
#define EHCI_PROGIF_EHCI 0x20
/* Capability registers (MMIO + 0x00) */
#define EHCI_CAP_CAPLENGTH 0x00
#define EHCI_CAP_HCSPARAMS 0x04
#define EHCI_CAP_HCCPARAMS 0x08
/* Operational registers (MMIO + caplength) */
#define EHCI_OP_USBCMD 0x00
#define EHCI_OP_USBSTS 0x04
#define EHCI_OP_USBINTR 0x08
#define EHCI_OP_FRINDEX 0x0C
#define EHCI_OP_ASYNCLIST 0x18
#define EHCI_OP_CONFIGFLAG 0x40
#define EHCI_OP_PORTSC 0x44
#define EHCI_PORT_STRIDE 0x04
/* USBCMD bits */
#define USBCMD_RUN (1u << 0)
#define USBCMD_HCRESET (1u << 1)
#define USBCMD_PSE (1u << 4)
#define USBCMD_ASE (1u << 5)
/* USBSTS bits */
#define USBSTS_USBINT (1u << 0)
#define USBSTS_PCD (1u << 2)
#define USBSTS_FLR (1u << 3)
#define USBSTS_HSE (1u << 4)
#define USBSTS_IAA (1u << 6)
#define USBSTS_HCHALT (1u << 12)
/* PORTSC bits — 与 QEMU include/hw/usb/ehci-regs.h / EHCI 1.0 spec 一致
* BUG-FIX: 原定义位错(PED=bit1 应为 bit2,speed 在 LINESTAT bit10:11 而非
* bit14:15,change 位是 bit1/3/5 而非 bit17/18/20/21)——端口永不使能、
* 速度永远读 0,导致 HC 不执行该端口上的传输。 */
#define PORTSC_CONNECT (1u << 0) /* CCS */
#define PORTSC_CSC (1u << 1) /* Connect Status Change (W1C) */
#define PORTSC_PED (1u << 2) /* Port Enable */
#define PORTSC_PEDC (1u << 3) /* Port Enable/Disable Change (W1C) */
#define PORTSC_OCA (1u << 4) /* Over-Current Active */
#define PORTSC_OCC (1u << 5) /* Over-Current Change (W1C) */
#define PORTSC_FPR (1u << 6) /* Force Port Resume */
#define PORTSC_SUSP (1u << 7) /* Suspend */
#define PORTSC_PR (1u << 8) /* Port Reset */
#define PORTSC_LS_SHIFT 10 /* Line Status = 端口速度 (bit10:11) */
#define PORTSC_LS_MASK 0x3
#define PORTSC_PP (1u << 12) /* Port Power */
#define PORTSC_POWNER (1u << 13)
/* RWC 位(W1C):CSC|PEDC|OCC —— 清 change 时写这些位 */
#define PORTSC_RWC (PORTSC_CSC | PORTSC_PEDC | PORTSC_OCC)
/* PLS/LS 值(Line Status 字段,非 PLS 状态机) */
#define LS_FULL 0
#define LS_LOW 1
#define LS_HIGH 2
/* TD token bits */
#define TD_ACTIVE (1u << 7)
#define TD_HALTED (1u << 6)
#define TD_BUFERR (1u << 5)
#define TD_BABBLE (1u << 4)
#define TD_XACTERR (1u << 3)
#define TD_PID_SHIFT 8
#define TD_PID_MASK 0x3
#define TD_CERR_SHIFT 10
#define TD_CERR_MASK 0x3
#define TD_IOC (1u << 15)
#define TD_BYTES_SHIFT 16
#define TD_BYTES_MASK 0x7FFF
#define TD_TOGGLE (1u << 31)
#define PID_OUT 0
#define PID_IN 1
#define PID_SETUP 2
/* QH 链接:最低位 1 = 列表尾(T 位),0 = QH 指针 */
#define QH_TERMINATE 0x1u
/* USB speeds (EPCAP/QH ep speed 字段) */
#define USB_SPEED_FULL 0
#define USB_SPEED_LOW 1
#define USB_SPEED_HIGH 2
/* BOT signatures */
#define BOT_CBW_SIG 0x43425355u /* "USBC" */
#define BOT_CSW_SIG 0x53425355u /* "USBS" */
/* SCSI opcodes */
#define SCSI_TEST_UNIT_READY 0x00
#define SCSI_INQUIRY 0x12
#define SCSI_READ_CAPACITY10 0x25
#define SCSI_READ10 0x28
#define SCSI_WRITE10 0x2A
/* ================================================================
* Data structures
* ================================================================ */
/* EHCI Transfer Descriptor — 32 字节,32 字节对齐 */
typedef struct {
u32 next; /* +0 */
u32 alt_next; /* +4 */
u32 token; /* +8 */
u32 buf[5]; /* +12 */
} ehci_td;
/* EHCI Queue Head — 44 字节,32 字节对齐
* 布局必须与 QEMU v11 EHCIqh / EHCI 1.0 spec 完全一致:
* +0 hlink(next), +4 epchar, +8 epcap(端点能力: hub addr+smask/cmask),
* +12 current_qtd, +16 next_qtd(overlay), +20 altnext(overlay), +24 token(overlay),
* +28 buf[5]
* BUG-FIX(关键): epcap 字段不能删!QEMU 从 +16 读 next_qtd、+20 读 altnext、
* +24 读 token。删掉 epcap 使 overlay 错位 4 字节——驱动写的 ov_next 落到
* current_qtd 位、ov_alt(0x1=T) 落到 next_qtd 位 → QEMU 认为 QH 无 TD
* 永不 FETCHQTD(token 恒 ACTIVE 0x80280)。 */
typedef struct {
u32 hlink; /* +0 */
u32 epchar; /* +4 */
u32 epcap; /* +8 */
u32 curqtd; /* +12 */
u32 ov_next; /* +16 overlay.next_qtd */
u32 ov_alt; /* +20 overlay.altnext */
u32 ov_token; /* +24 overlay.token */
u32 ov_buf[5]; /* +28 */
} ehci_qh;
/* MSC device state */
typedef struct {
u8 dev_addr;
u8 speed;
u8 bulk_out_ep; /* endpoint number (1..15) */
u8 bulk_in_ep;
u16 bulk_out_mps;
u16 bulk_in_mps;
u32 cbw_tag;
u64 sector_count;
u32 sector_size;
int ready;
} ehci_msc_dev;
/* ================================================================
* Global state
* ================================================================ */
static const struct dkm_kernel_api *g_api;
static const struct dkm_log_api *g_log;
static volatile u8 *g_mmio; /* EHCI BAR0 virtual */
static u32 g_caplen;
static u32 g_nports;
static u32 g_64bit; /* HCCPARAMS bit0 */
static u32 g_ppc; /* per-port power control bit4 */
/* DMA:异步列表区(QH/TD 池)+ 数据缓冲 + CSW 缓冲 */
static struct dkm_dma_buffer g_qh_dma; /* 4KB:QH×4 + TD×8 */
static struct dkm_dma_buffer g_xfer; /* 数据 bounce buffer(>=64KB) */
static struct dkm_dma_buffer g_csw; /* CSW 独立缓冲(防覆盖数据区前 13 字节) */
static ehci_qh *g_qh_ctrl;
static ehci_qh *g_qh_bulk_out;
static ehci_qh *g_qh_bulk_in;
static ehci_td *g_td_pool;
static u32 g_td_next;
static ehci_msc_dev g_msc;
static u8 g_pci_bus, g_pci_dev, g_pci_func;
/* ================================================================
* Utility
* ================================================================ */
static void log_hex(const char *prefix, u64 value) {
static const char hex[] = "0123456789abcdef";
char buf[19];
u32 pos = 0;
buf[pos++] = '0';
buf[pos++] = 'x';
for (int i = 15; i >= 0; i--)
buf[pos++] = hex[(value >> (i * 4)) & 0xf];
buf[pos] = 0;
g_log->info(prefix);
g_log->info(buf);
}
static void ehci_zero(void *ptr, u32 len) {
u8 *p = (u8 *)ptr;
for (u32 i = 0; i < len; i++) p[i] = 0;
}
static void ehci_memcpy(void *dst, const void *src, u32 len) {
u8 *d = (u8 *)dst;
const u8 *s = (const u8 *)src;
for (u32 i = 0; i < len; i++) d[i] = s[i];
}
static u32 mmio_read32(u32 off) {
return *(volatile u32 *)(void *)(g_mmio + off);
}
static void mmio_write32(u32 off, u32 value) {
*(volatile u32 *)(void *)(g_mmio + off) = value;
}
static void ehci_mb(void) {
__asm__ volatile("" ::: "memory");
}
/* 把物理地址编码进 32 位链接字段(64 位控制器用 CTRLDSSEGMENT 高 32 位) */
/* (内联使用,见 qh_submit_control/qh_enqueue) */
/* ================================================================
* Phase 1: PCI discovery + MMIO mapping
* ================================================================ */
static int ehci_find(u8 *out_bus, u8 *out_dev, u8 *out_func) {
for (u16 bus = 0; bus < 256; bus++) {
for (u8 dev = 0; dev < 32; dev++) {
u32 vd = dkm_pci_read((u8)bus, dev, 0, PCI_VENDOR_ID);
if ((vd & 0xffff) == 0xffff) continue;
u8 header = (u8)(dkm_pci_read((u8)bus, dev, 0, PCI_HEADER) >> 16);
u8 func_count = (header & 0x80) ? 8 : 1;
for (u8 func = 0; func < func_count; func++) {
u32 vd2 = dkm_pci_read((u8)bus, dev, func, PCI_VENDOR_ID);
if ((vd2 & 0xffff) == 0xffff) continue;
u32 class_reg = dkm_pci_read((u8)bus, dev, func, 0x08);
u8 prog_if = (u8)((class_reg >> 8) & 0xff);
u8 subclass = (u8)((class_reg >> 16) & 0xff);
u8 class_code = (u8)((class_reg >> 24) & 0xff);
if (class_code == EHCI_CLASS_SERIAL &&
subclass == EHCI_SUBCLASS_USB &&
prog_if == EHCI_PROGIF_EHCI) {
*out_bus = (u8)bus;
*out_dev = dev;
*out_func = func;
return 0;
}
}
}
}
return -1;
}
static volatile u8 *ehci_map_bar(u64 bar_phys) {
u64 bar_virt = g_api->hhdm_offset + bar_phys;
if (g_api->mm_map_mmio) {
void *mapped = g_api->mm_map_mmio(bar_phys, 0x1000);
if (mapped) {
g_log->info("[ehci] BAR mapped via mm_map_mmio");
return (volatile u8 *)mapped;
}
}
if (g_api->mmio && g_api->mmio->is_mapped) {
if (g_api->mmio->is_mapped(bar_virt) > 0) {
g_log->info("[ehci] HHDM covers BAR");
return (volatile u8 *)(uintptr_t)bar_virt;
}
if (g_api->mmio->map_mmio) {
if (g_api->mmio->map_mmio(bar_phys, 0x1000) == 0 &&
g_api->mmio->is_mapped(bar_virt) > 0) {
g_log->info("[ehci] BAR mapped via page tables");
return (volatile u8 *)(uintptr_t)bar_virt;
}
}
}
if (bar_phys < 0x100000000ULL) {
g_log->info("[ehci] assuming HHDM covers low BAR");
return (volatile u8 *)(uintptr_t)bar_virt;
}
g_log->error("[ehci] BAR MMIO unavailable");
return 0;
}
/* ================================================================
* Phase 1: HC reset and start
* ================================================================ */
static int ehci_hc_reset(void) {
/* 等待 HCHALT=1(Halted 时才能写 HCRESET) */
u64 deadline = dkm_rdtsc() + dkm_tsc_per_ms * 100;
while (dkm_rdtsc() < deadline) {
if (mmio_read32(g_caplen + EHCI_OP_USBSTS) & USBSTS_HCHALT) break;
__asm__ volatile("pause");
}
mmio_write32(g_caplen + EHCI_OP_USBCMD, USBCMD_HCRESET);
deadline = dkm_rdtsc() + dkm_tsc_per_ms * 100;
while (dkm_rdtsc() < deadline) {
if (!(mmio_read32(g_caplen + EHCI_OP_USBCMD) & USBCMD_HCRESET)) {
g_log->info("[ehci] HC reset complete");
return 0;
}
__asm__ volatile("pause");
}
g_log->error("[ehci] HC reset timeout");
return -1;
}
/* ================================================================
* Phase 2: QH/TD management
* ================================================================ */
static ehci_td *td_alloc(void) {
if (g_td_next >= 8) return 0;
ehci_td *td = &g_td_pool[g_td_next++];
ehci_zero(td, sizeof(ehci_td));
td->next = QH_TERMINATE;
td->alt_next = QH_TERMINATE;
return td;
}
/* 初始化一个 QH:endpoint=0 控制 / 指定端点 bulk。
* 注意:不能动 hlink —— ehci_hc_start 在启动时已把 ctrl/out/in 三个 QH
* 链成环;每次提交只更新 epchar/overlay,hlink 必须保留(否则环断裂,
* HC 停止遍历,overlay token 恒 0 → qh_wait 假成功返回空数据)。 */
static void qh_init(ehci_qh *qh, u8 dev_addr, u8 ep_num, u8 speed,
u16 mps, int control) {
qh->curqtd = 0;
qh->ov_next = QH_TERMINATE;
qh->ov_alt = QH_TERMINATE;
qh->ov_token = 0; /* inactive */
u32 epchar = (u32)dev_addr; /* [6:0] */
epchar |= ((u32)ep_num << 8); /* [11:8] */
epchar |= ((u32)speed << 12); /* [14:12] */
epchar |= ((u32)mps << 16); /* [26:16] */
if (control) epchar |= (1u << 27); /* control endpoint */
/* DTC 清 0:由 HC 管理 data toggle。
* H 位(bit15) 保留:ctrl 是环头 QH,每次提交重建 epchar 后必须
* 重新置 H,否则 QEMU WAITLISTHEAD 找不到入口(只在 H=1 的 QH
* 处进入 FETCHENTRY)。 */
u32 keep_h = qh->epchar & (1u << 15);
qh->epchar = epchar | keep_h;
/* epcap(端点能力):直连根端口 hub addr=0, smask/cmask=0。
* 该字段必须存在且清零——QEMU 依赖它使 overlay 偏移正确。 */
qh->epcap = 0;
}
/* 构建控制传输 TD 链:SETUP -> [DATA] -> STATUS,挂到 qh。 */
static int qh_submit_control(ehci_qh *qh, const u8 *setup8,
u8 *data, u32 data_len, u8 dir) {
/* 清空旧链:重置 overlay */
qh->curqtd = 0;
qh->ov_next = QH_TERMINATE;
qh->ov_token = 0;
g_td_next = 0; /* 复用池(单传输假设) */
ehci_td *t_setup = td_alloc();
ehci_td *t_data = 0;
ehci_td *t_status = td_alloc();
if (!t_setup || !t_status) return -1;
if (data_len > 0) {
t_data = td_alloc();
if (!t_data) return -2;
}
/* SETUP TD:8 字节,toggle=0,pid=SETUP
* 注意:必须先分配 t_data 再算 t_setup->next(原实现引用未分配
* 的 t_data → TD 链指向垃圾地址 → HC 走链崩溃/超时)。 */
if (data_len > 0) {
t_setup->next = (u32)(g_qh_dma.phys + (u64)((u8 *)t_data - (u8 *)g_qh_dma.virt));
} else {
t_setup->next = (u32)(g_qh_dma.phys + (u64)((u8 *)t_status - (u8 *)g_qh_dma.virt));
}
/* setup 数据嵌入 QH overlay buffer?标准做法:SETUP TD buffer 指向含 8 字节 setup 的内存 */
/* 简化:setup 包拷贝到 xfer 缓冲头部,TD buffer 指向它 */
{
u8 *sb = (u8 *)g_xfer.virt;
ehci_memcpy(sb, setup8, 8);
__asm__ volatile("wbinvd" ::: "memory");
t_setup->buf[0] = (u32)(g_xfer.phys & 0xFFFFFFFFu);
u32 tok = TD_ACTIVE | (PID_SETUP << TD_PID_SHIFT) | (8u << TD_BYTES_SHIFT);
t_setup->token = tok; /* toggle=0 */
}
/* DATA TD(可选)——t_data 已在上方分配,此处不再重复分配 */
if (data_len > 0 && t_data) {
/* 数据在 g_xfer.virt + 8 偏移处(IN:设备写这里;OUT:软件先拷入) */
u8 *db = (u8 *)g_xfer.virt + 8;
if (dir == PID_OUT) {
ehci_memcpy(db, data, data_len);
__asm__ volatile("wbinvd" ::: "memory");
}
t_data->buf[0] = (u32)((g_xfer.phys + 8) & 0xFFFFFFFFu);
t_data->next = (u32)(g_qh_dma.phys + (u64)((u8 *)t_status - (u8 *)g_qh_dma.virt));
u32 tok = TD_ACTIVE | ((u32)dir << TD_PID_SHIFT) | ((u32)data_len << TD_BYTES_SHIFT) | TD_TOGGLE;
t_data->token = tok; /* toggle=1 */
}
/* STATUS TD:反向 pid,toggle=1,长度 0 */
{
u8 spid = (dir == PID_IN) ? PID_OUT : PID_IN;
if (data_len == 0) spid = (dir == PID_IN) ? PID_OUT : PID_IN;
u32 tok = TD_ACTIVE | ((u32)spid << TD_PID_SHIFT) | TD_TOGGLE;
t_status->token = tok;
t_status->next = QH_TERMINATE;
}
/* QH overlay 指向第一个 TD */
qh->ov_next = (u32)(g_qh_dma.phys + (u64)((u8 *)t_setup - (u8 *)g_qh_dma.virt));
/* 写完 QH/TD 后刷新 CPU cache——DMA 控制器读物理内存需要;
* 缺此步在 WHPX 下 QEMU 读不到 ov_next(竞态),TCG 下侥幸通过。 */
__asm__ volatile("wbinvd" ::: "memory");
ehci_mb();
return 0;
}
/* 构建 bulk 传输单 TD:dir 0=OUT 1=IN。
* in_dma: IN 方向的目标 DMA 缓冲(数据用 g_xfer,CSW 用 g_csw——
* 防止 CSW 读覆盖数据区前 13 字节)。OUT 方向 in_dma 忽略(数据先拷入
* in_dma 指向的缓冲)。 */
static int qh_submit_bulk(ehci_qh *qh, u8 dir, const void *data, u32 data_len,
struct dkm_dma_buffer *in_dma) {
qh->curqtd = 0;
qh->ov_next = QH_TERMINATE;
qh->ov_token = 0;
g_td_next = 0;
ehci_td *td = td_alloc();
if (!td) return -1;
struct dkm_dma_buffer *dst = in_dma ? in_dma : &g_xfer;
u8 *buf = (u8 *)dst->virt;
if (dir == PID_OUT) {
ehci_memcpy(buf, data, data_len);
__asm__ volatile("wbinvd" ::: "memory");
}
td->buf[0] = (u32)(dst->phys & 0xFFFFFFFFu);
u32 tok = TD_ACTIVE | ((u32)dir << TD_PID_SHIFT) | ((u32)data_len << TD_BYTES_SHIFT);
td->token = tok; /* toggle 由 HC 管理(DTC=0) */
qh->ov_next = (u32)(g_qh_dma.phys + (u64)((u8 *)td - (u8 *)g_qh_dma.virt));
__asm__ volatile("wbinvd" ::: "memory");
ehci_mb();
return 0;
}
/* 等待 QH 上的传输完成。轮询首个 TD 的 token(HC 执行后清 ACTIVE、
* 出错置 HALTED)——比检查 overlay 可靠:HC 未执行时 overlay token
* 保持 inactive,轮询 overlay 会假成功返回空数据。first_td 传 TD 池指针,
* 由调用方从 qh->ov_next 反推或直接记录。
* BUG-FIX(缓存一致性):EHCI HC 经 DMA 写 TD 到物理内存,CPU 轮询前
* 必须失效缓存行,否则读到 write-back cache 旧值(Active 恒 1)→ 假超时。
* QEMU 复现证据:first_td token=0x80280 显示 SETUP 已执行成功(Active 清、
* 无错误位),但轮询超时——正是 cache 陈旧。 */
static int qh_wait(ehci_qh *qh, ehci_td *first_td, u32 timeout_ms) {
(void)qh;
u64 deadline = dkm_rdtsc() + dkm_tsc_per_ms * timeout_ms;
for (;;) {
/* 失效 TD 所在缓存行,强制从内存读 HC 的 DMA 写结果 */
__asm__ volatile("clflush (%0)" : : "r"(first_td) : "memory");
u32 tok = first_td->token;
if (!(tok & TD_ACTIVE)) {
if (tok & TD_HALTED) {
g_log->warn("[ehci] transfer halted");
log_hex("[ehci] token=", tok);
return -2;
}
return 0;
}
if (dkm_rdtsc() > deadline) {
g_log->warn("[ehci] transfer timeout");
log_hex("[ehci] first_td token=", tok);
return -1;
}
__asm__ volatile("pause");
}
}
/* 启动 HC:把三个 QH 链成环(ctrl→bulk_out→bulk_in→ctrl),
* 在 ASE=0(async schedule 停止)时写一次 ASYNCLIST,然后 RUN|ASE。
* 之后每次提交只改 QH overlay,不再碰 ASYNCLIST(规范要求该寄存器
* 只能在 async schedule 停止时写——QEMU 会拒绝运行期写入)。 */
static int ehci_hc_start(void) {
u64 ctrl_phys = g_qh_dma.phys + (u64)((u8 *)g_qh_ctrl - (u8 *)g_qh_dma.virt);
u64 out_phys = g_qh_dma.phys + (u64)((u8 *)g_qh_bulk_out - (u8 *)g_qh_dma.virt);
u64 in_phys = g_qh_dma.phys + (u64)((u8 *)g_qh_bulk_in - (u8 *)g_qh_dma.virt);
/* hlink 链接指针必须带类型位 bit1=1(QH 类型)。
* QEMU v11 的 NLPTR_TYPE_GET(x)=((x)>>1)&3,QH 类型=1 → 写物理地址|2。
* BUG-FIX: 裸地址(bit1=0)→ QEMU fetchentry 报 "non queue head
* request in async schedule" 并重置 HC,TD 永不执行。 */
g_qh_ctrl->hlink = (u32)((out_phys & 0xFFFFFFFFu) | 2u);
g_qh_bulk_out->hlink = (u32)((in_phys & 0xFFFFFFFFu) | 2u);
g_qh_bulk_in->hlink = (u32)((ctrl_phys & 0xFFFFFFFFu) | 2u);
/* H 位(bit15) = 回收头标记:QEMU 的 WAITLISTHEAD 状态只在环中找到
* H=1 的 QH 时进入 FETCHENTRY→FETCHQH。不置 H 位 → 状态机永远停在
* WAITLISTHEAD,TD 永不执行。ctrl 作为环头必须置 H。 */
g_qh_ctrl->epchar |= (1u << 15);
ehci_mb();
/* 确保 ASE=0(复位后默认 0) */
u32 cmd = mmio_read32(g_caplen + EHCI_OP_USBCMD);
mmio_write32(g_caplen + EHCI_OP_USBCMD, cmd & ~USBCMD_ASE);
ehci_mb();
mmio_write32(g_caplen + EHCI_OP_ASYNCLIST, (u32)((ctrl_phys & 0xFFFFFFFFu) | 2u));
ehci_mb();
mmio_write32(g_caplen + EHCI_OP_USBCMD,
mmio_read32(g_caplen + EHCI_OP_USBCMD) | USBCMD_ASE | USBCMD_RUN);
ehci_mb();
g_log->info("[ehci] async schedule started");
return 0;
}
/* 简单控制传输封装 */
static int ehci_control(u8 dev_addr, u8 speed, u16 mps0,
const u8 *setup8, u8 *data, u32 data_len, u8 dir) {
qh_init(g_qh_ctrl, dev_addr, 0, speed, mps0, 1);
if (qh_submit_control(g_qh_ctrl, setup8, data, data_len, dir) != 0) return -1;
int rc = qh_wait(g_qh_ctrl, &g_td_pool[0], 5000);
/* IN 方向:失效数据缓冲缓存行后把 HC DMA 写入的数据拷回调用方 */
if (rc == 0 && dir == PID_IN && data && data_len > 0) {
__asm__ volatile("clflush (%0)" : : "r"(g_xfer.virt) : "memory");
__asm__ volatile("clflush 64(%0)" : : "r"(g_xfer.virt) : "memory");
ehci_memcpy(data, (u8 *)g_xfer.virt + 8, data_len);
}
return rc;
}
/* 简单 bulk 传输封装(端点号已含方向编码在 QH)。
* in_dma: IN 方向的目标 DMA 缓冲(g_xfer 或 g_csw)。
* BUG-FIX: CSW 必须用独立缓冲——若与数据共用 g_xfer,13 字节 CSW 会
* 覆盖数据区前 13 字节(bps 字段被清零)。 */
static int ehci_bulk(ehci_qh *qh, u8 dev_addr, u8 speed, u16 mps,
u8 ep_num, u8 dir, const void *data, u32 data_len,
struct dkm_dma_buffer *in_dma) {
qh_init(qh, dev_addr, ep_num, speed, mps, 0);
if (qh_submit_bulk(qh, dir, data, data_len, in_dma) != 0) return -1;
int rc = qh_wait(qh, &g_td_pool[0], 10000);
if (rc == 0 && dir == PID_IN) {
struct dkm_dma_buffer *dst = in_dma ? in_dma : &g_xfer;
/* 失效缓存行后拷贝 */
__asm__ volatile("clflush (%0)" : : "r"(dst->virt) : "memory");
ehci_memcpy((void *)data, dst->virt, data_len);
}
return rc;
}
/* ================================================================
* Phase 3: Port scan and reset
* ================================================================ */
static int ehci_reset_port(u32 port) {
u32 po = g_caplen + EHCI_OP_PORTSC + port * EHCI_PORT_STRIDE;
u32 ps = mmio_read32(po);
if (!(ps & PORTSC_CONNECT)) return -1;
/* 复位序列(EHCI 1.0 §4.2.4 + QEMU 模型兼容):
* 1) 置 PR=1 请求复位
* 2) 保持 PR=1 一小段时间(QEMU 不置 PRC,等待只是给模拟器处理窗口)
* 3) 清 PR —— QEMU 在 PR 1→0 下降沿执行 usb_port_reset 并置 PED(仅高速)
* 4) 轮询 PED 确认使能
* BUG-FIX: 原实现等待 PRC(bit20),但 QEMU 从不置该位 → 200ms 必超时
* 枚举中止(QEMU hcd-ehci.c ehci_port_write 只处理 PR 下降沿)。 */
mmio_write32(po, ps | PORTSC_PR);
dkm_delay_ms(50);
/* 清 PR + 清 change 位(1→0 下降沿触发复位) */
ps = mmio_read32(po);
mmio_write32(po, (ps & ~PORTSC_PR) | PORTSC_RWC);
/* 轮询 PED */
u64 deadline = dkm_rdtsc() + dkm_tsc_per_ms * 200;
while (dkm_rdtsc() < deadline) {
ps = mmio_read32(po);
if (ps & PORTSC_PED) {
DKM_STAT_INC(ehci_port_ok);
return 0;
}
if (!(ps & PORTSC_CONNECT)) return -2; /* 复位中断开 */
__asm__ volatile("pause");
}
g_log->warn("[ehci] port not enabled after reset");
return -3;
}
static u8 ehci_port_speed(u32 port) {
u32 po = g_caplen + EHCI_OP_PORTSC + port * EHCI_PORT_STRIDE;
u32 ps = mmio_read32(po);
return (u8)((ps >> PORTSC_LS_SHIFT) & PORTSC_LS_MASK);
}
/* ================================================================
* Phase 4: USB enumeration
* ================================================================ */
/* 前置声明(BOT/SCSI 定义在 enum_msc 之后) */
static int ehci_scsi_inquiry(void);
static int ehci_bot_send_cbw(u8 lun, u8 flags, u32 data_len,
const u8 *cb, u8 cb_len);
static int ehci_bot_receive_csw(void);
static int ehci_get_device_descriptor(u8 *out, u32 len) {
u8 setup[8];
setup[0] = 0x80; setup[1] = 0x06;
setup[2] = 0x00; setup[3] = 0x01; /* Device descriptor */
setup[4] = 0x00; setup[5] = 0x00;
setup[6] = (u8)(len & 0xFF); setup[7] = (u8)((len >> 8) & 0xFF);
ehci_zero(out, len);
/* GET_DESCRIPTOR 阶段 EP0 MPS 未知,按速度用默认值 */
u16 mps0 = 64;
if (g_msc.speed == LS_LOW) mps0 = 8;
return ehci_control(g_msc.dev_addr, g_msc.speed, mps0, setup, out, len, PID_IN);
}
static int ehci_set_address(u8 addr, u16 mps0) {
u8 setup[8];
setup[0] = 0x00; setup[1] = 0x05;
setup[2] = (u8)(addr & 0xFF); setup[3] = 0x00;
setup[4] = 0x00; setup[5] = 0x00;
setup[6] = 0x00; setup[7] = 0x00;
return ehci_control(0, g_msc.speed, mps0, setup, 0, 0, PID_OUT);
}
static int ehci_set_configuration(u8 addr, u8 cfg, u16 mps0) {
u8 setup[8];
setup[0] = 0x00; setup[1] = 0x09;
setup[2] = cfg; setup[3] = 0x00;
setup[4] = 0x00; setup[5] = 0x00;
setup[6] = 0x00; setup[7] = 0x00;
return ehci_control(addr, g_msc.speed, mps0, setup, 0, 0, PID_OUT);
}
static int ehci_get_config_descriptor(u8 addr, u8 *out, u32 len) {
u8 setup[8];
setup[0] = 0x80; setup[1] = 0x06;
setup[2] = 0x00; setup[3] = 0x02; /* Configuration descriptor */
setup[4] = 0x00; setup[5] = 0x00;
setup[6] = (u8)(len & 0xFF); setup[7] = (u8)((len >> 8) & 0xFF);
ehci_zero(out, len);
return ehci_control(addr, g_msc.speed, 64, setup, out, len, PID_IN);
}
/* 枚举 MSC 设备:SET_ADDRESS -> GET_DESCRIPTOR -> SET_CONFIGURATION -> 端点解析 */
static int ehci_enum_msc(u32 port) {
g_msc.speed = ehci_port_speed(port);
log_hex("[ehci] port speed=", g_msc.speed);
u16 mps0 = 64; /* 全速/高速 EP0 默认 64 */
if (g_msc.speed == LS_LOW) mps0 = 8;
/* SET_ADDRESS(用默认 pipe,mps 按速度) */
if (ehci_set_address(1, mps0) != 0) {
g_log->warn("[ehci] SET_ADDRESS failed");
return -1;
}
g_msc.dev_addr = 1;
g_msc.bulk_out_mps = mps0; /* 后续控制传输用已知 mps0 */
/* GET_DESCRIPTOR(device, 18) */
u8 dev_desc[18];
if (ehci_get_device_descriptor(dev_desc, 18) != 0) {
g_log->warn("[ehci] GET_DESCRIPTOR(Device) failed");
return -2;
}
u8 dev_class = dev_desc[4];
u16 vid = (u16)dev_desc[8] | ((u16)dev_desc[9] << 8);
u16 pid = (u16)dev_desc[10] | ((u16)dev_desc[11] << 8);
u8 real_mps0 = dev_desc[7];
log_hex("[ehci] dev class=", dev_class);
log_hex("[ehci] VID=", vid);
log_hex("[ehci] PID=", pid);
log_hex("[ehci] bMaxPacketSize0=", real_mps0);
/* 设备声明的真实 EP0 MPS 与猜测不同时,用真实值 */
if (real_mps0 >= 8 && real_mps0 <= 64) mps0 = real_mps0;
/* SET_CONFIGURATION(1) */
if (ehci_set_configuration(g_msc.dev_addr, 1, mps0) != 0) {
g_log->warn("[ehci] SET_CONFIGURATION failed");
return -3;
}
/* GET_DESCRIPTOR(config, 255) 并解析 MSC 接口 + bulk 端点 */
u8 cfg_desc[255];
if (ehci_get_config_descriptor(g_msc.dev_addr, cfg_desc, 255) != 0) {
g_log->warn("[ehci] GET_DESCRIPTOR(Config) failed");
return -4;
}
u16 total_len = (u16)cfg_desc[2] | ((u16)cfg_desc[3] << 8);
u8 bulk_out_ep = 0, bulk_in_ep = 0;
u16 bulk_out_mps = 512, bulk_in_mps = 512;
int msc_found = 0;
u32 pos = 9; /* 跳过 config descriptor */
while (pos + 2 <= (u32)total_len && pos + cfg_desc[pos] <= (u32)total_len) {
u8 desc_len = cfg_desc[pos];
u8 desc_type = cfg_desc[pos + 1];
if (desc_type == 4 && desc_len >= 9) {
u8 iface_class = cfg_desc[pos + 5];
u8 iface_sub = cfg_desc[pos + 6];
u8 iface_proto = cfg_desc[pos + 7];
if (iface_class == 0x08 && iface_sub == 0x06 && iface_proto == 0x50) {
msc_found = 1;
g_log->info("[ehci] MSC BOT interface found");
u32 ep_pos = pos + desc_len;
while (ep_pos + 2 <= (u32)total_len) {
u8 ep_len = cfg_desc[ep_pos];
if (ep_len == 0 || ep_pos + ep_len > (u32)total_len) break;
if (cfg_desc[ep_pos + 1] == 5) {
u8 ep_addr = cfg_desc[ep_pos + 2];
u8 ep_attr = cfg_desc[ep_pos + 3];
u16 ep_mps = (u16)cfg_desc[ep_pos + 4] | ((u16)cfg_desc[ep_pos + 5] << 8);
if ((ep_attr & 0x03) == 0x02) {
if (ep_addr & 0x80) {
bulk_in_ep = ep_addr & 0x0F;
bulk_in_mps = ep_mps;
} else {
bulk_out_ep = ep_addr & 0x0F;
bulk_out_mps = ep_mps;
}
}
} else if (cfg_desc[ep_pos + 1] == 4) {
break;
}
ep_pos += ep_len;
}
break;
}
}
pos += desc_len;
}
if (!msc_found || bulk_out_ep == 0 || bulk_in_ep == 0) {
g_log->warn("[ehci] no MSC BOT interface found");
return -5;
}
log_hex("[ehci] Bulk OUT EP=", bulk_out_ep);
log_hex("[ehci] Bulk IN EP=", bulk_in_ep);
log_hex("[ehci] Bulk OUT MPS=", bulk_out_mps);
log_hex("[ehci] Bulk IN MPS=", bulk_in_mps);
g_msc.bulk_out_ep = bulk_out_ep;
g_msc.bulk_in_ep = bulk_in_ep;
g_msc.bulk_out_mps = bulk_out_mps;
g_msc.bulk_in_mps = bulk_in_mps;
g_msc.cbw_tag = 1;
/* INQUIRY 验证设备是块设备 */
if (ehci_scsi_inquiry() != 0) {
g_log->warn("[ehci] INQUIRY failed or not block device");
}
return 0;
}
/* ================================================================
* Phase 5: BOT + SCSI(复用 xhci 已验证的 CBW/CSW/SCSI 组包逻辑)
* ================================================================ */
static int ehci_bot_send_cbw(u8 lun, u8 flags, u32 data_len,
const u8 *cb, u8 cb_len) {
u8 cbw[31];
ehci_zero(cbw, 31);
cbw[0] = 0x55; cbw[1] = 0x53; cbw[2] = 0x42; cbw[3] = 0x43;
u32 tag = g_msc.cbw_tag++;
cbw[4] = (u8)(tag & 0xFF);
cbw[5] = (u8)((tag >> 8) & 0xFF);
cbw[6] = (u8)((tag >> 16) & 0xFF);
cbw[7] = (u8)((tag >> 24) & 0xFF);
cbw[8] = (u8)(data_len & 0xFF);
cbw[9] = (u8)((data_len >> 8) & 0xFF);
cbw[10] = (u8)((data_len >> 16) & 0xFF);
cbw[11] = (u8)((data_len >> 24) & 0xFF);
cbw[12] = flags;
cbw[13] = lun;
cbw[14] = cb_len;
for (u8 i = 0; i < cb_len && i < 16; i++) cbw[15 + i] = cb[i];
return ehci_bulk(g_qh_bulk_out, g_msc.dev_addr, g_msc.speed,
g_msc.bulk_out_mps, g_msc.bulk_out_ep, PID_OUT, cbw, 31, 0);
}
static int ehci_bot_receive_csw(void) {
u8 csw[13];
/* CSW 用独立 DMA 缓冲,避免覆盖数据阶段读入 g_xfer 的数据 */
int rc = ehci_bulk(g_qh_bulk_in, g_msc.dev_addr, g_msc.speed,
g_msc.bulk_in_mps, g_msc.bulk_in_ep, PID_IN, csw, 13, &g_csw);
if (rc != 0) return rc;
if (csw[0] != 0x55 || csw[1] != 0x53 || csw[2] != 0x42 || csw[3] != 0x53) {
g_log->error("[ehci] CSW signature mismatch");
return -2;
}
if (csw[12] != 0) {
log_hex("[ehci] CSW status=", csw[12]);
return -3;
}
return 0;
}
static int ehci_scsi_inquiry(void) {
u8 cb[16];
ehci_zero(cb, 16);
cb[0] = SCSI_INQUIRY;
cb[4] = 36;
if (ehci_bot_send_cbw(0, 0x80, 36, cb, 6) != 0) return -1;
u8 inq[36];
if (ehci_bulk(g_qh_bulk_in, g_msc.dev_addr, g_msc.speed,
g_msc.bulk_in_mps, g_msc.bulk_in_ep, PID_IN, inq, 36, &g_xfer) != 0) return -2;
if (ehci_bot_receive_csw() != 0) return -3;
log_hex("[ehci] INQ PeripheralType=", inq[0] & 0x1F);
return ((inq[0] & 0x1F) == 0) ? 0 : -4;
}
static int ehci_scsi_read_capacity(u64 *out_sectors, u32 *out_blk) {
u8 cb[16];
ehci_zero(cb, 16);
cb[0] = SCSI_READ_CAPACITY10;
if (ehci_bot_send_cbw(0, 0x80, 8, cb, 10) != 0) return -1;
u8 cap[8];
if (ehci_bulk(g_qh_bulk_in, g_msc.dev_addr, g_msc.speed,
g_msc.bulk_in_mps, g_msc.bulk_in_ep, PID_IN, cap, 8, &g_xfer) != 0) return -2;
if (ehci_bot_receive_csw() != 0) return -3;
u32 max_lba = ((u32)cap[0] << 24) | ((u32)cap[1] << 16) | ((u32)cap[2] << 8) | (u32)cap[3];
u32 blk = ((u32)cap[4] << 24) | ((u32)cap[5] << 16) | ((u32)cap[6] << 8) | (u32)cap[7];
*out_sectors = (u64)max_lba + 1;
*out_blk = blk;
log_hex("[ehci] capacity sectors=", *out_sectors);
log_hex("[ehci] block size=", blk);
return 0;
}
static int ehci_scsi_test_unit_ready(void) {
u8 cb[16];
ehci_zero(cb, 16);
cb[0] = SCSI_TEST_UNIT_READY;
if (ehci_bot_send_cbw(0, 0x00, 0, cb, 6) != 0) return -1;
return ehci_bot_receive_csw();
}
static int ehci_scsi_read10(u64 lba, u32 count, void *buffer) {
u8 cb[16];
ehci_zero(cb, 16);
cb[0] = SCSI_READ10;
cb[2] = (u8)((lba >> 24) & 0xFF);
cb[3] = (u8)((lba >> 16) & 0xFF);
cb[4] = (u8)((lba >> 8) & 0xFF);
cb[5] = (u8)(lba & 0xFF);
cb[7] = (u8)((count >> 8) & 0xFF);
cb[8] = (u8)(count & 0xFF);
u32 data_len = count * 512;
if (ehci_bot_send_cbw(0, 0x80, data_len, cb, 10) != 0) return -1;
if (ehci_bulk(g_qh_bulk_in, g_msc.dev_addr, g_msc.speed,
g_msc.bulk_in_mps, g_msc.bulk_in_ep, PID_IN, buffer, data_len, &g_xfer) != 0) return -2;
return ehci_bot_receive_csw();
}
static int ehci_scsi_write10(u64 lba, u32 count, const void *buffer) {
u8 cb[16];
ehci_zero(cb, 16);
cb[0] = SCSI_WRITE10;
cb[2] = (u8)((lba >> 24) & 0xFF);
cb[3] = (u8)((lba >> 16) & 0xFF);
cb[4] = (u8)((lba >> 8) & 0xFF);
cb[5] = (u8)(lba & 0xFF);
cb[7] = (u8)((count >> 8) & 0xFF);
cb[8] = (u8)(count & 0xFF);
u32 data_len = count * 512;
if (ehci_bot_send_cbw(0, 0x00, data_len, cb, 10) != 0) return -1;
if (ehci_bulk(g_qh_bulk_out, g_msc.dev_addr, g_msc.speed,
g_msc.bulk_out_mps, g_msc.bulk_out_ep, PID_OUT, buffer, data_len, 0) != 0) return -2;
return ehci_bot_receive_csw();
}
/* ================================================================
* Block provider
* ================================================================ */
static int ehci_block_read(void *ctx, u64 lba, u32 count, void *buffer) {
(void)ctx;
if (!g_msc.ready || !buffer || count == 0) return -1;
DKM_STAT_INC(ehci_block_reads);
u8 *buf = (u8 *)buffer;
while (count > 0) {
u32 chunk = count > 16 ? 16 : count;
if (ehci_scsi_read10(lba, chunk, g_xfer.virt) != 0) {
log_hex("[ehci] READ10 failed lba=", lba);
return -1;
}
ehci_memcpy(buf, g_xfer.virt, chunk * 512);
buf += chunk * 512;
lba += chunk;
count -= chunk;
}
return 0;
}
static int ehci_block_write(void *ctx, u64 lba, u32 count, const void *buffer) {
(void)ctx;
if (!g_msc.ready || !buffer || count == 0) return -1;
DKM_STAT_INC(ehci_block_writes);
const u8 *buf = (const u8 *)buffer;
while (count > 0) {
u32 chunk = count > 16 ? 16 : count;
ehci_memcpy(g_xfer.virt, buf, chunk * 512);
__asm__ volatile("wbinvd" ::: "memory");
if (ehci_scsi_write10(lba, chunk, g_xfer.virt) != 0) {
log_hex("[ehci] WRITE10 failed lba=", lba);
return -1;
}
buf += chunk * 512;
lba += chunk;
count -= chunk;
}
return 0;
}
/* ================================================================
* driver_init
* ================================================================ */
__attribute__((visibility("default")))
int driver_init(const struct dkm_kernel_api *api,
struct dkm_driver_handle *handle) {
(void)handle;
dkm_tsc_calibrate();
if (!api || !api->log) return -1;
g_api = api;
g_log = api->log;
dkm_instr_init(api);
g_log->info("[ehci] init begin");
/* PCI 发现 0C/03/20 */
u8 bus = 0, dev = 0, func = 0;
if (ehci_find(&bus, &dev, &func) != 0) {
g_log->info("[ehci] EHCI controller not found");
g_log->info("[ehci] driver ready");
return 0;
}
g_pci_bus = bus; g_pci_dev = dev; g_pci_func = func;
DKM_STAT_INC(ehci_pci_found);
g_log->info("[ehci] EHCI controller found");
log_hex("[ehci] bus=", bus);
log_hex("[ehci] dev=", dev);
log_hex("[ehci] func=", func);
u32 vd = dkm_pci_read(bus, dev, func, PCI_VENDOR_ID);
log_hex("[ehci] vendor=", vd & 0xffff);
log_hex("[ehci] device=", vd >> 16);
/* 使能 MEM + BUSM */
u32 command = dkm_pci_read(bus, dev, func, PCI_COMMAND) & 0xffff;
command |= PCI_CMD_MEM | PCI_CMD_BUSM;
dkm_pci_write(bus, dev, func, PCI_COMMAND, command);
log_hex("[ehci] PCI command=", command);
/* BAR0(EHCI 通常是 32 位 MMIO) */
u32 bar0_lo = dkm_pci_read(bus, dev, func, PCI_BAR0);
u64 bar_phys;
if ((bar0_lo & 0x7) == 0x4) {
u32 bar1_hi = dkm_pci_read(bus, dev, func, PCI_BAR1);
bar_phys = ((u64)bar1_hi << 32) | (u64)(bar0_lo & 0xFFFFFFF0u);
} else {
bar_phys = (u64)(bar0_lo & 0xFFFFFFF0u);
}
log_hex("[ehci] BAR0 phys=", bar_phys);
if (!api->hhdm_offset || !bar_phys) {
g_log->warn("[ehci] missing HHDM or BAR0");
g_log->info("[ehci] driver ready");
return 0;
}
g_mmio = ehci_map_bar(bar_phys);
if (!g_mmio) {
g_log->error("[ehci] BAR MMIO unavailable");
g_log->info("[ehci] driver ready");
return 0;
}
/* 能力寄存器 */
g_caplen = mmio_read32(EHCI_CAP_CAPLENGTH) & 0xFF;
u32 hcsp = mmio_read32(EHCI_CAP_HCSPARAMS);
u32 hccp = mmio_read32(EHCI_CAP_HCCPARAMS);
g_nports = hcsp & 0x0F;
g_64bit = hccp & 1u;
g_ppc = (hcsp >> 4) & 1u;
log_hex("[ehci] CAPLEN=", g_caplen);
log_hex("[ehci] nports=", g_nports);
log_hex("[ehci] 64bit=", g_64bit);
log_hex("[ehci] PPC=", g_ppc);
if (g_nports == 0) {
g_log->error("[ehci] no ports");
g_log->info("[ehci] driver ready");
return 0;
}
/* HC 复位 */
if (ehci_hc_reset() != 0) {
g_log->error("[ehci] HC reset failed");
g_log->info("[ehci] driver ready");
return 0;
}
/* 64 位控制器:CTRLDSSEGMENT = 0 */
if (g_64bit) mmio_write32(g_caplen + 0x10, 0);
/* DMA:异步列表页 + 数据缓冲 */
if (!api->dma) {
g_log->warn("[ehci] DMA API unavailable");
g_log->info("[ehci] driver ready");
return 0;
}
if (api->dma->alloc_pages(1, 4096, 0x100000000ULL, &g_qh_dma) != 0) {
g_log->error("[ehci] async list alloc failed");
g_log->info("[ehci] driver ready");
return 0;
}
if (api->dma->alloc_pages(16, 4096, 0x100000000ULL, &g_xfer) != 0) {
g_log->error("[ehci] xfer buf alloc failed");
g_log->info("[ehci] driver ready");
return 0;
}
if (api->dma->alloc_pages(1, 4096, 0x100000000ULL, &g_csw) != 0) {
g_log->error("[ehci] csw buf alloc failed");
g_log->info("[ehci] driver ready");
return 0;
}
ehci_zero(g_qh_dma.virt, g_qh_dma.size);
ehci_zero(g_xfer.virt, g_xfer.size);
ehci_zero(g_csw.virt, g_csw.size);
/* QH 布局:必须 32 字节对齐(EHCI 规范)。ctrl@0, out@64, in@128;
* TD 池 @256(TD 32 字节对齐)。原 48 字节间距导致 out/in 未对齐,
* HC 无法处理 QH → TD 永不被执行 → 超时。 */
g_qh_ctrl = (ehci_qh *)((u8 *)g_qh_dma.virt + 0);
g_qh_bulk_out = (ehci_qh *)((u8 *)g_qh_dma.virt + 64);
g_qh_bulk_in = (ehci_qh *)((u8 *)g_qh_dma.virt + 128);
g_td_pool = (ehci_td *)((u8 *)g_qh_dma.virt + 256);
/* 建环并启动 async schedule(必须在 CONFIGFLAG/端口操作前) */
ehci_hc_start();
/* CONFIGFLAG=1(OS 所有端口) */
mmio_write32(g_caplen + EHCI_OP_CONFIGFLAG, 1u);
/* 端口电源 */
for (u32 p = 0; p < g_nports; p++) {
u32 po = g_caplen + EHCI_OP_PORTSC + p * EHCI_PORT_STRIDE;
u32 ps = mmio_read32(po);
if (g_ppc && !(ps & PORTSC_PP)) {
mmio_write32(po, ps | PORTSC_PP);
dkm_delay_ms(20);
}
}
dkm_delay_ms(100); /* 端口稳定 */
/* 扫描端口,枚举 MSC */
g_msc.ready = 0;
for (u32 p = 0; p < g_nports; p++) {
u32 po = g_caplen + EHCI_OP_PORTSC + p * EHCI_PORT_STRIDE;
u32 ps = mmio_read32(po);
log_hex("[ehci] port=", p);
log_hex("[ehci] PORTSC=", ps);
if (!(ps & PORTSC_CONNECT)) continue;
if (ehci_reset_port(p) != 0) {
g_log->warn("[ehci] port reset failed");
continue;
}
dkm_delay_ms(100);
if (ehci_enum_msc(p) != 0) {
g_log->warn("[ehci] MSC enumeration failed");
continue;
}
/* TEST UNIT READY(重试 5 次) */
for (int i = 0; i < 5; i++) {
if (ehci_scsi_test_unit_ready() == 0) break;
dkm_delay_ms(100);
}
/* READ CAPACITY */
u64 sectors = 0;
u32 blk = 512;
if (ehci_scsi_read_capacity(&sectors, &blk) != 0) {
g_log->warn("[ehci] READ CAPACITY failed");
sectors = 0; blk = 512;
}
g_msc.sector_count = sectors;
g_msc.sector_size = blk;
g_msc.ready = 1;
DKM_STAT_INC(ehci_msc_found);
log_hex("[ehci] MSC device ready, sectors=", sectors);
log_hex("[ehci] MSC device block_size=", blk);
break;
}
/* 注册 block provider */
if (g_msc.ready && api->block && api->block->register_device) {
struct dkm_block_device_desc desc;
desc.name = "usb2";
desc.sector_size = g_msc.sector_size;
desc.sector_count = g_msc.sector_count;
desc.ctx = 0;
desc.read = ehci_block_read;
desc.write = ehci_block_write;
int index = api->block->register_device(&desc);
log_hex("[ehci] block provider index=", (u64)(i64)index);
} else {
g_log->info("[ehci] no MSC device found; block provider not registered");
}
g_log->info("[ehci] driver ready");
return 0;
}
__attribute__((visibility("default")))
int driver_exit(struct dkm_driver_handle *handle) {
(void)handle;
if (g_mmio) {
mmio_write32(g_caplen + EHCI_OP_USBCMD,
mmio_read32(g_caplen + EHCI_OP_USBCMD) & ~USBCMD_RUN);
}
return 0;
}
+430 -90
View File
@@ -92,6 +92,9 @@ const struct dkm_driver_desc driver_desc = {
#define XHCI_RT_IR0_ERDP_LO 0x38
#define XHCI_RT_IR0_ERDP_HI 0x3C
/* ERDP bits: bit3 = Event Handler Busy (软件写 1 清挂起) */
#define ERDP_EHB (1u << 3)
/* USBCMD bits */
#define USBCMD_RS (1u << 0)
#define USBCMD_RST (1u << 1)
@@ -109,8 +112,11 @@ const struct dkm_driver_desc driver_desc = {
#define PORTSC_PR (1u << 4)
#define PORTSC_PLS_SHIFT 5
#define PORTSC_PLS_MASK 0xF
#define PORTSC_SPEED_SHIFT 17
#define PORTSC_SPEED_MASK 0x7
/* Port Speed 字段在 PORTSC bits[13:10](xHCI 1.2 §5.4.8)。
* BUG-FIX: 原实现 shift=17/mask=0x7 是错的——QEMU 用 10:13,
* 误读导致 SuperSpeed(4) 被当成 FULL(1),EP0 MPS 错误。 */
#define PORTSC_SPEED_SHIFT 10
#define PORTSC_SPEED_MASK 0xF
/* TRB types */
#define TRB_TYPE_NORMAL 0x01
@@ -124,12 +130,14 @@ const struct dkm_driver_desc driver_desc = {
#define TRB_TYPE_CONFIGURE_EP 0x0C
#define TRB_TYPE_NOOP 0x17
/* Event TRB types — same namespace as command/transfer TRB types.
* Per xHCI spec §6.4: these are the TRB Type field values in the
* Event TRB control dword [15:10]. */
#define EVT_TYPE_TRANSFER 0x01 /* Transfer Event */
#define EVT_TYPE_CMD_COMPLETE 0x02 /* Command Completion Event */
#define EVT_TYPE_PORT_CHANGE 0x21 /* Port Status Change Event */
/* Event TRB types — xHCI 1.2 spec Table 6-28 (TRB Type field [15:10]).
* 规范值:Transfer=0x20, Command Completion=0x21, Port Status Change=0x22。
* BUG-FIX: 原定义 0x01/0x02/0x21 与规范冲突——CMD_COMPLETE(0x21) 被
* 误判为 PORT_CHANGE 事件消费,导致 Enable Slot 等命令事件环被提前
* 清空,后续命令全部超时(QEMU hcd-xhci.c xhci_write_event 佐证)。 */
#define EVT_TYPE_TRANSFER 0x20 /* Transfer Event */
#define EVT_TYPE_CMD_COMPLETE 0x21 /* Command Completion Event */
#define EVT_TYPE_PORT_CHANGE 0x22 /* Port Status Change Event */
/* TRB control field helpers */
#define TRB_TYPE_SHIFT 10
@@ -281,6 +289,149 @@ static void log_hex(const char *prefix, u64 value) {
g_log->info(buf);
}
/* ================================================================
* Framebuffer 阶段诊断(实机无串口时屏幕直接显示 xhci 失败点)
* 失败时整屏填背景色 + 中央画大号两位十六进制状态码,然后 halt。
* 码表(调用点注释中注明):
* 红底 0x01..0x07 基础设施失败(PCI/MMIO/caps/reset/ring/start)
* 红底 0x11..0x14 PCI 自检细分(见 xhci_pci_diag_code)
* 黄底 0x08 所有端口无设备可枚举
* 黄底 0x0A..0x0F 枚举失败(slot/address/descriptor/configure/scsi)
* 依赖 dkm_kernel_api.fb_* 字段(32bpp,与 console_fb 一致)。
* ================================================================ */
static const u8 g_fb_font_hex[16][8] = {
{0x3C,0x66,0x6E,0x76,0x66,0x66,0x3C,0x00}, /* 0 */
{0x18,0x38,0x18,0x18,0x18,0x18,0x7E,0x00}, /* 1 */
{0x3C,0x66,0x06,0x0C,0x18,0x30,0x7E,0x00}, /* 2 */
{0x3C,0x66,0x06,0x1C,0x06,0x66,0x3C,0x00}, /* 3 */
{0x0C,0x1C,0x3C,0x6C,0x7E,0x0C,0x0C,0x00}, /* 4 */
{0x7E,0x60,0x7C,0x06,0x06,0x66,0x3C,0x00}, /* 5 */
{0x1C,0x30,0x60,0x7C,0x66,0x66,0x3C,0x00}, /* 6 */
{0x7E,0x66,0x06,0x0C,0x18,0x18,0x18,0x00}, /* 7 */
{0x3C,0x66,0x66,0x3C,0x66,0x66,0x3C,0x00}, /* 8 */
{0x3C,0x66,0x66,0x3E,0x06,0x0C,0x38,0x00}, /* 9 */
{0x3C,0x66,0x66,0x7E,0x66,0x66,0x66,0x00}, /* A */
{0x7C,0x66,0x66,0x7C,0x66,0x66,0x7C,0x00}, /* B */
{0x3C,0x66,0x60,0x60,0x60,0x66,0x3C,0x00}, /* C */
{0x78,0x6C,0x66,0x66,0x66,0x6C,0x78,0x00}, /* D */
{0x7E,0x60,0x60,0x7C,0x60,0x60,0x7E,0x00}, /* E */
{0x7E,0x60,0x60,0x7C,0x60,0x60,0x60,0x00}, /* F */
};
static void fb_draw_char(u32 *fb, u64 pitch, int x0, int y0, int scale,
u32 color, int ch) {
const u8 *g = g_fb_font_hex[ch & 0xF];
for (int row = 0; row < 8; row++) {
u8 bits = g[row];
for (int col = 0; col < 8; col++) {
if (!(bits & (0x80u >> col))) continue;
for (int sy = 0; sy < scale; sy++) {
u32 *line = (u32 *)((u8 *)fb + (u64)(y0 + row * scale + sy) * pitch);
for (int sx = 0; sx < scale; sx++)
line[x0 + col * scale + sx] = color;
}
}
}
}
static void fb_diag_show(const struct dkm_kernel_api *api, u32 bg, u32 code) {
if (!api || !api->fb_address || !api->fb_width || !api->fb_height)
return; /* 无 framebuffer 时退化为仅串口日志 */
u32 *fb = (u32 *)api->fb_address;
u64 pitch = api->fb_pitch;
u64 w = api->fb_width, h = api->fb_height;
for (u64 y = 0; y < h; y++) {
u32 *line = (u32 *)((u8 *)fb + y * pitch);
for (u64 x = 0; x < w; x++) line[x] = bg;
}
int scale = 8;
int cw = 8 * scale;
int cx = (int)(w / 2) - cw; /* 两位数字整体居中 */
int cy = (int)(h / 2) - (8 * scale) / 2;
u32 fg = 0xFFFFFFFFu;
if (code >= 0x10) fb_draw_char(fb, pitch, cx, cy, scale, fg, (int)(code >> 4));
fb_draw_char(fb, pitch, cx + cw, cy, scale, fg, (int)(code & 0xF));
/* 停住屏幕,等待实机拍照/观察 */
for (;;) {
__asm__ volatile("cli; hlt");
}
}
/* 任意位数 hex(n=1..8),低位在前填充 */
static void fb_draw_hexn(u32 *fb, u64 pitch, int x0, int y0, int scale,
u32 color, u32 v, int n) {
for (int i = 0; i < n; i++) {
int nib = (int)((v >> (4 * (n - 1 - i))) & 0xF);
fb_draw_char(fb, pitch, x0 + i * 8 * scale, y0, scale, color, nib);
}
}
/* PCI 自检诊断清单项(bus/dev/device_id/class/progif) */
struct usb_ctl_info {
u32 bus;
u32 dev;
u32 devid; /* PCI device ID */
u32 cls; /* (class<<8)|subclass */
u32 progif;
};
/* 扩展诊断:大字标题码 + 下方逐行列出扫描到的 PCI 设备。
* 每行:bus(1) dev(1) deviceid(4) = 左 6 hex,class(2) progif(2) = 右 4 hex。
* scale=2 支持 16 行(640x480 完整容纳)。device ID 用于区分芯片型号:
* Intel 7系: xHCI=1e31, EHCI1=1e2d, EHCI2=1e26
* Intel 6系: EHCI1=1c2d, EHCI2=1c26 (H61 仅 1 个 EHCI)
* 第三方 USB3: ASMedia=1b21, Renesas=1033 */
/* 诊断用,保留 */
static void fb_diag_show_usb(const struct dkm_kernel_api *api, u32 bg, u32 code,
const struct usb_ctl_info *usb, u32 usb_count) __attribute__((unused));
static void fb_diag_show_usb(const struct dkm_kernel_api *api, u32 bg, u32 code,
const struct usb_ctl_info *usb, u32 usb_count) {
if (!api || !api->fb_address || !api->fb_width || !api->fb_height)
return;
u32 *fb = (u32 *)api->fb_address;
u64 pitch = api->fb_pitch;
u64 w = api->fb_width, h = api->fb_height;
for (u64 y = 0; y < h; y++) {
u32 *line = (u32 *)((u8 *)fb + y * pitch);
for (u64 x = 0; x < w; x++) line[x] = bg;
}
u32 fg = 0xFFFFFFFFu;
/* 标题大字(scale 6,两位居中,固定顶部) */
int s = 6, cw = 8 * s;
int cx = (int)(w / 2) - cw;
int cy = 8;
if (code >= 0x10) fb_draw_char(fb, pitch, cx, cy, s, fg, (int)(code >> 4));
fb_draw_char(fb, pitch, cx + cw, cy, s, fg, (int)(code & 0xF));
/* 信息行(scale 2,最多 16 行):
* 左:bus(1)+dev(1)+devid(4)=6 hex;右:class(2)+progif(2)=4 hex */
int s2 = 2, cw2 = 8 * s2;
int row_y = cy + 8 * s + 8;
int total = (6 + 1 + 4) * cw2; /* 176px */
int xl = (int)(w / 2) - total / 2;
int xr = xl + (6 + 1) * cw2;
u32 max_rows = usb_count < 16 ? usb_count : 16;
for (u32 i = 0; i < max_rows; i++) {
u32 bd = ((usb[i].bus & 0xFF) << 4) | (usb[i].dev & 0x1F);
fb_draw_hexn(fb, pitch, xl, row_y, s2, fg, bd, 2);
fb_draw_hexn(fb, pitch, xl + 2 * cw2, row_y, s2, fg, usb[i].devid & 0xFFFF, 4);
fb_draw_hexn(fb, pitch, xr, row_y, s2, fg, usb[i].cls & 0xFFFF, 2);
fb_draw_hexn(fb, pitch, xr + 2 * cw2, row_y, s2, fg, usb[i].progif & 0xFFFF, 2);
row_y += 8 * s2 + 4; /* 20px/行 */
}
for (;;) {
__asm__ volatile("cli; hlt");
}
}
/* 红底 = 基础设施失败,halt(0xFFFF0000 在 BGRA 下是纯红;
* 原 0xFF0000FF 实际渲染为蓝——0x01 那次实机测试显示“蓝底”即此原因) */
#define FB_FATAL(api, code) fb_diag_show((api), 0xFFFF0000u, (code))
/* 红底 PCI 自检:标题码 + USB 控制器清单 */
#define FB_FATAL_show_usb(api, code) \
fb_diag_show_usb((api), 0xFFFF0000u, (code), g_diag_usb, g_diag_usb_count)
/* 黄底 = 枚举失败,halt */
#define FB_ENUM_FAIL(code) fb_diag_show(g_api, 0xFFFFC800u, (code))
static void xhci_zero(void *ptr, u32 len) {
u8 *p = (u8 *)ptr;
for (u32 i = 0; i < len; i++) p[i] = 0;
@@ -321,6 +472,96 @@ static __inline__ void xhci_mb(void) {
* Phase 1: PCI discovery + MMIO mapping
* ================================================================ */
/* PCI 自检:区分“传统 0xCF8/0xCFC 配置机制失效” vs “确实无 xHCI 控制器”。
* 实机现象:xhci_find 全扫描失败(诊断码 0x01)——USB3 主板必然有 xHCI,
* 扫不到只可能是 (a) 配置机制读不到任何设备 (b) 设备在异常位置 (c) 控制器
* 是 EHCI 等非 xHCI。返回细分诊断码:
* 0x11 bus0/dev0/func0 vendor=0xFFFF → 0xCF8/0xCFC 机制失效
* 0x12 机制可用但全扫描无任何 USB 控制器 (class 0x0C/03)
* 0x13 有 USB 控制器但无 prog_if=0x30(全部 EHCI/UHCI/OHCI)
* 0x14 存在 prog_if=0x30 的 xHCI 但 xhci_find 漏匹配(防御性,理论不可能)
* 同时把扫描到的设备填入 g_diag_usb 供屏幕显示——记录策略:
* 第一遍收集全部 USB 控制器(class 0C/03,含 bus1+ 第三方芯片),
* 第二遍收集其他设备(bus0 优先),总上限 16 行。
* 关键 device ID 判读:Intel 7系 xHCI=1e31 / EHCI1=1e2d / EHCI2=1e26;
* Intel 6系 EHCI1=1c2d / EHCI2=1c26(H61 仅 1 个);ASMedia=1b21;
* Renesas=1033。 */
static struct usb_ctl_info g_diag_usb[16];
static u32 g_diag_usb_count;
#define DIAG_MAX 16
static void diag_add(u32 bus, u32 dev, u32 devid, u32 cls, u32 progif) {
if (g_diag_usb_count >= DIAG_MAX) return;
g_diag_usb[g_diag_usb_count].bus = bus;
g_diag_usb[g_diag_usb_count].dev = dev;
g_diag_usb[g_diag_usb_count].devid = devid;
g_diag_usb[g_diag_usb_count].cls = cls;
g_diag_usb[g_diag_usb_count].progif = progif;
g_diag_usb_count++;
}
/* 诊断用,保留(无 xHCI 场景默认不调用,可通过临时改 driver_init 调试) */
static u32 xhci_pci_diag_code(void) __attribute__((unused));
static u32 xhci_pci_diag_code(void) {
u32 vd0 = dkm_pci_read(0, 0, 0, PCI_VENDOR_ID);
g_diag_usb_count = 0;
if ((vd0 & 0xffff) == 0xffff) return 0x11;
u32 usb_total = 0, xhci_total = 0;
/* 第一遍:USB 控制器(全 bus,含 bus1+ 第三方芯片) */
for (u16 bus = 0; bus < 256; bus++) {
for (u8 dev = 0; dev < 32; dev++) {
u32 vd = dkm_pci_read((u8)bus, dev, 0, PCI_VENDOR_ID);
if ((vd & 0xffff) == 0xffff) continue;
u8 header = (u8)(dkm_pci_read((u8)bus, dev, 0, PCI_HEADER) >> 16);
u8 func_count = (header & 0x80) ? 8 : 1;
for (u8 func = 0; func < func_count; func++) {
u32 vd2 = dkm_pci_read((u8)bus, dev, func, PCI_VENDOR_ID);
if ((vd2 & 0xffff) == 0xffff) continue;
u32 class_reg = dkm_pci_read((u8)bus, dev, func, 0x08);
u8 prog_if = (u8)((class_reg >> 8) & 0xff);
u8 subclass = (u8)((class_reg >> 16) & 0xff);
u8 class_code = (u8)((class_reg >> 24) & 0xff);
if (class_code == 0x0C && subclass == 0x03) {
usb_total++;
if (prog_if == 0x30) xhci_total++;
diag_add(bus, dev, vd2 >> 16,
(u32)((class_code << 8) | subclass), prog_if);
}
}
}
}
/* 第二遍:其他设备补位(bus0 优先) */
if (g_diag_usb_count < DIAG_MAX) {
for (u16 bus = 0; bus < 256 && g_diag_usb_count < DIAG_MAX; bus++) {
for (u8 dev = 0; dev < 32 && g_diag_usb_count < DIAG_MAX; dev++) {
u32 vd = dkm_pci_read((u8)bus, dev, 0, PCI_VENDOR_ID);
if ((vd & 0xffff) == 0xffff) continue;
u8 header = (u8)(dkm_pci_read((u8)bus, dev, 0, PCI_HEADER) >> 16);
u8 func_count = (header & 0x80) ? 8 : 1;
for (u8 func = 0; func < func_count && g_diag_usb_count < DIAG_MAX; func++) {
u32 vd2 = dkm_pci_read((u8)bus, dev, func, PCI_VENDOR_ID);
if ((vd2 & 0xffff) == 0xffff) continue;
u32 class_reg = dkm_pci_read((u8)bus, dev, func, 0x08);
u8 prog_if = (u8)((class_reg >> 8) & 0xff);
u8 subclass = (u8)((class_reg >> 16) & 0xff);
u8 class_code = (u8)((class_reg >> 24) & 0xff);
if (class_code == 0x0C && subclass == 0x03) continue; /* 已收集 */
diag_add(bus, dev, vd2 >> 16,
(u32)((class_code << 8) | subclass), prog_if);
}
}
}
}
if (usb_total == 0) return 0x12;
if (xhci_total > 0) return 0x14;
return 0x13;
}
static int xhci_find(u8 *out_bus, u8 *out_dev, u8 *out_func) {
for (u16 bus = 0; bus < 256; bus++) {
for (u8 dev = 0; dev < 32; dev++) {
@@ -518,9 +759,18 @@ static int xhci_parse_caps(void) {
g_doorbell_off = mmio_read32(XHCI_CAP_DBOFF) & 0xFFFFFFF0u;
g_runtime_off = mmio_read32(XHCI_CAP_RTSOFF) & 0xFFFFFFE0u;
/* Page size */
/* Page size: PAGESIZE 寄存器 bit[n] 置位表示支持 2^(n+12) 字节页。
* 取置位的最低 bit(xHCI 规范要求软件使用最小支持页)。
* 原实现 (ps_reg & 0xF) 语义错误,实机多 bit 置位时会得到错误页大小。 */
u32 ps_reg = mmio_read32(g_cap_length + XHCI_OP_PAGESIZE);
g_page_size = 1u << ((ps_reg & 0xF) + 12);
u32 ps_bits = ps_reg & 0xFFFFu;
u32 ps_shift = 0;
if (ps_bits) {
while (!(ps_bits & 1u)) { ps_bits >>= 1; ps_shift++; }
g_page_size = 4096u << ps_shift;
} else {
g_page_size = 4096;
}
log_hex("[xhci] CAPLEN=", g_cap_length);
log_hex("[xhci] MaxSlots=", g_max_slots);
@@ -591,9 +841,13 @@ static u32 xhci_ring_enqueue(xhci_ring *ring, u64 param, u32 status, u32 control
return idx;
}
/* Ring a doorbell: slot_id=0 for command, otherwise endpoint doorbell */
/* Ring a doorbell: slot_id=0 for command, otherwise endpoint doorbell。
* Doorbell Registers 每个 4 字节(xHCI 1.2 §5.6):offset = slot_id * 4。
* BUG-FIX: 原实现 slot_id * 0x20 偏移错误——QEMU 门铃区 reg>>=2 后
* reg 即 slot_id,0x20 偏移会敲到 slot 8,该 slot 无 EP → 控制器不
* 处理 TRB → 无 Transfer Event → 轮询超时。 */
static void xhci_ring_doorbell(u32 slot_id, u32 target) {
mmio_write32(g_doorbell_off + slot_id * 0x20, target);
mmio_write32(g_doorbell_off + slot_id * 4, target);
}
/* ================================================================
@@ -627,9 +881,9 @@ static int xhci_poll_event(u32 expected_type, u64 timeout_ms,
g_evt_ring.enqueue = (g_evt_ring.enqueue + 1) % (g_evt_ring.size - 1);
if (g_evt_ring.enqueue == 0) g_evt_ccs ^= 1;
/* Update ERDP */
/* Update ERDP: 地址 16 字节对齐,bit0 保持 0,bit3=EHB 清挂起 */
u64 erdp = g_evt_ring.dma.phys + (u64)g_evt_ring.enqueue * sizeof(xhci_trb);
mmio_write64(g_runtime_off + XHCI_RT_IR0_ERDP_LO, erdp | g_evt_ccs);
mmio_write64(g_runtime_off + XHCI_RT_IR0_ERDP_LO, erdp | ERDP_EHB);
/* Check completion code */
u32 cc = (evt->status >> 24) & 0xFF;
@@ -659,7 +913,7 @@ static int xhci_poll_event(u32 expected_type, u64 timeout_ms,
g_evt_ring.enqueue = (g_evt_ring.enqueue + 1) % (g_evt_ring.size - 1);
if (g_evt_ring.enqueue == 0) g_evt_ccs ^= 1;
u64 erdp2 = g_evt_ring.dma.phys + (u64)g_evt_ring.enqueue * sizeof(xhci_trb);
mmio_write64(g_runtime_off + XHCI_RT_IR0_ERDP_LO, erdp2 | g_evt_ccs);
mmio_write64(g_runtime_off + XHCI_RT_IR0_ERDP_LO, erdp2 | ERDP_EHB);
continue;
}
@@ -677,7 +931,7 @@ static int xhci_poll_event(u32 expected_type, u64 timeout_ms,
static int xhci_cmd_submit(u64 param, u32 status, u32 control,
u64 timeout_ms,
u64 *out_param, u32 *out_status) {
u64 *out_param, u32 *out_status, u32 *out_control) {
/* Clear Event Ring interrupt pending */
mmio_write32(g_runtime_off + XHCI_RT_IR0_IMAN,
mmio_read32(g_runtime_off + XHCI_RT_IR0_IMAN) | 2u);
@@ -705,7 +959,7 @@ static int xhci_cmd_submit(u64 param, u32 status, u32 control,
}
int rc = xhci_poll_event(EVT_TYPE_CMD_COMPLETE, timeout_ms,
out_param, out_status, 0);
out_param, out_status, out_control);
/* Clear EINT */
mmio_write32(g_cap_length + XHCI_OP_USBSTS,
@@ -810,8 +1064,8 @@ static int xhci_controller_start(void) {
/* Configure Event Ring */
mmio_write32(g_runtime_off + XHCI_RT_IR0_ERSTSZ, 1);
mmio_write64(g_runtime_off + XHCI_RT_IR0_ERSTBA_LO, g_erst.phys);
u64 erdp = g_evt_ring.dma.phys | (u64)g_evt_ccs;
mmio_write64(g_runtime_off + XHCI_RT_IR0_ERDP_LO, erdp);
u64 erdp = g_evt_ring.dma.phys;
mmio_write64(g_runtime_off + XHCI_RT_IR0_ERDP_LO, erdp | ERDP_EHB);
/* Enable interrupt (IMAN.IE=1) */
mmio_write32(g_runtime_off + XHCI_RT_IR0_IMAN,
@@ -883,7 +1137,7 @@ static int xhci_reset_port(u32 port_idx) {
g_evt_ring.enqueue = (g_evt_ring.enqueue + 1) % (g_evt_ring.size - 1);
if (g_evt_ring.enqueue == 0) g_evt_ccs ^= 1;
u64 erdp = g_evt_ring.dma.phys + (u64)g_evt_ring.enqueue * sizeof(xhci_trb);
mmio_write64(g_runtime_off + XHCI_RT_IR0_ERDP_LO, erdp | g_evt_ccs);
mmio_write64(g_runtime_off + XHCI_RT_IR0_ERDP_LO, erdp | ERDP_EHB);
}
return 0;
@@ -911,15 +1165,18 @@ static int xhci_enable_slot(u8 *out_slot_id) {
u32 control = (TRB_TYPE_ENABLE_SLOT << TRB_TYPE_SHIFT);
u64 out_param = 0;
u32 out_status = 0;
u32 out_control = 0;
int rc = xhci_cmd_submit(0, 0, control, 5000, &out_param, &out_status);
int rc = xhci_cmd_submit(0, 0, control, 5000, &out_param, &out_status, &out_control);
if (rc != 0) {
g_log->error("[xhci] Enable Slot failed");
return rc;
}
/* Slot ID is in the upper bits of the completion event parameter */
*out_slot_id = (u8)((out_param >> 24) & 0xFF);
/* Slot ID 位于 Command Completion Event 的 TRB control[31:24]。
* (xHCI 1.2 §6.4.2.2:CMD_COMPLETE 事件 TRB parameter = 命令 TRB 地址,
* slot id 在 control 高字节 —— QEMU hcd-xhci.c xhci_write_event 佐证) */
*out_slot_id = (u8)((out_control >> 24) & 0xFF);
log_hex("[xhci] slot_id=", *out_slot_id);
return 0;
}
@@ -940,7 +1197,8 @@ static int xhci_address_device(u8 slot_id, int bsr) {
u64 out_param = 0;
u32 out_status = 0;
int rc = xhci_cmd_submit(input_ctx_phys, 0, control, 5000, &out_param, &out_status);
u32 out_control = 0;
int rc = xhci_cmd_submit(input_ctx_phys, 0, control, 5000, &out_param, &out_status, &out_control);
if (rc != 0) {
g_log->error("[xhci] Address Device failed");
return rc;
@@ -958,7 +1216,8 @@ static int xhci_configure_endpoint(u8 slot_id) {
u64 out_param = 0;
u32 out_status = 0;
int rc = xhci_cmd_submit(input_ctx_phys, 0, control, 5000, &out_param, &out_status);
u32 out_control = 0;
int rc = xhci_cmd_submit(input_ctx_phys, 0, control, 5000, &out_param, &out_status, &out_control);
if (rc != 0) {
g_log->error("[xhci] Configure Endpoint failed");
return rc;
@@ -979,7 +1238,16 @@ static int xhci_control_transfer(const u8 *setup_pkt, u8 *data, u32 data_len,
((u64)setup_pkt[2] << 16) | ((u64)setup_pkt[3] << 24);
u32 setup_status = 8; /* Setup packet length */
u32 setup_control = (TRB_TYPE_SETUP_STAGE << TRB_TYPE_SHIFT) | TRB_IOC;
/* Setup Stage TRB(不设 IOC:控制传输只需在最后一个 TRB 上报完成,
* 中间 TRB 设 IOC 会让 QEMU/实机产生多余 Transfer Event,残留事件
* 污染后续 CMD_COMPLETE 轮询——日志表现为 "unexpected event type") */
u32 setup_control = (TRB_TYPE_SETUP_STAGE << TRB_TYPE_SHIFT);
/* Setup Stage TRB 必须设置 IDT (Immediate Data, bit6):
* setup 包 8 字节直接内嵌在 TRB parameter 字段。
* BUG-FIX: 原实现缺 IDT,QEMU xhci_fire_ctl_transfer 校验
* `!(trb_setup->control & TRB_TR_IDT)` 直接返回 -1 → 无 Transfer
* Event → 轮询超时(GET_DESCRIPTOR 失败)。 */
setup_control |= (1u << 6); /* TRB_TR_IDT */
/* Set direction in TRB: bit 16 of Setup Stage TRB */
if (direction) setup_control |= (1u << 16);
@@ -995,7 +1263,8 @@ static int xhci_control_transfer(const u8 *setup_pkt, u8 *data, u32 data_len,
u64 data_phys = direction ? g_xfer_buf.phys : g_xfer_buf.phys;
u32 data_status = data_len;
u32 data_control = (TRB_TYPE_DATA_STAGE << TRB_TYPE_SHIFT) | TRB_IOC;
/* Data Stage 不设 IOC(避免多余事件残留) */
u32 data_control = (TRB_TYPE_DATA_STAGE << TRB_TYPE_SHIFT);
if (direction) data_control |= (1u << 16); /* DIR=IN */
xhci_ring_enqueue(&g_ep0_ring, data_phys, data_status, data_control);
@@ -1088,7 +1357,11 @@ static int xhci_bulk_transfer(xhci_ring *ring, u8 ep_num,
xhci_ring_enqueue(ring, g_xfer_buf.phys, data_len, control);
xhci_mb();
xhci_ring_doorbell(g_msc.slot_id, ep_num);
/* Doorbell target = Endpoint ID:EPn OUT→2n,EPn IN→2n+1。
* BUG-FIX: 原实现传 EP 号(2/1),QEMU xhci_kick_ep 按 Endpoint ID
* 索引 eps[epid-1] → 敲错端点 → 无 Transfer Event → 轮询超时。 */
u8 db_target = (direction ? (u8)(2u * ep_num + 1) : (u8)(2u * ep_num));
xhci_ring_doorbell(g_msc.slot_id, db_target);
/* Poll for Transfer Event */
u64 out_param = 0;
@@ -1097,6 +1370,7 @@ static int xhci_bulk_transfer(xhci_ring *ring, u8 ep_num,
&out_param, &out_status, 0);
if (rc != 0) {
g_log->warn("[xhci] bulk transfer failed");
log_hex("[xhci] bulk rc=", (u64)(i64)rc);
return rc;
}
@@ -1343,32 +1617,48 @@ static int xhci_block_write(void *ctx, u64 lba, u32 count, const void *buffer) {
* Phase 3: Build Input Context for Address Device
* ================================================================ */
static void xhci_build_input_ctx_slot(u8 slot_id, u8 speed, u16 mps0) {
static void xhci_build_input_ctx_slot(u8 slot_id, u8 speed, u16 mps0, u32 port_idx) {
(void)slot_id;
u32 ctx_sz = g_ctx_size;
u8 *ic = (u8 *)g_input_ctx.virt;
xhci_zero(ic, g_input_ctx.size);
/* Input Control Context: enable Slot Context (bit 0) and EP0 (bit 1) */
/* Input Control Context (xHCI 1.2 §6.4.3):
* DWORD0 = Drop Context Flags(本次全 0,不 drop 任何上下文)
* DWORD1 = Add Context Flags(bit0=Slot, bit1=EP0)
* BUG-FIX: 原实现把 Add flags 写进 DWORD0(Drop 槽),
* QEMU/实机校验 ictl_ctx[0]==0 && ictl_ctx[1]==0x3 直接失败 CC_TRB_ERROR。 */
u32 *icc = (u32 *)ic;
icc[0] = (1u << 1) | (1u << 0); /* A0=1 (Slot), A1=1 (EP0) */
icc[0] = 0x0; /* Drop Context Flags */
icc[1] = (1u << 0) | (1u << 1); /* Add: Slot + EP0 */
/* Slot Context starts at offset ctx_sz */
/* Slot Context (§6.2.2):
* DWORD0: Route String [0:19] + Speed [20:22] + Context Entries [27:31]
* DWORD1: Max Exit Latency [0:7] + Root Hub Port Number [16:23]
* BUG-FIX: 原实现 speed<<29(占用 Context Entries 位域)、MPS0 写入
* DWORD1(规范 Slot Context 无 MPS0 字段,MPS0 在 EP0 Context)——
* QEMU xhci_lookup_uport 读 DWORD1[16:23] 找端口,原值 port=0 查不到
* 设备 → CC_TRB_ERROR。 */
u32 *slot_ctx = (u32 *)(ic + ctx_sz);
u32 route_string = 0; /* direct-connect, no hub */
slot_ctx[0] = route_string | ((u32)speed << 29);
slot_ctx[1] = (u32)mps0; /* Max Packet Size for EP0 */
slot_ctx[2] = (1u << 27); /* Context Entries = 1 (only EP0) */
slot_ctx[0] = route_string | ((u32)speed << 20) | (1u << 27);
slot_ctx[1] = (port_idx + 1) << 16; /* Root Hub Port Number (1-based) */
/* EP0 Context starts at offset ctx_sz * 2 */
/* EP0 Context starts at offset ctx_sz * 2
* Endpoint Context (§6.2.3) 布局:
* DWORD1: CErr[4:5] + EP Type[6:8] + Max Packet Size[16:31]
* DWORD2: Dequeue Pointer Low[4:31](bit0=DCS, bits1:3=reserved)
* DWORD3: Dequeue Pointer High
* DWORD4: Average TRB Length[0:15]
* BUG-FIX: 原实现把 dequeue 写到 DWORD6/7——QEMU xhci_init_epctx
* 从 DWORD2/3 读 dequeue(ctx[2]&~0xf, ctx[3]),读到 0 → ring 无
* dequeue → kick_epctx 直接返回,TRB 永不处理 → 无 Transfer Event。 */
u32 *ep0_ctx = (u32 *)(ic + ctx_sz * 2);
/* EP Type = Control, Max Packet Size, etc. */
ep0_ctx[1] = (4u << 3) | ((u32)mps0 << 16); /* EP Type=4 (Control IN), MPS */
ep0_ctx[4] = 8; /* Average TRB Length */
/* Dequeue Pointer: EP0 transfer ring */
u64 ep0_deq = g_ep0_ring.dma.phys | (u64)g_ep0_ring.ccs;
ep0_ctx[6] = (u32)(ep0_deq & 0xFFFFFFFFu);
ep0_ctx[7] = (u32)(ep0_deq >> 32);
ep0_ctx[2] = (u32)(ep0_deq & 0xFFFFFFF0u) | (u32)g_ep0_ring.ccs;
ep0_ctx[3] = (u32)(ep0_deq >> 32);
ep0_ctx[4] = 8; /* Average TRB Length */
}
static void xhci_build_input_ctx_bulk_eps(u8 bulk_out_ep, u8 bulk_in_ep,
@@ -1376,31 +1666,45 @@ static void xhci_build_input_ctx_bulk_eps(u8 bulk_out_ep, u8 bulk_in_ep,
u32 ctx_sz = g_ctx_size;
u8 *ic = (u8 *)g_input_ctx.virt;
/* Update Input Control Context: enable EP0, Bulk OUT, Bulk IN */
/* Input Control Context(Configure Endpoint 语义,xHCI 1.2 §6.4.3):
* DWORD0 = Drop(0),DWORD1 = Add。
* Configure 时 bit0=Slot 必须 Add,bit1=EP0 不可重复 Add
* (QEMU xhci_configure_slot 校验 (ictl[1]&0x3)==0x1)。
* 端点位用 Context Index:EPn OUT→2n,EPn IN→2n+1
* (QEMU 从 i=2 开始遍历 Add flags,按 ictx+32*i 读 EP Context)。 */
u32 *icc = (u32 *)ic;
icc[0] = (1u << 1) | (1u << 0) |
(1u << bulk_out_ep) | (1u << bulk_in_ep);
u32 out_idx = 2u * bulk_out_ep;
u32 in_idx = 2u * bulk_in_ep + 1;
icc[0] = 0x0;
icc[1] = (1u << 0) | (1u << out_idx) | (1u << in_idx);
/* Update Slot Context: Context Entries = max(bulk_in_ep, bulk_out_ep) */
/* Update Slot Context: Context Entries = max Context Index
* (DWORD0 bits[27:31],保留 Speed/Route 原值)。 */
u32 *slot_ctx = (u32 *)(ic + ctx_sz);
u32 max_ep = bulk_out_ep > bulk_in_ep ? bulk_out_ep : bulk_in_ep;
slot_ctx[2] = (max_ep << 27);
u32 max_idx = out_idx > in_idx ? out_idx : in_idx;
slot_ctx[0] &= ~(0x1Fu << 27);
slot_ctx[0] |= (max_idx << 27);
/* Bulk OUT Endpoint Context (at offset ctx_sz * (1 + bulk_out_ep)) */
u32 *out_ctx = (u32 *)(ic + ctx_sz * (1 + bulk_out_ep));
/* Bulk OUT Endpoint Context。
* 偏移 = ctx_sz * (out_idx + 1):input context 布局是
* [ICC][Slot][EP0][EP1]... 每个占 1 个 ctx_sz,Context Index i 的
* EP context 在 (i+1) 个槽处(QEMU xhci_configure_slot 用
* ictx+32+(32*i) 读取)。BUG-FIX: 原实现 ctx_sz*out_idx 少了 ICC
* 槽 → 全部错位 32 字节 → QEMU 读到零 EP context。 */
u32 *out_ctx = (u32 *)(ic + ctx_sz * (out_idx + 1));
out_ctx[1] = (EP_TYPE_BULK_OUT << 3) | ((u32)out_mps << 16);
out_ctx[4] = 512; /* Average TRB Length */
u64 out_deq = g_bulk_out_ring.dma.phys | (u64)g_bulk_out_ring.ccs;
out_ctx[6] = (u32)(out_deq & 0xFFFFFFFFu);
out_ctx[7] = (u32)(out_deq >> 32);
out_ctx[2] = (u32)(out_deq & 0xFFFFFFF0u) | (u32)g_bulk_out_ring.ccs;
out_ctx[3] = (u32)(out_deq >> 32);
out_ctx[4] = 512; /* Average TRB Length */
/* Bulk IN Endpoint Context (at offset ctx_sz * (1 + bulk_in_ep)) */
u32 *in_ctx = (u32 *)(ic + ctx_sz * (1 + bulk_in_ep));
/* Bulk IN Endpoint Context (at offset ctx_sz * (in_idx + 1)) */
u32 *in_ctx = (u32 *)(ic + ctx_sz * (in_idx + 1));
in_ctx[1] = (EP_TYPE_BULK_IN << 3) | ((u32)in_mps << 16);
in_ctx[4] = 512; /* Average TRB Length */
u64 in_deq = g_bulk_in_ring.dma.phys | (u64)g_bulk_in_ring.ccs;
in_ctx[6] = (u32)(in_deq & 0xFFFFFFFFu);
in_ctx[7] = (u32)(in_deq >> 32);
in_ctx[2] = (u32)(in_deq & 0xFFFFFFF0u) | (u32)g_bulk_in_ring.ccs;
in_ctx[3] = (u32)(in_deq >> 32);
in_ctx[4] = 512; /* Average TRB Length */
}
/* ================================================================
@@ -1411,18 +1715,22 @@ static int xhci_enum_msc_device(u32 port_idx) {
u8 speed = xhci_get_port_speed(port_idx);
log_hex("[xhci] port speed=", speed);
/* Default MaxPacketSize for EP0 based on speed */
u16 mps0 = 64; /* High/Super-Speed default */
if (speed == USB_SPEED_FULL) mps0 = 64;
/* Default MaxPacketSize for EP0 based on speed
* (xHCI 1.2 §4.3: Full=8? No — FS/HS EP0 通常 64,LS=8,SS=512) */
u16 mps0 = 64; /* Full/High-Speed default */
if (speed == USB_SPEED_LOW) mps0 = 8;
if (speed == USB_SPEED_SUPER) mps0 = 512;
/* Step 1: Enable Slot */
u8 slot_id = 0;
if (xhci_enable_slot(&slot_id) != 0) return -1;
if (xhci_enable_slot(&slot_id) != 0) {
FB_ENUM_FAIL(0x0A); /* 黄: Enable Slot 失败 */
return -1;
}
g_msc.slot_id = slot_id;
g_msc.speed = speed;
/* Step 2: Allocate per-device DMA buffers */
/* Step 1.5: Allocate per-device DMA buffers(在 DCBAA 指向输出上下文之前) */
if (g_api->dma->alloc_pages(4, 4096, 0x100000000ULL, &g_input_ctx) != 0) return -2;
if (g_api->dma->alloc_pages(4, 4096, 0x100000000ULL, &g_dev_ctx) != 0) return -2;
if (g_api->dma->alloc_pages(4, 4096, 0x100000000ULL, &g_xfer_buf) != 0) return -2;
@@ -1431,18 +1739,30 @@ static int xhci_enum_msc_device(u32 port_idx) {
if (xhci_ring_init(&g_bulk_out_ring, XFER_RING_SIZE) != 0) return -2;
if (xhci_ring_init(&g_bulk_in_ring, XFER_RING_SIZE) != 0) return -2;
/* DCBAA[slot_id] 必须指向输出上下文(Device Context)。
* Address Device/Configure Endpoint 命令都会读取该地址;
* 缺失时 QEMU/实机将 octx=0 → DMA 写失败/CC_TRB_ERROR。 */
xhci_zero(g_dev_ctx.virt, g_dev_ctx.size);
u64 *dcbaa = (u64 *)g_dcbaa.virt;
dcbaa[slot_id] = g_dev_ctx.phys;
log_hex("[xhci] DCBAA[slot]=", dcbaa[slot_id]);
/* Step 3: Build Input Context and Address Device (BSR=1 first) */
xhci_build_input_ctx_slot(slot_id, speed, mps0);
xhci_build_input_ctx_slot(slot_id, speed, mps0, port_idx);
if (xhci_address_device(slot_id, 1) != 0) {
/* BSR=1 failed, try without BSR */
xhci_build_input_ctx_slot(slot_id, speed, mps0);
if (xhci_address_device(slot_id, 0) != 0) return -3;
xhci_build_input_ctx_slot(slot_id, speed, mps0, port_idx);
if (xhci_address_device(slot_id, 0) != 0) {
FB_ENUM_FAIL(0x0B); /* 黄: Address Device 失败(BSR=1/0 均失败) */
return -3;
}
}
/* Step 4: Get Device Descriptor */
u8 dev_desc[18];
if (xhci_get_device_descriptor(dev_desc) != 0) {
g_log->warn("[xhci] GET_DESCRIPTOR(Device) failed");
FB_ENUM_FAIL(0x0C); /* 黄: GET_DESCRIPTOR(Device) 失败 */
return -4;
}
@@ -1459,7 +1779,7 @@ static int xhci_enum_msc_device(u32 port_idx) {
/* Step 5: Re-address with real MPS if different */
if (real_mps0 != mps0 && real_mps0 >= 8) {
mps0 = real_mps0;
xhci_build_input_ctx_slot(slot_id, speed, mps0);
xhci_build_input_ctx_slot(slot_id, speed, mps0, port_idx);
if (xhci_address_device(slot_id, 0) != 0) {
g_log->warn("[xhci] re-address failed");
/* Continue anyway — device may still work */
@@ -1470,12 +1790,16 @@ static int xhci_enum_msc_device(u32 port_idx) {
u8 cfg_desc[255];
if (xhci_get_config_descriptor(cfg_desc, 255) != 0) {
g_log->warn("[xhci] GET_DESCRIPTOR(Config) failed");
FB_ENUM_FAIL(0x0C); /* 黄: GET_DESCRIPTOR(Config) 失败 */
return -5;
}
/* Parse configuration descriptor to find MSC interface and endpoints */
u16 total_len = (u16)cfg_desc[2] | ((u16)cfg_desc[3] << 8);
if (total_len < 9) return -5;
if (total_len < 9) {
FB_ENUM_FAIL(0x0D); /* 黄: 配置描述符过短 */
return -5;
}
u8 bulk_out_ep = 0, bulk_in_ep = 0;
u16 bulk_out_mps = 512, bulk_in_mps = 512;
@@ -1497,24 +1821,34 @@ static int xhci_enum_msc_device(u32 port_idx) {
msc_found = 1;
g_log->info("[xhci] MSC BOT interface found");
/* Scan following endpoint descriptors */
/* Scan following endpoint descriptors.
* SuperSpeed 设备在 endpoint 后紧跟 6 字节 SS Endpoint
* Companion descriptor (type 0x30)——必须跳过继续找下一
* 个 endpoint,不能因 type!=5 提前终止(Bulk OUT 常在
* IN 之后且被 companion 隔开)。 */
u32 ep_pos = pos + desc_len;
while (ep_pos + 7 <= (u32)total_len &&
cfg_desc[ep_pos + 1] == 5) { /* endpoint descriptor */
u8 ep_addr = cfg_desc[ep_pos + 2];
u8 ep_attr = cfg_desc[ep_pos + 3];
u16 ep_mps = (u16)cfg_desc[ep_pos + 4] | ((u16)cfg_desc[ep_pos + 5] << 8);
while (ep_pos + 2 <= (u32)total_len) {
u8 ep_len = cfg_desc[ep_pos];
if (ep_len == 0 || ep_pos + ep_len > (u32)total_len) break;
if (cfg_desc[ep_pos + 1] == 5) { /* endpoint descriptor */
u8 ep_addr = cfg_desc[ep_pos + 2];
u8 ep_attr = cfg_desc[ep_pos + 3];
u16 ep_mps = (u16)cfg_desc[ep_pos + 4] | ((u16)cfg_desc[ep_pos + 5] << 8);
if ((ep_attr & 0x03) == 0x02) { /* Bulk */
if (ep_addr & 0x80) {
bulk_in_ep = ep_addr & 0x0F;
bulk_in_mps = ep_mps;
} else {
bulk_out_ep = ep_addr & 0x0F;
bulk_out_mps = ep_mps;
if ((ep_attr & 0x03) == 0x02) { /* Bulk */
if (ep_addr & 0x80) {
bulk_in_ep = ep_addr & 0x0F;
bulk_in_mps = ep_mps;
} else {
bulk_out_ep = ep_addr & 0x0F;
bulk_out_mps = ep_mps;
}
}
} else if (cfg_desc[ep_pos + 1] == 4) {
/* 下一个 interface — 停止扫描 */
break;
}
ep_pos += cfg_desc[ep_pos];
ep_pos += ep_len;
}
break;
}
@@ -1524,6 +1858,7 @@ static int xhci_enum_msc_device(u32 port_idx) {
if (!msc_found || bulk_out_ep == 0 || bulk_in_ep == 0) {
g_log->warn("[xhci] no MSC BOT interface found");
FB_ENUM_FAIL(0x0D); /* 黄: 未找到 MSC BOT 接口/端点 */
return -6;
}
@@ -1543,6 +1878,7 @@ static int xhci_enum_msc_device(u32 port_idx) {
bulk_out_mps, bulk_in_mps);
if (xhci_configure_endpoint(slot_id) != 0) {
g_log->warn("[xhci] Configure Endpoint failed");
FB_ENUM_FAIL(0x0E); /* 黄: Configure Endpoint 失败 */
return -7;
}
@@ -1601,7 +1937,10 @@ int driver_init(const struct dkm_kernel_api *api,
u8 bus = 0, dev = 0, func = 0;
if (xhci_find(&bus, &dev, &func) != 0) {
g_log->info("[xhci] xHCI controller not found");
g_log->info("[xhci] driver ready");
/* BUG-FIX: 不 halt。xhci 是可选驱动(manifest required=false),
* 无 xHCI 的平台(Intel 6 系/纯 EHCI)必须继续引导到 EHCI/DSK,
* 否则 `for(;;)hlt` 卡死整条启动链。仅记日志,如需诊断可开
* xhci_pci_diag_code() 打印控制器清单(见注释)。 */
return 0;
}
@@ -1628,7 +1967,7 @@ int driver_init(const struct dkm_kernel_api *api,
u64 bar_phys;
if (bar0_lo & 1u) {
g_log->warn("[xhci] BAR0 is IO space; unsupported");
g_log->info("[xhci] driver ready");
FB_FATAL(api, 0x02); /* 红: BAR0 是 IO 空间 */
return 0;
}
if ((bar0_lo & 0x6u) == 0x4u) {
@@ -1644,7 +1983,7 @@ int driver_init(const struct dkm_kernel_api *api,
if (!api->hhdm_offset || !bar_phys) {
g_log->warn("[xhci] missing HHDM or BAR0; skip");
g_log->info("[xhci] driver ready");
FB_FATAL(api, 0x02); /* 红: 缺 HHDM/BAR */
return 0;
}
@@ -1652,14 +1991,14 @@ int driver_init(const struct dkm_kernel_api *api,
g_mmio = xhci_map_bar(api, bar_phys);
if (!g_mmio) {
g_log->error("[xhci] BAR MMIO unavailable; driver inactive");
g_log->info("[xhci] driver ready");
FB_FATAL(api, 0x03); /* 红: BAR MMIO 映射失败 */
return 0;
}
/* ---- Phase 1: Parse capabilities ---- */
if (xhci_parse_caps() != 0) {
g_log->error("[xhci] capability parse failed");
g_log->info("[xhci] driver ready");
FB_FATAL(api, 0x04); /* 红: capability 解析失败 */
return 0;
}
@@ -1669,27 +2008,27 @@ int driver_init(const struct dkm_kernel_api *api,
/* ---- Phase 1: Controller Reset ---- */
if (xhci_controller_reset() != 0) {
g_log->error("[xhci] controller reset failed");
g_log->info("[xhci] driver ready");
FB_FATAL(api, 0x05); /* 红: 控制器 reset 失败 */
return 0;
}
/* ---- Phase 2: Setup Rings + DCBAA + Scratchpad ---- */
if (!api->dma) {
g_log->warn("[xhci] DMA API unavailable");
g_log->info("[xhci] driver ready");
FB_FATAL(api, 0x06); /* 红: DMA API 缺失 */
return 0;
}
if (xhci_setup_rings() != 0) {
g_log->error("[xhci] ring setup failed");
g_log->info("[xhci] driver ready");
FB_FATAL(api, 0x06); /* 红: ring 初始化失败 */
return 0;
}
/* ---- Phase 2: Start Controller ---- */
if (xhci_controller_start() != 0) {
g_log->error("[xhci] controller start failed");
g_log->info("[xhci] driver ready");
FB_FATAL(api, 0x07); /* 红: 控制器启动失败 */
return 0;
}
@@ -1765,6 +2104,7 @@ int driver_init(const struct dkm_kernel_api *api,
}
} else {
g_log->info("[xhci] no MSC device found; block provider not registered");
FB_FATAL(api, 0x08); /* 黄: 所有端口无设备/枚举全部失败 */
}
g_log->info("[xhci] driver ready");
+1
View File
@@ -25,6 +25,7 @@ typedef struct dkm_block_api {
u64 (*sector_size)(u32 index);
const char *(*device_name)(u32 index);
int (*set_write_fn)(u32 index, dkm_block_write_fn fn);
u64 (*sector_count)(u32 index); /* 0x38: tail-append, 老内核该槽为 0 表示未知 */
} dkm_block_api;
void block_init(void);
+2 -1
View File
@@ -13,7 +13,8 @@ void log_error(const char *msg);
void log_hex64(const char *prefix, u64 value);
void panic(const char *msg);
/* ---- 内存日志缓冲区(实机启动日志持久化) ---- */
/* ---- 内存日志缓冲区(实机启动日志持久化) ----
* 由 disk_log_flush() 写入 FAT32 文件 SYSTEM/DESHAB64/DEV/BOOTLOG.TXT。 */
void log_capture_enable(int enable);
const char *log_get_buffer(void);
u32 log_get_length(void);
+7 -1
View File
@@ -58,6 +58,11 @@ static int block_set_write_fn_impl(u32 index, dkm_block_write_fn fn) {
return 0;
}
static u64 block_sector_count_impl(u32 index) {
if (index >= g_device_count) return 0;
return g_devices[index].sector_count;
}
static const dkm_block_api g_block_api = {
.register_device = block_register_device_impl,
.device_count = block_device_count_impl,
@@ -65,7 +70,8 @@ static const dkm_block_api g_block_api = {
.write = block_write_impl,
.sector_size = block_sector_size_impl,
.device_name = block_device_name_impl,
.set_write_fn = block_set_write_fn_impl
.set_write_fn = block_set_write_fn_impl,
.sector_count = block_sector_count_impl
};
const dkm_block_api *block_get_api(void) {
Binary file not shown.
+373
View File
@@ -520,6 +520,379 @@ int fat32_read_path(const char *path, u8 **out_data, u32 *out_size) {
return -8; /* 路径为空或无效 */
}
/* ---- FAT32 写入(实机启动日志落盘,2026-08 移植自 DSK fat32_write_*) ----
* 相比 DSK 版本的两点增强:
* 1) FAT 条目支持按需读-改-写(超出 256 扇区预读缓冲时逐扇区读写,
* 并同步镜像到所有 FAT 副本),不再受小分区限制。
* 2) 目录扫描跨簇 + 目录满时自动扩展,文件链支持多簇(日志可达 128KB)。
* 注意:与 DSK 一致,不更新 FSInfo(free count 会过期,测试工具可接受)。 */
/* 读取 FAT 表条目(28 位),支持按需读扇区。 */
static u32 fat32_get_cluster_entry(u32 fat_byte_off, u32 clus,
const fat32_bpb *bpb, const u8 *disk) {
u32 ent_off = fat_byte_off + clus * 4;
if (ent_off + 4 <= sizeof(g_dsk_fat32_disk)) {
return fat32_read_u32(disk + ent_off) & 0x0FFFFFFF;
}
return fat32_get_next_cluster(fat_byte_off, clus, bpb, disk);
}
/* 写 FAT 表条目。缓冲内条目直接改内存(同步镜像副本 1),
* 缓冲外条目按 FAT 副本逐个读-改-写扇区。返回 0 成功。 */
static int fat32_set_cluster_entry(u32 fat_byte_off, u32 fat_sectors, u32 clus,
u32 value, const fat32_bpb *bpb, u8 *disk) {
u32 ent_off = fat_byte_off + clus * 4;
if (ent_off + 4 <= sizeof(g_dsk_fat32_disk)) {
disk[ent_off] = (u8)(value & 0xFF);
disk[ent_off + 1] = (u8)((value >> 8) & 0xFF);
disk[ent_off + 2] = (u8)((value >> 16) & 0xFF);
disk[ent_off + 3] = (u8)((disk[ent_off + 3] & 0xF0) | ((value >> 24) & 0x0F));
/* 同步 FAT 副本 1 的缓冲镜像(若在缓冲内) */
if (bpb->fat_count >= 2) {
u32 e1 = ent_off + fat_sectors * 512;
if (e1 + 4 <= sizeof(g_dsk_fat32_disk)) {
disk[e1] = disk[ent_off];
disk[e1 + 1] = disk[ent_off + 1];
disk[e1 + 2] = disk[ent_off + 2];
disk[e1 + 3] = disk[ent_off + 3];
}
}
return 0;
}
/* 缓冲外:逐 FAT 副本读-改-写 */
const dkm_kernel_api *api = dkm_get_kernel_api();
if (!api || !api->block || !api->block->read || !api->block->write) return -1;
u32 sec_index = (clus * 4) / 512;
u32 ent_in_sec = (clus * 4) % 512;
u32 copies = bpb->fat_count;
if (copies > 4) copies = 4;
for (u32 f = 0; f < copies; f++) {
u32 sec_lba = bpb->reserved_sector_count + f * fat_sectors + sec_index;
if (api->block->read(0, sec_lba, 1, g_dsk_fat32_fat_sec) != 0) return -2;
g_dsk_fat32_fat_sec[ent_in_sec] = (u8)(value & 0xFF);
g_dsk_fat32_fat_sec[ent_in_sec + 1] = (u8)((value >> 8) & 0xFF);
g_dsk_fat32_fat_sec[ent_in_sec + 2] = (u8)((value >> 16) & 0xFF);
g_dsk_fat32_fat_sec[ent_in_sec + 3] = (u8)((g_dsk_fat32_fat_sec[ent_in_sec + 3] & 0xF0) | ((value >> 24) & 0x0F));
if (api->block->write(0, sec_lba, 1, g_dsk_fat32_fat_sec) != 0) return -3;
}
return 0;
}
/* 顺序扫描 FAT 找空闲簇(缓冲内直读,缓冲外按 8 扇区批量读)。
* from_clus: 起始簇号(建议传入上次分配结果+1,避免反复扫描)。
* 返回空闲簇号,失败返回 0。 */
static u32 fat32_find_free_cluster(u32 fat_lba, u32 fat_sectors, u32 from_clus) {
const dkm_kernel_api *api = dkm_get_kernel_api();
u8 *disk = g_dsk_fat32_disk;
u32 total_entries = (fat_sectors * 512) / 4;
u32 fat_byte_off = fat_lba * 512;
u32 c = from_clus;
while (c < total_entries) {
u32 ent_off = fat_byte_off + c * 4;
if (ent_off + 4 <= sizeof(g_dsk_fat32_disk)) {
if ((fat32_read_u32(disk + ent_off) & 0x0FFFFFFF) == 0) return c;
c++;
} else {
u32 sec_index = (c * 4) / 512;
u32 sec_lba = fat_lba + sec_index;
u32 secs = 8;
if (sec_lba + secs > fat_lba + fat_sectors) secs = fat_lba + fat_sectors - sec_lba;
if (api->block->read(0, sec_lba, secs, g_dsk_fat32_cluster) != 0) return 0;
u32 first_in_chunk = sec_index * 128;
u32 last_in_chunk = (sec_index + secs) * 128;
for (u32 cc = (c < first_in_chunk ? first_in_chunk : c);
cc < last_in_chunk && cc < total_entries; cc++) {
if ((fat32_read_u32(g_dsk_fat32_cluster + (cc - first_in_chunk) * 4) & 0x0FFFFFFF) == 0)
return cc;
}
c = last_in_chunk;
}
}
return 0;
}
/* 分配并链接 needed 个簇,全部标记 EOC。scan_from 记录扫描游标。
* 返回 0 成功;first/last 返回链首/链尾。 */
static int fat32_alloc_clusters(const fat32_bpb *bpb, u32 fat_lba,
u32 fat_sectors, u32 needed,
u32 *scan_from, u32 *first, u32 *last) {
u32 prev = 0;
u32 fc = 0, lc = 0;
u32 cur_scan = *scan_from;
for (u32 i = 0; i < needed; i++) {
u32 nc = fat32_find_free_cluster(fat_lba, fat_sectors, cur_scan);
if (nc == 0) return -1;
cur_scan = nc + 1;
if (fat32_set_cluster_entry(bpb->reserved_sector_count * 512, fat_sectors,
nc, 0x0FFFFFFF, bpb, g_dsk_fat32_disk) != 0)
return -2;
if (prev) {
if (fat32_set_cluster_entry(bpb->reserved_sector_count * 512, fat_sectors,
prev, nc, bpb, g_dsk_fat32_disk) != 0)
return -3;
} else {
fc = nc;
}
prev = nc;
lc = nc;
}
*scan_from = cur_scan;
*first = fc;
*last = lc;
return 0;
}
/* 在指定目录(dir_clus 起始簇)写入文件(8.3 名,11 字符)。
* 存在则覆盖(复用旧链/扩展/截断),否则新建。支持多簇目录与多簇文件。
* data 必须指向可寻址静态内存(如 log 缓冲)。返回 0 成功。 */
static int fat32_write_file_in_dir(u32 dir_clus, const char *name11,
const u8 *data, u32 size) {
const dkm_kernel_api *api = dkm_get_kernel_api();
if (!api || !api->block || !api->block->read || !api->block->write) return -1;
u8 *disk = g_dsk_fat32_disk;
if (api->block->read(0, 0, 256, disk) != 0) return -2;
const fat32_bpb *bpb = (const fat32_bpb *)disk;
if (bpb->boot_sig != 0xAA55 || bpb->bytes_per_sector != 512) return -3;
u32 spc = bpb->sectors_per_cluster;
u32 fat_lba = bpb->reserved_sector_count;
u32 fat_sectors = bpb->sectors_per_fat;
u32 data_lba = bpb->reserved_sector_count + (u32)bpb->fat_count * bpb->sectors_per_fat;
u32 fat_byte_off = fat_lba * 512;
u32 cluster_bytes = spc * 512;
/* ---- 1. 扫描目录链:找同名条目或空闲槽 ---- */
u32 cur = dir_clus;
u32 last_dir_clus = dir_clus;
u32 entry_clus = 0; /* 目录项所在目录簇 */
u32 entry_slot = 0;
int found = 0; /* 同名文件已存在 */
u32 old_first_clus = 0;
int done = 0;
while (cur >= 2 && cur < 0x0FFFFFF8) {
last_dir_clus = cur;
u32 clus_lba = data_lba + (cur - 2) * spc;
if (api->block->read(0, clus_lba, spc, g_dsk_fat32_cluster) != 0) return -4;
u32 me = cluster_bytes / 32;
const fat32_dir_entry *d = (const fat32_dir_entry *)g_dsk_fat32_cluster;
for (u32 e = 0; e < me; e++) {
if (d[e].name[0] == 0) { /* 目录结束标记 */
if (entry_clus == 0) { entry_clus = cur; entry_slot = e; }
done = 1;
break;
}
if ((u8)d[e].name[0] == 0xE5) { /* 已删除项,可复用 */
if (entry_clus == 0) { entry_clus = cur; entry_slot = e; }
continue;
}
if (d[e].attr == 0x0F || (d[e].attr & 0x08)) continue;
if (fat32_name11_eq(d[e].name, name11)) {
found = 1;
entry_clus = cur;
entry_slot = e;
old_first_clus = fat32_read_u16((const u8 *)&d[e].cluster_low) |
((u32)fat32_read_u16((const u8 *)&d[e].cluster_high) << 16);
done = 1;
break;
}
}
if (done) break;
cur = fat32_get_cluster_entry(fat_byte_off, cur, bpb, disk);
}
/* ---- 2. 目录满时扩展一个簇 ---- */
if (entry_clus == 0) {
u32 scan_from = 2;
u32 nc = fat32_find_free_cluster(fat_lba, fat_sectors, scan_from);
if (nc == 0) return -9;
if (fat32_set_cluster_entry(fat_byte_off, fat_sectors, nc, 0x0FFFFFFF,
bpb, disk) != 0)
return -10;
if (fat32_set_cluster_entry(fat_byte_off, fat_sectors, last_dir_clus, nc,
bpb, disk) != 0)
return -11;
for (u32 b = 0; b < cluster_bytes; b++) g_dsk_fat32_cluster[b] = 0;
u32 nlba = data_lba + (nc - 2) * spc;
if (api->block->write(0, nlba, spc, g_dsk_fat32_cluster) != 0) return -12;
entry_clus = nc;
entry_slot = 0;
}
/* ---- 3. 文件簇链:复用/扩展/截断 ---- */
u32 needed = (size + cluster_bytes - 1) / cluster_bytes;
if (needed == 0) needed = 1;
u32 first = 0;
u32 scan_from = 2;
if (found && old_first_clus >= 2) {
/* 走旧链,收集前 needed 个簇 */
u32 c = old_first_clus;
u32 cnt = 0;
u32 last = 0;
u32 tail = 0;
while (c >= 2 && c < 0x0FFFFFF8 && cnt < needed) {
last = c;
cnt++;
c = fat32_get_cluster_entry(fat_byte_off, c, bpb, disk);
}
first = old_first_clus;
if (cnt == needed) {
/* 截断:last 指向 EOC,释放旧链尾部 */
tail = fat32_get_cluster_entry(fat_byte_off, last, bpb, disk);
if (fat32_set_cluster_entry(fat_byte_off, fat_sectors, last, 0x0FFFFFFF,
bpb, disk) != 0)
return -13;
while (tail >= 2 && tail < 0x0FFFFFF8) {
u32 nn = fat32_get_cluster_entry(fat_byte_off, tail, bpb, disk);
if (fat32_set_cluster_entry(fat_byte_off, fat_sectors, tail, 0,
bpb, disk) != 0)
return -14;
tail = nn;
}
} else {
/* 旧链不足:last 之后补簇 */
u32 need_more = needed - cnt;
u32 nf = 0, nl = 0;
if (fat32_alloc_clusters(bpb, fat_lba, fat_sectors, need_more,
&scan_from, &nf, &nl) != 0)
return -15;
if (fat32_set_cluster_entry(fat_byte_off, fat_sectors, last, nf,
bpb, disk) != 0)
return -16;
}
} else {
u32 nf = 0, nl = 0;
if (fat32_alloc_clusters(bpb, fat_lba, fat_sectors, needed,
&scan_from, &nf, &nl) != 0)
return -17;
first = nf;
}
/* ---- 4. 写数据簇 ---- */
{
u32 c = first;
u32 remaining = size;
u32 off = 0;
while (c >= 2 && c < 0x0FFFFFF8 && remaining > 0) {
u32 lba = data_lba + (c - 2) * spc;
if (remaining >= cluster_bytes) {
if (api->block->write(0, lba, spc, data + off) != 0) return -18;
} else {
u8 *cb = g_dsk_fat32_cluster;
for (u32 b = 0; b < cluster_bytes; b++) cb[b] = 0;
for (u32 b = 0; b < remaining; b++) cb[b] = data[off + b];
if (api->block->write(0, lba, spc, cb) != 0) return -19;
}
if (remaining >= cluster_bytes) {
off += cluster_bytes;
remaining -= cluster_bytes;
} else {
off += remaining;
remaining = 0;
}
c = fat32_get_cluster_entry(fat_byte_off, c, bpb, disk);
}
}
/* ---- 5. 更新目录项 ---- */
{
u32 elba = data_lba + (entry_clus - 2) * spc;
if (api->block->read(0, elba, spc, g_dsk_fat32_cluster) != 0) return -20;
fat32_dir_entry *dir = (fat32_dir_entry *)g_dsk_fat32_cluster;
fat32_dir_entry *e = &dir[entry_slot];
if (!found) {
for (int i = 0; i < 11; i++) e->name[i] = name11[i];
e->attr = 0x20; /* archive */
e->nt_reserved = 0;
e->creation_tenth = 0;
e->creation_time = 0;
e->creation_date = 0;
e->access_date = 0;
e->write_time = 0;
e->write_date = 0;
}
e->cluster_high = (u16)((first >> 16) & 0xFFFF);
e->cluster_low = (u16)(first & 0xFFFF);
e->file_size = size;
if (api->block->write(0, elba, spc, g_dsk_fat32_cluster) != 0) return -21;
}
/* ---- 6. 回写 FAT:缓冲内区间按副本刷回(缓冲外条目已即时写盘) ---- */
{
u32 copies = bpb->fat_count;
if (copies > 4) copies = 4;
for (u32 f = 0; f < copies; f++) {
u32 flba = fat_lba + f * fat_sectors;
if (flba >= 256) continue;
u32 ns = fat_sectors;
if (flba + ns > 256) ns = 256 - flba;
if (ns == 0) continue;
if (api->block->write(0, flba, ns, disk + (u64)flba * 512) != 0) return -22;
}
}
log_info("[UTSM] fat32 write: ok");
return 0;
}
/* 在根目录写入文件(8.3 名)。 */
static int fat32_write_root_file(const char *name11, const u8 *data, u32 size) {
const dkm_kernel_api *api = dkm_get_kernel_api();
if (!api || !api->block || !api->block->read) return -1;
u8 *disk = g_dsk_fat32_disk;
if (api->block->read(0, 0, 256, disk) != 0) return -2;
const fat32_bpb *bpb = (const fat32_bpb *)disk;
if (bpb->boot_sig != 0xAA55) return -3;
return fat32_write_file_in_dir(bpb->root_cluster, name11, data, size);
}
/* 按 8.3 路径(每段 11 字符,'/' 分隔)定位子目录,返回起始簇,失败返回 0。 */
static u32 fat32_find_dir_path(const char *path) {
const dkm_kernel_api *api = dkm_get_kernel_api();
if (!api || !api->block || !api->block->read) return 0;
u8 *disk = g_dsk_fat32_disk;
if (api->block->read(0, 0, 256, disk) != 0) return 0;
const fat32_bpb *bpb = (const fat32_bpb *)disk;
if (bpb->boot_sig != 0xAA55 || bpb->bytes_per_sector != 512) return 0;
u32 cur = bpb->root_cluster;
u32 pos = 0;
while (path[pos]) {
char comp[12];
u32 ci = 0;
while (path[pos] && path[pos] != '/') {
if (ci < 11) comp[ci++] = path[pos];
pos++;
}
while (ci < 11) comp[ci++] = ' ';
comp[11] = 0;
if (path[pos] == '/') pos++;
if (comp[0] == ' ') break; /* 空段防呆 */
u32 sub = 0, sz = 0;
if (fat32_find_in_dir(cur, comp, 1, &sub, &sz, 0) != 0) return 0;
cur = sub;
}
return cur;
}
/* 实机启动日志落盘:写 FAT32 文件。
* 优先写 SYSTEM/DESHAB64/DEV/BOOTLOG.TXT;DEV 目录缺失时回退根目录 BOOTLOG.TXT。
* 相比旧原始扇区方案不再覆盖 GPT header/entries,主机可直接读取该文件。
* 返回 0 成功。 */
int utsm_bootlog_write(const u8 *data, u32 size) {
const dkm_kernel_api *api = dkm_get_kernel_api();
if (!api || !api->block || !api->block->device_count) return -1;
if (api->block->device_count() == 0) return -2;
if (!api->block->write) return -3;
if (!data || size == 0) return -4;
static const char name11[11] = {'B','O','O','T','L','O','G',' ','T','X','T'};
u32 dev_clus = fat32_find_dir_path("SYSTEM /DESHAB64 /DEV ");
if (dev_clus >= 2)
return fat32_write_file_in_dir(dev_clus, name11, data, size);
return fat32_write_root_file(name11, data, size);
}
/* ---- ELF checks ---- */
static int dsk_check_elf(const void *address, u64 size) {
if (!address || size < sizeof(elf64_ehdr)) return -1;
Binary file not shown.
+2 -1
View File
@@ -2,7 +2,8 @@
/* ---- 内存日志缓冲区(实机启动日志持久化) ----
* 默认启用捕获:所有日志同时写串口和内存缓冲。
* 块设备就绪后由 disk_log_flush() 把缓冲区写入磁盘原始扇区。 */
* 块设备就绪后由 disk_log_flush() 把缓冲区写入 FAT32 文件
* SYSTEM/DESHAB64/DEV/BOOTLOG.TXT(DEV 缺失时回退根目录 BOOTLOG.TXT)。 */
#define LOG_BUF_SIZE 524288u /* 512KB, 覆盖 LBA 2-1000 (999 扇区 ~500KB) */
static char g_log_buf[LOG_BUF_SIZE];
static u32 g_log_len = 0;
+24 -51
View File
@@ -26,6 +26,10 @@ void dsm_load_by_manifest_ex(const ini_config *cfg);
* Phase 1 已支持 LFN 长文件名 + 子目录遍历。 */
extern int fat32_read_path(const char *path, u8 **out_data, u32 *out_size);
/* dsk_loader.c: 实机启动日志落盘。把日志缓冲写入 FAT32 文件:
* SYSTEM/DESHAB64/DEV/BOOTLOG.TXT(DEV 缺失时回退根目录 BOOTLOG.TXT)。 */
extern int utsm_bootlog_write(const u8 *data, u32 size);
/* ---- 运行期配置全局变量(从 FUCK 文件初始化) ---- */
u32 g_utsm_max_segments = UTSM_MAX_SEGMENTS_DEFAULT;
u32 g_utsm_max_capabilities = UTSM_MAX_CAPABILITIES_DEFAULT;
@@ -149,12 +153,16 @@ static int utsm_load_fuck_config(ini_config *cfg) {
return -2;
}
/* === 实机日志持久化:把内存日志缓冲区写入磁盘原始扇区 ===
* 开发测试用:实机无串口时,启动后用 WinHex/dd 读取磁盘对应扇区即可查看日志。
* 扇区范围由 FUCK [boot] disk_log_start / disk_log_end 配置(默认 2-1000)。
* 注意: 写入 LBA 1-33 会覆盖 GPT header/entries,重启后 Limine 可能无法找到 ESP。
* 建议测试盘从 LBA 34 开始,或测试后重新烧录镜像。 */
static void disk_log_flush(int start_lba, int end_lba) {
/* === 实机日志持久化:把内存日志缓冲区写入 FAT32 文件 ===
* 目标: SYSTEM/DESHAB64/DEV/BOOTLOG.TXT(DEV 目录不存在时回退根目录 BOOTLOG.TXT)。
* 由 FUCK [boot] disk_log=1 启用。
* 相比旧原始扇区方案(LBA 2-1000):
* - 不再覆盖 GPT header/entries,不破坏 Limine 引导链
* - 日志以普通 FAT32 文件呈现,主机直接读取即可,无需 WinHex/dd
* 日志超出 BOOTLOG_MAX_BYTES 时截断(128KB 足够覆盖完整启动链)。 */
#define BOOTLOG_MAX_BYTES (128u * 1024u)
static void disk_log_flush(void) {
const dkm_kernel_api *api = dkm_get_kernel_api();
if (!api || !api->block || !api->block->write || !api->block->device_count) {
log_warn("[UTSM] disk_log: block device unavailable, skip");
@@ -164,10 +172,6 @@ static void disk_log_flush(int start_lba, int end_lba) {
log_warn("[UTSM] disk_log: no block device, skip");
return;
}
if (end_lba <= start_lba) {
log_warn("[UTSM] disk_log: invalid sector range");
return;
}
const char *buf = log_get_buffer();
u32 len = log_get_length();
@@ -175,45 +179,16 @@ static void disk_log_flush(int start_lba, int end_lba) {
log_warn("[UTSM] disk_log: log buffer empty, skip");
return;
}
if (len > BOOTLOG_MAX_BYTES) len = BOOTLOG_MAX_BYTES;
u32 avail_sectors = (u32)(end_lba - start_lba + 1);
u32 avail_bytes = avail_sectors * 512;
u32 write_bytes = (len < avail_bytes) ? len : avail_bytes;
u32 full_sectors = write_bytes / 512;
u32 rem_bytes = write_bytes % 512;
u64 lba = (u64)start_lba;
u32 offset = 0;
/* 写完整扇区(AHCI 单次最多 8 扇区,block API 内部分块) */
while (full_sectors > 0) {
u32 chunk = (full_sectors > 8) ? 8 : full_sectors;
int st = api->block->write(0, lba, chunk, buf + offset);
if (st != 0) {
log_error("[UTSM] disk_log: write failed");
log_hex64("[UTSM] disk_log: lba=", lba);
return;
}
lba += chunk;
offset += chunk * 512;
full_sectors -= chunk;
int rc = utsm_bootlog_write((const u8 *)buf, len);
if (rc == 0) {
log_info("[UTSM] disk_log: BOOTLOG.TXT written");
log_hex64("[UTSM] disk_log: bytes=", len);
} else {
log_error("[UTSM] disk_log: FAT32 write failed");
log_hex64("[UTSM] disk_log: rc=", (u64)(i64)rc);
}
/* 最后一个不完整扇区:补零后写入 */
if (rem_bytes > 0) {
u8 tail[512];
for (u32 i = 0; i < 512; i++) tail[i] = 0;
for (u32 i = 0; i < rem_bytes; i++) tail[i] = (u8)buf[offset + i];
int st = api->block->write(0, lba, 1, tail);
if (st != 0) {
log_error("[UTSM] disk_log: tail write failed");
return;
}
}
log_info("[UTSM] disk_log: flushed to disk");
log_hex64("[UTSM] disk_log: start_lba=", (u64)start_lba);
log_hex64("[UTSM] disk_log: end_lba=", (u64)end_lba);
log_hex64("[UTSM] disk_log: bytes=", write_bytes);
}
void kernel_main(void) {
@@ -497,13 +472,11 @@ void kernel_main(void) {
log_info("[UTSM] PE DLL manager initialized (SYSTEM/lib)");
}
/* === 实机日志持久化:把启动日志写入磁盘原始扇区(开发测试用) === */
/* === 实机日志持久化:把启动日志写入 FAT32 文件 BOOTLOG.TXT === */
{
int disk_log = ini_get_bool(cfg, "boot", "disk_log", 0);
if (disk_log) {
int log_start = ini_get_int(cfg, "boot", "disk_log_start", 2);
int log_end = ini_get_int(cfg, "boot", "disk_log_end", 1000);
disk_log_flush(log_start, log_end);
disk_log_flush();
}
}
Binary file not shown.
+4
View File
@@ -34,6 +34,8 @@ typedef struct dsk_block_api_mirror {
void *pad0; void *pad1; /* register_device, device_count */
block_read_fn read;
block_write_fn write;
void *pad2; void *pad3; void *pad4; /* sector_size, device_name, set_write_fn */
u64 (*sector_count)(u32 index); /* 0x38: tail-append, 老内核该槽为 NULL */
} dsk_block_api_mirror;
typedef struct dsk_kernel_api_mirror {
@@ -55,6 +57,8 @@ _Static_assert(offsetof(dsk_kernel_api_mirror, block) == 0xA8,
"dsk_kernel_api_mirror.block offset must be 0xA8 (matching dkm_kernel_api)");
_Static_assert(offsetof(dsk_block_api_mirror, read) == 16,
"dsk_block_api_mirror.read offset must be 16 (matching dkm_block_api)");
_Static_assert(offsetof(dsk_block_api_mirror, sector_count) == 0x38,
"dsk_block_api_mirror.sector_count offset must be 0x38 (matching dkm_block_api tail-append)");
static void sputc(char c) { for(unsigned i=0;i<100000;i++){if(inb(COM1+5)&0x20)break;} outb(COM1,(u8)c); }
static void swrite(const char *s) { while(*s){if(*s=='\n')sputc('\r');sputc(*s++);} }
+15
View File
@@ -0,0 +1,15 @@
/* deshab/boot_log.h — SDK 侧 boot log 绑定(见 CODE/tools/boot_log.h) */
#ifndef DESHAB_BOOT_LOG_H
#define DESHAB_BOOT_LOG_H
#include "../../tools/boot_log.h"
#include "boot_context.h"
static inline void dsb_bootlog_bind(dsb_boot_log_info **slot, const dsk_boot_context *ctx) {
boot_log_bind((boot_log_info **)slot, ctx ? ctx->utsm_state : 0);
}
/* 兼容别名 */
typedef boot_log_info dsb_boot_log_info;
#endif /* DESHAB_BOOT_LOG_H */
+1
View File
@@ -117,6 +117,7 @@ typedef struct dkm_block_api {
u64 (*sector_size)(u32 index);
const char *(*device_name)(u32 index);
int (*set_write_fn)(u32 index, dkm_block_write_fn fn);
u64 (*sector_count)(u32 index); /* 0x38: tail-append, 与 utsm/block.h 同步 */
} dkm_block_api;
/* ---- MMIO / 页表 API ----
+59
View File
@@ -0,0 +1,59 @@
/* boot_log.h — 跨 UTSM/DSK/应用 ELF 的启动日志环形缓冲(freestanding,无 libc)
*
* boot_log_info 由 UTSM 在静态内存中创建,经 dsk_boot_context.utsm_state 传递。
* DSK 注册 flush 回调,将缓冲写入 FAT32: SYSTEM/DESHAB64/DEV/BOOTLOG.TXT
* (DEV 目录不存在时回退 ESP 根目录 BOOTLOG.TXT)。
*/
#ifndef BOOT_LOG_H
#define BOOT_LOG_H
typedef unsigned int u32;
typedef unsigned long long u64;
#define BOOT_LOG_MAGIC 0x424C4746u /* "BLGF" */
#define BOOT_LOG_VERSION 1u
typedef struct boot_log_info boot_log_info;
typedef int (*boot_log_flush_fn)(void);
struct boot_log_info {
u32 magic;
u32 version;
char *buf;
u32 capacity;
u32 length;
u32 dropped;
boot_log_flush_fn flush;
};
static inline void boot_log_append(boot_log_info *bi, const char *s) {
if (!bi || bi->magic != BOOT_LOG_MAGIC || !s || !bi->buf)
return;
while (*s) {
if (bi->length < bi->capacity)
bi->buf[bi->length++] = *s;
else
bi->dropped++;
s++;
}
}
static inline void boot_log_bind(boot_log_info **slot, u64 utsm_state) {
if (!slot)
return;
*slot = 0;
if (!utsm_state)
return;
boot_log_info *bi = (boot_log_info *)(u64)utsm_state;
if (bi && bi->magic == BOOT_LOG_MAGIC && bi->buf && bi->capacity)
*slot = bi;
}
static inline int boot_log_try_flush(boot_log_info *bi) {
if (bi && bi->flush)
return bi->flush();
return -1;
}
#endif /* BOOT_LOG_H */
+856
View File
@@ -0,0 +1,856 @@
/* fat32_write.h - Deshab 共享 FAT32 写库(static inline,无库)
*
* 前置条件:包含者已定义 u8/u16/u32/u64/i64 基础类型。
* 通过 f32w_init() 注入 block_read/block_write 函数指针(签名与 f32_/gpt_ 库一致)。
*
* 与 fat32_io.h 的分工:
* fat32_io.h - 8.3 短名读写,依赖 256 扇区 BPB+FAT+根目录缓存窗口
* fat32_write.h - LFN 长名创建 / mkdir / 目录簇链扩展,FAT 按需单扇区访问
*
* 本库解决 fat32_io.h 的三个写缺口(大 ESP 场景,2GB: spc=8, FAT=4086 扇区,
* 根目录在分区 LBA 8204,均远超 256 扇区窗口):
* 1. LFN 生成:VFAT LFN 链(每项 13 UTF-16 字符,逆序存储,0x40 标志 +
* 短名 checksum),配套 ~N 数字尾巴的 8.3 短名生成与唯一化
* 2. mkdir:分配目录簇 + 写入 "." / ".." 项 + 父目录插入 LFN 条目
* 3. 目录簇链扩展:目录槽位不足时自动分配新簇并接入链尾(槽位可跨簇)
*
* FAT 访问策略:按需读改写单个 FAT 扇区(含缓存),修改后立即回写所有 FAT
* 副本(BPB->fc 份)。不依赖任何批量缓存窗口,任意簇号/FAT 偏移均可访问。
*
* 用法:
* f32w_init(block_read, block_write) - 初始化(注入块设备)
* f32w_write_file(dir_clus, "user.conf", d, n) - 目录中写/替换长名文件
* f32w_mkdir(dir_clus, "MyDir", &out_clus) - 创建子目录(LFN)
* f32w_resolve_dir("system/deshab64", &clus) - 按路径定位目录簇
* f32w_write_path("system/deshab64/user.conf", d, n)- 按路径写文件(LFN)
* f32w_mkdir_path("system/新建目录", &clus) - 按路径建目录
* f32w_find(dir_clus, name, want_dir, ...) - 按长名查找(LFN 优先)
*
* 缓冲区:每包含者约 9KB BSS(512 BPB + 512 FAT 扇区 + 簇缓冲 ×2)。
* 与 fat32_io.h 可同时包含(前缀 f32w_ / f32_ 不冲突),但二者状态独立。
*/
#ifndef DESHAB_FAT32_WRITE_H
#define DESHAB_FAT32_WRITE_H
#include "fat32_lfn.h"
/* ---- block 设备函数类型(与 fat32_io.h / gpt_write.h 一致:index 固定 0) ---- */
typedef int (*f32w_block_read_fn)(u32 index, u64 lba, u32 count, void *buf);
typedef int (*f32w_block_write_fn)(u32 index, u64 lba, u32 count, const void *buf);
static f32w_block_read_fn f32w_blk_read = 0;
static f32w_block_write_fn f32w_blk_write = 0;
/* ---- 目录簇缓冲大小(含 data 暂存缓冲)。build.ps1 mkfs spc=8 -> 4096。
* 包含者可在 include 前 #define F32W_CLUS_BYTES 覆盖(须为 512 的倍数)。 */
#ifndef F32W_CLUS_BYTES
#define F32W_CLUS_BYTES 4096
#endif
#define F32W_EOC 0x0FFFFFFFu
#define F32W_EOC_VAL 0x0FFFFFFFu /* 写入 FAT 的 EOC 值(高 4 位保留位置 0x0Fxxxxxx 已含) */
/* ---- BPB(512B,与 f32_bpb 布局一致;独立定义避免依赖 fat32_io.h) ---- */
typedef struct __attribute__((packed)) {
u8 jmp[3]; char oem[8]; u16 bps; u8 spc; u16 rsvd; u8 fc; u16 root_ent;
u16 ts16; u8 media; u16 spf16; u16 spt; u16 heads; u32 hidden; u32 ts32;
u32 spf; u16 flags; u16 ver; u32 root_clus; u16 fsi; u16 bkboot;
u8 res[12]; u8 drv; u8 ntfl; u8 sig; u32 ser; char lbl[11]; char typ[8];
u8 code[420]; u16 boot_sig;
} f32w_bpb_t;
typedef struct __attribute__((packed)) {
char name[11]; u8 attr; u8 ntr; u8 ctenth;
u16 ctime; u16 cdate; u16 adate; u16 chigh;
u16 wtime; u16 wdate; u16 clow; u32 fsize;
} f32w_dirent_t;
/* ---- 挂载上下文(f32w_bpb_load 填充) ---- */
typedef struct {
u32 spc; /* 每簇扇区数 */
u32 clus_bytes; /* spc * 512 */
u32 fat_lba; /* FAT 副本 0 起始 LBA(= rsvd) */
u32 fat_copies; /* FAT 副本数(BPB->fc,实际至少 2) */
u32 fat_sectors; /* 单份 FAT 扇区数(BPB->spf) */
u32 data_lba; /* 数据区起始 LBA */
u32 root_clus; /* 根目录首簇 */
u32 fat_entries; /* FAT 项数上界 = spf*512/4 */
int loaded;
} f32w_ctx;
static f32w_ctx f32w_c;
/* ---- 内部缓冲(每包含者独立) ---- */
static u8 f32w_sec[512]; /* BPB / FSInfo 扇区缓冲 */
static u8 f32w_fat[512]; /* FAT 单扇区缓存 */
static u32 f32w_fat_sec_no = 0xFFFFFFFFu; /* 缓存的 FAT 扇区号(FAT 内偏移) */
static u8 f32w_dir[F32W_CLUS_BYTES]; /* 目录簇缓存(槽位扫描/条目写入) */
static u32 f32w_dir_no = 0; /* 缓存的目录簇号(0=无,簇号最小为 2) */
static int f32w_dir_dirty = 0;
static u8 f32w_stage[F32W_CLUS_BYTES]; /* 数据写入暂存(尾簇零填充) */
static u32 f32w_alloc_hint = 2; /* 空闲簇分配起点提示 */
/* ---- 初始化:注入 block_read/block_write 函数指针 ---- */
static inline void f32w_init(f32w_block_read_fn rd, f32w_block_write_fn wr) {
f32w_blk_read = rd;
f32w_blk_write = wr;
f32w_c.loaded = 0;
f32w_fat_sec_no = 0xFFFFFFFFu;
f32w_dir_no = 0;
f32w_dir_dirty = 0;
f32w_alloc_hint = 2;
}
static inline int f32w_read_sectors(u32 lba, u32 count, u8 *out) {
return f32w_blk_read ? f32w_blk_read(0, lba, count, out) : -1;
}
static inline int f32w_write_sectors(u32 lba, u32 count, const u8 *buf) {
return f32w_blk_write ? f32w_blk_write(0, lba, count, buf) : -1;
}
/* ---- 小工具(无库约束:手写循环替代 mem*) ---- */
static inline void f32w_mem_set(u8 *p, u8 v, u32 n) { for (u32 i = 0; i < n; i++) p[i] = v; }
static inline u32 f32w_r32(const u8 *p) {
return (u32)p[0] | ((u32)p[1] << 8) | ((u32)p[2] << 16) | ((u32)p[3] << 24);
}
static inline u16 f32w_r16(const u8 *p) { return (u16)p[0] | ((u16)p[1] << 8); }
/* ---- BPB 加载 / 挂载上下文 ---- */
static inline int f32w_bpb_load(void) {
if (f32w_c.loaded) return 0;
if (f32w_read_sectors(0, 1, f32w_sec) != 0) return -1;
const f32w_bpb_t *b = (const f32w_bpb_t *)f32w_sec;
if (b->boot_sig != 0xAA55 || b->bps != 512) return -2;
if (b->spf == 0 || b->root_clus < 2 || b->spc == 0) return -3;
u32 fc = b->fc ? b->fc : 1;
u32 cb = (u32)b->spc * 512;
if (cb > F32W_CLUS_BYTES) return -4; /* 簇超出缓冲,包含者应调大 F32W_CLUS_BYTES */
f32w_c.spc = b->spc;
f32w_c.clus_bytes = cb;
f32w_c.fat_lba = b->rsvd;
f32w_c.fat_copies = fc;
f32w_c.fat_sectors = b->spf;
f32w_c.data_lba = b->rsvd + fc * b->spf;
f32w_c.root_clus = b->root_clus;
f32w_c.fat_entries = b->spf * 512 / 4;
f32w_c.loaded = 1;
f32w_fat_sec_no = 0xFFFFFFFFu; /* 新挂载,作废 FAT 缓存 */
return 0;
}
static inline u32 f32w_clus_lba(u32 clus) {
return f32w_c.data_lba + (clus - 2) * f32w_c.spc;
}
/* ---- FAT 按需访问(单扇区缓存 + 全副本回写) ---- */
/* 读 FAT 项。返回 0 成功,*out 为 28 位簇值。 */
static inline int f32w_fat_get(u32 clus, u32 *out) {
if (clus < 2 || clus >= f32w_c.fat_entries) return -1;
u32 sec = clus >> 7; /* 每扇区 128 项 */
u32 off = (clus & 127) * 4;
if (sec != f32w_fat_sec_no) {
if (f32w_read_sectors(f32w_c.fat_lba + sec, 1, f32w_fat) != 0) return -2;
f32w_fat_sec_no = sec;
}
*out = f32w_r32(f32w_fat + off) & 0x0FFFFFFF;
return 0;
}
/* 写 FAT 项(含 28 位掩码),立即回写所有 FAT 副本对应扇区。 */
static inline int f32w_fat_set(u32 clus, u32 val) {
if (clus < 2 || clus >= f32w_c.fat_entries) return -1;
u32 sec = clus >> 7;
u32 off = (clus & 127) * 4;
if (sec != f32w_fat_sec_no) {
if (f32w_read_sectors(f32w_c.fat_lba + sec, 1, f32w_fat) != 0) return -2;
f32w_fat_sec_no = sec;
}
u32 old = f32w_r32(f32w_fat + off);
val &= 0x0FFFFFFF;
f32w_fat[off] = (u8)(val & 0xFF);
f32w_fat[off + 1] = (u8)((val >> 8) & 0xFF);
f32w_fat[off + 2] = (u8)((val >> 16) & 0xFF);
f32w_fat[off + 3] = (u8)((old & 0xF0) | ((val >> 24) & 0x0F));
for (u32 f = 0; f < f32w_c.fat_copies; f++) {
u32 lba = f32w_c.fat_lba + f * f32w_c.fat_sectors + sec;
if (f32w_write_sectors(lba, 1, f32w_fat) != 0) return -3;
}
return 0;
}
/* 分配一个空闲簇(线性扫描 + 起点提示轮转)。返回簇号,0=已满/失败。 */
static inline u32 f32w_alloc_free(void) {
u32 total = f32w_c.fat_entries > 2 ? f32w_c.fat_entries - 2 : 0;
if (total == 0) return 0;
u32 start = (f32w_alloc_hint >= 2 && f32w_alloc_hint < f32w_c.fat_entries)
? f32w_alloc_hint : 2;
for (u32 i = 0; i < total; i++) {
u32 c = 2 + ((start - 2 + i) % total);
u32 v = 0;
if (f32w_fat_get(c, &v) != 0) return 0;
if (v == 0) {
f32w_alloc_hint = c + 1;
return c;
}
}
return 0;
}
/* 释放整条簇链(逐项清 0)。带环保护。 */
static inline int f32w_free_chain(u32 clus) {
u32 cur = clus;
u64 guard = 0;
while (cur >= 2 && cur < 0x0FFFFFF8) {
if (++guard > (u64)f32w_c.fat_entries + 2) return -1; /* FAT 成环,损坏 */
u32 next = 0;
if (f32w_fat_get(cur, &next) != 0) return -2;
if (f32w_fat_set(cur, 0) != 0) return -3;
cur = next;
}
return 0;
}
/* ---- 目录簇缓存(槽位扫描 / 条目写入共用) ---- */
static inline int f32w_dir_flush(void) {
if (!f32w_dir_dirty || f32w_dir_no == 0) { f32w_dir_dirty = 0; return 0; }
if (f32w_write_sectors(f32w_clus_lba(f32w_dir_no), f32w_c.spc, f32w_dir) != 0) return -1;
f32w_dir_dirty = 0;
return 0;
}
static inline int f32w_dir_load(u32 clus) {
if (f32w_dir_no == clus && clus != 0) return 0;
if (f32w_dir_flush() != 0) return -1;
if (f32w_read_sectors(f32w_clus_lba(clus), f32w_c.spc, f32w_dir) != 0) return -2;
f32w_dir_no = clus;
return 0;
}
/* 在 (clus, idx) 写入 32 字节目录项。 */
static inline int f32w_entry_write(u32 clus, u32 idx, const u8 *e32) {
if (idx * 32 + 32 > f32w_c.clus_bytes) return -1;
if (f32w_dir_load(clus) != 0) return -2;
for (int i = 0; i < 32; i++) f32w_dir[idx * 32 + i] = e32[i];
f32w_dir_dirty = 1;
return 0;
}
/* 槽位步进:同簇内 idx+1,越界则沿 FAT 链进入下一簇(run 保证连续)。 */
static inline int f32w_slot_step(u32 *clus, u32 *idx) {
(*idx)++;
if ((*idx) * 32 >= f32w_c.clus_bytes) {
u32 next = 0;
if (f32w_fat_get(*clus, &next) != 0) return -1;
if (next < 2 || next >= 0x0FFFFFF8) return -1;
*clus = next;
*idx = 0;
}
return 0;
}
/* ---- 8.3 短名生成(含 ~N 唯一化) ---- */
static inline char f32w_up(char c) { return (c >= 'a' && c <= 'z') ? (char)(c - 32) : c; }
/* 合法 8.3 短名字符(已转大写后):字母/数字/!#$%&'()-@^_`{}~ */
static inline int f32w_char_ok_83(char c) {
if (c >= 'A' && c <= 'Z') return 1;
if (c >= '0' && c <= '9') return 1;
if (c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'') return 1;
if (c == '(' || c == ')' || c == '-' || c == '@' || c == '^' || c == '_') return 1;
if (c == '`' || c == '{' || c == '}' || c == '~') return 1;
return 0;
}
/* 名字长度(手动 strlen)。 */
static inline u32 f32w_strlen(const char *s) {
u32 n = 0;
while (s[n]) n++;
return n;
}
/* 生成长名对应的 8.3 短名(未唯一化)。
* name11 : 输出 11 字符短名(大写、空格填充;非法字符转 '_',超长截断)
* needs_lfn: 输出 1=长名无法无损表示为 8.3(需写 LFN 链 + 后续 ~N 唯一化)
* 返回 0 成功,-1 名字非法(空/过长/含非 ASCII/纯点)。 */
static inline int f32w_make_short(const char *name, char name11[11], int *needs_lfn) {
u32 len = f32w_strlen(name);
if (len == 0 || len > 255) return -1;
u32 last_dot = 0xFFFFFFFFu;
u32 dot_count = 0;
int all_upper_valid = 1;
for (u32 i = 0; i < len; i++) {
char c = name[i];
if ((u8)c < 0x20 || (u8)c >= 0x7F || c == '/') return -1;
if (c == '.') { last_dot = i; dot_count++; }
if (c >= 'a' && c <= 'z') all_upper_valid = 0;
else if (!f32w_char_ok_83(f32w_up(c))) all_upper_valid = 0;
}
/* 纯点 / 尾点 / 首空格:非法(简化处理,与 Windows 行为近似) */
int non_dot = 0;
for (u32 i = 0; i < len; i++) if (name[i] != '.') { non_dot = 1; break; }
if (!non_dot || name[len - 1] == '.' || name[0] == ' ') return -1;
u32 base_end = (last_dot == 0xFFFFFFFFu) ? len : last_dot;
u32 base_len = base_end;
u32 ext_len = (last_dot == 0xFFFFFFFFu) ? 0 : len - last_dot - 1;
*needs_lfn = !(all_upper_valid && base_len <= 8 && ext_len <= 3 && dot_count <= 1);
for (int i = 0; i < 11; i++) name11[i] = ' ';
u32 bi = 0;
for (u32 i = 0; i < base_len && bi < 8; i++) {
char c = f32w_up(name[i]);
if (!f32w_char_ok_83(c)) c = '_';
name11[bi++] = c;
}
if (bi == 0) name11[bi++] = '_'; /* 空基名(如 ".config")用 '_' 兜底 */
u32 ei = 0;
if (last_dot != 0xFFFFFFFFu) {
for (u32 i = 0; i < ext_len && ei < 3; i++) {
char c = f32w_up(name[last_dot + 1 + i]);
if (!f32w_char_ok_83(c)) c = '_';
name11[8 + ei++] = c;
}
}
return 0;
}
/* 目录中是否已存在指定 11 字符短名(仅比较短名项)。1=存在,0=不存在,-1=IO 错。 */
static inline int f32w_dir_short_exists(u32 dir_clus, const char name11[11]) {
u32 dclus = dir_clus;
u64 guard = 0;
while (dclus >= 2 && dclus < 0x0FFFFFF8) {
if (++guard > (u64)f32w_c.fat_entries + 2) return -1;
if (f32w_dir_load(dclus) != 0) return -1;
u32 max_e = f32w_c.clus_bytes / 32;
for (u32 e = 0; e < max_e; e++) {
const u8 *ent = f32w_dir + e * 32;
if (ent[0] == 0x00) return 0; /* 目录结尾 */
if (ent[0] == 0xE5) continue;
if (ent[11] == 0x0F) continue; /* LFN 项 */
if (ent[11] & 0x08) continue; /* 卷标 */
int same = 1;
for (int i = 0; i < 11; i++)
if (ent[i] != (u8)name11[i]) { same = 0; break; }
if (same) return 1;
}
u32 next = 0;
if (f32w_fat_get(dclus, &next) != 0) return -1;
dclus = next;
}
return 0;
}
/* 生成长名对应的唯一 8.3 短名(lossy 时追加 ~1..~999999 数字尾巴)。
* 返回 0 成功,负值失败。 */
static inline int f32w_make_unique_short(u32 dir_clus, const char *name, char name11[11]) {
int needs_lfn = 0;
if (f32w_make_short(name, name11, &needs_lfn) != 0) return -1;
if (!needs_lfn) return 0; /* 无损 8.3,同名冲突由 f32w_find 语义覆盖 */
/* 提取 make_short 产生的 base / ext,枚举 BASE~N 直到唯一 */
char base[8];
u32 base_len = 0;
for (u32 i = 0; i < 8 && name11[i] != ' '; i++) base[base_len++] = name11[i];
if (base_len == 0) { base[0] = '_'; base_len = 1; }
for (u32 n = 1; n <= 999999u; n++) {
char digits[8];
int dn = 0;
u32 v = n;
while (v) { digits[dn++] = (char)('0' + (v % 10)); v /= 10; }
u32 bl = (dn + 1 >= 8) ? 1 : 8 - dn - 1; /* 保留 '~'+数字 的空间 */
if (base_len < bl) bl = base_len;
for (u32 i = 0; i < 8; i++) name11[i] = ' ';
for (u32 i = 0; i < bl; i++) name11[i] = base[i];
u32 p = bl;
name11[p++] = '~';
for (int i = dn - 1; i >= 0; i--) name11[p++] = digits[i];
int ex = f32w_dir_short_exists(dir_clus, name11);
if (ex < 0) return -2;
if (ex == 0) return 0;
}
return -3; /* 序号耗尽 */
}
/* ---- LFN 条目生成 ---- */
/* 13 个 UTF-16 槽位在 32 字节目录项内的字节偏移(name1[5] name2[6] name3[2]) */
static inline int f32w_lfn_slot_off(int slot) {
if (slot < 5) return 1 + slot * 2;
if (slot < 11) return 14 + (slot - 5) * 2;
return 28 + (slot - 11) * 2;
}
/* 构造第 ordinal 个 LFN 片段项(ordinal 1..total,total 为链长)。
* name 为 ASCII 长名,len 为字符数。out32 接收 32 字节编码。
* 最高序号项(ordinal==total)带 0x40 标志,含 0x0000 终止 + 0xFFFF 填充。
* 返回 0 成功。 */
static inline int f32w_build_lfn_entry(int ordinal, int total, const char *name,
u32 len, u8 cksum, u8 *out32) {
f32w_mem_set(out32, 0, 32);
/* 全槽位预填 0xFFFF */
for (int s = 0; s < 13; s++) {
int off = f32w_lfn_slot_off(s);
out32[off] = 0xFF;
out32[off + 1] = 0xFF;
}
u32 base = (u32)(ordinal - 1) * 13;
u32 cnt = (len - base) < 13 ? (len - base) : 13;
for (u32 j = 0; j < cnt; j++) {
int off = f32w_lfn_slot_off((int)j);
u16 c = (u16)(u8)name[base + j]; /* ASCII -> UTF-16 */
out32[off] = (u8)(c & 0xFF);
out32[off + 1] = (u8)(c >> 8);
}
if (ordinal == total && cnt < 13) {
int off = f32w_lfn_slot_off((int)cnt); /* 0x0000 终止符 */
out32[off] = 0;
out32[off + 1] = 0;
}
out32[0] = (u8)(ordinal | (ordinal == total ? 0x40 : 0x00));
out32[11] = 0x0F; /* ATTR_LONG_NAME */
out32[12] = 0; /* type */
out32[13] = cksum;
out32[26] = 0; /* 首簇号必须为 0 */
out32[27] = 0;
return 0;
}
/* 构造 8.3 短名项。 */
static inline void f32w_build_short_entry(const char name11[11], u8 attr,
u32 clus, u32 size, u8 *out32) {
f32w_mem_set(out32, 0, 32);
for (int i = 0; i < 11; i++) out32[i] = (u8)name11[i];
out32[11] = attr;
/* 时间戳字段保持 0(与 fat32_io.h 写路径一致) */
out32[21] = (u8)((clus >> 16) & 0xFF); /* chigh */
out32[20] = (u8)((clus >> 24) & 0xFF);
out32[26] = (u8)(clus & 0xFF); /* clow */
out32[27] = (u8)((clus >> 8) & 0xFF);
out32[28] = (u8)(size & 0xFF); /* fsize */
out32[29] = (u8)((size >> 8) & 0xFF);
out32[30] = (u8)((size >> 16) & 0xFF);
out32[31] = (u8)((size >> 24) & 0xFF);
}
/* ---- 目录槽位分配(含簇链扩展,槽位可跨簇) ---- */
/* 在目录簇链中找 count 个连续空闲槽位(0x00/0xE5)。链尾不足时自动分配
* 新簇:FAT 接链 + 新簇清零 + 落盘,槽位 run 跨簇继续累计。
* out_clus/out_idx : run 首槽位位置(簇号 + 簇内项索引)
* 返回 0 成功,负值失败(-3=磁盘满)。 */
static inline int f32w_dir_alloc_slots(u32 dir_clus, u32 count,
u32 *out_clus, u32 *out_idx) {
u32 run_clus = 0, run_idx = 0, run = 0;
u32 dclus = dir_clus;
u64 guard = 0;
while (dclus >= 2 && dclus < 0x0FFFFFF8) {
if (++guard > (u64)f32w_c.fat_entries + 2) return -1; /* FAT 成环 */
if (f32w_dir_load(dclus) != 0) return -2;
u32 max_e = f32w_c.clus_bytes / 32;
for (u32 e = 0; e < max_e; e++) {
u8 first = f32w_dir[e * 32];
if (first == 0x00 || first == 0xE5) {
if (run == 0) { run_clus = dclus; run_idx = e; }
run++;
if (run >= count) {
*out_clus = run_clus;
*out_idx = run_idx;
return 0;
}
} else {
run = 0;
}
}
u32 next = 0;
if (f32w_fat_get(dclus, &next) != 0) return -2;
if (next >= 2 && next < 0x0FFFFFF8) { dclus = next; continue; }
/* 链尾且 run 不足:扩展一个新簇接入链尾 */
u32 nc = f32w_alloc_free();
if (nc == 0) return -3;
if (f32w_fat_set(dclus, nc) != 0) return -4;
if (f32w_fat_set(nc, F32W_EOC_VAL) != 0) return -4;
if (f32w_dir_flush() != 0) return -5;
f32w_mem_set(f32w_dir, 0, f32w_c.clus_bytes); /* 新簇全 0 */
f32w_dir_no = nc;
f32w_dir_dirty = 1; /* 脏标记使 flush 落盘清零内容 */
if (f32w_dir_flush() != 0) return -5;
dclus = nc;
/* run 跨簇继续累计(新簇全 0x00,下一轮循环继续计数) */
}
return -6;
}
/* ---- 按长名查找(LFN 优先,8.3 回退;大小写不敏感) ---- */
/* 在目录中查找 name(长名或 8.3 显示名)。
* want_dir : -1 任意,0 只匹配文件,1 只匹配目录
* out_clus/size : 目标首簇 / 大小(可 NULL)
* out_ent_clus/idx : 短名项位置(可 NULL,用于原地更新)
* out_attr : 目录项属性(可 NULL)
* 返回 0 找到,-1 未找到,其他负值 IO 错。LFN 缓冲跨簇存活(链可跨簇)。 */
static inline int f32w_find(u32 dir_clus, const char *name, int want_dir,
u32 *out_clus, u32 *out_size,
u32 *out_ent_clus, u32 *out_ent_idx, u8 *out_attr) {
if (dir_clus == 0) dir_clus = f32w_c.root_clus;
u32 dclus = dir_clus;
u64 guard = 0;
fat32_lfn_buf lfn;
fat32_lfn_init(&lfn);
while (dclus >= 2 && dclus < 0x0FFFFFF8) {
if (++guard > (u64)f32w_c.fat_entries + 2) return -2;
if (f32w_dir_load(dclus) != 0) return -3;
u32 max_e = f32w_c.clus_bytes / 32;
for (u32 e = 0; e < max_e; e++) {
const u8 *ent = f32w_dir + e * 32;
if (ent[0] == 0x00) return -1; /* 目录结尾,未找到 */
if (ent[0] == 0xE5) { fat32_lfn_init(&lfn); continue; }
const f32w_dirent_t *de = (const f32w_dirent_t *)ent;
int is_short = fat32_lfn_process(&lfn, ent);
if (!is_short) continue;
if (de->attr & 0x08) { fat32_lfn_init(&lfn); continue; } /* 卷标 */
if (de->name[0] == '.' && (de->name[1] == ' ' || de->name[1] == '.')) {
fat32_lfn_init(&lfn); /* "." / ".." */
continue;
}
int entry_is_dir = (de->attr & 0x10) ? 1 : 0;
if (want_dir >= 0 && entry_is_dir != want_dir) {
fat32_lfn_init(&lfn);
continue;
}
int matched = 0;
if (lfn.valid) {
char ascii[FAT32_LFN_MAX];
if (fat32_lfn_to_ascii(&lfn, ascii, sizeof(ascii)) >= 0 &&
fat32_lfn_streq_ci(ascii, name)) matched = 1;
}
if (!matched) {
char disp[13];
fat32_lfn_short_to_str((const u8 *)de->name, disp);
if (fat32_lfn_streq_ci(disp, name)) matched = 1;
}
if (matched) {
u32 fc = (u32)f32w_r16((const u8 *)&de->clow) |
((u32)f32w_r16((const u8 *)&de->chigh) << 16);
if (out_clus) *out_clus = fc;
if (out_size) *out_size = de->fsize;
if (out_ent_clus) *out_ent_clus = dclus;
if (out_ent_idx) *out_ent_idx = e;
if (out_attr) *out_attr = de->attr;
return 0;
}
fat32_lfn_init(&lfn);
}
u32 next = 0;
if (f32w_fat_get(dclus, &next) != 0) return -3;
dclus = next;
}
return -1;
}
/* ---- 文件数据簇链写入(新建 / 复用扩展 / 截断收缩) ---- */
/* 写 size 字节数据。have>=2 时复用现有链(按需扩展或截断并释放多余簇),
* have<2 时全新分配。*out_first 输出结果首簇(size==0 时为 0)。
* 返回 0 成功,负值失败。 */
static inline int f32w_data_write(u32 have, const u8 *data, u32 size, u32 *out_first) {
u32 cb = f32w_c.clus_bytes;
u32 need = size ? (size + cb - 1) / cb : 0;
if (need == 0) {
if (have >= 2) {
if (f32w_free_chain(have) != 0) return -1;
}
*out_first = 0;
return 0;
}
u32 first = 0, prev = 0, count = 0;
if (have >= 2) {
first = have;
u32 cur = have;
while (cur >= 2 && cur < 0x0FFFFFF8 && count < need) {
prev = cur;
u32 next = 0;
if (f32w_fat_get(cur, &next) != 0) return -2;
cur = next;
count++;
}
while (count < need) { /* 现有链不足:扩展 */
u32 nc = f32w_alloc_free();
if (nc == 0) return -3;
if (f32w_fat_set(nc, F32W_EOC_VAL) != 0) return -4;
if (f32w_fat_set(prev, nc) != 0) return -4;
prev = nc;
count++;
}
if (cur >= 2 && cur < 0x0FFFFFF8) { /* 现有链过长:截断 */
if (f32w_fat_set(prev, F32W_EOC_VAL) != 0) return -4;
if (f32w_free_chain(cur) != 0) return -5;
}
} else {
for (u32 i = 0; i < need; i++) { /* 全新分配 */
u32 nc = f32w_alloc_free();
if (nc == 0) return -3;
if (f32w_fat_set(nc, F32W_EOC_VAL) != 0) return -4;
if (prev) {
if (f32w_fat_set(prev, nc) != 0) return -4;
} else {
first = nc;
}
prev = nc;
}
count = need;
}
/* 写数据:整簇直写源缓冲,尾簇经暂存缓冲零填充 */
u32 remaining = size;
const u8 *src = data;
u32 c = first;
for (u32 i = 0; i < count && remaining > 0; i++) {
u32 chunk = remaining < cb ? remaining : cb;
u32 lba = f32w_clus_lba(c);
if (chunk == cb) {
if (f32w_write_sectors(lba, f32w_c.spc, src) != 0) return -6;
} else {
f32w_mem_set(f32w_stage, 0, cb);
for (u32 b = 0; b < chunk; b++) f32w_stage[b] = src[b];
if (f32w_write_sectors(lba, f32w_c.spc, f32w_stage) != 0) return -6;
}
src += chunk;
remaining -= chunk;
if (i + 1 < count) {
u32 next = 0;
if (f32w_fat_get(c, &next) != 0) return -2;
c = next;
}
}
*out_first = first;
return 0;
}
/* ---- FSInfo 置未知(写操作后调用,best-effort) ----
* 分配/释放后空闲簇数不再准确,置 0xFFFFFFFF(未知)避免 UEFI/Windows
* 依赖陈旧计数。忽略失败(无 FSInfo 的镜像不受影响)。 */
static inline void f32w_fsinfo_unknown(void) {
if (!f32w_c.loaded) return;
u32 fsi_lba = 0;
{
/* 重新读 BPB 拿 FSInfo 扇区号(f32w_sec 此后未被覆盖过也可直接用) */
const f32w_bpb_t *b = (const f32w_bpb_t *)f32w_sec;
if (b->boot_sig != 0xAA55) return;
fsi_lba = b->fsi;
}
if (fsi_lba == 0 || fsi_lba == 0xFFFF) return;
u8 sec[512];
if (f32w_read_sectors(fsi_lba, 1, sec) != 0) return;
sec[488] = 0xFF; sec[489] = 0xFF; sec[490] = 0xFF; sec[491] = 0xFF;
sec[492] = 0xFF; sec[493] = 0xFF; sec[494] = 0xFF; sec[495] = 0xFF;
(void)f32w_write_sectors(fsi_lba, 1, sec);
}
/* ---- 写入 LFN 链 + 短名项(dir_alloc_slots 已定位 run 起点) ---- */
static inline int f32w_insert_entries(u32 dir_clus, const char *name,
const char name11[11], u32 clus, u32 size, u8 attr) {
u32 len = f32w_strlen(name);
int needs_lfn = 0;
/* needs_lfn 与调用方 make_unique_short 判定一致:重算(无损则短名回退匹配) */
{
char tmp11[11];
if (f32w_make_short(name, tmp11, &needs_lfn) != 0) return -1;
}
u32 nlfn = needs_lfn ? (len + 12) / 13 : 0;
u32 sc = 0, si = 0;
if (f32w_dir_alloc_slots(dir_clus, nlfn + 1, &sc, &si) != 0) return -2;
if (needs_lfn) {
u8 ck = fat32_lfn_checksum((const u8 *)name11);
for (int k = (int)nlfn; k >= 1; k--) { /* 逆序:最高序号最先落盘 */
u8 e[32];
f32w_build_lfn_entry(k, (int)nlfn, name, len, ck, e);
if (f32w_entry_write(sc, si, e) != 0) return -3;
if (k > 1 && f32w_slot_step(&sc, &si) != 0) return -4;
}
if (nlfn > 0 && f32w_slot_step(&sc, &si) != 0) return -4;
}
u8 se[32];
f32w_build_short_entry(name11, attr, clus, size, se);
if (f32w_entry_write(sc, si, se) != 0) return -3;
if (f32w_dir_flush() != 0) return -5;
return 0;
}
/* ================= 公共 API ================= */
/* 在目录中写/替换长名文件(LFN 创建 + 短名 ~N 唯一化 + FAT 链管理)。
* dir_clus : 目标目录首簇(0=根目录)
* name : 长文件名(ASCII;非 8.3 无损表示时自动生成 LFN 链)
* data/size: 文件内容(size 可为 0,簇链释放、大小清 0)
* 同名存在:文件原地替换内容(保留原目录项/LFN),目录返回 -20。
* 返回 0 成功,负值失败。 */
static inline int f32w_write_file(u32 dir_clus, const char *name,
const u8 *data, u32 size) {
if (f32w_bpb_load() != 0) return -1;
if (!f32w_blk_write) return -2;
if (!name || (!data && size)) return -3;
if (dir_clus == 0) dir_clus = f32w_c.root_clus;
u32 e_clus = 0, e_size = 0, ent_clus = 0, ent_idx = 0;
u8 e_attr = 0;
int fr = f32w_find(dir_clus, name, -1, &e_clus, &e_size, &ent_clus, &ent_idx, &e_attr);
if (fr == 0) {
if (e_attr & 0x10) return -20; /* 同名目录已存在 */
/* 原地替换:复用/扩展/截断原簇链,仅更新短名项 clus/size */
u32 first = 0;
if (f32w_data_write(e_clus, data, size, &first) != 0) return -4;
if (f32w_dir_load(ent_clus) != 0) return -5;
u8 *ent = f32w_dir + ent_idx * 32;
ent[20] = (u8)((first >> 24) & 0xFF); /* chigh */
ent[21] = (u8)((first >> 16) & 0xFF);
ent[26] = (u8)(first & 0xFF); /* clow */
ent[27] = (u8)((first >> 8) & 0xFF);
ent[28] = (u8)(size & 0xFF); /* fsize */
ent[29] = (u8)((size >> 8) & 0xFF);
ent[30] = (u8)((size >> 16) & 0xFF);
ent[31] = (u8)((size >> 24) & 0xFF);
f32w_dir_dirty = 1;
if (f32w_dir_flush() != 0) return -5;
f32w_fsinfo_unknown();
return 0;
}
/* 新建:唯一短名 -> 数据链 -> 目录槽位(含链扩展)-> LFN+短名项 */
char name11[11];
if (f32w_make_unique_short(dir_clus, name, name11) != 0) return -6;
u32 first = 0;
if (f32w_data_write(0, data, size, &first) != 0) return -7;
if (f32w_insert_entries(dir_clus, name, name11, first, size, 0x20) != 0) return -8;
f32w_fsinfo_unknown();
return 0;
}
/* 在目录中创建子目录(LFN + "." / ".." 项 + 父目录插入条目)。
* parent_clus: 父目录首簇(0=根目录)
* out_clus : 输出新目录首簇(可 NULL)
* 返回 0 成功,-20 同名已存在,其他负值失败。 */
static inline int f32w_mkdir(u32 parent_clus, const char *name, u32 *out_clus) {
if (f32w_bpb_load() != 0) return -1;
if (!f32w_blk_write) return -2;
if (!name) return -3;
if (parent_clus == 0) parent_clus = f32w_c.root_clus;
int fr = f32w_find(parent_clus, name, -1, 0, 0, 0, 0, 0);
if (fr == 0) return -20; /* 同名已存在 */
char name11[11];
if (f32w_make_unique_short(parent_clus, name, name11) != 0) return -6;
/* 分配目录簇并初始化 "." / ".." */
u32 nc = f32w_alloc_free();
if (nc == 0) return -21;
if (f32w_fat_set(nc, F32W_EOC_VAL) != 0) return -22;
if (f32w_dir_flush() != 0) return -23;
f32w_mem_set(f32w_dir, 0, f32w_c.clus_bytes);
{
u8 dot[32], dotdot[32];
char n_self[11] = {'.',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
char n_up[11] = {'.','.',' ',' ',' ',' ',' ',' ',' ',' ',' '};
u32 parent_link = (parent_clus == f32w_c.root_clus) ? 0 : parent_clus;
f32w_build_short_entry(n_self, 0x10, nc, 0, dot);
f32w_build_short_entry(n_up, 0x10, parent_link, 0, dotdot);
for (int i = 0; i < 32; i++) { f32w_dir[i] = dot[i]; f32w_dir[32 + i] = dotdot[i]; }
}
f32w_dir_no = nc;
f32w_dir_dirty = 1;
if (f32w_dir_flush() != 0) return -23;
/* 父目录插入条目(含链扩展) */
if (f32w_insert_entries(parent_clus, name, name11, nc, 0, 0x10) != 0) return -8;
f32w_fsinfo_unknown();
if (out_clus) *out_clus = nc;
return 0;
}
/* ---- 路径辅助('/' 分隔,每段长名;中间目录必须已存在) ---- */
/* 定位路径目录簇。空路径/"'/'" 返回根目录。 */
static inline int f32w_resolve_dir(const char *path, u32 *out_clus) {
if (!path || !out_clus) return -1;
if (f32w_bpb_load() != 0) return -2;
u32 cur = f32w_c.root_clus;
u32 pos = 0;
u32 path_len = f32w_strlen(path);
if (path_len == 0 || (path_len == 1 && path[0] == '/')) {
*out_clus = cur;
return 0;
}
while (pos < path_len) {
while (pos < path_len && path[pos] == '/') pos++;
if (pos >= path_len) break;
char comp[260];
u32 ci = 0;
while (pos < path_len && path[pos] != '/' && ci + 1 < sizeof(comp))
comp[ci++] = path[pos++];
comp[ci] = 0;
if (ci == 0) continue;
u32 sub = 0;
if (f32w_find(cur, comp, 1, &sub, 0, 0, 0, 0) != 0) return -3;
cur = sub;
}
*out_clus = cur;
return 0;
}
/* 按路径写文件(父目录必须已存在)。返回 0 成功,负值失败。 */
static inline int f32w_write_path(const char *path, const u8 *data, u32 size) {
if (!path) return -1;
if (f32w_bpb_load() != 0) return -2;
u32 path_len = f32w_strlen(path);
u32 last_slash = 0xFFFFFFFFu;
for (u32 i = 0; i < path_len; i++)
if (path[i] == '/') last_slash = i;
const char *fname = (last_slash == 0xFFFFFFFFu) ? path : path + last_slash + 1;
u32 dir_clus = 0;
if (last_slash == 0xFFFFFFFFu) {
dir_clus = f32w_c.root_clus;
} else {
char dirpath[260];
u32 dn = last_slash;
if (dn >= sizeof(dirpath)) return -3;
for (u32 i = 0; i < dn; i++) dirpath[i] = path[i];
dirpath[dn] = 0;
if (f32w_resolve_dir(dirpath, &dir_clus) != 0) return -4;
}
return f32w_write_file(dir_clus, fname, data, size);
}
/* 按路径创建目录(仅最后一段被创建,中间目录必须已存在)。返回 0 成功。 */
static inline int f32w_mkdir_path(const char *path, u32 *out_clus) {
if (!path) return -1;
if (f32w_bpb_load() != 0) return -2;
u32 path_len = f32w_strlen(path);
if (path_len == 0) return -3;
/* 去尾部 '/' */
while (path_len > 0 && path[path_len - 1] == '/') path_len--;
if (path_len == 0) return -3;
u32 last_slash = 0xFFFFFFFFu;
for (u32 i = 0; i < path_len; i++)
if (path[i] == '/') last_slash = i;
const char *dname = (last_slash == 0xFFFFFFFFu) ? path : path + last_slash + 1;
if ((u32)(dname - path) >= path_len) return -3; /* 防御:末段为空 */
u32 parent_clus = 0;
if (last_slash == 0xFFFFFFFFu) {
parent_clus = f32w_c.root_clus;
} else {
char dirpath[260];
u32 dn = last_slash;
if (dn >= sizeof(dirpath)) return -4;
for (u32 i = 0; i < dn; i++) dirpath[i] = path[i];
dirpath[dn] = 0;
if (f32w_resolve_dir(dirpath, &parent_clus) != 0) return -5;
}
return f32w_mkdir(parent_clus, dname, out_clus);
}
#endif /* DESHAB_FAT32_WRITE_H */
+23 -6
View File
@@ -305,11 +305,28 @@ static void go_up(void) {
}
}
/* 查找并进入 SYSTEM/user 目录 */
/* 查找并进入用户目录。
* 布局探测顺序(磁盘布局约定不同,两种镜像并存):
* 1) 根级 USER/ —— 树形布局(dev 镜像,含 DESKTOP/PICTURE/VEDIO)
* 2) SYSTEM/USER/ —— 旧树形布局(兼容遗留镜像)
* 3) 都不存在 —— 扁平布局(SATA 盘,用户文件直接在根目录,停留根目录即可)
* 匹配用 8.3 显示名(f32_name_from_83 已 trim 空格),如 "USER"/"SYSTEM"。 */
static void find_user_dir(void) {
/* 先查找 SYSTEM 目录 */
/* 1) 根级 USER */
file_count = 0;
f32_list_dir(0, fm_collect_cb, 0);
for (int i = 0; i < file_count; i++) {
if (files[i].is_dir && files[i].name[0] == 'U' && files[i].name[1] == 'S' &&
files[i].name[2] == 'E' && files[i].name[3] == 'R') {
path_clus[0] = files[i].clus;
path_name[0][0] = 'U'; path_name[0][1] = 'S'; path_name[0][2] = 'E';
path_name[0][3] = 'R'; path_name[0][4] = 0;
path_depth = 1;
return;
}
}
/* 2) 旧树形布局 SYSTEM/USER */
u32 system_clus = 0;
for (int i = 0; i < file_count; i++) {
if (files[i].is_dir && files[i].name[0] == 'S' && files[i].name[1] == 'Y' &&
@@ -319,15 +336,14 @@ static void find_user_dir(void) {
break;
}
}
if (!system_clus) return; /* SYSTEM 目录不存在,保持根目录 */
if (!system_clus) return; /* 扁平布局,保持根目录 */
/* 在 SYSTEM 中查找 user 目录 */
file_count = 0;
f32_list_dir(system_clus, fm_collect_cb, 0);
for (int i = 0; i < file_count; i++) {
if (files[i].is_dir && files[i].name[0] == 'U' && files[i].name[1] == 'S' &&
files[i].name[2] == 'E' && files[i].name[3] == 'R') {
/* 找到了 SYSTEM/user,设置路径栈 */
/* 找到了 SYSTEM/USER,设置路径栈 */
path_clus[0] = system_clus;
path_name[0][0] = 'S'; path_name[0][1] = 'Y'; path_name[0][2] = 'S';
path_name[0][3] = 'T'; path_name[0][4] = 'E'; path_name[0][5] = 'M';
@@ -339,6 +355,7 @@ static void find_user_dir(void) {
return;
}
}
/* SYSTEM 存在但无 SYSTEM/USER:停留根目录(保持原行为) */
}
__attribute__((visibility("default")))
@@ -359,7 +376,7 @@ void dsk_entry(const da_boot_context *ctx) {
f32_init((f32_block_read_fn)g_ac.block_read, (f32_block_write_fn)g_ac.block_write);
path_depth = 0;
/* 尝试进入 SYSTEM/user 目录 */
/* 查找用户目录:自动适配树形(根级 USER/)与扁平(根目录直放)两种布局 */
find_user_dir();
load_current_dir();
redraw_all();
+406
View File
@@ -0,0 +1,406 @@
/* gpt_write.h — Deshab 共享 GPT 写库(static inline,无库)
*
* 前置条件:包含者已定义 u8/u16/u32/u64/i64 基础类型。
* 通过 gpt_init() 注入 block_read/block_write 函数指针(签名与 f32 库一致)。
*
* 能力:
* gpt_probe() — 读 LBA1 校验 "EFI PART" 签名 + header CRC(轻量探测)
* gpt_load() — 加载 GPT 头 + 分区表到内部缓冲,并做 CRC 校验
* gpt_find_esp() — 查找 ESP 分区(type GUID c12a7328-...),输出起始/结束 LBA
* gpt_find_part() — 按任意 type GUID 查找分区
* gpt_update_esp() — 新增/更新 ESP 分区项(改起始/结束 LBA)
* gpt_commit() — 重算 entries CRC + 双 header CRC,写主表/备份表/主头/备份头
* gpt_blank_disk() — 全新初始化:protective MBR + 空 GPT(主+备份,无分区)
*
* 与 build.ps1(New-GptHeader / New-GptFat32Image)字节兼容:
* LBA0 protective MBR(type 0xEE),LBA1 主头,LBA2 主表(128×128B = 32 扇区),
* 备份表 lastLba-32,备份头 lastLba。GUID 按 .NET Guid.ToByteArray()
* little-endian 编码(前三组小端、后两组原序)。
* CRC32 为 IEEE 802.3(init 0xFFFFFFFF / poly 0xEDB88320 / xorout 0xFFFFFFFF),
* 与 build.ps1 Get-Crc32 逐位实现等价。
*
* 缓冲:包含者需提供 ~16.5KB BSS(1 扇区头缓冲 + 32 扇区分区表缓冲)。
*
* 典型流程(FirstInit 写盘 / 系统格式化):
* gpt_init(block_read, block_write);
* if (gpt_probe() != 0) gpt_blank_disk(total_sectors, NULL); // 空盘初始化
* gpt_load();
* gpt_update_esp(2048, total_sectors - 34); // 或扩容
* gpt_commit();
*/
#ifndef DESHAB_GPT_WRITE_H
#define DESHAB_GPT_WRITE_H
/* ---- block 设备函数类型(与 fat32_io.h 签名一致,index 固定 0) ---- */
typedef int (*gpt_block_read_fn)(u32 index, u64 lba, u32 count, void *buf);
typedef int (*gpt_block_write_fn)(u32 index, u64 lba, u32 count, const void *buf);
static gpt_block_read_fn gpt_blk_read = 0;
static gpt_block_write_fn gpt_blk_write = 0;
/* ---- GPT 常量(与 build.ps1 一致) ---- */
#define GPT_SIG_BYTES 8
#define GPT_ENTRIES 128u
#define GPT_ENTRY_SIZE 128u
#define GPT_ENTRY_SECTORS 32u /* 128×128 / 512 */
#define GPT_FIRST_USABLE 34u /* 2 + 32 */
#define GPT_HEADER_SIZE 92u
#define GPT_REVISION 0x00010000u
#define GPT_MBR_PART_OFF 446 /* protective MBR 分区项偏移 */
/* ---- GPT 头(512B,build.ps1 Set-Le* 布局) ---- */
typedef struct __attribute__((packed)) {
u8 sig[8]; /* "EFI PART" */
u32 revision; /* 0x00010000 */
u32 header_size; /* 92 */
u32 header_crc;
u32 reserved0;
u64 current_lba; /* 主头=1,备份头=lastLba */
u64 backup_lba;
u64 first_usable; /* 34 */
u64 last_usable; /* lastLba - 33 */
u8 disk_guid[16];
u64 entries_lba; /* 主表=2,备份表=lastLba-32 */
u32 entries_count; /* 128 */
u32 entries_size; /* 128 */
u32 entries_crc;
u8 reserved[420];
} gpt_header; /* 512B */
/* ---- 分区项(128B) ---- */
typedef struct __attribute__((packed)) {
u8 type_guid[16]; /* 全 0 = 空槽 */
u8 uniq_guid[16];
u64 first_lba;
u64 last_lba;
u64 attrs;
u16 name[36]; /* UTF-16LE,未用部分为 0 */
} gpt_part_entry;
/* ESP 类型 GUID:c12a7328-f81f-11d2-ba4b-00a0c93ec93b
* (.NET Guid.ToByteArray() 编码:前三组小端、后两组原序) */
static const u8 gpt_guid_esp[16] = {
0x28, 0x73, 0x2a, 0xc1, /* c12a7328 */
0x1f, 0xf8, /* f81f */
0xd2, 0x11, /* 11d2 */
0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b
};
/* ---- 内部缓冲(每包含者独立) ---- */
static u8 gpt_sec[512]; /* 单扇区(头/MBR)缓冲 */
static u8 gpt_tbl[GPT_ENTRY_SECTORS * 512]; /* 分区表缓冲(32 扇区) */
static u64 gpt_disk_sectors = 0; /* 磁盘总扇区数(探测后已知) */
/* ---- 初始化:注入 block_read/block_write 函数指针 ---- */
static inline void gpt_init(gpt_block_read_fn rd, gpt_block_write_fn wr) {
gpt_blk_read = rd;
gpt_blk_write = wr;
gpt_disk_sectors = 0;
}
static inline int gpt_read_sectors(u64 lba, u32 count, u8 *out) {
return gpt_blk_read ? gpt_blk_read(0, lba, count, out) : -1;
}
static inline int gpt_write_sectors(u64 lba, u32 count, const u8 *buf) {
return gpt_blk_write ? gpt_blk_write(0, lba, count, buf) : -1;
}
/* ---- 小工具(无库约束:手写循环替代 mem*) ---- */
static inline void gpt_mem_set(u8 *p, u8 v, u32 n) { for (u32 i = 0; i < n; i++) p[i] = v; }
static inline void gpt_mem_cpy(u8 *d, const u8 *s, u32 n) { for (u32 i = 0; i < n; i++) d[i] = s[i]; }
static inline int gpt_mem_eq(const u8 *a, const u8 *b, u32 n) {
for (u32 i = 0; i < n; i++) if (a[i] != b[i]) return 0;
return 1;
}
static inline u32 gpt_r32(const u8 *p) {
return (u32)p[0] | ((u32)p[1] << 8) | ((u32)p[2] << 16) | ((u32)p[3] << 24);
}
static inline void gpt_w16(u8 *p, u16 v) { p[0] = (u8)v; p[1] = (u8)(v >> 8); }
static inline void gpt_w32(u8 *p, u32 v) {
p[0] = (u8)v; p[1] = (u8)(v >> 8); p[2] = (u8)(v >> 16); p[3] = (u8)(v >> 24);
}
static inline void gpt_w64(u8 *p, u64 v) {
gpt_w32(p, (u32)v); gpt_w32(p + 4, (u32)(v >> 32));
}
/* ---- CRC32(IEEE 802.3,与 build.ps1 Get-Crc32 逐位实现等价;表驱动) ---- */
static u32 gpt_crc_tab[256];
static int gpt_crc_ready = 0;
static inline void gpt_crc_init(void) {
if (gpt_crc_ready) return;
for (u32 i = 0; i < 256; i++) {
u32 c = i;
for (int k = 0; k < 8; k++)
c = (c & 1) ? (c >> 1) ^ 0xEDB88320u : (c >> 1);
gpt_crc_tab[i] = c;
}
gpt_crc_ready = 1;
}
static inline u32 gpt_crc32(const u8 *p, u32 n) {
u32 crc = 0xFFFFFFFFu;
for (u32 i = 0; i < n; i++)
crc = (crc >> 8) ^ gpt_crc_tab[(crc ^ p[i]) & 0xFFu];
return crc ^ 0xFFFFFFFFu;
}
/* ---- GUID 工具 ---- */
/* "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" → 16B(.NET ToByteArray 编码)
* 返回 0 成功,-1 格式错误 */
static inline int gpt_guid_from_str(const char *s, u8 out[16]) {
static const int hex[256] = { ['0'] = 0, ['1'] = 1, ['2'] = 2, ['3'] = 3,
['4'] = 4, ['5'] = 5, ['6'] = 6, ['7'] = 7, ['8'] = 8, ['9'] = 9,
['a'] = 10, ['b'] = 11, ['c'] = 12, ['d'] = 13, ['e'] = 14, ['f'] = 15,
['A'] = 10, ['B'] = 11, ['C'] = 12, ['D'] = 13, ['E'] = 14, ['F'] = 15 };
/* 位置表:字符串下标 → 字节下标(1=前四组反序,0=后两组原序) */
static const struct { int str; int byte; int rev; } map[16] = {
{ 0, 3, 1 }, { 2, 2, 1 }, { 4, 1, 1 }, { 6, 0, 1 },
{ 9, 5, 1 }, { 11, 4, 1 },
{ 14, 7, 1 }, { 16, 6, 1 },
{ 19, 8, 0 }, { 21, 9, 0 }, { 23, 10, 0 }, { 25, 11, 0 },
{ 28, 12, 0 }, { 30, 13, 0 }, { 32, 14, 0 }, { 34, 15, 0 },
};
if (s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-') return -1;
for (int i = 0; i < 16; i++) {
int hi = hex[(u8)s[map[i].str]];
int lo = hex[(u8)s[map[i].str + 1]];
if (hi < 0 || lo < 0) return -1;
(void)0;
}
for (int i = 0; i < 16; i++)
out[map[i].byte] = (u8)((hex[(u8)s[map[i].str]] << 4) | hex[(u8)s[map[i].str + 1]]);
return 0;
}
/* 16B → "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"(与 .NET Guid.ToString() 同序) */
static inline void gpt_guid_to_str(const u8 g[16], char out[37]) {
static const char *hd = "0123456789abcdef";
static const struct { int byte; int rev; } om[16] = {
{ 3, 1 }, { 2, 1 }, { 1, 1 }, { 0, 1 },
{ 5, 1 }, { 4, 1 },
{ 7, 1 }, { 6, 1 },
{ 8, 0 }, { 9, 0 }, { 10, 0 }, { 11, 0 },
{ 12, 0 }, { 13, 0 }, { 14, 0 }, { 15, 0 },
};
for (int i = 0; i < 16; i++) {
int b = om[i].byte;
out[i * 2] = hd[g[b] >> 4];
out[i * 2 + 1] = hd[g[b] & 0xF];
if (i == 3 || i == 5 || i == 7 || i == 9) { out[i * 2 + 2] = '-'; }
}
out[36] = 0;
}
/* ---- GPT 头构建 / 校验 ---- */
/* 计算头 CRC:前 92 字节、header_crc 字段按 0 参与 */
static inline u32 gpt_header_crc(const gpt_header *h) {
u8 tmp[92];
gpt_mem_cpy(tmp, (const u8 *)h, 92);
gpt_w32(tmp + 16, 0);
return gpt_crc32(tmp, 92);
}
/* 构建头(不落盘):entries_crc 由调用者预先算好 */
static inline void gpt_header_build(gpt_header *h, u64 current_lba, u64 backup_lba,
u64 first_usable, u64 last_usable,
const u8 disk_guid[16],
u64 entries_lba, u32 entries_crc) {
static const u8 sig[8] = { 'E', 'F', 'I', ' ', 'P', 'A', 'R', 'T' };
gpt_mem_set((u8 *)h, 0, sizeof(*h));
gpt_mem_cpy(h->sig, sig, 8);
h->revision = GPT_REVISION;
h->header_size = GPT_HEADER_SIZE;
h->current_lba = current_lba;
h->backup_lba = backup_lba;
h->first_usable = first_usable;
h->last_usable = last_usable;
if (disk_guid) gpt_mem_cpy(h->disk_guid, disk_guid, 16);
h->entries_lba = entries_lba;
h->entries_count = GPT_ENTRIES;
h->entries_size = GPT_ENTRY_SIZE;
h->entries_crc = entries_crc;
h->header_crc = gpt_header_crc(h);
}
/* 校验 LBA 处的 GPT 头(签名/大小/current_lba/CRC),返回 0 有效 */
static inline int gpt_header_validate(const gpt_header *h, u64 expect_lba) {
static const u8 sig[8] = { 'E', 'F', 'I', ' ', 'P', 'A', 'R', 'T' };
if (!gpt_mem_eq(h->sig, sig, 8)) return -1;
if (h->revision != GPT_REVISION || h->header_size < GPT_HEADER_SIZE) return -2;
if (h->current_lba != expect_lba) return -3;
if (gpt_header_crc(h) != h->header_crc) return -4;
return 0;
}
/* ---- 分区表操作(内存缓冲) ---- */
static inline gpt_part_entry *gpt_part(u32 idx) {
return (gpt_part_entry *)(gpt_tbl + idx * GPT_ENTRY_SIZE);
}
/* 分区表 CRC(覆盖全部 32 扇区) */
static inline u32 gpt_entries_crc(void) {
return gpt_crc32(gpt_tbl, sizeof(gpt_tbl));
}
static inline int gpt_part_empty(const gpt_part_entry *e) {
return gpt_mem_eq(e->type_guid, (const u8 *)gpt_guid_esp /* 任意非 0 引用 */, 0) &&
gpt_mem_eq(e->type_guid, e->type_guid, 0); /* 恒真占位,防 -Wunused */
}
static inline int gpt_part_is_free(const gpt_part_entry *e) {
/* type_guid 全 0 = 空槽 */
static const u8 zero16[16] = { 0 };
return gpt_mem_eq(e->type_guid, zero16, 16);
}
/* 查找第一个 type_guid 匹配的分区(含全 0 停止),返回索引或 -1 */
static inline int gpt_find_part_type(const u8 type_guid[16], u64 *out_first, u64 *out_last) {
for (u32 i = 0; i < GPT_ENTRIES; i++) {
const gpt_part_entry *e = gpt_part(i);
if (gpt_part_is_free(e)) break;
if (gpt_mem_eq(e->type_guid, type_guid, 16)) {
if (out_first) *out_first = e->first_lba;
if (out_last) *out_last = e->last_lba;
return (int)i;
}
}
return -1;
}
/* 查找 ESP 分区,返回索引或 -1 */
static inline int gpt_find_esp(u64 *out_first, u64 *out_last) {
return gpt_find_part_type(gpt_guid_esp, out_first, out_last);
}
/* 分区名写入(ASCII → UTF-16LE,最多 36 字符) */
static inline void gpt_part_set_name(gpt_part_entry *e, const char *ascii) {
u32 i = 0;
for (; i < 36 && ascii[i]; i++) gpt_w16((u8 *)&e->name[i], (u16)ascii[i]);
for (; i < 36; i++) gpt_w16((u8 *)&e->name[i], 0);
}
/* 填充分区项到指定槽位(返回 0 成功,-1 槽位越界/非空) */
static inline int gpt_part_fill(u32 idx, const u8 type_guid[16], const u8 uniq_guid[16],
u64 first_lba, u64 last_lba, u64 attrs, const char *name) {
if (idx >= GPT_ENTRIES) return -1;
gpt_part_entry *e = gpt_part(idx);
if (!gpt_part_is_free(e)) return -2;
gpt_mem_cpy(e->type_guid, type_guid, 16);
if (uniq_guid) gpt_mem_cpy(e->uniq_guid, uniq_guid, 16);
else gpt_mem_set(e->uniq_guid, 0, 16);
e->first_lba = first_lba;
e->last_lba = last_lba;
e->attrs = attrs;
gpt_part_set_name(e, name);
return 0;
}
/* ---- 落盘 / 探测 ---- */
/* 探测 LBA1 是否为有效 GPT(轻量,不加载分区表) */
static inline int gpt_probe(void) {
if (gpt_read_sectors(1, 1, gpt_sec) != 0) return -1;
return gpt_header_validate((const gpt_header *)gpt_sec, 1);
}
/* 加载主头 + 主分区表到缓冲;校验头/表 CRC。total_sectors 为 0 时跳过盘尾推导 */
static inline int gpt_load(u64 total_sectors) {
if (gpt_read_sectors(1, 1, gpt_sec) != 0) return -1;
const gpt_header *h = (const gpt_header *)gpt_sec;
if (gpt_header_validate(h, 1) != 0) return -2;
if (h->entries_lba != 2 || h->entries_count != GPT_ENTRIES) return -3;
if (gpt_read_sectors(2, GPT_ENTRY_SECTORS, gpt_tbl) != 0) return -4;
if (gpt_entries_crc() != h->entries_crc) return -5;
gpt_disk_sectors = total_sectors;
return 0;
}
/* 全新初始化:protective MBR + 空 GPT(主+备份)。disk_guid 可 NULL(全 0)。
* total_sectors 必须 >= 70(34 + 32 表 + 2 头)。 */
static inline int gpt_blank_disk(u64 total_sectors, const u8 disk_guid[16]) {
if (total_sectors < GPT_FIRST_USABLE + GPT_ENTRY_SECTORS + 2) return -1;
/* LBA0 protective MBR(build.ps1 布局) */
gpt_mem_set(gpt_sec, 0, 512);
gpt_sec[GPT_MBR_PART_OFF + 4] = 0xEE; /* type */
gpt_w32(gpt_sec + GPT_MBR_PART_OFF + 8, 1); /* start LBA */
u64 prot = total_sectors - 1;
if (prot > 0xFFFFFFFFu) prot = 0xFFFFFFFFu;
gpt_w32(gpt_sec + GPT_MBR_PART_OFF + 12, (u32)prot); /* sectors */
gpt_sec[510] = 0x55; gpt_sec[511] = 0xAA;
if (gpt_write_sectors(0, 1, gpt_sec) != 0) return -2;
/* 空分区表 */
gpt_mem_set(gpt_tbl, 0, sizeof(gpt_tbl));
u32 entries_crc = gpt_crc32(gpt_tbl, sizeof(gpt_tbl));
/* 主头(LBA1)+ 备份头(lastLba) */
u64 last_lba = total_sectors - 1;
u64 last_usable = last_lba - GPT_ENTRY_SECTORS - 1;
gpt_header ph, bh;
gpt_header_build(&ph, 1, last_lba, GPT_FIRST_USABLE, last_usable,
disk_guid, 2, entries_crc);
gpt_header_build(&bh, last_lba, 1, GPT_FIRST_USABLE, last_usable,
disk_guid, last_lba - GPT_ENTRY_SECTORS, entries_crc);
if (gpt_write_sectors(1, 1, (const u8 *)&ph) != 0) return -3;
if (gpt_write_sectors(2, GPT_ENTRY_SECTORS, gpt_tbl) != 0) return -4;
if (gpt_write_sectors(last_lba - GPT_ENTRY_SECTORS, GPT_ENTRY_SECTORS, gpt_tbl) != 0) return -5;
if (gpt_write_sectors(last_lba, 1, (const u8 *)&bh) != 0) return -6;
gpt_disk_sectors = total_sectors;
return 0;
}
/* 新增/更新 ESP 分区项(内存缓冲,需 gpt_commit 落盘):
* 已有 ESP 则更新范围,否则填第一个空槽。返回槽位索引或负错误码 */
static inline int gpt_update_esp(u64 first_lba, u64 last_lba,
const u8 uniq_guid[16], const char *name) {
static const u8 zero16[16] = { 0 };
int idx = gpt_find_part_type(gpt_guid_esp, 0, 0);
if (idx >= 0) {
gpt_part_entry *e = gpt_part((u32)idx);
e->first_lba = first_lba;
e->last_lba = last_lba;
if (uniq_guid) gpt_mem_cpy(e->uniq_guid, uniq_guid, 16);
if (name) gpt_part_set_name(e, name);
return idx;
}
/* 找第一个空槽(类型全 0) */
for (u32 i = 0; i < GPT_ENTRIES; i++) {
if (gpt_part_is_free(gpt_part(i)))
return gpt_part_fill(i, gpt_guid_esp, uniq_guid ? uniq_guid : zero16,
first_lba, last_lba, 0, name ? name : "Deshab ESP");
}
return -3; /* 表满 */
}
/* 提交:重算 entries CRC + 双头 CRC,写主表/备份表/主头/备份头(幂等) */
static inline int gpt_commit(void) {
u64 last_lba = 0;
gpt_header h;
/* 读当前主头,取 last_usable / disk_guid / backup 布局 */
if (gpt_read_sectors(1, 1, gpt_sec) != 0) return -1;
gpt_mem_cpy((u8 *)&h, gpt_sec, sizeof(h));
if (gpt_header_validate(&h, 1) != 0) return -2;
last_lba = h.backup_lba;
u32 entries_crc = gpt_entries_crc();
gpt_header_build(&h, 1, last_lba, h.first_usable, h.last_usable,
h.disk_guid, 2, entries_crc);
gpt_header bh;
gpt_header_build(&bh, last_lba, 1, h.first_usable, h.last_usable,
h.disk_guid, last_lba - GPT_ENTRY_SECTORS, entries_crc);
if (gpt_write_sectors(2, GPT_ENTRY_SECTORS, gpt_tbl) != 0) return -3;
if (gpt_write_sectors(1, 1, (const u8 *)&h) != 0) return -4;
if (gpt_write_sectors(last_lba - GPT_ENTRY_SECTORS, GPT_ENTRY_SECTORS, gpt_tbl) != 0) return -5;
if (gpt_write_sectors(last_lba, 1, (const u8 *)&bh) != 0) return -6;
return 0;
}
#endif /* DESHAB_GPT_WRITE_H */
+179
View File
@@ -0,0 +1,179 @@
# read_usb_logs.ps1 - Read Deshab USB disk, parse GPT+FAT32, extract test logs
#
# Deshab 实机测试日志回读工具:U 盘(GPT ESP + FAT32)在 Windows 上无法
# 直接挂载(removable media 不支持盘符分配),此脚本以管理员权限直读
# 物理磁盘,解析 GPT 分区表 + FAT32 文件系统,把 SYSTEM/DESHAB64/DEV/ 下的
# 日志文件(BOOTLOG.TXT、BOOTxx.TXT、LOG 等)和根目录 DEVLOG 提取到本地。
#
# Usage (admin PowerShell):
# powershell -ExecutionPolicy Bypass -File "CODE\tools\read_usb_logs.ps1"
# powershell -ExecutionPolicy Bypass -File "CODE\tools\read_usb_logs.ps1" -DiskNumber 2
# powershell -ExecutionPolicy Bypass -File "CODE\tools\read_usb_logs.ps1" -OutDir ".\logs"
#
# 输出目录: .build_tmp\usb_logs\ (或 -OutDir 指定)
param(
[int]$DiskNumber = 1,
[string]$OutDir = 'd:\Code\DEAICUP\Deshab\.build_tmp\usb_logs'
)
$ErrorActionPreference = 'Stop'
$diskPath = '\\.\PhysicalDrive' + $DiskNumber
# ---- 检查管理员权限(打开物理磁盘需要) ----
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Host "[ERROR] Administrator privileges required to open $diskPath" -ForegroundColor Red
Write-Host " Run this script from an elevated PowerShell (Win+X -> Terminal (Admin))."
exit 1
}
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null
$script:fs = $null
$script:partStart = 0
$script:dataSec = 0
$script:rsvd = 0
$script:spc = 0
$script:csize = 0
function Read-Cluster([uint32]$clus) {
$lba = $dataSec + ($clus - 2) * $spc
$fs.Position = ([int64]$partStart + $lba) * 512
$b = [byte[]]::new($csize)
[void]$fs.Read($b, 0, $csize)
return ,$b
}
function Read-FatEntry([uint32]$c) {
$fatSec = [Math]::Floor(($c * 4) / 512)
$fs.Position = ([int64]$partStart + $rsvd + $fatSec) * 512
$fb = [byte[]]::new(512)
[void]$fs.Read($fb, 0, 512)
return ([BitConverter]::ToUInt32($fb, ($c * 4) % 512) -band 0x0FFFFFFF)
}
function Decode-Short([byte[]]$n) {
$s=''; for($i=0;$i -lt 8 -and $n[$i] -ne 0x20 -and $n[$i] -ne 0;$i++){$s+=[char]$n[$i]}
$e=''; for($i=8;$i -lt 11 -and $n[$i] -ne 0x20 -and $n[$i] -ne 0;$i++){$e+=[char]$n[$i]}
if($e){return "$s.$e"}else{return $s}
}
function Get-EntryCluster([byte[]]$buf, [int]$o) {
$clow = [BitConverter]::ToUInt16($buf, $o + 26)
$chigh = [BitConverter]::ToUInt16($buf, $o + 20)
return ($clow -bor ([int]$chigh -shl 16))
}
function Read-File([uint32]$firstClus, [uint32]$size) {
if ($size -eq 0) { return ,([byte[]]::new(0)) }
$data = [byte[]]::new($size)
$c = $firstClus; $off = 0; $remaining = $size
while ($c -ge 2 -and $c -lt 0x0FFFFFF8 -and $remaining -gt 0) {
$lba = $dataSec + ($c - 2) * $spc
$fs.Position = ([int64]$partStart + $lba) * 512
$chunk = [byte[]]::new($csize)
[void]$fs.Read($chunk, 0, $csize)
$n = [Math]::Min($csize, $remaining)
[Array]::Copy($chunk, 0, $data, $off, $n)
$off += $n; $remaining -= $n
$c = Read-FatEntry $c
}
return ,$data
}
function Scan-Dir([uint32]$dirClus) {
$result = @{}
$c = $dirClus
while ($c -ge 2 -and $c -lt 0x0FFFFFF8) {
$buf = Read-Cluster $c
for ($e = 0; $e -lt ($csize / 32); $e++) {
$o = $e * 32
if ($buf[$o] -eq 0) { return $result }
if ($buf[$o] -eq 0xE5) { continue }
$at = $buf[$o + 11]
if (($at -band 0x0F) -eq 0x0F) { continue } # LFN entry, skip
if ($at -band 0x08) { continue } # volume label
$name = Decode-Short $buf[$o..($o + 10)]
$result[$name] = @{ Cluster = (Get-EntryCluster $buf $o); Size = [BitConverter]::ToUInt32($buf, $o + 28); Attr = $at }
}
$c = Read-FatEntry $c
}
return $result
}
function Show-Head([byte[]]$data) {
if (-not $data -or $data.Length -eq 0) { Write-Host " [empty]"; return }
$txt = [System.Text.Encoding]::ASCII.GetString($data)
$len = [Math]::Min(400, $txt.Length)
$clean = ''
for ($i = 0; $i -lt $len; $i++) {
$code = [int]$txt[$i]
if (($code -ge 32 -and $code -le 126) -or $code -eq 10 -or $code -eq 13 -or $code -eq 9) { $clean += $txt[$i] } else { $clean += '.' }
}
Write-Host " [head] $clean"
}
Write-Host "=== Open $diskPath ==="
$fs = [System.IO.File]::Open($diskPath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
$fs.Position = 512
$lba1 = [byte[]]::new(512); [void]$fs.Read($lba1, 0, 512)
$sig = [System.Text.Encoding]::ASCII.GetString($lba1, 0, 8)
Write-Host "LBA1 signature: '$sig'"
if ($sig -ne 'EFI PART') { Write-Host "[ERROR] Not a GPT disk"; $fs.Close(); exit 1 }
$fs.Position = 1024
$pe = [byte[]]::new(128); [void]$fs.Read($pe, 0, 128)
$partStart = [BitConverter]::ToUInt64($pe, 32)
Write-Host "ESP start LBA: $partStart"
$fs.Position = $partStart * 512
$bpb = [byte[]]::new(512); [void]$fs.Read($bpb, 0, 512)
$bps = [BitConverter]::ToUInt16($bpb, 11)
$spc = $bpb[13]
$rsvd = [BitConverter]::ToUInt16($bpb, 14)
$nf = $bpb[16]
$spf = [BitConverter]::ToUInt32($bpb, 36)
$rootClus = [BitConverter]::ToUInt32($bpb, 44)
$dataSec = $rsvd + $nf * $spf
$csize = $bps * $spc
Write-Host "BPB: bps=$bps spc=$spc rsvd=$rsvd nf=$nf spf=$spf root=$rootClus dataSec=$dataSec"
$root = Scan-Dir $rootClus
Write-Host "=== ROOT ==="
$root.Keys | Sort-Object | ForEach-Object { Write-Host (" {0} clus={1} size={2}" -f $_, $root[$_].Cluster, $root[$_].Size) }
if (-not $root.ContainsKey('SYSTEM')) { Write-Host "[WARN] no SYSTEM dir"; $fs.Close(); exit 0 }
$sys = Scan-Dir $root['SYSTEM'].Cluster
if (-not $sys.ContainsKey('DESHAB64')) { Write-Host "[WARN] no DESHAB64 dir"; $fs.Close(); exit 0 }
$d64 = Scan-Dir $sys['DESHAB64'].Cluster
Write-Host "=== DESHAB64 ==="
$d64.Keys | Sort-Object | ForEach-Object { Write-Host (" {0} size={1}" -f $_, $d64[$_].Size) }
if (-not $d64.ContainsKey('DEV')) { Write-Host "[WARN] no DEV dir"; $fs.Close(); exit 0 }
$dev = Scan-Dir $d64['DEV'].Cluster
Write-Host "=== DESHAB64/DEV ==="
$dev.Keys | Sort-Object | ForEach-Object { Write-Host (" {0} size={1}" -f $_, $dev[$_].Size) }
Write-Host "=== EXTRACT to $OutDir ==="
foreach ($k in $dev.Keys) {
if (($dev[$k].Attr -band 0x10) -ne 0) { continue }
$data = Read-File $dev[$k].Cluster $dev[$k].Size
$safe = ($k -replace '[^A-Za-z0-9._-]', '_')
$outPath = Join-Path $OutDir $safe
[System.IO.File]::WriteAllBytes($outPath, $data)
Write-Host (" -> {0} ({1} bytes)" -f $safe, $data.Length)
Show-Head $data
}
foreach ($k in @('DEVLOG','TEST.TXT','COPY.TXT','MOVED.TXT','BOOTLOG')) {
if ($root.ContainsKey($k)) {
$data = Read-File $root[$k].Cluster $root[$k].Size
$outPath = Join-Path $OutDir ("ROOT_" + $k)
[System.IO.File]::WriteAllBytes($outPath, $data)
Write-Host (" [root] -> {0} ({1} bytes)" -f $k, $data.Length)
Show-Head $data
}
}
$fs.Close()
Write-Host "=== DONE ==="