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