Coverage Report

Created: 2026-01-10 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/bind9/lib/dns/qp.c
Line
Count
Source
1
/*
2
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3
 *
4
 * SPDX-License-Identifier: MPL-2.0
5
 *
6
 * This Source Code Form is subject to the terms of the Mozilla Public
7
 * License, v. 2.0. If a copy of the MPL was not distributed with this
8
 * file, you can obtain one at https://mozilla.org/MPL/2.0/.
9
 *
10
 * See the COPYRIGHT file distributed with this work for additional
11
 * information regarding copyright ownership.
12
 */
13
14
/*
15
 * For an overview, see doc/design/qp-trie.md
16
 */
17
18
#include <inttypes.h>
19
#include <stdbool.h>
20
#include <stddef.h>
21
#include <stdint.h>
22
#include <string.h>
23
24
#if FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
25
#include <sys/mman.h>
26
#include <unistd.h>
27
#endif
28
29
#include <isc/atomic.h>
30
#include <isc/bit.h>
31
#include <isc/buffer.h>
32
#include <isc/log.h>
33
#include <isc/magic.h>
34
#include <isc/mem.h>
35
#include <isc/mutex.h>
36
#include <isc/refcount.h>
37
#include <isc/result.h>
38
#include <isc/rwlock.h>
39
#include <isc/tid.h>
40
#include <isc/time.h>
41
#include <isc/types.h>
42
#include <isc/urcu.h>
43
#include <isc/util.h>
44
45
#include <dns/fixedname.h>
46
#include <dns/name.h>
47
#include <dns/qp.h>
48
#include <dns/types.h>
49
50
#include "qp_p.h"
51
52
#ifndef DNS_QP_LOG_STATS_LEVEL
53
#define DNS_QP_LOG_STATS_LEVEL 3
54
#endif
55
#ifndef DNS_QP_TRACE
56
#define DNS_QP_TRACE 0
57
#endif
58
59
/*
60
 * very basic garbage collector statistics
61
 *
62
 * XXXFANF for now we're logging GC times, but ideally we should
63
 * accumulate stats more quietly and report via the statschannel
64
 */
65
static atomic_uint_fast64_t compact_time;
66
static atomic_uint_fast64_t recycle_time;
67
static atomic_uint_fast64_t rollback_time;
68
69
/* for LOG_STATS() format strings */
70
#define PRItime " %" PRIu64 " ns "
71
72
#if DNS_QP_LOG_STATS_LEVEL
73
#define LOG_STATS(...)                                            \
74
16.2k
  isc_log_write(DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_QP, \
75
16.2k
          ISC_LOG_DEBUG(DNS_QP_LOG_STATS_LEVEL), __VA_ARGS__)
76
#else
77
#define LOG_STATS(...)
78
#endif
79
80
#if DNS_QP_TRACE
81
/*
82
 * TRACE is generally used in allocation-related functions so it doesn't
83
 * trace very high-frequency ops
84
 */
