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/module.h>
16 #include <sound/core.h>
17 #include <sound/pcm.h>
18 #include <sound/pcm_params.h>
19 
20 #include "u_audio.h"
21 
22 #define BUFF_SIZE_MAX	(PAGE_SIZE * 16)
23 #define PRD_SIZE_MAX	PAGE_SIZE
24 #define MIN_PERIODS	4
25 
26 struct uac_req {
27 	struct uac_rtd_params *pp; /* parent param */
28 	struct usb_request *req;
29 };
30 
31 /* Runtime data params for one stream */
32 struct uac_rtd_params {
33 	struct snd_uac_chip *uac; /* parent chip */
34 	bool ep_enabled; /* if the ep is enabled */
35 
36 	struct snd_pcm_substream *ss;
37 
38 	/* Ring buffer */
39 	ssize_t hw_ptr;
40 
41 	void *rbuf;
42 
43 	unsigned int max_psize;	/* MaxPacketSize of endpoint */
44 	struct uac_req *ureq;
45 
46 	spinlock_t lock;
47 };
48 
49 struct snd_uac_chip {
50 	struct g_audio *audio_dev;
51 
52 	struct uac_rtd_params p_prm;
53 	struct uac_rtd_params c_prm;
54 
55 	struct snd_card *card;
56 	struct snd_pcm *pcm;
57 
58 	/* timekeeping for the playback endpoint */
59 	unsigned int p_interval;
60 	unsigned int p_residue;
61 
62 	/* pre-calculated values for playback iso completion */
63 	unsigned int p_pktsize;
64 	unsigned int p_pktsize_residue;
65 	unsigned int p_framesize;
66 };
67 
68 static const struct snd_pcm_hardware uac_pcm_hardware = {
69 	.info = SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER
70 		 | SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID
71 		 | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME,
72 	.rates = SNDRV_PCM_RATE_CONTINUOUS,
73 	.periods_max = BUFF_SIZE_MAX / PRD_SIZE_MAX,
74 	.buffer_bytes_max = BUFF_SIZE_MAX,
75 	.period_bytes_max = PRD_SIZE_MAX,
76 	.periods_min = MIN_PERIODS,
77 };
78 
79 static void u_audio_iso_complete(struct usb_ep *ep, struct usb_request *req)
80 {
81 	unsigned int pending;
82 	unsigned long flags, flags2;
83 	unsigned int hw_ptr;
84 	int status = req->status;
85 	struct uac_req *ur = req->context;
86 	struct snd_pcm_substream *substream;
87 	struct snd_pcm_runtime *runtime;
88 	struct uac_rtd_params *prm = ur->pp;
89 	struct snd_uac_chip *uac = prm->uac;
90 
91 	/* i/f shutting down */
92 	if (!prm->ep_enabled || req->status == -ESHUTDOWN)
93 		return;
94 
95 	/*
96 	 * We can't really do much about bad xfers.
97 	 * Afterall, the ISOCH xfers could fail legitimately.
98 	 */
99 	if (status)
100 		pr_debug("%s: iso_complete status(%d) %d/%d\n",
101 			__func__, status, req->actual, req->length);
102 
103 	substream = prm->ss;
104 
105 	/* Do nothing if ALSA isn't active */
106 	if (!substream)
107 		goto exit;
108 
109 	snd_pcm_stream_lock_irqsave(substream, flags2);
110 
111 	runtime = substream->runtime;
112 	if (!runtime || !snd_pcm_running(substream)) {
113 		snd_pcm_stream_unlock_irqrestore(substream, flags2);
114 		goto exit;
115 	}
116 
117 	spin_lock_irqsave(&prm->lock, flags);
118 
119 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
120 		/*
121 		 * For each IN packet, take the quotient of the current data
122 		 * rate and the endpoint's interval as the base packet size.
123 		 * If there is a residue from this division, add it to the
124 		 * residue accumulator.
125 		 */
126 		req->length = uac->p_pktsize;
127 		uac->p_residue += uac->p_pktsize_residue;
128 
129 		/*
130 		 * Whenever there are more bytes in the accumulator than we
131 		 * need to add one more sample frame, increase this packet's
132 		 * size and decrease the accumulator.
133 		 */
134 		if (uac->p_residue / uac->p_interval >= uac->p_framesize) {
135 			req->length += uac->p_framesize;
136 			uac->p_residue -= uac->p_framesize *
137 					   uac->p_interval;
138 		}
139 
140 		req->actual = req->length;
141 	}
142 
143 	hw_ptr = prm->hw_ptr;
144 
145 	spin_unlock_irqrestore(&prm->lock, flags);
146 
147 	/* Pack USB load in ALSA ring buffer */
148 	pending = runtime->dma_bytes - hw_ptr;
149 
150 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
151 		if (unlikely(pending < req->actual)) {
152 			memcpy(req->buf, runtime->dma_area + hw_ptr, pending);
153 			memcpy(req->buf + pending, runtime->dma_area,
154 			       req->actual - pending);
155 		} else {
156 			memcpy(req->buf, runtime->dma_area + hw_ptr,
157 			       req->actual);
158 		}
159 	} else {
160 		if (unlikely(pending < req->actual)) {
161 			memcpy(runtime->dma_area + hw_ptr, req->buf, pending);
162 			memcpy(runtime->dma_area, req->buf + pending,
163 			       req->actual - pending);
164 		} else {
165 			memcpy(runtime->dma_area + hw_ptr, req->buf,
166 			       req->actual);
167 		}
168 	}
169 
170 	spin_lock_irqsave(&prm->lock, flags);
171 	/* update hw_ptr after data is copied to memory */
172 	prm->hw_ptr = (hw_ptr + req->actual) % runtime->dma_bytes;
173 	hw_ptr = prm->hw_ptr;
174 	spin_unlock_irqrestore(&prm->lock, flags);
175 	snd_pcm_stream_unlock_irqrestore(substream, flags2);
176 
177 	if ((hw_ptr % snd_pcm_lib_period_bytes(substream)) < req->actual)
178 		snd_pcm_period_elapsed(substream);
179 
180 exit:
181 	if (usb_ep_queue(ep, req, GFP_ATOMIC))
182 		dev_err(uac->card->dev, "%d Error!\n", __LINE__);
183 }
184 
185 static int uac_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
186 {
187 	struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
188 	struct uac_rtd_params *prm;
189 	struct g_audio *audio_dev;
190 	struct uac_params *params;
191 	unsigned long flags;
192 	int err = 0;
193 
194 	audio_dev = uac->audio_dev;
195 	params = &audio_dev->params;
196 
197 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
198 		prm = &uac->p_prm;
199 	else
200 		prm = &uac->c_prm;
201 
202 	spin_lock_irqsave(&prm->lock, flags);
203 
204 	/* Reset */
205 	prm->hw_ptr = 0;
206 
207 	switch (cmd) {
208 	case SNDRV_PCM_TRIGGER_START:
209 	case SNDRV_PCM_TRIGGER_RESUME:
210 		prm->ss = substream;
211 		break;
212 	case SNDRV_PCM_TRIGGER_STOP:
213 	case SNDRV_PCM_TRIGGER_SUSPEND:
214 		prm->ss = NULL;
215 		break;
216 	default:
217 		err = -EINVAL;
218 	}
219 
220 	spin_unlock_irqrestore(&prm->lock, flags);
221 
222 	/* Clear buffer after Play stops */
223 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK && !prm->ss)
224 		memset(prm->rbuf, 0, prm->max_psize * params->req_number);
225 
226 	return err;
227 }
228 
229 static snd_pcm_uframes_t uac_pcm_pointer(struct snd_pcm_substream *substream)
230 {
231 	struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
232 	struct uac_rtd_params *prm;
233 
234 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
235 		prm = &uac->p_prm;
236 	else
237 		prm = &uac->c_prm;
238 
239 	return bytes_to_frames(substream->runtime, prm->hw_ptr);
240 }
241 
242 static int uac_pcm_hw_params(struct snd_pcm_substream *substream,
243 			       struct snd_pcm_hw_params *hw_params)
244 {
245 	return snd_pcm_lib_malloc_pages(substream,
246 					params_buffer_bytes(hw_params));
247 }
248 
249 static int uac_pcm_hw_free(struct snd_pcm_substream *substream)
250 {
251 	return snd_pcm_lib_free_pages(substream);
252 }
253 
254 static int uac_pcm_open(struct snd_pcm_substream *substream)
255 {
256 	struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
257 	struct snd_pcm_runtime *runtime = substream->runtime;
258 	struct g_audio *audio_dev;
259 	struct uac_params *params;
260 	int p_ssize, c_ssize;
261 	int p_srate, c_srate;
262 	int p_chmask, c_chmask;
263 
264 	audio_dev = uac->audio_dev;
265 	params = &audio_dev->params;
266 	p_ssize = params->p_ssize;
267 	c_ssize = params->c_ssize;
268 	p_srate = params->p_srate;
269 	c_srate = params->c_srate;
270 	p_chmask = params->p_chmask;
271 	c_chmask = params->c_chmask;
272 	uac->p_residue = 0;
273 
274 	runtime->hw = uac_pcm_hardware;
275 
276 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
277 		spin_lock_init(&uac->p_prm.lock);
278 		runtime->hw.rate_min = p_srate;
279 		switch (p_ssize) {
280 		case 3:
281 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S24_3LE;
282 			break;
283 		case 4:
284 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S32_LE;
285 			break;
286 		default:
287 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
288 			break;
289 		}
290 		runtime->hw.channels_min = num_channels(p_chmask);
291 		runtime->hw.period_bytes_min = 2 * uac->p_prm.max_psize
292 						/ runtime->hw.periods_min;
293 	} else {
294 		spin_lock_init(&uac->c_prm.lock);
295 		runtime->hw.rate_min = c_srate;
296 		switch (c_ssize) {
297 		case 3:
298 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S24_3LE;
299 			break;
300 		case 4:
301 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S32_LE;
302 			break;
303 		default:
304 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
305 			break;
306 		}
307 		runtime->hw.channels_min = num_channels(c_chmask);
308 		runtime->hw.period_bytes_min = 2 * uac->c_prm.max_psize
309 						/ runtime->hw.periods_min;
310 	}
311 
312 	runtime->hw.rate_max = runtime->hw.rate_min;
313 	runtime->hw.channels_max = runtime->hw.channels_min;
314 
315 	snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
316 
317 	return 0;
318 }
319 
320 /* ALSA cries without these function pointers */
321 static int uac_pcm_null(struct snd_pcm_substream *substream)
322 {
323 	return 0;
324 }
325 
326 static const struct snd_pcm_ops uac_pcm_ops = {
327 	.open = uac_pcm_open,
328 	.close = uac_pcm_null,
329 	.ioctl = snd_pcm_lib_ioctl,
330 	.hw_params = uac_pcm_hw_params,
331 	.hw_free = uac_pcm_hw_free,
332 	.trigger = uac_pcm_trigger,
333 	.pointer = uac_pcm_pointer,
334 	.prepare = uac_pcm_null,
335 };
336 
337 static inline void free_ep(struct uac_rtd_params *prm, struct usb_ep *ep)
338 {
339 	struct snd_uac_chip *uac = prm->uac;
340 	struct g_audio *audio_dev;
341 	struct uac_params *params;
342 	int i;
343 
344 	if (!prm->ep_enabled)
345 		return;
346 
347 	prm->ep_enabled = false;
348 
349 	audio_dev = uac->audio_dev;
350 	params = &audio_dev->params;
351 
352 	for (i = 0; i < params->req_number; i++) {
353 		if (prm->ureq[i].req) {
354 			usb_ep_dequeue(ep, prm->ureq[i].req);
355 			usb_ep_free_request(ep, prm->ureq[i].req);
356 			prm->ureq[i].req = NULL;
357 		}
358 	}
359 
360 	if (usb_ep_disable(ep))
361 		dev_err(uac->card->dev, "%s:%d Error!\n", __func__, __LINE__);
362 }
363 
364 
365 int u_audio_start_capture(struct g_audio *audio_dev)
366 {
367 	struct snd_uac_chip *uac = audio_dev->uac;
368 	struct usb_gadget *gadget = audio_dev->gadget;
369 	struct device *dev = &gadget->dev;
370 	struct usb_request *req;
371 	struct usb_ep *ep;
372 	struct uac_rtd_params *prm;
373 	struct uac_params *params = &audio_dev->params;
374 	int req_len, i;
375 
376 	ep = audio_dev->out_ep;
377 	prm = &uac->c_prm;
378 	config_ep_by_speed(gadget, &audio_dev->func, ep);
379 	req_len = prm->max_psize;
380 
381 	prm->ep_enabled = true;
382 	usb_ep_enable(ep);
383 
384 	for (i = 0; i < params->req_number; i++) {
385 		if (!prm->ureq[i].req) {
386 			req = usb_ep_alloc_request(ep, GFP_ATOMIC);
387 			if (req == NULL)
388 				return -ENOMEM;
389 
390 			prm->ureq[i].req = req;
391 			prm->ureq[i].pp = prm;
392 
393 			req->zero = 0;
394 			req->context = &prm->ureq[i];
395 			req->length = req_len;
396 			req->complete = u_audio_iso_complete;
397 			req->buf = prm->rbuf + i * prm->max_psize;
398 		}
399 
400 		if (usb_ep_queue(ep, prm->ureq[i].req, GFP_ATOMIC))
401 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
402 	}
403 
404 	return 0;
405 }
406 EXPORT_SYMBOL_GPL(u_audio_start_capture);
407 
408 void u_audio_stop_capture(struct g_audio *audio_dev)
409 {
410 	struct snd_uac_chip *uac = audio_dev->uac;
411 
412 	free_ep(&uac->c_prm, audio_dev->out_ep);
413 }
414 EXPORT_SYMBOL_GPL(u_audio_stop_capture);
415 
416 int u_audio_start_playback(struct g_audio *audio_dev)
417 {
418 	struct snd_uac_chip *uac = audio_dev->uac;
419 	struct usb_gadget *gadget = audio_dev->gadget;
420 	struct device *dev = &gadget->dev;
421 	struct usb_request *req;
422 	struct usb_ep *ep;
423 	struct uac_rtd_params *prm;
424 	struct uac_params *params = &audio_dev->params;
425 	unsigned int factor, rate;
426 	const struct usb_endpoint_descriptor *ep_desc;
427 	int req_len, i;
428 
429 	ep = audio_dev->in_ep;
430 	prm = &uac->p_prm;
431 	config_ep_by_speed(gadget, &audio_dev->func, ep);
432 
433 	ep_desc = ep->desc;
434 
435 	/* pre-calculate the playback endpoint's interval */
436 	if (gadget->speed == USB_SPEED_FULL)
437 		factor = 1000;
438 	else
439 		factor = 8000;
440 
441 	/* pre-compute some values for iso_complete() */
442 	uac->p_framesize = params->p_ssize *
443 			    num_channels(params->p_chmask);
444 	rate = params->p_srate * uac->p_framesize;
445 	uac->p_interval = factor / (1 << (ep_desc->bInterval - 1));
446 	uac->p_pktsize = min_t(unsigned int, rate / uac->p_interval,
447 				prm->max_psize);
448 
449 	if (uac->p_pktsize < prm->max_psize)
450 		uac->p_pktsize_residue = rate % uac->p_interval;
451 	else
452 		uac->p_pktsize_residue = 0;
453 
454 	req_len = uac->p_pktsize;
455 	uac->p_residue = 0;
456 
457 	prm->ep_enabled = true;
458 	usb_ep_enable(ep);
459 
460 	for (i = 0; i < params->req_number; i++) {
461 		if (!prm->ureq[i].req) {
462 			req = usb_ep_alloc_request(ep, GFP_ATOMIC);
463 			if (req == NULL)
464 				return -ENOMEM;
465 
466 			prm->ureq[i].req = req;
467 			prm->ureq[i].pp = prm;
468 
469 			req->zero = 0;
470 			req->context = &prm->ureq[i];
471 			req->length = req_len;
472 			req->complete = u_audio_iso_complete;
473 			req->buf = prm->rbuf + i * prm->max_psize;
474 		}
475 
476 		if (usb_ep_queue(ep, prm->ureq[i].req, GFP_ATOMIC))
477 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
478 	}
479 
480 	return 0;
481 }
482 EXPORT_SYMBOL_GPL(u_audio_start_playback);
483 
484 void u_audio_stop_playback(struct g_audio *audio_dev)
485 {
486 	struct snd_uac_chip *uac = audio_dev->uac;
487 
488 	free_ep(&uac->p_prm, audio_dev->in_ep);
489 }
490 EXPORT_SYMBOL_GPL(u_audio_stop_playback);
491 
492 int g_audio_setup(struct g_audio *g_audio, const char *pcm_name,
493 					const char *card_name)
494 {
495 	struct snd_uac_chip *uac;
496 	struct snd_card *card;
497 	struct snd_pcm *pcm;
498 	struct uac_params *params;
499 	int p_chmask, c_chmask;
500 	int err;
501 
502 	if (!g_audio)
503 		return -EINVAL;
504 
505 	uac = kzalloc(sizeof(*uac), GFP_KERNEL);
506 	if (!uac)
507 		return -ENOMEM;
508 	g_audio->uac = uac;
509 	uac->audio_dev = g_audio;
510 
511 	params = &g_audio->params;
512 	p_chmask = params->p_chmask;
513 	c_chmask = params->c_chmask;
514 
515 	if (c_chmask) {
516 		struct uac_rtd_params *prm = &uac->c_prm;
517 
518 		uac->c_prm.uac = uac;
519 		prm->max_psize = g_audio->out_ep_maxpsize;
520 
521 		prm->ureq = kcalloc(params->req_number, sizeof(struct uac_req),
522 				GFP_KERNEL);
523 		if (!prm->ureq) {
524 			err = -ENOMEM;
525 			goto fail;
526 		}
527 
528 		prm->rbuf = kcalloc(params->req_number, prm->max_psize,
529 				GFP_KERNEL);
530 		if (!prm->rbuf) {
531 			prm->max_psize = 0;
532 			err = -ENOMEM;
533 			goto fail;
534 		}
535 	}
536 
537 	if (p_chmask) {
538 		struct uac_rtd_params *prm = &uac->p_prm;
539 
540 		uac->p_prm.uac = uac;
541 		prm->max_psize = g_audio->in_ep_maxpsize;
542 
543 		prm->ureq = kcalloc(params->req_number, sizeof(struct uac_req),
544 				GFP_KERNEL);
545 		if (!prm->ureq) {
546 			err = -ENOMEM;
547 			goto fail;
548 		}
549 
550 		prm->rbuf = kcalloc(params->req_number, prm->max_psize,
551 				GFP_KERNEL);
552 		if (!prm->rbuf) {
553 			prm->max_psize = 0;
554 			err = -ENOMEM;
555 			goto fail;
556 		}
557 	}
558 
559 	/* Choose any slot, with no id */
560 	err = snd_card_new(&g_audio->gadget->dev,
561 			-1, NULL, THIS_MODULE, 0, &card);
562 	if (err < 0)
563 		goto fail;
564 
565 	uac->card = card;
566 
567 	/*
568 	 * Create first PCM device
569 	 * Create a substream only for non-zero channel streams
570 	 */
571 	err = snd_pcm_new(uac->card, pcm_name, 0,
572 			       p_chmask ? 1 : 0, c_chmask ? 1 : 0, &pcm);
573 	if (err < 0)
574 		goto snd_fail;
575 
576 	strlcpy(pcm->name, pcm_name, sizeof(pcm->name));
577 	pcm->private_data = uac;
578 	uac->pcm = pcm;
579 
580 	snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &uac_pcm_ops);
581 	snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &uac_pcm_ops);
582 
583 	strlcpy(card->driver, card_name, sizeof(card->driver));
584 	strlcpy(card->shortname, card_name, sizeof(card->shortname));
585 	sprintf(card->longname, "%s %i", card_name, card->dev->id);
586 
587 	snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS,
588 					      NULL, 0, BUFF_SIZE_MAX);
589 
590 	err = snd_card_register(card);
591 
592 	if (!err)
593 		return 0;
594 
595 snd_fail:
596 	snd_card_free(card);
597 fail:
598 	kfree(uac->p_prm.ureq);
599 	kfree(uac->c_prm.ureq);
600 	kfree(uac->p_prm.rbuf);
601 	kfree(uac->c_prm.rbuf);
602 	kfree(uac);
603 
604 	return err;
605 }
606 EXPORT_SYMBOL_GPL(g_audio_setup);
607 
608 void g_audio_cleanup(struct g_audio *g_audio)
609 {
610 	struct snd_uac_chip *uac;
611 	struct snd_card *card;
612 
613 	if (!g_audio || !g_audio->uac)
614 		return;
615 
616 	uac = g_audio->uac;
617 	card = uac->card;
618 	if (card)
619 		snd_card_free(card);
620 
621 	kfree(uac->p_prm.ureq);
622 	kfree(uac->c_prm.ureq);
623 	kfree(uac->p_prm.rbuf);
624 	kfree(uac->c_prm.rbuf);
625 	kfree(uac);
626 }
627 EXPORT_SYMBOL_GPL(g_audio_cleanup);
628 
629 MODULE_LICENSE("GPL");
630 MODULE_DESCRIPTION("USB gadget \"ALSA sound card\" utilities");
631 MODULE_AUTHOR("Ruslan Bilovol");
632