1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! A safe rust wrapper for creating and using ramdisks.

#![deny(missing_docs)]
use {
    anyhow::{anyhow, Context as _, Error},
    fidl::endpoints::{ClientEnd, Proxy as _},
    fidl_fuchsia_device::{ControllerMarker, ControllerProxy, ControllerSynchronousProxy},
    fidl_fuchsia_hardware_block as fhardware_block,
    fidl_fuchsia_hardware_ramdisk::{Guid, RamdiskControllerMarker},
    fidl_fuchsia_io as fio,
    fuchsia_component::client::connect_to_named_protocol_at_dir_root,
    fuchsia_zircon as zx,
};

const GUID_LEN: usize = 16;
const DEV_PATH: &str = "/dev";
const RAMCTL_PATH: &str = "sys/platform/00:00:2d/ramctl";
const BLOCK_EXTENSION: &str = "block";

/// A type to help construct a [`RamdeviceClient`] optionally from a VMO.
pub struct RamdiskClientBuilder {
    ramdisk_source: RamdiskSource,
    block_size: u64,
    dev_root: Option<fio::DirectoryProxy>,
    guid: Option<[u8; GUID_LEN]>,
}

enum RamdiskSource {
    Vmo { vmo: zx::Vmo },
    Size { block_count: u64 },
}

impl RamdiskClientBuilder {
    /// Create a new ramdisk builder
    pub fn new(block_size: u64, block_count: u64) -> Self {
        Self {
            ramdisk_source: RamdiskSource::Size { block_count },
            block_size,
            dev_root: None,
            guid: None,
        }
    }

    /// Create a new ramdisk builder with a vmo
    pub fn new_with_vmo(vmo: zx::Vmo, block_size: Option<u64>) -> Self {
        Self {
            ramdisk_source: RamdiskSource::Vmo { vmo },
            block_size: block_size.unwrap_or(0),
            dev_root: None,
            guid: None,
        }
    }

    /// Use the given directory as "/dev" instead of opening "/dev" from the environment.
    pub fn dev_root(mut self, dev_root: fio::DirectoryProxy) -> Self {
        self.dev_root = Some(dev_root);
        self
    }

    /// Initialize the ramdisk with the given GUID, which can be queried from the ramdisk instance.
    pub fn guid(mut self, guid: [u8; GUID_LEN]) -> Self {
        self.guid = Some(guid);
        self
    }

    /// Create the ramdisk.
    pub async fn build(self) -> Result<RamdiskClient, Error> {
        let Self { ramdisk_source, block_size, dev_root, guid } = self;
        let dev_root = if let Some(dev_root) = dev_root {
            dev_root
        } else {
            fuchsia_fs::directory::open_in_namespace(DEV_PATH, fio::OpenFlags::RIGHT_READABLE)
                .with_context(|| format!("open {}", DEV_PATH))?
        };
        let ramdisk_controller =
            device_watcher::recursive_wait_and_open::<RamdiskControllerMarker>(
                &dev_root,
                RAMCTL_PATH,
            )
            .await
            .with_context(|| format!("waiting for {}", RAMCTL_PATH))?;
        let type_guid = guid.map(|guid| Guid { value: guid });
        let name = match ramdisk_source {
            RamdiskSource::Vmo { vmo } => ramdisk_controller
                .create_from_vmo_with_params(vmo, block_size, type_guid.as_ref())
                .await?
                .map_err(zx::Status::from_raw)
                .context("creating ramdisk from vmo")?,
            RamdiskSource::Size { block_count } => ramdisk_controller
                .create(block_size, block_count, type_guid.as_ref())
                .await?
                .map_err(zx::Status::from_raw)
                .with_context(|| format!("creating ramdisk with {} blocks", block_count))?,
        };
        let name = name.ok_or_else(|| anyhow!("Failed to get instance name"))?;
        RamdiskClient::new(dev_root, &name).await
    }
}

