Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Driver for IMS Passenger Control Unit Devices
0004  *
0005  * Copyright (C) 2013 The IMS Company
0006  */
0007 
0008 #include <linux/completion.h>
0009 #include <linux/device.h>
0010 #include <linux/firmware.h>
0011 #include <linux/ihex.h>
0012 #include <linux/input.h>
0013 #include <linux/kernel.h>
0014 #include <linux/leds.h>
0015 #include <linux/module.h>
0016 #include <linux/slab.h>
0017 #include <linux/types.h>
0018 #include <linux/usb/input.h>
0019 #include <linux/usb/cdc.h>
0020 #include <asm/unaligned.h>
0021 
0022 #define IMS_PCU_KEYMAP_LEN      32
0023 
0024 struct ims_pcu_buttons {
0025     struct input_dev *input;
0026     char name[32];
0027     char phys[32];
0028     unsigned short keymap[IMS_PCU_KEYMAP_LEN];
0029 };
0030 
0031 struct ims_pcu_gamepad {
0032     struct input_dev *input;
0033     char name[32];
0034     char phys[32];
0035 };
0036 
0037 struct ims_pcu_backlight {
0038     struct led_classdev cdev;
0039     char name[32];
0040 };
0041 
0042 #define IMS_PCU_PART_NUMBER_LEN     15
0043 #define IMS_PCU_SERIAL_NUMBER_LEN   8
0044 #define IMS_PCU_DOM_LEN         8
0045 #define IMS_PCU_FW_VERSION_LEN      (9 + 1)
0046 #define IMS_PCU_BL_VERSION_LEN      (9 + 1)
0047 #define IMS_PCU_BL_RESET_REASON_LEN (2 + 1)
0048 
0049 #define IMS_PCU_PCU_B_DEVICE_ID     5
0050 
0051 #define IMS_PCU_BUF_SIZE        128
0052 
0053 struct ims_pcu {
0054     struct usb_device *udev;
0055     struct device *dev; /* control interface's device, used for logging */
0056 
0057     unsigned int device_no;
0058 
0059     bool bootloader_mode;
0060 
0061     char part_number[IMS_PCU_PART_NUMBER_LEN];
0062     char serial_number[IMS_PCU_SERIAL_NUMBER_LEN];
0063     char date_of_manufacturing[IMS_PCU_DOM_LEN];
0064     char fw_version[IMS_PCU_FW_VERSION_LEN];
0065     char bl_version[IMS_PCU_BL_VERSION_LEN];
0066     char reset_reason[IMS_PCU_BL_RESET_REASON_LEN];
0067     int update_firmware_status;
0068     u8 device_id;
0069 
0070     u8 ofn_reg_addr;
0071 
0072     struct usb_interface *ctrl_intf;
0073 
0074     struct usb_endpoint_descriptor *ep_ctrl;
0075     struct urb *urb_ctrl;
0076     u8 *urb_ctrl_buf;
0077     dma_addr_t ctrl_dma;
0078     size_t max_ctrl_size;
0079 
0080     struct usb_interface *data_intf;
0081 
0082     struct usb_endpoint_descriptor *ep_in;
0083     struct urb *urb_in;
0084     u8 *urb_in_buf;
0085     dma_addr_t read_dma;
0086     size_t max_in_size;
0087 
0088     struct usb_endpoint_descriptor *ep_out;
0089     u8 *urb_out_buf;
0090     size_t max_out_size;
0091 
0092     u8 read_buf[IMS_PCU_BUF_SIZE];
0093     u8 read_pos;
0094     u8 check_sum;
0095     bool have_stx;
0096     bool have_dle;
0097 
0098     u8 cmd_buf[IMS_PCU_BUF_SIZE];
0099     u8 ack_id;
0100     u8 expected_response;
0101     u8 cmd_buf_len;
0102     struct completion cmd_done;
0103     struct mutex cmd_mutex;
0104 
0105     u32 fw_start_addr;
0106     u32 fw_end_addr;
0107     struct completion async_firmware_done;
0108 
0109     struct ims_pcu_buttons buttons;
0110     struct ims_pcu_gamepad *gamepad;
0111     struct ims_pcu_backlight backlight;
0112 
0113     bool setup_complete; /* Input and LED devices have been created */
0114 };
0115 
0116 
0117 /*********************************************************************
0118  *             Buttons Input device support                          *
0119  *********************************************************************/
0120 
0121 static const unsigned short ims_pcu_keymap_1[] = {
0122     [1] = KEY_ATTENDANT_OFF,
0123     [2] = KEY_ATTENDANT_ON,
0124     [3] = KEY_LIGHTS_TOGGLE,
0125     [4] = KEY_VOLUMEUP,
0126     [5] = KEY_VOLUMEDOWN,
0127     [6] = KEY_INFO,
0128 };
0129 
0130 static const unsigned short ims_pcu_keymap_2[] = {
0131     [4] = KEY_VOLUMEUP,
0132     [5] = KEY_VOLUMEDOWN,
0133     [6] = KEY_INFO,
0134 };
0135 
0136 static const unsigned short ims_pcu_keymap_3[] = {
0137     [1] = KEY_HOMEPAGE,
0138     [2] = KEY_ATTENDANT_TOGGLE,
0139     [3] = KEY_LIGHTS_TOGGLE,
0140     [4] = KEY_VOLUMEUP,
0141     [5] = KEY_VOLUMEDOWN,
0142     [6] = KEY_DISPLAYTOGGLE,
0143     [18] = KEY_PLAYPAUSE,
0144 };
0145 
0146 static const unsigned short ims_pcu_keymap_4[] = {
0147     [1] = KEY_ATTENDANT_OFF,
0148     [2] = KEY_ATTENDANT_ON,
0149     [3] = KEY_LIGHTS_TOGGLE,
0150     [4] = KEY_VOLUMEUP,
0151     [5] = KEY_VOLUMEDOWN,
0152     [6] = KEY_INFO,
0153     [18] = KEY_PLAYPAUSE,
0154 };
0155 
0156 static const unsigned short ims_pcu_keymap_5[] = {
0157     [1] = KEY_ATTENDANT_OFF,
0158     [2] = KEY_ATTENDANT_ON,
0159     [3] = KEY_LIGHTS_TOGGLE,
0160 };
0161 
0162 struct ims_pcu_device_info {
0163     const unsigned short *keymap;
0164     size_t keymap_len;
0165     bool has_gamepad;
0166 };
0167 
0168 #define IMS_PCU_DEVINFO(_n, _gamepad)               \
0169     [_n] = {                        \
0170         .keymap = ims_pcu_keymap_##_n,          \
0171         .keymap_len = ARRAY_SIZE(ims_pcu_keymap_##_n),  \
0172         .has_gamepad = _gamepad,            \
0173     }
0174 
0175 static const struct ims_pcu_device_info ims_pcu_device_info[] = {
0176     IMS_PCU_DEVINFO(1, true),
0177     IMS_PCU_DEVINFO(2, true),
0178     IMS_PCU_DEVINFO(3, true),
0179     IMS_PCU_DEVINFO(4, true),
0180     IMS_PCU_DEVINFO(5, false),
0181 };
0182 
0183 static void ims_pcu_buttons_report(struct ims_pcu *pcu, u32 data)
0184 {
0185     struct ims_pcu_buttons *buttons = &pcu->buttons;
0186     struct input_dev *input = buttons->input;
0187     int i;
0188 
0189     for (i = 0; i < 32; i++) {
0190         unsigned short keycode = buttons->keymap[i];
0191 
0192         if (keycode != KEY_RESERVED)
0193             input_report_key(input, keycode, data & (1UL << i));
0194     }
0195 
0196     input_sync(input);
0197 }
0198 
0199 static int ims_pcu_setup_buttons(struct ims_pcu *pcu,
0200                  const unsigned short *keymap,
0201                  size_t keymap_len)
0202 {
0203     struct ims_pcu_buttons *buttons = &pcu->buttons;
0204     struct input_dev *input;
0205     int i;
0206     int error;
0207 
0208     input = input_allocate_device();
0209     if (!input) {
0210         dev_err(pcu->dev,
0211             "Not enough memory for input input device\n");
0212         return -ENOMEM;
0213     }
0214 
0215     snprintf(buttons->name, sizeof(buttons->name),
0216          "IMS PCU#%d Button Interface", pcu->device_no);
0217 
0218     usb_make_path(pcu->udev, buttons->phys, sizeof(buttons->phys));
0219     strlcat(buttons->phys, "/input0", sizeof(buttons->phys));
0220 
0221     memcpy(buttons->keymap, keymap, sizeof(*keymap) * keymap_len);
0222 
0223     input->name = buttons->name;
0224     input->phys = buttons->phys;
0225     usb_to_input_id(pcu->udev, &input->id);
0226     input->dev.parent = &pcu->ctrl_intf->dev;
0227 
0228     input->keycode = buttons->keymap;
0229     input->keycodemax = ARRAY_SIZE(buttons->keymap);
0230     input->keycodesize = sizeof(buttons->keymap[0]);
0231 
0232     __set_bit(EV_KEY, input->evbit);
0233     for (i = 0; i < IMS_PCU_KEYMAP_LEN; i++)
0234         __set_bit(buttons->keymap[i], input->keybit);
0235     __clear_bit(KEY_RESERVED, input->keybit);
0236 
0237     error = input_register_device(input);
0238     if (error) {
0239         dev_err(pcu->dev,
0240             "Failed to register buttons input device: %d\n",
0241             error);
0242         input_free_device(input);
0243         return error;
0244     }
0245 
0246     buttons->input = input;
0247     return 0;
0248 }
0249 
0250 static void ims_pcu_destroy_buttons(struct ims_pcu *pcu)
0251 {
0252     struct ims_pcu_buttons *buttons = &pcu->buttons;
0253 
0254     input_unregister_device(buttons->input);
0255 }
0256 
0257 
0258 /*********************************************************************
0259  *             Gamepad Input device support                          *
0260  *********************************************************************/
0261 
0262 static void ims_pcu_gamepad_report(struct ims_pcu *pcu, u32 data)
0263 {
0264     struct ims_pcu_gamepad *gamepad = pcu->gamepad;
0265     struct input_dev *input = gamepad->input;
0266     int x, y;
0267 
0268     x = !!(data & (1 << 14)) - !!(data & (1 << 13));
0269     y = !!(data & (1 << 12)) - !!(data & (1 << 11));
0270 
0271     input_report_abs(input, ABS_X, x);
0272     input_report_abs(input, ABS_Y, y);
0273 
0274     input_report_key(input, BTN_A, data & (1 << 7));
0275     input_report_key(input, BTN_B, data & (1 << 8));
0276     input_report_key(input, BTN_X, data & (1 << 9));
0277     input_report_key(input, BTN_Y, data & (1 << 10));
0278     input_report_key(input, BTN_START, data & (1 << 15));
0279     input_report_key(input, BTN_SELECT, data & (1 << 16));
0280 
0281     input_sync(input);
0282 }
0283 
0284 static int ims_pcu_setup_gamepad(struct ims_pcu *pcu)
0285 {
0286     struct ims_pcu_gamepad *gamepad;
0287     struct input_dev *input;
0288     int error;
0289 
0290     gamepad = kzalloc(sizeof(struct ims_pcu_gamepad), GFP_KERNEL);
0291     input = input_allocate_device();
0292     if (!gamepad || !input) {
0293         dev_err(pcu->dev,
0294             "Not enough memory for gamepad device\n");
0295         error = -ENOMEM;
0296         goto err_free_mem;
0297     }
0298 
0299     gamepad->input = input;
0300 
0301     snprintf(gamepad->name, sizeof(gamepad->name),
0302          "IMS PCU#%d Gamepad Interface", pcu->device_no);
0303 
0304     usb_make_path(pcu->udev, gamepad->phys, sizeof(gamepad->phys));
0305     strlcat(gamepad->phys, "/input1", sizeof(gamepad->phys));
0306 
0307     input->name = gamepad->name;
0308     input->phys = gamepad->phys;
0309     usb_to_input_id(pcu->udev, &input->id);
0310     input->dev.parent = &pcu->ctrl_intf->dev;
0311 
0312     __set_bit(EV_KEY, input->evbit);
0313     __set_bit(BTN_A, input->keybit);
0314     __set_bit(BTN_B, input->keybit);
0315     __set_bit(BTN_X, input->keybit);
0316     __set_bit(BTN_Y, input->keybit);
0317     __set_bit(BTN_START, input->keybit);
0318     __set_bit(BTN_SELECT, input->keybit);
0319 
0320     __set_bit(EV_ABS, input->evbit);
0321     input_set_abs_params(input, ABS_X, -1, 1, 0, 0);
0322     input_set_abs_params(input, ABS_Y, -1, 1, 0, 0);
0323 
0324     error = input_register_device(input);
0325     if (error) {
0326         dev_err(pcu->dev,
0327             "Failed to register gamepad input device: %d\n",
0328             error);
0329         goto err_free_mem;
0330     }
0331 
0332     pcu->gamepad = gamepad;
0333     return 0;
0334 
0335 err_free_mem:
0336     input_free_device(input);
0337     kfree(gamepad);
0338     return error;
0339 }
0340 
0341 static void ims_pcu_destroy_gamepad(struct ims_pcu *pcu)
0342 {
0343     struct ims_pcu_gamepad *gamepad = pcu->gamepad;
0344 
0345     input_unregister_device(gamepad->input);
0346     kfree(gamepad);
0347 }
0348 
0349 
0350 /*********************************************************************
0351  *             PCU Communication protocol handling                   *
0352  *********************************************************************/
0353 
0354 #define IMS_PCU_PROTOCOL_STX        0x02
0355 #define IMS_PCU_PROTOCOL_ETX        0x03
0356 #define IMS_PCU_PROTOCOL_DLE        0x10
0357 
0358 /* PCU commands */
0359 #define IMS_PCU_CMD_STATUS      0xa0
0360 #define IMS_PCU_CMD_PCU_RESET       0xa1
0361 #define IMS_PCU_CMD_RESET_REASON    0xa2
0362 #define IMS_PCU_CMD_SEND_BUTTONS    0xa3
0363 #define IMS_PCU_CMD_JUMP_TO_BTLDR   0xa4
0364 #define IMS_PCU_CMD_GET_INFO        0xa5
0365 #define IMS_PCU_CMD_SET_BRIGHTNESS  0xa6
0366 #define IMS_PCU_CMD_EEPROM      0xa7
0367 #define IMS_PCU_CMD_GET_FW_VERSION  0xa8
0368 #define IMS_PCU_CMD_GET_BL_VERSION  0xa9
0369 #define IMS_PCU_CMD_SET_INFO        0xab
0370 #define IMS_PCU_CMD_GET_BRIGHTNESS  0xac
0371 #define IMS_PCU_CMD_GET_DEVICE_ID   0xae
0372 #define IMS_PCU_CMD_SPECIAL_INFO    0xb0
0373 #define IMS_PCU_CMD_BOOTLOADER      0xb1    /* Pass data to bootloader */
0374 #define IMS_PCU_CMD_OFN_SET_CONFIG  0xb3
0375 #define IMS_PCU_CMD_OFN_GET_CONFIG  0xb4
0376 
0377 /* PCU responses */
0378 #define IMS_PCU_RSP_STATUS      0xc0
0379 #define IMS_PCU_RSP_PCU_RESET       0   /* Originally 0xc1 */
0380 #define IMS_PCU_RSP_RESET_REASON    0xc2
0381 #define IMS_PCU_RSP_SEND_BUTTONS    0xc3
0382 #define IMS_PCU_RSP_JUMP_TO_BTLDR   0   /* Originally 0xc4 */
0383 #define IMS_PCU_RSP_GET_INFO        0xc5
0384 #define IMS_PCU_RSP_SET_BRIGHTNESS  0xc6
0385 #define IMS_PCU_RSP_EEPROM      0xc7
0386 #define IMS_PCU_RSP_GET_FW_VERSION  0xc8
0387 #define IMS_PCU_RSP_GET_BL_VERSION  0xc9
0388 #define IMS_PCU_RSP_SET_INFO        0xcb
0389 #define IMS_PCU_RSP_GET_BRIGHTNESS  0xcc
0390 #define IMS_PCU_RSP_CMD_INVALID     0xcd
0391 #define IMS_PCU_RSP_GET_DEVICE_ID   0xce
0392 #define IMS_PCU_RSP_SPECIAL_INFO    0xd0
0393 #define IMS_PCU_RSP_BOOTLOADER      0xd1    /* Bootloader response */
0394 #define IMS_PCU_RSP_OFN_SET_CONFIG  0xd2
0395 #define IMS_PCU_RSP_OFN_GET_CONFIG  0xd3
0396 
0397 
0398 #define IMS_PCU_RSP_EVNT_BUTTONS    0xe0    /* Unsolicited, button state */
0399 #define IMS_PCU_GAMEPAD_MASK        0x0001ff80UL    /* Bits 7 through 16 */
0400 
0401 
0402 #define IMS_PCU_MIN_PACKET_LEN      3
0403 #define IMS_PCU_DATA_OFFSET     2
0404 
0405 #define IMS_PCU_CMD_WRITE_TIMEOUT   100 /* msec */
0406 #define IMS_PCU_CMD_RESPONSE_TIMEOUT    500 /* msec */
0407 
0408 static void ims_pcu_report_events(struct ims_pcu *pcu)
0409 {
0410     u32 data = get_unaligned_be32(&pcu->read_buf[3]);
0411 
0412     ims_pcu_buttons_report(pcu, data & ~IMS_PCU_GAMEPAD_MASK);
0413     if (pcu->gamepad)
0414         ims_pcu_gamepad_report(pcu, data);
0415 }
0416 
0417 static void ims_pcu_handle_response(struct ims_pcu *pcu)
0418 {
0419     switch (pcu->read_buf[0]) {
0420     case IMS_PCU_RSP_EVNT_BUTTONS:
0421         if (likely(pcu->setup_complete))
0422             ims_pcu_report_events(pcu);
0423         break;
0424 
0425     default:
0426         /*
0427          * See if we got command completion.
0428          * If both the sequence and response code match save
0429          * the data and signal completion.
0430          */
0431         if (pcu->read_buf[0] == pcu->expected_response &&
0432             pcu->read_buf[1] == pcu->ack_id - 1) {
0433 
0434             memcpy(pcu->cmd_buf, pcu->read_buf, pcu->read_pos);
0435             pcu->cmd_buf_len = pcu->read_pos;
0436             complete(&pcu->cmd_done);
0437         }
0438         break;
0439     }
0440 }
0441 
0442 static void ims_pcu_process_data(struct ims_pcu *pcu, struct urb *urb)
0443 {
0444     int i;
0445 
0446     for (i = 0; i < urb->actual_length; i++) {
0447         u8 data = pcu->urb_in_buf[i];
0448 
0449         /* Skip everything until we get Start Xmit */
0450         if (!pcu->have_stx && data != IMS_PCU_PROTOCOL_STX)
0451             continue;
0452 
0453         if (pcu->have_dle) {
0454             pcu->have_dle = false;
0455             pcu->read_buf[pcu->read_pos++] = data;
0456             pcu->check_sum += data;
0457             continue;
0458         }
0459 
0460         switch (data) {
0461         case IMS_PCU_PROTOCOL_STX:
0462             if (pcu->have_stx)
0463                 dev_warn(pcu->dev,
0464                      "Unexpected STX at byte %d, discarding old data\n",
0465                      pcu->read_pos);
0466             pcu->have_stx = true;
0467             pcu->have_dle = false;
0468             pcu->read_pos = 0;
0469             pcu->check_sum = 0;
0470             break;
0471 
0472         case IMS_PCU_PROTOCOL_DLE:
0473             pcu->have_dle = true;
0474             break;
0475 
0476         case IMS_PCU_PROTOCOL_ETX:
0477             if (pcu->read_pos < IMS_PCU_MIN_PACKET_LEN) {
0478                 dev_warn(pcu->dev,
0479                      "Short packet received (%d bytes), ignoring\n",
0480                      pcu->read_pos);
0481             } else if (pcu->check_sum != 0) {
0482                 dev_warn(pcu->dev,
0483                      "Invalid checksum in packet (%d bytes), ignoring\n",
0484                      pcu->read_pos);
0485             } else {
0486                 ims_pcu_handle_response(pcu);
0487             }
0488 
0489             pcu->have_stx = false;
0490             pcu->have_dle = false;
0491             pcu->read_pos = 0;
0492             break;
0493 
0494         default:
0495             pcu->read_buf[pcu->read_pos++] = data;
0496             pcu->check_sum += data;
0497             break;
0498         }
0499     }
0500 }
0501 
0502 static bool ims_pcu_byte_needs_escape(u8 byte)
0503 {
0504     return byte == IMS_PCU_PROTOCOL_STX ||
0505            byte == IMS_PCU_PROTOCOL_ETX ||
0506            byte == IMS_PCU_PROTOCOL_DLE;
0507 }
0508 
0509 static int ims_pcu_send_cmd_chunk(struct ims_pcu *pcu,
0510                   u8 command, int chunk, int len)
0511 {
0512     int error;
0513 
0514     error = usb_bulk_msg(pcu->udev,
0515                  usb_sndbulkpipe(pcu->udev,
0516                          pcu->ep_out->bEndpointAddress),
0517                  pcu->urb_out_buf, len,
0518                  NULL, IMS_PCU_CMD_WRITE_TIMEOUT);
0519     if (error < 0) {
0520         dev_dbg(pcu->dev,
0521             "Sending 0x%02x command failed at chunk %d: %d\n",
0522             command, chunk, error);
0523         return error;
0524     }
0525 
0526     return 0;
0527 }
0528 
0529 static int ims_pcu_send_command(struct ims_pcu *pcu,
0530                 u8 command, const u8 *data, int len)
0531 {
0532     int count = 0;
0533     int chunk = 0;
0534     int delta;
0535     int i;
0536     int error;
0537     u8 csum = 0;
0538     u8 ack_id;
0539 
0540     pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_STX;
0541 
0542     /* We know the command need not be escaped */
0543     pcu->urb_out_buf[count++] = command;
0544     csum += command;
0545 
0546     ack_id = pcu->ack_id++;
0547     if (ack_id == 0xff)
0548         ack_id = pcu->ack_id++;
0549 
0550     if (ims_pcu_byte_needs_escape(ack_id))
0551         pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_DLE;
0552 
0553     pcu->urb_out_buf[count++] = ack_id;
0554     csum += ack_id;
0555 
0556     for (i = 0; i < len; i++) {
0557 
0558         delta = ims_pcu_byte_needs_escape(data[i]) ? 2 : 1;
0559         if (count + delta >= pcu->max_out_size) {
0560             error = ims_pcu_send_cmd_chunk(pcu, command,
0561                                ++chunk, count);
0562             if (error)
0563                 return error;
0564 
0565             count = 0;
0566         }
0567 
0568         if (delta == 2)
0569             pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_DLE;
0570 
0571         pcu->urb_out_buf[count++] = data[i];
0572         csum += data[i];
0573     }
0574 
0575     csum = 1 + ~csum;
0576 
0577     delta = ims_pcu_byte_needs_escape(csum) ? 3 : 2;
0578     if (count + delta >= pcu->max_out_size) {
0579         error = ims_pcu_send_cmd_chunk(pcu, command, ++chunk, count);
0580         if (error)
0581             return error;
0582 
0583         count = 0;
0584     }
0585 
0586     if (delta == 3)
0587         pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_DLE;
0588 
0589     pcu->urb_out_buf[count++] = csum;
0590     pcu->urb_out_buf[count++] = IMS_PCU_PROTOCOL_ETX;
0591 
0592     return ims_pcu_send_cmd_chunk(pcu, command, ++chunk, count);
0593 }
0594 
0595 static int __ims_pcu_execute_command(struct ims_pcu *pcu,
0596                      u8 command, const void *data, size_t len,
0597                      u8 expected_response, int response_time)
0598 {
0599     int error;
0600 
0601     pcu->expected_response = expected_response;
0602     init_completion(&pcu->cmd_done);
0603 
0604     error = ims_pcu_send_command(pcu, command, data, len);
0605     if (error)
0606         return error;
0607 
0608     if (expected_response &&
0609         !wait_for_completion_timeout(&pcu->cmd_done,
0610                      msecs_to_jiffies(response_time))) {
0611         dev_dbg(pcu->dev, "Command 0x%02x timed out\n", command);
0612         return -ETIMEDOUT;
0613     }
0614 
0615     return 0;
0616 }
0617 
0618 #define ims_pcu_execute_command(pcu, code, data, len)           \
0619     __ims_pcu_execute_command(pcu,                  \
0620                   IMS_PCU_CMD_##code, data, len,    \
0621                   IMS_PCU_RSP_##code,           \
0622                   IMS_PCU_CMD_RESPONSE_TIMEOUT)
0623 
0624 #define ims_pcu_execute_query(pcu, code)                \
0625     ims_pcu_execute_command(pcu, code, NULL, 0)
0626 
0627 /* Bootloader commands */
0628 #define IMS_PCU_BL_CMD_QUERY_DEVICE 0xa1
0629 #define IMS_PCU_BL_CMD_UNLOCK_CONFIG    0xa2
0630 #define IMS_PCU_BL_CMD_ERASE_APP    0xa3
0631 #define IMS_PCU_BL_CMD_PROGRAM_DEVICE   0xa4
0632 #define IMS_PCU_BL_CMD_PROGRAM_COMPLETE 0xa5
0633 #define IMS_PCU_BL_CMD_READ_APP     0xa6
0634 #define IMS_PCU_BL_CMD_RESET_DEVICE 0xa7
0635 #define IMS_PCU_BL_CMD_LAUNCH_APP   0xa8
0636 
0637 /* Bootloader commands */
0638 #define IMS_PCU_BL_RSP_QUERY_DEVICE 0xc1
0639 #define IMS_PCU_BL_RSP_UNLOCK_CONFIG    0xc2
0640 #define IMS_PCU_BL_RSP_ERASE_APP    0xc3
0641 #define IMS_PCU_BL_RSP_PROGRAM_DEVICE   0xc4
0642 #define IMS_PCU_BL_RSP_PROGRAM_COMPLETE 0xc5
0643 #define IMS_PCU_BL_RSP_READ_APP     0xc6
0644 #define IMS_PCU_BL_RSP_RESET_DEVICE 0   /* originally 0xa7 */
0645 #define IMS_PCU_BL_RSP_LAUNCH_APP   0   /* originally 0xa8 */
0646 
0647 #define IMS_PCU_BL_DATA_OFFSET      3
0648 
0649 static int __ims_pcu_execute_bl_command(struct ims_pcu *pcu,
0650                     u8 command, const void *data, size_t len,
0651                     u8 expected_response, int response_time)
0652 {
0653     int error;
0654 
0655     pcu->cmd_buf[0] = command;
0656     if (data)
0657         memcpy(&pcu->cmd_buf[1], data, len);
0658 
0659     error = __ims_pcu_execute_command(pcu,
0660                 IMS_PCU_CMD_BOOTLOADER, pcu->cmd_buf, len + 1,
0661                 expected_response ? IMS_PCU_RSP_BOOTLOADER : 0,
0662                 response_time);
0663     if (error) {
0664         dev_err(pcu->dev,
0665             "Failure when sending 0x%02x command to bootloader, error: %d\n",
0666             pcu->cmd_buf[0], error);
0667         return error;
0668     }
0669 
0670     if (expected_response && pcu->cmd_buf[2] != expected_response) {
0671         dev_err(pcu->dev,
0672             "Unexpected response from bootloader: 0x%02x, wanted 0x%02x\n",
0673             pcu->cmd_buf[2], expected_response);
0674         return -EINVAL;
0675     }
0676 
0677     return 0;
0678 }
0679 
0680 #define ims_pcu_execute_bl_command(pcu, code, data, len, timeout)   \
0681     __ims_pcu_execute_bl_command(pcu,               \
0682                      IMS_PCU_BL_CMD_##code, data, len,  \
0683                      IMS_PCU_BL_RSP_##code, timeout)    \
0684 
0685 #define IMS_PCU_INFO_PART_OFFSET    2
0686 #define IMS_PCU_INFO_DOM_OFFSET     17
0687 #define IMS_PCU_INFO_SERIAL_OFFSET  25
0688 
0689 #define IMS_PCU_SET_INFO_SIZE       31
0690 
0691 static int ims_pcu_get_info(struct ims_pcu *pcu)
0692 {
0693     int error;
0694 
0695     error = ims_pcu_execute_query(pcu, GET_INFO);
0696     if (error) {
0697         dev_err(pcu->dev,
0698             "GET_INFO command failed, error: %d\n", error);
0699         return error;
0700     }
0701 
0702     memcpy(pcu->part_number,
0703            &pcu->cmd_buf[IMS_PCU_INFO_PART_OFFSET],
0704            sizeof(pcu->part_number));
0705     memcpy(pcu->date_of_manufacturing,
0706            &pcu->cmd_buf[IMS_PCU_INFO_DOM_OFFSET],
0707            sizeof(pcu->date_of_manufacturing));
0708     memcpy(pcu->serial_number,
0709            &pcu->cmd_buf[IMS_PCU_INFO_SERIAL_OFFSET],
0710            sizeof(pcu->serial_number));
0711 
0712     return 0;
0713 }
0714 
0715 static int ims_pcu_set_info(struct ims_pcu *pcu)
0716 {
0717     int error;
0718 
0719     memcpy(&pcu->cmd_buf[IMS_PCU_INFO_PART_OFFSET],
0720            pcu->part_number, sizeof(pcu->part_number));
0721     memcpy(&pcu->cmd_buf[IMS_PCU_INFO_DOM_OFFSET],
0722            pcu->date_of_manufacturing, sizeof(pcu->date_of_manufacturing));
0723     memcpy(&pcu->cmd_buf[IMS_PCU_INFO_SERIAL_OFFSET],
0724            pcu->serial_number, sizeof(pcu->serial_number));
0725 
0726     error = ims_pcu_execute_command(pcu, SET_INFO,
0727                     &pcu->cmd_buf[IMS_PCU_DATA_OFFSET],
0728                     IMS_PCU_SET_INFO_SIZE);
0729     if (error) {
0730         dev_err(pcu->dev,
0731             "Failed to update device information, error: %d\n",
0732             error);
0733         return error;
0734     }
0735 
0736     return 0;
0737 }
0738 
0739 static int ims_pcu_switch_to_bootloader(struct ims_pcu *pcu)
0740 {
0741     int error;
0742 
0743     /* Execute jump to the bootoloader */
0744     error = ims_pcu_execute_command(pcu, JUMP_TO_BTLDR, NULL, 0);
0745     if (error) {
0746         dev_err(pcu->dev,
0747             "Failure when sending JUMP TO BOOLTLOADER command, error: %d\n",
0748             error);
0749         return error;
0750     }
0751 
0752     return 0;
0753 }
0754 
0755 /*********************************************************************
0756  *             Firmware Update handling                              *
0757  *********************************************************************/
0758 
0759 #define IMS_PCU_FIRMWARE_NAME   "imspcu.fw"
0760 
0761 struct ims_pcu_flash_fmt {
0762     __le32 addr;
0763     u8 len;
0764     u8 data[];
0765 };
0766 
0767 static unsigned int ims_pcu_count_fw_records(const struct firmware *fw)
0768 {
0769     const struct ihex_binrec *rec = (const struct ihex_binrec *)fw->data;
0770     unsigned int count = 0;
0771 
0772     while (rec) {
0773         count++;
0774         rec = ihex_next_binrec(rec);
0775     }
0776 
0777     return count;
0778 }
0779 
0780 static int ims_pcu_verify_block(struct ims_pcu *pcu,
0781                 u32 addr, u8 len, const u8 *data)
0782 {
0783     struct ims_pcu_flash_fmt *fragment;
0784     int error;
0785 
0786     fragment = (void *)&pcu->cmd_buf[1];
0787     put_unaligned_le32(addr, &fragment->addr);
0788     fragment->len = len;
0789 
0790     error = ims_pcu_execute_bl_command(pcu, READ_APP, NULL, 5,
0791                     IMS_PCU_CMD_RESPONSE_TIMEOUT);
0792     if (error) {
0793         dev_err(pcu->dev,
0794             "Failed to retrieve block at 0x%08x, len %d, error: %d\n",
0795             addr, len, error);
0796         return error;
0797     }
0798 
0799     fragment = (void *)&pcu->cmd_buf[IMS_PCU_BL_DATA_OFFSET];
0800     if (get_unaligned_le32(&fragment->addr) != addr ||
0801         fragment->len != len) {
0802         dev_err(pcu->dev,
0803             "Wrong block when retrieving 0x%08x (0x%08x), len %d (%d)\n",
0804             addr, get_unaligned_le32(&fragment->addr),
0805             len, fragment->len);
0806         return -EINVAL;
0807     }
0808 
0809     if (memcmp(fragment->data, data, len)) {
0810         dev_err(pcu->dev,
0811             "Mismatch in block at 0x%08x, len %d\n",
0812             addr, len);
0813         return -EINVAL;
0814     }
0815 
0816     return 0;
0817 }
0818 
0819 static int ims_pcu_flash_firmware(struct ims_pcu *pcu,
0820                   const struct firmware *fw,
0821                   unsigned int n_fw_records)
0822 {
0823     const struct ihex_binrec *rec = (const struct ihex_binrec *)fw->data;
0824     struct ims_pcu_flash_fmt *fragment;
0825     unsigned int count = 0;
0826     u32 addr;
0827     u8 len;
0828     int error;
0829 
0830     error = ims_pcu_execute_bl_command(pcu, ERASE_APP, NULL, 0, 2000);
0831     if (error) {
0832         dev_err(pcu->dev,
0833             "Failed to erase application image, error: %d\n",
0834             error);
0835         return error;
0836     }
0837 
0838     while (rec) {
0839         /*
0840          * The firmware format is messed up for some reason.
0841          * The address twice that of what is needed for some
0842          * reason and we end up overwriting half of the data
0843          * with the next record.
0844          */
0845         addr = be32_to_cpu(rec->addr) / 2;
0846         len = be16_to_cpu(rec->len);
0847 
0848         fragment = (void *)&pcu->cmd_buf[1];
0849         put_unaligned_le32(addr, &fragment->addr);
0850         fragment->len = len;
0851         memcpy(fragment->data, rec->data, len);
0852 
0853         error = ims_pcu_execute_bl_command(pcu, PROGRAM_DEVICE,
0854                         NULL, len + 5,
0855                         IMS_PCU_CMD_RESPONSE_TIMEOUT);
0856         if (error) {
0857             dev_err(pcu->dev,
0858                 "Failed to write block at 0x%08x, len %d, error: %d\n",
0859                 addr, len, error);
0860             return error;
0861         }
0862 
0863         if (addr >= pcu->fw_start_addr && addr < pcu->fw_end_addr) {
0864             error = ims_pcu_verify_block(pcu, addr, len, rec->data);
0865             if (error)
0866                 return error;
0867         }
0868 
0869         count++;
0870         pcu->update_firmware_status = (count * 100) / n_fw_records;
0871 
0872         rec = ihex_next_binrec(rec);
0873     }
0874 
0875     error = ims_pcu_execute_bl_command(pcu, PROGRAM_COMPLETE,
0876                         NULL, 0, 2000);
0877     if (error)
0878         dev_err(pcu->dev,
0879             "Failed to send PROGRAM_COMPLETE, error: %d\n",
0880             error);
0881 
0882     return 0;
0883 }
0884 
0885 static int ims_pcu_handle_firmware_update(struct ims_pcu *pcu,
0886                       const struct firmware *fw)
0887 {
0888     unsigned int n_fw_records;
0889     int retval;
0890 
0891     dev_info(pcu->dev, "Updating firmware %s, size: %zu\n",
0892          IMS_PCU_FIRMWARE_NAME, fw->size);
0893 
0894     n_fw_records = ims_pcu_count_fw_records(fw);
0895 
0896     retval = ims_pcu_flash_firmware(pcu, fw, n_fw_records);
0897     if (retval)
0898         goto out;
0899 
0900     retval = ims_pcu_execute_bl_command(pcu, LAUNCH_APP, NULL, 0, 0);
0901     if (retval)
0902         dev_err(pcu->dev,
0903             "Failed to start application image, error: %d\n",
0904             retval);
0905 
0906 out:
0907     pcu->update_firmware_status = retval;
0908     sysfs_notify(&pcu->dev->kobj, NULL, "update_firmware_status");
0909     return retval;
0910 }
0911 
0912 static void ims_pcu_process_async_firmware(const struct firmware *fw,
0913                        void *context)
0914 {
0915     struct ims_pcu *pcu = context;
0916     int error;
0917 
0918     if (!fw) {
0919         dev_err(pcu->dev, "Failed to get firmware %s\n",
0920             IMS_PCU_FIRMWARE_NAME);
0921         goto out;
0922     }
0923 
0924     error = ihex_validate_fw(fw);
0925     if (error) {
0926         dev_err(pcu->dev, "Firmware %s is invalid\n",
0927             IMS_PCU_FIRMWARE_NAME);
0928         goto out;
0929     }
0930 
0931     mutex_lock(&pcu->cmd_mutex);
0932     ims_pcu_handle_firmware_update(pcu, fw);
0933     mutex_unlock(&pcu->cmd_mutex);
0934 
0935     release_firmware(fw);
0936 
0937 out:
0938     complete(&pcu->async_firmware_done);
0939 }
0940 
0941 /*********************************************************************
0942  *             Backlight LED device support                          *
0943  *********************************************************************/
0944 
0945 #define IMS_PCU_MAX_BRIGHTNESS      31998
0946 
0947 static int ims_pcu_backlight_set_brightness(struct led_classdev *cdev,
0948                         enum led_brightness value)
0949 {
0950     struct ims_pcu_backlight *backlight =
0951             container_of(cdev, struct ims_pcu_backlight, cdev);
0952     struct ims_pcu *pcu =
0953             container_of(backlight, struct ims_pcu, backlight);
0954     __le16 br_val = cpu_to_le16(value);
0955     int error;
0956 
0957     mutex_lock(&pcu->cmd_mutex);
0958 
0959     error = ims_pcu_execute_command(pcu, SET_BRIGHTNESS,
0960                     &br_val, sizeof(br_val));
0961     if (error && error != -ENODEV)
0962         dev_warn(pcu->dev,
0963              "Failed to set desired brightness %u, error: %d\n",
0964              value, error);
0965 
0966     mutex_unlock(&pcu->cmd_mutex);
0967 
0968     return error;
0969 }
0970 
0971 static enum led_brightness
0972 ims_pcu_backlight_get_brightness(struct led_classdev *cdev)
0973 {
0974     struct ims_pcu_backlight *backlight =
0975             container_of(cdev, struct ims_pcu_backlight, cdev);
0976     struct ims_pcu *pcu =
0977             container_of(backlight, struct ims_pcu, backlight);
0978     int brightness;
0979     int error;
0980 
0981     mutex_lock(&pcu->cmd_mutex);
0982 
0983     error = ims_pcu_execute_query(pcu, GET_BRIGHTNESS);
0984     if (error) {
0985         dev_warn(pcu->dev,
0986              "Failed to get current brightness, error: %d\n",
0987              error);
0988         /* Assume the LED is OFF */
0989         brightness = LED_OFF;
0990     } else {
0991         brightness =
0992             get_unaligned_le16(&pcu->cmd_buf[IMS_PCU_DATA_OFFSET]);
0993     }
0994 
0995     mutex_unlock(&pcu->cmd_mutex);
0996 
0997     return brightness;
0998 }
0999 
1000 static int ims_pcu_setup_backlight(struct ims_pcu *pcu)
1001 {
1002     struct ims_pcu_backlight *backlight = &pcu->backlight;
1003     int error;
1004 
1005     snprintf(backlight->name, sizeof(backlight->name),
1006          "pcu%d::kbd_backlight", pcu->device_no);
1007 
1008     backlight->cdev.name = backlight->name;
1009     backlight->cdev.max_brightness = IMS_PCU_MAX_BRIGHTNESS;
1010     backlight->cdev.brightness_get = ims_pcu_backlight_get_brightness;
1011     backlight->cdev.brightness_set_blocking =
1012                      ims_pcu_backlight_set_brightness;
1013 
1014     error = led_classdev_register(pcu->dev, &backlight->cdev);
1015     if (error) {
1016         dev_err(pcu->dev,
1017             "Failed to register backlight LED device, error: %d\n",
1018             error);
1019         return error;
1020     }
1021 
1022     return 0;
1023 }
1024 
1025 static void ims_pcu_destroy_backlight(struct ims_pcu *pcu)
1026 {
1027     struct ims_pcu_backlight *backlight = &pcu->backlight;
1028 
1029     led_classdev_unregister(&backlight->cdev);
1030 }
1031 
1032 
1033 /*********************************************************************
1034  *             Sysfs attributes handling                             *
1035  *********************************************************************/
1036 
1037 struct ims_pcu_attribute {
1038     struct device_attribute dattr;
1039     size_t field_offset;
1040     int field_length;
1041 };
1042 
1043 static ssize_t ims_pcu_attribute_show(struct device *dev,
1044                       struct device_attribute *dattr,
1045                       char *buf)
1046 {
1047     struct usb_interface *intf = to_usb_interface(dev);
1048     struct ims_pcu *pcu = usb_get_intfdata(intf);
1049     struct ims_pcu_attribute *attr =
1050             container_of(dattr, struct ims_pcu_attribute, dattr);
1051     char *field = (char *)pcu + attr->field_offset;
1052 
1053     return scnprintf(buf, PAGE_SIZE, "%.*s\n", attr->field_length, field);
1054 }
1055 
1056 static ssize_t ims_pcu_attribute_store(struct device *dev,
1057                        struct device_attribute *dattr,
1058                        const char *buf, size_t count)
1059 {
1060 
1061     struct usb_interface *intf = to_usb_interface(dev);
1062     struct ims_pcu *pcu = usb_get_intfdata(intf);
1063     struct ims_pcu_attribute *attr =
1064             container_of(dattr, struct ims_pcu_attribute, dattr);
1065     char *field = (char *)pcu + attr->field_offset;
1066     size_t data_len;
1067     int error;
1068 
1069     if (count > attr->field_length)
1070         return -EINVAL;
1071 
1072     data_len = strnlen(buf, attr->field_length);
1073     if (data_len > attr->field_length)
1074         return -EINVAL;
1075 
1076     error = mutex_lock_interruptible(&pcu->cmd_mutex);
1077     if (error)
1078         return error;
1079 
1080     memset(field, 0, attr->field_length);
1081     memcpy(field, buf, data_len);
1082 
1083     error = ims_pcu_set_info(pcu);
1084 
1085     /*
1086      * Even if update failed, let's fetch the info again as we just
1087      * clobbered one of the fields.
1088      */
1089     ims_pcu_get_info(pcu);
1090 
1091     mutex_unlock(&pcu->cmd_mutex);
1092 
1093     return error < 0 ? error : count;
1094 }
1095 
1096 #define IMS_PCU_ATTR(_field, _mode)                 \
1097 struct ims_pcu_attribute ims_pcu_attr_##_field = {          \
1098     .dattr = __ATTR(_field, _mode,                  \
1099             ims_pcu_attribute_show,             \
1100             ims_pcu_attribute_store),           \
1101     .field_offset = offsetof(struct ims_pcu, _field),       \
1102     .field_length = sizeof(((struct ims_pcu *)NULL)->_field),   \
1103 }
1104 
1105 #define IMS_PCU_RO_ATTR(_field)                     \
1106         IMS_PCU_ATTR(_field, S_IRUGO)
1107 #define IMS_PCU_RW_ATTR(_field)                     \
1108         IMS_PCU_ATTR(_field, S_IRUGO | S_IWUSR)
1109 
1110 static IMS_PCU_RW_ATTR(part_number);
1111 static IMS_PCU_RW_ATTR(serial_number);
1112 static IMS_PCU_RW_ATTR(date_of_manufacturing);
1113 
1114 static IMS_PCU_RO_ATTR(fw_version);
1115 static IMS_PCU_RO_ATTR(bl_version);
1116 static IMS_PCU_RO_ATTR(reset_reason);
1117 
1118 static ssize_t ims_pcu_reset_device(struct device *dev,
1119                     struct device_attribute *dattr,
1120                     const char *buf, size_t count)
1121 {
1122     static const u8 reset_byte = 1;
1123     struct usb_interface *intf = to_usb_interface(dev);
1124     struct ims_pcu *pcu = usb_get_intfdata(intf);
1125     int value;
1126     int error;
1127 
1128     error = kstrtoint(buf, 0, &value);
1129     if (error)
1130         return error;
1131 
1132     if (value != 1)
1133         return -EINVAL;
1134 
1135     dev_info(pcu->dev, "Attempting to reset device\n");
1136 
1137     error = ims_pcu_execute_command(pcu, PCU_RESET, &reset_byte, 1);
1138     if (error) {
1139         dev_info(pcu->dev,
1140              "Failed to reset device, error: %d\n",
1141              error);
1142         return error;
1143     }
1144 
1145     return count;
1146 }
1147 
1148 static DEVICE_ATTR(reset_device, S_IWUSR, NULL, ims_pcu_reset_device);
1149 
1150 static ssize_t ims_pcu_update_firmware_store(struct device *dev,
1151                          struct device_attribute *dattr,
1152                          const char *buf, size_t count)
1153 {
1154     struct usb_interface *intf = to_usb_interface(dev);
1155     struct ims_pcu *pcu = usb_get_intfdata(intf);
1156     const struct firmware *fw = NULL;
1157     int value;
1158     int error;
1159 
1160     error = kstrtoint(buf, 0, &value);
1161     if (error)
1162         return error;
1163 
1164     if (value != 1)
1165         return -EINVAL;
1166 
1167     error = mutex_lock_interruptible(&pcu->cmd_mutex);
1168     if (error)
1169         return error;
1170 
1171     error = request_ihex_firmware(&fw, IMS_PCU_FIRMWARE_NAME, pcu->dev);
1172     if (error) {
1173         dev_err(pcu->dev, "Failed to request firmware %s, error: %d\n",
1174             IMS_PCU_FIRMWARE_NAME, error);
1175         goto out;
1176     }
1177 
1178     /*
1179      * If we are already in bootloader mode we can proceed with
1180      * flashing the firmware.
1181      *
1182      * If we are in application mode, then we need to switch into
1183      * bootloader mode, which will cause the device to disconnect
1184      * and reconnect as different device.
1185      */
1186     if (pcu->bootloader_mode)
1187         error = ims_pcu_handle_firmware_update(pcu, fw);
1188     else
1189         error = ims_pcu_switch_to_bootloader(pcu);
1190 
1191     release_firmware(fw);
1192 
1193 out:
1194     mutex_unlock(&pcu->cmd_mutex);
1195     return error ?: count;
1196 }
1197 
1198 static DEVICE_ATTR(update_firmware, S_IWUSR,
1199            NULL, ims_pcu_update_firmware_store);
1200 
1201 static ssize_t
1202 ims_pcu_update_firmware_status_show(struct device *dev,
1203                     struct device_attribute *dattr,
1204                     char *buf)
1205 {
1206     struct usb_interface *intf = to_usb_interface(dev);
1207     struct ims_pcu *pcu = usb_get_intfdata(intf);
1208 
1209     return scnprintf(buf, PAGE_SIZE, "%d\n", pcu->update_firmware_status);
1210 }
1211 
1212 static DEVICE_ATTR(update_firmware_status, S_IRUGO,
1213            ims_pcu_update_firmware_status_show, NULL);
1214 
1215 static struct attribute *ims_pcu_attrs[] = {
1216     &ims_pcu_attr_part_number.dattr.attr,
1217     &ims_pcu_attr_serial_number.dattr.attr,
1218     &ims_pcu_attr_date_of_manufacturing.dattr.attr,
1219     &ims_pcu_attr_fw_version.dattr.attr,
1220     &ims_pcu_attr_bl_version.dattr.attr,
1221     &ims_pcu_attr_reset_reason.dattr.attr,
1222     &dev_attr_reset_device.attr,
1223     &dev_attr_update_firmware.attr,
1224     &dev_attr_update_firmware_status.attr,
1225     NULL
1226 };
1227 
1228 static umode_t ims_pcu_is_attr_visible(struct kobject *kobj,
1229                        struct attribute *attr, int n)
1230 {
1231     struct device *dev = kobj_to_dev(kobj);
1232     struct usb_interface *intf = to_usb_interface(dev);
1233     struct ims_pcu *pcu = usb_get_intfdata(intf);
1234     umode_t mode = attr->mode;
1235 
1236     if (pcu->bootloader_mode) {
1237         if (attr != &dev_attr_update_firmware_status.attr &&
1238             attr != &dev_attr_update_firmware.attr &&
1239             attr != &dev_attr_reset_device.attr) {
1240             mode = 0;
1241         }
1242     } else {
1243         if (attr == &dev_attr_update_firmware_status.attr)
1244             mode = 0;
1245     }
1246 
1247     return mode;
1248 }
1249 
1250 static const struct attribute_group ims_pcu_attr_group = {
1251     .is_visible = ims_pcu_is_attr_visible,
1252     .attrs      = ims_pcu_attrs,
1253 };
1254 
1255 /* Support for a separate OFN attribute group */
1256 
1257 #define OFN_REG_RESULT_OFFSET   2
1258 
1259 static int ims_pcu_read_ofn_config(struct ims_pcu *pcu, u8 addr, u8 *data)
1260 {
1261     int error;
1262     s16 result;
1263 
1264     error = ims_pcu_execute_command(pcu, OFN_GET_CONFIG,
1265                     &addr, sizeof(addr));
1266     if (error)
1267         return error;
1268 
1269     result = (s16)get_unaligned_le16(pcu->cmd_buf + OFN_REG_RESULT_OFFSET);
1270     if (result < 0)
1271         return -EIO;
1272 
1273     /* We only need LSB */
1274     *data = pcu->cmd_buf[OFN_REG_RESULT_OFFSET];
1275     return 0;
1276 }
1277 
1278 static int ims_pcu_write_ofn_config(struct ims_pcu *pcu, u8 addr, u8 data)
1279 {
1280     u8 buffer[] = { addr, data };
1281     int error;
1282     s16 result;
1283 
1284     error = ims_pcu_execute_command(pcu, OFN_SET_CONFIG,
1285                     &buffer, sizeof(buffer));
1286     if (error)
1287         return error;
1288 
1289     result = (s16)get_unaligned_le16(pcu->cmd_buf + OFN_REG_RESULT_OFFSET);
1290     if (result < 0)
1291         return -EIO;
1292 
1293     return 0;
1294 }
1295 
1296 static ssize_t ims_pcu_ofn_reg_data_show(struct device *dev,
1297                      struct device_attribute *dattr,
1298                      char *buf)
1299 {
1300     struct usb_interface *intf = to_usb_interface(dev);
1301     struct ims_pcu *pcu = usb_get_intfdata(intf);
1302     int error;
1303     u8 data;
1304 
1305     mutex_lock(&pcu->cmd_mutex);
1306     error = ims_pcu_read_ofn_config(pcu, pcu->ofn_reg_addr, &data);
1307     mutex_unlock(&pcu->cmd_mutex);
1308 
1309     if (error)
1310         return error;
1311 
1312     return scnprintf(buf, PAGE_SIZE, "%x\n", data);
1313 }
1314 
1315 static ssize_t ims_pcu_ofn_reg_data_store(struct device *dev,
1316                       struct device_attribute *dattr,
1317                       const char *buf, size_t count)
1318 {
1319     struct usb_interface *intf = to_usb_interface(dev);
1320     struct ims_pcu *pcu = usb_get_intfdata(intf);
1321     int error;
1322     u8 value;
1323 
1324     error = kstrtou8(buf, 0, &value);
1325     if (error)
1326         return error;
1327 
1328     mutex_lock(&pcu->cmd_mutex);
1329     error = ims_pcu_write_ofn_config(pcu, pcu->ofn_reg_addr, value);
1330     mutex_unlock(&pcu->cmd_mutex);
1331 
1332     return error ?: count;
1333 }
1334 
1335 static DEVICE_ATTR(reg_data, S_IRUGO | S_IWUSR,
1336            ims_pcu_ofn_reg_data_show, ims_pcu_ofn_reg_data_store);
1337 
1338 static ssize_t ims_pcu_ofn_reg_addr_show(struct device *dev,
1339                      struct device_attribute *dattr,
1340                      char *buf)
1341 {
1342     struct usb_interface *intf = to_usb_interface(dev);
1343     struct ims_pcu *pcu = usb_get_intfdata(intf);
1344     int error;
1345 
1346     mutex_lock(&pcu->cmd_mutex);
1347     error = scnprintf(buf, PAGE_SIZE, "%x\n", pcu->ofn_reg_addr);
1348     mutex_unlock(&pcu->cmd_mutex);
1349 
1350     return error;
1351 }
1352 
1353 static ssize_t ims_pcu_ofn_reg_addr_store(struct device *dev,
1354                       struct device_attribute *dattr,
1355                       const char *buf, size_t count)
1356 {
1357     struct usb_interface *intf = to_usb_interface(dev);
1358     struct ims_pcu *pcu = usb_get_intfdata(intf);
1359     int error;
1360     u8 value;
1361 
1362     error = kstrtou8(buf, 0, &value);
1363     if (error)
1364         return error;
1365 
1366     mutex_lock(&pcu->cmd_mutex);
1367     pcu->ofn_reg_addr = value;
1368     mutex_unlock(&pcu->cmd_mutex);
1369 
1370     return count;
1371 }
1372 
1373 static DEVICE_ATTR(reg_addr, S_IRUGO | S_IWUSR,
1374            ims_pcu_ofn_reg_addr_show, ims_pcu_ofn_reg_addr_store);
1375 
1376 struct ims_pcu_ofn_bit_attribute {
1377     struct device_attribute dattr;
1378     u8 addr;
1379     u8 nr;
1380 };
1381 
1382 static ssize_t ims_pcu_ofn_bit_show(struct device *dev,
1383                     struct device_attribute *dattr,
1384                     char *buf)
1385 {
1386     struct usb_interface *intf = to_usb_interface(dev);
1387     struct ims_pcu *pcu = usb_get_intfdata(intf);
1388     struct ims_pcu_ofn_bit_attribute *attr =
1389         container_of(dattr, struct ims_pcu_ofn_bit_attribute, dattr);
1390     int error;
1391     u8 data;
1392 
1393     mutex_lock(&pcu->cmd_mutex);
1394     error = ims_pcu_read_ofn_config(pcu, attr->addr, &data);
1395     mutex_unlock(&pcu->cmd_mutex);
1396 
1397     if (error)
1398         return error;
1399 
1400     return scnprintf(buf, PAGE_SIZE, "%d\n", !!(data & (1 << attr->nr)));
1401 }
1402 
1403 static ssize_t ims_pcu_ofn_bit_store(struct device *dev,
1404                      struct device_attribute *dattr,
1405                      const char *buf, size_t count)
1406 {
1407     struct usb_interface *intf = to_usb_interface(dev);
1408     struct ims_pcu *pcu = usb_get_intfdata(intf);
1409     struct ims_pcu_ofn_bit_attribute *attr =
1410         container_of(dattr, struct ims_pcu_ofn_bit_attribute, dattr);
1411     int error;
1412     int value;
1413     u8 data;
1414 
1415     error = kstrtoint(buf, 0, &value);
1416     if (error)
1417         return error;
1418 
1419     if (value > 1)
1420         return -EINVAL;
1421 
1422     mutex_lock(&pcu->cmd_mutex);
1423 
1424     error = ims_pcu_read_ofn_config(pcu, attr->addr, &data);
1425     if (!error) {
1426         if (value)
1427             data |= 1U << attr->nr;
1428         else
1429             data &= ~(1U << attr->nr);
1430 
1431         error = ims_pcu_write_ofn_config(pcu, attr->addr, data);
1432     }
1433 
1434     mutex_unlock(&pcu->cmd_mutex);
1435 
1436     return error ?: count;
1437 }
1438 
1439 #define IMS_PCU_OFN_BIT_ATTR(_field, _addr, _nr)            \
1440 struct ims_pcu_ofn_bit_attribute ims_pcu_ofn_attr_##_field = {      \
1441     .dattr = __ATTR(_field, S_IWUSR | S_IRUGO,          \
1442             ims_pcu_ofn_bit_show, ims_pcu_ofn_bit_store),   \
1443     .addr = _addr,                          \
1444     .nr = _nr,                          \
1445 }
1446 
1447 static IMS_PCU_OFN_BIT_ATTR(engine_enable,   0x60, 7);
1448 static IMS_PCU_OFN_BIT_ATTR(speed_enable,    0x60, 6);
1449 static IMS_PCU_OFN_BIT_ATTR(assert_enable,   0x60, 5);
1450 static IMS_PCU_OFN_BIT_ATTR(xyquant_enable,  0x60, 4);
1451 static IMS_PCU_OFN_BIT_ATTR(xyscale_enable,  0x60, 1);
1452 
1453 static IMS_PCU_OFN_BIT_ATTR(scale_x2,        0x63, 6);
1454 static IMS_PCU_OFN_BIT_ATTR(scale_y2,        0x63, 7);
1455 
1456 static struct attribute *ims_pcu_ofn_attrs[] = {
1457     &dev_attr_reg_data.attr,
1458     &dev_attr_reg_addr.attr,
1459     &ims_pcu_ofn_attr_engine_enable.dattr.attr,
1460     &ims_pcu_ofn_attr_speed_enable.dattr.attr,
1461     &ims_pcu_ofn_attr_assert_enable.dattr.attr,
1462     &ims_pcu_ofn_attr_xyquant_enable.dattr.attr,
1463     &ims_pcu_ofn_attr_xyscale_enable.dattr.attr,
1464     &ims_pcu_ofn_attr_scale_x2.dattr.attr,
1465     &ims_pcu_ofn_attr_scale_y2.dattr.attr,
1466     NULL
1467 };
1468 
1469 static const struct attribute_group ims_pcu_ofn_attr_group = {
1470     .name   = "ofn",
1471     .attrs  = ims_pcu_ofn_attrs,
1472 };
1473 
1474 static void ims_pcu_irq(struct urb *urb)
1475 {
1476     struct ims_pcu *pcu = urb->context;
1477     int retval, status;
1478 
1479     status = urb->status;
1480 
1481     switch (status) {
1482     case 0:
1483         /* success */
1484         break;
1485     case -ECONNRESET:
1486     case -ENOENT:
1487     case -ESHUTDOWN:
1488         /* this urb is terminated, clean up */
1489         dev_dbg(pcu->dev, "%s - urb shutting down with status: %d\n",
1490             __func__, status);
1491         return;
1492     default:
1493         dev_dbg(pcu->dev, "%s - nonzero urb status received: %d\n",
1494             __func__, status);
1495         goto exit;
1496     }
1497 
1498     dev_dbg(pcu->dev, "%s: received %d: %*ph\n", __func__,
1499         urb->actual_length, urb->actual_length, pcu->urb_in_buf);
1500 
1501     if (urb == pcu->urb_in)
1502         ims_pcu_process_data(pcu, urb);
1503 
1504 exit:
1505     retval = usb_submit_urb(urb, GFP_ATOMIC);
1506     if (retval && retval != -ENODEV)
1507         dev_err(pcu->dev, "%s - usb_submit_urb failed with result %d\n",
1508             __func__, retval);
1509 }
1510 
1511 static int ims_pcu_buffers_alloc(struct ims_pcu *pcu)
1512 {
1513     int error;
1514 
1515     pcu->urb_in_buf = usb_alloc_coherent(pcu->udev, pcu->max_in_size,
1516                          GFP_KERNEL, &pcu->read_dma);
1517     if (!pcu->urb_in_buf) {
1518         dev_err(pcu->dev,
1519             "Failed to allocate memory for read buffer\n");
1520         return -ENOMEM;
1521     }
1522 
1523     pcu->urb_in = usb_alloc_urb(0, GFP_KERNEL);
1524     if (!pcu->urb_in) {
1525         dev_err(pcu->dev, "Failed to allocate input URB\n");
1526         error = -ENOMEM;
1527         goto err_free_urb_in_buf;
1528     }
1529 
1530     pcu->urb_in->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1531     pcu->urb_in->transfer_dma = pcu->read_dma;
1532 
1533     usb_fill_bulk_urb(pcu->urb_in, pcu->udev,
1534               usb_rcvbulkpipe(pcu->udev,
1535                       pcu->ep_in->bEndpointAddress),
1536               pcu->urb_in_buf, pcu->max_in_size,
1537               ims_pcu_irq, pcu);
1538 
1539     /*
1540      * We are using usb_bulk_msg() for sending so there is no point
1541      * in allocating memory with usb_alloc_coherent().
1542      */
1543     pcu->urb_out_buf = kmalloc(pcu->max_out_size, GFP_KERNEL);
1544     if (!pcu->urb_out_buf) {
1545         dev_err(pcu->dev, "Failed to allocate memory for write buffer\n");
1546         error = -ENOMEM;
1547         goto err_free_in_urb;
1548     }
1549 
1550     pcu->urb_ctrl_buf = usb_alloc_coherent(pcu->udev, pcu->max_ctrl_size,
1551                            GFP_KERNEL, &pcu->ctrl_dma);
1552     if (!pcu->urb_ctrl_buf) {
1553         dev_err(pcu->dev,
1554             "Failed to allocate memory for read buffer\n");
1555         error = -ENOMEM;
1556         goto err_free_urb_out_buf;
1557     }
1558 
1559     pcu->urb_ctrl = usb_alloc_urb(0, GFP_KERNEL);
1560     if (!pcu->urb_ctrl) {
1561         dev_err(pcu->dev, "Failed to allocate input URB\n");
1562         error = -ENOMEM;
1563         goto err_free_urb_ctrl_buf;
1564     }
1565 
1566     pcu->urb_ctrl->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1567     pcu->urb_ctrl->transfer_dma = pcu->ctrl_dma;
1568 
1569     usb_fill_int_urb(pcu->urb_ctrl, pcu->udev,
1570               usb_rcvintpipe(pcu->udev,
1571                      pcu->ep_ctrl->bEndpointAddress),
1572               pcu->urb_ctrl_buf, pcu->max_ctrl_size,
1573               ims_pcu_irq, pcu, pcu->ep_ctrl->bInterval);
1574 
1575     return 0;
1576 
1577 err_free_urb_ctrl_buf:
1578     usb_free_coherent(pcu->udev, pcu->max_ctrl_size,
1579               pcu->urb_ctrl_buf, pcu->ctrl_dma);
1580 err_free_urb_out_buf:
1581     kfree(pcu->urb_out_buf);
1582 err_free_in_urb:
1583     usb_free_urb(pcu->urb_in);
1584 err_free_urb_in_buf:
1585     usb_free_coherent(pcu->udev, pcu->max_in_size,
1586               pcu->urb_in_buf, pcu->read_dma);
1587     return error;
1588 }
1589 
1590 static void ims_pcu_buffers_free(struct ims_pcu *pcu)
1591 {
1592     usb_kill_urb(pcu->urb_in);
1593     usb_free_urb(pcu->urb_in);
1594 
1595     usb_free_coherent(pcu->udev, pcu->max_out_size,
1596               pcu->urb_in_buf, pcu->read_dma);
1597 
1598     kfree(pcu->urb_out_buf);
1599 
1600     usb_kill_urb(pcu->urb_ctrl);
1601     usb_free_urb(pcu->urb_ctrl);
1602 
1603     usb_free_coherent(pcu->udev, pcu->max_ctrl_size,
1604               pcu->urb_ctrl_buf, pcu->ctrl_dma);
1605 }
1606 
1607 static const struct usb_cdc_union_desc *
1608 ims_pcu_get_cdc_union_desc(struct usb_interface *intf)
1609 {
1610     const void *buf = intf->altsetting->extra;
1611     size_t buflen = intf->altsetting->extralen;
1612     struct usb_cdc_union_desc *union_desc;
1613 
1614     if (!buf) {
1615         dev_err(&intf->dev, "Missing descriptor data\n");
1616         return NULL;
1617     }
1618 
1619     if (!buflen) {
1620         dev_err(&intf->dev, "Zero length descriptor\n");
1621         return NULL;
1622     }
1623 
1624     while (buflen >= sizeof(*union_desc)) {
1625         union_desc = (struct usb_cdc_union_desc *)buf;
1626 
1627         if (union_desc->bLength > buflen) {
1628             dev_err(&intf->dev, "Too large descriptor\n");
1629             return NULL;
1630         }
1631 
1632         if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&
1633             union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {
1634             dev_dbg(&intf->dev, "Found union header\n");
1635 
1636             if (union_desc->bLength >= sizeof(*union_desc))
1637                 return union_desc;
1638 
1639             dev_err(&intf->dev,
1640                 "Union descriptor too short (%d vs %zd)\n",
1641                 union_desc->bLength, sizeof(*union_desc));
1642             return NULL;
1643         }
1644 
1645         buflen -= union_desc->bLength;
1646         buf += union_desc->bLength;
1647     }
1648 
1649     dev_err(&intf->dev, "Missing CDC union descriptor\n");
1650     return NULL;
1651 }
1652 
1653 static int ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu)
1654 {
1655     const struct usb_cdc_union_desc *union_desc;
1656     struct usb_host_interface *alt;
1657 
1658     union_desc = ims_pcu_get_cdc_union_desc(intf);
1659     if (!union_desc)
1660         return -EINVAL;
1661 
1662     pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev,
1663                      union_desc->bMasterInterface0);
1664     if (!pcu->ctrl_intf)
1665         return -EINVAL;
1666 
1667     alt = pcu->ctrl_intf->cur_altsetting;
1668 
1669     if (alt->desc.bNumEndpoints < 1)
1670         return -ENODEV;
1671 
1672     pcu->ep_ctrl = &alt->endpoint[0].desc;
1673     pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl);
1674 
1675     pcu->data_intf = usb_ifnum_to_if(pcu->udev,
1676                      union_desc->bSlaveInterface0);
1677     if (!pcu->data_intf)
1678         return -EINVAL;
1679 
1680     alt = pcu->data_intf->cur_altsetting;
1681     if (alt->desc.bNumEndpoints != 2) {
1682         dev_err(pcu->dev,
1683             "Incorrect number of endpoints on data interface (%d)\n",
1684             alt->desc.bNumEndpoints);
1685         return -EINVAL;
1686     }
1687 
1688     pcu->ep_out = &alt->endpoint[0].desc;
1689     if (!usb_endpoint_is_bulk_out(pcu->ep_out)) {
1690         dev_err(pcu->dev,
1691             "First endpoint on data interface is not BULK OUT\n");
1692         return -EINVAL;
1693     }
1694 
1695     pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out);
1696     if (pcu->max_out_size < 8) {
1697         dev_err(pcu->dev,
1698             "Max OUT packet size is too small (%zd)\n",
1699             pcu->max_out_size);
1700         return -EINVAL;
1701     }
1702 
1703     pcu->ep_in = &alt->endpoint[1].desc;
1704     if (!usb_endpoint_is_bulk_in(pcu->ep_in)) {
1705         dev_err(pcu->dev,
1706             "Second endpoint on data interface is not BULK IN\n");
1707         return -EINVAL;
1708     }
1709 
1710     pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in);
1711     if (pcu->max_in_size < 8) {
1712         dev_err(pcu->dev,
1713             "Max IN packet size is too small (%zd)\n",
1714             pcu->max_in_size);
1715         return -EINVAL;
1716     }
1717 
1718     return 0;
1719 }
1720 
1721 static int ims_pcu_start_io(struct ims_pcu *pcu)
1722 {
1723     int error;
1724 
1725     error = usb_submit_urb(pcu->urb_ctrl, GFP_KERNEL);
1726     if (error) {
1727         dev_err(pcu->dev,
1728             "Failed to start control IO - usb_submit_urb failed with result: %d\n",
1729             error);
1730         return -EIO;
1731     }
1732 
1733     error = usb_submit_urb(pcu->urb_in, GFP_KERNEL);
1734     if (error) {
1735         dev_err(pcu->dev,
1736             "Failed to start IO - usb_submit_urb failed with result: %d\n",
1737             error);
1738         usb_kill_urb(pcu->urb_ctrl);
1739         return -EIO;
1740     }
1741 
1742     return 0;
1743 }
1744 
1745 static void ims_pcu_stop_io(struct ims_pcu *pcu)
1746 {
1747     usb_kill_urb(pcu->urb_in);
1748     usb_kill_urb(pcu->urb_ctrl);
1749 }
1750 
1751 static int ims_pcu_line_setup(struct ims_pcu *pcu)
1752 {
1753     struct usb_host_interface *interface = pcu->ctrl_intf->cur_altsetting;
1754     struct usb_cdc_line_coding *line = (void *)pcu->cmd_buf;
1755     int error;
1756 
1757     memset(line, 0, sizeof(*line));
1758     line->dwDTERate = cpu_to_le32(57600);
1759     line->bDataBits = 8;
1760 
1761     error = usb_control_msg(pcu->udev, usb_sndctrlpipe(pcu->udev, 0),
1762                 USB_CDC_REQ_SET_LINE_CODING,
1763                 USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1764                 0, interface->desc.bInterfaceNumber,
1765                 line, sizeof(struct usb_cdc_line_coding),
1766                 5000);
1767     if (error < 0) {
1768         dev_err(pcu->dev, "Failed to set line coding, error: %d\n",
1769             error);
1770         return error;
1771     }
1772 
1773     error = usb_control_msg(pcu->udev, usb_sndctrlpipe(pcu->udev, 0),
1774                 USB_CDC_REQ_SET_CONTROL_LINE_STATE,
1775                 USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1776                 0x03, interface->desc.bInterfaceNumber,
1777                 NULL, 0, 5000);
1778     if (error < 0) {
1779         dev_err(pcu->dev, "Failed to set line state, error: %d\n",
1780             error);
1781         return error;
1782     }
1783 
1784     return 0;
1785 }
1786 
1787 static int ims_pcu_get_device_info(struct ims_pcu *pcu)
1788 {
1789     int error;
1790 
1791     error = ims_pcu_get_info(pcu);
1792     if (error)
1793         return error;
1794 
1795     error = ims_pcu_execute_query(pcu, GET_FW_VERSION);
1796     if (error) {
1797         dev_err(pcu->dev,
1798             "GET_FW_VERSION command failed, error: %d\n", error);
1799         return error;
1800     }
1801 
1802     snprintf(pcu->fw_version, sizeof(pcu->fw_version),
1803          "%02d%02d%02d%02d.%c%c",
1804          pcu->cmd_buf[2], pcu->cmd_buf[3], pcu->cmd_buf[4], pcu->cmd_buf[5],
1805          pcu->cmd_buf[6], pcu->cmd_buf[7]);
1806 
1807     error = ims_pcu_execute_query(pcu, GET_BL_VERSION);
1808     if (error) {
1809         dev_err(pcu->dev,
1810             "GET_BL_VERSION command failed, error: %d\n", error);
1811         return error;
1812     }
1813 
1814     snprintf(pcu->bl_version, sizeof(pcu->bl_version),
1815          "%02d%02d%02d%02d.%c%c",
1816          pcu->cmd_buf[2], pcu->cmd_buf[3], pcu->cmd_buf[4], pcu->cmd_buf[5],
1817          pcu->cmd_buf[6], pcu->cmd_buf[7]);
1818 
1819     error = ims_pcu_execute_query(pcu, RESET_REASON);
1820     if (error) {
1821         dev_err(pcu->dev,
1822             "RESET_REASON command failed, error: %d\n", error);
1823         return error;
1824     }
1825 
1826     snprintf(pcu->reset_reason, sizeof(pcu->reset_reason),
1827          "%02x", pcu->cmd_buf[IMS_PCU_DATA_OFFSET]);
1828 
1829     dev_dbg(pcu->dev,
1830         "P/N: %s, MD: %s, S/N: %s, FW: %s, BL: %s, RR: %s\n",
1831         pcu->part_number,
1832         pcu->date_of_manufacturing,
1833         pcu->serial_number,
1834         pcu->fw_version,
1835         pcu->bl_version,
1836         pcu->reset_reason);
1837 
1838     return 0;
1839 }
1840 
1841 static int ims_pcu_identify_type(struct ims_pcu *pcu, u8 *device_id)
1842 {
1843     int error;
1844 
1845     error = ims_pcu_execute_query(pcu, GET_DEVICE_ID);
1846     if (error) {
1847         dev_err(pcu->dev,
1848             "GET_DEVICE_ID command failed, error: %d\n", error);
1849         return error;
1850     }
1851 
1852     *device_id = pcu->cmd_buf[IMS_PCU_DATA_OFFSET];
1853     dev_dbg(pcu->dev, "Detected device ID: %d\n", *device_id);
1854 
1855     return 0;
1856 }
1857 
1858 static int ims_pcu_init_application_mode(struct ims_pcu *pcu)
1859 {
1860     static atomic_t device_no = ATOMIC_INIT(-1);
1861 
1862     const struct ims_pcu_device_info *info;
1863     int error;
1864 
1865     error = ims_pcu_get_device_info(pcu);
1866     if (error) {
1867         /* Device does not respond to basic queries, hopeless */
1868         return error;
1869     }
1870 
1871     error = ims_pcu_identify_type(pcu, &pcu->device_id);
1872     if (error) {
1873         dev_err(pcu->dev,
1874             "Failed to identify device, error: %d\n", error);
1875         /*
1876          * Do not signal error, but do not create input nor
1877          * backlight devices either, let userspace figure this
1878          * out (flash a new firmware?).
1879          */
1880         return 0;
1881     }
1882 
1883     if (pcu->device_id >= ARRAY_SIZE(ims_pcu_device_info) ||
1884         !ims_pcu_device_info[pcu->device_id].keymap) {
1885         dev_err(pcu->dev, "Device ID %d is not valid\n", pcu->device_id);
1886         /* Same as above, punt to userspace */
1887         return 0;
1888     }
1889 
1890     /* Device appears to be operable, complete initialization */
1891     pcu->device_no = atomic_inc_return(&device_no);
1892 
1893     /*
1894      * PCU-B devices, both GEN_1 and GEN_2 do not have OFN sensor
1895      */
1896     if (pcu->device_id != IMS_PCU_PCU_B_DEVICE_ID) {
1897         error = sysfs_create_group(&pcu->dev->kobj,
1898                        &ims_pcu_ofn_attr_group);
1899         if (error)
1900             return error;
1901     }
1902 
1903     error = ims_pcu_setup_backlight(pcu);
1904     if (error)
1905         return error;
1906 
1907     info = &ims_pcu_device_info[pcu->device_id];
1908     error = ims_pcu_setup_buttons(pcu, info->keymap, info->keymap_len);
1909     if (error)
1910         goto err_destroy_backlight;
1911 
1912     if (info->has_gamepad) {
1913         error = ims_pcu_setup_gamepad(pcu);
1914         if (error)
1915             goto err_destroy_buttons;
1916     }
1917 
1918     pcu->setup_complete = true;
1919 
1920     return 0;
1921 
1922 err_destroy_buttons:
1923     ims_pcu_destroy_buttons(pcu);
1924 err_destroy_backlight:
1925     ims_pcu_destroy_backlight(pcu);
1926     return error;
1927 }
1928 
1929 static void ims_pcu_destroy_application_mode(struct ims_pcu *pcu)
1930 {
1931     if (pcu->setup_complete) {
1932         pcu->setup_complete = false;
1933         mb(); /* make sure flag setting is not reordered */
1934 
1935         if (pcu->gamepad)
1936             ims_pcu_destroy_gamepad(pcu);
1937         ims_pcu_destroy_buttons(pcu);
1938         ims_pcu_destroy_backlight(pcu);
1939 
1940         if (pcu->device_id != IMS_PCU_PCU_B_DEVICE_ID)
1941             sysfs_remove_group(&pcu->dev->kobj,
1942                        &ims_pcu_ofn_attr_group);
1943     }
1944 }
1945 
1946 static int ims_pcu_init_bootloader_mode(struct ims_pcu *pcu)
1947 {
1948     int error;
1949 
1950     error = ims_pcu_execute_bl_command(pcu, QUERY_DEVICE, NULL, 0,
1951                        IMS_PCU_CMD_RESPONSE_TIMEOUT);
1952     if (error) {
1953         dev_err(pcu->dev, "Bootloader does not respond, aborting\n");
1954         return error;
1955     }
1956 
1957     pcu->fw_start_addr =
1958         get_unaligned_le32(&pcu->cmd_buf[IMS_PCU_DATA_OFFSET + 11]);
1959     pcu->fw_end_addr =
1960         get_unaligned_le32(&pcu->cmd_buf[IMS_PCU_DATA_OFFSET + 15]);
1961 
1962     dev_info(pcu->dev,
1963          "Device is in bootloader mode (addr 0x%08x-0x%08x), requesting firmware\n",
1964          pcu->fw_start_addr, pcu->fw_end_addr);
1965 
1966     error = request_firmware_nowait(THIS_MODULE, true,
1967                     IMS_PCU_FIRMWARE_NAME,
1968                     pcu->dev, GFP_KERNEL, pcu,
1969                     ims_pcu_process_async_firmware);
1970     if (error) {
1971         /* This error is not fatal, let userspace have another chance */
1972         complete(&pcu->async_firmware_done);
1973     }
1974 
1975     return 0;
1976 }
1977 
1978 static void ims_pcu_destroy_bootloader_mode(struct ims_pcu *pcu)
1979 {
1980     /* Make sure our initial firmware request has completed */
1981     wait_for_completion(&pcu->async_firmware_done);
1982 }
1983 
1984 #define IMS_PCU_APPLICATION_MODE    0
1985 #define IMS_PCU_BOOTLOADER_MODE     1
1986 
1987 static struct usb_driver ims_pcu_driver;
1988 
1989 static int ims_pcu_probe(struct usb_interface *intf,
1990              const struct usb_device_id *id)
1991 {
1992     struct usb_device *udev = interface_to_usbdev(intf);
1993     struct ims_pcu *pcu;
1994     int error;
1995 
1996     pcu = kzalloc(sizeof(struct ims_pcu), GFP_KERNEL);
1997     if (!pcu)
1998         return -ENOMEM;
1999 
2000     pcu->dev = &intf->dev;
2001     pcu->udev = udev;
2002     pcu->bootloader_mode = id->driver_info == IMS_PCU_BOOTLOADER_MODE;
2003     mutex_init(&pcu->cmd_mutex);
2004     init_completion(&pcu->cmd_done);
2005     init_completion(&pcu->async_firmware_done);
2006 
2007     error = ims_pcu_parse_cdc_data(intf, pcu);
2008     if (error)
2009         goto err_free_mem;
2010 
2011     error = usb_driver_claim_interface(&ims_pcu_driver,
2012                        pcu->data_intf, pcu);
2013     if (error) {
2014         dev_err(&intf->dev,
2015             "Unable to claim corresponding data interface: %d\n",
2016             error);
2017         goto err_free_mem;
2018     }
2019 
2020     usb_set_intfdata(pcu->ctrl_intf, pcu);
2021 
2022     error = ims_pcu_buffers_alloc(pcu);
2023     if (error)
2024         goto err_unclaim_intf;
2025 
2026     error = ims_pcu_start_io(pcu);
2027     if (error)
2028         goto err_free_buffers;
2029 
2030     error = ims_pcu_line_setup(pcu);
2031     if (error)
2032         goto err_stop_io;
2033 
2034     error = sysfs_create_group(&intf->dev.kobj, &ims_pcu_attr_group);
2035     if (error)
2036         goto err_stop_io;
2037 
2038     error = pcu->bootloader_mode ?
2039             ims_pcu_init_bootloader_mode(pcu) :
2040             ims_pcu_init_application_mode(pcu);
2041     if (error)
2042         goto err_remove_sysfs;
2043 
2044     return 0;
2045 
2046 err_remove_sysfs:
2047     sysfs_remove_group(&intf->dev.kobj, &ims_pcu_attr_group);
2048 err_stop_io:
2049     ims_pcu_stop_io(pcu);
2050 err_free_buffers:
2051     ims_pcu_buffers_free(pcu);
2052 err_unclaim_intf:
2053     usb_driver_release_interface(&ims_pcu_driver, pcu->data_intf);
2054 err_free_mem:
2055     kfree(pcu);
2056     return error;
2057 }
2058 
2059 static void ims_pcu_disconnect(struct usb_interface *intf)
2060 {
2061     struct ims_pcu *pcu = usb_get_intfdata(intf);
2062     struct usb_host_interface *alt = intf->cur_altsetting;
2063 
2064     usb_set_intfdata(intf, NULL);
2065 
2066     /*
2067      * See if we are dealing with control or data interface. The cleanup
2068      * happens when we unbind primary (control) interface.
2069      */
2070     if (alt->desc.bInterfaceClass != USB_CLASS_COMM)
2071         return;
2072 
2073     sysfs_remove_group(&intf->dev.kobj, &ims_pcu_attr_group);
2074 
2075     ims_pcu_stop_io(pcu);
2076 
2077     if (pcu->bootloader_mode)
2078         ims_pcu_destroy_bootloader_mode(pcu);
2079     else
2080         ims_pcu_destroy_application_mode(pcu);
2081 
2082     ims_pcu_buffers_free(pcu);
2083     kfree(pcu);
2084 }
2085 
2086 #ifdef CONFIG_PM
2087 static int ims_pcu_suspend(struct usb_interface *intf,
2088                pm_message_t message)
2089 {
2090     struct ims_pcu *pcu = usb_get_intfdata(intf);
2091     struct usb_host_interface *alt = intf->cur_altsetting;
2092 
2093     if (alt->desc.bInterfaceClass == USB_CLASS_COMM)
2094         ims_pcu_stop_io(pcu);
2095 
2096     return 0;
2097 }
2098 
2099 static int ims_pcu_resume(struct usb_interface *intf)
2100 {
2101     struct ims_pcu *pcu = usb_get_intfdata(intf);
2102     struct usb_host_interface *alt = intf->cur_altsetting;
2103     int retval = 0;
2104 
2105     if (alt->desc.bInterfaceClass == USB_CLASS_COMM) {
2106         retval = ims_pcu_start_io(pcu);
2107         if (retval == 0)
2108             retval = ims_pcu_line_setup(pcu);
2109     }
2110 
2111     return retval;
2112 }
2113 #endif
2114 
2115 static const struct usb_device_id ims_pcu_id_table[] = {
2116     {
2117         USB_DEVICE_AND_INTERFACE_INFO(0x04d8, 0x0082,
2118                     USB_CLASS_COMM,
2119                     USB_CDC_SUBCLASS_ACM,
2120                     USB_CDC_ACM_PROTO_AT_V25TER),
2121         .driver_info = IMS_PCU_APPLICATION_MODE,
2122     },
2123     {
2124         USB_DEVICE_AND_INTERFACE_INFO(0x04d8, 0x0083,
2125                     USB_CLASS_COMM,
2126                     USB_CDC_SUBCLASS_ACM,
2127                     USB_CDC_ACM_PROTO_AT_V25TER),
2128         .driver_info = IMS_PCU_BOOTLOADER_MODE,
2129     },
2130     { }
2131 };
2132 
2133 static struct usb_driver ims_pcu_driver = {
2134     .name           = "ims_pcu",
2135     .id_table       = ims_pcu_id_table,
2136     .probe          = ims_pcu_probe,
2137     .disconnect     = ims_pcu_disconnect,
2138 #ifdef CONFIG_PM
2139     .suspend        = ims_pcu_suspend,
2140     .resume         = ims_pcu_resume,
2141     .reset_resume       = ims_pcu_resume,
2142 #endif
2143 };
2144 
2145 module_usb_driver(ims_pcu_driver);
2146 
2147 MODULE_DESCRIPTION("IMS Passenger Control Unit driver");
2148 MODULE_AUTHOR("Dmitry Torokhov <dmitry.torokhov@gmail.com>");
2149 MODULE_LICENSE("GPL");