]> git.ipfire.org Git - thirdparty/glibc.git/blobdiff - elf/dl-tls.c
test-container: Fix "unused code" warnings on HURD
[thirdparty/glibc.git] / elf / dl-tls.c
index 576d9a14656d2efcc19f9de28a750fd0b62f3fe3..093cdddb7ed8ff53cf721a1290afe7138d22005e 100644 (file)
@@ -1,5 +1,5 @@
 /* Thread-local storage handling in the ELF dynamic linker.  Generic version.
-   Copyright (C) 2002-2013 Free Software Foundation, Inc.
+   Copyright (C) 2002-2022 Free Software Foundation, Inc.
    This file is part of the GNU C Library.
 
    The GNU C Library is free software; you can redistribute it and/or
@@ -14,7 +14,7 @@
 
    You should have received a copy of the GNU Lesser General Public
    License along with the GNU C Library; if not, see
-   <http://www.gnu.org/licenses/>.  */
+   <https://www.gnu.org/licenses/>.  */
 
 #include <assert.h>
 #include <errno.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <sys/param.h>
+#include <atomic.h>
 
 #include <tls.h>
 #include <dl-tls.h>
 #include <ldsodefs.h>
 
-/* Amount of excess space to allocate in the static TLS area
-   to allow dynamic loading of modules defining IE-model TLS data.  */
-#define TLS_STATIC_SURPLUS     64 + DL_NNS * 100
+#if PTHREAD_IN_LIBC
+# include <list.h>
+#endif
+
+#define TUNABLE_NAMESPACE rtld
+#include <dl-tunables.h>
+
+/* Surplus static TLS, GLRO(dl_tls_static_surplus), is used for
+
+   - IE TLS in libc.so for all dlmopen namespaces except in the initial
+     one where libc.so is not loaded dynamically but at startup time,
+   - IE TLS in other libraries which may be dynamically loaded even in the
+     initial namespace,
+   - and optionally for optimizing dynamic TLS access.
+
+   The maximum number of namespaces is DL_NNS, but to support that many
+   namespaces correctly the static TLS allocation should be significantly
+   increased, which may cause problems with small thread stacks due to the
+   way static TLS is accounted (bug 11787).
+
+   So there is a rtld.nns tunable limit on the number of supported namespaces
+   that affects the size of the static TLS and by default it's small enough
+   not to cause problems with existing applications. The limit is not
+   enforced or checked: it is the user's responsibility to increase rtld.nns
+   if more dlmopen namespaces are used.
+
+   Audit modules use their own namespaces, they are not included in rtld.nns,
+   but come on top when computing the number of namespaces.  */
+
+/* Size of initial-exec TLS in libc.so.  This should be the maximum of
+   observed PT_GNU_TLS sizes across all architectures.  Some
+   architectures have lower values due to differences in type sizes
+   and link editor capabilities.  */
+#define LIBC_IE_TLS 144
+
+/* Size of initial-exec TLS in libraries other than libc.so.
+   This should be large enough to cover runtime libraries of the
+   compiler such as libgomp and libraries in libc other than libc.so.  */
+#define OTHER_IE_TLS 144
+
+/* Default number of namespaces.  */
+#define DEFAULT_NNS 4
 
+/* Default for dl_tls_static_optional.  */
+#define OPTIONAL_TLS 512
+
+/* Compute the static TLS surplus based on the namespace count and the
+   TLS space that can be used for optimizations.  */
+static inline int
+tls_static_surplus (int nns, int opt_tls)
+{
+  return (nns - 1) * LIBC_IE_TLS + nns * OTHER_IE_TLS + opt_tls;
+}
+
+/* This value is chosen so that with default values for the tunables,
+   the computation of dl_tls_static_surplus in
+   _dl_tls_static_surplus_init yields the historic value 1664, for
+   backwards compatibility.  */
+#define LEGACY_TLS (1664 - tls_static_surplus (DEFAULT_NNS, OPTIONAL_TLS))
+
+/* Calculate the size of the static TLS surplus, when the given
+   number of audit modules are loaded.  Must be called after the
+   number of audit modules is known and before static TLS allocation.  */
+void
+_dl_tls_static_surplus_init (size_t naudit)
+{
+  size_t nns, opt_tls;
+
+#if HAVE_TUNABLES
+  nns = TUNABLE_GET (nns, size_t, NULL);
+  opt_tls = TUNABLE_GET (optional_static_tls, size_t, NULL);
+#else
+  /* Default values of the tunables.  */
+  nns = DEFAULT_NNS;
+  opt_tls = OPTIONAL_TLS;
+#endif
+  if (nns > DL_NNS)
+    nns = DL_NNS;
+  if (DL_NNS - nns < naudit)
+    _dl_fatal_printf ("Failed loading %lu audit modules, %lu are supported.\n",
+                     (unsigned long) naudit, (unsigned long) (DL_NNS - nns));
+  nns += naudit;
+
+  GL(dl_tls_static_optional) = opt_tls;
+  assert (LEGACY_TLS >= 0);
+  GLRO(dl_tls_static_surplus) = tls_static_surplus (nns, opt_tls) + LEGACY_TLS;
+}
 
 /* Out-of-memory handler.  */
-#ifdef SHARED
 static void
 __attribute__ ((__noreturn__))
 oom (void)
 {
   _dl_fatal_printf ("cannot allocate memory for thread-local data: ABORT\n");
 }
