PLC multi-core software lock step fault tolerance method, device, system and equipment

By compiling and executing the PLC high-level language source code in various ways and executing it synchronously, different program copies are generated and consistency checks are performed. This solves the problem of high reliability and fault tolerance in PLC systems when hardware failures occur, achieves efficient hardware fault detection and fault tolerance, and reduces costs.

CN121523210APending Publication Date: 2026-02-13CHENGDU SHUZI AUTOMATION TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202511700903.5
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-11-19
Publication Date
2026-02-13

AI Technical Summary

Technical Problem

Existing PLC systems struggle to achieve high reliability and fault tolerance when faced with random hardware failures, and current technologies either rely on expensive dedicated hardware or on software development models that are difficult to guarantee quality.

Method used

The PLC high-level language source code is compiled in a variety of ways by the compiler to generate multiple differentiated program copies, which are executed on different cores of commercial multi-core processors. The hardware synchronization mechanism is used to maintain synchronization. During runtime, consistency is checked through voting stubs. If they are consistent, execution continues; otherwise, fault handling is triggered.

Benefits of technology

Without requiring dedicated redundant hardware, it achieves efficient detection and fault tolerance for random hardware failures in the processor, significantly improving the reliability of the control system while greatly reducing implementation costs.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121523210A_ABST
    Figure CN121523210A_ABST
Patent Text Reader

Abstract

The invention relates to the technical field of industrial control systems, in particular to a PLC multi-core software lock step fault tolerance method, device, system and equipment. According to a compiler, performing diversified compilation on an intermediate representation or a low-level language code obtained by compiling a PLC high-level language source code to obtain at least two differentiated program copies; loading each differentiated program copy to different processor cores for operation during operation, and synchronously executing a periodic task according to a preset hardware synchronization mechanism during operation; during the period that all the processor cores synchronously execute the periodic task, according to a voting pile preset by a compiler, consistency verification is carried out on operation of each processor core, and a verification result is obtained; if the verification result is consistent, all the ready marks are cleared, and all the processor cores continue to execute subsequent instructions. The reliability of the control system is remarkably improved, and meanwhile the implementation cost is greatly reduced.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of industrial control system technology, specifically to a PLC multi-core software lockstep fault-tolerant method, device, system, and equipment. Background Technology

[0002] In critical industrial sectors such as chemical engineering, power generation, and rail transportation, the reliability of programmable logic controllers (PLCs) is of paramount importance. Any computational error caused by random hardware failures (such as memory or register bit flipping due to cosmic rays) can lead to significant economic losses or even safety incidents.

[0003] To address this issue, the industry currently employs two main technical approaches: Hardware Lock-step: This is the mainstream technology widely used in high-reliability PLCs (such as the Siemens S7-400H series and Rockwell ControlLogix redundant systems). Its core idea is to use two or more identical physical CPUs to synchronously execute the same instruction stream. After each clock cycle or instruction cycle, dedicated hardware comparison logic checks the calculation results of all CPUs. If an inconsistency is found, the system determines a fault and switches to a redundant unit or enters a safe state. The advantages of this approach are strong fault tolerance and extremely low fault detection latency. N-Version Programming: This is a classic software fault-tolerant approach, where multiple independent development teams develop N versions ("variants") of software with the same functionality but different implementations, based on the same requirements specification. During runtime, these variants execute in parallel, and a voting mechanism decides the final output. Its theoretical advantage lies in its ability to simultaneously resist hardware failures and software design flaws.

[0004] However, existing technologies either rely on expensive, rigid dedicated hardware or impractical software development models that are difficult to guarantee quality. Therefore, there is an urgent need for a method that can achieve high reliability and fault tolerance in a low-cost, automated manner on inexpensive commercial multi-core processors. Summary of the Invention

[0005] The purpose of this invention is to provide a method, apparatus, system and equipment for multi-core software lockstep fault tolerance in PLC, which solves the problems in the prior art.

[0006] This invention is achieved through the following technical solution:

[0007] In a first aspect, embodiments of the present invention provide a PLC multi-core software lockstep fault-tolerant method, applied to a PLC multi-core software lockstep fault-tolerant system, the system including a compiler and a runtime, comprising:

[0008] The compiler is used to perform diversified compilation of the intermediate representation or low-level language code obtained by compiling the PLC high-level language source code, resulting in at least two differentiated program copies.

[0009] According to the runtime, each differentiated program copy is loaded and run on a different processor core, and the cycle tasks are executed synchronously according to a preset hardware synchronization mechanism during the runtime.

[0010] During the synchronous execution of cycle tasks across all processor cores, the runtime performs consistency checks on the execution of each processor core based on the voting stubs preset by the compiler in each program copy, and obtains the check results.

[0011] If the verification results are consistent, all ready flags are cleared according to the runtime procedure, and each processor core continues to execute subsequent instructions.

[0012] Preferably, the step of performing diversified compilation on the intermediate representation or low-level language code obtained by compiling the PLC high-level language source code according to the compiler to obtain at least two differentiated program copies includes:

[0013] The compiler is used to compile the intermediate representation or low-level language code obtained by compiling the PLC high-level language source code to generate at least two program copies.

[0014] Based on a preset optimization strategy, different optimization processes are applied to the code structure and execution path of each program copy to obtain an optimized program copy corresponding to each program copy. The optimization strategy includes loop unrolling strategy and process inlining strategy.

[0015] Based on the instructions of each optimizer copy, instruction difference processing is performed to obtain the instruction processing program copy corresponding to the instructions of each optimizer copy;

[0016] Based on the variables in each instruction handler copy, variable difference processing is performed to obtain the differentiated program copy corresponding to each instruction handler copy.

[0017] Preferably, the instruction difference processing includes at least one of the following:

[0018] Allocate mutually exclusive or partially overlapping sets of preferred registers for different copies of the program;

[0019] Based on a pre-defined library of equivalent instruction patterns, perform equivalent substitutions on the instructions in the program copy.

[0020] Without violating data dependencies, rearrange the order of individual instructions in the program copy and / or randomly insert no-operation instructions into the instruction sequence.

