xref: /linux/sound/usb/fcp.c (revision c36461825469a9ceee2346a2e89286c522525da7)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Focusrite Control Protocol Driver for ALSA
4  *
5  * Copyright (c) 2024-2025 by Geoffrey D. Bennett <g at b4.vu>
6  */
7 /*
8  * DOC: Theory of Operation
9  *
10  * The Focusrite Control Protocol (FCP) driver provides a minimal
11  * kernel interface that allows a user-space driver (primarily
12  * fcp-server) to communicate with Focusrite USB audio interfaces
13  * using their vendor-specific protocol. This protocol is used by
14  * Scarlett 2nd Gen, 3rd Gen, 4th Gen, Clarett USB, Clarett+, and
15  * Vocaster series devices.
16  *
17  * Unlike the existing scarlett2 driver which implements all controls
18  * in kernel space, this driver takes a lighter-weight approach by
19  * moving most functionality to user space. The only control
20  * implemented in kernel space is the Level Meter, since it requires
21  * frequent polling of volatile data.
22  *
23  * The driver provides an hwdep interface that allows the user-space
24  * driver to:
25  *  - Initialise the protocol
26  *  - Send arbitrary FCP commands to the device
27  *  - Receive notifications from the device
28  *  - Configure the Level Meter control
29  *
30  * Usage Flow
31  * ----------
32  * 1. Open the hwdep device (requires CAP_SYS_RAWIO)
33  * 2. Get protocol version using FCP_IOCTL_PVERSION
34  * 3. Initialise protocol using FCP_IOCTL_INIT
35  * 4. Send commands using FCP_IOCTL_CMD
36  * 5. Receive notifications using read()
37  * 6. Optionally set up the Level Meter control using
38  *    FCP_IOCTL_SET_METER_MAP
39  * 7. Optionally add labels to the Level Meter control using
40  *    FCP_IOCTL_SET_METER_LABELS
41  *
42  * Level Meter
43  * -----------
44  * The Level Meter is implemented as an ALSA control that provides
45  * real-time level monitoring. When the control is read, the driver
46  * requests the current meter levels from the device, translates the
47  * levels using the configured mapping, and returns the result to the
48  * user. The mapping between device meters and the ALSA control's
49  * channels is configured with FCP_IOCTL_SET_METER_MAP.
50  *
51  * Labels for the Level Meter channels can be set using
52  * FCP_IOCTL_SET_METER_LABELS and read by applications through the
53  * control's TLV data. The labels are transferred as a sequence of
54  * null-terminated strings.
55  */
56 
57 #include <linux/slab.h>
58 #include <linux/usb.h>
59 
60 #include <sound/control.h>
61 #include <sound/hwdep.h>
62 #include <sound/tlv.h>
63 
64 #include <uapi/sound/fcp.h>
65 
66 #include "usbaudio.h"
67 #include "mixer.h"
68 #include "helper.h"
69 
70 #include "fcp.h"
71 
72 /* notify waiting to send to *file */
73 struct fcp_notify {
74 	wait_queue_head_t queue;
75 	u32               event;
76 	spinlock_t        lock;
77 };
78 
79 struct fcp_data {
80 	struct usb_mixer_interface *mixer;
81 
82 	struct mutex mutex;         /* serialise access to the device */
83 	struct completion cmd_done; /* wait for command completion */
84 	struct file *file;          /* hwdep file */
85 
86 	struct fcp_notify notify;
87 
88 	u8  bInterfaceNumber;
89 	u8  bEndpointAddress;
90 	u16 wMaxPacketSize;
91 	u8  bInterval;
92 
93 	uint16_t step0_resp_size;
94 	uint16_t step2_resp_size;
95 	uint32_t init1_opcode;
96 	uint32_t init2_opcode;
97 
98 	u8  init;
99 	u16 seq;
100 
101 	u8                   num_meter_slots;
102 	s16                 *meter_level_map;
103 	__le32              *meter_levels;
104 	struct snd_kcontrol *meter_ctl;
105 
106 	unsigned int *meter_labels_tlv;
107 	int           meter_labels_tlv_size;
108 };
109 
110 /*** USB Interactions ***/
111 
112 /* FCP Command ACK notification bit */
113 #define FCP_NOTIFY_ACK 1
114 
115 /* Vendor-specific USB control requests */
116 #define FCP_USB_REQ_STEP0  0
117 #define FCP_USB_REQ_CMD_TX 2
118 #define FCP_USB_REQ_CMD_RX 3
119 
120 /* Focusrite Control Protocol opcodes that the kernel side needs to
121  * know about
122  */
123 #define FCP_USB_REBOOT      0x00000003
124 #define FCP_USB_GET_METER   0x00001001
125 #define FCP_USB_FLASH_ERASE 0x00004002
126 #define FCP_USB_FLASH_WRITE 0x00004004
127 
128 #define FCP_USB_METER_LEVELS_GET_MAGIC 1
129 
130 #define FCP_SEGMENT_APP_GOLD 0
131 
132 #define FCP_MAX_METER_MAP_SIZE \
133 	(sizeof_field(struct snd_ctl_elem_value, value.integer.value) / \
134 	 sizeof(long))
135 
136 /* Forward declarations */
137 static int fcp_init(struct usb_mixer_interface *mixer,
138 		    void *step0_resp, void *step2_resp);
139 
140 /* FCP command request/response format */
141 struct fcp_usb_packet {
142 	__le32 opcode;
143 	__le16 size;
144 	__le16 seq;
145 	__le32 error;
146 	__le32 pad;
147 	u8 data[];
148 };
149 
150 static void fcp_fill_request_header(struct fcp_data *private,
151 				    struct fcp_usb_packet *req,
152 				    u32 opcode, u16 req_size)
153 {
154 	/* sequence must go up by 1 for each request */
155 	u16 seq = private->seq++;
156 
157 	req->opcode = cpu_to_le32(opcode);
158 	req->size = cpu_to_le16(req_size);
159 	req->seq = cpu_to_le16(seq);
160 	req->error = 0;
161 	req->pad = 0;
162 }
163 
164 static int fcp_usb_tx(struct usb_device *dev, int interface,
165 		      void *buf, u16 size)
166 {
167 	return snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0),
168 			FCP_USB_REQ_CMD_TX,
169 			USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
170 			0, interface, buf, size);
171 }
172 
173 static int fcp_usb_rx(struct usb_device *dev, int interface,
174 		      void *buf, u16 size)
175 {
176 	return snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0),
177 			FCP_USB_REQ_CMD_RX,
178 			USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
179 			0, interface, buf, size);
180 }
181 
182 /* Send an FCP command and get the response */
183 static int fcp_usb(struct usb_mixer_interface *mixer, u32 opcode,
184 		   const void *req_data, u16 req_size,
185 		   void *resp_data, u16 resp_size)
186 {
187 	struct fcp_data *private = mixer->private_data;
188 	struct usb_device *dev = mixer->chip->dev;
189 	int retries = 0;
190 	const int max_retries = 5;
191 	int err;
192 
193 	if (!mixer->urb)
194 		return -ENODEV;
195 
196 	struct fcp_usb_packet *req __free(kfree) = NULL;
197 	size_t req_buf_size = struct_size(req, data, req_size);
198 	req = kmalloc_flex(*req, data, req_size);
199 	if (!req)
200 		return -ENOMEM;
201 
202 	struct fcp_usb_packet *resp __free(kfree) = NULL;
203 	size_t resp_buf_size = struct_size(resp, data, resp_size);
204 	resp = kmalloc_flex(*resp, data, resp_size);
205 	if (!resp)
206 		return -ENOMEM;
207 
208 	/* build request message */
209 	fcp_fill_request_header(private, req, opcode, req_size);
210 	if (req_size)
211 		memcpy(req->data, req_data, req_size);
212 
213 	/* send the request and retry on EPROTO */
214 retry:
215 	err = fcp_usb_tx(dev, private->bInterfaceNumber, req, req_buf_size);
216 	if (err == -EPROTO && ++retries <= max_retries) {
217 		msleep(1 << (retries - 1));
218 		goto retry;
219 	}
220 
221 	if (err != req_buf_size) {
222 		usb_audio_err(mixer->chip,
223 			      "FCP request %08x failed: %d\n", opcode, err);
224 		return -EINVAL;
225 	}
226 
227 	if (!wait_for_completion_timeout(&private->cmd_done,
228 					 msecs_to_jiffies(1000))) {
229 		usb_audio_err(mixer->chip,
230 			      "FCP request %08x timed out\n", opcode);
231 
232 		return -ETIMEDOUT;
233 	}
234 
235 	/* send a second message to get the response */
236 	err = fcp_usb_rx(dev, private->bInterfaceNumber, resp, resp_buf_size);
237 
238 	/* validate the response */
239 
240 	if (err < 0) {
241 
242 		/* ESHUTDOWN and EPROTO are valid responses to a
243 		 * reboot request
244 		 */
245 		if (opcode == FCP_USB_REBOOT &&
246 		    (err == -ESHUTDOWN || err == -EPROTO))
247 			return 0;
248 
249 		usb_audio_err(mixer->chip,
250 			      "FCP read response %08x failed: %d\n",
251 			      opcode, err);
252 		return -EINVAL;
253 	}
254 
255 	if (err < sizeof(*resp)) {
256 		usb_audio_err(mixer->chip,
257 			      "FCP response %08x too short: %d\n",
258 			      opcode, err);
259 		return -EINVAL;
260 	}
261 
262 	if (req->seq != resp->seq) {
263 		usb_audio_err(mixer->chip,
264 			      "FCP response %08x seq mismatch %d/%d\n",
265 			      opcode,
266 			      le16_to_cpu(req->seq), le16_to_cpu(resp->seq));
267 		return -EINVAL;
268 	}
269 
270 	if (req->opcode != resp->opcode) {
271 		usb_audio_err(mixer->chip,
272 			      "FCP response %08x opcode mismatch %08x\n",
273 			      opcode, le32_to_cpu(resp->opcode));
274 		return -EINVAL;
275 	}
276 
277 	if (resp->error) {
278 		usb_audio_err(mixer->chip,
279 			      "FCP response %08x error %d\n",
280 			      opcode, le32_to_cpu(resp->error));
281 		return -EINVAL;
282 	}
283 
284 	if (err != resp_buf_size) {
285 		usb_audio_err(mixer->chip,
286 			      "FCP response %08x buffer size mismatch %d/%zu\n",
287 			      opcode, err, resp_buf_size);
288 		return -EINVAL;
289 	}
290 
291 	if (resp_size != le16_to_cpu(resp->size)) {
292 		usb_audio_err(mixer->chip,
293 			      "FCP response %08x size mismatch %d/%d\n",
294 			      opcode, resp_size, le16_to_cpu(resp->size));
295 		return -EINVAL;
296 	}
297 
298 	if (resp_data && resp_size > 0)
299 		memcpy(resp_data, resp->data, resp_size);
300 
301 	return 0;
302 }
303 
304 static int fcp_reinit(struct usb_mixer_interface *mixer)
305 {
306 	struct fcp_data *private = mixer->private_data;
307 
308 	if (mixer->urb)
309 		return 0;
310 
311 	void *step0_resp __free(kfree) =
312 		kmalloc(private->step0_resp_size, GFP_KERNEL);
313 	if (!step0_resp)
314 		return -ENOMEM;
315 
316 	void *step2_resp __free(kfree) =
317 		kmalloc(private->step2_resp_size, GFP_KERNEL);
318 	if (!step2_resp)
319 		return -ENOMEM;
320 
321 	return fcp_init(mixer, step0_resp, step2_resp);
322 }
323 
324 /*** Control Functions ***/
325 
326 /* helper function to create a new control */
327 static int fcp_add_new_ctl(struct usb_mixer_interface *mixer,
328 			   const struct snd_kcontrol_new *ncontrol,
329 			   int index, int channels, const char *name,
330 			   struct snd_kcontrol **kctl_return)
331 {
332 	struct snd_kcontrol *kctl;
333 	struct usb_mixer_elem_info *elem;
334 	int err;
335 
336 	elem = kzalloc_obj(*elem);
337 	if (!elem)
338 		return -ENOMEM;
339 
340 	/* We set USB_MIXER_BESPOKEN type, so that the core USB mixer code
341 	 * ignores them for resume and other operations.
342 	 * Also, the head.id field is set to 0, as we don't use this field.
343 	 */
344 	elem->head.mixer = mixer;
345 	elem->control = index;
346 	elem->head.id = 0;
347 	elem->channels = channels;
348 	elem->val_type = USB_MIXER_BESPOKEN;
349 
350 	kctl = snd_ctl_new1(ncontrol, elem);
351 	if (!kctl) {
352 		kfree(elem);
353 		return -ENOMEM;
354 	}
355 	kctl->private_free = snd_usb_mixer_elem_free;
356 
357 	strscpy(kctl->id.name, name, sizeof(kctl->id.name));
358 
359 	err = snd_usb_mixer_add_control(&elem->head, kctl);
360 	if (err < 0)
361 		return err;
362 
363 	if (kctl_return)
364 		*kctl_return = kctl;
365 
366 	return 0;
367 }
368 
369 /*** Level Meter Control ***/
370 
371 static int fcp_meter_ctl_info(struct snd_kcontrol *kctl,
372 			      struct snd_ctl_elem_info *uinfo)
373 {
374 	struct usb_mixer_elem_info *elem = kctl->private_data;
375 
376 	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
377 	uinfo->count = elem->channels;
378 	uinfo->value.integer.min = 0;
379 	uinfo->value.integer.max = 4095;
380 	uinfo->value.integer.step = 1;
381 	return 0;
382 }
383 
384 static int fcp_meter_ctl_get(struct snd_kcontrol *kctl,
385 			     struct snd_ctl_elem_value *ucontrol)
386 {
387 	struct usb_mixer_elem_info *elem = kctl->private_data;
388 	struct usb_mixer_interface *mixer = elem->head.mixer;
389 	struct fcp_data *private = mixer->private_data;
390 	int num_meter_slots, resp_size;
391 	__le32 *resp = private->meter_levels;
392 	int i, err = 0;
393 
394 	struct {
395 		__le16 pad;
396 		__le16 num_meters;
397 		__le32 magic;
398 	} __packed req;
399 
400 	guard(mutex)(&private->mutex);
401 
402 	err = fcp_reinit(mixer);
403 	if (err < 0)
404 		return err;
405 
406 	num_meter_slots = private->num_meter_slots;
407 	resp_size = num_meter_slots * sizeof(u32);
408 
409 	req.pad = 0;
410 	req.num_meters = cpu_to_le16(num_meter_slots);
411 	req.magic = cpu_to_le32(FCP_USB_METER_LEVELS_GET_MAGIC);
412 	err = fcp_usb(mixer, FCP_USB_GET_METER,
413 		      &req, sizeof(req), resp, resp_size);
414 	if (err < 0)
415 		return err;
416 
417 	if (WARN_ON_ONCE(elem->channels > FCP_MAX_METER_MAP_SIZE))
418 		return -EINVAL;
419 
420 	/* copy & translate from resp[] using meter_level_map[] */
421 	for (i = 0; i < elem->channels; i++) {
422 		int idx = private->meter_level_map[i];
423 		int value = idx < 0 ? 0 : le32_to_cpu(resp[idx]);
424 
425 		ucontrol->value.integer.value[i] = value;
426 	}
427 
428 	return 0;
429 }
430 
431 static int fcp_meter_tlv_callback(struct snd_kcontrol *kctl,
432 				  int op_flag, unsigned int size,
433 				  unsigned int __user *tlv)
434 {
435 	struct usb_mixer_elem_info *elem = kctl->private_data;
436 	struct usb_mixer_interface *mixer = elem->head.mixer;
437 	struct fcp_data *private = mixer->private_data;
438 
439 	guard(mutex)(&private->mutex);
440 
441 	if (op_flag == SNDRV_CTL_TLV_OP_READ) {
442 		if (private->meter_labels_tlv_size == 0)
443 			return 0;
444 
445 		if (size > private->meter_labels_tlv_size)
446 			size = private->meter_labels_tlv_size;
447 
448 		if (copy_to_user(tlv, private->meter_labels_tlv, size))
449 			return -EFAULT;
450 
451 		return size;
452 	}
453 
454 	return -EINVAL;
455 }
456 
457 static const struct snd_kcontrol_new fcp_meter_ctl = {
458 	.iface  = SNDRV_CTL_ELEM_IFACE_PCM,
459 	.access = SNDRV_CTL_ELEM_ACCESS_READ |
460 		  SNDRV_CTL_ELEM_ACCESS_VOLATILE,
461 	.info = fcp_meter_ctl_info,
462 	.get  = fcp_meter_ctl_get,
463 	.tlv  = { .c = fcp_meter_tlv_callback },
464 };
465 
466 /*** hwdep interface ***/
467 
468 /* FCP initialisation */
469 static int fcp_ioctl_init(struct usb_mixer_interface *mixer,
470 			  struct fcp_init __user *arg)
471 {
472 	struct fcp_init init;
473 	struct usb_device *dev = mixer->chip->dev;
474 	struct fcp_data *private = mixer->private_data;
475 	void *step2_resp;
476 	int err, buf_size;
477 
478 	if (usb_pipe_type_check(dev, usb_sndctrlpipe(dev, 0)))
479 		return -EINVAL;
480 
481 	/* Get initialisation parameters */
482 	if (copy_from_user(&init, arg, sizeof(init)))
483 		return -EFAULT;
484 
485 	/* Validate the response sizes */
486 	if (init.step0_resp_size < 1 ||
487 	    init.step0_resp_size > 255 ||
488 	    init.step2_resp_size < 1 ||
489 	    init.step2_resp_size > 255)
490 		return -EINVAL;
491 
492 	/* Allocate response buffer */
493 	buf_size = init.step0_resp_size + init.step2_resp_size;
494 
495 	void *resp __free(kfree) =
496 		kmalloc(buf_size, GFP_KERNEL);
497 	if (!resp)
498 		return -ENOMEM;
499 
500 	private->step0_resp_size = init.step0_resp_size;
501 	private->step2_resp_size = init.step2_resp_size;
502 	private->init1_opcode = init.init1_opcode;
503 	private->init2_opcode = init.init2_opcode;
504 
505 	step2_resp = resp + private->step0_resp_size;
506 
507 	err = fcp_init(mixer, resp, step2_resp);
508 	if (err < 0)
509 		return err;
510 
511 	if (copy_to_user(arg->resp, resp, buf_size))
512 		return -EFAULT;
513 
514 	return 0;
515 }
516 
517 /* Check that the command is allowed
518  * Don't permit erasing/writing segment 0 (App_Gold)
519  */
520 static int fcp_validate_cmd(u32 opcode, void *data, u16 size)
521 {
522 	if (opcode == FCP_USB_FLASH_ERASE) {
523 		struct {
524 			__le32 segment_num;
525 			__le32 pad;
526 		} __packed *req = data;
527 
528 		if (size != sizeof(*req))
529 			return -EINVAL;
530 
531 		if (le32_to_cpu(req->segment_num) == FCP_SEGMENT_APP_GOLD)
532 			return -EPERM;
533 
534 		if (req->pad != 0)
535 			return -EINVAL;
536 
537 	} else if (opcode == FCP_USB_FLASH_WRITE) {
538 		struct {
539 			__le32 segment_num;
540 			__le32 offset;
541 			__le32 pad;
542 			u8 data[];
543 		} __packed *req = data;
544 
545 		if (size < sizeof(*req))
546 			return -EINVAL;
547 
548 		if (le32_to_cpu(req->segment_num) == FCP_SEGMENT_APP_GOLD)
549 			return -EPERM;
550 
551 		if (req->pad != 0)
552 			return -EINVAL;
553 	}
554 
555 	return 0;
556 }
557 
558 /* Execute an FCP command specified by the user */
559 static int fcp_ioctl_cmd(struct usb_mixer_interface *mixer,
560 			 struct fcp_cmd __user *arg)
561 {
562 	struct fcp_cmd cmd;
563 	int err, buf_size;
564 	void *data __free(kfree) = NULL;
565 
566 	/* get opcode and request/response size */
567 	if (copy_from_user(&cmd, arg, sizeof(cmd)))
568 		return -EFAULT;
569 
570 	/* validate request and response sizes */
571 	if (cmd.req_size > 4096 || cmd.resp_size > 4096)
572 		return -EINVAL;
573 
574 	/* reinit if needed */
575 	err = fcp_reinit(mixer);
576 	if (err < 0)
577 		return err;
578 
579 	/* allocate request/response buffer */
580 	buf_size = max(cmd.req_size, cmd.resp_size);
581 
582 	if (buf_size > 0) {
583 		data = kmalloc(buf_size, GFP_KERNEL);
584 		if (!data)
585 			return -ENOMEM;
586 	}
587 
588 	/* copy request from user */
589 	if (cmd.req_size > 0)
590 		if (copy_from_user(data, arg->data, cmd.req_size))
591 			return -EFAULT;
592 
593 	/* check that the command is allowed */
594 	err = fcp_validate_cmd(cmd.opcode, data, cmd.req_size);
595 	if (err < 0)
596 		return err;
597 
598 	/* send request, get response */
599 	err = fcp_usb(mixer, cmd.opcode,
600 		      data, cmd.req_size, data, cmd.resp_size);
601 	if (err < 0)
602 		return err;
603 
604 	/* copy response to user */
605 	if (cmd.resp_size > 0)
606 		if (copy_to_user(arg->data, data, cmd.resp_size))
607 			return -EFAULT;
608 
609 	return 0;
610 }
611 
612 /* Validate the Level Meter map passed by the user */
613 static int validate_meter_map(const s16 *map, int map_size, int meter_slots)
614 {
615 	int i;
616 
617 	for (i = 0; i < map_size; i++)
618 		if (map[i] < -1 || map[i] >= meter_slots)
619 			return -EINVAL;
620 
621 	return 0;
622 }
623 
624 /* Set the Level Meter map and add the control */
625 static int fcp_ioctl_set_meter_map(struct usb_mixer_interface *mixer,
626 				   struct fcp_meter_map __user *arg)
627 {
628 	struct fcp_meter_map map;
629 	struct fcp_data *private = mixer->private_data;
630 	int err;
631 
632 	if (copy_from_user(&map, arg, sizeof(map)))
633 		return -EFAULT;
634 
635 	/* Don't allow changing the map size or meter slots once set */
636 	if (private->meter_ctl) {
637 		struct usb_mixer_elem_info *elem =
638 			private->meter_ctl->private_data;
639 
640 		if (map.map_size != elem->channels ||
641 		    map.meter_slots != private->num_meter_slots)
642 			return -EINVAL;
643 	}
644 
645 	/* Validate the map size */
646 	if (map.map_size < 1 ||
647 	    map.map_size > FCP_MAX_METER_MAP_SIZE ||
648 	    map.meter_slots < 1 || map.meter_slots > 255)
649 		return -EINVAL;
650 
651 	/* Allocate and copy the map data */
652 	s16 *tmp_map __free(kfree) =
653 		memdup_array_user(arg->map, map.map_size, sizeof(s16));
654 	if (IS_ERR(tmp_map))
655 		return PTR_ERR(tmp_map);
656 
657 	err = validate_meter_map(tmp_map, map.map_size, map.meter_slots);
658 	if (err < 0)
659 		return err;
660 
661 	/* If the control doesn't exist, create it */
662 	if (!private->meter_ctl) {
663 		/* Allocate buffer for the map */
664 		s16 *new_map __free(kfree) =
665 			kmalloc_objs(s16, map.map_size);
666 		if (!new_map)
667 			return -ENOMEM;
668 
669 		/* Allocate buffer for reading meter levels */
670 		__le32 *meter_levels __free(kfree) =
671 			kmalloc_array(map.meter_slots, sizeof(__le32),
672 				      GFP_KERNEL);
673 		if (!meter_levels)
674 			return -ENOMEM;
675 
676 		/* Create the Level Meter control */
677 		err = fcp_add_new_ctl(mixer, &fcp_meter_ctl, 0, map.map_size,
678 				      "Level Meter", &private->meter_ctl);
679 		if (err < 0)
680 			return err;
681 
682 		/* Success; save the pointers in private and don't free them */
683 		private->meter_level_map = new_map;
684 		private->meter_levels = meter_levels;
685 		private->num_meter_slots = map.meter_slots;
686 		new_map = NULL;
687 		meter_levels = NULL;
688 	}
689 
690 	/* Install the new map */
691 	memcpy(private->meter_level_map, tmp_map, map.map_size * sizeof(s16));
692 
693 	return 0;
694 }
695 
696 /* Set the Level Meter labels */
697 static int fcp_ioctl_set_meter_labels(struct usb_mixer_interface *mixer,
698 				      struct fcp_meter_labels __user *arg)
699 {
700 	struct fcp_meter_labels labels;
701 	struct fcp_data *private = mixer->private_data;
702 	unsigned int *tlv_data;
703 	unsigned int tlv_size, data_size;
704 
705 	if (copy_from_user(&labels, arg, sizeof(labels)))
706 		return -EFAULT;
707 
708 	/* Remove existing labels if size is zero */
709 	if (!labels.labels_size) {
710 
711 		/* Clear TLV read/callback bits if labels were present */
712 		if (private->meter_labels_tlv) {
713 			private->meter_ctl->vd[0].access &=
714 				~(SNDRV_CTL_ELEM_ACCESS_TLV_READ |
715 				  SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK);
716 			snd_ctl_notify(mixer->chip->card,
717 				       SNDRV_CTL_EVENT_MASK_INFO,
718 				       &private->meter_ctl->id);
719 		}
720 
721 		kfree(private->meter_labels_tlv);
722 		private->meter_labels_tlv = NULL;
723 		private->meter_labels_tlv_size = 0;
724 
725 		return 0;
726 	}
727 
728 	/* Validate size */
729 	if (labels.labels_size > 4096)
730 		return -EINVAL;
731 
732 	/* Calculate padded data size */
733 	data_size = ALIGN(labels.labels_size, sizeof(unsigned int));
734 
735 	/* Calculate total TLV size including header */
736 	tlv_size = sizeof(unsigned int) * 2 + data_size;
737 
738 	/* Allocate, set up TLV header, and copy the labels data */
739 	tlv_data = kzalloc(tlv_size, GFP_KERNEL);
740 	if (!tlv_data)
741 		return -ENOMEM;
742 	tlv_data[0] = SNDRV_CTL_TLVT_FCP_CHANNEL_LABELS;
743 	tlv_data[1] = data_size;
744 	if (copy_from_user(&tlv_data[2], arg->labels, labels.labels_size)) {
745 		kfree(tlv_data);
746 		return -EFAULT;
747 	}
748 
749 	/* Set TLV read/callback bits if labels weren't present */
750 	if (!private->meter_labels_tlv) {
751 		private->meter_ctl->vd[0].access |=
752 			SNDRV_CTL_ELEM_ACCESS_TLV_READ |
753 			SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
754 		snd_ctl_notify(mixer->chip->card,
755 			       SNDRV_CTL_EVENT_MASK_INFO,
756 			       &private->meter_ctl->id);
757 	}
758 
759 	/* Swap in the new labels */
760 	kfree(private->meter_labels_tlv);
761 	private->meter_labels_tlv = tlv_data;
762 	private->meter_labels_tlv_size = tlv_size;
763 
764 	return 0;
765 }
766 
767 static int fcp_hwdep_open(struct snd_hwdep *hw, struct file *file)
768 {
769 	struct usb_mixer_interface *mixer = hw->private_data;
770 	struct fcp_data *private = mixer->private_data;
771 
772 	if (!capable(CAP_SYS_RAWIO))
773 		return -EPERM;
774 
775 	private->file = file;
776 
777 	return 0;
778 }
779 
780 static int fcp_hwdep_ioctl(struct snd_hwdep *hw, struct file *file,
781 			   unsigned int cmd, unsigned long arg)
782 {
783 	struct usb_mixer_interface *mixer = hw->private_data;
784 	struct fcp_data *private = mixer->private_data;
785 	void __user *argp = (void __user *)arg;
786 
787 	guard(mutex)(&private->mutex);
788 
789 	switch (cmd) {
790 
791 	case FCP_IOCTL_PVERSION:
792 		return put_user(FCP_HWDEP_VERSION,
793 				(int __user *)argp) ? -EFAULT : 0;
794 		break;
795 
796 	case FCP_IOCTL_INIT:
797 		return fcp_ioctl_init(mixer, argp);
798 
799 	case FCP_IOCTL_CMD:
800 		if (!private->init)
801 			return -EINVAL;
802 		return fcp_ioctl_cmd(mixer, argp);
803 
804 	case FCP_IOCTL_SET_METER_MAP:
805 		if (!private->init)
806 			return -EINVAL;
807 		return fcp_ioctl_set_meter_map(mixer, argp);
808 
809 	case FCP_IOCTL_SET_METER_LABELS:
810 		if (!private->init)
811 			return -EINVAL;
812 		if (!private->meter_ctl)
813 			return -EINVAL;
814 		return fcp_ioctl_set_meter_labels(mixer, argp);
815 
816 	default:
817 		return -ENOIOCTLCMD;
818 	}
819 
820 	/* not reached */
821 }
822 
823 static long fcp_hwdep_read(struct snd_hwdep *hw, char __user *buf,
824 			   long count, loff_t *offset)
825 {
826 	struct usb_mixer_interface *mixer = hw->private_data;
827 	struct fcp_data *private = mixer->private_data;
828 	long ret = 0;
829 	u32 event;
830 
831 	if (count < sizeof(event))
832 		return -EINVAL;
833 
834 	ret = wait_event_interruptible(private->notify.queue,
835 				       private->notify.event);
836 	if (ret)
837 		return ret;
838 
839 	scoped_guard(spinlock_irqsave, &private->notify.lock) {
840 		event = private->notify.event;
841 		private->notify.event = 0;
842 	}
843 
844 	if (copy_to_user(buf, &event, sizeof(event)))
845 		return -EFAULT;
846 
847 	return sizeof(event);
848 }
849 
850 static __poll_t fcp_hwdep_poll(struct snd_hwdep *hw,
851 			       struct file *file,
852 			       poll_table *wait)
853 {
854 	struct usb_mixer_interface *mixer = hw->private_data;
855 	struct fcp_data *private = mixer->private_data;
856 	__poll_t mask = 0;
857 
858 	poll_wait(file, &private->notify.queue, wait);
859 
860 	if (private->notify.event)
861 		mask |= EPOLLIN | EPOLLRDNORM;
862 
863 	return mask;
864 }
865 
866 static int fcp_hwdep_release(struct snd_hwdep *hw, struct file *file)
867 {
868 	struct usb_mixer_interface *mixer = hw->private_data;
869 	struct fcp_data *private = mixer->private_data;
870 
871 	if (!private)
872 		return 0;
873 
874 	private->file = NULL;
875 
876 	return 0;
877 }
878 
879 static int fcp_hwdep_init(struct usb_mixer_interface *mixer)
880 {
881 	struct snd_hwdep *hw;
882 	int err;
883 
884 	err = snd_hwdep_new(mixer->chip->card, "Focusrite Control", 0, &hw);
885 	if (err < 0)
886 		return err;
887 
888 	hw->private_data = mixer;
889 	hw->exclusive = 1;
890 	hw->ops.open = fcp_hwdep_open;
891 	hw->ops.ioctl = fcp_hwdep_ioctl;
892 	hw->ops.ioctl_compat = fcp_hwdep_ioctl;
893 	hw->ops.read = fcp_hwdep_read;
894 	hw->ops.poll = fcp_hwdep_poll;
895 	hw->ops.release = fcp_hwdep_release;
896 
897 	return 0;
898 }
899 
900 /*** Cleanup ***/
901 
902 static void fcp_cleanup_urb(struct usb_mixer_interface *mixer)
903 {
904 	if (!mixer->urb)
905 		return;
906 
907 	usb_kill_urb(mixer->urb);
908 	kfree(mixer->urb->transfer_buffer);
909 	usb_free_urb(mixer->urb);
910 	mixer->urb = NULL;
911 }
912 
913 static void fcp_private_free(struct usb_mixer_interface *mixer)
914 {
915 	struct fcp_data *private = mixer->private_data;
916 
917 	fcp_cleanup_urb(mixer);
918 
919 	kfree(private->meter_level_map);
920 	kfree(private->meter_levels);
921 	kfree(private->meter_labels_tlv);
922 	kfree(private);
923 	mixer->private_data = NULL;
924 }
925 
926 static void fcp_private_suspend(struct usb_mixer_interface *mixer)
927 {
928 	fcp_cleanup_urb(mixer);
929 }
930 
931 /*** Callbacks ***/
932 
933 static void fcp_notify(struct urb *urb)
934 {
935 	struct usb_mixer_interface *mixer = urb->context;
936 	struct fcp_data *private = mixer->private_data;
937 	int len = urb->actual_length;
938 	int ustatus = urb->status;
939 	u32 data;
940 
941 	if (ustatus != 0 || len != 8)
942 		goto requeue;
943 
944 	data = le32_to_cpu(*(__le32 *)urb->transfer_buffer);
945 
946 	/* Handle command acknowledgement */
947 	if (data & FCP_NOTIFY_ACK) {
948 		complete(&private->cmd_done);
949 		data &= ~FCP_NOTIFY_ACK;
950 	}
951 
952 	if (data) {
953 		scoped_guard(spinlock_irqsave, &private->notify.lock) {
954 			private->notify.event |= data;
955 		}
956 
957 		wake_up_interruptible(&private->notify.queue);
958 	}
959 
960 requeue:
961 	if (ustatus != -ENOENT &&
962 	    ustatus != -ECONNRESET &&
963 	    ustatus != -ESHUTDOWN) {
964 		urb->dev = mixer->chip->dev;
965 		usb_submit_urb(urb, GFP_ATOMIC);
966 	} else {
967 		complete(&private->cmd_done);
968 	}
969 }
970 
971 /* Submit a URB to receive notifications from the device */
972 static int fcp_init_notify(struct usb_mixer_interface *mixer)
973 {
974 	struct usb_device *dev = mixer->chip->dev;
975 	struct fcp_data *private = mixer->private_data;
976 	unsigned int pipe = usb_rcvintpipe(dev, private->bEndpointAddress);
977 	void *transfer_buffer;
978 	int err;
979 
980 	/* Already set up */
981 	if (mixer->urb)
982 		return 0;
983 
984 	if (usb_pipe_type_check(dev, pipe))
985 		return -EINVAL;
986 
987 	mixer->urb = usb_alloc_urb(0, GFP_KERNEL);
988 	if (!mixer->urb)
989 		return -ENOMEM;
990 
991 	transfer_buffer = kmalloc(private->wMaxPacketSize, GFP_KERNEL);
992 	if (!transfer_buffer) {
993 		usb_free_urb(mixer->urb);
994 		mixer->urb = NULL;
995 		return -ENOMEM;
996 	}
997 
998 	usb_fill_int_urb(mixer->urb, dev, pipe,
999 			 transfer_buffer, private->wMaxPacketSize,
1000 			 fcp_notify, mixer, private->bInterval);
1001 
1002 	init_completion(&private->cmd_done);
1003 
1004 	err = usb_submit_urb(mixer->urb, GFP_KERNEL);
1005 	if (err) {
1006 		usb_audio_err(mixer->chip,
1007 			      "%s: usb_submit_urb failed: %d\n",
1008 			      __func__, err);
1009 		kfree(transfer_buffer);
1010 		usb_free_urb(mixer->urb);
1011 		mixer->urb = NULL;
1012 	}
1013 
1014 	return err;
1015 }
1016 
1017 /*** Initialisation ***/
1018 
1019 static int fcp_init(struct usb_mixer_interface *mixer,
1020 		    void *step0_resp, void *step2_resp)
1021 {
1022 	struct fcp_data *private = mixer->private_data;
1023 	struct usb_device *dev = mixer->chip->dev;
1024 	int err;
1025 
1026 	err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0),
1027 		FCP_USB_REQ_STEP0,
1028 		USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
1029 		0, private->bInterfaceNumber,
1030 		step0_resp, private->step0_resp_size);
1031 	if (err < 0)
1032 		return err;
1033 
1034 	err = fcp_init_notify(mixer);
1035 	if (err < 0)
1036 		return err;
1037 
1038 	private->seq = 0;
1039 	private->init = 1;
1040 
1041 	err = fcp_usb(mixer, private->init1_opcode, NULL, 0, NULL, 0);
1042 	if (err < 0)
1043 		return err;
1044 
1045 	err = fcp_usb(mixer, private->init2_opcode,
1046 		      NULL, 0, step2_resp, private->step2_resp_size);
1047 	if (err < 0)
1048 		return err;
1049 
1050 	return 0;
1051 }
1052 
1053 static int fcp_init_private(struct usb_mixer_interface *mixer)
1054 {
1055 	struct fcp_data *private =
1056 		kzalloc_obj(struct fcp_data);
1057 
1058 	if (!private)
1059 		return -ENOMEM;
1060 
1061 	mutex_init(&private->mutex);
1062 	init_waitqueue_head(&private->notify.queue);
1063 	spin_lock_init(&private->notify.lock);
1064 
1065 	mixer->private_data = private;
1066 	mixer->private_free = fcp_private_free;
1067 	mixer->private_suspend = fcp_private_suspend;
1068 
1069 	private->mixer = mixer;
1070 
1071 	return 0;
1072 }
1073 
1074 /* Look through the interface descriptors for the Focusrite Control
1075  * interface (bInterfaceClass = 255 Vendor Specific Class) and set
1076  * bInterfaceNumber, bEndpointAddress, wMaxPacketSize, and bInterval
1077  * in private
1078  */
1079 static int fcp_find_fc_interface(struct usb_mixer_interface *mixer)
1080 {
1081 	struct snd_usb_audio *chip = mixer->chip;
1082 	struct fcp_data *private = mixer->private_data;
1083 	struct usb_host_config *config = chip->dev->actconfig;
1084 	int i;
1085 
1086 	for (i = 0; i < config->desc.bNumInterfaces; i++) {
1087 		struct usb_interface *intf = config->interface[i];
1088 		struct usb_interface_descriptor *desc =
1089 			&intf->altsetting[0].desc;
1090 		struct usb_endpoint_descriptor *epd;
1091 
1092 		if (desc->bInterfaceClass != 255)
1093 			continue;
1094 		if (desc->bNumEndpoints < 1)
1095 			continue;
1096 
1097 		epd = get_endpoint(intf->altsetting, 0);
1098 		private->bInterfaceNumber = desc->bInterfaceNumber;
1099 		private->bEndpointAddress = usb_endpoint_num(epd);
1100 		private->wMaxPacketSize = le16_to_cpu(epd->wMaxPacketSize);
1101 		private->bInterval = epd->bInterval;
1102 		return 0;
1103 	}
1104 
1105 	usb_audio_err(chip, "Focusrite vendor-specific interface not found\n");
1106 	return -EINVAL;
1107 }
1108 
1109 int snd_fcp_init(struct usb_mixer_interface *mixer)
1110 {
1111 	struct snd_usb_audio *chip = mixer->chip;
1112 	int err;
1113 
1114 	/* only use UAC_VERSION_2 */
1115 	if (!mixer->protocol)
1116 		return 0;
1117 
1118 	err = fcp_init_private(mixer);
1119 	if (err < 0)
1120 		return err;
1121 
1122 	err = fcp_find_fc_interface(mixer);
1123 	if (err < 0)
1124 		return err;
1125 
1126 	err = fcp_hwdep_init(mixer);
1127 	if (err < 0)
1128 		return err;
1129 
1130 	usb_audio_info(chip,
1131 		"Focusrite Control Protocol Driver ready (pid=0x%04x); "
1132 		"report any issues to "
1133 		"https://github.com/geoffreybennett/fcp-support/issues",
1134 		USB_ID_PRODUCT(chip->usb_id));
1135 
1136 	return err;
1137 }
1138