]> git.ipfire.org Git - thirdparty/squid.git/blob - src/mem/PoolMalloc.cc
57be80248c3202f1a886554e4b93512e15d0fd55
[thirdparty/squid.git] / src / mem / PoolMalloc.cc
1 /*
2 * Copyright (C) 1996-2022 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 /*
10 * AUTHOR: Alex Rousskov, Andres Kroonmaa, Robert Collins, Henrik Nordstrom
11 */
12
13 #include "squid.h"
14 #include "mem/PoolMalloc.h"
15 #include "mem/Stats.h"
16
17 #include <cassert>
18 #include <cstring>
19
20 extern time_t squid_curtime;
21
22 void *
23 MemPoolMalloc::allocate()
24 {
25 void *obj = nullptr;
26 if (!freelist.empty()) {
27 obj = freelist.top();
28 freelist.pop();
29 }
30 if (obj) {
31 --meter.idle;
32 ++saved_calls;
33 } else {
34 if (doZero)
35 obj = xcalloc(1, obj_size);
36 else
37 obj = xmalloc(obj_size);
38 ++meter.alloc;
39 }
40 ++meter.inuse;
41 return obj;
42 }
43
44 void
45 MemPoolMalloc::deallocate(void *obj, bool aggressive)
46 {
47 --meter.inuse;
48 if (aggressive) {
49 xfree(obj);
50 --meter.alloc;
51 } else {
52 if (doZero)
53 memset(obj, 0, obj_size);
54 ++meter.idle;
55 freelist.push(obj);
56 }
57 }
58
59 /* TODO extract common logic to MemAllocate */
60 size_t
61 MemPoolMalloc::getStats(Mem::PoolStats &stats)
62 {
63 stats.pool = this;
64 stats.label = objectType();
65 stats.meter = &meter;
66 stats.obj_size = obj_size;
67 stats.chunk_capacity = 0;
68
69 stats.chunks_alloc += 0;
70 stats.chunks_inuse += 0;
71 stats.chunks_partial += 0;
72 stats.chunks_free += 0;
73
74 stats.items_alloc += meter.alloc.currentLevel();
75 stats.items_inuse += meter.inuse.currentLevel();
76 stats.items_idle += meter.idle.currentLevel();
77
78 stats.overhead += sizeof(MemPoolMalloc) + strlen(objectType()) + 1;
79
80 return meter.inuse.currentLevel();
81 }
82
83 int
84 MemPoolMalloc::getInUseCount()
85 {
86 return meter.inuse.currentLevel();
87 }
88
89 MemPoolMalloc::MemPoolMalloc(char const *aLabel, size_t aSize) : MemImplementingAllocator(aLabel, aSize)
90 {
91 }
92
93 MemPoolMalloc::~MemPoolMalloc()
94 {
95 assert(meter.inuse.currentLevel() == 0);
96 clean(0);
97 }
98
99 bool
100 MemPoolMalloc::idleTrigger(int shift) const
101 {
102 return freelist.size() >> (shift ? 8 : 0);
103 }
104
105 void
106 MemPoolMalloc::clean(time_t)
107 {
108 while (!freelist.empty()) {
109 void *obj = freelist.top();
110 freelist.pop();
111 --meter.idle;
112 --meter.alloc;
113 xfree(obj);
114 }
115 }
116