85
#define TRACE(fmt, ...)                                                        \
86
  do {                                                                   \
87
    if (isc_log_wouldlog(ISC_LOG_DEBUG(7))) {                      \
88
      isc_log_write(DNS_LOGCATEGORY_DATABASE,                \
89
              DNS_LOGMODULE_QP, ISC_LOG_DEBUG(7),      \
90
              "%s:%d:%s(qp %p uctx \"%s\"):t%" PRItid  \
91
              ": " fmt,                                \
92
              __FILE__, __LINE__, __func__, qp,        \
93
              qp ? TRIENAME(qp) : "(null)", isc_tid(), \
94
              ##__VA_ARGS__);                          \
95
    }                                                              \
96
  } while (0)
97
#else
98
#define TRACE(...)
99
#endif
100
101
#if DNS_QPMULTI_TRACE
102
ISC_REFCOUNT_STATIC_TRACE_DECL(dns_qpmulti);
103
#define dns_qpmulti_ref(ptr) dns_qpmulti__ref(ptr, __func__, __FILE__, __LINE__)
104
#define dns_qpmulti_unref(ptr) \
105
  dns_qpmulti__unref(ptr, __func__, __FILE__, __LINE__)
106
#define dns_qpmulti_attach(ptr, ptrp) \
107
  dns_qpmulti__attach(ptr, ptrp, __func__, __FILE__, __LINE__)
108
#define dns_qpmulti_detach(ptrp) \
109
  dns_qpmulti__detach(ptrp, __func__, __FILE__, __LINE__)
110
#else
111
ISC_REFCOUNT_STATIC_DECL(dns_qpmulti);
112
#endif
113
114
/***********************************************************************
115
 *
116
 *  converting DNS names to trie keys
117
 */
118
119
/*
120
 * Convert the namespace value. We map namespace values to numerical
121
 * digits so they can be represented in a single byte in the QP key;
122
 * thus namespace 0 becomes '0', etc.
123
 */
124
45.3M
#define ENCODE_NAMESPACE(c) dns_qp_bits_for_byte[(c) + (uint8_t)'0']
125
#define DECODE_NAMESPACE(c) dns_qp_byte_for_bit[(c)] - (uint8_t)'0'
126
127
25.3k
#define NAME_OFFSET 1
128
129
/*
130
 * Number of distinct byte values, i.e. 256
131
 */
132
5.65k
#define BYTE_VALUES (UINT8_MAX + 1)
133
134
/*
135
 * Lookup table mapping bytes in DNS names to bit positions, used
136
 * by dns_qpkey_fromname() to convert DNS names to qp-trie keys.
137
 *
138
 * Each element holds one or two bit positions, bit_one in the
139
 * lower half and bit_two in the upper half.
140
 *
141
 * For common hostname characters, bit_two is zero (which cannot
142
 * be a valid bit position).
143
 *
144
 * For others, bit_one is the escape bit, and bit_two is the
145
 * position of the character within the escaped range.
146
 */
147
uint16_t dns_qp_bits_for_byte[BYTE_VALUES] = { 0 };
148
149
/*
150
 * And the reverse, mapping bit positions to characters, so the tests
151
 * can print diagnostics involving qp-trie keys.
152
 *
153
 * This table only handles the first bit in an escape sequence; we
154
 * arrange that we can calculate the byte value for both bits by
155
 * adding the the second bit to the first bit's byte value.
156
 */
157
uint8_t dns_qp_byte_for_bit[SHIFT_OFFSET] = { 0 };
158
159
/*
160
 * Fill in the lookup tables at program startup. (It doesn't matter
161
 * when this is initialized relative to other startup code.)
162
 */
163
164
/*
165
 * The bit positions for bytes inside labels have to be between
166
 * SHIFT_BITMAP and SHIFT_OFFSET. (SHIFT_NOBYTE separates labels.)
167
 *
168
 * Each byte range in between common hostname characters has a different
169
 * escape character, to preserve the correct lexical order.
170
 *
171
 * Escaped byte ranges mostly fit into the space available in the
172
 * bitmap, except for those above 'z' (which is mostly bytes with the
173
 * top bit set). So, when we reach the end of the bitmap we roll over
174
 * to the next escape character.
175
 *
176
 * After filling the table we ensure that the bit positions for
177
 * hostname characters and escape characters all fit.
178
 */
179
void
180
22
dns__qp_initialize(void) {
181
  /* zero common character marker not a valid shift position */
182
22
  INSIST(0 < SHIFT_BITMAP);
183
  /* first bit is common byte or escape byte */
184
22
  dns_qpshift_t bit_one = SHIFT_BITMAP;
185
  /* second bit is position in escaped range */
186
22
  dns_qpshift_t bit_two = SHIFT_BITMAP;
187
22
  bool escaping = true;
188
189
5.65k
  for (unsigned int byte = 0; byte < BYTE_VALUES; byte++) {
190
5.63k
    if (qp_common_character(byte)) {
191
902
      escaping = false;
192
902
      bit_one++;
193
902
      dns_qp_byte_for_bit[bit_one] = byte;
194
902
      dns_qp_bits_for_byte[byte] = bit_one;
195
4.73k
    } else if ('A' <= byte && byte <= 'Z') {
196
      /* map upper case to lower case */
197
572
      dns_qpshift_t after_esc = bit_one + 1;
198
572
      dns_qpshift_t skip_punct = 'a' - '_';
199
572
      dns_qpshift_t letter = byte - 'A';
200
572
      dns_qpshift_t bit = after_esc + skip_punct + letter;
201
572
      dns_qp_bits_for_byte[byte] = bit;
202
      /* to simplify reverse conversion */
203
572
      bit_two++;
204
4.15k
    } else {
205
      /* non-hostname characters need to be escaped */
206
4.15k
      if (!escaping || bit_two >= SHIFT_OFFSET) {
207
88
        escaping = true;
208
88
        bit_one++;
209
88
        dns_qp_byte_for_bit[bit_one] = byte;
210
88
        bit_two = SHIFT_BITMAP;
211
88
      }
212
4.15k
      dns_qp_bits_for_byte[byte] = bit_two << 8 | bit_one;
213
4.15k
      bit_two++;
214
4.15k
    }
215
5.63k
  }
216
22
  ENSURE(bit_one < SHIFT_OFFSET);
217
22
}
218
219
void
220
0
dns__qp_shutdown(void) {
221
  /* Nothing */
222
0
}
223
224
/*
225
 * Convert a DNS name into a trie lookup key.
226
 *
227
 * Returns the length of the key.
228
 *
229
 * For performance we get our hands dirty in the guts of the name.
230
 *
231
 * We don't worry about the distinction between absolute and relative
232
 * names. When the trie is only used with absolute names, the first byte
233
 * of the key will always be SHIFT_NOBYTE and it will always be skipped
234
 * when traversing the trie. So keeping the root label costs little, and
235
 * it allows us to support tries of relative names too. In fact absolute
236
 * and relative names can be mixed in the same trie without causing
237
 * confusion, because the presence or absence of the initial
238
 * SHIFT_NOBYTE in the key disambiguates them (exactly like a trailing
239
 * dot in a zone file).
240
 */
241
size_t
242
dns_qpkey_fromname(dns_qpkey_t key, const dns_name_t *name,
243
45.3M
       dns_namespace_t space) {
244
45.3M
  REQUIRE(ISC_MAGIC_VALID(name, DNS_NAME_MAGIC));
245
246
45.3M
  dns_offsets_t offsets;
247
45.3M
  size_t labels = dns_name_offsets(name, offsets);
248
45.3M
  size_t len = 0;
249
250
  /* namespace */
251
45.3M
  key[len++] = ENCODE_NAMESPACE(space);
252
  /* name */
253
45.3M
  if (labels == 0) {
254
0
    key[len] = SHIFT_NOBYTE;
255
0
    return len;
256
0
  }
257
258
45.3M
  size_t label = labels;
259
294M
  while (label-- > 0) {
260
248M
    const uint8_t *ldata = name->ndata + offsets[label];
261
248M
    size_t label_len = *ldata++;
262
799M
    while (label_len-- > 0) {
263
550M
      uint16_t bits = dns_qp_bits_for_byte[*ldata++];
264
550M
      key[len++] = bits & 0xFF; /* bit_one */
265
550M
      if ((bits >> 8) != 0) {   /* escape? */
266
249M
        key[len++] = bits >> 8; /* bit_two */
267
249M
      }
268
550M
    }
269
    /* label terminator */
270
248M
    key[len++] = SHIFT_NOBYTE;
271
248M
  }
272
  /* mark end with a double NOBYTE */
273
45.3M
  key[len] = SHIFT_NOBYTE;
274
45.3M
  ENSURE(len < sizeof(dns_qpkey_t));
275
45.3M
  return len;
276
45.3M
}
277
278
void
279
dns_qpkey_toname(const dns_qpkey_t key, size_t keylen, dns_name_t *name,
280
455
     dns_namespace_t *space) {
281
455
  size_t locs[DNS_NAME_MAXLABELS];
282
455
  size_t loc = 0;
283
455
  size_t offset = 0;
284
285
455
  REQUIRE(ISC_MAGIC_VALID(name, DNS_NAME_MAGIC));
286
455
  REQUIRE(name->buffer != NULL);
287
455
  REQUIRE(keylen > 0);
288
289
455
  dns_name_reset(name);
290
291
455
  SET_IF_NOT_NULL(space, DECODE_NAMESPACE(key[offset++]));
292
293
455
  if (keylen == NAME_OFFSET) {
294
0
    return;
295
0
  }
296
297
  /* Scan the key looking for label boundaries */
298
30.1k
  for (; offset <= keylen; offset++) {
299
30.1k
    INSIST(key[offset] >= SHIFT_NOBYTE &&
300
30.1k
           key[offset] < SHIFT_OFFSET);
301
30.1k
    INSIST(loc < DNS_NAME_MAXLABELS);
302
30.1k
    if (qpkey_bit(key, keylen, offset) == SHIFT_NOBYTE) {
303
5.70k
      if (qpkey_bit(key, keylen, offset + 1) == SHIFT_NOBYTE)
304
455
      {
305
455
        locs[loc] = offset + 1;
306
455
        goto scanned;
307
455
      }
308
5.25k
      locs[loc++] = offset + 1;
309
24.4k
    } else if (offset == NAME_OFFSET) {
310
      /* This happens for a relative name */
311
0
      locs[loc++] = offset;
312
0
    }
313
30.1k
  }
314
455
  UNREACHABLE();
315
455
scanned:
316
317
  /*
318
   * In the key the labels are encoded in reverse order, so
319
   * we step backward through the label boundaries, then forward
320
   * through the labels, to create the DNS wire format data.
321
   */
322
5.70k
  while (loc-- > 0) {
323
5.25k
    uint8_t len = 0, *lenp = NULL;
324
325
    /* Store the location of the length byte */
326
5.25k
    lenp = isc_buffer_used(name->buffer);
327
328
    /* Add a length byte to the name data */
329
5.25k
    isc_buffer_putuint8(name->buffer, 0);
330
5.25k
    name->length++;
331
332
    /* Convert from escaped byte ranges to ASCII */
333
17.8k
    for (offset = locs[loc]; offset < locs[loc + 1] - 1; offset++) {
334
12.5k
      uint8_t bit = qpkey_bit(key, keylen, offset);
335
12.5k
      uint8_t byte = dns_qp_byte_for_bit[bit];
336
12.5k
      if (qp_common_character(byte)) {
337
761
        isc_buffer_putuint8(name->buffer, byte);
338
11.8k
      } else {
339
11.8k
        byte += key[++offset] - SHIFT_BITMAP;
340
11.8k
        isc_buffer_putuint8(name->buffer, byte);
341
11.8k
      }
342
12.5k
      len++;
343
12.5k
    }
344
345
5.25k
    name->length += len;
346
347
    /* Write the final label length to the length byte */
348
5.25k
    *lenp = len;
349
5.25k
  }
350
351
  /* Add a root label for absolute names */
352
455
  if (key[NAME_OFFSET] == SHIFT_NOBYTE) {
353
455
    name->attributes.absolute = true;
354
455
    isc_buffer_putuint8(name->buffer, 0);
355
455
    name->length++;
356
455
  }
357
358
455
  name->ndata = isc_buffer_base(name->buffer);
359
455
}
360
361
/*
362
 * Sentinel value for equal keys
363
 */
364
22.1M
#define QPKEY_EQUAL (~(size_t)0)
365
366
/*
367
 * Compare two keys and return the offset where they differ.
368
 *
369
 * This offset is used to work out where a trie search diverged: when one
370
 * of the keys is in the trie and one is not, the common prefix (up to the
371
 * offset) is the part of the unknown key that exists in the trie. This
372
 * matters for adding new keys or finding neighbours of missing keys.
373
 *
374
 * When the keys are different lengths it is possible (but unwise) for
375
 * the longer key to be the same as the shorter key but with superfluous
376
 * trailing SHIFT_NOBYTE elements. This makes the keys equal for the
377
 * purpose of traversing the trie.
378
 */
379
static size_t
380
qpkey_compare(const dns_qpkey_t key_a, const size_t keylen_a,
381
18.8M
        const dns_qpkey_t key_b, const size_t keylen_b) {
382
18.8M
  size_t keylen = ISC_MAX(keylen_a, keylen_b);
383
441M
  for (size_t offset = 0; offset < keylen; offset++) {
384
438M
    if (qpkey_bit(key_a, keylen_a, offset) !=
385
438M
        qpkey_bit(key_b, keylen_b, offset))
386
15.5M
    {
387
15.5M
      return offset;
388
15.5M
    }
389
438M
  }
390
3.32M
  return QPKEY_EQUAL;
391
18.8M
}
392
393
/***********************************************************************
394
 *
395
 *  allocator wrappers
396
 */
397
398
#if FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
399
400
/*
401
 * Optionally (for debugging) during a copy-on-write transaction, use
402
 * memory protection to ensure that the shared chunks are not modified.
403
 * Once a chunk becomes shared, it remains read-only until it is freed.
404
 * POSIX says we have to use mmap() to get an allocation that we can
405
 * definitely pass to mprotect().
406
 */
407
408
static size_t
409
0
chunk_size_raw(void) {
410
0
  size_t size = (size_t)sysconf(_SC_PAGE_SIZE);
411
0
  return ISC_MAX(size, QP_CHUNK_BYTES);
412
0
}
413
414
static void *
415
709k
chunk_get_raw(dns_qp_t *qp, size_t len) {
416
709k
  if (qp->write_protect) {
417
0
    size_t size = chunk_size_raw();
418
0
    void *ptr = mmap(NULL, size, PROT_READ | PROT_WRITE,
419
0
         MAP_ANON | MAP_PRIVATE, -1, 0);
420
0
    RUNTIME_CHECK(ptr != MAP_FAILED);
421
0
    return ptr;
422
709k
  } else {
423
709k
    return isc_mem_allocate(qp->mctx, len);
424
709k
  }
425
709k
}
426
427
static void
428
709k
chunk_free_raw(dns_qp_t *qp, void *ptr) {
429
709k
  if (qp->write_protect) {
430
0
    RUNTIME_CHECK(munmap(ptr, chunk_size_raw()) == 0);
431
709k
  } else {
432
709k
    isc_mem_free(qp->mctx, ptr);
433
709k
  }
434
709k
}
435
436
static void *
437
0
chunk_shrink_raw(dns_qp_t *qp, void *ptr, size_t bytes) {
438
0
  if (qp->write_protect) {
439
0
    return ptr;
440
0
  } else {
441
0
    return isc_mem_reallocate(qp->mctx, ptr, bytes);
442
0
  }
443
0
}
444
445
static void
446
18.6k
write_protect(dns_qp_t *qp, dns_qpchunk_t chunk) {
447
18.6k
  if (qp->write_protect) {
448
    /* see transaction_open() wrt this special case */
449
0
    if (qp->transaction_mode == QP_WRITE && chunk == qp->bump) {
450
0
      return;
451
0
    }
452
0
    TRACE("chunk %u", chunk);
453
0
    void *ptr = qp->base->ptr[chunk];
454
0
    size_t size = chunk_size_raw();
455
0
    RUNTIME_CHECK(mprotect(ptr, size, PROT_READ) >= 0);
456
0
  }
457
18.6k
}
458
459
#else
460
461
#define chunk_get_raw(qp, size) isc_mem_allocate(qp->mctx, size)
462
#define chunk_free_raw(qp, ptr) isc_mem_free(qp->mctx, ptr)
463
464
#define chunk_shrink_raw(qp, ptr, size) isc_mem_reallocate(qp->mctx, ptr, size)
465
466
#define write_protect(qp, chunk)
467
468
#endif
469
470
/***********************************************************************
471
 *
472
 *  allocator
473
 */
474
475
/*
476
 * When we reuse the bump chunk across multiple write transactions,
477
 * it can have an immutable prefix and a mutable suffix.
478
 */
479
static inline bool
480
106M
cells_immutable(dns_qp_t *qp, dns_qpref_t ref) {
481
106M
  dns_qpchunk_t chunk = ref_chunk(ref);
482
106M
  dns_qpcell_t cell = ref_cell(ref);
483
106M
  if (chunk == qp->bump) {
484
15.9M
    return cell < qp->fender;
485
90.7M
  } else {
486
90.7M
    return qp->usage[chunk].immutable;
487
90.7M
  }
488
106M
}
489
490
/*
491
 * Find the next power that is both bigger than size and prev_capacity,
492
 * but still within the chunk min and max sizes.
493
 */
494
static dns_qpcell_t
495
709k
next_capacity(uint32_t prev_capacity, uint32_t size) {
496
  /*
497
   * Request size was floored at 2 because builtin_clz used to be 0.
498
   * We keep this behavior because stdc_leading_zeros(0) = 32.
499
   */
500
709k
  size = ISC_MAX3(size, prev_capacity, 2U);
501
709k
  uint32_t log2 = 32U - stdc_leading_zeros(size - 1U);
502
503
709k
  return 1U << ISC_CLAMP(log2, QP_CHUNK_LOG_MIN, QP_CHUNK_LOG_MAX);
504
709k
}
505
506
/*
507
 * Create a fresh bump chunk and allocate some twigs from it.
508
 */
509
static dns_qpref_t
510
709k
chunk_alloc(dns_qp_t *qp, dns_qpchunk_t chunk, dns_qpweight_t size) {
511
709k
  INSIST(qp->base->ptr[chunk] == NULL);
512
709k
  INSIST(qp->usage[chunk].used == 0);
513
709k
  INSIST(qp->usage[chunk].free == 0);
514
709k
  INSIST(qp->chunk_capacity <= QP_CHUNK_SIZE);
515
516
709k
  qp->chunk_capacity = next_capacity(qp->chunk_capacity * 2u, size);
517
709k
  qp->base->ptr[chunk] =
518
709k
    chunk_get_raw(qp, qp->chunk_capacity * sizeof(dns_qpnode_t));
519
520
709k
  qp->usage[chunk] = (qp_usage_t){ .exists = true,
521
709k
           .used = size,
522
709k
           .capacity = qp->chunk_capacity };
523
709k
  qp->used_count += size;
524
709k
  qp->bump = chunk;
525
709k
  qp->fender = 0;
526
527
709k
  if (qp->write_protect) {
528
0
    TRACE("chunk %u base %p", chunk, qp->base->ptr[chunk]);
529
0
  }
530
709k
  return make_ref(chunk, 0);
531
709k
}
532
533
/*
534
 * This is used to grow the chunk arrays when they fill up. If the old
535
 * base array is in use by readers, we must make a clone, otherwise we
536
 * can reallocate in place.
537
 *
538
 * The isc_refcount_init() and qpbase_unref() in this function are a pair.
539
 */
540
static void
541
21.2k
realloc_chunk_arrays(dns_qp_t *qp, dns_qpchunk_t newmax) {
542
21.2k
  size_t oldptrs = sizeof(qp->base->ptr[0]) * qp->chunk_max;
543
21.2k
  size_t newptrs = sizeof(qp->base->ptr[0]) * newmax;
544
21.2k
  size_t size = STRUCT_FLEX_SIZE(qp->base, ptr, newmax);
545
546
21.2k
  if (qp->base == NULL || qpbase_unref(qp)) {
547
20.8k
    qp->base = isc_mem_reallocate(qp->mctx, qp->base, size);
548
20.8k
  } else {
549
389
    dns_qpbase_t *oldbase = qp->base;
550
389
    qp->base = isc_mem_allocate(qp->mctx, size);
551
389
    memmove(&qp->base->ptr[0], &oldbase->ptr[0], oldptrs);
552
389
  }
553
21.2k
  memset(&qp->base->ptr[qp->chunk_max], 0, newptrs - oldptrs);
554
21.2k
  isc_refcount_init(&qp->base->refcount, 1);
555
21.2k
  qp->base->magic = QPBASE_MAGIC;
556
557
  /* usage array is exclusive to the writer */
558
21.2k
  size_t oldusage = sizeof(qp->usage[0]) * qp->chunk_max;
559
21.2k
  size_t newusage = sizeof(qp->usage[0]) * newmax;
560
21.2k
  qp->usage = isc_mem_reallocate(qp->mctx, qp->usage, newusage);
561
21.2k
  memset(&qp->usage[qp->chunk_max], 0, newusage - oldusage);
562
563
21.2k
  qp->chunk_max = newmax;
564
565
21.2k
  TRACE("qpbase %p usage %p max %u", qp->base, qp->usage, qp->chunk_max);
566
21.2k
}
567
568
/*
569
 * There was no space in the bump chunk, so find a place to put a fresh
570
 * chunk in the chunk arrays, then allocate some twigs from it.
571
 */
572
static dns_qpref_t
573
709k
alloc_slow(dns_qp_t *qp, dns_qpweight_t size) {
574
709k
  dns_qpchunk_t chunk;
575
576
1.04G
  for (chunk = 0; chunk < qp->chunk_max; chunk++) {
577
1.04G
    if (!qp->usage[chunk].exists) {
578
688k
      return chunk_alloc(qp, chunk, size);
579
688k
    }
580
1.04G
  }
581
21.2k
  ENSURE(chunk == qp->chunk_max);
582
21.2k
  realloc_chunk_arrays(qp, GROWTH_FACTOR(chunk));
583
21.2k
  return chunk_alloc(qp, chunk, size);
584
709k
}
585
586
/*
587
 * Ensure we are using a fresh bump chunk.
588
 */
589
static void
590
21.7k
alloc_reset(dns_qp_t *qp) {
591
21.7k
  (void)alloc_slow(qp, 0);
592
21.7k
}
593
594
/*
595
 * Allocate some fresh twigs. This is the bump allocator fast path.
596
 */
597
static inline dns_qpref_t
598
15.1M
alloc_twigs(dns_qp_t *qp, dns_qpweight_t size) {
599
15.1M
  dns_qpchunk_t chunk = qp->bump;
600
15.1M
  dns_qpcell_t cell = qp->usage[chunk].used;
601
602
15.1M
  if (cell + size <= qp->usage[chunk].capacity) {
603
14.4M
    qp->usage[chunk].used += size;
604
14.4M
    qp->used_count += size;
605
14.4M
    return make_ref(chunk, cell);
606
14.4M
  } else {
607
687k
    return alloc_slow(qp, size);
608
687k
  }
609
15.1M
}
610
611
/*
612
 * Record that some twigs are no longer being used, and if possible
613
 * zero them to ensure that there isn't a spurious double detach when
614
 * the chunk is later recycled.
615
 *
616
 * Returns true if the twigs were immediately destroyed.
617
 *
618
 * NOTE: the caller is responsible for attaching or detaching any
619
 * leaves as required.
620
 */
621
static inline bool
622
12.0M
free_twigs(dns_qp_t *qp, dns_qpref_t twigs, dns_qpweight_t size) {
623
12.0M
  dns_qpchunk_t chunk = ref_chunk(twigs);
624
625
12.0M
  qp->free_count += size;
626
12.0M
  qp->usage[chunk].free += size;
627
12.0M
  ENSURE(qp->free_count <= qp->used_count);
628
12.0M
  ENSURE(qp->usage[chunk].free <= qp->usage[chunk].used);
629
630
12.0M
  if (cells_immutable(qp, twigs)) {
631
34.7k
    qp->hold_count += size;
632
34.7k
    ENSURE(qp->free_count >= qp->hold_count);
633
34.7k
    return false;
634
11.9M
  } else {
635
11.9M
    zero_twigs(ref_ptr(qp, twigs), size);
636
11.9M
    return true;
637
11.9M
  }
638
12.0M
}
639
640
/*
641
 * When some twigs have been copied, and free_twigs() could not
642
 * immediately destroy the old copy, we need to update the refcount
643
 * on any leaves that were duplicated.
644
 */
645
static void
646
16.0k
attach_twigs(dns_qp_t *qp, dns_qpnode_t *twigs, dns_qpweight_t size) {
647
55.2k
  for (dns_qpweight_t pos = 0; pos < size; pos++) {
648
39.2k
    if (node_tag(&twigs[pos]) == LEAF_TAG) {
649
29.1k
      attach_leaf(qp, &twigs[pos]);
650
29.1k
    }
651
39.2k
  }
652
16.0k
}
653
654
/***********************************************************************
655
 *
656
 *  chunk reclamation
657
 */
658
659
/*
660
 * Is any of this chunk still in use?
661
 */
662
static inline dns_qpcell_t
663
7.45M
chunk_usage(dns_qp_t *qp, dns_qpchunk_t chunk) {
664
7.45M
  return qp->usage[chunk].used - qp->usage[chunk].free;
665
7.45M
}
666
667
/*
668
 * We remove each empty chunk from the total counts when the chunk is
669
 * freed, or when it is scheduled for safe memory reclamation. We check
670
 * the chunk's phase to avoid discounting it twice in the latter case.
671
 */
672
static void
673
709k
chunk_discount(dns_qp_t *qp, dns_qpchunk_t chunk) {
674
709k
  if (qp->usage[chunk].discounted) {
675
361
    return;
676
361
  }
677
709k
  INSIST(qp->used_count >= qp->usage[chunk].used);
678
709k
  INSIST(qp->free_count >= qp->usage[chunk].free);
679
709k
  qp->used_count -= qp->usage[chunk].used;
680
709k
  qp->free_count -= qp->usage[chunk].free;
681
709k
  qp->usage[chunk].discounted = true;
682
709k
}
683
684
/*
685
 * When a chunk is being recycled, we need to detach any leaves that
686
 * remain, and free any `base` arrays that have been marked as unused.
687
 */
688
static void
689
709k
chunk_free(dns_qp_t *qp, dns_qpchunk_t chunk) {
690
709k
  if (qp->write_protect) {
691
0
    TRACE("chunk %u base %p", chunk, qp->base->ptr[chunk]);
692
0
  }
693
694
709k
  dns_qpnode_t *n = qp->base->ptr[chunk];
695
85.6M
  for (dns_qpcell_t count = qp->usage[chunk].used; count > 0;
696
84.9M
       count--, n++)
697
84.9M
  {
698
84.9M
    if (node_tag(n) == LEAF_TAG && node_pointer(n) != NULL) {
699
12.5M
      detach_leaf(qp, n);
700
72.4M
    } else if (count > 1 && reader_valid(n)) {
701
37.2k
      dns_qpreader_t qpr;
702
37.2k
      unpack_reader(&qpr, n);
703
      /* pairs with dns_qpmulti_commit() */
704
37.2k
      if (qpbase_unref(&qpr)) {
705
389
        isc_mem_free(qp->mctx, qpr.base);
706
389
      }
707
37.2k
    }
708
84.9M
  }
709
709k
  chunk_discount(qp, chunk);
710
709k
  chunk_free_raw(qp, qp->base->ptr[chunk]);
711
709k
  qp->base->ptr[chunk] = NULL;
712
709k
  qp->usage[chunk] = (qp_usage_t){};
713
709k
}
714
715
/*
716
 * Free any chunks that we can while a trie is in use.
717
 */
718
static void
719
3.79k
recycle(dns_qp_t *qp) {
720
3.79k
  unsigned int nfree = 0;
721
722
3.79k
  isc_nanosecs_t start = isc_time_monotonic();
723
724
1.07M
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
725
1.07M
    if (chunk != qp->bump && chunk_usage(qp, chunk) == 0 &&
726
683k
        qp->usage[chunk].exists && !qp->usage[chunk].immutable)
727
473k
    {
728
473k
      chunk_free(qp, chunk);
729
473k
      nfree++;
730
473k
    }
731
1.07M
  }
732
733
3.79k
  isc_nanosecs_t time = isc_time_monotonic() - start;
734
3.79k
  atomic_fetch_add_relaxed(&recycle_time, time);
735
736
3.79k
  if (nfree > 0) {
737
3.79k
    LOG_STATS("qp recycle" PRItime "free %u chunks", time, nfree);
738
3.79k
    LOG_STATS("qp recycle leaf %u live %u used %u free %u hold %u",
739
3.79k
        qp->leaf_count, qp->used_count - qp->free_count,
740
3.79k
        qp->used_count, qp->free_count, qp->hold_count);
741
3.79k
  }
742
3.79k
}
743
744
/*
745
 * asynchronous cleanup
746
 */
