Coverage Report

Created: 2026-02-26 06:45

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
17.2k
  isc_log_write(DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_QP, \
75
17.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
30.0M
#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
27.0k
#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
30.0M
       dns_namespace_t space) {
244
30.0M
  REQUIRE(ISC_MAGIC_VALID(name, DNS_NAME_MAGIC));
245
246
30.0M
  dns_offsets_t offsets;
247
30.0M
  size_t labels = dns_name_offsets(name, offsets);
248
30.0M
  size_t len = 0;
249
250
  /* namespace */
251
30.0M
  key[len++] = ENCODE_NAMESPACE(space);
252
  /* name */
253
30.0M
  if (labels == 0) {
254
0
    key[len] = SHIFT_NOBYTE;
255
0
    return len;
256
0
  }
257
258
30.0M
  size_t label = labels;
259
247M
  while (label-- > 0) {
260
217M
    const uint8_t *ldata = name->ndata + offsets[label];
261
217M
    size_t label_len = *ldata++;
262
619M
    while (label_len-- > 0) {
263
402M
      uint16_t bits = dns_qp_bits_for_byte[*ldata++];
264
402M
      key[len++] = bits & 0xFF; /* bit_one */
265
402M
      if ((bits >> 8) != 0) {   /* escape? */
266
215M
        key[len++] = bits >> 8; /* bit_two */
267
215M
      }
268
402M
    }
269
    /* label terminator */
270
217M
    key[len++] = SHIFT_NOBYTE;
271
217M
  }
272
  /* mark end with a double NOBYTE */
273
30.0M
  key[len] = SHIFT_NOBYTE;
274
30.0M
  ENSURE(len < sizeof(dns_qpkey_t));
275
30.0M
  return len;
276
30.0M
}
277
278
void
279
dns_qpkey_toname(const dns_qpkey_t key, size_t keylen, dns_name_t *name,
280
498
     dns_namespace_t *space) {
281
498
  size_t locs[DNS_NAME_MAXLABELS];
282
498
  size_t loc = 0;
283
498
  size_t offset = 0;
284
285
498
  REQUIRE(ISC_MAGIC_VALID(name, DNS_NAME_MAGIC));
286
498
  REQUIRE(name->buffer != NULL);
287
498
  REQUIRE(keylen > 0);
288
289
498
  dns_name_reset(name);
290
291
498
  SET_IF_NOT_NULL(space, DECODE_NAMESPACE(key[offset++]));
292
293
498
  if (keylen == NAME_OFFSET) {
294
0
    return;
295
0
  }
296
297
  /* Scan the key looking for label boundaries */
298
31.7k
  for (; offset <= keylen; offset++) {
299
31.7k
    INSIST(key[offset] >= SHIFT_NOBYTE &&
300
31.7k
           key[offset] < SHIFT_OFFSET);
301
31.7k
    INSIST(loc < DNS_NAME_MAXLABELS);
302
31.7k
    if (qpkey_bit(key, keylen, offset) == SHIFT_NOBYTE) {
303
5.66k
      if (qpkey_bit(key, keylen, offset + 1) == SHIFT_NOBYTE)
304
498
      {
305
498
        locs[loc] = offset + 1;
306
498
        goto scanned;
307
498
      }
308
5.16k
      locs[loc++] = offset + 1;
309
26.0k
    } else if (offset == NAME_OFFSET) {
310
      /* This happens for a relative name */
311
0
      locs[loc++] = offset;
312
0
    }
313
31.7k
  }
314
498
  UNREACHABLE();
315
498
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.66k
  while (loc-- > 0) {
323
5.16k
    uint8_t len = 0, *lenp = NULL;
324
325
    /* Store the location of the length byte */
326
5.16k
    lenp = isc_buffer_used(name->buffer);
327
328
    /* Add a length byte to the name data */
329
5.16k
    isc_buffer_putuint8(name->buffer, 0);
330
5.16k
    name->length++;
331
332
    /* Convert from escaped byte ranges to ASCII */
333
18.5k
    for (offset = locs[loc]; offset < locs[loc + 1] - 1; offset++) {
334
13.4k
      uint8_t bit = qpkey_bit(key, keylen, offset);
335
13.4k
      uint8_t byte = dns_qp_byte_for_bit[bit];
336
13.4k
      if (qp_common_character(byte)) {
337
784
        isc_buffer_putuint8(name->buffer, byte);
338
12.6k
      } else {
339
12.6k
        byte += key[++offset] - SHIFT_BITMAP;
340
12.6k
        isc_buffer_putuint8(name->buffer, byte);
341
12.6k
      }
342
13.4k
      len++;
343
13.4k
    }
344
345
5.16k
    name->length += len;
346
347
    /* Write the final label length to the length byte */
348
5.16k
    *lenp = len;
349
5.16k
  }
350
351
  /* Add a root label for absolute names */
352
498
  if (key[NAME_OFFSET] == SHIFT_NOBYTE) {
353
498
    name->attributes.absolute = true;
354
498
    isc_buffer_putuint8(name->buffer, 0);
355
498
    name->length++;
356
498
  }
357
358
498
  name->ndata = isc_buffer_base(name->buffer);
359
498
}
360
361
/*
362
 * Sentinel value for equal keys
363
 */
364
16.9M
#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
13.1M
        const dns_qpkey_t key_b, const size_t keylen_b) {
382
13.1M
  size_t keylen = ISC_MAX(keylen_a, keylen_b);
383
377M
  for (size_t offset = 0; offset < keylen; offset++) {
384
373M
    if (qpkey_bit(key_a, keylen_a, offset) !=
385
373M
        qpkey_bit(key_b, keylen_b, offset))
386
9.46M
    {
387
9.46M
      return offset;
388
9.46M
    }
389
373M
  }
390
3.72M
  return QPKEY_EQUAL;
391
13.1M
}
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
480k
chunk_get_raw(dns_qp_t *qp, size_t len) {
416
480k
  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
480k
  } else {
423
480k
    return isc_mem_allocate(qp->mctx, len);
424
480k
  }
425
480k
}
426
427
static void
428
480k
chunk_free_raw(dns_qp_t *qp, void *ptr) {
429
480k
  if (qp->write_protect) {
430
0
    RUNTIME_CHECK(munmap(ptr, chunk_size_raw()) == 0);
431
480k
  } else {
432
480k
    isc_mem_free(qp->mctx, ptr);
433
480k
  }
434
480k
}
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.1k
write_protect(dns_qp_t *qp, dns_qpchunk_t chunk) {
447
18.1k
  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.1k
}
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
64.7M
cells_immutable(dns_qp_t *qp, dns_qpref_t ref) {
481
64.7M
  dns_qpchunk_t chunk = ref_chunk(ref);
482
64.7M
  dns_qpcell_t cell = ref_cell(ref);
483
64.7M
  if (chunk == qp->bump) {
484
11.2M
    return cell < qp->fender;
485
53.4M
  } else {
486
53.4M
    return qp->usage[chunk].immutable;
487
53.4M
  }
488
64.7M
}
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
480k
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
480k
  size = ISC_MAX3(size, prev_capacity, 2U);
501
480k
  uint32_t log2 = 32U - stdc_leading_zeros(size - 1U);
502
503
480k
  return 1U << ISC_CLAMP(log2, QP_CHUNK_LOG_MIN, QP_CHUNK_LOG_MAX);
504
480k
}
505
506
/*
507
 * Create a fresh bump chunk and allocate some twigs from it.
508
 */
