xref: /linux/drivers/input/keyboard/cros_ec_keyb.c (revision b718342a7fbaa2dff5fefc31988c07af8c6cbc21)
1 // SPDX-License-Identifier: GPL-2.0
2 // ChromeOS EC keyboard driver
3 //
4 // Copyright (C) 2012 Google, Inc.
5 //
6 // This driver uses the ChromeOS EC byte-level message-based protocol for
7 // communicating the keyboard state (which keys are pressed) from a keyboard EC
8 // to the AP over some bus (such as i2c, lpc, spi).  The EC does debouncing,
9 // but everything else (including deghosting) is done here.  The main
10 // motivation for this is to keep the EC firmware as simple as possible, since
11 // it cannot be easily upgraded and EC flash/IRAM space is relatively
12 // expensive.
13 
14 #include <linux/module.h>
15 #include <linux/acpi.h>
16 #include <linux/bitops.h>
17 #include <linux/i2c.h>
18 #include <linux/input.h>
19 #include <linux/input/vivaldi-fmap.h>
20 #include <linux/interrupt.h>
21 #include <linux/kernel.h>
22 #include <linux/notifier.h>
23 #include <linux/platform_device.h>
24 #include <linux/slab.h>
25 #include <linux/sysrq.h>
26 #include <linux/input/matrix_keypad.h>
27 #include <linux/platform_data/cros_ec_commands.h>
28 #include <linux/platform_data/cros_ec_proto.h>
29 
30 #include <linux/unaligned.h>
31 
32 /*
33  * Maximum size of the normal key matrix, this is limited by the host command
34  * key_matrix field defined in ec_response_get_next_data_v3
35  */
36 #define CROS_EC_KEYBOARD_COLS_MAX 18
37 
38 /**
39  * struct cros_ec_keyb - Structure representing EC keyboard device
40  *
41  * @rows: Number of rows in the keypad
42  * @cols: Number of columns in the keypad
43  * @row_shift: log2 or number of rows, rounded up
44  * @ghost_filter: true to enable the matrix key-ghosting filter
45  * @valid_keys: bitmap of existing keys for each matrix column
46  * @old_kb_state: bitmap of keys pressed last scan
47  * @dev: Device pointer
48  * @ec: Top level ChromeOS device to use to talk to EC
49  * @idev: The input device for the matrix keys.
50  * @bs_idev: The input device for non-matrix buttons and switches (or NULL).
51  * @notifier: interrupt event notifier for transport devices
52  * @vdata: vivaldi function row data
53  * @has_fn_map: whether the driver uses an fn function-map layer
54  * @fn_active: tracks whether the function key is currently pressed
55  * @fn_combo_active: tracks whether another key was pressed while fn is active
56  */
57 struct cros_ec_keyb {
58 	unsigned int rows;
59 	unsigned int cols;
60 	int row_shift;
61 	bool ghost_filter;
62 	u8 valid_keys[CROS_EC_KEYBOARD_COLS_MAX];
63 	u8 old_kb_state[CROS_EC_KEYBOARD_COLS_MAX];
64 
65 	struct device *dev;
66 	struct cros_ec_device *ec;
67 
68 	struct input_dev *idev;
69 	struct input_dev *bs_idev;
70 	struct notifier_block notifier;
71 
72 	struct vivaldi_data vdata;
73 
74 	bool has_fn_map;
75 	bool fn_active;
76 	bool fn_combo_active;
77 };
78 
79 /**
80  * struct cros_ec_bs_map - Mapping between Linux keycodes and EC button/switch
81  *	bitmap #defines
82  *
83  * @ev_type: The type of the input event to generate (e.g., EV_KEY).
84  * @code: A linux keycode
85  * @bit: A #define like EC_MKBP_POWER_BUTTON or EC_MKBP_LID_OPEN
86  * @inverted: If the #define and EV_SW have opposite meanings, this is true.
87  *            Only applicable to switches.
88  */
89 struct cros_ec_bs_map {
90 	unsigned int ev_type;
91 	unsigned int code;
92 	u8 bit;
93 	bool inverted;
94 };
95 
96 /* cros_ec_keyb_bs - Map EC button/switch #defines into kernel ones */
97 static const struct cros_ec_bs_map cros_ec_keyb_bs[] = {
98 	/* Buttons */
99 	{
100 		.ev_type	= EV_KEY,
101 		.code		= KEY_POWER,
102 		.bit		= EC_MKBP_POWER_BUTTON,
103 	},
104 	{
105 		.ev_type	= EV_KEY,
106 		.code		= KEY_VOLUMEUP,
107 		.bit		= EC_MKBP_VOL_UP,
108 	},
109 	{
110 		.ev_type	= EV_KEY,
111 		.code		= KEY_VOLUMEDOWN,
112 		.bit		= EC_MKBP_VOL_DOWN,
113 	},
114 	{
115 		.ev_type        = EV_KEY,
116 		.code           = KEY_BRIGHTNESSUP,
117 		.bit            = EC_MKBP_BRI_UP,
118 	},
119 	{
120 		.ev_type        = EV_KEY,
121 		.code           = KEY_BRIGHTNESSDOWN,
122 		.bit            = EC_MKBP_BRI_DOWN,
123 	},
124 	{
125 		.ev_type        = EV_KEY,
126 		.code           = KEY_SCREENLOCK,
127 		.bit            = EC_MKBP_SCREEN_LOCK,
128 	},
129 
130 	/* Switches */
131 	{
132 		.ev_type	= EV_SW,
133 		.code		= SW_LID,
134 		.bit		= EC_MKBP_LID_OPEN,
135 		.inverted	= true,
136 	},
137 	{
138 		.ev_type	= EV_SW,
139 		.code		= SW_TABLET_MODE,
140 		.bit		= EC_MKBP_TABLET_MODE,
141 	},
142 };
143 
144 /*
145  * Returns true when there is at least one combination of pressed keys that
146  * results in ghosting.
147  */
148 static bool cros_ec_keyb_has_ghosting(struct cros_ec_keyb *ckdev, u8 *buf)
149 {
150 	int col1, col2, buf1, buf2;
151 	struct device *dev = ckdev->dev;
152 	u8 *valid_keys = ckdev->valid_keys;
153 
154 	/*
155 	 * Ghosting happens if for any pressed key X there are other keys
156 	 * pressed both in the same row and column of X as, for instance,
157 	 * in the following diagram:
158 	 *
159 	 * . . Y . g .
160 	 * . . . . . .
161 	 * . . . . . .
162 	 * . . X . Z .
163 	 *
164 	 * In this case only X, Y, and Z are pressed, but g appears to be
165 	 * pressed too (see Wikipedia).
166 	 */
167 	for (col1 = 0; col1 < ckdev->cols; col1++) {
168 		buf1 = buf[col1] & valid_keys[col1];
169 		for (col2 = col1 + 1; col2 < ckdev->cols; col2++) {
170 			buf2 = buf[col2] & valid_keys[col2];
171 			if (hweight8(buf1 & buf2) > 1) {
172 				dev_dbg(dev, "ghost found at: B[%02d]:0x%02x & B[%02d]:0x%02x",
173 					col1, buf1, col2, buf2);
174 				return true;
175 			}
176 		}
177 	}
178 
179 	return false;
180 }
181 
182 static void cros_ec_emit_fn_key(struct input_dev *input, unsigned int pos)
183 {
184 	input_event(input, EV_MSC, MSC_SCAN, pos);
185 	input_report_key(input, KEY_FN, true);
186 	input_sync(input);
187 
188 	input_event(input, EV_MSC, MSC_SCAN, pos);
189 	input_report_key(input, KEY_FN, false);
190 }
191 
192 static void cros_ec_keyb_process_key_plain(struct cros_ec_keyb *ckdev,
193 					   int row, int col, bool state)
194 {
195 	struct input_dev *idev = ckdev->idev;
196 	const unsigned short *keycodes = idev->keycode;
197 	int pos = MATRIX_SCAN_CODE(row, col, ckdev->row_shift);
198 
199 	input_event(idev, EV_MSC, MSC_SCAN, pos);
200 	input_report_key(idev, keycodes[pos], state);
201 }
202 
203 static void cros_ec_keyb_process_key_fn_map(struct cros_ec_keyb *ckdev,
204 					    int row, int col, bool state)
205 {
206 	struct input_dev *idev = ckdev->idev;
207 	const unsigned short *keycodes = idev->keycode;
208 	unsigned int pos, fn_pos;
209 	unsigned int code, fn_code;
210 
211 	pos = MATRIX_SCAN_CODE(row, col, ckdev->row_shift);
212 	code = keycodes[pos];
213 
214 	if (code == KEY_FN) {
215 		ckdev->fn_active = state;
216 		if (state) {
217 			ckdev->fn_combo_active = false;
218 		} else if (!ckdev->fn_combo_active) {
219 			/*
220 			 * Send both Fn press and release events if nothing
221 			 * else has been pressed together with Fn.
222 			 */
223 			cros_ec_emit_fn_key(idev, pos);
224 		}
225 		return;
226 	}
227 
228 	fn_pos = MATRIX_SCAN_CODE(row + ckdev->rows, col, ckdev->row_shift);
229 	fn_code = keycodes[fn_pos];
230 
231 	if (state) {
232 		if (ckdev->fn_active) {
233 			ckdev->fn_combo_active = true;
234 			if (!fn_code)
235 				return; /* Discard if no Fn mapping exists */
236 
237 			pos = fn_pos;
238 			code = fn_code;
239 		}
240 	} else {
241 		/*
242 		 * If the Fn-remapped code is currently pressed, release it.
243 		 * Otherwise, release the standard code (if it was pressed).
244 		 */
245 		if (fn_code && test_bit(fn_code, idev->key)) {
246 			pos = fn_pos;
247 			code = fn_code;
248 		} else if (!test_bit(code, idev->key)) {
249 			return; /* Discard, key press code was not sent */
250 		}
251 	}
252 
253 	input_event(idev, EV_MSC, MSC_SCAN, pos);
254 	input_report_key(idev, code, state);
255 }
256 
257 static void cros_ec_keyb_process_col(struct cros_ec_keyb *ckdev, int col,
258 				     u8 col_state, u8 changed)
259 {
260 	for (int row = 0; row < ckdev->rows; row++) {
261 		if (changed & BIT(row)) {
262 			u8 key_state = col_state & BIT(row);
263 
264 			dev_dbg(ckdev->dev, "changed: [r%d c%d]: byte %02x\n",
265 				row, col, key_state);
266 
267 			if (ckdev->has_fn_map)
268 				cros_ec_keyb_process_key_fn_map(ckdev, row, col,
269 								key_state);
270 			else
271 				cros_ec_keyb_process_key_plain(ckdev, row, col,
272 							       key_state);
273 		}
274 	}
275 }
276 
277 /*
278  * Compares the new keyboard state to the old one and produces key
279  * press/release events accordingly.  The keyboard state is one byte
280  * per column.
281  */
282 static void cros_ec_keyb_process(struct cros_ec_keyb *ckdev, u8 *kb_state, int len)
283 {
284 	if (ckdev->ghost_filter && cros_ec_keyb_has_ghosting(ckdev, kb_state)) {
285 		/*
286 		 * Simple-minded solution: ignore this state. The obvious
287 		 * improvement is to only ignore changes to keys involved in
288 		 * the ghosting, but process the other changes.
289 		 */
290 		dev_dbg(ckdev->dev, "ghosting found\n");
291 		return;
292 	}
293 
294 	for (int col = 0; col < ckdev->cols; col++) {
295 		u8 changed = kb_state[col] ^ ckdev->old_kb_state[col];
296 
297 		if (changed)
298 			cros_ec_keyb_process_col(ckdev, col, kb_state[col],
299 						 changed);
300 	}
301 
302 	memcpy(ckdev->old_kb_state, kb_state, sizeof(ckdev->old_kb_state));
303 	input_sync(ckdev->idev);
304 }
305 
306 /**
307  * cros_ec_keyb_report_bs - Report non-matrixed buttons or switches
308  *
309  * This takes a bitmap of buttons or switches from the EC and reports events,
310  * syncing at the end.
311  *
312  * @ckdev: The keyboard device.
313  * @ev_type: The input event type (e.g., EV_KEY).
314  * @mask: A bitmap of buttons from the EC.
315  */
316 static void cros_ec_keyb_report_bs(struct cros_ec_keyb *ckdev,
317 				   unsigned int ev_type, u32 mask)
318 
319 {
320 	struct input_dev *idev = ckdev->bs_idev;
321 	int i;
322 
323 	for (i = 0; i < ARRAY_SIZE(cros_ec_keyb_bs); i++) {
324 		const struct cros_ec_bs_map *map = &cros_ec_keyb_bs[i];
325 
326 		if (map->ev_type != ev_type)
327 			continue;
328 
329 		input_event(idev, ev_type, map->code,
330 			    !!(mask & BIT(map->bit)) ^ map->inverted);
331 	}
332 	input_sync(idev);
333 }
334 
335 static int cros_ec_keyb_work(struct notifier_block *nb,
336 			     unsigned long queued_during_suspend, void *_notify)
337 {
338 	struct cros_ec_keyb *ckdev = container_of(nb, struct cros_ec_keyb,
339 						  notifier);
340 	struct ec_response_get_next_event_v3 *event_data;
341 	unsigned int event_size;
342 	unsigned int ev_type;
343 	u32 val;
344 
345 	/*
346 	 * If not wake enabled, discard key state changes during
347 	 * suspend. Switches will be re-checked in
348 	 * cros_ec_keyb_resume() to be sure nothing is lost.
349 	 */
350 	if (queued_during_suspend && !device_may_wakeup(ckdev->dev))
351 		return NOTIFY_OK;
352 
353 	event_data = &ckdev->ec->event_data;
354 	event_size = ckdev->ec->event_size;
355 
356 	switch (event_data->event_type) {
357 	case EC_MKBP_EVENT_KEY_MATRIX:
358 		pm_wakeup_event(ckdev->dev, 0);
359 
360 		if (!ckdev->idev) {
361 			dev_warn_once(ckdev->dev, "Unexpected key matrix event\n");
362 			return NOTIFY_OK;
363 		}
364 
365 		if (event_size != ckdev->cols) {
366 			dev_err(ckdev->dev,
367 				"Discarded key matrix event, unexpected length: %d != %d\n",
368 				ckdev->ec->event_size, ckdev->cols);
369 			return NOTIFY_OK;
370 		}
371 
372 		cros_ec_keyb_process(ckdev, event_data->data.key_matrix, event_size);
373 		break;
374 
375 	case EC_MKBP_EVENT_SYSRQ:
376 		pm_wakeup_event(ckdev->dev, 0);
377 
378 		val = get_unaligned_le32(&event_data->data.sysrq);
379 		dev_dbg(ckdev->dev, "sysrq code from EC: %#x\n", val);
380 		handle_sysrq(val);
381 		break;
382 
383 	case EC_MKBP_EVENT_BUTTON:
384 	case EC_MKBP_EVENT_SWITCH:
385 		pm_wakeup_event(ckdev->dev, 0);
386 
387 		if (event_data->event_type == EC_MKBP_EVENT_BUTTON) {
388 			val = get_unaligned_le32(&event_data->data.buttons);
389 			ev_type = EV_KEY;
390 		} else {
391 			val = get_unaligned_le32(&event_data->data.switches);
392 			ev_type = EV_SW;
393 		}
394 		cros_ec_keyb_report_bs(ckdev, ev_type, val);
395 		break;
396 
397 	default:
398 		return NOTIFY_DONE;
399 	}
400 
401 	return NOTIFY_OK;
402 }
403 
404 /*
405  * Walks keycodes flipping bit in buffer COLUMNS deep where bit is ROW.  Used by
406  * ghosting logic to ignore NULL or virtual keys.
407  */
408 static void cros_ec_keyb_compute_valid_keys(struct cros_ec_keyb *ckdev)
409 {
410 	int row, col;
411 	int row_shift = ckdev->row_shift;
412 	unsigned short *keymap = ckdev->idev->keycode;
413 	unsigned short code;
414 
415 	BUG_ON(ckdev->idev->keycodesize != sizeof(*keymap));
416 
417 	for (col = 0; col < ckdev->cols; col++) {
418 		for (row = 0; row < ckdev->rows; row++) {
419 			code = keymap[MATRIX_SCAN_CODE(row, col, row_shift)];
420 			if (code != KEY_RESERVED && code != KEY_BATTERY)
421 				ckdev->valid_keys[col] |= BIT(row);
422 		}
423 		dev_dbg(ckdev->dev, "valid_keys[%02d] = 0x%02x\n",
424 			col, ckdev->valid_keys[col]);
425 	}
426 }
427 
428 /**
429  * cros_ec_keyb_info - Wrap the EC command EC_CMD_MKBP_INFO
430  *
431  * This wraps the EC_CMD_MKBP_INFO, abstracting out all of the marshalling and
432  * unmarshalling and different version nonsense into something simple.
433  *
434  * @ec_dev: The EC device
435  * @info_type: Either EC_MKBP_INFO_SUPPORTED or EC_MKBP_INFO_CURRENT.
436  * @event_type: Either EC_MKBP_EVENT_BUTTON or EC_MKBP_EVENT_SWITCH.  Actually
437  *              in some cases this could be EC_MKBP_EVENT_KEY_MATRIX or
438  *              EC_MKBP_EVENT_HOST_EVENT too but we don't use in this driver.
439  * @result: Where we'll store the result; a union
440  * @result_size: The size of the result.  Expected to be the size of one of
441  *               the elements in the union.
442  *
443  * Returns 0 if no error or -error upon error.
444  */
445 static int cros_ec_keyb_info(struct cros_ec_device *ec_dev,
446 			     enum ec_mkbp_info_type info_type,
447 			     enum ec_mkbp_event event_type,
448 			     union ec_response_get_next_data *result,
449 			     size_t result_size)
450 {
451 	struct ec_params_mkbp_info *params;
452 	struct cros_ec_command *msg;
453 	int ret;
454 
455 	msg = kzalloc(sizeof(*msg) + max_t(size_t, result_size,
456 					   sizeof(*params)), GFP_KERNEL);
457 	if (!msg)
458 		return -ENOMEM;
459 
460 	msg->command = EC_CMD_MKBP_INFO;
461 	msg->version = 1;
462 	msg->outsize = sizeof(*params);
463 	msg->insize = result_size;
464 	params = (struct ec_params_mkbp_info *)msg->data;
465 	params->info_type = info_type;
466 	params->event_type = event_type;
467 
468 	ret = cros_ec_cmd_xfer_status(ec_dev, msg);
469 	if (ret == -ENOPROTOOPT) {
470 		/* With older ECs we just return 0 for everything */
471 		memset(result, 0, result_size);
472 		ret = 0;
473 	} else if (ret < 0) {
474 		dev_warn(ec_dev->dev, "Transfer error %d/%d: %d\n",
475 			 (int)info_type, (int)event_type, ret);
476 	} else if (ret != result_size) {
477 		dev_warn(ec_dev->dev, "Wrong size %d/%d: %d != %zu\n",
478 			 (int)info_type, (int)event_type,
479 			 ret, result_size);
480 		ret = -EPROTO;
481 	} else {
482 		memcpy(result, msg->data, result_size);
483 		ret = 0;
484 	}
485 
486 	kfree(msg);
487 
488 	return ret;
489 }
490 
491 /**
492  * cros_ec_keyb_query_switches - Query the state of switches and report
493  *
494  * This will ask the EC about the current state of switches and report to the
495  * kernel.  Note that we don't query for buttons because they are more
496  * transitory and we'll get an update on the next release / press.
497  *
498  * @ckdev: The keyboard device
499  *
500  * Returns 0 if no error or -error upon error.
501  */
502 static int cros_ec_keyb_query_switches(struct cros_ec_keyb *ckdev)
503 {
504 	struct cros_ec_device *ec_dev = ckdev->ec;
505 	union ec_response_get_next_data event_data = {};
506 	int ret;
507 
508 	ret = cros_ec_keyb_info(ec_dev, EC_MKBP_INFO_CURRENT,
509 				EC_MKBP_EVENT_SWITCH, &event_data,
510 				sizeof(event_data.switches));
511 	if (ret)
512 		return ret;
513 
514 	cros_ec_keyb_report_bs(ckdev, EV_SW,
515 			       get_unaligned_le32(&event_data.switches));
516 
517 	return 0;
518 }
519 
520 /**
521  * cros_ec_keyb_resume - Resume the keyboard
522  *
523  * We use the resume notification as a chance to query the EC for switches.
524  *
525  * @dev: The keyboard device
526  *
527  * Returns 0 if no error or -error upon error.
528  */
529 static int cros_ec_keyb_resume(struct device *dev)
530 {
531 	struct cros_ec_keyb *ckdev = dev_get_drvdata(dev);
532 
533 	if (ckdev->bs_idev)
534 		return cros_ec_keyb_query_switches(ckdev);
535 
536 	return 0;
537 }
538 
539 /**
540  * cros_ec_keyb_register_bs - Register non-matrix buttons/switches
541  *
542  * Handles all the bits of the keyboard driver related to non-matrix buttons
543  * and switches, including asking the EC about which are present and telling
544  * the kernel to expect them.
545  *
546  * If this device has no support for buttons and switches we'll return no error
547  * but the ckdev->bs_idev will remain NULL when this function exits.
548  *
549  * @ckdev: The keyboard device
550  * @expect_buttons_switches: Indicates that EC must report button and/or
551  *   switch events
552  *
553  * Returns 0 if no error or -error upon error.
554  */
555 static int cros_ec_keyb_register_bs(struct cros_ec_keyb *ckdev,
556 				    bool expect_buttons_switches)
557 {
558 	struct cros_ec_device *ec_dev = ckdev->ec;
559 	struct device *dev = ckdev->dev;
560 	struct input_dev *idev;
561 	union ec_response_get_next_data event_data = {};
562 	const char *phys;
563 	u32 buttons;
564 	u32 switches;
565 	int ret;
566 	int i;
567 
568 	ret = cros_ec_keyb_info(ec_dev, EC_MKBP_INFO_SUPPORTED,
569 				EC_MKBP_EVENT_BUTTON, &event_data,
570 				sizeof(event_data.buttons));
571 	if (ret)
572 		return ret;
573 	buttons = get_unaligned_le32(&event_data.buttons);
574 
575 	ret = cros_ec_keyb_info(ec_dev, EC_MKBP_INFO_SUPPORTED,
576 				EC_MKBP_EVENT_SWITCH, &event_data,
577 				sizeof(event_data.switches));
578 	if (ret)
579 		return ret;
580 	switches = get_unaligned_le32(&event_data.switches);
581 
582 	if (!buttons && !switches)
583 		return expect_buttons_switches ? -EINVAL : 0;
584 
585 	/*
586 	 * We call the non-matrix buttons/switches 'input1', if present.
587 	 * Allocate phys before input dev, to ensure correct tear-down
588 	 * ordering.
589 	 */
590 	phys = devm_kasprintf(dev, GFP_KERNEL, "%s/input1", ec_dev->phys_name);
591 	if (!phys)
592 		return -ENOMEM;
593 
594 	idev = devm_input_allocate_device(dev);
595 	if (!idev)
596 		return -ENOMEM;
597 
598 	idev->name = "cros_ec_buttons";
599 	idev->phys = phys;
600 	__set_bit(EV_REP, idev->evbit);
601 
602 	idev->id.bustype = BUS_VIRTUAL;
603 	idev->id.version = 1;
604 	idev->id.product = 0;
605 	idev->dev.parent = dev;
606 
607 	input_set_drvdata(idev, ckdev);
608 	ckdev->bs_idev = idev;
609 
610 	for (i = 0; i < ARRAY_SIZE(cros_ec_keyb_bs); i++) {
611 		const struct cros_ec_bs_map *map = &cros_ec_keyb_bs[i];
612 
613 		if ((map->ev_type == EV_KEY && (buttons & BIT(map->bit))) ||
614 		    (map->ev_type == EV_SW && (switches & BIT(map->bit))))
615 			input_set_capability(idev, map->ev_type, map->code);
616 	}
617 
618 	ret = cros_ec_keyb_query_switches(ckdev);
619 	if (ret) {
620 		dev_err(dev, "cannot query switches\n");
621 		return ret;
622 	}
623 
624 	ret = input_register_device(ckdev->bs_idev);
625 	if (ret) {
626 		dev_err(dev, "cannot register input device\n");
627 		return ret;
628 	}
629 
630 	return 0;
631 }
632 
633 static void cros_ec_keyb_parse_vivaldi_physmap(struct cros_ec_keyb *ckdev)
634 {
635 	u32 *physmap = ckdev->vdata.function_row_physmap;
636 	unsigned int row, col, scancode;
637 	int n_physmap;
638 	int error;
639 	int i;
640 
641 	n_physmap = device_property_count_u32(ckdev->dev,
642 					      "function-row-physmap");
643 	if (n_physmap <= 0)
644 		return;
645 
646 	if (n_physmap >= VIVALDI_MAX_FUNCTION_ROW_KEYS) {
647 		dev_warn(ckdev->dev,
648 			 "only up to %d top row keys is supported (%d specified)\n",
649 			 VIVALDI_MAX_FUNCTION_ROW_KEYS, n_physmap);
650 		n_physmap = VIVALDI_MAX_FUNCTION_ROW_KEYS;
651 	}
652 
653 	error = device_property_read_u32_array(ckdev->dev,
654 					       "function-row-physmap",
655 					       physmap, n_physmap);
656 	if (error) {
657 		dev_warn(ckdev->dev,
658 			 "failed to parse function-row-physmap property: %d\n",
659 			 error);
660 		return;
661 	}
662 
663 	/*
664 	 * Convert (in place) from row/column encoding to matrix "scancode"
665 	 * used by the driver.
666 	 */
667 	for (i = 0; i < n_physmap; i++) {
668 		row = KEY_ROW(physmap[i]);
669 		col = KEY_COL(physmap[i]);
670 		scancode = MATRIX_SCAN_CODE(row, col, ckdev->row_shift);
671 		physmap[i] = scancode;
672 	}
673 
674 	ckdev->vdata.num_function_row_keys = n_physmap;
675 }
676 
677 /* Returns true if there is a KEY_FN code defined in the normal keymap */
678 static bool cros_ec_keyb_has_fn_key(struct cros_ec_keyb *ckdev)
679 {
680 	const unsigned short *keycodes = ckdev->idev->keycode;
681 	int i;
682 
683 	for (i = 0; i < MATRIX_SCAN_CODE(ckdev->rows, 0, ckdev->row_shift); i++) {
684 		if (keycodes[i] == KEY_FN)
685 			return true;
686 	}
687 
688 	return false;
689 }
690 
691 /*
692  * Returns true if there is a KEY_FN defined and at least one key in the fn
693  * layer keymap
694  */
695 static bool cros_ec_keyb_has_fn_map(struct cros_ec_keyb *ckdev)
696 {
697 	struct input_dev *idev = ckdev->idev;
698 	const unsigned short *keycodes = ckdev->idev->keycode;
699 	int i;
700 
701 	if (!cros_ec_keyb_has_fn_key(ckdev))
702 		return false;
703 
704 	for (i = MATRIX_SCAN_CODE(ckdev->rows, 0, ckdev->row_shift);
705 	     i < idev->keycodemax; i++) {
706 		if (keycodes[i] != KEY_RESERVED)
707 			return true;
708 	}
709 
710 	return false;
711 }
712 
713 /*
714  * Custom handler for the set keycode ioctl, calls the default handler and
715  * recomputes has_fn_map.
716  */
717 static int cros_ec_keyb_setkeycode(struct input_dev *idev,
718 				   const struct input_keymap_entry *ke,
719 				   unsigned int *old_keycode)
720 {
721 	struct cros_ec_keyb *ckdev = input_get_drvdata(idev);
722 	int ret;
723 
724 	ret = input_default_setkeycode(idev, ke, old_keycode);
725 	if (ret)
726 		return ret;
727 
728 	ckdev->has_fn_map = cros_ec_keyb_has_fn_map(ckdev);
729 
730 	return 0;
731 }
732 
733 /**
734  * cros_ec_keyb_register_matrix - Register matrix keys
735  *
736  * Handles all the bits of the keyboard driver related to matrix keys.
737  *
738  * @ckdev: The keyboard device
739  *
740  * Returns 0 if no error or -error upon error.
741  */
742 static int cros_ec_keyb_register_matrix(struct cros_ec_keyb *ckdev)
743 {
744 	struct cros_ec_device *ec_dev = ckdev->ec;
745 	struct device *dev = ckdev->dev;
746 	struct input_dev *idev;
747 	const char *phys;
748 	int err;
749 
750 	err = matrix_keypad_parse_properties(dev, &ckdev->rows, &ckdev->cols);
751 	if (err)
752 		return err;
753 
754 	if (ckdev->cols > CROS_EC_KEYBOARD_COLS_MAX) {
755 		dev_err(dev, "keypad,num-columns too large: %d (max: %d)\n",
756 			ckdev->cols, CROS_EC_KEYBOARD_COLS_MAX);
757 		return -EINVAL;
758 	}
759 
760 	/*
761 	 * We call the keyboard matrix 'input0'. Allocate phys before input
762 	 * dev, to ensure correct tear-down ordering.
763 	 */
764 	phys = devm_kasprintf(dev, GFP_KERNEL, "%s/input0", ec_dev->phys_name);
765 	if (!phys)
766 		return -ENOMEM;
767 
768 	idev = devm_input_allocate_device(dev);
769 	if (!idev)
770 		return -ENOMEM;
771 
772 	idev->name = CROS_EC_DEV_NAME;
773 	idev->phys = phys;
774 	__set_bit(EV_REP, idev->evbit);
775 
776 	idev->id.bustype = BUS_VIRTUAL;
777 	idev->id.version = 1;
778 	idev->id.product = 0;
779 	idev->dev.parent = dev;
780 	idev->setkeycode = cros_ec_keyb_setkeycode;
781 
782 	ckdev->ghost_filter = device_property_read_bool(dev, "google,needs-ghost-filter");
783 
784 	err = matrix_keypad_build_keymap(NULL, NULL, ckdev->rows * 2, ckdev->cols,
785 					 NULL, idev);
786 	if (err) {
787 		dev_err(dev, "cannot build key matrix\n");
788 		return err;
789 	}
790 
791 	ckdev->row_shift = get_count_order(ckdev->cols);
792 
793 	input_set_capability(idev, EV_MSC, MSC_SCAN);
794 	input_set_drvdata(idev, ckdev);
795 	ckdev->idev = idev;
796 	cros_ec_keyb_compute_valid_keys(ckdev);
797 	cros_ec_keyb_parse_vivaldi_physmap(ckdev);
798 
799 	ckdev->has_fn_map = cros_ec_keyb_has_fn_map(ckdev);
800 
801 	err = input_register_device(ckdev->idev);
802 	if (err) {
803 		dev_err(dev, "cannot register input device\n");
804 		return err;
805 	}
806 
807 	return 0;
808 }
809 
810 static ssize_t function_row_physmap_show(struct device *dev,
811 					 struct device_attribute *attr,
812 					 char *buf)
813 {
814 	const struct cros_ec_keyb *ckdev = dev_get_drvdata(dev);
815 	const struct vivaldi_data *data = &ckdev->vdata;
816 
817 	return vivaldi_function_row_physmap_show(data, buf);
818 }
819 
820 static DEVICE_ATTR_RO(function_row_physmap);
821 
822 static struct attribute *cros_ec_keyb_attrs[] = {
823 	&dev_attr_function_row_physmap.attr,
824 	NULL,
825 };
826 
827 static umode_t cros_ec_keyb_attr_is_visible(struct kobject *kobj,
828 					    struct attribute *attr,
829 					    int n)
830 {
831 	struct device *dev = kobj_to_dev(kobj);
832 	struct cros_ec_keyb *ckdev = dev_get_drvdata(dev);
833 
834 	if (attr == &dev_attr_function_row_physmap.attr &&
835 	    !ckdev->vdata.num_function_row_keys)
836 		return 0;
837 
838 	return attr->mode;
839 }
840 
841 static const struct attribute_group cros_ec_keyb_group = {
842 	.is_visible = cros_ec_keyb_attr_is_visible,
843 	.attrs = cros_ec_keyb_attrs,
844 };
845 __ATTRIBUTE_GROUPS(cros_ec_keyb);
846 
847 static int cros_ec_keyb_probe(struct platform_device *pdev)
848 {
849 	struct cros_ec_device *ec;
850 	struct device *dev = &pdev->dev;
851 	struct cros_ec_keyb *ckdev;
852 	bool buttons_switches_only = device_get_match_data(dev);
853 	int err;
854 
855 	/*
856 	 * If the parent ec device has not been probed yet, defer the probe of
857 	 * this keyboard/button driver until later.
858 	 */
859 	ec = dev_get_drvdata(pdev->dev.parent);
860 	if (!ec)
861 		return -EPROBE_DEFER;
862 	/*
863 	 * Even if the cros_ec_device pointer is available, still need to check
864 	 * if the device is fully registered before using it.
865 	 */
866 	if (!cros_ec_device_registered(ec))
867 		return -EPROBE_DEFER;
868 
869 	ckdev = devm_kzalloc(dev, sizeof(*ckdev), GFP_KERNEL);
870 	if (!ckdev)
871 		return -ENOMEM;
872 
873 	ckdev->ec = ec;
874 	ckdev->dev = dev;
875 	dev_set_drvdata(dev, ckdev);
876 
877 	if (!buttons_switches_only) {
878 		err = cros_ec_keyb_register_matrix(ckdev);
879 		if (err) {
880 			dev_err(dev, "cannot register matrix inputs: %d\n",
881 				err);
882 			return err;
883 		}
884 	}
885 
886 	err = cros_ec_keyb_register_bs(ckdev, buttons_switches_only);
887 	if (err) {
888 		dev_err(dev, "cannot register non-matrix inputs: %d\n", err);
889 		return err;
890 	}
891 
892 	ckdev->notifier.notifier_call = cros_ec_keyb_work;
893 	err = blocking_notifier_chain_register(&ckdev->ec->event_notifier,
894 					       &ckdev->notifier);
895 	if (err) {
896 		dev_err(dev, "cannot register notifier: %d\n", err);
897 		return err;
898 	}
899 
900 	device_init_wakeup(ckdev->dev, true);
901 	return 0;
902 }
903 
904 static void cros_ec_keyb_remove(struct platform_device *pdev)
905 {
906 	struct cros_ec_keyb *ckdev = dev_get_drvdata(&pdev->dev);
907 
908 	blocking_notifier_chain_unregister(&ckdev->ec->event_notifier,
909 					   &ckdev->notifier);
910 }
911 
912 #ifdef CONFIG_ACPI
913 static const struct acpi_device_id cros_ec_keyb_acpi_match[] = {
914 	{ "GOOG0007", true },
915 	{ }
916 };
917 MODULE_DEVICE_TABLE(acpi, cros_ec_keyb_acpi_match);
918 #endif
919 
920 #ifdef CONFIG_OF
921 static const struct of_device_id cros_ec_keyb_of_match[] = {
922 	{ .compatible = "google,cros-ec-keyb" },
923 	{ .compatible = "google,cros-ec-keyb-switches", .data = (void *)true },
924 	{}
925 };
926 MODULE_DEVICE_TABLE(of, cros_ec_keyb_of_match);
927 #endif
928 
929 static DEFINE_SIMPLE_DEV_PM_OPS(cros_ec_keyb_pm_ops, NULL, cros_ec_keyb_resume);
930 
931 static struct platform_driver cros_ec_keyb_driver = {
932 	.probe = cros_ec_keyb_probe,
933 	.remove = cros_ec_keyb_remove,
934 	.driver = {
935 		.name = "cros-ec-keyb",
936 		.dev_groups = cros_ec_keyb_groups,
937 		.of_match_table = of_match_ptr(cros_ec_keyb_of_match),
938 		.acpi_match_table = ACPI_PTR(cros_ec_keyb_acpi_match),
939 		.pm = pm_sleep_ptr(&cros_ec_keyb_pm_ops),
940 	},
941 };
942 
943 module_platform_driver(cros_ec_keyb_driver);
944 
945 MODULE_LICENSE("GPL v2");
946 MODULE_DESCRIPTION("ChromeOS EC keyboard driver");
947 MODULE_ALIAS("platform:cros-ec-keyb");
948