Memory management method and apparatus, electronic device, storage medium, and program product

By dividing the memory into regions and setting differentiated access permissions in the embedded real-time system, the problem that existing memory management schemes cannot guarantee the real-time performance of high-priority tasks is solved, thus achieving high efficiency and security in memory management.

CN122111641APending Publication Date: 2026-05-29BEIJING CHINA POWER INFORMATION TECH

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
BEIJING CHINA POWER INFORMATION TECH
Filing Date
2025-12-31
Publication Date
2026-05-29

AI Technical Summary

Technical Problem

In existing technologies, memory management schemes for embedded real-time systems cannot guarantee the strict real-time performance of high-priority real-time tasks. They suffer from problems such as memory fragmentation, insufficient isolation, and incompatibility with dynamic resource requirements, which lead to real-time task latency and affect system security.

Method used

Based on the task criticality level model, physical memory is divided into a high-priority task-specific area, a shared service area, and a low-priority task isolation area. Differentiated access permissions are set, and memory is pre-allocated through the task criticality level model. Fragmentation entropy and memory pressure are monitored, and differentiated defragmentation strategies and data migration are executed to optimize memory resource usage.

Benefits of technology

It achieves strict real-time performance for high-priority tasks, reduces memory fragmentation, improves system isolation and adaptability of dynamic resource management, and ensures system real-time performance and security.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122111641A_ABST
    Figure CN122111641A_ABST
Patent Text Reader

Abstract

The present disclosure provides a memory management method, device, electronic equipment, storage medium and program product, the method comprising: based on the task criticality level model, dividing the physical memory into several physically isolated memory regions, and setting differentiated access permissions for different memory regions; based on the task criticality level model, pre-allocating memory for tasks in the memory region corresponding to the corresponding task criticality level; monitoring the memory fragmentation distribution state of the task running to obtain a fragmentation entropy value, and in response to the fragmentation entropy value being greater than a fragmentation entropy value threshold, performing differentiated fragmentation consolidation strategies on different memory regions; predicting the memory pressure based on a load prediction model, and in response to the predicted memory pressure being greater than a memory pressure threshold, performing data migration and physical memory expansion; in response to the completion of task execution, recycling the memory resources occupied by the task, and based on the fragmentation entropy value, optimizing the fragmentation entropy value threshold and the memory pressure threshold. The strict real-time performance of high-priority real-time tasks is ensured.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This disclosure relates to the field of memory management technology, and in particular to a memory management method, apparatus, electronic device, storage medium, and program product. Background Technology

[0002] This section is intended to provide background or context for the embodiments of this disclosure as set forth in the claims. The description herein is not intended to be a prior art simply because it is included in this section.

[0003] In the field of embedded real-time systems, such as industrial control equipment like power load control terminals, the efficiency of memory management directly affects the system's real-time performance, reliability, and security.

[0004] However, existing memory management solutions have the following problems: Strict real-time performance (e.g., jitter tolerance less than 1 microsecond) cannot be guaranteed for high-priority real-time tasks (such as relay control, data acquisition, etc.). Summary of the Invention

[0005] In view of this, the purpose of this disclosure is to provide a memory management method, apparatus, electronic device, storage medium and program product, which at least to some extent solves one of the technical problems in the related art.

[0006] To achieve the above objectives, the first aspect of this exemplary embodiment provides a memory management method, comprising: Based on a pre-built task criticality level model, physical memory is divided into several physically isolated memory regions, and different access permissions are set for different memory regions. Based on the task criticality level model, memory is pre-allocated for the task in the memory region corresponding to the corresponding task criticality level; The fragmentation entropy value is obtained by monitoring the memory fragmentation distribution status during the operation of the task. In response to the fragmentation entropy value being greater than the fragmentation entropy value threshold, a differentiated fragmentation defragmentation strategy is executed for different memory regions. Memory pressure is predicted based on a pre-built load prediction model, and data migration and physical memory expansion are performed in response to the predicted memory pressure exceeding a memory pressure threshold. In response to the completion of the task, the memory resources occupied by the task are reclaimed, and the fragment entropy threshold and the memory pressure threshold are optimized based on the fragment entropy value.

[0007] In some exemplary embodiments, the method of dividing physical memory into several physically isolated memory regions based on a pre-built task criticality level model and setting differentiated access permissions for different memory regions includes: Initialize the hardware, obtain hardware parameters and physical memory distribution information, and establish a physical memory address mapping; The task criticality level model is constructed based on the functional requirements of the control terminal, and the correspondence between the task criticality level and the memory region is determined. The physical memory is divided into a high-priority task-specific area, a shared service area, and a low-priority task-isolated area. Configure different access permissions for the high-priority task exclusive area, the shared service area, and the low-priority task isolation area.

[0008] In some exemplary embodiments, the step of pre-allocating memory for a task in the memory region corresponding to the corresponding task criticality level based on the task criticality level model includes: Determine task priority weights and predict memory usage using a sliding window averaging method based on historical load data; In the high-priority task-specific area, a fixed-size memory block is allocated using the first-fit algorithm; in the shared service area, a buddy system is used to dynamically manage the free list; and in the low-priority task isolation area, a memory pool is predefined, and fragmentation reclamation is accelerated using a red-black tree index. Set an access control matrix for each memory region; Perform real-time verification and stress testing; Adjust memory allocation parameters based on test results.

[0009] In some exemplary embodiments, monitoring the memory fragmentation distribution status during task execution yields a fragmentation entropy value. In response to the fragmentation entropy value exceeding a fragmentation entropy threshold, a differentiated defragmentation strategy is executed for different memory regions, including: Scan the page table entries of each memory region to calculate the fragment entropy value; The fragment entropy threshold is calculated based on the sliding window mean and standard deviation. In response to the fragment entropy value being greater than the fragment entropy value threshold, a copy-and-sweep algorithm is used to migrate key data in the high-priority area, a mark-and-sweep algorithm is used to merge free blocks in the shared service area, and a lazy compaction strategy is used to release idle memory in batches in the low-priority area. Hardware-level memory barriers are inserted before and after the compaction operation. A software transactional memory mechanism is used to perform page table updates and free list modifications. During the compaction process, high-priority task preemption is prohibited and low-priority interrupts are masked.

[0010] In some exemplary embodiments, the prediction of memory pressure based on a pre-built load prediction model, and the data migration and physical memory expansion performed in response to the predicted memory pressure exceeding a memory pressure threshold, include: Input the task execution time, memory allocation, interrupt triggering frequency, and operation intensity into the load prediction model to obtain the memory pressure output by the load prediction model; Page activity is statistically analyzed by accessing page table entries, inactive memory pages are identified, and they are sorted by access frequency. Inactive memory pages are then migrated to external storage, and a circular buffer is used to manage the migration task. Configure the memory controller to connect to the new memory module, reconfigure the page table of the memory management unit to expand the virtual address space, adopt a progressive plug-in strategy to migrate data in stages, and use a weighted round-robin scheduling algorithm to allocate bandwidth.

[0011] In some exemplary embodiments, the step of reclaiming the memory resources occupied by the task in response to the completion of the task execution, and optimizing the fragmentation entropy threshold and the memory pressure threshold based on the fragmentation entropy value, includes: When a task enters a completed or abnormally terminated state, the occupied memory block is reclaimed and a status mark is made. In response to the number of consecutive free pages being less than the threshold for consecutive free pages, an object compaction and page-level merging algorithm is used to aggregate free memory; The fragment entropy value is calculated by combining the page-level fragment distribution and the change rate over time, and a dynamic threshold is generated based on the exponentially weighted moving average. Optimization is triggered when the fragment entropy value is greater than the threshold. Adjust the size of pre-allocated memory blocks based on historical allocation variance and optimize memory region allocation weights; The scan cycle is calculated based on the average allocation rate of the low priority area. When the idle time of a memory block is greater than the preset proportion of the time window, it is marked as reclaimable. When switching task contexts, reset the high-priority memory blocks to their pre-allocated state; The memory allocation success rate, average allocation latency, and fragmentation entropy are collected as feedback signals to calculate the parameter adjustment amount, and optimization strategies are deployed based on the parameter adjustment amount.

[0012] Based on the same inventive concept, a second aspect of the exemplary embodiments of this disclosure provides a memory management apparatus, including: The memory partitioning and permission setting module is configured to divide physical memory into several physically isolated memory regions based on a pre-built task criticality level model, and set different access permissions for different memory regions. The memory pre-allocation module is configured to pre-allocate memory for a task in the memory region corresponding to the corresponding task critical level based on the task critical level model. The fragmentation monitoring and defragmentation module is configured to monitor the memory fragmentation distribution status during the operation of the task to obtain the fragmentation entropy value, and in response to the fragmentation entropy value being greater than the fragmentation entropy value threshold, to execute differentiated fragmentation defragmentation strategies for different memory regions. The memory prediction and expansion module is configured to predict memory pressure based on a pre-built load prediction model, and to perform data migration and physical memory expansion in response to the predicted memory pressure being greater than a memory pressure threshold. The resource reclamation and parameter optimization module is configured to reclaim the memory resources occupied by the task in response to the completion of the task execution, and optimize the fragment entropy threshold and the memory pressure threshold based on the fragment entropy value.

[0013] Based on the same inventive concept, a third aspect of the exemplary embodiments of this disclosure provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the method as described in the first aspect.

[0014] Based on the same inventive concept, a fourth aspect of the exemplary embodiments of this disclosure provides a non-transitory computer-readable storage medium storing computer instructions for causing a computer to perform the method as described in the first aspect.

[0015] Based on the same inventive concept, a fifth aspect of the exemplary embodiments of this disclosure provides a computer program product including computer program instructions that, when run on a computer, cause the computer to perform the method as described in the first aspect.

[0016] As can be seen from the above description, the memory management method, apparatus, electronic device, storage medium, and program product provided in this disclosure include: dividing physical memory into several physically isolated memory regions based on a pre-built task criticality level model, and setting differentiated access permissions for different memory regions; pre-allocating memory for tasks in the memory regions corresponding to the corresponding task criticality level based on the task criticality level model; monitoring the memory fragmentation distribution status during task execution to obtain fragmentation entropy values, and executing differentiated defragmentation strategies for different memory regions in response to the fragmentation entropy value being greater than a fragmentation entropy value threshold; predicting memory pressure based on a pre-built load prediction model, and performing data migration and physical memory expansion in response to the predicted memory pressure being greater than a memory pressure threshold; and reclaiming the memory resources occupied by the task in response to the completion of task execution, and optimizing the fragmentation entropy value threshold and the memory pressure threshold based on the fragmentation entropy value. This ensures the strict real-time performance of high-priority real-time tasks. Attached Figure Description

[0017] To more clearly illustrate the technical solutions in this disclosure or related technologies, the accompanying drawings used in the description of the embodiments or related technologies will be briefly introduced below. Obviously, the accompanying drawings described below are only embodiments of this disclosure. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0018] Figure 1 A flowchart illustrating a memory management method provided for an exemplary embodiment of this disclosure; Figure 2 A schematic diagram of a data migration process provided for an exemplary embodiment of this disclosure; Figure 3 A schematic diagram of a memory block reclamation process provided for an exemplary embodiment of this disclosure; Figure 4 A schematic diagram of a memory block reset process provided for an exemplary embodiment of this disclosure; Figure 5 A schematic diagram of a memory management device provided for an exemplary embodiment of this disclosure; Figure 6 A schematic diagram of the structure of an electronic device provided as an exemplary embodiment of the present disclosure. Detailed Implementation

[0019] It is understood that before using the technical solutions disclosed in the various embodiments of this application, users should be informed of the types, scope of use, and usage scenarios of the personal information involved in this application in an appropriate manner in accordance with relevant laws and regulations, and user authorization should be obtained.

[0020] For example, upon receiving a user's active request, a prompt message is sent to the user to explicitly inform them that the requested operation will require the acquisition and use of the user's personal information. This allows the user to independently choose whether to provide personal information to the software or hardware, such as the electronic device, application, server, or storage medium performing the operations of this application's technical solution, based on the prompt message.

[0021] As an optional but non-limiting implementation, in response to a user's active request, sending a prompt message to the user can be done via a pop-up window, where the prompt message can be presented in text format. Furthermore, the pop-up window can also include a selection control allowing the user to choose "agree" or "disagree" to provide personal information to the electronic device.

