builtins/
msi_resource.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use anyhow::{format_err, Error};
6use fidl_fuchsia_kernel as fkernel;
7use futures::prelude::*;
8use std::sync::Arc;
9use zx::{self as zx, HandleBased, Resource};
10
11/// An implementation of fuchsia.kernel.MsiResource protocol.
12pub struct MsiResource {
13    resource: Resource,
14}
15
16impl MsiResource {
17    /// `resource` must be the msi resource.
18    pub fn new(resource: Resource) -> Result<Arc<Self>, Error> {
19        let resource_info = resource.info()?;
20        if resource_info.kind != zx::sys::ZX_RSRC_KIND_SYSTEM
21            || resource_info.base != zx::sys::ZX_RSRC_SYSTEM_MSI_BASE
22            || resource_info.size != 1
23        {
24            return Err(format_err!("Msi resource not available."));
25        }
26        Ok(Arc::new(Self { resource }))
27    }
28
29    pub async fn serve(
30        self: Arc<Self>,
31        mut stream: fkernel::MsiResourceRequestStream,
32    ) -> Result<(), Error> {
33        while let Some(fkernel::MsiResourceRequest::Get { responder }) = stream.try_next().await? {
34            responder.send(self.resource.duplicate_handle(zx::Rights::SAME_RIGHTS)?)?;
35        }
36        Ok(())
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43    use fuchsia_component::client::connect_to_protocol;
44    use {fidl_fuchsia_kernel as fkernel, fuchsia_async as fasync};
45
46    async fn get_msi_resource() -> Result<Resource, Error> {
47        let msi_resource_provider = connect_to_protocol::<fkernel::MsiResourceMarker>()?;
48        let msi_resource_handle = msi_resource_provider.get().await?;
49        Ok(Resource::from(msi_resource_handle))
50    }
51
52    async fn serve_msi_resource() -> Result<fkernel::MsiResourceProxy, Error> {
53        let msi_resource = get_msi_resource().await?;
54
55        let (proxy, stream) =
56            fidl::endpoints::create_proxy_and_stream::<fkernel::MsiResourceMarker>();
57        fasync::Task::local(
58            MsiResource::new(msi_resource)
59                .unwrap_or_else(|e| panic!("Error while creating msi resource service: {}", e))
60                .serve(stream)
61                .unwrap_or_else(|e| panic!("Error while serving MSI resource service: {}", e)),
62        )
63        .detach();
64        Ok(proxy)
65    }
66
67    #[fuchsia::test]
68    async fn base_type_is_msi() -> Result<(), Error> {
69        let msi_resource_provider = serve_msi_resource().await?;
70        let msi_resource: Resource = msi_resource_provider.get().await?;
71        let resource_info = msi_resource.info()?;
72        assert_eq!(resource_info.kind, zx::sys::ZX_RSRC_KIND_SYSTEM);
73        assert_eq!(resource_info.base, zx::sys::ZX_RSRC_SYSTEM_MSI_BASE);
74        assert_eq!(resource_info.size, 1);
75        Ok(())
76    }
77}