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