1/*
2 * Freescale DMA ALSA SoC PCM driver
3 *
4 * Author: Timur Tabi <timur@freescale.com>
5 *
6 * Copyright 2007-2010 Freescale Semiconductor, Inc.
7 *
8 * This file is licensed under the terms of the GNU General Public License
9 * version 2.  This program is licensed "as is" without any warranty of any
10 * kind, whether express or implied.
11 *
12 * This driver implements ASoC support for the Elo DMA controller, which is
13 * the DMA controller on Freescale 83xx, 85xx, and 86xx SOCs. In ALSA terms,
14 * the PCM driver is what handles the DMA buffer.
15 */
16
17#include <linux/module.h>
18#include <linux/init.h>
19#include <linux/platform_device.h>
20#include <linux/dma-mapping.h>
21#include <linux/interrupt.h>
22#include <linux/delay.h>
23#include <linux/gfp.h>
24#include <linux/of_platform.h>
25#include <linux/list.h>
26#include <linux/slab.h>
27
28#include <sound/core.h>
29#include <sound/pcm.h>
30#include <sound/pcm_params.h>
31#include <sound/soc.h>
32
33#include <asm/io.h>
34
35#include "fsl_dma.h"
36#include "fsl_ssi.h"	/* For the offset of stx0 and srx0 */
37
38/*
39 * The formats that the DMA controller supports, which is anything
40 * that is 8, 16, or 32 bits.
41 */
42#define FSLDMA_PCM_FORMATS (SNDRV_PCM_FMTBIT_S8 	| \
43			    SNDRV_PCM_FMTBIT_U8 	| \
44			    SNDRV_PCM_FMTBIT_S16_LE     | \
45			    SNDRV_PCM_FMTBIT_S16_BE     | \
46			    SNDRV_PCM_FMTBIT_U16_LE     | \
47			    SNDRV_PCM_FMTBIT_U16_BE     | \
48			    SNDRV_PCM_FMTBIT_S24_LE     | \
49			    SNDRV_PCM_FMTBIT_S24_BE     | \
50			    SNDRV_PCM_FMTBIT_U24_LE     | \
51			    SNDRV_PCM_FMTBIT_U24_BE     | \
52			    SNDRV_PCM_FMTBIT_S32_LE     | \
53			    SNDRV_PCM_FMTBIT_S32_BE     | \
54			    SNDRV_PCM_FMTBIT_U32_LE     | \
55			    SNDRV_PCM_FMTBIT_U32_BE)
56
57#define FSLDMA_PCM_RATES (SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_192000 | \
58			  SNDRV_PCM_RATE_CONTINUOUS)
59
60struct dma_object {
61	struct snd_soc_platform_driver dai;
62	dma_addr_t ssi_stx_phys;
63	dma_addr_t ssi_srx_phys;
64	unsigned int ssi_fifo_depth;
65	struct ccsr_dma_channel __iomem *channel;
66	unsigned int irq;
67	bool assigned;
68	char path[1];
69};
70
71/*
72 * The number of DMA links to use.  Two is the bare minimum, but if you
73 * have really small links you might need more.
74 */
75#define NUM_DMA_LINKS   2
76
77/** fsl_dma_private: p-substream DMA data
78 *
79 * Each substream has a 1-to-1 association with a DMA channel.
80 *
81 * The link[] array is first because it needs to be aligned on a 32-byte
82 * boundary, so putting it first will ensure alignment without padding the
83 * structure.
84 *
85 * @link[]: array of link descriptors
86 * @dma_channel: pointer to the DMA channel's registers
87 * @irq: IRQ for this DMA channel
88 * @substream: pointer to the substream object, needed by the ISR
89 * @ssi_sxx_phys: bus address of the STX or SRX register to use
90 * @ld_buf_phys: physical address of the LD buffer
91 * @current_link: index into link[] of the link currently being processed
92 * @dma_buf_phys: physical address of the DMA buffer
93 * @dma_buf_next: physical address of the next period to process
94 * @dma_buf_end: physical address of the byte after the end of the DMA
95 * @buffer period_size: the size of a single period
96 * @num_periods: the number of periods in the DMA buffer
97 */
98struct fsl_dma_private {
99	struct fsl_dma_link_descriptor link[NUM_DMA_LINKS];
100	struct ccsr_dma_channel __iomem *dma_channel;
101	unsigned int irq;
102	struct snd_pcm_substream *substream;
103	dma_addr_t ssi_sxx_phys;
104	unsigned int ssi_fifo_depth;
105	dma_addr_t ld_buf_phys;
106	unsigned int current_link;
107	dma_addr_t dma_buf_phys;
108	dma_addr_t dma_buf_next;
109	dma_addr_t dma_buf_end;
110	size_t period_size;
111	unsigned int num_periods;
112};
113
114/**
115 * fsl_dma_hardare: define characteristics of the PCM hardware.
116 *
117 * The PCM hardware is the Freescale DMA controller.  This structure defines
118 * the capabilities of that hardware.
119 *
120 * Since the sampling rate and data format are not controlled by the DMA
121 * controller, we specify no limits for those values.  The only exception is
122 * period_bytes_min, which is set to a reasonably low value to prevent the
123 * DMA controller from generating too many interrupts per second.
124 *
125 * Since each link descriptor has a 32-bit byte count field, we set
126 * period_bytes_max to the largest 32-bit number.  We also have no maximum
127 * number of periods.
128 *
129 * Note that we specify SNDRV_PCM_INFO_JOINT_DUPLEX here, but only because a
130 * limitation in the SSI driver requires the sample rates for playback and
131 * capture to be the same.
132 */
133static const struct snd_pcm_hardware fsl_dma_hardware = {
134
135	.info   		= SNDRV_PCM_INFO_INTERLEAVED |
136				  SNDRV_PCM_INFO_MMAP |
137				  SNDRV_PCM_INFO_MMAP_VALID |
138				  SNDRV_PCM_INFO_JOINT_DUPLEX |
139				  SNDRV_PCM_INFO_PAUSE,
140	.formats		= FSLDMA_PCM_FORMATS,
141	.rates  		= FSLDMA_PCM_RATES,
142	.rate_min       	= 5512,
143	.rate_max       	= 192000,
144	.period_bytes_min       = 512,  	/* A reasonable limit */
145	.period_bytes_max       = (u32) -1,
146	.periods_min    	= NUM_DMA_LINKS,
147	.periods_max    	= (unsigned int) -1,
148	.buffer_bytes_max       = 128 * 1024,   /* A reasonable limit */
149};
150
151/**
152 * fsl_dma_abort_stream: tell ALSA that the DMA transfer has aborted
153 *
154 * This function should be called by the ISR whenever the DMA controller
155 * halts data transfer.
156 */
157static void fsl_dma_abort_stream(struct snd_pcm_substream *substream)
158{
159	unsigned long flags;
160
161	snd_pcm_stream_lock_irqsave(substream, flags);
162
163	if (snd_pcm_running(substream))
164		snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
165
166	snd_pcm_stream_unlock_irqrestore(substream, flags);
167}
168
169/**
170 * fsl_dma_update_pointers - update LD pointers to point to the next period
171 *
172 * As each period is completed, this function changes the the link
173 * descriptor pointers for that period to point to the next period.
174 */
175static void fsl_dma_update_pointers(struct fsl_dma_private *dma_private)
176{
177	struct fsl_dma_link_descriptor *link =
178		&dma_private->link[dma_private->current_link];
179
180	/* Update our link descriptors to point to the next period. On a 36-bit
181	 * system, we also need to update the ESAD bits.  We also set (keep) the
182	 * snoop bits.  See the comments in fsl_dma_hw_params() about snooping.
183	 */
184	if (dma_private->substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
185		link->source_addr = cpu_to_be32(dma_private->dma_buf_next);
186#ifdef CONFIG_PHYS_64BIT
187		link->source_attr = cpu_to_be32(CCSR_DMA_ATR_SNOOP |
188			upper_32_bits(dma_private->dma_buf_next));
189#endif
190	} else {
191		link->dest_addr = cpu_to_be32(dma_private->dma_buf_next);
192#ifdef CONFIG_PHYS_64BIT
193		link->dest_attr = cpu_to_be32(CCSR_DMA_ATR_SNOOP |
194			upper_32_bits(dma_private->dma_buf_next));
195#endif
196	}
197
198	/* Update our variables for next time */
199	dma_private->dma_buf_next += dma_private->period_size;
200
201	if (dma_private->dma_buf_next >= dma_private->dma_buf_end)
202		dma_private->dma_buf_next = dma_private->dma_buf_phys;
203
204	if (++dma_private->current_link >= NUM_DMA_LINKS)
205		dma_private->current_link = 0;
206}
207
208/**
209 * fsl_dma_isr: interrupt handler for the DMA controller
210 *
211 * @irq: IRQ of the DMA channel
212 * @dev_id: pointer to the dma_private structure for this DMA channel
213 */
214static irqreturn_t fsl_dma_isr(int irq, void *dev_id)
215{
216	struct fsl_dma_private *dma_private = dev_id;
217	struct snd_pcm_substream *substream = dma_private->substream;
218	struct snd_soc_pcm_runtime *rtd = substream->private_data;
219	struct device *dev = rtd->platform->dev;
220	struct ccsr_dma_channel __iomem *dma_channel = dma_private->dma_channel;
221	irqreturn_t ret = IRQ_NONE;
222	u32 sr, sr2 = 0;
223
224	/* We got an interrupt, so read the status register to see what we
225	   were interrupted for.
226	 */
227	sr = in_be32(&dma_channel->sr);
228
229	if (sr & CCSR_DMA_SR_TE) {
230		dev_err(dev, "dma transmit error\n");
231		fsl_dma_abort_stream(substream);
232		sr2 |= CCSR_DMA_SR_TE;
233		ret = IRQ_HANDLED;
234	}
235
236	if (sr & CCSR_DMA_SR_CH)
237		ret = IRQ_HANDLED;
238
239	if (sr & CCSR_DMA_SR_PE) {
240		dev_err(dev, "dma programming error\n");
241		fsl_dma_abort_stream(substream);
242		sr2 |= CCSR_DMA_SR_PE;
243		ret = IRQ_HANDLED;
244	}
245
246	if (sr & CCSR_DMA_SR_EOLNI) {
247		sr2 |= CCSR_DMA_SR_EOLNI;
248		ret = IRQ_HANDLED;
249	}
250
251	if (sr & CCSR_DMA_SR_CB)
252		ret = IRQ_HANDLED;
253
254	if (sr & CCSR_DMA_SR_EOSI) {
255		/* Tell ALSA we completed a period. */
256		snd_pcm_period_elapsed(substream);
257
258		/*
259		 * Update our link descriptors to point to the next period. We
260		 * only need to do this if the number of periods is not equal to
261		 * the number of links.
262		 */
263		if (dma_private->num_periods != NUM_DMA_LINKS)
264			fsl_dma_update_pointers(dma_private);
265
266		sr2 |= CCSR_DMA_SR_EOSI;
267		ret = IRQ_HANDLED;
268	}
269
270	if (sr & CCSR_DMA_SR_EOLSI) {
271		sr2 |= CCSR_DMA_SR_EOLSI;
272		ret = IRQ_HANDLED;
273	}
274
275	/* Clear the bits that we set */
276	if (sr2)
277		out_be32(&dma_channel->sr, sr2);
278
279	return ret;
280}
281
282/**
283 * fsl_dma_new: initialize this PCM driver.
284 *
285 * This function is called when the codec driver calls snd_soc_new_pcms(),
286 * once for each .dai_link in the machine driver's snd_soc_card
287 * structure.
288 *
289 * snd_dma_alloc_pages() is just a front-end to dma_alloc_coherent(), which
290 * (currently) always allocates the DMA buffer in lowmem, even if GFP_HIGHMEM
291 * is specified. Therefore, any DMA buffers we allocate will always be in low
292 * memory, but we support for 36-bit physical addresses anyway.
293 *
294 * Regardless of where the memory is actually allocated, since the device can
295 * technically DMA to any 36-bit address, we do need to set the DMA mask to 36.
296 */
297static int fsl_dma_new(struct snd_card *card, struct snd_soc_dai *dai,
298	struct snd_pcm *pcm)
299{
300	static u64 fsl_dma_dmamask = DMA_BIT_MASK(36);
301	int ret;
302
303	if (!card->dev->dma_mask)
304		card->dev->dma_mask = &fsl_dma_dmamask;
305
306	if (!card->dev->coherent_dma_mask)
307		card->dev->coherent_dma_mask = fsl_dma_dmamask;
308
309	/* Some codecs have separate DAIs for playback and capture, so we
310	 * should allocate a DMA buffer only for the streams that are valid.
311	 */
312
313	if (pcm->streams[0].substream) {
314		ret = snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, card->dev,
315			fsl_dma_hardware.buffer_bytes_max,
316			&pcm->streams[0].substream->dma_buffer);
317		if (ret) {
318			dev_err(card->dev, "can't alloc playback dma buffer\n");
319			return ret;
320		}
321	}
322
323	if (pcm->streams[1].substream) {
324		ret = snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, card->dev,
325			fsl_dma_hardware.buffer_bytes_max,
326			&pcm->streams[1].substream->dma_buffer);
327		if (ret) {
328			dev_err(card->dev, "can't alloc capture dma buffer\n");
329			snd_dma_free_pages(&pcm->streams[0].substream->dma_buffer);
330			return ret;
331		}
332	}
333
334	return 0;
335}
336
337/**
338 * fsl_dma_open: open a new substream.
339 *
340 * Each substream has its own DMA buffer.
341 *
342 * ALSA divides the DMA buffer into N periods.  We create NUM_DMA_LINKS link
343 * descriptors that ping-pong from one period to the next.  For example, if
344 * there are six periods and two link descriptors, this is how they look
345 * before playback starts:
346 *
347 *      	   The last link descriptor
348 *   ____________  points back to the first
349 *  |   	 |
350 *  V   	 |
351 *  ___    ___   |
352 * |   |->|   |->|
353 * |___|  |___|
354 *   |      |
355 *   |      |
356 *   V      V
357 *  _________________________________________
358 * |      |      |      |      |      |      |  The DMA buffer is
359 * |      |      |      |      |      |      |    divided into 6 parts
360 * |______|______|______|______|______|______|
361 *
362 * and here's how they look after the first period is finished playing:
363 *
364 *   ____________
365 *  |   	 |
366 *  V   	 |
367 *  ___    ___   |
368 * |   |->|   |->|
369 * |___|  |___|
370 *   |      |
371 *   |______________
372 *          |       |
373 *          V       V
374 *  _________________________________________
375 * |      |      |      |      |      |      |
376 * |      |      |      |      |      |      |
377 * |______|______|______|______|______|______|
378 *
379 * The first link descriptor now points to the third period.  The DMA
380 * controller is currently playing the second period.  When it finishes, it
381 * will jump back to the first descriptor and play the third period.
382 *
383 * There are four reasons we do this:
384 *
385 * 1. The only way to get the DMA controller to automatically restart the
386 *    transfer when it gets to the end of the buffer is to use chaining
387 *    mode.  Basic direct mode doesn't offer that feature.
388 * 2. We need to receive an interrupt at the end of every period.  The DMA
389 *    controller can generate an interrupt at the end of every link transfer
390 *    (aka segment).  Making each period into a DMA segment will give us the
391 *    interrupts we need.
392 * 3. By creating only two link descriptors, regardless of the number of
393 *    periods, we do not need to reallocate the link descriptors if the
394 *    number of periods changes.
395 * 4. All of the audio data is still stored in a single, contiguous DMA
396 *    buffer, which is what ALSA expects.  We're just dividing it into
397 *    contiguous parts, and creating a link descriptor for each one.
398 */
399static int fsl_dma_open(struct snd_pcm_substream *substream)
400{
401	struct snd_pcm_runtime *runtime = substream->runtime;
402	struct snd_soc_pcm_runtime *rtd = substream->private_data;
403	struct device *dev = rtd->platform->dev;
404	struct dma_object *dma =
405		container_of(rtd->platform->driver, struct dma_object, dai);
406	struct fsl_dma_private *dma_private;
407	struct ccsr_dma_channel __iomem *dma_channel;
408	dma_addr_t ld_buf_phys;
409	u64 temp_link;  	/* Pointer to next link descriptor */
410	u32 mr;
411	unsigned int channel;
412	int ret = 0;
413	unsigned int i;
414
415	/*
416	 * Reject any DMA buffer whose size is not a multiple of the period
417	 * size.  We need to make sure that the DMA buffer can be evenly divided
418	 * into periods.
419	 */
420	ret = snd_pcm_hw_constraint_integer(runtime,
421		SNDRV_PCM_HW_PARAM_PERIODS);
422	if (ret < 0) {
423		dev_err(dev, "invalid buffer size\n");
424		return ret;
425	}
426
427	channel = substream->stream == SNDRV_PCM_STREAM_PLAYBACK ? 0 : 1;
428
429	if (dma->assigned) {
430		dev_err(dev, "dma channel already assigned\n");
431		return -EBUSY;
432	}
433
434	dma_private = dma_alloc_coherent(dev, sizeof(struct fsl_dma_private),
435					 &ld_buf_phys, GFP_KERNEL);
436	if (!dma_private) {
437		dev_err(dev, "can't allocate dma private data\n");
438		return -ENOMEM;
439	}
440	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
441		dma_private->ssi_sxx_phys = dma->ssi_stx_phys;
442	else
443		dma_private->ssi_sxx_phys = dma->ssi_srx_phys;
444
445	dma_private->ssi_fifo_depth = dma->ssi_fifo_depth;
446	dma_private->dma_channel = dma->channel;
447	dma_private->irq = dma->irq;
448	dma_private->substream = substream;
449	dma_private->ld_buf_phys = ld_buf_phys;
450	dma_private->dma_buf_phys = substream->dma_buffer.addr;
451
452	ret = request_irq(dma_private->irq, fsl_dma_isr, 0, "fsldma-audio",
453			  dma_private);
454	if (ret) {
455		dev_err(dev, "can't register ISR for IRQ %u (ret=%i)\n",
456			dma_private->irq, ret);
457		dma_free_coherent(dev, sizeof(struct fsl_dma_private),
458			dma_private, dma_private->ld_buf_phys);
459		return ret;
460	}
461
462	dma->assigned = 1;
463
464	snd_pcm_set_runtime_buffer(substream, &substream->dma_buffer);
465	snd_soc_set_runtime_hwparams(substream, &fsl_dma_hardware);
466	runtime->private_data = dma_private;
467
468	/* Program the fixed DMA controller parameters */
469
470	dma_channel = dma_private->dma_channel;
471
472	temp_link = dma_private->ld_buf_phys +
473		sizeof(struct fsl_dma_link_descriptor);
474
475	for (i = 0; i < NUM_DMA_LINKS; i++) {
476		dma_private->link[i].next = cpu_to_be64(temp_link);
477
478		temp_link += sizeof(struct fsl_dma_link_descriptor);
479	}
480	/* The last link descriptor points to the first */
481	dma_private->link[i - 1].next = cpu_to_be64(dma_private->ld_buf_phys);
482
483	/* Tell the DMA controller where the first link descriptor is */
484	out_be32(&dma_channel->clndar,
485		CCSR_DMA_CLNDAR_ADDR(dma_private->ld_buf_phys));
486	out_be32(&dma_channel->eclndar,
487		CCSR_DMA_ECLNDAR_ADDR(dma_private->ld_buf_phys));
488
489	/* The manual says the BCR must be clear before enabling EMP */
490	out_be32(&dma_channel->bcr, 0);
491
492	/*
493	 * Program the mode register for interrupts, external master control,
494	 * and source/destination hold.  Also clear the Channel Abort bit.
495	 */
496	mr = in_be32(&dma_channel->mr) &
497		~(CCSR_DMA_MR_CA | CCSR_DMA_MR_DAHE | CCSR_DMA_MR_SAHE);
498
499	/*
500	 * We want External Master Start and External Master Pause enabled,
501	 * because the SSI is controlling the DMA controller.  We want the DMA
502	 * controller to be set up in advance, and then we signal only the SSI
503	 * to start transferring.
504	 *
505	 * We want End-Of-Segment Interrupts enabled, because this will generate
506	 * an interrupt at the end of each segment (each link descriptor
507	 * represents one segment).  Each DMA segment is the same thing as an
508	 * ALSA period, so this is how we get an interrupt at the end of every
509	 * period.
510	 *
511	 * We want Error Interrupt enabled, so that we can get an error if
512	 * the DMA controller is mis-programmed somehow.
513	 */
514	mr |= CCSR_DMA_MR_EOSIE | CCSR_DMA_MR_EIE | CCSR_DMA_MR_EMP_EN |
515		CCSR_DMA_MR_EMS_EN;
516
517	/* For playback, we want the destination address to be held.  For
518	   capture, set the source address to be held. */
519	mr |= (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) ?
520		CCSR_DMA_MR_DAHE : CCSR_DMA_MR_SAHE;
521
522	out_be32(&dma_channel->mr, mr);
523
524	return 0;
525}
526
527/**
528 * fsl_dma_hw_params: continue initializing the DMA links
529 *
530 * This function obtains hardware parameters about the opened stream and
531 * programs the DMA controller accordingly.
532 *
533 * One drawback of big-endian is that when copying integers of different
534 * sizes to a fixed-sized register, the address to which the integer must be
535 * copied is dependent on the size of the integer.
536 *
537 * For example, if P is the address of a 32-bit register, and X is a 32-bit
538 * integer, then X should be copied to address P.  However, if X is a 16-bit
539 * integer, then it should be copied to P+2.  If X is an 8-bit register,
540 * then it should be copied to P+3.
541 *
542 * So for playback of 8-bit samples, the DMA controller must transfer single
543 * bytes from the DMA buffer to the last byte of the STX0 register, i.e.
544 * offset by 3 bytes. For 16-bit samples, the offset is two bytes.
545 *
546 * For 24-bit samples, the offset is 1 byte.  However, the DMA controller
547 * does not support 3-byte copies (the DAHTS register supports only 1, 2, 4,
548 * and 8 bytes at a time).  So we do not support packed 24-bit samples.
549 * 24-bit data must be padded to 32 bits.
550 */
551static int fsl_dma_hw_params(struct snd_pcm_substream *substream,
552	struct snd_pcm_hw_params *hw_params)
553{
554	struct snd_pcm_runtime *runtime = substream->runtime;
555	struct fsl_dma_private *dma_private = runtime->private_data;
556	struct snd_soc_pcm_runtime *rtd = substream->private_data;
557	struct device *dev = rtd->platform->dev;
558
559	/* Number of bits per sample */
560	unsigned int sample_bits =
561		snd_pcm_format_physical_width(params_format(hw_params));
562
563	/* Number of bytes per frame */
564	unsigned int sample_bytes = sample_bits / 8;
565
566	/* Bus address of SSI STX register */
567	dma_addr_t ssi_sxx_phys = dma_private->ssi_sxx_phys;
568
569	/* Size of the DMA buffer, in bytes */
570	size_t buffer_size = params_buffer_bytes(hw_params);
571
572	/* Number of bytes per period */
573	size_t period_size = params_period_bytes(hw_params);
574
575	/* Pointer to next period */
576	dma_addr_t temp_addr = substream->dma_buffer.addr;
577
578	/* Pointer to DMA controller */
579	struct ccsr_dma_channel __iomem *dma_channel = dma_private->dma_channel;
580
581	u32 mr; /* DMA Mode Register */
582
583	unsigned int i;
584
585	/* Initialize our DMA tracking variables */
586	dma_private->period_size = period_size;
587	dma_private->num_periods = params_periods(hw_params);
588	dma_private->dma_buf_end = dma_private->dma_buf_phys + buffer_size;
589	dma_private->dma_buf_next = dma_private->dma_buf_phys +
590		(NUM_DMA_LINKS * period_size);
591
592	if (dma_private->dma_buf_next >= dma_private->dma_buf_end)
593		/* This happens if the number of periods == NUM_DMA_LINKS */
594		dma_private->dma_buf_next = dma_private->dma_buf_phys;
595
596	mr = in_be32(&dma_channel->mr) & ~(CCSR_DMA_MR_BWC_MASK |
597		  CCSR_DMA_MR_SAHTS_MASK | CCSR_DMA_MR_DAHTS_MASK);
598
599	/* Due to a quirk of the SSI's STX register, the target address
600	 * for the DMA operations depends on the sample size.  So we calculate
601	 * that offset here.  While we're at it, also tell the DMA controller
602	 * how much data to transfer per sample.
603	 */
604	switch (sample_bits) {
605	case 8:
606		mr |= CCSR_DMA_MR_DAHTS_1 | CCSR_DMA_MR_SAHTS_1;
607		ssi_sxx_phys += 3;
608		break;
609	case 16:
610		mr |= CCSR_DMA_MR_DAHTS_2 | CCSR_DMA_MR_SAHTS_2;
611		ssi_sxx_phys += 2;
612		break;
613	case 32:
614		mr |= CCSR_DMA_MR_DAHTS_4 | CCSR_DMA_MR_SAHTS_4;
615		break;
616	default:
617		/* We should never get here */
618		dev_err(dev, "unsupported sample size %u\n", sample_bits);
619		return -EINVAL;
620	}
621
622	/*
623	 * BWC determines how many bytes are sent/received before the DMA
624	 * controller checks the SSI to see if it needs to stop. BWC should
625	 * always be a multiple of the frame size, so that we always transmit
626	 * whole frames.  Each frame occupies two slots in the FIFO.  The
627	 * parameter for CCSR_DMA_MR_BWC() is rounded down the next power of two
628	 * (MR[BWC] can only represent even powers of two).
629	 *
630	 * To simplify the process, we set BWC to the largest value that is
631	 * less than or equal to the FIFO watermark.  For playback, this ensures
632	 * that we transfer the maximum amount without overrunning the FIFO.
633	 * For capture, this ensures that we transfer the maximum amount without
634	 * underrunning the FIFO.
635	 *
636	 * f = SSI FIFO depth
637	 * w = SSI watermark value (which equals f - 2)
638	 * b = DMA bandwidth count (in bytes)
639	 * s = sample size (in bytes, which equals frame_size * 2)
640	 *
641	 * For playback, we never transmit more than the transmit FIFO
642	 * watermark, otherwise we might write more data than the FIFO can hold.
643	 * The watermark is equal to the FIFO depth minus two.
644	 *
645	 * For capture, two equations must hold:
646	 *	w > f - (b / s)
647	 *	w >= b / s
648	 *
649	 * So, b > 2 * s, but b must also be <= s * w.  To simplify, we set
650	 * b = s * w, which is equal to
651	 *      (dma_private->ssi_fifo_depth - 2) * sample_bytes.
652	 */
653	mr |= CCSR_DMA_MR_BWC((dma_private->ssi_fifo_depth - 2) * sample_bytes);
654
655	out_be32(&dma_channel->mr, mr);
656
657	for (i = 0; i < NUM_DMA_LINKS; i++) {
658		struct fsl_dma_link_descriptor *link = &dma_private->link[i];
659
660		link->count = cpu_to_be32(period_size);
661
662		/* The snoop bit tells the DMA controller whether it should tell
663		 * the ECM to snoop during a read or write to an address. For
664		 * audio, we use DMA to transfer data between memory and an I/O
665		 * device (the SSI's STX0 or SRX0 register). Snooping is only
666		 * needed if there is a cache, so we need to snoop memory
667		 * addresses only.  For playback, that means we snoop the source
668		 * but not the destination.  For capture, we snoop the
669		 * destination but not the source.
670		 *
671		 * Note that failing to snoop properly is unlikely to cause
672		 * cache incoherency if the period size is larger than the
673		 * size of L1 cache.  This is because filling in one period will
674		 * flush out the data for the previous period.  So if you
675		 * increased period_bytes_min to a large enough size, you might
676		 * get more performance by not snooping, and you'll still be
677		 * okay.  You'll need to update fsl_dma_update_pointers() also.
678		 */
679		if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
680			link->source_addr = cpu_to_be32(temp_addr);
681			link->source_attr = cpu_to_be32(CCSR_DMA_ATR_SNOOP |
682				upper_32_bits(temp_addr));
683
684			link->dest_addr = cpu_to_be32(ssi_sxx_phys);
685			link->dest_attr = cpu_to_be32(CCSR_DMA_ATR_NOSNOOP |
686				upper_32_bits(ssi_sxx_phys));
687		} else {
688			link->source_addr = cpu_to_be32(ssi_sxx_phys);
689			link->source_attr = cpu_to_be32(CCSR_DMA_ATR_NOSNOOP |
690				upper_32_bits(ssi_sxx_phys));
691
692			link->dest_addr = cpu_to_be32(temp_addr);
693			link->dest_attr = cpu_to_be32(CCSR_DMA_ATR_SNOOP |
694				upper_32_bits(temp_addr));
695		}
696
697		temp_addr += period_size;
698	}
699
700	return 0;
701}
702
703/**
704 * fsl_dma_pointer: determine the current position of the DMA transfer
705 *
706 * This function is called by ALSA when ALSA wants to know where in the
707 * stream buffer the hardware currently is.
708 *
709 * For playback, the SAR register contains the physical address of the most
710 * recent DMA transfer.  For capture, the value is in the DAR register.
711 *
712 * The base address of the buffer is stored in the source_addr field of the
713 * first link descriptor.
714 */
715static snd_pcm_uframes_t fsl_dma_pointer(struct snd_pcm_substream *substream)
716{
717	struct snd_pcm_runtime *runtime = substream->runtime;
718	struct fsl_dma_private *dma_private = runtime->private_data;
719	struct snd_soc_pcm_runtime *rtd = substream->private_data;
720	struct device *dev = rtd->platform->dev;
721	struct ccsr_dma_channel __iomem *dma_channel = dma_private->dma_channel;
722	dma_addr_t position;
723	snd_pcm_uframes_t frames;
724
725	/* Obtain the current DMA pointer, but don't read the ESAD bits if we
726	 * only have 32-bit DMA addresses.  This function is typically called
727	 * in interrupt context, so we need to optimize it.
728	 */
729	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
730		position = in_be32(&dma_channel->sar);
731#ifdef CONFIG_PHYS_64BIT
732		position |= (u64)(in_be32(&dma_channel->satr) &
733				  CCSR_DMA_ATR_ESAD_MASK) << 32;
734#endif
735	} else {
736		position = in_be32(&dma_channel->dar);
737#ifdef CONFIG_PHYS_64BIT
738		position |= (u64)(in_be32(&dma_channel->datr) &
739				  CCSR_DMA_ATR_ESAD_MASK) << 32;
740#endif
741	}
742
743	/*
744	 * When capture is started, the SSI immediately starts to fill its FIFO.
745	 * This means that the DMA controller is not started until the FIFO is
746	 * full.  However, ALSA calls this function before that happens, when
747	 * MR.DAR is still zero.  In this case, just return zero to indicate
748	 * that nothing has been received yet.
749	 */
750	if (!position)
751		return 0;
752
753	if ((position < dma_private->dma_buf_phys) ||
754	    (position > dma_private->dma_buf_end)) {
755		dev_err(dev, "dma pointer is out of range, halting stream\n");
756		return SNDRV_PCM_POS_XRUN;
757	}
758
759	frames = bytes_to_frames(runtime, position - dma_private->dma_buf_phys);
760
761	/*
762	 * If the current address is just past the end of the buffer, wrap it
763	 * around.
764	 */
765	if (frames == runtime->buffer_size)
766		frames = 0;
767
768	return frames;
769}
770
771/**
772 * fsl_dma_hw_free: release resources allocated in fsl_dma_hw_params()
773 *
774 * Release the resources allocated in fsl_dma_hw_params() and de-program the
775 * registers.
776 *
777 * This function can be called multiple times.
778 */
779static int fsl_dma_hw_free(struct snd_pcm_substream *substream)
780{
781	struct snd_pcm_runtime *runtime = substream->runtime;
782	struct fsl_dma_private *dma_private = runtime->private_data;
783
784	if (dma_private) {
785		struct ccsr_dma_channel __iomem *dma_channel;
786
787		dma_channel = dma_private->dma_channel;
788
789		/* Stop the DMA */
790		out_be32(&dma_channel->mr, CCSR_DMA_MR_CA);
791		out_be32(&dma_channel->mr, 0);
792
793		/* Reset all the other registers */
794		out_be32(&dma_channel->sr, -1);
795		out_be32(&dma_channel->clndar, 0);
796		out_be32(&dma_channel->eclndar, 0);
797		out_be32(&dma_channel->satr, 0);
798		out_be32(&dma_channel->sar, 0);
799		out_be32(&dma_channel->datr, 0);
800		out_be32(&dma_channel->dar, 0);
801		out_be32(&dma_channel->bcr, 0);
802		out_be32(&dma_channel->nlndar, 0);
803		out_be32(&dma_channel->enlndar, 0);
804	}
805
806	return 0;
807}
808
809/**
810 * fsl_dma_close: close the stream.
811 */
812static int fsl_dma_close(struct snd_pcm_substream *substream)
813{
814	struct snd_pcm_runtime *runtime = substream->runtime;
815	struct fsl_dma_private *dma_private = runtime->private_data;
816	struct snd_soc_pcm_runtime *rtd = substream->private_data;
817	struct device *dev = rtd->platform->dev;
818	struct dma_object *dma =
819		container_of(rtd->platform->driver, struct dma_object, dai);
820
821	if (dma_private) {
822		if (dma_private->irq)
823			free_irq(dma_private->irq, dma_private);
824
825		if (dma_private->ld_buf_phys) {
826			dma_unmap_single(dev, dma_private->ld_buf_phys,
827					 sizeof(dma_private->link),
828					 DMA_TO_DEVICE);
829		}
830
831		/* Deallocate the fsl_dma_private structure */
832		dma_free_coherent(dev, sizeof(struct fsl_dma_private),
833				  dma_private, dma_private->ld_buf_phys);
834		substream->runtime->private_data = NULL;
835	}
836
837	dma->assigned = 0;
838
839	return 0;
840}
841
842/*
843 * Remove this PCM driver.
844 */
845static void fsl_dma_free_dma_buffers(struct snd_pcm *pcm)
846{
847	struct snd_pcm_substream *substream;
848	unsigned int i;
849
850	for (i = 0; i < ARRAY_SIZE(pcm->streams); i++) {
851		substream = pcm->streams[i].substream;
852		if (substream) {
853			snd_dma_free_pages(&substream->dma_buffer);
854			substream->dma_buffer.area = NULL;
855			substream->dma_buffer.addr = 0;
856		}
857	}
858}
859
860/**
861 * find_ssi_node -- returns the SSI node that points to his DMA channel node
862 *
863 * Although this DMA driver attempts to operate independently of the other
864 * devices, it still needs to determine some information about the SSI device
865 * that it's working with.  Unfortunately, the device tree does not contain
866 * a pointer from the DMA channel node to the SSI node -- the pointer goes the
867 * other way.  So we need to scan the device tree for SSI nodes until we find
868 * the one that points to the given DMA channel node.  It's ugly, but at least
869 * it's contained in this one function.
870 */
871static struct device_node *find_ssi_node(struct device_node *dma_channel_np)
872{
873	struct device_node *ssi_np, *np;
874
875	for_each_compatible_node(ssi_np, NULL, "fsl,mpc8610-ssi") {
876		/* Check each DMA phandle to see if it points to us.  We
877		 * assume that device_node pointers are a valid comparison.
878		 */
879		np = of_parse_phandle(ssi_np, "fsl,playback-dma", 0);
880		if (np == dma_channel_np)
881			return ssi_np;
882
883		np = of_parse_phandle(ssi_np, "fsl,capture-dma", 0);
884		if (np == dma_channel_np)
885			return ssi_np;
886	}
887
888	return NULL;
889}
890
891static struct snd_pcm_ops fsl_dma_ops = {
892	.open   	= fsl_dma_open,
893	.close  	= fsl_dma_close,
894	.ioctl  	= snd_pcm_lib_ioctl,
895	.hw_params      = fsl_dma_hw_params,
896	.hw_free	= fsl_dma_hw_free,
897	.pointer	= fsl_dma_pointer,
898};
899
900static int __devinit fsl_soc_dma_probe(struct platform_device *pdev)
901 {
902	struct dma_object *dma;
903	struct device_node *np = pdev->dev.of_node;
904	struct device_node *ssi_np;
905	struct resource res;
906	const uint32_t *iprop;
907	int ret;
908
909	/* Find the SSI node that points to us. */
910	ssi_np = find_ssi_node(np);
911	if (!ssi_np) {
912		dev_err(&pdev->dev, "cannot find parent SSI node\n");
913		return -ENODEV;
914	}
915
916	ret = of_address_to_resource(ssi_np, 0, &res);
917	if (ret) {
918		dev_err(&pdev->dev, "could not determine resources for %s\n",
919			ssi_np->full_name);
920		of_node_put(ssi_np);
921		return ret;
922	}
923
924	dma = kzalloc(sizeof(*dma) + strlen(np->full_name), GFP_KERNEL);
925	if (!dma) {
926		dev_err(&pdev->dev, "could not allocate dma object\n");
927		of_node_put(ssi_np);
928		return -ENOMEM;
929	}
930
931	strcpy(dma->path, np->full_name);
932	dma->dai.ops = &fsl_dma_ops;
933	dma->dai.pcm_new = fsl_dma_new;
934	dma->dai.pcm_free = fsl_dma_free_dma_buffers;
935
936	/* Store the SSI-specific information that we need */
937	dma->ssi_stx_phys = res.start + offsetof(struct ccsr_ssi, stx0);
938	dma->ssi_srx_phys = res.start + offsetof(struct ccsr_ssi, srx0);
939
940	iprop = of_get_property(ssi_np, "fsl,fifo-depth", NULL);
941	if (iprop)
942		dma->ssi_fifo_depth = *iprop;
943	else
944                /* Older 8610 DTs didn't have the fifo-depth property */
945		dma->ssi_fifo_depth = 8;
946
947	of_node_put(ssi_np);
948
949	ret = snd_soc_register_platform(&pdev->dev, &dma->dai);
950	if (ret) {
951		dev_err(&pdev->dev, "could not register platform\n");
952		kfree(dma);
953		return ret;
954	}
955
956	dma->channel = of_iomap(np, 0);
957	dma->irq = irq_of_parse_and_map(np, 0);
958
959	dev_set_drvdata(&pdev->dev, dma);
960
961	return 0;
962}
963
964static int __devexit fsl_soc_dma_remove(struct platform_device *pdev)
965{
966	struct dma_object *dma = dev_get_drvdata(&pdev->dev);
967
968	snd_soc_unregister_platform(&pdev->dev);
969	iounmap(dma->channel);
970	irq_dispose_mapping(dma->irq);
971	kfree(dma);
972
973	return 0;
974}
975
976static const struct of_device_id fsl_soc_dma_ids[] = {
977	{ .compatible = "fsl,ssi-dma-channel", },
978	{}
979};
980MODULE_DEVICE_TABLE(of, fsl_soc_dma_ids);
981
982static struct platform_driver fsl_soc_dma_driver = {
983	.driver = {
984		.name = "fsl-pcm-audio",
985		.owner = THIS_MODULE,
986		.of_match_table = fsl_soc_dma_ids,
987	},
988	.probe = fsl_soc_dma_probe,
989	.remove = __devexit_p(fsl_soc_dma_remove),
990};
991
992static int __init fsl_soc_dma_init(void)
993{
994	pr_info("Freescale Elo DMA ASoC PCM Driver\n");
995
996	return platform_driver_register(&fsl_soc_dma_driver);
997}
998
999static void __exit fsl_soc_dma_exit(void)
1000{
1001	platform_driver_unregister(&fsl_soc_dma_driver);
1002}
1003
1004module_init(fsl_soc_dma_init);
1005module_exit(fsl_soc_dma_exit);
1006
1007MODULE_AUTHOR("Timur Tabi <timur@freescale.com>");
1008MODULE_DESCRIPTION("Freescale Elo DMA ASoC PCM Driver");
1009MODULE_LICENSE("GPL v2");
1010