-#endif
 
 
-size_t
-internal_function
-_dl_next_tls_modid (void)
+void
+_dl_assign_tls_modid (struct link_map *l)
 {
   size_t result;
 
@@ -76,7 +157,11 @@ _dl_next_tls_modid (void)
              }
 
            if (result - disp < runp->len)
-             break;
+             {
+               /* Mark the entry as used, so any dependency see it.  */
+               atomic_store_relaxed (&runp->slotinfo[result - disp].map, l);
+               break;
+             }
 
            disp += runp->len;
          }
@@ -98,19 +183,43 @@ _dl_next_tls_modid (void)
       /* No gaps, allocate a new entry.  */
     nogaps:
 
-      result = ++GL(dl_tls_max_dtv_idx);
+      result = GL(dl_tls_max_dtv_idx) + 1;
+      /* Can be read concurrently.  */
+      atomic_store_relaxed (&GL(dl_tls_max_dtv_idx), result);
     }
 
-  return result;
+  l->l_tls_modid = result;
+}
+
+
+size_t
+_dl_count_modids (void)
+{
+  /* The count is the max unless dlclose or failed dlopen created gaps.  */
+  if (__glibc_likely (!GL(dl_tls_dtv_gaps)))
+    return GL(dl_tls_max_dtv_idx);
+
+  /* We have gaps and are forced to count the non-NULL entries.  */
+  size_t n = 0;
+  struct dtv_slotinfo_list *runp = GL(dl_tls_dtv_slotinfo_list);
+  while (runp != NULL)
+    {
+      for (size_t i = 0; i < runp->len; ++i)
+       if (runp->slotinfo[i].map != NULL)
+         ++n;
+
+      runp = runp->next;
+    }
+
+  return n;
 }
 
 
 #ifdef SHARED
 void
-internal_function
 _dl_determine_tlsoffset (void)
 {
-  size_t max_align = TLS_TCB_ALIGN;
+  size_t max_align = TCB_ALIGNMENT;
   size_t freetop = 0;
   size_t freebottom = 0;
 
@@ -195,8 +304,9 @@ _dl_determine_tlsoffset (void)
     }
 
   GL(dl_tls_static_used) = offset;
-  GL(dl_tls_static_size) = (roundup (offset + TLS_STATIC_SURPLUS, max_align)
-                           + TLS_TCB_SIZE);
+  GLRO (dl_tls_static_size) = (roundup (offset + GLRO(dl_tls_static_surplus),
+                                       max_align)
+                              + TLS_TCB_SIZE);
 #elif TLS_DTV_AT_TP
   /* The TLS blocks start right after the TCB.  */
   size_t offset = TLS_TCB_SIZE;
@@ -239,60 +349,29 @@ _dl_determine_tlsoffset (void)
     }
 
   GL(dl_tls_static_used) = offset;
-  GL(dl_tls_static_size) = roundup (offset + TLS_STATIC_SURPLUS,
-                                   TLS_TCB_ALIGN);
+  GLRO (dl_tls_static_size) = roundup (offset + GLRO(dl_tls_static_surplus),
+                                      TCB_ALIGNMENT);
 #else
 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
 #endif
 
   /* The alignment requirement for the static TLS block.  */
-  GL(dl_tls_static_align) = max_align;
+  GLRO (dl_tls_static_align) = max_align;
 }
-
-
-/* This is called only when the data structure setup was skipped at startup,
-   when there was no need for it then.  Now we have dynamically loaded
-   something needing TLS, or libpthread needs it.  */
-int
-internal_function
-_dl_tls_setup (void)
-{
-  assert (GL(dl_tls_dtv_slotinfo_list) == NULL);
-  assert (GL(dl_tls_max_dtv_idx) == 0);
-
-  const size_t nelem = 2 + TLS_SLOTINFO_SURPLUS;
-
-  GL(dl_tls_dtv_slotinfo_list)
-    = calloc (1, (sizeof (struct dtv_slotinfo_list)
-                 + nelem * sizeof (struct dtv_slotinfo)));
-  if (GL(dl_tls_dtv_slotinfo_list) == NULL)
-    return -1;
-
-  GL(dl_tls_dtv_slotinfo_list)->len = nelem;
-
-  /* Number of elements in the static TLS block.  It can't be zero
-     because of various assumptions.  The one element is null.  */
-  GL(dl_tls_static_nelem) = GL(dl_tls_max_dtv_idx) = 1;
-
-  /* This initializes more variables for us.  */
-  _dl_determine_tlsoffset ();
-
-  return 0;
-}
-rtld_hidden_def (_dl_tls_setup)
-#endif
+#endif /* SHARED */
 
 static void *
