aboutsummaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/Kconfig34
-rw-r--r--lib/Kconfig.debug155
-rw-r--r--lib/Makefile21
-rw-r--r--lib/atomic64_test.c5
-rw-r--r--lib/bitmap.c12
-rw-r--r--lib/btree.c5
-rw-r--r--lib/cpu-notifier-error-inject.c63
-rw-r--r--lib/crc32.c2
-rw-r--r--lib/debugobjects.c11
-rw-r--r--lib/div64.c2
-rw-r--r--lib/dma-debug.c14
-rw-r--r--lib/dynamic_debug.c190
-rw-r--r--lib/dynamic_queue_limits.c18
-rw-r--r--lib/fault-inject.c4
-rw-r--r--lib/fdt.c2
-rw-r--r--lib/fdt_ro.c2
-rw-r--r--lib/fdt_rw.c2
-rw-r--r--lib/fdt_strerror.c2
-rw-r--r--lib/fdt_sw.c2
-rw-r--r--lib/fdt_wip.c2
-rw-r--r--lib/flex_proportions.c272
-rw-r--r--lib/jedec_ddr_data.c135
-rw-r--r--lib/kobject.c14
-rw-r--r--lib/kobject_uevent.c5
-rw-r--r--lib/list_debug.c23
-rw-r--r--lib/memory-notifier-error-inject.c48
-rw-r--r--lib/memweight.c38
-rw-r--r--lib/mpi/Makefile11
-rw-r--r--lib/mpi/generic_mpi-asm-defs.h4
-rw-r--r--lib/mpi/mpi-add.c234
-rw-r--r--lib/mpi/mpi-bit.c162
-rw-r--r--lib/mpi/mpi-cmp.c68
-rw-r--r--lib/mpi/mpi-div.c338
-rw-r--r--lib/mpi/mpi-gcd.c59
-rw-r--r--lib/mpi/mpi-inline.c31
-rw-r--r--lib/mpi/mpi-inv.c187
-rw-r--r--lib/mpi/mpi-mpow.c134
-rw-r--r--lib/mpi/mpi-mul.c194
-rw-r--r--lib/mpi/mpi-scan.c136
-rw-r--r--lib/mpi/mpicoder.c75
-rw-r--r--lib/mpi/mpih-div.c309
-rw-r--r--lib/mpi/mpih-mul.c30
-rw-r--r--lib/mpi/mpiutil.c88
-rw-r--r--lib/notifier-error-inject.c112
-rw-r--r--lib/notifier-error-inject.h24
-rw-r--r--lib/pSeries-reconfig-notifier-error-inject.c51
-rw-r--r--lib/pm-notifier-error-inject.c49
-rw-r--r--lib/radix-tree.c18
-rw-r--r--lib/raid6/Makefile2
-rw-r--r--lib/raid6/algos.c127
-rw-r--r--lib/raid6/mktables.c25
-rw-r--r--lib/raid6/recov.c18
-rw-r--r--lib/raid6/recov_ssse3.c336
-rw-r--r--lib/raid6/test/Makefile2
-rw-r--r--lib/raid6/test/test.c32
-rw-r--r--lib/raid6/x86.h15
-rw-r--r--lib/rational.c2
-rw-r--r--lib/scatterlist.c72
-rw-r--r--lib/spinlock_debug.c4
-rw-r--r--lib/stmp_device.c80
-rw-r--r--lib/string_helpers.c8
-rw-r--r--lib/strncpy_from_user.c113
-rw-r--r--lib/strnlen_user.c138
-rw-r--r--lib/swiotlb.c8
-rw-r--r--lib/test-kstrtox.c4
-rw-r--r--lib/vsprintf.c386
66 files changed, 2348 insertions, 2421 deletions
diff --git a/lib/Kconfig b/lib/Kconfig
index 4a8aba2e5cc0..bb94c1ba616a 100644
--- a/lib/Kconfig
+++ b/lib/Kconfig
@@ -16,6 +16,12 @@ config BITREVERSE
16config RATIONAL 16config RATIONAL
17 boolean 17 boolean
18 18
19config GENERIC_STRNCPY_FROM_USER
20 bool
21
22config GENERIC_STRNLEN_USER
23 bool
24
19config GENERIC_FIND_FIRST_BIT 25config GENERIC_FIND_FIRST_BIT
20 bool 26 bool
21 27
@@ -33,6 +39,9 @@ config GENERIC_IO
33 boolean 39 boolean
34 default n 40 default n
35 41
42config STMP_DEVICE
43 bool
44
36config CRC_CCITT 45config CRC_CCITT
37 tristate "CRC-CCITT functions" 46 tristate "CRC-CCITT functions"
38 help 47 help
@@ -331,6 +340,9 @@ config NLATTR
331config GENERIC_ATOMIC64 340config GENERIC_ATOMIC64
332 bool 341 bool
333 342
343config ARCH_HAS_ATOMIC64_DEC_IF_POSITIVE
344 def_bool y if GENERIC_ATOMIC64
345
334config LRU_CACHE 346config LRU_CACHE
335 tristate 347 tristate
336 348
@@ -353,6 +365,14 @@ config CORDIC
353 This option provides an implementation of the CORDIC algorithm; 365 This option provides an implementation of the CORDIC algorithm;
354 calculations are in fixed point. Module will be called cordic. 366 calculations are in fixed point. Module will be called cordic.
355 367
368config DDR
369 bool "JEDEC DDR data"
370 help
371 Data from JEDEC specs for DDR SDRAM memories,
372 particularly the AC timing parameters and addressing
373 information. This data is useful for drivers handling
374 DDR SDRAM controllers.
375
356config MPILIB 376config MPILIB
357 tristate 377 tristate
358 select CLZ_TAB 378 select CLZ_TAB
@@ -361,14 +381,6 @@ config MPILIB
361 It is used to implement RSA digital signature verification, 381 It is used to implement RSA digital signature verification,
362 which is used by IMA/EVM digital signature extension. 382 which is used by IMA/EVM digital signature extension.
363 383
364config MPILIB_EXTRA
365 bool
366 depends on MPILIB
367 help
368 Additional sources of multiprecision maths library from GnuPG.
369 This code is unnecessary for RSA digital signature verification,
370 but can be compiled if needed.
371
372config SIGNATURE 384config SIGNATURE
373 tristate 385 tristate
374 depends on KEYS && CRYPTO 386 depends on KEYS && CRYPTO
@@ -378,4 +390,10 @@ config SIGNATURE
378 Digital signature verification. Currently only RSA is supported. 390 Digital signature verification. Currently only RSA is supported.
379 Implementation is done using GnuPG MPI library 391 Implementation is done using GnuPG MPI library
380 392
393#
394# libfdt files, only selected if needed.
395#
396config LIBFDT
397 bool
398
381endmenu 399endmenu
diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug
index 6777153f18f3..2403a63b5da5 100644
--- a/lib/Kconfig.debug
+++ b/lib/Kconfig.debug
@@ -3,12 +3,16 @@ config PRINTK_TIME
3 bool "Show timing information on printks" 3 bool "Show timing information on printks"
4 depends on PRINTK 4 depends on PRINTK
5 help 5 help
6 Selecting this option causes timing information to be 6 Selecting this option causes time stamps of the printk()
7 included in printk output. This allows you to measure 7 messages to be added to the output of the syslog() system
8 the interval between kernel operations, including bootup 8 call and at the console.
9 operations. This is useful for identifying long delays 9
10 in kernel startup. Or add printk.time=1 at boot-time. 10 The timestamp is always recorded internally, and exported
11 See Documentation/kernel-parameters.txt 11 to /dev/kmsg. This flag just specifies if the timestamp should
12 be included, not that the timestamp is recorded.
13
14 The behavior is also controlled by the kernel command line
15 parameter printk.time=1. See Documentation/kernel-parameters.txt
12 16
13config DEFAULT_MESSAGE_LOGLEVEL 17config DEFAULT_MESSAGE_LOGLEVEL
14 int "Default message log level (1-7)" 18 int "Default message log level (1-7)"
@@ -70,6 +74,15 @@ config STRIP_ASM_SYMS
70 that look like '.Lxxx') so they don't pollute the output of 74 that look like '.Lxxx') so they don't pollute the output of
71 get_wchan() and suchlike. 75 get_wchan() and suchlike.
72 76
77config READABLE_ASM
78 bool "Generate readable assembler code"
79 depends on DEBUG_KERNEL
80 help
81 Disable some compiler optimizations that tend to generate human unreadable
82 assembler output. This may make the kernel slightly slower, but it helps
83 to keep kernel developers who have to stare a lot at assembler listings
84 sane.
85
73config UNUSED_SYMBOLS 86config UNUSED_SYMBOLS
74 bool "Enable unused/obsolete exported symbols" 87 bool "Enable unused/obsolete exported symbols"
75 default y if X86 88 default y if X86
@@ -228,6 +241,26 @@ config BOOTPARAM_SOFTLOCKUP_PANIC_VALUE
228 default 0 if !BOOTPARAM_SOFTLOCKUP_PANIC 241 default 0 if !BOOTPARAM_SOFTLOCKUP_PANIC
229 default 1 if BOOTPARAM_SOFTLOCKUP_PANIC 242 default 1 if BOOTPARAM_SOFTLOCKUP_PANIC
230 243
244config PANIC_ON_OOPS
245 bool "Panic on Oops" if EXPERT
246 default n
247 help
248 Say Y here to enable the kernel to panic when it oopses. This
249 has the same effect as setting oops=panic on the kernel command
250 line.
251
252 This feature is useful to ensure that the kernel does not do
253 anything erroneous after an oops which could result in data
254 corruption or other issues.
255
256 Say N if unsure.
257
258config PANIC_ON_OOPS_VALUE
259 int
260 range 0 1
261 default 0 if !PANIC_ON_OOPS
262 default 1 if PANIC_ON_OOPS
263
231config DETECT_HUNG_TASK 264config DETECT_HUNG_TASK
232 bool "Detect Hung Tasks" 265 bool "Detect Hung Tasks"
233 depends on DEBUG_KERNEL 266 depends on DEBUG_KERNEL
@@ -681,7 +714,7 @@ config STACKTRACE
681 714
682config DEBUG_STACK_USAGE 715config DEBUG_STACK_USAGE
683 bool "Stack utilization instrumentation" 716 bool "Stack utilization instrumentation"
684 depends on DEBUG_KERNEL 717 depends on DEBUG_KERNEL && !IA64 && !PARISC
685 help 718 help
686 Enables the display of the minimum amount of free stack which each 719 Enables the display of the minimum amount of free stack which each
687 task has ever had available in the sysrq-T and sysrq-P debug output. 720 task has ever had available in the sysrq-T and sysrq-P debug output.
@@ -1051,18 +1084,105 @@ config LKDTM
1051 Documentation on how to use the module can be found in 1084 Documentation on how to use the module can be found in
1052 Documentation/fault-injection/provoke-crashes.txt 1085 Documentation/fault-injection/provoke-crashes.txt
1053 1086
1087config NOTIFIER_ERROR_INJECTION
1088 tristate "Notifier error injection"
1089 depends on DEBUG_KERNEL
1090 select DEBUG_FS
1091 help
1092 This option provides the ability to inject artifical errors to
1093 specified notifier chain callbacks. It is useful to test the error
1094 handling of notifier call chain failures.
1095
1096 Say N if unsure.
1097
1054config CPU_NOTIFIER_ERROR_INJECT 1098config CPU_NOTIFIER_ERROR_INJECT
1055 tristate "CPU notifier error injection module" 1099 tristate "CPU notifier error injection module"
1056 depends on HOTPLUG_CPU && DEBUG_KERNEL 1100 depends on HOTPLUG_CPU && NOTIFIER_ERROR_INJECTION
1057 help 1101 help
1058 This option provides a kernel module that can be used to test 1102 This option provides a kernel module that can be used to test
1059 the error handling of the cpu notifiers 1103 the error handling of the cpu notifiers by injecting artifical
1104 errors to CPU notifier chain callbacks. It is controlled through
1105 debugfs interface under /sys/kernel/debug/notifier-error-inject/cpu
1106
1107 If the notifier call chain should be failed with some events
1108 notified, write the error code to "actions/<notifier event>/error".
1109
1110 Example: Inject CPU offline error (-1 == -EPERM)
1111
1112 # cd /sys/kernel/debug/notifier-error-inject/cpu
1113 # echo -1 > actions/CPU_DOWN_PREPARE/error
1114 # echo 0 > /sys/devices/system/cpu/cpu1/online
1115 bash: echo: write error: Operation not permitted
1060 1116
1061 To compile this code as a module, choose M here: the module will 1117 To compile this code as a module, choose M here: the module will
1062 be called cpu-notifier-error-inject. 1118 be called cpu-notifier-error-inject.
1063 1119
1064 If unsure, say N. 1120 If unsure, say N.
1065 1121
1122config PM_NOTIFIER_ERROR_INJECT
1123 tristate "PM notifier error injection module"
1124 depends on PM && NOTIFIER_ERROR_INJECTION
1125 default m if PM_DEBUG
1126 help
1127 This option provides the ability to inject artifical errors to
1128 PM notifier chain callbacks. It is controlled through debugfs
1129 interface /sys/kernel/debug/notifier-error-inject/pm
1130
1131 If the notifier call chain should be failed with some events
1132 notified, write the error code to "actions/<notifier event>/error".
1133
1134 Example: Inject PM suspend error (-12 = -ENOMEM)
1135
1136 # cd /sys/kernel/debug/notifier-error-inject/pm/
1137 # echo -12 > actions/PM_SUSPEND_PREPARE/error
1138 # echo mem > /sys/power/state
1139 bash: echo: write error: Cannot allocate memory
1140
1141 To compile this code as a module, choose M here: the module will
1142 be called pm-notifier-error-inject.
1143
1144 If unsure, say N.
1145
1146config MEMORY_NOTIFIER_ERROR_INJECT
1147 tristate "Memory hotplug notifier error injection module"
1148 depends on MEMORY_HOTPLUG_SPARSE && NOTIFIER_ERROR_INJECTION
1149 help
1150 This option provides the ability to inject artifical errors to
1151 memory hotplug notifier chain callbacks. It is controlled through
1152 debugfs interface under /sys/kernel/debug/notifier-error-inject/memory
1153
1154 If the notifier call chain should be failed with some events
1155 notified, write the error code to "actions/<notifier event>/error".
1156
1157 Example: Inject memory hotplug offline error (-12 == -ENOMEM)
1158
1159 # cd /sys/kernel/debug/notifier-error-inject/memory
1160 # echo -12 > actions/MEM_GOING_OFFLINE/error
1161 # echo offline > /sys/devices/system/memory/memoryXXX/state
1162 bash: echo: write error: Cannot allocate memory
1163
1164 To compile this code as a module, choose M here: the module will
1165 be called pSeries-reconfig-notifier-error-inject.
1166
1167 If unsure, say N.
1168
1169config PSERIES_RECONFIG_NOTIFIER_ERROR_INJECT
1170 tristate "pSeries reconfig notifier error injection module"
1171 depends on PPC_PSERIES && NOTIFIER_ERROR_INJECTION
1172 help
1173 This option provides the ability to inject artifical errors to
1174 pSeries reconfig notifier chain callbacks. It is controlled
1175 through debugfs interface under
1176 /sys/kernel/debug/notifier-error-inject/pSeries-reconfig/
1177
1178 If the notifier call chain should be failed with some events
1179 notified, write the error code to "actions/<notifier event>/error".
1180
1181 To compile this code as a module, choose M here: the module will
1182 be called memory-notifier-error-inject.
1183
1184 If unsure, say N.
1185
1066config FAULT_INJECTION 1186config FAULT_INJECTION
1067 bool "Fault-injection framework" 1187 bool "Fault-injection framework"
1068 depends on DEBUG_KERNEL 1188 depends on DEBUG_KERNEL
@@ -1205,8 +1325,13 @@ config DYNAMIC_DEBUG
1205 otherwise be available at runtime. These messages can then be 1325 otherwise be available at runtime. These messages can then be
1206 enabled/disabled based on various levels of scope - per source file, 1326 enabled/disabled based on various levels of scope - per source file,
1207 function, module, format string, and line number. This mechanism 1327 function, module, format string, and line number. This mechanism
1208 implicitly enables all pr_debug() and dev_dbg() calls. The impact of 1328 implicitly compiles in all pr_debug() and dev_dbg() calls, which
1209 this compile option is a larger kernel text size of about 2%. 1329 enlarges the kernel text size by about 2%.
1330
1331 If a source file is compiled with DEBUG flag set, any
1332 pr_debug() calls in it are enabled by default, but can be
1333 disabled at runtime as below. Note that DEBUG flag is
1334 turned on by many CONFIG_*DEBUG* options.
1210 1335
1211 Usage: 1336 Usage:
1212 1337
@@ -1223,16 +1348,16 @@ config DYNAMIC_DEBUG
1223 lineno : line number of the debug statement 1348 lineno : line number of the debug statement
1224 module : module that contains the debug statement 1349 module : module that contains the debug statement
1225 function : function that contains the debug statement 1350 function : function that contains the debug statement
1226 flags : 'p' means the line is turned 'on' for printing 1351 flags : '=p' means the line is turned 'on' for printing
1227 format : the format used for the debug statement 1352 format : the format used for the debug statement
1228 1353
1229 From a live system: 1354 From a live system:
1230 1355
1231 nullarbor:~ # cat <debugfs>/dynamic_debug/control 1356 nullarbor:~ # cat <debugfs>/dynamic_debug/control
1232 # filename:lineno [module]function flags format 1357 # filename:lineno [module]function flags format
1233 fs/aio.c:222 [aio]__put_ioctx - "__put_ioctx:\040freeing\040%p\012" 1358 fs/aio.c:222 [aio]__put_ioctx =_ "__put_ioctx:\040freeing\040%p\012"
1234 fs/aio.c:248 [aio]ioctx_alloc - "ENOMEM:\040nr_events\040too\040high\012" 1359 fs/aio.c:248 [aio]ioctx_alloc =_ "ENOMEM:\040nr_events\040too\040high\012"
1235 fs/aio.c:1770 [aio]sys_io_cancel - "calling\040cancel\012" 1360 fs/aio.c:1770 [aio]sys_io_cancel =_ "calling\040cancel\012"
1236 1361
1237 Example usage: 1362 Example usage:
1238 1363
diff --git a/lib/Makefile b/lib/Makefile
index 18515f0267c4..42d283edc4d3 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -11,7 +11,7 @@ lib-y := ctype.o string.o vsprintf.o cmdline.o \
11 rbtree.o radix-tree.o dump_stack.o timerqueue.o\ 11 rbtree.o radix-tree.o dump_stack.o timerqueue.o\
12 idr.o int_sqrt.o extable.o prio_tree.o \ 12 idr.o int_sqrt.o extable.o prio_tree.o \
13 sha1.o md5.o irq_regs.o reciprocal_div.o argv_split.o \ 13 sha1.o md5.o irq_regs.o reciprocal_div.o argv_split.o \
14 proportions.o prio_heap.o ratelimit.o show_mem.o \ 14 proportions.o flex_proportions.o prio_heap.o ratelimit.o show_mem.o \
15 is_single_threaded.o plist.o decompress.o 15 is_single_threaded.o plist.o decompress.o
16 16
17lib-$(CONFIG_MMU) += ioremap.o 17lib-$(CONFIG_MMU) += ioremap.o
@@ -22,7 +22,7 @@ lib-y += kobject.o klist.o
22obj-y += bcd.o div64.o sort.o parser.o halfmd4.o debug_locks.o random32.o \ 22obj-y += bcd.o div64.o sort.o parser.o halfmd4.o debug_locks.o random32.o \
23 bust_spinlocks.o hexdump.o kasprintf.o bitmap.o scatterlist.o \ 23 bust_spinlocks.o hexdump.o kasprintf.o bitmap.o scatterlist.o \
24 string_helpers.o gcd.o lcm.o list_sort.o uuid.o flex_array.o \ 24 string_helpers.o gcd.o lcm.o list_sort.o uuid.o flex_array.o \
25 bsearch.o find_last_bit.o find_next_bit.o llist.o 25 bsearch.o find_last_bit.o find_next_bit.o llist.o memweight.o
26obj-y += kstrtox.o 26obj-y += kstrtox.o
27obj-$(CONFIG_TEST_KSTRTOX) += test-kstrtox.o 27obj-$(CONFIG_TEST_KSTRTOX) += test-kstrtox.o
28 28
@@ -90,7 +90,12 @@ obj-$(CONFIG_AUDIT_GENERIC) += audit.o
90obj-$(CONFIG_SWIOTLB) += swiotlb.o 90obj-$(CONFIG_SWIOTLB) += swiotlb.o
91obj-$(CONFIG_IOMMU_HELPER) += iommu-helper.o 91obj-$(CONFIG_IOMMU_HELPER) += iommu-helper.o
92obj-$(CONFIG_FAULT_INJECTION) += fault-inject.o 92obj-$(CONFIG_FAULT_INJECTION) += fault-inject.o
93obj-$(CONFIG_NOTIFIER_ERROR_INJECTION) += notifier-error-inject.o
93obj-$(CONFIG_CPU_NOTIFIER_ERROR_INJECT) += cpu-notifier-error-inject.o 94obj-$(CONFIG_CPU_NOTIFIER_ERROR_INJECT) += cpu-notifier-error-inject.o
95obj-$(CONFIG_PM_NOTIFIER_ERROR_INJECT) += pm-notifier-error-inject.o
96obj-$(CONFIG_MEMORY_NOTIFIER_ERROR_INJECT) += memory-notifier-error-inject.o
97obj-$(CONFIG_PSERIES_RECONFIG_NOTIFIER_ERROR_INJECT) += \
98 pSeries-reconfig-notifier-error-inject.o
94 99
95lib-$(CONFIG_GENERIC_BUG) += bug.o 100lib-$(CONFIG_GENERIC_BUG) += bug.o
96 101
@@ -123,6 +128,18 @@ obj-$(CONFIG_SIGNATURE) += digsig.o
123 128
124obj-$(CONFIG_CLZ_TAB) += clz_tab.o 129obj-$(CONFIG_CLZ_TAB) += clz_tab.o
125 130
131obj-$(CONFIG_DDR) += jedec_ddr_data.o
132
133obj-$(CONFIG_GENERIC_STRNCPY_FROM_USER) += strncpy_from_user.o
134obj-$(CONFIG_GENERIC_STRNLEN_USER) += strnlen_user.o
135
136obj-$(CONFIG_STMP_DEVICE) += stmp_device.o
137
138libfdt_files = fdt.o fdt_ro.o fdt_wip.o fdt_rw.o fdt_sw.o fdt_strerror.o
139$(foreach file, $(libfdt_files), \
140 $(eval CFLAGS_$(file) = -I$(src)/../scripts/dtc/libfdt))
141lib-$(CONFIG_LIBFDT) += $(libfdt_files)
142
126hostprogs-y := gen_crc32table 143hostprogs-y := gen_crc32table
127clean-files := crc32table.h 144clean-files := crc32table.h
128 145
diff --git a/lib/atomic64_test.c b/lib/atomic64_test.c
index cb99b91c3a1d..00bca223d1e1 100644
--- a/lib/atomic64_test.c
+++ b/lib/atomic64_test.c
@@ -114,8 +114,7 @@ static __init int test_atomic64(void)
114 r += one; 114 r += one;
115 BUG_ON(v.counter != r); 115 BUG_ON(v.counter != r);
116 116
117#if defined(CONFIG_X86) || defined(CONFIG_MIPS) || defined(CONFIG_PPC) || \ 117#ifdef CONFIG_ARCH_HAS_ATOMIC64_DEC_IF_POSITIVE
118 defined(CONFIG_S390) || defined(_ASM_GENERIC_ATOMIC64_H) || defined(CONFIG_ARM)
119 INIT(onestwos); 118 INIT(onestwos);
120 BUG_ON(atomic64_dec_if_positive(&v) != (onestwos - 1)); 119 BUG_ON(atomic64_dec_if_positive(&v) != (onestwos - 1));
121 r -= one; 120 r -= one;
@@ -129,7 +128,7 @@ static __init int test_atomic64(void)
129 BUG_ON(atomic64_dec_if_positive(&v) != (-one - one)); 128 BUG_ON(atomic64_dec_if_positive(&v) != (-one - one));
130 BUG_ON(v.counter != r); 129 BUG_ON(v.counter != r);
131#else 130#else
132#warning Please implement atomic64_dec_if_positive for your architecture, and add it to the IF above 131#warning Please implement atomic64_dec_if_positive for your architecture and select the above Kconfig symbol
133#endif 132#endif
134 133
135 INIT(onestwos); 134 INIT(onestwos);
diff --git a/lib/bitmap.c b/lib/bitmap.c
index b5a8b6ad2454..06fdfa1aeba7 100644
--- a/lib/bitmap.c
+++ b/lib/bitmap.c
@@ -369,7 +369,8 @@ EXPORT_SYMBOL(bitmap_find_next_zero_area);
369 * @nmaskbits: size of bitmap, in bits 369 * @nmaskbits: size of bitmap, in bits
370 * 370 *
371 * Exactly @nmaskbits bits are displayed. Hex digits are grouped into 371 * Exactly @nmaskbits bits are displayed. Hex digits are grouped into
372 * comma-separated sets of eight digits per set. 372 * comma-separated sets of eight digits per set. Returns the number of
373 * characters which were written to *buf, excluding the trailing \0.
373 */ 374 */
374int bitmap_scnprintf(char *buf, unsigned int buflen, 375int bitmap_scnprintf(char *buf, unsigned int buflen,
375 const unsigned long *maskp, int nmaskbits) 376 const unsigned long *maskp, int nmaskbits)
@@ -517,8 +518,8 @@ EXPORT_SYMBOL(bitmap_parse_user);
517 * 518 *
518 * Helper routine for bitmap_scnlistprintf(). Write decimal number 519 * Helper routine for bitmap_scnlistprintf(). Write decimal number
519 * or range to buf, suppressing output past buf+buflen, with optional 520 * or range to buf, suppressing output past buf+buflen, with optional
520 * comma-prefix. Return len of what would be written to buf, if it 521 * comma-prefix. Return len of what was written to *buf, excluding the
521 * all fit. 522 * trailing \0.
522 */ 523 */
523static inline int bscnl_emit(char *buf, int buflen, int rbot, int rtop, int len) 524static inline int bscnl_emit(char *buf, int buflen, int rbot, int rtop, int len)
524{ 525{
@@ -544,9 +545,8 @@ static inline int bscnl_emit(char *buf, int buflen, int rbot, int rtop, int len)
544 * the range. Output format is compatible with the format 545 * the range. Output format is compatible with the format
545 * accepted as input by bitmap_parselist(). 546 * accepted as input by bitmap_parselist().
546 * 547 *
547 * The return value is the number of characters which would be 548 * The return value is the number of characters which were written to *buf
548 * generated for the given input, excluding the trailing '\0', as 549 * excluding the trailing '\0', as per ISO C99's scnprintf.
549 * per ISO C99.
550 */ 550 */
551int bitmap_scnlistprintf(char *buf, unsigned int buflen, 551int bitmap_scnlistprintf(char *buf, unsigned int buflen,
552 const unsigned long *maskp, int nmaskbits) 552 const unsigned long *maskp, int nmaskbits)
diff --git a/lib/btree.c b/lib/btree.c
index e5ec1e9c1aa5..f9a484676cb6 100644
--- a/lib/btree.c
+++ b/lib/btree.c
@@ -319,8 +319,8 @@ void *btree_get_prev(struct btree_head *head, struct btree_geo *geo,
319 319
320 if (head->height == 0) 320 if (head->height == 0)
321 return NULL; 321 return NULL;
322retry:
323 longcpy(key, __key, geo->keylen); 322 longcpy(key, __key, geo->keylen);
323retry:
324 dec_key(geo, key); 324 dec_key(geo, key);
325 325
326 node = head->node; 326 node = head->node;
@@ -351,7 +351,7 @@ retry:
351 } 351 }
352miss: 352miss:
353 if (retry_key) { 353 if (retry_key) {
354 __key = retry_key; 354 longcpy(key, retry_key, geo->keylen);
355 retry_key = NULL; 355 retry_key = NULL;
356 goto retry; 356 goto retry;
357 } 357 }
@@ -509,6 +509,7 @@ retry:
509int btree_insert(struct btree_head *head, struct btree_geo *geo, 509int btree_insert(struct btree_head *head, struct btree_geo *geo,
510 unsigned long *key, void *val, gfp_t gfp) 510 unsigned long *key, void *val, gfp_t gfp)
511{ 511{
512 BUG_ON(!val);
512 return btree_insert_level(head, geo, key, val, 1, gfp); 513 return btree_insert_level(head, geo, key, val, 1, gfp);
513} 514}
514EXPORT_SYMBOL_GPL(btree_insert); 515EXPORT_SYMBOL_GPL(btree_insert);
diff --git a/lib/cpu-notifier-error-inject.c b/lib/cpu-notifier-error-inject.c
index 4dc20321b0d5..707ca24f7b18 100644
--- a/lib/cpu-notifier-error-inject.c
+++ b/lib/cpu-notifier-error-inject.c
@@ -1,58 +1,45 @@
1#include <linux/kernel.h> 1#include <linux/kernel.h>
2#include <linux/cpu.h>
3#include <linux/module.h> 2#include <linux/module.h>
4#include <linux/notifier.h> 3#include <linux/cpu.h>
5 4
6static int priority; 5#include "notifier-error-inject.h"
7static int cpu_up_prepare_error;
8static int cpu_down_prepare_error;
9 6
7static int priority;
10module_param(priority, int, 0); 8module_param(priority, int, 0);
11MODULE_PARM_DESC(priority, "specify cpu notifier priority"); 9MODULE_PARM_DESC(priority, "specify cpu notifier priority");
12 10
13module_param(cpu_up_prepare_error, int, 0644); 11static struct notifier_err_inject cpu_notifier_err_inject = {
14MODULE_PARM_DESC(cpu_up_prepare_error, 12 .actions = {
15 "specify error code to inject CPU_UP_PREPARE action"); 13 { NOTIFIER_ERR_INJECT_ACTION(CPU_UP_PREPARE) },
16 14 { NOTIFIER_ERR_INJECT_ACTION(CPU_UP_PREPARE_FROZEN) },
17module_param(cpu_down_prepare_error, int, 0644); 15 { NOTIFIER_ERR_INJECT_ACTION(CPU_DOWN_PREPARE) },
18MODULE_PARM_DESC(cpu_down_prepare_error, 16 { NOTIFIER_ERR_INJECT_ACTION(CPU_DOWN_PREPARE_FROZEN) },
19 "specify error code to inject CPU_DOWN_PREPARE action"); 17 {}
20
21static int err_inject_cpu_callback(struct notifier_block *nfb,
22 unsigned long action, void *hcpu)
23{
24 int err = 0;
25
26 switch (action) {
27 case CPU_UP_PREPARE:
28 case CPU_UP_PREPARE_FROZEN:
29 err = cpu_up_prepare_error;
30 break;
31 case CPU_DOWN_PREPARE:
32 case CPU_DOWN_PREPARE_FROZEN:
33 err = cpu_down_prepare_error;
34 break;
35 } 18 }
36 if (err)
37 printk(KERN_INFO "Injecting error (%d) at cpu notifier\n", err);
38
39 return notifier_from_errno(err);
40}
41
42static struct notifier_block err_inject_cpu_notifier = {
43 .notifier_call = err_inject_cpu_callback,
44}; 19};
45 20
21static struct dentry *dir;
22
46static int err_inject_init(void) 23static int err_inject_init(void)
47{ 24{
48 err_inject_cpu_notifier.priority = priority; 25 int err;
26
27 dir = notifier_err_inject_init("cpu", notifier_err_inject_dir,
28 &cpu_notifier_err_inject, priority);
29 if (IS_ERR(dir))
30 return PTR_ERR(dir);
31
32 err = register_hotcpu_notifier(&cpu_notifier_err_inject.nb);
33 if (err)
34 debugfs_remove_recursive(dir);
49 35
50 return register_hotcpu_notifier(&err_inject_cpu_notifier); 36 return err;
51} 37}
52 38
53static void err_inject_exit(void) 39static void err_inject_exit(void)
54{ 40{
55 unregister_hotcpu_notifier(&err_inject_cpu_notifier); 41 unregister_hotcpu_notifier(&cpu_notifier_err_inject.nb);
42 debugfs_remove_recursive(dir);
56} 43}
57 44
58module_init(err_inject_init); 45module_init(err_inject_init);
diff --git a/lib/crc32.c b/lib/crc32.c
index b0d278fb1d91..61774b8db4de 100644
--- a/lib/crc32.c
+++ b/lib/crc32.c
@@ -74,7 +74,9 @@ crc32_body(u32 crc, unsigned char const *buf, size_t len, const u32 (*tab)[256])
74 size_t i; 74 size_t i;
75# endif 75# endif
76 const u32 *t0=tab[0], *t1=tab[1], *t2=tab[2], *t3=tab[3]; 76 const u32 *t0=tab[0], *t1=tab[1], *t2=tab[2], *t3=tab[3];
77# if CRC_LE_BITS != 32
77 const u32 *t4 = tab[4], *t5 = tab[5], *t6 = tab[6], *t7 = tab[7]; 78 const u32 *t4 = tab[4], *t5 = tab[5], *t6 = tab[6], *t7 = tab[7];
79# endif
78 u32 q; 80 u32 q;
79 81
80 /* Align it */ 82 /* Align it */
diff --git a/lib/debugobjects.c b/lib/debugobjects.c
index 0ab9ae8057f0..d11808ca4bc4 100644
--- a/lib/debugobjects.c
+++ b/lib/debugobjects.c
@@ -79,30 +79,29 @@ static const char *obj_states[ODEBUG_STATE_MAX] = {
79 [ODEBUG_STATE_NOTAVAILABLE] = "not available", 79 [ODEBUG_STATE_NOTAVAILABLE] = "not available",
80}; 80};
81 81
82static int fill_pool(void) 82static void fill_pool(void)
83{ 83{
84 gfp_t gfp = GFP_ATOMIC | __GFP_NORETRY | __GFP_NOWARN; 84 gfp_t gfp = GFP_ATOMIC | __GFP_NORETRY | __GFP_NOWARN;
85 struct debug_obj *new; 85 struct debug_obj *new;
86 unsigned long flags; 86 unsigned long flags;
87 87
88 if (likely(obj_pool_free >= ODEBUG_POOL_MIN_LEVEL)) 88 if (likely(obj_pool_free >= ODEBUG_POOL_MIN_LEVEL))
89 return obj_pool_free; 89 return;
90 90
91 if (unlikely(!obj_cache)) 91 if (unlikely(!obj_cache))
92 return obj_pool_free; 92 return;
93 93
94 while (obj_pool_free < ODEBUG_POOL_MIN_LEVEL) { 94 while (obj_pool_free < ODEBUG_POOL_MIN_LEVEL) {
95 95
96 new = kmem_cache_zalloc(obj_cache, gfp); 96 new = kmem_cache_zalloc(obj_cache, gfp);
97 if (!new) 97 if (!new)
98 return obj_pool_free; 98 return;
99 99
100 raw_spin_lock_irqsave(&pool_lock, flags); 100 raw_spin_lock_irqsave(&pool_lock, flags);
101 hlist_add_head(&new->node, &obj_pool); 101 hlist_add_head(&new->node, &obj_pool);
102 obj_pool_free++; 102 obj_pool_free++;
103 raw_spin_unlock_irqrestore(&pool_lock, flags); 103 raw_spin_unlock_irqrestore(&pool_lock, flags);
104 } 104 }
105 return obj_pool_free;
106} 105}
107 106
108/* 107/*
@@ -1052,10 +1051,10 @@ static int __init debug_objects_replace_static_objects(void)
1052 cnt++; 1051 cnt++;
1053 } 1052 }
1054 } 1053 }
1054 local_irq_enable();
1055 1055
1056 printk(KERN_DEBUG "ODEBUG: %d of %d active objects replaced\n", cnt, 1056 printk(KERN_DEBUG "ODEBUG: %d of %d active objects replaced\n", cnt,
1057 obj_pool_used); 1057 obj_pool_used);
1058 local_irq_enable();
1059 return 0; 1058 return 0;
1060free: 1059free:
1061 hlist_for_each_entry_safe(obj, node, tmp, &objects, node) { 1060 hlist_for_each_entry_safe(obj, node, tmp, &objects, node) {
diff --git a/lib/div64.c b/lib/div64.c
index 3ea24907d52e..a163b6caef73 100644
--- a/lib/div64.c
+++ b/lib/div64.c
@@ -87,7 +87,7 @@ EXPORT_SYMBOL(div_s64_rem);
87 * by the book 'Hacker's Delight'. The original source and full proof 87 * by the book 'Hacker's Delight'. The original source and full proof
88 * can be found here and is available for use without restriction. 88 * can be found here and is available for use without restriction.
89 * 89 *
90 * 'http://www.hackersdelight.org/HDcode/newCode/divDouble.c' 90 * 'http://www.hackersdelight.org/HDcode/newCode/divDouble.c.txt'
91 */ 91 */
92#ifndef div64_u64 92#ifndef div64_u64
93u64 div64_u64(u64 dividend, u64 divisor) 93u64 div64_u64(u64 dividend, u64 divisor)
diff --git a/lib/dma-debug.c b/lib/dma-debug.c
index 13ef2338be41..66ce41489133 100644
--- a/lib/dma-debug.c
+++ b/lib/dma-debug.c
@@ -78,7 +78,7 @@ static LIST_HEAD(free_entries);
78static DEFINE_SPINLOCK(free_entries_lock); 78static DEFINE_SPINLOCK(free_entries_lock);
79 79
80/* Global disable flag - will be set in case of an error */ 80/* Global disable flag - will be set in case of an error */
81static bool global_disable __read_mostly; 81static u32 global_disable __read_mostly;
82 82
83/* Global error count */ 83/* Global error count */
84static u32 error_count; 84static u32 error_count;
@@ -430,7 +430,7 @@ static struct dma_debug_entry *__dma_entry_alloc(void)
430 */ 430 */
431static struct dma_debug_entry *dma_entry_alloc(void) 431static struct dma_debug_entry *dma_entry_alloc(void)
432{ 432{
433 struct dma_debug_entry *entry = NULL; 433 struct dma_debug_entry *entry;
434 unsigned long flags; 434 unsigned long flags;
435 435
436 spin_lock_irqsave(&free_entries_lock, flags); 436 spin_lock_irqsave(&free_entries_lock, flags);
@@ -438,11 +438,14 @@ static struct dma_debug_entry *dma_entry_alloc(void)
438 if (list_empty(&free_entries)) { 438 if (list_empty(&free_entries)) {
439 pr_err("DMA-API: debugging out of memory - disabling\n"); 439 pr_err("DMA-API: debugging out of memory - disabling\n");
440 global_disable = true; 440 global_disable = true;
441 goto out; 441 spin_unlock_irqrestore(&free_entries_lock, flags);
442 return NULL;
442 } 443 }
443 444
444 entry = __dma_entry_alloc(); 445 entry = __dma_entry_alloc();
445 446
447 spin_unlock_irqrestore(&free_entries_lock, flags);
448
446#ifdef CONFIG_STACKTRACE 449#ifdef CONFIG_STACKTRACE
447 entry->stacktrace.max_entries = DMA_DEBUG_STACKTRACE_ENTRIES; 450 entry->stacktrace.max_entries = DMA_DEBUG_STACKTRACE_ENTRIES;
448 entry->stacktrace.entries = entry->st_entries; 451 entry->stacktrace.entries = entry->st_entries;
@@ -450,9 +453,6 @@ static struct dma_debug_entry *dma_entry_alloc(void)
450 save_stack_trace(&entry->stacktrace); 453 save_stack_trace(&entry->stacktrace);
451#endif 454#endif
452 455
453out:
454 spin_unlock_irqrestore(&free_entries_lock, flags);
455
456 return entry; 456 return entry;
457} 457}
458 458
@@ -657,7 +657,7 @@ static int dma_debug_fs_init(void)
657 657
658 global_disable_dent = debugfs_create_bool("disabled", 0444, 658 global_disable_dent = debugfs_create_bool("disabled", 0444,
659 dma_debug_dent, 659 dma_debug_dent,
660 (u32 *)&global_disable); 660 &global_disable);
661 if (!global_disable_dent) 661 if (!global_disable_dent)
662 goto out_err; 662 goto out_err;
663 663
diff --git a/lib/dynamic_debug.c b/lib/dynamic_debug.c
index 310c753cf83e..7ca29a0a3019 100644
--- a/lib/dynamic_debug.c
+++ b/lib/dynamic_debug.c
@@ -107,20 +107,22 @@ static char *ddebug_describe_flags(struct _ddebug *dp, char *buf,
107 return buf; 107 return buf;
108} 108}
109 109
110#define vpr_info_dq(q, msg) \ 110#define vpr_info(fmt, ...) \
111do { \ 111 if (verbose) do { pr_info(fmt, ##__VA_ARGS__); } while (0)
112 if (verbose) \ 112
113 /* trim last char off format print */ \ 113#define vpr_info_dq(q, msg) \
114 pr_info("%s: func=\"%s\" file=\"%s\" " \ 114do { \
115 "module=\"%s\" format=\"%.*s\" " \ 115 /* trim last char off format print */ \
116 "lineno=%u-%u", \ 116 vpr_info("%s: func=\"%s\" file=\"%s\" " \
117 msg, \ 117 "module=\"%s\" format=\"%.*s\" " \
118 q->function ? q->function : "", \ 118 "lineno=%u-%u", \
119 q->filename ? q->filename : "", \ 119 msg, \
120 q->module ? q->module : "", \ 120 q->function ? q->function : "", \
121 (int)(q->format ? strlen(q->format) - 1 : 0), \ 121 q->filename ? q->filename : "", \
122 q->format ? q->format : "", \ 122 q->module ? q->module : "", \
123 q->first_lineno, q->last_lineno); \ 123 (int)(q->format ? strlen(q->format) - 1 : 0), \
124 q->format ? q->format : "", \
125 q->first_lineno, q->last_lineno); \
124} while (0) 126} while (0)
125 127
126/* 128/*
@@ -180,12 +182,11 @@ static int ddebug_change(const struct ddebug_query *query,
180 if (newflags == dp->flags) 182 if (newflags == dp->flags)
181 continue; 183 continue;
182 dp->flags = newflags; 184 dp->flags = newflags;
183 if (verbose) 185 vpr_info("changed %s:%d [%s]%s =%s\n",
184 pr_info("changed %s:%d [%s]%s =%s\n", 186 trim_prefix(dp->filename), dp->lineno,
185 trim_prefix(dp->filename), dp->lineno, 187 dt->mod_name, dp->function,
186 dt->mod_name, dp->function, 188 ddebug_describe_flags(dp, flagbuf,
187 ddebug_describe_flags(dp, flagbuf, 189 sizeof(flagbuf)));
188 sizeof(flagbuf)));
189 } 190 }
190 } 191 }
191 mutex_unlock(&ddebug_lock); 192 mutex_unlock(&ddebug_lock);
@@ -337,7 +338,7 @@ static int check_set(const char **dest, char *src, char *name)
337 * Returns 0 on success, <0 on error. 338 * Returns 0 on success, <0 on error.
338 */ 339 */
339static int ddebug_parse_query(char *words[], int nwords, 340static int ddebug_parse_query(char *words[], int nwords,
340 struct ddebug_query *query) 341 struct ddebug_query *query, const char *modname)
341{ 342{
342 unsigned int i; 343 unsigned int i;
343 int rc; 344 int rc;
@@ -347,6 +348,10 @@ static int ddebug_parse_query(char *words[], int nwords,
347 return -EINVAL; 348 return -EINVAL;
348 memset(query, 0, sizeof(*query)); 349 memset(query, 0, sizeof(*query));
349 350
351 if (modname)
352 /* support $modname.dyndbg=<multiple queries> */
353 query->module = modname;
354
350 for (i = 0 ; i < nwords ; i += 2) { 355 for (i = 0 ; i < nwords ; i += 2) {
351 if (!strcmp(words[i], "func")) 356 if (!strcmp(words[i], "func"))
352 rc = check_set(&query->function, words[i+1], "func"); 357 rc = check_set(&query->function, words[i+1], "func");
@@ -410,8 +415,7 @@ static int ddebug_parse_flags(const char *str, unsigned int *flagsp,
410 default: 415 default:
411 return -EINVAL; 416 return -EINVAL;
412 } 417 }
413 if (verbose) 418 vpr_info("op='%c'\n", op);
414 pr_info("op='%c'\n", op);
415 419
416 for ( ; *str ; ++str) { 420 for ( ; *str ; ++str) {
417 for (i = ARRAY_SIZE(opt_array) - 1; i >= 0; i--) { 421 for (i = ARRAY_SIZE(opt_array) - 1; i >= 0; i--) {
@@ -423,8 +427,7 @@ static int ddebug_parse_flags(const char *str, unsigned int *flagsp,
423 if (i < 0) 427 if (i < 0)
424 return -EINVAL; 428 return -EINVAL;
425 } 429 }
426 if (verbose) 430 vpr_info("flags=0x%x\n", flags);
427 pr_info("flags=0x%x\n", flags);
428 431
429 /* calculate final *flagsp, *maskp according to mask and op */ 432 /* calculate final *flagsp, *maskp according to mask and op */
430 switch (op) { 433 switch (op) {
@@ -441,12 +444,11 @@ static int ddebug_parse_flags(const char *str, unsigned int *flagsp,
441 *flagsp = 0; 444 *flagsp = 0;
442 break; 445 break;
443 } 446 }
444 if (verbose) 447 vpr_info("*flagsp=0x%x *maskp=0x%x\n", *flagsp, *maskp);
445 pr_info("*flagsp=0x%x *maskp=0x%x\n", *flagsp, *maskp);
446 return 0; 448 return 0;
447} 449}
448 450
449static int ddebug_exec_query(char *query_string) 451static int ddebug_exec_query(char *query_string, const char *modname)
450{ 452{
451 unsigned int flags = 0, mask = 0; 453 unsigned int flags = 0, mask = 0;
452 struct ddebug_query query; 454 struct ddebug_query query;
@@ -457,7 +459,7 @@ static int ddebug_exec_query(char *query_string)
457 nwords = ddebug_tokenize(query_string, words, MAXWORDS); 459 nwords = ddebug_tokenize(query_string, words, MAXWORDS);
458 if (nwords <= 0) 460 if (nwords <= 0)
459 return -EINVAL; 461 return -EINVAL;
460 if (ddebug_parse_query(words, nwords-1, &query)) 462 if (ddebug_parse_query(words, nwords-1, &query, modname))
461 return -EINVAL; 463 return -EINVAL;
462 if (ddebug_parse_flags(words[nwords-1], &flags, &mask)) 464 if (ddebug_parse_flags(words[nwords-1], &flags, &mask))
463 return -EINVAL; 465 return -EINVAL;
@@ -473,7 +475,7 @@ static int ddebug_exec_query(char *query_string)
473 last error or number of matching callsites. Module name is either 475 last error or number of matching callsites. Module name is either
474 in param (for boot arg) or perhaps in query string. 476 in param (for boot arg) or perhaps in query string.
475*/ 477*/
476static int ddebug_exec_queries(char *query) 478static int ddebug_exec_queries(char *query, const char *modname)
477{ 479{
478 char *split; 480 char *split;
479 int i, errs = 0, exitcode = 0, rc, nfound = 0; 481 int i, errs = 0, exitcode = 0, rc, nfound = 0;
@@ -487,10 +489,9 @@ static int ddebug_exec_queries(char *query)
487 if (!query || !*query || *query == '#') 489 if (!query || !*query || *query == '#')
488 continue; 490 continue;
489 491
490 if (verbose) 492 vpr_info("query %d: \"%s\"\n", i, query);
491 pr_info("query %d: \"%s\"\n", i, query);
492 493
493 rc = ddebug_exec_query(query); 494 rc = ddebug_exec_query(query, modname);
494 if (rc < 0) { 495 if (rc < 0) {
495 errs++; 496 errs++;
496 exitcode = rc; 497 exitcode = rc;
@@ -498,7 +499,7 @@ static int ddebug_exec_queries(char *query)
498 nfound += rc; 499 nfound += rc;
499 i++; 500 i++;
500 } 501 }
501 pr_info("processed %d queries, with %d matches, %d errs\n", 502 vpr_info("processed %d queries, with %d matches, %d errs\n",
502 i, nfound, errs); 503 i, nfound, errs);
503 504
504 if (exitcode) 505 if (exitcode)
@@ -653,10 +654,9 @@ static ssize_t ddebug_proc_write(struct file *file, const char __user *ubuf,
653 return -EFAULT; 654 return -EFAULT;
654 } 655 }
655 tmpbuf[len] = '\0'; 656 tmpbuf[len] = '\0';
656 if (verbose) 657 vpr_info("read %d bytes from userspace\n", (int)len);
657 pr_info("read %d bytes from userspace\n", (int)len);
658 658
659 ret = ddebug_exec_queries(tmpbuf); 659 ret = ddebug_exec_queries(tmpbuf, NULL);
660 kfree(tmpbuf); 660 kfree(tmpbuf);
661 if (ret < 0) 661 if (ret < 0)
662 return ret; 662 return ret;
@@ -717,8 +717,7 @@ static void *ddebug_proc_start(struct seq_file *m, loff_t *pos)
717 struct _ddebug *dp; 717 struct _ddebug *dp;
718 int n = *pos; 718 int n = *pos;
719 719
720 if (verbose) 720 vpr_info("called m=%p *pos=%lld\n", m, (unsigned long long)*pos);
721 pr_info("called m=%p *pos=%lld\n", m, (unsigned long long)*pos);
722 721
723 mutex_lock(&ddebug_lock); 722 mutex_lock(&ddebug_lock);
724 723
@@ -742,9 +741,8 @@ static void *ddebug_proc_next(struct seq_file *m, void *p, loff_t *pos)
742 struct ddebug_iter *iter = m->private; 741 struct ddebug_iter *iter = m->private;
743 struct _ddebug *dp; 742 struct _ddebug *dp;
744 743
745 if (verbose) 744 vpr_info("called m=%p p=%p *pos=%lld\n",
746 pr_info("called m=%p p=%p *pos=%lld\n", 745 m, p, (unsigned long long)*pos);
747 m, p, (unsigned long long)*pos);
748 746
749 if (p == SEQ_START_TOKEN) 747 if (p == SEQ_START_TOKEN)
750 dp = ddebug_iter_first(iter); 748 dp = ddebug_iter_first(iter);
@@ -766,8 +764,7 @@ static int ddebug_proc_show(struct seq_file *m, void *p)
766 struct _ddebug *dp = p; 764 struct _ddebug *dp = p;
767 char flagsbuf[10]; 765 char flagsbuf[10];
768 766
769 if (verbose) 767 vpr_info("called m=%p p=%p\n", m, p);
770 pr_info("called m=%p p=%p\n", m, p);
771 768
772 if (p == SEQ_START_TOKEN) { 769 if (p == SEQ_START_TOKEN) {
773 seq_puts(m, 770 seq_puts(m,
@@ -791,8 +788,7 @@ static int ddebug_proc_show(struct seq_file *m, void *p)
791 */ 788 */
792static void ddebug_proc_stop(struct seq_file *m, void *p) 789static void ddebug_proc_stop(struct seq_file *m, void *p)
793{ 790{
794 if (verbose) 791 vpr_info("called m=%p p=%p\n", m, p);
795 pr_info("called m=%p p=%p\n", m, p);
796 mutex_unlock(&ddebug_lock); 792 mutex_unlock(&ddebug_lock);
797} 793}
798 794
@@ -815,8 +811,7 @@ static int ddebug_proc_open(struct inode *inode, struct file *file)
815 struct ddebug_iter *iter; 811 struct ddebug_iter *iter;
816 int err; 812 int err;
817 813
818 if (verbose) 814 vpr_info("called\n");
819 pr_info("called\n");
820 815
821 iter = kzalloc(sizeof(*iter), GFP_KERNEL); 816 iter = kzalloc(sizeof(*iter), GFP_KERNEL);
822 if (iter == NULL) 817 if (iter == NULL)
@@ -866,12 +861,51 @@ int ddebug_add_module(struct _ddebug *tab, unsigned int n,
866 list_add_tail(&dt->link, &ddebug_tables); 861 list_add_tail(&dt->link, &ddebug_tables);
867 mutex_unlock(&ddebug_lock); 862 mutex_unlock(&ddebug_lock);
868 863
869 if (verbose) 864 vpr_info("%u debug prints in module %s\n", n, dt->mod_name);
870 pr_info("%u debug prints in module %s\n", n, dt->mod_name);
871 return 0; 865 return 0;
872} 866}
873EXPORT_SYMBOL_GPL(ddebug_add_module); 867EXPORT_SYMBOL_GPL(ddebug_add_module);
874 868
869/* helper for ddebug_dyndbg_(boot|module)_param_cb */
870static int ddebug_dyndbg_param_cb(char *param, char *val,
871 const char *modname, int on_err)
872{
873 char *sep;
874
875 sep = strchr(param, '.');
876 if (sep) {
877 /* needed only for ddebug_dyndbg_boot_param_cb */
878 *sep = '\0';
879 modname = param;
880 param = sep + 1;
881 }
882 if (strcmp(param, "dyndbg"))
883 return on_err; /* determined by caller */
884
885 ddebug_exec_queries((val ? val : "+p"), modname);
886
887 return 0; /* query failure shouldnt stop module load */
888}
889
890/* handle both dyndbg and $module.dyndbg params at boot */
891static int ddebug_dyndbg_boot_param_cb(char *param, char *val,
892 const char *unused)
893{
894 vpr_info("%s=\"%s\"\n", param, val);
895 return ddebug_dyndbg_param_cb(param, val, NULL, 0);
896}
897
898/*
899 * modprobe foo finds foo.params in boot-args, strips "foo.", and
900 * passes them to load_module(). This callback gets unknown params,
901 * processes dyndbg params, rejects others.
902 */
903int ddebug_dyndbg_module_param_cb(char *param, char *val, const char *module)
904{
905 vpr_info("module: %s %s=\"%s\"\n", module, param, val);
906 return ddebug_dyndbg_param_cb(param, val, module, -ENOENT);
907}
908
875static void ddebug_table_free(struct ddebug_table *dt) 909static void ddebug_table_free(struct ddebug_table *dt)
876{ 910{
877 list_del_init(&dt->link); 911 list_del_init(&dt->link);
@@ -888,8 +922,7 @@ int ddebug_remove_module(const char *mod_name)
888 struct ddebug_table *dt, *nextdt; 922 struct ddebug_table *dt, *nextdt;
889 int ret = -ENOENT; 923 int ret = -ENOENT;
890 924
891 if (verbose) 925 vpr_info("removing module \"%s\"\n", mod_name);
892 pr_info("removing module \"%s\"\n", mod_name);
893 926
894 mutex_lock(&ddebug_lock); 927 mutex_lock(&ddebug_lock);
895 list_for_each_entry_safe(dt, nextdt, &ddebug_tables, link) { 928 list_for_each_entry_safe(dt, nextdt, &ddebug_tables, link) {
@@ -940,8 +973,10 @@ static int __init dynamic_debug_init(void)
940{ 973{
941 struct _ddebug *iter, *iter_start; 974 struct _ddebug *iter, *iter_start;
942 const char *modname = NULL; 975 const char *modname = NULL;
976 char *cmdline;
943 int ret = 0; 977 int ret = 0;
944 int n = 0; 978 int n = 0, entries = 0, modct = 0;
979 int verbose_bytes = 0;
945 980
946 if (__start___verbose == __stop___verbose) { 981 if (__start___verbose == __stop___verbose) {
947 pr_warn("_ddebug table is empty in a " 982 pr_warn("_ddebug table is empty in a "
@@ -952,10 +987,15 @@ static int __init dynamic_debug_init(void)
952 modname = iter->modname; 987 modname = iter->modname;
953 iter_start = iter; 988 iter_start = iter;
954 for (; iter < __stop___verbose; iter++) { 989 for (; iter < __stop___verbose; iter++) {
990 entries++;
991 verbose_bytes += strlen(iter->modname) + strlen(iter->function)
992 + strlen(iter->filename) + strlen(iter->format);
993
955 if (strcmp(modname, iter->modname)) { 994 if (strcmp(modname, iter->modname)) {
995 modct++;
956 ret = ddebug_add_module(iter_start, n, modname); 996 ret = ddebug_add_module(iter_start, n, modname);
957 if (ret) 997 if (ret)
958 goto out_free; 998 goto out_err;
959 n = 0; 999 n = 0;
960 modname = iter->modname; 1000 modname = iter->modname;
961 iter_start = iter; 1001 iter_start = iter;
@@ -964,29 +1004,45 @@ static int __init dynamic_debug_init(void)
964 } 1004 }
965 ret = ddebug_add_module(iter_start, n, modname); 1005 ret = ddebug_add_module(iter_start, n, modname);
966 if (ret) 1006 if (ret)
967 goto out_free; 1007 goto out_err;
1008
1009 ddebug_init_success = 1;
1010 vpr_info("%d modules, %d entries and %d bytes in ddebug tables,"
1011 " %d bytes in (readonly) verbose section\n",
1012 modct, entries, (int)( modct * sizeof(struct ddebug_table)),
1013 verbose_bytes + (int)(__stop___verbose - __start___verbose));
968 1014
969 /* ddebug_query boot param got passed -> set it up */ 1015 /* apply ddebug_query boot param, dont unload tables on err */
970 if (ddebug_setup_string[0] != '\0') { 1016 if (ddebug_setup_string[0] != '\0') {
971 ret = ddebug_exec_queries(ddebug_setup_string); 1017 pr_warn("ddebug_query param name is deprecated,"
1018 " change it to dyndbg\n");
1019 ret = ddebug_exec_queries(ddebug_setup_string, NULL);
972 if (ret < 0) 1020 if (ret < 0)
973 pr_warn("Invalid ddebug boot param %s", 1021 pr_warn("Invalid ddebug boot param %s",
974 ddebug_setup_string); 1022 ddebug_setup_string);
975 else 1023 else
976 pr_info("%d changes by ddebug_query\n", ret); 1024 pr_info("%d changes by ddebug_query\n", ret);
977
978 /* keep tables even on ddebug_query parse error */
979 ret = 0;
980 } 1025 }
1026 /* now that ddebug tables are loaded, process all boot args
1027 * again to find and activate queries given in dyndbg params.
1028 * While this has already been done for known boot params, it
1029 * ignored the unknown ones (dyndbg in particular). Reusing
1030 * parse_args avoids ad-hoc parsing. This will also attempt
1031 * to activate queries for not-yet-loaded modules, which is
1032 * slightly noisy if verbose, but harmless.
1033 */
1034 cmdline = kstrdup(saved_command_line, GFP_KERNEL);
1035 parse_args("dyndbg params", cmdline, NULL,
1036 0, 0, 0, &ddebug_dyndbg_boot_param_cb);
1037 kfree(cmdline);
1038 return 0;
981 1039
982out_free: 1040out_err:
983 if (ret) 1041 ddebug_remove_all_tables();
984 ddebug_remove_all_tables();
985 else
986 ddebug_init_success = 1;
987 return 0; 1042 return 0;
988} 1043}
989/* Allow early initialization for boot messages via boot param */ 1044/* Allow early initialization for boot messages via boot param */
990arch_initcall(dynamic_debug_init); 1045early_initcall(dynamic_debug_init);
1046
991/* Debugfs setup must be done later */ 1047/* Debugfs setup must be done later */
992module_init(dynamic_debug_init_debugfs); 1048fs_initcall(dynamic_debug_init_debugfs);
diff --git a/lib/dynamic_queue_limits.c b/lib/dynamic_queue_limits.c
index 6ab4587d052b..0777c5a45fa0 100644
--- a/lib/dynamic_queue_limits.c
+++ b/lib/dynamic_queue_limits.c
@@ -10,23 +10,27 @@
10#include <linux/jiffies.h> 10#include <linux/jiffies.h>
11#include <linux/dynamic_queue_limits.h> 11#include <linux/dynamic_queue_limits.h>
12 12
13#define POSDIFF(A, B) ((A) > (B) ? (A) - (B) : 0) 13#define POSDIFF(A, B) ((int)((A) - (B)) > 0 ? (A) - (B) : 0)
14#define AFTER_EQ(A, B) ((int)((A) - (B)) >= 0)
14 15
15/* Records completed count and recalculates the queue limit */ 16/* Records completed count and recalculates the queue limit */
16void dql_completed(struct dql *dql, unsigned int count) 17void dql_completed(struct dql *dql, unsigned int count)
17{ 18{
18 unsigned int inprogress, prev_inprogress, limit; 19 unsigned int inprogress, prev_inprogress, limit;
19 unsigned int ovlimit, all_prev_completed, completed; 20 unsigned int ovlimit, completed, num_queued;
21 bool all_prev_completed;
22
23 num_queued = ACCESS_ONCE(dql->num_queued);
20 24
21 /* Can't complete more than what's in queue */ 25 /* Can't complete more than what's in queue */
22 BUG_ON(count > dql->num_queued - dql->num_completed); 26 BUG_ON(count > num_queued - dql->num_completed);
23 27
24 completed = dql->num_completed + count; 28 completed = dql->num_completed + count;
25 limit = dql->limit; 29 limit = dql->limit;
26 ovlimit = POSDIFF(dql->num_queued - dql->num_completed, limit); 30 ovlimit = POSDIFF(num_queued - dql->num_completed, limit);
27 inprogress = dql->num_queued - completed; 31 inprogress = num_queued - completed;
28 prev_inprogress = dql->prev_num_queued - dql->num_completed; 32 prev_inprogress = dql->prev_num_queued - dql->num_completed;
29 all_prev_completed = POSDIFF(completed, dql->prev_num_queued); 33 all_prev_completed = AFTER_EQ(completed, dql->prev_num_queued);
30 34
31 if ((ovlimit && !inprogress) || 35 if ((ovlimit && !inprogress) ||
32 (dql->prev_ovlimit && all_prev_completed)) { 36 (dql->prev_ovlimit && all_prev_completed)) {
@@ -104,7 +108,7 @@ void dql_completed(struct dql *dql, unsigned int count)
104 dql->prev_ovlimit = ovlimit; 108 dql->prev_ovlimit = ovlimit;
105 dql->prev_last_obj_cnt = dql->last_obj_cnt; 109 dql->prev_last_obj_cnt = dql->last_obj_cnt;
106 dql->num_completed = completed; 110 dql->num_completed = completed;
107 dql->prev_num_queued = dql->num_queued; 111 dql->prev_num_queued = num_queued;
108} 112}
109EXPORT_SYMBOL(dql_completed); 113EXPORT_SYMBOL(dql_completed);
110 114
diff --git a/lib/fault-inject.c b/lib/fault-inject.c
index 6805453c18e7..f7210ad6cffd 100644
--- a/lib/fault-inject.c
+++ b/lib/fault-inject.c
@@ -101,6 +101,10 @@ static inline bool fail_stacktrace(struct fault_attr *attr)
101 101
102bool should_fail(struct fault_attr *attr, ssize_t size) 102bool should_fail(struct fault_attr *attr, ssize_t size)
103{ 103{
104 /* No need to check any other properties if the probability is 0 */
105 if (attr->probability == 0)
106 return false;
107
104 if (attr->task_filter && !fail_task(attr, current)) 108 if (attr->task_filter && !fail_task(attr, current))
105 return false; 109 return false;
106 110
diff --git a/lib/fdt.c b/lib/fdt.c
new file mode 100644
index 000000000000..97f20069fc37
--- /dev/null
+++ b/lib/fdt.c
@@ -0,0 +1,2 @@
1#include <linux/libfdt_env.h>
2#include "../scripts/dtc/libfdt/fdt.c"
diff --git a/lib/fdt_ro.c b/lib/fdt_ro.c
new file mode 100644
index 000000000000..f73c04ea7be4
--- /dev/null
+++ b/lib/fdt_ro.c
@@ -0,0 +1,2 @@
1#include <linux/libfdt_env.h>
2#include "../scripts/dtc/libfdt/fdt_ro.c"
diff --git a/lib/fdt_rw.c b/lib/fdt_rw.c
new file mode 100644
index 000000000000..0c1f0f4a4b13
--- /dev/null
+++ b/lib/fdt_rw.c
@@ -0,0 +1,2 @@
1#include <linux/libfdt_env.h>
2#include "../scripts/dtc/libfdt/fdt_rw.c"
diff --git a/lib/fdt_strerror.c b/lib/fdt_strerror.c
new file mode 100644
index 000000000000..8713e3ff4707
--- /dev/null
+++ b/lib/fdt_strerror.c
@@ -0,0 +1,2 @@
1#include <linux/libfdt_env.h>
2#include "../scripts/dtc/libfdt/fdt_strerror.c"
diff --git a/lib/fdt_sw.c b/lib/fdt_sw.c
new file mode 100644
index 000000000000..9ac7e50c76ce
--- /dev/null
+++ b/lib/fdt_sw.c
@@ -0,0 +1,2 @@
1#include <linux/libfdt_env.h>
2#include "../scripts/dtc/libfdt/fdt_sw.c"
diff --git a/lib/fdt_wip.c b/lib/fdt_wip.c
new file mode 100644
index 000000000000..45b3fc3d3ba1
--- /dev/null
+++ b/lib/fdt_wip.c
@@ -0,0 +1,2 @@
1#include <linux/libfdt_env.h>
2#include "../scripts/dtc/libfdt/fdt_wip.c"
diff --git a/lib/flex_proportions.c b/lib/flex_proportions.c
new file mode 100644
index 000000000000..c785554f9523
--- /dev/null
+++ b/lib/flex_proportions.c
@@ -0,0 +1,272 @@
1/*
2 * Floating proportions with flexible aging period
3 *
4 * Copyright (C) 2011, SUSE, Jan Kara <jack@suse.cz>
5 *
6 * The goal of this code is: Given different types of event, measure proportion
7 * of each type of event over time. The proportions are measured with
8 * exponentially decaying history to give smooth transitions. A formula
9 * expressing proportion of event of type 'j' is:
10 *
11 * p_{j} = (\Sum_{i>=0} x_{i,j}/2^{i+1})/(\Sum_{i>=0} x_i/2^{i+1})
12 *
13 * Where x_{i,j} is j's number of events in i-th last time period and x_i is
14 * total number of events in i-th last time period.
15 *
16 * Note that p_{j}'s are normalised, i.e.
17 *
18 * \Sum_{j} p_{j} = 1,
19 *
20 * This formula can be straightforwardly computed by maintaing denominator
21 * (let's call it 'd') and for each event type its numerator (let's call it
22 * 'n_j'). When an event of type 'j' happens, we simply need to do:
23 * n_j++; d++;
24 *
25 * When a new period is declared, we could do:
26 * d /= 2
27 * for each j
28 * n_j /= 2
29 *
30 * To avoid iteration over all event types, we instead shift numerator of event
31 * j lazily when someone asks for a proportion of event j or when event j
32 * occurs. This can bit trivially implemented by remembering last period in
33 * which something happened with proportion of type j.
34 */
35#include <linux/flex_proportions.h>
36
37int fprop_global_init(struct fprop_global *p)
38{
39 int err;
40
41 p->period = 0;
42 /* Use 1 to avoid dealing with periods with 0 events... */
43 err = percpu_counter_init(&p->events, 1);
44 if (err)
45 return err;
46 seqcount_init(&p->sequence);
47 return 0;
48}
49
50void fprop_global_destroy(struct fprop_global *p)
51{
52 percpu_counter_destroy(&p->events);
53}
54
55/*
56 * Declare @periods new periods. It is upto the caller to make sure period
57 * transitions cannot happen in parallel.
58 *
59 * The function returns true if the proportions are still defined and false
60 * if aging zeroed out all events. This can be used to detect whether declaring
61 * further periods has any effect.
62 */
63bool fprop_new_period(struct fprop_global *p, int periods)
64{
65 u64 events;
66 unsigned long flags;
67
68 local_irq_save(flags);
69 events = percpu_counter_sum(&p->events);
70 /*
71 * Don't do anything if there are no events.
72 */
73 if (events <= 1) {
74 local_irq_restore(flags);
75 return false;
76 }
77 write_seqcount_begin(&p->sequence);
78 if (periods < 64)
79 events -= events >> periods;
80 /* Use addition to avoid losing events happening between sum and set */
81 percpu_counter_add(&p->events, -events);
82 p->period += periods;
83 write_seqcount_end(&p->sequence);
84 local_irq_restore(flags);
85
86 return true;
87}
88
89/*
90 * ---- SINGLE ----
91 */
92
93int fprop_local_init_single(struct fprop_local_single *pl)
94{
95 pl->events = 0;
96 pl->period = 0;
97 raw_spin_lock_init(&pl->lock);
98 return 0;
99}
100
101void fprop_local_destroy_single(struct fprop_local_single *pl)
102{
103}
104
105static void fprop_reflect_period_single(struct fprop_global *p,
106 struct fprop_local_single *pl)
107{
108 unsigned int period = p->period;
109 unsigned long flags;
110
111 /* Fast path - period didn't change */
112 if (pl->period == period)
113 return;
114 raw_spin_lock_irqsave(&pl->lock, flags);
115 /* Someone updated pl->period while we were spinning? */
116 if (pl->period >= period) {
117 raw_spin_unlock_irqrestore(&pl->lock, flags);
118 return;
119 }
120 /* Aging zeroed our fraction? */
121 if (period - pl->period < BITS_PER_LONG)
122 pl->events >>= period - pl->period;
123 else
124 pl->events = 0;
125 pl->period = period;
126 raw_spin_unlock_irqrestore(&pl->lock, flags);
127}
128
129/* Event of type pl happened */
130void __fprop_inc_single(struct fprop_global *p, struct fprop_local_single *pl)
131{
132 fprop_reflect_period_single(p, pl);
133 pl->events++;
134 percpu_counter_add(&p->events, 1);
135}
136
137/* Return fraction of events of type pl */
138void fprop_fraction_single(struct fprop_global *p,
139 struct fprop_local_single *pl,
140 unsigned long *numerator, unsigned long *denominator)
141{
142 unsigned int seq;
143 s64 num, den;
144
145 do {
146 seq = read_seqcount_begin(&p->sequence);
147 fprop_reflect_period_single(p, pl);
148 num = pl->events;
149 den = percpu_counter_read_positive(&p->events);
150 } while (read_seqcount_retry(&p->sequence, seq));
151
152 /*
153 * Make fraction <= 1 and denominator > 0 even in presence of percpu
154 * counter errors
155 */
156 if (den <= num) {
157 if (num)
158 den = num;
159 else
160 den = 1;
161 }
162 *denominator = den;
163 *numerator = num;
164}
165
166/*
167 * ---- PERCPU ----
168 */
169#define PROP_BATCH (8*(1+ilog2(nr_cpu_ids)))
170
171int fprop_local_init_percpu(struct fprop_local_percpu *pl)
172{
173 int err;
174
175 err = percpu_counter_init(&pl->events, 0);
176 if (err)
177 return err;
178 pl->period = 0;
179 raw_spin_lock_init(&pl->lock);
180 return 0;
181}
182
183void fprop_local_destroy_percpu(struct fprop_local_percpu *pl)
184{
185 percpu_counter_destroy(&pl->events);
186}
187
188static void fprop_reflect_period_percpu(struct fprop_global *p,
189 struct fprop_local_percpu *pl)
190{
191 unsigned int period = p->period;
192 unsigned long flags;
193
194 /* Fast path - period didn't change */
195 if (pl->period == period)
196 return;
197 raw_spin_lock_irqsave(&pl->lock, flags);
198 /* Someone updated pl->period while we were spinning? */
199 if (pl->period >= period) {
200 raw_spin_unlock_irqrestore(&pl->lock, flags);
201 return;
202 }
203 /* Aging zeroed our fraction? */
204 if (period - pl->period < BITS_PER_LONG) {
205 s64 val = percpu_counter_read(&pl->events);
206
207 if (val < (nr_cpu_ids * PROP_BATCH))
208 val = percpu_counter_sum(&pl->events);
209
210 __percpu_counter_add(&pl->events,
211 -val + (val >> (period-pl->period)), PROP_BATCH);
212 } else
213 percpu_counter_set(&pl->events, 0);
214 pl->period = period;
215 raw_spin_unlock_irqrestore(&pl->lock, flags);
216}
217
218/* Event of type pl happened */
219void __fprop_inc_percpu(struct fprop_global *p, struct fprop_local_percpu *pl)
220{
221 fprop_reflect_period_percpu(p, pl);
222 __percpu_counter_add(&pl->events, 1, PROP_BATCH);
223 percpu_counter_add(&p->events, 1);
224}
225
226void fprop_fraction_percpu(struct fprop_global *p,
227 struct fprop_local_percpu *pl,
228 unsigned long *numerator, unsigned long *denominator)
229{
230 unsigned int seq;
231 s64 num, den;
232
233 do {
234 seq = read_seqcount_begin(&p->sequence);
235 fprop_reflect_period_percpu(p, pl);
236 num = percpu_counter_read_positive(&pl->events);
237 den = percpu_counter_read_positive(&p->events);
238 } while (read_seqcount_retry(&p->sequence, seq));
239
240 /*
241 * Make fraction <= 1 and denominator > 0 even in presence of percpu
242 * counter errors
243 */
244 if (den <= num) {
245 if (num)
246 den = num;
247 else
248 den = 1;
249 }
250 *denominator = den;
251 *numerator = num;
252}
253
254/*
255 * Like __fprop_inc_percpu() except that event is counted only if the given
256 * type has fraction smaller than @max_frac/FPROP_FRAC_BASE
257 */
258void __fprop_inc_percpu_max(struct fprop_global *p,
259 struct fprop_local_percpu *pl, int max_frac)
260{
261 if (unlikely(max_frac < FPROP_FRAC_BASE)) {
262 unsigned long numerator, denominator;
263
264 fprop_fraction_percpu(p, pl, &numerator, &denominator);
265 if (numerator >
266 (((u64)denominator) * max_frac) >> FPROP_FRAC_SHIFT)
267 return;
268 } else
269 fprop_reflect_period_percpu(p, pl);
270 __percpu_counter_add(&pl->events, 1, PROP_BATCH);
271 percpu_counter_add(&p->events, 1);
272}
diff --git a/lib/jedec_ddr_data.c b/lib/jedec_ddr_data.c
new file mode 100644
index 000000000000..6d2cbf1d567f
--- /dev/null
+++ b/lib/jedec_ddr_data.c
@@ -0,0 +1,135 @@
1/*
2 * DDR addressing details and AC timing parameters from JEDEC specs
3 *
4 * Copyright (C) 2012 Texas Instruments, Inc.
5 *
6 * Aneesh V <aneesh@ti.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2 as
10 * published by the Free Software Foundation.
11 */
12
13#include <memory/jedec_ddr.h>
14#include <linux/module.h>
15
16/* LPDDR2 addressing details from JESD209-2 section 2.4 */
17const struct lpddr2_addressing
18 lpddr2_jedec_addressing_table[NUM_DDR_ADDR_TABLE_ENTRIES] = {
19 {B4, T_REFI_15_6, T_RFC_90}, /* 64M */
20 {B4, T_REFI_15_6, T_RFC_90}, /* 128M */
21 {B4, T_REFI_7_8, T_RFC_90}, /* 256M */
22 {B4, T_REFI_7_8, T_RFC_90}, /* 512M */
23 {B8, T_REFI_7_8, T_RFC_130}, /* 1GS4 */
24 {B8, T_REFI_3_9, T_RFC_130}, /* 2GS4 */
25 {B8, T_REFI_3_9, T_RFC_130}, /* 4G */
26 {B8, T_REFI_3_9, T_RFC_210}, /* 8G */
27 {B4, T_REFI_7_8, T_RFC_130}, /* 1GS2 */
28 {B4, T_REFI_3_9, T_RFC_130}, /* 2GS2 */
29};
30EXPORT_SYMBOL_GPL(lpddr2_jedec_addressing_table);
31
32/* LPDDR2 AC timing parameters from JESD209-2 section 12 */
33const struct lpddr2_timings
34 lpddr2_jedec_timings[NUM_DDR_TIMING_TABLE_ENTRIES] = {
35 /* Speed bin 400(200 MHz) */
36 [0] = {
37 .max_freq = 200000000,
38 .min_freq = 10000000,
39 .tRPab = 21000,
40 .tRCD = 18000,
41 .tWR = 15000,
42 .tRAS_min = 42000,
43 .tRRD = 10000,
44 .tWTR = 10000,
45 .tXP = 7500,
46 .tRTP = 7500,
47 .tCKESR = 15000,
48 .tDQSCK_max = 5500,
49 .tFAW = 50000,
50 .tZQCS = 90000,
51 .tZQCL = 360000,
52 .tZQinit = 1000000,
53 .tRAS_max_ns = 70000,
54 .tDQSCK_max_derated = 6000,
55 },
56 /* Speed bin 533(266 MHz) */
57 [1] = {
58 .max_freq = 266666666,
59 .min_freq = 10000000,
60 .tRPab = 21000,
61 .tRCD = 18000,
62 .tWR = 15000,
63 .tRAS_min = 42000,
64 .tRRD = 10000,
65 .tWTR = 7500,
66 .tXP = 7500,
67 .tRTP = 7500,
68 .tCKESR = 15000,
69 .tDQSCK_max = 5500,
70 .tFAW = 50000,
71 .tZQCS = 90000,
72 .tZQCL = 360000,
73 .tZQinit = 1000000,
74 .tRAS_max_ns = 70000,
75 .tDQSCK_max_derated = 6000,
76 },
77 /* Speed bin 800(400 MHz) */
78 [2] = {
79 .max_freq = 400000000,
80 .min_freq = 10000000,
81 .tRPab = 21000,
82 .tRCD = 18000,
83 .tWR = 15000,
84 .tRAS_min = 42000,
85 .tRRD = 10000,
86 .tWTR = 7500,
87 .tXP = 7500,
88 .tRTP = 7500,
89 .tCKESR = 15000,
90 .tDQSCK_max = 5500,
91 .tFAW = 50000,
92 .tZQCS = 90000,
93 .tZQCL = 360000,
94 .tZQinit = 1000000,
95 .tRAS_max_ns = 70000,
96 .tDQSCK_max_derated = 6000,
97 },
98 /* Speed bin 1066(533 MHz) */
99 [3] = {
100 .max_freq = 533333333,
101 .min_freq = 10000000,
102 .tRPab = 21000,
103 .tRCD = 18000,
104 .tWR = 15000,
105 .tRAS_min = 42000,
106 .tRRD = 10000,
107 .tWTR = 7500,
108 .tXP = 7500,
109 .tRTP = 7500,
110 .tCKESR = 15000,
111 .tDQSCK_max = 5500,
112 .tFAW = 50000,
113 .tZQCS = 90000,
114 .tZQCL = 360000,
115 .tZQinit = 1000000,
116 .tRAS_max_ns = 70000,
117 .tDQSCK_max_derated = 5620,
118 },
119};
120EXPORT_SYMBOL_GPL(lpddr2_jedec_timings);
121
122const struct lpddr2_min_tck lpddr2_jedec_min_tck = {
123 .tRPab = 3,
124 .tRCD = 3,
125 .tWR = 3,
126 .tRASmin = 3,
127 .tRRD = 2,
128 .tWTR = 2,
129 .tXP = 2,
130 .tRTP = 2,
131 .tCKE = 3,
132 .tCKESR = 3,
133 .tFAW = 8
134};
135EXPORT_SYMBOL_GPL(lpddr2_jedec_min_tck);
diff --git a/lib/kobject.c b/lib/kobject.c
index aeefa8bc8b1c..e07ee1fcd6f1 100644
--- a/lib/kobject.c
+++ b/lib/kobject.c
@@ -47,13 +47,11 @@ static int populate_dir(struct kobject *kobj)
47static int create_dir(struct kobject *kobj) 47static int create_dir(struct kobject *kobj)
48{ 48{
49 int error = 0; 49 int error = 0;
50 if (kobject_name(kobj)) { 50 error = sysfs_create_dir(kobj);
51 error = sysfs_create_dir(kobj); 51 if (!error) {
52 if (!error) { 52 error = populate_dir(kobj);
53 error = populate_dir(kobj); 53 if (error)
54 if (error) 54 sysfs_remove_dir(kobj);
55 sysfs_remove_dir(kobj);
56 }
57 } 55 }
58 return error; 56 return error;
59} 57}
@@ -634,7 +632,7 @@ struct kobject *kobject_create(void)
634/** 632/**
635 * kobject_create_and_add - create a struct kobject dynamically and register it with sysfs 633 * kobject_create_and_add - create a struct kobject dynamically and register it with sysfs
636 * 634 *
637 * @name: the name for the kset 635 * @name: the name for the kobject
638 * @parent: the parent kobject of this kobject, if any. 636 * @parent: the parent kobject of this kobject, if any.
639 * 637 *
640 * This function creates a kobject structure dynamically and registers it 638 * This function creates a kobject structure dynamically and registers it
diff --git a/lib/kobject_uevent.c b/lib/kobject_uevent.c
index 1a91efa6d121..0401d2916d9f 100644
--- a/lib/kobject_uevent.c
+++ b/lib/kobject_uevent.c
@@ -373,13 +373,16 @@ EXPORT_SYMBOL_GPL(add_uevent_var);
373static int uevent_net_init(struct net *net) 373static int uevent_net_init(struct net *net)
374{ 374{
375 struct uevent_sock *ue_sk; 375 struct uevent_sock *ue_sk;
376 struct netlink_kernel_cfg cfg = {
377 .groups = 1,
378 };
376 379
377 ue_sk = kzalloc(sizeof(*ue_sk), GFP_KERNEL); 380 ue_sk = kzalloc(sizeof(*ue_sk), GFP_KERNEL);
378 if (!ue_sk) 381 if (!ue_sk)
379 return -ENOMEM; 382 return -ENOMEM;
380 383
381 ue_sk->sk = netlink_kernel_create(net, NETLINK_KOBJECT_UEVENT, 384 ue_sk->sk = netlink_kernel_create(net, NETLINK_KOBJECT_UEVENT,
382 1, NULL, NULL, THIS_MODULE); 385 THIS_MODULE, &cfg);
383 if (!ue_sk->sk) { 386 if (!ue_sk->sk) {
384 printk(KERN_ERR 387 printk(KERN_ERR
385 "kobject_uevent: unable to create netlink socket!\n"); 388 "kobject_uevent: unable to create netlink socket!\n");
diff --git a/lib/list_debug.c b/lib/list_debug.c
index 982b850d4e7a..c24c2f7e296f 100644
--- a/lib/list_debug.c
+++ b/lib/list_debug.c
@@ -10,6 +10,7 @@
10#include <linux/list.h> 10#include <linux/list.h>
11#include <linux/bug.h> 11#include <linux/bug.h>
12#include <linux/kernel.h> 12#include <linux/kernel.h>
13#include <linux/rculist.h>
13 14
14/* 15/*
15 * Insert a new entry between two known consecutive entries. 16 * Insert a new entry between two known consecutive entries.
@@ -30,6 +31,9 @@ void __list_add(struct list_head *new,
30 "list_add corruption. prev->next should be " 31 "list_add corruption. prev->next should be "
31 "next (%p), but was %p. (prev=%p).\n", 32 "next (%p), but was %p. (prev=%p).\n",
32 next, prev->next, prev); 33 next, prev->next, prev);
34 WARN(new == prev || new == next,
35 "list_add double add: new=%p, prev=%p, next=%p.\n",
36 new, prev, next);
33 next->prev = new; 37 next->prev = new;
34 new->next = next; 38 new->next = next;
35 new->prev = prev; 39 new->prev = prev;
@@ -75,3 +79,22 @@ void list_del(struct list_head *entry)
75 entry->prev = LIST_POISON2; 79 entry->prev = LIST_POISON2;
76} 80}
77EXPORT_SYMBOL(list_del); 81EXPORT_SYMBOL(list_del);
82
83/*
84 * RCU variants.
85 */
86void __list_add_rcu(struct list_head *new,
87 struct list_head *prev, struct list_head *next)
88{
89 WARN(next->prev != prev,
90 "list_add_rcu corruption. next->prev should be prev (%p), but was %p. (next=%p).\n",
91 prev, next->prev, next);
92 WARN(prev->next != next,
93 "list_add_rcu corruption. prev->next should be next (%p), but was %p. (prev=%p).\n",
94 next, prev->next, prev);
95 new->next = next;
96 new->prev = prev;
97 rcu_assign_pointer(list_next_rcu(prev), new);
98 next->prev = new;
99}
100EXPORT_SYMBOL(__list_add_rcu);
diff --git a/lib/memory-notifier-error-inject.c b/lib/memory-notifier-error-inject.c
new file mode 100644
index 000000000000..e6239bf0b0df
--- /dev/null
+++ b/lib/memory-notifier-error-inject.c
@@ -0,0 +1,48 @@
1#include <linux/kernel.h>
2#include <linux/module.h>
3#include <linux/memory.h>
4
5#include "notifier-error-inject.h"
6
7static int priority;
8module_param(priority, int, 0);
9MODULE_PARM_DESC(priority, "specify memory notifier priority");
10
11static struct notifier_err_inject memory_notifier_err_inject = {
12 .actions = {
13 { NOTIFIER_ERR_INJECT_ACTION(MEM_GOING_ONLINE) },
14 { NOTIFIER_ERR_INJECT_ACTION(MEM_GOING_OFFLINE) },
15 {}
16 }
17};
18
19static struct dentry *dir;
20
21static int err_inject_init(void)
22{
23 int err;
24
25 dir = notifier_err_inject_init("memory", notifier_err_inject_dir,
26 &memory_notifier_err_inject, priority);
27 if (IS_ERR(dir))
28 return PTR_ERR(dir);
29
30 err = register_memory_notifier(&memory_notifier_err_inject.nb);
31 if (err)
32 debugfs_remove_recursive(dir);
33
34 return err;
35}
36
37static void err_inject_exit(void)
38{
39 unregister_memory_notifier(&memory_notifier_err_inject.nb);
40 debugfs_remove_recursive(dir);
41}
42
43module_init(err_inject_init);
44module_exit(err_inject_exit);
45
46MODULE_DESCRIPTION("memory notifier error injection module");
47MODULE_LICENSE("GPL");
48MODULE_AUTHOR("Akinobu Mita <akinobu.mita@gmail.com>");
diff --git a/lib/memweight.c b/lib/memweight.c
new file mode 100644
index 000000000000..e35fc8771893
--- /dev/null
+++ b/lib/memweight.c
@@ -0,0 +1,38 @@
1#include <linux/export.h>
2#include <linux/bug.h>
3#include <linux/bitmap.h>
4
5/**
6 * memweight - count the total number of bits set in memory area
7 * @ptr: pointer to the start of the area
8 * @bytes: the size of the area
9 */
10size_t memweight(const void *ptr, size_t bytes)
11{
12 size_t ret = 0;
13 size_t longs;
14 const unsigned char *bitmap = ptr;
15
16 for (; bytes > 0 && ((unsigned long)bitmap) % sizeof(long);
17 bytes--, bitmap++)
18 ret += hweight8(*bitmap);
19
20 longs = bytes / sizeof(long);
21 if (longs) {
22 BUG_ON(longs >= INT_MAX / BITS_PER_LONG);
23 ret += bitmap_weight((unsigned long *)bitmap,
24 longs * BITS_PER_LONG);
25 bytes -= longs * sizeof(long);
26 bitmap += longs * sizeof(long);
27 }
28 /*
29 * The reason that this last loop is distinct from the preceding
30 * bitmap_weight() call is to compute 1-bits in the last region smaller
31 * than sizeof(long) properly on big-endian systems.
32 */
33 for (; bytes > 0; bytes--, bitmap++)
34 ret += hweight8(*bitmap);
35
36 return ret;
37}
38EXPORT_SYMBOL(memweight);
diff --git a/lib/mpi/Makefile b/lib/mpi/Makefile
index 567d52e74d77..45ca90a8639c 100644
--- a/lib/mpi/Makefile
+++ b/lib/mpi/Makefile
@@ -19,14 +19,3 @@ mpi-y = \
19 mpih-mul.o \ 19 mpih-mul.o \
20 mpi-pow.o \ 20 mpi-pow.o \
21 mpiutil.o 21 mpiutil.o
22
23mpi-$(CONFIG_MPILIB_EXTRA) += \
24 mpi-add.o \
25 mpi-div.o \
26 mpi-cmp.o \
27 mpi-gcd.o \
28 mpi-inline.o \
29 mpi-inv.o \
30 mpi-mpow.o \
31 mpi-mul.o \
32 mpi-scan.o
diff --git a/lib/mpi/generic_mpi-asm-defs.h b/lib/mpi/generic_mpi-asm-defs.h
deleted file mode 100644
index 047d1f5a7249..000000000000
--- a/lib/mpi/generic_mpi-asm-defs.h
+++ /dev/null
@@ -1,4 +0,0 @@
1/* This file defines some basic constants for the MPI machinery. We
2 * need to define the types on a per-CPU basis, so it is done with
3 * this file here. */
4#define BYTES_PER_MPI_LIMB (SIZEOF_UNSIGNED_LONG)
diff --git a/lib/mpi/mpi-add.c b/lib/mpi/mpi-add.c
deleted file mode 100644
index f56b9ba295e6..000000000000
--- a/lib/mpi/mpi-add.c
+++ /dev/null
@@ -1,234 +0,0 @@
1/* mpi-add.c - MPI functions
2 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
3 * Copyright (C) 1994, 1996 Free Software Foundation, Inc.
4 *
5 * This file is part of GnuPG.
6 *
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
20 *
21 * Note: This code is heavily based on the GNU MP Library.
22 * Actually it's the same code with only minor changes in the
23 * way the data is stored; this is to support the abstraction
24 * of an optional secure memory allocation which may be used
25 * to avoid revealing of sensitive data due to paging etc.
26 * The GNU MP Library itself is published under the LGPL;
27 * however I decided to publish this code under the plain GPL.
28 */
29
30#include "mpi-internal.h"
31
32/****************
33 * Add the unsigned integer V to the mpi-integer U and store the
34 * result in W. U and V may be the same.
35 */
36int mpi_add_ui(MPI w, const MPI u, unsigned long v)
37{
38 mpi_ptr_t wp, up;
39 mpi_size_t usize, wsize;
40 int usign, wsign;
41
42 usize = u->nlimbs;
43 usign = u->sign;
44 wsign = 0;
45
46 /* If not space for W (and possible carry), increase space. */
47 wsize = usize + 1;
48 if (w->alloced < wsize)
49 if (mpi_resize(w, wsize) < 0)
50 return -ENOMEM;
51
52 /* These must be after realloc (U may be the same as W). */
53 up = u->d;
54 wp = w->d;
55
56 if (!usize) { /* simple */
57 wp[0] = v;
58 wsize = v ? 1 : 0;
59 } else if (!usign) { /* mpi is not negative */
60 mpi_limb_t cy;
61 cy = mpihelp_add_1(wp, up, usize, v);
62 wp[usize] = cy;
63 wsize = usize + cy;
64 } else { /* The signs are different. Need exact comparison to determine
65 * which operand to subtract from which. */
66 if (usize == 1 && up[0] < v) {
67 wp[0] = v - up[0];
68 wsize = 1;
69 } else {
70 mpihelp_sub_1(wp, up, usize, v);
71 /* Size can decrease with at most one limb. */
72 wsize = usize - (wp[usize - 1] == 0);
73 wsign = 1;
74 }
75 }
76
77 w->nlimbs = wsize;
78 w->sign = wsign;
79 return 0;
80}
81
82int mpi_add(MPI w, MPI u, MPI v)
83{
84 mpi_ptr_t wp, up, vp;
85 mpi_size_t usize, vsize, wsize;
86 int usign, vsign, wsign;
87
88 if (u->nlimbs < v->nlimbs) { /* Swap U and V. */
89 usize = v->nlimbs;
90 usign = v->sign;
91 vsize = u->nlimbs;
92 vsign = u->sign;
93 wsize = usize + 1;
94 if (RESIZE_IF_NEEDED(w, wsize) < 0)
95 return -ENOMEM;
96 /* These must be after realloc (u or v may be the same as w). */
97 up = v->d;
98 vp = u->d;
99 } else {
100 usize = u->nlimbs;
101 usign = u->sign;
102 vsize = v->nlimbs;
103 vsign = v->sign;
104 wsize = usize + 1;
105 if (RESIZE_IF_NEEDED(w, wsize) < 0)
106 return -ENOMEM;
107 /* These must be after realloc (u or v may be the same as w). */
108 up = u->d;
109 vp = v->d;
110 }
111 wp = w->d;
112 wsign = 0;
113
114 if (!vsize) { /* simple */
115 MPN_COPY(wp, up, usize);
116 wsize = usize;
117 wsign = usign;
118 } else if (usign != vsign) { /* different sign */
119 /* This test is right since USIZE >= VSIZE */
120 if (usize != vsize) {
121 mpihelp_sub(wp, up, usize, vp, vsize);
122 wsize = usize;
123 MPN_NORMALIZE(wp, wsize);
124 wsign = usign;
125 } else if (mpihelp_cmp(up, vp, usize) < 0) {
126 mpihelp_sub_n(wp, vp, up, usize);
127 wsize = usize;
128 MPN_NORMALIZE(wp, wsize);
129 if (!usign)
130 wsign = 1;
131 } else {
132 mpihelp_sub_n(wp, up, vp, usize);
133 wsize = usize;
134 MPN_NORMALIZE(wp, wsize);
135 if (usign)
136 wsign = 1;
137 }
138 } else { /* U and V have same sign. Add them. */
139 mpi_limb_t cy = mpihelp_add(wp, up, usize, vp, vsize);
140 wp[usize] = cy;
141 wsize = usize + cy;
142 if (usign)
143 wsign = 1;
144 }
145
146 w->nlimbs = wsize;
147 w->sign = wsign;
148 return 0;
149}
150
151/****************
152 * Subtract the unsigned integer V from the mpi-integer U and store the
153 * result in W.
154 */
155int mpi_sub_ui(MPI w, MPI u, unsigned long v)
156{
157 mpi_ptr_t wp, up;
158 mpi_size_t usize, wsize;
159 int usign, wsign;
160
161 usize = u->nlimbs;
162 usign = u->sign;
163 wsign = 0;
164
165 /* If not space for W (and possible carry), increase space. */
166 wsize = usize + 1;
167 if (w->alloced < wsize)
168 if (mpi_resize(w, wsize) < 0)
169 return -ENOMEM;
170
171 /* These must be after realloc (U may be the same as W). */
172 up = u->d;
173 wp = w->d;
174
175 if (!usize) { /* simple */
176 wp[0] = v;
177 wsize = v ? 1 : 0;
178 wsign = 1;
179 } else if (usign) { /* mpi and v are negative */
180 mpi_limb_t cy;
181 cy = mpihelp_add_1(wp, up, usize, v);
182 wp[usize] = cy;
183 wsize = usize + cy;
184 } else { /* The signs are different. Need exact comparison to determine
185 * which operand to subtract from which. */
186 if (usize == 1 && up[0] < v) {
187 wp[0] = v - up[0];
188 wsize = 1;
189 wsign = 1;
190 } else {
191 mpihelp_sub_1(wp, up, usize, v);
192 /* Size can decrease with at most one limb. */
193 wsize = usize - (wp[usize - 1] == 0);
194 }
195 }
196
197 w->nlimbs = wsize;
198 w->sign = wsign;
199 return 0;
200}
201
202int mpi_sub(MPI w, MPI u, MPI v)
203{
204 int rc;
205
206 if (w == v) {
207 MPI vv;
208 if (mpi_copy(&vv, v) < 0)
209 return -ENOMEM;
210 vv->sign = !vv->sign;
211 rc = mpi_add(w, u, vv);
212 mpi_free(vv);
213 } else {
214 /* fixme: this is not thread-save (we temp. modify v) */
215 v->sign = !v->sign;
216 rc = mpi_add(w, u, v);
217 v->sign = !v->sign;
218 }
219 return rc;
220}
221
222int mpi_addm(MPI w, MPI u, MPI v, MPI m)
223{
224 if (mpi_add(w, u, v) < 0 || mpi_fdiv_r(w, w, m) < 0)
225 return -ENOMEM;
226 return 0;
227}
228
229int mpi_subm(MPI w, MPI u, MPI v, MPI m)
230{
231 if (mpi_sub(w, u, v) < 0 || mpi_fdiv_r(w, w, m) < 0)
232 return -ENOMEM;
233 return 0;
234}
diff --git a/lib/mpi/mpi-bit.c b/lib/mpi/mpi-bit.c
index 0c505361da19..568724804f29 100644
--- a/lib/mpi/mpi-bit.c
+++ b/lib/mpi/mpi-bit.c
@@ -54,165 +54,3 @@ unsigned mpi_get_nbits(MPI a)
54 return n; 54 return n;
55} 55}
56EXPORT_SYMBOL_GPL(mpi_get_nbits); 56EXPORT_SYMBOL_GPL(mpi_get_nbits);
57
58/****************
59 * Test whether bit N is set.
60 */
61int mpi_test_bit(MPI a, unsigned n)
62{
63 unsigned limbno, bitno;
64 mpi_limb_t limb;
65
66 limbno = n / BITS_PER_MPI_LIMB;
67 bitno = n % BITS_PER_MPI_LIMB;
68
69 if (limbno >= a->nlimbs)
70 return 0; /* too far left: this is a 0 */
71 limb = a->d[limbno];
72 return (limb & (A_LIMB_1 << bitno)) ? 1 : 0;
73}
74
75/****************
76 * Set bit N of A.
77 */
78int mpi_set_bit(MPI a, unsigned n)
79{
80 unsigned limbno, bitno;
81
82 limbno = n / BITS_PER_MPI_LIMB;
83 bitno = n % BITS_PER_MPI_LIMB;
84
85 if (limbno >= a->nlimbs) { /* resize */
86 if (a->alloced >= limbno)
87 if (mpi_resize(a, limbno + 1) < 0)
88 return -ENOMEM;
89 a->nlimbs = limbno + 1;
90 }
91 a->d[limbno] |= (A_LIMB_1 << bitno);
92 return 0;
93}
94
95/****************
96 * Set bit N of A. and clear all bits above
97 */
98int mpi_set_highbit(MPI a, unsigned n)
99{
100 unsigned limbno, bitno;
101
102 limbno = n / BITS_PER_MPI_LIMB;
103 bitno = n % BITS_PER_MPI_LIMB;
104
105 if (limbno >= a->nlimbs) { /* resize */
106 if (a->alloced >= limbno)
107 if (mpi_resize(a, limbno + 1) < 0)
108 return -ENOMEM;
109 a->nlimbs = limbno + 1;
110 }
111 a->d[limbno] |= (A_LIMB_1 << bitno);
112 for (bitno++; bitno < BITS_PER_MPI_LIMB; bitno++)
113 a->d[limbno] &= ~(A_LIMB_1 << bitno);
114 a->nlimbs = limbno + 1;
115 return 0;
116}
117
118/****************
119 * clear bit N of A and all bits above
120 */
121void mpi_clear_highbit(MPI a, unsigned n)
122{
123 unsigned limbno, bitno;
124
125 limbno = n / BITS_PER_MPI_LIMB;
126 bitno = n % BITS_PER_MPI_LIMB;
127
128 if (limbno >= a->nlimbs)
129 return; /* not allocated, so need to clear bits :-) */
130
131 for (; bitno < BITS_PER_MPI_LIMB; bitno++)
132 a->d[limbno] &= ~(A_LIMB_1 << bitno);
133 a->nlimbs = limbno + 1;
134}
135
136/****************
137 * Clear bit N of A.
138 */
139void mpi_clear_bit(MPI a, unsigned n)
140{
141 unsigned limbno, bitno;
142
143 limbno = n / BITS_PER_MPI_LIMB;
144 bitno = n % BITS_PER_MPI_LIMB;
145
146 if (limbno >= a->nlimbs)
147 return; /* don't need to clear this bit, it's to far to left */
148 a->d[limbno] &= ~(A_LIMB_1 << bitno);
149}
150
151/****************
152 * Shift A by N bits to the right
153 * FIXME: should use alloc_limb if X and A are same.
154 */
155int mpi_rshift(MPI x, MPI a, unsigned n)
156{
157 mpi_ptr_t xp;
158 mpi_size_t xsize;
159
160 xsize = a->nlimbs;
161 x->sign = a->sign;
162 if (RESIZE_IF_NEEDED(x, (size_t) xsize) < 0)
163 return -ENOMEM;
164 xp = x->d;
165
166 if (xsize) {
167 mpihelp_rshift(xp, a->d, xsize, n);
168 MPN_NORMALIZE(xp, xsize);
169 }
170 x->nlimbs = xsize;
171 return 0;
172}
173
174/****************
175 * Shift A by COUNT limbs to the left
176 * This is used only within the MPI library
177 */
178int mpi_lshift_limbs(MPI a, unsigned int count)
179{
180 const int n = a->nlimbs;
181 mpi_ptr_t ap;
182 int i;
183
184 if (!count || !n)
185 return 0;
186
187 if (RESIZE_IF_NEEDED(a, n + count) < 0)
188 return -ENOMEM;
189
190 ap = a->d;
191 for (i = n - 1; i >= 0; i--)
192 ap[i + count] = ap[i];
193 for (i = 0; i < count; i++)
194 ap[i] = 0;
195 a->nlimbs += count;
196 return 0;
197}
198
199/****************
200 * Shift A by COUNT limbs to the right
201 * This is used only within the MPI library
202 */
203void mpi_rshift_limbs(MPI a, unsigned int count)
204{
205 mpi_ptr_t ap = a->d;
206 mpi_size_t n = a->nlimbs;
207 unsigned int i;
208
209 if (count >= n) {
210 a->nlimbs = 0;
211 return;
212 }
213
214 for (i = 0; i < n - count; i++)
215 ap[i] = ap[i + count];
216 ap[i] = 0;
217 a->nlimbs -= count;
218}
diff --git a/lib/mpi/mpi-cmp.c b/lib/mpi/mpi-cmp.c
deleted file mode 100644
index 914bc42a8a80..000000000000
--- a/lib/mpi/mpi-cmp.c
+++ /dev/null
@@ -1,68 +0,0 @@
1/* mpi-cmp.c - MPI functions
2 * Copyright (C) 1998, 1999 Free Software Foundation, Inc.
3 *
4 * This file is part of GnuPG.
5 *
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
19 */
20
21#include "mpi-internal.h"
22
23int mpi_cmp_ui(MPI u, unsigned long v)
24{
25 mpi_limb_t limb = v;
26
27 mpi_normalize(u);
28 if (!u->nlimbs && !limb)
29 return 0;
30 if (u->sign)
31 return -1;
32 if (u->nlimbs > 1)
33 return 1;
34
35 if (u->d[0] == limb)
36 return 0;
37 else if (u->d[0] > limb)
38 return 1;
39 else
40 return -1;
41}
42
43int mpi_cmp(MPI u, MPI v)
44{
45 mpi_size_t usize, vsize;
46 int cmp;
47
48 mpi_normalize(u);
49 mpi_normalize(v);
50 usize = u->nlimbs;
51 vsize = v->nlimbs;
52 if (!u->sign && v->sign)
53 return 1;
54 if (u->sign && !v->sign)
55 return -1;
56 if (usize != vsize && !u->sign && !v->sign)
57 return usize - vsize;
58 if (usize != vsize && u->sign && v->sign)
59 return vsize + usize;
60 if (!usize)
61 return 0;
62 cmp = mpihelp_cmp(u->d, v->d, usize);
63 if (!cmp)
64 return 0;
65 if ((cmp < 0 ? 1 : 0) == (u->sign ? 1 : 0))
66 return 1;
67 return -1;
68}
diff --git a/lib/mpi/mpi-div.c b/lib/mpi/mpi-div.c
deleted file mode 100644
index f68cbbb4d4a4..000000000000
--- a/lib/mpi/mpi-div.c
+++ /dev/null
@@ -1,338 +0,0 @@
1/* mpi-div.c - MPI functions
2 * Copyright (C) 1994, 1996 Free Software Foundation, Inc.
3 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
4 *
5 * This file is part of GnuPG.
6 *
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
20 *
21 * Note: This code is heavily based on the GNU MP Library.
22 * Actually it's the same code with only minor changes in the
23 * way the data is stored; this is to support the abstraction
24 * of an optional secure memory allocation which may be used
25 * to avoid revealing of sensitive data due to paging etc.
26 * The GNU MP Library itself is published under the LGPL;
27 * however I decided to publish this code under the plain GPL.
28 */
29
30#include <linux/string.h>
31#include "mpi-internal.h"
32#include "longlong.h"
33
34int mpi_fdiv_r(MPI rem, MPI dividend, MPI divisor)
35{
36 int rc = -ENOMEM;
37 int divisor_sign = divisor->sign;
38 MPI temp_divisor = NULL;
39
40 /* We need the original value of the divisor after the remainder has been
41 * preliminary calculated. We have to copy it to temporary space if it's
42 * the same variable as REM. */
43 if (rem == divisor) {
44 if (mpi_copy(&temp_divisor, divisor) < 0)
45 goto nomem;
46 divisor = temp_divisor;
47 }
48
49 if (mpi_tdiv_qr(NULL, rem, dividend, divisor) < 0)
50 goto nomem;
51 if (((divisor_sign ? 1 : 0) ^ (dividend->sign ? 1 : 0)) && rem->nlimbs)
52 if (mpi_add(rem, rem, divisor) < 0)
53 goto nomem;
54
55 rc = 0;
56
57nomem:
58 if (temp_divisor)
59 mpi_free(temp_divisor);
60 return rc;
61}
62
63/****************
64 * Division rounding the quotient towards -infinity.
65 * The remainder gets the same sign as the denominator.
66 * rem is optional
67 */
68
69ulong mpi_fdiv_r_ui(MPI rem, MPI dividend, ulong divisor)
70{
71 mpi_limb_t rlimb;
72
73 rlimb = mpihelp_mod_1(dividend->d, dividend->nlimbs, divisor);
74 if (rlimb && dividend->sign)
75 rlimb = divisor - rlimb;
76
77 if (rem) {
78 rem->d[0] = rlimb;
79 rem->nlimbs = rlimb ? 1 : 0;
80 }
81 return rlimb;
82}
83
84int mpi_fdiv_q(MPI quot, MPI dividend, MPI divisor)
85{
86 MPI tmp = mpi_alloc(mpi_get_nlimbs(quot));
87 if (!tmp)
88 return -ENOMEM;
89 mpi_fdiv_qr(quot, tmp, dividend, divisor);
90 mpi_free(tmp);
91 return 0;
92}
93
94int mpi_fdiv_qr(MPI quot, MPI rem, MPI dividend, MPI divisor)
95{
96 int divisor_sign = divisor->sign;
97 MPI temp_divisor = NULL;
98
99 if (quot == divisor || rem == divisor) {
100 if (mpi_copy(&temp_divisor, divisor) < 0)
101 return -ENOMEM;
102 divisor = temp_divisor;
103 }
104
105 if (mpi_tdiv_qr(quot, rem, dividend, divisor) < 0)
106 goto nomem;
107
108 if ((divisor_sign ^ dividend->sign) && rem->nlimbs) {
109 if (mpi_sub_ui(quot, quot, 1) < 0)
110 goto nomem;
111 if (mpi_add(rem, rem, divisor) < 0)
112 goto nomem;
113 }
114
115 if (temp_divisor)
116 mpi_free(temp_divisor);
117
118 return 0;
119
120nomem:
121 mpi_free(temp_divisor);
122 return -ENOMEM;
123}
124
125/* If den == quot, den needs temporary storage.
126 * If den == rem, den needs temporary storage.
127 * If num == quot, num needs temporary storage.
128 * If den has temporary storage, it can be normalized while being copied,
129 * i.e no extra storage should be allocated.
130 */
131
132int mpi_tdiv_r(MPI rem, MPI num, MPI den)
133{
134 return mpi_tdiv_qr(NULL, rem, num, den);
135}
136
137int mpi_tdiv_qr(MPI quot, MPI rem, MPI num, MPI den)
138{
139 int rc = -ENOMEM;
140 mpi_ptr_t np, dp;
141 mpi_ptr_t qp, rp;
142 mpi_size_t nsize = num->nlimbs;
143 mpi_size_t dsize = den->nlimbs;
144 mpi_size_t qsize, rsize;
145 mpi_size_t sign_remainder = num->sign;
146 mpi_size_t sign_quotient = num->sign ^ den->sign;
147 unsigned normalization_steps;
148 mpi_limb_t q_limb;
149 mpi_ptr_t marker[5];
150 int markidx = 0;
151
152 if (!dsize)
153 return -EINVAL;
154
155 memset(marker, 0, sizeof(marker));
156
157 /* Ensure space is enough for quotient and remainder.
158 * We need space for an extra limb in the remainder, because it's
159 * up-shifted (normalized) below. */
160 rsize = nsize + 1;
161 if (mpi_resize(rem, rsize) < 0)
162 goto nomem;
163
164 qsize = rsize - dsize; /* qsize cannot be bigger than this. */
165 if (qsize <= 0) {
166 if (num != rem) {
167 rem->nlimbs = num->nlimbs;
168 rem->sign = num->sign;
169 MPN_COPY(rem->d, num->d, nsize);
170 }
171 if (quot) {
172 /* This needs to follow the assignment to rem, in case the
173 * numerator and quotient are the same. */
174 quot->nlimbs = 0;
175 quot->sign = 0;
176 }
177 return 0;
178 }
179
180 if (quot)
181 if (mpi_resize(quot, qsize) < 0)
182 goto nomem;
183
184 /* Read pointers here, when reallocation is finished. */
185 np = num->d;
186 dp = den->d;
187 rp = rem->d;
188
189 /* Optimize division by a single-limb divisor. */
190 if (dsize == 1) {
191 mpi_limb_t rlimb;
192 if (quot) {
193 qp = quot->d;
194 rlimb = mpihelp_divmod_1(qp, np, nsize, dp[0]);
195 qsize -= qp[qsize - 1] == 0;
196 quot->nlimbs = qsize;
197 quot->sign = sign_quotient;
198 } else
199 rlimb = mpihelp_mod_1(np, nsize, dp[0]);
200 rp[0] = rlimb;
201 rsize = rlimb != 0 ? 1 : 0;
202 rem->nlimbs = rsize;
203 rem->sign = sign_remainder;
204 return 0;
205 }
206
207 if (quot) {
208 qp = quot->d;
209 /* Make sure QP and NP point to different objects. Otherwise the
210 * numerator would be gradually overwritten by the quotient limbs. */
211 if (qp == np) { /* Copy NP object to temporary space. */
212 np = marker[markidx++] = mpi_alloc_limb_space(nsize);
213 if (!np)
214 goto nomem;
215 MPN_COPY(np, qp, nsize);
216 }
217 } else /* Put quotient at top of remainder. */
218 qp = rp + dsize;
219
220 count_leading_zeros(normalization_steps, dp[dsize - 1]);
221
222 /* Normalize the denominator, i.e. make its most significant bit set by
223 * shifting it NORMALIZATION_STEPS bits to the left. Also shift the
224 * numerator the same number of steps (to keep the quotient the same!).
225 */
226 if (normalization_steps) {
227 mpi_ptr_t tp;
228 mpi_limb_t nlimb;
229
230 /* Shift up the denominator setting the most significant bit of
231 * the most significant word. Use temporary storage not to clobber
232 * the original contents of the denominator. */
233 tp = marker[markidx++] = mpi_alloc_limb_space(dsize);
234 if (!tp)
235 goto nomem;
236 mpihelp_lshift(tp, dp, dsize, normalization_steps);
237 dp = tp;
238
239 /* Shift up the numerator, possibly introducing a new most
240 * significant word. Move the shifted numerator in the remainder
241 * meanwhile. */
242 nlimb = mpihelp_lshift(rp, np, nsize, normalization_steps);
243 if (nlimb) {
244 rp[nsize] = nlimb;
245 rsize = nsize + 1;
246 } else
247 rsize = nsize;
248 } else {
249 /* The denominator is already normalized, as required. Copy it to
250 * temporary space if it overlaps with the quotient or remainder. */
251 if (dp == rp || (quot && (dp == qp))) {
252 mpi_ptr_t tp;
253
254 tp = marker[markidx++] = mpi_alloc_limb_space(dsize);
255 if (!tp)
256 goto nomem;
257 MPN_COPY(tp, dp, dsize);
258 dp = tp;
259 }
260
261 /* Move the numerator to the remainder. */
262 if (rp != np)
263 MPN_COPY(rp, np, nsize);
264
265 rsize = nsize;
266 }
267
268 q_limb = mpihelp_divrem(qp, 0, rp, rsize, dp, dsize);
269
270 if (quot) {
271 qsize = rsize - dsize;
272 if (q_limb) {
273 qp[qsize] = q_limb;
274 qsize += 1;
275 }
276
277 quot->nlimbs = qsize;
278 quot->sign = sign_quotient;
279 }
280
281 rsize = dsize;
282 MPN_NORMALIZE(rp, rsize);
283
284 if (normalization_steps && rsize) {
285 mpihelp_rshift(rp, rp, rsize, normalization_steps);
286 rsize -= rp[rsize - 1] == 0 ? 1 : 0;
287 }
288
289 rem->nlimbs = rsize;
290 rem->sign = sign_remainder;
291
292 rc = 0;
293nomem:
294 while (markidx)
295 mpi_free_limb_space(marker[--markidx]);
296 return rc;
297}
298
299int mpi_tdiv_q_2exp(MPI w, MPI u, unsigned count)
300{
301 mpi_size_t usize, wsize;
302 mpi_size_t limb_cnt;
303
304 usize = u->nlimbs;
305 limb_cnt = count / BITS_PER_MPI_LIMB;
306 wsize = usize - limb_cnt;
307 if (limb_cnt >= usize)
308 w->nlimbs = 0;
309 else {
310 mpi_ptr_t wp;
311 mpi_ptr_t up;
312
313 if (RESIZE_IF_NEEDED(w, wsize) < 0)
314 return -ENOMEM;
315 wp = w->d;
316 up = u->d;
317
318 count %= BITS_PER_MPI_LIMB;
319 if (count) {
320 mpihelp_rshift(wp, up + limb_cnt, wsize, count);
321 wsize -= !wp[wsize - 1];
322 } else {
323 MPN_COPY_INCR(wp, up + limb_cnt, wsize);
324 }
325
326 w->nlimbs = wsize;
327 }
328 return 0;
329}
330
331/****************
332 * Check whether dividend is divisible by divisor
333 * (note: divisor must fit into a limb)
334 */
335int mpi_divisible_ui(MPI dividend, ulong divisor)
336{
337 return !mpihelp_mod_1(dividend->d, dividend->nlimbs, divisor);
338}
diff --git a/lib/mpi/mpi-gcd.c b/lib/mpi/mpi-gcd.c
deleted file mode 100644
index 13c48aef9c4e..000000000000
--- a/lib/mpi/mpi-gcd.c
+++ /dev/null
@@ -1,59 +0,0 @@
1/* mpi-gcd.c - MPI functions
2 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
3 *
4 * This file is part of GnuPG.
5 *
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
19 */
20
21#include "mpi-internal.h"
22
23/****************
24 * Find the greatest common divisor G of A and B.
25 * Return: true if this 1, false in all other cases
26 */
27int mpi_gcd(MPI g, const MPI xa, const MPI xb)
28{
29 MPI a = NULL, b = NULL;
30
31 if (mpi_copy(&a, xa) < 0)
32 goto nomem;
33
34 if (mpi_copy(&b, xb) < 0)
35 goto nomem;
36
37 /* TAOCP Vol II, 4.5.2, Algorithm A */
38 a->sign = 0;
39 b->sign = 0;
40 while (mpi_cmp_ui(b, 0)) {
41 if (mpi_fdiv_r(g, a, b) < 0) /* g used as temorary variable */
42 goto nomem;
43 if (mpi_set(a, b) < 0)
44 goto nomem;
45 if (mpi_set(b, g) < 0)
46 goto nomem;
47 }
48 if (mpi_set(g, a) < 0)
49 goto nomem;
50
51 mpi_free(a);
52 mpi_free(b);
53 return !mpi_cmp_ui(g, 1);
54
55nomem:
56 mpi_free(a);
57 mpi_free(b);
58 return -ENOMEM;
59}
diff --git a/lib/mpi/mpi-inline.c b/lib/mpi/mpi-inline.c
deleted file mode 100644
index 654f68aeed8b..000000000000
--- a/lib/mpi/mpi-inline.c
+++ /dev/null
@@ -1,31 +0,0 @@
1/* mpi-inline.c
2 * Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
3 *
4 * This file is part of GnuPG.
5 *
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
19 */
20
21/* put the inline functions as real functions into the lib */
22#define G10_MPI_INLINE_DECL
23
24#include "mpi-internal.h"
25
26/* always include the header becuase it is only
27 * included by mpi-internal if __GCC__ is defined but we
28 * need it here in all cases and the above definition of
29 * of the macro allows us to do so
30 */
31#include "mpi-inline.h"
diff --git a/lib/mpi/mpi-inv.c b/lib/mpi/mpi-inv.c
deleted file mode 100644
index 0951f9847745..000000000000
--- a/lib/mpi/mpi-inv.c
+++ /dev/null
@@ -1,187 +0,0 @@
1/* mpi-inv.c - MPI functions
2 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
3 *
4 * This file is part of GnuPG.
5 *
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
19 */
20
21#include "mpi-internal.h"
22
23/****************
24 * Calculate the multiplicative inverse X of A mod N
25 * That is: Find the solution x for
26 * 1 = (a*x) mod n
27 */
28int mpi_invm(MPI x, const MPI a, const MPI n)
29{
30 /* Extended Euclid's algorithm (See TAOPC Vol II, 4.5.2, Alg X)
31 * modified according to Michael Penk's solution for Exercice 35
32 * with further enhancement */
33 MPI u = NULL, v = NULL;
34 MPI u1 = NULL, u2 = NULL, u3 = NULL;
35 MPI v1 = NULL, v2 = NULL, v3 = NULL;
36 MPI t1 = NULL, t2 = NULL, t3 = NULL;
37 unsigned k;
38 int sign;
39 int odd = 0;
40 int rc = -ENOMEM;
41
42 if (mpi_copy(&u, a) < 0)
43 goto cleanup;
44 if (mpi_copy(&v, n) < 0)
45 goto cleanup;
46
47 for (k = 0; !mpi_test_bit(u, 0) && !mpi_test_bit(v, 0); k++) {
48 if (mpi_rshift(u, u, 1) < 0)
49 goto cleanup;
50 if (mpi_rshift(v, v, 1) < 0)
51 goto cleanup;
52 }
53 odd = mpi_test_bit(v, 0);
54
55 u1 = mpi_alloc_set_ui(1);
56 if (!u1)
57 goto cleanup;
58 if (!odd) {
59 u2 = mpi_alloc_set_ui(0);
60 if (!u2)
61 goto cleanup;
62 }
63 if (mpi_copy(&u3, u) < 0)
64 goto cleanup;
65 if (mpi_copy(&v1, v) < 0)
66 goto cleanup;
67 if (!odd) {
68 v2 = mpi_alloc(mpi_get_nlimbs(u));
69 if (!v2)
70 goto cleanup;
71 if (mpi_sub(v2, u1, u) < 0)
72 goto cleanup; /* U is used as const 1 */
73 }
74 if (mpi_copy(&v3, v) < 0)
75 goto cleanup;
76 if (mpi_test_bit(u, 0)) { /* u is odd */
77 t1 = mpi_alloc_set_ui(0);
78 if (!t1)
79 goto cleanup;
80 if (!odd) {
81 t2 = mpi_alloc_set_ui(1);
82 if (!t2)
83 goto cleanup;
84 t2->sign = 1;
85 }
86 if (mpi_copy(&t3, v) < 0)
87 goto cleanup;
88 t3->sign = !t3->sign;
89 goto Y4;
90 } else {
91 t1 = mpi_alloc_set_ui(1);
92 if (!t1)
93 goto cleanup;
94 if (!odd) {
95 t2 = mpi_alloc_set_ui(0);
96 if (!t2)
97 goto cleanup;
98 }
99 if (mpi_copy(&t3, u) < 0)
100 goto cleanup;
101 }
102 do {
103 do {
104 if (!odd) {
105 if (mpi_test_bit(t1, 0) || mpi_test_bit(t2, 0)) { /* one is odd */
106 if (mpi_add(t1, t1, v) < 0)
107 goto cleanup;
108 if (mpi_sub(t2, t2, u) < 0)
109 goto cleanup;
110 }
111 if (mpi_rshift(t1, t1, 1) < 0)
112 goto cleanup;
113 if (mpi_rshift(t2, t2, 1) < 0)
114 goto cleanup;
115 if (mpi_rshift(t3, t3, 1) < 0)
116 goto cleanup;
117 } else {
118 if (mpi_test_bit(t1, 0))
119 if (mpi_add(t1, t1, v) < 0)
120 goto cleanup;
121 if (mpi_rshift(t1, t1, 1) < 0)
122 goto cleanup;
123 if (mpi_rshift(t3, t3, 1) < 0)
124 goto cleanup;
125 }
126Y4:
127 ;
128 } while (!mpi_test_bit(t3, 0)); /* while t3 is even */
129
130 if (!t3->sign) {
131 if (mpi_set(u1, t1) < 0)
132 goto cleanup;
133 if (!odd)
134 if (mpi_set(u2, t2) < 0)
135 goto cleanup;
136 if (mpi_set(u3, t3) < 0)
137 goto cleanup;
138 } else {
139 if (mpi_sub(v1, v, t1) < 0)
140 goto cleanup;
141 sign = u->sign;
142 u->sign = !u->sign;
143 if (!odd)
144 if (mpi_sub(v2, u, t2) < 0)
145 goto cleanup;
146 u->sign = sign;
147 sign = t3->sign;
148 t3->sign = !t3->sign;
149 if (mpi_set(v3, t3) < 0)
150 goto cleanup;
151 t3->sign = sign;
152 }
153 if (mpi_sub(t1, u1, v1) < 0)
154 goto cleanup;
155 if (!odd)
156 if (mpi_sub(t2, u2, v2) < 0)
157 goto cleanup;
158 if (mpi_sub(t3, u3, v3) < 0)
159 goto cleanup;
160 if (t1->sign) {
161 if (mpi_add(t1, t1, v) < 0)
162 goto cleanup;
163 if (!odd)
164 if (mpi_sub(t2, t2, u) < 0)
165 goto cleanup;
166 }
167 } while (mpi_cmp_ui(t3, 0)); /* while t3 != 0 */
168 /* mpi_lshift( u3, k ); */
169 rc = mpi_set(x, u1);
170
171cleanup:
172 mpi_free(u1);
173 mpi_free(v1);
174 mpi_free(t1);
175 if (!odd) {
176 mpi_free(u2);
177 mpi_free(v2);
178 mpi_free(t2);
179 }
180 mpi_free(u3);
181 mpi_free(v3);
182 mpi_free(t3);
183
184 mpi_free(u);
185 mpi_free(v);
186 return rc;
187}
diff --git a/lib/mpi/mpi-mpow.c b/lib/mpi/mpi-mpow.c
deleted file mode 100644
index 7328d0d6c748..000000000000
--- a/lib/mpi/mpi-mpow.c
+++ /dev/null
@@ -1,134 +0,0 @@
1/* mpi-mpow.c - MPI functions
2 * Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3 *
4 * This file is part of GnuPG.
5 *
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
19 */
20
21#include "mpi-internal.h"
22#include "longlong.h"
23
24static int build_index(const MPI *exparray, int k, int i, int t)
25{
26 int j, bitno;
27 int index = 0;
28
29 bitno = t - i;
30 for (j = k - 1; j >= 0; j--) {
31 index <<= 1;
32 if (mpi_test_bit(exparray[j], bitno))
33 index |= 1;
34 }
35 return index;
36}
37
38/****************
39 * RES = (BASE[0] ^ EXP[0]) * (BASE[1] ^ EXP[1]) * ... * mod M
40 */
41int mpi_mulpowm(MPI res, MPI *basearray, MPI *exparray, MPI m)
42{
43 int rc = -ENOMEM;
44 int k; /* number of elements */
45 int t; /* bit size of largest exponent */
46 int i, j, idx;
47 MPI *G = NULL; /* table with precomputed values of size 2^k */
48 MPI tmp = NULL;
49
50 for (k = 0; basearray[k]; k++)
51 ;
52 if (!k) {
53 pr_emerg("mpi_mulpowm: assert(k) failed\n");
54 BUG();
55 }
56 for (t = 0, i = 0; (tmp = exparray[i]); i++) {
57 j = mpi_get_nbits(tmp);
58 if (j > t)
59 t = j;
60 }
61 if (i != k) {
62 pr_emerg("mpi_mulpowm: assert(i==k) failed\n");
63 BUG();
64 }
65 if (!t) {
66 pr_emerg("mpi_mulpowm: assert(t) failed\n");
67 BUG();
68 }
69 if (k >= 10) {
70 pr_emerg("mpi_mulpowm: assert(k<10) failed\n");
71 BUG();
72 }
73
74 G = kzalloc((1 << k) * sizeof *G, GFP_KERNEL);
75 if (!G)
76 goto err_out;
77
78 /* and calculate */
79 tmp = mpi_alloc(mpi_get_nlimbs(m) + 1);
80 if (!tmp)
81 goto nomem;
82 if (mpi_set_ui(res, 1) < 0)
83 goto nomem;
84 for (i = 1; i <= t; i++) {
85 if (mpi_mulm(tmp, res, res, m) < 0)
86 goto nomem;
87 idx = build_index(exparray, k, i, t);
88 if (!(idx >= 0 && idx < (1 << k))) {
89 pr_emerg("mpi_mulpowm: assert(idx >= 0 && idx < (1<<k)) failed\n");
90 BUG();
91 }
92 if (!G[idx]) {
93 if (!idx) {
94 G[0] = mpi_alloc_set_ui(1);
95 if (!G[0])
96 goto nomem;
97 } else {
98 for (j = 0; j < k; j++) {
99 if ((idx & (1 << j))) {
100 if (!G[idx]) {
101 if (mpi_copy
102 (&G[idx],
103 basearray[j]) < 0)
104 goto nomem;
105 } else {
106 if (mpi_mulm
107 (G[idx], G[idx],
108 basearray[j],
109 m) < 0)
110 goto nomem;
111 }
112 }
113 }
114 if (!G[idx]) {
115 G[idx] = mpi_alloc(0);
116 if (!G[idx])
117 goto nomem;
118 }
119 }
120 }
121 if (mpi_mulm(res, tmp, G[idx], m) < 0)
122 goto nomem;
123 }
124
125 rc = 0;
126nomem:
127 /* cleanup */
128 mpi_free(tmp);
129 for (i = 0; i < (1 << k); i++)
130 mpi_free(G[i]);
131 kfree(G);
132err_out:
133 return rc;
134}
diff --git a/lib/mpi/mpi-mul.c b/lib/mpi/mpi-mul.c
deleted file mode 100644
index 1f3219e27292..000000000000
--- a/lib/mpi/mpi-mul.c
+++ /dev/null
@@ -1,194 +0,0 @@
1/* mpi-mul.c - MPI functions
2 * Copyright (C) 1994, 1996 Free Software Foundation, Inc.
3 * Copyright (C) 1998, 2001 Free Software Foundation, Inc.
4 *
5 * This file is part of GnuPG.
6 *
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
20 *
21 * Note: This code is heavily based on the GNU MP Library.
22 * Actually it's the same code with only minor changes in the
23 * way the data is stored; this is to support the abstraction
24 * of an optional secure memory allocation which may be used
25 * to avoid revealing of sensitive data due to paging etc.
26 * The GNU MP Library itself is published under the LGPL;
27 * however I decided to publish this code under the plain GPL.
28 */
29
30#include "mpi-internal.h"
31
32int mpi_mul_ui(MPI prod, MPI mult, unsigned long small_mult)
33{
34 mpi_size_t size, prod_size;
35 mpi_ptr_t prod_ptr;
36 mpi_limb_t cy;
37 int sign;
38
39 size = mult->nlimbs;
40 sign = mult->sign;
41
42 if (!size || !small_mult) {
43 prod->nlimbs = 0;
44 prod->sign = 0;
45 return 0;
46 }
47
48 prod_size = size + 1;
49 if (prod->alloced < prod_size)
50 if (mpi_resize(prod, prod_size) < 0)
51 return -ENOMEM;
52 prod_ptr = prod->d;
53
54 cy = mpihelp_mul_1(prod_ptr, mult->d, size, (mpi_limb_t) small_mult);
55 if (cy)
56 prod_ptr[size++] = cy;
57 prod->nlimbs = size;
58 prod->sign = sign;
59 return 0;
60}
61
62int mpi_mul_2exp(MPI w, MPI u, unsigned long cnt)
63{
64 mpi_size_t usize, wsize, limb_cnt;
65 mpi_ptr_t wp;
66 mpi_limb_t wlimb;
67 int usign, wsign;
68
69 usize = u->nlimbs;
70 usign = u->sign;
71
72 if (!usize) {
73 w->nlimbs = 0;
74 w->sign = 0;
75 return 0;
76 }
77
78 limb_cnt = cnt / BITS_PER_MPI_LIMB;
79 wsize = usize + limb_cnt + 1;
80 if (w->alloced < wsize)
81 if (mpi_resize(w, wsize) < 0)
82 return -ENOMEM;
83 wp = w->d;
84 wsize = usize + limb_cnt;
85 wsign = usign;
86
87 cnt %= BITS_PER_MPI_LIMB;
88 if (cnt) {
89 wlimb = mpihelp_lshift(wp + limb_cnt, u->d, usize, cnt);
90 if (wlimb) {
91 wp[wsize] = wlimb;
92 wsize++;
93 }
94 } else {
95 MPN_COPY_DECR(wp + limb_cnt, u->d, usize);
96 }
97
98 /* Zero all whole limbs at low end. Do it here and not before calling
99 * mpn_lshift, not to lose for U == W. */
100 MPN_ZERO(wp, limb_cnt);
101
102 w->nlimbs = wsize;
103 w->sign = wsign;
104 return 0;
105}
106
107int mpi_mul(MPI w, MPI u, MPI v)
108{
109 int rc = -ENOMEM;
110 mpi_size_t usize, vsize, wsize;
111 mpi_ptr_t up, vp, wp;
112 mpi_limb_t cy;
113 int usign, vsign, sign_product;
114 int assign_wp = 0;
115 mpi_ptr_t tmp_limb = NULL;
116
117 if (u->nlimbs < v->nlimbs) { /* Swap U and V. */
118 usize = v->nlimbs;
119 usign = v->sign;
120 up = v->d;
121 vsize = u->nlimbs;
122 vsign = u->sign;
123 vp = u->d;
124 } else {
125 usize = u->nlimbs;
126 usign = u->sign;
127 up = u->d;
128 vsize = v->nlimbs;
129 vsign = v->sign;
130 vp = v->d;
131 }
132 sign_product = usign ^ vsign;
133 wp = w->d;
134
135 /* Ensure W has space enough to store the result. */
136 wsize = usize + vsize;
137 if (w->alloced < (size_t) wsize) {
138 if (wp == up || wp == vp) {
139 wp = mpi_alloc_limb_space(wsize);
140 if (!wp)
141 goto nomem;
142 assign_wp = 1;
143 } else {
144 if (mpi_resize(w, wsize) < 0)
145 goto nomem;
146 wp = w->d;
147 }
148 } else { /* Make U and V not overlap with W. */
149 if (wp == up) {
150 /* W and U are identical. Allocate temporary space for U. */
151 up = tmp_limb = mpi_alloc_limb_space(usize);
152 if (!up)
153 goto nomem;
154 /* Is V identical too? Keep it identical with U. */
155 if (wp == vp)
156 vp = up;
157 /* Copy to the temporary space. */
158 MPN_COPY(up, wp, usize);
159 } else if (wp == vp) {
160 /* W and V are identical. Allocate temporary space for V. */
161 vp = tmp_limb = mpi_alloc_limb_space(vsize);
162 if (!vp)
163 goto nomem;
164 /* Copy to the temporary space. */
165 MPN_COPY(vp, wp, vsize);
166 }
167 }
168
169 if (!vsize)
170 wsize = 0;
171 else {
172 if (mpihelp_mul(wp, up, usize, vp, vsize, &cy) < 0)
173 goto nomem;
174 wsize -= cy ? 0 : 1;
175 }
176
177 if (assign_wp)
178 mpi_assign_limb_space(w, wp, wsize);
179
180 w->nlimbs = wsize;
181 w->sign = sign_product;
182 rc = 0;
183nomem:
184 if (tmp_limb)
185 mpi_free_limb_space(tmp_limb);
186 return rc;
187}
188
189int mpi_mulm(MPI w, MPI u, MPI v, MPI m)
190{
191 if (mpi_mul(w, u, v) < 0)
192 return -ENOMEM;
193 return mpi_fdiv_r(w, w, m);
194}
diff --git a/lib/mpi/mpi-scan.c b/lib/mpi/mpi-scan.c
deleted file mode 100644
index b2da5ad96199..000000000000
--- a/lib/mpi/mpi-scan.c
+++ /dev/null
@@ -1,136 +0,0 @@
1/* mpi-scan.c - MPI functions
2 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
3 *
4 * This file is part of GnuPG.
5 *
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
19 */
20
21#include "mpi-internal.h"
22#include "longlong.h"
23
24/****************
25 * Scan through an mpi and return byte for byte. a -1 is returned to indicate
26 * the end of the mpi. Scanning is done from the lsb to the msb, returned
27 * values are in the range of 0 .. 255.
28 *
29 * FIXME: This code is VERY ugly!
30 */
31int mpi_getbyte(const MPI a, unsigned idx)
32{
33 int i, j;
34 unsigned n;
35 mpi_ptr_t ap;
36 mpi_limb_t limb;
37
38 ap = a->d;
39 for (n = 0, i = 0; i < a->nlimbs; i++) {
40 limb = ap[i];
41 for (j = 0; j < BYTES_PER_MPI_LIMB; j++, n++)
42 if (n == idx)
43 return (limb >> j * 8) & 0xff;
44 }
45 return -1;
46}
47
48/****************
49 * Put a value at position IDX into A. idx counts from lsb to msb
50 */
51void mpi_putbyte(MPI a, unsigned idx, int xc)
52{
53 int i, j;
54 unsigned n;
55 mpi_ptr_t ap;
56 mpi_limb_t limb, c;
57
58 c = xc & 0xff;
59 ap = a->d;
60 for (n = 0, i = 0; i < a->alloced; i++) {
61 limb = ap[i];
62 for (j = 0; j < BYTES_PER_MPI_LIMB; j++, n++)
63 if (n == idx) {
64#if BYTES_PER_MPI_LIMB == 4
65 if (j == 0)
66 limb = (limb & 0xffffff00) | c;
67 else if (j == 1)
68 limb = (limb & 0xffff00ff) | (c << 8);
69 else if (j == 2)
70 limb = (limb & 0xff00ffff) | (c << 16);
71 else
72 limb = (limb & 0x00ffffff) | (c << 24);
73#elif BYTES_PER_MPI_LIMB == 8
74 if (j == 0)
75 limb = (limb & 0xffffffffffffff00) | c;
76 else if (j == 1)
77 limb =
78 (limb & 0xffffffffffff00ff) | (c <<
79 8);
80 else if (j == 2)
81 limb =
82 (limb & 0xffffffffff00ffff) | (c <<
83 16);
84 else if (j == 3)
85 limb =
86 (limb & 0xffffffff00ffffff) | (c <<
87 24);
88 else if (j == 4)
89 limb =
90 (limb & 0xffffff00ffffffff) | (c <<
91 32);
92 else if (j == 5)
93 limb =
94 (limb & 0xffff00ffffffffff) | (c <<
95 40);
96 else if (j == 6)
97 limb =
98 (limb & 0xff00ffffffffffff) | (c <<
99 48);
100 else
101 limb =
102 (limb & 0x00ffffffffffffff) | (c <<
103 56);
104#else
105#error please enhance this function, its ugly - i know.
106#endif
107 if (a->nlimbs <= i)
108 a->nlimbs = i + 1;
109 ap[i] = limb;
110 return;
111 }
112 }
113 log_bug("index out of range\n");
114}
115
116/****************
117 * Count the number of zerobits at the low end of A
118 */
119unsigned mpi_trailing_zeros(const MPI a)
120{
121 unsigned n, count = 0;
122
123 for (n = 0; n < a->nlimbs; n++) {
124 if (a->d[n]) {
125 unsigned nn;
126 mpi_limb_t alimb = a->d[n];
127
128 count_trailing_zeros(nn, alimb);
129 count += nn;
130 break;
131 }
132 count += BITS_PER_MPI_LIMB;
133 }
134 return count;
135
136}
diff --git a/lib/mpi/mpicoder.c b/lib/mpi/mpicoder.c
index f26b41fcb48c..f0fa65995800 100644
--- a/lib/mpi/mpicoder.c
+++ b/lib/mpi/mpicoder.c
@@ -74,81 +74,6 @@ leave:
74EXPORT_SYMBOL_GPL(mpi_read_from_buffer); 74EXPORT_SYMBOL_GPL(mpi_read_from_buffer);
75 75
76/**************** 76/****************
77 * Make an mpi from a character string.
78 */
79int mpi_fromstr(MPI val, const char *str)
80{
81 int hexmode = 0, sign = 0, prepend_zero = 0, i, j, c, c1, c2;
82 unsigned nbits, nbytes, nlimbs;
83 mpi_limb_t a;
84
85 if (*str == '-') {
86 sign = 1;
87 str++;
88 }
89 if (*str == '0' && str[1] == 'x')
90 hexmode = 1;
91 else
92 return -EINVAL; /* other bases are not yet supported */
93 str += 2;
94
95 nbits = strlen(str) * 4;
96 if (nbits % 8)
97 prepend_zero = 1;
98 nbytes = (nbits + 7) / 8;
99 nlimbs = (nbytes + BYTES_PER_MPI_LIMB - 1) / BYTES_PER_MPI_LIMB;
100 if (val->alloced < nlimbs)
101 if (!mpi_resize(val, nlimbs))
102 return -ENOMEM;
103 i = BYTES_PER_MPI_LIMB - nbytes % BYTES_PER_MPI_LIMB;
104 i %= BYTES_PER_MPI_LIMB;
105 j = val->nlimbs = nlimbs;
106 val->sign = sign;
107 for (; j > 0; j--) {
108 a = 0;
109 for (; i < BYTES_PER_MPI_LIMB; i++) {
110 if (prepend_zero) {
111 c1 = '0';
112 prepend_zero = 0;
113 } else
114 c1 = *str++;
115 assert(c1);
116 c2 = *str++;
117 assert(c2);
118 if (c1 >= '0' && c1 <= '9')
119 c = c1 - '0';
120 else if (c1 >= 'a' && c1 <= 'f')
121 c = c1 - 'a' + 10;
122 else if (c1 >= 'A' && c1 <= 'F')
123 c = c1 - 'A' + 10;
124 else {
125 mpi_clear(val);
126 return 1;
127 }
128 c <<= 4;
129 if (c2 >= '0' && c2 <= '9')
130 c |= c2 - '0';
131 else if (c2 >= 'a' && c2 <= 'f')
132 c |= c2 - 'a' + 10;
133 else if (c2 >= 'A' && c2 <= 'F')
134 c |= c2 - 'A' + 10;
135 else {
136 mpi_clear(val);
137 return 1;
138 }
139 a <<= 8;
140 a |= c;
141 }
142 i = 0;
143
144 val->d[j - 1] = a;
145 }
146
147 return 0;
148}
149EXPORT_SYMBOL_GPL(mpi_fromstr);
150
151/****************
152 * Return an allocated buffer with the MPI (msb first). 77 * Return an allocated buffer with the MPI (msb first).
153 * NBYTES receives the length of this buffer. Caller must free the 78 * NBYTES receives the length of this buffer. Caller must free the
154 * return string (This function does return a 0 byte buffer with NBYTES 79 * return string (This function does return a 0 byte buffer with NBYTES
diff --git a/lib/mpi/mpih-div.c b/lib/mpi/mpih-div.c
index cde1aaec18da..c57d1d46295e 100644
--- a/lib/mpi/mpih-div.c
+++ b/lib/mpi/mpih-div.c
@@ -37,159 +37,6 @@
37#define UDIV_TIME UMUL_TIME 37#define UDIV_TIME UMUL_TIME
38#endif 38#endif
39 39
40/* FIXME: We should be using invert_limb (or invert_normalized_limb)
41 * here (not udiv_qrnnd).
42 */
43
44mpi_limb_t
45mpihelp_mod_1(mpi_ptr_t dividend_ptr, mpi_size_t dividend_size,
46 mpi_limb_t divisor_limb)
47{
48 mpi_size_t i;
49 mpi_limb_t n1, n0, r;
50 int dummy;
51
52 /* Botch: Should this be handled at all? Rely on callers? */
53 if (!dividend_size)
54 return 0;
55
56 /* If multiplication is much faster than division, and the
57 * dividend is large, pre-invert the divisor, and use
58 * only multiplications in the inner loop.
59 *
60 * This test should be read:
61 * Does it ever help to use udiv_qrnnd_preinv?
62 * && Does what we save compensate for the inversion overhead?
63 */
64 if (UDIV_TIME > (2 * UMUL_TIME + 6)
65 && (UDIV_TIME - (2 * UMUL_TIME + 6)) * dividend_size > UDIV_TIME) {
66 int normalization_steps;
67
68 count_leading_zeros(normalization_steps, divisor_limb);
69 if (normalization_steps) {
70 mpi_limb_t divisor_limb_inverted;
71
72 divisor_limb <<= normalization_steps;
73
74 /* Compute (2**2N - 2**N * DIVISOR_LIMB) / DIVISOR_LIMB. The
75 * result is a (N+1)-bit approximation to 1/DIVISOR_LIMB, with the
76 * most significant bit (with weight 2**N) implicit.
77 *
78 * Special case for DIVISOR_LIMB == 100...000.
79 */
80 if (!(divisor_limb << 1))
81 divisor_limb_inverted = ~(mpi_limb_t) 0;
82 else
83 udiv_qrnnd(divisor_limb_inverted, dummy,
84 -divisor_limb, 0, divisor_limb);
85
86 n1 = dividend_ptr[dividend_size - 1];
87 r = n1 >> (BITS_PER_MPI_LIMB - normalization_steps);
88
89 /* Possible optimization:
90 * if (r == 0
91 * && divisor_limb > ((n1 << normalization_steps)
92 * | (dividend_ptr[dividend_size - 2] >> ...)))
93 * ...one division less...
94 */
95 for (i = dividend_size - 2; i >= 0; i--) {
96 n0 = dividend_ptr[i];
97 UDIV_QRNND_PREINV(dummy, r, r,
98 ((n1 << normalization_steps)
99 | (n0 >>
100 (BITS_PER_MPI_LIMB -
101 normalization_steps))),
102 divisor_limb,
103 divisor_limb_inverted);
104 n1 = n0;
105 }
106 UDIV_QRNND_PREINV(dummy, r, r,
107 n1 << normalization_steps,
108 divisor_limb, divisor_limb_inverted);
109 return r >> normalization_steps;
110 } else {
111 mpi_limb_t divisor_limb_inverted;
112
113 /* Compute (2**2N - 2**N * DIVISOR_LIMB) / DIVISOR_LIMB. The
114 * result is a (N+1)-bit approximation to 1/DIVISOR_LIMB, with the
115 * most significant bit (with weight 2**N) implicit.
116 *
117 * Special case for DIVISOR_LIMB == 100...000.
118 */
119 if (!(divisor_limb << 1))
120 divisor_limb_inverted = ~(mpi_limb_t) 0;
121 else
122 udiv_qrnnd(divisor_limb_inverted, dummy,
123 -divisor_limb, 0, divisor_limb);
124
125 i = dividend_size - 1;
126 r = dividend_ptr[i];
127
128 if (r >= divisor_limb)
129 r = 0;
130 else
131 i--;
132
133 for (; i >= 0; i--) {
134 n0 = dividend_ptr[i];
135 UDIV_QRNND_PREINV(dummy, r, r,
136 n0, divisor_limb,
137 divisor_limb_inverted);
138 }
139 return r;
140 }
141 } else {
142 if (UDIV_NEEDS_NORMALIZATION) {
143 int normalization_steps;
144
145 count_leading_zeros(normalization_steps, divisor_limb);
146 if (normalization_steps) {
147 divisor_limb <<= normalization_steps;
148
149 n1 = dividend_ptr[dividend_size - 1];
150 r = n1 >> (BITS_PER_MPI_LIMB -
151 normalization_steps);
152
153 /* Possible optimization:
154 * if (r == 0
155 * && divisor_limb > ((n1 << normalization_steps)
156 * | (dividend_ptr[dividend_size - 2] >> ...)))
157 * ...one division less...
158 */
159 for (i = dividend_size - 2; i >= 0; i--) {
160 n0 = dividend_ptr[i];
161 udiv_qrnnd(dummy, r, r,
162 ((n1 << normalization_steps)
163 | (n0 >>
164 (BITS_PER_MPI_LIMB -
165 normalization_steps))),
166 divisor_limb);
167 n1 = n0;
168 }
169 udiv_qrnnd(dummy, r, r,
170 n1 << normalization_steps,
171 divisor_limb);
172 return r >> normalization_steps;
173 }
174 }
175 /* No normalization needed, either because udiv_qrnnd doesn't require
176 * it, or because DIVISOR_LIMB is already normalized. */
177 i = dividend_size - 1;
178 r = dividend_ptr[i];
179
180 if (r >= divisor_limb)
181 r = 0;
182 else
183 i--;
184
185 for (; i >= 0; i--) {
186 n0 = dividend_ptr[i];
187 udiv_qrnnd(dummy, r, r, n0, divisor_limb);
188 }
189 return r;
190 }
191}
192
193/* Divide num (NP/NSIZE) by den (DP/DSIZE) and write 40/* Divide num (NP/NSIZE) by den (DP/DSIZE) and write
194 * the NSIZE-DSIZE least significant quotient limbs at QP 41 * the NSIZE-DSIZE least significant quotient limbs at QP
195 * and the DSIZE long remainder at NP. If QEXTRA_LIMBS is 42 * and the DSIZE long remainder at NP. If QEXTRA_LIMBS is
@@ -387,159 +234,3 @@ q_test:
387 234
388 return most_significant_q_limb; 235 return most_significant_q_limb;
389} 236}
390
391/****************
392 * Divide (DIVIDEND_PTR,,DIVIDEND_SIZE) by DIVISOR_LIMB.
393 * Write DIVIDEND_SIZE limbs of quotient at QUOT_PTR.
394 * Return the single-limb remainder.
395 * There are no constraints on the value of the divisor.
396 *
397 * QUOT_PTR and DIVIDEND_PTR might point to the same limb.
398 */
399
400mpi_limb_t
401mpihelp_divmod_1(mpi_ptr_t quot_ptr,
402 mpi_ptr_t dividend_ptr, mpi_size_t dividend_size,
403 mpi_limb_t divisor_limb)
404{
405 mpi_size_t i;
406 mpi_limb_t n1, n0, r;
407 int dummy;
408
409 if (!dividend_size)
410 return 0;
411
412 /* If multiplication is much faster than division, and the
413 * dividend is large, pre-invert the divisor, and use
414 * only multiplications in the inner loop.
415 *
416 * This test should be read:
417 * Does it ever help to use udiv_qrnnd_preinv?
418 * && Does what we save compensate for the inversion overhead?
419 */
420 if (UDIV_TIME > (2 * UMUL_TIME + 6)
421 && (UDIV_TIME - (2 * UMUL_TIME + 6)) * dividend_size > UDIV_TIME) {
422 int normalization_steps;
423
424 count_leading_zeros(normalization_steps, divisor_limb);
425 if (normalization_steps) {
426 mpi_limb_t divisor_limb_inverted;
427
428 divisor_limb <<= normalization_steps;
429
430 /* Compute (2**2N - 2**N * DIVISOR_LIMB) / DIVISOR_LIMB. The
431 * result is a (N+1)-bit approximation to 1/DIVISOR_LIMB, with the
432 * most significant bit (with weight 2**N) implicit.
433 */
434 /* Special case for DIVISOR_LIMB == 100...000. */
435 if (!(divisor_limb << 1))
436 divisor_limb_inverted = ~(mpi_limb_t) 0;
437 else
438 udiv_qrnnd(divisor_limb_inverted, dummy,
439 -divisor_limb, 0, divisor_limb);
440
441 n1 = dividend_ptr[dividend_size - 1];
442 r = n1 >> (BITS_PER_MPI_LIMB - normalization_steps);
443
444 /* Possible optimization:
445 * if (r == 0
446 * && divisor_limb > ((n1 << normalization_steps)
447 * | (dividend_ptr[dividend_size - 2] >> ...)))
448 * ...one division less...
449 */
450 for (i = dividend_size - 2; i >= 0; i--) {
451 n0 = dividend_ptr[i];
452 UDIV_QRNND_PREINV(quot_ptr[i + 1], r, r,
453 ((n1 << normalization_steps)
454 | (n0 >>
455 (BITS_PER_MPI_LIMB -
456 normalization_steps))),
457 divisor_limb,
458 divisor_limb_inverted);
459 n1 = n0;
460 }
461 UDIV_QRNND_PREINV(quot_ptr[0], r, r,
462 n1 << normalization_steps,
463 divisor_limb, divisor_limb_inverted);
464 return r >> normalization_steps;
465 } else {
466 mpi_limb_t divisor_limb_inverted;
467
468 /* Compute (2**2N - 2**N * DIVISOR_LIMB) / DIVISOR_LIMB. The
469 * result is a (N+1)-bit approximation to 1/DIVISOR_LIMB, with the
470 * most significant bit (with weight 2**N) implicit.
471 */
472 /* Special case for DIVISOR_LIMB == 100...000. */
473 if (!(divisor_limb << 1))
474 divisor_limb_inverted = ~(mpi_limb_t) 0;
475 else
476 udiv_qrnnd(divisor_limb_inverted, dummy,
477 -divisor_limb, 0, divisor_limb);
478
479 i = dividend_size - 1;
480 r = dividend_ptr[i];
481
482 if (r >= divisor_limb)
483 r = 0;
484 else
485 quot_ptr[i--] = 0;
486
487 for (; i >= 0; i--) {
488 n0 = dividend_ptr[i];
489 UDIV_QRNND_PREINV(quot_ptr[i], r, r,
490 n0, divisor_limb,
491 divisor_limb_inverted);
492 }
493 return r;
494 }
495 } else {
496 if (UDIV_NEEDS_NORMALIZATION) {
497 int normalization_steps;
498
499 count_leading_zeros(normalization_steps, divisor_limb);
500 if (normalization_steps) {
501 divisor_limb <<= normalization_steps;
502
503 n1 = dividend_ptr[dividend_size - 1];
504 r = n1 >> (BITS_PER_MPI_LIMB -
505 normalization_steps);
506
507 /* Possible optimization:
508 * if (r == 0
509 * && divisor_limb > ((n1 << normalization_steps)
510 * | (dividend_ptr[dividend_size - 2] >> ...)))
511 * ...one division less...
512 */
513 for (i = dividend_size - 2; i >= 0; i--) {
514 n0 = dividend_ptr[i];
515 udiv_qrnnd(quot_ptr[i + 1], r, r,
516 ((n1 << normalization_steps)
517 | (n0 >>
518 (BITS_PER_MPI_LIMB -
519 normalization_steps))),
520 divisor_limb);
521 n1 = n0;
522 }
523 udiv_qrnnd(quot_ptr[0], r, r,
524 n1 << normalization_steps,
525 divisor_limb);
526 return r >> normalization_steps;
527 }
528 }
529 /* No normalization needed, either because udiv_qrnnd doesn't require
530 * it, or because DIVISOR_LIMB is already normalized. */
531 i = dividend_size - 1;
532 r = dividend_ptr[i];
533
534 if (r >= divisor_limb)
535 r = 0;
536 else
537 quot_ptr[i--] = 0;
538
539 for (; i >= 0; i--) {
540 n0 = dividend_ptr[i];
541 udiv_qrnnd(quot_ptr[i], r, r, n0, divisor_limb);
542 }
543 return r;
544 }
545}
diff --git a/lib/mpi/mpih-mul.c b/lib/mpi/mpih-mul.c
index c69c5eef233b..7c841719fdfb 100644
--- a/lib/mpi/mpih-mul.c
+++ b/lib/mpi/mpih-mul.c
@@ -330,36 +330,6 @@ mpih_sqr_n(mpi_ptr_t prodp, mpi_ptr_t up, mpi_size_t size, mpi_ptr_t tspace)
330 } 330 }
331} 331}
332 332
333/* This should be made into an inline function in gmp.h. */
334int mpihelp_mul_n(mpi_ptr_t prodp, mpi_ptr_t up, mpi_ptr_t vp, mpi_size_t size)
335{
336 if (up == vp) {
337 if (size < KARATSUBA_THRESHOLD)
338 mpih_sqr_n_basecase(prodp, up, size);
339 else {
340 mpi_ptr_t tspace;
341 tspace = mpi_alloc_limb_space(2 * size);
342 if (!tspace)
343 return -ENOMEM;
344 mpih_sqr_n(prodp, up, size, tspace);
345 mpi_free_limb_space(tspace);
346 }
347 } else {
348 if (size < KARATSUBA_THRESHOLD)
349 mul_n_basecase(prodp, up, vp, size);
350 else {
351 mpi_ptr_t tspace;
352 tspace = mpi_alloc_limb_space(2 * size);
353 if (!tspace)
354 return -ENOMEM;
355 mul_n(prodp, up, vp, size, tspace);
356 mpi_free_limb_space(tspace);
357 }
358 }
359
360 return 0;
361}
362
363int 333int
364mpihelp_mul_karatsuba_case(mpi_ptr_t prodp, 334mpihelp_mul_karatsuba_case(mpi_ptr_t prodp,
365 mpi_ptr_t up, mpi_size_t usize, 335 mpi_ptr_t up, mpi_size_t usize,
diff --git a/lib/mpi/mpiutil.c b/lib/mpi/mpiutil.c
index 26e4ed31e256..657979f71bef 100644
--- a/lib/mpi/mpiutil.c
+++ b/lib/mpi/mpiutil.c
@@ -106,13 +106,6 @@ int mpi_resize(MPI a, unsigned nlimbs)
106 return 0; 106 return 0;
107} 107}
108 108
109void mpi_clear(MPI a)
110{
111 a->nlimbs = 0;
112 a->nbits = 0;
113 a->flags = 0;
114}
115
116void mpi_free(MPI a) 109void mpi_free(MPI a)
117{ 110{
118 if (!a) 111 if (!a)
@@ -128,84 +121,3 @@ void mpi_free(MPI a)
128 kfree(a); 121 kfree(a);
129} 122}
130EXPORT_SYMBOL_GPL(mpi_free); 123EXPORT_SYMBOL_GPL(mpi_free);
131
132/****************
133 * Note: This copy function should not interpret the MPI
134 * but copy it transparently.
135 */
136int mpi_copy(MPI *copied, const MPI a)
137{
138 size_t i;
139 MPI b;
140
141 *copied = NULL;
142
143 if (a) {
144 b = mpi_alloc(a->nlimbs);
145 if (!b)
146 return -ENOMEM;
147
148 b->nlimbs = a->nlimbs;
149 b->sign = a->sign;
150 b->flags = a->flags;
151 b->nbits = a->nbits;
152
153 for (i = 0; i < b->nlimbs; i++)
154 b->d[i] = a->d[i];
155
156 *copied = b;
157 }
158
159 return 0;
160}
161
162int mpi_set(MPI w, const MPI u)
163{
164 mpi_ptr_t wp, up;
165 mpi_size_t usize = u->nlimbs;
166 int usign = u->sign;
167
168 if (RESIZE_IF_NEEDED(w, (size_t) usize) < 0)
169 return -ENOMEM;
170
171 wp = w->d;
172 up = u->d;
173 MPN_COPY(wp, up, usize);
174 w->nlimbs = usize;
175 w->nbits = u->nbits;
176 w->flags = u->flags;
177 w->sign = usign;
178 return 0;
179}
180
181int mpi_set_ui(MPI w, unsigned long u)
182{
183 if (RESIZE_IF_NEEDED(w, 1) < 0)
184 return -ENOMEM;
185 w->d[0] = u;
186 w->nlimbs = u ? 1 : 0;
187 w->sign = 0;
188 w->nbits = 0;
189 w->flags = 0;
190 return 0;
191}
192
193MPI mpi_alloc_set_ui(unsigned long u)
194{
195 MPI w = mpi_alloc(1);
196 if (!w)
197 return w;
198 w->d[0] = u;
199 w->nlimbs = u ? 1 : 0;
200 w->sign = 0;
201 return w;
202}
203
204void mpi_swap(MPI a, MPI b)
205{
206 struct gcry_mpi tmp;
207
208 tmp = *a;
209 *a = *b;
210 *b = tmp;
211}
diff --git a/lib/notifier-error-inject.c b/lib/notifier-error-inject.c
new file mode 100644
index 000000000000..44b92cb6224f
--- /dev/null
+++ b/lib/notifier-error-inject.c
@@ -0,0 +1,112 @@
1#include <linux/module.h>
2
3#include "notifier-error-inject.h"
4
5static int debugfs_errno_set(void *data, u64 val)
6{
7 *(int *)data = clamp_t(int, val, -MAX_ERRNO, 0);
8 return 0;
9}
10
11static int debugfs_errno_get(void *data, u64 *val)
12{
13 *val = *(int *)data;
14 return 0;
15}
16
17DEFINE_SIMPLE_ATTRIBUTE(fops_errno, debugfs_errno_get, debugfs_errno_set,
18 "%lld\n");
19
20static struct dentry *debugfs_create_errno(const char *name, mode_t mode,
21 struct dentry *parent, int *value)
22{
23 return debugfs_create_file(name, mode, parent, value, &fops_errno);
24}
25
26static int notifier_err_inject_callback(struct notifier_block *nb,
27 unsigned long val, void *p)
28{
29 int err = 0;
30 struct notifier_err_inject *err_inject =
31 container_of(nb, struct notifier_err_inject, nb);
32 struct notifier_err_inject_action *action;
33
34 for (action = err_inject->actions; action->name; action++) {
35 if (action->val == val) {
36 err = action->error;
37 break;
38 }
39 }
40 if (err)
41 pr_info("Injecting error (%d) to %s\n", err, action->name);
42
43 return notifier_from_errno(err);
44}
45
46struct dentry *notifier_err_inject_dir;
47EXPORT_SYMBOL_GPL(notifier_err_inject_dir);
48
49struct dentry *notifier_err_inject_init(const char *name, struct dentry *parent,
50 struct notifier_err_inject *err_inject, int priority)
51{
52 struct notifier_err_inject_action *action;
53 mode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
54 struct dentry *dir;
55 struct dentry *actions_dir;
56
57 err_inject->nb.notifier_call = notifier_err_inject_callback;
58 err_inject->nb.priority = priority;
59
60 dir = debugfs_create_dir(name, parent);
61 if (!dir)
62 return ERR_PTR(-ENOMEM);
63
64 actions_dir = debugfs_create_dir("actions", dir);
65 if (!actions_dir)
66 goto fail;
67
68 for (action = err_inject->actions; action->name; action++) {
69 struct dentry *action_dir;
70
71 action_dir = debugfs_create_dir(action->name, actions_dir);
72 if (!action_dir)
73 goto fail;
74
75 /*
76 * Create debugfs r/w file containing action->error. If
77 * notifier call chain is called with action->val, it will
78 * fail with the error code
79 */
80 if (!debugfs_create_errno("error", mode, action_dir,
81 &action->error))
82 goto fail;
83 }
84 return dir;
85fail:
86 debugfs_remove_recursive(dir);
87 return ERR_PTR(-ENOMEM);
88}
89EXPORT_SYMBOL_GPL(notifier_err_inject_init);
90
91static int __init err_inject_init(void)
92{
93 notifier_err_inject_dir =
94 debugfs_create_dir("notifier-error-inject", NULL);
95
96 if (!notifier_err_inject_dir)
97 return -ENOMEM;
98
99 return 0;
100}
101
102static void __exit err_inject_exit(void)
103{
104 debugfs_remove_recursive(notifier_err_inject_dir);
105}
106
107module_init(err_inject_init);
108module_exit(err_inject_exit);
109
110MODULE_DESCRIPTION("Notifier error injection module");
111MODULE_LICENSE("GPL");
112MODULE_AUTHOR("Akinobu Mita <akinobu.mita@gmail.com>");
diff --git a/lib/notifier-error-inject.h b/lib/notifier-error-inject.h
new file mode 100644
index 000000000000..99b3b6fc470b
--- /dev/null
+++ b/lib/notifier-error-inject.h
@@ -0,0 +1,24 @@
1#include <linux/atomic.h>
2#include <linux/debugfs.h>
3#include <linux/notifier.h>
4
5struct notifier_err_inject_action {
6 unsigned long val;
7 int error;
8 const char *name;
9};
10
11#define NOTIFIER_ERR_INJECT_ACTION(action) \
12 .name = #action, .val = (action),
13
14struct notifier_err_inject {
15 struct notifier_block nb;
16 struct notifier_err_inject_action actions[];
17 /* The last slot must be terminated with zero sentinel */
18};
19
20extern struct dentry *notifier_err_inject_dir;
21
22extern struct dentry *notifier_err_inject_init(const char *name,
23 struct dentry *parent, struct notifier_err_inject *err_inject,
24 int priority);
diff --git a/lib/pSeries-reconfig-notifier-error-inject.c b/lib/pSeries-reconfig-notifier-error-inject.c
new file mode 100644
index 000000000000..7f7c98dcd5c4
--- /dev/null
+++ b/lib/pSeries-reconfig-notifier-error-inject.c
@@ -0,0 +1,51 @@
1#include <linux/kernel.h>
2#include <linux/module.h>
3
4#include <asm/pSeries_reconfig.h>
5
6#include "notifier-error-inject.h"
7
8static int priority;
9module_param(priority, int, 0);
10MODULE_PARM_DESC(priority, "specify pSeries reconfig notifier priority");
11
12static struct notifier_err_inject reconfig_err_inject = {
13 .actions = {
14 { NOTIFIER_ERR_INJECT_ACTION(PSERIES_RECONFIG_ADD) },
15 { NOTIFIER_ERR_INJECT_ACTION(PSERIES_RECONFIG_REMOVE) },
16 { NOTIFIER_ERR_INJECT_ACTION(PSERIES_DRCONF_MEM_ADD) },
17 { NOTIFIER_ERR_INJECT_ACTION(PSERIES_DRCONF_MEM_REMOVE) },
18 {}
19 }
20};
21
22static struct dentry *dir;
23
24static int err_inject_init(void)
25{
26 int err;
27
28 dir = notifier_err_inject_init("pSeries-reconfig",
29 notifier_err_inject_dir, &reconfig_err_inject, priority);
30 if (IS_ERR(dir))
31 return PTR_ERR(dir);
32
33 err = pSeries_reconfig_notifier_register(&reconfig_err_inject.nb);
34 if (err)
35 debugfs_remove_recursive(dir);
36
37 return err;
38}
39
40static void err_inject_exit(void)
41{
42 pSeries_reconfig_notifier_unregister(&reconfig_err_inject.nb);
43 debugfs_remove_recursive(dir);
44}
45
46module_init(err_inject_init);
47module_exit(err_inject_exit);
48
49MODULE_DESCRIPTION("pSeries reconfig notifier error injection module");
50MODULE_LICENSE("GPL");
51MODULE_AUTHOR("Akinobu Mita <akinobu.mita@gmail.com>");
diff --git a/lib/pm-notifier-error-inject.c b/lib/pm-notifier-error-inject.c
new file mode 100644
index 000000000000..c094b2dedc23
--- /dev/null
+++ b/lib/pm-notifier-error-inject.c
@@ -0,0 +1,49 @@
1#include <linux/kernel.h>
2#include <linux/module.h>
3#include <linux/suspend.h>
4
5#include "notifier-error-inject.h"
6
7static int priority;
8module_param(priority, int, 0);
9MODULE_PARM_DESC(priority, "specify PM notifier priority");
10
11static struct notifier_err_inject pm_notifier_err_inject = {
12 .actions = {
13 { NOTIFIER_ERR_INJECT_ACTION(PM_HIBERNATION_PREPARE) },
14 { NOTIFIER_ERR_INJECT_ACTION(PM_SUSPEND_PREPARE) },
15 { NOTIFIER_ERR_INJECT_ACTION(PM_RESTORE_PREPARE) },
16 {}
17 }
18};
19
20static struct dentry *dir;
21
22static int err_inject_init(void)
23{
24 int err;
25
26 dir = notifier_err_inject_init("pm", notifier_err_inject_dir,
27 &pm_notifier_err_inject, priority);
28 if (IS_ERR(dir))
29 return PTR_ERR(dir);
30
31 err = register_pm_notifier(&pm_notifier_err_inject.nb);
32 if (err)
33 debugfs_remove_recursive(dir);
34
35 return err;
36}
37
38static void err_inject_exit(void)
39{
40 unregister_pm_notifier(&pm_notifier_err_inject.nb);
41 debugfs_remove_recursive(dir);
42}
43
44module_init(err_inject_init);
45module_exit(err_inject_exit);
46
47MODULE_DESCRIPTION("PM notifier error injection module");
48MODULE_LICENSE("GPL");
49MODULE_AUTHOR("Akinobu Mita <akinobu.mita@gmail.com>");
diff --git a/lib/radix-tree.c b/lib/radix-tree.c
index 86516f5588e3..e7964296fd50 100644
--- a/lib/radix-tree.c
+++ b/lib/radix-tree.c
@@ -73,11 +73,24 @@ static unsigned long height_to_maxindex[RADIX_TREE_MAX_PATH + 1] __read_mostly;
73static struct kmem_cache *radix_tree_node_cachep; 73static struct kmem_cache *radix_tree_node_cachep;
74 74
75/* 75/*
76 * The radix tree is variable-height, so an insert operation not only has
77 * to build the branch to its corresponding item, it also has to build the
78 * branch to existing items if the size has to be increased (by
79 * radix_tree_extend).
80 *
81 * The worst case is a zero height tree with just a single item at index 0,
82 * and then inserting an item at index ULONG_MAX. This requires 2 new branches
83 * of RADIX_TREE_MAX_PATH size to be created, with only the root node shared.
84 * Hence:
85 */
86#define RADIX_TREE_PRELOAD_SIZE (RADIX_TREE_MAX_PATH * 2 - 1)
87
88/*
76 * Per-cpu pool of preloaded nodes 89 * Per-cpu pool of preloaded nodes
77 */ 90 */
78struct radix_tree_preload { 91struct radix_tree_preload {
79 int nr; 92 int nr;
80 struct radix_tree_node *nodes[RADIX_TREE_MAX_PATH]; 93 struct radix_tree_node *nodes[RADIX_TREE_PRELOAD_SIZE];
81}; 94};
82static DEFINE_PER_CPU(struct radix_tree_preload, radix_tree_preloads) = { 0, }; 95static DEFINE_PER_CPU(struct radix_tree_preload, radix_tree_preloads) = { 0, };
83 96
@@ -673,6 +686,9 @@ void **radix_tree_next_chunk(struct radix_tree_root *root,
673 * during iterating; it can be zero only at the beginning. 686 * during iterating; it can be zero only at the beginning.
674 * And we cannot overflow iter->next_index in a single step, 687 * And we cannot overflow iter->next_index in a single step,
675 * because RADIX_TREE_MAP_SHIFT < BITS_PER_LONG. 688 * because RADIX_TREE_MAP_SHIFT < BITS_PER_LONG.
689 *
690 * This condition also used by radix_tree_next_slot() to stop
691 * contiguous iterating, and forbid swithing to the next chunk.
676 */ 692 */
677 index = iter->next_index; 693 index = iter->next_index;
678 if (!index && iter->index) 694 if (!index && iter->index)
diff --git a/lib/raid6/Makefile b/lib/raid6/Makefile
index 8a38102770f3..de06dfe165b8 100644
--- a/lib/raid6/Makefile
+++ b/lib/raid6/Makefile
@@ -1,6 +1,6 @@
1obj-$(CONFIG_RAID6_PQ) += raid6_pq.o 1obj-$(CONFIG_RAID6_PQ) += raid6_pq.o
2 2
3raid6_pq-y += algos.o recov.o tables.o int1.o int2.o int4.o \ 3raid6_pq-y += algos.o recov.o recov_ssse3.o tables.o int1.o int2.o int4.o \
4 int8.o int16.o int32.o altivec1.o altivec2.o altivec4.o \ 4 int8.o int16.o int32.o altivec1.o altivec2.o altivec4.o \
5 altivec8.o mmx.o sse1.o sse2.o 5 altivec8.o mmx.o sse1.o sse2.o
6hostprogs-y += mktables 6hostprogs-y += mktables
diff --git a/lib/raid6/algos.c b/lib/raid6/algos.c
index 8b02f60ffc86..589f5f50ad2e 100644
--- a/lib/raid6/algos.c
+++ b/lib/raid6/algos.c
@@ -17,11 +17,11 @@
17 */ 17 */
18 18
19#include <linux/raid/pq.h> 19#include <linux/raid/pq.h>
20#include <linux/module.h>
21#ifndef __KERNEL__ 20#ifndef __KERNEL__
22#include <sys/mman.h> 21#include <sys/mman.h>
23#include <stdio.h> 22#include <stdio.h>
24#else 23#else
24#include <linux/module.h>
25#include <linux/gfp.h> 25#include <linux/gfp.h>
26#if !RAID6_USE_EMPTY_ZERO_PAGE 26#if !RAID6_USE_EMPTY_ZERO_PAGE
27/* In .bss so it's zeroed */ 27/* In .bss so it's zeroed */
@@ -34,10 +34,6 @@ struct raid6_calls raid6_call;
34EXPORT_SYMBOL_GPL(raid6_call); 34EXPORT_SYMBOL_GPL(raid6_call);
35 35
36const struct raid6_calls * const raid6_algos[] = { 36const struct raid6_calls * const raid6_algos[] = {
37 &raid6_intx1,
38 &raid6_intx2,
39 &raid6_intx4,
40 &raid6_intx8,
41#if defined(__ia64__) 37#if defined(__ia64__)
42 &raid6_intx16, 38 &raid6_intx16,
43 &raid6_intx32, 39 &raid6_intx32,
@@ -61,6 +57,24 @@ const struct raid6_calls * const raid6_algos[] = {
61 &raid6_altivec4, 57 &raid6_altivec4,
62 &raid6_altivec8, 58 &raid6_altivec8,
63#endif 59#endif
60 &raid6_intx1,
61 &raid6_intx2,
62 &raid6_intx4,
63 &raid6_intx8,
64 NULL
65};
66
67void (*raid6_2data_recov)(int, size_t, int, int, void **);
68EXPORT_SYMBOL_GPL(raid6_2data_recov);
69
70void (*raid6_datap_recov)(int, size_t, int, void **);
71EXPORT_SYMBOL_GPL(raid6_datap_recov);
72
73const struct raid6_recov_calls *const raid6_recov_algos[] = {
74#if (defined(__i386__) || defined(__x86_64__)) && !defined(__arch_um__)
75 &raid6_recov_ssse3,
76#endif
77 &raid6_recov_intx1,
64 NULL 78 NULL
65}; 79};
66 80
@@ -72,59 +86,55 @@ const struct raid6_calls * const raid6_algos[] = {
72#define time_before(x, y) ((x) < (y)) 86#define time_before(x, y) ((x) < (y))
73#endif 87#endif
74 88
75/* Try to pick the best algorithm */ 89static inline const struct raid6_recov_calls *raid6_choose_recov(void)
76/* This code uses the gfmul table as convenient data set to abuse */
77
78int __init raid6_select_algo(void)
79{ 90{
80 const struct raid6_calls * const * algo; 91 const struct raid6_recov_calls *const *algo;
81 const struct raid6_calls * best; 92 const struct raid6_recov_calls *best;
82 char *syndromes;
83 void *dptrs[(65536/PAGE_SIZE)+2];
84 int i, disks;
85 unsigned long perf, bestperf;
86 int bestprefer;
87 unsigned long j0, j1;
88 93
89 disks = (65536/PAGE_SIZE)+2; 94 for (best = NULL, algo = raid6_recov_algos; *algo; algo++)
90 for ( i = 0 ; i < disks-2 ; i++ ) { 95 if (!best || (*algo)->priority > best->priority)
91 dptrs[i] = ((char *)raid6_gfmul) + PAGE_SIZE*i; 96 if (!(*algo)->valid || (*algo)->valid())
92 } 97 best = *algo;
93 98
94 /* Normal code - use a 2-page allocation to avoid D$ conflict */ 99 if (best) {
95 syndromes = (void *) __get_free_pages(GFP_KERNEL, 1); 100 raid6_2data_recov = best->data2;
101 raid6_datap_recov = best->datap;
96 102
97 if ( !syndromes ) { 103 printk("raid6: using %s recovery algorithm\n", best->name);
98 printk("raid6: Yikes! No memory available.\n"); 104 } else
99 return -ENOMEM; 105 printk("raid6: Yikes! No recovery algorithm found!\n");
100 }
101 106
102 dptrs[disks-2] = syndromes; 107 return best;
103 dptrs[disks-1] = syndromes + PAGE_SIZE; 108}
109
110static inline const struct raid6_calls *raid6_choose_gen(
111 void *(*const dptrs)[(65536/PAGE_SIZE)+2], const int disks)
112{
113 unsigned long perf, bestperf, j0, j1;
114 const struct raid6_calls *const *algo;
115 const struct raid6_calls *best;
104 116
105 bestperf = 0; bestprefer = 0; best = NULL; 117 for (bestperf = 0, best = NULL, algo = raid6_algos; *algo; algo++) {
118 if (!best || (*algo)->prefer >= best->prefer) {
119 if ((*algo)->valid && !(*algo)->valid())
120 continue;
106 121
107 for ( algo = raid6_algos ; *algo ; algo++ ) {
108 if ( !(*algo)->valid || (*algo)->valid() ) {
109 perf = 0; 122 perf = 0;
110 123
111 preempt_disable(); 124 preempt_disable();
112 j0 = jiffies; 125 j0 = jiffies;
113 while ( (j1 = jiffies) == j0 ) 126 while ((j1 = jiffies) == j0)
114 cpu_relax(); 127 cpu_relax();
115 while (time_before(jiffies, 128 while (time_before(jiffies,
116 j1 + (1<<RAID6_TIME_JIFFIES_LG2))) { 129 j1 + (1<<RAID6_TIME_JIFFIES_LG2))) {
117 (*algo)->gen_syndrome(disks, PAGE_SIZE, dptrs); 130 (*algo)->gen_syndrome(disks, PAGE_SIZE, *dptrs);
118 perf++; 131 perf++;
119 } 132 }
120 preempt_enable(); 133 preempt_enable();
121 134
122 if ( (*algo)->prefer > bestprefer || 135 if (perf > bestperf) {
123 ((*algo)->prefer == bestprefer &&
124 perf > bestperf) ) {
125 best = *algo;
126 bestprefer = best->prefer;
127 bestperf = perf; 136 bestperf = perf;
137 best = *algo;
128 } 138 }
129 printk("raid6: %-8s %5ld MB/s\n", (*algo)->name, 139 printk("raid6: %-8s %5ld MB/s\n", (*algo)->name,
130 (perf*HZ) >> (20-16+RAID6_TIME_JIFFIES_LG2)); 140 (perf*HZ) >> (20-16+RAID6_TIME_JIFFIES_LG2));
@@ -139,9 +149,46 @@ int __init raid6_select_algo(void)
139 } else 149 } else
140 printk("raid6: Yikes! No algorithm found!\n"); 150 printk("raid6: Yikes! No algorithm found!\n");
141 151
152 return best;
153}
154
155
156/* Try to pick the best algorithm */
157/* This code uses the gfmul table as convenient data set to abuse */
158
159int __init raid6_select_algo(void)
160{
161 const int disks = (65536/PAGE_SIZE)+2;
162
163 const struct raid6_calls *gen_best;
164 const struct raid6_recov_calls *rec_best;
165 char *syndromes;
166 void *dptrs[(65536/PAGE_SIZE)+2];
167 int i;
168
169 for (i = 0; i < disks-2; i++)
170 dptrs[i] = ((char *)raid6_gfmul) + PAGE_SIZE*i;
171
172 /* Normal code - use a 2-page allocation to avoid D$ conflict */
173 syndromes = (void *) __get_free_pages(GFP_KERNEL, 1);
174
175 if (!syndromes) {
176 printk("raid6: Yikes! No memory available.\n");
177 return -ENOMEM;
178 }
179
180 dptrs[disks-2] = syndromes;
181 dptrs[disks-1] = syndromes + PAGE_SIZE;
182
183 /* select raid gen_syndrome function */
184 gen_best = raid6_choose_gen(&dptrs, disks);
185
186 /* select raid recover functions */
187 rec_best = raid6_choose_recov();
188
142 free_pages((unsigned long)syndromes, 1); 189 free_pages((unsigned long)syndromes, 1);
143 190
144 return best ? 0 : -EINVAL; 191 return gen_best && rec_best ? 0 : -EINVAL;
145} 192}
146 193
147static void raid6_exit(void) 194static void raid6_exit(void)
diff --git a/lib/raid6/mktables.c b/lib/raid6/mktables.c
index 8a3780902cec..39787db588b0 100644
--- a/lib/raid6/mktables.c
+++ b/lib/raid6/mktables.c
@@ -81,6 +81,31 @@ int main(int argc, char *argv[])
81 printf("EXPORT_SYMBOL(raid6_gfmul);\n"); 81 printf("EXPORT_SYMBOL(raid6_gfmul);\n");
82 printf("#endif\n"); 82 printf("#endif\n");
83 83
84 /* Compute vector multiplication table */
85 printf("\nconst u8 __attribute__((aligned(256)))\n"
86 "raid6_vgfmul[256][32] =\n"
87 "{\n");
88 for (i = 0; i < 256; i++) {
89 printf("\t{\n");
90 for (j = 0; j < 16; j += 8) {
91 printf("\t\t");
92 for (k = 0; k < 8; k++)
93 printf("0x%02x,%c", gfmul(i, j + k),
94 (k == 7) ? '\n' : ' ');
95 }
96 for (j = 0; j < 16; j += 8) {
97 printf("\t\t");
98 for (k = 0; k < 8; k++)
99 printf("0x%02x,%c", gfmul(i, (j + k) << 4),
100 (k == 7) ? '\n' : ' ');
101 }
102 printf("\t},\n");
103 }
104 printf("};\n");
105 printf("#ifdef __KERNEL__\n");
106 printf("EXPORT_SYMBOL(raid6_vgfmul);\n");
107 printf("#endif\n");
108
84 /* Compute power-of-2 table (exponent) */ 109 /* Compute power-of-2 table (exponent) */
85 v = 1; 110 v = 1;
86 printf("\nconst u8 __attribute__((aligned(256)))\n" 111 printf("\nconst u8 __attribute__((aligned(256)))\n"
diff --git a/lib/raid6/recov.c b/lib/raid6/recov.c
index fe275d7b6b36..a95bccb8497d 100644
--- a/lib/raid6/recov.c
+++ b/lib/raid6/recov.c
@@ -22,8 +22,8 @@
22#include <linux/raid/pq.h> 22#include <linux/raid/pq.h>
23 23
24/* Recover two failed data blocks. */ 24/* Recover two failed data blocks. */
25void raid6_2data_recov(int disks, size_t bytes, int faila, int failb, 25static void raid6_2data_recov_intx1(int disks, size_t bytes, int faila,
26 void **ptrs) 26 int failb, void **ptrs)
27{ 27{
28 u8 *p, *q, *dp, *dq; 28 u8 *p, *q, *dp, *dq;
29 u8 px, qx, db; 29 u8 px, qx, db;
@@ -64,10 +64,10 @@ void raid6_2data_recov(int disks, size_t bytes, int faila, int failb,
64 p++; q++; 64 p++; q++;
65 } 65 }
66} 66}
67EXPORT_SYMBOL_GPL(raid6_2data_recov);
68 67
69/* Recover failure of one data block plus the P block */ 68/* Recover failure of one data block plus the P block */
70void raid6_datap_recov(int disks, size_t bytes, int faila, void **ptrs) 69static void raid6_datap_recov_intx1(int disks, size_t bytes, int faila,
70 void **ptrs)
71{ 71{
72 u8 *p, *q, *dq; 72 u8 *p, *q, *dq;
73 const u8 *qmul; /* Q multiplier table */ 73 const u8 *qmul; /* Q multiplier table */
@@ -96,7 +96,15 @@ void raid6_datap_recov(int disks, size_t bytes, int faila, void **ptrs)
96 q++; dq++; 96 q++; dq++;
97 } 97 }
98} 98}
99EXPORT_SYMBOL_GPL(raid6_datap_recov); 99
100
101const struct raid6_recov_calls raid6_recov_intx1 = {
102 .data2 = raid6_2data_recov_intx1,
103 .datap = raid6_datap_recov_intx1,
104 .valid = NULL,
105 .name = "intx1",
106 .priority = 0,
107};
100 108
101#ifndef __KERNEL__ 109#ifndef __KERNEL__
102/* Testing only */ 110/* Testing only */
diff --git a/lib/raid6/recov_ssse3.c b/lib/raid6/recov_ssse3.c
new file mode 100644
index 000000000000..ecb710c0b4d9
--- /dev/null
+++ b/lib/raid6/recov_ssse3.c
@@ -0,0 +1,336 @@
1/*
2 * Copyright (C) 2012 Intel Corporation
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; version 2
7 * of the License.
8 */
9
10#if (defined(__i386__) || defined(__x86_64__)) && !defined(__arch_um__)
11
12#include <linux/raid/pq.h>
13#include "x86.h"
14
15static int raid6_has_ssse3(void)
16{
17 return boot_cpu_has(X86_FEATURE_XMM) &&
18 boot_cpu_has(X86_FEATURE_XMM2) &&
19 boot_cpu_has(X86_FEATURE_SSSE3);
20}
21
22static void raid6_2data_recov_ssse3(int disks, size_t bytes, int faila,
23 int failb, void **ptrs)
24{
25 u8 *p, *q, *dp, *dq;
26 const u8 *pbmul; /* P multiplier table for B data */
27 const u8 *qmul; /* Q multiplier table (for both) */
28 static const u8 __aligned(16) x0f[16] = {
29 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f,
30 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f};
31
32 p = (u8 *)ptrs[disks-2];
33 q = (u8 *)ptrs[disks-1];
34
35 /* Compute syndrome with zero for the missing data pages
36 Use the dead data pages as temporary storage for
37 delta p and delta q */
38 dp = (u8 *)ptrs[faila];
39 ptrs[faila] = (void *)raid6_empty_zero_page;
40 ptrs[disks-2] = dp;
41 dq = (u8 *)ptrs[failb];
42 ptrs[failb] = (void *)raid6_empty_zero_page;
43 ptrs[disks-1] = dq;
44
45 raid6_call.gen_syndrome(disks, bytes, ptrs);
46
47 /* Restore pointer table */
48 ptrs[faila] = dp;
49 ptrs[failb] = dq;
50 ptrs[disks-2] = p;
51 ptrs[disks-1] = q;
52
53 /* Now, pick the proper data tables */
54 pbmul = raid6_vgfmul[raid6_gfexi[failb-faila]];
55 qmul = raid6_vgfmul[raid6_gfinv[raid6_gfexp[faila] ^
56 raid6_gfexp[failb]]];
57
58 kernel_fpu_begin();
59
60 asm volatile("movdqa %0,%%xmm7" : : "m" (x0f[0]));
61
62#ifdef CONFIG_X86_64
63 asm volatile("movdqa %0,%%xmm6" : : "m" (qmul[0]));
64 asm volatile("movdqa %0,%%xmm14" : : "m" (pbmul[0]));
65 asm volatile("movdqa %0,%%xmm15" : : "m" (pbmul[16]));
66#endif
67
68 /* Now do it... */
69 while (bytes) {
70#ifdef CONFIG_X86_64
71 /* xmm6, xmm14, xmm15 */
72
73 asm volatile("movdqa %0,%%xmm1" : : "m" (q[0]));
74 asm volatile("movdqa %0,%%xmm9" : : "m" (q[16]));
75 asm volatile("movdqa %0,%%xmm0" : : "m" (p[0]));
76 asm volatile("movdqa %0,%%xmm8" : : "m" (p[16]));
77 asm volatile("pxor %0,%%xmm1" : : "m" (dq[0]));
78 asm volatile("pxor %0,%%xmm9" : : "m" (dq[16]));
79 asm volatile("pxor %0,%%xmm0" : : "m" (dp[0]));
80 asm volatile("pxor %0,%%xmm8" : : "m" (dp[16]));
81
82 /* xmm0/8 = px */
83
84 asm volatile("movdqa %xmm6,%xmm4");
85 asm volatile("movdqa %0,%%xmm5" : : "m" (qmul[16]));
86 asm volatile("movdqa %xmm6,%xmm12");
87 asm volatile("movdqa %xmm5,%xmm13");
88 asm volatile("movdqa %xmm1,%xmm3");
89 asm volatile("movdqa %xmm9,%xmm11");
90 asm volatile("movdqa %xmm0,%xmm2"); /* xmm2/10 = px */
91 asm volatile("movdqa %xmm8,%xmm10");
92 asm volatile("psraw $4,%xmm1");
93 asm volatile("psraw $4,%xmm9");
94 asm volatile("pand %xmm7,%xmm3");
95 asm volatile("pand %xmm7,%xmm11");
96 asm volatile("pand %xmm7,%xmm1");
97 asm volatile("pand %xmm7,%xmm9");
98 asm volatile("pshufb %xmm3,%xmm4");
99 asm volatile("pshufb %xmm11,%xmm12");
100 asm volatile("pshufb %xmm1,%xmm5");
101 asm volatile("pshufb %xmm9,%xmm13");
102 asm volatile("pxor %xmm4,%xmm5");
103 asm volatile("pxor %xmm12,%xmm13");
104
105 /* xmm5/13 = qx */
106
107 asm volatile("movdqa %xmm14,%xmm4");
108 asm volatile("movdqa %xmm15,%xmm1");
109 asm volatile("movdqa %xmm14,%xmm12");
110 asm volatile("movdqa %xmm15,%xmm9");
111 asm volatile("movdqa %xmm2,%xmm3");
112 asm volatile("movdqa %xmm10,%xmm11");
113 asm volatile("psraw $4,%xmm2");
114 asm volatile("psraw $4,%xmm10");
115 asm volatile("pand %xmm7,%xmm3");
116 asm volatile("pand %xmm7,%xmm11");
117 asm volatile("pand %xmm7,%xmm2");
118 asm volatile("pand %xmm7,%xmm10");
119 asm volatile("pshufb %xmm3,%xmm4");
120 asm volatile("pshufb %xmm11,%xmm12");
121 asm volatile("pshufb %xmm2,%xmm1");
122 asm volatile("pshufb %xmm10,%xmm9");
123 asm volatile("pxor %xmm4,%xmm1");
124 asm volatile("pxor %xmm12,%xmm9");
125
126 /* xmm1/9 = pbmul[px] */
127 asm volatile("pxor %xmm5,%xmm1");
128 asm volatile("pxor %xmm13,%xmm9");
129 /* xmm1/9 = db = DQ */
130 asm volatile("movdqa %%xmm1,%0" : "=m" (dq[0]));
131 asm volatile("movdqa %%xmm9,%0" : "=m" (dq[16]));
132
133 asm volatile("pxor %xmm1,%xmm0");
134 asm volatile("pxor %xmm9,%xmm8");
135 asm volatile("movdqa %%xmm0,%0" : "=m" (dp[0]));
136 asm volatile("movdqa %%xmm8,%0" : "=m" (dp[16]));
137
138 bytes -= 32;
139 p += 32;
140 q += 32;
141 dp += 32;
142 dq += 32;
143#else
144 asm volatile("movdqa %0,%%xmm1" : : "m" (*q));
145 asm volatile("movdqa %0,%%xmm0" : : "m" (*p));
146 asm volatile("pxor %0,%%xmm1" : : "m" (*dq));
147 asm volatile("pxor %0,%%xmm0" : : "m" (*dp));
148
149 /* 1 = dq ^ q
150 * 0 = dp ^ p
151 */
152 asm volatile("movdqa %0,%%xmm4" : : "m" (qmul[0]));
153 asm volatile("movdqa %0,%%xmm5" : : "m" (qmul[16]));
154
155 asm volatile("movdqa %xmm1,%xmm3");
156 asm volatile("psraw $4,%xmm1");
157 asm volatile("pand %xmm7,%xmm3");
158 asm volatile("pand %xmm7,%xmm1");
159 asm volatile("pshufb %xmm3,%xmm4");
160 asm volatile("pshufb %xmm1,%xmm5");
161 asm volatile("pxor %xmm4,%xmm5");
162
163 asm volatile("movdqa %xmm0,%xmm2"); /* xmm2 = px */
164
165 /* xmm5 = qx */
166
167 asm volatile("movdqa %0,%%xmm4" : : "m" (pbmul[0]));
168 asm volatile("movdqa %0,%%xmm1" : : "m" (pbmul[16]));
169 asm volatile("movdqa %xmm2,%xmm3");
170 asm volatile("psraw $4,%xmm2");
171 asm volatile("pand %xmm7,%xmm3");
172 asm volatile("pand %xmm7,%xmm2");
173 asm volatile("pshufb %xmm3,%xmm4");
174 asm volatile("pshufb %xmm2,%xmm1");
175 asm volatile("pxor %xmm4,%xmm1");
176
177 /* xmm1 = pbmul[px] */
178 asm volatile("pxor %xmm5,%xmm1");
179 /* xmm1 = db = DQ */
180 asm volatile("movdqa %%xmm1,%0" : "=m" (*dq));
181
182 asm volatile("pxor %xmm1,%xmm0");
183 asm volatile("movdqa %%xmm0,%0" : "=m" (*dp));
184
185 bytes -= 16;
186 p += 16;
187 q += 16;
188 dp += 16;
189 dq += 16;
190#endif
191 }
192
193 kernel_fpu_end();
194}
195
196
197static void raid6_datap_recov_ssse3(int disks, size_t bytes, int faila,
198 void **ptrs)
199{
200 u8 *p, *q, *dq;
201 const u8 *qmul; /* Q multiplier table */
202 static const u8 __aligned(16) x0f[16] = {
203 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f,
204 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f};
205
206 p = (u8 *)ptrs[disks-2];
207 q = (u8 *)ptrs[disks-1];
208
209 /* Compute syndrome with zero for the missing data page
210 Use the dead data page as temporary storage for delta q */
211 dq = (u8 *)ptrs[faila];
212 ptrs[faila] = (void *)raid6_empty_zero_page;
213 ptrs[disks-1] = dq;
214
215 raid6_call.gen_syndrome(disks, bytes, ptrs);
216
217 /* Restore pointer table */
218 ptrs[faila] = dq;
219 ptrs[disks-1] = q;
220
221 /* Now, pick the proper data tables */
222 qmul = raid6_vgfmul[raid6_gfinv[raid6_gfexp[faila]]];
223
224 kernel_fpu_begin();
225
226 asm volatile("movdqa %0, %%xmm7" : : "m" (x0f[0]));
227
228 while (bytes) {
229#ifdef CONFIG_X86_64
230 asm volatile("movdqa %0, %%xmm3" : : "m" (dq[0]));
231 asm volatile("movdqa %0, %%xmm4" : : "m" (dq[16]));
232 asm volatile("pxor %0, %%xmm3" : : "m" (q[0]));
233 asm volatile("movdqa %0, %%xmm0" : : "m" (qmul[0]));
234
235 /* xmm3 = q[0] ^ dq[0] */
236
237 asm volatile("pxor %0, %%xmm4" : : "m" (q[16]));
238 asm volatile("movdqa %0, %%xmm1" : : "m" (qmul[16]));
239
240 /* xmm4 = q[16] ^ dq[16] */
241
242 asm volatile("movdqa %xmm3, %xmm6");
243 asm volatile("movdqa %xmm4, %xmm8");
244
245 /* xmm4 = xmm8 = q[16] ^ dq[16] */
246
247 asm volatile("psraw $4, %xmm3");
248 asm volatile("pand %xmm7, %xmm6");
249 asm volatile("pand %xmm7, %xmm3");
250 asm volatile("pshufb %xmm6, %xmm0");
251 asm volatile("pshufb %xmm3, %xmm1");
252 asm volatile("movdqa %0, %%xmm10" : : "m" (qmul[0]));
253 asm volatile("pxor %xmm0, %xmm1");
254 asm volatile("movdqa %0, %%xmm11" : : "m" (qmul[16]));
255
256 /* xmm1 = qmul[q[0] ^ dq[0]] */
257
258 asm volatile("psraw $4, %xmm4");
259 asm volatile("pand %xmm7, %xmm8");
260 asm volatile("pand %xmm7, %xmm4");
261 asm volatile("pshufb %xmm8, %xmm10");
262 asm volatile("pshufb %xmm4, %xmm11");
263 asm volatile("movdqa %0, %%xmm2" : : "m" (p[0]));
264 asm volatile("pxor %xmm10, %xmm11");
265 asm volatile("movdqa %0, %%xmm12" : : "m" (p[16]));
266
267 /* xmm11 = qmul[q[16] ^ dq[16]] */
268
269 asm volatile("pxor %xmm1, %xmm2");
270
271 /* xmm2 = p[0] ^ qmul[q[0] ^ dq[0]] */
272
273 asm volatile("pxor %xmm11, %xmm12");
274
275 /* xmm12 = p[16] ^ qmul[q[16] ^ dq[16]] */
276
277 asm volatile("movdqa %%xmm1, %0" : "=m" (dq[0]));
278 asm volatile("movdqa %%xmm11, %0" : "=m" (dq[16]));
279
280 asm volatile("movdqa %%xmm2, %0" : "=m" (p[0]));
281 asm volatile("movdqa %%xmm12, %0" : "=m" (p[16]));
282
283 bytes -= 32;
284 p += 32;
285 q += 32;
286 dq += 32;
287
288#else
289 asm volatile("movdqa %0, %%xmm3" : : "m" (dq[0]));
290 asm volatile("movdqa %0, %%xmm0" : : "m" (qmul[0]));
291 asm volatile("pxor %0, %%xmm3" : : "m" (q[0]));
292 asm volatile("movdqa %0, %%xmm1" : : "m" (qmul[16]));
293
294 /* xmm3 = *q ^ *dq */
295
296 asm volatile("movdqa %xmm3, %xmm6");
297 asm volatile("movdqa %0, %%xmm2" : : "m" (p[0]));
298 asm volatile("psraw $4, %xmm3");
299 asm volatile("pand %xmm7, %xmm6");
300 asm volatile("pand %xmm7, %xmm3");
301 asm volatile("pshufb %xmm6, %xmm0");
302 asm volatile("pshufb %xmm3, %xmm1");
303 asm volatile("pxor %xmm0, %xmm1");
304
305 /* xmm1 = qmul[*q ^ *dq */
306
307 asm volatile("pxor %xmm1, %xmm2");
308
309 /* xmm2 = *p ^ qmul[*q ^ *dq] */
310
311 asm volatile("movdqa %%xmm1, %0" : "=m" (dq[0]));
312 asm volatile("movdqa %%xmm2, %0" : "=m" (p[0]));
313
314 bytes -= 16;
315 p += 16;
316 q += 16;
317 dq += 16;
318#endif
319 }
320
321 kernel_fpu_end();
322}
323
324const struct raid6_recov_calls raid6_recov_ssse3 = {
325 .data2 = raid6_2data_recov_ssse3,
326 .datap = raid6_datap_recov_ssse3,
327 .valid = raid6_has_ssse3,
328#ifdef CONFIG_X86_64
329 .name = "ssse3x2",
330#else
331 .name = "ssse3x1",
332#endif
333 .priority = 1,
334};
335
336#endif
diff --git a/lib/raid6/test/Makefile b/lib/raid6/test/Makefile
index aa651697b6dc..c76151d94764 100644
--- a/lib/raid6/test/Makefile
+++ b/lib/raid6/test/Makefile
@@ -23,7 +23,7 @@ RANLIB = ranlib
23all: raid6.a raid6test 23all: raid6.a raid6test
24 24
25raid6.a: int1.o int2.o int4.o int8.o int16.o int32.o mmx.o sse1.o sse2.o \ 25raid6.a: int1.o int2.o int4.o int8.o int16.o int32.o mmx.o sse1.o sse2.o \
26 altivec1.o altivec2.o altivec4.o altivec8.o recov.o algos.o \ 26 altivec1.o altivec2.o altivec4.o altivec8.o recov.o recov_ssse3.o algos.o \
27 tables.o 27 tables.o
28 rm -f $@ 28 rm -f $@
29 $(AR) cq $@ $^ 29 $(AR) cq $@ $^
diff --git a/lib/raid6/test/test.c b/lib/raid6/test/test.c
index 7a930318b17d..5a485b7a7d3c 100644
--- a/lib/raid6/test/test.c
+++ b/lib/raid6/test/test.c
@@ -90,25 +90,35 @@ static int test_disks(int i, int j)
90int main(int argc, char *argv[]) 90int main(int argc, char *argv[])
91{ 91{
92 const struct raid6_calls *const *algo; 92 const struct raid6_calls *const *algo;
93 const struct raid6_recov_calls *const *ra;
93 int i, j; 94 int i, j;
94 int err = 0; 95 int err = 0;
95 96
96 makedata(); 97 makedata();
97 98
98 for (algo = raid6_algos; *algo; algo++) { 99 for (ra = raid6_recov_algos; *ra; ra++) {
99 if (!(*algo)->valid || (*algo)->valid()) { 100 if ((*ra)->valid && !(*ra)->valid())
100 raid6_call = **algo; 101 continue;
102 raid6_2data_recov = (*ra)->data2;
103 raid6_datap_recov = (*ra)->datap;
101 104
102 /* Nuke syndromes */ 105 printf("using recovery %s\n", (*ra)->name);
103 memset(data[NDISKS-2], 0xee, 2*PAGE_SIZE);
104 106
105 /* Generate assumed good syndrome */ 107 for (algo = raid6_algos; *algo; algo++) {
106 raid6_call.gen_syndrome(NDISKS, PAGE_SIZE, 108 if (!(*algo)->valid || (*algo)->valid()) {
107 (void **)&dataptrs); 109 raid6_call = **algo;
108 110
109 for (i = 0; i < NDISKS-1; i++) 111 /* Nuke syndromes */
110 for (j = i+1; j < NDISKS; j++) 112 memset(data[NDISKS-2], 0xee, 2*PAGE_SIZE);
111 err += test_disks(i, j); 113
114 /* Generate assumed good syndrome */
115 raid6_call.gen_syndrome(NDISKS, PAGE_SIZE,
116 (void **)&dataptrs);
117
118 for (i = 0; i < NDISKS-1; i++)
119 for (j = i+1; j < NDISKS; j++)
120 err += test_disks(i, j);
121 }
112 } 122 }
113 printf("\n"); 123 printf("\n");
114 } 124 }
diff --git a/lib/raid6/x86.h b/lib/raid6/x86.h
index cb2a8c91c886..d55d63232c55 100644
--- a/lib/raid6/x86.h
+++ b/lib/raid6/x86.h
@@ -35,24 +35,29 @@ static inline void kernel_fpu_end(void)
35{ 35{
36} 36}
37 37
38#define __aligned(x) __attribute__((aligned(x)))
39
38#define X86_FEATURE_MMX (0*32+23) /* Multimedia Extensions */ 40#define X86_FEATURE_MMX (0*32+23) /* Multimedia Extensions */
39#define X86_FEATURE_FXSR (0*32+24) /* FXSAVE and FXRSTOR instructions 41#define X86_FEATURE_FXSR (0*32+24) /* FXSAVE and FXRSTOR instructions
40 * (fast save and restore) */ 42 * (fast save and restore) */
41#define X86_FEATURE_XMM (0*32+25) /* Streaming SIMD Extensions */ 43#define X86_FEATURE_XMM (0*32+25) /* Streaming SIMD Extensions */
42#define X86_FEATURE_XMM2 (0*32+26) /* Streaming SIMD Extensions-2 */ 44#define X86_FEATURE_XMM2 (0*32+26) /* Streaming SIMD Extensions-2 */
45#define X86_FEATURE_XMM3 (4*32+ 0) /* "pni" SSE-3 */
46#define X86_FEATURE_SSSE3 (4*32+ 9) /* Supplemental SSE-3 */
47#define X86_FEATURE_AVX (4*32+28) /* Advanced Vector Extensions */
43#define X86_FEATURE_MMXEXT (1*32+22) /* AMD MMX extensions */ 48#define X86_FEATURE_MMXEXT (1*32+22) /* AMD MMX extensions */
44 49
45/* Should work well enough on modern CPUs for testing */ 50/* Should work well enough on modern CPUs for testing */
46static inline int boot_cpu_has(int flag) 51static inline int boot_cpu_has(int flag)
47{ 52{
48 u32 eax = (flag >> 5) ? 0x80000001 : 1; 53 u32 eax = (flag & 0x20) ? 0x80000001 : 1;
49 u32 edx; 54 u32 ecx, edx;
50 55
51 asm volatile("cpuid" 56 asm volatile("cpuid"
52 : "+a" (eax), "=d" (edx) 57 : "+a" (eax), "=d" (edx), "=c" (ecx)
53 : : "ecx", "ebx"); 58 : : "ebx");
54 59
55 return (edx >> (flag & 31)) & 1; 60 return ((flag & 0x80 ? ecx : edx) >> (flag & 31)) & 1;
56} 61}
57 62
58#endif /* ndef __KERNEL__ */ 63#endif /* ndef __KERNEL__ */
diff --git a/lib/rational.c b/lib/rational.c
index d326da3976f5..f0aa21c2a762 100644
--- a/lib/rational.c
+++ b/lib/rational.c
@@ -1,7 +1,7 @@
1/* 1/*
2 * rational fractions 2 * rational fractions
3 * 3 *
4 * Copyright (C) 2009 emlix GmbH, Oskar Schirmer <os@emlix.com> 4 * Copyright (C) 2009 emlix GmbH, Oskar Schirmer <oskar@scara.com>
5 * 5 *
6 * helper functions when coping with rational numbers 6 * helper functions when coping with rational numbers
7 */ 7 */
diff --git a/lib/scatterlist.c b/lib/scatterlist.c
index 6096e89bee55..fadae774a20c 100644
--- a/lib/scatterlist.c
+++ b/lib/scatterlist.c
@@ -279,14 +279,6 @@ int __sg_alloc_table(struct sg_table *table, unsigned int nents,
279 if (!left) 279 if (!left)
280 sg_mark_end(&sg[sg_size - 1]); 280 sg_mark_end(&sg[sg_size - 1]);
281 281
282 /*
283 * only really needed for mempool backed sg allocations (like
284 * SCSI), a possible improvement here would be to pass the
285 * table pointer into the allocator and let that clear these
286 * flags
287 */
288 gfp_mask &= ~__GFP_WAIT;
289 gfp_mask |= __GFP_HIGH;
290 prv = sg; 282 prv = sg;
291 } while (left); 283 } while (left);
292 284
@@ -319,6 +311,70 @@ int sg_alloc_table(struct sg_table *table, unsigned int nents, gfp_t gfp_mask)
319EXPORT_SYMBOL(sg_alloc_table); 311EXPORT_SYMBOL(sg_alloc_table);
320 312
321/** 313/**
314 * sg_alloc_table_from_pages - Allocate and initialize an sg table from
315 * an array of pages
316 * @sgt: The sg table header to use
317 * @pages: Pointer to an array of page pointers
318 * @n_pages: Number of pages in the pages array
319 * @offset: Offset from start of the first page to the start of a buffer
320 * @size: Number of valid bytes in the buffer (after offset)
321 * @gfp_mask: GFP allocation mask
322 *
323 * Description:
324 * Allocate and initialize an sg table from a list of pages. Contiguous
325 * ranges of the pages are squashed into a single scatterlist node. A user
326 * may provide an offset at a start and a size of valid data in a buffer
327 * specified by the page array. The returned sg table is released by
328 * sg_free_table.
329 *
330 * Returns:
331 * 0 on success, negative error on failure
332 */
333int sg_alloc_table_from_pages(struct sg_table *sgt,
334 struct page **pages, unsigned int n_pages,
335 unsigned long offset, unsigned long size,
336 gfp_t gfp_mask)
337{
338 unsigned int chunks;
339 unsigned int i;
340 unsigned int cur_page;
341 int ret;
342 struct scatterlist *s;
343
344 /* compute number of contiguous chunks */
345 chunks = 1;
346 for (i = 1; i < n_pages; ++i)
347 if (page_to_pfn(pages[i]) != page_to_pfn(pages[i - 1]) + 1)
348 ++chunks;
349
350 ret = sg_alloc_table(sgt, chunks, gfp_mask);
351 if (unlikely(ret))
352 return ret;
353
354 /* merging chunks and putting them into the scatterlist */
355 cur_page = 0;
356 for_each_sg(sgt->sgl, s, sgt->orig_nents, i) {
357 unsigned long chunk_size;
358 unsigned int j;
359
360 /* look for the end of the current chunk */
361 for (j = cur_page + 1; j < n_pages; ++j)
362 if (page_to_pfn(pages[j]) !=
363 page_to_pfn(pages[j - 1]) + 1)
364 break;
365
366 chunk_size = ((j - cur_page) << PAGE_SHIFT) - offset;
367 sg_set_page(s, pages[cur_page], min(size, chunk_size), offset);
368 size -= chunk_size;
369 offset = 0;
370 cur_page = j;
371 }
372
373 return 0;
374}
375EXPORT_SYMBOL(sg_alloc_table_from_pages);
376
377/**
322 * sg_miter_start - start mapping iteration over a sg list 378 * sg_miter_start - start mapping iteration over a sg list
323 * @miter: sg mapping iter to be started 379 * @miter: sg mapping iter to be started
324 * @sgl: sg list to iterate over 380 * @sgl: sg list to iterate over
diff --git a/lib/spinlock_debug.c b/lib/spinlock_debug.c
index 525d160d44f0..eb10578ae055 100644
--- a/lib/spinlock_debug.c
+++ b/lib/spinlock_debug.c
@@ -58,7 +58,7 @@ static void spin_dump(raw_spinlock_t *lock, const char *msg)
58 printk(KERN_EMERG "BUG: spinlock %s on CPU#%d, %s/%d\n", 58 printk(KERN_EMERG "BUG: spinlock %s on CPU#%d, %s/%d\n",
59 msg, raw_smp_processor_id(), 59 msg, raw_smp_processor_id(),
60 current->comm, task_pid_nr(current)); 60 current->comm, task_pid_nr(current));
61 printk(KERN_EMERG " lock: %p, .magic: %08x, .owner: %s/%d, " 61 printk(KERN_EMERG " lock: %pS, .magic: %08x, .owner: %s/%d, "
62 ".owner_cpu: %d\n", 62 ".owner_cpu: %d\n",
63 lock, lock->magic, 63 lock, lock->magic,
64 owner ? owner->comm : "<none>", 64 owner ? owner->comm : "<none>",
@@ -118,7 +118,7 @@ static void __spin_lock_debug(raw_spinlock_t *lock)
118 /* lockup suspected: */ 118 /* lockup suspected: */
119 if (print_once) { 119 if (print_once) {
120 print_once = 0; 120 print_once = 0;
121 spin_dump(lock, "lockup"); 121 spin_dump(lock, "lockup suspected");
122#ifdef CONFIG_SMP 122#ifdef CONFIG_SMP
123 trigger_all_cpu_backtrace(); 123 trigger_all_cpu_backtrace();
124#endif 124#endif
diff --git a/lib/stmp_device.c b/lib/stmp_device.c
new file mode 100644
index 000000000000..8ac9bcc4289a
--- /dev/null
+++ b/lib/stmp_device.c
@@ -0,0 +1,80 @@
1/*
2 * Copyright (C) 1999 ARM Limited
3 * Copyright (C) 2000 Deep Blue Solutions Ltd
4 * Copyright 2006-2007,2010 Freescale Semiconductor, Inc. All Rights Reserved.
5 * Copyright 2008 Juergen Beisert, kernel@pengutronix.de
6 * Copyright 2009 Ilya Yanok, Emcraft Systems Ltd, yanok@emcraft.com
7 * Copyright (C) 2011 Wolfram Sang, Pengutronix e.K.
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 */
14
15#include <linux/io.h>
16#include <linux/errno.h>
17#include <linux/delay.h>
18#include <linux/module.h>
19#include <linux/stmp_device.h>
20
21#define STMP_MODULE_CLKGATE (1 << 30)
22#define STMP_MODULE_SFTRST (1 << 31)
23
24/*
25 * Clear the bit and poll it cleared. This is usually called with
26 * a reset address and mask being either SFTRST(bit 31) or CLKGATE
27 * (bit 30).
28 */
29static int stmp_clear_poll_bit(void __iomem *addr, u32 mask)
30{
31 int timeout = 0x400;
32
33 writel(mask, addr + STMP_OFFSET_REG_CLR);
34 udelay(1);
35 while ((readl(addr) & mask) && --timeout)
36 /* nothing */;
37
38 return !timeout;
39}
40
41int stmp_reset_block(void __iomem *reset_addr)
42{
43 int ret;
44 int timeout = 0x400;
45
46 /* clear and poll SFTRST */
47 ret = stmp_clear_poll_bit(reset_addr, STMP_MODULE_SFTRST);
48 if (unlikely(ret))
49 goto error;
50
51 /* clear CLKGATE */
52 writel(STMP_MODULE_CLKGATE, reset_addr + STMP_OFFSET_REG_CLR);
53
54 /* set SFTRST to reset the block */
55 writel(STMP_MODULE_SFTRST, reset_addr + STMP_OFFSET_REG_SET);
56 udelay(1);
57
58 /* poll CLKGATE becoming set */
59 while ((!(readl(reset_addr) & STMP_MODULE_CLKGATE)) && --timeout)
60 /* nothing */;
61 if (unlikely(!timeout))
62 goto error;
63
64 /* clear and poll SFTRST */
65 ret = stmp_clear_poll_bit(reset_addr, STMP_MODULE_SFTRST);
66 if (unlikely(ret))
67 goto error;
68
69 /* clear and poll CLKGATE */
70 ret = stmp_clear_poll_bit(reset_addr, STMP_MODULE_CLKGATE);
71 if (unlikely(ret))
72 goto error;
73
74 return 0;
75
76error:
77 pr_err("%s(%p): module reset timeout\n", __func__, reset_addr);
78 return -ETIMEDOUT;
79}
80EXPORT_SYMBOL(stmp_reset_block);
diff --git a/lib/string_helpers.c b/lib/string_helpers.c
index dd4ece372699..1cffc223bff5 100644
--- a/lib/string_helpers.c
+++ b/lib/string_helpers.c
@@ -23,15 +23,15 @@
23int string_get_size(u64 size, const enum string_size_units units, 23int string_get_size(u64 size, const enum string_size_units units,
24 char *buf, int len) 24 char *buf, int len)
25{ 25{
26 const char *units_10[] = { "B", "kB", "MB", "GB", "TB", "PB", 26 static const char *units_10[] = { "B", "kB", "MB", "GB", "TB", "PB",
27 "EB", "ZB", "YB", NULL}; 27 "EB", "ZB", "YB", NULL};
28 const char *units_2[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB", 28 static const char *units_2[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB",
29 "EiB", "ZiB", "YiB", NULL }; 29 "EiB", "ZiB", "YiB", NULL };
30 const char **units_str[] = { 30 static const char **units_str[] = {
31 [STRING_UNITS_10] = units_10, 31 [STRING_UNITS_10] = units_10,
32 [STRING_UNITS_2] = units_2, 32 [STRING_UNITS_2] = units_2,
33 }; 33 };
34 const unsigned int divisor[] = { 34 static const unsigned int divisor[] = {
35 [STRING_UNITS_10] = 1000, 35 [STRING_UNITS_10] = 1000,
36 [STRING_UNITS_2] = 1024, 36 [STRING_UNITS_2] = 1024,
37 }; 37 };
diff --git a/lib/strncpy_from_user.c b/lib/strncpy_from_user.c
new file mode 100644
index 000000000000..bb2b201d6ad0
--- /dev/null
+++ b/lib/strncpy_from_user.c
@@ -0,0 +1,113 @@
1#include <linux/module.h>
2#include <linux/uaccess.h>
3#include <linux/kernel.h>
4#include <linux/errno.h>
5
6#include <asm/byteorder.h>
7#include <asm/word-at-a-time.h>
8
9#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
10#define IS_UNALIGNED(src, dst) 0
11#else
12#define IS_UNALIGNED(src, dst) \
13 (((long) dst | (long) src) & (sizeof(long) - 1))
14#endif
15
16/*
17 * Do a strncpy, return length of string without final '\0'.
18 * 'count' is the user-supplied count (return 'count' if we
19 * hit it), 'max' is the address space maximum (and we return
20 * -EFAULT if we hit it).
21 */
22static inline long do_strncpy_from_user(char *dst, const char __user *src, long count, unsigned long max)
23{
24 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
25 long res = 0;
26
27 /*
28 * Truncate 'max' to the user-specified limit, so that
29 * we only have one limit we need to check in the loop
30 */
31 if (max > count)
32 max = count;
33
34 if (IS_UNALIGNED(src, dst))
35 goto byte_at_a_time;
36
37 while (max >= sizeof(unsigned long)) {
38 unsigned long c, data;
39
40 /* Fall back to byte-at-a-time if we get a page fault */
41 if (unlikely(__get_user(c,(unsigned long __user *)(src+res))))
42 break;
43 *(unsigned long *)(dst+res) = c;
44 if (has_zero(c, &data, &constants)) {
45 data = prep_zero_mask(c, data, &constants);
46 data = create_zero_mask(data);
47 return res + find_zero(data);
48 }
49 res += sizeof(unsigned long);
50 max -= sizeof(unsigned long);
51 }
52
53byte_at_a_time:
54 while (max) {
55 char c;
56
57 if (unlikely(__get_user(c,src+res)))
58 return -EFAULT;
59 dst[res] = c;
60 if (!c)
61 return res;
62 res++;
63 max--;
64 }
65
66 /*
67 * Uhhuh. We hit 'max'. But was that the user-specified maximum
68 * too? If so, that's ok - we got as much as the user asked for.
69 */
70 if (res >= count)
71 return res;
72
73 /*
74 * Nope: we hit the address space limit, and we still had more
75 * characters the caller would have wanted. That's an EFAULT.
76 */
77 return -EFAULT;
78}
79
80/**
81 * strncpy_from_user: - Copy a NUL terminated string from userspace.
82 * @dst: Destination address, in kernel space. This buffer must be at
83 * least @count bytes long.
84 * @src: Source address, in user space.
85 * @count: Maximum number of bytes to copy, including the trailing NUL.
86 *
87 * Copies a NUL-terminated string from userspace to kernel space.
88 *
89 * On success, returns the length of the string (not including the trailing
90 * NUL).
91 *
92 * If access to userspace fails, returns -EFAULT (some data may have been
93 * copied).
94 *
95 * If @count is smaller than the length of the string, copies @count bytes
96 * and returns @count.
97 */
98long strncpy_from_user(char *dst, const char __user *src, long count)
99{
100 unsigned long max_addr, src_addr;
101
102 if (unlikely(count <= 0))
103 return 0;
104
105 max_addr = user_addr_max();
106 src_addr = (unsigned long)src;
107 if (likely(src_addr < max_addr)) {
108 unsigned long max = max_addr - src_addr;
109 return do_strncpy_from_user(dst, src, count, max);
110 }
111 return -EFAULT;
112}
113EXPORT_SYMBOL(strncpy_from_user);
diff --git a/lib/strnlen_user.c b/lib/strnlen_user.c
new file mode 100644
index 000000000000..a28df5206d95
--- /dev/null
+++ b/lib/strnlen_user.c
@@ -0,0 +1,138 @@
1#include <linux/kernel.h>
2#include <linux/export.h>
3#include <linux/uaccess.h>
4
5#include <asm/word-at-a-time.h>
6
7/* Set bits in the first 'n' bytes when loaded from memory */
8#ifdef __LITTLE_ENDIAN
9# define aligned_byte_mask(n) ((1ul << 8*(n))-1)
10#else
11# define aligned_byte_mask(n) (~0xfful << (BITS_PER_LONG - 8 - 8*(n)))
12#endif
13
14/*
15 * Do a strnlen, return length of string *with* final '\0'.
16 * 'count' is the user-supplied count, while 'max' is the
17 * address space maximum.
18 *
19 * Return 0 for exceptions (which includes hitting the address
20 * space maximum), or 'count+1' if hitting the user-supplied
21 * maximum count.
22 *
23 * NOTE! We can sometimes overshoot the user-supplied maximum
24 * if it fits in a aligned 'long'. The caller needs to check
25 * the return value against "> max".
26 */
27static inline long do_strnlen_user(const char __user *src, unsigned long count, unsigned long max)
28{
29 const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS;
30 long align, res = 0;
31 unsigned long c;
32
33 /*
34 * Truncate 'max' to the user-specified limit, so that
35 * we only have one limit we need to check in the loop
36 */
37 if (max > count)
38 max = count;
39
40 /*
41 * Do everything aligned. But that means that we
42 * need to also expand the maximum..
43 */
44 align = (sizeof(long) - 1) & (unsigned long)src;
45 src -= align;
46 max += align;
47
48 if (unlikely(__get_user(c,(unsigned long __user *)src)))
49 return 0;
50 c |= aligned_byte_mask(align);
51
52 for (;;) {
53 unsigned long data;
54 if (has_zero(c, &data, &constants)) {
55 data = prep_zero_mask(c, data, &constants);
56 data = create_zero_mask(data);
57 return res + find_zero(data) + 1 - align;
58 }
59 res += sizeof(unsigned long);
60 if (unlikely(max < sizeof(unsigned long)))
61 break;
62 max -= sizeof(unsigned long);
63 if (unlikely(__get_user(c,(unsigned long __user *)(src+res))))
64 return 0;
65 }
66 res -= align;
67
68 /*
69 * Uhhuh. We hit 'max'. But was that the user-specified maximum
70 * too? If so, return the marker for "too long".
71 */
72 if (res >= count)
73 return count+1;
74
75 /*
76 * Nope: we hit the address space limit, and we still had more
77 * characters the caller would have wanted. That's 0.
78 */
79 return 0;
80}
81
82/**
83 * strnlen_user: - Get the size of a user string INCLUDING final NUL.
84 * @str: The string to measure.
85 * @count: Maximum count (including NUL character)
86 *
87 * Context: User context only. This function may sleep.
88 *
89 * Get the size of a NUL-terminated string in user space.
90 *
91 * Returns the size of the string INCLUDING the terminating NUL.
92 * If the string is too long, returns 'count+1'.
93 * On exception (or invalid count), returns 0.
94 */
95long strnlen_user(const char __user *str, long count)
96{
97 unsigned long max_addr, src_addr;
98
99 if (unlikely(count <= 0))
100 return 0;
101
102 max_addr = user_addr_max();
103 src_addr = (unsigned long)str;
104 if (likely(src_addr < max_addr)) {
105 unsigned long max = max_addr - src_addr;
106 return do_strnlen_user(str, count, max);
107 }
108 return 0;
109}
110EXPORT_SYMBOL(strnlen_user);
111
112/**
113 * strlen_user: - Get the size of a user string INCLUDING final NUL.
114 * @str: The string to measure.
115 *
116 * Context: User context only. This function may sleep.
117 *
118 * Get the size of a NUL-terminated string in user space.
119 *
120 * Returns the size of the string INCLUDING the terminating NUL.
121 * On exception, returns 0.
122 *
123 * If there is a limit on the length of a valid string, you may wish to
124 * consider using strnlen_user() instead.
125 */
126long strlen_user(const char __user *str)
127{
128 unsigned long max_addr, src_addr;
129
130 max_addr = user_addr_max();
131 src_addr = (unsigned long)str;
132 if (likely(src_addr < max_addr)) {
133 unsigned long max = max_addr - src_addr;
134 return do_strnlen_user(str, ~0ul, max);
135 }
136 return 0;
137}
138EXPORT_SYMBOL(strlen_user);
diff --git a/lib/swiotlb.c b/lib/swiotlb.c
index 414f46ed1dcd..45bc1f83a5ad 100644
--- a/lib/swiotlb.c
+++ b/lib/swiotlb.c
@@ -130,11 +130,9 @@ void swiotlb_print_info(void)
130 pstart = virt_to_phys(io_tlb_start); 130 pstart = virt_to_phys(io_tlb_start);
131 pend = virt_to_phys(io_tlb_end); 131 pend = virt_to_phys(io_tlb_end);
132 132
133 printk(KERN_INFO "Placing %luMB software IO TLB between %p - %p\n", 133 printk(KERN_INFO "software IO TLB [mem %#010llx-%#010llx] (%luMB) mapped at [%p-%p]\n",
134 bytes >> 20, io_tlb_start, io_tlb_end); 134 (unsigned long long)pstart, (unsigned long long)pend - 1,
135 printk(KERN_INFO "software IO TLB at phys %#llx - %#llx\n", 135 bytes >> 20, io_tlb_start, io_tlb_end - 1);
136 (unsigned long long)pstart,
137 (unsigned long long)pend);
138} 136}
139 137
140void __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose) 138void __init swiotlb_init_with_tbl(char *tlb, unsigned long nslabs, int verbose)
diff --git a/lib/test-kstrtox.c b/lib/test-kstrtox.c
index d55769d63cb8..bea3f3fa3f02 100644
--- a/lib/test-kstrtox.c
+++ b/lib/test-kstrtox.c
@@ -11,7 +11,7 @@ struct test_fail {
11}; 11};
12 12
13#define DEFINE_TEST_FAIL(test) \ 13#define DEFINE_TEST_FAIL(test) \
14 const struct test_fail test[] __initdata 14 const struct test_fail test[] __initconst
15 15
16#define DECLARE_TEST_OK(type, test_type) \ 16#define DECLARE_TEST_OK(type, test_type) \
17 test_type { \ 17 test_type { \
@@ -21,7 +21,7 @@ struct test_fail {
21 } 21 }
22 22
23#define DEFINE_TEST_OK(type, test) \ 23#define DEFINE_TEST_OK(type, test) \
24 const type test[] __initdata 24 const type test[] __initconst
25 25
26#define TEST_FAIL(fn, type, fmt, test) \ 26#define TEST_FAIL(fn, type, fmt, test) \
27{ \ 27{ \
diff --git a/lib/vsprintf.c b/lib/vsprintf.c
index abbabec9720a..0e337541f005 100644
--- a/lib/vsprintf.c
+++ b/lib/vsprintf.c
@@ -112,106 +112,199 @@ int skip_atoi(const char **s)
112/* Decimal conversion is by far the most typical, and is used 112/* Decimal conversion is by far the most typical, and is used
113 * for /proc and /sys data. This directly impacts e.g. top performance 113 * for /proc and /sys data. This directly impacts e.g. top performance
114 * with many processes running. We optimize it for speed 114 * with many processes running. We optimize it for speed
115 * using code from 115 * using ideas described at <http://www.cs.uiowa.edu/~jones/bcd/divide.html>
116 * http://www.cs.uiowa.edu/~jones/bcd/decimal.html 116 * (with permission from the author, Douglas W. Jones).
117 * (with permission from the author, Douglas W. Jones). */ 117 */
118 118
119/* Formats correctly any integer in [0,99999]. 119#if BITS_PER_LONG != 32 || BITS_PER_LONG_LONG != 64
120 * Outputs from one to five digits depending on input. 120/* Formats correctly any integer in [0, 999999999] */
121 * On i386 gcc 4.1.2 -O2: ~250 bytes of code. */
122static noinline_for_stack 121static noinline_for_stack
123char *put_dec_trunc(char *buf, unsigned q) 122char *put_dec_full9(char *buf, unsigned q)
124{ 123{
125 unsigned d3, d2, d1, d0; 124 unsigned r;
126 d1 = (q>>4) & 0xf;
127 d2 = (q>>8) & 0xf;
128 d3 = (q>>12);
129
130 d0 = 6*(d3 + d2 + d1) + (q & 0xf);
131 q = (d0 * 0xcd) >> 11;
132 d0 = d0 - 10*q;
133 *buf++ = d0 + '0'; /* least significant digit */
134 d1 = q + 9*d3 + 5*d2 + d1;
135 if (d1 != 0) {
136 q = (d1 * 0xcd) >> 11;
137 d1 = d1 - 10*q;
138 *buf++ = d1 + '0'; /* next digit */
139
140 d2 = q + 2*d2;
141 if ((d2 != 0) || (d3 != 0)) {
142 q = (d2 * 0xd) >> 7;
143 d2 = d2 - 10*q;
144 *buf++ = d2 + '0'; /* next digit */
145
146 d3 = q + 4*d3;
147 if (d3 != 0) {
148 q = (d3 * 0xcd) >> 11;
149 d3 = d3 - 10*q;
150 *buf++ = d3 + '0'; /* next digit */
151 if (q != 0)
152 *buf++ = q + '0'; /* most sign. digit */
153 }
154 }
155 }
156 125
126 /*
127 * Possible ways to approx. divide by 10
128 * (x * 0x1999999a) >> 32 x < 1073741829 (multiply must be 64-bit)
129 * (x * 0xcccd) >> 19 x < 81920 (x < 262149 when 64-bit mul)
130 * (x * 0x6667) >> 18 x < 43699
131 * (x * 0x3334) >> 17 x < 16389
132 * (x * 0x199a) >> 16 x < 16389
133 * (x * 0x0ccd) >> 15 x < 16389
134 * (x * 0x0667) >> 14 x < 2739
135 * (x * 0x0334) >> 13 x < 1029
136 * (x * 0x019a) >> 12 x < 1029
137 * (x * 0x00cd) >> 11 x < 1029 shorter code than * 0x67 (on i386)
138 * (x * 0x0067) >> 10 x < 179
139 * (x * 0x0034) >> 9 x < 69 same
140 * (x * 0x001a) >> 8 x < 69 same
141 * (x * 0x000d) >> 7 x < 69 same, shortest code (on i386)
142 * (x * 0x0007) >> 6 x < 19
143 * See <http://www.cs.uiowa.edu/~jones/bcd/divide.html>
144 */
145 r = (q * (uint64_t)0x1999999a) >> 32;
146 *buf++ = (q - 10 * r) + '0'; /* 1 */
147 q = (r * (uint64_t)0x1999999a) >> 32;
148 *buf++ = (r - 10 * q) + '0'; /* 2 */
149 r = (q * (uint64_t)0x1999999a) >> 32;
150 *buf++ = (q - 10 * r) + '0'; /* 3 */
151 q = (r * (uint64_t)0x1999999a) >> 32;
152 *buf++ = (r - 10 * q) + '0'; /* 4 */
153 r = (q * (uint64_t)0x1999999a) >> 32;
154 *buf++ = (q - 10 * r) + '0'; /* 5 */
155 /* Now value is under 10000, can avoid 64-bit multiply */
156 q = (r * 0x199a) >> 16;
157 *buf++ = (r - 10 * q) + '0'; /* 6 */
158 r = (q * 0xcd) >> 11;
159 *buf++ = (q - 10 * r) + '0'; /* 7 */
160 q = (r * 0xcd) >> 11;
161 *buf++ = (r - 10 * q) + '0'; /* 8 */
162 *buf++ = q + '0'; /* 9 */
157 return buf; 163 return buf;
158} 164}
159/* Same with if's removed. Always emits five digits */ 165#endif
166
167/* Similar to above but do not pad with zeros.
168 * Code can be easily arranged to print 9 digits too, but our callers
169 * always call put_dec_full9() instead when the number has 9 decimal digits.
170 */
160static noinline_for_stack 171static noinline_for_stack
161char *put_dec_full(char *buf, unsigned q) 172char *put_dec_trunc8(char *buf, unsigned r)
162{ 173{
163 /* BTW, if q is in [0,9999], 8-bit ints will be enough, */ 174 unsigned q;
164 /* but anyway, gcc produces better code with full-sized ints */ 175
165 unsigned d3, d2, d1, d0; 176 /* Copy of previous function's body with added early returns */
166 d1 = (q>>4) & 0xf; 177 q = (r * (uint64_t)0x1999999a) >> 32;
167 d2 = (q>>8) & 0xf; 178 *buf++ = (r - 10 * q) + '0'; /* 2 */
168 d3 = (q>>12); 179 if (q == 0)
180 return buf;
181 r = (q * (uint64_t)0x1999999a) >> 32;
182 *buf++ = (q - 10 * r) + '0'; /* 3 */
183 if (r == 0)
184 return buf;
185 q = (r * (uint64_t)0x1999999a) >> 32;
186 *buf++ = (r - 10 * q) + '0'; /* 4 */
187 if (q == 0)
188 return buf;
189 r = (q * (uint64_t)0x1999999a) >> 32;
190 *buf++ = (q - 10 * r) + '0'; /* 5 */
191 if (r == 0)
192 return buf;
193 q = (r * 0x199a) >> 16;
194 *buf++ = (r - 10 * q) + '0'; /* 6 */
195 if (q == 0)
196 return buf;
197 r = (q * 0xcd) >> 11;
198 *buf++ = (q - 10 * r) + '0'; /* 7 */
199 if (r == 0)
200 return buf;
201 q = (r * 0xcd) >> 11;
202 *buf++ = (r - 10 * q) + '0'; /* 8 */
203 if (q == 0)
204 return buf;
205 *buf++ = q + '0'; /* 9 */
206 return buf;
207}
169 208
170 /* 209/* There are two algorithms to print larger numbers.
171 * Possible ways to approx. divide by 10 210 * One is generic: divide by 1000000000 and repeatedly print
172 * gcc -O2 replaces multiply with shifts and adds 211 * groups of (up to) 9 digits. It's conceptually simple,
173 * (x * 0xcd) >> 11: 11001101 - shorter code than * 0x67 (on i386) 212 * but requires a (unsigned long long) / 1000000000 division.
174 * (x * 0x67) >> 10: 1100111 213 *
175 * (x * 0x34) >> 9: 110100 - same 214 * Second algorithm splits 64-bit unsigned long long into 16-bit chunks,
176 * (x * 0x1a) >> 8: 11010 - same 215 * manipulates them cleverly and generates groups of 4 decimal digits.
177 * (x * 0x0d) >> 7: 1101 - same, shortest code (on i386) 216 * It so happens that it does NOT require long long division.
178 */ 217 *
179 d0 = 6*(d3 + d2 + d1) + (q & 0xf); 218 * If long is > 32 bits, division of 64-bit values is relatively easy,
180 q = (d0 * 0xcd) >> 11; 219 * and we will use the first algorithm.
181 d0 = d0 - 10*q; 220 * If long long is > 64 bits (strange architecture with VERY large long long),
182 *buf++ = d0 + '0'; 221 * second algorithm can't be used, and we again use the first one.
183 d1 = q + 9*d3 + 5*d2 + d1; 222 *
184 q = (d1 * 0xcd) >> 11; 223 * Else (if long is 32 bits and long long is 64 bits) we use second one.
185 d1 = d1 - 10*q; 224 */
186 *buf++ = d1 + '0';
187
188 d2 = q + 2*d2;
189 q = (d2 * 0xd) >> 7;
190 d2 = d2 - 10*q;
191 *buf++ = d2 + '0';
192
193 d3 = q + 4*d3;
194 q = (d3 * 0xcd) >> 11; /* - shorter code */
195 /* q = (d3 * 0x67) >> 10; - would also work */
196 d3 = d3 - 10*q;
197 *buf++ = d3 + '0';
198 *buf++ = q + '0';
199 225
200 return buf; 226#if BITS_PER_LONG != 32 || BITS_PER_LONG_LONG != 64
227
228/* First algorithm: generic */
229
230static
231char *put_dec(char *buf, unsigned long long n)
232{
233 if (n >= 100*1000*1000) {
234 while (n >= 1000*1000*1000)
235 buf = put_dec_full9(buf, do_div(n, 1000*1000*1000));
236 if (n >= 100*1000*1000)
237 return put_dec_full9(buf, n);
238 }
239 return put_dec_trunc8(buf, n);
201} 240}
202/* No inlining helps gcc to use registers better */ 241
242#else
243
244/* Second algorithm: valid only for 64-bit long longs */
245
203static noinline_for_stack 246static noinline_for_stack
204char *put_dec(char *buf, unsigned long long num) 247char *put_dec_full4(char *buf, unsigned q)
205{ 248{
206 while (1) { 249 unsigned r;
207 unsigned rem; 250 r = (q * 0xcccd) >> 19;
208 if (num < 100000) 251 *buf++ = (q - 10 * r) + '0';
209 return put_dec_trunc(buf, num); 252 q = (r * 0x199a) >> 16;
210 rem = do_div(num, 100000); 253 *buf++ = (r - 10 * q) + '0';
211 buf = put_dec_full(buf, rem); 254 r = (q * 0xcd) >> 11;
212 } 255 *buf++ = (q - 10 * r) + '0';
256 *buf++ = r + '0';
257 return buf;
213} 258}
214 259
260/* Based on code by Douglas W. Jones found at
261 * <http://www.cs.uiowa.edu/~jones/bcd/decimal.html#sixtyfour>
262 * (with permission from the author).
263 * Performs no 64-bit division and hence should be fast on 32-bit machines.
264 */
265static
266char *put_dec(char *buf, unsigned long long n)
267{
268 uint32_t d3, d2, d1, q, h;
269
270 if (n < 100*1000*1000)
271 return put_dec_trunc8(buf, n);
272
273 d1 = ((uint32_t)n >> 16); /* implicit "& 0xffff" */
274 h = (n >> 32);
275 d2 = (h ) & 0xffff;
276 d3 = (h >> 16); /* implicit "& 0xffff" */
277
278 q = 656 * d3 + 7296 * d2 + 5536 * d1 + ((uint32_t)n & 0xffff);
279
280 buf = put_dec_full4(buf, q % 10000);
281 q = q / 10000;
282
283 d1 = q + 7671 * d3 + 9496 * d2 + 6 * d1;
284 buf = put_dec_full4(buf, d1 % 10000);
285 q = d1 / 10000;
286
287 d2 = q + 4749 * d3 + 42 * d2;
288 buf = put_dec_full4(buf, d2 % 10000);
289 q = d2 / 10000;
290
291 d3 = q + 281 * d3;
292 if (!d3)
293 goto done;
294 buf = put_dec_full4(buf, d3 % 10000);
295 q = d3 / 10000;
296 if (!q)
297 goto done;
298 buf = put_dec_full4(buf, q);
299 done:
300 while (buf[-1] == '0')
301 --buf;
302
303 return buf;
304}
305
306#endif
307
215/* 308/*
216 * Convert passed number to decimal string. 309 * Convert passed number to decimal string.
217 * Returns the length of string. On buffer overflow, returns 0. 310 * Returns the length of string. On buffer overflow, returns 0.
@@ -220,16 +313,22 @@ char *put_dec(char *buf, unsigned long long num)
220 */ 313 */
221int num_to_str(char *buf, int size, unsigned long long num) 314int num_to_str(char *buf, int size, unsigned long long num)
222{ 315{
223 char tmp[21]; /* Enough for 2^64 in decimal */ 316 char tmp[sizeof(num) * 3];
224 int idx, len; 317 int idx, len;
225 318
226 len = put_dec(tmp, num) - tmp; 319 /* put_dec() may work incorrectly for num = 0 (generate "", not "0") */
320 if (num <= 9) {
321 tmp[0] = '0' + num;
322 len = 1;
323 } else {
324 len = put_dec(tmp, num) - tmp;
325 }
227 326
228 if (len > size) 327 if (len > size)
229 return 0; 328 return 0;
230 for (idx = 0; idx < len; ++idx) 329 for (idx = 0; idx < len; ++idx)
231 buf[idx] = tmp[len - idx - 1]; 330 buf[idx] = tmp[len - idx - 1];
232 return len; 331 return len;
233} 332}
234 333
235#define ZEROPAD 1 /* pad with zero */ 334#define ZEROPAD 1 /* pad with zero */
@@ -284,6 +383,7 @@ char *number(char *buf, char *end, unsigned long long num,
284 char locase; 383 char locase;
285 int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10); 384 int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
286 int i; 385 int i;
386 bool is_zero = num == 0LL;
287 387
288 /* locase = 0 or 0x20. ORing digits or letters with 'locase' 388 /* locase = 0 or 0x20. ORing digits or letters with 'locase'
289 * produces same digits or (maybe lowercased) letters */ 389 * produces same digits or (maybe lowercased) letters */
@@ -305,15 +405,16 @@ char *number(char *buf, char *end, unsigned long long num,
305 } 405 }
306 } 406 }
307 if (need_pfx) { 407 if (need_pfx) {
308 spec.field_width--;
309 if (spec.base == 16) 408 if (spec.base == 16)
409 spec.field_width -= 2;
410 else if (!is_zero)
310 spec.field_width--; 411 spec.field_width--;
311 } 412 }
312 413
313 /* generate full string in tmp[], in reverse order */ 414 /* generate full string in tmp[], in reverse order */
314 i = 0; 415 i = 0;
315 if (num == 0) 416 if (num < spec.base)
316 tmp[i++] = '0'; 417 tmp[i++] = digits[num] | locase;
317 /* Generic code, for any base: 418 /* Generic code, for any base:
318 else do { 419 else do {
319 tmp[i++] = (digits[do_div(num,base)] | locase); 420 tmp[i++] = (digits[do_div(num,base)] | locase);
@@ -353,9 +454,11 @@ char *number(char *buf, char *end, unsigned long long num,
353 } 454 }
354 /* "0x" / "0" prefix */ 455 /* "0x" / "0" prefix */
355 if (need_pfx) { 456 if (need_pfx) {
356 if (buf < end) 457 if (spec.base == 16 || !is_zero) {
357 *buf = '0'; 458 if (buf < end)
358 ++buf; 459 *buf = '0';
460 ++buf;
461 }
359 if (spec.base == 16) { 462 if (spec.base == 16) {
360 if (buf < end) 463 if (buf < end)
361 *buf = ('X' | locase); 464 *buf = ('X' | locase);
@@ -436,7 +539,7 @@ char *symbol_string(char *buf, char *end, void *ptr,
436 else if (ext != 'f' && ext != 's') 539 else if (ext != 'f' && ext != 's')
437 sprint_symbol(sym, value); 540 sprint_symbol(sym, value);
438 else 541 else
439 kallsyms_lookup(value, NULL, NULL, NULL, sym); 542 sprint_symbol_no_offset(sym, value);
440 543
441 return string(buf, end, sym, spec); 544 return string(buf, end, sym, spec);
442#else 545#else
@@ -552,6 +655,50 @@ char *resource_string(char *buf, char *end, struct resource *res,
552} 655}
553 656
554static noinline_for_stack 657static noinline_for_stack
658char *hex_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
659 const char *fmt)
660{
661 int i, len = 1; /* if we pass '%ph[CDN]', field witdh remains
662 negative value, fallback to the default */
663 char separator;
664
665 if (spec.field_width == 0)
666 /* nothing to print */
667 return buf;
668
669 if (ZERO_OR_NULL_PTR(addr))
670 /* NULL pointer */
671 return string(buf, end, NULL, spec);
672
673 switch (fmt[1]) {
674 case 'C':
675 separator = ':';
676 break;
677 case 'D':
678 separator = '-';
679 break;
680 case 'N':
681 separator = 0;
682 break;
683 default:
684 separator = ' ';
685 break;
686 }
687
688 if (spec.field_width > 0)
689 len = min_t(int, spec.field_width, 64);
690
691 for (i = 0; i < len && buf < end - 1; i++) {
692 buf = hex_byte_pack(buf, addr[i]);
693
694 if (buf < end && separator && i != len - 1)
695 *buf++ = separator;
696 }
697
698 return buf;
699}
700
701static noinline_for_stack
555char *mac_address_string(char *buf, char *end, u8 *addr, 702char *mac_address_string(char *buf, char *end, u8 *addr,
556 struct printf_spec spec, const char *fmt) 703 struct printf_spec spec, const char *fmt)
557{ 704{
@@ -559,15 +706,28 @@ char *mac_address_string(char *buf, char *end, u8 *addr,
559 char *p = mac_addr; 706 char *p = mac_addr;
560 int i; 707 int i;
561 char separator; 708 char separator;
709 bool reversed = false;
562 710
563 if (fmt[1] == 'F') { /* FDDI canonical format */ 711 switch (fmt[1]) {
712 case 'F':
564 separator = '-'; 713 separator = '-';
565 } else { 714 break;
715
716 case 'R':
717 reversed = true;
718 /* fall through */
719
720 default:
566 separator = ':'; 721 separator = ':';
722 break;
567 } 723 }
568 724
569 for (i = 0; i < 6; i++) { 725 for (i = 0; i < 6; i++) {
570 p = hex_byte_pack(p, addr[i]); 726 if (reversed)
727 p = hex_byte_pack(p, addr[5 - i]);
728 else
729 p = hex_byte_pack(p, addr[i]);
730
571 if (fmt[0] == 'M' && i != 5) 731 if (fmt[0] == 'M' && i != 5)
572 *p++ = separator; 732 *p++ = separator;
573 } 733 }
@@ -607,7 +767,7 @@ char *ip4_string(char *p, const u8 *addr, const char *fmt)
607 } 767 }
608 for (i = 0; i < 4; i++) { 768 for (i = 0; i < 4; i++) {
609 char temp[3]; /* hold each IP quad in reverse order */ 769 char temp[3]; /* hold each IP quad in reverse order */
610 int digits = put_dec_trunc(temp, addr[index]) - temp; 770 int digits = put_dec_trunc8(temp, addr[index]) - temp;
611 if (leading_zeros) { 771 if (leading_zeros) {
612 if (digits < 3) 772 if (digits < 3)
613 *p++ = '0'; 773 *p++ = '0';
@@ -830,6 +990,7 @@ int kptr_restrict __read_mostly;
830 * - 'm' For a 6-byte MAC address, it prints the hex address without colons 990 * - 'm' For a 6-byte MAC address, it prints the hex address without colons
831 * - 'MF' For a 6-byte MAC FDDI address, it prints the address 991 * - 'MF' For a 6-byte MAC FDDI address, it prints the address
832 * with a dash-separated hex notation 992 * with a dash-separated hex notation
993 * - '[mM]R For a 6-byte MAC address, Reverse order (Bluetooth)
833 * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way 994 * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way
834 * IPv4 uses dot-separated decimal without leading 0's (1.2.3.4) 995 * IPv4 uses dot-separated decimal without leading 0's (1.2.3.4)
835 * IPv6 uses colon separated network-order 16 bit hex with leading 0's 996 * IPv6 uses colon separated network-order 16 bit hex with leading 0's
@@ -857,6 +1018,13 @@ int kptr_restrict __read_mostly;
857 * correctness of the format string and va_list arguments. 1018 * correctness of the format string and va_list arguments.
858 * - 'K' For a kernel pointer that should be hidden from unprivileged users 1019 * - 'K' For a kernel pointer that should be hidden from unprivileged users
859 * - 'NF' For a netdev_features_t 1020 * - 'NF' For a netdev_features_t
1021 * - 'h[CDN]' For a variable-length buffer, it prints it as a hex string with
1022 * a certain separator (' ' by default):
1023 * C colon
1024 * D dash
1025 * N no separator
1026 * The maximum supported length is 64 bytes of the input. Consider
1027 * to use print_hex_dump() for the larger input.
860 * 1028 *
861 * Note: The difference between 'S' and 'F' is that on ia64 and ppc64 1029 * Note: The difference between 'S' and 'F' is that on ia64 and ppc64
862 * function pointers are really function descriptors, which contain a 1030 * function pointers are really function descriptors, which contain a
@@ -866,13 +1034,15 @@ static noinline_for_stack
866char *pointer(const char *fmt, char *buf, char *end, void *ptr, 1034char *pointer(const char *fmt, char *buf, char *end, void *ptr,
867 struct printf_spec spec) 1035 struct printf_spec spec)
868{ 1036{
1037 int default_width = 2 * sizeof(void *) + (spec.flags & SPECIAL ? 2 : 0);
1038
869 if (!ptr && *fmt != 'K') { 1039 if (!ptr && *fmt != 'K') {
870 /* 1040 /*
871 * Print (null) with the same width as a pointer so it makes 1041 * Print (null) with the same width as a pointer so it makes
872 * tabular output look nice. 1042 * tabular output look nice.
873 */ 1043 */
874 if (spec.field_width == -1) 1044 if (spec.field_width == -1)
875 spec.field_width = 2 * sizeof(void *); 1045 spec.field_width = default_width;
876 return string(buf, end, "(null)", spec); 1046 return string(buf, end, "(null)", spec);
877 } 1047 }
878 1048
@@ -888,9 +1058,12 @@ char *pointer(const char *fmt, char *buf, char *end, void *ptr,
888 case 'R': 1058 case 'R':
889 case 'r': 1059 case 'r':
890 return resource_string(buf, end, ptr, spec, fmt); 1060 return resource_string(buf, end, ptr, spec, fmt);
1061 case 'h':
1062 return hex_string(buf, end, ptr, spec, fmt);
891 case 'M': /* Colon separated: 00:01:02:03:04:05 */ 1063 case 'M': /* Colon separated: 00:01:02:03:04:05 */
892 case 'm': /* Contiguous: 000102030405 */ 1064 case 'm': /* Contiguous: 000102030405 */
893 /* [mM]F (FDDI, bit reversed) */ 1065 /* [mM]F (FDDI) */
1066 /* [mM]R (Reverse order; Bluetooth) */
894 return mac_address_string(buf, end, ptr, spec, fmt); 1067 return mac_address_string(buf, end, ptr, spec, fmt);
895 case 'I': /* Formatted IP supported 1068 case 'I': /* Formatted IP supported
896 * 4: 1.2.3.4 1069 * 4: 1.2.3.4
@@ -925,9 +1098,10 @@ char *pointer(const char *fmt, char *buf, char *end, void *ptr,
925 * %pK cannot be used in IRQ context because its test 1098 * %pK cannot be used in IRQ context because its test
926 * for CAP_SYSLOG would be meaningless. 1099 * for CAP_SYSLOG would be meaningless.
927 */ 1100 */
928 if (in_irq() || in_serving_softirq() || in_nmi()) { 1101 if (kptr_restrict && (in_irq() || in_serving_softirq() ||
1102 in_nmi())) {
929 if (spec.field_width == -1) 1103 if (spec.field_width == -1)
930 spec.field_width = 2 * sizeof(void *); 1104 spec.field_width = default_width;
931 return string(buf, end, "pK-error", spec); 1105 return string(buf, end, "pK-error", spec);
932 } 1106 }
933 if (!((kptr_restrict == 0) || 1107 if (!((kptr_restrict == 0) ||
@@ -944,7 +1118,7 @@ char *pointer(const char *fmt, char *buf, char *end, void *ptr,
944 } 1118 }
945 spec.flags |= SMALL; 1119 spec.flags |= SMALL;
946 if (spec.field_width == -1) { 1120 if (spec.field_width == -1) {
947 spec.field_width = 2 * sizeof(void *); 1121 spec.field_width = default_width;
948 spec.flags |= ZEROPAD; 1122 spec.flags |= ZEROPAD;
949 } 1123 }
950 spec.base = 16; 1124 spec.base = 16;
@@ -1175,8 +1349,12 @@ qualifier:
1175 * %pI6c print an IPv6 address as specified by RFC 5952 1349 * %pI6c print an IPv6 address as specified by RFC 5952
1176 * %pU[bBlL] print a UUID/GUID in big or little endian using lower or upper 1350 * %pU[bBlL] print a UUID/GUID in big or little endian using lower or upper
1177 * case. 1351 * case.
1352 * %*ph[CDN] a variable-length hex string with a separator (supports up to 64
1353 * bytes of the input)
1178 * %n is ignored 1354 * %n is ignored
1179 * 1355 *
1356 * ** Please update Documentation/printk-formats.txt when making changes **
1357 *
1180 * The return value is the number of characters which would 1358 * The return value is the number of characters which would
1181 * be generated for the given input, excluding the trailing 1359 * be generated for the given input, excluding the trailing
1182 * '\0', as per ISO C99. If you want to have the exact 1360 * '\0', as per ISO C99. If you want to have the exact