/* * QEMU System Emulator header * * Copyright (c) 2003 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef VL_H #define VL_H /* we put basic includes here to avoid repeating them in device drivers */ #include #include #include #include #include #include #include #include #include #include #include #include #ifndef O_LARGEFILE #define O_LARGEFILE 0 #endif #ifndef O_BINARY #define O_BINARY 0 #endif #ifdef _WIN32 #define lseek _lseeki64 #define ENOTSUP 4096 /* XXX: find 64 bit version */ #define ftruncate chsize static inline char *realpath(const char *path, char *resolved_path) { _fullpath(resolved_path, path, _MAX_PATH); return resolved_path; } #endif #ifdef QEMU_TOOL /* we use QEMU_TOOL in the command line tools which do not depend on the target CPU type */ #include "config-host.h" #include #include "osdep.h" #include "bswap.h" #else #include "cpu.h" #endif /* !defined(QEMU_TOOL) */ #ifndef glue #define xglue(x, y) x ## y #define glue(x, y) xglue(x, y) #define stringify(s) tostring(s) #define tostring(s) #s #endif /* vl.c */ uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c); void hw_error(const char *fmt, ...); int get_image_size(const char *filename); int load_image(const char *filename, uint8_t *addr); extern const char *bios_dir; void pstrcpy(char *buf, int buf_size, const char *str); char *pstrcat(char *buf, int buf_size, const char *s); int strstart(const char *str, const char *val, const char **ptr); extern int vm_running; typedef void VMStopHandler(void *opaque, int reason); int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque); void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque); void vm_start(void); void vm_stop(int reason); typedef void QEMUResetHandler(void *opaque); void qemu_register_reset(QEMUResetHandler *func, void *opaque); void qemu_system_reset_request(void); void qemu_system_shutdown_request(void); void main_loop_wait(int timeout); extern int audio_enabled; extern int sb16_enabled; extern int adlib_enabled; extern int gus_enabled; extern int ram_size; extern int bios_size; extern int rtc_utc; extern int cirrus_vga_enabled; extern int graphic_width; extern int graphic_height; extern int graphic_depth; /* XXX: make it dynamic */ #if defined (TARGET_PPC) #define BIOS_SIZE (512 * 1024) #else #define BIOS_SIZE ((256 + 64) * 1024) #endif /* keyboard/mouse support */ #define MOUSE_EVENT_LBUTTON 0x01 #define MOUSE_EVENT_RBUTTON 0x02 #define MOUSE_EVENT_MBUTTON 0x04 typedef void QEMUPutKBDEvent(void *opaque, int keycode); typedef void QEMUPutMouseEvent(void *opaque, int dx, int dy, int dz, int buttons_state); void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque); void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque); void kbd_put_keycode(int keycode); void kbd_mouse_event(int dx, int dy, int dz, int buttons_state); /* keysym is a unicode code except for special keys (see QEMU_KEY_xxx constants) */ #define QEMU_KEY_ESC1(c) ((c) | 0xe100) #define QEMU_KEY_BACKSPACE 0x007f #define QEMU_KEY_UP QEMU_KEY_ESC1('A') #define QEMU_KEY_DOWN QEMU_KEY_ESC1('B') #define QEMU_KEY_RIGHT QEMU_KEY_ESC1('C') #define QEMU_KEY_LEFT QEMU_KEY_ESC1('D') #define QEMU_KEY_HOME QEMU_KEY_ESC1(1) #define QEMU_KEY_END QEMU_KEY_ESC1(4) #define QEMU_KEY_PAGEUP QEMU_KEY_ESC1(5) #define QEMU_KEY_PAGEDOWN QEMU_KEY_ESC1(6) #define QEMU_KEY_DELETE QEMU_KEY_ESC1(3) #define QEMU_KEY_CTRL_UP 0xe400 #define QEMU_KEY_CTRL_DOWN 0xe401 #define QEMU_KEY_CTRL_LEFT 0xe402 #define QEMU_KEY_CTRL_RIGHT 0xe403 #define QEMU_KEY_CTRL_HOME 0xe404 #define QEMU_KEY_CTRL_END 0xe405 #define QEMU_KEY_CTRL_PAGEUP 0xe406 #define QEMU_KEY_CTRL_PAGEDOWN 0xe407 void kbd_put_keysym(int keysym); /* async I/O support */ typedef void IOReadHandler(void *opaque, const uint8_t *buf, int size); typedef int IOCanRWHandler(void *opaque); int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, IOReadHandler *fd_read, void *opaque); void qemu_del_fd_read_handler(int fd); /* character device */ #define CHR_EVENT_BREAK 0 /* serial break char */ #define CHR_EVENT_FOCUS 1 /* focus to this terminal (modal input needed) */ typedef void IOEventHandler(void *opaque, int event); typedef struct CharDriverState { int (*chr_write)(struct CharDriverState *s, const uint8_t *buf, int len); void (*chr_add_read_handler)(struct CharDriverState *s, IOCanRWHandler *fd_can_read, IOReadHandler *fd_read, void *opaque); IOEventHandler *chr_event; void (*chr_send_event)(struct CharDriverState *chr, int event); void *opaque; } CharDriverState; void qemu_chr_printf(CharDriverState *s, const char *fmt, ...); int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len); void qemu_chr_send_event(CharDriverState *s, int event); void qemu_chr_add_read_handler(CharDriverState *s, IOCanRWHandler *fd_can_read, IOReadHandler *fd_read, void *opaque); void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event); /* consoles */ typedef struct DisplayState DisplayState; typedef struct TextConsole TextConsole; extern TextConsole *vga_console; TextConsole *graphic_console_init(DisplayState *ds); int is_active_console(TextConsole *s); CharDriverState *text_console_init(DisplayState *ds); void console_select(unsigned int index); /* serial ports */ #define MAX_SERIAL_PORTS 4 extern CharDriverState *serial_hds[MAX_SERIAL_PORTS]; /* network redirectors support */ #define MAX_NICS 8 typedef struct NetDriverState { int index; /* index number in QEMU */ uint8_t macaddr[6]; char ifname[16]; void (*send_packet)(struct NetDriverState *nd, const uint8_t *buf, int size); void (*add_read_packet)(struct NetDriverState *nd, IOCanRWHandler *fd_can_read, IOReadHandler *fd_read, void *opaque); /* tun specific data */ int fd; /* slirp specific data */ } NetDriverState; extern int nb_nics; extern NetDriverState nd_table[MAX_NICS]; void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size); void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, IOReadHandler *fd_read, void *opaque); /* timers */ typedef struct QEMUClock QEMUClock; typedef struct QEMUTimer QEMUTimer; typedef void QEMUTimerCB(void *opaque); /* The real time clock should be used only for stuff which does not change the virtual machine state, as it is run even if the virtual machine is stopped. The real time clock has a frequency of 1000 Hz. */ extern QEMUClock *rt_clock; /* Rge virtual clock is only run during the emulation. It is stopped when the virtual machine is stopped. Virtual timers use a high precision clock, usually cpu cycles (use ticks_per_sec). */ extern QEMUClock *vm_clock; int64_t qemu_get_clock(QEMUClock *clock); QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque); void qemu_free_timer(QEMUTimer *ts); void qemu_del_timer(QEMUTimer *ts); void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time); int qemu_timer_pending(QEMUTimer *ts); extern int64_t ticks_per_sec; extern int pit_min_timer_count; void cpu_enable_ticks(void); void cpu_disable_ticks(void); /* VM Load/Save */ typedef FILE QEMUFile; void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size); void qemu_put_byte(QEMUFile *f, int v); void qemu_put_be16(QEMUFile *f, unsigned int v); void qemu_put_be32(QEMUFile *f, unsigned int v); void qemu_put_be64(QEMUFile *f, uint64_t v); int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size); int qemu_get_byte(QEMUFile *f); unsigned int qemu_get_be16(QEMUFile *f); unsigned int qemu_get_be32(QEMUFile *f); uint64_t qemu_get_be64(QEMUFile *f); static inline void qemu_put_be64s(QEMUFile *f, const uint64_t *pv) { qemu_put_be64(f, *pv); } static inline void qemu_put_be32s(QEMUFile *f, const uint32_t *pv) { qemu_put_be32(f, *pv); } static inline void qemu_put_be16s(QEMUFile *f, const uint16_t *pv) { qemu_put_be16(f, *pv); } static inline void qemu_put_8s(QEMUFile *f, const uint8_t *pv) { qemu_put_byte(f, *pv); } static inline void qemu_get_be64s(QEMUFile *f, uint64_t *pv) { *pv = qemu_get_be64(f); } static inline void qemu_get_be32s(QEMUFile *f, uint32_t *pv) { *pv = qemu_get_be32(f); } static inline void qemu_get_be16s(QEMUFile *f, uint16_t *pv) { *pv = qemu_get_be16(f); } static inline void qemu_get_8s(QEMUFile *f, uint8_t *pv) { *pv = qemu_get_byte(f); } int64_t qemu_ftell(QEMUFile *f); int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence); typedef void SaveStateHandler(QEMUFile *f, void *opaque); typedef int LoadStateHandler(QEMUFile *f, void *opaque, int version_id); int qemu_loadvm(const char *filename); int qemu_savevm(const char *filename); int register_savevm(const char *idstr, int instance_id, int version_id, SaveStateHandler *save_state, LoadStateHandler *load_state, void *opaque); void qemu_get_timer(QEMUFile *f, QEMUTimer *ts); void qemu_put_timer(QEMUFile *f, QEMUTimer *ts); /* block.c */ typedef struct BlockDriverState BlockDriverState; typedef struct BlockDriver BlockDriver; extern BlockDriver bdrv_raw; extern BlockDriver bdrv_cow; extern BlockDriver bdrv_qcow; extern BlockDriver bdrv_vmdk; extern BlockDriver bdrv_cloop; void bdrv_init(void); BlockDriver *bdrv_find_format(const char *format_name); int bdrv_create(BlockDriver *dr
# Debugging FAQ