-internal_function
 allocate_dtv (void *result)
 {
   dtv_t *dtv;
   size_t dtv_length;
 
+  /* Relaxed MO, because the dtv size is later rechecked, not relied on.  */
+  size_t max_modid = atomic_load_relaxed (&GL(dl_tls_max_dtv_idx));
   /* We allocate a few more elements in the dtv than are needed for the
      initial set of modules.  This should avoid in most cases expansions
      of the dtv.  */
-  dtv_length = GL(dl_tls_max_dtv_idx) + DTV_SURPLUS;
+  dtv_length = max_modid + DTV_SURPLUS;
   dtv = calloc (dtv_length + 2, sizeof (dtv_t));
   if (dtv != NULL)
     {
@@ -311,68 +390,141 @@ allocate_dtv (void *result)
   return result;
 }
 
-
-/* Get size and alignment requirements of the static TLS block.  */
+/* Get size and alignment requirements of the static TLS block.  This
+   function is no longer used by glibc itself, but the GCC sanitizers
+   use it despite the GLIBC_PRIVATE status.  */
 void
-internal_function
 _dl_get_tls_static_info (size_t *sizep, size_t *alignp)
 {
-  *sizep = GL(dl_tls_static_size);
-  *alignp = GL(dl_tls_static_align);
+  *sizep = GLRO (dl_tls_static_size);
+  *alignp = GLRO (dl_tls_static_align);
 }
 
+/* Derive the location of the pointer to the start of the original
+   allocation (before alignment) from the pointer to the TCB.  */
+static inline void **
+tcb_to_pointer_to_free_location (void *tcb)
+{
+#if TLS_TCB_AT_TP
+  /* The TCB follows the TLS blocks, and the pointer to the front
+     follows the TCB.  */
+  void **original_pointer_location = tcb + TLS_TCB_SIZE;
+#elif TLS_DTV_AT_TP
+  /* The TCB comes first, preceded by the pre-TCB, and the pointer is
+     before that.  */
+  void **original_pointer_location = tcb - TLS_PRE_TCB_SIZE - sizeof (void *);
+#endif
+  return original_pointer_location;
+}
 
 void *
-internal_function
 _dl_allocate_tls_storage (void)
 {
   void *result;
-  size_t size = GL(dl_tls_static_size);
+  size_t size = GLRO (dl_tls_static_size);
 
 #if TLS_DTV_AT_TP
   /* Memory layout is:
      [ TLS_PRE_TCB_SIZE ] [ TLS_TCB_SIZE ] [ TLS blocks ]
                          ^ This should be returned.  */
-  size += (TLS_PRE_TCB_SIZE + GL(dl_tls_static_align) - 1)
-         & ~(GL(dl_tls_static_align) - 1);
+  size += TLS_PRE_TCB_SIZE;
 #endif
 
-  /* Allocate a correctly aligned chunk of memory.  */
-  result = __libc_memalign (GL(dl_tls_static_align), size);
-  if (__builtin_expect (result != NULL, 1))
-    {
-      /* Allocate the DTV.  */
-      void *allocated = result;
+  /* Perform the allocation.  Reserve space for the required alignment
+     and the pointer to the original allocation.  */
+  size_t alignment = GLRO (dl_tls_static_align);
+  void *allocated = malloc (size + alignment + sizeof (void *));
+  if (__glibc_unlikely (allocated == NULL))
+    return NULL;
 
+  /* Perform alignment and allocate the DTV.  */
 #if TLS_TCB_AT_TP
-      /* The TCB follows the TLS blocks.  */
-      result = (char *) result + size - TLS_TCB_SIZE;
-
-      /* Clear the TCB data structure.  We can't ask the caller (i.e.
-        libpthread) to do it, because we will initialize the DTV et al.  */
-      memset (result, '\0', TLS_TCB_SIZE);
+  /* The TCB follows the TLS blocks, which determine the alignment.
+     (TCB alignment requirements have been taken into account when
+     calculating GLRO (dl_tls_static_align).)  */
+  void *aligned = (void *) roundup ((uintptr_t) allocated, alignment);
+  result = aligned + size - TLS_TCB_SIZE;
+
+  /* Clear the TCB data structure.  We can't ask the caller (i.e.
+     libpthread) to do it, because we will initialize the DTV et al.  */
+  memset (result, '\0', TLS_TCB_SIZE);
 #elif TLS_DTV_AT_TP
-      result = (char *) result + size - GL(dl_tls_static_size);
+  /* Pre-TCB and TCB come before the TLS blocks.  The layout computed
+     in _dl_determine_tlsoffset assumes that the TCB is aligned to the
+     TLS block alignment, and not just the TLS blocks after it.  This
+     can leave an unused alignment gap between the TCB and the TLS
+     blocks.  */
+  result = (void *) roundup
+    (sizeof (void *) + TLS_PRE_TCB_SIZE + (uintptr_t) allocated,
+     alignment);
+
+  /* Clear the TCB data structure and TLS_PRE_TCB_SIZE bytes before
+     it.  We can't ask the caller (i.e. libpthread) to do it, because
+     we will initialize the DTV et al.  */
+  memset (result - TLS_PRE_TCB_SIZE, '\0', TLS_PRE_TCB_SIZE + TLS_TCB_SIZE);
+#endif
+
+  /* Record the value of the original pointer for later
+     deallocation.  */
+  *tcb_to_pointer_to_free_location (result) = allocated;
 
-      /* Clear the TCB data structure and TLS_PRE_TCB_SIZE bytes before it.
-        We can't ask the caller (i.e. libpthread) to do it, because we will
-        initialize the DTV et al.  */
-      memset ((char *) result - TLS_PRE_TCB_SIZE, '\0',
-             TLS_PRE_TCB_SIZE + TLS_TCB_SIZE);
+  result = allocate_dtv (result);
+  if (result == NULL)
+    free (allocated);
+  return result;
+}
+
+
+#ifndef SHARED
+extern dtv_t _dl_static_dtv[];
+# define _dl_initial_dtv (&_dl_static_dtv[1])
 #endif
 
-      result = allocate_dtv (result);
-      if (result == NULL)
-       free (allocated);
+static dtv_t *
+_dl_resize_dtv (dtv_t *dtv, size_t max_modid)
+{
+  /* Resize the dtv.  */
+  dtv_t *newp;
+  size_t newsize = max_modid + DTV_SURPLUS;
+  size_t oldsize = dtv[-1].counter;
+
+  if (dtv == GL(dl_initial_dtv))
+    {
+      /* This is the initial dtv that was either statically allocated in
+        __libc_setup_tls or allocated during rtld startup using the
+        dl-minimal.c malloc instead of the real malloc.  We can't free
+        it, we have to abandon the old storage.  */
+
+      newp = malloc ((2 + newsize) * sizeof (dtv_t));
+      if (newp == NULL)
+       oom ();
+      memcpy (newp, &dtv[-1], (2 + oldsize) * sizeof (dtv_t));
+    }
+  else
+    {
+      newp = realloc (&dtv[-1],
+                     (2 + newsize) * sizeof (dtv_t));
+      if (newp == NULL)
+       oom ();
     }
 
-  return result;
+  newp[0].counter = newsize;
+
+  /* Clear the newly allocated part.  */
+  memset (newp + 2 + oldsize, '\0',
+         (newsize - oldsize) * sizeof (dtv_t));
+
+  /* Return the generation counter.  */
+  return &newp[1];
 }
 
 
+/* Allocate initial TLS.  RESULT should be a non-NULL pointer to storage
+   for the TLS space.  The DTV may be resized, and so this function may
+   call malloc to allocate that space.  The loader's GL(dl_load_tls_lock)
+   is taken when manipulating global TLS-related data in the loader.  */
 void *
-internal_function
-_dl_allocate_tls_init (void *result)
+_dl_allocate_tls_init (void *result, bool init_tls)
 {
   if (result == NULL)
     /* The memory allocation failed.  */
@@ -383,6 +535,19 @@ _dl_allocate_tls_init (void *result)
   size_t total = 0;
   size_t maxgen = 0;
 
+  /* Protects global dynamic TLS related state.  */
+  __rtld_lock_lock_recursive (GL(dl_load_tls_lock));
+
+  /* Check if the current dtv is big enough.   */
+  if (dtv[-1].counter < GL(dl_tls_max_dtv_idx))
+    {
+      /* Resize the dtv.  */
+      dtv = _dl_resize_dtv (dtv, GL(dl_tls_max_dtv_idx));
+
+      /* Install this new dtv in the thread data structures.  */
+      INSTALL_DTV (result, &dtv[-1]);
+    }
+
   /* We have to prepare the dtv for all currently loaded modules using
      TLS.  For those which are dynamically loaded we add the values
      indicating deferred allocation.  */
@@ -407,19 +572,17 @@ _dl_allocate_tls_init (void *result)
 
          /* Keep track of the maximum generation number.  This might
             not be the generation counter.  */
+         assert (listp->slotinfo[cnt].gen <= GL(dl_tls_generation));
          maxgen = MAX (maxgen, listp->slotinfo[cnt].gen);
 
+         dtv[map->l_tls_modid].pointer.val = TLS_DTV_UNALLOCATED;
+         dtv[map->l_tls_modid].pointer.to_free = NULL;
+
          if (map->l_tls_offset == NO_TLS_OFFSET
              || map->l_tls_offset == FORCED_DYNAMIC_TLS_OFFSET)
-           {
-             /* For dynamically loaded modules we simply store
-                the value indicating deferred allocation.  */
-             dtv[map->l_tls_modid].pointer.val = TLS_DTV_UNALLOCATED;
-             dtv[map->l_tls_modid].pointer.is_static = false;
-             continue;
-           }
+           continue;
 
-         assert (map->l_tls_modid == cnt);
+         assert (map->l_tls_modid == total + cnt);
          assert (map->l_tls_blocksize >= map->l_tls_initimage_size);
 #if TLS_TCB_AT_TP
          assert ((size_t) map->l_tls_offset >= map->l_tls_blocksize);
@@ -430,21 +593,31 @@ _dl_allocate_tls_init (void *result)
 # error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
 #endif
 
-         /* Copy the initialization image and clear the BSS part.  */
+         /* Set up the DTV entry.  The simplified __tls_get_addr that
+            some platforms use in static programs requires it.  */
          dtv[map->l_tls_modid].pointer.val = dest;
-         dtv[map->l_tls_modid].pointer.is_static = true;
+
+         /* Copy the initialization image and clear the BSS part.  For
+            audit modules or dependencies with initial-exec TLS, we can not
+            set the initial TLS image on default loader initialization
+            because it would already be set by the audit setup.  However,
+            subsequent thread creation would need to follow the default
+            behaviour.   */
+         if (map->l_ns != LM_ID_BASE && !init_tls)
+           continue;
          memset (__mempcpy (dest, map->l_tls_initimage,
                             map->l_tls_initimage_size), '\0',
                  map->l_tls_blocksize - map->l_tls_initimage_size);
        }
 
       total += cnt;
-      if (total >= GL(dl_tls_max_dtv_idx))
+      if (total > GL(dl_tls_max_dtv_idx))
        break;
 
       listp = listp->next;
       assert (listp != NULL);
     }
+  __rtld_lock_unlock_recursive (GL(dl_load_tls_lock));
 
   /* The DTV version is up-to-date now.  */
   dtv[0].counter = maxgen;
@@ -454,49 +627,30 @@ _dl_allocate_tls_init (void *result)
 rtld_hidden_def (_dl_allocate_tls_init)
 
 void *
-internal_function
 _dl_allocate_tls (void *mem)
 {
   return _dl_allocate_tls_init (mem == NULL
                                ? _dl_allocate_tls_storage ()
-                               : allocate_dtv (mem));
+                               : allocate_dtv (mem), true);
 }
 rtld_hidden_def (_dl_allocate_tls)
 
 