747
static void
748
361
reclaim_chunks_cb(struct rcu_head *arg) {
749
361
  qp_rcuctx_t *rcuctx = caa_container_of(arg, qp_rcuctx_t, rcu_head);
750
361
  REQUIRE(QPRCU_VALID(rcuctx));
751
361
  dns_qpmulti_t *multi = rcuctx->multi;
752
361
  REQUIRE(QPMULTI_VALID(multi));
753
754
361
  LOCK(&multi->mutex);
755
361
  dns_qp_t *qp = &multi->writer;
756
757
  /*
758
   * If chunk_max is zero, chunks have already been freed.
759
   */
760
361
  if (qp->chunk_max != 0) {
761
361
    unsigned int nfree = 0;
762
361
    isc_nanosecs_t start = isc_time_monotonic();
763
764
361
    INSIST(QP_VALID(qp));
765
766
722
    for (unsigned int i = 0; i < rcuctx->count; i++) {
767
361
      dns_qpchunk_t chunk = rcuctx->chunk[i];
768
361
      if (qp->usage[chunk].snapshot) {
769
        /* clean up when snapshot is destroyed */
770
0
        qp->usage[chunk].snapfree = true;
771
361
      } else {
772
361
        chunk_free(qp, chunk);
773
361
        nfree++;
774
361
      }
775
361
    }
776
777
361
    isc_nanosecs_t time = isc_time_monotonic() - start;
778
361
    recycle_time += time;
779
780
361
    if (nfree > 0) {
781
361
      LOG_STATS("qp reclaim" PRItime "free %u chunks", time,
782
361
          nfree);
783
361
      LOG_STATS(
784
361
        "qp reclaim leaf %u live %u used %u free %u "
785
361
        "hold %u",
786
361
        qp->leaf_count, qp->used_count - qp->free_count,
787
361
        qp->used_count, qp->free_count, qp->hold_count);
788
361
    }
789
361
  }
790
791
361
  UNLOCK(&multi->mutex);
792
793
361
  dns_qpmulti_detach(&multi);
794
361
  isc_mem_putanddetach(&rcuctx->mctx, rcuctx,
795
361
           STRUCT_FLEX_SIZE(rcuctx, chunk, rcuctx->count));
796
361
}
797
798
/*
799
 * At the end of a transaction, schedule empty but immutable chunks
800
 * for reclamation later.
801
 */
802
static void
803
37.2k
reclaim_chunks(dns_qpmulti_t *multi) {
804
37.2k
  dns_qp_t *qp = &multi->writer;
805
806
37.2k
  unsigned int count = 0;
807
423k
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
808
386k
    if (chunk != qp->bump && chunk_usage(qp, chunk) == 0 &&
809
139k
        qp->usage[chunk].exists && qp->usage[chunk].immutable &&
810
361
        !qp->usage[chunk].discounted)
811
361
    {
812
361
      count++;
813
361
    }
814
386k
  }
815
816
37.2k
  if (count == 0) {
817
36.8k
    return;
818
36.8k
  }
819
820
361
  qp_rcuctx_t *rcuctx =
821
361
    isc_mem_get(qp->mctx, STRUCT_FLEX_SIZE(rcuctx, chunk, count));
822
361
  *rcuctx = (qp_rcuctx_t){
823
361
    .magic = QPRCU_MAGIC,
824
361
    .multi = multi,
825
361
    .count = count,
826
361
  };
827
361
  isc_mem_attach(qp->mctx, &rcuctx->mctx);
828
829
361
  unsigned int i = 0;
830
294k
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
831
294k
    if (chunk != qp->bump && chunk_usage(qp, chunk) == 0 &&
832
97.6k
        qp->usage[chunk].exists && qp->usage[chunk].immutable &&
833
361
        !qp->usage[chunk].discounted)
834
361
    {
835
361
      rcuctx->chunk[i++] = chunk;
836
361
      chunk_discount(qp, chunk);
837
361
    }
838
294k
  }
839
840
  /*
841
   * Reference the qpmulti object to keep it from being
842
   * freed until reclaim_chunks_cb() runs.
843
   */
844
361
  dns_qpmulti_ref(multi);
845
361
  call_rcu(&rcuctx->rcu_head, reclaim_chunks_cb);
846
847
361
  LOG_STATS("qp will reclaim %u chunks", count);
848
361
}
849
850
/*
851
 * When a snapshot is destroyed, clean up chunks that need free()ing
852
 * and are not used by any remaining snapshots.
853
 */
854
static void
855
0
marksweep_chunks(dns_qpmulti_t *multi) {
856
0
  unsigned int nfree = 0;
857
858
0
  isc_nanosecs_t start = isc_time_monotonic();
859
860
0
  dns_qp_t *qpw = &multi->writer;
861
862
0
  ISC_LIST_FOREACH(multi->snapshots, qps, link) {
863
0
    for (dns_qpchunk_t chunk = 0; chunk < qps->chunk_max; chunk++) {
864
0
      if (qps->base->ptr[chunk] != NULL) {
865
0
        INSIST(qps->base->ptr[chunk] ==
866
0
               qpw->base->ptr[chunk]);
867
0
        qpw->usage[chunk].snapmark = true;
868
0
      }
869
0
    }
870
0
  }
871
872
0
  for (dns_qpchunk_t chunk = 0; chunk < qpw->chunk_max; chunk++) {
873
0
    qpw->usage[chunk].snapshot = qpw->usage[chunk].snapmark;
874
0
    qpw->usage[chunk].snapmark = false;
875
0
    if (qpw->usage[chunk].snapfree && !qpw->usage[chunk].snapshot) {
876
0
      chunk_free(qpw, chunk);
877
0
      nfree++;
878
0
    }
879
0
  }
880
881
0
  isc_nanosecs_t time = isc_time_monotonic() - start;
882
0
  recycle_time += time;
883
884
0
  if (nfree > 0) {
885
0
    LOG_STATS("qp marksweep" PRItime "free %u chunks", time, nfree);
886
0
    LOG_STATS(
887
0
      "qp marksweep leaf %u live %u used %u free %u hold %u",
888
0
      qpw->leaf_count, qpw->used_count - qpw->free_count,
889
0
      qpw->used_count, qpw->free_count, qpw->hold_count);
890
0
  }
891
0
}
892
893
/***********************************************************************
894
 *
895
 *  garbage collector
896
 */
897
898
/*
899
 * Move a branch node's twigs to the `bump` chunk, for copy-on-write
900
 * or for garbage collection. We don't update the node in place
901
 * because `compact_recursive()` does not ensure the node itself is
902
 * mutable until after it discovers evacuation was necessary.
903
 *
904
 * If free_twigs() could not immediately destroy the old twigs, we have
905
 * to re-attach to any leaves.
906
 */
907
static dns_qpref_t
908
1.86M
evacuate(dns_qp_t *qp, dns_qpnode_t *n) {
909
1.86M
  dns_qpweight_t size = branch_twigs_size(n);
910
1.86M
  dns_qpref_t old_ref = branch_twigs_ref(n);
911
1.86M
  dns_qpref_t new_ref = alloc_twigs(qp, size);
912
1.86M
  dns_qpnode_t *old_twigs = ref_ptr(qp, old_ref);
913
1.86M
  dns_qpnode_t *new_twigs = ref_ptr(qp, new_ref);
914
915
1.86M
  move_twigs(new_twigs, old_twigs, size);
916
1.86M
  if (!free_twigs(qp, old_ref, size)) {
917
15.5k
    attach_twigs(qp, new_twigs, size);
918
15.5k
  }
919
920
1.86M
  return new_ref;
921
1.86M
}
922
923
/*
924
 * Immutable nodes need copy-on-write. As we walk down the trie finding the
925
 * right place to modify, make_root_mutable() and make_twigs_mutable()
926
 * are called to ensure that immutable nodes on the path from the root are
927
 * copied to a mutable chunk.
928
 */
