1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * u_audio.c -- interface to USB gadget "ALSA sound card" utilities
4  *
5  * Copyright (C) 2016
6  * Author: Ruslan Bilovol <ruslan.bilovol@gmail.com>
7  *
8  * Sound card implementation was cut-and-pasted with changes
9  * from f_uac2.c and has:
10  *    Copyright (C) 2011
11  *    Yadwinder Singh (yadi.brar01@gmail.com)
12  *    Jaswinder Singh (jaswinder.singh@linaro.org)
13  */
14 
15 #include <linux/kernel.h>
16 #include <linux/module.h>
17 #include <sound/core.h>
18 #include <sound/pcm.h>
19 #include <sound/pcm_params.h>
20 #include <sound/control.h>
21 #include <sound/tlv.h>
22 #include <linux/usb/audio.h>
23 
24 #include "u_audio.h"
25 
26 #define BUFF_SIZE_MAX	(PAGE_SIZE * 16)
27 #define PRD_SIZE_MAX	PAGE_SIZE
28 #define MIN_PERIODS	4
29 
30 enum {
31 	UAC_FBACK_CTRL,
32 	UAC_P_PITCH_CTRL,
33 	UAC_MUTE_CTRL,
34 	UAC_VOLUME_CTRL,
35 };
36 
37 /* Runtime data params for one stream */
38 struct uac_rtd_params {
39 	struct snd_uac_chip *uac; /* parent chip */
40 	bool ep_enabled; /* if the ep is enabled */
41 
42 	struct snd_pcm_substream *ss;
43 
44 	/* Ring buffer */
45 	ssize_t hw_ptr;
46 
47 	void *rbuf;
48 
49 	unsigned int pitch;	/* Stream pitch ratio to 1000000 */
50 	unsigned int max_psize;	/* MaxPacketSize of endpoint */
51 
52 	struct usb_request **reqs;
53 
54 	struct usb_request *req_fback; /* Feedback endpoint request */
55 	bool fb_ep_enabled; /* if the ep is enabled */
56 
57   /* Volume/Mute controls and their state */
58   int fu_id; /* Feature Unit ID */
59   struct snd_kcontrol *snd_kctl_volume;
60   struct snd_kcontrol *snd_kctl_mute;
61   s16 volume_min, volume_max, volume_res;
62   s16 volume;
63   int mute;
64 
65   spinlock_t lock; /* lock for control transfers */
66 
67 };
68 
69 struct snd_uac_chip {
70 	struct g_audio *audio_dev;
71 
72 	struct uac_rtd_params p_prm;
73 	struct uac_rtd_params c_prm;
74 
75 	struct snd_card *card;
76 	struct snd_pcm *pcm;
77 
78 	/* pre-calculated values for playback iso completion */
79 	unsigned long long p_residue_mil;
80 	unsigned int p_interval;
81 	unsigned int p_framesize;
82 };
83 
84 static const struct snd_pcm_hardware uac_pcm_hardware = {
85 	.info = SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER
86 		 | SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID
87 		 | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME,
88 	.rates = SNDRV_PCM_RATE_CONTINUOUS,
89 	.periods_max = BUFF_SIZE_MAX / PRD_SIZE_MAX,
90 	.buffer_bytes_max = BUFF_SIZE_MAX,
91 	.period_bytes_max = PRD_SIZE_MAX,
92 	.periods_min = MIN_PERIODS,
93 };
94 
95 static void u_audio_set_fback_frequency(enum usb_device_speed speed,
96 					struct usb_ep *out_ep,
97 					unsigned long long freq,
98 					unsigned int pitch,
99 					void *buf)
100 {
101 	u32 ff = 0;
102 	const struct usb_endpoint_descriptor *ep_desc;
103 
104 	/*
105 	 * Because the pitch base is 1000000, the final divider here
106 	 * will be 1000 * 1000000 = 1953125 << 9
107 	 *
108 	 * Instead of dealing with big numbers lets fold this 9 left shift
109 	 */
110 
111 	if (speed == USB_SPEED_FULL) {
112 		/*
113 		 * Full-speed feedback endpoints report frequency
114 		 * in samples/frame
115 		 * Format is encoded in Q10.10 left-justified in the 24 bits,
116 		 * so that it has a Q10.14 format.
117 		 *
118 		 * ff = (freq << 14) / 1000
119 		 */
120 		freq <<= 5;
121 	} else {
122 		/*
123 		 * High-speed feedback endpoints report frequency
124 		 * in samples/microframe.
125 		 * Format is encoded in Q12.13 fitted into four bytes so that
126 		 * the binary point is located between the second and the third
127 		 * byte fromat (that is Q16.16)
128 		 *
129 		 * ff = (freq << 16) / 8000
130 		 *
131 		 * Win10 and OSX UAC2 drivers require number of samples per packet
132 		 * in order to honor the feedback value.
133 		 * Linux snd-usb-audio detects the applied bit-shift automatically.
134 		 */
135 		ep_desc = out_ep->desc;
136 		freq <<= 4 + (ep_desc->bInterval - 1);
137 	}
138 
139 	ff = DIV_ROUND_CLOSEST_ULL((freq * pitch), 1953125);
140 
141 	*(__le32 *)buf = cpu_to_le32(ff);
142 }
143 
144 static void u_audio_iso_complete(struct usb_ep *ep, struct usb_request *req)
145 {
146 	unsigned int pending;
147 	unsigned int hw_ptr;
148 	int status = req->status;
149 	struct snd_pcm_substream *substream;
150 	struct snd_pcm_runtime *runtime;
151 	struct uac_rtd_params *prm = req->context;
152 	struct snd_uac_chip *uac = prm->uac;
153 	struct g_audio *audio_dev = uac->audio_dev;
154 	struct uac_params *params = &audio_dev->params;
155 	unsigned int frames, p_pktsize;
156 	unsigned long long pitched_rate_mil, p_pktsize_residue_mil,
157 			residue_frames_mil, div_result;
158 
159 	/* i/f shutting down */
160 	if (!prm->ep_enabled) {
161 		usb_ep_free_request(ep, req);
162 		return;
163 	}
164 
165 	if (req->status == -ESHUTDOWN)
166 		return;
167 
168 	/*
169 	 * We can't really do much about bad xfers.
170 	 * Afterall, the ISOCH xfers could fail legitimately.
171 	 */
172 	if (status)
173 		pr_debug("%s: iso_complete status(%d) %d/%d\n",
174 			__func__, status, req->actual, req->length);
175 
176 	substream = prm->ss;
177 
178 	/* Do nothing if ALSA isn't active */
179 	if (!substream)
180 		goto exit;
181 
182 	snd_pcm_stream_lock(substream);
183 
184 	runtime = substream->runtime;
185 	if (!runtime || !snd_pcm_running(substream)) {
186 		snd_pcm_stream_unlock(substream);
187 		goto exit;
188 	}
189 
190 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
191 		/*
192 		 * For each IN packet, take the quotient of the current data
193 		 * rate and the endpoint's interval as the base packet size.
194 		 * If there is a residue from this division, add it to the
195 		 * residue accumulator.
196 		 */
197 		unsigned long long p_interval_mil = uac->p_interval * 1000000ULL;
198 
199 		pitched_rate_mil = (unsigned long long)
200 				params->p_srate * prm->pitch;
201 		div_result = pitched_rate_mil;
202 		do_div(div_result, uac->p_interval);
203 		do_div(div_result, 1000000);
204 		frames = (unsigned int) div_result;
205 
206 		pr_debug("p_srate %d, pitch %d, interval_mil %llu, frames %d\n",
207 				params->p_srate, prm->pitch, p_interval_mil, frames);
208 
209 		p_pktsize = min_t(unsigned int,
210 					uac->p_framesize * frames,
211 					ep->maxpacket);
212 
213 		if (p_pktsize < ep->maxpacket) {
214 			residue_frames_mil = pitched_rate_mil - frames * p_interval_mil;
215 			p_pktsize_residue_mil = uac->p_framesize * residue_frames_mil;
216 		} else
217 			p_pktsize_residue_mil = 0;
218 
219 		req->length = p_pktsize;
220 		uac->p_residue_mil += p_pktsize_residue_mil;
221 
222 		/*
223 		 * Whenever there are more bytes in the accumulator p_residue_mil than we
224 		 * need to add one more sample frame, increase this packet's
225 		 * size and decrease the accumulator.
226 		 */
227 		div_result = uac->p_residue_mil;
228 		do_div(div_result, uac->p_interval);
229 		do_div(div_result, 1000000);
230 		if ((unsigned int) div_result >= uac->p_framesize) {
231 			req->length += uac->p_framesize;
232 			uac->p_residue_mil -= uac->p_framesize * p_interval_mil;
233 			pr_debug("increased req length to %d\n", req->length);
234 		}
235 		pr_debug("remains uac->p_residue_mil %llu\n", uac->p_residue_mil);
236 
237 		req->actual = req->length;
238 	}
239 
240 	hw_ptr = prm->hw_ptr;
241 
242 	/* Pack USB load in ALSA ring buffer */
243 	pending = runtime->dma_bytes - hw_ptr;
244 
245 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
246 		if (unlikely(pending < req->actual)) {
247 			memcpy(req->buf, runtime->dma_area + hw_ptr, pending);
248 			memcpy(req->buf + pending, runtime->dma_area,
249 			       req->actual - pending);
250 		} else {
251 			memcpy(req->buf, runtime->dma_area + hw_ptr,
252 			       req->actual);
253 		}
254 	} else {
255 		if (unlikely(pending < req->actual)) {
256 			memcpy(runtime->dma_area + hw_ptr, req->buf, pending);
257 			memcpy(runtime->dma_area, req->buf + pending,
258 			       req->actual - pending);
259 		} else {
260 			memcpy(runtime->dma_area + hw_ptr, req->buf,
261 			       req->actual);
262 		}
263 	}
264 
265 	/* update hw_ptr after data is copied to memory */
266 	prm->hw_ptr = (hw_ptr + req->actual) % runtime->dma_bytes;
267 	hw_ptr = prm->hw_ptr;
268 	snd_pcm_stream_unlock(substream);
269 
270 	if ((hw_ptr % snd_pcm_lib_period_bytes(substream)) < req->actual)
271 		snd_pcm_period_elapsed(substream);
272 
273 exit:
274 	if (usb_ep_queue(ep, req, GFP_ATOMIC))
275 		dev_err(uac->card->dev, "%d Error!\n", __LINE__);
276 }
277 
278 static void u_audio_iso_fback_complete(struct usb_ep *ep,
279 				       struct usb_request *req)
280 {
281 	struct uac_rtd_params *prm = req->context;
282 	struct snd_uac_chip *uac = prm->uac;
283 	struct g_audio *audio_dev = uac->audio_dev;
284 	struct uac_params *params = &audio_dev->params;
285 	int status = req->status;
286 
287 	/* i/f shutting down */
288 	if (!prm->fb_ep_enabled) {
289 		kfree(req->buf);
290 		usb_ep_free_request(ep, req);
291 		return;
292 	}
293 
294 	if (req->status == -ESHUTDOWN)
295 		return;
296 
297 	/*
298 	 * We can't really do much about bad xfers.
299 	 * Afterall, the ISOCH xfers could fail legitimately.
300 	 */
301 	if (status)
302 		pr_debug("%s: iso_complete status(%d) %d/%d\n",
303 			__func__, status, req->actual, req->length);
304 
305 	u_audio_set_fback_frequency(audio_dev->gadget->speed, audio_dev->out_ep,
306 				    params->c_srate, prm->pitch,
307 				    req->buf);
308 
309 	if (usb_ep_queue(ep, req, GFP_ATOMIC))
310 		dev_err(uac->card->dev, "%d Error!\n", __LINE__);
311 }
312 
313 static int uac_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
314 {
315 	struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
316 	struct uac_rtd_params *prm;
317 	struct g_audio *audio_dev;
318 	struct uac_params *params;
319 	int err = 0;
320 
321 	audio_dev = uac->audio_dev;
322 	params = &audio_dev->params;
323 
324 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
325 		prm = &uac->p_prm;
326 	else
327 		prm = &uac->c_prm;
328 
329 	/* Reset */
330 	prm->hw_ptr = 0;
331 
332 	switch (cmd) {
333 	case SNDRV_PCM_TRIGGER_START:
334 	case SNDRV_PCM_TRIGGER_RESUME:
335 		prm->ss = substream;
336 		break;
337 	case SNDRV_PCM_TRIGGER_STOP:
338 	case SNDRV_PCM_TRIGGER_SUSPEND:
339 		prm->ss = NULL;
340 		break;
341 	default:
342 		err = -EINVAL;
343 	}
344 
345 	/* Clear buffer after Play stops */
346 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK && !prm->ss)
347 		memset(prm->rbuf, 0, prm->max_psize * params->req_number);
348 
349 	return err;
350 }
351 
352 static snd_pcm_uframes_t uac_pcm_pointer(struct snd_pcm_substream *substream)
353 {
354 	struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
355 	struct uac_rtd_params *prm;
356 
357 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
358 		prm = &uac->p_prm;
359 	else
360 		prm = &uac->c_prm;
361 
362 	return bytes_to_frames(substream->runtime, prm->hw_ptr);
363 }
364 
365 static u64 uac_ssize_to_fmt(int ssize)
366 {
367 	u64 ret;
368 
369 	switch (ssize) {
370 	case 3:
371 		ret = SNDRV_PCM_FMTBIT_S24_3LE;
372 		break;
373 	case 4:
374 		ret = SNDRV_PCM_FMTBIT_S32_LE;
375 		break;
376 	default:
377 		ret = SNDRV_PCM_FMTBIT_S16_LE;
378 		break;
379 	}
380 
381 	return ret;
382 }
383 
384 static int uac_pcm_open(struct snd_pcm_substream *substream)
385 {
386 	struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
387 	struct snd_pcm_runtime *runtime = substream->runtime;
388 	struct g_audio *audio_dev;
389 	struct uac_params *params;
390 	int p_ssize, c_ssize;
391 	int p_srate, c_srate;
392 	int p_chmask, c_chmask;
393 
394 	audio_dev = uac->audio_dev;
395 	params = &audio_dev->params;
396 	p_ssize = params->p_ssize;
397 	c_ssize = params->c_ssize;
398 	p_srate = params->p_srate;
399 	c_srate = params->c_srate;
400 	p_chmask = params->p_chmask;
401 	c_chmask = params->c_chmask;
402 	uac->p_residue_mil = 0;
403 
404 	runtime->hw = uac_pcm_hardware;
405 
406 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
407 		runtime->hw.rate_min = p_srate;
408 		runtime->hw.formats = uac_ssize_to_fmt(p_ssize);
409 		runtime->hw.channels_min = num_channels(p_chmask);
410 		runtime->hw.period_bytes_min = 2 * uac->p_prm.max_psize
411 						/ runtime->hw.periods_min;
412 	} else {
413 		runtime->hw.rate_min = c_srate;
414 		runtime->hw.formats = uac_ssize_to_fmt(c_ssize);
415 		runtime->hw.channels_min = num_channels(c_chmask);
416 		runtime->hw.period_bytes_min = 2 * uac->c_prm.max_psize
417 						/ runtime->hw.periods_min;
418 	}
419 
420 	runtime->hw.rate_max = runtime->hw.rate_min;
421 	runtime->hw.channels_max = runtime->hw.channels_min;
422 
423 	snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
424 
425 	return 0;
426 }
427 
428 /* ALSA cries without these function pointers */
429 static int uac_pcm_null(struct snd_pcm_substream *substream)
430 {
431 	return 0;
432 }
433 
434 static const struct snd_pcm_ops uac_pcm_ops = {
435 	.open = uac_pcm_open,
436 	.close = uac_pcm_null,
437 	.trigger = uac_pcm_trigger,
438 	.pointer = uac_pcm_pointer,
439 	.prepare = uac_pcm_null,
440 };
441 
442 static inline void free_ep(struct uac_rtd_params *prm, struct usb_ep *ep)
443 {
444 	struct snd_uac_chip *uac = prm->uac;
445 	struct g_audio *audio_dev;
446 	struct uac_params *params;
447 	int i;
448 
449 	if (!prm->ep_enabled)
450 		return;
451 
452 	audio_dev = uac->audio_dev;
453 	params = &audio_dev->params;
454 
455 	for (i = 0; i < params->req_number; i++) {
456 		if (prm->reqs[i]) {
457 			if (usb_ep_dequeue(ep, prm->reqs[i]))
458 				usb_ep_free_request(ep, prm->reqs[i]);
459 			/*
460 			 * If usb_ep_dequeue() cannot successfully dequeue the
461 			 * request, the request will be freed by the completion
462 			 * callback.
463 			 */
464 
465 			prm->reqs[i] = NULL;
466 		}
467 	}
468 
469 	prm->ep_enabled = false;
470 
471 	if (usb_ep_disable(ep))
472 		dev_err(uac->card->dev, "%s:%d Error!\n", __func__, __LINE__);
473 }
474 
475 static inline void free_ep_fback(struct uac_rtd_params *prm, struct usb_ep *ep)
476 {
477 	struct snd_uac_chip *uac = prm->uac;
478 
479 	if (!prm->fb_ep_enabled)
480 		return;
481 
482 	if (prm->req_fback) {
483 		if (usb_ep_dequeue(ep, prm->req_fback)) {
484 			kfree(prm->req_fback->buf);
485 			usb_ep_free_request(ep, prm->req_fback);
486 		}
487 		prm->req_fback = NULL;
488 	}
489 
490 	prm->fb_ep_enabled = false;
491 
492 	if (usb_ep_disable(ep))
493 		dev_err(uac->card->dev, "%s:%d Error!\n", __func__, __LINE__);
494 }
495 
496 int u_audio_start_capture(struct g_audio *audio_dev)
497 {
498 	struct snd_uac_chip *uac = audio_dev->uac;
499 	struct usb_gadget *gadget = audio_dev->gadget;
500 	struct device *dev = &gadget->dev;
501 	struct usb_request *req, *req_fback;
502 	struct usb_ep *ep, *ep_fback;
503 	struct uac_rtd_params *prm;
504 	struct uac_params *params = &audio_dev->params;
505 	int req_len, i;
506 
507 	ep = audio_dev->out_ep;
508 	prm = &uac->c_prm;
509 	config_ep_by_speed(gadget, &audio_dev->func, ep);
510 	req_len = ep->maxpacket;
511 
512 	prm->ep_enabled = true;
513 	usb_ep_enable(ep);
514 
515 	for (i = 0; i < params->req_number; i++) {
516 		if (!prm->reqs[i]) {
517 			req = usb_ep_alloc_request(ep, GFP_ATOMIC);
518 			if (req == NULL)
519 				return -ENOMEM;
520 
521 			prm->reqs[i] = req;
522 
523 			req->zero = 0;
524 			req->context = prm;
525 			req->length = req_len;
526 			req->complete = u_audio_iso_complete;
527 			req->buf = prm->rbuf + i * ep->maxpacket;
528 		}
529 
530 		if (usb_ep_queue(ep, prm->reqs[i], GFP_ATOMIC))
531 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
532 	}
533 
534 	ep_fback = audio_dev->in_ep_fback;
535 	if (!ep_fback)
536 		return 0;
537 
538 	/* Setup feedback endpoint */
539 	config_ep_by_speed(gadget, &audio_dev->func, ep_fback);
540 	prm->fb_ep_enabled = true;
541 	usb_ep_enable(ep_fback);
542 	req_len = ep_fback->maxpacket;
543 
544 	req_fback = usb_ep_alloc_request(ep_fback, GFP_ATOMIC);
545 	if (req_fback == NULL)
546 		return -ENOMEM;
547 
548 	prm->req_fback = req_fback;
549 	req_fback->zero = 0;
550 	req_fback->context = prm;
551 	req_fback->length = req_len;
552 	req_fback->complete = u_audio_iso_fback_complete;
553 
554 	req_fback->buf = kzalloc(req_len, GFP_ATOMIC);
555 	if (!req_fback->buf)
556 		return -ENOMEM;
557 
558 	/*
559 	 * Configure the feedback endpoint's reported frequency.
560 	 * Always start with original frequency since its deviation can't
561 	 * be meauserd at start of playback
562 	 */
563 	prm->pitch = 1000000;
564 	u_audio_set_fback_frequency(audio_dev->gadget->speed, ep,
565 				    params->c_srate, prm->pitch,
566 				    req_fback->buf);
567 
568 	if (usb_ep_queue(ep_fback, req_fback, GFP_ATOMIC))
569 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
570 
571 	return 0;
572 }
573 EXPORT_SYMBOL_GPL(u_audio_start_capture);
574 
575 void u_audio_stop_capture(struct g_audio *audio_dev)
576 {
577 	struct snd_uac_chip *uac = audio_dev->uac;
578 
579 	if (audio_dev->in_ep_fback)
580 		free_ep_fback(&uac->c_prm, audio_dev->in_ep_fback);
581 	free_ep(&uac->c_prm, audio_dev->out_ep);
582 }
583 EXPORT_SYMBOL_GPL(u_audio_stop_capture);
584 
585 int u_audio_start_playback(struct g_audio *audio_dev)
586 {
587 	struct snd_uac_chip *uac = audio_dev->uac;
588 	struct usb_gadget *gadget = audio_dev->gadget;
589 	struct device *dev = &gadget->dev;
590 	struct usb_request *req;
591 	struct usb_ep *ep;
592 	struct uac_rtd_params *prm;
593 	struct uac_params *params = &audio_dev->params;
594 	unsigned int factor;
595 	const struct usb_endpoint_descriptor *ep_desc;
596 	int req_len, i;
597 	unsigned int p_pktsize;
598 
599 	ep = audio_dev->in_ep;
600 	prm = &uac->p_prm;
601 	config_ep_by_speed(gadget, &audio_dev->func, ep);
602 
603 	ep_desc = ep->desc;
604 	/*
605 	 * Always start with original frequency
606 	 */
607 	prm->pitch = 1000000;
608 
609 	/* pre-calculate the playback endpoint's interval */
610 	if (gadget->speed == USB_SPEED_FULL)
611 		factor = 1000;
612 	else
613 		factor = 8000;
614 
615 	/* pre-compute some values for iso_complete() */
616 	uac->p_framesize = params->p_ssize *
617 			    num_channels(params->p_chmask);
618 	uac->p_interval = factor / (1 << (ep_desc->bInterval - 1));
619 	p_pktsize = min_t(unsigned int,
620 				uac->p_framesize *
621 					(params->p_srate / uac->p_interval),
622 				ep->maxpacket);
623 
624 	req_len = p_pktsize;
625 	uac->p_residue_mil = 0;
626 
627 	prm->ep_enabled = true;
628 	usb_ep_enable(ep);
629 
630 	for (i = 0; i < params->req_number; i++) {
631 		if (!prm->reqs[i]) {
632 			req = usb_ep_alloc_request(ep, GFP_ATOMIC);
633 			if (req == NULL)
634 				return -ENOMEM;
635 
636 			prm->reqs[i] = req;
637 
638 			req->zero = 0;
639 			req->context = prm;
640 			req->length = req_len;
641 			req->complete = u_audio_iso_complete;
642 			req->buf = prm->rbuf + i * ep->maxpacket;
643 		}
644 
645 		if (usb_ep_queue(ep, prm->reqs[i], GFP_ATOMIC))
646 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
647 	}
648 
649 	return 0;
650 }
651 EXPORT_SYMBOL_GPL(u_audio_start_playback);
652 
653 void u_audio_stop_playback(struct g_audio *audio_dev)
654 {
655 	struct snd_uac_chip *uac = audio_dev->uac;
656 
657 	free_ep(&uac->p_prm, audio_dev->in_ep);
658 }
659 EXPORT_SYMBOL_GPL(u_audio_stop_playback);
660 
661 int u_audio_get_volume(struct g_audio *audio_dev, int playback, s16 *val)
662 {
663 	struct snd_uac_chip *uac = audio_dev->uac;
664 	struct uac_rtd_params *prm;
665 	unsigned long flags;
666 
667 	if (playback)
668 		prm = &uac->p_prm;
669 	else
670 		prm = &uac->c_prm;
671 
672 	spin_lock_irqsave(&prm->lock, flags);
673 	*val = prm->volume;
674 	spin_unlock_irqrestore(&prm->lock, flags);
675 
676 	return 0;
677 }
678 EXPORT_SYMBOL_GPL(u_audio_get_volume);
679 
680 int u_audio_set_volume(struct g_audio *audio_dev, int playback, s16 val)
681 {
682 	struct snd_uac_chip *uac = audio_dev->uac;
683 	struct uac_rtd_params *prm;
684 	unsigned long flags;
685 	int change = 0;
686 
687 	if (playback)
688 		prm = &uac->p_prm;
689 	else
690 		prm = &uac->c_prm;
691 
692 	spin_lock_irqsave(&prm->lock, flags);
693 	val = clamp(val, prm->volume_min, prm->volume_max);
694 	if (prm->volume != val) {
695 		prm->volume = val;
696 		change = 1;
697 	}
698 	spin_unlock_irqrestore(&prm->lock, flags);
699 
700 	if (change)
701 		snd_ctl_notify(uac->card, SNDRV_CTL_EVENT_MASK_VALUE,
702 				&prm->snd_kctl_volume->id);
703 
704 	return 0;
705 }
706 EXPORT_SYMBOL_GPL(u_audio_set_volume);
707 
708 int u_audio_get_mute(struct g_audio *audio_dev, int playback, int *val)
709 {
710 	struct snd_uac_chip *uac = audio_dev->uac;
711 	struct uac_rtd_params *prm;
712 	unsigned long flags;
713 
714 	if (playback)
715 		prm = &uac->p_prm;
716 	else
717 		prm = &uac->c_prm;
718 
719 	spin_lock_irqsave(&prm->lock, flags);
720 	*val = prm->mute;
721 	spin_unlock_irqrestore(&prm->lock, flags);
722 
723 	return 0;
724 }
725 EXPORT_SYMBOL_GPL(u_audio_get_mute);
726 
727 int u_audio_set_mute(struct g_audio *audio_dev, int playback, int val)
728 {
729 	struct snd_uac_chip *uac = audio_dev->uac;
730 	struct uac_rtd_params *prm;
731 	unsigned long flags;
732 	int change = 0;
733 	int mute;
734 
735 	if (playback)
736 		prm = &uac->p_prm;
737 	else
738 		prm = &uac->c_prm;
739 
740 	mute = val ? 1 : 0;
741 
742 	spin_lock_irqsave(&prm->lock, flags);
743 	if (prm->mute != mute) {
744 		prm->mute = mute;
745 		change = 1;
746 	}
747 	spin_unlock_irqrestore(&prm->lock, flags);
748 
749 	if (change)
750 		snd_ctl_notify(uac->card, SNDRV_CTL_EVENT_MASK_VALUE,
751 			       &prm->snd_kctl_mute->id);
752 
753 	return 0;
754 }
755 EXPORT_SYMBOL_GPL(u_audio_set_mute);
756 
757 
758 static int u_audio_pitch_info(struct snd_kcontrol *kcontrol,
759 				   struct snd_ctl_elem_info *uinfo)
760 {
761 	struct uac_rtd_params *prm = snd_kcontrol_chip(kcontrol);
762 	struct snd_uac_chip *uac = prm->uac;
763 	struct g_audio *audio_dev = uac->audio_dev;
764 	struct uac_params *params = &audio_dev->params;
765 	unsigned int pitch_min, pitch_max;
766 
767 	pitch_min = (1000 - FBACK_SLOW_MAX) * 1000;
768 	pitch_max = (1000 + params->fb_max) * 1000;
769 
770 	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
771 	uinfo->count = 1;
772 	uinfo->value.integer.min = pitch_min;
773 	uinfo->value.integer.max = pitch_max;
774 	uinfo->value.integer.step = 1;
775 	return 0;
776 }
777 
778 static int u_audio_pitch_get(struct snd_kcontrol *kcontrol,
779 				   struct snd_ctl_elem_value *ucontrol)
780 {
781 	struct uac_rtd_params *prm = snd_kcontrol_chip(kcontrol);
782 
783 	ucontrol->value.integer.value[0] = prm->pitch;
784 
785 	return 0;
786 }
787 
788 static int u_audio_pitch_put(struct snd_kcontrol *kcontrol,
789 				  struct snd_ctl_elem_value *ucontrol)
790 {
791 	struct uac_rtd_params *prm = snd_kcontrol_chip(kcontrol);
792 	struct snd_uac_chip *uac = prm->uac;
793 	struct g_audio *audio_dev = uac->audio_dev;
794 	struct uac_params *params = &audio_dev->params;
795 	unsigned int val;
796 	unsigned int pitch_min, pitch_max;
797 	int change = 0;
798 
799 	pitch_min = (1000 - FBACK_SLOW_MAX) * 1000;
800 	pitch_max = (1000 + params->fb_max) * 1000;
801 
802 	val = ucontrol->value.integer.value[0];
803 
804 	if (val < pitch_min)
805 		val = pitch_min;
806 	if (val > pitch_max)
807 		val = pitch_max;
808 
809 	if (prm->pitch != val) {
810 		prm->pitch = val;
811 		change = 1;
812 	}
813 
814 	return change;
815 }
816 
817 static int u_audio_mute_info(struct snd_kcontrol *kcontrol,
818 				   struct snd_ctl_elem_info *uinfo)
819 {
820 	uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
821 	uinfo->count = 1;
822 	uinfo->value.integer.min = 0;
823 	uinfo->value.integer.max = 1;
824 	uinfo->value.integer.step = 1;
825 
826 	return 0;
827 }
828 
829 static int u_audio_mute_get(struct snd_kcontrol *kcontrol,
830 				   struct snd_ctl_elem_value *ucontrol)
831 {
832 	struct uac_rtd_params *prm = snd_kcontrol_chip(kcontrol);
833 	unsigned long flags;
834 
835 	spin_lock_irqsave(&prm->lock, flags);
836 	ucontrol->value.integer.value[0] = !prm->mute;
837 	spin_unlock_irqrestore(&prm->lock, flags);
838 
839 	return 0;
840 }
841 
842 static int u_audio_mute_put(struct snd_kcontrol *kcontrol,
843 				  struct snd_ctl_elem_value *ucontrol)
844 {
845 	struct uac_rtd_params *prm = snd_kcontrol_chip(kcontrol);
846 	struct snd_uac_chip *uac = prm->uac;
847 	struct g_audio *audio_dev = uac->audio_dev;
848 	unsigned int val;
849 	unsigned long flags;
850 	int change = 0;
851 
852 	val = !ucontrol->value.integer.value[0];
853 
854 	spin_lock_irqsave(&prm->lock, flags);
855 	if (val != prm->mute) {
856 		prm->mute = val;
857 		change = 1;
858 	}
859 	spin_unlock_irqrestore(&prm->lock, flags);
860 
861 	if (change && audio_dev->notify)
862 		audio_dev->notify(audio_dev, prm->fu_id, UAC_FU_MUTE);
863 
864 	return change;
865 }
866 
867 /*
868  * TLV callback for mixer volume controls
869  */
870 static int u_audio_volume_tlv(struct snd_kcontrol *kcontrol, int op_flag,
871 			 unsigned int size, unsigned int __user *_tlv)
872 {
873 	struct uac_rtd_params *prm = snd_kcontrol_chip(kcontrol);
874 	DECLARE_TLV_DB_MINMAX(scale, 0, 0);
875 
876 	if (size < sizeof(scale))
877 		return -ENOMEM;
878 
879 	/* UAC volume resolution is 1/256 dB, TLV is 1/100 dB */
880 	scale[2] = (prm->volume_min * 100) / 256;
881 	scale[3] = (prm->volume_max * 100) / 256;
882 	if (copy_to_user(_tlv, scale, sizeof(scale)))
883 		return -EFAULT;
884 
885 	return 0;
886 }
887 
888 static int u_audio_volume_info(struct snd_kcontrol *kcontrol,
889 				   struct snd_ctl_elem_info *uinfo)
890 {
891 	struct uac_rtd_params *prm = snd_kcontrol_chip(kcontrol);
892 
893 	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
894 	uinfo->count = 1;
895 	uinfo->value.integer.min = 0;
896 	uinfo->value.integer.max =
897 		(prm->volume_max - prm->volume_min + prm->volume_res - 1)
898 		/ prm->volume_res;
899 	uinfo->value.integer.step = 1;
900 
901 	return 0;
902 }
903 
904 static int u_audio_volume_get(struct snd_kcontrol *kcontrol,
905 				   struct snd_ctl_elem_value *ucontrol)
906 {
907 	struct uac_rtd_params *prm = snd_kcontrol_chip(kcontrol);
908 	unsigned long flags;
909 
910 	spin_lock_irqsave(&prm->lock, flags);
911 	ucontrol->value.integer.value[0] =
912 			(prm->volume - prm->volume_min) / prm->volume_res;
913 	spin_unlock_irqrestore(&prm->lock, flags);
914 
915 	return 0;
916 }
917 
918 static int u_audio_volume_put(struct snd_kcontrol *kcontrol,
919 				  struct snd_ctl_elem_value *ucontrol)
920 {
921 	struct uac_rtd_params *prm = snd_kcontrol_chip(kcontrol);
922 	struct snd_uac_chip *uac = prm->uac;
923 	struct g_audio *audio_dev = uac->audio_dev;
924 	unsigned int val;
925 	s16 volume;
926 	unsigned long flags;
927 	int change = 0;
928 
929 	val = ucontrol->value.integer.value[0];
930 
931 	spin_lock_irqsave(&prm->lock, flags);
932 	volume = (val * prm->volume_res) + prm->volume_min;
933 	volume = clamp(volume, prm->volume_min, prm->volume_max);
934 	if (volume != prm->volume) {
935 		prm->volume = volume;
936 		change = 1;
937 	}
938 	spin_unlock_irqrestore(&prm->lock, flags);
939 
940 	if (change && audio_dev->notify)
941 		audio_dev->notify(audio_dev, prm->fu_id, UAC_FU_VOLUME);
942 
943 	return change;
944 }
945 
946 
947 static struct snd_kcontrol_new u_audio_controls[]  = {
948   [UAC_FBACK_CTRL] {
949     .iface =        SNDRV_CTL_ELEM_IFACE_PCM,
950     .name =         "Capture Pitch 1000000",
951     .info =         u_audio_pitch_info,
952     .get =          u_audio_pitch_get,
953     .put =          u_audio_pitch_put,
954   },
955 	[UAC_P_PITCH_CTRL] {
956 		.iface =        SNDRV_CTL_ELEM_IFACE_PCM,
957 		.name =         "Playback Pitch 1000000",
958 		.info =         u_audio_pitch_info,
959 		.get =          u_audio_pitch_get,
960 		.put =          u_audio_pitch_put,
961 	},
962   [UAC_MUTE_CTRL] {
963 		.iface =	SNDRV_CTL_ELEM_IFACE_MIXER,
964 		.name =		"", /* will be filled later */
965 		.info =		u_audio_mute_info,
966 		.get =		u_audio_mute_get,
967 		.put =		u_audio_mute_put,
968 	},
969 	[UAC_VOLUME_CTRL] {
970 		.iface =	SNDRV_CTL_ELEM_IFACE_MIXER,
971 		.name =		"", /* will be filled later */
972 		.info =		u_audio_volume_info,
973 		.get =		u_audio_volume_get,
974 		.put =		u_audio_volume_put,
975 	},
976 };
977 
978 int g_audio_setup(struct g_audio *g_audio, const char *pcm_name,
979 					const char *card_name)
980 {
981 	struct snd_uac_chip *uac;
982 	struct snd_card *card;
983 	struct snd_pcm *pcm;
984 	struct snd_kcontrol *kctl;
985 	struct uac_params *params;
986 	int p_chmask, c_chmask;
987 	int i, err;
988 
989 	if (!g_audio)
990 		return -EINVAL;
991 
992 	uac = kzalloc(sizeof(*uac), GFP_KERNEL);
993 	if (!uac)
994 		return -ENOMEM;
995 	g_audio->uac = uac;
996 	uac->audio_dev = g_audio;
997 
998 	params = &g_audio->params;
999 	p_chmask = params->p_chmask;
1000 	c_chmask = params->c_chmask;
1001 
1002 	if (c_chmask) {
1003 		struct uac_rtd_params *prm = &uac->c_prm;
1004 
1005     spin_lock_init(&prm->lock);
1006     uac->c_prm.uac = uac;
1007 		prm->max_psize = g_audio->out_ep_maxpsize;
1008 
1009 		prm->reqs = kcalloc(params->req_number,
1010 				    sizeof(struct usb_request *),
1011 				    GFP_KERNEL);
1012 		if (!prm->reqs) {
1013 			err = -ENOMEM;
1014 			goto fail;
1015 		}
1016 
1017 		prm->rbuf = kcalloc(params->req_number, prm->max_psize,
1018 				GFP_KERNEL);
1019 		if (!prm->rbuf) {
1020 			prm->max_psize = 0;
1021 			err = -ENOMEM;
1022 			goto fail;
1023 		}
1024 	}
1025 
1026 	if (p_chmask) {
1027 		struct uac_rtd_params *prm = &uac->p_prm;
1028 
1029 		spin_lock_init(&prm->lock);
1030 		uac->p_prm.uac = uac;
1031 		prm->max_psize = g_audio->in_ep_maxpsize;
1032 
1033 		prm->reqs = kcalloc(params->req_number,
1034 				    sizeof(struct usb_request *),
1035 				    GFP_KERNEL);
1036 		if (!prm->reqs) {
1037 			err = -ENOMEM;
1038 			goto fail;
1039 		}
1040 
1041 		prm->rbuf = kcalloc(params->req_number, prm->max_psize,
1042 				GFP_KERNEL);
1043 		if (!prm->rbuf) {
1044 			prm->max_psize = 0;
1045 			err = -ENOMEM;
1046 			goto fail;
1047 		}
1048 	}
1049 
1050 	/* Choose any slot, with no id */
1051 	err = snd_card_new(&g_audio->gadget->dev,
1052 			-1, NULL, THIS_MODULE, 0, &card);
1053 	if (err < 0)
1054 		goto fail;
1055 
1056 	uac->card = card;
1057 
1058 	/*
1059 	 * Create first PCM device
1060 	 * Create a substream only for non-zero channel streams
1061 	 */
1062 	err = snd_pcm_new(uac->card, pcm_name, 0,
1063 			       p_chmask ? 1 : 0, c_chmask ? 1 : 0, &pcm);
1064 	if (err < 0)
1065 		goto snd_fail;
1066 
1067 	strscpy(pcm->name, pcm_name, sizeof(pcm->name));
1068 	pcm->private_data = uac;
1069 	uac->pcm = pcm;
1070 
1071 	snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &uac_pcm_ops);
1072 	snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &uac_pcm_ops);
1073 
1074 	/*
1075 	 * Create mixer and controls
1076 	 * Create only if it's required on USB side
1077 	 */
1078 	if ((c_chmask && g_audio->in_ep_fback)
1079 			|| (p_chmask && params->p_fu.id)
1080 			|| (c_chmask && params->c_fu.id))
1081 		strscpy(card->mixername, card_name, sizeof(card->driver));
1082 
1083 	if (c_chmask && g_audio->in_ep_fback) {
1084 		kctl = snd_ctl_new1(&u_audio_controls[UAC_FBACK_CTRL],
1085 				    &uac->c_prm);
1086 		if (!kctl) {
1087 			err = -ENOMEM;
1088 			goto snd_fail;
1089 		}
1090 
1091 		kctl->id.device = pcm->device;
1092 		kctl->id.subdevice = 0;
1093 
1094 		err = snd_ctl_add(card, kctl);
1095 		if (err < 0)
1096 			goto snd_fail;
1097 	}
1098 
1099 	if (p_chmask) {
1100 		kctl = snd_ctl_new1(&u_audio_controls[UAC_P_PITCH_CTRL],
1101 				    &uac->p_prm);
1102 		if (!kctl) {
1103 			err = -ENOMEM;
1104 			goto snd_fail;
1105 		}
1106 
1107 		kctl->id.device = pcm->device;
1108 		kctl->id.subdevice = 0;
1109 
1110 		err = snd_ctl_add(card, kctl);
1111 		if (err < 0)
1112 			goto snd_fail;
1113 	}
1114 
1115 	for (i = 0; i <= SNDRV_PCM_STREAM_LAST; i++) {
1116 		struct uac_rtd_params *prm;
1117 		struct uac_fu_params *fu;
1118 		char ctrl_name[24];
1119 		char *direction;
1120 
1121 		if (!pcm->streams[i].substream_count)
1122 			continue;
1123 
1124 		if (i == SNDRV_PCM_STREAM_PLAYBACK) {
1125 			prm = &uac->p_prm;
1126 			fu = &params->p_fu;
1127 			direction = "Playback";
1128 		} else {
1129 			prm = &uac->c_prm;
1130 			fu = &params->c_fu;
1131 			direction = "Capture";
1132 		}
1133 
1134 		prm->fu_id = fu->id;
1135 
1136 		if (fu->mute_present) {
1137 			snprintf(ctrl_name, sizeof(ctrl_name),
1138 					"PCM %s Switch", direction);
1139 
1140 			u_audio_controls[UAC_MUTE_CTRL].name = ctrl_name;
1141 
1142 			kctl = snd_ctl_new1(&u_audio_controls[UAC_MUTE_CTRL],
1143 					    prm);
1144 			if (!kctl) {
1145 				err = -ENOMEM;
1146 				goto snd_fail;
1147 			}
1148 
1149 			kctl->id.device = pcm->device;
1150 			kctl->id.subdevice = 0;
1151 
1152 			err = snd_ctl_add(card, kctl);
1153 			if (err < 0)
1154 				goto snd_fail;
1155 			prm->snd_kctl_mute = kctl;
1156 			prm->mute = 0;
1157 		}
1158 
1159 		if (fu->volume_present) {
1160 			snprintf(ctrl_name, sizeof(ctrl_name),
1161 					"PCM %s Volume", direction);
1162 
1163 			u_audio_controls[UAC_VOLUME_CTRL].name = ctrl_name;
1164 
1165 			kctl = snd_ctl_new1(&u_audio_controls[UAC_VOLUME_CTRL],
1166 					    prm);
1167 			if (!kctl) {
1168 				err = -ENOMEM;
1169 				goto snd_fail;
1170 			}
1171 
1172 			kctl->id.device = pcm->device;
1173 			kctl->id.subdevice = 0;
1174 
1175 
1176 			kctl->tlv.c = u_audio_volume_tlv;
1177 			kctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_TLV_READ |
1178 					SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
1179 
1180 			err = snd_ctl_add(card, kctl);
1181 			if (err < 0)
1182 				goto snd_fail;
1183 			prm->snd_kctl_volume = kctl;
1184 			prm->volume = fu->volume_max;
1185 			prm->volume_max = fu->volume_max;
1186 			prm->volume_min = fu->volume_min;
1187 			prm->volume_res = fu->volume_res;
1188 		}
1189 	}
1190 
1191 	strscpy(card->driver, card_name, sizeof(card->driver));
1192 	strscpy(card->shortname, card_name, sizeof(card->shortname));
1193 	sprintf(card->longname, "%s %i", card_name, card->dev->id);
1194 
1195 	snd_pcm_set_managed_buffer_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS,
1196 				       NULL, 0, BUFF_SIZE_MAX);
1197 
1198 	err = snd_card_register(card);
1199 
1200 	if (!err)
1201 		return 0;
1202 
1203 snd_fail:
1204 	snd_card_free(card);
1205 fail:
1206 	kfree(uac->p_prm.reqs);
1207 	kfree(uac->c_prm.reqs);
1208 	kfree(uac->p_prm.rbuf);
1209 	kfree(uac->c_prm.rbuf);
1210 	kfree(uac);
1211 
1212 	return err;
1213 }
1214 EXPORT_SYMBOL_GPL(g_audio_setup);
1215 
1216 void g_audio_cleanup(struct g_audio *g_audio)
1217 {
1218 	struct snd_uac_chip *uac;
1219 	struct snd_card *card;
1220 
1221 	if (!g_audio || !g_audio->uac)
1222 		return;
1223 
1224 	uac = g_audio->uac;
1225 	card = uac->card;
1226 	if (card)
1227 		snd_card_free(card);
1228 
1229 	kfree(uac->p_prm.reqs);
1230 	kfree(uac->c_prm.reqs);
1231 	kfree(uac->p_prm.rbuf);
1232 	kfree(uac->c_prm.rbuf);
1233 	kfree(uac);
1234 }
1235 EXPORT_SYMBOL_GPL(g_audio_cleanup);
1236 
1237 MODULE_LICENSE("GPL");
1238 MODULE_DESCRIPTION("USB gadget \"ALSA sound card\" utilities");
1239 MODULE_AUTHOR("Ruslan Bilovol");
1240