-#ifndef SHARED
-extern dtv_t _dl_static_dtv[];
-# define _dl_initial_dtv (&_dl_static_dtv[1])
-#endif
-
 void
-internal_function
 _dl_deallocate_tls (void *tcb, bool dealloc_tcb)
 {
   dtv_t *dtv = GET_DTV (tcb);
 
   /* We need to free the memory allocated for non-static TLS.  */
   for (size_t cnt = 0; cnt < dtv[-1].counter; ++cnt)
-    if (! dtv[1 + cnt].pointer.is_static
-       && dtv[1 + cnt].pointer.val != TLS_DTV_UNALLOCATED)
-      free (dtv[1 + cnt].pointer.val);
+    free (dtv[1 + cnt].pointer.to_free);
 
   /* The array starts with dtv[-1].  */
   if (dtv != GL(dl_initial_dtv))
     free (dtv - 1);
 
   if (dealloc_tcb)
-    {
-#if TLS_TCB_AT_TP
-      /* The TCB follows the TLS blocks.  Back up to free the whole block.  */
-      tcb -= GL(dl_tls_static_size) - TLS_TCB_SIZE;
-#elif TLS_DTV_AT_TP
-      /* Back up the TLS_PRE_TCB_SIZE bytes.  */
-      tcb -= (TLS_PRE_TCB_SIZE + GL(dl_tls_static_align) - 1)
-            & ~(GL(dl_tls_static_align) - 1);
-#endif
-      free (tcb);
-    }
+    free (*tcb_to_pointer_to_free_location (tcb));
 }
 rtld_hidden_def (_dl_deallocate_tls)
 