[0022] It is understood that the above notification and user authorization process are merely illustrative and do not constitute a limitation on the implementation of this application. Other methods that comply with relevant laws and regulations may also be applied to the implementation of this application.

[0023] It is understood that the data involved in this technical solution (including but not limited to the data itself, the acquisition or use of the data) shall comply with the requirements of relevant laws, regulations and related provisions.

[0024] To make the objectives, technical solutions, and advantages of this disclosure clearer, the principles and spirit of this disclosure will be described below with reference to several exemplary embodiments. It should be understood that these embodiments are provided merely to enable those skilled in the art to better understand and implement this disclosure, and are not intended to limit the scope of this disclosure in any way. Rather, these embodiments are provided to make this disclosure more thorough and complete, and to fully convey the scope of this disclosure to those skilled in the art.

[0025] In this article, it is important to understand that any number of elements in the accompanying figures is for illustrative purposes and not for limitation, and any naming is for distinction only and has no limiting meaning.

[0026] It should be noted that, unless otherwise defined, the technical or scientific terms used in the embodiments of this disclosure should have the ordinary meaning understood by one of ordinary skill in the art to which this disclosure pertains. The terms "first," "second," and similar words used in the embodiments of this disclosure do not indicate any order, quantity, or importance, but are merely used to distinguish different components. Terms such as "comprising" or "including" mean that the element or object preceding the word encompasses the elements or objects listed following the word and their equivalents, without excluding other elements or objects. Terms such as "connected" or "linked" are not limited to physical or mechanical connections, but can include electrical connections, whether direct or indirect. Terms such as "upper," "lower," "left," and "right" are used only to indicate relative positional relationships; when the absolute position of the described object changes, the relative positional relationship may also change accordingly. The article "a" or "an" preceding an element does not exclude the existence of multiple such elements.

[0027] The principles and spirit of this disclosure will be explained in detail below with reference to several representative embodiments.

[0028] As described in the background section, in the field of embedded real-time systems, such as industrial control equipment like power load control terminals, the performance of memory management directly affects the system's real-time performance, reliability, and security.

[0029] However, the inventors of this disclosure have discovered the following problems with existing memory management schemes: Strict real-time performance (e.g., jitter tolerance less than 1 microsecond) cannot be guaranteed for high-priority real-time tasks (such as relay control, data acquisition, etc.). Specifically: Mixed memory management leads to latency in real-time tasks: High-priority tasks (such as relay control) share memory space with low-priority tasks (such as log recording), causing high-priority tasks to be interfered with during memory allocation, and real-time performance cannot be guaranteed (judder often exceeds 1 microsecond).

[0030] Furthermore, the inventors of this disclosure have also discovered that existing memory management solutions suffer from the following problems: they cannot handle the challenges posed by memory fragmentation, insufficient isolation, and dynamic resource requirements, specifically including: Severe memory fragmentation: Frequent dynamic allocation and release lead to the accumulation of memory fragments, and allocation latency increases significantly with runtime.

[0031] Lack of prediction and adaptive mechanisms: The system cannot predict memory requirements based on load changes, resulting in delayed scaling response and an inability to meet the memory demands of sudden tasks in industrial scenarios.

[0032] Insufficient isolation: Unclear memory access permissions between tasks pose a risk of unauthorized access and affects system security.

[0033] To address the aforementioned issues, this disclosure provides a memory management scheme, specifically including: dividing physical memory into several physically isolated memory regions based on a pre-built task criticality level model, and setting differentiated access permissions for different memory regions; pre-allocating memory for tasks in the memory regions corresponding to their respective task criticality levels based on the task criticality level model; monitoring the memory fragmentation distribution status during task execution to obtain fragmentation entropy values, and executing differentiated defragmentation strategies for different memory regions in response to the fragmentation entropy value exceeding a fragmentation entropy value threshold; predicting memory pressure based on a pre-built load prediction model, and performing data migration and physical memory expansion in response to the predicted memory pressure exceeding a memory pressure threshold; and reclaiming the memory resources occupied by the task upon task completion, and optimizing the fragmentation entropy value threshold and the memory pressure threshold based on the fragmentation entropy value.

[0034] This ensures the strict real-time performance of high-priority real-time tasks.

[0035] Below, the relevant terms will be explained first: Task Criticality Level Model: A framework that prioritizes tasks (high / medium / low) based on their real-time requirements. High-priority tasks must meet the stringent requirement of jitter tolerance <1 microsecond. Memory regions are bound through static configuration files to ensure that critical tasks (such as relay control) exclusively occupy isolated memory space.

[0036] Memory Stress Index (MPI): A comprehensive indicator that quantifies system memory load. It is calculated by adding the current memory usage percentage to the allocation rate fluctuation coefficient. A dynamic scaling mechanism is triggered when the MPI > 0.85 or the growth rate per minute > 0.1.

[0037] Address space isolation technology: Differentiated access permissions are set through hardware MMU: high priority zone is read and written only in privileged mode, shared service zone allows interaction of medium priority tasks, and low priority zone prohibits direct physical address operations, thus achieving physical-level security isolation.

[0038] Magic Pattern: A special checksum filled during memory initialization (0xDEADBEEF for 32-bit systems and 0xDDBBAA99CC77 for 64-bit systems), which, together with CRC32 checksum, detects memory tampering or leakage, ensuring the integrity of data in high-priority areas.

[0039] Progressive plug-in strategy: When expanding memory, a three-stage cold and hot data migration is adopted: first move low-priority cold data, then move medium-priority non-real-time data, and finally move high-priority redundant cache. DMA weighted scheduling is used to ensure that the bandwidth ratio of critical tasks is ≥60%.

[0040] Fragmentation entropy (H(t)): A dynamic indicator that quantifies the degree of memory fragmentation, calculated by combining the probability density of fragment distribution with the rate of change over time. Defragmentation is triggered when the entropy exceeds the sliding window mean plus three standard deviations.

[0041] LSTM load prediction model: a three-layer stacked long short-term memory network. The input features include time-series data such as task execution time and memory allocation. The output is a predicted value of future memory demand. The prediction error is continuously reduced by the Adam optimizer.

[0042] Lazy compaction strategy: For the fragmentation reclamation mechanism of low priority areas, when the memory block idle time exceeds 70% of the time window (the window is 5 seconds by default), it is released in batches by page alignment and returned to the memory pool.

[0043] Transactional migration protocol: The memory hot-plugging process satisfies ACID properties: Atomicity is achieved through logging, consistency relies on CRC32 segmentation check, isolation is controlled by priority, and durability is guaranteed by TCM cache refresh.

[0044] Self-optimizing closed-loop control: A dynamic parameter tuning mechanism driven by a PID controller: It collects feedback signals such as allocation success rate and fragment entropy value, outputs parameter adjustment amount through proportional-integral-derivative operations, and deploys and updates strategies every 24 hours.

[0045] Dual-buffer switching: During memory expansion, the mapping relationship between the old and new addresses is maintained, and the mapping pointer is switched during the system's free window. Combined with a 5-microsecond delay buffer to absorb switching jitter, the critical task is achieved with zero awareness.

[0046] After introducing the basic principles of this disclosure, various non-limiting embodiments of this disclosure will be described in detail below.

[0047] refer to Figure 1 This is a flowchart illustrating a memory management method provided in an exemplary embodiment of the present disclosure.

[0048] Memory management methods include the following steps: Step S110: Based on the pre-built task criticality level model, divide the physical memory into several physically isolated memory regions and set different access permissions for different memory regions.

[0049] In practice, when the load control terminal device powers on and starts up, the physical memory is statically partitioned based on the task criticality level model (high / medium / low priority). Three independent memory regions are created using address space isolation technology: a high-priority task-specific region (statically pre-allocated fixed memory pool), a shared service region (dynamic buffer layer), and a low-priority task isolation region. This partitioning process achieves physical-level isolation through a hardware MMU (Memory Management Unit), ensuring independent memory access permissions for critical tasks.

[0050] In some exemplary embodiments, the method of dividing physical memory into several physically isolated memory regions based on a pre-built task criticality level model and setting differentiated access permissions for different memory regions includes: Initialize the hardware, obtain hardware parameters and physical memory distribution information, and establish a physical memory address mapping; The task criticality level model is constructed based on the functional requirements of the control terminal, and the correspondence between the task criticality level and the memory region is determined. The physical memory is divided into a high-priority task-specific area, a shared service area, and a low-priority task-isolated area. Configure different access permissions for the high-priority task exclusive area, the shared service area, and the low-priority task isolation area.

[0051] In specific implementation, based on a pre-built task criticality level model, physical memory is divided into several physically isolated memory regions, and differentiated access permissions are set for different memory regions, including: Hardware initialization and memory mapping establishment steps: The bootloader initializes the processor core, clock system and memory controller, reads hardware parameters to obtain physical memory distribution information, and establishes a physical memory address mapping table.

[0052] 1) Processor boot configuration: After power-on, the Bootloader code is executed to complete CPU core reset, clock system initialization (setting the PLL phase-locked loop to the system main frequency), memory controller (such as LPDDR4 controller) register configuration, and establish a communication channel between physical memory and bus interface.

[0053] By reading hardware parameters from the device tree or EEPROM, the total physical memory capacity and distribution information (such as starting address and bank division) can be obtained, and a memory physical address mapping table can be established.

[0054] 2) MMU page table initialization: Configure the page table base address register (TTBR) of the memory management unit (MMU) to establish the first-level page directory table (PGD) and the second-level page table (PTE).

[0055] Set memory access permissions: mark the high-priority task-specific area as read-only / executable (to prevent code tampering), set the shared service area to read-write (to support dynamic data interaction), and set the low-priority isolation area to read-write but prohibit interrupted access.

[0056] Task criticality level modeling and memory partitioning planning steps: Define task priority types according to the functional requirements of the control terminal, including high-priority real-time control tasks, medium-priority protocol parsing tasks, and low-priority log tasks, and solidify the binding relationship between priorities and memory regions through static configuration files.

[0057] 1) Definition and mapping of key levels: Based on the functional requirements of the load control terminal, a task priority model is defined as follows: High priority: Real-time control tasks (such as relay control, data acquisition, jitter tolerance <1 microsecond); Medium priority: Protocol parsing and middleware services (such as Modbus-TCP communication); Low priority: logging, non-real-time data analysis.

[0058] The binding relationship between priority and memory region is solidified through static configuration files (such as XML or binary mapping tables).

[0059] 2) Calculation of memory partition parameters: Based on historical load data analysis (offline testing or factory configuration), determine the memory usage percentage for each region: High priority area: 40%-50% of the total memory is reserved (fixed through a static pre-allocation algorithm); Shared service area: dynamic buffer layer, allocated on demand (initially 20% reserved); Low priority area: 30%-40% remaining (supports dynamic reclamation).

[0060] Example: If the total memory is 256MB, then 128MB will be allocated to the high-priority area (fixed pool), 51MB to the shared area, and 77MB to the low-priority area.

[0061] The steps for static partitioning and isolation of physical memory are as follows: Physical memory is divided into a high-priority task-specific area, a shared service area, and a low-priority task isolation area through the page table configuration of the Memory Management Unit (MMU), and a contiguous physical address range and access permissions are set for each area.

[0062] 1) Address space isolation technology High-priority exclusive zone: By setting a contiguous physical address range (e.g., 0x8000_0000-0x8200_0000) in the MMU page table, other tasks are prohibited from directly accessing it via DMA or peripherals.

[0063] Set the AP (Access Permission) bit to "privileged mode read / write only" in the page table entry to isolate user-mode tasks.

[0064] Shared service area: It employs dynamic page frame allocation, manages free pages through a Buddy System, and allocates memory blocks in 2KB / 4KB granularity on demand.

[0065] Configure domain access control to allow medium-priority tasks to read and write, but prohibit low-priority tasks from accessing across zones.

[0066] Low-priority isolation zone: The SLAB allocator is used to manage memory for small objects, and red-black tree indexes are used to accelerate garbage collection.

[0067] The Memory Protection Unit (MPU) can be used to set up an access violation interrupt to intercept illegal pointer operations.

[0068] 2) Implementation of the static pre-allocation algorithm High-priority memory pool persistence: Define a memory pool descriptor in the startup script, which includes the starting address, size, and allocation strategy (such as first-fit / best-fit).

[0069] The memory pool is initialized to 0xDEADBEEF mode using memset() to verify the integrity of physical memory.

[0070] Shared area dynamic buffer layer: Pre-allocate fixed-size memory page frames (e.g., 4KB per page) and maintain a free list to record available page frames.

