CHROMIUM: mkbp: Optimize ghosting algorithm.
[cascardo/linux.git] / drivers / input / keyboard / mkbp.c
1 /*
2  *  mkbp.c - keyboard driver for Matrix KeyBoard Protocol keyboards.
3  *
4  *  Copyright (C) 2012 Google, Inc
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  *
21  * The MKBP (matrix keyboard protocol) is a message-based protocol for
22  * communicating the keyboard state (which keys are pressed) from a keyboard EC
23  * to the AP over some bus (such as i2c, lpc, spi).  The EC does debouncing,
24  * but everything else (including deghosting) is done here.  The main
25  * motivation for this is to keep the EC firmware as simple as possible, since
26  * it cannot be easily upgraded and EC flash/IRAM space is relatively
27  * expensive.
28  */
29
30 #include <linux/module.h>
31 #include <linux/bitops.h>
32 #include <linux/i2c.h>
33 #include <linux/input.h>
34 #include <linux/kernel.h>
35 #include <linux/mfd/chromeos_ec.h>
36 #include <linux/mfd/chromeos_ec_commands.h>
37 #include <linux/notifier.h>
38 #include <linux/platform_device.h>
39 #include <linux/power_supply.h>
40 #include <linux/slab.h>
41
42 /*
43  * The standard MKBP keyboard matrix table.
44  *
45  * These may become variables when we switch to the Device Tree. However, the
46  * code and the protocol assume that NUM_ROWS = 8 (one byte per column).
47  */
48 #define MKBP_NUM_ROWS 8
49 #define MKBP_NUM_COLS 13
50
51 struct mkbp_device {
52         struct device *dev;
53         struct input_dev *idev;
54         struct chromeos_ec_device *ec;
55         struct notifier_block notifier;
56         struct notifier_block wake_notifier;
57         uint8_t valid_keys[MKBP_NUM_COLS];
58 };
59
60 /* We will read this table from the Device Tree when we have one. */
61 static uint16_t mkbp_keycodes[MKBP_NUM_ROWS][MKBP_NUM_COLS] = {
62         { 0x0,          KEY_LEFTMETA,   KEY_F1,         KEY_B,
63           KEY_F10,      0x0,            KEY_N,          0x0,
64           KEY_EQUAL,    0x0,            KEY_RIGHTALT,   0x0,
65           0x0 },
66         { 0x0,          KEY_ESC,        KEY_F4,         KEY_G,
67           KEY_F7,       0x0,            KEY_H,          0x0,
68           KEY_APOSTROPHE,KEY_F9,        0x0,            KEY_BACKSPACE,
69           0x0 },
70         { KEY_LEFTCTRL, KEY_TAB,        KEY_F3,         KEY_T,
71           KEY_F6,       KEY_RIGHTBRACE, KEY_Y,          KEY_102ND,
72           KEY_LEFTBRACE,KEY_F8,         0x0,            0x0,
73           0x0 },
74         { 0x0,          KEY_GRAVE,      KEY_F2,         KEY_5,
75           KEY_F5,       0x0,            KEY_6,          0x0,
76           KEY_MINUS,    0x0,            0x0,            KEY_BACKSLASH,
77           0x0 },
78         { KEY_RIGHTCTRL,KEY_A,          KEY_D,          KEY_F,
79           KEY_S,        KEY_K,          KEY_J,          0x0,
80           KEY_SEMICOLON,KEY_L,          KEY_BACKSLASH,  KEY_ENTER,
81           0x0 },
82         { 0x0,          KEY_Z,          KEY_C,          KEY_V,
83           KEY_X,        KEY_COMMA,      KEY_M,          KEY_LEFTSHIFT,
84           KEY_SLASH,    KEY_DOT,        0x0,            KEY_SPACE,
85           0x0 },
86         { 0x0,          KEY_1,          KEY_3,          KEY_4,
87           KEY_2,        KEY_8,          KEY_7,          0x0,
88           KEY_0,        KEY_9,          KEY_LEFTALT,    KEY_DOWN,
89           KEY_RIGHT },
90         { KEY_BATTERY,  KEY_Q,          KEY_E,          KEY_R,
91           KEY_W,        KEY_I,          KEY_U,          KEY_RIGHTSHIFT,
92           KEY_P,        KEY_O,          0x0,            KEY_UP,
93           KEY_LEFT }
94 };
95
96 static uint8_t identity_keycodes[256];
97
98 /*
99  * Sends a single key event to the input layer.
100  */
101 static inline void mkbp_send_key_event(struct mkbp_device *mkbp_dev,
102                                 int row, int col, int pressed)
103 {
104         struct input_dev *idev = mkbp_dev->idev;
105         int code = mkbp_keycodes[row][col];
106
107         /* This key signifies a change to power supply status */
108         if (code == KEY_BATTERY) {
109                 if (mkbp_dev->ec->charger)
110                         power_supply_changed(mkbp_dev->ec->charger);
111                 return;
112         }
113
114         input_report_key(idev, code, pressed);
115 }
116
117 /*
118  * Returns true when there is at least one combination of pressed keys that
119  * results in ghosting.
120  */
121 static bool mkbp_has_ghosting(struct mkbp_device *mkbp_dev, uint8_t *buf)
122 {
123         int col1, col2, buf1, buf2;
124         struct device *dev = mkbp_dev->dev;
125         uint8_t *valid_keys = mkbp_dev->valid_keys;
126
127         /*
128          * Ghosting happens if for any pressed key X there are other keys
129          * pressed both in the same row and column of X as, for instance,
130          * in the following diagram:
131          *
132          * . . Y . g .
133          * . . . . . .
134          * . . . . . .
135          * . . X . Z .
136          *
137          * In this case only X, Y, and Z are pressed, but g appears to be
138          * pressed too (see Wikipedia).
139          */
140         for (col1 = 0; col1 < MKBP_NUM_COLS; col1++) {
141                 buf1 = buf[col1] & valid_keys[col1];
142                 for (col2 = col1 + 1; col2 < MKBP_NUM_COLS; col2++) {
143                         buf2 = buf[col2] & valid_keys[col2];
144                         if (hweight8(buf1 & buf2) > 1) {
145                                 dev_dbg(dev, "ghost found at: B[%02d]:0x%02x & "
146                                         "B[%02d]:0x%02x", col1, buf1, col2,
147                                         buf2);
148                                 return true;
149                         }
150                 }
151         }
152         return false;
153 }
154
155 /*
156  * mkbp_old_state[row][col] is 1 when the most recent (valid) communication
157  * with the keyboard indicated that the key at row/col was in the pressed
158  * state.
159  */
160 static uint8_t mkbp_old_state[MKBP_NUM_ROWS][MKBP_NUM_COLS];
161
162 /*
163  * Compares the new keyboard state to the old one and produces key
164  * press/release events accordingly.  The keyboard state is 13 bytes (one byte
165  * per column)
166  */
167 static void mkbp_process(struct mkbp_device *mkbp_dev,
168                          uint8_t *kb_state, int len)
169 {
170         int col, row;
171         int new_state;
172         int num_cols;
173
174         num_cols = len;
175
176         if (mkbp_has_ghosting(mkbp_dev, kb_state)) {
177                 /*
178                  * Simple-minded solution: ignore this state. The obvious
179                  * improvement is to only ignore changes to keys involved in
180                  * the ghosting, but process the other changes.
181                  */
182                 dev_dbg(mkbp_dev->dev, "ghosting found\n");
183                 return;
184         }
185
186         for (col = 0; col < MKBP_NUM_COLS; col++) {
187                 for (row = 0; row < MKBP_NUM_ROWS; row++) {
188                         new_state = kb_state[col] & (1 << row);
189                         if (!!new_state != mkbp_old_state[row][col]) {
190                           dev_dbg(mkbp_dev->dev,
191                                   "changed: [r%d c%d]: byte %02x\n",
192                                   row, col, new_state);
193                         }
194                         if (new_state && !mkbp_old_state[row][col]) {
195                                 /* key press */
196                                 mkbp_send_key_event(mkbp_dev, row, col, 1);
197                                 mkbp_old_state[row][col] = 1;
198                         } else if (!new_state && mkbp_old_state[row][col]) {
199                                 /* key release */
200                                 mkbp_send_key_event(mkbp_dev, row, col, 0);
201                                 mkbp_old_state[row][col] = 0;
202                         }
203                 }
204         }
205         input_sync(mkbp_dev->idev);
206 }
207
208 static int mkbp_open(struct input_dev *dev)
209 {
210         struct mkbp_device *mkbp_dev = input_get_drvdata(dev);
211         int ret;
212
213         ret = blocking_notifier_chain_register(&mkbp_dev->ec->event_notifier,
214                                                 &mkbp_dev->notifier);
215         if (ret)
216                 return ret;
217         ret = blocking_notifier_chain_register(&mkbp_dev->ec->wake_notifier,
218                                                 &mkbp_dev->wake_notifier);
219         if (ret) {
220                 blocking_notifier_chain_unregister(
221                         &mkbp_dev->ec->event_notifier, &mkbp_dev->notifier);
222                 return ret;
223         }
224
225         return 0;
226 }
227
228 static void mkbp_close(struct input_dev *dev)
229 {
230         struct mkbp_device *mkbp_dev = input_get_drvdata(dev);
231
232         blocking_notifier_chain_unregister(&mkbp_dev->ec->event_notifier,
233                                            &mkbp_dev->notifier);
234         blocking_notifier_chain_unregister(&mkbp_dev->ec->wake_notifier,
235                                            &mkbp_dev->wake_notifier);
236 }
237
238 static int mkbp_get_state(struct mkbp_device *mkbp_dev, uint8_t *kb_state)
239 {
240         return mkbp_dev->ec->command_recv(mkbp_dev->ec, EC_CMD_MKBP_STATE,
241                                           kb_state, MKBP_NUM_COLS);
242 }
243
244 static int mkbp_work(struct notifier_block *nb,
245                      unsigned long state, void *_notify)
246 {
247         int ret;
248         struct mkbp_device *mkbp_dev = container_of(nb, struct mkbp_device,
249                                                     notifier);
250         uint8_t kb_state[MKBP_NUM_COLS];
251
252         ret = mkbp_get_state(mkbp_dev, kb_state);
253         if (ret >= 0)
254                 mkbp_process(mkbp_dev, kb_state, ret);
255
256         return NOTIFY_DONE;
257 }
258
259 /* On resume, clear any keys in the buffer, crosbug.com/p/14523 */
260 static int mkbp_clear_keyboard(struct notifier_block *nb,
261                                unsigned long state, void *_notify)
262 {
263         struct mkbp_device *mkbp_dev = container_of(nb, struct mkbp_device,
264                                                     wake_notifier);
265         uint8_t old_state[MKBP_NUM_COLS];
266         uint8_t new_state[MKBP_NUM_COLS];
267         unsigned long duration;
268         int i, ret;
269
270         /*
271          * Keep reading until we see that the scan state does not change.
272          * That indicates that we are done.
273          *
274          * Assume that the EC keyscan buffer is at most 32 deep.
275          *
276          * TODO(sjg@chromium.org): Add EC command to clear keyscan FIFO.
277          */
278         duration = jiffies;
279         ret = mkbp_get_state(mkbp_dev, new_state);
280         for (i = 1; !ret && i < 32; i++) {
281                 memcpy(old_state, new_state, sizeof(old_state));
282                 ret = mkbp_get_state(mkbp_dev, new_state);
283                 if (0 == memcmp(old_state, new_state, sizeof(old_state)))
284                         break;
285         }
286         duration = jiffies - duration;
287         dev_info(mkbp_dev->dev, "Discarded %d keyscan(s) in %dus\n", i,
288                 jiffies_to_usecs(duration));
289
290         return 0;
291 }
292
293 /*
294  * Walks keycodes flipping bit in buffer COLUMNS deep where bit is ROW.  Used by
295  * ghosting logic to ignore NULL or virtual keys.
296  */
297 static void __devinit mkbp_compute_valid_keys(struct mkbp_device *mkbp_dev)
298 {
299         int row, col;
300         uint16_t code;
301
302         BUILD_BUG_ON(MKBP_NUM_ROWS > sizeof(mkbp_dev->valid_keys));
303
304         for (col = 0; col < MKBP_NUM_COLS; col++) {
305                 for (row = 0; row < MKBP_NUM_ROWS; row++) {
306                         code = mkbp_keycodes[row][col];
307                         if (code && (code != KEY_BATTERY))
308                                 mkbp_dev->valid_keys[col] |= 1 << row;
309                 }
310                 dev_dbg(mkbp_dev->dev, "valid_keys[%02d] = 0x%02x\n",
311                         col, mkbp_dev->valid_keys[col]);
312         }
313 }
314
315 static int __devinit mkbp_probe(struct platform_device *pdev)
316 {
317         struct chromeos_ec_device *ec = dev_get_drvdata(pdev->dev.parent);
318         struct device *dev = ec->dev;
319         struct mkbp_device *mkbp_dev = NULL;
320         struct input_dev *idev = NULL;
321         int i, err;
322         bool input_device_registered = false;
323
324         dev_dbg(dev, "probing\n");
325
326         mkbp_dev = kzalloc(sizeof(*mkbp_dev), GFP_KERNEL);
327         idev = input_allocate_device();
328         if (idev == NULL || mkbp_dev == NULL) {
329                 err = -ENOMEM;
330                 dev_err(dev, "cannot allocate\n");
331                 goto fail;
332         }
333
334         mkbp_dev->ec = ec;
335         mkbp_dev->notifier.notifier_call = mkbp_work;
336         mkbp_dev->wake_notifier.notifier_call = mkbp_clear_keyboard;
337         mkbp_dev->dev = dev;
338         mkbp_compute_valid_keys(mkbp_dev);
339
340         idev->name = ec->get_name(ec);
341         idev->phys = ec->get_phys_name(ec);
342         idev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);
343         idev->keycode = identity_keycodes;
344         idev->keycodesize = sizeof(identity_keycodes[0]);
345         idev->keycodemax =
346                 sizeof(identity_keycodes) / sizeof(identity_keycodes[0]);
347         for (i = 0; i < idev->keycodemax; i++) {
348                 identity_keycodes[i] = i;
349                 input_set_capability(idev, EV_KEY, i);
350         }
351
352         /* TODO(sjg@chromium.org): This could be SPI or LPC */
353         idev->id.bustype = BUS_I2C;
354         idev->id.version = 1;
355         idev->id.product = 0;
356         idev->dev.parent = ec->get_parent(ec);
357         idev->open = mkbp_open;
358         idev->close = mkbp_close;
359
360         input_set_drvdata(idev, mkbp_dev);
361         mkbp_dev->idev = idev;
362         err = input_register_device(mkbp_dev->idev);
363         if (err) {
364                 dev_err(dev, "cannot register input device\n");
365                 goto fail;
366         }
367         /* We have seen the mkbp work function scheduled as much as 300ms after
368          * the interrupt service routine is called.  The default autorepeat
369          * delay is 250ms.  This can lead to spurious autorepeat.  A better fix
370          * would be to collect time stamps in the ISR, but for the moment a
371          * longer delay helps.
372          *
373          * Also note that we must change the delay after device registration,
374          * or else the input layer assumes that the driver does its own
375          * autorepeat.  (Which we will probably have to do.)
376          */
377         mkbp_dev->idev->rep[REP_DELAY] = 600;
378         input_device_registered = true;
379
380         dev_info(dev, "MKBP Keyboard ready\n");
381
382         return err;
383 fail:
384         if (input_device_registered)
385                 input_unregister_device(idev);
386         kfree(mkbp_dev);
387         input_free_device(idev);
388         return err;
389 }
390
391 static struct platform_driver mkbp_driver = {
392         .probe = mkbp_probe,
393         .driver = {
394                 .name = "mkbp",
395         },
396 };
397
398
399 module_platform_driver(mkbp_driver);
400
401 MODULE_LICENSE("GPL");
402 MODULE_DESCRIPTION("Matrix keyboard protocol driver");
403 MODULE_ALIAS("platform:mkbp");