@@ -520,21 +674,49 @@ rtld_hidden_def (_dl_deallocate_tls)
 #  define GET_ADDR_OFFSET ti->ti_offset
 # endif
 
+/* Allocate one DTV entry.  */
+static struct dtv_pointer
+allocate_dtv_entry (size_t alignment, size_t size)
+{
+  if (powerof2 (alignment) && alignment <= _Alignof (max_align_t))
+    {
+      /* The alignment is supported by malloc.  */
+      void *ptr = malloc (size);
+      return (struct dtv_pointer) { ptr, ptr };
+    }
 
-static void *
+  /* Emulate memalign to by manually aligning a pointer returned by
+     malloc.  First compute the size with an overflow check.  */
+  size_t alloc_size = size + alignment;
+  if (alloc_size < size)
+    return (struct dtv_pointer) {};
+
+  /* Perform the allocation.  This is the pointer we need to free
+     later.  */
+  void *start = malloc (alloc_size);
+  if (start == NULL)
+    return (struct dtv_pointer) {};
+
+  /* Find the aligned position within the larger allocation.  */
+  void *aligned = (void *) roundup ((uintptr_t) start, alignment);
+
+  return (struct dtv_pointer) { .val = aligned, .to_free = start };
+}
+
+static struct dtv_pointer
 allocate_and_init (struct link_map *map)
 {
-  void *newp;
-
-  newp = __libc_memalign (map->l_tls_align, map->l_tls_blocksize);
-  if (newp == NULL)
+  struct dtv_pointer result = allocate_dtv_entry
+    (map->l_tls_align, map->l_tls_blocksize);
+  if (result.val == NULL)
     oom ();
 
   /* Initialize the memory.  */
-  memset (__mempcpy (newp, map->l_tls_initimage, map->l_tls_initimage_size),
+  memset (__mempcpy (result.val, map->l_tls_initimage,
+                    map->l_tls_initimage_size),
          '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
 
-  return newp;
+  return result;
 }
 
 
@@ -570,12 +752,29 @@ _dl_update_slotinfo (unsigned long int req_modid)
 
   if (dtv[0].counter < listp->slotinfo[idx].gen)
     {
-      /* The generation counter for the slot is higher than what the
-        current dtv implements.  We have to update the whole dtv but
-        only those entries with a generation counter <= the one for
-        the entry we need.  */
+      /* CONCURRENCY NOTES:
+
+        Here the dtv needs to be updated to new_gen generation count.
+
+        This code may be called during TLS access when GL(dl_load_tls_lock)
+        is not held.  In that case the user code has to synchronize with
+        dlopen and dlclose calls of relevant modules.  A module m is
+        relevant if the generation of m <= new_gen and dlclose of m is
+        synchronized: a memory access here happens after the dlopen and
+        before the dlclose of relevant modules.  The dtv entries for
+        relevant modules need to be updated, other entries can be
+        arbitrary.
+
+        This e.g. means that the first part of the slotinfo list can be
+        accessed race free, but the tail may be concurrently extended.
+        Similarly relevant slotinfo entries can be read race free, but
+        other entries are racy.  However updating a non-relevant dtv
+        entry does not affect correctness.  For a relevant module m,
+        max_modid >= modid of m.  */
       size_t new_gen = listp->slotinfo[idx].gen;
       size_t total = 0;
+      size_t max_modid  = atomic_load_relaxed (&GL(dl_tls_max_dtv_idx));
+      assert (max_modid >= req_modid);
 
       /* We have to look through the entire dtv slotinfo list.  */
       listp =  GL(dl_tls_dtv_slotinfo_list);
@@ -583,12 +782,16 @@ _dl_update_slotinfo (unsigned long int req_modid)
        {
          for (size_t cnt = total == 0 ? 1 : 0; cnt < listp->len; ++cnt)
            {
-             size_t gen = listp->slotinfo[cnt].gen;
+             size_t modid = total + cnt;
+
+             /* Later entries are not relevant.  */
+             if (modid > max_modid)
+               break;
+
+             size_t gen = atomic_load_relaxed (&listp->slotinfo[cnt].gen);
 
              if (gen > new_gen)
-               /* This is a slot for a generation younger than the
-                  one we are handling now.  It might be incompletely
-                  set up so ignore it.  */
+               /* Not relevant.  */
                continue;
 
              /* If the entry is older than the current dtv layout we
@@ -597,61 +800,18 @@ _dl_update_slotinfo (unsigned long int req_modid)
                continue;
 
              /* If there is no map this means the entry is empty.  */
-             struct link_map *map = listp->slotinfo[cnt].map;
-             if (map == NULL)
-               {
-                 /* If this modid was used at some point the memory
-                    might still be allocated.  */
-                 if (! dtv[total + cnt].pointer.is_static
-                     && dtv[total + cnt].pointer.val != TLS_DTV_UNALLOCATED)
-                   {
-                     free (dtv[total + cnt].pointer.val);
-                     dtv[total + cnt].pointer.val = TLS_DTV_UNALLOCATED;
-                   }
-
-                 continue;
-               }
-
+             struct link_map *map
+               = atomic_load_relaxed (&listp->slotinfo[cnt].map);
              /* Check whether the current dtv array is large enough.  */
-             size_t modid = map->l_tls_modid;
-             assert (total + cnt == modid);
              if (dtv[-1].counter < modid)
                {
-                 /* Reallocate the dtv.  */
-                 dtv_t *newp;
-                 size_t newsize = GL(dl_tls_max_dtv_idx) + DTV_SURPLUS;
-                 size_t oldsize = dtv[-1].counter;
-
-                 assert (map->l_tls_modid <= newsize);
-
-                 if (dtv == GL(dl_initial_dtv))
-                   {
-                     /* This is the initial dtv that was allocated
-                        during rtld startup using the dl-minimal.c
-                        malloc instead of the real malloc.  We can't
-                        free it, we have to abandon the old storage.  */
-
-                     newp = malloc ((2 + newsize) * sizeof (dtv_t));
-                     if (newp == NULL)
-                       oom ();
-                     memcpy (newp, &dtv[-1], (2 + oldsize) * sizeof (dtv_t));
-                   }
-                 else
-                   {
-                     newp = realloc (&dtv[-1],
-                                     (2 + newsize) * sizeof (dtv_t));
-                     if (newp == NULL)
-                       oom ();
-                   }
-
-                 newp[0].counter = newsize;
-
-                 /* Clear the newly allocated part.  */
-                 memset (newp + 2 + oldsize, '\0',
-                         (newsize - oldsize) * sizeof (dtv_t));
-
-                 /* Point dtv to the generation counter.  */
-                 dtv = &newp[1];
+                 if (map == NULL)
+                   continue;
+
+                 /* Resize the dtv.  */
+                 dtv = _dl_resize_dtv (dtv, max_modid);
+
+                 assert (modid <= dtv[-1].counter);
 
                  /* Install this new dtv in the thread data
                     structures.  */
@@ -662,26 +822,26 @@ _dl_update_slotinfo (unsigned long int req_modid)
                 dtv entry free it.  */
              /* XXX Ideally we will at some point create a memory
                 pool.  */
-             if (! dtv[modid].pointer.is_static
-                 && dtv[modid].pointer.val != TLS_DTV_UNALLOCATED)
-               /* Note that free is called for NULL is well.  We
-                  deallocate even if it is this dtv entry we are
-                  supposed to load.  The reason is that we call
-                  memalign and not malloc.  */
-               free (dtv[modid].pointer.val);
-
-             /* This module is loaded dynamically- We defer memory
-                allocation.  */
-             dtv[modid].pointer.is_static = false;
+             free (dtv[modid].pointer.to_free);
              dtv[modid].pointer.val = TLS_DTV_UNALLOCATED;
+             dtv[modid].pointer.to_free = NULL;
 
              if (modid == req_modid)
                the_map = map;
            }
 
          total += listp->len;
+         if (total > max_modid)
+           break;
+
+         /* Synchronize with _dl_add_to_slotinfo.  Ideally this would
+            be consume MO since we only need to order the accesses to
+            the next node after the read of the address and on most
+            hardware (other than alpha) a normal load would do that
+            because of the address dependency.  */
+         listp = atomic_load_acquire (&listp->next);
        }
-      while ((listp = listp->next) != NULL);
+      while (listp != NULL);
 
       /* This will be the new maximum generation counter.  */
       dtv[0].counter = new_gen;
@@ -711,38 +871,44 @@ tls_get_addr_tail (GET_ADDR_ARGS, dtv_t *dtv, struct link_map *the_map)
       the_map = listp->slotinfo[idx].map;
     }
 
- again:
   /* Make sure that, if a dlopen running in parallel forces the
      variable into static storage, we'll wait until the address in the
      static TLS block is set up, and use that.  If we're undecided
      yet, make sure we make the decision holding the lock as well.  */
-  if (__builtin_expect (the_map->l_tls_offset
-                       != FORCED_DYNAMIC_TLS_OFFSET, 0))
+  if (__glibc_unlikely (the_map->l_tls_offset
+                       != FORCED_DYNAMIC_TLS_OFFSET))
     {
-      __rtld_lock_lock_recursive (GL(dl_load_lock));
-      if (__builtin_expect (the_map->l_tls_offset == NO_TLS_OFFSET, 1))
+      __rtld_lock_lock_recursive (GL(dl_load_tls_lock));
+      if (__glibc_likely (the_map->l_tls_offset == NO_TLS_OFFSET))
        {
          the_map->l_tls_offset = FORCED_DYNAMIC_TLS_OFFSET;
-         __rtld_lock_unlock_recursive (GL(dl_load_lock));
+         __rtld_lock_unlock_recursive (GL(dl_load_tls_lock));
        }
-      else
+      else if (__glibc_likely (the_map->l_tls_offset
+                              != FORCED_DYNAMIC_TLS_OFFSET))
        {
-         __rtld_lock_unlock_recursive (GL(dl_load_lock));
-         if (__builtin_expect (the_map->l_tls_offset
-                               != FORCED_DYNAMIC_TLS_OFFSET, 1))
-           {
-             void *p = dtv[GET_ADDR_MODULE].pointer.val;
-             if (__builtin_expect (p == TLS_DTV_UNALLOCATED, 0))
-               goto again;
+#if TLS_TCB_AT_TP
+         void *p = (char *) THREAD_SELF - the_map->l_tls_offset;
+#elif TLS_DTV_AT_TP
+         void *p = (char *) THREAD_SELF + the_map->l_tls_offset + TLS_PRE_TCB_SIZE;
+#else
+# error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
+#endif
+         __rtld_lock_unlock_recursive (GL(dl_load_tls_lock));
 
-             return (char *) p + GET_ADDR_OFFSET;
-           }
+         dtv[GET_ADDR_MODULE].pointer.to_free = NULL;
+         dtv[GET_ADDR_MODULE].pointer.val = p;
+
+         return (char *) p + GET_ADDR_OFFSET;
        }
+      else
+       __rtld_lock_unlock_recursive (GL(dl_load_tls_lock));
     }
-  void *p = dtv[GET_ADDR_MODULE].pointer.val = allocate_and_init (the_map);
-  dtv[GET_ADDR_MODULE].pointer.is_static = false;
+  struct dtv_pointer result = allocate_and_init (the_map);
+  dtv[GET_ADDR_MODULE].pointer = result;
+  assert (result.to_free != NULL);
 
-  return (char *) p + GET_ADDR_OFFSET;
+  return (char *) result.val + GET_ADDR_OFFSET;
 }
 
 
@@ -755,12 +921,22 @@ update_get_addr (GET_ADDR_ARGS)
 
   void *p = dtv[GET_ADDR_MODULE].pointer.val;
 
-  if (__builtin_expect (p == TLS_DTV_UNALLOCATED, 0))
+  if (__glibc_unlikely (p == TLS_DTV_UNALLOCATED))
     return tls_get_addr_tail (GET_ADDR_PARAM, dtv, the_map);
 
   return (void *) p + GET_ADDR_OFFSET;
 }
 
+/* For all machines that have a non-macro version of __tls_get_addr, we
+   want to use rtld_hidden_proto/rtld_hidden_def in order to call the
+   internal alias for __tls_get_addr from ld.so. This avoids a PLT entry
+   in ld.so for __tls_get_addr.  */
+
+#ifndef __tls_get_addr
+extern void * __tls_get_addr (GET_ADDR_ARGS);
+rtld_hidden_proto (__tls_get_addr)
+rtld_hidden_def (__tls_get_addr)
+#endif
 
 /* The generic dynamic and local dynamic model cannot be used in
    statically linked applications.  */
@@ -769,12 +945,17 @@ __tls_get_addr (GET_ADDR_ARGS)
 {
   dtv_t *dtv = THREAD_DTV ();
 
-  if (__builtin_expect (dtv[0].counter != GL(dl_tls_generation), 0))
+  /* Update is needed if dtv[0].counter < the generation of the accessed
+     module.  The global generation counter is used here as it is easier
+     to check.  Synchronization for the relaxed MO access is guaranteed
+     by user code, see CONCURRENCY NOTES in _dl_update_slotinfo.  */
+  size_t gen = atomic_load_relaxed (&GL(dl_tls_generation));
+  if (__glibc_unlikely (dtv[0].counter != gen))
     return update_get_addr (GET_ADDR_PARAM);
 
   void *p = dtv[GET_ADDR_MODULE].pointer.val;
 
-  if (__builtin_expect (p == TLS_DTV_UNALLOCATED, 0))
+  if (__glibc_unlikely (p == TLS_DTV_UNALLOCATED))
     return tls_get_addr_tail (GET_ADDR_PARAM, dtv, NULL);
 
   return (char *) p + GET_ADDR_OFFSET;
@@ -787,12 +968,15 @@ __tls_get_addr (GET_ADDR_ARGS)
 void *
 _dl_tls_get_addr_soft (struct link_map *l)
 {
-  if (__builtin_expect (l->l_tls_modid == 0, 0))
+  if (__glibc_unlikely (l->l_tls_modid == 0))
     /* This module has no TLS segment.  */
     return NULL;
 
   dtv_t *dtv = THREAD_DTV ();
-  if (__builtin_expect (dtv[0].counter != GL(dl_tls_generation), 0))
+  /* This may be called without holding the GL(dl_load_tls_lock).  Reading
+     arbitrary gen value is fine since this is best effort code.  */
+  size_t gen = atomic_load_relaxed (&GL(dl_tls_generation));
+  if (__glibc_unlikely (dtv[0].counter != gen))
     {
       /* This thread's DTV is not completely current,
         but it might already cover this module.  */
@@ -817,7 +1001,7 @@ _dl_tls_get_addr_soft (struct link_map *l)
     }
 
   void *data = dtv[l->l_tls_modid].pointer.val;
-  if (__builtin_expect (data == TLS_DTV_UNALLOCATED, 0))
+  if (__glibc_unlikely (data == TLS_DTV_UNALLOCATED))
     /* The DTV is current, but this thread has not yet needed
        to allocate this module's segment.  */
     data = NULL;
@@ -827,7 +1011,7 @@ _dl_tls_get_addr_soft (struct link_map *l)
 
 
 void
-_dl_add_to_slotinfo (struct link_map *l)
+_dl_add_to_slotinfo (struct link_map *l, bool do_add)
 {
   /* Now that we know the object is loaded successfully add
      modules containing TLS data to the dtv info table.  We
@@ -857,21 +1041,12 @@ _dl_add_to_slotinfo (struct link_map *l)
         the first slot.  */
       assert (idx == 0);
 
-      listp = prevp->next = (struct dtv_slotinfo_list *)
+      listp = (struct dtv_slotinfo_list *)
        malloc (sizeof (struct dtv_slotinfo_list)
                + TLS_SLOTINFO_SURPLUS * sizeof (struct dtv_slotinfo));
       if (listp == NULL)
        {
-         /* We ran out of memory.  We will simply fail this
-            call but don't undo anything we did so far.  The
-            application will crash or be terminated anyway very
-            soon.  */
-
-         /* We have to do this since some entries in the dtv
-            slotinfo array might already point to this
-            generation.  */
-         ++GL(dl_tls_generation);
-
+         /* We ran out of memory while resizing the dtv slotinfo list.  */
          _dl_signal_error (ENOMEM, "dlopen", NULL, N_("\
 cannot create TLS data structures"));
        }
@@ -880,9 +1055,51 @@ cannot create TLS data structures"));
       listp->next = NULL;
       memset (listp->slotinfo, '\0',
              TLS_SLOTINFO_SURPLUS * sizeof (struct dtv_slotinfo));
+      /* Synchronize with _dl_update_slotinfo.  */
+      atomic_store_release (&prevp->next, listp);
     }
 
   /* Add the information into the slotinfo data structure.  */
-  listp->slotinfo[idx].map = l;
-  listp->slotinfo[idx].gen = GL(dl_tls_generation) + 1;
+  if (do_add)
+    {
+      /* Can be read concurrently.  See _dl_update_slotinfo.  */
+      atomic_store_relaxed (&listp->slotinfo[idx].map, l);
+      atomic_store_relaxed (&listp->slotinfo[idx].gen,
+                           GL(dl_tls_generation) + 1);
+    }
+}
+
+#if PTHREAD_IN_LIBC
+static inline void __attribute__((always_inline))
+init_one_static_tls (struct pthread *curp, struct link_map *map)
+{
+# if TLS_TCB_AT_TP
+  void *dest = (char *) curp - map->l_tls_offset;
+# elif TLS_DTV_AT_TP
+  void *dest = (char *) curp + map->l_tls_offset + TLS_PRE_TCB_SIZE;
+# else
+#  error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
+# endif
+
+  /* Initialize the memory.  */
+  memset (__mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
+         '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
+}
+
+void
+_dl_init_static_tls (struct link_map *map)
+{
+  lll_lock (GL (dl_stack_cache_lock), LLL_PRIVATE);
+
+  /* Iterate over the list with system-allocated threads first.  */
+  list_t *runp;
+  list_for_each (runp, &GL (dl_stack_used))
+    init_one_static_tls (list_entry (runp, struct pthread, list), map);
+
+  /* Now the list with threads using user-allocated stacks.  */
+  list_for_each (runp, &GL (dl_stack_user))
+    init_one_static_tls (list_entry (runp, struct pthread, list), map);
+
+  lll_unlock (GL (dl_stack_cache_lock), LLL_PRIVATE);
 }
+#endif /* PTHREAD_IN_LIBC */