[0021] Preferably, the step of performing variable difference processing based on the variables in each instruction processor copy to obtain a differentiated program copy corresponding to each instruction processor copy includes:

[0022] The local variables in the function stack frame corresponding to each instruction handler copy are randomly arranged and padding bytes are randomly inserted between each local variable to obtain a data layout program copy.

[0023] And / or, adjust the storage order of global and static variables in memory for each instruction handler copy.

[0024] Preferably, the step of the runtime performing consistency verification on the operation of each processor core based on the voting stubs preset by the compiler in each program copy, and obtaining the verification result, includes:

[0025] According to the voting stubs preset in each program copy by the compiler, when the runtime detects that any processor core has reached the voting point corresponding to the voting stub, it generates data to be verified and a ready flag and enters a busy waiting state.

[0026] Once all processor cores have generated a ready flag, a consistency check is performed on all data to be verified, and the verification result is obtained.

[0027] Preferably, the hardware synchronization mechanism controls all processor cores to synchronize based on cross-core interrupts sent by the master processor core.

[0028] Preferably, the method further includes:

[0029] If the verification result is inconsistent, a non-maskable interrupt will be triggered during runtime, and the process will jump to the fault handling program. The fault handling program will record the diagnostic information and put the PLC into a safe shutdown state.

[0030] Secondly, embodiments of the present invention provide a PLC multi-core software lockstep fault-tolerant device, applied to a PLC multi-core software lockstep fault-tolerant system, the system including a compiler and a runtime, comprising:

[0031] The compilation module is used to perform diversified compilation of intermediate representation or low-level language code obtained by compiling PLC high-level language source code according to the compiler, so as to obtain at least two differentiated program copies;

[0032] The execution module is used to load each differentiated program copy onto different processor cores for execution according to the runtime, and to synchronously execute periodic tasks according to a preset hardware synchronization mechanism during the runtime.

[0033] The voting module is used to perform consistency checks on the operation of each processor core during the synchronous execution of cycle tasks across all processor cores, based on the voting stubs preset by the compiler in each program copy, and to obtain the check results.

[0034] If the verification module finds that the verification results are consistent, it will clear all ready flags during runtime, and each processor core will continue to execute subsequent instructions.

[0035] Thirdly, embodiments of the present invention provide a PLC multi-core software lockstep fault-tolerant system, comprising:

[0036] A compiler is used to perform diverse compilations on intermediate representations or low-level language code obtained from the compilation of PLC high-level language source code, resulting in at least two differentiated program copies.

[0037] During runtime, each differentiated program copy is loaded and run on a different processor core. During runtime, the periodic tasks are executed synchronously according to a preset hardware synchronization mechanism. During the synchronous execution of periodic tasks on all processor cores, the consistency of the execution of each processor core is checked according to the voting stubs preset in each program copy by the compiler, and the check result is obtained. If the check result is consistent, all ready flags are cleared according to the runtime, and each processor core continues to execute subsequent instructions.

[0038] Fourthly, embodiments of the present invention provide an electronic device, including: at least one processor, at least one memory, and computer program instructions stored in the memory, which, when executed by the processor, implement the method of the first aspect described above.

[0039] Compared with the prior art, the present invention has the following advantages and beneficial effects:

[0040] This solution automates and diversifies the compilation of intermediate representations or low-level language code derived from PLC high-level language source code using a compiler. This generates multiple program copies that are physically different but logically equivalent in terms of instruction sequence, data layout, and code structure. These copies are then loaded onto different cores of a commercial multi-core processor during runtime. Macro-cycle synchronization of the multiple copies is achieved using cross-core interrupts sent by the main core, ensuring consistent execution progress. During runtime, the compiler-preset voting stubs are used to verify the consistency of output data from key computing nodes. If the results are consistent, the synchronization flag is cleared and execution continues. Thus, without the need for dedicated redundant hardware, this solution achieves efficient detection and fault tolerance for random hardware failures in the processor through pure software, significantly improving the reliability of the control system while substantially reducing implementation costs. Attached Figure Description

[0041] To more clearly illustrate the technical solutions of the exemplary embodiments of the present invention, the accompanying drawings used in the embodiments will be briefly described below. It should be understood that the following drawings only show some embodiments of the present invention and should not be considered as a limitation of the scope. For those skilled in the art, other related drawings can be obtained based on these drawings without creative effort. In the drawings:

[0042] Figure 1 A flowchart illustrating the PLC multi-core software lockstep fault-tolerant method provided in this embodiment. Figure 1 ;

[0043] Figure 2 A flowchart illustrating the PLC multi-core software lockstep fault-tolerant method provided in this embodiment. Figure 2 ;

[0044] Figure 3 A flowchart illustrating the diverse compilers provided in this embodiment;

[0045] Figure 4 This is a schematic diagram of the synchronization and voting process provided in this embodiment;

[0046] Figure 5 This is a schematic diagram of the structure of the PLC multi-core software lockstep fault-tolerant device provided in this embodiment;

[0047] Figure 6 This is a schematic diagram of the structure of the electronic device provided in this embodiment. Detailed Implementation

[0048] To make the objectives, technical solutions, and advantages of the present invention clearer, the present invention will be further described in detail below with reference to the embodiments and accompanying drawings. The illustrative embodiments and descriptions of the present invention are only used to explain the present invention and are not intended to limit the present invention.

[0049] It should be noted that, in this document, relational terms such as "first" and "second" are used merely to distinguish one entity or operation from another, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Furthermore, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. Without further limitations, an element defined by the phrase "comprising..." does not exclude the presence of additional identical elements in the process, method, article, or apparatus that includes said element.

[0050] It should be noted that all actions involving the acquisition of signals, information, or data in this invention are carried out in compliance with the relevant data protection laws and regulations of the locality and with authorization from the owner of the relevant device.

[0051] Software lock-step: A software fault-tolerance technique that runs copies of a program with identical logic on two or more independent processor cores. By comparing the computation results of these copies at critical execution points, execution discrepancies caused by hardware failures are detected, thus simulating the function of hardware lock-step.

