From: Kostenzer Felix <[email protected]>

along with the addition made to Kconfig.debug, the prior existing
but permanently disabled test function has been slightly refactored.

patch has been tested using QEMU 2.1.2 with a .config obtained
through 'make defconfig' (x86_64) and manually enabling the option.

Signed-off-by: Kostenzer Felix <[email protected]>
---
 lib/Kconfig.debug |  8 ++++++++
 lib/sort.c        | 41 ++++++++++++++++++++++++-----------------
 2 files changed, 32 insertions(+), 17 deletions(-)

diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug
index a6c8db1..3f6b0ed 100644
--- a/lib/Kconfig.debug
+++ b/lib/Kconfig.debug
@@ -1718,6 +1718,14 @@ config TEST_LIST_SORT
 
          If unsure, say N.
 
+config TEST_SORT
+       bool "Array-based sort test"
+       depends on DEBUG_KERNEL
+       help
+         This option enables the self-test function of 'sort()' at boot.
+
+         If unsure, say N.
+
 config KPROBES_SANITY_TEST
        bool "Kprobes sanity tests"
        depends on DEBUG_KERNEL
diff --git a/lib/sort.c b/lib/sort.c
index fc20df4..a9b156e 100644
--- a/lib/sort.c
+++ b/lib/sort.c
@@ -4,6 +4,8 @@
  * Jan 23 2005  Matt Mackall <[email protected]>
  */
 
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
 #include <linux/types.h>
 #include <linux/export.h>
 #include <linux/sort.h>
@@ -102,41 +104,46 @@ void sort(void *base, size_t num, size_t size,
 
 EXPORT_SYMBOL(sort);
 
-#if 0
+#ifdef CONFIG_TEST_SORT
 #include <linux/slab.h>
+#include <linux/module.h>
 /* a simple boot-time regression test */
 
-int cmpint(const void *a, const void *b)
+#define TEST_LEN 1000
+
+static int __init cmpint(const void *a, const void *b)
 {
        return *(int *)a - *(int *)b;
 }
 
-static int sort_test(void)
+static int __init test_sort_init(void)
 {
-       int *a, i, r = 1;
-
-       a = kmalloc(1000 * sizeof(int), GFP_KERNEL);
-       BUG_ON(!a);
+       int *a, i, r = 1, err = -ENOMEM;
 
-       printk("testing sort()\n");
+       a = kmalloc_array(TEST_LEN, sizeof(*a), GFP_KERNEL);
+       if (!a)
+               return err;
 
-       for (i = 0; i < 1000; i++) {
+       for (i = 0; i < TEST_LEN; i++) {
                r = (r * 725861) % 6599;
                a[i] = r;
        }
 
-       sort(a, 1000, sizeof(int), cmpint, NULL);
+       sort(a, TEST_LEN, sizeof(*a), cmpint, NULL);
 
-       for (i = 0; i < 999; i++)
+       err = -EINVAL;
+       for (i = 0; i < TEST_LEN-1; i++)
                if (a[i] > a[i+1]) {
-                       printk("sort() failed!\n");
-                       break;
+                       pr_err("test has failed\n");
+                       goto exit;
                }
-
+       err = 0;
+       pr_info("test passed\n");
+exit:
        kfree(a);
-
-       return 0;
+       return err;
 }
 
-module_init(sort_test);
+module_init(test_sort_init);
+MODULE_LICENSE("GPL");
 #endif
-- 
2.1.4

Reply via email to