An enclave non-aware dynamic kernel resource scheduling method based on a RISC-V chip

CN122332131BActive Publication Date: 2026-10-23XI AN JIAOTONG UNIV +1
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202610716948.X
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2026-05-22
Publication Date
2026-10-23
Estimated Expiration
2046-05-22

AI Technical Summary

Technical Problem

但现有RISC-V TEE仍受限于静态资源分配模式,难以适配于原生场景下动态变化的负载需求,亟须突破资源配置固化的瓶颈

Benefits of technology

在本说明书提供的一种基于RISC-V芯片的Enclave无感知动态内核资源调度方法中,以安全监视器作为可信根构建Enclave,并在工作Enclave与安全调度器Enclave之间建立可信通道,安全调度器融合软硬指标负载数据,采用指数加权移动平均模型与迟滞区间算法生成扩缩容决策指令,并通过五阶段状态机实现物理核心的安全移交,用户态调度器通过动态Worker池管理与无锁工作窃取算法,自动实现新增核心的任务均衡与负载接管。其中,安全调度器+工作 Enclave的独立决策架构中,安全调度器作为独立 Enclave 运行,结合HPM 安全虚拟化与 E2E 可信通道,Enclave可根据实时负载按需占用核心,实现了Enclave内核数量的动态、安全、无感知扩缩容,显著提升众核处理器利用率,同时保障服务连续性与系统安全性。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122332131B_ABST
    Figure CN122332131B_ABST
Patent Text Reader

Abstract

The application discloses an Enclave non-perception dynamic kernel resource scheduling method based on a RISC-V chip and relates to the technical field of RISC-V trusted execution environment and resource dynamic scheduling. Based on the RISC-V architecture, a security monitor (SM) is deployed as a trusted root in the M-mode; an untrusted host operating system is run in the S-mode; a working Enclave and a security scheduler Enclave are run in the U-mode; the SM provides hardware indexes for the Enclave by monitoring and intercepting the access to a performance counter through hardware performance; a Runtime of the working Enclave collects soft indexes such as a task queue and reports the soft indexes on an E2E trusted channel; the security scheduler fuses double-dimension load calculation and comprehensive saturation and makes expansion and contraction decisions; the SM performs context cleaning and physical memory protection configuration switching according to a five-stage state machine and realizes safe handover; and the Runtime realizes the automatic balancing of new core tasks through dynamic working pool management and a lock-free work stealing algorithm. The application realizes the dynamic, safe and non-perception expansion and contraction of the number of Enclave kernels and significantly improves the utilization rate of many-core processors.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of RISC-V trusted execution environment and dynamic resource scheduling technology, and in particular to an Enclave-based dynamic kernel resource scheduling method based on RISC-V chips. Background Technology

[0002] In the computer science field, an enclave refers to a secure, isolated container within a Trusted Execution Environment (TEE) based on the RISC-V architecture. It carries user business logic, enabling secure code execution and data processing within it, while preventing untrusted operating systems (Host OS) or other malicious entities from accessing its memory and execution state.

[0003] With the deepening of digital transformation, cloud computing has become the core infrastructure of the global digital economy. Its computing paradigm is evolving towards high-density, highly elastic serverless computing, and more and more sensitive applications are choosing to migrate to the cloud to enjoy the advantages of elastic computing power and cost. However, the security protection of "data in use" throughout the data lifecycle has long been a weakness. Threats such as super administrator privileges of cloud service providers, operating system vulnerabilities, and virtualization escape attacks pose risks of leakage or tampering to sensitive data in the cloud. To fill this security gap, confidential computing has emerged. Its core is to build a protected enclave memory area through a trusted execution environment (TEE) with hardware and software collaboration, ensuring the confidentiality and integrity of code and data during execution. Even if the operating system or hypervisor is compromised, the resources inside the enclave cannot be accessed externally.

[0004] In recent years, the open-source RISC-V architecture has rapidly gained popularity in academia and industry due to its modularity, scalability, and lack of proprietary technology lock-in, giving rise to classic lightweight TEE solutions such as Keystone and Penglai. Meanwhile, RISC-V processors are evolving towards many-core architectures, with modern RISC-V processors capable of integrating 64 or even 128 cores or more, widely used in high-performance computing and data center scenarios. To adapt to many-core environments, mainstream RISC-V TEE solutions have continuously optimized multi-threading support: Keystone uses a "decentralization" mechanism to transfer thread management responsibilities to the Enclave's internal runtime, reducing the size of the Trusted Computing Base (TCB) and lowering mode switching overhead; Penglai introduces page table-level fine-grained isolation and native multi-threading support, enabling a single Enclave to bind multiple physical cores for parallel operation, improving throughput for data-intensive tasks. However, existing RISC-V TEEs are still limited by static resource allocation models, making it difficult to adapt to dynamically changing load demands in native scenarios, and urgently need to overcome the bottleneck of fixed resource configuration. Summary of the Invention

[0005] Therefore, it is necessary to provide an Enclave-based dynamic kernel resource scheduling method that is unaware of the above-mentioned technical problems.

[0006] The following technical solution is adopted in this specification: As a trusted root, the security monitor responds to the request to create an Enclave by constructing a working Enclave and a security scheduler Enclave through integrity metrics and PMP configuration, and establishes a trusted channel based on shared memory between the working Enclave and the security scheduler Enclave. The working Enclave virtualizes the Hardware Performance Monitor (HPM) counter through the security monitor to obtain hard indicator data representing the saturation of physical resources, and collects soft indicator data on the task scheduling path through the Runtime; and transmits the hard indicator data and the soft indicator data to the security scheduler Enclave through the trusted channel. The security scheduler Enclave analyzes the received hard and soft indicator data using a preset algorithm to generate scaling decision instructions that include the physical core identifier to be transferred and the target working Enclave identifier. In response to the scaling decision command, the security monitor invokes the physical core hot-swap state machine, executes the five-stage state machine transition in sequence, and transfers the core security corresponding to the physical core identifier to the target working Enclave. The target work Enclave starts its internal user-space scheduler and, through dynamic worker pool management and lock-free work theft mechanism, achieves task takeover and load balancing scheduling for the newly added core.

