Debian Codegraph @

src/core/lib/resource_quota/memory_quota.h

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 #ifndef GRPC_CORE_LIB_RESOURCE_QUOTA_MEMORY_QUOTA_H
16 #define GRPC_CORE_LIB_RESOURCE_QUOTA_MEMORY_QUOTA_H
17
18 #include <grpc/support/port_platform.h>
19
20 #include <stdint.h>
21
22 #include <atomic>
23 #include <cstddef>
24 #include <limits>
25 #include <memory>
26 #include <string>
27 #include <utility>
28
29 #include "absl/base/thread_annotations.h"
30 #include "absl/strings/string_view.h"
31 #include "absl/types/optional.h"
32
33 #include <grpc/event_engine/memory_allocator.h>
34 #include <grpc/event_engine/memory_request.h>
35 #include <grpc/support/log.h>
36
37 #include "src/core/lib/experiments/experiments.h"
38 #include "src/core/lib/gprpp/orphanable.h"
39 #include "src/core/lib/gprpp/ref_counted_ptr.h"
40 #include "src/core/lib/gprpp/sync.h"
41 #include "src/core/lib/gprpp/time.h"
42 #include "src/core/lib/promise/activity.h"
43 #include "src/core/lib/promise/poll.h"
44 #include "src/core/lib/resource_quota/periodic_update.h"
45
46 namespace grpc_core {
47
48 class BasicMemoryQuota;
49 class MemoryQuota;
50
51 using grpc_event_engine::experimental::MemoryRequest;
52
53 // Pull in impl under a different name to keep the gRPC/EventEngine separation
54 // clear.
55 using EventEngineMemoryAllocatorImpl =
56 grpc_event_engine::experimental::internal::MemoryAllocatorImpl;
57 using grpc_event_engine::experimental::MemoryAllocator;
58 template <typename T>
59 using Vector = grpc_event_engine::experimental::Vector<T>;
60
61 // Reclamation passes.
62 // When memory is tight, we start trying to claim some back from memory
63 // reclaimers. We do this in multiple passes: if there is a less destructive
64 // operation available, we do that, otherwise we do something more destructive.
65 enum class ReclamationPass {
66 // Non-empty reclamation ought to take index 0, but to simplify API we don't
67 // expose that publicly (it's an internal detail), and hence index zero is
68 // here unnamed.
69
70 // Benign reclamation is intended for reclamation steps that are not
71 // observable outside of gRPC (besides maybe causing an increase in CPU
72 // usage).
73 // Examples of such reclamation would be resizing buffers to fit the current
74 // load needs, rather than whatever was the peak usage requirement.
75 kBenign = 1,
76 // Idle reclamation is intended for reclamation steps that are observable
77 // outside of gRPC, but do not cause application work to be lost.
78 // Examples of such reclamation would be dropping channels that are not being
79 // used.
80 kIdle = 2,
81 // Destructive reclamation is our last resort, and is these reclamations are
82 // allowed to drop work - such as cancelling in flight requests.
83 kDestructive = 3,
84 };
85 static constexpr size_t kNumReclamationPasses = 4;
86
87 // For each reclamation function run we construct a ReclamationSweep.
88 // When this object is finally destroyed (it may be moved several times first),
89 // then that reclamation is complete and we may continue the reclamation loop.
90 class ReclamationSweep {
91 public:
92 ReclamationSweep() = default;
93 ReclamationSweep(std::shared_ptr<BasicMemoryQuota> memory_quota,
94 uint64_t sweep_token, Waker waker)
95 : memory_quota_(std::move(memory_quota)),
96 sweep_token_(sweep_token),
97 waker_(std::move(waker)) {}
98 ~ReclamationSweep();
99
100 ReclamationSweep(const ReclamationSweep&) = delete;
101 ReclamationSweep& operator=(const ReclamationSweep&) = delete;
102 ReclamationSweep(ReclamationSweep&&) = default;
103 ReclamationSweep& operator=(ReclamationSweep&&) = default;
104
105 // Has enough work been done that we would not be called upon again
106 // immediately to do reclamation work if we stopped and requeued. Reclaimers
107 // with a variable amount of work to do can use this to ascertain when they
108 // can stop more efficiently than going through the reclaimer queue once per
109 // work item.
110 bool IsSufficient() const;
111
112 // Explicit finish for users that wish to write it.
113 // Just destroying the object is enough, but sometimes the additional
114 // explicitness is warranted.
115 void Finish() {
116 [](ReclamationSweep) {}(std::move(*this));
117 }
118
119 private:
120 std::shared_ptr<BasicMemoryQuota> memory_quota_;
121 uint64_t sweep_token_;
122 Waker waker_;
123 };
124
125 class ReclaimerQueue {
126 private:
127 struct QueuedNode;
128 struct State;
129
130 public:
131 class Handle : public InternallyRefCounted<Handle> {
132 public:
133 Handle() = default;
134 template <typename F>
135 explicit Handle(F reclaimer, std::shared_ptr<State> state)
136 : sweep_(new SweepFn<F>(std::move(reclaimer), std::move(state))) {}
137 ~Handle() override {
138 GPR_DEBUG_ASSERT(sweep_.load(std::memory_order_relaxed) == nullptr);
139 }
140
141 Handle(const Handle&) = delete;
142 Handle& operator=(const Handle&) = delete;
143
144 void Orphan() final;
145 void Run(ReclamationSweep reclamation_sweep);
146 bool Requeue(ReclaimerQueue* new_queue);
147
148 private:
149 friend class ReclaimerQueue;
150 using InternallyRefCounted<Handle>::Ref;
151
152 class Sweep {
153 public:
154 virtual void RunAndDelete(absl::optional<ReclamationSweep> sweep) = 0;
155
156 protected:
157 explicit Sweep(std::shared_ptr<State> state) : state_(std::move(state)) {}
158 ~Sweep() = default;
159 void MarkCancelled();
160
161 private:
162 std::shared_ptr<State> state_;
163 };
164
165 template <typename F>
166 class SweepFn final : public Sweep {
167 public:
168 explicit SweepFn(F&& f, std::shared_ptr<State> state)
169 : Sweep(std::move(state)), f_(std::move(f)) {}
170 void RunAndDelete(absl::optional<ReclamationSweep> sweep) override {
171 if (!sweep.has_value()) MarkCancelled();
172 f_(std::move(sweep));
173 delete this;
174 }
175
176 private:
177 F f_;
178 };
179
180 std::atomic<Sweep*> sweep_{nullptr};
181 };
182
183 ReclaimerQueue();
184 ~ReclaimerQueue();
185
186 ReclaimerQueue(const ReclaimerQueue&) = delete;
187 ReclaimerQueue& operator=(const ReclaimerQueue&) = delete;
188
189 // Insert a new element at the back of the queue.
190 // If there is already an element from allocator at *index, then it is
191 // replaced with the new reclaimer and *index is unchanged. If there is not,
192 // then *index is set to the index of the newly queued entry.
193 // Associates the reclamation function with an allocator, and keeps that
194 // allocator alive, so that we can use the pointer as an ABA guard.
195 template <typename F>
196 GRPC_MUST_USE_RESULT OrphanablePtr<Handle> Insert(F reclaimer) {
197 auto p = MakeOrphanable<Handle>(std::move(reclaimer), state_);
198 Enqueue(p->Ref());
199 return p;
200 }
201
202 // Poll to see if an entry is available: returns Pending if not, or the
203 // removed reclamation function if so.
204 Poll<RefCountedPtr<Handle>> PollNext();
205
206 // This callable is the promise backing Next - it resolves when there is an
207 // entry available. This really just redirects to calling PollNext().
208 class NextPromise {
209 public:
210 explicit NextPromise(ReclaimerQueue* queue) : queue_(queue) {}
211 Poll<RefCountedPtr<Handle>> operator()() { return queue_->PollNext(); }
212
213 private:
214 // Borrowed ReclaimerQueue backing this promise.
215 ReclaimerQueue* queue_;
216 };
217 GRPC_MUST_USE_RESULT NextPromise Next() { return NextPromise(this); }
218
219 private:
220 void Enqueue(RefCountedPtr<Handle> handle);
221
222 std::shared_ptr<State> state_;
223 };
224
225 namespace memory_quota_detail {
226 // Controller: tries to adjust a control variable up or down to get memory
227 // pressure to some target. We use the control variable to size buffers
228 // throughout the stack.
229 class PressureController {
230 public:
231 PressureController(uint8_t max_ticks_same, uint8_t max_reduction_per_tick)
232 : max_ticks_same_(max_ticks_same),
233 max_reduction_per_tick_(max_reduction_per_tick) {}
234 // Update the controller, returns the new control value.
235 double Update(double error);
236 // Textual representation of the controller.
237 std::string DebugString() const;
238
239 private:
240 // How many update periods have we reached the same decision in a row?
241 // Too many and we should start expanding the search space since we're not
242 // being agressive enough.
243 uint8_t ticks_same_ = 0;
244 // Maximum number of ticks with the same value until we start expanding the
245 // control space.
246 const uint8_t max_ticks_same_;
247 // Maximum amount to reduce the reporting value per iteration (in tenths of a
248 // percentile).
249 const uint8_t max_reduction_per_tick_;
250 // Was the last error indicating a too low pressure (or if false,
251 // a too high pressure).
252 bool last_was_low_ = true;
253 // Current minimum value to report.
254 double min_ = 0.0;
255 // Current maximum value to report.
256 // Set so that the first change over will choose 1.0 for max.
257 double max_ = 2.0;
258 // Last control value reported.
259 double last_control_ = 0.0;
260 };
261
262 // Utility to track memory pressure.
263 // Tries to be conservative (returns a higher pressure than there may actually
264 // be) but to be eventually accurate.
265 class PressureTracker {
266 public:
267 double AddSampleAndGetControlValue(double sample);
268
269 private:
270 std::atomic<double> max_this_round_{0.0};
271 std::atomic<double> report_{0.0};
272 PeriodicUpdate update_{Duration::Seconds(1)};
273 PressureController controller_{100, 3};
274 };
275 } // namespace memory_quota_detail
276
277 class BasicMemoryQuota final
278 : public std::enable_shared_from_this<BasicMemoryQuota> {
279 public:
280 // Data about current memory pressure.
281 struct PressureInfo {
282 // The current instantaneously measured memory pressure.
283 double instantaneous_pressure;
284 // A control value that can be used to scale buffer sizes up or down to
285 // adjust memory pressure to our target set point.
286 double pressure_control_value;
287 // Maximum recommended individual allocation size.
288 size_t max_recommended_allocation_size;
289 };
290
291 explicit BasicMemoryQuota(std::string name) : name_(std::move(name)) {}
292
293 // Start the reclamation activity.
294 void Start();
295 // Stop the reclamation activity.
296 // Until reclamation is stopped, it's possible that circular references to the
297 // BasicMemoryQuota remain. i.e. to guarantee deletion, a singular owning
298 // object should call BasicMemoryQuota::Stop().
299 void Stop();
300
301 // Resize the quota to new_size.
302 void SetSize(size_t new_size);
303 // Forcefully take some memory from the quota, potentially entering
304 // overcommit.
305 void Take(size_t amount);
306 // Finish reclamation pass.
307 void FinishReclamation(uint64_t token, Waker waker);
308 // Return some memory to the quota.
309 void Return(size_t amount);
310 // Instantaneous memory pressure approximation.
311 PressureInfo GetPressureInfo();
312 // Get a reclamation queue
313 ReclaimerQueue* reclaimer_queue(size_t i) { return &reclaimers_[i]; }
314
315 // The name of this quota
316 absl::string_view name() const { return name_; }
317
318 private:
319 friend class ReclamationSweep;
320 class WaitForSweepPromise;
321
322 static constexpr intptr_t kInitialSize = std::numeric_limits<intptr_t>::max();
323
324 // The amount of memory that's free in this quota.
325 // We use intptr_t as a reasonable proxy for ssize_t that's portable.
326 // We allow arbitrary overcommit and so this must allow negative values.
327 std::atomic<intptr_t> free_bytes_{kInitialSize};
328 // The total number of bytes in this quota.
329 std::atomic<size_t> quota_size_{kInitialSize};
330
331 // Reclaimer queues.
332 ReclaimerQueue reclaimers_[kNumReclamationPasses];
333 // The reclaimer activity consumes reclaimers whenever we are in overcommit to
334 // try and get back under memory limits.
335 ActivityPtr reclaimer_activity_;
336 // Each time we do a reclamation sweep, we increment this counter and give it
337 // to the sweep in question. In this way, should we choose to cancel a sweep
338 // we can do so and not get confused when the sweep reports back that it's
339 // completed.
340 // We also increment this counter on completion of a sweep, as an indicator
341 // that the wait has ended.
342 std::atomic<uint64_t> reclamation_counter_{0};
343 // Memory pressure smoothing
344 memory_quota_detail::PressureTracker pressure_tracker_;
345 // The name of this quota - used for debugging/tracing/etc..
346 std::string name_;
347 };
348
349 // MemoryAllocatorImpl grants the owner the ability to allocate memory from an
350 // underlying resource quota.
351 class GrpcMemoryAllocatorImpl final : public EventEngineMemoryAllocatorImpl {
352 public:
353 explicit GrpcMemoryAllocatorImpl(
354 std::shared_ptr<BasicMemoryQuota> memory_quota, std::string name);
355 ~GrpcMemoryAllocatorImpl() override;
356
357 // Reserve bytes from the quota.
358 // If we enter overcommit, reclamation will begin concurrently.
359 // Returns the number of bytes reserved.
360 size_t Reserve(MemoryRequest request) override;
361
362 // Release some bytes that were previously reserved.
363 void Release(size_t n) override {
364 // Add the released memory to our free bytes counter... if this increases
365 // from 0 to non-zero, then we have more to do, otherwise, we're actually
366 // done.
367 size_t prev_free = free_bytes_.fetch_add(n, std::memory_order_release);
368 if ((!IsUnconstrainedMaxQuotaBufferSizeEnabled() &&
369 prev_free + n > kMaxQuotaBufferSize) ||
370 (IsPeriodicResourceQuotaReclamationEnabled() &&
371 donate_back_.Tick([](Duration) {}))) {
372 // Try to immediately return some free'ed memory back to the total quota.
373 MaybeDonateBack();
374 }
375 if (prev_free != 0) return;
376 MaybeRegisterReclaimer();
377 }
378
379 // Post a reclamation function.
380 template <typename F>
381 void PostReclaimer(ReclamationPass pass, F fn) {
382 MutexLock lock(&reclaimer_mu_);
383 GPR_ASSERT(!shutdown_);
384 InsertReclaimer(static_cast<size_t>(pass), std::move(fn));
385 }
386
387 // Shutdown the allocator.
388 void Shutdown() override;
389
390 // Read the instantaneous memory pressure
391 BasicMemoryQuota::PressureInfo GetPressureInfo() const {
392 return memory_quota_->GetPressureInfo();
393 }
394
395 // Name of this allocator
396 absl::string_view name() const { return name_; }
397
398 private:
399 static constexpr size_t kMaxQuotaBufferSize = 1024 * 1024;
400 // Primitive reservation function.
401 absl::optional<size_t> TryReserve(MemoryRequest request) GRPC_MUST_USE_RESULT;
402 // This function may be invoked during a memory release operation.
403 // It will try to return half of our free pool to the quota.
404 void MaybeDonateBack();
405 // Replenish bytes from the quota, without blocking, possibly entering
406 // overcommit.
407 void Replenish();
408 // If we have not already, register a reclamation function against the quota
409 // to sweep any free memory back to that quota.
410 void MaybeRegisterReclaimer() ABSL_LOCKS_EXCLUDED(reclaimer_mu_);
411 template <typename F>
412 void InsertReclaimer(size_t pass, F fn)
413 ABSL_EXCLUSIVE_LOCKS_REQUIRED(reclaimer_mu_) {
414 reclamation_handles_[pass] =
415 memory_quota_->reclaimer_queue(pass)->Insert(std::move(fn));
416 }
417
418 // Backing resource quota.
419 const std::shared_ptr<BasicMemoryQuota> memory_quota_;
420 // Amount of memory this allocator has cached for its own use: to avoid quota
421 // contention, each MemoryAllocator can keep some memory in addition to what
422 // it is immediately using, and the quota can pull it back under memory
423 // pressure.
424 std::atomic<size_t> free_bytes_{0};
425 // Amount of memory taken from the quota by this allocator.
426 std::atomic<size_t> taken_bytes_{sizeof(GrpcMemoryAllocatorImpl)};
427 std::atomic<bool> registered_reclaimer_{false};
428 // We try to donate back some memory periodically to the central quota.
429 PeriodicUpdate donate_back_{Duration::Seconds(10)};
430 Mutex reclaimer_mu_;
431 bool shutdown_ ABSL_GUARDED_BY(reclaimer_mu_) = false;
432 // Indices into the various reclaimer queues, used so that we can cancel
433 // reclamation should we shutdown or get rebound.
434 OrphanablePtr<ReclaimerQueue::Handle>
435 reclamation_handles_[kNumReclamationPasses] ABSL_GUARDED_BY(
436 reclaimer_mu_);
437 // Name of this allocator.
438 std::string name_;
439 };
440
441 // MemoryOwner is an enhanced MemoryAllocator that can also reclaim memory, and
442 // be rebound to a different memory quota.
443 // Different modules should not share a MemoryOwner between themselves, instead
444 // each module that requires a MemoryOwner should create one from a resource
445 // quota. This is because the MemoryOwner reclaimers are tied to the
446 // MemoryOwner's lifetime, and are not queryable, so passing a MemoryOwner to a
447 // new owning module means that module cannot reason about which reclaimers are
448 // active, nor what they might do.
449 class MemoryOwner final : public MemoryAllocator {
450 public:
451 MemoryOwner() = default;
452
453 explicit MemoryOwner(std::shared_ptr<GrpcMemoryAllocatorImpl> allocator)
454 : MemoryAllocator(std::move(allocator)) {}
455
456 // Post a reclaimer for some reclamation pass.
457 template <typename F>
458 void PostReclaimer(ReclamationPass pass, F fn) {
459 impl()->PostReclaimer(pass, std::move(fn));
460 }
461
462 // Instantaneous memory pressure in the underlying quota.
463 BasicMemoryQuota::PressureInfo GetPressureInfo() const {
464 return impl()->GetPressureInfo();
465 }
466
467 template <typename T, typename... Args>
468 OrphanablePtr<T> MakeOrphanable(Args&&... args) {
469 return OrphanablePtr<T>(New<T>(std::forward<Args>(args)...));
470 }
471
472 // Name of this object
473 absl::string_view name() const { return impl()->name(); }
474
475 // Is this object valid (ie has not been moved out of or reset)
476 bool is_valid() const { return impl() != nullptr; }
477
478 private:
479 const GrpcMemoryAllocatorImpl* impl() const {
480 return static_cast<const GrpcMemoryAllocatorImpl*>(get_internal_impl_ptr());
481 }
482
483 GrpcMemoryAllocatorImpl* impl() {
484 return static_cast<GrpcMemoryAllocatorImpl*>(get_internal_impl_ptr());
485 }
486 };
487
488 // MemoryQuota tracks the amount of memory available as part of a ResourceQuota.
489 class MemoryQuota final
490 : public grpc_event_engine::experimental::MemoryAllocatorFactory {
491 public:
492 explicit MemoryQuota(std::string name)
493 : memory_quota_(std::make_shared<BasicMemoryQuota>(std::move(name))) {
494 memory_quota_->Start();
495 }
496 ~MemoryQuota() override {
497 if (memory_quota_ != nullptr) memory_quota_->Stop();
498 }
499
500 MemoryQuota(const MemoryQuota&) = delete;
501 MemoryQuota& operator=(const MemoryQuota&) = delete;
502 MemoryQuota(MemoryQuota&&) = default;
503 MemoryQuota& operator=(MemoryQuota&&) = default;
504
505 MemoryAllocator CreateMemoryAllocator(absl::string_view name) override;
506 MemoryOwner CreateMemoryOwner(absl::string_view name);
507
508 // Resize the quota to new_size.
509 void SetSize(size_t new_size) { memory_quota_->SetSize(new_size); }
510
511 // Return true if the instantaneous memory pressure is high.
512 bool IsMemoryPressureHigh() const {
513 static constexpr double kMemoryPressureHighThreshold = 1.0;
514 return memory_quota_->GetPressureInfo().instantaneous_pressure >
515 kMemoryPressureHighThreshold;
516 }
517
518 private:
519 friend class MemoryOwner;
520 std::shared_ptr<BasicMemoryQuota> memory_quota_;
521 };
522
523 using MemoryQuotaRefPtr = std::shared_ptr<MemoryQuota>;
524 inline MemoryQuotaRefPtr MakeMemoryQuota(std::string name) {
525 return std::make_shared<MemoryQuota>(std::move(name));
526 }
527
528 } // namespace grpc_core
529
530 #endif // GRPC_CORE_LIB_RESOURCE_QUOTA_MEMORY_QUOTA_H