Skip to content

libs/libc/tls: Keep a copy of each __thread variable per thread. - #20723

Merged
xiaoxiang781216 merged 3 commits into
apache:masterfrom
casaroli:arm64-tls-tpidr
Nov 17, 2026
Merged

xiaoxiang781216 merged 3 commits into
apache:masterfrom
casaroli:arm64-tls-tpidr

Conversation

@casaroli

@casaroli casaroli commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A toolchain without native TLS, such as the Arm GNU toolchain for aarch64-none-elf, compiles __thread variables into calls to __emutls_get_address(). That toolchain's libgcc keeps one copy of each variable for the whole program: all threads read and write the same copy.

This PR adds __wrap___emutls_get_address() and __wrap___emutls_register_common() to libc, and links the image with --wrap=__emutls_get_address --wrap=__emutls_register_common (Make and CMake). The calls then go to libc whatever the order of the libraries, and the linker never takes libgcc's copy. With LTO the linker sees these calls only in the code made after it has chosen the archive members, so an LTO link also gets -u for the two __wrap_ names. The Toolchain.defs of each architecture that can have CONFIG_TLS_EMUTLS, and the sim Make.defs, add it to LDELFFLAGS and LDMODULEFLAGS, and the export keeps it. Each thread keeps its copies in an array that its TLS info points to; exit(), quick_exit() and pthread_exit() free them after the exit functions and the TLS destructors. It does not use pthread keys and does not need CONFIG_TLS_NELEM.

CONFIG_TLS_EMUTLS (default y, with a prompt for a board that has no space for it) builds this for the GCC and clang toolchains when libgcc is the builtin library (CONFIG_BUILTIN_TOOLCHAIN; compiler-rt has its own copy per thread), but not for armclang or GHS. The index is read and set with the atomic_ptr_t operations of #21843. The sim has it with GCC and the GNU linker (Linux, MinGW); the macOS and MSVC linkers have no --wrap, so the sim there does not have it.

The first commit makes atomic_ptr_t 16 bits where a pointer is 16 bits, as on AVR. It was atomic_t, 32 bits, so atomic_ptr_read() of the 16-bit index of GCC's control object also read two more bytes. On such a target the atomic_ptr_*() operations are now the GCC __atomic builtins on 2 bytes; on AVR they call the __atomic_*_2 functions that arch_atomic.c already has. Nothing else uses atomic_ptr_t yet. With it, AVR gets the per-thread copies too.

The documentation commit updates thread_local_storage.rst: libc's per-thread emutls, when to disable CONFIG_TLS_EMUTLS, and that the links use --wrap.

The 5-board libgcc order fix is in #21469. This PR needs it: without it, the user image of a protected build of lm3s6965-ek:qemu-protected and fvp-armv8r:pnsh links libgcc's emutls.o and not the version in libc. Seen in the symbols of both images and in the lm3s6965-ek link map.

Impact

__thread variables are per thread in flat, protected and kernel builds, with any value of CONFIG_TLS_NELEM, on every architecture whose GCC has no native TLS. Without LTO, an image without __thread variables links only two pointers and their checks. With LTO it links the emutls code (about 800 bytes on Cortex-M): nucleo-g431rb:nsh, the one LTO configuration without room for it, disables CONFIG_TLS_EMUTLS and keeps the behaviour of master. No ABI change. Not a breaking change.

Testing

Test programs tlsgroup.c (two threads, a copy per thread), tlsmany.c (twelve __thread variables with CONFIG_TLS_NELEM 4) and tlsstack.c.

qemu-armv8a:knsh (kernel) and qemu-armv8a:nsh (flat), under HVF, master 6b9b216:

Configuration master this PR
knsh, tlsgroup / tlsmany FAIL: all threads use one copy (one address) PASS
knsh, tlsstack not run PASS
nsh (flat), tlsgroup / tlsmany FAIL: tlsgroup shows one address for both threads; tlsmany fails PASS
nsh (flat) with CONFIG_TLS_ALIGNED, tlsstack not run PASS

ostest exits with status 0 on qemu-armv8a:knsh and qemu-armv8a:nsh with this PR.