[0007] Furthermore, the method is applied to a hierarchical RISC-V processor system, the hierarchical architecture comprising: The hardware layer includes a RISC-V multi-core processor, a physical memory protection register set, and a hardware performance monitor counter. The machine mode layer is used to run the security monitor; the security monitor serves as the trusted computing base of the system, has exclusive read and write access to the PMP register, and is used to process all privileged instructions involving changes to security boundaries. The regulator mode layer is used to run the host operating system and manage all system resources except for Enclave private memory, including the scheduling of idle physical cores and the allocation of insecure memory. The user mode layer and the supervisor mode layer are used to run the working Enclave that carries user business logic and the security scheduler Enclave that is responsible for resource monitoring and decision-making. The working Enclave and the security scheduler Enclave interact through a trusted channel based on shared memory. The runtime of the working Enclave periodically writes the de-identified load data into the trusted channel. The security scheduler reads the load data and makes scaling decisions based on the built-in algorithm. It then intervenes through the security monitor to perform the reallocation of physical cores.

[0008] Furthermore, the construction of the working Enclave includes: Based on the memory area required by the Enclave, a security monitor is used to perform security checks on the Runtime environment and user programs loaded into memory. An Enclave unique identity metric is generated by calculating the cryptographic hash value of the initial memory content; and this identity metric value serves as the trust foundation for remote authentication to ensure that the code and data have not been tampered with before startup. The security monitor constructs a hardware-enforced memory isolation boundary by programming the PMP register; and grants the Enclave the highest access rights to the private physical memory region, while depriving the host operating system and other Enclaves of access, thus completing the construction of the working Enclave.

[0009] Furthermore, the construction of the trusted channel specifically includes: The host operating system allocates a physically contiguous memory region as a shared buffer and registers it with the security monitor. After verifying that the memory region does not overlap with the existing Enclave memory, the security monitor configures the PMP register to revoke read, write and execute permissions for the memory region from programs other than the two communicating parties. The security monitor modifies the page table structure of the working Enclave and the security scheduler Enclave, maps the memory region to the virtual address space of the working Enclave and the security scheduler Enclave, and forces the user-mode access permission bit to be enabled and the global bit to be disabled in the page table entries, thereby completing the construction of the trusted channel.

[0010] Furthermore, the soft metrics data include task queue backlog length, thread spin wait time, and lock contention frequency data.

[0011] Furthermore, the step of analyzing load data through a preset algorithm to generate scaling up / down decision instructions specifically includes: The safety scheduler assigns positive weights to instruction throughput and negative weights to spin wait time based on the received hard and soft performance data through a polynomial fusion function, in order to eliminate the interference of invalid busy on load assessment and obtain the comprehensive computational saturation. The comprehensive saturation calculation is input into the exponentially weighted moving average model, which automatically adjusts according to the rapid changes in load by setting a dynamic decay factor to generate a smoothed load trend value. When the smoothed load value continuously exceeds the preset expansion threshold and the time interval since the last operation exceeds the preset cooling period, an expansion command is triggered; when the load value is lower than the preset reduction threshold and the cooling period requirement is met, a reduction command is triggered.

[0012] Furthermore, the five-stage state machine includes the host-owned state, the lending state, the cleaning state, the enclave-active state, and the return state.

[0013] Furthermore, the step of executing a five-stage state machine transition via a physical core hot-swappable state machine to securely transfer the core to the target working enclave includes: Upon receiving the expansion decision instruction, the selected idle core is marked as Lending in the scheduler, the distribution of ordinary tasks to it is stopped, and a core handover call request is initiated to the security monitor. The security monitor receives the core handover call request, sets the core state to Monitor-Sanitizing, and clears or resets all general-purpose registers, floating-point registers, and control status registers to their safe default values. Execute the sfence.vma instruction to refresh the TLB of the core, completely clearing the residual address mapping; and after the clearing is completed, modify the PMP configuration to switch the execution permission of the core from supervisor mode to the memory isolation domain where the target working Enclave is located, and update the state of the core to Enclave-Active; The program counter is set to point to the hot-plug entry address of the Enclave Runtime, and the mret instruction is executed to cause the core to jump to the target working Enclave.

[0014] Furthermore, the user-space scheduler within the target working enclave includes: The dynamic worker pool management module is used to maintain a concurrent and safe worker linked list, and supports dynamic registration and deregistration of physical cores; The lock-free task stealing module allows each worker core to maintain a local double-ended queue. Idle cores can steal tasks from the tail of other busy cores' queues via atomic instructions.

[0015] The above-mentioned technical solutions adopted in this specification can achieve the following beneficial effects: This specification provides a method for dynamic kernel resource scheduling of Enclaves based on RISC-V chips, where the Enclave is constructed using a security monitor as the root of trust. A trusted channel is established between the working Enclave and the security scheduler Enclave. The security scheduler integrates hardware and software load data, uses an exponentially weighted moving average model and a hysteresis interval algorithm to generate scaling decisions, and implements secure handover of physical cores through a five-stage state machine. The user-space scheduler automatically balances tasks and takes over loads for newly added cores through dynamic worker pool management and a lock-free work-stealing algorithm. In the independent decision-making architecture of the security scheduler and working Enclaves, the security scheduler runs as an independent Enclave. Combined with HPM secure virtualization and an E2E trusted channel, the Enclave can occupy cores on demand according to real-time load, achieving dynamic, secure, and seamless scaling of the number of Enclave cores. This significantly improves the utilization of many-core processors while ensuring service continuity and system security.

[0016] Furthermore, through trusted monitoring, independent decision-making, and secure collaboration mechanisms, it can effectively resist spoofed load, scheduling attacks, and side-channel attacks, ensuring the integrity and confidentiality of Enclave execution. Attached Figure Description

[0017] The accompanying drawings, which are included to provide a further understanding of this application and form part of this application, illustrate exemplary embodiments and are used to explain this application, but do not constitute an undue limitation of this application. In the drawings:

