GNU Linux-libre 4.19.264-gnu1
[releases.git] / drivers / usb / gadget / function / u_audio.c
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 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 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) {
93                 usb_ep_free_request(ep, req);
94                 return;
95         }
96
97         if (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         snd_pcm_stream_lock_irqsave(substream, flags2);
115
116         runtime = substream->runtime;
117         if (!runtime || !snd_pcm_running(substream)) {
118                 snd_pcm_stream_unlock_irqrestore(substream, flags2);
119                 goto exit;
120         }
121
122         spin_lock_irqsave(&prm->lock, flags);
123
124         if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
125                 /*
126                  * For each IN packet, take the quotient of the current data
127                  * rate and the endpoint's interval as the base packet size.
128                  * If there is a residue from this division, add it to the
129                  * residue accumulator.
130                  */
131                 req->length = uac->p_pktsize;
132                 uac->p_residue += uac->p_pktsize_residue;
133
134                 /*
135                  * Whenever there are more bytes in the accumulator than we
136                  * need to add one more sample frame, increase this packet's
137                  * size and decrease the accumulator.
138                  */
139                 if (uac->p_residue / uac->p_interval >= uac->p_framesize) {
140                         req->length += uac->p_framesize;
141                         uac->p_residue -= uac->p_framesize *
142                                            uac->p_interval;
143                 }
144
145                 req->actual = req->length;
146         }
147
148         hw_ptr = prm->hw_ptr;
149
150         spin_unlock_irqrestore(&prm->lock, flags);
151
152         /* Pack USB load in ALSA ring buffer */
153         pending = runtime->dma_bytes - hw_ptr;
154
155         if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
156                 if (unlikely(pending < req->actual)) {
157                         memcpy(req->buf, runtime->dma_area + hw_ptr, pending);
158                         memcpy(req->buf + pending, runtime->dma_area,
159                                req->actual - pending);
160                 } else {
161                         memcpy(req->buf, runtime->dma_area + hw_ptr,
162                                req->actual);
163                 }
164         } else {
165                 if (unlikely(pending < req->actual)) {
166                         memcpy(runtime->dma_area + hw_ptr, req->buf, pending);
167                         memcpy(runtime->dma_area, req->buf + pending,
168                                req->actual - pending);
169                 } else {
170                         memcpy(runtime->dma_area + hw_ptr, req->buf,
171                                req->actual);
172                 }
173         }
174
175         spin_lock_irqsave(&prm->lock, flags);
176         /* update hw_ptr after data is copied to memory */
177         prm->hw_ptr = (hw_ptr + req->actual) % runtime->dma_bytes;
178         hw_ptr = prm->hw_ptr;
179         spin_unlock_irqrestore(&prm->lock, flags);
180         snd_pcm_stream_unlock_irqrestore(substream, flags2);
181
182         if ((hw_ptr % snd_pcm_lib_period_bytes(substream)) < req->actual)
183                 snd_pcm_period_elapsed(substream);
184
185 exit:
186         if (usb_ep_queue(ep, req, GFP_ATOMIC))
187                 dev_err(uac->card->dev, "%d Error!\n", __LINE__);
188 }
189
190 static int uac_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
191 {
192         struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
193         struct uac_rtd_params *prm;
194         struct g_audio *audio_dev;
195         struct uac_params *params;
196         unsigned long flags;
197         int err = 0;
198
199         audio_dev = uac->audio_dev;
200         params = &audio_dev->params;
201
202         if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
203                 prm = &uac->p_prm;
204         else
205                 prm = &uac->c_prm;
206
207         spin_lock_irqsave(&prm->lock, flags);
208
209         /* Reset */
210         prm->hw_ptr = 0;
211
212         switch (cmd) {
213         case SNDRV_PCM_TRIGGER_START:
214         case SNDRV_PCM_TRIGGER_RESUME:
215                 prm->ss = substream;
216                 break;
217         case SNDRV_PCM_TRIGGER_STOP:
218         case SNDRV_PCM_TRIGGER_SUSPEND:
219                 prm->ss = NULL;
220                 break;
221         default:
222                 err = -EINVAL;
223         }
224
225         spin_unlock_irqrestore(&prm->lock, flags);
226
227         /* Clear buffer after Play stops */
228         if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK && !prm->ss)
229                 memset(prm->rbuf, 0, prm->max_psize * params->req_number);
230
231         return err;
232 }
233
234 static snd_pcm_uframes_t uac_pcm_pointer(struct snd_pcm_substream *substream)
235 {
236         struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
237         struct uac_rtd_params *prm;
238
239         if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
240                 prm = &uac->p_prm;
241         else
242                 prm = &uac->c_prm;
243
244         return bytes_to_frames(substream->runtime, prm->hw_ptr);
245 }
246
247 static int uac_pcm_hw_params(struct snd_pcm_substream *substream,
248                                struct snd_pcm_hw_params *hw_params)
249 {
250         return snd_pcm_lib_malloc_pages(substream,
251                                         params_buffer_bytes(hw_params));
252 }
253
254 static int uac_pcm_hw_free(struct snd_pcm_substream *substream)
255 {
256         return snd_pcm_lib_free_pages(substream);
257 }
258
259 static int uac_pcm_open(struct snd_pcm_substream *substream)
260 {
261         struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
262         struct snd_pcm_runtime *runtime = substream->runtime;
263         struct g_audio *audio_dev;
264         struct uac_params *params;
265         int p_ssize, c_ssize;
266         int p_srate, c_srate;
267         int p_chmask, c_chmask;
268
269         audio_dev = uac->audio_dev;
270         params = &audio_dev->params;
271         p_ssize = params->p_ssize;
272         c_ssize = params->c_ssize;
273         p_srate = params->p_srate;
274         c_srate = params->c_srate;
275         p_chmask = params->p_chmask;
276         c_chmask = params->c_chmask;
277         uac->p_residue = 0;
278
279         runtime->hw = uac_pcm_hardware;
280
281         if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
282                 spin_lock_init(&uac->p_prm.lock);
283                 runtime->hw.rate_min = p_srate;
284                 switch (p_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(p_chmask);
296                 runtime->hw.period_bytes_min = 2 * uac->p_prm.max_psize
297                                                 / runtime->hw.periods_min;
298         } else {
299                 spin_lock_init(&uac->c_prm.lock);
300                 runtime->hw.rate_min = c_srate;
301                 switch (c_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(c_chmask);
313                 runtime->hw.period_bytes_min = 2 * uac->c_prm.max_psize
314                                                 / runtime->hw.periods_min;
315         }
316
317         runtime->hw.rate_max = runtime->hw.rate_min;
318         runtime->hw.channels_max = runtime->hw.channels_min;
319
320         snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
321
322         return 0;
323 }
324
325 /* ALSA cries without these function pointers */
326 static int uac_pcm_null(struct snd_pcm_substream *substream)
327 {
328         return 0;
329 }
330
331 static const struct snd_pcm_ops uac_pcm_ops = {
332         .open = uac_pcm_open,
333         .close = uac_pcm_null,
334         .ioctl = snd_pcm_lib_ioctl,
335         .hw_params = uac_pcm_hw_params,
336         .hw_free = uac_pcm_hw_free,
337         .trigger = uac_pcm_trigger,
338         .pointer = uac_pcm_pointer,
339         .prepare = uac_pcm_null,
340 };
341
342 static inline void free_ep(struct uac_rtd_params *prm, struct usb_ep *ep)
343 {
344         struct snd_uac_chip *uac = prm->uac;
345         struct g_audio *audio_dev;
346         struct uac_params *params;
347         int i;
348
349         if (!prm->ep_enabled)
350                 return;
351
352         audio_dev = uac->audio_dev;
353         params = &audio_dev->params;
354
355         for (i = 0; i < params->req_number; i++) {
356                 if (prm->ureq[i].req) {
357                         if (usb_ep_dequeue(ep, prm->ureq[i].req))
358                                 usb_ep_free_request(ep, prm->ureq[i].req);
359                         /*
360                          * If usb_ep_dequeue() cannot successfully dequeue the
361                          * request, the request will be freed by the completion
362                          * callback.
363                          */
364
365                         prm->ureq[i].req = NULL;
366                 }
367         }
368
369         prm->ep_enabled = false;
370
371         if (usb_ep_disable(ep))
372                 dev_err(uac->card->dev, "%s:%d Error!\n", __func__, __LINE__);
373 }
374
375 int u_audio_start_capture(struct g_audio *audio_dev)
376 {
377         struct snd_uac_chip *uac = audio_dev->uac;
378         struct usb_gadget *gadget = audio_dev->gadget;
379         struct device *dev = &gadget->dev;
380         struct usb_request *req;
381         struct usb_ep *ep;
382         struct uac_rtd_params *prm;
383         struct uac_params *params = &audio_dev->params;
384         int req_len, i;
385
386         ep = audio_dev->out_ep;
387         prm = &uac->c_prm;
388         config_ep_by_speed(gadget, &audio_dev->func, ep);
389         req_len = prm->max_psize;
390
391         prm->ep_enabled = true;
392         usb_ep_enable(ep);
393
394         for (i = 0; i < params->req_number; i++) {
395                 if (!prm->ureq[i].req) {
396                         req = usb_ep_alloc_request(ep, GFP_ATOMIC);
397                         if (req == NULL)
398                                 return -ENOMEM;
399
400                         prm->ureq[i].req = req;
401                         prm->ureq[i].pp = prm;
402
403                         req->zero = 0;
404                         req->context = &prm->ureq[i];
405                         req->length = req_len;
406                         req->complete = u_audio_iso_complete;
407                         req->buf = prm->rbuf + i * prm->max_psize;
408                 }
409
410                 if (usb_ep_queue(ep, prm->ureq[i].req, GFP_ATOMIC))
411                         dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
412         }
413
414         return 0;
415 }
416 EXPORT_SYMBOL_GPL(u_audio_start_capture);
417
418 void u_audio_stop_capture(struct g_audio *audio_dev)
419 {
420         struct snd_uac_chip *uac = audio_dev->uac;
421
422         free_ep(&uac->c_prm, audio_dev->out_ep);
423 }
424 EXPORT_SYMBOL_GPL(u_audio_stop_capture);
425
426 int u_audio_start_playback(struct g_audio *audio_dev)
427 {
428         struct snd_uac_chip *uac = audio_dev->uac;
429         struct usb_gadget *gadget = audio_dev->gadget;
430         struct device *dev = &gadget->dev;
431         struct usb_request *req;
432         struct usb_ep *ep;
433         struct uac_rtd_params *prm;
434         struct uac_params *params = &audio_dev->params;
435         unsigned int factor, rate;
436         const struct usb_endpoint_descriptor *ep_desc;
437         int req_len, i;
438
439         ep = audio_dev->in_ep;
440         prm = &uac->p_prm;
441         config_ep_by_speed(gadget, &audio_dev->func, ep);
442
443         ep_desc = ep->desc;
444
445         /* pre-calculate the playback endpoint's interval */
446         if (gadget->speed == USB_SPEED_FULL)
447                 factor = 1000;
448         else
449                 factor = 8000;
450
451         /* pre-compute some values for iso_complete() */
452         uac->p_framesize = params->p_ssize *
453                             num_channels(params->p_chmask);
454         rate = params->p_srate * uac->p_framesize;
455         uac->p_interval = factor / (1 << (ep_desc->bInterval - 1));
456         uac->p_pktsize = min_t(unsigned int, rate / uac->p_interval,
457                                 prm->max_psize);
458
459         if (uac->p_pktsize < prm->max_psize)
460                 uac->p_pktsize_residue = rate % uac->p_interval;
461         else
462                 uac->p_pktsize_residue = 0;
463
464         req_len = uac->p_pktsize;
465         uac->p_residue = 0;
466
467         prm->ep_enabled = true;
468         usb_ep_enable(ep);
469
470         for (i = 0; i < params->req_number; i++) {
471                 if (!prm->ureq[i].req) {
472                         req = usb_ep_alloc_request(ep, GFP_ATOMIC);
473                         if (req == NULL)
474                                 return -ENOMEM;
475
476                         prm->ureq[i].req = req;
477                         prm->ureq[i].pp = prm;
478
479                         req->zero = 0;
480                         req->context = &prm->ureq[i];
481                         req->length = req_len;
482                         req->complete = u_audio_iso_complete;
483                         req->buf = prm->rbuf + i * prm->max_psize;
484                 }
485
486                 if (usb_ep_queue(ep, prm->ureq[i].req, GFP_ATOMIC))
487                         dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
488         }
489
490         return 0;
491 }
492 EXPORT_SYMBOL_GPL(u_audio_start_playback);
493
494 void u_audio_stop_playback(struct g_audio *audio_dev)
495 {
496         struct snd_uac_chip *uac = audio_dev->uac;
497
498         free_ep(&uac->p_prm, audio_dev->in_ep);
499 }
500 EXPORT_SYMBOL_GPL(u_audio_stop_playback);
501
502 int g_audio_setup(struct g_audio *g_audio, const char *pcm_name,
503                                         const char *card_name)
504 {
505         struct snd_uac_chip *uac;
506         struct snd_card *card;
507         struct snd_pcm *pcm;
508         struct uac_params *params;
509         int p_chmask, c_chmask;
510         int err;
511
512         if (!g_audio)
513                 return -EINVAL;
514
515         uac = kzalloc(sizeof(*uac), GFP_KERNEL);
516         if (!uac)
517                 return -ENOMEM;
518         g_audio->uac = uac;
519         uac->audio_dev = g_audio;
520
521         params = &g_audio->params;
522         p_chmask = params->p_chmask;
523         c_chmask = params->c_chmask;
524
525         if (c_chmask) {
526                 struct uac_rtd_params *prm = &uac->c_prm;
527
528                 uac->c_prm.uac = uac;
529                 prm->max_psize = g_audio->out_ep_maxpsize;
530
531                 prm->ureq = kcalloc(params->req_number, sizeof(struct uac_req),
532                                 GFP_KERNEL);
533                 if (!prm->ureq) {
534                         err = -ENOMEM;
535                         goto fail;
536                 }
537
538                 prm->rbuf = kcalloc(params->req_number, prm->max_psize,
539                                 GFP_KERNEL);
540                 if (!prm->rbuf) {
541                         prm->max_psize = 0;
542                         err = -ENOMEM;
543                         goto fail;
544                 }
545         }
546
547         if (p_chmask) {
548                 struct uac_rtd_params *prm = &uac->p_prm;
549
550                 uac->p_prm.uac = uac;
551                 prm->max_psize = g_audio->in_ep_maxpsize;
552
553                 prm->ureq = kcalloc(params->req_number, sizeof(struct uac_req),
554                                 GFP_KERNEL);
555                 if (!prm->ureq) {
556                         err = -ENOMEM;
557                         goto fail;
558                 }
559
560                 prm->rbuf = kcalloc(params->req_number, prm->max_psize,
561                                 GFP_KERNEL);
562                 if (!prm->rbuf) {
563                         prm->max_psize = 0;
564                         err = -ENOMEM;
565                         goto fail;
566                 }
567         }
568
569         /* Choose any slot, with no id */
570         err = snd_card_new(&g_audio->gadget->dev,
571                         -1, NULL, THIS_MODULE, 0, &card);
572         if (err < 0)
573                 goto fail;
574
575         uac->card = card;
576
577         /*
578          * Create first PCM device
579          * Create a substream only for non-zero channel streams
580          */
581         err = snd_pcm_new(uac->card, pcm_name, 0,
582                                p_chmask ? 1 : 0, c_chmask ? 1 : 0, &pcm);
583         if (err < 0)
584                 goto snd_fail;
585
586         strlcpy(pcm->name, pcm_name, sizeof(pcm->name));
587         pcm->private_data = uac;
588         uac->pcm = pcm;
589
590         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &uac_pcm_ops);
591         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &uac_pcm_ops);
592
593         strlcpy(card->driver, card_name, sizeof(card->driver));
594         strlcpy(card->shortname, card_name, sizeof(card->shortname));
595         sprintf(card->longname, "%s %i", card_name, card->dev->id);
596
597         snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS,
598                 snd_dma_continuous_data(GFP_KERNEL), 0, BUFF_SIZE_MAX);
599
600         err = snd_card_register(card);
601
602         if (!err)
603                 return 0;
604
605 snd_fail:
606         snd_card_free(card);
607 fail:
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         return err;
615 }
616 EXPORT_SYMBOL_GPL(g_audio_setup);
617
618 void g_audio_cleanup(struct g_audio *g_audio)
619 {
620         struct snd_uac_chip *uac;
621         struct snd_card *card;
622
623         if (!g_audio || !g_audio->uac)
624                 return;
625
626         uac = g_audio->uac;
627         card = uac->card;
628         if (card)
629                 snd_card_free(card);
630
631         kfree(uac->p_prm.ureq);
632         kfree(uac->c_prm.ureq);
633         kfree(uac->p_prm.rbuf);
634         kfree(uac->c_prm.rbuf);
635         kfree(uac);
636 }
637 EXPORT_SYMBOL_GPL(g_audio_cleanup);
638
639 MODULE_LICENSE("GPL");
640 MODULE_DESCRIPTION("USB gadget \"ALSA sound card\" utilities");
641 MODULE_AUTHOR("Ruslan Bilovol");