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         if (!req)
314                 return NULL;
315
316         req->buf = kmalloc(buffer_size, GFP_KERNEL);
317         if (!req->buf) {
318                 usb_ep_free_request(ep, req);
319                 return NULL;
320         }
321         req->length = buffer_size;
322         return req;
323 }
324
325 static void audio_request_free(struct usb_request *req, struct usb_ep *ep)
326 {
327         if (req) {
328                 kfree(req->buf);
329                 usb_ep_free_request(ep, req);
330         }
331 }
332
333 static void audio_req_put(struct audio_dev *audio, struct usb_request *req)
334 {
335         unsigned long flags;
336
337         spin_lock_irqsave(&audio->lock, flags);
338         list_add_tail(&req->list, &audio->idle_reqs);
339         spin_unlock_irqrestore(&audio->lock, flags);
340 }
341
342 static struct usb_request *audio_req_get(struct audio_dev *audio)
343 {
344         unsigned long flags;
345         struct usb_request *req;
346
347         spin_lock_irqsave(&audio->lock, flags);
348         if (list_empty(&audio->idle_reqs)) {
349                 req = 0;
350         } else {
351                 req = list_first_entry(&audio->idle_reqs, struct usb_request,
352                                 list);
353                 list_del(&req->list);
354         }
355         spin_unlock_irqrestore(&audio->lock, flags);
356         return req;
357 }
358
359 /* send the appropriate number of packets to match our bitrate */
360 static void audio_send(struct audio_dev *audio)
361 {
362         struct snd_pcm_runtime *runtime;
363         struct usb_request *req;
364         int length, length1, length2, ret;
365         s64 msecs;
366         s64 frames;
367         ktime_t now;
368
369         /* audio->substream will be null if we have been closed */
370         if (!audio->substream)
371                 return;
372         /* audio->buffer_pos will be null if we have been stopped */
373         if (!audio->buffer_pos)
374                 return;
375
376         runtime = audio->substream->runtime;
377
378         /* compute number of frames to send */
379         now = ktime_get();
380         msecs = ktime_to_ns(now) - ktime_to_ns(audio->start_time);
381         do_div(msecs, 1000000);
382         frames = msecs * SAMPLE_RATE;
383         do_div(frames, 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 /*-------------------------------------------------------------------------*/
587
588 static void audio_build_desc(struct audio_dev *audio)
589 {
590         u8 *sam_freq;
591         int rate;
592
593         /* Set channel numbers */
594         input_terminal_desc.bNrChannels = 2;
595         as_type_i_desc.bNrChannels = 2;
596
597         /* Set sample rates */
598         rate = SAMPLE_RATE;
599         sam_freq = as_type_i_desc.tSamFreq[0];
600         memcpy(sam_freq, &rate, 3);
601 }
602
603
604 static int snd_card_setup(struct usb_configuration *c,
605         struct audio_source_config *config);
606 static struct audio_source_instance *to_fi_audio_source(
607         const struct usb_function_instance *fi);
608
609
610 /* audio function driver setup/binding */
611 static int
612 audio_bind(struct usb_configuration *c, struct usb_function *f)
613 {
614         struct usb_composite_dev *cdev = c->cdev;
615         struct audio_dev *audio = func_to_audio(f);
616         int status;
617         struct usb_ep *ep;
618         struct usb_request *req;
619         int i;
620         int err;
621
622         if (IS_ENABLED(CONFIG_USB_CONFIGFS)) {
623                 struct audio_source_instance *fi_audio =
624                                 to_fi_audio_source(f->fi);
625                 struct audio_source_config *config =
626                                 fi_audio->config;
627
628                 err = snd_card_setup(c, config);
629                 if (err)
630                         return err;
631         }
632
633         audio_build_desc(audio);
634
635         /* allocate instance-specific interface IDs, and patch descriptors */
636         status = usb_interface_id(c, f);
637         if (status < 0)
638                 goto fail;
639         ac_interface_desc.bInterfaceNumber = status;
640
641         /* AUDIO_AC_INTERFACE */
642         ac_header_desc.baInterfaceNr[0] = status;
643
644         status = usb_interface_id(c, f);
645         if (status < 0)
646                 goto fail;
647         as_interface_alt_0_desc.bInterfaceNumber = status;
648         as_interface_alt_1_desc.bInterfaceNumber = status;
649
650         /* AUDIO_AS_INTERFACE */
651         ac_header_desc.baInterfaceNr[1] = status;
652
653         status = -ENODEV;
654
655         /* allocate our endpoint */
656         ep = usb_ep_autoconfig(cdev->gadget, &fs_as_in_ep_desc);
657         if (!ep)
658                 goto fail;
659         audio->in_ep = ep;
660         ep->driver_data = audio; /* claim */
661
662         if (gadget_is_dualspeed(c->cdev->gadget))
663                 hs_as_in_ep_desc.bEndpointAddress =
664                         fs_as_in_ep_desc.bEndpointAddress;
665
666         f->fs_descriptors = fs_audio_desc;
667         f->hs_descriptors = hs_audio_desc;
668
669         for (i = 0, status = 0; i < IN_EP_REQ_COUNT && status == 0; i++) {
670                 req = audio_request_new(ep, IN_EP_MAX_PACKET_SIZE);
671                 if (req) {
672                         req->context = audio;
673                         req->complete = audio_data_complete;
674                         audio_req_put(audio, req);
675                 } else
676                         status = -ENOMEM;
677         }
678
679 fail:
680         return status;
681 }
682
683 static void
684 audio_unbind(struct usb_configuration *c, struct usb_function *f)
685 {
686         struct audio_dev *audio = func_to_audio(f);
687         struct usb_request *req;
688
689         while ((req = audio_req_get(audio)))
690                 audio_request_free(req, audio->in_ep);
691
692         snd_card_free_when_closed(audio->card);
693         audio->card = NULL;
694         audio->pcm = NULL;
695         audio->substream = NULL;
696         audio->in_ep = NULL;
697
698         if (IS_ENABLED(CONFIG_USB_CONFIGFS)) {
699                 struct audio_source_instance *fi_audio =
700                                 to_fi_audio_source(f->fi);
701                 struct audio_source_config *config =
702                                 fi_audio->config;
703
704                 config->card = -1;
705                 config->device = -1;
706         }
707 }
708
709 static void audio_pcm_playback_start(struct audio_dev *audio)
710 {
711         audio->start_time = ktime_get();
712         audio->frames_sent = 0;
713         audio_send(audio);
714 }
715
716 static void audio_pcm_playback_stop(struct audio_dev *audio)
717 {
718         unsigned long flags;
719
720         spin_lock_irqsave(&audio->lock, flags);
721         audio->buffer_start = 0;
722         audio->buffer_end = 0;
723         audio->buffer_pos = 0;
724         spin_unlock_irqrestore(&audio->lock, flags);
725 }
726
727 static int audio_pcm_open(struct snd_pcm_substream *substream)
728 {
729         struct snd_pcm_runtime *runtime = substream->runtime;
730         struct audio_dev *audio = substream->private_data;
731
732         runtime->private_data = audio;
733         runtime->hw = audio_hw_info;
734         snd_pcm_limit_hw_rates(runtime);
735         runtime->hw.channels_max = 2;
736
737         audio->substream = substream;
738         return 0;
739 }
740
741 static int audio_pcm_close(struct snd_pcm_substream *substream)
742 {
743         struct audio_dev *audio = substream->private_data;
744         unsigned long flags;
745
746         spin_lock_irqsave(&audio->lock, flags);
747         audio->substream = NULL;
748         spin_unlock_irqrestore(&audio->lock, flags);
749
750         return 0;
751 }
752
753 static int audio_pcm_hw_params(struct snd_pcm_substream *substream,
754                                 struct snd_pcm_hw_params *params)
755 {
756         unsigned int channels = params_channels(params);
757         unsigned int rate = params_rate(params);
758
759         if (rate != SAMPLE_RATE)
760                 return -EINVAL;
761         if (channels != 2)
762                 return -EINVAL;
763
764         return snd_pcm_lib_alloc_vmalloc_buffer(substream,
765                 params_buffer_bytes(params));
766 }
767
768 static int audio_pcm_hw_free(struct snd_pcm_substream *substream)
769 {
770         return snd_pcm_lib_free_vmalloc_buffer(substream);
771 }
772
773 static int audio_pcm_prepare(struct snd_pcm_substream *substream)
774 {
775         struct snd_pcm_runtime *runtime = substream->runtime;
776         struct audio_dev *audio = runtime->private_data;
777
778         audio->period = snd_pcm_lib_period_bytes(substream);
779         audio->period_offset = 0;
780         audio->buffer_start = runtime->dma_area;
781         audio->buffer_end = audio->buffer_start
782                 + snd_pcm_lib_buffer_bytes(substream);
783         audio->buffer_pos = audio->buffer_start;
784
785         return 0;
786 }
787
788 static snd_pcm_uframes_t audio_pcm_pointer(struct snd_pcm_substream *substream)
789 {
790         struct snd_pcm_runtime *runtime = substream->runtime;
791         struct audio_dev *audio = runtime->private_data;
792         ssize_t bytes = audio->buffer_pos - audio->buffer_start;
793
794         /* return offset of next frame to fill in our buffer */
795         return bytes_to_frames(runtime, bytes);
796 }
797
798 static int audio_pcm_playback_trigger(struct snd_pcm_substream *substream,
799                                         int cmd)
800 {
801         struct audio_dev *audio = substream->runtime->private_data;
802         int ret = 0;
803
804         switch (cmd) {
805         case SNDRV_PCM_TRIGGER_START:
806         case SNDRV_PCM_TRIGGER_RESUME:
807                 audio_pcm_playback_start(audio);
808                 break;
809
810         case SNDRV_PCM_TRIGGER_STOP:
811         case SNDRV_PCM_TRIGGER_SUSPEND:
812                 audio_pcm_playback_stop(audio);
813                 break;
814
815         default:
816                 ret = -EINVAL;
817         }
818
819         return ret;
820 }
821
822 static struct audio_dev _audio_dev = {
823         .func = {
824                 .name = "audio_source",
825                 .bind = audio_bind,
826                 .unbind = audio_unbind,
827                 .set_alt = audio_set_alt,
828                 .setup = audio_setup,
829                 .disable = audio_disable,
830         },
831         .lock = __SPIN_LOCK_UNLOCKED(_audio_dev.lock),
832         .idle_reqs = LIST_HEAD_INIT(_audio_dev.idle_reqs),
833 };
834
835 static struct snd_pcm_ops audio_playback_ops = {
836         .open           = audio_pcm_open,
837         .close          = audio_pcm_close,
838         .ioctl          = snd_pcm_lib_ioctl,
839         .hw_params      = audio_pcm_hw_params,
840         .hw_free        = audio_pcm_hw_free,
841         .prepare        = audio_pcm_prepare,
842         .trigger        = audio_pcm_playback_trigger,
843         .pointer        = audio_pcm_pointer,
844 };
845
846 int audio_source_bind_config(struct usb_configuration *c,
847                 struct audio_source_config *config)
848 {
849         struct audio_dev *audio;
850         int err;
851
852         config->card = -1;
853         config->device = -1;
854
855         audio = &_audio_dev;
856
857         err = snd_card_setup(c, config);
858         if (err)
859                 return err;
860
861         err = usb_add_function(c, &audio->func);
862         if (err)
863                 goto add_fail;
864
865         return 0;
866
867 add_fail:
868         snd_card_free(audio->card);
869         return err;
870 }
871
872 static int snd_card_setup(struct usb_configuration *c,
873                 struct audio_source_config *config)
874 {
875         struct audio_dev *audio;
876         struct snd_card *card;
877         struct snd_pcm *pcm;
878         int err;
879
880         audio = &_audio_dev;
881
882         err = snd_card_new(&c->cdev->gadget->dev,
883                         SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1,
884                         THIS_MODULE, 0, &card);
885         if (err)
886                 return err;
887
888         err = snd_pcm_new(card, "USB audio source", 0, 1, 0, &pcm);
889         if (err)
890                 goto pcm_fail;
891
892         pcm->private_data = audio;
893         pcm->info_flags = 0;
894         audio->pcm = pcm;
895
896         strlcpy(pcm->name, "USB gadget audio", sizeof(pcm->name));
897
898         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &audio_playback_ops);
899         snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
900                                 NULL, 0, 64 * 1024);
901
902         strlcpy(card->driver, "audio_source", sizeof(card->driver));
903         strlcpy(card->shortname, card->driver, sizeof(card->shortname));
904         strlcpy(card->longname, "USB accessory audio source",
905                 sizeof(card->longname));
906
907         err = snd_card_register(card);
908         if (err)
909                 goto register_fail;
910
911         config->card = pcm->card->number;
912         config->device = pcm->device;
913         audio->card = card;
914         return 0;
915
916 register_fail:
917 pcm_fail:
918         snd_card_free(audio->card);
919         return err;
920 }
921
922 static struct audio_source_instance *to_audio_source_instance(
923                                         struct config_item *item)
924 {
925         return container_of(to_config_group(item), struct audio_source_instance,
926                 func_inst.group);
927 }
928
929 static struct audio_source_instance *to_fi_audio_source(
930                                         const struct usb_function_instance *fi)
931 {
932         return container_of(fi, struct audio_source_instance, func_inst);
933 }
934
935 static void audio_source_attr_release(struct config_item *item)
936 {
937         struct audio_source_instance *fi_audio = to_audio_source_instance(item);
938
939         usb_put_function_instance(&fi_audio->func_inst);
940 }
941
942 static int audio_source_set_inst_name(struct usb_function_instance *fi,
943                                         const char *name)
944 {
945         struct audio_source_instance *fi_audio;
946         char *ptr;
947         int name_len;
948
949         name_len = strlen(name) + 1;
950         if (name_len > MAX_INST_NAME_LEN)
951                 return -ENAMETOOLONG;
952
953         ptr = kstrndup(name, name_len, GFP_KERNEL);
954         if (!ptr)
955                 return -ENOMEM;
956
957         fi_audio = to_fi_audio_source(fi);
958         fi_audio->name = ptr;
959
960         return 0;
961 }
962
963 static void audio_source_free_inst(struct usb_function_instance *fi)
964 {
965         struct audio_source_instance *fi_audio;
966
967         fi_audio = to_fi_audio_source(fi);
968         device_destroy(fi_audio->audio_device->class,
969                         fi_audio->audio_device->devt);
970         kfree(fi_audio->name);
971         kfree(fi_audio->config);
972 }
973
974 static ssize_t audio_source_pcm_show(struct device *dev,
975                 struct device_attribute *attr, char *buf)
976 {
977         struct audio_source_instance *fi_audio = dev_get_drvdata(dev);
978         struct audio_source_config *config = fi_audio->config;
979
980         /* print PCM card and device numbers */
981         return sprintf(buf, "%d %d\n", config->card, config->device);
982 }
983
984 struct device *create_function_device(char *name);
985
986 static struct usb_function_instance *audio_source_alloc_inst(void)
987 {
988         struct audio_source_instance *fi_audio;
989         struct device_attribute **attrs;
990         struct device_attribute *attr;
991         struct device *dev;
992         void *err_ptr;
993         int err = 0;
994
995         fi_audio = kzalloc(sizeof(*fi_audio), GFP_KERNEL);
996         if (!fi_audio)
997                 return ERR_PTR(-ENOMEM);
998
999         fi_audio->func_inst.set_inst_name = audio_source_set_inst_name;
1000         fi_audio->func_inst.free_func_inst = audio_source_free_inst;
1001
1002         fi_audio->config = kzalloc(sizeof(struct audio_source_config),
1003                                                         GFP_KERNEL);
1004         if (!fi_audio->config) {
1005                 err_ptr = ERR_PTR(-ENOMEM);
1006                 goto fail_audio;
1007         }
1008
1009         config_group_init_type_name(&fi_audio->func_inst.group, "",
1010                                                 &audio_source_func_type);
1011         dev = create_function_device("f_audio_source");
1012
1013         if (IS_ERR(dev)) {
1014                 err_ptr = dev;
1015                 goto fail_audio_config;
1016         }
1017
1018         fi_audio->config->card = -1;
1019         fi_audio->config->device = -1;
1020         fi_audio->audio_device = dev;
1021
1022         attrs = audio_source_function_attributes;
1023         if (attrs) {
1024                 while ((attr = *attrs++) && !err)
1025                         err = device_create_file(dev, attr);
1026                 if (err) {
1027                         err_ptr = ERR_PTR(-EINVAL);
1028                         goto fail_device;
1029                 }
1030         }
1031
1032         dev_set_drvdata(dev, fi_audio);
1033         _audio_dev.config = fi_audio->config;
1034
1035         return  &fi_audio->func_inst;
1036
1037 fail_device:
1038         device_destroy(dev->class, dev->devt);
1039 fail_audio_config:
1040         kfree(fi_audio->config);
1041 fail_audio:
1042         kfree(fi_audio);
1043         return err_ptr;
1044
1045 }
1046
1047 static struct usb_function *audio_source_alloc(struct usb_function_instance *fi)
1048 {
1049         return &_audio_dev.func;
1050 }
1051
1052 DECLARE_USB_FUNCTION_INIT(audio_source, audio_source_alloc_inst,
1053                         audio_source_alloc);
1054 MODULE_LICENSE("GPL");