GNU Linux-libre 4.19.304-gnu1
[releases.git] / drivers / dma / dmaengine.c
1 /*
2  * Copyright(c) 2004 - 2006 Intel Corporation. All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by the Free
6  * Software Foundation; either version 2 of the License, or (at your option)
7  * any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  *
14  * The full GNU General Public License is included in this distribution in the
15  * file called COPYING.
16  */
17
18 /*
19  * This code implements the DMA subsystem. It provides a HW-neutral interface
20  * for other kernel code to use asynchronous memory copy capabilities,
21  * if present, and allows different HW DMA drivers to register as providing
22  * this capability.
23  *
24  * Due to the fact we are accelerating what is already a relatively fast
25  * operation, the code goes to great lengths to avoid additional overhead,
26  * such as locking.
27  *
28  * LOCKING:
29  *
30  * The subsystem keeps a global list of dma_device structs it is protected by a
31  * mutex, dma_list_mutex.
32  *
33  * A subsystem can get access to a channel by calling dmaengine_get() followed
34  * by dma_find_channel(), or if it has need for an exclusive channel it can call
35  * dma_request_channel().  Once a channel is allocated a reference is taken
36  * against its corresponding driver to disable removal.
37  *
38  * Each device has a channels list, which runs unlocked but is never modified
39  * once the device is registered, it's just setup by the driver.
40  *
41  * See Documentation/driver-api/dmaengine for more details
42  */
43
44 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
45
46 #include <linux/platform_device.h>
47 #include <linux/dma-mapping.h>
48 #include <linux/init.h>
49 #include <linux/module.h>
50 #include <linux/mm.h>
51 #include <linux/device.h>
52 #include <linux/dmaengine.h>
53 #include <linux/hardirq.h>
54 #include <linux/spinlock.h>
55 #include <linux/percpu.h>
56 #include <linux/rcupdate.h>
57 #include <linux/mutex.h>
58 #include <linux/jiffies.h>
59 #include <linux/rculist.h>
60 #include <linux/idr.h>
61 #include <linux/slab.h>
62 #include <linux/acpi.h>
63 #include <linux/acpi_dma.h>
64 #include <linux/of_dma.h>
65 #include <linux/mempool.h>
66
67 static DEFINE_MUTEX(dma_list_mutex);
68 static DEFINE_IDA(dma_ida);
69 static LIST_HEAD(dma_device_list);
70 static long dmaengine_ref_count;
71
72 /* --- sysfs implementation --- */
73
74 /**
75  * dev_to_dma_chan - convert a device pointer to the its sysfs container object
76  * @dev - device node
77  *
78  * Must be called under dma_list_mutex
79  */
80 static struct dma_chan *dev_to_dma_chan(struct device *dev)
81 {
82         struct dma_chan_dev *chan_dev;
83
84         chan_dev = container_of(dev, typeof(*chan_dev), device);
85         return chan_dev->chan;
86 }
87
88 static ssize_t memcpy_count_show(struct device *dev,
89                                  struct device_attribute *attr, char *buf)
90 {
91         struct dma_chan *chan;
92         unsigned long count = 0;
93         int i;
94         int err;
95
96         mutex_lock(&dma_list_mutex);
97         chan = dev_to_dma_chan(dev);
98         if (chan) {
99                 for_each_possible_cpu(i)
100                         count += per_cpu_ptr(chan->local, i)->memcpy_count;
101                 err = sprintf(buf, "%lu\n", count);
102         } else
103                 err = -ENODEV;
104         mutex_unlock(&dma_list_mutex);
105
106         return err;
107 }
108 static DEVICE_ATTR_RO(memcpy_count);
109
110 static ssize_t bytes_transferred_show(struct device *dev,
111                                       struct device_attribute *attr, char *buf)
112 {
113         struct dma_chan *chan;
114         unsigned long count = 0;
115         int i;
116         int err;
117
118         mutex_lock(&dma_list_mutex);
119         chan = dev_to_dma_chan(dev);
120         if (chan) {
121                 for_each_possible_cpu(i)
122                         count += per_cpu_ptr(chan->local, i)->bytes_transferred;
123                 err = sprintf(buf, "%lu\n", count);
124         } else
125                 err = -ENODEV;
126         mutex_unlock(&dma_list_mutex);
127
128         return err;
129 }
130 static DEVICE_ATTR_RO(bytes_transferred);
131
132 static ssize_t in_use_show(struct device *dev, struct device_attribute *attr,
133                            char *buf)
134 {
135         struct dma_chan *chan;
136         int err;
137
138         mutex_lock(&dma_list_mutex);
139         chan = dev_to_dma_chan(dev);
140         if (chan)
141                 err = sprintf(buf, "%d\n", chan->client_count);
142         else
143                 err = -ENODEV;
144         mutex_unlock(&dma_list_mutex);
145
146         return err;
147 }
148 static DEVICE_ATTR_RO(in_use);
149
150 static struct attribute *dma_dev_attrs[] = {
151         &dev_attr_memcpy_count.attr,
152         &dev_attr_bytes_transferred.attr,
153         &dev_attr_in_use.attr,
154         NULL,
155 };
156 ATTRIBUTE_GROUPS(dma_dev);
157
158 static void chan_dev_release(struct device *dev)
159 {
160         struct dma_chan_dev *chan_dev;
161
162         chan_dev = container_of(dev, typeof(*chan_dev), device);
163         if (atomic_dec_and_test(chan_dev->idr_ref)) {
164                 ida_free(&dma_ida, chan_dev->dev_id);
165                 kfree(chan_dev->idr_ref);
166         }
167         kfree(chan_dev);
168 }
169
170 static struct class dma_devclass = {
171         .name           = "dma",
172         .dev_groups     = dma_dev_groups,
173         .dev_release    = chan_dev_release,
174 };
175
176 /* --- client and device registration --- */
177
178 #define dma_device_satisfies_mask(device, mask) \
179         __dma_device_satisfies_mask((device), &(mask))
180 static int
181 __dma_device_satisfies_mask(struct dma_device *device,
182                             const dma_cap_mask_t *want)
183 {
184         dma_cap_mask_t has;
185
186         bitmap_and(has.bits, want->bits, device->cap_mask.bits,
187                 DMA_TX_TYPE_END);
188         return bitmap_equal(want->bits, has.bits, DMA_TX_TYPE_END);
189 }
190
191 static struct module *dma_chan_to_owner(struct dma_chan *chan)
192 {
193         return chan->device->owner;
194 }
195
196 /**
197  * balance_ref_count - catch up the channel reference count
198  * @chan - channel to balance ->client_count versus dmaengine_ref_count
199  *
200  * balance_ref_count must be called under dma_list_mutex
201  */
202 static void balance_ref_count(struct dma_chan *chan)
203 {
204         struct module *owner = dma_chan_to_owner(chan);
205
206         while (chan->client_count < dmaengine_ref_count) {
207                 __module_get(owner);
208                 chan->client_count++;
209         }
210 }
211
212 /**
213  * dma_chan_get - try to grab a dma channel's parent driver module
214  * @chan - channel to grab
215  *
216  * Must be called under dma_list_mutex
217  */
218 static int dma_chan_get(struct dma_chan *chan)
219 {
220         struct module *owner = dma_chan_to_owner(chan);
221         int ret;
222
223         /* The channel is already in use, update client count */
224         if (chan->client_count) {
225                 __module_get(owner);
226                 chan->client_count++;
227                 return 0;
228         }
229
230         if (!try_module_get(owner))
231                 return -ENODEV;
232
233         /* allocate upon first client reference */
234         if (chan->device->device_alloc_chan_resources) {
235                 ret = chan->device->device_alloc_chan_resources(chan);
236                 if (ret < 0)
237                         goto err_out;
238         }
239
240         chan->client_count++;
241
242         if (!dma_has_cap(DMA_PRIVATE, chan->device->cap_mask))
243                 balance_ref_count(chan);
244
245         return 0;
246
247 err_out:
248         module_put(owner);
249         return ret;
250 }
251
252 /**
253  * dma_chan_put - drop a reference to a dma channel's parent driver module
254  * @chan - channel to release
255  *
256  * Must be called under dma_list_mutex
257  */
258 static void dma_chan_put(struct dma_chan *chan)
259 {
260         /* This channel is not in use, bail out */
261         if (!chan->client_count)
262                 return;
263
264         chan->client_count--;
265         module_put(dma_chan_to_owner(chan));
266
267         /* This channel is not in use anymore, free it */
268         if (!chan->client_count && chan->device->device_free_chan_resources) {
269                 /* Make sure all operations have completed */
270                 dmaengine_synchronize(chan);
271                 chan->device->device_free_chan_resources(chan);
272         }
273
274         /* If the channel is used via a DMA request router, free the mapping */
275         if (chan->router && chan->router->route_free) {
276                 chan->router->route_free(chan->router->dev, chan->route_data);
277                 chan->router = NULL;
278                 chan->route_data = NULL;
279         }
280 }
281
282 enum dma_status dma_sync_wait(struct dma_chan *chan, dma_cookie_t cookie)
283 {
284         enum dma_status status;
285         unsigned long dma_sync_wait_timeout = jiffies + msecs_to_jiffies(5000);
286
287         dma_async_issue_pending(chan);
288         do {
289                 status = dma_async_is_tx_complete(chan, cookie, NULL, NULL);
290                 if (time_after_eq(jiffies, dma_sync_wait_timeout)) {
291                         dev_err(chan->device->dev, "%s: timeout!\n", __func__);
292                         return DMA_ERROR;
293                 }
294                 if (status != DMA_IN_PROGRESS)
295                         break;
296                 cpu_relax();
297         } while (1);
298
299         return status;
300 }
301 EXPORT_SYMBOL(dma_sync_wait);
302
303 /**
304  * dma_cap_mask_all - enable iteration over all operation types
305  */
306 static dma_cap_mask_t dma_cap_mask_all;
307
308 /**
309  * dma_chan_tbl_ent - tracks channel allocations per core/operation
310  * @chan - associated channel for this entry
311  */
312 struct dma_chan_tbl_ent {
313         struct dma_chan *chan;
314 };
315
316 /**
317  * channel_table - percpu lookup table for memory-to-memory offload providers
318  */
319 static struct dma_chan_tbl_ent __percpu *channel_table[DMA_TX_TYPE_END];
320
321 static int __init dma_channel_table_init(void)
322 {
323         enum dma_transaction_type cap;
324         int err = 0;
325
326         bitmap_fill(dma_cap_mask_all.bits, DMA_TX_TYPE_END);
327
328         /* 'interrupt', 'private', and 'slave' are channel capabilities,
329          * but are not associated with an operation so they do not need
330          * an entry in the channel_table
331          */
332         clear_bit(DMA_INTERRUPT, dma_cap_mask_all.bits);
333         clear_bit(DMA_PRIVATE, dma_cap_mask_all.bits);
334         clear_bit(DMA_SLAVE, dma_cap_mask_all.bits);
335
336         for_each_dma_cap_mask(cap, dma_cap_mask_all) {
337                 channel_table[cap] = alloc_percpu(struct dma_chan_tbl_ent);
338                 if (!channel_table[cap]) {
339                         err = -ENOMEM;
340                         break;
341                 }
342         }
343
344         if (err) {
345                 pr_err("initialization failure\n");
346                 for_each_dma_cap_mask(cap, dma_cap_mask_all)
347                         free_percpu(channel_table[cap]);
348         }
349
350         return err;
351 }
352 arch_initcall(dma_channel_table_init);
353
354 /**
355  * dma_find_channel - find a channel to carry out the operation
356  * @tx_type: transaction type
357  */
358 struct dma_chan *dma_find_channel(enum dma_transaction_type tx_type)
359 {
360         return this_cpu_read(channel_table[tx_type]->chan);
361 }
362 EXPORT_SYMBOL(dma_find_channel);
363
364 /**
365  * dma_issue_pending_all - flush all pending operations across all channels
366  */
367 void dma_issue_pending_all(void)
368 {
369         struct dma_device *device;
370         struct dma_chan *chan;
371
372         rcu_read_lock();
373         list_for_each_entry_rcu(device, &dma_device_list, global_node) {
374                 if (dma_has_cap(DMA_PRIVATE, device->cap_mask))
375                         continue;
376                 list_for_each_entry(chan, &device->channels, device_node)
377                         if (chan->client_count)
378                                 device->device_issue_pending(chan);
379         }
380         rcu_read_unlock();
381 }
382 EXPORT_SYMBOL(dma_issue_pending_all);
383
384 /**
385  * dma_chan_is_local - returns true if the channel is in the same numa-node as the cpu
386  */
387 static bool dma_chan_is_local(struct dma_chan *chan, int cpu)
388 {
389         int node = dev_to_node(chan->device->dev);
390         return node == -1 || cpumask_test_cpu(cpu, cpumask_of_node(node));
391 }
392
393 /**
394  * min_chan - returns the channel with min count and in the same numa-node as the cpu
395  * @cap: capability to match
396  * @cpu: cpu index which the channel should be close to
397  *
398  * If some channels are close to the given cpu, the one with the lowest
399  * reference count is returned. Otherwise, cpu is ignored and only the
400  * reference count is taken into account.
401  * Must be called under dma_list_mutex.
402  */
403 static struct dma_chan *min_chan(enum dma_transaction_type cap, int cpu)
404 {
405         struct dma_device *device;
406         struct dma_chan *chan;
407         struct dma_chan *min = NULL;
408         struct dma_chan *localmin = NULL;
409
410         list_for_each_entry(device, &dma_device_list, global_node) {
411                 if (!dma_has_cap(cap, device->cap_mask) ||
412                     dma_has_cap(DMA_PRIVATE, device->cap_mask))
413                         continue;
414                 list_for_each_entry(chan, &device->channels, device_node) {
415                         if (!chan->client_count)
416                                 continue;
417                         if (!min || chan->table_count < min->table_count)
418                                 min = chan;
419
420                         if (dma_chan_is_local(chan, cpu))
421                                 if (!localmin ||
422                                     chan->table_count < localmin->table_count)
423                                         localmin = chan;
424                 }
425         }
426
427         chan = localmin ? localmin : min;
428
429         if (chan)
430                 chan->table_count++;
431
432         return chan;
433 }
434
435 /**
436  * dma_channel_rebalance - redistribute the available channels
437  *
438  * Optimize for cpu isolation (each cpu gets a dedicated channel for an
439  * operation type) in the SMP case,  and operation isolation (avoid
440  * multi-tasking channels) in the non-SMP case.  Must be called under
441  * dma_list_mutex.
442  */
443 static void dma_channel_rebalance(void)
444 {
445         struct dma_chan *chan;
446         struct dma_device *device;
447         int cpu;
448         int cap;
449
450         /* undo the last distribution */
451         for_each_dma_cap_mask(cap, dma_cap_mask_all)
452                 for_each_possible_cpu(cpu)
453                         per_cpu_ptr(channel_table[cap], cpu)->chan = NULL;
454
455         list_for_each_entry(device, &dma_device_list, global_node) {
456                 if (dma_has_cap(DMA_PRIVATE, device->cap_mask))
457                         continue;
458                 list_for_each_entry(chan, &device->channels, device_node)
459                         chan->table_count = 0;
460         }
461
462         /* don't populate the channel_table if no clients are available */
463         if (!dmaengine_ref_count)
464                 return;
465
466         /* redistribute available channels */
467         for_each_dma_cap_mask(cap, dma_cap_mask_all)
468                 for_each_online_cpu(cpu) {
469                         chan = min_chan(cap, cpu);
470                         per_cpu_ptr(channel_table[cap], cpu)->chan = chan;
471                 }
472 }
473
474 int dma_get_slave_caps(struct dma_chan *chan, struct dma_slave_caps *caps)
475 {
476         struct dma_device *device;
477
478         if (!chan || !caps)
479                 return -EINVAL;
480
481         device = chan->device;
482
483         /* check if the channel supports slave transactions */
484         if (!(test_bit(DMA_SLAVE, device->cap_mask.bits) ||
485               test_bit(DMA_CYCLIC, device->cap_mask.bits)))
486                 return -ENXIO;
487
488         /*
489          * Check whether it reports it uses the generic slave
490          * capabilities, if not, that means it doesn't support any
491          * kind of slave capabilities reporting.
492          */
493         if (!device->directions)
494                 return -ENXIO;
495
496         caps->src_addr_widths = device->src_addr_widths;
497         caps->dst_addr_widths = device->dst_addr_widths;
498         caps->directions = device->directions;
499         caps->max_burst = device->max_burst;
500         caps->residue_granularity = device->residue_granularity;
501         caps->descriptor_reuse = device->descriptor_reuse;
502         caps->cmd_pause = !!device->device_pause;
503         caps->cmd_resume = !!device->device_resume;
504         caps->cmd_terminate = !!device->device_terminate_all;
505
506         return 0;
507 }
508 EXPORT_SYMBOL_GPL(dma_get_slave_caps);
509
510 static struct dma_chan *private_candidate(const dma_cap_mask_t *mask,
511                                           struct dma_device *dev,
512                                           dma_filter_fn fn, void *fn_param)
513 {
514         struct dma_chan *chan;
515
516         if (mask && !__dma_device_satisfies_mask(dev, mask)) {
517                 dev_dbg(dev->dev, "%s: wrong capabilities\n", __func__);
518                 return NULL;
519         }
520         /* devices with multiple channels need special handling as we need to
521          * ensure that all channels are either private or public.
522          */
523         if (dev->chancnt > 1 && !dma_has_cap(DMA_PRIVATE, dev->cap_mask))
524                 list_for_each_entry(chan, &dev->channels, device_node) {
525                         /* some channels are already publicly allocated */
526                         if (chan->client_count)
527                                 return NULL;
528                 }
529
530         list_for_each_entry(chan, &dev->channels, device_node) {
531                 if (chan->client_count) {
532                         dev_dbg(dev->dev, "%s: %s busy\n",
533                                  __func__, dma_chan_name(chan));
534                         continue;
535                 }
536                 if (fn && !fn(chan, fn_param)) {
537                         dev_dbg(dev->dev, "%s: %s filter said false\n",
538                                  __func__, dma_chan_name(chan));
539                         continue;
540                 }
541                 return chan;
542         }
543
544         return NULL;
545 }
546
547 static struct dma_chan *find_candidate(struct dma_device *device,
548                                        const dma_cap_mask_t *mask,
549                                        dma_filter_fn fn, void *fn_param)
550 {
551         struct dma_chan *chan = private_candidate(mask, device, fn, fn_param);
552         int err;
553
554         if (chan) {
555                 /* Found a suitable channel, try to grab, prep, and return it.
556                  * We first set DMA_PRIVATE to disable balance_ref_count as this
557                  * channel will not be published in the general-purpose
558                  * allocator
559                  */
560                 dma_cap_set(DMA_PRIVATE, device->cap_mask);
561                 device->privatecnt++;
562                 err = dma_chan_get(chan);
563
564                 if (err) {
565                         if (err == -ENODEV) {
566                                 dev_dbg(device->dev, "%s: %s module removed\n",
567                                         __func__, dma_chan_name(chan));
568                                 list_del_rcu(&device->global_node);
569                         } else
570                                 dev_dbg(device->dev,
571                                         "%s: failed to get %s: (%d)\n",
572                                          __func__, dma_chan_name(chan), err);
573
574                         if (--device->privatecnt == 0)
575                                 dma_cap_clear(DMA_PRIVATE, device->cap_mask);
576
577                         chan = ERR_PTR(err);
578                 }
579         }
580
581         return chan ? chan : ERR_PTR(-EPROBE_DEFER);
582 }
583
584 /**
585  * dma_get_slave_channel - try to get specific channel exclusively
586  * @chan: target channel
587  */
588 struct dma_chan *dma_get_slave_channel(struct dma_chan *chan)
589 {
590         int err = -EBUSY;
591
592         /* lock against __dma_request_channel */
593         mutex_lock(&dma_list_mutex);
594
595         if (chan->client_count == 0) {
596                 struct dma_device *device = chan->device;
597
598                 dma_cap_set(DMA_PRIVATE, device->cap_mask);
599                 device->privatecnt++;
600                 err = dma_chan_get(chan);
601                 if (err) {
602                         dev_dbg(chan->device->dev,
603                                 "%s: failed to get %s: (%d)\n",
604                                 __func__, dma_chan_name(chan), err);
605                         chan = NULL;
606                         if (--device->privatecnt == 0)
607                                 dma_cap_clear(DMA_PRIVATE, device->cap_mask);
608                 }
609         } else
610                 chan = NULL;
611
612         mutex_unlock(&dma_list_mutex);
613
614
615         return chan;
616 }
617 EXPORT_SYMBOL_GPL(dma_get_slave_channel);
618
619 struct dma_chan *dma_get_any_slave_channel(struct dma_device *device)
620 {
621         dma_cap_mask_t mask;
622         struct dma_chan *chan;
623
624         dma_cap_zero(mask);
625         dma_cap_set(DMA_SLAVE, mask);
626
627         /* lock against __dma_request_channel */
628         mutex_lock(&dma_list_mutex);
629
630         chan = find_candidate(device, &mask, NULL, NULL);
631
632         mutex_unlock(&dma_list_mutex);
633
634         return IS_ERR(chan) ? NULL : chan;
635 }
636 EXPORT_SYMBOL_GPL(dma_get_any_slave_channel);
637
638 /**
639  * __dma_request_channel - try to allocate an exclusive channel
640  * @mask: capabilities that the channel must satisfy
641  * @fn: optional callback to disposition available channels
642  * @fn_param: opaque parameter to pass to dma_filter_fn
643  *
644  * Returns pointer to appropriate DMA channel on success or NULL.
645  */
646 struct dma_chan *__dma_request_channel(const dma_cap_mask_t *mask,
647                                        dma_filter_fn fn, void *fn_param)
648 {
649         struct dma_device *device, *_d;
650         struct dma_chan *chan = NULL;
651
652         /* Find a channel */
653         mutex_lock(&dma_list_mutex);
654         list_for_each_entry_safe(device, _d, &dma_device_list, global_node) {
655                 chan = find_candidate(device, mask, fn, fn_param);
656                 if (!IS_ERR(chan))
657                         break;
658
659                 chan = NULL;
660         }
661         mutex_unlock(&dma_list_mutex);
662
663         pr_debug("%s: %s (%s)\n",
664                  __func__,
665                  chan ? "success" : "fail",
666                  chan ? dma_chan_name(chan) : NULL);
667
668         return chan;
669 }
670 EXPORT_SYMBOL_GPL(__dma_request_channel);
671
672 static const struct dma_slave_map *dma_filter_match(struct dma_device *device,
673                                                     const char *name,
674                                                     struct device *dev)
675 {
676         int i;
677
678         if (!device->filter.mapcnt)
679                 return NULL;
680
681         for (i = 0; i < device->filter.mapcnt; i++) {
682                 const struct dma_slave_map *map = &device->filter.map[i];
683
684                 if (!strcmp(map->devname, dev_name(dev)) &&
685                     !strcmp(map->slave, name))
686                         return map;
687         }
688
689         return NULL;
690 }
691
692 /**
693  * dma_request_chan - try to allocate an exclusive slave channel
694  * @dev:        pointer to client device structure
695  * @name:       slave channel name
696  *
697  * Returns pointer to appropriate DMA channel on success or an error pointer.
698  */
699 struct dma_chan *dma_request_chan(struct device *dev, const char *name)
700 {
701         struct dma_device *d, *_d;
702         struct dma_chan *chan = NULL;
703
704         /* If device-tree is present get slave info from here */
705         if (dev->of_node)
706                 chan = of_dma_request_slave_channel(dev->of_node, name);
707
708         /* If device was enumerated by ACPI get slave info from here */
709         if (has_acpi_companion(dev) && !chan)
710                 chan = acpi_dma_request_slave_chan_by_name(dev, name);
711
712         if (chan) {
713                 /* Valid channel found or requester need to be deferred */
714                 if (!IS_ERR(chan) || PTR_ERR(chan) == -EPROBE_DEFER)
715                         return chan;
716         }
717
718         /* Try to find the channel via the DMA filter map(s) */
719         mutex_lock(&dma_list_mutex);
720         list_for_each_entry_safe(d, _d, &dma_device_list, global_node) {
721                 dma_cap_mask_t mask;
722                 const struct dma_slave_map *map = dma_filter_match(d, name, dev);
723
724                 if (!map)
725                         continue;
726
727                 dma_cap_zero(mask);
728                 dma_cap_set(DMA_SLAVE, mask);
729
730                 chan = find_candidate(d, &mask, d->filter.fn, map->param);
731                 if (!IS_ERR(chan))
732                         break;
733         }
734         mutex_unlock(&dma_list_mutex);
735
736         return chan ? chan : ERR_PTR(-EPROBE_DEFER);
737 }
738 EXPORT_SYMBOL_GPL(dma_request_chan);
739
740 /**
741  * dma_request_slave_channel - try to allocate an exclusive slave channel
742  * @dev:        pointer to client device structure
743  * @name:       slave channel name
744  *
745  * Returns pointer to appropriate DMA channel on success or NULL.
746  */
747 struct dma_chan *dma_request_slave_channel(struct device *dev,
748                                            const char *name)
749 {
750         struct dma_chan *ch = dma_request_chan(dev, name);
751         if (IS_ERR(ch))
752                 return NULL;
753
754         return ch;
755 }
756 EXPORT_SYMBOL_GPL(dma_request_slave_channel);
757
758 /**
759  * dma_request_chan_by_mask - allocate a channel satisfying certain capabilities
760  * @mask: capabilities that the channel must satisfy
761  *
762  * Returns pointer to appropriate DMA channel on success or an error pointer.
763  */
764 struct dma_chan *dma_request_chan_by_mask(const dma_cap_mask_t *mask)
765 {
766         struct dma_chan *chan;
767
768         if (!mask)
769                 return ERR_PTR(-ENODEV);
770
771         chan = __dma_request_channel(mask, NULL, NULL);
772         if (!chan) {
773                 mutex_lock(&dma_list_mutex);
774                 if (list_empty(&dma_device_list))
775                         chan = ERR_PTR(-EPROBE_DEFER);
776                 else
777                         chan = ERR_PTR(-ENODEV);
778                 mutex_unlock(&dma_list_mutex);
779         }
780
781         return chan;
782 }
783 EXPORT_SYMBOL_GPL(dma_request_chan_by_mask);
784
785 void dma_release_channel(struct dma_chan *chan)
786 {
787         mutex_lock(&dma_list_mutex);
788         WARN_ONCE(chan->client_count != 1,
789                   "chan reference count %d != 1\n", chan->client_count);
790         dma_chan_put(chan);
791         /* drop PRIVATE cap enabled by __dma_request_channel() */
792         if (--chan->device->privatecnt == 0)
793                 dma_cap_clear(DMA_PRIVATE, chan->device->cap_mask);
794         mutex_unlock(&dma_list_mutex);
795 }
796 EXPORT_SYMBOL_GPL(dma_release_channel);
797
798 /**
799  * dmaengine_get - register interest in dma_channels
800  */
801 void dmaengine_get(void)
802 {
803         struct dma_device *device, *_d;
804         struct dma_chan *chan;
805         int err;
806
807         mutex_lock(&dma_list_mutex);
808         dmaengine_ref_count++;
809
810         /* try to grab channels */
811         list_for_each_entry_safe(device, _d, &dma_device_list, global_node) {
812                 if (dma_has_cap(DMA_PRIVATE, device->cap_mask))
813                         continue;
814                 list_for_each_entry(chan, &device->channels, device_node) {
815                         err = dma_chan_get(chan);
816                         if (err == -ENODEV) {
817                                 /* module removed before we could use it */
818                                 list_del_rcu(&device->global_node);
819                                 break;
820                         } else if (err)
821                                 dev_dbg(chan->device->dev,
822                                         "%s: failed to get %s: (%d)\n",
823                                         __func__, dma_chan_name(chan), err);
824                 }
825         }
826
827         /* if this is the first reference and there were channels
828          * waiting we need to rebalance to get those channels
829          * incorporated into the channel table
830          */
831         if (dmaengine_ref_count == 1)
832                 dma_channel_rebalance();
833         mutex_unlock(&dma_list_mutex);
834 }
835 EXPORT_SYMBOL(dmaengine_get);
836
837 /**
838  * dmaengine_put - let dma drivers be removed when ref_count == 0
839  */
840 void dmaengine_put(void)
841 {
842         struct dma_device *device;
843         struct dma_chan *chan;
844
845         mutex_lock(&dma_list_mutex);
846         dmaengine_ref_count--;
847         BUG_ON(dmaengine_ref_count < 0);
848         /* drop channel references */
849         list_for_each_entry(device, &dma_device_list, global_node) {
850                 if (dma_has_cap(DMA_PRIVATE, device->cap_mask))
851                         continue;
852                 list_for_each_entry(chan, &device->channels, device_node)
853                         dma_chan_put(chan);
854         }
855         mutex_unlock(&dma_list_mutex);
856 }
857 EXPORT_SYMBOL(dmaengine_put);
858
859 static bool device_has_all_tx_types(struct dma_device *device)
860 {
861         /* A device that satisfies this test has channels that will never cause
862          * an async_tx channel switch event as all possible operation types can
863          * be handled.
864          */
865         #ifdef CONFIG_ASYNC_TX_DMA
866         if (!dma_has_cap(DMA_INTERRUPT, device->cap_mask))
867                 return false;
868         #endif
869
870         #if IS_ENABLED(CONFIG_ASYNC_MEMCPY)
871         if (!dma_has_cap(DMA_MEMCPY, device->cap_mask))
872                 return false;
873         #endif
874
875         #if IS_ENABLED(CONFIG_ASYNC_XOR)
876         if (!dma_has_cap(DMA_XOR, device->cap_mask))
877                 return false;
878
879         #ifndef CONFIG_ASYNC_TX_DISABLE_XOR_VAL_DMA
880         if (!dma_has_cap(DMA_XOR_VAL, device->cap_mask))
881                 return false;
882         #endif
883         #endif
884
885         #if IS_ENABLED(CONFIG_ASYNC_PQ)
886         if (!dma_has_cap(DMA_PQ, device->cap_mask))
887                 return false;
888
889         #ifndef CONFIG_ASYNC_TX_DISABLE_PQ_VAL_DMA
890         if (!dma_has_cap(DMA_PQ_VAL, device->cap_mask))
891                 return false;
892         #endif
893         #endif
894
895         return true;
896 }
897
898 static int get_dma_id(struct dma_device *device)
899 {
900         int rc = ida_alloc(&dma_ida, GFP_KERNEL);
901
902         if (rc < 0)
903                 return rc;
904         device->dev_id = rc;
905         return 0;
906 }
907
908 /**
909  * dma_async_device_register - registers DMA devices found
910  * @device: &dma_device
911  */
912 int dma_async_device_register(struct dma_device *device)
913 {
914         int chancnt = 0, rc;
915         struct dma_chan* chan;
916         atomic_t *idr_ref;
917
918         if (!device)
919                 return -ENODEV;
920
921         /* validate device routines */
922         if (!device->dev) {
923                 pr_err("DMAdevice must have dev\n");
924                 return -EIO;
925         }
926
927         device->owner = device->dev->driver->owner;
928
929         if (dma_has_cap(DMA_MEMCPY, device->cap_mask) && !device->device_prep_dma_memcpy) {
930                 dev_err(device->dev,
931                         "Device claims capability %s, but op is not defined\n",
932                         "DMA_MEMCPY");
933                 return -EIO;
934         }
935
936         if (dma_has_cap(DMA_XOR, device->cap_mask) && !device->device_prep_dma_xor) {
937                 dev_err(device->dev,
938                         "Device claims capability %s, but op is not defined\n",
939                         "DMA_XOR");
940                 return -EIO;
941         }
942
943         if (dma_has_cap(DMA_XOR_VAL, device->cap_mask) && !device->device_prep_dma_xor_val) {
944                 dev_err(device->dev,
945                         "Device claims capability %s, but op is not defined\n",
946                         "DMA_XOR_VAL");
947                 return -EIO;
948         }
949
950         if (dma_has_cap(DMA_PQ, device->cap_mask) && !device->device_prep_dma_pq) {
951                 dev_err(device->dev,
952                         "Device claims capability %s, but op is not defined\n",
953                         "DMA_PQ");
954                 return -EIO;
955         }
956
957         if (dma_has_cap(DMA_PQ_VAL, device->cap_mask) && !device->device_prep_dma_pq_val) {
958                 dev_err(device->dev,
959                         "Device claims capability %s, but op is not defined\n",
960                         "DMA_PQ_VAL");
961                 return -EIO;
962         }
963
964         if (dma_has_cap(DMA_MEMSET, device->cap_mask) && !device->device_prep_dma_memset) {
965                 dev_err(device->dev,
966                         "Device claims capability %s, but op is not defined\n",
967                         "DMA_MEMSET");
968                 return -EIO;
969         }
970
971         if (dma_has_cap(DMA_INTERRUPT, device->cap_mask) && !device->device_prep_dma_interrupt) {
972                 dev_err(device->dev,
973                         "Device claims capability %s, but op is not defined\n",
974                         "DMA_INTERRUPT");
975                 return -EIO;
976         }
977
978         if (dma_has_cap(DMA_CYCLIC, device->cap_mask) && !device->device_prep_dma_cyclic) {
979                 dev_err(device->dev,
980                         "Device claims capability %s, but op is not defined\n",
981                         "DMA_CYCLIC");
982                 return -EIO;
983         }
984
985         if (dma_has_cap(DMA_INTERLEAVE, device->cap_mask) && !device->device_prep_interleaved_dma) {
986                 dev_err(device->dev,
987                         "Device claims capability %s, but op is not defined\n",
988                         "DMA_INTERLEAVE");
989                 return -EIO;
990         }
991
992
993         if (!device->device_tx_status) {
994                 dev_err(device->dev, "Device tx_status is not defined\n");
995                 return -EIO;
996         }
997
998
999         if (!device->device_issue_pending) {
1000                 dev_err(device->dev, "Device issue_pending is not defined\n");
1001                 return -EIO;
1002         }
1003
1004         /* note: this only matters in the
1005          * CONFIG_ASYNC_TX_ENABLE_CHANNEL_SWITCH=n case
1006          */
1007         if (device_has_all_tx_types(device))
1008                 dma_cap_set(DMA_ASYNC_TX, device->cap_mask);
1009
1010         idr_ref = kmalloc(sizeof(*idr_ref), GFP_KERNEL);
1011         if (!idr_ref)
1012                 return -ENOMEM;
1013         rc = get_dma_id(device);
1014         if (rc != 0) {
1015                 kfree(idr_ref);
1016                 return rc;
1017         }
1018
1019         atomic_set(idr_ref, 0);
1020
1021         /* represent channels in sysfs. Probably want devs too */
1022         list_for_each_entry(chan, &device->channels, device_node) {
1023                 rc = -ENOMEM;
1024                 chan->local = alloc_percpu(typeof(*chan->local));
1025                 if (chan->local == NULL)
1026                         goto err_out;
1027                 chan->dev = kzalloc(sizeof(*chan->dev), GFP_KERNEL);
1028                 if (chan->dev == NULL) {
1029                         free_percpu(chan->local);
1030                         chan->local = NULL;
1031                         goto err_out;
1032                 }
1033
1034                 chan->chan_id = chancnt++;
1035                 chan->dev->device.class = &dma_devclass;
1036                 chan->dev->device.parent = device->dev;
1037                 chan->dev->chan = chan;
1038                 chan->dev->idr_ref = idr_ref;
1039                 chan->dev->dev_id = device->dev_id;
1040                 atomic_inc(idr_ref);
1041                 dev_set_name(&chan->dev->device, "dma%dchan%d",
1042                              device->dev_id, chan->chan_id);
1043
1044                 rc = device_register(&chan->dev->device);
1045                 if (rc) {
1046                         free_percpu(chan->local);
1047                         chan->local = NULL;
1048                         kfree(chan->dev);
1049                         atomic_dec(idr_ref);
1050                         goto err_out;
1051                 }
1052                 chan->client_count = 0;
1053         }
1054
1055         if (!chancnt) {
1056                 dev_err(device->dev, "%s: device has no channels!\n", __func__);
1057                 rc = -ENODEV;
1058                 goto err_out;
1059         }
1060
1061         device->chancnt = chancnt;
1062
1063         mutex_lock(&dma_list_mutex);
1064         /* take references on public channels */
1065         if (dmaengine_ref_count && !dma_has_cap(DMA_PRIVATE, device->cap_mask))
1066                 list_for_each_entry(chan, &device->channels, device_node) {
1067                         /* if clients are already waiting for channels we need
1068                          * to take references on their behalf
1069                          */
1070                         if (dma_chan_get(chan) == -ENODEV) {
1071                                 /* note we can only get here for the first
1072                                  * channel as the remaining channels are
1073                                  * guaranteed to get a reference
1074                                  */
1075                                 rc = -ENODEV;
1076                                 mutex_unlock(&dma_list_mutex);
1077                                 goto err_out;
1078                         }
1079                 }
1080         list_add_tail_rcu(&device->global_node, &dma_device_list);
1081         if (dma_has_cap(DMA_PRIVATE, device->cap_mask))
1082                 device->privatecnt++;   /* Always private */
1083         dma_channel_rebalance();
1084         mutex_unlock(&dma_list_mutex);
1085
1086         return 0;
1087
1088 err_out:
1089         /* if we never registered a channel just release the idr */
1090         if (atomic_read(idr_ref) == 0) {
1091                 ida_free(&dma_ida, device->dev_id);
1092                 kfree(idr_ref);
1093                 return rc;
1094         }
1095
1096         list_for_each_entry(chan, &device->channels, device_node) {
1097                 if (chan->local == NULL)
1098                         continue;
1099                 mutex_lock(&dma_list_mutex);
1100                 chan->dev->chan = NULL;
1101                 mutex_unlock(&dma_list_mutex);
1102                 device_unregister(&chan->dev->device);
1103                 free_percpu(chan->local);
1104         }
1105         return rc;
1106 }
1107 EXPORT_SYMBOL(dma_async_device_register);
1108
1109 /**
1110  * dma_async_device_unregister - unregister a DMA device
1111  * @device: &dma_device
1112  *
1113  * This routine is called by dma driver exit routines, dmaengine holds module
1114  * references to prevent it being called while channels are in use.
1115  */
1116 void dma_async_device_unregister(struct dma_device *device)
1117 {
1118         struct dma_chan *chan;
1119
1120         mutex_lock(&dma_list_mutex);
1121         list_del_rcu(&device->global_node);
1122         dma_channel_rebalance();
1123         mutex_unlock(&dma_list_mutex);
1124
1125         list_for_each_entry(chan, &device->channels, device_node) {
1126                 WARN_ONCE(chan->client_count,
1127                           "%s called while %d clients hold a reference\n",
1128                           __func__, chan->client_count);
1129                 mutex_lock(&dma_list_mutex);
1130                 chan->dev->chan = NULL;
1131                 mutex_unlock(&dma_list_mutex);
1132                 device_unregister(&chan->dev->device);
1133                 free_percpu(chan->local);
1134         }
1135 }
1136 EXPORT_SYMBOL(dma_async_device_unregister);
1137
1138 static void dmam_device_release(struct device *dev, void *res)
1139 {
1140         struct dma_device *device;
1141
1142         device = *(struct dma_device **)res;
1143         dma_async_device_unregister(device);
1144 }
1145
1146 /**
1147  * dmaenginem_async_device_register - registers DMA devices found
1148  * @device: &dma_device
1149  *
1150  * The operation is managed and will be undone on driver detach.
1151  */
1152 int dmaenginem_async_device_register(struct dma_device *device)
1153 {
1154         void *p;
1155         int ret;
1156
1157         p = devres_alloc(dmam_device_release, sizeof(void *), GFP_KERNEL);
1158         if (!p)
1159                 return -ENOMEM;
1160
1161         ret = dma_async_device_register(device);
1162         if (!ret) {
1163                 *(struct dma_device **)p = device;
1164                 devres_add(device->dev, p);
1165         } else {
1166                 devres_free(p);
1167         }
1168
1169         return ret;
1170 }
1171 EXPORT_SYMBOL(dmaenginem_async_device_register);
1172
1173 struct dmaengine_unmap_pool {
1174         struct kmem_cache *cache;
1175         const char *name;
1176         mempool_t *pool;
1177         size_t size;
1178 };
1179
1180 #define __UNMAP_POOL(x) { .size = x, .name = "dmaengine-unmap-" __stringify(x) }
1181 static struct dmaengine_unmap_pool unmap_pool[] = {
1182         __UNMAP_POOL(2),
1183         #if IS_ENABLED(CONFIG_DMA_ENGINE_RAID)
1184         __UNMAP_POOL(16),
1185         __UNMAP_POOL(128),
1186         __UNMAP_POOL(256),
1187         #endif
1188 };
1189
1190 static struct dmaengine_unmap_pool *__get_unmap_pool(int nr)
1191 {
1192         int order = get_count_order(nr);
1193
1194         switch (order) {
1195         case 0 ... 1:
1196                 return &unmap_pool[0];
1197 #if IS_ENABLED(CONFIG_DMA_ENGINE_RAID)
1198         case 2 ... 4:
1199                 return &unmap_pool[1];
1200         case 5 ... 7:
1201                 return &unmap_pool[2];
1202         case 8:
1203                 return &unmap_pool[3];
1204 #endif
1205         default:
1206                 BUG();
1207                 return NULL;
1208         }
1209 }
1210
1211 static void dmaengine_unmap(struct kref *kref)
1212 {
1213         struct dmaengine_unmap_data *unmap = container_of(kref, typeof(*unmap), kref);
1214         struct device *dev = unmap->dev;
1215         int cnt, i;
1216
1217         cnt = unmap->to_cnt;
1218         for (i = 0; i < cnt; i++)
1219                 dma_unmap_page(dev, unmap->addr[i], unmap->len,
1220                                DMA_TO_DEVICE);
1221         cnt += unmap->from_cnt;
1222         for (; i < cnt; i++)
1223                 dma_unmap_page(dev, unmap->addr[i], unmap->len,
1224                                DMA_FROM_DEVICE);
1225         cnt += unmap->bidi_cnt;
1226         for (; i < cnt; i++) {
1227                 if (unmap->addr[i] == 0)
1228                         continue;
1229                 dma_unmap_page(dev, unmap->addr[i], unmap->len,
1230                                DMA_BIDIRECTIONAL);
1231         }
1232         cnt = unmap->map_cnt;
1233         mempool_free(unmap, __get_unmap_pool(cnt)->pool);
1234 }
1235
1236 void dmaengine_unmap_put(struct dmaengine_unmap_data *unmap)
1237 {
1238         if (unmap)
1239                 kref_put(&unmap->kref, dmaengine_unmap);
1240 }
1241 EXPORT_SYMBOL_GPL(dmaengine_unmap_put);
1242
1243 static void dmaengine_destroy_unmap_pool(void)
1244 {
1245         int i;
1246
1247         for (i = 0; i < ARRAY_SIZE(unmap_pool); i++) {
1248                 struct dmaengine_unmap_pool *p = &unmap_pool[i];
1249
1250                 mempool_destroy(p->pool);
1251                 p->pool = NULL;
1252                 kmem_cache_destroy(p->cache);
1253                 p->cache = NULL;
1254         }
1255 }
1256
1257 static int __init dmaengine_init_unmap_pool(void)
1258 {
1259         int i;
1260
1261         for (i = 0; i < ARRAY_SIZE(unmap_pool); i++) {
1262                 struct dmaengine_unmap_pool *p = &unmap_pool[i];
1263                 size_t size;
1264
1265                 size = sizeof(struct dmaengine_unmap_data) +
1266                        sizeof(dma_addr_t) * p->size;
1267
1268                 p->cache = kmem_cache_create(p->name, size, 0,
1269                                              SLAB_HWCACHE_ALIGN, NULL);
1270                 if (!p->cache)
1271                         break;
1272                 p->pool = mempool_create_slab_pool(1, p->cache);
1273                 if (!p->pool)
1274                         break;
1275         }
1276
1277         if (i == ARRAY_SIZE(unmap_pool))
1278                 return 0;
1279
1280         dmaengine_destroy_unmap_pool();
1281         return -ENOMEM;
1282 }
1283
1284 struct dmaengine_unmap_data *
1285 dmaengine_get_unmap_data(struct device *dev, int nr, gfp_t flags)
1286 {
1287         struct dmaengine_unmap_data *unmap;
1288
1289         unmap = mempool_alloc(__get_unmap_pool(nr)->pool, flags);
1290         if (!unmap)
1291                 return NULL;
1292
1293         memset(unmap, 0, sizeof(*unmap));
1294         kref_init(&unmap->kref);
1295         unmap->dev = dev;
1296         unmap->map_cnt = nr;
1297
1298         return unmap;
1299 }
1300 EXPORT_SYMBOL(dmaengine_get_unmap_data);
1301
1302 void dma_async_tx_descriptor_init(struct dma_async_tx_descriptor *tx,
1303         struct dma_chan *chan)
1304 {
1305         tx->chan = chan;
1306         #ifdef CONFIG_ASYNC_TX_ENABLE_CHANNEL_SWITCH
1307         spin_lock_init(&tx->lock);
1308         #endif
1309 }
1310 EXPORT_SYMBOL(dma_async_tx_descriptor_init);
1311
1312 /* dma_wait_for_async_tx - spin wait for a transaction to complete
1313  * @tx: in-flight transaction to wait on
1314  */
1315 enum dma_status
1316 dma_wait_for_async_tx(struct dma_async_tx_descriptor *tx)
1317 {
1318         unsigned long dma_sync_wait_timeout = jiffies + msecs_to_jiffies(5000);
1319
1320         if (!tx)
1321                 return DMA_COMPLETE;
1322
1323         while (tx->cookie == -EBUSY) {
1324                 if (time_after_eq(jiffies, dma_sync_wait_timeout)) {
1325                         dev_err(tx->chan->device->dev,
1326                                 "%s timeout waiting for descriptor submission\n",
1327                                 __func__);
1328                         return DMA_ERROR;
1329                 }
1330                 cpu_relax();
1331         }
1332         return dma_sync_wait(tx->chan, tx->cookie);
1333 }
1334 EXPORT_SYMBOL_GPL(dma_wait_for_async_tx);
1335
1336 /* dma_run_dependencies - helper routine for dma drivers to process
1337  *      (start) dependent operations on their target channel
1338  * @tx: transaction with dependencies
1339  */
1340 void dma_run_dependencies(struct dma_async_tx_descriptor *tx)
1341 {
1342         struct dma_async_tx_descriptor *dep = txd_next(tx);
1343         struct dma_async_tx_descriptor *dep_next;
1344         struct dma_chan *chan;
1345
1346         if (!dep)
1347                 return;
1348
1349         /* we'll submit tx->next now, so clear the link */
1350         txd_clear_next(tx);
1351         chan = dep->chan;
1352
1353         /* keep submitting up until a channel switch is detected
1354          * in that case we will be called again as a result of
1355          * processing the interrupt from async_tx_channel_switch
1356          */
1357         for (; dep; dep = dep_next) {
1358                 txd_lock(dep);
1359                 txd_clear_parent(dep);
1360                 dep_next = txd_next(dep);
1361                 if (dep_next && dep_next->chan == chan)
1362                         txd_clear_next(dep); /* ->next will be submitted */
1363                 else
1364                         dep_next = NULL; /* submit current dep and terminate */
1365                 txd_unlock(dep);
1366
1367                 dep->tx_submit(dep);
1368         }
1369
1370         chan->device->device_issue_pending(chan);
1371 }
1372 EXPORT_SYMBOL_GPL(dma_run_dependencies);
1373
1374 static int __init dma_bus_init(void)
1375 {
1376         int err = dmaengine_init_unmap_pool();
1377
1378         if (err)
1379                 return err;
1380         return class_register(&dma_devclass);
1381 }
1382 arch_initcall(dma_bus_init);
1383
1384