1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * f_uac2.c -- USB Audio Class 2.0 Function
4  *
5  * Copyright (C) 2011
6  *    Yadwinder Singh (yadi.brar01@gmail.com)
7  *    Jaswinder Singh (jaswinder.singh@linaro.org)
8  *
9  * Copyright (C) 2020
10  *    Ruslan Bilovol (ruslan.bilovol@gmail.com)
11  */
12 
13 #include <linux/usb/audio.h>
14 #include <linux/usb/audio-v2.h>
15 #include <linux/module.h>
16 
17 #include "u_audio.h"
18 
19 #include "u_uac2.h"
20 
21 /* UAC2 spec: 4.1 Audio Channel Cluster Descriptor */
22 #define UAC2_CHANNEL_MASK 0x07FFFFFF
23 
24 /*
25  * The driver implements a simple UAC_2 topology.
26  * USB-OUT -> IT_1 -> FU -> OT_3 -> ALSA_Capture
27  * ALSA_Playback -> IT_2 -> FU -> OT_4 -> USB-IN
28  * Capture and Playback sampling rates are independently
29  *  controlled by two clock sources :
30  *    CLK_5 := c_srate, and CLK_6 := p_srate
31  */
32 #define USB_OUT_CLK_ID	(out_clk_src_desc.bClockID)
33 #define USB_IN_CLK_ID	(in_clk_src_desc.bClockID)
34 #define USB_OUT_FU_ID	(out_feature_unit_desc->bUnitID)
35 #define USB_IN_FU_ID	(in_feature_unit_desc->bUnitID)
36 
37 #define CONTROL_ABSENT	0
38 #define CONTROL_RDONLY	1
39 #define CONTROL_RDWR	3
40 
41 #define CLK_FREQ_CTRL	0
42 #define CLK_VLD_CTRL	2
43 #define FU_MUTE_CTRL	0
44 #define FU_VOL_CTRL	2
45 
46 #define COPY_CTRL	0
47 #define CONN_CTRL	2
48 #define OVRLD_CTRL	4
49 #define CLSTR_CTRL	6
50 #define UNFLW_CTRL	8
51 #define OVFLW_CTRL	10
52 
53 #define EPIN_EN(_opts) ((_opts)->p_chmask != 0)
54 #define EPOUT_EN(_opts) ((_opts)->c_chmask != 0)
55 #define FUIN_EN(_opts) (EPIN_EN(_opts) \
56 				&& ((_opts)->p_mute_present \
57 				|| (_opts)->p_volume_present))
58 #define FUOUT_EN(_opts) (EPOUT_EN(_opts) \
59 				&& ((_opts)->c_mute_present \
60 				|| (_opts)->c_volume_present))
61 #define EPOUT_FBACK_IN_EN(_opts) ((_opts)->c_sync == USB_ENDPOINT_SYNC_ASYNC)
62 
63 struct f_uac2 {
64 	struct g_audio g_audio;
65 	u8 ac_intf, as_in_intf, as_out_intf;
66 	u8 ac_alt, as_in_alt, as_out_alt;	/* needed for get_alt() */
67 
68 	struct usb_ctrlrequest setup_cr;	/* will be used in data stage */
69 
70 	/* Interrupt IN endpoint of AC interface */
71 	struct usb_ep	*int_ep;
72 	atomic_t	int_count;
73 };
74 
75 static inline struct f_uac2 *func_to_uac2(struct usb_function *f)
76 {
77 	return container_of(f, struct f_uac2, g_audio.func);
78 }
79 
80 static inline
81 struct f_uac2_opts *g_audio_to_uac2_opts(struct g_audio *agdev)
82 {
83 	return container_of(agdev->func.fi, struct f_uac2_opts, func_inst);
84 }
85 
86 static int afunc_notify(struct g_audio *agdev, int unit_id, int cs);
87 
88 /* --------- USB Function Interface ------------- */
89 
90 enum {
91 	STR_ASSOC,
92 	STR_IF_CTRL,
93 	STR_CLKSRC_IN,
94 	STR_CLKSRC_OUT,
95 	STR_USB_IT,
96 	STR_IO_IT,
97 	STR_USB_OT,
98 	STR_IO_OT,
99 	STR_FU_IN,
100 	STR_FU_OUT,
101 	STR_AS_OUT_ALT0,
102 	STR_AS_OUT_ALT1,
103 	STR_AS_IN_ALT0,
104 	STR_AS_IN_ALT1,
105 };
106 
107 static char clksrc_in[8];
108 static char clksrc_out[8];
109 
110 static struct usb_string strings_fn[] = {
111 	[STR_ASSOC].s = "Source/Sink",
112 	[STR_IF_CTRL].s = "Topology Control",
113 	[STR_CLKSRC_IN].s = clksrc_in,
114 	[STR_CLKSRC_OUT].s = clksrc_out,
115 	[STR_USB_IT].s = "USBH Out",
116 	[STR_IO_IT].s = "USBD Out",
117 	[STR_USB_OT].s = "USBH In",
118 	[STR_IO_OT].s = "USBD In",
119 	[STR_FU_IN].s = "Capture Volume",
120 	[STR_FU_OUT].s = "Playback Volume",
121 	[STR_AS_OUT_ALT0].s = "Playback Inactive",
122 	[STR_AS_OUT_ALT1].s = "Playback Active",
123 	[STR_AS_IN_ALT0].s = "Capture Inactive",
124 	[STR_AS_IN_ALT1].s = "Capture Active",
125 	{ },
126 };
127 
128 static struct usb_gadget_strings str_fn = {
129 	.language = 0x0409,	/* en-us */
130 	.strings = strings_fn,
131 };
132 
133 static struct usb_gadget_strings *fn_strings[] = {
134 	&str_fn,
135 	NULL,
136 };
137 
138 static struct usb_interface_assoc_descriptor iad_desc = {
139 	.bLength = sizeof iad_desc,
140 	.bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
141 
142 	.bFirstInterface = 0,
143 	.bInterfaceCount = 3,
144 	.bFunctionClass = USB_CLASS_AUDIO,
145 	.bFunctionSubClass = UAC2_FUNCTION_SUBCLASS_UNDEFINED,
146 	.bFunctionProtocol = UAC_VERSION_2,
147 };
148 
149 /* Audio Control Interface */
150 static struct usb_interface_descriptor std_ac_if_desc = {
151 	.bLength = sizeof std_ac_if_desc,
152 	.bDescriptorType = USB_DT_INTERFACE,
153 
154 	.bAlternateSetting = 0,
155 	/* .bNumEndpoints = DYNAMIC */
156 	.bInterfaceClass = USB_CLASS_AUDIO,
157 	.bInterfaceSubClass = USB_SUBCLASS_AUDIOCONTROL,
158 	.bInterfaceProtocol = UAC_VERSION_2,
159 };
160 
161 /* Clock source for IN traffic */
162 static struct uac_clock_source_descriptor in_clk_src_desc = {
163 	.bLength = sizeof in_clk_src_desc,
164 	.bDescriptorType = USB_DT_CS_INTERFACE,
165 
166 	.bDescriptorSubtype = UAC2_CLOCK_SOURCE,
167 	/* .bClockID = DYNAMIC */
168 	.bmAttributes = UAC_CLOCK_SOURCE_TYPE_INT_FIXED,
169 	.bmControls = (CONTROL_RDONLY << CLK_FREQ_CTRL),
170 	.bAssocTerminal = 0,
171 };
172 
173 /* Clock source for OUT traffic */
174 static struct uac_clock_source_descriptor out_clk_src_desc = {
175 	.bLength = sizeof out_clk_src_desc,
176 	.bDescriptorType = USB_DT_CS_INTERFACE,
177 
178 	.bDescriptorSubtype = UAC2_CLOCK_SOURCE,
179 	/* .bClockID = DYNAMIC */
180 	.bmAttributes = UAC_CLOCK_SOURCE_TYPE_INT_FIXED,
181 	.bmControls = (CONTROL_RDONLY << CLK_FREQ_CTRL),
182 	.bAssocTerminal = 0,
183 };
184 
185 /* Input Terminal for USB_OUT */
186 static struct uac2_input_terminal_descriptor usb_out_it_desc = {
187 	.bLength = sizeof usb_out_it_desc,
188 	.bDescriptorType = USB_DT_CS_INTERFACE,
189 
190 	.bDescriptorSubtype = UAC_INPUT_TERMINAL,
191 	/* .bTerminalID = DYNAMIC */
192 	.wTerminalType = cpu_to_le16(UAC_TERMINAL_STREAMING),
193 	.bAssocTerminal = 0,
194 	/* .bCSourceID = DYNAMIC */
195 	.iChannelNames = 0,
196 	.bmControls = cpu_to_le16(CONTROL_RDWR << COPY_CTRL),
197 };
198 
199 /* Input Terminal for I/O-In */
200 static struct uac2_input_terminal_descriptor io_in_it_desc = {
201 	.bLength = sizeof io_in_it_desc,
202 	.bDescriptorType = USB_DT_CS_INTERFACE,
203 
204 	.bDescriptorSubtype = UAC_INPUT_TERMINAL,
205 	/* .bTerminalID = DYNAMIC */
206 	.wTerminalType = cpu_to_le16(UAC_INPUT_TERMINAL_UNDEFINED),
207 	.bAssocTerminal = 0,
208 	/* .bCSourceID = DYNAMIC */
209 	.iChannelNames = 0,
210 	.bmControls = cpu_to_le16(CONTROL_RDWR << COPY_CTRL),
211 };
212 
213 /* Ouput Terminal for USB_IN */
214 static struct uac2_output_terminal_descriptor usb_in_ot_desc = {
215 	.bLength = sizeof usb_in_ot_desc,
216 	.bDescriptorType = USB_DT_CS_INTERFACE,
217 
218 	.bDescriptorSubtype = UAC_OUTPUT_TERMINAL,
219 	/* .bTerminalID = DYNAMIC */
220 	.wTerminalType = cpu_to_le16(UAC_TERMINAL_STREAMING),
221 	.bAssocTerminal = 0,
222 	/* .bSourceID = DYNAMIC */
223 	/* .bCSourceID = DYNAMIC */
224 	.bmControls = cpu_to_le16(CONTROL_RDWR << COPY_CTRL),
225 };
226 
227 /* Ouput Terminal for I/O-Out */
228 static struct uac2_output_terminal_descriptor io_out_ot_desc = {
229 	.bLength = sizeof io_out_ot_desc,
230 	.bDescriptorType = USB_DT_CS_INTERFACE,
231 
232 	.bDescriptorSubtype = UAC_OUTPUT_TERMINAL,
233 	/* .bTerminalID = DYNAMIC */
234 	.wTerminalType = cpu_to_le16(UAC_OUTPUT_TERMINAL_UNDEFINED),
235 	.bAssocTerminal = 0,
236 	/* .bSourceID = DYNAMIC */
237 	/* .bCSourceID = DYNAMIC */
238 	.bmControls = cpu_to_le16(CONTROL_RDWR << COPY_CTRL),
239 };
240 
241 static struct uac2_feature_unit_descriptor *in_feature_unit_desc;
242 static struct uac2_feature_unit_descriptor *out_feature_unit_desc;
243 
244 static struct uac2_ac_header_descriptor ac_hdr_desc = {
245 	.bLength = sizeof ac_hdr_desc,
246 	.bDescriptorType = USB_DT_CS_INTERFACE,
247 
248 	.bDescriptorSubtype = UAC_MS_HEADER,
249 	.bcdADC = cpu_to_le16(0x200),
250 	.bCategory = UAC2_FUNCTION_IO_BOX,
251 	/* .wTotalLength = DYNAMIC */
252 	.bmControls = 0,
253 };
254 
255 /* AC IN Interrupt Endpoint */
256 static struct usb_endpoint_descriptor fs_ep_int_desc = {
257 	.bLength = USB_DT_ENDPOINT_SIZE,
258 	.bDescriptorType = USB_DT_ENDPOINT,
259 
260 	.bEndpointAddress = USB_DIR_IN,
261 	.bmAttributes = USB_ENDPOINT_XFER_INT,
262 	.wMaxPacketSize = cpu_to_le16(6),
263 	.bInterval = 1,
264 };
265 
266 static struct usb_endpoint_descriptor hs_ep_int_desc = {
267 	.bLength = USB_DT_ENDPOINT_SIZE,
268 	.bDescriptorType = USB_DT_ENDPOINT,
269 
270 	.bmAttributes = USB_ENDPOINT_XFER_INT,
271 	.wMaxPacketSize = cpu_to_le16(6),
272 	.bInterval = 4,
273 };
274 
275 static struct usb_endpoint_descriptor ss_ep_int_desc = {
276 	.bLength = USB_DT_ENDPOINT_SIZE,
277 	.bDescriptorType = USB_DT_ENDPOINT,
278 
279 	.bEndpointAddress = USB_DIR_IN,
280 	.bmAttributes = USB_ENDPOINT_XFER_INT,
281 	.wMaxPacketSize = cpu_to_le16(6),
282 	.bInterval = 4,
283 };
284 
285 /* Audio Streaming OUT Interface - Alt0 */
286 static struct usb_interface_descriptor std_as_out_if0_desc = {
287 	.bLength = sizeof std_as_out_if0_desc,
288 	.bDescriptorType = USB_DT_INTERFACE,
289 
290 	.bAlternateSetting = 0,
291 	.bNumEndpoints = 0,
292 	.bInterfaceClass = USB_CLASS_AUDIO,
293 	.bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
294 	.bInterfaceProtocol = UAC_VERSION_2,
295 };
296 
297 /* Audio Streaming OUT Interface - Alt1 */
298 static struct usb_interface_descriptor std_as_out_if1_desc = {
299 	.bLength = sizeof std_as_out_if1_desc,
300 	.bDescriptorType = USB_DT_INTERFACE,
301 
302 	.bAlternateSetting = 1,
303 	.bNumEndpoints = 1,
304 	.bInterfaceClass = USB_CLASS_AUDIO,
305 	.bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
306 	.bInterfaceProtocol = UAC_VERSION_2,
307 };
308 
309 /* Audio Stream OUT Intface Desc */
310 static struct uac2_as_header_descriptor as_out_hdr_desc = {
311 	.bLength = sizeof as_out_hdr_desc,
312 	.bDescriptorType = USB_DT_CS_INTERFACE,
313 
314 	.bDescriptorSubtype = UAC_AS_GENERAL,
315 	/* .bTerminalLink = DYNAMIC */
316 	.bmControls = 0,
317 	.bFormatType = UAC_FORMAT_TYPE_I,
318 	.bmFormats = cpu_to_le32(UAC_FORMAT_TYPE_I_PCM),
319 	.iChannelNames = 0,
320 };
321 
322 /* Audio USB_OUT Format */
323 static struct uac2_format_type_i_descriptor as_out_fmt1_desc = {
324 	.bLength = sizeof as_out_fmt1_desc,
325 	.bDescriptorType = USB_DT_CS_INTERFACE,
326 	.bDescriptorSubtype = UAC_FORMAT_TYPE,
327 	.bFormatType = UAC_FORMAT_TYPE_I,
328 };
329 
330 /* STD AS ISO OUT Endpoint */
331 static struct usb_endpoint_descriptor fs_epout_desc = {
332 	.bLength = USB_DT_ENDPOINT_SIZE,
333 	.bDescriptorType = USB_DT_ENDPOINT,
334 
335 	.bEndpointAddress = USB_DIR_OUT,
336 	/* .bmAttributes = DYNAMIC */
337 	/* .wMaxPacketSize = DYNAMIC */
338 	.bInterval = 1,
339 };
340 
341 static struct usb_endpoint_descriptor hs_epout_desc = {
342 	.bLength = USB_DT_ENDPOINT_SIZE,
343 	.bDescriptorType = USB_DT_ENDPOINT,
344 
345 	/* .bmAttributes = DYNAMIC */
346 	/* .wMaxPacketSize = DYNAMIC */
347 	.bInterval = 4,
348 };
349 
350 static struct usb_endpoint_descriptor ss_epout_desc = {
351 	.bLength = USB_DT_ENDPOINT_SIZE,
352 	.bDescriptorType = USB_DT_ENDPOINT,
353 
354 	.bEndpointAddress = USB_DIR_OUT,
355 	/* .bmAttributes = DYNAMIC */
356 	/* .wMaxPacketSize = DYNAMIC */
357 	.bInterval = 4,
358 };
359 
360 static struct usb_ss_ep_comp_descriptor ss_epout_desc_comp = {
361 	.bLength		= sizeof(ss_epout_desc_comp),
362 	.bDescriptorType	= USB_DT_SS_ENDPOINT_COMP,
363 	.bMaxBurst		= 0,
364 	.bmAttributes		= 0,
365 	/* wBytesPerInterval = DYNAMIC */
366 };
367 
368 /* CS AS ISO OUT Endpoint */
369 static struct uac2_iso_endpoint_descriptor as_iso_out_desc = {
370 	.bLength = sizeof as_iso_out_desc,
371 	.bDescriptorType = USB_DT_CS_ENDPOINT,
372 
373 	.bDescriptorSubtype = UAC_EP_GENERAL,
374 	.bmAttributes = 0,
375 	.bmControls = 0,
376 	.bLockDelayUnits = 0,
377 	.wLockDelay = 0,
378 };
379 
380 /* STD AS ISO IN Feedback Endpoint */
381 static struct usb_endpoint_descriptor fs_epin_fback_desc = {
382 	.bLength = USB_DT_ENDPOINT_SIZE,
383 	.bDescriptorType = USB_DT_ENDPOINT,
384 
385 	.bEndpointAddress = USB_DIR_IN,
386 	.bmAttributes = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_USAGE_FEEDBACK,
387 	.wMaxPacketSize = cpu_to_le16(3),
388 	.bInterval = 1,
389 };
390 
391 static struct usb_endpoint_descriptor hs_epin_fback_desc = {
392 	.bLength = USB_DT_ENDPOINT_SIZE,
393 	.bDescriptorType = USB_DT_ENDPOINT,
394 
395 	.bmAttributes = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_USAGE_FEEDBACK,
396 	.wMaxPacketSize = cpu_to_le16(4),
397 	.bInterval = 4,
398 };
399 
400 static struct usb_endpoint_descriptor ss_epin_fback_desc = {
401 	.bLength = USB_DT_ENDPOINT_SIZE,
402 	.bDescriptorType = USB_DT_ENDPOINT,
403 
404 	.bEndpointAddress = USB_DIR_IN,
405 	.bmAttributes = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_USAGE_FEEDBACK,
406 	.wMaxPacketSize = cpu_to_le16(4),
407 	.bInterval = 4,
408 };
409 
410 static struct usb_ss_ep_comp_descriptor ss_epin_fback_desc_comp = {
411 	.bLength		= sizeof(ss_epin_fback_desc_comp),
412 	.bDescriptorType	= USB_DT_SS_ENDPOINT_COMP,
413 	.bMaxBurst		= 0,
414 	.bmAttributes		= 0,
415 	.wBytesPerInterval	= cpu_to_le16(4),
416 };
417 
418 
419 /* Audio Streaming IN Interface - Alt0 */
420 static struct usb_interface_descriptor std_as_in_if0_desc = {
421 	.bLength = sizeof std_as_in_if0_desc,
422 	.bDescriptorType = USB_DT_INTERFACE,
423 
424 	.bAlternateSetting = 0,
425 	.bNumEndpoints = 0,
426 	.bInterfaceClass = USB_CLASS_AUDIO,
427 	.bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
428 	.bInterfaceProtocol = UAC_VERSION_2,
429 };
430 
431 /* Audio Streaming IN Interface - Alt1 */
432 static struct usb_interface_descriptor std_as_in_if1_desc = {
433 	.bLength = sizeof std_as_in_if1_desc,
434 	.bDescriptorType = USB_DT_INTERFACE,
435 
436 	.bAlternateSetting = 1,
437 	.bNumEndpoints = 1,
438 	.bInterfaceClass = USB_CLASS_AUDIO,
439 	.bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
440 	.bInterfaceProtocol = UAC_VERSION_2,
441 };
442 
443 /* Audio Stream IN Intface Desc */
444 static struct uac2_as_header_descriptor as_in_hdr_desc = {
445 	.bLength = sizeof as_in_hdr_desc,
446 	.bDescriptorType = USB_DT_CS_INTERFACE,
447 
448 	.bDescriptorSubtype = UAC_AS_GENERAL,
449 	/* .bTerminalLink = DYNAMIC */
450 	.bmControls = 0,
451 	.bFormatType = UAC_FORMAT_TYPE_I,
452 	.bmFormats = cpu_to_le32(UAC_FORMAT_TYPE_I_PCM),
453 	.iChannelNames = 0,
454 };
455 
456 /* Audio USB_IN Format */
457 static struct uac2_format_type_i_descriptor as_in_fmt1_desc = {
458 	.bLength = sizeof as_in_fmt1_desc,
459 	.bDescriptorType = USB_DT_CS_INTERFACE,
460 	.bDescriptorSubtype = UAC_FORMAT_TYPE,
461 	.bFormatType = UAC_FORMAT_TYPE_I,
462 };
463 
464 /* STD AS ISO IN Endpoint */
465 static struct usb_endpoint_descriptor fs_epin_desc = {
466 	.bLength = USB_DT_ENDPOINT_SIZE,
467 	.bDescriptorType = USB_DT_ENDPOINT,
468 
469 	.bEndpointAddress = USB_DIR_IN,
470 	.bmAttributes = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC,
471 	/* .wMaxPacketSize = DYNAMIC */
472 	.bInterval = 1,
473 };
474 
475 static struct usb_endpoint_descriptor hs_epin_desc = {
476 	.bLength = USB_DT_ENDPOINT_SIZE,
477 	.bDescriptorType = USB_DT_ENDPOINT,
478 
479 	.bmAttributes = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC,
480 	/* .wMaxPacketSize = DYNAMIC */
481 	.bInterval = 4,
482 };
483 
484 static struct usb_endpoint_descriptor ss_epin_desc = {
485 	.bLength = USB_DT_ENDPOINT_SIZE,
486 	.bDescriptorType = USB_DT_ENDPOINT,
487 
488 	.bEndpointAddress = USB_DIR_IN,
489 	.bmAttributes = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC,
490 	/* .wMaxPacketSize = DYNAMIC */
491 	.bInterval = 4,
492 };
493 
494 static struct usb_ss_ep_comp_descriptor ss_epin_desc_comp = {
495 	.bLength		= sizeof(ss_epin_desc_comp),
496 	.bDescriptorType	= USB_DT_SS_ENDPOINT_COMP,
497 	.bMaxBurst		= 0,
498 	.bmAttributes		= 0,
499 	/* wBytesPerInterval = DYNAMIC */
500 };
501 
502 /* CS AS ISO IN Endpoint */
503 static struct uac2_iso_endpoint_descriptor as_iso_in_desc = {
504 	.bLength = sizeof as_iso_in_desc,
505 	.bDescriptorType = USB_DT_CS_ENDPOINT,
506 
507 	.bDescriptorSubtype = UAC_EP_GENERAL,
508 	.bmAttributes = 0,
509 	.bmControls = 0,
510 	.bLockDelayUnits = 0,
511 	.wLockDelay = 0,
512 };
513 
514 static struct usb_descriptor_header *fs_audio_desc[] = {
515 	(struct usb_descriptor_header *)&iad_desc,
516 	(struct usb_descriptor_header *)&std_ac_if_desc,
517 
518 	(struct usb_descriptor_header *)&ac_hdr_desc,
519 	(struct usb_descriptor_header *)&in_clk_src_desc,
520 	(struct usb_descriptor_header *)&out_clk_src_desc,
521 	(struct usb_descriptor_header *)&usb_out_it_desc,
522 	(struct usb_descriptor_header *)&out_feature_unit_desc,
523 	(struct usb_descriptor_header *)&io_in_it_desc,
524 	(struct usb_descriptor_header *)&usb_in_ot_desc,
525 	(struct usb_descriptor_header *)&in_feature_unit_desc,
526 	(struct usb_descriptor_header *)&io_out_ot_desc,
527 
528 	(struct usb_descriptor_header *)&fs_ep_int_desc,
529 
530 	(struct usb_descriptor_header *)&std_as_out_if0_desc,
531 	(struct usb_descriptor_header *)&std_as_out_if1_desc,
532 
533 	(struct usb_descriptor_header *)&as_out_hdr_desc,
534 	(struct usb_descriptor_header *)&as_out_fmt1_desc,
535 	(struct usb_descriptor_header *)&fs_epout_desc,
536 	(struct usb_descriptor_header *)&as_iso_out_desc,
537 	(struct usb_descriptor_header *)&fs_epin_fback_desc,
538 
539 	(struct usb_descriptor_header *)&std_as_in_if0_desc,
540 	(struct usb_descriptor_header *)&std_as_in_if1_desc,
541 
542 	(struct usb_descriptor_header *)&as_in_hdr_desc,
543 	(struct usb_descriptor_header *)&as_in_fmt1_desc,
544 	(struct usb_descriptor_header *)&fs_epin_desc,
545 	(struct usb_descriptor_header *)&as_iso_in_desc,
546 	NULL,
547 };
548 
549 static struct usb_descriptor_header *hs_audio_desc[] = {
550 	(struct usb_descriptor_header *)&iad_desc,
551 	(struct usb_descriptor_header *)&std_ac_if_desc,
552 
553 	(struct usb_descriptor_header *)&ac_hdr_desc,
554 	(struct usb_descriptor_header *)&in_clk_src_desc,
555 	(struct usb_descriptor_header *)&out_clk_src_desc,
556 	(struct usb_descriptor_header *)&usb_out_it_desc,
557 	(struct usb_descriptor_header *)&out_feature_unit_desc,
558 	(struct usb_descriptor_header *)&io_in_it_desc,
559 	(struct usb_descriptor_header *)&usb_in_ot_desc,
560 	(struct usb_descriptor_header *)&in_feature_unit_desc,
561 	(struct usb_descriptor_header *)&io_out_ot_desc,
562 
563 	(struct usb_descriptor_header *)&hs_ep_int_desc,
564 
565 	(struct usb_descriptor_header *)&std_as_out_if0_desc,
566 	(struct usb_descriptor_header *)&std_as_out_if1_desc,
567 
568 	(struct usb_descriptor_header *)&as_out_hdr_desc,
569 	(struct usb_descriptor_header *)&as_out_fmt1_desc,
570 	(struct usb_descriptor_header *)&hs_epout_desc,
571 	(struct usb_descriptor_header *)&as_iso_out_desc,
572 	(struct usb_descriptor_header *)&hs_epin_fback_desc,
573 
574 	(struct usb_descriptor_header *)&std_as_in_if0_desc,
575 	(struct usb_descriptor_header *)&std_as_in_if1_desc,
576 
577 	(struct usb_descriptor_header *)&as_in_hdr_desc,
578 	(struct usb_descriptor_header *)&as_in_fmt1_desc,
579 	(struct usb_descriptor_header *)&hs_epin_desc,
580 	(struct usb_descriptor_header *)&as_iso_in_desc,
581 	NULL,
582 };
583 
584 static struct usb_descriptor_header *ss_audio_desc[] = {
585 	(struct usb_descriptor_header *)&iad_desc,
586 	(struct usb_descriptor_header *)&std_ac_if_desc,
587 
588 	(struct usb_descriptor_header *)&ac_hdr_desc,
589 	(struct usb_descriptor_header *)&in_clk_src_desc,
590 	(struct usb_descriptor_header *)&out_clk_src_desc,
591 	(struct usb_descriptor_header *)&usb_out_it_desc,
592   (struct usb_descriptor_header *)&out_feature_unit_desc,
593 	(struct usb_descriptor_header *)&io_in_it_desc,
594 	(struct usb_descriptor_header *)&usb_in_ot_desc,
595 	(struct usb_descriptor_header *)&in_feature_unit_desc,
596 	(struct usb_descriptor_header *)&io_out_ot_desc,
597 
598   (struct usb_descriptor_header *)&ss_ep_int_desc,
599 
600 	(struct usb_descriptor_header *)&std_as_out_if0_desc,
601 	(struct usb_descriptor_header *)&std_as_out_if1_desc,
602 
603 	(struct usb_descriptor_header *)&as_out_hdr_desc,
604 	(struct usb_descriptor_header *)&as_out_fmt1_desc,
605 	(struct usb_descriptor_header *)&ss_epout_desc,
606 	(struct usb_descriptor_header *)&ss_epout_desc_comp,
607 	(struct usb_descriptor_header *)&as_iso_out_desc,
608 	(struct usb_descriptor_header *)&ss_epin_fback_desc,
609 	(struct usb_descriptor_header *)&ss_epin_fback_desc_comp,
610 
611 	(struct usb_descriptor_header *)&std_as_in_if0_desc,
612 	(struct usb_descriptor_header *)&std_as_in_if1_desc,
613 
614 	(struct usb_descriptor_header *)&as_in_hdr_desc,
615 	(struct usb_descriptor_header *)&as_in_fmt1_desc,
616 	(struct usb_descriptor_header *)&ss_epin_desc,
617 	(struct usb_descriptor_header *)&ss_epin_desc_comp,
618 	(struct usb_descriptor_header *)&as_iso_in_desc,
619 	NULL,
620 };
621 
622 struct cntrl_cur_lay2 {
623 	__le16	wCUR;
624 };
625 
626 struct cntrl_range_lay2 {
627 	__le16	wNumSubRanges;
628 	__le16	wMIN;
629 	__le16	wMAX;
630 	__le16	wRES;
631 } __packed;
632 
633 struct cntrl_cur_lay3 {
634 	__le32	dCUR;
635 };
636 
637 struct cntrl_range_lay3 {
638 	__le16	wNumSubRanges;
639 	__le32	dMIN;
640 	__le32	dMAX;
641 	__le32	dRES;
642 } __packed;
643 
644 static int set_ep_max_packet_size(const struct f_uac2_opts *uac2_opts,
645 	struct usb_endpoint_descriptor *ep_desc,
646 	enum usb_device_speed speed, bool is_playback)
647 {
648 	int chmask, srate, ssize;
649 	u16 max_size_bw, max_size_ep;
650 	unsigned int factor;
651 
652 	switch (speed) {
653 	case USB_SPEED_FULL:
654 		max_size_ep = 1023;
655 		factor = 1000;
656 		break;
657 
658 	case USB_SPEED_HIGH:
659 	case USB_SPEED_SUPER:
660 		max_size_ep = 1024;
661 		factor = 8000;
662 		break;
663 
664 	default:
665 		return -EINVAL;
666 	}
667 
668 	if (is_playback) {
669 		chmask = uac2_opts->p_chmask;
670 		srate = uac2_opts->p_srate;
671 		ssize = uac2_opts->p_ssize;
672 	} else {
673 		chmask = uac2_opts->c_chmask;
674 		srate = uac2_opts->c_srate;
675 		ssize = uac2_opts->c_ssize;
676 	}
677 
678 	if (is_playback || (uac2_opts->c_sync == USB_ENDPOINT_SYNC_ASYNC)) {
679 		// playback is always async, capture only when configured
680 		// Win10 requires max packet size + 1 frame
681 		srate = srate * (1000 + uac2_opts->fb_max) / 1000;
682 		// updated srate is always bigger, therefore DIV_ROUND_UP always yields +1
683 		max_size_bw = num_channels(chmask) * ssize *
684 			(DIV_ROUND_UP(srate, factor / (1 << (ep_desc->bInterval - 1))));
685 	} else {
686 		// adding 1 frame provision for Win10
687 		max_size_bw = num_channels(chmask) * ssize *
688 			(DIV_ROUND_UP(srate, factor / (1 << (ep_desc->bInterval - 1))) + 1);
689 	}
690 	ep_desc->wMaxPacketSize = cpu_to_le16(min_t(u16, max_size_bw,
691 						    max_size_ep));
692 
693 	return 0;
694 }
695 
696 static struct uac2_feature_unit_descriptor *build_fu_desc(int chmask)
697 {
698 	struct uac2_feature_unit_descriptor *fu_desc;
699 	int channels = num_channels(chmask);
700 	int fu_desc_size = UAC2_DT_FEATURE_UNIT_SIZE(channels);
701 
702 	fu_desc = kzalloc(fu_desc_size, GFP_KERNEL);
703 	if (!fu_desc)
704 		return NULL;
705 
706 	fu_desc->bLength = fu_desc_size;
707 	fu_desc->bDescriptorType = USB_DT_CS_INTERFACE;
708 
709 	fu_desc->bDescriptorSubtype = UAC_FEATURE_UNIT;
710 
711 	/* bUnitID, bSourceID and bmaControls will be defined later */
712 
713 	return fu_desc;
714 }
715 
716 /* Use macro to overcome line length limitation */
717 #define USBDHDR(p) (struct usb_descriptor_header *)(p)
718 
719 static void setup_headers(struct f_uac2_opts *opts,
720 			  struct usb_descriptor_header **headers,
721 			  enum usb_device_speed speed)
722 {
723 	struct usb_ss_ep_comp_descriptor *epout_desc_comp = NULL;
724 	struct usb_ss_ep_comp_descriptor *epin_desc_comp = NULL;
725 	struct usb_ss_ep_comp_descriptor *epin_fback_desc_comp = NULL;
726 	struct usb_endpoint_descriptor *epout_desc;
727 	struct usb_endpoint_descriptor *epin_desc;
728 	struct usb_endpoint_descriptor *epin_fback_desc;
729 	struct usb_endpoint_descriptor *ep_int_desc;
730 	int i;
731 
732 	switch (speed) {
733 	case USB_SPEED_FULL:
734 		epout_desc = &fs_epout_desc;
735 		epin_desc = &fs_epin_desc;
736 		epin_fback_desc = &fs_epin_fback_desc;
737 		ep_int_desc = &fs_ep_int_desc;
738 		break;
739 	case USB_SPEED_HIGH:
740 		epout_desc = &hs_epout_desc;
741 		epin_desc = &hs_epin_desc;
742 		epin_fback_desc = &hs_epin_fback_desc;
743 		ep_int_desc = &hs_ep_int_desc;
744 		break;
745 	default:
746 		epout_desc = &ss_epout_desc;
747 		epin_desc = &ss_epin_desc;
748 		epout_desc_comp = &ss_epout_desc_comp;
749 		epin_desc_comp = &ss_epin_desc_comp;
750 		epin_fback_desc = &ss_epin_fback_desc;
751 		epin_fback_desc_comp = &ss_epin_fback_desc_comp;
752 		ep_int_desc = &ss_ep_int_desc;
753 	}
754 
755 	i = 0;
756 	headers[i++] = USBDHDR(&iad_desc);
757 	headers[i++] = USBDHDR(&std_ac_if_desc);
758 	headers[i++] = USBDHDR(&ac_hdr_desc);
759 	if (EPIN_EN(opts))
760 		headers[i++] = USBDHDR(&in_clk_src_desc);
761 	if (EPOUT_EN(opts)) {
762 		headers[i++] = USBDHDR(&out_clk_src_desc);
763 		headers[i++] = USBDHDR(&usb_out_it_desc);
764 
765 		if (FUOUT_EN(opts))
766 			headers[i++] = USBDHDR(out_feature_unit_desc);
767 	}
768 
769 	if (EPIN_EN(opts)) {
770 		headers[i++] = USBDHDR(&io_in_it_desc);
771 
772 		if (FUIN_EN(opts))
773 			headers[i++] = USBDHDR(in_feature_unit_desc);
774 
775 		headers[i++] = USBDHDR(&usb_in_ot_desc);
776 	}
777 
778 	if (EPOUT_EN(opts))
779 		headers[i++] = USBDHDR(&io_out_ot_desc);
780 
781 	if (FUOUT_EN(opts) || FUIN_EN(opts))
782 		headers[i++] = USBDHDR(ep_int_desc);
783 
784 	if (EPOUT_EN(opts)) {
785 		headers[i++] = USBDHDR(&std_as_out_if0_desc);
786 		headers[i++] = USBDHDR(&std_as_out_if1_desc);
787 		headers[i++] = USBDHDR(&as_out_hdr_desc);
788 		headers[i++] = USBDHDR(&as_out_fmt1_desc);
789 		headers[i++] = USBDHDR(epout_desc);
790 		if (epout_desc_comp)
791 			headers[i++] = USBDHDR(epout_desc_comp);
792 
793 		headers[i++] = USBDHDR(&as_iso_out_desc);
794 
795 		if (EPOUT_FBACK_IN_EN(opts)) {
796 			headers[i++] = USBDHDR(epin_fback_desc);
797 			if (epin_fback_desc_comp)
798 				headers[i++] = USBDHDR(epin_fback_desc_comp);
799 		}
800 	}
801 
802 	if (EPIN_EN(opts)) {
803 		headers[i++] = USBDHDR(&std_as_in_if0_desc);
804 		headers[i++] = USBDHDR(&std_as_in_if1_desc);
805 		headers[i++] = USBDHDR(&as_in_hdr_desc);
806 		headers[i++] = USBDHDR(&as_in_fmt1_desc);
807 		headers[i++] = USBDHDR(epin_desc);
808 		if (epin_desc_comp)
809 			headers[i++] = USBDHDR(epin_desc_comp);
810 
811 		headers[i++] = USBDHDR(&as_iso_in_desc);
812 	}
813 	headers[i] = NULL;
814 }
815 
816 static void setup_descriptor(struct f_uac2_opts *opts)
817 {
818 	/* patch descriptors */
819 	int i = 1; /* ID's start with 1 */
820 
821 	if (EPOUT_EN(opts))
822 		usb_out_it_desc.bTerminalID = i++;
823 	if (EPIN_EN(opts))
824 		io_in_it_desc.bTerminalID = i++;
825 	if (EPOUT_EN(opts))
826 		io_out_ot_desc.bTerminalID = i++;
827 	if (EPIN_EN(opts))
828 		usb_in_ot_desc.bTerminalID = i++;
829 	if (FUOUT_EN(opts))
830 		out_feature_unit_desc->bUnitID = i++;
831 	if (FUIN_EN(opts))
832 		in_feature_unit_desc->bUnitID = i++;
833 	if (EPOUT_EN(opts))
834 		out_clk_src_desc.bClockID = i++;
835 	if (EPIN_EN(opts))
836 		in_clk_src_desc.bClockID = i++;
837 
838 	usb_out_it_desc.bCSourceID = out_clk_src_desc.bClockID;
839 
840 	if (FUIN_EN(opts)) {
841 		usb_in_ot_desc.bSourceID = in_feature_unit_desc->bUnitID;
842 		in_feature_unit_desc->bSourceID = io_in_it_desc.bTerminalID;
843 	} else {
844 		usb_in_ot_desc.bSourceID = io_in_it_desc.bTerminalID;
845 	}
846 
847 	usb_in_ot_desc.bCSourceID = in_clk_src_desc.bClockID;
848 	io_in_it_desc.bCSourceID = in_clk_src_desc.bClockID;
849 	io_out_ot_desc.bCSourceID = out_clk_src_desc.bClockID;
850 
851 	if (FUOUT_EN(opts)) {
852 		io_out_ot_desc.bSourceID = out_feature_unit_desc->bUnitID;
853 		out_feature_unit_desc->bSourceID = usb_out_it_desc.bTerminalID;
854 	} else {
855 		io_out_ot_desc.bSourceID = usb_out_it_desc.bTerminalID;
856 	}
857 
858 	as_out_hdr_desc.bTerminalLink = usb_out_it_desc.bTerminalID;
859 	as_in_hdr_desc.bTerminalLink = usb_in_ot_desc.bTerminalID;
860 
861 	iad_desc.bInterfaceCount = 1;
862 	ac_hdr_desc.wTotalLength = cpu_to_le16(sizeof(ac_hdr_desc));
863 
864 	if (EPIN_EN(opts)) {
865 		u16 len = le16_to_cpu(ac_hdr_desc.wTotalLength);
866 
867 		len += sizeof(in_clk_src_desc);
868 		len += sizeof(usb_in_ot_desc);
869 
870 		if (FUIN_EN(opts))
871 			len += in_feature_unit_desc->bLength;
872 
873 		len += sizeof(io_in_it_desc);
874 		ac_hdr_desc.wTotalLength = cpu_to_le16(len);
875 		iad_desc.bInterfaceCount++;
876 	}
877 	if (EPOUT_EN(opts)) {
878 		u16 len = le16_to_cpu(ac_hdr_desc.wTotalLength);
879 
880 		len += sizeof(out_clk_src_desc);
881 		len += sizeof(usb_out_it_desc);
882 
883 		if (FUOUT_EN(opts))
884 			len += out_feature_unit_desc->bLength;
885 
886 		len += sizeof(io_out_ot_desc);
887 		ac_hdr_desc.wTotalLength = cpu_to_le16(len);
888 		iad_desc.bInterfaceCount++;
889 	}
890 
891 	setup_headers(opts, fs_audio_desc, USB_SPEED_FULL);
892 	setup_headers(opts, hs_audio_desc, USB_SPEED_HIGH);
893 	setup_headers(opts, ss_audio_desc, USB_SPEED_SUPER);
894 }
895 
896 static int afunc_validate_opts(struct g_audio *agdev, struct device *dev)
897 {
898 	struct f_uac2_opts *opts = g_audio_to_uac2_opts(agdev);
899 
900 	if (!opts->p_chmask && !opts->c_chmask) {
901 		dev_err(dev, "Error: no playback and capture channels\n");
902 		return -EINVAL;
903 	} else if (opts->p_chmask & ~UAC2_CHANNEL_MASK) {
904 		dev_err(dev, "Error: unsupported playback channels mask\n");
905 		return -EINVAL;
906 	} else if (opts->c_chmask & ~UAC2_CHANNEL_MASK) {
907 		dev_err(dev, "Error: unsupported capture channels mask\n");
908 		return -EINVAL;
909 	} else if ((opts->p_ssize < 1) || (opts->p_ssize > 4)) {
910 		dev_err(dev, "Error: incorrect playback sample size\n");
911 		return -EINVAL;
912 	} else if ((opts->c_ssize < 1) || (opts->c_ssize > 4)) {
913 		dev_err(dev, "Error: incorrect capture sample size\n");
914 		return -EINVAL;
915 	} else if (!opts->p_srate) {
916 		dev_err(dev, "Error: incorrect playback sampling rate\n");
917 		return -EINVAL;
918 	} else if (!opts->c_srate) {
919 		dev_err(dev, "Error: incorrect capture sampling rate\n");
920 		return -EINVAL;
921 	}
922 
923 	if (opts->p_volume_max <= opts->p_volume_min) {
924 		dev_err(dev, "Error: incorrect playback volume max/min\n");
925 			return -EINVAL;
926 	} else if (opts->c_volume_max <= opts->c_volume_min) {
927 		dev_err(dev, "Error: incorrect capture volume max/min\n");
928 			return -EINVAL;
929 	} else if (opts->p_volume_res <= 0) {
930 		dev_err(dev, "Error: negative/zero playback volume resolution\n");
931 			return -EINVAL;
932 	} else if (opts->c_volume_res <= 0) {
933 		dev_err(dev, "Error: negative/zero capture volume resolution\n");
934 			return -EINVAL;
935 	}
936 
937 	if ((opts->p_volume_max - opts->p_volume_min) % opts->p_volume_res) {
938 		dev_err(dev, "Error: incorrect playback volume resolution\n");
939 			return -EINVAL;
940 	} else if ((opts->c_volume_max - opts->c_volume_min) % opts->c_volume_res) {
941 		dev_err(dev, "Error: incorrect capture volume resolution\n");
942 			return -EINVAL;
943 	}
944 
945 	return 0;
946 }
947 
948 static int
949 afunc_bind(struct usb_configuration *cfg, struct usb_function *fn)
950 {
951 	struct f_uac2 *uac2 = func_to_uac2(fn);
952 	struct g_audio *agdev = func_to_g_audio(fn);
953 	struct usb_composite_dev *cdev = cfg->cdev;
954 	struct usb_gadget *gadget = cdev->gadget;
955 	struct device *dev = &gadget->dev;
956 	struct f_uac2_opts *uac2_opts = g_audio_to_uac2_opts(agdev);
957 	struct usb_string *us;
958 	int ret;
959 
960 	ret = afunc_validate_opts(agdev, dev);
961 	if (ret)
962 		return ret;
963 
964 	us = usb_gstrings_attach(cdev, fn_strings, ARRAY_SIZE(strings_fn));
965 	if (IS_ERR(us))
966 		return PTR_ERR(us);
967 
968 	if (FUOUT_EN(uac2_opts)) {
969 		out_feature_unit_desc = build_fu_desc(uac2_opts->c_chmask);
970 		if (!out_feature_unit_desc)
971 			return -ENOMEM;
972 	}
973 	if (FUIN_EN(uac2_opts)) {
974 		in_feature_unit_desc = build_fu_desc(uac2_opts->p_chmask);
975 		if (!in_feature_unit_desc) {
976 			ret = -ENOMEM;
977 			goto err_free_fu;
978 		}
979 	}
980 
981 	iad_desc.iFunction = us[STR_ASSOC].id;
982 	std_ac_if_desc.iInterface = us[STR_IF_CTRL].id;
983 	in_clk_src_desc.iClockSource = us[STR_CLKSRC_IN].id;
984 	out_clk_src_desc.iClockSource = us[STR_CLKSRC_OUT].id;
985 	usb_out_it_desc.iTerminal = us[STR_USB_IT].id;
986 	io_in_it_desc.iTerminal = us[STR_IO_IT].id;
987 	usb_in_ot_desc.iTerminal = us[STR_USB_OT].id;
988 	io_out_ot_desc.iTerminal = us[STR_IO_OT].id;
989 	std_as_out_if0_desc.iInterface = us[STR_AS_OUT_ALT0].id;
990 	std_as_out_if1_desc.iInterface = us[STR_AS_OUT_ALT1].id;
991 	std_as_in_if0_desc.iInterface = us[STR_AS_IN_ALT0].id;
992 	std_as_in_if1_desc.iInterface = us[STR_AS_IN_ALT1].id;
993 
994 	if (FUOUT_EN(uac2_opts)) {
995 		u8 *i_feature = (u8 *)out_feature_unit_desc +
996 				out_feature_unit_desc->bLength - 1;
997 		*i_feature = us[STR_FU_OUT].id;
998 	}
999 	if (FUIN_EN(uac2_opts)) {
1000 		u8 *i_feature = (u8 *)in_feature_unit_desc +
1001 				in_feature_unit_desc->bLength - 1;
1002 		*i_feature = us[STR_FU_IN].id;
1003 	}
1004 
1005 
1006 	/* Initialize the configurable parameters */
1007 	usb_out_it_desc.bNrChannels = num_channels(uac2_opts->c_chmask);
1008 	usb_out_it_desc.bmChannelConfig = cpu_to_le32(uac2_opts->c_chmask);
1009 	io_in_it_desc.bNrChannels = num_channels(uac2_opts->p_chmask);
1010 	io_in_it_desc.bmChannelConfig = cpu_to_le32(uac2_opts->p_chmask);
1011 	as_out_hdr_desc.bNrChannels = num_channels(uac2_opts->c_chmask);
1012 	as_out_hdr_desc.bmChannelConfig = cpu_to_le32(uac2_opts->c_chmask);
1013 	as_in_hdr_desc.bNrChannels = num_channels(uac2_opts->p_chmask);
1014 	as_in_hdr_desc.bmChannelConfig = cpu_to_le32(uac2_opts->p_chmask);
1015 	as_out_fmt1_desc.bSubslotSize = uac2_opts->c_ssize;
1016 	as_out_fmt1_desc.bBitResolution = uac2_opts->c_ssize * 8;
1017 	as_in_fmt1_desc.bSubslotSize = uac2_opts->p_ssize;
1018 	as_in_fmt1_desc.bBitResolution = uac2_opts->p_ssize * 8;
1019 	if (FUOUT_EN(uac2_opts)) {
1020 		__le32 *bma = (__le32 *)&out_feature_unit_desc->bmaControls[0];
1021 		u32 control = 0;
1022 
1023 		if (uac2_opts->c_mute_present)
1024 			control |= CONTROL_RDWR << FU_MUTE_CTRL;
1025 		if (uac2_opts->c_volume_present)
1026 			control |= CONTROL_RDWR << FU_VOL_CTRL;
1027 		*bma = cpu_to_le32(control);
1028 	}
1029 	if (FUIN_EN(uac2_opts)) {
1030 		__le32 *bma = (__le32 *)&in_feature_unit_desc->bmaControls[0];
1031 		u32 control = 0;
1032 
1033 		if (uac2_opts->p_mute_present)
1034 			control |= CONTROL_RDWR << FU_MUTE_CTRL;
1035 		if (uac2_opts->p_volume_present)
1036 			control |= CONTROL_RDWR << FU_VOL_CTRL;
1037 		*bma = cpu_to_le32(control);
1038 	}
1039 
1040 	snprintf(clksrc_in, sizeof(clksrc_in), "%uHz", uac2_opts->p_srate);
1041 	snprintf(clksrc_out, sizeof(clksrc_out), "%uHz", uac2_opts->c_srate);
1042 
1043 	ret = usb_interface_id(cfg, fn);
1044 	if (ret < 0) {
1045 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1046 		goto err_free_fu;
1047 	}
1048 	iad_desc.bFirstInterface = ret;
1049 
1050 	std_ac_if_desc.bInterfaceNumber = ret;
1051 	uac2->ac_intf = ret;
1052 	uac2->ac_alt = 0;
1053 
1054 	if (EPOUT_EN(uac2_opts)) {
1055 		ret = usb_interface_id(cfg, fn);
1056 		if (ret < 0) {
1057 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1058 			goto err_free_fu;
1059 		}
1060 		std_as_out_if0_desc.bInterfaceNumber = ret;
1061 		std_as_out_if1_desc.bInterfaceNumber = ret;
1062 		uac2->as_out_intf = ret;
1063 		uac2->as_out_alt = 0;
1064 
1065 		if (EPOUT_FBACK_IN_EN(uac2_opts)) {
1066 			fs_epout_desc.bmAttributes =
1067 			  USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC;
1068 			hs_epout_desc.bmAttributes =
1069 			  USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC;
1070 			ss_epout_desc.bmAttributes =
1071 			  USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC;
1072 			std_as_out_if1_desc.bNumEndpoints++;
1073 		} else {
1074 			fs_epout_desc.bmAttributes =
1075 			  USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ADAPTIVE;
1076 			hs_epout_desc.bmAttributes =
1077 			  USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ADAPTIVE;
1078 			ss_epout_desc.bmAttributes =
1079 			  USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ADAPTIVE;
1080 		}
1081 	}
1082 
1083 	if (EPIN_EN(uac2_opts)) {
1084 		ret = usb_interface_id(cfg, fn);
1085 		if (ret < 0) {
1086 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1087 			goto err_free_fu;
1088 		}
1089 		std_as_in_if0_desc.bInterfaceNumber = ret;
1090 		std_as_in_if1_desc.bInterfaceNumber = ret;
1091 		uac2->as_in_intf = ret;
1092 		uac2->as_in_alt = 0;
1093 	}
1094 
1095 	if (FUOUT_EN(uac2_opts) || FUIN_EN(uac2_opts)) {
1096 		uac2->int_ep = usb_ep_autoconfig(gadget, &fs_ep_int_desc);
1097 		if (!uac2->int_ep) {
1098 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1099 			ret = -ENODEV;
1100 			goto err_free_fu;
1101 		}
1102 
1103 		std_ac_if_desc.bNumEndpoints = 1;
1104 	}
1105 
1106 	/* Calculate wMaxPacketSize according to audio bandwidth */
1107 	ret = set_ep_max_packet_size(uac2_opts, &fs_epin_desc, USB_SPEED_FULL,
1108 				     true);
1109 	if (ret < 0) {
1110 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1111 		return ret;
1112 	}
1113 
1114 	ret = set_ep_max_packet_size(uac2_opts, &fs_epout_desc, USB_SPEED_FULL,
1115 				     false);
1116 	if (ret < 0) {
1117 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1118 		return ret;
1119 	}
1120 
1121 	ret = set_ep_max_packet_size(uac2_opts, &hs_epin_desc, USB_SPEED_HIGH,
1122 				     true);
1123 	if (ret < 0) {
1124 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1125 		return ret;
1126 	}
1127 
1128 	ret = set_ep_max_packet_size(uac2_opts, &hs_epout_desc, USB_SPEED_HIGH,
1129 				     false);
1130 	if (ret < 0) {
1131 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1132 		return ret;
1133 	}
1134 
1135 	ret = set_ep_max_packet_size(uac2_opts, &ss_epin_desc, USB_SPEED_SUPER,
1136 				     true);
1137 	if (ret < 0) {
1138 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1139 		return ret;
1140 	}
1141 
1142 	ret = set_ep_max_packet_size(uac2_opts, &ss_epout_desc, USB_SPEED_SUPER,
1143 				     false);
1144 	if (ret < 0) {
1145 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1146 		return ret;
1147 	}
1148 
1149 	if (EPOUT_EN(uac2_opts)) {
1150 		agdev->out_ep = usb_ep_autoconfig(gadget, &fs_epout_desc);
1151 		if (!agdev->out_ep) {
1152 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1153 			ret = -ENODEV;
1154 			goto err_free_fu;
1155 		}
1156 		if (EPOUT_FBACK_IN_EN(uac2_opts)) {
1157 			agdev->in_ep_fback = usb_ep_autoconfig(gadget,
1158 						       &fs_epin_fback_desc);
1159 			if (!agdev->in_ep_fback) {
1160 				dev_err(dev, "%s:%d Error!\n",
1161 					__func__, __LINE__);
1162 				ret = -ENODEV;
1163 				goto err_free_fu;
1164 			}
1165 		}
1166 	}
1167 
1168 	if (EPIN_EN(uac2_opts)) {
1169 		agdev->in_ep = usb_ep_autoconfig(gadget, &fs_epin_desc);
1170 		if (!agdev->in_ep) {
1171 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1172 			ret = -ENODEV;
1173 			goto err_free_fu;
1174 		}
1175 	}
1176 
1177 	agdev->in_ep_maxpsize = max_t(u16,
1178 				le16_to_cpu(fs_epin_desc.wMaxPacketSize),
1179 				le16_to_cpu(hs_epin_desc.wMaxPacketSize));
1180 	agdev->out_ep_maxpsize = max_t(u16,
1181 				le16_to_cpu(fs_epout_desc.wMaxPacketSize),
1182 				le16_to_cpu(hs_epout_desc.wMaxPacketSize));
1183 
1184 	agdev->in_ep_maxpsize = max_t(u16, agdev->in_ep_maxpsize,
1185 				le16_to_cpu(ss_epin_desc.wMaxPacketSize));
1186 	agdev->out_ep_maxpsize = max_t(u16, agdev->out_ep_maxpsize,
1187 				le16_to_cpu(ss_epout_desc.wMaxPacketSize));
1188 
1189 	ss_epin_desc_comp.wBytesPerInterval = ss_epin_desc.wMaxPacketSize;
1190 	ss_epout_desc_comp.wBytesPerInterval = ss_epout_desc.wMaxPacketSize;
1191 
1192 	// HS and SS endpoint addresses are copied from autoconfigured FS descriptors
1193 	hs_ep_int_desc.bEndpointAddress = fs_ep_int_desc.bEndpointAddress;
1194 	hs_epout_desc.bEndpointAddress = fs_epout_desc.bEndpointAddress;
1195 	hs_epin_fback_desc.bEndpointAddress = fs_epin_fback_desc.bEndpointAddress;
1196 	hs_epin_desc.bEndpointAddress = fs_epin_desc.bEndpointAddress;
1197 	ss_epout_desc.bEndpointAddress = fs_epout_desc.bEndpointAddress;
1198 	ss_epin_fback_desc.bEndpointAddress = fs_epin_fback_desc.bEndpointAddress;
1199 	ss_epin_desc.bEndpointAddress = fs_epin_desc.bEndpointAddress;
1200 	ss_ep_int_desc.bEndpointAddress = fs_ep_int_desc.bEndpointAddress;
1201 
1202 	setup_descriptor(uac2_opts);
1203 
1204 	ret = usb_assign_descriptors(fn, fs_audio_desc, hs_audio_desc, ss_audio_desc,
1205 				     ss_audio_desc);
1206 	if (ret)
1207 		goto err_free_fu;
1208 
1209 	agdev->gadget = gadget;
1210 
1211 	agdev->params.p_chmask = uac2_opts->p_chmask;
1212 	agdev->params.p_srate = uac2_opts->p_srate;
1213 	agdev->params.p_ssize = uac2_opts->p_ssize;
1214 	if (FUIN_EN(uac2_opts)) {
1215 		agdev->params.p_fu.id = USB_IN_FU_ID;
1216 		agdev->params.p_fu.mute_present = uac2_opts->p_mute_present;
1217 		agdev->params.p_fu.volume_present = uac2_opts->p_volume_present;
1218 		agdev->params.p_fu.volume_min = uac2_opts->p_volume_min;
1219 		agdev->params.p_fu.volume_max = uac2_opts->p_volume_max;
1220 		agdev->params.p_fu.volume_res = uac2_opts->p_volume_res;
1221 	}
1222 	agdev->params.c_chmask = uac2_opts->c_chmask;
1223 	agdev->params.c_srate = uac2_opts->c_srate;
1224 	agdev->params.c_ssize = uac2_opts->c_ssize;
1225 	if (FUOUT_EN(uac2_opts)) {
1226 		agdev->params.c_fu.id = USB_OUT_FU_ID;
1227 		agdev->params.c_fu.mute_present = uac2_opts->c_mute_present;
1228 		agdev->params.c_fu.volume_present = uac2_opts->c_volume_present;
1229 		agdev->params.c_fu.volume_min = uac2_opts->c_volume_min;
1230 		agdev->params.c_fu.volume_max = uac2_opts->c_volume_max;
1231 		agdev->params.c_fu.volume_res = uac2_opts->c_volume_res;
1232 	}
1233 	agdev->params.req_number = uac2_opts->req_number;
1234 	agdev->params.fb_max = uac2_opts->fb_max;
1235 
1236 	if (FUOUT_EN(uac2_opts) || FUIN_EN(uac2_opts))
1237     agdev->notify = afunc_notify;
1238 
1239 	ret = g_audio_setup(agdev, "UAC2 PCM", "UAC2_Gadget");
1240 	if (ret)
1241 		goto err_free_descs;
1242 
1243 	return 0;
1244 
1245 err_free_descs:
1246 	usb_free_all_descriptors(fn);
1247 	agdev->gadget = NULL;
1248 err_free_fu:
1249 	kfree(out_feature_unit_desc);
1250 	out_feature_unit_desc = NULL;
1251 	kfree(in_feature_unit_desc);
1252 	in_feature_unit_desc = NULL;
1253 	return ret;
1254 }
1255 
1256 static void
1257 afunc_notify_complete(struct usb_ep *_ep, struct usb_request *req)
1258 {
1259 	struct g_audio *agdev = req->context;
1260 	struct f_uac2 *uac2 = func_to_uac2(&agdev->func);
1261 
1262 	atomic_dec(&uac2->int_count);
1263 	kfree(req->buf);
1264 	usb_ep_free_request(_ep, req);
1265 }
1266 
1267 static int
1268 afunc_notify(struct g_audio *agdev, int unit_id, int cs)
1269 {
1270 	struct f_uac2 *uac2 = func_to_uac2(&agdev->func);
1271 	struct usb_request *req;
1272 	struct uac2_interrupt_data_msg *msg;
1273 	u16 w_index, w_value;
1274 	int ret;
1275 
1276 	if (!uac2->int_ep->enabled)
1277 		return 0;
1278 
1279 	if (atomic_inc_return(&uac2->int_count) > UAC2_DEF_INT_REQ_NUM) {
1280 		atomic_dec(&uac2->int_count);
1281 		return 0;
1282 	}
1283 
1284 	req = usb_ep_alloc_request(uac2->int_ep, GFP_ATOMIC);
1285 	if (req == NULL) {
1286 		ret = -ENOMEM;
1287 		goto err_dec_int_count;
1288 	}
1289 
1290 	msg = kzalloc(sizeof(*msg), GFP_ATOMIC);
1291 	if (msg == NULL) {
1292 		ret = -ENOMEM;
1293 		goto err_free_request;
1294 	}
1295 
1296 	w_index = unit_id << 8 | uac2->ac_intf;
1297 	w_value = cs << 8;
1298 
1299 	msg->bInfo = 0; /* Non-vendor, interface interrupt */
1300 	msg->bAttribute = UAC2_CS_CUR;
1301 	msg->wIndex = cpu_to_le16(w_index);
1302 	msg->wValue = cpu_to_le16(w_value);
1303 
1304 	req->length = sizeof(*msg);
1305 	req->buf = msg;
1306 	req->context = agdev;
1307 	req->complete = afunc_notify_complete;
1308 
1309 	ret = usb_ep_queue(uac2->int_ep, req, GFP_ATOMIC);
1310 
1311 	if (ret)
1312 		goto err_free_msg;
1313 
1314 	return 0;
1315 
1316 err_free_msg:
1317 	kfree(msg);
1318 err_free_request:
1319 	usb_ep_free_request(uac2->int_ep, req);
1320 err_dec_int_count:
1321 	atomic_dec(&uac2->int_count);
1322 
1323 	return ret;
1324 }
1325 
1326 static int
1327 afunc_set_alt(struct usb_function *fn, unsigned intf, unsigned alt)
1328 {
1329 	struct usb_composite_dev *cdev = fn->config->cdev;
1330 	struct f_uac2 *uac2 = func_to_uac2(fn);
1331 	struct g_audio *agdev = func_to_g_audio(fn);
1332 	struct usb_gadget *gadget = cdev->gadget;
1333 	struct device *dev = &gadget->dev;
1334 	int ret = 0;
1335 
1336 	/* No i/f has more than 2 alt settings */
1337 	if (alt > 1) {
1338 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1339 		return -EINVAL;
1340 	}
1341 
1342 	if (intf == uac2->ac_intf) {
1343 		/* Control I/f has only 1 AltSetting - 0 */
1344 		if (alt) {
1345 			dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1346 			return -EINVAL;
1347 		}
1348 
1349 		/* restart interrupt endpoint */
1350 		if (uac2->int_ep) {
1351 			usb_ep_disable(uac2->int_ep);
1352 			config_ep_by_speed(gadget, &agdev->func, uac2->int_ep);
1353 			usb_ep_enable(uac2->int_ep);
1354 		}
1355 
1356 		return 0;
1357 	}
1358 
1359 	if (intf == uac2->as_out_intf) {
1360 		uac2->as_out_alt = alt;
1361 
1362 		if (alt)
1363 			ret = u_audio_start_capture(&uac2->g_audio);
1364 		else
1365 			u_audio_stop_capture(&uac2->g_audio);
1366 	} else if (intf == uac2->as_in_intf) {
1367 		uac2->as_in_alt = alt;
1368 
1369 		if (alt)
1370 			ret = u_audio_start_playback(&uac2->g_audio);
1371 		else
1372 			u_audio_stop_playback(&uac2->g_audio);
1373 	} else {
1374 		dev_err(dev, "%s:%d Error!\n", __func__, __LINE__);
1375 		return -EINVAL;
1376 	}
1377 
1378 	return ret;
1379 }
1380 
1381 static int
1382 afunc_get_alt(struct usb_function *fn, unsigned intf)
1383 {
1384 	struct f_uac2 *uac2 = func_to_uac2(fn);
1385 	struct g_audio *agdev = func_to_g_audio(fn);
1386 
1387 	if (intf == uac2->ac_intf)
1388 		return uac2->ac_alt;
1389 	else if (intf == uac2->as_out_intf)
1390 		return uac2->as_out_alt;
1391 	else if (intf == uac2->as_in_intf)
1392 		return uac2->as_in_alt;
1393 	else
1394 		dev_err(&agdev->gadget->dev,
1395 			"%s:%d Invalid Interface %d!\n",
1396 			__func__, __LINE__, intf);
1397 
1398 	return -EINVAL;
1399 }
1400 
1401 static void
1402 afunc_disable(struct usb_function *fn)
1403 {
1404 	struct f_uac2 *uac2 = func_to_uac2(fn);
1405 
1406 	uac2->as_in_alt = 0;
1407 	uac2->as_out_alt = 0;
1408 	u_audio_stop_capture(&uac2->g_audio);
1409 	u_audio_stop_playback(&uac2->g_audio);
1410 	if (uac2->int_ep)
1411 		usb_ep_disable(uac2->int_ep);
1412 }
1413 
1414 static int
1415 in_rq_cur(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1416 {
1417 	struct usb_request *req = fn->config->cdev->req;
1418 	struct g_audio *agdev = func_to_g_audio(fn);
1419 	struct f_uac2_opts *opts = g_audio_to_uac2_opts(agdev);
1420 	u16 w_length = le16_to_cpu(cr->wLength);
1421 	u16 w_index = le16_to_cpu(cr->wIndex);
1422 	u16 w_value = le16_to_cpu(cr->wValue);
1423 	u8 entity_id = (w_index >> 8) & 0xff;
1424 	u8 control_selector = w_value >> 8;
1425 	int value = -EOPNOTSUPP;
1426 	int p_srate, c_srate;
1427 
1428 	p_srate = opts->p_srate;
1429 	c_srate = opts->c_srate;
1430 
1431 	if ((entity_id == USB_IN_CLK_ID) || (entity_id == USB_OUT_CLK_ID)) {
1432 		if (control_selector == UAC2_CS_CONTROL_SAM_FREQ) {
1433 			struct cntrl_cur_lay3 c;
1434 
1435 			memset(&c, 0, sizeof(struct cntrl_cur_lay3));
1436 
1437 			if (entity_id == USB_IN_CLK_ID)
1438 				c.dCUR = cpu_to_le32(p_srate);
1439 			else if (entity_id == USB_OUT_CLK_ID)
1440 				c.dCUR = cpu_to_le32(c_srate);
1441 
1442 			value = min_t(unsigned int, w_length, sizeof(c));
1443 			memcpy(req->buf, &c, value);
1444 		} else if (control_selector == UAC2_CS_CONTROL_CLOCK_VALID) {
1445 			*(u8 *)req->buf = 1;
1446 			value = min_t(unsigned int, w_length, 1);
1447 		} else {
1448 			dev_err(&agdev->gadget->dev,
1449 				"%s:%d control_selector=%d TODO!\n",
1450 				__func__, __LINE__, control_selector);
1451 		}
1452 	} else if ((FUIN_EN(opts) && (entity_id == USB_IN_FU_ID)) ||
1453 			(FUOUT_EN(opts) && (entity_id == USB_OUT_FU_ID))) {
1454 		unsigned int is_playback = 0;
1455 
1456 		if (FUIN_EN(opts) && (entity_id == USB_IN_FU_ID))
1457 			is_playback = 1;
1458 
1459 		if (control_selector == UAC_FU_MUTE) {
1460 			unsigned int mute;
1461 
1462 			u_audio_get_mute(agdev, is_playback, &mute);
1463 
1464 			*(u8 *)req->buf = mute;
1465 			value = min_t(unsigned int, w_length, 1);
1466 		} else if (control_selector == UAC_FU_VOLUME) {
1467 			struct cntrl_cur_lay2 c;
1468 			s16 volume;
1469 
1470 			memset(&c, 0, sizeof(struct cntrl_cur_lay2));
1471 
1472 			u_audio_get_volume(agdev, is_playback, &volume);
1473 			c.wCUR = cpu_to_le16(volume);
1474 
1475 			value = min_t(unsigned int, w_length, sizeof(c));
1476 			memcpy(req->buf, &c, value);
1477 		} else {
1478 			dev_err(&agdev->gadget->dev,
1479 				"%s:%d control_selector=%d TODO!\n",
1480 				__func__, __LINE__, control_selector);
1481 		}
1482 	} else {
1483 		dev_err(&agdev->gadget->dev,
1484 			"%s:%d entity_id=%d control_selector=%d TODO!\n",
1485 			__func__, __LINE__, entity_id, control_selector);
1486 	}
1487 
1488 	return value;
1489 }
1490 
1491 static int
1492 in_rq_range(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1493 {
1494 	struct usb_request *req = fn->config->cdev->req;
1495 	struct g_audio *agdev = func_to_g_audio(fn);
1496 	struct f_uac2_opts *opts = g_audio_to_uac2_opts(agdev);
1497 	u16 w_length = le16_to_cpu(cr->wLength);
1498 	u16 w_index = le16_to_cpu(cr->wIndex);
1499 	u16 w_value = le16_to_cpu(cr->wValue);
1500 	u8 entity_id = (w_index >> 8) & 0xff;
1501 	u8 control_selector = w_value >> 8;
1502 	int value = -EOPNOTSUPP;
1503 	int p_srate, c_srate;
1504 
1505 	p_srate = opts->p_srate;
1506 	c_srate = opts->c_srate;
1507 
1508 	if ((entity_id == USB_IN_CLK_ID) || (entity_id == USB_OUT_CLK_ID)) {
1509 		if (control_selector == UAC2_CS_CONTROL_SAM_FREQ) {
1510 			struct cntrl_range_lay3 r;
1511 
1512 			if (entity_id == USB_IN_CLK_ID)
1513 				r.dMIN = cpu_to_le32(p_srate);
1514 			else if (entity_id == USB_OUT_CLK_ID)
1515 				r.dMIN = cpu_to_le32(c_srate);
1516 			else
1517 				return -EOPNOTSUPP;
1518 
1519 			r.dMAX = r.dMIN;
1520 			r.dRES = 0;
1521 			r.wNumSubRanges = cpu_to_le16(1);
1522 
1523 			value = min_t(unsigned int, w_length, sizeof(r));
1524 			memcpy(req->buf, &r, value);
1525 		} else {
1526 			dev_err(&agdev->gadget->dev,
1527 				"%s:%d control_selector=%d TODO!\n",
1528 				__func__, __LINE__, control_selector);
1529 		}
1530 	} else if ((FUIN_EN(opts) && (entity_id == USB_IN_FU_ID)) ||
1531 			(FUOUT_EN(opts) && (entity_id == USB_OUT_FU_ID))) {
1532 		unsigned int is_playback = 0;
1533 
1534 		if (FUIN_EN(opts) && (entity_id == USB_IN_FU_ID))
1535 			is_playback = 1;
1536 
1537 		if (control_selector == UAC_FU_VOLUME) {
1538 			struct cntrl_range_lay2 r;
1539 			s16 max_db, min_db, res_db;
1540 
1541 			if (is_playback) {
1542 				max_db = opts->p_volume_max;
1543 				min_db = opts->p_volume_min;
1544 				res_db = opts->p_volume_res;
1545 			} else {
1546 				max_db = opts->c_volume_max;
1547 				min_db = opts->c_volume_min;
1548 				res_db = opts->c_volume_res;
1549 			}
1550 
1551 			r.wMAX = cpu_to_le16(max_db);
1552 			r.wMIN = cpu_to_le16(min_db);
1553 			r.wRES = cpu_to_le16(res_db);
1554 			r.wNumSubRanges = cpu_to_le16(1);
1555 
1556 			value = min_t(unsigned int, w_length, sizeof(r));
1557 			memcpy(req->buf, &r, value);
1558 		} else {
1559 			dev_err(&agdev->gadget->dev,
1560 				"%s:%d control_selector=%d TODO!\n",
1561 				__func__, __LINE__, control_selector);
1562 		}
1563 	} else {
1564 		dev_err(&agdev->gadget->dev,
1565 			"%s:%d entity_id=%d control_selector=%d TODO!\n",
1566 			__func__, __LINE__, entity_id, control_selector);
1567 	}
1568 
1569 	return value;
1570 }
1571 
1572 static int
1573 ac_rq_in(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1574 {
1575 	if (cr->bRequest == UAC2_CS_CUR)
1576 		return in_rq_cur(fn, cr);
1577 	else if (cr->bRequest == UAC2_CS_RANGE)
1578 		return in_rq_range(fn, cr);
1579 	else
1580 		return -EOPNOTSUPP;
1581 }
1582 
1583 static void
1584 out_rq_cur_complete(struct usb_ep *ep, struct usb_request *req)
1585 {
1586 	struct g_audio *agdev = req->context;
1587 	struct usb_composite_dev *cdev = agdev->func.config->cdev;
1588 	struct f_uac2_opts *opts = g_audio_to_uac2_opts(agdev);
1589 	struct f_uac2 *uac2 = func_to_uac2(&agdev->func);
1590 	struct usb_ctrlrequest *cr = &uac2->setup_cr;
1591 	u16 w_index = le16_to_cpu(cr->wIndex);
1592 	u16 w_value = le16_to_cpu(cr->wValue);
1593 	u8 entity_id = (w_index >> 8) & 0xff;
1594 	u8 control_selector = w_value >> 8;
1595 
1596 	if (req->status != 0) {
1597 		dev_dbg(&cdev->gadget->dev, "completion err %d\n", req->status);
1598 		return;
1599 	}
1600 
1601 	if ((FUIN_EN(opts) && (entity_id == USB_IN_FU_ID)) ||
1602 		(FUOUT_EN(opts) && (entity_id == USB_OUT_FU_ID))) {
1603 		unsigned int is_playback = 0;
1604 
1605 		if (FUIN_EN(opts) && (entity_id == USB_IN_FU_ID))
1606 			is_playback = 1;
1607 
1608 		if (control_selector == UAC_FU_MUTE) {
1609 			u8 mute = *(u8 *)req->buf;
1610 
1611 			u_audio_set_mute(agdev, is_playback, mute);
1612 
1613 			return;
1614 		} else if (control_selector == UAC_FU_VOLUME) {
1615 			struct cntrl_cur_lay2 *c = req->buf;
1616 			s16 volume;
1617 
1618 			volume = le16_to_cpu(c->wCUR);
1619 			u_audio_set_volume(agdev, is_playback, volume);
1620 
1621 			return;
1622 		} else {
1623 			dev_err(&agdev->gadget->dev,
1624 				"%s:%d control_selector=%d TODO!\n",
1625 				__func__, __LINE__, control_selector);
1626 			usb_ep_set_halt(ep);
1627 		}
1628 	}
1629 }
1630 
1631 static int
1632 out_rq_cur(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1633 {
1634 	struct usb_request *req = fn->config->cdev->req;
1635 	struct g_audio *agdev = func_to_g_audio(fn);
1636 	struct f_uac2_opts *opts = g_audio_to_uac2_opts(agdev);
1637 	struct f_uac2 *uac2 = func_to_uac2(fn);
1638 	u16 w_length = le16_to_cpu(cr->wLength);
1639 	u16 w_index = le16_to_cpu(cr->wIndex);
1640 	u16 w_value = le16_to_cpu(cr->wValue);
1641 	u8 entity_id = (w_index >> 8) & 0xff;
1642 	u8 control_selector = w_value >> 8;
1643 
1644 	if ((entity_id == USB_IN_CLK_ID) || (entity_id == USB_OUT_CLK_ID)) {
1645 		if (control_selector == UAC2_CS_CONTROL_SAM_FREQ)
1646 			return w_length;
1647 	} else if ((FUIN_EN(opts) && (entity_id == USB_IN_FU_ID)) ||
1648 			(FUOUT_EN(opts) && (entity_id == USB_OUT_FU_ID))) {
1649 		memcpy(&uac2->setup_cr, cr, sizeof(*cr));
1650 		req->context = agdev;
1651 		req->complete = out_rq_cur_complete;
1652 
1653 		return w_length;
1654 	} else {
1655 		dev_err(&agdev->gadget->dev,
1656 			"%s:%d entity_id=%d control_selector=%d TODO!\n",
1657 			__func__, __LINE__, entity_id, control_selector);
1658 	}
1659 	return -EOPNOTSUPP;
1660 }
1661 
1662 static int
1663 setup_rq_inf(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1664 {
1665 	struct f_uac2 *uac2 = func_to_uac2(fn);
1666 	struct g_audio *agdev = func_to_g_audio(fn);
1667 	u16 w_index = le16_to_cpu(cr->wIndex);
1668 	u8 intf = w_index & 0xff;
1669 
1670 	if (intf != uac2->ac_intf) {
1671 		dev_err(&agdev->gadget->dev,
1672 			"%s:%d Error!\n", __func__, __LINE__);
1673 		return -EOPNOTSUPP;
1674 	}
1675 
1676 	if (cr->bRequestType & USB_DIR_IN)
1677 		return ac_rq_in(fn, cr);
1678 	else if (cr->bRequest == UAC2_CS_CUR)
1679 		return out_rq_cur(fn, cr);
1680 
1681 	return -EOPNOTSUPP;
1682 }
1683 
1684 static int
1685 afunc_setup(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1686 {
1687 	struct usb_composite_dev *cdev = fn->config->cdev;
1688 	struct g_audio *agdev = func_to_g_audio(fn);
1689 	struct usb_request *req = cdev->req;
1690 	u16 w_length = le16_to_cpu(cr->wLength);
1691 	int value = -EOPNOTSUPP;
1692 
1693 	/* Only Class specific requests are supposed to reach here */
1694 	if ((cr->bRequestType & USB_TYPE_MASK) != USB_TYPE_CLASS)
1695 		return -EOPNOTSUPP;
1696 
1697 	if ((cr->bRequestType & USB_RECIP_MASK) == USB_RECIP_INTERFACE)
1698 		value = setup_rq_inf(fn, cr);
1699 	else
1700 		dev_err(&agdev->gadget->dev, "%s:%d Error!\n",
1701 				__func__, __LINE__);
1702 
1703 	if (value >= 0) {
1704 		req->length = value;
1705 		req->zero = value < w_length;
1706 		value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
1707 		if (value < 0) {
1708 			dev_err(&agdev->gadget->dev,
1709 				"%s:%d Error!\n", __func__, __LINE__);
1710 			req->status = 0;
1711 		}
1712 	}
1713 
1714 	return value;
1715 }
1716 
1717 static inline struct f_uac2_opts *to_f_uac2_opts(struct config_item *item)
1718 {
1719 	return container_of(to_config_group(item), struct f_uac2_opts,
1720 			    func_inst.group);
1721 }
1722 
1723 static void f_uac2_attr_release(struct config_item *item)
1724 {
1725 	struct f_uac2_opts *opts = to_f_uac2_opts(item);
1726 
1727 	usb_put_function_instance(&opts->func_inst);
1728 }
1729 
1730 static struct configfs_item_operations f_uac2_item_ops = {
1731 	.release	= f_uac2_attr_release,
1732 };
1733 
1734 #define uac2_kstrtou32 kstrtou32
1735 #define uac2_kstrtos16 kstrtos16
1736 #define uac2_kstrtobool(s, base, res) kstrtobool((s), (res))
1737 
1738 static const char *u32_fmt = "%u\n";
1739 static const char *s16_fmt = "%hd\n";
1740 static const char *bool_fmt = "%u\n";
1741 
1742 #define UAC2_ATTRIBUTE(type, name)					\
1743 static ssize_t f_uac2_opts_##name##_show(struct config_item *item,	\
1744 					 char *page)			\
1745 {									\
1746 	struct f_uac2_opts *opts = to_f_uac2_opts(item);		\
1747 	int result;							\
1748 									\
1749 	mutex_lock(&opts->lock);					\
1750 	result = sprintf(page, type##_fmt, opts->name);			\
1751 	mutex_unlock(&opts->lock);					\
1752 									\
1753 	return result;							\
1754 }									\
1755 									\
1756 static ssize_t f_uac2_opts_##name##_store(struct config_item *item,	\
1757 					  const char *page, size_t len)	\
1758 {									\
1759 	struct f_uac2_opts *opts = to_f_uac2_opts(item);		\
1760 	int ret;							\
1761 	type num;							\
1762 									\
1763 	mutex_lock(&opts->lock);					\
1764 	if (opts->refcnt) {						\
1765 		ret = -EBUSY;						\
1766 		goto end;						\
1767 	}								\
1768 									\
1769 	ret = uac2_kstrto##type(page, 0, &num);				\
1770 	if (ret)							\
1771 		goto end;						\
1772 									\
1773 	opts->name = num;						\
1774 	ret = len;							\
1775 									\
1776 end:									\
1777 	mutex_unlock(&opts->lock);					\
1778 	return ret;							\
1779 }									\
1780 									\
1781 CONFIGFS_ATTR(f_uac2_opts_, name)
1782 
1783 #define UAC2_ATTRIBUTE_SYNC(name)					\
1784 static ssize_t f_uac2_opts_##name##_show(struct config_item *item,	\
1785 					 char *page)			\
1786 {									\
1787 	struct f_uac2_opts *opts = to_f_uac2_opts(item);		\
1788 	int result;							\
1789 	char *str;							\
1790 									\
1791 	mutex_lock(&opts->lock);					\
1792 	switch (opts->name) {						\
1793 	case USB_ENDPOINT_SYNC_ASYNC:					\
1794 		str = "async";						\
1795 		break;							\
1796 	case USB_ENDPOINT_SYNC_ADAPTIVE:				\
1797 		str = "adaptive";					\
1798 		break;							\
1799 	default:							\
1800 		str = "unknown";					\
1801 		break;							\
1802 	}								\
1803 	result = sprintf(page, "%s\n", str);				\
1804 	mutex_unlock(&opts->lock);					\
1805 									\
1806 	return result;							\
1807 }									\
1808 									\
1809 static ssize_t f_uac2_opts_##name##_store(struct config_item *item,	\
1810 					  const char *page, size_t len)	\
1811 {									\
1812 	struct f_uac2_opts *opts = to_f_uac2_opts(item);		\
1813 	int ret = 0;							\
1814 									\
1815 	mutex_lock(&opts->lock);					\
1816 	if (opts->refcnt) {						\
1817 		ret = -EBUSY;						\
1818 		goto end;						\
1819 	}								\
1820 									\
1821 	if (!strncmp(page, "async", 5))					\
1822 		opts->name = USB_ENDPOINT_SYNC_ASYNC;			\
1823 	else if (!strncmp(page, "adaptive", 8))				\
1824 		opts->name = USB_ENDPOINT_SYNC_ADAPTIVE;		\
1825 	else {								\
1826 		ret = -EINVAL;						\
1827 		goto end;						\
1828 	}								\
1829 									\
1830 	ret = len;							\
1831 									\
1832 end:									\
1833 	mutex_unlock(&opts->lock);					\
1834 	return ret;							\
1835 }									\
1836 									\
1837 CONFIGFS_ATTR(f_uac2_opts_, name)
1838 
1839 UAC2_ATTRIBUTE(u32, p_chmask);
1840 UAC2_ATTRIBUTE(u32, p_srate);
1841 UAC2_ATTRIBUTE(u32, p_ssize);
1842 UAC2_ATTRIBUTE(u32, c_chmask);
1843 UAC2_ATTRIBUTE(u32, c_srate);
1844 UAC2_ATTRIBUTE_SYNC(c_sync);
1845 UAC2_ATTRIBUTE(u32, c_ssize);
1846 UAC2_ATTRIBUTE(u32, req_number);
1847 
1848 UAC2_ATTRIBUTE(bool, p_mute_present);
1849 UAC2_ATTRIBUTE(bool, p_volume_present);
1850 UAC2_ATTRIBUTE(s16, p_volume_min);
1851 UAC2_ATTRIBUTE(s16, p_volume_max);
1852 UAC2_ATTRIBUTE(s16, p_volume_res);
1853 
1854 UAC2_ATTRIBUTE(bool, c_mute_present);
1855 UAC2_ATTRIBUTE(bool, c_volume_present);
1856 UAC2_ATTRIBUTE(s16, c_volume_min);
1857 UAC2_ATTRIBUTE(s16, c_volume_max);
1858 UAC2_ATTRIBUTE(s16, c_volume_res);
1859 UAC2_ATTRIBUTE(u32, fb_max);
1860 
1861 static struct configfs_attribute *f_uac2_attrs[] = {
1862 	&f_uac2_opts_attr_p_chmask,
1863 	&f_uac2_opts_attr_p_srate,
1864 	&f_uac2_opts_attr_p_ssize,
1865 	&f_uac2_opts_attr_c_chmask,
1866 	&f_uac2_opts_attr_c_srate,
1867 	&f_uac2_opts_attr_c_ssize,
1868 	&f_uac2_opts_attr_c_sync,
1869 	&f_uac2_opts_attr_req_number,
1870 	&f_uac2_opts_attr_fb_max,
1871 
1872 	&f_uac2_opts_attr_p_mute_present,
1873 	&f_uac2_opts_attr_p_volume_present,
1874 	&f_uac2_opts_attr_p_volume_min,
1875 	&f_uac2_opts_attr_p_volume_max,
1876 	&f_uac2_opts_attr_p_volume_res,
1877 
1878 	&f_uac2_opts_attr_c_mute_present,
1879 	&f_uac2_opts_attr_c_volume_present,
1880 	&f_uac2_opts_attr_c_volume_min,
1881 	&f_uac2_opts_attr_c_volume_max,
1882 	&f_uac2_opts_attr_c_volume_res,
1883 
1884 	NULL,
1885 };
1886 
1887 static const struct config_item_type f_uac2_func_type = {
1888 	.ct_item_ops	= &f_uac2_item_ops,
1889 	.ct_attrs	= f_uac2_attrs,
1890 	.ct_owner	= THIS_MODULE,
1891 };
1892 
1893 static void afunc_free_inst(struct usb_function_instance *f)
1894 {
1895 	struct f_uac2_opts *opts;
1896 
1897 	opts = container_of(f, struct f_uac2_opts, func_inst);
1898 	kfree(opts);
1899 }
1900 
1901 static struct usb_function_instance *afunc_alloc_inst(void)
1902 {
1903 	struct f_uac2_opts *opts;
1904 
1905 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
1906 	if (!opts)
1907 		return ERR_PTR(-ENOMEM);
1908 
1909 	mutex_init(&opts->lock);
1910 	opts->func_inst.free_func_inst = afunc_free_inst;
1911 
1912 	config_group_init_type_name(&opts->func_inst.group, "",
1913 				    &f_uac2_func_type);
1914 
1915 	opts->p_chmask = UAC2_DEF_PCHMASK;
1916 	opts->p_srate = UAC2_DEF_PSRATE;
1917 	opts->p_ssize = UAC2_DEF_PSSIZE;
1918 	opts->c_chmask = UAC2_DEF_CCHMASK;
1919 	opts->c_srate = UAC2_DEF_CSRATE;
1920 	opts->c_ssize = UAC2_DEF_CSSIZE;
1921 	opts->c_sync = UAC2_DEF_CSYNC;
1922 
1923 	opts->p_mute_present = UAC2_DEF_MUTE_PRESENT;
1924 	opts->p_volume_present = UAC2_DEF_VOLUME_PRESENT;
1925 	opts->p_volume_min = UAC2_DEF_MIN_DB;
1926 	opts->p_volume_max = UAC2_DEF_MAX_DB;
1927 	opts->p_volume_res = UAC2_DEF_RES_DB;
1928 
1929 	opts->c_mute_present = UAC2_DEF_MUTE_PRESENT;
1930 	opts->c_volume_present = UAC2_DEF_VOLUME_PRESENT;
1931 	opts->c_volume_min = UAC2_DEF_MIN_DB;
1932 	opts->c_volume_max = UAC2_DEF_MAX_DB;
1933 	opts->c_volume_res = UAC2_DEF_RES_DB;
1934 
1935 	opts->req_number = UAC2_DEF_REQ_NUM;
1936 	opts->fb_max = FBACK_FAST_MAX;
1937 	return &opts->func_inst;
1938 }
1939 
1940 static void afunc_free(struct usb_function *f)
1941 {
1942 	struct g_audio *agdev;
1943 	struct f_uac2_opts *opts;
1944 
1945 	agdev = func_to_g_audio(f);
1946 	opts = container_of(f->fi, struct f_uac2_opts, func_inst);
1947 	kfree(agdev);
1948 	mutex_lock(&opts->lock);
1949 	--opts->refcnt;
1950 	mutex_unlock(&opts->lock);
1951 }
1952 
1953 static void afunc_unbind(struct usb_configuration *c, struct usb_function *f)
1954 {
1955 	struct g_audio *agdev = func_to_g_audio(f);
1956 
1957 	g_audio_cleanup(agdev);
1958 	usb_free_all_descriptors(f);
1959 
1960 	agdev->gadget = NULL;
1961 
1962 	kfree(out_feature_unit_desc);
1963 	out_feature_unit_desc = NULL;
1964 	kfree(in_feature_unit_desc);
1965 	in_feature_unit_desc = NULL;
1966 }
1967 
1968 static struct usb_function *afunc_alloc(struct usb_function_instance *fi)
1969 {
1970 	struct f_uac2	*uac2;
1971 	struct f_uac2_opts *opts;
1972 
1973 	uac2 = kzalloc(sizeof(*uac2), GFP_KERNEL);
1974 	if (uac2 == NULL)
1975 		return ERR_PTR(-ENOMEM);
1976 
1977 	opts = container_of(fi, struct f_uac2_opts, func_inst);
1978 	mutex_lock(&opts->lock);
1979 	++opts->refcnt;
1980 	mutex_unlock(&opts->lock);
1981 
1982 	uac2->g_audio.func.name = "uac2_func";
1983 	uac2->g_audio.func.bind = afunc_bind;
1984 	uac2->g_audio.func.unbind = afunc_unbind;
1985 	uac2->g_audio.func.set_alt = afunc_set_alt;
1986 	uac2->g_audio.func.get_alt = afunc_get_alt;
1987 	uac2->g_audio.func.disable = afunc_disable;
1988 	uac2->g_audio.func.setup = afunc_setup;
1989 	uac2->g_audio.func.free_func = afunc_free;
1990 
1991 	return &uac2->g_audio.func;
1992 }
1993 
1994 DECLARE_USB_FUNCTION_INIT(uac2, afunc_alloc_inst, afunc_alloc);
1995 MODULE_LICENSE("GPL");
1996 MODULE_AUTHOR("Yadwinder Singh");
1997 MODULE_AUTHOR("Jaswinder Singh");
1998 MODULE_AUTHOR("Ruslan Bilovol");
1999