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