[0052] Diversified Compilation: A compiler technology that starts from a single source code and automatically generates two or more program copies that are physically different at the binary level but are completely equivalent in logical function by applying different compilation strategies (such as instruction substitution, register allocation, data layout perturbation, etc.).

[0053] Runtime: Also known as the runtime system, it is the software layer that provides core services during program execution. In this invention, it specifically refers to the underlying software system responsible for managing the loading, synchronization, data voting, fault adjudication, and handling of diverse program copies.

[0054] Commercial off-the-shelf (COTS) refers to standardized, non-customized commercial products that can be purchased directly from the market, typically general-purpose processors, chips, or software components. This contrasts with application-specific integrated circuits (ASICs) designed specifically for particular applications.

[0055] N-Version Programming: A classic software fault-tolerance method that involves organizing N independent teams to develop N different software versions based on the same requirements, and using voting at runtime to shield potential software design flaws.

[0056] Random hardware failure refers to unpredictable malfunctions of electronic components caused by physical factors such as aging, cosmic rays, and electromagnetic interference. Single-event upsets (SEUs) induced by high-energy particles are one of the main causes of transient calculation errors.

[0057] Non-Maskable Interrupt (NMI): A hardware interrupt with the highest priority that cannot be masked (ignored) by the operating system or ordinary programs through software. It is typically used to handle the most urgent system events, such as serious hardware failures, ensuring that the system can immediately enter the preset fault handling routine.

[0058] Inter-Processor Interrupt (IPI): In a multi-core processor system, this is a mechanism by which one processor core sends an interrupt signal to one or more other cores. It is a key hardware feature for achieving efficient communication and synchronization between cores.

[0059] Busy wait (Spin-wait / Spinlock): A synchronization technique where a processor core continuously checks the condition in a loop when it needs to wait for a certain condition to be met (such as waiting for another core to complete a task), without voluntarily relinquishing CPU execution rights. This method has extremely low latency and is suitable for scenarios with very short waiting times.

[0060] Voting Stub: A small piece of code automatically inserted into a critical location in the source code by a multi-source compiler. Its function is to invoke the voting service provided by the runtime system, submit the calculation result of this copy of the program to shared memory, and participate in the synchronization and comparison process.

[0061] Process Image Output (PIO): A specific area in the PLC's memory used to cache the values ​​to be written to the physical output modules (such as relays and servo drives) in the next scan cycle. At the end of the scan cycle, the PLC firmware updates the entire PIO area's data to the physical output hardware all at once.

[0062] Example 1

[0063] Please see Figure 1 This invention provides a PLC multi-core software lockstep fault-tolerant method, applied to a PLC multi-core software lockstep fault-tolerant system. The system includes a compiler and a runtime, comprising:

[0064] S1. Based on the compiler, perform diversified compilation on the intermediate representation or low-level language code obtained by compiling the PLC high-level language source code to obtain at least two differentiated program copies;

[0065] This step involves a diversified compilation process to address the reliance on dedicated hardware for hardware lockstepping technology and the high development costs of N-version programming. It aims to automatically generate multiple executables with inherent differences from a single source program. Specifically, the compiler, as the functional entity implementing this step, processes the intermediate representation or low-level language code (e.g., structured text conforming to IEC 61131-3) derived from the input PLC high-level language source code through its embedded diversified code generation engine. This engine generates two or more physically distinct but functionally equivalent program copies at the binary level by applying at least one differentiated compilation strategy, such as instruction-level diversification (e.g., selecting different sets of physical registers for different copies or replacing them with equivalent instruction sequences) or data layout diversification (e.g., changing the order of global variables in memory segments). This automated process ensures the necessary diversity among the program copies, allowing subsequent redundant execution to effectively expose computational discrepancies caused by random transient failures of the processor core, cache, or memory units, while avoiding the risks of logical inconsistencies and exorbitant costs associated with manually developing multiple versions in N-version programming.

[0066] S2. According to the runtime, each differentiated program copy is loaded and run on a different processor core, and the periodic tasks are executed synchronously according to the preset hardware synchronization mechanism during the runtime.

[0067] This step is executed at runtime, and its motivation is to ensure that multiple program copies maintain macroscopic temporal consistency, thereby laying the foundation for subsequent validity comparisons at deterministic execution points. In implementation, during the initialization phase, the runtime loads the differentiated program copies generated in step S1 onto different isolated cores of a commercial multi-core processor. During runtime, cyclical tasks are executed synchronously according to a preset hardware synchronization mechanism. This hardware-based synchronization mechanism overcomes the timing jitter and uncertainty that pure software synchronization may introduce, ensuring that the execution flow of all copies remains aligned at the macroscopic cyclical level. This guarantees that they are within a comparable timing window when calculating critical data, providing the necessary time consistency guarantee for the consistency verification in step S3.

[0068] The pre-defined hardware synchronization mechanism controls the synchronization of all processor cores based on cross-core interrupts sent by the master processor core. At the beginning of each control scan cycle, the runtime service designated on the master processor core sends synchronization signals to other cores executing copies via the cross-core interrupt mechanism provided by the processor architecture. A cross-core interrupt is a hardware-supported inter-core communication facility that can wake up or notify the target core in a low-latency and deterministic manner. Upon receiving this interrupt, all slave cores begin executing the tasks of the current cycle together with the master core.

[0069] S3. During the synchronous execution of the cycle task across all processor cores, the runtime performs a consistency check on the execution of each processor core based on the voting stubs preset by the compiler in each program copy, and obtains the check result.