929
930
static inline dns_qpnode_t *
931
13.2M
make_root_mutable(dns_qp_t *qp) {
932
13.2M
  if (cells_immutable(qp, qp->root_ref)) {
933
6.36k
    qp->root_ref = evacuate(qp, MOVABLE_ROOT(qp));
934
6.36k
  }
935
13.2M
  return ref_ptr(qp, qp->root_ref);
936
13.2M
}
937
938
static inline void
939
75.7M
make_twigs_mutable(dns_qp_t *qp, dns_qpnode_t *n) {
940
75.7M
  if (cells_immutable(qp, branch_twigs_ref(n))) {
941
8.14k
    *n = make_node(branch_index(n), evacuate(qp, n));
942
8.14k
  }
943
75.7M
}
944
945
/*
946
 * Compact the trie by traversing the whole thing recursively, copying
947
 * bottom-up as required. The aim is to avoid evacuation as much as
948
 * possible, but when parts of the trie are immutable, we need to evacuate
949
 * the paths from the root to the parts of the trie that occupy
950
 * fragmented chunks.
951
 *
952
 * Without the QP_MIN_USED check, the algorithm will leave the trie
953
 * unchanged. If the children are all leaves, the loop changes nothing,
954
 * so we will return this node's original ref. If all of the children
955
 * that are branches did not need moving, again, the loop changes
956
 * nothing. So the evacuation check is the only place that the
957
 * algorithm introduces ref changes, that then bubble up towards the
958
 * root through the logic inside the loop.
959
 */
960
static dns_qpref_t
961
5.74M
compact_recursive(dns_qp_t *qp, dns_qpnode_t *parent) {
962
5.74M
  dns_qpweight_t size = branch_twigs_size(parent);
963
5.74M
  dns_qpref_t twigs_ref = branch_twigs_ref(parent);
964
5.74M
  dns_qpchunk_t chunk = ref_chunk(twigs_ref);
965
966
5.74M
  if (qp->compact_all ||
967
5.74M
      (chunk != qp->bump && chunk_usage(qp, chunk) < QP_MIN_USED))
968
1.84M
  {
969
1.84M
    twigs_ref = evacuate(qp, parent);
970
1.84M
  }
971
5.74M
  bool immutable = cells_immutable(qp, twigs_ref);
972
52.5M
  for (dns_qpweight_t pos = 0; pos < size; pos++) {
973
46.7M
    dns_qpnode_t *child = ref_ptr(qp, twigs_ref) + pos;
974
46.7M
    if (!is_branch(child)) {
975
41.0M
      continue;
976
41.0M
    }
977
5.73M
    dns_qpref_t old_grandtwigs = branch_twigs_ref(child);
978
5.73M
    dns_qpref_t new_grandtwigs = compact_recursive(qp, child);
979
5.73M
    if (old_grandtwigs == new_grandtwigs) {
980
3.89M
      continue;
981
3.89M
    }
982
1.84M
    if (immutable) {
983
82
      twigs_ref = evacuate(qp, parent);
984
      /* the twigs have moved */
985
82
      child = ref_ptr(qp, twigs_ref) + pos;
986
82
      immutable = false;
987
82
    }
988
1.84M
    *child = make_node(branch_index(child), new_grandtwigs);
989
1.84M
  }
990
5.74M
  return twigs_ref;
991
5.74M
}
992
993
static void
994
3.79k
compact(dns_qp_t *qp) {
995
3.79k
  LOG_STATS("qp compact before leaf %u live %u used %u free %u hold %u",
996
3.79k
      qp->leaf_count, qp->used_count - qp->free_count,
997
3.79k
      qp->used_count, qp->free_count, qp->hold_count);
998
999
3.79k
  isc_nanosecs_t start = isc_time_monotonic();
1000
1001
3.79k
  if (qp->usage[qp->bump].free > QP_MAX_FREE) {
1002
3.02k
    alloc_reset(qp);
1003
3.02k
  }
1004
1005
3.79k
  if (qp->leaf_count > 0) {
1006
3.79k
    qp->root_ref = compact_recursive(qp, MOVABLE_ROOT(qp));
1007
3.79k
  }
1008
3.79k
  qp->compact_all = false;
1009
1010
3.79k
  isc_nanosecs_t time = isc_time_monotonic() - start;
1011
3.79k
  atomic_fetch_add_relaxed(&compact_time, time);
1012
1013
3.79k
  LOG_STATS("qp compact" PRItime
1014
3.79k
      "leaf %u live %u used %u free %u hold %u",
1015
3.79k
      time, qp->leaf_count, qp->used_count - qp->free_count,
1016
3.79k
      qp->used_count, qp->free_count, qp->hold_count);
1017
3.79k
}
1018
1019
void
1020
18.6k
dns_qp_compact(dns_qp_t *qp, dns_qpgc_t mode) {
1021
18.6k
  REQUIRE(QP_VALID(qp));
1022
18.6k
  if (mode == DNS_QPGC_MAYBE && !QP_NEEDGC(qp)) {
1023
18.5k
    return;
1024
18.5k
  }
1025
42
  if (mode == DNS_QPGC_ALL) {
1026
0
    alloc_reset(qp);
1027
0
    qp->compact_all = true;
1028
0
  }
1029
42
  compact(qp);
1030
42
  recycle(qp);
1031
42
}
1032
1033
/*
1034
 * Free some twigs and (if they were destroyed immediately so that the
1035
 * result from QP_MAX_GARBAGE can change) compact the trie if necessary.
1036
 *
1037
 * This is called by the trie modification API entry points. The
1038
 * free_twigs() function requires the caller to attach or detach any
1039
 * leaves as necessary. Callers of squash_twigs() satisfy this
1040
 * requirement by calling make_twigs_mutable().
1041
 *
1042
 * Aside: In typical garbage collectors, compaction is triggered when
1043
 * the allocator runs out of space. But that is because typical garbage
1044
 * collectors do not know how much memory can be recovered, so they must
1045
 * find out by scanning the heap. The qp-trie code was originally
1046
 * designed to use malloc() and free(), so it has more information about
1047
 * when garbage collection might be worthwhile. Hence we can trigger
1048
 * collection when garbage passes a threshold.
1049
 *
1050
 * XXXFANF: If we need to avoid latency outliers caused by compaction in
1051
 * write transactions, we can check qp->transaction_mode here.
1052
 */
1053
static inline bool
1054
9.44M
squash_twigs(dns_qp_t *qp, dns_qpref_t twigs, dns_qpweight_t size) {
1055
9.44M
  bool destroyed = free_twigs(qp, twigs, size);
1056
9.44M
  if (destroyed && QP_AUTOGC(qp)) {
1057
3.74k
    compact(qp);
1058
3.74k
    recycle(qp);
1059
    /*
1060
     * This shouldn't happen if the garbage collector is
1061
     * working correctly. We can recover at the cost of some
1062
     * time and space, but recovery should be cheaper than
1063
     * letting compact+recycle fail repeatedly.
1064
     */
1065
3.74k
    if (QP_AUTOGC(qp)) {
1066
0
      isc_log_write(DNS_LOGCATEGORY_DATABASE,
1067
0
              DNS_LOGMODULE_QP, ISC_LOG_NOTICE,
1068
0
              "qp %p uctx \"%s\" compact/recycle "
1069
0
              "failed to recover any space, "
1070
0
              "scheduling a full compaction",
1071
0
              qp, TRIENAME(qp));
1072
0
      qp->compact_all = true;
1073
0
    }
1074
3.74k
  }
1075
9.44M
  return destroyed;
1076
9.44M
}
1077
1078
/***********************************************************************
1079
 *
1080
 *  public accessors for memory management internals
1081
 */
1082
1083
dns_qp_memusage_t
1084
2
dns_qp_memusage(dns_qp_t *qp) {
1085
2
  REQUIRE(QP_VALID(qp));
1086
1087
2
  dns_qp_memusage_t memusage = {
1088
2
    .uctx = qp->uctx,
1089
2
    .leaves = qp->leaf_count,
1090
2
    .live = qp->used_count - qp->free_count,
1091
2
    .used = qp->used_count,
1092
2
    .hold = qp->hold_count,
1093
2
    .free = qp->free_count,
1094
2
    .node_size = sizeof(dns_qpnode_t),
1095
2
    .fragmented = QP_NEEDGC(qp),
1096
2
  };
1097
1098
2
  size_t chunk_usage_bytes = 0;
1099
6
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
1100
4
    if (qp->base->ptr[chunk] != NULL) {
1101
2
      chunk_usage_bytes += qp->usage[chunk].capacity;
1102
2
      memusage.chunk_count += 1;
1103
2
    }
1104
4
  }
1105
1106
  /*
1107
   * XXXFANF does not subtract chunks that have been shrunk,
1108
   * and does not count unreclaimed dns_qpbase_t objects
1109
   */
1110
2
  memusage.bytes = chunk_usage_bytes +
1111
2
       qp->chunk_max * sizeof(qp->base->ptr[0]) +
1112
2
       qp->chunk_max * sizeof(qp->usage[0]);
1113
1114
2
  return memusage;
1115
2
}
1116
1117
dns_qp_memusage_t
1118
2
dns_qpmulti_memusage(dns_qpmulti_t *multi) {
1119
2
  REQUIRE(QPMULTI_VALID(multi));
1120
2
  LOCK(&multi->mutex);
1121
1122
2
  dns_qp_t *qp = &multi->writer;
1123
2
  INSIST(QP_VALID(qp));
1124
1125
2
  dns_qp_memusage_t memusage = dns_qp_memusage(qp);
1126
1127
2
  if (qp->transaction_mode == QP_UPDATE && qp->usage != NULL) {
1128
0
    memusage.bytes -= qp->usage[qp->bump].capacity;
1129
0
    memusage.bytes += qp->usage[qp->bump].used *
1130
0
          sizeof(dns_qpnode_t);
1131
0
  }
1132
1133
2
  UNLOCK(&multi->mutex);
1134
2
  return memusage;
1135
2
}
1136
1137
void
1138
dns_qp_gctime(isc_nanosecs_t *compact_p, isc_nanosecs_t *recycle_p,
1139
0
        isc_nanosecs_t *rollback_p) {
1140
0
  *compact_p = atomic_load_relaxed(&compact_time);
1141
0
  *recycle_p = atomic_load_relaxed(&recycle_time);
1142
0
  *rollback_p = atomic_load_relaxed(&rollback_time);
1143
0
}
1144
1145
/***********************************************************************
1146
 *
1147
 *  read-write transactions
1148
 */
1149
1150
static dns_qp_t *
1151
37.2k
transaction_open(dns_qpmulti_t *multi, dns_qp_t **qptp) {
1152
37.2k
  REQUIRE(QPMULTI_VALID(multi));
1153
37.2k
  REQUIRE(qptp != NULL && *qptp == NULL);
1154
1155
37.2k
  LOCK(&multi->mutex);
1156
1157
37.2k
  dns_qp_t *qp = &multi->writer;
1158
37.2k
  INSIST(QP_VALID(qp));
1159
1160
  /*
1161
   * Mark existing chunks as immutable.
1162
   *
1163
   * Aside: The bump chunk is special: in a series of write
1164
   * transactions the bump chunk is reused; the first part (up
1165
   * to fender) is immutable, the rest mutable. But we set its
1166
   * immutable flag so that when the bump chunk fills up, the
1167
   * first part continues to be treated as immutable. (And the
1168
   * rest of the chunk too, but that's OK.)
1169
   */
1170
74.4k
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
1171
37.2k
    if (qp->usage[chunk].exists) {
1172
18.6k
      qp->usage[chunk].immutable = true;
1173
18.6k
      write_protect(qp, chunk);
1174
18.6k
    }
1175
37.2k
  }
1176
1177
  /*
1178
   * Ensure QP_AUTOGC() ignores free space in immutable chunks.
1179
   */
1180
37.2k
  qp->hold_count = qp->free_count;
1181
1182
37.2k
  *qptp = qp;
1183
37.2k
  return qp;
1184
37.2k
}
1185
1186
/*
1187
 * a write is light
1188
 *
1189
 * We need to ensure we allocate from a fresh chunk if the last transaction
1190
 * shrunk the bump chunk; but usually in a sequence of write transactions
1191
 * we just put `fender` at the point where we started this generation.
1192
 *
1193
 * (Aside: Instead of keeping the previous transaction's mode, I
1194
 * considered forcing allocation into the slow path by fiddling with
1195
 * the bump chunk's usage counters. But that is troublesome because
1196
 * `chunk_free()` needs to know how much of the chunk to scan.)
1197
 */
1198
void
1199
37.2k
dns_qpmulti_write(dns_qpmulti_t *multi, dns_qp_t **qptp) {
1200
37.2k
  dns_qp_t *qp = transaction_open(multi, qptp);
1201
37.2k
  TRACE("");
1202
1203
37.2k
  if (qp->transaction_mode == QP_WRITE) {
1204
18.6k
    qp->fender = qp->usage[qp->bump].used;
1205
18.6k
  } else {
1206
18.6k
    alloc_reset(qp);
1207
18.6k
  }
1208
37.2k
  qp->transaction_mode = QP_WRITE;
1209
37.2k
}
1210
1211
/*
1212
 * an update is heavier
1213
 *
1214
 * We always reset the allocator to the start of a fresh chunk,
1215
 * because the previous transaction was probably an update that shrunk
1216
 * the bump chunk. It simplifies rollback because `fender` is always zero.
1217
 *
1218
 * To rollback a transaction, we need to reset all the allocation
1219
 * counters to their previous state, in particular we need to un-free
1220
 * any nodes that were copied to make them mutable. This means we need
1221
 * to make a copy of basically the whole `dns_qp_t writer`: everything
1222
 * but the chunks holding the trie nodes.
1223
 *
1224
 * We do most of the transaction setup before creating the rollback
1225
 * state so that after rollback we have a correct idea of which chunks
1226
 * are immutable, and so we have the correct transaction mode to make
1227
 * the next transaction allocate a new bump chunk. The exception is
1228
 * resetting the allocator, which we do after creating the rollback
1229
 * state; if this transaction is rolled back then the next transaction
1230
 * will start from the rollback state and also reset the allocator as
1231
 * one of its first actions.
1232
 */
