hc
2023-02-13 e440ec23c5a540cdd3f7464e8779219be6fd3d95
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
// SPDX-License-Identifier: GPL-2.0+
/*
 * u_audio.c -- interface to USB gadget "ALSA sound card" utilities
 *
 * Copyright (C) 2016
 * Author: Ruslan Bilovol <ruslan.bilovol@gmail.com>
 *
 * Sound card implementation was cut-and-pasted with changes
 * from f_uac2.c and has:
 *    Copyright (C) 2011
 *    Yadwinder Singh (yadi.brar01@gmail.com)
 *    Jaswinder Singh (jaswinder.singh@linaro.org)
 */
 
#include <linux/module.h>
#include <linux/usb/audio.h>
#include <sound/control.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
 
#include "u_audio.h"
 
#define BUFF_SIZE_MAX    (PAGE_SIZE * 16)
#define PRD_SIZE_MAX    PAGE_SIZE
#define MIN_PERIODS    4
 
#define CLK_PPM_GROUP_SIZE    20
 
static struct class *audio_class;
 
struct uac_req {
   struct uac_rtd_params *pp; /* parent param */
   struct usb_request *req;
};
 
/* Runtime data params for one stream */
struct uac_rtd_params {
   struct snd_uac_chip *uac; /* parent chip */
   bool ep_enabled; /* if the ep is enabled */
 
   struct snd_pcm_substream *ss;
 
   /* Ring buffer */
   ssize_t hw_ptr;
 
   void *rbuf;
 
   unsigned max_psize;    /* MaxPacketSize of endpoint */
   struct uac_req *ureq;
 
   spinlock_t lock;
};
 
struct snd_uac_chip {
   struct g_audio *audio_dev;
 
   struct uac_rtd_params p_prm;
   struct uac_rtd_params c_prm;
 
   struct snd_card *card;
   struct snd_pcm *pcm;
 
   /* timekeeping for the playback endpoint */
   unsigned int p_interval;
   unsigned int p_residue;
 
   /* pre-calculated values for playback iso completion */
   unsigned int p_pktsize;
   unsigned int p_pktsize_residue;
   unsigned int p_framesize;
};
 
static const struct snd_pcm_hardware uac_pcm_hardware = {
   .info = SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER
        | SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID
        | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME,
   .rates = SNDRV_PCM_RATE_CONTINUOUS,
   .periods_max = BUFF_SIZE_MAX / PRD_SIZE_MAX,
   .buffer_bytes_max = BUFF_SIZE_MAX,
   .period_bytes_max = PRD_SIZE_MAX,
   .periods_min = MIN_PERIODS,
};
 
static void u_audio_iso_complete(struct usb_ep *ep, struct usb_request *req)
{
   unsigned pending;
   unsigned long flags, flags2;
   unsigned int hw_ptr;
   int status = req->status;
   struct uac_req *ur = req->context;
   struct snd_pcm_substream *substream;
   struct snd_pcm_runtime *runtime;
   struct uac_rtd_params *prm = ur->pp;
   struct snd_uac_chip *uac = prm->uac;
 
   /* i/f shutting down */
   if (!prm->ep_enabled) {
       usb_ep_free_request(ep, req);
       return;
   }
 
   if (req->status == -ESHUTDOWN)
       return;
 
   /*
    * We can't really do much about bad xfers.
    * Afterall, the ISOCH xfers could fail legitimately.
    */
   if (status)
       pr_debug("%s: iso_complete status(%d) %d/%d\n",
           __func__, status, req->actual, req->length);
 
   substream = prm->ss;
 
   /* Do nothing if ALSA isn't active */
   if (!substream)
       goto exit;
 
   snd_pcm_stream_lock_irqsave(substream, flags2);
 
   runtime = substream->runtime;
   if (!runtime || !snd_pcm_running(substream)) {
       snd_pcm_stream_unlock_irqrestore(substream, flags2);
       goto exit;
   }
 
   spin_lock_irqsave(&prm->lock, flags);
 
   if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
       /*
        * For each IN packet, take the quotient of the current data
        * rate and the endpoint's interval as the base packet size.
        * If there is a residue from this division, add it to the
        * residue accumulator.
        */
       req->length = uac->p_pktsize;
       uac->p_residue += uac->p_pktsize_residue;
 
       /*
        * Whenever there are more bytes in the accumulator than we
        * need to add one more sample frame, increase this packet's
        * size and decrease the accumulator.
        */
       if (uac->p_residue / uac->p_interval >= uac->p_framesize) {
           req->length += uac->p_framesize;
           uac->p_residue -= uac->p_framesize *
                      uac->p_interval;
       }
 
       req->actual = req->length;
   }
 
   hw_ptr = prm->hw_ptr;
 
   spin_unlock_irqrestore(&prm->lock, flags);
 
   /* Pack USB load in ALSA ring buffer */
   pending = runtime->dma_bytes - hw_ptr;
 
   if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
       if (unlikely(pending < req->actual)) {
           memcpy(req->buf, runtime->dma_area + hw_ptr, pending);
           memcpy(req->buf + pending, runtime->dma_area,
                  req->actual - pending);
       } else {
           memcpy(req->buf, runtime->dma_area + hw_ptr,
                  req->actual);
       }
   } else {
       if (unlikely(pending < req->actual)) {
           memcpy(runtime->dma_area + hw_ptr, req->buf, pending);
           memcpy(runtime->dma_area, req->buf + pending,
                  req->actual - pending);
       } else {
           memcpy(runtime->dma_area + hw_ptr, req->buf,
                  req->actual);
       }
   }
 
   spin_lock_irqsave(&prm->lock, flags);
   /* update hw_ptr after data is copied to memory */
   prm->hw_ptr = (hw_ptr + req->actual) % runtime->dma_bytes;
   hw_ptr = prm->hw_ptr;
   spin_unlock_irqrestore(&prm->lock, flags);
   snd_pcm_stream_unlock_irqrestore(substream, flags2);
 
   if ((hw_ptr % snd_pcm_lib_period_bytes(substream)) < req->actual)
       snd_pcm_period_elapsed(substream);
 