/// A client for managing a ramdisk. This can be created with the [`RamdiskClient::create`]
/// function or through the type returned by [`RamdiskClient::builder`] to specify additional
/// options.
pub struct RamdiskClient {
    block_dir: Option<fio::DirectoryProxy>,
    block_controller: Option<ControllerProxy>,
    ramdisk_controller: Option<ControllerProxy>,
}

impl RamdiskClient {
    async fn new(dev_root: fio::DirectoryProxy, instance_name: &str) -> Result<Self, Error> {
        let ramdisk_path = format!("{RAMCTL_PATH}/{instance_name}");
        let ramdisk_controller_path = format!("{ramdisk_path}/device_controller");
        let block_path = format!("{ramdisk_path}/{BLOCK_EXTENSION}");

        // Wait for ramdisk path to appear
        let ramdisk_controller = device_watcher::recursive_wait_and_open::<ControllerMarker>(
            &dev_root,
            &ramdisk_controller_path,
        )
        .await
        .with_context(|| format!("waiting for {}", &ramdisk_controller_path))?;

        // Wait for the block path to appear
        let block_dir = device_watcher::recursive_wait_and_open_directory(&dev_root, &block_path)
            .await
            .with_context(|| format!("waiting for {}", &block_path))?;

        let block_controller = connect_to_named_protocol_at_dir_root::<ControllerMarker>(
            &block_dir,
            "device_controller",
        )
        .with_context(|| {
            format!("opening block controller at {}/device_controller", &block_path)
        })?;

        Ok(RamdiskClient {
            block_dir: Some(block_dir),
            block_controller: Some(block_controller),
            ramdisk_controller: Some(ramdisk_controller),
        })
    }

    /// Create a new ramdisk builder with the given block_size and block_count.
    pub fn builder(block_size: u64, block_count: u64) -> RamdiskClientBuilder {
        RamdiskClientBuilder::new(block_size, block_count)
    }

    /// Create a new ramdisk.
    pub async fn create(block_size: u64, block_count: u64) -> Result<Self, Error> {
        Self::builder(block_size, block_count).build().await
    }

    /// Get a reference to the block controller.
    pub fn as_controller(&self) -> Option<&ControllerProxy> {
        self.block_controller.as_ref()
    }

    /// Take the block controller.
    pub fn take_controller(&mut self) -> Option<ControllerProxy> {
        self.block_controller.take()
    }

    /// Get a reference to the block directory proxy.
    pub fn as_dir(&self) -> Option<&fio::DirectoryProxy> {
        self.block_dir.as_ref()
    }

    /// Take the block directory proxy.
    pub fn take_dir(&mut self) -> Option<fio::DirectoryProxy> {
        self.block_dir.take()
    }

    /// Get an open channel to the underlying ramdevice.
    pub async fn open(
        &self,
    ) -> Result<fidl::endpoints::ClientEnd<fhardware_block::BlockMarker>, Error> {
        // At this point, we have already waited on the block path to appear so
        // we can directly open a connection to the ramdevice.
        // TODO(https://fxbug.dev/42063787): In order to allow multiplexing to be removed, use
        // connect_to_device_fidl to connect to the BlockProxy instead of connect_to_.._dir_root.
        // Requires downstream work.
        let block_dir = self.as_dir().ok_or_else(|| anyhow!("directory is invalid"))?;
        let block_proxy =
            connect_to_named_protocol_at_dir_root::<fhardware_block::BlockMarker>(block_dir, ".")?;
        let block_client_end = ClientEnd::<fhardware_block::BlockMarker>::new(
            block_proxy.into_channel().unwrap().into(),
        );
        Ok(block_client_end)
    }