[0018] Figure 1 This document provides a flowchart illustrating an Enclave-based dynamic kernel resource scheduling method for RISC-V chips. Figure 2 This is a schematic diagram illustrating the PMP principle provided in this manual; Figure 3 This is a schematic diagram of the kernel security expansion process provided in this manual; Figure 4 This is a schematic diagram of unlocked theft provided in this manual. Detailed Implementation

[0019] To make the objectives, technical solutions, and advantages of this specification clearer, the technical solutions of this application will be clearly and completely described below in conjunction with specific embodiments and corresponding drawings. Obviously, the described embodiments are only a part of the embodiments of this application, and not all of them. All other embodiments obtained by those skilled in the art based on the embodiments in this specification without creative effort are within the scope of protection of this application.

[0020] Existing related technologies mainly focus on five areas: RISC-V TEE resource allocation, load monitoring, scaling up / down decision-making, coordination protocols, and in-enclave scheduling.

[0021] Regarding static resource allocation, solutions like Keystone require the Enclave to preset the memory size and number of CPU cores before startup, and then lock the resource boundaries through remote proof after startup, maintaining a 1:1 static binding between cores and threads. Although Penglai supports multi-core binding, the number of cores still needs to be configured during the initialization phase and cannot be dynamically adjusted at runtime, resulting in low resource utilization.

[0022] In the field of trusted load monitoring, there are two main types of solutions: one is intrusive monitoring based on LibOS / agents. For example, SCONE reports system call activity to the host OS through a shared queue inside the Enclave, and SE-Lambda deploys a monitoring module in the SGX Enclave to intercept system calls to collect execution time and memory allocation. However, these solutions require modification of the Enclave runtime, resulting in poor compatibility and high implementation costs. The other type is hardware-assisted monitoring. Keystone intercepts hardware performance counter (HPM) access through the M-mode security monitor (SM), providing only coarse-grained load data to the host OS, which cannot support accurate decision-making within the Enclave. Although the solution proposed by Domingos et al. achieves support for RISC-V HPM access to the operating system, it does not consider the TEE security isolation requirements. Untrusted OSs can use this mechanism to spy on the Enclave microarchitecture state, leading to the risk of side-channel attacks.

[0023] Regarding dynamic scaling decisions, Kubernetes Vertical Pod Autoscalers (VPAs) in cloud-native environments recommend configurations based on historical resource usage data, but adjusting resources requires restarting the Pod, leading to service interruptions. The DITTO solution in the TEE domain employs a threshold-triggered scaling strategy for confidential virtual machines, controlling core wake-up and suspension via high / low watermarks, but it is not adapted to Enclave scenarios and relies on Hypervisor scheduling, posing a security risk of scheduling algorithm manipulation. While proactive decision-making schemes based on Deep Reinforcement Learning (DRL) possess strong generalization capabilities, they face challenges such as cold start, slow training convergence, and poor interpretability, making them difficult to deploy in security-critical systems.

[0024] Regarding seamless collaborative protocols, existing solutions mostly achieve resource transfer through synchronous system calls (such as SBI calls), resulting in high interaction overhead and response latency. Inter-enclave communication relies on a "copy + encryption" model, involving multiple copying and complex encryption / decryption operations during data transmission, leading to low efficiency. In terms of scheduling within enclaves, Occlum implements M:N thread scheduling within SGXEnclaves, but the number of physical cores is statically fixed, making it unable to adapt to runtime resource changes. ZygOS uses a work-stealing algorithm to optimize multi-core load balancing, but it is not adapted to TEE security isolation environments and cannot support dynamic hot-swapping of cores.

[0025] The existing technology has five major flaws: First, resource allocation is static. After the Enclave starts, the resource boundaries are fixed. Users need to reserve cores according to peak load, which leads to a large number of CPU cores being idle and wasted under low load. Under high load, it is impossible to dynamically expand to cope with sudden traffic, making it difficult to adapt to highly elastic scenarios such as Serverless. Second, load monitoring has security risks or is highly intrusive. Monitoring solutions that rely on untrusted host OS are vulnerable to "false intelligence attacks." The host OS can forge load data to induce incorrect decisions, while intrusive monitoring solutions require modification of the Enclave runtime or application code, resulting in poor compatibility. Third, scaling up and down decisions are lagging and lack security. Traditional threshold triggering algorithms are easily affected by traffic spikes, leading to resource jitter. DRL-based solutions face implementation obstacles, and the decision-making logic often runs in an untrusted OS or Hypervisor layer, making them susceptible to manipulation that could trigger starvation attacks or side-channel attacks. Fourth, resource coordination efficiency is low, synchronous system calls result in high core handover overhead, and communication between Enclaves lacks efficient and secure protocols, leading to high data transmission latency. Fifth, Enclave's internal scheduling does not support dynamic core adaptation. The existing scheduler has a fixed number of physical cores, and newly added cores cannot automatically take over tasks. Upper-layer applications need to be aware of resource changes and manually adjust them, which does not meet the "unaware" requirement.

[0026] Based on the aforementioned deficiencies of existing RISC-V TEEs in dynamic resource management, this invention builds a dynamic scaling system that integrates monitoring, decision-making, scheduling, and collaboration throughout the entire process. This system utilizes the privileged hierarchical structure and hardware isolation components (PMP registers, HPM counters) of the RISC-V architecture. Through three core mechanisms—precise load awareness, secure resource scheduling, and seamless switching collaboration—it achieves collaborative optimization of Enclave dynamic scaling, security isolation, and service continuity. This allows for resource management goals of "on-demand allocation, dynamic scaling, and application-insensitive" without requiring modifications to upper-layer application code.

[0027] This invention provides a non-perceptive dynamic kernel scaling system for the RISC-V architecture. The system is divided into three privileged levels from bottom to top on the physical hardware: M-mode (machine mode), S-mode (supervisor mode), and U-mode (user mode).

[0028] The hardware layer provides basic RISC-V multicore processor support, including standard Physical Memory Protection (PMP) register sets, Hardware Performance Monitor (HPM) counters, and large-capacity DRAM.