[0070] This step is executed at runtime. Its core lies in making output decisions at pre-defined checkpoints in the program flow. The motivation is to accurately capture computational deviations caused by hardware failures without introducing excessive performance overhead. In implementation, during the compilation phase (step S1), the compiler automatically inserts voting stub code at critical execution points, especially before operations whose execution results will affect the external security state of the system, such as before writing data to the process image output area. A voting stub is a small piece of code injected by the compiler to call the runtime voting service. When any processor core executes to this voting stub, it pauses its current thread, writes the critical data to be verified (such as calculated output values ​​and state variables) to a designated area of ​​the inter-core shared memory, sets its own ready flag, and then enters a waiting state. The runtime system, usually managed by the main processor core, continuously monitors the ready flags of all cores. When it detects that all cores participating in the voting have set their flags, indicating that they have reached the same logical point and committed data, the main core initiates a consistency check operation. This operation typically compares the corresponding data committed by multiple copies in shared memory bitwise or by value. This design concentrates resource-intensive comparison operations at a single point and inserts voting points only on the critical path, thereby achieving a balance between fault detection coverage and system runtime performance, ensuring the timeliness and effectiveness of fault detection.

[0071] S4. If the verification result is consistent, then clear all ready flags according to the runtime, and each processor core continues to execute subsequent instructions.

[0072] This step, executed at runtime, defines the normal operating procedure of the system when no fault is detected. Its motivation is to ensure that the system can efficiently and reliably recover to the parallel execution state after passing the consistency check, thus maintaining the real-time performance of the control task. When the consistency check result in step S3 indicates that the data submitted by all program replicas is completely consistent, the runtime service on the main processor core will perform a cleanup operation, specifically clearing the ready flags corresponding to each core in the inter-core shared memory. This cleanup action acts as a synchronous release signal, enabling all cores in the waiting state to simultaneously detect that the condition is met, thereby immediately exiting the waiting loop from the voting stub code and continuing to execute their subsequent instruction stream. This mechanism implements a lightweight and deterministic synchronous release, avoiding confusion in the next cycle's voting process due to residual flags, ensuring the continuous and correct advancement of the multi-replica execution process, and thus minimizing the impact of the entire fault-tolerant system on the normal real-time performance of the PLC application when no fault occurs.

[0073] In some implementations, S1 involves performing a diversified compilation of the intermediate representation or low-level language code obtained from the PLC high-level language source code using a compiler, resulting in at least two differentiated program copies, including:

[0074] S11. Compile the intermediate representation or low-level language code obtained by compiling the PLC high-level language source code into at least two program copies according to the compiler.

[0075] This initial step aims to prepare the foundational execution for subsequent diversified processing. Its motivation lies in establishing an initial framework that allows for the application of differentiated compilation strategies, ensuring that all derived copies originate from the same logical source. Specifically, the compiler first performs routine syntactic and semantic analysis on the intermediate representation or low-level language code compiled from the input PLC high-level language source code, generating an intermediate representation; this process ensures the functional logical homogeneity of the program copies. Subsequently, instead of generating a single object code, the compiler initiates at least two independent code generation processes based on the same intermediate representation, thus producing two or more initial program copies. These initial copies are logically equivalent but remain physically independent entities.

[0076] S12. Based on the preset optimization strategy, different optimization processes are applied to the code structure and execution path of each program copy to obtain the optimized program copy corresponding to each program copy. The optimization strategy includes loop unrolling strategy and process inlining strategy.

[0077] The motivation behind this step is to introduce high-level semantic structural differences between different program copies by applying macroscopic code transformations, thereby reducing the sensitivity of their execution flow to hardware failures. In implementation, the compiler assigns a mutually exclusive combination of high-level optimization strategies to each initial program copy. For example, a loop unrolling strategy can be applied to a specific function in the first copy, which reduces loop control overhead by copying the loop body multiple times, resulting in a more linear code structure with more repetitive instruction sequences. Simultaneously, a procedural inlining strategy is applied to the same function in the second copy, which directly replaces the function call with the function body of the called function, eliminating the call instruction and altering the program's call stack structure and locality. These two strategies reconstruct the code's control flow graph and basic block layout from different dimensions, causing the same algorithm to exhibit different macroscopic instruction sequence forms in different copies. This structural difference makes it difficult for transient failures to trigger completely identical control flow errors in multiple copies, thus improving the fault detection coverage of the fault tolerance mechanism at the macroscopic level.

[0078] S13. Based on the instructions of each optimized program copy, perform instruction difference processing to obtain the instruction processing program copy corresponding to the instructions of each optimized program copy.

[0079] The motivation behind this step is to further introduce randomness at the instruction encoding and execution timing levels, building upon the macroscopic structural differences established in step S12, to prevent localized hardware failures targeting specific instructions or registers. After completing advanced optimizations, the compiler performs instruction-level differentiation processing on each optimized program copy during the target code generation phase. This includes, but is not limited to: register allocation substitution, i.e., assigning different sets of physical registers to different copies; and equivalent instruction sequence replacement, i.e., utilizing functionally equivalent instructions with different opcode or operand types existing in the processor instruction set. Through such operations, even if two copies execute the same logic at a high level, their final binary machine code sequence, register dependencies, and power consumption and timing characteristics during execution will differ. This microscopic difference means that a single bit flip caused by factors such as particle collisions is very likely to only affect the instruction decoding or execution result of one copy, thus being captured by subsequent consistency checks.

[0080] S14. Based on the variables in each instruction handler copy, perform variable difference processing to obtain the differentiated program copy corresponding to each instruction handler copy.

[0081] The motivation behind this step is to extend the diversity of the instruction level to the data access level by altering the program's data memory layout, thereby isolating the risk of data corruption caused by memory unit or address bus failures. The compiler differentiates the data layout of the instruction handler copy generated in the preceding steps. Specifically, this includes scrambling the relative order of global and static variables in the .data or .bss data segment, disrupting their default memory arrangement; it also randomizes the order and padding of local variables in the stack frame. After this processing, the same logical variable may reside at different physical memory addresses in different copies. Therefore, a transient failure targeting a specific physical memory address can corrupt different logical variables in different copies, leading to inconsistent calculation results at the data level. This, combined with the code structure and instruction sequence differences introduced in the preceding steps, constitutes a multi-dimensional protection system covering code execution and data access, significantly reducing the probability of common-mode failures and ensuring the effectiveness of the software lockstep mechanism.

