xref: /linux/sound/soc/stm/stm32_sai_sub.c (revision 8fc4e4aa2bfca8d32e8bc2a01526ea2da450e6cb)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * STM32 ALSA SoC Digital Audio Interface (SAI) driver.
4  *
5  * Copyright (C) 2016, STMicroelectronics - All Rights Reserved
6  * Author(s): Olivier Moysan <olivier.moysan@st.com> for STMicroelectronics.
7  */
8 
9 #include <linux/clk.h>
10 #include <linux/clk-provider.h>
11 #include <linux/kernel.h>
12 #include <linux/module.h>
13 #include <linux/of_irq.h>
14 #include <linux/of_platform.h>
15 #include <linux/pm_runtime.h>
16 #include <linux/regmap.h>
17 
18 #include <sound/asoundef.h>
19 #include <sound/core.h>
20 #include <sound/dmaengine_pcm.h>
21 #include <sound/pcm_params.h>
22 
23 #include "stm32_sai.h"
24 
25 #define SAI_FREE_PROTOCOL	0x0
26 #define SAI_SPDIF_PROTOCOL	0x1
27 
28 #define SAI_SLOT_SIZE_AUTO	0x0
29 #define SAI_SLOT_SIZE_16	0x1
30 #define SAI_SLOT_SIZE_32	0x2
31 
32 #define SAI_DATASIZE_8		0x2
33 #define SAI_DATASIZE_10		0x3
34 #define SAI_DATASIZE_16		0x4
35 #define SAI_DATASIZE_20		0x5
36 #define SAI_DATASIZE_24		0x6
37 #define SAI_DATASIZE_32		0x7
38 
39 #define STM_SAI_DAI_NAME_SIZE	15
40 
41 #define STM_SAI_IS_PLAYBACK(ip)	((ip)->dir == SNDRV_PCM_STREAM_PLAYBACK)
42 #define STM_SAI_IS_CAPTURE(ip)	((ip)->dir == SNDRV_PCM_STREAM_CAPTURE)
43 
44 #define STM_SAI_A_ID		0x0
45 #define STM_SAI_B_ID		0x1
46 
47 #define STM_SAI_IS_SUB_A(x)	((x)->id == STM_SAI_A_ID)
48 #define STM_SAI_IS_SUB_B(x)	((x)->id == STM_SAI_B_ID)
49 #define STM_SAI_BLOCK_NAME(x)	(((x)->id == STM_SAI_A_ID) ? "A" : "B")
50 
51 #define SAI_SYNC_NONE		0x0
52 #define SAI_SYNC_INTERNAL	0x1
53 #define SAI_SYNC_EXTERNAL	0x2
54 
55 #define STM_SAI_PROTOCOL_IS_SPDIF(ip)	((ip)->spdif)
56 #define STM_SAI_HAS_SPDIF(x)	((x)->pdata->conf.has_spdif_pdm)
57 #define STM_SAI_HAS_PDM(x)	((x)->pdata->conf.has_spdif_pdm)
58 #define STM_SAI_HAS_EXT_SYNC(x) (!STM_SAI_IS_F4(sai->pdata))
59 
60 #define SAI_IEC60958_BLOCK_FRAMES	192
61 #define SAI_IEC60958_STATUS_BYTES	24
62 
63 #define SAI_MCLK_NAME_LEN		32
64 #define SAI_RATE_11K			11025
65 
66 /**
67  * struct stm32_sai_sub_data - private data of SAI sub block (block A or B)
68  * @pdev: device data pointer
69  * @regmap: SAI register map pointer
70  * @regmap_config: SAI sub block register map configuration pointer
71  * @dma_params: dma configuration data for rx or tx channel
72  * @cpu_dai_drv: DAI driver data pointer
73  * @cpu_dai: DAI runtime data pointer
74  * @substream: PCM substream data pointer
75  * @pdata: SAI block parent data pointer
76  * @np_sync_provider: synchronization provider node
77  * @sai_ck: kernel clock feeding the SAI clock generator
78  * @sai_mclk: master clock from SAI mclk provider
79  * @phys_addr: SAI registers physical base address
80  * @mclk_rate: SAI block master clock frequency (Hz). set at init
81  * @id: SAI sub block id corresponding to sub-block A or B
82  * @dir: SAI block direction (playback or capture). set at init
83  * @master: SAI block mode flag. (true=master, false=slave) set at init
84  * @spdif: SAI S/PDIF iec60958 mode flag. set at init
85  * @fmt: SAI block format. relevant only for custom protocols. set at init
86  * @sync: SAI block synchronization mode. (none, internal or external)
87  * @synco: SAI block ext sync source (provider setting). (none, sub-block A/B)
88  * @synci: SAI block ext sync source (client setting). (SAI sync provider index)
89  * @fs_length: frame synchronization length. depends on protocol settings
90  * @slots: rx or tx slot number
91  * @slot_width: rx or tx slot width in bits
92  * @slot_mask: rx or tx active slots mask. set at init or at runtime
93  * @data_size: PCM data width. corresponds to PCM substream width.
94  * @spdif_frm_cnt: S/PDIF playback frame counter
95  * @iec958: iec958 data
96  * @ctrl_lock: control lock
97  * @irq_lock: prevent race condition with IRQ
98  */
99 struct stm32_sai_sub_data {
100 	struct platform_device *pdev;
101 	struct regmap *regmap;
102 	const struct regmap_config *regmap_config;
103 	struct snd_dmaengine_dai_dma_data dma_params;
104 	struct snd_soc_dai_driver cpu_dai_drv;
105 	struct snd_soc_dai *cpu_dai;
106 	struct snd_pcm_substream *substream;
107 	struct stm32_sai_data *pdata;
108 	struct device_node *np_sync_provider;
109 	struct clk *sai_ck;
110 	struct clk *sai_mclk;
111 	dma_addr_t phys_addr;
112 	unsigned int mclk_rate;
113 	unsigned int id;
114 	int dir;
115 	bool master;
116 	bool spdif;
117 	int fmt;
118 	int sync;
119 	int synco;
120 	int synci;
121 	int fs_length;
122 	int slots;
123 	int slot_width;
124 	int slot_mask;
125 	int data_size;
126 	unsigned int spdif_frm_cnt;
127 	struct snd_aes_iec958 iec958;
128 	struct mutex ctrl_lock; /* protect resources accessed by controls */
129 	spinlock_t irq_lock; /* used to prevent race condition with IRQ */
130 };
131 
132 enum stm32_sai_fifo_th {
133 	STM_SAI_FIFO_TH_EMPTY,
134 	STM_SAI_FIFO_TH_QUARTER,
135 	STM_SAI_FIFO_TH_HALF,
136 	STM_SAI_FIFO_TH_3_QUARTER,
137 	STM_SAI_FIFO_TH_FULL,
138 };
139 
140 static bool stm32_sai_sub_readable_reg(struct device *dev, unsigned int reg)
141 {
142 	switch (reg) {
143 	case STM_SAI_CR1_REGX:
144 	case STM_SAI_CR2_REGX:
145 	case STM_SAI_FRCR_REGX:
146 	case STM_SAI_SLOTR_REGX:
147 	case STM_SAI_IMR_REGX:
148 	case STM_SAI_SR_REGX:
149 	case STM_SAI_CLRFR_REGX:
150 	case STM_SAI_DR_REGX:
151 	case STM_SAI_PDMCR_REGX:
152 	case STM_SAI_PDMLY_REGX:
153 		return true;
154 	default:
155 		return false;
156 	}
157 }
158 
159 static bool stm32_sai_sub_volatile_reg(struct device *dev, unsigned int reg)
160 {
161 	switch (reg) {
162 	case STM_SAI_DR_REGX:
163 	case STM_SAI_SR_REGX:
164 		return true;
165 	default:
166 		return false;
167 	}
168 }
169 
170 static bool stm32_sai_sub_writeable_reg(struct device *dev, unsigned int reg)
171 {
172 	switch (reg) {
173 	case STM_SAI_CR1_REGX:
174 	case STM_SAI_CR2_REGX:
175 	case STM_SAI_FRCR_REGX:
176 	case STM_SAI_SLOTR_REGX:
177 	case STM_SAI_IMR_REGX:
178 	case STM_SAI_CLRFR_REGX:
179 	case STM_SAI_DR_REGX:
180 	case STM_SAI_PDMCR_REGX:
181 	case STM_SAI_PDMLY_REGX:
182 		return true;
183 	default:
184 		return false;
185 	}
186 }
187 
188 static int stm32_sai_sub_reg_up(struct stm32_sai_sub_data *sai,
189 				unsigned int reg, unsigned int mask,
190 				unsigned int val)
191 {
192 	int ret;
193 
194 	ret = clk_enable(sai->pdata->pclk);
195 	if (ret < 0)
196 		return ret;
197 
198 	ret = regmap_update_bits(sai->regmap, reg, mask, val);
199 
200 	clk_disable(sai->pdata->pclk);
201 
202 	return ret;
203 }
204 
205 static int stm32_sai_sub_reg_wr(struct stm32_sai_sub_data *sai,
206 				unsigned int reg, unsigned int mask,
207 				unsigned int val)
208 {
209 	int ret;
210 
211 	ret = clk_enable(sai->pdata->pclk);
212 	if (ret < 0)
213 		return ret;
214 
215 	ret = regmap_write_bits(sai->regmap, reg, mask, val);
216 
217 	clk_disable(sai->pdata->pclk);
218 
219 	return ret;
220 }
221 
222 static int stm32_sai_sub_reg_rd(struct stm32_sai_sub_data *sai,
223 				unsigned int reg, unsigned int *val)
224 {
225 	int ret;
226 
227 	ret = clk_enable(sai->pdata->pclk);
228 	if (ret < 0)
229 		return ret;
230 
231 	ret = regmap_read(sai->regmap, reg, val);
232 
233 	clk_disable(sai->pdata->pclk);
234 
235 	return ret;
236 }
237 
238 static const struct regmap_config stm32_sai_sub_regmap_config_f4 = {
239 	.reg_bits = 32,
240 	.reg_stride = 4,
241 	.val_bits = 32,
242 	.max_register = STM_SAI_DR_REGX,
243 	.readable_reg = stm32_sai_sub_readable_reg,
244 	.volatile_reg = stm32_sai_sub_volatile_reg,
245 	.writeable_reg = stm32_sai_sub_writeable_reg,
246 	.fast_io = true,
247 	.cache_type = REGCACHE_FLAT,
248 };
249 
250 static const struct regmap_config stm32_sai_sub_regmap_config_h7 = {
251 	.reg_bits = 32,
252 	.reg_stride = 4,
253 	.val_bits = 32,
254 	.max_register = STM_SAI_PDMLY_REGX,
255 	.readable_reg = stm32_sai_sub_readable_reg,
256 	.volatile_reg = stm32_sai_sub_volatile_reg,
257 	.writeable_reg = stm32_sai_sub_writeable_reg,
258 	.fast_io = true,
259 	.cache_type = REGCACHE_FLAT,
260 };
261 
262 static int snd_pcm_iec958_info(struct snd_kcontrol *kcontrol,
263 			       struct snd_ctl_elem_info *uinfo)
264 {
265 	uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
266 	uinfo->count = 1;
267 
268 	return 0;
269 }
270 
271 static int snd_pcm_iec958_get(struct snd_kcontrol *kcontrol,
272 			      struct snd_ctl_elem_value *uctl)
273 {
274 	struct stm32_sai_sub_data *sai = snd_kcontrol_chip(kcontrol);
275 
276 	mutex_lock(&sai->ctrl_lock);
277 	memcpy(uctl->value.iec958.status, sai->iec958.status, 4);
278 	mutex_unlock(&sai->ctrl_lock);
279 
280 	return 0;
281 }
282 
283 static int snd_pcm_iec958_put(struct snd_kcontrol *kcontrol,
284 			      struct snd_ctl_elem_value *uctl)
285 {
286 	struct stm32_sai_sub_data *sai = snd_kcontrol_chip(kcontrol);
287 
288 	mutex_lock(&sai->ctrl_lock);
289 	memcpy(sai->iec958.status, uctl->value.iec958.status, 4);
290 	mutex_unlock(&sai->ctrl_lock);
291 
292 	return 0;
293 }
294 
295 static const struct snd_kcontrol_new iec958_ctls = {
296 	.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
297 			SNDRV_CTL_ELEM_ACCESS_VOLATILE),
298 	.iface = SNDRV_CTL_ELEM_IFACE_PCM,
299 	.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, DEFAULT),
300 	.info = snd_pcm_iec958_info,
301 	.get = snd_pcm_iec958_get,
302 	.put = snd_pcm_iec958_put,
303 };
304 
305 struct stm32_sai_mclk_data {
306 	struct clk_hw hw;
307 	unsigned long freq;
308 	struct stm32_sai_sub_data *sai_data;
309 };
310 
311 #define to_mclk_data(_hw) container_of(_hw, struct stm32_sai_mclk_data, hw)
312 #define STM32_SAI_MAX_CLKS 1
313 
314 static int stm32_sai_get_clk_div(struct stm32_sai_sub_data *sai,
315 				 unsigned long input_rate,
316 				 unsigned long output_rate)
317 {
318 	int version = sai->pdata->conf.version;
319 	int div;
320 
321 	div = DIV_ROUND_CLOSEST(input_rate, output_rate);
322 	if (div > SAI_XCR1_MCKDIV_MAX(version)) {
323 		dev_err(&sai->pdev->dev, "Divider %d out of range\n", div);
324 		return -EINVAL;
325 	}
326 	dev_dbg(&sai->pdev->dev, "SAI divider %d\n", div);
327 
328 	if (input_rate % div)
329 		dev_dbg(&sai->pdev->dev,
330 			"Rate not accurate. requested (%ld), actual (%ld)\n",
331 			output_rate, input_rate / div);
332 
333 	return div;
334 }
335 
336 static int stm32_sai_set_clk_div(struct stm32_sai_sub_data *sai,
337 				 unsigned int div)
338 {
339 	int version = sai->pdata->conf.version;
340 	int ret, cr1, mask;
341 
342 	if (div > SAI_XCR1_MCKDIV_MAX(version)) {
343 		dev_err(&sai->pdev->dev, "Divider %d out of range\n", div);
344 		return -EINVAL;
345 	}
346 
347 	mask = SAI_XCR1_MCKDIV_MASK(SAI_XCR1_MCKDIV_WIDTH(version));
348 	cr1 = SAI_XCR1_MCKDIV_SET(div);
349 	ret = stm32_sai_sub_reg_up(sai, STM_SAI_CR1_REGX, mask, cr1);
350 	if (ret < 0)
351 		dev_err(&sai->pdev->dev, "Failed to update CR1 register\n");
352 
353 	return ret;
354 }
355 
356 static int stm32_sai_set_parent_clock(struct stm32_sai_sub_data *sai,
357 				      unsigned int rate)
358 {
359 	struct platform_device *pdev = sai->pdev;
360 	struct clk *parent_clk = sai->pdata->clk_x8k;
361 	int ret;
362 
363 	if (!(rate % SAI_RATE_11K))
364 		parent_clk = sai->pdata->clk_x11k;
365 
366 	ret = clk_set_parent(sai->sai_ck, parent_clk);
367 	if (ret)
368 		dev_err(&pdev->dev, " Error %d setting sai_ck parent clock. %s",
369 			ret, ret == -EBUSY ?
370 			"Active stream rates conflict\n" : "\n");
371 
372 	return ret;
373 }
374 
375 static long stm32_sai_mclk_round_rate(struct clk_hw *hw, unsigned long rate,
376 				      unsigned long *prate)
377 {
378 	struct stm32_sai_mclk_data *mclk = to_mclk_data(hw);
379 	struct stm32_sai_sub_data *sai = mclk->sai_data;
380 	int div;
381 
382 	div = stm32_sai_get_clk_div(sai, *prate, rate);
383 	if (div < 0)
384 		return div;
385 
386 	mclk->freq = *prate / div;
387 
388 	return mclk->freq;
389 }
390 
391 static unsigned long stm32_sai_mclk_recalc_rate(struct clk_hw *hw,
392 						unsigned long parent_rate)
393 {
394 	struct stm32_sai_mclk_data *mclk = to_mclk_data(hw);
395 
396 	return mclk->freq;
397 }
398 
399 static int stm32_sai_mclk_set_rate(struct clk_hw *hw, unsigned long rate,
400 				   unsigned long parent_rate)
401 {
402 	struct stm32_sai_mclk_data *mclk = to_mclk_data(hw);
403 	struct stm32_sai_sub_data *sai = mclk->sai_data;
404 	int div, ret;
405 
406 	div = stm32_sai_get_clk_div(sai, parent_rate, rate);
407 	if (div < 0)
408 		return div;
409 
410 	ret = stm32_sai_set_clk_div(sai, div);
411 	if (ret)
412 		return ret;
413 
414 	mclk->freq = rate;
415 
416 	return 0;
417 }
418 
419 static int stm32_sai_mclk_enable(struct clk_hw *hw)
420 {
421 	struct stm32_sai_mclk_data *mclk = to_mclk_data(hw);
422 	struct stm32_sai_sub_data *sai = mclk->sai_data;
423 
424 	dev_dbg(&sai->pdev->dev, "Enable master clock\n");
425 
426 	return stm32_sai_sub_reg_up(sai, STM_SAI_CR1_REGX,
427 				    SAI_XCR1_MCKEN, SAI_XCR1_MCKEN);
428 }
429 
430 static void stm32_sai_mclk_disable(struct clk_hw *hw)
431 {
432 	struct stm32_sai_mclk_data *mclk = to_mclk_data(hw);
433 	struct stm32_sai_sub_data *sai = mclk->sai_data;
434 
435 	dev_dbg(&sai->pdev->dev, "Disable master clock\n");
436 
437 	stm32_sai_sub_reg_up(sai, STM_SAI_CR1_REGX, SAI_XCR1_MCKEN, 0);
438 }
439 
440 static const struct clk_ops mclk_ops = {
441 	.enable = stm32_sai_mclk_enable,
442 	.disable = stm32_sai_mclk_disable,
443 	.recalc_rate = stm32_sai_mclk_recalc_rate,
444 	.round_rate = stm32_sai_mclk_round_rate,
445 	.set_rate = stm32_sai_mclk_set_rate,
446 };
447 
448 static int stm32_sai_add_mclk_provider(struct stm32_sai_sub_data *sai)
449 {
450 	struct clk_hw *hw;
451 	struct stm32_sai_mclk_data *mclk;
452 	struct device *dev = &sai->pdev->dev;
453 	const char *pname = __clk_get_name(sai->sai_ck);
454 	char *mclk_name, *p, *s = (char *)pname;
455 	int ret, i = 0;
456 
457 	mclk = devm_kzalloc(dev, sizeof(*mclk), GFP_KERNEL);
458 	if (!mclk)
459 		return -ENOMEM;
460 
461 	mclk_name = devm_kcalloc(dev, sizeof(char),
462 				 SAI_MCLK_NAME_LEN, GFP_KERNEL);
463 	if (!mclk_name)
464 		return -ENOMEM;
465 
466 	/*
467 	 * Forge mclk clock name from parent clock name and suffix.
468 	 * String after "_" char is stripped in parent name.
469 	 */
470 	p = mclk_name;
471 	while (*s && *s != '_' && (i < (SAI_MCLK_NAME_LEN - 7))) {
472 		*p++ = *s++;
473 		i++;
474 	}
475 	STM_SAI_IS_SUB_A(sai) ? strcat(p, "a_mclk") : strcat(p, "b_mclk");
476 
477 	mclk->hw.init = CLK_HW_INIT(mclk_name, pname, &mclk_ops, 0);
478 	mclk->sai_data = sai;
479 	hw = &mclk->hw;
480 
481 	dev_dbg(dev, "Register master clock %s\n", mclk_name);
482 	ret = devm_clk_hw_register(&sai->pdev->dev, hw);
483 	if (ret) {
484 		dev_err(dev, "mclk register returned %d\n", ret);
485 		return ret;
486 	}
487 
488 	sai->sai_mclk = devm_clk_hw_get_clk(dev, hw, NULL);
489 	if (IS_ERR(sai->sai_mclk))
490 		return PTR_ERR(sai->sai_mclk);
491 
492 	/* register mclk provider */
493 	return devm_of_clk_add_hw_provider(dev, of_clk_hw_simple_get, hw);
494 }
495 
496 static irqreturn_t stm32_sai_isr(int irq, void *devid)
497 {
498 	struct stm32_sai_sub_data *sai = (struct stm32_sai_sub_data *)devid;
499 	struct platform_device *pdev = sai->pdev;
500 	unsigned int sr, imr, flags;
501 	snd_pcm_state_t status = SNDRV_PCM_STATE_RUNNING;
502 
503 	stm32_sai_sub_reg_rd(sai, STM_SAI_IMR_REGX, &imr);
504 	stm32_sai_sub_reg_rd(sai, STM_SAI_SR_REGX, &sr);
505 
506 	flags = sr & imr;
507 	if (!flags)
508 		return IRQ_NONE;
509 
510 	stm32_sai_sub_reg_wr(sai, STM_SAI_CLRFR_REGX, SAI_XCLRFR_MASK,
511 			     SAI_XCLRFR_MASK);
512 
513 	if (!sai->substream) {
514 		dev_err(&pdev->dev, "Device stopped. Spurious IRQ 0x%x\n", sr);
515 		return IRQ_NONE;
516 	}
517 
518 	if (flags & SAI_XIMR_OVRUDRIE) {
519 		dev_err(&pdev->dev, "IRQ %s\n",
520 			STM_SAI_IS_PLAYBACK(sai) ? "underrun" : "overrun");
521 		status = SNDRV_PCM_STATE_XRUN;
522 	}
523 
524 	if (flags & SAI_XIMR_MUTEDETIE)
525 		dev_dbg(&pdev->dev, "IRQ mute detected\n");
526 
527 	if (flags & SAI_XIMR_WCKCFGIE) {
528 		dev_err(&pdev->dev, "IRQ wrong clock configuration\n");
529 		status = SNDRV_PCM_STATE_DISCONNECTED;
530 	}
531 
532 	if (flags & SAI_XIMR_CNRDYIE)
533 		dev_err(&pdev->dev, "IRQ Codec not ready\n");
534 
535 	if (flags & SAI_XIMR_AFSDETIE) {
536 		dev_err(&pdev->dev, "IRQ Anticipated frame synchro\n");
537 		status = SNDRV_PCM_STATE_XRUN;
538 	}
539 
540 	if (flags & SAI_XIMR_LFSDETIE) {
541 		dev_err(&pdev->dev, "IRQ Late frame synchro\n");
542 		status = SNDRV_PCM_STATE_XRUN;
543 	}
544 
545 	spin_lock(&sai->irq_lock);
546 	if (status != SNDRV_PCM_STATE_RUNNING && sai->substream)
547 		snd_pcm_stop_xrun(sai->substream);
548 	spin_unlock(&sai->irq_lock);
549 
550 	return IRQ_HANDLED;
551 }
552 
553 static int stm32_sai_set_sysclk(struct snd_soc_dai *cpu_dai,
554 				int clk_id, unsigned int freq, int dir)
555 {
556 	struct stm32_sai_sub_data *sai = snd_soc_dai_get_drvdata(cpu_dai);
557 	int ret;
558 
559 	if (dir == SND_SOC_CLOCK_OUT && sai->sai_mclk) {
560 		ret = stm32_sai_sub_reg_up(sai, STM_SAI_CR1_REGX,
561 					   SAI_XCR1_NODIV,
562 					 freq ? 0 : SAI_XCR1_NODIV);
563 		if (ret < 0)
564 			return ret;
565 
566 		/* Assume shutdown if requested frequency is 0Hz */
567 		if (!freq) {
568 			/* Release mclk rate only if rate was actually set */
569 			if (sai->mclk_rate) {
570 				clk_rate_exclusive_put(sai->sai_mclk);
571 				sai->mclk_rate = 0;
572 			}
573 			return 0;
574 		}
575 
576 		/* If master clock is used, set parent clock now */
577 		ret = stm32_sai_set_parent_clock(sai, freq);
578 		if (ret)
579 			return ret;
580 
581 		ret = clk_set_rate_exclusive(sai->sai_mclk, freq);
582 		if (ret) {
583 			dev_err(cpu_dai->dev,
584 				ret == -EBUSY ?
585 				"Active streams have incompatible rates" :
586 				"Could not set mclk rate\n");
587 			return ret;
588 		}
589 
590 		dev_dbg(cpu_dai->dev, "SAI MCLK frequency is %uHz\n", freq);
591 		sai->mclk_rate = freq;
592 	}
593 
594 	return 0;
595 }
596 
597 static int stm32_sai_set_dai_tdm_slot(struct snd_soc_dai *cpu_dai, u32 tx_mask,
598 				      u32 rx_mask, int slots, int slot_width)
599 {
600 	struct stm32_sai_sub_data *sai = snd_soc_dai_get_drvdata(cpu_dai);
601 	int slotr, slotr_mask, slot_size;
602 
603 	if (STM_SAI_PROTOCOL_IS_SPDIF(sai)) {
604 		dev_warn(cpu_dai->dev, "Slot setting relevant only for TDM\n");
605 		return 0;
606 	}
607 
608 	dev_dbg(cpu_dai->dev, "Masks tx/rx:%#x/%#x, slots:%d, width:%d\n",
609 		tx_mask, rx_mask, slots, slot_width);
610 
611 	switch (slot_width) {
612 	case 16:
613 		slot_size = SAI_SLOT_SIZE_16;
614 		break;
615 	case 32:
616 		slot_size = SAI_SLOT_SIZE_32;
617 		break;
618 	default:
619 		slot_size = SAI_SLOT_SIZE_AUTO;
620 		break;
621 	}
622 
623 	slotr = SAI_XSLOTR_SLOTSZ_SET(slot_size) |
624 		SAI_XSLOTR_NBSLOT_SET(slots - 1);
625 	slotr_mask = SAI_XSLOTR_SLOTSZ_MASK | SAI_XSLOTR_NBSLOT_MASK;
626 
627 	/* tx/rx mask set in machine init, if slot number defined in DT */
628 	if (STM_SAI_IS_PLAYBACK(sai)) {
629 		sai->slot_mask = tx_mask;
630 		slotr |= SAI_XSLOTR_SLOTEN_SET(tx_mask);
631 	}
632 
633 	if (STM_SAI_IS_CAPTURE(sai)) {
634 		sai->slot_mask = rx_mask;
635 		slotr |= SAI_XSLOTR_SLOTEN_SET(rx_mask);
636 	}
637 
638 	slotr_mask |= SAI_XSLOTR_SLOTEN_MASK;
639 
640 	stm32_sai_sub_reg_up(sai, STM_SAI_SLOTR_REGX, slotr_mask, slotr);
641 
642 	sai->slot_width = slot_width;
643 	sai->slots = slots;
644 
645 	return 0;
646 }
647 
648 static int stm32_sai_set_dai_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt)
649 {
650 	struct stm32_sai_sub_data *sai = snd_soc_dai_get_drvdata(cpu_dai);
651 	int cr1, frcr = 0;
652 	int cr1_mask, frcr_mask = 0;
653 	int ret;
654 
655 	dev_dbg(cpu_dai->dev, "fmt %x\n", fmt);
656 
657 	/* Do not generate master by default */
658 	cr1 = SAI_XCR1_NODIV;
659 	cr1_mask = SAI_XCR1_NODIV;
660 
661 	cr1_mask |= SAI_XCR1_PRTCFG_MASK;
662 	if (STM_SAI_PROTOCOL_IS_SPDIF(sai)) {
663 		cr1 |= SAI_XCR1_PRTCFG_SET(SAI_SPDIF_PROTOCOL);
664 		goto conf_update;
665 	}
666 
667 	cr1 |= SAI_XCR1_PRTCFG_SET(SAI_FREE_PROTOCOL);
668 
669 	switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
670 	/* SCK active high for all protocols */
671 	case SND_SOC_DAIFMT_I2S:
672 		cr1 |= SAI_XCR1_CKSTR;
673 		frcr |= SAI_XFRCR_FSOFF | SAI_XFRCR_FSDEF;
674 		break;
675 	/* Left justified */
676 	case SND_SOC_DAIFMT_MSB:
677 		frcr |= SAI_XFRCR_FSPOL | SAI_XFRCR_FSDEF;
678 		break;
679 	/* Right justified */
680 	case SND_SOC_DAIFMT_LSB:
681 		frcr |= SAI_XFRCR_FSPOL | SAI_XFRCR_FSDEF;
682 		break;
683 	case SND_SOC_DAIFMT_DSP_A:
684 		frcr |= SAI_XFRCR_FSPOL | SAI_XFRCR_FSOFF;
685 		break;
686 	case SND_SOC_DAIFMT_DSP_B:
687 		frcr |= SAI_XFRCR_FSPOL;
688 		break;
689 	default:
690 		dev_err(cpu_dai->dev, "Unsupported protocol %#x\n",
691 			fmt & SND_SOC_DAIFMT_FORMAT_MASK);
692 		return -EINVAL;
693 	}
694 
695 	cr1_mask |= SAI_XCR1_CKSTR;
696 	frcr_mask |= SAI_XFRCR_FSPOL | SAI_XFRCR_FSOFF |
697 		     SAI_XFRCR_FSDEF;
698 
699 	/* DAI clock strobing. Invert setting previously set */
700 	switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
701 	case SND_SOC_DAIFMT_NB_NF:
702 		break;
703 	case SND_SOC_DAIFMT_IB_NF:
704 		cr1 ^= SAI_XCR1_CKSTR;
705 		break;
706 	case SND_SOC_DAIFMT_NB_IF:
707 		frcr ^= SAI_XFRCR_FSPOL;
708 		break;
709 	case SND_SOC_DAIFMT_IB_IF:
710 		/* Invert fs & sck */
711 		cr1 ^= SAI_XCR1_CKSTR;
712 		frcr ^= SAI_XFRCR_FSPOL;
713 		break;
714 	default:
715 		dev_err(cpu_dai->dev, "Unsupported strobing %#x\n",
716 			fmt & SND_SOC_DAIFMT_INV_MASK);
717 		return -EINVAL;
718 	}
719 	cr1_mask |= SAI_XCR1_CKSTR;
720 	frcr_mask |= SAI_XFRCR_FSPOL;
721 
722 	stm32_sai_sub_reg_up(sai, STM_SAI_FRCR_REGX, frcr_mask, frcr);
723 
724 	/* DAI clock master masks */
725 	switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
726 	case SND_SOC_DAIFMT_CBM_CFM:
727 		/* codec is master */
728 		cr1 |= SAI_XCR1_SLAVE;
729 		sai->master = false;
730 		break;
731 	case SND_SOC_DAIFMT_CBS_CFS:
732 		sai->master = true;
733 		break;
734 	default:
735 		dev_err(cpu_dai->dev, "Unsupported mode %#x\n",
736 			fmt & SND_SOC_DAIFMT_MASTER_MASK);
737 		return -EINVAL;
738 	}
739 
740 	/* Set slave mode if sub-block is synchronized with another SAI */
741 	if (sai->sync) {
742 		dev_dbg(cpu_dai->dev, "Synchronized SAI configured as slave\n");
743 		cr1 |= SAI_XCR1_SLAVE;
744 		sai->master = false;
745 	}
746 
747 	cr1_mask |= SAI_XCR1_SLAVE;
748 
749 conf_update:
750 	ret = stm32_sai_sub_reg_up(sai, STM_SAI_CR1_REGX, cr1_mask, cr1);
751 	if (ret < 0) {
752 		dev_err(cpu_dai->dev, "Failed to update CR1 register\n");
753 		return ret;
754 	}
755 
756 	sai->fmt = fmt;
757 
758 	return 0;
759 }
760 
761 static int stm32_sai_startup(struct snd_pcm_substream *substream,
762 			     struct snd_soc_dai *cpu_dai)
763 {
764 	struct stm32_sai_sub_data *sai = snd_soc_dai_get_drvdata(cpu_dai);
765 	int imr, cr2, ret;
766 	unsigned long flags;
767 
768 	spin_lock_irqsave(&sai->irq_lock, flags);
769 	sai->substream = substream;
770 	spin_unlock_irqrestore(&sai->irq_lock, flags);
771 
772 	if (STM_SAI_PROTOCOL_IS_SPDIF(sai)) {
773 		snd_pcm_hw_constraint_mask64(substream->runtime,
774 					     SNDRV_PCM_HW_PARAM_FORMAT,
775 					     SNDRV_PCM_FMTBIT_S32_LE);
776 		snd_pcm_hw_constraint_single(substream->runtime,
777 					     SNDRV_PCM_HW_PARAM_CHANNELS, 2);
778 	}
779 
780 	ret = clk_prepare_enable(sai->sai_ck);
781 	if (ret < 0) {
782 		dev_err(cpu_dai->dev, "Failed to enable clock: %d\n", ret);
783 		return ret;
784 	}
785 
786 	/* Enable ITs */
787 	stm32_sai_sub_reg_wr(sai, STM_SAI_CLRFR_REGX,
788 			     SAI_XCLRFR_MASK, SAI_XCLRFR_MASK);
789 
790 	imr = SAI_XIMR_OVRUDRIE;
791 	if (STM_SAI_IS_CAPTURE(sai)) {
792 		stm32_sai_sub_reg_rd(sai, STM_SAI_CR2_REGX, &cr2);
793 		if (cr2 & SAI_XCR2_MUTECNT_MASK)
794 			imr |= SAI_XIMR_MUTEDETIE;
795 	}
796 
797 	if (sai->master)
798 		imr |= SAI_XIMR_WCKCFGIE;
799 	else
800 		imr |= SAI_XIMR_AFSDETIE | SAI_XIMR_LFSDETIE;
801 
802 	stm32_sai_sub_reg_up(sai, STM_SAI_IMR_REGX,
803 			     SAI_XIMR_MASK, imr);
804 
805 	return 0;
806 }
807 
808 static int stm32_sai_set_config(struct snd_soc_dai *cpu_dai,
809 				struct snd_pcm_substream *substream,
810 				struct snd_pcm_hw_params *params)
811 {
812 	struct stm32_sai_sub_data *sai = snd_soc_dai_get_drvdata(cpu_dai);
813 	int cr1, cr1_mask, ret;
814 
815 	/*
816 	 * DMA bursts increment is set to 4 words.
817 	 * SAI fifo threshold is set to half fifo, to keep enough space
818 	 * for DMA incoming bursts.
819 	 */
820 	stm32_sai_sub_reg_wr(sai, STM_SAI_CR2_REGX,
821 			     SAI_XCR2_FFLUSH | SAI_XCR2_FTH_MASK,
822 			     SAI_XCR2_FFLUSH |
823 			     SAI_XCR2_FTH_SET(STM_SAI_FIFO_TH_HALF));
824 
825 	/* DS bits in CR1 not set for SPDIF (size forced to 24 bits).*/
826 	if (STM_SAI_PROTOCOL_IS_SPDIF(sai)) {
827 		sai->spdif_frm_cnt = 0;
828 		return 0;
829 	}
830 
831 	/* Mode, data format and channel config */
832 	cr1_mask = SAI_XCR1_DS_MASK;
833 	switch (params_format(params)) {
834 	case SNDRV_PCM_FORMAT_S8:
835 		cr1 = SAI_XCR1_DS_SET(SAI_DATASIZE_8);
836 		break;
837 	case SNDRV_PCM_FORMAT_S16_LE:
838 		cr1 = SAI_XCR1_DS_SET(SAI_DATASIZE_16);
839 		break;
840 	case SNDRV_PCM_FORMAT_S32_LE:
841 		cr1 = SAI_XCR1_DS_SET(SAI_DATASIZE_32);
842 		break;
843 	default:
844 		dev_err(cpu_dai->dev, "Data format not supported\n");
845 		return -EINVAL;
846 	}
847 
848 	cr1_mask |= SAI_XCR1_MONO;
849 	if ((sai->slots == 2) && (params_channels(params) == 1))
850 		cr1 |= SAI_XCR1_MONO;
851 
852 	ret = stm32_sai_sub_reg_up(sai, STM_SAI_CR1_REGX, cr1_mask, cr1);
853 	if (ret < 0) {
854 		dev_err(cpu_dai->dev, "Failed to update CR1 register\n");
855 		return ret;
856 	}
857 
858 	return 0;
859 }
860 
861 static int stm32_sai_set_slots(struct snd_soc_dai *cpu_dai)
862 {
863 	struct stm32_sai_sub_data *sai = snd_soc_dai_get_drvdata(cpu_dai);
864 	int slotr, slot_sz;
865 
866 	stm32_sai_sub_reg_rd(sai, STM_SAI_SLOTR_REGX, &slotr);
867 
868 	/*
869 	 * If SLOTSZ is set to auto in SLOTR, align slot width on data size
870 	 * By default slot width = data size, if not forced from DT
871 	 */
872 	slot_sz = slotr & SAI_XSLOTR_SLOTSZ_MASK;
873 	if (slot_sz == SAI_XSLOTR_SLOTSZ_SET(SAI_SLOT_SIZE_AUTO))
874 		sai->slot_width = sai->data_size;
875 
876 	if (sai->slot_width < sai->data_size) {
877 		dev_err(cpu_dai->dev,
878 			"Data size %d larger than slot width\n",
879 			sai->data_size);
880 		return -EINVAL;
881 	}
882 
883 	/* Slot number is set to 2, if not specified in DT */
884 	if (!sai->slots)
885 		sai->slots = 2;
886 
887 	/* The number of slots in the audio frame is equal to NBSLOT[3:0] + 1*/
888 	stm32_sai_sub_reg_up(sai, STM_SAI_SLOTR_REGX,
889 			     SAI_XSLOTR_NBSLOT_MASK,
890 			     SAI_XSLOTR_NBSLOT_SET((sai->slots - 1)));
891 
892 	/* Set default slots mask if not already set from DT */
893 	if (!(slotr & SAI_XSLOTR_SLOTEN_MASK)) {
894 		sai->slot_mask = (1 << sai->slots) - 1;
895 		stm32_sai_sub_reg_up(sai,
896 				     STM_SAI_SLOTR_REGX, SAI_XSLOTR_SLOTEN_MASK,
897 				     SAI_XSLOTR_SLOTEN_SET(sai->slot_mask));
898 	}
899 
900 	dev_dbg(cpu_dai->dev, "Slots %d, slot width %d\n",
901 		sai->slots, sai->slot_width);
902 
903 	return 0;
904 }
905 
906 static void stm32_sai_set_frame(struct snd_soc_dai *cpu_dai)
907 {
908 	struct stm32_sai_sub_data *sai = snd_soc_dai_get_drvdata(cpu_dai);
909 	int fs_active, offset, format;
910 	int frcr, frcr_mask;
911 
912 	format = sai->fmt & SND_SOC_DAIFMT_FORMAT_MASK;
913 	sai->fs_length = sai->slot_width * sai->slots;
914 
915 	fs_active = sai->fs_length / 2;
916 	if ((format == SND_SOC_DAIFMT_DSP_A) ||
917 	    (format == SND_SOC_DAIFMT_DSP_B))
918 		fs_active = 1;
919 
920 	frcr = SAI_XFRCR_FRL_SET((sai->fs_length - 1));
921 	frcr |= SAI_XFRCR_FSALL_SET((fs_active - 1));
922 	frcr_mask = SAI_XFRCR_FRL_MASK | SAI_XFRCR_FSALL_MASK;
923 
924 	dev_dbg(cpu_dai->dev, "Frame length %d, frame active %d\n",
925 		sai->fs_length, fs_active);
926 
927 	stm32_sai_sub_reg_up(sai, STM_SAI_FRCR_REGX, frcr_mask, frcr);
928 
929 	if ((sai->fmt & SND_SOC_DAIFMT_FORMAT_MASK) == SND_SOC_DAIFMT_LSB) {
930 		offset = sai->slot_width - sai->data_size;
931 
932 		stm32_sai_sub_reg_up(sai, STM_SAI_SLOTR_REGX,
933 				     SAI_XSLOTR_FBOFF_MASK,
934 				     SAI_XSLOTR_FBOFF_SET(offset));
935 	}
936 }
937 
938 static void stm32_sai_init_iec958_status(struct stm32_sai_sub_data *sai)
939 {
940 	unsigned char *cs = sai->iec958.status;
941 
942 	cs[0] = IEC958_AES0_CON_NOT_COPYRIGHT | IEC958_AES0_CON_EMPHASIS_NONE;
943 	cs[1] = IEC958_AES1_CON_GENERAL;
944 	cs[2] = IEC958_AES2_CON_SOURCE_UNSPEC | IEC958_AES2_CON_CHANNEL_UNSPEC;
945 	cs[3] = IEC958_AES3_CON_CLOCK_1000PPM | IEC958_AES3_CON_FS_NOTID;
946 }
947 
948 static void stm32_sai_set_iec958_status(struct stm32_sai_sub_data *sai,
949 					struct snd_pcm_runtime *runtime)
950 {
951 	if (!runtime)
952 		return;
953 
954 	/* Force the sample rate according to runtime rate */
955 	mutex_lock(&sai->ctrl_lock);
956 	switch (runtime->rate) {
957 	case 22050:
958 		sai->iec958.status[3] = IEC958_AES3_CON_FS_22050;
959 		break;
960 	case 44100:
961 		sai->iec958.status[3] = IEC958_AES3_CON_FS_44100;
962 		break;
963 	case 88200:
964 		sai->iec958.status[3] = IEC958_AES3_CON_FS_88200;
965 		break;
966 	case 176400:
967 		sai->iec958.status[3] = IEC958_AES3_CON_FS_176400;
968 		break;
969 	case 24000:
970 		sai->iec958.status[3] = IEC958_AES3_CON_FS_24000;
971 		break;
972 	case 48000:
973 		sai->iec958.status[3] = IEC958_AES3_CON_FS_48000;
974 		break;
975 	case 96000:
976 		sai->iec958.status[3] = IEC958_AES3_CON_FS_96000;
977 		break;
978 	case 192000:
979 		sai->iec958.status[3] = IEC958_AES3_CON_FS_192000;
980 		break;
981 	case 32000:
982 		sai->iec958.status[3] = IEC958_AES3_CON_FS_32000;
983 		break;
984 	default:
985 		sai->iec958.status[3] = IEC958_AES3_CON_FS_NOTID;
986 		break;
987 	}
988 	mutex_unlock(&sai->ctrl_lock);
989 }
990 
991 static int stm32_sai_configure_clock(struct snd_soc_dai *cpu_dai,
992 				     struct snd_pcm_hw_params *params)
993 {
994 	struct stm32_sai_sub_data *sai = snd_soc_dai_get_drvdata(cpu_dai);
995 	int div = 0, cr1 = 0;
996 	int sai_clk_rate, mclk_ratio, den;
997 	unsigned int rate = params_rate(params);
998 	int ret;
999 
1000 	if (!sai->sai_mclk) {
1001 		ret = stm32_sai_set_parent_clock(sai, rate);
1002 		if (ret)
1003 			return ret;
1004 	}
1005 	sai_clk_rate = clk_get_rate(sai->sai_ck);
1006 
1007 	if (STM_SAI_IS_F4(sai->pdata)) {
1008 		/* mclk on (NODIV=0)
1009 		 *   mclk_rate = 256 * fs
1010 		 *   MCKDIV = 0 if sai_ck < 3/2 * mclk_rate
1011 		 *   MCKDIV = sai_ck / (2 * mclk_rate) otherwise
1012 		 * mclk off (NODIV=1)
1013 		 *   MCKDIV ignored. sck = sai_ck
1014 		 */
1015 		if (!sai->mclk_rate)
1016 			return 0;
1017 
1018 		if (2 * sai_clk_rate >= 3 * sai->mclk_rate) {
1019 			div = stm32_sai_get_clk_div(sai, sai_clk_rate,
1020 						    2 * sai->mclk_rate);
1021 			if (div < 0)
1022 				return div;
1023 		}
1024 	} else {
1025 		/*
1026 		 * TDM mode :
1027 		 *   mclk on
1028 		 *      MCKDIV = sai_ck / (ws x 256)	(NOMCK=0. OSR=0)
1029 		 *      MCKDIV = sai_ck / (ws x 512)	(NOMCK=0. OSR=1)
1030 		 *   mclk off
1031 		 *      MCKDIV = sai_ck / (frl x ws)	(NOMCK=1)
1032 		 * Note: NOMCK/NODIV correspond to same bit.
1033 		 */
1034 		if (STM_SAI_PROTOCOL_IS_SPDIF(sai)) {
1035 			div = stm32_sai_get_clk_div(sai, sai_clk_rate,
1036 						    rate * 128);
1037 			if (div < 0)
1038 				return div;
1039 		} else {
1040 			if (sai->mclk_rate) {
1041 				mclk_ratio = sai->mclk_rate / rate;
1042 				if (mclk_ratio == 512) {
1043 					cr1 = SAI_XCR1_OSR;
1044 				} else if (mclk_ratio != 256) {
1045 					dev_err(cpu_dai->dev,
1046 						"Wrong mclk ratio %d\n",
1047 						mclk_ratio);
1048 					return -EINVAL;
1049 				}
1050 
1051 				stm32_sai_sub_reg_up(sai,
1052 						     STM_SAI_CR1_REGX,
1053 						     SAI_XCR1_OSR, cr1);
1054 
1055 				div = stm32_sai_get_clk_div(sai, sai_clk_rate,
1056 							    sai->mclk_rate);
1057 				if (div < 0)
1058 					return div;
1059 			} else {
1060 				/* mclk-fs not set, master clock not active */
1061 				den = sai->fs_length * params_rate(params);
1062 				div = stm32_sai_get_clk_div(sai, sai_clk_rate,
1063 							    den);
1064 				if (div < 0)
1065 					return div;
1066 			}
1067 		}
1068 	}
1069 
1070 	return stm32_sai_set_clk_div(sai, div);
1071 }
1072 
1073 static int stm32_sai_hw_params(struct snd_pcm_substream *substream,
1074 			       struct snd_pcm_hw_params *params,
1075 			       struct snd_soc_dai *cpu_dai)
1076 {
1077 	struct stm32_sai_sub_data *sai = snd_soc_dai_get_drvdata(cpu_dai);
1078 	int ret;
1079 
1080 	sai->data_size = params_width(params);
1081 
1082 	if (STM_SAI_PROTOCOL_IS_SPDIF(sai)) {
1083 		/* Rate not already set in runtime structure */
1084 		substream->runtime->rate = params_rate(params);
1085 		stm32_sai_set_iec958_status(sai, substream->runtime);
1086 	} else {
1087 		ret = stm32_sai_set_slots(cpu_dai);
1088 		if (ret < 0)
1089 			return ret;
1090 		stm32_sai_set_frame(cpu_dai);
1091 	}
1092 
1093 	ret = stm32_sai_set_config(cpu_dai, substream, params);
1094 	if (ret)
1095 		return ret;
1096 
1097 	if (sai->master)
1098 		ret = stm32_sai_configure_clock(cpu_dai, params);
1099 
1100 	return ret;
1101 }
1102 
1103 static int stm32_sai_trigger(struct snd_pcm_substream *substream, int cmd,
1104 			     struct snd_soc_dai *cpu_dai)
1105 {
1106 	struct stm32_sai_sub_data *sai = snd_soc_dai_get_drvdata(cpu_dai);
1107 	int ret;
1108 
1109 	switch (cmd) {
1110 	case SNDRV_PCM_TRIGGER_START:
1111 	case SNDRV_PCM_TRIGGER_RESUME:
1112 	case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1113 		dev_dbg(cpu_dai->dev, "Enable DMA and SAI\n");
1114 
1115 		stm32_sai_sub_reg_up(sai, STM_SAI_CR1_REGX,
1116 				     SAI_XCR1_DMAEN, SAI_XCR1_DMAEN);
1117 
1118 		/* Enable SAI */
1119 		ret = stm32_sai_sub_reg_up(sai, STM_SAI_CR1_REGX,
1120 					   SAI_XCR1_SAIEN, SAI_XCR1_SAIEN);
1121 		if (ret < 0)
1122 			dev_err(cpu_dai->dev, "Failed to update CR1 register\n");
1123 		break;
1124 	case SNDRV_PCM_TRIGGER_SUSPEND:
1125 	case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1126 	case SNDRV_PCM_TRIGGER_STOP:
1127 		dev_dbg(cpu_dai->dev, "Disable DMA and SAI\n");
1128 
1129 		stm32_sai_sub_reg_up(sai, STM_SAI_IMR_REGX,
1130 				     SAI_XIMR_MASK, 0);
1131 
1132 		stm32_sai_sub_reg_up(sai, STM_SAI_CR1_REGX,
1133 				     SAI_XCR1_SAIEN,
1134 				     (unsigned int)~SAI_XCR1_SAIEN);
1135 
1136 		ret = stm32_sai_sub_reg_up(sai, STM_SAI_CR1_REGX,
1137 					   SAI_XCR1_DMAEN,
1138 					   (unsigned int)~SAI_XCR1_DMAEN);
1139 		if (ret < 0)
1140 			dev_err(cpu_dai->dev, "Failed to update CR1 register\n");
1141 
1142 		if (STM_SAI_PROTOCOL_IS_SPDIF(sai))
1143 			sai->spdif_frm_cnt = 0;
1144 		break;
1145 	default:
1146 		return -EINVAL;
1147 	}
1148 
1149 	return ret;
1150 }
1151 
1152 static void stm32_sai_shutdown(struct snd_pcm_substream *substream,
1153 			       struct snd_soc_dai *cpu_dai)
1154 {
1155 	struct stm32_sai_sub_data *sai = snd_soc_dai_get_drvdata(cpu_dai);
1156 	unsigned long flags;
1157 
1158 	stm32_sai_sub_reg_up(sai, STM_SAI_IMR_REGX, SAI_XIMR_MASK, 0);
1159 
1160 	clk_disable_unprepare(sai->sai_ck);
1161 
1162 	spin_lock_irqsave(&sai->irq_lock, flags);
1163 	sai->substream = NULL;
1164 	spin_unlock_irqrestore(&sai->irq_lock, flags);
1165 }
1166 
1167 static int stm32_sai_pcm_new(struct snd_soc_pcm_runtime *rtd,
1168 			     struct snd_soc_dai *cpu_dai)
1169 {
1170 	struct stm32_sai_sub_data *sai = dev_get_drvdata(cpu_dai->dev);
1171 	struct snd_kcontrol_new knew = iec958_ctls;
1172 
1173 	if (STM_SAI_PROTOCOL_IS_SPDIF(sai)) {
1174 		dev_dbg(&sai->pdev->dev, "%s: register iec controls", __func__);
1175 		knew.device = rtd->pcm->device;
1176 		return snd_ctl_add(rtd->pcm->card, snd_ctl_new1(&knew, sai));
1177 	}
1178 
1179 	return 0;
1180 }
1181 
1182 static int stm32_sai_dai_probe(struct snd_soc_dai *cpu_dai)
1183 {
1184 	struct stm32_sai_sub_data *sai = dev_get_drvdata(cpu_dai->dev);
1185 	int cr1 = 0, cr1_mask, ret;
1186 
1187 	sai->cpu_dai = cpu_dai;
1188 
1189 	sai->dma_params.addr = (dma_addr_t)(sai->phys_addr + STM_SAI_DR_REGX);
1190 	/*
1191 	 * DMA supports 4, 8 or 16 burst sizes. Burst size 4 is the best choice,
1192 	 * as it allows bytes, half-word and words transfers. (See DMA fifos
1193 	 * constraints).
1194 	 */
1195 	sai->dma_params.maxburst = 4;
1196 	if (sai->pdata->conf.fifo_size < 8)
1197 		sai->dma_params.maxburst = 1;
1198 	/* Buswidth will be set by framework at runtime */
1199 	sai->dma_params.addr_width = DMA_SLAVE_BUSWIDTH_UNDEFINED;
1200 
1201 	if (STM_SAI_IS_PLAYBACK(sai))
1202 		snd_soc_dai_init_dma_data(cpu_dai, &sai->dma_params, NULL);
1203 	else
1204 		snd_soc_dai_init_dma_data(cpu_dai, NULL, &sai->dma_params);
1205 
1206 	/* Next settings are not relevant for spdif mode */
1207 	if (STM_SAI_PROTOCOL_IS_SPDIF(sai))
1208 		return 0;
1209 
1210 	cr1_mask = SAI_XCR1_RX_TX;
1211 	if (STM_SAI_IS_CAPTURE(sai))
1212 		cr1 |= SAI_XCR1_RX_TX;
1213 
1214 	/* Configure synchronization */
1215 	if (sai->sync == SAI_SYNC_EXTERNAL) {
1216 		/* Configure synchro client and provider */
1217 		ret = sai->pdata->set_sync(sai->pdata, sai->np_sync_provider,
1218 					   sai->synco, sai->synci);
1219 		if (ret)
1220 			return ret;
1221 	}
1222 
1223 	cr1_mask |= SAI_XCR1_SYNCEN_MASK;
1224 	cr1 |= SAI_XCR1_SYNCEN_SET(sai->sync);
1225 
1226 	return stm32_sai_sub_reg_up(sai, STM_SAI_CR1_REGX, cr1_mask, cr1);
1227 }
1228 
1229 static const struct snd_soc_dai_ops stm32_sai_pcm_dai_ops = {
1230 	.set_sysclk	= stm32_sai_set_sysclk,
1231 	.set_fmt	= stm32_sai_set_dai_fmt,
1232 	.set_tdm_slot	= stm32_sai_set_dai_tdm_slot,
1233 	.startup	= stm32_sai_startup,
1234 	.hw_params	= stm32_sai_hw_params,
1235 	.trigger	= stm32_sai_trigger,
1236 	.shutdown	= stm32_sai_shutdown,
1237 };
1238 
1239 static int stm32_sai_pcm_process_spdif(struct snd_pcm_substream *substream,
1240 				       int channel, unsigned long hwoff,
1241 				       void *buf, unsigned long bytes)
1242 {
1243 	struct snd_pcm_runtime *runtime = substream->runtime;
1244 	struct snd_soc_pcm_runtime *rtd = asoc_substream_to_rtd(substream);
1245 	struct snd_soc_dai *cpu_dai = asoc_rtd_to_cpu(rtd, 0);
1246 	struct stm32_sai_sub_data *sai = dev_get_drvdata(cpu_dai->dev);
1247 	int *ptr = (int *)(runtime->dma_area + hwoff +
1248 			   channel * (runtime->dma_bytes / runtime->channels));
1249 	ssize_t cnt = bytes_to_samples(runtime, bytes);
1250 	unsigned int frm_cnt = sai->spdif_frm_cnt;
1251 	unsigned int byte;
1252 	unsigned int mask;
1253 
1254 	do {
1255 		*ptr = ((*ptr >> 8) & 0x00ffffff);
1256 
1257 		/* Set channel status bit */
1258 		byte = frm_cnt >> 3;
1259 		mask = 1 << (frm_cnt - (byte << 3));
1260 		if (sai->iec958.status[byte] & mask)
1261 			*ptr |= 0x04000000;
1262 		ptr++;
1263 
1264 		if (!(cnt % 2))
1265 			frm_cnt++;
1266 
1267 		if (frm_cnt == SAI_IEC60958_BLOCK_FRAMES)
1268 			frm_cnt = 0;
1269 	} while (--cnt);
1270 	sai->spdif_frm_cnt = frm_cnt;
1271 
1272 	return 0;
1273 }
1274 
1275 /* No support of mmap in S/PDIF mode */
1276 static const struct snd_pcm_hardware stm32_sai_pcm_hw_spdif = {
1277 	.info = SNDRV_PCM_INFO_INTERLEAVED,
1278 	.buffer_bytes_max = 8 * PAGE_SIZE,
1279 	.period_bytes_min = 1024,
1280 	.period_bytes_max = PAGE_SIZE,
1281 	.periods_min = 2,
1282 	.periods_max = 8,
1283 };
1284 
1285 static const struct snd_pcm_hardware stm32_sai_pcm_hw = {
1286 	.info = SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_MMAP,
1287 	.buffer_bytes_max = 8 * PAGE_SIZE,
1288 	.period_bytes_min = 1024, /* 5ms at 48kHz */
1289 	.period_bytes_max = PAGE_SIZE,
1290 	.periods_min = 2,
1291 	.periods_max = 8,
1292 };
1293 
1294 static struct snd_soc_dai_driver stm32_sai_playback_dai = {
1295 		.probe = stm32_sai_dai_probe,
1296 		.pcm_new = stm32_sai_pcm_new,
1297 		.id = 1, /* avoid call to fmt_single_name() */
1298 		.playback = {
1299 			.channels_min = 1,
1300 			.channels_max = 2,
1301 			.rate_min = 8000,
1302 			.rate_max = 192000,
1303 			.rates = SNDRV_PCM_RATE_CONTINUOUS,
1304 			/* DMA does not support 24 bits transfers */
1305 			.formats =
1306 				SNDRV_PCM_FMTBIT_S8 |
1307 				SNDRV_PCM_FMTBIT_S16_LE |
1308 				SNDRV_PCM_FMTBIT_S32_LE,
1309 		},
1310 		.ops = &stm32_sai_pcm_dai_ops,
1311 };
1312 
1313 static struct snd_soc_dai_driver stm32_sai_capture_dai = {
1314 		.probe = stm32_sai_dai_probe,
1315 		.id = 1, /* avoid call to fmt_single_name() */
1316 		.capture = {
1317 			.channels_min = 1,
1318 			.channels_max = 2,
1319 			.rate_min = 8000,
1320 			.rate_max = 192000,
1321 			.rates = SNDRV_PCM_RATE_CONTINUOUS,
1322 			/* DMA does not support 24 bits transfers */
1323 			.formats =
1324 				SNDRV_PCM_FMTBIT_S8 |
1325 				SNDRV_PCM_FMTBIT_S16_LE |
1326 				SNDRV_PCM_FMTBIT_S32_LE,
1327 		},
1328 		.ops = &stm32_sai_pcm_dai_ops,
1329 };
1330 
1331 static const struct snd_dmaengine_pcm_config stm32_sai_pcm_config = {
1332 	.pcm_hardware = &stm32_sai_pcm_hw,
1333 	.prepare_slave_config = snd_dmaengine_pcm_prepare_slave_config,
1334 };
1335 
1336 static const struct snd_dmaengine_pcm_config stm32_sai_pcm_config_spdif = {
1337 	.pcm_hardware = &stm32_sai_pcm_hw_spdif,
1338 	.prepare_slave_config = snd_dmaengine_pcm_prepare_slave_config,
1339 	.process = stm32_sai_pcm_process_spdif,
1340 };
1341 
1342 static const struct snd_soc_component_driver stm32_component = {
1343 	.name = "stm32-sai",
1344 };
1345 
1346 static const struct of_device_id stm32_sai_sub_ids[] = {
1347 	{ .compatible = "st,stm32-sai-sub-a",
1348 	  .data = (void *)STM_SAI_A_ID},
1349 	{ .compatible = "st,stm32-sai-sub-b",
1350 	  .data = (void *)STM_SAI_B_ID},
1351 	{}
1352 };
1353 MODULE_DEVICE_TABLE(of, stm32_sai_sub_ids);
1354 
1355 static int stm32_sai_sub_parse_of(struct platform_device *pdev,
1356 				  struct stm32_sai_sub_data *sai)
1357 {
1358 	struct device_node *np = pdev->dev.of_node;
1359 	struct resource *res;
1360 	void __iomem *base;
1361 	struct of_phandle_args args;
1362 	int ret;
1363 
1364 	if (!np)
1365 		return -ENODEV;
1366 
1367 	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1368 	base = devm_ioremap_resource(&pdev->dev, res);
1369 	if (IS_ERR(base))
1370 		return PTR_ERR(base);
1371 
1372 	sai->phys_addr = res->start;
1373 
1374 	sai->regmap_config = &stm32_sai_sub_regmap_config_f4;
1375 	/* Note: PDM registers not available for sub-block B */
1376 	if (STM_SAI_HAS_PDM(sai) && STM_SAI_IS_SUB_A(sai))
1377 		sai->regmap_config = &stm32_sai_sub_regmap_config_h7;
1378 
1379 	/*
1380 	 * Do not manage peripheral clock through regmap framework as this
1381 	 * can lead to circular locking issue with sai master clock provider.
1382 	 * Manage peripheral clock directly in driver instead.
1383 	 */
1384 	sai->regmap = devm_regmap_init_mmio(&pdev->dev, base,
1385 					    sai->regmap_config);
1386 	if (IS_ERR(sai->regmap)) {
1387 		if (PTR_ERR(sai->regmap) != -EPROBE_DEFER)
1388 			dev_err(&pdev->dev, "Regmap init error %ld\n",
1389 				PTR_ERR(sai->regmap));
1390 		return PTR_ERR(sai->regmap);
1391 	}
1392 
1393 	/* Get direction property */
1394 	if (of_property_match_string(np, "dma-names", "tx") >= 0) {
1395 		sai->dir = SNDRV_PCM_STREAM_PLAYBACK;
1396 	} else if (of_property_match_string(np, "dma-names", "rx") >= 0) {
1397 		sai->dir = SNDRV_PCM_STREAM_CAPTURE;
1398 	} else {
1399 		dev_err(&pdev->dev, "Unsupported direction\n");
1400 		return -EINVAL;
1401 	}
1402 
1403 	/* Get spdif iec60958 property */
1404 	sai->spdif = false;
1405 	if (of_get_property(np, "st,iec60958", NULL)) {
1406 		if (!STM_SAI_HAS_SPDIF(sai) ||
1407 		    sai->dir == SNDRV_PCM_STREAM_CAPTURE) {
1408 			dev_err(&pdev->dev, "S/PDIF IEC60958 not supported\n");
1409 			return -EINVAL;
1410 		}
1411 		stm32_sai_init_iec958_status(sai);
1412 		sai->spdif = true;
1413 		sai->master = true;
1414 	}
1415 
1416 	/* Get synchronization property */
1417 	args.np = NULL;
1418 	ret = of_parse_phandle_with_fixed_args(np, "st,sync", 1, 0, &args);
1419 	if (ret < 0  && ret != -ENOENT) {
1420 		dev_err(&pdev->dev, "Failed to get st,sync property\n");
1421 		return ret;
1422 	}
1423 
1424 	sai->sync = SAI_SYNC_NONE;
1425 	if (args.np) {
1426 		if (args.np == np) {
1427 			dev_err(&pdev->dev, "%pOFn sync own reference\n", np);
1428 			of_node_put(args.np);
1429 			return -EINVAL;
1430 		}
1431 
1432 		sai->np_sync_provider  = of_get_parent(args.np);
1433 		if (!sai->np_sync_provider) {
1434 			dev_err(&pdev->dev, "%pOFn parent node not found\n",
1435 				np);
1436 			of_node_put(args.np);
1437 			return -ENODEV;
1438 		}
1439 
1440 		sai->sync = SAI_SYNC_INTERNAL;
1441 		if (sai->np_sync_provider != sai->pdata->pdev->dev.of_node) {
1442 			if (!STM_SAI_HAS_EXT_SYNC(sai)) {
1443 				dev_err(&pdev->dev,
1444 					"External synchro not supported\n");
1445 				of_node_put(args.np);
1446 				return -EINVAL;
1447 			}
1448 			sai->sync = SAI_SYNC_EXTERNAL;
1449 
1450 			sai->synci = args.args[0];
1451 			if (sai->synci < 1 ||
1452 			    (sai->synci > (SAI_GCR_SYNCIN_MAX + 1))) {
1453 				dev_err(&pdev->dev, "Wrong SAI index\n");
1454 				of_node_put(args.np);
1455 				return -EINVAL;
1456 			}
1457 
1458 			if (of_property_match_string(args.np, "compatible",
1459 						     "st,stm32-sai-sub-a") >= 0)
1460 				sai->synco = STM_SAI_SYNC_OUT_A;
1461 
1462 			if (of_property_match_string(args.np, "compatible",
1463 						     "st,stm32-sai-sub-b") >= 0)
1464 				sai->synco = STM_SAI_SYNC_OUT_B;
1465 
1466 			if (!sai->synco) {
1467 				dev_err(&pdev->dev, "Unknown SAI sub-block\n");
1468 				of_node_put(args.np);
1469 				return -EINVAL;
1470 			}
1471 		}
1472 
1473 		dev_dbg(&pdev->dev, "%s synchronized with %s\n",
1474 			pdev->name, args.np->full_name);
1475 	}
1476 
1477 	of_node_put(args.np);
1478 	sai->sai_ck = devm_clk_get(&pdev->dev, "sai_ck");
1479 	if (IS_ERR(sai->sai_ck)) {
1480 		if (PTR_ERR(sai->sai_ck) != -EPROBE_DEFER)
1481 			dev_err(&pdev->dev, "Missing kernel clock sai_ck: %ld\n",
1482 				PTR_ERR(sai->sai_ck));
1483 		return PTR_ERR(sai->sai_ck);
1484 	}
1485 
1486 	ret = clk_prepare(sai->pdata->pclk);
1487 	if (ret < 0)
1488 		return ret;
1489 
1490 	if (STM_SAI_IS_F4(sai->pdata))
1491 		return 0;
1492 
1493 	/* Register mclk provider if requested */
1494 	if (of_find_property(np, "#clock-cells", NULL)) {
1495 		ret = stm32_sai_add_mclk_provider(sai);
1496 		if (ret < 0)
1497 			return ret;
1498 	} else {
1499 		sai->sai_mclk = devm_clk_get(&pdev->dev, "MCLK");
1500 		if (IS_ERR(sai->sai_mclk)) {
1501 			if (PTR_ERR(sai->sai_mclk) != -ENOENT)
1502 				return PTR_ERR(sai->sai_mclk);
1503 			sai->sai_mclk = NULL;
1504 		}
1505 	}
1506 
1507 	return 0;
1508 }
1509 
1510 static int stm32_sai_sub_probe(struct platform_device *pdev)
1511 {
1512 	struct stm32_sai_sub_data *sai;
1513 	const struct of_device_id *of_id;
1514 	const struct snd_dmaengine_pcm_config *conf = &stm32_sai_pcm_config;
1515 	int ret;
1516 
1517 	sai = devm_kzalloc(&pdev->dev, sizeof(*sai), GFP_KERNEL);
1518 	if (!sai)
1519 		return -ENOMEM;
1520 
1521 	of_id = of_match_device(stm32_sai_sub_ids, &pdev->dev);
1522 	if (!of_id)
1523 		return -EINVAL;
1524 	sai->id = (uintptr_t)of_id->data;
1525 
1526 	sai->pdev = pdev;
1527 	mutex_init(&sai->ctrl_lock);
1528 	spin_lock_init(&sai->irq_lock);
1529 	platform_set_drvdata(pdev, sai);
1530 
1531 	sai->pdata = dev_get_drvdata(pdev->dev.parent);
1532 	if (!sai->pdata) {
1533 		dev_err(&pdev->dev, "Parent device data not available\n");
1534 		return -EINVAL;
1535 	}
1536 
1537 	ret = stm32_sai_sub_parse_of(pdev, sai);
1538 	if (ret)
1539 		return ret;
1540 
1541 	if (STM_SAI_IS_PLAYBACK(sai))
1542 		sai->cpu_dai_drv = stm32_sai_playback_dai;
1543 	else
1544 		sai->cpu_dai_drv = stm32_sai_capture_dai;
1545 	sai->cpu_dai_drv.name = dev_name(&pdev->dev);
1546 
1547 	ret = devm_request_irq(&pdev->dev, sai->pdata->irq, stm32_sai_isr,
1548 			       IRQF_SHARED, dev_name(&pdev->dev), sai);
1549 	if (ret) {
1550 		dev_err(&pdev->dev, "IRQ request returned %d\n", ret);
1551 		return ret;
1552 	}
1553 
1554 	if (STM_SAI_PROTOCOL_IS_SPDIF(sai))
1555 		conf = &stm32_sai_pcm_config_spdif;
1556 
1557 	ret = snd_dmaengine_pcm_register(&pdev->dev, conf, 0);
1558 	if (ret) {
1559 		if (ret != -EPROBE_DEFER)
1560 			dev_err(&pdev->dev, "Could not register pcm dma\n");
1561 		return ret;
1562 	}
1563 
1564 	ret = snd_soc_register_component(&pdev->dev, &stm32_component,
1565 					 &sai->cpu_dai_drv, 1);
1566 	if (ret) {
1567 		snd_dmaengine_pcm_unregister(&pdev->dev);
1568 		return ret;
1569 	}
1570 
1571 	pm_runtime_enable(&pdev->dev);
1572 
1573 	return 0;
1574 }
1575 
1576 static int stm32_sai_sub_remove(struct platform_device *pdev)
1577 {
1578 	struct stm32_sai_sub_data *sai = dev_get_drvdata(&pdev->dev);
1579 
1580 	clk_unprepare(sai->pdata->pclk);
1581 	snd_dmaengine_pcm_unregister(&pdev->dev);
1582 	snd_soc_unregister_component(&pdev->dev);
1583 	pm_runtime_disable(&pdev->dev);
1584 
1585 	return 0;
1586 }
1587 
1588 #ifdef CONFIG_PM_SLEEP
1589 static int stm32_sai_sub_suspend(struct device *dev)
1590 {
1591 	struct stm32_sai_sub_data *sai = dev_get_drvdata(dev);
1592 	int ret;
1593 
1594 	ret = clk_enable(sai->pdata->pclk);
1595 	if (ret < 0)
1596 		return ret;
1597 
1598 	regcache_cache_only(sai->regmap, true);
1599 	regcache_mark_dirty(sai->regmap);
1600 
1601 	clk_disable(sai->pdata->pclk);
1602 
1603 	return 0;
1604 }
1605 
1606 static int stm32_sai_sub_resume(struct device *dev)
1607 {
1608 	struct stm32_sai_sub_data *sai = dev_get_drvdata(dev);
1609 	int ret;
1610 
1611 	ret = clk_enable(sai->pdata->pclk);
1612 	if (ret < 0)
1613 		return ret;
1614 
1615 	regcache_cache_only(sai->regmap, false);
1616 	ret = regcache_sync(sai->regmap);
1617 
1618 	clk_disable(sai->pdata->pclk);
1619 
1620 	return ret;
1621 }
1622 #endif /* CONFIG_PM_SLEEP */
1623 
1624 static const struct dev_pm_ops stm32_sai_sub_pm_ops = {
1625 	SET_SYSTEM_SLEEP_PM_OPS(stm32_sai_sub_suspend, stm32_sai_sub_resume)
1626 };
1627 
1628 static struct platform_driver stm32_sai_sub_driver = {
1629 	.driver = {
1630 		.name = "st,stm32-sai-sub",
1631 		.of_match_table = stm32_sai_sub_ids,
1632 		.pm = &stm32_sai_sub_pm_ops,
1633 	},
1634 	.probe = stm32_sai_sub_probe,
1635 	.remove = stm32_sai_sub_remove,
1636 };
1637 
1638 module_platform_driver(stm32_sai_sub_driver);
1639 
1640 MODULE_DESCRIPTION("STM32 Soc SAI sub-block Interface");
1641 MODULE_AUTHOR("Olivier Moysan <olivier.moysan@st.com>");
1642 MODULE_ALIAS("platform:st,stm32-sai-sub");
1643 MODULE_LICENSE("GPL v2");
1644