3 * Copyright 2017 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 #include <grpc/support/port_platform.h>
21 #include "src/core/lib/gprpp/arena.h"
27 #include <grpc/support/alloc.h>
28 #include <grpc/support/atm.h>
29 #include <grpc/support/log.h>
30 #include <grpc/support/sync.h>
32 #include "src/core/lib/gpr/alloc.h"
33 #include "src/core/lib/gprpp/memory.h"
37 void* ArenaStorage(size_t initial_size) {
38 static constexpr size_t base_size =
39 GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_core::Arena));
40 initial_size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(initial_size);
41 size_t alloc_size = base_size + initial_size;
42 static constexpr size_t alignment =
43 (GPR_CACHELINE_SIZE > GPR_MAX_ALIGNMENT &&
44 GPR_CACHELINE_SIZE % GPR_MAX_ALIGNMENT == 0)
47 return gpr_malloc_aligned(alloc_size, alignment);
57 Zone* prev_z = z->prev;
64 Arena* Arena::Create(size_t initial_size) {
65 return new (ArenaStorage(initial_size)) Arena(initial_size);
68 std::pair<Arena*, void*> Arena::CreateWithAlloc(size_t initial_size,
70 static constexpr size_t base_size =
71 GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Arena));
73 new (ArenaStorage(initial_size)) Arena(initial_size, alloc_size);
74 void* first_alloc = reinterpret_cast<char*>(new_arena) + base_size;
75 return std::make_pair(new_arena, first_alloc);
78 size_t Arena::Destroy() {
79 size_t size = total_used_.load(std::memory_order_relaxed);
81 gpr_free_aligned(this);
85 void* Arena::AllocZone(size_t size) {
86 // If the allocation isn't able to end in the initial zone, create a new
87 // zone for this allocation, and any unused space in the initial zone is
88 // wasted. This overflowing and wasting is uncommon because of our arena
89 // sizing hysteresis (that is, most calls should have a large enough initial
90 // zone and will not need to grow the arena).
91 static constexpr size_t zone_base_size =
92 GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Zone));
93 size_t alloc_size = zone_base_size + size;
94 Zone* z = new (gpr_malloc_aligned(alloc_size, GPR_MAX_ALIGNMENT)) Zone();
96 gpr_spinlock_lock(&arena_growth_spinlock_);
99 gpr_spinlock_unlock(&arena_growth_spinlock_);
101 return reinterpret_cast<char*>(z) + zone_base_size;
104 } // namespace grpc_core