1233
void
1234
0
dns_qpmulti_update(dns_qpmulti_t *multi, dns_qp_t **qptp) {
1235
0
  dns_qp_t *qp = transaction_open(multi, qptp);
1236
0
  TRACE("");
1237
1238
0
  qp->transaction_mode = QP_UPDATE;
1239
1240
0
  dns_qp_t *rollback = isc_mem_allocate(qp->mctx, sizeof(*rollback));
1241
0
  memmove(rollback, qp, sizeof(*rollback));
1242
  /* can be uninitialized on the first transaction */
1243
0
  if (rollback->base != NULL) {
1244
0
    INSIST(QPBASE_VALID(rollback->base));
1245
0
    INSIST(qp->usage != NULL && qp->chunk_max > 0);
1246
    /* paired with either _commit() or _rollback() */
1247
0
    isc_refcount_increment(&rollback->base->refcount);
1248
0
    size_t usage_bytes = sizeof(qp->usage[0]) * qp->chunk_max;
1249
0
    rollback->usage = isc_mem_allocate(qp->mctx, usage_bytes);
1250
0
    memmove(rollback->usage, qp->usage, usage_bytes);
1251
0
  }
1252
0
  INSIST(multi->rollback == NULL);
1253
0
  multi->rollback = rollback;
1254
1255
0
  alloc_reset(qp);
1256
0
}
1257
1258
void
1259
37.2k
dns_qpmulti_commit(dns_qpmulti_t *multi, dns_qp_t **qptp) {
1260
37.2k
  REQUIRE(QPMULTI_VALID(multi));
1261
37.2k
  REQUIRE(qptp != NULL && *qptp == &multi->writer);
1262
37.2k
  REQUIRE(multi->writer.transaction_mode == QP_WRITE ||
1263
37.2k
    multi->writer.transaction_mode == QP_UPDATE);
1264
1265
37.2k
  dns_qp_t *qp = *qptp;
1266
37.2k
  TRACE("");
1267
1268
37.2k
  if (qp->transaction_mode == QP_UPDATE) {
1269
0
    INSIST(multi->rollback != NULL);
1270
    /* paired with dns_qpmulti_update() */
1271
0
    if (qpbase_unref(multi->rollback)) {
1272
0
      isc_mem_free(qp->mctx, multi->rollback->base);
1273
0
    }
1274
0
    if (multi->rollback->usage != NULL) {
1275
0
      isc_mem_free(qp->mctx, multi->rollback->usage);
1276
0
    }
1277
0
    isc_mem_free(qp->mctx, multi->rollback);
1278
0
  }
1279
37.2k
  INSIST(multi->rollback == NULL);
1280
1281
  /* not the first commit? */
1282
37.2k
  if (multi->reader_ref != INVALID_REF) {
1283
18.6k
    INSIST(cells_immutable(qp, multi->reader_ref));
1284
18.6k
    free_twigs(qp, multi->reader_ref, READER_SIZE);
1285
18.6k
  }
1286
1287
37.2k
  if (qp->transaction_mode == QP_UPDATE) {
1288
    /* minimize memory overhead */
1289
0
    compact(qp);
1290
0
    multi->reader_ref = alloc_twigs(qp, READER_SIZE);
1291
0
    qp->base->ptr[qp->bump] = chunk_shrink_raw(
1292
0
      qp, qp->base->ptr[qp->bump],
1293
0
      qp->usage[qp->bump].used * sizeof(dns_qpnode_t));
1294
37.2k
  } else {
1295
37.2k
    multi->reader_ref = alloc_twigs(qp, READER_SIZE);
1296
37.2k
  }
1297
1298
  /* anchor a new version of the trie */
1299
37.2k
  dns_qpnode_t *reader = ref_ptr(qp, multi->reader_ref);
1300
37.2k
  make_reader(reader, multi);
1301
  /* paired with chunk_free() */
1302
37.2k
  isc_refcount_increment(&qp->base->refcount);
1303
1304
37.2k
  rcu_assign_pointer(multi->reader, reader); /* COMMIT */
1305
1306
  /* clean up what we can right now */
1307
37.2k
  if (qp->transaction_mode == QP_UPDATE || QP_NEEDGC(qp)) {
1308
5
    recycle(qp);
1309
5
  }
1310
1311
  /* schedule the rest for later */
1312
37.2k
  reclaim_chunks(multi);
1313
1314
37.2k
  *qptp = NULL;
1315
37.2k
  UNLOCK(&multi->mutex);
1316
37.2k
}
1317
1318
/*
1319
 * Throw away everything that was allocated during this transaction.
1320
 */
1321
void
1322
0
dns_qpmulti_rollback(dns_qpmulti_t *multi, dns_qp_t **qptp) {
1323
0
  unsigned int nfree = 0;
1324
1325
0
  REQUIRE(QPMULTI_VALID(multi));
1326
0
  REQUIRE(multi->writer.transaction_mode == QP_UPDATE);
1327
0
  REQUIRE(qptp != NULL && *qptp == &multi->writer);
1328
1329
0
  dns_qp_t *qp = *qptp;
1330
0
  TRACE("");
1331
1332
0
  isc_nanosecs_t start = isc_time_monotonic();
1333
1334
0
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
1335
0
    if (qp->base->ptr[chunk] != NULL && !qp->usage[chunk].immutable)
1336
0
    {
1337
0
      chunk_free(qp, chunk);
1338
      /*
1339
       * we need to clear its base pointer in the rollback
1340
       * trie, in case the arrays were resized
1341
       */
1342
0
      if (chunk < multi->rollback->chunk_max) {
1343
0
        INSIST(!multi->rollback->usage[chunk].exists);
1344
0
        multi->rollback->base->ptr[chunk] = NULL;
1345
0
      }
1346
0
      nfree++;
1347
0
    }
1348
0
  }
1349
1350
  /*
1351
   * multi->rollback->base and multi->writer->base are the same,
1352
   * unless there was a realloc_chunk_arrays() during the transaction
1353
   */
1354
0
  if (qpbase_unref(qp)) {
1355
    /* paired with dns_qpmulti_update() */
1356
0
    isc_mem_free(qp->mctx, qp->base);
1357
0
  }
1358
0
  isc_mem_free(qp->mctx, qp->usage);
1359
1360
  /* reset allocator state */
1361
0
  INSIST(multi->rollback != NULL);
1362
0
  memmove(qp, multi->rollback, sizeof(*qp));
1363
0
  isc_mem_free(qp->mctx, multi->rollback);
1364
0
  INSIST(multi->rollback == NULL);
1365
1366
0
  isc_nanosecs_t time = isc_time_monotonic() - start;
1367
0
  atomic_fetch_add_relaxed(&rollback_time, time);
1368
1369
0
  LOG_STATS("qp rollback" PRItime "free %u chunks", time, nfree);
1370
1371
0
  *qptp = NULL;
1372
0
  UNLOCK(&multi->mutex);
1373
0
}
1374
1375
/***********************************************************************
1376
 *
1377
 *  read-only transactions
1378
 */
1379
1380
static dns_qpmulti_t *
1381
587
reader_open(dns_qpmulti_t *multi, dns_qpreadable_t qpr) {
1382
587
  dns_qpreader_t *qp = dns_qpreader(qpr);
1383
587
  dns_qpnode_t *reader = rcu_dereference(multi->reader);
1384
587
  if (reader == NULL) {
1385
0
    QP_INIT(qp, multi->writer.methods, multi->writer.uctx);
1386
587
  } else {
1387
587
    multi = unpack_reader(qp, reader);
1388
587
  }
1389
587
  return multi;
1390
587
}
1391
1392
/*
1393
 * a query is light
1394
 */
1395
1396
void
1397
587
dns_qpmulti_query(dns_qpmulti_t *multi, dns_qpread_t *qp) {
1398
587
  REQUIRE(QPMULTI_VALID(multi));
1399
587
  REQUIRE(qp != NULL);
1400
1401
587
  qp->tid = isc_tid();
1402
587
  rcu_read_lock();
1403
1404
587
  dns_qpmulti_t *whence = reader_open(multi, qp);
1405
587
  INSIST(whence == multi);
1406
587
}
1407
1408
void
1409
587
dns_qpread_destroy(dns_qpmulti_t *multi, dns_qpread_t *qp) {
1410
587
  REQUIRE(QPMULTI_VALID(multi));
1411
587
  REQUIRE(QP_VALID(qp));
1412
587
  REQUIRE(qp->tid == isc_tid());
1413
587
  *qp = (dns_qpread_t){};
1414
587
  rcu_read_unlock();
1415
587
}
1416
1417
/*
1418
 * a snapshot is heavy
1419
 */
1420
1421
void
1422
0
dns_qpmulti_snapshot(dns_qpmulti_t *multi, dns_qpsnap_t **qpsp) {
1423
0
  REQUIRE(QPMULTI_VALID(multi));
1424
0
  REQUIRE(qpsp != NULL && *qpsp == NULL);
1425
1426
0
  rcu_read_lock();
1427
1428
0
  LOCK(&multi->mutex);
1429
1430
0
  dns_qp_t *qpw = &multi->writer;
1431
0
  size_t bytes = sizeof(dns_qpsnap_t) + sizeof(dns_qpbase_t) +
1432
0
           sizeof(qpw->base->ptr[0]) * qpw->chunk_max;
1433
0
  dns_qpsnap_t *qps = isc_mem_allocate(qpw->mctx, bytes);
1434
1435
0
  qps->whence = reader_open(multi, qps);
1436
0
  INSIST(qps->whence == multi);
1437
1438
  /* not a separate allocation */
1439
0
  qps->base = (dns_qpbase_t *)(qps + 1);
1440
0
  isc_refcount_init(&qps->base->refcount, 0);
1441
1442
  /*
1443
   * only copy base pointers of chunks we need, so we can
1444
   * reclaim unused memory in dns_qpsnap_destroy()
1445
   */
1446
0
  qps->chunk_max = qpw->chunk_max;
1447
0
  for (dns_qpchunk_t chunk = 0; chunk < qpw->chunk_max; chunk++) {
1448
0
    if (qpw->usage[chunk].exists && chunk_usage(qpw, chunk) > 0) {
1449
0
      qpw->usage[chunk].snapshot = true;
1450
0
      qps->base->ptr[chunk] = qpw->base->ptr[chunk];
1451
0
    } else {
1452
0
      qps->base->ptr[chunk] = NULL;
1453
0
    }
1454
0
  }
1455
0
  ISC_LIST_INITANDAPPEND(multi->snapshots, qps, link);
1456
1457
0
  *qpsp = qps;
1458
0
  UNLOCK(&multi->mutex);
1459
1460
0
  rcu_read_unlock();
1461
0
}
1462
1463
void
1464
0
dns_qpsnap_destroy(dns_qpmulti_t *multi, dns_qpsnap_t **qpsp) {
1465
0
  REQUIRE(QPMULTI_VALID(multi));
1466
0
  REQUIRE(qpsp != NULL && *qpsp != NULL);
1467
1468
0
  LOCK(&multi->mutex);
1469
1470
0
  dns_qpsnap_t *qp = *qpsp;
1471
1472
  /* make sure the API is being used correctly */
1473
0
  REQUIRE(qp->whence == multi);
1474
1475
0
  ISC_LIST_UNLINK(multi->snapshots, qp, link);
1476
1477
  /*
1478
   * eagerly reclaim chunks that are now unused, so that memory does
1479
   * not accumulate when a trie has a lot of updates and snapshots
1480
   */
1481
0
  marksweep_chunks(multi);
1482
1483
0
  isc_mem_free(multi->writer.mctx, qp);
1484
1485
0
  *qpsp = NULL;
1486
0
  UNLOCK(&multi->mutex);
1487
0
}
1488
1489
/***********************************************************************
1490
 *
1491
 *  constructors, destructors
1492
 */
1493
1494
void
1495
dns_qp_create(isc_mem_t *mctx, const dns_qpmethods_t *methods, void *uctx,
1496
143
        dns_qp_t **qptp) {
1497
143
  REQUIRE(mctx != NULL);
1498
143
  REQUIRE(methods != NULL);
1499
143
  REQUIRE(qptp != NULL && *qptp == NULL);
1500
1501
143
  dns_qp_t *qp = isc_mem_get(mctx, sizeof(*qp));
1502
143
  QP_INIT(qp, methods, uctx);
1503
143
  isc_mem_attach(mctx, &qp->mctx);
1504
143
  alloc_reset(qp);
1505
143
  TRACE("");
1506
143
  *qptp = qp;
1507
143
}
1508
1509
void
1510
dns_qpmulti_create(isc_mem_t *mctx, const dns_qpmethods_t *methods, void *uctx,
1511
18.6k
       dns_qpmulti_t **qpmp) {
1512
18.6k
  REQUIRE(qpmp != NULL && *qpmp == NULL);
1513
1514
18.6k
  dns_qpmulti_t *multi = isc_mem_get(mctx, sizeof(*multi));
1515
18.6k
  *multi = (dns_qpmulti_t){ .magic = QPMULTI_MAGIC,
1516
18.6k
          .reader_ref = INVALID_REF,
1517
18.6k
          .references = ISC_REFCOUNT_INITIALIZER(1) };
1518
18.6k
  isc_mutex_init(&multi->mutex);
1519
18.6k
  ISC_LIST_INIT(multi->snapshots);
1520
1521
  /*
1522
   * Do not waste effort allocating a bump chunk that will be thrown
1523
   * away when a transaction is opened. dns_qpmulti_update() always
1524
   * allocates; to ensure dns_qpmulti_write() does too, pretend the
1525
   * previous transaction was an update
1526
   */
1527
18.6k
  dns_qp_t *qp = &multi->writer;
1528
18.6k
  QP_INIT(qp, methods, uctx);
1529
18.6k
  isc_mem_attach(mctx, &qp->mctx);
1530
18.6k
  qp->transaction_mode = QP_UPDATE;
1531
18.6k
  TRACE("");
1532
18.6k
  *qpmp = multi;
1533
18.6k
}
1534
1535
static void
1536
18.7k
destroy_guts(dns_qp_t *qp) {
1537
18.7k
  if (qp->chunk_max == 0) {
1538
0
    return;
1539
0
  }
1540
1541
375k
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
1542
356k
    if (qp->base->ptr[chunk] != NULL) {
1543
235k
      chunk_free(qp, chunk);
1544
235k
    }
1545
356k
  }
