xref: /netbsd-src/external/mpl/bind/dist/lib/dns/cache.c (revision 8e33eff89e26cf71871ead62f0d5063e1313c33a)
1 /*	$NetBSD: cache.c,v 1.12 2024/09/22 00:14:05 christos Exp $	*/
2 
3 /*
4  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
5  *
6  * SPDX-License-Identifier: MPL-2.0
7  *
8  * This Source Code Form is subject to the terms of the Mozilla Public
9  * License, v. 2.0. If a copy of the MPL was not distributed with this
10  * file, you can obtain one at https://mozilla.org/MPL/2.0/.
11  *
12  * See the COPYRIGHT file distributed with this work for additional
13  * information regarding copyright ownership.
14  */
15 
16 /*! \file */
17 
18 #include <inttypes.h>
19 #include <stdbool.h>
20 
21 #include <isc/mem.h>
22 #include <isc/print.h>
23 #include <isc/refcount.h>
24 #include <isc/result.h>
25 #include <isc/stats.h>
26 #include <isc/string.h>
27 #include <isc/task.h>
28 #include <isc/time.h>
29 #include <isc/timer.h>
30 #include <isc/util.h>
31 
32 #include <dns/cache.h>
33 #include <dns/db.h>
34 #include <dns/dbiterator.h>
35 #include <dns/events.h>
36 #include <dns/log.h>
37 #include <dns/masterdump.h>
38 #include <dns/rdata.h>
39 #include <dns/rdataset.h>
40 #include <dns/rdatasetiter.h>
41 #include <dns/stats.h>
42 
43 #ifdef HAVE_JSON_C
44 #include <json_object.h>
45 #endif /* HAVE_JSON_C */
46 
47 #ifdef HAVE_LIBXML2
48 #include <libxml/xmlwriter.h>
49 #define ISC_XMLCHAR (const xmlChar *)
50 #endif /* HAVE_LIBXML2 */
51 
52 #include "rbtdb.h"
53 
54 #define CACHE_MAGIC	   ISC_MAGIC('$', '$', '$', '$')
55 #define VALID_CACHE(cache) ISC_MAGIC_VALID(cache, CACHE_MAGIC)
56 
57 /*!
58  * Control incremental cleaning.
59  * DNS_CACHE_MINSIZE is how many bytes is the floor for
60  * dns_cache_setcachesize(). See also DNS_CACHE_CLEANERINCREMENT
61  */
62 #define DNS_CACHE_MINSIZE 2097152U /*%< Bytes.  2097152 = 2 MB */
63 /*!
64  * Control incremental cleaning.
65  * CLEANERINCREMENT is how many nodes are examined in one pass.
66  * See also DNS_CACHE_MINSIZE
67  */
68 #define DNS_CACHE_CLEANERINCREMENT 1000U /*%< Number of nodes. */
69 
70 /***
71  ***	Types
72  ***/
73 
74 /*
75  * A cache_cleaner_t encapsulates the state of the periodic
76  * cache cleaning.
77  */
78 
79 typedef struct cache_cleaner cache_cleaner_t;
80 
81 typedef enum {
82 	cleaner_s_idle, /*%< Waiting for cleaning interval to expire. */
83 	cleaner_s_busy, /*%< Currently cleaning. */
84 	cleaner_s_done	/*%< Freed enough memory after being overmem. */
85 } cleaner_state_t;
86 
87 /*
88  * Convenience macros for comprehensive assertion checking.
89  */
90 #define CLEANER_IDLE(c) \
91 	((c)->state == cleaner_s_idle && (c)->resched_event != NULL)
92 #define CLEANER_BUSY(c)                                           \
93 	((c)->state == cleaner_s_busy && (c)->iterator != NULL && \
94 	 (c)->resched_event == NULL)
95 
96 /*%
97  * Accesses to a cache cleaner object are synchronized through
98  * task/event serialization, or locked from the cache object.
99  */
100 struct cache_cleaner {
101 	isc_mutex_t lock;
102 	/*%<
103 	 * Locks overmem_event, overmem.  Note: never allocate memory
104 	 * while holding this lock - that could lead to deadlock since
105 	 * the lock is take by water() which is called from the memory
106 	 * allocator.
107 	 */
108 
109 	dns_cache_t *cache;
110 	isc_task_t *task;
111 	isc_event_t *resched_event; /*% Sent by cleaner task to
112 				     * itself to reschedule */
113 	isc_event_t *overmem_event;
114 
115 	dns_dbiterator_t *iterator;
116 	unsigned int increment; /*% Number of names to
117 				 * clean in one increment */
118 	cleaner_state_t state;	/*% Idle/Busy. */
119 	bool overmem;		/*% The cache is in an overmem state.
120 				 * */
121 	bool replaceiterator;
122 };
123 
124 /*%
125  * The actual cache object.
126  */
127 
128 struct dns_cache {
129 	/* Unlocked. */
130 	unsigned int magic;
131 	isc_mutex_t lock;
132 	isc_mem_t *mctx;  /* Memory context for the dns_cache object */
133 	isc_mem_t *hmctx; /* Heap memory */
134 	isc_mem_t *tmctx; /* Tree memory */
135 	isc_taskmgr_t *taskmgr;
136 	char *name;
137 	isc_refcount_t references;
138 	isc_refcount_t live_tasks;
139 
140 	/* Locked by 'lock'. */
141 	dns_rdataclass_t rdclass;
142 	dns_db_t *db;
143 	cache_cleaner_t cleaner;
144 	char *db_type;
145 	int db_argc;
146 	char **db_argv;
147 	size_t size;
148 	dns_ttl_t serve_stale_ttl;
149 	dns_ttl_t serve_stale_refresh;
150 	isc_stats_t *stats;
151 	uint32_t maxrrperset;
152 	uint32_t maxtypepername;
153 };
154 
155 /***
156  ***	Functions
157  ***/
158 
159 static isc_result_t
160 cache_cleaner_init(dns_cache_t *cache, isc_taskmgr_t *taskmgr,
161 		   isc_timermgr_t *timermgr, cache_cleaner_t *cleaner);
162 
163 static void
164 incremental_cleaning_action(isc_task_t *task, isc_event_t *event);
165 
166 static void
167 cleaner_shutdown_action(isc_task_t *task, isc_event_t *event);
168 
169 static void
170 overmem_cleaning_action(isc_task_t *task, isc_event_t *event);
171 
172 static void
173 water(void *arg, int mark);
174 
175 static isc_result_t
176 cache_create_db(dns_cache_t *cache, dns_db_t **dbp, isc_mem_t **tmctxp,
177 		isc_mem_t **hmctxp) {
178 	isc_result_t result;
179 	isc_task_t *dbtask = NULL;
180 	isc_task_t *prunetask = NULL;
181 	dns_db_t *db = NULL;
182 	isc_mem_t *tmctx = NULL;
183 	isc_mem_t *hmctx = NULL;
184 
185 	REQUIRE(dbp != NULL && *dbp == NULL);
186 	REQUIRE(tmctxp != NULL && *tmctxp == NULL);
187 	REQUIRE(hmctxp != NULL && *hmctxp == NULL);
188 
189 	/*
190 	 * This will be the cache memory context, which is subject
191 	 * to cleaning when the configured memory limits are exceeded.
192 	 */
193 	isc_mem_create(&tmctx);
194 	isc_mem_setname(tmctx, "cache");
195 
196 	/*
197 	 * This will be passed to RBTDB to use for heaps. This is separate
198 	 * from the main cache memory because it can grow quite large under
199 	 * heavy load and could otherwise cause the cache to be cleaned too
200 	 * aggressively.
201 	 */
202 	isc_mem_create(&hmctx);
203 	isc_mem_setname(hmctx, "cache_heap");
204 
205 	if (strcmp(cache->db_type, "rbt") == 0) {
206 		cache->db_argv[0] = (char *)hmctx;
207 	}
208 	result = dns_db_create(tmctx, cache->db_type, dns_rootname,
209 			       dns_dbtype_cache, cache->rdclass, cache->db_argc,
210 			       cache->db_argv, &db);
211 	if (result != ISC_R_SUCCESS) {
212 		goto cleanup_mctx;
213 	}
214 
215 	dns_db_setservestalettl(db, cache->serve_stale_ttl);
216 	dns_db_setservestalerefresh(db, cache->serve_stale_refresh);
217 	dns_db_setmaxrrperset(db, cache->maxrrperset);
218 	dns_db_setmaxtypepername(db, cache->maxtypepername);
219 
220 	if (cache->taskmgr == NULL) {
221 		*dbp = db;
222 		*tmctxp = tmctx;
223 		*hmctxp = hmctx;
224 		return (ISC_R_SUCCESS);
225 	}
226 
227 	result = isc_task_create(cache->taskmgr, 1, &dbtask);
228 	if (result != ISC_R_SUCCESS) {
229 		goto cleanup_db;
230 	}
231 	isc_task_setname(dbtask, "cache_dbtask", NULL);
232 
233 	result = isc_task_create(cache->taskmgr, UINT_MAX, &prunetask);
234 	if (result != ISC_R_SUCCESS) {
235 		goto cleanup_dbtask;
236 	}
237 	isc_task_setname(prunetask, "cache_prunetask", NULL);
238 
239 	dns_db_settask(db, dbtask, prunetask);
240 
241 	isc_task_detach(&prunetask);
242 	isc_task_detach(&dbtask);
243 
244 	*dbp = db;
245 	*tmctxp = tmctx;
246 	*hmctxp = hmctx;
247 
248 	return (ISC_R_SUCCESS);
249 
250 cleanup_dbtask:
251 	isc_task_detach(&dbtask);
252 cleanup_db:
253 	dns_db_detach(&db);
254 cleanup_mctx:
255 	isc_mem_detach(&tmctx);
256 	isc_mem_detach(&hmctx);
257 
258 	return (result);
259 }
260 
261 static void
262 cache_free(dns_cache_t *cache) {
263 	REQUIRE(VALID_CACHE(cache));
264 
265 	isc_refcount_destroy(&cache->references);
266 	isc_refcount_destroy(&cache->live_tasks);
267 
268 	isc_mem_clearwater(cache->tmctx);
269 
270 	if (cache->cleaner.task != NULL) {
271 		isc_task_detach(&cache->cleaner.task);
272 	}
273 
274 	if (cache->cleaner.overmem_event != NULL) {
275 		isc_event_free(&cache->cleaner.overmem_event);
276 	}
277 
278 	if (cache->cleaner.resched_event != NULL) {
279 		isc_event_free(&cache->cleaner.resched_event);
280 	}
281 
282 	if (cache->cleaner.iterator != NULL) {
283 		dns_dbiterator_destroy(&cache->cleaner.iterator);
284 	}
285 
286 	isc_mutex_destroy(&cache->cleaner.lock);
287 
288 	if (cache->db != NULL) {
289 		dns_db_detach(&cache->db);
290 	}
291 
292 	if (cache->db_argv != NULL) {
293 		/*
294 		 * We don't free db_argv[0] in "rbt" cache databases
295 		 * as it's a pointer to hmctx
296 		 */
297 		int extra = 0;
298 		if (strcmp(cache->db_type, "rbt") == 0) {
299 			extra = 1;
300 			cache->db_argv[0] = NULL;
301 		}
302 		for (int i = extra; i < cache->db_argc; i++) {
303 			if (cache->db_argv[i] != NULL) {
304 				isc_mem_free(cache->mctx, cache->db_argv[i]);
305 			}
306 		}
307 		isc_mem_put(cache->mctx, cache->db_argv,
308 			    cache->db_argc * sizeof(char *));
309 	}
310 
311 	if (cache->db_type != NULL) {
312 		isc_mem_free(cache->mctx, cache->db_type);
313 	}
314 
315 	if (cache->name != NULL) {
316 		isc_mem_free(cache->mctx, cache->name);
317 	}
318 
319 	if (cache->stats != NULL) {
320 		isc_stats_detach(&cache->stats);
321 	}
322 
323 	if (cache->taskmgr != NULL) {
324 		isc_taskmgr_detach(&cache->taskmgr);
325 	}
326 
327 	isc_mutex_destroy(&cache->lock);
328 
329 	cache->magic = 0;
330 	if (cache->hmctx != NULL) {
331 		isc_mem_detach(&cache->hmctx);
332 	}
333 	if (cache->tmctx != NULL) {
334 		isc_mem_detach(&cache->tmctx);
335 	}
336 	isc_mem_putanddetach(&cache->mctx, cache, sizeof(*cache));
337 }
338 
339 isc_result_t
340 dns_cache_create(isc_mem_t *mctx, isc_taskmgr_t *taskmgr,
341 		 isc_timermgr_t *timermgr, dns_rdataclass_t rdclass,
342 		 const char *cachename, const char *db_type,
343 		 unsigned int db_argc, char **db_argv, dns_cache_t **cachep) {
344 	isc_result_t result;
345 	dns_cache_t *cache;
346 	int i, extra = 0;
347 
348 	REQUIRE(cachep != NULL);
349 	REQUIRE(*cachep == NULL);
350 	REQUIRE(mctx != NULL);
351 	REQUIRE(taskmgr != NULL || strcmp(db_type, "rbt") != 0);
352 	REQUIRE(cachename != NULL);
353 
354 	cache = isc_mem_get(mctx, sizeof(*cache));
355 	*cache = (dns_cache_t){
356 		.db_type = isc_mem_strdup(mctx, db_type),
357 		.rdclass = rdclass,
358 		.db_argc = db_argc,
359 		.name = cachename == NULL ? NULL
360 					  : isc_mem_strdup(mctx, cachename),
361 		.magic = CACHE_MAGIC,
362 	};
363 
364 	isc_mutex_init(&cache->lock);
365 	isc_mem_attach(mctx, &cache->mctx);
366 
367 	if (taskmgr != NULL) {
368 		isc_taskmgr_attach(taskmgr, &cache->taskmgr);
369 	}
370 
371 	isc_refcount_init(&cache->references, 1);
372 	isc_refcount_init(&cache->live_tasks, 1);
373 
374 	result = isc_stats_create(mctx, &cache->stats,
375 				  dns_cachestatscounter_max);
376 	if (result != ISC_R_SUCCESS) {
377 		goto cleanup;
378 	}
379 
380 	/*
381 	 * For databases of type "rbt" we pass hmctx to dns_db_create()
382 	 * via cache->db_argv, followed by the rest of the arguments in
383 	 * db_argv (of which there really shouldn't be any).
384 	 */
385 	if (strcmp(cache->db_type, "rbt") == 0) {
386 		extra = 1;
387 		cache->db_argc++;
388 	}
389 
390 	if (cache->db_argc != 0) {
391 		cache->db_argv = isc_mem_get(mctx,
392 					     cache->db_argc * sizeof(char *));
393 
394 		for (i = 0; i < cache->db_argc; i++) {
395 			cache->db_argv[i] = NULL;
396 		}
397 
398 		for (i = extra; i < cache->db_argc; i++) {
399 			cache->db_argv[i] = isc_mem_strdup(mctx,
400 							   db_argv[i - extra]);
401 		}
402 	}
403 
404 	/*
405 	 * Create the database
406 	 */
407 	result = cache_create_db(cache, &cache->db, &cache->tmctx,
408 				 &cache->hmctx);
409 	if (result != ISC_R_SUCCESS) {
410 		goto cleanup;
411 	}
412 
413 	/*
414 	 * RBT-type cache DB has its own mechanism of cache cleaning and doesn't
415 	 * need the control of the generic cleaner.
416 	 */
417 	if (strcmp(db_type, "rbt") == 0) {
418 		result = cache_cleaner_init(cache, NULL, NULL, &cache->cleaner);
419 	} else {
420 		result = cache_cleaner_init(cache, taskmgr, timermgr,
421 					    &cache->cleaner);
422 	}
423 	if (result != ISC_R_SUCCESS) {
424 		goto cleanup;
425 	}
426 
427 	result = dns_db_setcachestats(cache->db, cache->stats);
428 	if (result != ISC_R_SUCCESS) {
429 		goto cleanup;
430 	}
431 
432 	*cachep = cache;
433 	return (ISC_R_SUCCESS);
434 
435 cleanup:
436 	cache_free(cache);
437 	return (result);
438 }
439 
440 void
441 dns_cache_attach(dns_cache_t *cache, dns_cache_t **targetp) {
442 	REQUIRE(VALID_CACHE(cache));
443 	REQUIRE(targetp != NULL && *targetp == NULL);
444 
445 	isc_refcount_increment(&cache->references);
446 
447 	*targetp = cache;
448 }
449 
450 void
451 dns_cache_detach(dns_cache_t **cachep) {
452 	dns_cache_t *cache;
453 
454 	REQUIRE(cachep != NULL);
455 	cache = *cachep;
456 	*cachep = NULL;
457 	REQUIRE(VALID_CACHE(cache));
458 
459 	if (isc_refcount_decrement(&cache->references) == 1) {
460 		cache->cleaner.overmem = false;
461 
462 		/*
463 		 * If the cleaner task exists, let it free the cache.
464 		 */
465 		if (isc_refcount_decrement(&cache->live_tasks) > 1) {
466 			isc_task_shutdown(cache->cleaner.task);
467 		} else {
468 			cache_free(cache);
469 		}
470 	}
471 }
472 
473 void
474 dns_cache_attachdb(dns_cache_t *cache, dns_db_t **dbp) {
475 	REQUIRE(VALID_CACHE(cache));
476 	REQUIRE(dbp != NULL && *dbp == NULL);
477 	REQUIRE(cache->db != NULL);
478 
479 	LOCK(&cache->lock);
480 	dns_db_attach(cache->db, dbp);
481 	UNLOCK(&cache->lock);
482 }
483 
484 const char *
485 dns_cache_getname(dns_cache_t *cache) {
486 	REQUIRE(VALID_CACHE(cache));
487 
488 	return (cache->name);
489 }
490 
491 /*
492  * Initialize the cache cleaner object at *cleaner.
493  * Space for the object must be allocated by the caller.
494  */
495 
496 static isc_result_t
497 cache_cleaner_init(dns_cache_t *cache, isc_taskmgr_t *taskmgr,
498 		   isc_timermgr_t *timermgr, cache_cleaner_t *cleaner) {
499 	isc_result_t result;
500 
501 	isc_mutex_init(&cleaner->lock);
502 
503 	cleaner->increment = DNS_CACHE_CLEANERINCREMENT;
504 	cleaner->state = cleaner_s_idle;
505 	cleaner->cache = cache;
506 	cleaner->iterator = NULL;
507 	cleaner->overmem = false;
508 	cleaner->replaceiterator = false;
509 
510 	cleaner->task = NULL;
511 	cleaner->resched_event = NULL;
512 	cleaner->overmem_event = NULL;
513 
514 	result = dns_db_createiterator(cleaner->cache->db, false,
515 				       &cleaner->iterator);
516 	if (result != ISC_R_SUCCESS) {
517 		goto cleanup;
518 	}
519 
520 	if (taskmgr != NULL && timermgr != NULL) {
521 		result = isc_task_create(taskmgr, 1, &cleaner->task);
522 		if (result != ISC_R_SUCCESS) {
523 			UNEXPECTED_ERROR("isc_task_create() failed: %s",
524 					 isc_result_totext(result));
525 			result = ISC_R_UNEXPECTED;
526 			goto cleanup;
527 		}
528 		isc_refcount_increment(&cleaner->cache->live_tasks);
529 		isc_task_setname(cleaner->task, "cachecleaner", cleaner);
530 
531 		result = isc_task_onshutdown(cleaner->task,
532 					     cleaner_shutdown_action, cache);
533 		if (result != ISC_R_SUCCESS) {
534 			isc_refcount_decrement0(&cleaner->cache->live_tasks);
535 			UNEXPECTED_ERROR("cache cleaner: "
536 					 "isc_task_onshutdown() failed: %s",
537 					 isc_result_totext(result));
538 			goto cleanup;
539 		}
540 
541 		cleaner->resched_event = isc_event_allocate(
542 			cache->mctx, cleaner, DNS_EVENT_CACHECLEAN,
543 			incremental_cleaning_action, cleaner,
544 			sizeof(isc_event_t));
545 
546 		cleaner->overmem_event = isc_event_allocate(
547 			cache->mctx, cleaner, DNS_EVENT_CACHEOVERMEM,
548 			overmem_cleaning_action, cleaner, sizeof(isc_event_t));
549 	}
550 
551 	return (ISC_R_SUCCESS);
552 
553 cleanup:
554 	if (cleaner->overmem_event != NULL) {
555 		isc_event_free(&cleaner->overmem_event);
556 	}
557 	if (cleaner->resched_event != NULL) {
558 		isc_event_free(&cleaner->resched_event);
559 	}
560 	if (cleaner->task != NULL) {
561 		isc_task_detach(&cleaner->task);
562 	}
563 	if (cleaner->iterator != NULL) {
564 		dns_dbiterator_destroy(&cleaner->iterator);
565 	}
566 	isc_mutex_destroy(&cleaner->lock);
567 
568 	return (result);
569 }
570 
571 static void
572 begin_cleaning(cache_cleaner_t *cleaner) {
573 	isc_result_t result = ISC_R_SUCCESS;
574 
575 	REQUIRE(CLEANER_IDLE(cleaner));
576 
577 	/*
578 	 * Create an iterator, if it does not already exist, and
579 	 * position it at the beginning of the cache.
580 	 */
581 	if (cleaner->iterator == NULL) {
582 		result = dns_db_createiterator(cleaner->cache->db, false,
583 					       &cleaner->iterator);
584 	}
585 	if (result != ISC_R_SUCCESS) {
586 		isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
587 			      DNS_LOGMODULE_CACHE, ISC_LOG_WARNING,
588 			      "cache cleaner could not create "
589 			      "iterator: %s",
590 			      isc_result_totext(result));
591 	} else {
592 		dns_dbiterator_setcleanmode(cleaner->iterator, true);
593 		result = dns_dbiterator_first(cleaner->iterator);
594 	}
595 	if (result != ISC_R_SUCCESS) {
596 		/*
597 		 * If the result is ISC_R_NOMORE, the database is empty,
598 		 * so there is nothing to be cleaned.
599 		 */
600 		if (result != ISC_R_NOMORE && cleaner->iterator != NULL) {
601 			UNEXPECTED_ERROR("cache cleaner: "
602 					 "dns_dbiterator_first() failed: %s",
603 					 isc_result_totext(result));
604 			dns_dbiterator_destroy(&cleaner->iterator);
605 		} else if (cleaner->iterator != NULL) {
606 			result = dns_dbiterator_pause(cleaner->iterator);
607 			RUNTIME_CHECK(result == ISC_R_SUCCESS);
608 		}
609 	} else {
610 		/*
611 		 * Pause the iterator to free its lock.
612 		 */
613 		result = dns_dbiterator_pause(cleaner->iterator);
614 		RUNTIME_CHECK(result == ISC_R_SUCCESS);
615 
616 		isc_log_write(
617 			dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_CACHE,
618 			ISC_LOG_DEBUG(1), "begin cache cleaning, mem inuse %lu",
619 			(unsigned long)isc_mem_inuse(cleaner->cache->mctx));
620 		cleaner->state = cleaner_s_busy;
621 		isc_task_send(cleaner->task, &cleaner->resched_event);
622 	}
623 
624 	return;
625 }
626 
627 static void
628 end_cleaning(cache_cleaner_t *cleaner, isc_event_t *event) {
629 	isc_result_t result;
630 
631 	REQUIRE(CLEANER_BUSY(cleaner));
632 	REQUIRE(event != NULL);
633 
634 	result = dns_dbiterator_pause(cleaner->iterator);
635 	if (result != ISC_R_SUCCESS) {
636 		dns_dbiterator_destroy(&cleaner->iterator);
637 	}
638 
639 	isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_CACHE,
640 		      ISC_LOG_DEBUG(1), "end cache cleaning, mem inuse %lu",
641 		      (unsigned long)isc_mem_inuse(cleaner->cache->mctx));
642 
643 	cleaner->state = cleaner_s_idle;
644 	cleaner->resched_event = event;
645 }
646 
647 /*
648  * This is called when the cache either surpasses its upper limit
649  * or shrinks beyond its lower limit.
650  */
651 static void
652 overmem_cleaning_action(isc_task_t *task, isc_event_t *event) {
653 	cache_cleaner_t *cleaner = event->ev_arg;
654 	bool want_cleaning = false;
655 
656 	UNUSED(task);
657 
658 	INSIST(task == cleaner->task);
659 	INSIST(event->ev_type == DNS_EVENT_CACHEOVERMEM);
660 	INSIST(cleaner->overmem_event == NULL);
661 
662 	isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_CACHE,
663 		      ISC_LOG_DEBUG(1),
664 		      "overmem_cleaning_action called, "
665 		      "overmem = %d, state = %d",
666 		      cleaner->overmem, cleaner->state);
667 
668 	LOCK(&cleaner->lock);
669 
670 	if (cleaner->overmem) {
671 		if (cleaner->state == cleaner_s_idle) {
672 			want_cleaning = true;
673 		}
674 	} else {
675 		if (cleaner->state == cleaner_s_busy) {
676 			/*
677 			 * end_cleaning() can't be called here because
678 			 * then both cleaner->overmem_event and
679 			 * cleaner->resched_event will point to this
680 			 * event.  Set the state to done, and then
681 			 * when the incremental_cleaning_action() event
682 			 * is posted, it will handle the end_cleaning.
683 			 */
684 			cleaner->state = cleaner_s_done;
685 		}
686 	}
687 
688 	cleaner->overmem_event = event;
689 
690 	UNLOCK(&cleaner->lock);
691 
692 	if (want_cleaning) {
693 		begin_cleaning(cleaner);
694 	}
695 }
696 
697 /*
698  * Do incremental cleaning.
699  */
700 static void
701 incremental_cleaning_action(isc_task_t *task, isc_event_t *event) {
702 	cache_cleaner_t *cleaner = event->ev_arg;
703 	isc_result_t result;
704 	unsigned int n_names;
705 	isc_time_t start;
706 
707 	UNUSED(task);
708 
709 	INSIST(task == cleaner->task);
710 	INSIST(event->ev_type == DNS_EVENT_CACHECLEAN);
711 
712 	if (cleaner->state == cleaner_s_done) {
713 		cleaner->state = cleaner_s_busy;
714 		end_cleaning(cleaner, event);
715 		LOCK(&cleaner->cache->lock);
716 		LOCK(&cleaner->lock);
717 		if (cleaner->replaceiterator) {
718 			dns_dbiterator_destroy(&cleaner->iterator);
719 			(void)dns_db_createiterator(cleaner->cache->db, false,
720 						    &cleaner->iterator);
721 			cleaner->replaceiterator = false;
722 		}
723 		UNLOCK(&cleaner->lock);
724 		UNLOCK(&cleaner->cache->lock);
725 		return;
726 	}
727 
728 	INSIST(CLEANER_BUSY(cleaner));
729 
730 	n_names = cleaner->increment;
731 
732 	REQUIRE(DNS_DBITERATOR_VALID(cleaner->iterator));
733 
734 	isc_time_now(&start);
735 	while (n_names-- > 0) {
736 		dns_dbnode_t *node = NULL;
737 
738 		result = dns_dbiterator_current(cleaner->iterator, &node, NULL);
739 		if (result != ISC_R_SUCCESS) {
740 			UNEXPECTED_ERROR("cache cleaner: "
741 					 "dns_dbiterator_current() failed: %s",
742 					 isc_result_totext(result));
743 
744 			end_cleaning(cleaner, event);
745 			return;
746 		}
747 
748 		/*
749 		 * The node was not needed, but was required by
750 		 * dns_dbiterator_current().  Give up its reference.
751 		 */
752 		dns_db_detachnode(cleaner->cache->db, &node);
753 
754 		/*
755 		 * Step to the next node.
756 		 */
757 		result = dns_dbiterator_next(cleaner->iterator);
758 
759 		if (result != ISC_R_SUCCESS) {
760 			/*
761 			 * Either the end was reached (ISC_R_NOMORE) or
762 			 * some error was signaled.  If the cache is still
763 			 * overmem and no error was encountered,
764 			 * keep trying to clean it, otherwise stop cleaning.
765 			 */
766 			if (result != ISC_R_NOMORE) {
767 				UNEXPECTED_ERROR("cache cleaner: "
768 						 "dns_dbiterator_next() "
769 						 "failed: %s",
770 						 isc_result_totext(result));
771 			} else if (cleaner->overmem) {
772 				result =
773 					dns_dbiterator_first(cleaner->iterator);
774 				if (result == ISC_R_SUCCESS) {
775 					isc_log_write(dns_lctx,
776 						      DNS_LOGCATEGORY_DATABASE,
777 						      DNS_LOGMODULE_CACHE,
778 						      ISC_LOG_DEBUG(1),
779 						      "cache cleaner: "
780 						      "still overmem, "
781 						      "reset and try again");
782 					continue;
783 				}
784 			}
785 
786 			end_cleaning(cleaner, event);
787 			return;
788 		}
789 	}
790 
791 	/*
792 	 * We have successfully performed a cleaning increment but have
793 	 * not gone through the entire cache.  Free the iterator locks
794 	 * and reschedule another batch.  If it fails, just try to continue
795 	 * anyway.
796 	 */
797 	result = dns_dbiterator_pause(cleaner->iterator);
798 	RUNTIME_CHECK(result == ISC_R_SUCCESS);
799 
800 	isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_CACHE,
801 		      ISC_LOG_DEBUG(1),
802 		      "cache cleaner: checked %u nodes, "
803 		      "mem inuse %lu, sleeping",
804 		      cleaner->increment,
805 		      (unsigned long)isc_mem_inuse(cleaner->cache->mctx));
806 
807 	isc_task_send(task, &event);
808 	INSIST(CLEANER_BUSY(cleaner));
809 	return;
810 }
811 
812 /*
813  * Do immediate cleaning.
814  */
815 isc_result_t
816 dns_cache_clean(dns_cache_t *cache, isc_stdtime_t now) {
817 	isc_result_t result;
818 	dns_dbiterator_t *iterator = NULL;
819 
820 	REQUIRE(VALID_CACHE(cache));
821 
822 	result = dns_db_createiterator(cache->db, 0, &iterator);
823 	if (result != ISC_R_SUCCESS) {
824 		return (result);
825 	}
826 
827 	result = dns_dbiterator_first(iterator);
828 
829 	while (result == ISC_R_SUCCESS) {
830 		dns_dbnode_t *node = NULL;
831 		result = dns_dbiterator_current(iterator, &node,
832 						(dns_name_t *)NULL);
833 		if (result != ISC_R_SUCCESS) {
834 			break;
835 		}
836 
837 		/*
838 		 * Check TTLs, mark expired rdatasets stale.
839 		 */
840 		result = dns_db_expirenode(cache->db, node, now);
841 		if (result != ISC_R_SUCCESS) {
842 			UNEXPECTED_ERROR("cache cleaner: dns_db_expirenode() "
843 					 "failed: %s",
844 					 isc_result_totext(result));
845 			/*
846 			 * Continue anyway.
847 			 */
848 		}
849 
850 		/*
851 		 * This is where the actual freeing takes place.
852 		 */
853 		dns_db_detachnode(cache->db, &node);
854 
855 		result = dns_dbiterator_next(iterator);
856 	}
857 
858 	dns_dbiterator_destroy(&iterator);
859 
860 	if (result == ISC_R_NOMORE) {
861 		result = ISC_R_SUCCESS;
862 	}
863 
864 	return (result);
865 }
866 
867 static void
868 water(void *arg, int mark) {
869 	dns_cache_t *cache = arg;
870 	bool overmem = (mark == ISC_MEM_HIWATER);
871 
872 	REQUIRE(VALID_CACHE(cache));
873 
874 	LOCK(&cache->cleaner.lock);
875 
876 	if (overmem != cache->cleaner.overmem) {
877 		dns_db_overmem(cache->db, overmem);
878 		cache->cleaner.overmem = overmem;
879 		isc_mem_waterack(cache->tmctx, mark);
880 	}
881 
882 	if (cache->cleaner.overmem_event != NULL) {
883 		isc_task_send(cache->cleaner.task,
884 			      &cache->cleaner.overmem_event);
885 	}
886 
887 	UNLOCK(&cache->cleaner.lock);
888 }
889 
890 static void
891 updatewater(dns_cache_t *cache) {
892 	size_t hi = cache->size - (cache->size >> 3); /* ~ 7/8ths. */
893 	size_t lo = cache->size - (cache->size >> 2); /* ~ 3/4ths. */
894 	if (cache->size == 0U || hi == 0U || lo == 0U) {
895 		isc_mem_clearwater(cache->tmctx);
896 	} else {
897 		isc_mem_setwater(cache->tmctx, water, cache, hi, lo);
898 	}
899 }
900 
901 void
902 dns_cache_setcachesize(dns_cache_t *cache, size_t size) {
903 	REQUIRE(VALID_CACHE(cache));
904 
905 	/*
906 	 * Impose a minimum cache size; pathological things happen if there
907 	 * is too little room.
908 	 */
909 	if (size != 0U && size < DNS_CACHE_MINSIZE) {
910 		size = DNS_CACHE_MINSIZE;
911 	}
912 
913 	LOCK(&cache->lock);
914 	cache->size = size;
915 	updatewater(cache);
916 	UNLOCK(&cache->lock);
917 }
918 
919 size_t
920 dns_cache_getcachesize(dns_cache_t *cache) {
921 	size_t size;
922 
923 	REQUIRE(VALID_CACHE(cache));
924 
925 	LOCK(&cache->lock);
926 	size = cache->size;
927 	UNLOCK(&cache->lock);
928 
929 	return (size);
930 }
931 
932 void
933 dns_cache_setservestalettl(dns_cache_t *cache, dns_ttl_t ttl) {
934 	REQUIRE(VALID_CACHE(cache));
935 
936 	LOCK(&cache->lock);
937 	cache->serve_stale_ttl = ttl;
938 	UNLOCK(&cache->lock);
939 
940 	(void)dns_db_setservestalettl(cache->db, ttl);
941 }
942 
943 dns_ttl_t
944 dns_cache_getservestalettl(dns_cache_t *cache) {
945 	dns_ttl_t ttl;
946 	isc_result_t result;
947 
948 	REQUIRE(VALID_CACHE(cache));
949 
950 	/*
951 	 * Could get it straight from the dns_cache_t, but use db
952 	 * to confirm the value that the db is really using.
953 	 */
954 	result = dns_db_getservestalettl(cache->db, &ttl);
955 	return (result == ISC_R_SUCCESS ? ttl : 0);
956 }
957 
958 void
959 dns_cache_setservestalerefresh(dns_cache_t *cache, dns_ttl_t interval) {
960 	REQUIRE(VALID_CACHE(cache));
961 
962 	LOCK(&cache->lock);
963 	cache->serve_stale_refresh = interval;
964 	UNLOCK(&cache->lock);
965 
966 	(void)dns_db_setservestalerefresh(cache->db, interval);
967 }
968 
969 dns_ttl_t
970 dns_cache_getservestalerefresh(dns_cache_t *cache) {
971 	isc_result_t result;
972 	dns_ttl_t interval;
973 
974 	REQUIRE(VALID_CACHE(cache));
975 
976 	result = dns_db_getservestalerefresh(cache->db, &interval);
977 	return (result == ISC_R_SUCCESS ? interval : 0);
978 }
979 
980 /*
981  * The cleaner task is shutting down; do the necessary cleanup.
982  */
983 static void
984 cleaner_shutdown_action(isc_task_t *task, isc_event_t *event) {
985 	dns_cache_t *cache = event->ev_arg;
986 
987 	UNUSED(task);
988 
989 	INSIST(task == cache->cleaner.task);
990 	INSIST(event->ev_type == ISC_TASKEVENT_SHUTDOWN);
991 
992 	if (CLEANER_BUSY(&cache->cleaner)) {
993 		end_cleaning(&cache->cleaner, event);
994 	} else {
995 		isc_event_free(&event);
996 	}
997 
998 	/* Make sure we don't reschedule anymore. */
999 	(void)isc_task_purge(task, NULL, DNS_EVENT_CACHECLEAN, NULL);
1000 
1001 	isc_refcount_decrementz(&cache->live_tasks);
1002 
1003 	cache_free(cache);
1004 }
1005 
1006 isc_result_t
1007 dns_cache_flush(dns_cache_t *cache) {
1008 	dns_db_t *db = NULL, *olddb;
1009 	dns_dbiterator_t *dbiterator = NULL, *olddbiterator = NULL;
1010 	isc_result_t result;
1011 	isc_mem_t *tmctx = NULL, *oldtmctx;
1012 	isc_mem_t *hmctx = NULL, *oldhmctx;
1013 
1014 	result = cache_create_db(cache, &db, &tmctx, &hmctx);
1015 	if (result != ISC_R_SUCCESS) {
1016 		return (result);
1017 	}
1018 
1019 	result = dns_db_createiterator(db, false, &dbiterator);
1020 	if (result != ISC_R_SUCCESS) {
1021 		dns_db_detach(&db);
1022 		isc_mem_detach(&tmctx);
1023 		isc_mem_detach(&hmctx);
1024 		return (result);
1025 	}
1026 
1027 	LOCK(&cache->lock);
1028 	LOCK(&cache->cleaner.lock);
1029 	isc_mem_clearwater(cache->tmctx);
1030 	if (cache->cleaner.state == cleaner_s_idle) {
1031 		olddbiterator = cache->cleaner.iterator;
1032 		cache->cleaner.iterator = dbiterator;
1033 		dbiterator = NULL;
1034 	} else {
1035 		if (cache->cleaner.state == cleaner_s_busy) {
1036 			cache->cleaner.state = cleaner_s_done;
1037 		}
1038 		cache->cleaner.replaceiterator = true;
1039 	}
1040 	oldhmctx = cache->hmctx;
1041 	cache->hmctx = hmctx;
1042 	oldtmctx = cache->tmctx;
1043 	cache->tmctx = tmctx;
1044 	updatewater(cache);
1045 	olddb = cache->db;
1046 	cache->db = db;
1047 	dns_db_setcachestats(cache->db, cache->stats);
1048 	UNLOCK(&cache->cleaner.lock);
1049 	UNLOCK(&cache->lock);
1050 
1051 	if (dbiterator != NULL) {
1052 		dns_dbiterator_destroy(&dbiterator);
1053 	}
1054 	if (olddbiterator != NULL) {
1055 		dns_dbiterator_destroy(&olddbiterator);
1056 	}
1057 	dns_db_detach(&olddb);
1058 	isc_mem_detach(&oldhmctx);
1059 	isc_mem_detach(&oldtmctx);
1060 
1061 	return (ISC_R_SUCCESS);
1062 }
1063 
1064 static isc_result_t
1065 clearnode(dns_db_t *db, dns_dbnode_t *node) {
1066 	isc_result_t result;
1067 	dns_rdatasetiter_t *iter = NULL;
1068 
1069 	result = dns_db_allrdatasets(db, node, NULL, DNS_DB_STALEOK,
1070 				     (isc_stdtime_t)0, &iter);
1071 	if (result != ISC_R_SUCCESS) {
1072 		return (result);
1073 	}
1074 
1075 	for (result = dns_rdatasetiter_first(iter); result == ISC_R_SUCCESS;
1076 	     result = dns_rdatasetiter_next(iter))
1077 	{
1078 		dns_rdataset_t rdataset;
1079 		dns_rdataset_init(&rdataset);
1080 
1081 		dns_rdatasetiter_current(iter, &rdataset);
1082 		result = dns_db_deleterdataset(db, node, NULL, rdataset.type,
1083 					       rdataset.covers);
1084 		dns_rdataset_disassociate(&rdataset);
1085 		if (result != ISC_R_SUCCESS && result != DNS_R_UNCHANGED) {
1086 			break;
1087 		}
1088 	}
1089 
1090 	if (result == ISC_R_NOMORE) {
1091 		result = ISC_R_SUCCESS;
1092 	}
1093 
1094 	dns_rdatasetiter_destroy(&iter);
1095 	return (result);
1096 }
1097 
1098 static isc_result_t
1099 cleartree(dns_db_t *db, const dns_name_t *name) {
1100 	isc_result_t result, answer = ISC_R_SUCCESS;
1101 	dns_dbiterator_t *iter = NULL;
1102 	dns_dbnode_t *node = NULL, *top = NULL;
1103 	dns_fixedname_t fnodename;
1104 	dns_name_t *nodename;
1105 
1106 	/*
1107 	 * Create the node if it doesn't exist so dns_dbiterator_seek()
1108 	 * can find it.  We will continue even if this fails.
1109 	 */
1110 	(void)dns_db_findnode(db, name, true, &top);
1111 
1112 	nodename = dns_fixedname_initname(&fnodename);
1113 
1114 	result = dns_db_createiterator(db, 0, &iter);
1115 	if (result != ISC_R_SUCCESS) {
1116 		goto cleanup;
1117 	}
1118 
1119 	result = dns_dbiterator_seek(iter, name);
1120 	if (result == DNS_R_PARTIALMATCH) {
1121 		result = dns_dbiterator_next(iter);
1122 	}
1123 	if (result != ISC_R_SUCCESS) {
1124 		goto cleanup;
1125 	}
1126 
1127 	while (result == ISC_R_SUCCESS) {
1128 		result = dns_dbiterator_current(iter, &node, nodename);
1129 		if (result == DNS_R_NEWORIGIN) {
1130 			result = ISC_R_SUCCESS;
1131 		}
1132 		if (result != ISC_R_SUCCESS) {
1133 			goto cleanup;
1134 		}
1135 		/*
1136 		 * Are we done?
1137 		 */
1138 		if (!dns_name_issubdomain(nodename, name)) {
1139 			goto cleanup;
1140 		}
1141 
1142 		/*
1143 		 * If clearnode fails record and move onto the next node.
1144 		 */
1145 		result = clearnode(db, node);
1146 		if (result != ISC_R_SUCCESS && answer == ISC_R_SUCCESS) {
1147 			answer = result;
1148 		}
1149 		dns_db_detachnode(db, &node);
1150 		result = dns_dbiterator_next(iter);
1151 	}
1152 
1153 cleanup:
1154 	if (result == ISC_R_NOMORE || result == ISC_R_NOTFOUND) {
1155 		result = ISC_R_SUCCESS;
1156 	}
1157 	if (result != ISC_R_SUCCESS && answer == ISC_R_SUCCESS) {
1158 		answer = result;
1159 	}
1160 	if (node != NULL) {
1161 		dns_db_detachnode(db, &node);
1162 	}
1163 	if (iter != NULL) {
1164 		dns_dbiterator_destroy(&iter);
1165 	}
1166 	if (top != NULL) {
1167 		dns_db_detachnode(db, &top);
1168 	}
1169 
1170 	return (answer);
1171 }
1172 
1173 isc_result_t
1174 dns_cache_flushname(dns_cache_t *cache, const dns_name_t *name) {
1175 	return (dns_cache_flushnode(cache, name, false));
1176 }
1177 
1178 isc_result_t
1179 dns_cache_flushnode(dns_cache_t *cache, const dns_name_t *name, bool tree) {
1180 	isc_result_t result;
1181 	dns_dbnode_t *node = NULL;
1182 	dns_db_t *db = NULL;
1183 
1184 	if (tree && dns_name_equal(name, dns_rootname)) {
1185 		return (dns_cache_flush(cache));
1186 	}
1187 
1188 	LOCK(&cache->lock);
1189 	if (cache->db != NULL) {
1190 		dns_db_attach(cache->db, &db);
1191 	}
1192 	UNLOCK(&cache->lock);
1193 	if (db == NULL) {
1194 		return (ISC_R_SUCCESS);
1195 	}
1196 
1197 	if (tree) {
1198 		result = cleartree(cache->db, name);
1199 	} else {
1200 		result = dns_db_findnode(cache->db, name, false, &node);
1201 		if (result == ISC_R_NOTFOUND) {
1202 			result = ISC_R_SUCCESS;
1203 			goto cleanup_db;
1204 		}
1205 		if (result != ISC_R_SUCCESS) {
1206 			goto cleanup_db;
1207 		}
1208 		result = clearnode(cache->db, node);
1209 		dns_db_detachnode(cache->db, &node);
1210 	}
1211 
1212 cleanup_db:
1213 	dns_db_detach(&db);
1214 	return (result);
1215 }
1216 
1217 isc_stats_t *
1218 dns_cache_getstats(dns_cache_t *cache) {
1219 	REQUIRE(VALID_CACHE(cache));
1220 	return (cache->stats);
1221 }
1222 
1223 void
1224 dns_cache_updatestats(dns_cache_t *cache, isc_result_t result) {
1225 	REQUIRE(VALID_CACHE(cache));
1226 	if (cache->stats == NULL) {
1227 		return;
1228 	}
1229 
1230 	switch (result) {
1231 	case ISC_R_SUCCESS:
1232 	case DNS_R_NCACHENXDOMAIN:
1233 	case DNS_R_NCACHENXRRSET:
1234 	case DNS_R_CNAME:
1235 	case DNS_R_DNAME:
1236 	case DNS_R_GLUE:
1237 	case DNS_R_ZONECUT:
1238 	case DNS_R_COVERINGNSEC:
1239 		isc_stats_increment(cache->stats,
1240 				    dns_cachestatscounter_queryhits);
1241 		break;
1242 	default:
1243 		isc_stats_increment(cache->stats,
1244 				    dns_cachestatscounter_querymisses);
1245 	}
1246 }
1247 
1248 void
1249 dns_cache_setmaxrrperset(dns_cache_t *cache, uint32_t value) {
1250 	REQUIRE(VALID_CACHE(cache));
1251 
1252 	cache->maxrrperset = value;
1253 	if (cache->db != NULL) {
1254 		dns_db_setmaxrrperset(cache->db, value);
1255 	}
1256 }
1257 
1258 void
1259 dns_cache_setmaxtypepername(dns_cache_t *cache, uint32_t value) {
1260 	REQUIRE(VALID_CACHE(cache));
1261 
1262 	cache->maxtypepername = value;
1263 	if (cache->db != NULL) {
1264 		dns_db_setmaxtypepername(cache->db, value);
1265 	}
1266 }
1267 
1268 /*
1269  * XXX: Much of the following code has been copied in from statschannel.c.
1270  * We should refactor this into a generic function in stats.c that can be
1271  * called from both places.
1272  */
1273 typedef struct cache_dumparg {
1274 	isc_statsformat_t type;
1275 	void *arg;		 /* type dependent argument */
1276 	int ncounters;		 /* for general statistics */
1277 	int *counterindices;	 /* for general statistics */
1278 	uint64_t *countervalues; /* for general statistics */
1279 	isc_result_t result;
1280 } cache_dumparg_t;
1281 
1282 static void
1283 getcounter(isc_statscounter_t counter, uint64_t val, void *arg) {
1284 	cache_dumparg_t *dumparg = arg;
1285 
1286 	REQUIRE(counter < dumparg->ncounters);
1287 	dumparg->countervalues[counter] = val;
1288 }
1289 
1290 static void
1291 getcounters(isc_stats_t *stats, isc_statsformat_t type, int ncounters,
1292 	    int *indices, uint64_t *values) {
1293 	cache_dumparg_t dumparg;
1294 
1295 	memset(values, 0, sizeof(values[0]) * ncounters);
1296 
1297 	dumparg.type = type;
1298 	dumparg.ncounters = ncounters;
1299 	dumparg.counterindices = indices;
1300 	dumparg.countervalues = values;
1301 
1302 	isc_stats_dump(stats, getcounter, &dumparg, ISC_STATSDUMP_VERBOSE);
1303 }
1304 
1305 void
1306 dns_cache_dumpstats(dns_cache_t *cache, FILE *fp) {
1307 	int indices[dns_cachestatscounter_max];
1308 	uint64_t values[dns_cachestatscounter_max];
1309 
1310 	REQUIRE(VALID_CACHE(cache));
1311 
1312 	getcounters(cache->stats, isc_statsformat_file,
1313 		    dns_cachestatscounter_max, indices, values);
1314 
1315 	fprintf(fp, "%20" PRIu64 " %s\n", values[dns_cachestatscounter_hits],
1316 		"cache hits");
1317 	fprintf(fp, "%20" PRIu64 " %s\n", values[dns_cachestatscounter_misses],
1318 		"cache misses");
1319 	fprintf(fp, "%20" PRIu64 " %s\n",
1320 		values[dns_cachestatscounter_queryhits],
1321 		"cache hits (from query)");
1322 	fprintf(fp, "%20" PRIu64 " %s\n",
1323 		values[dns_cachestatscounter_querymisses],
1324 		"cache misses (from query)");
1325 	fprintf(fp, "%20" PRIu64 " %s\n",
1326 		values[dns_cachestatscounter_deletelru],
1327 		"cache records deleted due to memory exhaustion");
1328 	fprintf(fp, "%20" PRIu64 " %s\n",
1329 		values[dns_cachestatscounter_deletettl],
1330 		"cache records deleted due to TTL expiration");
1331 	fprintf(fp, "%20" PRIu64 " %s\n",
1332 		values[dns_cachestatscounter_coveringnsec],
1333 		"covering nsec returned");
1334 	fprintf(fp, "%20u %s\n", dns_db_nodecount(cache->db, dns_dbtree_main),
1335 		"cache database nodes");
1336 	fprintf(fp, "%20u %s\n", dns_db_nodecount(cache->db, dns_dbtree_nsec),
1337 		"cache NSEC auxiliary database nodes");
1338 	fprintf(fp, "%20" PRIu64 " %s\n", (uint64_t)dns_db_hashsize(cache->db),
1339 		"cache database hash buckets");
1340 
1341 	fprintf(fp, "%20" PRIu64 " %s\n", (uint64_t)isc_mem_total(cache->tmctx),
1342 		"cache tree memory total");
1343 	fprintf(fp, "%20" PRIu64 " %s\n", (uint64_t)isc_mem_inuse(cache->tmctx),
1344 		"cache tree memory in use");
1345 	fprintf(fp, "%20" PRIu64 " %s\n",
1346 		(uint64_t)isc_mem_maxinuse(cache->tmctx),
1347 		"cache tree highest memory in use");
1348 
1349 	fprintf(fp, "%20" PRIu64 " %s\n", (uint64_t)isc_mem_total(cache->hmctx),
1350 		"cache heap memory total");
1351 	fprintf(fp, "%20" PRIu64 " %s\n", (uint64_t)isc_mem_inuse(cache->hmctx),
1352 		"cache heap memory in use");
1353 	fprintf(fp, "%20" PRIu64 " %s\n",
1354 		(uint64_t)isc_mem_maxinuse(cache->hmctx),
1355 		"cache heap highest memory in use");
1356 }
1357 
1358 #ifdef HAVE_LIBXML2
1359 #define TRY0(a)                     \
1360 	do {                        \
1361 		xmlrc = (a);        \
1362 		if (xmlrc < 0)      \
1363 			goto error; \
1364 	} while (0)
1365 static int
1366 renderstat(const char *name, uint64_t value, xmlTextWriterPtr writer) {
1367 	int xmlrc;
1368 
1369 	TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "counter"));
1370 	TRY0(xmlTextWriterWriteAttribute(writer, ISC_XMLCHAR "name",
1371 					 ISC_XMLCHAR name));
1372 	TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "", value));
1373 	TRY0(xmlTextWriterEndElement(writer)); /* counter */
1374 
1375 error:
1376 	return (xmlrc);
1377 }
1378 
1379 int
1380 dns_cache_renderxml(dns_cache_t *cache, void *writer0) {
1381 	int indices[dns_cachestatscounter_max];
1382 	uint64_t values[dns_cachestatscounter_max];
1383 	int xmlrc;
1384 	xmlTextWriterPtr writer = (xmlTextWriterPtr)writer0;
1385 
1386 	REQUIRE(VALID_CACHE(cache));
1387 
1388 	getcounters(cache->stats, isc_statsformat_file,
1389 		    dns_cachestatscounter_max, indices, values);
1390 	TRY0(renderstat("CacheHits", values[dns_cachestatscounter_hits],
1391 			writer));
1392 	TRY0(renderstat("CacheMisses", values[dns_cachestatscounter_misses],
1393 			writer));
1394 	TRY0(renderstat("QueryHits", values[dns_cachestatscounter_queryhits],
1395 			writer));
1396 	TRY0(renderstat("QueryMisses",
1397 			values[dns_cachestatscounter_querymisses], writer));
1398 	TRY0(renderstat("DeleteLRU", values[dns_cachestatscounter_deletelru],
1399 			writer));
1400 	TRY0(renderstat("DeleteTTL", values[dns_cachestatscounter_deletettl],
1401 			writer));
1402 	TRY0(renderstat("CoveringNSEC",
1403 			values[dns_cachestatscounter_coveringnsec], writer));
1404 
1405 	TRY0(renderstat("CacheNodes",
1406 			dns_db_nodecount(cache->db, dns_dbtree_main), writer));
1407 	TRY0(renderstat("CacheNSECNodes",
1408 			dns_db_nodecount(cache->db, dns_dbtree_nsec), writer));
1409 	TRY0(renderstat("CacheBuckets", dns_db_hashsize(cache->db), writer));
1410 
1411 	TRY0(renderstat("TreeMemTotal", isc_mem_total(cache->tmctx), writer));
1412 	TRY0(renderstat("TreeMemInUse", isc_mem_inuse(cache->tmctx), writer));
1413 	TRY0(renderstat("TreeMemMax", isc_mem_maxinuse(cache->tmctx), writer));
1414 
1415 	TRY0(renderstat("HeapMemTotal", isc_mem_total(cache->hmctx), writer));
1416 	TRY0(renderstat("HeapMemInUse", isc_mem_inuse(cache->hmctx), writer));
1417 	TRY0(renderstat("HeapMemMax", isc_mem_maxinuse(cache->hmctx), writer));
1418 error:
1419 	return (xmlrc);
1420 }
1421 #endif /* ifdef HAVE_LIBXML2 */
1422 
1423 #ifdef HAVE_JSON_C
1424 #define CHECKMEM(m)                              \
1425 	do {                                     \
1426 		if (m == NULL) {                 \
1427 			result = ISC_R_NOMEMORY; \
1428 			goto error;              \
1429 		}                                \
1430 	} while (0)
1431 
1432 isc_result_t
1433 dns_cache_renderjson(dns_cache_t *cache, void *cstats0) {
1434 	isc_result_t result = ISC_R_SUCCESS;
1435 	int indices[dns_cachestatscounter_max];
1436 	uint64_t values[dns_cachestatscounter_max];
1437 	json_object *obj;
1438 	json_object *cstats = (json_object *)cstats0;
1439 
1440 	REQUIRE(VALID_CACHE(cache));
1441 
1442 	getcounters(cache->stats, isc_statsformat_file,
1443 		    dns_cachestatscounter_max, indices, values);
1444 
1445 	obj = json_object_new_int64(values[dns_cachestatscounter_hits]);
1446 	CHECKMEM(obj);
1447 	json_object_object_add(cstats, "CacheHits", obj);
1448 
1449 	obj = json_object_new_int64(values[dns_cachestatscounter_misses]);
1450 	CHECKMEM(obj);
1451 	json_object_object_add(cstats, "CacheMisses", obj);
1452 
1453 	obj = json_object_new_int64(values[dns_cachestatscounter_queryhits]);
1454 	CHECKMEM(obj);
1455 	json_object_object_add(cstats, "QueryHits", obj);
1456 
1457 	obj = json_object_new_int64(values[dns_cachestatscounter_querymisses]);
1458 	CHECKMEM(obj);
1459 	json_object_object_add(cstats, "QueryMisses", obj);
1460 
1461 	obj = json_object_new_int64(values[dns_cachestatscounter_deletelru]);
1462 	CHECKMEM(obj);
1463 	json_object_object_add(cstats, "DeleteLRU", obj);
1464 
1465 	obj = json_object_new_int64(values[dns_cachestatscounter_deletettl]);
1466 	CHECKMEM(obj);
1467 	json_object_object_add(cstats, "DeleteTTL", obj);
1468 
1469 	obj = json_object_new_int64(values[dns_cachestatscounter_coveringnsec]);
1470 	CHECKMEM(obj);
1471 	json_object_object_add(cstats, "CoveringNSEC", obj);
1472 
1473 	obj = json_object_new_int64(
1474 		dns_db_nodecount(cache->db, dns_dbtree_main));
1475 	CHECKMEM(obj);
1476 	json_object_object_add(cstats, "CacheNodes", obj);
1477 
1478 	obj = json_object_new_int64(
1479 		dns_db_nodecount(cache->db, dns_dbtree_nsec));
1480 	CHECKMEM(obj);
1481 	json_object_object_add(cstats, "CacheNSECNodes", obj);
1482 
1483 	obj = json_object_new_int64(dns_db_hashsize(cache->db));
1484 	CHECKMEM(obj);
1485 	json_object_object_add(cstats, "CacheBuckets", obj);
1486 
1487 	obj = json_object_new_int64(isc_mem_total(cache->tmctx));
1488 	CHECKMEM(obj);
1489 	json_object_object_add(cstats, "TreeMemTotal", obj);
1490 
1491 	obj = json_object_new_int64(isc_mem_inuse(cache->tmctx));
1492 	CHECKMEM(obj);
1493 	json_object_object_add(cstats, "TreeMemInUse", obj);
1494 
1495 	obj = json_object_new_int64(isc_mem_maxinuse(cache->tmctx));
1496 	CHECKMEM(obj);
1497 	json_object_object_add(cstats, "TreeMemMax", obj);
1498 
1499 	obj = json_object_new_int64(isc_mem_total(cache->hmctx));
1500 	CHECKMEM(obj);
1501 	json_object_object_add(cstats, "HeapMemTotal", obj);
1502 
1503 	obj = json_object_new_int64(isc_mem_inuse(cache->hmctx));
1504 	CHECKMEM(obj);
1505 	json_object_object_add(cstats, "HeapMemInUse", obj);
1506 
1507 	obj = json_object_new_int64(isc_mem_maxinuse(cache->hmctx));
1508 	CHECKMEM(obj);
1509 	json_object_object_add(cstats, "HeapMemMax", obj);
1510 
1511 	result = ISC_R_SUCCESS;
1512 error:
1513 	return (result);
1514 }
1515 #endif /* ifdef HAVE_JSON_C */
1516