Debian Codegraph @

src/core/lib/resource_quota/memory_quota.cc

raw
1 // Copyright 2021 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <grpc/support/port_platform.h>
16
17 #include "src/core/lib/resource_quota/memory_quota.h"
18
19 #include <inttypes.h>
20
21 #include <algorithm>
22 #include <atomic>
23 #include <tuple>
24
25 #include "absl/status/status.h"
26 #include "absl/strings/str_cat.h"
27
28 #include "src/core/lib/debug/trace.h"
29 #include "src/core/lib/gpr/useful.h"
30 #include "src/core/lib/gprpp/mpscq.h"
31 #include "src/core/lib/promise/detail/basic_seq.h"
32 #include "src/core/lib/promise/exec_ctx_wakeup_scheduler.h"
33 #include "src/core/lib/promise/loop.h"
34 #include "src/core/lib/promise/map.h"
35 #include "src/core/lib/promise/race.h"
36 #include "src/core/lib/promise/seq.h"
37 #include "src/core/lib/resource_quota/trace.h"
38
39 namespace grpc_core {
40
41 // Maximum number of bytes an allocator will request from a quota in one step.
42 // Larger allocations than this will require multiple allocation requests.
43 static constexpr size_t kMaxReplenishBytes = 1024 * 1024;
44
45 // Minimum number of bytes an allocator will request from a quota in one step.
46 static constexpr size_t kMinReplenishBytes = 4096;
47
48 //
49 // Reclaimer
50 //
51
52 ReclamationSweep::~ReclamationSweep() {
53 if (memory_quota_ != nullptr) {
54 memory_quota_->FinishReclamation(sweep_token_, std::move(waker_));
55 }
56 }
57
58 //
59 // ReclaimerQueue
60 //
61
62 struct ReclaimerQueue::QueuedNode
63 : public MultiProducerSingleConsumerQueue::Node {
64 explicit QueuedNode(RefCountedPtr<Handle> reclaimer_handle)
65 : reclaimer_handle(std::move(reclaimer_handle)) {}
66 RefCountedPtr<Handle> reclaimer_handle;
67 };
68
69 struct ReclaimerQueue::State {
70 Mutex reader_mu;
71 MultiProducerSingleConsumerQueue queue; // reader_mu must be held to pop
72 Waker waker ABSL_GUARDED_BY(reader_mu);
73
74 ~State() {
75 bool empty = false;
76 do {
77 delete static_cast<QueuedNode*>(queue.PopAndCheckEnd(&empty));
78 } while (!empty);
79 }
80 };
81
82 void ReclaimerQueue::Handle::Orphan() {
83 if (auto* sweep = sweep_.exchange(nullptr, std::memory_order_acq_rel)) {
84 sweep->RunAndDelete(absl::nullopt);
85 }
86 Unref();
87 }
88
89 void ReclaimerQueue::Handle::Run(ReclamationSweep reclamation_sweep) {
90 if (auto* sweep = sweep_.exchange(nullptr, std::memory_order_acq_rel)) {
91 sweep->RunAndDelete(std::move(reclamation_sweep));
92 }
93 }
94
95 bool ReclaimerQueue::Handle::Requeue(ReclaimerQueue* new_queue) {
96 if (sweep_.load(std::memory_order_relaxed)) {
97 new_queue->Enqueue(Ref());
98 return true;
99 } else {
100 return false;
101 }
102 }
103
104 void ReclaimerQueue::Handle::Sweep::MarkCancelled() {
105 // When we cancel a reclaimer we rotate the elements of the queue once -
106 // taking one non-cancelled node from the start, and placing it on the end.
107 // This ensures that we don't suffer from head of line blocking whereby a
108 // non-cancelled reclaimer at the head of the queue, in the absence of memory
109 // pressure, prevents the remainder of the queue from being cleaned up.
110 MutexLock lock(&state_->reader_mu);
111 while (true) {
112 bool empty = false;
113 std::unique_ptr<QueuedNode> node(
114 static_cast<QueuedNode*>(state_->queue.PopAndCheckEnd(&empty)));
115 if (node == nullptr) break;
116 if (node->reclaimer_handle->sweep_.load(std::memory_order_relaxed) !=
117 nullptr) {
118 state_->queue.Push(node.release());
119 break;
120 }
121 }
122 }
123
124 ReclaimerQueue::ReclaimerQueue() : state_(std::make_shared<State>()) {}
125
126 ReclaimerQueue::~ReclaimerQueue() = default;
127
128 void ReclaimerQueue::Enqueue(RefCountedPtr<Handle> handle) {
129 if (state_->queue.Push(new QueuedNode(std::move(handle)))) {
130 MutexLock lock(&state_->reader_mu);
131 state_->waker.Wakeup();
132 }
133 }
134
135 Poll<RefCountedPtr<ReclaimerQueue::Handle>> ReclaimerQueue::PollNext() {
136 MutexLock lock(&state_->reader_mu);
137 bool empty = false;
138 // Try to pull from the queue.
139 std::unique_ptr<QueuedNode> node(
140 static_cast<QueuedNode*>(state_->queue.PopAndCheckEnd(&empty)));
141 // If we get something, great.
142 if (node != nullptr) return std::move(node->reclaimer_handle);
143 if (!empty) {
144 // If we don't, but the queue is probably not empty, schedule an immediate
145 // repoll.
146 Activity::current()->ForceImmediateRepoll();
147 } else {
148 // Otherwise, schedule a wakeup for whenever something is pushed.
149 state_->waker = Activity::current()->MakeNonOwningWaker();
150 }
151 return Pending{};
152 }
153
154 //
155 // GrpcMemoryAllocatorImpl
156 //
157
158 GrpcMemoryAllocatorImpl::GrpcMemoryAllocatorImpl(
159 std::shared_ptr<BasicMemoryQuota> memory_quota, std::string name)
160 : memory_quota_(memory_quota), name_(std::move(name)) {
161 memory_quota_->Take(taken_bytes_);
162 }
163
164 GrpcMemoryAllocatorImpl::~GrpcMemoryAllocatorImpl() {
165 GPR_ASSERT(free_bytes_.load(std::memory_order_acquire) +
166 sizeof(GrpcMemoryAllocatorImpl) ==
167 taken_bytes_.load(std::memory_order_relaxed));
168 memory_quota_->Return(taken_bytes_);
169 }
170
171 void GrpcMemoryAllocatorImpl::Shutdown() {
172 std::shared_ptr<BasicMemoryQuota> memory_quota;
173 OrphanablePtr<ReclaimerQueue::Handle>
174 reclamation_handles[kNumReclamationPasses];
175 {
176 MutexLock lock(&reclaimer_mu_);
177 GPR_ASSERT(!shutdown_);
178 shutdown_ = true;
179 memory_quota = memory_quota_;
180 for (size_t i = 0; i < kNumReclamationPasses; i++) {
181 reclamation_handles[i] = std::exchange(reclamation_handles_[i], nullptr);
182 }
183 }
184 }
185
186 size_t GrpcMemoryAllocatorImpl::Reserve(MemoryRequest request) {
187 // Validate request - performed here so we don't bloat the generated code with
188 // inlined asserts.
189 GPR_ASSERT(request.min() <= request.max());
190 GPR_ASSERT(request.max() <= MemoryRequest::max_allowed_size());
191 while (true) {
192 // Attempt to reserve memory from our pool.
193 auto reservation = TryReserve(request);
194 if (reservation.has_value()) {
195 return *reservation;
196 }
197 // If that failed, grab more from the quota and retry.
198 Replenish();
199 }
200 }
201
202 absl::optional<size_t> GrpcMemoryAllocatorImpl::TryReserve(
203 MemoryRequest request) {
204 // How much memory should we request? (see the scaling below)
205 size_t scaled_size_over_min = request.max() - request.min();
206 // Scale the request down according to memory pressure if we have that
207 // flexibility.
208 if (scaled_size_over_min != 0) {
209 const auto pressure_info = memory_quota_->GetPressureInfo();
210 double pressure = pressure_info.pressure_control_value;
211 size_t max_recommended_allocation_size =
212 pressure_info.max_recommended_allocation_size;
213 // Reduce allocation size proportional to the pressure > 80% usage.
214 if (pressure > 0.8) {
215 scaled_size_over_min =
216 std::min(scaled_size_over_min,
217 static_cast<size_t>((request.max() - request.min()) *
218 (1.0 - pressure) / 0.2));
219 }
220 if (max_recommended_allocation_size < request.min()) {
221 scaled_size_over_min = 0;
222 } else if (request.min() + scaled_size_over_min >
223 max_recommended_allocation_size) {
224 scaled_size_over_min = max_recommended_allocation_size - request.min();
225 }
226 }
227
228 // How much do we want to reserve?
229 const size_t reserve = request.min() + scaled_size_over_min;
230 // See how many bytes are available.
231 size_t available = free_bytes_.load(std::memory_order_acquire);
232 while (true) {
233 // Does the current free pool satisfy the request?
234 if (available < reserve) {
235 return {};
236 }
237 // Try to reserve the requested amount.
238 // If the amount of free memory changed through this loop, then available
239 // will be set to the new value and we'll repeat.
240 if (free_bytes_.compare_exchange_weak(available, available - reserve,
241 std::memory_order_acq_rel,
242 std::memory_order_acquire)) {
243 return reserve;
244 }
245 }
246 }
247
248 void GrpcMemoryAllocatorImpl::MaybeDonateBack() {
249 size_t free = free_bytes_.load(std::memory_order_relaxed);
250 while (free > 0) {
251 size_t ret = 0;
252 if (!IsUnconstrainedMaxQuotaBufferSizeEnabled() &&
253 free > kMaxQuotaBufferSize / 2) {
254 ret = std::max(ret, free - kMaxQuotaBufferSize / 2);
255 }
256 if (IsPeriodicResourceQuotaReclamationEnabled()) {
257 ret = std::max(ret, free > 8192 ? free / 2 : free);
258 }
259 const size_t new_free = free - ret;
260 if (free_bytes_.compare_exchange_weak(free, new_free,
261 std::memory_order_acq_rel,
262 std::memory_order_acquire)) {
263 if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
264 gpr_log(GPR_INFO, "[%p|%s] Early return %" PRIdPTR " bytes", this,
265 name_.c_str(), ret);
266 }
267 GPR_ASSERT(taken_bytes_.fetch_sub(ret, std::memory_order_relaxed) >= ret);
268 memory_quota_->Return(ret);
269 return;
270 }
271 }
272 }
273
274 void GrpcMemoryAllocatorImpl::Replenish() {
275 // Attempt a fairly low rate exponential growth request size, bounded between
276 // some reasonable limits declared at top of file.
277 auto amount = Clamp(taken_bytes_.load(std::memory_order_relaxed) / 3,
278 kMinReplenishBytes, kMaxReplenishBytes);
279 // Take the requested amount from the quota.
280 memory_quota_->Take(amount);
281 // Record that we've taken it.
282 taken_bytes_.fetch_add(amount, std::memory_order_relaxed);
283 // Add the taken amount to the free pool.
284 free_bytes_.fetch_add(amount, std::memory_order_acq_rel);
285 // See if we can add ourselves as a reclaimer.
286 MaybeRegisterReclaimer();
287 }
288
289 void GrpcMemoryAllocatorImpl::MaybeRegisterReclaimer() {
290 // If the reclaimer is already registered, then there's nothing to do.
291 if (registered_reclaimer_.exchange(true, std::memory_order_relaxed)) {
292 return;
293 }
294 MutexLock lock(&reclaimer_mu_);
295 if (shutdown_) return;
296 // Grab references to the things we'll need
297 auto self = shared_from_this();
298 std::weak_ptr<EventEngineMemoryAllocatorImpl> self_weak{self};
299 registered_reclaimer_ = true;
300 InsertReclaimer(0, [self_weak](absl::optional<ReclamationSweep> sweep) {
301 if (!sweep.has_value()) return;
302 auto self = self_weak.lock();
303 if (self == nullptr) return;
304 auto* p = static_cast<GrpcMemoryAllocatorImpl*>(self.get());
305 p->registered_reclaimer_.store(false, std::memory_order_relaxed);
306 // Figure out how many bytes we can return to the quota.
307 size_t return_bytes = p->free_bytes_.exchange(0, std::memory_order_acq_rel);
308 if (return_bytes == 0) return;
309 // Subtract that from our outstanding balance.
310 p->taken_bytes_.fetch_sub(return_bytes);
311 // And return them to the quota.
312 p->memory_quota_->Return(return_bytes);
313 });
314 }
315
316 //
317 // BasicMemoryQuota
318 //
319
320 class BasicMemoryQuota::WaitForSweepPromise {
321 public:
322 WaitForSweepPromise(std::shared_ptr<BasicMemoryQuota> memory_quota,
323 uint64_t token)
324 : memory_quota_(std::move(memory_quota)), token_(token) {}
325
326 struct Empty {};
327 Poll<Empty> operator()() {
328 if (memory_quota_->reclamation_counter_.load(std::memory_order_relaxed) !=
329 token_) {
330 return Empty{};
331 } else {
332 return Pending{};
333 }
334 }
335
336 private:
337 std::shared_ptr<BasicMemoryQuota> memory_quota_;
338 uint64_t token_;
339 };
340
341 void BasicMemoryQuota::Start() {
342 auto self = shared_from_this();
343
344 // Reclamation loop:
345 // basically, wait until we are in overcommit (free_bytes_ < 0), and then:
346 // while (free_bytes_ < 0) reclaim_memory()
347 // ... and repeat
348 auto reclamation_loop = Loop(Seq(
349 [self]() -> Poll<int> {
350 // If there's free memory we no longer need to reclaim memory!
351 if (self->free_bytes_.load(std::memory_order_acquire) > 0) {
352 return Pending{};
353 }
354 return 0;
355 },
356 [self]() {
357 // Race biases to the first thing that completes... so this will
358 // choose the highest priority/least destructive thing to do that's
359 // available.
360 auto annotate = [](const char* name) {
361 return [name](RefCountedPtr<ReclaimerQueue::Handle> f) {
362 return std::make_tuple(name, std::move(f));
363 };
364 };
365 return Race(Map(self->reclaimers_[0].Next(), annotate("compact")),
366 Map(self->reclaimers_[1].Next(), annotate("benign")),
367 Map(self->reclaimers_[2].Next(), annotate("idle")),
368 Map(self->reclaimers_[3].Next(), annotate("destructive")));
369 },
370 [self](
371 std::tuple<const char*, RefCountedPtr<ReclaimerQueue::Handle>> arg) {
372 auto reclaimer = std::move(std::get<1>(arg));
373 if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
374 double free = std::max(intptr_t(0), self->free_bytes_.load());
375 size_t quota_size = self->quota_size_.load();
376 gpr_log(GPR_INFO,
377 "RQ: %s perform %s reclamation. Available free bytes: %f, "
378 "total quota_size: %zu",
379 self->name_.c_str(), std::get<0>(arg), free, quota_size);
380 }
381 // One of the reclaimer queues gave us a way to get back memory.
382 // Call the reclaimer with a token that contains enough to wake us
383 // up again.
384 const uint64_t token =
385 self->reclamation_counter_.fetch_add(1, std::memory_order_relaxed) +
386 1;
387 reclaimer->Run(ReclamationSweep(
388 self, token, Activity::current()->MakeNonOwningWaker()));
389 // Return a promise that will wait for our barrier. This will be
390 // awoken by the token above being destroyed. So, once that token is
391 // destroyed, we'll be able to proceed.
392 return WaitForSweepPromise(self, token);
393 },
394 []() -> LoopCtl<absl::Status> {
395 // Continue the loop!
396 return Continue{};
397 }));
398
399 reclaimer_activity_ =
400 MakeActivity(std::move(reclamation_loop), ExecCtxWakeupScheduler(),
401 [](absl::Status status) {
402 GPR_ASSERT(status.code() == absl::StatusCode::kCancelled);
403 });
404 }
405
406 void BasicMemoryQuota::Stop() { reclaimer_activity_.reset(); }
407
408 void BasicMemoryQuota::SetSize(size_t new_size) {
409 size_t old_size = quota_size_.exchange(new_size, std::memory_order_relaxed);
410 if (old_size < new_size) {
411 // We're growing the quota.
412 Return(new_size - old_size);
413 } else {
414 // We're shrinking the quota.
415 Take(old_size - new_size);
416 }
417 }
418
419 void BasicMemoryQuota::Take(size_t amount) {
420 // If there's a request for nothing, then do nothing!
421 if (amount == 0) return;
422 GPR_DEBUG_ASSERT(amount <= std::numeric_limits<intptr_t>::max());
423 // Grab memory from the quota.
424 auto prior = free_bytes_.fetch_sub(amount, std::memory_order_acq_rel);
425 // If we push into overcommit, awake the reclaimer.
426 if (prior >= 0 && prior < static_cast<intptr_t>(amount)) {
427 if (reclaimer_activity_ != nullptr) reclaimer_activity_->ForceWakeup();
428 }
429 }
430
431 void BasicMemoryQuota::FinishReclamation(uint64_t token, Waker waker) {
432 uint64_t current = reclamation_counter_.load(std::memory_order_relaxed);
433 if (current != token) return;
434 if (reclamation_counter_.compare_exchange_strong(current, current + 1,
435 std::memory_order_relaxed,
436 std::memory_order_relaxed)) {
437 if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
438 double free = std::max(intptr_t(0), free_bytes_.load());
439 size_t quota_size = quota_size_.load();
440 gpr_log(GPR_INFO,
441 "RQ: %s reclamation complete. Available free bytes: %f, "
442 "total quota_size: %zu",
443 name_.c_str(), free, quota_size);
444 }
445 waker.Wakeup();
446 }
447 }
448
449 void BasicMemoryQuota::Return(size_t amount) {
450 free_bytes_.fetch_add(amount, std::memory_order_relaxed);
451 }
452
453 BasicMemoryQuota::PressureInfo BasicMemoryQuota::GetPressureInfo() {
454 double free = free_bytes_.load();
455 if (free < 0) free = 0;
456 size_t quota_size = quota_size_.load();
457 double size = quota_size;
458 if (size < 1) return PressureInfo{1, 1, 1};
459 PressureInfo pressure_info;
460 pressure_info.instantaneous_pressure = std::max(0.0, (size - free) / size);
461 if (IsMemoryPressureControllerEnabled()) {
462 pressure_info.pressure_control_value =
463 pressure_tracker_.AddSampleAndGetControlValue(
464 pressure_info.instantaneous_pressure);
465 } else {
466 pressure_info.pressure_control_value =
467 std::min(pressure_info.instantaneous_pressure, 1.0);
468 }
469 pressure_info.max_recommended_allocation_size = quota_size / 16;
470 return pressure_info;
471 }
472
473 //
474 // PressureTracker
475 //
476
477 namespace memory_quota_detail {
478
479 double PressureController::Update(double error) {
480 bool is_low = error < 0;
481 bool was_low = std::exchange(last_was_low_, is_low);
482 double new_control; // leave unset to compiler can note bad branches
483 if (is_low && was_low) {
484 // Memory pressure is too low this round, and was last round too.
485 // If we have reached the min reporting value last time, then we will report
486 // the same value again this time and can start to increase the ticks_same_
487 // counter.
488 if (last_control_ == min_) {
489 ticks_same_++;
490 if (ticks_same_ >= max_ticks_same_) {
491 // If it's been the same for too long, reduce the min reported value
492 // down towards zero.
493 min_ /= 2.0;
494 ticks_same_ = 0;
495 }
496 }
497 // Target the min reporting value.
498 new_control = min_;
499 } else if (!is_low && !was_low) {
500 // Memory pressure is high, and was high previously.
501 ticks_same_++;
502 if (ticks_same_ >= max_ticks_same_) {
503 // It's been high for too long, increase the max reporting value up
504 // towards 1.0.
505 max_ = (1.0 + max_) / 2.0;
506 ticks_same_ = 0;
507 }
508 // Target the max reporting value.
509 new_control = max_;
510 } else if (is_low) {
511 // Memory pressure is low, but was high last round.
512 // Target the min reporting value, but first update it to be closer to the
513 // current max (that we've been reporting lately).
514 // In this way the min will gradually climb towards the max as we find a
515 // stable point.
516 // If this is too high, then we'll eventually move it back towards zero.
517 ticks_same_ = 0;
518 min_ = (min_ + max_) / 2.0;
519 new_control = min_;
520 } else {
521 // Memory pressure is high, but was low last round.
522 // Target the max reporting value, but first update it to be closer to the
523 // last reported value.
524 // The first switchover will have last_control_ being 0, and max_ being 2,
525 // so we'll immediately choose 1.0 which will tend to really slow down
526 // progress.
527 // If we end up targetting too low, we'll eventually move it back towards
528 // 1.0 after max_ticks_same_ ticks.
529 ticks_same_ = 0;
530 max_ = (last_control_ + max_) / 2.0;
531 new_control = max_;
532 }
533 // If the control value is decreasing we do it slowly. This avoids rapid
534 // oscillations.
535 // (If we want a control value that's higher than the last one we snap
536 // immediately because it's likely that memory pressure is growing unchecked).
537 if (new_control < last_control_) {
538 new_control =
539 std::max(new_control, last_control_ - max_reduction_per_tick_ / 1000.0);
540 }
541 last_control_ = new_control;
542 return new_control;
543 }
544
545 std::string PressureController::DebugString() const {
546 return absl::StrCat(last_was_low_ ? "low" : "high", " min=", min_,
547 " max=", max_, " ticks=", ticks_same_,
548 " last_control=", last_control_);
549 }
550
551 double PressureTracker::AddSampleAndGetControlValue(double sample) {
552 static const double kSetPoint = 95.0;
553
554 double max_so_far = max_this_round_.load(std::memory_order_relaxed);
555 if (sample > max_so_far) {
556 max_this_round_.compare_exchange_weak(max_so_far, sample,
557 std::memory_order_relaxed,
558 std::memory_order_relaxed);
559 }
560 // If memory pressure is almost done, immediately hit the brakes and report
561 // full memory usage.
562 if (sample >= 0.99) {
563 report_.store(1.0, std::memory_order_relaxed);
564 }
565 update_.Tick([&](Duration) {
566 // Reset the round tracker with the new sample.
567 const double current_estimate =
568 max_this_round_.exchange(sample, std::memory_order_relaxed);
569 double report;
570 if (current_estimate > 0.99) {
571 // Under very high memory pressure we... just max things out.
572 report = controller_.Update(1e99);
573 } else {
574 report = controller_.Update(current_estimate - kSetPoint);
575 }
576 if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
577 gpr_log(GPR_INFO, "RQ: pressure:%lf report:%lf controller:%s",
578 current_estimate, report, controller_.DebugString().c_str());
579 }
580 report_.store(report, std::memory_order_relaxed);
581 });
582 return report_.load(std::memory_order_relaxed);
583 }
584
585 } // namespace memory_quota_detail
586
587 //
588 // MemoryQuota
589 //
590
591 MemoryAllocator MemoryQuota::CreateMemoryAllocator(absl::string_view name) {
592 auto impl = std::make_shared<GrpcMemoryAllocatorImpl>(
593 memory_quota_, absl::StrCat(memory_quota_->name(), "/allocator/", name));
594 return MemoryAllocator(std::move(impl));
595 }
596
597 MemoryOwner MemoryQuota::CreateMemoryOwner(absl::string_view name) {
598 auto impl = std::make_shared<GrpcMemoryAllocatorImpl>(
599 memory_quota_, absl::StrCat(memory_quota_->name(), "/owner/", name));
600 return MemoryOwner(std::move(impl));
601 }
602
603 } // namespace grpc_core