509
static dns_qpref_t
510
480k
chunk_alloc(dns_qp_t *qp, dns_qpchunk_t chunk, dns_qpweight_t size) {
511
480k
  INSIST(qp->base->ptr[chunk] == NULL);
512
480k
  INSIST(qp->usage[chunk].used == 0);
513
480k
  INSIST(qp->usage[chunk].free == 0);
514
480k
  INSIST(qp->chunk_capacity <= QP_CHUNK_SIZE);
515
516
480k
  qp->chunk_capacity = next_capacity(qp->chunk_capacity * 2u, size);
517
480k
  qp->base->ptr[chunk] =
518
480k
    chunk_get_raw(qp, qp->chunk_capacity * sizeof(dns_qpnode_t));
519
520
480k
  qp->usage[chunk] = (qp_usage_t){ .exists = true,
521
480k
           .used = size,
522
480k
           .capacity = qp->chunk_capacity };
523
480k
  qp->used_count += size;
524
480k
  qp->bump = chunk;
525
480k
  qp->fender = 0;
526
527
480k
  if (qp->write_protect) {
528
0
    TRACE("chunk %u base %p", chunk, qp->base->ptr[chunk]);
529
0
  }
530
480k
  return make_ref(chunk, 0);
531
480k
}
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
20.8k
realloc_chunk_arrays(dns_qp_t *qp, dns_qpchunk_t newmax) {
542
20.8k
  size_t oldptrs = sizeof(qp->base->ptr[0]) * qp->chunk_max;
543
20.8k
  size_t newptrs = sizeof(qp->base->ptr[0]) * newmax;
544
20.8k
  size_t size = STRUCT_FLEX_SIZE(qp->base, ptr, newmax);
545
546
20.8k
  if (qp->base == NULL || qpbase_unref(qp)) {
547
20.4k
    qp->base = isc_mem_reallocate(qp->mctx, qp->base, size);
548
20.4k
  } else {
549
428
    dns_qpbase_t *oldbase = qp->base;
550
428
    qp->base = isc_mem_allocate(qp->mctx, size);
551
428
    memmove(&qp->base->ptr[0], &oldbase->ptr[0], oldptrs);
552
428
  }
553
20.8k
  memset(&qp->base->ptr[qp->chunk_max], 0, newptrs - oldptrs);
554
20.8k
  isc_refcount_init(&qp->base->refcount, 1);
555
20.8k
  qp->base->magic = QPBASE_MAGIC;
556
557
  /* usage array is exclusive to the writer */
558
20.8k
  size_t oldusage = sizeof(qp->usage[0]) * qp->chunk_max;
559
20.8k
  size_t newusage = sizeof(qp->usage[0]) * newmax;
560
20.8k
  qp->usage = isc_mem_reallocate(qp->mctx, qp->usage, newusage);
561
20.8k
  memset(&qp->usage[qp->chunk_max], 0, newusage - oldusage);
562
563
20.8k
  qp->chunk_max = newmax;
564
565
20.8k
  TRACE("qpbase %p usage %p max %u", qp->base, qp->usage, qp->chunk_max);
566
20.8k
}
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
480k
alloc_slow(dns_qp_t *qp, dns_qpweight_t size) {
574
480k
  dns_qpchunk_t chunk;
575
576
356M
  for (chunk = 0; chunk < qp->chunk_max; chunk++) {
577
356M
    if (!qp->usage[chunk].exists) {
578
459k
      return chunk_alloc(qp, chunk, size);
579
459k
    }
580
356M
  }
581
20.8k
  ENSURE(chunk == qp->chunk_max);
582
20.8k
  realloc_chunk_arrays(qp, GROWTH_FACTOR(chunk));
583
20.8k
  return chunk_alloc(qp, chunk, size);
584
480k
}
585
586
/*
587
 * Ensure we are using a fresh bump chunk.
588
 */
589
static void
590
21.4k
alloc_reset(dns_qp_t *qp) {
591
21.4k
  (void)alloc_slow(qp, 0);
592
21.4k
}
593
594
/*
595
 * Allocate some fresh twigs. This is the bump allocator fast path.
596
 */
597
static inline dns_qpref_t
598
9.92M
alloc_twigs(dns_qp_t *qp, dns_qpweight_t size) {
599
9.92M
  dns_qpchunk_t chunk = qp->bump;
600
9.92M
  dns_qpcell_t cell = qp->usage[chunk].used;
601
602
9.92M
  if (cell + size <= qp->usage[chunk].capacity) {
603
9.46M
    qp->usage[chunk].used += size;
604
9.46M
    qp->used_count += size;
605
9.46M
    return make_ref(chunk, cell);
606
9.46M
  } else {
607
458k
    return alloc_slow(qp, size);
608
458k
  }
609
9.92M
}
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
8.11M
free_twigs(dns_qp_t *qp, dns_qpref_t twigs, dns_qpweight_t size) {
623
8.11M
  dns_qpchunk_t chunk = ref_chunk(twigs);
624
625
8.11M
  qp->free_count += size;
626
8.11M
  qp->usage[chunk].free += size;
627
8.11M
  ENSURE(qp->free_count <= qp->used_count);
628
8.11M
  ENSURE(qp->usage[chunk].free <= qp->usage[chunk].used);
629
630
8.11M
  if (cells_immutable(qp, twigs)) {
631
34.2k
    qp->hold_count += size;
632
34.2k
    ENSURE(qp->free_count >= qp->hold_count);
633
34.2k
    return false;
634
8.07M
  } else {
635
8.07M
    zero_twigs(ref_ptr(qp, twigs), size);
636
8.07M
    return true;
637
8.07M
  }
638
8.11M
}
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.1k
attach_twigs(dns_qp_t *qp, dns_qpnode_t *twigs, dns_qpweight_t size) {
647
55.9k
  for (dns_qpweight_t pos = 0; pos < size; pos++) {
648
39.8k
    if (node_tag(&twigs[pos]) == LEAF_TAG) {
649
29.7k
      attach_leaf(qp, &twigs[pos]);
650
29.7k
    }
651
39.8k
  }
652
16.1k
}
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
4.82M
chunk_usage(dns_qp_t *qp, dns_qpchunk_t chunk) {
664
4.82M
  return qp->usage[chunk].used - qp->usage[chunk].free;
665
4.82M
}
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
480k
chunk_discount(dns_qp_t *qp, dns_qpchunk_t chunk) {
674
480k
  if (qp->usage[chunk].discounted) {
675
389
    return;
676
389
  }
677
480k
  INSIST(qp->used_count >= qp->usage[chunk].used);
678
480k
  INSIST(qp->free_count >= qp->usage[chunk].free);
679
480k
  qp->used_count -= qp->usage[chunk].used;
680
480k
  qp->free_count -= qp->usage[chunk].free;
681
480k
  qp->usage[chunk].discounted = true;
682
480k
}
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
480k
chunk_free(dns_qp_t *qp, dns_qpchunk_t chunk) {
690
480k
  if (qp->write_protect) {
691
0
    TRACE("chunk %u base %p", chunk, qp->base->ptr[chunk]);
692
0
  }
693
694
480k
  dns_qpnode_t *n = qp->base->ptr[chunk];
695
57.4M
  for (dns_qpcell_t count = qp->usage[chunk].used; count > 0;
696
56.9M
       count--, n++)
697
56.9M
  {
698
56.9M
    if (node_tag(n) == LEAF_TAG && node_pointer(n) != NULL) {
699
7.77M
      detach_leaf(qp, n);
700
49.1M
    } else if (count > 1 && reader_valid(n)) {
701
36.2k
      dns_qpreader_t qpr;
702
36.2k
      unpack_reader(&qpr, n);
703
      /* pairs with dns_qpmulti_commit() */
704
36.2k
      if (qpbase_unref(&qpr)) {
705
428
        isc_mem_free(qp->mctx, qpr.base);
706
428
      }
707
36.2k
    }
708
56.9M
  }
709
480k
  chunk_discount(qp, chunk);
710
480k
  chunk_free_raw(qp, qp->base->ptr[chunk]);
711
480k
  qp->base->ptr[chunk] = NULL;
712
480k
  qp->usage[chunk] = (qp_usage_t){};
713
480k
}
714
715
/*
716
 * Free any chunks that we can while a trie is in use.
717
 */
