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