]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - converter/ibmpc_usb/ibmpc_usb.c
ibmpc_usb: Update prebuilt firmware files
[max/tmk_keyboard.git] / converter / ibmpc_usb / ibmpc_usb.c
1 /*
2 Copyright 2019,2020 Jun Wako <wakojun@gmail.com>
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include <stdint.h>
19 #include <stdbool.h>
20 #include "print.h"
21 #include "util.h"
22 #include "debug.h"
23 #include "ibmpc.h"
24 #include "host.h"
25 #include "led.h"
26 #include "matrix.h"
27 #include "timer.h"
28 #include "action.h"
29 #include "ibmpc_usb.h"
30 #include "ibmpc.h"
31
32
33 static void matrix_make(uint8_t code);
34 static void matrix_break(uint8_t code);
35
36 static int8_t process_cs1(uint8_t code);
37 static int8_t process_cs2(uint8_t code);
38 static int8_t process_cs3(uint8_t code);
39
40
41 static uint8_t matrix[MATRIX_ROWS];
42 #define ROW(code)      ((code>>3)&0x0F)
43 #define COL(code)      (code&0x07)
44
45 static int16_t read_wait(uint16_t wait_ms)
46 {
47     uint16_t start = timer_read();
48     int16_t code;
49     while ((code = ibmpc_host_recv()) == -1 && timer_elapsed(start) < wait_ms);
50     return code;
51 }
52
53 static uint16_t read_keyboard_id(void)
54 {
55     uint16_t id = 0;
56     int16_t  code = 0;
57
58     // temporary fix Z-150 AT should response with ID
59     if (ibmpc_protocol == IBMPC_PROTOCOL_AT_Z150) return 0xFFFD;
60
61     // Disable
62     //code = ibmpc_host_send(0xF5);
63
64     // Read ID
65     code = ibmpc_host_send(0xF2);
66     if (code == -1) { id = 0xFFFF; goto DONE; }     // XT or No keyboard
67     if (code != 0xFA) { id = 0xFFFE; goto DONE; }   // Broken PS/2?
68
69     // ID takes 500ms max TechRef [8] 4-41
70     code = read_wait(500);
71     if (code == -1) { id = 0x0000; goto DONE; }     // AT
72     id = (code & 0xFF)<<8;
73
74     // Mouse responds with one-byte 00, this returns 00FF [y] p.14
75     code = read_wait(500);
76     id |= code & 0xFF;
77
78 DONE:
79     // Enable
80     //code = ibmpc_host_send(0xF4);
81
82     return id;
83 }
84
85 void hook_early_init(void)
86 {
87     ibmpc_host_init();
88     ibmpc_host_enable();
89 }
90
91 void matrix_init(void)
92 {
93     debug_enable = true;
94
95     // initialize matrix state: all keys off
96     for (uint8_t i=0; i < MATRIX_ROWS; i++) matrix[i] = 0x00;
97
98     return;
99 }
100
101 /*
102  * keyboard recognition
103  *
104  * 1. Send F2 to get keyboard ID
105  *      a. no ACK(FA): XT keyobard
106  *      b. ACK but no ID: 84-key AT keyboard CodeSet2
107  *      c. ID is AB 83: PS/2 keyboard CodeSet2
108  *      d. ID is BF BF: Terminal keyboard CodeSet3
109  *      e. error on recv: maybe broken PS/2
110  */
111 uint8_t current_protocol = 0;
112 uint16_t keyboard_id = 0x0000;
113 keyboard_kind_t keyboard_kind = NONE;
114 uint8_t matrix_scan(void)
115 {
116     // scan code reading states
117     static enum {
118         INIT,
119         WAIT_SETTLE,
120         AT_RESET,
121         XT_RESET,
122         XT_RESET_WAIT,
123         XT_RESET_DONE,
124         WAIT_AA,
125         WAIT_AABF,
126         WAIT_AABFBF,
127         READ_ID,
128         SETUP,
129         LOOP,
130     } state = INIT;
131     static uint16_t init_time;
132
133
134     if (ibmpc_error) {
135         xprintf("\nERR:%02X ISR:%04X ", ibmpc_error, ibmpc_isr_debug);
136
137         // when recv error, neither send error nor buffer full
138         if (!(ibmpc_error & (IBMPC_ERR_SEND | IBMPC_ERR_FULL))) {
139             // keyboard init again
140             if (state == LOOP) {
141                 xprintf("[RST] ");
142                 state = INIT;
143             }
144         }
145
146         // clear or process error
147         ibmpc_error = IBMPC_ERR_NONE;
148         ibmpc_isr_debug = 0;
149     }
150
151     // check protocol change AT/XT
152     if (ibmpc_protocol && ibmpc_protocol != current_protocol) {
153         xprintf("\nPRT:%02X ISR:%04X ", ibmpc_protocol, ibmpc_isr_debug);
154
155         // protocol change between AT and XT indicates that
156         // keyboard is hotswapped or something goes wrong.
157         // This requires initializing keyboard again probably.
158         if (((current_protocol&IBMPC_PROTOCOL_XT) && (ibmpc_protocol&IBMPC_PROTOCOL_AT)) ||
159             ((current_protocol&IBMPC_PROTOCOL_AT) && (ibmpc_protocol&IBMPC_PROTOCOL_XT))) {
160             if (state == LOOP) {
161                 xprintf("[CHG] ");
162                 state = INIT;
163             }
164         }
165
166         current_protocol = ibmpc_protocol;
167         ibmpc_isr_debug = 0;
168     }
169
170     switch (state) {
171         case INIT:
172             ibmpc_host_disable();
173
174             xprintf("I%u ", timer_read());
175             keyboard_kind = NONE;
176             keyboard_id = 0x0000;
177             current_protocol = 0;
178
179             matrix_clear();
180             clear_keyboard();
181
182             init_time = timer_read();
183             state = WAIT_SETTLE;
184             break;
185         case WAIT_SETTLE:
186             // wait for keyboard to settle after plugin
187             if (timer_elapsed(init_time) > 1000) {
188                 state = AT_RESET;
189             }
190             break;
191         case AT_RESET:
192             ibmpc_host_isr_clear();
193             ibmpc_host_enable();
194             wait_ms(1); // keyboard can't respond to command without this
195
196             // SKIDATA-2-DE(and some other keyboards?) stores 'Code Set' setting in nonvlatile memory
197             // and keeps it until receiving reset. Sending reset here may be useful to clear it, perhaps.
198             // https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#select-alternate-scan-codesf0
199
200             // reset command
201             if (0xFA == ibmpc_host_send(0xFF)) {
202                 state = WAIT_AA;
203             } else {
204                 state = XT_RESET;
205             }
206             xprintf("A%u ", timer_read());
207             break;
208         case XT_RESET:
209             // Reset XT-initialize keyboard
210             // XT: hard reset 500ms for IBM XT Type-1 keyboard and clones
211             // XT: soft reset 20ms min
212             // https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-XT-Keyboard-Protocol#keyboard-soft-reset
213             ibmpc_host_disable();   // soft reset: Clock Lo/Data Hi
214             IBMPC_RST_LO();         // hard reset: Reset pin Lo
215
216             init_time = timer_read();
217             state = XT_RESET_WAIT;
218             break;
219         case XT_RESET_WAIT:
220             if (timer_elapsed(init_time) > 500) {
221                 state = XT_RESET_DONE;
222             }
223             break;
224         case XT_RESET_DONE:
225             IBMPC_RST_HIZ();        // hard reset: Reset pin HiZ
226             ibmpc_host_isr_clear();
227             ibmpc_host_enable();    // soft reset: idle(Clock Hi/Data Hi)
228
229             xprintf("X%u ", timer_read());
230             init_time = timer_read();
231             state = WAIT_AA;
232             break;
233         case WAIT_AA:
234             // 1) Read BAT code and ID on keybaord power-up
235             // For example, XT/AT sends 'AA' and Terminal sends 'AA BF BF' after BAT
236             // AT 84-key: POR and BAT can take 900-9900ms according to AT TechRef [8] 4-7
237             // AT 101/102-key: POR and BAT can take 450-2500ms according to AT TechRef [8] 4-39
238             // 2) Read key typed by user or anything after error on protocol or scan code
239             // This can happen in case of keyboard hotswap, unstable hardware, signal integrity problem or bug
240
241             /* wait until keyboard sends any code without 10000ms timeout
242             if (timer_elapsed(init_time) > 10000) {
243                 state = READ_ID;
244             }
245             */
246             if (ibmpc_host_recv() != -1) {  // wait for AA
247                 xprintf("W%u ", timer_read());
248                 init_time = timer_read();
249                 state = WAIT_AABF;
250             }
251             break;
252         case WAIT_AABF:
253             // NOTE: we can omit to wait BF BF
254             // ID takes 500ms max? TechRef [8] 4-41, though 1ms is enough for 122-key Terminal 6110345
255             if (timer_elapsed(init_time) > 500) {
256                 state = READ_ID;
257             }
258             if (ibmpc_host_recv() != -1) {  // wait for BF
259                 xprintf("W%u ", timer_read());
260                 init_time = timer_read();
261                 state = WAIT_AABFBF;
262             }
263             break;
264         case WAIT_AABFBF:
265             if (timer_elapsed(init_time) > 500) {
266                 state = READ_ID;
267             }
268             if (ibmpc_host_recv() != -1) {  // wait for BF
269                 xprintf("W%u ", timer_read());
270                 state = READ_ID;
271             }
272             break;
273         case READ_ID:
274             keyboard_id = read_keyboard_id();
275             xprintf("R%u ", timer_read());
276
277             if (0x0000 == keyboard_id) {            // CodeSet2 AT(IBM PC AT 84-key)
278                 keyboard_kind = PC_AT;
279             } else if (0xFFFF == keyboard_id) {     // CodeSet1 XT
280                 keyboard_kind = PC_XT;
281             } else if (0xFFFE == keyboard_id) {     // CodeSet2 PS/2 fails to response?
282                 keyboard_kind = PC_AT;
283             } else if (0xFFFD == keyboard_id) {     // Zenith Z-150 AT
284                 keyboard_kind = PC_AT_Z150;
285             } else if (0x00FF == keyboard_id) {     // Mouse is not supported
286                 xprintf("Mouse: not supported\n");
287                 keyboard_kind = NONE;
288 #ifdef G80_2551_SUPPORT
289             } else if (0xAB86 == keyboard_id ||
290                        0xAB85 == keyboard_id) {     // For G80-2551 and other 122-key terminal
291                 // https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#ab86
292                 // https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#ab85
293
294                 if ((0xFA == ibmpc_host_send(0xF0)) &&
295                     (0xFA == ibmpc_host_send(0x03))) {
296                     // switch to code set 3
297                     keyboard_kind = PC_TERMINAL;
298                 } else {
299                     keyboard_kind = PC_AT;
300                 }
301 #endif
302             } else if (0xBFB0 == keyboard_id) {     // IBM RT Keyboard
303                 // https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#bfb0
304                 // TODO: LED indicator fix
305                 //keyboard_kind = PC_TERMINAL_IBM_RT;
306                 keyboard_kind = PC_TERMINAL;
307             } else if (0xAB00 == (keyboard_id & 0xFF00)) {  // CodeSet2 PS/2
308                 keyboard_kind = PC_AT;
309             } else if (0xBF00 == (keyboard_id & 0xFF00)) {  // CodeSet3 Terminal
310                 keyboard_kind = PC_TERMINAL;
311             } else {
312                 keyboard_kind = PC_AT;
313             }
314
315             xprintf("\nID:%04X(%s) ", keyboard_id, KEYBOARD_KIND_STR(keyboard_kind));
316
317             state = SETUP;
318             break;
319         case SETUP:
320             xprintf("S%u ", timer_read());
321             switch (keyboard_kind) {
322                 case PC_XT:
323                     break;
324                 case PC_AT:
325                     led_set(host_keyboard_leds());
326                     break;
327                 case PC_AT_Z150:
328                     // TODO: do not set indicators temporarily for debug
329                     break;
330                 case PC_TERMINAL:
331                     // Set all keys to make/break type
332                     ibmpc_host_send(0xF8);
333                     // This should not be harmful
334                     led_set(host_keyboard_leds());
335                     break;
336                 default:
337                     break;
338             }
339             state = LOOP;
340             xprintf("L%u ", timer_read());
341         case LOOP:
342             {
343                 uint16_t code = ibmpc_host_recv();
344                 if (code == -1) {
345                     // no code
346                     break;
347                 }
348
349                 // Keyboard Error/Overrun([3]p.26) or Buffer full
350                 // Scan Code Set 1: 0xFF
351                 // Scan Code Set 2 and 3: 0x00
352                 // Buffer full(IBMPC_ERR_FULL): 0xFF
353                 if (code == 0x00 || code == 0xFF) {
354                     // clear stuck keys
355                     matrix_clear();
356                     clear_keyboard();
357
358                     xprintf("\n[OVR] ");
359                     break;
360                 }
361
362                 switch (keyboard_kind) {
363                     case PC_XT:
364                         if (process_cs1(code) == -1) state = INIT;
365                         break;
366                     case PC_AT:
367                     case PC_AT_Z150:
368                         if (process_cs2(code) == -1) state = INIT;
369                         break;
370                     case PC_TERMINAL:
371                         if (process_cs3(code) == -1) state = INIT;
372                         break;
373                     default:
374                         break;
375                 }
376             }
377             break;
378         default:
379             break;
380     }
381     return 1;
382 }
383
384 inline
385 bool matrix_is_on(uint8_t row, uint8_t col)
386 {
387     return (matrix[row] & (1<<col));
388 }
389
390 inline
391 uint8_t matrix_get_row(uint8_t row)
392 {
393     return matrix[row];
394 }
395
396 uint8_t matrix_key_count(void)
397 {
398     uint8_t count = 0;
399     for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
400         count += bitpop(matrix[i]);
401     }
402     return count;
403 }
404
405
406 inline
407 static void matrix_make(uint8_t code)
408 {
409     if (!matrix_is_on(ROW(code), COL(code))) {
410         matrix[ROW(code)] |= 1<<COL(code);
411     }
412 }
413
414 inline
415 static void matrix_break(uint8_t code)
416 {
417     if (matrix_is_on(ROW(code), COL(code))) {
418         matrix[ROW(code)] &= ~(1<<COL(code));
419     }
420 }
421
422 void matrix_clear(void)
423 {
424     for (uint8_t i=0; i < MATRIX_ROWS; i++) matrix[i] = 0x00;
425 }
426
427 void led_set(uint8_t usb_led)
428 {
429     // Sending before keyboard recognition may be harmful for XT keyboard
430     if (keyboard_kind == NONE) return;
431
432     // XT keyobard doesn't support any command and it is harmful perhaps
433     // https://github.com/tmk/tmk_keyboard/issues/635#issuecomment-626993437
434     if (keyboard_kind == PC_XT) return;
435
436     // It should be safe to send the command to keyboards with AT protocol
437     // - IBM Terminal doesn't support the command and response with 0xFE but it is not harmful.
438     // - Some other Terminals like G80-2551 supports the command.
439     //   https://geekhack.org/index.php?topic=103648.msg2894921#msg2894921
440
441     // TODO: PC_TERMINAL_IBM_RT support
442     uint8_t ibmpc_led = 0;
443     if (usb_led &  (1<<USB_LED_SCROLL_LOCK))
444         ibmpc_led |= (1<<IBMPC_LED_SCROLL_LOCK);
445     if (usb_led &  (1<<USB_LED_NUM_LOCK))
446         ibmpc_led |= (1<<IBMPC_LED_NUM_LOCK);
447     if (usb_led &  (1<<USB_LED_CAPS_LOCK))
448         ibmpc_led |= (1<<IBMPC_LED_CAPS_LOCK);
449     ibmpc_host_set_led(ibmpc_led);
450 }
451
452
453 /*******************************************************************************
454  * XT: Scan Code Set 1
455  *
456  * See [3], [a]
457  *
458  * E0-escaped scan codes are translated into unused range of the matrix.(54-7F)
459  *
460  *     01-53: Normal codes used in original XT keyboard
461  *     54-7F: Not used in original XT keyboard
462  *
463  *         0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
464  *     50  -   -   -   -   *   *   x   x   x   x   *   *   *   *   *   *
465  *     60  *   *   *   *   x   x   x   x   x   x   x   x   x   x   x   *
466  *     70  x   *   *   x   *   *   x   *   *   x   *   x   *   x   x   *
467  *
468  * -: codes existed in original XT keyboard
469  * *: E0-escaped codes translated
470  * x: Non-espcaped codes(Some are not used in real keyboards probably)
471  *
472  * Codes assigned in range 54-7F:
473  *
474  *     50  -                60  Up*                 70  KANAx
475  *     51  -                61  Left*               71  Insert*
476  *     52  -                62  Down*               72  Delete*
477  *     53  -                63  Right*              73  ROx
478  *     54  PrintScr*        64  F13x                74  Home*
479  *     55  Pause*           65  F14x                75  End*
480  *     56  Euro2x           66  F15x                76  F24x
481  *     57  F11x             67  F16x                77  PageUp*
482  *     58  F12x             68  F17x                78  PageDown*
483  *     59  Keypad=x         69  F18x                79  HENKANx
484  *     5A  LGUI*            6A  F19x                7A  RCTL*
485  *     5B  RGUI*            6B  F20x                7B  MUHENKANx
486  *     5C  APP*             6C  F21x                7C  RALT*
487  *     5D  Mute*            6D  F22x                7D  JPYx
488  *     5E  Volume Down*     6E  F23x                7E  Keypad,x
489  *     5F  Volume Up*       6F  Keypad Enter*       7F  Keypad/ *
490  */
491 static uint8_t cs1_e0code(uint8_t code) {
492     switch(code) {
493         // Original IBM XT keyboard doesn't use E0-codes probably
494         // Some XT compatilble keyobards need these keys?
495         case 0x37: return 0x54; // Print Screen
496         case 0x46: return 0x55; // Ctrl + Pause
497         case 0x5B: return 0x5A; // Left  GUI
498         case 0x5C: return 0x5B; // Right GUI
499         case 0x5D: return 0x5C; // Application
500         case 0x20: return 0x5D; // Mute
501         case 0x2E: return 0x5E; // Volume Down
502         case 0x30: return 0x5F; // Volume Up
503         case 0x48: return 0x60; // Up
504         case 0x4B: return 0x61; // Left
505         case 0x50: return 0x62; // Down
506         case 0x4D: return 0x63; // Right
507         case 0x1C: return 0x6F; // Keypad Enter
508         case 0x52: return 0x71; // Insert
509         case 0x53: return 0x72; // Delete
510         case 0x47: return 0x74; // Home
511         case 0x4F: return 0x75; // End
512         case 0x49: return 0x77; // Page Up
513         case 0x51: return 0x78; // Page Down
514         case 0x1D: return 0x7A; // Right Ctrl
515         case 0x38: return 0x7C; // Right Alt
516         case 0x35: return 0x7F; // Keypad /
517
518         // Shared matrix cell with other keys
519         case 0x5E: return 0x70; // Power (KANA)
520         case 0x5F: return 0x79; // Sleep (HENKAN)
521         case 0x63: return 0x7B; // Wake  (MUHENKAN)
522
523         default:
524            xprintf("!CS1_E0_%02X!\n", code);
525            return code;
526     }
527     return 0x00;
528 }
529
530 static int8_t process_cs1(uint8_t code)
531 {
532     static enum {
533         INIT,
534         E0,
535         // Pause: E1 1D 45, E1 9D C5 [a]
536         E1,
537         E1_1D,
538         E1_9D,
539     } state = INIT;
540
541     switch (state) {
542         case INIT:
543             switch (code) {
544                 case 0xE0:
545                     state = E0;
546                     break;
547                 case 0xE1:
548                     state = E1;
549                     break;
550                 default:
551                     if (code < 0x80)
552                         matrix_make(code);
553                     else
554                         matrix_break(code & 0x7F);
555                     break;
556             }
557             break;
558         case E0:
559             switch (code) {
560                 case 0x2A:
561                 case 0xAA:
562                 case 0x36:
563                 case 0xB6:
564                     //ignore fake shift
565                     state = INIT;
566                     break;
567                 default:
568                     if (code < 0x80)
569                         matrix_make(cs1_e0code(code));
570                     else
571                         matrix_break(cs1_e0code(code & 0x7F));
572                     state = INIT;
573                     break;
574             }
575             break;
576         case E1:
577             switch (code) {
578                 case 0x1D:
579                     state = E1_1D;
580                     break;
581                 case 0x9D:
582                     state = E1_9D;
583                     break;
584                 default:
585                     state = INIT;
586                     break;
587             }
588             break;
589         case E1_1D:
590             switch (code) {
591                 case 0x45:
592                     matrix_make(0x55); // Pause
593                     state = INIT;
594                     break;
595                 default:
596                     state = INIT;
597                     break;
598             }
599             break;
600         case E1_9D:
601             switch (code) {
602                 case 0xC5:
603                     matrix_break(0x55); // Pause
604                     state = INIT;
605                     break;
606                 default:
607                     state = INIT;
608                     break;
609             }
610             break;
611         default:
612             state = INIT;
613     }
614     return 0;
615 }
616
617
618 /*******************************************************************************
619  * AT, PS/2: Scan Code Set 2
620  *
621  * Exceptional Handling
622  * --------------------
623  * Some keys should be handled exceptionally. See [b].
624  *
625  * Scan codes are varied or prefix/postfix'd depending on modifier key state.
626  *
627  * 1) Insert, Delete, Home, End, PageUp, PageDown, Up, Down, Right, Left
628  *     a) when Num Lock is off
629  *     modifiers | make                      | break
630  *     ----------+---------------------------+----------------------
631  *     Ohter     |                    <make> | <break>
632  *     LShift    | E0 F0 12           <make> | <break>  E0 12
633  *     RShift    | E0 F0 59           <make> | <break>  E0 59
634  *     L+RShift  | E0 F0 12  E0 F0 59 <make> | <break>  E0 59 E0 12
635  *
636  *     b) when Num Lock is on
637  *     modifiers | make                      | break
638  *     ----------+---------------------------+----------------------
639  *     Other     | E0 12              <make> | <break>  E0 F0 12
640  *     Shift'd   |                    <make> | <break>
641  *
642  *     Handling: These prefix/postfix codes are ignored.
643  *
644  *
645  * 2) Keypad /
646  *     modifiers | make                      | break
647  *     ----------+---------------------------+----------------------
648  *     Ohter     |                    <make> | <break>
649  *     LShift    | E0 F0 12           <make> | <break>  E0 12
650  *     RShift    | E0 F0 59           <make> | <break>  E0 59
651  *     L+RShift  | E0 F0 12  E0 F0 59 <make> | <break>  E0 59 E0 12
652  *
653  *     Handling: These prefix/postfix codes are ignored.
654  *
655  *
656  * 3) PrintScreen
657  *     modifiers | make         | break
658  *     ----------+--------------+-----------------------------------
659  *     Other     | E0 12  E0 7C | E0 F0 7C  E0 F0 12
660  *     Shift'd   |        E0 7C | E0 F0 7C
661  *     Control'd |        E0 7C | E0 F0 7C
662  *     Alt'd     |           84 | F0 84
663  *
664  *     Handling: These prefix/postfix codes are ignored, and both scan codes
665  *               'E0 7C' and 84 are seen as PrintScreen.
666  *
667  * 4) Pause
668  *     modifiers | make(no break code)
669  *     ----------+--------------------------------------------------
670  *     Other     | E1 14 77 E1 F0 14 F0 77
671  *     Control'd | E0 7E E0 F0 7E
672  *
673  *     Handling: Both code sequences are treated as a whole.
674  *               And we need a ad hoc 'pseudo break code' hack to get the key off
675  *               because it has no break code.
676  *
677  * Notes:
678  * 'Hanguel/English'(F1) and 'Hanja'(F2) have no break code. See [a].
679  * These two Korean keys need exceptional handling and are not supported for now.
680  *
681  */
682 static uint8_t cs2_e0code(uint8_t code) {
683     switch(code) {
684         // E0 prefixed codes translation See [a].
685         case 0x11: return 0x0F; // right alt
686         case 0x14: return 0x17; // right control
687         case 0x1F: return 0x19; // left GUI
688         case 0x27: return 0x1F; // right GUI
689         case 0x2F: return 0x5C; // apps
690         case 0x4A: return 0x60; // keypad /
691         case 0x5A: return 0x62; // keypad enter
692         case 0x69: return 0x27; // end
693         case 0x6B: return 0x53; // cursor left
694         case 0x6C: return 0x2F; // home
695         case 0x70: return 0x39; // insert
696         case 0x71: return 0x37; // delete
697         case 0x72: return 0x3F; // cursor down
698         case 0x74: return 0x47; // cursor right
699         case 0x75: return 0x4F; // cursor up
700         case 0x7A: return 0x56; // page down
701         case 0x7D: return 0x5E; // page up
702         case 0x7C: return 0x7F; // Print Screen
703         case 0x7E: return 0x00; // Control'd Pause
704
705         case 0x21: return 0x65; // volume down
706         case 0x32: return 0x6E; // volume up
707         case 0x23: return 0x6F; // mute
708         case 0x10: return 0x08; // (WWW search)     -> F13
709         case 0x18: return 0x10; // (WWW favourites) -> F14
710         case 0x20: return 0x18; // (WWW refresh)    -> F15
711         case 0x28: return 0x20; // (WWW stop)       -> F16
712         case 0x30: return 0x28; // (WWW forward)    -> F17
713         case 0x38: return 0x30; // (WWW back)       -> F18
714         case 0x3A: return 0x38; // (WWW home)       -> F19
715         case 0x40: return 0x40; // (my computer)    -> F20
716         case 0x48: return 0x48; // (email)          -> F21
717         case 0x2B: return 0x50; // (calculator)     -> F22
718         case 0x34: return 0x08; // (play/pause)     -> F13
719         case 0x3B: return 0x10; // (stop)           -> F14
720         case 0x15: return 0x18; // (previous track) -> F15
721         case 0x4D: return 0x20; // (next track)     -> F16
722         case 0x50: return 0x28; // (media select)   -> F17
723         case 0x5E: return 0x50; // (ACPI wake)      -> F22
724         case 0x3F: return 0x57; // (ACPI sleep)     -> F23
725         case 0x37: return 0x5F; // (ACPI power)     -> F24
726
727         // https://github.com/tmk/tmk_keyboard/pull/636
728         case 0x03: return 0x18; // Help        DEC LK411 -> F15
729         case 0x04: return 0x08; // F13         DEC LK411
730         case 0x0B: return 0x20; // Do          DEC LK411 -> F16
731         case 0x0C: return 0x10; // F14         DEC LK411
732         case 0x0D: return 0x19; // LCompose    DEC LK411 -> LGUI
733         case 0x79: return 0x6D; // KP-         DEC LK411 -> PCMM
734         case 0x83: return 0x28; // F17         DEC LK411
735         default: return (code & 0x7F);
736     }
737 }
738
739 static int8_t process_cs2(uint8_t code)
740 {
741     // scan code reading states
742     static enum {
743         INIT,
744         F0,
745         E0,
746         E0_F0,
747         // Pause
748         E1,
749         E1_14,
750         E1_F0,
751         E1_F0_14,
752         E1_F0_14_F0,
753     } state = INIT;
754
755     switch (state) {
756         case INIT:
757             switch (code) {
758                 case 0xE0:
759                     state = E0;
760                     break;
761                 case 0xF0:
762                     state = F0;
763                     break;
764                 case 0xE1:
765                     state = E1;
766                     break;
767                 case 0x83:  // F7
768                     matrix_make(0x02);
769                     state = INIT;
770                     break;
771                 case 0x84:  // Alt'd PrintScreen
772                     matrix_make(0x7F);
773                     state = INIT;
774                     break;
775                 case 0xAA:  // Self-test passed
776                 case 0xFC:  // Self-test failed
777                     // replug or unstable connection probably
778                 default:    // normal key make
779                     state = INIT;
780                     if (code < 0x80) {
781                         matrix_make(code);
782                     } else {
783                         matrix_clear();
784                         xprintf("!CS2_INIT!\n");
785                         return -1;
786                     }
787             }
788             break;
789         case E0:    // E0-Prefixed
790             switch (code) {
791                 case 0x12:  // to be ignored
792                 case 0x59:  // to be ignored
793                     state = INIT;
794                     break;
795                 case 0xF0:
796                     state = E0_F0;
797                     break;
798                 default:
799                     state = INIT;
800                     if (code < 0x80) {
801                         matrix_make(cs2_e0code(code));
802                     } else {
803                         matrix_clear();
804                         xprintf("!CS2_E0!\n");
805                         return -1;
806                     }
807             }
808             break;
809         case F0:    // Break code
810             switch (code) {
811                 case 0x83:  // F7
812                     matrix_break(0x02);
813                     state = INIT;
814                     break;
815                 case 0x84:  // Alt'd PrintScreen
816                     matrix_break(0x7F);
817                     state = INIT;
818                     break;
819                 default:
820                     state = INIT;
821                     if (code < 0x80) {
822                         matrix_break(code);
823                     } else {
824                         matrix_clear();
825                         xprintf("!CS2_F0!\n");
826                         return -1;
827                     }
828             }
829             break;
830         case E0_F0: // Break code of E0-prefixed
831             switch (code) {
832                 case 0x12:  // to be ignored
833                 case 0x59:  // to be ignored
834                     state = INIT;
835                     break;
836                 default:
837                     state = INIT;
838                     if (code < 0x80) {
839                         matrix_break(cs2_e0code(code));
840                     } else {
841                         matrix_clear();
842                         xprintf("!CS2_E0_F0!\n");
843                         return -1;
844                     }
845             }
846             break;
847         // Pause make: E1 14 77
848         case E1:
849             switch (code) {
850                 case 0x14:
851                     state = E1_14;
852                     break;
853                 case 0xF0:
854                     state = E1_F0;
855                     break;
856                 default:
857                     state = INIT;
858             }
859             break;
860         case E1_14:
861             switch (code) {
862                 case 0x77:
863                     matrix_make(0x00);
864                     state = INIT;
865                     break;
866                 default:
867                     state = INIT;
868             }
869             break;
870         // Pause break: E1 F0 14 F0 77
871         case E1_F0:
872             switch (code) {
873                 case 0x14:
874                     state = E1_F0_14;
875                     break;
876                 default:
877                     state = INIT;
878             }
879             break;
880         case E1_F0_14:
881             switch (code) {
882                 case 0xF0:
883                     state = E1_F0_14_F0;
884                     break;
885                 default:
886                     state = INIT;
887             }
888             break;
889         case E1_F0_14_F0:
890             switch (code) {
891                 case 0x77:
892                     matrix_break(0x00);
893                     state = INIT;
894                     break;
895                 default:
896                     state = INIT;
897             }
898             break;
899         default:
900             state = INIT;
901     }
902     return 0;
903 }
904
905 /*
906  * Terminal: Scan Code Set 3
907  *
908  * See [3], [7] and
909  * https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#scan-code-set-3
910  */
911 static int8_t process_cs3(uint8_t code)
912 {
913     static enum {
914         READY,
915         F0,
916 #ifdef G80_2551_SUPPORT
917         // G80-2551 four extra keys around cursor keys
918         G80,
919         G80_F0,
920 #endif
921     } state = READY;
922
923     switch (state) {
924         case READY:
925             switch (code) {
926                 case 0xF0:
927                     state = F0;
928                     break;
929                 case 0x83:  // PrintScreen
930                     matrix_make(0x02);
931                     break;
932                 case 0x84:  // Keypad *
933                     matrix_make(0x7F);
934                     break;
935                 case 0x85:  // Muhenkan
936                     matrix_make(0x0B);
937                     break;
938                 case 0x86:  // Henkan
939                     matrix_make(0x06);
940                     break;
941                 case 0x87:  // Hiragana
942                     matrix_make(0x00);
943                     break;
944                 case 0x8B:  // Left GUI
945                     matrix_make(0x01);
946                     break;
947                 case 0x8C:  // Right GUI
948                     matrix_make(0x09);
949                     break;
950                 case 0x8D:  // Application
951                     matrix_make(0x0A);
952                     break;
953 #ifdef G80_2551_SUPPORT
954                 case 0x80:  // G80-2551 four extra keys around cursor keys
955                     state = G80;
956                     break;
957 #endif
958                 default:    // normal key make
959                     if (code < 0x80) {
960                         matrix_make(code);
961                     } else {
962                         xprintf("!CS3_READY!\n");
963                         return -1;
964                     }
965             }
966             break;
967         case F0:    // Break code
968             switch (code) {
969                 case 0x83:  // PrintScreen
970                     matrix_break(0x02);
971                     state = READY;
972                     break;
973                 case 0x84:  // Keypad *
974                     matrix_break(0x7F);
975                     state = READY;
976                     break;
977                 case 0x85:  // Muhenkan
978                     matrix_break(0x0B);
979                     state = READY;
980                     break;
981                 case 0x86:  // Henkan
982                     matrix_break(0x06);
983                     state = READY;
984                     break;
985                 case 0x87:  // Hiragana
986                     matrix_break(0x00);
987                     state = READY;
988                     break;
989                 case 0x8B:  // Left GUI
990                     matrix_break(0x01);
991                     state = READY;
992                     break;
993                 case 0x8C:  // Right GUI
994                     matrix_break(0x09);
995                     state = READY;
996                     break;
997                 case 0x8D:  // Application
998                     matrix_break(0x0A);
999                     state = READY;
1000                     break;
1001                 default:
1002                     state = READY;
1003                     if (code < 0x80) {
1004                         matrix_break(code);
1005                     } else {
1006                         xprintf("!CS3_F0!\n");
1007                         return -1;
1008                     }
1009             }
1010             break;
1011 #ifdef G80_2551_SUPPORT
1012         /*
1013          * G80-2551 terminal keyboard support
1014          * https://deskthority.net/wiki/Cherry_G80-2551
1015          * https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#g80-2551-in-code-set-3
1016          */
1017         case G80:   // G80-2551 four extra keys around cursor keys
1018             switch (code) {
1019                 case (0x26):    // TD= -> JYEN
1020                     matrix_make(0x5D);
1021                     break;
1022                 case (0x25):    // page with edge -> NUHS
1023                     matrix_make(0x53);
1024                     break;
1025                 case (0x16):    // two pages -> RO
1026                     matrix_make(0x51);
1027                     break;
1028                 case (0x1E):    // calc -> KANA
1029                     matrix_make(0x00);
1030                     break;
1031                 case (0xF0):
1032                     state = G80_F0;
1033                     return 0;
1034                 default:
1035                     // Not supported
1036                     matrix_clear();
1037                     break;
1038             }
1039             state = READY;
1040             break;
1041         case G80_F0:
1042             switch (code) {
1043                 case (0x26):    // TD= -> JYEN
1044                     matrix_break(0x5D);
1045                     break;
1046                 case (0x25):    // page with edge -> NUHS
1047                     matrix_break(0x53);
1048                     break;
1049                 case (0x16):    // two pages -> RO
1050                     matrix_break(0x51);
1051                     break;
1052                 case (0x1E):    // calc -> KANA
1053                     matrix_break(0x00);
1054                     break;
1055                 default:
1056                     // Not supported
1057                     matrix_clear();
1058                     break;
1059             }
1060             state = READY;
1061             break;
1062 #endif
1063     }
1064     return 0;
1065 }
1066
1067 /*
1068  * IBM PC Keyboard Protocol Resources:
1069  *
1070  * [a] Microsoft USB HID to PS/2 Translation Table - Scan Code Set 1 and 2
1071  * http://download.microsoft.com/download/1/6/1/161ba512-40e2-4cc9-843a-923143f3456c/translate.pdf
1072  *
1073  * [b] Microsoft Keyboard Scan Code Specification - Special rules of Scan Code Set 1 and 2
1074  * http://download.microsoft.com/download/1/6/1/161ba512-40e2-4cc9-843a-923143f3456c/scancode.doc
1075  *
1076  * [1] PS/2 Reference Manuals - Collection of IBM Personal System/2 documents.
1077  * http://www.mcamafia.de/pdf/pdfref.htm
1078  *
1079  * [2] Keyboard and Auxiliary Device Controller - Signal Timing and Format
1080  * http://www.mcamafia.de/pdf/ibm_hitrc07.pdf
1081  *
1082  * [3] Keyboards(101- and 102-key) - Keyboard Layout, Scan Code Set, POR, and Commands.
1083  * http://www.mcamafia.de/pdf/ibm_hitrc11.pdf
1084  *
1085  * [4] IBM PC XT Keyboard Protocol
1086  * https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-XT-Keyboard-Protocol
1087  *
1088  * [5] IBM Keyboard Scan Code by John Elliott - 83-key, 84-key, 102-key and 122-key
1089  * https://www.seasip.info/VintagePC/index.html
1090  *
1091  * [6] IBM 1391406 Keyboard - Scan Code Set 2 of 102-key PS/2 keyboard
1092  * https://www.seasip.info/VintagePC/ibm_1391406.html
1093  *
1094  * [7] The IBM 6110344 Keyboard - Scan Code Set 3 of 122-key terminal keyboard
1095  * https://www.seasip.info/VintagePC/ibm_6110344.html
1096  *
1097  * [8] IBM PC AT Technical Reference 1986
1098  * http://bitsavers.org/pdf/ibm/pc/at/6183355_PC_AT_Technical_Reference_Mar86.pdf
1099  *
1100  * [y] TrackPoint Engineering Specifications for version 3E
1101  * https://web.archive.org/web/20100526161812/http://wwwcssrv.almaden.ibm.com/trackpoint/download.html
1102  *
1103  * [z] [Soarer's XT/AT/PS2/Terminal to USB converter]
1104  * https://geekhack.org/index.php?topic=17458.0
1105  *
1106  */