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