Which instruction causes machine to user mode switch?

with hello world application & with metal library my assembly code on Hifive1 Rev B board,

csrr t0, mideleg;
jalr x0, 0(ra);

jump into early trap vector due to access denial. I think this is due to user code accessing csr mideleg. Now, after reset it should be in machine mode, which code switches it into user?

hi @bsvtgc please see this freedom-e-sdk example of switching to user mode: freedom-e-sdk/example-user-mode.c at master · sifive/freedom-e-sdk · GitHub

@Jim so the mode/MPP is set to 0-user and returned.

Now how to switch from user to machine and keep executing the rest of application in machine mode. I am looking to do the exactly opposite of example. From user mode, trap into trap handler set the mode to machine and return (set mepc) to user function. In this case, will rest of the user code execute in machine mode?

hi @bsvtgc , To switch from user to machine mode you can execute an ECALL instruction.

hi @Jim thanks I used ECALL to trap into trap handler however, the mstatus register holds/reads the same value 0x1800 both in user mode and in machine mode in freedom studio with metal library. Is it okay? I am expecting the privileged levels to be changed inside trap handler.

MPP = 00 (bits 11 and 12 of MSTATUS) when you trap from user mode with ECALL. If you are reading 0x1800 after the ECALL then you were not in user mode before the trap. To enter user mode on the HiFive Rev B, make sure you set MPP = 0, set UIE = 0, MPIE = 1, setup at least one PMP, then MRET. User mode has NO PERMISSIONS by default therefore you must setup a PMP entry before the MRET instruction or you will trap before you actually enter user mode.