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