1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 *  GPIO driven matrix keyboard driver
4 *
5 *  Copyright (c) 2008 Marek Vasut <marek.vasut@gmail.com>
6 *
7 *  Based on corgikbd.c
8 */
9
10#include <linux/types.h>
11#include <linux/delay.h>
12#include <linux/gpio/consumer.h>
13#include <linux/platform_device.h>
14#include <linux/input.h>
15#include <linux/irq.h>
16#include <linux/interrupt.h>
17#include <linux/jiffies.h>
18#include <linux/module.h>
19#include <linux/gpio.h>
20#include <linux/input/matrix_keypad.h>
21#include <linux/slab.h>
22#include <linux/of.h>
23#include <linux/of_gpio.h>
24#include <linux/of_platform.h>
25
26struct matrix_keypad {
27	const struct matrix_keypad_platform_data *pdata;
28	struct input_dev *input_dev;
29	unsigned int row_shift;
30
31	unsigned int row_irqs[MATRIX_MAX_ROWS];
32	unsigned int num_row_irqs;
33	DECLARE_BITMAP(wakeup_enabled_irqs, MATRIX_MAX_ROWS);
34
35	uint32_t last_key_state[MATRIX_MAX_COLS];
36	struct delayed_work work;
37	spinlock_t lock;
38	bool scan_pending;
39	bool stopped;
40	bool gpio_all_disabled;
41};
42
43/*
44 * NOTE: If drive_inactive_cols is false, then the GPIO has to be put into
45 * HiZ when de-activated to cause minmal side effect when scanning other
46 * columns. In that case it is configured here to be input, otherwise it is
47 * driven with the inactive value.
48 */
49static void __activate_col(const struct matrix_keypad_platform_data *pdata,
50			   int col, bool on)
51{
52	bool level_on = !pdata->active_low;
53
54	if (on) {
55		gpio_direction_output(pdata->col_gpios[col], level_on);
56	} else {
57		gpio_set_value_cansleep(pdata->col_gpios[col], !level_on);
58		if (!pdata->drive_inactive_cols)
59			gpio_direction_input(pdata->col_gpios[col]);
60	}
61}
62
63static void activate_col(const struct matrix_keypad_platform_data *pdata,
64			 int col, bool on)
65{
66	__activate_col(pdata, col, on);
67
68	if (on && pdata->col_scan_delay_us)
69		udelay(pdata->col_scan_delay_us);
70}
71
72static void activate_all_cols(const struct matrix_keypad_platform_data *pdata,
73			      bool on)
74{
75	int col;
76
77	for (col = 0; col < pdata->num_col_gpios; col++)
78		__activate_col(pdata, col, on);
79}
80
81static bool row_asserted(const struct matrix_keypad_platform_data *pdata,
82			 int row)
83{
84	return gpio_get_value_cansleep(pdata->row_gpios[row]) ?
85			!pdata->active_low : pdata->active_low;
86}
87
88static void enable_row_irqs(struct matrix_keypad *keypad)
89{
90	int i;
91
92	for (i = 0; i < keypad->num_row_irqs; i++)
93		enable_irq(keypad->row_irqs[i]);
94}
95
96static void disable_row_irqs(struct matrix_keypad *keypad)
97{
98	int i;
99
100	for (i = 0; i < keypad->num_row_irqs; i++)
101		disable_irq_nosync(keypad->row_irqs[i]);
102}
103
104/*
105 * This gets the keys from keyboard and reports it to input subsystem
106 */
107static void matrix_keypad_scan(struct work_struct *work)
108{
109	struct matrix_keypad *keypad =
110		container_of(work, struct matrix_keypad, work.work);
111	struct input_dev *input_dev = keypad->input_dev;
112	const unsigned short *keycodes = input_dev->keycode;
113	const struct matrix_keypad_platform_data *pdata = keypad->pdata;
114	uint32_t new_state[MATRIX_MAX_COLS];
115	int row, col, code;
116
117	/* de-activate all columns for scanning */
118	activate_all_cols(pdata, false);
119
120	memset(new_state, 0, sizeof(new_state));
121
122	for (row = 0; row < pdata->num_row_gpios; row++)
123		gpio_direction_input(pdata->row_gpios[row]);
124
125	/* assert each column and read the row status out */
126	for (col = 0; col < pdata->num_col_gpios; col++) {
127
128		activate_col(pdata, col, true);
129
130		for (row = 0; row < pdata->num_row_gpios; row++)
131			new_state[col] |=
132				row_asserted(pdata, row) ? (1 << row) : 0;
133
134		activate_col(pdata, col, false);
135	}
136
137	for (col = 0; col < pdata->num_col_gpios; col++) {
138		uint32_t bits_changed;
139
140		bits_changed = keypad->last_key_state[col] ^ new_state[col];
141		if (bits_changed == 0)
142			continue;
143
144		for (row = 0; row < pdata->num_row_gpios; row++) {
145			if ((bits_changed & (1 << row)) == 0)
146				continue;
147
148			code = MATRIX_SCAN_CODE(row, col, keypad->row_shift);
149			input_event(input_dev, EV_MSC, MSC_SCAN, code);
150			input_report_key(input_dev,
151					 keycodes[code],
152					 new_state[col] & (1 << row));
153		}
154	}
155	input_sync(input_dev);
156
157	memcpy(keypad->last_key_state, new_state, sizeof(new_state));
158
159	activate_all_cols(pdata, true);
160
161	/* Enable IRQs again */
162	spin_lock_irq(&keypad->lock);
163	keypad->scan_pending = false;
164	enable_row_irqs(keypad);
165	spin_unlock_irq(&keypad->lock);
166}
167
168static irqreturn_t matrix_keypad_interrupt(int irq, void *id)
169{
170	struct matrix_keypad *keypad = id;
171	unsigned long flags;
172
173	spin_lock_irqsave(&keypad->lock, flags);
174
175	/*
176	 * See if another IRQ beaten us to it and scheduled the
177	 * scan already. In that case we should not try to
178	 * disable IRQs again.
179	 */
180	if (unlikely(keypad->scan_pending || keypad->stopped))
181		goto out;
182
183	disable_row_irqs(keypad);
184	keypad->scan_pending = true;
185	schedule_delayed_work(&keypad->work,
186		msecs_to_jiffies(keypad->pdata->debounce_ms));
187
188out:
189	spin_unlock_irqrestore(&keypad->lock, flags);
190	return IRQ_HANDLED;
191}
192
193static int matrix_keypad_start(struct input_dev *dev)
194{
195	struct matrix_keypad *keypad = input_get_drvdata(dev);
196
197	keypad->stopped = false;
198	mb();
199
200	/*
201	 * Schedule an immediate key scan to capture current key state;
202	 * columns will be activated and IRQs be enabled after the scan.
203	 */
204	schedule_delayed_work(&keypad->work, 0);
205
206	return 0;
207}
208
209static void matrix_keypad_stop(struct input_dev *dev)
210{
211	struct matrix_keypad *keypad = input_get_drvdata(dev);
212
213	spin_lock_irq(&keypad->lock);
214	keypad->stopped = true;
215	spin_unlock_irq(&keypad->lock);
216
217	flush_delayed_work(&keypad->work);
218	/*
219	 * matrix_keypad_scan() will leave IRQs enabled;
220	 * we should disable them now.
221	 */
222	disable_row_irqs(keypad);
223}
224
225static void matrix_keypad_enable_wakeup(struct matrix_keypad *keypad)
226{
227	int i;
228
229	for_each_clear_bit(i, keypad->wakeup_enabled_irqs, keypad->num_row_irqs)
230		if (enable_irq_wake(keypad->row_irqs[i]) == 0)
231			__set_bit(i, keypad->wakeup_enabled_irqs);
232}
233
234static void matrix_keypad_disable_wakeup(struct matrix_keypad *keypad)
235{
236	int i;
237
238	for_each_set_bit(i, keypad->wakeup_enabled_irqs, keypad->num_row_irqs) {
239		disable_irq_wake(keypad->row_irqs[i]);
240		__clear_bit(i, keypad->wakeup_enabled_irqs);
241	}
242}
243
244static int matrix_keypad_suspend(struct device *dev)
245{
246	struct platform_device *pdev = to_platform_device(dev);
247	struct matrix_keypad *keypad = platform_get_drvdata(pdev);
248
249	matrix_keypad_stop(keypad->input_dev);
250
251	if (device_may_wakeup(&pdev->dev))
252		matrix_keypad_enable_wakeup(keypad);
253
254	return 0;
255}
256
257static int matrix_keypad_resume(struct device *dev)
258{
259	struct platform_device *pdev = to_platform_device(dev);
260	struct matrix_keypad *keypad = platform_get_drvdata(pdev);
261
262	if (device_may_wakeup(&pdev->dev))
263		matrix_keypad_disable_wakeup(keypad);
264
265	matrix_keypad_start(keypad->input_dev);
266
267	return 0;
268}
269
270static DEFINE_SIMPLE_DEV_PM_OPS(matrix_keypad_pm_ops,
271				matrix_keypad_suspend, matrix_keypad_resume);
272
273static int matrix_keypad_init_gpio(struct platform_device *pdev,
274				   struct matrix_keypad *keypad)
275{
276	const struct matrix_keypad_platform_data *pdata = keypad->pdata;
277	int i, irq, err;
278
279	/* initialized strobe lines as outputs, activated */
280	for (i = 0; i < pdata->num_col_gpios; i++) {
281		err = devm_gpio_request(&pdev->dev,
282					pdata->col_gpios[i], "matrix_kbd_col");
283		if (err) {
284			dev_err(&pdev->dev,
285				"failed to request GPIO%d for COL%d\n",
286				pdata->col_gpios[i], i);
287			return err;
288		}
289
290		gpio_direction_output(pdata->col_gpios[i], !pdata->active_low);
291	}
292
293	for (i = 0; i < pdata->num_row_gpios; i++) {
294		err = devm_gpio_request(&pdev->dev,
295					pdata->row_gpios[i], "matrix_kbd_row");
296		if (err) {
297			dev_err(&pdev->dev,
298				"failed to request GPIO%d for ROW%d\n",
299				pdata->row_gpios[i], i);
300			return err;
301		}
302
303		gpio_direction_input(pdata->row_gpios[i]);
304	}
305
306	if (pdata->clustered_irq > 0) {
307		err = devm_request_any_context_irq(&pdev->dev,
308				pdata->clustered_irq,
309				matrix_keypad_interrupt,
310				pdata->clustered_irq_flags,
311				"matrix-keypad", keypad);
312		if (err < 0) {
313			dev_err(&pdev->dev,
314				"Unable to acquire clustered interrupt\n");
315			return err;
316		}
317
318		keypad->row_irqs[0] = pdata->clustered_irq;
319		keypad->num_row_irqs = 1;
320	} else {
321		for (i = 0; i < pdata->num_row_gpios; i++) {
322			irq = gpio_to_irq(pdata->row_gpios[i]);
323			if (irq < 0) {
324				err = irq;
325				dev_err(&pdev->dev,
326					"Unable to convert GPIO line %i to irq: %d\n",
327					pdata->row_gpios[i], err);
328				return err;
329			}
330
331			err = devm_request_any_context_irq(&pdev->dev,
332					irq,
333					matrix_keypad_interrupt,
334					IRQF_TRIGGER_RISING |
335						IRQF_TRIGGER_FALLING,
336					"matrix-keypad", keypad);
337			if (err < 0) {
338				dev_err(&pdev->dev,
339					"Unable to acquire interrupt for GPIO line %i\n",
340					pdata->row_gpios[i]);
341				return err;
342			}
343
344			keypad->row_irqs[i] = irq;
345		}
346
347		keypad->num_row_irqs = pdata->num_row_gpios;
348	}
349
350	/* initialized as disabled - enabled by input->open */
351	disable_row_irqs(keypad);
352
353	return 0;
354}
355
356#ifdef CONFIG_OF
357static struct matrix_keypad_platform_data *
358matrix_keypad_parse_dt(struct device *dev)
359{
360	struct matrix_keypad_platform_data *pdata;
361	struct device_node *np = dev->of_node;
362	unsigned int *gpios;
363	int ret, i, nrow, ncol;
364
365	if (!np) {
366		dev_err(dev, "device lacks DT data\n");
367		return ERR_PTR(-ENODEV);
368	}
369
370	pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
371	if (!pdata) {
372		dev_err(dev, "could not allocate memory for platform data\n");
373		return ERR_PTR(-ENOMEM);
374	}
375
376	pdata->num_row_gpios = nrow = gpiod_count(dev, "row");
377	pdata->num_col_gpios = ncol = gpiod_count(dev, "col");
378	if (nrow < 0 || ncol < 0) {
379		dev_err(dev, "number of keypad rows/columns not specified\n");
380		return ERR_PTR(-EINVAL);
381	}
382
383	pdata->no_autorepeat = of_property_read_bool(np, "linux,no-autorepeat");
384
385	pdata->wakeup = of_property_read_bool(np, "wakeup-source") ||
386			of_property_read_bool(np, "linux,wakeup"); /* legacy */
387
388	pdata->active_low = of_property_read_bool(np, "gpio-activelow");
389
390	pdata->drive_inactive_cols =
391		of_property_read_bool(np, "drive-inactive-cols");
392
393	of_property_read_u32(np, "debounce-delay-ms", &pdata->debounce_ms);
394	of_property_read_u32(np, "col-scan-delay-us",
395						&pdata->col_scan_delay_us);
396
397	gpios = devm_kcalloc(dev,
398			     pdata->num_row_gpios + pdata->num_col_gpios,
399			     sizeof(unsigned int),
400			     GFP_KERNEL);
401	if (!gpios) {
402		dev_err(dev, "could not allocate memory for gpios\n");
403		return ERR_PTR(-ENOMEM);
404	}
405
406	for (i = 0; i < nrow; i++) {
407		ret = of_get_named_gpio(np, "row-gpios", i);
408		if (ret < 0)
409			return ERR_PTR(ret);
410		gpios[i] = ret;
411	}
412
413	for (i = 0; i < ncol; i++) {
414		ret = of_get_named_gpio(np, "col-gpios", i);
415		if (ret < 0)
416			return ERR_PTR(ret);
417		gpios[nrow + i] = ret;
418	}
419
420	pdata->row_gpios = gpios;
421	pdata->col_gpios = &gpios[pdata->num_row_gpios];
422
423	return pdata;
424}
425#else
426static inline struct matrix_keypad_platform_data *
427matrix_keypad_parse_dt(struct device *dev)
428{
429	dev_err(dev, "no platform data defined\n");
430
431	return ERR_PTR(-EINVAL);
432}
433#endif
434
435static int matrix_keypad_probe(struct platform_device *pdev)
436{
437	const struct matrix_keypad_platform_data *pdata;
438	struct matrix_keypad *keypad;
439	struct input_dev *input_dev;
440	int err;
441
442	pdata = dev_get_platdata(&pdev->dev);
443	if (!pdata) {
444		pdata = matrix_keypad_parse_dt(&pdev->dev);
445		if (IS_ERR(pdata))
446			return PTR_ERR(pdata);
447	} else if (!pdata->keymap_data) {
448		dev_err(&pdev->dev, "no keymap data defined\n");
449		return -EINVAL;
450	}
451
452	keypad = devm_kzalloc(&pdev->dev, sizeof(*keypad), GFP_KERNEL);
453	if (!keypad)
454		return -ENOMEM;
455
456	input_dev = devm_input_allocate_device(&pdev->dev);
457	if (!input_dev)
458		return -ENOMEM;
459
460	keypad->input_dev = input_dev;
461	keypad->pdata = pdata;
462	keypad->row_shift = get_count_order(pdata->num_col_gpios);
463	keypad->stopped = true;
464	INIT_DELAYED_WORK(&keypad->work, matrix_keypad_scan);
465	spin_lock_init(&keypad->lock);
466
467	input_dev->name		= pdev->name;
468	input_dev->id.bustype	= BUS_HOST;
469	input_dev->open		= matrix_keypad_start;
470	input_dev->close	= matrix_keypad_stop;
471
472	err = matrix_keypad_build_keymap(pdata->keymap_data, NULL,
473					 pdata->num_row_gpios,
474					 pdata->num_col_gpios,
475					 NULL, input_dev);
476	if (err) {
477		dev_err(&pdev->dev, "failed to build keymap\n");
478		return -ENOMEM;
479	}
480
481	if (!pdata->no_autorepeat)
482		__set_bit(EV_REP, input_dev->evbit);
483	input_set_capability(input_dev, EV_MSC, MSC_SCAN);
484	input_set_drvdata(input_dev, keypad);
485
486	err = matrix_keypad_init_gpio(pdev, keypad);
487	if (err)
488		return err;
489
490	err = input_register_device(keypad->input_dev);
491	if (err)
492		return err;
493
494	device_init_wakeup(&pdev->dev, pdata->wakeup);
495	platform_set_drvdata(pdev, keypad);
496
497	return 0;
498}
499
500#ifdef CONFIG_OF
501static const struct of_device_id matrix_keypad_dt_match[] = {
502	{ .compatible = "gpio-matrix-keypad" },
503	{ }
504};
505MODULE_DEVICE_TABLE(of, matrix_keypad_dt_match);
506#endif
507
508static struct platform_driver matrix_keypad_driver = {
509	.probe		= matrix_keypad_probe,
510	.driver		= {
511		.name	= "matrix-keypad",
512		.pm	= pm_sleep_ptr(&matrix_keypad_pm_ops),
513		.of_match_table = of_match_ptr(matrix_keypad_dt_match),
514	},
515};
516module_platform_driver(matrix_keypad_driver);
517
518MODULE_AUTHOR("Marek Vasut <marek.vasut@gmail.com>");
519MODULE_DESCRIPTION("GPIO Driven Matrix Keypad Driver");
520MODULE_LICENSE("GPL v2");
521MODULE_ALIAS("platform:matrix-keypad");
522