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