1546
18.7k
  qp->chunk_max = 0;
1547
18.7k
  ENSURE(qp->used_count == 0);
1548
18.7k
  ENSURE(qp->free_count == 0);
1549
18.7k
  ENSURE(isc_refcount_current(&qp->base->refcount) == 1);
1550
18.7k
  isc_mem_free(qp->mctx, qp->base);
1551
18.7k
  isc_mem_free(qp->mctx, qp->usage);
1552
18.7k
  qp->magic = 0;
1553
18.7k
}
1554
1555
void
1556
143
dns_qp_destroy(dns_qp_t **qptp) {
1557
143
  REQUIRE(qptp != NULL);
1558
143
  REQUIRE(QP_VALID(*qptp));
1559
1560
143
  dns_qp_t *qp = *qptp;
1561
143
  *qptp = NULL;
1562
1563
  /* do not try to destroy part of a dns_qpmulti_t */
1564
143
  REQUIRE(qp->transaction_mode == QP_NONE);
1565
1566
143
  TRACE("");
1567
143
  destroy_guts(qp);
1568
143
  isc_mem_putanddetach(&qp->mctx, qp, sizeof(*qp));
1569
143
}
1570
1571
static void
1572
18.6k
qpmulti_free_mem(dns_qpmulti_t *multi) {
1573
18.6k
  REQUIRE(QPMULTI_VALID(multi));
1574
1575
  /* reassure thread sanitizer */
1576
18.6k
  LOCK(&multi->mutex);
1577
18.6k
  dns_qp_t *qp = &multi->writer;
1578
18.6k
  UNLOCK(&multi->mutex);
1579
1580
18.6k
  isc_mutex_destroy(&multi->mutex);
1581
18.6k
  isc_mem_putanddetach(&qp->mctx, multi, sizeof(*multi));
1582
18.6k
}
1583
1584
#if QPMULTI_TRACE
1585
ISC_REFCOUNT_STATIC_TRACE_IMPL(dns_qpmulti, qpmulti_free_mem)
1586
#else
1587
38.3k
ISC_REFCOUNT_STATIC_IMPL(dns_qpmulti, qpmulti_free_mem)
qp.c:dns_qpmulti_ref
Line
Count
Source
1587
ISC_REFCOUNT_STATIC_IMPL(dns_qpmulti, qpmulti_free_mem)
qp.c:dns_qpmulti_detach
Line
Count
Source
1587
ISC_REFCOUNT_STATIC_IMPL(dns_qpmulti, qpmulti_free_mem)
qp.c:dns_qpmulti_unref
Line
Count
Source
1587
ISC_REFCOUNT_STATIC_IMPL(dns_qpmulti, qpmulti_free_mem)
1588
38.3k
#endif
1589
38.3k
1590
38.3k
static void
1591
38.3k
qpmulti_destroy_guts_cb(struct rcu_head *arg) {
1592
18.6k
  qp_rcuctx_t *rcuctx = caa_container_of(arg, qp_rcuctx_t, rcu_head);
1593
18.6k
  REQUIRE(QPRCU_VALID(rcuctx));
1594
  /* only nonzero for reclaim_chunks_cb() */
1595
18.6k
  REQUIRE(rcuctx->count == 0);
1596
1597
18.6k
  dns_qpmulti_t *multi = rcuctx->multi;
1598
18.6k
  REQUIRE(QPMULTI_VALID(multi));
1599
1600
  /* reassure thread sanitizer */
1601
18.6k
  LOCK(&multi->mutex);
1602
1603
18.6k
  dns_qp_t *qp = &multi->writer;
1604
18.6k
  REQUIRE(QP_VALID(qp));
1605
1606
18.6k
  destroy_guts(qp);
1607
1608
18.6k
  UNLOCK(&multi->mutex);
1609
1610
18.6k
  dns_qpmulti_detach(&multi);
1611
18.6k
  isc_mem_putanddetach(&rcuctx->mctx, rcuctx,
1612
18.6k
           STRUCT_FLEX_SIZE(rcuctx, chunk, rcuctx->count));
1613
18.6k
}
1614
1615
void
1616
18.6k
dns_qpmulti_destroy(dns_qpmulti_t **qpmp) {
1617
18.6k
  dns_qp_t *qp = NULL;
1618
18.6k
  dns_qpmulti_t *multi = NULL;
1619
18.6k
  qp_rcuctx_t *rcuctx = NULL;
1620
1621
18.6k
  REQUIRE(qpmp != NULL);
1622
18.6k
  REQUIRE(QPMULTI_VALID(*qpmp));
1623
1624
18.6k
  multi = *qpmp;
1625
18.6k
  qp = &multi->writer;
1626
18.6k
  *qpmp = NULL;
1627
1628
18.6k
  REQUIRE(QP_VALID(qp));
1629
18.6k
  REQUIRE(multi->rollback == NULL);
1630
18.6k
  REQUIRE(ISC_LIST_EMPTY(multi->snapshots));
1631
1632
18.6k
  rcuctx = isc_mem_get(qp->mctx, STRUCT_FLEX_SIZE(rcuctx, chunk, 0));
1633
18.6k
  *rcuctx = (qp_rcuctx_t){
1634
18.6k
    .magic = QPRCU_MAGIC,
1635
18.6k
    .multi = multi,
1636
18.6k
  };
1637
18.6k
  isc_mem_attach(qp->mctx, &rcuctx->mctx);
1638
18.6k
  call_rcu(&rcuctx->rcu_head, qpmulti_destroy_guts_cb);
1639
18.6k
}
1640
1641
/***********************************************************************
1642
 *
1643
 *  modification
1644
 */
1645
1646
isc_result_t
1647
13.3M
dns_qp_insert(dns_qp_t *qp, void *pval, uint32_t ival) {
1648
13.3M
  dns_qpref_t new_ref, old_ref;
1649
13.3M
  dns_qpnode_t new_leaf, old_node;
1650
13.3M
  dns_qpnode_t *new_twigs = NULL, *old_twigs = NULL;
1651
13.3M
  dns_qpshift_t new_bit, old_bit;
1652
13.3M
  dns_qpweight_t old_size, new_size;
1653
13.3M
  dns_qpkey_t new_key, old_key;
1654
13.3M
  size_t new_keylen, old_keylen;
1655
13.3M
  size_t offset;
1656
13.3M
  uint64_t index;
1657
13.3M
  dns_qpshift_t bit;
1658
13.3M
  dns_qpweight_t pos;
1659
13.3M
  dns_qpnode_t *n = NULL;
1660
1661
13.3M
  REQUIRE(QP_VALID(qp));
1662
1663
13.3M
  new_leaf = make_leaf(pval, ival);
1664
13.3M
  new_keylen = leaf_qpkey(qp, &new_leaf, new_key);
1665
1666
  /* first leaf in an empty trie? */
1667
13.3M
  if (qp->leaf_count == 0) {
1668
723k
    new_ref = alloc_twigs(qp, 1);
1669
723k
    new_twigs = ref_ptr(qp, new_ref);
1670
723k
    *new_twigs = new_leaf;
1671
723k
    attach_leaf(qp, new_twigs);
1672
723k
    qp->leaf_count++;
1673
723k
    qp->root_ref = new_ref;
1674
723k
    return ISC_R_SUCCESS;
1675
723k
  }
1676
1677
  /*
1678
   * We need to keep searching down to a leaf even if our key is
1679
   * missing from this branch. It doesn't matter which twig we
1680
   * choose since the keys are all the same up to this node's
1681
   * offset. Note that if we simply use branch_twig_pos(n, bit)
1682
   * we may get an out-of-bounds access if our bit is greater
1683
   * than all the set bits in the node.
1684
   */
1685
12.6M
  n = ref_ptr(qp, qp->root_ref);
1686
99.9M
  while (is_branch(n)) {
1687
87.3M
    prefetch_twigs(qp, n);
1688
87.3M
    dns_qpref_t ref = branch_twigs_ref(n);
1689
87.3M
    bit = branch_keybit(n, new_key, new_keylen);
1690
87.3M
    pos = branch_has_twig(n, bit) ? branch_twig_pos(n, bit) : 0;
1691
87.3M
    n = ref_ptr(qp, ref + pos);
1692
87.3M
  }
1693
1694
  /* do the keys differ, and if so, where? */
1695
12.6M
  old_keylen = leaf_qpkey(qp, n, old_key);
1696
12.6M
  offset = qpkey_compare(new_key, new_keylen, old_key, old_keylen);
1697
12.6M
  if (offset == QPKEY_EQUAL) {
1698
144k
    return ISC_R_EXISTS;
1699
144k
  }
1700
12.5M
  new_bit = qpkey_bit(new_key, new_keylen, offset);
1701
12.5M
  old_bit = qpkey_bit(old_key, old_keylen, offset);
1702
1703
  /* find where to insert a branch or grow an existing branch. */
1704
12.5M
  n = make_root_mutable(qp);
1705
88.2M
  while (is_branch(n)) {
1706
85.3M
    prefetch_twigs(qp, n);
1707
85.3M
    if (offset < branch_key_offset(n)) {
1708
237k
      goto newbranch;
1709
237k
    }
1710
85.1M
    if (offset == branch_key_offset(n)) {
1711
9.44M
      goto growbranch;
1712
9.44M
    }
1713
75.7M
    make_twigs_mutable(qp, n);
1714
75.7M
    bit = branch_keybit(n, new_key, new_keylen);
1715
75.7M
    INSIST(branch_has_twig(n, bit));
1716
75.7M
    n = branch_twig_ptr(qp, n, bit);
1717
75.7M
  }
1718
  /* fall through */
1719
1720
3.06M
newbranch:
1721
3.06M
  new_ref = alloc_twigs(qp, 2);
1722
3.06M
  new_twigs = ref_ptr(qp, new_ref);
1723
1724
  /* save before overwriting. */
1725
3.06M
  old_node = *n;
1726
1727
  /* new branch node takes old node's place */
1728
3.06M
  index = BRANCH_TAG | (1ULL << new_bit) | (1ULL << old_bit) |
1729
3.06M
    ((uint64_t)offset << SHIFT_OFFSET);
1730
3.06M
  *n = make_node(index, new_ref);
1731
1732
  /* populate twigs */
1733
3.06M
  new_twigs[old_bit > new_bit] = old_node;
1734
3.06M
  new_twigs[new_bit > old_bit] = new_leaf;
1735
1736
3.06M
  attach_leaf(qp, &new_leaf);
1737
3.06M
  qp->leaf_count++;
1738
1739
3.06M
  return ISC_R_SUCCESS;
1740
1741
9.44M
growbranch:
1742
9.44M
  INSIST(!branch_has_twig(n, new_bit));
1743
1744
  /* locate twigs vectors */
1745
9.44M
  old_size = branch_twigs_size(n);
1746
9.44M
  new_size = old_size + 1;
1747
9.44M
  old_ref = branch_twigs_ref(n);
1748
9.44M
  new_ref = alloc_twigs(qp, new_size);
1749
9.44M
  old_twigs = ref_ptr(qp, old_ref);
1750
9.44M
  new_twigs = ref_ptr(qp, new_ref);
1751
1752
  /* embiggen branch node */
1753
9.44M
  index = branch_index(n) | (1ULL << new_bit);
1754
9.44M
  *n = make_node(index, new_ref);
1755
1756
  /* embiggen twigs vector */
1757
9.44M
  pos = branch_twig_pos(n, new_bit);
1758
9.44M
  move_twigs(new_twigs, old_twigs, pos);
1759
9.44M
  new_twigs[pos] = new_leaf;
1760
9.44M
  move_twigs(new_twigs + pos + 1, old_twigs + pos, old_size - pos);
1761
1762
9.44M
  if (squash_twigs(qp, old_ref, old_size)) {
1763
    /* old twigs destroyed, only attach to new leaf */
1764
9.44M
    attach_leaf(qp, &new_leaf);
1765
9.44M
  } else {
1766
    /* old twigs duplicated, attach to all leaves */
1767
578
    attach_twigs(qp, new_twigs, new_size);
1768
578
  }
1769
9.44M
  qp->leaf_count++;
1770
1771
9.44M
  return ISC_R_SUCCESS;
1772
12.5M
}
1773
1774
isc_result_t
1775
dns_qp_deletekey(dns_qp_t *qp, const dns_qpkey_t search_key,
1776
1.84M
     size_t search_keylen, void **pval_r, uint32_t *ival_r) {
1777
1.84M
  REQUIRE(QP_VALID(qp));
1778
1.84M
  REQUIRE(search_keylen < sizeof(dns_qpkey_t));
1779
1780
1.84M
  if (get_root(qp) == NULL) {
1781
1.14M
    return ISC_R_NOTFOUND;
1782
1.14M
  }
1783
1784
704k
  dns_qpshift_t bit = 0; /* suppress warning */
1785
704k
  dns_qpnode_t *parent = NULL;
1786
704k
  dns_qpnode_t *n = make_root_mutable(qp);
1787
704k
  while (is_branch(n)) {
1788
0
    prefetch_twigs(qp, n);
1789
0
    bit = branch_keybit(n, search_key, search_keylen);
1790
0
    if (!branch_has_twig(n, bit)) {
1791
0
      return ISC_R_NOTFOUND;
1792
0
    }
1793
0
    make_twigs_mutable(qp, n);
1794
0
    parent = n;
1795
0
    n = branch_twig_ptr(qp, n, bit);
1796
0
  }
1797
1798
704k
  dns_qpkey_t found_key;
1799
704k
  size_t found_keylen = leaf_qpkey(qp, n, found_key);
1800
704k
  if (qpkey_compare(search_key, search_keylen, found_key, found_keylen) !=
1801
704k
      QPKEY_EQUAL)
1802
0
  {
1803
0
    return ISC_R_NOTFOUND;
1804
0
  }
1805
1806
704k
  SET_IF_NOT_NULL(pval_r, leaf_pval(n));
1807
704k
  SET_IF_NOT_NULL(ival_r, leaf_ival(n));
1808
704k
  detach_leaf(qp, n);
1809
704k
  qp->leaf_count--;
1810
1811
  /* trie becomes empty */
1812
704k
  if (qp->leaf_count == 0) {
1813
704k
    INSIST(parent == NULL);
1814
704k
    INSIST(n == get_root(qp));
1815
704k
    free_twigs(qp, qp->root_ref, 1);
1816
704k
    qp->root_ref = INVALID_REF;
1817
704k
    return ISC_R_SUCCESS;
1818
704k
  }
1819
1820
  /* step back to parent node */
1821
0
  n = parent;
1822
0
  parent = NULL;
1823
1824
0
  INSIST(bit != 0);
1825
0
  dns_qpweight_t size = branch_twigs_size(n);
1826
0
  dns_qpweight_t pos = branch_twig_pos(n, bit);
1827
0
  dns_qpref_t ref = branch_twigs_ref(n);
1828
0
  dns_qpnode_t *twigs = ref_ptr(qp, ref);
1829
1830
0
  if (size == 2) {
1831
    /*
1832
     * move the other twig to the parent branch.
1833
     */
1834
0
    *n = twigs[!pos];
1835
0
    squash_twigs(qp, ref, 2);
1836
0
  } else {
1837
    /*
1838
     * shrink the twigs in place, to avoid using the bump
1839
     * chunk too fast - the gc will clean up after us
1840
     */
1841
0
    *n = make_node(branch_index(n) & ~(1ULL << bit), ref);
1842
0
    move_twigs(twigs + pos, twigs + pos + 1, size - pos - 1);
1843
0
    squash_twigs(qp, ref + size - 1, 1);
1844
0
  }
1845
1846
0
  return ISC_R_SUCCESS;
1847
704k
}
1848
1849
isc_result_t
1850
dns_qp_deletename(dns_qp_t *qp, const dns_name_t *name, dns_namespace_t space,
1851
2
      void **pval_r, uint32_t *ival_r) {
1852
2
  dns_qpkey_t key;
1853
2
  size_t keylen = dns_qpkey_fromname(key, name, space);
1854
2
  return dns_qp_deletekey(qp, key, keylen, pval_r, ival_r);
1855
2
}
1856
1857
/***********************************************************************
1858
 *  chains
1859
 */