Again after the review of 2026-11-14, on master 43d9de6 (with #21843):

  • qemu-armv8a:nsh (flat), tlsgroup.c as a loadable module (it calls __wrap___emutls_get_address): PASS. qemu-armv8a:knsh, tlsgroup.c as a program built from the export (LDELFFLAGS and LDMODULEFLAGS have the --wrap options): PASS.
  • qemu-armv8a:knsh with libs/libc: Free the __thread copies of a module when it is unloaded. #21470: tlsgroup.c, tlsmany.c, tlsstack.c and atexittls.c PASS; ostest exits with status 0 on knsh and nsh.
  • Kconfig: CONFIG_TLS_EMUTLS=y on qemu-armv8a:nsh and mps2-an500:knsh (CONFIG_BUILTIN_TOOLCHAIN); not set on mps3-an547:clang (CONFIG_BUILTIN_COMPILER_RT).
  • The 11 Arm LTO configurations, GCC 13.2 as in CI: all link. nucleo-g431rb:nsh has 219 bytes free on master and overflowed by 580 bytes with this code, so it disables CONFIG_TLS_EMUTLS (text+data then the same as master; savedefconfig gives the same defconfig; Make and CMake). CMake nucleo-f302r8:cansock (LTO) links with the -u options and the __wrap_ functions.

Again after the review comments on AVR and the stm32g4 defconfigs, on master 43d9de6:

  • AVR, the CI image (avr-gcc 5.4.0), EXTRAFLAGS="-Wno-cpp -Werror": the 12 AVR configurations that build on master build with CONFIG_TLS_EMUTLS=y and 0 warnings (amber:hello, arduino-mega2560:hello/nsh, elegoo-mega2560r3:nsh, mega1284p-xplained:hello/nsh, moteino-mega:hello/nsh, micropendous3:hello, teensy-2.0:hello/nsh/usbmsc). Without __thread variables, the 10 images measured grow by 28 bytes of text (the exit hook). breadxavr:nsh/ws2812 do not build on master or with this PR (the image has no device specs for avr128da28). The AVR32 configurations (avr32dev1:nsh/ostest, mizar32a:nsh) do not get the option (their toolchain choices do not select ARCH_TOOLCHAIN_GNU), and their images are the same as on master.
  • arduino-mega2560:hello with hello_main.c replaced by a two-thread __thread test: the image calls __wrap___emutls_get_address() of libc, and libgcc's emutls.o is not linked; __atomic_load_2() and __atomic_store_2() come from arch_atomic.c. Not run: NuttX does not start on qemu-system-avr (master also waits in nxsem_wait() with no interrupt), and no AVR board was available.
  • b-g431b-esc1:nsh and nucleo-g431kb:nsh now keep CONFIG_TLS_EMUTLS: with LTO they link with 128821 and 128789 bytes of text+data in 128 KiB of flash. nucleo-g431rb:nsh keeps it disabled. On master e1eca35 the CMake build of nucleo-g431rb:nsh overflows by 20 bytes without this PR.
  • qemu-armv8a:nsh tlsload.c (libs/libc: Free the __thread copies of a module when it is unloaded. #21470) and qemu-armv8a:knsh tlsgroup.c, tlsmany.c, tlsstack.c, atexittls.c PASS; ostest exits with status 0 on knsh and nsh; mps2-an500:knsh with -Werror: 0 warnings.

Builds with EXTRAFLAGS="-Wno-cpp -Werror", each OK: qemu-armv8a:knsh, qemu-armv8a:nsh, mps2-an500:knsh, rv-virt:knsh64, rv-virt:pnsh64, lm3s6965-ek:qemu-protected, and with tls_emutls.c compiled in each of these; nucleo-g431rb:nsh and sim:nsh (macOS), which do not compile it.

The second commit has [skip-cmake-parity]: the --wrap options for ELF programs and modules (the sim Make.defs part) come to CMake in #20812.

tools/checkpatch.sh -c -u -m -g passes.

@github-actions github-actions Bot added Arch: arm64 Issues related to ARM64 (64-bit) architecture Area: OS Components OS Components issues Size: M The size of the change in this PR is medium labels Oct 17, 2026
@github-actions

github-actions Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

arduino-mega2560

  • flash: .text +70 B (+0.1%, 68,240 B / 262,144 B, total: 26% used)
  • sram: .bss +16 B (+0.6%, 2,833 B / 8,192 B, total: 35% used)

esp32-devkitc

  • ROM: .flash.text +56 B (+0.0%, 131,372 B / 4,194,272 B, total: 3% used)
  • dram0_0_seg: .dram0.bss +192 B (+1.9%, 10,248 B / 180,736 B, total: 6% used)
  • irom0_0_seg: .flash.text +56 B (+0.1%, 97,236 B / 3,342,304 B, total: 3% used)

hifive1-revb

  • flash: .text -4 B (-0.0%, 87,416 B / 4,194,304 B, total: 2% used)
  • sram: .bss +64 B (+1.6%, 4,060 B / 16,384 B, total: 25% used)

mirtoo

  • kseg0_progmem: .text +16 B (+0.0%, 69,732 B / 131,072 B, total: 53% used)
  • kseg1_datamem: .bss +64 B, .sbss +4 B (+2.6%, 2,688 B / 32,256 B, total: 8% used)

qemu-armv8a

  • Code: .text.exit +16 B, .text.exited_child +4 B, .text.nxsig_dispatch_unmasked -4 B, .text.nxsig_kill +12 B, .text.nxsig_notification_source -4 B, .text.nxsig_tcbdispatch -8 B, .text.nxsig_tgkill +12 B, .text.nxsig_timedwait -4 B, .text.nxtask_exithook +4 B, .text.pthread_exit +16 B, .text.pthread_sigqueue +4 B, .text.syslog_write_foreach +20 B (+0.0%, 368,036 B)
  • Data: .bss.g_sigpool +192 B (+0.3%, 78,141 B)

qemu-intel64

  • Code: .text +134 B (+0.0%, 8,698,355 B)
  • Data: .bss +192 B (+0.2%, 108,377 B)

rx65n-rsk2mb

  • RAM: .bss +192 B (+2.9%, 6,928 B / 262,144 B, total: 3% used)
  • ROM: .text +32 B (+0.0%, 93,004 B / 2,097,152 B, total: 4% used)

s698pm-dkit

  • Code: .text +144 B (+0.0%, 397,296 B)
  • Data: .bss +128 B (+1.1%, 12,123 B)

stm32-nucleo-f103rb

  • flash: .text +28 B (+0.1%, 35,868 B / 131,072 B, total: 27% used)
  • sram: .bss +72 B (+2.9%, 2,556 B / 20,480 B, total: 12% used)

Catch memory regressions in CI with MemBrowse. Free for open source.

acassis
acassis previously approved these changes Oct 17, 2026
@github-actions github-actions Bot added Area: Documentation Improvements or additions to documentation and removed Area: OS Components OS Components issues labels Oct 17, 2026
acassis
acassis previously approved these changes Oct 18, 2026
Comment thread arch/arm64/include/irq.h Resolved
Comment thread libs/libc/tls/Make.defs Resolved
acassis
acassis previously approved these changes Oct 23, 2026
jerpelea
jerpelea previously approved these changes Oct 28, 2026
cederom
cederom previously approved these changes Oct 28, 2026

@cederom cederom left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @casaroli :-)

Comment thread libs/libc/tls/tls_emutls.c Resolved
@casaroli
casaroli dismissed stale reviews from cederom, jerpelea, and acassis via 5803dda October 28, 2026 11:09
jerpelea
jerpelea previously approved these changes Oct 28, 2026
@casaroli

casaroli commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

This PR is split to make the review easier. Review order:

  1. boards: Link libgcc after the user libraries of a protected build. #21469: the libgcc link order of 5 boards. This PR needs it.
  2. This PR: the per-thread copies of __thread variables.
  3. In either order, both need this PR:

The code is the same as before the split.

@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

🔗 Cross-repo PR dependencies

The read-only Build run reported the following dependent PR(s) and fetched head SHA(s):

CI run: https://github.com/apache/nuttx/actions/runs/43234237518

@xiaoxiang781216

Copy link
Copy Markdown
Contributor

@casaroli need rebase the patch to resolve the ci break.

@casaroli

Copy link
Copy Markdown
Contributor Author

Done.

Comment thread libs/libc/tls/Kconfig Resolved
Comment thread libs/libc/tls/Kconfig Resolved
Comment thread libs/libc/tls/Kconfig Resolved
Comment thread libs/libc/tls/Kconfig Resolved
Comment thread libs/libc/tls/CMakeLists.txt Resolved
Comment thread libs/libc/tls/tls_emutls.c Resolved
Comment thread libs/libc/tls/tls_getinfo.c Resolved
Comment thread libs/libc/tls/Kconfig Resolved
…gets.

atomic_ptr_t was atomic_t, 32 bits, also where a pointer is 16 bits, as
on AVR.  atomic_ptr_read() of a variable as wide as a pointer then read
two more bytes, and atomic_ptr_set() wrote them.

When UINTPTR_MAX <= UINT16_MAX, atomic_ptr_t is now a 16-bit atomic, and
the atomic_ptr_*() operations are the GCC __atomic builtins on 2 bytes.
Where the CPU has no atomic instructions, as on AVR, GCC calls the
__atomic_*_2 functions that libs/libc/machine/arch_atomic.c already
provides.  Nothing uses atomic_ptr_t yet, so no user changes.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
A toolchain without native TLS, such as the Arm GNU toolchain for
aarch64-none-elf, compiles __thread variables into calls to
__emutls_get_address().  That toolchain's libgcc is built with the
single thread model, so its __emutls_get_address() keeps one copy of
each variable for the whole program: all threads read and write the
same copy.

Add __wrap___emutls_get_address() and __wrap___emutls_register_common()
to libc, and link the image with "--wrap=__emutls_get_address
--wrap=__emutls_register_common" (tools/Config.mk and
libs/libc/tls/CMakeLists.txt; CMake also wraps the user image of a
protected build).  The calls then go to libc whatever the order of the
libraries, and the linker never takes libgcc's copy.  With LTO the
linker sees these calls only in the code made after it has chosen the
archive members, so an LTO link also gets "-u" for the two __wrap_
names.  EMUTLS_LDFLAGS gives the same options in the form for $(LD).
The Toolchain.defs of each architecture that can have CONFIG_TLS_EMUTLS,
and the sim Make.defs, add it to LDELFFLAGS and LDMODULEFLAGS, and the
export keeps it, so the links of modules and programs get it too.  The
system symbol table (libc.csv) exports the __wrap_ names, which a module
linked with --wrap refers to.  The real names are weak aliases for a
link without --wrap, such as the user image of a protected build or a
program built outside NuttX: libc comes before libgcc there, and in a
--whole-archive link libgcc's strong definitions win without a conflict.