exit:
   if (usb_ep_queue(ep, req, GFP_ATOMIC))
       dev_err(uac->card->dev, "%d Error!\n", __LINE__);
}
 
static int uac_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
   struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
   struct uac_rtd_params *prm;
   struct g_audio *audio_dev;
   struct uac_params *params;
   unsigned long flags;
   int err = 0;
 
   audio_dev = uac->audio_dev;
   params = &audio_dev->params;
 
   if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
       prm = &uac->p_prm;
   else
       prm = &uac->c_prm;
 
   spin_lock_irqsave(&prm->lock, flags);
 
   /* Reset */
   prm->hw_ptr = 0;
 
   switch (cmd) {
   case SNDRV_PCM_TRIGGER_START:
   case SNDRV_PCM_TRIGGER_RESUME:
       prm->ss = substream;
       break;
   case SNDRV_PCM_TRIGGER_STOP:
   case SNDRV_PCM_TRIGGER_SUSPEND:
       prm->ss = NULL;
       break;
   default:
       err = -EINVAL;
   }
 
   spin_unlock_irqrestore(&prm->lock, flags);
 
   /* Clear buffer after Play stops */
   if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK && !prm->ss)
       memset(prm->rbuf, 0, prm->max_psize * params->req_number);
 
   return err;
}
 
static snd_pcm_uframes_t uac_pcm_pointer(struct snd_pcm_substream *substream)
{
   struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
   struct uac_rtd_params *prm;
 
   if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
       prm = &uac->p_prm;
   else
       prm = &uac->c_prm;
 
   return bytes_to_frames(substream->runtime, prm->hw_ptr);
}
 
static int uac_pcm_hw_params(struct snd_pcm_substream *substream,
                  struct snd_pcm_hw_params *hw_params)
{
   return snd_pcm_lib_malloc_pages(substream,
                   params_buffer_bytes(hw_params));
}
 
static int uac_pcm_hw_free(struct snd_pcm_substream *substream)
{
   return snd_pcm_lib_free_pages(substream);
}
 
static int uac_pcm_open(struct snd_pcm_substream *substream)
{
   struct snd_uac_chip *uac = snd_pcm_substream_chip(substream);
   struct snd_pcm_runtime *runtime = substream->runtime;
   struct g_audio *audio_dev = uac->audio_dev;
   struct uac_params *params;
   int p_ssize, c_ssize;
   int p_srate, c_srate;
   int p_chmask, c_chmask;
 
   params = &audio_dev->params;
   p_ssize = params->p_ssize;
   c_ssize = params->c_ssize;
   p_srate = params->p_srate_active;
   c_srate = params->c_srate_active;
   p_chmask = params->p_chmask;
   c_chmask = params->c_chmask;
   uac->p_residue = 0;
 
   runtime->hw = uac_pcm_hardware;
 
   if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
       spin_lock_init(&uac->p_prm.lock);
       runtime->hw.rate_min = p_srate;
       switch (p_ssize) {
       case 3:
           runtime->hw.formats = SNDRV_PCM_FMTBIT_S24_3LE;
           break;
       case 4:
           runtime->hw.formats = SNDRV_PCM_FMTBIT_S32_LE;
           break;
       default:
           runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
           break;
       }
       runtime->hw.channels_min = num_channels(p_chmask);
       runtime->hw.period_bytes_min = 2 * uac->p_prm.max_psize
                       / runtime->hw.periods_min;
   } else {
       spin_lock_init(&uac->c_prm.lock);
       runtime->hw.rate_min = c_srate;
       switch (c_ssize) {
       case 3:
           runtime->hw.formats = SNDRV_PCM_FMTBIT_S24_3LE;
           break;
       case 4:
           runtime->hw.formats = SNDRV_PCM_FMTBIT_S32_LE;
           break;
       default:
           runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
           break;
       }
       runtime->hw.channels_min = num_channels(c_chmask);
       runtime->hw.period_bytes_min = 2 * uac->c_prm.max_psize
                       / runtime->hw.periods_min;
   }
 
   runtime->hw.rate_max = runtime->hw.rate_min;
   runtime->hw.channels_max = runtime->hw.channels_min;
 
   snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
 
   return 0;
}
 
