summaryrefslogtreecommitdiff
path: root/nn/common/Types.cpp
blob: 17485f4427c1df10fc2b8631cda70c2f90875742 (plain)
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
/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Types.h"

#include <android-base/logging.h>
#include <cutils/native_handle.h>
#include <errno.h>
#include <poll.h>

#include <algorithm>
#include <cstddef>
#include <iterator>
#include <limits>
#include <optional>
#include <utility>
#include <vector>

#include "OperandTypes.h"
#include "OperationTypes.h"
#include "Result.h"

namespace android::nn {
namespace {

constexpr size_t safeDivideRoundedUp(size_t numerator, size_t denominator) {
    CHECK_NE(denominator, 0u);
    CHECK_LE(numerator, std::numeric_limits<size_t>::max() - denominator);
    return (numerator + denominator - 1) / denominator;
}

constexpr size_t safeMultiply(size_t a, size_t b) {
    if (b == 0) {
        return 0;
    }
    CHECK_LE(a, std::numeric_limits<size_t>::max() / b);
    return a * b;
}

std::vector<AlignedData> allocateAligned(const uint8_t* data, size_t length) {
    constexpr size_t kElementSize = sizeof(AlignedData);
    const size_t numberElements = safeDivideRoundedUp(length, kElementSize);
    std::vector<AlignedData> output(numberElements);
    std::memcpy(output.data(), data, length);
    return output;
}

}  // anonymous namespace

Model::OperandValues::OperandValues() {
    constexpr size_t kNumberBytes = 4 * 1024;
    constexpr size_t kElementSize = sizeof(AlignedData);
    constexpr size_t kNumberElements = safeDivideRoundedUp(kNumberBytes, kElementSize);
    mData.reserve(kNumberElements);
}

Model::OperandValues::OperandValues(const uint8_t* data, size_t length)
    : mData(allocateAligned(data, length)) {}

DataLocation Model::OperandValues::append(const uint8_t* data, size_t length) {
    const size_t offset = size();
    auto contents = allocateAligned(data, length);
    mData.insert(mData.end(), contents.begin(), contents.end());
    CHECK_LE(offset, std::numeric_limits<uint32_t>::max());
    CHECK_LE(length, std::numeric_limits<uint32_t>::max());
    return {.offset = static_cast<uint32_t>(offset), .length = static_cast<uint32_t>(length)};
}

const uint8_t* Model::OperandValues::data() const {
    return reinterpret_cast<const uint8_t*>(mData.data());
}

size_t Model::OperandValues::size() const {
    return safeMultiply(mData.size(), sizeof(AlignedData));
}

Capabilities::OperandPerformanceTable::OperandPerformanceTable(
        std::vector<OperandPerformance> operandPerformances)
    : mSorted(std::move(operandPerformances)) {}

Result<Capabilities::OperandPerformanceTable> Capabilities::OperandPerformanceTable::create(
        std::vector<OperandPerformance> operandPerformances) {
    const auto notUnique = [](const auto& lhs, const auto& rhs) { return !(lhs.type < rhs.type); };
    const bool isUnique = std::adjacent_find(operandPerformances.begin(), operandPerformances.end(),
                                             notUnique) == operandPerformances.end();
    if (!isUnique) {
        return NN_ERROR() << "Failed to create OperandPerformanceTable: Input must be sorted by "
                             "key (in ascending order), and there must be no duplicate keys";
    }

    return Capabilities::OperandPerformanceTable(std::move(operandPerformances));
}

Capabilities::PerformanceInfo Capabilities::OperandPerformanceTable::lookup(
        OperandType operandType) const {
    // Search for operand type in the sorted collection.
    constexpr auto cmp = [](const auto& performance, auto type) { return performance.type < type; };
    const auto it = std::lower_bound(mSorted.begin(), mSorted.end(), operandType, cmp);

    // If the operand type is found, return its corresponding info.
    if (it != mSorted.end() && it->type == operandType) {
        return it->info;
    }

    // If no performance info is defined, use the default value (float's max).
    return Capabilities::PerformanceInfo{};
}

const std::vector<Capabilities::OperandPerformance>&
Capabilities::OperandPerformanceTable::asVector() const {
    return mSorted;
}

SyncFence SyncFence::createAsSignaled() {
    return SyncFence(nullptr);
}

Result<SyncFence> SyncFence::create(NativeHandle syncFence) {
    const bool isValid = (syncFence != nullptr && syncFence->handle() != nullptr &&
                          syncFence->handle()->numFds == 1 && syncFence->handle()->numInts == 0 &&
                          &syncFence->handle()->data[0] != nullptr);
    if (!isValid) {
        return NN_ERROR() << "Invalid sync fence handle passed to SyncFence::create";
    }
    return SyncFence(std::move(syncFence));
}

SyncFence::SyncFence(NativeHandle syncFence) : mSyncFence(std::move(syncFence)) {}

SyncFence::FenceState SyncFence::syncWait(OptionalTimeout optionalTimeout) const {
    if (mSyncFence == nullptr) {
        return FenceState::SIGNALED;
    }

    const int fd = mSyncFence->handle()->data[0];
    const int timeout = optionalTimeout.value_or(Timeout{-1}).count();

    // This implementation is directly based on the ::sync_wait() implementation.

    struct pollfd fds;
    int ret;

    if (fd < 0) {
        errno = EINVAL;
        return FenceState::UNKNOWN;
    }

    fds.fd = fd;
    fds.events = POLLIN;

    do {
        ret = poll(&fds, 1, timeout);
        if (ret > 0) {
            if (fds.revents & POLLNVAL) {
                errno = EINVAL;
                return FenceState::UNKNOWN;
            }
            if (fds.revents & POLLERR) {
                errno = EINVAL;
                return FenceState::ERROR;
            }
            return FenceState::SIGNALED;
        } else if (ret == 0) {
            errno = ETIME;
            return FenceState::ACTIVE;
        }
    } while (ret == -1 && (errno == EINTR || errno == EAGAIN));

    return FenceState::UNKNOWN;
}

NativeHandle SyncFence::getHandle() const {
    return mSyncFence;
}

}  // namespace android::nn