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