static int uac_pcm_rate_info(struct snd_kcontrol *kcontrol,
               struct snd_ctl_elem_info *uinfo)
{
   uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
   uinfo->count = 1;
   uinfo->value.integer.min = 0;
   uinfo->value.integer.max = 324000;
   return 0;
}
 
static int uac_pcm_rate_get(struct snd_kcontrol *kcontrol,
                  struct snd_ctl_elem_value *ucontrol)
{
   struct snd_uac_chip *uac = snd_kcontrol_chip(kcontrol);
   struct g_audio *audio_dev = uac->audio_dev;
   struct uac_params *params = &audio_dev->params;
 
   if (kcontrol->private_value == SNDRV_PCM_STREAM_CAPTURE)
       ucontrol->value.integer.value[0] = params->c_srate_active;
   else if (kcontrol->private_value == SNDRV_PCM_STREAM_PLAYBACK)
       ucontrol->value.integer.value[0] = params->p_srate_active;
   else
       return -EINVAL;
 
   return 0;
}
 
static struct snd_kcontrol_new uac_pcm_controls[] = {
{
   .iface = SNDRV_CTL_ELEM_IFACE_PCM,
   .name = "Capture Rate",
   .access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE,
   .info = uac_pcm_rate_info,
   .get = uac_pcm_rate_get,
   .private_value = SNDRV_PCM_STREAM_CAPTURE,
},
{
   .iface = SNDRV_CTL_ELEM_IFACE_PCM,
   .name = "Playback Rate",
   .access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE,
   .info = uac_pcm_rate_info,
   .get = uac_pcm_rate_get,
   .private_value = SNDRV_PCM_STREAM_PLAYBACK,
},
};
 
/* ALSA cries without these function pointers */
static int uac_pcm_null(struct snd_pcm_substream *substream)
{
   return 0;
}
 
static const struct snd_pcm_ops uac_pcm_ops = {
   .open = uac_pcm_open,
   .close = uac_pcm_null,
   .ioctl = snd_pcm_lib_ioctl,
   .hw_params = uac_pcm_hw_params,
   .hw_free = uac_pcm_hw_free,
   .trigger = uac_pcm_trigger,
   .pointer = uac_pcm_pointer,
   .prepare = uac_pcm_null,
};
 
static inline void free_ep(struct uac_rtd_params *prm, struct usb_ep *ep)
{
   struct snd_uac_chip *uac = prm->uac;
   struct g_audio *audio_dev;
   struct uac_params *params;
   int i;
 
   if (!prm->ep_enabled)
       return;
 
   audio_dev = uac->audio_dev;
   params = &audio_dev->params;
 
   for (i = 0; i < params->req_number; i++) {
       if (prm->ureq[i].req) {
           if (usb_ep_dequeue(ep, prm->ureq[i].req))
               usb_ep_free_request(ep, prm->ureq[i].req);
           /*
            * If usb_ep_dequeue() cannot successfully dequeue the
            * request, the request will be freed by the completion
            * callback.
            */
 
           prm->ureq[i].req = NULL;
       }
   }
 
   prm->ep_enabled = false;
 
   if (usb_ep_disable(ep))
       dev_err(uac->card->dev, "%s:%d Error!\n", __func__, __LINE__);
}
 
static struct snd_kcontrol *u_audio_get_ctl(struct g_audio *audio_dev,
       const char *name)
{
   struct snd_ctl_elem_id elem_id;
 
   memset(&elem_id, 0, sizeof(elem_id));
   elem_id.iface = SNDRV_CTL_ELEM_IFACE_PCM;
   strlcpy(elem_id.name, name, sizeof(elem_id.name));
   return snd_ctl_find_id(audio_dev->uac->card, &elem_id);
}
 