    /// Get an open channel to the underlying ramdevice.
    pub fn connect(
        &self,
        server_end: fidl::endpoints::ServerEnd<fhardware_block::BlockMarker>,
    ) -> Result<(), Error> {
        let block_dir = self.as_dir().ok_or_else(|| anyhow!("directory is invalid"))?;
        Ok(block_dir.open(
            fio::OpenFlags::empty(),
            fio::ModeType::empty(),
            ".",
            server_end.into_channel().into(),
        )?)
    }

    /// Get an open channel to the underlying ramdevice's controller.
    pub fn open_controller(
        &self,
    ) -> Result<fidl::endpoints::ClientEnd<fidl_fuchsia_device::ControllerMarker>, Error> {
        let block_dir = self.as_dir().ok_or_else(|| anyhow!("directory is invalid"))?;
        let controller_proxy = connect_to_named_protocol_at_dir_root::<
            fidl_fuchsia_device::ControllerMarker,
        >(block_dir, "device_controller")?;
        Ok(ClientEnd::new(controller_proxy.into_channel().unwrap().into()))
    }

    /// Starts unbinding the underlying ramdisk and returns before the device is removed. This
    /// deallocates all resources for this ramdisk, which will remove all data written to the
    /// associated ramdisk.
    pub async fn destroy(mut self) -> Result<(), Error> {
        let ramdisk_controller = self
            .ramdisk_controller
            .take()
            .ok_or_else(|| anyhow!("ramdisk controller is invalid"))?;
        let () = ramdisk_controller
            .schedule_unbind()
            .await
            .context("unbind transport")?
            .map_err(zx::Status::from_raw)
            .context("unbind response")?;
        Ok(())
    }

    /// Unbinds the underlying ramdisk and waits for the device and all child devices to be removed.
    /// This deallocates all resources for this ramdisk, which will remove all data written to the
    /// associated ramdisk.
    pub async fn destroy_and_wait_for_removal(mut self) -> Result<(), Error> {
        // Calling `schedule_unbind` on the ramdisk controller initiates the unbind process but
        // doesn't wait for anything to complete. The unbinding process starts at the ramdisk and
        // propagates down through the child devices. FIDL connections are closed during the unbind
        // process so the ramdisk controller connection will be closed before connections to the
        // child block device. After unbinding, the drivers are removed starting at the children and
        // ending at the ramdisk.

        let block_controller =
            self.block_controller.take().ok_or_else(|| anyhow!("block controller is invalid"))?;
        let ramdisk_controller = self
            .ramdisk_controller
            .take()
            .ok_or_else(|| anyhow!("ramdisk controller is invalid"))?;
        let () = ramdisk_controller
            .schedule_unbind()
            .await
            .context("unbind transport")?
            .map_err(zx::Status::from_raw)
            .context("unbind response")?;
        let _: (zx::Signals, zx::Signals) =
            futures::future::try_join(block_controller.on_closed(), ramdisk_controller.on_closed())
                .await
                .context("on closed")?;
        Ok(())
    }

    /// Consume the RamdiskClient without destroying the underlying ramdisk. The caller must
    /// manually destroy the ramdisk device after calling this function.
    ///
    /// This should be used instead of `std::mem::forget`, as the latter will leak memory.
    pub fn forget(mut self) -> Result<(), Error> {
        let _: ControllerProxy = self
            .ramdisk_controller
            .take()
            .ok_or_else(|| anyhow!("ramdisk controller is invalid"))?;
        Ok(())
    }
}

impl Drop for RamdiskClient {
    fn drop(&mut self) {
        if let Some(ramdisk_controller) = self.ramdisk_controller.take() {
            let _: Result<Result<(), _>, _> =
                ControllerSynchronousProxy::new(ramdisk_controller.into_channel().unwrap().into())
                    .schedule_unbind(zx::Time::INFINITE);
        }
    }
}

#[cfg(test)]
mod tests {
    use {super::*, assert_matches::assert_matches};

    // Note that if these tests flake, all downstream tests that depend on this crate may too.

    const TEST_GUID: [u8; GUID_LEN] = [
        0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
        0x10,
    ];