[0071] A reference counting mechanism is used to manage the lifecycle of page frames. When a page frame is released, it is only marked as available, and the physical page is not immediately reclaimed.

[0072] Access control and security hardening steps: Set background area protection through the Memory Protection Unit (MPU), make unallocated memory inaccessible, and configure differentiated access permissions for each memory area, including privileged mode read and write only, and user read and write but prohibit interrupted access.

[0073] 1) Access permission level High priority zone: Only interrupt service routines (ISRs) and real-time kernel threads are allowed to access it; ordinary tasks will trigger memory access exceptions.

[0074] Shared service area: Medium-priority tasks request memory through system call interfaces (such as mmap()), and the kernel authorizes the task after verifying its priority.

[0075] Enable copy-on-write mechanism to prevent data contention among multiple tasks.

[0076] Low priority area: Non-privileged tasks are restricted to accessing memory-mapped files (mmap) only, and direct physical address operations are prohibited.

[0077] 2) Hardware-level protection Enable the MPU's background region to make unallocated memory inaccessible and prevent out-of-bounds access.

[0078] Configure a cache consistency protocol (such as MESI) to ensure data synchronization in the shared area under a multi-core environment.

[0079] Initialization verification and self-test steps: Through memory stress testing and real-time verification, verify data integrity and memory allocation latency to ensure jitter is less than 5 microseconds.

[0080] 1) Memory stress test Write all 0xAA mode to the high priority area and all 0x55 mode to the low priority area, and verify data integrity using CRC32.

[0081] Simulate memory leak scenarios (such as continuous memory allocation without release) to verify the effectiveness of the isolation mechanism.

[0082] 2) Real-time verification Use a high-precision timer (such as SysTick for ARM Cortex-M) to measure the time from triggering a critical task to memory allocation completion, ensuring jitter is <5 microseconds.

[0083] As an example, negative control terminal memory management based on the ARM Cortex-M7 platform: The processor includes: ARM Cortex-M7 (120MHz clock speed, 2MB Flash, 256MB LPDDR4).

[0084] The memory controller includes: LPDDR4 controller (timing configuration: tRCD=15 nanoseconds, tRP=15 nanoseconds, tRAS=35 nanoseconds).

[0085] Peripheral interfaces include: Ethernet MAC, CAN bus, RS485, and USB 2.0.

[0086] The security module includes a hardware encryption engine (supporting AES-256 / SHA-256).

[0087] As an example, the following verification tests were performed to verify the validity of this disclosure: The test items include high-priority area allocation latency, shared area write speed, and low-priority area reclamation efficiency.

[0088] The expected result for high-priority area allocation latency is ≤5 microseconds (from task triggering to memory allocation completion), while the actual measured data is 3.2 microseconds (captured by oscilloscope).

[0089] The expected write speed for the shared area was 120MB / s (continuous write test), and the actual measured speed was 118MB / s (CrystalDiskMark).

[0090] The expected result for low-priority area reclamation efficiency is to release 50MB of memory within 100 milliseconds, while the actual measured data is 89 milliseconds (Valgrind test).

[0091] Step S120: Based on the task criticality level model, pre-allocate memory for the task in the memory region corresponding to the corresponding task criticality level.

[0092] In practice, based on the task priority list, high-priority tasks are allocated fixed memory blocks in a dedicated area (using a static pre-allocation algorithm), medium-priority tasks are allocated dynamic memory blocks on demand in the shared service area, and low-priority tasks are allocated restricted memory in an isolated area through access control. During the pre-allocation phase, memory pool technology is used to solidify the memory block layout, avoiding runtime dynamic allocation contention. The memory block size for critical tasks is determined based on historical load data predictions.

[0093] In some exemplary embodiments, the step of pre-allocating memory for a task in the memory region corresponding to the corresponding task criticality level based on the task criticality level model includes: Determine task priority weights and predict memory usage using a sliding window averaging method based on historical load data; In the high-priority task-specific area, a fixed-size memory block is allocated using the first-fit algorithm; in the shared service area, a buddy system is used to dynamically manage the free list; and in the low-priority task isolation area, a memory pool is predefined, and fragmentation reclamation is accelerated using a red-black tree index. Set an access control matrix for each memory region; Perform real-time verification and stress testing; Adjust memory allocation parameters based on test results.

[0094] In specific implementation, the step of pre-allocating memory for a task in the memory region corresponding to the corresponding task criticality level based on the task criticality level model includes: Task priority modeling and memory requirement calculation steps: Calculate task priority weights based on task deadlines, task cycles, and jitter tolerance coefficients, and predict memory usage using the sliding window averaging method based on historical load data.

[0095] Task priority weight:

[0096] Where T critical T is the task deadline. period For the task period, Q latency Jitter tolerance factor (Q for high priority tasks) latency ≥1 microsecond).

[0097] Memory demand prediction model: Based on historical load data, the sliding window averaging method is used to predict memory usage:

[0098] Parameter description: α: Historical data weight (recommended value: 0.7~0.9); N: Number of sampling periods; A historic moment Memory usage; : Actual memory usage during the i-th run.

[0099] As an example, referring to the table below, the priority mapping rules are as follows: Priority mapping rule table

[0100] Where Mhigh represents the memory size allocated to high-priority tasks; Mmid represents the memory size allocated to medium-priority tasks; Mlow represents the memory size allocated to low-priority tasks; and Mtotal represents the total physical memory size of the system.

[0101] Memory pool initialization and static pre-allocation steps: In the high-priority task-specific area, a fixed-size memory block is allocated using the first-fit algorithm, and the memory block is initialized in magic number mode and its integrity is verified using CRC32. In the shared service area, a buddy system is used to dynamically manage free page frames and maintain a free linked list. In the low-priority task isolation area, a SLAB allocator is used to predefine the memory pool, and red-black tree indexing is used to accelerate fragmentation reclamation.

[0102] High-priority memory pool construction: Physical memory partitioning: Establishing a contiguous physical address space using the MMU page table: Starting address = Base high Size = M high =N page PageSize The page size is selected based on hardware characteristics (e.g., 4KB); Base high Represented as the starting address of the high-priority memory region; N page This represents the page number of a high-priority memory region.

[0103] Memory block solidification: A fixed-size block allocation is achieved using the First-Fit algorithm.

[0104] Each block is initialized to magic number mode (e.g., 0xDEADBEEF) and its integrity is verified using CRC32.

[0105] in, This is represented as the i-th bit of the "magic number" filled during memory initialization; This represents the i-th bit value of the pattern filled during memory initialization; This is represented as a modulo operation, which means performing a modulo operation on the result using a 32-bit unsigned integer.

[0106] Dynamic management of shared service areas: The Buddy System is implemented by dividing memory blocks into powers of 2 and maintaining free lists hierarchically.

[0107] in, Represented as the size of a memory block; This represents the minimum block size in memory allocation.

[0108] Choose the minimum that satisfies 2 during allocation. k Blocks ≥ RequestSize are merged with adjacent free blocks when released.

[0109] Low-priority area isolation mechanism: SLAB Allocator: Predefined memory pools based on object type (e.g., log structures), each SLAB contains: Slab = {Metadata + Object Array + Free Bitmap} Red-black tree indexing accelerates fragmentation reclamation, with node keys representing memory addresses.

[0110] Access control and security hardening steps: Set up an access control matrix for each memory region. High priority regions are only accessible to interrupt service routines and real-time kernel threads. Shared service regions allow medium priority tasks to request memory through system call interfaces. Low priority regions restrict non-privileged tasks to access memory only through memory-mapped files.

[0111] As an example, refer to the table below; the access control matrix is ​​as follows: Access Control Matrix Table

[0112] Among them, atomic operation guarantee: memory allocation / release uses LL / SC instructions to achieve lock-free operation.

[0113] Real-time verification and stress testing steps: Simulate memory flood tests and fragmentation resistance tests to verify allocation success rate and fragmentation entropy value, ensuring that the allocation success rate is not less than 99.99% and the fragmentation entropy value is less than 0.5.

[0114] Timing constraint verification: Critical path delay calculation:

[0115] in: T MMU Page table traversal delay (approximately 20 cycles for ARM Cortex-M7); T Cache Data prefetch latency (ignored when L1 cache is hit); T Lock Atomic operation time (approximately 3 cycles for LL / SC instructions); T DMADMA transfer time (if peripherals are involved).

[0116] Stress testing scenarios: 1. Memory surge test: Simulate 105 consecutive requests for low-priority memory blocks to verify the isolation zone reclamation mechanism:

[0117] A success rate of ≥99.99% is required.

[0118] 2. Fragment resistance test: Alternately allocate / release memory blocks of sizes alternating between 2k and 2k+1, and calculate the fragmentation entropy value:

[0119] Where pi is the proportion of the i-th type of fragment, and H < 0.5 (ideal uniform distribution).

[0120] The self-optimizing closed-loop mechanism steps are as follows: Based on the results of real-time verification and stress testing, the memory allocation parameters are dynamically adjusted. The memory allocation success rate and fragmentation entropy value are collected as feedback signals. The PID controller performs proportional-integral-derivative operations to output the adjustment amount of the pre-allocated memory block size. The updated memory allocation strategy is deployed at a fixed cycle of no more than 24 hours.

[0121] In practical implementation, the following parameters are optimized through a self-optimizing closed-loop mechanism: The offset or coefficient in the dynamic threshold (Threshold(t)) for defragmentation triggering: causes the system to trigger defragmentation earlier or later.

[0122] Thresholds used for decision-making in memory prediction models: such as the trigger threshold for the Memory Stress Index (MPI).

[0123] Weights in the allocation strategy: Weight parameters of the Q-learning algorithm when selecting allocation regions (high / medium / low priority).

[0124] The frequency of timed scanning of low-priority areas (Tscan) or the idle condition (β value).

[0125] Aggressiveness of memory compression operations: the criteria used by the compression algorithm to merge free blocks.

[0126] Dynamic adjustment algorithm: Adaptive memory block size: Adjusts pre-allocation granularity based on historical allocation records.

[0127] Where σ² is the memory request variance and λ is the decay factor (recommended to be 0.1~0.5).

[0128] Defragmentation trigger conditions: Sorting will be initiated when any of the following conditions are met:

[0129] in, This is expressed as the ratio of currently free memory to total memory. Represented as memory fragment entropy value; This is expressed as the rate of change of the current memory fragmentation over time, i.e., the rate at which the degree of fragmentation changes over time.

[0130] Step S130: Monitor the memory fragmentation distribution status during the task's execution to obtain the fragmentation entropy value. In response to the fragmentation entropy value being greater than the fragmentation entropy value threshold, execute differentiated fragmentation defragmentation strategies for different memory regions.

[0131] In practice, the task monitors the memory block distribution in real time during runtime and quantifies the degree of memory fragmentation using a fragmentation entropy algorithm. When the fragmentation entropy value exceeds a dynamic threshold, a defragmentation mechanism is triggered: a copying defragmentation algorithm is used for high-priority areas (preserving critical data), a mark-and-sweep algorithm is used for shared areas, and a lazy defragmentation strategy is used for low-priority areas. The defragmentation process ensures task continuity through atomic operations, avoiding service interruptions.

[0132] In some exemplary embodiments, monitoring the memory fragmentation distribution status during task execution yields a fragmentation entropy value. In response to the fragmentation entropy value exceeding a fragmentation entropy threshold, a differentiated defragmentation strategy is executed for different memory regions, including: Scan the page table entries of each memory region to calculate the fragment entropy value; The fragment entropy threshold is calculated based on the sliding window mean and standard deviation. In response to the fragment entropy value being greater than the fragment entropy value threshold, a copy-and-sweep algorithm is used to migrate key data in the high-priority area, a mark-and-sweep algorithm is used to merge free blocks in the shared service area, and a lazy compaction strategy is used to release idle memory in batches in the low-priority area. Hardware-level memory barriers are inserted before and after the compaction operation. A software transactional memory mechanism is used to perform page table updates and free list modifications. During the compaction process, high-priority task preemption is prohibited and low-priority interrupts are masked.

[0133] In specific implementation, the monitoring of the memory fragmentation distribution status during the task execution yields a fragmentation entropy value. In response to the fragmentation entropy value exceeding a fragmentation entropy threshold, differentiated defragmentation strategies are executed for different memory regions, including: Real-time monitoring and quantitative evaluation of memory fragmentation steps: Scan page table entries of each memory region at fixed intervals, count the number of free pages, the sequence of the longest consecutive free pages, and the fragmentation flag of allocated pages, and dynamically calculate the fragmentation entropy value H(t) based on the fragmentation type weight function and probability density function.

