xref: /linux/drivers/usb/gadget/function/f_midi2.c (revision c532de5a67a70f8533d495f8f2aaa9a0491c3ad0)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * f_midi2.c -- USB MIDI 2.0 class function driver
4  */
5 
6 #include <linux/device.h>
7 #include <linux/kernel.h>
8 #include <linux/module.h>
9 #include <linux/slab.h>
10 
11 #include <sound/core.h>
12 #include <sound/control.h>
13 #include <sound/ump.h>
14 #include <sound/ump_msg.h>
15 #include <sound/ump_convert.h>
16 
17 #include <linux/usb/ch9.h>
18 #include <linux/usb/func_utils.h>
19 #include <linux/usb/gadget.h>
20 #include <linux/usb/audio.h>
21 #include <linux/usb/midi-v2.h>
22 
23 #include "u_midi2.h"
24 
25 struct f_midi2;
26 struct f_midi2_ep;
27 struct f_midi2_usb_ep;
28 
29 /* Context for each USB request */
30 struct f_midi2_req_ctx {
31 	struct f_midi2_usb_ep *usb_ep;	/* belonging USB EP */
32 	unsigned int index;		/* array index: 0-31 */
33 	struct usb_request *req;	/* assigned request */
34 };
35 
36 /* Resources for a USB Endpoint */
37 struct f_midi2_usb_ep {
38 	struct f_midi2 *card;		/* belonging card */
39 	struct f_midi2_ep *ep;		/* belonging UMP EP (optional) */
40 	struct usb_ep *usb_ep;		/* assigned USB EP */
41 	void (*complete)(struct usb_ep *usb_ep, struct usb_request *req);
42 	unsigned long free_reqs;	/* bitmap for unused requests */
43 	unsigned int num_reqs;		/* number of allocated requests */
44 	struct f_midi2_req_ctx *reqs;	/* request context array */
45 };
46 
47 /* Resources for UMP Function Block (and USB Group Terminal Block) */
48 struct f_midi2_block {
49 	struct f_midi2_block_info info;	/* FB info, copied from configfs */
50 	struct snd_ump_block *fb;	/* assigned FB */
51 	unsigned int gtb_id;		/* assigned GTB id */
52 	unsigned int string_id;		/* assigned string id */
53 };
54 
55 /* Temporary buffer for altset 0 MIDI 1.0 handling */
56 struct f_midi2_midi1_port {
57 	unsigned int pending; /* pending bytes on the input buffer */
58 	u8 buf[32];	/* raw MIDI 1.0 byte input */
59 	u8 state;	/* running status */
60 	u8 data[2];	/* rendered USB MIDI 1.0 packet data */
61 };
62 
63 /* MIDI 1.0 message states */
64 enum {
65 	STATE_INITIAL = 0,	/* pseudo state */
66 	STATE_1PARAM,
67 	STATE_2PARAM_1,
68 	STATE_2PARAM_2,
69 	STATE_SYSEX_0,
70 	STATE_SYSEX_1,
71 	STATE_SYSEX_2,
72 	STATE_REAL_TIME,
73 	STATE_FINISHED,		/* pseudo state */
74 };
75 
76 /* Resources for UMP Endpoint */
77 struct f_midi2_ep {
78 	struct snd_ump_endpoint *ump;	/* assigned UMP EP */
79 	struct f_midi2 *card;		/* belonging MIDI 2.0 device */
80 
81 	struct f_midi2_ep_info info;	/* UMP EP info, copied from configfs */
82 	unsigned int num_blks;		/* number of FBs */
83 	struct f_midi2_block blks[SNDRV_UMP_MAX_BLOCKS];	/* UMP FBs */
84 
85 	struct f_midi2_usb_ep ep_in;	/* USB MIDI EP-in */
86 	struct f_midi2_usb_ep ep_out;	/* USB MIDI EP-out */
87 
88 	u8 in_group_to_cable[SNDRV_UMP_MAX_GROUPS]; /* map to cable; 1-based! */
89 };
90 
91 /* indices for USB strings */
92 enum {
93 	STR_IFACE = 0,
94 	STR_GTB1 = 1,
95 };
96 
97 /* 1-based GTB id to string id */
98 #define gtb_to_str_id(id)	(STR_GTB1 + (id) - 1)
99 
100 /* mapping from MIDI 1.0 cable to UMP group */
101 struct midi1_cable_mapping {
102 	struct f_midi2_ep *ep;
103 	unsigned char block;
104 	unsigned char group;
105 };
106 
107 /* operation mode */
108 enum {
109 	MIDI_OP_MODE_UNSET,	/* no altset set yet */
110 	MIDI_OP_MODE_MIDI1,	/* MIDI 1.0 (altset 0) is used */
111 	MIDI_OP_MODE_MIDI2,	/* MIDI 2.0 (altset 1) is used */
112 };
113 
114 /* Resources for MIDI 2.0 Device */
115 struct f_midi2 {
116 	struct usb_function func;
117 	struct usb_gadget *gadget;
118 	struct snd_card *card;
119 
120 	/* MIDI 1.0 in/out USB EPs */
121 	struct f_midi2_usb_ep midi1_ep_in;
122 	struct f_midi2_usb_ep midi1_ep_out;
123 
124 	/* number of MIDI 1.0 I/O cables */
125 	unsigned int num_midi1_in;
126 	unsigned int num_midi1_out;
127 
128 	/* conversion for MIDI 1.0 EP-in */
129 	struct f_midi2_midi1_port midi1_port[MAX_CABLES];
130 	/* conversion for MIDI 1.0 EP-out */
131 	struct ump_cvt_to_ump midi1_ump_cvt;
132 	/* mapping between cables and UMP groups */
133 	struct midi1_cable_mapping in_cable_mapping[MAX_CABLES];
134 	struct midi1_cable_mapping out_cable_mapping[MAX_CABLES];
135 
136 	int midi_if;			/* USB MIDI interface number */
137 	int operation_mode;		/* current operation mode */
138 
139 	spinlock_t queue_lock;
140 
141 	struct f_midi2_card_info info;	/* card info, copied from configfs */
142 
143 	unsigned int num_eps;
144 	struct f_midi2_ep midi2_eps[MAX_UMP_EPS];
145 
146 	unsigned int total_blocks;	/* total number of blocks of all EPs */
147 	struct usb_string *string_defs;
148 	struct usb_string *strings;
149 };
150 
151 #define func_to_midi2(f)	container_of(f, struct f_midi2, func)
152 
153 /* convert from MIDI protocol number (1 or 2) to SNDRV_UMP_EP_INFO_PROTO_* */
154 #define to_ump_protocol(v)	(((v) & 3) << 8)
155 
156 /* get EP name string */
157 static const char *ump_ep_name(const struct f_midi2_ep *ep)
158 {
159 	return ep->info.ep_name ? ep->info.ep_name : "MIDI 2.0 Gadget";
160 }
161 
162 /* get EP product ID string */
163 static const char *ump_product_id(const struct f_midi2_ep *ep)
164 {
165 	return ep->info.product_id ? ep->info.product_id : "Unique Product ID";
166 }
167 
168 /* get FB name string */
169 static const char *ump_fb_name(const struct f_midi2_block_info *info)
170 {
171 	return info->name ? info->name : "MIDI 2.0 Gadget I/O";
172 }
173 
174 /*
175  * USB Descriptor Definitions
176  */
177 /* GTB header descriptor */
178 static struct usb_ms20_gr_trm_block_header_descriptor gtb_header_desc = {
179 	.bLength =		sizeof(gtb_header_desc),
180 	.bDescriptorType =	USB_DT_CS_GR_TRM_BLOCK,
181 	.bDescriptorSubtype =	USB_MS_GR_TRM_BLOCK_HEADER,
182 	.wTotalLength =		__cpu_to_le16(0x12), // to be filled
183 };
184 
185 /* GTB descriptor template: most items are replaced dynamically */
186 static struct usb_ms20_gr_trm_block_descriptor gtb_desc = {
187 	.bLength =		sizeof(gtb_desc),
188 	.bDescriptorType =	USB_DT_CS_GR_TRM_BLOCK,
189 	.bDescriptorSubtype =	USB_MS_GR_TRM_BLOCK,
190 	.bGrpTrmBlkID =		0x01,
191 	.bGrpTrmBlkType =	USB_MS_GR_TRM_BLOCK_TYPE_BIDIRECTIONAL,
192 	.nGroupTrm =		0x00,
193 	.nNumGroupTrm =		1,
194 	.iBlockItem =		0,
195 	.bMIDIProtocol =	USB_MS_MIDI_PROTO_1_0_64,
196 	.wMaxInputBandwidth =	0,
197 	.wMaxOutputBandwidth =	0,
198 };
199 
200 DECLARE_USB_MIDI_OUT_JACK_DESCRIPTOR(1);
201 DECLARE_USB_MS_ENDPOINT_DESCRIPTOR(16);
202 DECLARE_UAC_AC_HEADER_DESCRIPTOR(1);
203 DECLARE_USB_MS20_ENDPOINT_DESCRIPTOR(32);
204 
205 #define EP_MAX_PACKET_INT	8
206 
207 /* Audio Control Interface */
208 static struct usb_interface_descriptor midi2_audio_if_desc = {
209 	.bLength =		USB_DT_INTERFACE_SIZE,
210 	.bDescriptorType =	USB_DT_INTERFACE,
211 	.bInterfaceNumber =	0, // to be filled
212 	.bNumEndpoints =	0,
213 	.bInterfaceClass =	USB_CLASS_AUDIO,
214 	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOCONTROL,
215 	.bInterfaceProtocol =	0,
216 	.iInterface =		0,
217 };
218 
219 static struct uac1_ac_header_descriptor_1 midi2_audio_class_desc = {
220 	.bLength =		0x09,
221 	.bDescriptorType =	USB_DT_CS_INTERFACE,
222 	.bDescriptorSubtype =	0x01,
223 	.bcdADC =		__cpu_to_le16(0x0100),
224 	.wTotalLength =		__cpu_to_le16(0x0009),
225 	.bInCollection =	0x01,
226 	.baInterfaceNr =	{ 0x01 }, // to be filled
227 };
228 
229 /* MIDI 1.0 Streaming Interface (altset 0) */
230 static struct usb_interface_descriptor midi2_midi1_if_desc = {
231 	.bLength =		USB_DT_INTERFACE_SIZE,
232 	.bDescriptorType =	USB_DT_INTERFACE,
233 	.bInterfaceNumber =	0, // to be filled
234 	.bAlternateSetting =	0,
235 	.bNumEndpoints =	2, // to be filled
236 	.bInterfaceClass =	USB_CLASS_AUDIO,
237 	.bInterfaceSubClass =	USB_SUBCLASS_MIDISTREAMING,
238 	.bInterfaceProtocol =	0,
239 	.iInterface =		0, // to be filled
240 };
241 
242 static struct usb_ms_header_descriptor midi2_midi1_class_desc = {
243 	.bLength =		0x07,
244 	.bDescriptorType =	USB_DT_CS_INTERFACE,
245 	.bDescriptorSubtype =	USB_MS_HEADER,
246 	.bcdMSC =		__cpu_to_le16(0x0100),
247 	.wTotalLength =		__cpu_to_le16(0x41), // to be calculated
248 };
249 
250 /* MIDI 1.0 EP OUT */
251 static struct usb_endpoint_descriptor midi2_midi1_ep_out_desc = {
252 	.bLength =		USB_DT_ENDPOINT_AUDIO_SIZE,
253 	.bDescriptorType =	USB_DT_ENDPOINT,
254 	.bEndpointAddress =	USB_DIR_OUT | 0, // set up dynamically
255 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
256 };
257 
258 static struct usb_ss_ep_comp_descriptor midi2_midi1_ep_out_ss_comp_desc = {
259 	.bLength                = sizeof(midi2_midi1_ep_out_ss_comp_desc),
260 	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
261 };
262 
263 static struct usb_ms_endpoint_descriptor_16 midi2_midi1_ep_out_class_desc = {
264 	.bLength =		0x05, // to be filled
265 	.bDescriptorType =	USB_DT_CS_ENDPOINT,
266 	.bDescriptorSubtype =	USB_MS_GENERAL,
267 	.bNumEmbMIDIJack =	1,
268 	.baAssocJackID =	{ 0x01 },
269 };
270 
271 /* MIDI 1.0 EP IN */
272 static struct usb_endpoint_descriptor midi2_midi1_ep_in_desc = {
273 	.bLength =		USB_DT_ENDPOINT_AUDIO_SIZE,
274 	.bDescriptorType =	USB_DT_ENDPOINT,
275 	.bEndpointAddress =	USB_DIR_IN | 0, // set up dynamically
276 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
277 };
278 
279 static struct usb_ss_ep_comp_descriptor midi2_midi1_ep_in_ss_comp_desc = {
280 	.bLength                = sizeof(midi2_midi1_ep_in_ss_comp_desc),
281 	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
282 };
283 
284 static struct usb_ms_endpoint_descriptor_16 midi2_midi1_ep_in_class_desc = {
285 	.bLength =		0x05, // to be filled
286 	.bDescriptorType =	USB_DT_CS_ENDPOINT,
287 	.bDescriptorSubtype =	USB_MS_GENERAL,
288 	.bNumEmbMIDIJack =	1,
289 	.baAssocJackID =	{ 0x03 },
290 };
291 
292 /* MIDI 2.0 Streaming Interface (altset 1) */
293 static struct usb_interface_descriptor midi2_midi2_if_desc = {
294 	.bLength =		USB_DT_INTERFACE_SIZE,
295 	.bDescriptorType =	USB_DT_INTERFACE,
296 	.bInterfaceNumber =	0, // to be filled
297 	.bAlternateSetting =	1,
298 	.bNumEndpoints =	2, // to be filled
299 	.bInterfaceClass =	USB_CLASS_AUDIO,
300 	.bInterfaceSubClass =	USB_SUBCLASS_MIDISTREAMING,
301 	.bInterfaceProtocol =	0,
302 	.iInterface =		0, // to be filled
303 };
304 
305 static struct usb_ms_header_descriptor midi2_midi2_class_desc = {
306 	.bLength =		0x07,
307 	.bDescriptorType =	USB_DT_CS_INTERFACE,
308 	.bDescriptorSubtype =	USB_MS_HEADER,
309 	.bcdMSC =		__cpu_to_le16(0x0200),
310 	.wTotalLength =		__cpu_to_le16(0x07),
311 };
312 
313 /* MIDI 2.0 EP OUT */
314 static struct usb_endpoint_descriptor midi2_midi2_ep_out_desc[MAX_UMP_EPS];
315 
316 static struct usb_ss_ep_comp_descriptor midi2_midi2_ep_out_ss_comp_desc = {
317 	.bLength                = sizeof(midi2_midi1_ep_out_ss_comp_desc),
318 	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
319 };
320 
321 static struct usb_ms20_endpoint_descriptor_32 midi2_midi2_ep_out_class_desc[MAX_UMP_EPS];
322 
323 /* MIDI 2.0 EP IN */
324 static struct usb_endpoint_descriptor midi2_midi2_ep_in_desc[MAX_UMP_EPS];
325 
326 static struct usb_ss_ep_comp_descriptor midi2_midi2_ep_in_ss_comp_desc = {
327 	.bLength                = sizeof(midi2_midi2_ep_in_ss_comp_desc),
328 	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
329 };
330 
331 static struct usb_ms20_endpoint_descriptor_32 midi2_midi2_ep_in_class_desc[MAX_UMP_EPS];
332 
333 /* Arrays of descriptors to be created */
334 static void *midi2_audio_descs[] = {
335 	&midi2_audio_if_desc,
336 	&midi2_audio_class_desc,
337 	NULL
338 };
339 
340 static void *midi2_midi1_descs[] = {
341 	&midi2_midi1_if_desc,
342 	&midi2_midi1_class_desc,
343 	NULL
344 };
345 
346 static void *midi2_midi1_ep_out_descs[] = {
347 	&midi2_midi1_ep_out_desc,
348 	&midi2_midi1_ep_out_class_desc,
349 	NULL
350 };
351 
352 static void *midi2_midi1_ep_in_descs[] = {
353 	&midi2_midi1_ep_in_desc,
354 	&midi2_midi1_ep_in_class_desc,
355 	NULL
356 };
357 
358 static void *midi2_midi1_ep_out_ss_descs[] = {
359 	&midi2_midi1_ep_out_desc,
360 	&midi2_midi1_ep_out_ss_comp_desc,
361 	&midi2_midi1_ep_out_class_desc,
362 	NULL
363 };
364 
365 static void *midi2_midi1_ep_in_ss_descs[] = {
366 	&midi2_midi1_ep_in_desc,
367 	&midi2_midi1_ep_in_ss_comp_desc,
368 	&midi2_midi1_ep_in_class_desc,
369 	NULL
370 };
371 
372 static void *midi2_midi2_descs[] = {
373 	&midi2_midi2_if_desc,
374 	&midi2_midi2_class_desc,
375 	NULL
376 };
377 
378 /*
379  * USB request handling
380  */
381 
382 /* get an empty request for the given EP */
383 static struct usb_request *get_empty_request(struct f_midi2_usb_ep *usb_ep)
384 {
385 	struct usb_request *req = NULL;
386 	unsigned long flags;
387 	int index;
388 
389 	spin_lock_irqsave(&usb_ep->card->queue_lock, flags);
390 	if (!usb_ep->free_reqs)
391 		goto unlock;
392 	index = find_first_bit(&usb_ep->free_reqs, usb_ep->num_reqs);
393 	if (index >= usb_ep->num_reqs)
394 		goto unlock;
395 	req = usb_ep->reqs[index].req;
396 	if (!req)
397 		goto unlock;
398 	clear_bit(index, &usb_ep->free_reqs);
399 	req->length = 0;
400  unlock:
401 	spin_unlock_irqrestore(&usb_ep->card->queue_lock, flags);
402 	return req;
403 }
404 
405 /* put the empty request back */
406 static void put_empty_request(struct usb_request *req)
407 {
408 	struct f_midi2_req_ctx *ctx = req->context;
409 	unsigned long flags;
410 
411 	spin_lock_irqsave(&ctx->usb_ep->card->queue_lock, flags);
412 	set_bit(ctx->index, &ctx->usb_ep->free_reqs);
413 	spin_unlock_irqrestore(&ctx->usb_ep->card->queue_lock, flags);
414 }
415 
416 /*
417  * UMP v1.1 Stream message handling
418  */
419 
420 /* queue a request to UMP EP; request is either queued or freed after this */
421 static int queue_request_ep_raw(struct usb_request *req)
422 {
423 	struct f_midi2_req_ctx *ctx = req->context;
424 	int err;
425 
426 	req->complete = ctx->usb_ep->complete;
427 	err = usb_ep_queue(ctx->usb_ep->usb_ep, req, GFP_ATOMIC);
428 	if (err) {
429 		put_empty_request(req);
430 		return err;
431 	}
432 	return 0;
433 }
434 
435 /* queue a request with endianness conversion */
436 static int queue_request_ep_in(struct usb_request *req)
437 {
438 	/* UMP packets have to be converted to little-endian */
439 	cpu_to_le32_array((u32 *)req->buf, req->length >> 2);
440 	return queue_request_ep_raw(req);
441 }
442 
443 /* reply a UMP packet via EP-in */
444 static int reply_ep_in(struct f_midi2_ep *ep, const void *buf, int len)
445 {
446 	struct f_midi2_usb_ep *usb_ep = &ep->ep_in;
447 	struct usb_request *req;
448 
449 	req = get_empty_request(usb_ep);
450 	if (!req)
451 		return -ENOSPC;
452 
453 	req->length = len;
454 	memcpy(req->buf, buf, len);
455 	return queue_request_ep_in(req);
456 }
457 
458 /* reply a UMP stream EP info */
459 static void reply_ump_stream_ep_info(struct f_midi2_ep *ep)
460 {
461 	struct snd_ump_stream_msg_ep_info rep = {
462 		.type = UMP_MSG_TYPE_STREAM,
463 		.status = UMP_STREAM_MSG_STATUS_EP_INFO,
464 		.ump_version_major = 0x01,
465 		.ump_version_minor = 0x01,
466 		.num_function_blocks = ep->num_blks,
467 		.static_function_block = !!ep->card->info.static_block,
468 		.protocol = (UMP_STREAM_MSG_EP_INFO_CAP_MIDI1 |
469 			     UMP_STREAM_MSG_EP_INFO_CAP_MIDI2) >> 8,
470 	};
471 
472 	reply_ep_in(ep, &rep, sizeof(rep));
473 }
474 
475 /* reply a UMP EP device info */
476 static void reply_ump_stream_ep_device(struct f_midi2_ep *ep)
477 {
478 	struct snd_ump_stream_msg_devince_info rep = {
479 		.type = UMP_MSG_TYPE_STREAM,
480 		.status = UMP_STREAM_MSG_STATUS_DEVICE_INFO,
481 		.manufacture_id = ep->info.manufacturer,
482 		.family_lsb = ep->info.family & 0xff,
483 		.family_msb = (ep->info.family >> 8) & 0xff,
484 		.model_lsb = ep->info.model & 0xff,
485 		.model_msb = (ep->info.model >> 8) & 0xff,
486 		.sw_revision = ep->info.sw_revision,
487 	};
488 
489 	reply_ep_in(ep, &rep, sizeof(rep));
490 }
491 
492 #define UMP_STREAM_PKT_BYTES	16	/* UMP stream packet size = 16 bytes*/
493 #define UMP_STREAM_EP_STR_OFF	2	/* offset of name string for EP info */
494 #define UMP_STREAM_FB_STR_OFF	3	/* offset of name string for FB info */
495 
496 /* Helper to replay a string */
497 static void reply_ump_stream_string(struct f_midi2_ep *ep, const u8 *name,
498 				    unsigned int type, unsigned int extra,
499 				    unsigned int start_ofs)
500 {
501 	struct f_midi2_usb_ep *usb_ep = &ep->ep_in;
502 	struct f_midi2 *midi2 = ep->card;
503 	struct usb_request *req;
504 	unsigned int pos;
505 	u32 *buf;
506 
507 	if (!*name)
508 		return;
509 	req = get_empty_request(usb_ep);
510 	if (!req)
511 		return;
512 
513 	buf = (u32 *)req->buf;
514 	pos = start_ofs;
515 	for (;;) {
516 		if (pos == start_ofs) {
517 			memset(buf, 0, UMP_STREAM_PKT_BYTES);
518 			buf[0] = ump_stream_compose(type, 0) | extra;
519 		}
520 		buf[pos / 4] |= *name++ << ((3 - (pos % 4)) * 8);
521 		if (!*name) {
522 			if (req->length)
523 				buf[0] |= UMP_STREAM_MSG_FORMAT_END << 26;
524 			req->length += UMP_STREAM_PKT_BYTES;
525 			break;
526 		}
527 		if (++pos == UMP_STREAM_PKT_BYTES) {
528 			if (!req->length)
529 				buf[0] |= UMP_STREAM_MSG_FORMAT_START << 26;
530 			else
531 				buf[0] |= UMP_STREAM_MSG_FORMAT_CONTINUE << 26;
532 			req->length += UMP_STREAM_PKT_BYTES;
533 			if (midi2->info.req_buf_size - req->length < UMP_STREAM_PKT_BYTES)
534 				break;
535 			buf += 4;
536 			pos = start_ofs;
537 		}
538 	}
539 
540 	if (req->length)
541 		queue_request_ep_in(req);
542 	else
543 		put_empty_request(req);
544 }
545 
546 /* Reply a UMP EP name string */
547 static void reply_ump_stream_ep_name(struct f_midi2_ep *ep)
548 {
549 	reply_ump_stream_string(ep, ump_ep_name(ep),
550 				UMP_STREAM_MSG_STATUS_EP_NAME, 0,
551 				UMP_STREAM_EP_STR_OFF);
552 }
553 
554 /* Reply a UMP EP product ID string */
555 static void reply_ump_stream_ep_pid(struct f_midi2_ep *ep)
556 {
557 	reply_ump_stream_string(ep, ump_product_id(ep),
558 				UMP_STREAM_MSG_STATUS_PRODUCT_ID, 0,
559 				UMP_STREAM_EP_STR_OFF);
560 }
561 
562 /* Reply a UMP EP stream config */
563 static void reply_ump_stream_ep_config(struct f_midi2_ep *ep)
564 {
565 	struct snd_ump_stream_msg_stream_cfg rep = {
566 		.type = UMP_MSG_TYPE_STREAM,
567 		.status = UMP_STREAM_MSG_STATUS_STREAM_CFG,
568 	};
569 
570 	if (ep->info.protocol == 2)
571 		rep.protocol = UMP_STREAM_MSG_EP_INFO_CAP_MIDI2 >> 8;
572 	else
573 		rep.protocol = UMP_STREAM_MSG_EP_INFO_CAP_MIDI1 >> 8;
574 
575 	reply_ep_in(ep, &rep, sizeof(rep));
576 }
577 
578 /* Reply a UMP FB info */
579 static void reply_ump_stream_fb_info(struct f_midi2_ep *ep, int blk)
580 {
581 	struct f_midi2_block_info *b = &ep->blks[blk].info;
582 	struct snd_ump_stream_msg_fb_info rep = {
583 		.type = UMP_MSG_TYPE_STREAM,
584 		.status = UMP_STREAM_MSG_STATUS_FB_INFO,
585 		.active = !!b->active,
586 		.function_block_id = blk,
587 		.ui_hint = b->ui_hint,
588 		.midi_10 = b->is_midi1,
589 		.direction = b->direction,
590 		.first_group = b->first_group,
591 		.num_groups = b->num_groups,
592 		.midi_ci_version = b->midi_ci_version,
593 		.sysex8_streams = b->sysex8_streams,
594 	};
595 
596 	reply_ep_in(ep, &rep, sizeof(rep));
597 }
598 
599 /* Reply a FB name string */
600 static void reply_ump_stream_fb_name(struct f_midi2_ep *ep, unsigned int blk)
601 {
602 	reply_ump_stream_string(ep, ump_fb_name(&ep->blks[blk].info),
603 				UMP_STREAM_MSG_STATUS_FB_NAME, blk << 8,
604 				UMP_STREAM_FB_STR_OFF);
605 }
606 
607 /* Process a UMP Stream message */
608 static void process_ump_stream_msg(struct f_midi2_ep *ep, const u32 *data)
609 {
610 	struct f_midi2 *midi2 = ep->card;
611 	unsigned int format, status, blk;
612 
613 	format = ump_stream_message_format(*data);
614 	status = ump_stream_message_status(*data);
615 	switch (status) {
616 	case UMP_STREAM_MSG_STATUS_EP_DISCOVERY:
617 		if (format)
618 			return; // invalid
619 		if (data[1] & UMP_STREAM_MSG_REQUEST_EP_INFO)
620 			reply_ump_stream_ep_info(ep);
621 		if (data[1] & UMP_STREAM_MSG_REQUEST_DEVICE_INFO)
622 			reply_ump_stream_ep_device(ep);
623 		if (data[1] & UMP_STREAM_MSG_REQUEST_EP_NAME)
624 			reply_ump_stream_ep_name(ep);
625 		if (data[1] & UMP_STREAM_MSG_REQUEST_PRODUCT_ID)
626 			reply_ump_stream_ep_pid(ep);
627 		if (data[1] & UMP_STREAM_MSG_REQUEST_STREAM_CFG)
628 			reply_ump_stream_ep_config(ep);
629 		return;
630 	case UMP_STREAM_MSG_STATUS_STREAM_CFG_REQUEST:
631 		if (*data & UMP_STREAM_MSG_EP_INFO_CAP_MIDI2) {
632 			ep->info.protocol = 2;
633 			DBG(midi2, "Switching Protocol to MIDI2\n");
634 		} else {
635 			ep->info.protocol = 1;
636 			DBG(midi2, "Switching Protocol to MIDI1\n");
637 		}
638 		snd_ump_switch_protocol(ep->ump, to_ump_protocol(ep->info.protocol));
639 		reply_ump_stream_ep_config(ep);
640 		return;
641 	case UMP_STREAM_MSG_STATUS_FB_DISCOVERY:
642 		if (format)
643 			return; // invalid
644 		blk = (*data >> 8) & 0xff;
645 		if (blk == 0xff) {
646 			/* inquiry for all blocks */
647 			for (blk = 0; blk < ep->num_blks; blk++) {
648 				if (*data & UMP_STREAM_MSG_REQUEST_FB_INFO)
649 					reply_ump_stream_fb_info(ep, blk);
650 				if (*data & UMP_STREAM_MSG_REQUEST_FB_NAME)
651 					reply_ump_stream_fb_name(ep, blk);
652 			}
653 		} else if (blk < ep->num_blks) {
654 			/* only the specified block */
655 			if (*data & UMP_STREAM_MSG_REQUEST_FB_INFO)
656 				reply_ump_stream_fb_info(ep, blk);
657 			if (*data & UMP_STREAM_MSG_REQUEST_FB_NAME)
658 				reply_ump_stream_fb_name(ep, blk);
659 		}
660 		return;
661 	}
662 }
663 
664 /* Process UMP messages included in a USB request */
665 static void process_ump(struct f_midi2_ep *ep, const struct usb_request *req)
666 {
667 	const u32 *data = (u32 *)req->buf;
668 	int len = req->actual >> 2;
669 	const u32 *in_buf = ep->ump->input_buf;
670 
671 	for (; len > 0; len--, data++) {
672 		if (snd_ump_receive_ump_val(ep->ump, *data) <= 0)
673 			continue;
674 		if (ump_message_type(*in_buf) == UMP_MSG_TYPE_STREAM)
675 			process_ump_stream_msg(ep, in_buf);
676 	}
677 }
678 
679 /*
680  * MIDI 2.0 UMP USB request handling
681  */
682 
683 /* complete handler for UMP EP-out requests */
684 static void f_midi2_ep_out_complete(struct usb_ep *usb_ep,
685 				    struct usb_request *req)
686 {
687 	struct f_midi2_req_ctx *ctx = req->context;
688 	struct f_midi2_ep *ep = ctx->usb_ep->ep;
689 	struct f_midi2 *midi2 = ep->card;
690 	int status = req->status;
691 
692 	if (status) {
693 		DBG(midi2, "%s complete error %d: %d/%d\n",
694 		    usb_ep->name, status, req->actual, req->length);
695 		goto error;
696 	}
697 
698 	/* convert to UMP packet in native endianness */
699 	le32_to_cpu_array((u32 *)req->buf, req->actual >> 2);
700 
701 	if (midi2->info.process_ump)
702 		process_ump(ep, req);
703 
704 	snd_ump_receive(ep->ump, req->buf, req->actual & ~3);
705 
706 	if (midi2->operation_mode != MIDI_OP_MODE_MIDI2)
707 		goto error;
708 
709 	if (queue_request_ep_raw(req))
710 		goto error;
711 	return;
712 
713  error:
714 	put_empty_request(req);
715 }
716 
717 /* Transmit UMP packets received from user-space to the gadget */
718 static void process_ump_transmit(struct f_midi2_ep *ep)
719 {
720 	struct f_midi2_usb_ep *usb_ep = &ep->ep_in;
721 	struct f_midi2 *midi2 = ep->card;
722 	struct usb_request *req;
723 	int len;
724 
725 	if (!usb_ep->usb_ep->enabled)
726 		return;
727 
728 	for (;;) {
729 		req = get_empty_request(usb_ep);
730 		if (!req)
731 			break;
732 		len = snd_ump_transmit(ep->ump, (u32 *)req->buf,
733 				       midi2->info.req_buf_size);
734 		if (len <= 0) {
735 			put_empty_request(req);
736 			break;
737 		}
738 
739 		req->length = len;
740 		if (queue_request_ep_in(req) < 0)
741 			break;
742 	}
743 }
744 
745 /* Complete handler for UMP EP-in requests */
746 static void f_midi2_ep_in_complete(struct usb_ep *usb_ep,
747 				   struct usb_request *req)
748 {
749 	struct f_midi2_req_ctx *ctx = req->context;
750 	struct f_midi2_ep *ep = ctx->usb_ep->ep;
751 	struct f_midi2 *midi2 = ep->card;
752 	int status = req->status;
753 
754 	put_empty_request(req);
755 
756 	if (status) {
757 		DBG(midi2, "%s complete error %d: %d/%d\n",
758 		    usb_ep->name, status, req->actual, req->length);
759 		return;
760 	}
761 
762 	process_ump_transmit(ep);
763 }
764 
765 /*
766  * MIDI1 (altset 0) USB request handling
767  */
768 
769 /* process one MIDI byte -- copied from f_midi.c
770  *
771  * fill the packet or request if needed
772  * returns true if the request became empty (queued)
773  */
774 static bool process_midi1_byte(struct f_midi2 *midi2, u8 cable, u8 b,
775 			       struct usb_request **req_p)
776 {
777 	struct f_midi2_midi1_port *port = &midi2->midi1_port[cable];
778 	u8 p[4] = { cable << 4, 0, 0, 0 };
779 	int next_state = STATE_INITIAL;
780 	struct usb_request *req = *req_p;
781 
782 	switch (b) {
783 	case 0xf8 ... 0xff:
784 		/* System Real-Time Messages */
785 		p[0] |= 0x0f;
786 		p[1] = b;
787 		next_state = port->state;
788 		port->state = STATE_REAL_TIME;
789 		break;
790 
791 	case 0xf7:
792 		/* End of SysEx */
793 		switch (port->state) {
794 		case STATE_SYSEX_0:
795 			p[0] |= 0x05;
796 			p[1] = 0xf7;
797 			next_state = STATE_FINISHED;
798 			break;
799 		case STATE_SYSEX_1:
800 			p[0] |= 0x06;
801 			p[1] = port->data[0];
802 			p[2] = 0xf7;
803 			next_state = STATE_FINISHED;
804 			break;
805 		case STATE_SYSEX_2:
806 			p[0] |= 0x07;
807 			p[1] = port->data[0];
808 			p[2] = port->data[1];
809 			p[3] = 0xf7;
810 			next_state = STATE_FINISHED;
811 			break;
812 		default:
813 			/* Ignore byte */
814 			next_state = port->state;
815 			port->state = STATE_INITIAL;
816 		}
817 		break;
818 
819 	case 0xf0 ... 0xf6:
820 		/* System Common Messages */
821 		port->data[0] = port->data[1] = 0;
822 		port->state = STATE_INITIAL;
823 		switch (b) {
824 		case 0xf0:
825 			port->data[0] = b;
826 			port->data[1] = 0;
827 			next_state = STATE_SYSEX_1;
828 			break;
829 		case 0xf1:
830 		case 0xf3:
831 			port->data[0] = b;
832 			next_state = STATE_1PARAM;
833 			break;
834 		case 0xf2:
835 			port->data[0] = b;
836 			next_state = STATE_2PARAM_1;
837 			break;
838 		case 0xf4:
839 		case 0xf5:
840 			next_state = STATE_INITIAL;
841 			break;
842 		case 0xf6:
843 			p[0] |= 0x05;
844 			p[1] = 0xf6;
845 			next_state = STATE_FINISHED;
846 			break;
847 		}
848 		break;
849 
850 	case 0x80 ... 0xef:
851 		/*
852 		 * Channel Voice Messages, Channel Mode Messages
853 		 * and Control Change Messages.
854 		 */
855 		port->data[0] = b;
856 		port->data[1] = 0;
857 		port->state = STATE_INITIAL;
858 		if (b >= 0xc0 && b <= 0xdf)
859 			next_state = STATE_1PARAM;
860 		else
861 			next_state = STATE_2PARAM_1;
862 		break;
863 
864 	case 0x00 ... 0x7f:
865 		/* Message parameters */
866 		switch (port->state) {
867 		case STATE_1PARAM:
868 			if (port->data[0] < 0xf0)
869 				p[0] |= port->data[0] >> 4;
870 			else
871 				p[0] |= 0x02;
872 
873 			p[1] = port->data[0];
874 			p[2] = b;
875 			/* This is to allow Running State Messages */
876 			next_state = STATE_1PARAM;
877 			break;
878 		case STATE_2PARAM_1:
879 			port->data[1] = b;
880 			next_state = STATE_2PARAM_2;
881 			break;
882 		case STATE_2PARAM_2:
883 			if (port->data[0] < 0xf0)
884 				p[0] |= port->data[0] >> 4;
885 			else
886 				p[0] |= 0x03;
887 
888 			p[1] = port->data[0];
889 			p[2] = port->data[1];
890 			p[3] = b;
891 			/* This is to allow Running State Messages */
892 			next_state = STATE_2PARAM_1;
893 			break;
894 		case STATE_SYSEX_0:
895 			port->data[0] = b;
896 			next_state = STATE_SYSEX_1;
897 			break;
898 		case STATE_SYSEX_1:
899 			port->data[1] = b;
900 			next_state = STATE_SYSEX_2;
901 			break;
902 		case STATE_SYSEX_2:
903 			p[0] |= 0x04;
904 			p[1] = port->data[0];
905 			p[2] = port->data[1];
906 			p[3] = b;
907 			next_state = STATE_SYSEX_0;
908 			break;
909 		}
910 		break;
911 	}
912 
913 	/* States where we have to write into the USB request */
914 	if (next_state == STATE_FINISHED ||
915 	    port->state == STATE_SYSEX_2 ||
916 	    port->state == STATE_1PARAM ||
917 	    port->state == STATE_2PARAM_2 ||
918 	    port->state == STATE_REAL_TIME) {
919 		memcpy(req->buf + req->length, p, sizeof(p));
920 		req->length += sizeof(p);
921 
922 		if (next_state == STATE_FINISHED) {
923 			next_state = STATE_INITIAL;
924 			port->data[0] = port->data[1] = 0;
925 		}
926 
927 		if (midi2->info.req_buf_size - req->length <= 4) {
928 			queue_request_ep_raw(req);
929 			*req_p = NULL;
930 			return true;
931 		}
932 	}
933 
934 	port->state = next_state;
935 	return false;
936 }
937 
938 /* process all pending MIDI bytes in the internal buffer;
939  * returns true if the request gets empty
940  * returns false if all have been processed
941  */
942 static bool process_midi1_pending_buf(struct f_midi2 *midi2,
943 				      struct usb_request **req_p)
944 {
945 	unsigned int cable, c;
946 
947 	for (cable = 0; cable < midi2->num_midi1_in; cable++) {
948 		struct f_midi2_midi1_port *port = &midi2->midi1_port[cable];
949 
950 		if (!port->pending)
951 			continue;
952 		for (c = 0; c < port->pending; c++) {
953 			if (process_midi1_byte(midi2, cable, port->buf[c],
954 					       req_p)) {
955 				port->pending -= c;
956 				if (port->pending)
957 					memmove(port->buf, port->buf + c,
958 						port->pending);
959 				return true;
960 			}
961 		}
962 		port->pending = 0;
963 	}
964 
965 	return false;
966 }
967 
968 /* fill the MIDI bytes onto the temporary buffer
969  */
970 static void fill_midi1_pending_buf(struct f_midi2 *midi2, u8 cable, u8 *buf,
971 				   unsigned int size)
972 {
973 	struct f_midi2_midi1_port *port = &midi2->midi1_port[cable];
974 
975 	if (port->pending + size > sizeof(port->buf))
976 		return;
977 	memcpy(port->buf + port->pending, buf, size);
978 	port->pending += size;
979 }
980 
981 /* try to process data given from the associated UMP stream */
982 static void process_midi1_transmit(struct f_midi2 *midi2)
983 {
984 	struct f_midi2_usb_ep *usb_ep = &midi2->midi1_ep_in;
985 	struct f_midi2_ep *ep = &midi2->midi2_eps[0];
986 	struct usb_request *req = NULL;
987 	/* 12 is the largest outcome (4 MIDI1 cmds) for a single UMP packet */
988 	unsigned char outbuf[12];
989 	unsigned char group, cable;
990 	int len, size;
991 	u32 ump;
992 
993 	if (!usb_ep->usb_ep || !usb_ep->usb_ep->enabled)
994 		return;
995 
996 	for (;;) {
997 		if (!req) {
998 			req = get_empty_request(usb_ep);
999 			if (!req)
1000 				break;
1001 		}
1002 
1003 		if (process_midi1_pending_buf(midi2, &req))
1004 			continue;
1005 
1006 		len = snd_ump_transmit(ep->ump, &ump, 4);
1007 		if (len <= 0)
1008 			break;
1009 		if (snd_ump_receive_ump_val(ep->ump, ump) <= 0)
1010 			continue;
1011 		size = snd_ump_convert_from_ump(ep->ump->input_buf, outbuf,
1012 						&group);
1013 		if (size <= 0)
1014 			continue;
1015 		cable = ep->in_group_to_cable[group];
1016 		if (!cable)
1017 			continue;
1018 		cable--; /* to 0-base */
1019 		fill_midi1_pending_buf(midi2, cable, outbuf, size);
1020 	}
1021 
1022 	if (req) {
1023 		if (req->length)
1024 			queue_request_ep_raw(req);
1025 		else
1026 			put_empty_request(req);
1027 	}
1028 }
1029 
1030 /* complete handler for MIDI1 EP-in requests */
1031 static void f_midi2_midi1_ep_in_complete(struct usb_ep *usb_ep,
1032 					 struct usb_request *req)
1033 {
1034 	struct f_midi2_req_ctx *ctx = req->context;
1035 	struct f_midi2 *midi2 = ctx->usb_ep->card;
1036 	int status = req->status;
1037 
1038 	put_empty_request(req);
1039 
1040 	if (status) {
1041 		DBG(midi2, "%s complete error %d: %d/%d\n",
1042 		    usb_ep->name, status, req->actual, req->length);
1043 		return;
1044 	}
1045 
1046 	process_midi1_transmit(midi2);
1047 }
1048 
1049 /* complete handler for MIDI1 EP-out requests */
1050 static void f_midi2_midi1_ep_out_complete(struct usb_ep *usb_ep,
1051 					  struct usb_request *req)
1052 {
1053 	struct f_midi2_req_ctx *ctx = req->context;
1054 	struct f_midi2 *midi2 = ctx->usb_ep->card;
1055 	struct f_midi2_ep *ep;
1056 	struct ump_cvt_to_ump *cvt = &midi2->midi1_ump_cvt;
1057 	static const u8 midi1_packet_bytes[16] = {
1058 		0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1
1059 	};
1060 	unsigned int group, cable, bytes, c, len;
1061 	int status = req->status;
1062 	const u8 *buf = req->buf;
1063 
1064 	if (status) {
1065 		DBG(midi2, "%s complete error %d: %d/%d\n",
1066 		    usb_ep->name, status, req->actual, req->length);
1067 		goto error;
1068 	}
1069 
1070 	len = req->actual >> 2;
1071 	for (; len; len--, buf += 4) {
1072 		cable = *buf >> 4;
1073 		ep = midi2->out_cable_mapping[cable].ep;
1074 		if (!ep)
1075 			continue;
1076 		group = midi2->out_cable_mapping[cable].group;
1077 		bytes = midi1_packet_bytes[*buf & 0x0f];
1078 		for (c = 0; c < bytes; c++) {
1079 			snd_ump_convert_to_ump(cvt, group,
1080 					       to_ump_protocol(ep->info.protocol),
1081 					       buf[c + 1]);
1082 			if (cvt->ump_bytes) {
1083 				snd_ump_receive(ep->ump, cvt->ump,
1084 						cvt->ump_bytes);
1085 				cvt->ump_bytes = 0;
1086 			}
1087 		}
1088 	}
1089 
1090 	if (midi2->operation_mode != MIDI_OP_MODE_MIDI1)
1091 		goto error;
1092 
1093 	if (queue_request_ep_raw(req))
1094 		goto error;
1095 	return;
1096 
1097  error:
1098 	put_empty_request(req);
1099 }
1100 
1101 /*
1102  * Common EP handling helpers
1103  */
1104 
1105 /* Start MIDI EP */
1106 static int f_midi2_start_ep(struct f_midi2_usb_ep *usb_ep,
1107 			    struct usb_function *fn)
1108 {
1109 	int err;
1110 
1111 	if (!usb_ep->usb_ep)
1112 		return 0;
1113 
1114 	usb_ep_disable(usb_ep->usb_ep);
1115 	err = config_ep_by_speed(usb_ep->card->gadget, fn, usb_ep->usb_ep);
1116 	if (err)
1117 		return err;
1118 	return usb_ep_enable(usb_ep->usb_ep);
1119 }
1120 
1121 /* Drop pending requests */
1122 static void f_midi2_drop_reqs(struct f_midi2_usb_ep *usb_ep)
1123 {
1124 	int i;
1125 
1126 	if (!usb_ep->usb_ep || !usb_ep->num_reqs)
1127 		return;
1128 
1129 	for (i = 0; i < usb_ep->num_reqs; i++) {
1130 		if (!test_bit(i, &usb_ep->free_reqs) && usb_ep->reqs[i].req) {
1131 			usb_ep_dequeue(usb_ep->usb_ep, usb_ep->reqs[i].req);
1132 			set_bit(i, &usb_ep->free_reqs);
1133 		}
1134 	}
1135 }
1136 
1137 /* Allocate requests for the given EP */
1138 static int f_midi2_alloc_ep_reqs(struct f_midi2_usb_ep *usb_ep)
1139 {
1140 	struct f_midi2 *midi2 = usb_ep->card;
1141 	int i;
1142 
1143 	if (!usb_ep->usb_ep)
1144 		return 0;
1145 	if (!usb_ep->reqs)
1146 		return -EINVAL;
1147 
1148 	for (i = 0; i < midi2->info.num_reqs; i++) {
1149 		if (usb_ep->reqs[i].req)
1150 			continue;
1151 		usb_ep->reqs[i].req = alloc_ep_req(usb_ep->usb_ep,
1152 						   midi2->info.req_buf_size);
1153 		if (!usb_ep->reqs[i].req)
1154 			return -ENOMEM;
1155 		usb_ep->reqs[i].req->context = &usb_ep->reqs[i];
1156 	}
1157 	return 0;
1158 }
1159 
1160 /* Free allocated requests */
1161 static void f_midi2_free_ep_reqs(struct f_midi2_usb_ep *usb_ep)
1162 {
1163 	struct f_midi2 *midi2 = usb_ep->card;
1164 	int i;
1165 
1166 	for (i = 0; i < midi2->info.num_reqs; i++) {
1167 		if (!usb_ep->reqs[i].req)
1168 			continue;
1169 		free_ep_req(usb_ep->usb_ep, usb_ep->reqs[i].req);
1170 		usb_ep->reqs[i].req = NULL;
1171 	}
1172 }
1173 
1174 /* Initialize EP */
1175 static int f_midi2_init_ep(struct f_midi2 *midi2, struct f_midi2_ep *ep,
1176 			   struct f_midi2_usb_ep *usb_ep,
1177 			   void *desc,
1178 			   void (*complete)(struct usb_ep *usb_ep,
1179 					    struct usb_request *req))
1180 {
1181 	int i;
1182 
1183 	usb_ep->card = midi2;
1184 	usb_ep->ep = ep;
1185 	usb_ep->usb_ep = usb_ep_autoconfig(midi2->gadget, desc);
1186 	if (!usb_ep->usb_ep)
1187 		return -ENODEV;
1188 	usb_ep->complete = complete;
1189 
1190 	usb_ep->reqs = kcalloc(midi2->info.num_reqs, sizeof(*usb_ep->reqs),
1191 			       GFP_KERNEL);
1192 	if (!usb_ep->reqs)
1193 		return -ENOMEM;
1194 	for (i = 0; i < midi2->info.num_reqs; i++) {
1195 		usb_ep->reqs[i].index = i;
1196 		usb_ep->reqs[i].usb_ep = usb_ep;
1197 		set_bit(i, &usb_ep->free_reqs);
1198 		usb_ep->num_reqs++;
1199 	}
1200 
1201 	return 0;
1202 }
1203 
1204 /* Free EP */
1205 static void f_midi2_free_ep(struct f_midi2_usb_ep *usb_ep)
1206 {
1207 	f_midi2_drop_reqs(usb_ep);
1208 
1209 	f_midi2_free_ep_reqs(usb_ep);
1210 
1211 	kfree(usb_ep->reqs);
1212 	usb_ep->num_reqs = 0;
1213 	usb_ep->free_reqs = 0;
1214 	usb_ep->reqs = NULL;
1215 }
1216 
1217 /* Queue requests for EP-out at start */
1218 static void f_midi2_queue_out_reqs(struct f_midi2_usb_ep *usb_ep)
1219 {
1220 	int i, err;
1221 
1222 	if (!usb_ep->usb_ep)
1223 		return;
1224 
1225 	for (i = 0; i < usb_ep->num_reqs; i++) {
1226 		if (!test_bit(i, &usb_ep->free_reqs) || !usb_ep->reqs[i].req)
1227 			continue;
1228 		usb_ep->reqs[i].req->complete = usb_ep->complete;
1229 		err = usb_ep_queue(usb_ep->usb_ep, usb_ep->reqs[i].req,
1230 				   GFP_ATOMIC);
1231 		if (!err)
1232 			clear_bit(i, &usb_ep->free_reqs);
1233 	}
1234 }
1235 
1236 /*
1237  * Gadget Function callbacks
1238  */
1239 
1240 /* stop both IN and OUT EPs */
1241 static void f_midi2_stop_eps(struct f_midi2_usb_ep *ep_in,
1242 			     struct f_midi2_usb_ep *ep_out)
1243 {
1244 	f_midi2_drop_reqs(ep_in);
1245 	f_midi2_drop_reqs(ep_out);
1246 	f_midi2_free_ep_reqs(ep_in);
1247 	f_midi2_free_ep_reqs(ep_out);
1248 }
1249 
1250 /* start/queue both IN and OUT EPs */
1251 static int f_midi2_start_eps(struct f_midi2_usb_ep *ep_in,
1252 			     struct f_midi2_usb_ep *ep_out,
1253 			     struct usb_function *fn)
1254 {
1255 	int err;
1256 
1257 	err = f_midi2_start_ep(ep_in, fn);
1258 	if (err)
1259 		return err;
1260 	err = f_midi2_start_ep(ep_out, fn);
1261 	if (err)
1262 		return err;
1263 
1264 	err = f_midi2_alloc_ep_reqs(ep_in);
1265 	if (err)
1266 		return err;
1267 	err = f_midi2_alloc_ep_reqs(ep_out);
1268 	if (err)
1269 		return err;
1270 
1271 	f_midi2_queue_out_reqs(ep_out);
1272 	return 0;
1273 }
1274 
1275 /* gadget function set_alt callback */
1276 static int f_midi2_set_alt(struct usb_function *fn, unsigned int intf,
1277 			   unsigned int alt)
1278 {
1279 	struct f_midi2 *midi2 = func_to_midi2(fn);
1280 	struct f_midi2_ep *ep;
1281 	int i, op_mode, err;
1282 
1283 	if (intf != midi2->midi_if || alt > 1)
1284 		return 0;
1285 
1286 	if (alt == 0)
1287 		op_mode = MIDI_OP_MODE_MIDI1;
1288 	else if (alt == 1)
1289 		op_mode = MIDI_OP_MODE_MIDI2;
1290 	else
1291 		op_mode = MIDI_OP_MODE_UNSET;
1292 
1293 	if (midi2->operation_mode == op_mode)
1294 		return 0;
1295 
1296 	midi2->operation_mode = op_mode;
1297 
1298 	if (op_mode != MIDI_OP_MODE_MIDI1)
1299 		f_midi2_stop_eps(&midi2->midi1_ep_in, &midi2->midi1_ep_out);
1300 
1301 	if (op_mode != MIDI_OP_MODE_MIDI2) {
1302 		for (i = 0; i < midi2->num_eps; i++) {
1303 			ep = &midi2->midi2_eps[i];
1304 			f_midi2_stop_eps(&ep->ep_in, &ep->ep_out);
1305 		}
1306 	}
1307 
1308 	if (op_mode == MIDI_OP_MODE_MIDI1)
1309 		return f_midi2_start_eps(&midi2->midi1_ep_in,
1310 					 &midi2->midi1_ep_out, fn);
1311 
1312 	if (op_mode == MIDI_OP_MODE_MIDI2) {
1313 		for (i = 0; i < midi2->num_eps; i++) {
1314 			ep = &midi2->midi2_eps[i];
1315 
1316 			err = f_midi2_start_eps(&ep->ep_in, &ep->ep_out, fn);
1317 			if (err)
1318 				return err;
1319 		}
1320 	}
1321 
1322 	return 0;
1323 }
1324 
1325 /* gadget function get_alt callback */
1326 static int f_midi2_get_alt(struct usb_function *fn, unsigned int intf)
1327 {
1328 	struct f_midi2 *midi2 = func_to_midi2(fn);
1329 
1330 	if (intf == midi2->midi_if &&
1331 	    midi2->operation_mode == MIDI_OP_MODE_MIDI2)
1332 		return 1;
1333 	return 0;
1334 }
1335 
1336 /* convert UMP direction to USB MIDI 2.0 direction */
1337 static unsigned int ump_to_usb_dir(unsigned int ump_dir)
1338 {
1339 	switch (ump_dir) {
1340 	case SNDRV_UMP_DIR_INPUT:
1341 		return USB_MS_GR_TRM_BLOCK_TYPE_INPUT_ONLY;
1342 	case SNDRV_UMP_DIR_OUTPUT:
1343 		return USB_MS_GR_TRM_BLOCK_TYPE_OUTPUT_ONLY;
1344 	default:
1345 		return USB_MS_GR_TRM_BLOCK_TYPE_BIDIRECTIONAL;
1346 	}
1347 }
1348 
1349 /* assign GTB descriptors (for the given request) */
1350 static void assign_block_descriptors(struct f_midi2 *midi2,
1351 				     struct usb_request *req,
1352 				     int max_len)
1353 {
1354 	struct usb_ms20_gr_trm_block_header_descriptor header;
1355 	struct usb_ms20_gr_trm_block_descriptor *desc;
1356 	struct f_midi2_block_info *b;
1357 	struct f_midi2_ep *ep;
1358 	int i, blk, len;
1359 	char *data;
1360 
1361 	len = sizeof(gtb_header_desc) + sizeof(gtb_desc) * midi2->total_blocks;
1362 	if (WARN_ON(len > midi2->info.req_buf_size))
1363 		return;
1364 
1365 	header = gtb_header_desc;
1366 	header.wTotalLength = cpu_to_le16(len);
1367 	if (max_len < len) {
1368 		len = min_t(int, len, sizeof(header));
1369 		memcpy(req->buf, &header, len);
1370 		req->length = len;
1371 		req->zero = len < max_len;
1372 		return;
1373 	}
1374 
1375 	memcpy(req->buf, &header, sizeof(header));
1376 	data = req->buf + sizeof(header);
1377 	for (i = 0; i < midi2->num_eps; i++) {
1378 		ep = &midi2->midi2_eps[i];
1379 		for (blk = 0; blk < ep->num_blks; blk++) {
1380 			b = &ep->blks[blk].info;
1381 			desc = (struct usb_ms20_gr_trm_block_descriptor *)data;
1382 
1383 			*desc = gtb_desc;
1384 			desc->bGrpTrmBlkID = ep->blks[blk].gtb_id;
1385 			desc->bGrpTrmBlkType = ump_to_usb_dir(b->direction);
1386 			desc->nGroupTrm = b->first_group;
1387 			desc->nNumGroupTrm = b->num_groups;
1388 			desc->iBlockItem = ep->blks[blk].string_id;
1389 
1390 			if (ep->info.protocol == 2)
1391 				desc->bMIDIProtocol = USB_MS_MIDI_PROTO_2_0;
1392 			else
1393 				desc->bMIDIProtocol = USB_MS_MIDI_PROTO_1_0_128;
1394 
1395 			if (b->is_midi1 == 2) {
1396 				desc->wMaxInputBandwidth = cpu_to_le16(1);
1397 				desc->wMaxOutputBandwidth = cpu_to_le16(1);
1398 			}
1399 
1400 			data += sizeof(*desc);
1401 		}
1402 	}
1403 
1404 	req->length = len;
1405 	req->zero = len < max_len;
1406 }
1407 
1408 /* gadget function setup callback: handle GTB requests */
1409 static int f_midi2_setup(struct usb_function *fn,
1410 			 const struct usb_ctrlrequest *ctrl)
1411 {
1412 	struct f_midi2 *midi2 = func_to_midi2(fn);
1413 	struct usb_composite_dev *cdev = fn->config->cdev;
1414 	struct usb_request *req = cdev->req;
1415 	u16 value, length;
1416 
1417 	if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD ||
1418 	    ctrl->bRequest != USB_REQ_GET_DESCRIPTOR)
1419 		return -EOPNOTSUPP;
1420 
1421 	value = le16_to_cpu(ctrl->wValue);
1422 	length = le16_to_cpu(ctrl->wLength);
1423 
1424 	if ((value >> 8) != USB_DT_CS_GR_TRM_BLOCK)
1425 		return -EOPNOTSUPP;
1426 
1427 	/* handle only altset 1 */
1428 	if ((value & 0xff) != 1)
1429 		return -EOPNOTSUPP;
1430 
1431 	assign_block_descriptors(midi2, req, length);
1432 	return usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
1433 }
1434 
1435 /* gadget function disable callback */
1436 static void f_midi2_disable(struct usb_function *fn)
1437 {
1438 	struct f_midi2 *midi2 = func_to_midi2(fn);
1439 
1440 	midi2->operation_mode = MIDI_OP_MODE_UNSET;
1441 }
1442 
1443 /*
1444  * ALSA UMP ops: most of them are NOPs, only trigger for write is needed
1445  */
1446 static int f_midi2_ump_open(struct snd_ump_endpoint *ump, int dir)
1447 {
1448 	return 0;
1449 }
1450 
1451 static void f_midi2_ump_close(struct snd_ump_endpoint *ump, int dir)
1452 {
1453 }
1454 
1455 static void f_midi2_ump_trigger(struct snd_ump_endpoint *ump, int dir, int up)
1456 {
1457 	struct f_midi2_ep *ep = ump->private_data;
1458 	struct f_midi2 *midi2 = ep->card;
1459 
1460 	if (up && dir == SNDRV_RAWMIDI_STREAM_OUTPUT) {
1461 		switch (midi2->operation_mode) {
1462 		case MIDI_OP_MODE_MIDI1:
1463 			process_midi1_transmit(midi2);
1464 			break;
1465 		case MIDI_OP_MODE_MIDI2:
1466 			process_ump_transmit(ep);
1467 			break;
1468 		}
1469 	}
1470 }
1471 
1472 static void f_midi2_ump_drain(struct snd_ump_endpoint *ump, int dir)
1473 {
1474 }
1475 
1476 static const struct snd_ump_ops f_midi2_ump_ops = {
1477 	.open = f_midi2_ump_open,
1478 	.close = f_midi2_ump_close,
1479 	.trigger = f_midi2_ump_trigger,
1480 	.drain = f_midi2_ump_drain,
1481 };
1482 
1483 /*
1484  * "Operation Mode" control element
1485  */
1486 static int f_midi2_operation_mode_info(struct snd_kcontrol *kcontrol,
1487 				       struct snd_ctl_elem_info *uinfo)
1488 {
1489 	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1490 	uinfo->count = 1;
1491 	uinfo->value.integer.min = MIDI_OP_MODE_UNSET;
1492 	uinfo->value.integer.max = MIDI_OP_MODE_MIDI2;
1493 	return 0;
1494 }
1495 
1496 static int f_midi2_operation_mode_get(struct snd_kcontrol *kcontrol,
1497 				      struct snd_ctl_elem_value *ucontrol)
1498 {
1499 	struct f_midi2 *midi2 = snd_kcontrol_chip(kcontrol);
1500 
1501 	ucontrol->value.integer.value[0] = midi2->operation_mode;
1502 	return 0;
1503 }
1504 
1505 static const struct snd_kcontrol_new operation_mode_ctl = {
1506 	.iface = SNDRV_CTL_ELEM_IFACE_RAWMIDI,
1507 	.name = "Operation Mode",
1508 	.access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE,
1509 	.info = f_midi2_operation_mode_info,
1510 	.get = f_midi2_operation_mode_get,
1511 };
1512 
1513 /*
1514  * ALSA UMP instance creation / deletion
1515  */
1516 static void f_midi2_free_card(struct f_midi2 *midi2)
1517 {
1518 	if (midi2->card) {
1519 		snd_card_free_when_closed(midi2->card);
1520 		midi2->card = NULL;
1521 	}
1522 }
1523 
1524 /* use a reverse direction for the gadget host */
1525 static int reverse_dir(int dir)
1526 {
1527 	if (!dir || dir == SNDRV_UMP_DIR_BIDIRECTION)
1528 		return dir;
1529 	return (dir == SNDRV_UMP_DIR_OUTPUT) ?
1530 		SNDRV_UMP_DIR_INPUT : SNDRV_UMP_DIR_OUTPUT;
1531 }
1532 
1533 static int f_midi2_create_card(struct f_midi2 *midi2)
1534 {
1535 	struct snd_card *card;
1536 	struct snd_ump_endpoint *ump;
1537 	struct f_midi2_ep *ep;
1538 	int i, id, blk, err;
1539 	__be32 sw;
1540 
1541 	err = snd_card_new(&midi2->gadget->dev, -1, NULL, THIS_MODULE, 0,
1542 			   &card);
1543 	if (err < 0)
1544 		return err;
1545 	midi2->card = card;
1546 
1547 	strcpy(card->driver, "f_midi2");
1548 	strcpy(card->shortname, "MIDI 2.0 Gadget");
1549 	strcpy(card->longname, "MIDI 2.0 Gadget");
1550 
1551 	id = 0;
1552 	for (i = 0; i < midi2->num_eps; i++) {
1553 		ep = &midi2->midi2_eps[i];
1554 		err = snd_ump_endpoint_new(card, "MIDI 2.0 Gadget", id,
1555 					   1, 1, &ump);
1556 		if (err < 0)
1557 			goto error;
1558 		id++;
1559 
1560 		ep->ump = ump;
1561 		ump->no_process_stream = true;
1562 		ump->private_data = ep;
1563 		ump->ops = &f_midi2_ump_ops;
1564 		if (midi2->info.static_block)
1565 			ump->info.flags |= SNDRV_UMP_EP_INFO_STATIC_BLOCKS;
1566 		ump->info.protocol_caps = (ep->info.protocol_caps & 3) << 8;
1567 		ump->info.protocol = to_ump_protocol(ep->info.protocol);
1568 		ump->info.version = 0x0101;
1569 		ump->info.family_id = ep->info.family;
1570 		ump->info.model_id = ep->info.model;
1571 		ump->info.manufacturer_id = ep->info.manufacturer & 0xffffff;
1572 		sw = cpu_to_be32(ep->info.sw_revision);
1573 		memcpy(ump->info.sw_revision, &sw, 4);
1574 
1575 		strscpy(ump->info.name, ump_ep_name(ep),
1576 			sizeof(ump->info.name));
1577 		strscpy(ump->info.product_id, ump_product_id(ep),
1578 			sizeof(ump->info.product_id));
1579 		strscpy(ump->core.name, ump->info.name, sizeof(ump->core.name));
1580 
1581 		for (blk = 0; blk < ep->num_blks; blk++) {
1582 			const struct f_midi2_block_info *b = &ep->blks[blk].info;
1583 			struct snd_ump_block *fb;
1584 
1585 			err = snd_ump_block_new(ump, blk,
1586 						reverse_dir(b->direction),
1587 						b->first_group, b->num_groups,
1588 						&ep->blks[blk].fb);
1589 			if (err < 0)
1590 				goto error;
1591 			fb = ep->blks[blk].fb;
1592 			fb->info.active = !!b->active;
1593 			fb->info.midi_ci_version = b->midi_ci_version;
1594 			fb->info.ui_hint = reverse_dir(b->ui_hint);
1595 			fb->info.sysex8_streams = b->sysex8_streams;
1596 			fb->info.flags |= b->is_midi1;
1597 			strscpy(fb->info.name, ump_fb_name(b),
1598 				sizeof(fb->info.name));
1599 		}
1600 	}
1601 
1602 	for (i = 0; i < midi2->num_eps; i++) {
1603 		err = snd_ump_attach_legacy_rawmidi(midi2->midi2_eps[i].ump,
1604 						    "Legacy MIDI", id);
1605 		if (err < 0)
1606 			goto error;
1607 		id++;
1608 	}
1609 
1610 	err = snd_ctl_add(card, snd_ctl_new1(&operation_mode_ctl, midi2));
1611 	if (err < 0)
1612 		goto error;
1613 
1614 	err = snd_card_register(card);
1615 	if (err < 0)
1616 		goto error;
1617 
1618 	return 0;
1619 
1620  error:
1621 	f_midi2_free_card(midi2);
1622 	return err;
1623 }
1624 
1625 /*
1626  * Creation of USB descriptors
1627  */
1628 struct f_midi2_usb_config {
1629 	struct usb_descriptor_header **list;
1630 	unsigned int size;
1631 	unsigned int alloc;
1632 
1633 	/* MIDI 1.0 jacks */
1634 	unsigned char jack_in, jack_out, jack_id;
1635 	struct usb_midi_in_jack_descriptor jack_ins[MAX_CABLES];
1636 	struct usb_midi_out_jack_descriptor_1 jack_outs[MAX_CABLES];
1637 };
1638 
1639 static int append_config(struct f_midi2_usb_config *config, void *d)
1640 {
1641 	unsigned int size;
1642 	void *buf;
1643 
1644 	if (config->size + 2 >= config->alloc) {
1645 		size = config->size + 16;
1646 		buf = krealloc(config->list, size * sizeof(void *), GFP_KERNEL);
1647 		if (!buf)
1648 			return -ENOMEM;
1649 		config->list = buf;
1650 		config->alloc = size;
1651 	}
1652 
1653 	config->list[config->size] = d;
1654 	config->size++;
1655 	config->list[config->size] = NULL;
1656 	return 0;
1657 }
1658 
1659 static int append_configs(struct f_midi2_usb_config *config, void **d)
1660 {
1661 	int err;
1662 
1663 	for (; *d; d++) {
1664 		err = append_config(config, *d);
1665 		if (err)
1666 			return err;
1667 	}
1668 	return 0;
1669 }
1670 
1671 static int append_midi1_in_jack(struct f_midi2 *midi2,
1672 				struct f_midi2_usb_config *config,
1673 				struct midi1_cable_mapping *map,
1674 				unsigned int type)
1675 {
1676 	struct usb_midi_in_jack_descriptor *jack =
1677 		&config->jack_ins[config->jack_in++];
1678 	int id = ++config->jack_id;
1679 	int err;
1680 
1681 	jack->bLength = 0x06;
1682 	jack->bDescriptorType = USB_DT_CS_INTERFACE;
1683 	jack->bDescriptorSubtype = USB_MS_MIDI_IN_JACK;
1684 	jack->bJackType = type;
1685 	jack->bJackID = id;
1686 	/* use the corresponding block name as jack name */
1687 	if (map->ep)
1688 		jack->iJack = map->ep->blks[map->block].string_id;
1689 
1690 	err = append_config(config, jack);
1691 	if (err < 0)
1692 		return err;
1693 	return id;
1694 }
1695 
1696 static int append_midi1_out_jack(struct f_midi2 *midi2,
1697 				 struct f_midi2_usb_config *config,
1698 				 struct midi1_cable_mapping *map,
1699 				 unsigned int type, unsigned int source)
1700 {
1701 	struct usb_midi_out_jack_descriptor_1 *jack =
1702 		&config->jack_outs[config->jack_out++];
1703 	int id = ++config->jack_id;
1704 	int err;
1705 
1706 	jack->bLength = 0x09;
1707 	jack->bDescriptorType = USB_DT_CS_INTERFACE;
1708 	jack->bDescriptorSubtype = USB_MS_MIDI_OUT_JACK;
1709 	jack->bJackType = type;
1710 	jack->bJackID = id;
1711 	jack->bNrInputPins = 1;
1712 	jack->pins[0].baSourceID = source;
1713 	jack->pins[0].baSourcePin = 0x01;
1714 	/* use the corresponding block name as jack name */
1715 	if (map->ep)
1716 		jack->iJack = map->ep->blks[map->block].string_id;
1717 
1718 	err = append_config(config, jack);
1719 	if (err < 0)
1720 		return err;
1721 	return id;
1722 }
1723 
1724 static int f_midi2_create_usb_configs(struct f_midi2 *midi2,
1725 				      struct f_midi2_usb_config *config,
1726 				      int speed)
1727 {
1728 	void **midi1_in_eps, **midi1_out_eps;
1729 	int i, jack, total;
1730 	int err;
1731 
1732 	switch (speed) {
1733 	default:
1734 	case USB_SPEED_HIGH:
1735 		midi2_midi1_ep_out_desc.wMaxPacketSize = cpu_to_le16(512);
1736 		midi2_midi1_ep_in_desc.wMaxPacketSize = cpu_to_le16(512);
1737 		for (i = 0; i < midi2->num_eps; i++)
1738 			midi2_midi2_ep_out_desc[i].wMaxPacketSize =
1739 				cpu_to_le16(512);
1740 		fallthrough;
1741 	case USB_SPEED_FULL:
1742 		midi1_in_eps = midi2_midi1_ep_in_descs;
1743 		midi1_out_eps = midi2_midi1_ep_out_descs;
1744 		break;
1745 	case USB_SPEED_SUPER:
1746 		midi2_midi1_ep_out_desc.wMaxPacketSize = cpu_to_le16(1024);
1747 		midi2_midi1_ep_in_desc.wMaxPacketSize = cpu_to_le16(1024);
1748 		for (i = 0; i < midi2->num_eps; i++)
1749 			midi2_midi2_ep_out_desc[i].wMaxPacketSize =
1750 				cpu_to_le16(1024);
1751 		midi1_in_eps = midi2_midi1_ep_in_ss_descs;
1752 		midi1_out_eps = midi2_midi1_ep_out_ss_descs;
1753 		break;
1754 	}
1755 
1756 	err = append_configs(config, midi2_audio_descs);
1757 	if (err < 0)
1758 		return err;
1759 
1760 	if (midi2->num_midi1_in && midi2->num_midi1_out)
1761 		midi2_midi1_if_desc.bNumEndpoints = 2;
1762 	else
1763 		midi2_midi1_if_desc.bNumEndpoints = 1;
1764 
1765 	err = append_configs(config, midi2_midi1_descs);
1766 	if (err < 0)
1767 		return err;
1768 
1769 	total = USB_DT_MS_HEADER_SIZE;
1770 	if (midi2->num_midi1_out) {
1771 		midi2_midi1_ep_out_class_desc.bLength =
1772 			USB_DT_MS_ENDPOINT_SIZE(midi2->num_midi1_out);
1773 		total += midi2_midi1_ep_out_class_desc.bLength;
1774 		midi2_midi1_ep_out_class_desc.bNumEmbMIDIJack =
1775 			midi2->num_midi1_out;
1776 		total += midi2->num_midi1_out *
1777 			(USB_DT_MIDI_IN_SIZE + USB_DT_MIDI_OUT_SIZE(1));
1778 		for (i = 0; i < midi2->num_midi1_out; i++) {
1779 			jack = append_midi1_in_jack(midi2, config,
1780 						    &midi2->in_cable_mapping[i],
1781 						    USB_MS_EMBEDDED);
1782 			if (jack < 0)
1783 				return jack;
1784 			midi2_midi1_ep_out_class_desc.baAssocJackID[i] = jack;
1785 			jack = append_midi1_out_jack(midi2, config,
1786 						     &midi2->in_cable_mapping[i],
1787 						     USB_MS_EXTERNAL, jack);
1788 			if (jack < 0)
1789 				return jack;
1790 		}
1791 	}
1792 
1793 	if (midi2->num_midi1_in) {
1794 		midi2_midi1_ep_in_class_desc.bLength =
1795 			USB_DT_MS_ENDPOINT_SIZE(midi2->num_midi1_in);
1796 		total += midi2_midi1_ep_in_class_desc.bLength;
1797 		midi2_midi1_ep_in_class_desc.bNumEmbMIDIJack =
1798 			midi2->num_midi1_in;
1799 		total += midi2->num_midi1_in *
1800 			(USB_DT_MIDI_IN_SIZE + USB_DT_MIDI_OUT_SIZE(1));
1801 		for (i = 0; i < midi2->num_midi1_in; i++) {
1802 			jack = append_midi1_in_jack(midi2, config,
1803 						    &midi2->out_cable_mapping[i],
1804 						    USB_MS_EXTERNAL);
1805 			if (jack < 0)
1806 				return jack;
1807 			jack = append_midi1_out_jack(midi2, config,
1808 						     &midi2->out_cable_mapping[i],
1809 						     USB_MS_EMBEDDED, jack);
1810 			if (jack < 0)
1811 				return jack;
1812 			midi2_midi1_ep_in_class_desc.baAssocJackID[i] = jack;
1813 		}
1814 	}
1815 
1816 	midi2_midi1_class_desc.wTotalLength = cpu_to_le16(total);
1817 
1818 	if (midi2->num_midi1_out) {
1819 		err = append_configs(config, midi1_out_eps);
1820 		if (err < 0)
1821 			return err;
1822 	}
1823 	if (midi2->num_midi1_in) {
1824 		err = append_configs(config, midi1_in_eps);
1825 		if (err < 0)
1826 			return err;
1827 	}
1828 
1829 	err = append_configs(config, midi2_midi2_descs);
1830 	if (err < 0)
1831 		return err;
1832 
1833 	for (i = 0; i < midi2->num_eps; i++) {
1834 		err = append_config(config, &midi2_midi2_ep_out_desc[i]);
1835 		if (err < 0)
1836 			return err;
1837 		if (speed == USB_SPEED_SUPER || speed == USB_SPEED_SUPER_PLUS) {
1838 			err = append_config(config, &midi2_midi2_ep_out_ss_comp_desc);
1839 			if (err < 0)
1840 				return err;
1841 		}
1842 		err = append_config(config, &midi2_midi2_ep_out_class_desc[i]);
1843 		if (err < 0)
1844 			return err;
1845 		err = append_config(config, &midi2_midi2_ep_in_desc[i]);
1846 		if (err < 0)
1847 			return err;
1848 		if (speed == USB_SPEED_SUPER || speed == USB_SPEED_SUPER_PLUS) {
1849 			err = append_config(config, &midi2_midi2_ep_in_ss_comp_desc);
1850 			if (err < 0)
1851 				return err;
1852 		}
1853 		err = append_config(config, &midi2_midi2_ep_in_class_desc[i]);
1854 		if (err < 0)
1855 			return err;
1856 	}
1857 
1858 	return 0;
1859 }
1860 
1861 static void f_midi2_free_usb_configs(struct f_midi2_usb_config *config)
1862 {
1863 	kfree(config->list);
1864 	memset(config, 0, sizeof(*config));
1865 }
1866 
1867 /* as we use the static descriptors for simplicity, serialize bind call */
1868 static DEFINE_MUTEX(f_midi2_desc_mutex);
1869 
1870 /* fill MIDI2 EP class-specific descriptor */
1871 static void fill_midi2_class_desc(struct f_midi2_ep *ep,
1872 				  struct usb_ms20_endpoint_descriptor_32 *cdesc)
1873 {
1874 	int blk;
1875 
1876 	cdesc->bLength = USB_DT_MS20_ENDPOINT_SIZE(ep->num_blks);
1877 	cdesc->bDescriptorType = USB_DT_CS_ENDPOINT;
1878 	cdesc->bDescriptorSubtype = USB_MS_GENERAL_2_0;
1879 	cdesc->bNumGrpTrmBlock = ep->num_blks;
1880 	for (blk = 0; blk < ep->num_blks; blk++)
1881 		cdesc->baAssoGrpTrmBlkID[blk] = ep->blks[blk].gtb_id;
1882 }
1883 
1884 /* initialize MIDI2 EP-in */
1885 static int f_midi2_init_midi2_ep_in(struct f_midi2 *midi2, int index)
1886 {
1887 	struct f_midi2_ep *ep = &midi2->midi2_eps[index];
1888 	struct usb_endpoint_descriptor *desc = &midi2_midi2_ep_in_desc[index];
1889 
1890 	desc->bLength = USB_DT_ENDPOINT_SIZE;
1891 	desc->bDescriptorType = USB_DT_ENDPOINT;
1892 	desc->bEndpointAddress = USB_DIR_IN;
1893 	desc->bmAttributes = USB_ENDPOINT_XFER_INT;
1894 	desc->wMaxPacketSize = cpu_to_le16(EP_MAX_PACKET_INT);
1895 	desc->bInterval = 1;
1896 
1897 	fill_midi2_class_desc(ep, &midi2_midi2_ep_in_class_desc[index]);
1898 
1899 	return f_midi2_init_ep(midi2, ep, &ep->ep_in, desc,
1900 			       f_midi2_ep_in_complete);
1901 }
1902 
1903 /* initialize MIDI2 EP-out */
1904 static int f_midi2_init_midi2_ep_out(struct f_midi2 *midi2, int index)
1905 {
1906 	struct f_midi2_ep *ep = &midi2->midi2_eps[index];
1907 	struct usb_endpoint_descriptor *desc = &midi2_midi2_ep_out_desc[index];
1908 
1909 	desc->bLength = USB_DT_ENDPOINT_SIZE;
1910 	desc->bDescriptorType = USB_DT_ENDPOINT;
1911 	desc->bEndpointAddress = USB_DIR_OUT;
1912 	desc->bmAttributes = USB_ENDPOINT_XFER_BULK;
1913 
1914 	fill_midi2_class_desc(ep, &midi2_midi2_ep_out_class_desc[index]);
1915 
1916 	return f_midi2_init_ep(midi2, ep, &ep->ep_out, desc,
1917 			       f_midi2_ep_out_complete);
1918 }
1919 
1920 /* gadget function bind callback */
1921 static int f_midi2_bind(struct usb_configuration *c, struct usb_function *f)
1922 {
1923 	struct usb_composite_dev *cdev = c->cdev;
1924 	struct f_midi2 *midi2 = func_to_midi2(f);
1925 	struct f_midi2_ep *ep;
1926 	struct f_midi2_usb_config config = {};
1927 	struct usb_gadget_strings string_fn = {
1928 		.language = 0x0409,	/* en-us */
1929 		.strings = midi2->string_defs,
1930 	};
1931 	struct usb_gadget_strings *strings[] = {
1932 		&string_fn,
1933 		NULL,
1934 	};
1935 	int i, blk, status;
1936 
1937 	midi2->gadget = cdev->gadget;
1938 	midi2->operation_mode = MIDI_OP_MODE_UNSET;
1939 
1940 	status = f_midi2_create_card(midi2);
1941 	if (status < 0)
1942 		goto fail_register;
1943 
1944 	/* maybe allocate device-global string ID */
1945 	midi2->strings = usb_gstrings_attach(c->cdev, strings,
1946 					     midi2->total_blocks + 1);
1947 	if (IS_ERR(midi2->strings)) {
1948 		status = PTR_ERR(midi2->strings);
1949 		goto fail_string;
1950 	}
1951 
1952 	mutex_lock(&f_midi2_desc_mutex);
1953 	midi2_midi1_if_desc.iInterface = midi2->strings[STR_IFACE].id;
1954 	midi2_midi2_if_desc.iInterface = midi2->strings[STR_IFACE].id;
1955 	for (i = 0; i < midi2->num_eps; i++) {
1956 		ep = &midi2->midi2_eps[i];
1957 		for (blk = 0; blk < ep->num_blks; blk++)
1958 			ep->blks[blk].string_id =
1959 				midi2->strings[gtb_to_str_id(ep->blks[blk].gtb_id)].id;
1960 	}
1961 
1962 	midi2_midi2_if_desc.bNumEndpoints = midi2->num_eps * 2;
1963 
1964 	/* audio interface */
1965 	status = usb_interface_id(c, f);
1966 	if (status < 0)
1967 		goto fail;
1968 	midi2_audio_if_desc.bInterfaceNumber = status;
1969 
1970 	/* MIDI streaming */
1971 	status = usb_interface_id(c, f);
1972 	if (status < 0)
1973 		goto fail;
1974 	midi2->midi_if = status;
1975 	midi2_midi1_if_desc.bInterfaceNumber = status;
1976 	midi2_midi2_if_desc.bInterfaceNumber = status;
1977 	midi2_audio_class_desc.baInterfaceNr[0] = status;
1978 
1979 	/* allocate instance-specific endpoints */
1980 	if (midi2->midi2_eps[0].blks[0].info.direction != SNDRV_UMP_DIR_OUTPUT) {
1981 		status = f_midi2_init_ep(midi2, NULL, &midi2->midi1_ep_in,
1982 					 &midi2_midi1_ep_in_desc,
1983 					 f_midi2_midi1_ep_in_complete);
1984 		if (status)
1985 			goto fail;
1986 	}
1987 
1988 	if (midi2->midi2_eps[0].blks[0].info.direction != SNDRV_UMP_DIR_INPUT) {
1989 		status = f_midi2_init_ep(midi2, NULL, &midi2->midi1_ep_out,
1990 					 &midi2_midi1_ep_out_desc,
1991 					 f_midi2_midi1_ep_out_complete);
1992 		if (status)
1993 			goto fail;
1994 	}
1995 
1996 	for (i = 0; i < midi2->num_eps; i++) {
1997 		status = f_midi2_init_midi2_ep_in(midi2, i);
1998 		if (status)
1999 			goto fail;
2000 		status = f_midi2_init_midi2_ep_out(midi2, i);
2001 		if (status)
2002 			goto fail;
2003 	}
2004 
2005 	status = f_midi2_create_usb_configs(midi2, &config, USB_SPEED_FULL);
2006 	if (status < 0)
2007 		goto fail;
2008 	f->fs_descriptors = usb_copy_descriptors(config.list);
2009 	if (!f->fs_descriptors) {
2010 		status = -ENOMEM;
2011 		goto fail;
2012 	}
2013 	f_midi2_free_usb_configs(&config);
2014 
2015 	status = f_midi2_create_usb_configs(midi2, &config, USB_SPEED_HIGH);
2016 	if (status < 0)
2017 		goto fail;
2018 	f->hs_descriptors = usb_copy_descriptors(config.list);
2019 	if (!f->hs_descriptors) {
2020 		status = -ENOMEM;
2021 		goto fail;
2022 	}
2023 	f_midi2_free_usb_configs(&config);
2024 
2025 	status = f_midi2_create_usb_configs(midi2, &config, USB_SPEED_SUPER);
2026 	if (status < 0)
2027 		goto fail;
2028 	f->ss_descriptors = usb_copy_descriptors(config.list);
2029 	if (!f->ss_descriptors) {
2030 		status = -ENOMEM;
2031 		goto fail;
2032 	}
2033 	f_midi2_free_usb_configs(&config);
2034 
2035 	mutex_unlock(&f_midi2_desc_mutex);
2036 	return 0;
2037 
2038 fail:
2039 	f_midi2_free_usb_configs(&config);
2040 	mutex_unlock(&f_midi2_desc_mutex);
2041 	usb_free_all_descriptors(f);
2042 fail_string:
2043 	f_midi2_free_card(midi2);
2044 fail_register:
2045 	ERROR(midi2, "%s: can't bind, err %d\n", f->name, status);
2046 	return status;
2047 }
2048 
2049 /* gadget function unbind callback */
2050 static void f_midi2_unbind(struct usb_configuration *c, struct usb_function *f)
2051 {
2052 	struct f_midi2 *midi2 = func_to_midi2(f);
2053 	int i;
2054 
2055 	f_midi2_free_card(midi2);
2056 
2057 	f_midi2_free_ep(&midi2->midi1_ep_in);
2058 	f_midi2_free_ep(&midi2->midi1_ep_out);
2059 	for (i = 0; i < midi2->num_eps; i++) {
2060 		f_midi2_free_ep(&midi2->midi2_eps[i].ep_in);
2061 		f_midi2_free_ep(&midi2->midi2_eps[i].ep_out);
2062 	}
2063 
2064 	usb_free_all_descriptors(f);
2065 }
2066 
2067 /*
2068  * ConfigFS interface
2069  */
2070 
2071 /* type conversion helpers */
2072 static inline struct f_midi2_opts *to_f_midi2_opts(struct config_item *item)
2073 {
2074 	return container_of(to_config_group(item), struct f_midi2_opts,
2075 			    func_inst.group);
2076 }
2077 
2078 static inline struct f_midi2_ep_opts *
2079 to_f_midi2_ep_opts(struct config_item *item)
2080 {
2081 	return container_of(to_config_group(item), struct f_midi2_ep_opts,
2082 			    group);
2083 }
2084 
2085 static inline struct f_midi2_block_opts *
2086 to_f_midi2_block_opts(struct config_item *item)
2087 {
2088 	return container_of(to_config_group(item), struct f_midi2_block_opts,
2089 			    group);
2090 }
2091 
2092 /* trim the string to be usable for EP and FB name strings */
2093 static void make_name_string(char *s)
2094 {
2095 	char *p;
2096 
2097 	p = strchr(s, '\n');
2098 	if (p)
2099 		*p = 0;
2100 
2101 	p = s + strlen(s);
2102 	for (; p > s && isspace(*p); p--)
2103 		*p = 0;
2104 }
2105 
2106 /* configfs helpers: generic show/store for unisnged int */
2107 static ssize_t f_midi2_opts_uint_show(struct f_midi2_opts *opts,
2108 				      u32 val, const char *format, char *page)
2109 {
2110 	int result;
2111 
2112 	mutex_lock(&opts->lock);
2113 	result = sprintf(page, format, val);
2114 	mutex_unlock(&opts->lock);
2115 	return result;
2116 }
2117 
2118 static ssize_t f_midi2_opts_uint_store(struct f_midi2_opts *opts,
2119 				       u32 *valp, u32 minval, u32 maxval,
2120 				       const char *page, size_t len)
2121 {
2122 	int ret;
2123 	u32 val;
2124 
2125 	mutex_lock(&opts->lock);
2126 	if (opts->refcnt) {
2127 		ret = -EBUSY;
2128 		goto end;
2129 	}
2130 
2131 	ret = kstrtou32(page, 0, &val);
2132 	if (ret)
2133 		goto end;
2134 	if (val < minval || val > maxval) {
2135 		ret = -EINVAL;
2136 		goto end;
2137 	}
2138 
2139 	*valp = val;
2140 	ret = len;
2141 
2142 end:
2143 	mutex_unlock(&opts->lock);
2144 	return ret;
2145 }
2146 
2147 /* generic store for bool */
2148 static ssize_t f_midi2_opts_bool_store(struct f_midi2_opts *opts,
2149 				       bool *valp, const char *page, size_t len)
2150 {
2151 	int ret;
2152 	bool val;
2153 
2154 	mutex_lock(&opts->lock);
2155 	if (opts->refcnt) {
2156 		ret = -EBUSY;
2157 		goto end;
2158 	}
2159 
2160 	ret = kstrtobool(page, &val);
2161 	if (ret)
2162 		goto end;
2163 	*valp = val;
2164 	ret = len;
2165 
2166 end:
2167 	mutex_unlock(&opts->lock);
2168 	return ret;
2169 }
2170 
2171 /* generic show/store for string */
2172 static ssize_t f_midi2_opts_str_show(struct f_midi2_opts *opts,
2173 				     const char *str, char *page)
2174 {
2175 	int result = 0;
2176 
2177 	mutex_lock(&opts->lock);
2178 	if (str)
2179 		result = scnprintf(page, PAGE_SIZE, "%s\n", str);
2180 	mutex_unlock(&opts->lock);
2181 	return result;
2182 }
2183 
2184 static ssize_t f_midi2_opts_str_store(struct f_midi2_opts *opts,
2185 				      const char **strp, size_t maxlen,
2186 				      const char *page, size_t len)
2187 {
2188 	char *c;
2189 	int ret;
2190 
2191 	mutex_lock(&opts->lock);
2192 	if (opts->refcnt) {
2193 		ret = -EBUSY;
2194 		goto end;
2195 	}
2196 
2197 	c = kstrndup(page, min(len, maxlen), GFP_KERNEL);
2198 	if (!c) {
2199 		ret = -ENOMEM;
2200 		goto end;
2201 	}
2202 
2203 	kfree(*strp);
2204 	make_name_string(c);
2205 	*strp = c;
2206 	ret = len;
2207 
2208 end:
2209 	mutex_unlock(&opts->lock);
2210 	return ret;
2211 }
2212 
2213 /*
2214  * Definitions for UMP Block config
2215  */
2216 
2217 /* define an uint option for block */
2218 #define F_MIDI2_BLOCK_OPT(name, format, minval, maxval)			\
2219 static ssize_t f_midi2_block_opts_##name##_show(struct config_item *item,\
2220 					  char *page)			\
2221 {									\
2222 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
2223 	return f_midi2_opts_uint_show(opts->ep->opts, opts->info.name,	\
2224 				      format "\n", page);		\
2225 }									\
2226 									\
2227 static ssize_t f_midi2_block_opts_##name##_store(struct config_item *item,\
2228 					 const char *page, size_t len)	\
2229 {									\
2230 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
2231 	return f_midi2_opts_uint_store(opts->ep->opts, &opts->info.name,\
2232 				       minval, maxval, page, len);	\
2233 }									\
2234 									\
2235 CONFIGFS_ATTR(f_midi2_block_opts_, name)
2236 
2237 /* define a boolean option for block */
2238 #define F_MIDI2_BLOCK_BOOL_OPT(name)					\
2239 static ssize_t f_midi2_block_opts_##name##_show(struct config_item *item,\
2240 					  char *page)			\
2241 {									\
2242 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
2243 	return f_midi2_opts_uint_show(opts->ep->opts, opts->info.name,	\
2244 				      "%u\n", page);			\
2245 }									\
2246 									\
2247 static ssize_t f_midi2_block_opts_##name##_store(struct config_item *item,\
2248 					 const char *page, size_t len)	\
2249 {									\
2250 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
2251 	return f_midi2_opts_bool_store(opts->ep->opts, &opts->info.name,\
2252 				       page, len);			\
2253 }									\
2254 									\
2255 CONFIGFS_ATTR(f_midi2_block_opts_, name)
2256 
2257 F_MIDI2_BLOCK_OPT(direction, "0x%x", 1, 3);
2258 F_MIDI2_BLOCK_OPT(first_group, "0x%x", 0, 15);
2259 F_MIDI2_BLOCK_OPT(num_groups, "0x%x", 1, 16);
2260 F_MIDI2_BLOCK_OPT(midi1_first_group, "0x%x", 0, 15);
2261 F_MIDI2_BLOCK_OPT(midi1_num_groups, "0x%x", 0, 16);
2262 F_MIDI2_BLOCK_OPT(ui_hint, "0x%x", 0, 3);
2263 F_MIDI2_BLOCK_OPT(midi_ci_version, "%u", 0, 1);
2264 F_MIDI2_BLOCK_OPT(sysex8_streams, "%u", 0, 255);
2265 F_MIDI2_BLOCK_OPT(is_midi1, "%u", 0, 2);
2266 F_MIDI2_BLOCK_BOOL_OPT(active);
2267 
2268 static ssize_t f_midi2_block_opts_name_show(struct config_item *item,
2269 					    char *page)
2270 {
2271 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);
2272 
2273 	return f_midi2_opts_str_show(opts->ep->opts, opts->info.name, page);
2274 }
2275 
2276 static ssize_t f_midi2_block_opts_name_store(struct config_item *item,
2277 					     const char *page, size_t len)
2278 {
2279 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);
2280 
2281 	return f_midi2_opts_str_store(opts->ep->opts, &opts->info.name, 128,
2282 				      page, len);
2283 }
2284 
2285 CONFIGFS_ATTR(f_midi2_block_opts_, name);
2286 
2287 static struct configfs_attribute *f_midi2_block_attrs[] = {
2288 	&f_midi2_block_opts_attr_direction,
2289 	&f_midi2_block_opts_attr_first_group,
2290 	&f_midi2_block_opts_attr_num_groups,
2291 	&f_midi2_block_opts_attr_midi1_first_group,
2292 	&f_midi2_block_opts_attr_midi1_num_groups,
2293 	&f_midi2_block_opts_attr_ui_hint,
2294 	&f_midi2_block_opts_attr_midi_ci_version,
2295 	&f_midi2_block_opts_attr_sysex8_streams,
2296 	&f_midi2_block_opts_attr_is_midi1,
2297 	&f_midi2_block_opts_attr_active,
2298 	&f_midi2_block_opts_attr_name,
2299 	NULL,
2300 };
2301 
2302 static void f_midi2_block_opts_release(struct config_item *item)
2303 {
2304 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);
2305 
2306 	kfree(opts->info.name);
2307 	kfree(opts);
2308 }
2309 
2310 static struct configfs_item_operations f_midi2_block_item_ops = {
2311 	.release	= f_midi2_block_opts_release,
2312 };
2313 
2314 static const struct config_item_type f_midi2_block_type = {
2315 	.ct_item_ops	= &f_midi2_block_item_ops,
2316 	.ct_attrs	= f_midi2_block_attrs,
2317 	.ct_owner	= THIS_MODULE,
2318 };
2319 
2320 /* create a f_midi2_block_opts instance for the given block number */
2321 static int f_midi2_block_opts_create(struct f_midi2_ep_opts *ep_opts,
2322 				     unsigned int blk,
2323 				     struct f_midi2_block_opts **block_p)
2324 {
2325 	struct f_midi2_block_opts *block_opts;
2326 	int ret = 0;
2327 
2328 	mutex_lock(&ep_opts->opts->lock);
2329 	if (ep_opts->opts->refcnt || ep_opts->blks[blk]) {
2330 		ret = -EBUSY;
2331 		goto out;
2332 	}
2333 
2334 	block_opts = kzalloc(sizeof(*block_opts), GFP_KERNEL);
2335 	if (!block_opts) {
2336 		ret = -ENOMEM;
2337 		goto out;
2338 	}
2339 
2340 	block_opts->ep = ep_opts;
2341 	block_opts->id = blk;
2342 
2343 	/* set up the default values */
2344 	block_opts->info.direction = SNDRV_UMP_DIR_BIDIRECTION;
2345 	block_opts->info.first_group = 0;
2346 	block_opts->info.num_groups = 1;
2347 	block_opts->info.ui_hint = SNDRV_UMP_BLOCK_UI_HINT_BOTH;
2348 	block_opts->info.active = 1;
2349 
2350 	ep_opts->blks[blk] = block_opts;
2351 	*block_p = block_opts;
2352 
2353  out:
2354 	mutex_unlock(&ep_opts->opts->lock);
2355 	return ret;
2356 }
2357 
2358 /* make_group callback for a block */
2359 static struct config_group *
2360 f_midi2_opts_block_make(struct config_group *group, const char *name)
2361 {
2362 	struct f_midi2_ep_opts *ep_opts;
2363 	struct f_midi2_block_opts *block_opts;
2364 	unsigned int blk;
2365 	int ret;
2366 
2367 	if (strncmp(name, "block.", 6))
2368 		return ERR_PTR(-EINVAL);
2369 	ret = kstrtouint(name + 6, 10, &blk);
2370 	if (ret)
2371 		return ERR_PTR(ret);
2372 
2373 	ep_opts = to_f_midi2_ep_opts(&group->cg_item);
2374 
2375 	if (blk >= SNDRV_UMP_MAX_BLOCKS)
2376 		return ERR_PTR(-EINVAL);
2377 	if (ep_opts->blks[blk])
2378 		return ERR_PTR(-EBUSY);
2379 	ret = f_midi2_block_opts_create(ep_opts, blk, &block_opts);
2380 	if (ret)
2381 		return ERR_PTR(ret);
2382 
2383 	config_group_init_type_name(&block_opts->group, name,
2384 				    &f_midi2_block_type);
2385 	return &block_opts->group;
2386 }
2387 
2388 /* drop_item callback for a block */
2389 static void
2390 f_midi2_opts_block_drop(struct config_group *group, struct config_item *item)
2391 {
2392 	struct f_midi2_block_opts *block_opts = to_f_midi2_block_opts(item);
2393 
2394 	mutex_lock(&block_opts->ep->opts->lock);
2395 	block_opts->ep->blks[block_opts->id] = NULL;
2396 	mutex_unlock(&block_opts->ep->opts->lock);
2397 	config_item_put(item);
2398 }
2399 
2400 /*
2401  * Definitions for UMP Endpoint config
2402  */
2403 
2404 /* define an uint option for EP */
2405 #define F_MIDI2_EP_OPT(name, format, minval, maxval)			\
2406 static ssize_t f_midi2_ep_opts_##name##_show(struct config_item *item,	\
2407 					     char *page)		\
2408 {									\
2409 	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
2410 	return f_midi2_opts_uint_show(opts->opts, opts->info.name,	\
2411 				      format "\n", page);		\
2412 }									\
2413 									\
2414 static ssize_t f_midi2_ep_opts_##name##_store(struct config_item *item,	\
2415 					   const char *page, size_t len)\
2416 {									\
2417 	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
2418 	return f_midi2_opts_uint_store(opts->opts, &opts->info.name,	\
2419 				       minval, maxval, page, len);	\
2420 }									\
2421 									\
2422 CONFIGFS_ATTR(f_midi2_ep_opts_, name)
2423 
2424 /* define a string option for EP */
2425 #define F_MIDI2_EP_STR_OPT(name, maxlen)				\
2426 static ssize_t f_midi2_ep_opts_##name##_show(struct config_item *item,	\
2427 					     char *page)		\
2428 {									\
2429 	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
2430 	return f_midi2_opts_str_show(opts->opts, opts->info.name, page);\
2431 }									\
2432 									\
2433 static ssize_t f_midi2_ep_opts_##name##_store(struct config_item *item,	\
2434 					 const char *page, size_t len)	\
2435 {									\
2436 	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
2437 	return f_midi2_opts_str_store(opts->opts, &opts->info.name, maxlen,\
2438 				      page, len);			\
2439 }									\
2440 									\
2441 CONFIGFS_ATTR(f_midi2_ep_opts_, name)
2442 
2443 F_MIDI2_EP_OPT(protocol, "0x%x", 1, 2);
2444 F_MIDI2_EP_OPT(protocol_caps, "0x%x", 1, 3);
2445 F_MIDI2_EP_OPT(manufacturer, "0x%x", 0, 0xffffff);
2446 F_MIDI2_EP_OPT(family, "0x%x", 0, 0xffff);
2447 F_MIDI2_EP_OPT(model, "0x%x", 0, 0xffff);
2448 F_MIDI2_EP_OPT(sw_revision, "0x%x", 0, 0xffffffff);
2449 F_MIDI2_EP_STR_OPT(ep_name, 128);
2450 F_MIDI2_EP_STR_OPT(product_id, 128);
2451 
2452 static struct configfs_attribute *f_midi2_ep_attrs[] = {
2453 	&f_midi2_ep_opts_attr_protocol,
2454 	&f_midi2_ep_opts_attr_protocol_caps,
2455 	&f_midi2_ep_opts_attr_ep_name,
2456 	&f_midi2_ep_opts_attr_product_id,
2457 	&f_midi2_ep_opts_attr_manufacturer,
2458 	&f_midi2_ep_opts_attr_family,
2459 	&f_midi2_ep_opts_attr_model,
2460 	&f_midi2_ep_opts_attr_sw_revision,
2461 	NULL,
2462 };
2463 
2464 static void f_midi2_ep_opts_release(struct config_item *item)
2465 {
2466 	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);
2467 
2468 	kfree(opts->info.ep_name);
2469 	kfree(opts->info.product_id);
2470 	kfree(opts);
2471 }
2472 
2473 static struct configfs_item_operations f_midi2_ep_item_ops = {
2474 	.release	= f_midi2_ep_opts_release,
2475 };
2476 
2477 static struct configfs_group_operations f_midi2_ep_group_ops = {
2478 	.make_group	= f_midi2_opts_block_make,
2479 	.drop_item	= f_midi2_opts_block_drop,
2480 };
2481 
2482 static const struct config_item_type f_midi2_ep_type = {
2483 	.ct_item_ops	= &f_midi2_ep_item_ops,
2484 	.ct_group_ops	= &f_midi2_ep_group_ops,
2485 	.ct_attrs	= f_midi2_ep_attrs,
2486 	.ct_owner	= THIS_MODULE,
2487 };
2488 
2489 /* create a f_midi2_ep_opts instance */
2490 static int f_midi2_ep_opts_create(struct f_midi2_opts *opts,
2491 				  unsigned int index,
2492 				  struct f_midi2_ep_opts **ep_p)
2493 {
2494 	struct f_midi2_ep_opts *ep_opts;
2495 
2496 	ep_opts = kzalloc(sizeof(*ep_opts), GFP_KERNEL);
2497 	if (!ep_opts)
2498 		return -ENOMEM;
2499 
2500 	ep_opts->opts = opts;
2501 	ep_opts->index = index;
2502 
2503 	/* set up the default values */
2504 	ep_opts->info.protocol = 2;
2505 	ep_opts->info.protocol_caps = 3;
2506 
2507 	opts->eps[index] = ep_opts;
2508 	*ep_p = ep_opts;
2509 	return 0;
2510 }
2511 
2512 /* make_group callback for an EP */
2513 static struct config_group *
2514 f_midi2_opts_ep_make(struct config_group *group, const char *name)
2515 {
2516 	struct f_midi2_opts *opts;
2517 	struct f_midi2_ep_opts *ep_opts;
2518 	unsigned int index;
2519 	int ret;
2520 
2521 	if (strncmp(name, "ep.", 3))
2522 		return ERR_PTR(-EINVAL);
2523 	ret = kstrtouint(name + 3, 10, &index);
2524 	if (ret)
2525 		return ERR_PTR(ret);
2526 
2527 	opts = to_f_midi2_opts(&group->cg_item);
2528 	if (index >= MAX_UMP_EPS)
2529 		return ERR_PTR(-EINVAL);
2530 	if (opts->eps[index])
2531 		return ERR_PTR(-EBUSY);
2532 	ret = f_midi2_ep_opts_create(opts, index, &ep_opts);
2533 	if (ret)
2534 		return ERR_PTR(ret);
2535 
2536 	config_group_init_type_name(&ep_opts->group, name, &f_midi2_ep_type);
2537 	return &ep_opts->group;
2538 }
2539 
2540 /* drop_item callback for an EP */
2541 static void
2542 f_midi2_opts_ep_drop(struct config_group *group, struct config_item *item)
2543 {
2544 	struct f_midi2_ep_opts *ep_opts = to_f_midi2_ep_opts(item);
2545 
2546 	mutex_lock(&ep_opts->opts->lock);
2547 	ep_opts->opts->eps[ep_opts->index] = NULL;
2548 	mutex_unlock(&ep_opts->opts->lock);
2549 	config_item_put(item);
2550 }
2551 
2552 /*
2553  * Definitions for card config
2554  */
2555 
2556 /* define a bool option for card */
2557 #define F_MIDI2_BOOL_OPT(name)						\
2558 static ssize_t f_midi2_opts_##name##_show(struct config_item *item,	\
2559 					  char *page)			\
2560 {									\
2561 	struct f_midi2_opts *opts = to_f_midi2_opts(item);		\
2562 	return f_midi2_opts_uint_show(opts, opts->info.name,		\
2563 				      "%u\n", page);			\
2564 }									\
2565 									\
2566 static ssize_t f_midi2_opts_##name##_store(struct config_item *item,	\
2567 					 const char *page, size_t len)	\
2568 {									\
2569 	struct f_midi2_opts *opts = to_f_midi2_opts(item);		\
2570 	return f_midi2_opts_bool_store(opts, &opts->info.name,		\
2571 				       page, len);			\
2572 }									\
2573 									\
2574 CONFIGFS_ATTR(f_midi2_opts_, name)
2575 
2576 F_MIDI2_BOOL_OPT(process_ump);
2577 F_MIDI2_BOOL_OPT(static_block);
2578 
2579 static ssize_t f_midi2_opts_iface_name_show(struct config_item *item,
2580 					    char *page)
2581 {
2582 	struct f_midi2_opts *opts = to_f_midi2_opts(item);
2583 
2584 	return f_midi2_opts_str_show(opts, opts->info.iface_name, page);
2585 }
2586 
2587 static ssize_t f_midi2_opts_iface_name_store(struct config_item *item,
2588 					     const char *page, size_t len)
2589 {
2590 	struct f_midi2_opts *opts = to_f_midi2_opts(item);
2591 
2592 	return f_midi2_opts_str_store(opts, &opts->info.iface_name, 128,
2593 				      page, len);
2594 }
2595 
2596 CONFIGFS_ATTR(f_midi2_opts_, iface_name);
2597 
2598 static struct configfs_attribute *f_midi2_attrs[] = {
2599 	&f_midi2_opts_attr_process_ump,
2600 	&f_midi2_opts_attr_static_block,
2601 	&f_midi2_opts_attr_iface_name,
2602 	NULL
2603 };
2604 
2605 static void f_midi2_opts_release(struct config_item *item)
2606 {
2607 	struct f_midi2_opts *opts = to_f_midi2_opts(item);
2608 
2609 	usb_put_function_instance(&opts->func_inst);
2610 }
2611 
2612 static struct configfs_item_operations f_midi2_item_ops = {
2613 	.release	= f_midi2_opts_release,
2614 };
2615 
2616 static struct configfs_group_operations f_midi2_group_ops = {
2617 	.make_group	= f_midi2_opts_ep_make,
2618 	.drop_item	= f_midi2_opts_ep_drop,
2619 };
2620 
2621 static const struct config_item_type f_midi2_func_type = {
2622 	.ct_item_ops	= &f_midi2_item_ops,
2623 	.ct_group_ops	= &f_midi2_group_ops,
2624 	.ct_attrs	= f_midi2_attrs,
2625 	.ct_owner	= THIS_MODULE,
2626 };
2627 
2628 static void f_midi2_free_inst(struct usb_function_instance *f)
2629 {
2630 	struct f_midi2_opts *opts;
2631 
2632 	opts = container_of(f, struct f_midi2_opts, func_inst);
2633 
2634 	kfree(opts->info.iface_name);
2635 	kfree(opts);
2636 }
2637 
2638 /* gadget alloc_inst */
2639 static struct usb_function_instance *f_midi2_alloc_inst(void)
2640 {
2641 	struct f_midi2_opts *opts;
2642 	struct f_midi2_ep_opts *ep_opts;
2643 	struct f_midi2_block_opts *block_opts;
2644 	int ret;
2645 
2646 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
2647 	if (!opts)
2648 		return ERR_PTR(-ENOMEM);
2649 
2650 	mutex_init(&opts->lock);
2651 	opts->func_inst.free_func_inst = f_midi2_free_inst;
2652 	opts->info.process_ump = true;
2653 	opts->info.static_block = true;
2654 	opts->info.num_reqs = 32;
2655 	opts->info.req_buf_size = 512;
2656 
2657 	/* create the default ep */
2658 	ret = f_midi2_ep_opts_create(opts, 0, &ep_opts);
2659 	if (ret) {
2660 		kfree(opts);
2661 		return ERR_PTR(ret);
2662 	}
2663 
2664 	/* create the default block */
2665 	ret = f_midi2_block_opts_create(ep_opts, 0, &block_opts);
2666 	if (ret) {
2667 		kfree(ep_opts);
2668 		kfree(opts);
2669 		return ERR_PTR(ret);
2670 	}
2671 
2672 	/* set up the default MIDI1 (that is mandatory) */
2673 	block_opts->info.midi1_num_groups = 1;
2674 
2675 	config_group_init_type_name(&opts->func_inst.group, "",
2676 				    &f_midi2_func_type);
2677 
2678 	config_group_init_type_name(&ep_opts->group, "ep.0",
2679 				    &f_midi2_ep_type);
2680 	configfs_add_default_group(&ep_opts->group, &opts->func_inst.group);
2681 
2682 	config_group_init_type_name(&block_opts->group, "block.0",
2683 				    &f_midi2_block_type);
2684 	configfs_add_default_group(&block_opts->group, &ep_opts->group);
2685 
2686 	return &opts->func_inst;
2687 }
2688 
2689 static void do_f_midi2_free(struct f_midi2 *midi2, struct f_midi2_opts *opts)
2690 {
2691 	mutex_lock(&opts->lock);
2692 	--opts->refcnt;
2693 	mutex_unlock(&opts->lock);
2694 	kfree(midi2->string_defs);
2695 	kfree(midi2);
2696 }
2697 
2698 static void f_midi2_free(struct usb_function *f)
2699 {
2700 	do_f_midi2_free(func_to_midi2(f),
2701 			container_of(f->fi, struct f_midi2_opts, func_inst));
2702 }
2703 
2704 /* verify the parameters set up via configfs;
2705  * return the number of EPs or a negative error
2706  */
2707 static int verify_parameters(struct f_midi2_opts *opts)
2708 {
2709 	int i, j, num_eps, num_blks;
2710 	struct f_midi2_ep_info *ep;
2711 	struct f_midi2_block_info *bp;
2712 
2713 	for (num_eps = 0; num_eps < MAX_UMP_EPS && opts->eps[num_eps];
2714 	     num_eps++)
2715 		;
2716 	if (!num_eps) {
2717 		pr_err("f_midi2: No EP is defined\n");
2718 		return -EINVAL;
2719 	}
2720 
2721 	num_blks = 0;
2722 	for (i = 0; i < num_eps; i++) {
2723 		ep = &opts->eps[i]->info;
2724 		if (!(ep->protocol_caps & ep->protocol)) {
2725 			pr_err("f_midi2: Invalid protocol 0x%x (caps 0x%x) for EP %d\n",
2726 			       ep->protocol, ep->protocol_caps, i);
2727 			return -EINVAL;
2728 		}
2729 
2730 		for (j = 0; j < SNDRV_UMP_MAX_BLOCKS && opts->eps[i]->blks[j];
2731 		     j++, num_blks++) {
2732 			bp = &opts->eps[i]->blks[j]->info;
2733 			if (bp->first_group + bp->num_groups > SNDRV_UMP_MAX_GROUPS) {
2734 				pr_err("f_midi2: Invalid group definitions for block %d:%d\n",
2735 				       i, j);
2736 				return -EINVAL;
2737 			}
2738 
2739 			if (bp->midi1_num_groups) {
2740 				if (bp->midi1_first_group < bp->first_group ||
2741 				    bp->midi1_first_group + bp->midi1_num_groups >
2742 				    bp->first_group + bp->num_groups) {
2743 					pr_err("f_midi2: Invalid MIDI1 group definitions for block %d:%d\n",
2744 					       i, j);
2745 					return -EINVAL;
2746 				}
2747 			}
2748 		}
2749 	}
2750 	if (!num_blks) {
2751 		pr_err("f_midi2: No block is defined\n");
2752 		return -EINVAL;
2753 	}
2754 
2755 	return num_eps;
2756 }
2757 
2758 /* fill mapping between MIDI 1.0 cable and UMP EP/group */
2759 static void fill_midi1_cable_mapping(struct f_midi2 *midi2,
2760 				     struct f_midi2_ep *ep,
2761 				     int blk)
2762 {
2763 	const struct f_midi2_block_info *binfo = &ep->blks[blk].info;
2764 	struct midi1_cable_mapping *map;
2765 	int i, group;
2766 
2767 	if (!binfo->midi1_num_groups)
2768 		return;
2769 	if (binfo->direction != SNDRV_UMP_DIR_OUTPUT) {
2770 		group = binfo->midi1_first_group;
2771 		map = midi2->in_cable_mapping + midi2->num_midi1_in;
2772 		for (i = 0; i < binfo->midi1_num_groups; i++, group++, map++) {
2773 			if (midi2->num_midi1_in >= MAX_CABLES)
2774 				break;
2775 			map->ep = ep;
2776 			map->block = blk;
2777 			map->group = group;
2778 			midi2->num_midi1_in++;
2779 			/* store 1-based cable number */
2780 			ep->in_group_to_cable[group] = midi2->num_midi1_in;
2781 		}
2782 	}
2783 
2784 	if (binfo->direction != SNDRV_UMP_DIR_INPUT) {
2785 		group = binfo->midi1_first_group;
2786 		map = midi2->out_cable_mapping + midi2->num_midi1_out;
2787 		for (i = 0; i < binfo->midi1_num_groups; i++, group++, map++) {
2788 			if (midi2->num_midi1_out >= MAX_CABLES)
2789 				break;
2790 			map->ep = ep;
2791 			map->block = blk;
2792 			map->group = group;
2793 			midi2->num_midi1_out++;
2794 		}
2795 	}
2796 }
2797 
2798 /* gadget alloc callback */
2799 static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi)
2800 {
2801 	struct f_midi2 *midi2;
2802 	struct f_midi2_opts *opts;
2803 	struct f_midi2_ep *ep;
2804 	struct f_midi2_block *bp;
2805 	int i, num_eps, blk;
2806 
2807 	midi2 = kzalloc(sizeof(*midi2), GFP_KERNEL);
2808 	if (!midi2)
2809 		return ERR_PTR(-ENOMEM);
2810 
2811 	opts = container_of(fi, struct f_midi2_opts, func_inst);
2812 	mutex_lock(&opts->lock);
2813 	num_eps = verify_parameters(opts);
2814 	if (num_eps < 0) {
2815 		mutex_unlock(&opts->lock);
2816 		kfree(midi2);
2817 		return ERR_PTR(num_eps);
2818 	}
2819 	++opts->refcnt;
2820 	mutex_unlock(&opts->lock);
2821 
2822 	spin_lock_init(&midi2->queue_lock);
2823 
2824 	midi2->func.name = "midi2_func";
2825 	midi2->func.bind = f_midi2_bind;
2826 	midi2->func.unbind = f_midi2_unbind;
2827 	midi2->func.get_alt = f_midi2_get_alt;
2828 	midi2->func.set_alt = f_midi2_set_alt;
2829 	midi2->func.setup = f_midi2_setup;
2830 	midi2->func.disable = f_midi2_disable;
2831 	midi2->func.free_func = f_midi2_free;
2832 
2833 	midi2->info = opts->info;
2834 	midi2->num_eps = num_eps;
2835 
2836 	for (i = 0; i < num_eps; i++) {
2837 		ep = &midi2->midi2_eps[i];
2838 		ep->info = opts->eps[i]->info;
2839 		ep->card = midi2;
2840 		for (blk = 0; blk < SNDRV_UMP_MAX_BLOCKS &&
2841 			     opts->eps[i]->blks[blk]; blk++) {
2842 			bp = &ep->blks[blk];
2843 			ep->num_blks++;
2844 			bp->info = opts->eps[i]->blks[blk]->info;
2845 			bp->gtb_id = ++midi2->total_blocks;
2846 		}
2847 	}
2848 
2849 	midi2->string_defs = kcalloc(midi2->total_blocks + 1,
2850 				     sizeof(*midi2->string_defs), GFP_KERNEL);
2851 	if (!midi2->string_defs) {
2852 		do_f_midi2_free(midi2, opts);
2853 		return ERR_PTR(-ENOMEM);
2854 	}
2855 
2856 	if (opts->info.iface_name && *opts->info.iface_name)
2857 		midi2->string_defs[STR_IFACE].s = opts->info.iface_name;
2858 	else
2859 		midi2->string_defs[STR_IFACE].s = ump_ep_name(&midi2->midi2_eps[0]);
2860 
2861 	for (i = 0; i < midi2->num_eps; i++) {
2862 		ep = &midi2->midi2_eps[i];
2863 		for (blk = 0; blk < ep->num_blks; blk++) {
2864 			bp = &ep->blks[blk];
2865 			midi2->string_defs[gtb_to_str_id(bp->gtb_id)].s =
2866 				ump_fb_name(&bp->info);
2867 
2868 			fill_midi1_cable_mapping(midi2, ep, blk);
2869 		}
2870 	}
2871 
2872 	if (!midi2->num_midi1_in && !midi2->num_midi1_out) {
2873 		pr_err("f_midi2: MIDI1 definition is missing\n");
2874 		do_f_midi2_free(midi2, opts);
2875 		return ERR_PTR(-EINVAL);
2876 	}
2877 
2878 	return &midi2->func;
2879 }
2880 
2881 DECLARE_USB_FUNCTION_INIT(midi2, f_midi2_alloc_inst, f_midi2_alloc);
2882 
2883 MODULE_DESCRIPTION("USB MIDI 2.0 class function driver");
2884 MODULE_LICENSE("GPL");
2885