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