2
0
mirror of https://gitlab.isc.org/isc-projects/bind9 synced 2025-08-26 03:58:15 +00:00

385 Commits

Author SHA1 Message Date
Ondřej Surý
1fe391fd40 Make all tasks to be bound to a thread
Previously, tasks could be created either unbound or bound to a specific
thread (worker loop).  The unbound tasks would be assigned to a random
thread every time isc_task_send() was called.  Because there's no logic
that would assign the task to the least busy worker, this just creates
unpredictability.  Instead of random assignment, bind all the previously
unbound tasks to worker 0, which is guaranteed to exist.
2022-05-25 16:04:51 +02:00
Evan Hunt
694bc50273 Fix the fetches-per-server quota calculation
Since commit bad5a523c2e, when the fetches-per-server quota
was increased or decreased, instead of the value being set to
the newly calculated quota, it was set to the *minimum* of
the new quota or 1 - which effectively meant it was always set to 1.
it should instead have been the maximum, to prevent the value from
ever dropping to zero.
2022-05-13 21:47:27 -07:00
Evan Hunt
3b13edc5bd attach the resolver to the ADB
the ADB depends on the resolver, but previously only accessed it
via the view. as view->resolver may now be detached before the ADB
finishes, a shutdown race was possible. attaching to the resolver
directly prevents this.
2022-05-13 13:39:55 -07:00
Evan Hunt
51cd295c4b remove resolver whenshutdown events
weakly attaching and detaching when creating and destroying the
resolver obviates the need to have a callback event to do the weak
detach. remove the dns_resolver_whenshutdown() mechanism, as it is
now unused.
2022-05-13 13:36:10 -07:00
Evan Hunt
a2d491279a remove ADB whenshutdown events
weakly attaching and detaching the view when creating or destroying
the ADB obviates the need for a whenshutdown callback event to do
the detaching.  remove the dns_adb_whenshutdown() mechanism, since
it is no longer needed.
2022-05-13 13:36:10 -07:00
Evan Hunt
3027f59f6f move ADB and resolver stats out of the view object
for better object separation, ADB and resolver statistics counters
are now stored in the ADB and resolver objects themsevles, rather than
in the associated view.
2022-05-13 13:36:10 -07:00
Tony Finch
933f0bebe0 Clean up #include <isc/string.h>
It isn't just about HP/UX any more.
2022-05-03 12:38:59 +00:00
Tony Finch
c44d7c8034 Use a case-sensitive hash table for ADB address entries
The key for the ADB `entrybuckets` hash table is a binary `struct
isc_sockaddr` so it seems wrong to use a case-insensitive hash.
2022-05-03 12:36:48 +00:00
Tony Finch
8707cb7ad4 Reduce padding in ADB address entries
Saves a couple of bytes in `struct dns_adbentry`.
2022-05-03 12:36:48 +00:00
Tony Finch
66b3cb9732 Remove several superfluous newlines in log messages 2022-05-02 23:49:38 +01:00
Evan Hunt
a1e9a59e2b lock find when unlinking adbname->finds in dns_adb_cancelfind()
In dns_adb_cancelfind(), we need to release the find lock and
then acquire the bucket and find locks in that order, for
consistency with locking hierarchy elsehwere. Previously we
were only acquiring the bucket lock.

Also rewrote the function for better readability.
2022-04-26 12:59:59 +02:00
Ondřej Surý
b55e8a959f Allow attaching to dns_adb which is shutting down
The dns__adb_attach() had an assertion failure that prevented to attach
to dns_adb if the dns_adb was shutting down.  There was a race between
checking for .exiting in dns_adb_createfind and creating new_adbfind() -
other thread could have set the .exiting to true between the check.

