1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15
16 #include <cstddef>
17 #include <cstdint>
18
19 #include "lib/stdcompat/bit.h"
20 #include "pw_allocator/block/allocatable.h"
21 #include "pw_allocator/block/result.h"
22 #include "pw_allocator/hardening.h"
23 #include "pw_allocator/layout.h"
24 #include "pw_bytes/alignment.h"
25 #include "pw_status/status.h"
26
27 namespace pw::allocator {
28 namespace internal {
29
30 // Trivial base class for trait support.
31 struct AlignableBase {};
32
33 } // namespace internal
34
35 /// Mix-in for blocks that can be split on alignment boundaries.
36 ///
37 /// Block mix-ins are stateless and trivially constructible. See `BasicBlock`
38 /// for details on how mix-ins can be combined to implement blocks.
39 ///
40 /// This mix-in requires its derived type also derive from `AllocatableBlock`.
41 template <typename Derived>
42 class AlignableBlock : public internal::AlignableBase {
43 protected:
AlignableBlock()44 constexpr explicit AlignableBlock() {
45 // Assert within a function, since `Derived` is not complete when this type
46 // is defined.
47 static_assert(is_allocatable_v<Derived>,
48 "Types derived from AlignableBlock must also derive from "
49 "AllocatableBlock");
50 }
51
52 /// @copydoc AllocatableBlock::CanAlloc
53 constexpr StatusWithSize DoCanAlloc(Layout layout) const;
54
55 /// @copydoc AllocatableBlock::AllocFirst
56 static constexpr BlockResult<Derived> DoAllocFirst(Derived*&& block,
57 Layout layout);
58
59 /// @copydoc AllocatableBlock::AllocLast
60 static constexpr BlockResult<Derived> DoAllocLast(Derived*&& block,
61 Layout layout);
62
63 private:
derived()64 constexpr const Derived* derived() const {
65 return static_cast<const Derived*>(this);
66 }
67
68 /// Allocates a block of `new_inner_size` that starts after `leading` bytes.
69 static constexpr BlockResult<Derived> DoAllocAligned(Derived*&& block,
70 size_t leading,
71 size_t new_inner_size);
72
73 // BlockWithLayout calls DoAllocFirst
74 template <typename>
75 friend class BlockWithLayout;
76 };
77
78 /// Trait type that allows interrogating a block as to whether it is alignable.
79 template <typename BlockType>
80 struct is_alignable : std::is_base_of<internal::AlignableBase, BlockType> {};
81
82 /// Helper variable template for `is_alignable<BlockType>::value`.
83 template <typename BlockType>
84 constexpr bool is_alignable_v = is_alignable<BlockType>::value;
85
86 // Template method implementations.
87
88 template <typename Derived>
DoCanAlloc(Layout layout)89 constexpr StatusWithSize AlignableBlock<Derived>::DoCanAlloc(
90 Layout layout) const {
91 // How much extra space is available?
92 auto result = derived()->AllocatableBlock<Derived>::DoCanAlloc(layout);
93 if (!result.ok()) {
94 return result;
95 }
96 size_t extra = result.size();
97
98 // Is the default alignment sufficient?
99 if (layout.alignment() <= Derived::kAlignment) {
100 return StatusWithSize(extra);
101 }
102
103 // What is the last aligned address within the leading extra space?
104 auto addr = cpp20::bit_cast<uintptr_t>(derived()->UsableSpace());
105 uintptr_t aligned_addr = addr;
106 Hardening::Increment(aligned_addr, extra);
107 aligned_addr = AlignDown(aligned_addr, layout.alignment());
108
109 // Is there an aligned address within the extra space?
110 if (aligned_addr < addr) {
111 return StatusWithSize::ResourceExhausted();
112 }
113
114 // If splitting the first block, is there enough extra for a valid block?
115 size_t leading_outer_size = aligned_addr - addr;
116 if (leading_outer_size != 0 && leading_outer_size < Derived::kMinOuterSize &&
117 derived()->Prev() == nullptr) {
118 return StatusWithSize::ResourceExhausted();
119 }
120
121 return StatusWithSize(leading_outer_size);
122 }
123
124 template <typename Derived>
DoAllocFirst(Derived * && block,Layout layout)125 constexpr BlockResult<Derived> AlignableBlock<Derived>::DoAllocFirst(
126 Derived*&& block, Layout layout) {
127 // Is the default alignment sufficient?
128 if (layout.alignment() <= Derived::kAlignment) {
129 return AllocatableBlock<Derived>::DoAllocFirst(std::move(block), layout);
130 }
131
132 // What is the first aligned address within the leading extra space?
133 size_t size = AlignUp(layout.size(), Derived::kAlignment);
134 layout = Layout(size, layout.alignment());
135 StatusWithSize can_alloc = block->DoCanAlloc(layout);
136 if (!can_alloc.ok()) {
137 return BlockResult(block, can_alloc.status());
138 }
139 size_t extra = can_alloc.size();
140 size_t leading_outer_size = extra - AlignDown(extra, layout.alignment());
141
142 // If splitting the first block, there must be enough for a valid block.
143 if (leading_outer_size != 0 && leading_outer_size <= Derived::kMinOuterSize &&
144 block->Prev() == nullptr) {
145 leading_outer_size += AlignUp(Derived::kMinOuterSize - leading_outer_size,
146 layout.alignment());
147 }
148 if (leading_outer_size > extra) {
149 return BlockResult(block, Status::ResourceExhausted());
150 }
151
152 // Allocate the aligned block.
153 return DoAllocAligned(std::move(block), leading_outer_size, layout.size());
154 }
155
156 template <typename Derived>
DoAllocLast(Derived * && block,Layout layout)157 constexpr BlockResult<Derived> AlignableBlock<Derived>::DoAllocLast(
158 Derived*&& block, Layout layout) {
159 // Is the default alignment sufficient?
160 if (layout.alignment() <= Derived::kAlignment) {
161 return AllocatableBlock<Derived>::DoAllocLast(std::move(block), layout);
162 }
163
164 // What is the last aligned address within the leading extra space?
165 size_t size = AlignUp(layout.size(), Derived::kAlignment);
166 layout = Layout(size, layout.alignment());
167 StatusWithSize can_alloc = block->DoCanAlloc(layout);
168 if (!can_alloc.ok()) {
169 return BlockResult(block, can_alloc.status());
170 }
171 size_t leading_outer_size = can_alloc.size();
172
173 // Allocate the aligned block.
174 return DoAllocAligned(std::move(block), leading_outer_size, layout.size());
175 }
176
177 template <typename Derived>
DoAllocAligned(Derived * && block,size_t leading_outer_size,size_t new_inner_size)178 constexpr BlockResult<Derived> AlignableBlock<Derived>::DoAllocAligned(
179 Derived*&& block, size_t leading_outer_size, size_t new_inner_size) {
180 // Allocate everything after aligned address.
181 Layout layout(block->InnerSize() - leading_outer_size, Derived::kAlignment);
182 auto alloc_result =
183 AllocatableBlock<Derived>::DoAllocLast(std::move(block), layout);
184 if (!alloc_result.ok()) {
185 return alloc_result;
186 }
187 block = alloc_result.block();
188
189 // Resize the allocation to the requested size.
190 auto resize_result = block->DoResize(new_inner_size);
191 if (!resize_result.ok()) {
192 return resize_result;
193 }
194
195 return BlockResult(
196 block, alloc_result.prev(), resize_result.next(), alloc_result.size());
197 }
198
199 } // namespace pw::allocator
200