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