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