[0029] M-mode runs the Security Monitor (SM), which acts as the Trusted Computation Base (TCB) for the entire system. It has exclusive read and write access to the PMP register and is responsible for handling all privileged instructions that involve changes to security boundaries.

[0030] S-mode runs an untrusted Host OS that manages all system resources except for Enclave private memory, including the scheduling of idle physical cores and the allocation of insecure memory.

[0031] U-mode and S-mode run two types of isolated execution entities: one is the working Enclave that carries user business logic, and the other is the security scheduler Enclave that is specifically responsible for resource monitoring and decision-making. The two interact through a trusted channel (E2E) based on shared memory. The runtime of the working Enclave periodically writes anonymized load data to the channel. The security scheduler reads the data and makes scaling decisions based on its built-in algorithm. Then, it requests the SM to intervene and perform the reallocation of physical cores through a system call.

[0032] The technical solutions provided by the various embodiments of this application are described in detail below with reference to the accompanying drawings.

[0033] Figure 1 This is a flowchart illustrating an Enclave-based dynamic kernel resource scheduling method for RISC-V chips, as described in this specification. The method includes the following steps: S101: System initialization and trusted channel construction phase.

[0034] Upon system startup, the Security Monitor (SM) deployed in M ​​mode is initialized first as the system's root of trust. When the Host OS receives a request to create an Enclave, it allocates a contiguous region in physical memory as the Enclave's dedicated physical memory (EPM) and submits the physical address range of this region to the SM. The SM then intervenes, performing integrity measurements on the Enclave runtime code and user application code loaded into this region, calculating their cryptographic hash values ​​to generate unique identity fingerprints, and comparing and verifying them with pre-set signatures. After successful verification, the SM locks the memory region by programming the PMP registers, revoking the Host OS's read, write, and execute permissions, thereby constructing a hardware-enforced memory isolation boundary and starting the working Enclave and the security scheduler Enclave.

[0035] Meanwhile, to establish a secure communication link between the working enclave and the security scheduler, the SM executes the E2E trusted channel construction process. The host OS allocates an additional physical page as a shared buffer and registers it with the SM. After verifying the request, the SM utilizes PMP mechanisms (such as...) Figure 2 As shown, the physical page is marked as inaccessible to the Host OS. The page table mapping is then modified to map the same physical memory block to the virtual address spaces of both the working Enclave and the security scheduler, and the corresponding user-mode read / write permissions are set in the page table entries. The SM also initializes the metadata structure of the circular buffer (such as read / write pointers and mutex flags) at the header of this shared memory region, completing the physical setup of the encrypted data exchange channel. At this point, the system enters a ready state.

[0036] S102: Full-dimensional load monitoring and data synchronization stage.

[0037] During system operation, the load monitoring mechanism operates in parallel at both the hardware and software levels. At the underlying hardware level, the HPM secure virtualization module in M ​​mode continuously intercepts and proxies access requests from worker enclaves to performance counters. When an enclave requests to read the instruction retirement count (minstret) or CPU cycle count (mcycle), the SM reads the physical register values ​​and subtracts time slice counts preempted by the host OS due to interrupts or exceptions, calculating accurate clean execution time and instruction throughput (IPC) to reflect the true saturation of physical resources. These hard metrics are synchronized in real time to the security scheduler's monitoring interface.

[0038] At the software level, the Runtime of the working Enclave integrates a soft metrics acquisition submodule. This module implants probes on the critical paths of the task scheduler (such as task enqueueing, dequeueing, and lock acquisition) to record in real time the current task queue backlog length, thread spin wait time, and kernel lock contention frequency. The acquisition module packages these discrete soft metrics data into standardized load status frames and asynchronously sends them to the safety scheduler through a circular buffer of an E2E trusted channel. Upon receiving the data, the load fusion calculation submodule inside the safety scheduler uses a multinomial fusion algorithm to weight the hard and soft metrics, calculating the current "overall computational saturation," thereby achieving an accurate and real-time assessment of the working Enclave's load status.

[0039] S103: Intelligent scaling decision-making and instruction issuance stage.

[0040] The safety scheduler performs dynamic scaling up and down decisions based on real-time load data. Its internal EWMA (Exponentially Weighted Moving Average) prediction submodule maintains historical load time-series data and predicts future traffic trends by calculating the slope of load changes. The decision logic is based on a hysteresis interval model: when the smoothed overall computational saturation consistently exceeds a preset high-water level threshold (e.g., 85%), and the time interval since the last scaling up operation exceeds the forced cooling period, the algorithm determines the system is overloaded and generates a scaling up request; conversely, when the load is below a low-water level threshold (e.g., 30%) and cooling requirements are met, a scaling down request is generated.

[0041] Once a decision instruction is generated, the security scheduler sends a resource request message to the Supervisor Binary Interface (SM) containing the target Enclave ID and the required number of cores. The SM, acting as arbitrator, first verifies the digital signature of the request to ensure it has not been tampered with, and then checks the current global resource allocation table. After confirming the request's legitimacy, the SM notifies the Host OS to perform the corresponding physical core allocation or reclamation operation via an SBI (Supervisor Binary Interface) call or a virtual interrupt.

[0042] S104: Physical core security cleaning and handover phase.

[0043] The core handover process strictly follows the flow logic of the physical core hot-plug state machine. In expansion scenarios, the Host OS selects a target core from the idle core pool, marks its state as "Lending," removes it from the OS scheduler, and then calls the SM interface to hand over control. After taking over the core, the SM immediately performs a context cleanup operation, clearing all general-purpose registers, floating-point registers, and sensitive CSR registers, and forcibly flushing the TLB to remove old address mapping remnants and prevent information leakage. After cleanup, the SM atomically switches the core's PMP configuration, instantly switching its physical view to the isolation domain of the working Enclave, updating the core state to "Enclave-Active," and finally jumping to the EnclaveRuntime's hot-plug entry point to complete the handover (e.g., ...). Figure 3 (As shown).