CONFIG_TLS_EMUTLS (default y) builds this for the GCC and clang
toolchains when libgcc is the builtin library (BUILTIN_TOOLCHAIN;
compiler-rt has its own copy per thread), but not for armclang or GHS.
The sim has it with GCC and the GNU linker (Linux, and MinGW, whose GCC
uses emulated TLS): the sim links NuttX into nuttx.rel with --wrap, and
nuttx-names.in renames the weak real names, so the host program keeps
its own libgcc copy.  The macOS and MSVC linkers have no --wrap, so the
sim there does not have it.  The control object and the parameters use
the types of libgcc's emutls.c, as GCC declares its built-in
__emutls_register_common(): a machine word for the size and the
alignment and an integer as wide as a pointer for the index, which is
read and set with the atomic_ptr_t operations (16 bits on AVR, with the
previous commit).

Each variable gets a global index on its first use.  Each thread keeps
its copies in an array that its TLS info points to; a copy is made on
the first use from the variable's template, or zeroed.  exit(),
quick_exit() and pthread_exit() free the copies after the exit
functions and the TLS destructors, which may still use them.  They call
the code through a pointer that it sets on its first use, so a program
without __thread variables does not link it.  Without CONFIG_TLS_EMUTLS
there is no pointer and no call.  A thread that gets a new
copy of the TLS info of its parent (vfork()) starts with no copies.
Nothing depends on pthread keys or CONFIG_TLS_NELEM.