718
static void
719
4.02k
recycle(dns_qp_t *qp) {
720
4.02k
  unsigned int nfree = 0;
721
722
4.02k
  isc_nanosecs_t start = isc_time_monotonic();
723
724
772k
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
725
768k
    if (chunk != qp->bump && chunk_usage(qp, chunk) == 0 &&
726
487k
        qp->usage[chunk].exists && !qp->usage[chunk].immutable)
727
334k
    {
728
334k
      chunk_free(qp, chunk);
729
334k
      nfree++;
730
334k
    }
731
768k
  }
732
733
4.02k
  isc_nanosecs_t time = isc_time_monotonic() - start;
734
4.02k
  atomic_fetch_add_relaxed(&recycle_time, time);
735
736
4.02k
  if (nfree > 0) {
737
4.02k
    LOG_STATS("qp recycle" PRItime "free %u chunks", time, nfree);
738
4.02k
    LOG_STATS("qp recycle leaf %u live %u used %u free %u hold %u",
739
4.02k
        qp->leaf_count, qp->used_count - qp->free_count,
740
4.02k
        qp->used_count, qp->free_count, qp->hold_count);
741
4.02k
  }
742
4.02k
}
743
744
/*
745
 * asynchronous cleanup
746
 */
747
static void
748
389
reclaim_chunks_cb(struct rcu_head *arg) {
749
389
  qp_rcuctx_t *rcuctx = caa_container_of(arg, qp_rcuctx_t, rcu_head);
750
389
  REQUIRE(QPRCU_VALID(rcuctx));
751
389
  dns_qpmulti_t *multi = rcuctx->multi;
752
389
  REQUIRE(QPMULTI_VALID(multi));
753
754
389
  LOCK(&multi->mutex);
755
389
  dns_qp_t *qp = &multi->writer;
756
757
  /*
758
   * If chunk_max is zero, chunks have already been freed.
759
   */
760
389
  if (qp->chunk_max != 0) {
761
389
    unsigned int nfree = 0;
762
389
    isc_nanosecs_t start = isc_time_monotonic();
763
764
389
    INSIST(QP_VALID(qp));
765
766
778
    for (unsigned int i = 0; i < rcuctx->count; i++) {
767
389
      dns_qpchunk_t chunk = rcuctx->chunk[i];
768
389
      if (qp->usage[chunk].snapshot) {
769
        /* clean up when snapshot is destroyed */
770
0
        qp->usage[chunk].snapfree = true;
771
389
      } else {
772
389
        chunk_free(qp, chunk);
773
389
        nfree++;
774
389
      }
775
389
    }
776
777
389
    isc_nanosecs_t time = isc_time_monotonic() - start;
778
389
    recycle_time += time;
779
780
389
    if (nfree > 0) {
781
389
      LOG_STATS("qp reclaim" PRItime "free %u chunks", time,
782
389
          nfree);
783
389
      LOG_STATS(
784
389
        "qp reclaim leaf %u live %u used %u free %u "
785
389
        "hold %u",
786
389
        qp->leaf_count, qp->used_count - qp->free_count,
787
389
        qp->used_count, qp->free_count, qp->hold_count);
788
389
    }
789
389
  }
790
791
389
  UNLOCK(&multi->mutex);
792
793
389
  dns_qpmulti_detach(&multi);
794
389
  isc_mem_putanddetach(&rcuctx->mctx, rcuctx,
795
389
           STRUCT_FLEX_SIZE(rcuctx, chunk, rcuctx->count));
796
389
}
797
798
/*
799
 * At the end of a transaction, schedule empty but immutable chunks
800
 * for reclamation later.
801
 */
802
static void
803
36.2k
reclaim_chunks(dns_qpmulti_t *multi) {
804
36.2k
  dns_qp_t *qp = &multi->writer;
805
806
36.2k
  unsigned int count = 0;
807
302k
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
808
266k
    if (chunk != qp->bump && chunk_usage(qp, chunk) == 0 &&
809
110k
        qp->usage[chunk].exists && qp->usage[chunk].immutable &&
810
389
        !qp->usage[chunk].discounted)
811
389
    {
812
389
      count++;
813
389
    }
814
266k
  }
815
816
36.2k
  if (count == 0) {
817
35.9k
    return;
818
35.9k
  }
819
820
389
  qp_rcuctx_t *rcuctx =
821
389
    isc_mem_get(qp->mctx, STRUCT_FLEX_SIZE(rcuctx, chunk, count));
822
389
  *rcuctx = (qp_rcuctx_t){
823
389
    .magic = QPRCU_MAGIC,
824
389
    .multi = multi,
825
389
    .count = count,
826
389
  };
827
389
  isc_mem_attach(qp->mctx, &rcuctx->mctx);
828
829
389
  unsigned int i = 0;
830
193k
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
831
193k
    if (chunk != qp->bump && chunk_usage(qp, chunk) == 0 &&
832
74.8k
        qp->usage[chunk].exists && qp->usage[chunk].immutable &&
833
389
        !qp->usage[chunk].discounted)
834
389
    {
835
389
      rcuctx->chunk[i++] = chunk;
836
389
      chunk_discount(qp, chunk);
837
389
    }
838
193k
  }
839
840
  /*
841
   * Reference the qpmulti object to keep it from being
842
   * freed until reclaim_chunks_cb() runs.
843
   */
844
389
  dns_qpmulti_ref(multi);
845
389
  call_rcu(&rcuctx->rcu_head, reclaim_chunks_cb);
846
847
389
  LOG_STATS("qp will reclaim %u chunks", count);
848
389
}
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.24M
evacuate(dns_qp_t *qp, dns_qpnode_t *n) {
909
1.24M
  dns_qpweight_t size = branch_twigs_size(n);
910
1.24M
  dns_qpref_t old_ref = branch_twigs_ref(n);
911
1.24M
  dns_qpref_t new_ref = alloc_twigs(qp, size);
912
1.24M
  dns_qpnode_t *old_twigs = ref_ptr(qp, old_ref);
913
1.24M
  dns_qpnode_t *new_twigs = ref_ptr(qp, new_ref);
914
915
1.24M
  move_twigs(new_twigs, old_twigs, size);
916
1.24M
  if (!free_twigs(qp, old_ref, size)) {
917
15.4k
    attach_twigs(qp, new_twigs, size);
918
15.4k
  }
919
920
1.24M
  return new_ref;
921
1.24M
}
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
8.62M
make_root_mutable(dns_qp_t *qp) {
932
8.62M
  if (cells_immutable(qp, qp->root_ref)) {
933
6.27k
    qp->root_ref = evacuate(qp, MOVABLE_ROOT(qp));
934
6.27k
  }
935
8.62M
  return ref_ptr(qp, qp->root_ref);
936
8.62M
}
937
938
static inline void
939
44.3M
make_twigs_mutable(dns_qp_t *qp, dns_qpnode_t *n) {
940
44.3M
  if (cells_immutable(qp, branch_twigs_ref(n))) {
941
8.10k
    *n = make_node(branch_index(n), evacuate(qp, n));
942
8.10k
  }
943
44.3M
}
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
3.63M
compact_recursive(dns_qp_t *qp, dns_qpnode_t *parent) {
962
3.63M
  dns_qpweight_t size = branch_twigs_size(parent);
963
3.63M
  dns_qpref_t twigs_ref = branch_twigs_ref(parent);
964
3.63M
  dns_qpchunk_t chunk = ref_chunk(twigs_ref);
965
966
3.63M
  if (qp->compact_all ||
967
3.63M
      (chunk != qp->bump && chunk_usage(qp, chunk) < QP_MIN_USED))
968
1.23M
  {
969
1.23M
    twigs_ref = evacuate(qp, parent);
970
1.23M
  }
971
3.63M
  bool immutable = cells_immutable(qp, twigs_ref);
972
36.9M
  for (dns_qpweight_t pos = 0; pos < size; pos++) {
973
33.3M
    dns_qpnode_t *child = ref_ptr(qp, twigs_ref) + pos;
974
33.3M
    if (!is_branch(child)) {
975
29.6M
      continue;
976
29.6M
    }
977
3.63M
    dns_qpref_t old_grandtwigs = branch_twigs_ref(child);
978
3.63M
    dns_qpref_t new_grandtwigs = compact_recursive(qp, child);
979
3.63M
    if (old_grandtwigs == new_grandtwigs) {
980
2.40M
      continue;
981
2.40M
    }
982
1.23M
    if (immutable) {
983
83
      twigs_ref = evacuate(qp, parent);
984
      /* the twigs have moved */
985
83
      child = ref_ptr(qp, twigs_ref) + pos;
986
83
      immutable = false;
987
83
    }
988
1.23M
    *child = make_node(branch_index(child), new_grandtwigs);
989
1.23M
  }
990
3.63M
  return twigs_ref;
991
3.63M
}
992
993
static void
994
4.02k
compact(dns_qp_t *qp) {
995
4.02k
  LOG_STATS("qp compact before leaf %u live %u used %u free %u hold %u",
996
4.02k
      qp->leaf_count, qp->used_count - qp->free_count,
997
4.02k
      qp->used_count, qp->free_count, qp->hold_count);
998
999
4.02k
  isc_nanosecs_t start = isc_time_monotonic();
1000
1001
4.02k
  if (qp->usage[qp->bump].free > QP_MAX_FREE) {
1002
3.15k
    alloc_reset(qp);
1003
3.15k
  }
1004
1005
4.02k
  if (qp->leaf_count > 0) {
1006
4.02k
    qp->root_ref = compact_recursive(qp, MOVABLE_ROOT(qp));
1007
4.02k
  }
1008
4.02k
  qp->compact_all = false;
1009
1010
4.02k
  isc_nanosecs_t time = isc_time_monotonic() - start;
1011
4.02k
  atomic_fetch_add_relaxed(&compact_time, time);
1012
1013
4.02k
  LOG_STATS("qp compact" PRItime
1014
4.02k
      "leaf %u live %u used %u free %u hold %u",
1015
4.02k
      time, qp->leaf_count, qp->used_count - qp->free_count,
1016
4.02k
      qp->used_count, qp->free_count, qp->hold_count);
1017
4.02k
}
1018
1019
void
1020
18.1k
dns_qp_compact(dns_qp_t *qp, dns_qpgc_t mode) {
1021
18.1k
  REQUIRE(QP_VALID(qp));
1022
18.1k
  if (mode == DNS_QPGC_MAYBE && !QP_NEEDGC(qp)) {
1023
18.0k
    return;
1024
18.0k
  }
1025
53
  if (mode == DNS_QPGC_ALL) {
1026
0
    alloc_reset(qp);
1027
0
    qp->compact_all = true;
1028
0
  }
1029
53
  compact(qp);
1030
53
  recycle(qp);
1031
53
}
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
5.94M
squash_twigs(dns_qp_t *qp, dns_qpref_t twigs, dns_qpweight_t size) {
1055
5.94M
  bool destroyed = free_twigs(qp, twigs, size);
1056
5.94M
  if (destroyed && QP_AUTOGC(qp)) {
1057
3.97k
    compact(qp);
1058
3.97k
    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.97k
    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.97k
  }
1075
5.94M
  return destroyed;
1076
5.94M
}
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
36.2k
transaction_open(dns_qpmulti_t *multi, dns_qp_t **qptp) {
1152
36.2k
  REQUIRE(QPMULTI_VALID(multi));
1153
36.2k
  REQUIRE(qptp != NULL && *qptp == NULL);
1154
1155
36.2k
  LOCK(&multi->mutex);
1156
1157
36.2k
  dns_qp_t *qp = &multi->writer;
1158
36.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
72.5k
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
1171
36.2k
    if (qp->usage[chunk].exists) {
1172
18.1k
      qp->usage[chunk].immutable = true;
1173
18.1k
      write_protect(qp, chunk);
1174
18.1k
    }
1175
36.2k
  }
1176
1177
  /*
1178
   * Ensure QP_AUTOGC() ignores free space in immutable chunks.
1179
   */
1180
36.2k
  qp->hold_count = qp->free_count;
1181
1182
36.2k
  *qptp = qp;
1183
36.2k
  return qp;
1184
36.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
36.2k
dns_qpmulti_write(dns_qpmulti_t *multi, dns_qp_t **qptp) {
1200
36.2k
  dns_qp_t *qp = transaction_open(multi, qptp);
1201
36.2k
  TRACE("");
1202
1203
36.2k
  if (qp->transaction_mode == QP_WRITE) {
1204
18.1k
    qp->fender = qp->usage[qp->bump].used;
1205
18.1k
  } else {
1206
18.1k
    alloc_reset(qp);
1207
18.1k
  }
1208
36.2k
  qp->transaction_mode = QP_WRITE;
1209
36.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
36.2k
dns_qpmulti_commit(dns_qpmulti_t *multi, dns_qp_t **qptp) {
1260
36.2k
  REQUIRE(QPMULTI_VALID(multi));
1261
36.2k
  REQUIRE(qptp != NULL && *qptp == &multi->writer);
1262
36.2k
  REQUIRE(multi->writer.transaction_mode == QP_WRITE ||
1263
36.2k
    multi->writer.transaction_mode == QP_UPDATE);
1264
1265
36.2k
  dns_qp_t *qp = *qptp;
1266
36.2k
  TRACE("");
1267
1268
36.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
36.2k
  INSIST(multi->rollback == NULL);
1280
1281
  /* not the first commit? */
1282
36.2k
  if (multi->reader_ref != INVALID_REF) {
1283
18.1k
    INSIST(cells_immutable(qp, multi->reader_ref));
1284
18.1k
    free_twigs(qp, multi->reader_ref, READER_SIZE);
1285
18.1k
  }
1286
1287
36.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
36.2k
  } else {
1295
36.2k
    multi->reader_ref = alloc_twigs(qp, READER_SIZE);
1296
36.2k
  }
1297
1298
  /* anchor a new version of the trie */
1299
36.2k
  dns_qpnode_t *reader = ref_ptr(qp, multi->reader_ref);
1300
36.2k
  make_reader(reader, multi);
1301
  /* paired with chunk_free() */
1302
36.2k
  isc_refcount_increment(&qp->base->refcount);
1303
1304
36.2k
  rcu_assign_pointer(multi->reader, reader); /* COMMIT */
1305
1306
  /* clean up what we can right now */
1307
36.2k
  if (qp->transaction_mode == QP_UPDATE || QP_NEEDGC(qp)) {
1308
4
    recycle(qp);
1309
4
  }
1310
1311
  /* schedule the rest for later */
1312
36.2k
  reclaim_chunks(multi);
1313
1314
36.2k
  *qptp = NULL;
1315
36.2k
  UNLOCK(&multi->mutex);
1316
36.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
578
reader_open(dns_qpmulti_t *multi, dns_qpreadable_t qpr) {
1382
578
  dns_qpreader_t *qp = dns_qpreader(qpr);
1383
578
  dns_qpnode_t *reader = rcu_dereference(multi->reader);
1384
578
  if (reader == NULL) {
1385
0
    QP_INIT(qp, multi->writer.methods, multi->writer.uctx);
1386
578
  } else {
1387
578
    multi = unpack_reader(qp, reader);
1388
578
  }
1389
578
  return multi;
1390
578
}
1391
1392
/*
1393
 * a query is light
1394
 */
1395
1396
void
1397
578
dns_qpmulti_query(dns_qpmulti_t *multi, dns_qpread_t *qp) {
1398
578
  REQUIRE(QPMULTI_VALID(multi));
1399
578
  REQUIRE(qp != NULL);
1400
1401
578
  qp->tid = isc_tid();
1402
578
  rcu_read_lock();
1403
1404
578
  dns_qpmulti_t *whence = reader_open(multi, qp);
1405
578
  INSIST(whence == multi);
1406
578
}
1407
1408
void
1409
578
dns_qpread_destroy(dns_qpmulti_t *multi, dns_qpread_t *qp) {
1410
578
  REQUIRE(QPMULTI_VALID(multi));
1411
578
  REQUIRE(QP_VALID(qp));
1412
578
  REQUIRE(qp->tid == isc_tid());
1413
578
  *qp = (dns_qpread_t){};
1414
578
  rcu_read_unlock();
1415
578
}
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
144
        dns_qp_t **qptp) {
1497
144
  REQUIRE(mctx != NULL);
1498
144
  REQUIRE(methods != NULL);
1499
144
  REQUIRE(qptp != NULL && *qptp == NULL);
1500
1501
144
  dns_qp_t *qp = isc_mem_get(mctx, sizeof(*qp));
1502
144
  QP_INIT(qp, methods, uctx);
1503
144
  isc_mem_attach(mctx, &qp->mctx);
1504
144
  alloc_reset(qp);
1505
144
  TRACE("");
1506
144
  *qptp = qp;
1507
144
}
1508
1509
void
1510
dns_qpmulti_create(isc_mem_t *mctx, const dns_qpmethods_t *methods, void *uctx,
1511
18.1k
       dns_qpmulti_t **qpmp) {
1512
18.1k
  REQUIRE(qpmp != NULL && *qpmp == NULL);
1513
1514
18.1k
  dns_qpmulti_t *multi = isc_mem_get(mctx, sizeof(*multi));
1515
18.1k
  *multi = (dns_qpmulti_t){ .magic = QPMULTI_MAGIC,
1516
18.1k
          .reader_ref = INVALID_REF,
1517
18.1k
          .references = ISC_REFCOUNT_INITIALIZER(1) };
1518
18.1k
  isc_mutex_init(&multi->mutex);
1519
18.1k
  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.1k
  dns_qp_t *qp = &multi->writer;
1528
18.1k
  QP_INIT(qp, methods, uctx);
1529
18.1k
  isc_mem_attach(mctx, &qp->mctx);
1530
18.1k
  qp->transaction_mode = QP_UPDATE;
1531
18.1k
  TRACE("");
1532
18.1k
  *qpmp = multi;
1533
18.1k
}
1534
1535
static void
1536
18.2k
destroy_guts(dns_qp_t *qp) {
1537
18.2k
  if (qp->chunk_max == 0) {
1538
0
    return;
1539
0
  }
1540
1541
257k
  for (dns_qpchunk_t chunk = 0; chunk < qp->chunk_max; chunk++) {
1542
238k
    if (qp->base->ptr[chunk] != NULL) {
1543
145k
      chunk_free(qp, chunk);
1544
145k
    }
1545
238k
  }
1546
18.2k
  qp->chunk_max = 0;
1547
18.2k
  ENSURE(qp->used_count == 0);
1548
18.2k
  ENSURE(qp->free_count == 0);
1549
18.2k
  ENSURE(isc_refcount_current(&qp->base->refcount) == 1);
1550
18.2k
  isc_mem_free(qp->mctx, qp->base);
1551
18.2k
  isc_mem_free(qp->mctx, qp->usage);
1552
18.2k
  qp->magic = 0;
1553
18.2k
}
1554
1555
void
1556
144
dns_qp_destroy(dns_qp_t **qptp) {
1557
144
  REQUIRE(qptp != NULL);
1558
144
  REQUIRE(QP_VALID(*qptp));
1559
1560
144
  dns_qp_t *qp = *qptp;
1561
144
  *qptp = NULL;
1562
1563
  /* do not try to destroy part of a dns_qpmulti_t */
1564
144
  REQUIRE(qp->transaction_mode == QP_NONE);
1565
1566
144
  TRACE("");
1567
144
  destroy_guts(qp);
1568
144
  isc_mem_putanddetach(&qp->mctx, qp, sizeof(*qp));
1569
144
}
1570
1571
static void
1572
18.1k
qpmulti_free_mem(dns_qpmulti_t *multi) {
1573
18.1k
  REQUIRE(QPMULTI_VALID(multi));
1574
1575
  /* reassure thread sanitizer */
1576
18.1k
  LOCK(&multi->mutex);
1577
18.1k
  dns_qp_t *qp = &multi->writer;
1578
18.1k
  UNLOCK(&multi->mutex);
1579
1580
18.1k
  isc_mutex_destroy(&multi->mutex);
1581
18.1k
  isc_mem_putanddetach(&qp->mctx, multi, sizeof(*multi));
1582
18.1k
}
1583
1584
#if QPMULTI_TRACE
1585
ISC_REFCOUNT_STATIC_TRACE_IMPL(dns_qpmulti, qpmulti_free_mem)
1586
#else
1587
37.4k
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
37.4k
#endif
1589
37.4k
1590
37.4k
static void
1591
37.4k
qpmulti_destroy_guts_cb(struct rcu_head *arg) {
1592
18.1k
  qp_rcuctx_t *rcuctx = caa_container_of(arg, qp_rcuctx_t, rcu_head);
1593
18.1k
  REQUIRE(QPRCU_VALID(rcuctx));
1594
  /* only nonzero for reclaim_chunks_cb() */
1595
18.1k
  REQUIRE(rcuctx->count == 0);
1596
1597
18.1k
  dns_qpmulti_t *multi = rcuctx->multi;
1598
18.1k
  REQUIRE(QPMULTI_VALID(multi));
1599
1600
  /* reassure thread sanitizer */
1601
18.1k
  LOCK(&multi->mutex);
1602
1603
18.1k
  dns_qp_t *qp = &multi->writer;
1604
18.1k
  REQUIRE(QP_VALID(qp));
1605
1606
18.1k
  destroy_guts(qp);
1607
1608
18.1k
  UNLOCK(&multi->mutex);
1609
1610
18.1k
  dns_qpmulti_detach(&multi);
1611
18.1k
  isc_mem_putanddetach(&rcuctx->mctx, rcuctx,
1612
18.1k
           STRUCT_FLEX_SIZE(rcuctx, chunk, rcuctx->count));
1613
18.1k
}
1614
1615
void
1616
18.1k
dns_qpmulti_destroy(dns_qpmulti_t **qpmp) {
1617
18.1k
  dns_qp_t *qp = NULL;
1618
18.1k
  dns_qpmulti_t *multi = NULL;
1619
18.1k
  qp_rcuctx_t *rcuctx = NULL;
1620
1621
18.1k
  REQUIRE(qpmp != NULL);
1622
18.1k
  REQUIRE(QPMULTI_VALID(*qpmp));
1623
1624
18.1k
  multi = *qpmp;
1625
18.1k
  qp = &multi->writer;
1626
18.1k
  *qpmp = NULL;
1627
1628
18.1k
  REQUIRE(QP_VALID(qp));
1629
18.1k
  REQUIRE(multi->rollback == NULL);
1630
18.1k
  REQUIRE(ISC_LIST_EMPTY(multi->snapshots));
1631
1632
18.1k
  rcuctx = isc_mem_get(qp->mctx, STRUCT_FLEX_SIZE(rcuctx, chunk, 0));
1633
18.1k
  *rcuctx = (qp_rcuctx_t){
1634
18.1k
    .magic = QPRCU_MAGIC,
1635
18.1k
    .multi = multi,
1636
18.1k
  };
1637
18.1k
  isc_mem_attach(qp->mctx, &rcuctx->mctx);
1638
18.1k
  call_rcu(&rcuctx->rcu_head, qpmulti_destroy_guts_cb);
1639
18.1k
}
1640
1641
/***********************************************************************
1642
 *
1643
 *  modification
1644
 */