int u_audio_set_capture_srate(struct g_audio *audio_dev, int srate)
{
   struct snd_kcontrol *ctl = u_audio_get_ctl(audio_dev, "Capture Rate");
   struct uac_params *params = &audio_dev->params;
   int i;
 
   for (i = 0; i < UAC_MAX_RATES; i++) {
       if (params->c_srate[i] == srate) {
           audio_dev->usb_state[SET_SAMPLE_RATE_OUT] = true;
           schedule_work(&audio_dev->work);
 
           params->c_srate_active = srate;
           snd_ctl_notify(audio_dev->uac->card,
                   SNDRV_CTL_EVENT_MASK_VALUE, &ctl->id);
           return 0;
       }
       if (params->c_srate[i] == 0)
           break;
   }
 
   return -EINVAL;
}
EXPORT_SYMBOL_GPL(u_audio_set_capture_srate);
 
static void u_audio_set_playback_pktsize(struct g_audio *audio_dev, int srate)
{
   struct uac_params *params = &audio_dev->params;
   struct snd_uac_chip *uac = audio_dev->uac;
   struct usb_gadget *gadget = audio_dev->gadget;
   const struct usb_endpoint_descriptor *ep_desc;
   struct uac_rtd_params *prm;
   unsigned int factor;
 
   prm = &uac->p_prm;
   /* set srate before starting playback, epin is not configured */
   if (!prm->ep_enabled)
       return;
 
   ep_desc = audio_dev->in_ep->desc;
 
   /* pre-calculate the playback endpoint's interval */
   if (gadget->speed == USB_SPEED_FULL)
       factor = 1000;
   else
       factor = 8000;
 
   /* pre-compute some values for iso_complete() */
   uac->p_framesize = params->p_ssize *
               num_channels(params->p_chmask);
   uac->p_interval = factor / (1 << (ep_desc->bInterval - 1));
   uac->p_pktsize = min_t(unsigned int,
               uac->p_framesize *
               (params->p_srate_active / uac->p_interval),
               prm->max_psize);
 
   if (uac->p_pktsize < prm->max_psize)
       uac->p_pktsize_residue = uac->p_framesize *
           (params->p_srate_active % uac->p_interval);
   else
       uac->p_pktsize_residue = 0;
}
 
int u_audio_set_playback_srate(struct g_audio *audio_dev, int srate)
{
   struct snd_kcontrol *ctl = u_audio_get_ctl(audio_dev, "Playback Rate");
   struct uac_params *params = &audio_dev->params;
   int i;
 
   for (i = 0; i < UAC_MAX_RATES; i++) {
       if (params->p_srate[i] == srate) {
           audio_dev->usb_state[SET_SAMPLE_RATE_IN] = true;
           schedule_work(&audio_dev->work);
 
           params->p_srate_active = srate;
           u_audio_set_playback_pktsize(audio_dev, srate);
           snd_ctl_notify(audio_dev->uac->card,
                   SNDRV_CTL_EVENT_MASK_VALUE, &ctl->id);
           return 0;
       }
       if (params->p_srate[i] == 0)
           break;
   }
 
   return -EINVAL;
}
EXPORT_SYMBOL_GPL(u_audio_set_playback_srate);
 
int u_audio_start_capture(struct g_audio *audio_dev)
{
   struct snd_uac_chip *uac = audio_dev->uac;
   struct usb_gadget *gadget = audio_dev->gadget;
   struct device *dev = &gadget->dev;
   struct usb_request *req;
   struct usb_ep *ep;
   struct uac_rtd_params *prm;
   struct uac_params *params = &audio_dev->params;
   int req_len, i;
 
   /*
    * For better compatibility on some PC Hosts which
    * failed to send SetInterface(AltSet=0) to stop
    * capture last time. It needs to stop capture
    * prior to start capture next time.
    */
   if (audio_dev->stream_state[STATE_OUT])
       u_audio_stop_capture(audio_dev);
 
   audio_dev->usb_state[SET_INTERFACE_OUT] = true;
   audio_dev->stream_state[STATE_OUT] = true;
   schedule_work(&audio_dev->work);
 
   ep = audio_dev->out_ep;
   prm = &uac->c_prm;
   config_ep_by_speed(gadget, &audio_dev->func, ep);
   req_len = prm->max_psize;
 
   prm->ep_enabled = true;
   usb_ep_enable(ep);
 
   for (i = 0; i < params->req_number; i++) {
       if (!prm->ureq[i].req) {
           req = usb_ep_alloc_request(ep, GFP_ATOMIC);
           if (req == NULL)
               return -ENOMEM;
 
           prm->ureq[i].req = req;
           prm->ureq[i].pp = prm;
 
           req->zero = 0;
           req->context = &prm->ureq[i];
           req->length = req_len;
           req->complete = u_audio_iso_complete;
           req->buf = prm->rbuf + i * prm->max_psize;
       }
 
       if (usb_ep_queue(ep, prm->ureq[i].req, GFP_ATOMIC))
           dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
   }
 
   return 0;
}
EXPORT_SYMBOL_GPL(u_audio_start_capture);
 
