xref: /linux/drivers/input/misc/ims-pcu.c (revision d4579af29e67ca8722db0a1194227f8015c8981d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Driver for IMS Passenger Control Unit Devices
4  *
5  * Copyright (C) 2013 The IMS Company
6  */
7 
8 #include <linux/completion.h>
9 #include <linux/device.h>
10 #include <linux/firmware.h>
11 #include <linux/ihex.h>
12 #include <linux/input.h>
13 #include <linux/kernel.h>
14 #include <linux/leds.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/sysfs.h>
18 #include <linux/types.h>
19 #include <linux/usb/input.h>
20 #include <linux/usb/cdc.h>
21 #include <linux/unaligned.h>
22 
23 #define IMS_PCU_KEYMAP_LEN		32
24 
25 struct ims_pcu_buttons {
26 	struct input_dev *input;
27 	char name[32];
28 	char phys[32];
29 	unsigned short keymap[IMS_PCU_KEYMAP_LEN];
30 };
31 
32 struct ims_pcu_gamepad {
33 	struct input_dev *input;
34 	char name[32];
35 	char phys[32];
36 };
37 
38 struct ims_pcu_backlight {
39 	struct led_classdev cdev;
40 	char name[32];
41 };
42 
43 #define IMS_PCU_PART_NUMBER_LEN		15
44 #define IMS_PCU_SERIAL_NUMBER_LEN	8
45 #define IMS_PCU_DOM_LEN			8
46 #define IMS_PCU_FW_VERSION_LEN		16
47 #define IMS_PCU_BL_VERSION_LEN		16
48 #define IMS_PCU_BL_RESET_REASON_LEN	(2 + 1)
49 
50 #define IMS_PCU_PCU_B_DEVICE_ID		5
51 
52 #define IMS_PCU_BUF_SIZE		128
53 
54 struct ims_pcu {
55 	struct usb_device *udev;
56 	struct device *dev; /* control interface's device, used for logging */
57 
58 	unsigned int device_no;
59 
60 	bool bootloader_mode;
61 
62 	char part_number[IMS_PCU_PART_NUMBER_LEN];
63 	char serial_number[IMS_PCU_SERIAL_NUMBER_LEN];
64 	char date_of_manufacturing[IMS_PCU_DOM_LEN];
65 	char fw_version[IMS_PCU_FW_VERSION_LEN];
66 	char bl_version[IMS_PCU_BL_VERSION_LEN];
67 	char reset_reason[IMS_PCU_BL_RESET_REASON_LEN];
68 	int update_firmware_status;
69 	u8 device_id;
70 
71 	u8 ofn_reg_addr;
72 
73 	struct usb_interface *ctrl_intf;
74 
75 	struct usb_endpoint_descriptor *ep_ctrl;
76 	struct urb *urb_ctrl;
77 	u8 *urb_ctrl_buf;
78 	dma_addr_t ctrl_dma;
79 	size_t max_ctrl_size;
80 
81 	struct usb_interface *data_intf;
82 
83 	struct usb_endpoint_descriptor *ep_in;
84 	struct urb *urb_in;
85 	u8 *urb_in_buf;
86 	dma_addr_t read_dma;
87 	size_t max_in_size;
88 
89 	struct usb_endpoint_descriptor *ep_out;
90 	u8 *urb_out_buf;
91 	size_t max_out_size;
92 
93 	u8 read_buf[IMS_PCU_BUF_SIZE];
94 	u8 read_pos;
95 	u8 check_sum;
96 	bool have_stx;
97 	bool have_dle;
98 
99 	u8 cmd_buf[IMS_PCU_BUF_SIZE];
100 	u8 ack_id;
101 	u8 expected_response;
102 	u8 cmd_buf_len;
103 	struct completion cmd_done;
104 	struct mutex cmd_mutex;
105 
106 	u32 fw_start_addr;
107 	u32 fw_end_addr;
108 	struct completion async_firmware_done;
109 
110 	struct ims_pcu_buttons buttons;
111 	struct ims_pcu_gamepad *gamepad;
112 	struct ims_pcu_backlight backlight;
113 
114 	bool setup_complete; /* Input and LED devices have been created */
115 };
116 
117 
118 /*********************************************************************
119  *             Buttons Input device support                          *
120  *********************************************************************/
121 
122 static const unsigned short ims_pcu_keymap_1[] = {
123 	[1] = KEY_ATTENDANT_OFF,
124 	[2] = KEY_ATTENDANT_ON,
125 	[3] = KEY_LIGHTS_TOGGLE,
126 	[4] = KEY_VOLUMEUP,
127 	[5] = KEY_VOLUMEDOWN,
128 	[6] = KEY_INFO,
129 };
130 
131 static const unsigned short ims_pcu_keymap_2[] = {
132 	[4] = KEY_VOLUMEUP,
133 	[5] = KEY_VOLUMEDOWN,
134 	[6] = KEY_INFO,
135 };
136 
137 static const unsigned short ims_pcu_keymap_3[] = {
138 	[1] = KEY_HOMEPAGE,
139 	[2] = KEY_ATTENDANT_TOGGLE,
140 	[3] = KEY_LIGHTS_TOGGLE,
141 	[4] = KEY_VOLUMEUP,
142 	[5] = KEY_VOLUMEDOWN,
143 	[6] = KEY_DISPLAYTOGGLE,
144 	[18] = KEY_PLAYPAUSE,
145 };
146 
147 static const unsigned short ims_pcu_keymap_4[] = {
148 	[1] = KEY_ATTENDANT_OFF,
149 	[2] = KEY_ATTENDANT_ON,
150 	[3] = KEY_LIGHTS_TOGGLE,
151 	[4] = KEY_VOLUMEUP,
152 	[5] = KEY_VOLUMEDOWN,
153 	[6] = KEY_INFO,
154 	[18] = KEY_PLAYPAUSE,
155 };
156 
157 static const unsigned short ims_pcu_keymap_5[] = {
158 	[1] = KEY_ATTENDANT_OFF,
159 	[2] = KEY_ATTENDANT_ON,
160 	[3] = KEY_LIGHTS_TOGGLE,
161 };
162 
163 struct ims_pcu_device_info {
164 	const unsigned short *keymap;
165 	size_t keymap_len;
166 	bool has_gamepad;
167 };
168 
169 #define IMS_PCU_DEVINFO(_n, _gamepad)				\
170 	[_n] = {						\
171 		.keymap = ims_pcu_keymap_##_n,			\
172 		.keymap_len = ARRAY_SIZE(ims_pcu_keymap_##_n),	\
173 		.has_gamepad = _gamepad,			\
174 	}
175 
176 static const struct ims_pcu_device_info ims_pcu_device_info[] = {
177 	IMS_PCU_DEVINFO(1, true),
178 	IMS_PCU_DEVINFO(2, true),
179 	IMS_PCU_DEVINFO(3, true),
180 	IMS_PCU_DEVINFO(4, true),
181 	IMS_PCU_DEVINFO(5, false),
182 };
183 
184 static void ims_pcu_buttons_report(struct ims_pcu *pcu, u32 data)
185 {
186 	struct ims_pcu_buttons *buttons = &pcu->buttons;
187 	struct input_dev *input = buttons->input;
188 	int i;
189 
190 	for (i = 0; i < 32; i++) {
191 		unsigned short keycode = buttons->keymap[i];
192 
193 		if (keycode != KEY_RESERVED)
194 			input_report_key(input, keycode, data & (1UL << i));
195 	}
196 
197 	input_sync(input);
198 }
199 
200 static int ims_pcu_setup_buttons(struct ims_pcu *pcu,
201 				 const unsigned short *keymap,
202 				 size_t keymap_len)
203 {
204 	struct ims_pcu_buttons *buttons = &pcu->buttons;
205 	struct input_dev *input;
206 	int i;
207 	int error;
208 
209 	input = input_allocate_device();
210 	if (!input) {
211 		dev_err(pcu->dev, "Not enough memory for input device\n");
212 		return -ENOMEM;
213 	}
214 
215 	snprintf(buttons->name, sizeof(buttons->name),
216 		 "IMS PCU#%d Button Interface", pcu->device_no);
217 
218 	usb_make_path(pcu->udev, buttons->phys, sizeof(buttons->phys));
219 	strlcat(buttons->phys, "/input0", sizeof(buttons->phys));
220 
221 	memcpy(buttons->keymap, keymap, sizeof(*keymap) * keymap_len);
222 
223 	input->name = buttons->name;
224 	input->phys = buttons->phys;
225 	usb_to_input_id(pcu->udev, &input->id);
226 	input->dev.parent = &pcu->ctrl_intf->dev;
227 
228 	input->keycode = buttons->keymap;
229 	input->keycodemax = ARRAY_SIZE(buttons->keymap);
230 	input->keycodesize = sizeof(buttons->keymap[0]);
231 
232 	__set_bit(EV_KEY, input->evbit);
233 	for (i = 0; i < IMS_PCU_KEYMAP_LEN; i++)
234 		__set_bit(buttons->keymap[i], input->keybit);
235 	__clear_bit(KEY_RESERVED, input->keybit);
236 
237 	error = input_register_device(input);
238 	if (error) {
239 		dev_err(pcu->dev,
240 			"Failed to register buttons input device: %d\n",
241 			error);
242 		input_free_device(input);
243 		return error;
244 	}
245 
246 	buttons->input = input;
247 	return 0;
248 }
249 
250 static void ims_pcu_destroy_buttons(struct ims_pcu *pcu)
251 {
252 	struct ims_pcu_buttons *buttons = &pcu->buttons;
253 
254 	input_unregister_device(buttons->input);
255 }
256 
257 
258 /*********************************************************************
259  *             Gamepad Input device support                          *
260  *********************************************************************/
261 
262 static void ims_pcu_gamepad_report(struct ims_pcu *pcu, u32 data)
263 {
264 	struct ims_pcu_gamepad *gamepad = pcu->gamepad;
265 	struct input_dev *input = gamepad->input;
266 	int x, y;
267 
268 	x = !!(data & (1 << 14)) - !!(data & (1 << 13));
269 	y = !!(data & (1 << 12)) - !!(data & (1 << 11));
270 
271 	input_report_abs(input, ABS_X, x);
272 	input_report_abs(input, ABS_Y, y);
273 
274 	input_report_key(input, BTN_A, data & (1 << 7));
275 	input_report_key(input, BTN_B, data & (1 << 8));
276 	input_report_key(input, BTN_X, data & (1 << 9));
277 	input_report_key(input, BTN_Y, data & (1 << 10));
278 	input_report_key(input, BTN_START, data & (1 << 15));
279 	input_report_key(input, BTN_SELECT, data & (1 << 16));
280 
281 	input_sync(input);
282 }
283 
284 static int ims_pcu_setup_gamepad(struct ims_pcu *pcu)
285 {
286 	struct ims_pcu_gamepad *gamepad;
287 	struct input_dev *input;
288 	int error;
289 
290 	gamepad = kzalloc_obj(*gamepad);
291 	input = input_allocate_device();
292 	if (!gamepad || !input) {
293 		dev_err(pcu->dev,
294 			"Not enough memory for gamepad device\n");
295 		error = -ENOMEM;
296 		goto err_free_mem;
297 	}
298 
299 	gamepad->input = input;
300 
301 	snprintf(gamepad->name, sizeof(gamepad->name),
302 		 "IMS PCU#%d Gamepad Interface", pcu->device_no);
303 
304 	usb_make_path(pcu->udev, gamepad->phys, sizeof(gamepad->phys));
305 	strlcat(gamepad->phys, "/input1", sizeof(gamepad->phys));
306 
307 	input->name = gamepad->name;
308 	input->phys = gamepad->phys;
309 	usb_to_input_id(pcu->udev, &input->id);
310 	input->dev.parent = &pcu->ctrl_intf->dev;
311 
312 	__set_bit(EV_KEY, input->evbit);
313 	__set_bit(BTN_A, input->keybit);
314 	__set_bit(BTN_B, input->keybit);
315 	__set_bit(BTN_X, input->keybit);
316 	__set_bit(BTN_Y, input->keybit);
317 	__set_bit(BTN_START, input->keybit);
318 	__set_bit(BTN_SELECT, input->keybit);
319 
320 	__set_bit(EV_ABS, input->evbit);
321 	input_set_abs_params(input, ABS_X, -1, 1, 0, 0);
322 	input_set_abs_params(input, ABS_Y, -1, 1, 0, 0);
323 
324 	error = input_register_device(input);
325 	if (error) {
326 		dev_err(pcu->dev,
327 			"Failed to register gamepad input device: %d\n",
328 			error);
329 		goto err_free_mem;
330 	}
331 
332 	pcu->gamepad = gamepad;
333 	return 0;
334 
335 err_free_mem:
336 	input_free_device(input);
337 	kfree(gamepad);
338 	return error;
339 }
340 
341 static void ims_pcu_destroy_gamepad(struct ims_pcu *pcu)
342 {
343 	struct ims_pcu_gamepad *gamepad = pcu->gamepad;
344 
345 	input_unregister_device(gamepad->input);
346 	kfree(gamepad);
347 }
348 
349 
350 /*********************************************************************
351  *             PCU Communication protocol handling                   *
352  *********************************************************************/
353 
354 #define IMS_PCU_PROTOCOL_STX		0x02
355 #define IMS_PCU_PROTOCOL_ETX		0x03
356 #define IMS_PCU_PROTOCOL_DLE		0x10
357 
358 /* PCU commands */
359 #define IMS_PCU_CMD_STATUS		0xa0
360 #define IMS_PCU_CMD_PCU_RESET		0xa1
361 #define IMS_PCU_CMD_RESET_REASON	0xa2
362 #define IMS_PCU_CMD_SEND_BUTTONS	0xa3
363 #define IMS_PCU_CMD_JUMP_TO_BTLDR	0xa4
364 #define IMS_PCU_CMD_GET_INFO		0xa5
365 #define IMS_PCU_CMD_SET_BRIGHTNESS	0xa6
366 #define IMS_PCU_CMD_EEPROM		0xa7
367 #define IMS_PCU_CMD_GET_FW_VERSION	0xa8
368 #define IMS_PCU_CMD_GET_BL_VERSION	0xa9
369 #define IMS_PCU_CMD_SET_INFO		0xab
370 #define IMS_PCU_CMD_GET_BRIGHTNESS	0xac
371 #define IMS_PCU_CMD_GET_DEVICE_ID	0xae
372 #define IMS_PCU_CMD_SPECIAL_INFO	0xb0
373 #define IMS_PCU_CMD_BOOTLOADER		0xb1	/* Pass data to bootloader */
374 #define IMS_PCU_CMD_OFN_SET_CONFIG	0xb3
375 #define IMS_PCU_CMD_OFN_GET_CONFIG	0xb4
376 
377 /* PCU responses */
378 #define IMS_PCU_RSP_STATUS		0xc0
379 #define IMS_PCU_RSP_PCU_RESET		0	/* Originally 0xc1 */
380 #define IMS_PCU_RSP_RESET_REASON	0xc2
381 #define IMS_PCU_RSP_SEND_BUTTONS	0xc3
382 #define IMS_PCU_RSP_JUMP_TO_BTLDR	0	/* Originally 0xc4 */
383 #define IMS_PCU_RSP_GET_INFO		0xc5
384 #define IMS_PCU_RSP_SET_BRIGHTNESS	0xc6
385 #define IMS_PCU_RSP_EEPROM		0xc7
386 #define IMS_PCU_RSP_GET_FW_VERSION	0xc8
387 #define IMS_PCU_RSP_GET_BL_VERSION	0xc9
388 #define IMS_PCU_RSP_SET_INFO		0xcb
389 #define IMS_PCU_RSP_GET_BRIGHTNESS	0xcc
390 #define IMS_PCU_RSP_CMD_INVALID		0xcd
391 #define IMS_PCU_RSP_GET_DEVICE_ID	0xce
392 #define IMS_PCU_RSP_SPECIAL_INFO	0xd0
393 #define IMS_PCU_RSP_BOOTLOADER		0xd1	/* Bootloader response */
394 #define IMS_PCU_RSP_OFN_SET_CONFIG	0xd2
395 #define IMS_PCU_RSP_OFN_GET_CONFIG	0xd3
396 
397 
398 #define IMS_PCU_RSP_EVNT_BUTTONS	0xe0	/* Unsolicited, button state */
399 #define IMS_PCU_GAMEPAD_MASK		0x0001ff80UL	/* Bits 7 through 16 */
400 
401 
402 #define IMS_PCU_MIN_PACKET_LEN		3
403 #define IMS_PCU_DATA_OFFSET		2
404 
405 #define IMS_PCU_CMD_WRITE_TIMEOUT	100 /* msec */
406 #define IMS_PCU_CMD_RESPONSE_TIMEOUT	500 /* msec */
407 
408 static void ims_pcu_report_events(struct ims_pcu *pcu)
409 {
410 	u32 data;
411 
412 	/* 6-axis setting (1 byte) + button data + checksum */
413 	if (pcu->read_pos < IMS_PCU_DATA_OFFSET + 1 + sizeof(data) + 1) {
414 		dev_warn(pcu->dev, "Short buttons report: %d bytes\n",
415 			 pcu->read_pos);
416 		return;
417 	}
418 
419 	data = get_unaligned_be32(&pcu->read_buf[IMS_PCU_DATA_OFFSET + 1]);
420 
421 	ims_pcu_buttons_report(pcu, data & ~IMS_PCU_GAMEPAD_MASK);
422 	if (pcu->gamepad)
423 		ims_pcu_gamepad_report(pcu, data);
424 }
425 
426 static void ims_pcu_handle_response(struct ims_pcu *pcu)
427 {
428 	switch (pcu->read_buf[0]) {
429 	case IMS_PCU_RSP_EVNT_BUTTONS:
430 		if (likely(pcu->setup_complete))
431 			ims_pcu_report_events(pcu);
432 		break;
433 
434 	default:
435 		/*
436 		 * See if we got command completion.
437 		 * If both the sequence and response code match save
438 		 * the data and signal completion.
439 		 */
440 		if (pcu->read_buf[0] == pcu->expected_response &&
441 		    pcu->read_buf[1] == pcu->ack_id - 1) {
442 
443 			memcpy(pcu->cmd_buf, pcu->read_buf, pcu->read_pos);
444 			pcu->cmd_buf_len = pcu->read_pos;
445 			complete(&pcu->cmd_done);
446 		}
447 		break;
448 	}
449 }
450 
451 static void ims_pcu_reset_packet(struct ims_pcu *pcu)
452 {
453 	pcu->have_stx = false;
454 	pcu->have_dle = false;
455 	pcu->read_pos = 0;
456 	pcu->check_sum = 0;
457 }
458 
459 static void ims_pcu_process_data(struct ims_pcu *pcu, struct urb *urb)
460 {
461 	int i;
462 
463 	for (i = 0; i < urb->actual_length; i++) {
464 		u8 data = pcu->urb_in_buf[i];
465 
466 		/* Skip everything until we get Start Xmit */
467 		if (!pcu->have_stx && data != IMS_PCU_PROTOCOL_STX)
468 			continue;
469 
470 		if (pcu->have_dle) {
471 			if (pcu->read_pos >= IMS_PCU_BUF_SIZE) {
472 				dev_warn(pcu->dev,
473 					 "Packet too long (%d bytes), discarding\n",
474 					 pcu->read_pos);
475 				ims_pcu_reset_packet(pcu);
476 				continue;
477 			}
478 
479 			pcu->have_dle = false;
480 			pcu->read_buf[pcu->read_pos++] = data;
481 			pcu->check_sum += data;
482 			continue;
483 		}
484 
485 		switch (data) {
486 		case IMS_PCU_PROTOCOL_STX:
487 			if (pcu->have_stx)
488 				dev_warn(pcu->dev,
489 					 "Unexpected STX at byte %d, discarding old data\n",
490 					 pcu->read_pos);
491 			ims_pcu_reset_packet(pcu);
492 			pcu->have_stx = true;
493 			break;
494 
495 		case IMS_PCU_PROTOCOL_DLE:
496 			pcu->have_dle = true;
497 			break;
498 
499 		case IMS_PCU_PROTOCOL_ETX:
500 			if (pcu->read_pos < IMS_PCU_MIN_PACKET_LEN) {
501 				dev_warn(pcu->dev,
502 					 "Short packet received (%d bytes), ignoring\n",
503 					 pcu->read_pos);
504 			} else if (pcu->check_sum != 0) {
505 				dev_warn(pcu->dev,
506 					 "Invalid checksum in packet (%d bytes), ignoring\n",
507 					 pcu->read_pos);
508 			} else {
509 				ims_pcu_handle_response(pcu);
510 			}
511 
512 			ims_pcu_reset_packet(pcu);
513 			break;
514 
515 		default:
516 			if (pcu->read_pos >= IMS_PCU_BUF_SIZE) {
517 				dev_warn(pcu->dev,
518 					 "Packet too long (%d bytes), discarding\n",
519 					 pcu->read_pos);
520 				ims_pcu_reset_packet(pcu);
521 				continue;
522 			}
523 
524 			pcu->read_buf[pcu->read_pos++] = data;
525 			pcu->check_sum += data;
526 			break;
527 		}
528 	}
529 }
530 
531 static bool ims_pcu_byte_needs_escape(u8 byte)
532 {
533 	return byte == IMS_PCU_PROTOCOL_STX ||
534 	       byte == IMS_PCU_PROTOCOL_ETX ||
535 	       byte == IMS_PCU_PROTOCOL_DLE;
536 }
537 
538 static int ims_pcu_send_cmd_chunk(struct ims_pcu *pcu,
539 				  u8 command, int chunk, int len)
540 {
541 	int error;
542 
543 	error = usb_bulk_msg(pcu->udev,
544 			     usb_sndbulkpipe(pcu->udev,
545 					     pcu->ep_out->bEndpointAddress),
546 			     pcu->urb_out_buf, len,
547 			     NULL, IMS_PCU_CMD_WRITE_TIMEOUT);
548 	if (error < 0) {
549 		dev_dbg(pcu->dev,
550 			"Sending 0x%02x command failed at chunk %d: %d\n",
551 			command, chunk, error);
552 		return error;
553 	}
554 
555 	return 0;
556 }
557 
558 static int ims_pcu_send_command(struct ims_pcu *pcu,
559 				u8 command, const u8 *data, int len)
560 {
561 	int count = 0;
562 	int chunk = 0;
563 	int delta;
564 	int i;
565 	int error;
566 	u8 csum = 0;
567 	u8 ack_id;
568 
569 	pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_STX;
570 
571 	/* We know the command need not be escaped */
572 	pcu->urb_out_buf[count++] = command;
573 	csum += command;
574 
575 	ack_id = pcu->ack_id++;
576 	if (ack_id == 0xff)
577 		ack_id = pcu->ack_id++;
578 
579 	if (ims_pcu_byte_needs_escape(ack_id))
580 		pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_DLE;
581 
582 	pcu->urb_out_buf[count++] = ack_id;
583 	csum += ack_id;
584 
585 	for (i = 0; i < len; i++) {
586 
587 		delta = ims_pcu_byte_needs_escape(data[i]) ? 2 : 1;
588 		if (count + delta >= pcu->max_out_size) {
589 			error = ims_pcu_send_cmd_chunk(pcu, command,
590 						       ++chunk, count);
591 			if (error)
592 				return error;
593 
594 			count = 0;
595 		}
596 
597 		if (delta == 2)
598 			pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_DLE;
599 
600 		pcu->urb_out_buf[count++] = data[i];
601 		csum += data[i];
602 	}
603 
604 	csum = 1 + ~csum;
605 
606 	delta = ims_pcu_byte_needs_escape(csum) ? 3 : 2;
607 	if (count + delta >= pcu->max_out_size) {
608 		error = ims_pcu_send_cmd_chunk(pcu, command, ++chunk, count);
609 		if (error)
610 			return error;
611 
612 		count = 0;
613 	}
614 
615 	if (delta == 3)
616 		pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_DLE;
617 
618 	pcu->urb_out_buf[count++] = csum;
619 	pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_ETX;
620 
621 	return ims_pcu_send_cmd_chunk(pcu, command, ++chunk, count);
622 }
623 
624 static int __ims_pcu_execute_command(struct ims_pcu *pcu,
625 				     u8 command, const void *data, size_t len,
626 				     u8 expected_response, int response_time)
627 {
628 	int error;
629 
630 	pcu->expected_response = expected_response;
631 	init_completion(&pcu->cmd_done);
632 
633 	error = ims_pcu_send_command(pcu, command, data, len);
634 	if (error)
635 		return error;
636 
637 	if (expected_response &&
638 	    !wait_for_completion_timeout(&pcu->cmd_done,
639 					 msecs_to_jiffies(response_time))) {
640 		dev_dbg(pcu->dev, "Command 0x%02x timed out\n", command);
641 		return -ETIMEDOUT;
642 	}
643 
644 	return 0;
645 }
646 
647 #define ims_pcu_execute_command(pcu, code, data, len)			\
648 	__ims_pcu_execute_command(pcu,					\
649 				  IMS_PCU_CMD_##code, data, len,	\
650 				  IMS_PCU_RSP_##code,			\
651 				  IMS_PCU_CMD_RESPONSE_TIMEOUT)
652 
653 #define ims_pcu_execute_query(pcu, code)				\
654 	ims_pcu_execute_command(pcu, code, NULL, 0)
655 
656 /* Bootloader commands */
657 #define IMS_PCU_BL_CMD_QUERY_DEVICE	0xa1
658 #define IMS_PCU_BL_CMD_UNLOCK_CONFIG	0xa2
659 #define IMS_PCU_BL_CMD_ERASE_APP	0xa3
660 #define IMS_PCU_BL_CMD_PROGRAM_DEVICE	0xa4
661 #define IMS_PCU_BL_CMD_PROGRAM_COMPLETE	0xa5
662 #define IMS_PCU_BL_CMD_READ_APP		0xa6
663 #define IMS_PCU_BL_CMD_RESET_DEVICE	0xa7
664 #define IMS_PCU_BL_CMD_LAUNCH_APP	0xa8
665 
666 /* Bootloader commands */
667 #define IMS_PCU_BL_RSP_QUERY_DEVICE	0xc1
668 #define IMS_PCU_BL_RSP_UNLOCK_CONFIG	0xc2
669 #define IMS_PCU_BL_RSP_ERASE_APP	0xc3
670 #define IMS_PCU_BL_RSP_PROGRAM_DEVICE	0xc4
671 #define IMS_PCU_BL_RSP_PROGRAM_COMPLETE	0xc5
672 #define IMS_PCU_BL_RSP_READ_APP		0xc6
673 #define IMS_PCU_BL_RSP_RESET_DEVICE	0	/* originally 0xa7 */
674 #define IMS_PCU_BL_RSP_LAUNCH_APP	0	/* originally 0xa8 */
675 
676 #define IMS_PCU_BL_DATA_OFFSET		3
677 
678 static int __ims_pcu_execute_bl_command(struct ims_pcu *pcu,
679 					u8 command, const void *data, size_t len,
680 					u8 expected_response, int response_time)
681 {
682 	int error;
683 
684 	pcu->cmd_buf[0] = command;
685 	if (data)
686 		memcpy(&pcu->cmd_buf[1], data, len);
687 
688 	error = __ims_pcu_execute_command(pcu,
689 				IMS_PCU_CMD_BOOTLOADER, pcu->cmd_buf, len + 1,
690 				expected_response ? IMS_PCU_RSP_BOOTLOADER : 0,
691 				response_time);
692 	if (error) {
693 		dev_err(pcu->dev,
694 			"Failure when sending 0x%02x command to bootloader, error: %d\n",
695 			pcu->cmd_buf[0], error);
696 		return error;
697 	}
698 
699 	if (expected_response) {
700 		if (pcu->cmd_buf_len < 3) {
701 			dev_err(pcu->dev, "Short response from bootloader: %d bytes\n",
702 				pcu->cmd_buf_len);
703 			return -EIO;
704 		}
705 
706 		if (pcu->cmd_buf[2] != expected_response) {
707 			dev_err(pcu->dev,
708 				"Unexpected response from bootloader: 0x%02x, wanted 0x%02x\n",
709 				pcu->cmd_buf[2], expected_response);
710 			return -EINVAL;
711 		}
712 	}
713 
714 	return 0;
715 }
716 
717 #define ims_pcu_execute_bl_command(pcu, code, data, len, timeout)	\
718 	__ims_pcu_execute_bl_command(pcu,				\
719 				     IMS_PCU_BL_CMD_##code, data, len,	\
720 				     IMS_PCU_BL_RSP_##code, timeout)	\
721 
722 #define IMS_PCU_INFO_PART_OFFSET	2
723 #define IMS_PCU_INFO_DOM_OFFSET		17
724 #define IMS_PCU_INFO_SERIAL_OFFSET	25
725 
726 #define IMS_PCU_SET_INFO_SIZE		31
727 
728 static int ims_pcu_get_info(struct ims_pcu *pcu)
729 {
730 	int error;
731 
732 	error = ims_pcu_execute_query(pcu, GET_INFO);
733 	if (error) {
734 		dev_err(pcu->dev,
735 			"GET_INFO command failed, error: %d\n", error);
736 		return error;
737 	}
738 
739 	if (pcu->cmd_buf_len < IMS_PCU_DATA_OFFSET + IMS_PCU_SET_INFO_SIZE + 1) {
740 		dev_err(pcu->dev, "Short GET_INFO response: %d bytes\n",
741 			pcu->cmd_buf_len);
742 		return -EIO;
743 	}
744 
745 	memcpy(pcu->part_number,
746 	       &pcu->cmd_buf[IMS_PCU_INFO_PART_OFFSET],
747 	       sizeof(pcu->part_number));
748 	memcpy(pcu->date_of_manufacturing,
749 	       &pcu->cmd_buf[IMS_PCU_INFO_DOM_OFFSET],
750 	       sizeof(pcu->date_of_manufacturing));
751 	memcpy(pcu->serial_number,
752 	       &pcu->cmd_buf[IMS_PCU_INFO_SERIAL_OFFSET],
753 	       sizeof(pcu->serial_number));
754 
755 	return 0;
756 }
757 
758 static int ims_pcu_set_info(struct ims_pcu *pcu)
759 {
760 	int error;
761 
762 	memcpy(&pcu->cmd_buf[IMS_PCU_INFO_PART_OFFSET],
763 	       pcu->part_number, sizeof(pcu->part_number));
764 	memcpy(&pcu->cmd_buf[IMS_PCU_INFO_DOM_OFFSET],
765 	       pcu->date_of_manufacturing, sizeof(pcu->date_of_manufacturing));
766 	memcpy(&pcu->cmd_buf[IMS_PCU_INFO_SERIAL_OFFSET],
767 	       pcu->serial_number, sizeof(pcu->serial_number));
768 
769 	error = ims_pcu_execute_command(pcu, SET_INFO,
770 					&pcu->cmd_buf[IMS_PCU_DATA_OFFSET],
771 					IMS_PCU_SET_INFO_SIZE);
772 	if (error) {
773 		dev_err(pcu->dev,
774 			"Failed to update device information, error: %d\n",
775 			error);
776 		return error;
777 	}
778 
779 	return 0;
780 }
781 
782 static int ims_pcu_switch_to_bootloader(struct ims_pcu *pcu)
783 {
784 	int error;
785 
786 	/* Execute jump to the bootloader */
787 	error = ims_pcu_execute_command(pcu, JUMP_TO_BTLDR, NULL, 0);
788 	if (error) {
789 		dev_err(pcu->dev,
790 			"Failure when sending JUMP TO BOOTLOADER command, error: %d\n",
791 			error);
792 		return error;
793 	}
794 
795 	return 0;
796 }
797 
798 /*********************************************************************
799  *             Firmware Update handling                              *
800  *********************************************************************/
801 
802 #define IMS_PCU_FIRMWARE_NAME	"imspcu.fw"
803 
804 struct ims_pcu_flash_fmt {
805 	__le32 addr;
806 	u8 len;
807 	u8 data[] __counted_by(len);
808 };
809 
810 static unsigned int ims_pcu_count_fw_records(const struct firmware *fw)
811 {
812 	const struct ihex_binrec *rec = (const struct ihex_binrec *)fw->data;
813 	unsigned int count = 0;
814 
815 	while (rec) {
816 		count++;
817 		rec = ihex_next_binrec(rec);
818 	}
819 
820 	return count;
821 }
822 
823 static int ims_pcu_verify_block(struct ims_pcu *pcu,
824 				u32 addr, u8 len, const u8 *data)
825 {
826 	struct ims_pcu_flash_fmt *fragment;
827 	int error;
828 
829 	fragment = (void *)&pcu->cmd_buf[1];
830 	put_unaligned_le32(addr, &fragment->addr);
831 	fragment->len = len;
832 
833 	error = ims_pcu_execute_bl_command(pcu, READ_APP, NULL, 5,
834 					IMS_PCU_CMD_RESPONSE_TIMEOUT);
835 	if (error) {
836 		dev_err(pcu->dev,
837 			"Failed to retrieve block at 0x%08x, len %d, error: %d\n",
838 			addr, len, error);
839 		return error;
840 	}
841 
842 	if (pcu->cmd_buf_len < IMS_PCU_BL_DATA_OFFSET + sizeof(*fragment) + len + 1) {
843 		dev_err(pcu->dev, "Short READ_APP response: %d bytes\n",
844 			pcu->cmd_buf_len);
845 		return -EIO;
846 	}
847 
848 	fragment = (void *)&pcu->cmd_buf[IMS_PCU_BL_DATA_OFFSET];
849 	if (get_unaligned_le32(&fragment->addr) != addr ||
850 	    fragment->len != len) {
851 		dev_err(pcu->dev,
852 			"Wrong block when retrieving 0x%08x (0x%08x), len %d (%d)\n",
853 			addr, get_unaligned_le32(&fragment->addr),
854 			len, fragment->len);
855 		return -EINVAL;
856 	}
857 
858 	if (memcmp(fragment->data, data, len)) {
859 		dev_err(pcu->dev,
860 			"Mismatch in block at 0x%08x, len %d\n",
861 			addr, len);
862 		return -EINVAL;
863 	}
864 
865 	return 0;
866 }
867 
868 static int ims_pcu_flash_firmware(struct ims_pcu *pcu,
869 				  const struct firmware *fw,
870 				  unsigned int n_fw_records)
871 {
872 	const struct ihex_binrec *rec = (const struct ihex_binrec *)fw->data;
873 	struct ims_pcu_flash_fmt *fragment;
874 	unsigned int count = 0;
875 	u32 addr;
876 	u8 len;
877 	int error;
878 
879 	error = ims_pcu_execute_bl_command(pcu, ERASE_APP, NULL, 0, 2000);
880 	if (error) {
881 		dev_err(pcu->dev,
882 			"Failed to erase application image, error: %d\n",
883 			error);
884 		return error;
885 	}
886 
887 	while (rec) {
888 		/*
889 		 * The firmware format is messed up for some reason.
890 		 * The address twice that of what is needed for some
891 		 * reason and we end up overwriting half of the data
892 		 * with the next record.
893 		 */
894 		addr = be32_to_cpu(rec->addr) / 2;
895 		len = be16_to_cpu(rec->len);
896 
897 		if (len > sizeof(pcu->cmd_buf) - 1 - sizeof(*fragment)) {
898 			dev_err(pcu->dev,
899 				"Invalid record length in firmware: %d\n", len);
900 			return -EINVAL;
901 		}
902 
903 		fragment = (void *)&pcu->cmd_buf[1];
904 		put_unaligned_le32(addr, &fragment->addr);
905 		fragment->len = len;
906 		memcpy(fragment->data, rec->data, len);
907 
908 		error = ims_pcu_execute_bl_command(pcu, PROGRAM_DEVICE,
909 						NULL, len + 5,
910 						IMS_PCU_CMD_RESPONSE_TIMEOUT);
911 		if (error) {
912 			dev_err(pcu->dev,
913 				"Failed to write block at 0x%08x, len %d, error: %d\n",
914 				addr, len, error);
915 			return error;
916 		}
917 
918 		if (addr >= pcu->fw_start_addr && addr < pcu->fw_end_addr) {
919 			error = ims_pcu_verify_block(pcu, addr, len, rec->data);
920 			if (error)
921 				return error;
922 		}
923 
924 		count++;
925 		pcu->update_firmware_status = (count * 100) / n_fw_records;
926 
927 		rec = ihex_next_binrec(rec);
928 	}
929 
930 	error = ims_pcu_execute_bl_command(pcu, PROGRAM_COMPLETE,
931 					    NULL, 0, 2000);
932 	if (error)
933 		dev_err(pcu->dev,
934 			"Failed to send PROGRAM_COMPLETE, error: %d\n",
935 			error);
936 
937 	return 0;
938 }
939 
940 static int ims_pcu_handle_firmware_update(struct ims_pcu *pcu,
941 					  const struct firmware *fw)
942 {
943 	unsigned int n_fw_records;
944 	int retval;
945 
946 	dev_info(pcu->dev, "Updating firmware %s, size: %zu\n",
947 		 IMS_PCU_FIRMWARE_NAME, fw->size);
948 
949 	n_fw_records = ims_pcu_count_fw_records(fw);
950 
951 	retval = ims_pcu_flash_firmware(pcu, fw, n_fw_records);
952 	if (retval)
953 		goto out;
954 
955 	retval = ims_pcu_execute_bl_command(pcu, LAUNCH_APP, NULL, 0, 0);
956 	if (retval)
957 		dev_err(pcu->dev,
958 			"Failed to start application image, error: %d\n",
959 			retval);
960 
961 out:
962 	pcu->update_firmware_status = retval;
963 	sysfs_notify(&pcu->dev->kobj, NULL, "update_firmware_status");
964 	return retval;
965 }
966 
967 static void ims_pcu_process_async_firmware(const struct firmware *_fw,
968 					   void *context)
969 {
970 	const struct firmware *fw __free(firmware) = _fw;
971 	struct ims_pcu *pcu = context;
972 	int error;
973 
974 	if (!fw) {
975 		dev_err(pcu->dev, "Failed to get firmware %s\n",
976 			IMS_PCU_FIRMWARE_NAME);
977 		goto out;
978 	}
979 
980 	error = ihex_validate_fw(fw);
981 	if (error) {
982 		dev_err(pcu->dev, "Firmware %s is invalid\n",
983 			IMS_PCU_FIRMWARE_NAME);
984 		goto out;
985 	}
986 
987 	scoped_guard(mutex, &pcu->cmd_mutex)
988 		ims_pcu_handle_firmware_update(pcu, fw);
989 
990 out:
991 	complete(&pcu->async_firmware_done);
992 }
993 
994 /*********************************************************************
995  *             Backlight LED device support                          *
996  *********************************************************************/
997 
998 #define IMS_PCU_MAX_BRIGHTNESS		31998
999 
1000 static int ims_pcu_backlight_set_brightness(struct led_classdev *cdev,
1001 					    enum led_brightness value)
1002 {
1003 	struct ims_pcu_backlight *backlight =
1004 			container_of(cdev, struct ims_pcu_backlight, cdev);
1005 	struct ims_pcu *pcu =
1006 			container_of(backlight, struct ims_pcu, backlight);
1007 	__le16 br_val = cpu_to_le16(value);
1008 	int error;
1009 
1010 	guard(mutex)(&pcu->cmd_mutex);
1011 
1012 	error = ims_pcu_execute_command(pcu, SET_BRIGHTNESS,
1013 					&br_val, sizeof(br_val));
1014 	if (error && error != -ENODEV)
1015 		dev_warn(pcu->dev,
1016 			 "Failed to set desired brightness %u, error: %d\n",
1017 			 value, error);
1018 
1019 	return error;
1020 }
1021 
1022 static enum led_brightness
1023 ims_pcu_backlight_get_brightness(struct led_classdev *cdev)
1024 {
1025 	struct ims_pcu_backlight *backlight =
1026 			container_of(cdev, struct ims_pcu_backlight, cdev);
1027 	struct ims_pcu *pcu =
1028 			container_of(backlight, struct ims_pcu, backlight);
1029 	int brightness;
1030 	int error;
1031 
1032 	guard(mutex)(&pcu->cmd_mutex);
1033 
1034 	error = ims_pcu_execute_query(pcu, GET_BRIGHTNESS);
1035 	if (error) {
1036 		dev_warn(pcu->dev,
1037 			 "Failed to get current brightness, error: %d\n",
1038 			 error);
1039 		/* Assume the LED is OFF */
1040 		brightness = LED_OFF;
1041 	} else if (pcu->cmd_buf_len < IMS_PCU_DATA_OFFSET + 2 + 1) {
1042 		dev_err(pcu->dev, "Short GET_BRIGHTNESS response: %d bytes\n",
1043 			pcu->cmd_buf_len);
1044 		brightness = LED_OFF;
1045 	} else {
1046 		brightness =
1047 			get_unaligned_le16(&pcu->cmd_buf[IMS_PCU_DATA_OFFSET]);
1048 	}
1049 
1050 	return brightness;
1051 }
1052 
1053 static int ims_pcu_setup_backlight(struct ims_pcu *pcu)
1054 {
1055 	struct ims_pcu_backlight *backlight = &pcu->backlight;
1056 	int error;
1057 
1058 	snprintf(backlight->name, sizeof(backlight->name),
1059 		 "pcu%d::kbd_backlight", pcu->device_no);
1060 
1061 	backlight->cdev.name = backlight->name;
1062 	backlight->cdev.max_brightness = IMS_PCU_MAX_BRIGHTNESS;
1063 	backlight->cdev.brightness_get = ims_pcu_backlight_get_brightness;
1064 	backlight->cdev.brightness_set_blocking =
1065 					 ims_pcu_backlight_set_brightness;
1066 
1067 	error = led_classdev_register(pcu->dev, &backlight->cdev);
1068 	if (error) {
1069 		dev_err(pcu->dev,
1070 			"Failed to register backlight LED device, error: %d\n",
1071 			error);
1072 		return error;
1073 	}
1074 
1075 	return 0;
1076 }
1077 
1078 static void ims_pcu_destroy_backlight(struct ims_pcu *pcu)
1079 {
1080 	struct ims_pcu_backlight *backlight = &pcu->backlight;
1081 
1082 	led_classdev_unregister(&backlight->cdev);
1083 }
1084 
1085 
1086 /*********************************************************************
1087  *             Sysfs attributes handling                             *
1088  *********************************************************************/
1089 
1090 struct ims_pcu_attribute {
1091 	struct device_attribute dattr;
1092 	size_t field_offset;
1093 	int field_length;
1094 };
1095 
1096 static ssize_t ims_pcu_attribute_show(struct device *dev,
1097 				      struct device_attribute *dattr,
1098 				      char *buf)
1099 {
1100 	struct usb_interface *intf = to_usb_interface(dev);
1101 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1102 	struct ims_pcu_attribute *attr =
1103 			container_of(dattr, struct ims_pcu_attribute, dattr);
1104 	char *field = (char *)pcu + attr->field_offset;
1105 
1106 	return sysfs_emit(buf, "%.*s\n", attr->field_length, field);
1107 }
1108 
1109 static ssize_t ims_pcu_attribute_store(struct device *dev,
1110 				       struct device_attribute *dattr,
1111 				       const char *buf, size_t count)
1112 {
1113 
1114 	struct usb_interface *intf = to_usb_interface(dev);
1115 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1116 	struct ims_pcu_attribute *attr =
1117 			container_of(dattr, struct ims_pcu_attribute, dattr);
1118 	char *field = (char *)pcu + attr->field_offset;
1119 	size_t data_len;
1120 	int error;
1121 
1122 	if (count > attr->field_length)
1123 		return -EINVAL;
1124 
1125 	data_len = strnlen(buf, attr->field_length);
1126 	if (data_len > attr->field_length)
1127 		return -EINVAL;
1128 
1129 	scoped_cond_guard(mutex_intr, return -EINTR, &pcu->cmd_mutex) {
1130 		memset(field, 0, attr->field_length);
1131 		memcpy(field, buf, data_len);
1132 
1133 		error = ims_pcu_set_info(pcu);
1134 
1135 		/*
1136 		 * Even if update failed, let's fetch the info again as we just
1137 		 * clobbered one of the fields.
1138 		 */
1139 		ims_pcu_get_info(pcu);
1140 
1141 		if (error)
1142 			return error;
1143 	}
1144 
1145 	return count;
1146 }
1147 
1148 #define IMS_PCU_ATTR(_field, _mode)					\
1149 struct ims_pcu_attribute ims_pcu_attr_##_field = {			\
1150 	.dattr = __ATTR(_field, _mode,					\
1151 			ims_pcu_attribute_show,				\
1152 			ims_pcu_attribute_store),			\
1153 	.field_offset = offsetof(struct ims_pcu, _field),		\
1154 	.field_length = sizeof(((struct ims_pcu *)NULL)->_field),	\
1155 }
1156 
1157 #define IMS_PCU_RO_ATTR(_field)						\
1158 		IMS_PCU_ATTR(_field, S_IRUGO)
1159 #define IMS_PCU_RW_ATTR(_field)						\
1160 		IMS_PCU_ATTR(_field, S_IRUGO | S_IWUSR)
1161 
1162 static IMS_PCU_RW_ATTR(part_number);
1163 static IMS_PCU_RW_ATTR(serial_number);
1164 static IMS_PCU_RW_ATTR(date_of_manufacturing);
1165 
1166 static IMS_PCU_RO_ATTR(fw_version);
1167 static IMS_PCU_RO_ATTR(bl_version);
1168 static IMS_PCU_RO_ATTR(reset_reason);
1169 
1170 static ssize_t ims_pcu_reset_device(struct device *dev,
1171 				    struct device_attribute *dattr,
1172 				    const char *buf, size_t count)
1173 {
1174 	static const u8 reset_byte = 1;
1175 	struct usb_interface *intf = to_usb_interface(dev);
1176 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1177 	int value;
1178 	int error;
1179 
1180 	error = kstrtoint(buf, 0, &value);
1181 	if (error)
1182 		return error;
1183 
1184 	if (value != 1)
1185 		return -EINVAL;
1186 
1187 	dev_info(pcu->dev, "Attempting to reset device\n");
1188 
1189 	guard(mutex)(&pcu->cmd_mutex);
1190 
1191 	error = ims_pcu_execute_command(pcu, PCU_RESET, &reset_byte, 1);
1192 	if (error) {
1193 		dev_info(pcu->dev,
1194 			 "Failed to reset device, error: %d\n",
1195 			 error);
1196 		return error;
1197 	}
1198 
1199 	return count;
1200 }
1201 
1202 static DEVICE_ATTR(reset_device, S_IWUSR, NULL, ims_pcu_reset_device);
1203 
1204 static ssize_t ims_pcu_update_firmware_store(struct device *dev,
1205 					     struct device_attribute *dattr,
1206 					     const char *buf, size_t count)
1207 {
1208 	struct usb_interface *intf = to_usb_interface(dev);
1209 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1210 	int value;
1211 	int error;
1212 
1213 	error = kstrtoint(buf, 0, &value);
1214 	if (error)
1215 		return error;
1216 
1217 	if (value != 1)
1218 		return -EINVAL;
1219 
1220 	const struct firmware *fw __free(firmware) = NULL;
1221 	error = request_ihex_firmware(&fw, IMS_PCU_FIRMWARE_NAME, pcu->dev);
1222 	if (error) {
1223 		dev_err(pcu->dev, "Failed to request firmware %s, error: %d\n",
1224 			IMS_PCU_FIRMWARE_NAME, error);
1225 		return error;
1226 	}
1227 
1228 	scoped_cond_guard(mutex_intr, return -EINTR, &pcu->cmd_mutex) {
1229 		/*
1230 		 * If we are already in bootloader mode we can proceed with
1231 		 * flashing the firmware.
1232 		 *
1233 		 * If we are in application mode, then we need to switch into
1234 		 * bootloader mode, which will cause the device to disconnect
1235 		 * and reconnect as different device.
1236 		 */
1237 		if (pcu->bootloader_mode)
1238 			error = ims_pcu_handle_firmware_update(pcu, fw);
1239 		else
1240 			error = ims_pcu_switch_to_bootloader(pcu);
1241 
1242 		if (error)
1243 			return error;
1244 	}
1245 
1246 	return count;
1247 }
1248 
1249 static DEVICE_ATTR(update_firmware, S_IWUSR,
1250 		   NULL, ims_pcu_update_firmware_store);
1251 
1252 static ssize_t
1253 ims_pcu_update_firmware_status_show(struct device *dev,
1254 				    struct device_attribute *dattr,
1255 				    char *buf)
1256 {
1257 	struct usb_interface *intf = to_usb_interface(dev);
1258 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1259 
1260 	return sysfs_emit(buf, "%d\n", pcu->update_firmware_status);
1261 }
1262 
1263 static DEVICE_ATTR(update_firmware_status, S_IRUGO,
1264 		   ims_pcu_update_firmware_status_show, NULL);
1265 
1266 static struct attribute *ims_pcu_attrs[] = {
1267 	&ims_pcu_attr_part_number.dattr.attr,
1268 	&ims_pcu_attr_serial_number.dattr.attr,
1269 	&ims_pcu_attr_date_of_manufacturing.dattr.attr,
1270 	&ims_pcu_attr_fw_version.dattr.attr,
1271 	&ims_pcu_attr_bl_version.dattr.attr,
1272 	&ims_pcu_attr_reset_reason.dattr.attr,
1273 	&dev_attr_reset_device.attr,
1274 	&dev_attr_update_firmware.attr,
1275 	&dev_attr_update_firmware_status.attr,
1276 	NULL
1277 };
1278 
1279 static umode_t ims_pcu_is_attr_visible(struct kobject *kobj,
1280 				       struct attribute *attr, int n)
1281 {
1282 	struct device *dev = kobj_to_dev(kobj);
1283 	struct usb_interface *intf = to_usb_interface(dev);
1284 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1285 	umode_t mode = attr->mode;
1286 
1287 	if (intf != pcu->ctrl_intf)
1288 		return 0;
1289 
1290 	if (pcu->bootloader_mode) {
1291 		if (attr != &dev_attr_update_firmware_status.attr &&
1292 		    attr != &dev_attr_update_firmware.attr &&
1293 		    attr != &dev_attr_reset_device.attr) {
1294 			mode = 0;
1295 		}
1296 	} else {
1297 		if (attr == &dev_attr_update_firmware_status.attr)
1298 			mode = 0;
1299 	}
1300 
1301 	return mode;
1302 }
1303 
1304 static const struct attribute_group ims_pcu_attr_group = {
1305 	.is_visible	= ims_pcu_is_attr_visible,
1306 	.attrs		= ims_pcu_attrs,
1307 };
1308 
1309 /* Support for a separate OFN attribute group */
1310 
1311 #define OFN_REG_RESULT_OFFSET	2
1312 
1313 static int ims_pcu_read_ofn_config(struct ims_pcu *pcu, u8 addr, u8 *data)
1314 {
1315 	int error;
1316 	s16 result;
1317 
1318 	error = ims_pcu_execute_command(pcu, OFN_GET_CONFIG,
1319 					&addr, sizeof(addr));
1320 	if (error)
1321 		return error;
1322 
1323 	if (pcu->cmd_buf_len < OFN_REG_RESULT_OFFSET + 2 + 1) {
1324 		dev_err(pcu->dev, "Short OFN_GET_CONFIG response: %d bytes\n",
1325 			pcu->cmd_buf_len);
1326 		return -EIO;
1327 	}
1328 
1329 	result = (s16)get_unaligned_le16(pcu->cmd_buf + OFN_REG_RESULT_OFFSET);
1330 	if (result < 0)
1331 		return -EIO;
1332 
1333 	/* We only need LSB */
1334 	*data = pcu->cmd_buf[OFN_REG_RESULT_OFFSET];
1335 	return 0;
1336 }
1337 
1338 static int ims_pcu_write_ofn_config(struct ims_pcu *pcu, u8 addr, u8 data)
1339 {
1340 	u8 buffer[] = { addr, data };
1341 	int error;
1342 	s16 result;
1343 
1344 	error = ims_pcu_execute_command(pcu, OFN_SET_CONFIG,
1345 					&buffer, sizeof(buffer));
1346 	if (error)
1347 		return error;
1348 
1349 	if (pcu->cmd_buf_len < OFN_REG_RESULT_OFFSET + 2 + 1) {
1350 		dev_err(pcu->dev, "Short OFN_SET_CONFIG response: %d bytes\n",
1351 			pcu->cmd_buf_len);
1352 		return -EIO;
1353 	}
1354 
1355 	result = (s16)get_unaligned_le16(pcu->cmd_buf + OFN_REG_RESULT_OFFSET);
1356 	if (result < 0)
1357 		return -EIO;
1358 
1359 	return 0;
1360 }
1361 
1362 static ssize_t ims_pcu_ofn_reg_data_show(struct device *dev,
1363 					 struct device_attribute *dattr,
1364 					 char *buf)
1365 {
1366 	struct usb_interface *intf = to_usb_interface(dev);
1367 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1368 	int error;
1369 	u8 data;
1370 
1371 	scoped_guard(mutex, &pcu->cmd_mutex) {
1372 		error = ims_pcu_read_ofn_config(pcu, pcu->ofn_reg_addr, &data);
1373 		if (error)
1374 			return error;
1375 	}
1376 
1377 	return sysfs_emit(buf, "%x\n", data);
1378 }
1379 
1380 static ssize_t ims_pcu_ofn_reg_data_store(struct device *dev,
1381 					  struct device_attribute *dattr,
1382 					  const char *buf, size_t count)
1383 {
1384 	struct usb_interface *intf = to_usb_interface(dev);
1385 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1386 	int error;
1387 	u8 value;
1388 
1389 	error = kstrtou8(buf, 0, &value);
1390 	if (error)
1391 		return error;
1392 
1393 	guard(mutex)(&pcu->cmd_mutex);
1394 
1395 	error = ims_pcu_write_ofn_config(pcu, pcu->ofn_reg_addr, value);
1396 	if (error)
1397 		return error;
1398 
1399 	return count;
1400 }
1401 
1402 static DEVICE_ATTR(reg_data, S_IRUGO | S_IWUSR,
1403 		   ims_pcu_ofn_reg_data_show, ims_pcu_ofn_reg_data_store);
1404 
1405 static ssize_t ims_pcu_ofn_reg_addr_show(struct device *dev,
1406 					 struct device_attribute *dattr,
1407 					 char *buf)
1408 {
1409 	struct usb_interface *intf = to_usb_interface(dev);
1410 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1411 
1412 	guard(mutex)(&pcu->cmd_mutex);
1413 
1414 	return sysfs_emit(buf, "%x\n", pcu->ofn_reg_addr);
1415 }
1416 
1417 static ssize_t ims_pcu_ofn_reg_addr_store(struct device *dev,
1418 					  struct device_attribute *dattr,
1419 					  const char *buf, size_t count)
1420 {
1421 	struct usb_interface *intf = to_usb_interface(dev);
1422 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1423 	int error;
1424 	u8 value;
1425 
1426 	error = kstrtou8(buf, 0, &value);
1427 	if (error)
1428 		return error;
1429 
1430 	guard(mutex)(&pcu->cmd_mutex);
1431 
1432 	pcu->ofn_reg_addr = value;
1433 
1434 	return count;
1435 }
1436 
1437 static DEVICE_ATTR(reg_addr, S_IRUGO | S_IWUSR,
1438 		   ims_pcu_ofn_reg_addr_show, ims_pcu_ofn_reg_addr_store);
1439 
1440 struct ims_pcu_ofn_bit_attribute {
1441 	struct device_attribute dattr;
1442 	u8 addr;
1443 	u8 nr;
1444 };
1445 
1446 static ssize_t ims_pcu_ofn_bit_show(struct device *dev,
1447 				    struct device_attribute *dattr,
1448 				    char *buf)
1449 {
1450 	struct usb_interface *intf = to_usb_interface(dev);
1451 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1452 	struct ims_pcu_ofn_bit_attribute *attr =
1453 		container_of(dattr, struct ims_pcu_ofn_bit_attribute, dattr);
1454 	int error;
1455 	u8 data;
1456 
1457 	scoped_guard(mutex, &pcu->cmd_mutex) {
1458 		error = ims_pcu_read_ofn_config(pcu, attr->addr, &data);
1459 		if (error)
1460 			return error;
1461 	}
1462 
1463 	return sysfs_emit(buf, "%d\n", !!(data & (1 << attr->nr)));
1464 }
1465 
1466 static ssize_t ims_pcu_ofn_bit_store(struct device *dev,
1467 				     struct device_attribute *dattr,
1468 				     const char *buf, size_t count)
1469 {
1470 	struct usb_interface *intf = to_usb_interface(dev);
1471 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1472 	struct ims_pcu_ofn_bit_attribute *attr =
1473 		container_of(dattr, struct ims_pcu_ofn_bit_attribute, dattr);
1474 	int error;
1475 	int value;
1476 	u8 data;
1477 
1478 	error = kstrtoint(buf, 0, &value);
1479 	if (error)
1480 		return error;
1481 
1482 	if (value > 1)
1483 		return -EINVAL;
1484 
1485 	scoped_guard(mutex, &pcu->cmd_mutex) {
1486 		error = ims_pcu_read_ofn_config(pcu, attr->addr, &data);
1487 		if (error)
1488 			return error;
1489 
1490 		if (value)
1491 			data |= 1U << attr->nr;
1492 		else
1493 			data &= ~(1U << attr->nr);
1494 
1495 		error = ims_pcu_write_ofn_config(pcu, attr->addr, data);
1496 		if (error)
1497 			return error;
1498 	}
1499 
1500 	return count;
1501 }
1502 
1503 #define IMS_PCU_OFN_BIT_ATTR(_field, _addr, _nr)			\
1504 struct ims_pcu_ofn_bit_attribute ims_pcu_ofn_attr_##_field = {		\
1505 	.dattr = __ATTR(_field, S_IWUSR | S_IRUGO,			\
1506 			ims_pcu_ofn_bit_show, ims_pcu_ofn_bit_store),	\
1507 	.addr = _addr,							\
1508 	.nr = _nr,							\
1509 }
1510 
1511 static IMS_PCU_OFN_BIT_ATTR(engine_enable,   0x60, 7);
1512 static IMS_PCU_OFN_BIT_ATTR(speed_enable,    0x60, 6);
1513 static IMS_PCU_OFN_BIT_ATTR(assert_enable,   0x60, 5);
1514 static IMS_PCU_OFN_BIT_ATTR(xyquant_enable,  0x60, 4);
1515 static IMS_PCU_OFN_BIT_ATTR(xyscale_enable,  0x60, 1);
1516 
1517 static IMS_PCU_OFN_BIT_ATTR(scale_x2,        0x63, 6);
1518 static IMS_PCU_OFN_BIT_ATTR(scale_y2,        0x63, 7);
1519 
1520 static struct attribute *ims_pcu_ofn_attrs[] = {
1521 	&dev_attr_reg_data.attr,
1522 	&dev_attr_reg_addr.attr,
1523 	&ims_pcu_ofn_attr_engine_enable.dattr.attr,
1524 	&ims_pcu_ofn_attr_speed_enable.dattr.attr,
1525 	&ims_pcu_ofn_attr_assert_enable.dattr.attr,
1526 	&ims_pcu_ofn_attr_xyquant_enable.dattr.attr,
1527 	&ims_pcu_ofn_attr_xyscale_enable.dattr.attr,
1528 	&ims_pcu_ofn_attr_scale_x2.dattr.attr,
1529 	&ims_pcu_ofn_attr_scale_y2.dattr.attr,
1530 	NULL
1531 };
1532 
1533 static umode_t ims_pcu_ofn_is_attr_visible(struct kobject *kobj,
1534 					   struct attribute *attr, int n)
1535 {
1536 	struct device *dev = kobj_to_dev(kobj);
1537 	struct usb_interface *intf = to_usb_interface(dev);
1538 	struct ims_pcu *pcu = usb_get_intfdata(intf);
1539 	umode_t mode = attr->mode;
1540 
1541 	if (intf != pcu->ctrl_intf)
1542 		return SYSFS_GROUP_INVISIBLE;
1543 
1544 	/*
1545 	 * PCU-B devices, both GEN_1 and GEN_2 do not have OFN sensor.
1546 	 */
1547 	if (pcu->bootloader_mode || pcu->device_id == IMS_PCU_PCU_B_DEVICE_ID)
1548 		mode = 0;
1549 
1550 	return mode;
1551 }
1552 
1553 static const struct attribute_group ims_pcu_ofn_attr_group = {
1554 	.name		= "ofn",
1555 	.is_visible	= ims_pcu_ofn_is_attr_visible,
1556 	.attrs		= ims_pcu_ofn_attrs,
1557 };
1558 
1559 static void ims_pcu_irq(struct urb *urb)
1560 {
1561 	struct ims_pcu *pcu = urb->context;
1562 	int retval, status;
1563 
1564 	status = urb->status;
1565 
1566 	switch (status) {
1567 	case 0:
1568 		/* success */
1569 		break;
1570 	case -ECONNRESET:
1571 	case -ENOENT:
1572 	case -ESHUTDOWN:
1573 		/* this urb is terminated, clean up */
1574 		dev_dbg(pcu->dev, "%s - urb shutting down with status: %d\n",
1575 			__func__, status);
1576 		return;
1577 	default:
1578 		dev_dbg(pcu->dev, "%s - nonzero urb status received: %d\n",
1579 			__func__, status);
1580 		goto exit;
1581 	}
1582 
1583 	dev_dbg(pcu->dev, "%s: received %d: %*ph\n", __func__,
1584 		urb->actual_length, urb->actual_length, urb->transfer_buffer);
1585 
1586 	if (urb == pcu->urb_in)
1587 		ims_pcu_process_data(pcu, urb);
1588 
1589 exit:
1590 	retval = usb_submit_urb(urb, GFP_ATOMIC);
1591 	if (retval && retval != -ENODEV)
1592 		dev_err(pcu->dev, "%s - usb_submit_urb failed with result %d\n",
1593 			__func__, retval);
1594 }
1595 
1596 static int ims_pcu_buffers_alloc(struct ims_pcu *pcu)
1597 {
1598 	int error;
1599 
1600 	pcu->urb_in_buf = usb_alloc_coherent(pcu->udev, pcu->max_in_size,
1601 					     GFP_KERNEL, &pcu->read_dma);
1602 	if (!pcu->urb_in_buf) {
1603 		dev_err(pcu->dev,
1604 			"Failed to allocate memory for read buffer\n");
1605 		return -ENOMEM;
1606 	}
1607 
1608 	pcu->urb_in = usb_alloc_urb(0, GFP_KERNEL);
1609 	if (!pcu->urb_in) {
1610 		dev_err(pcu->dev, "Failed to allocate input URB\n");
1611 		error = -ENOMEM;
1612 		goto err_free_urb_in_buf;
1613 	}
1614 
1615 	pcu->urb_in->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1616 	pcu->urb_in->transfer_dma = pcu->read_dma;
1617 
1618 	usb_fill_bulk_urb(pcu->urb_in, pcu->udev,
1619 			  usb_rcvbulkpipe(pcu->udev,
1620 					  pcu->ep_in->bEndpointAddress),
1621 			  pcu->urb_in_buf, pcu->max_in_size,
1622 			  ims_pcu_irq, pcu);
1623 
1624 	/*
1625 	 * We are using usb_bulk_msg() for sending so there is no point
1626 	 * in allocating memory with usb_alloc_coherent().
1627 	 */
1628 	pcu->urb_out_buf = kmalloc(pcu->max_out_size, GFP_KERNEL);
1629 	if (!pcu->urb_out_buf) {
1630 		dev_err(pcu->dev, "Failed to allocate memory for write buffer\n");
1631 		error = -ENOMEM;
1632 		goto err_free_in_urb;
1633 	}
1634 
1635 	pcu->urb_ctrl_buf = usb_alloc_coherent(pcu->udev, pcu->max_ctrl_size,
1636 					       GFP_KERNEL, &pcu->ctrl_dma);
1637 	if (!pcu->urb_ctrl_buf) {
1638 		dev_err(pcu->dev,
1639 			"Failed to allocate memory for read buffer\n");
1640 		error = -ENOMEM;
1641 		goto err_free_urb_out_buf;
1642 	}
1643 
1644 	pcu->urb_ctrl = usb_alloc_urb(0, GFP_KERNEL);
1645 	if (!pcu->urb_ctrl) {
1646 		dev_err(pcu->dev, "Failed to allocate input URB\n");
1647 		error = -ENOMEM;
1648 		goto err_free_urb_ctrl_buf;
1649 	}
1650 
1651 	pcu->urb_ctrl->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1652 	pcu->urb_ctrl->transfer_dma = pcu->ctrl_dma;
1653 
1654 	usb_fill_int_urb(pcu->urb_ctrl, pcu->udev,
1655 			  usb_rcvintpipe(pcu->udev,
1656 					 pcu->ep_ctrl->bEndpointAddress),
1657 			  pcu->urb_ctrl_buf, pcu->max_ctrl_size,
1658 			  ims_pcu_irq, pcu, pcu->ep_ctrl->bInterval);
1659 
1660 	return 0;
1661 
1662 err_free_urb_ctrl_buf:
1663 	usb_free_coherent(pcu->udev, pcu->max_ctrl_size,
1664 			  pcu->urb_ctrl_buf, pcu->ctrl_dma);
1665 err_free_urb_out_buf:
1666 	kfree(pcu->urb_out_buf);
1667 err_free_in_urb:
1668 	usb_free_urb(pcu->urb_in);
1669 err_free_urb_in_buf:
1670 	usb_free_coherent(pcu->udev, pcu->max_in_size,
1671 			  pcu->urb_in_buf, pcu->read_dma);
1672 	return error;
1673 }
1674 
1675 static void ims_pcu_buffers_free(struct ims_pcu *pcu)
1676 {
1677 	usb_kill_urb(pcu->urb_in);
1678 	usb_free_urb(pcu->urb_in);
1679 
1680 	usb_free_coherent(pcu->udev, pcu->max_in_size,
1681 			  pcu->urb_in_buf, pcu->read_dma);
1682 
1683 	kfree(pcu->urb_out_buf);
1684 
1685 	usb_kill_urb(pcu->urb_ctrl);
1686 	usb_free_urb(pcu->urb_ctrl);
1687 
1688 	usb_free_coherent(pcu->udev, pcu->max_ctrl_size,
1689 			  pcu->urb_ctrl_buf, pcu->ctrl_dma);
1690 }
1691 
1692 static const struct usb_cdc_union_desc *
1693 ims_pcu_get_cdc_union_desc(struct usb_interface *intf)
1694 {
1695 	const void *buf = intf->altsetting->extra;
1696 	size_t buflen = intf->altsetting->extralen;
1697 	struct usb_cdc_union_desc *union_desc;
1698 
1699 	if (!buf) {
1700 		dev_err(&intf->dev, "Missing descriptor data\n");
1701 		return NULL;
1702 	}
1703 
1704 	if (!buflen) {
1705 		dev_err(&intf->dev, "Zero length descriptor\n");
1706 		return NULL;
1707 	}
1708 
1709 	while (buflen >= sizeof(*union_desc)) {
1710 		union_desc = (struct usb_cdc_union_desc *)buf;
1711 
1712 		if (union_desc->bLength < 2 || union_desc->bLength > buflen) {
1713 			dev_err(&intf->dev, "Invalid descriptor length: %d\n",
1714 				union_desc->bLength);
1715 			return NULL;
1716 		}
1717 
1718 		if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&
1719 		    union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {
1720 			dev_dbg(&intf->dev, "Found union header\n");
1721 
1722 			if (union_desc->bLength >= sizeof(*union_desc))
1723 				return union_desc;
1724 
1725 			dev_err(&intf->dev,
1726 				"Union descriptor too short (%d vs %zd)\n",
1727 				union_desc->bLength, sizeof(*union_desc));
1728 			return NULL;
1729 		}
1730 
1731 		buflen -= union_desc->bLength;
1732 		buf += union_desc->bLength;
1733 	}
1734 
1735 	dev_err(&intf->dev, "Missing CDC union descriptor\n");
1736 	return NULL;
1737 }
1738 
1739 static int ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu)
1740 {
1741 	const struct usb_cdc_union_desc *union_desc;
1742 	struct usb_host_interface *alt;
1743 
1744 	union_desc = ims_pcu_get_cdc_union_desc(intf);
1745 	if (!union_desc)
1746 		return -EINVAL;
1747 
1748 	pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev,
1749 					 union_desc->bMasterInterface0);
1750 	if (pcu->ctrl_intf != intf)
1751 		return -EINVAL;
1752 
1753 	alt = pcu->ctrl_intf->cur_altsetting;
1754 
1755 	if (alt->desc.bNumEndpoints < 1)
1756 		return -ENODEV;
1757 
1758 	pcu->ep_ctrl = &alt->endpoint[0].desc;
1759 	if (!usb_endpoint_is_int_in(pcu->ep_ctrl)) {
1760 		dev_err(pcu->dev,
1761 			"Control endpoint is not INTERRUPT IN\n");
1762 		return -EINVAL;
1763 	}
1764 
1765 	pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl);
1766 
1767 	pcu->data_intf = usb_ifnum_to_if(pcu->udev,
1768 					 union_desc->bSlaveInterface0);
1769 	if (!pcu->data_intf)
1770 		return -EINVAL;
1771 
1772 	alt = pcu->data_intf->cur_altsetting;
1773 	if (alt->desc.bNumEndpoints != 2) {
1774 		dev_err(pcu->dev,
1775 			"Incorrect number of endpoints on data interface (%d)\n",
1776 			alt->desc.bNumEndpoints);
1777 		return -EINVAL;
1778 	}
1779 
1780 	pcu->ep_out = &alt->endpoint[0].desc;
1781 	if (!usb_endpoint_is_bulk_out(pcu->ep_out)) {
1782 		dev_err(pcu->dev,
1783 			"First endpoint on data interface is not BULK OUT\n");
1784 		return -EINVAL;
1785 	}
1786 
1787 	pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out);
1788 	if (pcu->max_out_size < 8) {
1789 		dev_err(pcu->dev,
1790 			"Max OUT packet size is too small (%zd)\n",
1791 			pcu->max_out_size);
1792 		return -EINVAL;
1793 	}
1794 
1795 	pcu->ep_in = &alt->endpoint[1].desc;
1796 	if (!usb_endpoint_is_bulk_in(pcu->ep_in)) {
1797 		dev_err(pcu->dev,
1798 			"Second endpoint on data interface is not BULK IN\n");
1799 		return -EINVAL;
1800 	}
1801 
1802 	pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in);
1803 	if (pcu->max_in_size < 8) {
1804 		dev_err(pcu->dev,
1805 			"Max IN packet size is too small (%zd)\n",
1806 			pcu->max_in_size);
1807 		return -EINVAL;
1808 	}
1809 
1810 	return 0;
1811 }
1812 
1813 static int ims_pcu_start_io(struct ims_pcu *pcu)
1814 {
1815 	int error;
1816 
1817 	error = usb_submit_urb(pcu->urb_ctrl, GFP_KERNEL);
1818 	if (error) {
1819 		dev_err(pcu->dev,
1820 			"Failed to start control IO - usb_submit_urb failed with result: %d\n",
1821 			error);
1822 		return -EIO;
1823 	}
1824 
1825 	error = usb_submit_urb(pcu->urb_in, GFP_KERNEL);
1826 	if (error) {
1827 		dev_err(pcu->dev,
1828 			"Failed to start IO - usb_submit_urb failed with result: %d\n",
1829 			error);
1830 		usb_kill_urb(pcu->urb_ctrl);
1831 		return -EIO;
1832 	}
1833 
1834 	return 0;
1835 }
1836 
1837 static void ims_pcu_stop_io(struct ims_pcu *pcu)
1838 {
1839 	usb_kill_urb(pcu->urb_in);
1840 	usb_kill_urb(pcu->urb_ctrl);
1841 }
1842 
1843 static int ims_pcu_line_setup(struct ims_pcu *pcu)
1844 {
1845 	struct usb_host_interface *interface = pcu->ctrl_intf->cur_altsetting;
1846 	struct usb_cdc_line_coding *line __free(kfree) =
1847 				kmalloc(sizeof(*line), GFP_KERNEL);
1848 	int error;
1849 
1850 	if (!line)
1851 		return -ENOMEM;
1852 
1853 	line->dwDTERate = cpu_to_le32(57600);
1854 	line->bCharFormat = USB_CDC_1_STOP_BITS;
1855 	line->bParityType = USB_CDC_NO_PARITY;
1856 	line->bDataBits = 8;
1857 
1858 	error = usb_control_msg(pcu->udev, usb_sndctrlpipe(pcu->udev, 0),
1859 				USB_CDC_REQ_SET_LINE_CODING,
1860 				USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1861 				0, interface->desc.bInterfaceNumber,
1862 				line, sizeof(struct usb_cdc_line_coding),
1863 				5000);
1864 	if (error < 0) {
1865 		dev_err(pcu->dev, "Failed to set line coding, error: %d\n",
1866 			error);
1867 		return error;
1868 	}
1869 
1870 	error = usb_control_msg(pcu->udev, usb_sndctrlpipe(pcu->udev, 0),
1871 				USB_CDC_REQ_SET_CONTROL_LINE_STATE,
1872 				USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1873 				0x03, interface->desc.bInterfaceNumber,
1874 				NULL, 0, 5000);
1875 	if (error < 0) {
1876 		dev_err(pcu->dev, "Failed to set line state, error: %d\n",
1877 			error);
1878 		return error;
1879 	}
1880 
1881 	return 0;
1882 }
1883 
1884 static int ims_pcu_get_device_info(struct ims_pcu *pcu)
1885 {
1886 	int error;
1887 
1888 	error = ims_pcu_get_info(pcu);
1889 	if (error)
1890 		return error;
1891 
1892 	error = ims_pcu_execute_query(pcu, GET_FW_VERSION);
1893 	if (error) {
1894 		dev_err(pcu->dev,
1895 			"GET_FW_VERSION command failed, error: %d\n", error);
1896 		return error;
1897 	}
1898 
1899 	if (pcu->cmd_buf_len < IMS_PCU_DATA_OFFSET + 6 + 1) {
1900 		dev_err(pcu->dev, "Short GET_FW_VERSION response: %d bytes\n",
1901 			pcu->cmd_buf_len);
1902 		return -EIO;
1903 	}
1904 
1905 	snprintf(pcu->fw_version, sizeof(pcu->fw_version),
1906 		 "%02d%02d%02d%02d.%c%c",
1907 		 pcu->cmd_buf[2], pcu->cmd_buf[3], pcu->cmd_buf[4], pcu->cmd_buf[5],
1908 		 pcu->cmd_buf[6], pcu->cmd_buf[7]);
1909 
1910 	error = ims_pcu_execute_query(pcu, GET_BL_VERSION);
1911 	if (error) {
1912 		dev_err(pcu->dev,
1913 			"GET_BL_VERSION command failed, error: %d\n", error);
1914 		return error;
1915 	}
1916 
1917 	if (pcu->cmd_buf_len < IMS_PCU_DATA_OFFSET + 6 + 1) {
1918 		dev_err(pcu->dev, "Short GET_BL_VERSION response: %d bytes\n",
1919 			pcu->cmd_buf_len);
1920 		return -EIO;
1921 	}
1922 
1923 	snprintf(pcu->bl_version, sizeof(pcu->bl_version),
1924 		 "%02d%02d%02d%02d.%c%c",
1925 		 pcu->cmd_buf[2], pcu->cmd_buf[3], pcu->cmd_buf[4], pcu->cmd_buf[5],
1926 		 pcu->cmd_buf[6], pcu->cmd_buf[7]);
1927 
1928 	error = ims_pcu_execute_query(pcu, RESET_REASON);
1929 	if (error) {
1930 		dev_err(pcu->dev,
1931 			"RESET_REASON command failed, error: %d\n", error);
1932 		return error;
1933 	}
1934 
1935 	if (pcu->cmd_buf_len < IMS_PCU_DATA_OFFSET + 1 + 1) {
1936 		dev_err(pcu->dev, "Short RESET_REASON response: %d bytes\n",
1937 			pcu->cmd_buf_len);
1938 		return -EIO;
1939 	}
1940 
1941 	snprintf(pcu->reset_reason, sizeof(pcu->reset_reason),
1942 		 "%02x", pcu->cmd_buf[IMS_PCU_DATA_OFFSET]);
1943 
1944 	dev_dbg(pcu->dev,
1945 		"P/N: %s, MD: %s, S/N: %s, FW: %s, BL: %s, RR: %s\n",
1946 		pcu->part_number,
1947 		pcu->date_of_manufacturing,
1948 		pcu->serial_number,
1949 		pcu->fw_version,
1950 		pcu->bl_version,
1951 		pcu->reset_reason);
1952 
1953 	return 0;
1954 }
1955 
1956 static int ims_pcu_identify_type(struct ims_pcu *pcu, u8 *device_id)
1957 {
1958 	int error;
1959 
1960 	error = ims_pcu_execute_query(pcu, GET_DEVICE_ID);
1961 	if (error) {
1962 		dev_err(pcu->dev,
1963 			"GET_DEVICE_ID command failed, error: %d\n", error);
1964 		return error;
1965 	}
1966 
1967 	if (pcu->cmd_buf_len < IMS_PCU_DATA_OFFSET + 1 + 1) {
1968 		dev_err(pcu->dev, "Short GET_DEVICE_ID response: %d bytes\n",
1969 			pcu->cmd_buf_len);
1970 		return -EIO;
1971 	}
1972 
1973 	*device_id = pcu->cmd_buf[IMS_PCU_DATA_OFFSET];
1974 	dev_dbg(pcu->dev, "Detected device ID: %d\n", *device_id);
1975 
1976 	return 0;
1977 }
1978 
1979 static int ims_pcu_init_application_mode(struct ims_pcu *pcu)
1980 {
1981 	static atomic_t device_no = ATOMIC_INIT(-1);
1982 
1983 	const struct ims_pcu_device_info *info;
1984 	int error;
1985 
1986 	error = ims_pcu_get_device_info(pcu);
1987 	if (error) {
1988 		/* Device does not respond to basic queries, hopeless */
1989 		return error;
1990 	}
1991 
1992 	error = ims_pcu_identify_type(pcu, &pcu->device_id);
1993 	if (error) {
1994 		dev_err(pcu->dev,
1995 			"Failed to identify device, error: %d\n", error);
1996 		/*
1997 		 * Do not signal error, but do not create input nor
1998 		 * backlight devices either, let userspace figure this
1999 		 * out (flash a new firmware?).
2000 		 */
2001 		return 0;
2002 	}
2003 
2004 	if (pcu->device_id >= ARRAY_SIZE(ims_pcu_device_info) ||
2005 	    !ims_pcu_device_info[pcu->device_id].keymap) {
2006 		dev_err(pcu->dev, "Device ID %d is not valid\n", pcu->device_id);
2007 		/* Same as above, punt to userspace */
2008 		return 0;
2009 	}
2010 
2011 	/* Device appears to be operable, complete initialization */
2012 	pcu->device_no = atomic_inc_return(&device_no);
2013 
2014 	error = ims_pcu_setup_backlight(pcu);
2015 	if (error)
2016 		return error;
2017 
2018 	info = &ims_pcu_device_info[pcu->device_id];
2019 	error = ims_pcu_setup_buttons(pcu, info->keymap, info->keymap_len);
2020 	if (error)
2021 		goto err_destroy_backlight;
2022 
2023 	if (info->has_gamepad) {
2024 		error = ims_pcu_setup_gamepad(pcu);
2025 		if (error)
2026 			goto err_destroy_buttons;
2027 	}
2028 
2029 	pcu->setup_complete = true;
2030 
2031 	return 0;
2032 
2033 err_destroy_buttons:
2034 	ims_pcu_destroy_buttons(pcu);
2035 err_destroy_backlight:
2036 	ims_pcu_destroy_backlight(pcu);
2037 	return error;
2038 }
2039 
2040 static void ims_pcu_destroy_application_mode(struct ims_pcu *pcu)
2041 {
2042 	if (pcu->setup_complete) {
2043 		pcu->setup_complete = false;
2044 		mb(); /* make sure flag setting is not reordered */
2045 
2046 		if (pcu->gamepad)
2047 			ims_pcu_destroy_gamepad(pcu);
2048 		ims_pcu_destroy_buttons(pcu);
2049 		ims_pcu_destroy_backlight(pcu);
2050 	}
2051 }
2052 
2053 static int ims_pcu_init_bootloader_mode(struct ims_pcu *pcu)
2054 {
2055 	int error;
2056 
2057 	error = ims_pcu_execute_bl_command(pcu, QUERY_DEVICE, NULL, 0,
2058 					   IMS_PCU_CMD_RESPONSE_TIMEOUT);
2059 	if (error) {
2060 		dev_err(pcu->dev, "Bootloader does not respond, aborting\n");
2061 		return error;
2062 	}
2063 
2064 	if (pcu->cmd_buf_len < IMS_PCU_DATA_OFFSET + 15 + 4 + 1) {
2065 		dev_err(pcu->dev, "Short QUERY_DEVICE response: %d bytes\n",
2066 			pcu->cmd_buf_len);
2067 		return -EIO;
2068 	}
2069 
2070 	pcu->fw_start_addr =
2071 		get_unaligned_le32(&pcu->cmd_buf[IMS_PCU_DATA_OFFSET + 11]);
2072 	pcu->fw_end_addr =
2073 		get_unaligned_le32(&pcu->cmd_buf[IMS_PCU_DATA_OFFSET + 15]);
2074 
2075 	dev_info(pcu->dev,
2076 		 "Device is in bootloader mode (addr 0x%08x-0x%08x), requesting firmware\n",
2077 		 pcu->fw_start_addr, pcu->fw_end_addr);
2078 
2079 	error = request_firmware_nowait(THIS_MODULE, true,
2080 					IMS_PCU_FIRMWARE_NAME,
2081 					pcu->dev, GFP_KERNEL, pcu,
2082 					ims_pcu_process_async_firmware);
2083 	if (error) {
2084 		/* This error is not fatal, let userspace have another chance */
2085 		complete(&pcu->async_firmware_done);
2086 	}
2087 
2088 	return 0;
2089 }
2090 
2091 static void ims_pcu_destroy_bootloader_mode(struct ims_pcu *pcu)
2092 {
2093 	/* Make sure our initial firmware request has completed */
2094 	wait_for_completion(&pcu->async_firmware_done);
2095 }
2096 
2097 #define IMS_PCU_APPLICATION_MODE	0
2098 #define IMS_PCU_BOOTLOADER_MODE		1
2099 
2100 static struct usb_driver ims_pcu_driver;
2101 
2102 static int ims_pcu_probe(struct usb_interface *intf,
2103 			 const struct usb_device_id *id)
2104 {
2105 	struct usb_device *udev = interface_to_usbdev(intf);
2106 	struct ims_pcu *pcu;
2107 	int error;
2108 
2109 	pcu = kzalloc_obj(*pcu);
2110 	if (!pcu)
2111 		return -ENOMEM;
2112 
2113 	pcu->dev = &intf->dev;
2114 	pcu->udev = udev;
2115 	pcu->bootloader_mode = id->driver_info == IMS_PCU_BOOTLOADER_MODE;
2116 	mutex_init(&pcu->cmd_mutex);
2117 	init_completion(&pcu->cmd_done);
2118 	init_completion(&pcu->async_firmware_done);
2119 
2120 	error = ims_pcu_parse_cdc_data(intf, pcu);
2121 	if (error)
2122 		goto err_free_mem;
2123 
2124 	error = usb_driver_claim_interface(&ims_pcu_driver,
2125 					   pcu->data_intf, pcu);
2126 	if (error) {
2127 		dev_err(&intf->dev,
2128 			"Unable to claim corresponding data interface: %d\n",
2129 			error);
2130 		goto err_free_mem;
2131 	}
2132 
2133 	usb_set_intfdata(pcu->ctrl_intf, pcu);
2134 
2135 	error = ims_pcu_buffers_alloc(pcu);
2136 	if (error)
2137 		goto err_unclaim_intf;
2138 
2139 	error = ims_pcu_start_io(pcu);
2140 	if (error)
2141 		goto err_free_buffers;
2142 
2143 	error = ims_pcu_line_setup(pcu);
2144 	if (error)
2145 		goto err_stop_io;
2146 
2147 	error = pcu->bootloader_mode ?
2148 			ims_pcu_init_bootloader_mode(pcu) :
2149 			ims_pcu_init_application_mode(pcu);
2150 	if (error)
2151 		goto err_stop_io;
2152 
2153 	return 0;
2154 
2155 err_stop_io:
2156 	ims_pcu_stop_io(pcu);
2157 err_free_buffers:
2158 	ims_pcu_buffers_free(pcu);
2159 err_unclaim_intf:
2160 	usb_driver_release_interface(&ims_pcu_driver, pcu->data_intf);
2161 err_free_mem:
2162 	kfree(pcu);
2163 	return error;
2164 }
2165 
2166 static void ims_pcu_disconnect(struct usb_interface *intf)
2167 {
2168 	struct ims_pcu *pcu = usb_get_intfdata(intf);
2169 
2170 	usb_set_intfdata(intf, NULL);
2171 
2172 	/*
2173 	 * See if we are dealing with control or data interface. The cleanup
2174 	 * happens when we unbind primary (control) interface.
2175 	 */
2176 	if (intf != pcu->ctrl_intf)
2177 		return;
2178 
2179 	ims_pcu_stop_io(pcu);
2180 
2181 	if (pcu->bootloader_mode)
2182 		ims_pcu_destroy_bootloader_mode(pcu);
2183 	else
2184 		ims_pcu_destroy_application_mode(pcu);
2185 
2186 	ims_pcu_buffers_free(pcu);
2187 	usb_driver_release_interface(&ims_pcu_driver, pcu->data_intf);
2188 	kfree(pcu);
2189 }
2190 
2191 #ifdef CONFIG_PM
2192 static int ims_pcu_suspend(struct usb_interface *intf,
2193 			   pm_message_t message)
2194 {
2195 	struct ims_pcu *pcu = usb_get_intfdata(intf);
2196 	struct usb_host_interface *alt = intf->cur_altsetting;
2197 
2198 	if (alt->desc.bInterfaceClass == USB_CLASS_COMM)
2199 		ims_pcu_stop_io(pcu);
2200 
2201 	return 0;
2202 }
2203 
2204 static int ims_pcu_resume(struct usb_interface *intf)
2205 {
2206 	struct ims_pcu *pcu = usb_get_intfdata(intf);
2207 	struct usb_host_interface *alt = intf->cur_altsetting;
2208 	int retval = 0;
2209 
2210 	if (alt->desc.bInterfaceClass == USB_CLASS_COMM) {
2211 		retval = ims_pcu_start_io(pcu);
2212 		if (retval == 0)
2213 			retval = ims_pcu_line_setup(pcu);
2214 	}
2215 
2216 	return retval;
2217 }
2218 #endif
2219 
2220 static const struct usb_device_id ims_pcu_id_table[] = {
2221 	{
2222 		USB_DEVICE_AND_INTERFACE_INFO(0x04d8, 0x0082,
2223 					USB_CLASS_COMM,
2224 					USB_CDC_SUBCLASS_ACM,
2225 					USB_CDC_ACM_PROTO_AT_V25TER),
2226 		.driver_info = IMS_PCU_APPLICATION_MODE,
2227 	},
2228 	{
2229 		USB_DEVICE_AND_INTERFACE_INFO(0x04d8, 0x0083,
2230 					USB_CLASS_COMM,
2231 					USB_CDC_SUBCLASS_ACM,
2232 					USB_CDC_ACM_PROTO_AT_V25TER),
2233 		.driver_info = IMS_PCU_BOOTLOADER_MODE,
2234 	},
2235 	{ }
2236 };
2237 
2238 static const struct attribute_group *ims_pcu_sysfs_groups[] = {
2239 	&ims_pcu_attr_group,
2240 	&ims_pcu_ofn_attr_group,
2241 	NULL
2242 };
2243 
2244 static struct usb_driver ims_pcu_driver = {
2245 	.name			= "ims_pcu",
2246 	.id_table		= ims_pcu_id_table,
2247 	.dev_groups		= ims_pcu_sysfs_groups,
2248 	.probe			= ims_pcu_probe,
2249 	.disconnect		= ims_pcu_disconnect,
2250 #ifdef CONFIG_PM
2251 	.suspend		= ims_pcu_suspend,
2252 	.resume			= ims_pcu_resume,
2253 	.reset_resume		= ims_pcu_resume,
2254 #endif
2255 };
2256 
2257 module_usb_driver(ims_pcu_driver);
2258 
2259 MODULE_DESCRIPTION("IMS Passenger Control Unit driver");
2260 MODULE_AUTHOR("Dmitry Torokhov <dmitry.torokhov@gmail.com>");
2261 MODULE_LICENSE("GPL");
2262