linux/drivers/hid/hid-logitech-hidpp.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 *  HIDPP protocol for Logitech receivers
   4 *
   5 *  Copyright (c) 2011 Logitech (c)
   6 *  Copyright (c) 2012-2013 Google (c)
   7 *  Copyright (c) 2013-2014 Red Hat Inc.
   8 */
   9
  10
  11#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  12
  13#include <linux/device.h>
  14#include <linux/input.h>
  15#include <linux/usb.h>
  16#include <linux/hid.h>
  17#include <linux/module.h>
  18#include <linux/slab.h>
  19#include <linux/sched.h>
  20#include <linux/sched/clock.h>
  21#include <linux/kfifo.h>
  22#include <linux/input/mt.h>
  23#include <linux/workqueue.h>
  24#include <linux/atomic.h>
  25#include <linux/fixp-arith.h>
  26#include <asm/unaligned.h>
  27#include "usbhid/usbhid.h"
  28#include "hid-ids.h"
  29
  30MODULE_LICENSE("GPL");
  31MODULE_AUTHOR("Benjamin Tissoires <benjamin.tissoires@gmail.com>");
  32MODULE_AUTHOR("Nestor Lopez Casado <nlopezcasad@logitech.com>");
  33
  34static bool disable_raw_mode;
  35module_param(disable_raw_mode, bool, 0644);
  36MODULE_PARM_DESC(disable_raw_mode,
  37        "Disable Raw mode reporting for touchpads and keep firmware gestures.");
  38
  39static bool disable_tap_to_click;
  40module_param(disable_tap_to_click, bool, 0644);
  41MODULE_PARM_DESC(disable_tap_to_click,
  42        "Disable Tap-To-Click mode reporting for touchpads (only on the K400 currently).");
  43
  44#define REPORT_ID_HIDPP_SHORT                   0x10
  45#define REPORT_ID_HIDPP_LONG                    0x11
  46#define REPORT_ID_HIDPP_VERY_LONG               0x12
  47
  48#define HIDPP_REPORT_SHORT_LENGTH               7
  49#define HIDPP_REPORT_LONG_LENGTH                20
  50#define HIDPP_REPORT_VERY_LONG_MAX_LENGTH       64
  51
  52#define HIDPP_REPORT_SHORT_SUPPORTED            BIT(0)
  53#define HIDPP_REPORT_LONG_SUPPORTED             BIT(1)
  54#define HIDPP_REPORT_VERY_LONG_SUPPORTED        BIT(2)
  55
  56#define HIDPP_SUB_ID_CONSUMER_VENDOR_KEYS       0x03
  57#define HIDPP_SUB_ID_ROLLER                     0x05
  58#define HIDPP_SUB_ID_MOUSE_EXTRA_BTNS           0x06
  59
  60#define HIDPP_QUIRK_CLASS_WTP                   BIT(0)
  61#define HIDPP_QUIRK_CLASS_M560                  BIT(1)
  62#define HIDPP_QUIRK_CLASS_K400                  BIT(2)
  63#define HIDPP_QUIRK_CLASS_G920                  BIT(3)
  64#define HIDPP_QUIRK_CLASS_K750                  BIT(4)
  65
  66/* bits 2..20 are reserved for classes */
  67/* #define HIDPP_QUIRK_CONNECT_EVENTS           BIT(21) disabled */
  68#define HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS        BIT(22)
  69#define HIDPP_QUIRK_NO_HIDINPUT                 BIT(23)
  70#define HIDPP_QUIRK_FORCE_OUTPUT_REPORTS        BIT(24)
  71#define HIDPP_QUIRK_UNIFYING                    BIT(25)
  72#define HIDPP_QUIRK_HI_RES_SCROLL_1P0           BIT(26)
  73#define HIDPP_QUIRK_HI_RES_SCROLL_X2120         BIT(27)
  74#define HIDPP_QUIRK_HI_RES_SCROLL_X2121         BIT(28)
  75#define HIDPP_QUIRK_HIDPP_WHEELS                BIT(29)
  76#define HIDPP_QUIRK_HIDPP_EXTRA_MOUSE_BTNS      BIT(30)
  77#define HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS  BIT(31)
  78
  79/* These are just aliases for now */
  80#define HIDPP_QUIRK_KBD_SCROLL_WHEEL HIDPP_QUIRK_HIDPP_WHEELS
  81#define HIDPP_QUIRK_KBD_ZOOM_WHEEL   HIDPP_QUIRK_HIDPP_WHEELS
  82
  83/* Convenience constant to check for any high-res support. */
  84#define HIDPP_QUIRK_HI_RES_SCROLL       (HIDPP_QUIRK_HI_RES_SCROLL_1P0 | \
  85                                         HIDPP_QUIRK_HI_RES_SCROLL_X2120 | \
  86                                         HIDPP_QUIRK_HI_RES_SCROLL_X2121)
  87
  88#define HIDPP_QUIRK_DELAYED_INIT                HIDPP_QUIRK_NO_HIDINPUT
  89
  90#define HIDPP_CAPABILITY_HIDPP10_BATTERY        BIT(0)
  91#define HIDPP_CAPABILITY_HIDPP20_BATTERY        BIT(1)
  92#define HIDPP_CAPABILITY_BATTERY_MILEAGE        BIT(2)
  93#define HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS   BIT(3)
  94#define HIDPP_CAPABILITY_BATTERY_VOLTAGE        BIT(4)
  95
  96#define lg_map_key_clear(c)  hid_map_usage_clear(hi, usage, bit, max, EV_KEY, (c))
  97
  98/*
  99 * There are two hidpp protocols in use, the first version hidpp10 is known
 100 * as register access protocol or RAP, the second version hidpp20 is known as
 101 * feature access protocol or FAP
 102 *
 103 * Most older devices (including the Unifying usb receiver) use the RAP protocol
 104 * where as most newer devices use the FAP protocol. Both protocols are
 105 * compatible with the underlying transport, which could be usb, Unifiying, or
 106 * bluetooth. The message lengths are defined by the hid vendor specific report
 107 * descriptor for the HIDPP_SHORT report type (total message lenth 7 bytes) and
 108 * the HIDPP_LONG report type (total message length 20 bytes)
 109 *
 110 * The RAP protocol uses both report types, whereas the FAP only uses HIDPP_LONG
 111 * messages. The Unifying receiver itself responds to RAP messages (device index
 112 * is 0xFF for the receiver), and all messages (short or long) with a device
 113 * index between 1 and 6 are passed untouched to the corresponding paired
 114 * Unifying device.
 115 *
 116 * The paired device can be RAP or FAP, it will receive the message untouched
 117 * from the Unifiying receiver.
 118 */
 119
 120struct fap {
 121        u8 feature_index;
 122        u8 funcindex_clientid;
 123        u8 params[HIDPP_REPORT_VERY_LONG_MAX_LENGTH - 4U];
 124};
 125
 126struct rap {
 127        u8 sub_id;
 128        u8 reg_address;
 129        u8 params[HIDPP_REPORT_VERY_LONG_MAX_LENGTH - 4U];
 130};
 131
 132struct hidpp_report {
 133        u8 report_id;
 134        u8 device_index;
 135        union {
 136                struct fap fap;
 137                struct rap rap;
 138                u8 rawbytes[sizeof(struct fap)];
 139        };
 140} __packed;
 141
 142struct hidpp_battery {
 143        u8 feature_index;
 144        u8 solar_feature_index;
 145        u8 voltage_feature_index;
 146        struct power_supply_desc desc;
 147        struct power_supply *ps;
 148        char name[64];
 149        int status;
 150        int capacity;
 151        int level;
 152        int voltage;
 153        int charge_type;
 154        bool online;
 155};
 156
 157/**
 158 * struct hidpp_scroll_counter - Utility class for processing high-resolution
 159 *                             scroll events.
 160 * @dev: the input device for which events should be reported.
 161 * @wheel_multiplier: the scalar multiplier to be applied to each wheel event
 162 * @remainder: counts the number of high-resolution units moved since the last
 163 *             low-resolution event (REL_WHEEL or REL_HWHEEL) was sent. Should
 164 *             only be used by class methods.
 165 * @direction: direction of last movement (1 or -1)
 166 * @last_time: last event time, used to reset remainder after inactivity
 167 */
 168struct hidpp_scroll_counter {
 169        int wheel_multiplier;
 170        int remainder;
 171        int direction;
 172        unsigned long long last_time;
 173};
 174
 175struct hidpp_device {
 176        struct hid_device *hid_dev;
 177        struct input_dev *input;
 178        struct mutex send_mutex;
 179        void *send_receive_buf;
 180        char *name;             /* will never be NULL and should not be freed */
 181        wait_queue_head_t wait;
 182        int very_long_report_length;
 183        bool answer_available;
 184        u8 protocol_major;
 185        u8 protocol_minor;
 186
 187        void *private_data;
 188
 189        struct work_struct work;
 190        struct kfifo delayed_work_fifo;
 191        atomic_t connected;
 192        struct input_dev *delayed_input;
 193
 194        unsigned long quirks;
 195        unsigned long capabilities;
 196        u8 supported_reports;
 197
 198        struct hidpp_battery battery;
 199        struct hidpp_scroll_counter vertical_wheel_counter;
 200
 201        u8 wireless_feature_index;
 202};
 203
 204/* HID++ 1.0 error codes */
 205#define HIDPP_ERROR                             0x8f
 206#define HIDPP_ERROR_SUCCESS                     0x00
 207#define HIDPP_ERROR_INVALID_SUBID               0x01
 208#define HIDPP_ERROR_INVALID_ADRESS              0x02
 209#define HIDPP_ERROR_INVALID_VALUE               0x03
 210#define HIDPP_ERROR_CONNECT_FAIL                0x04
 211#define HIDPP_ERROR_TOO_MANY_DEVICES            0x05
 212#define HIDPP_ERROR_ALREADY_EXISTS              0x06
 213#define HIDPP_ERROR_BUSY                        0x07
 214#define HIDPP_ERROR_UNKNOWN_DEVICE              0x08
 215#define HIDPP_ERROR_RESOURCE_ERROR              0x09
 216#define HIDPP_ERROR_REQUEST_UNAVAILABLE         0x0a
 217#define HIDPP_ERROR_INVALID_PARAM_VALUE         0x0b
 218#define HIDPP_ERROR_WRONG_PIN_CODE              0x0c
 219/* HID++ 2.0 error codes */
 220#define HIDPP20_ERROR                           0xff
 221
 222static void hidpp_connect_event(struct hidpp_device *hidpp_dev);
 223
 224static int __hidpp_send_report(struct hid_device *hdev,
 225                                struct hidpp_report *hidpp_report)
 226{
 227        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
 228        int fields_count, ret;
 229
 230        switch (hidpp_report->report_id) {
 231        case REPORT_ID_HIDPP_SHORT:
 232                fields_count = HIDPP_REPORT_SHORT_LENGTH;
 233                break;
 234        case REPORT_ID_HIDPP_LONG:
 235                fields_count = HIDPP_REPORT_LONG_LENGTH;
 236                break;
 237        case REPORT_ID_HIDPP_VERY_LONG:
 238                fields_count = hidpp->very_long_report_length;
 239                break;
 240        default:
 241                return -ENODEV;
 242        }
 243
 244        /*
 245         * set the device_index as the receiver, it will be overwritten by
 246         * hid_hw_request if needed
 247         */
 248        hidpp_report->device_index = 0xff;
 249
 250        if (hidpp->quirks & HIDPP_QUIRK_FORCE_OUTPUT_REPORTS) {
 251                ret = hid_hw_output_report(hdev, (u8 *)hidpp_report, fields_count);
 252        } else {
 253                ret = hid_hw_raw_request(hdev, hidpp_report->report_id,
 254                        (u8 *)hidpp_report, fields_count, HID_OUTPUT_REPORT,
 255                        HID_REQ_SET_REPORT);
 256        }
 257
 258        return ret == fields_count ? 0 : -1;
 259}
 260
 261/**
 262 * hidpp_send_message_sync() returns 0 in case of success, and something else
 263 * in case of a failure.
 264 * - If ' something else' is positive, that means that an error has been raised
 265 *   by the protocol itself.
 266 * - If ' something else' is negative, that means that we had a classic error
 267 *   (-ENOMEM, -EPIPE, etc...)
 268 */
 269static int hidpp_send_message_sync(struct hidpp_device *hidpp,
 270        struct hidpp_report *message,
 271        struct hidpp_report *response)
 272{
 273        int ret;
 274
 275        mutex_lock(&hidpp->send_mutex);
 276
 277        hidpp->send_receive_buf = response;
 278        hidpp->answer_available = false;
 279
 280        /*
 281         * So that we can later validate the answer when it arrives
 282         * in hidpp_raw_event
 283         */
 284        *response = *message;
 285
 286        ret = __hidpp_send_report(hidpp->hid_dev, message);
 287
 288        if (ret) {
 289                dbg_hid("__hidpp_send_report returned err: %d\n", ret);
 290                memset(response, 0, sizeof(struct hidpp_report));
 291                goto exit;
 292        }
 293
 294        if (!wait_event_timeout(hidpp->wait, hidpp->answer_available,
 295                                5*HZ)) {
 296                dbg_hid("%s:timeout waiting for response\n", __func__);
 297                memset(response, 0, sizeof(struct hidpp_report));
 298                ret = -ETIMEDOUT;
 299        }
 300
 301        if (response->report_id == REPORT_ID_HIDPP_SHORT &&
 302            response->rap.sub_id == HIDPP_ERROR) {
 303                ret = response->rap.params[1];
 304                dbg_hid("%s:got hidpp error %02X\n", __func__, ret);
 305                goto exit;
 306        }
 307
 308        if ((response->report_id == REPORT_ID_HIDPP_LONG ||
 309                        response->report_id == REPORT_ID_HIDPP_VERY_LONG) &&
 310                        response->fap.feature_index == HIDPP20_ERROR) {
 311                ret = response->fap.params[1];
 312                dbg_hid("%s:got hidpp 2.0 error %02X\n", __func__, ret);
 313                goto exit;
 314        }
 315
 316exit:
 317        mutex_unlock(&hidpp->send_mutex);
 318        return ret;
 319
 320}
 321
 322static int hidpp_send_fap_command_sync(struct hidpp_device *hidpp,
 323        u8 feat_index, u8 funcindex_clientid, u8 *params, int param_count,
 324        struct hidpp_report *response)
 325{
 326        struct hidpp_report *message;
 327        int ret;
 328
 329        if (param_count > sizeof(message->fap.params))
 330                return -EINVAL;
 331
 332        message = kzalloc(sizeof(struct hidpp_report), GFP_KERNEL);
 333        if (!message)
 334                return -ENOMEM;
 335
 336        if (param_count > (HIDPP_REPORT_LONG_LENGTH - 4))
 337                message->report_id = REPORT_ID_HIDPP_VERY_LONG;
 338        else
 339                message->report_id = REPORT_ID_HIDPP_LONG;
 340        message->fap.feature_index = feat_index;
 341        message->fap.funcindex_clientid = funcindex_clientid;
 342        memcpy(&message->fap.params, params, param_count);
 343
 344        ret = hidpp_send_message_sync(hidpp, message, response);
 345        kfree(message);
 346        return ret;
 347}
 348
 349static int hidpp_send_rap_command_sync(struct hidpp_device *hidpp_dev,
 350        u8 report_id, u8 sub_id, u8 reg_address, u8 *params, int param_count,
 351        struct hidpp_report *response)
 352{
 353        struct hidpp_report *message;
 354        int ret, max_count;
 355
 356        /* Send as long report if short reports are not supported. */
 357        if (report_id == REPORT_ID_HIDPP_SHORT &&
 358            !(hidpp_dev->supported_reports & HIDPP_REPORT_SHORT_SUPPORTED))
 359                report_id = REPORT_ID_HIDPP_LONG;
 360
 361        switch (report_id) {
 362        case REPORT_ID_HIDPP_SHORT:
 363                max_count = HIDPP_REPORT_SHORT_LENGTH - 4;
 364                break;
 365        case REPORT_ID_HIDPP_LONG:
 366                max_count = HIDPP_REPORT_LONG_LENGTH - 4;
 367                break;
 368        case REPORT_ID_HIDPP_VERY_LONG:
 369                max_count = hidpp_dev->very_long_report_length - 4;
 370                break;
 371        default:
 372                return -EINVAL;
 373        }
 374
 375        if (param_count > max_count)
 376                return -EINVAL;
 377
 378        message = kzalloc(sizeof(struct hidpp_report), GFP_KERNEL);
 379        if (!message)
 380                return -ENOMEM;
 381        message->report_id = report_id;
 382        message->rap.sub_id = sub_id;
 383        message->rap.reg_address = reg_address;
 384        memcpy(&message->rap.params, params, param_count);
 385
 386        ret = hidpp_send_message_sync(hidpp_dev, message, response);
 387        kfree(message);
 388        return ret;
 389}
 390
 391static void delayed_work_cb(struct work_struct *work)
 392{
 393        struct hidpp_device *hidpp = container_of(work, struct hidpp_device,
 394                                                        work);
 395        hidpp_connect_event(hidpp);
 396}
 397
 398static inline bool hidpp_match_answer(struct hidpp_report *question,
 399                struct hidpp_report *answer)
 400{
 401        return (answer->fap.feature_index == question->fap.feature_index) &&
 402           (answer->fap.funcindex_clientid == question->fap.funcindex_clientid);
 403}
 404
 405static inline bool hidpp_match_error(struct hidpp_report *question,
 406                struct hidpp_report *answer)
 407{
 408        return ((answer->rap.sub_id == HIDPP_ERROR) ||
 409            (answer->fap.feature_index == HIDPP20_ERROR)) &&
 410            (answer->fap.funcindex_clientid == question->fap.feature_index) &&
 411            (answer->fap.params[0] == question->fap.funcindex_clientid);
 412}
 413
 414static inline bool hidpp_report_is_connect_event(struct hidpp_device *hidpp,
 415                struct hidpp_report *report)
 416{
 417        return (hidpp->wireless_feature_index &&
 418                (report->fap.feature_index == hidpp->wireless_feature_index)) ||
 419                ((report->report_id == REPORT_ID_HIDPP_SHORT) &&
 420                (report->rap.sub_id == 0x41));
 421}
 422
 423/**
 424 * hidpp_prefix_name() prefixes the current given name with "Logitech ".
 425 */
 426static void hidpp_prefix_name(char **name, int name_length)
 427{
 428#define PREFIX_LENGTH 9 /* "Logitech " */
 429
 430        int new_length;
 431        char *new_name;
 432
 433        if (name_length > PREFIX_LENGTH &&
 434            strncmp(*name, "Logitech ", PREFIX_LENGTH) == 0)
 435                /* The prefix has is already in the name */
 436                return;
 437
 438        new_length = PREFIX_LENGTH + name_length;
 439        new_name = kzalloc(new_length, GFP_KERNEL);
 440        if (!new_name)
 441                return;
 442
 443        snprintf(new_name, new_length, "Logitech %s", *name);
 444
 445        kfree(*name);
 446
 447        *name = new_name;
 448}
 449
 450/**
 451 * hidpp_scroll_counter_handle_scroll() - Send high- and low-resolution scroll
 452 *                                        events given a high-resolution wheel
 453 *                                        movement.
 454 * @counter: a hid_scroll_counter struct describing the wheel.
 455 * @hi_res_value: the movement of the wheel, in the mouse's high-resolution
 456 *                units.
 457 *
 458 * Given a high-resolution movement, this function converts the movement into
 459 * fractions of 120 and emits high-resolution scroll events for the input
 460 * device. It also uses the multiplier from &struct hid_scroll_counter to
 461 * emit low-resolution scroll events when appropriate for
 462 * backwards-compatibility with userspace input libraries.
 463 */
 464static void hidpp_scroll_counter_handle_scroll(struct input_dev *input_dev,
 465                                               struct hidpp_scroll_counter *counter,
 466                                               int hi_res_value)
 467{
 468        int low_res_value, remainder, direction;
 469        unsigned long long now, previous;
 470
 471        hi_res_value = hi_res_value * 120/counter->wheel_multiplier;
 472        input_report_rel(input_dev, REL_WHEEL_HI_RES, hi_res_value);
 473
 474        remainder = counter->remainder;
 475        direction = hi_res_value > 0 ? 1 : -1;
 476
 477        now = sched_clock();
 478        previous = counter->last_time;
 479        counter->last_time = now;
 480        /*
 481         * Reset the remainder after a period of inactivity or when the
 482         * direction changes. This prevents the REL_WHEEL emulation point
 483         * from sliding for devices that don't always provide the same
 484         * number of movements per detent.
 485         */
 486        if (now - previous > 1000000000 || direction != counter->direction)
 487                remainder = 0;
 488
 489        counter->direction = direction;
 490        remainder += hi_res_value;
 491
 492        /* Some wheels will rest 7/8ths of a detent from the previous detent
 493         * after slow movement, so we want the threshold for low-res events to
 494         * be in the middle between two detents (e.g. after 4/8ths) as
 495         * opposed to on the detents themselves (8/8ths).
 496         */
 497        if (abs(remainder) >= 60) {
 498                /* Add (or subtract) 1 because we want to trigger when the wheel
 499                 * is half-way to the next detent (i.e. scroll 1 detent after a
 500                 * 1/2 detent movement, 2 detents after a 1 1/2 detent movement,
 501                 * etc.).
 502                 */
 503                low_res_value = remainder / 120;
 504                if (low_res_value == 0)
 505                        low_res_value = (hi_res_value > 0 ? 1 : -1);
 506                input_report_rel(input_dev, REL_WHEEL, low_res_value);
 507                remainder -= low_res_value * 120;
 508        }
 509        counter->remainder = remainder;
 510}
 511
 512/* -------------------------------------------------------------------------- */
 513/* HIDP++ 1.0 commands                                                        */
 514/* -------------------------------------------------------------------------- */
 515
 516#define HIDPP_SET_REGISTER                              0x80
 517#define HIDPP_GET_REGISTER                              0x81
 518#define HIDPP_SET_LONG_REGISTER                         0x82
 519#define HIDPP_GET_LONG_REGISTER                         0x83
 520
 521/**
 522 * hidpp10_set_register - Modify a HID++ 1.0 register.
 523 * @hidpp_dev: the device to set the register on.
 524 * @register_address: the address of the register to modify.
 525 * @byte: the byte of the register to modify. Should be less than 3.
 526 * @mask: mask of the bits to modify
 527 * @value: new values for the bits in mask
 528 * Return: 0 if successful, otherwise a negative error code.
 529 */
 530static int hidpp10_set_register(struct hidpp_device *hidpp_dev,
 531        u8 register_address, u8 byte, u8 mask, u8 value)
 532{
 533        struct hidpp_report response;
 534        int ret;
 535        u8 params[3] = { 0 };
 536
 537        ret = hidpp_send_rap_command_sync(hidpp_dev,
 538                                          REPORT_ID_HIDPP_SHORT,
 539                                          HIDPP_GET_REGISTER,
 540                                          register_address,
 541                                          NULL, 0, &response);
 542        if (ret)
 543                return ret;
 544
 545        memcpy(params, response.rap.params, 3);
 546
 547        params[byte] &= ~mask;
 548        params[byte] |= value & mask;
 549
 550        return hidpp_send_rap_command_sync(hidpp_dev,
 551                                           REPORT_ID_HIDPP_SHORT,
 552                                           HIDPP_SET_REGISTER,
 553                                           register_address,
 554                                           params, 3, &response);
 555}
 556
 557#define HIDPP_REG_ENABLE_REPORTS                        0x00
 558#define HIDPP_ENABLE_CONSUMER_REPORT                    BIT(0)
 559#define HIDPP_ENABLE_WHEEL_REPORT                       BIT(2)
 560#define HIDPP_ENABLE_MOUSE_EXTRA_BTN_REPORT             BIT(3)
 561#define HIDPP_ENABLE_BAT_REPORT                         BIT(4)
 562#define HIDPP_ENABLE_HWHEEL_REPORT                      BIT(5)
 563
 564static int hidpp10_enable_battery_reporting(struct hidpp_device *hidpp_dev)
 565{
 566        return hidpp10_set_register(hidpp_dev, HIDPP_REG_ENABLE_REPORTS, 0,
 567                          HIDPP_ENABLE_BAT_REPORT, HIDPP_ENABLE_BAT_REPORT);
 568}
 569
 570#define HIDPP_REG_FEATURES                              0x01
 571#define HIDPP_ENABLE_SPECIAL_BUTTON_FUNC                BIT(1)
 572#define HIDPP_ENABLE_FAST_SCROLL                        BIT(6)
 573
 574/* On HID++ 1.0 devices, high-res scroll was called "scrolling acceleration". */
 575static int hidpp10_enable_scrolling_acceleration(struct hidpp_device *hidpp_dev)
 576{
 577        return hidpp10_set_register(hidpp_dev, HIDPP_REG_FEATURES, 0,
 578                          HIDPP_ENABLE_FAST_SCROLL, HIDPP_ENABLE_FAST_SCROLL);
 579}
 580
 581#define HIDPP_REG_BATTERY_STATUS                        0x07
 582
 583static int hidpp10_battery_status_map_level(u8 param)
 584{
 585        int level;
 586
 587        switch (param) {
 588        case 1 ... 2:
 589                level = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
 590                break;
 591        case 3 ... 4:
 592                level = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
 593                break;
 594        case 5 ... 6:
 595                level = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
 596                break;
 597        case 7:
 598                level = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
 599                break;
 600        default:
 601                level = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
 602        }
 603
 604        return level;
 605}
 606
 607static int hidpp10_battery_status_map_status(u8 param)
 608{
 609        int status;
 610
 611        switch (param) {
 612        case 0x00:
 613                /* discharging (in use) */
 614                status = POWER_SUPPLY_STATUS_DISCHARGING;
 615                break;
 616        case 0x21: /* (standard) charging */
 617        case 0x24: /* fast charging */
 618        case 0x25: /* slow charging */
 619                status = POWER_SUPPLY_STATUS_CHARGING;
 620                break;
 621        case 0x26: /* topping charge */
 622        case 0x22: /* charge complete */
 623                status = POWER_SUPPLY_STATUS_FULL;
 624                break;
 625        case 0x20: /* unknown */
 626                status = POWER_SUPPLY_STATUS_UNKNOWN;
 627                break;
 628        /*
 629         * 0x01...0x1F = reserved (not charging)
 630         * 0x23 = charging error
 631         * 0x27..0xff = reserved
 632         */
 633        default:
 634                status = POWER_SUPPLY_STATUS_NOT_CHARGING;
 635                break;
 636        }
 637
 638        return status;
 639}
 640
 641static int hidpp10_query_battery_status(struct hidpp_device *hidpp)
 642{
 643        struct hidpp_report response;
 644        int ret, status;
 645
 646        ret = hidpp_send_rap_command_sync(hidpp,
 647                                        REPORT_ID_HIDPP_SHORT,
 648                                        HIDPP_GET_REGISTER,
 649                                        HIDPP_REG_BATTERY_STATUS,
 650                                        NULL, 0, &response);
 651        if (ret)
 652                return ret;
 653
 654        hidpp->battery.level =
 655                hidpp10_battery_status_map_level(response.rap.params[0]);
 656        status = hidpp10_battery_status_map_status(response.rap.params[1]);
 657        hidpp->battery.status = status;
 658        /* the capacity is only available when discharging or full */
 659        hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
 660                                status == POWER_SUPPLY_STATUS_FULL;
 661
 662        return 0;
 663}
 664
 665#define HIDPP_REG_BATTERY_MILEAGE                       0x0D
 666
 667static int hidpp10_battery_mileage_map_status(u8 param)
 668{
 669        int status;
 670
 671        switch (param >> 6) {
 672        case 0x00:
 673                /* discharging (in use) */
 674                status = POWER_SUPPLY_STATUS_DISCHARGING;
 675                break;
 676        case 0x01: /* charging */
 677                status = POWER_SUPPLY_STATUS_CHARGING;
 678                break;
 679        case 0x02: /* charge complete */
 680                status = POWER_SUPPLY_STATUS_FULL;
 681                break;
 682        /*
 683         * 0x03 = charging error
 684         */
 685        default:
 686                status = POWER_SUPPLY_STATUS_NOT_CHARGING;
 687                break;
 688        }
 689
 690        return status;
 691}
 692
 693static int hidpp10_query_battery_mileage(struct hidpp_device *hidpp)
 694{
 695        struct hidpp_report response;
 696        int ret, status;
 697
 698        ret = hidpp_send_rap_command_sync(hidpp,
 699                                        REPORT_ID_HIDPP_SHORT,
 700                                        HIDPP_GET_REGISTER,
 701                                        HIDPP_REG_BATTERY_MILEAGE,
 702                                        NULL, 0, &response);
 703        if (ret)
 704                return ret;
 705
 706        hidpp->battery.capacity = response.rap.params[0];
 707        status = hidpp10_battery_mileage_map_status(response.rap.params[2]);
 708        hidpp->battery.status = status;
 709        /* the capacity is only available when discharging or full */
 710        hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
 711                                status == POWER_SUPPLY_STATUS_FULL;
 712
 713        return 0;
 714}
 715
 716static int hidpp10_battery_event(struct hidpp_device *hidpp, u8 *data, int size)
 717{
 718        struct hidpp_report *report = (struct hidpp_report *)data;
 719        int status, capacity, level;
 720        bool changed;
 721
 722        if (report->report_id != REPORT_ID_HIDPP_SHORT)
 723                return 0;
 724
 725        switch (report->rap.sub_id) {
 726        case HIDPP_REG_BATTERY_STATUS:
 727                capacity = hidpp->battery.capacity;
 728                level = hidpp10_battery_status_map_level(report->rawbytes[1]);
 729                status = hidpp10_battery_status_map_status(report->rawbytes[2]);
 730                break;
 731        case HIDPP_REG_BATTERY_MILEAGE:
 732                capacity = report->rap.params[0];
 733                level = hidpp->battery.level;
 734                status = hidpp10_battery_mileage_map_status(report->rawbytes[3]);
 735                break;
 736        default:
 737                return 0;
 738        }
 739
 740        changed = capacity != hidpp->battery.capacity ||
 741                  level != hidpp->battery.level ||
 742                  status != hidpp->battery.status;
 743
 744        /* the capacity is only available when discharging or full */
 745        hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
 746                                status == POWER_SUPPLY_STATUS_FULL;
 747
 748        if (changed) {
 749                hidpp->battery.level = level;
 750                hidpp->battery.status = status;
 751                if (hidpp->battery.ps)
 752                        power_supply_changed(hidpp->battery.ps);
 753        }
 754
 755        return 0;
 756}
 757
 758#define HIDPP_REG_PAIRING_INFORMATION                   0xB5
 759#define HIDPP_EXTENDED_PAIRING                          0x30
 760#define HIDPP_DEVICE_NAME                               0x40
 761
 762static char *hidpp_unifying_get_name(struct hidpp_device *hidpp_dev)
 763{
 764        struct hidpp_report response;
 765        int ret;
 766        u8 params[1] = { HIDPP_DEVICE_NAME };
 767        char *name;
 768        int len;
 769
 770        ret = hidpp_send_rap_command_sync(hidpp_dev,
 771                                        REPORT_ID_HIDPP_SHORT,
 772                                        HIDPP_GET_LONG_REGISTER,
 773                                        HIDPP_REG_PAIRING_INFORMATION,
 774                                        params, 1, &response);
 775        if (ret)
 776                return NULL;
 777
 778        len = response.rap.params[1];
 779
 780        if (2 + len > sizeof(response.rap.params))
 781                return NULL;
 782
 783        if (len < 4) /* logitech devices are usually at least Xddd */
 784                return NULL;
 785
 786        name = kzalloc(len + 1, GFP_KERNEL);
 787        if (!name)
 788                return NULL;
 789
 790        memcpy(name, &response.rap.params[2], len);
 791
 792        /* include the terminating '\0' */
 793        hidpp_prefix_name(&name, len + 1);
 794
 795        return name;
 796}
 797
 798static int hidpp_unifying_get_serial(struct hidpp_device *hidpp, u32 *serial)
 799{
 800        struct hidpp_report response;
 801        int ret;
 802        u8 params[1] = { HIDPP_EXTENDED_PAIRING };
 803
 804        ret = hidpp_send_rap_command_sync(hidpp,
 805                                        REPORT_ID_HIDPP_SHORT,
 806                                        HIDPP_GET_LONG_REGISTER,
 807                                        HIDPP_REG_PAIRING_INFORMATION,
 808                                        params, 1, &response);
 809        if (ret)
 810                return ret;
 811
 812        /*
 813         * We don't care about LE or BE, we will output it as a string
 814         * with %4phD, so we need to keep the order.
 815         */
 816        *serial = *((u32 *)&response.rap.params[1]);
 817        return 0;
 818}
 819
 820static int hidpp_unifying_init(struct hidpp_device *hidpp)
 821{
 822        struct hid_device *hdev = hidpp->hid_dev;
 823        const char *name;
 824        u32 serial;
 825        int ret;
 826
 827        ret = hidpp_unifying_get_serial(hidpp, &serial);
 828        if (ret)
 829                return ret;
 830
 831        snprintf(hdev->uniq, sizeof(hdev->uniq), "%04x-%4phD",
 832                 hdev->product, &serial);
 833        dbg_hid("HID++ Unifying: Got serial: %s\n", hdev->uniq);
 834
 835        name = hidpp_unifying_get_name(hidpp);
 836        if (!name)
 837                return -EIO;
 838
 839        snprintf(hdev->name, sizeof(hdev->name), "%s", name);
 840        dbg_hid("HID++ Unifying: Got name: %s\n", name);
 841
 842        kfree(name);
 843        return 0;
 844}
 845
 846/* -------------------------------------------------------------------------- */
 847/* 0x0000: Root                                                               */
 848/* -------------------------------------------------------------------------- */
 849
 850#define HIDPP_PAGE_ROOT                                 0x0000
 851#define HIDPP_PAGE_ROOT_IDX                             0x00
 852
 853#define CMD_ROOT_GET_FEATURE                            0x01
 854#define CMD_ROOT_GET_PROTOCOL_VERSION                   0x11
 855
 856static int hidpp_root_get_feature(struct hidpp_device *hidpp, u16 feature,
 857        u8 *feature_index, u8 *feature_type)
 858{
 859        struct hidpp_report response;
 860        int ret;
 861        u8 params[2] = { feature >> 8, feature & 0x00FF };
 862
 863        ret = hidpp_send_fap_command_sync(hidpp,
 864                        HIDPP_PAGE_ROOT_IDX,
 865                        CMD_ROOT_GET_FEATURE,
 866                        params, 2, &response);
 867        if (ret)
 868                return ret;
 869
 870        if (response.fap.params[0] == 0)
 871                return -ENOENT;
 872
 873        *feature_index = response.fap.params[0];
 874        *feature_type = response.fap.params[1];
 875
 876        return ret;
 877}
 878
 879static int hidpp_root_get_protocol_version(struct hidpp_device *hidpp)
 880{
 881        const u8 ping_byte = 0x5a;
 882        u8 ping_data[3] = { 0, 0, ping_byte };
 883        struct hidpp_report response;
 884        int ret;
 885
 886        ret = hidpp_send_rap_command_sync(hidpp,
 887                        REPORT_ID_HIDPP_SHORT,
 888                        HIDPP_PAGE_ROOT_IDX,
 889                        CMD_ROOT_GET_PROTOCOL_VERSION,
 890                        ping_data, sizeof(ping_data), &response);
 891
 892        if (ret == HIDPP_ERROR_INVALID_SUBID) {
 893                hidpp->protocol_major = 1;
 894                hidpp->protocol_minor = 0;
 895                goto print_version;
 896        }
 897
 898        /* the device might not be connected */
 899        if (ret == HIDPP_ERROR_RESOURCE_ERROR)
 900                return -EIO;
 901
 902        if (ret > 0) {
 903                hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
 904                        __func__, ret);
 905                return -EPROTO;
 906        }
 907        if (ret)
 908                return ret;
 909
 910        if (response.rap.params[2] != ping_byte) {
 911                hid_err(hidpp->hid_dev, "%s: ping mismatch 0x%02x != 0x%02x\n",
 912                        __func__, response.rap.params[2], ping_byte);
 913                return -EPROTO;
 914        }
 915
 916        hidpp->protocol_major = response.rap.params[0];
 917        hidpp->protocol_minor = response.rap.params[1];
 918
 919print_version:
 920        hid_info(hidpp->hid_dev, "HID++ %u.%u device connected.\n",
 921                 hidpp->protocol_major, hidpp->protocol_minor);
 922        return 0;
 923}
 924
 925/* -------------------------------------------------------------------------- */
 926/* 0x0005: GetDeviceNameType                                                  */
 927/* -------------------------------------------------------------------------- */
 928
 929#define HIDPP_PAGE_GET_DEVICE_NAME_TYPE                 0x0005
 930
 931#define CMD_GET_DEVICE_NAME_TYPE_GET_COUNT              0x01
 932#define CMD_GET_DEVICE_NAME_TYPE_GET_DEVICE_NAME        0x11
 933#define CMD_GET_DEVICE_NAME_TYPE_GET_TYPE               0x21
 934
 935static int hidpp_devicenametype_get_count(struct hidpp_device *hidpp,
 936        u8 feature_index, u8 *nameLength)
 937{
 938        struct hidpp_report response;
 939        int ret;
 940
 941        ret = hidpp_send_fap_command_sync(hidpp, feature_index,
 942                CMD_GET_DEVICE_NAME_TYPE_GET_COUNT, NULL, 0, &response);
 943
 944        if (ret > 0) {
 945                hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
 946                        __func__, ret);
 947                return -EPROTO;
 948        }
 949        if (ret)
 950                return ret;
 951
 952        *nameLength = response.fap.params[0];
 953
 954        return ret;
 955}
 956
 957static int hidpp_devicenametype_get_device_name(struct hidpp_device *hidpp,
 958        u8 feature_index, u8 char_index, char *device_name, int len_buf)
 959{
 960        struct hidpp_report response;
 961        int ret, i;
 962        int count;
 963
 964        ret = hidpp_send_fap_command_sync(hidpp, feature_index,
 965                CMD_GET_DEVICE_NAME_TYPE_GET_DEVICE_NAME, &char_index, 1,
 966                &response);
 967
 968        if (ret > 0) {
 969                hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
 970                        __func__, ret);
 971                return -EPROTO;
 972        }
 973        if (ret)
 974                return ret;
 975
 976        switch (response.report_id) {
 977        case REPORT_ID_HIDPP_VERY_LONG:
 978                count = hidpp->very_long_report_length - 4;
 979                break;
 980        case REPORT_ID_HIDPP_LONG:
 981                count = HIDPP_REPORT_LONG_LENGTH - 4;
 982                break;
 983        case REPORT_ID_HIDPP_SHORT:
 984                count = HIDPP_REPORT_SHORT_LENGTH - 4;
 985                break;
 986        default:
 987                return -EPROTO;
 988        }
 989
 990        if (len_buf < count)
 991                count = len_buf;
 992
 993        for (i = 0; i < count; i++)
 994                device_name[i] = response.fap.params[i];
 995
 996        return count;
 997}
 998
 999static char *hidpp_get_device_name(struct hidpp_device *hidpp)