1645
1646
isc_result_t
1647
8.78M
dns_qp_insert(dns_qp_t *qp, void *pval, uint32_t ival) {
1648
8.78M
  dns_qpref_t new_ref, old_ref;
1649
8.78M
  dns_qpnode_t new_leaf, old_node;
1650
8.78M
  dns_qpnode_t *new_twigs = NULL, *old_twigs = NULL;
1651
8.78M
  dns_qpshift_t new_bit, old_bit;
1652
8.78M
  dns_qpweight_t old_size, new_size;
1653
8.78M
  dns_qpkey_t new_key, old_key;
1654
8.78M
  size_t new_keylen, old_keylen;
1655
8.78M
  size_t offset;
1656
8.78M
  uint64_t index;
1657
8.78M
  dns_qpshift_t bit;
1658
8.78M
  dns_qpweight_t pos;
1659
8.78M
  dns_qpnode_t *n = NULL;
1660
1661
8.78M
  REQUIRE(QP_VALID(qp));
1662
1663
8.78M
  new_leaf = make_leaf(pval, ival);
1664
8.78M
  new_keylen = leaf_qpkey(qp, &new_leaf, new_key);
1665
1666
  /* first leaf in an empty trie? */
1667
8.78M
  if (qp->leaf_count == 0) {
1668
916k
    new_ref = alloc_twigs(qp, 1);
1669
916k
    new_twigs = ref_ptr(qp, new_ref);
1670
916k
    *new_twigs = new_leaf;
1671
916k
    attach_leaf(qp, new_twigs);
1672
916k
    qp->leaf_count++;
1673
916k
    qp->root_ref = new_ref;
1674
916k
    return ISC_R_SUCCESS;
1675
916k
  }
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
7.86M
  n = ref_ptr(qp, qp->root_ref);
1686
58.9M
  while (is_branch(n)) {
1687
51.0M
    prefetch_twigs(qp, n);
1688
51.0M
    dns_qpref_t ref = branch_twigs_ref(n);
1689
51.0M
    bit = branch_keybit(n, new_key, new_keylen);
1690
51.0M
    pos = branch_has_twig(n, bit) ? branch_twig_pos(n, bit) : 0;
1691
51.0M
    n = ref_ptr(qp, ref + pos);
1692
51.0M
  }
1693
1694
  /* do the keys differ, and if so, where? */
1695
7.86M
  old_keylen = leaf_qpkey(qp, n, old_key);
1696
7.86M
  offset = qpkey_compare(new_key, new_keylen, old_key, old_keylen);
1697
7.86M
  if (offset == QPKEY_EQUAL) {
1698
142k
    return ISC_R_EXISTS;
1699
142k
  }
1700
7.72M
  new_bit = qpkey_bit(new_key, new_keylen, offset);
1701
7.72M
  old_bit = qpkey_bit(old_key, old_keylen, offset);
1702
1703
  /* find where to insert a branch or grow an existing branch. */
1704
7.72M
  n = make_root_mutable(qp);
1705
52.0M
  while (is_branch(n)) {
1706
50.3M
    prefetch_twigs(qp, n);
1707
50.3M
    if (offset < branch_key_offset(n)) {
1708
80.9k
      goto newbranch;
1709
80.9k
    }
1710
50.2M
    if (offset == branch_key_offset(n)) {
1711
5.94M
      goto growbranch;
1712
5.94M
    }
1713
44.3M
    make_twigs_mutable(qp, n);
1714
44.3M
    bit = branch_keybit(n, new_key, new_keylen);
1715
44.3M
    INSIST(branch_has_twig(n, bit));
1716
44.3M
    n = branch_twig_ptr(qp, n, bit);
1717
44.3M
  }
1718
  /* fall through */
1719
1720
1.77M
newbranch:
1721
1.77M
  new_ref = alloc_twigs(qp, 2);
1722
1.77M
  new_twigs = ref_ptr(qp, new_ref);
1723
1724
  /* save before overwriting. */
1725
1.77M
  old_node = *n;
1726
1727
  /* new branch node takes old node's place */
1728
1.77M
  index = BRANCH_TAG | (1ULL << new_bit) | (1ULL << old_bit) |
1729
1.77M
    ((uint64_t)offset << SHIFT_OFFSET);
1730
1.77M
  *n = make_node(index, new_ref);
1731
1732
  /* populate twigs */
1733
1.77M
  new_twigs[old_bit > new_bit] = old_node;
1734
1.77M
  new_twigs[new_bit > old_bit] = new_leaf;
1735
1736
1.77M
  attach_leaf(qp, &new_leaf);
1737
1.77M
  qp->leaf_count++;
1738
1739
1.77M
  return ISC_R_SUCCESS;
1740
1741
5.94M
growbranch:
1742
5.94M
  INSIST(!branch_has_twig(n, new_bit));
1743
1744
  /* locate twigs vectors */
1745
5.94M
  old_size = branch_twigs_size(n);
1746
5.94M
  new_size = old_size + 1;
1747
5.94M
  old_ref = branch_twigs_ref(n);
1748
5.94M
  new_ref = alloc_twigs(qp, new_size);
1749
5.94M
  old_twigs = ref_ptr(qp, old_ref);
1750
5.94M
  new_twigs = ref_ptr(qp, new_ref);
1751
1752
  /* embiggen branch node */
1753
5.94M
  index = branch_index(n) | (1ULL << new_bit);
1754
5.94M
  *n = make_node(index, new_ref);
1755
1756
  /* embiggen twigs vector */
1757
5.94M
  pos = branch_twig_pos(n, new_bit);
1758
5.94M
  move_twigs(new_twigs, old_twigs, pos);
1759
5.94M
  new_twigs[pos] = new_leaf;
1760
5.94M
  move_twigs(new_twigs + pos + 1, old_twigs + pos, old_size - pos);
1761
1762
5.94M
  if (squash_twigs(qp, old_ref, old_size)) {
1763
    /* old twigs destroyed, only attach to new leaf */
1764
5.94M
    attach_leaf(qp, &new_leaf);
1765
5.94M
  } else {
1766
    /* old twigs duplicated, attach to all leaves */
1767
638
    attach_twigs(qp, new_twigs, new_size);
1768
638
  }
1769
5.94M
  qp->leaf_count++;
1770
1771
5.94M
  return ISC_R_SUCCESS;
1772
7.72M
}
1773
1774
isc_result_t
1775
dns_qp_deletekey(dns_qp_t *qp, const dns_qpkey_t search_key,
1776
2.20M
     size_t search_keylen, void **pval_r, uint32_t *ival_r) {
1777
2.20M
  REQUIRE(QP_VALID(qp));
1778
2.20M
  REQUIRE(search_keylen < sizeof(dns_qpkey_t));
1779
1780
2.20M
  if (get_root(qp) == NULL) {
1781
1.30M
    return ISC_R_NOTFOUND;
1782
1.30M
  }
1783
1784
898k
  dns_qpshift_t bit = 0; /* suppress warning */
1785
898k
  dns_qpnode_t *parent = NULL;
1786
898k
  dns_qpnode_t *n = make_root_mutable(qp);
1787
898k
  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
898k
  dns_qpkey_t found_key;
1799
898k
  size_t found_keylen = leaf_qpkey(qp, n, found_key);
1800
898k
  if (qpkey_compare(search_key, search_keylen, found_key, found_keylen) !=
1801
898k
      QPKEY_EQUAL)
1802
0
  {
1803
0
    return ISC_R_NOTFOUND;
1804
0
  }
1805
1806
898k
  SET_IF_NOT_NULL(pval_r, leaf_pval(n));
1807
898k
  SET_IF_NOT_NULL(ival_r, leaf_ival(n));
1808
898k
  detach_leaf(qp, n);
1809
898k
  qp->leaf_count--;
1810
1811
  /* trie becomes empty */
1812
898k
  if (qp->leaf_count == 0) {
1813
898k
    INSIST(parent == NULL);
1814
898k
    INSIST(n == get_root(qp));
1815
898k
    free_twigs(qp, qp->root_ref, 1);
1816
898k
    qp->root_ref = INVALID_REF;
1817
898k
    return ISC_R_SUCCESS;
1818
898k
  }
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
898k
}
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
572
dns_qpchain_init(dns_qpreadable_t qpr, dns_qpchain_t *chain) {
1862
572
  dns_qpreader_t *qp = dns_qpreader(qpr);
1863
572
  REQUIRE(QP_VALID(qp));
1864
572
  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
572
  chain->magic = QPCHAIN_MAGIC;
1872
572
  chain->qp = qp;
1873
572
  chain->len = 0;
1874
572
}
1875
1876
unsigned int
1877
199
dns_qpchain_length(dns_qpchain_t *chain) {
1878
199
  REQUIRE(QPCHAIN_VALID(chain));
1879
1880
199
  return chain->len;
1881
199
}
1882
1883
void
1884
dns_qpchain_node(dns_qpchain_t *chain, unsigned int level, void **pval_r,
1885
78
     uint32_t *ival_r) {
1886
78
  dns_qpnode_t *node = NULL;
1887
1888
78
  REQUIRE(QPCHAIN_VALID(chain));
1889
78
  REQUIRE(level < chain->len);
1890
1891
78
  node = chain->chain[level].node;
1892
78
  SET_IF_NOT_NULL(pval_r, leaf_pval(node));
1893
78
  SET_IF_NOT_NULL(ival_r, leaf_ival(node));
1894
78
}
1895
1896
/***********************************************************************
1897
 *  iterators
1898
 */
