1 // Copyright 2018 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 
5 #include <fcntl.h>
6 #include <limits.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 
10 #include <fbl/unique_fd.h>
11 #include <fs-management/ram-nand.h>
12 #include <fuchsia/hardware/nand/c/fidl.h>
13 #include <lib/fzl/fdio.h>
14 #include <unittest/unittest.h>
15 
16 #include <utility>
17 
18 namespace {
19 
BuildConfig()20 fuchsia_hardware_nand_RamNandInfo BuildConfig() {
21     fuchsia_hardware_nand_RamNandInfo config = {};
22     config.vmo = ZX_HANDLE_INVALID;
23     config.nand_info = {4096, 4, 5, 6, 0, fuchsia_hardware_nand_Class_TEST, {}};
24     return config;
25 }
26 
27 class NandDevice {
28   public:
NandDevice(const fuchsia_hardware_nand_RamNandInfo & config=BuildConfig ())29       explicit NandDevice(const fuchsia_hardware_nand_RamNandInfo& config = BuildConfig()) {
30           if (fs_mgmt::RamNand::Create(&config, &ram_nand_) == ZX_OK) {
31               // caller_ want's to own the device, so we re-open it even though
32               // ram_nand_ already has it open.
33               fbl::unique_fd device(dup(ram_nand_->fd().get()));
34               caller_.reset(std::move(device));
35           }
36       }
37 
38     ~NandDevice() = default;
39 
IsValid() const40     bool IsValid() const { return caller_ ? true : false; }
41 
path()42     const char* path() { return ram_nand_->path(); }
43 
44   private:
45 
46     std::optional<fs_mgmt::RamNand> ram_nand_;
47     fzl::FdioCaller caller_;
48     DISALLOW_COPY_ASSIGN_AND_MOVE(NandDevice);
49 };
50 
TrivialLifetimeTest()51 bool TrivialLifetimeTest() {
52     BEGIN_TEST;
53     fbl::String path;
54     {
55         NandDevice device;
56         ASSERT_TRUE(device.IsValid());
57         path = fbl::String(device.path());
58     }
59 
60     fbl::unique_fd found(open(path.c_str(), O_RDWR));
61     ASSERT_FALSE(found);
62     END_TEST;
63 }
64 
ExportConfigTest()65 bool ExportConfigTest() {
66     BEGIN_TEST;
67     fuchsia_hardware_nand_RamNandInfo config = BuildConfig();
68     config.export_nand_config = true;
69 
70     NandDevice device(config);
71     ASSERT_TRUE(device.IsValid());
72     END_TEST;
73 }
74 
ExportPartitionsTest()75 bool ExportPartitionsTest() {
76     BEGIN_TEST;
77     fuchsia_hardware_nand_RamNandInfo config = BuildConfig();
78     config.export_partition_map = true;
79 
80     NandDevice device(config);
81     ASSERT_TRUE(device.IsValid());
82     END_TEST;
83 }
84 
85 }  // namespace
86 
87 BEGIN_TEST_CASE(RamNandCtlTests)
88 RUN_TEST_SMALL(TrivialLifetimeTest)
89 RUN_TEST_SMALL(ExportConfigTest)
90 RUN_TEST_SMALL(ExportPartitionsTest)
91 END_TEST_CASE(RamNandCtlTests)
92