[0044] In a downsizing scenario, the SM (Worker Management Module) notifies the Runtime of the working Enclave via an inter-core interrupt to initiate the Worker deregistration process. The target core first disables interrupts, saves the context of the currently executing user task, and pushes it back to the global ready queue to ensure no task is lost. Subsequently, the core deregisters itself from the Runtime's Worker pool, releases kernel stack resources, and enters the SM via the ecall instruction. The SM performs the reverse cleanup process, resetting the PMP (Program Management Platform) configuration to restore the HostOS's access rights, updating the core state to "Host-Owned," and ultimately returning control to the Host OS.

[0045] S105: Dynamic load balancing and service continuity assurance phase.

[0046] Once a new core (Worker) joins the work enclave and completes initialization, it immediately begins task processing. At this point, the Runtime's lock-free work-stealing submodule comes into play: the newly added Worker's local task queue is initially empty; it automatically and randomly selects another busy Worker (Victim) and uses atomic instructions to "steal" half of the tasks to be executed from the tail of the Victim's queue for local execution. This mechanism ensures that the newly added computing resources can alleviate system pressure within milliseconds, eliminating hotspot bottlenecks. In the event of scaling down or core preemption, the Runtime guarantees the atomic transfer of unfinished tasks on the affected core to other active Workers or the global queue. Combined with the work-stealing mechanism, the remaining cores automatically take over these tasks, thus ensuring continuous execution of upper-layer business logic and zero-interruption service even under drastic fluctuations in underlying hardware resources.

[0047] Furthermore, the core modules of this method are designed in detail, including: 1. Enclave and E2E Construction The secure execution environment of the Enclave is built with the SM as the root of trust: First, the Host OS allocates the memory area required by the Enclave. The SM performs security verification on the runtime environment and user programs loaded into memory. It generates a unique identity metric for the Enclave by calculating the cryptographic hash value of the initial memory content. This metric serves as the root of trust for remote authentication, ensuring that the code and data have not been tampered with before startup. After verification, the SM constructs a hardware-enforced memory isolation boundary by programming the PMP register, granting the Enclave the highest access rights to the private physical memory area, while depriving the Host OS and other Enclaves of their access capabilities. After all permission configurations take effect, the SM switches the CPU to user mode, starts the Enclave execution, and ensures the confidentiality and integrity of its runtime.

[0048] To achieve efficient and secure communication between the working enclave and the secure scheduler, the system establishes an E2E trusted channel during the enclave creation phase. This channel begins when the host OS allocates a physically contiguous memory page as a shared buffer and initiates a registration request to the SM. The SM first checks whether this memory region overlaps with existing enclave memory or reserved memory. Upon confirmation of its legitimacy, it immediately locks the physical address range and, by configuring the PMP register, revokes the host OS's read-write-execute (RWX) permissions for this region, retaining only a "non-accessible allocated resource" marker. Subsequently, the SM modifies the page table structures of both the working enclave and the secure scheduler, mapping this physical memory region into the virtual address spaces of both enclaves. In the page table entry (PTE) settings, the SM forcibly enables the "user-mode access allowed" bit (U-bit) and disables the "global" bit (G-bit), ensuring that the region can only be accessed within a specific enclave context. To prevent side-channel attacks via shared memory, a ring buffer structure is used inside the channel, and random padding data is introduced to mask the actual communication traffic pattern.

[0049] 2. A reliable resource monitoring and decision-making mechanism To address the issues of unreliable or highly intrusive existing monitoring solutions, this technical solution designs a resource management architecture of "trusted monitoring and independent decision-making." Its core comprises three parts: HPM secure virtualization, a two-dimensional load assessment model, and a lightweight hysteresis scaling algorithm. HPM secure virtualization is implemented in M ​​mode. The SM intercepts all access requests to RISC-V HPM counters (such as the minstret instruction retirement counter and the mcycle cycle counter), verifying the source of the request: if the request originates from a legitimate Enclave, the SM reads the actual hardware counter value, writes it to the Enclave's virtual register, and resumes execution, enabling the Enclave to "introspect" on its own performance; if the request originates from the Host OS, the SM returns obfuscated data (e.g., reduced precision or added random noise) according to security policies, shielding fine-grained microarchitectural events and defending against side-channel attacks.

[0050] The dual-dimensional load assessment model integrates hardware-level "hard metrics" and Enclave-internal "soft metrics." The acquisition of low-level hard metrics relies on the SM's virtualization of the HPM counter. When a worker Enclave attempts to read the mcycle (cycle count) or minstret (instruction count) register, this operation triggers an illegal instruction exception, trapping it in M-mode. The SM catches this exception and verifies whether the current instruction originates from a legitimate Enclave context. If so, the SM reads the actual value of the physical hardware counter and subtracts the counter increment during the Enclave's scheduling period (i.e., excluding Host OS occupancy time) to obtain the Enclave's net execution time. Finally, the corrected value is written to the Enclave's general-purpose registers, and execution resumes. The acquisition of upper-level soft metrics is automatically performed by the Runtime within the scheduling loop. The Runtime increments the "spin wait counter" each time it fails to acquire a task from the task queue (i.e., the queue is empty); and increments the "lock contention counter" when it successfully acquires a task but is blocked due to lock contention. A lightweight monitoring thread inside the Enclave periodically (e.g., every 10ms) reads these software counters and virtualized hardware counters, packages them into load status frames, and sends them to the security scheduler via an E2E channel.

[0051] After receiving the load status frame, the safety scheduler first performs data cleaning and fusion. It uses a polynomial fusion function to calculate "comprehensive computation saturation," which assigns a positive weight to instruction throughput (IPC) and a negative weight to spin wait time, thus eliminating interference from ineffective busy operations on load assessment. After obtaining the real-time saturation, the algorithm inputs it into an exponentially weighted moving average (EWMA) model to calculate the smoothed load trend value. This model sets a dynamic decay factor α, which automatically increases to improve sensitivity when the load rises sharply and decreases to enhance noise immunity when the load is stable. The decision logic is based on hysteresis intervals: setting expansion threshold Thigh (e.g., 85%) and reduction threshold Tlow (e.g., 30%). Expansion is triggered only when the smoothed load value consistently exceeds Thigh and the time interval since the last expansion operation exceeds a preset cooling period (e.g., 50ms); conversely, reduction is triggered only when the load is below Tlow and the cooling period requirement is met. If the load is detected to spike to the safe circuit breaker value (e.g., 98%), the bypass cooling-off period check is immediately interrupted, and a capacity expansion request is forcibly triggered to handle the sudden traffic surge.