[0134] Fragment distribution status monitoring mechanism: Dynamic page table scanning: This method uses a hardware page table walk (HTW) mechanism to scan the page table entries of each memory region at a frequency of Tscan = 100 milliseconds for low-priority areas.

[0135] Key statistical indicators: Number of free pages: Fk; The maximum consecutive free page length sequence L = {l1, l2, ..., lm}; The fragmentation flag of the allocated page is FragFlagi (0: unfragmented, 1: fragmented).

[0136] Dynamic calculation of fragment entropy: Define the fragment type weight function w(l):

[0137] in: minOrder=4 (minimum number of consecutive pages); maxOrder=12 (maximum number of consecutive pages).

[0138] Fragment entropy calculation formula:

[0139] in: (Probability density function) I(·) is an indicator function (1 if the condition is met, 0 otherwise); Dynamic threshold determination model: The threshold is determined using the sliding window mean-standard deviation method:

[0140] in: μH(t): The sliding window mean of fragment entropy values ​​over the past 30 seconds; σH(t): corresponding standard deviation; Triggering condition: Defragmentation is initiated when H(t) > Threshold(t).

[0141] Defragmentation strategy selection and execution steps: When the fragmentation entropy value exceeds the dynamic threshold calculated based on the sliding window mean and standard deviation, a differentiated defragmentation strategy is triggered. In the high-priority area, a copy-based defragmentation algorithm is used to migrate key data. In the shared service area, a mark-and-sweep algorithm is used to merge free blocks. In the low-priority area, a defragmentation strategy is used to release idle memory in batches.

[0142] Regional Differentiation Strategy Decision Tree: if region == high priority region then Perform copy-based organization elif region == shared area then Execute the mark-and-sweep algorithm else Perform lazy compaction end High-priority area copy-and-containment: Key data identification: Mark key data regions using the memory access heatmap associated with the Task Control Block (TCB):

[0143] If CriticalData(addr) > θ c (threshold θ) c If the value is 0.8, it is marked as non-migratable.

[0144] Memory block migration process: 1. Create a temporary mirror buffer (size is 15% of the total capacity of the high-priority area). 2. Execute the two-pointer in-place copy algorithm: new_ptr=memcpy( tmp_buf , old_ptr , BlockSize ) 3. Update page table mappings: TLBFlush old_vaddr ) → Map ( new_paddr → old_vaddr ) Shared area marking-cleanup algorithm: Garbage marking phase: Suspend medium-priority tasks (pause time t) suspend <50 microseconds); Traverse the shared area page table and mark the active objects:

[0145] Memory reclamation phase: 1. Merge adjacent free blocks:

[0146] 2. Release inactive objects:

[0147] Lazy compaction of low-priority areas: Recycle window mechanism: Maintenance Time Window Window size T window =5 seconds Recycling conditions:

[0148] Where β = 0.7 (empirical threshold).

[0149] Batch release strategy: Page-aligned aggregation release: ReleaseBatch(start,end)=Unmap(start)→ZeroPage(start)→ReturnToPool(start) The atomicity guarantee mechanism steps of the compaction process are as follows: hardware-level memory barrier instructions are inserted before and after the compaction operation, software transaction memory mechanism is used to ensure the atomicity of page table updates and free list modifications, and high-priority tasks are prohibited from preemption for up to 200 microseconds during compaction, while only low-priority interrupts are masked.

[0150] Lock-free memory operation protocol: Memory barrier insertion: Inserting hardware-level memory barriers before and after the defragmentation operation. DMB SY; Ensures the order of memory operations; ISB; Refresh instruction pipeline; Transactional memory updates: Employing a software transactional memory (STM) mechanism. stm_start_transaction(); / / Perform page table update / / Modify the free list if (stm_commit_transaction()) { / / Submission successful } else { / / Rollback operation } Real-time security measures: Preemption Prohibition Window: High-priority tasks are prohibited from preempting during the cleanup period, with a time limit of T. preempt_ban =200 microseconds; Interrupt masking strategy: Only mask low-priority interrupts (such as logging interrupts) and retain high-priority interrupts (such as fault alarms); The defragmentation effect evaluation steps are as follows: calculate the length of the maximum continuous free block after defragmentation, which should be no less than 2minOrder+2; measure the change rate of memory allocation latency for critical tasks, which should be less than 5%; and update the fragment entropy threshold based on reinforcement learning.

[0151] Post-processing verification workflow: 1. Memory continuity measure: Calculate the length of the maximum contiguous free block Lmax after reorganization:

[0152] Target:

[0153] in, This represents the length of the largest contiguous free memory block after a memory defragmentation operation (such as defragmentation, memory compaction, etc.) has been completed.

[0154] 2. Performance rollback detection: Measure the rate of change in memory allocation latency for critical tasks:

[0155] Require

[0156] in, This represents the latency of memory allocation before memory defragmentation or optimization operations. This represents the latency of memory allocation after a memory defragmentation or optimization operation.

[0157] 3. Adaptive parameter tuning: Update the fragment entropy threshold based on reinforcement learning:

[0158] in: η = 0.05 (learning rate) Htarget = 0.3 (target entropy value) This represents the entropy value of memory fragmentation at the current moment.

[0159] Step S140: Predict memory pressure based on a pre-built load prediction model; in response to the predicted memory pressure being greater than a memory pressure threshold, perform data migration and physical memory expansion.

[0160] In practice, historical task cycles are analyzed based on an LSTM load prediction model to predict future memory demand trends. When memory pressure is predicted to exceed a threshold, inactive memory pages in low-priority areas are swapped to external storage using virtual memory mapping technology, while physical memory modules are expanded as needed. The expansion process employs a gradual plug-in strategy, using a DMA controller to achieve seamless switching between old and new memory, ensuring zero impact on critical tasks.

[0161] In some exemplary embodiments, the prediction of memory pressure based on a pre-built load prediction model, and the data migration and physical memory expansion performed in response to the predicted memory pressure exceeding a memory pressure threshold, include: Input the task execution time, memory allocation, interrupt triggering frequency, and operation intensity into the load prediction model to obtain the memory pressure output by the load prediction model; Page activity is statistically analyzed by accessing page table entries, inactive memory pages are identified, and they are sorted by access frequency. Inactive memory pages are then migrated to external storage, and a circular buffer is used to manage the migration task. Configure the memory controller to connect to the new memory module, reconfigure the page table of the memory management unit to expand the virtual address space, adopt a progressive plug-in strategy to migrate data in stages, and use a weighted round-robin scheduling algorithm to allocate bandwidth.

[0162] In specific implementation, the memory pressure is predicted based on a pre-built load prediction model. In response to the predicted memory pressure exceeding a memory pressure threshold, data migration and physical memory expansion are performed, including: Memory demand forecasting and dynamic expansion decision steps: Construct an LSTM load forecasting model, with input features including task execution time, memory allocation, interrupt triggering frequency and I / O operation intensity, outputting future memory demand forecasts, and minimizing the forecast error through the Adam optimizer; calculate the memory stress index MPI(t), and trigger expansion when MPI(t) is greater than 0.85 or the growth rate per minute is greater than 0.1.

[0163] 1.1 Construction of LSTM Load Prediction Model 1. Input Feature Engineering: Extracting historical task periodic feature vector x t :

[0164] in: T exec (t): Task execution time; M alloc (t): Memory allocation amount; I freq (t): Interrupt trigger frequency; Cio (t): I / O operation intensity.

[0165] 2. LSTM network structure: A three-layer stacked LSTM model is used, with hidden layer dimension H=128 and the output layer being a single neuron:

[0166]

[0167]

[0168]

[0169] +

[0170] tanh ( ) in, This represents the output of the Forget Gate at time step t; Represented as the Sigmoid activation function; Represented as the weight matrix of the forget gate; This is represented as the input feature vector at the current time step t; Represented as the bias vector of the forget gate; This is represented as the output of the input gate at time step t; It is represented as the weight matrix of the input gate; It is represented as the bias vector of the input gate; This represents the output of the output gate at time step t; This is represented as the weight matrix of the output gate; This is represented as the bias vector of the output gate; This is represented as the value of the candidate cell state at time step t; The weight matrix is ​​represented as the candidate cell state. Represented as a bias vector of candidate cell states; This represents the value of the hidden state at time step t.

[0171] The output layer activation function uses ReLU:

[0172] in, This is represented as the weight matrix of the LSTM output layer; This is represented as the bias vector of the LSTM output layer.

[0173] 3. Prediction error optimization: Use mean squared error (MSE) as the loss function:

[0174] Where T represents the length of the time series.

[0175] Update parameters using the Adam optimizer:

[0176] Among them η=0.001, β1=0.9, β2=0.999, =1e 8; This is expressed as the first moment estimate of the gradient, i.e., the exponentially weighted moving average of the gradient; This is expressed as the gradient at time step t; It is expressed as the second moment estimate of the gradient, i.e., the exponentially weighted moving average of the squared gradient; This is represented as the model parameters at time step t.

[0177] 1.2 Dynamically Expanding Decision-Making Mechanism 1. Memory stress index calculation: Define the Memory Stress Index (MPI):

[0178] in: M used (t): Current memory usage; σ alloc (t): Standard deviation of distribution rate; μ alloc (t): Mean distribution rate.

[0179] 2. Extended trigger conditions: The extension is activated when any of the following conditions are met:

[0180] Virtual memory mapping and data migration steps: Page activity is counted by accessing page table entries, inactive memory pages are identified and sorted by access frequency; inactive memory pages are migrated to external storage using the DMA controller, and the migration task is managed by a circular buffer.

[0181] 2.1 Identification of Inactive Memory Pages 1. Page visit frequency statistics: Page activity is measured using the page table entry access bit:

[0182] Set threshold θ active =0.2, pages with a value lower than this are marked as inactive.

[0183] 2. Page priority sorting: Sort by popularity level:

[0184] Where α=0.7 controls the weight of hot and cold data.

[0185] 2.2 External Storage Interaction Protocol 1. Data migration process: As an example, see reference Figure 2 ,in: Select inactive pages to generate a migration task queue; Determine if the DMA is idle; If DMA is idle, initiate DMA transfer, update page table mapping, and release physical memory; If the DMA is not idle, insert it into the wait queue.

[0186] 2. Asynchronous transmission control: Migration tasks are managed using a ring buffer:

[0187] The flow control mechanism is triggered when BufferStatus(t) > 0.9.

[0188] Physical memory expansion and seamless switching steps: Configure the memory controller to connect the new memory module through the SMBus / IC interface, reconfigure the MMU page table to expand the virtual address space; adopt a progressive plug-in strategy to migrate data in stages, including first migrating low-priority cold data, then migrating medium-priority non-real-time data, and finally migrating high-priority redundant cache; use a weighted round-robin scheduling algorithm to allocate DMA bandwidth to ensure that the bandwidth ratio of high-priority tasks is not less than 60%.

[0189] 3.1 Dynamic Memory Module Access 1. Hardware Interaction Protocol: Configure the memory controller via the SMBus / I²C interface: CommandSequence=[CMD_INIT, CMD_IDENTIFY, CMD_ENABLE] Complete voltage matching (e.g., LPDDR4-3200) and clock synchronization for new memory modules.

[0190] 2. Address space expansion: Reconfigure the MMU page tables to expand the virtual address space: NewTTBR=OldTTBR∨(0x1< <BankSelectBits) Where BankSelectBits=2 indicates that a new memory Bank has been added.

[0191] 3.2 Progressive Insertion / Removal Strategy 1. Staged transfer algorithm: Memory expansion is divided into three stages: Phase 1: Migrating low-priority cold data Phase 2: Migrating high-priority non-real-time data Phase 3: Migrating high-priority redundant caches The completion rate for each stage must meet the following requirements:

[0192] 2. DMA scheduling strategy: Bandwidth is allocated using a weighted round-robin scheduling algorithm:

[0193] in Ensure that high-priority tasks account for no less than 60% of the bandwidth.

[0194] Data integrity verification and performance assurance steps: Calculate CRC32 check values ​​for each block of migrated data to verify consistency; reserve a 5-microsecond buffer to absorb migration jitter and maintain the dual mapping relationship between the old and new addresses, and switch the mapping pointer during the system's idle window.