void u_audio_stop_capture(struct g_audio *audio_dev)
{
   struct snd_uac_chip *uac = audio_dev->uac;
 
   free_ep(&uac->c_prm, audio_dev->out_ep);
 
   audio_dev->usb_state[SET_INTERFACE_OUT] = true;
   audio_dev->stream_state[STATE_OUT] = false;
   schedule_work(&audio_dev->work);
}
EXPORT_SYMBOL_GPL(u_audio_stop_capture);
 
int u_audio_start_playback(struct g_audio *audio_dev)
{
   struct snd_uac_chip *uac = audio_dev->uac;
   struct usb_gadget *gadget = audio_dev->gadget;
   struct device *dev = audio_dev->device;
   struct usb_request *req;
   struct usb_ep *ep;
   struct uac_rtd_params *prm;
   struct uac_params *params = &audio_dev->params;
   int req_len, i;
 
   /*
    * For better compatibility on some PC Hosts which
    * failed to send SetInterface(AltSet=0) to stop
    * playback last time. It needs to stop playback
    * prior to start playback next time.
    */
   if (audio_dev->stream_state[STATE_IN])
       u_audio_stop_playback(audio_dev);
 
   audio_dev->usb_state[SET_INTERFACE_IN] = true;
   audio_dev->stream_state[STATE_IN] = true;
   schedule_work(&audio_dev->work);
 
   dev_dbg(dev, "start playback with rate %d\n", params->p_srate_active);
   ep = audio_dev->in_ep;
   prm = &uac->p_prm;
   config_ep_by_speed(gadget, &audio_dev->func, ep);
 
   prm->ep_enabled = true;
   usb_ep_enable(ep);
 
   u_audio_set_playback_pktsize(audio_dev, params->p_srate_active);
   req_len = uac->p_pktsize;
   uac->p_residue = 0;
 
   for (i = 0; i < params->req_number; i++) {
       if (!prm->ureq[i].req) {
           req = usb_ep_alloc_request(ep, GFP_ATOMIC);
           if (req == NULL)
               return -ENOMEM;
 
           prm->ureq[i].req = req;
           prm->ureq[i].pp = prm;
 
           req->zero = 0;
           req->context = &prm->ureq[i];
           req->length = req_len;
           req->complete = u_audio_iso_complete;
           req->buf = prm->rbuf + i * prm->max_psize;
       }
 
       if (usb_ep_queue(ep, prm->ureq[i].req, GFP_ATOMIC))
           dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
   }
 
   return 0;
}
EXPORT_SYMBOL_GPL(u_audio_start_playback);
 
void u_audio_stop_playback(struct g_audio *audio_dev)
{
   struct snd_uac_chip *uac = audio_dev->uac;
 
   free_ep(&uac->p_prm, audio_dev->in_ep);
 
   audio_dev->usb_state[SET_INTERFACE_IN] = true;
   audio_dev->stream_state[STATE_IN] = false;
   schedule_work(&audio_dev->work);
}
EXPORT_SYMBOL_GPL(u_audio_stop_playback);
 
int u_audio_fu_set_cmd(struct usb_audio_control *con, u8 cmd, int value)
{
   struct g_audio *audio_dev = (struct g_audio *)con->context;
   struct uac_params *params = &audio_dev->params;
 
   switch (cmd) {
   case UAC_SET_CUR:
       if (!strncmp(con->name, "Capture Mute", 12)) {
           params->c_mute = value;
           audio_dev->usb_state[SET_MUTE_OUT] = true;
       } else if (!strncmp(con->name, "Capture Volume", 14)) {
           params->c_volume = value;
           audio_dev->usb_state[SET_VOLUME_OUT] = true;
       } else if (!strncmp(con->name, "Playback Mute", 13)) {
           params->p_mute = value;
           audio_dev->usb_state[SET_MUTE_IN] = true;
       } else if (!strncmp(con->name, "Playback Volume", 15)) {
           params->p_volume = value;
           audio_dev->usb_state[SET_VOLUME_IN] = true;
       }
       break;
   case UAC_SET_RES:
       /* fall through */
   default:
       return 0;
   }
 
   con->data[cmd] = value;
   schedule_work(&audio_dev->work);
 
   return 0;
}
EXPORT_SYMBOL_GPL(u_audio_fu_set_cmd);
 
int u_audio_fu_get_cmd(struct usb_audio_control *con, u8 cmd)
{
   struct g_audio *audio_dev = (struct g_audio *)con->context;
 
   dev_dbg(audio_dev->device, "GET_CMD con %s cmd %d data %d\n",
       con->name, cmd, (int16_t)con->data[cmd]);
   return con->data[cmd];
}
EXPORT_SYMBOL_GPL(u_audio_fu_get_cmd);
 
