xref: /linux/drivers/input/serio/libps2.c (revision ffd01c3bcc1af4d8c3e7949152af0d9fe3d1fda5)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * PS/2 driver library
4  *
5  * Copyright (c) 1999-2002 Vojtech Pavlik
6  * Copyright (c) 2004 Dmitry Torokhov
7  */
8 
9 
10 #include <linux/delay.h>
11 #include <linux/export.h>
12 #include <linux/module.h>
13 #include <linux/sched.h>
14 #include <linux/interrupt.h>
15 #include <linux/input.h>
16 #include <linux/kmsan-checks.h>
17 #include <linux/serio.h>
18 #include <linux/i8042.h>
19 #include <linux/libps2.h>
20 
21 #define DRIVER_DESC	"PS/2 driver library"
22 
23 #define PS2_CMD_SETSCALE11	0x00e6
24 #define PS2_CMD_SETRES		0x10e8
25 #define PS2_CMD_EX_SETLEDS	0x20eb
26 #define PS2_CMD_SETLEDS		0x10ed
27 #define PS2_CMD_GETID		0x02f2
28 #define PS2_CMD_SETREP		0x10f3 /* Set repeat rate/set report rate */
29 #define PS2_CMD_RESET_BAT	0x02ff
30 
31 #define PS2_RET_BAT		0xaa
32 #define PS2_RET_ID		0x00
33 #define PS2_RET_ACK		0xfa
34 #define PS2_RET_NAK		0xfe
35 #define PS2_RET_ERR		0xfc
36 
37 #define PS2_FLAG_ACK		BIT(0)	/* Waiting for ACK/NAK */
38 #define PS2_FLAG_CMD		BIT(1)	/* Waiting for a command to finish */
39 #define PS2_FLAG_CMD1		BIT(2)	/* Waiting for the first byte of command response */
40 #define PS2_FLAG_WAITID		BIT(3)	/* Command executing is GET ID */
41 #define PS2_FLAG_NAK		BIT(4)	/* Last transmission was NAKed */
42 #define PS2_FLAG_PASS_NOACK	BIT(5)	/* Pass non-ACK byte to receive handler */
43 
44 static int ps2_do_sendbyte(struct ps2dev *ps2dev, u8 byte,
45 			   unsigned int timeout, unsigned int max_attempts)
46 	__releases(&ps2dev->serio->lock) __acquires(&ps2dev->serio->lock)
47 {
48 	int attempt = 0;
49 	int error;
50 
51 	lockdep_assert_held(&ps2dev->serio->lock);
52 
53 	do {
54 		ps2dev->nak = 1;
55 		ps2dev->flags |= PS2_FLAG_ACK;
56 
57 		serio_continue_rx(ps2dev->serio);
58 
59 		error = serio_write(ps2dev->serio, byte);
60 		if (error)
61 			dev_dbg(&ps2dev->serio->dev,
62 				"failed to write %#02x: %d\n", byte, error);
63 		else
64 			wait_event_timeout(ps2dev->wait,
65 					   !(ps2dev->flags & PS2_FLAG_ACK),
66 					   msecs_to_jiffies(timeout));
67 
68 		serio_pause_rx(ps2dev->serio);
69 	} while (ps2dev->nak == PS2_RET_NAK && ++attempt < max_attempts);
70 
71 	ps2dev->flags &= ~PS2_FLAG_ACK;
72 
73 	if (!error) {
74 		switch (ps2dev->nak) {
75 		case 0:
76 			break;
77 		case PS2_RET_NAK:
78 			error = -EAGAIN;
79 			break;
80 		case PS2_RET_ERR:
81 			error = -EPROTO;
82 			break;
83 		default:
84 			error = -EIO;
85 			break;
86 		}
87 	}
88 
89 	if (error || attempt > 1)
90 		dev_dbg(&ps2dev->serio->dev,
91 			"%02x - %d (%x), attempt %d\n",
92 			byte, error, ps2dev->nak, attempt);
93 
94 	return error;
95 }
96 
97 /**
98  * ps2_sendbyte - sends a byte to the device and wait for acknowledgement
99  * @ps2dev: a PS/2 device to send the data to
100  * @byte: data to be sent to the device
101  * @timeout: timeout for sending the data and receiving an acknowledge
102  *
103  * The function doesn't handle retransmission, the caller is expected to handle
104  * it when needed.
105  *
106  * ps2_sendbyte() can only be called from a process context.
107  */
108 int ps2_sendbyte(struct ps2dev *ps2dev, u8 byte, unsigned int timeout)
109 {
110 	int retval;
111 
112 	guard(serio_pause_rx)(ps2dev->serio);
113 
114 	retval = ps2_do_sendbyte(ps2dev, byte, timeout, 1);
115 	dev_dbg(&ps2dev->serio->dev, "%02x - %x\n", byte, ps2dev->nak);
116 
117 	return retval;
118 }
119 EXPORT_SYMBOL(ps2_sendbyte);
120 
121 /**
122  * ps2_begin_command - mark beginning of execution of a complex command
123  * @ps2dev: a PS/2 device executing the command
124  *
125  * Serializes a complex/compound command. Once command is finished
126  * ps2_end_command() should be called.
127  */
128 void ps2_begin_command(struct ps2dev *ps2dev)
129 {
130 	struct mutex *m = ps2dev->serio->ps2_cmd_mutex ?: &ps2dev->cmd_mutex;
131 
132 	mutex_lock(m);
133 }
134 EXPORT_SYMBOL(ps2_begin_command);
135 
136 /**
137  * ps2_end_command - mark end of execution of a complex command
138  * @ps2dev: a PS/2 device executing the command
139  */
140 void ps2_end_command(struct ps2dev *ps2dev)
141 {
142 	struct mutex *m = ps2dev->serio->ps2_cmd_mutex ?: &ps2dev->cmd_mutex;
143 
144 	mutex_unlock(m);
145 }
146 EXPORT_SYMBOL(ps2_end_command);
147 
148 /**
149  * ps2_drain - waits for device to transmit requested number of bytes
150  * and discards them
151  * @ps2dev: the PS/2 device that should be drained
152  * @maxbytes: maximum number of bytes to be drained
153  * @timeout: time to drain the device
154  */
155 void ps2_drain(struct ps2dev *ps2dev, size_t maxbytes, unsigned int timeout)
156 {
157 	if (WARN_ON(maxbytes > sizeof(ps2dev->cmdbuf)))
158 		maxbytes = sizeof(ps2dev->cmdbuf);
159 
160 	ps2_begin_command(ps2dev);
161 
162 	scoped_guard(serio_pause_rx, ps2dev->serio) {
163 		ps2dev->flags = PS2_FLAG_CMD;
164 		ps2dev->cmdcnt = maxbytes;
165 	}
166 
167 	wait_event_timeout(ps2dev->wait,
168 			   !(ps2dev->flags & PS2_FLAG_CMD),
169 			   msecs_to_jiffies(timeout));
170 
171 	ps2_end_command(ps2dev);
172 }
173 EXPORT_SYMBOL(ps2_drain);
174 
175 /**
176  * ps2_is_keyboard_id - checks received ID byte against the list of
177  *   known keyboard IDs
178  * @id_byte: data byte that should be checked
179  */
180 bool ps2_is_keyboard_id(u8 id_byte)
181 {
182 	static const u8 keyboard_ids[] = {
183 		0xab,	/* Regular keyboards		*/
184 		0xac,	/* NCD Sun keyboard		*/
185 		0x2b,	/* Trust keyboard, translated	*/
186 		0x5d,	/* Trust keyboard		*/
187 		0x60,	/* NMB SGI keyboard, translated */
188 		0x47,	/* NMB SGI keyboard		*/
189 	};
190 
191 	return memchr(keyboard_ids, id_byte, sizeof(keyboard_ids)) != NULL;
192 }
193 EXPORT_SYMBOL(ps2_is_keyboard_id);
194 
195 /*
196  * ps2_adjust_timeout() is called after receiving 1st byte of command
197  * response and tries to reduce remaining timeout to speed up command
198  * completion.
199  */
200 static int ps2_adjust_timeout(struct ps2dev *ps2dev,
201 			      unsigned int command, unsigned int timeout)
202 {
203 	switch (command) {
204 	case PS2_CMD_RESET_BAT:
205 		/*
206 		 * Device has sent the first response byte after
207 		 * reset command, reset is thus done, so we can
208 		 * shorten the timeout.
209 		 * The next byte will come soon (keyboard) or not
210 		 * at all (mouse).
211 		 */
212 		if (timeout > msecs_to_jiffies(100))
213 			timeout = msecs_to_jiffies(100);
214 		break;
215 
216 	case PS2_CMD_GETID:
217 		/*
218 		 * Microsoft Natural Elite keyboard responds to
219 		 * the GET ID command as it were a mouse, with
220 		 * a single byte. Fail the command so atkbd will
221 		 * use alternative probe to detect it.
222 		 */
223 		if (ps2dev->cmdbuf[1] == 0xaa) {
224 			scoped_guard(serio_pause_rx, ps2dev->serio)
225 				ps2dev->flags = 0;
226 
227 			timeout = 0;
228 		}
229 
230 		/*
231 		 * If device behind the port is not a keyboard there
232 		 * won't be 2nd byte of ID response.
233 		 */
234 		if (!ps2_is_keyboard_id(ps2dev->cmdbuf[1])) {
235 			scoped_guard(serio_pause_rx, ps2dev->serio)
236 				ps2dev->flags = ps2dev->cmdcnt = 0;
237 
238 			timeout = 0;
239 		}
240 		break;
241 
242 	default:
243 		break;
244 	}
245 
246 	return timeout;
247 }
248 
249 /**
250  * __ps2_command - send a command to PS/2 device
251  * @ps2dev: the PS/2 device that should execute the command
252  * @param: a buffer containing parameters to be sent along with the command,
253  *   or place where the results of the command execution will be deposited,
254  *   or both
255  * @command: command word that encodes the command itself, as well as number of
256  *   additional parameter bytes that should be sent to the device and expected
257  *   length of the command response
258  *
259  * Not serialized. Callers should use ps2_begin_command() and ps2_end_command()
260  * to ensure proper serialization for complex commands.
261  */
262 int __ps2_command(struct ps2dev *ps2dev, u8 *param, unsigned int command)
263 {
264 	unsigned int timeout;
265 	unsigned int send = (command >> 12) & 0xf;
266 	unsigned int receive = (command >> 8) & 0xf;
267 	int rc;
268 	int i;
269 	u8 send_param[16];
270 
271 	if (WARN_ON(receive > sizeof(ps2dev->cmdbuf)))
272 		return -EINVAL;
273 
274 	if (WARN_ON(send && !param))
275 		return -EINVAL;
276 
277 	memcpy(send_param, param, send);
278 
279 	/*
280 	 * Not using guard notation because we need to break critical
281 	 * section below while waiting for the response.
282 	 */
283 	serio_pause_rx(ps2dev->serio);
284 
285 	ps2dev->cmdcnt = receive;
286 
287 	switch (command) {
288 	case PS2_CMD_GETID:
289 		/*
290 		 * Some mice do not ACK the "get ID" command, prepare to
291 		 * handle this.
292 		 */
293 		ps2dev->flags = PS2_FLAG_WAITID;
294 		break;
295 
296 	case PS2_CMD_SETLEDS:
297 	case PS2_CMD_EX_SETLEDS:
298 	case PS2_CMD_SETREP:
299 		ps2dev->flags = PS2_FLAG_PASS_NOACK;
300 		break;
301 
302 	default:
303 		ps2dev->flags = 0;
304 		break;
305 	}
306 
307 	if (receive) {
308 		/* Indicate that we expect response to the command. */
309 		ps2dev->flags |= PS2_FLAG_CMD | PS2_FLAG_CMD1;
310 		if (param)
311 			for (i = 0; i < receive; i++)
312 				ps2dev->cmdbuf[(receive - 1) - i] = param[i];
313 	}
314 
315 	/*
316 	 * Some devices (Synaptics) perform the reset before
317 	 * ACKing the reset command, and so it can take a long
318 	 * time before the ACK arrives.
319 	 */
320 	timeout = command == PS2_CMD_RESET_BAT ? 1000 : 200;
321 
322 	rc = ps2_do_sendbyte(ps2dev, command & 0xff, timeout, 2);
323 	if (rc)
324 		goto out_reset_flags;
325 
326 	/* Send command parameters, if any. */
327 	for (i = 0; i < send; i++) {
328 		rc = ps2_do_sendbyte(ps2dev, param[i], 200, 2);
329 		if (rc)
330 			goto out_reset_flags;
331 	}
332 
333 	serio_continue_rx(ps2dev->serio);
334 
335 	/*
336 	 * The reset command takes a long time to execute.
337 	 */
338 	timeout = msecs_to_jiffies(command == PS2_CMD_RESET_BAT ? 4000 : 500);
339 
340 	timeout = wait_event_timeout(ps2dev->wait,
341 				     !(ps2dev->flags & PS2_FLAG_CMD1), timeout);
342 
343 	if (ps2dev->cmdcnt && !(ps2dev->flags & PS2_FLAG_CMD1)) {
344 
345 		timeout = ps2_adjust_timeout(ps2dev, command, timeout);
346 		wait_event_timeout(ps2dev->wait,
347 				   !(ps2dev->flags & PS2_FLAG_CMD), timeout);
348 	}
349 
350 	serio_pause_rx(ps2dev->serio);
351 
352 	if (param) {
353 		for (i = 0; i < receive; i++)
354 			param[i] = ps2dev->cmdbuf[(receive - 1) - i];
355 		kmsan_unpoison_memory(param, receive);
356 	}
357 
358 	if (ps2dev->cmdcnt &&
359 	    (command != PS2_CMD_RESET_BAT || ps2dev->cmdcnt != 1)) {
360 		rc = -EPROTO;
361 		goto out_reset_flags;
362 	}
363 
364 	rc = 0;
365 
366  out_reset_flags:
367 	ps2dev->flags = 0;
368 	serio_continue_rx(ps2dev->serio);
369 
370 	dev_dbg(&ps2dev->serio->dev,
371 		"%02x [%*ph] - %x/%08lx [%*ph]\n",
372 		command & 0xff, send, send_param,
373 		ps2dev->nak, ps2dev->flags,
374 		receive, param ?: send_param);
375 
376 	/*
377 	 * ps_command() handles resends itself, so do not leak -EAGAIN
378 	 * to the callers.
379 	 */
380 	return rc != -EAGAIN ? rc : -EPROTO;
381 }
382 EXPORT_SYMBOL(__ps2_command);
383 
384 /**
385  * ps2_command - send a command to PS/2 device
386  * @ps2dev: the PS/2 device that should execute the command
387  * @param: a buffer containing parameters to be sent along with the command,
388  *   or place where the results of the command execution will be deposited,
389  *   or both
390  * @command: command word that encodes the command itself, as well as number of
391  *   additional parameter bytes that should be sent to the device and expected
392  *   length of the command response
393  *
394  * Note: ps2_command() serializes the command execution so that only one
395  * command can be executed at a time for either individual port or the entire
396  * 8042 controller.
397  */
398 int ps2_command(struct ps2dev *ps2dev, u8 *param, unsigned int command)
399 {
400 	int rc;
401 
402 	ps2_begin_command(ps2dev);
403 	rc = __ps2_command(ps2dev, param, command);
404 	ps2_end_command(ps2dev);
405 
406 	return rc;
407 }
408 EXPORT_SYMBOL(ps2_command);
409 
410 /**
411  * ps2_sliced_command - sends an extended PS/2 command to a mouse
412  * @ps2dev: the PS/2 device that should execute the command
413  * @command: command byte
414  *
415  * The command is sent using "sliced" syntax understood by advanced devices,
416  * such as Logitech or Synaptics touchpads. The command is encoded as:
417  * 0xE6 0xE8 rr 0xE8 ss 0xE8 tt 0xE8 uu where (rr*64)+(ss*16)+(tt*4)+uu
418  * is the command.
419  */
420 int ps2_sliced_command(struct ps2dev *ps2dev, u8 command)
421 {
422 	int i;
423 	int retval;
424 
425 	ps2_begin_command(ps2dev);
426 
427 	retval = __ps2_command(ps2dev, NULL, PS2_CMD_SETSCALE11);
428 	if (retval)
429 		goto out;
430 
431 	for (i = 6; i >= 0; i -= 2) {
432 		u8 d = (command >> i) & 3;
433 		retval = __ps2_command(ps2dev, &d, PS2_CMD_SETRES);
434 		if (retval)
435 			break;
436 	}
437 
438 out:
439 	dev_dbg(&ps2dev->serio->dev, "%02x - %d\n", command, retval);
440 	ps2_end_command(ps2dev);
441 	return retval;
442 }
443 EXPORT_SYMBOL(ps2_sliced_command);
444 
445 /**
446  * ps2_init - initializes ps2dev structure
447  * @ps2dev: structure to be initialized
448  * @serio: serio port associated with the PS/2 device
449  * @pre_receive_handler: validation handler to check basic communication state
450  * @receive_handler: main protocol handler
451  *
452  * Prepares ps2dev structure for use in drivers for PS/2 devices.
453  */
454 void ps2_init(struct ps2dev *ps2dev, struct serio *serio,
455 	      ps2_pre_receive_handler_t pre_receive_handler,
456 	      ps2_receive_handler_t receive_handler)
457 {
458 	ps2dev->pre_receive_handler = pre_receive_handler;
459 	ps2dev->receive_handler = receive_handler;
460 
461 	mutex_init(&ps2dev->cmd_mutex);
462 	lockdep_set_subclass(&ps2dev->cmd_mutex, serio->depth);
463 	init_waitqueue_head(&ps2dev->wait);
464 	ps2dev->serio = serio;
465 	serio_set_drvdata(serio, ps2dev);
466 }
467 EXPORT_SYMBOL(ps2_init);
468 
469 /*
470  * ps2_handle_response() stores device's response to a command and notifies
471  * the process waiting for completion of the command. Note that there is a
472  * distinction between waiting for the first byte of the response, and
473  * waiting for subsequent bytes. It is done so that callers could shorten
474  * timeouts once first byte of response is received.
475  */
476 static void ps2_handle_response(struct ps2dev *ps2dev, u8 data)
477 {
478 	if (ps2dev->cmdcnt)
479 		ps2dev->cmdbuf[--ps2dev->cmdcnt] = data;
480 
481 	if (ps2dev->flags & PS2_FLAG_CMD1) {
482 		ps2dev->flags &= ~PS2_FLAG_CMD1;
483 		if (ps2dev->cmdcnt)
484 			wake_up(&ps2dev->wait);
485 	}
486 
487 	if (!ps2dev->cmdcnt) {
488 		ps2dev->flags &= ~PS2_FLAG_CMD;
489 		wake_up(&ps2dev->wait);
490 	}
491 }
492 
493 /*
494  * ps2_handle_ack() processes ACK/NAK of a command from a PS/2 device,
495  * possibly applying workarounds for mice not acknowledging the "get ID"
496  * command.
497  */
498 static void ps2_handle_ack(struct ps2dev *ps2dev, u8 data)
499 {
500 	switch (data) {
501 	case PS2_RET_ACK:
502 		ps2dev->nak = 0;
503 		break;
504 
505 	case PS2_RET_NAK:
506 		ps2dev->flags |= PS2_FLAG_NAK;
507 		ps2dev->nak = PS2_RET_NAK;
508 		break;
509 
510 	case PS2_RET_ERR:
511 		if (ps2dev->flags & PS2_FLAG_NAK) {
512 			ps2dev->flags &= ~PS2_FLAG_NAK;
513 			ps2dev->nak = PS2_RET_ERR;
514 			break;
515 		}
516 		fallthrough;
517 
518 	/*
519 	 * Workaround for mice which don't ACK the Get ID command.
520 	 * These are valid mouse IDs that we recognize.
521 	 */
522 	case 0x00:
523 	case 0x03:
524 	case 0x04:
525 		if (ps2dev->flags & PS2_FLAG_WAITID) {
526 			ps2dev->nak = 0;
527 			break;
528 		}
529 		fallthrough;
530 	default:
531 		/*
532 		 * Do not signal errors if we get unexpected reply while
533 		 * waiting for an ACK to the initial (first) command byte:
534 		 * the device might not be quiesced yet and continue
535 		 * delivering data. For certain commands (such as set leds and
536 		 * set repeat rate) that can be used during normal device
537 		 * operation, we even pass this data byte to the normal receive
538 		 * handler.
539 		 * Note that we reset PS2_FLAG_WAITID flag, so the workaround
540 		 * for mice not acknowledging the Get ID command only triggers
541 		 * on the 1st byte; if device spews data we really want to see
542 		 * a real ACK from it.
543 		 */
544 		dev_dbg(&ps2dev->serio->dev, "unexpected %#02x\n", data);
545 		if (ps2dev->flags & PS2_FLAG_PASS_NOACK)
546 			ps2dev->receive_handler(ps2dev, data);
547 		ps2dev->flags &= ~(PS2_FLAG_WAITID | PS2_FLAG_PASS_NOACK);
548 		return;
549 	}
550 
551 	if (!ps2dev->nak)
552 		ps2dev->flags &= ~PS2_FLAG_NAK;
553 
554 	ps2dev->flags &= ~PS2_FLAG_ACK;
555 
556 	if (!ps2dev->nak && data != PS2_RET_ACK)
557 		ps2_handle_response(ps2dev, data);
558 	else
559 		wake_up(&ps2dev->wait);
560 }
561 
562 /*
563  * Clears state of PS/2 device after communication error by resetting majority
564  * of flags and waking up waiters, if any.
565  */
566 static void ps2_cleanup(struct ps2dev *ps2dev)
567 {
568 	unsigned long old_flags = ps2dev->flags;
569 
570 	/* reset all flags except last nak */
571 	ps2dev->flags &= PS2_FLAG_NAK;
572 
573 	if (old_flags & PS2_FLAG_ACK)
574 		ps2dev->nak = 1;
575 
576 	if (old_flags & (PS2_FLAG_ACK | PS2_FLAG_CMD))
577 		wake_up(&ps2dev->wait);
578 }
579 
580 /**
581  * ps2_interrupt - common interrupt handler for PS/2 devices
582  * @serio: serio port for the device
583  * @data: a data byte received from the device
584  * @flags: flags such as %SERIO_PARITY or %SERIO_TIMEOUT indicating state of
585  *   the data transfer
586  *
587  * ps2_interrupt() invokes pre-receive handler, optionally handles command
588  * acknowledgement and response from the device, and finally passes the data
589  * to the main protocol handler for future processing.
590  */
591 irqreturn_t ps2_interrupt(struct serio *serio, u8 data, unsigned int flags) {
592 	struct ps2dev *ps2dev = serio_get_drvdata(serio);
593 	enum ps2_disposition rc;
594 
595 	rc = ps2dev->pre_receive_handler(ps2dev, data, flags);
596 	switch (rc) {
597 	case PS2_ERROR:
598 		ps2_cleanup(ps2dev);
599 		break;
600 
601 	case PS2_IGNORE:
602 		break;
603 
604 	case PS2_PROCESS:
605 		if (ps2dev->flags & PS2_FLAG_ACK)
606 			ps2_handle_ack(ps2dev, data);
607 		else if (ps2dev->flags & PS2_FLAG_CMD)
608 			ps2_handle_response(ps2dev, data);
609 		else
610 			ps2dev->receive_handler(ps2dev, data);
611 		break;
612 	}
613 
614 	return IRQ_HANDLED;
615 }
616 EXPORT_SYMBOL(ps2_interrupt);
617 
618 MODULE_AUTHOR("Dmitry Torokhov <dtor@mail.ru>");
619 MODULE_DESCRIPTION("PS/2 driver library");
620 MODULE_LICENSE("GPL");
621