1899
1900
void
1901
650
dns_qpiter_init(dns_qpreadable_t qpr, dns_qpiter_t *qpi) {
1902
650
  dns_qpreader_t *qp = dns_qpreader(qpr);
1903
650
  REQUIRE(QP_VALID(qp));
1904
650
  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
650
  qpi->qp = qp;
1912
650
  qpi->sp = 0;
1913
650
  qpi->magic = QPITER_MAGIC;
1914
  /*
1915
   * The top of the stack must be initialized.
1916
   */
1917
650
  qpi->stack[qpi->sp] = NULL;
1918
650
}
1919
1920
/*
1921
 * are we at the last twig in this branch (in whichever direction
1922
 * we're iterating)?
1923
 */
1924
static bool
1925
312
last_twig(dns_qpiter_t *qpi, bool forward) {
1926
312
  dns_qpweight_t pos = 0, max = 0;
1927
312
  if (qpi->sp > 0) {
1928
234
    dns_qpnode_t *child = qpi->stack[qpi->sp];
1929
234
    dns_qpnode_t *parent = qpi->stack[qpi->sp - 1];
1930
234
    pos = child - ref_ptr(qpi->qp, branch_twigs_ref(parent));
1931
234
    if (forward) {
1932
234
      max = branch_twigs_size(parent) - 1;
1933
234
    }
1934
234
  }
1935
312
  return pos == max;
1936
312
}
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
234
iterate(bool forward, dns_qpiter_t *qpi, void **pval_r, uint32_t *ival_r) {
1945
234
  dns_qpnode_t *node = NULL;
1946
234
  bool initial_branch = true;
1947
1948
234
  REQUIRE(QPITER_VALID(qpi));
1949
1950
234
  dns_qpreader_t *qp = qpi->qp;
1951
1952
234
  REQUIRE(QP_VALID(qp));
1953
1954
234
  node = get_root(qp);
1955
234
  if (node == NULL) {
1956
0
    return ISC_R_NOMORE;
1957
0
  }
1958
1959
312
  do {
1960
312
    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
312
    } 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
312
    } 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
156
      if (qpi->sp == 0) {
1979
        /*
1980
         * we've finished iterating. reinitialize
1981
         * the iterator, then return ISC_R_NOMORE.
1982
         */
1983
78
        dns_qpiter_init(qpi->qp, qpi);
1984
78
        return ISC_R_NOMORE;
1985
78
      }
1986
1987
      /*
1988
       * pop the stack, and resume at the parent branch.
1989
       */
1990
78
      qpi->stack[qpi->sp] = NULL;
1991
78
      qpi->sp--;
1992
78
      continue;
1993
156
    } else {
1994
      /*
1995
       * there are more twigs in the current branch,
1996
       * so step the node pointer forward (or back).
1997
       */
1998
156
      qpi->stack[qpi->sp] += (forward ? 1 : -1);
1999
156
      node = qpi->stack[qpi->sp];
2000
156
    }
2001
2002
    /*
2003
     * if we're at a branch now, we loop down to the
2004
     * left- or rightmost leaf.
2005
     */
2006
156
    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
234
  } while (is_branch(node));
2015
2016
  /* we're at a leaf: return its data to the caller */
2017
156
  SET_IF_NOT_NULL(pval_r, leaf_pval(node));
2018
156
  SET_IF_NOT_NULL(ival_r, leaf_ival(node));
2019
156
  return ISC_R_SUCCESS;
