1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * f_audio.c -- USB Audio class function driver
4   *
5  * Copyright (C) 2008 Bryan Wu <cooloney@kernel.org>
6  * Copyright (C) 2008 Analog Devices, Inc
7  *
8  * Enter bugs at http://blackfin.uclinux.org/
9  */
10 
11 #include <linux/slab.h>
12 #include <linux/kernel.h>
13 #include <linux/module.h>
14 #include <linux/device.h>
15 #include <linux/atomic.h>
16 
17 #include "u_uac1_legacy.h"
18 
19 static int generic_set_cmd(struct usb_audio_control *con, u8 cmd, int value);
20 static int generic_get_cmd(struct usb_audio_control *con, u8 cmd);
21 
22 /*
23  * DESCRIPTORS ... most are static, but strings and full
24  * configuration descriptors are built on demand.
25  */
26 
27 /*
28  * We have two interfaces- AudioControl and AudioStreaming
29  * TODO: only supcard playback currently
30  */
31 #define F_AUDIO_AC_INTERFACE	0
32 #define F_AUDIO_AS_INTERFACE	1
33 #define F_AUDIO_NUM_INTERFACES	1
34 
35 /* B.3.1  Standard AC Interface Descriptor */
36 static struct usb_interface_descriptor ac_interface_desc = {
37 	.bLength =		USB_DT_INTERFACE_SIZE,
38 	.bDescriptorType =	USB_DT_INTERFACE,
39 	.bNumEndpoints =	0,
40 	.bInterfaceClass =	USB_CLASS_AUDIO,
41 	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOCONTROL,
42 };
43 
44 /*
45  * The number of AudioStreaming and MIDIStreaming interfaces
46  * in the Audio Interface Collection
47  */
48 DECLARE_UAC_AC_HEADER_DESCRIPTOR(1);
49 
50 #define UAC_DT_AC_HEADER_LENGTH	UAC_DT_AC_HEADER_SIZE(F_AUDIO_NUM_INTERFACES)
51 /* 1 input terminal, 1 output terminal and 1 feature unit */
52 #define UAC_DT_TOTAL_LENGTH (UAC_DT_AC_HEADER_LENGTH + UAC_DT_INPUT_TERMINAL_SIZE \
53 	+ UAC_DT_OUTPUT_TERMINAL_SIZE + UAC_DT_FEATURE_UNIT_SIZE(0))
54 /* B.3.2  Class-Specific AC Interface Descriptor */
55 static struct uac1_ac_header_descriptor_1 ac_header_desc = {
56 	.bLength =		UAC_DT_AC_HEADER_LENGTH,
57 	.bDescriptorType =	USB_DT_CS_INTERFACE,
58 	.bDescriptorSubtype =	UAC_HEADER,
59 	.bcdADC =		__constant_cpu_to_le16(0x0100),
60 	.wTotalLength =		__constant_cpu_to_le16(UAC_DT_TOTAL_LENGTH),
61 	.bInCollection =	F_AUDIO_NUM_INTERFACES,
62 	.baInterfaceNr = {
63 	/* Interface number of the first AudioStream interface */
64 		[0] =		1,
65 	}
66 };
67 
68 #define INPUT_TERMINAL_ID	1
69 static struct uac_input_terminal_descriptor input_terminal_desc = {
70 	.bLength =		UAC_DT_INPUT_TERMINAL_SIZE,
71 	.bDescriptorType =	USB_DT_CS_INTERFACE,
72 	.bDescriptorSubtype =	UAC_INPUT_TERMINAL,
73 	.bTerminalID =		INPUT_TERMINAL_ID,
74 	.wTerminalType =	UAC_TERMINAL_STREAMING,
75 	.bAssocTerminal =	0,
76 	.wChannelConfig =	0x3,
77 };
78 
79 DECLARE_UAC_FEATURE_UNIT_DESCRIPTOR(0);
80 
81 #define FEATURE_UNIT_ID		2
82 static struct uac_feature_unit_descriptor_0 feature_unit_desc = {
83 	.bLength		= UAC_DT_FEATURE_UNIT_SIZE(0),
84 	.bDescriptorType	= USB_DT_CS_INTERFACE,
85 	.bDescriptorSubtype	= UAC_FEATURE_UNIT,
86 	.bUnitID		= FEATURE_UNIT_ID,
87 	.bSourceID		= INPUT_TERMINAL_ID,
88 	.bControlSize		= 2,
89 	.bmaControls[0]		= (UAC_FU_MUTE | UAC_FU_VOLUME),
90 };
91 
92 static struct usb_audio_control mute_control = {
93 	.list = LIST_HEAD_INIT(mute_control.list),
94 	.name = "Mute Control",
95 	.type = UAC_FU_MUTE,
96 	/* Todo: add real Mute control code */
97 	.set = generic_set_cmd,
98 	.get = generic_get_cmd,
99 };
100 
101 static struct usb_audio_control volume_control = {
102 	.list = LIST_HEAD_INIT(volume_control.list),
103 	.name = "Volume Control",
104 	.type = UAC_FU_VOLUME,
105 	/* Todo: add real Volume control code */
106 	.set = generic_set_cmd,
107 	.get = generic_get_cmd,
108 };
109 
110 static struct usb_audio_control_selector feature_unit = {
111 	.list = LIST_HEAD_INIT(feature_unit.list),
112 	.id = FEATURE_UNIT_ID,
113 	.name = "Mute & Volume Control",
114 	.type = UAC_FEATURE_UNIT,
115 	.desc = (struct usb_descriptor_header *)&feature_unit_desc,
116 };
117 
118 #define OUTPUT_TERMINAL_ID	3
119 static struct uac1_output_terminal_descriptor output_terminal_desc = {
120 	.bLength		= UAC_DT_OUTPUT_TERMINAL_SIZE,
121 	.bDescriptorType	= USB_DT_CS_INTERFACE,
122 	.bDescriptorSubtype	= UAC_OUTPUT_TERMINAL,
123 	.bTerminalID		= OUTPUT_TERMINAL_ID,
124 	.wTerminalType		= UAC_OUTPUT_TERMINAL_SPEAKER,
125 	.bAssocTerminal		= FEATURE_UNIT_ID,
126 	.bSourceID		= FEATURE_UNIT_ID,
127 };
128 
129 /* B.4.1  Standard AS Interface Descriptor */
130 static struct usb_interface_descriptor as_interface_alt_0_desc = {
131 	.bLength =		USB_DT_INTERFACE_SIZE,
132 	.bDescriptorType =	USB_DT_INTERFACE,
133 	.bAlternateSetting =	0,
134 	.bNumEndpoints =	0,
135 	.bInterfaceClass =	USB_CLASS_AUDIO,
136 	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOSTREAMING,
137 };
138 
139 static struct usb_interface_descriptor as_interface_alt_1_desc = {
140 	.bLength =		USB_DT_INTERFACE_SIZE,
141 	.bDescriptorType =	USB_DT_INTERFACE,
142 	.bAlternateSetting =	1,
143 	.bNumEndpoints =	1,
144 	.bInterfaceClass =	USB_CLASS_AUDIO,
145 	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOSTREAMING,
146 };
147 
148 /* B.4.2  Class-Specific AS Interface Descriptor */
149 static struct uac1_as_header_descriptor as_header_desc = {
150 	.bLength =		UAC_DT_AS_HEADER_SIZE,
151 	.bDescriptorType =	USB_DT_CS_INTERFACE,
152 	.bDescriptorSubtype =	UAC_AS_GENERAL,
153 	.bTerminalLink =	INPUT_TERMINAL_ID,
154 	.bDelay =		1,
155 	.wFormatTag =		UAC_FORMAT_TYPE_I_PCM,
156 };
157 
158 DECLARE_UAC_FORMAT_TYPE_I_DISCRETE_DESC(1);
159 
160 static struct uac_format_type_i_discrete_descriptor_1 as_type_i_desc = {
161 	.bLength =		UAC_FORMAT_TYPE_I_DISCRETE_DESC_SIZE(1),
162 	.bDescriptorType =	USB_DT_CS_INTERFACE,
163 	.bDescriptorSubtype =	UAC_FORMAT_TYPE,
164 	.bFormatType =		UAC_FORMAT_TYPE_I,
165 	.bSubframeSize =	2,
166 	.bBitResolution =	16,
167 	.bSamFreqType =		1,
168 };
169 
170 /* Standard ISO OUT Endpoint Descriptor */
171 static struct usb_endpoint_descriptor as_out_ep_desc  = {
172 	.bLength =		USB_DT_ENDPOINT_AUDIO_SIZE,
173 	.bDescriptorType =	USB_DT_ENDPOINT,
174 	.bEndpointAddress =	USB_DIR_OUT,
175 	.bmAttributes =		USB_ENDPOINT_SYNC_ADAPTIVE
176 				| USB_ENDPOINT_XFER_ISOC,
177 	.wMaxPacketSize	=	cpu_to_le16(UAC1_OUT_EP_MAX_PACKET_SIZE),
178 	.bInterval =		4,
179 };
180 
181 /* Class-specific AS ISO OUT Endpoint Descriptor */
182 static struct uac_iso_endpoint_descriptor as_iso_out_desc = {
183 	.bLength =		UAC_ISO_ENDPOINT_DESC_SIZE,
184 	.bDescriptorType =	USB_DT_CS_ENDPOINT,
185 	.bDescriptorSubtype =	UAC_EP_GENERAL,
186 	.bmAttributes = 	1,
187 	.bLockDelayUnits =	1,
188 	.wLockDelay =		__constant_cpu_to_le16(1),
189 };
190 
191 static struct usb_descriptor_header *f_audio_desc[] = {
192 	(struct usb_descriptor_header *)&ac_interface_desc,
193 	(struct usb_descriptor_header *)&ac_header_desc,
194 
195 	(struct usb_descriptor_header *)&input_terminal_desc,
196 	(struct usb_descriptor_header *)&output_terminal_desc,
197 	(struct usb_descriptor_header *)&feature_unit_desc,
198 
199 	(struct usb_descriptor_header *)&as_interface_alt_0_desc,
200 	(struct usb_descriptor_header *)&as_interface_alt_1_desc,
201 	(struct usb_descriptor_header *)&as_header_desc,
202 
203 	(struct usb_descriptor_header *)&as_type_i_desc,
204 
205 	(struct usb_descriptor_header *)&as_out_ep_desc,
206 	(struct usb_descriptor_header *)&as_iso_out_desc,
207 	NULL,
208 };
209 
210 enum {
211 	STR_AC_IF,
212 	STR_INPUT_TERMINAL,
213 	STR_INPUT_TERMINAL_CH_NAMES,
214 	STR_FEAT_DESC_0,
215 	STR_OUTPUT_TERMINAL,
216 	STR_AS_IF_ALT0,
217 	STR_AS_IF_ALT1,
218 };
219 
220 static struct usb_string strings_uac1[] = {
221 	[STR_AC_IF].s = "AC Interface",
222 	[STR_INPUT_TERMINAL].s = "Input terminal",
223 	[STR_INPUT_TERMINAL_CH_NAMES].s = "Channels",
224 	[STR_FEAT_DESC_0].s = "Volume control & mute",
225 	[STR_OUTPUT_TERMINAL].s = "Output terminal",
226 	[STR_AS_IF_ALT0].s = "AS Interface",
227 	[STR_AS_IF_ALT1].s = "AS Interface",
228 	{ },
229 };
230 
231 static struct usb_gadget_strings str_uac1 = {
232 	.language = 0x0409,	/* en-us */
233 	.strings = strings_uac1,
234 };
235 
236 static struct usb_gadget_strings *uac1_strings[] = {
237 	&str_uac1,
238 	NULL,
239 };
240 
241 /*
242  * This function is an ALSA sound card following USB Audio Class Spec 1.0.
243  */
244 
245 /*-------------------------------------------------------------------------*/
246 struct f_audio_buf {
247 	u8 *buf;
248 	int actual;
249 	struct list_head list;
250 };
251 
252 static struct f_audio_buf *f_audio_buffer_alloc(int buf_size)
253 {
254 	struct f_audio_buf *copy_buf;
255 
256 	copy_buf = kzalloc(sizeof *copy_buf, GFP_ATOMIC);
257 	if (!copy_buf)
258 		return ERR_PTR(-ENOMEM);
259 
260 	copy_buf->buf = kzalloc(buf_size, GFP_ATOMIC);
261 	if (!copy_buf->buf) {
262 		kfree(copy_buf);
263 		return ERR_PTR(-ENOMEM);
264 	}
265 
266 	return copy_buf;
267 }
268 
269 static void f_audio_buffer_free(struct f_audio_buf *audio_buf)
270 {
271 	kfree(audio_buf->buf);
272 	kfree(audio_buf);
273 }
274 /*-------------------------------------------------------------------------*/
275 
276 struct f_audio {
277 	struct gaudio			card;
278 
279 	u8 ac_intf, ac_alt;
280 	u8 as_intf, as_alt;
281 
282 	/* endpoints handle full and/or high speeds */
283 	struct usb_ep			*out_ep;
284 
285 	spinlock_t			lock;
286 	struct f_audio_buf *copy_buf;
287 	struct work_struct playback_work;
288 	struct list_head play_queue;
289 
290 	/* Control Set command */
291 	struct list_head cs;
292 	u8 set_cmd;
293 	struct usb_audio_control *set_con;
294 };
295 
296 static inline struct f_audio *func_to_audio(struct usb_function *f)
297 {
298 	return container_of(f, struct f_audio, card.func);
299 }
300 
301 /*-------------------------------------------------------------------------*/
302 
303 static void f_audio_playback_work(struct work_struct *data)
304 {
305 	struct f_audio *audio = container_of(data, struct f_audio,
306 					playback_work);
307 	struct f_audio_buf *play_buf;
308 
309 	spin_lock_irq(&audio->lock);
310 	if (list_empty(&audio->play_queue)) {
311 		spin_unlock_irq(&audio->lock);
312 		return;
313 	}
314 	play_buf = list_first_entry(&audio->play_queue,
315 			struct f_audio_buf, list);
316 	list_del(&play_buf->list);
317 	spin_unlock_irq(&audio->lock);
318 
319 	u_audio_playback(&audio->card, play_buf->buf, play_buf->actual);
320 	f_audio_buffer_free(play_buf);
321 }
322 
323 static int f_audio_out_ep_complete(struct usb_ep *ep, struct usb_request *req)
324 {
325 	struct f_audio *audio = req->context;
326 	struct usb_composite_dev *cdev = audio->card.func.config->cdev;
327 	struct f_audio_buf *copy_buf = audio->copy_buf;
328 	struct f_uac1_legacy_opts *opts;
329 	int audio_buf_size;
330 	int err;
331 
332 	opts = container_of(audio->card.func.fi, struct f_uac1_legacy_opts,
333 			    func_inst);
334 	audio_buf_size = opts->audio_buf_size;
335 
336 	if (!copy_buf)
337 		return -EINVAL;
338 
339 	/* Copy buffer is full, add it to the play_queue */
340 	if (audio_buf_size - copy_buf->actual < req->actual) {
341 		list_add_tail(&copy_buf->list, &audio->play_queue);
342 		schedule_work(&audio->playback_work);
343 		copy_buf = f_audio_buffer_alloc(audio_buf_size);
344 		if (IS_ERR(copy_buf))
345 			return -ENOMEM;
346 	}
347 
348 	memcpy(copy_buf->buf + copy_buf->actual, req->buf, req->actual);
349 	copy_buf->actual += req->actual;
350 	audio->copy_buf = copy_buf;
351 
352 	err = usb_ep_queue(ep, req, GFP_ATOMIC);
353 	if (err)
354 		ERROR(cdev, "%s queue req: %d\n", ep->name, err);
355 
356 	return 0;
357 
358 }
359 
360 static void f_audio_complete(struct usb_ep *ep, struct usb_request *req)
361 {
362 	struct f_audio *audio = req->context;
363 	int status = req->status;
364 	u32 data = 0;
365 	struct usb_ep *out_ep = audio->out_ep;
366 
367 	switch (status) {
368 
369 	case 0:				/* normal completion? */
370 		if (ep == out_ep)
371 			f_audio_out_ep_complete(ep, req);
372 		else if (audio->set_con) {
373 			memcpy(&data, req->buf, req->length);
374 			audio->set_con->set(audio->set_con, audio->set_cmd,
375 					le16_to_cpu(data));
376 			audio->set_con = NULL;
377 		}
378 		break;
379 	default:
380 		break;
381 	}
382 }
383 
384 static int audio_set_intf_req(struct usb_function *f,
385 		const struct usb_ctrlrequest *ctrl)
386 {
387 	struct f_audio		*audio = func_to_audio(f);
388 	struct usb_composite_dev *cdev = f->config->cdev;
389 	struct usb_request	*req = cdev->req;
390 	u8			id = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
391 	u16			len = le16_to_cpu(ctrl->wLength);
392 	u16			w_value = le16_to_cpu(ctrl->wValue);
393 	u8			con_sel = (w_value >> 8) & 0xFF;
394 	u8			cmd = (ctrl->bRequest & 0x0F);
395 	struct usb_audio_control_selector *cs;
396 	struct usb_audio_control *con;
397 
398 	DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, entity %d\n",
399 			ctrl->bRequest, w_value, len, id);
400 
401 	list_for_each_entry(cs, &audio->cs, list) {
402 		if (cs->id == id) {
403 			list_for_each_entry(con, &cs->control, list) {
404 				if (con->type == con_sel) {
405 					audio->set_con = con;
406 					break;
407 				}
408 			}
409 			break;
410 		}
411 	}
412 
413 	audio->set_cmd = cmd;
414 	req->context = audio;
415 	req->complete = f_audio_complete;
416 
417 	return len;
418 }
419 
420 static int audio_get_intf_req(struct usb_function *f,
421 		const struct usb_ctrlrequest *ctrl)
422 {
423 	struct f_audio		*audio = func_to_audio(f);
424 	struct usb_composite_dev *cdev = f->config->cdev;
425 	struct usb_request	*req = cdev->req;
426 	int			value = -EOPNOTSUPP;
427 	u8			id = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
428 	u16			len = le16_to_cpu(ctrl->wLength);
429 	u16			w_value = le16_to_cpu(ctrl->wValue);
430 	u8			con_sel = (w_value >> 8) & 0xFF;
431 	u8			cmd = (ctrl->bRequest & 0x0F);
432 	struct usb_audio_control_selector *cs;
433 	struct usb_audio_control *con;
434 
435 	DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, entity %d\n",
436 			ctrl->bRequest, w_value, len, id);
437 
438 	list_for_each_entry(cs, &audio->cs, list) {
439 		if (cs->id == id) {
440 			list_for_each_entry(con, &cs->control, list) {
441 				if (con->type == con_sel && con->get) {
442 					value = con->get(con, cmd);
443 					break;
444 				}
445 			}
446 			break;
447 		}
448 	}
449 
450 	req->context = audio;
451 	req->complete = f_audio_complete;
452 	len = min_t(size_t, sizeof(value), len);
453 	memcpy(req->buf, &value, len);
454 
455 	return len;
456 }
457 
458 static int audio_set_endpoint_req(struct usb_function *f,
459 		const struct usb_ctrlrequest *ctrl)
460 {
461 	struct usb_composite_dev *cdev = f->config->cdev;
462 	int			value = -EOPNOTSUPP;
463 	u16			ep = le16_to_cpu(ctrl->wIndex);
464 	u16			len = le16_to_cpu(ctrl->wLength);
465 	u16			w_value = le16_to_cpu(ctrl->wValue);
466 
467 	DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
468 			ctrl->bRequest, w_value, len, ep);
469 
470 	switch (ctrl->bRequest) {
471 	case UAC_SET_CUR:
472 		value = len;
473 		break;
474 
475 	case UAC_SET_MIN:
476 		break;
477 
478 	case UAC_SET_MAX:
479 		break;
480 
481 	case UAC_SET_RES:
482 		break;
483 
484 	case UAC_SET_MEM:
485 		break;
486 
487 	default:
488 		break;
489 	}
490 
491 	return value;
492 }
493 
494 static int audio_get_endpoint_req(struct usb_function *f,
495 		const struct usb_ctrlrequest *ctrl)
496 {
497 	struct usb_composite_dev *cdev = f->config->cdev;
498 	int value = -EOPNOTSUPP;
499 	u8 ep = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
500 	u16 len = le16_to_cpu(ctrl->wLength);
501 	u16 w_value = le16_to_cpu(ctrl->wValue);
502 
503 	DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
504 			ctrl->bRequest, w_value, len, ep);
505 
506 	switch (ctrl->bRequest) {
507 	case UAC_GET_CUR:
508 	case UAC_GET_MIN:
509 	case UAC_GET_MAX:
510 	case UAC_GET_RES:
511 		value = len;
512 		break;
513 	case UAC_GET_MEM:
514 		break;
515 	default:
516 		break;
517 	}
518 
519 	return value;
520 }
521 
522 static int
523 f_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_INTERFACE:
537 		value = audio_set_intf_req(f, ctrl);
538 		break;
539 
540 	case USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE:
541 		value = audio_get_intf_req(f, ctrl);
542 		break;
543 
544 	case USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
545 		value = audio_set_endpoint_req(f, ctrl);
546 		break;
547 
548 	case USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
549 		value = audio_get_endpoint_req(f, ctrl);
550 		break;
551 
552 	default:
553 		ERROR(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
554 			ctrl->bRequestType, ctrl->bRequest,
555 			w_value, w_index, w_length);
556 	}
557 
558 	/* respond with data transfer or status phase? */
559 	if (value >= 0) {
560 		DBG(cdev, "audio req%02x.%02x v%04x i%04x l%d\n",
561 			ctrl->bRequestType, ctrl->bRequest,
562 			w_value, w_index, w_length);
563 		req->zero = 0;
564 		req->length = value;
565 		value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
566 		if (value < 0)
567 			ERROR(cdev, "audio response on err %d\n", value);
568 	}
569 
570 	/* device either stalls (value < 0) or reports success */
571 	return value;
572 }
573 
574 static int f_audio_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
575 {
576 	struct f_audio		*audio = func_to_audio(f);
577 	struct usb_composite_dev *cdev = f->config->cdev;
578 	struct usb_ep *out_ep = audio->out_ep;
579 	struct usb_request *req;
580 	struct f_uac1_legacy_opts *opts;
581 	int req_buf_size, req_count, audio_buf_size;
582 	int i = 0, err = 0;
583 
584 	DBG(cdev, "intf %d, alt %d\n", intf, alt);
585 
586 	opts = container_of(f->fi, struct f_uac1_legacy_opts, func_inst);
587 	req_buf_size = opts->req_buf_size;
588 	req_count = opts->req_count;
589 	audio_buf_size = opts->audio_buf_size;
590 
591 	/* No i/f has more than 2 alt settings */
592 	if (alt > 1) {
593 		ERROR(cdev, "%s:%d Error!\n", __func__, __LINE__);
594 		return -EINVAL;
595 	}
596 
597 	if (intf == audio->ac_intf) {
598 		/* Control I/f has only 1 AltSetting - 0 */
599 		if (alt) {
600 			ERROR(cdev, "%s:%d Error!\n", __func__, __LINE__);
601 			return -EINVAL;
602 		}
603 		return 0;
604 	} else if (intf == audio->as_intf) {
605 		if (alt == 1) {
606 			err = config_ep_by_speed(cdev->gadget, f, out_ep);
607 			if (err)
608 				return err;
609 
610 			usb_ep_enable(out_ep);
611 			audio->copy_buf = f_audio_buffer_alloc(audio_buf_size);
612 			if (IS_ERR(audio->copy_buf))
613 				return -ENOMEM;
614 
615 			/*
616 			 * allocate a bunch of read buffers
617 			 * and queue them all at once.
618 			 */
619 			for (i = 0; i < req_count && err == 0; i++) {
620 				req = usb_ep_alloc_request(out_ep, GFP_ATOMIC);
621 				if (req) {
622 					req->buf = kzalloc(req_buf_size,
623 							GFP_ATOMIC);
624 					if (req->buf) {
625 						req->length = req_buf_size;
626 						req->context = audio;
627 						req->complete =
628 							f_audio_complete;
629 						err = usb_ep_queue(out_ep,
630 							req, GFP_ATOMIC);
631 						if (err)
632 							ERROR(cdev,
633 							"%s queue req: %d\n",
634 							out_ep->name, err);
635 					} else
636 						err = -ENOMEM;
637 				} else
638 					err = -ENOMEM;
639 			}
640 
641 		} else {
642 			struct f_audio_buf *copy_buf = audio->copy_buf;
643 			if (copy_buf) {
644 				list_add_tail(&copy_buf->list,
645 						&audio->play_queue);
646 				schedule_work(&audio->playback_work);
647 			}
648 		}
649 		audio->as_alt = alt;
650 	}
651 
652 	return err;
653 }
654 
655 static int f_audio_get_alt(struct usb_function *f, unsigned intf)
656 {
657 	struct f_audio		*audio = func_to_audio(f);
658 	struct usb_composite_dev *cdev = f->config->cdev;
659 
660 	if (intf == audio->ac_intf)
661 		return audio->ac_alt;
662 	else if (intf == audio->as_intf)
663 		return audio->as_alt;
664 	else
665 		ERROR(cdev, "%s:%d Invalid Interface %d!\n",
666 		      __func__, __LINE__, intf);
667 
668 	return -EINVAL;
669 }
670 
671 static void f_audio_disable(struct usb_function *f)
672 {
673 	return;
674 }
675 
676 /*-------------------------------------------------------------------------*/
677 
678 static void f_audio_build_desc(struct f_audio *audio)
679 {
680 	struct gaudio *card = &audio->card;
681 	u8 *sam_freq;
682 	int rate;
683 
684 	/* Set channel numbers */
685 	input_terminal_desc.bNrChannels = u_audio_get_playback_channels(card);
686 	as_type_i_desc.bNrChannels = u_audio_get_playback_channels(card);
687 
688 	/* Set sample rates */
689 	rate = u_audio_get_playback_rate(card);
690 	sam_freq = as_type_i_desc.tSamFreq[0];
691 	memcpy(sam_freq, &rate, 3);
692 
693 	/* Todo: Set Sample bits and other parameters */
694 
695 	return;
696 }
697 
698 /* audio function driver setup/binding */
699 static int
700 f_audio_bind(struct usb_configuration *c, struct usb_function *f)
701 {
702 	struct usb_composite_dev *cdev = c->cdev;
703 	struct f_audio		*audio = func_to_audio(f);
704 	struct usb_string	*us;
705 	int			status;
706 	struct usb_ep		*ep = NULL;
707 	struct f_uac1_legacy_opts	*audio_opts;
708 
709 	audio_opts = container_of(f->fi, struct f_uac1_legacy_opts, func_inst);
710 	audio->card.gadget = c->cdev->gadget;
711 	/* set up ASLA audio devices */
712 	if (!audio_opts->bound) {
713 		status = gaudio_setup(&audio->card);
714 		if (status < 0)
715 			return status;
716 		audio_opts->bound = true;
717 	}
718 	us = usb_gstrings_attach(cdev, uac1_strings, ARRAY_SIZE(strings_uac1));
719 	if (IS_ERR(us))
720 		return PTR_ERR(us);
721 	ac_interface_desc.iInterface = us[STR_AC_IF].id;
722 	input_terminal_desc.iTerminal = us[STR_INPUT_TERMINAL].id;
723 	input_terminal_desc.iChannelNames = us[STR_INPUT_TERMINAL_CH_NAMES].id;
724 	feature_unit_desc.iFeature = us[STR_FEAT_DESC_0].id;
725 	output_terminal_desc.iTerminal = us[STR_OUTPUT_TERMINAL].id;
726 	as_interface_alt_0_desc.iInterface = us[STR_AS_IF_ALT0].id;
727 	as_interface_alt_1_desc.iInterface = us[STR_AS_IF_ALT1].id;
728 
729 
730 	f_audio_build_desc(audio);
731 
732 	/* allocate instance-specific interface IDs, and patch descriptors */
733 	status = usb_interface_id(c, f);
734 	if (status < 0)
735 		goto fail;
736 	ac_interface_desc.bInterfaceNumber = status;
737 	audio->ac_intf = status;
738 	audio->ac_alt = 0;
739 
740 	status = usb_interface_id(c, f);
741 	if (status < 0)
742 		goto fail;
743 	as_interface_alt_0_desc.bInterfaceNumber = status;
744 	as_interface_alt_1_desc.bInterfaceNumber = status;
745 	audio->as_intf = status;
746 	audio->as_alt = 0;
747 
748 	status = -ENODEV;
749 
750 	/* allocate instance-specific endpoints */
751 	ep = usb_ep_autoconfig(cdev->gadget, &as_out_ep_desc);
752 	if (!ep)
753 		goto fail;
754 	audio->out_ep = ep;
755 	audio->out_ep->desc = &as_out_ep_desc;
756 
757 	status = -ENOMEM;
758 
759 	/* copy descriptors, and track endpoint copies */
760 	status = usb_assign_descriptors(f, f_audio_desc, f_audio_desc, NULL,
761 					NULL);
762 	if (status)
763 		goto fail;
764 	return 0;
765 
766 fail:
767 	gaudio_cleanup(&audio->card);
768 	return status;
769 }
770 
771 /*-------------------------------------------------------------------------*/
772 
773 static int generic_set_cmd(struct usb_audio_control *con, u8 cmd, int value)
774 {
775 	con->data[cmd] = value;
776 
777 	return 0;
778 }
779 
780 static int generic_get_cmd(struct usb_audio_control *con, u8 cmd)
781 {
782 	return con->data[cmd];
783 }
784 
785 /* Todo: add more control selecotor dynamically */
786 static int control_selector_init(struct f_audio *audio)
787 {
788 	INIT_LIST_HEAD(&audio->cs);
789 	list_add(&feature_unit.list, &audio->cs);
790 
791 	INIT_LIST_HEAD(&feature_unit.control);
792 	list_add(&mute_control.list, &feature_unit.control);
793 	list_add(&volume_control.list, &feature_unit.control);
794 
795 	volume_control.data[UAC__CUR] = 0xffc0;
796 	volume_control.data[UAC__MIN] = 0xe3a0;
797 	volume_control.data[UAC__MAX] = 0xfff0;
798 	volume_control.data[UAC__RES] = 0x0030;
799 
800 	return 0;
801 }
802 
803 static inline
804 struct f_uac1_legacy_opts *to_f_uac1_opts(struct config_item *item)
805 {
806 	return container_of(to_config_group(item), struct f_uac1_legacy_opts,
807 			    func_inst.group);
808 }
809 
810 static void f_uac1_attr_release(struct config_item *item)
811 {
812 	struct f_uac1_legacy_opts *opts = to_f_uac1_opts(item);
813 
814 	usb_put_function_instance(&opts->func_inst);
815 }
816 
817 static struct configfs_item_operations f_uac1_item_ops = {
818 	.release	= f_uac1_attr_release,
819 };
820 
821 #define UAC1_INT_ATTRIBUTE(name)					\
822 static ssize_t f_uac1_opts_##name##_show(struct config_item *item,	\
823 					 char *page)			\
824 {									\
825 	struct f_uac1_legacy_opts *opts = to_f_uac1_opts(item);		\
826 	int result;							\
827 									\
828 	mutex_lock(&opts->lock);					\
829 	result = sprintf(page, "%u\n", opts->name);			\
830 	mutex_unlock(&opts->lock);					\
831 									\
832 	return result;							\
833 }									\
834 									\
835 static ssize_t f_uac1_opts_##name##_store(struct config_item *item,		\
836 					  const char *page, size_t len)	\
837 {									\
838 	struct f_uac1_legacy_opts *opts = to_f_uac1_opts(item);		\
839 	int ret;							\
840 	u32 num;							\
841 									\
842 	mutex_lock(&opts->lock);					\
843 	if (opts->refcnt) {						\
844 		ret = -EBUSY;						\
845 		goto end;						\
846 	}								\
847 									\
848 	ret = kstrtou32(page, 0, &num);					\
849 	if (ret)							\
850 		goto end;						\
851 									\
852 	opts->name = num;						\
853 	ret = len;							\
854 									\
855 end:									\
856 	mutex_unlock(&opts->lock);					\
857 	return ret;							\
858 }									\
859 									\
860 CONFIGFS_ATTR(f_uac1_opts_, name)
861 
862 UAC1_INT_ATTRIBUTE(req_buf_size);
863 UAC1_INT_ATTRIBUTE(req_count);
864 UAC1_INT_ATTRIBUTE(audio_buf_size);
865 
866 #define UAC1_STR_ATTRIBUTE(name)					\
867 static ssize_t f_uac1_opts_##name##_show(struct config_item *item,	\
868 					 char *page)			\
869 {									\
870 	struct f_uac1_legacy_opts *opts = to_f_uac1_opts(item);		\
871 	int result;							\
872 									\
873 	mutex_lock(&opts->lock);					\
874 	result = sprintf(page, "%s\n", opts->name);			\
875 	mutex_unlock(&opts->lock);					\
876 									\
877 	return result;							\
878 }									\
879 									\
880 static ssize_t f_uac1_opts_##name##_store(struct config_item *item,	\
881 					  const char *page, size_t len)	\
882 {									\
883 	struct f_uac1_legacy_opts *opts = to_f_uac1_opts(item);		\
884 	int ret = -EBUSY;						\
885 	char *tmp;							\
886 									\
887 	mutex_lock(&opts->lock);					\
888 	if (opts->refcnt)						\
889 		goto end;						\
890 									\
891 	tmp = kstrndup(page, len, GFP_KERNEL);				\
892 	if (tmp) {							\
893 		ret = -ENOMEM;						\
894 		goto end;						\
895 	}								\
896 	if (opts->name##_alloc)						\
897 		kfree(opts->name);					\
898 	opts->name##_alloc = true;					\
899 	opts->name = tmp;						\
900 	ret = len;							\
901 									\
902 end:									\
903 	mutex_unlock(&opts->lock);					\
904 	return ret;							\
905 }									\
906 									\
907 CONFIGFS_ATTR(f_uac1_opts_, name)
908 
909 UAC1_STR_ATTRIBUTE(fn_play);
910 UAC1_STR_ATTRIBUTE(fn_cap);
911 UAC1_STR_ATTRIBUTE(fn_cntl);
912 
913 static struct configfs_attribute *f_uac1_attrs[] = {
914 	&f_uac1_opts_attr_req_buf_size,
915 	&f_uac1_opts_attr_req_count,
916 	&f_uac1_opts_attr_audio_buf_size,
917 	&f_uac1_opts_attr_fn_play,
918 	&f_uac1_opts_attr_fn_cap,
919 	&f_uac1_opts_attr_fn_cntl,
920 	NULL,
921 };
922 
923 static const struct config_item_type f_uac1_func_type = {
924 	.ct_item_ops	= &f_uac1_item_ops,
925 	.ct_attrs	= f_uac1_attrs,
926 	.ct_owner	= THIS_MODULE,
927 };
928 
929 static void f_audio_free_inst(struct usb_function_instance *f)
930 {
931 	struct f_uac1_legacy_opts *opts;
932 
933 	opts = container_of(f, struct f_uac1_legacy_opts, func_inst);
934 	if (opts->fn_play_alloc)
935 		kfree(opts->fn_play);
936 	if (opts->fn_cap_alloc)
937 		kfree(opts->fn_cap);
938 	if (opts->fn_cntl_alloc)
939 		kfree(opts->fn_cntl);
940 	kfree(opts);
941 }
942 
943 static struct usb_function_instance *f_audio_alloc_inst(void)
944 {
945 	struct f_uac1_legacy_opts *opts;
946 
947 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
948 	if (!opts)
949 		return ERR_PTR(-ENOMEM);
950 
951 	mutex_init(&opts->lock);
952 	opts->func_inst.free_func_inst = f_audio_free_inst;
953 
954 	config_group_init_type_name(&opts->func_inst.group, "",
955 				    &f_uac1_func_type);
956 
957 	opts->req_buf_size = UAC1_OUT_EP_MAX_PACKET_SIZE;
958 	opts->req_count = UAC1_REQ_COUNT;
959 	opts->audio_buf_size = UAC1_AUDIO_BUF_SIZE;
960 	opts->fn_play = FILE_PCM_PLAYBACK;
961 	opts->fn_cap = FILE_PCM_CAPTURE;
962 	opts->fn_cntl = FILE_CONTROL;
963 	return &opts->func_inst;
964 }
965 
966 static void f_audio_free(struct usb_function *f)
967 {
968 	struct f_audio *audio = func_to_audio(f);
969 	struct f_uac1_legacy_opts *opts;
970 
971 	gaudio_cleanup(&audio->card);
972 	opts = container_of(f->fi, struct f_uac1_legacy_opts, func_inst);
973 	kfree(audio);
974 	mutex_lock(&opts->lock);
975 	--opts->refcnt;
976 	mutex_unlock(&opts->lock);
977 }
978 
979 static void f_audio_unbind(struct usb_configuration *c, struct usb_function *f)
980 {
981 	usb_free_all_descriptors(f);
982 }
983 
984 static struct usb_function *f_audio_alloc(struct usb_function_instance *fi)
985 {
986 	struct f_audio *audio;
987 	struct f_uac1_legacy_opts *opts;
988 
989 	/* allocate and initialize one new instance */
990 	audio = kzalloc(sizeof(*audio), GFP_KERNEL);
991 	if (!audio)
992 		return ERR_PTR(-ENOMEM);
993 
994 	audio->card.func.name = "g_audio";
995 
996 	opts = container_of(fi, struct f_uac1_legacy_opts, func_inst);
997 	mutex_lock(&opts->lock);
998 	++opts->refcnt;
999 	mutex_unlock(&opts->lock);
1000 	INIT_LIST_HEAD(&audio->play_queue);
1001 	spin_lock_init(&audio->lock);
1002 
1003 	audio->card.func.bind = f_audio_bind;
1004 	audio->card.func.unbind = f_audio_unbind;
1005 	audio->card.func.set_alt = f_audio_set_alt;
1006 	audio->card.func.get_alt = f_audio_get_alt;
1007 	audio->card.func.setup = f_audio_setup;
1008 	audio->card.func.disable = f_audio_disable;
1009 	audio->card.func.free_func = f_audio_free;
1010 
1011 	control_selector_init(audio);
1012 
1013 	INIT_WORK(&audio->playback_work, f_audio_playback_work);
1014 
1015 	return &audio->card.func;
1016 }
1017 
1018 DECLARE_USB_FUNCTION_INIT(uac1_legacy, f_audio_alloc_inst, f_audio_alloc);
1019 MODULE_LICENSE("GPL");
1020 MODULE_AUTHOR("Bryan Wu");
1021