[0082] In some embodiments, the instruction difference processing includes at least one of the following:

[0083] 1. Allocate mutually exclusive or partially overlapping sets of preferred registers for different copies of the program;

[0084] Specifically, for example, on an ARM processor with 32 general-purpose registers, the compiler can be configured to prioritize the use of registers R0 to R15 when generating copy A, and prioritize the use of registers R16 to R31 when generating copy B. This deliberate isolation of physical register resources ensures that errors caused by register file bit flipping in one copy are extremely difficult to reproduce accurately in another copy using a different set of registers.

[0085] 2. Based on the preset equivalent instruction pattern library, perform equivalent replacement on the instructions in the program copy;

[0086] Specifically, this equivalent instruction pattern library is a pre-verified set of instruction mapping rules containing multiple instructions with identical semantic functions but different binary opcodes. For example, an addition instruction ADD R1,R2,R3 can be replaced with an equivalent reverse subtraction instruction RSB R1,R3,R2 (when the operand order is adjustable), or a comparison instruction CMP R0,#0 can be replaced with a test instruction TST R0,R0. Through this micro-level semantic equivalence transformation of instructions, fundamental differences in the binary instruction streams of different copies can be achieved without changing the program logic.

[0087] 3. Without violating data dependencies, rearrange the order of independent instructions in the program copy and / or randomly insert no-operation instructions into the instruction sequence.

[0088] Specifically, independent instructions refer to those instructions that do not have read-write dependencies. The compiler or assembler can rearrange their issue order. For example, the instruction sequence LDR R1,[R0]; ADD R2,R3,R4 can be rearranged to ADD R2,R3,R4; LDR R1,[R0]. This changes the layout of the instructions in memory and the timing of the processor's instruction fetching and decoding. Furthermore, NOP (no-operation) instructions can be randomly inserted, which artificially creates different time delays and memory address offsets in the instruction sequence. This means that even when two copies are executing the same computational logic, the physical distribution of their corresponding machine code in memory and the execution timeline of the processor core are completely different.

[0089] In some implementations, S14 involves performing variable difference processing based on the variables in each instruction processor copy to obtain a differentiated program copy corresponding to each instruction processor copy, including:

[0090] S141. Randomly arrange the local variables in the function stack frame corresponding to each instruction handler copy and randomly insert padding bytes between each local variable to obtain a data layout program copy.

[0091] Specifically, a function stack frame is a contiguous area allocated in stack memory during a function call to store local variables, return addresses, and other information. During standard compilation, the layout order of local variables within the stack frame is usually related to the declaration order in the source code or the compiler's fixed optimization strategy. To achieve differentiation, when generating object code for each instruction handler copy, the compiler intentionally randomizes the relative offset addresses of local variables within the same function within the stack frame, i.e., changes their physical arrangement order. Simultaneously, the compiler also randomly inserts padding bytes of variable length between these variables. For example, for a function containing three integer variables a, b, and c, the layout order in the stack frame of copy A might be a-padding-c-padding-b, while in copy B it might be b-padding-a-padding-c. This processing causes the same logical variable to occupy different physical memory locations in different copies of the stack frame, and the contents of their adjacent memory units are also completely different. A bit flip fault targeting a specific region of the stack memory (e.g., hitting the location of variable a in replica A) is very likely to hit another variable (such as variable b) or a padding region in replica B, thus triggering different error modes at the data level and ensuring that the fault can be caught by subsequent consistency checks.

[0092] And / or, S142, adjust the storage order of global and static variables in memory corresponding to each instruction handler copy.

[0093] Specifically, global and static variables are typically placed in the program's data segments (such as .data and .bss), which have a fixed memory layout at program loading time. Traditional compilation and linking processes arrange these variables in a predetermined order (such as symbol table order). In this step, the compiler or linker, when generating the final executable image, changes the relative storage order of these variables in the corresponding data segments for different instruction handler copies. For example, a set of global variables X, Y, and Z declared in the source code might be stored consecutively in the data segment of copy A in the order X, Y, Z, while in copy B they are rearranged to Z, X, Y. This scrambling of global data segments disrupts the mapping relationship of global state data at physical memory addresses between different copies. Therefore, a memory controller failure sufficient to affect the value of variable Y in copy A, or a single-event flip caused by a cosmic ray, will affect variable X at the same physical address in copy B, resulting in a detectable divergence in the global state of the two copies, effectively preventing common-mode errors caused by data memory failures.

[0094] In some implementations, S3, the process of the runtime performing a consistency check on the operation of each processor core based on the voting stubs preset by the compiler in each program copy, and obtaining the check result, includes:

[0095] S31. According to the voting stubs preset in each program copy by the compiler, when the runtime detects that any processor core has reached the voting point corresponding to the voting stub, it generates data to be verified and a ready flag and enters a busy waiting state.

[0096] The motivation behind this invention is to build a non-blocking, low-overhead distributed data commit mechanism to ensure that each program copy can pause its execution flow and safely commit its intermediate computational state when it reaches a point that has a critical impact on the external state of the system, preparing for subsequent centralized consensus decisions. Specifically, a voting stub is a small piece of code automatically inserted into a specific location in the program during the compilation phase by a diverse compiler. These locations are typically at the forefront of the execution flow where output (such as writing to the process image output area) or critical state updates are about to occur. When any program copy running on different processor cores reaches this voting stub, it performs the following atomic operations: First, it copies the critical data that needs to be verified, such as a set of computation results about to be written to the physical output, from its local memory space to its dedicated commit area in an inter-core shared memory area accessible to all cores; this data is the data to be verified. Then, the core sets a ready flag bound to it in the shared memory to announce to the system that it has reached the synchronization point and completed the data commit. After completing the above actions, the processor core immediately enters a loop state called busy wait. In this state, it continuously polls and checks a global synchronization condition controlled by the runtime system without continuing to execute subsequent program instructions. This design allows the replica to pause immediately after data is committed, preventing contamination of subsequent states due to continued execution, thus ensuring the purity and comparability of the committed data state. At the same time, the busy wait mechanism has extremely low latency in scenarios with very short expected waiting times, ensuring the real-time performance of fault tolerance detection.