1860
void
1861
581
dns_qpchain_init(dns_qpreadable_t qpr, dns_qpchain_t *chain) {
1862
581
  dns_qpreader_t *qp = dns_qpreader(qpr);
1863
581
  REQUIRE(QP_VALID(qp));
1864
581
  REQUIRE(chain != NULL);
1865
1866
  /*
1867
   * dns_qpchain_t contains a 2kb buffer, which is slow to
1868
   * zero-initialize. Therefore we avoid designated initializers, and
1869
   * initialize each field manually.
1870
   */
1871
581
  chain->magic = QPCHAIN_MAGIC;
1872
581
  chain->qp = qp;
1873
581
  chain->len = 0;
1874
581
}
1875
1876
unsigned int
1877
200
dns_qpchain_length(dns_qpchain_t *chain) {
1878
200
  REQUIRE(QPCHAIN_VALID(chain));
1879
1880
200
  return chain->len;
1881
200
}
1882
1883
void
1884
dns_qpchain_node(dns_qpchain_t *chain, unsigned int level, void **pval_r,
1885
74
     uint32_t *ival_r) {
1886
74
  dns_qpnode_t *node = NULL;
1887
1888
74
  REQUIRE(QPCHAIN_VALID(chain));
1889
74
  REQUIRE(level < chain->len);
1890
1891
74
  node = chain->chain[level].node;
1892
74
  SET_IF_NOT_NULL(pval_r, leaf_pval(node));
1893
74
  SET_IF_NOT_NULL(ival_r, leaf_ival(node));
1894
74
}
1895
1896
/***********************************************************************
1897
 *  iterators
1898
 */
1899
1900
void
1901
655
dns_qpiter_init(dns_qpreadable_t qpr, dns_qpiter_t *qpi) {
1902
655
  dns_qpreader_t *qp = dns_qpreader(qpr);
1903
655
  REQUIRE(QP_VALID(qp));
1904
655
  REQUIRE(qpi != NULL);
1905
1906
  /*
1907
   * dns_qpiter_t contains a 4kb buffer, which is slow to zero-initialize.
1908
   * Therefore we avoid designated initializers, and initialize each
1909
   * field manually.
1910
   */
1911
655
  qpi->qp = qp;
1912
655
  qpi->sp = 0;
1913
655
  qpi->magic = QPITER_MAGIC;
1914
  /*
1915
   * The top of the stack must be initialized.
1916
   */
1917
655
  qpi->stack[qpi->sp] = NULL;
1918
655
}
1919
1920
/*
1921
 * are we at the last twig in this branch (in whichever direction
1922
 * we're iterating)?
1923
 */
1924
static bool
1925
296
last_twig(dns_qpiter_t *qpi, bool forward) {
1926
296
  dns_qpweight_t pos = 0, max = 0;
1927
296
  if (qpi->sp > 0) {
1928
222
    dns_qpnode_t *child = qpi->stack[qpi->sp];
1929
222
    dns_qpnode_t *parent = qpi->stack[qpi->sp - 1];
1930
222
    pos = child - ref_ptr(qpi->qp, branch_twigs_ref(parent));
1931
222
    if (forward) {
1932
222
      max = branch_twigs_size(parent) - 1;
1933
222
    }
1934
222
  }
1935
296
  return pos == max;
1936
296
}
1937
1938
/*
1939
 * move a QP iterator forward or back to the next or previous leaf.
1940
 * note: this function can go wrong when the iterator refers to
1941
 * a mutable view of the trie which is altered while iterating
1942
 */
1943
static isc_result_t
1944
222
iterate(bool forward, dns_qpiter_t *qpi, void **pval_r, uint32_t *ival_r) {
1945
222
  dns_qpnode_t *node = NULL;
1946
222
  bool initial_branch = true;
1947
1948
222
  REQUIRE(QPITER_VALID(qpi));
1949
1950
222
  dns_qpreader_t *qp = qpi->qp;
1951
1952
222
  REQUIRE(QP_VALID(qp));
1953
1954
222
  node = get_root(qp);
1955
222
  if (node == NULL) {
1956
0
    return ISC_R_NOMORE;
1957
0
  }
1958
1959
296
  do {
1960
296
    if (qpi->stack[qpi->sp] == NULL) {
1961
      /* newly initialized iterator: use the root node */
1962
0
      INSIST(qpi->sp == 0);
1963
0
      qpi->stack[0] = node;
1964
296
    } else if (!initial_branch) {
1965
      /*
1966
       * in a prior loop, we reached a branch; from
1967
       * here we just need to get the highest or lowest
1968
       * leaf in the subtree; we don't need to bother
1969
       * stepping forward or backward through twigs
1970
       * anymore.
1971
       */
1972
0
      INSIST(qpi->sp > 0);
1973
296
    } else if (last_twig(qpi, forward)) {
1974
      /*
1975
       * we've stepped to the end (or the beginning,
1976
       * if we're iterating backwards) of a set of twigs.
1977
       */
1978
148
      if (qpi->sp == 0) {
1979
        /*
1980
         * we've finished iterating. reinitialize
1981
         * the iterator, then return ISC_R_NOMORE.
1982
         */
1983
74
        dns_qpiter_init(qpi->qp, qpi);
1984
74
        return ISC_R_NOMORE;
1985
74
      }
1986
1987
      /*
1988
       * pop the stack, and resume at the parent branch.
1989
       */
1990
74
      qpi->stack[qpi->sp] = NULL;
1991
74
      qpi->sp--;
1992
74
      continue;
1993
148
    } else {
1994
      /*
1995
       * there are more twigs in the current branch,
1996
       * so step the node pointer forward (or back).
1997
       */
1998
148
      qpi->stack[qpi->sp] += (forward ? 1 : -1);
1999
148
      node = qpi->stack[qpi->sp];
2000
148
    }
2001
2002
    /*
2003
     * if we're at a branch now, we loop down to the
2004
     * left- or rightmost leaf.
2005
     */
2006
148
    if (is_branch(node)) {
2007
0
      qpi->sp++;
2008
0
      INSIST(qpi->sp < DNS_QP_MAXKEY);
2009
0
      node = ref_ptr(qp, branch_twigs_ref(node)) +
2010
0
             (forward ? 0 : branch_twigs_size(node) - 1);
2011
0
      qpi->stack[qpi->sp] = node;
2012
0
      initial_branch = false;
2013
0
    }
2014
222
  } while (is_branch(node));
2015
2016
  /* we're at a leaf: return its data to the caller */
2017
148
  SET_IF_NOT_NULL(pval_r, leaf_pval(node));
2018
148
  SET_IF_NOT_NULL(ival_r, leaf_ival(node));
2019
148
  return ISC_R_SUCCESS;
2020
222
}
2021
2022
isc_result_t
2023
222
dns_qpiter_next(dns_qpiter_t *qpi, void **pval_r, uint32_t *ival_r) {
2024
222
  return iterate(true, qpi, pval_r, ival_r);
2025
222
}
2026
2027
isc_result_t
2028
0
dns_qpiter_prev(dns_qpiter_t *qpi, void **pval_r, uint32_t *ival_r) {
2029
0
  return iterate(false, qpi, pval_r, ival_r);
2030
0
}
2031
2032
isc_result_t
2033
74
dns_qpiter_current(dns_qpiter_t *qpi, void **pval_r, uint32_t *ival_r) {
2034
74
  dns_qpnode_t *node = NULL;
2035
2036
74
  REQUIRE(QPITER_VALID(qpi));
2037
2038
74
  node = qpi->stack[qpi->sp];
2039
74
  if (node == NULL || is_branch(node)) {
2040
0
    return ISC_R_FAILURE;
2041
0
  }
2042
2043
74
  SET_IF_NOT_NULL(pval_r, leaf_pval(node));
2044
74
  SET_IF_NOT_NULL(ival_r, leaf_ival(node));
2045
74
  return ISC_R_SUCCESS;
2046
74
}
2047
2048
/***********************************************************************
2049
 *
2050
 *  search
2051
 */