1000{
1001        u8 feature_type;
1002        u8 feature_index;
1003        u8 __name_length;
1004        char *name;
1005        unsigned index = 0;
1006        int ret;
1007
1008        ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_GET_DEVICE_NAME_TYPE,
1009                &feature_index, &feature_type);
1010        if (ret)
1011                return NULL;
1012
1013        ret = hidpp_devicenametype_get_count(hidpp, feature_index,
1014                &__name_length);
1015        if (ret)
1016                return NULL;
1017
1018        name = kzalloc(__name_length + 1, GFP_KERNEL);
1019        if (!name)
1020                return NULL;
1021
1022        while (index < __name_length) {
1023                ret = hidpp_devicenametype_get_device_name(hidpp,
1024                        feature_index, index, name + index,
1025                        __name_length - index);
1026                if (ret <= 0) {
1027                        kfree(name);
1028                        return NULL;
1029                }
1030                index += ret;
1031        }
1032
1033        /* include the terminating '\0' */
1034        hidpp_prefix_name(&name, __name_length + 1);
1035
1036        return name;
1037}
1038
1039/* -------------------------------------------------------------------------- */
1040/* 0x1000: Battery level status                                               */
1041/* -------------------------------------------------------------------------- */
1042
1043#define HIDPP_PAGE_BATTERY_LEVEL_STATUS                         0x1000
1044
1045#define CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_LEVEL_STATUS       0x00
1046#define CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_CAPABILITY         0x10
1047
1048#define EVENT_BATTERY_LEVEL_STATUS_BROADCAST                    0x00
1049
1050#define FLAG_BATTERY_LEVEL_DISABLE_OSD                          BIT(0)
1051#define FLAG_BATTERY_LEVEL_MILEAGE                              BIT(1)
1052#define FLAG_BATTERY_LEVEL_RECHARGEABLE                         BIT(2)
1053
1054static int hidpp_map_battery_level(int capacity)
1055{
1056        if (capacity < 11)
1057                return POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1058        /*
1059         * The spec says this should be < 31 but some devices report 30
1060         * with brand new batteries and Windows reports 30 as "Good".
1061         */
1062        else if (capacity < 30)
1063                return POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1064        else if (capacity < 81)
1065                return POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1066        return POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1067}
1068
1069static int hidpp20_batterylevel_map_status_capacity(u8 data[3], int *capacity,
1070                                                    int *next_capacity,
1071                                                    int *level)
1072{
1073        int status;
1074
1075        *capacity = data[0];
1076        *next_capacity = data[1];
1077        *level = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
1078
1079        /* When discharging, we can rely on the device reported capacity.
1080         * For all other states the device reports 0 (unknown).
1081         */
1082        switch (data[2]) {
1083                case 0: /* discharging (in use) */
1084                        status = POWER_SUPPLY_STATUS_DISCHARGING;
1085                        *level = hidpp_map_battery_level(*capacity);
1086                        break;
1087                case 1: /* recharging */
1088                        status = POWER_SUPPLY_STATUS_CHARGING;
1089                        break;
1090                case 2: /* charge in final stage */
1091                        status = POWER_SUPPLY_STATUS_CHARGING;
1092                        break;
1093                case 3: /* charge complete */
1094                        status = POWER_SUPPLY_STATUS_FULL;
1095                        *level = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1096                        *capacity = 100;
1097                        break;
1098                case 4: /* recharging below optimal speed */
1099                        status = POWER_SUPPLY_STATUS_CHARGING;
1100                        break;
1101                /* 5 = invalid battery type
1102                   6 = thermal error
1103                   7 = other charging error */
1104                default:
1105                        status = POWER_SUPPLY_STATUS_NOT_CHARGING;
1106                        break;
1107        }
1108
1109        return status;
1110}
1111
1112static int hidpp20_batterylevel_get_battery_capacity(struct hidpp_device *hidpp,
1113                                                     u8 feature_index,
1114                                                     int *status,
1115                                                     int *capacity,
1116                                                     int *next_capacity,
1117                                                     int *level)
1118{
1119        struct hidpp_report response;
1120        int ret;
1121        u8 *params = (u8 *)response.fap.params;
1122
1123        ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1124                                          CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_LEVEL_STATUS,
1125                                          NULL, 0, &response);
1126        /* Ignore these intermittent errors */
1127        if (ret == HIDPP_ERROR_RESOURCE_ERROR)
1128                return -EIO;
1129        if (ret > 0) {
1130                hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1131                        __func__, ret);
1132                return -EPROTO;
1133        }
1134        if (ret)
1135                return ret;
1136
1137        *status = hidpp20_batterylevel_map_status_capacity(params, capacity,
1138                                                           next_capacity,
1139                                                           level);
1140
1141        return 0;
1142}
1143
1144static int hidpp20_batterylevel_get_battery_info(struct hidpp_device *hidpp,
1145                                                  u8 feature_index)
1146{
1147        struct hidpp_report response;
1148        int ret;
1149        u8 *params = (u8 *)response.fap.params;
1150        unsigned int level_count, flags;
1151
1152        ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1153                                          CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_CAPABILITY,
1154                                          NULL, 0, &response);
1155        if (ret > 0) {
1156                hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1157                        __func__, ret);
1158                return -EPROTO;
1159        }
1160        if (ret)
1161                return ret;
1162
1163        level_count = params[0];
1164        flags = params[1];
1165
1166        if (level_count < 10 || !(flags & FLAG_BATTERY_LEVEL_MILEAGE))
1167                hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS;
1168        else
1169                hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_MILEAGE;
1170
1171        return 0;
1172}
1173
1174static int hidpp20_query_battery_info(struct hidpp_device *hidpp)
1175{
1176        u8 feature_type;
1177        int ret;
1178        int status, capacity, next_capacity, level;
1179
1180        if (hidpp->battery.feature_index == 0xff) {
1181                ret = hidpp_root_get_feature(hidpp,
1182                                             HIDPP_PAGE_BATTERY_LEVEL_STATUS,
1183                                             &hidpp->battery.feature_index,
1184                                             &feature_type);
1185                if (ret)
1186                        return ret;
1187        }
1188
1189        ret = hidpp20_batterylevel_get_battery_capacity(hidpp,
1190                                                hidpp->battery.feature_index,
1191                                                &status, &capacity,
1192                                                &next_capacity, &level);
1193        if (ret)
1194                return ret;
1195
1196        ret = hidpp20_batterylevel_get_battery_info(hidpp,
1197                                                hidpp->battery.feature_index);
1198        if (ret)
1199                return ret;
1200
1201        hidpp->battery.status = status;
1202        hidpp->battery.capacity = capacity;
1203        hidpp->battery.level = level;
1204        /* the capacity is only available when discharging or full */
1205        hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
1206                                status == POWER_SUPPLY_STATUS_FULL;
1207
1208        return 0;
1209}
1210
1211static int hidpp20_battery_event(struct hidpp_device *hidpp,
1212                                 u8 *data, int size)
1213{
1214        struct hidpp_report *report = (struct hidpp_report *)data;
1215        int status, capacity, next_capacity, level;
1216        bool changed;
1217
1218        if (report->fap.feature_index != hidpp->battery.feature_index ||
1219            report->fap.funcindex_clientid != EVENT_BATTERY_LEVEL_STATUS_BROADCAST)
1220                return 0;
1221
1222        status = hidpp20_batterylevel_map_status_capacity(report->fap.params,
1223                                                          &capacity,
1224                                                          &next_capacity,
1225                                                          &level);
1226
1227        /* the capacity is only available when discharging or full */
1228        hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
1229                                status == POWER_SUPPLY_STATUS_FULL;
1230
1231        changed = capacity != hidpp->battery.capacity ||
1232                  level != hidpp->battery.level ||
1233                  status != hidpp->battery.status;
1234
1235        if (changed) {
1236                hidpp->battery.level = level;
1237                hidpp->battery.capacity = capacity;
1238                hidpp->battery.status = status;
1239                if (hidpp->battery.ps)
1240                        power_supply_changed(hidpp->battery.ps);
1241        }
1242
1243        return 0;
1244}
1245
1246/* -------------------------------------------------------------------------- */
1247/* 0x1001: Battery voltage                                                    */
1248/* -------------------------------------------------------------------------- */
1249
1250#define HIDPP_PAGE_BATTERY_VOLTAGE 0x1001
1251
1252#define CMD_BATTERY_VOLTAGE_GET_BATTERY_VOLTAGE 0x00
1253
1254#define EVENT_BATTERY_VOLTAGE_STATUS_BROADCAST 0x00
1255
1256static int hidpp20_battery_map_status_voltage(u8 data[3], int *voltage,
1257                                                int *level, int *charge_type)
1258{
1259        int status;
1260
1261        long flags = (long) data[2];
1262
1263        if (flags & 0x80)
1264                switch (flags & 0x07) {
1265                case 0:
1266                        status = POWER_SUPPLY_STATUS_CHARGING;
1267                        break;
1268                case 1:
1269                        status = POWER_SUPPLY_STATUS_FULL;
1270                        *level = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1271                        break;
1272                case 2:
1273                        status = POWER_SUPPLY_STATUS_NOT_CHARGING;
1274                        break;
1275                default:
1276                        status = POWER_SUPPLY_STATUS_UNKNOWN;
1277                        break;
1278                }
1279        else
1280                status = POWER_SUPPLY_STATUS_DISCHARGING;
1281
1282        *charge_type = POWER_SUPPLY_CHARGE_TYPE_STANDARD;
1283        if (test_bit(3, &flags)) {
1284                *charge_type = POWER_SUPPLY_CHARGE_TYPE_FAST;
1285        }
1286        if (test_bit(4, &flags)) {
1287                *charge_type = POWER_SUPPLY_CHARGE_TYPE_TRICKLE;
1288        }
1289        if (test_bit(5, &flags)) {
1290                *level = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1291        }
1292
1293        *voltage = get_unaligned_be16(data);
1294
1295        return status;
1296}
1297
1298static int hidpp20_battery_get_battery_voltage(struct hidpp_device *hidpp,
1299                                                 u8 feature_index,
1300                                                 int *status, int *voltage,
1301                                                 int *level, int *charge_type)
1302{
1303        struct hidpp_report response;
1304        int ret;
1305        u8 *params = (u8 *)response.fap.params;
1306
1307        ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1308                                          CMD_BATTERY_VOLTAGE_GET_BATTERY_VOLTAGE,
1309                                          NULL, 0, &response);
1310
1311        if (ret > 0) {
1312                hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1313                        __func__, ret);
1314                return -EPROTO;
1315        }
1316        if (ret)
1317                return ret;
1318
1319        hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_VOLTAGE;
1320
1321        *status = hidpp20_battery_map_status_voltage(params, voltage,
1322                                                     level, charge_type);
1323
1324        return 0;
1325}
1326
1327static int hidpp20_query_battery_voltage_info(struct hidpp_device *hidpp)
1328{
1329        u8 feature_type;
1330        int ret;
1331        int status, voltage, level, charge_type;
1332
1333        if (hidpp->battery.voltage_feature_index == 0xff) {
1334                ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_BATTERY_VOLTAGE,
1335                                             &hidpp->battery.voltage_feature_index,
1336                                             &feature_type);
1337                if (ret)
1338                        return ret;
1339        }
1340
1341        ret = hidpp20_battery_get_battery_voltage(hidpp,
1342                                                  hidpp->battery.voltage_feature_index,
1343                                                  &status, &voltage, &level, &charge_type);
1344
1345        if (ret)
1346                return ret;
1347
1348        hidpp->battery.status = status;
1349        hidpp->battery.voltage = voltage;
1350        hidpp->battery.level = level;
1351        hidpp->battery.charge_type = charge_type;
1352        hidpp->battery.online = status != POWER_SUPPLY_STATUS_NOT_CHARGING;
1353
1354        return 0;
1355}
1356
1357static int hidpp20_battery_voltage_event(struct hidpp_device *hidpp,
1358                                            u8 *data, int size)
1359{
1360        struct hidpp_report *report = (struct hidpp_report *)data;
1361        int status, voltage, level, charge_type;
1362
1363        if (report->fap.feature_index != hidpp->battery.voltage_feature_index ||
1364                report->fap.funcindex_clientid != EVENT_BATTERY_VOLTAGE_STATUS_BROADCAST)
1365                return 0;
1366
1367        status = hidpp20_battery_map_status_voltage(report->fap.params, &voltage,
1368                                                    &level, &charge_type);
1369
1370        hidpp->battery.online = status != POWER_SUPPLY_STATUS_NOT_CHARGING;
1371
1372        if (voltage != hidpp->battery.voltage || status != hidpp->battery.status) {
1373                hidpp->battery.voltage = voltage;
1374                hidpp->battery.status = status;
1375                hidpp->battery.level = level;
1376                hidpp->battery.charge_type = charge_type;
1377                if (hidpp->battery.ps)
1378                        power_supply_changed(hidpp->battery.ps);
1379        }
1380        return 0;
1381}
1382
1383static enum power_supply_property hidpp_battery_props[] = {
1384        POWER_SUPPLY_PROP_ONLINE,
1385        POWER_SUPPLY_PROP_STATUS,
1386        POWER_SUPPLY_PROP_SCOPE,
1387        POWER_SUPPLY_PROP_MODEL_NAME,
1388        POWER_SUPPLY_PROP_MANUFACTURER,
1389        POWER_SUPPLY_PROP_SERIAL_NUMBER,
1390        0, /* placeholder for POWER_SUPPLY_PROP_CAPACITY, */
1391        0, /* placeholder for POWER_SUPPLY_PROP_CAPACITY_LEVEL, */
1392        0, /* placeholder for POWER_SUPPLY_PROP_VOLTAGE_NOW, */
1393};
1394
1395static int hidpp_battery_get_property(struct power_supply *psy,
1396                                      enum power_supply_property psp,
1397                                      union power_supply_propval *val)
1398{
1399        struct hidpp_device *hidpp = power_supply_get_drvdata(psy);
1400        int ret = 0;
1401
1402        switch(psp) {
1403                case POWER_SUPPLY_PROP_STATUS:
1404                        val->intval = hidpp->battery.status;
1405                        break;
1406                case POWER_SUPPLY_PROP_CAPACITY:
1407                        val->intval = hidpp->battery.capacity;
1408                        break;
1409                case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
1410                        val->intval = hidpp->battery.level;
1411                        break;
1412                case POWER_SUPPLY_PROP_SCOPE:
1413                        val->intval = POWER_SUPPLY_SCOPE_DEVICE;
1414                        break;
1415                case POWER_SUPPLY_PROP_ONLINE:
1416                        val->intval = hidpp->battery.online;
1417                        break;
1418                case POWER_SUPPLY_PROP_MODEL_NAME:
1419                        if (!strncmp(hidpp->name, "Logitech ", 9))
1420                                val->strval = hidpp->name + 9;
1421                        else
1422                                val->strval = hidpp->name;
1423                        break;
1424                case POWER_SUPPLY_PROP_MANUFACTURER:
1425                        val->strval = "Logitech";
1426                        break;
1427                case POWER_SUPPLY_PROP_SERIAL_NUMBER:
1428                        val->strval = hidpp->hid_dev->uniq;
1429                        break;
1430                case POWER_SUPPLY_PROP_VOLTAGE_NOW:
1431                        /* hardware reports voltage in in mV. sysfs expects uV */
1432                        val->intval = hidpp->battery.voltage * 1000;
1433                        break;
1434                case POWER_SUPPLY_PROP_CHARGE_TYPE:
1435                        val->intval = hidpp->battery.charge_type;
1436                        break;
1437                default:
1438                        ret = -EINVAL;
1439                        break;
1440        }
1441
1442        return ret;
1443}
1444
1445/* -------------------------------------------------------------------------- */
1446/* 0x1d4b: Wireless device status                                             */
1447/* -------------------------------------------------------------------------- */
1448#define HIDPP_PAGE_WIRELESS_DEVICE_STATUS                       0x1d4b
1449
1450static int hidpp_set_wireless_feature_index(struct hidpp_device *hidpp)
1451{
1452        u8 feature_type;
1453        int ret;
1454
1455        ret = hidpp_root_get_feature(hidpp,
1456                                     HIDPP_PAGE_WIRELESS_DEVICE_STATUS,
1457                                     &hidpp->wireless_feature_index,
1458                                     &feature_type);
1459
1460        return ret;
1461}
1462
1463/* -------------------------------------------------------------------------- */
1464/* 0x2120: Hi-resolution scrolling                                            */
1465/* -------------------------------------------------------------------------- */
1466
1467#define HIDPP_PAGE_HI_RESOLUTION_SCROLLING                      0x2120
1468
1469#define CMD_HI_RESOLUTION_SCROLLING_SET_HIGHRES_SCROLLING_MODE  0x10
1470
1471static int hidpp_hrs_set_highres_scrolling_mode(struct hidpp_device *hidpp,
1472        bool enabled, u8 *multiplier)
1473{
1474        u8 feature_index;
1475        u8 feature_type;
1476        int ret;
1477        u8 params[1];
1478        struct hidpp_report response;
1479
1480        ret = hidpp_root_get_feature(hidpp,
1481                                     HIDPP_PAGE_HI_RESOLUTION_SCROLLING,
1482                                     &feature_index,
1483                                     &feature_type);
1484        if (ret)
1485                return ret;
1486
1487        params[0] = enabled ? BIT(0) : 0;
1488        ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1489                                          CMD_HI_RESOLUTION_SCROLLING_SET_HIGHRES_SCROLLING_MODE,
1490                                          params, sizeof(params), &response);
1491        if (ret)
1492                return ret;
1493        *multiplier = response.fap.params[1];
1494        return 0;
1495}
1496
1497/* -------------------------------------------------------------------------- */
1498/* 0x2121: HiRes Wheel                                                        */
1499/* -------------------------------------------------------------------------- */
1500
1501#define HIDPP_PAGE_HIRES_WHEEL          0x2121
1502
1503#define CMD_HIRES_WHEEL_GET_WHEEL_CAPABILITY    0x00
1504#define CMD_HIRES_WHEEL_SET_WHEEL_MODE          0x20
1505
1506static int hidpp_hrw_get_wheel_capability(struct hidpp_device *hidpp,
1507        u8 *multiplier)
1508{
1509        u8 feature_index;
1510        u8 feature_type;
1511        int ret;
1512        struct hidpp_report response;
1513
1514        ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_HIRES_WHEEL,
1515                                     &feature_index, &feature_type);
1516        if (ret)
1517                goto return_default;
1518
1519        ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1520                                          CMD_HIRES_WHEEL_GET_WHEEL_CAPABILITY,
1521                                          NULL, 0, &response);
1522        if (ret)
1523                goto return_default;
1524
1525        *multiplier = response.fap.params[0];
1526        return 0;
1527return_default:
1528        hid_warn(hidpp->hid_dev,
1529                 "Couldn't get wheel multiplier (error %d)\n", ret);
1530        return ret;
1531}
1532
1533static int hidpp_hrw_set_wheel_mode(struct hidpp_device *hidpp, bool invert,
1534        bool high_resolution, bool use_hidpp)
1535{
1536        u8 feature_index;
1537        u8 feature_type;
1538        int ret;
1539        u8 params[1];
1540        struct hidpp_report response;
1541
1542        ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_HIRES_WHEEL,
1543                                     &feature_index, &feature_type);
1544        if (ret)
1545                return ret;
1546
1547        params[0] = (invert          ? BIT(2) : 0) |
1548                    (high_resolution ? BIT(1) : 0) |
1549                    (use_hidpp       ? BIT(0) : 0);
1550
1551        return hidpp_send_fap_command_sync(hidpp, feature_index,
1552                                           CMD_HIRES_WHEEL_SET_WHEEL_MODE,
1553                                           params, sizeof(params), &response);
1554}
1555
1556/* -------------------------------------------------------------------------- */
1557/* 0x4301: Solar Keyboard                                                     */
1558/* -------------------------------------------------------------------------- */
1559
1560#define HIDPP_PAGE_SOLAR_KEYBOARD                       0x4301
1561
1562#define CMD_SOLAR_SET_LIGHT_MEASURE                     0x00
1563
1564#define EVENT_SOLAR_BATTERY_BROADCAST                   0x00
1565#define EVENT_SOLAR_BATTERY_LIGHT_MEASURE               0x10
1566#define EVENT_SOLAR_CHECK_LIGHT_BUTTON                  0x20
1567
1568static int hidpp_solar_request_battery_event(struct hidpp_device *hidpp)
1569{
1570        struct hidpp_report response;
1571        u8 params[2] = { 1, 1 };
1572        u8 feature_type;
1573        int ret;
1574
1575        if (hidpp->battery.feature_index == 0xff) {
1576                ret = hidpp_root_get_feature(hidpp,
1577                                             HIDPP_PAGE_SOLAR_KEYBOARD,
1578                                             &hidpp->battery.solar_feature_index,
1579                                             &feature_type);
1580                if (ret)
1581                        return ret;
1582        }
1583
1584        ret = hidpp_send_fap_command_sync(hidpp,
1585                                          hidpp->battery.solar_feature_index,
1586                                          CMD_SOLAR_SET_LIGHT_MEASURE,
1587                                          params, 2, &response);
1588        if (ret > 0) {
1589                hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1590                        __func__, ret);
1591                return -EPROTO;
1592        }
1593        if (ret)
1594                return ret;
1595
1596        hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_MILEAGE;
1597
1598        return 0;
1599}
1600
1601static int hidpp_solar_battery_event(struct hidpp_device *hidpp,
1602                                     u8 *data, int size)
1603{
1604        struct hidpp_report *report = (struct hidpp_report *)data;
1605        int capacity, lux, status;
1606        u8 function;
1607
1608        function = report->fap.funcindex_clientid;
1609
1610
1611        if (report->fap.feature_index != hidpp->battery.solar_feature_index ||
1612            !(function == EVENT_SOLAR_BATTERY_BROADCAST ||
1613              function == EVENT_SOLAR_BATTERY_LIGHT_MEASURE ||
1614              function == EVENT_SOLAR_CHECK_LIGHT_BUTTON))
1615                return 0;
1616
1617        capacity = report->fap.params[0];
1618
1619        switch (function) {
1620        case EVENT_SOLAR_BATTERY_LIGHT_MEASURE:
1621                lux = (report->fap.params[1] << 8) | report->fap.params[2];
1622                if (lux > 200)
1623                        status = POWER_SUPPLY_STATUS_CHARGING;
1624                else
1625                        status = POWER_SUPPLY_STATUS_DISCHARGING;
1626                break;
1627        case EVENT_SOLAR_CHECK_LIGHT_BUTTON:
1628        default:
1629                if (capacity < hidpp->battery.capacity)
1630                        status = POWER_SUPPLY_STATUS_DISCHARGING;
1631                else
1632                        status = POWER_SUPPLY_STATUS_CHARGING;
1633
1634        }
1635
1636        if (capacity == 100)
1637                status = POWER_SUPPLY_STATUS_FULL;
1638
1639        hidpp->battery.online = true;
1640        if (capacity != hidpp->battery.capacity ||
1641            status != hidpp->battery.status) {
1642                hidpp->battery.capacity = capacity;
1643                hidpp->battery.status = status;
1644                if (hidpp->battery.ps)
1645                        power_supply_changed(hidpp->battery.ps);
1646        }
1647
1648        return 0;
1649}
1650
1651/* -------------------------------------------------------------------------- */
1652/* 0x6010: Touchpad FW items                                                  */
1653/* -------------------------------------------------------------------------- */
1654
1655#define HIDPP_PAGE_TOUCHPAD_FW_ITEMS                    0x6010
1656
1657#define CMD_TOUCHPAD_FW_ITEMS_SET                       0x10
1658
1659struct hidpp_touchpad_fw_items {
1660        uint8_t presence;
1661        uint8_t desired_state;
1662        uint8_t state;
1663        uint8_t persistent;
1664};
1665
1666/**
1667 * send a set state command to the device by reading the current items->state
1668 * field. items is then filled with the current state.
1669 */
1670static int hidpp_touchpad_fw_items_set(struct hidpp_device *hidpp,
1671                                       u8 feature_index,
1672                                       struct hidpp_touchpad_fw_items *items)
1673{
1674        struct hidpp_report response;
1675        int ret;
1676        u8 *params = (u8 *)response.fap.params;
1677
1678        ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1679                CMD_TOUCHPAD_FW_ITEMS_SET, &items->state, 1, &response);
1680
1681        if (ret > 0) {
1682                hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1683                        __func__, ret);
1684                return -EPROTO;
1685        }
1686        if (ret)
1687                return ret;
1688
1689        items->presence = params[0];
1690        items->desired_state = params[1];
1691        items->state = params[2];
1692        items->persistent = params[3];
1693
1694        return 0;
1695}
1696
1697/* -------------------------------------------------------------------------- */
1698/* 0x6100: TouchPadRawXY                                                      */
1699/* -------------------------------------------------------------------------- */
1700
1701#define HIDPP_PAGE_TOUCHPAD_RAW_XY                      0x6100
1702
1703#define CMD_TOUCHPAD_GET_RAW_INFO                       0x01
1704#define CMD_TOUCHPAD_SET_RAW_REPORT_STATE               0x21
1705
1706#define EVENT_TOUCHPAD_RAW_XY                           0x00
1707
1708#define TOUCHPAD_RAW_XY_ORIGIN_LOWER_LEFT               0x01
1709#define TOUCHPAD_RAW_XY_ORIGIN_UPPER_LEFT               0x03
1710
1711struct hidpp_touchpad_raw_info {
1712        u16 x_size;
1713        u16 y_size;
1714        u8 z_range;
1715        u8 area_range;
1716        u8 timestamp_unit;
1717        u8 maxcontacts;
1718        u8 origin;
1719        u16 res;
1720};
1721
1722struct hidpp_touchpad_raw_xy_finger {
1723        u8 contact_type;
1724        u8 contact_status;
1725        u16 x;
1726        u16 y;
1727        u8 z;
1728        u8 area;
1729        u8 finger_id;
1730};
1731
1732struct hidpp_touchpad_raw_xy {
1733        u16 timestamp;
1734        struct hidpp_touchpad_raw_xy_finger fingers[2];
1735        u8 spurious_flag;
1736        u8 end_of_frame;
1737        u8 finger_count;
1738        u8 button;
1739};
1740
1741static int hidpp_touchpad_get_raw_info(struct hidpp_device *hidpp,
1742        u8 feature_index, struct hidpp_touchpad_raw_info *raw_info)
1743{
1744        struct hidpp_report response;
1745        int ret;
1746        u8 *params = (u8 *)response.fap.params;
1747
1748        ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1749                CMD_TOUCHPAD_GET_RAW_INFO, NULL, 0, &response);
1750
1751        if (ret > 0) {
1752                hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1753                        __func__, ret);
1754                return -EPROTO;
1755        }
1756        if (ret)
1757                return ret;
1758
1759        raw_info->x_size = get_unaligned_be16(&params[0]);
1760        raw_info->y_size = get_unaligned_be16(&params[2]);
1761        raw_info->z_range = params[4];
1762        raw_info->area_range = params[5];
1763        raw_info->maxcontacts = params[7];
1764        raw_info->origin = params[8];
1765        /* res is given in unit per inch */
1766        raw_info->res = get_unaligned_be16(&params[13]) * 2 / 51;
1767
1768        return ret;
1769}
1770
1771static int hidpp_touchpad_set_raw_report_state(struct hidpp_device *hidpp_dev,
1772                u8 feature_index, bool send_raw_reports,
1773                bool sensor_enhanced_settings)
1774{
1775        struct hidpp_report response;
1776
1777        /*
1778         * Params:
1779         *   bit 0 - enable raw
1780         *   bit 1 - 16bit Z, no area
1781         *   bit 2 - enhanced sensitivity
1782         *   bit 3 - width, height (4 bits each) instead of area
1783         *   bit 4 - send raw + gestures (degrades smoothness)
1784         *   remaining bits - reserved
1785         */
1786        u8 params = send_raw_reports | (sensor_enhanced_settings << 2);
1787
1788        return hidpp_send_fap_command_sync(hidpp_dev, feature_index,
1789                CMD_TOUCHPAD_SET_RAW_REPORT_STATE, &params, 1, &response);
1790}
1791
1792static void hidpp_touchpad_touch_event(u8 *data,
1793        struct hidpp_touchpad_raw_xy_finger *finger)
1794{
1795        u8 x_m = data[0] << 2;
1796        u8 y_m = data[2] << 2;
1797
1798        finger->x = x_m << 6 | data[1];
1799        finger->y = y_m << 6 | data[3];
1800
1801        finger->contact_type = data[0] >> 6;
1802        finger->contact_status = data[2] >> 6;
1803
1804        finger->z = data[4];
1805        finger->area = data[5];
1806        finger->finger_id = data[6] >> 4;
1807}
1808
1809static void hidpp_touchpad_raw_xy_event(struct hidpp_device *hidpp_dev,
1810                u8 *data, struct hidpp_touchpad_raw_xy *raw_xy)
1811{
1812        memset(raw_xy, 0, sizeof(struct hidpp_touchpad_raw_xy));
1813        raw_xy->end_of_frame = data[8] & 0x01;
1814        raw_xy->spurious_flag = (data[8] >> 1) & 0x01;
1815        raw_xy->finger_count = data[15] & 0x0f;
1816        raw_xy->button = (data[8] >> 2) & 0x01;
1817
1818        if (raw_xy->finger_count) {
1819                hidpp_touchpad_touch_event(&data[2], &raw_xy->fingers[0]);
1820                hidpp_touchpad_touch_event(&data[9], &raw_xy->fingers[1]);
1821        }
1822}
1823
1824/* -------------------------------------------------------------------------- */
1825/* 0x8123: Force feedback support                                             */
1826/* -------------------------------------------------------------------------- */
1827
1828#define HIDPP_FF_GET_INFO               0x01
1829#define HIDPP_FF_RESET_ALL              0x11
1830#define HIDPP_FF_DOWNLOAD_EFFECT        0x21
1831#define HIDPP_FF_SET_EFFECT_STATE       0x31
1832#define HIDPP_FF_DESTROY_EFFECT         0x41
1833#define HIDPP_FF_GET_APERTURE           0x51
1834#define HIDPP_FF_SET_APERTURE           0x61
1835#define HIDPP_FF_GET_GLOBAL_GAINS       0x71
1836#define HIDPP_FF_SET_GLOBAL_GAINS       0x81
1837
1838#define HIDPP_FF_EFFECT_STATE_GET       0x00
1839#define HIDPP_FF_EFFECT_STATE_STOP      0x01
1840#define HIDPP_FF_EFFECT_STATE_PLAY      0x02
1841#define HIDPP_FF_EFFECT_STATE_PAUSE     0x03
1842
1843#define HIDPP_FF_EFFECT_CONSTANT        0x00
1844#define HIDPP_FF_EFFECT_PERIODIC_SINE           0x01
1845#define HIDPP_FF_EFFECT_PERIODIC_SQUARE         0x02
1846#define HIDPP_FF_EFFECT_PERIODIC_TRIANGLE       0x03
1847#define HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHUP     0x04
1848#define HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHDOWN   0x05
1849#define HIDPP_FF_EFFECT_SPRING          0x06
1850#define HIDPP_FF_EFFECT_DAMPER          0x07
1851#define HIDPP_FF_EFFECT_FRICTION        0x08
1852#define HIDPP_FF_EFFECT_INERTIA         0x09
1853#define HIDPP_FF_EFFECT_RAMP            0x0A
1854
1855#define HIDPP_FF_EFFECT_AUTOSTART       0x80
1856
1857#define HIDPP_FF_EFFECTID_NONE          -1
1858#define HIDPP_FF_EFFECTID_AUTOCENTER    -2
1859#define HIDPP_AUTOCENTER_PARAMS_LENGTH  18
1860
1861#define HIDPP_FF_MAX_PARAMS     20
1862#define HIDPP_FF_RESERVED_SLOTS 1
1863
1864struct hidpp_ff_private_data {
1865        struct hidpp_device *hidpp;
1866        u8 feature_index;
1867        u8 version;
1868        u16 gain;
1869        s16 range;
1870        u8 slot_autocenter;
1871        u8 num_effects;
1872        int *effect_ids;
1873        struct workqueue_struct *wq;
1874        atomic_t workqueue_size;
1875};
1876
1877struct hidpp_ff_work_data {
1878        struct work_struct work;
1879        struct hidpp_ff_private_data *data;
1880        int effect_id;
1881        u8 command;
1882        u8 params[HIDPP_FF_MAX_PARAMS];
1883        u8 size;
1884};
1885
1886static const signed short hidpp_ff_effects[] = {
1887        FF_CONSTANT,
1888        FF_PERIODIC,
1889        FF_SINE,
1890        FF_SQUARE,
1891        FF_SAW_UP,
1892        FF_SAW_DOWN,
1893        FF_TRIANGLE,
1894        FF_SPRING,
1895        FF_DAMPER,
1896        FF_AUTOCENTER,
1897        FF_GAIN,
1898        -1
1899};
1900
1901static const signed short hidpp_ff_effects_v2[] = {
1902        FF_RAMP,
1903        FF_FRICTION,
1904        FF_INERTIA,
1905        -1
1906};
1907
1908static const u8 HIDPP_FF_CONDITION_CMDS[] = {
1909        HIDPP_FF_EFFECT_SPRING,
1910        HIDPP_FF_EFFECT_FRICTION,
1911        HIDPP_FF_EFFECT_DAMPER,
1912        HIDPP_FF_EFFECT_INERTIA
1913};
1914
1915static const char *HIDPP_FF_CONDITION_NAMES[] = {
1916        "spring",
1917        "friction",
1918        "damper",
1919        "inertia"
1920};
1921
1922
1923static u8 hidpp_ff_find_effect(struct hidpp_ff_private_data *data, int effect_id)
1924{
1925        int i;
1926
1927        for (i = 0; i < data->num_effects; i++)
1928                if (data->effect_ids[i] == effect_id)
1929                        return i+1;
1930
1931        return 0;
1932}
1933
1934static void hidpp_ff_work_handler(struct work_struct *w)
1935{
1936        struct hidpp_ff_work_data *wd = container_of(w, struct hidpp_ff_work_data, work);
1937        struct hidpp_ff_private_data *data = wd->data;
1938        struct hidpp_report response;
1939        u8 slot;
1940        int ret;
1941
1942        /* add slot number if needed */
1943        switch (wd->effect_id) {
1944        case HIDPP_FF_EFFECTID_AUTOCENTER:
1945                wd->params[0] = data->slot_autocenter;
1946                break;
1947        case HIDPP_FF_EFFECTID_NONE:
1948                /* leave slot as zero */
1949                break;
1950        default:
1951                /* find current slot for effect */
1952                wd->params[0] = hidpp_ff_find_effect(data, wd->effect_id);
1953                break;
1954        }
1955
1956        /* send command and wait for reply */
1957        ret = hidpp_send_fap_command_sync(data->hidpp, data->feature_index,
1958                wd->command, wd->params, wd->size, &response);
1959
1960        if (ret) {
1961                hid_err(data->hidpp->hid_dev, "Failed to send command to device!\n");
1962                goto out;
1963        }
1964
1965        /* parse return data */
1966        switch (wd->command) {
1967        case HIDPP_FF_DOWNLOAD_EFFECT:
1968                slot = response.fap.params[0];
1969                if (slot > 0 && slot <= data->num_effects) {
1970                        if (wd->effect_id >= 0)
1971                                /* regular effect uploaded */
1972                                data->effect_ids[slot-1] = wd->effect_id;
1973                        else if (wd->effect_id >= HIDPP_FF_EFFECTID_AUTOCENTER)
1974                                /* autocenter spring uploaded */
1975                                data->slot_autocenter = slot;
1976                }
1977                break;
1978        case HIDPP_FF_DESTROY_EFFECT:
1979                if (wd->effect_id >= 0)
1980                        /* regular effect destroyed */
1981                        data->effect_ids[wd->params[0]-1] = -1;
1982                else if (wd->effect_id >= HIDPP_FF_EFFECTID_AUTOCENTER)
1983                        /* autocenter spring destoyed */
1984                        data->slot_autocenter = 0;
1985                break;
1986        case HIDPP_FF_SET_GLOBAL_GAINS:
1987                data->gain = (wd->params[0] << 8) + wd->params[1];
1988                break;
1989        case HIDPP_FF_SET_APERTURE:
1990                data->range = (wd->params[0] << 8) + wd->params[1];
1991                break;
1992        default:
1993                /* no action needed */
1994                break;
1995        }
1996
1997out:
1998        atomic_dec(&data->workqueue_size);
1999        kfree(wd);
2000}
2001
2002static int hidpp_ff_queue_work(struct hidpp_ff_private_data *data, int effect_id, u8 command, u8 *params, u8 size)
2003{
2004        struct hidpp_ff_work_data *wd = kzalloc(sizeof(*wd), GFP_KERNEL);
2005        int s;
2006
2007        if (!wd)
2008                return -ENOMEM;
2009
2010        INIT_WORK(&wd->work, hidpp_ff_work_handler);
2011
2012        wd->data = data;
2013        wd->effect_id = effect_id;
2014        wd->command = command;
2015        wd->size = size;
2016        memcpy(wd->params, params, size);
2017
2018        atomic_inc(&data->workqueue_size);
2019        queue_work(data->wq, &wd->work);
2020
2021        /* warn about excessive queue size */
2022        s = atomic_read(&data->workqueue_size);
2023        if (s >= 20 && s % 20 == 0)
2024                hid_warn(data->hidpp->hid_dev, "Force feedback command queue contains %d commands, causing substantial delays!", s);
2025
2026        return 0;
2027}
2028
2029static int hidpp_ff_upload_effect(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old)
2030{
2031        struct hidpp_ff_private_data *data = dev->ff->private;
2032        u8 params[20];
2033        u8 size;
2034        int force;
2035
2036        /* set common parameters */
2037        params[2] = effect->replay.length >> 8;
2038        params[3] = effect->replay.length & 255;
2039        params[4] = effect->replay.delay >> 8;
2040        params[5] = effect->replay.delay & 255;
2041
2042        switch (effect->type) {
2043        case FF_CONSTANT:
2044                force = (effect->u.constant.level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
2045                params[1] = HIDPP_FF_EFFECT_CONSTANT;
2046                params[6] = force >> 8;
2047                params[7] = force & 255;
2048                params[8] = effect->u.constant.envelope.attack_level >> 7;
2049                params[9] = effect->u.constant.envelope.attack_length >> 8;
2050                params[10] = effect->u.constant.envelope.attack_length & 255;
2051                params[11] = effect->u.constant.envelope.fade_level >> 7;
2052                params[12] = effect->u.constant.envelope.fade_length >> 8;
2053                params[13] = effect->u.constant.envelope.fade_length & 255;
2054                size = 14;
2055                dbg_hid("Uploading constant force level=%d in dir %d = %d\n",
2056                                effect->u.constant.level,
2057                                effect->direction, force);
2058                dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
2059                                effect->u.constant.envelope.attack_level,
2060                                effect->u.constant.envelope.attack_length,
2061                                effect->u.constant.envelope.fade_level,
2062                                effect->u.constant.envelope.fade_length);
2063                break;
2064        case FF_PERIODIC:
2065        {
2066                switch (effect->u.periodic.waveform) {
2067                case FF_SINE:
2068                        params[1] = HIDPP_FF_EFFECT_PERIODIC_SINE;
2069                        break;
2070                case FF_SQUARE:
2071                        params[1] = HIDPP_FF_EFFECT_PERIODIC_SQUARE;
2072                        break;
2073                case FF_SAW_UP:
2074                        params[1] = HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHUP;
2075                        break;
2076                case FF_SAW_DOWN:
2077                        params[1] = HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHDOWN;
2078                        break;
2079                case FF_TRIANGLE:
2080                        params[1] = HIDPP_FF_EFFECT_PERIODIC_TRIANGLE;
2081                        break;
2082                default:
2083                        hid_err(data->hidpp->hid_dev, "Unexpected periodic waveform type %i!\n", effect->u.periodic.waveform);
2084                        return -EINVAL;
2085                }
2086                force = (effect->u.periodic.magnitude * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
2087                params[6] = effect->u.periodic.magnitude >> 8;
2088                params[7] = effect->u.periodic.magnitude & 255;
2089                params[8] = effect->u.periodic.offset >> 8;
2090                params[9] = effect->u.periodic.offset & 255;
2091                params[10] = effect->u.periodic.period >> 8;
2092                params[11] = effect->u.periodic.period & 255;
2093                params[12] = effect->u.periodic.phase >> 8;
2094                params[13] = effect->u.periodic.phase & 255;
2095                params[14] = effect->u.periodic.envelope.attack_level >> 7;
2096                params[15] = effect->u.periodic.envelope.attack_length >> 8;
2097                params[16] = effect->u.periodic.envelope.attack_length & 255;
2098                params[17] = effect->u.periodic.envelope.fade_level >> 7;
2099                params[18] = effect->u.periodic.envelope.fade_length >> 8;
2100                params[19] = effect->u.periodic.envelope.fade_length & 255;
2101                size = 20;
2102                dbg_hid("Uploading periodic force mag=%d/dir=%d, offset=%d, period=%d ms, phase=%d\n",
2103                                effect->u.periodic.magnitude, effect->direction,
2104                                effect->u.periodic.offset,
2105                                effect->u.periodic.period,
2106                                effect->u.periodic.phase);
2107                dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
2108                                effect->u.periodic.envelope.attack_level,
2109                                effect->u.periodic.envelope.attack_length,
2110                                effect->u.periodic.envelope.fade_level,
2111                                effect->u.periodic.envelope.fade_length);
2112                break;
2113        }
2114        case FF_RAMP:
2115                params[1] = HIDPP_FF_EFFECT_RAMP;
2116                force = (effect->u.ramp.start_level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
2117                params[6] = force >> 8;
2118                params[7] = force & 255;
2119                force = (effect->u.ramp.end_level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
2120                params[8] = force >> 8;
2121                params[9] = force & 255;
2122                params[10] = effect->u.ramp.envelope.attack_level >> 7;
2123                params[11] = effect->u.ramp.envelope.attack_length >> 8;
2124                params[12] = effect->u.ramp.envelope.attack_length & 255;
2125                params[13] = effect->u.ramp.envelope.fade_level >> 7;
2126                params[14] = effect->u.ramp.envelope.fade_length >> 8;
2127                params[15] = effect->u.ramp.envelope.fade_length & 255;
2128                size = 16;
2129                dbg_hid("Uploading ramp force level=%d -> %d in dir %d = %d\n",
2130                                effect->u.ramp.start_level,
2131                                effect->u.ramp.end_level,
2132                                effect->direction, force);
2133                dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
2134                                effect->u.ramp.envelope.attack_level,
2135                                effect->u.ramp.envelope.attack_length,
2136                                effect->u.ramp.envelope.fade_level,
2137                                effect->u.ramp.envelope.fade_length);
2138                break;
2139        case FF_FRICTION:
2140        case FF_INERTIA:
2141        case FF_SPRING:
2142        case FF_DAMPER:
2143                params[1] = HIDPP_FF_CONDITION_CMDS[effect->type - FF_SPRING];
2144                params[6] = effect->u.condition[0].left_saturation >> 9;
2145                params[7] = (effect->u.condition[0].left_saturation >> 1) & 255;
2146                params[8] = effect->u.condition[0].left_coeff >> 8;
2147                params[9] = effect->u.condition[0].left_coeff & 255;
2148                params[10] = effect->u.condition[0].deadband >> 9;
2149                params[11] = (effect->u.condition[0].deadband >> 1) & 255;
2150                params[12] = effect->u.condition[0].center >> 8;
2151                params[13] = effect->u.condition[0].center & 255;
2152                params[14] = effect->u.condition[0].right_coeff >> 8;
2153                params[15] = effect->u.condition[0].right_coeff & 255;
2154                params[16] = effect->u.condition[0].right_saturation >> 9;
2155                params[17] = (effect->u.condition[0].right_saturation >> 1) & 255;
2156                size = 18;
2157                dbg_hid("Uploading %s force left coeff=%d, left sat=%d, right coeff=%d, right sat=%d\n",
2158                                HIDPP_FF_CONDITION_NAMES[effect->type - FF_SPRING],
2159                                effect->u.condition[0].left_coeff,
2160                                effect->u.condition[0].left_saturation,
2161                                effect->u.condition[0].right_coeff,
2162                                effect->u.condition[0].right_saturation);
2163                dbg_hid("          deadband=%d, center=%d\n",
2164                                effect->u.condition[0].deadband,
2165                                effect->u.condition[0].center);
2166                break;
2167        default:
2168                hid_err(data->hidpp->hid_dev, "Unexpected force type %i!\n", effect->type);
2169                return -EINVAL;
2170        }
2171
2172        return hidpp_ff_queue_work(data, effect->id, HIDPP_FF_DOWNLOAD_EFFECT, params, size);
2173}
2174
2175static int hidpp_ff_playback(struct input_dev *dev, int effect_id, int value)
2176{
2177        struct hidpp_ff_private_data *data = dev->ff->private;
2178        u8 params[2];
2179
2180        params[1] = value ? HIDPP_FF_EFFECT_STATE_PLAY : HIDPP_FF_EFFECT_STATE_STOP;
2181
2182        dbg_hid("St%sing playback of effect %d.\n", value?"art":"opp", effect_id);
2183
2184        return hidpp_ff_queue_work(data, effect_id, HIDPP_FF_SET_EFFECT_STATE, params, ARRAY_SIZE(params));
2185}
2186
2187static int hidpp_ff_erase_effect(struct input_dev *dev, int effect_id)
2188{
2189        struct hidpp_ff_private_data *data = dev->ff->private;
2190        u8 slot = 0;
2191
2192        dbg_hid("Erasing effect %d.\n", effect_id);
2193
2194        return hidpp_ff_queue_work(data, effect_id, HIDPP_FF_DESTROY_EFFECT, &slot, 1);
2195}
2196
2197static void hidpp_ff_set_autocenter(struct input_dev *dev, u16 magnitude)
2198{
2199        struct hidpp_ff_private_data *data = dev->ff->private;
2200        u8 params[HIDPP_AUTOCENTER_PARAMS_LENGTH];
2201
2202        dbg_hid("Setting autocenter to %d.\n", magnitude);
2203
2204        /* start a standard spring effect */
2205        params[1] = HIDPP_FF_EFFECT_SPRING | HIDPP_FF_EFFECT_AUTOSTART;
2206        /* zero delay and duration */
2207        params[2] = params[3] = params[4] = params[5] = 0;
2208        /* set coeff to 25% of saturation */
2209        params[8] = params[14] = magnitude >> 11;
2210        params[9] = params[15] = (magnitude >> 3) & 255;
2211        params[6] = params[16] = magnitude >> 9;
2212        params[7] = params[17] = (magnitude >> 1) & 255;
2213        /* zero deadband and center */
2214        params[10] = params[11] = params[12] = params[13] = 0;
2215
2216        hidpp_ff_queue_work(data, HIDPP_FF_EFFECTID_AUTOCENTER, HIDPP_FF_DOWNLOAD_EFFECT, params, ARRAY_SIZE(params));
2217}
2218
2219static void hidpp_ff_set_gain(struct input_dev *dev, u16 gain)
2220{
2221        struct hidpp_ff_private_data *data = dev->ff->private;
2222        u8 params[4];
2223
2224        dbg_hid("Setting gain to %d.\n", gain);
2225
2226        params[0] = gain >> 8;
2227        params[1] = gain & 255;
2228        params[2] = 0; /* no boost */
2229        params[3] = 0;
2230
2231        hidpp_ff_queue_work(data, HIDPP_FF_EFFECTID_NONE, HIDPP_FF_SET_GLOBAL_GAINS, params, ARRAY_SIZE(params));
2232}
2233
2234static ssize_t hidpp_ff_range_show(struct device *dev, struct device_attribute *attr, char *buf)
2235{
2236        struct hid_device *hid = to_hid_device(dev);
2237        struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
2238        struct input_dev *idev = hidinput->input;
2239        struct hidpp_ff_private_data *data = idev->ff->private;
2240
2241        return scnprintf(buf, PAGE_SIZE, "%u\n", data->range);
2242}
2243
2244static ssize_t hidpp_ff_range_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
2245{
2246        struct hid_device *hid = to_hid_device(dev);
2247        struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
2248        struct input_dev *idev = hidinput->input;
2249        struct hidpp_ff_private_data *data = idev->ff->private;
2250        u8 params[2];
2251        int range = simple_strtoul(buf, NULL, 10);
2252
2253        range = clamp(range, 180, 900);
2254
2255        params[0] = range >> 8;
2256        params[1] = range & 0x00FF;
2257
2258        hidpp_ff_queue_work(data, -1, HIDPP_FF_SET_APERTURE, params, ARRAY_SIZE(params));
2259
2260        return count;
2261}
2262
2263static DEVICE_ATTR(range, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH, hidpp_ff_range_show, hidpp_ff_range_store);
2264
2265static void hidpp_ff_destroy(struct ff_device *ff)
2266{
2267        struct hidpp_ff_private_data *data = ff->private;
2268        struct hid_device *hid = data->hidpp->hid_dev;
2269
2270        hid_info(hid, "Unloading HID++ force feedback.\n");
2271
2272        device_remove_file(&hid->dev, &dev_attr_range);
2273        destroy_workqueue(data->wq);
2274        kfree(data->effect_ids);
2275}
2276
2277static int hidpp_ff_init(struct hidpp_device *hidpp,
2278                         struct hidpp_ff_private_data *data)
2279{
2280        struct hid_device *hid = hidpp->hid_dev;
2281        struct hid_input *hidinput;
2282        struct input_dev *dev;
2283        const struct usb_device_descriptor *udesc = &(hid_to_usb_dev(hid)->descriptor);
2284        const u16 bcdDevice = le16_to_cpu(udesc->bcdDevice);
2285        struct ff_device *ff;
2286        int error, j, num_slots = data->num_effects;
2287        u8 version;
2288
2289        if (list_empty(&hid->inputs)) {
2290                hid_err(hid, "no inputs found\n");
2291                return -ENODEV;
2292        }
2293        hidinput = list_entry(hid->inputs.next, struct hid_input, list);
2294        dev = hidinput->input;
2295
2296        if (!dev) {
2297                hid_err(hid, "Struct input_dev not set!\n");
2298                return -EINVAL;
2299        }
2300
2301        /* Get firmware release */
2302        version = bcdDevice & 255;
2303
2304        /* Set supported force feedback capabilities */
2305        for (j = 0; hidpp_ff_effects[j] >= 0; j++)
2306                set_bit(hidpp_ff_effects[j], dev->ffbit);
2307        if (version > 1)
2308                for (j = 0; hidpp_ff_effects_v2[j] >= 0; j++)
2309                        set_bit(hidpp_ff_effects_v2[j], dev->ffbit);
2310
2311        error = input_ff_create(dev, num_slots);
2312
2313        if (error) {
2314                hid_err(dev, "Failed to create FF device!\n");
2315                return error;
2316        }
2317        /*
2318         * Create a copy of passed data, so we can transfer memory
2319         * ownership to FF core
2320         */
2321        data = kmemdup(data, sizeof(*data), GFP_KERNEL);
2322        if (!data)
2323                return -ENOMEM;
2324        data->effect_ids = kcalloc(num_slots, sizeof(int), GFP_KERNEL);
2325        if (!data->effect_ids) {
2326                kfree(data);
2327                return -ENOMEM;
2328        }
2329        data->wq = create_singlethread_workqueue("hidpp-ff-sendqueue");
2330        if (!data->wq) {
2331                kfree(data->effect_ids);
2332                kfree(data);
2333                return -ENOMEM;
2334        }
2335
2336        data->hidpp = hidpp;
2337        data->version = version;
2338        for (j = 0; j < num_slots; j++)
2339                data->effect_ids[j] = -1;
2340
2341        ff = dev->ff;
2342        ff->private = data;
2343
2344        ff->upload = hidpp_ff_upload_effect;
2345        ff->erase = hidpp_ff_erase_effect;
2346        ff->playback = hidpp_ff_playback;
2347        ff->set_gain = hidpp_ff_set_gain;
2348        ff->set_autocenter = hidpp_ff_set_autocenter;
2349        ff->destroy = hidpp_ff_destroy;
2350
2351        /* Create sysfs interface */
2352        error = device_create_file(&(hidpp->hid_dev->dev), &dev_attr_range);
2353        if (error)
2354                hid_warn(hidpp->hid_dev, "Unable to create sysfs interface for \"range\", errno %d!\n", error);
2355
2356        /* init the hardware command queue */
2357        atomic_set(&data->workqueue_size, 0);
2358
2359        hid_info(hid, "Force feedback support loaded (firmware release %d).\n",
2360                 version);
2361
2362        return 0;
2363}
2364
2365/* ************************************************************************** */
2366/*                                                                            */
2367/* Device Support                                                             */
2368/*                                                                            */
2369/* ************************************************************************** */
2370
2371/* -------------------------------------------------------------------------- */
2372/* Touchpad HID++ devices                                                     */
2373/* -------------------------------------------------------------------------- */
2374
2375#define WTP_MANUAL_RESOLUTION                           39
2376
2377struct wtp_data {
2378        u16 x_size, y_size;
2379        u8 finger_count;
2380        u8 mt_feature_index;
2381        u8 button_feature_index;
2382        u8 maxcontacts;
2383        bool flip_y;
2384        unsigned int resolution;
2385};
2386
2387static int wtp_input_mapping(struct hid_device *hdev, struct hid_input *hi,
2388                struct hid_field *field, struct hid_usage *usage,
2389                unsigned long **bit, int *max)
2390{
2391        return -1;
2392}
2393
2394static void wtp_populate_input(struct hidpp_device *hidpp,
2395                               struct input_dev *input_dev)
2396{
2397        struct wtp_data *wd = hidpp->private_data;
2398
2399        __set_bit(EV_ABS, input_dev->evbit);
2400        __set_bit(EV_KEY, input_dev->evbit);
2401        __clear_bit(EV_REL, input_dev->evbit);
2402        __clear_bit(EV_LED, input_dev->evbit);
2403
2404        input_set_abs_params(input_dev, ABS_MT_POSITION_X, 0, wd->x_size, 0, 0);
2405        input_abs_set_res(input_dev, ABS_MT_POSITION_X, wd->resolution);
2406        input_set_abs_params(input_dev, ABS_MT_POSITION_Y, 0, wd->y_size, 0, 0);
2407        input_abs_set_res(input_dev, ABS_MT_POSITION_Y, wd->resolution);
2408
2409        /* Max pressure is not given by the devices, pick one */
2410        input_set_abs_params(input_dev, ABS_MT_PRESSURE, 0, 50, 0, 0);
2411
2412        input_set_capability(input_dev, EV_KEY, BTN_LEFT);
2413
2414        if (hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS)
2415                input_set_capability(input_dev, EV_KEY, BTN_RIGHT);
2416        else
2417                __set_bit(INPUT_PROP_BUTTONPAD, input_dev->propbit);
2418
2419        input_mt_init_slots(input_dev, wd->maxcontacts, INPUT_MT_POINTER |
2420                INPUT_MT_DROP_UNUSED);
2421}
2422
2423static void wtp_touch_event(struct hidpp_device *hidpp,
2424        struct hidpp_touchpad_raw_xy_finger *touch_report)
2425{
2426        struct wtp_data *wd = hidpp->private_data;
2427        int slot;
2428
2429        if (!touch_report->finger_id || touch_report->contact_type)
2430                /* no actual data */
2431                return;
2432
2433        slot = input_mt_get_slot_by_key(hidpp->input, touch_report->finger_id);
2434
2435        input_mt_slot(hidpp->input, slot);
2436        input_mt_report_slot_state(hidpp->input, MT_TOOL_FINGER,
2437                                        touch_report->contact_status);
2438        if (touch_report->contact_status) {
2439                input_event(hidpp->input, EV_ABS, ABS_MT_POSITION_X,
2440                                touch_report->x);
2441                input_event(hidpp->input, EV_ABS, ABS_MT_POSITION_Y,
2442                                wd->flip_y ? wd->y_size - touch_report->y :
2443                                             touch_report->y);
2444                input_event(hidpp->input, EV_ABS, ABS_MT_PRESSURE,
2445                                touch_report->area);
2446        }
2447}
2448
2449static void wtp_send_raw_xy_event(struct hidpp_device *hidpp,
2450                struct hidpp_touchpad_raw_xy *raw)
2451{
2452        int i;
2453
2454        for (i = 0; i < 2; i++)
2455                wtp_touch_event(hidpp, &(raw->fingers[i]));
2456
2457        if (raw->end_of_frame &&
2458            !(hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS))
2459                input_event(hidpp->input, EV_KEY, BTN_LEFT, raw->button);
2460
2461        if (raw->end_of_frame || raw->finger_count <= 2) {
2462                input_mt_sync_frame(hidpp->input);
2463                input_sync(hidpp->input);
2464        }
2465}
2466
2467static int wtp_mouse_raw_xy_event(struct hidpp_device *hidpp, u8 *data)
2468{
2469        struct wtp_data *wd = hidpp->private_data;
2470        u8 c1_area = ((data[7] & 0xf) * (data[7] & 0xf) +
2471                      (data[7] >> 4) * (data[7] >> 4)) / 2;
2472        u8 c2_area = ((data[13] & 0xf) * (data[13] & 0xf) +
2473                      (data[13] >> 4) * (data[13] >> 4)) / 2;
2474        struct hidpp_touchpad_raw_xy raw = {
2475                .timestamp = data[1],
2476                .fingers = {
2477                        {
2478                                .contact_type = 0,
2479                                .contact_status = !!data[7],
2480                                .x = get_unaligned_le16(&data[3]),
2481                                .y = get_unaligned_le16(&data[5]),
2482                                .z = c1_area,
2483                                .area = c1_area,
2484                                .finger_id = data[2],
2485                        }, {
2486                                .contact_type = 0,
2487                                .contact_status = !!data[13],
2488                                .x = get_unaligned_le16(&data[9]),
2489                                .y = get_unaligned_le16(&data[11]),
2490                                .z = c2_area,
2491                                .area = c2_area,
2492                                .finger_id = data[8],
2493                        }
2494                },
2495                .finger_count = wd->maxcontacts,
2496                .spurious_flag = 0,
2497                .end_of_frame = (data[0] >> 7) == 0,
2498                .button = data[0] & 0x01,
2499        };
2500
2501        wtp_send_raw_xy_event(hidpp, &raw);
2502
2503        return 1;
2504}
2505
2506static int wtp_raw_event(struct hid_device *hdev, u8 *data, int size)
2507{
2508        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2509        struct wtp_data *wd = hidpp->private_data;
2510        struct hidpp_report *report = (struct hidpp_report *)data;
2511        struct hidpp_touchpad_raw_xy raw;
2512
2513        if (!wd || !hidpp->input)
2514                return 1;
2515
2516        switch (data[0]) {
2517        case 0x02:
2518                if (size < 2) {
2519                        hid_err(hdev, "Received HID report of bad size (%d)",
2520                                size);
2521                        return 1;
2522                }
2523                if (hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS) {
2524                        input_event(hidpp->input, EV_KEY, BTN_LEFT,
2525                                        !!(data[1] & 0x01));
2526                        input_event(hidpp->input, EV_KEY, BTN_RIGHT,
2527                                        !!(data[1] & 0x02));
2528                        input_sync(hidpp->input);
2529                        return 0;
2530                } else {
2531                        if (size < 21)
2532                                return 1;
2533                        return wtp_mouse_raw_xy_event(hidpp, &data[7]);
2534                }
2535        case REPORT_ID_HIDPP_LONG:
2536                /* size is already checked in hidpp_raw_event. */
2537                if ((report->fap.feature_index != wd->mt_feature_index) ||
2538                    (report->fap.funcindex_clientid != EVENT_TOUCHPAD_RAW_XY))
2539                        return 1;
2540                hidpp_touchpad_raw_xy_event(hidpp, data + 4, &raw);
2541
2542                wtp_send_raw_xy_event(hidpp, &raw);
2543                return 0;
2544        }
2545
2546        return 0;
2547}
2548
2549static int wtp_get_config(struct hidpp_device *hidpp)
2550{
2551        struct wtp_data *wd = hidpp->private_data;
2552        struct hidpp_touchpad_raw_info raw_info = {0};
2553        u8 feature_type;
2554        int ret;
2555
2556        ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_TOUCHPAD_RAW_XY,
2557                &wd->mt_feature_index, &feature_type);
2558        if (ret)
2559                /* means that the device is not powered up */
2560                return ret;
2561
2562        ret = hidpp_touchpad_get_raw_info(hidpp, wd->mt_feature_index,
2563                &raw_info);
2564        if (ret)
2565                return ret;
2566
2567        wd->x_size = raw_info.x_size;
2568        wd->y_size = raw_info.y_size;
2569        wd->maxcontacts = raw_info.maxcontacts;
2570        wd->flip_y = raw_info.origin == TOUCHPAD_RAW_XY_ORIGIN_LOWER_LEFT;
2571        wd->resolution = raw_info.res;
2572        if (!wd->resolution)
2573                wd->resolution = WTP_MANUAL_RESOLUTION;
2574
2575        return 0;
2576}
2577
2578static int wtp_allocate(struct hid_device *hdev, const struct hid_device_id *id)
2579{
2580        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2581        struct wtp_data *wd;
2582
2583        wd = devm_kzalloc(&hdev->dev, sizeof(struct wtp_data),
2584                        GFP_KERNEL);
2585        if (!wd)
2586                return -ENOMEM;
2587
2588        hidpp->private_data = wd;
2589
2590        return 0;
2591};
2592
2593static int wtp_connect(struct hid_device *hdev, bool connected)
2594{
2595        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2596        struct wtp_data *wd = hidpp->private_data;
2597        int ret;
2598
2599        if (!wd->x_size) {
2600                ret = wtp_get_config(hidpp);
2601                if (ret) {
2602                        hid_err(hdev, "Can not get wtp config: %d\n", ret);
2603                        return ret;
2604                }
2605        }
2606
2607        return hidpp_touchpad_set_raw_report_state(hidpp, wd->mt_feature_index,
2608                        true, true);
2609}
2610
2611/* ------------------------------------------------------------------------- */
2612/* Logitech M560 devices                                                     */
2613/* ------------------------------------------------------------------------- */
2614
2615/*
2616 * Logitech M560 protocol overview
2617 *
2618 * The Logitech M560 mouse, is designed for windows 8. When the middle and/or
2619 * the sides buttons are pressed, it sends some keyboard keys events
2620 * instead of buttons ones.
2621 * To complicate things further, the middle button keys sequence
2622 * is different from the odd press and the even press.
2623 *
2624 * forward button -> Super_R
2625 * backward button -> Super_L+'d' (press only)
2626 * middle button -> 1st time: Alt_L+SuperL+XF86TouchpadOff (press only)
2627 *                  2nd time: left-click (press only)
2628 * NB: press-only means that when the button is pressed, the
2629 * KeyPress/ButtonPress and KeyRelease/ButtonRelease events are generated
2630 * together sequentially; instead when the button is released, no event is
2631 * generated !
2632 *
2633 * With the command
2634 *      10<xx>0a 3500af03 (where <xx> is the mouse id),
2635 * the mouse reacts differently:
2636 * - it never sends a keyboard key event
2637 * - for the three mouse button it sends:
2638 *      middle button               press   11<xx>0a 3500af00...
2639 *      side 1 button (forward)     press   11<xx>0a 3500b000...
2640 *      side 2 button (backward)    press   11<xx>0a 3500ae00...
2641 *      middle/side1/side2 button   release 11<xx>0a 35000000...
2642 */
2643
2644static const u8 m560_config_parameter[] = {0x00, 0xaf, 0x03};
2645
2646/* how buttons are mapped in the report */
2647#define M560_MOUSE_BTN_LEFT             0x01
2648#define M560_MOUSE_BTN_RIGHT            0x02
2649#define M560_MOUSE_BTN_WHEEL_LEFT       0x08
2650#define M560_MOUSE_BTN_WHEEL_RIGHT      0x10
2651
2652#define M560_SUB_ID                     0x0a
2653#define M560_BUTTON_MODE_REGISTER       0x35
2654
2655static int m560_send_config_command(struct hid_device *hdev, bool connected)
2656{
2657        struct hidpp_report response;
2658        struct hidpp_device *hidpp_dev;
2659
2660        hidpp_dev = hid_get_drvdata(hdev);
2661
2662        return hidpp_send_rap_command_sync(
2663                hidpp_dev,
2664                REPORT_ID_HIDPP_SHORT,
2665                M560_SUB_ID,
2666                M560_BUTTON_MODE_REGISTER,
2667                (u8 *)m560_config_parameter,
2668                sizeof(m560_config_parameter),
2669                &response
2670        );
2671}
2672
2673static int m560_raw_event(struct hid_device *hdev, u8 *data, int size)
2674{
2675        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2676
2677        /* sanity check */
2678        if (!hidpp->input) {
2679                hid_err(hdev, "error in parameter\n");
2680                return -EINVAL;
2681        }
2682
2683        if (size < 7) {
2684                hid_err(hdev, "error in report\n");
2685                return 0;
2686        }
2687
2688        if (data[0] == REPORT_ID_HIDPP_LONG &&
2689            data[2] == M560_SUB_ID && data[6] == 0x00) {
2690                /*
2691                 * m560 mouse report for middle, forward and backward button
2692                 *
2693                 * data[0] = 0x11
2694                 * data[1] = device-id
2695                 * data[2] = 0x0a
2696                 * data[5] = 0xaf -> middle
2697                 *           0xb0 -> forward
2698                 *           0xae -> backward
2699                 *           0x00 -> release all
2700                 * data[6] = 0x00
2701                 */
2702
2703                switch (data[5]) {
2704                case 0xaf:
2705                        input_report_key(hidpp->input, BTN_MIDDLE, 1);
2706                        break;
2707                case 0xb0:
2708                        input_report_key(hidpp->input, BTN_FORWARD, 1);
2709                        break;
2710                case 0xae:
2711                        input_report_key(hidpp->input, BTN_BACK, 1);
2712                        break;
2713                case 0x00:
2714                        input_report_key(hidpp->input, BTN_BACK, 0);
2715                        input_report_key(hidpp->input, BTN_FORWARD, 0);
2716                        input_report_key(hidpp->input, BTN_MIDDLE, 0);
2717                        break;
2718                default:
2719                        hid_err(hdev, "error in report\n");
2720                        return 0;
2721                }
2722                input_sync(hidpp->input);
2723
2724        } else if (data[0] == 0x02) {
2725                /*
2726                 * Logitech M560 mouse report
2727                 *
2728                 * data[0] = type (0x02)
2729                 * data[1..2] = buttons
2730                 * data[3..5] = xy
2731                 * data[6] = wheel
2732                 */
2733
2734                int v;
2735
2736                input_report_key(hidpp->input, BTN_LEFT,
2737                        !!(data[1] & M560_MOUSE_BTN_LEFT));
2738                input_report_key(hidpp->input, BTN_RIGHT,
2739                        !!(data[1] & M560_MOUSE_BTN_RIGHT));
2740
2741                if (data[1] & M560_MOUSE_BTN_WHEEL_LEFT) {
2742                        input_report_rel(hidpp->input, REL_HWHEEL, -1);
2743                        input_report_rel(hidpp->input, REL_HWHEEL_HI_RES,
2744                                         -120);
2745                } else if (data[1] & M560_MOUSE_BTN_WHEEL_RIGHT) {
2746                        input_report_rel(hidpp->input, REL_HWHEEL, 1);
2747                        input_report_rel(hidpp->input, REL_HWHEEL_HI_RES,
2748                                         120);
2749                }
2750
2751                v = hid_snto32(hid_field_extract(hdev, data+3, 0, 12), 12);
2752                input_report_rel(hidpp->input, REL_X, v);
2753
2754                v = hid_snto32(hid_field_extract(hdev, data+3, 12, 12), 12);
2755                input_report_rel(hidpp->input, REL_Y, v);
2756
2757                v = hid_snto32(data[6], 8);
2758                if (v != 0)
2759                        hidpp_scroll_counter_handle_scroll(hidpp->input,
2760                                        &hidpp->vertical_wheel_counter, v);
2761
2762                input_sync(hidpp->input);
2763        }
2764
2765        return 1;
2766}
2767
2768static void m560_populate_input(struct hidpp_device *hidpp,
2769                                struct input_dev *input_dev)
2770{
2771        __set_bit(EV_KEY, input_dev->evbit);
2772        __set_bit(BTN_MIDDLE, input_dev->keybit);
2773        __set_bit(BTN_RIGHT, input_dev->keybit);
2774        __set_bit(BTN_LEFT, input_dev->keybit);
2775        __set_bit(BTN_BACK, input_dev->keybit);
2776        __set_bit(BTN_FORWARD, input_dev->keybit);
2777
2778        __set_bit(EV_REL, input_dev->evbit);
2779        __set_bit(REL_X, input_dev->relbit);
2780        __set_bit(REL_Y, input_dev->relbit);
2781        __set_bit(REL_WHEEL, input_dev->relbit);
2782        __set_bit(REL_HWHEEL, input_dev->relbit);
2783        __set_bit(REL_WHEEL_HI_RES, input_dev->relbit);
2784        __set_bit(REL_HWHEEL_HI_RES, input_dev->relbit);
2785}
2786
2787static int m560_input_mapping(struct hid_device *hdev, struct hid_input *hi,
2788                struct hid_field *field, struct hid_usage *usage,
2789                unsigned long **bit, int *max)
2790{
2791        return -1;
2792}
2793
2794/* ------------------------------------------------------------------------- */
2795/* Logitech K400 devices                                                     */
2796/* ------------------------------------------------------------------------- */
2797
2798/*
2799 * The Logitech K400 keyboard has an embedded touchpad which is seen
2800 * as a mouse from the OS point of view. There is a hardware shortcut to disable
2801 * tap-to-click but the setting is not remembered accross reset, annoying some
2802 * users.
2803 *
2804 * We can toggle this feature from the host by using the feature 0x6010:
2805 * Touchpad FW items
2806 */
2807
2808struct k400_private_data {
2809        u8 feature_index;
2810};
2811
2812static int k400_disable_tap_to_click(struct hidpp_device *hidpp)
2813{
2814        struct k400_private_data *k400 = hidpp->private_data;
2815        struct hidpp_touchpad_fw_items items = {};
2816        int ret;
2817        u8 feature_type;
2818
2819        if (!k400->feature_index) {
2820                ret = hidpp_root_get_feature(hidpp,
2821                        HIDPP_PAGE_TOUCHPAD_FW_ITEMS,
2822                        &k400->feature_index, &feature_type);
2823                if (ret)
2824                        /* means that the device is not powered up */
2825                        return ret;
2826        }
2827
2828        ret = hidpp_touchpad_fw_items_set(hidpp, k400->feature_index, &items);
2829        if (ret)
2830                return ret;
2831
2832        return 0;
2833}
2834
2835static int k400_allocate(struct hid_device *hdev)
2836{
2837        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2838        struct k400_private_data *k400;
2839
2840        k400 = devm_kzalloc(&hdev->dev, sizeof(struct k400_private_data),
2841                            GFP_KERNEL);
2842        if (!k400)
2843                return -ENOMEM;
2844
2845        hidpp->private_data = k400;
2846
2847        return 0;
2848};
2849
2850static int k400_connect(struct hid_device *hdev, bool connected)
2851{
2852        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2853
2854        if (!disable_tap_to_click)
2855                return 0;
2856
2857        return k400_disable_tap_to_click(hidpp);
2858}
2859
2860/* ------------------------------------------------------------------------- */
2861/* Logitech G920 Driving Force Racing Wheel for Xbox One                     */
2862/* ------------------------------------------------------------------------- */
2863
2864#define HIDPP_PAGE_G920_FORCE_FEEDBACK                  0x8123
2865
2866static int g920_ff_set_autocenter(struct hidpp_device *hidpp,
2867                                  struct hidpp_ff_private_data *data)
2868{
2869        struct hidpp_report response;
2870        u8 params[HIDPP_AUTOCENTER_PARAMS_LENGTH] = {
2871                [1] = HIDPP_FF_EFFECT_SPRING | HIDPP_FF_EFFECT_AUTOSTART,
2872        };
2873        int ret;
2874
2875        /* initialize with zero autocenter to get wheel in usable state */
2876
2877        dbg_hid("Setting autocenter to 0.\n");
2878        ret = hidpp_send_fap_command_sync(hidpp, data->feature_index,
2879                                          HIDPP_FF_DOWNLOAD_EFFECT,
2880                                          params, ARRAY_SIZE(params),
2881                                          &response);
2882        if (ret)
2883                hid_warn(hidpp->hid_dev, "Failed to autocenter device!\n");
2884        else
2885                data->slot_autocenter = response.fap.params[0];
2886
2887        return ret;
2888}
2889
2890static int g920_get_config(struct hidpp_device *hidpp,
2891                           struct hidpp_ff_private_data *data)
2892{
2893        struct hidpp_report response;
2894        u8 feature_type;
2895        int ret;
2896
2897        memset(data, 0, sizeof(*data));
2898
2899        /* Find feature and store for later use */
2900        ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_G920_FORCE_FEEDBACK,
2901                                     &data->feature_index, &feature_type);
2902        if (ret)
2903                return ret;
2904
2905        /* Read number of slots available in device */
2906        ret = hidpp_send_fap_command_sync(hidpp, data->feature_index,
2907                                          HIDPP_FF_GET_INFO,
2908                                          NULL, 0,
2909                                          &response);
2910        if (ret) {
2911                if (ret < 0)
2912                        return ret;
2913                hid_err(hidpp->hid_dev,
2914                        "%s: received protocol error 0x%02x\n", __func__, ret);
2915                return -EPROTO;
2916        }
2917
2918        data->num_effects = response.fap.params[0] - HIDPP_FF_RESERVED_SLOTS;
2919
2920        /* reset all forces */
2921        ret = hidpp_send_fap_command_sync(hidpp, data->feature_index,
2922                                          HIDPP_FF_RESET_ALL,
2923                                          NULL, 0,
2924                                          &response);
2925        if (ret)
2926                hid_warn(hidpp->hid_dev, "Failed to reset all forces!\n");
2927
2928        ret = hidpp_send_fap_command_sync(hidpp, data->feature_index,
2929                                          HIDPP_FF_GET_APERTURE,
2930                                          NULL, 0,
2931                                          &response);
2932        if (ret) {
2933                hid_warn(hidpp->hid_dev,
2934                         "Failed to read range from device!\n");
2935        }
2936        data->range = ret ?
2937                900 : get_unaligned_be16(&response.fap.params[0]);
2938
2939        /* Read the current gain values */
2940        ret = hidpp_send_fap_command_sync(hidpp, data->feature_index,
2941                                          HIDPP_FF_GET_GLOBAL_GAINS,
2942                                          NULL, 0,
2943                                          &response);
2944        if (ret)
2945                hid_warn(hidpp->hid_dev,
2946                         "Failed to read gain values from device!\n");
2947        data->gain = ret ?
2948                0xffff : get_unaligned_be16(&response.fap.params[0]);
2949
2950        /* ignore boost value at response.fap.params[2] */
2951
2952        return g920_ff_set_autocenter(hidpp, data);
2953}
2954
2955/* -------------------------------------------------------------------------- */
2956/* Logitech Dinovo Mini keyboard with builtin touchpad                        */
2957/* -------------------------------------------------------------------------- */
2958#define DINOVO_MINI_PRODUCT_ID          0xb30c
2959
2960static int lg_dinovo_input_mapping(struct hid_device *hdev, struct hid_input *hi,
2961                struct hid_field *field, struct hid_usage *usage,
2962                unsigned long **bit, int *max)
2963{
2964        if ((usage->hid & HID_USAGE_PAGE) != HID_UP_LOGIVENDOR)
2965                return 0;
2966
2967        switch (usage->hid & HID_USAGE) {
2968        case 0x00d: lg_map_key_clear(KEY_MEDIA);        break;
2969        default:
2970                return 0;
2971        }
2972        return 1;
2973}
2974
2975/* -------------------------------------------------------------------------- */
2976/* HID++1.0 devices which use HID++ reports for their wheels                  */
2977/* -------------------------------------------------------------------------- */
2978static int hidpp10_wheel_connect(struct hidpp_device *hidpp)
2979{
2980        return hidpp10_set_register(hidpp, HIDPP_REG_ENABLE_REPORTS, 0,
2981                        HIDPP_ENABLE_WHEEL_REPORT | HIDPP_ENABLE_HWHEEL_REPORT,
2982                        HIDPP_ENABLE_WHEEL_REPORT | HIDPP_ENABLE_HWHEEL_REPORT);
2983}
2984
2985static int hidpp10_wheel_raw_event(struct hidpp_device *hidpp,
2986                                   u8 *data, int size)
2987{
2988        s8 value, hvalue;
2989
2990        if (!hidpp->input)
2991                return -EINVAL;
2992
2993        if (size < 7)
2994                return 0;
2995
2996        if (data[0] != REPORT_ID_HIDPP_SHORT || data[2] != HIDPP_SUB_ID_ROLLER)
2997                return 0;
2998
2999        value = data[3];
3000        hvalue = data[4];
3001
3002        input_report_rel(hidpp->input, REL_WHEEL, value);
3003        input_report_rel(hidpp->input, REL_WHEEL_HI_RES, value * 120);
3004        input_report_rel(hidpp->input, REL_HWHEEL, hvalue);
3005        input_report_rel(hidpp->input, REL_HWHEEL_HI_RES, hvalue * 120);
3006        input_sync(hidpp->input);
3007
3008        return 1;
3009}
3010
3011static void hidpp10_wheel_populate_input(struct hidpp_device *hidpp,
3012                                         struct input_dev *input_dev)
3013{
3014        __set_bit(EV_REL, input_dev->evbit);
3015        __set_bit(REL_WHEEL, input_dev->relbit);
3016        __set_bit(REL_WHEEL_HI_RES, input_dev->relbit);
3017        __set_bit(REL_HWHEEL, input_dev->relbit);
3018        __set_bit(REL_HWHEEL_HI_RES, input_dev->relbit);
3019}
3020
3021/* -------------------------------------------------------------------------- */
3022/* HID++1.0 mice which use HID++ reports for extra mouse buttons              */
3023/* -------------------------------------------------------------------------- */
3024static int hidpp10_extra_mouse_buttons_connect(struct hidpp_device *hidpp)
3025{
3026        return hidpp10_set_register(hidpp, HIDPP_REG_ENABLE_REPORTS, 0,
3027                                    HIDPP_ENABLE_MOUSE_EXTRA_BTN_REPORT,
3028                                    HIDPP_ENABLE_MOUSE_EXTRA_BTN_REPORT);
3029}
3030
3031static int hidpp10_extra_mouse_buttons_raw_event(struct hidpp_device *hidpp,
3032                                    u8 *data, int size)
3033{
3034        int i;
3035
3036        if (!hidpp->input)
3037                return -EINVAL;
3038
3039        if (size < 7)
3040                return 0;
3041
3042        if (data[0] != REPORT_ID_HIDPP_SHORT ||
3043            data[2] != HIDPP_SUB_ID_MOUSE_EXTRA_BTNS)
3044                return 0;
3045
3046        /*
3047         * Buttons are either delivered through the regular mouse report *or*
3048         * through the extra buttons report. At least for button 6 how it is
3049         * delivered differs per receiver firmware version. Even receivers with
3050         * the same usb-id show different behavior, so we handle both cases.
3051         */
3052        for (i = 0; i < 8; i++)
3053                input_report_key(hidpp->input, BTN_MOUSE + i,
3054                                 (data[3] & (1 << i)));
3055
3056        /* Some mice report events on button 9+, use BTN_MISC */
3057        for (i = 0; i < 8; i++)
3058                input_report_key(hidpp->input, BTN_MISC + i,
3059                                 (data[4] & (1 << i)));
3060
3061        input_sync(hidpp->input);
3062        return 1;
3063}
3064
3065static void hidpp10_extra_mouse_buttons_populate_input(
3066                        struct hidpp_device *hidpp, struct input_dev *input_dev)
3067{
3068        /* BTN_MOUSE - BTN_MOUSE+7 are set already by the descriptor */
3069        __set_bit(BTN_0, input_dev->keybit);
3070        __set_bit(BTN_1, input_dev->keybit);
3071        __set_bit(BTN_2, input_dev->keybit);
3072        __set_bit(BTN_3, input_dev->keybit);
3073        __set_bit(BTN_4, input_dev->keybit);
3074        __set_bit(BTN_5, input_dev->keybit);
3075        __set_bit(BTN_6, input_dev->keybit);
3076        __set_bit(BTN_7, input_dev->keybit);
3077}
3078
3079/* -------------------------------------------------------------------------- */
3080/* HID++1.0 kbds which only report 0x10xx consumer usages through sub-id 0x03 */
3081/* -------------------------------------------------------------------------- */
3082
3083/* Find the consumer-page input report desc and change Maximums to 0x107f */
3084static u8 *hidpp10_consumer_keys_report_fixup(struct hidpp_device *hidpp,
3085                                              u8 *_rdesc, unsigned int *rsize)
3086{
3087        /* Note 0 terminated so we can use strnstr to search for this. */
3088        static const char consumer_rdesc_start[] = {
3089                0x05, 0x0C,     /* USAGE_PAGE (Consumer Devices)       */
3090                0x09, 0x01,     /* USAGE (Consumer Control)            */
3091                0xA1, 0x01,     /* COLLECTION (Application)            */
3092                0x85, 0x03,     /* REPORT_ID = 3                       */
3093                0x75, 0x10,     /* REPORT_SIZE (16)                    */
3094                0x95, 0x02,     /* REPORT_COUNT (2)                    */
3095                0x15, 0x01,     /* LOGICAL_MIN (1)                     */
3096                0x26, 0x00      /* LOGICAL_MAX (...                    */
3097        };
3098        char *consumer_rdesc, *rdesc = (char *)_rdesc;
3099        unsigned int size;
3100
3101        consumer_rdesc = strnstr(rdesc, consumer_rdesc_start, *rsize);
3102        size = *rsize - (consumer_rdesc - rdesc);
3103        if (consumer_rdesc && size >= 25) {
3104                consumer_rdesc[15] = 0x7f;
3105                consumer_rdesc[16] = 0x10;
3106                consumer_rdesc[20] = 0x7f;
3107                consumer_rdesc[21] = 0x10;
3108        }
3109        return _rdesc;
3110}
3111
3112static int hidpp10_consumer_keys_connect(struct hidpp_device *hidpp)
3113{
3114        return hidpp10_set_register(hidpp, HIDPP_REG_ENABLE_REPORTS, 0,
3115                                    HIDPP_ENABLE_CONSUMER_REPORT,
3116                                    HIDPP_ENABLE_CONSUMER_REPORT);
3117}
3118
3119static int hidpp10_consumer_keys_raw_event(struct hidpp_device *hidpp,
3120                                           u8 *data, int size)
3121{
3122        u8 consumer_report[5];
3123
3124        if (size < 7)
3125                return 0;
3126
3127        if (data[0] != REPORT_ID_HIDPP_SHORT ||
3128            data[2] != HIDPP_SUB_ID_CONSUMER_VENDOR_KEYS)
3129                return 0;
3130
3131        /*
3132         * Build a normal consumer report (3) out of the data, this detour
3133         * is necessary to get some keyboards to report their 0x10xx usages.
3134         */
3135        consumer_report[0] = 0x03;
3136        memcpy(&consumer_report[1], &data[3], 4);
3137        /* We are called from atomic context */
3138        hid_report_raw_event(hidpp->hid_dev, HID_INPUT_REPORT,
3139                             consumer_report, 5, 1);
3140
3141        return 1;
3142}
3143
3144/* -------------------------------------------------------------------------- */
3145/* High-resolution scroll wheels                                              */
3146/* -------------------------------------------------------------------------- */
3147
3148static int hi_res_scroll_enable(struct hidpp_device *hidpp)
3149{
3150        int ret;
3151        u8 multiplier = 1;
3152
3153        if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL_X2121) {
3154                ret = hidpp_hrw_set_wheel_mode(hidpp, false, true, false);
3155                if (ret == 0)
3156                        ret = hidpp_hrw_get_wheel_capability(hidpp, &multiplier);
3157        } else if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL_X2120) {
3158                ret = hidpp_hrs_set_highres_scrolling_mode(hidpp, true,
3159                                                           &multiplier);
3160        } else /* if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL_1P0) */ {
3161                ret = hidpp10_enable_scrolling_acceleration(hidpp);
3162                multiplier = 8;
3163        }
3164        if (ret)
3165                return ret;
3166
3167        if (multiplier == 0)
3168                multiplier = 1;
3169
3170        hidpp->vertical_wheel_counter.wheel_multiplier = multiplier;
3171        hid_dbg(hidpp->hid_dev, "wheel multiplier = %d\n", multiplier);
3172        return 0;
3173}
3174
3175/* -------------------------------------------------------------------------- */
3176/* Generic HID++ devices                                                      */
3177/* -------------------------------------------------------------------------- */
3178
3179static u8 *hidpp_report_fixup(struct hid_device *hdev, u8 *rdesc,
3180                              unsigned int *rsize)
3181{
3182        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3183
3184        if (!hidpp)
3185                return rdesc;
3186
3187        /* For 27 MHz keyboards the quirk gets set after hid_parse. */
3188        if (hdev->group == HID_GROUP_LOGITECH_27MHZ_DEVICE ||
3189            (hidpp->quirks & HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS))
3190                rdesc = hidpp10_consumer_keys_report_fixup(hidpp, rdesc, rsize);
3191
3192        return rdesc;
3193}
3194
3195static int hidpp_input_mapping(struct hid_device *hdev, struct hid_input *hi,
3196                struct hid_field *field, struct hid_usage *usage,
3197                unsigned long **bit, int *max)
3198{
3199        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3200
3201        if (!hidpp)
3202                return 0;
3203
3204        if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
3205                return wtp_input_mapping(hdev, hi, field, usage, bit, max);
3206        else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560 &&
3207                        field->application != HID_GD_MOUSE)
3208                return m560_input_mapping(hdev, hi, field, usage, bit, max);
3209
3210        if (hdev->product == DINOVO_MINI_PRODUCT_ID)
3211                return lg_dinovo_input_mapping(hdev, hi, field, usage, bit, max);
3212
3213        return 0;
3214}
3215
3216static int hidpp_input_mapped(struct hid_device *hdev, struct hid_input *hi,
3217                struct hid_field *field, struct hid_usage *usage,
3218                unsigned long **bit, int *max)
3219{
3220        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3221
3222        if (!hidpp)
3223                return 0;
3224
3225        /* Ensure that Logitech G920 is not given a default fuzz/flat value */
3226        if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
3227                if (usage->type == EV_ABS && (usage->code == ABS_X ||
3228                                usage->code == ABS_Y || usage->code == ABS_Z ||
3229                                usage->code == ABS_RZ)) {
3230                        field->application = HID_GD_MULTIAXIS;
3231                }
3232        }
3233
3234        return 0;
3235}
3236
3237
3238static void hidpp_populate_input(struct hidpp_device *hidpp,
3239                                 struct input_dev *input)
3240{
3241        hidpp->input = input;
3242
3243        if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
3244                wtp_populate_input(hidpp, input);
3245        else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560)
3246                m560_populate_input(hidpp, input);
3247
3248        if (hidpp->quirks & HIDPP_QUIRK_HIDPP_WHEELS)
3249                hidpp10_wheel_populate_input(hidpp, input);
3250
3251        if (hidpp->quirks & HIDPP_QUIRK_HIDPP_EXTRA_MOUSE_BTNS)
3252                hidpp10_extra_mouse_buttons_populate_input(hidpp, input);
3253}
3254
3255static int hidpp_input_configured(struct hid_device *hdev,
3256                                struct hid_input *hidinput)
3257{
3258        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3259        struct input_dev *input = hidinput->input;
3260
3261        if (!hidpp)
3262                return 0;
3263
3264        hidpp_populate_input(hidpp, input);
3265
3266        return 0;
3267}
3268
3269static int hidpp_raw_hidpp_event(struct hidpp_device *hidpp, u8 *data,
3270                int size)
3271{
3272        struct hidpp_report *question = hidpp->send_receive_buf;
3273        struct hidpp_report *answer = hidpp->send_receive_buf;
3274        struct hidpp_report *report = (struct hidpp_report *)data;
3275        int ret;
3276
3277        /*
3278         * If the mutex is locked then we have a pending answer from a
3279         * previously sent command.
3280         */
3281        if (unlikely(mutex_is_locked(&hidpp->send_mutex))) {
3282                /*
3283                 * Check for a correct hidpp20 answer or the corresponding
3284                 * error
3285                 */
3286                if (hidpp_match_answer(question, report) ||
3287                                hidpp_match_error(question, report)) {
3288                        *answer = *report;
3289                        hidpp->answer_available = true;
3290                        wake_up(&hidpp->wait);
3291                        /*
3292                         * This was an answer to a command that this driver sent
3293                         * We return 1 to hid-core to avoid forwarding the
3294                         * command upstream as it has been treated by the driver
3295                         */
3296
3297                        return 1;
3298                }
3299        }
3300
3301        if (unlikely(hidpp_report_is_connect_event(hidpp, report))) {
3302                atomic_set(&hidpp->connected,
3303                                !(report->rap.params[0] & (1 << 6)));
3304                if (schedule_work(&hidpp->work) == 0)
3305                        dbg_hid("%s: connect event already queued\n", __func__);
3306                return 1;
3307        }
3308
3309        if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP20_BATTERY) {
3310                ret = hidpp20_battery_event(hidpp, data, size);
3311                if (ret != 0)
3312                        return ret;
3313                ret = hidpp_solar_battery_event(hidpp, data, size);
3314                if (ret != 0)
3315                        return ret;
3316                ret = hidpp20_battery_voltage_event(hidpp, data, size);
3317                if (ret != 0)
3318                        return ret;
3319        }
3320
3321        if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP10_BATTERY) {
3322                ret = hidpp10_battery_event(hidpp, data, size);
3323                if (ret != 0)
3324                        return ret;
3325        }
3326
3327        if (hidpp->quirks & HIDPP_QUIRK_HIDPP_WHEELS) {
3328                ret = hidpp10_wheel_raw_event(hidpp, data, size);
3329                if (ret != 0)
3330                        return ret;
3331        }
3332
3333        if (hidpp->quirks & HIDPP_QUIRK_HIDPP_EXTRA_MOUSE_BTNS) {
3334                ret = hidpp10_extra_mouse_buttons_raw_event(hidpp, data, size);
3335                if (ret != 0)
3336                        return ret;
3337        }
3338
3339        if (hidpp->quirks & HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS) {
3340                ret = hidpp10_consumer_keys_raw_event(hidpp, data, size);
3341                if (ret != 0)
3342                        return ret;
3343        }
3344
3345        return 0;
3346}
3347
3348static int hidpp_raw_event(struct hid_device *hdev, struct hid_report *report,
3349                u8 *data, int size)
3350{
3351        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3352        int ret = 0;
3353
3354        if (!hidpp)
3355                return 0;
3356
3357        /* Generic HID++ processing. */
3358        switch (data[0]) {
3359        case REPORT_ID_HIDPP_VERY_LONG:
3360                if (size != hidpp->very_long_report_length) {
3361                        hid_err(hdev, "received hid++ report of bad size (%d)",
3362                                size);
3363                        return 1;
3364                }
3365                ret = hidpp_raw_hidpp_event(hidpp, data, size);
3366                break;
3367        case REPORT_ID_HIDPP_LONG:
3368                if (size != HIDPP_REPORT_LONG_LENGTH) {
3369                        hid_err(hdev, "received hid++ report of bad size (%d)",
3370                                size);
3371                        return 1;
3372                }
3373                ret = hidpp_raw_hidpp_event(hidpp, data, size);
3374                break;
3375        case REPORT_ID_HIDPP_SHORT:
3376                if (size != HIDPP_REPORT_SHORT_LENGTH) {
3377                        hid_err(hdev, "received hid++ report of bad size (%d)",
3378                                size);
3379                        return 1;
3380                }
3381                ret = hidpp_raw_hidpp_event(hidpp, data, size);
3382                break;
3383        }
3384
3385        /* If no report is available for further processing, skip calling
3386         * raw_event of subclasses. */
3387        if (ret != 0)
3388                return ret;
3389
3390        if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
3391                return wtp_raw_event(hdev, data, size);
3392        else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560)
3393                return m560_raw_event(hdev, data, size);
3394
3395        return 0;
3396}
3397
3398static int hidpp_event(struct hid_device *hdev, struct hid_field *field,
3399        struct hid_usage *usage, __s32 value)
3400{
3401        /* This function will only be called for scroll events, due to the
3402         * restriction imposed in hidpp_usages.
3403         */
3404        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3405        struct hidpp_scroll_counter *counter;
3406
3407        if (!hidpp)
3408                return 0;
3409
3410        counter = &hidpp->vertical_wheel_counter;
3411        /* A scroll event may occur before the multiplier has been retrieved or
3412         * the input device set, or high-res scroll enabling may fail. In such
3413         * cases we must return early (falling back to default behaviour) to
3414         * avoid a crash in hidpp_scroll_counter_handle_scroll.
3415         */
3416        if (!(hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL) || value == 0
3417            || hidpp->input == NULL || counter->wheel_multiplier == 0)
3418                return 0;
3419
3420        hidpp_scroll_counter_handle_scroll(hidpp->input, counter, value);
3421        return 1;
3422}
3423
3424static int hidpp_initialize_battery(struct hidpp_device *hidpp)
3425{
3426        static atomic_t battery_no = ATOMIC_INIT(0);
3427        struct power_supply_config cfg = { .drv_data = hidpp };
3428        struct power_supply_desc *desc = &hidpp->battery.desc;
3429        enum power_supply_property *battery_props;
3430        struct hidpp_battery *battery;
3431        unsigned int num_battery_props;
3432        unsigned long n;
3433        int ret;
3434
3435        if (hidpp->battery.ps)
3436                return 0;
3437
3438        hidpp->battery.feature_index = 0xff;
3439        hidpp->battery.solar_feature_index = 0xff;
3440        hidpp->battery.voltage_feature_index = 0xff;
3441
3442        if (hidpp->protocol_major >= 2) {
3443                if (hidpp->quirks & HIDPP_QUIRK_CLASS_K750)
3444                        ret = hidpp_solar_request_battery_event(hidpp);
3445                else {
3446                        ret = hidpp20_query_battery_voltage_info(hidpp);
3447                        if (ret)
3448                                ret = hidpp20_query_battery_info(hidpp);
3449                }
3450
3451                if (ret)
3452                        return ret;
3453                hidpp->capabilities |= HIDPP_CAPABILITY_HIDPP20_BATTERY;
3454        } else {
3455                ret = hidpp10_query_battery_status(hidpp);
3456                if (ret) {
3457                        ret = hidpp10_query_battery_mileage(hidpp);
3458                        if (ret)
3459                                return -ENOENT;
3460                        hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_MILEAGE;
3461                } else {
3462                        hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS;
3463                }
3464                hidpp->capabilities |= HIDPP_CAPABILITY_HIDPP10_BATTERY;
3465        }
3466
3467        battery_props = devm_kmemdup(&hidpp->hid_dev->dev,
3468                                     hidpp_battery_props,
3469                                     sizeof(hidpp_battery_props),
3470                                     GFP_KERNEL);
3471        if (!battery_props)
3472                return -ENOMEM;
3473
3474        num_battery_props = ARRAY_SIZE(hidpp_battery_props) - 3;
3475
3476        if (hidpp->capabilities & HIDPP_CAPABILITY_BATTERY_MILEAGE)
3477                battery_props[num_battery_props++] =
3478                                POWER_SUPPLY_PROP_CAPACITY;
3479
3480        if (hidpp->capabilities & HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS)
3481                battery_props[num_battery_props++] =
3482                                POWER_SUPPLY_PROP_CAPACITY_LEVEL;
3483
3484        if (hidpp->capabilities & HIDPP_CAPABILITY_BATTERY_VOLTAGE)
3485                battery_props[num_battery_props++] =
3486                        POWER_SUPPLY_PROP_VOLTAGE_NOW;
3487
3488        battery = &hidpp->battery;
3489
3490        n = atomic_inc_return(&battery_no) - 1;
3491        desc->properties = battery_props;
3492        desc->num_properties = num_battery_props;
3493        desc->get_property = hidpp_battery_get_property;
3494        sprintf(battery->name, "hidpp_battery_%ld", n);
3495        desc->name = battery->name;
3496        desc->type = POWER_SUPPLY_TYPE_BATTERY;
3497        desc->use_for_apm = 0;
3498
3499        battery->ps = devm_power_supply_register(&hidpp->hid_dev->dev,
3500                                                 &battery->desc,
3501                                                 &cfg);
3502        if (IS_ERR(battery->ps))
3503                return PTR_ERR(battery->ps);
3504
3505        power_supply_powers(battery->ps, &hidpp->hid_dev->dev);
3506
3507        return ret;
3508}
3509
3510static void hidpp_overwrite_name(struct hid_device *hdev)
3511{
3512        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3513        char *name;
3514
3515        if (hidpp->protocol_major < 2)
3516                return;
3517
3518        name = hidpp_get_device_name(hidpp);
3519
3520        if (!name) {
3521                hid_err(hdev, "unable to retrieve the name of the device");
3522        } else {
3523                dbg_hid("HID++: Got name: %s\n", name);
3524                snprintf(hdev->name, sizeof(hdev->name), "%s", name);
3525        }
3526
3527        kfree(name);
3528}
3529
3530static int hidpp_input_open(struct input_dev *dev)
3531{
3532        struct hid_device *hid = input_get_drvdata(dev);
3533
3534        return hid_hw_open(hid);
3535}
3536
3537static void hidpp_input_close(struct input_dev *dev)
3538{
3539        struct hid_device *hid = input_get_drvdata(dev);
3540
3541        hid_hw_close(hid);
3542}
3543
3544static struct input_dev *hidpp_allocate_input(struct hid_device *hdev)
3545{
3546        struct input_dev *input_dev = devm_input_allocate_device(&hdev->dev);
3547        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3548
3549        if (!input_dev)
3550                return NULL;
3551
3552        input_set_drvdata(input_dev, hdev);
3553        input_dev->open = hidpp_input_open;
3554        input_dev->close = hidpp_input_close;
3555
3556        input_dev->name = hidpp->name;
3557        input_dev->phys = hdev->phys;
3558        input_dev->uniq = hdev->uniq;
3559        input_dev->id.bustype = hdev->bus;
3560        input_dev->id.vendor  = hdev->vendor;
3561        input_dev->id.product = hdev->product;
3562        input_dev->id.version = hdev->version;
3563        input_dev->dev.parent = &hdev->dev;
3564
3565        return input_dev;
3566}
3567
3568static void hidpp_connect_event(struct hidpp_device *hidpp)
3569{
3570        struct hid_device *hdev = hidpp->hid_dev;
3571        int ret = 0;
3572        bool connected = atomic_read(&hidpp->connected);
3573        struct input_dev *input;
3574        char *name, *devm_name;
3575
3576        if (!connected) {
3577                if (hidpp->battery.ps) {
3578                        hidpp->battery.online = false;
3579                        hidpp->battery.status = POWER_SUPPLY_STATUS_UNKNOWN;
3580                        hidpp->battery.level = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
3581                        power_supply_changed(hidpp->battery.ps);
3582                }
3583                return;
3584        }
3585
3586        if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP) {
3587                ret = wtp_connect(hdev, connected);
3588                if (ret)
3589                        return;
3590        } else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560) {
3591                ret = m560_send_config_command(hdev, connected);
3592                if (ret)
3593                        return;
3594        } else if (hidpp->quirks & HIDPP_QUIRK_CLASS_K400) {
3595                ret = k400_connect(hdev, connected);
3596                if (ret)
3597                        return;
3598        }
3599
3600        if (hidpp->quirks & HIDPP_QUIRK_HIDPP_WHEELS) {
3601                ret = hidpp10_wheel_connect(hidpp);
3602                if (ret)
3603                        return;
3604        }
3605
3606        if (hidpp->quirks & HIDPP_QUIRK_HIDPP_EXTRA_MOUSE_BTNS) {
3607                ret = hidpp10_extra_mouse_buttons_connect(hidpp);
3608                if (ret)
3609                        return;
3610        }
3611
3612        if (hidpp->quirks & HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS) {
3613                ret = hidpp10_consumer_keys_connect(hidpp);
3614                if (ret)
3615                        return;
3616        }
3617
3618        /* the device is already connected, we can ask for its name and
3619         * protocol */
3620        if (!hidpp->protocol_major) {
3621                ret = hidpp_root_get_protocol_version(hidpp);
3622                if (ret) {
3623                        hid_err(hdev, "Can not get the protocol version.\n");
3624                        return;
3625                }
3626        }
3627
3628        if (hidpp->name == hdev->name && hidpp->protocol_major >= 2) {
3629                name = hidpp_get_device_name(hidpp);
3630                if (name) {
3631                        devm_name = devm_kasprintf(&hdev->dev, GFP_KERNEL,
3632                                                   "%s", name);
3633                        kfree(name);
3634                        if (!devm_name)
3635                                return;
3636
3637                        hidpp->name = devm_name;
3638                }
3639        }
3640
3641        hidpp_initialize_battery(hidpp);
3642
3643        /* forward current battery state */
3644        if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP10_BATTERY) {
3645                hidpp10_enable_battery_reporting(hidpp);
3646                if (hidpp->capabilities & HIDPP_CAPABILITY_BATTERY_MILEAGE)
3647                        hidpp10_query_battery_mileage(hidpp);
3648                else
3649                        hidpp10_query_battery_status(hidpp);
3650        } else if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP20_BATTERY) {
3651                if (hidpp->capabilities & HIDPP_CAPABILITY_BATTERY_VOLTAGE)
3652                        hidpp20_query_battery_voltage_info(hidpp);
3653                else
3654                        hidpp20_query_battery_info(hidpp);
3655        }
3656        if (hidpp->battery.ps)
3657                power_supply_changed(hidpp->battery.ps);
3658
3659        if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL)
3660                hi_res_scroll_enable(hidpp);
3661
3662        if (!(hidpp->quirks & HIDPP_QUIRK_NO_HIDINPUT) || hidpp->delayed_input)
3663                /* if the input nodes are already created, we can stop now */
3664                return;
3665
3666        input = hidpp_allocate_input(hdev);
3667        if (!input) {
3668                hid_err(hdev, "cannot allocate new input device: %d\n", ret);
3669                return;
3670        }
3671
3672        hidpp_populate_input(hidpp, input);
3673
3674        ret = input_register_device(input);
3675        if (ret)
3676                input_free_device(input);
3677
3678        hidpp->delayed_input = input;
3679}
3680
3681static DEVICE_ATTR(builtin_power_supply, 0000, NULL, NULL);
3682
3683static struct attribute *sysfs_attrs[] = {
3684        &dev_attr_builtin_power_supply.attr,
3685        NULL
3686};
3687
3688static const struct attribute_group ps_attribute_group = {
3689        .attrs = sysfs_attrs
3690};
3691
3692static int hidpp_get_report_length(struct hid_device *hdev, int id)
3693{
3694        struct hid_report_enum *re;
3695        struct hid_report *report;
3696
3697        re = &(hdev->report_enum[HID_OUTPUT_REPORT]);
3698        report = re->report_id_hash[id];
3699        if (!report)
3700                return 0;
3701
3702        return report->field[0]->report_count + 1;
3703}
3704
3705static u8 hidpp_validate_device(struct hid_device *hdev)
3706{
3707        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3708        int id, report_length;
3709        u8 supported_reports = 0;
3710
3711        id = REPORT_ID_HIDPP_SHORT;
3712        report_length = hidpp_get_report_length(hdev, id);
3713        if (report_length) {
3714                if (report_length < HIDPP_REPORT_SHORT_LENGTH)
3715                        goto bad_device;
3716
3717                supported_reports |= HIDPP_REPORT_SHORT_SUPPORTED;
3718        }
3719
3720        id = REPORT_ID_HIDPP_LONG;
3721        report_length = hidpp_get_report_length(hdev, id);
3722        if (report_length) {
3723                if (report_length < HIDPP_REPORT_LONG_LENGTH)
3724                        goto bad_device;
3725
3726                supported_reports |= HIDPP_REPORT_LONG_SUPPORTED;
3727        }
3728
3729        id = REPORT_ID_HIDPP_VERY_LONG;
3730        report_length = hidpp_get_report_length(hdev, id);
3731        if (report_length) {
3732                if (report_length < HIDPP_REPORT_LONG_LENGTH ||
3733                    report_length > HIDPP_REPORT_VERY_LONG_MAX_LENGTH)
3734                        goto bad_device;
3735
3736                supported_reports |= HIDPP_REPORT_VERY_LONG_SUPPORTED;
3737                hidpp->very_long_report_length = report_length;
3738        }
3739
3740        return supported_reports;
3741
3742bad_device:
3743        hid_warn(hdev, "not enough values in hidpp report %d\n", id);
3744        return false;
3745}
3746
3747static bool hidpp_application_equals(struct hid_device *hdev,
3748                                     unsigned int application)
3749{
3750        struct list_head *report_list;
3751        struct hid_report *report;
3752
3753        report_list = &hdev->report_enum[HID_INPUT_REPORT].report_list;
3754        report = list_first_entry_or_null(report_list, struct hid_report, list);
3755        return report && report->application == application;
3756}
3757
3758static int hidpp_probe(struct hid_device *hdev, const struct hid_device_id *id)
3759{
3760        struct hidpp_device *hidpp;
3761        int ret;
3762        bool connected;
3763        unsigned int connect_mask = HID_CONNECT_DEFAULT;
3764        struct hidpp_ff_private_data data;
3765
3766        /* report_fixup needs drvdata to be set before we call hid_parse */
3767        hidpp = devm_kzalloc(&hdev->dev, sizeof(*hidpp), GFP_KERNEL);
3768        if (!hidpp)
3769                return -ENOMEM;
3770
3771        hidpp->hid_dev = hdev;
3772        hidpp->name = hdev->name;
3773        hidpp->quirks = id->driver_data;
3774        hid_set_drvdata(hdev, hidpp);
3775
3776        ret = hid_parse(hdev);
3777        if (ret) {
3778                hid_err(hdev, "%s:parse failed\n", __func__);
3779                return ret;
3780        }
3781
3782        /*
3783         * Make sure the device is HID++ capable, otherwise treat as generic HID
3784         */
3785        hidpp->supported_reports = hidpp_validate_device(hdev);
3786
3787        if (!hidpp->supported_reports) {
3788                hid_set_drvdata(hdev, NULL);
3789                devm_kfree(&hdev->dev, hidpp);
3790                return hid_hw_start(hdev, HID_CONNECT_DEFAULT);
3791        }
3792
3793        if (id->group == HID_GROUP_LOGITECH_DJ_DEVICE)
3794                hidpp->quirks |= HIDPP_QUIRK_UNIFYING;
3795
3796        if (id->group == HID_GROUP_LOGITECH_27MHZ_DEVICE &&
3797            hidpp_application_equals(hdev, HID_GD_MOUSE))
3798                hidpp->quirks |= HIDPP_QUIRK_HIDPP_WHEELS |
3799                                 HIDPP_QUIRK_HIDPP_EXTRA_MOUSE_BTNS;
3800
3801        if (id->group == HID_GROUP_LOGITECH_27MHZ_DEVICE &&
3802            hidpp_application_equals(hdev, HID_GD_KEYBOARD))
3803                hidpp->quirks |= HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS;
3804
3805        if (disable_raw_mode) {
3806                hidpp->quirks &= ~HIDPP_QUIRK_CLASS_WTP;
3807                hidpp->quirks &= ~HIDPP_QUIRK_NO_HIDINPUT;
3808        }
3809
3810        if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP) {
3811                ret = wtp_allocate(hdev, id);
3812                if (ret)
3813                        return ret;
3814        } else if (hidpp->quirks & HIDPP_QUIRK_CLASS_K400) {
3815                ret = k400_allocate(hdev);
3816                if (ret)
3817                        return ret;
3818        }
3819
3820        INIT_WORK(&hidpp->work, delayed_work_cb);
3821        mutex_init(&hidpp->send_mutex);
3822        init_waitqueue_head(&hidpp->wait);
3823
3824        /* indicates we are handling the battery properties in the kernel */
3825        ret = sysfs_create_group(&hdev->dev.kobj, &ps_attribute_group);
3826        if (ret)
3827                hid_warn(hdev, "Cannot allocate sysfs group for %s\n",
3828                         hdev->name);
3829
3830        /*
3831         * Plain USB connections need to actually call start and open
3832         * on the transport driver to allow incoming data.
3833         */
3834        ret = hid_hw_start(hdev, 0);
3835        if (ret) {
3836                hid_err(hdev, "hw start failed\n");
3837                goto hid_hw_start_fail;
3838        }
3839
3840        ret = hid_hw_open(hdev);
3841        if (ret < 0) {
3842                dev_err(&hdev->dev, "%s:hid_hw_open returned error:%d\n",
3843                        __func__, ret);
3844                goto hid_hw_open_fail;
3845        }
3846
3847        /* Allow incoming packets */
3848        hid_device_io_start(hdev);
3849
3850        if (hidpp->quirks & HIDPP_QUIRK_UNIFYING)
3851                hidpp_unifying_init(hidpp);
3852
3853        connected = hidpp_root_get_protocol_version(hidpp) == 0;
3854        atomic_set(&hidpp->connected, connected);
3855        if (!(hidpp->quirks & HIDPP_QUIRK_UNIFYING)) {
3856                if (!connected) {
3857                        ret = -ENODEV;
3858                        hid_err(hdev, "Device not connected");
3859                        goto hid_hw_init_fail;
3860                }
3861
3862                hidpp_overwrite_name(hdev);
3863        }
3864
3865        if (connected && hidpp->protocol_major >= 2) {
3866                ret = hidpp_set_wireless_feature_index(hidpp);
3867                if (ret == -ENOENT)
3868                        hidpp->wireless_feature_index = 0;
3869                else if (ret)
3870                        goto hid_hw_init_fail;
3871        }
3872
3873        if (connected && (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)) {
3874                ret = wtp_get_config(hidpp);
3875                if (ret)
3876                        goto hid_hw_init_fail;
3877        } else if (connected && (hidpp->quirks & HIDPP_QUIRK_CLASS_G920)) {
3878                ret = g920_get_config(hidpp, &data);
3879                if (ret)
3880                        goto hid_hw_init_fail;
3881        }
3882
3883        hidpp_connect_event(hidpp);
3884
3885        /* Reset the HID node state */
3886        hid_device_io_stop(hdev);
3887        hid_hw_close(hdev);
3888        hid_hw_stop(hdev);
3889
3890        if (hidpp->quirks & HIDPP_QUIRK_NO_HIDINPUT)
3891                connect_mask &= ~HID_CONNECT_HIDINPUT;
3892
3893        /* Now export the actual inputs and hidraw nodes to the world */
3894        ret = hid_hw_start(hdev, connect_mask);
3895        if (ret) {
3896                hid_err(hdev, "%s:hid_hw_start returned error\n", __func__);
3897                goto hid_hw_start_fail;
3898        }
3899
3900        if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
3901                ret = hidpp_ff_init(hidpp, &data);
3902                if (ret)
3903                        hid_warn(hidpp->hid_dev,
3904                     "Unable to initialize force feedback support, errno %d\n",
3905                                 ret);
3906        }
3907
3908        return ret;
3909
3910hid_hw_init_fail:
3911        hid_hw_close(hdev);
3912hid_hw_open_fail:
3913        hid_hw_stop(hdev);
3914hid_hw_start_fail:
3915        sysfs_remove_group(&hdev->dev.kobj, &ps_attribute_group);
3916        cancel_work_sync(&hidpp->work);
3917        mutex_destroy(&hidpp->send_mutex);
3918        return ret;
3919}
3920
3921static void hidpp_remove(struct hid_device *hdev)
3922{
3923        struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3924
3925        if (!hidpp)
3926                return hid_hw_stop(hdev);
3927
3928        sysfs_remove_group(&hdev->dev.kobj, &ps_attribute_group);
3929
3930        hid_hw_stop(hdev);
3931        cancel_work_sync(&hidpp->work);
3932        mutex_destroy(&hidpp->send_mutex);
3933}
3934
3935#define LDJ_DEVICE(product) \
3936        HID_DEVICE(BUS_USB, HID_GROUP_LOGITECH_DJ_DEVICE, \
3937                   USB_VENDOR_ID_LOGITECH, (product))
3938
3939#define L27MHZ_DEVICE(product) \
3940        HID_DEVICE(BUS_USB, HID_GROUP_LOGITECH_27MHZ_DEVICE, \
3941                   USB_VENDOR_ID_LOGITECH, (product))
3942
3943static const struct hid_device_id hidpp_devices[] = {
3944        { /* wireless touchpad */
3945          LDJ_DEVICE(0x4011),
3946          .driver_data = HIDPP_QUIRK_CLASS_WTP | HIDPP_QUIRK_DELAYED_INIT |
3947                         HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS },
3948        { /* wireless touchpad T650 */
3949          LDJ_DEVICE(0x4101),
3950          .driver_data = HIDPP_QUIRK_CLASS_WTP | HIDPP_QUIRK_DELAYED_INIT },
3951        { /* wireless touchpad T651 */
3952          HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH,
3953                USB_DEVICE_ID_LOGITECH_T651),
3954          .driver_data = HIDPP_QUIRK_CLASS_WTP },
3955        { /* Mouse Logitech Anywhere MX */
3956          LDJ_DEVICE(0x1017), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_1P0 },
3957        { /* Mouse Logitech Cube */
3958          LDJ_DEVICE(0x4010), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2120 },
3959        { /* Mouse Logitech M335 */
3960          LDJ_DEVICE(0x4050), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3961        { /* Mouse Logitech M515 */
3962          LDJ_DEVICE(0x4007), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2120 },
3963        { /* Mouse logitech M560 */
3964          LDJ_DEVICE(0x402d),
3965          .driver_data = HIDPP_QUIRK_DELAYED_INIT | HIDPP_QUIRK_CLASS_M560
3966                | HIDPP_QUIRK_HI_RES_SCROLL_X2120 },
3967        { /* Mouse Logitech M705 (firmware RQM17) */
3968          LDJ_DEVICE(0x101b), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_1P0 },
3969        { /* Mouse Logitech M705 (firmware RQM67) */
3970          LDJ_DEVICE(0x406d), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3971        { /* Mouse Logitech M720 */
3972          LDJ_DEVICE(0x405e), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3973        { /* Mouse Logitech MX Anywhere 2 */
3974          LDJ_DEVICE(0x404a), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3975        { LDJ_DEVICE(0x4072), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3976        { LDJ_DEVICE(0xb013), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3977        { LDJ_DEVICE(0xb018), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3978        { LDJ_DEVICE(0xb01f), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3979        { /* Mouse Logitech MX Anywhere 2S */
3980          LDJ_DEVICE(0x406a), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3981        { /* Mouse Logitech MX Master */
3982          LDJ_DEVICE(0x4041), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3983        { LDJ_DEVICE(0x4060), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3984        { LDJ_DEVICE(0x4071), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3985        { /* Mouse Logitech MX Master 2S */
3986          LDJ_DEVICE(0x4069), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3987        { /* Mouse Logitech MX Master 3 */
3988          LDJ_DEVICE(0x4082), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3989        { /* Mouse Logitech Performance MX */
3990          LDJ_DEVICE(0x101a), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_1P0 },
3991        { /* Keyboard logitech K400 */
3992          LDJ_DEVICE(0x4024),
3993          .driver_data = HIDPP_QUIRK_CLASS_K400 },
3994        { /* Solar Keyboard Logitech K750 */
3995          LDJ_DEVICE(0x4002),
3996          .driver_data = HIDPP_QUIRK_CLASS_K750 },
3997        { /* Keyboard MX5000 (Bluetooth-receiver in HID proxy mode) */
3998          LDJ_DEVICE(0xb305),
3999          .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
4000        { /* Dinovo Edge (Bluetooth-receiver in HID proxy mode) */
4001          LDJ_DEVICE(0xb309),
4002          .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
4003        { /* Keyboard MX5500 (Bluetooth-receiver in HID proxy mode) */
4004          LDJ_DEVICE(0xb30b),
4005          .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
4006
4007        { LDJ_DEVICE(HID_ANY_ID) },
4008
4009        { /* Keyboard LX501 (Y-RR53) */
4010          L27MHZ_DEVICE(0x0049),
4011          .driver_data = HIDPP_QUIRK_KBD_ZOOM_WHEEL },
4012        { /* Keyboard MX3000 (Y-RAM74) */
4013          L27MHZ_DEVICE(0x0057),
4014          .driver_data = HIDPP_QUIRK_KBD_SCROLL_WHEEL },
4015        { /* Keyboard MX3200 (Y-RAV80) */
4016          L27MHZ_DEVICE(0x005c),
4017          .driver_data = HIDPP_QUIRK_KBD_ZOOM_WHEEL },
4018        { /* S510 Media Remote */
4019          L27MHZ_DEVICE(0x00fe),
4020          .driver_data = HIDPP_QUIRK_KBD_SCROLL_WHEEL },
4021
4022        { L27MHZ_DEVICE(HID_ANY_ID) },
4023
4024        { /* Logitech G403 Wireless Gaming Mouse over USB */
4025          HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC082) },
4026        { /* Logitech G703 Gaming Mouse over USB */
4027          HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC087) },
4028        { /* Logitech G703 Hero Gaming Mouse over USB */
4029          HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC090) },
4030        { /* Logitech G900 Gaming Mouse over USB */
4031          HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC081) },
4032        { /* Logitech G903 Gaming Mouse over USB */
4033          HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC086) },
4034        { /* Logitech G903 Hero Gaming Mouse over USB */
4035          HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC091) },
4036        { /* Logitech G920 Wheel over USB */
4037          HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G920_WHEEL),
4038                .driver_data = HIDPP_QUIRK_CLASS_G920 | HIDPP_QUIRK_FORCE_OUTPUT_REPORTS},
4039        { /* Logitech G Pro Gaming Mouse over USB */
4040          HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC088) },
4041
4042        { /* MX5000 keyboard over Bluetooth */
4043          HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, 0xb305),
4044          .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
4045        { /* Dinovo Edge keyboard over Bluetooth */
4046          HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, 0xb309),
4047          .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
4048        { /* MX5500 keyboard over Bluetooth */
4049          HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, 0xb30b),
4050          .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
4051        { /* M-RCQ142 V470 Cordless Laser Mouse over Bluetooth */
4052          HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, 0xb008) },
4053        { /* MX Master mouse over Bluetooth */
4054          HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, 0xb012),
4055          .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
4056        { /* MX Ergo trackball over Bluetooth */
4057          HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, 0xb01d) },
4058        { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, 0xb01e),
4059          .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
4060        { /* MX Master 3 mouse over Bluetooth */
4061          HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, 0xb023),
4062          .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
4063        {}
4064};
4065
4066MODULE_DEVICE_TABLE(hid, hidpp_devices);
4067
4068static const struct hid_usage_id hidpp_usages[] = {
4069        { HID_GD_WHEEL, EV_REL, REL_WHEEL_HI_RES },
4070        { HID_ANY_ID - 1, HID_ANY_ID - 1, HID_ANY_ID - 1}
4071};
4072
4073static struct hid_driver hidpp_driver = {
4074        .name = "logitech-hidpp-device",
4075        .id_table = hidpp_devices,
4076        .report_fixup = hidpp_report_fixup,
4077        .probe = hidpp_probe,
4078        .remove = hidpp_remove,
4079        .raw_event = hidpp_raw_event,
4080        .usage_table = hidpp_usages,
4081        .event = hidpp_event,
4082        .input_configured = hidpp_input_configured,
4083        .input_mapping = hidpp_input_mapping,
4084        .input_mapped = hidpp_input_mapped,
4085};
4086
4087module_hid_driver(hidpp_driver);
4088