[0097] S32. When all processor cores generate a ready flag, perform a consistency check on all data to be checked and obtain the check result.

[0098] The motivation behind this invention is to provide a centralized, efficient, and deterministic decision-making mechanism that detects execution divergences caused by hardware failures by comparing computation results from multiple redundant execution paths. In implementation, this process is driven by a synchronous voting runtime service designated on the main processor core (e.g., Core 0). This runtime service continuously or periodically monitors the ready flags of all cores participating in lockstep execution in the inter-core shared memory. Only when it detects that the ready flags of all cores are set does it indicate that all redundant replicas have safely arrived at the same logical voting point and completed the submission of the data to be verified, thus entering a stable, comparable state window. Subsequently, the main processor core activates its consistency verification logic, which includes a bitwise or value-wise comparison algorithm to compare the data submitted by each replica in the shared memory item by item. This centralized adjudication method avoids the communication complexity and timing issues that may arise from distributed voting. After verification, a clear verification result is obtained: the data is completely consistent or inconsistent. The technical advantage of this design is that it concentrates resource-intensive comparison operations on a single core, improving execution efficiency, and ensures the freshness and consistency of data at the time of comparison through direct access to shared memory, thus providing a reliable basis for the system to trigger an immediate and deterministic response when a fault is detected.

[0099] In some embodiments, the method further includes:

[0100] If the verification result is inconsistent, a non-maskable interrupt is triggered, and the process jumps to the fault handling program. The fault handling program will record the diagnostic information and put the PLC into a safe shutdown state.

[0101] This step, after detecting execution discrepancies caused by hardware faults through consistency checks, provides an immediate, reliable, and uninterruptible response mechanism to ensure the control system can quickly transition to a predefined stable and safe state. This prevents erroneous calculation results from having unsafe effects on external actuators and preserves crucial fault scene information for post-event diagnosis. Specifically, when the verification result obtained by the main processor core in step S32 indicates inconsistencies in the data to be verified across multiple program copies, the runtime system immediately triggers a non-maskable interrupt via software instructions. A non-maskable interrupt is a hardware interrupt mechanism with the highest priority. Its key characteristic is that it cannot be ignored by the operating system or application programs by masking interrupt instructions, thus ensuring an absolutely unobstructed fault response path. After triggering this interrupt, the processor's hardware logic forcibly suspends any instructions currently being executed on all cores and automatically jumps the program counter to the non-maskable interrupt handler pre-bound to a fixed memory address, i.e., the fault handler in this embodiment. This fault handling program, as a rigorously verified piece of highly reliable code, exhibits atomicity and determinism in its execution. It first performs diagnostic information recording, including dumping inconsistent data to be verified in the shared memory between cores, the program counter values ​​of each core at the time of the fault, register snapshots, and system timestamps—all context states—to a specific area of ​​non-volatile memory. This action provides crucial first-hand data for subsequent root cause analysis. Next, the program invokes the PLC's safety function logic to cut off the power output of the output modules, for example, by setting safety signals or invoking the driver's safety torque shutdown function. This puts all controlled actuators (such as motors and valves) into a powerless or holding state, thereby achieving a safe system shutdown. Through this series of actions, a closed-loop control chain is established from fault detection to safety response. The non-maskable interrupts guaranteed by hardware ensure the timeliness and necessity of the response, and by recording diagnostic information and guiding the system to a safe state, the spread of fault consequences is minimized, meeting the core functional safety requirements of industrial control systems.

[0102] For example, in a typical five-axis CNC machine tool or high-speed packaging robot application, one of the core tasks of the PLC is to calculate and output the position setpoints of multiple servo axes (X, Y, Z, A, C) in real time for each control cycle (typically 1-4 milliseconds) based on preset G-code or motion programs. This involves complex floating-point operations such as inverse kinematics, trajectory interpolation (linear, circular, helical), and velocity planning.

[0103] Even a tiny calculation error can cause a tool or robotic arm to deviate from its intended trajectory, with possible consequences:

[0104] High-value workpiece scrapping: When processing expensive workpieces such as aero-engine blades and precision molds, even a slight deviation in the path can lead to the direct scrapping of the entire workpiece, which is worth hundreds of thousands.

[0105] Equipment damage and safety risks: Incorrect paths may cause the tool to collide with the workpiece or machine tool fixture, damaging the spindle, tool and servo system, and even posing a safety threat to on-site operators.

[0106] In this embodiment, as Figure 2 As shown, a PLC equipped with a standard, commercial (COTS) quad-core ARM processor is used to complete the motion control tasks of the aforementioned five-axis CNC.

[0107] Compilation stage:

[0108] Machine tool manufacturers use ST (Structured Text) language, which conforms to the IEC 61131-3 standard, to write motion control programs. The program contains a key function block called Trajectory_Interpolator, which is responsible for calculating the position increments of each axis for the next cycle based on the target point and interpolation type.

[0109] The ST source code was fed into the diverse code generation compiler of this invention.

[0110] Instruction-level diversity: The Trajectory_Interpolator function block contains a large number of floating-point (LREAL type) multiplication and addition operations.

[0111] like Figure 3 As shown, when the compiler generates a binary copy:

[0112] For copy A, use the processor's standard floating-point instructions and prioritize the use of the floating-point register set {S0-S15}.

[0113] For copy B, under the premise of logical equivalence, try to use the "Fused Multiply-Add" (FMA) instruction and give priority to the use of the floating-point register group {S16-S31}.

[0114] The data layout is diversified: the data blocks (DBs) storing key LREAL type variables such as target location, current location, and speed are placed at different base addresses in the memory images of replica A and replica B, and the relative order of internal variables is also shuffled.

[0115] Voting Stub Insertion: The compiler automatically recognizes that a voting stub is inserted here before the program writes the calculation results to the Process Image Output (PIO) area to control the position of the servo drive. The data to be voted on is an array containing five LREAL values, representing the position settings for the next cycle of the five axes X, Y, Z, A, and C.

[0116] Operation phase:

[0117] like Figure 4 As shown, the runtime system loads copy A onto Core 0 and copy B onto Core 1 for execution. Core 2 and Core 3 can be used for other non-safety-critical tasks, such as HMI communication or data logging.

[0118] The two replicas synchronize to start each 1ms control cycle via a shared hardware timer.

[0119] Fault detection and response:

[0120] Hypothetical scenario: While a machine tool is milling a precision curved surface, a high-energy neutron strikes the processor, causing a bit flip in a floating-point register S8 in Core 0, which is running copy A, during interpolation calculations.

[0121] Influence:

[0122] This bit flip caused a tiny deviation of 0.005mm in the position setting value of the X-axis for the next cycle calculated by copy A, resulting in a value of 125.355mm.

[0123] Replica B, running on Core 1, used a different register S24 for its calculations and was unaffected by the fault, calculating the correct location as 125.350mm.

[0124] Voting and Ruling:

[0125] The two copies arrive at the voting point almost simultaneously and submit their calculated five-axis position arrays to shared memory.

[0126] When comparing two arrays, the main core (Core 0) discovered a difference in the X-axis values ​​(the binary representation of 125.355 is different from the binary representation of 125.350).

[0127] Safety procedures:

[0128] If the vote fails, an unmaskable interrupt (NMI) is immediately triggered.

[0129] The NMI handler immediately stops writing new position settings to the process image output area and calls the servo drive's "Safe Torque Off (STO)" or "Safe Stop 1 (SS1)" function to bring all axes to a safe and rapid stop at their current positions.

[0130] The system dumps the inconsistent data (two location arrays) in shared memory and the program context at the time of the failure to flash memory and issues a "computing core failure" alarm.

[0131] Example 2

[0132] Please see Figure 5 This invention provides a PLC multi-core software lockstep fault-tolerant device, applied to a PLC multi-core software lockstep fault-tolerant system. The system includes a compiler and a runtime, comprising:

[0133] The compilation module 501 is used to perform diversified compilation of the intermediate representation or low-level language code obtained by compiling the PLC high-level language source code according to the compiler, so as to obtain at least two differentiated program copies.

[0134] The execution module 502 is used to load each differentiated program copy onto different processor cores for execution according to the runtime, and to synchronously execute periodic tasks according to a preset hardware synchronization mechanism during the runtime.

[0135] The voting module 503 is used to perform consistency verification on the operation of each processor core during the synchronous execution of the cycle task by all processor cores, based on the voting stubs preset by the compiler in each program copy, and obtain the verification result.

[0136] If the verification module 504 finds that the verification results are consistent, it will clear all ready flags during runtime, and each processor core will continue to execute subsequent instructions.

[0137] It should be noted that each module and unit in the PLC multi-core software lockstep fault-tolerant device in this embodiment corresponds one-to-one with each step in the PLC multi-core software lockstep fault-tolerant method in the aforementioned embodiment. Therefore, the specific implementation of this embodiment can refer to the implementation of the aforementioned PLC multi-core software lockstep fault-tolerant method, and will not be repeated here.

[0138] Example 3

[0139] This embodiment provides a PLC multi-core software lockstep fault-tolerant system, including:

[0140] A compiler is used to perform diverse compilations on intermediate representations or low-level language code obtained from the compilation of PLC high-level language source code, resulting in at least two differentiated program copies.

[0141] During runtime, each differentiated program copy is loaded and run on a different processor core. During runtime, the periodic tasks are executed synchronously according to a preset hardware synchronization mechanism. During the synchronous execution of periodic tasks on all processor cores, the consistency of the execution of each processor core is checked according to the voting stubs preset in each program copy by the compiler, and the check result is obtained. If the check result is consistent, all ready flags are cleared according to the runtime, and each processor core continues to execute subsequent instructions.

[0142] Example 4

[0143] Please see Figure 6 This embodiment provides an electronic device, including at least one processor 601 and a memory 602. Optionally, the device further includes a communication component 603. The processor 601, memory 602, and communication component 603 are connected via a bus 604.

[0144] In a specific implementation, at least one processor 601 executes computer execution instructions stored in memory 602, causing at least one processor 601 to perform the above-described method.

[0145] The specific implementation process of processor 601 can be found in the above method embodiments, and its implementation principle and technical effect are similar. It will not be repeated here.

[0146] In the above embodiments, it should be understood that the processor can be a Central Processing Unit (CPU), or other general-purpose processors, digital signal processors (DSPs), application-specific integrated circuits (ASICs), etc. The general-purpose processor can be a microprocessor or any conventional processor. The steps of the method disclosed in this invention can be directly implemented by a hardware processor, or implemented by a combination of hardware and software modules within the processor.

[0147] The memory may include random access memory (RAM) and may also include non-volatile memory (NVM), such as at least one disk storage device.

[0148] The bus can be an Industry Standard Architecture (ISA) bus, a Peripheral Component Interconnect (PCI) bus, or an Extended Industry Standard Architecture (EISA) bus, etc. Buses can be categorized as address buses, data buses, control buses, etc. For ease of illustration, the buses shown in the accompanying drawings are not limited to a single bus or a single type of bus.

[0149] This application also provides a computer program product, including a computer program that, when executed by a processor, implements the above-described method.

[0150] This application also provides a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, implement the above-described method.

[0151] The aforementioned readable storage medium can be implemented by any type of volatile or non-volatile storage device or a combination thereof, such as static random access memory (SRAM), electrically erasable programmable read-only memory (EEPROM), erasable programmable read-only memory (EPROM), programmable read-only memory (PROM), read-only memory (ROM), magnetic storage, flash memory, magnetic disk, or optical disk. The readable storage medium can be any available medium accessible to a general-purpose or special-purpose computer.

[0152] An exemplary readable storage medium is coupled to a processor, enabling the processor to read information from and write information to the readable storage medium. Of course, the readable storage medium can also be a component of the processor. The processor and the readable storage medium can reside in an Application Specific Integrated Circuit (ASIC). Alternatively, the processor and the readable storage medium can exist as discrete components in the device.

