xref: /linux-6.15/drivers/dma/dmatest.c (revision 7f2b7226)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * DMA Engine test module
4  *
5  * Copyright (C) 2007 Atmel Corporation
6  * Copyright (C) 2013 Intel Corporation
7  */
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9 
10 #include <linux/delay.h>
11 #include <linux/dma-mapping.h>
12 #include <linux/dmaengine.h>
13 #include <linux/freezer.h>
14 #include <linux/init.h>
15 #include <linux/kthread.h>
16 #include <linux/sched/task.h>
17 #include <linux/module.h>
18 #include <linux/moduleparam.h>
19 #include <linux/random.h>
20 #include <linux/slab.h>
21 #include <linux/wait.h>
22 
23 static unsigned int test_buf_size = 16384;
24 module_param(test_buf_size, uint, S_IRUGO | S_IWUSR);
25 MODULE_PARM_DESC(test_buf_size, "Size of the memcpy test buffer");
26 
27 static char test_device[32];
28 module_param_string(device, test_device, sizeof(test_device),
29 		S_IRUGO | S_IWUSR);
30 MODULE_PARM_DESC(device, "Bus ID of the DMA Engine to test (default: any)");
31 
32 static unsigned int threads_per_chan = 1;
33 module_param(threads_per_chan, uint, S_IRUGO | S_IWUSR);
34 MODULE_PARM_DESC(threads_per_chan,
35 		"Number of threads to start per channel (default: 1)");
36 
37 static unsigned int max_channels;
38 module_param(max_channels, uint, S_IRUGO | S_IWUSR);
39 MODULE_PARM_DESC(max_channels,
40 		"Maximum number of channels to use (default: all)");
41 
42 static unsigned int iterations;
43 module_param(iterations, uint, S_IRUGO | S_IWUSR);
44 MODULE_PARM_DESC(iterations,
45 		"Iterations before stopping test (default: infinite)");
46 
47 static unsigned int dmatest;
48 module_param(dmatest, uint, S_IRUGO | S_IWUSR);
49 MODULE_PARM_DESC(dmatest,
50 		"dmatest 0-memcpy 1-memset (default: 0)");
51 
52 static unsigned int xor_sources = 3;
53 module_param(xor_sources, uint, S_IRUGO | S_IWUSR);
54 MODULE_PARM_DESC(xor_sources,
55 		"Number of xor source buffers (default: 3)");
56 
57 static unsigned int pq_sources = 3;
58 module_param(pq_sources, uint, S_IRUGO | S_IWUSR);
59 MODULE_PARM_DESC(pq_sources,
60 		"Number of p+q source buffers (default: 3)");
61 
62 static int timeout = 3000;
63 module_param(timeout, int, S_IRUGO | S_IWUSR);
64 MODULE_PARM_DESC(timeout, "Transfer Timeout in msec (default: 3000), "
65 		 "Pass -1 for infinite timeout");
66 
67 static bool noverify;
68 module_param(noverify, bool, S_IRUGO | S_IWUSR);
69 MODULE_PARM_DESC(noverify, "Disable data verification (default: verify)");
70 
71 static bool norandom;
72 module_param(norandom, bool, 0644);
73 MODULE_PARM_DESC(norandom, "Disable random offset setup (default: random)");
74 
75 static bool verbose;
76 module_param(verbose, bool, S_IRUGO | S_IWUSR);
77 MODULE_PARM_DESC(verbose, "Enable \"success\" result messages (default: off)");
78 
79 static int alignment = -1;
80 module_param(alignment, int, 0644);
81 MODULE_PARM_DESC(alignment, "Custom data address alignment taken as 2^(alignment) (default: not used (-1))");
82 
83 static unsigned int transfer_size;
84 module_param(transfer_size, uint, 0644);
85 MODULE_PARM_DESC(transfer_size, "Optional custom transfer size in bytes (default: not used (0))");
86 
87 static bool polled;
88 module_param(polled, bool, S_IRUGO | S_IWUSR);
89 MODULE_PARM_DESC(polled, "Use polling for completion instead of interrupts");
90 
91 /**
92  * struct dmatest_params - test parameters.
93  * @buf_size:		size of the memcpy test buffer
94  * @channel:		bus ID of the channel to test
95  * @device:		bus ID of the DMA Engine to test
96  * @threads_per_chan:	number of threads to start per channel
97  * @max_channels:	maximum number of channels to use
98  * @iterations:		iterations before stopping test
99  * @xor_sources:	number of xor source buffers
100  * @pq_sources:		number of p+q source buffers
101  * @timeout:		transfer timeout in msec, -1 for infinite timeout
102  * @noverify:		disable data verification
103  * @norandom:		disable random offset setup
104  * @alignment:		custom data address alignment taken as 2^alignment
105  * @transfer_size:	custom transfer size in bytes
106  * @polled:		use polling for completion instead of interrupts
107  */
108 struct dmatest_params {
109 	unsigned int	buf_size;
110 	char		channel[20];
111 	char		device[32];
112 	unsigned int	threads_per_chan;
113 	unsigned int	max_channels;
114 	unsigned int	iterations;
115 	unsigned int	xor_sources;
116 	unsigned int	pq_sources;
117 	int		timeout;
118 	bool		noverify;
119 	bool		norandom;
120 	int		alignment;
121 	unsigned int	transfer_size;
122 	bool		polled;
123 };
124 
125 /**
126  * struct dmatest_info - test information.
127  * @params:		test parameters
128  * @lock:		access protection to the fields of this structure
129  */
130 static struct dmatest_info {
131 	/* Test parameters */
132 	struct dmatest_params	params;
133 
134 	/* Internal state */
135 	struct list_head	channels;
136 	unsigned int		nr_channels;
137 	struct mutex		lock;
138 	bool			did_init;
139 } test_info = {
140 	.channels = LIST_HEAD_INIT(test_info.channels),
141 	.lock = __MUTEX_INITIALIZER(test_info.lock),
142 };
143 
144 static int dmatest_run_set(const char *val, const struct kernel_param *kp);
145 static int dmatest_run_get(char *val, const struct kernel_param *kp);
146 static const struct kernel_param_ops run_ops = {
147 	.set = dmatest_run_set,
148 	.get = dmatest_run_get,
149 };
150 static bool dmatest_run;
151 module_param_cb(run, &run_ops, &dmatest_run, S_IRUGO | S_IWUSR);
152 MODULE_PARM_DESC(run, "Run the test (default: false)");
153 
154 static int dmatest_chan_set(const char *val, const struct kernel_param *kp);
155 static int dmatest_chan_get(char *val, const struct kernel_param *kp);
156 static const struct kernel_param_ops multi_chan_ops = {
157 	.set = dmatest_chan_set,
158 	.get = dmatest_chan_get,
159 };
160 
161 static char test_channel[20];
162 static struct kparam_string newchan_kps = {
163 	.string = test_channel,
164 	.maxlen = 20,
165 };
166 module_param_cb(channel, &multi_chan_ops, &newchan_kps, 0644);
167 MODULE_PARM_DESC(channel, "Bus ID of the channel to test (default: any)");
168 
169 static int dmatest_test_list_get(char *val, const struct kernel_param *kp);
170 static const struct kernel_param_ops test_list_ops = {
171 	.get = dmatest_test_list_get,
172 };
173 module_param_cb(test_list, &test_list_ops, NULL, 0444);
174 MODULE_PARM_DESC(test_list, "Print current test list");
175 
176 /* Maximum amount of mismatched bytes in buffer to print */
177 #define MAX_ERROR_COUNT		32
178 
179 /*
180  * Initialization patterns. All bytes in the source buffer has bit 7
181  * set, all bytes in the destination buffer has bit 7 cleared.
182  *
183  * Bit 6 is set for all bytes which are to be copied by the DMA
184  * engine. Bit 5 is set for all bytes which are to be overwritten by
185  * the DMA engine.
186  *
187  * The remaining bits are the inverse of a counter which increments by
188  * one for each byte address.
189  */
190 #define PATTERN_SRC		0x80
191 #define PATTERN_DST		0x00
192 #define PATTERN_COPY		0x40
193 #define PATTERN_OVERWRITE	0x20
194 #define PATTERN_COUNT_MASK	0x1f
195 #define PATTERN_MEMSET_IDX	0x01
196 
197 /* Fixed point arithmetic ops */
198 #define FIXPT_SHIFT		8
199 #define FIXPNT_MASK		0xFF
200 #define FIXPT_TO_INT(a)	((a) >> FIXPT_SHIFT)
201 #define INT_TO_FIXPT(a)	((a) << FIXPT_SHIFT)
202 #define FIXPT_GET_FRAC(a)	((((a) & FIXPNT_MASK) * 100) >> FIXPT_SHIFT)
203 
204 /* poor man's completion - we want to use wait_event_freezable() on it */
205 struct dmatest_done {
206 	bool			done;
207 	wait_queue_head_t	*wait;
208 };
209 
210 struct dmatest_data {
211 	u8		**raw;
212 	u8		**aligned;
213 	unsigned int	cnt;
214 	unsigned int	off;
215 };
216 
217 struct dmatest_thread {
218 	struct list_head	node;
219 	struct dmatest_info	*info;
220 	struct task_struct	*task;
221 	struct dma_chan		*chan;
222 	struct dmatest_data	src;
223 	struct dmatest_data	dst;
224 	enum dma_transaction_type type;
225 	wait_queue_head_t done_wait;
226 	struct dmatest_done test_done;
227 	bool			done;
228 	bool			pending;
229 };
230 
231 struct dmatest_chan {
232 	struct list_head	node;
233 	struct dma_chan		*chan;
234 	struct list_head	threads;
235 };
236 
237 static DECLARE_WAIT_QUEUE_HEAD(thread_wait);
238 static bool wait;
239 
240 static bool is_threaded_test_run(struct dmatest_info *info)
241 {
242 	struct dmatest_chan *dtc;
243 
244 	list_for_each_entry(dtc, &info->channels, node) {
245 		struct dmatest_thread *thread;
246 
247 		list_for_each_entry(thread, &dtc->threads, node) {
248 			if (!thread->done)
249 				return true;
250 		}
251 	}
252 
253 	return false;
254 }
255 
256 static bool is_threaded_test_pending(struct dmatest_info *info)
257 {
258 	struct dmatest_chan *dtc;
259 
260 	list_for_each_entry(dtc, &info->channels, node) {
261 		struct dmatest_thread *thread;
262 
263 		list_for_each_entry(thread, &dtc->threads, node) {
264 			if (thread->pending)
265 				return true;
266 		}
267 	}
268 
269 	return false;
270 }
271 
272 static int dmatest_wait_get(char *val, const struct kernel_param *kp)
273 {
274 	struct dmatest_info *info = &test_info;
275 	struct dmatest_params *params = &info->params;
276 
277 	if (params->iterations)
278 		wait_event(thread_wait, !is_threaded_test_run(info));
279 	wait = true;
280 	return param_get_bool(val, kp);
281 }
282 
283 static const struct kernel_param_ops wait_ops = {
284 	.get = dmatest_wait_get,
285 	.set = param_set_bool,
286 };
287 module_param_cb(wait, &wait_ops, &wait, S_IRUGO);
288 MODULE_PARM_DESC(wait, "Wait for tests to complete (default: false)");
289 
290 static bool dmatest_match_channel(struct dmatest_params *params,
291 		struct dma_chan *chan)
292 {
293 	if (params->channel[0] == '\0')
294 		return true;
295 	return strcmp(dma_chan_name(chan), params->channel) == 0;
296 }
297 
298 static bool dmatest_match_device(struct dmatest_params *params,
299 		struct dma_device *device)
300 {
301 	if (params->device[0] == '\0')
302 		return true;
303 	return strcmp(dev_name(device->dev), params->device) == 0;
304 }
305 
306 static unsigned long dmatest_random(void)
307 {
308 	unsigned long buf;
309 
310 	prandom_bytes(&buf, sizeof(buf));
311 	return buf;
312 }
313 
314 static inline u8 gen_inv_idx(u8 index, bool is_memset)
315 {
316 	u8 val = is_memset ? PATTERN_MEMSET_IDX : index;
317 
318 	return ~val & PATTERN_COUNT_MASK;
319 }
320 
321 static inline u8 gen_src_value(u8 index, bool is_memset)
322 {
323 	return PATTERN_SRC | gen_inv_idx(index, is_memset);
324 }
325 
326 static inline u8 gen_dst_value(u8 index, bool is_memset)
327 {
328 	return PATTERN_DST | gen_inv_idx(index, is_memset);
329 }
330 
331 static void dmatest_init_srcs(u8 **bufs, unsigned int start, unsigned int len,
332 		unsigned int buf_size, bool is_memset)
333 {
334 	unsigned int i;
335 	u8 *buf;
336 
337 	for (; (buf = *bufs); bufs++) {
338 		for (i = 0; i < start; i++)
339 			buf[i] = gen_src_value(i, is_memset);
340 		for ( ; i < start + len; i++)
341 			buf[i] = gen_src_value(i, is_memset) | PATTERN_COPY;
342 		for ( ; i < buf_size; i++)
343 			buf[i] = gen_src_value(i, is_memset);
344 		buf++;
345 	}
346 }
347 
348 static void dmatest_init_dsts(u8 **bufs, unsigned int start, unsigned int len,
349 		unsigned int buf_size, bool is_memset)
350 {
351 	unsigned int i;
352 	u8 *buf;
353 
354 	for (; (buf = *bufs); bufs++) {
355 		for (i = 0; i < start; i++)
356 			buf[i] = gen_dst_value(i, is_memset);
357 		for ( ; i < start + len; i++)
358 			buf[i] = gen_dst_value(i, is_memset) |
359 						PATTERN_OVERWRITE;
360 		for ( ; i < buf_size; i++)
361 			buf[i] = gen_dst_value(i, is_memset);
362 	}
363 }
364 
365 static void dmatest_mismatch(u8 actual, u8 pattern, unsigned int index,
366 		unsigned int counter, bool is_srcbuf, bool is_memset)
367 {
368 	u8		diff = actual ^ pattern;
369 	u8		expected = pattern | gen_inv_idx(counter, is_memset);
370 	const char	*thread_name = current->comm;
371 
372 	if (is_srcbuf)
373 		pr_warn("%s: srcbuf[0x%x] overwritten! Expected %02x, got %02x\n",
374 			thread_name, index, expected, actual);
375 	else if ((pattern & PATTERN_COPY)
376 			&& (diff & (PATTERN_COPY | PATTERN_OVERWRITE)))
377 		pr_warn("%s: dstbuf[0x%x] not copied! Expected %02x, got %02x\n",
378 			thread_name, index, expected, actual);
379 	else if (diff & PATTERN_SRC)
380 		pr_warn("%s: dstbuf[0x%x] was copied! Expected %02x, got %02x\n",
381 			thread_name, index, expected, actual);
382 	else
383 		pr_warn("%s: dstbuf[0x%x] mismatch! Expected %02x, got %02x\n",
384 			thread_name, index, expected, actual);
385 }
386 
387 static unsigned int dmatest_verify(u8 **bufs, unsigned int start,
388 		unsigned int end, unsigned int counter, u8 pattern,
389 		bool is_srcbuf, bool is_memset)
390 {
391 	unsigned int i;
392 	unsigned int error_count = 0;
393 	u8 actual;
394 	u8 expected;
395 	u8 *buf;
396 	unsigned int counter_orig = counter;
397 
398 	for (; (buf = *bufs); bufs++) {
399 		counter = counter_orig;
400 		for (i = start; i < end; i++) {
401 			actual = buf[i];
402 			expected = pattern | gen_inv_idx(counter, is_memset);
403 			if (actual != expected) {
404 				if (error_count < MAX_ERROR_COUNT)
405 					dmatest_mismatch(actual, pattern, i,
406 							 counter, is_srcbuf,
407 							 is_memset);
408 				error_count++;
409 			}
410 			counter++;
411 		}
412 	}
413 
414 	if (error_count > MAX_ERROR_COUNT)
415 		pr_warn("%s: %u errors suppressed\n",
416 			current->comm, error_count - MAX_ERROR_COUNT);
417 
418 	return error_count;
419 }
420 
421 
422 static void dmatest_callback(void *arg)
423 {
424 	struct dmatest_done *done = arg;
425 	struct dmatest_thread *thread =
426 		container_of(done, struct dmatest_thread, test_done);
427 	if (!thread->done) {
428 		done->done = true;
429 		wake_up_all(done->wait);
430 	} else {
431 		/*
432 		 * If thread->done, it means that this callback occurred
433 		 * after the parent thread has cleaned up. This can
434 		 * happen in the case that driver doesn't implement
435 		 * the terminate_all() functionality and a dma operation
436 		 * did not occur within the timeout period
437 		 */
438 		WARN(1, "dmatest: Kernel memory may be corrupted!!\n");
439 	}
440 }
441 
442 static unsigned int min_odd(unsigned int x, unsigned int y)
443 {
444 	unsigned int val = min(x, y);
445 
446 	return val % 2 ? val : val - 1;
447 }
448 
449 static void result(const char *err, unsigned int n, unsigned int src_off,
450 		   unsigned int dst_off, unsigned int len, unsigned long data)
451 {
452 	pr_info("%s: result #%u: '%s' with src_off=0x%x dst_off=0x%x len=0x%x (%lu)\n",
453 		current->comm, n, err, src_off, dst_off, len, data);
454 }
455 
456 static void dbg_result(const char *err, unsigned int n, unsigned int src_off,
457 		       unsigned int dst_off, unsigned int len,
458 		       unsigned long data)
459 {
460 	pr_debug("%s: result #%u: '%s' with src_off=0x%x dst_off=0x%x len=0x%x (%lu)\n",
461 		 current->comm, n, err, src_off, dst_off, len, data);
462 }
463 
464 #define verbose_result(err, n, src_off, dst_off, len, data) ({	\
465 	if (verbose)						\
466 		result(err, n, src_off, dst_off, len, data);	\
467 	else							\
468 		dbg_result(err, n, src_off, dst_off, len, data);\
469 })
470 
471 static unsigned long long dmatest_persec(s64 runtime, unsigned int val)
472 {
473 	unsigned long long per_sec = 1000000;
474 
475 	if (runtime <= 0)
476 		return 0;
477 
478 	/* drop precision until runtime is 32-bits */
479 	while (runtime > UINT_MAX) {
480 		runtime >>= 1;
481 		per_sec <<= 1;
482 	}
483 
484 	per_sec *= val;
485 	per_sec = INT_TO_FIXPT(per_sec);
486 	do_div(per_sec, runtime);
487 
488 	return per_sec;
489 }
490 
491 static unsigned long long dmatest_KBs(s64 runtime, unsigned long long len)
492 {
493 	return FIXPT_TO_INT(dmatest_persec(runtime, len >> 10));
494 }
495 
496 static void __dmatest_free_test_data(struct dmatest_data *d, unsigned int cnt)
497 {
498 	unsigned int i;
499 
500 	for (i = 0; i < cnt; i++)
501 		kfree(d->raw[i]);
502 
503 	kfree(d->aligned);
504 	kfree(d->raw);
505 }
506 
507 static void dmatest_free_test_data(struct dmatest_data *d)
508 {
509 	__dmatest_free_test_data(d, d->cnt);
510 }
511 
512 static int dmatest_alloc_test_data(struct dmatest_data *d,
513 		unsigned int buf_size, u8 align)
514 {
515 	unsigned int i = 0;
516 
517 	d->raw = kcalloc(d->cnt + 1, sizeof(u8 *), GFP_KERNEL);
518 	if (!d->raw)
519 		return -ENOMEM;
520 
521 	d->aligned = kcalloc(d->cnt + 1, sizeof(u8 *), GFP_KERNEL);
522 	if (!d->aligned)
523 		goto err;
524 
525 	for (i = 0; i < d->cnt; i++) {
526 		d->raw[i] = kmalloc(buf_size + align, GFP_KERNEL);
527 		if (!d->raw[i])
528 			goto err;
529 
530 		/* align to alignment restriction */
531 		if (align)
532 			d->aligned[i] = PTR_ALIGN(d->raw[i], align);
533 		else
534 			d->aligned[i] = d->raw[i];
535 	}
536 
537 	return 0;
538 err:
539 	__dmatest_free_test_data(d, i);
540 	return -ENOMEM;
541 }
542 
543 /*
544  * This function repeatedly tests DMA transfers of various lengths and
545  * offsets for a given operation type until it is told to exit by
546  * kthread_stop(). There may be multiple threads running this function
547  * in parallel for a single channel, and there may be multiple channels
548  * being tested in parallel.
549  *
550  * Before each test, the source and destination buffer is initialized
551  * with a known pattern. This pattern is different depending on
552  * whether it's in an area which is supposed to be copied or
553  * overwritten, and different in the source and destination buffers.
554  * So if the DMA engine doesn't copy exactly what we tell it to copy,
555  * we'll notice.
556  */
557 static int dmatest_func(void *data)
558 {
559 	struct dmatest_thread	*thread = data;
560 	struct dmatest_done	*done = &thread->test_done;
561 	struct dmatest_info	*info;
562 	struct dmatest_params	*params;
563 	struct dma_chan		*chan;
564 	struct dma_device	*dev;
565 	unsigned int		error_count;
566 	unsigned int		failed_tests = 0;
567 	unsigned int		total_tests = 0;
568 	dma_cookie_t		cookie;
569 	enum dma_status		status;
570 	enum dma_ctrl_flags 	flags;
571 	u8			*pq_coefs = NULL;
572 	int			ret;
573 	unsigned int 		buf_size;
574 	struct dmatest_data	*src;
575 	struct dmatest_data	*dst;
576 	int			i;
577 	ktime_t			ktime, start, diff;
578 	ktime_t			filltime = 0;
579 	ktime_t			comparetime = 0;
580 	s64			runtime = 0;
581 	unsigned long long	total_len = 0;
582 	unsigned long long	iops = 0;
583 	u8			align = 0;
584 	bool			is_memset = false;
585 	dma_addr_t		*srcs;
586 	dma_addr_t		*dma_pq;
587 
588 	set_freezable();
589 
590 	ret = -ENOMEM;
591 
592 	smp_rmb();
593 	thread->pending = false;
594 	info = thread->info;
595 	params = &info->params;
596 	chan = thread->chan;
597 	dev = chan->device;
598 	src = &thread->src;
599 	dst = &thread->dst;
600 	if (thread->type == DMA_MEMCPY) {
601 		align = params->alignment < 0 ? dev->copy_align :
602 						params->alignment;
603 		src->cnt = dst->cnt = 1;
604 	} else if (thread->type == DMA_MEMSET) {
605 		align = params->alignment < 0 ? dev->fill_align :
606 						params->alignment;
607 		src->cnt = dst->cnt = 1;
608 		is_memset = true;
609 	} else if (thread->type == DMA_XOR) {
610 		/* force odd to ensure dst = src */
611 		src->cnt = min_odd(params->xor_sources | 1, dev->max_xor);
612 		dst->cnt = 1;
613 		align = params->alignment < 0 ? dev->xor_align :
614 						params->alignment;
615 	} else if (thread->type == DMA_PQ) {
616 		/* force odd to ensure dst = src */
617 		src->cnt = min_odd(params->pq_sources | 1, dma_maxpq(dev, 0));
618 		dst->cnt = 2;
619 		align = params->alignment < 0 ? dev->pq_align :
620 						params->alignment;
621 
622 		pq_coefs = kmalloc(params->pq_sources + 1, GFP_KERNEL);
623 		if (!pq_coefs)
624 			goto err_thread_type;
625 
626 		for (i = 0; i < src->cnt; i++)
627 			pq_coefs[i] = 1;
628 	} else
629 		goto err_thread_type;
630 
631 	/* Check if buffer count fits into map count variable (u8) */
632 	if ((src->cnt + dst->cnt) >= 255) {
633 		pr_err("too many buffers (%d of 255 supported)\n",
634 		       src->cnt + dst->cnt);
635 		goto err_free_coefs;
636 	}
637 
638 	buf_size = params->buf_size;
639 	if (1 << align > buf_size) {
640 		pr_err("%u-byte buffer too small for %d-byte alignment\n",
641 		       buf_size, 1 << align);
642 		goto err_free_coefs;
643 	}
644 
645 	if (dmatest_alloc_test_data(src, buf_size, align) < 0)
646 		goto err_free_coefs;
647 
648 	if (dmatest_alloc_test_data(dst, buf_size, align) < 0)
649 		goto err_src;
650 
651 	set_user_nice(current, 10);
652 
653 	srcs = kcalloc(src->cnt, sizeof(dma_addr_t), GFP_KERNEL);
654 	if (!srcs)
655 		goto err_dst;
656 
657 	dma_pq = kcalloc(dst->cnt, sizeof(dma_addr_t), GFP_KERNEL);
658 	if (!dma_pq)
659 		goto err_srcs_array;
660 
661 	/*
662 	 * src and dst buffers are freed by ourselves below
663 	 */
664 	if (params->polled)
665 		flags = DMA_CTRL_ACK;
666 	else
667 		flags = DMA_CTRL_ACK | DMA_PREP_INTERRUPT;
668 
669 	ktime = ktime_get();
670 	while (!kthread_should_stop()
671 	       && !(params->iterations && total_tests >= params->iterations)) {
672 		struct dma_async_tx_descriptor *tx = NULL;
673 		struct dmaengine_unmap_data *um;
674 		dma_addr_t *dsts;
675 		unsigned int len;
676 
677 		total_tests++;
678 
679 		if (params->transfer_size) {
680 			if (params->transfer_size >= buf_size) {
681 				pr_err("%u-byte transfer size must be lower than %u-buffer size\n",
682 				       params->transfer_size, buf_size);
683 				break;
684 			}
685 			len = params->transfer_size;
686 		} else if (params->norandom) {
687 			len = buf_size;
688 		} else {
689 			len = dmatest_random() % buf_size + 1;
690 		}
691 
692 		/* Do not alter transfer size explicitly defined by user */
693 		if (!params->transfer_size) {
694 			len = (len >> align) << align;
695 			if (!len)
696 				len = 1 << align;
697 		}
698 		total_len += len;
699 
700 		if (params->norandom) {
701 			src->off = 0;
702 			dst->off = 0;
703 		} else {
704 			src->off = dmatest_random() % (buf_size - len + 1);
705 			dst->off = dmatest_random() % (buf_size - len + 1);
706 
707 			src->off = (src->off >> align) << align;
708 			dst->off = (dst->off >> align) << align;
709 		}
710 
711 		if (!params->noverify) {
712 			start = ktime_get();
713 			dmatest_init_srcs(src->aligned, src->off, len,
714 					  buf_size, is_memset);
715 			dmatest_init_dsts(dst->aligned, dst->off, len,
716 					  buf_size, is_memset);
717 
718 			diff = ktime_sub(ktime_get(), start);
719 			filltime = ktime_add(filltime, diff);
720 		}
721 
722 		um = dmaengine_get_unmap_data(dev->dev, src->cnt + dst->cnt,
723 					      GFP_KERNEL);
724 		if (!um) {
725 			failed_tests++;
726 			result("unmap data NULL", total_tests,
727 			       src->off, dst->off, len, ret);
728 			continue;
729 		}
730 
731 		um->len = buf_size;
732 		for (i = 0; i < src->cnt; i++) {
733 			void *buf = src->aligned[i];
734 			struct page *pg = virt_to_page(buf);
735 			unsigned long pg_off = offset_in_page(buf);
736 
737 			um->addr[i] = dma_map_page(dev->dev, pg, pg_off,
738 						   um->len, DMA_TO_DEVICE);
739 			srcs[i] = um->addr[i] + src->off;
740 			ret = dma_mapping_error(dev->dev, um->addr[i]);
741 			if (ret) {
742 				result("src mapping error", total_tests,
743 				       src->off, dst->off, len, ret);
744 				goto error_unmap_continue;
745 			}
746 			um->to_cnt++;
747 		}
748 		/* map with DMA_BIDIRECTIONAL to force writeback/invalidate */
749 		dsts = &um->addr[src->cnt];
750 		for (i = 0; i < dst->cnt; i++) {
751 			void *buf = dst->aligned[i];
752 			struct page *pg = virt_to_page(buf);
753 			unsigned long pg_off = offset_in_page(buf);
754 
755 			dsts[i] = dma_map_page(dev->dev, pg, pg_off, um->len,
756 					       DMA_BIDIRECTIONAL);
757 			ret = dma_mapping_error(dev->dev, dsts[i]);
758 			if (ret) {
759 				result("dst mapping error", total_tests,
760 				       src->off, dst->off, len, ret);
761 				goto error_unmap_continue;
762 			}
763 			um->bidi_cnt++;
764 		}
765 
766 		if (thread->type == DMA_MEMCPY)
767 			tx = dev->device_prep_dma_memcpy(chan,
768 							 dsts[0] + dst->off,
769 							 srcs[0], len, flags);
770 		else if (thread->type == DMA_MEMSET)
771 			tx = dev->device_prep_dma_memset(chan,
772 						dsts[0] + dst->off,
773 						*(src->aligned[0] + src->off),
774 						len, flags);
775 		else if (thread->type == DMA_XOR)
776 			tx = dev->device_prep_dma_xor(chan,
777 						      dsts[0] + dst->off,
778 						      srcs, src->cnt,
779 						      len, flags);
780 		else if (thread->type == DMA_PQ) {
781 			for (i = 0; i < dst->cnt; i++)
782 				dma_pq[i] = dsts[i] + dst->off;
783 			tx = dev->device_prep_dma_pq(chan, dma_pq, srcs,
784 						     src->cnt, pq_coefs,
785 						     len, flags);
786 		}
787 
788 		if (!tx) {
789 			result("prep error", total_tests, src->off,
790 			       dst->off, len, ret);
791 			msleep(100);
792 			goto error_unmap_continue;
793 		}
794 
795 		done->done = false;
796 		if (!params->polled) {
797 			tx->callback = dmatest_callback;
798 			tx->callback_param = done;
799 		}
800 		cookie = tx->tx_submit(tx);
801 
802 		if (dma_submit_error(cookie)) {
803 			result("submit error", total_tests, src->off,
804 			       dst->off, len, ret);
805 			msleep(100);
806 			goto error_unmap_continue;
807 		}
808 
809 		if (params->polled) {
810 			status = dma_sync_wait(chan, cookie);
811 			dmaengine_terminate_sync(chan);
812 			if (status == DMA_COMPLETE)
813 				done->done = true;
814 		} else {
815 			dma_async_issue_pending(chan);
816 
817 			wait_event_freezable_timeout(thread->done_wait,
818 					done->done,
819 					msecs_to_jiffies(params->timeout));
820 
821 			status = dma_async_is_tx_complete(chan, cookie, NULL,
822 							  NULL);
823 		}
824 
825 		if (!done->done) {
826 			result("test timed out", total_tests, src->off, dst->off,
827 			       len, 0);
828 			goto error_unmap_continue;
829 		} else if (status != DMA_COMPLETE) {
830 			result(status == DMA_ERROR ?
831 			       "completion error status" :
832 			       "completion busy status", total_tests, src->off,
833 			       dst->off, len, ret);
834 			goto error_unmap_continue;
835 		}
836 
837 		dmaengine_unmap_put(um);
838 
839 		if (params->noverify) {
840 			verbose_result("test passed", total_tests, src->off,
841 				       dst->off, len, 0);
842 			continue;
843 		}
844 
845 		start = ktime_get();
846 		pr_debug("%s: verifying source buffer...\n", current->comm);
847 		error_count = dmatest_verify(src->aligned, 0, src->off,
848 				0, PATTERN_SRC, true, is_memset);
849 		error_count += dmatest_verify(src->aligned, src->off,
850 				src->off + len, src->off,
851 				PATTERN_SRC | PATTERN_COPY, true, is_memset);
852 		error_count += dmatest_verify(src->aligned, src->off + len,
853 				buf_size, src->off + len,
854 				PATTERN_SRC, true, is_memset);
855 
856 		pr_debug("%s: verifying dest buffer...\n", current->comm);
857 		error_count += dmatest_verify(dst->aligned, 0, dst->off,
858 				0, PATTERN_DST, false, is_memset);
859 
860 		error_count += dmatest_verify(dst->aligned, dst->off,
861 				dst->off + len, src->off,
862 				PATTERN_SRC | PATTERN_COPY, false, is_memset);
863 
864 		error_count += dmatest_verify(dst->aligned, dst->off + len,
865 				buf_size, dst->off + len,
866 				PATTERN_DST, false, is_memset);
867 
868 		diff = ktime_sub(ktime_get(), start);
869 		comparetime = ktime_add(comparetime, diff);
870 
871 		if (error_count) {
872 			result("data error", total_tests, src->off, dst->off,
873 			       len, error_count);
874 			failed_tests++;
875 		} else {
876 			verbose_result("test passed", total_tests, src->off,
877 				       dst->off, len, 0);
878 		}
879 
880 		continue;
881 
882 error_unmap_continue:
883 		dmaengine_unmap_put(um);
884 		failed_tests++;
885 	}
886 	ktime = ktime_sub(ktime_get(), ktime);
887 	ktime = ktime_sub(ktime, comparetime);
888 	ktime = ktime_sub(ktime, filltime);
889 	runtime = ktime_to_us(ktime);
890 
891 	ret = 0;
892 	kfree(dma_pq);
893 err_srcs_array:
894 	kfree(srcs);
895 err_dst:
896 	dmatest_free_test_data(dst);
897 err_src:
898 	dmatest_free_test_data(src);
899 err_free_coefs:
900 	kfree(pq_coefs);
901 err_thread_type:
902 	iops = dmatest_persec(runtime, total_tests);
903 	pr_info("%s: summary %u tests, %u failures %llu.%02llu iops %llu KB/s (%d)\n",
904 		current->comm, total_tests, failed_tests,
905 		FIXPT_TO_INT(iops), FIXPT_GET_FRAC(iops),
906 		dmatest_KBs(runtime, total_len), ret);
907 
908 	/* terminate all transfers on specified channels */
909 	if (ret || failed_tests)
910 		dmaengine_terminate_sync(chan);
911 
912 	thread->done = true;
913 	wake_up(&thread_wait);
914 
915 	return ret;
916 }
917 
918 static void dmatest_cleanup_channel(struct dmatest_chan *dtc)
919 {
920 	struct dmatest_thread	*thread;
921 	struct dmatest_thread	*_thread;
922 	int			ret;
923 
924 	list_for_each_entry_safe(thread, _thread, &dtc->threads, node) {
925 		ret = kthread_stop(thread->task);
926 		pr_debug("thread %s exited with status %d\n",
927 			 thread->task->comm, ret);
928 		list_del(&thread->node);
929 		put_task_struct(thread->task);
930 		kfree(thread);
931 	}
932 
933 	/* terminate all transfers on specified channels */
934 	dmaengine_terminate_sync(dtc->chan);
935 
936 	kfree(dtc);
937 }
938 
939 static int dmatest_add_threads(struct dmatest_info *info,
940 		struct dmatest_chan *dtc, enum dma_transaction_type type)
941 {
942 	struct dmatest_params *params = &info->params;
943 	struct dmatest_thread *thread;
944 	struct dma_chan *chan = dtc->chan;
945 	char *op;
946 	unsigned int i;
947 
948 	if (type == DMA_MEMCPY)
949 		op = "copy";
950 	else if (type == DMA_MEMSET)
951 		op = "set";
952 	else if (type == DMA_XOR)
953 		op = "xor";
954 	else if (type == DMA_PQ)
955 		op = "pq";
956 	else
957 		return -EINVAL;
958 
959 	for (i = 0; i < params->threads_per_chan; i++) {
960 		thread = kzalloc(sizeof(struct dmatest_thread), GFP_KERNEL);
961 		if (!thread) {
962 			pr_warn("No memory for %s-%s%u\n",
963 				dma_chan_name(chan), op, i);
964 			break;
965 		}
966 		thread->info = info;
967 		thread->chan = dtc->chan;
968 		thread->type = type;
969 		thread->test_done.wait = &thread->done_wait;
970 		init_waitqueue_head(&thread->done_wait);
971 		smp_wmb();
972 		thread->task = kthread_create(dmatest_func, thread, "%s-%s%u",
973 				dma_chan_name(chan), op, i);
974 		if (IS_ERR(thread->task)) {
975 			pr_warn("Failed to create thread %s-%s%u\n",
976 				dma_chan_name(chan), op, i);
977 			kfree(thread);
978 			break;
979 		}
980 
981 		/* srcbuf and dstbuf are allocated by the thread itself */
982 		get_task_struct(thread->task);
983 		list_add_tail(&thread->node, &dtc->threads);
984 		thread->pending = true;
985 	}
986 
987 	return i;
988 }
989 
990 static int dmatest_add_channel(struct dmatest_info *info,
991 		struct dma_chan *chan)
992 {
993 	struct dmatest_chan	*dtc;
994 	struct dma_device	*dma_dev = chan->device;
995 	unsigned int		thread_count = 0;
996 	int cnt;
997 
998 	dtc = kmalloc(sizeof(struct dmatest_chan), GFP_KERNEL);
999 	if (!dtc) {
1000 		pr_warn("No memory for %s\n", dma_chan_name(chan));
1001 		return -ENOMEM;
1002 	}
1003 
1004 	dtc->chan = chan;
1005 	INIT_LIST_HEAD(&dtc->threads);
1006 
1007 	if (dma_has_cap(DMA_MEMCPY, dma_dev->cap_mask)) {
1008 		if (dmatest == 0) {
1009 			cnt = dmatest_add_threads(info, dtc, DMA_MEMCPY);
1010 			thread_count += cnt > 0 ? cnt : 0;
1011 		}
1012 	}
1013 
1014 	if (dma_has_cap(DMA_MEMSET, dma_dev->cap_mask)) {
1015 		if (dmatest == 1) {
1016 			cnt = dmatest_add_threads(info, dtc, DMA_MEMSET);
1017 			thread_count += cnt > 0 ? cnt : 0;
1018 		}
1019 	}
1020 
1021 	if (dma_has_cap(DMA_XOR, dma_dev->cap_mask)) {
1022 		cnt = dmatest_add_threads(info, dtc, DMA_XOR);
1023 		thread_count += cnt > 0 ? cnt : 0;
1024 	}
1025 	if (dma_has_cap(DMA_PQ, dma_dev->cap_mask)) {
1026 		cnt = dmatest_add_threads(info, dtc, DMA_PQ);
1027 		thread_count += cnt > 0 ? cnt : 0;
1028 	}
1029 
1030 	pr_info("Added %u threads using %s\n",
1031 		thread_count, dma_chan_name(chan));
1032 
1033 	list_add_tail(&dtc->node, &info->channels);
1034 	info->nr_channels++;
1035 
1036 	return 0;
1037 }
1038 
1039 static bool filter(struct dma_chan *chan, void *param)
1040 {
1041 	struct dmatest_params *params = param;
1042 
1043 	if (!dmatest_match_channel(params, chan) ||
1044 	    !dmatest_match_device(params, chan->device))
1045 		return false;
1046 	else
1047 		return true;
1048 }
1049 
1050 static void request_channels(struct dmatest_info *info,
1051 			     enum dma_transaction_type type)
1052 {
1053 	dma_cap_mask_t mask;
1054 
1055 	dma_cap_zero(mask);
1056 	dma_cap_set(type, mask);
1057 	for (;;) {
1058 		struct dmatest_params *params = &info->params;
1059 		struct dma_chan *chan;
1060 
1061 		chan = dma_request_channel(mask, filter, params);
1062 		if (chan) {
1063 			if (dmatest_add_channel(info, chan)) {
1064 				dma_release_channel(chan);
1065 				break; /* add_channel failed, punt */
1066 			}
1067 		} else
1068 			break; /* no more channels available */
1069 		if (params->max_channels &&
1070 		    info->nr_channels >= params->max_channels)
1071 			break; /* we have all we need */
1072 	}
1073 }
1074 
1075 static void add_threaded_test(struct dmatest_info *info)
1076 {
1077 	struct dmatest_params *params = &info->params;
1078 
1079 	/* Copy test parameters */
1080 	params->buf_size = test_buf_size;
1081 	strlcpy(params->channel, strim(test_channel), sizeof(params->channel));
1082 	strlcpy(params->device, strim(test_device), sizeof(params->device));
1083 	params->threads_per_chan = threads_per_chan;
1084 	params->max_channels = max_channels;
1085 	params->iterations = iterations;
1086 	params->xor_sources = xor_sources;
1087 	params->pq_sources = pq_sources;
1088 	params->timeout = timeout;
1089 	params->noverify = noverify;
1090 	params->norandom = norandom;
1091 	params->alignment = alignment;
1092 	params->transfer_size = transfer_size;
1093 	params->polled = polled;
1094 
1095 	request_channels(info, DMA_MEMCPY);
1096 	request_channels(info, DMA_MEMSET);
1097 	request_channels(info, DMA_XOR);
1098 	request_channels(info, DMA_PQ);
1099 }
1100 
1101 static void run_pending_tests(struct dmatest_info *info)
1102 {
1103 	struct dmatest_chan *dtc;
1104 	unsigned int thread_count = 0;
1105 
1106 	list_for_each_entry(dtc, &info->channels, node) {
1107 		struct dmatest_thread *thread;
1108 
1109 		thread_count = 0;
1110 		list_for_each_entry(thread, &dtc->threads, node) {
1111 			wake_up_process(thread->task);
1112 			thread_count++;
1113 		}
1114 		pr_info("Started %u threads using %s\n",
1115 			thread_count, dma_chan_name(dtc->chan));
1116 	}
1117 }
1118 
1119 static void stop_threaded_test(struct dmatest_info *info)
1120 {
1121 	struct dmatest_chan *dtc, *_dtc;
1122 	struct dma_chan *chan;
1123 
1124 	list_for_each_entry_safe(dtc, _dtc, &info->channels, node) {
1125 		list_del(&dtc->node);
1126 		chan = dtc->chan;
1127 		dmatest_cleanup_channel(dtc);
1128 		pr_debug("dropped channel %s\n", dma_chan_name(chan));
1129 		dma_release_channel(chan);
1130 	}
1131 
1132 	info->nr_channels = 0;
1133 }
1134 
1135 static void start_threaded_tests(struct dmatest_info *info)
1136 {
1137 	/* we might be called early to set run=, defer running until all
1138 	 * parameters have been evaluated
1139 	 */
1140 	if (!info->did_init)
1141 		return;
1142 
1143 	run_pending_tests(info);
1144 }
1145 
1146 static int dmatest_run_get(char *val, const struct kernel_param *kp)
1147 {
1148 	struct dmatest_info *info = &test_info;
1149 
1150 	mutex_lock(&info->lock);
1151 	if (is_threaded_test_run(info)) {
1152 		dmatest_run = true;
1153 	} else {
1154 		if (!is_threaded_test_pending(info))
1155 			stop_threaded_test(info);
1156 		dmatest_run = false;
1157 	}
1158 	mutex_unlock(&info->lock);
1159 
1160 	return param_get_bool(val, kp);
1161 }
1162 
1163 static int dmatest_run_set(const char *val, const struct kernel_param *kp)
1164 {
1165 	struct dmatest_info *info = &test_info;
1166 	int ret;
1167 
1168 	mutex_lock(&info->lock);
1169 	ret = param_set_bool(val, kp);
1170 	if (ret) {
1171 		mutex_unlock(&info->lock);
1172 		return ret;
1173 	} else if (dmatest_run) {
1174 		if (is_threaded_test_pending(info))
1175 			start_threaded_tests(info);
1176 		else
1177 			pr_info("Could not start test, no channels configured\n");
1178 	} else {
1179 		stop_threaded_test(info);
1180 	}
1181 
1182 	mutex_unlock(&info->lock);
1183 
1184 	return ret;
1185 }
1186 
1187 static int dmatest_chan_set(const char *val, const struct kernel_param *kp)
1188 {
1189 	struct dmatest_info *info = &test_info;
1190 	struct dmatest_chan *dtc;
1191 	char chan_reset_val[20];
1192 	int ret = 0;
1193 
1194 	mutex_lock(&info->lock);
1195 	ret = param_set_copystring(val, kp);
1196 	if (ret) {
1197 		mutex_unlock(&info->lock);
1198 		return ret;
1199 	}
1200 	/*Clear any previously run threads */
1201 	if (!is_threaded_test_run(info) && !is_threaded_test_pending(info))
1202 		stop_threaded_test(info);
1203 	/* Reject channels that are already registered */
1204 	if (is_threaded_test_pending(info)) {
1205 		list_for_each_entry(dtc, &info->channels, node) {
1206 			if (strcmp(dma_chan_name(dtc->chan),
1207 				   strim(test_channel)) == 0) {
1208 				dtc = list_last_entry(&info->channels,
1209 						      struct dmatest_chan,
1210 						      node);
1211 				strlcpy(chan_reset_val,
1212 					dma_chan_name(dtc->chan),
1213 					sizeof(chan_reset_val));
1214 				ret = -EBUSY;
1215 				goto add_chan_err;
1216 			}
1217 		}
1218 	}
1219 
1220 	add_threaded_test(info);
1221 
1222 	/* Check if channel was added successfully */
1223 	dtc = list_last_entry(&info->channels, struct dmatest_chan, node);
1224 
1225 	if (dtc->chan) {
1226 		/*
1227 		 * if new channel was not successfully added, revert the
1228 		 * "test_channel" string to the name of the last successfully
1229 		 * added channel. exception for when users issues empty string
1230 		 * to channel parameter.
1231 		 */
1232 		if ((strcmp(dma_chan_name(dtc->chan), strim(test_channel)) != 0)
1233 		    && (strcmp("", strim(test_channel)) != 0)) {
1234 			ret = -EINVAL;
1235 			strlcpy(chan_reset_val, dma_chan_name(dtc->chan),
1236 				sizeof(chan_reset_val));
1237 			goto add_chan_err;
1238 		}
1239 
1240 	} else {
1241 		/* Clear test_channel if no channels were added successfully */
1242 		strlcpy(chan_reset_val, "", sizeof(chan_reset_val));
1243 		ret = -EBUSY;
1244 		goto add_chan_err;
1245 	}
1246 
1247 	mutex_unlock(&info->lock);
1248 
1249 	return ret;
1250 
1251 add_chan_err:
1252 	param_set_copystring(chan_reset_val, kp);
1253 	mutex_unlock(&info->lock);
1254 
1255 	return ret;
1256 }
1257 
1258 static int dmatest_chan_get(char *val, const struct kernel_param *kp)
1259 {
1260 	struct dmatest_info *info = &test_info;
1261 
1262 	mutex_lock(&info->lock);
1263 	if (!is_threaded_test_run(info) && !is_threaded_test_pending(info)) {
1264 		stop_threaded_test(info);
1265 		strlcpy(test_channel, "", sizeof(test_channel));
1266 	}
1267 	mutex_unlock(&info->lock);
1268 
1269 	return param_get_string(val, kp);
1270 }
1271 
1272 static int dmatest_test_list_get(char *val, const struct kernel_param *kp)
1273 {
1274 	struct dmatest_info *info = &test_info;
1275 	struct dmatest_chan *dtc;
1276 	unsigned int thread_count = 0;
1277 
1278 	list_for_each_entry(dtc, &info->channels, node) {
1279 		struct dmatest_thread *thread;
1280 
1281 		thread_count = 0;
1282 		list_for_each_entry(thread, &dtc->threads, node) {
1283 			thread_count++;
1284 		}
1285 		pr_info("%u threads using %s\n",
1286 			thread_count, dma_chan_name(dtc->chan));
1287 	}
1288 
1289 	return 0;
1290 }
1291 
1292 static int __init dmatest_init(void)
1293 {
1294 	struct dmatest_info *info = &test_info;
1295 	struct dmatest_params *params = &info->params;
1296 
1297 	if (dmatest_run) {
1298 		mutex_lock(&info->lock);
1299 		add_threaded_test(info);
1300 		run_pending_tests(info);
1301 		mutex_unlock(&info->lock);
1302 	}
1303 
1304 	if (params->iterations && wait)
1305 		wait_event(thread_wait, !is_threaded_test_run(info));
1306 
1307 	/* module parameters are stable, inittime tests are started,
1308 	 * let userspace take over 'run' control
1309 	 */
1310 	info->did_init = true;
1311 
1312 	return 0;
1313 }
1314 /* when compiled-in wait for drivers to load first */
1315 late_initcall(dmatest_init);
1316 
1317 static void __exit dmatest_exit(void)
1318 {
1319 	struct dmatest_info *info = &test_info;
1320 
1321 	mutex_lock(&info->lock);
1322 	stop_threaded_test(info);
1323 	mutex_unlock(&info->lock);
1324 }
1325 module_exit(dmatest_exit);
1326 
1327 MODULE_AUTHOR("Haavard Skinnemoen (Atmel)");
1328 MODULE_LICENSE("GPL v2");
1329