With LTO every program links this code (about 800 bytes on Cortex-M;
see the -u above), so the option has a prompt: nucleo-g431rb:nsh, the
one LTO configuration without room for it, disables it.

The --wrap options for ELF programs and modules (the sim Make.defs part
of this commit) come to the CMake build in a separate change.

[skip-cmake-parity]

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
libc now provides its own __emutls_get_address(), so a __thread
variable has one copy per thread also with a single-thread libgcc.  The
TLS guide said that libgcc's emutls implements the keyword.  It now
also says when the copies are freed, that the links use --wrap, and
that code loaded at run time finds the libc version in the system
symbol table.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
Comment thread include/nuttx/atomic.h Resolved
Comment thread libs/libc/tls/Kconfig Resolved
@raiden00pl

Copy link
Copy Markdown
Member

@casaroli @xiaoxiang781216 @GUIDINGLI

This change costs every LTO image ~1.5 KB of flash, even when nothing in the image uses __thread. The -u __wrap___emutls_get_address / -u __wrap___emutls_register_common options force tls_emutls.c into the link, and it also pulls realloc(), memmove() and the semaphore code.

Measured on nucleo-f302r8 with CONFIG_DEFAULT_SMALL=y and CONFIG_LTO_FULL=y, simple hello world, GCC 16.2, master 8a282a5:

