cartesi / machine-emulator

The off-chain implementation of the Cartesi Machine
GNU Lesser General Public License v3.0
58 stars 32 forks source link

Add soft yield instruction #161

Closed edubart closed 5 months ago

edubart commented 8 months ago

This PR introduces the soft yield runtime config, it's a new kind of yield with the purpose of stopping the interpreter main loop immediately, to execute external code outside the machine.

This feature is only useful when using libcartesi library in applications that uses cartesi machine in its frontend, and has no use in the cartesi-machine cli or in the rollups backend, and it's disabled by default.

A soft yield happens when soft yield runtime config is true and the instruction SRAIW x0, x31, shamt is executed for any given shamt (32 possible values), the main interpreter loop will break with CM_BREAK_REASON_YIELDED_SOFTLY reason, and the programmer of the cartesi machine can handle this situation to perform operations in the outside.

When this instruction is executed in the rollups backend, it works as a NOP operation, while being a valid RISC-V instruction. SRAIW was chosen from the list of HINT instructions reserved from custom use in the RISC-V specification. Only shift instructions have HINTs available reserved for custom use, I choose SRAIW because I think it's the most uncommon one among the available shift instructions, to impact less the additional branching.

The main advantage of the soft yield when comparing with automatic yields are:

This is a solution for #134 , more disadvantages of automatic yields were also described there

Depends on