Guest User

Untitled

a guest
Apr 14th, 2026
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 8.84 KB | None | 0 0
  1. // SPDX-License-Identifier: GPL-2.0-only OR MIT
  2. #![recursion_limit = "2048"]
  3.  
  4. //! Apple PMPv1 driver
  5. //!
  6. //! Copyright (C) The Asahi Linux Contributors
  7.  
  8. #![no_std]
  9.  
  10. #![cfg(CONFIG_RUST_APPLE_PMP_V1= "y")]
  11.  
  12. use core::{
  13.     mem,
  14.     slice,
  15. };
  16.  
  17. use kernel::{
  18.     bindings,
  19.     device::{
  20.         self,
  21.         Core,
  22.     },
  23.     platform,
  24.     devres::Devres,
  25.     dma,
  26.     io::mem::IoMem,
  27.     iosys_map::IoSysMapRef,
  28.     module_platform_driver,
  29.     new_mutex,
  30.     of,
  31.     prelude::*,
  32.     soc::apple::rtkit,
  33.     sync::{
  34.         Arc,
  35.         Mutex,
  36.     },
  37.     types::{
  38.         ARef,
  39.         ForeignOwnable,
  40.     },
  41. };
  42.  
  43.  
  44. const PMP_MMIO_SIZE: usize = 0x10000;
  45. const ASC_MMIO_SIZE: usize = 0x4000;
  46. const PMP_ENDPOINT: u8 = 0x20;
  47. const OPC_STARTUP: u64 = 0;
  48. const OPC_CONFIGURE: u64 = 0x10;
  49. const OPC_CONFIGURE_ACK: u64 = 0x20;
  50. const OPC_INIT1: u64 = 0x200;
  51. const OPC_INIT1_ACK: u64 = 0x201;
  52. const OPC_INIT2: u64 = 0x202;
  53. const OPC_INIT2_ACK: u64 = 0x203;
  54. const OPC_DEVPWR: u64 = 0x20e;
  55. const OPC_DEVPWR_SYNC: u64 = 0x208;
  56. const OPC_DEVPWR_ACK: u64 = 0x209;
  57. const OPC_CHANGESTATE1: u64 = 0x20c;
  58. const OPC_CHANGESTATE1_ACK: u64 = 0x20d;
  59. const OPC_CHANGESTATE2: u64 = 0x20a;
  60. const OPC_CHANGESTATE2_ACK: u64 = 0x20b;
  61. const OPC_SHIFT: u32 = 48;
  62.  
  63. type ShMem = dma::CoherentAllocation<u8>;
  64.  
  65. struct PmpState {
  66.     devpwr_status: u64
  67. }
  68.  
  69. impl PmpState {
  70.     fn new() -> Result<Self> {
  71.         Ok(PmpState { devpwr_status: 0 })
  72.     }
  73.  
  74.     fn get_device_power_status(&self, dev: u64) -> bool {
  75.         self.devpwr_status & (1 << dev) == 1
  76.     }
  77.  
  78.     fn set_device_power_status(&mut self, dev: u64) {
  79.         self.devpwr_status ^= 1 << dev;
  80.     }
  81. }
  82.  
  83. #[pin_data]
  84. struct PmpData {
  85.     dev: ARef<device::Device>,
  86.     pmp_mmio: Pin<KBox<Devres<IoMem<PMP_MMIO_SIZE>>>>,
  87.     asc_mmio: Pin<KBox<Devres<IoMem<ASC_MMIO_SIZE>>>>,
  88.     #[pin]
  89.     rtkit: Mutex<Option<rtkit::RtKit<PmpData>>>,
  90.     #[pin]
  91.     state: Mutex<PmpState>,
  92.     shmem: ShMem,
  93. }
  94.  
  95. fn build_shmem(dev: &platform::Device<device::Core>) -> Result<ShMem> {
  96.     let mut shmem =
  97.         dma::CoherentAllocation::<u8>::alloc_coherent(dev.as_ref(), PMP_MMIO_SIZE, GFP_KERNEL)?;
  98.     let fwnode = dev.as_ref().fwnode().ok_or(EIO)?;
  99.  
  100.     // SAFETY:
  101.     // Only this driver communicates with PMP. PMP waits for Configure message
  102.     // thus no r/w operations from the shared memory.
  103.     unsafe {
  104.         shmem.as_slice_mut(0, shmem.count())?.fill(0);
  105.     }
  106.  
  107.     Ok(shmem)
  108. }
  109.  
  110. impl PmpData {
  111.     fn new(pdev: &platform::Device<Core>) -> Result<Arc<PmpData>> {
  112.         let pmp_req = pdev.io_request_by_name(c"pmp").ok_or(EINVAL)?;
  113.         let pmp_mmio = KBox::pin_init(pmp_req.iomap_sized::<PMP_MMIO_SIZE>(), GFP_KERNEL)?;
  114.         let asc_req = pdev.io_request_by_name(c"asc").ok_or(EINVAL)?;
  115.         let asc_mmio = KBox::pin_init(asc_req.iomap_sized::<ASC_MMIO_SIZE>(), GFP_KERNEL)?;
  116.         Arc::pin_init(
  117.             try_pin_init!(
  118.                 PmpData {
  119.                     dev: pdev.as_ref().into(),
  120.                     pmp_mmio,
  121.                     asc_mmio,
  122.                     rtkit <- new_mutex!(None),
  123.                     state <- new_mutex!(PmpState::new()?),
  124.                     shmem: build_shmem(pdev)?,
  125.                 }
  126.             ),
  127.             GFP_KERNEL,
  128.         )
  129.     }
  130.  
  131.     fn start(&self) -> Result<()> {
  132.         let mut guard = self.rtkit.lock();
  133.         let mut rtk = guard.as_mut().as_pin_mut().unwrap();
  134.         rtk.as_mut().wake()?;
  135.         rtk.start_endpoint(PMP_ENDPOINT)
  136.     }
  137.  
  138.     fn startup(&self) -> Result<u64> {
  139.         self.send_init_config()?;
  140.  
  141.         Ok(0)
  142.     }
  143.  
  144.     fn send_init_config(&self) -> Result<u64> {
  145.         let mut dva: u64 = 0xc0000000;
  146.         let mut maps: KVec<u8> = KVec::<u8>::new();
  147.         let node = self.dev.fwnode().ok_or(EIO)?;
  148.  
  149.         let n_entries = node.property_count_elem::<u64>(c"apple,init-ranges")? / 2;
  150.         let regions = node
  151.             .property_read_array_vec::<u64>(c"apple,init-ranges", n_entries * 2)?
  152.             .required_by(&self.dev)?;
  153.  
  154.         let domain = unsafe { bindings::iommu_get_domain_for_dev(self.dev.as_raw()) };
  155.  
  156.         let mut err = 0;
  157.  
  158.         let mut map_addresses = |reg_indx_start: usize, reg_indx_end: usize, dva: u64| -> Result<()> {
  159.             for i in reg_indx_start..reg_indx_end {
  160.                 let addr = regions[i * 2];
  161.                 let size: u64 = regions[i * 2 + 1];
  162.                 if size == 0 {
  163.                     maps.extend_from_slice(&0u64.to_le_bytes(), GFP_KERNEL)?;
  164.                     maps.extend_from_slice(&0u64.to_le_bytes(), GFP_KERNEL)?;
  165.                     continue;
  166.                 }
  167.  
  168.                 pr_info!("map {:#x} -> {:#x} [{:#x}]\n", addr, dva, size);
  169.  
  170.                 unsafe {
  171.                     err = bindings::iommu_map(
  172.                         domain,
  173.                         0xc0000000 as usize,
  174.                         addr,
  175.                         size as usize,
  176.                         (bindings::IOMMU_READ | bindings::IOMMU_WRITE | bindings::IOMMU_MMIO) as i32,
  177.                         bindings::GFP_KERNEL,
  178.                     );
  179.  
  180.                     if err != 0 {
  181.                         break;
  182.                     }
  183.                 }
  184.  
  185.                 maps.extend_from_slice(&dva.to_le_bytes(), GFP_KERNEL)?;
  186.                 maps.extend_from_slice(&size.to_le_bytes(), GFP_KERNEL)?;
  187.             }
  188.  
  189.             Ok(())
  190.         };
  191.  
  192.         // 1st region
  193.         map_addresses(3, 17, dva)?;
  194.  
  195.         // TODO
  196.         // if err != 0 {
  197.         //     return Err(Error::from_errno(err));
  198.         // }
  199.  
  200.  
  201.         // 2nd region
  202.         dva = 0xc1000000;
  203.         map_addresses(17, 18, dva)?;
  204.  
  205.         // 3rd region
  206.         dva = 0xc2000000;
  207.         map_addresses(18, 24, dva)?;
  208.  
  209.         // so on...
  210.         dva = 0xc3000000;
  211.         map_addresses(24, 30, dva)?;
  212.  
  213.         dva = 0xc4000000;
  214.         map_addresses(30, 33, dva)?;
  215.  
  216.         dva = 0xc5000000;
  217.         map_addresses(33, 35, dva)?;
  218.  
  219.         dva = 0xc0024000;
  220.         map_addresses(35, 37, dva)?;
  221.  
  222.         dva = 0xc6000000;
  223.         map_addresses(37, 38, dva)?;
  224.  
  225.         dva = 0xc1004000;
  226.         map_addresses(38, 39, dva)?;
  227.  
  228.         dva = 0xc3074000;
  229.         map_addresses(39, 42, dva)?;
  230.  
  231.         dva = 0xc2074000;
  232.         map_addresses(42, 43, dva)?;
  233.  
  234.         dva = 0xc1008000;
  235.         map_addresses(43, 44, dva)?;
  236.  
  237.         let configure_msg = (OPC_CONFIGURE << OPC_SHIFT) | (self.shmem.dma_handle() >> 11);
  238.  
  239.         Ok(configure_msg)
  240.     }
  241.  
  242.     fn recv_message(&self, msg: u64) -> Result<()> {
  243.         let opc = (msg >> OPC_SHIFT) & 0xFF;
  244.         let reply = match opc {
  245.             OPC_STARTUP => self.startup()?,
  246.             OPC_CONFIGURE_ACK =>
  247.                 OPC_INIT1 << OPC_SHIFT | (1 << 15) + 3,
  248.             OPC_INIT1_ACK =>
  249.                 OPC_INIT2 << OPC_SHIFT | (1 << 15),
  250.             OPC_INIT2_ACK => 0,
  251.             _ => {
  252.                 dev_err!(self.dev, "Got unknown message {}", msg);
  253.                 return Err(EIO);
  254.             }
  255.         };
  256.  
  257.         if reply != 0 {
  258.             let mut rtk_guard = self.rtkit.lock();
  259.             let rtk = rtk_guard.as_mut().as_pin_mut().unwrap();
  260.             rtk.send_message(PMP_ENDPOINT, reply)?;
  261.         }
  262.  
  263.         Ok(())
  264.     }
  265. }
  266.  
  267. #[allow(dead_code)]
  268. struct PmpDriverV1(Arc<PmpData>);
  269.  
  270. kernel::of_device_table!(
  271.     OF_TABLE,
  272.     MODULE_OF_TABLE,
  273.     (),
  274.     [(of::DeviceId::new(c"apple,t8103-pmp-v1"), ())]
  275. );
  276.  
  277. unsafe impl Send for PmpData {}
  278. unsafe impl Sync for PmpData {}
  279.  
  280. struct NoBuffer;
  281. impl rtkit::Buffer for NoBuffer {
  282.     fn iova(&self) -> Result<usize> {
  283.         unreachable!()
  284.     }
  285.  
  286.     fn buf(&mut self) -> Result<IoSysMapRef<'_, u8>> {
  287.        unreachable!()
  288.    }
  289. }
  290.  
  291. #[vtable]
  292. impl rtkit::Operations for PmpData {
  293.    type Data = Arc<PmpData>;
  294.    type Buffer = NoBuffer;
  295.  
  296.    fn recv_message(data: <Self::Data as ForeignOwnable>::Borrowed<'_>, _ep: u8, msg: u64) {
  297.         let ret = data.recv_message(msg);
  298.         if let Err(e) = ret {
  299.             dev_err!(data.dev, "Failed to handle rtkit message, error: {:?}", e);
  300.         }
  301.     }
  302.  
  303.     fn crashed(data: <Self::Data as ForeignOwnable>::Borrowed<'_>, _crashlog: Option<&[u8]>) {
  304.        dev_err!(data.dev, "PMP firmware crashed");
  305.    }
  306. }
  307.  
  308. impl platform::Driver for PmpDriverV1 {
  309.    type IdInfo = ();
  310.  
  311.    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
  312.  
  313.    fn probe(pdev: &platform::Device<Core>, _info: Option<&()>) -> impl PinInit<Self, Error> {
  314.        let dev: ARef<device::Device> = pdev.as_ref().into();
  315.        let data = PmpData::new(pdev)?;
  316.        let rtkit = rtkit::RtKit::<PmpData>::new(&dev, None, 0, data.clone())?;
  317.        *data.rtkit.lock() = Some(rtkit);
  318.        data.start()?;
  319.  
  320.        Ok(PmpDriverV1(data))
  321.    }
  322. }
  323.  
  324. module_platform_driver! {
  325.    type: PmpDriverV1,
  326.    name: "apple_pmp_v1",
  327.    license: "Dual MIT/GPL",
  328. }
  329.  
Advertisement
Add Comment
Please, Sign In to add comment