static void g_audio_work(struct work_struct *data)
{
   struct g_audio *audio = container_of(data, struct g_audio, work);
   struct uac_params *params = &audio->params;
   char *uac_event[4]  = { NULL, NULL, NULL, NULL };
   char str[19];
   signed short volume;
   int i;
 
   for (i = 0; i < SET_USB_STATE_MAX; i++) {
       if (!audio->usb_state[i])
           continue;
 
       switch (i) {
       case SET_INTERFACE_OUT:
           uac_event[0] = "USB_STATE=SET_INTERFACE";
           uac_event[1] = "STREAM_DIRECTION=OUT";
           uac_event[2] = audio->stream_state[STATE_OUT] ?
                      "STREAM_STATE=ON" : "STREAM_STATE=OFF";
           break;
       case SET_INTERFACE_IN:
           uac_event[0] = "USB_STATE=SET_INTERFACE";
           uac_event[1] = "STREAM_DIRECTION=IN";
           uac_event[2] = audio->stream_state[STATE_IN] ?
                      "STREAM_STATE=ON" : "STREAM_STATE=OFF";
           break;
       case SET_SAMPLE_RATE_OUT:
           uac_event[0] = "USB_STATE=SET_SAMPLE_RATE";
           uac_event[1] = "STREAM_DIRECTION=OUT";
           snprintf(str, sizeof(str), "SAMPLE_RATE=%d",
                       params->c_srate_active);
           uac_event[2] = str;
           break;
       case SET_SAMPLE_RATE_IN:
           uac_event[0] = "USB_STATE=SET_SAMPLE_RATE";
           uac_event[1] = "STREAM_DIRECTION=IN";
           snprintf(str, sizeof(str), "SAMPLE_RATE=%d",
                       params->p_srate_active);
           uac_event[2] = str;
           break;
       case SET_MUTE_OUT:
           uac_event[0] = "USB_STATE=SET_MUTE";
           uac_event[1] = "STREAM_DIRECTION=OUT";
           snprintf(str, sizeof(str), "MUTE=%d", params->c_mute);
           uac_event[2] = str;
           break;
       case SET_MUTE_IN:
           uac_event[0] = "USB_STATE=SET_MUTE";
           uac_event[1] = "STREAM_DIRECTION=IN";
           snprintf(str, sizeof(str), "MUTE=%d", params->p_mute);
           uac_event[2] = str;
           break;
       case SET_VOLUME_OUT:
           uac_event[0] = "USB_STATE=SET_VOLUME";
           uac_event[1] = "STREAM_DIRECTION=OUT";
           volume = (signed short)params->c_volume;
           volume /= UAC_VOLUME_RES;
           snprintf(str, sizeof(str), "VOLUME=%d%%", volume + 50);
           uac_event[2] = str;
           break;
       case SET_VOLUME_IN:
           uac_event[0] = "USB_STATE=SET_VOLUME";
           uac_event[1] = "STREAM_DIRECTION=IN";
           volume = (signed short)params->p_volume;
           volume /= UAC_VOLUME_RES;
           snprintf(str, sizeof(str), "VOLUME=%d%%", volume + 50);
           uac_event[2] = str;
           break;
       case SET_AUDIO_CLK:
           uac_event[0] = "USB_STATE=SET_AUDIO_CLK";
           snprintf(str, sizeof(str), "PPM=%d", params->ppm);
           uac_event[1] = str;
       default:
           break;
       }
 
       audio->usb_state[i] = false;
       kobject_uevent_env(&audio->device->kobj, KOBJ_CHANGE,
                  uac_event);
       dev_dbg(audio->device, "%s: sent uac uevent %s %s %s\n",
           __func__, uac_event[0], uac_event[1], uac_event[2]);
   }
}
 