[0195] 4.1 Migration Consistency Verification 1. CRC32 segmentation check: Calculate checksums for each block of migrated data: CRC block (p)=crc32(PageData(p),PageSize) Receiver verification formula:

[0196] 4.2 Real-time performance guarantee measures 1. Interruption delay compensation: Reserved time buffer T buffer =5 microseconds, used to absorb migration jitter:

[0197] 2. Dual buffer switching: Maintain the dual mapping relationship between the old and new memory:

[0198] Switching time T switch Choose during the system's idle window period.

[0199] in, This indicates the moment of memory mapping switching, that is, the point in time when switching from the old memory mapping to the new memory mapping.

[0200] Error handling and rollback mechanism steps: During data migration and expansion, a transactional migration protocol that meets ACID properties is adopted; when an error occurs or verification fails during the migration process, a fast rollback strategy is initiated. The fast rollback strategy includes: rolling back the page table to the previous stable state, reinitializing the affected memory area, and requiring all rollback operations to be completed within 200 microseconds.

[0201] 5.1 Recovery from Migration Failure 1. Transactional migration protocol: Each migration task must satisfy ACID properties: Atomicity: Migration progress is recorded via logs; Consistency: Checksum and double verification; Isolation: Prioritized isolation to prevent interference; Persistence: Refresh the TCM cache after updating the page table.

[0202] 2. Fast rollback strategy: When a migration error is detected: Rollback()→RevertPageTable()→Re-initializeMemory() The rollback operation must be completed within 200 microseconds.

[0203] Step S150: In response to the completion of the task, reclaim the memory resources occupied by the task, and optimize the fragment entropy threshold and the memory pressure threshold based on the fragment entropy value.

[0204] In practice, upon completion of a task, the memory blocks it occupies are immediately reclaimed and marked as available. Free memory blocks are reorganized using a memory compression algorithm, and subsequent allocation strategies are optimized based on fragmentation entropy assessment results. Low-priority areas utilize a timed scanning mechanism to automatically release idle memory, while high-priority memory blocks are immediately reset to their pre-allocated state after task completion, forming a self-optimizing closed loop for memory management.

[0205] In some exemplary embodiments, the step of reclaiming the memory resources occupied by the task in response to the completion of the task execution, and optimizing the fragmentation entropy threshold and the memory pressure threshold based on the fragmentation entropy value, includes: When a task enters a completed or abnormally terminated state, the occupied memory block is reclaimed and a status mark is made. In response to the number of consecutive free pages being less than the threshold for consecutive free pages, an object compaction and page-level merging algorithm is used to aggregate free memory; The fragment entropy value is calculated by combining the page-level fragment distribution and the change rate over time, and a dynamic threshold is generated based on the exponentially weighted moving average. Optimization is triggered when the fragment entropy value is greater than the threshold. Adjust the size of pre-allocated memory blocks based on historical allocation variance and optimize memory region allocation weights; The scan cycle is calculated based on the average allocation rate of the low priority area. When the idle time of a memory block is greater than the preset proportion of the time window, it is marked as reclaimable. When switching task contexts, reset the high-priority memory blocks to their pre-allocated state; The memory allocation success rate, average allocation latency, and fragmentation entropy are collected as feedback signals to calculate the parameter adjustment amount, and optimization strategies are deployed based on the parameter adjustment amount.

[0206] In specific implementation, in response to the completion of the task, the memory resources occupied by the task are reclaimed, and based on the fragmentation entropy value, the fragmentation entropy threshold and the memory pressure threshold are optimized, including: Memory reclamation and status marking steps: When a task enters a completed or abnormally terminated state, the memory block it occupies is immediately reclaimed, and dirty pages are marked through page table entries and the last access time is recorded with an additional timestamp.

[0207] Task termination response mechanism 1. Resource release trigger conditions: When the task state machine enters the TASK_COMPLETED or TASK_ABORTED state, the recycling process is initiated immediately:

[0208] 2. Memory block reclamation process: As an example, refer to Figure 3 ,in: Release the request and perform a memory block status check; If the memory block is clean, it is directly reclaimed, the free list is updated, and the fragment entropy value is adjusted. If the memory block is marked as dirty, perform a write-back operation to reclaim it directly, update the free list, and adjust the fragment entropy value.

[0209] 3. Status marking specification: Dirty page indicator: A page has been modified by marking the Dirty bit in a page table entry. Lifecycle tag: Includes a timestamp recording the last access time.

[0210] Priority tag: Inherits the original task priority for subsequent allocation strategies. Memory compression and reorganization steps: When the number of consecutive free pages is less than 2^minOrder, compression is initiated. SLAB object compaction and page-level merging algorithms are used to aggregate free memory, and the compression ratio is required to be no less than 30%.

[0211] Free memory aggregation algorithm 1. Compression trigger conditions: When the number of consecutive free pages Ncontiguous < 2 minOrder Start compression at time:

[0212] 2. Memory compression strategy: SLAB object compaction: CompactSlab(s) = Memcpy(s) >newbase,s >base,s >size) Eliminate internal fragmentation by copying the object and update the bitmap marker.

[0213] Page-level merging algorithm:

[0214] 3. Compression efficiency evaluation: Compression ratio calculation formula:

[0215] Target: CR ≥ 30% in typical scenarios Fragment entropy dynamic evaluation steps: Calculate fragment entropy H(t) by combining page-level fragment distribution and time dimension change rate, and generate dynamic threshold based on exponential weighted moving average. Optimization is triggered when H(t) is greater than the threshold.

[0216] Fragmentation Quantification Model 1. Entropy calculation formula: Combining page-level fragmentation distribution with the time dimension:

[0217] in: S i (t): The proportion of fragment of type i λ: Time decay factor (recommended value: 0.01) dT / dt: Fragmentation growth rate : The total size of all memory fragments in the current system.

[0218] 2. Dynamic threshold generation: Based on EWMA (Exponential Weighted Moving Average):

[0219] Where α = 0.3, optimization is triggered when H(t) > Threshold(t).

[0220] The dynamic optimization steps of the allocation strategy are as follows: adjust the size of the pre-allocated memory block based on the historical allocation variance, and optimize the memory region allocation weights through the Q-learning algorithm.

[0221] Adaptive allocation parameter adjustment 1. Granularity calculation: Adjust pre-assigned size based on historical allocation variance:

[0222] Where σ 2 To determine the size variance, λ = 0.05 controls the sensitivity.

[0223] 2. Adjustment of regional allocation weights: Optimize allocation priority using the Q-learning algorithm:

[0224] The state s represents the current memory pressure, and the action a selects the allocation region (high / medium / low priority).

[0225] Low-priority area timed scan steps: The scan cycle is calculated based on the average allocation rate of low-priority areas, with a default of 5 seconds. When a memory block is idle for more than 70% of the time window, it is marked as reclaimable.

[0226] Automatic release mechanism for idle memory 1. Scan cycle calculation:

[0227] Where μ alloc The average allocation rate is set for low-priority areas.

[0228] 2. Release condition determination: Python code: if IdleTime(block) > β T_window: if block.last_access_time <T_window_start: mark_as_reclaimable() Where β = 0.7, T window =5 seconds.

[0229] High-priority area pre-allocation reset steps: When switching task contexts, immediately reset the high-priority area memory block to the pre-allocation state and fill it with magic number mode to verify integrity via CRC32.

[0230] Task context switching handling 1. Memory block reset process: As an example, see reference Figure 4 ,in: The task is terminated; check for any residual data. If not, skip erasure, reset page table properties, inject magic number mode, and update CRC checksum; If so, perform a secure erase, reset page table attributes, inject magic number mode, and update CRC checksum.

[0231] 2. Magic Number Pattern Injection: Populate the memory pool using a specific pattern:

[0232] Integrity is ensured through CRC32 checksum verification:

[0233] The closed-loop feedback mechanism steps are as follows: collect memory allocation success rate, average allocation latency and fragment entropy value as feedback signals, adjust the output parameters through the PID controller, and deploy and update the strategy every 24 hours. The error signal e(t) is the difference between the target entropy value and the current entropy value.

[0234] Self-optimizing control loop: 1. Feedback signal acquisition: Memory allocation success rate S alloc Average distribution delay T avg Fragment entropy value H.

[0235] 2. Control strategy generation: Use a PID controller to adjust and optimize parameters:

[0236] The error signal Parameter K p =0.5, K i =0.1, K d=0.05; This is expressed as the fragmentation error at time t; It is expressed as a time step, which is the amount of change over time.

[0237] 3. Strategy deployment cycle: The policy is updated every 24 hours.

[0238] in, This represents the time interval for policy updates; This is represented as the initial time reference point.

[0239] The following application examples illustrate the solutions provided in this disclosure: Application Example 1: Fault Handling and Recovery of Power Load Control Terminals During Peak Electricity Consumption Periods The power grid in a certain region has entered the peak summer electricity consumption period, and the power load control terminal is operating stably. Suddenly, the system detects a current overload on a feeder, requiring immediate execution of a series of operations: quickly disconnecting non-critical loads (such as billboard lighting), recording fault data, analyzing the cause of the event, and reporting it to the main station.

[0240] Instance process description 1. System startup and steady-state operation: The terminal device powers on and starts up. During the system initialization phase, the Memory Management Unit (MMU) has strictly divided the 256MB of physical memory into three regions according to the preset criticality level model: High-priority area (128MB): Dedicated to real-time tasks such as "relay control" and "three-phase power acquisition". This area has been pre-allocated as fixed-size memory blocks and marked as accessible only in privileged mode.

[0241] Shared service area (50MB): Used for medium-priority services such as "Modbus-TCP communication protocol stack" and "data preprocessing", and is dynamically managed using a partner system.

[0242] Low priority zone (78MB): Used for background tasks such as "run log recording" and "historical data statistical analysis", and managed by the SLAB allocator.

[0243] The system enters a steady state, and each task runs normally in its respective memory region. The fragmentation monitoring module quietly scans the memory layout every 100 milliseconds, and the calculated fragmentation entropy value is low (0.2), indicating that the memory is healthy.

[0244] 2. Emergency Triggering and High-Priority Task Response: An overcurrent alarm triggers a high-priority interrupt. The "Relay Tripping Control" task is immediately activated.

[0245] Zero contention allocation: Since the memory block required by this task has been statically pre-allocated from its dedicated high-priority memory pool when the system starts, it does not need to wait for dynamic allocation and directly obtains memory from a fixed address for calculating control parameters and generating tripping instructions.

[0246] Extreme real-time performance: The entire latency from task triggering to memory access completion was measured at 3.2 microseconds, far below the design requirement of 5 microseconds, ensuring that the relay can act within milliseconds, successfully disconnect the load, and prevent the accident from escalating.

[0247] 3. Concurrent task execution and dynamic memory management: At the same time the relay activates, other tasks are also triggered: Medium-priority tasks: The "Fault Data Recording" task dynamically requests memory from the shared service area to cache power waveform data before and after the fault. The partner system quickly allocates a contiguous block of memory of the required size. The "Communication Service" task also requests memory, preparing to package and upload brief fault information to the main station.

[0248] Low-priority tasks: A "detailed event analysis" task is created, which allocates memory in a low-priority isolation area for in-depth analysis of the cause of failure. The memory access of this task is monitored by the MPU and will not interfere with high-priority tasks.

[0249] 4. Memory pressure prediction and dynamic scaling: The fault handling caused a surge in memory requests within a short period of time. The system's built-in LSTM prediction model analyzed current and historical data (such as memory allocation rate and task cycle) and predicted that the Memory Stress Index (MPI) would exceed the threshold of 0.85 within the next 30 seconds.

[0250] Proactive scaling decision: The system decides to initiate a memory scaling process instead of waiting for memory to run out.

[0251] Seamless data migration: The memory management module first identifies "inactive" log data pages that have not been accessed recently in the low-priority area, and then silently swaps these pages to external Flash storage via the DMA controller. This process is completely transparent (zero-awareness) to the critical tasks being executed. The freed-up physical memory is incorporated into the shared service area to handle any subsequent data flows.

[0252] 5. Closed loop of task completion and resource recycling: After the fault handling sequence is completed: Immediate memory reclamation: After the "relay control" task completes, the high-priority memory blocks it occupies are immediately reset and marked as available, awaiting the next task invocation. Faulty data packets in the shared area are also immediately released after being successfully sent to the master station.