2020
234
}
2021
2022
isc_result_t
2023
234
dns_qpiter_next(dns_qpiter_t *qpi, void **pval_r, uint32_t *ival_r) {
2024
234
  return iterate(true, qpi, pval_r, ival_r);
2025
234
}
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
78
dns_qpiter_current(dns_qpiter_t *qpi, void **pval_r, uint32_t *ival_r) {
2034
78
  dns_qpnode_t *node = NULL;
2035
2036
78
  REQUIRE(QPITER_VALID(qpi));
2037
2038
78
  node = qpi->stack[qpi->sp];
2039
78
  if (node == NULL || is_branch(node)) {
2040
0
    return ISC_R_FAILURE;
2041
0
  }
2042
2043
78
  SET_IF_NOT_NULL(pval_r, leaf_pval(node));
2044
78
  SET_IF_NOT_NULL(ival_r, leaf_ival(node));
2045
78
  return ISC_R_SUCCESS;
2046
78
}
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
11.5M
        size_t search_keylen, void **pval_r, uint32_t *ival_r) {
2056
11.5M
  dns_qpreader_t *qp = dns_qpreader(qpr);
2057
11.5M
  dns_qpkey_t found_key;
2058
11.5M
  size_t found_keylen;
2059
11.5M
  dns_qpshift_t bit;
2060
11.5M
  dns_qpnode_t *n = NULL;
2061
2062
11.5M
  REQUIRE(QP_VALID(qp));
2063
11.5M
  REQUIRE(search_keylen < sizeof(dns_qpkey_t));
2064
2065
11.5M
  n = get_root(qp);
2066
11.5M
  if (n == NULL) {
2067
1.27M
    return ISC_R_NOTFOUND;
2068
1.27M
  }
2069
2070
109M
  while (is_branch(n)) {
2071
104M
    prefetch_twigs(qp, n);
2072
104M
    bit = branch_keybit(n, search_key, search_keylen);
2073
104M
    if (!branch_has_twig(n, bit)) {
2074
5.86M
      return ISC_R_NOTFOUND;
2075
5.86M
    }
2076
99.0M
    n = branch_twig_ptr(qp, n, bit);
2077
99.0M
  }
2078
2079
4.42M
  found_keylen = leaf_qpkey(qp, n, found_key);
2080
4.42M
  if (qpkey_compare(search_key, search_keylen, found_key, found_keylen) !=
2081
4.42M
      QPKEY_EQUAL)
2082
1.74M
  {
2083
1.74M
    return ISC_R_NOTFOUND;
2084
1.74M
  }
2085
2086
2.68M
  SET_IF_NOT_NULL(pval_r, leaf_pval(n));
2087
2.68M
  SET_IF_NOT_NULL(ival_r, leaf_ival(n));
2088
2.68M
  return ISC_R_SUCCESS;
2089
4.42M
}
2090
2091
isc_result_t
2092
dns_qp_getname(dns_qpreadable_t qpr, const dns_name_t *name,
2093
10.2M
         dns_namespace_t space, void **pval_r, uint32_t *ival_r) {
2094
10.2M
  dns_qpkey_t key;
2095
10.2M
  size_t keylen = dns_qpkey_fromname(key, name, space);
2096
10.2M
  return dns_qp_getkey(qpr, key, keylen, pval_r, ival_r);
2097
10.2M
}
2098
2099
static inline void
2100
398
add_link(dns_qpchain_t *chain, dns_qpnode_t *node, size_t offset) {
2101
  /* prevent duplication */
2102
398
  if (chain->len != 0 && chain->chain[chain->len - 1].node == node) {
2103
0
    return;
2104
0
  }
2105
398
  chain->chain[chain->len].node = node;
2106
398
  chain->chain[chain->len].offset = offset;
2107
398
  chain->len++;
2108
398
  INSIST(chain->len <= DNS_NAME_MAXLABELS);
2109
398
}
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
78
greatest_leaf(dns_qpreadable_t qpr, dns_qpnode_t *n, dns_qpiter_t *iter) {
2122
78
  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
78
  iter->stack[++iter->sp] = n;
2129
78
}
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
78
      dns_qpshift_t fbit) {
2142
78
  dns_qpweight_t pos = branch_twig_pos(n, sbit);
2143
78
  if (branch_has_twig(n, sbit)) {
2144
78
    return pos - (kbit < fbit);
2145
78
  }
2146
0
  return pos - 1;
2147
78
}
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
199
       size_t len) {
2165
199
  dns_qpnode_t *n = it->stack[it->sp];
2166
2167
199
  REQUIRE(!is_branch(n));
2168
2169
199
  dns_qpkey_t found;
2170
199
  size_t foundlen = leaf_qpkey(qp, n, found);
2171
199
  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
199
  if (to == QPKEY_EQUAL) {
2175
121
    return;
2176
121
  }
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
78
  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
78
  while (it->sp > 0) {
2196
78
    dns_qpnode_t *b = it->stack[it->sp - 1];
2197
78
    if (branch_key_offset(b) < to) {
2198
78
      break;
2199
78
    }
2200
0
    it->sp--;
2201
0
  }
2202
78
  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
78
  dns_qpshift_t kbit = qpkey_bit(key, len, to);
2210
78
  dns_qpshift_t fbit = qpkey_bit(found, foundlen, to);
2211
78
  dns_qpshift_t sbit = 0;
2212
2213
78
  if (is_branch(n) && branch_key_offset(n) == to) {
2214
    /* We are on the correct branch now. */
2215
0
    sbit = kbit;
2216
78
  } 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
78
  } else {
2226
    /* We are at the first unmatched node, pop up the stack. */
2227
78
    n = it->stack[--it->sp];
2228
78
    sbit = qpkey_bit(key, len, branch_key_offset(n));
2229
78
  }
2230
2231
78
  INSIST(is_branch(n));
2232
2233
78
  prefetch_twigs(qp, n);
2234
78
  dns_qpnode_t *twigs = branch_twigs(qp, n);
2235
78
  int toff = twig_offset(n, sbit, kbit, fbit);
2236
78
  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
78
    greatest_leaf(qp, twigs + toff, it);
2243
78
  } 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
78
}
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
156
fix_chain(dns_qpchain_t *chain, size_t offset) {
2261
156
  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
156
}
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
572
        void **pval_r, uint32_t *ival_r) {
2273
572
  dns_qpreader_t *qp = dns_qpreader(qpr);
2274
572
  dns_qpkey_t search, found;
2275
572
  size_t searchlen, foundlen;
2276
572
  size_t offset = 0;
2277
572
  dns_qpnode_t *n = NULL;
2278
572
  dns_qpshift_t bit = SHIFT_NOBYTE;
2279
572
  dns_qpchain_t oc;
2280
572
  dns_qpiter_t it;
2281
572
  bool matched = false;
2282
572
  bool setiter = true;
2283
2284
572
  REQUIRE(QP_VALID(qp));
2285
2286
572
  searchlen = dns_qpkey_fromname(search, name, space);
2287
2288
572
  if (chain == NULL) {
2289
0
    chain = &oc;
2290
0
  }
2291
572
  if (iter == NULL) {
2292
373
    iter = &it;
2293
373
    setiter = false;
2294
373
  }
2295
572
  dns_qpchain_init(qp, chain);
2296
572
  dns_qpiter_init(qp, iter);
2297
2298
572
  n = get_root(qp);
2299
572
  if (n == NULL) {
2300
0
    return ISC_R_NOTFOUND;
2301
0
  }
2302
572
  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
771
  while (is_branch(n)) {
2312
199
    prefetch_twigs(qp, n);
2313
2314
199
    offset = branch_key_offset(n);
2315
199
    bit = qpkey_bit(search, searchlen, offset);
2316
199
    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
199
    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
199
    matched = branch_has_twig(n, bit);
2340
199
    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
199
      n = branch_twig_ptr(qp, n, bit);
2347
199
    } 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
199
    iter->stack[++iter->sp] = n;
2357
199
  }
2358
2359
572
  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
199
    fix_iterator(qp, iter, search, searchlen);
2366
199
    n = iter->stack[iter->sp];
2367
199
  }
2368
2369
  /* at this point, n can only be a leaf node */
2370
572
  INSIST(!is_branch(n));
2371
2372
572
  foundlen = leaf_qpkey(qp, n, found);
2373
572
  offset = qpkey_compare(search, searchlen, found, foundlen);
2374
2375
  /* the search ended with an exact or partial match */
2376
572
  if (offset == QPKEY_EQUAL || offset == foundlen) {
2377
398
    isc_result_t result = ISC_R_SUCCESS;
2378
2379
398
    if (offset == foundlen) {
2380
156
      fix_chain(chain, offset);
2381
156
      result = DNS_R_PARTIALMATCH;
2382
156
    }
2383
398
    add_link(chain, n, offset);
2384
2385
398
    SET_IF_NOT_NULL(pval_r, leaf_pval(n));
2386
398
    SET_IF_NOT_NULL(ival_r, leaf_ival(n));
2387
398
    return result;
2388
398
  }
2389
2390
  /*
2391
   * the requested name was not found, but if an ancestor
2392
   * was, we can retrieve that from the chain.
2393
   */
2394
174
  int len = chain->len;
2395
174
  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
174
  return ISC_R_NOTFOUND;
2413
174
}
2414
2415
/**********************************************************************/