static void ppm_calculate_work(struct work_struct *data)
{
   struct g_audio *g_audio = container_of(data, struct g_audio,
                          ppm_work.work);
   struct usb_gadget *gadget = g_audio->gadget;
   uint32_t frame_number, fn_msec, clk_msec;
   struct frame_number_data *fn = g_audio->fn;
   uint64_t time_now, time_msec_tmp;
   int32_t ppm;
   static int32_t ppms[CLK_PPM_GROUP_SIZE];
   static int32_t ppm_sum;
   int32_t cnt = fn->second % CLK_PPM_GROUP_SIZE;
 
   time_now = ktime_get_raw();
   frame_number = gadget->ops->get_frame(gadget);
 
   if (g_audio->fn->time_last &&
       time_now - g_audio->fn->time_last > 1500000000ULL)
       dev_warn(g_audio->device, "PPM work scheduled too slow!\n");
 
   g_audio->fn->time_last = time_now;
 
   /*
    * If usb is disconnected, the controller will not receive the
    * SoF signal and frame number will be invalid. Because we can't
    * get accurate time of disconnect and whether the gadget will be
    * plugged into the same host next time or not. We must clear all
    * statistics.
    */
   if (gadget->state != USB_STATE_CONFIGURED) {
       memset(g_audio->fn, 0, sizeof(*g_audio->fn));
       dev_dbg(g_audio->device, "Disconnect. frame number is cleared\n");
       goto out;
   }
 
   /* Fist statistic to record begin frame number and system time */
   if (!g_audio->fn->second++) {
       g_audio->fn->time_begin = g_audio->fn->time_last;
       g_audio->fn->fn_begin = frame_number;
       g_audio->fn->fn_last = frame_number;
       goto out;
   }
 
   /*
    * For DWC3 Controller, only 13 bits is used to store frame(micro)
    * number. In other words, the frame number will overflow at most
    * 2.047 seconds. We add another registor fn_overflow the record
    * total frame number.
    */
   if (frame_number <= g_audio->fn->fn_last)
       g_audio->fn->fn_overflow++;
   g_audio->fn->fn_last = frame_number;
 
   if (!g_audio->fn->fn_overflow)
       goto out;
 
   /* The lower 3 bits represent micro number frame, we don't need it */
   fn_msec = (((fn->fn_overflow - 1) << 14) +
          (BIT(14) + fn->fn_last - fn->fn_begin) + BIT(2)) >> 3;
   time_msec_tmp = fn->time_last - fn->time_begin + 500000ULL;
   do_div(time_msec_tmp, 1000000U);
   clk_msec = (uint32_t)time_msec_tmp;
 
   /*
    * According to the definition of ppm:
    *   host_clk = (1 + ppm / 1000000) * gadget_clk
    * we can get:
    *   ppm = (host_clk - gadget_clk) * 1000000 / gadget_clk
    */
   ppm = (fn_msec > clk_msec) ?
         (fn_msec - clk_msec) * 1000000L / clk_msec :
         -((clk_msec - fn_msec) * 1000000L / clk_msec);
 
   ppm_sum = ppm_sum - ppms[cnt] + ppm;
   ppms[cnt] = ppm;
 
   dev_dbg(g_audio->device,
       "frame %u msec %u ppm_calc %d ppm_avage(%d) %d\n",
       fn_msec, clk_msec, ppm, CLK_PPM_GROUP_SIZE,
       ppm_sum / CLK_PPM_GROUP_SIZE);
 
   /*
    * We calculate the average of ppm over a period of time. If the
    * latest frame number is too far from the average, no event will
    * be sent.
    */
   if (abs(ppm_sum / CLK_PPM_GROUP_SIZE - ppm) < 3) {
       ppm = ppm_sum > 0 ?
             (ppm_sum + CLK_PPM_GROUP_SIZE / 2) / CLK_PPM_GROUP_SIZE :
             (ppm_sum - CLK_PPM_GROUP_SIZE / 2) / CLK_PPM_GROUP_SIZE;
       if (ppm != g_audio->params.ppm) {
           g_audio->params.ppm = ppm;
           g_audio->usb_state[SET_AUDIO_CLK] = true;
           schedule_work(&g_audio->work);
       }
   }
 
out:
   schedule_delayed_work(&g_audio->ppm_work, 1 * HZ);
}
 
