94084c
commit 15a0c5730d1d5aeb95f50c9ec7470640084feae8
94084c
Author: Chung-Lin Tang <cltang@codesourcery.com>
94084c
Date:   Thu Oct 21 21:41:22 2021 +0800
94084c
94084c
    elf: Fix slow DSO sorting behavior in dynamic loader (BZ #17645)
94084c
    
94084c
    This second patch contains the actual implementation of a new sorting algorithm
94084c
    for shared objects in the dynamic loader, which solves the slow behavior that
94084c
    the current "old" algorithm falls into when the DSO set contains circular
94084c
    dependencies.
94084c
    
94084c
    The new algorithm implemented here is simply depth-first search (DFS) to obtain
94084c
    the Reverse-Post Order (RPO) sequence, a topological sort. A new l_visited:1
94084c
    bitfield is added to struct link_map to more elegantly facilitate such a search.
94084c
    
94084c
    The DFS algorithm is applied to the input maps[nmap-1] backwards towards
94084c
    maps[0]. This has the effect of a more "shallow" recursion depth in general
94084c
    since the input is in BFS. Also, when combined with the natural order of
94084c
    processing l_initfini[] at each node, this creates a resulting output sorting
94084c
    closer to the intuitive "left-to-right" order in most cases.
94084c
    
94084c
    Another notable implementation adjustment related to this _dl_sort_maps change
94084c
    is the removing of two char arrays 'used' and 'done' in _dl_close_worker to
94084c
    represent two per-map attributes. This has been changed to simply use two new
94084c
    bit-fields l_map_used:1, l_map_done:1 added to struct link_map. This also allows
94084c
    discarding the clunky 'used' array sorting that _dl_sort_maps had to sometimes
94084c
    do along the way.
94084c
    
94084c
    Tunable support for switching between different sorting algorithms at runtime is
94084c
    also added. A new tunable 'glibc.rtld.dynamic_sort' with current valid values 1
94084c
    (old algorithm) and 2 (new DFS algorithm) has been added. At time of commit
94084c
    of this patch, the default setting is 1 (old algorithm).
94084c
    
94084c
    Signed-off-by: Chung-Lin Tang  <cltang@codesourcery.com>
94084c
    Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
94084c
94084c
diff --git a/elf/dl-close.c b/elf/dl-close.c
94084c
index cd7b9c9fe83a1a44..f6fbf9de7d78555b 100644
94084c
--- a/elf/dl-close.c
94084c
+++ b/elf/dl-close.c
94084c
@@ -167,8 +167,6 @@ _dl_close_worker (struct link_map *map, bool force)
94084c
 
94084c
   bool any_tls = false;
94084c
   const unsigned int nloaded = ns->_ns_nloaded;
94084c
-  char used[nloaded];
94084c
-  char done[nloaded];
94084c
   struct link_map *maps[nloaded];
94084c
 
94084c
   /* Run over the list and assign indexes to the link maps and enter
94084c
@@ -176,24 +174,21 @@ _dl_close_worker (struct link_map *map, bool force)
94084c
   int idx = 0;
94084c
   for (struct link_map *l = ns->_ns_loaded; l != NULL; l = l->l_next)
94084c
     {
94084c
+      l->l_map_used = 0;
94084c
+      l->l_map_done = 0;
94084c
       l->l_idx = idx;
94084c
       maps[idx] = l;
94084c
       ++idx;
94084c
-
94084c
     }
94084c
   assert (idx == nloaded);
94084c
 
94084c
-  /* Prepare the bitmaps.  */
94084c
-  memset (used, '\0', sizeof (used));
94084c
-  memset (done, '\0', sizeof (done));
94084c
-
94084c
   /* Keep track of the lowest index link map we have covered already.  */
94084c
   int done_index = -1;
94084c
   while (++done_index < nloaded)
94084c
     {
94084c
       struct link_map *l = maps[done_index];
94084c
 
94084c
-      if (done[done_index])
94084c
+      if (l->l_map_done)
94084c
 	/* Already handled.  */
94084c
 	continue;
94084c
 
94084c
@@ -204,12 +199,12 @@ _dl_close_worker (struct link_map *map, bool force)
94084c
 	  /* See CONCURRENCY NOTES in cxa_thread_atexit_impl.c to know why
94084c
 	     acquire is sufficient and correct.  */
94084c
 	  && atomic_load_acquire (&l->l_tls_dtor_count) == 0
94084c
-	  && !used[done_index])
94084c
+	  && !l->l_map_used)
94084c
 	continue;