[0153] The division of units is merely a logical functional division; in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be indirect coupling or communication connection through some interfaces, devices, or units, and may be electrical, mechanical, or other forms.

[0154] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.

[0155] In addition, the functional units in the various embodiments of the present invention can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit.

[0156] If a function is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of this invention, or the part that contributes to the prior art, or a part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods of the various embodiments of this invention. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, or optical disks.

[0157] Those skilled in the art will understand that all or part of the steps of the above-described method embodiments can be implemented by hardware related to program instructions. The aforementioned program can be stored in a computer-readable storage medium. When executed, the program performs the steps of the above-described method embodiments; and the aforementioned storage medium includes various media capable of storing program code, such as ROM, RAM, magnetic disks, or optical disks.

[0158] The specific embodiments described above further illustrate the purpose, technical solution, and beneficial effects of the present invention. It should be understood that the above description is only a specific embodiment of the present invention and is not intended to limit the scope of protection of the present invention. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.

Claims

1. A method for lockstep fault tolerance in PLC multi-core software, characterized in that, An application in a multi-core PLC software lockstep fault-tolerant system, the system including a compiler and a runtime, comprising: The compiler is used to perform diversified compilation of the intermediate representation or low-level language code obtained by compiling the PLC high-level language source code, resulting in at least two differentiated program copies. According to the runtime, each differentiated program copy is loaded and run on a different processor core, and the cycle tasks are executed synchronously according to a preset hardware synchronization mechanism during the runtime. During the synchronous execution of cycle tasks across all processor cores, the runtime performs consistency checks on the execution of each processor core based on the voting stubs preset by the compiler in each program copy, and obtains the check results. If the verification results are consistent, all ready flags are cleared according to the runtime procedure, and each processor core continues to execute subsequent instructions.

2. The method according to claim 1, characterized in that, The process of performing diverse compilation on the intermediate representation or low-level language code obtained by compiling the PLC high-level language source code according to the compiler yields at least two differentiated program copies, including: The compiler is used to compile the intermediate representation or low-level language code obtained by compiling the PLC high-level language source code to generate at least two program copies. Based on a preset optimization strategy, different optimization processes are applied to the code structure and execution path of each program copy to obtain an optimized program copy corresponding to each program copy. The optimization strategy includes loop unrolling strategy and process inlining strategy. Based on the instructions of each optimizer copy, instruction difference processing is performed to obtain the instruction processing program copy corresponding to the instructions of each optimizer copy; Based on the variables in each instruction handler copy, variable difference processing is performed to obtain the differentiated program copy corresponding to each instruction handler copy.

3. The method according to claim 2, characterized in that, The instruction difference processing includes at least one of the following: Allocate mutually exclusive or partially overlapping sets of preferred registers for different copies of the program; Based on a pre-defined library of equivalent instruction patterns, perform equivalent substitutions on the instructions in the program copy. Without violating data dependencies, rearrange the order of individual instructions in the program copy and / or randomly insert no-operation instructions into the instruction sequence.

4. The method according to claim 2, characterized in that, The step of performing variable difference processing based on the variables in each instruction processor copy to obtain a differentiated program copy corresponding to each instruction processor copy includes: The local variables in the function stack frame corresponding to each instruction handler copy are randomly arranged and padding bytes are randomly inserted between each local variable to obtain a data layout program copy. And / or, adjust the storage order of global and static variables in memory for each instruction handler copy.

5. The method according to claim 2, characterized in that, The process of performing consistency checks on the execution of each processor core based on the voting stubs preset by the compiler in each program copy, and obtaining the check results, includes: According to the voting stubs preset in each program copy by the compiler, when the runtime detects that any processor core has reached the voting point corresponding to the voting stub, it generates data to be verified and a ready flag and enters a busy waiting state. Once all processor cores have generated a ready flag, a consistency check is performed on all data to be verified, and the verification result is obtained.

6. The method according to claim 1, characterized in that, The hardware synchronization mechanism controls all processor cores to synchronize based on cross-core interrupts sent by the master processor core.

7. The method according to any one of claims 1-6, characterized in that, The method further includes: If the verification result is inconsistent, a non-maskable interrupt will be triggered during runtime, and the process will jump to the fault handling program. The fault handling program will record the diagnostic information and put the PLC into a safe shutdown state.

8. A PLC multi-core software lockstep fault-tolerant device, characterized in that, An application in a multi-core PLC software lockstep fault-tolerant system, the system including a compiler and a runtime, comprising: The compilation module is used to perform diversified compilation of intermediate representation or low-level language code obtained by compiling PLC high-level language source code according to the compiler, so as to obtain at least two differentiated program copies; The execution module is used to load each differentiated program copy onto different processor cores for execution according to the runtime, and to synchronously execute periodic tasks according to a preset hardware synchronization mechanism during the runtime. The voting module is used to perform consistency checks on the operation of each processor core during the synchronous execution of cycle tasks across all processor cores, based on the voting stubs preset by the compiler in each program copy, and to obtain the check results. If the verification module finds that the verification results are consistent, it will clear all ready flags during runtime, and each processor core will continue to execute subsequent instructions.

9. A PLC multi-core software lockstep fault-tolerant system, characterized in that, include: A compiler is used to perform diverse compilations on intermediate representations or low-level language code obtained from the compilation of PLC high-level language source code, resulting in at least two differentiated program copies. During runtime, each differentiated program copy is loaded onto a different processor core and executed synchronously according to a preset hardware synchronization mechanism. During the synchronous execution of cycle tasks across all processor cores, a consistency check is performed on the operation of each processor core based on the voting stubs preset by the compiler in each program copy, and the check result is obtained. If the verification results are consistent, all ready flags are cleared according to the runtime procedure, and each processor core continues to execute subsequent instructions.

10. An electronic device, characterized in that, include: At least one processor, at least one memory, and computer program instructions stored in the memory, which, when executed by the processor, implement the method as described in any one of claims 1-7.