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