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 <fbl/alloc_checker.h>
6
7#include "vim-audio-utils.h"
8
9namespace audio {
10namespace vim2 {
11
12fbl::RefPtr<Registers> Registers::Create(const platform_device_protocol_t* pdev,
13                                         uint32_t which_mmio,
14                                         zx_status_t* out_res) {
15    fbl::AllocChecker ac;
16    auto ret = fbl::AdoptRef(new (&ac) Registers());
17    if (!ac.check()) {
18        *out_res = ZX_ERR_NO_MEMORY;
19    } else {
20        *out_res = ret->Map(pdev, which_mmio);
21    }
22
23    return (*out_res != ZX_OK) ? nullptr : ret;
24}
25
26Registers::~Registers() {
27    io_buffer_release(&buf_);
28}
29
30zx_status_t Registers::Map(const platform_device_protocol_t* pdev, uint32_t which_mmio) {
31    ZX_DEBUG_ASSERT(pdev != nullptr);
32    ZX_DEBUG_ASSERT(buf_.virt == nullptr);
33    zx_status_t res;
34
35    res = pdev_map_mmio_buffer(pdev, which_mmio, ZX_CACHE_POLICY_UNCACHED_DEVICE, &buf_);
36    if (res == ZX_OK) {
37        base_ = reinterpret_cast<volatile uint32_t*>(
38                reinterpret_cast<uintptr_t>(buf_.virt) + buf_.offset);
39    }
40
41    return res;
42}
43
44fbl::RefPtr<RefCountedVmo> RefCountedVmo::Create(zx::vmo vmo) {
45    if (!vmo.is_valid()) {
46        return nullptr;
47    }
48
49    fbl::AllocChecker ac;
50    auto ret = fbl::AdoptRef(new (&ac) RefCountedVmo(fbl::move(vmo)));
51    if (!ac.check()) {
52        return nullptr;
53    }
54
55    return ret;
56}
57
58}  // namespace vim2
59}  // namespace audio
60