Merge branch 'linux-linaro-lsk-v4.4' into linux-linaro-lsk-v4.4-android
[firefly-linux-kernel-4.4.55.git] / drivers / usb / gadget / function / f_audio_source.c
1 /*
2  * Gadget Function Driver for USB audio source device
3  *
4  * Copyright (C) 2012 Google, Inc.
5  *
6  * This software is licensed under the terms of the GNU General Public
7  * License version 2, as published by the Free Software Foundation, and
8  * may be copied, distributed, and modified under those terms.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  */
16
17 #include <linux/device.h>
18 #include <linux/usb/audio.h>
19 #include <linux/wait.h>
20 #include <sound/core.h>
21 #include <sound/initval.h>
22 #include <sound/pcm.h>
23
24 #include <linux/usb.h>
25 #include <linux/usb_usual.h>
26 #include <linux/usb/ch9.h>
27 #include <linux/configfs.h>
28 #include <linux/usb/composite.h>
29 #include <linux/module.h>
30 #include <linux/moduleparam.h>
31 #define SAMPLE_RATE 44100
32 #define FRAMES_PER_MSEC (SAMPLE_RATE / 1000)
33
34 #define IN_EP_MAX_PACKET_SIZE 256
35
36 /* Number of requests to allocate */
37 #define IN_EP_REQ_COUNT 4
38
39 #define AUDIO_AC_INTERFACE      0
40 #define AUDIO_AS_INTERFACE      1
41 #define AUDIO_NUM_INTERFACES    2
42 #define MAX_INST_NAME_LEN     40
43
44 /* B.3.1  Standard AC Interface Descriptor */
45 static struct usb_interface_descriptor ac_interface_desc = {
46         .bLength =              USB_DT_INTERFACE_SIZE,
47         .bDescriptorType =      USB_DT_INTERFACE,
48         .bNumEndpoints =        0,
49         .bInterfaceClass =      USB_CLASS_AUDIO,
50         .bInterfaceSubClass =   USB_SUBCLASS_AUDIOCONTROL,
51 };
52
53 DECLARE_UAC_AC_HEADER_DESCRIPTOR(2);
54
55 #define UAC_DT_AC_HEADER_LENGTH UAC_DT_AC_HEADER_SIZE(AUDIO_NUM_INTERFACES)
56 /* 1 input terminal, 1 output terminal and 1 feature unit */
57 #define UAC_DT_TOTAL_LENGTH (UAC_DT_AC_HEADER_LENGTH \
58         + UAC_DT_INPUT_TERMINAL_SIZE + UAC_DT_OUTPUT_TERMINAL_SIZE \
59         + UAC_DT_FEATURE_UNIT_SIZE(0))
60 /* B.3.2  Class-Specific AC Interface Descriptor */
61 static struct uac1_ac_header_descriptor_2 ac_header_desc = {
62         .bLength =              UAC_DT_AC_HEADER_LENGTH,
63         .bDescriptorType =      USB_DT_CS_INTERFACE,
64         .bDescriptorSubtype =   UAC_HEADER,
65         .bcdADC =               __constant_cpu_to_le16(0x0100),
66         .wTotalLength =         __constant_cpu_to_le16(UAC_DT_TOTAL_LENGTH),
67         .bInCollection =        AUDIO_NUM_INTERFACES,
68         .baInterfaceNr = {
69                 [0] =           AUDIO_AC_INTERFACE,
70                 [1] =           AUDIO_AS_INTERFACE,
71         }
72 };
73
74 #define INPUT_TERMINAL_ID       1
75 static struct uac_input_terminal_descriptor input_terminal_desc = {
76         .bLength =              UAC_DT_INPUT_TERMINAL_SIZE,
77         .bDescriptorType =      USB_DT_CS_INTERFACE,
78         .bDescriptorSubtype =   UAC_INPUT_TERMINAL,
79         .bTerminalID =          INPUT_TERMINAL_ID,
80         .wTerminalType =        UAC_INPUT_TERMINAL_MICROPHONE,
81         .bAssocTerminal =       0,
82         .wChannelConfig =       0x3,
83 };
84
85 DECLARE_UAC_FEATURE_UNIT_DESCRIPTOR(0);
86
87 #define FEATURE_UNIT_ID         2
88 static struct uac_feature_unit_descriptor_0 feature_unit_desc = {
89         .bLength                = UAC_DT_FEATURE_UNIT_SIZE(0),
90         .bDescriptorType        = USB_DT_CS_INTERFACE,
91         .bDescriptorSubtype     = UAC_FEATURE_UNIT,
92         .bUnitID                = FEATURE_UNIT_ID,
93         .bSourceID              = INPUT_TERMINAL_ID,
94         .bControlSize           = 2,
95 };
96
97 #define OUTPUT_TERMINAL_ID      3
98 static struct uac1_output_terminal_descriptor output_terminal_desc = {
99         .bLength                = UAC_DT_OUTPUT_TERMINAL_SIZE,
100         .bDescriptorType        = USB_DT_CS_INTERFACE,
101         .bDescriptorSubtype     = UAC_OUTPUT_TERMINAL,
102         .bTerminalID            = OUTPUT_TERMINAL_ID,
103         .wTerminalType          = UAC_TERMINAL_STREAMING,
104         .bAssocTerminal         = FEATURE_UNIT_ID,
105         .bSourceID              = FEATURE_UNIT_ID,
106 };
107
108 /* B.4.1  Standard AS Interface Descriptor */
109 static struct usb_interface_descriptor as_interface_alt_0_desc = {
110         .bLength =              USB_DT_INTERFACE_SIZE,
111         .bDescriptorType =      USB_DT_INTERFACE,
112         .bAlternateSetting =    0,
113         .bNumEndpoints =        0,
114         .bInterfaceClass =      USB_CLASS_AUDIO,
115         .bInterfaceSubClass =   USB_SUBCLASS_AUDIOSTREAMING,
116 };
117
118 static struct usb_interface_descriptor as_interface_alt_1_desc = {
119         .bLength =              USB_DT_INTERFACE_SIZE,
120         .bDescriptorType =      USB_DT_INTERFACE,
121         .bAlternateSetting =    1,
122         .bNumEndpoints =        1,
123         .bInterfaceClass =      USB_CLASS_AUDIO,
124         .bInterfaceSubClass =   USB_SUBCLASS_AUDIOSTREAMING,
125 };
126
127 /* B.4.2  Class-Specific AS Interface Descriptor */
128 static struct uac1_as_header_descriptor as_header_desc = {
129         .bLength =              UAC_DT_AS_HEADER_SIZE,
130         .bDescriptorType =      USB_DT_CS_INTERFACE,
131         .bDescriptorSubtype =   UAC_AS_GENERAL,
132         .bTerminalLink =        INPUT_TERMINAL_ID,
133         .bDelay =               1,
134         .wFormatTag =           UAC_FORMAT_TYPE_I_PCM,
135 };
136
137 DECLARE_UAC_FORMAT_TYPE_I_DISCRETE_DESC(1);
138
139 static struct uac_format_type_i_discrete_descriptor_1 as_type_i_desc = {
140         .bLength =              UAC_FORMAT_TYPE_I_DISCRETE_DESC_SIZE(1),
141         .bDescriptorType =      USB_DT_CS_INTERFACE,
142         .bDescriptorSubtype =   UAC_FORMAT_TYPE,
143         .bFormatType =          UAC_FORMAT_TYPE_I,
144         .bSubframeSize =        2,
145         .bBitResolution =       16,
146         .bSamFreqType =         1,
147 };
148
149 /* Standard ISO IN Endpoint Descriptor for highspeed */
150 static struct usb_endpoint_descriptor hs_as_in_ep_desc  = {
151         .bLength =              USB_DT_ENDPOINT_AUDIO_SIZE,
152         .bDescriptorType =      USB_DT_ENDPOINT,
153         .bEndpointAddress =     USB_DIR_IN,
154         .bmAttributes =         USB_ENDPOINT_SYNC_SYNC
155                                 | USB_ENDPOINT_XFER_ISOC,
156         .wMaxPacketSize =       __constant_cpu_to_le16(IN_EP_MAX_PACKET_SIZE),
157         .bInterval =            4, /* poll 1 per millisecond */
158 };
159
160 /* Standard ISO IN Endpoint Descriptor for highspeed */
161 static struct usb_endpoint_descriptor fs_as_in_ep_desc  = {
162         .bLength =              USB_DT_ENDPOINT_AUDIO_SIZE,
163         .bDescriptorType =      USB_DT_ENDPOINT,
164         .bEndpointAddress =     USB_DIR_IN,
165         .bmAttributes =         USB_ENDPOINT_SYNC_SYNC
166                                 | USB_ENDPOINT_XFER_ISOC,
167         .wMaxPacketSize =       __constant_cpu_to_le16(IN_EP_MAX_PACKET_SIZE),
168         .bInterval =            1, /* poll 1 per millisecond */
169 };
170
171 /* Class-specific AS ISO OUT Endpoint Descriptor */
172 static struct uac_iso_endpoint_descriptor as_iso_in_desc = {
173         .bLength =              UAC_ISO_ENDPOINT_DESC_SIZE,
174         .bDescriptorType =      USB_DT_CS_ENDPOINT,
175         .bDescriptorSubtype =   UAC_EP_GENERAL,
176         .bmAttributes =         1,
177         .bLockDelayUnits =      1,
178         .wLockDelay =           __constant_cpu_to_le16(1),
179 };
180
181 static struct usb_descriptor_header *hs_audio_desc[] = {
182         (struct usb_descriptor_header *)&ac_interface_desc,
183         (struct usb_descriptor_header *)&ac_header_desc,
184
185         (struct usb_descriptor_header *)&input_terminal_desc,
186         (struct usb_descriptor_header *)&output_terminal_desc,
187         (struct usb_descriptor_header *)&feature_unit_desc,
188
189         (struct usb_descriptor_header *)&as_interface_alt_0_desc,
190         (struct usb_descriptor_header *)&as_interface_alt_1_desc,
191         (struct usb_descriptor_header *)&as_header_desc,
192
193         (struct usb_descriptor_header *)&as_type_i_desc,
194
195         (struct usb_descriptor_header *)&hs_as_in_ep_desc,
196         (struct usb_descriptor_header *)&as_iso_in_desc,
197         NULL,
198 };
199
200 static struct usb_descriptor_header *fs_audio_desc[] = {
201         (struct usb_descriptor_header *)&ac_interface_desc,
202         (struct usb_descriptor_header *)&ac_header_desc,
203
204         (struct usb_descriptor_header *)&input_terminal_desc,
205         (struct usb_descriptor_header *)&output_terminal_desc,
206         (struct usb_descriptor_header *)&feature_unit_desc,
207
208         (struct usb_descriptor_header *)&as_interface_alt_0_desc,
209         (struct usb_descriptor_header *)&as_interface_alt_1_desc,
210         (struct usb_descriptor_header *)&as_header_desc,
211
212         (struct usb_descriptor_header *)&as_type_i_desc,
213
214         (struct usb_descriptor_header *)&fs_as_in_ep_desc,
215         (struct usb_descriptor_header *)&as_iso_in_desc,
216         NULL,
217 };
218
219 static struct snd_pcm_hardware audio_hw_info = {
220         .info =                 SNDRV_PCM_INFO_MMAP |
221                                 SNDRV_PCM_INFO_MMAP_VALID |
222                                 SNDRV_PCM_INFO_BATCH |
223                                 SNDRV_PCM_INFO_INTERLEAVED |
224                                 SNDRV_PCM_INFO_BLOCK_TRANSFER,
225
226         .formats                = SNDRV_PCM_FMTBIT_S16_LE,
227         .channels_min           = 2,
228         .channels_max           = 2,
229         .rate_min               = SAMPLE_RATE,
230         .rate_max               = SAMPLE_RATE,
231
232         .buffer_bytes_max =     1024 * 1024,
233         .period_bytes_min =     64,
234         .period_bytes_max =     512 * 1024,
235         .periods_min =          2,
236         .periods_max =          1024,
237 };
238
239 /*-------------------------------------------------------------------------*/
240
241 struct audio_source_config {
242         int     card;
243         int     device;
244 };
245
246 struct audio_dev {
247         struct usb_function             func;
248         struct snd_card                 *card;
249         struct snd_pcm                  *pcm;
250         struct snd_pcm_substream *substream;
251
252         struct list_head                idle_reqs;
253         struct usb_ep                   *in_ep;
254
255         spinlock_t                      lock;
256
257         /* beginning, end and current position in our buffer */
258         void                            *buffer_start;
259         void                            *buffer_end;
260         void                            *buffer_pos;
261
262         /* byte size of a "period" */
263         unsigned int                    period;
264         /* bytes sent since last call to snd_pcm_period_elapsed */
265         unsigned int                    period_offset;
266         /* time we started playing */
267         ktime_t                         start_time;
268         /* number of frames sent since start_time */
269         s64                             frames_sent;
270         struct audio_source_config      *config;
271 };
272
273 static inline struct audio_dev *func_to_audio(struct usb_function *f)
274 {
275         return container_of(f, struct audio_dev, func);
276 }
277
278 /*-------------------------------------------------------------------------*/
279
280 struct audio_source_instance {
281         struct usb_function_instance func_inst;
282         const char *name;
283         struct audio_source_config *config;
284         struct device *audio_device;
285 };
286
287 static void audio_source_attr_release(struct config_item *item);
288
289 static struct configfs_item_operations audio_source_item_ops = {
290         .release        = audio_source_attr_release,
291 };
292
293 static struct config_item_type audio_source_func_type = {
294         .ct_item_ops    = &audio_source_item_ops,
295         .ct_owner       = THIS_MODULE,
296 };
297
298 static ssize_t audio_source_pcm_show(struct device *dev,
299                 struct device_attribute *attr, char *buf);
300
301 static DEVICE_ATTR(pcm, S_IRUGO, audio_source_pcm_show, NULL);
302
303 static struct device_attribute *audio_source_function_attributes[] = {
304         &dev_attr_pcm,
305         NULL
306 };
307
308 /*--------------------------------------------------------------------------*/
309
310 static struct usb_request *audio_request_new(struct usb_ep *ep, int buffer_size)
311 {
312         struct usb_request *req = usb_ep_alloc_request(ep, GFP_KERNEL);
313
314         if (!req)
315                 return NULL;
316
317         req->buf = kmalloc(buffer_size, GFP_KERNEL);
318         if (!req->buf) {
319                 usb_ep_free_request(ep, req);
320                 return NULL;
321         }
322         req->length = buffer_size;
323         return req;
324 }
325
326 static void audio_request_free(struct usb_request *req, struct usb_ep *ep)
327 {
328         if (req) {
329                 kfree(req->buf);
330                 usb_ep_free_request(ep, req);
331         }
332 }
333
334 static void audio_req_put(struct audio_dev *audio, struct usb_request *req)
335 {
336         unsigned long flags;
337
338         spin_lock_irqsave(&audio->lock, flags);
339         list_add_tail(&req->list, &audio->idle_reqs);
340         spin_unlock_irqrestore(&audio->lock, flags);
341 }
342
343 static struct usb_request *audio_req_get(struct audio_dev *audio)
344 {
345         unsigned long flags;
346         struct usb_request *req;
347
348         spin_lock_irqsave(&audio->lock, flags);
349         if (list_empty(&audio->idle_reqs)) {
350                 req = 0;
351         } else {
352                 req = list_first_entry(&audio->idle_reqs, struct usb_request,
353                                 list);
354                 list_del(&req->list);
355         }
356         spin_unlock_irqrestore(&audio->lock, flags);
357         return req;
358 }
359
360 /* send the appropriate number of packets to match our bitrate */
361 static void audio_send(struct audio_dev *audio)
362 {
363         struct snd_pcm_runtime *runtime;
364         struct usb_request *req;
365         int length, length1, length2, ret;
366         s64 msecs;
367         s64 frames;
368         ktime_t now;
369
370         /* audio->substream will be null if we have been closed */
371         if (!audio->substream)
372                 return;
373         /* audio->buffer_pos will be null if we have been stopped */
374         if (!audio->buffer_pos)
375                 return;
376
377         runtime = audio->substream->runtime;
378
379         /* compute number of frames to send */
380         now = ktime_get();
381         msecs = div_s64((ktime_to_ns(now) - ktime_to_ns(audio->start_time)),
382                         1000000);
383         frames = div_s64((msecs * SAMPLE_RATE), 1000);
384
385         /* Readjust our frames_sent if we fall too far behind.
386          * If we get too far behind it is better to drop some frames than
387          * to keep sending data too fast in an attempt to catch up.
388          */
389         if (frames - audio->frames_sent > 10 * FRAMES_PER_MSEC)
390                 audio->frames_sent = frames - FRAMES_PER_MSEC;
391
392         frames -= audio->frames_sent;
393
394         /* We need to send something to keep the pipeline going */
395         if (frames <= 0)
396                 frames = FRAMES_PER_MSEC;
397
398         while (frames > 0) {
399                 req = audio_req_get(audio);
400                 if (!req)
401                         break;
402
403                 length = frames_to_bytes(runtime, frames);
404                 if (length > IN_EP_MAX_PACKET_SIZE)
405                         length = IN_EP_MAX_PACKET_SIZE;
406
407                 if (audio->buffer_pos + length > audio->buffer_end)
408                         length1 = audio->buffer_end - audio->buffer_pos;
409                 else
410                         length1 = length;
411                 memcpy(req->buf, audio->buffer_pos, length1);
412                 if (length1 < length) {
413                         /* Wrap around and copy remaining length
414                          * at beginning of buffer.
415                          */
416                         length2 = length - length1;
417                         memcpy(req->buf + length1, audio->buffer_start,
418                                         length2);
419                         audio->buffer_pos = audio->buffer_start + length2;
420                 } else {
421                         audio->buffer_pos += length1;
422                         if (audio->buffer_pos >= audio->buffer_end)
423                                 audio->buffer_pos = audio->buffer_start;
424                 }
425
426                 req->length = length;
427                 ret = usb_ep_queue(audio->in_ep, req, GFP_ATOMIC);
428                 if (ret < 0) {
429                         pr_err("usb_ep_queue failed ret: %d\n", ret);
430                         audio_req_put(audio, req);
431                         break;
432                 }
433
434                 frames -= bytes_to_frames(runtime, length);
435                 audio->frames_sent += bytes_to_frames(runtime, length);
436         }
437 }
438
439 static void audio_control_complete(struct usb_ep *ep, struct usb_request *req)
440 {
441         /* nothing to do here */
442 }
443
444 static void audio_data_complete(struct usb_ep *ep, struct usb_request *req)
445 {
446         struct audio_dev *audio = req->context;
447
448         pr_debug("audio_data_complete req->status %d req->actual %d\n",
449                 req->status, req->actual);
450
451         audio_req_put(audio, req);
452
453         if (!audio->buffer_start || req->status)
454                 return;
455
456         audio->period_offset += req->actual;
457         if (audio->period_offset >= audio->period) {
458                 snd_pcm_period_elapsed(audio->substream);
459                 audio->period_offset = 0;
460         }
461         audio_send(audio);
462 }
463
464 static int audio_set_endpoint_req(struct usb_function *f,
465                 const struct usb_ctrlrequest *ctrl)
466 {
467         int value = -EOPNOTSUPP;
468         u16 ep = le16_to_cpu(ctrl->wIndex);
469         u16 len = le16_to_cpu(ctrl->wLength);
470         u16 w_value = le16_to_cpu(ctrl->wValue);
471
472         pr_debug("bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
473                         ctrl->bRequest, w_value, len, ep);
474
475         switch (ctrl->bRequest) {
476         case UAC_SET_CUR:
477         case UAC_SET_MIN:
478         case UAC_SET_MAX:
479         case UAC_SET_RES:
480                 value = len;
481                 break;
482         default:
483                 break;
484         }
485
486         return value;
487 }
488
489 static int audio_get_endpoint_req(struct usb_function *f,
490                 const struct usb_ctrlrequest *ctrl)
491 {
492         struct usb_composite_dev *cdev = f->config->cdev;
493         int value = -EOPNOTSUPP;
494         u8 ep = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
495         u16 len = le16_to_cpu(ctrl->wLength);
496         u16 w_value = le16_to_cpu(ctrl->wValue);
497         u8 *buf = cdev->req->buf;
498
499         pr_debug("bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
500                         ctrl->bRequest, w_value, len, ep);
501
502         if (w_value == UAC_EP_CS_ATTR_SAMPLE_RATE << 8) {
503                 switch (ctrl->bRequest) {
504                 case UAC_GET_CUR:
505                 case UAC_GET_MIN:
506                 case UAC_GET_MAX:
507                 case UAC_GET_RES:
508                         /* return our sample rate */
509                         buf[0] = (u8)SAMPLE_RATE;
510                         buf[1] = (u8)(SAMPLE_RATE >> 8);
511                         buf[2] = (u8)(SAMPLE_RATE >> 16);
512                         value = 3;
513                         break;
514                 default:
515                         break;
516                 }
517         }
518
519         return value;
520 }
521
522 static int
523 audio_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
524 {
525         struct usb_composite_dev *cdev = f->config->cdev;
526         struct usb_request *req = cdev->req;
527         int value = -EOPNOTSUPP;
528         u16 w_index = le16_to_cpu(ctrl->wIndex);
529         u16 w_value = le16_to_cpu(ctrl->wValue);
530         u16 w_length = le16_to_cpu(ctrl->wLength);
531
532         /* composite driver infrastructure handles everything; interface
533          * activation uses set_alt().
534          */
535         switch (ctrl->bRequestType) {
536         case USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
537                 value = audio_set_endpoint_req(f, ctrl);
538                 break;
539
540         case USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
541                 value = audio_get_endpoint_req(f, ctrl);
542                 break;
543         }
544
545         /* respond with data transfer or status phase? */
546         if (value >= 0) {
547                 pr_debug("audio req%02x.%02x v%04x i%04x l%d\n",
548                         ctrl->bRequestType, ctrl->bRequest,
549                         w_value, w_index, w_length);
550                 req->zero = 0;
551                 req->length = value;
552                 req->complete = audio_control_complete;
553                 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
554                 if (value < 0)
555                         pr_err("audio response on err %d\n", value);
556         }
557
558         /* device either stalls (value < 0) or reports success */
559         return value;
560 }
561
562 static int audio_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
563 {
564         struct audio_dev *audio = func_to_audio(f);
565         struct usb_composite_dev *cdev = f->config->cdev;
566         int ret;
567
568         pr_debug("audio_set_alt intf %d, alt %d\n", intf, alt);
569
570         ret = config_ep_by_speed(cdev->gadget, f, audio->in_ep);
571         if (ret)
572                 return ret;
573
574         usb_ep_enable(audio->in_ep);
575         return 0;
576 }
577
578 static void audio_disable(struct usb_function *f)
579 {
580         struct audio_dev        *audio = func_to_audio(f);
581
582         pr_debug("audio_disable\n");
583         usb_ep_disable(audio->in_ep);
584 }
585
586 static void audio_free_func(struct usb_function *f)
587 {
588         /* no-op */
589 }
590
591 /*-------------------------------------------------------------------------*/
592
593 static void audio_build_desc(struct audio_dev *audio)
594 {
595         u8 *sam_freq;
596         int rate;
597
598         /* Set channel numbers */
599         input_terminal_desc.bNrChannels = 2;
600         as_type_i_desc.bNrChannels = 2;
601
602         /* Set sample rates */
603         rate = SAMPLE_RATE;
604         sam_freq = as_type_i_desc.tSamFreq[0];
605         memcpy(sam_freq, &rate, 3);
606 }
607
608
609 static int snd_card_setup(struct usb_configuration *c,
610         struct audio_source_config *config);
611 static struct audio_source_instance *to_fi_audio_source(
612         const struct usb_function_instance *fi);
613
614
615 /* audio function driver setup/binding */
616 static int
617 audio_bind(struct usb_configuration *c, struct usb_function *f)
618 {
619         struct usb_composite_dev *cdev = c->cdev;
620         struct audio_dev *audio = func_to_audio(f);
621         int status;
622         struct usb_ep *ep;
623         struct usb_request *req;
624         int i;
625         int err;
626
627         if (IS_ENABLED(CONFIG_USB_CONFIGFS)) {
628                 struct audio_source_instance *fi_audio =
629                                 to_fi_audio_source(f->fi);
630                 struct audio_source_config *config =
631                                 fi_audio->config;
632
633                 err = snd_card_setup(c, config);
634                 if (err)
635                         return err;
636         }
637
638         audio_build_desc(audio);
639
640         /* allocate instance-specific interface IDs, and patch descriptors */
641         status = usb_interface_id(c, f);
642         if (status < 0)
643                 goto fail;
644         ac_interface_desc.bInterfaceNumber = status;
645
646         /* AUDIO_AC_INTERFACE */
647         ac_header_desc.baInterfaceNr[0] = status;
648
649         status = usb_interface_id(c, f);
650         if (status < 0)
651                 goto fail;
652         as_interface_alt_0_desc.bInterfaceNumber = status;
653         as_interface_alt_1_desc.bInterfaceNumber = status;
654
655         /* AUDIO_AS_INTERFACE */
656         ac_header_desc.baInterfaceNr[1] = status;
657
658         status = -ENODEV;
659
660         /* allocate our endpoint */
661         ep = usb_ep_autoconfig(cdev->gadget, &fs_as_in_ep_desc);
662         if (!ep)
663                 goto fail;
664         audio->in_ep = ep;
665         ep->driver_data = audio; /* claim */
666
667         if (gadget_is_dualspeed(c->cdev->gadget))
668                 hs_as_in_ep_desc.bEndpointAddress =
669                         fs_as_in_ep_desc.bEndpointAddress;
670
671         f->fs_descriptors = fs_audio_desc;
672         f->hs_descriptors = hs_audio_desc;
673
674         for (i = 0, status = 0; i < IN_EP_REQ_COUNT && status == 0; i++) {
675                 req = audio_request_new(ep, IN_EP_MAX_PACKET_SIZE);
676                 if (req) {
677                         req->context = audio;
678                         req->complete = audio_data_complete;
679                         audio_req_put(audio, req);
680                 } else
681                         status = -ENOMEM;
682         }
683
684 fail:
685         return status;
686 }
687
688 static void
689 audio_unbind(struct usb_configuration *c, struct usb_function *f)
690 {
691         struct audio_dev *audio = func_to_audio(f);
692         struct usb_request *req;
693
694         while ((req = audio_req_get(audio)))
695                 audio_request_free(req, audio->in_ep);
696
697         snd_card_free_when_closed(audio->card);
698         audio->card = NULL;
699         audio->pcm = NULL;
700         audio->substream = NULL;
701         audio->in_ep = NULL;
702
703         if (IS_ENABLED(CONFIG_USB_CONFIGFS)) {
704                 struct audio_source_instance *fi_audio =
705                                 to_fi_audio_source(f->fi);
706                 struct audio_source_config *config =
707                                 fi_audio->config;
708
709                 config->card = -1;
710                 config->device = -1;
711         }
712 }
713
714 static void audio_pcm_playback_start(struct audio_dev *audio)
715 {
716         audio->start_time = ktime_get();
717         audio->frames_sent = 0;
718         audio_send(audio);
719 }
720
721 static void audio_pcm_playback_stop(struct audio_dev *audio)
722 {
723         unsigned long flags;
724
725         spin_lock_irqsave(&audio->lock, flags);
726         audio->buffer_start = 0;
727         audio->buffer_end = 0;
728         audio->buffer_pos = 0;
729         spin_unlock_irqrestore(&audio->lock, flags);
730 }
731
732 static int audio_pcm_open(struct snd_pcm_substream *substream)
733 {
734         struct snd_pcm_runtime *runtime = substream->runtime;
735         struct audio_dev *audio = substream->private_data;
736
737         runtime->private_data = audio;
738         runtime->hw = audio_hw_info;
739         snd_pcm_limit_hw_rates(runtime);
740         runtime->hw.channels_max = 2;
741
742         audio->substream = substream;
743         return 0;
744 }
745
746 static int audio_pcm_close(struct snd_pcm_substream *substream)
747 {
748         struct audio_dev *audio = substream->private_data;
749         unsigned long flags;
750
751         spin_lock_irqsave(&audio->lock, flags);
752         audio->substream = NULL;
753         spin_unlock_irqrestore(&audio->lock, flags);
754
755         return 0;
756 }
757
758 static int audio_pcm_hw_params(struct snd_pcm_substream *substream,
759                                 struct snd_pcm_hw_params *params)
760 {
761         unsigned int channels = params_channels(params);
762         unsigned int rate = params_rate(params);
763
764         if (rate != SAMPLE_RATE)
765                 return -EINVAL;
766         if (channels != 2)
767                 return -EINVAL;
768
769         return snd_pcm_lib_alloc_vmalloc_buffer(substream,
770                 params_buffer_bytes(params));
771 }
772
773 static int audio_pcm_hw_free(struct snd_pcm_substream *substream)
774 {
775         return snd_pcm_lib_free_vmalloc_buffer(substream);
776 }
777
778 static int audio_pcm_prepare(struct snd_pcm_substream *substream)
779 {
780         struct snd_pcm_runtime *runtime = substream->runtime;
781         struct audio_dev *audio = runtime->private_data;
782
783         audio->period = snd_pcm_lib_period_bytes(substream);
784         audio->period_offset = 0;
785         audio->buffer_start = runtime->dma_area;
786         audio->buffer_end = audio->buffer_start
787                 + snd_pcm_lib_buffer_bytes(substream);
788         audio->buffer_pos = audio->buffer_start;
789
790         return 0;
791 }
792
793 static snd_pcm_uframes_t audio_pcm_pointer(struct snd_pcm_substream *substream)
794 {
795         struct snd_pcm_runtime *runtime = substream->runtime;
796         struct audio_dev *audio = runtime->private_data;
797         ssize_t bytes = audio->buffer_pos - audio->buffer_start;
798
799         /* return offset of next frame to fill in our buffer */
800         return bytes_to_frames(runtime, bytes);
801 }
802
803 static int audio_pcm_playback_trigger(struct snd_pcm_substream *substream,
804                                         int cmd)
805 {
806         struct audio_dev *audio = substream->runtime->private_data;
807         int ret = 0;
808
809         switch (cmd) {
810         case SNDRV_PCM_TRIGGER_START:
811         case SNDRV_PCM_TRIGGER_RESUME:
812                 audio_pcm_playback_start(audio);
813                 break;
814
815         case SNDRV_PCM_TRIGGER_STOP:
816         case SNDRV_PCM_TRIGGER_SUSPEND:
817                 audio_pcm_playback_stop(audio);
818                 break;
819
820         default:
821                 ret = -EINVAL;
822         }
823
824         return ret;
825 }
826
827 static struct audio_dev _audio_dev = {
828         .func = {
829                 .name = "audio_source",
830                 .bind = audio_bind,
831                 .unbind = audio_unbind,
832                 .set_alt = audio_set_alt,
833                 .setup = audio_setup,
834                 .disable = audio_disable,
835                 .free_func = audio_free_func,
836         },
837         .lock = __SPIN_LOCK_UNLOCKED(_audio_dev.lock),
838         .idle_reqs = LIST_HEAD_INIT(_audio_dev.idle_reqs),
839 };
840
841 static struct snd_pcm_ops audio_playback_ops = {
842         .open           = audio_pcm_open,
843         .close          = audio_pcm_close,
844         .ioctl          = snd_pcm_lib_ioctl,
845         .hw_params      = audio_pcm_hw_params,
846         .hw_free        = audio_pcm_hw_free,
847         .prepare        = audio_pcm_prepare,
848         .trigger        = audio_pcm_playback_trigger,
849         .pointer        = audio_pcm_pointer,
850 };
851
852 int audio_source_bind_config(struct usb_configuration *c,
853                 struct audio_source_config *config)
854 {
855         struct audio_dev *audio;
856         int err;
857
858         config->card = -1;
859         config->device = -1;
860
861         audio = &_audio_dev;
862
863         err = snd_card_setup(c, config);
864         if (err)
865                 return err;
866
867         err = usb_add_function(c, &audio->func);
868         if (err)
869                 goto add_fail;
870
871         return 0;
872
873 add_fail:
874         snd_card_free(audio->card);
875         return err;
876 }
877
878 static int snd_card_setup(struct usb_configuration *c,
879                 struct audio_source_config *config)
880 {
881         struct audio_dev *audio;
882         struct snd_card *card;
883         struct snd_pcm *pcm;
884         int err;
885
886         audio = &_audio_dev;
887
888         err = snd_card_new(&c->cdev->gadget->dev,
889                         SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1,
890                         THIS_MODULE, 0, &card);
891         if (err)
892                 return err;
893
894         err = snd_pcm_new(card, "USB audio source", 0, 1, 0, &pcm);
895         if (err)
896                 goto pcm_fail;
897
898         pcm->private_data = audio;
899         pcm->info_flags = 0;
900         audio->pcm = pcm;
901
902         strlcpy(pcm->name, "USB gadget audio", sizeof(pcm->name));
903
904         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &audio_playback_ops);
905         snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
906                                 NULL, 0, 64 * 1024);
907
908         strlcpy(card->driver, "audio_source", sizeof(card->driver));
909         strlcpy(card->shortname, card->driver, sizeof(card->shortname));
910         strlcpy(card->longname, "USB accessory audio source",
911                 sizeof(card->longname));
912
913         err = snd_card_register(card);
914         if (err)
915                 goto register_fail;
916
917         config->card = pcm->card->number;
918         config->device = pcm->device;
919         audio->card = card;
920         return 0;
921
922 register_fail:
923 pcm_fail:
924         snd_card_free(audio->card);
925         return err;
926 }
927
928 static struct audio_source_instance *to_audio_source_instance(
929                                         struct config_item *item)
930 {
931         return container_of(to_config_group(item), struct audio_source_instance,
932                 func_inst.group);
933 }
934
935 static struct audio_source_instance *to_fi_audio_source(
936                                         const struct usb_function_instance *fi)
937 {
938         return container_of(fi, struct audio_source_instance, func_inst);
939 }
940
941 static void audio_source_attr_release(struct config_item *item)
942 {
943         struct audio_source_instance *fi_audio = to_audio_source_instance(item);
944
945         usb_put_function_instance(&fi_audio->func_inst);
946 }
947
948 static int audio_source_set_inst_name(struct usb_function_instance *fi,
949                                         const char *name)
950 {
951         struct audio_source_instance *fi_audio;
952         char *ptr;
953         int name_len;
954
955         name_len = strlen(name) + 1;
956         if (name_len > MAX_INST_NAME_LEN)
957                 return -ENAMETOOLONG;
958
959         ptr = kstrndup(name, name_len, GFP_KERNEL);
960         if (!ptr)
961                 return -ENOMEM;
962
963         fi_audio = to_fi_audio_source(fi);
964         fi_audio->name = ptr;
965
966         return 0;
967 }
968
969 static void audio_source_free_inst(struct usb_function_instance *fi)
970 {
971         struct audio_source_instance *fi_audio;
972
973         fi_audio = to_fi_audio_source(fi);
974         device_destroy(fi_audio->audio_device->class,
975                         fi_audio->audio_device->devt);
976         kfree(fi_audio->name);
977         kfree(fi_audio->config);
978 }
979
980 static ssize_t audio_source_pcm_show(struct device *dev,
981                 struct device_attribute *attr, char *buf)
982 {
983         struct audio_source_instance *fi_audio = dev_get_drvdata(dev);
984         struct audio_source_config *config = fi_audio->config;
985
986         /* print PCM card and device numbers */
987         return sprintf(buf, "%d %d\n", config->card, config->device);
988 }
989
990 struct device *create_function_device(char *name);
991
992 static struct usb_function_instance *audio_source_alloc_inst(void)
993 {
994         struct audio_source_instance *fi_audio;
995         struct device_attribute **attrs;
996         struct device_attribute *attr;
997         struct device *dev;
998         void *err_ptr;
999         int err = 0;
1000
1001         fi_audio = kzalloc(sizeof(*fi_audio), GFP_KERNEL);
1002         if (!fi_audio)
1003                 return ERR_PTR(-ENOMEM);
1004
1005         fi_audio->func_inst.set_inst_name = audio_source_set_inst_name;
1006         fi_audio->func_inst.free_func_inst = audio_source_free_inst;
1007
1008         fi_audio->config = kzalloc(sizeof(struct audio_source_config),
1009                                                         GFP_KERNEL);
1010         if (!fi_audio->config) {
1011                 err_ptr = ERR_PTR(-ENOMEM);
1012                 goto fail_audio;
1013         }
1014
1015         config_group_init_type_name(&fi_audio->func_inst.group, "",
1016                                                 &audio_source_func_type);
1017         dev = create_function_device("f_audio_source");
1018
1019         if (IS_ERR(dev)) {
1020                 err_ptr = dev;
1021                 goto fail_audio_config;
1022         }
1023
1024         fi_audio->config->card = -1;
1025         fi_audio->config->device = -1;
1026         fi_audio->audio_device = dev;
1027
1028         attrs = audio_source_function_attributes;
1029         if (attrs) {
1030                 while ((attr = *attrs++) && !err)
1031                         err = device_create_file(dev, attr);
1032                 if (err) {
1033                         err_ptr = ERR_PTR(-EINVAL);
1034                         goto fail_device;
1035                 }
1036         }
1037
1038         dev_set_drvdata(dev, fi_audio);
1039         _audio_dev.config = fi_audio->config;
1040
1041         return  &fi_audio->func_inst;
1042
1043 fail_device:
1044         device_destroy(dev->class, dev->devt);
1045 fail_audio_config:
1046         kfree(fi_audio->config);
1047 fail_audio:
1048         kfree(fi_audio);
1049         return err_ptr;
1050
1051 }
1052
1053 static struct usb_function *audio_source_alloc(struct usb_function_instance *fi)
1054 {
1055         return &_audio_dev.func;
1056 }
1057
1058 DECLARE_USB_FUNCTION_INIT(audio_source, audio_source_alloc_inst,
1059                         audio_source_alloc);
1060 MODULE_LICENSE("GPL");