xref: /openbmc/linux/sound/usb/clock.c (revision b2765275)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Clock domain and sample rate management functions
4  */
5 
6 #include <linux/bitops.h>
7 #include <linux/init.h>
8 #include <linux/string.h>
9 #include <linux/usb.h>
10 #include <linux/usb/audio.h>
11 #include <linux/usb/audio-v2.h>
12 #include <linux/usb/audio-v3.h>
13 
14 #include <sound/core.h>
15 #include <sound/info.h>
16 #include <sound/pcm.h>
17 
18 #include "usbaudio.h"
19 #include "card.h"
20 #include "helper.h"
21 #include "clock.h"
22 #include "quirks.h"
23 
24 static void *find_uac_clock_desc(struct usb_host_interface *iface, int id,
25 				 bool (*validator)(void *, int), u8 type)
26 {
27 	void *cs = NULL;
28 
29 	while ((cs = snd_usb_find_csint_desc(iface->extra, iface->extralen,
30 					     cs, type))) {
31 		if (validator(cs, id))
32 			return cs;
33 	}
34 
35 	return NULL;
36 }
37 
38 static bool validate_clock_source_v2(void *p, int id)
39 {
40 	struct uac_clock_source_descriptor *cs = p;
41 	return cs->bClockID == id;
42 }
43 
44 static bool validate_clock_source_v3(void *p, int id)
45 {
46 	struct uac3_clock_source_descriptor *cs = p;
47 	return cs->bClockID == id;
48 }
49 
50 static bool validate_clock_selector_v2(void *p, int id)
51 {
52 	struct uac_clock_selector_descriptor *cs = p;
53 	return cs->bClockID == id;
54 }
55 
56 static bool validate_clock_selector_v3(void *p, int id)
57 {
58 	struct uac3_clock_selector_descriptor *cs = p;
59 	return cs->bClockID == id;
60 }
61 
62 static bool validate_clock_multiplier_v2(void *p, int id)
63 {
64 	struct uac_clock_multiplier_descriptor *cs = p;
65 	return cs->bClockID == id;
66 }
67 
68 static bool validate_clock_multiplier_v3(void *p, int id)
69 {
70 	struct uac3_clock_multiplier_descriptor *cs = p;
71 	return cs->bClockID == id;
72 }
73 
74 #define DEFINE_FIND_HELPER(name, obj, validator, type)		\
75 static obj *name(struct usb_host_interface *iface, int id)	\
76 {								\
77 	return find_uac_clock_desc(iface, id, validator, type);	\
78 }
79 
80 DEFINE_FIND_HELPER(snd_usb_find_clock_source,
81 		   struct uac_clock_source_descriptor,
82 		   validate_clock_source_v2, UAC2_CLOCK_SOURCE);
83 DEFINE_FIND_HELPER(snd_usb_find_clock_source_v3,
84 		   struct uac3_clock_source_descriptor,
85 		   validate_clock_source_v3, UAC3_CLOCK_SOURCE);
86 
87 DEFINE_FIND_HELPER(snd_usb_find_clock_selector,
88 		   struct uac_clock_selector_descriptor,
89 		   validate_clock_selector_v2, UAC2_CLOCK_SELECTOR);
90 DEFINE_FIND_HELPER(snd_usb_find_clock_selector_v3,
91 		   struct uac3_clock_selector_descriptor,
92 		   validate_clock_selector_v3, UAC3_CLOCK_SELECTOR);
93 
94 DEFINE_FIND_HELPER(snd_usb_find_clock_multiplier,
95 		   struct uac_clock_multiplier_descriptor,
96 		   validate_clock_multiplier_v2, UAC2_CLOCK_MULTIPLIER);
97 DEFINE_FIND_HELPER(snd_usb_find_clock_multiplier_v3,
98 		   struct uac3_clock_multiplier_descriptor,
99 		   validate_clock_multiplier_v3, UAC3_CLOCK_MULTIPLIER);
100 
101 static int uac_clock_selector_get_val(struct snd_usb_audio *chip, int selector_id)
102 {
103 	unsigned char buf;
104 	int ret;
105 
106 	ret = snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0),
107 			      UAC2_CS_CUR,
108 			      USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
109 			      UAC2_CX_CLOCK_SELECTOR << 8,
110 			      snd_usb_ctrl_intf(chip) | (selector_id << 8),
111 			      &buf, sizeof(buf));
112 
113 	if (ret < 0)
114 		return ret;
115 
116 	return buf;
117 }
118 
119 static int uac_clock_selector_set_val(struct snd_usb_audio *chip, int selector_id,
120 					unsigned char pin)
121 {
122 	int ret;
123 
124 	ret = snd_usb_ctl_msg(chip->dev, usb_sndctrlpipe(chip->dev, 0),
125 			      UAC2_CS_CUR,
126 			      USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
127 			      UAC2_CX_CLOCK_SELECTOR << 8,
128 			      snd_usb_ctrl_intf(chip) | (selector_id << 8),
129 			      &pin, sizeof(pin));
130 	if (ret < 0)
131 		return ret;
132 
133 	if (ret != sizeof(pin)) {
134 		usb_audio_err(chip,
135 			"setting selector (id %d) unexpected length %d\n",
136 			selector_id, ret);
137 		return -EINVAL;
138 	}
139 
140 	ret = uac_clock_selector_get_val(chip, selector_id);
141 	if (ret < 0)
142 		return ret;
143 
144 	if (ret != pin) {
145 		usb_audio_err(chip,
146 			"setting selector (id %d) to %x failed (current: %d)\n",
147 			selector_id, pin, ret);
148 		return -EINVAL;
149 	}
150 
151 	return ret;
152 }
153 
154 /*
155  * Assume the clock is valid if clock source supports only one single sample
156  * rate, the terminal is connected directly to it (there is no clock selector)
157  * and clock type is internal. This is to deal with some Denon DJ controllers
158  * that always reports that clock is invalid.
159  */
160 static bool uac_clock_source_is_valid_quirk(struct snd_usb_audio *chip,
161 					    struct audioformat *fmt,
162 					    int source_id)
163 {
164 	if (fmt->protocol == UAC_VERSION_2) {
165 		struct uac_clock_source_descriptor *cs_desc =
166 			snd_usb_find_clock_source(chip->ctrl_intf, source_id);
167 
168 		if (!cs_desc)
169 			return false;
170 
171 		return (fmt->nr_rates == 1 &&
172 			(fmt->clock & 0xff) == cs_desc->bClockID &&
173 			(cs_desc->bmAttributes & 0x3) !=
174 				UAC_CLOCK_SOURCE_TYPE_EXT);
175 	}
176 
177 	return false;
178 }
179 
180 static bool uac_clock_source_is_valid(struct snd_usb_audio *chip,
181 				      struct audioformat *fmt,
182 				      int source_id)
183 {
184 	int err;
185 	unsigned char data;
186 	struct usb_device *dev = chip->dev;
187 	u32 bmControls;
188 
189 	if (fmt->protocol == UAC_VERSION_3) {
190 		struct uac3_clock_source_descriptor *cs_desc =
191 			snd_usb_find_clock_source_v3(chip->ctrl_intf, source_id);
192 
193 		if (!cs_desc)
194 			return false;
195 		bmControls = le32_to_cpu(cs_desc->bmControls);
196 	} else { /* UAC_VERSION_1/2 */
197 		struct uac_clock_source_descriptor *cs_desc =
198 			snd_usb_find_clock_source(chip->ctrl_intf, source_id);
199 
200 		if (!cs_desc)
201 			return false;
202 		bmControls = cs_desc->bmControls;
203 	}
204 
205 	/* If a clock source can't tell us whether it's valid, we assume it is */
206 	if (!uac_v2v3_control_is_readable(bmControls,
207 				      UAC2_CS_CONTROL_CLOCK_VALID))
208 		return true;
209 
210 	err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), UAC2_CS_CUR,
211 			      USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN,
212 			      UAC2_CS_CONTROL_CLOCK_VALID << 8,
213 			      snd_usb_ctrl_intf(chip) | (source_id << 8),
214 			      &data, sizeof(data));
215 
216 	if (err < 0) {
217 		dev_warn(&dev->dev,
218 			 "%s(): cannot get clock validity for id %d\n",
219 			   __func__, source_id);
220 		return false;
221 	}
222 
223 	if (data)
224 		return true;
225 	else
226 		return uac_clock_source_is_valid_quirk(chip, fmt, source_id);
227 }
228 
229 static int __uac_clock_find_source(struct snd_usb_audio *chip,
230 				   struct audioformat *fmt, int entity_id,
231 				   unsigned long *visited, bool validate)
232 {
233 	struct uac_clock_source_descriptor *source;
234 	struct uac_clock_selector_descriptor *selector;
235 	struct uac_clock_multiplier_descriptor *multiplier;
236 
237 	entity_id &= 0xff;
238 
239 	if (test_and_set_bit(entity_id, visited)) {
240 		usb_audio_warn(chip,
241 			 "%s(): recursive clock topology detected, id %d.\n",
242 			 __func__, entity_id);
243 		return -EINVAL;
244 	}
245 
246 	/* first, see if the ID we're looking for is a clock source already */
247 	source = snd_usb_find_clock_source(chip->ctrl_intf, entity_id);
248 	if (source) {
249 		entity_id = source->bClockID;
250 		if (validate && !uac_clock_source_is_valid(chip, fmt,
251 								entity_id)) {
252 			usb_audio_err(chip,
253 				"clock source %d is not valid, cannot use\n",
254 				entity_id);
255 			return -ENXIO;
256 		}
257 		return entity_id;
258 	}
259 
260 	selector = snd_usb_find_clock_selector(chip->ctrl_intf, entity_id);
261 	if (selector) {
262 		int ret, i, cur;
263 
264 		/* the entity ID we are looking for is a selector.
265 		 * find out what it currently selects */
266 		ret = uac_clock_selector_get_val(chip, selector->bClockID);
267 		if (ret < 0)
268 			return ret;
269 
270 		/* Selector values are one-based */
271 
272 		if (ret > selector->bNrInPins || ret < 1) {
273 			usb_audio_err(chip,
274 				"%s(): selector reported illegal value, id %d, ret %d\n",
275 				__func__, selector->bClockID, ret);
276 
277 			return -EINVAL;
278 		}
279 
280 		cur = ret;
281 		ret = __uac_clock_find_source(chip, fmt,
282 					      selector->baCSourceID[ret - 1],
283 					      visited, validate);
284 		if (!validate || ret > 0 || !chip->autoclock)
285 			return ret;
286 
287 		/* The current clock source is invalid, try others. */
288 		for (i = 1; i <= selector->bNrInPins; i++) {
289 			int err;
290 
291 			if (i == cur)
292 				continue;
293 
294 			ret = __uac_clock_find_source(chip, fmt,
295 						      selector->baCSourceID[i - 1],
296 						      visited, true);
297 			if (ret < 0)
298 				continue;
299 
300 			err = uac_clock_selector_set_val(chip, entity_id, i);
301 			if (err < 0)
302 				continue;
303 
304 			usb_audio_info(chip,
305 				 "found and selected valid clock source %d\n",
306 				 ret);
307 			return ret;
308 		}
309 
310 		return -ENXIO;
311 	}
312 
313 	/* FIXME: multipliers only act as pass-thru element for now */
314 	multiplier = snd_usb_find_clock_multiplier(chip->ctrl_intf, entity_id);
315 	if (multiplier)
316 		return __uac_clock_find_source(chip, fmt,
317 					       multiplier->bCSourceID,
318 					       visited, validate);
319 
320 	return -EINVAL;
321 }
322 
323 static int __uac3_clock_find_source(struct snd_usb_audio *chip,
324 				    struct audioformat *fmt, int entity_id,
325 				    unsigned long *visited, bool validate)
326 {
327 	struct uac3_clock_source_descriptor *source;
328 	struct uac3_clock_selector_descriptor *selector;
329 	struct uac3_clock_multiplier_descriptor *multiplier;
330 
331 	entity_id &= 0xff;
332 
333 	if (test_and_set_bit(entity_id, visited)) {
334 		usb_audio_warn(chip,
335 			 "%s(): recursive clock topology detected, id %d.\n",
336 			 __func__, entity_id);
337 		return -EINVAL;
338 	}
339 
340 	/* first, see if the ID we're looking for is a clock source already */
341 	source = snd_usb_find_clock_source_v3(chip->ctrl_intf, entity_id);
342 	if (source) {
343 		entity_id = source->bClockID;
344 		if (validate && !uac_clock_source_is_valid(chip, fmt,
345 								entity_id)) {
346 			usb_audio_err(chip,
347 				"clock source %d is not valid, cannot use\n",
348 				entity_id);
349 			return -ENXIO;
350 		}
351 		return entity_id;
352 	}
353 
354 	selector = snd_usb_find_clock_selector_v3(chip->ctrl_intf, entity_id);
355 	if (selector) {
356 		int ret, i, cur;
357 
358 		/* the entity ID we are looking for is a selector.
359 		 * find out what it currently selects */
360 		ret = uac_clock_selector_get_val(chip, selector->bClockID);
361 		if (ret < 0)
362 			return ret;
363 
364 		/* Selector values are one-based */
365 
366 		if (ret > selector->bNrInPins || ret < 1) {
367 			usb_audio_err(chip,
368 				"%s(): selector reported illegal value, id %d, ret %d\n",
369 				__func__, selector->bClockID, ret);
370 
371 			return -EINVAL;
372 		}
373 
374 		cur = ret;
375 		ret = __uac3_clock_find_source(chip, fmt,
376 					       selector->baCSourceID[ret - 1],
377 					       visited, validate);
378 		if (!validate || ret > 0 || !chip->autoclock)
379 			return ret;
380 
381 		/* The current clock source is invalid, try others. */
382 		for (i = 1; i <= selector->bNrInPins; i++) {
383 			int err;
384 
385 			if (i == cur)
386 				continue;
387 
388 			ret = __uac3_clock_find_source(chip, fmt,
389 						       selector->baCSourceID[i - 1],
390 						       visited, true);
391 			if (ret < 0)
392 				continue;
393 
394 			err = uac_clock_selector_set_val(chip, entity_id, i);
395 			if (err < 0)
396 				continue;
397 
398 			usb_audio_info(chip,
399 				 "found and selected valid clock source %d\n",
400 				 ret);
401 			return ret;
402 		}
403 
404 		return -ENXIO;
405 	}
406 
407 	/* FIXME: multipliers only act as pass-thru element for now */
408 	multiplier = snd_usb_find_clock_multiplier_v3(chip->ctrl_intf,
409 						      entity_id);
410 	if (multiplier)
411 		return __uac3_clock_find_source(chip, fmt,
412 						multiplier->bCSourceID,
413 						visited, validate);
414 
415 	return -EINVAL;
416 }
417 
418 /*
419  * For all kinds of sample rate settings and other device queries,
420  * the clock source (end-leaf) must be used. However, clock selectors,
421  * clock multipliers and sample rate converters may be specified as
422  * clock source input to terminal. This functions walks the clock path
423  * to its end and tries to find the source.
424  *
425  * The 'visited' bitfield is used internally to detect recursive loops.
426  *
427  * Returns the clock source UnitID (>=0) on success, or an error.
428  */
429 int snd_usb_clock_find_source(struct snd_usb_audio *chip,
430 			      struct audioformat *fmt, bool validate)
431 {
432 	DECLARE_BITMAP(visited, 256);
433 	memset(visited, 0, sizeof(visited));
434 
435 	switch (fmt->protocol) {
436 	case UAC_VERSION_2:
437 		return __uac_clock_find_source(chip, fmt, fmt->clock, visited,
438 					       validate);
439 	case UAC_VERSION_3:
440 		return __uac3_clock_find_source(chip, fmt, fmt->clock, visited,
441 					       validate);
442 	default:
443 		return -EINVAL;
444 	}
445 }
446 
447 static int set_sample_rate_v1(struct snd_usb_audio *chip, int iface,
448 			      struct usb_host_interface *alts,
449 			      struct audioformat *fmt, int rate)
450 {
451 	struct usb_device *dev = chip->dev;
452 	unsigned int ep;
453 	unsigned char data[3];
454 	int err, crate;
455 
456 	if (get_iface_desc(alts)->bNumEndpoints < 1)
457 		return -EINVAL;
458 	ep = get_endpoint(alts, 0)->bEndpointAddress;
459 
460 	/* if endpoint doesn't have sampling rate control, bail out */
461 	if (!(fmt->attributes & UAC_EP_CS_ATTR_SAMPLE_RATE))
462 		return 0;
463 
464 	data[0] = rate;
465 	data[1] = rate >> 8;
466 	data[2] = rate >> 16;
467 	err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
468 			      USB_TYPE_CLASS | USB_RECIP_ENDPOINT | USB_DIR_OUT,
469 			      UAC_EP_CS_ATTR_SAMPLE_RATE << 8, ep,
470 			      data, sizeof(data));
471 	if (err < 0) {
472 		dev_err(&dev->dev, "%d:%d: cannot set freq %d to ep %#x\n",
473 			iface, fmt->altsetting, rate, ep);
474 		return err;
475 	}
476 
477 	/* Don't check the sample rate for devices which we know don't
478 	 * support reading */
479 	if (snd_usb_get_sample_rate_quirk(chip))
480 		return 0;
481 	/* the firmware is likely buggy, don't repeat to fail too many times */
482 	if (chip->sample_rate_read_error > 2)
483 		return 0;
484 
485 	err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), UAC_GET_CUR,
486 			      USB_TYPE_CLASS | USB_RECIP_ENDPOINT | USB_DIR_IN,
487 			      UAC_EP_CS_ATTR_SAMPLE_RATE << 8, ep,
488 			      data, sizeof(data));
489 	if (err < 0) {
490 		dev_err(&dev->dev, "%d:%d: cannot get freq at ep %#x\n",
491 			iface, fmt->altsetting, ep);
492 		chip->sample_rate_read_error++;
493 		return 0; /* some devices don't support reading */
494 	}
495 
496 	crate = data[0] | (data[1] << 8) | (data[2] << 16);
497 	if (crate != rate) {
498 		dev_warn(&dev->dev, "current rate %d is different from the runtime rate %d\n", crate, rate);
499 		// runtime->rate = crate;
500 	}
501 
502 	return 0;
503 }
504 
505 static int get_sample_rate_v2v3(struct snd_usb_audio *chip, int iface,
506 			      int altsetting, int clock)
507 {
508 	struct usb_device *dev = chip->dev;
509 	__le32 data;
510 	int err;
511 
512 	err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), UAC2_CS_CUR,
513 			      USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN,
514 			      UAC2_CS_CONTROL_SAM_FREQ << 8,
515 			      snd_usb_ctrl_intf(chip) | (clock << 8),
516 			      &data, sizeof(data));
517 	if (err < 0) {
518 		dev_warn(&dev->dev, "%d:%d: cannot get freq (v2/v3): err %d\n",
519 			 iface, altsetting, err);
520 		return 0;
521 	}
522 
523 	return le32_to_cpu(data);
524 }
525 
526 static int set_sample_rate_v2v3(struct snd_usb_audio *chip, int iface,
527 			      struct usb_host_interface *alts,
528 			      struct audioformat *fmt, int rate)
529 {
530 	struct usb_device *dev = chip->dev;
531 	__le32 data;
532 	int err, cur_rate, prev_rate;
533 	int clock;
534 	bool writeable;
535 	u32 bmControls;
536 
537 	/* First, try to find a valid clock. This may trigger
538 	 * automatic clock selection if the current clock is not
539 	 * valid.
540 	 */
541 	clock = snd_usb_clock_find_source(chip, fmt, true);
542 	if (clock < 0) {
543 		/* We did not find a valid clock, but that might be
544 		 * because the current sample rate does not match an
545 		 * external clock source. Try again without validation
546 		 * and we will do another validation after setting the
547 		 * rate.
548 		 */
549 		clock = snd_usb_clock_find_source(chip, fmt, false);
550 		if (clock < 0)
551 			return clock;
552 	}
553 
554 	prev_rate = get_sample_rate_v2v3(chip, iface, fmt->altsetting, clock);
555 	if (prev_rate == rate)
556 		goto validation;
557 
558 	if (fmt->protocol == UAC_VERSION_3) {
559 		struct uac3_clock_source_descriptor *cs_desc;
560 
561 		cs_desc = snd_usb_find_clock_source_v3(chip->ctrl_intf, clock);
562 		bmControls = le32_to_cpu(cs_desc->bmControls);
563 	} else {
564 		struct uac_clock_source_descriptor *cs_desc;
565 
566 		cs_desc = snd_usb_find_clock_source(chip->ctrl_intf, clock);
567 		bmControls = cs_desc->bmControls;
568 	}
569 
570 	writeable = uac_v2v3_control_is_writeable(bmControls,
571 						  UAC2_CS_CONTROL_SAM_FREQ);
572 	if (writeable) {
573 		data = cpu_to_le32(rate);
574 		err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC2_CS_CUR,
575 				      USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_OUT,
576 				      UAC2_CS_CONTROL_SAM_FREQ << 8,
577 				      snd_usb_ctrl_intf(chip) | (clock << 8),
578 				      &data, sizeof(data));
579 		if (err < 0) {
580 			usb_audio_err(chip,
581 				"%d:%d: cannot set freq %d (v2/v3): err %d\n",
582 				iface, fmt->altsetting, rate, err);
583 			return err;
584 		}
585 
586 		cur_rate = get_sample_rate_v2v3(chip, iface,
587 						fmt->altsetting, clock);
588 	} else {
589 		cur_rate = prev_rate;
590 	}
591 
592 	if (cur_rate != rate) {
593 		if (!writeable) {
594 			usb_audio_warn(chip,
595 				 "%d:%d: freq mismatch (RO clock): req %d, clock runs @%d\n",
596 				 iface, fmt->altsetting, rate, cur_rate);
597 			return -ENXIO;
598 		}
599 		usb_audio_dbg(chip,
600 			"current rate %d is different from the runtime rate %d\n",
601 			cur_rate, rate);
602 	}
603 
604 	/* Some devices doesn't respond to sample rate changes while the
605 	 * interface is active. */
606 	if (rate != prev_rate) {
607 		usb_set_interface(dev, iface, 0);
608 		snd_usb_set_interface_quirk(dev);
609 		usb_set_interface(dev, iface, fmt->altsetting);
610 		snd_usb_set_interface_quirk(dev);
611 	}
612 
613 validation:
614 	/* validate clock after rate change */
615 	if (!uac_clock_source_is_valid(chip, fmt, clock))
616 		return -ENXIO;
617 	return 0;
618 }
619 
620 int snd_usb_init_sample_rate(struct snd_usb_audio *chip, int iface,
621 			     struct usb_host_interface *alts,
622 			     struct audioformat *fmt, int rate)
623 {
624 	switch (fmt->protocol) {
625 	case UAC_VERSION_1:
626 	default:
627 		return set_sample_rate_v1(chip, iface, alts, fmt, rate);
628 
629 	case UAC_VERSION_3:
630 		if (chip->badd_profile >= UAC3_FUNCTION_SUBCLASS_GENERIC_IO) {
631 			if (rate != UAC3_BADD_SAMPLING_RATE)
632 				return -ENXIO;
633 			else
634 				return 0;
635 		}
636 	/* fall through */
637 	case UAC_VERSION_2:
638 		return set_sample_rate_v2v3(chip, iface, alts, fmt, rate);
639 	}
640 }
641 
642