Remove the assertion failure and allow attaching to dns_adb even while
shutting down.  The process of dns_adb shutting down would be noticed
only a moments later when any other callback is called.
2022-04-22 16:48:37 +02:00
Evan Hunt
73ff8850bf ADB entries could be unlinked too soon
due to a typo in the code, ADB entries were unlinked from their entry
buckets during shutdown if they had a nonzero reference count. they
were only supposed to be unlinked if the reference count was exactly
one (that being the reference held by the bucket itself).
2022-04-11 17:29:03 -07:00
Mark Andrews
ed1e480c53 Move lock to before label to prevent duplicate lock
*** CID 351370:  Program hangs  (LOCK)
    /lib/dns/adb.c: 2699 in dns_adb_cancelfind()
    2693
    2694     	LOCK(&nbucket->lock);
    2695     	ISC_LIST_UNLINK(adbname->finds, find, plink);
    2696     	UNLOCK(&nbucket->lock);
    2697
    2698     cleanup:
    >>>     CID 351370:  Program hangs  (LOCK)
    >>>     "pthread_mutex_lock" locks "find->lock" while it is locked.
    2699     	LOCK(&find->lock);
    2700     	if (!FIND_EVENTSENT(find)) {
    2701     		ev = &find->event;
    2702     		task = ev->ev_sender;
    2703     		ev->ev_sender = find;
    2704     		ev->ev_type = DNS_EVENT_ADBCANCELED;
2022-04-06 12:56:17 +10:00
Mark Andrews
05e08a21d1 Remove unnecessary NULL test leading to REVERSE_INULL false positive
*** CID 351371:  Null pointer dereferences  (REVERSE_INULL)
    /lib/dns/adb.c: 2615 in dns_adb_createfind()
    2609     	/*
    2610     	 * Copy out error flags from the name structure into the find.
    2611     	 */
    2612     	find->result_v4 = find_err_map[adbname->fetch_err];
    2613     	find->result_v6 = find_err_map[adbname->fetch6_err];
    2614
    >>>     CID 351371:  Null pointer dereferences  (REVERSE_INULL)
    >>>     Null-checking "find" suggests that it may be null, but it has already been dereferenced on all paths leading to the check.
    2615     	if (find != NULL) {
    2616     		if (want_event) {
    2617     			INSIST((find->flags & DNS_ADBFIND_ADDRESSMASK) != 0);
    2618     			isc_task_attach(task, &(isc_task_t *){ NULL });
    2619     			find->event.ev_sender = task;
    2620     			find->event.ev_action = action;
2022-04-06 12:54:08 +10:00
Evan Hunt
199be183fa Add detailed ADB and entry attach/detach tracing
To turn on detailed debug tracing of dns_adb and dns_adbentry
reference counting, #define ADB_TRACE at the top of adb.c. This
is off by default.
2022-03-30 10:12:25 +02:00
Evan Hunt
d48d8e1cf0 Refactor ADB reference counting, shutdown and locking
The ADB previously used separate reference counters for internal
and external references, plus additional counters for ABD find
and namehook objects, and used all these counters to coordinate
its shutdown process, which was a multi-stage affair involving
a sequence of control events.

It also used a complex interlocking set of static functions for
referencing, deferencing, linking, unlinking, and cleaning up various
internal objects; these functions returned boolean values to their
callers to indicate what additional processing was needed.

The changes in the previous two commits destabilized this fragile
system in a way that was difficult to recover from, so in this commit
we refactor all of it. The dns_adb and dns_adbentry objects now use
conventional attach and detach functions for reference counting, and
the shutdown process is much more straightforward.  Instead of
handling shutdown asynchronously, we can just destroy the ADB when
references reach zero

In addition, ADB locking has been simplified. Instead of a
single `find_{name,entry}_and_lock()` function which searches for
a name or entry's hash bucket, locks it, and then searches for the
name or entry in the bucket, we now use one function to find the
bucket (leaving it to the caller to do the locking) and another
find the name or entry.  Instead of locking the entire ADB when
modifying hash tables, we now use read-write locks around the
specific hash table. The only remaining need for adb->lock
is when modifying the `whenshutdown` list.

Comments throughout the module have been improved.
2022-03-30 10:12:25 +02:00
Evan Hunt
76bcb4d16b Refactor how ADB names and entries are stored in the dns_adb
Replace adb->{names,entries} and related arrays (indexed by hashed
bucket) with a isc_ht hash tables storing the new struct
adb{name,entry}bucket_t that wraps all the variables that were
originally stored in arrays indexed by "bucket" number stored directly
in the struct dns_adb.

Previously, the task exclusive mode has been used to grow the internal
arrays used to store the named and entries objects.  The isc_ht hash
tables are now protected by the isc_rwlock instead and thus the usage of
the task exclusive mode has been removed from the dns_adb.

Co-authored-by: Ondřej Surý <ondrej@isc.org>
2022-03-30 10:09:18 +02:00
Evan Hunt
6e11211ac6 minor pre-refactoring cleanups
the use of "result" as a variable name for a boolean return value
was confusing; all 'result' variables that are not isc_result_t
have been renamed to 'ret'.

The static function print_dns_name() was a duplicate of
dns_name_print(), so it has been replaced with that.

Changed INSIST to REQUIRE where appropriate, and added NULL
initialization for pointer variables.
2022-03-30 09:55:00 +02:00
Ondřej Surý
20f0936cf2 Remove use of the inline keyword used as suggestion to compiler
Historically, the inline keyword was a strong suggestion to the compiler
that it should inline the function marked inline.  As compilers became
better at optimising, this functionality has receded, and using inline
as a suggestion to inline a function is obsolete.  The compiler will
happily ignore it and inline something else entirely if it finds that's
a better optimisation.

Therefore, remove all the occurences of the inline keyword with static
functions inside single compilation unit and leave the decision whether
to inline a function or not entirely on the compiler

NOTE: We keep the usage the inline keyword when the purpose is to change
the linkage behaviour.
2022-03-25 08:33:43 +01:00
Ondřej Surý
58bd26b6cf Update the copyright information in all files in the repository
This commit converts the license handling to adhere to the REUSE
specification.  It specifically:

1. Adds used licnses to LICENSES/ directory

2. Add "isc" template for adding the copyright boilerplate

3. Changes all source files to include copyright and SPDX license
   header, this includes all the C sources, documentation, zone files,
   configuration files.  There are notes in the doc/dev/copyrights file
   on how to add correct headers to the new files.

4. Handle the rest that can't be modified via .reuse/dep5 file.  The
   binary (or otherwise unmodifiable) files could have license places
   next to them in <foo>.license file, but this would lead to cluttered
   repository and most of the files handled in the .reuse/dep5 file are
   system test files.
2022-01-11 09:05:02 +01:00
Ondřej Surý
7e002d89b4 Fix the data race when shutting down dns_adb
When dns_adb is shutting down, first the adb->shutting_down flag is set
and then task is created that runs shutdown_stage2() that sets the
shutdown flag on names and entries.  However, when dns_adb_createfind()
is called, only the individual shutdown flags are being checked, and the
global adb->shutting_down flag was not checked.  Because of that it was
possible for a different thread to slip in and create new find between
the dns_adb_shutdown() and dns_adb_detach(), but before the
shutdown_stage2() task is complete.  This was detected by
ThreadSanitizer as data race because the zonetable might have been
already detached by dns_view shutdown process and simultaneously
accessed by dns_adb_createfind().

This commit converts the adb->shutting_down to atomic_bool to prevent
the global adb lock when creating the find.
2021-11-22 11:09:21 +01:00
Evan Hunt
93f5bc893e incidental cleanup
The NAME_FETCH_A and NAME_FETCH_AAAA macros were meant to be
boolean, indicating whether the pointers were set or not, while
the NAME_FETCH_V4 and NAME_FETCH_V6 macros were meant to return
the pointer values. The latter were only used as booleans, so
they've been removed in favor of the former.

Also did some style cleanup and removed an unreachable code block.
2021-10-21 01:39:30 -07:00
Evan Hunt
18cc459e05 Incidental cleanup
- there are several allocation functions in adb.c that can no
  longer return NULL.
- a macro in rbt.c was never used.
2021-10-18 14:35:50 -07:00
Ondřej Surý
2e3a2eecfe Make isc_result a static enum
Remove the dynamic registration of result codes.  Convert isc_result_t
from unsigned + #defines into 32-bit enum type in grand unified
<isc/result.h> header.  Keep the existing values of the result codes
even at the expense of the description and identifier tables being
unnecessary large.

Additionally, add couple of:

    switch (result) {
    [...]
    default:
        break;
    }

statements where compiler now complains about missing enum values in the
switch statement.
2021-10-06 11:22:20 +02:00
Evan Hunt
08ce69a0ea Rewrite dns_resolver and dns_request to use netmgr timeouts
- The `timeout_action` parameter to dns_dispatch_addresponse() been
  replaced with a netmgr callback that is called when a dispatch read
  times out.  this callback may optionally reset the read timer and
  resume reading.

- Added a function to convert isc_interval to milliseconds; this is used
  to translate fctx->interval into a value that can be passed to
  dns_dispatch_addresponse() as the timeout.

- Note that netmgr timeouts are accurate to the millisecond, so code to
  check whether a timeout has been reached cannot rely on microsecond
  accuracy.

- If serve-stale is configured, then a timeout received by the resolver
  may trigger it to return stale data, and then resume waiting for the
  read timeout. this is no longer based on a separate stale timer.

- The code for canceling requests in request.c has been altered so that
  it can run asynchronously.

- TCP timeout events apply to the dispatch, which may be shared by
  multiple queries.  since in the event of a timeout we have no query ID
  to use to identify the resp we wanted, we now just send the timeout to
  the oldest query that was pending.

- There was some additional refactoring in the resolver: combining
  fctx_join() and fctx_try_events() into one function to reduce code
  duplication, and using fixednames in fetchctx and fetchevent.

- Incidental fix: new_adbaddrinfo() can't return NULL anymore, so the
  code can be simplified.
2021-10-02 11:39:56 -07:00
Ondřej Surý
22db2705cd Use static storage for isc_mem water_t
On the isc_mem water change the old water_t structure could be used
after free.  Instead of introducing reference counting on the hot-path
we are going to introduce additional constraints on the
isc_mem_setwater.  Once it's set for the first time, the additional
calls have to be made with the same water and water_arg arguments.
2021-07-22 11:51:46 +02:00
Ondřej Surý
9c3bebc26f Properly disable the "water" in isc_mem
The proper way how to disable the water limit in the isc_mem context is
to call:

    isc_mem_setwater(ctx, NULL, NULL, 0, 0);

this ensures that the old water callback is called with ISC_MEM_LOWATER
if the callback was called with ISC_MEM_HIWATER before.

Historically, there were some places where the limits were disabled by
calling:

    isc_mem_setwater(ctx, water, water_arg, 0, 0);

which would also call the old callback, but it also causes the water_t
to be allocated and extra check to be executed because water callback is
not NULL.

This commits unifies the calls to disable water to the preferred form.
2021-07-09 15:58:02 +02:00
Ondřej Surý
f487c6948b Replace locked mempools with memory contexts
Current mempools are kind of hybrid structures - they serve two
purposes:

 1. mempool with a lock is basically static sized allocator with
    pre-allocated free items

 2. mempool without a lock is a doubly-linked list of preallocated items

The first kind of usage could be easily replaced with jemalloc small
sized arena objects and thread-local caches.

The second usage not-so-much and we need to keep this (in
libdns:message.c) for performance reasons.
2021-07-09 15:58:02 +02:00
Evan Hunt
b0aadaac8e rename dns_name_copynf() to dns_name_copy()
dns_name_copy() is now the standard name-copying function.
2021-05-22 00:37:27 -07:00
Ondřej Surý
bb990030d3 Simplify the EDNS buffer size logic for DNS Flag Day 2020
The DNS Flag Day 2020 aims to remove the IP fragmentation problem from
the UDP DNS communication.  In this commit, we implement the required
changes and simplify the logic for picking the EDNS Buffer Size.

1. The defaults for `edns-udp-size`, `max-udp-size` and
   `nocookie-udp-size` have been changed to `1232` (the value picked by
   DNS Flag Day 2020).

2. The probing heuristics that would try 512->4096->1432->1232 buffer
   sizes has been removed and the resolver will always use just the
   `edns-udp-size` value.

3. Instead of just disabling the PMTUD mechanism on the UDP sockets, we
   now set IP_DONTFRAG (IPV6_DONTFRAG) flag.  That means that the UDP
   packets won't get ever fragmented.  If the ICMP packets are lost the
   UDP will just timeout and eventually be retried over TCP.
2020-10-05 16:21:21 +02:00
Evan Hunt
dcee985b7f update all copyright headers to eliminate the typo 2020-09-14 16:20:40 -07:00
Ondřej Surý
e24bc324b4 Fix the rbt hashtable and grow it when setting max-cache-size
There were several problems with rbt hashtable implementation:

1. Our internal hashing function returns uint64_t value, but it was
   silently truncated to unsigned int in dns_name_hash() and
   dns_name_fullhash() functions.  As the SipHash 2-4 higher bits are
   more random, we need to use the upper half of the return value.

2. The hashtable implementation in rbt.c was using modulo to pick the
   slot number for the hash table.  This has several problems because
   modulo is: a) slow, b) oblivious to patterns in the input data.  This
   could lead to very uneven distribution of the hashed data in the
   hashtable.  Combined with the single-linked lists we use, it could
   really hog-down the lookup and removal of the nodes from the rbt
   tree[a].  The Fibonacci Hashing is much better fit for the hashtable
   function here.  For longer description, read "Fibonacci Hashing: The
   Optimization that the World Forgot"[b] or just look at the Linux
   kernel.  Also this will make Diego very happy :).