[0052] 3. Secure and efficient asynchronous collaboration protocol To address the lack of a standard and efficient resource handover protocol between the Host OS and Enclave, this technical solution designs an asynchronous collaborative mechanism of "untrusted dominance and trusted execution," comprising a control channel based on shared memory and a physical core hot-swappable state machine. The control channel runs between the Host OS and Enclave, and between Enclaves: the working Enclave sends collected load data to the security scheduler through this channel; the security scheduler issues a "resource grant" message requesting core allocation; after verifying the validity of the request, the SM notifies the target Enclave to take over the core through the channel. The entire process uses an asynchronous interaction mode, avoiding the high overhead of synchronous system calls.

[0053] The physical core hot-swappable state machine defines a rigorous core transition lifecycle, ensuring unique and clear core ownership and avoiding the "dual ownership" security vulnerability. The state transition includes five stages: "Host-Owned → Lending → Monitor-Sanitizing → Enclave-Active → Returning". When the Host OS responds to a scaling request, it first marks the selected idle core in the scheduler as Lending, stops assigning ordinary tasks to it, and initiates a core handover call (SBI Call) to the SM. After receiving the request, the SM sets the core state to Monitor-Sanitizing and then performs context cleaning: clearing or resetting all general-purpose registers (x1-x31), floating-point registers (f0-f31), and related control status registers (such as sstatus, sepc) to safe default values. Next, the SM executes the sfence.vma instruction to refresh the core's TLB, completely clearing any remaining address mappings. After cleaning, the SM modifies the PMP configuration, switching the execution permission of the core from S-mode to the memory isolation domain where the target Enclave resides, and updates the core state to Enclave-Active. Finally, the SM sets the program counter (PC) to point to the hot-plug entry address of the Enclave Runtime and executes the `mret` instruction, causing the core to jump to the Enclave and begin executing the initialization code. The entire process is atomic; failure at any step will cause the core state to roll back to Host-Owned.

[0054] 4. Supports dynamic hot-swappable M:N user-space scheduler To ensure that upper-layer applications are unaware of core changes, this technical solution deeply reconstructs the Enclave Runtime, designing a dynamically scalable M:N user-space scheduler, comprising dynamic worker pool management and a lock-free work-stealing algorithm. Dynamic worker pool management breaks the static binding between physical cores and execution threads. The Runtime internally maintains a concurrency-safe worker linked list, recording all currently available physical execution units (HARTs). When a new core enters the Enclave via hot-plugging and jumps to the Runtime entry point, the initialization code allocates an independent kernel stack and thread-local storage (TLS) area for it. After initialization, the core registers itself with the worker pool and marks itself as "Active." When a core needs to be reclaimed, the Runtime triggers a worker deregistration process. The core first disables interrupts, saves the state of the currently executing user thread to the Task Control Block (TCB) and returns it to the global ready queue, then removes itself from the worker pool, releases its stack space, and uses the ecall instruction to trap into the SM to return the physical core. The entire process employs atomic operations to prevent race conditions.

[0055] Lock-free work-stealing algorithms (such as...) Figure 4 As shown, a decentralized design is adopted, with each Worker core having a local double-ended queue (Deque) to store user threads (Green Threads) to be executed. The local core retrieves tasks from the tail of the queue in a first-in-first-out (FIFO) order, maximizing the utilization of CPU cache locality. When a new core joins the Enclave or a core completes all its local tasks and becomes idle, the work-stealing logic is activated. It randomly selects other busy Worker cores (Victim) and uses RISC-V atomic instructions (such as lr / sc load-condition store instructions and AMO atomic memory operation instructions) to achieve lock-free access, "stealing" half of the tasks from the tail of the Victim queue for execution. This ensures that dynamically added cores can automatically and transparently take over the backlog of tasks, achieving load balancing, and the upper-layer application does not need to be aware of the change in the number of cores.

[0056] Furthermore, in one or more embodiments of this specification, for the core module of this technical solution, the following feasible alternatives exist, which can expand the scope of patent protection: In terms of HPM secure virtualization, in addition to the existing "SM interception + data isolation" solution, the "Enclave embedded point + SM verification" mode can be adopted. A lightweight performance acquisition point is embedded in the Enclave Runtime. The acquired data is encrypted and transmitted to the secure scheduler through the E2E channel. The SM only verifies the data integrity, which is suitable for RISC-V platforms without HPM hardware support; In terms of trusted channel construction, the shared memory mechanism can be replaced with the "encrypted message queue + SM forwarding" mode. The working Enclave and the secure scheduler transmit data through the encrypted message queue. The SM acts as a forwarding node to verify the data signature, improving communication security, which is suitable for high-security scenarios.

[0057] Regarding load balancing algorithms, the lock-free work-stealing algorithm can be replaced with a "centralized task scheduling + dynamic task distribution" mechanism. A centralized task manager is deployed in the Runtime to collect the load status of each worker in real time and distribute new tasks directly to idle cores. This is suitable for scenarios with large task granularity and low scheduling frequency. The physical core hot-swappable state machine can be simplified to a four-stage process. The functions of the "Lending" and "Returning" states are integrated into the interaction process between the Host OS and SM, reducing the state transition links. This is suitable for lightweight TEE scenarios with low resource scheduling frequency.

[0058] Regarding scaling decision-making algorithms, the EWMA prediction model can be replaced with a Kalman filter-based prediction algorithm to improve prediction accuracy under nonlinear load scenarios; alternatively, a simplified algorithm of "fixed threshold + sliding window counting" can be used to reduce computational resource consumption, which is suitable for lightweight enclave application scenarios with high real-time decision requirements.

