xref: /linux/sound/soc/sdca/sdca_asoc.c (revision 1ce42a11bed134903e352010a01fa53073a6b395)
1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (C) 2025 Cirrus Logic, Inc. and
3 //                    Cirrus Logic International Semiconductor Ltd.
4 
5 /*
6  * The MIPI SDCA specification is available for public downloads at
7  * https://www.mipi.org/mipi-sdca-v1-0-download
8  */
9 
10 #include <linux/bits.h>
11 #include <linux/bitmap.h>
12 #include <linux/build_bug.h>
13 #include <linux/delay.h>
14 #include <linux/dev_printk.h>
15 #include <linux/device.h>
16 #include <linux/minmax.h>
17 #include <linux/module.h>
18 #include <linux/overflow.h>
19 #include <linux/pm_runtime.h>
20 #include <linux/regmap.h>
21 #include <linux/soundwire/sdw_registers.h>
22 #include <linux/string_helpers.h>
23 #include <linux/types.h>
24 #include <sound/control.h>
25 #include <sound/pcm.h>
26 #include <sound/pcm_params.h>
27 #include <sound/sdca.h>
28 #include <sound/sdca_asoc.h>
29 #include <sound/sdca_function.h>
30 #include <sound/soc.h>
31 #include <sound/soc-component.h>
32 #include <sound/soc-dai.h>
33 #include <sound/soc-dapm.h>
34 #include <sound/tlv.h>
35 
36 static bool exported_control(struct sdca_entity *entity, struct sdca_control *control)
37 {
38 	switch (SDCA_CTL_TYPE(entity->type, control->sel)) {
39 	case SDCA_CTL_TYPE_S(GE, DETECTED_MODE):
40 		return true;
41 	default:
42 		break;
43 	}
44 
45 	return control->layers & (SDCA_ACCESS_LAYER_USER |
46 				  SDCA_ACCESS_LAYER_APPLICATION);
47 }
48 
49 static bool readonly_control(struct sdca_control *control)
50 {
51 	return control->has_fixed || control->mode == SDCA_ACCESS_MODE_RO;
52 }
53 
54 static int ge_count_routes(struct sdca_entity *entity)
55 {
56 	int count = 0;
57 	int i, j;
58 
59 	for (i = 0; i < entity->ge.num_modes; i++) {
60 		struct sdca_ge_mode *mode = &entity->ge.modes[i];
61 
62 		for (j = 0; j < mode->num_controls; j++) {
63 			struct sdca_ge_control *affected = &mode->controls[j];
64 
65 			if (affected->sel != SDCA_CTL_SU_SELECTOR || affected->val)
66 				count++;
67 		}
68 	}
69 
70 	return count;
71 }
72 
73 /**
74  * sdca_asoc_count_component - count the various component parts
75  * @dev: Pointer to the device against which allocations will be done.
76  * @function: Pointer to the Function information.
77  * @num_widgets: Output integer pointer, will be filled with the
78  * required number of DAPM widgets for the Function.
79  * @num_routes: Output integer pointer, will be filled with the
80  * required number of DAPM routes for the Function.
81  * @num_controls: Output integer pointer, will be filled with the
82  * required number of ALSA controls for the Function.
83  * @num_dais: Output integer pointer, will be filled with the
84  * required number of ASoC DAIs for the Function.
85  *
86  * This function counts various things within the SDCA Function such
87  * that the calling driver can allocate appropriate space before
88  * calling the appropriate population functions.
89  *
90  * Return: Returns zero on success, and a negative error code on failure.
91  */
92 int sdca_asoc_count_component(struct device *dev, struct sdca_function_data *function,
93 			      int *num_widgets, int *num_routes, int *num_controls,
94 			      int *num_dais)
95 {
96 	struct sdca_control *control;
97 	int i, j;
98 
99 	*num_widgets = function->num_entities - 1;
100 	*num_routes = 0;
101 	*num_controls = 0;
102 	*num_dais = 0;
103 
104 	for (i = 0; i < function->num_entities - 1; i++) {
105 		struct sdca_entity *entity = &function->entities[i];
106 		bool skip_primary_routes = false;
107 
108 		/* Add supply/DAI widget connections */
109 		switch (entity->type) {
110 		case SDCA_ENTITY_TYPE_IT:
111 		case SDCA_ENTITY_TYPE_OT:
112 			*num_routes += !!entity->iot.clock;
113 			*num_routes += !!entity->iot.is_dataport;
114 			*num_controls += !entity->iot.is_dataport;
115 			*num_dais += !!entity->iot.is_dataport;
116 			break;
117 		case SDCA_ENTITY_TYPE_PDE:
118 			*num_routes += entity->pde.num_managed;
119 			break;
120 		case SDCA_ENTITY_TYPE_GE:
121 			*num_routes += ge_count_routes(entity);
122 			skip_primary_routes = true;
123 			break;
124 		case SDCA_ENTITY_TYPE_SU:
125 			control = sdca_selector_find_control(dev, entity, SDCA_CTL_SU_SELECTOR);
126 			if (!control)
127 				return -EINVAL;
128 
129 			skip_primary_routes = (control->layers == SDCA_ACCESS_LAYER_DEVICE);
130 			break;
131 		default:
132 			break;
133 		}
134 
135 		if (entity->group)
136 			(*num_routes)++;
137 
138 		/* Add primary entity connections from DisCo */
139 		if (!skip_primary_routes)
140 			*num_routes += entity->num_sources;
141 
142 		for (j = 0; j < entity->num_controls; j++) {
143 			if (exported_control(entity, &entity->controls[j]))
144 				(*num_controls)++;
145 		}
146 	}
147 
148 	return 0;
149 }
150 EXPORT_SYMBOL_NS(sdca_asoc_count_component, "SND_SOC_SDCA");
151 
152 static int ge_put_enum_double(struct snd_kcontrol *kcontrol,
153 			      struct snd_ctl_elem_value *ucontrol)
154 {
155 	struct snd_soc_dapm_context *dapm = snd_soc_dapm_kcontrol_to_dapm(kcontrol);
156 	struct snd_soc_component *component = snd_soc_dapm_to_component(dapm);
157 	struct device *dev = component->dev;
158 	struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
159 	unsigned int *item = ucontrol->value.enumerated.item;
160 	unsigned int reg = e->reg;
161 	int ret;
162 
163 	if (item[0] >= e->items)
164 		return -EINVAL;
165 
166 	reg &= ~SDW_SDCA_CTL_CSEL(0x3F);
167 	reg |= SDW_SDCA_CTL_CSEL(SDCA_CTL_GE_DETECTED_MODE);
168 
169 	ret = pm_runtime_resume_and_get(dev);
170 	if (ret < 0) {
171 		dev_err(dev, "failed to resume writing %s: %d\n",
172 			kcontrol->id.name, ret);
173 		return ret;
174 	}
175 
176 	ret = snd_soc_component_read(component, reg);
177 	pm_runtime_put(dev);
178 	if (ret < 0)
179 		return ret;
180 	else if (ret <= SDCA_DETECTED_MODE_DETECTION_IN_PROGRESS)
181 		return -EBUSY;
182 
183 	ret = snd_soc_enum_item_to_val(e, item[0]);
184 	if (ret <= SDCA_DETECTED_MODE_DETECTION_IN_PROGRESS)
185 		return -EINVAL;
186 
187 	return snd_soc_dapm_put_enum_double(kcontrol, ucontrol);
188 }
189 
190 static int entity_early_parse_ge(struct device *dev,
191 				 struct sdca_function_data *function,
192 				 struct sdca_entity *entity)
193 {
194 	struct sdca_control_range *range;
195 	struct sdca_control *control;
196 	struct snd_kcontrol_new *kctl;
197 	struct soc_enum *soc_enum;
198 	const char *control_name;
199 	unsigned int *values;
200 	const char **texts;
201 	int i;
202 
203 	control = sdca_selector_find_control(dev, entity, SDCA_CTL_GE_SELECTED_MODE);
204 	if (!control)
205 		return -EINVAL;
206 
207 	if (control->layers != SDCA_ACCESS_LAYER_CLASS)
208 		dev_warn(dev, "%s: unexpected access layer: %x\n",
209 			 entity->label, control->layers);
210 
211 	range = sdca_control_find_range(dev, entity, control, SDCA_SELECTED_MODE_NCOLS, 0);
212 	if (!range)
213 		return -EINVAL;
214 
215 	control_name = devm_kasprintf(dev, GFP_KERNEL, "%s %s",
216 				      entity->label, control->label);
217 	if (!control_name)
218 		return -ENOMEM;
219 
220 	kctl = devm_kzalloc(dev, sizeof(*kctl), GFP_KERNEL);
221 	if (!kctl)
222 		return -ENOMEM;
223 
224 	soc_enum = devm_kzalloc(dev, sizeof(*soc_enum), GFP_KERNEL);
225 	if (!soc_enum)
226 		return -ENOMEM;
227 
228 	texts = devm_kcalloc(dev, range->rows + 3, sizeof(*texts), GFP_KERNEL);
229 	if (!texts)
230 		return -ENOMEM;
231 
232 	values = devm_kcalloc(dev, range->rows + 3, sizeof(*values), GFP_KERNEL);
233 	if (!values)
234 		return -ENOMEM;
235 
236 	texts[0] = "Jack Unplugged";
237 	texts[1] = "Jack Unknown";
238 	texts[2] = "Detection in Progress";
239 	values[0] = SDCA_DETECTED_MODE_JACK_UNPLUGGED;
240 	values[1] = SDCA_DETECTED_MODE_JACK_UNKNOWN;
241 	values[2] = SDCA_DETECTED_MODE_DETECTION_IN_PROGRESS;
242 	for (i = 0; i < range->rows; i++) {
243 		enum sdca_terminal_type type;
244 
245 		type = sdca_range(range, SDCA_SELECTED_MODE_TERM_TYPE, i);
246 
247 		values[i + 3] = sdca_range(range, SDCA_SELECTED_MODE_INDEX, i);
248 		texts[i + 3] = sdca_find_terminal_name(type);
249 		if (!texts[i + 3]) {
250 			dev_err(dev, "%s: unrecognised terminal type: %#x\n",
251 				entity->label, type);
252 			return -EINVAL;
253 		}
254 	}
255 
256 	soc_enum->reg = SDW_SDCA_CTL(function->desc->adr, entity->id, control->sel, 0);
257 	soc_enum->items = range->rows + 3;
258 	soc_enum->mask = roundup_pow_of_two(soc_enum->items) - 1;
259 	soc_enum->texts = texts;
260 	soc_enum->values = values;
261 
262 	kctl->iface = SNDRV_CTL_ELEM_IFACE_MIXER;
263 	kctl->name = control_name;
264 	kctl->info = snd_soc_info_enum_double;
265 	kctl->get = snd_soc_dapm_get_enum_double;
266 	kctl->put = ge_put_enum_double;
267 	kctl->private_value = (unsigned long)soc_enum;
268 
269 	entity->ge.kctl = kctl;
270 
271 	return 0;
272 }
273 
274 static void add_route(struct snd_soc_dapm_route **route, const char *sink,
275 		      const char *control, const char *source)
276 {
277 	(*route)->sink = sink;
278 	(*route)->control = control;
279 	(*route)->source = source;
280 	(*route)++;
281 }
282 
283 static int entity_parse_simple(struct device *dev,
284 			       struct sdca_function_data *function,
285 			       struct sdca_entity *entity,
286 			       struct snd_soc_dapm_widget **widget,
287 			       struct snd_soc_dapm_route **route,
288 			       enum snd_soc_dapm_type id)
289 {
290 	int i;
291 
292 	(*widget)->id = id;
293 	(*widget)++;
294 
295 	for (i = 0; i < entity->num_sources; i++)
296 		add_route(route, entity->label, NULL, entity->sources[i]->label);
297 
298 	return 0;
299 }
300 
301 static int entity_parse_it(struct device *dev,
302 			   struct sdca_function_data *function,
303 			   struct sdca_entity *entity,
304 			   struct snd_soc_dapm_widget **widget,
305 			   struct snd_soc_dapm_route **route)
306 {
307 	int i;
308 
309 	if (entity->iot.is_dataport) {
310 		const char *aif_name = devm_kasprintf(dev, GFP_KERNEL, "%s %s",
311 						      entity->label, "Playback");
312 		if (!aif_name)
313 			return -ENOMEM;
314 
315 		(*widget)->id = snd_soc_dapm_aif_in;
316 
317 		add_route(route, entity->label, NULL, aif_name);
318 	} else {
319 		(*widget)->id = snd_soc_dapm_mic;
320 	}
321 
322 	if (entity->iot.clock)
323 		add_route(route, entity->label, NULL, entity->iot.clock->label);
324 
325 	for (i = 0; i < entity->num_sources; i++)
326 		add_route(route, entity->label, NULL, entity->sources[i]->label);
327 
328 	(*widget)++;
329 
330 	return 0;
331 }
332 
333 static int entity_parse_ot(struct device *dev,
334 			   struct sdca_function_data *function,
335 			   struct sdca_entity *entity,
336 			   struct snd_soc_dapm_widget **widget,
337 			   struct snd_soc_dapm_route **route)
338 {
339 	int i;
340 
341 	if (entity->iot.is_dataport) {
342 		const char *aif_name = devm_kasprintf(dev, GFP_KERNEL, "%s %s",
343 						      entity->label, "Capture");
344 		if (!aif_name)
345 			return -ENOMEM;
346 
347 		(*widget)->id = snd_soc_dapm_aif_out;
348 
349 		add_route(route, aif_name, NULL, entity->label);
350 	} else {
351 		(*widget)->id = snd_soc_dapm_spk;
352 	}
353 
354 	if (entity->iot.clock)
355 		add_route(route, entity->label, NULL, entity->iot.clock->label);
356 
357 	for (i = 0; i < entity->num_sources; i++)
358 		add_route(route, entity->label, NULL, entity->sources[i]->label);
359 
360 	(*widget)++;
361 
362 	return 0;
363 }
364 
365 /**
366  * sdca_asoc_pde_poll_actual_ps - Verify PDE power state reached target state
367  * @dev: Pointer to the device for error logging.
368  * @regmap: Register map for reading ACTUAL_PS register.
369  * @function_id: SDCA function identifier.
370  * @entity_id: SDCA entity identifier for the power domain.
371  * @from_ps: Source power state (SDCA_PDE_PSn value).
372  * @to_ps: Target power state (SDCA_PDE_PSn value).
373  * @pde_delays: Pointer to array of PDE delay specifications for this device,
374  *              or NULL to use default polling interval.
375  * @num_delays: Number of entries in pde_delays array.
376  *
377  * This function polls the ACTUAL_PS register to verify that a PDE power state
378  * transition has completed. Per SDCA specification, after writing REQUESTED_PS,
379  * the caller must poll ACTUAL_PS until it reflects the requested state.
380  *
381  * This function implements the polling logic but does NOT modify the power state.
382  * The caller is responsible for writing REQUESTED_PS before invoking this function.
383  *
384  * If a delay table is provided, appropriate polling intervals are extracted based
385  * on the from_ps and to_ps transition. If no table is provided or no matching entry
386  * is found, a default polling interval is used.
387  *
388  * Return: Returns zero when ACTUAL_PS reaches the target state, -ETIMEDOUT if the
389  * polling times out before reaching the target state, or a negative error code if
390  * a register read fails.
391  */
392 int sdca_asoc_pde_poll_actual_ps(struct device *dev, struct regmap *regmap,
393 				 int function_id, int entity_id,
394 			    int from_ps, int to_ps,
395 			    const struct sdca_pde_delay *pde_delays,
396 			    int num_delays)
397 {
398 	static const int polls = 100;
399 	static const int default_poll_us = 1000;
400 	unsigned int reg, val;
401 	int i, poll_us = default_poll_us;
402 	int ret;
403 
404 	if (pde_delays && num_delays > 0) {
405 		for (i = 0; i < num_delays; i++) {
406 			if (pde_delays[i].from_ps == from_ps && pde_delays[i].to_ps == to_ps) {
407 				poll_us = pde_delays[i].us / polls;
408 				break;
409 			}
410 		}
411 	}
412 
413 	reg = SDW_SDCA_CTL(function_id, entity_id, SDCA_CTL_PDE_ACTUAL_PS, 0);
414 
415 	for (i = 0; i < polls; i++) {
416 		if (i)
417 			fsleep(poll_us);
418 
419 		ret = regmap_read(regmap, reg, &val);
420 		if (ret)
421 			return ret;
422 		else if (val == to_ps)
423 			return 0;
424 	}
425 
426 	return -ETIMEDOUT;
427 }
428 EXPORT_SYMBOL_NS(sdca_asoc_pde_poll_actual_ps, "SND_SOC_SDCA");
429 
430 static int entity_pde_event(struct snd_soc_dapm_widget *widget,
431 			    struct snd_kcontrol *kctl, int event)
432 {
433 	struct snd_soc_component *component = snd_soc_dapm_to_component(widget->dapm);
434 	struct sdca_entity *entity = widget->priv;
435 	int from, to;
436 	int ret;
437 
438 	if (!component)
439 		return -EIO;
440 
441 	switch (event) {
442 	case SND_SOC_DAPM_POST_PMD:
443 		from = widget->on_val;
444 		to = widget->off_val;
445 		break;
446 	case SND_SOC_DAPM_POST_PMU:
447 		from = widget->off_val;
448 		to = widget->on_val;
449 		break;
450 	default:
451 		return 0;
452 	}
453 
454 	ret = sdca_asoc_pde_poll_actual_ps(component->dev, component->regmap,
455 					   SDW_SDCA_CTL_FUNC(widget->reg),
456 					   SDW_SDCA_CTL_ENT(widget->reg),
457 					   from, to,
458 					   entity->pde.max_delay,
459 					   entity->pde.num_max_delay);
460 	if (ret)
461 		dev_err(component->dev, "%s: PDE transition %x -> %x failed, err=%d\n",
462 			entity->label, from, to, ret);
463 
464 	return ret;
465 }
466 
467 static int entity_parse_pde(struct device *dev,
468 			    struct sdca_function_data *function,
469 			    struct sdca_entity *entity,
470 			    struct snd_soc_dapm_widget **widget,
471 			    struct snd_soc_dapm_route **route)
472 {
473 	unsigned int target = (1 << SDCA_PDE_PS0) | (1 << SDCA_PDE_PS3);
474 	struct sdca_control_range *range;
475 	struct sdca_control *control;
476 	unsigned int mask = 0;
477 	int i;
478 
479 	control = sdca_selector_find_control(dev, entity, SDCA_CTL_PDE_REQUESTED_PS);
480 	if (!control)
481 		return -EINVAL;
482 
483 	/* Power should only be controlled by the driver */
484 	if (control->layers != SDCA_ACCESS_LAYER_CLASS)
485 		dev_warn(dev, "%s: unexpected access layer: %x\n",
486 			 entity->label, control->layers);
487 
488 	range = sdca_control_find_range(dev, entity, control, SDCA_REQUESTED_PS_NCOLS, 0);
489 	if (!range)
490 		return -EINVAL;
491 
492 	for (i = 0; i < range->rows; i++)
493 		mask |= 1 << sdca_range(range, SDCA_REQUESTED_PS_STATE, i);
494 
495 	if ((mask & target) != target) {
496 		dev_err(dev, "%s: power control missing states\n", entity->label);
497 		return -EINVAL;
498 	}
499 
500 	(*widget)->id = snd_soc_dapm_supply;
501 	(*widget)->reg = SDW_SDCA_CTL(function->desc->adr, entity->id, control->sel, 0);
502 	(*widget)->mask = GENMASK(control->nbits - 1, 0);
503 	(*widget)->on_val = SDCA_PDE_PS0;
504 	(*widget)->off_val = SDCA_PDE_PS3;
505 	(*widget)->event_flags = SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD;
506 	(*widget)->event = entity_pde_event;
507 	(*widget)->priv = entity;
508 	(*widget)++;
509 
510 	for (i = 0; i < entity->pde.num_managed; i++)
511 		add_route(route, entity->pde.managed[i]->label, NULL, entity->label);
512 
513 	for (i = 0; i < entity->num_sources; i++)
514 		add_route(route, entity->label, NULL, entity->sources[i]->label);
515 
516 	return 0;
517 }
518 
519 /* Device selector units are controlled through a group entity */
520 static int entity_parse_su_device(struct device *dev,
521 				  struct sdca_function_data *function,
522 				  struct sdca_entity *entity,
523 				  struct snd_soc_dapm_widget **widget,
524 				  struct snd_soc_dapm_route **route)
525 {
526 	struct sdca_control_range *range;
527 	int i, j;
528 
529 	if (!entity->group) {
530 		dev_err(dev, "%s: device selector unit missing group\n", entity->label);
531 		return -EINVAL;
532 	}
533 
534 	range = sdca_selector_find_range(dev, entity->group, SDCA_CTL_GE_SELECTED_MODE,
535 					 SDCA_SELECTED_MODE_NCOLS, 0);
536 	if (!range)
537 		return -EINVAL;
538 
539 	(*widget)->id = snd_soc_dapm_mux_named_ctl;
540 	(*widget)->kcontrol_news = entity->group->ge.kctl;
541 	(*widget)->num_kcontrols = 1;
542 	(*widget)++;
543 
544 	for (i = 0; i < entity->group->ge.num_modes; i++) {
545 		struct sdca_ge_mode *mode = &entity->group->ge.modes[i];
546 
547 		for (j = 0; j < mode->num_controls; j++) {
548 			struct sdca_ge_control *affected = &mode->controls[j];
549 			int term;
550 
551 			if (affected->id != entity->id ||
552 			    affected->sel != SDCA_CTL_SU_SELECTOR ||
553 			    !affected->val)
554 				continue;
555 
556 			if (affected->val - 1 >= entity->num_sources) {
557 				dev_err(dev, "%s: bad control value: %#x\n",
558 					entity->label, affected->val);
559 				return -EINVAL;
560 			}
561 
562 			term = sdca_range_search(range, SDCA_SELECTED_MODE_INDEX,
563 						 mode->val, SDCA_SELECTED_MODE_TERM_TYPE);
564 			if (!term) {
565 				dev_err(dev, "%s: mode not found: %#x\n",
566 					entity->label, mode->val);
567 				return -EINVAL;
568 			}
569 
570 			add_route(route, entity->label, sdca_find_terminal_name(term),
571 				  entity->sources[affected->val - 1]->label);
572 		}
573 	}
574 
575 	return 0;
576 }
577 
578 /* Class selector units will be exported as an ALSA control */
579 static int entity_parse_su_class(struct device *dev,
580 				 struct sdca_function_data *function,
581 				 struct sdca_entity *entity,
582 				 struct sdca_control *control,
583 				 struct snd_soc_dapm_widget **widget,
584 				 struct snd_soc_dapm_route **route)
585 {
586 	struct snd_kcontrol_new *kctl;
587 	struct soc_enum *soc_enum;
588 	const char **texts;
589 	int i;
590 
591 	kctl = devm_kzalloc(dev, sizeof(*kctl), GFP_KERNEL);
592 	if (!kctl)
593 		return -ENOMEM;
594 
595 	soc_enum = devm_kzalloc(dev, sizeof(*soc_enum), GFP_KERNEL);
596 	if (!soc_enum)
597 		return -ENOMEM;
598 
599 	texts = devm_kcalloc(dev, entity->num_sources + 1, sizeof(*texts), GFP_KERNEL);
600 	if (!texts)
601 		return -ENOMEM;
602 
603 	texts[0] = "No Signal";
604 	for (i = 0; i < entity->num_sources; i++)
605 		texts[i + 1] = entity->sources[i]->label;
606 
607 	soc_enum->reg = SDW_SDCA_CTL(function->desc->adr, entity->id, control->sel, 0);
608 	soc_enum->items = entity->num_sources + 1;
609 	soc_enum->mask = roundup_pow_of_two(soc_enum->items) - 1;
610 	soc_enum->texts = texts;
611 
612 	kctl->iface = SNDRV_CTL_ELEM_IFACE_MIXER;
613 	kctl->name = "Route";
614 	kctl->info = snd_soc_info_enum_double;
615 	kctl->get = snd_soc_dapm_get_enum_double;
616 	kctl->put = snd_soc_dapm_put_enum_double;
617 	kctl->private_value = (unsigned long)soc_enum;
618 
619 	(*widget)->id = snd_soc_dapm_mux;
620 	(*widget)->kcontrol_news = kctl;
621 	(*widget)->num_kcontrols = 1;
622 	(*widget)++;
623 
624 	for (i = 0; i < entity->num_sources; i++)
625 		add_route(route, entity->label, texts[i + 1], entity->sources[i]->label);
626 
627 	return 0;
628 }
629 
630 static int entity_parse_su(struct device *dev,
631 			   struct sdca_function_data *function,
632 			   struct sdca_entity *entity,
633 			   struct snd_soc_dapm_widget **widget,
634 			   struct snd_soc_dapm_route **route)
635 {
636 	struct sdca_control *control;
637 
638 	if (!entity->num_sources) {
639 		dev_err(dev, "%s: selector with no inputs\n", entity->label);
640 		return -EINVAL;
641 	}
642 
643 	control = sdca_selector_find_control(dev, entity, SDCA_CTL_SU_SELECTOR);
644 	if (!control)
645 		return -EINVAL;
646 
647 	if (control->layers == SDCA_ACCESS_LAYER_DEVICE)
648 		return entity_parse_su_device(dev, function, entity, widget, route);
649 
650 	if (control->layers != SDCA_ACCESS_LAYER_CLASS)
651 		dev_warn(dev, "%s: unexpected access layer: %x\n",
652 			 entity->label, control->layers);
653 
654 	return entity_parse_su_class(dev, function, entity, control, widget, route);
655 }
656 
657 static int entity_parse_mu(struct device *dev,
658 			   struct sdca_function_data *function,
659 			   struct sdca_entity *entity,
660 			   struct snd_soc_dapm_widget **widget,
661 			   struct snd_soc_dapm_route **route)
662 {
663 	struct sdca_control *control;
664 	struct snd_kcontrol_new *kctl;
665 	int i;
666 
667 	if (!entity->num_sources) {
668 		dev_err(dev, "%s: selector 1 or more inputs\n", entity->label);
669 		return -EINVAL;
670 	}
671 
672 	control = sdca_selector_find_control(dev, entity, SDCA_CTL_MU_MIXER);
673 	if (!control)
674 		return -EINVAL;
675 
676 	/* MU control should be through DAPM */
677 	if (control->layers != SDCA_ACCESS_LAYER_CLASS)
678 		dev_warn(dev, "%s: unexpected access layer: %x\n",
679 			 entity->label, control->layers);
680 
681 	kctl = devm_kcalloc(dev, entity->num_sources, sizeof(*kctl), GFP_KERNEL);
682 	if (!kctl)
683 		return -ENOMEM;
684 
685 	for (i = 0; i < entity->num_sources; i++) {
686 		const char *control_name;
687 		struct soc_mixer_control *mc;
688 
689 		control_name = devm_kasprintf(dev, GFP_KERNEL, "%s %d",
690 					      control->label, i + 1);
691 		if (!control_name)
692 			return -ENOMEM;
693 
694 		mc = devm_kzalloc(dev, sizeof(*mc), GFP_KERNEL);
695 		if (!mc)
696 			return -ENOMEM;
697 
698 		mc->reg = SND_SOC_NOPM;
699 		mc->rreg = SND_SOC_NOPM;
700 		mc->invert = 1; // Ensure default is connected
701 		mc->min = 0;
702 		mc->max = 1;
703 
704 		kctl[i].name = control_name;
705 		kctl[i].private_value = (unsigned long)mc;
706 		kctl[i].iface = SNDRV_CTL_ELEM_IFACE_MIXER;
707 		kctl[i].info = snd_soc_info_volsw;
708 		kctl[i].get = snd_soc_dapm_get_volsw;
709 		kctl[i].put = snd_soc_dapm_put_volsw;
710 	}
711 
712 	(*widget)->id = snd_soc_dapm_mixer;
713 	(*widget)->kcontrol_news = kctl;
714 	(*widget)->num_kcontrols = entity->num_sources;
715 	(*widget)++;
716 
717 	for (i = 0; i < entity->num_sources; i++)
718 		add_route(route, entity->label, kctl[i].name, entity->sources[i]->label);
719 
720 	return 0;
721 }
722 
723 static int entity_cs_event(struct snd_soc_dapm_widget *widget,
724 			   struct snd_kcontrol *kctl, int event)
725 {
726 	struct snd_soc_component *component = snd_soc_dapm_to_component(widget->dapm);
727 	struct sdca_entity *entity = widget->priv;
728 
729 	if (!component)
730 		return -EIO;
731 
732 	if (entity->cs.max_delay)
733 		fsleep(entity->cs.max_delay);
734 
735 	return 0;
736 }
737 
738 static int entity_parse_cs(struct device *dev,
739 			   struct sdca_function_data *function,
740 			   struct sdca_entity *entity,
741 			   struct snd_soc_dapm_widget **widget,
742 			   struct snd_soc_dapm_route **route)
743 {
744 	int i;
745 
746 	(*widget)->id = snd_soc_dapm_supply;
747 	(*widget)->subseq = 1; /* Ensure these run after PDEs */
748 	(*widget)->event_flags = SND_SOC_DAPM_POST_PMU;
749 	(*widget)->event = entity_cs_event;
750 	(*widget)->priv = entity;
751 	(*widget)++;
752 
753 	for (i = 0; i < entity->num_sources; i++)
754 		add_route(route, entity->label, NULL, entity->sources[i]->label);
755 
756 	return 0;
757 }
758 
759 /**
760  * sdca_asoc_populate_dapm - fill in arrays of DAPM widgets and routes
761  * @dev: Pointer to the device against which allocations will be done.
762  * @function: Pointer to the Function information.
763  * @widget: Array of DAPM widgets to be populated.
764  * @route: Array of DAPM routes to be populated.
765  *
766  * This function populates arrays of DAPM widgets and routes from the
767  * DisCo information for a particular SDCA Function. Typically,
768  * snd_soc_asoc_count_component will be used to allocate appropriately
769  * sized arrays before calling this function.
770  *
771  * Return: Returns zero on success, and a negative error code on failure.
772  */
773 int sdca_asoc_populate_dapm(struct device *dev, struct sdca_function_data *function,
774 			    struct snd_soc_dapm_widget *widget,
775 			    struct snd_soc_dapm_route *route)
776 {
777 	int ret;
778 	int i;
779 
780 	for (i = 0; i < function->num_entities - 1; i++) {
781 		struct sdca_entity *entity = &function->entities[i];
782 
783 		/*
784 		 * Some entities need to add controls "early" as they are
785 		 * referenced by other entities.
786 		 */
787 		switch (entity->type) {
788 		case SDCA_ENTITY_TYPE_GE:
789 			ret = entity_early_parse_ge(dev, function, entity);
790 			if (ret)
791 				return ret;
792 			break;
793 		default:
794 			break;
795 		}
796 	}
797 
798 	for (i = 0; i < function->num_entities - 1; i++) {
799 		struct sdca_entity *entity = &function->entities[i];
800 
801 		widget->name = entity->label;
802 		widget->reg = SND_SOC_NOPM;
803 
804 		switch (entity->type) {
805 		case SDCA_ENTITY_TYPE_IT:
806 			ret = entity_parse_it(dev, function, entity, &widget, &route);
807 			break;
808 		case SDCA_ENTITY_TYPE_OT:
809 			ret = entity_parse_ot(dev, function, entity, &widget, &route);
810 			break;
811 		case SDCA_ENTITY_TYPE_PDE:
812 			ret = entity_parse_pde(dev, function, entity, &widget, &route);
813 			break;
814 		case SDCA_ENTITY_TYPE_SU:
815 			ret = entity_parse_su(dev, function, entity, &widget, &route);
816 			break;
817 		case SDCA_ENTITY_TYPE_MU:
818 			ret = entity_parse_mu(dev, function, entity, &widget, &route);
819 			break;
820 		case SDCA_ENTITY_TYPE_CS:
821 			ret = entity_parse_cs(dev, function, entity, &widget, &route);
822 			break;
823 		case SDCA_ENTITY_TYPE_CX:
824 			/*
825 			 * FIXME: For now we will just treat these as a supply,
826 			 * meaning all options are enabled.
827 			 */
828 			dev_warn(dev, "%s: clock selectors not fully supported yet\n",
829 				 entity->label);
830 			ret = entity_parse_simple(dev, function, entity, &widget,
831 						  &route, snd_soc_dapm_supply);
832 			break;
833 		case SDCA_ENTITY_TYPE_TG:
834 			ret = entity_parse_simple(dev, function, entity, &widget,
835 						  &route, snd_soc_dapm_siggen);
836 			break;
837 		case SDCA_ENTITY_TYPE_GE:
838 			ret = entity_parse_simple(dev, function, entity, &widget,
839 						  &route, snd_soc_dapm_supply);
840 			break;
841 		default:
842 			ret = entity_parse_simple(dev, function, entity, &widget,
843 						  &route, snd_soc_dapm_pga);
844 			break;
845 		}
846 		if (ret)
847 			return ret;
848 
849 		if (entity->group)
850 			add_route(&route, entity->label, NULL, entity->group->label);
851 	}
852 
853 	return 0;
854 }
855 EXPORT_SYMBOL_NS(sdca_asoc_populate_dapm, "SND_SOC_SDCA");
856 
857 static int q78_write(struct snd_soc_component *component,
858 		     struct soc_mixer_control *mc,
859 		     unsigned int reg, const int val)
860 {
861 	unsigned int mask = GENMASK(mc->sign_bit, 0);
862 	unsigned int reg_val;
863 
864 	if (val < 0 || val > mc->max - mc->min)
865 		return -EINVAL;
866 
867 	reg_val = (val + mc->min) * mc->shift;
868 
869 	return snd_soc_component_update_bits(component, reg, mask, reg_val);
870 }
871 
872 int sdca_asoc_q78_put_volsw(struct snd_kcontrol *kcontrol,
873 			    struct snd_ctl_elem_value *ucontrol)
874 {
875 	struct soc_mixer_control *mc = (struct soc_mixer_control *)kcontrol->private_value;
876 	struct snd_soc_component *component = snd_kcontrol_chip(kcontrol);
877 	int ret;
878 
879 	ret = q78_write(component, mc, mc->reg, ucontrol->value.integer.value[0]);
880 	if (ret < 0)
881 		return ret;
882 
883 	if (snd_soc_volsw_is_stereo(mc)) {
884 		int err; /* Don't drop change flag */
885 
886 		err = q78_write(component, mc, mc->rreg, ucontrol->value.integer.value[1]);
887 		if (err)
888 			return err;
889 	}
890 
891 	return ret;
892 }
893 EXPORT_SYMBOL_NS(sdca_asoc_q78_put_volsw, "SND_SOC_SDCA");
894 
895 static int q78_read(struct snd_soc_component *component,
896 		    struct soc_mixer_control *mc, unsigned int reg)
897 {
898 	unsigned int reg_val;
899 	int val;
900 
901 	reg_val = snd_soc_component_read(component, reg);
902 
903 	val = (sign_extend32(reg_val, mc->sign_bit) / (int)mc->shift) - mc->min;
904 
905 	return val & GENMASK(mc->sign_bit, 0);
906 }
907 
908 int sdca_asoc_q78_get_volsw(struct snd_kcontrol *kcontrol,
909 			    struct snd_ctl_elem_value *ucontrol)
910 {
911 	struct soc_mixer_control *mc = (struct soc_mixer_control *)kcontrol->private_value;
912 	struct snd_soc_component *component = snd_kcontrol_chip(kcontrol);
913 
914 	ucontrol->value.integer.value[0] = q78_read(component, mc, mc->reg);
915 
916 	if (snd_soc_volsw_is_stereo(mc))
917 		ucontrol->value.integer.value[1] = q78_read(component, mc, mc->rreg);
918 
919 	return 0;
920 }
921 EXPORT_SYMBOL_NS(sdca_asoc_q78_get_volsw, "SND_SOC_SDCA");
922 
923 static int control_limit_kctl(struct device *dev,
924 			      struct sdca_entity *entity,
925 			      struct sdca_control *control,
926 			      struct snd_kcontrol_new *kctl)
927 {
928 	struct soc_mixer_control *mc = (struct soc_mixer_control *)kctl->private_value;
929 	struct sdca_control_range *range;
930 	int min, max, step;
931 	unsigned int *tlv;
932 
933 	if (control->type != SDCA_CTL_DATATYPE_Q7P8DB)
934 		return 0;
935 
936 	/*
937 	 * FIXME: For now only handle the simple case of a single linear range
938 	 */
939 	range = sdca_control_find_range(dev, entity, control, SDCA_VOLUME_LINEAR_NCOLS, 1);
940 	if (!range)
941 		return -EINVAL;
942 
943 	min = sdca_range(range, SDCA_VOLUME_LINEAR_MIN, 0);
944 	max = sdca_range(range, SDCA_VOLUME_LINEAR_MAX, 0);
945 	step = sdca_range(range, SDCA_VOLUME_LINEAR_STEP, 0);
946 
947 	min = sign_extend32(min, control->nbits - 1);
948 	max = sign_extend32(max, control->nbits - 1);
949 
950 	tlv = devm_kcalloc(dev, 4, sizeof(*tlv), GFP_KERNEL);
951 	if (!tlv)
952 		return -ENOMEM;
953 
954 	tlv[0] = SNDRV_CTL_TLVT_DB_MINMAX;
955 	tlv[1] = 2 * sizeof(*tlv);
956 	tlv[2] = (min * 100) >> 8;
957 	tlv[3] = (max * 100) >> 8;
958 
959 	mc->min = min / step;
960 	mc->max = max / step;
961 	mc->shift = step;
962 	mc->sign_bit = 15;
963 
964 	kctl->tlv.p = tlv;
965 	kctl->access |= SNDRV_CTL_ELEM_ACCESS_TLV_READ;
966 	kctl->get = sdca_asoc_q78_get_volsw;
967 	kctl->put = sdca_asoc_q78_put_volsw;
968 
969 	return 0;
970 }
971 
972 static int volatile_get_volsw(struct snd_kcontrol *kcontrol,
973 			      struct snd_ctl_elem_value *ucontrol)
974 {
975 	struct snd_soc_component *component = snd_kcontrol_chip(kcontrol);
976 	struct device *dev = component->dev;
977 	int ret;
978 
979 	ret = pm_runtime_resume_and_get(dev);
980 	if (ret < 0) {
981 		dev_err(dev, "failed to resume reading %s: %d\n",
982 			kcontrol->id.name, ret);
983 		return ret;
984 	}
985 
986 	ret = snd_soc_get_volsw(kcontrol, ucontrol);
987 
988 	pm_runtime_put(dev);
989 
990 	return ret;
991 }
992 
993 static int volatile_put_volsw(struct snd_kcontrol *kcontrol,
994 			      struct snd_ctl_elem_value *ucontrol)
995 {
996 	struct snd_soc_component *component = snd_kcontrol_chip(kcontrol);
997 	struct device *dev = component->dev;
998 	int ret;
999 
1000 	ret = pm_runtime_resume_and_get(dev);
1001 	if (ret < 0) {
1002 		dev_err(dev, "failed to resume writing %s: %d\n",
1003 			kcontrol->id.name, ret);
1004 		return ret;
1005 	}
1006 
1007 	ret = snd_soc_put_volsw(kcontrol, ucontrol);
1008 
1009 	pm_runtime_put(dev);
1010 
1011 	return ret;
1012 }
1013 
1014 static int populate_control(struct device *dev,
1015 			    struct sdca_function_data *function,
1016 			    struct sdca_entity *entity,
1017 			    struct sdca_control *control,
1018 			    struct snd_kcontrol_new **kctl)
1019 {
1020 	const char *control_suffix = "";
1021 	const char *control_name;
1022 	struct soc_mixer_control *mc;
1023 	int index = 0;
1024 	int ret;
1025 	int cn;
1026 
1027 	if (!exported_control(entity, control))
1028 		return 0;
1029 
1030 	if (control->type == SDCA_CTL_DATATYPE_ONEBIT)
1031 		control_suffix = " Switch";
1032 
1033 	control_name = devm_kasprintf(dev, GFP_KERNEL, "%s %s%s", entity->label,
1034 				      control->label, control_suffix);
1035 	if (!control_name)
1036 		return -ENOMEM;
1037 
1038 	mc = devm_kzalloc(dev, sizeof(*mc), GFP_KERNEL);
1039 	if (!mc)
1040 		return -ENOMEM;
1041 
1042 	for_each_set_bit(cn, (unsigned long *)&control->cn_list,
1043 			 BITS_PER_TYPE(control->cn_list)) {
1044 		switch (index++) {
1045 		case 0:
1046 			mc->reg = SDW_SDCA_CTL(function->desc->adr, entity->id,
1047 					       control->sel, cn);
1048 			mc->rreg = mc->reg;
1049 			break;
1050 		case 1:
1051 			mc->rreg = SDW_SDCA_CTL(function->desc->adr, entity->id,
1052 						control->sel, cn);
1053 			break;
1054 		default:
1055 			dev_err(dev, "%s: %s: only mono/stereo controls supported\n",
1056 				entity->label, control->label);
1057 			return -EINVAL;
1058 		}
1059 	}
1060 
1061 	mc->min = 0;
1062 	mc->max = clamp((0x1ull << control->nbits) - 1, 0, type_max(mc->max));
1063 
1064 	if (SDCA_CTL_TYPE(entity->type, control->sel) == SDCA_CTL_TYPE_S(FU, MUTE))
1065 		mc->invert = true;
1066 
1067 	(*kctl)->name = control_name;
1068 	(*kctl)->private_value = (unsigned long)mc;
1069 	(*kctl)->iface = SNDRV_CTL_ELEM_IFACE_MIXER;
1070 	(*kctl)->info = snd_soc_info_volsw;
1071 	if (control->is_volatile) {
1072 		(*kctl)->get = volatile_get_volsw;
1073 		(*kctl)->put = volatile_put_volsw;
1074 	} else {
1075 		(*kctl)->get = snd_soc_get_volsw;
1076 		(*kctl)->put = snd_soc_put_volsw;
1077 	}
1078 
1079 	if (readonly_control(control))
1080 		(*kctl)->access = SNDRV_CTL_ELEM_ACCESS_READ;
1081 	else
1082 		(*kctl)->access = SNDRV_CTL_ELEM_ACCESS_READWRITE;
1083 
1084 	ret = control_limit_kctl(dev, entity, control, *kctl);
1085 	if (ret)
1086 		return ret;
1087 
1088 	(*kctl)++;
1089 
1090 	return 0;
1091 }
1092 
1093 static int populate_pin_switch(struct device *dev,
1094 			       struct sdca_entity *entity,
1095 			       struct snd_kcontrol_new **kctl)
1096 {
1097 	const char *control_name;
1098 
1099 	control_name = devm_kasprintf(dev, GFP_KERNEL, "%s Switch", entity->label);
1100 	if (!control_name)
1101 		return -ENOMEM;
1102 
1103 	(*kctl)->name = control_name;
1104 	(*kctl)->private_value = (unsigned long)entity->label;
1105 	(*kctl)->iface = SNDRV_CTL_ELEM_IFACE_MIXER;
1106 	(*kctl)->info = snd_soc_dapm_info_pin_switch;
1107 	(*kctl)->get = snd_soc_dapm_get_component_pin_switch;
1108 	(*kctl)->put = snd_soc_dapm_put_component_pin_switch;
1109 	(*kctl)++;
1110 
1111 	return 0;
1112 }
1113 
1114 /**
1115  * sdca_asoc_populate_controls - fill in an array of ALSA controls for a Function
1116  * @dev: Pointer to the device against which allocations will be done.
1117  * @function: Pointer to the Function information.
1118  * @kctl: Array of ALSA controls to be populated.
1119  *
1120  * This function populates an array of ALSA controls from the DisCo
1121  * information for a particular SDCA Function. Typically,
1122  * snd_soc_asoc_count_component will be used to allocate an
1123  * appropriately sized array before calling this function.
1124  *
1125  * Return: Returns zero on success, and a negative error code on failure.
1126  */
1127 int sdca_asoc_populate_controls(struct device *dev,
1128 				struct sdca_function_data *function,
1129 				struct snd_kcontrol_new *kctl)
1130 {
1131 	int i, j;
1132 	int ret;
1133 
1134 	for (i = 0; i < function->num_entities; i++) {
1135 		struct sdca_entity *entity = &function->entities[i];
1136 
1137 		switch (entity->type) {
1138 		case SDCA_ENTITY_TYPE_IT:
1139 		case SDCA_ENTITY_TYPE_OT:
1140 			if (!entity->iot.is_dataport) {
1141 				ret = populate_pin_switch(dev, entity, &kctl);
1142 				if (ret)
1143 					return ret;
1144 			}
1145 			break;
1146 		default:
1147 			break;
1148 		}
1149 
1150 		for (j = 0; j < entity->num_controls; j++) {
1151 			ret = populate_control(dev, function, entity,
1152 					       &entity->controls[j], &kctl);
1153 			if (ret)
1154 				return ret;
1155 		}
1156 	}
1157 
1158 	return 0;
1159 }
1160 EXPORT_SYMBOL_NS(sdca_asoc_populate_controls, "SND_SOC_SDCA");
1161 
1162 static unsigned int rate_find_mask(unsigned int rate)
1163 {
1164 	switch (rate) {
1165 	case 0:
1166 		return SNDRV_PCM_RATE_8000_768000;
1167 	case 5512:
1168 		return SNDRV_PCM_RATE_5512;
1169 	case 8000:
1170 		return SNDRV_PCM_RATE_8000;
1171 	case 11025:
1172 		return SNDRV_PCM_RATE_11025;
1173 	case 16000:
1174 		return SNDRV_PCM_RATE_16000;
1175 	case 22050:
1176 		return SNDRV_PCM_RATE_22050;
1177 	case 32000:
1178 		return SNDRV_PCM_RATE_32000;
1179 	case 44100:
1180 		return SNDRV_PCM_RATE_44100;
1181 	case 48000:
1182 		return SNDRV_PCM_RATE_48000;
1183 	case 64000:
1184 		return SNDRV_PCM_RATE_64000;
1185 	case 88200:
1186 		return SNDRV_PCM_RATE_88200;
1187 	case 96000:
1188 		return SNDRV_PCM_RATE_96000;
1189 	case 176400:
1190 		return SNDRV_PCM_RATE_176400;
1191 	case 192000:
1192 		return SNDRV_PCM_RATE_192000;
1193 	case 352800:
1194 		return SNDRV_PCM_RATE_352800;
1195 	case 384000:
1196 		return SNDRV_PCM_RATE_384000;
1197 	case 705600:
1198 		return SNDRV_PCM_RATE_705600;
1199 	case 768000:
1200 		return SNDRV_PCM_RATE_768000;
1201 	case 12000:
1202 		return SNDRV_PCM_RATE_12000;
1203 	case 24000:
1204 		return SNDRV_PCM_RATE_24000;
1205 	case 128000:
1206 		return SNDRV_PCM_RATE_128000;
1207 	default:
1208 		return 0;
1209 	}
1210 }
1211 
1212 static u64 width_find_mask(unsigned int bits)
1213 {
1214 	switch (bits) {
1215 	case 0:
1216 		return SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_S16_LE |
1217 		       SNDRV_PCM_FMTBIT_S20_LE | SNDRV_PCM_FMTBIT_S24_LE |
1218 		       SNDRV_PCM_FMTBIT_S32_LE;
1219 	case 8:
1220 		return SNDRV_PCM_FMTBIT_S8;
1221 	case 16:
1222 		return SNDRV_PCM_FMTBIT_S16_LE;
1223 	case 20:
1224 		return SNDRV_PCM_FMTBIT_S20_LE;
1225 	case 24:
1226 		return SNDRV_PCM_FMTBIT_S24_LE;
1227 	case 32:
1228 		return SNDRV_PCM_FMTBIT_S32_LE;
1229 	default:
1230 		return 0;
1231 	}
1232 }
1233 
1234 static int populate_rate_format(struct device *dev,
1235 				struct sdca_function_data *function,
1236 				struct sdca_entity *entity,
1237 				struct snd_soc_pcm_stream *stream)
1238 {
1239 	struct sdca_control_range *range;
1240 	unsigned int sample_rate, sample_width;
1241 	unsigned int clock_rates = 0;
1242 	unsigned int rates = 0;
1243 	u64 formats = 0;
1244 	int sel, i;
1245 
1246 	switch (entity->type) {
1247 	case SDCA_ENTITY_TYPE_IT:
1248 		sel = SDCA_CTL_IT_USAGE;
1249 		break;
1250 	case SDCA_ENTITY_TYPE_OT:
1251 		sel = SDCA_CTL_OT_USAGE;
1252 		break;
1253 	default:
1254 		dev_err(dev, "%s: entity type has no usage control\n",
1255 			entity->label);
1256 		return -EINVAL;
1257 	}
1258 
1259 	if (entity->iot.clock) {
1260 		range = sdca_selector_find_range(dev, entity->iot.clock,
1261 						 SDCA_CTL_CS_SAMPLERATEINDEX,
1262 						 SDCA_SAMPLERATEINDEX_NCOLS, 0);
1263 		if (!range)
1264 			return -EINVAL;
1265 
1266 		for (i = 0; i < range->rows; i++) {
1267 			sample_rate = sdca_range(range, SDCA_SAMPLERATEINDEX_RATE, i);
1268 			clock_rates |= rate_find_mask(sample_rate);
1269 		}
1270 	} else {
1271 		clock_rates = UINT_MAX;
1272 	}
1273 
1274 	range = sdca_selector_find_range(dev, entity, sel, SDCA_USAGE_NCOLS, 0);
1275 	if (!range)
1276 		return -EINVAL;
1277 
1278 	for (i = 0; i < range->rows; i++) {
1279 		sample_rate = sdca_range(range, SDCA_USAGE_SAMPLE_RATE, i);
1280 		sample_rate = rate_find_mask(sample_rate);
1281 
1282 		if (sample_rate & clock_rates) {
1283 			rates |= sample_rate;
1284 
1285 			sample_width = sdca_range(range, SDCA_USAGE_SAMPLE_WIDTH, i);
1286 			formats |= width_find_mask(sample_width);
1287 		}
1288 	}
1289 
1290 	stream->formats = formats;
1291 	stream->rates = rates;
1292 
1293 	return 0;
1294 }
1295 
1296 /**
1297  * sdca_asoc_populate_dais - fill in an array of DAI drivers for a Function
1298  * @dev: Pointer to the device against which allocations will be done.
1299  * @function: Pointer to the Function information.
1300  * @dais: Array of DAI drivers to be populated.
1301  * @ops: DAI ops to be attached to each of the created DAI drivers.
1302  *
1303  * This function populates an array of ASoC DAI drivers from the DisCo
1304  * information for a particular SDCA Function. Typically,
1305  * snd_soc_asoc_count_component will be used to allocate an
1306  * appropriately sized array before calling this function.
1307  *
1308  * Return: Returns zero on success, and a negative error code on failure.
1309  */
1310 int sdca_asoc_populate_dais(struct device *dev, struct sdca_function_data *function,
1311 			    struct snd_soc_dai_driver *dais,
1312 			    const struct snd_soc_dai_ops *ops)
1313 {
1314 	int i, j;
1315 	int ret;
1316 
1317 	for (i = 0, j = 0; i < function->num_entities - 1; i++) {
1318 		struct sdca_entity *entity = &function->entities[i];
1319 		struct snd_soc_pcm_stream *stream;
1320 		const char *stream_suffix;
1321 
1322 		switch (entity->type) {
1323 		case SDCA_ENTITY_TYPE_IT:
1324 			stream = &dais[j].playback;
1325 			stream_suffix = "Playback";
1326 			break;
1327 		case SDCA_ENTITY_TYPE_OT:
1328 			stream = &dais[j].capture;
1329 			stream_suffix = "Capture";
1330 			break;
1331 		default:
1332 			continue;
1333 		}
1334 
1335 		/* Can't check earlier as only terminals have an iot member. */
1336 		if (!entity->iot.is_dataport)
1337 			continue;
1338 
1339 		stream->stream_name = devm_kasprintf(dev, GFP_KERNEL, "%s %s",
1340 						     entity->label, stream_suffix);
1341 		if (!stream->stream_name)
1342 			return -ENOMEM;
1343 		/* Channels will be further limited by constraints */
1344 		stream->channels_min = 1;
1345 		stream->channels_max = SDCA_MAX_CHANNEL_COUNT;
1346 
1347 		ret = populate_rate_format(dev, function, entity, stream);
1348 		if (ret)
1349 			return ret;
1350 
1351 		dais[j].id = i;
1352 		dais[j].name = entity->label;
1353 		dais[j].ops = ops;
1354 		j++;
1355 	}
1356 
1357 	return 0;
1358 }
1359 EXPORT_SYMBOL_NS(sdca_asoc_populate_dais, "SND_SOC_SDCA");
1360 
1361 /**
1362  * sdca_asoc_populate_component - fill in a component driver for a Function
1363  * @dev: Pointer to the device against which allocations will be done.
1364  * @function: Pointer to the Function information.
1365  * @component_drv: Pointer to the component driver to be populated.
1366  * @dai_drv: Pointer to the DAI driver array to be allocated and populated.
1367  * @num_dai_drv: Pointer to integer that will be populated with the number of
1368  * DAI drivers.
1369  * @ops: DAI ops pointer that will be used for each DAI driver.
1370  *
1371  * This function populates a snd_soc_component_driver structure based
1372  * on the DisCo information for a particular SDCA Function. It does
1373  * all allocation internally.
1374  *
1375  * Return: Returns zero on success, and a negative error code on failure.
1376  */
1377 int sdca_asoc_populate_component(struct device *dev,
1378 				 struct sdca_function_data *function,
1379 				 struct snd_soc_component_driver *component_drv,
1380 				 struct snd_soc_dai_driver **dai_drv, int *num_dai_drv,
1381 				 const struct snd_soc_dai_ops *ops)
1382 {
1383 	struct snd_soc_dapm_widget *widgets;
1384 	struct snd_soc_dapm_route *routes;
1385 	struct snd_kcontrol_new *controls;
1386 	struct snd_soc_dai_driver *dais;
1387 	int num_widgets, num_routes, num_controls, num_dais;
1388 	int ret;
1389 
1390 	ret = sdca_asoc_count_component(dev, function, &num_widgets, &num_routes,
1391 					&num_controls, &num_dais);
1392 	if (ret)
1393 		return ret;
1394 
1395 	widgets = devm_kcalloc(dev, num_widgets, sizeof(*widgets), GFP_KERNEL);
1396 	if (!widgets)
1397 		return -ENOMEM;
1398 
1399 	routes = devm_kcalloc(dev, num_routes, sizeof(*routes), GFP_KERNEL);
1400 	if (!routes)
1401 		return -ENOMEM;
1402 
1403 	controls = devm_kcalloc(dev, num_controls, sizeof(*controls), GFP_KERNEL);
1404 	if (!controls)
1405 		return -ENOMEM;
1406 
1407 	dais = devm_kcalloc(dev, num_dais, sizeof(*dais), GFP_KERNEL);
1408 	if (!dais)
1409 		return -ENOMEM;
1410 
1411 	ret = sdca_asoc_populate_dapm(dev, function, widgets, routes);
1412 	if (ret)
1413 		return ret;
1414 
1415 	ret = sdca_asoc_populate_controls(dev, function, controls);
1416 	if (ret)
1417 		return ret;
1418 
1419 	ret = sdca_asoc_populate_dais(dev, function, dais, ops);
1420 	if (ret)
1421 		return ret;
1422 
1423 	component_drv->dapm_widgets = widgets;
1424 	component_drv->num_dapm_widgets = num_widgets;
1425 	component_drv->dapm_routes = routes;
1426 	component_drv->num_dapm_routes = num_routes;
1427 	component_drv->controls = controls;
1428 	component_drv->num_controls = num_controls;
1429 
1430 	*dai_drv = dais;
1431 	*num_dai_drv = num_dais;
1432 
1433 	return 0;
1434 }
1435 EXPORT_SYMBOL_NS(sdca_asoc_populate_component, "SND_SOC_SDCA");
1436 
1437 /**
1438  * sdca_asoc_set_constraints - constrain channels available on a DAI
1439  * @dev: Pointer to the device, used for error messages.
1440  * @regmap: Pointer to the Function register map.
1441  * @function: Pointer to the Function information.
1442  * @substream: Pointer to the PCM substream.
1443  * @dai: Pointer to the ASoC DAI.
1444  *
1445  * Typically called from startup().
1446  *
1447  * Return: Returns zero on success, and a negative error code on failure.
1448  */
1449 int sdca_asoc_set_constraints(struct device *dev, struct regmap *regmap,
1450 			      struct sdca_function_data *function,
1451 			      struct snd_pcm_substream *substream,
1452 			      struct snd_soc_dai *dai)
1453 {
1454 	static const unsigned int channel_list[] = {
1455 		 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
1456 		17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
1457 	};
1458 	struct sdca_entity *entity = &function->entities[dai->id];
1459 	struct snd_pcm_hw_constraint_list *constraint;
1460 	struct sdca_control_range *range;
1461 	struct sdca_control *control;
1462 	unsigned int channel_mask = 0;
1463 	int i, ret;
1464 
1465 	static_assert(ARRAY_SIZE(channel_list) == SDCA_MAX_CHANNEL_COUNT);
1466 	static_assert(sizeof(channel_mask) * BITS_PER_BYTE >= SDCA_MAX_CHANNEL_COUNT);
1467 
1468 	if (entity->type != SDCA_ENTITY_TYPE_IT)
1469 		return 0;
1470 
1471 	control = sdca_selector_find_control(dev, entity, SDCA_CTL_IT_CLUSTERINDEX);
1472 	if (!control)
1473 		return -EINVAL;
1474 
1475 	range = sdca_control_find_range(dev, entity, control, SDCA_CLUSTER_NCOLS, 0);
1476 	if (!range)
1477 		return -EINVAL;
1478 
1479 	for (i = 0; i < range->rows; i++) {
1480 		int clusterid = sdca_range(range, SDCA_CLUSTER_CLUSTERID, i);
1481 		struct sdca_cluster *cluster;
1482 
1483 		cluster = sdca_id_find_cluster(dev, function, clusterid);
1484 		if (!cluster)
1485 			return -ENODEV;
1486 
1487 		channel_mask |= (1 << (cluster->num_channels - 1));
1488 	}
1489 
1490 	dev_dbg(dev, "%s: set channel constraint mask: %#x\n",
1491 		entity->label, channel_mask);
1492 
1493 	constraint = kzalloc_obj(*constraint);
1494 	if (!constraint)
1495 		return -ENOMEM;
1496 
1497 	constraint->count = ARRAY_SIZE(channel_list);
1498 	constraint->list = channel_list;
1499 	constraint->mask = channel_mask;
1500 
1501 	ret = snd_pcm_hw_constraint_list(substream->runtime, 0,
1502 					 SNDRV_PCM_HW_PARAM_CHANNELS,
1503 					 constraint);
1504 	if (ret) {
1505 		dev_err(dev, "%s: failed to add constraint: %d\n", entity->label, ret);
1506 		kfree(constraint);
1507 		return ret;
1508 	}
1509 
1510 	dai->priv = constraint;
1511 
1512 	return 0;
1513 }
1514 EXPORT_SYMBOL_NS(sdca_asoc_set_constraints, "SND_SOC_SDCA");
1515 
1516 /**
1517  * sdca_asoc_free_constraints - free constraint allocations
1518  * @substream: Pointer to the PCM substream.
1519  * @dai: Pointer to the ASoC DAI.
1520  *
1521  * Typically called from shutdown().
1522  */
1523 void sdca_asoc_free_constraints(struct snd_pcm_substream *substream,
1524 				struct snd_soc_dai *dai)
1525 {
1526 	struct snd_pcm_hw_constraint_list *constraint = dai->priv;
1527 
1528 	kfree(constraint);
1529 }
1530 EXPORT_SYMBOL_NS(sdca_asoc_free_constraints, "SND_SOC_SDCA");
1531 
1532 /**
1533  * sdca_asoc_get_port - return SoundWire port for a DAI
1534  * @dev: Pointer to the device, used for error messages.
1535  * @regmap: Pointer to the Function register map.
1536  * @function: Pointer to the Function information.
1537  * @dai: Pointer to the ASoC DAI.
1538  *
1539  * Typically called from hw_params().
1540  *
1541  * Return: Returns a positive port number on success, and a negative error
1542  * code on failure.
1543  */
1544 int sdca_asoc_get_port(struct device *dev, struct regmap *regmap,
1545 		       struct sdca_function_data *function,
1546 		       struct snd_soc_dai *dai)
1547 {
1548 	struct sdca_entity *entity = &function->entities[dai->id];
1549 	struct sdca_control_range *range;
1550 	unsigned int reg, val;
1551 	int sel = -EINVAL;
1552 	int i, ret;
1553 
1554 	switch (entity->type) {
1555 	case SDCA_ENTITY_TYPE_IT:
1556 		sel = SDCA_CTL_IT_DATAPORT_SELECTOR;
1557 		break;
1558 	case SDCA_ENTITY_TYPE_OT:
1559 		sel = SDCA_CTL_OT_DATAPORT_SELECTOR;
1560 		break;
1561 	default:
1562 		break;
1563 	}
1564 
1565 	if (sel < 0 || !entity->iot.is_dataport) {
1566 		dev_err(dev, "%s: port number only available for dataports\n",
1567 			entity->label);
1568 		return -EINVAL;
1569 	}
1570 
1571 	range = sdca_selector_find_range(dev, entity, sel, SDCA_DATAPORT_SELECTOR_NCOLS,
1572 					 SDCA_DATAPORT_SELECTOR_NROWS);
1573 	if (!range)
1574 		return -EINVAL;
1575 
1576 	reg = SDW_SDCA_CTL(function->desc->adr, entity->id, sel, 0);
1577 
1578 	ret = regmap_read(regmap, reg, &val);
1579 	if (ret) {
1580 		dev_err(dev, "%s: failed to read dataport selector: %d\n",
1581 			entity->label, ret);
1582 		return ret;
1583 	}
1584 
1585 	for (i = 0; i < range->rows; i++) {
1586 		static const u8 port_mask = 0xF;
1587 
1588 		sel = sdca_range(range, val & port_mask, i);
1589 
1590 		/*
1591 		 * FIXME: Currently only a single dataport is supported, so
1592 		 * return the first one found, technically up to 4 dataports
1593 		 * could be linked, but this is not yet supported.
1594 		 */
1595 		if (sel != 0xFF)
1596 			return sel;
1597 
1598 		val >>= hweight8(port_mask);
1599 	}
1600 
1601 	dev_err(dev, "%s: no dataport found\n", entity->label);
1602 	return -ENODEV;
1603 }
1604 EXPORT_SYMBOL_NS(sdca_asoc_get_port, "SND_SOC_SDCA");
1605 
1606 static int set_cluster(struct device *dev, struct regmap *regmap,
1607 		       struct sdca_function_data *function,
1608 		       struct sdca_entity *entity, unsigned int channels)
1609 {
1610 	int sel = SDCA_CTL_IT_CLUSTERINDEX;
1611 	struct sdca_control_range *range;
1612 	int i, ret;
1613 
1614 	range = sdca_selector_find_range(dev, entity, sel, SDCA_CLUSTER_NCOLS, 0);
1615 	if (!range)
1616 		return -EINVAL;
1617 
1618 	for (i = 0; i < range->rows; i++) {
1619 		int cluster_id = sdca_range(range, SDCA_CLUSTER_CLUSTERID, i);
1620 		struct sdca_cluster *cluster;
1621 
1622 		cluster = sdca_id_find_cluster(dev, function, cluster_id);
1623 		if (!cluster)
1624 			return -ENODEV;
1625 
1626 		if (cluster->num_channels == channels) {
1627 			int index = sdca_range(range, SDCA_CLUSTER_BYTEINDEX, i);
1628 			unsigned int reg = SDW_SDCA_CTL(function->desc->adr,
1629 							entity->id, sel, 0);
1630 
1631 			ret = regmap_update_bits(regmap, reg, 0xFF, index);
1632 			if (ret) {
1633 				dev_err(dev, "%s: failed to write cluster index: %d\n",
1634 					entity->label, ret);
1635 				return ret;
1636 			}
1637 
1638 			dev_dbg(dev, "%s: set cluster to %d (%d channels)\n",
1639 				entity->label, index, channels);
1640 
1641 			return 0;
1642 		}
1643 	}
1644 
1645 	dev_err(dev, "%s: no cluster for %d channels\n", entity->label, channels);
1646 	return -EINVAL;
1647 }
1648 
1649 static int set_clock(struct device *dev, struct regmap *regmap,
1650 		     struct sdca_function_data *function,
1651 		     struct sdca_entity *entity, int target_rate)
1652 {
1653 	int sel = SDCA_CTL_CS_SAMPLERATEINDEX;
1654 	struct sdca_control_range *range;
1655 	int i, ret;
1656 
1657 	range = sdca_selector_find_range(dev, entity, sel, SDCA_SAMPLERATEINDEX_NCOLS, 0);
1658 	if (!range)
1659 		return -EINVAL;
1660 
1661 	for (i = 0; i < range->rows; i++) {
1662 		unsigned int rate = sdca_range(range, SDCA_SAMPLERATEINDEX_RATE, i);
1663 
1664 		if (rate == target_rate) {
1665 			unsigned int index = sdca_range(range,
1666 							SDCA_SAMPLERATEINDEX_INDEX,
1667 							i);
1668 			unsigned int reg = SDW_SDCA_CTL(function->desc->adr,
1669 							entity->id, sel, 0);
1670 
1671 			ret = regmap_update_bits(regmap, reg, 0xFF, index);
1672 			if (ret) {
1673 				dev_err(dev, "%s: failed to write clock rate: %d\n",
1674 					entity->label, ret);
1675 				return ret;
1676 			}
1677 
1678 			dev_dbg(dev, "%s: set clock rate to %d (%dHz)\n",
1679 				entity->label, index, rate);
1680 
1681 			return 0;
1682 		}
1683 	}
1684 
1685 	dev_err(dev, "%s: no clock rate for %dHz\n", entity->label, target_rate);
1686 	return -EINVAL;
1687 }
1688 
1689 static int set_usage(struct device *dev, struct regmap *regmap,
1690 		     struct sdca_function_data *function,
1691 		     struct sdca_entity *entity, int sel,
1692 		     int target_rate, int target_width)
1693 {
1694 	struct sdca_control_range *range;
1695 	int i, ret;
1696 
1697 	range = sdca_selector_find_range(dev, entity, sel, SDCA_USAGE_NCOLS, 0);
1698 	if (!range)
1699 		return -EINVAL;
1700 
1701 	for (i = 0; i < range->rows; i++) {
1702 		unsigned int rate = sdca_range(range, SDCA_USAGE_SAMPLE_RATE, i);
1703 		unsigned int width = sdca_range(range, SDCA_USAGE_SAMPLE_WIDTH, i);
1704 
1705 		if ((!rate || rate == target_rate) && (!width || width == target_width)) {
1706 			unsigned int usage = sdca_range(range, SDCA_USAGE_NUMBER, i);
1707 			unsigned int reg = SDW_SDCA_CTL(function->desc->adr,
1708 							entity->id, sel, 0);
1709 
1710 			ret = regmap_update_bits(regmap, reg, 0xFF, usage);
1711 			if (ret) {
1712 				dev_err(dev, "%s: failed to write usage: %d\n",
1713 					entity->label, ret);
1714 				return ret;
1715 			}
1716 
1717 			dev_dbg(dev, "%s: set usage to %#x (%dHz, %d bits)\n",
1718 				entity->label, usage, target_rate, target_width);
1719 
1720 			return 0;
1721 		}
1722 	}
1723 
1724 	dev_err(dev, "%s: no usage for %dHz, %dbits\n",
1725 		entity->label, target_rate, target_width);
1726 	return -EINVAL;
1727 }
1728 
1729 /**
1730  * sdca_asoc_hw_params - set SDCA channels, sample rate and bit depth
1731  * @dev: Pointer to the device, used for error messages.
1732  * @regmap: Pointer to the Function register map.
1733  * @function: Pointer to the Function information.
1734  * @substream: Pointer to the PCM substream.
1735  * @params: Pointer to the hardware parameters.
1736  * @dai: Pointer to the ASoC DAI.
1737  *
1738  * Typically called from hw_params().
1739  *
1740  * Return: Returns zero on success, and a negative error code on failure.
1741  */
1742 int sdca_asoc_hw_params(struct device *dev, struct regmap *regmap,
1743 			struct sdca_function_data *function,
1744 			struct snd_pcm_substream *substream,
1745 			struct snd_pcm_hw_params *params,
1746 			struct snd_soc_dai *dai)
1747 {
1748 	struct sdca_entity *entity = &function->entities[dai->id];
1749 	int channels = params_channels(params);
1750 	int width = params_width(params);
1751 	int rate = params_rate(params);
1752 	int usage_sel;
1753 	int ret;
1754 
1755 	switch (entity->type) {
1756 	case SDCA_ENTITY_TYPE_IT:
1757 		ret = set_cluster(dev, regmap, function, entity, channels);
1758 		if (ret)
1759 			return ret;
1760 
1761 		usage_sel = SDCA_CTL_IT_USAGE;
1762 		break;
1763 	case SDCA_ENTITY_TYPE_OT:
1764 		usage_sel = SDCA_CTL_OT_USAGE;
1765 		break;
1766 	default:
1767 		dev_err(dev, "%s: hw_params on non-terminal entity\n", entity->label);
1768 		return -EINVAL;
1769 	}
1770 
1771 	if (entity->iot.clock) {
1772 		ret = set_clock(dev, regmap, function, entity->iot.clock, rate);
1773 		if (ret)
1774 			return ret;
1775 	}
1776 
1777 	ret = set_usage(dev, regmap, function, entity, usage_sel, rate, width);
1778 	if (ret)
1779 		return ret;
1780 
1781 	return 0;
1782 }
1783 EXPORT_SYMBOL_NS(sdca_asoc_hw_params, "SND_SOC_SDCA");
1784