6b2dd0
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
ec4acb
From: Peter Jones <pjones@redhat.com>
ec4acb
Date: Fri, 9 Dec 2016 15:39:47 -0500
31cddd
Subject: [PATCH] Add quicksort implementation
ec4acb
ec4acb
This will be used to sort the boot menu entries that are read from
ec4acb
the BootLoaderSpec config files.
ec4acb
---
ec4acb
 grub-core/kern/qsort.c | 279 +++++++++++++++++++++++++++++++++++++++++++++++++
ec4acb
 include/grub/misc.h    |  15 +++
ec4acb
 2 files changed, 294 insertions(+)
ec4acb
 create mode 100644 grub-core/kern/qsort.c
ec4acb
ec4acb
diff --git a/grub-core/kern/qsort.c b/grub-core/kern/qsort.c
ec4acb
new file mode 100644
ec4acb
index 00000000000..7f3fc9ffdae
ec4acb
--- /dev/null
ec4acb
+++ b/grub-core/kern/qsort.c
ec4acb
@@ -0,0 +1,279 @@
ec4acb
+/* quicksort
ec4acb
+ * This file from the GNU C Library.
ec4acb
+ * Copyright (C) 1991-2016 Free Software Foundation, Inc.
ec4acb
+ * Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
ec4acb
+ *
ec4acb
+ *  GRUB  --  GRand Unified Bootloader
ec4acb
+ *
ec4acb
+ *  GRUB is free software: you can redistribute it and/or modify
ec4acb
+ *  it under the terms of the GNU General Public License as published by
ec4acb
+ *  the Free Software Foundation, either version 3 of the License, or
ec4acb
+ *  (at your option) any later version.
ec4acb
+ *
ec4acb
+ *  GRUB is distributed in the hope that it will be useful,
ec4acb
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
ec4acb
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
ec4acb
+ *  GNU General Public License for more details.
ec4acb
+ *
ec4acb
+ *  You should have received a copy of the GNU General Public License
ec4acb
+ *  along with GRUB.  If not, see <http: www.gnu.org="" licenses=""/>.
ec4acb
+ */
ec4acb
+
ec4acb
+/* If you consider tuning this algorithm, you should consult first:
ec4acb
+   Engineering a sort function; Jon Bentley and M. Douglas McIlroy;
ec4acb
+   Software - Practice and Experience; Vol. 23 (11), 1249-1265, 1993.  */
ec4acb
+
ec4acb
+#include <grub types.h="">
ec4acb
+#include <grub misc.h="">
ec4acb
+#include <grub mm.h="">
ec4acb
+
ec4acb
+#define CHAR_BIT 8
ec4acb
+
ec4acb
+/* Byte-wise swap two items of size SIZE. */
ec4acb
+#define SWAP(a, b, size)						      \
ec4acb
+  do									      \
ec4acb
+    {									      \
ec4acb
+      grub_size_t __size = (size);						      \
ec4acb
+      char *__a = (a), *__b = (b);					      \
ec4acb
+      do								      \
ec4acb
+	{								      \
ec4acb
+	  char __tmp = *__a;						      \
ec4acb
+	  *__a++ = *__b;						      \
ec4acb
+	  *__b++ = __tmp;						      \
ec4acb
+	} while (--__size > 0);						      \
ec4acb
+    } while (0)
ec4acb
+
ec4acb
+/* Discontinue quicksort algorithm when partition gets below this size.
ec4acb
+   This particular magic number was chosen to work best on a Sun 4/260. */
ec4acb
+#define MAX_THRESH 4
ec4acb
+
ec4acb
+/* Stack node declarations used to store unfulfilled partition obligations. */
ec4acb
+typedef struct
ec4acb
+  {
ec4acb
+    char *lo;
ec4acb
+    char *hi;
ec4acb
+  } stack_node;
ec4acb
+
ec4acb
+/* The next 4 #defines implement a very fast in-line stack abstraction. */
ec4acb
+/* The stack needs log (total_elements) entries (we could even subtract
ec4acb
+   log(MAX_THRESH)).  Since total_elements has type grub_size_t, we get as
ec4acb
+   upper bound for log (total_elements):
ec4acb
+   bits per byte (CHAR_BIT) * sizeof(grub_size_t).  */
ec4acb
+#define STACK_SIZE	(CHAR_BIT * sizeof(grub_size_t))
ec4acb
+#define PUSH(low, high)	((void) ((top->lo = (low)), (top->hi = (high)), ++top))
ec4acb
+#define	POP(low, high)	((void) (--top, (low = top->lo), (high = top->hi)))
ec4acb
+#define	STACK_NOT_EMPTY	(stack < top)
ec4acb
+
ec4acb
+
ec4acb
+/* Order size using quicksort.  This implementation incorporates
ec4acb
+   four optimizations discussed in Sedgewick:
ec4acb
+
ec4acb
+   1. Non-recursive, using an explicit stack of pointer that store the
ec4acb
+      next array partition to sort.  To save time, this maximum amount
ec4acb
+      of space required to store an array of SIZE_MAX is allocated on the
ec4acb
+      stack.  Assuming a 32-bit (64 bit) integer for grub_size_t, this needs
ec4acb
+      only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
ec4acb
+      Pretty cheap, actually.
ec4acb
+
ec4acb
+   2. Chose the pivot element using a median-of-three decision tree.
ec4acb
+      This reduces the probability of selecting a bad pivot value and
ec4acb
+      eliminates certain extraneous comparisons.
ec4acb
+
ec4acb
+   3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
ec4acb
+      insertion sort to order the MAX_THRESH items within each partition.
ec4acb
+      This is a big win, since insertion sort is faster for small, mostly
ec4acb
+      sorted array segments.
ec4acb
+
ec4acb
+   4. The larger of the two sub-partitions is always pushed onto the
ec4acb
+      stack first, with the algorithm then concentrating on the
ec4acb
+      smaller partition.  This *guarantees* no more than log (total_elems)
ec4acb
+      stack size is needed (actually O(1) in this case)!  */
ec4acb
+
ec4acb
+void
ec4acb
+grub_qsort (void *const pbase, grub_size_t total_elems, grub_size_t size,
ec4acb
+	    grub_compar_d_fn_t cmp, void *arg)
ec4acb
+{
ec4acb
+  char *base_ptr = (char *) pbase;
ec4acb
+
ec4acb
+  const grub_size_t max_thresh = MAX_THRESH * size;
ec4acb
+
ec4acb
+  if (total_elems == 0)
ec4acb
+    /* Avoid lossage with unsigned arithmetic below.  */
ec4acb
+    return;
ec4acb
+
ec4acb
+  if (total_elems > MAX_THRESH)
ec4acb
+    {
ec4acb
+      char *lo = base_ptr;
ec4acb
+      char *hi = &lo[size * (total_elems - 1)];
ec4acb
+      stack_node stack[STACK_SIZE];
ec4acb
+      stack_node *top = stack;
ec4acb
+
ec4acb
+      PUSH (NULL, NULL);
ec4acb
+
ec4acb
+      while (STACK_NOT_EMPTY)
ec4acb
+        {
ec4acb
+          char *left_ptr;
ec4acb
+          char *right_ptr;
ec4acb
+
ec4acb
+	  /* Select median value from among LO, MID, and HI. Rearrange
ec4acb
+	     LO and HI so the three values are sorted. This lowers the
ec4acb
+	     probability of picking a pathological pivot value and
ec4acb
+	     skips a comparison for both the LEFT_PTR and RIGHT_PTR in
ec4acb
+	     the while loops. */
ec4acb
+
ec4acb
+	  char *mid = lo + size * ((hi - lo) / size >> 1);
ec4acb
+
ec4acb
+	  if ((*cmp) ((void *) mid, (void *) lo, arg) < 0)
ec4acb
+	    SWAP (mid, lo, size);
ec4acb
+	  if ((*cmp) ((void *) hi, (void *) mid, arg) < 0)
ec4acb
+	    SWAP (mid, hi, size);
ec4acb
+	  else
ec4acb
+	    goto jump_over;
ec4acb
+	  if ((*cmp) ((void *) mid, (void *) lo, arg) < 0)
ec4acb
+	    SWAP (mid, lo, size);
ec4acb
+	jump_over:;
ec4acb
+
ec4acb
+	  left_ptr  = lo + size;
ec4acb
+	  right_ptr = hi - size;
ec4acb
+
ec4acb
+	  /* Here's the famous ``collapse the walls'' section of quicksort.
ec4acb
+	     Gotta like those tight inner loops!  They are the main reason
ec4acb
+	     that this algorithm runs much faster than others. */
ec4acb
+	  do
ec4acb
+	    {
ec4acb
+	      while ((*cmp) ((void *) left_ptr, (void *) mid, arg) < 0)
ec4acb
+		left_ptr += size;
ec4acb
+
ec4acb
+	      while ((*cmp) ((void *) mid, (void *) right_ptr, arg) < 0)
ec4acb
+		right_ptr -= size;
ec4acb
+
ec4acb
+	      if (left_ptr < right_ptr)
ec4acb
+		{
ec4acb
+		  SWAP (left_ptr, right_ptr, size);
ec4acb
+		  if (mid == left_ptr)
ec4acb
+		    mid = right_ptr;
ec4acb
+		  else if (mid == right_ptr)
ec4acb
+		    mid = left_ptr;
ec4acb
+		  left_ptr += size;
ec4acb
+		  right_ptr -= size;
ec4acb
+		}
ec4acb
+	      else if (left_ptr == right_ptr)
ec4acb
+		{
ec4acb
+		  left_ptr += size;
ec4acb
+		  right_ptr -= size;
ec4acb
+		  break;
ec4acb
+		}
ec4acb
+	    }
ec4acb
+	  while (left_ptr <= right_ptr);
ec4acb
+
ec4acb
+          /* Set up pointers for next iteration.  First determine whether
ec4acb
+             left and right partitions are below the threshold size.  If so,
ec4acb
+             ignore one or both.  Otherwise, push the larger partition's
ec4acb
+             bounds on the stack and continue sorting the smaller one. */
ec4acb
+
ec4acb
+          if ((grub_size_t) (right_ptr - lo) <= max_thresh)
ec4acb
+            {
ec4acb
+              if ((grub_size_t) (hi - left_ptr) <= max_thresh)
ec4acb
+		/* Ignore both small partitions. */
ec4acb
+                POP (lo, hi);
ec4acb
+              else
ec4acb
+		/* Ignore small left partition. */
ec4acb
+                lo = left_ptr;
ec4acb
+            }
ec4acb
+          else if ((grub_size_t) (hi - left_ptr) <= max_thresh)
ec4acb
+	    /* Ignore small right partition. */
ec4acb
+            hi = right_ptr;
ec4acb
+          else if ((right_ptr - lo) > (hi - left_ptr))
ec4acb
+            {
ec4acb
+	      /* Push larger left partition indices. */
ec4acb
+              PUSH (lo, right_ptr);
ec4acb
+              lo = left_ptr;
ec4acb
+            }
ec4acb
+          else
ec4acb
+            {
ec4acb
+	      /* Push larger right partition indices. */
ec4acb
+              PUSH (left_ptr, hi);
ec4acb
+              hi = right_ptr;
ec4acb
+            }
ec4acb
+        }
ec4acb
+    }
ec4acb
+
ec4acb
+  /* Once the BASE_PTR array is partially sorted by quicksort the rest
ec4acb
+     is completely sorted using insertion sort, since this is efficient
ec4acb
+     for partitions below MAX_THRESH size. BASE_PTR points to the beginning
ec4acb
+     of the array to sort, and END_PTR points at the very last element in
ec4acb
+     the array (*not* one beyond it!). */
ec4acb
+
ec4acb
+#define min(x, y) ((x) < (y) ? (x) : (y))
ec4acb
+
ec4acb
+  {
ec4acb
+    char *const end_ptr = &base_ptr[size * (total_elems - 1)];
ec4acb
+    char *tmp_ptr = base_ptr;
ec4acb
+    char *thresh = min(end_ptr, base_ptr + max_thresh);
ec4acb
+    char *run_ptr;
ec4acb
+
ec4acb
+    /* Find smallest element in first threshold and place it at the
ec4acb
+       array's beginning.  This is the smallest array element,
ec4acb
+       and the operation speeds up insertion sort's inner loop. */
ec4acb
+
ec4acb
+    for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
ec4acb
+      if ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, arg) < 0)
ec4acb
+        tmp_ptr = run_ptr;
ec4acb
+
ec4acb
+    if (tmp_ptr != base_ptr)
ec4acb
+      SWAP (tmp_ptr, base_ptr, size);
ec4acb
+
ec4acb
+    /* Insertion sort, running from left-hand-side up to right-hand-side.  */
ec4acb
+
ec4acb
+    run_ptr = base_ptr + size;
ec4acb
+    while ((run_ptr += size) <= end_ptr)
ec4acb
+      {
ec4acb
+	tmp_ptr = run_ptr - size;
ec4acb
+	while ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, arg) < 0)
ec4acb
+	  tmp_ptr -= size;
ec4acb
+
ec4acb
+	tmp_ptr += size;
ec4acb
+        if (tmp_ptr != run_ptr)
ec4acb
+          {
ec4acb
+            char *trav;
ec4acb
+
ec4acb
+	    trav = run_ptr + size;
ec4acb
+	    while (--trav >= run_ptr)
ec4acb
+              {
ec4acb
+                char c = *trav;
ec4acb
+                char *hi, *lo;
ec4acb
+
ec4acb
+                for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
ec4acb
+                  *hi = *lo;
ec4acb
+                *hi = c;
ec4acb
+              }
ec4acb
+          }
ec4acb
+      }
ec4acb
+  }
ec4acb
+}
ec4acb
+
ec4acb
+void *
ec4acb
+grub_bsearch (const void *key, const void *base, grub_size_t nmemb, grub_size_t size,
ec4acb
+	 grub_compar_d_fn_t compar, void *state)
ec4acb
+{
ec4acb
+  grub_size_t l, u, idx;
ec4acb
+  const void *p;
ec4acb
+  int comparison;
ec4acb
+
ec4acb
+  l = 0;
ec4acb
+  u = nmemb;
ec4acb
+  while (l < u)
ec4acb
+    {
ec4acb
+      idx = (l + u) / 2;
ec4acb
+      p = (void *) (((const char *) base) + (idx * size));
ec4acb
+      comparison = (*compar) (key, p, state);
ec4acb
+      if (comparison < 0)
ec4acb
+	u = idx;
ec4acb
+      else if (comparison > 0)
ec4acb
+	l = idx + 1;
ec4acb
+      else
ec4acb
+	return (void *) p;
ec4acb
+    }
ec4acb
+
ec4acb
+  return NULL;
ec4acb
+}
ec4acb
diff --git a/include/grub/misc.h b/include/grub/misc.h
752ceb
index fcaf1201e39..cbfae75a1b4 100644
ec4acb
--- a/include/grub/misc.h
ec4acb
+++ b/include/grub/misc.h
752ceb
@@ -507,4 +507,19 @@ void EXPORT_FUNC(grub_real_boot_time) (const char *file,
ec4acb
 #define grub_max(a, b) (((a) > (b)) ? (a) : (b))
ec4acb
 #define grub_min(a, b) (((a) < (b)) ? (a) : (b))
ec4acb
 
ec4acb
+typedef int (*grub_compar_d_fn_t) (const void *p0, const void *p1, void *state);
ec4acb
+
ec4acb
+void *EXPORT_FUNC(grub_bsearch) (const void *key,
ec4acb
+			    const void *base,
ec4acb
+			    grub_size_t nmemb,
ec4acb
+			    grub_size_t size,
ec4acb
+			    grub_compar_d_fn_t compar,
ec4acb
+			    void *state);
ec4acb
+
ec4acb
+void EXPORT_FUNC(grub_qsort) (void *const pbase,
ec4acb
+			 grub_size_t total_elems,
ec4acb
+			 grub_size_t size,
ec4acb
+			 grub_compar_d_fn_t cmp,
ec4acb
+			 void *state);
ec4acb
+
ec4acb
 #endif /* ! GRUB_MISC_HEADER */