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/gadget.h>
19 #include <linux/usb/audio.h>
20 #include <linux/usb/midi-v2.h>
21 
22 #include "u_f.h"
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 >= ep->num_blks)
646 			return;
647 		if (*data & UMP_STREAM_MSG_REQUEST_FB_INFO)
648 			reply_ump_stream_fb_info(ep, blk);
649 		if (*data & UMP_STREAM_MSG_REQUEST_FB_NAME)
650 			reply_ump_stream_fb_name(ep, blk);
651 		return;
652 	}
653 }
654 
655 /* Process UMP messages included in a USB request */
656 static void process_ump(struct f_midi2_ep *ep, const struct usb_request *req)
657 {
658 	const u32 *data = (u32 *)req->buf;
659 	int len = req->actual >> 2;
660 	const u32 *in_buf = ep->ump->input_buf;
661 
662 	for (; len > 0; len--, data++) {
663 		if (snd_ump_receive_ump_val(ep->ump, *data) <= 0)
664 			continue;
665 		if (ump_message_type(*in_buf) == UMP_MSG_TYPE_STREAM)
666 			process_ump_stream_msg(ep, in_buf);
667 	}
668 }
669 
670 /*
671  * MIDI 2.0 UMP USB request handling
672  */
673 
674 /* complete handler for UMP EP-out requests */
675 static void f_midi2_ep_out_complete(struct usb_ep *usb_ep,
676 				    struct usb_request *req)
677 {
678 	struct f_midi2_req_ctx *ctx = req->context;
679 	struct f_midi2_ep *ep = ctx->usb_ep->ep;
680 	struct f_midi2 *midi2 = ep->card;
681 	int status = req->status;
682 
683 	if (status) {
684 		DBG(midi2, "%s complete error %d: %d/%d\n",
685 		    usb_ep->name, status, req->actual, req->length);
686 		goto error;
687 	}
688 
689 	/* convert to UMP packet in native endianness */
690 	le32_to_cpu_array((u32 *)req->buf, req->actual >> 2);
691 
692 	if (midi2->info.process_ump)
693 		process_ump(ep, req);
694 
695 	snd_ump_receive(ep->ump, req->buf, req->actual & ~3);
696 
697 	if (midi2->operation_mode != MIDI_OP_MODE_MIDI2)
698 		goto error;
699 
700 	if (queue_request_ep_raw(req))
701 		goto error;
702 	return;
703 
704  error:
705 	put_empty_request(req);
706 }
707 
708 /* Transmit UMP packets received from user-space to the gadget */
709 static void process_ump_transmit(struct f_midi2_ep *ep)
710 {
711 	struct f_midi2_usb_ep *usb_ep = &ep->ep_in;
712 	struct f_midi2 *midi2 = ep->card;
713 	struct usb_request *req;
714 	int len;
715 
716 	if (!usb_ep->usb_ep->enabled)
717 		return;
718 
719 	for (;;) {
720 		req = get_empty_request(usb_ep);
721 		if (!req)
722 			break;
723 		len = snd_ump_transmit(ep->ump, (u32 *)req->buf,
724 				       midi2->info.req_buf_size);
725 		if (len <= 0) {
726 			put_empty_request(req);
727 			break;
728 		}
729 
730 		req->length = len;
731 		if (queue_request_ep_in(req) < 0)
732 			break;
733 	}
734 }
735 
736 /* Complete handler for UMP EP-in requests */
737 static void f_midi2_ep_in_complete(struct usb_ep *usb_ep,
738 				   struct usb_request *req)
739 {
740 	struct f_midi2_req_ctx *ctx = req->context;
741 	struct f_midi2_ep *ep = ctx->usb_ep->ep;
742 	struct f_midi2 *midi2 = ep->card;
743 	int status = req->status;
744 
745 	put_empty_request(req);
746 
747 	if (status) {
748 		DBG(midi2, "%s complete error %d: %d/%d\n",
749 		    usb_ep->name, status, req->actual, req->length);
750 		return;
751 	}
752 
753 	process_ump_transmit(ep);
754 }
755 
756 /*
757  * MIDI1 (altset 0) USB request handling
758  */
759 
760 /* process one MIDI byte -- copied from f_midi.c
761  *
762  * fill the packet or request if needed
763  * returns true if the request became empty (queued)
764  */
765 static bool process_midi1_byte(struct f_midi2 *midi2, u8 cable, u8 b,
766 			       struct usb_request **req_p)
767 {
768 	struct f_midi2_midi1_port *port = &midi2->midi1_port[cable];
769 	u8 p[4] = { cable << 4, 0, 0, 0 };
770 	int next_state = STATE_INITIAL;
771 	struct usb_request *req = *req_p;
772 
773 	switch (b) {
774 	case 0xf8 ... 0xff:
775 		/* System Real-Time Messages */
776 		p[0] |= 0x0f;
777 		p[1] = b;
778 		next_state = port->state;
779 		port->state = STATE_REAL_TIME;
780 		break;
781 
782 	case 0xf7:
783 		/* End of SysEx */
784 		switch (port->state) {
785 		case STATE_SYSEX_0:
786 			p[0] |= 0x05;
787 			p[1] = 0xf7;
788 			next_state = STATE_FINISHED;
789 			break;
790 		case STATE_SYSEX_1:
791 			p[0] |= 0x06;
792 			p[1] = port->data[0];
793 			p[2] = 0xf7;
794 			next_state = STATE_FINISHED;
795 			break;
796 		case STATE_SYSEX_2:
797 			p[0] |= 0x07;
798 			p[1] = port->data[0];
799 			p[2] = port->data[1];
800 			p[3] = 0xf7;
801 			next_state = STATE_FINISHED;
802 			break;
803 		default:
804 			/* Ignore byte */
805 			next_state = port->state;
806 			port->state = STATE_INITIAL;
807 		}
808 		break;
809 
810 	case 0xf0 ... 0xf6:
811 		/* System Common Messages */
812 		port->data[0] = port->data[1] = 0;
813 		port->state = STATE_INITIAL;
814 		switch (b) {
815 		case 0xf0:
816 			port->data[0] = b;
817 			port->data[1] = 0;
818 			next_state = STATE_SYSEX_1;
819 			break;
820 		case 0xf1:
821 		case 0xf3:
822 			port->data[0] = b;
823 			next_state = STATE_1PARAM;
824 			break;
825 		case 0xf2:
826 			port->data[0] = b;
827 			next_state = STATE_2PARAM_1;
828 			break;
829 		case 0xf4:
830 		case 0xf5:
831 			next_state = STATE_INITIAL;
832 			break;
833 		case 0xf6:
834 			p[0] |= 0x05;
835 			p[1] = 0xf6;
836 			next_state = STATE_FINISHED;
837 			break;
838 		}
839 		break;
840 
841 	case 0x80 ... 0xef:
842 		/*
843 		 * Channel Voice Messages, Channel Mode Messages
844 		 * and Control Change Messages.
845 		 */
846 		port->data[0] = b;
847 		port->data[1] = 0;
848 		port->state = STATE_INITIAL;
849 		if (b >= 0xc0 && b <= 0xdf)
850 			next_state = STATE_1PARAM;
851 		else
852 			next_state = STATE_2PARAM_1;
853 		break;
854 
855 	case 0x00 ... 0x7f:
856 		/* Message parameters */
857 		switch (port->state) {
858 		case STATE_1PARAM:
859 			if (port->data[0] < 0xf0)
860 				p[0] |= port->data[0] >> 4;
861 			else
862 				p[0] |= 0x02;
863 
864 			p[1] = port->data[0];
865 			p[2] = b;
866 			/* This is to allow Running State Messages */
867 			next_state = STATE_1PARAM;
868 			break;
869 		case STATE_2PARAM_1:
870 			port->data[1] = b;
871 			next_state = STATE_2PARAM_2;
872 			break;
873 		case STATE_2PARAM_2:
874 			if (port->data[0] < 0xf0)
875 				p[0] |= port->data[0] >> 4;
876 			else
877 				p[0] |= 0x03;
878 
879 			p[1] = port->data[0];
880 			p[2] = port->data[1];
881 			p[3] = b;
882 			/* This is to allow Running State Messages */
883 			next_state = STATE_2PARAM_1;
884 			break;
885 		case STATE_SYSEX_0:
886 			port->data[0] = b;
887 			next_state = STATE_SYSEX_1;
888 			break;
889 		case STATE_SYSEX_1:
890 			port->data[1] = b;
891 			next_state = STATE_SYSEX_2;
892 			break;
893 		case STATE_SYSEX_2:
894 			p[0] |= 0x04;
895 			p[1] = port->data[0];
896 			p[2] = port->data[1];
897 			p[3] = b;
898 			next_state = STATE_SYSEX_0;
899 			break;
900 		}
901 		break;
902 	}
903 
904 	/* States where we have to write into the USB request */
905 	if (next_state == STATE_FINISHED ||
906 	    port->state == STATE_SYSEX_2 ||
907 	    port->state == STATE_1PARAM ||
908 	    port->state == STATE_2PARAM_2 ||
909 	    port->state == STATE_REAL_TIME) {
910 		memcpy(req->buf + req->length, p, sizeof(p));
911 		req->length += sizeof(p);
912 
913 		if (next_state == STATE_FINISHED) {
914 			next_state = STATE_INITIAL;
915 			port->data[0] = port->data[1] = 0;
916 		}
917 
918 		if (midi2->info.req_buf_size - req->length <= 4) {
919 			queue_request_ep_raw(req);
920 			*req_p = NULL;
921 			return true;
922 		}
923 	}
924 
925 	port->state = next_state;
926 	return false;
927 }
928 
929 /* process all pending MIDI bytes in the internal buffer;
930  * returns true if the request gets empty
931  * returns false if all have been processed
932  */
933 static bool process_midi1_pending_buf(struct f_midi2 *midi2,
934 				      struct usb_request **req_p)
935 {
936 	unsigned int cable, c;
937 
938 	for (cable = 0; cable < midi2->num_midi1_in; cable++) {
939 		struct f_midi2_midi1_port *port = &midi2->midi1_port[cable];
940 
941 		if (!port->pending)
942 			continue;
943 		for (c = 0; c < port->pending; c++) {
944 			if (process_midi1_byte(midi2, cable, port->buf[c],
945 					       req_p)) {
946 				port->pending -= c;
947 				if (port->pending)
948 					memmove(port->buf, port->buf + c,
949 						port->pending);
950 				return true;
951 			}
952 		}
953 		port->pending = 0;
954 	}
955 
956 	return false;
957 }
958 
959 /* fill the MIDI bytes onto the temporary buffer
960  */
961 static void fill_midi1_pending_buf(struct f_midi2 *midi2, u8 cable, u8 *buf,
962 				   unsigned int size)
963 {
964 	struct f_midi2_midi1_port *port = &midi2->midi1_port[cable];
965 
966 	if (port->pending + size > sizeof(port->buf))
967 		return;
968 	memcpy(port->buf + port->pending, buf, size);
969 	port->pending += size;
970 }
971 
972 /* try to process data given from the associated UMP stream */
973 static void process_midi1_transmit(struct f_midi2 *midi2)
974 {
975 	struct f_midi2_usb_ep *usb_ep = &midi2->midi1_ep_in;
976 	struct f_midi2_ep *ep = &midi2->midi2_eps[0];
977 	struct usb_request *req = NULL;
978 	/* 12 is the largest outcome (4 MIDI1 cmds) for a single UMP packet */
979 	unsigned char outbuf[12];
980 	unsigned char group, cable;
981 	int len, size;
982 	u32 ump;
983 
984 	if (!usb_ep->usb_ep || !usb_ep->usb_ep->enabled)
985 		return;
986 
987 	for (;;) {
988 		if (!req) {
989 			req = get_empty_request(usb_ep);
990 			if (!req)
991 				break;
992 		}
993 
994 		if (process_midi1_pending_buf(midi2, &req))
995 			continue;
996 
997 		len = snd_ump_transmit(ep->ump, &ump, 4);
998 		if (len <= 0)
999 			break;
1000 		if (snd_ump_receive_ump_val(ep->ump, ump) <= 0)
1001 			continue;
1002 		size = snd_ump_convert_from_ump(ep->ump->input_buf, outbuf,
1003 						&group);
1004 		if (size <= 0)
1005 			continue;
1006 		cable = ep->in_group_to_cable[group];
1007 		if (!cable)
1008 			continue;
1009 		cable--; /* to 0-base */
1010 		fill_midi1_pending_buf(midi2, cable, outbuf, size);
1011 	}
1012 
1013 	if (req) {
1014 		if (req->length)
1015 			queue_request_ep_raw(req);
1016 		else
1017 			put_empty_request(req);
1018 	}
1019 }
1020 
1021 /* complete handler for MIDI1 EP-in requests */
1022 static void f_midi2_midi1_ep_in_complete(struct usb_ep *usb_ep,
1023 					 struct usb_request *req)
1024 {
1025 	struct f_midi2_req_ctx *ctx = req->context;
1026 	struct f_midi2 *midi2 = ctx->usb_ep->card;
1027 	int status = req->status;
1028 
1029 	put_empty_request(req);
1030 
1031 	if (status) {
1032 		DBG(midi2, "%s complete error %d: %d/%d\n",
1033 		    usb_ep->name, status, req->actual, req->length);
1034 		return;
1035 	}
1036 
1037 	process_midi1_transmit(midi2);
1038 }
1039 
1040 /* complete handler for MIDI1 EP-out requests */
1041 static void f_midi2_midi1_ep_out_complete(struct usb_ep *usb_ep,
1042 					  struct usb_request *req)
1043 {
1044 	struct f_midi2_req_ctx *ctx = req->context;
1045 	struct f_midi2 *midi2 = ctx->usb_ep->card;
1046 	struct f_midi2_ep *ep;
1047 	struct ump_cvt_to_ump *cvt = &midi2->midi1_ump_cvt;
1048 	static const u8 midi1_packet_bytes[16] = {
1049 		0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1
1050 	};
1051 	unsigned int group, cable, bytes, c, len;
1052 	int status = req->status;
1053 	const u8 *buf = req->buf;
1054 
1055 	if (status) {
1056 		DBG(midi2, "%s complete error %d: %d/%d\n",
1057 		    usb_ep->name, status, req->actual, req->length);
1058 		goto error;
1059 	}
1060 
1061 	len = req->actual >> 2;
1062 	for (; len; len--, buf += 4) {
1063 		cable = *buf >> 4;
1064 		ep = midi2->out_cable_mapping[cable].ep;
1065 		if (!ep)
1066 			continue;
1067 		group = midi2->out_cable_mapping[cable].group;
1068 		bytes = midi1_packet_bytes[*buf & 0x0f];
1069 		for (c = 0; c < bytes; c++) {
1070 			snd_ump_convert_to_ump(cvt, group,
1071 					       to_ump_protocol(ep->info.protocol),
1072 					       buf[c + 1]);
1073 			if (cvt->ump_bytes) {
1074 				snd_ump_receive(ep->ump, cvt->ump,
1075 						cvt->ump_bytes);
1076 				cvt->ump_bytes = 0;
1077 			}
1078 		}
1079 	}
1080 
1081 	if (midi2->operation_mode != MIDI_OP_MODE_MIDI1)
1082 		goto error;
1083 
1084 	if (queue_request_ep_raw(req))
1085 		goto error;
1086 	return;
1087 
1088  error:
1089 	put_empty_request(req);
1090 }
1091 
1092 /*
1093  * Common EP handling helpers
1094  */
1095 
1096 /* Start MIDI EP */
1097 static int f_midi2_start_ep(struct f_midi2_usb_ep *usb_ep,
1098 			    struct usb_function *fn)
1099 {
1100 	int err;
1101 
1102 	if (!usb_ep->usb_ep)
1103 		return 0;
1104 
1105 	usb_ep_disable(usb_ep->usb_ep);
1106 	err = config_ep_by_speed(usb_ep->card->gadget, fn, usb_ep->usb_ep);
1107 	if (err)
1108 		return err;
1109 	return usb_ep_enable(usb_ep->usb_ep);
1110 }
1111 
1112 /* Drop pending requests */
1113 static void f_midi2_drop_reqs(struct f_midi2_usb_ep *usb_ep)
1114 {
1115 	int i;
1116 
1117 	if (!usb_ep->usb_ep || !usb_ep->num_reqs)
1118 		return;
1119 
1120 	for (i = 0; i < usb_ep->num_reqs; i++) {
1121 		if (!test_bit(i, &usb_ep->free_reqs) && usb_ep->reqs[i].req) {
1122 			usb_ep_dequeue(usb_ep->usb_ep, usb_ep->reqs[i].req);
1123 			set_bit(i, &usb_ep->free_reqs);
1124 		}
1125 	}
1126 }
1127 
1128 /* Allocate requests for the given EP */
1129 static int f_midi2_alloc_ep_reqs(struct f_midi2_usb_ep *usb_ep)
1130 {
1131 	struct f_midi2 *midi2 = usb_ep->card;
1132 	int i;
1133 
1134 	if (!usb_ep->usb_ep)
1135 		return 0;
1136 	if (!usb_ep->reqs)
1137 		return -EINVAL;
1138 
1139 	for (i = 0; i < midi2->info.num_reqs; i++) {
1140 		if (usb_ep->reqs[i].req)
1141 			continue;
1142 		usb_ep->reqs[i].req = alloc_ep_req(usb_ep->usb_ep,
1143 						   midi2->info.req_buf_size);
1144 		if (!usb_ep->reqs[i].req)
1145 			return -ENOMEM;
1146 		usb_ep->reqs[i].req->context = &usb_ep->reqs[i];
1147 	}
1148 	return 0;
1149 }
1150 
1151 /* Free allocated requests */
1152 static void f_midi2_free_ep_reqs(struct f_midi2_usb_ep *usb_ep)
1153 {
1154 	struct f_midi2 *midi2 = usb_ep->card;
1155 	int i;
1156 
1157 	for (i = 0; i < midi2->info.num_reqs; i++) {
1158 		if (!usb_ep->reqs[i].req)
1159 			continue;
1160 		free_ep_req(usb_ep->usb_ep, usb_ep->reqs[i].req);
1161 		usb_ep->reqs[i].req = NULL;
1162 	}
1163 }
1164 
1165 /* Initialize EP */
1166 static int f_midi2_init_ep(struct f_midi2 *midi2, struct f_midi2_ep *ep,
1167 			   struct f_midi2_usb_ep *usb_ep,
1168 			   void *desc,
1169 			   void (*complete)(struct usb_ep *usb_ep,
1170 					    struct usb_request *req))
1171 {
1172 	int i;
1173 
1174 	usb_ep->card = midi2;
1175 	usb_ep->ep = ep;
1176 	usb_ep->usb_ep = usb_ep_autoconfig(midi2->gadget, desc);
1177 	if (!usb_ep->usb_ep)
1178 		return -ENODEV;
1179 	usb_ep->complete = complete;
1180 
1181 	usb_ep->reqs = kcalloc(midi2->info.num_reqs, sizeof(*usb_ep->reqs),
1182 			       GFP_KERNEL);
1183 	if (!usb_ep->reqs)
1184 		return -ENOMEM;
1185 	for (i = 0; i < midi2->info.num_reqs; i++) {
1186 		usb_ep->reqs[i].index = i;
1187 		usb_ep->reqs[i].usb_ep = usb_ep;
1188 		set_bit(i, &usb_ep->free_reqs);
1189 		usb_ep->num_reqs++;
1190 	}
1191 
1192 	return 0;
1193 }
1194 
1195 /* Free EP */
1196 static void f_midi2_free_ep(struct f_midi2_usb_ep *usb_ep)
1197 {
1198 	f_midi2_drop_reqs(usb_ep);
1199 
1200 	f_midi2_free_ep_reqs(usb_ep);
1201 
1202 	kfree(usb_ep->reqs);
1203 	usb_ep->num_reqs = 0;
1204 	usb_ep->free_reqs = 0;
1205 	usb_ep->reqs = NULL;
1206 }
1207 
1208 /* Queue requests for EP-out at start */
1209 static void f_midi2_queue_out_reqs(struct f_midi2_usb_ep *usb_ep)
1210 {
1211 	int i, err;
1212 
1213 	if (!usb_ep->usb_ep)
1214 		return;
1215 
1216 	for (i = 0; i < usb_ep->num_reqs; i++) {
1217 		if (!test_bit(i, &usb_ep->free_reqs) || !usb_ep->reqs[i].req)
1218 			continue;
1219 		usb_ep->reqs[i].req->complete = usb_ep->complete;
1220 		err = usb_ep_queue(usb_ep->usb_ep, usb_ep->reqs[i].req,
1221 				   GFP_ATOMIC);
1222 		if (!err)
1223 			clear_bit(i, &usb_ep->free_reqs);
1224 	}
1225 }
1226 
1227 /*
1228  * Gadget Function callbacks
1229  */
1230 
1231 /* stop both IN and OUT EPs */
1232 static void f_midi2_stop_eps(struct f_midi2_usb_ep *ep_in,
1233 			     struct f_midi2_usb_ep *ep_out)
1234 {
1235 	f_midi2_drop_reqs(ep_in);
1236 	f_midi2_drop_reqs(ep_out);
1237 	f_midi2_free_ep_reqs(ep_in);
1238 	f_midi2_free_ep_reqs(ep_out);
1239 }
1240 
1241 /* start/queue both IN and OUT EPs */
1242 static int f_midi2_start_eps(struct f_midi2_usb_ep *ep_in,
1243 			     struct f_midi2_usb_ep *ep_out,
1244 			     struct usb_function *fn)
1245 {
1246 	int err;
1247 
1248 	err = f_midi2_start_ep(ep_in, fn);
1249 	if (err)
1250 		return err;
1251 	err = f_midi2_start_ep(ep_out, fn);
1252 	if (err)
1253 		return err;
1254 
1255 	err = f_midi2_alloc_ep_reqs(ep_in);
1256 	if (err)
1257 		return err;
1258 	err = f_midi2_alloc_ep_reqs(ep_out);
1259 	if (err)
1260 		return err;
1261 
1262 	f_midi2_queue_out_reqs(ep_out);
1263 	return 0;
1264 }
1265 
1266 /* gadget function set_alt callback */
1267 static int f_midi2_set_alt(struct usb_function *fn, unsigned int intf,
1268 			   unsigned int alt)
1269 {
1270 	struct f_midi2 *midi2 = func_to_midi2(fn);
1271 	struct f_midi2_ep *ep;
1272 	int i, op_mode, err;
1273 
1274 	if (intf != midi2->midi_if || alt > 1)
1275 		return 0;
1276 
1277 	if (alt == 0)
1278 		op_mode = MIDI_OP_MODE_MIDI1;
1279 	else if (alt == 1)
1280 		op_mode = MIDI_OP_MODE_MIDI2;
1281 	else
1282 		op_mode = MIDI_OP_MODE_UNSET;
1283 
1284 	if (midi2->operation_mode == op_mode)
1285 		return 0;
1286 
1287 	midi2->operation_mode = op_mode;
1288 
1289 	if (op_mode != MIDI_OP_MODE_MIDI1)
1290 		f_midi2_stop_eps(&midi2->midi1_ep_in, &midi2->midi1_ep_out);
1291 
1292 	if (op_mode != MIDI_OP_MODE_MIDI2) {
1293 		for (i = 0; i < midi2->num_eps; i++) {
1294 			ep = &midi2->midi2_eps[i];
1295 			f_midi2_stop_eps(&ep->ep_in, &ep->ep_out);
1296 		}
1297 	}
1298 
1299 	if (op_mode == MIDI_OP_MODE_MIDI1)
1300 		return f_midi2_start_eps(&midi2->midi1_ep_in,
1301 					 &midi2->midi1_ep_out, fn);
1302 
1303 	if (op_mode == MIDI_OP_MODE_MIDI2) {
1304 		for (i = 0; i < midi2->num_eps; i++) {
1305 			ep = &midi2->midi2_eps[i];
1306 
1307 			err = f_midi2_start_eps(&ep->ep_in, &ep->ep_out, fn);
1308 			if (err)
1309 				return err;
1310 		}
1311 	}
1312 
1313 	return 0;
1314 }
1315 
1316 /* gadget function get_alt callback */
1317 static int f_midi2_get_alt(struct usb_function *fn, unsigned int intf)
1318 {
1319 	struct f_midi2 *midi2 = func_to_midi2(fn);
1320 
1321 	if (intf == midi2->midi_if &&
1322 	    midi2->operation_mode == MIDI_OP_MODE_MIDI2)
1323 		return 1;
1324 	return 0;
1325 }
1326 
1327 /* convert UMP direction to USB MIDI 2.0 direction */
1328 static unsigned int ump_to_usb_dir(unsigned int ump_dir)
1329 {
1330 	switch (ump_dir) {
1331 	case SNDRV_UMP_DIR_INPUT:
1332 		return USB_MS_GR_TRM_BLOCK_TYPE_INPUT_ONLY;
1333 	case SNDRV_UMP_DIR_OUTPUT:
1334 		return USB_MS_GR_TRM_BLOCK_TYPE_OUTPUT_ONLY;
1335 	default:
1336 		return USB_MS_GR_TRM_BLOCK_TYPE_BIDIRECTIONAL;
1337 	}
1338 }
1339 
1340 /* assign GTB descriptors (for the given request) */
1341 static void assign_block_descriptors(struct f_midi2 *midi2,
1342 				     struct usb_request *req,
1343 				     int max_len)
1344 {
1345 	struct usb_ms20_gr_trm_block_header_descriptor header;
1346 	struct usb_ms20_gr_trm_block_descriptor *desc;
1347 	struct f_midi2_block_info *b;
1348 	struct f_midi2_ep *ep;
1349 	int i, blk, len;
1350 	char *data;
1351 
1352 	len = sizeof(gtb_header_desc) + sizeof(gtb_desc) * midi2->total_blocks;
1353 	if (WARN_ON(len > midi2->info.req_buf_size))
1354 		return;
1355 
1356 	header = gtb_header_desc;
1357 	header.wTotalLength = cpu_to_le16(len);
1358 	if (max_len < len) {
1359 		len = min_t(int, len, sizeof(header));
1360 		memcpy(req->buf, &header, len);
1361 		req->length = len;
1362 		req->zero = len < max_len;
1363 		return;
1364 	}
1365 
1366 	memcpy(req->buf, &header, sizeof(header));
1367 	data = req->buf + sizeof(header);
1368 	for (i = 0; i < midi2->num_eps; i++) {
1369 		ep = &midi2->midi2_eps[i];
1370 		for (blk = 0; blk < ep->num_blks; blk++) {
1371 			b = &ep->blks[blk].info;
1372 			desc = (struct usb_ms20_gr_trm_block_descriptor *)data;
1373 
1374 			*desc = gtb_desc;
1375 			desc->bGrpTrmBlkID = ep->blks[blk].gtb_id;
1376 			desc->bGrpTrmBlkType = ump_to_usb_dir(b->direction);
1377 			desc->nGroupTrm = b->first_group;
1378 			desc->nNumGroupTrm = b->num_groups;
1379 			desc->iBlockItem = ep->blks[blk].string_id;
1380 
1381 			if (ep->info.protocol == 2)
1382 				desc->bMIDIProtocol = USB_MS_MIDI_PROTO_2_0;
1383 			else
1384 				desc->bMIDIProtocol = USB_MS_MIDI_PROTO_1_0_128;
1385 
1386 			if (b->is_midi1 == 2) {
1387 				desc->wMaxInputBandwidth = cpu_to_le16(1);
1388 				desc->wMaxOutputBandwidth = cpu_to_le16(1);
1389 			}
1390 
1391 			data += sizeof(*desc);
1392 		}
1393 	}
1394 
1395 	req->length = len;
1396 	req->zero = len < max_len;
1397 }
1398 
1399 /* gadget function setup callback: handle GTB requests */
1400 static int f_midi2_setup(struct usb_function *fn,
1401 			 const struct usb_ctrlrequest *ctrl)
1402 {
1403 	struct f_midi2 *midi2 = func_to_midi2(fn);
1404 	struct usb_composite_dev *cdev = fn->config->cdev;
1405 	struct usb_request *req = cdev->req;
1406 	u16 value, length;
1407 
1408 	if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD ||
1409 	    ctrl->bRequest != USB_REQ_GET_DESCRIPTOR)
1410 		return -EOPNOTSUPP;
1411 
1412 	value = le16_to_cpu(ctrl->wValue);
1413 	length = le16_to_cpu(ctrl->wLength);
1414 
1415 	if ((value >> 8) != USB_DT_CS_GR_TRM_BLOCK)
1416 		return -EOPNOTSUPP;
1417 
1418 	/* handle only altset 1 */
1419 	if ((value & 0xff) != 1)
1420 		return -EOPNOTSUPP;
1421 
1422 	assign_block_descriptors(midi2, req, length);
1423 	return usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
1424 }
1425 
1426 /* gadget function disable callback */
1427 static void f_midi2_disable(struct usb_function *fn)
1428 {
1429 	struct f_midi2 *midi2 = func_to_midi2(fn);
1430 
1431 	midi2->operation_mode = MIDI_OP_MODE_UNSET;
1432 }
1433 
1434 /*
1435  * ALSA UMP ops: most of them are NOPs, only trigger for write is needed
1436  */
1437 static int f_midi2_ump_open(struct snd_ump_endpoint *ump, int dir)
1438 {
1439 	return 0;
1440 }
1441 
1442 static void f_midi2_ump_close(struct snd_ump_endpoint *ump, int dir)
1443 {
1444 }
1445 
1446 static void f_midi2_ump_trigger(struct snd_ump_endpoint *ump, int dir, int up)
1447 {
1448 	struct f_midi2_ep *ep = ump->private_data;
1449 	struct f_midi2 *midi2 = ep->card;
1450 
1451 	if (up && dir == SNDRV_RAWMIDI_STREAM_OUTPUT) {
1452 		switch (midi2->operation_mode) {
1453 		case MIDI_OP_MODE_MIDI1:
1454 			process_midi1_transmit(midi2);
1455 			break;
1456 		case MIDI_OP_MODE_MIDI2:
1457 			process_ump_transmit(ep);
1458 			break;
1459 		}
1460 	}
1461 }
1462 
1463 static void f_midi2_ump_drain(struct snd_ump_endpoint *ump, int dir)
1464 {
1465 }
1466 
1467 static const struct snd_ump_ops f_midi2_ump_ops = {
1468 	.open = f_midi2_ump_open,
1469 	.close = f_midi2_ump_close,
1470 	.trigger = f_midi2_ump_trigger,
1471 	.drain = f_midi2_ump_drain,
1472 };
1473 
1474 /*
1475  * "Operation Mode" control element
1476  */
1477 static int f_midi2_operation_mode_info(struct snd_kcontrol *kcontrol,
1478 				       struct snd_ctl_elem_info *uinfo)
1479 {
1480 	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1481 	uinfo->count = 1;
1482 	uinfo->value.integer.min = MIDI_OP_MODE_UNSET;
1483 	uinfo->value.integer.max = MIDI_OP_MODE_MIDI2;
1484 	return 0;
1485 }
1486 
1487 static int f_midi2_operation_mode_get(struct snd_kcontrol *kcontrol,
1488 				      struct snd_ctl_elem_value *ucontrol)
1489 {
1490 	struct f_midi2 *midi2 = snd_kcontrol_chip(kcontrol);
1491 
1492 	ucontrol->value.integer.value[0] = midi2->operation_mode;
1493 	return 0;
1494 }
1495 
1496 static const struct snd_kcontrol_new operation_mode_ctl = {
1497 	.iface = SNDRV_CTL_ELEM_IFACE_RAWMIDI,
1498 	.name = "Operation Mode",
1499 	.access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE,
1500 	.info = f_midi2_operation_mode_info,
1501 	.get = f_midi2_operation_mode_get,
1502 };
1503 
1504 /*
1505  * ALSA UMP instance creation / deletion
1506  */
1507 static void f_midi2_free_card(struct f_midi2 *midi2)
1508 {
1509 	if (midi2->card) {
1510 		snd_card_free_when_closed(midi2->card);
1511 		midi2->card = NULL;
1512 	}
1513 }
1514 
1515 /* use a reverse direction for the gadget host */
1516 static int reverse_dir(int dir)
1517 {
1518 	if (!dir || dir == SNDRV_UMP_DIR_BIDIRECTION)
1519 		return dir;
1520 	return (dir == SNDRV_UMP_DIR_OUTPUT) ?
1521 		SNDRV_UMP_DIR_INPUT : SNDRV_UMP_DIR_OUTPUT;
1522 }
1523 
1524 static int f_midi2_create_card(struct f_midi2 *midi2)
1525 {
1526 	struct snd_card *card;
1527 	struct snd_ump_endpoint *ump;
1528 	struct f_midi2_ep *ep;
1529 	int i, id, blk, err;
1530 	__be32 sw;
1531 
1532 	err = snd_card_new(&midi2->gadget->dev, -1, NULL, THIS_MODULE, 0,
1533 			   &card);
1534 	if (err < 0)
1535 		return err;
1536 	midi2->card = card;
1537 
1538 	strcpy(card->driver, "f_midi2");
1539 	strcpy(card->shortname, "MIDI 2.0 Gadget");
1540 	strcpy(card->longname, "MIDI 2.0 Gadget");
1541 
1542 	id = 0;
1543 	for (i = 0; i < midi2->num_eps; i++) {
1544 		ep = &midi2->midi2_eps[i];
1545 		err = snd_ump_endpoint_new(card, "MIDI 2.0 Gadget", id,
1546 					   1, 1, &ump);
1547 		if (err < 0)
1548 			goto error;
1549 		id++;
1550 
1551 		ep->ump = ump;
1552 		ump->no_process_stream = true;
1553 		ump->private_data = ep;
1554 		ump->ops = &f_midi2_ump_ops;
1555 		if (midi2->info.static_block)
1556 			ump->info.flags |= SNDRV_UMP_EP_INFO_STATIC_BLOCKS;
1557 		ump->info.protocol_caps = (ep->info.protocol_caps & 3) << 8;
1558 		ump->info.protocol = to_ump_protocol(ep->info.protocol);
1559 		ump->info.version = 0x0101;
1560 		ump->info.family_id = ep->info.family;
1561 		ump->info.model_id = ep->info.model;
1562 		ump->info.manufacturer_id = ep->info.manufacturer & 0xffffff;
1563 		sw = cpu_to_be32(ep->info.sw_revision);
1564 		memcpy(ump->info.sw_revision, &sw, 4);
1565 
1566 		strscpy(ump->info.name, ump_ep_name(ep),
1567 			sizeof(ump->info.name));
1568 		strscpy(ump->info.product_id, ump_product_id(ep),
1569 			sizeof(ump->info.product_id));
1570 		strscpy(ump->core.name, ump->info.name, sizeof(ump->core.name));
1571 
1572 		for (blk = 0; blk < ep->num_blks; blk++) {
1573 			const struct f_midi2_block_info *b = &ep->blks[blk].info;
1574 			struct snd_ump_block *fb;
1575 
1576 			err = snd_ump_block_new(ump, blk,
1577 						reverse_dir(b->direction),
1578 						b->first_group, b->num_groups,
1579 						&ep->blks[blk].fb);
1580 			if (err < 0)
1581 				goto error;
1582 			fb = ep->blks[blk].fb;
1583 			fb->info.active = !!b->active;
1584 			fb->info.midi_ci_version = b->midi_ci_version;
1585 			fb->info.ui_hint = reverse_dir(b->ui_hint);
1586 			fb->info.sysex8_streams = b->sysex8_streams;
1587 			fb->info.flags |= b->is_midi1;
1588 			strscpy(fb->info.name, ump_fb_name(b),
1589 				sizeof(fb->info.name));
1590 		}
1591 	}
1592 
1593 	for (i = 0; i < midi2->num_eps; i++) {
1594 		err = snd_ump_attach_legacy_rawmidi(midi2->midi2_eps[i].ump,
1595 						    "Legacy MIDI", id);
1596 		if (err < 0)
1597 			goto error;
1598 		id++;
1599 	}
1600 
1601 	err = snd_ctl_add(card, snd_ctl_new1(&operation_mode_ctl, midi2));
1602 	if (err < 0)
1603 		goto error;
1604 
1605 	err = snd_card_register(card);
1606 	if (err < 0)
1607 		goto error;
1608 
1609 	return 0;
1610 
1611  error:
1612 	f_midi2_free_card(midi2);
1613 	return err;
1614 }
1615 
1616 /*
1617  * Creation of USB descriptors
1618  */
1619 struct f_midi2_usb_config {
1620 	struct usb_descriptor_header **list;
1621 	unsigned int size;
1622 	unsigned int alloc;
1623 
1624 	/* MIDI 1.0 jacks */
1625 	unsigned char jack_in, jack_out, jack_id;
1626 	struct usb_midi_in_jack_descriptor jack_ins[MAX_CABLES];
1627 	struct usb_midi_out_jack_descriptor_1 jack_outs[MAX_CABLES];
1628 };
1629 
1630 static int append_config(struct f_midi2_usb_config *config, void *d)
1631 {
1632 	unsigned int size;
1633 	void *buf;
1634 
1635 	if (config->size + 2 >= config->alloc) {
1636 		size = config->size + 16;
1637 		buf = krealloc(config->list, size * sizeof(void *), GFP_KERNEL);
1638 		if (!buf)
1639 			return -ENOMEM;
1640 		config->list = buf;
1641 		config->alloc = size;
1642 	}
1643 
1644 	config->list[config->size] = d;
1645 	config->size++;
1646 	config->list[config->size] = NULL;
1647 	return 0;
1648 }
1649 
1650 static int append_configs(struct f_midi2_usb_config *config, void **d)
1651 {
1652 	int err;
1653 
1654 	for (; *d; d++) {
1655 		err = append_config(config, *d);
1656 		if (err)
1657 			return err;
1658 	}
1659 	return 0;
1660 }
1661 
1662 static int append_midi1_in_jack(struct f_midi2 *midi2,
1663 				struct f_midi2_usb_config *config,
1664 				struct midi1_cable_mapping *map,
1665 				unsigned int type)
1666 {
1667 	struct usb_midi_in_jack_descriptor *jack =
1668 		&config->jack_ins[config->jack_in++];
1669 	int id = ++config->jack_id;
1670 	int err;
1671 
1672 	jack->bLength = 0x06;
1673 	jack->bDescriptorType = USB_DT_CS_INTERFACE;
1674 	jack->bDescriptorSubtype = USB_MS_MIDI_IN_JACK;
1675 	jack->bJackType = type;
1676 	jack->bJackID = id;
1677 	/* use the corresponding block name as jack name */
1678 	if (map->ep)
1679 		jack->iJack = map->ep->blks[map->block].string_id;
1680 
1681 	err = append_config(config, jack);
1682 	if (err < 0)
1683 		return err;
1684 	return id;
1685 }
1686 
1687 static int append_midi1_out_jack(struct f_midi2 *midi2,
1688 				 struct f_midi2_usb_config *config,
1689 				 struct midi1_cable_mapping *map,
1690 				 unsigned int type, unsigned int source)
1691 {
1692 	struct usb_midi_out_jack_descriptor_1 *jack =
1693 		&config->jack_outs[config->jack_out++];
1694 	int id = ++config->jack_id;
1695 	int err;
1696 
1697 	jack->bLength = 0x09;
1698 	jack->bDescriptorType = USB_DT_CS_INTERFACE;
1699 	jack->bDescriptorSubtype = USB_MS_MIDI_OUT_JACK;
1700 	jack->bJackType = type;
1701 	jack->bJackID = id;
1702 	jack->bNrInputPins = 1;
1703 	jack->pins[0].baSourceID = source;
1704 	jack->pins[0].baSourcePin = 0x01;
1705 	/* use the corresponding block name as jack name */
1706 	if (map->ep)
1707 		jack->iJack = map->ep->blks[map->block].string_id;
1708 
1709 	err = append_config(config, jack);
1710 	if (err < 0)
1711 		return err;
1712 	return id;
1713 }
1714 
1715 static int f_midi2_create_usb_configs(struct f_midi2 *midi2,
1716 				      struct f_midi2_usb_config *config,
1717 				      int speed)
1718 {
1719 	void **midi1_in_eps, **midi1_out_eps;
1720 	int i, jack, total;
1721 	int err;
1722 
1723 	switch (speed) {
1724 	default:
1725 	case USB_SPEED_HIGH:
1726 		midi2_midi1_ep_out_desc.wMaxPacketSize = cpu_to_le16(512);
1727 		midi2_midi1_ep_in_desc.wMaxPacketSize = cpu_to_le16(512);
1728 		for (i = 0; i < midi2->num_eps; i++)
1729 			midi2_midi2_ep_out_desc[i].wMaxPacketSize =
1730 				cpu_to_le16(512);
1731 		fallthrough;
1732 	case USB_SPEED_FULL:
1733 		midi1_in_eps = midi2_midi1_ep_in_descs;
1734 		midi1_out_eps = midi2_midi1_ep_out_descs;
1735 		break;
1736 	case USB_SPEED_SUPER:
1737 		midi2_midi1_ep_out_desc.wMaxPacketSize = cpu_to_le16(1024);
1738 		midi2_midi1_ep_in_desc.wMaxPacketSize = cpu_to_le16(1024);
1739 		for (i = 0; i < midi2->num_eps; i++)
1740 			midi2_midi2_ep_out_desc[i].wMaxPacketSize =
1741 				cpu_to_le16(1024);
1742 		midi1_in_eps = midi2_midi1_ep_in_ss_descs;
1743 		midi1_out_eps = midi2_midi1_ep_out_ss_descs;
1744 		break;
1745 	}
1746 
1747 	err = append_configs(config, midi2_audio_descs);
1748 	if (err < 0)
1749 		return err;
1750 
1751 	if (midi2->num_midi1_in && midi2->num_midi1_out)
1752 		midi2_midi1_if_desc.bNumEndpoints = 2;
1753 	else
1754 		midi2_midi1_if_desc.bNumEndpoints = 1;
1755 
1756 	err = append_configs(config, midi2_midi1_descs);
1757 	if (err < 0)
1758 		return err;
1759 
1760 	total = USB_DT_MS_HEADER_SIZE;
1761 	if (midi2->num_midi1_out) {
1762 		midi2_midi1_ep_out_class_desc.bLength =
1763 			USB_DT_MS_ENDPOINT_SIZE(midi2->num_midi1_out);
1764 		total += midi2_midi1_ep_out_class_desc.bLength;
1765 		midi2_midi1_ep_out_class_desc.bNumEmbMIDIJack =
1766 			midi2->num_midi1_out;
1767 		total += midi2->num_midi1_out *
1768 			(USB_DT_MIDI_IN_SIZE + USB_DT_MIDI_OUT_SIZE(1));
1769 		for (i = 0; i < midi2->num_midi1_out; i++) {
1770 			jack = append_midi1_in_jack(midi2, config,
1771 						    &midi2->in_cable_mapping[i],
1772 						    USB_MS_EMBEDDED);
1773 			if (jack < 0)
1774 				return jack;
1775 			midi2_midi1_ep_out_class_desc.baAssocJackID[i] = jack;
1776 			jack = append_midi1_out_jack(midi2, config,
1777 						     &midi2->in_cable_mapping[i],
1778 						     USB_MS_EXTERNAL, jack);
1779 			if (jack < 0)
1780 				return jack;
1781 		}
1782 	}
1783 
1784 	if (midi2->num_midi1_in) {
1785 		midi2_midi1_ep_in_class_desc.bLength =
1786 			USB_DT_MS_ENDPOINT_SIZE(midi2->num_midi1_in);
1787 		total += midi2_midi1_ep_in_class_desc.bLength;
1788 		midi2_midi1_ep_in_class_desc.bNumEmbMIDIJack =
1789 			midi2->num_midi1_in;
1790 		total += midi2->num_midi1_in *
1791 			(USB_DT_MIDI_IN_SIZE + USB_DT_MIDI_OUT_SIZE(1));
1792 		for (i = 0; i < midi2->num_midi1_in; i++) {
1793 			jack = append_midi1_in_jack(midi2, config,
1794 						    &midi2->out_cable_mapping[i],
1795 						    USB_MS_EXTERNAL);
1796 			if (jack < 0)
1797 				return jack;
1798 			jack = append_midi1_out_jack(midi2, config,
1799 						     &midi2->out_cable_mapping[i],
1800 						     USB_MS_EMBEDDED, jack);
1801 			if (jack < 0)
1802 				return jack;
1803 			midi2_midi1_ep_in_class_desc.baAssocJackID[i] = jack;
1804 		}
1805 	}
1806 
1807 	midi2_midi1_class_desc.wTotalLength = cpu_to_le16(total);
1808 
1809 	if (midi2->num_midi1_out) {
1810 		err = append_configs(config, midi1_out_eps);
1811 		if (err < 0)
1812 			return err;
1813 	}
1814 	if (midi2->num_midi1_in) {
1815 		err = append_configs(config, midi1_in_eps);
1816 		if (err < 0)
1817 			return err;
1818 	}
1819 
1820 	err = append_configs(config, midi2_midi2_descs);
1821 	if (err < 0)
1822 		return err;
1823 
1824 	for (i = 0; i < midi2->num_eps; i++) {
1825 		err = append_config(config, &midi2_midi2_ep_out_desc[i]);
1826 		if (err < 0)
1827 			return err;
1828 		if (speed == USB_SPEED_SUPER || speed == USB_SPEED_SUPER_PLUS) {
1829 			err = append_config(config, &midi2_midi2_ep_out_ss_comp_desc);
1830 			if (err < 0)
1831 				return err;
1832 		}
1833 		err = append_config(config, &midi2_midi2_ep_out_class_desc[i]);
1834 		if (err < 0)
1835 			return err;
1836 		err = append_config(config, &midi2_midi2_ep_in_desc[i]);
1837 		if (err < 0)
1838 			return err;
1839 		if (speed == USB_SPEED_SUPER || speed == USB_SPEED_SUPER_PLUS) {
1840 			err = append_config(config, &midi2_midi2_ep_in_ss_comp_desc);
1841 			if (err < 0)
1842 				return err;
1843 		}
1844 		err = append_config(config, &midi2_midi2_ep_in_class_desc[i]);
1845 		if (err < 0)
1846 			return err;
1847 	}
1848 
1849 	return 0;
1850 }
1851 
1852 static void f_midi2_free_usb_configs(struct f_midi2_usb_config *config)
1853 {
1854 	kfree(config->list);
1855 	memset(config, 0, sizeof(*config));
1856 }
1857 
1858 /* as we use the static descriptors for simplicity, serialize bind call */
1859 static DEFINE_MUTEX(f_midi2_desc_mutex);
1860 
1861 /* fill MIDI2 EP class-specific descriptor */
1862 static void fill_midi2_class_desc(struct f_midi2_ep *ep,
1863 				  struct usb_ms20_endpoint_descriptor_32 *cdesc)
1864 {
1865 	int blk;
1866 
1867 	cdesc->bLength = USB_DT_MS20_ENDPOINT_SIZE(ep->num_blks);
1868 	cdesc->bDescriptorType = USB_DT_CS_ENDPOINT;
1869 	cdesc->bDescriptorSubtype = USB_MS_GENERAL_2_0;
1870 	cdesc->bNumGrpTrmBlock = ep->num_blks;
1871 	for (blk = 0; blk < ep->num_blks; blk++)
1872 		cdesc->baAssoGrpTrmBlkID[blk] = ep->blks[blk].gtb_id;
1873 }
1874 
1875 /* initialize MIDI2 EP-in */
1876 static int f_midi2_init_midi2_ep_in(struct f_midi2 *midi2, int index)
1877 {
1878 	struct f_midi2_ep *ep = &midi2->midi2_eps[index];
1879 	struct usb_endpoint_descriptor *desc = &midi2_midi2_ep_in_desc[index];
1880 
1881 	desc->bLength = USB_DT_ENDPOINT_SIZE;
1882 	desc->bDescriptorType = USB_DT_ENDPOINT;
1883 	desc->bEndpointAddress = USB_DIR_IN;
1884 	desc->bmAttributes = USB_ENDPOINT_XFER_INT;
1885 	desc->wMaxPacketSize = cpu_to_le16(EP_MAX_PACKET_INT);
1886 	desc->bInterval = 1;
1887 
1888 	fill_midi2_class_desc(ep, &midi2_midi2_ep_in_class_desc[index]);
1889 
1890 	return f_midi2_init_ep(midi2, ep, &ep->ep_in, desc,
1891 			       f_midi2_ep_in_complete);
1892 }
1893 
1894 /* initialize MIDI2 EP-out */
1895 static int f_midi2_init_midi2_ep_out(struct f_midi2 *midi2, int index)
1896 {
1897 	struct f_midi2_ep *ep = &midi2->midi2_eps[index];
1898 	struct usb_endpoint_descriptor *desc = &midi2_midi2_ep_out_desc[index];
1899 
1900 	desc->bLength = USB_DT_ENDPOINT_SIZE;
1901 	desc->bDescriptorType = USB_DT_ENDPOINT;
1902 	desc->bEndpointAddress = USB_DIR_OUT;
1903 	desc->bmAttributes = USB_ENDPOINT_XFER_BULK;
1904 
1905 	fill_midi2_class_desc(ep, &midi2_midi2_ep_out_class_desc[index]);
1906 
1907 	return f_midi2_init_ep(midi2, ep, &ep->ep_out, desc,
1908 			       f_midi2_ep_out_complete);
1909 }
1910 
1911 /* gadget function bind callback */
1912 static int f_midi2_bind(struct usb_configuration *c, struct usb_function *f)
1913 {
1914 	struct usb_composite_dev *cdev = c->cdev;
1915 	struct f_midi2 *midi2 = func_to_midi2(f);
1916 	struct f_midi2_ep *ep;
1917 	struct f_midi2_usb_config config = {};
1918 	struct usb_gadget_strings string_fn = {
1919 		.language = 0x0409,	/* en-us */
1920 		.strings = midi2->string_defs,
1921 	};
1922 	struct usb_gadget_strings *strings[] = {
1923 		&string_fn,
1924 		NULL,
1925 	};
1926 	int i, blk, status;
1927 
1928 	midi2->gadget = cdev->gadget;
1929 	midi2->operation_mode = MIDI_OP_MODE_UNSET;
1930 
1931 	status = f_midi2_create_card(midi2);
1932 	if (status < 0)
1933 		goto fail_register;
1934 
1935 	/* maybe allocate device-global string ID */
1936 	midi2->strings = usb_gstrings_attach(c->cdev, strings,
1937 					     midi2->total_blocks + 1);
1938 	if (IS_ERR(midi2->strings)) {
1939 		status = PTR_ERR(midi2->strings);
1940 		goto fail_string;
1941 	}
1942 
1943 	mutex_lock(&f_midi2_desc_mutex);
1944 	midi2_midi1_if_desc.iInterface = midi2->strings[STR_IFACE].id;
1945 	midi2_midi2_if_desc.iInterface = midi2->strings[STR_IFACE].id;
1946 	for (i = 0; i < midi2->num_eps; i++) {
1947 		ep = &midi2->midi2_eps[i];
1948 		for (blk = 0; blk < ep->num_blks; blk++)
1949 			ep->blks[blk].string_id =
1950 				midi2->strings[gtb_to_str_id(ep->blks[blk].gtb_id)].id;
1951 	}
1952 
1953 	midi2_midi2_if_desc.bNumEndpoints = midi2->num_eps * 2;
1954 
1955 	/* audio interface */
1956 	status = usb_interface_id(c, f);
1957 	if (status < 0)
1958 		goto fail;
1959 	midi2_audio_if_desc.bInterfaceNumber = status;
1960 
1961 	/* MIDI streaming */
1962 	status = usb_interface_id(c, f);
1963 	if (status < 0)
1964 		goto fail;
1965 	midi2->midi_if = status;
1966 	midi2_midi1_if_desc.bInterfaceNumber = status;
1967 	midi2_midi2_if_desc.bInterfaceNumber = status;
1968 	midi2_audio_class_desc.baInterfaceNr[0] = status;
1969 
1970 	/* allocate instance-specific endpoints */
1971 	if (midi2->midi2_eps[0].blks[0].info.direction != SNDRV_UMP_DIR_OUTPUT) {
1972 		status = f_midi2_init_ep(midi2, NULL, &midi2->midi1_ep_in,
1973 					 &midi2_midi1_ep_in_desc,
1974 					 f_midi2_midi1_ep_in_complete);
1975 		if (status)
1976 			goto fail;
1977 	}
1978 
1979 	if (midi2->midi2_eps[0].blks[0].info.direction != SNDRV_UMP_DIR_INPUT) {
1980 		status = f_midi2_init_ep(midi2, NULL, &midi2->midi1_ep_out,
1981 					 &midi2_midi1_ep_out_desc,
1982 					 f_midi2_midi1_ep_out_complete);
1983 		if (status)
1984 			goto fail;
1985 	}
1986 
1987 	for (i = 0; i < midi2->num_eps; i++) {
1988 		status = f_midi2_init_midi2_ep_in(midi2, i);
1989 		if (status)
1990 			goto fail;
1991 		status = f_midi2_init_midi2_ep_out(midi2, i);
1992 		if (status)
1993 			goto fail;
1994 	}
1995 
1996 	status = f_midi2_create_usb_configs(midi2, &config, USB_SPEED_FULL);
1997 	if (status < 0)
1998 		goto fail;
1999 	f->fs_descriptors = usb_copy_descriptors(config.list);
2000 	if (!f->fs_descriptors) {
2001 		status = -ENOMEM;
2002 		goto fail;
2003 	}
2004 	f_midi2_free_usb_configs(&config);
2005 
2006 	status = f_midi2_create_usb_configs(midi2, &config, USB_SPEED_HIGH);
2007 	if (status < 0)
2008 		goto fail;
2009 	f->hs_descriptors = usb_copy_descriptors(config.list);
2010 	if (!f->hs_descriptors) {
2011 		status = -ENOMEM;
2012 		goto fail;
2013 	}
2014 	f_midi2_free_usb_configs(&config);
2015 
2016 	status = f_midi2_create_usb_configs(midi2, &config, USB_SPEED_SUPER);
2017 	if (status < 0)
2018 		goto fail;
2019 	f->ss_descriptors = usb_copy_descriptors(config.list);
2020 	if (!f->ss_descriptors) {
2021 		status = -ENOMEM;
2022 		goto fail;
2023 	}
2024 	f_midi2_free_usb_configs(&config);
2025 
2026 	mutex_unlock(&f_midi2_desc_mutex);
2027 	return 0;
2028 
2029 fail:
2030 	f_midi2_free_usb_configs(&config);
2031 	mutex_unlock(&f_midi2_desc_mutex);
2032 	usb_free_all_descriptors(f);
2033 fail_string:
2034 	f_midi2_free_card(midi2);
2035 fail_register:
2036 	ERROR(midi2, "%s: can't bind, err %d\n", f->name, status);
2037 	return status;
2038 }
2039 
2040 /* gadget function unbind callback */
2041 static void f_midi2_unbind(struct usb_configuration *c, struct usb_function *f)
2042 {
2043 	struct f_midi2 *midi2 = func_to_midi2(f);
2044 	int i;
2045 
2046 	f_midi2_free_card(midi2);
2047 
2048 	f_midi2_free_ep(&midi2->midi1_ep_in);
2049 	f_midi2_free_ep(&midi2->midi1_ep_out);
2050 	for (i = 0; i < midi2->num_eps; i++) {
2051 		f_midi2_free_ep(&midi2->midi2_eps[i].ep_in);
2052 		f_midi2_free_ep(&midi2->midi2_eps[i].ep_out);
2053 	}
2054 
2055 	usb_free_all_descriptors(f);
2056 }
2057 
2058 /*
2059  * ConfigFS interface
2060  */
2061 
2062 /* type conversion helpers */
2063 static inline struct f_midi2_opts *to_f_midi2_opts(struct config_item *item)
2064 {
2065 	return container_of(to_config_group(item), struct f_midi2_opts,
2066 			    func_inst.group);
2067 }
2068 
2069 static inline struct f_midi2_ep_opts *
2070 to_f_midi2_ep_opts(struct config_item *item)
2071 {
2072 	return container_of(to_config_group(item), struct f_midi2_ep_opts,
2073 			    group);
2074 }
2075 
2076 static inline struct f_midi2_block_opts *
2077 to_f_midi2_block_opts(struct config_item *item)
2078 {
2079 	return container_of(to_config_group(item), struct f_midi2_block_opts,
2080 			    group);
2081 }
2082 
2083 /* trim the string to be usable for EP and FB name strings */
2084 static void make_name_string(char *s)
2085 {
2086 	char *p;
2087 
2088 	p = strchr(s, '\n');
2089 	if (p)
2090 		*p = 0;
2091 
2092 	p = s + strlen(s);
2093 	for (; p > s && isspace(*p); p--)
2094 		*p = 0;
2095 }
2096 
2097 /* configfs helpers: generic show/store for unisnged int */
2098 static ssize_t f_midi2_opts_uint_show(struct f_midi2_opts *opts,
2099 				      u32 val, const char *format, char *page)
2100 {
2101 	int result;
2102 
2103 	mutex_lock(&opts->lock);
2104 	result = sprintf(page, format, val);
2105 	mutex_unlock(&opts->lock);
2106 	return result;
2107 }
2108 
2109 static ssize_t f_midi2_opts_uint_store(struct f_midi2_opts *opts,
2110 				       u32 *valp, u32 minval, u32 maxval,
2111 				       const char *page, size_t len)
2112 {
2113 	int ret;
2114 	u32 val;
2115 
2116 	mutex_lock(&opts->lock);
2117 	if (opts->refcnt) {
2118 		ret = -EBUSY;
2119 		goto end;
2120 	}
2121 
2122 	ret = kstrtou32(page, 0, &val);
2123 	if (ret)
2124 		goto end;
2125 	if (val < minval || val > maxval) {
2126 		ret = -EINVAL;
2127 		goto end;
2128 	}
2129 
2130 	*valp = val;
2131 	ret = len;
2132 
2133 end:
2134 	mutex_unlock(&opts->lock);
2135 	return ret;
2136 }
2137 
2138 /* generic store for bool */
2139 static ssize_t f_midi2_opts_bool_store(struct f_midi2_opts *opts,
2140 				       bool *valp, const char *page, size_t len)
2141 {
2142 	int ret;
2143 	bool val;
2144 
2145 	mutex_lock(&opts->lock);
2146 	if (opts->refcnt) {
2147 		ret = -EBUSY;
2148 		goto end;
2149 	}
2150 
2151 	ret = kstrtobool(page, &val);
2152 	if (ret)
2153 		goto end;
2154 	*valp = val;
2155 	ret = len;
2156 
2157 end:
2158 	mutex_unlock(&opts->lock);
2159 	return ret;
2160 }
2161 
2162 /* generic show/store for string */
2163 static ssize_t f_midi2_opts_str_show(struct f_midi2_opts *opts,
2164 				     const char *str, char *page)
2165 {
2166 	int result = 0;
2167 
2168 	mutex_lock(&opts->lock);
2169 	if (str)
2170 		result = scnprintf(page, PAGE_SIZE, "%s\n", str);
2171 	mutex_unlock(&opts->lock);
2172 	return result;
2173 }
2174 
2175 static ssize_t f_midi2_opts_str_store(struct f_midi2_opts *opts,
2176 				      const char **strp, size_t maxlen,
2177 				      const char *page, size_t len)
2178 {
2179 	char *c;
2180 	int ret;
2181 
2182 	mutex_lock(&opts->lock);
2183 	if (opts->refcnt) {
2184 		ret = -EBUSY;
2185 		goto end;
2186 	}
2187 
2188 	c = kstrndup(page, min(len, maxlen), GFP_KERNEL);
2189 	if (!c) {
2190 		ret = -ENOMEM;
2191 		goto end;
2192 	}
2193 
2194 	kfree(*strp);
2195 	make_name_string(c);
2196 	*strp = c;
2197 	ret = len;
2198 
2199 end:
2200 	mutex_unlock(&opts->lock);
2201 	return ret;
2202 }
2203 
2204 /*
2205  * Definitions for UMP Block config
2206  */
2207 
2208 /* define an uint option for block */
2209 #define F_MIDI2_BLOCK_OPT(name, format, minval, maxval)			\
2210 static ssize_t f_midi2_block_opts_##name##_show(struct config_item *item,\
2211 					  char *page)			\
2212 {									\
2213 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
2214 	return f_midi2_opts_uint_show(opts->ep->opts, opts->info.name,	\
2215 				      format "\n", page);		\
2216 }									\
2217 									\
2218 static ssize_t f_midi2_block_opts_##name##_store(struct config_item *item,\
2219 					 const char *page, size_t len)	\
2220 {									\
2221 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
2222 	return f_midi2_opts_uint_store(opts->ep->opts, &opts->info.name,\
2223 				       minval, maxval, page, len);	\
2224 }									\
2225 									\
2226 CONFIGFS_ATTR(f_midi2_block_opts_, name)
2227 
2228 /* define a boolean option for block */
2229 #define F_MIDI2_BLOCK_BOOL_OPT(name)					\
2230 static ssize_t f_midi2_block_opts_##name##_show(struct config_item *item,\
2231 					  char *page)			\
2232 {									\
2233 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
2234 	return f_midi2_opts_uint_show(opts->ep->opts, opts->info.name,	\
2235 				      "%u\n", page);			\
2236 }									\
2237 									\
2238 static ssize_t f_midi2_block_opts_##name##_store(struct config_item *item,\
2239 					 const char *page, size_t len)	\
2240 {									\
2241 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
2242 	return f_midi2_opts_bool_store(opts->ep->opts, &opts->info.name,\
2243 				       page, len);			\
2244 }									\
2245 									\
2246 CONFIGFS_ATTR(f_midi2_block_opts_, name)
2247 
2248 F_MIDI2_BLOCK_OPT(direction, "0x%x", 1, 3);
2249 F_MIDI2_BLOCK_OPT(first_group, "0x%x", 0, 15);
2250 F_MIDI2_BLOCK_OPT(num_groups, "0x%x", 1, 16);
2251 F_MIDI2_BLOCK_OPT(midi1_first_group, "0x%x", 0, 15);
2252 F_MIDI2_BLOCK_OPT(midi1_num_groups, "0x%x", 0, 16);
2253 F_MIDI2_BLOCK_OPT(ui_hint, "0x%x", 0, 3);
2254 F_MIDI2_BLOCK_OPT(midi_ci_version, "%u", 0, 1);
2255 F_MIDI2_BLOCK_OPT(sysex8_streams, "%u", 0, 255);
2256 F_MIDI2_BLOCK_OPT(is_midi1, "%u", 0, 2);
2257 F_MIDI2_BLOCK_BOOL_OPT(active);
2258 
2259 static ssize_t f_midi2_block_opts_name_show(struct config_item *item,
2260 					    char *page)
2261 {
2262 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);
2263 
2264 	return f_midi2_opts_str_show(opts->ep->opts, opts->info.name, page);
2265 }
2266 
2267 static ssize_t f_midi2_block_opts_name_store(struct config_item *item,
2268 					     const char *page, size_t len)
2269 {
2270 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);
2271 
2272 	return f_midi2_opts_str_store(opts->ep->opts, &opts->info.name, 128,
2273 				      page, len);
2274 }
2275 
2276 CONFIGFS_ATTR(f_midi2_block_opts_, name);
2277 
2278 static struct configfs_attribute *f_midi2_block_attrs[] = {
2279 	&f_midi2_block_opts_attr_direction,
2280 	&f_midi2_block_opts_attr_first_group,
2281 	&f_midi2_block_opts_attr_num_groups,
2282 	&f_midi2_block_opts_attr_midi1_first_group,
2283 	&f_midi2_block_opts_attr_midi1_num_groups,
2284 	&f_midi2_block_opts_attr_ui_hint,
2285 	&f_midi2_block_opts_attr_midi_ci_version,
2286 	&f_midi2_block_opts_attr_sysex8_streams,
2287 	&f_midi2_block_opts_attr_is_midi1,
2288 	&f_midi2_block_opts_attr_active,
2289 	&f_midi2_block_opts_attr_name,
2290 	NULL,
2291 };
2292 
2293 static void f_midi2_block_opts_release(struct config_item *item)
2294 {
2295 	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);
2296 
2297 	kfree(opts->info.name);
2298 	kfree(opts);
2299 }
2300 
2301 static struct configfs_item_operations f_midi2_block_item_ops = {
2302 	.release	= f_midi2_block_opts_release,
2303 };
2304 
2305 static const struct config_item_type f_midi2_block_type = {
2306 	.ct_item_ops	= &f_midi2_block_item_ops,
2307 	.ct_attrs	= f_midi2_block_attrs,
2308 	.ct_owner	= THIS_MODULE,
2309 };
2310 
2311 /* create a f_midi2_block_opts instance for the given block number */
2312 static int f_midi2_block_opts_create(struct f_midi2_ep_opts *ep_opts,
2313 				     unsigned int blk,
2314 				     struct f_midi2_block_opts **block_p)
2315 {
2316 	struct f_midi2_block_opts *block_opts;
2317 	int ret = 0;
2318 
2319 	mutex_lock(&ep_opts->opts->lock);
2320 	if (ep_opts->opts->refcnt || ep_opts->blks[blk]) {
2321 		ret = -EBUSY;
2322 		goto out;
2323 	}
2324 
2325 	block_opts = kzalloc(sizeof(*block_opts), GFP_KERNEL);
2326 	if (!block_opts) {
2327 		ret = -ENOMEM;
2328 		goto out;
2329 	}
2330 
2331 	block_opts->ep = ep_opts;
2332 	block_opts->id = blk;
2333 
2334 	/* set up the default values */
2335 	block_opts->info.direction = SNDRV_UMP_DIR_BIDIRECTION;
2336 	block_opts->info.first_group = 0;
2337 	block_opts->info.num_groups = 1;
2338 	block_opts->info.ui_hint = SNDRV_UMP_BLOCK_UI_HINT_BOTH;
2339 	block_opts->info.active = 1;
2340 
2341 	ep_opts->blks[blk] = block_opts;
2342 	*block_p = block_opts;
2343 
2344  out:
2345 	mutex_unlock(&ep_opts->opts->lock);
2346 	return ret;
2347 }
2348 
2349 /* make_group callback for a block */
2350 static struct config_group *
2351 f_midi2_opts_block_make(struct config_group *group, const char *name)
2352 {
2353 	struct f_midi2_ep_opts *ep_opts;
2354 	struct f_midi2_block_opts *block_opts;
2355 	unsigned int blk;
2356 	int ret;
2357 
2358 	if (strncmp(name, "block.", 6))
2359 		return ERR_PTR(-EINVAL);
2360 	ret = kstrtouint(name + 6, 10, &blk);
2361 	if (ret)
2362 		return ERR_PTR(ret);
2363 
2364 	ep_opts = to_f_midi2_ep_opts(&group->cg_item);
2365 
2366 	if (blk >= SNDRV_UMP_MAX_BLOCKS)
2367 		return ERR_PTR(-EINVAL);
2368 	if (ep_opts->blks[blk])
2369 		return ERR_PTR(-EBUSY);
2370 	ret = f_midi2_block_opts_create(ep_opts, blk, &block_opts);
2371 	if (ret)
2372 		return ERR_PTR(ret);
2373 
2374 	config_group_init_type_name(&block_opts->group, name,
2375 				    &f_midi2_block_type);
2376 	return &block_opts->group;
2377 }
2378 
2379 /* drop_item callback for a block */
2380 static void
2381 f_midi2_opts_block_drop(struct config_group *group, struct config_item *item)
2382 {
2383 	struct f_midi2_block_opts *block_opts = to_f_midi2_block_opts(item);
2384 
2385 	mutex_lock(&block_opts->ep->opts->lock);
2386 	block_opts->ep->blks[block_opts->id] = NULL;
2387 	mutex_unlock(&block_opts->ep->opts->lock);
2388 	config_item_put(item);
2389 }
2390 
2391 /*
2392  * Definitions for UMP Endpoint config
2393  */
2394 
2395 /* define an uint option for EP */
2396 #define F_MIDI2_EP_OPT(name, format, minval, maxval)			\
2397 static ssize_t f_midi2_ep_opts_##name##_show(struct config_item *item,	\
2398 					     char *page)		\
2399 {									\
2400 	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
2401 	return f_midi2_opts_uint_show(opts->opts, opts->info.name,	\
2402 				      format "\n", page);		\
2403 }									\
2404 									\
2405 static ssize_t f_midi2_ep_opts_##name##_store(struct config_item *item,	\
2406 					   const char *page, size_t len)\
2407 {									\
2408 	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
2409 	return f_midi2_opts_uint_store(opts->opts, &opts->info.name,	\
2410 				       minval, maxval, page, len);	\
2411 }									\
2412 									\
2413 CONFIGFS_ATTR(f_midi2_ep_opts_, name)
2414 
2415 /* define a string option for EP */
2416 #define F_MIDI2_EP_STR_OPT(name, maxlen)				\
2417 static ssize_t f_midi2_ep_opts_##name##_show(struct config_item *item,	\
2418 					     char *page)		\
2419 {									\
2420 	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
2421 	return f_midi2_opts_str_show(opts->opts, opts->info.name, page);\
2422 }									\
2423 									\
2424 static ssize_t f_midi2_ep_opts_##name##_store(struct config_item *item,	\
2425 					 const char *page, size_t len)	\
2426 {									\
2427 	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
2428 	return f_midi2_opts_str_store(opts->opts, &opts->info.name, maxlen,\
2429 				      page, len);			\
2430 }									\
2431 									\
2432 CONFIGFS_ATTR(f_midi2_ep_opts_, name)
2433 
2434 F_MIDI2_EP_OPT(protocol, "0x%x", 1, 2);
2435 F_MIDI2_EP_OPT(protocol_caps, "0x%x", 1, 3);
2436 F_MIDI2_EP_OPT(manufacturer, "0x%x", 0, 0xffffff);
2437 F_MIDI2_EP_OPT(family, "0x%x", 0, 0xffff);
2438 F_MIDI2_EP_OPT(model, "0x%x", 0, 0xffff);
2439 F_MIDI2_EP_OPT(sw_revision, "0x%x", 0, 0xffffffff);
2440 F_MIDI2_EP_STR_OPT(ep_name, 128);
2441 F_MIDI2_EP_STR_OPT(product_id, 128);
2442 
2443 static struct configfs_attribute *f_midi2_ep_attrs[] = {
2444 	&f_midi2_ep_opts_attr_protocol,
2445 	&f_midi2_ep_opts_attr_protocol_caps,
2446 	&f_midi2_ep_opts_attr_ep_name,
2447 	&f_midi2_ep_opts_attr_product_id,
2448 	&f_midi2_ep_opts_attr_manufacturer,
2449 	&f_midi2_ep_opts_attr_family,
2450 	&f_midi2_ep_opts_attr_model,
2451 	&f_midi2_ep_opts_attr_sw_revision,
2452 	NULL,
2453 };
2454 
2455 static void f_midi2_ep_opts_release(struct config_item *item)
2456 {
2457 	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);
2458 
2459 	kfree(opts->info.ep_name);
2460 	kfree(opts->info.product_id);
2461 	kfree(opts);
2462 }
2463 
2464 static struct configfs_item_operations f_midi2_ep_item_ops = {
2465 	.release	= f_midi2_ep_opts_release,
2466 };
2467 
2468 static struct configfs_group_operations f_midi2_ep_group_ops = {
2469 	.make_group	= f_midi2_opts_block_make,
2470 	.drop_item	= f_midi2_opts_block_drop,
2471 };
2472 
2473 static const struct config_item_type f_midi2_ep_type = {
2474 	.ct_item_ops	= &f_midi2_ep_item_ops,
2475 	.ct_group_ops	= &f_midi2_ep_group_ops,
2476 	.ct_attrs	= f_midi2_ep_attrs,
2477 	.ct_owner	= THIS_MODULE,
2478 };
2479 
2480 /* create a f_midi2_ep_opts instance */
2481 static int f_midi2_ep_opts_create(struct f_midi2_opts *opts,
2482 				  unsigned int index,
2483 				  struct f_midi2_ep_opts **ep_p)
2484 {
2485 	struct f_midi2_ep_opts *ep_opts;
2486 
2487 	ep_opts = kzalloc(sizeof(*ep_opts), GFP_KERNEL);
2488 	if (!ep_opts)
2489 		return -ENOMEM;
2490 
2491 	ep_opts->opts = opts;
2492 	ep_opts->index = index;
2493 
2494 	/* set up the default values */
2495 	ep_opts->info.protocol = 2;
2496 	ep_opts->info.protocol_caps = 3;
2497 
2498 	opts->eps[index] = ep_opts;
2499 	*ep_p = ep_opts;
2500 	return 0;
2501 }
2502 
2503 /* make_group callback for an EP */
2504 static struct config_group *
2505 f_midi2_opts_ep_make(struct config_group *group, const char *name)
2506 {
2507 	struct f_midi2_opts *opts;
2508 	struct f_midi2_ep_opts *ep_opts;
2509 	unsigned int index;
2510 	int ret;
2511 
2512 	if (strncmp(name, "ep.", 3))
2513 		return ERR_PTR(-EINVAL);
2514 	ret = kstrtouint(name + 3, 10, &index);
2515 	if (ret)
2516 		return ERR_PTR(ret);
2517 
2518 	opts = to_f_midi2_opts(&group->cg_item);
2519 	if (index >= MAX_UMP_EPS)
2520 		return ERR_PTR(-EINVAL);
2521 	if (opts->eps[index])
2522 		return ERR_PTR(-EBUSY);
2523 	ret = f_midi2_ep_opts_create(opts, index, &ep_opts);
2524 	if (ret)
2525 		return ERR_PTR(ret);
2526 
2527 	config_group_init_type_name(&ep_opts->group, name, &f_midi2_ep_type);
2528 	return &ep_opts->group;
2529 }
2530 
2531 /* drop_item callback for an EP */
2532 static void
2533 f_midi2_opts_ep_drop(struct config_group *group, struct config_item *item)
2534 {
2535 	struct f_midi2_ep_opts *ep_opts = to_f_midi2_ep_opts(item);
2536 
2537 	mutex_lock(&ep_opts->opts->lock);
2538 	ep_opts->opts->eps[ep_opts->index] = NULL;
2539 	mutex_unlock(&ep_opts->opts->lock);
2540 	config_item_put(item);
2541 }
2542 
2543 /*
2544  * Definitions for card config
2545  */
2546 
2547 /* define a bool option for card */
2548 #define F_MIDI2_BOOL_OPT(name)						\
2549 static ssize_t f_midi2_opts_##name##_show(struct config_item *item,	\
2550 					  char *page)			\
2551 {									\
2552 	struct f_midi2_opts *opts = to_f_midi2_opts(item);		\
2553 	return f_midi2_opts_uint_show(opts, opts->info.name,		\
2554 				      "%u\n", page);			\
2555 }									\
2556 									\
2557 static ssize_t f_midi2_opts_##name##_store(struct config_item *item,	\
2558 					 const char *page, size_t len)	\
2559 {									\
2560 	struct f_midi2_opts *opts = to_f_midi2_opts(item);		\
2561 	return f_midi2_opts_bool_store(opts, &opts->info.name,		\
2562 				       page, len);			\
2563 }									\
2564 									\
2565 CONFIGFS_ATTR(f_midi2_opts_, name)
2566 
2567 F_MIDI2_BOOL_OPT(process_ump);
2568 F_MIDI2_BOOL_OPT(static_block);
2569 
2570 static ssize_t f_midi2_opts_iface_name_show(struct config_item *item,
2571 					    char *page)
2572 {
2573 	struct f_midi2_opts *opts = to_f_midi2_opts(item);
2574 
2575 	return f_midi2_opts_str_show(opts, opts->info.iface_name, page);
2576 }
2577 
2578 static ssize_t f_midi2_opts_iface_name_store(struct config_item *item,
2579 					     const char *page, size_t len)
2580 {
2581 	struct f_midi2_opts *opts = to_f_midi2_opts(item);
2582 
2583 	return f_midi2_opts_str_store(opts, &opts->info.iface_name, 128,
2584 				      page, len);
2585 }
2586 
2587 CONFIGFS_ATTR(f_midi2_opts_, iface_name);
2588 
2589 static struct configfs_attribute *f_midi2_attrs[] = {
2590 	&f_midi2_opts_attr_process_ump,
2591 	&f_midi2_opts_attr_static_block,
2592 	&f_midi2_opts_attr_iface_name,
2593 	NULL
2594 };
2595 
2596 static void f_midi2_opts_release(struct config_item *item)
2597 {
2598 	struct f_midi2_opts *opts = to_f_midi2_opts(item);
2599 
2600 	usb_put_function_instance(&opts->func_inst);
2601 }
2602 
2603 static struct configfs_item_operations f_midi2_item_ops = {
2604 	.release	= f_midi2_opts_release,
2605 };
2606 
2607 static struct configfs_group_operations f_midi2_group_ops = {
2608 	.make_group	= f_midi2_opts_ep_make,
2609 	.drop_item	= f_midi2_opts_ep_drop,
2610 };
2611 
2612 static const struct config_item_type f_midi2_func_type = {
2613 	.ct_item_ops	= &f_midi2_item_ops,
2614 	.ct_group_ops	= &f_midi2_group_ops,
2615 	.ct_attrs	= f_midi2_attrs,
2616 	.ct_owner	= THIS_MODULE,
2617 };
2618 
2619 static void f_midi2_free_inst(struct usb_function_instance *f)
2620 {
2621 	struct f_midi2_opts *opts;
2622 
2623 	opts = container_of(f, struct f_midi2_opts, func_inst);
2624 
2625 	kfree(opts->info.iface_name);
2626 	kfree(opts);
2627 }
2628 
2629 /* gadget alloc_inst */
2630 static struct usb_function_instance *f_midi2_alloc_inst(void)
2631 {
2632 	struct f_midi2_opts *opts;
2633 	struct f_midi2_ep_opts *ep_opts;
2634 	struct f_midi2_block_opts *block_opts;
2635 	int ret;
2636 
2637 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
2638 	if (!opts)
2639 		return ERR_PTR(-ENOMEM);
2640 
2641 	mutex_init(&opts->lock);
2642 	opts->func_inst.free_func_inst = f_midi2_free_inst;
2643 	opts->info.process_ump = true;
2644 	opts->info.static_block = true;
2645 	opts->info.num_reqs = 32;
2646 	opts->info.req_buf_size = 512;
2647 
2648 	/* create the default ep */
2649 	ret = f_midi2_ep_opts_create(opts, 0, &ep_opts);
2650 	if (ret) {
2651 		kfree(opts);
2652 		return ERR_PTR(ret);
2653 	}
2654 
2655 	/* create the default block */
2656 	ret = f_midi2_block_opts_create(ep_opts, 0, &block_opts);
2657 	if (ret) {
2658 		kfree(ep_opts);
2659 		kfree(opts);
2660 		return ERR_PTR(ret);
2661 	}
2662 
2663 	/* set up the default MIDI1 (that is mandatory) */
2664 	block_opts->info.midi1_num_groups = 1;
2665 
2666 	config_group_init_type_name(&opts->func_inst.group, "",
2667 				    &f_midi2_func_type);
2668 
2669 	config_group_init_type_name(&ep_opts->group, "ep.0",
2670 				    &f_midi2_ep_type);
2671 	configfs_add_default_group(&ep_opts->group, &opts->func_inst.group);
2672 
2673 	config_group_init_type_name(&block_opts->group, "block.0",
2674 				    &f_midi2_block_type);
2675 	configfs_add_default_group(&block_opts->group, &ep_opts->group);
2676 
2677 	return &opts->func_inst;
2678 }
2679 
2680 static void do_f_midi2_free(struct f_midi2 *midi2, struct f_midi2_opts *opts)
2681 {
2682 	mutex_lock(&opts->lock);
2683 	--opts->refcnt;
2684 	mutex_unlock(&opts->lock);
2685 	kfree(midi2->string_defs);
2686 	kfree(midi2);
2687 }
2688 
2689 static void f_midi2_free(struct usb_function *f)
2690 {
2691 	do_f_midi2_free(func_to_midi2(f),
2692 			container_of(f->fi, struct f_midi2_opts, func_inst));
2693 }
2694 
2695 /* verify the parameters set up via configfs;
2696  * return the number of EPs or a negative error
2697  */
2698 static int verify_parameters(struct f_midi2_opts *opts)
2699 {
2700 	int i, j, num_eps, num_blks;
2701 	struct f_midi2_ep_info *ep;
2702 	struct f_midi2_block_info *bp;
2703 
2704 	for (num_eps = 0; num_eps < MAX_UMP_EPS && opts->eps[num_eps];
2705 	     num_eps++)
2706 		;
2707 	if (!num_eps) {
2708 		pr_err("f_midi2: No EP is defined\n");
2709 		return -EINVAL;
2710 	}
2711 
2712 	num_blks = 0;
2713 	for (i = 0; i < num_eps; i++) {
2714 		ep = &opts->eps[i]->info;
2715 		if (!(ep->protocol_caps & ep->protocol)) {
2716 			pr_err("f_midi2: Invalid protocol 0x%x (caps 0x%x) for EP %d\n",
2717 			       ep->protocol, ep->protocol_caps, i);
2718 			return -EINVAL;
2719 		}
2720 
2721 		for (j = 0; j < SNDRV_UMP_MAX_BLOCKS && opts->eps[i]->blks[j];
2722 		     j++, num_blks++) {
2723 			bp = &opts->eps[i]->blks[j]->info;
2724 			if (bp->first_group + bp->num_groups > SNDRV_UMP_MAX_GROUPS) {
2725 				pr_err("f_midi2: Invalid group definitions for block %d:%d\n",
2726 				       i, j);
2727 				return -EINVAL;
2728 			}
2729 
2730 			if (bp->midi1_num_groups) {
2731 				if (bp->midi1_first_group < bp->first_group ||
2732 				    bp->midi1_first_group + bp->midi1_num_groups >
2733 				    bp->first_group + bp->num_groups) {
2734 					pr_err("f_midi2: Invalid MIDI1 group definitions for block %d:%d\n",
2735 					       i, j);
2736 					return -EINVAL;
2737 				}
2738 			}
2739 		}
2740 	}
2741 	if (!num_blks) {
2742 		pr_err("f_midi2: No block is defined\n");
2743 		return -EINVAL;
2744 	}
2745 
2746 	return num_eps;
2747 }
2748 
2749 /* fill mapping between MIDI 1.0 cable and UMP EP/group */
2750 static void fill_midi1_cable_mapping(struct f_midi2 *midi2,
2751 				     struct f_midi2_ep *ep,
2752 				     int blk)
2753 {
2754 	const struct f_midi2_block_info *binfo = &ep->blks[blk].info;
2755 	struct midi1_cable_mapping *map;
2756 	int i, group;
2757 
2758 	if (!binfo->midi1_num_groups)
2759 		return;
2760 	if (binfo->direction != SNDRV_UMP_DIR_OUTPUT) {
2761 		group = binfo->midi1_first_group;
2762 		map = midi2->in_cable_mapping + midi2->num_midi1_in;
2763 		for (i = 0; i < binfo->midi1_num_groups; i++, group++, map++) {
2764 			if (midi2->num_midi1_in >= MAX_CABLES)
2765 				break;
2766 			map->ep = ep;
2767 			map->block = blk;
2768 			map->group = group;
2769 			midi2->num_midi1_in++;
2770 			/* store 1-based cable number */
2771 			ep->in_group_to_cable[group] = midi2->num_midi1_in;
2772 		}
2773 	}
2774 
2775 	if (binfo->direction != SNDRV_UMP_DIR_INPUT) {
2776 		group = binfo->midi1_first_group;
2777 		map = midi2->out_cable_mapping + midi2->num_midi1_out;
2778 		for (i = 0; i < binfo->midi1_num_groups; i++, group++, map++) {
2779 			if (midi2->num_midi1_out >= MAX_CABLES)
2780 				break;
2781 			map->ep = ep;
2782 			map->block = blk;
2783 			map->group = group;
2784 			midi2->num_midi1_out++;
2785 		}
2786 	}
2787 }
2788 
2789 /* gadget alloc callback */
2790 static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi)
2791 {
2792 	struct f_midi2 *midi2;
2793 	struct f_midi2_opts *opts;
2794 	struct f_midi2_ep *ep;
2795 	struct f_midi2_block *bp;
2796 	int i, num_eps, blk;
2797 
2798 	midi2 = kzalloc(sizeof(*midi2), GFP_KERNEL);
2799 	if (!midi2)
2800 		return ERR_PTR(-ENOMEM);
2801 
2802 	opts = container_of(fi, struct f_midi2_opts, func_inst);
2803 	mutex_lock(&opts->lock);
2804 	num_eps = verify_parameters(opts);
2805 	if (num_eps < 0) {
2806 		mutex_unlock(&opts->lock);
2807 		kfree(midi2);
2808 		return ERR_PTR(num_eps);
2809 	}
2810 	++opts->refcnt;
2811 	mutex_unlock(&opts->lock);
2812 
2813 	spin_lock_init(&midi2->queue_lock);
2814 
2815 	midi2->func.name = "midi2_func";
2816 	midi2->func.bind = f_midi2_bind;
2817 	midi2->func.unbind = f_midi2_unbind;
2818 	midi2->func.get_alt = f_midi2_get_alt;
2819 	midi2->func.set_alt = f_midi2_set_alt;
2820 	midi2->func.setup = f_midi2_setup;
2821 	midi2->func.disable = f_midi2_disable;
2822 	midi2->func.free_func = f_midi2_free;
2823 
2824 	midi2->info = opts->info;
2825 	midi2->num_eps = num_eps;
2826 
2827 	for (i = 0; i < num_eps; i++) {
2828 		ep = &midi2->midi2_eps[i];
2829 		ep->info = opts->eps[i]->info;
2830 		ep->card = midi2;
2831 		for (blk = 0; blk < SNDRV_UMP_MAX_BLOCKS &&
2832 			     opts->eps[i]->blks[blk]; blk++) {
2833 			bp = &ep->blks[blk];
2834 			ep->num_blks++;
2835 			bp->info = opts->eps[i]->blks[blk]->info;
2836 			bp->gtb_id = ++midi2->total_blocks;
2837 		}
2838 	}
2839 
2840 	midi2->string_defs = kcalloc(midi2->total_blocks + 1,
2841 				     sizeof(*midi2->string_defs), GFP_KERNEL);
2842 	if (!midi2->string_defs) {
2843 		do_f_midi2_free(midi2, opts);
2844 		return ERR_PTR(-ENOMEM);
2845 	}
2846 
2847 	if (opts->info.iface_name && *opts->info.iface_name)
2848 		midi2->string_defs[STR_IFACE].s = opts->info.iface_name;
2849 	else
2850 		midi2->string_defs[STR_IFACE].s = ump_ep_name(&midi2->midi2_eps[0]);
2851 
2852 	for (i = 0; i < midi2->num_eps; i++) {
2853 		ep = &midi2->midi2_eps[i];
2854 		for (blk = 0; blk < ep->num_blks; blk++) {
2855 			bp = &ep->blks[blk];
2856 			midi2->string_defs[gtb_to_str_id(bp->gtb_id)].s =
2857 				ump_fb_name(&bp->info);
2858 
2859 			fill_midi1_cable_mapping(midi2, ep, blk);
2860 		}
2861 	}
2862 
2863 	if (!midi2->num_midi1_in && !midi2->num_midi1_out) {
2864 		pr_err("f_midi2: MIDI1 definition is missing\n");
2865 		do_f_midi2_free(midi2, opts);
2866 		return ERR_PTR(-EINVAL);
2867 	}
2868 
2869 	return &midi2->func;
2870 }
2871 
2872 DECLARE_USB_FUNCTION_INIT(midi2, f_midi2_alloc_inst, f_midi2_alloc);
2873 
2874 MODULE_LICENSE("GPL");
2875