[0253] Self-optimization: After resource reclamation, the defragmentation mechanism is triggered, lightly compressing the shared area and merging free blocks. The system records the peak memory usage and allocation latency of various tasks during this event. This data will be used to fine-tune future memory prediction models and allocation strategies (e.g., slightly increasing the initial reservation ratio of the shared area), forming a closed loop of continuous optimization.

[0254] Application Example 2: Memory Management Scenario of Load Control Terminal in Intelligent Power Distribution System A smart power distribution system in a certain region has deployed a load control terminal based on ARM Cortex-M7, which is responsible for real-time monitoring of line status, controlling circuit breaker operation, communicating with the master station, and recording operation logs. The terminal has 256MB of physical memory in LPDDR4 and needs to handle high real-time control tasks, medium-priority communication tasks, and low-priority logging tasks simultaneously.

[0255] 1. System startup and memory partition initialization: Device power-on: After the terminal starts up, the bootloader initializes the CPU clock to 480MHz and configures the LPDDR4 controller timing (tRCD=15 nanoseconds, tRP=15 nanoseconds).

[0256] Memory allocation: Based on a preset task criticality level model: High priority area (128MB): Dedicated to relay control and data acquisition tasks. It is fixedly mapped to physical addresses 0x80000000-0x80800000 through the MMU page table, and the permissions are set to "privileged mode read and write only".

[0257] Shared service area (50MB): Used for Modbus-TCP protocol parsing tasks, supporting dynamic allocation of 4KB memory pages.

[0258] Low priority area (78MB): Used for logging tasks, small memory objects are managed by the SLAB allocator.

[0259] Security hardening: Enable MPU background area protection, and set unallocated memory to inaccessible to prevent out-of-bounds operations.

[0260] 2. Task execution and real-time memory allocation: High-priority tasks (relay control): Once the task is triggered, a fixed memory block is allocated directly from the high-priority memory pool (the pre-allocation algorithm ensures a latency of ≤3.2 microseconds).

[0261] The memory block is initialized to 0xDEADBEEF mode, and CRC32 checksum ensures data integrity.

[0262] Medium priority tasks (Modbus-TCP communication): The protocol parsing task dynamically requests a 256KB buffer in the shared area through the buddy system for message assembly.

[0263] The system calls an interface to verify task priority before authorizing access, and a copy-on-write mechanism avoids data races.

[0264] Low-priority tasks (logging): The log module allocates 16MB of space in the low-priority area using a red-black tree index to record the device's operating status.

[0265] If an unauthorized area is accessed, the MPU triggers an interrupt and logs the security event.

[0266] 3. Fragmentation organization and real-time performance guarantee: Fragmentation monitoring: The system scans the page table every 100 milliseconds and calculates the fragmentation entropy value. When the entropy value exceeds a dynamic threshold (e.g., 0.6), defragmentation is triggered.

[0267] Differentiated reorganization strategy: High-priority area: Copy-based cleanup. Non-critical data is migrated to a temporary buffer (occupying 15% of the capacity), page table mappings are updated, and relay control tasks are ensured to be unaffected.

[0268] Shared area: Mark-sweep algorithm. Pause the Modbus-TCP task (<50 microseconds), mark active objects, and then merge free blocks.

[0269] Low priority area: Lazy compaction. Release idle memory in batches during system idle periods (e.g., no log writes within 5 seconds).

[0270] Atomic operation safeguards: During the compaction process, a memory barrier instruction is inserted to prevent high-priority task preemption (up to 200 microseconds), only log interrupts are masked, while fault alarm interrupts are retained.

[0271] 4. Dynamic memory expansion and load prediction: Load forecasting: The LSTM model analyzes historical data (such as task execution time and interrupt frequency) to predict future memory requirements. Expansion is triggered when the Memory Stress Index (MPI) > 0.85 or the growth rate per minute > 10%.

[0272] Data migration: Identify inactive log pages (access frequency < 0.2) in low-priority areas and migrate them to an external SD card via DMA.

[0273] The incremental expansion is divided into three phases: first, migrate cold data; then, migrate non-real-time protocol data; and finally, migrate redundant cache.

[0274] Seamless switching: The dual mapping mechanism ensures uninterrupted Modbus-TCP communication during the extension process, the switching point is selected during the system idle period, and the delay compensation of 5 microseconds absorbs jitter.

[0275] 5. Resource recycling and self-optimizing closed loop: Reclaiming memory upon task completion: When the Modbus-TCP session ends, shared memory is immediately released to the free list; after the log task is completed, low-priority memory is marked as reclaimable.

[0276] Compression and Reorganization: When there are fewer than 16 consecutive free pages, SLAB object compaction is initiated, with a compression ratio of up to 35%.

[0277] Adaptive optimization: The allocation granularity is dynamically adjusted based on the fragment entropy value (e.g., reducing the block size when the request variance is large).

[0278] The Q-learning algorithm optimizes the allocation of weights to different regions, prioritizing high-priority tasks.

[0279] The PID control parameters are updated every 24 hours based on indicators such as allocation success rate (>99.99%) and delay (Δ<5%).

[0280] As can be seen from the above, the memory management method provided in this disclosure includes: dividing physical memory into several physically isolated memory regions based on a pre-built task criticality level model, and setting differentiated access permissions for different memory regions; pre-allocating memory for tasks in the memory regions corresponding to the corresponding task criticality level based on the task criticality level model; monitoring the memory fragmentation distribution status during task execution to obtain fragmentation entropy values, and executing differentiated defragmentation strategies for different memory regions in response to the fragmentation entropy value being greater than a fragmentation entropy value threshold; predicting memory pressure based on a pre-built load prediction model, and performing data migration and physical memory expansion in response to the predicted memory pressure being greater than a memory pressure threshold; and reclaiming the memory resources occupied by the task in response to the completion of task execution, and optimizing the fragmentation entropy value threshold and the memory pressure threshold based on the fragmentation entropy value.

[0281] This ensures the strict real-time performance of high-priority real-time tasks.

[0282] The key to this invention lies in constructing a three-level collaborative mechanism of hardware isolation architecture, intelligent optimization engine, and closed-loop self-regulating system: First, physical-level memory partitioning is achieved through MMU / MPU (static pre-allocation of a fixed pool in the high-priority area / dynamic management of the shared area by the partner system / isolation and reclamation of the low-priority area by SLAB), combined with AP permission bits and domain control to eliminate task interference; Second, the degree of fragmentation is dynamically quantified based on the fragmentation entropy model (triggering differentiated reorganization of high-priority area data migration / shared area marking and cleaning / low-priority area batch release), and cold data pre-migration is achieved by using LSTM network to predict load trends; Finally, the allocation parameters are dynamically tuned by PID controller (with fragmentation entropy error driving allocation granularity optimization) combined with 24-hour reinforcement learning strategy updates to form a self-optimizing closed loop.

[0283] Hardware isolation architecture: including physical partitioning rules for three-level memory regions, MMU / MPU access control matrix and magic number mode verification mechanism; Intelligent optimization engine: fragment entropy dynamic threshold algorithm, LSTM load prediction model structure and progressive plug-in / plug-out strategy process; Closed-loop control system: Adaptive tuning logic based on PID parameters, fragmentation defragmentation trigger condition decision tree and transactional migration protocol; Industrial control applications: Zero-interruption guarantee scheme for high-priority tasks, and implementation method of fragmentation rate <5% in 256MB memory scenarios.

