ANDROID: usb: gadget: audio_source: fix comparison of distinct pointer types
[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 = div_s64((ktime_to_ns(now) - ktime_to_ns(audio->start_time)),
381                         1000000);
382         frames = div_s64((msecs * SAMPLE_RATE), 1000);
383
384         /* Readjust our frames_sent if we fall too far behind.
385          * If we get too far behind it is better to drop some frames than
386          * to keep sending data too fast in an attempt to catch up.
387          */
388         if (frames - audio->frames_sent > 10 * FRAMES_PER_MSEC)
389                 audio->frames_sent = frames - FRAMES_PER_MSEC;
390
391         frames -= audio->frames_sent;
392
393         /* We need to send something to keep the pipeline going */
394         if (frames <= 0)
395                 frames = FRAMES_PER_MSEC;
396
397         while (frames > 0) {
398                 req = audio_req_get(audio);
399                 if (!req)
400                         break;
401
402                 length = frames_to_bytes(runtime, frames);
403                 if (length > IN_EP_MAX_PACKET_SIZE)
404                         length = IN_EP_MAX_PACKET_SIZE;
405
406                 if (audio->buffer_pos + length > audio->buffer_end)
407                         length1 = audio->buffer_end - audio->buffer_pos;
408                 else
409                         length1 = length;
410                 memcpy(req->buf, audio->buffer_pos, length1);
411                 if (length1 < length) {
412                         /* Wrap around and copy remaining length
413                          * at beginning of buffer.
414                          */
415                         length2 = length - length1;
416                         memcpy(req->buf + length1, audio->buffer_start,
417                                         length2);
418                         audio->buffer_pos = audio->buffer_start + length2;
419                 } else {
420                         audio->buffer_pos += length1;
421                         if (audio->buffer_pos >= audio->buffer_end)
422                                 audio->buffer_pos = audio->buffer_start;
423                 }
424
425                 req->length = length;
426                 ret = usb_ep_queue(audio->in_ep, req, GFP_ATOMIC);
427                 if (ret < 0) {
428                         pr_err("usb_ep_queue failed ret: %d\n", ret);
429                         audio_req_put(audio, req);
430                         break;
431                 }
432
433                 frames -= bytes_to_frames(runtime, length);
434                 audio->frames_sent += bytes_to_frames(runtime, length);
435         }
436 }
437
438 static void audio_control_complete(struct usb_ep *ep, struct usb_request *req)
439 {
440         /* nothing to do here */
441 }
442
443 static void audio_data_complete(struct usb_ep *ep, struct usb_request *req)
444 {
445         struct audio_dev *audio = req->context;
446
447         pr_debug("audio_data_complete req->status %d req->actual %d\n",
448                 req->status, req->actual);
449
450         audio_req_put(audio, req);
451
452         if (!audio->buffer_start || req->status)
453                 return;
454
455         audio->period_offset += req->actual;
456         if (audio->period_offset >= audio->period) {
457                 snd_pcm_period_elapsed(audio->substream);
458                 audio->period_offset = 0;
459         }
460         audio_send(audio);
461 }
462
463 static int audio_set_endpoint_req(struct usb_function *f,
464                 const struct usb_ctrlrequest *ctrl)
465 {
466         int value = -EOPNOTSUPP;
467         u16 ep = le16_to_cpu(ctrl->wIndex);
468         u16 len = le16_to_cpu(ctrl->wLength);
469         u16 w_value = le16_to_cpu(ctrl->wValue);
470
471         pr_debug("bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
472                         ctrl->bRequest, w_value, len, ep);
473
474         switch (ctrl->bRequest) {
475         case UAC_SET_CUR:
476         case UAC_SET_MIN:
477         case UAC_SET_MAX:
478         case UAC_SET_RES:
479                 value = len;
480                 break;
481         default:
482                 break;
483         }
484
485         return value;
486 }
487
488 static int audio_get_endpoint_req(struct usb_function *f,
489                 const struct usb_ctrlrequest *ctrl)
490 {
491         struct usb_composite_dev *cdev = f->config->cdev;
492         int value = -EOPNOTSUPP;
493         u8 ep = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
494         u16 len = le16_to_cpu(ctrl->wLength);
495         u16 w_value = le16_to_cpu(ctrl->wValue);
496         u8 *buf = cdev->req->buf;
497
498         pr_debug("bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
499                         ctrl->bRequest, w_value, len, ep);
500
501         if (w_value == UAC_EP_CS_ATTR_SAMPLE_RATE << 8) {
502                 switch (ctrl->bRequest) {
503                 case UAC_GET_CUR:
504                 case UAC_GET_MIN:
505                 case UAC_GET_MAX:
506                 case UAC_GET_RES:
507                         /* return our sample rate */
508                         buf[0] = (u8)SAMPLE_RATE;
509                         buf[1] = (u8)(SAMPLE_RATE >> 8);
510                         buf[2] = (u8)(SAMPLE_RATE >> 16);
511                         value = 3;
512                         break;
513                 default:
514                         break;
515                 }
516         }
517
518         return value;
519 }
520
521 static int
522 audio_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
523 {
524         struct usb_composite_dev *cdev = f->config->cdev;
525         struct usb_request *req = cdev->req;
526         int value = -EOPNOTSUPP;
527         u16 w_index = le16_to_cpu(ctrl->wIndex);
528         u16 w_value = le16_to_cpu(ctrl->wValue);
529         u16 w_length = le16_to_cpu(ctrl->wLength);
530
531         /* composite driver infrastructure handles everything; interface
532          * activation uses set_alt().
533          */
534         switch (ctrl->bRequestType) {
535         case USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
536                 value = audio_set_endpoint_req(f, ctrl);
537                 break;
538
539         case USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
540                 value = audio_get_endpoint_req(f, ctrl);
541                 break;
542         }
543
544         /* respond with data transfer or status phase? */
545         if (value >= 0) {
546                 pr_debug("audio req%02x.%02x v%04x i%04x l%d\n",
547                         ctrl->bRequestType, ctrl->bRequest,
548                         w_value, w_index, w_length);
549                 req->zero = 0;
550                 req->length = value;
551                 req->complete = audio_control_complete;
552                 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
553                 if (value < 0)
554                         pr_err("audio response on err %d\n", value);
555         }
556
557         /* device either stalls (value < 0) or reports success */
558         return value;
559 }
560
561 static int audio_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
562 {
563         struct audio_dev *audio = func_to_audio(f);
564         struct usb_composite_dev *cdev = f->config->cdev;
565         int ret;
566
567         pr_debug("audio_set_alt intf %d, alt %d\n", intf, alt);
568
569         ret = config_ep_by_speed(cdev->gadget, f, audio->in_ep);
570         if (ret)
571                 return ret;
572
573         usb_ep_enable(audio->in_ep);
574         return 0;
575 }
576
577 static void audio_disable(struct usb_function *f)
578 {
579         struct audio_dev        *audio = func_to_audio(f);
580
581         pr_debug("audio_disable\n");
582         usb_ep_disable(audio->in_ep);
583 }
584
585 static void audio_free_func(struct usb_function *f)
586 {
587         /* no-op */
588 }
589
590 /*-------------------------------------------------------------------------*/
591
592 static void audio_build_desc(struct audio_dev *audio)
593 {
594         u8 *sam_freq;
595         int rate;
596
597         /* Set channel numbers */
598         input_terminal_desc.bNrChannels = 2;
599         as_type_i_desc.bNrChannels = 2;
600
601         /* Set sample rates */
602         rate = SAMPLE_RATE;
603         sam_freq = as_type_i_desc.tSamFreq[0];
604         memcpy(sam_freq, &rate, 3);
605 }
606
607
608 static int snd_card_setup(struct usb_configuration *c,
609         struct audio_source_config *config);
610 static struct audio_source_instance *to_fi_audio_source(
611         const struct usb_function_instance *fi);
612
613
614 /* audio function driver setup/binding */
615 static int
616 audio_bind(struct usb_configuration *c, struct usb_function *f)
617 {
618         struct usb_composite_dev *cdev = c->cdev;
619         struct audio_dev *audio = func_to_audio(f);
620         int status;
621         struct usb_ep *ep;
622         struct usb_request *req;
623         int i;
624         int err;
625
626         if (IS_ENABLED(CONFIG_USB_CONFIGFS)) {
627                 struct audio_source_instance *fi_audio =
628                                 to_fi_audio_source(f->fi);
629                 struct audio_source_config *config =
630                                 fi_audio->config;
631
632                 err = snd_card_setup(c, config);
633                 if (err)
634                         return err;
635         }
636
637         audio_build_desc(audio);
638
639         /* allocate instance-specific interface IDs, and patch descriptors */
640         status = usb_interface_id(c, f);
641         if (status < 0)
642                 goto fail;
643         ac_interface_desc.bInterfaceNumber = status;
644
645         /* AUDIO_AC_INTERFACE */
646         ac_header_desc.baInterfaceNr[0] = status;
647
648         status = usb_interface_id(c, f);
649         if (status < 0)
650                 goto fail;
651         as_interface_alt_0_desc.bInterfaceNumber = status;
652         as_interface_alt_1_desc.bInterfaceNumber = status;
653
654         /* AUDIO_AS_INTERFACE */
655         ac_header_desc.baInterfaceNr[1] = status;
656
657         status = -ENODEV;
658
659         /* allocate our endpoint */
660         ep = usb_ep_autoconfig(cdev->gadget, &fs_as_in_ep_desc);
661         if (!ep)
662                 goto fail;
663         audio->in_ep = ep;
664         ep->driver_data = audio; /* claim */
665
666         if (gadget_is_dualspeed(c->cdev->gadget))
667                 hs_as_in_ep_desc.bEndpointAddress =
668                         fs_as_in_ep_desc.bEndpointAddress;
669
670         f->fs_descriptors = fs_audio_desc;
671         f->hs_descriptors = hs_audio_desc;
672
673         for (i = 0, status = 0; i < IN_EP_REQ_COUNT && status == 0; i++) {
674                 req = audio_request_new(ep, IN_EP_MAX_PACKET_SIZE);
675                 if (req) {
676                         req->context = audio;
677                         req->complete = audio_data_complete;
678                         audio_req_put(audio, req);
679                 } else
680                         status = -ENOMEM;
681         }
682
683 fail:
684         return status;
685 }
686
687 static void
688 audio_unbind(struct usb_configuration *c, struct usb_function *f)
689 {
690         struct audio_dev *audio = func_to_audio(f);
691         struct usb_request *req;
692
693         while ((req = audio_req_get(audio)))
694                 audio_request_free(req, audio->in_ep);
695
696         snd_card_free_when_closed(audio->card);
697         audio->card = NULL;
698         audio->pcm = NULL;
699         audio->substream = NULL;
700         audio->in_ep = NULL;
701
702         if (IS_ENABLED(CONFIG_USB_CONFIGFS)) {
703                 struct audio_source_instance *fi_audio =
704                                 to_fi_audio_source(f->fi);
705                 struct audio_source_config *config =
706                                 fi_audio->config;
707
708                 config->card = -1;
709                 config->device = -1;
710         }
711 }
712
713 static void audio_pcm_playback_start(struct audio_dev *audio)
714 {
715         audio->start_time = ktime_get();
716         audio->frames_sent = 0;
717         audio_send(audio);
718 }
719
720 static void audio_pcm_playback_stop(struct audio_dev *audio)
721 {
722         unsigned long flags;
723
724         spin_lock_irqsave(&audio->lock, flags);
725         audio->buffer_start = 0;
726         audio->buffer_end = 0;
727         audio->buffer_pos = 0;
728         spin_unlock_irqrestore(&audio->lock, flags);
729 }
730
731 static int audio_pcm_open(struct snd_pcm_substream *substream)
732 {
733         struct snd_pcm_runtime *runtime = substream->runtime;
734         struct audio_dev *audio = substream->private_data;
735
736         runtime->private_data = audio;
737         runtime->hw = audio_hw_info;
738         snd_pcm_limit_hw_rates(runtime);
739         runtime->hw.channels_max = 2;
740
741         audio->substream = substream;
742         return 0;
743 }
744
745 static int audio_pcm_close(struct snd_pcm_substream *substream)
746 {
747         struct audio_dev *audio = substream->private_data;
748         unsigned long flags;
749
750         spin_lock_irqsave(&audio->lock, flags);
751         audio->substream = NULL;
752         spin_unlock_irqrestore(&audio->lock, flags);
753
754         return 0;
755 }
756
757 static int audio_pcm_hw_params(struct snd_pcm_substream *substream,
758                                 struct snd_pcm_hw_params *params)
759 {
760         unsigned int channels = params_channels(params);
761         unsigned int rate = params_rate(params);
762
763         if (rate != SAMPLE_RATE)
764                 return -EINVAL;
765         if (channels != 2)
766                 return -EINVAL;
767
768         return snd_pcm_lib_alloc_vmalloc_buffer(substream,
769                 params_buffer_bytes(params));
770 }
771
772 static int audio_pcm_hw_free(struct snd_pcm_substream *substream)
773 {
774         return snd_pcm_lib_free_vmalloc_buffer(substream);
775 }
776
777 static int audio_pcm_prepare(struct snd_pcm_substream *substream)
778 {
779         struct snd_pcm_runtime *runtime = substream->runtime;
780         struct audio_dev *audio = runtime->private_data;
781
782         audio->period = snd_pcm_lib_period_bytes(substream);
783         audio->period_offset = 0;
784         audio->buffer_start = runtime->dma_area;
785         audio->buffer_end = audio->buffer_start
786                 + snd_pcm_lib_buffer_bytes(substream);
787         audio->buffer_pos = audio->buffer_start;
788
789         return 0;
790 }
791
792 static snd_pcm_uframes_t audio_pcm_pointer(struct snd_pcm_substream *substream)
793 {
794         struct snd_pcm_runtime *runtime = substream->runtime;
795         struct audio_dev *audio = runtime->private_data;
796         ssize_t bytes = audio->buffer_pos - audio->buffer_start;
797
798         /* return offset of next frame to fill in our buffer */
799         return bytes_to_frames(runtime, bytes);
800 }
801
802 static int audio_pcm_playback_trigger(struct snd_pcm_substream *substream,
803                                         int cmd)
804 {
805         struct audio_dev *audio = substream->runtime->private_data;
806         int ret = 0;
807
808         switch (cmd) {
809         case SNDRV_PCM_TRIGGER_START:
810         case SNDRV_PCM_TRIGGER_RESUME:
811                 audio_pcm_playback_start(audio);
812                 break;
813
814         case SNDRV_PCM_TRIGGER_STOP:
815         case SNDRV_PCM_TRIGGER_SUSPEND:
816                 audio_pcm_playback_stop(audio);
817                 break;
818
819         default:
820                 ret = -EINVAL;
821         }
822
823         return ret;
824 }
825
826 static struct audio_dev _audio_dev = {
827         .func = {
828                 .name = "audio_source",
829                 .bind = audio_bind,
830                 .unbind = audio_unbind,
831                 .set_alt = audio_set_alt,
832                 .setup = audio_setup,
833                 .disable = audio_disable,
834                 .free_func = audio_free_func,
835         },
836         .lock = __SPIN_LOCK_UNLOCKED(_audio_dev.lock),
837         .idle_reqs = LIST_HEAD_INIT(_audio_dev.idle_reqs),
838 };
839
840 static struct snd_pcm_ops audio_playback_ops = {
841         .open           = audio_pcm_open,
842         .close          = audio_pcm_close,
843         .ioctl          = snd_pcm_lib_ioctl,
844         .hw_params      = audio_pcm_hw_params,
845         .hw_free        = audio_pcm_hw_free,
846         .prepare        = audio_pcm_prepare,
847         .trigger        = audio_pcm_playback_trigger,
848         .pointer        = audio_pcm_pointer,
849 };
850
851 int audio_source_bind_config(struct usb_configuration *c,
852                 struct audio_source_config *config)
853 {
854         struct audio_dev *audio;
855         int err;
856
857         config->card = -1;
858         config->device = -1;
859
860         audio = &_audio_dev;
861
862         err = snd_card_setup(c, config);
863         if (err)
864                 return err;
865
866         err = usb_add_function(c, &audio->func);
867         if (err)
868                 goto add_fail;
869
870         return 0;
871
872 add_fail:
873         snd_card_free(audio->card);
874         return err;
875 }
876
877 static int snd_card_setup(struct usb_configuration *c,
878                 struct audio_source_config *config)
879 {
880         struct audio_dev *audio;
881         struct snd_card *card;
882         struct snd_pcm *pcm;
883         int err;
884
885         audio = &_audio_dev;
886
887         err = snd_card_new(&c->cdev->gadget->dev,
888                         SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1,
889                         THIS_MODULE, 0, &card);
890         if (err)
891                 return err;
892
893         err = snd_pcm_new(card, "USB audio source", 0, 1, 0, &pcm);
894         if (err)
895                 goto pcm_fail;
896
897         pcm->private_data = audio;
898         pcm->info_flags = 0;
899         audio->pcm = pcm;
900
901         strlcpy(pcm->name, "USB gadget audio", sizeof(pcm->name));
902
903         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &audio_playback_ops);
904         snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
905                                 NULL, 0, 64 * 1024);
906
907         strlcpy(card->driver, "audio_source", sizeof(card->driver));
908         strlcpy(card->shortname, card->driver, sizeof(card->shortname));
909         strlcpy(card->longname, "USB accessory audio source",
910                 sizeof(card->longname));
911
912         err = snd_card_register(card);
913         if (err)
914                 goto register_fail;
915
916         config->card = pcm->card->number;
917         config->device = pcm->device;
918         audio->card = card;
919         return 0;
920
921 register_fail:
922 pcm_fail:
923         snd_card_free(audio->card);
924         return err;
925 }
926
927 static struct audio_source_instance *to_audio_source_instance(
928                                         struct config_item *item)
929 {
930         return container_of(to_config_group(item), struct audio_source_instance,
931                 func_inst.group);
932 }
933
934 static struct audio_source_instance *to_fi_audio_source(
935                                         const struct usb_function_instance *fi)
936 {
937         return container_of(fi, struct audio_source_instance, func_inst);
938 }
939
940 static void audio_source_attr_release(struct config_item *item)
941 {
942         struct audio_source_instance *fi_audio = to_audio_source_instance(item);
943
944         usb_put_function_instance(&fi_audio->func_inst);
945 }
946
947 static int audio_source_set_inst_name(struct usb_function_instance *fi,
948                                         const char *name)
949 {
950         struct audio_source_instance *fi_audio;
951         char *ptr;
952         int name_len;
953
954         name_len = strlen(name) + 1;
955         if (name_len > MAX_INST_NAME_LEN)
956                 return -ENAMETOOLONG;
957
958         ptr = kstrndup(name, name_len, GFP_KERNEL);
959         if (!ptr)
960                 return -ENOMEM;
961
962         fi_audio = to_fi_audio_source(fi);
963         fi_audio->name = ptr;
964
965         return 0;
966 }
967
968 static void audio_source_free_inst(struct usb_function_instance *fi)
969 {
970         struct audio_source_instance *fi_audio;
971
972         fi_audio = to_fi_audio_source(fi);
973         device_destroy(fi_audio->audio_device->class,
974                         fi_audio->audio_device->devt);
975         kfree(fi_audio->name);
976         kfree(fi_audio->config);
977 }
978
979 static ssize_t audio_source_pcm_show(struct device *dev,
980                 struct device_attribute *attr, char *buf)
981 {
982         struct audio_source_instance *fi_audio = dev_get_drvdata(dev);
983         struct audio_source_config *config = fi_audio->config;
984
985         /* print PCM card and device numbers */
986         return sprintf(buf, "%d %d\n", config->card, config->device);
987 }
988
989 struct device *create_function_device(char *name);
990
991 static struct usb_function_instance *audio_source_alloc_inst(void)
992 {
993         struct audio_source_instance *fi_audio;
994         struct device_attribute **attrs;
995         struct device_attribute *attr;
996         struct device *dev;
997         void *err_ptr;
998         int err = 0;
999
1000         fi_audio = kzalloc(sizeof(*fi_audio), GFP_KERNEL);
1001         if (!fi_audio)
1002                 return ERR_PTR(-ENOMEM);
1003
1004         fi_audio->func_inst.set_inst_name = audio_source_set_inst_name;
1005         fi_audio->func_inst.free_func_inst = audio_source_free_inst;
1006
1007         fi_audio->config = kzalloc(sizeof(struct audio_source_config),
1008                                                         GFP_KERNEL);
1009         if (!fi_audio->config) {
1010                 err_ptr = ERR_PTR(-ENOMEM);
1011                 goto fail_audio;
1012         }
1013
1014         config_group_init_type_name(&fi_audio->func_inst.group, "",
1015                                                 &audio_source_func_type);
1016         dev = create_function_device("f_audio_source");
1017
1018         if (IS_ERR(dev)) {
1019                 err_ptr = dev;
1020                 goto fail_audio_config;
1021         }
1022
1023         fi_audio->config->card = -1;
1024         fi_audio->config->device = -1;
1025         fi_audio->audio_device = dev;
1026
1027         attrs = audio_source_function_attributes;
1028         if (attrs) {
1029                 while ((attr = *attrs++) && !err)
1030                         err = device_create_file(dev, attr);
1031                 if (err) {
1032                         err_ptr = ERR_PTR(-EINVAL);
1033                         goto fail_device;
1034                 }
1035         }
1036
1037         dev_set_drvdata(dev, fi_audio);
1038         _audio_dev.config = fi_audio->config;
1039
1040         return  &fi_audio->func_inst;
1041
1042 fail_device:
1043         device_destroy(dev->class, dev->devt);
1044 fail_audio_config:
1045         kfree(fi_audio->config);
1046 fail_audio:
1047         kfree(fi_audio);
1048         return err_ptr;
1049
1050 }
1051
1052 static struct usb_function *audio_source_alloc(struct usb_function_instance *fi)
1053 {
1054         return &_audio_dev.func;
1055 }
1056
1057 DECLARE_USB_FUNCTION_INIT(audio_source, audio_source_alloc_inst,
1058                         audio_source_alloc);
1059 MODULE_LICENSE("GPL");