This page details various common questions people have about troubleshooting their keyboards.

# Debug Console

## `hid_listen` Can't Recognize Device
When debug console of your device is not ready you will see like this:

```
Waiting for device:.........
```

once the device is plugged in then *hid_listen* finds it you will get this message:

```
Waiting for new device:.........................
Listening:
```

If you can't get this 'Listening:' message try building with `CONSOLE_ENABLE=yes` in [Makefile]

You may need privilege to access the device on OS like Linux.
- try `sudo hid_listen`

## Can't Get Message on Console
Check:
- *hid_listen* finds your device. See above.
- Enable debug with pressing **Magic**+d. See [Magic Commands](https://github.com/tmk/tmk_keyboard#magic-commands).
- set `debug_enable=true` usually in `matrix_init()` in **matrix.c**.
- try using 'print' function instead of debug print. See **common/print.h**.
- disconnect other devices with console function. See [Issue #97](https://github.com/tmk/tmk_keyboard/issues/97).

## Linux or UNIX Like System Requires Super User Privilege
Just use 'sudo' to execute *hid_listen* with privilege.
```
$ sudo hid_listen
```

Or add an *udev rule* for TMK devices with placing a file in rules directory. The directory may vary on each system.

File: /etc/udev/rules.d/52-tmk-keyboard.rules(in case of Ubuntu)
```
# tmk keyboard products     https://github.com/tmk/tmk_keyboard
SUBSYSTEMS=="usb", ATTRS{idVendor}=="feed", MODE:="0666"
```

***

# Miscellaneous
## Safety Considerations

You probably don't want to "brick" your keyboard, making it impossible
to rewrite firmware onto it.  Here are some of the parameters to show
what things are (and likely aren't) too risky.

- If your keyboard map does not include RESET, then, to get into DFU
  mode, you will need to press the reset button on the PCB, which
  requires unscrewing the bottom.
- Messing with tmk_core / common files might make the keyboard
  inoperable
- Too large a .hex file is trouble; `make dfu` will erase the block,
  test the size (oops, wrong order!), which errors out, failing to
  flash the keyboard, leaving it in DFU mode.
  - To this end, note that the maximum .hex file size on Planck is
    7000h (28672 decimal)

```
Linking: .build/planck_rev4_cbbrowne.elf                                                            [OK]
Creating load file for Flash: .build/planck_rev4_cbbrowne.hex                                       [OK]

Size after:
   text    data     bss     dec     hex filename
      0   22396       0   22396    577c planck_rev4_cbbrowne.hex
```

  - The above file is of size 22396/577ch, which is less than
    28672/7000h
  - As long as you have a suitable alternative .hex file around, you
    can retry, loading that one
  - Some of the options you might specify in your keyboard's Makefile
    consume extra memory; watch out for BOOTMAGIC_ENABLE,
    MOUSEKEY_ENABLE, EXTRAKEY_ENABLE, CONSOLE_ENABLE, API_SYSEX_ENABLE
- DFU tools do /not/ allow you to write into the bootloader (unless
  you throw in extra fruit salad of options), so there is little risk
  there.
- EEPROM has around a 100000 write cycle.  You shouldn't rewrite the
  firmware repeatedly and continually; that'll burn the EEPROM
  eventually.
## NKRO Doesn't work
First you have to compile firmware with this build option `NKRO_ENABLE` in **Makefile**.

Try `Magic` **N** command(`LShift+RShift+N` by default) when **NKRO** still doesn't work. You can use this command to toggle between **NKRO** and **6KRO** mode temporarily. In some situations **NKRO** doesn't work you need to switch to **6KRO** mode, in particular when you are in BIOS.

If your firmware built with `BOOTMAGIC_ENABLE` you need to turn its switch on by `BootMagic` **N** command(`Space+N` by default). This setting is stored in EEPROM and kept over power cycles.

https://github.com/tmk/tmk_keyboard#boot-magic-configuration---virtual-dip-switch


## TrackPoint Needs Reset Circuit (PS/2 Mouse Support)
Without reset circuit you will have inconsistent result due to improper initialize of the hardware. See circuit schematic of TPM754.

- http://geekhack.org/index.php?topic=50176.msg1127447#msg1127447
- http://www.mikrocontroller.net/attachment/52583/tpm754.pdf


## Can't Read Column of Matrix Beyond 16
Use `1UL<<16` instead of `1<<16` in `read_cols()` in [matrix.h] when your columns goes beyond 16.

In C `1` means one of [int] type which is [16 bit] in case of AVR so you can't shift left more than 15. You will get unexpected zero when you say `1<<16`. You have to use [unsigned long] type with `1UL`.

http://deskthority.net/workshop-f7/rebuilding-and-redesigning-a-classic-thinkpad-keyboard-t6181-60.html#p146279


## Bootloader Jump Doesn't Work
Properly configure bootloader size in **Makefile**. With wrong section size bootloader won't probably start with **Magic command** and **Boot Magic**.
```
# Size of Bootloaders in bytes:
#   Atmel DFU loader(ATmega32U4)   4096
#   Atmel DFU loader(AT90USB128)   8192
#   LUFA bootloader(ATmega32U4)    4096
#   Arduino Caterina(ATmega32U4)   4096
#   USBaspLoader(ATmega***)        2048
#   Teensy   halfKay(ATmega32U4)   512
#   Teensy++ halfKay(AT90USB128)   2048
OPT_DEFS += -DBOOTLOADER_SIZE=4096
```
AVR Boot section size are defined by setting **BOOTSZ** fuse in fact. Consult with your MCU datasheet.
Note that **Word**(2 bytes) size and address are used in datasheet while TMK uses **Byte**.

AVR Boot section is located at end of Flash memory like the followings.
```
byte     Atmel/LUFA(ATMega32u4)          byte     Atmel(AT90SUB1286)
0x0000   +---------------+               0x00000  +---------------+
         |               |                        |               |
         |               |                        |               |
         |  Application  |                        |  Application  |
         |               |                        |               |
         =               =                        =               =
         |               | 32KB-4KB               |               | 128KB-8KB
0x6000   +---------------+               0x1E000  +---------------+
         |  Bootloader   | 4KB                    |  Bootloader   | 8KB
0x7FFF   +---------------+               0x1FFFF  +---------------+


byte     Teensy(ATMega32u4)              byte     Teensy++(AT90SUB1286)
0x0000   +---------------+               0x00000  +---------------+
         |               |                        |               |
         |               |                        |               |
         |  Application  |                        |  Application  |
         |               |                        |               |
         =               =                        =               =
         |               | 32KB-512B              |               | 128KB-2KB
0x7E00   +---------------+               0x1FC00  +---------------+
         |  Bootloader   | 512B                   |  Bootloader   | 2KB
0x7FFF   +---------------+               0x1FFFF  +---------------+
```

And see this discussion for further reference.
https://github.com/tmk/tmk_keyboard/issues/179

If you are using a TeensyUSB, there is a [known bug](https://github.com/qmk/qmk_firmware/issues/164) in which the hardware reset button prevents the RESET key from working. Unplugging the keyboard and plugging it back in should resolve the problem.

## Special Extra Key Doesn't Work (System, Audio Control Keys)
You need to define `EXTRAKEY_ENABLE` in `rules.mk` to use them in QMK.

```
EXTRAKEY_ENABLE = yes          # Audio control and System control
```

## Wakeup from Sleep Doesn't Work

In Windows check `Allow this device to wake the computer` setting in Power **Management property** tab of **Device Manager**. Also check BIOS setting.

Pressing any key during sleep should wake host.

## Using Arduino?

**Note that Arduino pin naming is different from actual chip.** For example, Arduino pin `D0` is not `PD0`. Check circuit with its schematics yourself.

- http://arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf
- http://arduino.cc/en/uploads/Main/arduino-micro-schematic.pdf

Arduino Leonardo and micro have **ATMega32U4** and can be used for TMK, though Arduino bootloader may be a problem.


## Using PF4-7 Pins of USB AVR?
You need to set JTD bit of MCUCR yourself to use PF4-7 as GPIO. Those pins are configured to serve JTAG function by default. MCUs like ATMega*U* or AT90USB* are affected with this.

If you are using Teensy this isn't needed. Teensy is shipped with JTAGEN fuse bit unprogrammed to disable the function.

See this code.
```
    // JTAG disable for PORT F. write JTD bit twice within four cycles.
    MCUCR |= (1<<JTD);
    MCUCR |= (1<<JTD);
```
https://github.com/tmk/tmk_keyboard/blob/master/keyboard/hbkb/matrix.c#L67

And read **26.5.1 MCU Control Register – MCUCR** of ATMega32U4 datasheet.


## Adding LED Indicators of Lock Keys
You need your own LED indicators for CapsLock, ScrollLock and NumLock? See this post.

http://deskthority.net/workshop-f7/tmk-keyboard-firmware-collection-t4478-120.html#p191560

## Program Arduino Micro/Leonardo
Push reset button and then run command like this within 8 seconds.

```
avrdude -patmega32u4 -cavr109 -b57600 -Uflash:w:adb_usb.hex -P/dev/ttyACM0
```

Device name will vary depending on your system.

http://arduino.cc/en/Main/ArduinoBoardMicro
https://geekhack.org/index.php?topic=14290.msg1563867#msg1563867


## USB 3 Compatibility
I heard some people have a problem with USB 3 port, try USB 2 port.


## Mac Compatibility
### OS X 10.11 and Hub
https://geekhack.org/index.php?topic=14290.msg1884034#msg1884034


## Problem on BIOS (UEFI)/Resume (Sleep & Wake)/Power Cycles
Some people reported their keyboard stops working on BIOS and/or after resume(power cycles).

As of now root of its cause is not clear but some build options seem to be related. In Makefile try to disable those options like `CONSOLE_ENABLE`, `NKRO_ENABLE`, `SLEEP_LED_ENABLE` and/or others.

https://github.com/tmk/tmk_keyboard/issues/266
https://geekhack.org/index.php?topic=41989.msg1967778#msg1967778



## FLIP Doesn't Work
### `AtLibUsbDfu.dll` Not Found
Remove current driver and reinstall one FLIP provides from DeviceManager.
http://imgur.com/a/bnwzy