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