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