LCOV - code coverage report
Current view: top level - common - sort.c (source / functions) Hit Total Coverage
Test: a simple test Lines: 36 53 67.9 %
Date: 2024-06-05 20:10:43 Functions: 3 3 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : // SPDX-License-Identifier: GPL-2.0
       2             : /*
       3             :  * A fast, small, non-recursive O(n log n) sort for the Linux kernel
       4             :  *
       5             :  * This performs n*log2(n) + 0.37*n + o(n) comparisons on average,
       6             :  * and 1.5*n*log2(n) + O(n) in the (very contrived) worst case.
       7             :  *
       8             :  * Glibc qsort() manages n*log2(n) - 1.26*n for random inputs (1.63*n
       9             :  * better) at the expense of stack usage and much larger code to avoid
      10             :  * quicksort's O(n^2) worst case.
      11             :  */
      12             : 
      13             : #include <stdio.h>
      14             : #include <stdbool.h>
      15             : #include <linux/types.h>
      16             : 
      17             : #include "sort.h"
      18             : #include "linux_types.h"
      19             : 
      20             : /**
      21             :  * is_aligned - is this pointer & size okay for word-wide copying?
      22             :  * @base: pointer to data
      23             :  * @size: size of each element
      24             :  * @align: required alignment (typically 4 or 8)
      25             :  *
      26             :  * Returns true if elements can be copied using word loads and stores.
      27             :  * The size must be a multiple of the alignment.
      28             :  *
      29             :  * For some reason, gcc doesn't know to optimize "if (a & mask || b & mask)"
      30             :  * to "if ((a | b) & mask)", so we do that by hand.
      31             :  */
      32             : __const __always_inline
      33             : static bool is_aligned(const void *base, size_t size, unsigned char align)
      34             : {
      35        2297 :         unsigned char lsbits = (unsigned char)size;
      36             : 
      37             :         (void)base;
      38             :         return (lsbits & (align - 1)) == 0;
      39             : }
      40             : 
      41             : /**
      42             :  * swap_words_32 - swap two elements in 32-bit chunks
      43             :  * @a: pointer to the first element to swap
      44             :  * @b: pointer to the second element to swap
      45             :  * @n: element size (must be a multiple of 4)
      46             :  *
      47             :  * Exchange the two objects in memory.  This exploits base+index addressing,
      48             :  * which basically all CPUs have, to minimize loop overhead computations.
      49             :  *
      50             :  * For some reason, on x86 gcc 7.3.0 adds a redundant test of n at the
      51             :  * bottom of the loop, even though the zero flag is still valid from the
      52             :  * subtract (since the intervening mov instructions don't alter the flags).
      53             :  * Gcc 8.1.0 doesn't have that problem.
      54             :  */
      55             : static void swap_words_32(void *a, void *b, size_t n)
      56             : {
      57             :         do {
      58           0 :                 u32 t = *(u32 *)(a + (n -= 4));
      59           0 :                 *(u32 *)(a + n) = *(u32 *)(b + n);
      60           0 :                 *(u32 *)(b + n) = t;
      61           0 :         } while (n);
      62             : }
      63             : 
      64             : /**
      65             :  * swap_words_64 - swap two elements in 64-bit chunks
      66             :  * @a: pointer to the first element to swap
      67             :  * @b: pointer to the second element to swap
      68             :  * @n: element size (must be a multiple of 8)
      69             :  *
      70             :  * Exchange the two objects in memory.  This exploits base+index
      71             :  * addressing, which basically all CPUs have, to minimize loop overhead
      72             :  * computations.
      73             :  *
      74             :  * We'd like to use 64-bit loads if possible.  If they're not, emulating
      75             :  * one requires base+index+4 addressing which x86 has but most other
      76             :  * processors do not.
      77             :  */
      78             : static void swap_words_64(void *a, void *b, size_t n)
      79             : {
      80             :         do {
      81     1957195 :                 u64 t = *(u64 *)(a + (n -= 8));
      82     1957195 :                 *(u64 *)(a + n) = *(u64 *)(b + n);
      83     1957195 :                 *(u64 *)(b + n) = t;
      84     1957195 :         } while (n);
      85             : }
      86             : 
      87             : /**
      88             :  * swap_bytes - swap two elements a byte at a time
      89             :  * @a: pointer to the first element to swap
      90             :  * @b: pointer to the second element to swap
      91             :  * @n: element size
      92             :  *
      93             :  * This is the fallback if alignment doesn't allow using larger chunks.
      94             :  */
      95             : static void swap_bytes(void *a, void *b, size_t n)
      96             : {
      97             :         do {
      98           0 :                 char t = ((char *)a)[--n];
      99           0 :                 ((char *)a)[n] = ((char *)b)[n];
     100           0 :                 ((char *)b)[n] = t;
     101           0 :         } while (n);
     102             : }
     103             : 
     104             : /*
     105             :  * The values are arbitrary as long as they can't be confused with
     106             :  * a pointer, but small integers make for the smallest compare
     107             :  * instructions.
     108             :  */
     109             : #define SWAP_WORDS_64 (swap_r_func_t)0
     110             : #define SWAP_WORDS_32 (swap_r_func_t)1
     111             : #define SWAP_BYTES    (swap_r_func_t)2
     112             : #define SWAP_WRAPPER  (swap_r_func_t)3
     113             : 
     114             : struct wrapper {
     115             :         cmp_func_t cmp;
     116             :         swap_func_t swap;
     117             : };
     118             : 
     119             : /*
     120             :  * The function pointer is last to make tail calls most efficient if the
     121             :  * compiler decides not to inline this function.
     122             :  */
     123     1957195 : static void do_swap(void *a, void *b, size_t size, swap_r_func_t swap_func, const void *priv)
     124             : {
     125     1957195 :         if (swap_func == SWAP_WRAPPER) {
     126           0 :                 ((const struct wrapper *)priv)->swap(a, b, (int)size);
     127           0 :                 return;
     128             :         }
     129             : 
     130     1957195 :         if (swap_func == SWAP_WORDS_64)
     131             :                 swap_words_64(a, b, size);
     132           0 :         else if (swap_func == SWAP_WORDS_32)
     133             :                 swap_words_32(a, b, size);
     134           0 :         else if (swap_func == SWAP_BYTES)
     135             :                 swap_bytes(a, b, size);
     136             :         else
     137           0 :                 swap_func(a, b, (int)size, priv);
     138             : }
     139             : 
     140             : #define _CMP_WRAPPER ((cmp_r_func_t)0L)
     141             : 
     142             : static int do_cmp(const void *a, const void *b, cmp_r_func_t cmp, const void *priv)
     143             : {
     144     2983390 :         if (cmp == _CMP_WRAPPER)
     145     2983390 :                 return ((const struct wrapper *)priv)->cmp(a, b);
     146           0 :         return cmp(a, b, priv);
     147             : }
     148             : 
     149             : /**
     150             :  * parent - given the offset of the child, find the offset of the parent.
     151             :  * @i: the offset of the heap element whose parent is sought.  Non-zero.
     152             :  * @lsbit: a precomputed 1-bit mask, equal to "size & -size"
     153             :  * @size: size of each element
     154             :  *
     155             :  * In terms of array indexes, the parent of element j = @i/@size is simply
     156             :  * (j-1)/2.  But when working in byte offsets, we can't use implicit
     157             :  * truncation of integer divides.
     158             :  *
     159             :  * Fortunately, we only need one bit of the quotient, not the full divide.
     160             :  * @size has a least significant bit.  That bit will be clear if @i is
     161             :  * an even multiple of @size, and set if it's an odd multiple.
     162             :  *
     163             :  * Logically, we're doing "if (i & lsbit) i -= size;", but since the
     164             :  * branch is unpredictable, it's done with a bit of clever branch-free
     165             :  * code instead.
     166             :  */
     167             : __const __always_inline
     168             : static size_t parent(size_t i, unsigned int lsbit, size_t size)
     169             : {
     170     2157950 :         i -= size;
     171     2157950 :         i -= size & -(i & lsbit);
     172     2157950 :         return i / 2;
     173             : }
     174             : 
     175             : /**
     176             :  * sort_r - sort an array of elements
     177             :  * @base: pointer to data to sort
     178             :  * @num: number of elements
     179             :  * @size: size of each element
     180             :  * @cmp_func: pointer to comparison function
     181             :  * @swap_func: pointer to swap function or NULL
     182             :  * @priv: third argument passed to comparison function
     183             :  *
     184             :  * This function does a heapsort on the given array.  You may provide
     185             :  * a swap_func function if you need to do something more than a memory
     186             :  * copy (e.g. fix up pointers or auxiliary data), but the built-in swap
     187             :  * avoids a slow retpoline and so is significantly faster.
     188             :  *
     189             :  * Sorting time is O(n log n) both on average and worst-case. While
     190             :  * quicksort is slightly faster on average, it suffers from exploitable
     191             :  * O(n*n) worst-case behavior and extra memory requirements that make
     192             :  * it less suitable for kernel use.
     193             :  */
     194        3427 : void sort_r(void *base, size_t num, size_t size,
     195             :             cmp_r_func_t cmp_func,
     196             :             swap_r_func_t swap_func,
     197             :             const void *priv)
     198             : {
     199             :         /* pre-scale counters for performance */
     200        3427 :         size_t n = num * size, a = (num/2) * size;
     201        3427 :         const unsigned int lsbit = size & -size;  /* Used to find parent */
     202             : 
     203        3427 :         if (!a)         /* num < 2 || size == 0 */
     204             :                 return;
     205             : 
     206             :         /* called from 'sort' without swap function, let's pick the default */
     207        2297 :         if (swap_func == SWAP_WRAPPER && !((struct wrapper *)priv)->swap)
     208             :                 swap_func = NULL;
     209             : 
     210           0 :         if (!swap_func) {
     211        2297 :                 if (is_aligned(base, size, 8))
     212             :                         swap_func = SWAP_WORDS_64;
     213           0 :                 else if (is_aligned(base, size, 4))
     214             :                         swap_func = SWAP_WORDS_32;
     215             :                 else
     216           0 :                         swap_func = SWAP_BYTES;
     217             :         }
     218             : 
     219             :         /*
     220             :          * Loop invariants:
     221             :          * 1. elements [a,n) satisfy the heap property (compare greater than
     222             :          *    all of their children),
     223             :          * 2. elements [n,num*size) are sorted, and
     224             :          * 3. a <= b <= c <= d <= n (whenever they are valid).
     225             :          */
     226             :         for (;;) {
     227             :                 size_t b, c, d;
     228             : 
     229      513344 :                 if (a)                  /* Building heap: sift down --a */
     230      170904 :                         a -= size;
     231      342440 :                 else if (n -= size)     /* Sorting: Extract root to --n */
     232      340143 :                         do_swap(base, base + n, size, swap_func, priv);
     233             :                 else                    /* Sort complete */
     234             :                         break;
     235             : 
     236             :                 /*
     237             :                  * Sift element at "a" down into heap.  This is the
     238             :                  * "bottom-up" variant, which significantly reduces
     239             :                  * calls to cmp_func(): we find the sift-down path all
     240             :                  * the way to the leaves (one compare per level), then
     241             :                  * backtrack to find where to insert the target element.
     242             :                  *
     243             :                  * Because elements tend to sift down close to the leaves,
     244             :                  * this uses fewer compares than doing two per level
     245             :                  * on the way down.  (A bit more than half as many on
     246             :                  * average, 3/4 worst-case.)
     247             :                  */
     248     3164389 :                 for (b = a; c = 2*b + size, (d = c + size) < n;)
     249     4284590 :                         b = do_cmp(base + c, base + d, cmp_func, priv) >= 0 ? c : d;
     250      511047 :                 if (d == n)     /* Special case last leaf with no sibling */
     251       15655 :                         b = c;
     252             : 
     253             :                 /* Now backtrack from "b" to the correct location for "a" */
     254     1893040 :                 while (b != a && do_cmp(base + a, base + b, cmp_func, priv) >= 0)
     255      540898 :                         b = parent(b, lsbit, size);
     256      511047 :                 c = b;                  /* Where "a" belongs */
     257     2639146 :                 while (b != a) {        /* Shift it into place */
     258     1617052 :                         b = parent(b, lsbit, size);
     259     1617052 :                         do_swap(base + b, base + c, size, swap_func, priv);
     260             :                 }
     261             :         }
     262             : }
     263             : 
     264        3427 : void sort(void *base, size_t num, size_t size,
     265             :           cmp_func_t cmp_func,
     266             :           swap_func_t swap_func)
     267             : {
     268        3427 :         struct wrapper w = {
     269             :                 .cmp  = cmp_func,
     270             :                 .swap = swap_func,
     271             :         };
     272             : 
     273        3427 :         return sort_r(base, num, size, _CMP_WRAPPER, SWAP_WRAPPER, &w);
     274             : }

Generated by: LCOV version 1.13