// K2130 guest experiment: PSCI SYSTEM_OFF path in the product kernel runtime. // Discovers the PSCI conduit from the live DTB, queries real QEMU PSCI // firmware via HVC for PSCI_VERSION, PSCI_FEATURES(SYSTEM_OFF) and an // unsupported function ID, verifies negative probes (absent PSCI and // unsupported function), runs an EL0 shell tool that is denied power-off, and // runs EL0 PID1 to reject a Reset ticket on the Off path, arm SYSTEM_OFF with // a committed Off ticket, and distinguish guest shutdown diagnosis from a bare // host QMP quit. use super::feature_el0 as el0; use turkos_kernel::runtime::guest_power_capability::{ALL,Authority,Identity,Op,Ticket}; use turkos_kernel::runtime::guest_power_psci_off::{Conduit,Error,Executor,Phase,Probe,Receipt,PSCI_FEATURES,PSCI_VERSION,SYSTEM_OFF}; use turkos_kernel::runtime::psci_call::{discover_conduit,Conduit as DtbConduit}; use core::arch::asm; use core::ptr::{addr_of,addr_of_mut,read_volatile,write_volatile}; #[unsafe(no_mangle)] static mut OS_K2130_EVIDENCE:[u64;64]=[0;64]; #[unsafe(no_mangle)] static mut OS_K2130_CAPTURE_GATE:u8=0; static SHELL_TOOL:&[u8]=include_bytes!("k2130-shell-tool.bin"); static PID1:&[u8]=include_bytes!("k2130-pid1.bin"); const MAGIC:u64=0x4b32_3133_305f_504f; // "K2130_PO" const SYS_EXIT:u64=1; const SYS_REQUEST:u64=16; const SYS_ARM_OFF:u64=17; const SYS_WORK:u64=18; const SYS_VERIFY:u64=19; const UNSUPPORTED_FN:u64=0x8400_00ff; const REFUSED:u64=1<<63; const PID1_ID:el0::Identity=el0::Identity{pid:1,generation:0x2130_0001}; struct State{ authority:Option, exec:Option, held:Option<(el0::Identity,Ticket)>, user:Option, boot_id:u64, conduit:Conduit, work:u64, calls:usize, base:usize, } static mut STATE:State=State{authority:None,exec:None,held:None,user:None,boot_id:0,conduit:Conduit::Hvc,work:0,calls:0,base:0}; fn state()->&'static mut State{unsafe{&mut *addr_of_mut!(STATE)}} fn word(i:usize,v:u64){unsafe{write_volatile(addr_of_mut!(OS_K2130_EVIDENCE).cast::().add(i),v)}} #[inline(never)] fn checkpoint(stage:u64){ word(1,stage); unsafe{write_volatile(addr_of_mut!(OS_K2130_CAPTURE_GATE),0)}; el0::write_fields("TURKOS/OS/K2130: CAPTURE",&[("STAGE",stage)]); while unsafe{read_volatile(addr_of!(OS_K2130_CAPTURE_GATE))}==0{unsafe{asm!("yield",options(nomem,nostack,preserves_flags))}} } fn identity(id:el0::Identity)->Identity{Identity{pid:id.pid,generation:id.generation}} fn hvc(function:u64,arg0:u64)->u64{ let out:u64; unsafe{asm!("hvc #0",inout("x0")function=>out,inout("x1")arg0=>_,lateout("x2")_,lateout("x3")_,options(nomem,nostack))}; out } fn code(r:Result)->u64{match r{Ok(_)=>0,Err(e)=>REFUSED|e as u64}} #[inline(never)] fn probe_stage(boot:&super::BootData)->Result<(),&'static str>{ let boot_id=unsafe{read_volatile(addr_of!(super::OS_K680_EVIDENCE).cast::())}; let blob=unsafe{core::slice::from_raw_parts(boot.dtb_address as *const u8,boot.dtb_size)}; let scratch=unsafe{&mut *addr_of_mut!(super::OS_K700_WORKSPACE)}; let dtb_conduit=discover_conduit(blob,scratch).map_err(|_|"k2130-dtb-psci")?; let conduit=match dtb_conduit{DtbConduit::Hvc=>Conduit::Hvc,DtbConduit::Smc=>Conduit::Smc}; if conduit!=Conduit::Hvc{return Err("k2130-expected-hvc")} let version=hvc(PSCI_VERSION,0) as u32; let features_off=hvc(PSCI_FEATURES,SYSTEM_OFF) as u32 as i32; let features_bad=hvc(PSCI_FEATURES,UNSUPPORTED_FN) as u32 as i32; let mut neg_absent=Executor::new(boot_id).map_err(|_|"k2130-neg-absent")?; let err_absent=code(neg_absent.probe(Probe{present:false,enabled:true,compatible:true,conduit:None,version:0,features_off:-1})); let mut neg_unsup=Executor::new(boot_id).map_err(|_|"k2130-neg-unsup")?; let err_unsup=code(neg_unsup.probe(Probe{present:true,enabled:true,compatible:true,conduit:Some(conduit),version,features_off:features_bad})); let mut exec=Executor::new(boot_id).map_err(|_|"k2130-exec")?; let probed=exec.probe(Probe{present:true,enabled:true,compatible:true,conduit:Some(conduit),version,features_off}).map_err(|_|"k2130-probe")?; for(j,v)in[boot_id,conduit as u64,version as u64,features_off as i64 as u64,features_bad as u32 as u64,err_absent,neg_absent.status().refused,err_unsup,neg_unsup.status().refused,probed.phase as u64,probed.conduit,probed.version as u64].into_iter().enumerate(){word(4+j,v)} let st=state(); st.authority=Some(Authority::new(identity(PID1_ID),ALL).map_err(|_|"k2130-authority")?); st.exec=Some(exec); st.held=None; st.boot_id=boot_id; st.conduit=conduit; Ok(()) } fn dispatch(caller:el0::Identity,frame:&mut el0::Frame)->el0::Step{ let st=state(); let authority=st.authority.as_mut().unwrap(); let exec=st.exec.as_mut().unwrap(); let r=match frame.number(){ SYS_REQUEST=>{ let op=match frame.arg(0){1=>Op::Off,2=>Op::Reset,_=>return el0::Step::Exit(0xbad)}; match authority.request(identity(caller),op){Ok(t)=>{let s=t.sequence();st.held=Some((caller,t));s}Err(e)=>REFUSED|e as u64} } SYS_ARM_OFF=>match st.held.take(){ Some((owner,t)) if owner==caller=>{ let seq=t.sequence(); match authority.commit(t){ Ok(op)=>match exec.arm_off(op as u64,seq){Ok(inv)=>inv.function,Err(e)=>REFUSED|e as u64}, Err((e,t))=>{st.held=Some((owner,t));REFUSED|e as u64} } } other=>{st.held=other;REFUSED|Error::Ticket as u64} }, SYS_WORK=>{st.work+=1;st.work} SYS_VERIFY=>{ let guest_ok=frame.arg(0)==1; let receipt=Receipt{boot_id:st.boot_id,conduit:st.conduit,function:SYSTEM_OFF,ticket_sequence:exec.status().last_ticket,guest_diagnosed:guest_ok,host_quit:!guest_ok}; code(exec.verify_guest_off(receipt)) } SYS_EXIT=>return el0::Step::Exit(frame.arg(0)), _=>return el0::Step::Exit(0xbad), }; if st.calls<6{word(st.base+st.calls,r);st.calls+=1} frame.ret(r);el0::Step::Resume } #[inline(never)] fn run_program(allocator:&mut super::memory::FrameAllocator,tables:&super::mmu::Tables,boot:&super::BootData,id:el0::Identity,image:&[u8],base:usize)->Result{ let st=state(); st.user=Some(unsafe{tables.build_user_space(allocator,boot.hardware.ram_base,boot.hardware.ram_size)}.map_err(|_|"k2130-user")?); let user=st.user.as_ref().unwrap(); if !user.contract_valid(tables.root){return Err("k2130-user-contract")} unsafe{el0::load(user,image)}?; st.work=0;st.calls=0;st.base=base; let mut handler=dispatch; let outcome=unsafe{el0::run(st.user.as_ref().unwrap(),id,[0,0],&mut handler)}; let user=st.user.take().unwrap(); unsafe{user.release_after_tlbi(allocator,tables.root)}.map_err(|_|"k2130-release")?; Ok(outcome) } #[inline(never)] fn record_shell(shell:&el0::Outcome){ let st=state(); let as1=st.authority.as_ref().unwrap().status(); let es1=st.exec.as_ref().unwrap().status(); for(j,v)in[shell.exit,shell.syscalls,shell.fault,as1.denied,as1.issued,es1.phase as u64,es1.armed,es1.refused].into_iter().enumerate(){word(24+j,v)} } #[inline(never)] fn finish_stage(shell:&el0::Outcome,pid1:&el0::Outcome,free_before:u64,free_after:u64)->Result<(),&'static str>{ let st=state(); let as2=st.authority.as_ref().unwrap().status(); let es2=st.exec.as_ref().unwrap().status(); for(j,v)in[pid1.exit,pid1.syscalls,pid1.fault,as2.issued,as2.committed,as2.denied,as2.pending,es2.boot_id,es2.phase as u64,es2.conduit,es2.version as u64,es2.armed,es2.refused,es2.returned_failures,es2.last_ticket,SYSTEM_OFF].into_iter().enumerate(){word(40+j,v)} word(3,free_after); if free_after!=free_before{return Err("k2130-frame-accounting")} if shell.exit!=4||pid1.exit!=0x201||es2.phase!=Phase::Armed||es2.armed!=1||es2.refused!=1||as2.committed!=2{return Err("k2130-outcome")} checkpoint(3); el0::write_fields("TURKOS/OS/K2130-PSCI-OFF:",&[("BOOT_ID",st.boot_id),("CONDUIT",es2.conduit),("VERSION",es2.version as u64),("FEATURES_OFF",0),("ARMED",es2.armed),("REFUSED",es2.refused),("HOST_QUIT_REJECTED",1),("FREE_EQUAL",1)]); Ok(()) } #[inline(never)] fn run_inner(runtime:&mut super::OsK660Runtime,tables:&super::mmu::Tables,boot:&super::BootData)->Result<(),&'static str>{ let allocator=&mut runtime.memory_mut().map_err(|_|"k2130-memory")?.allocator; let free_before=allocator.remaining_pages();word(0,MAGIC);word(2,free_before as u64); probe_stage(boot)?; checkpoint(1); let shell=run_program(allocator,tables,boot,el0::Identity{pid:9,generation:0x2130_0009},SHELL_TOOL,16)?; record_shell(&shell); checkpoint(2); let pid1=run_program(allocator,tables,boot,PID1_ID,PID1,32)?; let free_after=allocator.remaining_pages(); finish_stage(&shell,&pid1,free_before,free_after) } extern "C" fn entry(runtime:*mut super::OsK660Runtime,tables:*const super::mmu::Tables,boot:*const super::BootData,out:*mut Result<(),&'static str>){ unsafe{*out=run_inner(&mut *runtime,&*tables,&*boot)} } #[inline(never)] pub fn run(runtime:&mut super::OsK660Runtime,tables:&super::mmu::Tables,boot:&super::BootData)->Result<(),&'static str>{ let mut out:Result<(),&'static str>=Ok(()); let top=(addr_of!(super::OS_K900_STACK) as u64+4096+65536-16)&!15; unsafe{asm!( "mov x9, sp", "mov sp, x4", "stp x9, x30, [sp, #-16]!", "blr x5", "ldp x9, x30, [sp], #16", "mov sp, x9", in("x0")runtime as *mut _, in("x1")tables as *const _, in("x2")boot as *const _, in("x3")&mut out as *mut _, in("x4")top, in("x5")entry as usize, clobber_abi("C"), )}; out }