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_open(struct snd_pcm_substream *substream)
243 {
244 	struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
245 	struct snd_pcm_runtime *runtime = substream->runtime;
246 	struct g_audio *audio_dev;
247 	struct uac_params *params;
248 	int p_ssize, c_ssize;
249 	int p_srate, c_srate;
250 	int p_chmask, c_chmask;
251 
252 	audio_dev = uac->audio_dev;
253 	params = &audio_dev->params;
254 	p_ssize = params->p_ssize;
255 	c_ssize = params->c_ssize;
256 	p_srate = params->p_srate;
257 	c_srate = params->c_srate;
258 	p_chmask = params->p_chmask;
259 	c_chmask = params->c_chmask;
260 	uac->p_residue = 0;
261 
262 	runtime->hw = uac_pcm_hardware;
263 
264 	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
265 		spin_lock_init(&uac->p_prm.lock);
266 		runtime->hw.rate_min = p_srate;
267 		switch (p_ssize) {
268 		case 3:
269 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S24_3LE;
270 			break;
271 		case 4:
272 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S32_LE;
273 			break;
274 		default:
275 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
276 			break;
277 		}
278 		runtime->hw.channels_min = num_channels(p_chmask);
279 		runtime->hw.period_bytes_min = 2 * uac->p_prm.max_psize
280 						/ runtime->hw.periods_min;
281 	} else {
282 		spin_lock_init(&uac->c_prm.lock);
283 		runtime->hw.rate_min = c_srate;
284 		switch (c_ssize) {
285 		case 3:
286 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S24_3LE;
287 			break;
288 		case 4:
289 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S32_LE;
290 			break;
291 		default:
292 			runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
293 			break;
294 		}
295 		runtime->hw.channels_min = num_channels(c_chmask);
296 		runtime->hw.period_bytes_min = 2 * uac->c_prm.max_psize
297 						/ runtime->hw.periods_min;
298 	}
299 
300 	runtime->hw.rate_max = runtime->hw.rate_min;
301 	runtime->hw.channels_max = runtime->hw.channels_min;
302 
303 	snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
304 
305 	return 0;
306 }
307 
308 /* ALSA cries without these function pointers */
309 static int uac_pcm_null(struct snd_pcm_substream *substream)
310 {
311 	return 0;
312 }
313 
314 static const struct snd_pcm_ops uac_pcm_ops = {
315 	.open = uac_pcm_open,
316 	.close = uac_pcm_null,
317 	.trigger = uac_pcm_trigger,
318 	.pointer = uac_pcm_pointer,
319 	.prepare = uac_pcm_null,
320 };
321 
322 static inline void free_ep(struct uac_rtd_params *prm, struct usb_ep *ep)
323 {
324 	struct snd_uac_chip *uac = prm->uac;
325 	struct g_audio *audio_dev;
326 	struct uac_params *params;
327 	int i;
328 
329 	if (!prm->ep_enabled)
330 		return;
331 
332 	prm->ep_enabled = false;
333 
334 	audio_dev = uac->audio_dev;
335 	params = &audio_dev->params;
336 
337 	for (i = 0; i < params->req_number; i++) {
338 		if (prm->ureq[i].req) {
339 			usb_ep_dequeue(ep, prm->ureq[i].req);
340 			usb_ep_free_request(ep, prm->ureq[i].req);
341 			prm->ureq[i].req = NULL;
342 		}
343 	}
344 
345 	if (usb_ep_disable(ep))
346 		dev_err(uac->card->dev, "%s:%d Error!\n", __func__, __LINE__);
347 }
348 
349 
350 int u_audio_start_capture(struct g_audio *audio_dev)
351 {
352 	struct snd_uac_chip *uac = audio_dev->uac;
353 	struct usb_gadget *gadget = audio_dev->gadget;
354 	struct device *dev = &gadget->dev;
355 	struct usb_request *req;
356 	struct usb_ep *ep;
357 	struct uac_rtd_params *prm;
358 	struct uac_params *params = &audio_dev->params;
359 	int req_len, i;
360 
361 	ep = audio_dev->out_ep;
362 	prm = &uac->c_prm;
363 	config_ep_by_speed(gadget, &audio_dev->func, ep);
364 	req_len = ep->maxpacket;
365 
366 	prm->ep_enabled = true;
367 	usb_ep_enable(ep);
368 
369 	for (i = 0; i < params->req_number; i++) {
370 		if (!prm->ureq[i].req) {
371 			req = usb_ep_alloc_request(ep, GFP_ATOMIC);
372 			if (req == NULL)
373 				return -ENOMEM;
374 
375 			prm->ureq[i].req = req;
376 			prm->ureq[i].pp = prm;
377 
378 			req->zero = 0;
379 			req->context = &prm->ureq[i];
380 			req->length = req_len;
381 			req->complete = u_audio_iso_complete;
382 			req->buf = prm->rbuf + i * ep->maxpacket;
383 		}
384 
385 		if (usb_ep_queue(ep, prm->ureq[i].req, GFP_ATOMIC))
386 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
387 	}
388 
389 	return 0;
390 }
391 EXPORT_SYMBOL_GPL(u_audio_start_capture);
392 
393 void u_audio_stop_capture(struct g_audio *audio_dev)
394 {
395 	struct snd_uac_chip *uac = audio_dev->uac;
396 
397 	free_ep(&uac->c_prm, audio_dev->out_ep);
398 }
399 EXPORT_SYMBOL_GPL(u_audio_stop_capture);
400 
401 int u_audio_start_playback(struct g_audio *audio_dev)
402 {
403 	struct snd_uac_chip *uac = audio_dev->uac;
404 	struct usb_gadget *gadget = audio_dev->gadget;
405 	struct device *dev = &gadget->dev;
406 	struct usb_request *req;
407 	struct usb_ep *ep;
408 	struct uac_rtd_params *prm;
409 	struct uac_params *params = &audio_dev->params;
410 	unsigned int factor;
411 	const struct usb_endpoint_descriptor *ep_desc;
412 	int req_len, i;
413 
414 	ep = audio_dev->in_ep;
415 	prm = &uac->p_prm;
416 	config_ep_by_speed(gadget, &audio_dev->func, ep);
417 
418 	ep_desc = ep->desc;
419 
420 	/* pre-calculate the playback endpoint's interval */
421 	if (gadget->speed == USB_SPEED_FULL)
422 		factor = 1000;
423 	else
424 		factor = 8000;
425 
426 	/* pre-compute some values for iso_complete() */
427 	uac->p_framesize = params->p_ssize *
428 			    num_channels(params->p_chmask);
429 	uac->p_interval = factor / (1 << (ep_desc->bInterval - 1));
430 	uac->p_pktsize = min_t(unsigned int,
431 				uac->p_framesize *
432 					(params->p_srate / uac->p_interval),
433 				ep->maxpacket);
434 
435 	if (uac->p_pktsize < ep->maxpacket)
436 		uac->p_pktsize_residue = uac->p_framesize *
437 			(params->p_srate % uac->p_interval);
438 	else
439 		uac->p_pktsize_residue = 0;
440 
441 	req_len = uac->p_pktsize;
442 	uac->p_residue = 0;
443 
444 	prm->ep_enabled = true;
445 	usb_ep_enable(ep);
446 
447 	for (i = 0; i < params->req_number; i++) {
448 		if (!prm->ureq[i].req) {
449 			req = usb_ep_alloc_request(ep, GFP_ATOMIC);
450 			if (req == NULL)
451 				return -ENOMEM;
452 
453 			prm->ureq[i].req = req;
454 			prm->ureq[i].pp = prm;
455 
456 			req->zero = 0;
457 			req->context = &prm->ureq[i];
458 			req->length = req_len;
459 			req->complete = u_audio_iso_complete;
460 			req->buf = prm->rbuf + i * ep->maxpacket;
461 		}
462 
463 		if (usb_ep_queue(ep, prm->ureq[i].req, GFP_ATOMIC))
464 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
465 	}
466 
467 	return 0;
468 }
469 EXPORT_SYMBOL_GPL(u_audio_start_playback);
470 
471 void u_audio_stop_playback(struct g_audio *audio_dev)
472 {
473 	struct snd_uac_chip *uac = audio_dev->uac;
474 
475 	free_ep(&uac->p_prm, audio_dev->in_ep);
476 }
477 EXPORT_SYMBOL_GPL(u_audio_stop_playback);
478 
479 int g_audio_setup(struct g_audio *g_audio, const char *pcm_name,
480 					const char *card_name)
481 {
482 	struct snd_uac_chip *uac;
483 	struct snd_card *card;
484 	struct snd_pcm *pcm;
485 	struct uac_params *params;
486 	int p_chmask, c_chmask;
487 	int err;
488 
489 	if (!g_audio)
490 		return -EINVAL;
491 
492 	uac = kzalloc(sizeof(*uac), GFP_KERNEL);
493 	if (!uac)
494 		return -ENOMEM;
495 	g_audio->uac = uac;
496 	uac->audio_dev = g_audio;
497 
498 	params = &g_audio->params;
499 	p_chmask = params->p_chmask;
500 	c_chmask = params->c_chmask;
501 
502 	if (c_chmask) {
503 		struct uac_rtd_params *prm = &uac->c_prm;
504 
505 		uac->c_prm.uac = uac;
506 		prm->max_psize = g_audio->out_ep_maxpsize;
507 
508 		prm->ureq = kcalloc(params->req_number, sizeof(struct uac_req),
509 				GFP_KERNEL);
510 		if (!prm->ureq) {
511 			err = -ENOMEM;
512 			goto fail;
513 		}
514 
515 		prm->rbuf = kcalloc(params->req_number, prm->max_psize,
516 				GFP_KERNEL);
517 		if (!prm->rbuf) {
518 			prm->max_psize = 0;
519 			err = -ENOMEM;
520 			goto fail;
521 		}
522 	}
523 
524 	if (p_chmask) {
525 		struct uac_rtd_params *prm = &uac->p_prm;
526 
527 		uac->p_prm.uac = uac;
528 		prm->max_psize = g_audio->in_ep_maxpsize;
529 
530 		prm->ureq = kcalloc(params->req_number, sizeof(struct uac_req),
531 				GFP_KERNEL);
532 		if (!prm->ureq) {
533 			err = -ENOMEM;
534 			goto fail;
535 		}
536 
537 		prm->rbuf = kcalloc(params->req_number, prm->max_psize,
538 				GFP_KERNEL);
539 		if (!prm->rbuf) {
540 			prm->max_psize = 0;
541 			err = -ENOMEM;
542 			goto fail;
543 		}
544 	}
545 
546 	/* Choose any slot, with no id */
547 	err = snd_card_new(&g_audio->gadget->dev,
548 			-1, NULL, THIS_MODULE, 0, &card);
549 	if (err < 0)
550 		goto fail;
551 
552 	uac->card = card;
553 
554 	/*
555 	 * Create first PCM device
556 	 * Create a substream only for non-zero channel streams
557 	 */
558 	err = snd_pcm_new(uac->card, pcm_name, 0,
559 			       p_chmask ? 1 : 0, c_chmask ? 1 : 0, &pcm);
560 	if (err < 0)
561 		goto snd_fail;
562 
563 	strlcpy(pcm->name, pcm_name, sizeof(pcm->name));
564 	pcm->private_data = uac;
565 	uac->pcm = pcm;
566 
567 	snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &uac_pcm_ops);
568 	snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &uac_pcm_ops);
569 
570 	strlcpy(card->driver, card_name, sizeof(card->driver));
571 	strlcpy(card->shortname, card_name, sizeof(card->shortname));
572 	sprintf(card->longname, "%s %i", card_name, card->dev->id);
573 
574 	snd_pcm_set_managed_buffer_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS,
575 				       NULL, 0, BUFF_SIZE_MAX);
576 
577 	err = snd_card_register(card);
578 
579 	if (!err)
580 		return 0;
581 
582 snd_fail:
583 	snd_card_free(card);
584 fail:
585 	kfree(uac->p_prm.ureq);
586 	kfree(uac->c_prm.ureq);
587 	kfree(uac->p_prm.rbuf);
588 	kfree(uac->c_prm.rbuf);
589 	kfree(uac);
590 
591 	return err;
592 }
593 EXPORT_SYMBOL_GPL(g_audio_setup);
594 
595 void g_audio_cleanup(struct g_audio *g_audio)
596 {
597 	struct snd_uac_chip *uac;
598 	struct snd_card *card;
599 
600 	if (!g_audio || !g_audio->uac)
601 		return;
602 
603 	uac = g_audio->uac;
604 	card = uac->card;
605 	if (card)
606 		snd_card_free(card);
607 
608 	kfree(uac->p_prm.ureq);
609 	kfree(uac->c_prm.ureq);
610 	kfree(uac->p_prm.rbuf);
611 	kfree(uac->c_prm.rbuf);
612 	kfree(uac);
613 }
614 EXPORT_SYMBOL_GPL(g_audio_cleanup);
615 
616 MODULE_LICENSE("GPL");
617 MODULE_DESCRIPTION("USB gadget \"ALSA sound card\" utilities");
618 MODULE_AUTHOR("Ruslan Bilovol");
619