1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * f_uac1.c -- USB Audio Class 1.0 Function (using u_audio API)
4  *
5  * Copyright (C) 2016 Ruslan Bilovol <ruslan.bilovol@gmail.com>
6  *
7  * This driver doesn't expect any real Audio codec to be present
8  * on the device - the audio streams are simply sinked to and
9  * sourced from a virtual ALSA sound card created.
10  *
11  * This file is based on f_uac1.c which is
12  *   Copyright (C) 2008 Bryan Wu <cooloney@kernel.org>
13  *   Copyright (C) 2008 Analog Devices, Inc
14  */
15 
16 #include <linux/usb/audio.h>
17 #include <linux/module.h>
18 
19 #include "u_audio.h"
20 #include "u_uac1.h"
21 
22 /* UAC1 spec: 3.7.2.3 Audio Channel Cluster Format */
23 #define UAC1_CHANNEL_MASK 0x0FFF
24 
25 #define EPIN_EN(_opts) ((_opts)->p_chmask != 0)
26 #define EPOUT_EN(_opts) ((_opts)->c_chmask != 0)
27 
28 struct f_uac1 {
29 	struct g_audio g_audio;
30 	u8 ac_intf, as_in_intf, as_out_intf;
31 	u8 ac_alt, as_in_alt, as_out_alt;	/* needed for get_alt() */
32 };
33 
34 static inline struct f_uac1 *func_to_uac1(struct usb_function *f)
35 {
36 	return container_of(f, struct f_uac1, g_audio.func);
37 }
38 
39 static inline struct f_uac1_opts *g_audio_to_uac1_opts(struct g_audio *audio)
40 {
41 	return container_of(audio->func.fi, struct f_uac1_opts, func_inst);
42 }
43 
44 /*
45  * DESCRIPTORS ... most are static, but strings and full
46  * configuration descriptors are built on demand.
47  */
48 
49 /*
50  * We have three interfaces - one AudioControl and two AudioStreaming
51  *
52  * The driver implements a simple UAC_1 topology.
53  * USB-OUT -> IT_1 -> OT_2 -> ALSA_Capture
54  * ALSA_Playback -> IT_3 -> OT_4 -> USB-IN
55  */
56 
57 /* B.3.1  Standard AC Interface Descriptor */
58 static struct usb_interface_descriptor ac_interface_desc = {
59 	.bLength =		USB_DT_INTERFACE_SIZE,
60 	.bDescriptorType =	USB_DT_INTERFACE,
61 	.bNumEndpoints =	0,
62 	.bInterfaceClass =	USB_CLASS_AUDIO,
63 	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOCONTROL,
64 };
65 
66 /* B.3.2  Class-Specific AC Interface Descriptor */
67 static struct uac1_ac_header_descriptor *ac_header_desc;
68 
69 static struct uac_input_terminal_descriptor usb_out_it_desc = {
70 	.bLength =		UAC_DT_INPUT_TERMINAL_SIZE,
71 	.bDescriptorType =	USB_DT_CS_INTERFACE,
72 	.bDescriptorSubtype =	UAC_INPUT_TERMINAL,
73 	/* .bTerminalID =	DYNAMIC */
74 	.wTerminalType =	cpu_to_le16(UAC_TERMINAL_STREAMING),
75 	.bAssocTerminal =	0,
76 	.wChannelConfig =	cpu_to_le16(0x3),
77 };
78 
79 static struct uac1_output_terminal_descriptor io_out_ot_desc = {
80 	.bLength		= UAC_DT_OUTPUT_TERMINAL_SIZE,
81 	.bDescriptorType	= USB_DT_CS_INTERFACE,
82 	.bDescriptorSubtype	= UAC_OUTPUT_TERMINAL,
83 	/* .bTerminalID =	DYNAMIC */
84 	.wTerminalType		= cpu_to_le16(UAC_OUTPUT_TERMINAL_SPEAKER),
85 	.bAssocTerminal		= 0,
86 	/* .bSourceID =		DYNAMIC */
87 };
88 
89 static struct uac_input_terminal_descriptor io_in_it_desc = {
90 	.bLength		= UAC_DT_INPUT_TERMINAL_SIZE,
91 	.bDescriptorType	= USB_DT_CS_INTERFACE,
92 	.bDescriptorSubtype	= UAC_INPUT_TERMINAL,
93 	/* .bTerminalID		= DYNAMIC */
94 	.wTerminalType		= cpu_to_le16(UAC_INPUT_TERMINAL_MICROPHONE),
95 	.bAssocTerminal		= 0,
96 	.wChannelConfig		= cpu_to_le16(0x3),
97 };
98 
99 static struct uac1_output_terminal_descriptor usb_in_ot_desc = {
100 	.bLength =		UAC_DT_OUTPUT_TERMINAL_SIZE,
101 	.bDescriptorType =	USB_DT_CS_INTERFACE,
102 	.bDescriptorSubtype =	UAC_OUTPUT_TERMINAL,
103 	/* .bTerminalID =	DYNAMIC */
104 	.wTerminalType =	cpu_to_le16(UAC_TERMINAL_STREAMING),
105 	.bAssocTerminal =	0,
106 	/* .bSourceID =		DYNAMIC */
107 };
108 
109 /* B.4.1  Standard AS Interface Descriptor */
110 static struct usb_interface_descriptor as_out_interface_alt_0_desc = {
111 	.bLength =		USB_DT_INTERFACE_SIZE,
112 	.bDescriptorType =	USB_DT_INTERFACE,
113 	.bAlternateSetting =	0,
114 	.bNumEndpoints =	0,
115 	.bInterfaceClass =	USB_CLASS_AUDIO,
116 	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOSTREAMING,
117 };
118 
119 static struct usb_interface_descriptor as_out_interface_alt_1_desc = {
120 	.bLength =		USB_DT_INTERFACE_SIZE,
121 	.bDescriptorType =	USB_DT_INTERFACE,
122 	.bAlternateSetting =	1,
123 	.bNumEndpoints =	1,
124 	.bInterfaceClass =	USB_CLASS_AUDIO,
125 	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOSTREAMING,
126 };
127 
128 static struct usb_interface_descriptor as_in_interface_alt_0_desc = {
129 	.bLength =		USB_DT_INTERFACE_SIZE,
130 	.bDescriptorType =	USB_DT_INTERFACE,
131 	.bAlternateSetting =	0,
132 	.bNumEndpoints =	0,
133 	.bInterfaceClass =	USB_CLASS_AUDIO,
134 	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOSTREAMING,
135 };
136 
137 static struct usb_interface_descriptor as_in_interface_alt_1_desc = {
138 	.bLength =		USB_DT_INTERFACE_SIZE,
139 	.bDescriptorType =	USB_DT_INTERFACE,
140 	.bAlternateSetting =	1,
141 	.bNumEndpoints =	1,
142 	.bInterfaceClass =	USB_CLASS_AUDIO,
143 	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOSTREAMING,
144 };
145 
146 /* B.4.2  Class-Specific AS Interface Descriptor */
147 static struct uac1_as_header_descriptor as_out_header_desc = {
148 	.bLength =		UAC_DT_AS_HEADER_SIZE,
149 	.bDescriptorType =	USB_DT_CS_INTERFACE,
150 	.bDescriptorSubtype =	UAC_AS_GENERAL,
151 	/* .bTerminalLink =	DYNAMIC */
152 	.bDelay =		1,
153 	.wFormatTag =		cpu_to_le16(UAC_FORMAT_TYPE_I_PCM),
154 };
155 
156 static struct uac1_as_header_descriptor as_in_header_desc = {
157 	.bLength =		UAC_DT_AS_HEADER_SIZE,
158 	.bDescriptorType =	USB_DT_CS_INTERFACE,
159 	.bDescriptorSubtype =	UAC_AS_GENERAL,
160 	/* .bTerminalLink =	DYNAMIC */
161 	.bDelay =		1,
162 	.wFormatTag =		cpu_to_le16(UAC_FORMAT_TYPE_I_PCM),
163 };
164 
165 DECLARE_UAC_FORMAT_TYPE_I_DISCRETE_DESC(1);
166 
167 static struct uac_format_type_i_discrete_descriptor_1 as_out_type_i_desc = {
168 	.bLength =		UAC_FORMAT_TYPE_I_DISCRETE_DESC_SIZE(1),
169 	.bDescriptorType =	USB_DT_CS_INTERFACE,
170 	.bDescriptorSubtype =	UAC_FORMAT_TYPE,
171 	.bFormatType =		UAC_FORMAT_TYPE_I,
172 	.bSubframeSize =	2,
173 	.bBitResolution =	16,
174 	.bSamFreqType =		1,
175 };
176 
177 /* Standard ISO OUT Endpoint Descriptor */
178 static struct usb_endpoint_descriptor as_out_ep_desc  = {
179 	.bLength =		USB_DT_ENDPOINT_AUDIO_SIZE,
180 	.bDescriptorType =	USB_DT_ENDPOINT,
181 	.bEndpointAddress =	USB_DIR_OUT,
182 	.bmAttributes =		USB_ENDPOINT_SYNC_ADAPTIVE
183 				| USB_ENDPOINT_XFER_ISOC,
184 	.wMaxPacketSize	=	cpu_to_le16(UAC1_OUT_EP_MAX_PACKET_SIZE),
185 	.bInterval =		4,
186 };
187 
188 /* Class-specific AS ISO OUT Endpoint Descriptor */
189 static struct uac_iso_endpoint_descriptor as_iso_out_desc = {
190 	.bLength =		UAC_ISO_ENDPOINT_DESC_SIZE,
191 	.bDescriptorType =	USB_DT_CS_ENDPOINT,
192 	.bDescriptorSubtype =	UAC_EP_GENERAL,
193 	.bmAttributes =		1,
194 	.bLockDelayUnits =	1,
195 	.wLockDelay =		cpu_to_le16(1),
196 };
197 
198 static struct uac_format_type_i_discrete_descriptor_1 as_in_type_i_desc = {
199 	.bLength =		UAC_FORMAT_TYPE_I_DISCRETE_DESC_SIZE(1),
200 	.bDescriptorType =	USB_DT_CS_INTERFACE,
201 	.bDescriptorSubtype =	UAC_FORMAT_TYPE,
202 	.bFormatType =		UAC_FORMAT_TYPE_I,
203 	.bSubframeSize =	2,
204 	.bBitResolution =	16,
205 	.bSamFreqType =		1,
206 };
207 
208 /* Standard ISO OUT Endpoint Descriptor */
209 static struct usb_endpoint_descriptor as_in_ep_desc  = {
210 	.bLength =		USB_DT_ENDPOINT_AUDIO_SIZE,
211 	.bDescriptorType =	USB_DT_ENDPOINT,
212 	.bEndpointAddress =	USB_DIR_IN,
213 	.bmAttributes =		USB_ENDPOINT_SYNC_ASYNC
214 				| USB_ENDPOINT_XFER_ISOC,
215 	.wMaxPacketSize	=	cpu_to_le16(UAC1_OUT_EP_MAX_PACKET_SIZE),
216 	.bInterval =		4,
217 };
218 
219 /* Class-specific AS ISO OUT Endpoint Descriptor */
220 static struct uac_iso_endpoint_descriptor as_iso_in_desc = {
221 	.bLength =		UAC_ISO_ENDPOINT_DESC_SIZE,
222 	.bDescriptorType =	USB_DT_CS_ENDPOINT,
223 	.bDescriptorSubtype =	UAC_EP_GENERAL,
224 	.bmAttributes =		1,
225 	.bLockDelayUnits =	0,
226 	.wLockDelay =		0,
227 };
228 
229 static struct usb_descriptor_header *f_audio_desc[] = {
230 	(struct usb_descriptor_header *)&ac_interface_desc,
231 	(struct usb_descriptor_header *)&ac_header_desc,
232 
233 	(struct usb_descriptor_header *)&usb_out_it_desc,
234 	(struct usb_descriptor_header *)&io_out_ot_desc,
235 	(struct usb_descriptor_header *)&io_in_it_desc,
236 	(struct usb_descriptor_header *)&usb_in_ot_desc,
237 
238 	(struct usb_descriptor_header *)&as_out_interface_alt_0_desc,
239 	(struct usb_descriptor_header *)&as_out_interface_alt_1_desc,
240 	(struct usb_descriptor_header *)&as_out_header_desc,
241 
242 	(struct usb_descriptor_header *)&as_out_type_i_desc,
243 
244 	(struct usb_descriptor_header *)&as_out_ep_desc,
245 	(struct usb_descriptor_header *)&as_iso_out_desc,
246 
247 	(struct usb_descriptor_header *)&as_in_interface_alt_0_desc,
248 	(struct usb_descriptor_header *)&as_in_interface_alt_1_desc,
249 	(struct usb_descriptor_header *)&as_in_header_desc,
250 
251 	(struct usb_descriptor_header *)&as_in_type_i_desc,
252 
253 	(struct usb_descriptor_header *)&as_in_ep_desc,
254 	(struct usb_descriptor_header *)&as_iso_in_desc,
255 	NULL,
256 };
257 
258 enum {
259 	STR_AC_IF,
260 	STR_USB_OUT_IT,
261 	STR_USB_OUT_IT_CH_NAMES,
262 	STR_IO_OUT_OT,
263 	STR_IO_IN_IT,
264 	STR_IO_IN_IT_CH_NAMES,
265 	STR_USB_IN_OT,
266 	STR_AS_OUT_IF_ALT0,
267 	STR_AS_OUT_IF_ALT1,
268 	STR_AS_IN_IF_ALT0,
269 	STR_AS_IN_IF_ALT1,
270 };
271 
272 static struct usb_string strings_uac1[] = {
273 	[STR_AC_IF].s = "AC Interface",
274 	[STR_USB_OUT_IT].s = "Playback Input terminal",
275 	[STR_USB_OUT_IT_CH_NAMES].s = "Playback Channels",
276 	[STR_IO_OUT_OT].s = "Playback Output terminal",
277 	[STR_IO_IN_IT].s = "Capture Input terminal",
278 	[STR_IO_IN_IT_CH_NAMES].s = "Capture Channels",
279 	[STR_USB_IN_OT].s = "Capture Output terminal",
280 	[STR_AS_OUT_IF_ALT0].s = "Playback Inactive",
281 	[STR_AS_OUT_IF_ALT1].s = "Playback Active",
282 	[STR_AS_IN_IF_ALT0].s = "Capture Inactive",
283 	[STR_AS_IN_IF_ALT1].s = "Capture Active",
284 	{ },
285 };
286 
287 static struct usb_gadget_strings str_uac1 = {
288 	.language = 0x0409,	/* en-us */
289 	.strings = strings_uac1,
290 };
291 
292 static struct usb_gadget_strings *uac1_strings[] = {
293 	&str_uac1,
294 	NULL,
295 };
296 
297 /*
298  * This function is an ALSA sound card following USB Audio Class Spec 1.0.
299  */
300 
301 static int audio_set_endpoint_req(struct usb_function *f,
302 		const struct usb_ctrlrequest *ctrl)
303 {
304 	struct usb_composite_dev *cdev = f->config->cdev;
305 	int			value = -EOPNOTSUPP;
306 	u16			ep = le16_to_cpu(ctrl->wIndex);
307 	u16			len = le16_to_cpu(ctrl->wLength);
308 	u16			w_value = le16_to_cpu(ctrl->wValue);
309 
310 	DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
311 			ctrl->bRequest, w_value, len, ep);
312 
313 	switch (ctrl->bRequest) {
314 	case UAC_SET_CUR:
315 		value = len;
316 		break;
317 
318 	case UAC_SET_MIN:
319 		break;
320 
321 	case UAC_SET_MAX:
322 		break;
323 
324 	case UAC_SET_RES:
325 		break;
326 
327 	case UAC_SET_MEM:
328 		break;
329 
330 	default:
331 		break;
332 	}
333 
334 	return value;
335 }
336 
337 static int audio_get_endpoint_req(struct usb_function *f,
338 		const struct usb_ctrlrequest *ctrl)
339 {
340 	struct usb_composite_dev *cdev = f->config->cdev;
341 	int value = -EOPNOTSUPP;
342 	u8 ep = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
343 	u16 len = le16_to_cpu(ctrl->wLength);
344 	u16 w_value = le16_to_cpu(ctrl->wValue);
345 
346 	DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
347 			ctrl->bRequest, w_value, len, ep);
348 
349 	switch (ctrl->bRequest) {
350 	case UAC_GET_CUR:
351 	case UAC_GET_MIN:
352 	case UAC_GET_MAX:
353 	case UAC_GET_RES:
354 		value = len;
355 		break;
356 	case UAC_GET_MEM:
357 		break;
358 	default:
359 		break;
360 	}
361 
362 	return value;
363 }
364 
365 static int
366 f_audio_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
367 {
368 	struct usb_composite_dev *cdev = f->config->cdev;
369 	struct usb_request	*req = cdev->req;
370 	int			value = -EOPNOTSUPP;
371 	u16			w_index = le16_to_cpu(ctrl->wIndex);
372 	u16			w_value = le16_to_cpu(ctrl->wValue);
373 	u16			w_length = le16_to_cpu(ctrl->wLength);
374 
375 	/* composite driver infrastructure handles everything; interface
376 	 * activation uses set_alt().
377 	 */
378 	switch (ctrl->bRequestType) {
379 	case USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
380 		value = audio_set_endpoint_req(f, ctrl);
381 		break;
382 
383 	case USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
384 		value = audio_get_endpoint_req(f, ctrl);
385 		break;
386 
387 	default:
388 		ERROR(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
389 			ctrl->bRequestType, ctrl->bRequest,
390 			w_value, w_index, w_length);
391 	}
392 
393 	/* respond with data transfer or status phase? */
394 	if (value >= 0) {
395 		DBG(cdev, "audio req%02x.%02x v%04x i%04x l%d\n",
396 			ctrl->bRequestType, ctrl->bRequest,
397 			w_value, w_index, w_length);
398 		req->zero = 0;
399 		req->length = value;
400 		value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
401 		if (value < 0)
402 			ERROR(cdev, "audio response on err %d\n", value);
403 	}
404 
405 	/* device either stalls (value < 0) or reports success */
406 	return value;
407 }
408 
409 static int f_audio_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
410 {
411 	struct usb_composite_dev *cdev = f->config->cdev;
412 	struct usb_gadget *gadget = cdev->gadget;
413 	struct device *dev = &gadget->dev;
414 	struct f_uac1 *uac1 = func_to_uac1(f);
415 	int ret = 0;
416 
417 	/* No i/f has more than 2 alt settings */
418 	if (alt > 1) {
419 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
420 		return -EINVAL;
421 	}
422 
423 	if (intf == uac1->ac_intf) {
424 		/* Control I/f has only 1 AltSetting - 0 */
425 		if (alt) {
426 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
427 			return -EINVAL;
428 		}
429 		return 0;
430 	}
431 
432 	if (intf == uac1->as_out_intf) {
433 		uac1->as_out_alt = alt;
434 
435 		if (alt)
436 			ret = u_audio_start_capture(&uac1->g_audio);
437 		else
438 			u_audio_stop_capture(&uac1->g_audio);
439 	} else if (intf == uac1->as_in_intf) {
440 		uac1->as_in_alt = alt;
441 
442 		if (alt)
443 			ret = u_audio_start_playback(&uac1->g_audio);
444 		else
445 			u_audio_stop_playback(&uac1->g_audio);
446 	} else {
447 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
448 		return -EINVAL;
449 	}
450 
451 	return ret;
452 }
453 
454 static int f_audio_get_alt(struct usb_function *f, unsigned intf)
455 {
456 	struct usb_composite_dev *cdev = f->config->cdev;
457 	struct usb_gadget *gadget = cdev->gadget;
458 	struct device *dev = &gadget->dev;
459 	struct f_uac1 *uac1 = func_to_uac1(f);
460 
461 	if (intf == uac1->ac_intf)
462 		return uac1->ac_alt;
463 	else if (intf == uac1->as_out_intf)
464 		return uac1->as_out_alt;
465 	else if (intf == uac1->as_in_intf)
466 		return uac1->as_in_alt;
467 	else
468 		dev_err(dev, "%s:%d Invalid Interface %d!\n",
469 			__func__, __LINE__, intf);
470 
471 	return -EINVAL;
472 }
473 
474 
475 static void f_audio_disable(struct usb_function *f)
476 {
477 	struct f_uac1 *uac1 = func_to_uac1(f);
478 
479 	uac1->as_out_alt = 0;
480 	uac1->as_in_alt = 0;
481 
482 	u_audio_stop_playback(&uac1->g_audio);
483 	u_audio_stop_capture(&uac1->g_audio);
484 }
485 
486 /*-------------------------------------------------------------------------*/
487 
488 static struct
489 uac1_ac_header_descriptor *build_ac_header_desc(struct f_uac1_opts *opts)
490 {
491 	struct uac1_ac_header_descriptor *ac_desc;
492 	int ac_header_desc_size;
493 	int num_ifaces = 0;
494 
495 	if (EPOUT_EN(opts))
496 		num_ifaces++;
497 	if (EPIN_EN(opts))
498 		num_ifaces++;
499 
500 	ac_header_desc_size = UAC_DT_AC_HEADER_SIZE(num_ifaces);
501 
502 	ac_desc = kzalloc(ac_header_desc_size, GFP_KERNEL);
503 	if (!ac_desc)
504 		return NULL;
505 
506 	ac_desc->bLength = ac_header_desc_size;
507 	ac_desc->bDescriptorType = USB_DT_CS_INTERFACE;
508 	ac_desc->bDescriptorSubtype = UAC_HEADER;
509 	ac_desc->bcdADC = cpu_to_le16(0x0100);
510 	ac_desc->bInCollection = num_ifaces;
511 
512 	/* wTotalLength and baInterfaceNr will be defined later */
513 
514 	return ac_desc;
515 }
516 
517 /* Use macro to overcome line length limitation */
518 #define USBDHDR(p) (struct usb_descriptor_header *)(p)
519 
520 static void setup_descriptor(struct f_uac1_opts *opts)
521 {
522 	/* patch descriptors */
523 	int i = 1; /* ID's start with 1 */
524 
525 	if (EPOUT_EN(opts))
526 		usb_out_it_desc.bTerminalID = i++;
527 	if (EPIN_EN(opts))
528 		io_in_it_desc.bTerminalID = i++;
529 	if (EPOUT_EN(opts))
530 		io_out_ot_desc.bTerminalID = i++;
531 	if (EPIN_EN(opts))
532 		usb_in_ot_desc.bTerminalID = i++;
533 
534 	usb_in_ot_desc.bSourceID = io_in_it_desc.bTerminalID;
535 	io_out_ot_desc.bSourceID = usb_out_it_desc.bTerminalID;
536 
537 	as_out_header_desc.bTerminalLink = usb_out_it_desc.bTerminalID;
538 	as_in_header_desc.bTerminalLink = usb_in_ot_desc.bTerminalID;
539 
540 	ac_header_desc->wTotalLength = cpu_to_le16(ac_header_desc->bLength);
541 
542 	if (EPIN_EN(opts)) {
543 		u16 len = le16_to_cpu(ac_header_desc->wTotalLength);
544 
545 		len += sizeof(usb_in_ot_desc);
546 		len += sizeof(io_in_it_desc);
547 		ac_header_desc->wTotalLength = cpu_to_le16(len);
548 	}
549 	if (EPOUT_EN(opts)) {
550 		u16 len = le16_to_cpu(ac_header_desc->wTotalLength);
551 
552 		len += sizeof(usb_out_it_desc);
553 		len += sizeof(io_out_ot_desc);
554 		ac_header_desc->wTotalLength = cpu_to_le16(len);
555 	}
556 
557 	i = 0;
558 	f_audio_desc[i++] = USBDHDR(&ac_interface_desc);
559 	f_audio_desc[i++] = USBDHDR(ac_header_desc);
560 
561 	if (EPOUT_EN(opts)) {
562 		f_audio_desc[i++] = USBDHDR(&usb_out_it_desc);
563 		f_audio_desc[i++] = USBDHDR(&io_out_ot_desc);
564 	}
565 
566 	if (EPIN_EN(opts)) {
567 		f_audio_desc[i++] = USBDHDR(&io_in_it_desc);
568 		f_audio_desc[i++] = USBDHDR(&usb_in_ot_desc);
569 	}
570 
571 	if (EPOUT_EN(opts)) {
572 		f_audio_desc[i++] = USBDHDR(&as_out_interface_alt_0_desc);
573 		f_audio_desc[i++] = USBDHDR(&as_out_interface_alt_1_desc);
574 		f_audio_desc[i++] = USBDHDR(&as_out_header_desc);
575 		f_audio_desc[i++] = USBDHDR(&as_out_type_i_desc);
576 		f_audio_desc[i++] = USBDHDR(&as_out_ep_desc);
577 		f_audio_desc[i++] = USBDHDR(&as_iso_out_desc);
578 	}
579 	if (EPIN_EN(opts)) {
580 		f_audio_desc[i++] = USBDHDR(&as_in_interface_alt_0_desc);
581 		f_audio_desc[i++] = USBDHDR(&as_in_interface_alt_1_desc);
582 		f_audio_desc[i++] = USBDHDR(&as_in_header_desc);
583 		f_audio_desc[i++] = USBDHDR(&as_in_type_i_desc);
584 		f_audio_desc[i++] = USBDHDR(&as_in_ep_desc);
585 		f_audio_desc[i++] = USBDHDR(&as_iso_in_desc);
586 	}
587 	f_audio_desc[i] = NULL;
588 }
589 
590 static int f_audio_validate_opts(struct g_audio *audio, struct device *dev)
591 {
592 	struct f_uac1_opts *opts = g_audio_to_uac1_opts(audio);
593 
594 	if (!opts->p_chmask && !opts->c_chmask) {
595 		dev_err(dev, "Error: no playback and capture channels\n");
596 		return -EINVAL;
597 	} else if (opts->p_chmask & ~UAC1_CHANNEL_MASK) {
598 		dev_err(dev, "Error: unsupported playback channels mask\n");
599 		return -EINVAL;
600 	} else if (opts->c_chmask & ~UAC1_CHANNEL_MASK) {
601 		dev_err(dev, "Error: unsupported capture channels mask\n");
602 		return -EINVAL;
603 	} else if ((opts->p_ssize < 1) || (opts->p_ssize > 4)) {
604 		dev_err(dev, "Error: incorrect playback sample size\n");
605 		return -EINVAL;
606 	} else if ((opts->c_ssize < 1) || (opts->c_ssize > 4)) {
607 		dev_err(dev, "Error: incorrect capture sample size\n");
608 		return -EINVAL;
609 	} else if (!opts->p_srate) {
610 		dev_err(dev, "Error: incorrect playback sampling rate\n");
611 		return -EINVAL;
612 	} else if (!opts->c_srate) {
613 		dev_err(dev, "Error: incorrect capture sampling rate\n");
614 		return -EINVAL;
615 	}
616 
617 	return 0;
618 }
619 
620 /* audio function driver setup/binding */
621 static int f_audio_bind(struct usb_configuration *c, struct usb_function *f)
622 {
623 	struct usb_composite_dev	*cdev = c->cdev;
624 	struct usb_gadget		*gadget = cdev->gadget;
625 	struct device			*dev = &gadget->dev;
626 	struct f_uac1			*uac1 = func_to_uac1(f);
627 	struct g_audio			*audio = func_to_g_audio(f);
628 	struct f_uac1_opts		*audio_opts;
629 	struct usb_ep			*ep = NULL;
630 	struct usb_string		*us;
631 	u8				*sam_freq;
632 	int				rate;
633 	int				ba_iface_id;
634 	int				status;
635 
636 	status = f_audio_validate_opts(audio, dev);
637 	if (status)
638 		return status;
639 
640 	audio_opts = container_of(f->fi, struct f_uac1_opts, func_inst);
641 
642 	us = usb_gstrings_attach(cdev, uac1_strings, ARRAY_SIZE(strings_uac1));
643 	if (IS_ERR(us))
644 		return PTR_ERR(us);
645 
646 	ac_header_desc = build_ac_header_desc(audio_opts);
647 	if (!ac_header_desc)
648 		return -ENOMEM;
649 
650 	ac_interface_desc.iInterface = us[STR_AC_IF].id;
651 	usb_out_it_desc.iTerminal = us[STR_USB_OUT_IT].id;
652 	usb_out_it_desc.iChannelNames = us[STR_USB_OUT_IT_CH_NAMES].id;
653 	io_out_ot_desc.iTerminal = us[STR_IO_OUT_OT].id;
654 	as_out_interface_alt_0_desc.iInterface = us[STR_AS_OUT_IF_ALT0].id;
655 	as_out_interface_alt_1_desc.iInterface = us[STR_AS_OUT_IF_ALT1].id;
656 	io_in_it_desc.iTerminal = us[STR_IO_IN_IT].id;
657 	io_in_it_desc.iChannelNames = us[STR_IO_IN_IT_CH_NAMES].id;
658 	usb_in_ot_desc.iTerminal = us[STR_USB_IN_OT].id;
659 	as_in_interface_alt_0_desc.iInterface = us[STR_AS_IN_IF_ALT0].id;
660 	as_in_interface_alt_1_desc.iInterface = us[STR_AS_IN_IF_ALT1].id;
661 
662 	/* Set channel numbers */
663 	usb_out_it_desc.bNrChannels = num_channels(audio_opts->c_chmask);
664 	usb_out_it_desc.wChannelConfig = cpu_to_le16(audio_opts->c_chmask);
665 	as_out_type_i_desc.bNrChannels = num_channels(audio_opts->c_chmask);
666 	as_out_type_i_desc.bSubframeSize = audio_opts->c_ssize;
667 	as_out_type_i_desc.bBitResolution = audio_opts->c_ssize * 8;
668 	io_in_it_desc.bNrChannels = num_channels(audio_opts->p_chmask);
669 	io_in_it_desc.wChannelConfig = cpu_to_le16(audio_opts->p_chmask);
670 	as_in_type_i_desc.bNrChannels = num_channels(audio_opts->p_chmask);
671 	as_in_type_i_desc.bSubframeSize = audio_opts->p_ssize;
672 	as_in_type_i_desc.bBitResolution = audio_opts->p_ssize * 8;
673 
674 	/* Set sample rates */
675 	rate = audio_opts->c_srate;
676 	sam_freq = as_out_type_i_desc.tSamFreq[0];
677 	memcpy(sam_freq, &rate, 3);
678 	rate = audio_opts->p_srate;
679 	sam_freq = as_in_type_i_desc.tSamFreq[0];
680 	memcpy(sam_freq, &rate, 3);
681 
682 	/* allocate instance-specific interface IDs, and patch descriptors */
683 	status = usb_interface_id(c, f);
684 	if (status < 0)
685 		goto fail;
686 	ac_interface_desc.bInterfaceNumber = status;
687 	uac1->ac_intf = status;
688 	uac1->ac_alt = 0;
689 
690 	ba_iface_id = 0;
691 
692 	if (EPOUT_EN(audio_opts)) {
693 		status = usb_interface_id(c, f);
694 		if (status < 0)
695 			goto fail;
696 		as_out_interface_alt_0_desc.bInterfaceNumber = status;
697 		as_out_interface_alt_1_desc.bInterfaceNumber = status;
698 		ac_header_desc->baInterfaceNr[ba_iface_id++] = status;
699 		uac1->as_out_intf = status;
700 		uac1->as_out_alt = 0;
701 	}
702 
703 	if (EPIN_EN(audio_opts)) {
704 		status = usb_interface_id(c, f);
705 		if (status < 0)
706 			goto fail;
707 		as_in_interface_alt_0_desc.bInterfaceNumber = status;
708 		as_in_interface_alt_1_desc.bInterfaceNumber = status;
709 		ac_header_desc->baInterfaceNr[ba_iface_id++] = status;
710 		uac1->as_in_intf = status;
711 		uac1->as_in_alt = 0;
712 	}
713 
714 	audio->gadget = gadget;
715 
716 	status = -ENODEV;
717 
718 	/* allocate instance-specific endpoints */
719 	if (EPOUT_EN(audio_opts)) {
720 		ep = usb_ep_autoconfig(cdev->gadget, &as_out_ep_desc);
721 		if (!ep)
722 			goto fail;
723 		audio->out_ep = ep;
724 		audio->out_ep->desc = &as_out_ep_desc;
725 	}
726 
727 	if (EPIN_EN(audio_opts)) {
728 		ep = usb_ep_autoconfig(cdev->gadget, &as_in_ep_desc);
729 		if (!ep)
730 			goto fail;
731 		audio->in_ep = ep;
732 		audio->in_ep->desc = &as_in_ep_desc;
733 	}
734 
735 	setup_descriptor(audio_opts);
736 
737 	/* copy descriptors, and track endpoint copies */
738 	status = usb_assign_descriptors(f, f_audio_desc, f_audio_desc, NULL,
739 					NULL);
740 	if (status)
741 		goto fail;
742 
743 	audio->out_ep_maxpsize = le16_to_cpu(as_out_ep_desc.wMaxPacketSize);
744 	audio->in_ep_maxpsize = le16_to_cpu(as_in_ep_desc.wMaxPacketSize);
745 	audio->params.c_chmask = audio_opts->c_chmask;
746 	audio->params.c_srate = audio_opts->c_srate;
747 	audio->params.c_ssize = audio_opts->c_ssize;
748 	audio->params.p_chmask = audio_opts->p_chmask;
749 	audio->params.p_srate = audio_opts->p_srate;
750 	audio->params.p_ssize = audio_opts->p_ssize;
751 	audio->params.req_number = audio_opts->req_number;
752 
753 	status = g_audio_setup(audio, "UAC1_PCM", "UAC1_Gadget");
754 	if (status)
755 		goto err_card_register;
756 
757 	return 0;
758 
759 err_card_register:
760 	usb_free_all_descriptors(f);
761 fail:
762 	kfree(ac_header_desc);
763 	ac_header_desc = NULL;
764 	return status;
765 }
766 
767 /*-------------------------------------------------------------------------*/
768 
769 static inline struct f_uac1_opts *to_f_uac1_opts(struct config_item *item)
770 {
771 	return container_of(to_config_group(item), struct f_uac1_opts,
772 			    func_inst.group);
773 }
774 
775 static void f_uac1_attr_release(struct config_item *item)
776 {
777 	struct f_uac1_opts *opts = to_f_uac1_opts(item);
778 
779 	usb_put_function_instance(&opts->func_inst);
780 }
781 
782 static struct configfs_item_operations f_uac1_item_ops = {
783 	.release	= f_uac1_attr_release,
784 };
785 
786 #define UAC1_ATTRIBUTE(name)						\
787 static ssize_t f_uac1_opts_##name##_show(				\
788 					  struct config_item *item,	\
789 					  char *page)			\
790 {									\
791 	struct f_uac1_opts *opts = to_f_uac1_opts(item);		\
792 	int result;							\
793 									\
794 	mutex_lock(&opts->lock);					\
795 	result = sprintf(page, "%u\n", opts->name);			\
796 	mutex_unlock(&opts->lock);					\
797 									\
798 	return result;							\
799 }									\
800 									\
801 static ssize_t f_uac1_opts_##name##_store(				\
802 					  struct config_item *item,	\
803 					  const char *page, size_t len)	\
804 {									\
805 	struct f_uac1_opts *opts = to_f_uac1_opts(item);		\
806 	int ret;							\
807 	u32 num;							\
808 									\
809 	mutex_lock(&opts->lock);					\
810 	if (opts->refcnt) {						\
811 		ret = -EBUSY;						\
812 		goto end;						\
813 	}								\
814 									\
815 	ret = kstrtou32(page, 0, &num);					\
816 	if (ret)							\
817 		goto end;						\
818 									\
819 	opts->name = num;						\
820 	ret = len;							\
821 									\
822 end:									\
823 	mutex_unlock(&opts->lock);					\
824 	return ret;							\
825 }									\
826 									\
827 CONFIGFS_ATTR(f_uac1_opts_, name)
828 
829 UAC1_ATTRIBUTE(c_chmask);
830 UAC1_ATTRIBUTE(c_srate);
831 UAC1_ATTRIBUTE(c_ssize);
832 UAC1_ATTRIBUTE(p_chmask);
833 UAC1_ATTRIBUTE(p_srate);
834 UAC1_ATTRIBUTE(p_ssize);
835 UAC1_ATTRIBUTE(req_number);
836 
837 static struct configfs_attribute *f_uac1_attrs[] = {
838 	&f_uac1_opts_attr_c_chmask,
839 	&f_uac1_opts_attr_c_srate,
840 	&f_uac1_opts_attr_c_ssize,
841 	&f_uac1_opts_attr_p_chmask,
842 	&f_uac1_opts_attr_p_srate,
843 	&f_uac1_opts_attr_p_ssize,
844 	&f_uac1_opts_attr_req_number,
845 	NULL,
846 };
847 
848 static const struct config_item_type f_uac1_func_type = {
849 	.ct_item_ops	= &f_uac1_item_ops,
850 	.ct_attrs	= f_uac1_attrs,
851 	.ct_owner	= THIS_MODULE,
852 };
853 
854 static void f_audio_free_inst(struct usb_function_instance *f)
855 {
856 	struct f_uac1_opts *opts;
857 
858 	opts = container_of(f, struct f_uac1_opts, func_inst);
859 	kfree(opts);
860 }
861 
862 static struct usb_function_instance *f_audio_alloc_inst(void)
863 {
864 	struct f_uac1_opts *opts;
865 
866 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
867 	if (!opts)
868 		return ERR_PTR(-ENOMEM);
869 
870 	mutex_init(&opts->lock);
871 	opts->func_inst.free_func_inst = f_audio_free_inst;
872 
873 	config_group_init_type_name(&opts->func_inst.group, "",
874 				    &f_uac1_func_type);
875 
876 	opts->c_chmask = UAC1_DEF_CCHMASK;
877 	opts->c_srate = UAC1_DEF_CSRATE;
878 	opts->c_ssize = UAC1_DEF_CSSIZE;
879 	opts->p_chmask = UAC1_DEF_PCHMASK;
880 	opts->p_srate = UAC1_DEF_PSRATE;
881 	opts->p_ssize = UAC1_DEF_PSSIZE;
882 	opts->req_number = UAC1_DEF_REQ_NUM;
883 	return &opts->func_inst;
884 }
885 
886 static void f_audio_free(struct usb_function *f)
887 {
888 	struct g_audio *audio;
889 	struct f_uac1_opts *opts;
890 
891 	audio = func_to_g_audio(f);
892 	opts = container_of(f->fi, struct f_uac1_opts, func_inst);
893 	kfree(audio);
894 	mutex_lock(&opts->lock);
895 	--opts->refcnt;
896 	mutex_unlock(&opts->lock);
897 }
898 
899 static void f_audio_unbind(struct usb_configuration *c, struct usb_function *f)
900 {
901 	struct g_audio *audio = func_to_g_audio(f);
902 
903 	g_audio_cleanup(audio);
904 	usb_free_all_descriptors(f);
905 
906 	kfree(ac_header_desc);
907 	ac_header_desc = NULL;
908 
909 	audio->gadget = NULL;
910 }
911 
912 static struct usb_function *f_audio_alloc(struct usb_function_instance *fi)
913 {
914 	struct f_uac1 *uac1;
915 	struct f_uac1_opts *opts;
916 
917 	/* allocate and initialize one new instance */
918 	uac1 = kzalloc(sizeof(*uac1), GFP_KERNEL);
919 	if (!uac1)
920 		return ERR_PTR(-ENOMEM);
921 
922 	opts = container_of(fi, struct f_uac1_opts, func_inst);
923 	mutex_lock(&opts->lock);
924 	++opts->refcnt;
925 	mutex_unlock(&opts->lock);
926 
927 	uac1->g_audio.func.name = "uac1_func";
928 	uac1->g_audio.func.bind = f_audio_bind;
929 	uac1->g_audio.func.unbind = f_audio_unbind;
930 	uac1->g_audio.func.set_alt = f_audio_set_alt;
931 	uac1->g_audio.func.get_alt = f_audio_get_alt;
932 	uac1->g_audio.func.setup = f_audio_setup;
933 	uac1->g_audio.func.disable = f_audio_disable;
934 	uac1->g_audio.func.free_func = f_audio_free;
935 
936 	return &uac1->g_audio.func;
937 }
938 
939 DECLARE_USB_FUNCTION_INIT(uac1, f_audio_alloc_inst, f_audio_alloc);
940 MODULE_LICENSE("GPL");
941 MODULE_AUTHOR("Ruslan Bilovol");
942