Home | History | Annotate | Download | only in docs
      1 Introduction
      2 ============
      3 
      4 This file documents the 'goldfish' virtual hardware platform used to run some
      5 emulated Android systems under QEMU. It serves as a reference for implementers
      6 of virtual devices in QEMU, as well as Linux kernel developers who need to
      7 maintain the corresponding drivers.
      8 
      9 The following abbreviations will be used here:
     10 
     11   $QEMU  -> path to the Android AOSP directory, i.e. a git clone of
     12             https://android.googlesource.com/platform/external/qemu.git
     13 
     14   $KERNEL -> path to the Android goldfish kernel source tree, i.e. a git clone of
     15              https://android.googlesource.com/kernel/goldfish.git
     16 
     17              More specifically, to the android-goldfish-2.6.29 branch for now.
     18 
     19 'goldfish' is the name of a family of similar virtual hardware platforms, that
     20 mostly differ in the virtual CPU they support. 'goldfish' started as an
     21 ARM-specific platform, but has now been ported to x86 and MIPS virtual CPUs.
     22 
     23 Inside of QEMU, goldfish-specific virtual device implementation sources files
     24 are in $QEMU/hw/android/goldfish/*.c sources
     25 
     26 Inside the Linux kernel tree, they are under $KERNEL/arch/$ARCH/mach-goldfish,
     27 or $KERNEL/arch/$ARCH/goldfish/, as well as a few arch-independent drivers in
     28 different locations (detailed below).
     29 
     30 Goldfish devices appear to the Linux kernel as 'platform devices'. Read [1] and
     31 [2] for an introduction and reference documentation for these.
     32 
     33 Each device is identified by a name, and an optional unique id (an integer used
     34 to distinguish between several identical instances of similar devices, like
     35 serial ports, of block devices). When only one instance of a given device can
     36 be used, an ID of -1 is used instead.
     37 
     38 It also communicates with the kernel through:
     39 
     40   - One or more 32-bit of I/O registers, mapped to physical addresses at
     41     specific locations which depend on the architecture.
     42 
     43   - Zero or more interrupt requests, used to signal to the kernel that an
     44     important event occured.
     45 
     46     Note that IRQ lines are numbered from 0 to 31, and are relative to the
     47     goldfish interrupt controller, documented below.
     48 
     49 
     50 [1] http://lwn.net/Articles/448499/
     51 [2] https://www.kernel.org/doc/Documentation/driver-model/platform.txt
     52 
     53 
     54 I. Goldfish platform bus:
     55 =========================
     56 
     57 The 'platform bus', in Linux kernel speak, is a special device that is capable
     58 of enumerating other platform devices found on the system to the kernel. This
     59 flexibility allows to customize which virtual devices are available when running
     60 a given emulated system configuration.
     61 
     62 Relevant files:
     63   $QEMU/hw/android/goldfish/device.c
     64   $KERNEL/arch/arm/mach-goldfish/pdev_bus.c
     65   $KERNEL/arch/x86/mach-goldfish/pdev_bus.c
     66   $KERNEL/arch/mips/goldfish/pdev_bus.c
     67 
     68 Device properties:
     69   Name: goldfish_device_bus
     70   Id:   -1
     71   IrqCount: 1
     72 
     73   32-bit I/O registers (offset, name, abstract)
     74 
     75     0x00 BUS_OP      R: Iterate to next device in enumeration.
     76                      W: Start device enumeration.
     77 
     78     0x04 GET_NAME    W: Copy device name to kernel memory.
     79     0x08 NAME_LEN    R: Read length of current device's name.
     80     0x0c ID          R: Read id of current device.
     81     0x10 IO_BASE     R: Read I/O base address of current device.
     82     0x14 IO_SIZE     R: Read I/O base size of current device.
     83     0x18 IRQ_BASE    R: Read base IRQ of current device.
     84     0x1c IRQ_COUNT   R: Read IRQ count of current device.
     85 
     86     # For 64-bit guest architectures only:
     87     0x20 NAME_ADDR_HIGH  W: Write high 32-bit of kernel address of name
     88                             buffer used by GET_NAME. Must be written to
     89                             before the GET_NAME write.
     90 
     91 The kernel iterates over the list of current devices with something like:
     92 
     93    IO_WRITE(BUS_OP, 0);    // Start iteration, any value other than 0 is invalid.
     94    for (;;) {
     95      int ret = IO_READ(BUS_OP);
     96      if (ret == 0 /* OP_DONE */) {
     97        // no more devices.
     98        break;
     99      }
    100      else if (ret == 8 /* OP_ADD_DEV */) {
    101        // Read device properties.
    102        Device dev;
    103        dev.name_len  = IO_READ(NAME_LEN);
    104        dev.id        = IO_READ(ID);
    105        dev.io_base   = IO_READ(IO_BASE);
    106        dev.io_size   = IO_READ(IO_SIZE);
    107        dev.irq_base  = IO_READ(IRQ_BASE);
    108        dev.irq_count = IO_READ(IRQ_COUNT);
    109 
    110        dev.name = kalloc(dev.name_len + 1);  // allocate room for device name.
    111     #if 64BIT_GUEST_CPU
    112        IO_WRITE(NAME_ADDR_HIGH, (uint32_t)(dev.name >> 32));
    113     #endif
    114        IO_WRITE(GET_NAME, (uint32_t)dev.name);  // copy to kernel memory.
    115        dev.name[dev.name_len] = 0;
    116 
    117        .. add device to kernel's list.
    118      }
    119      else {
    120        // Not returned by current goldfish implementation.
    121      }
    122    }
    123 
    124 The device also uses a single IRQ, which it will raise to indicate to the kernel
    125 that new devices are available, or that some of them have been removed. The
    126 kernel will then start a new enumeration. The IRQ is lowered by the device only
    127 when a IO_READ(BUS_OP) returns 0 (OP_DONE).
    128 
    129 NOTE: The kernel hard-codes a platform_device definition with the name
    130       "goldfish_pdev_bus" for the platform bus (e.g. see
    131       $KERNEL/arch/arm/mach-goldfish/board-goldfish.c), however, the bus itself
    132       will appear during enumeration as a device named "goldfish_device_bus"
    133 
    134       The kernel driver for the platform bus only matches the "goldfish_pdev_bus"
    135       name, and will ignore any device named "goldfish_device_bus".
    136 
    137 
    138 II. Goldfish interrupt controller:
    139 ==================================
    140 
    141 IMPORTANT: The controller IS NOT USED IN EMULATED X86 SYSTEMS.
    142            TODO(digit): Indicate which virtual PIC is used on x86 systems.
    143 
    144 Relevant files:
    145   $QEMU/hw/android/goldfish/interrupt.c
    146   $KERNEL/arch/arm/mach-goldfish/board-goldfish.c
    147   $KERNEL/arch/mips/goldfish/goldfish-interrupt.c
    148 
    149 Device properties:
    150   Name: goldfish_interrupt_controller
    151   Id: -1
    152   IrqCount: 0  (uses parent CPU IRQ instead).
    153 
    154   32-bit I/O registers (offset, name, abtract):
    155     0x00 STATUS       R: Read the number of pending interrupts (0 to 32).
    156     0x04 NUMBER       R: Read the lowest pending interrupt index, or 0 if none.
    157     0x08 DISABLE_ALL  W: Clear all pending interrupts (does not disable them!)
    158     0x0c DISABLE      W: Disable a given interrupt, value must be in [0..31].
    159     0x10 ENABLE       W: Enable a given interrupt, value must be in [0..31].
    160 
    161 Goldfish provides its own interrupt controller that can manage up to 32 distinct
    162 maskable interrupt request lines. The controller itself is cascaded from a
    163 parent CPU IRQ.
    164 
    165 What this means in practice:
    166 
    167   - Each IRQ has a 'level' that is either 'high' (1) or 'low' (0).
    168 
    169   - Each IRQ also has a binary 'enable' flag.
    170 
    171   - Whenever (level == 1 && enabled == 1) is reached due to a state change, the
    172     controller raises its parent IRQ. This typically interrupts the CPU and
    173     forces the kernel to deal with the interrupt request.
    174 
    175   - Raised/Enabled interrupts that have not been serviced yet are called
    176     "pending". Raised/Disabled interrupts are called "masked" and are
    177     essentially silent until enabled.
    178 
    179 When the interrupt controller triggers the parent IRQ, the kernel should do
    180 the following:
    181 
    182   num_pending = IO_READ(STATUS);  // Read number of pending interrupts.
    183   for (int n = 0; n < num_pending; ++n) {
    184     int irq_index = IO_READ(NUMBER);  // Read n-th interrupt index.
    185     .. service interrupt request with the proper driver.
    186   }
    187 
    188 IO_WRITE(DISABLE, <num>) or IO_WRITE(ENABLE, <num>) can change the 'enable' flag
    189 of a given IRQ. <num> must be a value in the [0..31] range. Note that enabling
    190 an IRQ which has already been raised will make it active, i.e. it will raise
    191 the parent IRQ.
    192 
    193 IO_WRITE(DISABLE_ALL, 0) can be used to lower all interrupt levels at once (even
    194 disabled one). Note that this constant is probably mis-named since it does not
    195 change the 'enable' flag of any IRQ.
    196 
    197 Note that this is the only way for the kernel to lower an IRQ level through
    198 this device. Generally speaking, Goldfish devices are responsible for lowering
    199 their own IRQ, which is performed either when a specific condition is met, or
    200 when the kernel reads from or writes to a device-specific I/O register.
    201 
    202 
    203 III. Godlfish timer:
    204 ====================
    205 
    206 NOTE: This is not used on x86 emulated platforms.
    207 
    208 Relevant files:
    209   $QEMU/hw/android/goldfish/timer.c
    210   $KERNEL/arch/arm/mach-goldfish/timer.c
    211   $KERNEL/arch/mips/goldfish/goldfish-time.c
    212 
    213 Device properties:
    214   Name: goldfish_timer
    215   Id: -1
    216   IrqCount: 1
    217 
    218   32-bit I/O registers (offset, name, abstract)
    219     0x00  TIME_LOW         R: Get current time, then return low-order 32-bits.
    220     0x04  TIME_HIGH        R: Return high 32-bits from previous TIME_LOW read.
    221     0x08  ALARM_LOW        W: Set low 32-bit value of alarm, then arm it.
    222     0x0c  ALARM_HIGH       W: Set high 32-bit value of alarm.
    223     0x10  CLEAR_INTERRUPT  W: Lower device's irq level.
    224     0x14  CLEAR_ALARM
    225 
    226 This device is used to return the current host time to the kernel, as a
    227 high-precision signed 64-bit nanoseconds value, starting from a liberal point
    228 in time. This value should correspond to the QEMU "vm_clock", i.e. it should
    229 not be updated when the emulated system does _not_ run, and hence cannot be
    230 based directly on a host clock.
    231 
    232 To read the value, the kernel must perform an IO_READ(TIME_LOW), which returns
    233 an unsigned 32-bit value, before an IO_READ(TIME_HIGH), which returns a signed
    234 32-bit value, corresponding to the higher half of the full value.
    235 
    236 The device can also be used to program an alarm, with something like:
    237 
    238   IO_WRITE(ALARM_HIGH, <high-value>)  // Must happen first.
    239   IO_WRITE(ALARM_LOW, <low-value>)    // Must happen second.
    240 
    241 When the corresponding value is reached, the device will raise its IRQ. Note
    242 that the IRQ is raised as soon as the second IO_WRITE() if the alarm value is
    243 already older than the current time.
    244 
    245 IO_WRITE(CLEAR_INTERRUPT, <any>) can be used to lower the IRQ level once the
    246 alarm has been handled by the kernel.
    247 
    248 IO_WRITE(CLEAR_ALARM, <any>) can be used to disarm an existing alarm, if any.
    249 
    250 Note: At the moment, the alarm is only used on ARM-based system. MIPS based
    251       systems only use TIME_LOW / TIME_HIGH on this device.
    252 
    253 
    254 III. Goldfish real-time clock (RTC):
    255 ====================================
    256 
    257 Relevant files:
    258   $QEMU/hw/android/goldfish/timer.c
    259   $KERNEL/drivers/rtc/rtc-goldfish.c
    260 
    261 Device properties:
    262   Name: goldfish_rtc
    263   Id: -1
    264   IrqCount: 1
    265   I/O Registers:
    266     0x00  TIME_LOW         R: Get current time, then return low-order 32-bits.
    267     0x04  TIME_HIGH        R: Return high 32-bits, from previous TIME_LOW read.
    268     0x08  ALARM_LOW        W: Set low 32-bit value or alarm, then arm it.
    269     0x0c  ALARM_HIGH       W: Set high 32-bit value of alarm.
    270     0x10  CLEAR_INTERRUPT  W: Lower device's irq level.
    271 
    272 This device is _very_ similar to the Goldfish timer one, with the following
    273 important differences:
    274 
    275   - Values reported are still 64-bit nanoseconds, but they have a granularity
    276     of 1 second, and represent host-specific values (really 'time() * 1e9')
    277 
    278   - The alarm is non-functioning, i.e. writing to ALARM_LOW / ALARM_HIGH will
    279     work, but will never arm any alarm.
    280 
    281 To support old Goldfish kernels, make sure to support writing to
    282 ALARM_LOW / ALARM_HIGH / CLEAR_INTERRUPT, even if the device never raises its
    283 IRQ.
    284 
    285 
    286 IV. Goldfish serial port (tty):
    287 ===============================
    288 
    289 Relevant files:
    290   $QEMU/hw/android/goldfish/tty.c
    291   $KERNEL/drivers/char/goldfish_tty.c
    292   $KERNEL/arch/arm/mach-goldfish/include/debug-macro.S
    293 
    294 Device properties:
    295   Name: goldfish_tty
    296   Id: 0 to N
    297   IrqCount:
    298   I/O Registers:
    299     0x00  PUT_CHAR      W: Write a single 8-bit value to the serial port.
    300     0x04  BYTES_READY   R: Read the number of available buffered input bytes.
    301     0x08  CMD           W: Send command (see below).
    302     0x10  DATA_PTR      W: Write kernel buffer address.
    303     0x14  DATA_LEN      W: Write kernel buffer size.
    304 
    305     # For 64-bit guest CPUs only:
    306     0x18  DATA_PTR_HIGH    W: Write high 32 bits of kernel buffer address.
    307 
    308 This is the first case of a multi-instance goldfish device in this document.
    309 Each instance implements a virtual serial port that contains a small internal
    310 buffer where incoming data is stored until the kernel fetches it.
    311 
    312 The CMD I/O register is used to send various commands to the device, identified
    313 by the following values:
    314 
    315   0x00  CMD_INT_DISABLE   Disable device.
    316   0x01  CMD_INT_ENABLE    Enable device.
    317   0x02  CMD_WRITE_BUFFER  Write buffer from kernel to device.
    318   0x03  CMD_READ_BUFFER   Read buffer from device to kernel.
    319 
    320 Each device instance uses one IRQ that is raised to indicate that there is
    321 incoming/buffered data to read. To read such data, the kernel should do the
    322 following:
    323 
    324     len = IO_READ(PUT_CHAR);   // Read length of incoming data.
    325     if (len == 0) return;      // Nothing to do.
    326 
    327     available = get_buffer(len, &buffer);  // Get address of buffer and its size.
    328     #if 64BIT_GUEST_CPU
    329     IO_WRITE(DATA_PTR_HIGH, buffer >> 32);
    330     #endif
    331     IO_WRITE(DATA_PTR, buffer);            // Write buffer address to device.
    332     IO_WRITE(DATA_LEN, available);         // Write buffer length to device.
    333     IO_WRITE(CMD, CMD_READ_BUFFER);        // Read the data into kernel buffer.
    334 
    335 The device will automatically lower its IRQ when there is no more input data
    336 in its buffer. However, the kernel can also temporarily disable device interrupts
    337 with CMD_INT_DISABLE / CMD_INT_ENABLE.
    338 
    339 Note that disabling interrupts does not flush the buffer, nor prevent it from
    340 buffering further data from external inputs.
    341 
    342 To write to the serial port, the device can either send a single byte at a time
    343 with:
    344 
    345   IO_WRITE(PUT_CHAR, <value>)    // Send the lower 8 bits of <value>.
    346 
    347 Or use the mode efficient sequence:
    348 
    349   #if 64BIT_GUEST_CPU
    350   IO_WRITE(DATA_PTR_HIGH, buffer >> 32)
    351   #endif
    352   IO_WRITE(DATA_PTR, buffer)
    353   IO_WRITE(DATA_LEN, buffer_len)
    354   IO_WRITE(CMD, CMD_WRITE_BUFFER)
    355 
    356 The former is less efficient but simpler, and is typically used by the kernel
    357 to send debug messages only.
    358 
    359 Note that the Android emulator always reserves the first two virtual serial
    360 ports:
    361 
    362   - The first one is used to receive kernel messages, this is done by adding
    363     the 'console=ttyS0' parameter to the kernel command line in
    364     $QEMU/vl-android.c
    365 
    366   - The second one is used to setup the legacy "qemud" channel, used on older
    367     Android platform revisions. This is done by adding 'android.qemud=ttyS1'
    368     on the kernel command line in $QEMU/vl-android.c
    369 
    370     Read docs/ANDROID-QEMUD.TXT for more details about the data that passes
    371     through this serial port. In a nutshell, this is required to emulate older
    372     Android releases (e.g. cupcake). It provides a direct communication channel
    373     between the guest system and the emulator.
    374 
    375     More recent Android platforms do not use QEMUD anymore, but instead rely
    376     on the much faster "QEMU pipe" device, described later in this document as
    377     well as in docs/ANDROID-QEMU-PIPE.TXT.
    378 
    379 
    380 V. Goldfish framebuffer:
    381 ========================
    382 
    383 Relevant files:
    384   $QEMU/hw/android/goldfish/fb.c
    385   $KERNEL/drivers/video/goldfish_fb.c
    386 
    387 Device properties:
    388   Name: goldfish_fb
    389   Id: 0 to N  (only one used in practice).
    390   IrqCount: 0
    391   I/O Registers:
    392     0x00  GET_WIDTH       R: Read framebuffer width in pixels.
    393     0x04  GET_HEIGHT      R: Read framebuffer height in pixels.
    394     0x08  INT_STATUS
    395     0x0c  INT_ENABLE
    396     0x10  SET_BASE
    397     0x14  SET_ROTATION
    398     0x18  SET_BLANK       W: Set 'blank' flag.
    399     0x1c  GET_PHYS_WIDTH  R: Read framebuffer width in millimeters.
    400     0x20  GET_PHYS_HEIGHT R: Read framebuffer height in millimeters.
    401     0x24  GET_FORMAT      R: Read framebuffer pixel format.
    402 
    403 The framebuffer device is a bit peculiar, because it uses, in addition to the
    404 typical I/O registers and IRQs, a large area of physical memory, allocated by
    405 the kernel, but visible to the emulator, to store a large pixel buffer.
    406 
    407 The emulator is responsible for displaying the framebuffer content in its UI
    408 window, which can be rotated, as instructed by the kernel.
    409 
    410 IMPORTANT NOTE: When GPU emulation is enabled, the framebuffer will typically
    411 only be used during boot. Note that GPU emulation doesn't rely on a specific
    412 virtual GPU device, however, it uses the "QEMU Pipe" device described below.
    413 For more information, please read:
    414 
    415   https://android.googlesource.com/platform/sdk/+/master/emulator/opengl/DESIGN
    416 
    417 On boot, the kernel will read various properties of the framebuffer:
    418 
    419   IO_READ(GET_WIDTH) and IO_READ(GET_HEIGHT) return the width and height of
    420   the framebuffer in pixels. Note that a 'row' corresponds to consecutive bytes
    421   in memory, but doesn't necessarily to an horizontal line on the final display,
    422   due to possible rotation (see SET_ROTATION below).
    423 
    424   IO_READ(GET_PHYS_WIDTH) and IO_READ(GET_PHYS_HEIGHT) return the emulated
    425   physical width and height in millimeters, this is later used by the kernel
    426   and the platform to determine the device's emulated density.
    427 
    428   IO_READ(GET_FORMAT) returns a value matching the format of pixels in the
    429   framebuffer. Note that these values are specified by the Android hardware
    430   abstraction layer (HAL) and cannot change:
    431 
    432     0x01  HAL_PIXEL_FORMAT_BRGA_8888
    433     0x02  HAL_PIXEL_FORMAT_RGBX_8888
    434     0x03  HAL_PIXEL_FORMAT_RGB_888
    435     0x04  HAL_PIXEL_FORMAT_RGB_565
    436     0x05  HAL_PIXEL_FORMAT_BGRA_8888
    437     0x06  HAL_PIXEL_FORMAT_RGBA_5551
    438     0x08  HAL_PIXEL_FORMAT_RGBA_4444
    439 
    440   HOWEVER, the kernel driver only expects a value of HAL_PIXEL_FORMAT_RGB_565
    441   at the moment. Until this is fixed, the virtual device should always return
    442   the value 0x04 here. Rows are not padded, so the size in bytes of a single
    443   framebuffer will always be exactly 'width * heigth * 2'.
    444 
    445   Note that GPU emulation doesn't have this limitation and can use and display
    446   32-bit surfaces properly, because it doesn't use the framebuffer.
    447 
    448 The device has a 'blank' flag. When set to 1, the UI should only display an
    449 empty/blank framebuffer, ignoring the content of the framebuffer memory.
    450 It is set with IO_WRITE(SET_BLANK, <value>), where value can be 1 or 0. This is
    451 used when simulating suspend/resume.
    452 
    453 IMPORTANT: The framebuffer memory is allocated by the kernel, which will send
    454 its physical address to the device by using IO_WRITE(SET_BASE, <address>).
    455 
    456 The kernel really allocates a memory buffer large enough to hold *two*
    457 framebuffers, in order to implement panning / double-buffering. This also means
    458 that calls to IO_WRITE(SET_BASE, <address>) will be frequent.
    459 
    460 The allocation happens with dma_alloc_writecombine() on ARM, which can only
    461 allocate a maximum of 4 MB, this limits the size of each framebuffer to 2 MB,
    462 which may not be enough to emulate high-density devices :-(
    463 
    464 For other architectures, dma_alloc_coherent() is used instead, and has the same
    465 upper limit / limitation.
    466 
    467 TODO(digit): Explain how it's possible to raise this limit by modifyinf
    468              CONSISTENT_DMA_SIZE and/or MAX_ORDER in the kernel configuration.
    469 
    470 The device uses a single IRQ to notify the kernel of several events. When it
    471 is raised, the kernel IRQ handler must IO_READ(INT_STATUS), which will return
    472 a value containing the following bit flags:
    473 
    474   bit 0: Set to 1 to indicate a VSYNC event.
    475 
    476   bit 1: Set to 1 to indicate that the content of a previous SET_BASE has
    477          been properly displayed.
    478 
    479 Note that reading this register also lowers the device's IRQ level.
    480 
    481 The second flag is essentially a way to notify the kernel that an
    482 IO_WRITE(SET_BASE, <address>) operation has been succesfully processed by
    483 the emulator, i.e. that the new content has been displayed to the user.
    484 
    485 The kernel can control which flags should raise an IRQ by using
    486 IO_WRITE(INT_ENABLE, <flags>), where <flags> has the same format as the
    487 result of IO_READ(INT_STATUS). If the corresponding bit is 0, the an IRQ
    488 for the corresponding event will never be generated,
    489 
    490 
    491 VI. Goldfish audio device:
    492 ==========================
    493 
    494 Relevant files:
    495   $QEMU/hw/android/goldfish/audio.c
    496   $KERNEL/drivers/misc/goldfish_audio.c
    497 
    498 Device properties:
    499   Name: goldfish_audio
    500   Id: -1
    501   IrqCount: 1
    502   I/O Registers:
    503     0x00  INT_STATUS
    504     0x04  INT_ENABLE
    505     0x08  SET_WRITE_BUFFER_1     W: Set address of first kernel output buffer.
    506     0x0c  SET_WRITE_BUFFER_2     W: Set address of second kernel output buffer.
    507     0x10  WRITE_BUFFER_1         W: Send first kernel buffer samples to output.
    508     0x14  WRITE_BUFFER_2         W: Send second kernel buffer samples to output.
    509     0x18  READ_SUPPORTED         R: Reads 1 if input is supported, 0 otherwise.
    510     0x1c  SET_READ_BUFFER
    511     0x20  START_READ
    512     0x24  READ_BUFFER_AVAILABLE
    513 
    514     # For 64-bit guest CPUs
    515     0x28  SET_WRITE_BUFFER_1_HIGH  W: Set high 32 bits of 1st kernel output buffer address.
    516     0x30  SET_WRITE_BUFFER_2_HIGH  W: Set high 32 bits  of 2nd kernel output buffer address.
    517     0x34  SET_READ_BUFFER_HIGH     W: Set high 32 bits of kernel input buffer address.
    518 
    519 This device implements a virtual sound card with the following properties:
    520 
    521   - Stereo output at fixed 44.1 kHz frequency, using signed 16-bit samples.
    522     Mandatory.
    523 
    524   - Mono input at fixed 8 kHz frequency, using signed 16-bit samples.
    525     Optional.
    526 
    527 For output, the kernel driver allocates two internal buffers to hold output
    528 samples, and passes their physical address to the emulator as follows:
    529 
    530   #if 64BIT_GUEST_CPU
    531   IO_WRITE(SET_WRITE_BUFFER_1_HIGH, (uint32_t)(buffer1 >> 32));
    532   IO_WRITE(SET_WRITE_BUFFER_2_HIGH, (uint32_t)(buffer2 >> 32));
    533   #endif
    534   IO_WRITE(SET_WRITE_BUFFER_1, (uint32_t)buffer1);
    535   IO_WRITE(SET_WRITE_BUFFER_2, (uint32_t)buffer2);
    536 
    537 After this, samples will be sent from the driver to the virtual device by
    538 using one of IO_WRITE(WRITE_BUFFER_1, <length1>) or
    539 IO_WRITE(WRITE_BUFFER_2, <length2>), depending on which sample buffer to use.
    540 NOTE: Each length is in bytes.
    541 
    542 Note however that the driver should wait, before doing this, until the device
    543 gives permission by raising its IRQ and setting the appropriate 'status' flags.
    544 
    545 The virtual device has an internal 'int_status' field made of 3 bit flags:
    546 
    547   bit0: 1 iff the device is ready to receive data from the first buffer.
    548   bit1: 1 iff the device is ready to receive data from the second buffer.
    549   bit2: 1 iff the device has input samples for the kernel to read.
    550 
    551 Note that an IO_READ(INT_STATUS) also automatically lowers the IRQ level,
    552 except if the read value is 0 (which should not happen, since it should not
    553 raise the IRQ).
    554 
    555 The corresponding interrupts can be masked by using IO_WRITE(INT_ENABLE, <mask>),
    556 where <mask> has the same format as 'int_status'. A 1 bit in the mask enables the
    557 IRQ raise when the corresponding status bit is also set to 1.
    558 
    559 For input, the driver should first IO_READ(READ_SUPPORTED), which will return 1
    560 if the virtual device supports input, or 0 otherwise. If it does support it,
    561 the driver must allocate an internal buffer and send its physical address with
    562 IO_WRITE(SET_READ_BUFFER, <read-buffer>) (with a previous write to
    563 SET_READ_BUFFER_HIGH on 64-bit guest CPUS), then perform
    564 IO_WRITE(START_READ, <read-buffer-length>) to start recording and
    565 specify the kernel's buffer length.
    566 
    567 Later, the device will raise its IRQ and set bit2 of 'int_status' to indicate
    568 there are incoming samples to the driver. In its interrupt handler, the latter
    569 should IO_READ(READ_BUFFER_AVAILABLE), which triggers the transfer (from the
    570 device to the kernel), as well as return the size in bytes of the samples.
    571 
    572 
    573 VII. Goldfish battery:
    574 ======================
    575 
    576 Relevant files:
    577   $QEMU/hw/android/goldfish/battery.c
    578   $QEMU/hw/power_supply.h
    579   $KERNEL/drivers/power/goldfish_battery.c
    580 
    581 Device properties:
    582   Name: goldfish_battery
    583   Id: -1
    584   IrqCount: 1
    585   I/O Registers:
    586     0x00 INT_STATUS   R: Read battery and A/C status change bits.
    587     0x04 INT_ENABLE   W: Enable or disable IRQ on status change.
    588     0x08 AC_ONLINE    R: Read 0 if AC power disconnected, 1 otherwise.
    589     0x0c STATUS       R: Read battery status (charging/full/... see below).
    590     0x10 HEALTH       R: Read battery health (good/overheat/... see below).
    591     0x14 PRESENT      R: Read 1 if battery is present, 0 otherwise.
    592     0x18 CAPACITY     R: Read battery charge percentage in [0..100] range.
    593 
    594 A simple device used to report the state of the virtual device's battery, and
    595 whether the device is powered through a USB or A/C adapter.
    596 
    597 The device uses a single IRQ to notify the kernel that the battery or A/C status
    598 changed. When this happens, the kernel should perform an IO_READ(INT_STATUS)
    599 which returns a 2-bit value containing flags:
    600 
    601   bit 0: Set to 1 to indicate a change in battery status.
    602   bit 1: Set to 1 to indicate a change in A/C status.
    603 
    604 Note that reading this register also lowers the IRQ level.
    605 
    606 The A/C status can be read with IO_READ(AC_ONLINE), which returns 1 if the
    607 device is powered, or 0 otherwise.
    608 
    609 The battery status is spread over multiple I/O registers:
    610 
    611   IO_READ(PRESENT) returns 1 if the battery is present in the virtual device,
    612   or 0 otherwise.
    613 
    614   IO_READ(CAPACITY) returns the battery's charge percentage, as an integer
    615   between 0 and 100, inclusive. NOTE: This register is probably misnamed since
    616   it does not represent the battery's capacity, but it's current charge level.
    617 
    618   IO_READ(STATUS) returns one of the following values:
    619 
    620     0x00  UNKNOWN      Battery state is unknown.
    621     0x01  CHARGING     Battery is charging.
    622     0x02  DISCHARGING  Battery is discharging.
    623     0x03  NOT_CHARGING Battery is not charging (e.g. full or dead).
    624 
    625   IO_READ(HEALTH) returns one of the following values:
    626 
    627     0x00  UNKNOWN         Battery health unknown.
    628     0x01  GOOD            Battery is in good condition.
    629     0x02  OVERHEATING     Battery is over-heating.
    630     0x03  DEAD            Battery is dead.
    631     0x04  OVERVOLTAGE     Battery generates too much voltage.
    632     0x05  UNSPEC_FAILURE  Battery has unspecified failure.
    633 
    634 The kernel can use IO_WRITE(INT_ENABLE, <flags>) to select which condition
    635 changes should trigger an IRQ. <flags> is a 2-bit value using the same format
    636 as INT_STATUS.
    637 
    638 
    639 VIII. Goldfish events device (user input):
    640 ==========================================
    641 
    642 Relevant files:
    643   $QEMU/hw/android/goldfish/events_device.c
    644   $KERNEL/drivers/input/keyboard/goldfish_events.c
    645 
    646 Device properties:
    647   Name: goldfish_events
    648   Id: -1
    649   IrqCount: 1
    650   I/O Registers:
    651     0x00 READ       R: Read next event type, code or value.
    652     0x00 SET_PAGE   W: Set page index.
    653     0x04 LEN        R: Read length of page data.
    654     0x08 DATA       R: Read page data.
    655     ....            R: Read additional page data (see below).
    656 
    657 This device is responsible for sending several kinds of user input events to
    658 the kernel, i.e. emulated device buttons, hardware keyboard, touch screen,
    659 trackball and lid events.
    660 
    661 NOTE: Android supports other input devices like mice or game controllers
    662       through USB or Bluetooth, these are not supported by this virtual
    663       Goldfish device.
    664 
    665 NOTE: The 'lid event' is useful for devices with a clamshell of foldable
    666       keyboard design, and is used to report when it is opened or closed.
    667 
    668 As per Linux conventions, each 'emulated event' is sent to the kernel as a
    669 series of (<type>,<code>,<value>) triplets or 32-bit values. For more
    670 information, see:
    671 
    672   https://www.kernel.org/doc/Documentation/input/input.txt
    673 
    674 As well as the <linux/input.h> kernel header.
    675 
    676 Note that in the context of goldfish:
    677 
    678  - Button and keyboard events are reported with:
    679      (EV_KEY, <code>, <press>)
    680 
    681    Where <code> is a 9-bit keycode, as defined by <linux/input.h>, and
    682    <press> is 1 for key/button presses, and 0 for releases.
    683 
    684  - For touchscreen events, a single-touch event is reported with:
    685      (EV_ABS, ABS_X, <x-position>) +
    686      (EV_ABS, ABS_Y, <y-position>) +
    687      (EV_ABS, ABS_Z, 0) +
    688      (EV_KEY, BTN_TOUCH, <button-state>) +
    689      (EV_SYN, 0, 0)
    690 
    691    where <x-position> and <y-position> are the horizontal and vertical position
    692    of the touch event, respectfully, and <button-state> is either 1 or 0 and
    693    indicates the start/end of the touch gesture, respectively.
    694 
    695  - For multi-touch events, things are much more complicated. In a nutshell,
    696    these events are reported through (EV_ABS, ABS_MT_XXXXX, YYY) triplets,
    697    as documented at:
    698 
    699    https://www.kernel.org/doc/Documentation/input/multi-touch-protocol.txt
    700 
    701    TODO(digit): There may be bugs in either the virtual device or driver code
    702                 when it comes to multi-touch. Iron out the situation and better
    703                 explain what's required to support all Android platforms.
    704 
    705  - For trackball events:
    706      (EV_REL, REL_X, <x-delta>) +
    707      (EV_REL, REL_Y, <y-delta>) +
    708      (EV_SYN, 0, 0)
    709 
    710    Where <x-delta> and <y-delta> are the signed relative trackball displacement
    711    in the horizontal and vertical directions, respectively.
    712 
    713  - For lid events:
    714      (EV_SW, 0, 1) + (EV_SYN, 0, 0)    // When lid is closed.
    715      (EV_SW, 0, 0) + (EV_SYN, 0, 0)    // When lid is opened.
    716 
    717 When the kernel driver starts, it will probe the device to know what kind
    718 of events are supported by the emulated configuration. There are several
    719 categories of queries:
    720 
    721   - Asking for the current physical keyboard 'charmap' name, used by the system
    722     to translate keycodes in actual characters. In practice, this will nearly
    723     always be 'goldfish' for emulated systems, but this out of spec for this
    724     document.
    725 
    726   - Asking which event codes are supported for a given event type
    727     (e.g. all the possible KEY_XXX values generated for EV_KEY typed triplets).
    728 
    729   - Asking for various minimum or maximum values for each supported EV_ABS
    730     event code. For example the min/max values of (EV_ABS, ABS_X, ...) triplets,
    731     to know the bounds of the input touch panel.
    732 
    733 The kernel driver first select which kind of query it wants by using
    734 IO_WRITE(SET_PAGE, <page>), where <page> is one of the following values:
    735 
    736     PAGE_NAME    0x0000   Keyboard charmap name.
    737     PAGE_EVBITS  0x10000  Event code supported sets.
    738     PAGE_ABSDATA 0x20003  (really 0x20000 + EV_ABS) EV_ABS min/max values.
    739 
    740 Once a 'page' has been selected, it is possible to read from it with
    741 IO_READ(LEN) and IO_READ(DATA). In practice:
    742 
    743   - To read the name of the keyboard charmap, the kernel will do:
    744 
    745       IO_WRITE(SET_PAGE, PAGE_NAME);  # Ind
    746 
    747       charmap_name_len = IO_READ(LEN);
    748       charmap_name = kalloc(charmap_name_len + 1);
    749       for (int n = 0; n < charmap_name_len; ++n)
    750         charmap_name[n] = (char) IO_READ(DATA);
    751       charmap_name[n] = 0;
    752 
    753   - To read which codes a given event type (here EV_KEY) supports:
    754 
    755       IO_WRITE(SET_PAGE, PAGE_EVBITS + EV_KEY);  // Or EV_REL, EV_ABS, etc...
    756 
    757       bitmask_len = IO_READ(LEN);
    758       for (int offset = 0; offset < bitmask_len; ++offset) {
    759           uint8_t mask = (uint8_t) IO_READ(DATA):
    760           for (int bit = 0; bit < 8; ++bit) {
    761               int code = (offset * 8) + bit;
    762               if ((mask & (1 << bit)) != 0) {
    763                   ... record that keycode |code| is supported.
    764               }
    765           }
    766       }
    767 
    768   - To read the range values of absolute event values:
    769 
    770       IO_WRITE(SET_PAGE, PAGE_ABSDATA);
    771       max_entries = IO_READ(LEN);
    772       for (int n = 0; n < max_entries; n += 4) {
    773         int32_t min = IO_READ(DATA + n);
    774         int32_t max = IO_READ(DATA + n + 4);
    775         int32_t fuzz = IO_READ(DATA + n + 8);
    776         int32_t flat = IO_READ(DATA + n + 12);
    777         int event_code = n/4;
    778 
    779         // Record (min, max, fuzz, flat) values for EV_ABS 'event_code'.
    780       }
    781 
    782     Note that the 'fuzz' and 'flat' values reported by Goldfish are always 0,
    783     refer to the source for more details.
    784 
    785 At runtime, the device implements a small buffer for incoming event triplets
    786 (each one is stored as three 32-bit integers in a circular buffer), and raises
    787 its IRQ to signal them to the kernel.
    788 
    789 When that happens, the kernel driver should use IO_READ(READ) to extract the
    790 32-bit values from the device. Note that three IO_READ() calls are required to
    791 extract a single event triplet.
    792 
    793 There are a few important notes here:
    794 
    795   - The IRQ should not be raised _before_ the kernel driver is started
    796     (otherwise the driver will be confused and ignore all events).
    797 
    798     I.e. the emulator can buffer events before kernel initialization completes,
    799     but should only raise the IRQ, if needed, lazily. Currently this is done
    800     on the first IO_READ(LEN) following a IO_WRITE(SET_PAGE, PAGE_ABSDATA).
    801 
    802   - The IRQ is lowered by the device once all event values have been read,
    803     i.e. its buffer is empty.
    804 
    805     However, on x86, if after an IO_READ(READ), there are still values in the
    806     device's buffer, the IRQ should be lowered then re-raised immediately.
    807 
    808 
    809 IX. Goldfish NAND device:
    810 =========================
    811 
    812 Relevant files:
    813   $QEMU/hw/android/goldfish/nand.c
    814   $KERNEL/drivers/mtd/devices/goldfish_nand.c
    815 
    816 Device properties:
    817   Name: goldfish_nand
    818   Id: -1
    819   IrqCount: 1
    820   I/O Registers:
    821 
    822 This virtual device can provide access to one or more emulated NAND memory
    823 banks [3] (each one being backed by a different host file in the current
    824 implementation).
    825 
    826 These are used to back the following virtual partition files:
    827 
    828   - system.img
    829   - data.img
    830   - cache.img
    831 
    832 TODO(digit): Complete this.
    833 
    834 
    835 [3] http://en.wikipedia.org/wiki/Flash_memory#NAND_memories
    836 
    837 
    838 X. Goldfish MMC device:
    839 =======================
    840 
    841 Relevant files:
    842   $QEMU/hw/android/goldfish/mmc.c
    843   $KERNEL/drivers/mmc/host/goldfish.c
    844 
    845 Device properties:
    846   Name: goldfish_mmc
    847   Id: -1
    848   IrqCount: 1
    849   I/O Registers:
    850 
    851 Similar to the NAND device, but uses a different, higher-level interface
    852 to access the emulated 'flash' memory. This is only used to access the
    853 virtual SDCard device with the Android emulator.
    854 
    855 TODO(digit): Complete this.
    856 
    857 
    858 XIV. QEMU Pipe device:
    859 ======================
    860 
    861 Relevant files:
    862   $QEMU/hw/android/goldfish/pipe.c
    863   $KERNEL/drivers/misc/qemupipe/qemu_pipe.c
    864 
    865 Device properties:
    866   Name: qemu_pipe
    867   Id: -1
    868   IrqCount: 1
    869   I/O Registers:
    870     0x00  COMMAND          W: Write to perform command (see below).
    871     0x04  STATUS           R: Read status
    872     0x08  CHANNEL          RW: Read or set current channel id.
    873     0x0c  SIZE             RW: Read or set current buffer size.
    874     0x10  ADDRESS          RW: Read or set current buffer physical address.
    875     0x14  WAKES            R: Read wake flags.
    876     0x18  PARAMS_ADDR_LOW  RW: Read/set low bytes of parameters block address.
    877     0x1c  PARAMS_ADDR_HIGH RW: Read/set high bytes of parameters block address.
    878     0x20  ACCESS_PARAMS    W: Perform access with parameter block.
    879 
    880 This is a special device that is totally specific to QEMU, but allows guest
    881 processes to communicate directly with the emulator with extremely high
    882 performance. This is achieved by avoiding any in-kernel memory copies, relying
    883 on the fact that QEMU can access guest memory at runtime (under proper
    884 conditions controlled by the kernel).
    885 
    886 Please refer to $QEMU/docs/ANDROID-QEMU-PIPE.TXT for full details on the
    887 device's operations.
    888 
    889 
    890 XIII. QEMU Trace device:
    891 ========================
    892 
    893 Relevant files:
    894   $QEMU/hw/android/goldfish/trace.c
    895   $KERNEL/drivers/misc/qemutrace/qemu_trace.c
    896   $KERNEL/drivers/misc/qemutrace/qemu_trace_sysfs.c
    897   $KERNEL/fs/exec.c
    898   $KERNEL/exit.c
    899   $KERNEL/fork.c
    900   $KERNEL/sched/core.c
    901   $KERNEL/mm/mmap.c
    902 
    903 Device properties:
    904   Name: qemu_trace
    905   Id: -1
    906   IrqCount: 0
    907   I/O Registers:
    908 
    909 TODO(digit)
    910 
    911