[0059] Furthermore, the key parameters of this technical solution can be flexibly configured to adapt to different application scenarios: the sliding window size of the EWMA prediction model can be set to 10-100ms, the high watermark threshold of the hysteresis interval is recommended to be configured to 70%-90%, the low watermark threshold is recommended to be configured to 10%-30%, and the core hot-swap cooling period can be adjusted within the range of 10-100ms; in terms of hardware adaptation, this solution is suitable for many-core processors (core number ≥ 4) that support RISC-V privileged architecture (M-mode / S-mode / U-mode), no less than 16 PMP registers, and have minstret / mcycle basic counters.

[0060] In terms of software dependencies, Enclave Runtime needs to be modified based on Keystone Eyrie or Penglai Monitor, adding dynamic worker pool management, lock-free queues and load collection modules; SM needs to be extended with PMP dynamic configuration interface, HPM access interception logic and core state management functions.

[0061] In terms of expected technical effects, the core hot-swap response time is ≤10μs, the service interruption rate during Enclave scaling is ≤0.1%, the CPU utilization of many-core servers is improved by more than 30% compared with the existing static solution, and it supports the direct recompilation and running of existing multi-threaded applications such as Redis and Nginx without modifying the source code.

[0062] In summary, such as Figure 1 The key innovations of the Enclave-based dynamic kernel resource scheduling method based on RISC-V chips can be summarized as follows: (1) Trusted decision architecture: An independent decision architecture of "security scheduler + working enclave" is proposed. The security scheduler runs as an independent enclave. Combined with HPM secure virtualization and E2E trusted channel, it realizes trusted load monitoring and scaling decision without relying on HostOS, solves the security problems of data falsification and scheduling algorithm manipulation in existing solutions, and ensures the confidentiality and integrity of the decision process.

[0063] (2) HPM secure virtualization method: Implement fine-grained virtualization of RISC-V HPM counter in M ​​mode, provide real performance data to Enclave through access interception and identity verification to support "introspection", and shield fine-grained microarchitecture events from Host OS, taking into account both monitoring accuracy and side-channel attack defense, filling the security gap of existing HPM applications in TEE scenarios.

[0064] (3) Dual-dimensional load assessment model: It integrates hardware-level "hard indicators" and Enclave internal "soft indicators", and calculates the comprehensive computing saturation through multi-dimensional fusion function. It can distinguish between effective computing and spin waiting, solve the problem of load misjudgment caused by single indicators, and provide accurate data support for scaling up and down decisions.

[0065] (4) Lightweight Hysteresis Scaling-Down Algorithm: Based on the EWMA prediction model and hysteresis interval and cooling period mechanism, it realizes predictive scaling-down decision-making, effectively filters traffic spikes, avoids resource jitter, balances system response speed and stability, and is suitable for cloud-native dynamic load scenarios.

[0066] (5) Physical core hot-swap state machine: Defines a five-stage core flow lifecycle, and achieves microsecond-level physical core handover by minimizing context cleaning and atomic PMP configuration switching, ensuring secure isolation and low latency during the core flow process, and breaking through the performance bottleneck of existing synchronous collaboration protocols.

[0067] (5) M:N lockless work stealing scheduler: Through dynamic worker pool management and lockless double-ended queue design, it realizes dynamic registration / deregistration of physical cores and automatic load balancing, ensuring that upper-layer applications are unaware of changes in the number of cores, and improving system compatibility and resource utilization.

[0068] The technical problems to be solved and the advantages of the technical solution in this patent application include: The core technical issues are: First, it enables dynamic scaling of the number of Enclave cores in a RISC-V TEE environment, and the scaling operation is completely transparent to upper-layer applications without requiring modification of application code. Second, build a reliable load monitoring and decision-making system to get rid of dependence on untrusted host OS and defend against false load attacks and scheduling manipulation risks; Third, design an efficient and secure asynchronous collaboration protocol to reduce the overhead of hot-swapping physical cores and ensure secure isolation during core transfer. Fourth, it enables automatic load balancing of dynamic cores, ensuring that newly added cores can quickly take over backlogged tasks and improve the utilization rate of many core resources.

[0069] The technical advantages are reflected in: First, resource utilization is significantly improved. Through a dynamic scaling mechanism, Enclave can occupy cores on demand according to real-time load, release idle cores for other tasks when the load is low, and quickly scale up when the load is high, greatly improving the CPU utilization of many-core servers. Second, it has strong scenario adaptability, and its millisecond-level core hot-swappable capability perfectly matches the elastic requirements of serverless computing, helping trusted computing technology to be applied on a large scale in high-volume and volatile scenarios such as financial risk control and medical image analysis. Third, it has high security. Through trusted monitoring, independent decision-making and security collaboration mechanisms, it resists false load, scheduling attacks and side-channel attacks, ensuring the integrity and confidentiality of Enclave execution. Fourth, it has good compatibility. The "unobtrusive" design supports the direct compilation and execution of existing multi-threaded applications without modifying the source code, which lowers the threshold for implementing the dynamic TEE architecture and protects users' existing software assets.

[0070] The technical features of the above embodiments can be combined in any way. For the sake of brevity, not all possible combinations of the technical features in the above embodiments are described. However, as long as there is no contradiction in the combination of these technical features, they should be considered to be within the scope of this specification.

Claims