    #[fuchsia::test]
    async fn create_get_dir_proxy_destroy() {
        // just make sure all the functions are hooked up properly.
        let ramdisk =
            RamdiskClient::builder(512, 2048).build().await.expect("failed to create ramdisk");
        let ramdisk_dir = ramdisk.as_dir().expect("directory is invalid");
        fuchsia_fs::directory::readdir(ramdisk_dir).await.expect("failed to readdir");
        ramdisk.destroy().await.expect("failed to destroy the ramdisk");
    }

    #[fuchsia::test]
    async fn create_with_dev_root_and_guid_get_dir_proxy_destroy() {
        let dev_root =
            fuchsia_fs::directory::open_in_namespace(DEV_PATH, fio::OpenFlags::RIGHT_READABLE)
                .with_context(|| format!("open {}", DEV_PATH))
                .expect("failed to create directory proxy");
        let ramdisk = RamdiskClient::builder(512, 2048)
            .dev_root(dev_root)
            .guid(TEST_GUID)
            .build()
            .await
            .expect("failed to create ramdisk");
        let ramdisk_dir = ramdisk.as_dir().expect("directory is invalid");
        fuchsia_fs::directory::readdir(ramdisk_dir).await.expect("failed to readdir");
        ramdisk.destroy().await.expect("failed to destroy the ramdisk");
    }

    #[fuchsia::test]
    async fn create_with_guid_get_dir_proxy_destroy() {
        let ramdisk = RamdiskClient::builder(512, 2048)
            .guid(TEST_GUID)
            .build()
            .await
            .expect("failed to create ramdisk");
        let ramdisk_dir = ramdisk.as_dir().expect("invalid directory proxy");
        fuchsia_fs::directory::readdir(ramdisk_dir).await.expect("failed to readdir");
        ramdisk.destroy().await.expect("failed to destroy the ramdisk");
    }

    #[fuchsia::test]
    async fn create_open_destroy() {
        let ramdisk = RamdiskClient::create(512, 2048).await.unwrap();
        let client = ramdisk.open().await.unwrap().into_proxy().unwrap();
        client.get_info().await.expect("get_info failed").unwrap();
        ramdisk.destroy().await.expect("failed to destroy the ramdisk");
        // The ramdisk will be scheduled to be unbound, so `client` may be valid for some time.
    }

    #[fuchsia::test]
    async fn create_open_forget() {
        let ramdisk = RamdiskClient::create(512, 2048).await.unwrap();
        let client = ramdisk.open().await.unwrap().into_proxy().unwrap();
        client.get_info().await.expect("get_info failed").unwrap();
        assert!(ramdisk.forget().is_ok());
        // We should succeed calling `get_info` as the ramdisk should still exist.
        client.get_info().await.expect("get_info failed").unwrap();
    }

    #[fuchsia::test]
    async fn destroy_and_wait_for_removal() {
        let mut ramdisk = RamdiskClient::create(512, 2048).await.unwrap();
        let dir = ramdisk.take_dir().unwrap();

        assert_matches!(
            fuchsia_fs::directory::readdir(&dir).await.unwrap().as_slice(),
            [
                fuchsia_fs::directory::DirEntry {
                    name: name1,
                    kind: fuchsia_fs::directory::DirentKind::File,
                },
                fuchsia_fs::directory::DirEntry {
                    name: name2,
                    kind: fuchsia_fs::directory::DirentKind::File,
                },
            ] if [name1, name2] == [
                fidl_fuchsia_device_fs::DEVICE_CONTROLLER_NAME,
                fidl_fuchsia_device_fs::DEVICE_PROTOCOL_NAME,
              ]
        );

        let () = ramdisk.destroy_and_wait_for_removal().await.unwrap();

        assert_matches!(fuchsia_fs::directory::readdir(&dir).await.unwrap().as_slice(), []);
    }
}