2052
2053
isc_result_t
2054
dns_qp_getkey(dns_qpreadable_t qpr, const dns_qpkey_t search_key,
2055
16.2M
        size_t search_keylen, void **pval_r, uint32_t *ival_r) {
2056
16.2M
  dns_qpreader_t *qp = dns_qpreader(qpr);
2057
16.2M
  dns_qpkey_t found_key;
2058
16.2M
  size_t found_keylen;
2059
16.2M
  dns_qpshift_t bit;
2060
16.2M
  dns_qpnode_t *n = NULL;
2061
2062
16.2M
  REQUIRE(QP_VALID(qp));
2063
16.2M
  REQUIRE(search_keylen < sizeof(dns_qpkey_t));
2064
2065
16.2M
  n = get_root(qp);
2066
16.2M
  if (n == NULL) {
2067
1.26M
    return ISC_R_NOTFOUND;
2068
1.26M
  }
2069
2070
146M
  while (is_branch(n)) {
2071
140M
    prefetch_twigs(qp, n);
2072
140M
    bit = branch_keybit(n, search_key, search_keylen);
2073
140M
    if (!branch_has_twig(n, bit)) {
2074
9.44M
      return ISC_R_NOTFOUND;
2075
9.44M
    }
2076
131M
    n = branch_twig_ptr(qp, n, bit);
2077
131M
  }
2078
2079
5.50M
  found_keylen = leaf_qpkey(qp, n, found_key);
2080
5.50M
  if (qpkey_compare(search_key, search_keylen, found_key, found_keylen) !=
2081
5.50M
      QPKEY_EQUAL)
2082
3.02M
  {
2083
3.02M
    return ISC_R_NOTFOUND;
2084
3.02M
  }
2085
2086
2.47M
  SET_IF_NOT_NULL(pval_r, leaf_pval(n));
2087
2.47M
  SET_IF_NOT_NULL(ival_r, leaf_ival(n));
2088
2.47M
  return ISC_R_SUCCESS;
2089
5.50M
}
2090
2091
isc_result_t
2092
dns_qp_getname(dns_qpreadable_t qpr, const dns_name_t *name,
2093
14.8M
         dns_namespace_t space, void **pval_r, uint32_t *ival_r) {
2094
14.8M
  dns_qpkey_t key;
2095
14.8M
  size_t keylen = dns_qpkey_fromname(key, name, space);
2096
14.8M
  return dns_qp_getkey(qpr, key, keylen, pval_r, ival_r);
2097
14.8M
}
2098
2099
static inline void
2100
400
add_link(dns_qpchain_t *chain, dns_qpnode_t *node, size_t offset) {
2101
  /* prevent duplication */
2102
400
  if (chain->len != 0 && chain->chain[chain->len - 1].node == node) {
2103
0
    return;
2104
0
  }
2105
400
  chain->chain[chain->len].node = node;
2106
400
  chain->chain[chain->len].offset = offset;
2107
400
  chain->len++;
2108
400
  INSIST(chain->len <= DNS_NAME_MAXLABELS);
2109
400
}
2110
2111
static inline void
2112
0
prevleaf(dns_qpiter_t *it) {
2113
0
  isc_result_t result = dns_qpiter_prev(it, NULL, NULL);
2114
0
  if (result == ISC_R_NOMORE) {
2115
0
    result = dns_qpiter_prev(it, NULL, NULL);
2116
0
  }
2117
0
  RUNTIME_CHECK(result == ISC_R_SUCCESS);
2118
0
}
2119
2120
static inline void
2121
74
greatest_leaf(dns_qpreadable_t qpr, dns_qpnode_t *n, dns_qpiter_t *iter) {
2122
74
  while (is_branch(n)) {
2123
0
    dns_qpref_t ref = branch_twigs_ref(n) + branch_twigs_size(n) -
2124
0
          1;
2125
0
    iter->stack[++iter->sp] = n;
2126
0
    n = ref_ptr(qpr, ref);
2127
0
  }
2128
74
  iter->stack[++iter->sp] = n;
2129
74
}
2130
2131
static inline dns_qpnode_t *
2132
0
anyleaf(dns_qpreader_t *qp, dns_qpnode_t *n) {
2133
0
  while (is_branch(n)) {
2134
0
    n = branch_twigs(qp, n);
2135
0
  }
2136
0
  return n;
2137
0
}
2138
2139
static inline int
2140
twig_offset(dns_qpnode_t *n, dns_qpshift_t sbit, dns_qpshift_t kbit,
2141
74
      dns_qpshift_t fbit) {
2142
74
  dns_qpweight_t pos = branch_twig_pos(n, sbit);
2143
74
  if (branch_has_twig(n, sbit)) {
2144
74
    return pos - (kbit < fbit);
2145
74
  }
2146
0
  return pos - 1;
2147
74
}
2148
2149
/*
2150
 * If dns_qp_lookup() was passed an iterator, we want it to point at the
2151
 * matching name in the case of an exact match, or at the predecessor name
2152
 * for a non-exact match.
2153
 *
2154
 * If there is an exact match, then there is nothing to be done. Otherwise,
2155
 * we pop up the iterator stack until we find a parent branch with an offset
2156
 * that is before the position where the search key differs from the found key.
2157
 * From there we can step to the leaf that is the predecessor of the searched
2158
 * name.
2159
 *
2160
 * Requires the iterator to be pointing at a leaf node.
2161
 */
2162
static void
2163
fix_iterator(dns_qpreader_t *qp, dns_qpiter_t *it, dns_qpkey_t key,
2164
200
       size_t len) {
2165
200
  dns_qpnode_t *n = it->stack[it->sp];
2166
2167
200
  REQUIRE(!is_branch(n));
2168
2169
200
  dns_qpkey_t found;
2170
200
  size_t foundlen = leaf_qpkey(qp, n, found);
2171
200
  size_t to = qpkey_compare(key, len, found, foundlen);
2172
2173
  /* If the keys are equal, the iterator is already at the right node. */
2174
200
  if (to == QPKEY_EQUAL) {
2175
126
    return;
2176
126
  }
2177
2178
  /*
2179
   * Special case: if the key differs even before the root
2180
   * key offset, it means the name desired either precedes or
2181
   * follows the entire range of names in the database, and
2182
   * popping up the stack won't help us, so just move the
2183
   * iterator one step back from the origin and return.
2184
   */
2185
74
  if (to < branch_key_offset(it->stack[0])) {
2186
0
    dns_qpiter_init(qp, it);
2187
0
    prevleaf(it);
2188
0
    return;
2189
0
  }
2190
2191
  /*
2192
   * As long as the branch offset point is after the point where the
2193
   * key differs, we need to branch up and find a better node.
2194
   */
2195
74
  while (it->sp > 0) {
2196
74
    dns_qpnode_t *b = it->stack[it->sp - 1];
2197
74
    if (branch_key_offset(b) < to) {
2198
74
      break;
2199
74
    }
2200
0
    it->sp--;
2201
0
  }
2202
74
  n = it->stack[it->sp];
2203
2204
  /*
2205
   * Either we are now at the correct branch, or we are at the
2206
   * first unmatched node. Determine the bit position for the
2207
   * twig we need (sbit).
2208
   */
2209
74
  dns_qpshift_t kbit = qpkey_bit(key, len, to);
2210
74
  dns_qpshift_t fbit = qpkey_bit(found, foundlen, to);
2211
74
  dns_qpshift_t sbit = 0;
2212
2213
74
  if (is_branch(n) && branch_key_offset(n) == to) {
2214
    /* We are on the correct branch now. */
2215
0
    sbit = kbit;
2216
74
  } else if (it->sp == 0) {
2217
    /*
2218
     * We are on the root branch, popping up the stack won't
2219
     * help us, so just move the iterator one step back from the
2220
     * origin and return.
2221
     */
2222
0
    dns_qpiter_init(qp, it);
2223
0
    prevleaf(it);
2224
0
    return;
2225
74
  } else {
2226
    /* We are at the first unmatched node, pop up the stack. */
2227
74
    n = it->stack[--it->sp];
2228
74
    sbit = qpkey_bit(key, len, branch_key_offset(n));
2229
74
  }
2230
2231
74
  INSIST(is_branch(n));
2232
2233
74
  prefetch_twigs(qp, n);
2234
74
  dns_qpnode_t *twigs = branch_twigs(qp, n);
2235
74
  int toff = twig_offset(n, sbit, kbit, fbit);
2236
74
  if (toff >= 0) {
2237
    /*
2238
     * The name we want would've been after some twig in
2239
     * this branch. Walk down from that twig to the
2240
     * highest leaf in its subtree to get the predecessor.
2241
     */
2242
74
    greatest_leaf(qp, twigs + toff, it);
2243
74
  } else {
2244
    /*
2245
     * Every leaf below this node is greater than the one we
2246
     * wanted, so the previous leaf is the predecessor.
2247
     */
2248
0
    prevleaf(it);
2249
0
  }
2250
74
}
2251
2252
/*
2253
 * When searching for a requested name in dns_qp_lookup(), we might add
2254
 * a leaf node to the chain, then subsequently determine that it was a
2255
 * dead end. When this happens, the chain can be left holding a node
2256
 * that is *not* an ancestor of the requested name. We correct for that
2257
 * here.
2258
 */
2259
static void
2260
148
fix_chain(dns_qpchain_t *chain, size_t offset) {
2261
148
  while (chain->len > 0 && chain->chain[chain->len - 1].offset >= offset)
2262
0
  {
2263
0
    chain->len--;
2264
0
    chain->chain[chain->len].node = NULL;
2265
0
    chain->chain[chain->len].offset = 0;
2266
0
  }
2267
148
}
2268
2269
isc_result_t
2270
dns_qp_lookup(dns_qpreadable_t qpr, const dns_name_t *name,
2271
        dns_namespace_t space, dns_qpiter_t *iter, dns_qpchain_t *chain,
2272
581
        void **pval_r, uint32_t *ival_r) {
2273
581
  dns_qpreader_t *qp = dns_qpreader(qpr);
2274
581
  dns_qpkey_t search, found;
2275
581
  size_t searchlen, foundlen;
2276
581
  size_t offset = 0;
2277
581
  dns_qpnode_t *n = NULL;
2278
581
  dns_qpshift_t bit = SHIFT_NOBYTE;
2279
581
  dns_qpchain_t oc;
2280
581
  dns_qpiter_t it;
2281
581
  bool matched = false;
2282
581
  bool setiter = true;
2283
2284
581
  REQUIRE(QP_VALID(qp));
2285
2286
581
  searchlen = dns_qpkey_fromname(search, name, space);
2287
2288
581
  if (chain == NULL) {
2289
0
    chain = &oc;
2290
0
  }
2291
581
  if (iter == NULL) {
2292
381
    iter = &it;
2293
381
    setiter = false;
2294
381
  }
2295
581
  dns_qpchain_init(qp, chain);
2296
581
  dns_qpiter_init(qp, iter);
2297
2298
581
  n = get_root(qp);
2299
581
  if (n == NULL) {
2300
0
    return ISC_R_NOTFOUND;
2301
0
  }
2302
581
  iter->stack[0] = n;
2303
2304
  /*
2305
   * Like `dns_qp_insert()`, we must find a leaf. However, we don't make a
2306
   * second pass: instead, we keep track of any leaves with shorter keys
2307
   * that we discover along the way. (In general, qp-trie searches can be
2308
   * one-pass, by recording their traversal, or two-pass, for less stack
2309
   * memory usage.)
2310
   */
2311
781
  while (is_branch(n)) {
2312
200
    prefetch_twigs(qp, n);
2313
2314
200
    offset = branch_key_offset(n);
2315
200
    bit = qpkey_bit(search, searchlen, offset);
2316
200
    dns_qpnode_t *twigs = branch_twigs(qp, n);
2317
2318
    /*
2319
     * A shorter key that can be a parent domain always has a
2320
     * leaf node at SHIFT_NOBYTE (indicating end of its key)
2321
     * where our search key has a normal character immediately
2322
     * after a label separator.
2323
     *
2324
     * Note 1: It is OK if `off - 1` underflows: it will
2325
     * become SIZE_MAX, which is greater than `searchlen`, so
2326
     * `qpkey_bit()` will return SHIFT_NOBYTE, which is what we
2327
     * want when `off == 0`.
2328
     *
2329
     * Note 2: If SHIFT_NOBYTE twig is present, it will always
2330
     * be in position 0, the first location in 'twigs'.
2331
     */
2332
200
    if (bit != SHIFT_NOBYTE && branch_has_twig(n, SHIFT_NOBYTE) &&
2333
0
        qpkey_bit(search, searchlen, offset - 1) == SHIFT_NOBYTE &&
2334
0
        !is_branch(twigs))
2335
0
    {
2336
0
      add_link(chain, twigs, offset);
2337
0
    }
2338
2339
200
    matched = branch_has_twig(n, bit);
2340
200
    if (matched) {
2341
      /*
2342
       * found a match: if it's a branch, we keep
2343
       * searching, and if it's a leaf, we drop out of
2344
       * the loop.
2345
       */
2346
200
      n = branch_twig_ptr(qp, n, bit);
2347
200
    } else {
2348
      /*
2349
       * this branch is a dead end, and the predecessor
2350
       * doesn't matter. now we just need to find a leaf
2351
       * to end on so that qpkey_leaf() will work below.
2352
       */
2353
0
      n = anyleaf(qp, twigs);
2354
0
    }
2355
2356
200
    iter->stack[++iter->sp] = n;
2357
200
  }
2358
2359
581
  if (setiter) {
2360
    /*
2361
     * we found a leaf, but it might not be the leaf we wanted.
2362
     * if it isn't, and if the caller passed us an iterator,
2363
     * then we might need to reposition it.
2364
     */
2365
200
    fix_iterator(qp, iter, search, searchlen);
2366
200
    n = iter->stack[iter->sp];
2367
200
  }
2368
2369
  /* at this point, n can only be a leaf node */
2370
581
  INSIST(!is_branch(n));
2371
2372
581
  foundlen = leaf_qpkey(qp, n, found);
2373
581
  offset = qpkey_compare(search, searchlen, found, foundlen);
2374
2375
  /* the search ended with an exact or partial match */
2376
581
  if (offset == QPKEY_EQUAL || offset == foundlen) {
2377
400
    isc_result_t result = ISC_R_SUCCESS;
2378
2379
400
    if (offset == foundlen) {
2380
148
      fix_chain(chain, offset);
2381
148
      result = DNS_R_PARTIALMATCH;
2382
148
    }
2383
400
    add_link(chain, n, offset);
2384
2385
400
    SET_IF_NOT_NULL(pval_r, leaf_pval(n));
2386
400
    SET_IF_NOT_NULL(ival_r, leaf_ival(n));
2387
400
    return result;
2388
400
  }
2389
2390
  /*
2391
   * the requested name was not found, but if an ancestor
2392
   * was, we can retrieve that from the chain.
2393
   */
2394
181
  int len = chain->len;
2395
181
  while (len-- > 0) {
2396
0
    if (offset >= chain->chain[len].offset) {
2397
0
      n = chain->chain[len].node;
2398
0
      SET_IF_NOT_NULL(pval_r, leaf_pval(n));
2399
0
      SET_IF_NOT_NULL(ival_r, leaf_ival(n));
2400
0
      return DNS_R_PARTIALMATCH;
2401
0
    } else {
2402
      /*
2403
       * oops, during the search we found and added
2404
       * a leaf that's longer than the requested
2405
       * name; remove it from the chain.
2406
       */
2407
0
      chain->len--;
2408
0
    }
2409
0
  }
2410
2411
  /* nothing was found at all */
2412
181
  return ISC_R_NOTFOUND;
2413
181
}
2414
2415
/**********************************************************************/