3. The hashtable would rehash every time the number of nodes in the rbt
   tree would exceed 3 * (hashtable size).  The overcommit will make the
   uneven distribution in the hashtable even worse, but the main problem
   lies in the rehashing - every time the database grows beyond the
   limit, each subsequent rehashing will be much slower.  The mitigation
   here is letting the rbt know how big the cache can grown and
   pre-allocate the hashtable to be big enough to actually never need to
   rehash.  This will consume more memory at the start, but since the
   size of the hashtable is capped to `1 << 32` (e.g. 4 mio entries), it
   will only consume maximum of 32GB of memory for hashtable in the
   worst case (and max-cache-size would need to be set to more than
   4TB).  Calling the dns_db_adjusthashsize() will also cap the maximum
   size of the hashtable to the pre-computed number of bits, so it won't
   try to consume more gigabytes of memory than available for the
   database.

   FIXME: What is the average size of the rbt node that gets hashed?  I
   chose the pagesize (4k) as initial value to precompute the size of
   the hashtable, but the value is based on feeling and not any real
   data.

For future work, there are more places where we use result of the hash
value modulo some small number and that would benefit from Fibonacci
Hashing to get better distribution.

Notes:
a. A doubly linked list should be used here to speedup the removal of
   the entries from the hashtable.