94084c
 
94084c
       /* We need this object and we handle it now.  */
94084c
-      done[done_index] = 1;
94084c
-      used[done_index] = 1;
94084c
+      l->l_map_used = 1;
94084c
+      l->l_map_done = 1;
94084c
       /* Signal the object is still needed.  */
94084c
       l->l_idx = IDX_STILL_USED;
94084c
 
94084c
@@ -225,9 +220,9 @@ _dl_close_worker (struct link_map *map, bool force)
94084c
 		{
94084c
 		  assert ((*lp)->l_idx >= 0 && (*lp)->l_idx < nloaded);
94084c
 
94084c
-		  if (!used[(*lp)->l_idx])
94084c
+		  if (!(*lp)->l_map_used)
94084c
 		    {
94084c
-		      used[(*lp)->l_idx] = 1;
94084c
+		      (*lp)->l_map_used = 1;
94084c
 		      /* If we marked a new object as used, and we've
94084c
 			 already processed it, then we need to go back
94084c
 			 and process again from that point forward to
94084c
@@ -250,9 +245,9 @@ _dl_close_worker (struct link_map *map, bool force)
94084c
 	      {
94084c
 		assert (jmap->l_idx >= 0 && jmap->l_idx < nloaded);
94084c
 
94084c
-		if (!used[jmap->l_idx])
94084c
+		if (!jmap->l_map_used)
94084c
 		  {
94084c
-		    used[jmap->l_idx] = 1;
94084c
+		    jmap->l_map_used = 1;
94084c
 		    if (jmap->l_idx - 1 < done_index)
94084c
 		      done_index = jmap->l_idx - 1;
94084c
 		  }
94084c
@@ -262,8 +257,7 @@ _dl_close_worker (struct link_map *map, bool force)
94084c
 
94084c
   /* Sort the entries.  We can skip looking for the binary itself which is
94084c
      at the front of the search list for the main namespace.  */
94084c
-  _dl_sort_maps (maps + (nsid == LM_ID_BASE), nloaded - (nsid == LM_ID_BASE),
94084c
-		 used + (nsid == LM_ID_BASE), true);
94084c
+  _dl_sort_maps (maps, nloaded, (nsid == LM_ID_BASE), true);
94084c
 
94084c
   /* Call all termination functions at once.  */
94084c
 #ifdef SHARED
94084c
@@ -280,7 +274,7 @@ _dl_close_worker (struct link_map *map, bool force)
94084c
       /* All elements must be in the same namespace.  */
94084c
       assert (imap->l_ns == nsid);
94084c
 
94084c
-      if (!used[i])
94084c
+      if (!imap->l_map_used)
94084c
 	{
94084c
 	  assert (imap->l_type == lt_loaded && !imap->l_nodelete_active);
94084c
 
94084c
@@ -333,7 +327,7 @@ _dl_close_worker (struct link_map *map, bool force)
94084c
 	  if (i < first_loaded)
94084c
 	    first_loaded = i;
94084c
 	}
94084c
-      /* Else used[i].  */
94084c
+      /* Else imap->l_map_used.  */
94084c
       else if (imap->l_type == lt_loaded)
94084c
 	{
94084c
 	  struct r_scope_elem *new_list = NULL;
94084c
@@ -560,7 +554,7 @@ _dl_close_worker (struct link_map *map, bool force)
94084c
   for (unsigned int i = first_loaded; i < nloaded; ++i)
94084c
     {
94084c
       struct link_map *imap = maps[i];
94084c
-      if (!used[i])
94084c
+      if (!imap->l_map_used)
94084c
 	{
94084c
 	  assert (imap->l_type == lt_loaded);
94084c
 
94084c
diff --git a/elf/dl-deps.c b/elf/dl-deps.c
94084c
index 087a49b212a96920..237d9636c5be780c 100644
94084c
--- a/elf/dl-deps.c
94084c
+++ b/elf/dl-deps.c
94084c
@@ -613,10 +613,9 @@ Filters not supported with LD_TRACE_PRELINKING"));
94084c
 
94084c
   /* If libc.so.6 is the main map, it participates in the sort, so
94084c
      that the relocation order is correct regarding libc.so.6.  */
94084c
-  if (l_initfini[0] == GL (dl_ns)[l_initfini[0]->l_ns].libc_map)
94084c
-    _dl_sort_maps (l_initfini, nlist, NULL, false);
94084c
-  else
94084c
-    _dl_sort_maps (&l_initfini[1], nlist - 1, NULL, false);
94084c
+  _dl_sort_maps (l_initfini, nlist,
94084c
+		 (l_initfini[0] != GL (dl_ns)[l_initfini[0]->l_ns].libc_map),
94084c
+		 false);
94084c
 
94084c
   /* Terminate the list of dependencies.  */
94084c
   l_initfini[nlist] = NULL;
94084c
diff --git a/elf/dl-fini.c b/elf/dl-fini.c
94084c
index 6dbdfe4b3ebbeb89..c683884c355dfd52 100644
94084c
--- a/elf/dl-fini.c
94084c
+++ b/elf/dl-fini.c
94084c
@@ -92,8 +92,7 @@ _dl_fini (void)
94084c
 	  /* Now we have to do the sorting.  We can skip looking for the
94084c
 	     binary itself which is at the front of the search list for
94084c
 	     the main namespace.  */
94084c
-	  _dl_sort_maps (maps + (ns == LM_ID_BASE), nmaps - (ns == LM_ID_BASE),
94084c
-			 NULL, true);
94084c
+	  _dl_sort_maps (maps, nmaps, (ns == LM_ID_BASE), true);
94084c
 
94084c
 	  /* We do not rely on the linked list of loaded object anymore
94084c
 	     from this point on.  We have our own list here (maps).  The
94084c
diff --git a/elf/dl-sort-maps.c b/elf/dl-sort-maps.c
94084c
index d21770267a37e128..a274ed66cc987735 100644
94084c
--- a/elf/dl-sort-maps.c
94084c
+++ b/elf/dl-sort-maps.c
94084c
@@ -16,16 +16,24 @@
94084c
    License along with the GNU C Library; if not, see
94084c
    <https://www.gnu.org/licenses/>.  */
94084c
 
94084c
+#include <assert.h>
94084c
 #include <ldsodefs.h>
94084c
+#include <elf/dl-tunables.h>
94084c
 
94084c
+/* Note: this is the older, "original" sorting algorithm, being used as
94084c
+   default up to 2.35.
94084c
 
94084c
-/* Sort array MAPS according to dependencies of the contained objects.
94084c
-   Array USED, if non-NULL, is permutated along MAPS.  If FOR_FINI this is
94084c
-   called for finishing an object.  */
94084c
-void
94084c
-_dl_sort_maps (struct link_map **maps, unsigned int nmaps, char *used,
94084c
-	       bool for_fini)
94084c
+   Sort array MAPS according to dependencies of the contained objects.
94084c
+   If FOR_FINI is true, this is called for finishing an object.  */
94084c
+static void
94084c
+_dl_sort_maps_original (struct link_map **maps, unsigned int nmaps,
94084c
+			unsigned int skip, bool for_fini)
94084c
 {
94084c
+  /* Allows caller to do the common optimization of skipping the first map,
94084c
+     usually the main binary.  */
94084c
+  maps += skip;
94084c
+  nmaps -= skip;
94084c
+
94084c
   /* A list of one element need not be sorted.  */
94084c
   if (nmaps <= 1)
94084c
     return;
94084c
@@ -66,14 +74,6 @@ _dl_sort_maps (struct link_map **maps, unsigned int nmaps, char *used,
94084c
 			   (k - i) * sizeof (maps[0]));
94084c
 		  maps[k] = thisp;
94084c
 
94084c
-		  if (used != NULL)
94084c
-		    {
94084c
-		      char here_used = used[i];
94084c
-		      memmove (&used[i], &used[i + 1],
94084c
-			       (k - i) * sizeof (used[0]));
94084c
-		      used[k] = here_used;
94084c
-		    }
94084c
-
94084c
 		  if (seen[i + 1] > nmaps - i)
94084c
 		    {
94084c
 		      ++i;
94084c
@@ -120,3 +120,183 @@ _dl_sort_maps (struct link_map **maps, unsigned int nmaps, char *used,
94084c
     next:;
94084c
     }
94084c
 }
94084c
+
94084c
+#if !HAVE_TUNABLES
94084c
+/* In this case, just default to the original algorithm.  */
94084c
+strong_alias (_dl_sort_maps_original, _dl_sort_maps);
94084c
+#else
94084c
+
94084c
+/* We use a recursive function due to its better clarity and ease of
94084c
+   implementation, as well as faster execution speed. We already use
94084c
+   alloca() for list allocation during the breadth-first search of
94084c
+   dependencies in _dl_map_object_deps(), and this should be on the
94084c
+   same order of worst-case stack usage.
94084c
+
94084c
+   Note: the '*rpo' parameter is supposed to point to one past the
94084c
+   last element of the array where we save the sort results, and is
94084c
+   decremented before storing the current map at each level.  */
94084c
+
94084c
+static void
94084c
+dfs_traversal (struct link_map ***rpo, struct link_map *map,
94084c
+	       bool *do_reldeps)
94084c
+{
94084c
+  if (map->l_visited)
94084c
+    return;
94084c
+
94084c
+  map->l_visited = 1;
94084c
+
94084c
+  if (map->l_initfini)
94084c
+    {
94084c
+      for (int i = 0; map->l_initfini[i] != NULL; i++)
94084c
+	{
94084c
+	  struct link_map *dep = map->l_initfini[i];
94084c
+	  if (dep->l_visited == 0
94084c
+	      && dep->l_main_map == 0)
94084c
+	    dfs_traversal (rpo, dep, do_reldeps);
94084c
+	}
94084c
+    }
94084c
+
94084c
+  if (__glibc_unlikely (do_reldeps != NULL && map->l_reldeps != NULL))
94084c
+    {
94084c
+      /* Indicate that we encountered relocation dependencies during
94084c
+	 traversal.  */
94084c
+      *do_reldeps = true;
94084c
+
94084c
+      for (int m = map->l_reldeps->act - 1; m >= 0; m--)
94084c
+	{
94084c
+	  struct link_map *dep = map->l_reldeps->list[m];
94084c
+	  if (dep->l_visited == 0
94084c
+	      && dep->l_main_map == 0)
94084c
+	    dfs_traversal (rpo, dep, do_reldeps);
94084c
+	}
94084c
+    }
94084c
+
94084c
+  *rpo -= 1;
94084c
+  **rpo = map;
94084c
+}
94084c
+
94084c
+/* Topologically sort array MAPS according to dependencies of the contained
94084c
+   objects.  */
94084c
+
94084c
+static void
94084c
+_dl_sort_maps_dfs (struct link_map **maps, unsigned int nmaps,
94084c
+		   unsigned int skip __attribute__ ((unused)), bool for_fini)
94084c
+{
94084c
+  for (int i = nmaps - 1; i >= 0; i--)
94084c
+    maps[i]->l_visited = 0;
94084c
+
94084c
+  /* We apply DFS traversal for each of maps[i] until the whole total order
94084c
+     is found and we're at the start of the Reverse-Postorder (RPO) sequence,
94084c
+     which is a topological sort.
94084c
+
94084c
+     We go from maps[nmaps - 1] backwards towards maps[0] at this level.
94084c
+     Due to the breadth-first search (BFS) ordering we receive, going
94084c
+     backwards usually gives a more shallow depth-first recursion depth,
94084c
+     adding more stack usage safety. Also, combined with the natural
94084c
+     processing order of l_initfini[] at each node during DFS, this maintains
94084c
+     an ordering closer to the original link ordering in the sorting results
94084c
+     under most simpler cases.
94084c
+
94084c
+     Another reason we order the top level backwards, it that maps[0] is
94084c
+     usually exactly the main object of which we're in the midst of
94084c
+     _dl_map_object_deps() processing, and maps[0]->l_initfini[] is still
94084c
+     blank. If we start the traversal from maps[0], since having no
94084c
+     dependencies yet filled in, maps[0] will always be immediately
94084c
+     incorrectly placed at the last place in the order (first in reverse).
94084c
+     Adjusting the order so that maps[0] is last traversed naturally avoids
94084c
+     this problem.
94084c
+
94084c
+     Further, the old "optimization" of skipping the main object at maps[0]
94084c
+     from the call-site (i.e. _dl_sort_maps(maps+1,nmaps-1)) is in general
94084c
+     no longer valid, since traversing along object dependency-links
94084c
+     may "find" the main object even when it is not included in the initial
94084c
+     order (e.g. a dlopen()'ed shared object can have circular dependencies
94084c
+     linked back to itself). In such a case, traversing N-1 objects will
94084c
+     create a N-object result, and raise problems.
94084c
+
94084c
+     To summarize, just passing in the full list, and iterating from back
94084c
+     to front makes things much more straightforward.  */
94084c
+
94084c
+  /* Array to hold RPO sorting results, before we copy back to maps[].  */
94084c
+  struct link_map *rpo[nmaps];
94084c
+
94084c
+  /* The 'head' position during each DFS iteration. Note that we start at
94084c
+     one past the last element due to first-decrement-then-store (see the
94084c
+     bottom of above dfs_traversal() routine).  */
94084c
+  struct link_map **rpo_head = &rpo[nmaps];
94084c
+
94084c
+  bool do_reldeps = false;
94084c
+  bool *do_reldeps_ref = (for_fini ? &do_reldeps : NULL);
94084c
+
94084c
+  for (int i = nmaps - 1; i >= 0; i--)
94084c
+    {
94084c
+      dfs_traversal (&rpo_head, maps[i], do_reldeps_ref);
94084c
+
94084c
+      /* We can break early if all objects are already placed.  */
94084c
+      if (rpo_head == rpo)
94084c
+	goto end;
94084c
+    }
94084c
+  assert (rpo_head == rpo);
94084c
+
94084c
+ end:
94084c
+  /* Here we may do a second pass of sorting, using only l_initfini[]
94084c
+     static dependency links. This is avoided if !FOR_FINI or if we didn't
94084c
+     find any reldeps in the first DFS traversal.
94084c
+
94084c
+     The reason we do this is: while it is unspecified how circular
94084c
+     dependencies should be handled, the presumed reasonable behavior is to
94084c
+     have destructors to respect static dependency links as much as possible,
94084c
+     overriding reldeps if needed. And the first sorting pass, which takes
94084c
+     l_initfini/l_reldeps links equally, may not preserve this priority.
94084c
+
94084c
+     Hence we do a 2nd sorting pass, taking only DT_NEEDED links into account
94084c
+     (see how the do_reldeps argument to dfs_traversal() is NULL below).  */
94084c
+  if (do_reldeps)
94084c
+    {
94084c
+      for (int i = nmaps - 1; i >= 0; i--)
94084c
+	rpo[i]->l_visited = 0;
94084c
+
94084c
+      struct link_map **maps_head = &maps[nmaps];
94084c
+      for (int i = nmaps - 1; i >= 0; i--)
94084c
+	{
94084c
+	  dfs_traversal (&maps_head, rpo[i], NULL);
94084c
+
94084c
+	  /* We can break early if all objects are already placed.
94084c
+	     The below memcpy is not needed in the do_reldeps case here,
94084c
+	     since we wrote back to maps[] during DFS traversal.  */
94084c
+	  if (maps_head == maps)
94084c
+	    return;
94084c
+	}
94084c
+      assert (maps_head == maps);
94084c
+      return;
94084c
+    }
94084c
+
94084c
+  memcpy (maps, rpo, sizeof (struct link_map *) * nmaps);
94084c
+}
94084c
+
94084c
+void
94084c
+_dl_sort_maps_init (void)
94084c
+{
94084c
+  int32_t algorithm = TUNABLE_GET (glibc, rtld, dynamic_sort, int32_t, NULL);
94084c
+  GLRO(dl_dso_sort_algo) = algorithm == 1 ? dso_sort_algorithm_original
94084c
+					  : dso_sort_algorithm_dfs;
94084c
+}
94084c
+
94084c
+void
94084c
+_dl_sort_maps (struct link_map **maps, unsigned int nmaps,
94084c
+	       unsigned int skip, bool for_fini)
94084c
+{
94084c
+  /* It can be tempting to use a static function pointer to store and call
94084c
+     the current selected sorting algorithm routine, but experimentation
94084c
+     shows that current processors still do not handle indirect branches
94084c
+     that efficiently, plus a static function pointer will involve
94084c
+     PTR_MANGLE/DEMANGLE, further impairing performance of small, common
94084c
+     input cases. A simple if-case with direct function calls appears to
94084c
+     be the fastest.  */
94084c
+  if (__glibc_likely (GLRO(dl_dso_sort_algo) == dso_sort_algorithm_original))
94084c
+    _dl_sort_maps_original (maps, nmaps, skip, for_fini);
94084c
+  else
94084c
+    _dl_sort_maps_dfs (maps, nmaps, skip, for_fini);
94084c
+}
94084c
+
94084c
+#endif /* HAVE_TUNABLES.  */
94084c
diff --git a/elf/dl-support.c b/elf/dl-support.c
94084c
index d8c06ba7eb4c76ea..c5ee5d33aa7e1d65 100644
94084c
--- a/elf/dl-support.c
94084c
+++ b/elf/dl-support.c
94084c
@@ -166,6 +166,8 @@ size_t _dl_phnum;
94084c
 uint64_t _dl_hwcap;
94084c
 uint64_t _dl_hwcap2;
94084c
 
94084c
+enum dso_sort_algorithm _dl_dso_sort_algo;
94084c
+
94084c
 /* The value of the FPU control word the kernel will preset in hardware.  */
94084c
 fpu_control_t _dl_fpu_control = _FPU_DEFAULT;
94084c
 
94084c
diff --git a/elf/dl-sysdep.c b/elf/dl-sysdep.c
94084c
index 2c684c2db2a1f59b..4dc366eea445e974 100644
94084c
--- a/elf/dl-sysdep.c
94084c
+++ b/elf/dl-sysdep.c
94084c
@@ -231,6 +231,9 @@ _dl_sysdep_start (void **start_argptr,
94084c
 
94084c
   __tunables_init (_environ);
94084c
 
94084c
+  /* Initialize DSO sorting algorithm after tunables.  */
94084c
+  _dl_sort_maps_init ();
94084c
+
94084c
 #ifdef DL_SYSDEP_INIT
94084c
   DL_SYSDEP_INIT;
94084c
 #endif
94084c
diff --git a/elf/dl-tunables.list b/elf/dl-tunables.list
94084c
index 8ddd4a23142a941b..46ffb2378416f90f 100644
94084c
--- a/elf/dl-tunables.list
94084c
+++ b/elf/dl-tunables.list
94084c
@@ -156,4 +156,13 @@ glibc {
94084c
       security_level: SXID_IGNORE
94084c
     }
94084c
   }
94084c
+
94084c
+  rtld {
94084c
+    dynamic_sort {
94084c
+      type: INT_32
94084c
+      minval: 1
94084c
+      maxval: 2
94084c
+      default: 1
94084c
+    }
94084c
+  }
94084c
 }
94084c
diff --git a/elf/dso-sort-tests-1.def b/elf/dso-sort-tests-1.def
94084c
index 873ddf55d91155c6..5f7f18ef270bc12d 100644
94084c
--- a/elf/dso-sort-tests-1.def
94084c
+++ b/elf/dso-sort-tests-1.def
94084c
@@ -62,5 +62,5 @@ output: b>a>{}
94084c
 # The below expected outputs are what the two algorithms currently produce
94084c
 # respectively, for regression testing purposes.
94084c
 tst-bz15311: {+a;+e;+f;+g;+d;%d;-d;-g;-f;-e;-a};a->b->c->d;d=>[ba];c=>a;b=>e=>a;c=>f=>b;d=>g=>c
94084c
-xfail_output(glibc.rtld.dynamic_sort=1): {+a[d>c>b>a>];+e[e>];+f[f>];+g[g>];+d[];%d(b(e(a()))a()g(c(a()f(b(e(a()))))));-d[];-g[];-f[];-e[];-a[
94084c
+output(glibc.rtld.dynamic_sort=1): {+a[d>c>b>a>];+e[e>];+f[f>];+g[g>];+d[];%d(b(e(a()))a()g(c(a()f(b(e(a()))))));-d[];-g[];-f[];-e[];-a[
94084c
 output(glibc.rtld.dynamic_sort=2): {+a[d>c>b>a>];+e[e>];+f[f>];+g[g>];+d[];%d(b(e(a()))a()g(c(a()f(b(e(a()))))));-d[];-g[];-f[];-e[];-a[
94084c
diff --git a/elf/rtld.c b/elf/rtld.c
94084c
index 6bbb373c5743cb99..84eac9a8df7125a6 100644
94084c
--- a/elf/rtld.c
94084c
+++ b/elf/rtld.c
94084c
@@ -1426,6 +1426,9 @@ dl_main (const ElfW(Phdr) *phdr,
94084c
       main_map->l_name = (char *) "";
94084c
       *user_entry = main_map->l_entry;
94084c
 
94084c
+      /* Set bit indicating this is the main program map.  */
94084c
+      main_map->l_main_map = 1;
94084c
+
94084c
 #ifdef HAVE_AUX_VECTOR
94084c
       /* Adjust the on-stack auxiliary vector so that it looks like the
94084c
 	 binary was executed directly.  */
94084c
diff --git a/elf/tst-rtld-list-tunables.exp b/elf/tst-rtld-list-tunables.exp
94084c
index 9f66c528855fb21d..9bf572715f996ca6 100644
94084c
--- a/elf/tst-rtld-list-tunables.exp
94084c
+++ b/elf/tst-rtld-list-tunables.exp
94084c
@@ -10,5 +10,6 @@ glibc.malloc.tcache_max: 0x0 (min: 0x0, max: 0x[f]+)
94084c
 glibc.malloc.tcache_unsorted_limit: 0x0 (min: 0x0, max: 0x[f]+)
94084c
 glibc.malloc.top_pad: 0x0 (min: 0x0, max: 0x[f]+)
94084c
 glibc.malloc.trim_threshold: 0x0 (min: 0x0, max: 0x[f]+)
94084c
+glibc.rtld.dynamic_sort: 1 (min: 1, max: 2)
94084c
 glibc.rtld.nns: 0x4 (min: 0x1, max: 0x10)
94084c
 glibc.rtld.optional_static_tls: 0x200 (min: 0x0, max: 0x[f]+)
94084c
diff --git a/include/link.h b/include/link.h
94084c
index c46aced9f7b43ba0..4dcf01d8aea90bc2 100644
94084c
--- a/include/link.h
94084c
+++ b/include/link.h
94084c
@@ -181,6 +181,11 @@ struct link_map
94084c
     unsigned int l_init_called:1; /* Nonzero if DT_INIT function called.  */
94084c
     unsigned int l_global:1;	/* Nonzero if object in _dl_global_scope.  */
94084c
     unsigned int l_reserved:2;	/* Reserved for internal use.  */
94084c
+    unsigned int l_main_map:1;  /* Nonzero for the map of the main program.  */
94084c
+    unsigned int l_visited:1;   /* Used internally for map dependency
94084c
+				   graph traversal.  */
94084c
+    unsigned int l_map_used:1;  /* These two bits are used during traversal */
94084c
+    unsigned int l_map_done:1;  /* of maps in _dl_close_worker. */
94084c
     unsigned int l_phdr_allocated:1; /* Nonzero if the data structure pointed
94084c
 					to by `l_phdr' is allocated.  */
94084c
     unsigned int l_soname_added:1; /* Nonzero if the SONAME is for sure in
94084c
diff --git a/manual/tunables.texi b/manual/tunables.texi
94084c
index 658547c6137bf177..10f4d75993f9940f 100644
94084c
--- a/manual/tunables.texi
94084c
+++ b/manual/tunables.texi
94084c
@@ -309,6 +309,17 @@ changed once allocated at process startup.  The default allocation of
94084c
 optional static TLS is 512 bytes and is allocated in every thread.
94084c
 @end deftp
94084c
 
94084c
+@deftp Tunable glibc.rtld.dynamic_sort
94084c
+Sets the algorithm to use for DSO sorting, valid values are @samp{1} and
94084c
+@samp{2}.  For value of @samp{1}, an older O(n^3) algorithm is used, which is
94084c
+long time tested, but may have performance issues when dependencies between
94084c
+shared objects contain cycles due to circular dependencies.  When set to the
94084c
+value of @samp{2}, a different algorithm is used, which implements a
94084c
+topological sort through depth-first search, and does not exhibit the
94084c
+performance issues of @samp{1}.
94084c
+
94084c
+The default value of this tunable is @samp{1}.
94084c
+@end deftp
94084c
 
94084c
 @node Elision Tunables
94084c
 @section Elision Tunables
94084c
diff --git a/sysdeps/generic/ldsodefs.h b/sysdeps/generic/ldsodefs.h
94084c
index fcbbf6974827cdf1..bcf1f199c5985c65 100644
94084c
--- a/sysdeps/generic/ldsodefs.h
94084c
+++ b/sysdeps/generic/ldsodefs.h
94084c
@@ -245,6 +245,13 @@ enum allowmask
94084c
   };
94084c
 
94084c
 
94084c
+/* DSO sort algorithm to use (check dl-sort-maps.c).  */
94084c
+enum dso_sort_algorithm
94084c
+  {
94084c
+    dso_sort_algorithm_original,
94084c
+    dso_sort_algorithm_dfs
94084c
+  };
94084c
+
94084c
 struct audit_ifaces
94084c
 {
94084c
   void (*activity) (uintptr_t *, unsigned int);
94084c
@@ -672,6 +679,8 @@ struct rtld_global_ro
94084c
      platforms.  */
94084c
   EXTERN uint64_t _dl_hwcap2;
94084c
 
94084c
+  EXTERN enum dso_sort_algorithm _dl_dso_sort_algo;
94084c
+
94084c
 #ifdef SHARED
94084c
   /* We add a function table to _rtld_global which is then used to
94084c
      call the function instead of going through the PLT.  The result
94084c
@@ -1098,7 +1107,7 @@ extern void _dl_fini (void) attribute_hidden;
94084c
 
94084c
 /* Sort array MAPS according to dependencies of the contained objects.  */
94084c
 extern void _dl_sort_maps (struct link_map **maps, unsigned int nmaps,
94084c
-			   char *used, bool for_fini) attribute_hidden;
94084c
+			   unsigned int skip, bool for_fini) attribute_hidden;
94084c
 
94084c
 /* The dynamic linker calls this function before and having changing
94084c
    any shared object mappings.  The `r_state' member of `struct r_debug'
94084c
@@ -1225,6 +1234,9 @@ extern struct link_map * _dl_get_dl_main_map (void)
94084c
 # endif
94084c
 #endif
94084c
 
94084c
+/* Initialize the DSO sort algorithm to use.  */
94084c
+extern void _dl_sort_maps_init (void) attribute_hidden;
94084c
+
94084c
 /* Initialization of libpthread for statically linked applications.
94084c
    If libpthread is not linked in, this is an empty function.  */
94084c
 void __pthread_initialize_minimal (void) weak_function;