fix dependency check logic cause config always disabled
[lunaix-os.git] / lunaix-os / arch / x86 / hal / ps2kbd.c
1 #include <lunaix/clock.h>
2 #include <lunaix/ds/mutex.h>
3 #include <lunaix/input.h>
4 #include <lunaix/keyboard.h>
5 #include <lunaix/syslog.h>
6 #include <lunaix/timer.h>
7 #include <lunaix/hart_state.h>
8
9 #include <hal/irq.h>
10
11 #include "asm/x86.h"
12
13 #include <klibc/string.h>
14
15 #include "asm/x86_cpu.h"
16 #include <asm/x86_pmio.h>
17
18 #define PS2_PORT_ENC_DATA 0x60
19 #define PS2_PORT_ENC_CMDREG 0x60
20 #define PS2_PORT_CTRL_STATUS 0x64
21 #define PS2_PORT_CTRL_CMDREG 0x64
22
23 #define PS2_STATUS_OFULL 0x1
24 #define PS2_STATUS_IFULL 0x2
25
26 #define PS2_RESULT_ACK 0xfa
27 #define PS2_RESULT_NAK 0xfe // resend
28 #define PS2_RESULT_ECHO 0xee
29 #define PS2_RESULT_TEST_OK 0x55
30
31 // PS/2 keyboard device related commands
32 #define PS2_KBD_CMD_SETLED 0xed
33 #define PS2_KBD_CMD_ECHO 0xee
34 #define PS2_KBD_CMD_SCANCODE_SET 0xf0
35 #define PS2_KBD_CMD_IDENTIFY 0xf2
36 #define PS2_KBD_CMD_SCAN_ENABLE 0xf4
37 #define PS2_KBD_CMD_SCAN_DISABLE 0xf5
38
39 // PS/2 *controller* related commands
40 #define PS2_CMD_PORT1_DISABLE 0xad
41 #define PS2_CMD_PORT1_ENABLE 0xae
42 #define PS2_CMD_PORT2_DISABLE 0xa7
43 #define PS2_CMD_PORT2_ENABLE 0xa8
44 #define PS2_CMD_SELFTEST 0xaa
45 #define PS2_CMD_SELFTEST_PORT1 0xab
46
47 #define PS2_CMD_READ_CFG 0x20
48 #define PS2_CMD_WRITE_CFG 0x60
49
50 #define PS2_CFG_P1INT 0x1
51 #define PS2_CFG_P2INT 0x2
52 #define PS2_CFG_TRANSLATION 0x40
53
54 #define PS2_DELAY 1000
55
56 #define PS2_CMD_QUEUE_SIZE 8
57
58 #define PS2_NO_ARG 0xff00
59
60 #define PC_AT_IRQ_KBD                   1
61
62 struct ps2_cmd
63 {
64     char cmd;
65     char arg;
66 };
67
68 struct ps2_kbd_state
69 {
70     volatile char state;
71     volatile char masked;
72     volatile kbd_kstate_t key_state;
73     kbd_keycode_t* translation_table;
74 };
75
76 struct ps2_cmd_queue
77 {
78     struct ps2_cmd cmd_queue[PS2_CMD_QUEUE_SIZE];
79     int queue_ptr;
80     int queue_len;
81     mutex_t mutex;
82 };
83
84 /**
85  * @brief 向PS/2控制器的控制端口(0x64)发送指令并等待返回代码。
86  * 注意,对于没有返回代码的命令请使用`ps2_post_cmd`,否则会造成死锁。
87  * 通过调用该方法向控制器发送指令,请区别 ps2_issue_dev_cmd
88  *
89  * @param cmd
90  * @param args
91  */
92 static u8_t
93 ps2_issue_cmd(char cmd, u16_t arg);
94
95 /**
96  * @brief 向PS/2控制器的编码器端口(0x60)发送指令并等待返回代码。
97  * 注意,对于没有返回代码的命令请使用`ps2_post_cmd`,否则会造成死锁。
98  * 通过调用该方法向PS/2设备发送指令,请区别 ps2_issue_cmd
99  *
100  * @param cmd
101  * @param args
102  */
103 static u8_t
104 ps2_issue_dev_cmd(char cmd, u16_t arg);
105
106 /**
107  * @brief 向PS/2控制器发送指令,不等待返回代码。
108  *
109  * @param port 端口号
110  * @param cmd
111  * @param args
112  * @return char
113  */
114 static void
115 ps2_post_cmd(u8_t port, char cmd, u16_t arg);
116
117 static void
118 ps2_device_post_cmd(char cmd, char arg);
119
120 static void
121 ps2_process_cmd(void* arg);
122
123 #define PS2_DEV_CMD_MAX_ATTEMPTS 5
124
125 LOG_MODULE("i8042");
126
127 static struct ps2_cmd_queue cmd_q;
128 static struct ps2_kbd_state kbd_state;
129
130 #define KEY_NUM(x) (x + 0x30)
131 #define KEY_NPAD(x) ON_KEYPAD(KEY_NUM(x))
132
133 // 我们使用 Scancode Set 2
134
135 // clang-format off
136
137 // 大部分的扫描码(键码)
138 static kbd_keycode_t scancode_set2[] = {
139     0, KEY_F9, 0, KEY_F5, KEY_F3, KEY_F1, KEY_F2, KEY_F12, 0, KEY_F10, KEY_F8, KEY_F6,
140     KEY_F4, KEY_HTAB, '`', 0, 0, KEY_LALT, KEY_LSHIFT, 0, KEY_LCTRL, 'q', KEY_NUM(1), 
141     0, 0, 0, 'z', 's', 'a', 'w', KEY_NUM(2), 0, 0, 'c', 'x', 'd', 'e', KEY_NUM(4), KEY_NUM(3), 
142     0, 0, KEY_SPACE, 'v', 'f', 't', 'r', KEY_NUM(5),
143     0, 0, 'n', 'b', 'h', 'g', 'y', KEY_NUM(6), 0, 0, 0, 'm', 'j', 'u', KEY_NUM(7), KEY_NUM(8),
144     0, 0, ',', 'k', 'i', 'o', KEY_NUM(0), KEY_NUM(9), 0, 0, '.', '/', 'l', ';', 'p', '-', 0, 0,
145     0, '\'', 0, '[', '=', 0, 0, KEY_CAPSLK, KEY_RSHIFT, KEY_LF, ']', 0, '\\', 0, 0, 0, 0, 0, 0, 0,
146     0, KEY_BS, 0, 0, KEY_NPAD(1), 0, KEY_NPAD(4), KEY_NPAD(7), 0, 0, 0, KEY_NPAD(0), ON_KEYPAD('.'),
147     KEY_NPAD(2), KEY_NPAD(5), KEY_NPAD(6), KEY_NPAD(8), KEY_ESC, KEY_NUMSLK, KEY_F11, ON_KEYPAD('+'),
148     KEY_NPAD(3), ON_KEYPAD('-'), ON_KEYPAD('*'), KEY_NPAD(9), KEY_SCRLLK, 0, 0, 0, 0, KEY_F7
149 };
150
151 // 一些特殊的键码(以 0xe0 位前缀的)
152 static kbd_keycode_t scancode_set2_ex[] = {
153     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_RALT, 0, 0,
154     KEY_RCTRL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
155     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
156     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ON_KEYPAD('/'), 0, 0, 0, 0, 0, 0, 0, 0, 
157     0, 0, 0, 0, 0, 0, 0, ON_KEYPAD(KEY_LF), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158     KEY_END, 0, KEY_LEFT, KEY_HOME,
159     0, 0, 0, KEY_INSERT, KEY_DELETE, KEY_DOWN, 0, KEY_RIGHT, KEY_UP, 0, 0,
160     0, 0, KEY_PG_DOWN, 0, 0, KEY_PG_UP
161 };
162
163 // 用于处理 Shift+<key> 的情况
164 static kbd_keycode_t scancode_set2_shift[] = {
165     0, KEY_F9, 0, KEY_F5, KEY_F3, KEY_F1, KEY_F2, KEY_F12, 0, KEY_F10, KEY_F8, KEY_F6,
166     KEY_F4, KEY_HTAB, '~', 0, 0, KEY_LALT, KEY_LSHIFT, 0, KEY_LCTRL, 'Q', '!', 
167     0, 0, 0, 'Z', 'S', 'A', 'W', '@', 0, 0, 'C', 'X', 'D', 'E', '$', '#', 
168     0, 0, KEY_SPACE, 'V', 'F', 'T', 'R', '%',
169     0, 0, 'N', 'B', 'H', 'G', 'Y', '^', 0, 0, 0, 'M', 'J', 'U', '&', '*',
170     0, 0, '<', 'K', 'I', 'O', ')', '(', 0, 0, '>', '?', 'L', ':', 'P', '_', 0, 0,
171     0, '"', 0, '{', '+', 0, 0, KEY_CAPSLK, KEY_RSHIFT, KEY_LF, '}', 0, '|', 0, 0, 0, 0, 0, 0, 0,
172     0, KEY_BS, 0, 0, KEY_NPAD(1), 0, KEY_NPAD(4), KEY_NPAD(7), 0, 0, 0, KEY_NPAD(0), ON_KEYPAD('.'),
173     KEY_NPAD(2), KEY_NPAD(5), KEY_NPAD(6), KEY_NPAD(8), KEY_ESC, KEY_NUMSLK, KEY_F11, ON_KEYPAD('+'),
174     KEY_NPAD(3), ON_KEYPAD('-'), ON_KEYPAD('*'), KEY_SCRLLK, 0, 0, 0, 0, KEY_F7
175 };
176
177 // clang-format on
178
179 static struct input_device* kbd_idev;
180
181 #define KBD_STATE_KWAIT 0x00
182 #define KBD_STATE_KSPECIAL 0x01
183 #define KBD_STATE_KRELEASED 0x02
184 #define KBD_STATE_E012 0x03
185 #define KBD_STATE_KRELEASED_E0 0x04
186 #define KBD_STATE_CMDPROCS 0x40
187
188 // #define KBD_ENABLE_SPIRQ_FIX
189 #define KBD_ENABLE_SPIRQ_FIX2
190 // #define KBD_DBGLOG
191
192 static void
193 intr_ps2_kbd_handler(irq_t irq, const struct hart_state* hstate);
194
195 static u8_t
196 ps2_issue_cmd_wretry(char cmd, u16_t arg);
197
198 static void
199 ps2_device_post_cmd(char cmd, char arg)
200 {
201     mutex_lock(&cmd_q.mutex);
202     int index = (cmd_q.queue_ptr + cmd_q.queue_len) % PS2_CMD_QUEUE_SIZE;
203     if (index == cmd_q.queue_ptr && cmd_q.queue_len) {
204         // 队列已满!
205         mutex_unlock(&cmd_q.mutex);
206         return;
207     }
208
209     struct ps2_cmd* container = &cmd_q.cmd_queue[index];
210     container->cmd = cmd;
211     container->arg = arg;
212     cmd_q.queue_len++;
213
214     // 释放锁,同理。
215     mutex_unlock(&cmd_q.mutex);
216 }
217
218 static int
219 ps2_kbd_create(struct device_def* devdef, morph_t* obj)
220 {
221
222     memset(&cmd_q, 0, sizeof(cmd_q));
223     memset(&kbd_state, 0, sizeof(kbd_state));
224
225     mutex_init(&cmd_q.mutex);
226
227     kbd_state.translation_table = scancode_set2;
228     kbd_state.state = KBD_STATE_KWAIT;
229
230     kbd_idev = input_add_device(&devdef->class, devdef->name);
231
232     /* FIXME This require systematical rework! */
233     // acpi_context* acpi_ctx = acpi_get_context();
234     // if (acpi_ctx->fadt.header.rev > 1) {
235     //     /*
236     //      *
237     //      只有当前ACPI版本大于1时,我们才使用FADT的IAPC_BOOT_ARCH去判断8042是否存在。
238     //      *  这是一个坑,在ACPI v1中,这个字段是reserved!而这及至ACPI
239     //      v2才出现。
240     //      *  需要注意:Bochs 和 QEMU 使用的是ACPI v1,而非 v2
241     //      * (virtualbox好像是v4)
242     //      *
243     //      *  (2022/6/29)
244     //      *
245     //      QEMU在7.0.0版本中,修复了FADT::IAPC_BOOT无法正确提供关于i8042的信息的bug
246     //      *      https://wiki.qemu.org/ChangeLog/7.0#ACPI_.2F_SMBIOS
247     //      *
248     //      *
249     //      请看Bochs的bios源码(QEMU的BIOS其实是照抄bochs的,所以也是一个德行。。):
250     //      *
251     //      https://bochs.sourceforge.io/cgi-bin/lxr/source/bios/rombios32.c#L1314
252     //      */
253     //     if (!(acpi_ctx->fadt.boot_arch & IAPC_ARCH_8042)) {
254     //         ERROR("not found\n");
255     //         // FUTURE: Some alternative fallback on this? Check PCI bus for
256     //         USB
257     //         // controller instead?
258     //         return;
259     //     }
260     // } else {
261     //     WARN("outdated FADT used, assuming exists.\n");
262     // }
263
264     char result;
265
266     // 1、禁用任何的PS/2设备
267     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, PS2_CMD_PORT1_DISABLE, PS2_NO_ARG);
268     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, PS2_CMD_PORT2_DISABLE, PS2_NO_ARG);
269
270     // 2、清空控制器缓冲区
271     port_rdbyte(PS2_PORT_ENC_DATA);
272
273     // 3、屏蔽所有PS/2设备(端口1&2)IRQ,并且禁用键盘键码转换功能
274     result = ps2_issue_cmd(PS2_CMD_READ_CFG, PS2_NO_ARG);
275     result = result & ~(PS2_CFG_P1INT | PS2_CFG_P2INT);
276     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, PS2_CMD_WRITE_CFG, result);
277
278     // 4、控制器自检
279     result = ps2_issue_cmd_wretry(PS2_CMD_SELFTEST, PS2_NO_ARG);
280     if (result != PS2_RESULT_TEST_OK) {
281         WARN("controller self-test failed. (%x)", result);
282         goto done;
283     }
284
285     // 5、设备自检(端口1自检,通常是我们的键盘)
286     result = ps2_issue_cmd_wretry(PS2_CMD_SELFTEST_PORT1, PS2_NO_ARG);
287     if (result != 0) {
288         ERROR("interface test on port 1 failed. (%x)", result);
289         goto done;
290     }
291
292     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, PS2_CMD_PORT2_DISABLE, PS2_NO_ARG);
293
294     // 6、开启位于端口1的 IRQ,并启用端口1。不用理会端口2,那儿一般是鼠标。
295     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, PS2_CMD_PORT1_ENABLE, PS2_NO_ARG);
296     result = ps2_issue_cmd(PS2_CMD_READ_CFG, PS2_NO_ARG);
297     // 重新设置配置字节,因为控制器自检有可能重置我们先前做的改动。
298     result = (result | PS2_CFG_P1INT) & ~(PS2_CFG_TRANSLATION | PS2_CFG_P2INT);
299     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, PS2_CMD_WRITE_CFG, result);
300
301     // 至此,PS/2控制器和设备已完成初始化,可以正常使用。
302
303     /*
304      *   一切准备就绪后,我们才教ioapic去启用IRQ#1。
305      *   至于为什么要在这里,原因是:初始化所使用的一些指令可能会导致IRQ#1的触发(因为返回码),或者是一些什么
306      *  情况导致IRQ#1的误触发(可能是未初始化导致IRQ#1线上不稳定)。于是这些IRQ#1会堆积在APIC的队列里(因为此时我们正在
307      *  初始化8042,屏蔽了所有中断,IF=0)。
308      *  当sti后,这些堆积的中断会紧跟着递送进CPU里,导致我们的键盘handler误认为由按键按下,从而将这个毫无意义的数值加入
309      *  我们的队列中,以供上层读取。
310      *
311      *  所以,保险的方法是:在初始化后才去设置ioapic,这样一来我们就能有一个稳定的IRQ#1以放心使用。
312      */
313     
314     irq_t irq = irq_declare_line(intr_ps2_kbd_handler, PC_AT_IRQ_KBD);    
315     irq_assign(irq_owning_domain(kbd_idev->dev_if), irq, NULL);
316
317     return 0;
318
319 done:
320     return 1;
321 }
322
323 static void
324 ps2_process_cmd(void* arg)
325 {
326     /*
327      * 检查锁是否已被启用,如果启用,则表明该timer中断发生时,某个指令正在入队。
328      * 如果是这种情况则跳过,留到下一轮再尝试处理。
329      * 注意,这里其实是ISR的一部分(timer中断),对于单核CPU来说,ISR等同于单个的原子操作。
330      * (因为EFLAGS.IF=0,所有可屏蔽中断被屏蔽。对于NMI的情况,那么就直接算是triple
331      * fault了,所以也没有讨论的意义)
332      * 所以,假若我们遵从互斥锁的严格定义(即这里需要阻塞),那么中断将会被阻塞,进而造成死锁。
333      * 因此,我们这里仅仅进行判断。
334      * 会不会产生指令堆积?不会,因为指令发送的频率远远低于指令队列清空的频率。在目前,我们发送的唯一指令
335      * 就只是用来开关键盘上的LED灯(如CAPSLOCK)。
336      */
337     if (mutex_on_hold(&cmd_q.mutex) || !cmd_q.queue_len) {
338         return;
339     }
340
341     // 处理队列排头的指令
342     struct ps2_cmd* pending_cmd = &cmd_q.cmd_queue[cmd_q.queue_ptr];
343     u8_t result;
344     int attempts = 0;
345
346     // 尝试将命令发送至PS/2键盘(通过PS/2控制器)
347     // 如果不成功(0x60 IO口返回 0xfe,即 NAK i.e. Resend)
348     // 则尝试最多五次
349     do {
350         result = ps2_issue_dev_cmd(pending_cmd->cmd, pending_cmd->arg);
351 #ifdef KBD_ENABLE_SPIRQ_FIX
352         kbd_state.state += KBD_STATE_CMDPROCS;
353 #endif
354         attempts++;
355     } while (result == PS2_RESULT_NAK && attempts < PS2_DEV_CMD_MAX_ATTEMPTS);
356     // XXX: 是否需要处理不成功的指令?
357
358     cmd_q.queue_ptr = (cmd_q.queue_ptr + 1) % PS2_CMD_QUEUE_SIZE;
359     cmd_q.queue_len--;
360 }
361
362 static void
363 kbd_buffer_key_event(kbd_keycode_t key, u8_t scancode, kbd_kstate_t state)
364 {
365     /*
366         forgive me on these ugly bit-level tricks,
367         I really hate doing branching on these "fliping switch" things
368     */
369     if (key == KEY_CAPSLK) {
370         kbd_state.key_state ^= KBD_KEY_FCAPSLKED & -state;
371     } else if (key == KEY_NUMSLK) {
372         kbd_state.key_state ^= KBD_KEY_FNUMBLKED & -state;
373     } else if (key == KEY_SCRLLK) {
374         kbd_state.key_state ^= KBD_KEY_FSCRLLKED & -state;
375     } else {
376         if ((key & MODIFR)) {
377             kbd_kstate_t tmp = (KBD_KEY_FLSHIFT_HELD << (key & 0x00ff));
378             kbd_state.key_state = (kbd_state.key_state & ~tmp) | (tmp & -state);
379         } else if (!(key & 0xff00) &&
380                    (kbd_state.key_state &
381                     (KBD_KEY_FLSHIFT_HELD | KBD_KEY_FRSHIFT_HELD))) {
382             key = scancode_set2_shift[scancode];
383         }
384         state = state | kbd_state.key_state;
385         key = key & (0xffdf |
386                      -('a' > key || key > 'z' || !(state & KBD_KEY_FCAPSLKED)));
387
388         struct input_evt_pkt ipkt = { .pkt_type = (state & KBD_KEY_FPRESSED)
389                                                     ? PKT_PRESS
390                                                     : PKT_RELEASE,
391                                       .scan_code = scancode,
392                                       .sys_code = (state << 16) | key };
393
394         input_fire_event(kbd_idev, &ipkt);
395
396         return;
397     }
398
399     if (state & KBD_KEY_FPRESSED) {
400         // Ooops, this guy generates irq!
401         ps2_device_post_cmd(PS2_KBD_CMD_SETLED,
402                             (kbd_state.key_state >> 1) & 0x00ff);
403     }
404 }
405
406 static void
407 intr_ps2_kbd_handler(irq_t irq, const struct hart_state* hstate)
408 {
409
410     // This is important! Don't believe me? try comment it out and run on Bochs!
411     // while (!(port_rdbyte(PS2_PORT_CTRL_STATUS) & PS2_STATUS_OFULL))
412     //    ;
413
414     // I know you are tempting to move this chunk after the keyboard state
415     // check. But DO NOT. This chunk is in right place and right order. Moving
416     // it at your own risk This is to ensure we've cleared the output buffer
417     // everytime, so it won't pile up across irqs.
418     u8_t scancode = port_rdbyte(PS2_PORT_ENC_DATA);
419     kbd_keycode_t key;
420
421     /*
422      *    判断键盘是否处在指令发送状态,防止误触发。(伪输入中断)
423      * 这是因为我们需要向ps/2设备发送指令(比如控制led灯),而指令会有返回码。
424      * 这就会有可能导致ps/2控制器在受到我们的命令后(在ps2_process_cmd中),
425      * 产生IRQ#1中断(虽然说这种情况取决于底层BIOS实现,但还是会发生,比如QEMU和bochs)。
426      * 所以这就是说,当IRQ#1中断产生时,我们的CPU正处在另一个ISR中。这样就会导致所有的外部中断被缓存在APIC内部的
427      * FIFO队列里,进行排队等待(APIC长度为二的队列 {IRR, TMR};参考 Intel
428      * Manual Vol.3A 10.8.4)
429      * 那么当ps2_process_cmd执行完后(内嵌在#APIC_TIMER_IV),CPU返回EOI给APIC,APIC紧接着将排在队里的IRQ#1发送给CPU
430      * 造成误触发。也就是说,我们此时读入的scancode实则上是上一个指令的返回代码。
431      *
432      * Problem 1 (Fixed):
433      *      但是这种方法有个问题,那就是,假若我们的某一个命令失败了一次,ps/2给出0xfe,我们重传,ps/2收到指令并给出0xfa。
434      *  那么这样一来,将会由两个连续的IRQ#1产生。而APIC是最多可以缓存两个IRQ,于是我们就会漏掉一个IRQ,依然会误触发。
435      * Solution:
436      *      累加掩码 ;)
437      *
438      * Problem 2:
439      *    +
440      * 这种累加掩码的操作是基于只有一号IRQ产生的中断的假设,万一中间夹杂了别的中断?Race
441      * Condition!
442      *    +
443      * 不很稳定x1,假如连续4次发送失败,那么就会导致累加的掩码上溢出,从而导致下述判断失败。
444      */
445 #ifdef KBD_ENABLE_SPIRQ_FIX
446     if ((kbd_state.state & 0xc0)) {
447         kbd_state.state -= KBD_STATE_CMDPROCS;
448
449         return;
450     }
451 #endif
452
453 #ifdef KBD_ENABLE_SPIRQ_FIX2
454     if (scancode == PS2_RESULT_ACK || scancode == PS2_RESULT_NAK) {
455         ps2_process_cmd(NULL);
456         return;
457     }
458 #endif
459
460 #ifdef KBD_DBGLOG
461     DEBUG("%x\n", scancode & 0xff);
462 #endif
463
464     switch (kbd_state.state) {
465         case KBD_STATE_KWAIT:
466             if (scancode == 0xf0) { // release code
467                 kbd_state.state = KBD_STATE_KRELEASED;
468             } else if (scancode == 0xe0) {
469                 kbd_state.state = KBD_STATE_KSPECIAL;
470                 kbd_state.translation_table = scancode_set2_ex;
471             } else {
472                 key = kbd_state.translation_table[scancode];
473                 kbd_buffer_key_event(key, scancode, KBD_KEY_FPRESSED);
474             }
475             break;
476         case KBD_STATE_KSPECIAL:
477             if (scancode == 0x12) {
478                 kbd_state.state = KBD_STATE_E012;
479             } else if (scancode == 0xf0) { // release code
480                 kbd_state.state = KBD_STATE_KRELEASED_E0;
481             } else {
482                 key = kbd_state.translation_table[scancode];
483                 kbd_buffer_key_event(key, scancode, KBD_KEY_FPRESSED);
484
485                 kbd_state.state = KBD_STATE_KWAIT;
486                 kbd_state.translation_table = scancode_set2;
487             }
488             break;
489         // handle the '0xE0, 0x12, 0xE0, xx' sequence
490         case KBD_STATE_E012:
491             if (scancode == 0xe0) {
492                 kbd_state.state = KBD_STATE_KSPECIAL;
493                 kbd_state.translation_table = scancode_set2_ex;
494             }
495             break;
496         case KBD_STATE_KRELEASED_E0:
497             if (scancode == 0x12) {
498                 goto escape_release;
499             }
500             // fall through
501         case KBD_STATE_KRELEASED:
502             key = kbd_state.translation_table[scancode];
503             kbd_buffer_key_event(key, scancode, KBD_KEY_FRELEASED);
504
505         escape_release:
506             // reset the translation table to scancode_set2
507             kbd_state.state = KBD_STATE_KWAIT;
508             kbd_state.translation_table = scancode_set2;
509             break;
510
511         default:
512             break;
513     }
514 }
515
516 static u8_t
517 ps2_issue_cmd(char cmd, u16_t arg)
518 {
519     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, cmd, arg);
520
521     // 等待PS/2控制器返回。通过轮询(polling)状态寄存器的 bit 0
522     // 如置位,则表明返回代码此时就在 0x60 IO口上等待读取。
523     while (!(port_rdbyte(PS2_PORT_CTRL_STATUS) & PS2_STATUS_OFULL))
524         ;
525
526     return port_rdbyte(PS2_PORT_ENC_CMDREG);
527 }
528
529 static u8_t
530 ps2_issue_cmd_wretry(char cmd, u16_t arg)
531 {
532     u8_t r, c = 0;
533     while ((r = ps2_issue_cmd(cmd, arg)) == PS2_RESULT_NAK && c < 5) {
534         c++;
535     }
536     if (c >= 5) {
537         WARN("max attempt reached.");
538     }
539     return r;
540 }
541
542 static void
543 ps2_post_cmd(u8_t port, char cmd, u16_t arg)
544 {
545     // 等待PS/2输入缓冲区清空,这样我们才可以写入命令
546     while (port_rdbyte(PS2_PORT_CTRL_STATUS) & PS2_STATUS_IFULL)
547         ;
548
549     port_wrbyte(port, cmd);
550     port_delay(PS2_DELAY);
551
552     if (!(arg & PS2_NO_ARG)) {
553         // 所有参数一律通过0x60传入。
554         while (port_rdbyte(PS2_PORT_CTRL_STATUS) & PS2_STATUS_IFULL)
555             ;
556         port_wrbyte(PS2_PORT_ENC_CMDREG, (u8_t)(arg & 0x00ff));
557         port_delay(PS2_DELAY);
558     }
559 }
560
561 static u8_t
562 ps2_issue_dev_cmd(char cmd, u16_t arg)
563 {
564     ps2_post_cmd(PS2_PORT_ENC_CMDREG, cmd, arg);
565
566     // 等待PS/2控制器返回。通过轮询(polling)状态寄存器的 bit 0
567     // 如置位,则表明返回代码此时就在 0x60 IO口上等待读取。
568     while (!(port_rdbyte(PS2_PORT_CTRL_STATUS) & PS2_STATUS_OFULL))
569         ;
570
571     return port_rdbyte(PS2_PORT_ENC_CMDREG);
572 }
573
574 static struct device_def devrtc_i8042kbd = {
575     def_device_class(INTEL, INPUT, KBD),
576     def_device_name("i8042 Keyboard"),
577     def_on_create(ps2_kbd_create)
578 };
579 EXPORT_DEVICE(i8042_kbd, &devrtc_i8042kbd, load_onboot);