2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
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.
9 /* DEBUG: section 13 High Level Memory Pool Management */
12 #include "acl/AclDenyInfoList.h"
13 #include "acl/AclNameList.h"
14 #include "base/PackableStream.h"
15 #include "ClientInfo.h"
19 #include "icmp/net_db.h"
21 #include "mem/forward.h"
22 #include "mem/Meter.h"
25 #include "mgr/Registration.h"
26 #include "SquidConfig.h"
27 #include "SquidList.h"
28 #include "SquidTime.h"
34 /* forward declarations */
35 static void memFree2K(void *);
36 static void memFree4K(void *);
37 static void memFree8K(void *);
38 static void memFree16K(void *);
39 static void memFree32K(void *);
40 static void memFree64K(void *);
42 /* local prototypes */
43 static void memStringStats(std::ostream
&);
46 static double xm_time
= 0;
47 static double xm_deltat
= 0;
50 #define mem_str_pool_count 6
57 static Mem::Meter StrCountMeter
;
58 static Mem::Meter StrVolumeMeter
;
60 static Mem::Meter HugeBufCountMeter
;
61 static Mem::Meter HugeBufVolumeMeter
;
64 static MemAllocator
*&
67 static MemAllocator
*pools
[MEM_MAX
];
68 static bool initialized
= false;
71 memset(pools
, '\0', sizeof(pools
));
73 // Mem::Init() makes use of GetPool(type) to initialize
74 // the actual pools. So must come after the flag is true
82 GetStrPool(size_t type
)
84 static MemAllocator
*strPools
[mem_str_pool_count
];
85 static bool initialized
= false;
87 static const PoolMeta PoolAttrs
[mem_str_pool_count
] = {
88 {"Short Strings", MemAllocator::RoundedSize(36)}, /* to fit rfc1123 and similar */
89 {"Medium Strings", MemAllocator::RoundedSize(128)}, /* to fit most urls */
90 {"Long Strings", MemAllocator::RoundedSize(512)},
91 {"1KB Strings", MemAllocator::RoundedSize(1024)},
92 {"4KB Strings", MemAllocator::RoundedSize(4*1024)},
93 {"16KB Strings", MemAllocator::RoundedSize(16*1024)}
97 memset(strPools
, '\0', sizeof(strPools
));
99 /** Lastly init the string pools. */
100 for (int i
= 0; i
< mem_str_pool_count
; ++i
) {
101 strPools
[i
] = memPoolCreate(PoolAttrs
[i
].name
, PoolAttrs
[i
].obj_size
);
102 strPools
[i
]->zeroBlocks(false);
104 if (strPools
[i
]->objectSize() != PoolAttrs
[i
].obj_size
)
105 debugs(13, DBG_IMPORTANT
, "NOTICE: " << PoolAttrs
[i
].name
<<
106 " is " << strPools
[i
]->objectSize() <<
107 " bytes instead of requested " <<
108 PoolAttrs
[i
].obj_size
<< " bytes");
114 return *strPools
[type
];
117 /* Find the best fit string pool type */
119 memFindStringSizeType(size_t net_size
, bool fuzzy
)
121 mem_type type
= MEM_NONE
;
122 for (unsigned int i
= 0; i
< mem_str_pool_count
; ++i
) {
123 auto &pool
= GetStrPool(i
);
124 if (fuzzy
&& net_size
< pool
.objectSize()) {
125 type
= static_cast<mem_type
>(i
);
127 } else if (net_size
== pool
.objectSize()) {
128 type
= static_cast<mem_type
>(i
);
137 memStringStats(std::ostream
&stream
)
140 int pooled_count
= 0;
141 size_t pooled_volume
= 0;
143 stream
<< "String Pool\t Impact\t\t\n \t (%strings)\t (%volume)\n";
146 for (i
= 0; i
< mem_str_pool_count
; ++i
) {
147 const auto &pool
= GetStrPool(i
);
148 const auto plevel
= pool
.getMeter().inuse
.currentLevel();
149 stream
<< std::setw(20) << std::left
<< pool
.objectType();
150 stream
<< std::right
<< "\t " << xpercentInt(plevel
, StrCountMeter
.currentLevel());
151 stream
<< "\t " << xpercentInt(plevel
* pool
.objectSize(), StrVolumeMeter
.currentLevel()) << "\n";
152 pooled_count
+= plevel
;
153 pooled_volume
+= plevel
* pool
.objectSize();
157 stream
<< std::setw(20) << std::left
<< "Other Strings";
158 stream
<< std::right
<< "\t ";
159 stream
<< xpercentInt(StrCountMeter
.currentLevel() - pooled_count
, StrCountMeter
.currentLevel()) << "\t ";
160 stream
<< xpercentInt(StrVolumeMeter
.currentLevel() - pooled_volume
, StrVolumeMeter
.currentLevel()) << "\n\n";
164 memBufStats(std::ostream
& stream
)
166 stream
<< "Large buffers: " <<
167 HugeBufCountMeter
.currentLevel() << " (" <<
168 HugeBufVolumeMeter
.currentLevel() / 1024 << " KB)\n";
172 Mem::Stats(StoreEntry
* sentry
)
174 PackableStream
stream(*sentry
);
176 memStringStats(stream
);
179 if (RUNNING_ON_VALGRIND
) {
180 long int leaked
= 0, dubious
= 0, reachable
= 0, suppressed
= 0;
181 stream
<< "Valgrind Report:\n";
182 stream
<< "Type\tAmount\n";
183 debugs(13, DBG_IMPORTANT
, "Asking valgrind for memleaks");
184 VALGRIND_DO_LEAK_CHECK
;
185 debugs(13, DBG_IMPORTANT
, "Getting valgrind statistics");
186 VALGRIND_COUNT_LEAKS(leaked
, dubious
, reachable
, suppressed
);
187 stream
<< "Leaked\t" << leaked
<< "\n";
188 stream
<< "Dubious\t" << dubious
<< "\n";
189 stream
<< "Reachable\t" << reachable
<< "\n";
190 stream
<< "Suppressed\t" << suppressed
<< "\n";
201 * we have a limit on _total_ amount of idle memory so we ignore max_pages for now.
202 * Will ignore repeated calls for the same pool type.
204 * Relies on Mem::Init() having been called beforehand.
207 memDataInit(mem_type type
, const char *name
, size_t size
, int, bool doZero
)
209 assert(name
&& size
);
211 if (GetPool(type
) != NULL
)
214 GetPool(type
) = memPoolCreate(name
, size
);
215 GetPool(type
)->zeroBlocks(doZero
);
218 /* find appropriate pool and use it (pools always init buffer with 0s) */
220 memAllocate(mem_type type
)
222 assert(GetPool(type
));
223 return GetPool(type
)->alloc();
226 /* give memory back to the pool */
228 memFree(void *p
, int type
)
230 assert(GetPool(type
));
231 GetPool(type
)->freeOne(p
);
234 /* allocate a variable size buffer using best-fit string pool */
236 memAllocString(size_t net_size
, size_t * gross_size
)
240 auto type
= memFindStringSizeType(net_size
, true);
241 if (type
!= MEM_NONE
) {
242 auto &pool
= GetStrPool(type
);
243 *gross_size
= pool
.objectSize();
244 assert(*gross_size
>= net_size
);
246 StrVolumeMeter
+= *gross_size
;
250 *gross_size
= net_size
;
252 StrVolumeMeter
+= *gross_size
;
253 return xcalloc(1, net_size
);
261 for (int counter
= 0; counter
< mem_str_pool_count
; ++counter
)
262 result
+= GetStrPool(counter
).inUseCount();
267 /* free buffer allocated with memAllocString() */
269 memFreeString(size_t size
, void *buf
)
273 auto type
= memFindStringSizeType(size
, false);
274 if (type
!= MEM_NONE
)
275 GetStrPool(type
).freeOne(buf
);
280 StrVolumeMeter
-= size
;
283 /* Find the best fit MEM_X_BUF type */
285 memFindBufSizeType(size_t net_size
, size_t * gross_size
)
290 if (net_size
<= 2 * 1024) {
293 } else if (net_size
<= 4 * 1024) {
296 } else if (net_size
<= 8 * 1024) {
299 } else if (net_size
<= 16 * 1024) {
302 } else if (net_size
<= 32 * 1024) {
305 } else if (net_size
<= 64 * 1024) {
319 /* allocate a variable size buffer using best-fit pool */
321 memAllocBuf(size_t net_size
, size_t * gross_size
)
323 mem_type type
= memFindBufSizeType(net_size
, gross_size
);
325 if (type
!= MEM_NONE
)
326 return memAllocate(type
);
329 HugeBufVolumeMeter
+= *gross_size
;
330 return xcalloc(1, net_size
);
334 /* resize a variable sized buffer using best-fit pool */
336 memReallocBuf(void *oldbuf
, size_t net_size
, size_t * gross_size
)
338 /* XXX This can be optimized on very large buffers to use realloc() */
339 /* TODO: if the existing gross size is >= new gross size, do nothing */
340 size_t new_gross_size
;
341 void *newbuf
= memAllocBuf(net_size
, &new_gross_size
);
344 size_t data_size
= *gross_size
;
346 if (data_size
> net_size
)
347 data_size
= net_size
;
349 memcpy(newbuf
, oldbuf
, data_size
);
351 memFreeBuf(*gross_size
, oldbuf
);
354 *gross_size
= new_gross_size
;
358 /* free buffer allocated with memAllocBuf() */
360 memFreeBuf(size_t size
, void *buf
)
362 mem_type type
= memFindBufSizeType(size
, NULL
);
364 if (type
!= MEM_NONE
)
369 HugeBufVolumeMeter
-= size
;
373 static double clean_interval
= 15.0; /* time to live of idle chunk before release */
376 Mem::CleanIdlePools(void *)
378 MemPools::GetInstance().clean(static_cast<time_t>(clean_interval
));
379 eventAdd("memPoolCleanIdlePools", CleanIdlePools
, NULL
, clean_interval
, 1);
385 int64_t new_pool_limit
;
387 /** Set to configured value first */
388 if (!Config
.onoff
.mem_pools
)
390 else if (Config
.MemPools
.limit
> 0)
391 new_pool_limit
= Config
.MemPools
.limit
;
393 if (Config
.MemPools
.limit
== 0)
394 debugs(13, DBG_IMPORTANT
, "memory_pools_limit 0 has been chagned to memory_pools_limit none. Please update your config");
401 * No debugging here please because this method is called before
402 * the debug log is configured and we'll get the message on
403 * stderr when doing things like 'squid -k reconfigure'
405 if (MemPools::GetInstance().idleLimit() > new_pool_limit
)
406 debugs(13, DBG_IMPORTANT
, "Shrinking idle mem pools to "<< std::setprecision(3) << toMB(new_pool_limit
) << " MB");
409 MemPools::GetInstance().setIdleLimit(new_pool_limit
);
412 /* XXX make these classes do their own memory management */
413 #include "HttpHdrContRange.h"
418 /* all pools are ready to be used */
419 static bool MemIsInitialized
= false;
420 if (MemIsInitialized
)
424 * NOTE: Mem::Init() is called before the config file is parsed
425 * and before the debugging module has been initialized. Any
426 * debug messages here at level 0 or 1 will always be printed
431 * Then initialize all pools.
433 * Starting with generic 2kB - 64kB buffr pools, then specific object types.
435 * It does not hurt much to have a lot of pools since sizeof(MemPool) is
436 * small; someday we will figure out what to do with all the entries here
437 * that are never used or used only once; perhaps we should simply use
438 * malloc() for those? @?@
440 memDataInit(MEM_2K_BUF
, "2K Buffer", 2048, 10, false);
441 memDataInit(MEM_4K_BUF
, "4K Buffer", 4096, 10, false);
442 memDataInit(MEM_8K_BUF
, "8K Buffer", 8192, 10, false);
443 memDataInit(MEM_16K_BUF
, "16K Buffer", 16384, 10, false);
444 memDataInit(MEM_32K_BUF
, "32K Buffer", 32768, 10, false);
445 memDataInit(MEM_64K_BUF
, "64K Buffer", 65536, 10, false);
446 memDataInit(MEM_ACL_DENY_INFO_LIST
, "AclDenyInfoList",
447 sizeof(AclDenyInfoList
), 0);
448 memDataInit(MEM_ACL_NAME_LIST
, "acl_name_list", sizeof(AclNameList
), 0);
449 memDataInit(MEM_LINK_LIST
, "link_list", sizeof(link_list
), 10);
450 memDataInit(MEM_DLINK_NODE
, "dlink_node", sizeof(dlink_node
), 10);
451 memDataInit(MEM_DREAD_CTRL
, "dread_ctrl", sizeof(dread_ctrl
), 0);
452 memDataInit(MEM_DWRITE_Q
, "dwrite_q", sizeof(dwrite_q
), 0);
453 memDataInit(MEM_HTTP_HDR_CONTENT_RANGE
, "HttpHdrContRange", sizeof(HttpHdrContRange
), 0);
454 memDataInit(MEM_NETDBENTRY
, "netdbEntry", sizeof(netdbEntry
), 0);
455 memDataInit(MEM_NET_DB_NAME
, "net_db_name", sizeof(net_db_name
), 0);
456 memDataInit(MEM_CLIENT_INFO
, "ClientInfo", sizeof(ClientInfo
), 0);
457 memDataInit(MEM_MD5_DIGEST
, "MD5 digest", SQUID_MD5_DIGEST_LENGTH
, 0);
458 GetPool(MEM_MD5_DIGEST
)->setChunkSize(512 * 1024);
460 MemIsInitialized
= true;
462 // finally register with the cache manager
463 Mgr::RegisterAction("mem", "Memory Utilization", Mem::Stats
, 0, 1);
469 debugs(13, 3, "Memory pools are '" <<
470 (Config
.onoff
.mem_pools
? "on" : "off") << "'; limit: " <<
471 std::setprecision(3) << toMB(MemPools::GetInstance().idleLimit()) <<
475 mem_type
&operator++ (mem_type
&aMem
)
478 aMem
= (mem_type
)(++tmp
);
483 * Test that all entries are initialized
488 mem_type t
= MEM_NONE
;
490 while (++t
< MEM_DONTFREE
) {
492 * If you hit this assertion, then you forgot to add a
493 * memDataInit() line for type 't'.
494 * Or placed the pool type in the wrong section of the enum list.
503 MemPoolGlobalStats stats
;
504 if (Config
.MemPools
.limit
> 0) // do not reset if disabled or same
505 MemPools::GetInstance().setIdleLimit(0);
506 MemPools::GetInstance().clean(0);
507 memPoolGetGlobalStats(&stats
);
509 if (stats
.tot_items_inuse
)
510 debugs(13, 2, "memCleanModule: " << stats
.tot_items_inuse
<<
511 " items in " << stats
.tot_chunks_inuse
<< " chunks and " <<
512 stats
.tot_pools_inuse
<< " pools are left dirty");
516 memInUse(mem_type type
)
518 return GetPool(type
)->inUseCount();
526 memFree(p
, MEM_2K_BUF
);
532 memFree(p
, MEM_4K_BUF
);
538 memFree(p
, MEM_8K_BUF
);
544 memFree(p
, MEM_16K_BUF
);
550 memFree(p
, MEM_32K_BUF
);
556 memFree(p
, MEM_64K_BUF
);
560 cxx_xfree(void * ptr
)
566 memFreeBufFunc(size_t size
)
590 HugeBufVolumeMeter
-= size
;
598 Mem::PoolReport(const MemPoolStats
* mp_st
, const MemPoolMeter
* AllMeter
, std::ostream
&stream
)
602 MemPoolMeter
*pm
= mp_st
->meter
;
603 const char *delim
= "\t ";
605 stream
.setf(std::ios_base::fixed
);
606 stream
<< std::setw(20) << std::left
<< mp_st
->label
<< delim
;
607 stream
<< std::setw(4) << std::right
<< mp_st
->obj_size
<< delim
;
610 if (mp_st
->chunk_capacity
) {
611 stream
<< std::setw(4) << toKB(mp_st
->obj_size
* mp_st
->chunk_capacity
) << delim
;
612 stream
<< std::setw(4) << mp_st
->chunk_capacity
<< delim
;
614 needed
= mp_st
->items_inuse
/ mp_st
->chunk_capacity
;
616 if (mp_st
->items_inuse
% mp_st
->chunk_capacity
)
619 excess
= mp_st
->chunks_inuse
- needed
;
621 stream
<< std::setw(4) << mp_st
->chunks_alloc
<< delim
;
622 stream
<< std::setw(4) << mp_st
->chunks_inuse
<< delim
;
623 stream
<< std::setw(4) << mp_st
->chunks_free
<< delim
;
624 stream
<< std::setw(4) << mp_st
->chunks_partial
<< delim
;
625 stream
<< std::setprecision(3) << xpercent(excess
, needed
) << delim
;
636 * Fragmentation calculation:
637 * needed = inuse.currentLevel() / chunk_capacity
638 * excess = used - needed
639 * fragmentation = excess / needed * 100%
641 * Fragm = (alloced - (inuse / obj_ch) ) / alloced
644 stream
<< mp_st
->items_alloc
<< delim
;
645 stream
<< toKB(mp_st
->obj_size
* pm
->alloc
.currentLevel()) << delim
;
646 stream
<< toKB(mp_st
->obj_size
* pm
->alloc
.peak()) << delim
;
647 stream
<< std::setprecision(2) << ((squid_curtime
- pm
->alloc
.peakTime()) / 3600.) << delim
;
648 stream
<< std::setprecision(3) << xpercent(mp_st
->obj_size
* pm
->alloc
.currentLevel(), AllMeter
->alloc
.currentLevel()) << delim
;
650 stream
<< mp_st
->items_inuse
<< delim
;
651 stream
<< toKB(mp_st
->obj_size
* pm
->inuse
.currentLevel()) << delim
;
652 stream
<< toKB(mp_st
->obj_size
* pm
->inuse
.peak()) << delim
;
653 stream
<< std::setprecision(2) << ((squid_curtime
- pm
->inuse
.peakTime()) / 3600.) << delim
;
654 stream
<< std::setprecision(3) << xpercent(pm
->inuse
.currentLevel(), pm
->alloc
.currentLevel()) << delim
;
656 stream
<< mp_st
->items_idle
<< delim
;
657 stream
<< toKB(mp_st
->obj_size
* pm
->idle
.currentLevel()) << delim
;
658 stream
<< toKB(mp_st
->obj_size
* pm
->idle
.peak()) << delim
;
660 stream
<< (int)pm
->gb_saved
.count
<< delim
;
661 stream
<< std::setprecision(3) << xpercent(pm
->gb_saved
.count
, AllMeter
->gb_allocated
.count
) << delim
;
662 stream
<< std::setprecision(3) << xpercent(pm
->gb_saved
.bytes
, AllMeter
->gb_allocated
.bytes
) << delim
;
663 stream
<< std::setprecision(3) << xdiv(pm
->gb_allocated
.count
- pm
->gb_oallocated
.count
, xm_deltat
) << "\n";
664 pm
->gb_oallocated
.count
= pm
->gb_allocated
.count
;
668 MemPoolReportSorter(const void *a
, const void *b
)
670 const MemPoolStats
*A
= (MemPoolStats
*) a
;
671 const MemPoolStats
*B
= (MemPoolStats
*) b
;
673 // use this to sort on %Total Allocated
675 double pa
= (double) A
->obj_size
* A
->meter
->alloc
.currentLevel();
676 double pb
= (double) B
->obj_size
* B
->meter
->alloc
.currentLevel();
685 // use this to sort on In Use high(hrs)
687 if (A
->meter
->inuse
.peakTime() > B
->meter
->inuse
.peakTime())
690 if (B
->meter
->inuse
.peakTime() > A
->meter
->inuse
.peakTime())
699 Mem::Report(std::ostream
&stream
)
702 static MemPoolStats mp_stats
;
703 static MemPoolGlobalStats mp_total
;
705 MemPoolIterator
*iter
;
709 stream
<< "Current memory usage:\n";
711 stream
<< "Pool\t Obj Size\t"
712 "Chunks\t\t\t\t\t\t\t"
713 "Allocated\t\t\t\t\t"
716 "Allocations Saved\t\t\t"
721 "(#)\t used\t free\t part\t %Frag\t "
722 "(#)\t (KB)\t high (KB)\t high (hrs)\t %Tot\t"
723 "(#)\t (KB)\t high (KB)\t high (hrs)\t %alloc\t"
724 "(#)\t (KB)\t high (KB)\t"
725 "(#)\t %cnt\t %vol\t"
728 xm_deltat
= current_dtime
- xm_time
;
729 xm_time
= current_dtime
;
731 /* Get stats for Totals report line */
732 memPoolGetGlobalStats(&mp_total
);
734 MemPoolStats
*sortme
= (MemPoolStats
*) xcalloc(mp_total
.tot_pools_alloc
,sizeof(*sortme
));
738 iter
= memPoolIterate();
740 while ((pool
= memPoolIterateNext(iter
))) {
741 pool
->getStats(&mp_stats
);
743 if (!mp_stats
.pool
) /* pool destroyed */
746 if (mp_stats
.pool
->getMeter().gb_allocated
.count
> 0) {
747 /* this pool has been used */
748 sortme
[npools
] = mp_stats
;
755 memPoolIterateDone(&iter
);
757 qsort(sortme
, npools
, sizeof(*sortme
), MemPoolReportSorter
);
759 for (int i
= 0; i
< npools
; ++i
) {
760 PoolReport(&sortme
[i
], mp_total
.TheMeter
, stream
);
765 mp_stats
.pool
= NULL
;
766 mp_stats
.label
= "Total";
767 mp_stats
.meter
= mp_total
.TheMeter
;
768 mp_stats
.obj_size
= 1;
769 mp_stats
.chunk_capacity
= 0;
770 mp_stats
.chunk_size
= 0;
771 mp_stats
.chunks_alloc
= mp_total
.tot_chunks_alloc
;
772 mp_stats
.chunks_inuse
= mp_total
.tot_chunks_inuse
;
773 mp_stats
.chunks_partial
= mp_total
.tot_chunks_partial
;
774 mp_stats
.chunks_free
= mp_total
.tot_chunks_free
;
775 mp_stats
.items_alloc
= mp_total
.tot_items_alloc
;
776 mp_stats
.items_inuse
= mp_total
.tot_items_inuse
;
777 mp_stats
.items_idle
= mp_total
.tot_items_idle
;
778 mp_stats
.overhead
= mp_total
.tot_overhead
;
780 PoolReport(&mp_stats
, mp_total
.TheMeter
, stream
);
783 stream
<< "Cumulative allocated volume: "<< double_to_str(buf
, 64, mp_total
.TheMeter
->gb_allocated
.bytes
) << "\n";
785 stream
<< "Current overhead: " << mp_total
.tot_overhead
<< " bytes (" <<
786 std::setprecision(3) << xpercent(mp_total
.tot_overhead
, mp_total
.TheMeter
->inuse
.currentLevel()) << "%)\n";
788 if (mp_total
.mem_idle_limit
>= 0)
789 stream
<< "Idle pool limit: " << std::setprecision(2) << toMB(mp_total
.mem_idle_limit
) << " MB\n";
791 stream
<< "Total Pools created: " << mp_total
.tot_pools_alloc
<< "\n";
792 stream
<< "Pools ever used: " << mp_total
.tot_pools_alloc
- not_used
<< " (shown above)\n";
793 stream
<< "Currently in use: " << mp_total
.tot_pools_inuse
<< "\n";