1. A method for Enclave-less dynamic kernel resource scheduling based on a RISC-V chip, characterized in that, include: As a trusted root, the security monitor responds to the request to create an Enclave by constructing a working Enclave and a security scheduler Enclave through integrity metrics and PMP configuration, and establishes a trusted channel based on shared memory between the working Enclave and the security scheduler Enclave. The working Enclave virtualizes the Hardware Performance Monitor (HPM) counter through the security monitor to obtain hard indicator data representing the saturation of physical resources, and collects soft indicator data on the task scheduling path through the Runtime; and transmits the hard indicator data and the soft indicator data to the security scheduler Enclave through the trusted channel. The security scheduler Enclave analyzes the received hard and soft indicator data using a preset algorithm to generate scaling decision instructions that include the physical core identifier to be transferred and the target working Enclave identifier. In response to the scaling decision command, the security monitor invokes the physical core hot-swap state machine to execute a five-stage state machine transition, and transfers the core security corresponding to the physical core identifier to the target working Enclave. The target work Enclave starts its internal user-space scheduler and, through dynamic worker pool management and lock-free work theft mechanism, achieves task takeover and load balancing scheduling of the newly added core. The five-stage state machine includes the host-owned state, the lending state, the cleaning state, the enclave active state, and the return state. The invocation of the physical core hot-swap state machine to execute the five-stage state machine transition includes: Upon receiving the expansion decision instruction, the selected idle core is marked as being loaned out in the scheduler, the distribution of ordinary tasks to it is stopped, and a core handover call request is initiated to the security monitor. The security monitor receives the core handover call request, sets the status of the idle core to the cleaning state, and clears or resets all general-purpose registers, floating-point registers, and control status registers to their safe default values. The sfence.vma instruction is executed to refresh the TLB of the idle core, completely clearing the residual address mapping; and after the clearing is completed, the PMP configuration is modified to switch the execution permission of the idle core from the supervisor mode to the memory isolation domain where the target working Enclave is located, and the status of the idle core is updated to the Enclave active state. Set the program counter to point to the hot-plug entry address of the Enclave Runtime and execute the mret instruction to cause the idle core to jump to the target working Enclave; Upon receiving the scaling-down decision instruction, the security monitor notifies the Runtime of the worker Enclave to stop distributing new tasks to the cores to be returned, and to migrate the unfinished tasks of the cores to be returned, save the context, and deregister from the worker pool. After the core to be returned enters the security monitor via ecall, the security monitor changes the status of the core to be returned from the Enclave active state to the return in progress state. The security monitor performs a reverse cleaning process and resets the PMP configuration, restores the host operating system's access permissions, updates the status of the core to be returned to the host-owned state, and returns control to the host operating system.

2. The Enclave-based dynamic kernel resource scheduling method for RISC-V chips as described in claim 1, characterized in that, The construction of the working Enclave includes: Based on the memory area required by the Enclave, a security monitor is used to perform security checks on the Runtime environment and user programs loaded into memory. A unique identity metric for the Enclave is generated by calculating the cryptographic hash value of the initial memory content; and this identity metric is used as the trust foundation for remote authentication to ensure that the code and data have not been tampered with before startup. The security monitor constructs a hardware-enforced memory isolation boundary by programming the PMP register; and grants the Enclave the highest access rights to the private physical memory region, while depriving the host operating system and other Enclaves of access, thus completing the construction of the working Enclave.

3. The Enclave-based dynamic kernel resource scheduling method for RISC-V chips as described in claim 1, characterized in that, The construction of the trusted channel specifically includes: Obtain a physically contiguous memory region and register it with the security monitor as a shared buffer; The security monitor verifies the shared buffer and, after confirming that the memory region does not overlap with the existing Enclave memory, configures the PMP register to revoke read, write, and execute permissions for the memory region from other programs besides the two communicating parties. The security monitor modifies the page table structure of the working Enclave and the security scheduler Enclave, maps the memory region to the virtual address space of the working Enclave and the security scheduler Enclave, and forces the user-mode access permission bit to be enabled and the global bit to be disabled in the page table entries, thereby completing the construction of the trusted channel.

4. The Enclave-based dynamic kernel resource scheduling method for RISC-V chips as described in claim 1, characterized in that, The soft metrics data include task queue backlog length, thread spin wait time, and lock contention frequency.

5. The Enclave-based dynamic kernel resource scheduling method for RISC-V chips as described in claim 1, characterized in that, The generation of the scaling decision instruction specifically includes: The safety scheduler assigns positive weights to instruction throughput and negative weights to spin wait time based on the received hard and soft performance data through a polynomial fusion function, in order to eliminate the interference of invalid busy on load assessment and obtain the comprehensive computational saturation. The comprehensive saturation calculation is input into the exponentially weighted moving average model, which automatically adjusts according to the changes in load value by setting a dynamic decay factor to generate a smoothed load trend value. When the smoothed load value continuously exceeds the preset expansion threshold and the time interval since the last operation exceeds the preset cooling period, an expansion command is triggered; when the load value is lower than the preset reduction threshold and the cooling period requirement is met, a reduction command is triggered.

6. The Enclave-based dynamic kernel resource scheduling method for RISC-V chips as described in claim 1, characterized in that, The target job's internal user-space scheduler includes: The dynamic worker pool management module is used to maintain a concurrent and safe worker linked list, and supports dynamic registration and deregistration of physical cores; The lock-free task stealing module allows each worker core to maintain a local double-ended queue. Idle cores can steal tasks from the tail of other busy cores' queues via atomic instructions.

7. The Enclave-based dynamic kernel resource scheduling method for RISC-V chips as described in claim 1, characterized in that, The method is applied to a layered architecture RISC-V processor system, the layered architecture comprising: The hardware layer includes a RISC-V multi-core processor, a physical memory protection register set, and a hardware performance monitor counter. The machine mode layer is used to run the security monitor; the security monitor serves as the trusted computing base of the system, has exclusive read and write access to the PMP register, and is used to process all privileged instructions involving changes to security boundaries. The regulator mode layer is used to run the host operating system and manage all system resources except for Enclave private memory, including the scheduling of idle physical cores and the allocation of insecure memory. The user mode layer and the supervisor mode layer are used to run the working Enclave that carries user business logic and the security scheduler Enclave that is responsible for resource monitoring and decision-making. The working Enclave and the security scheduler Enclave interact through a trusted channel based on shared memory. The runtime of the working Enclave periodically writes the de-identified load data into the trusted channel. The security scheduler reads the load data and makes scaling decisions based on the built-in algorithm. It then intervenes through the security monitor to perform the reallocation of physical cores.

Citation Information

Patent Citations

  • Trusted execution environment implementation method, computer equipment and storage medium

    CN117494108A

  • Zero-knowledge proof identity authentication system and method based on RISC-V trusted execution environment

    CN121619107A