[0284] This invention addresses the problem of uncontrolled latency in critical tasks caused by mixed memory management in existing embedded real-time systems. Because traditional memory allocation mechanisms do not isolate tasks by priority (high and low priority tasks share memory space), high-priority tasks (such as relay control) are easily interfered with by low-priority tasks (such as log writing blocking) during memory allocation, resulting in real-time jitter exceeding 1 microsecond. At the same time, the accumulation of fragments in dynamic memory allocation causes a surge in allocation latency (sudden tasks need to traverse the fragment space), and the lack of a predictive mechanism causes memory expansion to lag (expansion response time > 100 milliseconds). To this end, this invention achieves its purpose through three-level hardware isolation + entropy warning + predictive expansion: ① Constructing physical isolation regions based on MMU / MPU (static solidification of high-priority areas / dynamic allocation by the shared area's partner system / lazy reclamation of low-priority areas) to eliminate interference between tasks; ② Real-time calculation of fragment entropy values ​​triggering differentiated defragmentation (migrating key data in high-priority areas / marking and cleaning in shared areas / batch release in low-priority areas), compressing defragmentation time to within 200 microseconds; ③ Predicting memory requirements through an LSTM model (inputting time-series characteristics such as task cycle and allocation amount), initiating cold data migration and gradual expansion when the pressure index > 0.85, ensuring zero-interruption execution of high-priority tasks, and ultimately achieving industrial-grade deterministic assurance of fragmentation rate < 5% and allocation jitter < 2 microseconds in a 256MB memory scenario.

[0285] It should be noted that the method of this disclosure embodiment can be executed by a single device, such as a computer or server. The method of this embodiment can also be applied to a distributed scenario, where multiple devices cooperate to complete the task. In such a distributed scenario, one of these devices may execute only one or more steps of the method of this disclosure embodiment, and the multiple devices will interact with each other to complete the method described.

[0286] It should be noted that the above description describes some embodiments of this disclosure. Other embodiments are within the scope of the appended claims. In some cases, the actions or steps recorded in the claims can be performed in a different order than that shown in the above embodiments and still achieve the desired result. Furthermore, the processes depicted in the drawings do not necessarily require a specific or sequential order to achieve the desired result. In some embodiments, multitasking and parallel processing are also possible or may be advantageous.

[0287] Based on the same inventive concept, corresponding to any of the above-described embodiments, this disclosure also provides a memory management device.

[0288] refer to Figure 5 A memory management device, comprising the following modules: The memory partitioning and permission setting module 910 is configured to divide physical memory into several physically isolated memory regions based on a pre-built task criticality level model, and set different access permissions for different memory regions. The memory pre-allocation module 920 is configured to pre-allocate memory for a task in the memory region corresponding to the corresponding task critical level based on the task critical level model. The fragmentation monitoring and defragmentation module 930 is configured to monitor the memory fragmentation distribution status during the operation of the task to obtain the fragmentation entropy value, and in response to the fragmentation entropy value being greater than the fragmentation entropy value threshold, to execute a differentiated fragmentation defragmentation strategy for different memory regions. The memory prediction and expansion module 940 is configured to predict memory pressure based on a pre-built load prediction model, and to perform data migration and physical memory expansion in response to the predicted memory pressure being greater than a memory pressure threshold. The resource reclamation and parameter optimization module 950 is configured to reclaim the memory resources occupied by the task in response to the completion of the task execution, and optimize the fragment entropy threshold and the memory pressure threshold based on the fragment entropy value.

[0289] In some exemplary embodiments, the memory partitioning and permission setting module 910 is specifically configured as follows: Initialize the hardware, obtain hardware parameters and physical memory distribution information, and establish a physical memory address mapping; The task criticality level model is constructed based on the functional requirements of the control terminal, and the correspondence between the task criticality level and the memory region is determined. The physical memory is divided into a high-priority task-specific area, a shared service area, and a low-priority task-isolated area. Configure different access permissions for the high-priority task exclusive area, the shared service area, and the low-priority task isolation area.

[0290] In some exemplary embodiments, the memory pre-allocation module 920 is specifically configured as follows: Determine task priority weights and predict memory usage using a sliding window averaging method based on historical load data; In the high-priority task-specific area, a fixed-size memory block is allocated using the first-fit algorithm; in the shared service area, a buddy system is used to dynamically manage the free list; and in the low-priority task isolation area, a memory pool is predefined, and fragmentation reclamation is accelerated using a red-black tree index. Set an access control matrix for each memory region; Perform real-time verification and stress testing; Adjust memory allocation parameters based on test results.

[0291] In some exemplary embodiments, the fragmentation monitoring and defragmentation module 930 is specifically configured as follows: Scan the page table entries of each memory region to calculate the fragment entropy value; The fragment entropy threshold is calculated based on the sliding window mean and standard deviation. In response to the fragment entropy value being greater than the fragment entropy value threshold, a copy-and-sweep algorithm is used to migrate key data in the high-priority area, a mark-and-sweep algorithm is used to merge free blocks in the shared service area, and a lazy compaction strategy is used to release idle memory in batches in the low-priority area. Hardware-level memory barriers are inserted before and after the compaction operation. A software transactional memory mechanism is used to perform page table updates and free list modifications. During the compaction process, high-priority task preemption is prohibited and low-priority interrupts are masked.

[0292] In some exemplary embodiments, the memory prediction and expansion module 940 is specifically configured as follows: Input the task execution time, memory allocation, interrupt triggering frequency, and operation intensity into the load prediction model to obtain the memory pressure output by the load prediction model; Page activity is statistically analyzed by accessing page table entries, inactive memory pages are identified, and they are sorted by access frequency. Inactive memory pages are then migrated to external storage, and a circular buffer is used to manage the migration task. Configure the memory controller to connect to the new memory module, reconfigure the page table of the memory management unit to expand the virtual address space, adopt a progressive plug-in strategy to migrate data in stages, and use a weighted round-robin scheduling algorithm to allocate bandwidth.

[0293] In some exemplary embodiments, the resource recovery and parameter optimization module 950 is configured as follows: When a task enters a completed or abnormally terminated state, the occupied memory block is reclaimed and a status mark is made. In response to the number of consecutive free pages being less than the threshold for consecutive free pages, an object compaction and page-level merging algorithm is used to aggregate free memory; The fragment entropy value is calculated by combining the page-level fragment distribution and the change rate over time, and a dynamic threshold is generated based on the exponentially weighted moving average. Optimization is triggered when the fragment entropy value is greater than the threshold. Adjust the size of pre-allocated memory blocks based on historical allocation variance and optimize memory region allocation weights; The scan cycle is calculated based on the average allocation rate of the low priority area. When the idle time of a memory block is greater than the preset proportion of the time window, it is marked as reclaimable. When switching task contexts, reset the high-priority memory blocks to their pre-allocated state; The memory allocation success rate, average allocation latency, and fragmentation entropy are collected as feedback signals to calculate the parameter adjustment amount, and optimization strategies are deployed based on the parameter adjustment amount.

[0294] For ease of description, the above apparatus is described in terms of its functions, divided into various modules. Of course, in implementing this disclosure, the functions of each module can be implemented in one or more software and / or hardware.

[0295] The apparatus of the above embodiments is used to implement the corresponding memory management method in any of the foregoing embodiments, and has the beneficial effects of the corresponding method embodiments, which will not be repeated here.

[0296] Based on the same inventive concept, corresponding to the methods of any of the above embodiments, this disclosure also provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the memory management method described in any of the above embodiments.

[0297] Figure 6This embodiment illustrates a more specific hardware structure of an electronic device, which may include a processor 1010, a memory 1020, an input / output interface 1030, a communication interface 1040, and a bus 1050. The processor 1010, memory 1020, input / output interface 1030, and communication interface 1040 are interconnected internally via the bus 1050.

[0298] The processor 1010 can be implemented using a general-purpose CPU (Central Processing Unit), microprocessor, application-specific integrated circuit (ASIC), or one or more integrated circuits, and is used to execute relevant programs to implement the technical solutions provided in the embodiments of this specification.

[0299] The memory 1020 can be implemented in the form of ROM (Read Only Memory), RAM (Random Access Memory), static storage device, dynamic storage device, etc. The memory 1020 can store the operating system and other applications. When the technical solutions provided in the embodiments of this specification are implemented by software or firmware, the relevant program code is stored in the memory 1020 and is called and executed by the processor 1010.

[0300] The input / output interface 1030 is used to connect input / output modules to realize information input and output. The input / output modules can be configured as components in the device (not shown in the figure) or externally connected to the device to provide corresponding functions. Input devices may include keyboards, mice, touch screens, microphones, various sensors, etc., and output devices may include displays, speakers, vibrators, indicator lights, etc.

[0301] The communication interface 1040 is used to connect a communication module (not shown in the figure) to enable communication between this device and other devices. The communication module can communicate via wired means (such as USB, Ethernet cable, etc.) or wireless means (such as mobile network, WIFI, Bluetooth, etc.).

[0302] Bus 1050 includes a pathway for transmitting information between various components of the device, such as processor 1010, memory 1020, input / output interface 1030, and communication interface 1040.

[0303] It should be noted that although the above-described device only shows the processor 1010, memory 1020, input / output interface 1030, communication interface 1040, and bus 1050, in specific implementations, the device may also include other components necessary for normal operation. Furthermore, those skilled in the art will understand that the above-described device may only include the components necessary for implementing the embodiments of this specification, and not necessarily all the components shown in the figures.

[0304] The electronic devices described above are used to implement the corresponding memory management methods in any of the foregoing embodiments and have the beneficial effects of the corresponding method embodiments, which will not be repeated here.

[0305] The memory 1020 stores machine-readable instructions executable by the processor 1010. When the electronic device is running, the processor 1010 communicates with the memory 1020 via the bus 1050, causing the processor 1010 to execute the following instructions during operation: Based on a pre-built task criticality level model, physical memory is divided into several physically isolated memory regions, and different access permissions are set for different memory regions. Based on the task criticality level model, memory is pre-allocated for the task in the memory region corresponding to the corresponding task criticality level; The fragmentation entropy value is obtained by monitoring the memory fragmentation distribution status during the operation of the task. In response to the fragmentation entropy value being greater than the fragmentation entropy value threshold, a differentiated fragmentation defragmentation strategy is executed for different memory regions. Memory pressure is predicted based on a pre-built load prediction model, and data migration and physical memory expansion are performed in response to the predicted memory pressure exceeding a memory pressure threshold. In response to the completion of the task, the memory resources occupied by the task are reclaimed, and the fragment entropy threshold and the memory pressure threshold are optimized based on the fragment entropy value.

[0306] In one possible implementation, the instructions executed by the processor 1010, which divide physical memory into several physically isolated memory regions based on a pre-built task criticality level model and set differentiated access permissions for different memory regions, include: Initialize the hardware, obtain hardware parameters and physical memory distribution information, and establish a physical memory address mapping; The task criticality level model is constructed based on the functional requirements of the control terminal, and the correspondence between the task criticality level and the memory region is determined. The physical memory is divided into a high-priority task-specific area, a shared service area, and a low-priority task-isolated area. Configure different access permissions for the high-priority task exclusive area, the shared service area, and the low-priority task isolation area.

[0307] In one possible implementation, the instruction executed by processor 1010, which pre-allocates memory for a task in the memory region corresponding to the corresponding task criticality level based on the task criticality level model, includes: Determine task priority weights and predict memory usage using a sliding window averaging method based on historical load data; In the high-priority task-specific area, a fixed-size memory block is allocated using the first-fit algorithm; in the shared service area, a buddy system is used to dynamically manage the free list; and in the low-priority task isolation area, a memory pool is predefined, and fragmentation reclamation is accelerated using a red-black tree index. Set an access control matrix for each memory region; Perform real-time verification and stress testing; Adjust memory allocation parameters based on test results.

[0308] In one possible implementation, the instructions executed by the processor 1010 include monitoring the memory fragmentation distribution status during task execution to obtain a fragmentation entropy value, and, in response to the fragmentation entropy value being greater than a fragmentation entropy value threshold, executing a differentiated defragmentation strategy for different memory regions, including: Scan the page table entries of each memory region to calculate the fragment entropy value; The fragment entropy threshold is calculated based on the sliding window mean and standard deviation. In response to the fragment entropy value being greater than the fragment entropy value threshold, a copy-and-sweep algorithm is used to migrate key data in the high-priority area, a mark-and-sweep algorithm is used to merge free blocks in the shared service area, and a lazy compaction strategy is used to release idle memory in batches in the low-priority area. Hardware-level memory barriers are inserted before and after the compaction operation. A software transactional memory mechanism is used to perform page table updates and free list modifications. During the compaction process, high-priority task preemption is prohibited and low-priority interrupts are masked.

[0309] In one possible implementation, the instructions executed by processor 1010, which predict memory pressure based on a pre-built load prediction model, and in response to the predicted memory pressure exceeding a memory pressure threshold, perform data migration and physical memory expansion, include: Input the task execution time, memory allocation, interrupt triggering frequency, and operation intensity into the load prediction model to obtain the memory pressure output by the load prediction model; Page activity is statistically analyzed by accessing page table entries, inactive memory pages are identified, and they are sorted by access frequency. Inactive memory pages are then migrated to external storage, and a circular buffer is used to manage the migration task. Configure the memory controller to connect to the new memory module, reconfigure the page table of the memory management unit to expand the virtual address space, adopt a progressive plug-in strategy to migrate data in stages, and use a weighted round-robin scheduling algorithm to allocate bandwidth.

[0310] In one possible implementation, the instructions executed by the processor 1010, in response to the completion of the task, include reclaiming the memory resources occupied by the task and optimizing the fragmentation entropy threshold and the memory pressure threshold based on the fragmentation entropy value, including: When a task enters a completed or abnormally terminated state, the occupied memory block is reclaimed and a status mark is made. In response to the number of consecutive free pages being less than the threshold for consecutive free pages, an object compaction and page-level merging algorithm is used to aggregate free memory; The fragment entropy value is calculated by combining the page-level fragment distribution and the change rate over time, and a dynamic threshold is generated based on the exponentially weighted moving average. Optimization is triggered when the fragment entropy value is greater than the threshold. Adjust the size of pre-allocated memory blocks based on historical allocation variance and optimize memory region allocation weights; The scan cycle is calculated based on the average allocation rate of the low priority area. When the idle time of a memory block is greater than the preset proportion of the time window, it is marked as reclaimable. When switching task contexts, reset the high-priority memory blocks to their pre-allocated state; The memory allocation success rate, average allocation latency, and fragmentation entropy are collected as feedback signals to calculate the parameter adjustment amount, and optimization strategies are deployed based on the parameter adjustment amount.

[0311] Based on the same inventive concept, corresponding to the methods of any of the above embodiments, this disclosure also provides a non-transitory computer-readable storage medium that stores computer instructions for causing the computer to execute the memory management method as described in any of the above embodiments.

[0312] The computer-readable medium of this embodiment includes permanent and non-permanent, removable and non-removable media, and information storage can be implemented by any method or technology. Information can be computer-readable instructions, data structures, program modules, or other data. Examples of computer storage media include, but are not limited to, phase-change memory (PRAM), static random access memory (SRAM), dynamic random access memory (DRAM), other types of random access memory (RAM), read-only memory (ROM), electrically erasable programmable read-only memory (EEPROM), flash memory or other memory technologies, CD-ROM, digital versatile optical disc (DVD) or other optical storage, magnetic tape, magnetic magnetic disk storage or other magnetic storage devices, or any other non-transfer medium that can be used to store information accessible by a computing device.

[0313] The aforementioned non-transitory computer-readable storage media can be any available medium or data storage device that a computer can access, including but not limited to magnetic storage (such as floppy disks, hard disks, magnetic tapes, magneto-optical disks (MOs), etc.), optical storage (such as CDs, DVDs, BDs, HVDs, etc.), and semiconductor storage (such as ROMs, EPROMs, EEPROMs, non-volatile memory (NAND FLASH), solid-state drives (SSDs)).

[0314] The computer instructions stored in the storage medium of the above embodiments are used to cause the computer to execute the memory management method as described in any of the embodiments in the exemplary method section above, and have the beneficial effects of the corresponding method embodiments, which will not be repeated here.

[0315] Based on the same inventive concept, corresponding to the memory management method described in any of the above embodiments, this disclosure also provides a computer program product, which includes computer program instructions. In some embodiments, the computer program instructions can be executed by one or more processors of a computer to cause the computer and / or the processors to perform the memory management method. Corresponding to the execution entity for each step in each embodiment of the memory management method, the processor executing the corresponding step may belong to the corresponding execution entity.

[0316] The computer program products of the above embodiments are used to cause the computer and / or the processor to execute the memory management method as described in any of the above embodiments, and have the beneficial effects of the corresponding method embodiments, which will not be repeated here.

[0317] Those skilled in the art will recognize that embodiments of this disclosure can be implemented as a system, method, or computer program product. Therefore, this disclosure can be implemented as entirely hardware, entirely software (including firmware, resident software, microcode, etc.), or a combination of hardware and software, generally referred to herein as a "circuit," "module," or "system." Furthermore, in some embodiments, this disclosure can also be implemented as a computer program product contained in one or more computer-readable media, which includes computer-readable program code.

[0318] Any combination of one or more computer-readable media may be used. A computer-readable medium can be a computer-readable signal medium or a computer-readable storage medium. A computer-readable storage medium can be, for example,, but not limited to, an electrical, magnetic, optical, electromagnetic, infrared, or semiconductor system, apparatus, or device, or any combination thereof. More specific examples (not exhaustive) of a computer-readable storage medium may include: an electrical connection having one or more wires, a portable computer disk, a hard disk, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fiber, portable compact disk read-only memory (CD-ROM), optical storage device, magnetic storage device, or any suitable combination thereof. In this document, a computer-readable storage medium can be any tangible medium that contains or stores a program that can be used by or in connection with an instruction execution system, apparatus, or device.

[0319] Computer-readable signal media may include data signals propagated in baseband or as part of a carrier wave, carrying computer-readable program code. Such propagated data signals may take various forms, including but not limited to electromagnetic signals, optical signals, or any suitable combination thereof. Computer-readable signal media may also be any computer-readable medium other than computer-readable storage media, capable of sending, propagating, or transmitting programs for use by or in connection with an instruction execution system, apparatus, or device.

[0320] Program code contained on a computer-readable medium may be transmitted using any suitable medium, including but not limited to wireless, wire, optical fiber, RF, etc., or any suitable combination thereof.

[0321] Computer program code for performing the operations of this disclosure can be written in one or more programming languages ​​or a combination thereof, including object-oriented programming languages ​​such as Java, Smalltalk, and C++, and conventional procedural programming languages ​​such as the "C" language or similar programming languages. The program code can be executed entirely on the user's computer, partially on the user's computer, as a standalone software package, partially on the user's computer and partially on a remote computer, or entirely on a remote computer or server. In cases involving remote computers, the remote computer can be connected to the user's computer via any type of network, including a local area network (LAN) or a wide area network (WAN), or it can be connected to an external computer (e.g., via the Internet using an Internet service provider).

[0322] It should be understood that each block of a flowchart and / or block diagram, as well as combinations of blocks in a flowchart and / or block diagram, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, a special-purpose computer, or other programmable data processing device to produce a machine that, when executed by a computer or other programmable data processing device, creates means for implementing the functions / operations specified in the blocks of the flowchart and / or block diagram.

[0323] These computer program instructions may also be stored in a computer-readable medium that enables a computer or other programmable data processing apparatus to function in a particular manner, such that the instructions stored in the computer-readable medium produce a product comprising an instruction apparatus that implements the functions / operations specified in the boxes of a flowchart and / or block diagram.

[0324] Computer program instructions may also be loaded onto a computer, other programmable data processing apparatus, or other device to cause a series of operational steps to be performed on the computer, other programmable data processing apparatus, or other device to produce a computer-implemented process, such that the instructions that execute on the computer or other programmable apparatus can provide a process for implementing the functions / operations specified in the boxes of a flowchart and / or block diagram.

[0325] Furthermore, although the operations of the methods of this disclosure are described in a specific order in the accompanying drawings, this does not require or imply that these operations must be performed in that specific order, or that all of the operations shown must be performed to achieve the desired result. Rather, the steps depicted in the flowcharts may be executed in a different order. Additionally or alternatively, certain steps may be omitted, multiple steps may be combined into one step, and / or one step may be broken down into multiple steps.

[0326] The flowcharts and block diagrams in the accompanying drawings illustrate the architecture, functionality, and operation of possible implementations of systems, methods, and computer program products according to various embodiments of this application. Each block in a flowchart or block diagram may represent a module, segment, or portion of code, which contains one or more executable instructions for implementing a specified logical function. It should also be noted that in some alternative implementations, the functions indicated in the blocks may occur in a different order than those indicated in the drawings. For example, two consecutively indicated blocks may actually be executed substantially in parallel, and they may sometimes be executed in reverse order, depending on the functions involved. It should also be noted that each block in a block diagram or flowchart, and combinations of blocks in a block diagram or flowchart, can be implemented using a dedicated hardware-based system that performs the specified function or operation, or using a combination of dedicated hardware and computer instructions.

[0327] It should be noted that although several modules or units for the device used to perform actions have been mentioned in the detailed description above, this division is not mandatory. In fact, according to the embodiments of this application, the features and functions of two or more modules or units described above can be embodied in one module or unit. Conversely, the features and functions of one module or unit described above can be further divided and embodied by multiple modules or units.

[0328] Those skilled in the art should understand that the discussion of any of the above embodiments is merely exemplary and is not intended to imply that the scope of this application (including the claims) is limited to these examples; within the framework of this application, the technical features of the above embodiments or different embodiments can also be combined, the steps can be implemented in any order, and there are many other variations of different aspects of the embodiments of this application as described above, which are not provided in the details for the sake of brevity.

[0329] Additionally, to simplify the description and discussion, and to avoid obscuring the embodiments of this application, the well-known power / ground connections to integrated circuit (IC) chips and other components may or may not be shown in the provided drawings. Furthermore, the apparatus may be shown in block diagram form to avoid obscuring the embodiments of this application, and this also takes into account the fact that the details of the implementation of these block diagram apparatuses are highly dependent on the platform on which the embodiments of this application will be implemented (i.e., these details should be fully understood by those skilled in the art). While specific details (e.g., circuits) have been set forth to describe exemplary embodiments of this application, it will be apparent to those skilled in the art that the embodiments of this application can be implemented without these specific details or with variations thereof. Therefore, these descriptions should be considered illustrative rather than restrictive.

[0330] Although this application has been described in conjunction with specific embodiments thereof, many substitutions, modifications, and variations of these embodiments will be apparent to those skilled in the art from the foregoing description. For example, other memory architectures (e.g., dynamic RAM (DRAM)) may be used with the embodiments discussed.

[0331] The embodiments of this application are intended to cover all such substitutions, modifications, and variations that fall within the broad scope of the appended claims. Therefore, any omissions, modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the embodiments of this application should be included within the protection scope of this application.

[0332] While the spirit and principles of this disclosure have been described with reference to several specific embodiments, it should be understood that this disclosure is not limited to the disclosed specific embodiments, and the division of aspects does not imply that features in these aspects cannot be combined for benefit; such division is merely for convenience of expression. This disclosure is intended to cover various modifications and equivalent arrangements included within the spirit and scope of the appended claims. The scope of the appended claims is to be interpreted in the broadest sense, thereby encompassing all such modifications and equivalent structures and functions.

Claims

1. A memory management method, characterized in that, include: Based on a pre-built task criticality level model, physical memory is divided into several physically isolated memory regions, and different access permissions are set for different memory regions. Based on the task criticality level model, memory is pre-allocated for the task in the memory region corresponding to the corresponding task criticality level; The fragmentation entropy value is obtained by monitoring the memory fragmentation distribution status during the operation of the task. In response to the fragmentation entropy value being greater than the fragmentation entropy value threshold, a differentiated fragmentation defragmentation strategy is executed for different memory regions. Memory pressure is predicted based on a pre-built load prediction model, and data migration and physical memory expansion are performed in response to the predicted memory pressure exceeding a memory pressure threshold. In response to the completion of the task, the memory resources occupied by the task are reclaimed, and the fragment entropy threshold and the memory pressure threshold are optimized based on the fragment entropy value.

2. The method according to claim 1, characterized in that, The pre-built task criticality level model divides physical memory into several physically isolated memory regions and sets differentiated access permissions for different memory regions, including: Initialize the hardware, obtain hardware parameters and physical memory distribution information, and establish a physical memory address mapping; The task criticality level model is constructed based on the functional requirements of the control terminal, and the correspondence between the task criticality level and the memory region is determined. The physical memory is divided into a high-priority task-specific area, a shared service area, and a low-priority task-isolated area. Configure different access permissions for the high-priority task exclusive area, the shared service area, and the low-priority task isolation area.

3. The method according to claim 2, characterized in that, The step of pre-allocating memory for a task in the memory region corresponding to the task criticality level based on the task criticality level includes: Determine task priority weights and predict memory usage using a sliding window averaging method based on historical load data; In the high-priority task-specific area, a fixed-size memory block is allocated using the first-fit algorithm; in the shared service area, a buddy system is used to dynamically manage the free list; and in the low-priority task isolation area, a memory pool is predefined, and fragmentation reclamation is accelerated using a red-black tree index. Set an access control matrix for each memory region; Perform real-time verification and stress testing; Adjust memory allocation parameters based on test results.

4. The method according to claim 2, characterized in that, The monitoring of memory fragmentation distribution during task execution yields fragmentation entropy values. In response to fragmentation entropy values ​​exceeding a threshold, differentiated defragmentation strategies are implemented for different memory regions, including: Scan the page table entries of each memory region to calculate the fragment entropy value; The fragment entropy threshold is calculated based on the sliding window mean and standard deviation. In response to the fragment entropy value being greater than the fragment entropy value threshold, a copy-and-sweep algorithm is used to migrate key data in the high-priority area, a mark-and-sweep algorithm is used to merge free blocks in the shared service area, and a lazy compaction strategy is used to release idle memory in batches in the low-priority area. Hardware-level memory barriers are inserted before and after the compaction operation. A software transactional memory mechanism is used to perform page table updates and free list modifications. During the compaction process, high-priority task preemption is prohibited and low-priority interrupts are masked.

5. The method according to claim 1, characterized in that, The method predicts memory pressure based on a pre-built load prediction model. In response to the predicted memory pressure exceeding a memory pressure threshold, data migration and physical memory expansion are performed, including: Input the task execution time, memory allocation, interrupt triggering frequency, and operation intensity into the load prediction model to obtain the memory pressure output by the load prediction model; Page activity is statistically analyzed by accessing page table entries, inactive memory pages are identified, and they are sorted by access frequency. Inactive memory pages are then migrated to external storage, and a circular buffer is used to manage the migration task. Configure the memory controller to connect to the new memory module, reconfigure the page table of the memory management unit to expand the virtual address space, adopt a progressive plug-in strategy to migrate data in stages, and use a weighted round-robin scheduling algorithm to allocate bandwidth.

6. The method according to claim 1, characterized in that, In response to the completion of the task, the memory resources occupied by the task are reclaimed, and the fragmentation entropy threshold and the memory pressure threshold are optimized based on the fragmentation entropy value, including: When a task enters a completed or abnormally terminated state, the occupied memory block is reclaimed and a status mark is made. In response to the number of consecutive free pages being less than the threshold for consecutive free pages, an object compaction and page-level merging algorithm is used to aggregate free memory; The fragment entropy value is calculated by combining the page-level fragment distribution and the change rate over time, and a dynamic threshold is generated based on the exponentially weighted moving average. Optimization is triggered when the fragment entropy value is greater than the threshold. Adjust the size of pre-allocated memory blocks based on historical allocation variance and optimize memory region allocation weights; The scan cycle is calculated based on the average allocation rate of the low priority area. When the idle time of a memory block is greater than the preset proportion of the time window, it is marked as reclaimable. When switching task contexts, reset the high-priority memory blocks to their pre-allocated state; The memory allocation success rate, average allocation latency, and fragmentation entropy are collected as feedback signals to calculate the parameter adjustment amount, and optimization strategies are deployed based on the parameter adjustment amount.

7. A memory management device, characterized in that, include: The memory partitioning and permission setting module is configured to divide physical memory into several physically isolated memory regions based on a pre-built task criticality level model, and set different access permissions for different memory regions. The memory pre-allocation module is configured to pre-allocate memory for a task in the memory region corresponding to the corresponding task critical level based on the task critical level model. The fragmentation monitoring and defragmentation module is configured to monitor the memory fragmentation distribution status during the operation of the task to obtain the fragmentation entropy value, and in response to the fragmentation entropy value being greater than the fragmentation entropy value threshold, to execute differentiated fragmentation defragmentation strategies for different memory regions. The memory prediction and expansion module is configured to predict memory pressure based on a pre-built load prediction model, and to perform data migration and physical memory expansion in response to the predicted memory pressure being greater than a memory pressure threshold. The resource reclamation and parameter optimization module is configured to reclaim the memory resources occupied by the task in response to the completion of the task execution, and optimize the fragment entropy threshold and the memory pressure threshold based on the fragment entropy value.

8. An electronic device, characterized in that, It includes a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor, when executing the program, implements the method as described in any one of claims 1 to 6.

9. A non-transitory computer-readable storage medium, characterized in that, The non-transitory computer-readable storage medium stores computer instructions for causing the computer to perform the method of any one of claims 1 to 6.

10. A computer program product, characterized in that, It includes computer program instructions that, when run on a computer, cause the computer to perform the method as described in any one of claims 1 to 6.