int g_audio_setup(struct g_audio *g_audio, const char *pcm_name,
                   const char *card_name)
{
   struct snd_uac_chip *uac;
   struct snd_card *card;
   struct snd_pcm *pcm;
   struct uac_params *params;
   int p_chmask, c_chmask;
   int err;
   int i;
 
   if (!g_audio)
       return -EINVAL;
 
   uac = kzalloc(sizeof(*uac), GFP_KERNEL);
   if (!uac)
       return -ENOMEM;
   g_audio->uac = uac;
   uac->audio_dev = g_audio;
 
   params = &g_audio->params;
   p_chmask = params->p_chmask;
   c_chmask = params->c_chmask;
 
   g_audio->fn = kzalloc(sizeof(*g_audio->fn), GFP_KERNEL);
   if (!g_audio->fn) {
       err = -ENOMEM;
       goto fail;
   }
 
   if (c_chmask) {
       struct uac_rtd_params *prm = &uac->c_prm;
 
       uac->c_prm.uac = uac;
       prm->max_psize = g_audio->out_ep_maxpsize;
 
       prm->ureq = kcalloc(params->req_number, sizeof(struct uac_req),
               GFP_KERNEL);
       if (!prm->ureq) {
           err = -ENOMEM;
           goto fail;
       }
 
       prm->rbuf = kcalloc(params->req_number, prm->max_psize,
               GFP_KERNEL);
       if (!prm->rbuf) {
           prm->max_psize = 0;
           err = -ENOMEM;
           goto fail;
       }
   }
 
   if (p_chmask) {
       struct uac_rtd_params *prm = &uac->p_prm;
 
       uac->p_prm.uac = uac;
       prm->max_psize = g_audio->in_ep_maxpsize;
 
       prm->ureq = kcalloc(params->req_number, sizeof(struct uac_req),
               GFP_KERNEL);
       if (!prm->ureq) {
           err = -ENOMEM;
           goto fail;
       }
 
       prm->rbuf = kcalloc(params->req_number, prm->max_psize,
               GFP_KERNEL);
       if (!prm->rbuf) {
           prm->max_psize = 0;
           err = -ENOMEM;
           goto fail;
       }
   }
 
   /* Choose any slot, with no id */
   err = snd_card_new(&g_audio->gadget->dev,
           -1, NULL, THIS_MODULE, 0, &card);
   if (err < 0)
       goto fail;
 
   uac->card = card;
 
   /*
    * Create first PCM device
    * Create a substream only for non-zero channel streams
    */
   err = snd_pcm_new(uac->card, pcm_name, 0,
                  p_chmask ? 1 : 0, c_chmask ? 1 : 0, &pcm);
   if (err < 0)
       goto snd_fail;
 
   strlcpy(pcm->name, pcm_name, sizeof(pcm->name));
   pcm->private_data = uac;
   uac->pcm = pcm;
 
   snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &uac_pcm_ops);
   snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &uac_pcm_ops);
 
   strlcpy(card->driver, card_name, sizeof(card->driver));
   strlcpy(card->shortname, card_name, sizeof(card->shortname));
   sprintf(card->longname, "%s %i", card_name, card->dev->id);
 
   snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS,
       snd_dma_continuous_data(GFP_KERNEL), 0, BUFF_SIZE_MAX);
 
   /* Add controls */
   for (i = 0; i < ARRAY_SIZE(uac_pcm_controls); i++) {
       err = snd_ctl_add(card,
               snd_ctl_new1(&uac_pcm_controls[i], uac));
       if (err < 0)
           goto snd_fail;
   }
 
   err = snd_card_register(card);
   if (err < 0)
       goto snd_fail;
 
   g_audio->device = device_create(audio_class, NULL, MKDEV(0, 0), NULL,
                   "%s", g_audio->uac->card->longname);
   if (IS_ERR(g_audio->device)) {
       err = PTR_ERR(g_audio->device);
       goto snd_fail;
   }
 
   INIT_WORK(&g_audio->work, g_audio_work);
   INIT_DELAYED_WORK(&g_audio->ppm_work, ppm_calculate_work);
   ppm_calculate_work(&g_audio->ppm_work.work);
 
   if (!err)
       return 0;
 
snd_fail:
   snd_card_free(card);
fail:
   kfree(uac->p_prm.ureq);
   kfree(uac->c_prm.ureq);
   kfree(uac->p_prm.rbuf);
   kfree(uac->c_prm.rbuf);
   kfree(uac);
   kfree(g_audio->fn);
 
   return err;
}
EXPORT_SYMBOL_GPL(g_audio_setup);
 
void g_audio_cleanup(struct g_audio *g_audio)
{
   struct snd_uac_chip *uac;
   struct snd_card *card;
 
   if (!g_audio || !g_audio->uac)
       return;
 
   cancel_work_sync(&g_audio->work);
   cancel_delayed_work_sync(&g_audio->ppm_work);
   device_destroy(g_audio->device->class, g_audio->device->devt);
   g_audio->device = NULL;
 
   uac = g_audio->uac;
   card = uac->card;
   if (card)
       snd_card_free(card);
 
   free_ep(&uac->c_prm, g_audio->out_ep);
   free_ep(&uac->p_prm, g_audio->in_ep);
 
   kfree(uac->p_prm.ureq);
   kfree(uac->c_prm.ureq);
   kfree(uac->p_prm.rbuf);
   kfree(uac->c_prm.rbuf);
   kfree(uac);
   kfree(g_audio->fn);
}
EXPORT_SYMBOL_GPL(g_audio_cleanup);
 
static int __init u_audio_init(void)
{
   int err = 0;
 
   audio_class = class_create(THIS_MODULE, "u_audio");
   if (IS_ERR(audio_class)) {
       err = PTR_ERR(audio_class);
       audio_class = NULL;
   }
 
   return err;
}
module_init(u_audio_init);
 
static void __exit u_audio_exit(void)
{
   if (audio_class)
       class_destroy(audio_class);
}
module_exit(u_audio_exit);
 
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("USB gadget \"ALSA sound card\" utilities");
MODULE_AUTHOR("Ruslan Bilovol");