b. https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/
2020-07-21 08:44:26 +02:00
Evan Hunt
57e54c46e4 change "expr == false" to "!expr" in conditionals 2020-05-25 16:09:57 -07:00
Mark Andrews
3ee5ea2fdb Reduce the number of fetches we make when looking up addresses
If there are more that 5 NS record for a zone only perform a
maximum of 4 address lookups for all the name servers.  This
limits the amount of remote lookup performed for server
addresses at each level for a given query.
2020-05-19 12:30:29 +02:00
Ondřej Surý
60c632ab91 Workaround MSVC warning C4477
Due to a way the stdatomic.h shim is implemented on Windows, the MSVC
always things that the outside type is the largest - atomic_(u)int_fast64_t.
This can lead to false positives as this one:

  lib\dns\adb.c(3678): warning C4477: 'fprintf' : format string '%u' requires an argument of type 'unsigned int', but variadic argument 2 has type 'unsigned __int64'

We workaround the issue by loading the value in a scoped local variable
with correct type first.
2020-04-15 12:47:42 +02:00
Ondřej Surý
5777c44ad0 Reformat using the new rules 2020-02-14 09:31:05 +01:00
Evan Hunt
e851ed0bb5 apply the modified style 2020-02-13 15:05:06 -08:00
Ondřej Surý
056e133c4c Use clang-tidy to add curly braces around one-line statements
The command used to reformat the files in this commit was:

./util/run-clang-tidy \
	-clang-tidy-binary clang-tidy-11
	-clang-apply-replacements-binary clang-apply-replacements-11 \
	-checks=-*,readability-braces-around-statements \
	-j 9 \
	-fix \
	-format \
	-style=file \
	-quiet
clang-format -i --style=format $(git ls-files '*.c' '*.h')
uncrustify -c .uncrustify.cfg --replace --no-backup $(git ls-files '*.c' '*.h')
clang-format -i --style=format $(git ls-files '*.c' '*.h')
2020-02-13 22:07:21 +01:00
Ondřej Surý
36c6105e4f Use coccinelle to add braces to nested single line statement
Both clang-tidy and uncrustify chokes on statement like this:

for (...)
	if (...)
		break;

This commit uses a very simple semantic patch (below) to add braces around such
statements.

Semantic patch used:

@@
statement S;
expression E;
@@

while (...)
- if (E) S
+ { if (E) { S } }

@@
statement S;
expression E;
@@

for (...;...;...)
- if (E) S
+ { if (E) { S } }

@@
statement S;
expression E;
@@

if (...)
- if (E) S
+ { if (E) { S } }
2020-02-13 21:58:55 +01:00
Ondřej Surý
f50b1e0685 Use clang-format to reformat the source files 2020-02-12 15:04:17 +01:00
Ondřej Surý
bc1d4c9cb4 Clear the pointer to destroyed object early using the semantic patch
Also disable the semantic patch as the code needs tweaks here and there because
some destroy functions might not destroy the object and return early if the
object is still in use.
2020-02-09 18:00:17 -08:00
Ondřej Surý
5eb3f71a3e Refactor the isc_mempool_create() usage using the semantic patch
The isc_mempool_create() function now cannot fail with ISC_R_MEMORY.
This commit removes all the checks on the return code using the semantic
patch from previous commit, as isc_mempool_create() now returns void.
2020-02-03 08:27:16 +01:00
Ondřej Surý
edd97cddc1 Refactor dns_name_dup() usage using the semantic patch 2019-11-29 14:00:37 +01:00
Ondřej Surý
21eab267df Fix missing adb->{e,i}refcnt locking 2019-11-26 13:07:12 +01:00
Witold Kręcicki
bad5a523c2 lib/dns/adb.c: Use atomics for adb quota values and reference counting 2019-11-26 13:07:12 +01:00
Witold Kręcicki
7d93371581 lib/dns/adb.c: don't use more than 64 lock simultaneously when run under TSAN
- TSAN can't handle more than 64 locks in one thread, lock ADB bucket-by-bucket
   in TSAN mode. This means that the dump won't be consistent but it's good
   enough for testing

 - Use proper order when unlocking adb->namelocks and adb->entrylocks when
   dumping ADB.
2019-11-18 06:51:30 +01:00
Ondřej Surý
56ef09c3a1 Describe the polynomial backoff curve used in the quota adjustment 2019-11-05 09:48:15 +01:00
Ondřej Surý
c2dad0dcb2 Replace RUNTIME_CHECK(dns_name_copy(..., NULL)) with dns_name_copynf()
Use the semantic patch from the previous commit to replace all the calls to
dns_name_copy() with NULL as third argument with dns_name_copynf().
2019-10-01 10:43:26 +10:00
Ondřej Surý
89b269b0d2 Add RUNTIME_CHECK() around result = dns_name_copy(..., NULL) calls
This second commit uses second semantic patch to replace the calls to
dns_name_copy() with NULL as third argument where the result was stored in a
isc_result_t variable.  As the dns_name_copy(..., NULL) cannot fail gracefully
when the third argument is NULL, it was just a bunch of dead code.

Couple of manual tweaks (removing dead labels and unused variables) were
manually applied on top of the semantic patch.
2019-10-01 10:43:26 +10:00