flash sram
CONFIG_TLS_EMUTLS=y (default) 23208 B 1160 B
CONFIG_TLS_EMUTLS=n 21752 B 1120 B

That is +1456 B (+6.7%) of flash for a feature the image doesn't use. The smallest image I have (no console, no files) goes from 8.8 KB to 10.1 KB. Without LTO the difference is only 12 B, so the cost comes only from the forced -u symbols.

The PR description mentions ~800 B and one board that overflowed, so the cost was known. But the option defaults to y for everyone, including CONFIG_DEFAULT_SMALL=y configurations, where users expect the smallest image. Most small boards will never use __thread, and users won't know that a new option silently ate 1.5 KB of their flash.

Can we at least make it:

config TLS_EMUTLS
	bool "Per-thread copies of emulated TLS variables"
	default !DEFAULT_SMALL

Even better would be to link this code only when __thread is used, without the unconditional -u for LTO builds.

@raiden00pl raiden00pl mentioned this pull request Nov 18, 2026
1 task done
@acassis

acassis commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

@casaroli @xiaoxiang781216 @GUIDINGLI

This change costs every LTO image ~1.5 KB of flash, even when nothing in the image uses __thread. The -u __wrap___emutls_get_address / -u __wrap___emutls_register_common options force tls_emutls.c into the link, and it also pulls realloc(), memmove() and the semaphore code.

Measured on nucleo-f302r8 with CONFIG_DEFAULT_SMALL=y and CONFIG_LTO_FULL=y, simple hello world, GCC 16.2, master 8a282a5:
flash sram
CONFIG_TLS_EMUTLS=y (default) 23208 B 1160 B
CONFIG_TLS_EMUTLS=n 21752 B 1120 B

That is +1456 B (+6.7%) of flash for a feature the image doesn't use. The smallest image I have (no console, no files) goes from 8.8 KB to 10.1 KB. Without LTO the difference is only 12 B, so the cost comes only from the forced -u symbols.

The PR description mentions ~800 B and one board that overflowed, so the cost was known. But the option defaults to y for everyone, including CONFIG_DEFAULT_SMALL=y configurations, where users expect the smallest image. Most small boards will never use __thread, and users won't know that a new option silently ate 1.5 KB of their flash.

Can we at least make it:

config TLS_EMUTLS
	bool "Per-thread copies of emulated TLS variables"
	default !DEFAULT_SMALL

Even better would be to link this code only when __thread is used, without the unconditional -u for LTO builds.

@casaroli please take a look

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Arch: arm Issues related to ARM (32-bit) architecture Arch: arm64 Issues related to ARM64 (64-bit) architecture Arch: mips Issues related to the MIPS architecture Arch: risc-v Issues related to the RISC-V (32-bit or 64-bit) architecture Arch: simulator Issues related to the SIMulator Arch: sparc Issues related to the SPARC architecture Arch: x86_64 Issues related to the x86_64 architecture Arch: xtensa Issues related to the Xtensa architecture Area: Build system Board: arm Board: simulator Size: L The size of the change in this PR is large

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants