Merge pull request #1360 from rneugeba/cmd

Introduce subcommands to 'moby' and add a 'run' sub command
This commit is contained in:
Rolf Neugebauer 2017-03-22 14:53:07 +00:00 committed by GitHub
commit d2e53018c6
126 changed files with 34048 additions and 159 deletions

View File

@ -15,12 +15,12 @@ bin/moby: $(MOBY_DEPS) | bin
tar cf - vendor src/initrd src/pad4 -C src/cmd/moby . | docker run --rm --net=none --log-driver=none -i $(CROSS) $(GO_COMPILE) --package github.com/docker/moby -o $@ | tar xf -
moby-initrd.img: bin/moby moby.yaml
$^
bin/moby build moby.yaml
moby-bzImage: moby-initrd.img
test-initrd.img: bin/moby test/test.yaml
$^
bin/moby build test/test.yaml
test-bzImage: test-initrd.img

View File

@ -22,7 +22,7 @@ This will build the Moby customisation tool and a Moby initrd image.
If you already have a Go build environment and installed the source in your `GOPATH`
you can do `go install github.com/docker/moby/cmd/moby` to install the `moby` tool
instead, and then use `moby moby.yaml` to build the example configuration.
instead, and then use `moby build moby.yaml` to build the example configuration.
#### Build requirements
@ -32,6 +32,9 @@ instead, and then use `moby moby.yaml` to build the example configuration.
### Booting and Testing
If you have a recent version of Docker for Mac installed you can use `moby run <name>` to execute the image you created with `moby build <name>.yaml`
The Makefile also specifies a number of targets:
- `make qemu` will boot up a sample Moby in qemu in a container
- on OSX: `make hyperkit` will boot up Moby in hyperkit
- `make test` or `make hyperkit-test` will run the test suite
@ -40,7 +43,7 @@ instead, and then use `moby moby.yaml` to build the example configuration.
## Customise
To customise, copy or modify the [`moby.yaml`](moby.yaml) to your own `file.yaml` or use on of the [examples](examples/) and then run `./bin/moby file.yaml` to
To customise, copy or modify the [`moby.yaml`](moby.yaml) to your own `file.yaml` or use on of the [examples](examples/) and then run `./bin/moby build file.yaml` to
generate its specified output. You can run the output with `./scripts/qemu.sh` or `./scripts/hyperkit.sh`, or on other
platforms.

158
src/cmd/moby/build.go Normal file
View File

@ -0,0 +1,158 @@
package main
import (
"archive/tar"
"bytes"
"errors"
"io"
"io/ioutil"
"log"
"path/filepath"
"github.com/docker/moby/src/initrd"
)
const (
docker2tar = "mobylinux/docker2tar:82a3f11f70b2959c7100dd6e184b511ebfc65908@sha256:e4fd36febc108477a2e5316d263ac257527779409891c7ac10d455a162df05c1"
)
func untarKernel(buf *bytes.Buffer, bzimageName, ktarName string) (*bytes.Buffer, *bytes.Buffer, error) {
tr := tar.NewReader(buf)
var bzimage, ktar *bytes.Buffer
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
log.Fatalln(err)
}
switch hdr.Name {
case bzimageName:
bzimage = new(bytes.Buffer)
_, err := io.Copy(bzimage, tr)
if err != nil {
return nil, nil, err
}
case ktarName:
ktar = new(bytes.Buffer)
_, err := io.Copy(bzimage, tr)
if err != nil {
return nil, nil, err
}
default:
continue
}
}
if ktar == nil || bzimage == nil {
return nil, nil, errors.New("did not find bzImage and kernel.tar in tarball")
}
return bzimage, ktar, nil
}
func containersInitrd(containers []*bytes.Buffer) (*bytes.Buffer, error) {
w := new(bytes.Buffer)
iw := initrd.NewWriter(w)
defer iw.Close()
for _, file := range containers {
_, err := initrd.Copy(iw, file)
if err != nil {
return nil, err
}
}
return w, nil
}
func build(name string, args []string) {
conf := "moby.yaml"
if len(args) > 0 {
conf = args[0]
}
if name == "" {
name = filepath.Base(conf)
ext := filepath.Ext(conf)
if ext != "" {
name = name[:len(name)-len(ext)]
}
}
config, err := ioutil.ReadFile(conf)
if err != nil {
log.Fatalf("Cannot open config file: %v", err)
}
m, err := NewConfig(config)
if err != nil {
log.Fatalf("Invalid config: %v", err)
}
containers := []*bytes.Buffer{}
// get kernel bzImage and initrd tarball from container
// TODO examine contents to see what names they might have
const (
bzimageName = "bzImage"
ktarName = "kernel.tar"
)
out, err := dockerRun(m.Kernel.Image, "tar", "cf", "-", bzimageName, ktarName)
if err != nil {
log.Fatalf("Failed to extract kernel image and tarball: %v", err)
}
buf := bytes.NewBuffer(out)
bzimage, ktar, err := untarKernel(buf, bzimageName, ktarName)
if err != nil {
log.Fatalf("Could not extract bzImage and kernel filesystem from tarball")
}
containers = append(containers, ktar)
// convert init image to tarball
init, err := dockerRun("-v", "/var/run/docker.sock:/var/run/docker.sock", docker2tar, m.Init)
if err != nil {
log.Fatalf("Failed to build init tarball: %v", err)
}
buffer := bytes.NewBuffer(init)
containers = append(containers, buffer)
for i, image := range m.System {
args := ConfigToRun(i, "system", &image)
out, err := dockerRun(args...)
if err != nil {
log.Fatalf("Failed to build container tarball: %v", err)
}
buffer := bytes.NewBuffer(out)
containers = append(containers, buffer)
}
for i, image := range m.Daemon {
args := ConfigToRun(i, "daemon", &image)
out, err := dockerRun(args...)
if err != nil {
log.Fatalf("Failed to build container tarball: %v", err)
}
buffer := bytes.NewBuffer(out)
containers = append(containers, buffer)
}
// add files
buffer, err = filesystem(m)
if err != nil {
log.Fatalf("failed to add filesystem parts: %v", err)
}
containers = append(containers, buffer)
initrd, err := containersInitrd(containers)
if err != nil {
log.Fatalf("Failed to make initrd %v", err)
}
err = outputs(m, name, bzimage.Bytes(), initrd.Bytes())
if err != nil {
log.Fatalf("Error writing outputs: %v", err)
}
}

View File

@ -1,22 +1,13 @@
package main
import (
"archive/tar"
"bytes"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"github.com/docker/moby/src/initrd"
)
const (
docker2tar = "mobylinux/docker2tar:82a3f11f70b2959c7100dd6e184b511ebfc65908@sha256:e4fd36febc108477a2e5316d263ac257527779409891c7ac10d455a162df05c1"
)
func dockerRun(args ...string) ([]byte, error) {
@ -104,155 +95,61 @@ func dockerRunInput(input io.Reader, args ...string) ([]byte, error) {
return stdout, nil
}
func untarKernel(buf *bytes.Buffer, bzimageName, ktarName string) (*bytes.Buffer, *bytes.Buffer, error) {
tr := tar.NewReader(buf)
var bzimage, ktar *bytes.Buffer
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
log.Fatalln(err)
}
switch hdr.Name {
case bzimageName:
bzimage = new(bytes.Buffer)
_, err := io.Copy(bzimage, tr)
if err != nil {
return nil, nil, err
}
case ktarName:
ktar = new(bytes.Buffer)
_, err := io.Copy(bzimage, tr)
if err != nil {
return nil, nil, err
}
default:
continue
}
}
if ktar == nil || bzimage == nil {
return nil, nil, errors.New("did not find bzImage and kernel.tar in tarball")
}
return bzimage, ktar, nil
}
func containersInitrd(containers []*bytes.Buffer) (*bytes.Buffer, error) {
w := new(bytes.Buffer)
iw := initrd.NewWriter(w)
defer iw.Close()
for _, file := range containers {
_, err := initrd.Copy(iw, file)
if err != nil {
return nil, err
}
}
return w, nil
}
func build(m *Moby, name string) {
containers := []*bytes.Buffer{}
// get kernel bzImage and initrd tarball from container
// TODO examine contents to see what names they might have
const (
bzimageName = "bzImage"
ktarName = "kernel.tar"
)
out, err := dockerRun(m.Kernel.Image, "tar", "cf", "-", bzimageName, ktarName)
if err != nil {
log.Fatalf("Failed to extract kernel image and tarball: %v", err)
}
buf := bytes.NewBuffer(out)
bzimage, ktar, err := untarKernel(buf, bzimageName, ktarName)
if err != nil {
log.Fatalf("Could not extract bzImage and kernel filesystem from tarball")
}
containers = append(containers, ktar)
// convert init image to tarball
init, err := dockerRun("-v", "/var/run/docker.sock:/var/run/docker.sock", docker2tar, m.Init)
if err != nil {
log.Fatalf("Failed to build init tarball: %v", err)
}
buffer := bytes.NewBuffer(init)
containers = append(containers, buffer)
for i, image := range m.System {
args := ConfigToRun(i, "system", &image)
out, err := dockerRun(args...)
if err != nil {
log.Fatalf("Failed to build container tarball: %v", err)
}
buffer := bytes.NewBuffer(out)
containers = append(containers, buffer)
}
for i, image := range m.Daemon {
args := ConfigToRun(i, "daemon", &image)
out, err := dockerRun(args...)
if err != nil {
log.Fatalf("Failed to build container tarball: %v", err)
}
buffer := bytes.NewBuffer(out)
containers = append(containers, buffer)
}
// add files
buffer, err = filesystem(m)
if err != nil {
log.Fatalf("failed to add filesystem parts: %v", err)
}
containers = append(containers, buffer)
initrd, err := containersInitrd(containers)
if err != nil {
log.Fatalf("Failed to make initrd %v", err)
}
err = outputs(m, name, bzimage.Bytes(), initrd.Bytes())
if err != nil {
log.Fatalf("Error writing outputs: %v", err)
}
}
var (
conf string
name string
)
func main() {
flag.StringVar(&name, "name", "", "Name to use for output files")
flag.Parse()
conf = "moby.yaml"
if len(flag.Args()) > 0 {
conf = flag.Args()[0]
flag.Usage = func() {
fmt.Printf("USAGE: %s COMMAND\n\n", os.Args[0])
fmt.Printf("Commands:\n")
fmt.Printf(" build Build a Moby image from a YAML file\n")
fmt.Printf(" run Run a Moby image on a local hypervisor\n")
fmt.Printf(" help Print this message\n")
fmt.Printf("\n")
fmt.Printf("Run '%s COMMAND --help' for more information on the command\n", os.Args[0])
}
if name == "" {
name = filepath.Base(conf)
ext := filepath.Ext(conf)
if ext != "" {
name = name[:len(name)-len(ext)]
}
buildCmd := flag.NewFlagSet("build", flag.ExitOnError)
buildCmd.Usage = func() {
fmt.Printf("USAGE: %s build [options] [file.yaml]\n\n", os.Args[0])
fmt.Printf("'file.yaml' defaults to 'moby.yaml' if not specified.\n\n")
fmt.Printf("Options:\n")
buildCmd.PrintDefaults()
}
buildName := buildCmd.String("name", "", "Name to use for output files")
runCmd := flag.NewFlagSet("run", flag.ExitOnError)
runCmd.Usage = func() {
fmt.Printf("USAGE: %s run [options] [prefix]\n\n", os.Args[0])
fmt.Printf("'prefix' specifies the path to the VM image.\n")
fmt.Printf("It defaults to './moby'.\n")
fmt.Printf("\n")
fmt.Printf("Options:\n")
runCmd.PrintDefaults()
fmt.Printf("\n")
fmt.Printf("If 'data' is supplied or if 'background' is selected\n")
fmt.Printf("some per VM state is kept in a sub-directory in the ~/.moby\n")
}
runCPUs := runCmd.Int("cpus", 1, "Number of CPUs")
runMem := runCmd.Int("mem", 1024, "Amount of memory in MB")
runDiskSz := runCmd.Int("disk-size", 0, "Size of Disk in MB")
runDisk := runCmd.String("disk", "", "Path to disk image to used")
if len(os.Args) < 2 {
fmt.Printf("Please specify a command.\n\n")
flag.Usage()
os.Exit(1)
}
config, err := ioutil.ReadFile(conf)
if err != nil {
log.Fatalf("Cannot open config file: %v", err)
switch os.Args[1] {
case "build":
buildCmd.Parse(os.Args[2:])
build(*buildName, buildCmd.Args())
case "run":
runCmd.Parse(os.Args[2:])
run(*runCPUs, *runMem, *runDiskSz, *runDisk, runCmd.Args())
case "help":
flag.Usage()
default:
fmt.Printf("%q is not valid command.\n\n", os.Args[1])
flag.Usage()
os.Exit(1)
}
m, err := NewConfig(config)
if err != nil {
log.Fatalf("Invalid config: %v", err)
}
build(m, name)
}

View File

@ -0,0 +1,51 @@
// +build darwin
package main
import (
"io/ioutil"
"log"
"os"
"os/user"
"github.com/docker/hyperkit/go"
)
func run(cpus, mem, diskSz int, disk string, args []string) {
prefix := "moby"
if len(args) > 0 {
prefix = args[0]
}
cmdline, err := ioutil.ReadFile(prefix + "-cmdline")
if err != nil {
log.Fatalf("Cannot open cmdline file: %v", err)
}
if diskSz != 0 && disk == "" {
disk = prefix + "-disk.img"
}
h, err := hyperkit.New("", "", "auto", disk)
if err != nil {
log.Fatalln("Error creating hyperkit: ", err)
}
h.Kernel = prefix + "-bzImage"
h.Initrd = prefix + "-initrd.img"
h.CPUs = cpus
h.Memory = mem
h.DiskSize = diskSz
err = h.Run(string(cmdline))
if err != nil {
log.Fatalf("Cannot run hyperkit: %v", err)
}
}
func getHome() string {
if usr, err := user.Current(); err == nil {
return usr.HomeDir
}
return os.Getenv("HOME")
}

View File

@ -0,0 +1,11 @@
// +build !darwin
package main
import (
"log"
)
func run(cpus, mem, diskSz int, userData string, args []string) {
log.Fatalf("'run' is not support yet on your OS")
}

View File

@ -1,5 +1,8 @@
github.com/docker/hyperkit/go 9f093be2e131133a7ec63f859d75242f1db9116e
github.com/googleapis/gax-go 8c5154c0fe5bf18cf649634d4c6df50897a32751
github.com/golang/protobuf/proto c9c7427a2a70d2eb3bafa0ab2dc163e45f143317
github.com/mitchellh/go-ps 4fdf99ab29366514c69ccccddab5dc58b8d84062
github.com/rneugeba/iso9660wrap 9c7eaf5ac74b2416be8b7b8d1f35b9af44a6e4fa
github.com/surma/gocpio fcb68777e7dc4ea43ffce871b552c0d073c17495
cloud.google.com/go/storage 0bee953ffbf6fda3be3f56f1e9578f16a1e978a4
golang.org/x/net/context a6577fac2d73be281a500b310739095313165611

115
vendor/github.com/docker/hyperkit/README.md generated vendored Normal file
View File

@ -0,0 +1,115 @@
## [HyperKit](http://github.com/docker/hyperkit)
![Build Status OSX](https://circleci.com/gh/docker/hyperkit.svg?style=shield&circle-token=cf8379b302eab2bbf33821cafe164dbefb71982d)
*HyperKit* is a toolkit for embedding hypervisor capabilities in your application. It includes a complete hypervisor, based on [xhyve](https://github.com/mist64/xhyve)/[bhyve](http://bhyve.org), which is optimized for lightweight virtual machines and container deployment. It is designed to be interfaced with higher-level components such as the [VPNKit](https://github.com/docker/vpnkit) and [DataKit](https://github.com/docker/datakit).
HyperKit currently only supports Mac OS X using the [Hypervisor.framework](https://developer.apple.com/library/mac/documentation/DriversKernelHardware/Reference/Hypervisor/index.html). It is a core component of Docker For Mac.
## Requirements
* OS X 10.10.3 Yosemite or later
* a 2010 or later Mac (i.e. a CPU that supports EPT)
## Reporting Bugs
If you are using a version of Hyperkit which is embedded into a higher level application (e.g. [Docker for Mac](https://github.com/docker/for-mac)) then please report any issues against that higher level application in the first instance. That way the relevant team can triage and determine if the issue lies in Hyperkit and assign as necessary.
If you are using Hyperkit directly then please report issues against this repository.
## Usage
$ hyperkit -h
## Building
$ git clone https://github.com/docker/hyperkit
$ cd hyperkit
$ make
The resulting binary will be in `build/hyperkit`
To enable qcow support in the block backend an OCaml [OPAM](https://opam.ocaml.org) development
environment is required with the qcow module available. A
suitable environment can be setup by installing `opam` and `libev`
via `brew` and using `opam` to install the appropriate libraries:
$ brew install opam libev
$ opam init
$ eval `opam config env`
$ opam install uri qcow.0.8.1 mirage-block-unix.2.6.0 conf-libev logs fmt mirage-unix
Notes:
- `opam config env` must be evaluated each time prior to building
hyperkit so the build will find the ocaml environment.
- Any previous pin of `mirage-block-unix` or `qcow`
should be removed with the commands:
```sh
$ opam update
$ opam pin remove mirage-block-unix
$ opam pin remove qcow
```
## Tracing
HyperKit defines a number of static DTrace probes to simplify investigation of
performance problems. To list the probes supported by your version of HyperKit,
type the following command while HyperKit VM is running:
$ sudo dtrace -l -P 'hyperkit$target' -p $(pgrep hyperkit)
Refer to scripts in dtrace/ directory for examples of possible usage and
available probes.
### Relationship to xhyve and bhyve
HyperKit includes a hypervisor derived from [xhyve](http://www.xhyve.org), which in turn
was derived from [bhyve](http://www.bhyve.org). See the [original xhyve
README](README.xhyve.md) which incorporates the bhyve README.
We try to avoid deviating from these upstreams unnecessarily in order
to more easily share code, for example the various device
models/emulations should be easily shareable.
### Reporting security issues
The maintainers take security seriously. If you discover a security issue,
please bring it to their attention right away!
Please **DO NOT** file a public issue, instead send your report privately to
[security@docker.com](mailto:security@docker.com).
Security reports are greatly appreciated and we will publicly thank you for it.
We also like to send gifts&mdash;if you're into Docker schwag, make sure to let
us know. We currently do not offer a paid security bounty program, but are not
ruling it out in the future.
## Copyright and license
Copyright the authors and contributors. See individual source files
for details.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

224
vendor/github.com/docker/hyperkit/README.xhyve.md generated vendored Normal file
View File

@ -0,0 +1,224 @@
# [xhyve.org](http://www.xhyve.org)
![](./xhyve_logo.png)
<!-- https://thenounproject.com/term/squirrel/57718/ -->
About
-----
The *xhyve hypervisor* is a port of [bhyve](http://www.bhyve.org) to OS X. It is built on top of [Hypervisor.framework](https://developer.apple.com/library/mac/documentation/DriversKernelHardware/Reference/Hypervisor/index.html) in OS X 10.10 Yosemite and higher, runs entirely in userspace, and has no other dependencies. It can run FreeBSD and vanilla Linux distributions and may gain support for other guest operating systems in the future.
License: BSD
Introduction: [http://www.pagetable.com/?p=831](http://www.pagetable.com/?p=831)
Requirements
------------
* OS X 10.10.3 Yosemite or later
* a 2010 or later Mac (i.e. a CPU that supports EPT)
Installation
------------
If you have homebrew, then simply:
$ brew update
$ brew install --HEAD xhyve
The `--HEAD` in the brew command ensures that you always get the latest changes, even if the homebrew database is not yet updated. If for any reason you don't want that simply do `brew install xhyve` .
if not then:
Building
--------
$ git clone https://github.com/mist64/xhyve
$ cd xhyve
$ make
The resulting binary will be in build/xhyve
Usage
-----
$ xhyve -h
What is bhyve?
--------------
bhyve is the FreeBSD hypervisor, roughly analogous to KVM + QEMU on Linux. It has a focus on simplicity and being legacy free.
It exposes the following peripherals to virtual machines:
- Local x(2)APIC
- IO-APIC
- 8259A PIC
- 8253/8254 PIT
- HPET
- PM Timer
- RTC
- PCI
- host bridge
- passthrough
- UART
- AHCI (i.e. HDD and CD)
- VirtIO block device
- VirtIO networking
- VirtIO RNG
Notably absent are sound, USB, HID and any kind of graphics support. With a focus on server virtualization this is not strictly a requirement. bhyve may gain desktop virtualization capabilities in the future but this doesn't seem to be a priority.
Unlike QEMU, bhyve also currently lacks any kind of guest-side firmware (QEMU uses the GPL3 [SeaBIOS](http://www.seabios.org)), but aims to provide a compatible [OVMF EFI](http://www.linux-kvm.org/page/OVMF) in the near future. It does however provide ACPI, SMBIOS and MP Tables.
bhyve architecture
------------------
Linux
I/O VM control FreeBSD NetBSD
OpenBSD
| A | A | |
V | V | V V
+-------------++-------------++-------------++-------------+
| || || || |
| bhyve || bhyvectl || bhyveload || grub2-bhyve |
| || || || |
| || || || |
+-------------++-------------++-------------++-------------+
+----------------------------------------------------------+
| libvmmapi |
+----------------------------------------------------------+
A
| user
------------------------------┼------------------------------
| ioctl FreeBSD kernel
V
+----------------------------+
| VMX/SVM host |
| VMX/SVM guest |
| VMX/SVM nested paging |
| Timers |
| Interrupts |
+----------------------------+
vmm.ko
**vmm.ko**
The bhyve FreeBSD kernel module. Manages VM and vCPU objects, the guest physical address space and handles guest interaction with PIC, PIT, HPET, PM Timer, x(2)APIC and I/O-APIC. Contains a minimal x86 emulator to decode guest MMIO. Executes the two innermost vCPU runloops (VMX/SVM and interrupts/timers/paging). Has backends for Intel VMX and AMD SVM. Provides an ioctl and mmap API to userspace.
**libvmmapi**
Thin abstraction layer between the vmm.ko ioctl interface and the userspace C API.
**bhyve**
The userspace bhyve component (kind of a very light-weight QEMU) that executes virtual machines. Runs the guest I/O vCPU runloops. Manages ACPI, PCI and all non in-kernel devices. Interacts with vmm.ko through libvmmapi.
**bhyvectl**
Somewhat superfluous utility to introspect and manage the life cycle of virtual machines. Virtual machines and vCPUs can exist as kernel objects independently of a bhyve host process. Typically used to delete VM objects after use. Odd architectural choice.
**bhyveload**
Userspace port of the FreeBSD bootloader. Since bhyve still lacks a firmware this is a cumbersome workaround to bootstrap a guest operating system. It creates a VM object, loads the FreeBSD kernel into guest memory, sets up the initial vCPU state and then exits. Only then a VM can be executed by bhyve.
**grub2-bhyve**
Performs the same function as bhyveload but is a userspace port of [GRUB2](http://github.com/grehan-freebsd/grub2-bhyve). It is used to bootstrap guest operating systems other than FreeBSD, i.e. Linux, OpenBSD and NetBSD.
Support for Windows guests is work in progress and dependent on the EFI port.
xhyve architecture
------------------
+----------------------------------------------------------+
| xhyve |
| |
| I/O |
| |
| |
| |
|+--------------------------------------------------------+|
|| vmm VMX guest ||
|| Timers ||
|| Interrupts ||
|+--------------------------------------------------------+|
+----------------------------------------------------------+
+----------------------------------------------------------+
| Hypervisor.framework |
+----------------------------------------------------------+
A
| user
------------------------------┼------------------------------
|syscall xnu kernel
V
VMX host
VMX nested paging
xhyve shares most of the code with bhyve but is architecturally very different. Hypervisor.framework provides an interface to the VMX VMCS guest state and a safe subset of the VMCS control fields, thus making userspace hypervisors without any additional kernel extensions possible. The VMX host state and all aspects of nested paging are handled by the OS X kernel, you can manage the guest physical address space simply through mapping of regions of your own address space.
*xhyve* is equivalent to the *bhyve* process but gains a subset of a userspace port of the vmm kernel module. SVM, PCI passthrough and the VMX host and EPT aspects are dropped. The vmm component provides a libvmmapi compatible interface to xhyve. Hypervisor.framework seems to enforce a strict 1:1 relationship between a host process/VM and host thread/vCPU, that means VMs and vCPUs can only be interacted with by the processes and threads that created them. Therefore, unlike bhyve, xhyve needs to adhere to a single process model. Multiple virtual machines can be created by launching multiple instances of xhyve. xhyve retains most of the bhyve command line interface.
*bhyvectl*, *bhyveload* and *grub2-bhyve* are incompatible with a single process model and are dropped. As a stop-gap solution until we have a proper firmware xhyve supports the Linux [kexec protocol](http://www.kernel.org/doc/Documentation/x86/boot.txt), a very simple and straightforward way to bootstrap a Linux kernel. It takes a bzImage and optionally initrd image and kernel parameter string as input.
Networking
------
If you want the same IP address across VM reboots, assign a UUID to a particular VM:
$ xhyve [-U uuid]
**Optional:**
If you need more advanced networking and already have a configured [TAP](http://tuntaposx.sourceforge.net) device you can use it with:
virtio-tap,tapX
instead of:
virtio-net
Where *X* is your tap device, i.e. */dev/tapX*.
Issues
------
If you are, or were, running any version of VirtualBox, prior to 4.3.30 or 5.0,
and attempt to run xhyve your system will immediately crash as a kernel panic is
triggered. This is due to a VirtualBox bug (that got fixed in newest VirtualBox
versions) as VirtualBox wasn't playing nice with OSX's Hypervisor.framework used
by xhyve.
To get around this you either have to update to newest VirtualBox 4.3 or 5.0 or,
if you for some reason are unable to update, to reboot
your Mac after using VirtualBox and before attempting to use xhyve.
(see issues [#5](https://github.com/mist64/xhyve/issues/5) and
[#9](https://github.com/mist64/xhyve/issues/9) for the full context)
TODO
----
- vmm:
- enable APIC access page to speed up APIC emulation (**performance**)
- enable x2APIC MSRs (even faster) (**performance**)
- vmm_callout:
- is a quick'n'dirty implementation of the FreeBSD kernel callout mechanism
- seems to be racy
- fix races or perhaps replace with something better
- use per vCPU timer event thread (**performance**)?
- use hardware VMX preemption timer instead of `pthread_cond_wait` (**performance**)
- some 32-bit guests are broken (support PAE paging in VMCS)
- PCID guest support (**performance**)
- block_if:
- OS X does not support `preadv`/`pwritev`, we need to serialize reads and writes for the time being until we find a better solution. (**performance**)
- support block devices other than plain files
- virtio_net:
- unify TAP and vmnet backends
- vmnet: make it not require root
- vmnet: send/receive more than a single packet at a time (**performance**)
- virtio_rnd:
- is untested
- remove explicit state transitions:
- since only the owning task/thread can modify the VM/vCPUs a lot of the synchronization might be unnecessary (**performance**)
- performance, performance and performance
- remove vestigial code, cleanup

533
vendor/github.com/docker/hyperkit/go/hyperkit.go generated vendored Normal file
View File

@ -0,0 +1,533 @@
// +build darwin
// Package hyperkit provides a Go wrapper around the hyperkit
// command. It currently shells out to start hyperkit with the
// provided configuration.
//
// Most of the arguments should be self explanatory, but console
// handling deserves a mention. If the Console is configured with
// ConsoleStdio, the hyperkit is started with stdin, stdout, and
// stderr plumbed through to the VM console. If Console is set to
// ConsoleFile hyperkit the console output is redirected to a file and
// console input is disabled. For this mode StateDir has to be set and
// the interactive console is accessible via a 'tty' file created
// there.
//
// Currently this module has some limitations:
// - Only supports zero or one disk image
// - Only support zero or one network interface connected to VPNKit
// - Only kexec boot
//
// This package is currently implemented by shelling out a hyperkit
// process. In the future we may change this to become a wrapper
// around the hyperkit library.
package hyperkit
import (
"bufio"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"github.com/mitchellh/go-ps"
"github.com/rneugeba/iso9660wrap"
)
const (
// ConsoleStdio configures console to use Stdio
ConsoleStdio = iota
// ConsoleFile configures console to a tty and output to a file
ConsoleFile
defaultVPNKitSock = "Library/Containers/com.docker.docker/Data/s50"
defaultDiskImage = "disk.img"
defaultCPUs = 1
defaultMemory = 1024 // 1G
jsonFile = "hyperkit.json"
pidFile = "hyperkit.pid"
)
var defaultHyperKits = []string{"hyperkit",
"com.docker.hyperkit",
"/usr/local/bin/hyperkit",
"/Applications/Docker.app/Contents/MacOS/com.docker.hyperkit"}
// HyperKit contains the configuration of the hyperkit VM
type HyperKit struct {
// HyperKit is the path to the hyperkit binary
HyperKit string `json:"hyperkit"`
// StateDir is the directory where runtime state is kept. If left empty, no state will be kept.
StateDir string `json:"state_dir"`
// VPNKitSock is the location of the VPNKit socket used for networking.
VPNKitSock string `json:"vpnkit_sock"`
// DiskImage is the path to the disk image to use
DiskImage string `json:"disk"`
// ISOImage is the (optional) path to a ISO image to attach
ISOImage string `json:"iso"`
// Kernel is the path to the kernel image to boot
Kernel string `json:"kernel"`
// Initrd is the path to the initial ramdisk to boot off
Initrd string `json:"initrd"`
// CPUs is the number CPUs to configure
CPUs int `json:"cpus"`
// Memory is the amount of megabytes of memory for the VM
Memory int `json:"memory"`
// DiskSize is the size of the disk image in megabytes. If zero and DiskImage does not exist, no disk will be attached.
DiskSize int `json:"disk_size"`
// Console defines where the console of the VM should be
// connected to. ConsoleStdio and ConsoleFile are supported.
Console int `json:"console"`
// UserData, if non empty, will be added to a ISO under the
// filename `config` and passed to the VM.
UserData string `json:"user_data"`
// Below here are internal members, but they are exported so
// that they are written to the state json file, if configured.
// Pid of the hyperkit process
Pid int `json:"pid"`
// Arguments used to execute the hyperkit process
Arguments []string `json:"arguments"`
// CmdLine is a single string of the command line
CmdLine string `json:"cmdline"`
process *os.Process
background bool
log *log.Logger
}
// New creates a template config structure.
// - If hyperkit can't be found an error is returned.
// - If vpnkitsock is empty no networking is configured. If it is set
// to "auto" it tries to re-use the Docker for Mac VPNKit connection.
// - If statedir is "" no state is written to disk.
func New(hyperkit, statedir, vpnkitsock, diskimage string) (*HyperKit, error) {
h := HyperKit{}
var err error
h.HyperKit, err = checkHyperKit(hyperkit)
if err != nil {
return nil, err
}
h.StateDir = statedir
h.VPNKitSock, err = checkVPNKitSock(vpnkitsock)
if err != nil {
return nil, err
}
h.DiskImage = diskimage
h.CPUs = defaultCPUs
h.Memory = defaultMemory
h.Console = ConsoleStdio
h.UserData = ""
return &h, nil
}
// FromState reads a json file from statedir and populates a HyperKit structure.
func FromState(statedir string) (*HyperKit, error) {
b, err := ioutil.ReadFile(filepath.Join(statedir, jsonFile))
if err != nil {
return nil, fmt.Errorf("Can't read json file: ", err)
}
h := &HyperKit{}
err = json.Unmarshal(b, h)
if err != nil {
return nil, fmt.Errorf("Can't parse json file: ", err)
}
// Make sure the pid written by hyperkit is the same as in the json
d, err := ioutil.ReadFile(filepath.Join(statedir, pidFile))
if err != nil {
return nil, err
}
pid, err := strconv.Atoi(string(d[:]))
if err != nil {
return nil, err
}
if h.Pid != pid {
return nil, fmt.Errorf("pids do not match %d != %d", h.Pid, pid)
}
h.process, err = os.FindProcess(h.Pid)
if err != nil {
return nil, err
}
return h, nil
}
// SetLogger sets the log instance to use for the output of the hyperkit process itself (not the console of the VM).
// This is only relevant when Console is set to ConsoleFile
func (h *HyperKit) SetLogger(logger *log.Logger) {
h.log = logger
}
// Run the VM with a given command line until it exits
func (h *HyperKit) Run(cmdline string) error {
h.background = false
return h.execute(cmdline)
}
// Start the VM with a given command line in the background
func (h *HyperKit) Start(cmdline string) error {
h.background = true
return h.execute(cmdline)
}
func (h *HyperKit) execute(cmdline string) error {
var err error
// Sanity checks on configuration
if h.Console == ConsoleFile && h.StateDir == "" {
return fmt.Errorf("If ConsoleFile is set, StateDir was be specified")
}
if h.UserData != "" && h.ISOImage != "" {
return fmt.Errorf("If UserData is supplied, ISOImage must not be set")
}
if h.ISOImage != "" {
if _, err = os.Stat(h.ISOImage); os.IsNotExist(err) {
return fmt.Errorf("ISO %s does not exist", h.ISOImage)
}
}
if h.UserData != "" && h.StateDir == "" {
return fmt.Errorf("If UserData is supplied, StateDir was be specified")
}
if _, err = os.Stat(h.Kernel); os.IsNotExist(err) {
return fmt.Errorf("Kernel %s does not exist", h.Kernel)
}
if _, err = os.Stat(h.Initrd); os.IsNotExist(err) {
return fmt.Errorf("initrd %s does not exist", h.Initrd)
}
if h.DiskImage == "" && h.StateDir == "" && h.DiskSize != 0 {
return fmt.Errorf("Can't create disk, because neither DiskImage nor StateDir is set")
}
// Create files
if h.StateDir != "" {
err = os.MkdirAll(h.StateDir, 0755)
if err != nil {
return err
}
}
if h.DiskImage == "" && h.DiskSize != 0 {
h.DiskImage = filepath.Join(h.StateDir, "disk.img")
}
if _, err = os.Stat(h.DiskImage); os.IsNotExist(err) {
if h.DiskSize != 0 {
err = CreateDiskImage(h.DiskImage, h.DiskSize)
if err != nil {
return err
}
}
}
if h.UserData != "" {
h.ISOImage, err = createUserDataISO(h.StateDir, h.UserData)
if err != nil {
return err
}
}
// Run
h.buildArgs(cmdline)
err = h.execHyperKit()
if err != nil {
return err
}
return nil
}
// Stop the running VM
func (h *HyperKit) Stop() error {
if h.process == nil {
return fmt.Errorf("hyperkit process not known")
}
if !h.IsRunning() {
return nil
}
err := h.process.Kill()
if err != nil {
return err
}
return nil
}
// IsRunning returns true if the hyperkit process is running.
func (h *HyperKit) IsRunning() bool {
// os.FindProcess on Unix always returns a process object even
// if the process does not exists. There does not seem to be
// a call to find out if the process is running either, so we
// use another package to find out.
proc, err := ps.FindProcess(h.Pid)
if err != nil {
return false
}
if proc == nil {
return false
}
return true
}
// Remove deletes all statefiles if present.
// This also removes the StateDir if empty.
// If keepDisk is set, the diskimage will not get removed.
func (h *HyperKit) Remove(keepDisk bool) error {
if h.IsRunning() {
return fmt.Errorf("Can't remove state as process is running")
}
if h.StateDir == "" {
// If there is not state directory we don't mess with the disk
return nil
}
if !keepDisk {
return os.RemoveAll(h.StateDir)
}
files, _ := ioutil.ReadDir(h.StateDir)
for _, f := range files {
fn := filepath.Clean(filepath.Join(h.StateDir, f.Name()))
if fn == h.DiskImage {
continue
}
err := os.Remove(fn)
if err != nil {
return err
}
}
return nil
}
// Convert to json string
func (h *HyperKit) String() string {
s, err := json.Marshal(h)
if err != nil {
return err.Error()
}
return string(s)
}
// CreateDiskImage creates a empty file suitable for use as a disk image for a hyperkit VM.
func CreateDiskImage(location string, sizeMB int) error {
f, err := os.Create(location)
if err != nil {
return err
}
defer f.Close()
buf := make([]byte, 1048676)
for i := 0; i < sizeMB; i++ {
f.Write(buf)
}
return nil
}
func (h *HyperKit) buildArgs(cmdline string) {
a := []string{"-A", "-u"}
if h.StateDir != "" {
a = append(a, "-F", filepath.Join(h.StateDir, pidFile))
}
a = append(a, "-c", fmt.Sprintf("%d", h.CPUs))
a = append(a, "-m", fmt.Sprintf("%dM", h.Memory))
a = append(a, "-s", "0:0,hostbridge")
if h.VPNKitSock != "" {
a = append(a, "-s", fmt.Sprintf("1:0,virtio-vpnkit,path=%s", h.VPNKitSock))
}
if h.DiskImage != "" {
a = append(a, "-s", fmt.Sprintf("2:0,virtio-blk,%s", h.DiskImage))
}
if h.ISOImage != "" {
a = append(a, "-s", fmt.Sprintf("4,ahci-cd,%s", h.ISOImage))
}
a = append(a, "-s", "10,virtio-rnd")
a = append(a, "-s", "31,lpc")
if h.Console == ConsoleFile {
a = append(a, "-l", fmt.Sprintf("com1,autopty=%s/tty,log=%s/console-ring", h.StateDir, h.StateDir))
} else {
a = append(a, "-l", "com1,stdio")
}
kernArgs := fmt.Sprintf("kexec,%s,%s,earlyprintk=serial %s", h.Kernel, h.Initrd, cmdline)
a = append(a, "-f", kernArgs)
h.Arguments = a
h.CmdLine = h.HyperKit + " " + strings.Join(a, " ")
}
// Execute hyperkit and plumb stdin/stdout/stderr.
func (h *HyperKit) execHyperKit() error {
cmd := exec.Command(h.HyperKit, h.Arguments...)
cmd.Env = os.Environ()
// Plumb in stdin/stdout/stderr. If ConsoleStdio is configured
// plumb them to the system streams. If a logger is specified,
// use it for stdout/stderr logging. Otherwise use the default
// /dev/null.
if h.Console == ConsoleStdio {
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
} else if h.log != nil {
stdoutChan := make(chan string)
stderrChan := make(chan string)
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
stream(stdout, stdoutChan)
stream(stderr, stderrChan)
done := make(chan struct{})
go func() {
for {
select {
case stderrl := <-stderrChan:
log.Printf("%s", stderrl)
case stdoutl := <-stdoutChan:
log.Printf("%s", stdoutl)
case <-done:
return
}
}
}()
}
err := cmd.Start()
if err != nil {
return err
}
h.Pid = cmd.Process.Pid
h.process = cmd.Process
err = h.writeState()
if err != nil {
h.process.Kill()
return err
}
if !h.background {
err = cmd.Wait()
if err != nil {
return err
}
}
return nil
}
// writeState write the state to a JSON file
func (h *HyperKit) writeState() error {
if h.StateDir == "" {
// This is not an error
return nil
}
s, err := json.Marshal(h)
if err != nil {
return err
}
return ioutil.WriteFile(filepath.Join(h.StateDir, jsonFile), []byte(s), 0644)
}
func stream(r io.ReadCloser, dest chan<- string) {
go func() {
defer r.Close()
reader := bufio.NewReader(r)
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
dest <- line
}
}()
}
// Create a ISO with Userdata in the specified directory
func createUserDataISO(dir string, init string) (string, error) {
cfgName := filepath.Join(dir, "config")
isoName := cfgName + ".iso"
if err := ioutil.WriteFile(cfgName, []byte(init), 0644); err != nil {
return "", err
}
outfh, err := os.OpenFile(isoName, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if err != nil {
return "", err
}
infh, err := os.Open(cfgName)
if err != nil {
return "", err
}
err = iso9660wrap.WriteFile(outfh, infh)
if err != nil {
return "", err
}
return isoName, nil
}
// checkHyperKit tries to find and/or validate the path of hyperkit
func checkHyperKit(hyperkit string) (string, error) {
if hyperkit != "" {
p, err := exec.LookPath(hyperkit)
if err != nil {
return "", fmt.Errorf("Could not find hyperkit executable: ", hyperkit)
}
return p, nil
}
// Look in a number of default locations
for _, hyperkit := range defaultHyperKits {
p, err := exec.LookPath(hyperkit)
if err == nil {
return p, nil
}
}
return "", fmt.Errorf("Could not find hyperkit executable")
}
// checkVPNKitSock tries to find and/or validate the path of the VPNKit socket
func checkVPNKitSock(vpnkitsock string) (string, error) {
if vpnkitsock == "auto" {
vpnkitsock = filepath.Join(getHome(), defaultVPNKitSock)
}
vpnkitsock = filepath.Clean(vpnkitsock)
_, err := os.Stat(vpnkitsock)
if err != nil {
return "", err
}
return vpnkitsock, nil
}
func getHome() string {
if usr, err := user.Current(); err == nil {
return usr.HomeDir
}
return os.Getenv("HOME")
}

View File

@ -0,0 +1,57 @@
/*-
* Copyright (c) 2012 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
/* if set, create AML instead of ASL and calling out to iasl */
#define ACPITBL_AML 1
#define SCI_INT 9
#define SMI_CMD 0xb2
#define BHYVE_ACPI_ENABLE 0xa0
#define BHYVE_ACPI_DISABLE 0xa1
#define PM1A_EVT_ADDR 0x400
#define PM1A_EVT_ADDR2 0x402
#define PM1A_CNT_ADDR 0x404
#define IO_PMTMR 0x408 /* 4-byte i/o port for the timer */
int acpi_build(int ncpu);
void dsdt_line(const char *fmt, ...);
void dsdt_fixed_ioport(uint16_t iobase, uint16_t length);
void dsdt_fixed_irq(uint8_t irq);
void dsdt_fixed_mem32(uint32_t base, uint32_t length);
void dsdt_indent(int levels);
void dsdt_unindent(int levels);
void dsdt_fixup(int bus, uint16_t iobase, uint16_t iolimit, uint32_t membase32,
uint32_t memlimit32, uint64_t membase64, uint64_t memlimit64);
void sci_init(void);

View File

@ -0,0 +1,319 @@
/*-
* Copyright (c) 1998 - 2008 Søren Schmidt <sos@FreeBSD.org>
* Copyright (c) 2009-2012 Alexander Motin <mav@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer,
* without modification, immediately at the beginning of the file.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
/* ATA register defines */
#define ATA_DATA 0 /* (RW) data */
#define ATA_FEATURE 1 /* (W) feature */
#define ATA_F_DMA 0x01 /* enable DMA */
#define ATA_F_OVL 0x02 /* enable overlap */
#define ATA_COUNT 2 /* (W) sector count */
#define ATA_SECTOR 3 /* (RW) sector # */
#define ATA_CYL_LSB 4 /* (RW) cylinder# LSB */
#define ATA_CYL_MSB 5 /* (RW) cylinder# MSB */
#define ATA_DRIVE 6 /* (W) Sector/Drive/Head */
#define ATA_D_LBA 0x40 /* use LBA addressing */
#define ATA_D_IBM 0xa0 /* 512 byte sectors, ECC */
#define ATA_COMMAND 7 /* (W) command */
#define ATA_ERROR 8 /* (R) error */
#define ATA_E_ILI 0x01 /* illegal length */
#define ATA_E_NM 0x02 /* no media */
#define ATA_E_ABORT 0x04 /* command aborted */
#define ATA_E_MCR 0x08 /* media change request */
#define ATA_E_IDNF 0x10 /* ID not found */
#define ATA_E_MC 0x20 /* media changed */
#define ATA_E_UNC 0x40 /* uncorrectable data */
#define ATA_E_ICRC 0x80 /* UDMA crc error */
#define ATA_E_ATAPI_SENSE_MASK 0xf0 /* ATAPI sense key mask */
#define ATA_IREASON 9 /* (R) interrupt reason */
#define ATA_I_CMD 0x01 /* cmd (1) | data (0) */
#define ATA_I_IN 0x02 /* read (1) | write (0) */
#define ATA_I_RELEASE 0x04 /* released bus (1) */
#define ATA_I_TAGMASK 0xf8 /* tag mask */
#define ATA_STATUS 10 /* (R) status */
#define ATA_ALTSTAT 11 /* (R) alternate status */
#define ATA_S_ERROR 0x01 /* error */
#define ATA_S_INDEX 0x02 /* index */
#define ATA_S_CORR 0x04 /* data corrected */
#define ATA_S_DRQ 0x08 /* data request */
#define ATA_S_DSC 0x10 /* drive seek completed */
#define ATA_S_SERVICE 0x10 /* drive needs service */
#define ATA_S_DWF 0x20 /* drive write fault */
#define ATA_S_DMA 0x20 /* DMA ready */
#define ATA_S_READY 0x40 /* drive ready */
#define ATA_S_BUSY 0x80 /* busy */
#define ATA_CONTROL 12 /* (W) control */
#define ATA_A_IDS 0x02 /* disable interrupts */
#define ATA_A_RESET 0x04 /* RESET controller */
#define ATA_A_4BIT 0x08 /* 4 head bits */
#define ATA_A_HOB 0x80 /* High Order Byte enable */
/* SATA register defines */
#define ATA_SSTATUS 13
#define ATA_SS_DET_MASK 0x0000000f
#define ATA_SS_DET_NO_DEVICE 0x00000000
#define ATA_SS_DET_DEV_PRESENT 0x00000001
#define ATA_SS_DET_PHY_ONLINE 0x00000003
#define ATA_SS_DET_PHY_OFFLINE 0x00000004
#define ATA_SS_SPD_MASK 0x000000f0
#define ATA_SS_SPD_NO_SPEED 0x00000000
#define ATA_SS_SPD_GEN1 0x00000010
#define ATA_SS_SPD_GEN2 0x00000020
#define ATA_SS_SPD_GEN3 0x00000030
#define ATA_SS_IPM_MASK 0x00000f00
#define ATA_SS_IPM_NO_DEVICE 0x00000000
#define ATA_SS_IPM_ACTIVE 0x00000100
#define ATA_SS_IPM_PARTIAL 0x00000200
#define ATA_SS_IPM_SLUMBER 0x00000600
#define ATA_SS_IPM_DEVSLEEP 0x00000800
#define ATA_SERROR 14
#define ATA_SE_DATA_CORRECTED 0x00000001
#define ATA_SE_COMM_CORRECTED 0x00000002
#define ATA_SE_DATA_ERR 0x00000100
#define ATA_SE_COMM_ERR 0x00000200
#define ATA_SE_PROT_ERR 0x00000400
#define ATA_SE_HOST_ERR 0x00000800
#define ATA_SE_PHY_CHANGED 0x00010000
#define ATA_SE_PHY_IERROR 0x00020000
#define ATA_SE_COMM_WAKE 0x00040000
#define ATA_SE_DECODE_ERR 0x00080000
#define ATA_SE_PARITY_ERR 0x00100000
#define ATA_SE_CRC_ERR 0x00200000
#define ATA_SE_HANDSHAKE_ERR 0x00400000
#define ATA_SE_LINKSEQ_ERR 0x00800000
#define ATA_SE_TRANSPORT_ERR 0x01000000
#define ATA_SE_UNKNOWN_FIS 0x02000000
#define ATA_SE_EXCHANGED 0x04000000
#define ATA_SCONTROL 15
#define ATA_SC_DET_MASK 0x0000000f
#define ATA_SC_DET_IDLE 0x00000000
#define ATA_SC_DET_RESET 0x00000001
#define ATA_SC_DET_DISABLE 0x00000004
#define ATA_SC_SPD_MASK 0x000000f0
#define ATA_SC_SPD_NO_SPEED 0x00000000
#define ATA_SC_SPD_SPEED_GEN1 0x00000010
#define ATA_SC_SPD_SPEED_GEN2 0x00000020
#define ATA_SC_SPD_SPEED_GEN3 0x00000030
#define ATA_SC_IPM_MASK 0x00000f00
#define ATA_SC_IPM_NONE 0x00000000
#define ATA_SC_IPM_DIS_PARTIAL 0x00000100
#define ATA_SC_IPM_DIS_SLUMBER 0x00000200
#define ATA_SC_IPM_DIS_DEVSLEEP 0x00000400
#define ATA_SACTIVE 16
#define AHCI_MAX_PORTS 32
#define AHCI_MAX_SLOTS 32
#define AHCI_MAX_IRQS 16
/* SATA AHCI v1.0 register defines */
#define AHCI_CAP 0x00
#define AHCI_CAP_NPMASK 0x0000001f
#define AHCI_CAP_SXS 0x00000020
#define AHCI_CAP_EMS 0x00000040
#define AHCI_CAP_CCCS 0x00000080
#define AHCI_CAP_NCS 0x00001F00
#define AHCI_CAP_NCS_SHIFT 8
#define AHCI_CAP_PSC 0x00002000
#define AHCI_CAP_SSC 0x00004000
#define AHCI_CAP_PMD 0x00008000
#define AHCI_CAP_FBSS 0x00010000
#define AHCI_CAP_SPM 0x00020000
#define AHCI_CAP_SAM 0x00080000
#define AHCI_CAP_ISS 0x00F00000
#define AHCI_CAP_ISS_SHIFT 20
#define AHCI_CAP_SCLO 0x01000000
#define AHCI_CAP_SAL 0x02000000
#define AHCI_CAP_SALP 0x04000000
#define AHCI_CAP_SSS 0x08000000
#define AHCI_CAP_SMPS 0x10000000
#define AHCI_CAP_SSNTF 0x20000000
#define AHCI_CAP_SNCQ 0x40000000
#define AHCI_CAP_64BIT 0x80000000
#define AHCI_GHC 0x04
#define AHCI_GHC_AE 0x80000000
#define AHCI_GHC_MRSM 0x00000004
#define AHCI_GHC_IE 0x00000002
#define AHCI_GHC_HR 0x00000001
#define AHCI_IS 0x08
#define AHCI_PI 0x0c
#define AHCI_VS 0x10
#define AHCI_CCCC 0x14
#define AHCI_CCCC_TV_MASK 0xffff0000
#define AHCI_CCCC_TV_SHIFT 16
#define AHCI_CCCC_CC_MASK 0x0000ff00
#define AHCI_CCCC_CC_SHIFT 8
#define AHCI_CCCC_INT_MASK 0x000000f8
#define AHCI_CCCC_INT_SHIFT 3
#define AHCI_CCCC_EN 0x00000001
#define AHCI_CCCP 0x18
#define AHCI_EM_LOC 0x1C
#define AHCI_EM_CTL 0x20
#define AHCI_EM_MR 0x00000001
#define AHCI_EM_TM 0x00000100
#define AHCI_EM_RST 0x00000200
#define AHCI_EM_LED 0x00010000
#define AHCI_EM_SAFTE 0x00020000
#define AHCI_EM_SES2 0x00040000
#define AHCI_EM_SGPIO 0x00080000
#define AHCI_EM_SMB 0x01000000
#define AHCI_EM_XMT 0x02000000
#define AHCI_EM_ALHD 0x04000000
#define AHCI_EM_PM 0x08000000
#define AHCI_CAP2 0x24
#define AHCI_CAP2_BOH 0x00000001
#define AHCI_CAP2_NVMP 0x00000002
#define AHCI_CAP2_APST 0x00000004
#define AHCI_CAP2_SDS 0x00000008
#define AHCI_CAP2_SADM 0x00000010
#define AHCI_CAP2_DESO 0x00000020
#define AHCI_OFFSET 0x100
#define AHCI_STEP 0x80
#define AHCI_P_CLB 0x00
#define AHCI_P_CLBU 0x04
#define AHCI_P_FB 0x08
#define AHCI_P_FBU 0x0c
#define AHCI_P_IS 0x10
#define AHCI_P_IE 0x14
#define AHCI_P_IX_DHR 0x00000001
#define AHCI_P_IX_PS 0x00000002
#define AHCI_P_IX_DS 0x00000004
#define AHCI_P_IX_SDB 0x00000008
#define AHCI_P_IX_UF 0x00000010
#define AHCI_P_IX_DP 0x00000020
#define AHCI_P_IX_PC 0x00000040
#define AHCI_P_IX_MP 0x00000080
#define AHCI_P_IX_PRC 0x00400000
#define AHCI_P_IX_IPM 0x00800000
#define AHCI_P_IX_OF 0x01000000
#define AHCI_P_IX_INF 0x04000000
#define AHCI_P_IX_IF 0x08000000
#define AHCI_P_IX_HBD 0x10000000
#define AHCI_P_IX_HBF 0x20000000
#define AHCI_P_IX_TFE 0x40000000
#define AHCI_P_IX_CPD 0x80000000
#define AHCI_P_CMD 0x18
#define AHCI_P_CMD_ST 0x00000001
#define AHCI_P_CMD_SUD 0x00000002
#define AHCI_P_CMD_POD 0x00000004
#define AHCI_P_CMD_CLO 0x00000008
#define AHCI_P_CMD_FRE 0x00000010
#define AHCI_P_CMD_CCS_MASK 0x00001f00
#define AHCI_P_CMD_CCS_SHIFT 8
#define AHCI_P_CMD_ISS 0x00002000
#define AHCI_P_CMD_FR 0x00004000
#define AHCI_P_CMD_CR 0x00008000
#define AHCI_P_CMD_CPS 0x00010000
#define AHCI_P_CMD_PMA 0x00020000
#define AHCI_P_CMD_HPCP 0x00040000
#define AHCI_P_CMD_MPSP 0x00080000
#define AHCI_P_CMD_CPD 0x00100000
#define AHCI_P_CMD_ESP 0x00200000
#define AHCI_P_CMD_FBSCP 0x00400000
#define AHCI_P_CMD_APSTE 0x00800000
#define AHCI_P_CMD_ATAPI 0x01000000
#define AHCI_P_CMD_DLAE 0x02000000
#define AHCI_P_CMD_ALPE 0x04000000
#define AHCI_P_CMD_ASP 0x08000000
#define AHCI_P_CMD_ICC_MASK 0xf0000000
#define AHCI_P_CMD_NOOP 0x00000000
#define AHCI_P_CMD_ACTIVE 0x10000000
#define AHCI_P_CMD_PARTIAL 0x20000000
#define AHCI_P_CMD_SLUMBER 0x60000000
#define AHCI_P_CMD_DEVSLEEP 0x80000000
#define AHCI_P_TFD 0x20
#define AHCI_P_SIG 0x24
#define AHCI_P_SSTS 0x28
#define AHCI_P_SCTL 0x2c
#define AHCI_P_SERR 0x30
#define AHCI_P_SACT 0x34
#define AHCI_P_CI 0x38
#define AHCI_P_SNTF 0x3C
#define AHCI_P_FBS 0x40
#define AHCI_P_FBS_EN 0x00000001
#define AHCI_P_FBS_DEC 0x00000002
#define AHCI_P_FBS_SDE 0x00000004
#define AHCI_P_FBS_DEV 0x00000f00
#define AHCI_P_FBS_DEV_SHIFT 8
#define AHCI_P_FBS_ADO 0x0000f000
#define AHCI_P_FBS_ADO_SHIFT 12
#define AHCI_P_FBS_DWE 0x000f0000
#define AHCI_P_FBS_DWE_SHIFT 16
#define AHCI_P_DEVSLP 0x44
#define AHCI_P_DEVSLP_ADSE 0x00000001
#define AHCI_P_DEVSLP_DSP 0x00000002
#define AHCI_P_DEVSLP_DETO 0x000003fc
#define AHCI_P_DEVSLP_DETO_SHIFT 2
#define AHCI_P_DEVSLP_MDAT 0x00007c00
#define AHCI_P_DEVSLP_MDAT_SHIFT 10
#define AHCI_P_DEVSLP_DITO 0x01ff8000
#define AHCI_P_DEVSLP_DITO_SHIFT 15
#define AHCI_P_DEVSLP_DM 0x0e000000
#define AHCI_P_DEVSLP_DM_SHIFT 25
/* Just to be sure, if building as module. */
#if MAXPHYS < 512 * 1024
#undef MAXPHYS
#define MAXPHYS 512 * 1024
#endif
/* Pessimistic prognosis on number of required S/G entries */
#define AHCI_SG_ENTRIES (roundup(btoc(MAXPHYS) + 1, 8))
/* Command list. 32 commands. First, 1Kbyte aligned. */
#define AHCI_CL_OFFSET 0
#define AHCI_CL_SIZE 32
/* Command tables. Up to 32 commands, Each, 128byte aligned. */
#define AHCI_CT_OFFSET (AHCI_CL_OFFSET + AHCI_CL_SIZE * AHCI_MAX_SLOTS)
#define AHCI_CT_SIZE (128 + AHCI_SG_ENTRIES * 16)
/* Total main work area. */
#define AHCI_WORK_SIZE (AHCI_CT_OFFSET + AHCI_CT_SIZE * ch->numslots)

View File

@ -0,0 +1,66 @@
/*-
* Copyright (c) 2013 Peter Grehan <grehan@freebsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
/*
* The block API to be used by bhyve block-device emulations. The routines
* are thread safe, with no assumptions about the context of the completion
* callback - it may occur in the caller's context, or asynchronously in
* another thread.
*/
#pragma once
#include <sys/uio.h>
#include <sys/unistd.h>
#define BLOCKIF_IOV_MAX (128-2) /* not practical to be IOV_MAX */
struct blockif_req {
struct iovec br_iov[BLOCKIF_IOV_MAX];
int br_iovcnt;
off_t br_offset;
ssize_t br_resid;
void (*br_callback)(struct blockif_req *req, int err);
void *br_param;
};
struct blockif_ctxt;
struct blockif_ctxt *blockif_open(const char *optstr, const char *ident);
off_t blockif_size(struct blockif_ctxt *bc);
void blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s);
int blockif_sectsz(struct blockif_ctxt *bc);
void blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off);
int blockif_queuesz(struct blockif_ctxt *bc);
int blockif_is_ro(struct blockif_ctxt *bc);
int blockif_candelete(struct blockif_ctxt *bc);
int blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq);
int blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq);
int blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq);
int blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq);
int blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq);
int blockif_close(struct blockif_ctxt *bc);

View File

@ -0,0 +1,31 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
void init_dbgport(int port);

View File

@ -0,0 +1,8 @@
#pragma once
#include <stdint.h>
#include <stdbool.h>
void bootrom_init(const char *bootrom_path);
uint64_t bootrom_load(void);
bool bootrom_contains_gpa(uint64_t gpa);

View File

@ -0,0 +1,102 @@
#pragma once
#include <stdint.h>
/*
* USERBOOT interface versions
*/
#define USERBOOT_VERSION_1 1
#define USERBOOT_VERSION_2 2
#define USERBOOT_VERSION_3 3
/*
* Exit codes from the loader
*/
#define USERBOOT_EXIT_QUIT 1
#define USERBOOT_EXIT_REBOOT 2
struct loader_callbacks {
/* Console i/o */
/* Wait until a key is pressed on the console and then return it */
int (*getc)(void *arg);
/* Write the character ch to the console */
void (*putc)(void *arg, int ch);
/* Return non-zero if a key can be read from the console */
int (*poll)(void *arg);
/* Host filesystem i/o */
/* Open a file in the host filesystem */
int (*open)(void *arg, const char *filename, void **h_return);
/* Close a file */
int (*close)(void *arg, void *h);
/* Return non-zero if the file is a directory */
int (*isdir)(void *arg, void *h);
/* Read size bytes from a file. The number of bytes remaining in dst after
* reading is returned in *resid_return
*/
int (*read)(void *arg, void *h, void *dst, size_t size,
size_t *resid_return);
/* Read an entry from a directory. The entry's inode number is returned in
* fileno_return, its type in *type_return and the name length in
* *namelen_return. The name itself is copied to the buffer name which must
* be at least PATH_MAX in size.
*/
int (*readdir)(void *arg, void *h, uint32_t *fileno_return,
uint8_t *type_return, size_t *namelen_return, char *name);
/* Seek to a location within an open file */
int (*seek)(void *arg, void *h, uint64_t offset, int whence);
/* Return some stat(2) related information about the file */
int (*stat)(void *arg, void *h, int *mode_return, int *uid_return,
int *gid_return, uint64_t *size_return);
/* Disk image i/o */
/* Read from a disk image at the given offset */
int (*diskread)(void *arg, int unit, uint64_t offset, void *dst,
size_t size, size_t *resid_return);
/* Guest virtual machine i/o */
/* Copy to the guest address space */
int (*copyin)(void *arg, const void *from, uint64_t to, size_t size);
/* Copy from the guest address space */
int (*copyout)(void *arg, uint64_t from, void *to, size_t size);
/* Set a guest register value */
void (*setreg)(void *arg, int, uint64_t);
/* Set a guest MSR value */
void (*setmsr)(void *arg, int, uint64_t);
/* Set a guest CR value */
void (*setcr)(void *arg, int, uint64_t);
/* Set the guest GDT address */
void (*setgdt)(void *arg, uint64_t, size_t);
/* Transfer control to the guest at the given address */
void (*exec)(void *arg, uint64_t pc);
/* Misc */
/* Sleep for usec microseconds */
void (*delay)(void *arg, int usec);
/* Exit with the given exit code */
void (*exit)(void);
/* Return guest physical memory map details */
void (*getmem)(void *arg, uint64_t *lowmem, uint64_t *highmem);
/* ioctl interface to the disk device */
int (*diskioctl)(void *arg, int unit, u_long cmd, void *data);
/*
* Returns an environment variable in the form "name=value".
*
* If there are no more variables that need to be set in the
* loader environment then return NULL.
*
* 'num' is used as a handle for the callback to identify which
* environment variable to return next. It will begin at 0 and
* each invocation will add 1 to the previous value of 'num'.
*/
const char * (*getenv)(void *arg, int num);
};
void fbsd_init(char *userboot_path, char *bootvolume_path, char *kernelenv,
char *cons);
uint64_t fbsd_load(void);

View File

@ -0,0 +1,86 @@
#pragma once
#include <stdint.h>
struct setup_header {
uint8_t setup_sects; /* The size of the setup in sectors */
uint16_t root_flags; /* If set, the root is mounted readonly */
uint32_t syssize; /* The size of the 32-bit code in 16-byte paras */
uint16_t ram_size; /* DO NOT USE - for bootsect.S use only */
uint16_t vid_mode; /* Video mode control */
uint16_t root_dev; /* Default root device number */
uint16_t boot_flag; /* 0xAA55 magic number */
uint16_t jump; /* Jump instruction */
uint32_t header; /* Magic signature "HdrS" */
uint16_t version; /* Boot protocol version supported */
uint32_t realmode_swtch; /* Boot loader hook (see below) */
uint16_t start_sys_seg; /* The load-low segment (0x1000) (obsolete) */
uint16_t kernel_version; /* Pointer to kernel version string */
uint8_t type_of_loader; /* Boot loader identifier */
uint8_t loadflags; /* Boot protocol option flags */
uint16_t setup_move_size; /* Move to high memory size (used with hooks) */
uint32_t code32_start; /* Boot loader hook (see below) */
uint32_t ramdisk_image; /* initrd load address (set by boot loader) */
uint32_t ramdisk_size; /* initrd size (set by boot loader) */
uint32_t bootsect_kludge; /* DO NOT USE - for bootsect.S use only */
uint16_t heap_end_ptr; /* Free memory after setup end */
uint8_t ext_loader_ver; /* Extended boot loader version */
uint8_t ext_loader_type; /* Extended boot loader ID */
uint32_t cmd_line_ptr; /* 32-bit pointer to the kernel command line */
uint32_t initrd_addr_max; /* Highest legal initrd address */
uint32_t kernel_alignment; /* Physical addr alignment required for kernel */
uint8_t relocatable_kernel; /* Whether kernel is relocatable or not */
uint8_t min_alignment; /* Minimum alignment, as a power of two */
uint16_t xloadflags; /* Boot protocol option flags */
uint32_t cmdline_size; /* Maximum size of the kernel command line */
uint32_t hardware_subarch; /* Hardware subarchitecture */
uint64_t hardware_subarch_data; /* Subarchitecture-specific data */
uint32_t payload_offset; /* Offset of kernel payload */
uint32_t payload_length; /* Length of kernel payload */
uint64_t setup_data; /* 64bit pointer to linked list of struct setup_data */
uint64_t pref_address; /* Preferred loading address */
uint32_t init_size; /* Linear memory required during initialization */
uint32_t handover_offset; /* Offset of handover entry point */
} __attribute__((packed));
struct zero_page {
uint8_t screen_info[64];
uint8_t apm_bios_info[20];
uint8_t _0[4];
uint64_t tboot_addr;
uint8_t ist_info[16];
uint8_t _1[16];
uint8_t hd0_info[16];
uint8_t hd1_info[16];
uint8_t sys_desc_table[16];
uint8_t olpc_ofw_header[16];
uint32_t ext_ramdisk_image;
uint32_t ext_ramdisk_size;
uint32_t ext_cmd_line_ptr;
uint8_t _2[116];
uint8_t edid_info[128];
uint8_t efi_info[32];
uint32_t alt_mem_k;
uint32_t scratch;
uint8_t e820_entries;
uint8_t eddbuf_entries;
uint8_t edd_mbr_sig_buf_entries;
uint8_t kbd_status;
uint8_t _3[3];
uint8_t sentinel;
uint8_t _4[1];
struct setup_header setup_header;
uint8_t _5[(0x290 - 0x1f1 - sizeof(struct setup_header))];
uint32_t edd_mbr_sig_buffer[16];
struct {
uint64_t addr;
uint64_t size;
uint32_t type;
} __attribute__((packed)) e820_map[128];
uint8_t _6[48];
uint8_t eddbuf[492];
uint8_t _7[276];
} __attribute__((packed));
void kexec_init(char *kernel_path, char *initrd_path, char *cmdline);
uint64_t kexec(void);

View File

@ -0,0 +1,76 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <xhyve/support/linker_set.h>
struct vm_exit;
/*
* inout emulation handlers return 0 on success and -1 on failure.
*/
typedef int (*inout_func_t)(int vcpu, int in, int port,
int bytes, uint32_t *eax, void *arg);
struct inout_port {
const char *name;
int port;
int size;
int flags;
inout_func_t handler;
void *arg;
};
#define IOPORT_F_IN 0x1
#define IOPORT_F_OUT 0x2
#define IOPORT_F_INOUT (IOPORT_F_IN | IOPORT_F_OUT)
/*
* The following flags are used internally and must not be used by
* device models.
*/
#define IOPORT_F_DEFAULT 0x80000000 /* claimed by default handler */
#define INOUT_PORT(name, port, flags, handler) \
static struct inout_port __CONCAT(__inout_port, port) = { \
#name, \
(port), \
1, \
(flags), \
(handler), \
0 \
}; \
DATA_SET(inout_port_set, __CONCAT(__inout_port, port))
void init_inout(void);
int emulate_inout(int vcpu, struct vm_exit *vmexit, int strict);
int register_inout(struct inout_port *iop);
int unregister_inout(struct inout_port *iop);
void init_bvmcons(void);

View File

@ -0,0 +1,36 @@
/*-
* Copyright (c) 2014 Hudson River Trading LLC
* Written by: John H. Baldwin <jhb@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
/*
* Allocate a PCI IRQ from the I/O APIC.
*/
void ioapic_init(void);
int ioapic_pci_alloc_irq(void);

View File

@ -0,0 +1,58 @@
/*-
* Copyright (c) 2012 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <xhyve/support/linker_set.h>
typedef int (*mem_func_t)(int vcpu, int dir, uint64_t addr, int size,
uint64_t *val, void *arg1, long arg2);
struct mem_range {
const char *name;
int flags;
mem_func_t handler;
void *arg1;
long arg2;
uint64_t base;
uint64_t size;
};
#define MEM_F_READ 0x1
#define MEM_F_WRITE 0x2
#define MEM_F_RW 0x3
#define MEM_F_IMMUTABLE 0x4 /* mem_range cannot be unregistered */
void init_mem(void);
int emulate_mem(int vcpu, uint64_t paddr, struct vie *vie,
struct vm_guest_paging *paging);
int register_mem(struct mem_range *memp);
int register_mem_fallback(struct mem_range *memp);
int unregister_mem(struct mem_range *memp);

View File

@ -0,0 +1,47 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
enum ev_type {
EVF_READ,
EVF_WRITE,
EVF_TIMER,
EVF_SIGNAL
};
struct mevent;
struct mevent *mevent_add(int fd, enum ev_type type,
void (*func)(int, enum ev_type, void *), void *param);
int mevent_enable(struct mevent *evp);
int mevent_disable(struct mevent *evp);
int mevent_delete(struct mevent *evp);
int mevent_delete_close(struct mevent *evp);
void mevent_dispatch(void);

View File

@ -0,0 +1,32 @@
/*-
* Copyright (c) 2012 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
int mptable_build(int ncpu);
void mptable_add_oemtbl(void *tbl, int tblsz);

View File

@ -0,0 +1,269 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <pthread.h>
#include <assert.h>
#include <xhyve/support/misc.h>
#include <xhyve/support/pcireg.h>
#include <xhyve/support/linker_set.h>
#define PCI_BARMAX PCIR_MAX_BAR_0 /* BAR registers in a Type 0 header */
struct pci_devinst;
struct memory_region;
struct pci_devemu {
/* name of device emulation */
char *pe_emu;
/* instance creation */
int (*pe_init)(struct pci_devinst *, char *opts);
/* ACPI DSDT enumeration */
void (*pe_write_dsdt)(struct pci_devinst *);
/* config space read/write callbacks */
int (*pe_cfgwrite)(int vcpu, struct pci_devinst *pi,
int offset, int bytes, uint32_t val);
int (*pe_cfgread)(int vcpu, struct pci_devinst *pi, int offset, int bytes,
uint32_t *retval);
/* BAR read/write callbacks */
void (*pe_barwrite)(int vcpu, struct pci_devinst *pi, int baridx,
uint64_t offset, int size, uint64_t value);
uint64_t (*pe_barread)(int vcpu, struct pci_devinst *pi, int baridx,
uint64_t offset, int size);
};
#define PCI_EMUL_SET(x) DATA_SET(pci_devemu_set, x)
enum pcibar_type {
PCIBAR_NONE,
PCIBAR_IO,
PCIBAR_MEM32,
PCIBAR_MEM64,
PCIBAR_MEMHI64
};
struct pcibar {
enum pcibar_type type; /* io or memory */
uint64_t size;
uint64_t addr;
};
#define PI_NAMESZ 40
struct msix_table_entry {
uint64_t addr;
uint32_t msg_data;
uint32_t vector_control;
};
/*
* In case the structure is modified to hold extra information, use a define
* for the size that should be emulated.
*/
#define MSIX_TABLE_ENTRY_SIZE 16
#define MAX_MSIX_TABLE_ENTRIES 2048
#define PBA_SIZE(msgnum) (roundup2((msgnum), 64) / 8)
enum lintr_stat {
IDLE,
ASSERTED,
PENDING
};
struct pci_devinst {
struct pci_devemu *pi_d;
uint8_t pi_bus, pi_slot, pi_func;
char pi_name[PI_NAMESZ];
int pi_bar_getsize;
int pi_prevcap;
int pi_capend;
struct {
int8_t pin;
enum lintr_stat state;
int pirq_pin;
int ioapic_irq;
pthread_mutex_t lock;
} pi_lintr;
struct {
int enabled;
uint64_t addr;
uint64_t msg_data;
int maxmsgnum;
} pi_msi;
struct {
int enabled;
int table_bar;
int pba_bar;
uint32_t table_offset;
int table_count;
uint32_t pba_offset;
int pba_size;
int function_mask;
struct msix_table_entry *table; /* allocated at runtime */
} pi_msix;
void *pi_arg; /* devemu-private data */
u_char pi_cfgdata[PCI_REGMAX + 1];
struct pcibar pi_bar[PCI_BARMAX + 1];
};
struct msicap {
uint8_t capid;
uint8_t nextptr;
uint16_t msgctrl;
uint32_t addrlo;
uint32_t addrhi;
uint16_t msgdata;
} __packed;
struct msixcap {
uint8_t capid;
uint8_t nextptr;
uint16_t msgctrl;
uint32_t table_info; /* bar index and offset within it */
uint32_t pba_info; /* bar index and offset within it */
} __packed;
struct pciecap {
uint8_t capid;
uint8_t nextptr;
uint16_t pcie_capabilities;
uint32_t dev_capabilities; /* all devices */
uint16_t dev_control;
uint16_t dev_status;
uint32_t link_capabilities; /* devices with links */
uint16_t link_control;
uint16_t link_status;
uint32_t slot_capabilities; /* ports with slots */
uint16_t slot_control;
uint16_t slot_status;
uint16_t root_control; /* root ports */
uint16_t root_capabilities;
uint32_t root_status;
uint32_t dev_capabilities2; /* all devices */
uint16_t dev_control2;
uint16_t dev_status2;
uint32_t link_capabilities2; /* devices with links */
uint16_t link_control2;
uint16_t link_status2;
uint32_t slot_capabilities2; /* ports with slots */
uint16_t slot_control2;
uint16_t slot_status2;
} __packed;
typedef void (*pci_lintr_cb)(int b, int s, int pin, int pirq_pin,
int ioapic_irq, void *arg);
int init_pci(void);
void msicap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
int bytes, uint32_t val);
void msixcap_cfgwrite(struct pci_devinst *pi, int capoff, int offset,
int bytes, uint32_t val);
void pci_callback(void);
int pci_emul_alloc_bar(struct pci_devinst *pdi, int idx,
enum pcibar_type type, uint64_t size);
int pci_emul_alloc_pbar(struct pci_devinst *pdi, int idx,
uint64_t hostbase, enum pcibar_type type, uint64_t size);
int pci_emul_add_msicap(struct pci_devinst *pi, int msgnum);
int pci_emul_add_pciecap(struct pci_devinst *pi, int pcie_device_type);
void pci_generate_msi(struct pci_devinst *pi, int msgnum);
void pci_generate_msix(struct pci_devinst *pi, int msgnum);
void pci_lintr_assert(struct pci_devinst *pi);
void pci_lintr_deassert(struct pci_devinst *pi);
void pci_lintr_request(struct pci_devinst *pi);
int pci_msi_enabled(struct pci_devinst *pi);
int pci_msix_enabled(struct pci_devinst *pi);
int pci_msix_table_bar(struct pci_devinst *pi);
int pci_msix_pba_bar(struct pci_devinst *pi);
int pci_msi_msgnum(struct pci_devinst *pi);
int pci_parse_slot(char *opt);
void pci_populate_msicap(struct msicap *cap, int msgs, int nextptr);
int pci_emul_add_msixcap(struct pci_devinst *pi, int msgnum, int barnum);
int pci_emul_msix_twrite(struct pci_devinst *pi, uint64_t offset, int size,
uint64_t value);
uint64_t pci_emul_msix_tread(struct pci_devinst *pi, uint64_t offset, int size);
int pci_count_lintr(int bus);
void pci_walk_lintr(int bus, pci_lintr_cb cb, void *arg);
void pci_write_dsdt(void);
uint64_t pci_ecfg_base(void);
int pci_bus_configured(int bus);
static __inline void
pci_set_cfgdata8(struct pci_devinst *pi, int offset, uint8_t val)
{
assert(offset <= PCI_REGMAX);
*(uint8_t *)(((uintptr_t) &pi->pi_cfgdata) + ((unsigned) offset)) = val;
}
static __inline void
pci_set_cfgdata16(struct pci_devinst *pi, int offset, uint16_t val)
{
assert(offset <= (PCI_REGMAX - 1) && (offset & 1) == 0);
*(uint16_t *)(((uintptr_t) &pi->pi_cfgdata) + ((unsigned) offset)) = val;
}
static __inline void
pci_set_cfgdata32(struct pci_devinst *pi, int offset, uint32_t val)
{
assert(offset <= (PCI_REGMAX - 3) && (offset & 3) == 0);
*(uint32_t *)(((uintptr_t) &pi->pi_cfgdata) + ((unsigned) offset)) = val;
}
static __inline uint8_t
pci_get_cfgdata8(struct pci_devinst *pi, int offset)
{
assert(offset <= PCI_REGMAX);
return (*(uint8_t *)(((uintptr_t) &pi->pi_cfgdata) + ((unsigned) offset)));
}
static __inline uint16_t
pci_get_cfgdata16(struct pci_devinst *pi, int offset)
{
assert(offset <= (PCI_REGMAX - 1) && (offset & 1) == 0);
return (*(uint16_t *)(((uintptr_t) &pi->pi_cfgdata) + ((unsigned) offset)));
}
static __inline uint32_t
pci_get_cfgdata32(struct pci_devinst *pi, int offset)
{
assert(offset <= (PCI_REGMAX - 3) && (offset & 3) == 0);
return (*(uint32_t *)(((uintptr_t) &pi->pi_cfgdata) + ((unsigned) offset)));
}

View File

@ -0,0 +1,42 @@
/*-
* Copyright (c) 2014 Hudson River Trading LLC
* Written by: John H. Baldwin <jhb@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
struct pci_devinst;
void pci_irq_assert(struct pci_devinst *pi);
void pci_irq_deassert(struct pci_devinst *pi);
void pci_irq_init(void);
void pci_irq_reserve(int irq);
void pci_irq_use(int irq);
int pirq_alloc_pin(void);
int pirq_irq(int pin);
uint8_t pirq_read(int pin);
void pirq_write(int pin, uint8_t val);

View File

@ -0,0 +1,70 @@
/*-
* Copyright (c) 2013 Neel Natu <neel@freebsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <xhyve/support/linker_set.h>
typedef void (*lpc_write_dsdt_t)(void);
struct lpc_dsdt {
lpc_write_dsdt_t handler;
};
#define LPC_DSDT(handler) \
static struct lpc_dsdt __CONCAT(__lpc_dsdt, handler) = { \
(handler), \
}; \
DATA_SET(lpc_dsdt_set, __CONCAT(__lpc_dsdt, handler))
enum lpc_sysres_type {
LPC_SYSRES_IO,
LPC_SYSRES_MEM
};
struct lpc_sysres {
enum lpc_sysres_type type;
uint32_t base;
uint32_t length;
};
#define LPC_SYSRES(type, base, length) \
static struct lpc_sysres __CONCAT(__lpc_sysres, base) = {\
(type), \
(base), \
(length) \
}; \
DATA_SET(lpc_sysres_set, __CONCAT(__lpc_sysres, base))
#define SYSRES_IO(base, length) LPC_SYSRES(LPC_SYSRES_IO, base, length)
#define SYSRES_MEM(base, length) LPC_SYSRES(LPC_SYSRES_MEM, base, length)
int lpc_device_parse(const char *opt);
char *lpc_pirq_name(int pin);
void lpc_pirq_routed(void);

View File

@ -0,0 +1,31 @@
/*
* Copyright (c) 2013 Peter Grehan <grehan@freebsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
void rtc_init(int use_localtime);

View File

@ -0,0 +1,31 @@
/*-
* Copyright (c) 2014 Tycho Nightingale <tycho.nightingale@pluribusnetworks.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
int smbios_build(void);

View File

@ -0,0 +1,64 @@
/*-
* Copyright (c) 2005 Poul-Henning Kamp
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#define HPET_MEM_WIDTH 0x400 /* Expected memory region size */
/* General registers */
#define HPET_CAPABILITIES 0x0 /* General capabilities and ID */
#define HPET_CAP_VENDOR_ID 0xffff0000
#define HPET_CAP_LEG_RT 0x00008000
#define HPET_CAP_COUNT_SIZE 0x00002000 /* 1 = 64-bit, 0 = 32-bit */
#define HPET_CAP_NUM_TIM 0x00001f00
#define HPET_CAP_REV_ID 0x000000ff
#define HPET_PERIOD 0x4 /* Period (1/hz) of timer */
#define HPET_CONFIG 0x10 /* General configuration register */
#define HPET_CNF_LEG_RT 0x00000002
#define HPET_CNF_ENABLE 0x00000001
#define HPET_ISR 0x20 /* General interrupt status register */
#define HPET_MAIN_COUNTER 0xf0 /* Main counter register */
/* Timer registers */
#define HPET_TIMER_CAP_CNF(x) ((x) * 0x20 + 0x100)
#define HPET_TCAP_INT_ROUTE 0xffffffff00000000
#define HPET_TCAP_FSB_INT_DEL 0x00008000
#define HPET_TCNF_FSB_EN 0x00004000
#define HPET_TCNF_INT_ROUTE 0x00003e00
#define HPET_TCNF_32MODE 0x00000100
#define HPET_TCNF_VAL_SET 0x00000040
#define HPET_TCAP_SIZE 0x00000020 /* 1 = 64-bit, 0 = 32-bit */
#define HPET_TCAP_PER_INT 0x00000010 /* Supports periodic interrupts */
#define HPET_TCNF_TYPE 0x00000008 /* 1 = periodic, 0 = one-shot */
#define HPET_TCNF_INT_ENB 0x00000004
#define HPET_TCNF_INT_TYPE 0x00000002 /* 1 = level triggered, 0 = edge */
#define HPET_TIMER_COMPARATOR(x) ((x) * 0x20 + 0x108)
#define HPET_TIMER_FSB_VAL(x) ((x) * 0x20 + 0x110)
#define HPET_TIMER_FSB_ADDR(x) ((x) * 0x20 + 0x114)
#define HPET_MIN_CYCLES 128 /* Period considered reliable. */

View File

@ -0,0 +1,509 @@
/*-
* Copyright (c) 1996, by Peter Wemm and Steve Passe
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. The name of the developer may NOT be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
/*
* Local && I/O APIC definitions.
*/
/*
* Pentium P54C+ Built-in APIC
* (Advanced programmable Interrupt Controller)
*
* Base Address of Built-in APIC in memory location
* is 0xfee00000.
*
* Map of APIC Registers:
*
* Offset (hex) Description Read/Write state
* 000 Reserved
* 010 Reserved
* 020 ID Local APIC ID R/W
* 030 VER Local APIC Version R
* 040 Reserved
* 050 Reserved
* 060 Reserved
* 070 Reserved
* 080 Task Priority Register R/W
* 090 Arbitration Priority Register R
* 0A0 Processor Priority Register R
* 0B0 EOI Register W
* 0C0 RRR Remote read R
* 0D0 Logical Destination R/W
* 0E0 Destination Format Register 0..27 R; 28..31 R/W
* 0F0 SVR Spurious Interrupt Vector Reg. 0..3 R; 4..9 R/W
* 100 ISR 000-031 R
* 110 ISR 032-063 R
* 120 ISR 064-095 R
* 130 ISR 095-128 R
* 140 ISR 128-159 R
* 150 ISR 160-191 R
* 160 ISR 192-223 R
* 170 ISR 224-255 R
* 180 TMR 000-031 R
* 190 TMR 032-063 R
* 1A0 TMR 064-095 R
* 1B0 TMR 095-128 R
* 1C0 TMR 128-159 R
* 1D0 TMR 160-191 R
* 1E0 TMR 192-223 R
* 1F0 TMR 224-255 R
* 200 IRR 000-031 R
* 210 IRR 032-063 R
* 220 IRR 064-095 R
* 230 IRR 095-128 R
* 240 IRR 128-159 R
* 250 IRR 160-191 R
* 260 IRR 192-223 R
* 270 IRR 224-255 R
* 280 Error Status Register R
* 290 Reserved
* 2A0 Reserved
* 2B0 Reserved
* 2C0 Reserved
* 2D0 Reserved
* 2E0 Reserved
* 2F0 Local Vector Table (CMCI) R/W
* 300 ICR_LOW Interrupt Command Reg. (0-31) R/W
* 310 ICR_HI Interrupt Command Reg. (32-63) R/W
* 320 Local Vector Table (Timer) R/W
* 330 Local Vector Table (Thermal) R/W (PIV+)
* 340 Local Vector Table (Performance) R/W (P6+)
* 350 LVT1 Local Vector Table (LINT0) R/W
* 360 LVT2 Local Vector Table (LINT1) R/W
* 370 LVT3 Local Vector Table (ERROR) R/W
* 380 Initial Count Reg. for Timer R/W
* 390 Current Count of Timer R
* 3A0 Reserved
* 3B0 Reserved
* 3C0 Reserved
* 3D0 Reserved
* 3E0 Timer Divide Configuration Reg. R/W
* 3F0 Reserved
*/
/******************************************************************************
* global defines, etc.
*/
/******************************************************************************
* LOCAL APIC structure
*/
#define PAD3 int : 32; int : 32; int : 32
#define PAD4 int : 32; int : 32; int : 32; int : 32
struct LAPIC {
/* reserved */ PAD4;
/* reserved */ PAD4;
uint32_t id; PAD3;
uint32_t version; PAD3;
/* reserved */ PAD4;
/* reserved */ PAD4;
/* reserved */ PAD4;
/* reserved */ PAD4;
uint32_t tpr; PAD3;
uint32_t apr; PAD3;
uint32_t ppr; PAD3;
uint32_t eoi; PAD3;
/* reserved */ PAD4;
uint32_t ldr; PAD3;
uint32_t dfr; PAD3;
uint32_t svr; PAD3;
uint32_t isr0; PAD3;
uint32_t isr1; PAD3;
uint32_t isr2; PAD3;
uint32_t isr3; PAD3;
uint32_t isr4; PAD3;
uint32_t isr5; PAD3;
uint32_t isr6; PAD3;
uint32_t isr7; PAD3;
uint32_t tmr0; PAD3;
uint32_t tmr1; PAD3;
uint32_t tmr2; PAD3;
uint32_t tmr3; PAD3;
uint32_t tmr4; PAD3;
uint32_t tmr5; PAD3;
uint32_t tmr6; PAD3;
uint32_t tmr7; PAD3;
uint32_t irr0; PAD3;
uint32_t irr1; PAD3;
uint32_t irr2; PAD3;
uint32_t irr3; PAD3;
uint32_t irr4; PAD3;
uint32_t irr5; PAD3;
uint32_t irr6; PAD3;
uint32_t irr7; PAD3;
uint32_t esr; PAD3;
/* reserved */ PAD4;
/* reserved */ PAD4;
/* reserved */ PAD4;
/* reserved */ PAD4;
/* reserved */ PAD4;
/* reserved */ PAD4;
uint32_t lvt_cmci; PAD3;
uint32_t icr_lo; PAD3;
uint32_t icr_hi; PAD3;
uint32_t lvt_timer; PAD3;
uint32_t lvt_thermal; PAD3;
uint32_t lvt_pcint; PAD3;
uint32_t lvt_lint0; PAD3;
uint32_t lvt_lint1; PAD3;
uint32_t lvt_error; PAD3;
uint32_t icr_timer; PAD3;
uint32_t ccr_timer; PAD3;
/* reserved */ PAD4;
/* reserved */ PAD4;
/* reserved */ PAD4;
/* reserved */ PAD4;
uint32_t dcr_timer; PAD3;
/* reserved */ PAD4;
};
typedef struct LAPIC lapic_t;
enum LAPIC_REGISTERS {
LAPIC_ID = 0x2,
LAPIC_VERSION = 0x3,
LAPIC_TPR = 0x8,
LAPIC_APR = 0x9,
LAPIC_PPR = 0xa,
LAPIC_EOI = 0xb,
LAPIC_LDR = 0xd,
LAPIC_DFR = 0xe, /* Not in x2APIC */
LAPIC_SVR = 0xf,
LAPIC_ISR0 = 0x10,
LAPIC_ISR1 = 0x11,
LAPIC_ISR2 = 0x12,
LAPIC_ISR3 = 0x13,
LAPIC_ISR4 = 0x14,
LAPIC_ISR5 = 0x15,
LAPIC_ISR6 = 0x16,
LAPIC_ISR7 = 0x17,
LAPIC_TMR0 = 0x18,
LAPIC_TMR1 = 0x19,
LAPIC_TMR2 = 0x1a,
LAPIC_TMR3 = 0x1b,
LAPIC_TMR4 = 0x1c,
LAPIC_TMR5 = 0x1d,
LAPIC_TMR6 = 0x1e,
LAPIC_TMR7 = 0x1f,
LAPIC_IRR0 = 0x20,
LAPIC_IRR1 = 0x21,
LAPIC_IRR2 = 0x22,
LAPIC_IRR3 = 0x23,
LAPIC_IRR4 = 0x24,
LAPIC_IRR5 = 0x25,
LAPIC_IRR6 = 0x26,
LAPIC_IRR7 = 0x27,
LAPIC_ESR = 0x28,
LAPIC_LVT_CMCI = 0x2f,
LAPIC_ICR_LO = 0x30,
LAPIC_ICR_HI = 0x31, /* Not in x2APIC */
LAPIC_LVT_TIMER = 0x32,
LAPIC_LVT_THERMAL = 0x33,
LAPIC_LVT_PCINT = 0x34,
LAPIC_LVT_LINT0 = 0x35,
LAPIC_LVT_LINT1 = 0x36,
LAPIC_LVT_ERROR = 0x37,
LAPIC_ICR_TIMER = 0x38,
LAPIC_CCR_TIMER = 0x39,
LAPIC_DCR_TIMER = 0x3e,
LAPIC_SELF_IPI = 0x3f, /* Only in x2APIC */
};
/*
* The LAPIC_SELF_IPI register only exists in x2APIC mode. The
* formula below is applicable only to reserve the memory region,
* i.e. for xAPIC mode, where LAPIC_SELF_IPI finely serves as the
* address past end of the region.
*/
#define LAPIC_MEM_REGION (LAPIC_SELF_IPI * 0x10)
#define LAPIC_MEM_MUL 0x10
/******************************************************************************
* I/O APIC structure
*/
struct IOAPIC {
uint32_t ioregsel; PAD3;
uint32_t iowin; PAD3;
};
typedef struct IOAPIC ioapic_t;
#undef PAD4
#undef PAD3
/******************************************************************************
* various code 'logical' values
*/
/******************************************************************************
* LOCAL APIC defines
*/
/* default physical locations of LOCAL (CPU) APICs */
#define DEFAULT_APIC_BASE 0xfee00000
/* constants relating to APIC ID registers */
#define APIC_ID_MASK 0xff000000
#define APIC_ID_SHIFT 24
#define APIC_ID_CLUSTER 0xf0
#define APIC_ID_CLUSTER_ID 0x0f
#define APIC_MAX_CLUSTER 0xe
#define APIC_MAX_INTRACLUSTER_ID 3
#define APIC_ID_CLUSTER_SHIFT 4
/* fields in VER */
#define APIC_VER_VERSION 0x000000ff
#define APIC_VER_MAXLVT 0x00ff0000
#define MAXLVTSHIFT 16
#define APIC_VER_EOI_SUPPRESSION 0x01000000
/* fields in LDR */
#define APIC_LDR_RESERVED 0x00ffffff
/* fields in DFR */
#define APIC_DFR_RESERVED 0x0fffffff
#define APIC_DFR_MODEL_MASK 0xf0000000
#define APIC_DFR_MODEL_FLAT 0xf0000000
#define APIC_DFR_MODEL_CLUSTER 0x00000000
/* fields in SVR */
#define APIC_SVR_VECTOR 0x000000ff
#define APIC_SVR_VEC_PROG 0x000000f0
#define APIC_SVR_VEC_FIX 0x0000000f
#define APIC_SVR_ENABLE 0x00000100
# define APIC_SVR_SWDIS 0x00000000
# define APIC_SVR_SWEN 0x00000100
#define APIC_SVR_FOCUS 0x00000200
# define APIC_SVR_FEN 0x00000000
# define APIC_SVR_FDIS 0x00000200
#define APIC_SVR_EOI_SUPPRESSION 0x00001000
/* fields in TPR */
#define APIC_TPR_PRIO 0x000000ff
# define APIC_TPR_INT 0x000000f0
# define APIC_TPR_SUB 0x0000000f
/* fields in ESR */
#define APIC_ESR_SEND_CS_ERROR 0x00000001
#define APIC_ESR_RECEIVE_CS_ERROR 0x00000002
#define APIC_ESR_SEND_ACCEPT 0x00000004
#define APIC_ESR_RECEIVE_ACCEPT 0x00000008
#define APIC_ESR_SEND_ILLEGAL_VECTOR 0x00000020
#define APIC_ESR_RECEIVE_ILLEGAL_VECTOR 0x00000040
#define APIC_ESR_ILLEGAL_REGISTER 0x00000080
/* fields in ICR_LOW */
#define APIC_VECTOR_MASK 0x000000ff
#define APIC_DELMODE_MASK 0x00000700
# define APIC_DELMODE_FIXED 0x00000000
# define APIC_DELMODE_LOWPRIO 0x00000100
# define APIC_DELMODE_SMI 0x00000200
# define APIC_DELMODE_RR 0x00000300
# define APIC_DELMODE_NMI 0x00000400
# define APIC_DELMODE_INIT 0x00000500
# define APIC_DELMODE_STARTUP 0x00000600
# define APIC_DELMODE_RESV 0x00000700
#define APIC_DESTMODE_MASK 0x00000800
# define APIC_DESTMODE_PHY 0x00000000
# define APIC_DESTMODE_LOG 0x00000800
#define APIC_DELSTAT_MASK 0x00001000
# define APIC_DELSTAT_IDLE 0x00000000
# define APIC_DELSTAT_PEND 0x00001000
#define APIC_RESV1_MASK 0x00002000
#define APIC_LEVEL_MASK 0x00004000
# define APIC_LEVEL_DEASSERT 0x00000000
# define APIC_LEVEL_ASSERT 0x00004000
#define APIC_TRIGMOD_MASK 0x00008000
# define APIC_TRIGMOD_EDGE 0x00000000
# define APIC_TRIGMOD_LEVEL 0x00008000
#define APIC_RRSTAT_MASK 0x00030000
# define APIC_RRSTAT_INVALID 0x00000000
# define APIC_RRSTAT_INPROG 0x00010000
# define APIC_RRSTAT_VALID 0x00020000
# define APIC_RRSTAT_RESV 0x00030000
#define APIC_DEST_MASK 0x000c0000
# define APIC_DEST_DESTFLD 0x00000000
# define APIC_DEST_SELF 0x00040000
# define APIC_DEST_ALLISELF 0x00080000
# define APIC_DEST_ALLESELF 0x000c0000
#define APIC_RESV2_MASK 0xfff00000
#define APIC_ICRLO_RESV_MASK (APIC_RESV1_MASK | APIC_RESV2_MASK)
/* fields in LVT1/2 */
#define APIC_LVT_VECTOR 0x000000ff
#define APIC_LVT_DM 0x00000700
# define APIC_LVT_DM_FIXED 0x00000000
# define APIC_LVT_DM_SMI 0x00000200
# define APIC_LVT_DM_NMI 0x00000400
# define APIC_LVT_DM_INIT 0x00000500
# define APIC_LVT_DM_EXTINT 0x00000700
#define APIC_LVT_DS 0x00001000
#define APIC_LVT_IIPP 0x00002000
#define APIC_LVT_IIPP_INTALO 0x00002000
#define APIC_LVT_IIPP_INTAHI 0x00000000
#define APIC_LVT_RIRR 0x00004000
#define APIC_LVT_TM 0x00008000
#define APIC_LVT_M 0x00010000
/* fields in LVT Timer */
#define APIC_LVTT_VECTOR 0x000000ff
#define APIC_LVTT_DS 0x00001000
#define APIC_LVTT_M 0x00010000
#define APIC_LVTT_TM 0x00020000
# define APIC_LVTT_TM_ONE_SHOT 0x00000000
# define APIC_LVTT_TM_PERIODIC 0x00020000
/* APIC timer current count */
#define APIC_TIMER_MAX_COUNT 0xffffffff
/* fields in TDCR */
#define APIC_TDCR_2 0x00
#define APIC_TDCR_4 0x01
#define APIC_TDCR_8 0x02
#define APIC_TDCR_16 0x03
#define APIC_TDCR_32 0x08
#define APIC_TDCR_64 0x09
#define APIC_TDCR_128 0x0a
#define APIC_TDCR_1 0x0b
/* LVT table indices */
#define APIC_LVT_LINT0 0
#define APIC_LVT_LINT1 1
#define APIC_LVT_TIMER 2
#define APIC_LVT_ERROR 3
#define APIC_LVT_PMC 4
#define APIC_LVT_THERMAL 5
#define APIC_LVT_CMCI 6
#define APIC_LVT_MAX APIC_LVT_CMCI
/******************************************************************************
* I/O APIC defines
*/
/* default physical locations of an IO APIC */
#define DEFAULT_IO_APIC_BASE 0xfec00000
/* window register offset */
#define IOAPIC_WINDOW 0x10
#define IOAPIC_EOIR 0x40
/* indexes into IO APIC */
#define IOAPIC_ID 0x00
#define IOAPIC_VER 0x01
#define IOAPIC_ARB 0x02
#define IOAPIC_REDTBL 0x10
#define IOAPIC_REDTBL0 IOAPIC_REDTBL
#define IOAPIC_REDTBL1 (IOAPIC_REDTBL+0x02)
#define IOAPIC_REDTBL2 (IOAPIC_REDTBL+0x04)
#define IOAPIC_REDTBL3 (IOAPIC_REDTBL+0x06)
#define IOAPIC_REDTBL4 (IOAPIC_REDTBL+0x08)
#define IOAPIC_REDTBL5 (IOAPIC_REDTBL+0x0a)
#define IOAPIC_REDTBL6 (IOAPIC_REDTBL+0x0c)
#define IOAPIC_REDTBL7 (IOAPIC_REDTBL+0x0e)
#define IOAPIC_REDTBL8 (IOAPIC_REDTBL+0x10)
#define IOAPIC_REDTBL9 (IOAPIC_REDTBL+0x12)
#define IOAPIC_REDTBL10 (IOAPIC_REDTBL+0x14)
#define IOAPIC_REDTBL11 (IOAPIC_REDTBL+0x16)
#define IOAPIC_REDTBL12 (IOAPIC_REDTBL+0x18)
#define IOAPIC_REDTBL13 (IOAPIC_REDTBL+0x1a)
#define IOAPIC_REDTBL14 (IOAPIC_REDTBL+0x1c)
#define IOAPIC_REDTBL15 (IOAPIC_REDTBL+0x1e)
#define IOAPIC_REDTBL16 (IOAPIC_REDTBL+0x20)
#define IOAPIC_REDTBL17 (IOAPIC_REDTBL+0x22)
#define IOAPIC_REDTBL18 (IOAPIC_REDTBL+0x24)
#define IOAPIC_REDTBL19 (IOAPIC_REDTBL+0x26)
#define IOAPIC_REDTBL20 (IOAPIC_REDTBL+0x28)
#define IOAPIC_REDTBL21 (IOAPIC_REDTBL+0x2a)
#define IOAPIC_REDTBL22 (IOAPIC_REDTBL+0x2c)
#define IOAPIC_REDTBL23 (IOAPIC_REDTBL+0x2e)
/* fields in VER */
#define IOART_VER_VERSION 0x000000ff
#define IOART_VER_MAXREDIR 0x00ff0000
#define MAXREDIRSHIFT 16
/*
* fields in the IO APIC's redirection table entries
*/
#define IOART_DEST APIC_ID_MASK /* broadcast addr: all APICs */
#define IOART_RESV 0x00fe0000 /* reserved */
#define IOART_INTMASK 0x00010000 /* R/W: INTerrupt mask */
# define IOART_INTMCLR 0x00000000 /* clear, allow INTs */
# define IOART_INTMSET 0x00010000 /* set, inhibit INTs */
#define IOART_TRGRMOD 0x00008000 /* R/W: trigger mode */
# define IOART_TRGREDG 0x00000000 /* edge */
# define IOART_TRGRLVL 0x00008000 /* level */
#define IOART_REM_IRR 0x00004000 /* RO: remote IRR */
#define IOART_INTPOL 0x00002000 /* R/W: INT input pin polarity */
# define IOART_INTAHI 0x00000000 /* active high */
# define IOART_INTALO 0x00002000 /* active low */
#define IOART_DELIVS 0x00001000 /* RO: delivery status */
#define IOART_DESTMOD 0x00000800 /* R/W: destination mode */
# define IOART_DESTPHY 0x00000000 /* physical */
# define IOART_DESTLOG 0x00000800 /* logical */
#define IOART_DELMOD 0x00000700 /* R/W: delivery mode */
# define IOART_DELFIXED 0x00000000 /* fixed */
# define IOART_DELLOPRI 0x00000100 /* lowest priority */
# define IOART_DELSMI 0x00000200 /* System Management INT */
# define IOART_DELRSV1 0x00000300 /* reserved */
# define IOART_DELNMI 0x00000400 /* NMI signal */
# define IOART_DELINIT 0x00000500 /* INIT signal */
# define IOART_DELRSV2 0x00000600 /* reserved */
# define IOART_DELEXINT 0x00000700 /* External INTerrupt */
#define IOART_INTVEC 0x000000ff /* R/W: INTerrupt vector field */

View File

@ -0,0 +1,637 @@
/*-
* Copyright (c) 2000 - 2008 Søren Schmidt <sos@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer,
* without modification, immediately at the beginning of the file.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <xhyve/support/misc.h>
/* ATA/ATAPI device parameters */
struct ata_params {
/*000*/ u_int16_t config; /* configuration info */
#define ATA_PROTO_MASK 0x8003
#define ATA_PROTO_ATAPI 0x8000
#define ATA_PROTO_ATAPI_12 0x8000
#define ATA_PROTO_ATAPI_16 0x8001
#define ATA_PROTO_CFA 0x848a
#define ATA_ATAPI_TYPE_MASK 0x1f00
#define ATA_ATAPI_TYPE_DIRECT 0x0000 /* disk/floppy */
#define ATA_ATAPI_TYPE_TAPE 0x0100 /* streaming tape */
#define ATA_ATAPI_TYPE_CDROM 0x0500 /* CD-ROM device */
#define ATA_ATAPI_TYPE_OPTICAL 0x0700 /* optical disk */
#define ATA_DRQ_MASK 0x0060
#define ATA_DRQ_SLOW 0x0000 /* cpu 3 ms delay */
#define ATA_DRQ_INTR 0x0020 /* interrupt 10 ms delay */
#define ATA_DRQ_FAST 0x0040 /* accel 50 us delay */
#define ATA_RESP_INCOMPLETE 0x0004
/*001*/ u_int16_t cylinders; /* # of cylinders */
/*002*/ u_int16_t specconf; /* specific configuration */
/*003*/ u_int16_t heads; /* # heads */
u_int16_t obsolete4;
u_int16_t obsolete5;
/*006*/ u_int16_t sectors; /* # sectors/track */
/*007*/ u_int16_t vendor7[3];
/*010*/ u_int8_t serial[20]; /* serial number */
/*020*/ u_int16_t retired20;
u_int16_t retired21;
u_int16_t obsolete22;
/*023*/ u_int8_t revision[8]; /* firmware revision */
/*027*/ u_int8_t model[40]; /* model name */
/*047*/ u_int16_t sectors_intr; /* sectors per interrupt */
/*048*/ u_int16_t usedmovsd; /* double word read/write? */
/*049*/ u_int16_t capabilities1;
#define ATA_SUPPORT_DMA 0x0100
#define ATA_SUPPORT_LBA 0x0200
#define ATA_SUPPORT_IORDY 0x0400
#define ATA_SUPPORT_IORDYDIS 0x0800
#define ATA_SUPPORT_OVERLAP 0x4000
/*050*/ u_int16_t capabilities2;
/*051*/ u_int16_t retired_piomode; /* PIO modes 0-2 */
#define ATA_RETIRED_PIO_MASK 0x0300
/*052*/ u_int16_t retired_dmamode; /* DMA modes */
#define ATA_RETIRED_DMA_MASK 0x0003
/*053*/ u_int16_t atavalid; /* fields valid */
#define ATA_FLAG_54_58 0x0001 /* words 54-58 valid */
#define ATA_FLAG_64_70 0x0002 /* words 64-70 valid */
#define ATA_FLAG_88 0x0004 /* word 88 valid */
/*054*/ u_int16_t current_cylinders;
/*055*/ u_int16_t current_heads;
/*056*/ u_int16_t current_sectors;
/*057*/ u_int16_t current_size_1;
/*058*/ u_int16_t current_size_2;
/*059*/ u_int16_t multi;
#define ATA_MULTI_VALID 0x0100
/*060*/ u_int16_t lba_size_1;
u_int16_t lba_size_2;
u_int16_t obsolete62;
/*063*/ u_int16_t mwdmamodes; /* multiword DMA modes */
/*064*/ u_int16_t apiomodes; /* advanced PIO modes */
/*065*/ u_int16_t mwdmamin; /* min. M/W DMA time/word ns */
/*066*/ u_int16_t mwdmarec; /* rec. M/W DMA time ns */
/*067*/ u_int16_t pioblind; /* min. PIO cycle w/o flow */
/*068*/ u_int16_t pioiordy; /* min. PIO cycle IORDY flow */
/*069*/ u_int16_t support3;
#define ATA_SUPPORT_RZAT 0x0020
#define ATA_SUPPORT_DRAT 0x4000
u_int16_t reserved70;
/*071*/ u_int16_t rlsovlap; /* rel time (us) for overlap */
/*072*/ u_int16_t rlsservice; /* rel time (us) for service */
u_int16_t reserved73;
u_int16_t reserved74;
/*075*/ u_int16_t queue;
#define ATA_QUEUE_LEN(x) ((x) & 0x001f)
/*76*/ u_int16_t satacapabilities;
#define ATA_SATA_GEN1 0x0002
#define ATA_SATA_GEN2 0x0004
#define ATA_SATA_GEN3 0x0008
#define ATA_SUPPORT_NCQ 0x0100
#define ATA_SUPPORT_IFPWRMNGTRCV 0x0200
#define ATA_SUPPORT_PHYEVENTCNT 0x0400
#define ATA_SUPPORT_NCQ_UNLOAD 0x0800
#define ATA_SUPPORT_NCQ_PRIO 0x1000
#define ATA_SUPPORT_HAPST 0x2000
#define ATA_SUPPORT_DAPST 0x4000
#define ATA_SUPPORT_READLOGDMAEXT 0x8000
/*77*/ u_int16_t satacapabilities2;
#define ATA_SATA_CURR_GEN_MASK 0x0006
#define ATA_SUPPORT_NCQ_STREAM 0x0010
#define ATA_SUPPORT_NCQ_QMANAGEMENT 0x0020
#define ATA_SUPPORT_RCVSND_FPDMA_QUEUED 0x0040
/*78*/ u_int16_t satasupport;
#define ATA_SUPPORT_NONZERO 0x0002
#define ATA_SUPPORT_AUTOACTIVATE 0x0004
#define ATA_SUPPORT_IFPWRMNGT 0x0008
#define ATA_SUPPORT_INORDERDATA 0x0010
#define ATA_SUPPORT_ASYNCNOTIF 0x0020
#define ATA_SUPPORT_SOFTSETPRESERVE 0x0040
/*79*/ u_int16_t sataenabled;
#define ATA_ENABLED_DAPST 0x0080
/*080*/ u_int16_t version_major;
/*081*/ u_int16_t version_minor;
struct {
/*082/085*/ u_int16_t command1;
#define ATA_SUPPORT_SMART 0x0001
#define ATA_SUPPORT_SECURITY 0x0002
#define ATA_SUPPORT_REMOVABLE 0x0004
#define ATA_SUPPORT_POWERMGT 0x0008
#define ATA_SUPPORT_PACKET 0x0010
#define ATA_SUPPORT_WRITECACHE 0x0020
#define ATA_SUPPORT_LOOKAHEAD 0x0040
#define ATA_SUPPORT_RELEASEIRQ 0x0080
#define ATA_SUPPORT_SERVICEIRQ 0x0100
#define ATA_SUPPORT_RESET 0x0200
#define ATA_SUPPORT_PROTECTED 0x0400
#define ATA_SUPPORT_WRITEBUFFER 0x1000
#define ATA_SUPPORT_READBUFFER 0x2000
#define ATA_SUPPORT_NOP 0x4000
/*083/086*/ u_int16_t command2;
#define ATA_SUPPORT_MICROCODE 0x0001
#define ATA_SUPPORT_QUEUED 0x0002
#define ATA_SUPPORT_CFA 0x0004
#define ATA_SUPPORT_APM 0x0008
#define ATA_SUPPORT_NOTIFY 0x0010
#define ATA_SUPPORT_STANDBY 0x0020
#define ATA_SUPPORT_SPINUP 0x0040
#define ATA_SUPPORT_MAXSECURITY 0x0100
#define ATA_SUPPORT_AUTOACOUSTIC 0x0200
#define ATA_SUPPORT_ADDRESS48 0x0400
#define ATA_SUPPORT_OVERLAY 0x0800
#define ATA_SUPPORT_FLUSHCACHE 0x1000
#define ATA_SUPPORT_FLUSHCACHE48 0x2000
/*084/087*/ u_int16_t extension;
#define ATA_SUPPORT_SMARTLOG 0x0001
#define ATA_SUPPORT_SMARTTEST 0x0002
#define ATA_SUPPORT_MEDIASN 0x0004
#define ATA_SUPPORT_MEDIAPASS 0x0008
#define ATA_SUPPORT_STREAMING 0x0010
#define ATA_SUPPORT_GENLOG 0x0020
#define ATA_SUPPORT_WRITEDMAFUAEXT 0x0040
#define ATA_SUPPORT_WRITEDMAQFUAEXT 0x0080
#define ATA_SUPPORT_64BITWWN 0x0100
#define ATA_SUPPORT_UNLOAD 0x2000
} __packed support, enabled;
/*088*/ u_int16_t udmamodes; /* UltraDMA modes */
/*089*/ u_int16_t erase_time; /* time req'd in 2min units */
/*090*/ u_int16_t enhanced_erase_time; /* time req'd in 2min units */
/*091*/ u_int16_t apm_value;
/*092*/ u_int16_t master_passwd_revision; /* password revision code */
/*093*/ u_int16_t hwres;
#define ATA_CABLE_ID 0x2000
/*094*/ u_int16_t acoustic;
#define ATA_ACOUSTIC_CURRENT(x) ((x) & 0x00ff)
#define ATA_ACOUSTIC_VENDOR(x) (((x) & 0xff00) >> 8)
/*095*/ u_int16_t stream_min_req_size;
/*096*/ u_int16_t stream_transfer_time;
/*097*/ u_int16_t stream_access_latency;
/*098*/ u_int32_t stream_granularity;
/*100*/ u_int16_t lba_size48_1;
u_int16_t lba_size48_2;
u_int16_t lba_size48_3;
u_int16_t lba_size48_4;
u_int16_t reserved104;
/*105*/ u_int16_t max_dsm_blocks;
/*106*/ u_int16_t pss;
#define ATA_PSS_LSPPS 0x000F
#define ATA_PSS_LSSABOVE512 0x1000
#define ATA_PSS_MULTLS 0x2000
#define ATA_PSS_VALID_MASK 0xC000
#define ATA_PSS_VALID_VALUE 0x4000
/*107*/ u_int16_t isd;
/*108*/ u_int16_t wwn[4];
u_int16_t reserved112[5];
/*117*/ u_int16_t lss_1;
/*118*/ u_int16_t lss_2;
/*119*/ u_int16_t support2;
#define ATA_SUPPORT_WRITEREADVERIFY 0x0002
#define ATA_SUPPORT_WRITEUNCORREXT 0x0004
#define ATA_SUPPORT_RWLOGDMAEXT 0x0008
#define ATA_SUPPORT_MICROCODE3 0x0010
#define ATA_SUPPORT_FREEFALL 0x0020
/*120*/ u_int16_t enabled2;
u_int16_t reserved121[6];
/*127*/ u_int16_t removable_status;
/*128*/ u_int16_t security_status;
#define ATA_SECURITY_LEVEL 0x0100 /* 0: high, 1: maximum */
#define ATA_SECURITY_ENH_SUPP 0x0020 /* enhanced erase supported */
#define ATA_SECURITY_COUNT_EXP 0x0010 /* count expired */
#define ATA_SECURITY_FROZEN 0x0008 /* security config is frozen */
#define ATA_SECURITY_LOCKED 0x0004 /* drive is locked */
#define ATA_SECURITY_ENABLED 0x0002 /* ATA Security is enabled */
#define ATA_SECURITY_SUPPORTED 0x0001 /* ATA Security is supported */
u_int16_t reserved129[31];
/*160*/ u_int16_t cfa_powermode1;
u_int16_t reserved161;
/*162*/ u_int16_t cfa_kms_support;
/*163*/ u_int16_t cfa_trueide_modes;
/*164*/ u_int16_t cfa_memory_modes;
u_int16_t reserved165[4];
/*169*/ u_int16_t support_dsm;
#define ATA_SUPPORT_DSM_TRIM 0x0001
u_int16_t reserved170[6];
/*176*/ u_int8_t media_serial[60];
/*206*/ u_int16_t sct;
u_int16_t reserved206[2];
/*209*/ u_int16_t lsalign;
/*210*/ u_int16_t wrv_sectors_m3_1;
u_int16_t wrv_sectors_m3_2;
/*212*/ u_int16_t wrv_sectors_m2_1;
u_int16_t wrv_sectors_m2_2;
/*214*/ u_int16_t nv_cache_caps;
/*215*/ u_int16_t nv_cache_size_1;
u_int16_t nv_cache_size_2;
/*217*/ u_int16_t media_rotation_rate;
#define ATA_RATE_NOT_REPORTED 0x0000
#define ATA_RATE_NON_ROTATING 0x0001
u_int16_t reserved218;
/*219*/ u_int16_t nv_cache_opt;
/*220*/ u_int16_t wrv_mode;
u_int16_t reserved221;
/*222*/ u_int16_t transport_major;
/*223*/ u_int16_t transport_minor;
u_int16_t reserved224[31];
/*255*/ u_int16_t integrity;
} __packed;
/* ATA Dataset Management */
#define ATA_DSM_BLK_SIZE 512
#define ATA_DSM_BLK_RANGES 64
#define ATA_DSM_RANGE_SIZE 8
#define ATA_DSM_RANGE_MAX 65535
/*
* ATA Device Register
*
* bit 7 Obsolete (was 1 in early ATA specs)
* bit 6 Sets LBA/CHS mode. 1=LBA, 0=CHS
* bit 5 Obsolete (was 1 in early ATA specs)
* bit 4 1 = Slave Drive, 0 = Master Drive
* bit 3-0 In LBA mode, 27-24 of address. In CHS mode, head number
*/
#define ATA_DEV_MASTER 0x00
#define ATA_DEV_SLAVE 0x10
#define ATA_DEV_LBA 0x40
/* ATA limits */
#define ATA_MAX_28BIT_LBA 268435455UL
/* ATA Status Register */
#define ATA_STATUS_ERROR 0x01
#define ATA_STATUS_DEVICE_FAULT 0x20
/* ATA Error Register */
#define ATA_ERROR_ABORT 0x04
#define ATA_ERROR_ID_NOT_FOUND 0x10
/* ATA HPA Features */
#define ATA_HPA_FEAT_MAX_ADDR 0x00
#define ATA_HPA_FEAT_SET_PWD 0x01
#define ATA_HPA_FEAT_LOCK 0x02
#define ATA_HPA_FEAT_UNLOCK 0x03
#define ATA_HPA_FEAT_FREEZE 0x04
/* ATA transfer modes */
#define ATA_MODE_MASK 0x0f
#define ATA_DMA_MASK 0xf0
#define ATA_PIO 0x00
#define ATA_PIO0 0x08
#define ATA_PIO1 0x09
#define ATA_PIO2 0x0a
#define ATA_PIO3 0x0b
#define ATA_PIO4 0x0c
#define ATA_PIO_MAX 0x0f
#define ATA_DMA 0x10
#define ATA_WDMA0 0x20
#define ATA_WDMA1 0x21
#define ATA_WDMA2 0x22
#define ATA_UDMA0 0x40
#define ATA_UDMA1 0x41
#define ATA_UDMA2 0x42
#define ATA_UDMA3 0x43
#define ATA_UDMA4 0x44
#define ATA_UDMA5 0x45
#define ATA_UDMA6 0x46
#define ATA_SA150 0x47
#define ATA_SA300 0x48
#define ATA_DMA_MAX 0x4f
/* ATA commands */
#define ATA_NOP 0x00 /* NOP */
#define ATA_NF_FLUSHQUEUE 0x00 /* flush queued cmd's */
#define ATA_NF_AUTOPOLL 0x01 /* start autopoll function */
#define ATA_DATA_SET_MANAGEMENT 0x06
#define ATA_DSM_TRIM 0x01
#define ATA_DEVICE_RESET 0x08 /* reset device */
#define ATA_READ 0x20 /* read */
#define ATA_READ48 0x24 /* read 48bit LBA */
#define ATA_READ_DMA48 0x25 /* read DMA 48bit LBA */
#define ATA_READ_DMA_QUEUED48 0x26 /* read DMA QUEUED 48bit LBA */
#define ATA_READ_NATIVE_MAX_ADDRESS48 0x27 /* read native max addr 48bit */
#define ATA_READ_MUL48 0x29 /* read multi 48bit LBA */
#define ATA_READ_STREAM_DMA48 0x2a /* read DMA stream 48bit LBA */
#define ATA_READ_LOG_EXT 0x2f /* read log ext - PIO Data-In */
#define ATA_READ_STREAM48 0x2b /* read stream 48bit LBA */
#define ATA_WRITE 0x30 /* write */
#define ATA_WRITE48 0x34 /* write 48bit LBA */
#define ATA_WRITE_DMA48 0x35 /* write DMA 48bit LBA */
#define ATA_WRITE_DMA_QUEUED48 0x36 /* write DMA QUEUED 48bit LBA*/
#define ATA_SET_MAX_ADDRESS48 0x37 /* set max address 48bit */
#define ATA_WRITE_MUL48 0x39 /* write multi 48bit LBA */
#define ATA_WRITE_STREAM_DMA48 0x3a
#define ATA_WRITE_STREAM48 0x3b
#define ATA_WRITE_DMA_FUA48 0x3d
#define ATA_WRITE_DMA_QUEUED_FUA48 0x3e
#define ATA_WRITE_LOG_EXT 0x3f
#define ATA_READ_VERIFY 0x40
#define ATA_READ_VERIFY48 0x42
#define ATA_READ_LOG_DMA_EXT 0x47 /* read log DMA ext - PIO Data-In */
#define ATA_READ_FPDMA_QUEUED 0x60 /* read DMA NCQ */
#define ATA_WRITE_FPDMA_QUEUED 0x61 /* write DMA NCQ */
#define ATA_NCQ_NON_DATA 0x63 /* NCQ non-data command */
#define ATA_SEND_FPDMA_QUEUED 0x64 /* send DMA NCQ */
#define ATA_SFPDMA_DSM 0x00 /* Data set management */
#define ATA_SFPDMA_DSM_TRIM 0x01 /* Set trim bit in auxilary */
#define ATA_SFPDMA_HYBRID_EVICT 0x01 /* Hybrid Evict */
#define ATA_SFPDMA_WLDMA 0x02 /* Write Log DMA EXT */
#define ATA_RECV_FPDMA_QUEUED 0x65 /* recieve DMA NCQ */
#define ATA_SEP_ATTN 0x67 /* SEP request */
#define ATA_SEEK 0x70 /* seek */
#define ATA_PACKET_CMD 0xa0 /* packet command */
#define ATA_ATAPI_IDENTIFY 0xa1 /* get ATAPI params*/
#define ATA_SERVICE 0xa2 /* service command */
#define ATA_SMART_CMD 0xb0 /* SMART command */
#define ATA_CFA_ERASE 0xc0 /* CFA erase */
#define ATA_READ_MUL 0xc4 /* read multi */
#define ATA_WRITE_MUL 0xc5 /* write multi */
#define ATA_SET_MULTI 0xc6 /* set multi size */
#define ATA_READ_DMA_QUEUED 0xc7 /* read DMA QUEUED */
#define ATA_READ_DMA 0xc8 /* read DMA */
#define ATA_WRITE_DMA 0xca /* write DMA */
#define ATA_WRITE_DMA_QUEUED 0xcc /* write DMA QUEUED */
#define ATA_WRITE_MUL_FUA48 0xce
#define ATA_STANDBY_IMMEDIATE 0xe0 /* standby immediate */
#define ATA_IDLE_IMMEDIATE 0xe1 /* idle immediate */
#define ATA_STANDBY_CMD 0xe2 /* standby */
#define ATA_IDLE_CMD 0xe3 /* idle */
#define ATA_READ_BUFFER 0xe4 /* read buffer */
#define ATA_READ_PM 0xe4 /* read portmultiplier */
#define ATA_SLEEP 0xe6 /* sleep */
#define ATA_FLUSHCACHE 0xe7 /* flush cache to disk */
#define ATA_WRITE_PM 0xe8 /* write portmultiplier */
#define ATA_FLUSHCACHE48 0xea /* flush cache to disk */
#define ATA_ATA_IDENTIFY 0xec /* get ATA params */
#define ATA_SETFEATURES 0xef /* features command */
#define ATA_SF_SETXFER 0x03 /* set transfer mode */
#define ATA_SF_ENAB_WCACHE 0x02 /* enable write cache */
#define ATA_SF_DIS_WCACHE 0x82 /* disable write cache */
#define ATA_SF_ENAB_PUIS 0x06 /* enable PUIS */
#define ATA_SF_DIS_PUIS 0x86 /* disable PUIS */
#define ATA_SF_PUIS_SPINUP 0x07 /* PUIS spin-up */
#define ATA_SF_ENAB_RCACHE 0xaa /* enable readahead cache */
#define ATA_SF_DIS_RCACHE 0x55 /* disable readahead cache */
#define ATA_SF_ENAB_RELIRQ 0x5d /* enable release interrupt */
#define ATA_SF_DIS_RELIRQ 0xdd /* disable release interrupt */
#define ATA_SF_ENAB_SRVIRQ 0x5e /* enable service interrupt */
#define ATA_SF_DIS_SRVIRQ 0xde /* disable service interrupt */
#define ATA_SECURITY_SET_PASSWORD 0xf1 /* set drive password */
#define ATA_SECURITY_UNLOCK 0xf2 /* unlock drive using passwd */
#define ATA_SECURITY_ERASE_PREPARE 0xf3 /* prepare to erase drive */
#define ATA_SECURITY_ERASE_UNIT 0xf4 /* erase all blocks on drive */
#define ATA_SECURITY_FREEZE_LOCK 0xf5 /* freeze security config */
#define ATA_SECURITY_DISABLE_PASSWORD 0xf6 /* disable drive password */
#define ATA_READ_NATIVE_MAX_ADDRESS 0xf8 /* read native max address */
#define ATA_SET_MAX_ADDRESS 0xf9 /* set max address */
/* ATAPI commands */
#define ATAPI_TEST_UNIT_READY 0x00 /* check if device is ready */
#define ATAPI_REZERO 0x01 /* rewind */
#define ATAPI_REQUEST_SENSE 0x03 /* get sense data */
#define ATAPI_FORMAT 0x04 /* format unit */
#define ATAPI_READ 0x08 /* read data */
#define ATAPI_WRITE 0x0a /* write data */
#define ATAPI_WEOF 0x10 /* write filemark */
#define ATAPI_WF_WRITE 0x01
#define ATAPI_SPACE 0x11 /* space command */
#define ATAPI_SP_FM 0x01
#define ATAPI_SP_EOD 0x03
#define ATAPI_INQUIRY 0x12 /* get inquiry data */
#define ATAPI_MODE_SELECT 0x15 /* mode select */
#define ATAPI_ERASE 0x19 /* erase */
#define ATAPI_MODE_SENSE 0x1a /* mode sense */
#define ATAPI_START_STOP 0x1b /* start/stop unit */
#define ATAPI_SS_LOAD 0x01
#define ATAPI_SS_RETENSION 0x02
#define ATAPI_SS_EJECT 0x04
#define ATAPI_PREVENT_ALLOW 0x1e /* media removal */
#define ATAPI_READ_FORMAT_CAPACITIES 0x23 /* get format capacities */
#define ATAPI_READ_CAPACITY 0x25 /* get volume capacity */
#define ATAPI_READ_BIG 0x28 /* read data */
#define ATAPI_WRITE_BIG 0x2a /* write data */
#define ATAPI_LOCATE 0x2b /* locate to position */
#define ATAPI_READ_POSITION 0x34 /* read position */
#define ATAPI_SYNCHRONIZE_CACHE 0x35 /* flush buf, close channel */
#define ATAPI_WRITE_BUFFER 0x3b /* write device buffer */
#define ATAPI_READ_BUFFER 0x3c /* read device buffer */
#define ATAPI_READ_SUBCHANNEL 0x42 /* get subchannel info */
#define ATAPI_READ_TOC 0x43 /* get table of contents */
#define ATAPI_PLAY_10 0x45 /* play by lba */
#define ATAPI_PLAY_MSF 0x47 /* play by MSF address */
#define ATAPI_PLAY_TRACK 0x48 /* play by track number */
#define ATAPI_PAUSE 0x4b /* pause audio operation */
#define ATAPI_READ_DISK_INFO 0x51 /* get disk info structure */
#define ATAPI_READ_TRACK_INFO 0x52 /* get track info structure */
#define ATAPI_RESERVE_TRACK 0x53 /* reserve track */
#define ATAPI_SEND_OPC_INFO 0x54 /* send OPC structurek */
#define ATAPI_MODE_SELECT_BIG 0x55 /* set device parameters */
#define ATAPI_REPAIR_TRACK 0x58 /* repair track */
#define ATAPI_READ_MASTER_CUE 0x59 /* read master CUE info */
#define ATAPI_MODE_SENSE_BIG 0x5a /* get device parameters */
#define ATAPI_CLOSE_TRACK 0x5b /* close track/session */
#define ATAPI_READ_BUFFER_CAPACITY 0x5c /* get buffer capicity */
#define ATAPI_SEND_CUE_SHEET 0x5d /* send CUE sheet */
#define ATAPI_SERVICE_ACTION_IN 0x96 /* get service data */
#define ATAPI_BLANK 0xa1 /* blank the media */
#define ATAPI_SEND_KEY 0xa3 /* send DVD key structure */
#define ATAPI_REPORT_KEY 0xa4 /* get DVD key structure */
#define ATAPI_PLAY_12 0xa5 /* play by lba */
#define ATAPI_LOAD_UNLOAD 0xa6 /* changer control command */
#define ATAPI_READ_STRUCTURE 0xad /* get DVD structure */
#define ATAPI_PLAY_CD 0xb4 /* universal play command */
#define ATAPI_SET_SPEED 0xbb /* set drive speed */
#define ATAPI_MECH_STATUS 0xbd /* get changer status */
#define ATAPI_READ_CD 0xbe /* read data */
#define ATAPI_POLL_DSC 0xff /* poll DSC status bit */
struct ata_ioc_devices {
int channel;
char name[2][32];
struct ata_params params[2];
};
/* pr channel ATA ioctl calls */
#define IOCATAGMAXCHANNEL _IOR('a', 1, int)
#define IOCATAREINIT _IOW('a', 2, int)
#define IOCATAATTACH _IOW('a', 3, int)
#define IOCATADETACH _IOW('a', 4, int)
#define IOCATADEVICES _IOWR('a', 5, struct ata_ioc_devices)
/* ATAPI request sense structure */
struct atapi_sense {
u_int8_t error; /* current or deferred errors */
#define ATA_SENSE_VALID 0x80
u_int8_t segment; /* segment number */
u_int8_t key; /* sense key */
#define ATA_SENSE_KEY_MASK 0x0f /* sense key mask */
#define ATA_SENSE_NO_SENSE 0x00 /* no specific sense key info */
#define ATA_SENSE_RECOVERED_ERROR 0x01 /* command OK, data recovered */
#define ATA_SENSE_NOT_READY 0x02 /* no access to drive */
#define ATA_SENSE_MEDIUM_ERROR 0x03 /* non-recovered data error */
#define ATA_SENSE_HARDWARE_ERROR 0x04 /* non-recoverable HW failure */
#define ATA_SENSE_ILLEGAL_REQUEST 0x05 /* invalid command param(s) */
#define ATA_SENSE_UNIT_ATTENTION 0x06 /* media changed */
#define ATA_SENSE_DATA_PROTECT 0x07 /* write protect */
#define ATA_SENSE_BLANK_CHECK 0x08 /* blank check */
#define ATA_SENSE_VENDOR_SPECIFIC 0x09 /* vendor specific skey */
#define ATA_SENSE_COPY_ABORTED 0x0a /* copy aborted */
#define ATA_SENSE_ABORTED_COMMAND 0x0b /* command aborted, try again */
#define ATA_SENSE_EQUAL 0x0c /* equal */
#define ATA_SENSE_VOLUME_OVERFLOW 0x0d /* volume overflow */
#define ATA_SENSE_MISCOMPARE 0x0e /* data dont match the medium */
#define ATA_SENSE_RESERVED 0x0f
#define ATA_SENSE_ILI 0x20;
#define ATA_SENSE_EOM 0x40;
#define ATA_SENSE_FILEMARK 0x80;
u_int32_t cmd_info; /* cmd information */
u_int8_t sense_length; /* additional sense len (n-7) */
u_int32_t cmd_specific_info; /* additional cmd spec info */
u_int8_t asc; /* additional sense code */
u_int8_t ascq; /* additional sense code qual */
u_int8_t replaceable_unit_code; /* replaceable unit code */
u_int8_t specific; /* sense key specific */
#define ATA_SENSE_SPEC_VALID 0x80
#define ATA_SENSE_SPEC_MASK 0x7f
u_int8_t specific1; /* sense key specific */
u_int8_t specific2; /* sense key specific */
} __packed;
struct ata_ioc_request {
union {
struct {
u_int8_t command;
u_int8_t feature;
u_int64_t lba;
u_int16_t count;
} ata;
struct {
char ccb[16];
struct atapi_sense sense;
} atapi;
} u;
caddr_t data;
int count;
int flags;
#define ATA_CMD_CONTROL 0x01
#define ATA_CMD_READ 0x02
#define ATA_CMD_WRITE 0x04
#define ATA_CMD_ATAPI 0x08
int timeout;
int error;
};
struct ata_security_password {
u_int16_t ctrl;
#define ATA_SECURITY_PASSWORD_USER 0x0000
#define ATA_SECURITY_PASSWORD_MASTER 0x0001
#define ATA_SECURITY_ERASE_NORMAL 0x0000
#define ATA_SECURITY_ERASE_ENHANCED 0x0002
#define ATA_SECURITY_LEVEL_HIGH 0x0000
#define ATA_SECURITY_LEVEL_MAXIMUM 0x0100
u_int8_t password[32];
u_int16_t revision;
u_int16_t reserved[238];
};
/* pr device ATA ioctl calls */
#define IOCATAREQUEST _IOWR('a', 100, struct ata_ioc_request)
#define IOCATAGPARM _IOR('a', 101, struct ata_params)
#define IOCATAGMODE _IOR('a', 102, int)
#define IOCATASMODE _IOW('a', 103, int)
#define IOCATAGSPINDOWN _IOR('a', 104, int)
#define IOCATASSPINDOWN _IOW('a', 105, int)
struct ata_ioc_raid_config {
int lun;
int type;
#define AR_JBOD 0x0001
#define AR_SPAN 0x0002
#define AR_RAID0 0x0004
#define AR_RAID1 0x0008
#define AR_RAID01 0x0010
#define AR_RAID3 0x0020
#define AR_RAID4 0x0040
#define AR_RAID5 0x0080
int interleave;
int status;
#define AR_READY 1
#define AR_DEGRADED 2
#define AR_REBUILDING 4
int progress;
int total_disks;
int disks[16];
};
struct ata_ioc_raid_status {
int lun;
int type;
int interleave;
int status;
int progress;
int total_disks;
struct {
int state;
#define AR_DISK_ONLINE 0x01
#define AR_DISK_PRESENT 0x02
#define AR_DISK_SPARE 0x04
int lun;
} disks[16];
};
/* ATA RAID ioctl calls */
#define IOCATARAIDCREATE _IOWR('a', 200, struct ata_ioc_raid_config)
#define IOCATARAIDDELETE _IOW('a', 201, int)
#define IOCATARAIDSTATUS _IOWR('a', 202, struct ata_ioc_raid_status)
#define IOCATARAIDADDSPARE _IOW('a', 203, struct ata_ioc_raid_config)
#define IOCATARAIDREBUILD _IOW('a', 204, int)

View File

@ -0,0 +1,443 @@
/*-
* Copyright (c) 1998 Doug Rabson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <xhyve/support/misc.h>
#define __compiler_membar() __asm __volatile(" " : : : "memory")
#define mb() __asm __volatile("mfence;" : : : "memory")
#define wmb() __asm __volatile("sfence;" : : : "memory")
#define rmb() __asm __volatile("lfence;" : : : "memory")
/*
* Various simple operations on memory, each of which is atomic in the
* presence of interrupts and multiple processors.
*
* atomic_set_char(P, V) (*(u_char *)(P) |= (V))
* atomic_clear_char(P, V) (*(u_char *)(P) &= ~(V))
* atomic_add_char(P, V) (*(u_char *)(P) += (V))
* atomic_subtract_char(P, V) (*(u_char *)(P) -= (V))
*
* atomic_set_short(P, V) (*(u_short *)(P) |= (V))
* atomic_clear_short(P, V) (*(u_short *)(P) &= ~(V))
* atomic_add_short(P, V) (*(u_short *)(P) += (V))
* atomic_subtract_short(P, V) (*(u_short *)(P) -= (V))
*
* atomic_set_int(P, V) (*(u_int *)(P) |= (V))
* atomic_clear_int(P, V) (*(u_int *)(P) &= ~(V))
* atomic_add_int(P, V) (*(u_int *)(P) += (V))
* atomic_subtract_int(P, V) (*(u_int *)(P) -= (V))
* atomic_swap_int(P, V) (return (*(u_int *)(P)); *(u_int *)(P) = (V);)
* atomic_readandclear_int(P) (return (*(u_int *)(P)); *(u_int *)(P) = 0;)
*
* atomic_set_long(P, V) (*(u_long *)(P) |= (V))
* atomic_clear_long(P, V) (*(u_long *)(P) &= ~(V))
* atomic_add_long(P, V) (*(u_long *)(P) += (V))
* atomic_subtract_long(P, V) (*(u_long *)(P) -= (V))
* atomic_swap_long(P, V) (return (*(u_long *)(P)); *(u_long *)(P) = (V);)
* atomic_readandclear_long(P) (return (*(u_long *)(P)); *(u_long *)(P) = 0;)
*/
#define MPLOCKED "lock ; "
/*
* The assembly is volatilized to avoid code chunk removal by the compiler.
* GCC aggressively reorders operations and memory clobbering is necessary
* in order to avoid that for memory barriers.
*/
#define ATOMIC_ASM(NAME, TYPE, OP, CONS, V) \
static __inline void \
atomic_##NAME##_##TYPE(volatile u_##TYPE *p, u_##TYPE v)\
{ \
__asm __volatile(MPLOCKED OP \
: "+m" (*p) \
: CONS (V) \
: "cc"); \
} \
\
static __inline void \
atomic_##NAME##_barr_##TYPE(volatile u_##TYPE *p, u_##TYPE v)\
{ \
__asm __volatile(MPLOCKED OP \
: "+m" (*p) \
: CONS (V) \
: "memory", "cc"); \
} \
struct __hack
/*
* Atomic compare and set, used by the mutex functions
*
* if (*dst == expect) *dst = src (all 32 bit words)
*
* Returns 0 on failure, non-zero on success
*/
static __inline int
atomic_cmpset_int(volatile u_int *dst, u_int expect, u_int src)
{
u_char res;
__asm __volatile(
" " MPLOCKED " "
" cmpxchgl %3,%1 ; "
" sete %0 ; "
"# atomic_cmpset_int"
: "=q" (res), /* 0 */
"+m" (*dst), /* 1 */
"+a" (expect) /* 2 */
: "r" (src) /* 3 */
: "memory", "cc");
return (res);
}
static __inline int
atomic_cmpset_long(volatile u_long *dst, u_long expect, u_long src)
{
u_char res;
__asm __volatile(
" " MPLOCKED " "
" cmpxchgq %3,%1 ; "
" sete %0 ; "
"# atomic_cmpset_long"
: "=q" (res), /* 0 */
"+m" (*dst), /* 1 */
"+a" (expect) /* 2 */
: "r" (src) /* 3 */
: "memory", "cc");
return (res);
}
/*
* Atomically add the value of v to the integer pointed to by p and return
* the previous value of *p.
*/
static __inline u_int
atomic_fetchadd_int(volatile u_int *p, u_int v)
{
__asm __volatile(
" " MPLOCKED " "
" xaddl %0,%1 ; "
"# atomic_fetchadd_int"
: "+r" (v), /* 0 */
"+m" (*p) /* 1 */
: : "cc");
return (v);
}
/*
* Atomically add the value of v to the long integer pointed to by p and return
* the previous value of *p.
*/
static __inline u_long
atomic_fetchadd_long(volatile u_long *p, u_long v)
{
__asm __volatile(
" " MPLOCKED " "
" xaddq %0,%1 ; "
"# atomic_fetchadd_long"
: "+r" (v), /* 0 */
"+m" (*p) /* 1 */
: : "cc");
return (v);
}
static __inline int
atomic_testandset_int(volatile u_int *p, u_int v)
{
u_char res;
__asm __volatile(
" " MPLOCKED " "
" btsl %2,%1 ; "
" setc %0 ; "
"# atomic_testandset_int"
: "=q" (res), /* 0 */
"+m" (*p) /* 1 */
: "Ir" (v & 0x1f) /* 2 */
: "cc");
return (res);
}
static __inline int
atomic_testandset_long(volatile u_long *p, u_int v)
{
u_char res;
__asm __volatile(
" " MPLOCKED " "
" btsq %2,%1 ; "
" setc %0 ; "
"# atomic_testandset_long"
: "=q" (res), /* 0 */
"+m" (*p) /* 1 */
: "Jr" ((u_long)(v & 0x3f)) /* 2 */
: "cc");
return (res);
}
/*
* We assume that a = b will do atomic loads and stores. Due to the
* IA32 memory model, a simple store guarantees release semantics.
*
* However, loads may pass stores, so for atomic_load_acq we have to
* ensure a Store/Load barrier to do the load in SMP kernels. We use
* "lock cmpxchg" as recommended by the AMD Software Optimization
* Guide, and not mfence. For UP kernels, however, the cache of the
* single processor is always consistent, so we only need to take care
* of the compiler.
*/
#define ATOMIC_STORE(TYPE) \
static __inline void \
atomic_store_rel_##TYPE(volatile u_##TYPE *p, u_##TYPE v)\
{ \
__compiler_membar(); \
*p = v; \
} \
struct __hack
#define ATOMIC_LOAD(TYPE, LOP) \
static __inline u_##TYPE \
atomic_load_acq_##TYPE(volatile u_##TYPE *p) \
{ \
u_##TYPE res; \
\
__asm __volatile(MPLOCKED LOP \
: "=a" (res), /* 0 */ \
"+m" (*p) /* 1 */ \
: : "memory", "cc"); \
return (res); \
} \
struct __hack
ATOMIC_ASM(set, char, "orb %b1,%0", "iq", v);
ATOMIC_ASM(clear, char, "andb %b1,%0", "iq", ~v);
ATOMIC_ASM(add, char, "addb %b1,%0", "iq", v);
ATOMIC_ASM(subtract, char, "subb %b1,%0", "iq", v);
ATOMIC_ASM(set, short, "orw %w1,%0", "ir", v);
ATOMIC_ASM(clear, short, "andw %w1,%0", "ir", ~v);
ATOMIC_ASM(add, short, "addw %w1,%0", "ir", v);
ATOMIC_ASM(subtract, short, "subw %w1,%0", "ir", v);
ATOMIC_ASM(set, int, "orl %1,%0", "ir", v);
ATOMIC_ASM(clear, int, "andl %1,%0", "ir", ~v);
ATOMIC_ASM(add, int, "addl %1,%0", "ir", v);
ATOMIC_ASM(subtract, int, "subl %1,%0", "ir", v);
ATOMIC_ASM(set, long, "orq %1,%0", "ir", v);
ATOMIC_ASM(clear, long, "andq %1,%0", "ir", ~v);
ATOMIC_ASM(add, long, "addq %1,%0", "ir", v);
ATOMIC_ASM(subtract, long, "subq %1,%0", "ir", v);
ATOMIC_LOAD(char, "cmpxchgb %b0,%1");
ATOMIC_LOAD(short, "cmpxchgw %w0,%1");
ATOMIC_LOAD(int, "cmpxchgl %0,%1");
ATOMIC_LOAD(long, "cmpxchgq %0,%1");
ATOMIC_STORE(char);
ATOMIC_STORE(short);
ATOMIC_STORE(int);
ATOMIC_STORE(long);
#undef ATOMIC_ASM
#undef ATOMIC_LOAD
#undef ATOMIC_STORE
/* Read the current value and store a new value in the destination. */
static __inline u_int
atomic_swap_int(volatile u_int *p, u_int v)
{
__asm __volatile(
" xchgl %1,%0 ; "
"# atomic_swap_int"
: "+r" (v), /* 0 */
"+m" (*p)); /* 1 */
return (v);
}
static __inline u_long
atomic_swap_long(volatile u_long *p, u_long v)
{
__asm __volatile(
" xchgq %1,%0 ; "
"# atomic_swap_long"
: "+r" (v), /* 0 */
"+m" (*p)); /* 1 */
return (v);
}
#define atomic_set_acq_char atomic_set_barr_char
#define atomic_set_rel_char atomic_set_barr_char
#define atomic_clear_acq_char atomic_clear_barr_char
#define atomic_clear_rel_char atomic_clear_barr_char
#define atomic_add_acq_char atomic_add_barr_char
#define atomic_add_rel_char atomic_add_barr_char
#define atomic_subtract_acq_char atomic_subtract_barr_char
#define atomic_subtract_rel_char atomic_subtract_barr_char
#define atomic_set_acq_short atomic_set_barr_short
#define atomic_set_rel_short atomic_set_barr_short
#define atomic_clear_acq_short atomic_clear_barr_short
#define atomic_clear_rel_short atomic_clear_barr_short
#define atomic_add_acq_short atomic_add_barr_short
#define atomic_add_rel_short atomic_add_barr_short
#define atomic_subtract_acq_short atomic_subtract_barr_short
#define atomic_subtract_rel_short atomic_subtract_barr_short
#define atomic_set_acq_int atomic_set_barr_int
#define atomic_set_rel_int atomic_set_barr_int
#define atomic_clear_acq_int atomic_clear_barr_int
#define atomic_clear_rel_int atomic_clear_barr_int
#define atomic_add_acq_int atomic_add_barr_int
#define atomic_add_rel_int atomic_add_barr_int
#define atomic_subtract_acq_int atomic_subtract_barr_int
#define atomic_subtract_rel_int atomic_subtract_barr_int
#define atomic_cmpset_acq_int atomic_cmpset_int
#define atomic_cmpset_rel_int atomic_cmpset_int
#define atomic_set_acq_long atomic_set_barr_long
#define atomic_set_rel_long atomic_set_barr_long
#define atomic_clear_acq_long atomic_clear_barr_long
#define atomic_clear_rel_long atomic_clear_barr_long
#define atomic_add_acq_long atomic_add_barr_long
#define atomic_add_rel_long atomic_add_barr_long
#define atomic_subtract_acq_long atomic_subtract_barr_long
#define atomic_subtract_rel_long atomic_subtract_barr_long
#define atomic_cmpset_acq_long atomic_cmpset_long
#define atomic_cmpset_rel_long atomic_cmpset_long
#define atomic_readandclear_int(p) atomic_swap_int(p, 0)
#define atomic_readandclear_long(p) atomic_swap_long(p, 0)
/* Operations on 8-bit bytes. */
#define atomic_set_8 atomic_set_char
#define atomic_set_acq_8 atomic_set_acq_char
#define atomic_set_rel_8 atomic_set_rel_char
#define atomic_clear_8 atomic_clear_char
#define atomic_clear_acq_8 atomic_clear_acq_char
#define atomic_clear_rel_8 atomic_clear_rel_char
#define atomic_add_8 atomic_add_char
#define atomic_add_acq_8 atomic_add_acq_char
#define atomic_add_rel_8 atomic_add_rel_char
#define atomic_subtract_8 atomic_subtract_char
#define atomic_subtract_acq_8 atomic_subtract_acq_char
#define atomic_subtract_rel_8 atomic_subtract_rel_char
#define atomic_load_acq_8 atomic_load_acq_char
#define atomic_store_rel_8 atomic_store_rel_char
/* Operations on 16-bit words. */
#define atomic_set_16 atomic_set_short
#define atomic_set_acq_16 atomic_set_acq_short
#define atomic_set_rel_16 atomic_set_rel_short
#define atomic_clear_16 atomic_clear_short
#define atomic_clear_acq_16 atomic_clear_acq_short
#define atomic_clear_rel_16 atomic_clear_rel_short
#define atomic_add_16 atomic_add_short
#define atomic_add_acq_16 atomic_add_acq_short
#define atomic_add_rel_16 atomic_add_rel_short
#define atomic_subtract_16 atomic_subtract_short
#define atomic_subtract_acq_16 atomic_subtract_acq_short
#define atomic_subtract_rel_16 atomic_subtract_rel_short
#define atomic_load_acq_16 atomic_load_acq_short
#define atomic_store_rel_16 atomic_store_rel_short
/* Operations on 32-bit double words. */
#define atomic_set_32 atomic_set_int
#define atomic_set_acq_32 atomic_set_acq_int
#define atomic_set_rel_32 atomic_set_rel_int
#define atomic_clear_32 atomic_clear_int
#define atomic_clear_acq_32 atomic_clear_acq_int
#define atomic_clear_rel_32 atomic_clear_rel_int
#define atomic_add_32 atomic_add_int
#define atomic_add_acq_32 atomic_add_acq_int
#define atomic_add_rel_32 atomic_add_rel_int
#define atomic_subtract_32 atomic_subtract_int
#define atomic_subtract_acq_32 atomic_subtract_acq_int
#define atomic_subtract_rel_32 atomic_subtract_rel_int
#define atomic_load_acq_32 atomic_load_acq_int
#define atomic_store_rel_32 atomic_store_rel_int
#define atomic_cmpset_32 atomic_cmpset_int
#define atomic_cmpset_acq_32 atomic_cmpset_acq_int
#define atomic_cmpset_rel_32 atomic_cmpset_rel_int
#define atomic_swap_32 atomic_swap_int
#define atomic_readandclear_32 atomic_readandclear_int
#define atomic_fetchadd_32 atomic_fetchadd_int
#define atomic_testandset_32 atomic_testandset_int
/* Operations on 64-bit quad words. */
#define atomic_set_64 atomic_set_long
#define atomic_set_acq_64 atomic_set_acq_long
#define atomic_set_rel_64 atomic_set_rel_long
#define atomic_clear_64 atomic_clear_long
#define atomic_clear_acq_64 atomic_clear_acq_long
#define atomic_clear_rel_64 atomic_clear_rel_long
#define atomic_add_64 atomic_add_long
#define atomic_add_acq_64 atomic_add_acq_long
#define atomic_add_rel_64 atomic_add_rel_long
#define atomic_subtract_64 atomic_subtract_long
#define atomic_subtract_acq_64 atomic_subtract_acq_long
#define atomic_subtract_rel_64 atomic_subtract_rel_long
#define atomic_load_acq_64 atomic_load_acq_long
#define atomic_store_rel_64 atomic_store_rel_long
#define atomic_cmpset_64 atomic_cmpset_long
#define atomic_cmpset_acq_64 atomic_cmpset_acq_long
#define atomic_cmpset_rel_64 atomic_cmpset_rel_long
#define atomic_swap_64 atomic_swap_long
#define atomic_readandclear_64 atomic_readandclear_long
#define atomic_testandset_64 atomic_testandset_long
/* Operations on pointers. */
#define atomic_set_ptr atomic_set_long
#define atomic_set_acq_ptr atomic_set_acq_long
#define atomic_set_rel_ptr atomic_set_rel_long
#define atomic_clear_ptr atomic_clear_long
#define atomic_clear_acq_ptr atomic_clear_acq_long
#define atomic_clear_rel_ptr atomic_clear_rel_long
#define atomic_add_ptr atomic_add_long
#define atomic_add_acq_ptr atomic_add_acq_long
#define atomic_add_rel_ptr atomic_add_rel_long
#define atomic_subtract_ptr atomic_subtract_long
#define atomic_subtract_acq_ptr atomic_subtract_acq_long
#define atomic_subtract_rel_ptr atomic_subtract_rel_long
#define atomic_load_acq_ptr atomic_load_acq_long
#define atomic_store_rel_ptr atomic_store_rel_long
#define atomic_cmpset_ptr atomic_cmpset_long
#define atomic_cmpset_acq_ptr atomic_cmpset_acq_long
#define atomic_cmpset_rel_ptr atomic_cmpset_rel_long
#define atomic_swap_ptr atomic_swap_long
#define atomic_readandclear_ptr atomic_readandclear_long

View File

@ -0,0 +1,215 @@
/*-
* Copyright (c) 2008, Jeffrey Roberson <jeff@freebsd.org>
* All rights reserved.
*
* Copyright (c) 2008 Nokia Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice unmodified, this list of conditions, and the following
* disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <strings.h>
#include <sys/types.h>
/*
* Macros addressing word and bit within it, tuned to make compiler
* optimize cases when SETSIZE fits into single machine word.
*/
#define _BITSET_BITS (sizeof(long) * NBBY)
#define __bitset_words(_s) (howmany(_s, _BITSET_BITS))
#define __bitset_mask(_s, n) \
(1L << ((__bitset_words((_s)) == 1) ? \
(size_t)(n) : ((n) % _BITSET_BITS)))
#define __bitset_word(_s, n) \
((__bitset_words((_s)) == 1) ? 0 : ((n) / _BITSET_BITS))
#define BITSET_DEFINE(t, _s) \
struct t { \
long __bits[__bitset_words((_s))]; \
}
#define BITSET_T_INITIALIZER(x) \
{ .__bits = { x } }
#define BITSET_FSET(n) \
[ 0 ... ((n) - 1) ] = (-1L)
#define BIT_CLR(_s, n, p) \
((p)->__bits[__bitset_word(_s, n)] &= ~__bitset_mask((_s), (n)))
#define BIT_COPY(_s, f, t) (void)(*(t) = *(f))
#define BIT_ISSET(_s, n, p) \
((((p)->__bits[__bitset_word(_s, n)] & __bitset_mask((_s), (n))) != 0))
#define BIT_SET(_s, n, p) \
((p)->__bits[__bitset_word(_s, n)] |= __bitset_mask((_s), (n)))
#define BIT_ZERO(_s, p) do { \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
(p)->__bits[__i] = 0L; \
} while (0)
#define BIT_FILL(_s, p) do { \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
(p)->__bits[__i] = -1L; \
} while (0)
#define BIT_SETOF(_s, n, p) do { \
BIT_ZERO(_s, p); \
(p)->__bits[__bitset_word(_s, n)] = __bitset_mask((_s), (n)); \
} while (0)
/* Is p empty. */
#define BIT_EMPTY(_s, p) __extension__ ({ \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
if ((p)->__bits[__i]) \
break; \
__i == __bitset_words((_s)); \
})
/* Is p full set. */
#define BIT_ISFULLSET(_s, p) __extension__ ({ \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
if ((p)->__bits[__i] != (long)-1) \
break; \
__i == __bitset_words((_s)); \
})
/* Is c a subset of p. */
#define BIT_SUBSET(_s, p, c) __extension__ ({ \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
if (((c)->__bits[__i] & \
(p)->__bits[__i]) != \
(c)->__bits[__i]) \
break; \
__i == __bitset_words((_s)); \
})
/* Are there any common bits between b & c? */
#define BIT_OVERLAP(_s, p, c) __extension__ ({ \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
if (((c)->__bits[__i] & \
(p)->__bits[__i]) != 0) \
break; \
__i != __bitset_words((_s)); \
})
/* Compare two sets, returns 0 if equal 1 otherwise. */
#define BIT_CMP(_s, p, c) __extension__ ({ \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
if (((c)->__bits[__i] != \
(p)->__bits[__i])) \
break; \
__i != __bitset_words((_s)); \
})
#define BIT_OR(_s, d, s) do { \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
(d)->__bits[__i] |= (s)->__bits[__i]; \
} while (0)
#define BIT_AND(_s, d, s) do { \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
(d)->__bits[__i] &= (s)->__bits[__i]; \
} while (0)
#define BIT_NAND(_s, d, s) do { \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
(d)->__bits[__i] &= ~(s)->__bits[__i]; \
} while (0)
#define BIT_CLR_ATOMIC(_s, n, p) \
atomic_clear_long(((volatile u_long *) \
&(p)->__bits[__bitset_word(_s, n)]), __bitset_mask((_s), n))
#define BIT_SET_ATOMIC(_s, n, p) \
atomic_set_long(((volatile u_long *) &(p)->__bits[__bitset_word(_s, n)]), \
__bitset_mask((_s), n))
#define BIT_SET_ATOMIC_ACQ(_s, n, p) \
atomic_set_acq_long(&(p)->__bits[__bitset_word(_s, n)], \
__bitset_mask((_s), n))
/* Convenience functions catering special cases. */
#define BIT_AND_ATOMIC(_s, d, s) do { \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
atomic_clear_long(&(d)->__bits[__i], \
~(s)->__bits[__i]); \
} while (0)
#define BIT_OR_ATOMIC(_s, d, s) do { \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
atomic_set_long(&(d)->__bits[__i], \
(s)->__bits[__i]); \
} while (0)
#define BIT_COPY_STORE_REL(_s, f, t) do { \
size_t __i; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
atomic_store_rel_long(&(t)->__bits[__i], \
(f)->__bits[__i]); \
} while (0)
#define BIT_FFS(_s, p) __extension__ ({ \
size_t __i; \
int __bit; \
\
__bit = 0; \
for (__i = 0; __i < __bitset_words((_s)); __i++) { \
if ((p)->__bits[__i] != 0) { \
__bit = ffsl((p)->__bits[__i]); \
__bit += __i * _BITSET_BITS; \
break; \
} \
} \
__bit; \
})
#define BIT_COUNT(_s, p) __extension__ ({ \
size_t __i; \
int __count; \
\
__count = 0; \
for (__i = 0; __i < __bitset_words((_s)); __i++) \
__count += __bitcountl((p)->__bits[__i]); \
__count; \
})

View File

@ -0,0 +1,150 @@
/*-
* Copyright (c) 2008, Jeffrey Roberson <jeff@freebsd.org>
* All rights reserved.
*
* Copyright (c) 2008 Nokia Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice unmodified, this list of conditions, and the following
* disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <xhyve/support/bitset.h>
#define CPU_MAXSIZE 32
#ifndef CPU_SETSIZE
#define CPU_SETSIZE CPU_MAXSIZE
#endif
// #define _NCPUBITS _BITSET_BITS
// #define _NCPUWORDS __bitset_words(CPU_SETSIZE)
BITSET_DEFINE(_cpuset, CPU_SETSIZE);
typedef struct _cpuset cpuset_t;
// #define CPUSET_FSET BITSET_FSET(_NCPUWORDS)
// #define CPUSET_T_INITIALIZER BITSET_T_INITIALIZER
// #define CPUSETBUFSIZ ((2 + sizeof(long) * 2) * _NCPUWORDS)
#define CPU_CLR(n, p) BIT_CLR(CPU_SETSIZE, n, p)
// #define CPU_COPY(f, t) BIT_COPY(CPU_SETSIZE, f, t)
#define CPU_ISSET(n, p) BIT_ISSET(CPU_SETSIZE, n, p)
#define CPU_SET(n, p) BIT_SET(CPU_SETSIZE, n, p)
#define CPU_ZERO(p) BIT_ZERO(CPU_SETSIZE, p)
// #define CPU_FILL(p) BIT_FILL(CPU_SETSIZE, p)
#define CPU_SETOF(n, p) BIT_SETOF(CPU_SETSIZE, n, p)
#define CPU_EMPTY(p) BIT_EMPTY(CPU_SETSIZE, p)
// #define CPU_ISFULLSET(p) BIT_ISFULLSET(CPU_SETSIZE, p)
// #define CPU_SUBSET(p, c) BIT_SUBSET(CPU_SETSIZE, p, c)
// #define CPU_OVERLAP(p, c) BIT_OVERLAP(CPU_SETSIZE, p, c)
#define CPU_CMP(p, c) BIT_CMP(CPU_SETSIZE, p, c)
// #define CPU_OR(d, s) BIT_OR(CPU_SETSIZE, d, s)
#define CPU_AND(d, s) BIT_AND(CPU_SETSIZE, d, s)
// #define CPU_NAND(d, s) BIT_NAND(CPU_SETSIZE, d, s)
#define CPU_CLR_ATOMIC(n, p) BIT_CLR_ATOMIC(CPU_SETSIZE, n, p)
#define CPU_SET_ATOMIC(n, p) BIT_SET_ATOMIC(CPU_SETSIZE, n, p)
// #define CPU_SET_ATOMIC_ACQ(n, p) BIT_SET_ATOMIC_ACQ(CPU_SETSIZE, n, p)
// #define CPU_AND_ATOMIC(n, p) BIT_AND_ATOMIC(CPU_SETSIZE, n, p)
// #define CPU_OR_ATOMIC(d, s) BIT_OR_ATOMIC(CPU_SETSIZE, d, s)
// #define CPU_COPY_STORE_REL(f, t) BIT_COPY_STORE_REL(CPU_SETSIZE, f, t)
#define CPU_FFS(p) BIT_FFS(CPU_SETSIZE, p)
// #define CPU_COUNT(p) BIT_COUNT(CPU_SETSIZE, p)
// /*
// * Valid cpulevel_t values.
// */
// #define CPU_LEVEL_ROOT 1 /* All system cpus. */
// #define CPU_LEVEL_CPUSET 2 /* Available cpus for which. */
// #define CPU_LEVEL_WHICH 3 /* Actual mask/id for which. */
// /*
// * Valid cpuwhich_t values.
// */
// #define CPU_WHICH_TID 1 /* Specifies a thread id. */
// #define CPU_WHICH_PID 2 /* Specifies a process id. */
// #define CPU_WHICH_CPUSET 3 /* Specifies a set id. */
// #define CPU_WHICH_IRQ 4 /* Specifies an irq #. */
// #define CPU_WHICH_JAIL 5 /* Specifies a jail id. */
// #define CPU_WHICH_DOMAIN 6 /* Specifies a NUMA domain id. */
// /*
// * Reserved cpuset identifiers.
// */
// #define CPUSET_INVALID -1
// #define CPUSET_DEFAULT 0
// #ifdef _KERNEL
// LIST_HEAD(setlist, cpuset);
// /*
// * cpusets encapsulate cpu binding information for one or more threads.
// *
// * a - Accessed with atomics.
// * s - Set at creation, never modified. Only a ref required to read.
// * c - Locked internally by a cpuset lock.
// *
// * The bitmask is only modified while holding the cpuset lock. It may be
// * read while only a reference is held but the consumer must be prepared
// * to deal with inconsistent results.
// */
// struct cpuset {
// cpuset_t cs_mask; /* bitmask of valid cpus. */
// volatile u_int cs_ref; /* (a) Reference count. */
// int cs_flags; /* (s) Flags from below. */
// cpusetid_t cs_id; /* (s) Id or INVALID. */
// struct cpuset *cs_parent; /* (s) Pointer to our parent. */
// LIST_ENTRY(cpuset) cs_link; /* (c) All identified sets. */
// LIST_ENTRY(cpuset) cs_siblings; /* (c) Sibling set link. */
// struct setlist cs_children; /* (c) List of children. */
// };
// #define CPU_SET_ROOT 0x0001 /* Set is a root set. */
// #define CPU_SET_RDONLY 0x0002 /* No modification allowed. */
// extern cpuset_t *cpuset_root;
// struct prison;
// struct proc;
// struct cpuset *cpuset_thread0(void);
// struct cpuset *cpuset_ref(struct cpuset *);
// void cpuset_rel(struct cpuset *);
// int cpuset_setthread(lwpid_t id, cpuset_t *);
// int cpuset_setithread(lwpid_t id, int cpu);
// int cpuset_create_root(struct prison *, struct cpuset **);
// int cpuset_setproc_update_set(struct proc *, struct cpuset *);
// char *cpusetobj_strprint(char *, const cpuset_t *);
// int cpusetobj_strscan(cpuset_t *, const char *);
// #else
// __BEGIN_DECLS
// int cpuset(cpusetid_t *);
// int cpuset_setid(cpuwhich_t, id_t, cpusetid_t);
// int cpuset_getid(cpulevel_t, cpuwhich_t, id_t, cpusetid_t *);
// int cpuset_getaffinity(cpulevel_t, cpuwhich_t, id_t, size_t, cpuset_t *);
// int cpuset_setaffinity(cpulevel_t, cpuwhich_t, id_t, size_t, const cpuset_t *);
// __END_DECLS
// #endif

View File

@ -0,0 +1,81 @@
/*-
* Copyright (c) 1993 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* from: Header: timerreg.h,v 1.2 93/02/28 15:08:58 mccanne Exp
* $FreeBSD$
*/
/*
* Register definitions for the Intel 8253 Programmable Interval Timer.
*
* This chip has three independent 16-bit down counters that can be
* read on the fly. There are three mode registers and three countdown
* registers. The countdown registers are addressed directly, via the
* first three I/O ports. The three mode registers are accessed via
* the fourth I/O port, with two bits in the mode byte indicating the
* register. (Why are hardware interfaces always so braindead?).
*
* To write a value into the countdown register, the mode register
* is first programmed with a command indicating the which byte of
* the two byte register is to be modified. The three possibilities
* are load msb (TMR_MR_MSB), load lsb (TMR_MR_LSB), or load lsb then
* msb (TMR_MR_BOTH).
*
* To read the current value ("on the fly") from the countdown register,
* you write a "latch" command into the mode register, then read the stable
* value from the corresponding I/O port. For example, you write
* TMR_MR_LATCH into the corresponding mode register. Presumably,
* after doing this, a write operation to the I/O port would result
* in undefined behavior (but hopefully not fry the chip).
* Reading in this manner has no side effects.
*/
/*
* Macros for specifying values to be written into a mode register.
*/
#pragma once
#define TIMER_REG_CNTR0 0 /* timer 0 counter port */
#define TIMER_REG_CNTR1 1 /* timer 1 counter port */
#define TIMER_REG_CNTR2 2 /* timer 2 counter port */
#define TIMER_REG_MODE 3 /* timer mode port */
#define TIMER_SEL0 0x00 /* select counter 0 */
#define TIMER_SEL1 0x40 /* select counter 1 */
#define TIMER_SEL2 0x80 /* select counter 2 */
#define TIMER_INTTC 0x00 /* mode 0, intr on terminal cnt */
#define TIMER_ONESHOT 0x02 /* mode 1, one shot */
#define TIMER_RATEGEN 0x04 /* mode 2, rate generator */
#define TIMER_SQWAVE 0x06 /* mode 3, square wave */
#define TIMER_SWSTROBE 0x08 /* mode 4, s/w triggered strobe */
#define TIMER_HWSTROBE 0x0a /* mode 5, h/w triggered strobe */
#define TIMER_LATCH 0x00 /* latch counter for reading */
#define TIMER_LSB 0x10 /* r/w counter LSB */
#define TIMER_MSB 0x20 /* r/w counter MSB */
#define TIMER_16BIT 0x30 /* r/w counter 16 bits, LSB first */
#define TIMER_BCD 0x01 /* count in BCD */

View File

@ -0,0 +1,83 @@
/*-
* Copyright (c) 2003 Peter Wemm
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
/*
* Register defintions for the i8259A programmable interrupt controller.
*/
#pragma once
/* Initialization control word 1. Written to even address. */
#define ICW1_IC4 0x01 /* ICW4 present */
#define ICW1_SNGL 0x02 /* 1 = single, 0 = cascaded */
#define ICW1_ADI 0x04 /* 1 = 4, 0 = 8 byte vectors */
#define ICW1_LTIM 0x08 /* 1 = level trigger, 0 = edge */
#define ICW1_RESET 0x10 /* must be 1 */
/* 0x20 - 0x80 - in 8080/8085 mode only */
/* Initialization control word 2. Written to the odd address. */
/* No definitions, it is the base vector of the IDT for 8086 mode */
/* Initialization control word 3. Written to the odd address. */
/* For a master PIC, bitfield indicating a slave 8259 on given input */
/* For slave, lower 3 bits are the slave's ID binary id on master */
/* Initialization control word 4. Written to the odd address. */
#define ICW4_8086 0x01 /* 1 = 8086, 0 = 8080 */
#define ICW4_AEOI 0x02 /* 1 = Auto EOI */
#define ICW4_MS 0x04 /* 1 = buffered master, 0 = slave */
#define ICW4_BUF 0x08 /* 1 = enable buffer mode */
#define ICW4_SFNM 0x10 /* 1 = special fully nested mode */
/* Operation control words. Written after initialization. */
/* Operation control word type 1 */
/*
* No definitions. Written to the odd address. Bitmask for interrupts.
* 1 = disabled.
*/
/* Operation control word type 2. Bit 3 (0x08) must be zero. Even address. */
#define OCW2_L0 0x01 /* Level */
#define OCW2_L1 0x02
#define OCW2_L2 0x04
/* 0x08 must be 0 to select OCW2 vs OCW3 */
/* 0x10 must be 0 to select OCW2 vs ICW1 */
#define OCW2_EOI 0x20 /* 1 = EOI */
#define OCW2_SL 0x40 /* EOI mode */
#define OCW2_R 0x80 /* EOI mode */
/* Operation control word type 3. Bit 3 (0x08) must be set. Even address. */
#define OCW3_RIS 0x01 /* 1 = read IS, 0 = read IR */
#define OCW3_RR 0x02 /* register read */
#define OCW3_P 0x04 /* poll mode command */
/* 0x08 must be 1 to select OCW3 vs OCW2 */
#define OCW3_SEL 0x08 /* must be 1 */
/* 0x10 must be 0 to select OCW3 vs ICW1 */
#define OCW3_SMM 0x20 /* special mode mask */
#define OCW3_ESMM 0x40 /* enable SMM */

View File

@ -0,0 +1,96 @@
/*-
* Copyright (c) 1999 John D. Polstra
* Copyright (c) 1999,2001 Peter Wemm <peter@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
/* xhyve: sort of working linker sets for MachO */
#pragma once
#define __GLOBL1(sym) __asm__(".globl " #sym)
#define __GLOBL(sym) __GLOBL1(sym)
#define __section(x) __attribute__((__section__(x)))
/*
* The following macros are used to declare global sets of objects, which
* are collected by the linker into a `linker_set' as defined below.
* For ELF, this is done by constructing a separate segment for each set.
*/
#define __MAKE_SET_CONST const
/*
* Private macros, not to be used outside this header file.
*/
#define __MAKE_SET(set, sym) \
__GLOBL(__CONCAT(__start_set_,set)); \
__GLOBL(__CONCAT(__stop_set_,set)); \
static void const * __MAKE_SET_CONST \
__set_##set##_sym_##sym __section("__"#set",__set") \
__used = &(sym)
/*
* Public macros.
*/
#define TEXT_SET(set, sym) __MAKE_SET(set, sym)
#define DATA_SET(set, sym) __MAKE_SET(set, sym)
#define BSS_SET(set, sym) __MAKE_SET(set, sym)
#define ABS_SET(set, sym) __MAKE_SET(set, sym)
#define SET_ENTRY(set, sym) __MAKE_SET(set, sym)
/*
* Initialize before referring to a given linker set.
*/
#define SET_DECLARE(set, ptype) \
extern ptype __weak *__CONCAT(__start_set_,set) \
__asm("segment$start$__"#set); \
extern ptype __weak *__CONCAT(__stop_set_,set) \
__asm("segment$end$__"#set)
#define SET_BEGIN(set) \
(&__CONCAT(__start_set_,set))
#define SET_LIMIT(set) \
(&__CONCAT(__stop_set_,set))
/*
* Iterate over all the elements of a set.
*
* Sets always contain addresses of things, and "pvar" points to words
* containing those addresses. Thus is must be declared as "type **pvar",
* and the address of each set item is obtained inside the loop by "*pvar".
*/
#define SET_FOREACH(pvar, set) \
for (pvar = SET_BEGIN(set); pvar < SET_LIMIT(set); pvar++)
#define SET_ITEM(set, i) \
((SET_BEGIN(set))[i])
/*
* Provide a count of the items in a set.
*/
#define SET_COUNT(set) \
(SET_LIMIT(set) - SET_BEGIN(set))

View File

@ -0,0 +1,49 @@
/* MD5.H - header file for MD5C.C
* $FreeBSD$
*/
/*-
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
#pragma once
#include <xhyve/support/misc.h>
#define MD5_BLOCK_LENGTH 64
#define MD5_DIGEST_LENGTH 16
#define MD5_DIGEST_STRING_LENGTH (MD5_DIGEST_LENGTH * 2 + 1)
/* MD5 context. */
typedef struct MD5Context {
u_int32_t state[4]; /* state (ABCD) */
u_int32_t count[2]; /* number of bits, modulo 2^64 (lsb first) */
unsigned char buffer[64]; /* input buffer */
} MD5_CTX;
void MD5Init(MD5_CTX *);
void MD5Update(MD5_CTX *, const void *, unsigned int);
void MD5Final(unsigned char [16], MD5_CTX *);
char * MD5End(MD5_CTX *, char *);
char * MD5File(const char *, char *);
char * MD5FileChunk(const char *, char *, off_t, off_t);
char * MD5Data(const void *, unsigned int, char *);

View File

@ -0,0 +1,94 @@
#pragma once
#include <assert.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define UNUSED __attribute__ ((unused))
#define CTASSERT(x) _Static_assert ((x), "CTASSERT")
#define XHYVE_PAGE_SIZE 0x1000
#define XHYVE_PAGE_MASK (XHYVE_PAGE_SIZE - 1)
#define XHYVE_PAGE_SHIFT 12
#define __aligned(x) __attribute__ ((aligned ((x))))
#define __packed __attribute__ ((packed))
#define nitems(x) (sizeof((x)) / sizeof((x)[0]))
#define powerof2(x) ((((x)-1)&(x))==0)
#define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */
#define nitems(x) (sizeof((x)) / sizeof((x)[0]))
#define min(x, y) (((x) < (y)) ? (x) : (y))
#define xhyve_abort(...) \
do { \
fprintf(stderr, __VA_ARGS__); \
abort(); \
} while (0)
#define xhyve_warn(...) \
do { \
fprintf(stderr, __VA_ARGS__); \
} while (0)
#ifdef XHYVE_CONFIG_ASSERT
#define KASSERT(exp, msg) if (!(exp)) xhyve_abort msg
#define KWARN(exp, msg) if (!(exp)) xhyve_warn msg
#else
#define KASSERT(exp, msg) if (0) xhyve_abort msg
#define KWARN(exp, msg) if (0) xhyve_warn msg
#endif
#define FALSE 0
#define TRUE 1
#define XHYVE_PROT_READ 1
#define XHYVE_PROT_WRITE 2
#define XHYVE_PROT_EXECUTE 4
#define VM_SUCCESS 0
/* sys/sys/types.h */
typedef unsigned char u_char;
typedef unsigned short u_short;
typedef unsigned int u_int;
typedef unsigned long u_long;
static inline void cpuid_count(uint32_t ax, uint32_t cx, uint32_t *p) {
__asm__ __volatile__ ("cpuid"
: "=a" (p[0]), "=b" (p[1]), "=c" (p[2]), "=d" (p[3])
: "0" (ax), "c" (cx));
}
static inline void do_cpuid(unsigned ax, unsigned *p) {
__asm__ __volatile__ ("cpuid"
: "=a" (p[0]), "=b" (p[1]), "=c" (p[2]), "=d" (p[3])
: "0" (ax));
}
/* Used to trigger a self-shutdown */
extern void push_power_button(void);
/* Error checking pthread mutex operations */
static inline void xpthread_mutex_init(pthread_mutex_t *mutex)
{
int rc = pthread_mutex_init(mutex, NULL);
if (__builtin_expect(rc != 0, 0))
xhyve_abort("pthread_mutex_init failed: %d: %s\n",
rc, strerror(rc));
}
static inline void xpthread_mutex_lock(pthread_mutex_t *mutex)
{
int rc = pthread_mutex_lock(mutex);
if (__builtin_expect(rc != 0, 0))
xhyve_abort("pthread_mutex_lock failed: %d: %s\n",
rc, strerror(rc));
}
static inline void xpthread_mutex_unlock(pthread_mutex_t *mutex)
{
int rc = pthread_mutex_unlock(mutex);
if (__builtin_expect(rc != 0, 0))
xhyve_abort("pthread_mutex_unlock failed: %d: %s\n",
rc, strerror(rc));
}

View File

@ -0,0 +1,189 @@
/*-
* Copyright (c) 1996, by Steve Passe
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. The name of the developer may NOT be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <xhyve/support/misc.h>
enum busTypes {
NOBUS = 0,
CBUS = 1,
CBUSII = 2,
EISA = 3,
ISA = 6,
MCA = 9,
PCI = 13,
XPRESS = 18,
MAX_BUSTYPE = 18,
UNKNOWN_BUSTYPE = 0xff
};
/* MP Floating Pointer Structure */
typedef struct MPFPS {
uint8_t signature[4];
uint32_t pap;
uint8_t length;
uint8_t spec_rev;
uint8_t checksum;
uint8_t config_type;
uint8_t mpfb2;
uint8_t mpfb3;
uint8_t mpfb4;
uint8_t mpfb5;
} __packed *mpfps_t;
#define MPFB2_IMCR_PRESENT 0x80
#define MPFB2_MUL_CLK_SRCS 0x40
/* MP Configuration Table Header */
typedef struct MPCTH {
uint8_t signature[4];
uint16_t base_table_length;
uint8_t spec_rev;
uint8_t checksum;
uint8_t oem_id[8];
uint8_t product_id[12];
uint32_t oem_table_pointer;
uint16_t oem_table_size;
uint16_t entry_count;
uint32_t apic_address;
uint16_t extended_table_length;
uint8_t extended_table_checksum;
uint8_t reserved;
} __packed *mpcth_t;
/* Base table entries */
#define MPCT_ENTRY_PROCESSOR 0
#define MPCT_ENTRY_BUS 1
#define MPCT_ENTRY_IOAPIC 2
#define MPCT_ENTRY_INT 3
#define MPCT_ENTRY_LOCAL_INT 4
typedef struct PROCENTRY {
uint8_t type;
uint8_t apic_id;
uint8_t apic_version;
uint8_t cpu_flags;
uint32_t cpu_signature;
uint32_t feature_flags;
uint32_t reserved1;
uint32_t reserved2;
} __packed *proc_entry_ptr;
#define PROCENTRY_FLAG_EN 0x01
#define PROCENTRY_FLAG_BP 0x02
typedef struct BUSENTRY {
uint8_t type;
uint8_t bus_id;
uint8_t bus_type[6];
} __packed *bus_entry_ptr;
typedef struct IOAPICENTRY {
uint8_t type;
uint8_t apic_id;
uint8_t apic_version;
uint8_t apic_flags;
uint32_t apic_address;
} __packed *io_apic_entry_ptr;
#define IOAPICENTRY_FLAG_EN 0x01
typedef struct INTENTRY {
uint8_t type;
uint8_t int_type;
uint16_t int_flags;
uint8_t src_bus_id;
uint8_t src_bus_irq;
uint8_t dst_apic_id;
uint8_t dst_apic_int;
} __packed *int_entry_ptr;
#define INTENTRY_TYPE_INT 0
#define INTENTRY_TYPE_NMI 1
#define INTENTRY_TYPE_SMI 2
#define INTENTRY_TYPE_EXTINT 3
#define INTENTRY_FLAGS_POLARITY 0x3
#define INTENTRY_FLAGS_POLARITY_CONFORM 0x0
#define INTENTRY_FLAGS_POLARITY_ACTIVEHI 0x1
#define INTENTRY_FLAGS_POLARITY_ACTIVELO 0x3
#define INTENTRY_FLAGS_TRIGGER 0xc
#define INTENTRY_FLAGS_TRIGGER_CONFORM 0x0
#define INTENTRY_FLAGS_TRIGGER_EDGE 0x4
#define INTENTRY_FLAGS_TRIGGER_LEVEL 0xc
/* Extended table entries */
typedef struct EXTENTRY {
uint8_t type;
uint8_t length;
} __packed *ext_entry_ptr;
#define MPCT_EXTENTRY_SAS 0x80
#define MPCT_EXTENTRY_BHD 0x81
#define MPCT_EXTENTRY_CBASM 0x82
typedef struct SASENTRY {
uint8_t type;
uint8_t length;
uint8_t bus_id;
uint8_t address_type;
uint64_t address_base;
uint64_t address_length;
} __packed *sas_entry_ptr;
#define SASENTRY_TYPE_IO 0
#define SASENTRY_TYPE_MEMORY 1
#define SASENTRY_TYPE_PREFETCH 2
typedef struct BHDENTRY {
uint8_t type;
uint8_t length;
uint8_t bus_id;
uint8_t bus_info;
uint8_t parent_bus;
uint8_t reserved[3];
} __packed *bhd_entry_ptr;
#define BHDENTRY_INFO_SUBTRACTIVE_DECODE 0x1
typedef struct CBASMENTRY {
uint8_t type;
uint8_t length;
uint8_t bus_id;
uint8_t address_mod;
uint32_t predefined_range;
} __packed *cbasm_entry_ptr;
#define CBASMENTRY_ADDRESS_MOD_ADD 0x0
#define CBASMENTRY_ADDRESS_MOD_SUBTRACT 0x1
#define CBASMENTRY_RANGE_ISA_IO 0
#define CBASMENTRY_RANGE_VGA_IO 1

View File

@ -0,0 +1,242 @@
/*-
* Copyright (c) 1991 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* from: @(#)ns16550.h 7.1 (Berkeley) 5/9/91
* $FreeBSD$
*/
/*
* NS8250... UART registers.
*/
/* 8250 registers #[0-6]. */
#pragma once
#define com_data 0 /* data register (R/W) */
#define REG_DATA com_data
#define com_ier 1 /* interrupt enable register (W) */
#define REG_IER com_ier
#define IER_ERXRDY 0x1
#define IER_ETXRDY 0x2
#define IER_ERLS 0x4
#define IER_EMSC 0x8
#define IER_BITS "\20\1ERXRDY\2ETXRDY\3ERLS\4EMSC"
#define com_iir 2 /* interrupt identification register (R) */
#define REG_IIR com_iir
#define IIR_IMASK 0xf
#define IIR_RXTOUT 0xc
#define IIR_BUSY 0x7
#define IIR_RLS 0x6
#define IIR_RXRDY 0x4
#define IIR_TXRDY 0x2
#define IIR_NOPEND 0x1
#define IIR_MLSC 0x0
#define IIR_FIFO_MASK 0xc0 /* set if FIFOs are enabled */
#define IIR_BITS "\20\1NOPEND\2TXRDY\3RXRDY"
#define com_lcr 3 /* line control register (R/W) */
#define com_cfcr com_lcr /* character format control register (R/W) */
#define REG_LCR com_lcr
#define LCR_DLAB 0x80
#define CFCR_DLAB LCR_DLAB
#define LCR_EFR_ENABLE 0xbf /* magic to enable EFR on 16650 up */
#define CFCR_EFR_ENABLE LCR_EFR_ENABLE
#define LCR_SBREAK 0x40
#define CFCR_SBREAK LCR_SBREAK
#define LCR_PZERO 0x30
#define CFCR_PZERO LCR_PZERO
#define LCR_PONE 0x20
#define CFCR_PONE LCR_PONE
#define LCR_PEVEN 0x10
#define CFCR_PEVEN LCR_PEVEN
#define LCR_PODD 0x00
#define CFCR_PODD LCR_PODD
#define LCR_PENAB 0x08
#define CFCR_PENAB LCR_PENAB
#define LCR_STOPB 0x04
#define CFCR_STOPB LCR_STOPB
#define LCR_8BITS 0x03
#define CFCR_8BITS LCR_8BITS
#define LCR_7BITS 0x02
#define CFCR_7BITS LCR_7BITS
#define LCR_6BITS 0x01
#define CFCR_6BITS LCR_6BITS
#define LCR_5BITS 0x00
#define CFCR_5BITS LCR_5BITS
#define com_mcr 4 /* modem control register (R/W) */
#define REG_MCR com_mcr
#define MCR_PRESCALE 0x80 /* only available on 16650 up */
#define MCR_LOOPBACK 0x10
#define MCR_IE 0x08
#define MCR_IENABLE MCR_IE
#define MCR_DRS 0x04
#define MCR_RTS 0x02
#define MCR_DTR 0x01
#define MCR_BITS "\20\1DTR\2RTS\3DRS\4IE\5LOOPBACK\10PRESCALE"
#define com_lsr 5 /* line status register (R/W) */
#define REG_LSR com_lsr
#define LSR_RCV_FIFO 0x80
#define LSR_TEMT 0x40
#define LSR_TSRE LSR_TEMT
#define LSR_THRE 0x20
#define LSR_TXRDY LSR_THRE
#define LSR_BI 0x10
#define LSR_FE 0x08
#define LSR_PE 0x04
#define LSR_OE 0x02
#define LSR_RXRDY 0x01
#define LSR_RCV_MASK 0x1f
#define LSR_BITS "\20\1RXRDY\2OE\3PE\4FE\5BI\6THRE\7TEMT\10RCV_FIFO"
#define com_msr 6 /* modem status register (R/W) */
#define REG_MSR com_msr
#define MSR_DCD 0x80
#define MSR_RI 0x40
#define MSR_DSR 0x20
#define MSR_CTS 0x10
#define MSR_DDCD 0x08
#define MSR_TERI 0x04
#define MSR_DDSR 0x02
#define MSR_DCTS 0x01
#define MSR_BITS "\20\1DCTS\2DDSR\3TERI\4DDCD\5CTS\6DSR\7RI\10DCD"
/* 8250 multiplexed registers #[0-1]. Access enabled by LCR[7]. */
#define com_dll 0 /* divisor latch low (R/W) */
#define com_dlbl com_dll
#define com_dlm 1 /* divisor latch high (R/W) */
#define com_dlbh com_dlm
#define REG_DLL com_dll
#define REG_DLH com_dlm
/* 16450 register #7. Not multiplexed. */
#define com_scr 7 /* scratch register (R/W) */
/* 16550 register #2. Not multiplexed. */
#define com_fcr 2 /* FIFO control register (W) */
#define com_fifo com_fcr
#define REG_FCR com_fcr
#define FCR_ENABLE 0x01
#define FIFO_ENABLE FCR_ENABLE
#define FCR_RCV_RST 0x02
#define FIFO_RCV_RST FCR_RCV_RST
#define FCR_XMT_RST 0x04
#define FIFO_XMT_RST FCR_XMT_RST
#define FCR_DMA 0x08
#define FIFO_DMA_MODE FCR_DMA
#define FCR_RX_LOW 0x00
#define FIFO_RX_LOW FCR_RX_LOW
#define FCR_RX_MEDL 0x40
#define FIFO_RX_MEDL FCR_RX_MEDL
#define FCR_RX_MEDH 0x80
#define FIFO_RX_MEDH FCR_RX_MEDH
#define FCR_RX_HIGH 0xc0
#define FIFO_RX_HIGH FCR_RX_HIGH
#define FCR_BITS "\20\1ENABLE\2RCV_RST\3XMT_RST\4DMA"
/* 16650 registers #2,[4-7]. Access enabled by LCR_EFR_ENABLE. */
#define com_efr 2 /* enhanced features register (R/W) */
#define REG_EFR com_efr
#define EFR_CTS 0x80
#define EFR_AUTOCTS EFR_CTS
#define EFR_RTS 0x40
#define EFR_AUTORTS EFR_RTS
#define EFR_EFE 0x10 /* enhanced functions enable */
#define com_xon1 4 /* XON 1 character (R/W) */
#define com_xon2 5 /* XON 2 character (R/W) */
#define com_xoff1 6 /* XOFF 1 character (R/W) */
#define com_xoff2 7 /* XOFF 2 character (R/W) */
#define DW_REG_USR 31 /* DesignWare derived Uart Status Reg */
#define com_usr 39 /* Octeon 16750/16550 Uart Status Reg */
#define REG_USR com_usr
#define USR_BUSY 1 /* Uart Busy. Serial transfer in progress */
#define USR_TXFIFO_NOTFULL 2 /* Uart TX FIFO Not full */
/* 16950 register #1. Access enabled by ACR[7]. Also requires !LCR[7]. */
#define com_asr 1 /* additional status register (R[0-7]/W[0-1]) */
/* 16950 register #3. R/W access enabled by ACR[7]. */
#define com_rfl 3 /* receiver fifo level (R) */
/*
* 16950 register #4. Access enabled by ACR[7]. Also requires
* !LCR_EFR_ENABLE.
*/
#define com_tfl 4 /* transmitter fifo level (R) */
/*
* 16950 register #5. Accessible if !LCR_EFR_ENABLE. Read access also
* requires ACR[6].
*/
#define com_icr 5 /* index control register (R/W) */
/*
* 16950 register #7. It is the same as com_scr except it has a different
* abbreviation in the manufacturer's data sheet and it also serves as an
* index into the Indexed Control register set.
*/
#define com_spr com_scr /* scratch pad (and index) register (R/W) */
#define REG_SPR com_scr
/*
* 16950 indexed control registers #[0-0x13]. Access is via index in SPR,
* data in ICR (if ICR is accessible).
*/
#define com_acr 0 /* additional control register (R/W) */
#define ACR_ASE 0x80 /* ASR/RFL/TFL enable */
#define ACR_ICRE 0x40 /* ICR enable */
#define ACR_TLE 0x20 /* TTL/RTL enable */
#define com_cpr 1 /* clock prescaler register (R/W) */
#define com_tcr 2 /* times clock register (R/W) */
#define com_ttl 4 /* transmitter trigger level (R/W) */
#define com_rtl 5 /* receiver trigger level (R/W) */
/* ... */
/* Hardware extension mode register for RSB-2000/3000. */
#define com_emr com_msr
#define EMR_EXBUFF 0x04
#define EMR_CTSFLW 0x08
#define EMR_DSRFLW 0x10
#define EMR_RTSFLW 0x20
#define EMR_DTRFLW 0x40
#define EMR_EFMODE 0x80

View File

@ -0,0 +1,945 @@
/*-
* Copyright (c) 1997, Stefan Esser <se@freebsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice unmodified, this list of conditions, and the following
* disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $FreeBSD$
*
*/
#pragma once
/*
* PCIM_xxx: mask to locate subfield in register
* PCIR_xxx: config register offset
* PCIC_xxx: device class
* PCIS_xxx: device subclass
* PCIP_xxx: device programming interface
* PCIV_xxx: PCI vendor ID (only required to fixup ancient devices)
* PCID_xxx: device ID
* PCIY_xxx: capability identification number
* PCIZ_xxx: extended capability identification number
*/
/* some PCI bus constants */
#define PCI_DOMAINMAX 65535 /* highest supported domain number */
#define PCI_BUSMAX 255 /* highest supported bus number */
#define PCI_SLOTMAX 31 /* highest supported slot number */
#define PCI_FUNCMAX 7 /* highest supported function number */
#define PCI_REGMAX 255 /* highest supported config register addr. */
#define PCIE_REGMAX 4095 /* highest supported config register addr. */
#define PCI_MAXHDRTYPE 2
#define PCIE_ARI_SLOTMAX 0
#define PCIE_ARI_FUNCMAX 255
#define PCI_RID_BUS_SHIFT 8
#define PCI_RID_SLOT_SHIFT 3
#define PCI_RID_FUNC_SHIFT 0
#define PCI_RID(bus, slot, func) \
((((bus) & PCI_BUSMAX) << PCI_RID_BUS_SHIFT) | \
(((slot) & PCI_SLOTMAX) << PCI_RID_SLOT_SHIFT) | \
(((func) & PCI_FUNCMAX) << PCI_RID_FUNC_SHIFT))
#define PCI_ARI_RID(bus, func) \
((((bus) & PCI_BUSMAX) << PCI_RID_BUS_SHIFT) | \
(((func) & PCIE_ARI_FUNCMAX) << PCI_RID_FUNC_SHIFT))
#define PCI_RID2BUS(rid) (((rid) >> PCI_RID_BUS_SHIFT) & PCI_BUSMAX)
#define PCI_RID2SLOT(rid) (((rid) >> PCI_RID_SLOT_SHIFT) & PCI_SLOTMAX)
#define PCI_RID2FUNC(rid) (((rid) >> PCI_RID_FUNC_SHIFT) & PCI_FUNCMAX)
#define PCIE_ARI_RID2SLOT(rid) (0)
#define PCIE_ARI_RID2FUNC(rid) \
(((rid) >> PCI_RID_FUNC_SHIFT) & PCIE_ARI_FUNCMAX)
#define PCIE_ARI_SLOT(func) (((func) >> PCI_RID_SLOT_SHIFT) & PCI_SLOTMAX)
#define PCIE_ARI_FUNC(func) (((func) >> PCI_RID_FUNC_SHIFT) & PCI_FUNCMAX)
/* PCI config header registers for all devices */
#define PCIR_DEVVENDOR 0x00
#define PCIR_VENDOR 0x00
#define PCIR_DEVICE 0x02
#define PCIR_COMMAND 0x04
#define PCIM_CMD_PORTEN 0x0001
#define PCIM_CMD_MEMEN 0x0002
#define PCIM_CMD_BUSMASTEREN 0x0004
#define PCIM_CMD_SPECIALEN 0x0008
#define PCIM_CMD_MWRICEN 0x0010
#define PCIM_CMD_PERRESPEN 0x0040
#define PCIM_CMD_SERRESPEN 0x0100
#define PCIM_CMD_BACKTOBACK 0x0200
#define PCIM_CMD_INTxDIS 0x0400
#define PCIR_STATUS 0x06
#define PCIM_STATUS_INTxSTATE 0x0008
#define PCIM_STATUS_CAPPRESENT 0x0010
#define PCIM_STATUS_66CAPABLE 0x0020
#define PCIM_STATUS_BACKTOBACK 0x0080
#define PCIM_STATUS_MDPERR 0x0100
#define PCIM_STATUS_SEL_FAST 0x0000
#define PCIM_STATUS_SEL_MEDIMUM 0x0200
#define PCIM_STATUS_SEL_SLOW 0x0400
#define PCIM_STATUS_SEL_MASK 0x0600
#define PCIM_STATUS_STABORT 0x0800
#define PCIM_STATUS_RTABORT 0x1000
#define PCIM_STATUS_RMABORT 0x2000
#define PCIM_STATUS_SERR 0x4000
#define PCIM_STATUS_PERR 0x8000
#define PCIR_REVID 0x08
#define PCIR_PROGIF 0x09
#define PCIR_SUBCLASS 0x0a
#define PCIR_CLASS 0x0b
#define PCIR_CACHELNSZ 0x0c
#define PCIR_LATTIMER 0x0d
#define PCIR_HDRTYPE 0x0e
#define PCIM_HDRTYPE 0x7f
#define PCIM_HDRTYPE_NORMAL 0x00
#define PCIM_HDRTYPE_BRIDGE 0x01
#define PCIM_HDRTYPE_CARDBUS 0x02
#define PCIM_MFDEV 0x80
#define PCIR_BIST 0x0f
/* Capability Register Offsets */
#define PCICAP_ID 0x0
#define PCICAP_NEXTPTR 0x1
/* Capability Identification Numbers */
#define PCIY_PMG 0x01 /* PCI Power Management */
#define PCIY_AGP 0x02 /* AGP */
#define PCIY_VPD 0x03 /* Vital Product Data */
#define PCIY_SLOTID 0x04 /* Slot Identification */
#define PCIY_MSI 0x05 /* Message Signaled Interrupts */
#define PCIY_CHSWP 0x06 /* CompactPCI Hot Swap */
#define PCIY_PCIX 0x07 /* PCI-X */
#define PCIY_HT 0x08 /* HyperTransport */
#define PCIY_VENDOR 0x09 /* Vendor Unique */
#define PCIY_DEBUG 0x0a /* Debug port */
#define PCIY_CRES 0x0b /* CompactPCI central resource control */
#define PCIY_HOTPLUG 0x0c /* PCI Hot-Plug */
#define PCIY_SUBVENDOR 0x0d /* PCI-PCI bridge subvendor ID */
#define PCIY_AGP8X 0x0e /* AGP 8x */
#define PCIY_SECDEV 0x0f /* Secure Device */
#define PCIY_EXPRESS 0x10 /* PCI Express */
#define PCIY_MSIX 0x11 /* MSI-X */
#define PCIY_SATA 0x12 /* SATA */
#define PCIY_PCIAF 0x13 /* PCI Advanced Features */
/* Extended Capability Register Fields */
#define PCIR_EXTCAP 0x100
#define PCIM_EXTCAP_ID 0x0000ffff
#define PCIM_EXTCAP_VER 0x000f0000
#define PCIM_EXTCAP_NEXTPTR 0xfff00000
#define PCI_EXTCAP_ID(ecap) ((ecap) & PCIM_EXTCAP_ID)
#define PCI_EXTCAP_VER(ecap) (((ecap) & PCIM_EXTCAP_VER) >> 16)
#define PCI_EXTCAP_NEXTPTR(ecap) (((ecap) & PCIM_EXTCAP_NEXTPTR) >> 20)
/* Extended Capability Identification Numbers */
#define PCIZ_AER 0x0001 /* Advanced Error Reporting */
#define PCIZ_VC 0x0002 /* Virtual Channel if MFVC Ext Cap not set */
#define PCIZ_SERNUM 0x0003 /* Device Serial Number */
#define PCIZ_PWRBDGT 0x0004 /* Power Budgeting */
#define PCIZ_RCLINK_DCL 0x0005 /* Root Complex Link Declaration */
#define PCIZ_RCLINK_CTL 0x0006 /* Root Complex Internal Link Control */
#define PCIZ_RCEC_ASSOC 0x0007 /* Root Complex Event Collector Association */
#define PCIZ_MFVC 0x0008 /* Multi-Function Virtual Channel */
#define PCIZ_VC2 0x0009 /* Virtual Channel if MFVC Ext Cap set */
#define PCIZ_RCRB 0x000a /* RCRB Header */
#define PCIZ_VENDOR 0x000b /* Vendor Unique */
#define PCIZ_CAC 0x000c /* Configuration Access Correction -- obsolete */
#define PCIZ_ACS 0x000d /* Access Control Services */
#define PCIZ_ARI 0x000e /* Alternative Routing-ID Interpretation */
#define PCIZ_ATS 0x000f /* Address Translation Services */
#define PCIZ_SRIOV 0x0010 /* Single Root IO Virtualization */
#define PCIZ_MRIOV 0x0011 /* Multiple Root IO Virtualization */
#define PCIZ_MULTICAST 0x0012 /* Multicast */
#define PCIZ_PAGE_REQ 0x0013 /* Page Request */
#define PCIZ_AMD 0x0014 /* Reserved for AMD */
#define PCIZ_RESIZE_BAR 0x0015 /* Resizable BAR */
#define PCIZ_DPA 0x0016 /* Dynamic Power Allocation */
#define PCIZ_TPH_REQ 0x0017 /* TPH Requester */
#define PCIZ_LTR 0x0018 /* Latency Tolerance Reporting */
#define PCIZ_SEC_PCIE 0x0019 /* Secondary PCI Express */
#define PCIZ_PMUX 0x001a /* Protocol Multiplexing */
#define PCIZ_PASID 0x001b /* Process Address Space ID */
#define PCIZ_LN_REQ 0x001c /* LN Requester */
#define PCIZ_DPC 0x001d /* Downstream Porto Containment */
#define PCIZ_L1PM 0x001e /* L1 PM Substates */
/* config registers for header type 0 devices */
#define PCIR_BARS 0x10
#define PCIR_BAR(x) (PCIR_BARS + (x) * 4)
#define PCIR_MAX_BAR_0 5
#define PCI_RID2BAR(rid) (((rid) - PCIR_BARS) / 4)
#define PCI_BAR_IO(x) (((x) & PCIM_BAR_SPACE) == PCIM_BAR_IO_SPACE)
#define PCI_BAR_MEM(x) (((x) & PCIM_BAR_SPACE) == PCIM_BAR_MEM_SPACE)
#define PCIM_BAR_SPACE 0x00000001
#define PCIM_BAR_MEM_SPACE 0
#define PCIM_BAR_IO_SPACE 1
#define PCIM_BAR_MEM_TYPE 0x00000006
#define PCIM_BAR_MEM_32 0
#define PCIM_BAR_MEM_1MB 2 /* Locate below 1MB in PCI <= 2.1 */
#define PCIM_BAR_MEM_64 4
#define PCIM_BAR_MEM_PREFETCH 0x00000008
#define PCIM_BAR_MEM_BASE 0xfffffffffffffff0ULL
#define PCIM_BAR_IO_RESERVED 0x00000002
#define PCIM_BAR_IO_BASE 0xfffffffc
#define PCIR_CIS 0x28
#define PCIM_CIS_ASI_MASK 0x00000007
#define PCIM_CIS_ASI_CONFIG 0
#define PCIM_CIS_ASI_BAR0 1
#define PCIM_CIS_ASI_BAR1 2
#define PCIM_CIS_ASI_BAR2 3
#define PCIM_CIS_ASI_BAR3 4
#define PCIM_CIS_ASI_BAR4 5
#define PCIM_CIS_ASI_BAR5 6
#define PCIM_CIS_ASI_ROM 7
#define PCIM_CIS_ADDR_MASK 0x0ffffff8
#define PCIM_CIS_ROM_MASK 0xf0000000
#define PCIM_CIS_CONFIG_MASK 0xff
#define PCIR_SUBVEND_0 0x2c
#define PCIR_SUBDEV_0 0x2e
#define PCIR_BIOS 0x30
#define PCIM_BIOS_ENABLE 0x01
#define PCIM_BIOS_ADDR_MASK 0xfffff800
#define PCIR_CAP_PTR 0x34
#define PCIR_INTLINE 0x3c
#define PCIR_INTPIN 0x3d
#define PCIR_MINGNT 0x3e
#define PCIR_MAXLAT 0x3f
/* config registers for header type 1 (PCI-to-PCI bridge) devices */
#define PCIR_MAX_BAR_1 1
#define PCIR_SECSTAT_1 0x1e
#define PCIR_PRIBUS_1 0x18
#define PCIR_SECBUS_1 0x19
#define PCIR_SUBBUS_1 0x1a
#define PCIR_SECLAT_1 0x1b
#define PCIR_IOBASEL_1 0x1c
#define PCIR_IOLIMITL_1 0x1d
#define PCIR_IOBASEH_1 0x30
#define PCIR_IOLIMITH_1 0x32
#define PCIM_BRIO_16 0x0
#define PCIM_BRIO_32 0x1
#define PCIM_BRIO_MASK 0xf
#define PCIR_MEMBASE_1 0x20
#define PCIR_MEMLIMIT_1 0x22
#define PCIR_PMBASEL_1 0x24
#define PCIR_PMLIMITL_1 0x26
#define PCIR_PMBASEH_1 0x28
#define PCIR_PMLIMITH_1 0x2c
#define PCIM_BRPM_32 0x0
#define PCIM_BRPM_64 0x1
#define PCIM_BRPM_MASK 0xf
#define PCIR_BIOS_1 0x38
#define PCIR_BRIDGECTL_1 0x3e
/* config registers for header type 2 (CardBus) devices */
#define PCIR_MAX_BAR_2 0
#define PCIR_CAP_PTR_2 0x14
#define PCIR_SECSTAT_2 0x16
#define PCIR_PRIBUS_2 0x18
#define PCIR_SECBUS_2 0x19
#define PCIR_SUBBUS_2 0x1a
#define PCIR_SECLAT_2 0x1b
#define PCIR_MEMBASE0_2 0x1c
#define PCIR_MEMLIMIT0_2 0x20
#define PCIR_MEMBASE1_2 0x24
#define PCIR_MEMLIMIT1_2 0x28
#define PCIR_IOBASE0_2 0x2c
#define PCIR_IOLIMIT0_2 0x30
#define PCIR_IOBASE1_2 0x34
#define PCIR_IOLIMIT1_2 0x38
#define PCIR_BRIDGECTL_2 0x3e
#define PCIR_SUBVEND_2 0x40
#define PCIR_SUBDEV_2 0x42
#define PCIR_PCCARDIF_2 0x44
/* PCI device class, subclass and programming interface definitions */
#define PCIC_OLD 0x00
#define PCIS_OLD_NONVGA 0x00
#define PCIS_OLD_VGA 0x01
#define PCIC_STORAGE 0x01
#define PCIS_STORAGE_SCSI 0x00
#define PCIS_STORAGE_IDE 0x01
#define PCIP_STORAGE_IDE_MODEPRIM 0x01
#define PCIP_STORAGE_IDE_PROGINDPRIM 0x02
#define PCIP_STORAGE_IDE_MODESEC 0x04
#define PCIP_STORAGE_IDE_PROGINDSEC 0x08
#define PCIP_STORAGE_IDE_MASTERDEV 0x80
#define PCIS_STORAGE_FLOPPY 0x02
#define PCIS_STORAGE_IPI 0x03
#define PCIS_STORAGE_RAID 0x04
#define PCIS_STORAGE_ATA_ADMA 0x05
#define PCIS_STORAGE_SATA 0x06
#define PCIP_STORAGE_SATA_AHCI_1_0 0x01
#define PCIS_STORAGE_SAS 0x07
#define PCIS_STORAGE_NVM 0x08
#define PCIP_STORAGE_NVM_NVMHCI_1_0 0x01
#define PCIP_STORAGE_NVM_ENTERPRISE_NVMHCI_1_0 0x02
#define PCIS_STORAGE_OTHER 0x80
#define PCIC_NETWORK 0x02
#define PCIS_NETWORK_ETHERNET 0x00
#define PCIS_NETWORK_TOKENRING 0x01
#define PCIS_NETWORK_FDDI 0x02
#define PCIS_NETWORK_ATM 0x03
#define PCIS_NETWORK_ISDN 0x04
#define PCIS_NETWORK_WORLDFIP 0x05
#define PCIS_NETWORK_PICMG 0x06
#define PCIS_NETWORK_OTHER 0x80
#define PCIC_DISPLAY 0x03
#define PCIS_DISPLAY_VGA 0x00
#define PCIS_DISPLAY_XGA 0x01
#define PCIS_DISPLAY_3D 0x02
#define PCIS_DISPLAY_OTHER 0x80
#define PCIC_MULTIMEDIA 0x04
#define PCIS_MULTIMEDIA_VIDEO 0x00
#define PCIS_MULTIMEDIA_AUDIO 0x01
#define PCIS_MULTIMEDIA_TELE 0x02
#define PCIS_MULTIMEDIA_HDA 0x03
#define PCIS_MULTIMEDIA_OTHER 0x80
#define PCIC_MEMORY 0x05
#define PCIS_MEMORY_RAM 0x00
#define PCIS_MEMORY_FLASH 0x01
#define PCIS_MEMORY_OTHER 0x80
#define PCIC_BRIDGE 0x06
#define PCIS_BRIDGE_HOST 0x00
#define PCIS_BRIDGE_ISA 0x01
#define PCIS_BRIDGE_EISA 0x02
#define PCIS_BRIDGE_MCA 0x03
#define PCIS_BRIDGE_PCI 0x04
#define PCIP_BRIDGE_PCI_SUBTRACTIVE 0x01
#define PCIS_BRIDGE_PCMCIA 0x05
#define PCIS_BRIDGE_NUBUS 0x06
#define PCIS_BRIDGE_CARDBUS 0x07
#define PCIS_BRIDGE_RACEWAY 0x08
#define PCIS_BRIDGE_PCI_TRANSPARENT 0x09
#define PCIS_BRIDGE_INFINIBAND 0x0a
#define PCIS_BRIDGE_OTHER 0x80
#define PCIC_SIMPLECOMM 0x07
#define PCIS_SIMPLECOMM_UART 0x00
#define PCIP_SIMPLECOMM_UART_8250 0x00
#define PCIP_SIMPLECOMM_UART_16450A 0x01
#define PCIP_SIMPLECOMM_UART_16550A 0x02
#define PCIP_SIMPLECOMM_UART_16650A 0x03
#define PCIP_SIMPLECOMM_UART_16750A 0x04
#define PCIP_SIMPLECOMM_UART_16850A 0x05
#define PCIP_SIMPLECOMM_UART_16950A 0x06
#define PCIS_SIMPLECOMM_PAR 0x01
#define PCIS_SIMPLECOMM_MULSER 0x02
#define PCIS_SIMPLECOMM_MODEM 0x03
#define PCIS_SIMPLECOMM_GPIB 0x04
#define PCIS_SIMPLECOMM_SMART_CARD 0x05
#define PCIS_SIMPLECOMM_OTHER 0x80
#define PCIC_BASEPERIPH 0x08
#define PCIS_BASEPERIPH_PIC 0x00
#define PCIP_BASEPERIPH_PIC_8259A 0x00
#define PCIP_BASEPERIPH_PIC_ISA 0x01
#define PCIP_BASEPERIPH_PIC_EISA 0x02
#define PCIP_BASEPERIPH_PIC_IO_APIC 0x10
#define PCIP_BASEPERIPH_PIC_IOX_APIC 0x20
#define PCIS_BASEPERIPH_DMA 0x01
#define PCIS_BASEPERIPH_TIMER 0x02
#define PCIS_BASEPERIPH_RTC 0x03
#define PCIS_BASEPERIPH_PCIHOT 0x04
#define PCIS_BASEPERIPH_SDHC 0x05
#define PCIS_BASEPERIPH_IOMMU 0x06
#define PCIS_BASEPERIPH_OTHER 0x80
#define PCIC_INPUTDEV 0x09
#define PCIS_INPUTDEV_KEYBOARD 0x00
#define PCIS_INPUTDEV_DIGITIZER 0x01
#define PCIS_INPUTDEV_MOUSE 0x02
#define PCIS_INPUTDEV_SCANNER 0x03
#define PCIS_INPUTDEV_GAMEPORT 0x04
#define PCIS_INPUTDEV_OTHER 0x80
#define PCIC_DOCKING 0x0a
#define PCIS_DOCKING_GENERIC 0x00
#define PCIS_DOCKING_OTHER 0x80
#define PCIC_PROCESSOR 0x0b
#define PCIS_PROCESSOR_386 0x00
#define PCIS_PROCESSOR_486 0x01
#define PCIS_PROCESSOR_PENTIUM 0x02
#define PCIS_PROCESSOR_ALPHA 0x10
#define PCIS_PROCESSOR_POWERPC 0x20
#define PCIS_PROCESSOR_MIPS 0x30
#define PCIS_PROCESSOR_COPROC 0x40
#define PCIC_SERIALBUS 0x0c
#define PCIS_SERIALBUS_FW 0x00
#define PCIS_SERIALBUS_ACCESS 0x01
#define PCIS_SERIALBUS_SSA 0x02
#define PCIS_SERIALBUS_USB 0x03
#define PCIP_SERIALBUS_USB_UHCI 0x00
#define PCIP_SERIALBUS_USB_OHCI 0x10
#define PCIP_SERIALBUS_USB_EHCI 0x20
#define PCIP_SERIALBUS_USB_XHCI 0x30
#define PCIP_SERIALBUS_USB_DEVICE 0xfe
#define PCIS_SERIALBUS_FC 0x04
#define PCIS_SERIALBUS_SMBUS 0x05
#define PCIS_SERIALBUS_INFINIBAND 0x06
#define PCIS_SERIALBUS_IPMI 0x07
#define PCIP_SERIALBUS_IPMI_SMIC 0x00
#define PCIP_SERIALBUS_IPMI_KCS 0x01
#define PCIP_SERIALBUS_IPMI_BT 0x02
#define PCIS_SERIALBUS_SERCOS 0x08
#define PCIS_SERIALBUS_CANBUS 0x09
#define PCIC_WIRELESS 0x0d
#define PCIS_WIRELESS_IRDA 0x00
#define PCIS_WIRELESS_IR 0x01
#define PCIS_WIRELESS_RF 0x10
#define PCIS_WIRELESS_BLUETOOTH 0x11
#define PCIS_WIRELESS_BROADBAND 0x12
#define PCIS_WIRELESS_80211A 0x20
#define PCIS_WIRELESS_80211B 0x21
#define PCIS_WIRELESS_OTHER 0x80
#define PCIC_INTELLIIO 0x0e
#define PCIS_INTELLIIO_I2O 0x00
#define PCIC_SATCOM 0x0f
#define PCIS_SATCOM_TV 0x01
#define PCIS_SATCOM_AUDIO 0x02
#define PCIS_SATCOM_VOICE 0x03
#define PCIS_SATCOM_DATA 0x04
#define PCIC_CRYPTO 0x10
#define PCIS_CRYPTO_NETCOMP 0x00
#define PCIS_CRYPTO_ENTERTAIN 0x10
#define PCIS_CRYPTO_OTHER 0x80
#define PCIC_DASP 0x11
#define PCIS_DASP_DPIO 0x00
#define PCIS_DASP_PERFCNTRS 0x01
#define PCIS_DASP_COMM_SYNC 0x10
#define PCIS_DASP_MGMT_CARD 0x20
#define PCIS_DASP_OTHER 0x80
#define PCIC_OTHER 0xff
/* Bridge Control Values. */
#define PCIB_BCR_PERR_ENABLE 0x0001
#define PCIB_BCR_SERR_ENABLE 0x0002
#define PCIB_BCR_ISA_ENABLE 0x0004
#define PCIB_BCR_VGA_ENABLE 0x0008
#define PCIB_BCR_MASTER_ABORT_MODE 0x0020
#define PCIB_BCR_SECBUS_RESET 0x0040
#define PCIB_BCR_SECBUS_BACKTOBACK 0x0080
#define PCIB_BCR_PRI_DISCARD_TIMEOUT 0x0100
#define PCIB_BCR_SEC_DISCARD_TIMEOUT 0x0200
#define PCIB_BCR_DISCARD_TIMER_STATUS 0x0400
#define PCIB_BCR_DISCARD_TIMER_SERREN 0x0800
/* PCI power manangement */
#define PCIR_POWER_CAP 0x2
#define PCIM_PCAP_SPEC 0x0007
#define PCIM_PCAP_PMEREQCLK 0x0008
#define PCIM_PCAP_DEVSPECINIT 0x0020
#define PCIM_PCAP_AUXPWR_0 0x0000
#define PCIM_PCAP_AUXPWR_55 0x0040
#define PCIM_PCAP_AUXPWR_100 0x0080
#define PCIM_PCAP_AUXPWR_160 0x00c0
#define PCIM_PCAP_AUXPWR_220 0x0100
#define PCIM_PCAP_AUXPWR_270 0x0140
#define PCIM_PCAP_AUXPWR_320 0x0180
#define PCIM_PCAP_AUXPWR_375 0x01c0
#define PCIM_PCAP_AUXPWRMASK 0x01c0
#define PCIM_PCAP_D1SUPP 0x0200
#define PCIM_PCAP_D2SUPP 0x0400
#define PCIM_PCAP_D0PME 0x0800
#define PCIM_PCAP_D1PME 0x1000
#define PCIM_PCAP_D2PME 0x2000
#define PCIM_PCAP_D3PME_HOT 0x4000
#define PCIM_PCAP_D3PME_COLD 0x8000
#define PCIR_POWER_STATUS 0x4
#define PCIM_PSTAT_D0 0x0000
#define PCIM_PSTAT_D1 0x0001
#define PCIM_PSTAT_D2 0x0002
#define PCIM_PSTAT_D3 0x0003
#define PCIM_PSTAT_DMASK 0x0003
#define PCIM_PSTAT_NOSOFTRESET 0x0008
#define PCIM_PSTAT_PMEENABLE 0x0100
#define PCIM_PSTAT_D0POWER 0x0000
#define PCIM_PSTAT_D1POWER 0x0200
#define PCIM_PSTAT_D2POWER 0x0400
#define PCIM_PSTAT_D3POWER 0x0600
#define PCIM_PSTAT_D0HEAT 0x0800
#define PCIM_PSTAT_D1HEAT 0x0a00
#define PCIM_PSTAT_D2HEAT 0x0c00
#define PCIM_PSTAT_D3HEAT 0x0e00
#define PCIM_PSTAT_DATASELMASK 0x1e00
#define PCIM_PSTAT_DATAUNKN 0x0000
#define PCIM_PSTAT_DATADIV10 0x2000
#define PCIM_PSTAT_DATADIV100 0x4000
#define PCIM_PSTAT_DATADIV1000 0x6000
#define PCIM_PSTAT_DATADIVMASK 0x6000
#define PCIM_PSTAT_PME 0x8000
#define PCIR_POWER_BSE 0x6
#define PCIM_PMCSR_BSE_D3B3 0x00
#define PCIM_PMCSR_BSE_D3B2 0x40
#define PCIM_PMCSR_BSE_BPCCE 0x80
#define PCIR_POWER_DATA 0x7
/* VPD capability registers */
#define PCIR_VPD_ADDR 0x2
#define PCIR_VPD_DATA 0x4
/* PCI Message Signalled Interrupts (MSI) */
#define PCIR_MSI_CTRL 0x2
#define PCIM_MSICTRL_VECTOR 0x0100
#define PCIM_MSICTRL_64BIT 0x0080
#define PCIM_MSICTRL_MME_MASK 0x0070
#define PCIM_MSICTRL_MME_1 0x0000
#define PCIM_MSICTRL_MME_2 0x0010
#define PCIM_MSICTRL_MME_4 0x0020
#define PCIM_MSICTRL_MME_8 0x0030
#define PCIM_MSICTRL_MME_16 0x0040
#define PCIM_MSICTRL_MME_32 0x0050
#define PCIM_MSICTRL_MMC_MASK 0x000E
#define PCIM_MSICTRL_MMC_1 0x0000
#define PCIM_MSICTRL_MMC_2 0x0002
#define PCIM_MSICTRL_MMC_4 0x0004
#define PCIM_MSICTRL_MMC_8 0x0006
#define PCIM_MSICTRL_MMC_16 0x0008
#define PCIM_MSICTRL_MMC_32 0x000A
#define PCIM_MSICTRL_MSI_ENABLE 0x0001
#define PCIR_MSI_ADDR 0x4
#define PCIR_MSI_ADDR_HIGH 0x8
#define PCIR_MSI_DATA 0x8
#define PCIR_MSI_DATA_64BIT 0xc
#define PCIR_MSI_MASK 0x10
#define PCIR_MSI_PENDING 0x14
/* PCI-X definitions */
/* For header type 0 devices */
#define PCIXR_COMMAND 0x2
#define PCIXM_COMMAND_DPERR_E 0x0001 /* Data Parity Error Recovery */
#define PCIXM_COMMAND_ERO 0x0002 /* Enable Relaxed Ordering */
#define PCIXM_COMMAND_MAX_READ 0x000c /* Maximum Burst Read Count */
#define PCIXM_COMMAND_MAX_READ_512 0x0000
#define PCIXM_COMMAND_MAX_READ_1024 0x0004
#define PCIXM_COMMAND_MAX_READ_2048 0x0008
#define PCIXM_COMMAND_MAX_READ_4096 0x000c
#define PCIXM_COMMAND_MAX_SPLITS 0x0070 /* Maximum Split Transactions */
#define PCIXM_COMMAND_MAX_SPLITS_1 0x0000
#define PCIXM_COMMAND_MAX_SPLITS_2 0x0010
#define PCIXM_COMMAND_MAX_SPLITS_3 0x0020
#define PCIXM_COMMAND_MAX_SPLITS_4 0x0030
#define PCIXM_COMMAND_MAX_SPLITS_8 0x0040
#define PCIXM_COMMAND_MAX_SPLITS_12 0x0050
#define PCIXM_COMMAND_MAX_SPLITS_16 0x0060
#define PCIXM_COMMAND_MAX_SPLITS_32 0x0070
#define PCIXM_COMMAND_VERSION 0x3000
#define PCIXR_STATUS 0x4
#define PCIXM_STATUS_DEVFN 0x000000FF
#define PCIXM_STATUS_BUS 0x0000FF00
#define PCIXM_STATUS_64BIT 0x00010000
#define PCIXM_STATUS_133CAP 0x00020000
#define PCIXM_STATUS_SC_DISCARDED 0x00040000
#define PCIXM_STATUS_UNEXP_SC 0x00080000
#define PCIXM_STATUS_COMPLEX_DEV 0x00100000
#define PCIXM_STATUS_MAX_READ 0x00600000
#define PCIXM_STATUS_MAX_READ_512 0x00000000
#define PCIXM_STATUS_MAX_READ_1024 0x00200000
#define PCIXM_STATUS_MAX_READ_2048 0x00400000
#define PCIXM_STATUS_MAX_READ_4096 0x00600000
#define PCIXM_STATUS_MAX_SPLITS 0x03800000
#define PCIXM_STATUS_MAX_SPLITS_1 0x00000000
#define PCIXM_STATUS_MAX_SPLITS_2 0x00800000
#define PCIXM_STATUS_MAX_SPLITS_3 0x01000000
#define PCIXM_STATUS_MAX_SPLITS_4 0x01800000
#define PCIXM_STATUS_MAX_SPLITS_8 0x02000000
#define PCIXM_STATUS_MAX_SPLITS_12 0x02800000
#define PCIXM_STATUS_MAX_SPLITS_16 0x03000000
#define PCIXM_STATUS_MAX_SPLITS_32 0x03800000
#define PCIXM_STATUS_MAX_CUM_READ 0x1C000000
#define PCIXM_STATUS_RCVD_SC_ERR 0x20000000
#define PCIXM_STATUS_266CAP 0x40000000
#define PCIXM_STATUS_533CAP 0x80000000
/* For header type 1 devices (PCI-X bridges) */
#define PCIXR_SEC_STATUS 0x2
#define PCIXM_SEC_STATUS_64BIT 0x0001
#define PCIXM_SEC_STATUS_133CAP 0x0002
#define PCIXM_SEC_STATUS_SC_DISC 0x0004
#define PCIXM_SEC_STATUS_UNEXP_SC 0x0008
#define PCIXM_SEC_STATUS_SC_OVERRUN 0x0010
#define PCIXM_SEC_STATUS_SR_DELAYED 0x0020
#define PCIXM_SEC_STATUS_BUS_MODE 0x03c0
#define PCIXM_SEC_STATUS_VERSION 0x3000
#define PCIXM_SEC_STATUS_266CAP 0x4000
#define PCIXM_SEC_STATUS_533CAP 0x8000
#define PCIXR_BRIDGE_STATUS 0x4
#define PCIXM_BRIDGE_STATUS_DEVFN 0x000000FF
#define PCIXM_BRIDGE_STATUS_BUS 0x0000FF00
#define PCIXM_BRIDGE_STATUS_64BIT 0x00010000
#define PCIXM_BRIDGE_STATUS_133CAP 0x00020000
#define PCIXM_BRIDGE_STATUS_SC_DISCARDED 0x00040000
#define PCIXM_BRIDGE_STATUS_UNEXP_SC 0x00080000
#define PCIXM_BRIDGE_STATUS_SC_OVERRUN 0x00100000
#define PCIXM_BRIDGE_STATUS_SR_DELAYED 0x00200000
#define PCIXM_BRIDGE_STATUS_DEVID_MSGCAP 0x20000000
#define PCIXM_BRIDGE_STATUS_266CAP 0x40000000
#define PCIXM_BRIDGE_STATUS_533CAP 0x80000000
/* HT (HyperTransport) Capability definitions */
#define PCIR_HT_COMMAND 0x2
#define PCIM_HTCMD_CAP_MASK 0xf800 /* Capability type. */
#define PCIM_HTCAP_SLAVE 0x0000 /* 000xx */
#define PCIM_HTCAP_HOST 0x2000 /* 001xx */
#define PCIM_HTCAP_SWITCH 0x4000 /* 01000 */
#define PCIM_HTCAP_INTERRUPT 0x8000 /* 10000 */
#define PCIM_HTCAP_REVISION_ID 0x8800 /* 10001 */
#define PCIM_HTCAP_UNITID_CLUMPING 0x9000 /* 10010 */
#define PCIM_HTCAP_EXT_CONFIG_SPACE 0x9800 /* 10011 */
#define PCIM_HTCAP_ADDRESS_MAPPING 0xa000 /* 10100 */
#define PCIM_HTCAP_MSI_MAPPING 0xa800 /* 10101 */
#define PCIM_HTCAP_DIRECT_ROUTE 0xb000 /* 10110 */
#define PCIM_HTCAP_VCSET 0xb800 /* 10111 */
#define PCIM_HTCAP_RETRY_MODE 0xc000 /* 11000 */
#define PCIM_HTCAP_X86_ENCODING 0xc800 /* 11001 */
#define PCIM_HTCAP_GEN3 0xd000 /* 11010 */
#define PCIM_HTCAP_FLE 0xd800 /* 11011 */
#define PCIM_HTCAP_PM 0xe000 /* 11100 */
#define PCIM_HTCAP_HIGH_NODE_COUNT 0xe800 /* 11101 */
/* HT MSI Mapping Capability definitions. */
#define PCIM_HTCMD_MSI_ENABLE 0x0001
#define PCIM_HTCMD_MSI_FIXED 0x0002
#define PCIR_HTMSI_ADDRESS_LO 0x4
#define PCIR_HTMSI_ADDRESS_HI 0x8
/* PCI Vendor capability definitions */
#define PCIR_VENDOR_LENGTH 0x2
#define PCIR_VENDOR_DATA 0x3
/* PCI EHCI Debug Port definitions */
#define PCIR_DEBUG_PORT 0x2
#define PCIM_DEBUG_PORT_OFFSET 0x1FFF
#define PCIM_DEBUG_PORT_BAR 0xe000
/* PCI-PCI Bridge Subvendor definitions */
#define PCIR_SUBVENDCAP_ID 0x4
/* PCI Express definitions */
#define PCIER_FLAGS 0x2
#define PCIEM_FLAGS_VERSION 0x000F
#define PCIEM_FLAGS_TYPE 0x00F0
#define PCIEM_TYPE_ENDPOINT 0x0000
#define PCIEM_TYPE_LEGACY_ENDPOINT 0x0010
#define PCIEM_TYPE_ROOT_PORT 0x0040
#define PCIEM_TYPE_UPSTREAM_PORT 0x0050
#define PCIEM_TYPE_DOWNSTREAM_PORT 0x0060
#define PCIEM_TYPE_PCI_BRIDGE 0x0070
#define PCIEM_TYPE_PCIE_BRIDGE 0x0080
#define PCIEM_TYPE_ROOT_INT_EP 0x0090
#define PCIEM_TYPE_ROOT_EC 0x00a0
#define PCIEM_FLAGS_SLOT 0x0100
#define PCIEM_FLAGS_IRQ 0x3e00
#define PCIER_DEVICE_CAP 0x4
#define PCIEM_CAP_MAX_PAYLOAD 0x00000007
#define PCIEM_CAP_PHANTHOM_FUNCS 0x00000018
#define PCIEM_CAP_EXT_TAG_FIELD 0x00000020
#define PCIEM_CAP_L0S_LATENCY 0x000001c0
#define PCIEM_CAP_L1_LATENCY 0x00000e00
#define PCIEM_CAP_ROLE_ERR_RPT 0x00008000
#define PCIEM_CAP_SLOT_PWR_LIM_VAL 0x03fc0000
#define PCIEM_CAP_SLOT_PWR_LIM_SCALE 0x0c000000
#define PCIEM_CAP_FLR 0x10000000
#define PCIER_DEVICE_CTL 0x8
#define PCIEM_CTL_COR_ENABLE 0x0001
#define PCIEM_CTL_NFER_ENABLE 0x0002
#define PCIEM_CTL_FER_ENABLE 0x0004
#define PCIEM_CTL_URR_ENABLE 0x0008
#define PCIEM_CTL_RELAXED_ORD_ENABLE 0x0010
#define PCIEM_CTL_MAX_PAYLOAD 0x00e0
#define PCIEM_CTL_EXT_TAG_FIELD 0x0100
#define PCIEM_CTL_PHANTHOM_FUNCS 0x0200
#define PCIEM_CTL_AUX_POWER_PM 0x0400
#define PCIEM_CTL_NOSNOOP_ENABLE 0x0800
#define PCIEM_CTL_MAX_READ_REQUEST 0x7000
#define PCIEM_CTL_BRDG_CFG_RETRY 0x8000 /* PCI-E - PCI/PCI-X bridges */
#define PCIEM_CTL_INITIATE_FLR 0x8000 /* FLR capable endpoints */
#define PCIER_DEVICE_STA 0xa
#define PCIEM_STA_CORRECTABLE_ERROR 0x0001
#define PCIEM_STA_NON_FATAL_ERROR 0x0002
#define PCIEM_STA_FATAL_ERROR 0x0004
#define PCIEM_STA_UNSUPPORTED_REQ 0x0008
#define PCIEM_STA_AUX_POWER 0x0010
#define PCIEM_STA_TRANSACTION_PND 0x0020
#define PCIER_LINK_CAP 0xc
#define PCIEM_LINK_CAP_MAX_SPEED 0x0000000f
#define PCIEM_LINK_CAP_MAX_WIDTH 0x000003f0
#define PCIEM_LINK_CAP_ASPM 0x00000c00
#define PCIEM_LINK_CAP_L0S_EXIT 0x00007000
#define PCIEM_LINK_CAP_L1_EXIT 0x00038000
#define PCIEM_LINK_CAP_CLOCK_PM 0x00040000
#define PCIEM_LINK_CAP_SURPRISE_DOWN 0x00080000
#define PCIEM_LINK_CAP_DL_ACTIVE 0x00100000
#define PCIEM_LINK_CAP_LINK_BW_NOTIFY 0x00200000
#define PCIEM_LINK_CAP_ASPM_COMPLIANCE 0x00400000
#define PCIEM_LINK_CAP_PORT 0xff000000
#define PCIER_LINK_CTL 0x10
#define PCIEM_LINK_CTL_ASPMC_DIS 0x0000
#define PCIEM_LINK_CTL_ASPMC_L0S 0x0001
#define PCIEM_LINK_CTL_ASPMC_L1 0x0002
#define PCIEM_LINK_CTL_ASPMC 0x0003
#define PCIEM_LINK_CTL_RCB 0x0008
#define PCIEM_LINK_CTL_LINK_DIS 0x0010
#define PCIEM_LINK_CTL_RETRAIN_LINK 0x0020
#define PCIEM_LINK_CTL_COMMON_CLOCK 0x0040
#define PCIEM_LINK_CTL_EXTENDED_SYNC 0x0080
#define PCIEM_LINK_CTL_ECPM 0x0100
#define PCIEM_LINK_CTL_HAWD 0x0200
#define PCIEM_LINK_CTL_LBMIE 0x0400
#define PCIEM_LINK_CTL_LABIE 0x0800
#define PCIER_LINK_STA 0x12
#define PCIEM_LINK_STA_SPEED 0x000f
#define PCIEM_LINK_STA_WIDTH 0x03f0
#define PCIEM_LINK_STA_TRAINING_ERROR 0x0400
#define PCIEM_LINK_STA_TRAINING 0x0800
#define PCIEM_LINK_STA_SLOT_CLOCK 0x1000
#define PCIEM_LINK_STA_DL_ACTIVE 0x2000
#define PCIEM_LINK_STA_LINK_BW_MGMT 0x4000
#define PCIEM_LINK_STA_LINK_AUTO_BW 0x8000
#define PCIER_SLOT_CAP 0x14
#define PCIEM_SLOT_CAP_APB 0x00000001
#define PCIEM_SLOT_CAP_PCP 0x00000002
#define PCIEM_SLOT_CAP_MRLSP 0x00000004
#define PCIEM_SLOT_CAP_AIP 0x00000008
#define PCIEM_SLOT_CAP_PIP 0x00000010
#define PCIEM_SLOT_CAP_HPS 0x00000020
#define PCIEM_SLOT_CAP_HPC 0x00000040
#define PCIEM_SLOT_CAP_SPLV 0x00007f80
#define PCIEM_SLOT_CAP_SPLS 0x00018000
#define PCIEM_SLOT_CAP_EIP 0x00020000
#define PCIEM_SLOT_CAP_NCCS 0x00040000
#define PCIEM_SLOT_CAP_PSN 0xfff80000
#define PCIER_SLOT_CTL 0x18
#define PCIEM_SLOT_CTL_ABPE 0x0001
#define PCIEM_SLOT_CTL_PFDE 0x0002
#define PCIEM_SLOT_CTL_MRLSCE 0x0004
#define PCIEM_SLOT_CTL_PDCE 0x0008
#define PCIEM_SLOT_CTL_CCIE 0x0010
#define PCIEM_SLOT_CTL_HPIE 0x0020
#define PCIEM_SLOT_CTL_AIC 0x00c0
#define PCIEM_SLOT_CTL_PIC 0x0300
#define PCIEM_SLOT_CTL_PCC 0x0400
#define PCIEM_SLOT_CTL_EIC 0x0800
#define PCIEM_SLOT_CTL_DLLSCE 0x1000
#define PCIER_SLOT_STA 0x1a
#define PCIEM_SLOT_STA_ABP 0x0001
#define PCIEM_SLOT_STA_PFD 0x0002
#define PCIEM_SLOT_STA_MRLSC 0x0004
#define PCIEM_SLOT_STA_PDC 0x0008
#define PCIEM_SLOT_STA_CC 0x0010
#define PCIEM_SLOT_STA_MRLSS 0x0020
#define PCIEM_SLOT_STA_PDS 0x0040
#define PCIEM_SLOT_STA_EIS 0x0080
#define PCIEM_SLOT_STA_DLLSC 0x0100
#define PCIER_ROOT_CTL 0x1c
#define PCIEM_ROOT_CTL_SERR_CORR 0x0001
#define PCIEM_ROOT_CTL_SERR_NONFATAL 0x0002
#define PCIEM_ROOT_CTL_SERR_FATAL 0x0004
#define PCIEM_ROOT_CTL_PME 0x0008
#define PCIEM_ROOT_CTL_CRS_VIS 0x0010
#define PCIER_ROOT_CAP 0x1e
#define PCIEM_ROOT_CAP_CRS_VIS 0x0001
#define PCIER_ROOT_STA 0x20
#define PCIEM_ROOT_STA_PME_REQID_MASK 0x0000ffff
#define PCIEM_ROOT_STA_PME_STATUS 0x00010000
#define PCIEM_ROOT_STA_PME_PEND 0x00020000
#define PCIER_DEVICE_CAP2 0x24
#define PCIEM_CAP2_ARI 0x20
#define PCIER_DEVICE_CTL2 0x28
#define PCIEM_CTL2_COMP_TIMEOUT_VAL 0x000f
#define PCIEM_CTL2_COMP_TIMEOUT_DIS 0x0010
#define PCIEM_CTL2_ARI 0x0020
#define PCIEM_CTL2_ATOMIC_REQ_ENABLE 0x0040
#define PCIEM_CTL2_ATOMIC_EGR_BLOCK 0x0080
#define PCIEM_CTL2_ID_ORDERED_REQ_EN 0x0100
#define PCIEM_CTL2_ID_ORDERED_CMP_EN 0x0200
#define PCIEM_CTL2_LTR_ENABLE 0x0400
#define PCIEM_CTL2_OBFF 0x6000
#define PCIEM_OBFF_DISABLE 0x0000
#define PCIEM_OBFF_MSGA_ENABLE 0x2000
#define PCIEM_OBFF_MSGB_ENABLE 0x4000
#define PCIEM_OBFF_WAKE_ENABLE 0x6000
#define PCIEM_CTL2_END2END_TLP 0x8000
#define PCIER_DEVICE_STA2 0x2a
#define PCIER_LINK_CAP2 0x2c
#define PCIER_LINK_CTL2 0x30
#define PCIER_LINK_STA2 0x32
#define PCIER_SLOT_CAP2 0x34
#define PCIER_SLOT_CTL2 0x38
#define PCIER_SLOT_STA2 0x3a
/* MSI-X definitions */
#define PCIR_MSIX_CTRL 0x2
#define PCIM_MSIXCTRL_MSIX_ENABLE 0x8000
#define PCIM_MSIXCTRL_FUNCTION_MASK 0x4000
#define PCIM_MSIXCTRL_TABLE_SIZE 0x07FF
#define PCIR_MSIX_TABLE 0x4
#define PCIR_MSIX_PBA 0x8
#define PCIM_MSIX_BIR_MASK 0x7
#define PCIM_MSIX_BIR_BAR_10 0
#define PCIM_MSIX_BIR_BAR_14 1
#define PCIM_MSIX_BIR_BAR_18 2
#define PCIM_MSIX_BIR_BAR_1C 3
#define PCIM_MSIX_BIR_BAR_20 4
#define PCIM_MSIX_BIR_BAR_24 5
#define PCIM_MSIX_VCTRL_MASK 0x1
/* PCI Advanced Features definitions */
#define PCIR_PCIAF_CAP 0x3
#define PCIM_PCIAFCAP_TP 0x01
#define PCIM_PCIAFCAP_FLR 0x02
#define PCIR_PCIAF_CTRL 0x4
#define PCIR_PCIAFCTRL_FLR 0x01
#define PCIR_PCIAF_STATUS 0x5
#define PCIR_PCIAFSTATUS_TP 0x01
/* Advanced Error Reporting */
#define PCIR_AER_UC_STATUS 0x04
#define PCIM_AER_UC_TRAINING_ERROR 0x00000001
#define PCIM_AER_UC_DL_PROTOCOL_ERROR 0x00000010
#define PCIM_AER_UC_SURPRISE_LINK_DOWN 0x00000020
#define PCIM_AER_UC_POISONED_TLP 0x00001000
#define PCIM_AER_UC_FC_PROTOCOL_ERROR 0x00002000
#define PCIM_AER_UC_COMPLETION_TIMEOUT 0x00004000
#define PCIM_AER_UC_COMPLETER_ABORT 0x00008000
#define PCIM_AER_UC_UNEXPECTED_COMPLETION 0x00010000
#define PCIM_AER_UC_RECEIVER_OVERFLOW 0x00020000
#define PCIM_AER_UC_MALFORMED_TLP 0x00040000
#define PCIM_AER_UC_ECRC_ERROR 0x00080000
#define PCIM_AER_UC_UNSUPPORTED_REQUEST 0x00100000
#define PCIM_AER_UC_ACS_VIOLATION 0x00200000
#define PCIM_AER_UC_INTERNAL_ERROR 0x00400000
#define PCIM_AER_UC_MC_BLOCKED_TLP 0x00800000
#define PCIM_AER_UC_ATOMIC_EGRESS_BLK 0x01000000
#define PCIM_AER_UC_TLP_PREFIX_BLOCKED 0x02000000
#define PCIR_AER_UC_MASK 0x08 /* Shares bits with UC_STATUS */
#define PCIR_AER_UC_SEVERITY 0x0c /* Shares bits with UC_STATUS */
#define PCIR_AER_COR_STATUS 0x10
#define PCIM_AER_COR_RECEIVER_ERROR 0x00000001
#define PCIM_AER_COR_BAD_TLP 0x00000040
#define PCIM_AER_COR_BAD_DLLP 0x00000080
#define PCIM_AER_COR_REPLAY_ROLLOVER 0x00000100
#define PCIM_AER_COR_REPLAY_TIMEOUT 0x00001000
#define PCIM_AER_COR_ADVISORY_NF_ERROR 0x00002000
#define PCIM_AER_COR_INTERNAL_ERROR 0x00004000
#define PCIM_AER_COR_HEADER_LOG_OVFLOW 0x00008000
#define PCIR_AER_COR_MASK 0x14 /* Shares bits with COR_STATUS */
#define PCIR_AER_CAP_CONTROL 0x18
#define PCIM_AER_FIRST_ERROR_PTR 0x0000001f
#define PCIM_AER_ECRC_GEN_CAPABLE 0x00000020
#define PCIM_AER_ECRC_GEN_ENABLE 0x00000040
#define PCIM_AER_ECRC_CHECK_CAPABLE 0x00000080
#define PCIM_AER_ECRC_CHECK_ENABLE 0x00000100
#define PCIM_AER_MULT_HDR_CAPABLE 0x00000200
#define PCIM_AER_MULT_HDR_ENABLE 0x00000400
#define PCIM_AER_TLP_PREFIX_LOG_PRESENT 0x00000800
#define PCIR_AER_HEADER_LOG 0x1c
#define PCIR_AER_ROOTERR_CMD 0x2c /* Only for root complex ports */
#define PCIM_AER_ROOTERR_COR_ENABLE 0x00000001
#define PCIM_AER_ROOTERR_NF_ENABLE 0x00000002
#define PCIM_AER_ROOTERR_F_ENABLE 0x00000004
#define PCIR_AER_ROOTERR_STATUS 0x30 /* Only for root complex ports */
#define PCIM_AER_ROOTERR_COR_ERR 0x00000001
#define PCIM_AER_ROOTERR_MULTI_COR_ERR 0x00000002
#define PCIM_AER_ROOTERR_UC_ERR 0x00000004
#define PCIM_AER_ROOTERR_MULTI_UC_ERR 0x00000008
#define PCIM_AER_ROOTERR_FIRST_UC_FATAL 0x00000010
#define PCIM_AER_ROOTERR_NF_ERR 0x00000020
#define PCIM_AER_ROOTERR_F_ERR 0x00000040
#define PCIM_AER_ROOTERR_INT_MESSAGE 0xf8000000
#define PCIR_AER_COR_SOURCE_ID 0x34 /* Only for root complex ports */
#define PCIR_AER_ERR_SOURCE_ID 0x36 /* Only for root complex ports */
#define PCIR_AER_TLP_PREFIX_LOG 0x38 /* Only for TLP prefix functions */
/* Virtual Channel definitions */
#define PCIR_VC_CAP1 0x04
#define PCIM_VC_CAP1_EXT_COUNT 0x00000007
#define PCIM_VC_CAP1_LOWPRI_EXT_COUNT 0x00000070
#define PCIR_VC_CAP2 0x08
#define PCIR_VC_CONTROL 0x0C
#define PCIR_VC_STATUS 0x0E
#define PCIR_VC_RESOURCE_CAP(n) (0x10 + (n) * 0x0C)
#define PCIR_VC_RESOURCE_CTL(n) (0x14 + (n) * 0x0C)
#define PCIR_VC_RESOURCE_STA(n) (0x18 + (n) * 0x0C)
/* Serial Number definitions */
#define PCIR_SERIAL_LOW 0x04
#define PCIR_SERIAL_HIGH 0x08
/* SR-IOV definitions */
#define PCIR_SRIOV_CTL 0x08
#define PCIM_SRIOV_VF_EN 0x01
#define PCIM_SRIOV_VF_MSE 0x08 /* Memory space enable. */
#define PCIM_SRIOV_ARI_EN 0x10
#define PCIR_SRIOV_TOTAL_VFS 0x0E
#define PCIR_SRIOV_NUM_VFS 0x10
#define PCIR_SRIOV_VF_OFF 0x14
#define PCIR_SRIOV_VF_STRIDE 0x16
#define PCIR_SRIOV_VF_DID 0x1A
#define PCIR_SRIOV_PAGE_CAP 0x1C
#define PCIR_SRIOV_PAGE_SIZE 0x20
#define PCI_SRIOV_BASE_PAGE_SHIFT 12
#define PCIR_SRIOV_BARS 0x24
#define PCIR_SRIOV_BAR(x) (PCIR_SRIOV_BARS + (x) * 4)

View File

@ -0,0 +1,89 @@
/*-
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* from: @(#)psl.h 5.2 (Berkeley) 1/18/91
* $FreeBSD$
*/
#pragma once
/*
* 386 processor status longword.
*/
#define PSL_C 0x00000001 /* carry bit */
#define PSL_PF 0x00000004 /* parity bit */
#define PSL_AF 0x00000010 /* bcd carry bit */
#define PSL_Z 0x00000040 /* zero bit */
#define PSL_N 0x00000080 /* negative bit */
#define PSL_T 0x00000100 /* trace enable bit */
#define PSL_I 0x00000200 /* interrupt enable bit */
#define PSL_D 0x00000400 /* string instruction direction bit */
#define PSL_V 0x00000800 /* overflow bit */
#define PSL_IOPL 0x00003000 /* i/o privilege level */
#define PSL_NT 0x00004000 /* nested task bit */
#define PSL_RF 0x00010000 /* resume flag bit */
#define PSL_VM 0x00020000 /* virtual 8086 mode bit */
#define PSL_AC 0x00040000 /* alignment checking */
#define PSL_VIF 0x00080000 /* virtual interrupt enable */
#define PSL_VIP 0x00100000 /* virtual interrupt pending */
#define PSL_ID 0x00200000 /* identification bit */
/*
* The i486 manual says that we are not supposed to change reserved flags,
* but this is too much trouble since the reserved flags depend on the cpu
* and setting them to their historical values works in practice.
*/
#define PSL_RESERVED_DEFAULT 0x00000002
/*
* Initial flags for kernel and user mode. The kernel later inherits
* PSL_I and some other flags from user mode.
*/
#define PSL_KERNEL PSL_RESERVED_DEFAULT
#define PSL_USER (PSL_RESERVED_DEFAULT | PSL_I)
/*
* Bits that can be changed in user mode on 486's. We allow these bits
* to be changed using ptrace(), sigreturn() and procfs. Setting PS_NT
* is undesirable but it may as well be allowed since users can inflict
* it on the kernel directly. Changes to PSL_AC are silently ignored on
* 386's.
*
* Users are allowed to change the privileged flag PSL_RF. The cpu sets PSL_RF
* in tf_eflags for faults. Debuggers should sometimes set it there too.
* tf_eflags is kept in the signal context during signal handling and there is
* no other place to remember it, so the PSL_RF bit may be corrupted by the
* signal handler without us knowing. Corruption of the PSL_RF bit at worst
* causes one more or one less debugger trap, so allowing it is fairly
* harmless.
*/
#define PSL_USERCHANGE (PSL_C | PSL_PF | PSL_AF | PSL_Z | PSL_N | PSL_T \
| PSL_D | PSL_V | PSL_NT | PSL_RF | PSL_AC | PSL_ID)

View File

@ -0,0 +1,111 @@
/*-
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* from: @(#)rtc.h 7.1 (Berkeley) 5/12/91
* $FreeBSD$
*/
/*
* MC146818 RTC Register locations
*/
#pragma once
#define RTC_SEC 0x00 /* seconds */
#define RTC_SECALRM 0x01 /* seconds alarm */
#define RTC_MIN 0x02 /* minutes */
#define RTC_MINALRM 0x03 /* minutes alarm */
#define RTC_HRS 0x04 /* hours */
#define RTC_HRSALRM 0x05 /* hours alarm */
#define RTC_WDAY 0x06 /* week day */
#define RTC_DAY 0x07 /* day of month */
#define RTC_MONTH 0x08 /* month of year */
#define RTC_YEAR 0x09 /* month of year */
#define RTC_STATUSA 0x0a /* status register A */
#define RTCSA_TUP 0x80 /* time update, don't look now */
#define RTCSA_RESET 0x70 /* reset divider */
#define RTCSA_DIVIDER 0x20 /* divider correct for 32768 Hz */
#define RTCSA_8192 0x03 /* 8192 Hz interrupt */
#define RTCSA_4096 0x04
#define RTCSA_2048 0x05
#define RTCSA_1024 0x06 /* default for profiling */
#define RTCSA_PROF RTCSA_1024
#define RTC_PROFRATE 1024
#define RTCSA_512 0x07
#define RTCSA_256 0x08
#define RTCSA_128 0x09
#define RTCSA_NOPROF RTCSA_128
#define RTC_NOPROFRATE 128
#define RTCSA_64 0x0a
#define RTCSA_32 0x0b /* 32 Hz interrupt */
#define RTC_STATUSB 0x0b /* status register B */
#define RTCSB_DST 0x01 /* USA Daylight Savings Time enable */
#define RTCSB_24HR 0x02 /* 0 = 12 hours, 1 = 24 hours */
#define RTCSB_BCD 0x04 /* 0 = BCD, 1 = Binary coded time */
#define RTCSB_SQWE 0x08 /* 1 = output sqare wave at SQW pin */
#define RTCSB_UINTR 0x10 /* 1 = enable update-ended interrupt */
#define RTCSB_AINTR 0x20 /* 1 = enable alarm interrupt */
#define RTCSB_PINTR 0x40 /* 1 = enable periodic clock interrupt */
#define RTCSB_HALT 0x80 /* stop clock updates */
#define RTC_INTR 0x0c /* status register C (R) interrupt source */
#define RTCIR_UPDATE 0x10 /* update intr */
#define RTCIR_ALARM 0x20 /* alarm intr */
#define RTCIR_PERIOD 0x40 /* periodic intr */
#define RTCIR_INT 0x80 /* interrupt output signal */
#define RTC_STATUSD 0x0d /* status register D (R) Lost Power */
#define RTCSD_PWR 0x80 /* clock power OK */
#define RTC_DIAG 0x0e /* status register E - bios diagnostic */
#define RTCDG_BITS "\020\010clock_battery\007ROM_cksum\006config_unit\005memory_size\004fixed_disk\003invalid_time"
#define RTC_RESET 0x0f /* status register F - reset code byte */
#define RTCRS_RST 0x00 /* normal reset */
#define RTCRS_LOAD 0x04 /* load system */
#define RTC_FDISKETTE 0x10 /* diskette drive type in upper/lower nibble */
#define RTCFDT_NONE 0 /* none present */
#define RTCFDT_360K 0x10 /* 360K */
#define RTCFDT_12M 0x20 /* 1.2M */
#define RTCFDT_720K 0x30 /* 720K */
#define RTCFDT_144M 0x40 /* 1.44M */
#define RTCFDT_288M_1 0x50 /* 2.88M, some BIOSes */
#define RTCFDT_288M 0x60 /* 2.88M */
#define RTC_BASELO 0x15 /* low byte of basemem size */
#define RTC_BASEHI 0x16 /* high byte of basemem size */
#define RTC_EXTLO 0x17 /* low byte of extended mem size */
#define RTC_EXTHI 0x18 /* low byte of extended mem size */
#define RTC_CENTURY 0x32 /* current century */

View File

@ -0,0 +1,277 @@
/*-
* Copyright (c) 1989, 1990 William F. Jolitz
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* from: @(#)segments.h 7.1 (Berkeley) 5/9/91
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <xhyve/support/misc.h>
// /*
// * X86 Segmentation Data Structures and definitions
// */
/* Selectors */
#define SEL_RPL_MASK 3 /* requester priv level */
#define ISPL(s) ((s) & 3) /* priority level of a selector */
#define SEL_KPL 0 /* kernel priority level */
#define SEL_UPL 3 /* user priority level */
#define ISLDT(s) ((s) & SEL_LDT) /* is it local or global */
#define SEL_LDT 4 /* local descriptor table */
#define IDXSEL(s) (((s)>>3) & 0x1fff) /* index of selector */
#define LSEL(s,r) (((s)<<3) | SEL_LDT | r) /* a local selector */
#define GSEL(s,r) (((s)<<3) | r) /* a global selector */
/*
* User segment descriptors (%cs, %ds etc for i386 apps. 64 bit wide)
* For long-mode apps, %cs only has the conforming bit in sd_type, the sd_dpl,
* sd_p, sd_l and sd_def32 which must be zero). %ds only has sd_p.
*/
struct segment_descriptor {
unsigned sd_lolimit:16; /* segment extent (lsb) */
unsigned sd_lobase:24; /* segment base address (lsb) */
unsigned sd_type:5; /* segment type */
unsigned sd_dpl:2; /* segment descriptor priority level */
unsigned sd_p:1; /* segment descriptor present */
unsigned sd_hilimit:4; /* segment extent (msb) */
unsigned sd_xx:2; /* unused */
unsigned sd_def32:1; /* default 32 vs 16 bit size */
unsigned sd_gran:1; /* limit granularity (byte/page units)*/
unsigned sd_hibase:8; /* segment base address (msb) */
} __packed;
struct user_segment_descriptor {
uint64_t sd_lolimit:16; /* segment extent (lsb) */
uint64_t sd_lobase:24; /* segment base address (lsb) */
uint64_t sd_type:5; /* segment type */
uint64_t sd_dpl:2; /* segment descriptor priority level */
uint64_t sd_p:1; /* segment descriptor present */
uint64_t sd_hilimit:4; /* segment extent (msb) */
uint64_t sd_xx:1; /* unused */
uint64_t sd_long:1; /* long mode (cs only) */
uint64_t sd_def32:1; /* default 32 vs 16 bit size */
uint64_t sd_gran:1; /* limit granularity (byte/page units)*/
uint64_t sd_hibase:8; /* segment base address (msb) */
};
#define USD_GETBASE(sd) (((sd)->sd_lobase) | (sd)->sd_hibase << 24)
#define USD_SETBASE(sd, b) (sd)->sd_lobase = (b); \
(sd)->sd_hibase = ((b) >> 24);
#define USD_GETLIMIT(sd) (((sd)->sd_lolimit) | (sd)->sd_hilimit << 16)
#define USD_SETLIMIT(sd, l) (sd)->sd_lolimit = (l); \
(sd)->sd_hilimit = ((l) >> 16);
// #ifdef __i386__
// /*
// * Gate descriptors (e.g. indirect descriptors)
// */
// struct gate_descriptor {
// unsigned gd_looffset:16; /* gate offset (lsb) */
// unsigned gd_selector:16; /* gate segment selector */
// unsigned gd_stkcpy:5; /* number of stack wds to cpy */
// unsigned gd_xx:3; /* unused */
// unsigned gd_type:5; /* segment type */
// unsigned gd_dpl:2; /* segment descriptor priority level */
// unsigned gd_p:1; /* segment descriptor present */
// unsigned gd_hioffset:16; /* gate offset (msb) */
// } __packed;
// /*
// * Generic descriptor
// */
// union descriptor {
// struct segment_descriptor sd;
// struct gate_descriptor gd;
// };
// #else
// /*
// * Gate descriptors (e.g. indirect descriptors, trap, interrupt etc. 128 bit)
// * Only interrupt and trap gates have gd_ist.
// */
// struct gate_descriptor {
// uint64_t gd_looffset:16; /* gate offset (lsb) */
// uint64_t gd_selector:16; /* gate segment selector */
// uint64_t gd_ist:3; /* IST table index */
// uint64_t gd_xx:5; /* unused */
// uint64_t gd_type:5; /* segment type */
// uint64_t gd_dpl:2; /* segment descriptor priority level */
// uint64_t gd_p:1; /* segment descriptor present */
// uint64_t gd_hioffset:48; /* gate offset (msb) */
// uint64_t sd_xx1:32;
// } __packed;
// /*
// * Generic descriptor
// */
// union descriptor {
// struct user_segment_descriptor sd;
// struct gate_descriptor gd;
// };
// #endif
/* system segments and gate types */
#define SDT_SYSNULL 0 /* system null */
#define SDT_SYS286TSS 1 /* system 286 TSS available */
#define SDT_SYSLDT 2 /* system local descriptor table */
#define SDT_SYS286BSY 3 /* system 286 TSS busy */
#define SDT_SYS286CGT 4 /* system 286 call gate */
#define SDT_SYSTASKGT 5 /* system task gate */
#define SDT_SYS286IGT 6 /* system 286 interrupt gate */
#define SDT_SYS286TGT 7 /* system 286 trap gate */
#define SDT_SYSNULL2 8 /* system null again */
#define SDT_SYS386TSS 9 /* system 386 TSS available */
#define SDT_SYSTSS 9 /* system available 64 bit TSS */
#define SDT_SYSNULL3 10 /* system null again */
#define SDT_SYS386BSY 11 /* system 386 TSS busy */
#define SDT_SYSBSY 11 /* system busy 64 bit TSS */
#define SDT_SYS386CGT 12 /* system 386 call gate */
#define SDT_SYSCGT 12 /* system 64 bit call gate */
#define SDT_SYSNULL4 13 /* system null again */
#define SDT_SYS386IGT 14 /* system 386 interrupt gate */
#define SDT_SYSIGT 14 /* system 64 bit interrupt gate */
#define SDT_SYS386TGT 15 /* system 386 trap gate */
#define SDT_SYSTGT 15 /* system 64 bit trap gate */
// /* memory segment types */
// #define SDT_MEMRO 16 memory read only
// #define SDT_MEMROA 17 /* memory read only accessed */
#define SDT_MEMRW 18 /* memory read write */
#define SDT_MEMRWA 19 /* memory read write accessed */
// #define SDT_MEMROD 20 /* memory read only expand dwn limit */
// #define SDT_MEMRODA 21 /* memory read only expand dwn limit accessed */
// #define SDT_MEMRWD 22 /* memory read write expand dwn limit */
// #define SDT_MEMRWDA 23 /* memory read write expand dwn limit accessed*/
// #define SDT_MEME 24 /* memory execute only */
// #define SDT_MEMEA 25 /* memory execute only accessed */
#define SDT_MEMER 26 /* memory execute read */
#define SDT_MEMERA 27 /* memory execute read accessed */
// #define SDT_MEMEC 28 /* memory execute only conforming */
// #define SDT_MEMEAC 29 /* memory execute only accessed conforming */
// #define SDT_MEMERC 30 /* memory execute read conforming */
// #define SDT_MEMERAC 31 /* memory execute read accessed conforming */
// /*
// * Size of IDT table
// */
// #define NIDT 256 /* 32 reserved, 0x80 syscall, most are h/w */
// #define NRSVIDT 32 /* reserved entries for cpu exceptions */
/*
* Entries in the Interrupt Descriptor Table (IDT)
*/
#define IDT_DE 0 /* #DE: Divide Error */
#define IDT_DB 1 /* #DB: Debug */
#define IDT_NMI 2 /* Nonmaskable External Interrupt */
#define IDT_BP 3 /* #BP: Breakpoint */
#define IDT_OF 4 /* #OF: Overflow */
#define IDT_BR 5 /* #BR: Bound Range Exceeded */
#define IDT_UD 6 /* #UD: Undefined/Invalid Opcode */
#define IDT_NM 7 /* #NM: No Math Coprocessor */
#define IDT_DF 8 /* #DF: Double Fault */
#define IDT_FPUGP 9 /* Coprocessor Segment Overrun */
#define IDT_TS 10 /* #TS: Invalid TSS */
#define IDT_NP 11 /* #NP: Segment Not Present */
#define IDT_SS 12 /* #SS: Stack Segment Fault */
#define IDT_GP 13 /* #GP: General Protection Fault */
#define IDT_PF 14 /* #PF: Page Fault */
#define IDT_MF 16 /* #MF: FPU Floating-Point Error */
#define IDT_AC 17 /* #AC: Alignment Check */
#define IDT_MC 18 /* #MC: Machine Check */
#define IDT_XF 19 /* #XF: SIMD Floating-Point Exception */
#define IDT_IO_INTS NRSVIDT /* Base of IDT entries for I/O interrupts. */
#define IDT_SYSCALL 0x80 /* System Call Interrupt Vector */
#define IDT_DTRACE_RET 0x92 /* DTrace pid provider Interrupt Vector */
#define IDT_EVTCHN 0x93 /* Xen HVM Event Channel Interrupt Vector */
// #if defined(__i386__)
// /*
// * Entries in the Global Descriptor Table (GDT)
// * Note that each 4 entries share a single 32 byte L1 cache line.
// * Some of the fast syscall instructions require a specific order here.
// */
// #define GNULL_SEL 0 /* Null Descriptor */
// #define GPRIV_SEL 1 /* SMP Per-Processor Private Data */
// #define GUFS_SEL 2 /* User %fs Descriptor (order critical: 1) */
// #define GUGS_SEL 3 /* User %gs Descriptor (order critical: 2) */
// #define GCODE_SEL 4 /* Kernel Code Descriptor (order critical: 1) */
// #define GDATA_SEL 5 /* Kernel Data Descriptor (order critical: 2) */
// #define GUCODE_SEL 6 /* User Code Descriptor (order critical: 3) */
// #define GUDATA_SEL 7 /* User Data Descriptor (order critical: 4) */
// #define GBIOSLOWMEM_SEL 8 /* BIOS low memory access (must be entry 8) */
// #define GPROC0_SEL 9 /* Task state process slot zero and up */
// #define GLDT_SEL 10 /* Default User LDT */
// #define GUSERLDT_SEL 11 /* User LDT */
// #define GPANIC_SEL 12 /* Task state to consider panic from */
// #define GBIOSCODE32_SEL 13 /* BIOS interface (32bit Code) */
// #define GBIOSCODE16_SEL 14 /* BIOS interface (16bit Code) */
// #define GBIOSDATA_SEL 15 /* BIOS interface (Data) */
// #define GBIOSUTIL_SEL 16 /* BIOS interface (Utility) */
// #define GBIOSARGS_SEL 17 /* BIOS interface (Arguments) */
// #define GNDIS_SEL 18 /* For the NDIS layer */
// #define NGDT 19
// /*
// * Entries in the Local Descriptor Table (LDT)
// */
// #define LSYS5CALLS_SEL 0 /* forced by intel BCS */
// #define LSYS5SIGR_SEL 1
// #define L43BSDCALLS_SEL 2 /* notyet */
// #define LUCODE_SEL 3
// #define LSOL26CALLS_SEL 4 /* Solaris >= 2.6 system call gate */
// #define LUDATA_SEL 5
// /* separate stack, es,fs,gs sels ? */
// /* #define LPOSIXCALLS_SEL 5*/ /* notyet */
// #define LBSDICALLS_SEL 16 /* BSDI system call gate */
// #define NLDT (LBSDICALLS_SEL + 1)
// #else /* !__i386__ */
// /*
// * Entries in the Global Descriptor Table (GDT)
// */
// #define GNULL_SEL 0 /* Null Descriptor */
// #define GNULL2_SEL 1 /* Null Descriptor */
// #define GUFS32_SEL 2 /* User 32 bit %fs Descriptor */
// #define GUGS32_SEL 3 /* User 32 bit %gs Descriptor */
// #define GCODE_SEL 4 /* Kernel Code Descriptor */
// #define GDATA_SEL 5 /* Kernel Data Descriptor */
// #define GUCODE32_SEL 6 /* User 32 bit code Descriptor */
// #define GUDATA_SEL 7 /* User 32/64 bit Data Descriptor */
// #define GUCODE_SEL 8 /* User 64 bit Code Descriptor */
// #define GPROC0_SEL 9 /* TSS for entering kernel etc */
// /* slot 10 is second half of GPROC0_SEL */
// #define GUSERLDT_SEL 11 /* LDT */
// /* slot 12 is second half of GUSERLDT_SEL */
// #define NGDT 13
// #endif /* __i386__ */

View File

@ -0,0 +1,845 @@
/*-
* Copyright (c) 1991 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* from: @(#)specialreg.h 7.1 (Berkeley) 5/9/91
* $FreeBSD$
*/
#pragma once
/*
* Bits in 386 special registers:
*/
#define CR0_PE 0x00000001 /* Protected mode Enable */
#define CR0_MP 0x00000002 /* "Math" (fpu) Present */
#define CR0_EM 0x00000004 /* EMulate FPU instructions. (trap ESC only) */
#define CR0_TS 0x00000008 /* Task Switched (if MP, trap ESC and WAIT) */
#define CR0_PG 0x80000000 /* PaGing enable */
/*
* Bits in 486 special registers:
*/
#define CR0_ET 0x00000010 /* Extension type */
#define CR0_NE 0x00000020 /* Numeric Error enable (EX16 vs IRQ13) */
#define CR0_WP 0x00010000 /* Write Protect (honor page protect in
all modes) */
#define CR0_AM 0x00040000 /* Alignment Mask (set to enable AC flag) */
#define CR0_NW 0x20000000 /* Not Write-through */
#define CR0_CD 0x40000000 /* Cache Disable */
#define CR3_PCID_SAVE 0x8000000000000000
#define CR3_PCID_MASK 0xfff
/*
* Bits in PPro special registers
*/
#define CR4_VME 0x00000001 /* Virtual 8086 mode extensions */
#define CR4_PVI 0x00000002 /* Protected-mode virtual interrupts */
#define CR4_TSD 0x00000004 /* Time stamp disable */
#define CR4_DE 0x00000008 /* Debugging extensions */
#define CR4_PSE 0x00000010 /* Page size extensions */
#define CR4_PAE 0x00000020 /* Physical address extension */
#define CR4_MCE 0x00000040 /* Machine check enable */
#define CR4_PGE 0x00000080 /* Page global enable */
#define CR4_PCE 0x00000100 /* Performance monitoring counter enable */
#define CR4_FXSR 0x00000200 /* Fast FPU save/restore used by OS */
#define CR4_XMM 0x00000400 /* enable SIMD/MMX2 to use except 16 */
#define CR4_VMXE 0x00002000 /* enable VMX operation (Intel-specific) */
#define CR4_FSGSBASE 0x00010000 /* Enable FS/GS BASE accessing instructions */
#define CR4_PCIDE 0x00020000 /* Enable Context ID */
#define CR4_XSAVE 0x00040000 /* XSETBV/XGETBV */
#define CR4_SMEP 0x00100000 /* Supervisor-Mode Execution Prevention */
/*
* Bits in AMD64 special registers. EFER is 64 bits wide.
*/
#define EFER_SCE 0x000000001 /* System Call Extensions (R/W) */
#define EFER_LME 0x000000100 /* Long mode enable (R/W) */
#define EFER_LMA 0x000000400 /* Long mode active (R) */
#define EFER_NXE 0x000000800 /* PTE No-Execute bit enable (R/W) */
#define EFER_SVM 0x000001000 /* SVM enable bit for AMD, reserved for Intel */
#define EFER_LMSLE 0x000002000 /* Long Mode Segment Limit Enable */
#define EFER_FFXSR 0x000004000 /* Fast FXSAVE/FSRSTOR */
#define EFER_TCE 0x000008000 /* Translation Cache Extension */
/*
* Intel Extended Features registers
*/
#define XCR0 0 /* XFEATURE_ENABLED_MASK register */
#define XFEATURE_ENABLED_X87 0x00000001
#define XFEATURE_ENABLED_SSE 0x00000002
#define XFEATURE_ENABLED_YMM_HI128 0x00000004
#define XFEATURE_ENABLED_AVX XFEATURE_ENABLED_YMM_HI128
#define XFEATURE_ENABLED_BNDREGS 0x00000008
#define XFEATURE_ENABLED_BNDCSR 0x00000010
#define XFEATURE_ENABLED_OPMASK 0x00000020
#define XFEATURE_ENABLED_ZMM_HI256 0x00000040
#define XFEATURE_ENABLED_HI16_ZMM 0x00000080
#define XFEATURE_AVX \
(XFEATURE_ENABLED_X87 | XFEATURE_ENABLED_SSE | XFEATURE_ENABLED_AVX)
#define XFEATURE_AVX512 \
(XFEATURE_ENABLED_OPMASK | XFEATURE_ENABLED_ZMM_HI256 | \
XFEATURE_ENABLED_HI16_ZMM)
#define XFEATURE_MPX \
(XFEATURE_ENABLED_BNDREGS | XFEATURE_ENABLED_BNDCSR)
/*
* CPUID instruction features register
*/
#define CPUID_FPU 0x00000001
#define CPUID_VME 0x00000002
#define CPUID_DE 0x00000004
#define CPUID_PSE 0x00000008
#define CPUID_TSC 0x00000010
#define CPUID_MSR 0x00000020
#define CPUID_PAE 0x00000040
#define CPUID_MCE 0x00000080
#define CPUID_CX8 0x00000100
#define CPUID_APIC 0x00000200
#define CPUID_B10 0x00000400
#define CPUID_SEP 0x00000800
#define CPUID_MTRR 0x00001000
#define CPUID_PGE 0x00002000
#define CPUID_MCA 0x00004000
#define CPUID_CMOV 0x00008000
#define CPUID_PAT 0x00010000
#define CPUID_PSE36 0x00020000
#define CPUID_PSN 0x00040000
#define CPUID_CLFSH 0x00080000
#define CPUID_B20 0x00100000
#define CPUID_DS 0x00200000
#define CPUID_ACPI 0x00400000
#define CPUID_MMX 0x00800000
#define CPUID_FXSR 0x01000000
#define CPUID_SSE 0x02000000
#define CPUID_XMM 0x02000000
#define CPUID_SSE2 0x04000000
#define CPUID_SS 0x08000000
#define CPUID_HTT 0x10000000
#define CPUID_TM 0x20000000
#define CPUID_IA64 0x40000000
#define CPUID_PBE 0x80000000
#define CPUID2_SSE3 0x00000001
#define CPUID2_PCLMULQDQ 0x00000002
#define CPUID2_DTES64 0x00000004
#define CPUID2_MON 0x00000008
#define CPUID2_DS_CPL 0x00000010
#define CPUID2_VMX 0x00000020
#define CPUID2_SMX 0x00000040
#define CPUID2_EST 0x00000080
#define CPUID2_TM2 0x00000100
#define CPUID2_SSSE3 0x00000200
#define CPUID2_CNXTID 0x00000400
#define CPUID2_SDBG 0x00000800
#define CPUID2_FMA 0x00001000
#define CPUID2_CX16 0x00002000
#define CPUID2_XTPR 0x00004000
#define CPUID2_PDCM 0x00008000
#define CPUID2_PCID 0x00020000
#define CPUID2_DCA 0x00040000
#define CPUID2_SSE41 0x00080000
#define CPUID2_SSE42 0x00100000
#define CPUID2_X2APIC 0x00200000
#define CPUID2_MOVBE 0x00400000
#define CPUID2_POPCNT 0x00800000
#define CPUID2_TSCDLT 0x01000000
#define CPUID2_AESNI 0x02000000
#define CPUID2_XSAVE 0x04000000
#define CPUID2_OSXSAVE 0x08000000
#define CPUID2_AVX 0x10000000
#define CPUID2_F16C 0x20000000
#define CPUID2_RDRAND 0x40000000
#define CPUID2_HV 0x80000000
/*
* Important bits in the Thermal and Power Management flags
* CPUID.6 EAX and ECX.
*/
#define CPUTPM1_SENSOR 0x00000001
#define CPUTPM1_TURBO 0x00000002
#define CPUTPM1_ARAT 0x00000004
#define CPUTPM2_EFFREQ 0x00000001
/*
* Important bits in the AMD extended cpuid flags
*/
#define AMDID_SYSCALL 0x00000800
#define AMDID_MP 0x00080000
#define AMDID_NX 0x00100000
#define AMDID_EXT_MMX 0x00400000
#define AMDID_FFXSR 0x02000000
#define AMDID_PAGE1GB 0x04000000
#define AMDID_RDTSCP 0x08000000
#define AMDID_LM 0x20000000
#define AMDID_EXT_3DNOW 0x40000000
#define AMDID_3DNOW 0x80000000
#define AMDID2_LAHF 0x00000001
#define AMDID2_CMP 0x00000002
#define AMDID2_SVM 0x00000004
#define AMDID2_EXT_APIC 0x00000008
#define AMDID2_CR8 0x00000010
#define AMDID2_ABM 0x00000020
#define AMDID2_SSE4A 0x00000040
#define AMDID2_MAS 0x00000080
#define AMDID2_PREFETCH 0x00000100
#define AMDID2_OSVW 0x00000200
#define AMDID2_IBS 0x00000400
#define AMDID2_XOP 0x00000800
#define AMDID2_SKINIT 0x00001000
#define AMDID2_WDT 0x00002000
#define AMDID2_LWP 0x00008000
#define AMDID2_FMA4 0x00010000
#define AMDID2_TCE 0x00020000
#define AMDID2_NODE_ID 0x00080000
#define AMDID2_TBM 0x00200000
#define AMDID2_TOPOLOGY 0x00400000
#define AMDID2_PCXC 0x00800000
#define AMDID2_PNXC 0x01000000
#define AMDID2_DBE 0x04000000
#define AMDID2_PTSC 0x08000000
#define AMDID2_PTSCEL2I 0x10000000
/*
* CPUID instruction 1 eax info
*/
#define CPUID_STEPPING 0x0000000f
#define CPUID_MODEL 0x000000f0
#define CPUID_FAMILY 0x00000f00
#define CPUID_EXT_MODEL 0x000f0000
#define CPUID_EXT_FAMILY 0x0ff00000
// #ifdef __i386__
// #define CPUID_TO_MODEL(id) \
// ((((id) & CPUID_MODEL) >> 4) | \
// ((((id) & CPUID_FAMILY) >= 0x600) ? \
// (((id) & CPUID_EXT_MODEL) >> 12) : 0))
// #define CPUID_TO_FAMILY(id) \
// ((((id) & CPUID_FAMILY) >> 8) + \
// ((((id) & CPUID_FAMILY) == 0xf00) ? \
// (((id) & CPUID_EXT_FAMILY) >> 20) : 0))
// #else
// #define CPUID_TO_MODEL(id) \
// ((((id) & CPUID_MODEL) >> 4) | \
// (((id) & CPUID_EXT_MODEL) >> 12))
// #define CPUID_TO_FAMILY(id) \
// ((((id) & CPUID_FAMILY) >> 8) + \
// (((id) & CPUID_EXT_FAMILY) >> 20))
// #endif
/*
* CPUID instruction 1 ebx info
*/
#define CPUID_BRAND_INDEX 0x000000ff
#define CPUID_CLFUSH_SIZE 0x0000ff00
#define CPUID_HTT_CORES 0x00ff0000
#define CPUID_LOCAL_APIC_ID 0xff000000
/*
* CPUID instruction 5 info
*/
#define CPUID5_MON_MIN_SIZE 0x0000ffff /* eax */
#define CPUID5_MON_MAX_SIZE 0x0000ffff /* ebx */
#define CPUID5_MON_MWAIT_EXT 0x00000001 /* ecx */
#define CPUID5_MWAIT_INTRBREAK 0x00000002 /* ecx */
/*
* MWAIT cpu power states. Lower 4 bits are sub-states.
*/
#define MWAIT_C0 0xf0
#define MWAIT_C1 0x00
#define MWAIT_C2 0x10
#define MWAIT_C3 0x20
#define MWAIT_C4 0x30
/*
* MWAIT extensions.
*/
/* Interrupt breaks MWAIT even when masked. */
#define MWAIT_INTRBREAK 0x00000001
/*
* CPUID instruction 6 ecx info
*/
#define CPUID_PERF_STAT 0x00000001
#define CPUID_PERF_BIAS 0x00000008
/*
* CPUID instruction 0xb ebx info.
*/
#define CPUID_TYPE_INVAL 0
#define CPUID_TYPE_SMT 1
#define CPUID_TYPE_CORE 2
/*
* CPUID instruction 0xd Processor Extended State Enumeration Sub-leaf 1
*/
#define CPUID_EXTSTATE_XSAVEOPT 0x00000001
#define CPUID_EXTSTATE_XSAVEC 0x00000002
#define CPUID_EXTSTATE_XINUSE 0x00000004
#define CPUID_EXTSTATE_XSAVES 0x00000008
/*
* AMD extended function 8000_0007h edx info
*/
#define AMDPM_TS 0x00000001
#define AMDPM_FID 0x00000002
#define AMDPM_VID 0x00000004
#define AMDPM_TTP 0x00000008
#define AMDPM_TM 0x00000010
#define AMDPM_STC 0x00000020
#define AMDPM_100MHZ_STEPS 0x00000040
#define AMDPM_HW_PSTATE 0x00000080
#define AMDPM_TSC_INVARIANT 0x00000100
#define AMDPM_CPB 0x00000200
/*
* AMD extended function 8000_0008h ecx info
*/
#define AMDID_CMP_CORES 0x000000ff
#define AMDID_COREID_SIZE 0x0000f000
#define AMDID_COREID_SIZE_SHIFT 12
/*
* CPUID instruction 7 Structured Extended Features, leaf 0 ebx info
*/
#define CPUID_STDEXT_FSGSBASE 0x00000001
#define CPUID_STDEXT_TSC_ADJUST 0x00000002
#define CPUID_STDEXT_BMI1 0x00000008
#define CPUID_STDEXT_HLE 0x00000010
#define CPUID_STDEXT_AVX2 0x00000020
#define CPUID_STDEXT_SMEP 0x00000080
#define CPUID_STDEXT_BMI2 0x00000100
#define CPUID_STDEXT_ERMS 0x00000200
#define CPUID_STDEXT_INVPCID 0x00000400
#define CPUID_STDEXT_RTM 0x00000800
#define CPUID_STDEXT_MPX 0x00004000
#define CPUID_STDEXT_AVX512F 0x00010000
#define CPUID_STDEXT_RDSEED 0x00040000
#define CPUID_STDEXT_ADX 0x00080000
#define CPUID_STDEXT_SMAP 0x00100000
#define CPUID_STDEXT_CLFLUSHOPT 0x00800000
#define CPUID_STDEXT_PROCTRACE 0x02000000
#define CPUID_STDEXT_AVX512PF 0x04000000
#define CPUID_STDEXT_AVX512ER 0x08000000
#define CPUID_STDEXT_AVX512CD 0x10000000
#define CPUID_STDEXT_SHA 0x20000000
/*
* CPUID manufacturers identifiers
*/
#define AMD_VENDOR_ID "AuthenticAMD"
#define CENTAUR_VENDOR_ID "CentaurHauls"
#define CYRIX_VENDOR_ID "CyrixInstead"
#define INTEL_VENDOR_ID "GenuineIntel"
#define NEXGEN_VENDOR_ID "NexGenDriven"
#define NSC_VENDOR_ID "Geode by NSC"
#define RISE_VENDOR_ID "RiseRiseRise"
#define SIS_VENDOR_ID "SiS SiS SiS "
#define TRANSMETA_VENDOR_ID "GenuineTMx86"
#define UMC_VENDOR_ID "UMC UMC UMC "
/*
* Model-specific registers for the i386 family
*/
#define MSR_P5_MC_ADDR 0x000
#define MSR_P5_MC_TYPE 0x001
#define MSR_TSC 0x010
#define MSR_P5_CESR 0x011
#define MSR_P5_CTR0 0x012
#define MSR_P5_CTR1 0x013
#define MSR_IA32_PLATFORM_ID 0x017
#define MSR_APICBASE 0x01b
#define MSR_EBL_CR_POWERON 0x02a
#define MSR_TEST_CTL 0x033
#define MSR_IA32_FEATURE_CONTROL 0x03a
#define MSR_BIOS_UPDT_TRIG 0x079
#define MSR_BBL_CR_D0 0x088
#define MSR_BBL_CR_D1 0x089
#define MSR_BBL_CR_D2 0x08a
#define MSR_BIOS_SIGN 0x08b
#define MSR_PERFCTR0 0x0c1
#define MSR_PERFCTR1 0x0c2
#define MSR_PLATFORM_INFO 0x0ce
#define MSR_MPERF 0x0e7
#define MSR_APERF 0x0e8
#define MSR_IA32_EXT_CONFIG 0x0ee /* Undocumented. Core Solo/Duo only */
#define MSR_MTRRcap 0x0fe
#define MSR_BBL_CR_ADDR 0x116
#define MSR_BBL_CR_DECC 0x118
#define MSR_BBL_CR_CTL 0x119
#define MSR_BBL_CR_TRIG 0x11a
#define MSR_BBL_CR_BUSY 0x11b
#define MSR_BBL_CR_CTL3 0x11e
#define MSR_SYSENTER_CS_MSR 0x174
#define MSR_SYSENTER_ESP_MSR 0x175
#define MSR_SYSENTER_EIP_MSR 0x176
#define MSR_MCG_CAP 0x179
#define MSR_MCG_STATUS 0x17a
#define MSR_MCG_CTL 0x17b
#define MSR_EVNTSEL0 0x186
#define MSR_EVNTSEL1 0x187
#define MSR_THERM_CONTROL 0x19a
#define MSR_THERM_INTERRUPT 0x19b
#define MSR_THERM_STATUS 0x19c
#define MSR_IA32_MISC_ENABLE 0x1a0
#define MSR_IA32_TEMPERATURE_TARGET 0x1a2
#define MSR_TURBO_RATIO_LIMIT 0x1ad
#define MSR_TURBO_RATIO_LIMIT1 0x1ae
#define MSR_DEBUGCTLMSR 0x1d9
#define MSR_LASTBRANCHFROMIP 0x1db
#define MSR_LASTBRANCHTOIP 0x1dc
#define MSR_LASTINTFROMIP 0x1dd
#define MSR_LASTINTTOIP 0x1de
#define MSR_ROB_CR_BKUPTMPDR6 0x1e0
#define MSR_MTRRVarBase 0x200
#define MSR_MTRR64kBase 0x250
#define MSR_MTRR16kBase 0x258
#define MSR_MTRR4kBase 0x268
#define MSR_PAT 0x277
#define MSR_MC0_CTL2 0x280
#define MSR_MTRRdefType 0x2ff
#define MSR_MC0_CTL 0x400
#define MSR_MC0_STATUS 0x401
#define MSR_MC0_ADDR 0x402
#define MSR_MC0_MISC 0x403
#define MSR_MC1_CTL 0x404
#define MSR_MC1_STATUS 0x405
#define MSR_MC1_ADDR 0x406
#define MSR_MC1_MISC 0x407
#define MSR_MC2_CTL 0x408
#define MSR_MC2_STATUS 0x409
#define MSR_MC2_ADDR 0x40a
#define MSR_MC2_MISC 0x40b
#define MSR_MC3_CTL 0x40c
#define MSR_MC3_STATUS 0x40d
#define MSR_MC3_ADDR 0x40e
#define MSR_MC3_MISC 0x40f
#define MSR_MC4_CTL 0x410
#define MSR_MC4_STATUS 0x411
#define MSR_MC4_ADDR 0x412
#define MSR_MC4_MISC 0x413
#define MSR_RAPL_POWER_UNIT 0x606
#define MSR_PKG_ENERGY_STATUS 0x611
#define MSR_DRAM_ENERGY_STATUS 0x619
#define MSR_PP0_ENERGY_STATUS 0x639
#define MSR_PP1_ENERGY_STATUS 0x641
/*
* VMX MSRs
*/
#define MSR_VMX_BASIC 0x480
#define MSR_VMX_PINBASED_CTLS 0x481
#define MSR_VMX_PROCBASED_CTLS 0x482
#define MSR_VMX_EXIT_CTLS 0x483
#define MSR_VMX_ENTRY_CTLS 0x484
#define MSR_VMX_CR0_FIXED0 0x486
#define MSR_VMX_CR0_FIXED1 0x487
#define MSR_VMX_CR4_FIXED0 0x488
#define MSR_VMX_CR4_FIXED1 0x489
#define MSR_VMX_PROCBASED_CTLS2 0x48b
#define MSR_VMX_EPT_VPID_CAP 0x48c
#define MSR_VMX_TRUE_PINBASED_CTLS 0x48d
#define MSR_VMX_TRUE_PROCBASED_CTLS 0x48e
#define MSR_VMX_TRUE_EXIT_CTLS 0x48f
#define MSR_VMX_TRUE_ENTRY_CTLS 0x490
/*
* X2APIC MSRs
*/
#define MSR_APIC_000 0x800
#define MSR_APIC_ID 0x802
#define MSR_APIC_VERSION 0x803
#define MSR_APIC_TPR 0x808
#define MSR_APIC_EOI 0x80b
#define MSR_APIC_LDR 0x80d
#define MSR_APIC_SVR 0x80f
#define MSR_APIC_ISR0 0x810
#define MSR_APIC_ISR1 0x811
#define MSR_APIC_ISR2 0x812
#define MSR_APIC_ISR3 0x813
#define MSR_APIC_ISR4 0x814
#define MSR_APIC_ISR5 0x815
#define MSR_APIC_ISR6 0x816
#define MSR_APIC_ISR7 0x817
#define MSR_APIC_TMR0 0x818
#define MSR_APIC_IRR0 0x820
#define MSR_APIC_ESR 0x828
#define MSR_APIC_LVT_CMCI 0x82F
#define MSR_APIC_ICR 0x830
#define MSR_APIC_LVT_TIMER 0x832
#define MSR_APIC_LVT_THERMAL 0x833
#define MSR_APIC_LVT_PCINT 0x834
#define MSR_APIC_LVT_LINT0 0x835
#define MSR_APIC_LVT_LINT1 0x836
#define MSR_APIC_LVT_ERROR 0x837
#define MSR_APIC_ICR_TIMER 0x838
#define MSR_APIC_CCR_TIMER 0x839
#define MSR_APIC_DCR_TIMER 0x83e
#define MSR_APIC_SELF_IPI 0x83f
#define MSR_IA32_XSS 0xda0
#define MSR_IA32_TSC_AUX 0xc0000103
/*
* Constants related to MSR's.
*/
#define APICBASE_RESERVED 0x000002ff
#define APICBASE_BSP 0x00000100
#define APICBASE_X2APIC 0x00000400
#define APICBASE_ENABLED 0x00000800
#define APICBASE_ADDRESS 0xfffff000
/* MSR_IA32_FEATURE_CONTROL related */
#define IA32_FEATURE_CONTROL_LOCK 0x01 /* lock bit */
#define IA32_FEATURE_CONTROL_SMX_EN 0x02 /* enable VMX inside SMX */
#define IA32_FEATURE_CONTROL_VMX_EN 0x04 /* enable VMX outside SMX */
/*
* PAT modes.
*/
#define PAT_UNCACHEABLE 0x00
#define PAT_WRITE_COMBINING 0x01
#define PAT_WRITE_THROUGH 0x04
#define PAT_WRITE_PROTECTED 0x05
#define PAT_WRITE_BACK 0x06
#define PAT_UNCACHED 0x07
#define PAT_VALUE(i, m) ((long long)(m) << (8 * (i)))
#define PAT_MASK(i) PAT_VALUE(i, 0xff)
/*
* Constants related to MTRRs
*/
#define MTRR_UNCACHEABLE 0x00
#define MTRR_WRITE_COMBINING 0x01
#define MTRR_WRITE_THROUGH 0x04
#define MTRR_WRITE_PROTECTED 0x05
#define MTRR_WRITE_BACK 0x06
#define MTRR_N64K 8 /* numbers of fixed-size entries */
#define MTRR_N16K 16
#define MTRR_N4K 64
#define MTRR_CAP_WC 0x0000000000000400
#define MTRR_CAP_FIXED 0x0000000000000100
#define MTRR_CAP_VCNT 0x00000000000000ff
#define MTRR_DEF_ENABLE 0x0000000000000800
#define MTRR_DEF_FIXED_ENABLE 0x0000000000000400
#define MTRR_DEF_TYPE 0x00000000000000ff
#define MTRR_PHYSBASE_PHYSBASE 0x000ffffffffff000
#define MTRR_PHYSBASE_TYPE 0x00000000000000ff
#define MTRR_PHYSMASK_PHYSMASK 0x000ffffffffff000
#define MTRR_PHYSMASK_VALID 0x0000000000000800
/*
* Cyrix configuration registers, accessible as IO ports.
*/
#define CCR0 0xc0 /* Configuration control register 0 */
#define CCR0_NC0 0x01 /* First 64K of each 1M memory region is
non-cacheable */
#define CCR0_NC1 0x02 /* 640K-1M region is non-cacheable */
#define CCR0_A20M 0x04 /* Enables A20M# input pin */
#define CCR0_KEN 0x08 /* Enables KEN# input pin */
#define CCR0_FLUSH 0x10 /* Enables FLUSH# input pin */
#define CCR0_BARB 0x20 /* Flushes internal cache when entering hold
state */
#define CCR0_CO 0x40 /* Cache org: 1=direct mapped, 0=2x set
assoc */
#define CCR0_SUSPEND 0x80 /* Enables SUSP# and SUSPA# pins */
#define CCR1 0xc1 /* Configuration control register 1 */
#define CCR1_RPL 0x01 /* Enables RPLSET and RPLVAL# pins */
#define CCR1_SMI 0x02 /* Enables SMM pins */
#define CCR1_SMAC 0x04 /* System management memory access */
#define CCR1_MMAC 0x08 /* Main memory access */
#define CCR1_NO_LOCK 0x10 /* Negate LOCK# */
#define CCR1_SM3 0x80 /* SMM address space address region 3 */
#define CCR2 0xc2
#define CCR2_WB 0x02 /* Enables WB cache interface pins */
#define CCR2_SADS 0x02 /* Slow ADS */
#define CCR2_LOCK_NW 0x04 /* LOCK NW Bit */
#define CCR2_SUSP_HLT 0x08 /* Suspend on HALT */
#define CCR2_WT1 0x10 /* WT region 1 */
#define CCR2_WPR1 0x10 /* Write-protect region 1 */
#define CCR2_BARB 0x20 /* Flushes write-back cache when entering
hold state. */
#define CCR2_BWRT 0x40 /* Enables burst write cycles */
#define CCR2_USE_SUSP 0x80 /* Enables suspend pins */
#define CCR3 0xc3
#define CCR3_SMILOCK 0x01 /* SMM register lock */
#define CCR3_NMI 0x02 /* Enables NMI during SMM */
#define CCR3_LINBRST 0x04 /* Linear address burst cycles */
#define CCR3_SMMMODE 0x08 /* SMM Mode */
#define CCR3_MAPEN0 0x10 /* Enables Map0 */
#define CCR3_MAPEN1 0x20 /* Enables Map1 */
#define CCR3_MAPEN2 0x40 /* Enables Map2 */
#define CCR3_MAPEN3 0x80 /* Enables Map3 */
#define CCR4 0xe8
#define CCR4_IOMASK 0x07
#define CCR4_MEM 0x08 /* Enables momory bypassing */
#define CCR4_DTE 0x10 /* Enables directory table entry cache */
#define CCR4_FASTFPE 0x20 /* Fast FPU exception */
#define CCR4_CPUID 0x80 /* Enables CPUID instruction */
#define CCR5 0xe9
#define CCR5_WT_ALLOC 0x01 /* Write-through allocate */
#define CCR5_SLOP 0x02 /* LOOP instruction slowed down */
#define CCR5_LBR1 0x10 /* Local bus region 1 */
#define CCR5_ARREN 0x20 /* Enables ARR region */
#define CCR6 0xea
#define CCR7 0xeb
/* Performance Control Register (5x86 only). */
#define PCR0 0x20
#define PCR0_RSTK 0x01 /* Enables return stack */
#define PCR0_BTB 0x02 /* Enables branch target buffer */
#define PCR0_LOOP 0x04 /* Enables loop */
#define PCR0_AIS 0x08 /* Enables all instrcutions stalled to
serialize pipe. */
#define PCR0_MLR 0x10 /* Enables reordering of misaligned loads */
#define PCR0_BTBRT 0x40 /* Enables BTB test register. */
#define PCR0_LSSER 0x80 /* Disable reorder */
/* Device Identification Registers */
#define DIR0 0xfe
#define DIR1 0xff
/*
* Machine Check register constants.
*/
#define MCG_CAP_COUNT 0x000000ff
#define MCG_CAP_CTL_P 0x00000100
#define MCG_CAP_EXT_P 0x00000200
#define MCG_CAP_CMCI_P 0x00000400
#define MCG_CAP_TES_P 0x00000800
#define MCG_CAP_EXT_CNT 0x00ff0000
#define MCG_CAP_SER_P 0x01000000
#define MCG_STATUS_RIPV 0x00000001
#define MCG_STATUS_EIPV 0x00000002
#define MCG_STATUS_MCIP 0x00000004
#define MCG_CTL_ENABLE 0xffffffffffffffff
#define MCG_CTL_DISABLE 0x0000000000000000
#define MSR_MC_CTL(x) (MSR_MC0_CTL + (x) * 4)
#define MSR_MC_STATUS(x) (MSR_MC0_STATUS + (x) * 4)
#define MSR_MC_ADDR(x) (MSR_MC0_ADDR + (x) * 4)
#define MSR_MC_MISC(x) (MSR_MC0_MISC + (x) * 4)
#define MSR_MC_CTL2(x) (MSR_MC0_CTL2 + (x)) /* If MCG_CAP_CMCI_P */
#define MC_STATUS_MCA_ERROR 0x000000000000ffff
#define MC_STATUS_MODEL_ERROR 0x00000000ffff0000
#define MC_STATUS_OTHER_INFO 0x01ffffff00000000
#define MC_STATUS_COR_COUNT 0x001fffc000000000 /* If MCG_CAP_CMCI_P */
#define MC_STATUS_TES_STATUS 0x0060000000000000 /* If MCG_CAP_TES_P */
#define MC_STATUS_AR 0x0080000000000000 /* If MCG_CAP_TES_P */
#define MC_STATUS_S 0x0100000000000000 /* If MCG_CAP_TES_P */
#define MC_STATUS_PCC 0x0200000000000000
#define MC_STATUS_ADDRV 0x0400000000000000
#define MC_STATUS_MISCV 0x0800000000000000
#define MC_STATUS_EN 0x1000000000000000
#define MC_STATUS_UC 0x2000000000000000
#define MC_STATUS_OVER 0x4000000000000000
#define MC_STATUS_VAL 0x8000000000000000
#define MC_MISC_RA_LSB 0x000000000000003f /* If MCG_CAP_SER_P */
#define MC_MISC_ADDRESS_MODE 0x00000000000001c0 /* If MCG_CAP_SER_P */
#define MC_CTL2_THRESHOLD 0x0000000000007fff
#define MC_CTL2_CMCI_EN 0x0000000040000000
/*
* The following four 3-byte registers control the non-cacheable regions.
* These registers must be written as three separate bytes.
*
* NCRx+0: A31-A24 of starting address
* NCRx+1: A23-A16 of starting address
* NCRx+2: A15-A12 of starting address | NCR_SIZE_xx.
*
* The non-cacheable region's starting address must be aligned to the
* size indicated by the NCR_SIZE_xx field.
*/
#define NCR1 0xc4
#define NCR2 0xc7
#define NCR3 0xca
#define NCR4 0xcd
#define NCR_SIZE_0K 0
#define NCR_SIZE_4K 1
#define NCR_SIZE_8K 2
#define NCR_SIZE_16K 3
#define NCR_SIZE_32K 4
#define NCR_SIZE_64K 5
#define NCR_SIZE_128K 6
#define NCR_SIZE_256K 7
#define NCR_SIZE_512K 8
#define NCR_SIZE_1M 9
#define NCR_SIZE_2M 10
#define NCR_SIZE_4M 11
#define NCR_SIZE_8M 12
#define NCR_SIZE_16M 13
#define NCR_SIZE_32M 14
#define NCR_SIZE_4G 15
/*
* The address region registers are used to specify the location and
* size for the eight address regions.
*
* ARRx + 0: A31-A24 of start address
* ARRx + 1: A23-A16 of start address
* ARRx + 2: A15-A12 of start address | ARR_SIZE_xx
*/
#define ARR0 0xc4
#define ARR1 0xc7
#define ARR2 0xca
#define ARR3 0xcd
#define ARR4 0xd0
#define ARR5 0xd3
#define ARR6 0xd6
#define ARR7 0xd9
#define ARR_SIZE_0K 0
#define ARR_SIZE_4K 1
#define ARR_SIZE_8K 2
#define ARR_SIZE_16K 3
#define ARR_SIZE_32K 4
#define ARR_SIZE_64K 5
#define ARR_SIZE_128K 6
#define ARR_SIZE_256K 7
#define ARR_SIZE_512K 8
#define ARR_SIZE_1M 9
#define ARR_SIZE_2M 10
#define ARR_SIZE_4M 11
#define ARR_SIZE_8M 12
#define ARR_SIZE_16M 13
#define ARR_SIZE_32M 14
#define ARR_SIZE_4G 15
/*
* The region control registers specify the attributes associated with
* the ARRx addres regions.
*/
#define RCR0 0xdc
#define RCR1 0xdd
#define RCR2 0xde
#define RCR3 0xdf
#define RCR4 0xe0
#define RCR5 0xe1
#define RCR6 0xe2
#define RCR7 0xe3
#define RCR_RCD 0x01 /* Disables caching for ARRx (x = 0-6). */
#define RCR_RCE 0x01 /* Enables caching for ARR7. */
#define RCR_WWO 0x02 /* Weak write ordering. */
#define RCR_WL 0x04 /* Weak locking. */
#define RCR_WG 0x08 /* Write gathering. */
#define RCR_WT 0x10 /* Write-through. */
#define RCR_NLB 0x20 /* LBA# pin is not asserted. */
/* AMD Write Allocate Top-Of-Memory and Control Register */
#define AMD_WT_ALLOC_TME 0x40000 /* top-of-memory enable */
#define AMD_WT_ALLOC_PRE 0x20000 /* programmable range enable */
#define AMD_WT_ALLOC_FRE 0x10000 /* fixed (A0000-FFFFF) range enable */
/* AMD64 MSR's */
#define MSR_EFER 0xc0000080 /* extended features */
#define MSR_STAR 0xc0000081 /* legacy mode SYSCALL target/cs/ss */
#define MSR_LSTAR 0xc0000082 /* long mode SYSCALL target rip */
#define MSR_CSTAR 0xc0000083 /* compat mode SYSCALL target rip */
#define MSR_SF_MASK 0xc0000084 /* syscall flags mask */
#define MSR_FSBASE 0xc0000100 /* base address of the %fs "segment" */
#define MSR_GSBASE 0xc0000101 /* base address of the %gs "segment" */
#define MSR_KGSBASE 0xc0000102 /* base address of the kernel %gs */
#define MSR_PERFEVSEL0 0xc0010000
#define MSR_PERFEVSEL1 0xc0010001
#define MSR_PERFEVSEL2 0xc0010002
#define MSR_PERFEVSEL3 0xc0010003
#define MSR_K7_PERFCTR0 0xc0010004
#define MSR_K7_PERFCTR1 0xc0010005
#define MSR_K7_PERFCTR2 0xc0010006
#define MSR_K7_PERFCTR3 0xc0010007
#define MSR_SYSCFG 0xc0010010
#define MSR_HWCR 0xc0010015
#define MSR_IORRBASE0 0xc0010016
#define MSR_IORRMASK0 0xc0010017
#define MSR_IORRBASE1 0xc0010018
#define MSR_IORRMASK1 0xc0010019
#define MSR_TOP_MEM 0xc001001a /* boundary for ram below 4G */
#define MSR_TOP_MEM2 0xc001001d /* boundary for ram above 4G */
#define MSR_NB_CFG1 0xc001001f /* NB configuration 1 */
#define MSR_P_STATE_LIMIT 0xc0010061 /* P-state Current Limit Register */
#define MSR_P_STATE_CONTROL 0xc0010062 /* P-state Control Register */
#define MSR_P_STATE_STATUS 0xc0010063 /* P-state Status Register */
#define MSR_P_STATE_CONFIG(n) (0xc0010064 + (n)) /* P-state Config */
#define MSR_SMM_ADDR 0xc0010112 /* SMM TSEG base address */
#define MSR_SMM_MASK 0xc0010113 /* SMM TSEG address mask */
#define MSR_IC_CFG 0xc0011021 /* Instruction Cache Configuration */
#define MSR_K8_UCODE_UPDATE 0xc0010020 /* update microcode */
#define MSR_MC0_CTL_MASK 0xc0010044
#define MSR_VM_CR 0xc0010114 /* SVM: feature control */
#define MSR_VM_HSAVE_PA 0xc0010117 /* SVM: host save area address */
/* MSR_VM_CR related */
#define VM_CR_SVMDIS 0x10 /* SVM: disabled by BIOS */
/* VIA ACE crypto featureset: for via_feature_rng */
#define VIA_HAS_RNG 1 /* cpu has RNG */
/* VIA ACE crypto featureset: for via_feature_xcrypt */
#define VIA_HAS_AES 1 /* cpu has AES */
#define VIA_HAS_SHA 2 /* cpu has SHA1 & SHA256 */
#define VIA_HAS_MM 4 /* cpu has RSA instructions */
#define VIA_HAS_AESCTR 8 /* cpu has AES-CTR instructions */
/* Centaur Extended Feature flags */
#define VIA_CPUID_HAS_RNG 0x000004
#define VIA_CPUID_DO_RNG 0x000008
#define VIA_CPUID_HAS_ACE 0x000040
#define VIA_CPUID_DO_ACE 0x000080
#define VIA_CPUID_HAS_ACE2 0x000100
#define VIA_CPUID_DO_ACE2 0x000200
#define VIA_CPUID_HAS_PHE 0x000400
#define VIA_CPUID_DO_PHE 0x000800
#define VIA_CPUID_HAS_PMM 0x001000
#define VIA_CPUID_DO_PMM 0x002000
/* VIA ACE xcrypt-* instruction context control options */
#define VIA_CRYPT_CWLO_ROUND_M 0x0000000f
#define VIA_CRYPT_CWLO_ALG_M 0x00000070
#define VIA_CRYPT_CWLO_ALG_AES 0x00000000
#define VIA_CRYPT_CWLO_KEYGEN_M 0x00000080
#define VIA_CRYPT_CWLO_KEYGEN_HW 0x00000000
#define VIA_CRYPT_CWLO_KEYGEN_SW 0x00000080
#define VIA_CRYPT_CWLO_NORMAL 0x00000000
#define VIA_CRYPT_CWLO_INTERMEDIATE 0x00000100
#define VIA_CRYPT_CWLO_ENCRYPT 0x00000000
#define VIA_CRYPT_CWLO_DECRYPT 0x00000200
#define VIA_CRYPT_CWLO_KEY128 0x0000000a /* 128bit, 10 rds */
#define VIA_CRYPT_CWLO_KEY192 0x0000040c /* 192bit, 12 rds */
#define VIA_CRYPT_CWLO_KEY256 0x0000080e /* 256bit, 15 rds */

View File

@ -0,0 +1,47 @@
/*-
* Copyright (C) 2005 TAKAHASHI Yoshihiro. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
/*
* The outputs of the three timers are connected as follows:
*
* timer 0 -> irq 0
* timer 1 -> dma chan 0 (for dram refresh)
* timer 2 -> speaker (via keyboard controller)
*
* Timer 0 is used to call hardclock.
* Timer 2 is used to generate console beeps.
*/
#pragma once
#include <xhyve/support/i8253reg.h>
#define IO_TIMER1 0x40 /* 8253 Timer #1 */
#define TIMER_CNTR0 (IO_TIMER1 + TIMER_REG_CNTR0)
#define TIMER_CNTR1 (IO_TIMER1 + TIMER_REG_CNTR1)
#define TIMER_CNTR2 (IO_TIMER1 + TIMER_REG_CNTR2)
#define TIMER_MODE (IO_TIMER1 + TIMER_REG_MODE)

View File

@ -0,0 +1,746 @@
/* $NetBSD: tree.h,v 1.8 2004/03/28 19:38:30 provos Exp $ */
/* $OpenBSD: tree.h,v 1.7 2002/10/17 21:51:54 art Exp $ */
/* $FreeBSD: src/sys/sys/tree.h,v 1.7 2007/12/28 07:03:26 jasone Exp $ */
/*-
* Copyright 2002 Niels Provos <provos@citi.umich.edu>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
/*
* This file defines data structures for different types of trees:
* splay trees and red-black trees.
*
* A splay tree is a self-organizing data structure. Every operation
* on the tree causes a splay to happen. The splay moves the requested
* node to the root of the tree and partly rebalances it.
*
* This has the benefit that request locality causes faster lookups as
* the requested nodes move to the top of the tree. On the other hand,
* every lookup causes memory writes.
*
* The Balance Theorem bounds the total access time for m operations
* and n inserts on an initially empty tree as O((m + n)lg n). The
* amortized cost for a sequence of m accesses to a splay tree is O(lg n);
*
* A red-black tree is a binary search tree with the node color as an
* extra attribute. It fulfills a set of conditions:
* - every search path from the root to a leaf consists of the
* same number of black nodes,
* - each red node (except for the root) has a black parent,
* - each leaf node is black.
*
* Every operation on a red-black tree is bounded as O(lg n).
* The maximum height of a red-black tree is 2lg (n+1).
*/
#define SPLAY_HEAD(name, type) \
struct name { \
struct type *sph_root; /* root of the tree */ \
}
#define SPLAY_INITIALIZER(root) \
{ NULL }
#define SPLAY_INIT(root) do { \
(root)->sph_root = NULL; \
} while (/*CONSTCOND*/ 0)
#define SPLAY_ENTRY(type) \
struct { \
struct type *spe_left; /* left element */ \
struct type *spe_right; /* right element */ \
}
#define SPLAY_LEFT(elm, field) (elm)->field.spe_left
#define SPLAY_RIGHT(elm, field) (elm)->field.spe_right
#define SPLAY_ROOT(head) (head)->sph_root
#define SPLAY_EMPTY(head) (SPLAY_ROOT(head) == NULL)
/* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */
#define SPLAY_ROTATE_RIGHT(head, tmp, field) do { \
SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \
SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
(head)->sph_root = tmp; \
} while (/*CONSTCOND*/ 0)
#define SPLAY_ROTATE_LEFT(head, tmp, field) do { \
SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \
SPLAY_LEFT(tmp, field) = (head)->sph_root; \
(head)->sph_root = tmp; \
} while (/*CONSTCOND*/ 0)
#define SPLAY_LINKLEFT(head, tmp, field) do { \
SPLAY_LEFT(tmp, field) = (head)->sph_root; \
tmp = (head)->sph_root; \
(head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \
} while (/*CONSTCOND*/ 0)
#define SPLAY_LINKRIGHT(head, tmp, field) do { \
SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
tmp = (head)->sph_root; \
(head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \
} while (/*CONSTCOND*/ 0)
#define SPLAY_ASSEMBLE(head, node, left, right, field) do { \
SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \
SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\
SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \
SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \
} while (/*CONSTCOND*/ 0)
/* Generates prototypes and inline functions */
#define SPLAY_PROTOTYPE(name, type, field, cmp) \
void name##_SPLAY(struct name *, struct type *); \
void name##_SPLAY_MINMAX(struct name *, int); \
struct type *name##_SPLAY_INSERT(struct name *, struct type *); \
struct type *name##_SPLAY_REMOVE(struct name *, struct type *); \
\
/* Finds the node with the same key as elm */ \
static __inline struct type * \
name##_SPLAY_FIND(struct name *head, struct type *elm) \
{ \
if (SPLAY_EMPTY(head)) \
return(NULL); \
name##_SPLAY(head, elm); \
if ((cmp)(elm, (head)->sph_root) == 0) \
return (head->sph_root); \
return (NULL); \
} \
\
static __inline struct type * \
name##_SPLAY_NEXT(struct name *head, struct type *elm) \
{ \
name##_SPLAY(head, elm); \
if (SPLAY_RIGHT(elm, field) != NULL) { \
elm = SPLAY_RIGHT(elm, field); \
while (SPLAY_LEFT(elm, field) != NULL) { \
elm = SPLAY_LEFT(elm, field); \
} \
} else \
elm = NULL; \
return (elm); \
} \
\
static __inline struct type * \
name##_SPLAY_MIN_MAX(struct name *head, int val) \
{ \
name##_SPLAY_MINMAX(head, val); \
return (SPLAY_ROOT(head)); \
}
/* Main splay operation.
* Moves node close to the key of elm to top
*/
#define SPLAY_GENERATE(name, type, field, cmp) \
struct type * \
name##_SPLAY_INSERT(struct name *head, struct type *elm) \
{ \
if (SPLAY_EMPTY(head)) { \
SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL; \
} else { \
int __comp; \
name##_SPLAY(head, elm); \
__comp = (cmp)(elm, (head)->sph_root); \
if(__comp < 0) { \
SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\
SPLAY_RIGHT(elm, field) = (head)->sph_root; \
SPLAY_LEFT((head)->sph_root, field) = NULL; \
} else if (__comp > 0) { \
SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\
SPLAY_LEFT(elm, field) = (head)->sph_root; \
SPLAY_RIGHT((head)->sph_root, field) = NULL; \
} else \
return ((head)->sph_root); \
} \
(head)->sph_root = (elm); \
return (NULL); \
} \
\
struct type * \
name##_SPLAY_REMOVE(struct name *head, struct type *elm) \
{ \
struct type *__tmp; \
if (SPLAY_EMPTY(head)) \
return (NULL); \
name##_SPLAY(head, elm); \
if ((cmp)(elm, (head)->sph_root) == 0) { \
if (SPLAY_LEFT((head)->sph_root, field) == NULL) { \
(head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\
} else { \
__tmp = SPLAY_RIGHT((head)->sph_root, field); \
(head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\
name##_SPLAY(head, elm); \
SPLAY_RIGHT((head)->sph_root, field) = __tmp; \
} \
return (elm); \
} \
return (NULL); \
} \
\
void \
name##_SPLAY(struct name *head, struct type *elm) \
{ \
struct type __node, *__left, *__right, *__tmp; \
int __comp; \
\
SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
__left = __right = &__node; \
\
while ((__comp = (cmp)(elm, (head)->sph_root)) != 0) { \
if (__comp < 0) { \
__tmp = SPLAY_LEFT((head)->sph_root, field); \
if (__tmp == NULL) \
break; \
if ((cmp)(elm, __tmp) < 0){ \
SPLAY_ROTATE_RIGHT(head, __tmp, field); \
if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
break; \
} \
SPLAY_LINKLEFT(head, __right, field); \
} else if (__comp > 0) { \
__tmp = SPLAY_RIGHT((head)->sph_root, field); \
if (__tmp == NULL) \
break; \
if ((cmp)(elm, __tmp) > 0){ \
SPLAY_ROTATE_LEFT(head, __tmp, field); \
if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
break; \
} \
SPLAY_LINKRIGHT(head, __left, field); \
} \
} \
SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
} \
\
/* Splay with either the minimum or the maximum element \
* Used to find minimum or maximum element in tree. \
*/ \
void name##_SPLAY_MINMAX(struct name *head, int __comp) \
{ \
struct type __node, *__left, *__right, *__tmp; \
\
SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
__left = __right = &__node; \
\
while (1) { \
if (__comp < 0) { \
__tmp = SPLAY_LEFT((head)->sph_root, field); \
if (__tmp == NULL) \
break; \
if (__comp < 0){ \
SPLAY_ROTATE_RIGHT(head, __tmp, field); \
if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
break; \
} \
SPLAY_LINKLEFT(head, __right, field); \
} else if (__comp > 0) { \
__tmp = SPLAY_RIGHT((head)->sph_root, field); \
if (__tmp == NULL) \
break; \
if (__comp > 0) { \
SPLAY_ROTATE_LEFT(head, __tmp, field); \
if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
break; \
} \
SPLAY_LINKRIGHT(head, __left, field); \
} \
} \
SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
}
#define SPLAY_NEGINF -1
#define SPLAY_INF 1
#define SPLAY_INSERT(name, x, y) name##_SPLAY_INSERT(x, y)
#define SPLAY_REMOVE(name, x, y) name##_SPLAY_REMOVE(x, y)
#define SPLAY_FIND(name, x, y) name##_SPLAY_FIND(x, y)
#define SPLAY_NEXT(name, x, y) name##_SPLAY_NEXT(x, y)
#define SPLAY_MIN(name, x) (SPLAY_EMPTY(x) ? NULL \
: name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF))
#define SPLAY_MAX(name, x) (SPLAY_EMPTY(x) ? NULL \
: name##_SPLAY_MIN_MAX(x, SPLAY_INF))
#define SPLAY_FOREACH(x, name, head) \
for ((x) = SPLAY_MIN(name, head); \
(x) != NULL; \
(x) = SPLAY_NEXT(name, head, x))
/* Macros that define a red-black tree */
#define RB_HEAD(name, type) \
struct name { \
struct type *rbh_root; /* root of the tree */ \
}
#define RB_INITIALIZER(root) \
{ NULL }
#define RB_INIT(root) do { \
(root)->rbh_root = NULL; \
} while (/*CONSTCOND*/ 0)
/*
* Undef for Linux
*/
#undef RB_BLACK
#undef RB_RED
#undef RB_ROOT
#define RB_BLACK 0
#define RB_RED 1
#define RB_ENTRY(type) \
struct { \
struct type *rbe_left; /* left element */ \
struct type *rbe_right; /* right element */ \
struct type *rbe_parent; /* parent element */ \
int rbe_color; /* node color */ \
}
#define RB_LEFT(elm, field) (elm)->field.rbe_left
#define RB_RIGHT(elm, field) (elm)->field.rbe_right
#define RB_PARENT(elm, field) (elm)->field.rbe_parent
#define RB_COLOR(elm, field) (elm)->field.rbe_color
#define RB_ROOT(head) (head)->rbh_root
#define RB_EMPTY(head) (RB_ROOT(head) == NULL)
#define RB_SET(elm, parent, field) do { \
RB_PARENT(elm, field) = parent; \
RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \
RB_COLOR(elm, field) = RB_RED; \
} while (/*CONSTCOND*/ 0)
#define RB_SET_BLACKRED(black, red, field) do { \
RB_COLOR(black, field) = RB_BLACK; \
RB_COLOR(red, field) = RB_RED; \
} while (/*CONSTCOND*/ 0)
#ifndef RB_AUGMENT
#define RB_AUGMENT(x) do {} while (0)
#endif
#define RB_ROTATE_LEFT(head, elm, tmp, field) do { \
(tmp) = RB_RIGHT(elm, field); \
if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field)) != NULL) { \
RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \
} \
RB_AUGMENT(elm); \
if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \
if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
else \
RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
} else \
(head)->rbh_root = (tmp); \
RB_LEFT(tmp, field) = (elm); \
RB_PARENT(elm, field) = (tmp); \
RB_AUGMENT(tmp); \
if ((RB_PARENT(tmp, field))) \
RB_AUGMENT(RB_PARENT(tmp, field)); \
} while (/*CONSTCOND*/ 0)
#define RB_ROTATE_RIGHT(head, elm, tmp, field) do { \
(tmp) = RB_LEFT(elm, field); \
if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field)) != NULL) { \
RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \
} \
RB_AUGMENT(elm); \
if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \
if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
else \
RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
} else \
(head)->rbh_root = (tmp); \
RB_RIGHT(tmp, field) = (elm); \
RB_PARENT(elm, field) = (tmp); \
RB_AUGMENT(tmp); \
if ((RB_PARENT(tmp, field))) \
RB_AUGMENT(RB_PARENT(tmp, field)); \
} while (/*CONSTCOND*/ 0)
/* Generates prototypes and inline functions */
#define RB_PROTOTYPE(name, type, field, cmp) \
RB_PROTOTYPE_INTERNAL(name, type, field, cmp,)
#define RB_PROTOTYPE_STATIC(name, type, field, cmp) \
RB_PROTOTYPE_INTERNAL(name, type, field, cmp, __unused static)
#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr) \
attr void name##_RB_INSERT_COLOR(struct name *, struct type *); \
attr void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *); \
attr struct type *name##_RB_REMOVE(struct name *, struct type *); \
attr struct type *name##_RB_INSERT(struct name *, struct type *); \
attr struct type *name##_RB_FIND(struct name *, struct type *); \
attr struct type *name##_RB_NFIND(struct name *, struct type *); \
attr struct type *name##_RB_NEXT(struct type *); \
attr struct type *name##_RB_PREV(struct type *); \
attr struct type *name##_RB_MINMAX(struct name *, int) \
/* Main rb operation.
* Moves node close to the key of elm to top
*/
#define RB_GENERATE(name, type, field, cmp) \
RB_GENERATE_INTERNAL(name, type, field, cmp,)
#define RB_GENERATE_STATIC(name, type, field, cmp) \
RB_GENERATE_INTERNAL(name, type, field, cmp, __unused static)
#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr) \
attr void \
name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \
{ \
struct type *parent, *gparent, *tmp; \
while ((parent = RB_PARENT(elm, field)) != NULL && \
RB_COLOR(parent, field) == RB_RED) { \
gparent = RB_PARENT(parent, field); \
if (parent == RB_LEFT(gparent, field)) { \
tmp = RB_RIGHT(gparent, field); \
if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
RB_COLOR(tmp, field) = RB_BLACK; \
RB_SET_BLACKRED(parent, gparent, field);\
elm = gparent; \
continue; \
} \
if (RB_RIGHT(parent, field) == elm) { \
RB_ROTATE_LEFT(head, parent, tmp, field);\
tmp = parent; \
parent = elm; \
elm = tmp; \
} \
RB_SET_BLACKRED(parent, gparent, field); \
RB_ROTATE_RIGHT(head, gparent, tmp, field); \
} else { \
tmp = RB_LEFT(gparent, field); \
if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
RB_COLOR(tmp, field) = RB_BLACK; \
RB_SET_BLACKRED(parent, gparent, field);\
elm = gparent; \
continue; \
} \
if (RB_LEFT(parent, field) == elm) { \
RB_ROTATE_RIGHT(head, parent, tmp, field);\
tmp = parent; \
parent = elm; \
elm = tmp; \
} \
RB_SET_BLACKRED(parent, gparent, field); \
RB_ROTATE_LEFT(head, gparent, tmp, field); \
} \
} \
RB_COLOR(head->rbh_root, field) = RB_BLACK; \
} \
\
attr void \
name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \
{ \
struct type *tmp; \
while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && \
elm != RB_ROOT(head)) { \
if (RB_LEFT(parent, field) == elm) { \
tmp = RB_RIGHT(parent, field); \
if (RB_COLOR(tmp, field) == RB_RED) { \
RB_SET_BLACKRED(tmp, parent, field); \
RB_ROTATE_LEFT(head, parent, tmp, field);\
tmp = RB_RIGHT(parent, field); \
} \
if ((RB_LEFT(tmp, field) == NULL || \
RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
(RB_RIGHT(tmp, field) == NULL || \
RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
RB_COLOR(tmp, field) = RB_RED; \
elm = parent; \
parent = RB_PARENT(elm, field); \
} else { \
if (RB_RIGHT(tmp, field) == NULL || \
RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\
struct type *oleft; \
if ((oleft = RB_LEFT(tmp, field)) \
!= NULL) \
RB_COLOR(oleft, field) = RB_BLACK;\
RB_COLOR(tmp, field) = RB_RED; \
RB_ROTATE_RIGHT(head, tmp, oleft, field);\
tmp = RB_RIGHT(parent, field); \
} \
RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
RB_COLOR(parent, field) = RB_BLACK; \
if (RB_RIGHT(tmp, field)) \
RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\
RB_ROTATE_LEFT(head, parent, tmp, field);\
elm = RB_ROOT(head); \
break; \
} \
} else { \
tmp = RB_LEFT(parent, field); \
if (RB_COLOR(tmp, field) == RB_RED) { \
RB_SET_BLACKRED(tmp, parent, field); \
RB_ROTATE_RIGHT(head, parent, tmp, field);\
tmp = RB_LEFT(parent, field); \
} \
if ((RB_LEFT(tmp, field) == NULL || \
RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
(RB_RIGHT(tmp, field) == NULL || \
RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
RB_COLOR(tmp, field) = RB_RED; \
elm = parent; \
parent = RB_PARENT(elm, field); \
} else { \
if (RB_LEFT(tmp, field) == NULL || \
RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\
struct type *oright; \
if ((oright = RB_RIGHT(tmp, field)) \
!= NULL) \
RB_COLOR(oright, field) = RB_BLACK;\
RB_COLOR(tmp, field) = RB_RED; \
RB_ROTATE_LEFT(head, tmp, oright, field);\
tmp = RB_LEFT(parent, field); \
} \
RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
RB_COLOR(parent, field) = RB_BLACK; \
if (RB_LEFT(tmp, field)) \
RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\
RB_ROTATE_RIGHT(head, parent, tmp, field);\
elm = RB_ROOT(head); \
break; \
} \
} \
} \
if (elm) \
RB_COLOR(elm, field) = RB_BLACK; \
} \
\
attr struct type * \
name##_RB_REMOVE(struct name *head, struct type *elm) \
{ \
struct type *child, *parent, *old = elm; \
int color; \
if (RB_LEFT(elm, field) == NULL) \
child = RB_RIGHT(elm, field); \
else if (RB_RIGHT(elm, field) == NULL) \
child = RB_LEFT(elm, field); \
else { \
struct type *left; \
elm = RB_RIGHT(elm, field); \
while ((left = RB_LEFT(elm, field)) != NULL) \
elm = left; \
child = RB_RIGHT(elm, field); \
parent = RB_PARENT(elm, field); \
color = RB_COLOR(elm, field); \
if (child) \
RB_PARENT(child, field) = parent; \
if (parent) { \
if (RB_LEFT(parent, field) == elm) \
RB_LEFT(parent, field) = child; \
else \
RB_RIGHT(parent, field) = child; \
RB_AUGMENT(parent); \
} else \
RB_ROOT(head) = child; \
if (RB_PARENT(elm, field) == old) \
parent = elm; \
(elm)->field = (old)->field; \
if (RB_PARENT(old, field)) { \
if (RB_LEFT(RB_PARENT(old, field), field) == old)\
RB_LEFT(RB_PARENT(old, field), field) = elm;\
else \
RB_RIGHT(RB_PARENT(old, field), field) = elm;\
RB_AUGMENT(RB_PARENT(old, field)); \
} else \
RB_ROOT(head) = elm; \
RB_PARENT(RB_LEFT(old, field), field) = elm; \
if (RB_RIGHT(old, field)) \
RB_PARENT(RB_RIGHT(old, field), field) = elm; \
if (parent) { \
left = parent; \
do { \
RB_AUGMENT(left); \
} while ((left = RB_PARENT(left, field)) != NULL); \
} \
goto color; \
} \
parent = RB_PARENT(elm, field); \
color = RB_COLOR(elm, field); \
if (child) \
RB_PARENT(child, field) = parent; \
if (parent) { \
if (RB_LEFT(parent, field) == elm) \
RB_LEFT(parent, field) = child; \
else \
RB_RIGHT(parent, field) = child; \
RB_AUGMENT(parent); \
} else \
RB_ROOT(head) = child; \
color: \
if (color == RB_BLACK) \
name##_RB_REMOVE_COLOR(head, parent, child); \
return (old); \
} \
\
/* Inserts a node into the RB tree */ \
attr struct type * \
name##_RB_INSERT(struct name *head, struct type *elm) \
{ \
struct type *tmp; \
struct type *parent = NULL; \
int comp = 0; \
tmp = RB_ROOT(head); \
while (tmp) { \
parent = tmp; \
comp = (cmp)(elm, parent); \
if (comp < 0) \
tmp = RB_LEFT(tmp, field); \
else if (comp > 0) \
tmp = RB_RIGHT(tmp, field); \
else \
return (tmp); \
} \
RB_SET(elm, parent, field); \
if (parent != NULL) { \
if (comp < 0) \
RB_LEFT(parent, field) = elm; \
else \
RB_RIGHT(parent, field) = elm; \
RB_AUGMENT(parent); \
} else \
RB_ROOT(head) = elm; \
name##_RB_INSERT_COLOR(head, elm); \
return (NULL); \
} \
\
/* Finds the node with the same key as elm */ \
attr struct type * \
name##_RB_FIND(struct name *head, struct type *elm) \
{ \
struct type *tmp = RB_ROOT(head); \
int comp; \
while (tmp) { \
comp = cmp(elm, tmp); \
if (comp < 0) \
tmp = RB_LEFT(tmp, field); \
else if (comp > 0) \
tmp = RB_RIGHT(tmp, field); \
else \
return (tmp); \
} \
return (NULL); \
} \
\
/* Finds the first node greater than or equal to the search key */ \
attr struct type * \
name##_RB_NFIND(struct name *head, struct type *elm) \
{ \
struct type *tmp = RB_ROOT(head); \
struct type *res = NULL; \
int comp; \
while (tmp) { \
comp = cmp(elm, tmp); \
if (comp < 0) { \
res = tmp; \
tmp = RB_LEFT(tmp, field); \
} \
else if (comp > 0) \
tmp = RB_RIGHT(tmp, field); \
else \
return (tmp); \
} \
return (res); \
} \
\
/* ARGSUSED */ \
attr struct type * \
name##_RB_NEXT(struct type *elm) \
{ \
if (RB_RIGHT(elm, field)) { \
elm = RB_RIGHT(elm, field); \
while (RB_LEFT(elm, field)) \
elm = RB_LEFT(elm, field); \
} else { \
if (RB_PARENT(elm, field) && \
(elm == RB_LEFT(RB_PARENT(elm, field), field))) \
elm = RB_PARENT(elm, field); \
else { \
while (RB_PARENT(elm, field) && \
(elm == RB_RIGHT(RB_PARENT(elm, field), field)))\
elm = RB_PARENT(elm, field); \
elm = RB_PARENT(elm, field); \
} \
} \
return (elm); \
} \
\
/* ARGSUSED */ \
attr struct type * \
name##_RB_PREV(struct type *elm) \
{ \
if (RB_LEFT(elm, field)) { \
elm = RB_LEFT(elm, field); \
while (RB_RIGHT(elm, field)) \
elm = RB_RIGHT(elm, field); \
} else { \
if (RB_PARENT(elm, field) && \
(elm == RB_RIGHT(RB_PARENT(elm, field), field))) \
elm = RB_PARENT(elm, field); \
else { \
while (RB_PARENT(elm, field) && \
(elm == RB_LEFT(RB_PARENT(elm, field), field)))\
elm = RB_PARENT(elm, field); \
elm = RB_PARENT(elm, field); \
} \
} \
return (elm); \
} \
\
attr struct type * \
name##_RB_MINMAX(struct name *head, int val) \
{ \
struct type *tmp = RB_ROOT(head); \
struct type *parent = NULL; \
while (tmp) { \
parent = tmp; \
if (val < 0) \
tmp = RB_LEFT(tmp, field); \
else \
tmp = RB_RIGHT(tmp, field); \
} \
return (parent); \
}
#define RB_NEGINF -1
#define RB_INF 1
#define RB_INSERT(name, x, y) name##_RB_INSERT(x, y)
#define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y)
#define RB_FIND(name, x, y) name##_RB_FIND(x, y)
#define RB_NFIND(name, x, y) name##_RB_NFIND(x, y)
#define RB_NEXT(name, x, y) name##_RB_NEXT(y)
#define RB_PREV(name, x, y) name##_RB_PREV(y)
#define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF)
#define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF)
#define RB_FOREACH(x, name, head) \
for ((x) = RB_MIN(name, head); \
(x) != NULL; \
(x) = name##_RB_NEXT(x))
#define RB_FOREACH_REVERSE(x, name, head) \
for ((x) = RB_MAX(name, head); \
(x) != NULL; \
(x) = name##_RB_PREV(x))

View File

@ -0,0 +1,150 @@
/*-
* Copyright (c) 2002,2005 Marcel Moolenaar
* Copyright (c) 2002 Hiten Mahesh Pandya
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#define _UUID_NODE_LEN 6
struct uuid {
uint32_t time_low;
uint16_t time_mid;
uint16_t time_hi_and_version;
uint8_t clock_seq_hi_and_reserved;
uint8_t clock_seq_low;
uint8_t node[_UUID_NODE_LEN];
};
typedef struct uuid uuid_internal_t;
/*
* This implementation mostly conforms to the DCE 1.1 specification.
* See Also:
* uuidgen(1), uuidgen(2), uuid(3)
*/
/* Status codes returned by the functions. */
#define uuid_s_ok 0
#define uuid_s_bad_version 1
#define uuid_s_invalid_string_uuid 2
#define uuid_s_no_memory 3
/*
* uuid_create_nil() - create a nil UUID.
* See also:
* http://www.opengroup.org/onlinepubs/009629399/uuid_create_nil.htm
*/
static inline void
uuid_create_nil(uuid_t *u, uint32_t *status)
{
if (status)
*status = uuid_s_ok;
bzero(u, sizeof(*u));
}
static inline void
uuid_enc_le(void *buf, uuid_t *uuid)
{
uuid_internal_t *u = (uuid_internal_t *) ((void *) uuid);
uint8_t *p = buf;
int i;
memcpy(p, &u->time_low, 4);
memcpy(p, &u->time_mid, 2);
memcpy(p, &u->time_hi_and_version, 2);
p[8] = u->clock_seq_hi_and_reserved;
p[9] = u->clock_seq_low;
for (i = 0; i < _UUID_NODE_LEN; i++)
p[10 + i] = u->node[i];
}
/*
* uuid_from_string() - convert a string representation of an UUID into
* a binary representation.
* See also:
* http://www.opengroup.org/onlinepubs/009629399/uuid_from_string.htm
*
* NOTE: The sequence field is in big-endian, while the time fields are in
* native byte order.
*/
static inline void
uuid_from_string(const char *s, uuid_t *uuid, uint32_t *status)
{
uuid_internal_t *u = (uuid_internal_t *) ((void *) uuid);
int n;
/* Short-circuit 2 special cases: NULL pointer and empty string. */
if (s == NULL || *s == '\0') {
uuid_create_nil(((uuid_t *) u), status);
return;
}
/* Assume the worst. */
if (status != NULL)
*status = uuid_s_invalid_string_uuid;
/* The UUID string representation has a fixed length. */
if (strlen(s) != 36)
return;
/*
* We only work with "new" UUIDs. New UUIDs have the form:
* 01234567-89ab-cdef-0123-456789abcdef
* The so called "old" UUIDs, which we don't support, have the form:
* 0123456789ab.cd.ef.01.23.45.67.89.ab
*/
if (s[8] != '-')
return;
n = sscanf(s,
"%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
&u->time_low, &u->time_mid, &u->time_hi_and_version,
&u->clock_seq_hi_and_reserved, &u->clock_seq_low, &u->node[0],
&u->node[1], &u->node[2], &u->node[3], &u->node[4], &u->node[5]);
/* Make sure we have all conversions. */
if (n != 11)
return;
/* We have a successful scan. Check semantics... */
n = u->clock_seq_hi_and_reserved;
if ((n & 0x80) != 0x00 && /* variant 0? */
(n & 0xc0) != 0x80 && /* variant 1? */
(n & 0xe0) != 0xc0) { /* variant 2? */
if (status != NULL)
*status = uuid_s_bad_version;
} else {
if (status != NULL)
*status = uuid_s_ok;
}
}

View File

@ -0,0 +1,42 @@
/*-
* Copyright (c) 2013 Neel Natu <neel@freebsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#define UART_IO_BAR_SIZE 8
struct uart_softc;
typedef void (*uart_intr_func_t)(void *arg);
struct uart_softc *uart_init(uart_intr_func_t intr_assert,
uart_intr_func_t intr_deassert, void *arg);
int uart_legacy_alloc(int unit, int *ioaddr, int *irq);
uint8_t uart_read(struct uart_softc *sc, int offset);
void uart_write(struct uart_softc *sc, int offset, uint8_t value);
int uart_set_backend(struct uart_softc *sc, const char *backend, const char *devname);

View File

@ -0,0 +1,473 @@
/*-
* Copyright (c) 2013 Chris Torek <torek @ torek net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <pthread.h>
/*
* These are derived from several virtio specifications.
*
* Some useful links:
* https://github.com/rustyrussell/virtio-spec
* http://people.redhat.com/pbonzini/virtio-spec.pdf
*/
/*
* A virtual device has zero or more "virtual queues" (virtqueue).
* Each virtqueue uses at least two 4096-byte pages, laid out thus:
*
* +-----------------------------------------------+
* | "desc": <N> descriptors, 16 bytes each |
* | ----------------------------------------- |
* | "avail": 2 uint16; <N> uint16; 1 uint16 |
* | ----------------------------------------- |
* | pad to 4k boundary |
* +-----------------------------------------------+
* | "used": 2 x uint16; <N> elems; 1 uint16 |
* | ----------------------------------------- |
* | pad to 4k boundary |
* +-----------------------------------------------+
*
* The number <N> that appears here is always a power of two and is
* limited to no more than 32768 (as it must fit in a 16-bit field).
* If <N> is sufficiently large, the above will occupy more than
* two pages. In any case, all pages must be physically contiguous
* within the guest's physical address space.
*
* The <N> 16-byte "desc" descriptors consist of a 64-bit guest
* physical address <addr>, a 32-bit length <len>, a 16-bit
* <flags>, and a 16-bit <next> field (all in guest byte order).
*
* There are three flags that may be set :
* NEXT descriptor is chained, so use its "next" field
* WRITE descriptor is for host to write into guest RAM
* (else host is to read from guest RAM)
* INDIRECT descriptor address field is (guest physical)
* address of a linear array of descriptors
*
* Unless INDIRECT is set, <len> is the number of bytes that may
* be read/written from guest physical address <addr>. If
* INDIRECT is set, WRITE is ignored and <len> provides the length
* of the indirect descriptors (and <len> must be a multiple of
* 16). Note that NEXT may still be set in the main descriptor
* pointing to the indirect, and should be set in each indirect
* descriptor that uses the next descriptor (these should generally
* be numbered sequentially). However, INDIRECT must not be set
* in the indirect descriptors. Upon reaching an indirect descriptor
* without a NEXT bit, control returns to the direct descriptors.
*
* Except inside an indirect, each <next> value must be in the
* range [0 .. N) (i.e., the half-open interval). (Inside an
* indirect, each <next> must be in the range [0 .. <len>/16).)
*
* The "avail" data structures reside in the same pages as the
* "desc" structures since both together are used by the device to
* pass information to the hypervisor's virtual driver. These
* begin with a 16-bit <flags> field and 16-bit index <idx>, then
* have <N> 16-bit <ring> values, followed by one final 16-bit
* field <used_event>. The <N> <ring> entries are simply indices
* indices into the descriptor ring (and thus must meet the same
* constraints as each <next> value). However, <idx> is counted
* up from 0 (initially) and simply wraps around after 65535; it
* is taken mod <N> to find the next available entry.
*
* The "used" ring occupies a separate page or pages, and contains
* values written from the virtual driver back to the guest OS.
* This begins with a 16-bit <flags> and 16-bit <idx>, then there
* are <N> "vring_used" elements, followed by a 16-bit <avail_event>.
* The <N> "vring_used" elements consist of a 32-bit <id> and a
* 32-bit <len> (vu_tlen below). The <id> is simply the index of
* the head of a descriptor chain the guest made available
* earlier, and the <len> is the number of bytes actually written,
* e.g., in the case of a network driver that provided a large
* receive buffer but received only a small amount of data.
*
* The two event fields, <used_event> and <avail_event>, in the
* avail and used rings (respectively -- note the reversal!), are
* always provided, but are used only if the virtual device
* negotiates the VIRTIO_RING_F_EVENT_IDX feature during feature
* negotiation. Similarly, both rings provide a flag --
* VRING_AVAIL_F_NO_INTERRUPT and VRING_USED_F_NO_NOTIFY -- in
* their <flags> field, indicating that the guest does not need an
* interrupt, or that the hypervisor driver does not need a
* notify, when descriptors are added to the corresponding ring.
* (These are provided only for interrupt optimization and need
* not be implemented.)
*/
#define VRING_ALIGN 4096
#define VRING_DESC_F_NEXT (1 << 0)
#define VRING_DESC_F_WRITE (1 << 1)
#define VRING_DESC_F_INDIRECT (1 << 2)
struct virtio_desc { /* AKA vring_desc */
uint64_t vd_addr; /* guest physical address */
uint32_t vd_len; /* length of scatter/gather seg */
uint16_t vd_flags; /* VRING_F_DESC_* */
uint16_t vd_next; /* next desc if F_NEXT */
} __packed;
struct virtio_used { /* AKA vring_used_elem */
uint32_t vu_idx; /* head of used descriptor chain */
uint32_t vu_tlen; /* length written-to */
} __packed;
#define VRING_AVAIL_F_NO_INTERRUPT 1
struct vring_avail {
uint16_t va_flags; /* VRING_AVAIL_F_* */
uint16_t va_idx; /* counts to 65535, then cycles */
uint16_t va_ring[]; /* size N, reported in QNUM value */
/* uint16_t va_used_event; -- after N ring entries */
} __packed;
#define VRING_USED_F_NO_NOTIFY 1
struct vring_used {
uint16_t vu_flags; /* VRING_USED_F_* */
uint16_t vu_idx; /* counts to 65535, then cycles */
struct virtio_used vu_ring[]; /* size N */
/* uint16_t vu_avail_event; -- after N ring entries */
} __packed;
/*
* The address of any given virtual queue is determined by a single
* Page Frame Number register. The guest writes the PFN into the
* PCI config space. However, a device that has two or more
* virtqueues can have a different PFN, and size, for each queue.
* The number of queues is determinable via the PCI config space
* VTCFG_R_QSEL register. Writes to QSEL select the queue: 0 means
* queue #0, 1 means queue#1, etc. Once a queue is selected, the
* remaining PFN and QNUM registers refer to that queue.
*
* QNUM is a read-only register containing a nonzero power of two
* that indicates the (hypervisor's) queue size. Or, if reading it
* produces zero, the hypervisor does not have a corresponding
* queue. (The number of possible queues depends on the virtual
* device. The block device has just one; the network device
* provides either two -- 0 = receive, 1 = transmit -- or three,
* with 2 = control.)
*
* PFN is a read/write register giving the physical page address of
* the virtqueue in guest memory (the guest must allocate enough space
* based on the hypervisor's provided QNUM).
*
* QNOTIFY is effectively write-only: when the guest writes a queue
* number to the register, the hypervisor should scan the specified
* virtqueue. (Reading QNOTIFY currently always gets 0).
*/
/*
* PFN register shift amount
*/
#define VRING_PFN 12
/*
* Virtio device types
*
* XXX Should really be merged with <dev/virtio/virtio.h> defines
*/
#define VIRTIO_TYPE_NET 1
#define VIRTIO_TYPE_BLOCK 2
#define VIRTIO_TYPE_CONSOLE 3
#define VIRTIO_TYPE_ENTROPY 4
#define VIRTIO_TYPE_BALLOON 5
#define VIRTIO_TYPE_IOMEMORY 6
#define VIRTIO_TYPE_RPMSG 7
#define VIRTIO_TYPE_SCSI 8
#define VIRTIO_TYPE_9P 9
#define VIRTIO_TYPE_SOCK 19
/* experimental IDs start at 65535 and work down */
/*
* PCI vendor/device IDs
*/
#define VIRTIO_VENDOR 0x1AF4
#define VIRTIO_DEV_NET 0x1000
#define VIRTIO_DEV_BLOCK 0x1001
#define VIRTIO_DEV_RANDOM 0x1002
#define VIRTIO_DEV_9P 0x1009
#define VIRTIO_DEV_SOCK 0x103f /* In the legacy range. */
/*
* PCI config space constants.
*
* If MSI-X is enabled, the ISR register is generally not used,
* and the configuration vector and queue vector appear at offsets
* 20 and 22 with the remaining configuration registers at 24.
* If MSI-X is not enabled, those two registers disappear and
* the remaining configuration registers start at offset 20.
*/
#define VTCFG_R_HOSTCAP 0
#define VTCFG_R_GUESTCAP 4
#define VTCFG_R_PFN 8
#define VTCFG_R_QNUM 12
#define VTCFG_R_QSEL 14
#define VTCFG_R_QNOTIFY 16
#define VTCFG_R_STATUS 18
#define VTCFG_R_ISR 19
#define VTCFG_R_CFGVEC 20
#define VTCFG_R_QVEC 22
#define VTCFG_R_CFG0 20 /* No MSI-X */
#define VTCFG_R_CFG1 24 /* With MSI-X */
#define VTCFG_R_MSIX 20
/*
* Bits in VTCFG_R_STATUS. Guests need not actually set any of these,
* but a guest writing 0 to this register means "please reset".
*/
#define VTCFG_STATUS_ACK 0x01 /* guest OS has acknowledged dev */
#define VTCFG_STATUS_DRIVER 0x02 /* guest OS driver is loaded */
#define VTCFG_STATUS_DRIVER_OK 0x04 /* guest OS driver ready */
#define VTCFG_STATUS_FAILED 0x80 /* guest has given up on this dev */
/*
* Bits in VTCFG_R_ISR. These apply only if not using MSI-X.
*
* (We don't [yet?] ever use CONF_CHANGED.)
*/
#define VTCFG_ISR_QUEUES 0x01 /* re-scan queues */
#define VTCFG_ISR_CONF_CHANGED 0x80 /* configuration changed */
#define VIRTIO_MSI_NO_VECTOR 0xFFFF
/*
* Feature flags.
* Note: bits 0 through 23 are reserved to each device type.
*/
#define VIRTIO_F_NOTIFY_ON_EMPTY (1 << 24)
#define VIRTIO_RING_F_INDIRECT_DESC (1 << 28)
#define VIRTIO_RING_F_EVENT_IDX (1 << 29)
/* From section 2.3, "Virtqueue Configuration", of the virtio specification */
static inline size_t
vring_size(u_int qsz)
{
size_t size;
/* constant 3 below = va_flags, va_idx, va_used_event */
size = sizeof(struct virtio_desc) * qsz + sizeof(uint16_t) * (3 + qsz);
size = roundup2(size, ((size_t) VRING_ALIGN));
/* constant 3 below = vu_flags, vu_idx, vu_avail_event */
size += sizeof(uint16_t) * 3 + sizeof(struct virtio_used) * qsz;
size = roundup2(size, ((size_t) VRING_ALIGN));
return (size);
}
struct pci_devinst;
struct vqueue_info;
/*
* A virtual device, with some number (possibly 0) of virtual
* queues and some size (possibly 0) of configuration-space
* registers private to the device. The virtio_softc should come
* at the front of each "derived class", so that a pointer to the
* virtio_softc is also a pointer to the more specific, derived-
* from-virtio driver's softc.
*
* Note: inside each hypervisor virtio driver, changes to these
* data structures must be locked against other threads, if any.
* Except for PCI config space register read/write, we assume each
* driver does the required locking, but we need a pointer to the
* lock (if there is one) for PCI config space read/write ops.
*
* When the guest reads or writes the device's config space, the
* generic layer checks for operations on the special registers
* described above. If the offset of the register(s) being read
* or written is past the CFG area (CFG0 or CFG1), the request is
* passed on to the virtual device, after subtracting off the
* generic-layer size. (So, drivers can just use the offset as
* an offset into "struct config", for instance.)
*
* (The virtio layer also makes sure that the read or write is to/
* from a "good" config offset, hence vc_cfgsize, and on BAR #0.
* However, the driver must verify the read or write size and offset
* and that no one is writing a readonly register.)
*
* The BROKED flag ("this thing done gone and broked") is for future
* use.
*/
#define VIRTIO_USE_MSIX 0x01
#define VIRTIO_EVENT_IDX 0x02 /* use the event-index values */
#define VIRTIO_BROKED 0x08 /* ??? */
struct virtio_softc {
struct virtio_consts *vs_vc; /* constants (see below) */
int vs_flags; /* VIRTIO_* flags from above */
pthread_mutex_t *vs_mtx; /* POSIX mutex, if any */
struct pci_devinst *vs_pi; /* PCI device instance */
uint32_t vs_negotiated_caps; /* negotiated capabilities */
struct vqueue_info *vs_queues; /* one per vc_nvq */
int vs_curq; /* current queue */
uint8_t vs_status; /* value from last status write */
uint8_t vs_isr; /* ISR flags, if not MSI-X */
uint16_t vs_msix_cfg_idx; /* MSI-X vector for config event */
};
#define VS_LOCK(vs) \
do { \
if (vs->vs_mtx) \
pthread_mutex_lock(vs->vs_mtx); \
} while (0)
#define VS_UNLOCK(vs) \
do { \
if (vs->vs_mtx) \
pthread_mutex_unlock(vs->vs_mtx); \
} while (0)
struct virtio_consts {
/* name of driver (for diagnostics) */
const char *vc_name;
/* number of virtual queues */
int vc_nvq;
/* size of dev-specific config regs */
size_t vc_cfgsize;
/* called on virtual device reset */
void (*vc_reset)(void *);
/* called on QNOTIFY if no VQ notify */
void (*vc_qnotify)(void *, struct vqueue_info *);
/* called to read config regs */
int (*vc_cfgread)(void *, int, int, uint32_t *);
/* called to write config regs */
int (*vc_cfgwrite)(void *, int, int, uint32_t);
/* called to apply negotiated features */
void (*vc_apply_features)(void *, uint64_t);
/* hypervisor-provided capabilities */
uint64_t vc_hv_caps;
};
/*
* Data structure allocated (statically) per virtual queue.
*
* Drivers may change vq_qsize after a reset. When the guest OS
* requests a device reset, the hypervisor first calls
* vs->vs_vc->vc_reset(); then the data structure below is
* reinitialized (for each virtqueue: vs->vs_vc->vc_nvq).
*
* The remaining fields should only be fussed-with by the generic
* code.
*
* Note: the addresses of vq_desc, vq_avail, and vq_used are all
* computable from each other, but it's a lot simpler if we just
* keep a pointer to each one. The event indices are similarly
* (but more easily) computable, and this time we'll compute them:
* they're just XX_ring[N].
*/
#define VQ_ALLOC 0x01 /* set once we have a pfn */
#define VQ_BROKED 0x02 /* ??? */
struct vqueue_info {
/* size of this queue (a power of 2) */
uint16_t vq_qsize;
/* called instead of vc_notify, if not NULL */
void (*vq_notify)(void *, struct vqueue_info *);
/* backpointer to softc */
struct virtio_softc *vq_vs;
/* we're the num'th queue in the softc */
uint16_t vq_num;
/* flags (see above) */
uint16_t vq_flags;
/* a recent value of vq_avail->va_idx */
uint16_t vq_last_avail;
/* saved vq_used->vu_idx; see vq_endchains */
uint16_t vq_save_used;
/* MSI-X index, or VIRTIO_MSI_NO_VECTOR */
uint16_t vq_msix_idx;
/* PFN of virt queue (not shifted!) */
uint32_t vq_pfn;
/* descriptor array */
volatile struct virtio_desc *vq_desc;
/* the "avail" ring */
volatile struct vring_avail *vq_avail;
/* the "used" ring */
volatile struct vring_used *vq_used;
};
/* as noted above, these are sort of backwards, name-wise */
#define VQ_AVAIL_EVENT_IDX(vq) \
(*(volatile uint16_t *)&(vq)->vq_used->vu_ring[(vq)->vq_qsize])
#define VQ_USED_EVENT_IDX(vq) \
((vq)->vq_avail->va_ring[(vq)->vq_qsize])
/*
* Is this ring ready for I/O?
*/
static inline int
vq_ring_ready(struct vqueue_info *vq)
{
return (vq->vq_flags & VQ_ALLOC);
}
/*
* Are there "available" descriptors? (This does not count
* how many, just returns True if there are some.)
*/
static inline int
vq_has_descs(struct vqueue_info *vq)
{
return (vq_ring_ready(vq) && vq->vq_last_avail !=
vq->vq_avail->va_idx);
}
/*
* Deliver an interrupt to guest on the given virtual queue
* (if possible, or a generic MSI interrupt if not using MSI-X).
*/
static inline void
vq_interrupt(struct virtio_softc *vs, struct vqueue_info *vq)
{
if (pci_msix_enabled(vs->vs_pi))
pci_generate_msix(vs->vs_pi, vq->vq_msix_idx);
else {
VS_LOCK(vs);
vs->vs_isr |= VTCFG_ISR_QUEUES;
pci_generate_msi(vs->vs_pi, 0);
pci_lintr_assert(vs->vs_pi);
VS_UNLOCK(vs);
}
}
struct iovec;
void vi_softc_linkup(struct virtio_softc *vs, struct virtio_consts *vc,
void *dev_softc, struct pci_devinst *pi, struct vqueue_info *queues);
int vi_intr_init(struct virtio_softc *vs, int barnum, int use_msix);
void vi_reset_dev(struct virtio_softc *);
void vi_set_io_bar(struct virtio_softc *, int);
int vq_getchain(struct vqueue_info *vq, uint16_t *pidx, struct iovec *iov,
int n_iov, uint16_t *flags);
void vq_retchain(struct vqueue_info *vq);
void vq_relchain(struct vqueue_info *vq, uint16_t idx, uint32_t iolen);
void vq_endchains(struct vqueue_info *vq, int used_all_avail);
uint64_t vi_pci_read(int vcpu, struct pci_devinst *pi, int baridx,
uint64_t offset, int size);
void vi_pci_write(int vcpu, struct pci_devinst *pi, int baridx, uint64_t offset,
int size, uint64_t value);

View File

@ -0,0 +1,386 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <Hypervisor/hv.h>
#include <Hypervisor/hv_vmx.h>
#include <xhyve/vmm/vmm.h>
int vmcs_getreg(int vcpuid, int ident, uint64_t *rv);
int vmcs_setreg(int vcpuid, int ident, uint64_t val);
int vmcs_getdesc(int vcpuid, int ident, struct seg_desc *desc);
int vmcs_setdesc(int vcpuid, int ident, struct seg_desc *desc);
static __inline uint64_t
vmcs_read(int vcpuid, uint32_t encoding)
{
uint64_t val;
hv_vmx_vcpu_read_vmcs(((hv_vcpuid_t) vcpuid), encoding, &val);
return (val);
}
static __inline void
vmcs_write(int vcpuid, uint32_t encoding, uint64_t val)
{
if (encoding == 0x00004002) {
if (val == 0x0000000000000004) {
abort();
}
}
hv_vmx_vcpu_write_vmcs(((hv_vcpuid_t) vcpuid), encoding, val);
}
#define vmexit_instruction_length(vcpuid) \
vmcs_read(vcpuid, VMCS_EXIT_INSTRUCTION_LENGTH)
#define vmcs_guest_rip(vcpuid) \
vmcs_read(vcpuid, VMCS_GUEST_RIP)
#define vmcs_instruction_error(vcpuid) \
vmcs_read(vcpuid, VMCS_INSTRUCTION_ERROR)
#define vmcs_exit_reason(vcpuid) \
(vmcs_read(vcpuid, VMCS_EXIT_REASON) & 0xffff)
#define vmcs_exit_qualification(vcpuid) \
vmcs_read(vcpuid, VMCS_EXIT_QUALIFICATION)
#define vmcs_guest_cr3(vcpuid) \
vmcs_read(vcpuid, VMCS_GUEST_CR3)
#define vmcs_gpa(vcpuid) \
vmcs_read(vcpuid, VMCS_GUEST_PHYSICAL_ADDRESS)
#define vmcs_gla(vcpuid) \
vmcs_read(vcpuid, VMCS_GUEST_LINEAR_ADDRESS)
#define vmcs_idt_vectoring_info(vcpuid) \
vmcs_read(vcpuid, VMCS_IDT_VECTORING_INFO)
#define vmcs_idt_vectoring_err(vcpuid) \
vmcs_read(vcpuid, VMCS_IDT_VECTORING_ERROR)
#define VMCS_INITIAL 0xffffffffffffffff
#define VMCS_IDENT(encoding) ((int) (((unsigned) (encoding)) | 0x80000000))
/*
* VMCS field encodings from Appendix H, Intel Architecture Manual Vol3B.
*/
#define VMCS_INVALID_ENCODING 0xffffffff
/* 16-bit control fields */
#define VMCS_VPID 0x00000000
#define VMCS_PIR_VECTOR 0x00000002
/* 16-bit guest-state fields */
#define VMCS_GUEST_ES_SELECTOR 0x00000800
#define VMCS_GUEST_CS_SELECTOR 0x00000802
#define VMCS_GUEST_SS_SELECTOR 0x00000804
#define VMCS_GUEST_DS_SELECTOR 0x00000806
#define VMCS_GUEST_FS_SELECTOR 0x00000808
#define VMCS_GUEST_GS_SELECTOR 0x0000080A
#define VMCS_GUEST_LDTR_SELECTOR 0x0000080C
#define VMCS_GUEST_TR_SELECTOR 0x0000080E
#define VMCS_GUEST_INTR_STATUS 0x00000810
/* 16-bit host-state fields */
#define VMCS_HOST_ES_SELECTOR 0x00000C00
#define VMCS_HOST_CS_SELECTOR 0x00000C02
#define VMCS_HOST_SS_SELECTOR 0x00000C04
#define VMCS_HOST_DS_SELECTOR 0x00000C06
#define VMCS_HOST_FS_SELECTOR 0x00000C08
#define VMCS_HOST_GS_SELECTOR 0x00000C0A
#define VMCS_HOST_TR_SELECTOR 0x00000C0C
/* 64-bit control fields */
#define VMCS_IO_BITMAP_A 0x00002000
#define VMCS_IO_BITMAP_B 0x00002002
#define VMCS_MSR_BITMAP 0x00002004
#define VMCS_EXIT_MSR_STORE 0x00002006
#define VMCS_EXIT_MSR_LOAD 0x00002008
#define VMCS_ENTRY_MSR_LOAD 0x0000200A
#define VMCS_EXECUTIVE_VMCS 0x0000200C
#define VMCS_TSC_OFFSET 0x00002010
#define VMCS_VIRTUAL_APIC 0x00002012
#define VMCS_APIC_ACCESS 0x00002014
#define VMCS_PIR_DESC 0x00002016
#define VMCS_EPTP 0x0000201A
#define VMCS_EOI_EXIT0 0x0000201C
#define VMCS_EOI_EXIT1 0x0000201E
#define VMCS_EOI_EXIT2 0x00002020
#define VMCS_EOI_EXIT3 0x00002022
#define VMCS_EOI_EXIT(vector) (VMCS_EOI_EXIT0 + ((vector) / 64) * 2)
/* 64-bit read-only fields */
#define VMCS_GUEST_PHYSICAL_ADDRESS 0x00002400
/* 64-bit guest-state fields */
#define VMCS_LINK_POINTER 0x00002800
#define VMCS_GUEST_IA32_DEBUGCTL 0x00002802
#define VMCS_GUEST_IA32_PAT 0x00002804
#define VMCS_GUEST_IA32_EFER 0x00002806
#define VMCS_GUEST_IA32_PERF_GLOBAL_CTRL 0x00002808
#define VMCS_GUEST_PDPTE0 0x0000280A
#define VMCS_GUEST_PDPTE1 0x0000280C
#define VMCS_GUEST_PDPTE2 0x0000280E
#define VMCS_GUEST_PDPTE3 0x00002810
/* 64-bit host-state fields */
#define VMCS_HOST_IA32_PAT 0x00002C00
#define VMCS_HOST_IA32_EFER 0x00002C02
#define VMCS_HOST_IA32_PERF_GLOBAL_CTRL 0x00002C04
/* 32-bit control fields */
#define VMCS_PIN_BASED_CTLS 0x00004000
#define VMCS_PRI_PROC_BASED_CTLS 0x00004002
#define VMCS_EXCEPTION_BITMAP 0x00004004
#define VMCS_PF_ERROR_MASK 0x00004006
#define VMCS_PF_ERROR_MATCH 0x00004008
#define VMCS_CR3_TARGET_COUNT 0x0000400A
#define VMCS_EXIT_CTLS 0x0000400C
#define VMCS_EXIT_MSR_STORE_COUNT 0x0000400E
#define VMCS_EXIT_MSR_LOAD_COUNT 0x00004010
#define VMCS_ENTRY_CTLS 0x00004012
#define VMCS_ENTRY_MSR_LOAD_COUNT 0x00004014
#define VMCS_ENTRY_INTR_INFO 0x00004016
#define VMCS_ENTRY_EXCEPTION_ERROR 0x00004018
#define VMCS_ENTRY_INST_LENGTH 0x0000401A
#define VMCS_TPR_THRESHOLD 0x0000401C
#define VMCS_SEC_PROC_BASED_CTLS 0x0000401E
#define VMCS_PLE_GAP 0x00004020
#define VMCS_PLE_WINDOW 0x00004022
/* 32-bit read-only data fields */
#define VMCS_INSTRUCTION_ERROR 0x00004400
#define VMCS_EXIT_REASON 0x00004402
#define VMCS_EXIT_INTR_INFO 0x00004404
#define VMCS_EXIT_INTR_ERRCODE 0x00004406
#define VMCS_IDT_VECTORING_INFO 0x00004408
#define VMCS_IDT_VECTORING_ERROR 0x0000440A
#define VMCS_EXIT_INSTRUCTION_LENGTH 0x0000440C
#define VMCS_EXIT_INSTRUCTION_INFO 0x0000440E
/* 32-bit guest-state fields */
#define VMCS_GUEST_ES_LIMIT 0x00004800
#define VMCS_GUEST_CS_LIMIT 0x00004802
#define VMCS_GUEST_SS_LIMIT 0x00004804
#define VMCS_GUEST_DS_LIMIT 0x00004806
#define VMCS_GUEST_FS_LIMIT 0x00004808
#define VMCS_GUEST_GS_LIMIT 0x0000480A
#define VMCS_GUEST_LDTR_LIMIT 0x0000480C
#define VMCS_GUEST_TR_LIMIT 0x0000480E
#define VMCS_GUEST_GDTR_LIMIT 0x00004810
#define VMCS_GUEST_IDTR_LIMIT 0x00004812
#define VMCS_GUEST_ES_ACCESS_RIGHTS 0x00004814
#define VMCS_GUEST_CS_ACCESS_RIGHTS 0x00004816
#define VMCS_GUEST_SS_ACCESS_RIGHTS 0x00004818
#define VMCS_GUEST_DS_ACCESS_RIGHTS 0x0000481A
#define VMCS_GUEST_FS_ACCESS_RIGHTS 0x0000481C
#define VMCS_GUEST_GS_ACCESS_RIGHTS 0x0000481E
#define VMCS_GUEST_LDTR_ACCESS_RIGHTS 0x00004820
#define VMCS_GUEST_TR_ACCESS_RIGHTS 0x00004822
#define VMCS_GUEST_INTERRUPTIBILITY 0x00004824
#define VMCS_GUEST_ACTIVITY 0x00004826
#define VMCS_GUEST_SMBASE 0x00004828
#define VMCS_GUEST_IA32_SYSENTER_CS 0x0000482A
#define VMCS_PREEMPTION_TIMER_VALUE 0x0000482E
/* 32-bit host state fields */
#define VMCS_HOST_IA32_SYSENTER_CS 0x00004C00
/* Natural Width control fields */
#define VMCS_CR0_MASK 0x00006000
#define VMCS_CR4_MASK 0x00006002
#define VMCS_CR0_SHADOW 0x00006004
#define VMCS_CR4_SHADOW 0x00006006
#define VMCS_CR3_TARGET0 0x00006008
#define VMCS_CR3_TARGET1 0x0000600A
#define VMCS_CR3_TARGET2 0x0000600C
#define VMCS_CR3_TARGET3 0x0000600E
/* Natural Width read-only fields */
#define VMCS_EXIT_QUALIFICATION 0x00006400
#define VMCS_IO_RCX 0x00006402
#define VMCS_IO_RSI 0x00006404
#define VMCS_IO_RDI 0x00006406
#define VMCS_IO_RIP 0x00006408
#define VMCS_GUEST_LINEAR_ADDRESS 0x0000640A
/* Natural Width guest-state fields */
#define VMCS_GUEST_CR0 0x00006800
#define VMCS_GUEST_CR3 0x00006802
#define VMCS_GUEST_CR4 0x00006804
#define VMCS_GUEST_ES_BASE 0x00006806
#define VMCS_GUEST_CS_BASE 0x00006808
#define VMCS_GUEST_SS_BASE 0x0000680A
#define VMCS_GUEST_DS_BASE 0x0000680C
#define VMCS_GUEST_FS_BASE 0x0000680E
#define VMCS_GUEST_GS_BASE 0x00006810
#define VMCS_GUEST_LDTR_BASE 0x00006812
#define VMCS_GUEST_TR_BASE 0x00006814
#define VMCS_GUEST_GDTR_BASE 0x00006816
#define VMCS_GUEST_IDTR_BASE 0x00006818
#define VMCS_GUEST_DR7 0x0000681A
#define VMCS_GUEST_RSP 0x0000681C
#define VMCS_GUEST_RIP 0x0000681E
#define VMCS_GUEST_RFLAGS 0x00006820
#define VMCS_GUEST_PENDING_DBG_EXCEPTIONS 0x00006822
#define VMCS_GUEST_IA32_SYSENTER_ESP 0x00006824
#define VMCS_GUEST_IA32_SYSENTER_EIP 0x00006826
/* Natural Width host-state fields */
#define VMCS_HOST_CR0 0x00006C00
#define VMCS_HOST_CR3 0x00006C02
#define VMCS_HOST_CR4 0x00006C04
#define VMCS_HOST_FS_BASE 0x00006C06
#define VMCS_HOST_GS_BASE 0x00006C08
#define VMCS_HOST_TR_BASE 0x00006C0A
#define VMCS_HOST_GDTR_BASE 0x00006C0C
#define VMCS_HOST_IDTR_BASE 0x00006C0E
#define VMCS_HOST_IA32_SYSENTER_ESP 0x00006C10
#define VMCS_HOST_IA32_SYSENTER_EIP 0x00006C12
#define VMCS_HOST_RSP 0x00006C14
#define VMCS_HOST_RIP 0x00006c16
/*
* VM instruction error numbers
*/
#define VMRESUME_WITH_NON_LAUNCHED_VMCS 5
/*
* VMCS exit reasons
*/
#define EXIT_REASON_EXCEPTION 0
#define EXIT_REASON_EXT_INTR 1
#define EXIT_REASON_TRIPLE_FAULT 2
#define EXIT_REASON_INIT 3
#define EXIT_REASON_SIPI 4
#define EXIT_REASON_IO_SMI 5
#define EXIT_REASON_SMI 6
#define EXIT_REASON_INTR_WINDOW 7
#define EXIT_REASON_NMI_WINDOW 8
#define EXIT_REASON_TASK_SWITCH 9
#define EXIT_REASON_CPUID 10
#define EXIT_REASON_GETSEC 11
#define EXIT_REASON_HLT 12
#define EXIT_REASON_INVD 13
#define EXIT_REASON_INVLPG 14
#define EXIT_REASON_RDPMC 15
#define EXIT_REASON_RDTSC 16
#define EXIT_REASON_RSM 17
#define EXIT_REASON_VMCALL 18
#define EXIT_REASON_VMCLEAR 19
#define EXIT_REASON_VMLAUNCH 20
#define EXIT_REASON_VMPTRLD 21
#define EXIT_REASON_VMPTRST 22
#define EXIT_REASON_VMREAD 23
#define EXIT_REASON_VMRESUME 24
#define EXIT_REASON_VMWRITE 25
#define EXIT_REASON_VMXOFF 26
#define EXIT_REASON_VMXON 27
#define EXIT_REASON_CR_ACCESS 28
#define EXIT_REASON_DR_ACCESS 29
#define EXIT_REASON_INOUT 30
#define EXIT_REASON_RDMSR 31
#define EXIT_REASON_WRMSR 32
#define EXIT_REASON_INVAL_VMCS 33
#define EXIT_REASON_INVAL_MSR 34
#define EXIT_REASON_MWAIT 36
#define EXIT_REASON_MTF 37
#define EXIT_REASON_MONITOR 39
#define EXIT_REASON_PAUSE 40
#define EXIT_REASON_MCE_DURING_ENTRY 41
#define EXIT_REASON_TPR 43
#define EXIT_REASON_APIC_ACCESS 44
#define EXIT_REASON_VIRTUALIZED_EOI 45
#define EXIT_REASON_GDTR_IDTR 46
#define EXIT_REASON_LDTR_TR 47
#define EXIT_REASON_EPT_FAULT 48
#define EXIT_REASON_EPT_MISCONFIG 49
#define EXIT_REASON_INVEPT 50
#define EXIT_REASON_RDTSCP 51
#define EXIT_REASON_VMX_PREEMPT 52
#define EXIT_REASON_INVVPID 53
#define EXIT_REASON_WBINVD 54
#define EXIT_REASON_XSETBV 55
#define EXIT_REASON_APIC_WRITE 56
/*
* NMI unblocking due to IRET.
*
* Applies to VM-exits due to hardware exception or EPT fault.
*/
#define EXIT_QUAL_NMIUDTI (1U << 12)
/*
* VMCS interrupt information fields
*/
#define VMCS_INTR_VALID (1U << 31)
#define VMCS_INTR_T_MASK 0x700U /* Interruption-info type */
#define VMCS_INTR_T_HWINTR (0U << 8)
#define VMCS_INTR_T_NMI (2U << 8)
#define VMCS_INTR_T_HWEXCEPTION (3U << 8)
#define VMCS_INTR_T_SWINTR (4U << 8)
#define VMCS_INTR_T_PRIV_SWEXCEPTION (5U << 8)
#define VMCS_INTR_T_SWEXCEPTION (6U << 8)
#define VMCS_INTR_DEL_ERRCODE (1U << 11)
/*
* VMCS IDT-Vectoring information fields
*/
#define VMCS_IDT_VEC_VALID (1U << 31)
#define VMCS_IDT_VEC_ERRCODE_VALID (1U << 11)
/*
* VMCS Guest interruptibility field
*/
#define VMCS_INTERRUPTIBILITY_STI_BLOCKING (1U << 0)
#define VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING (1U << 1)
#define VMCS_INTERRUPTIBILITY_SMI_BLOCKING (1U << 2)
#define VMCS_INTERRUPTIBILITY_NMI_BLOCKING (1U << 3)
/*
* Exit qualification for EXIT_REASON_INVAL_VMCS
*/
#define EXIT_QUAL_NMI_WHILE_STI_BLOCKING 3
/*
* Exit qualification for EPT violation
*/
#define EPT_VIOLATION_DATA_READ (1UL << 0)
#define EPT_VIOLATION_DATA_WRITE (1UL << 1)
#define EPT_VIOLATION_INST_FETCH (1UL << 2)
#define EPT_VIOLATION_GPA_READABLE (1UL << 3)
#define EPT_VIOLATION_GPA_WRITEABLE (1UL << 4)
#define EPT_VIOLATION_GPA_EXECUTABLE (1UL << 5)
#define EPT_VIOLATION_GLA_VALID (1UL << 7)
#define EPT_VIOLATION_XLAT_VALID (1UL << 8)
/*
* Exit qualification for APIC-access VM exit
*/
#define APIC_ACCESS_OFFSET(qual) ((qual) & 0xFFF)
#define APIC_ACCESS_TYPE(qual) (((qual) >> 12) & 0xF)
/*
* Exit qualification for APIC-write VM exit
*/
#define APIC_WRITE_OFFSET(qual) ((qual) & 0xFFF)

View File

@ -0,0 +1,91 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stddef.h>
#include <xhyve/support/misc.h>
#include <xhyve/vmm/vmm.h>
#include <xhyve/vmm/intel/vmcs.h>
struct vmxcap {
int set;
uint32_t proc_ctls;
uint32_t proc_ctls2;
};
struct vmxstate {
uint64_t nextrip; /* next instruction to be executed by guest */
int lastcpu; /* host cpu that this 'vcpu' last ran on */
uint16_t vpid;
};
struct apic_page {
uint32_t reg[XHYVE_PAGE_SIZE / 4];
};
CTASSERT(sizeof(struct apic_page) == XHYVE_PAGE_SIZE);
/* Posted Interrupt Descriptor (described in section 29.6 of the Intel SDM) */
struct pir_desc {
uint64_t pir[4];
uint64_t pending;
uint64_t unused[3];
} __aligned(64);
CTASSERT(sizeof(struct pir_desc) == 64);
/* Index into the 'guest_msrs[]' array */
enum {
IDX_MSR_LSTAR,
IDX_MSR_CSTAR,
IDX_MSR_STAR,
IDX_MSR_SF_MASK,
IDX_MSR_KGSBASE,
IDX_MSR_PAT,
GUEST_MSR_NUM /* must be the last enumeration */
};
/* virtual machine softc */
struct vmx {
struct apic_page apic_page[VM_MAXCPU]; /* one apic page per vcpu */
uint64_t guest_msrs[VM_MAXCPU][GUEST_MSR_NUM];
struct vmxcap cap[VM_MAXCPU];
struct vmxstate state[VM_MAXCPU];
struct vm *vm;
};
#define VMX_GUEST_VMEXIT 0
#define VMX_VMRESUME_ERROR 1
#define VMX_VMLAUNCH_ERROR 2
#define VMX_INVEPT_ERROR 3
void vmx_call_isr(uintptr_t entry);
u_long vmx_fix_cr0(u_long cr0);
u_long vmx_fix_cr4(u_long cr4);
extern char vmx_exit_guest[];

View File

@ -0,0 +1,95 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
/* Pin-Based VM-Execution Controls */
#define PINBASED_EXTINT_EXITING (1u << 0)
#define PINBASED_NMI_EXITING (1u << 3)
#define PINBASED_VIRTUAL_NMI (1u << 5)
#define PINBASED_PREMPTION_TIMER (1u << 6)
#define PINBASED_POSTED_INTERRUPT (1u << 7)
/* Primary Processor-Based VM-Execution Controls */
#define PROCBASED_INT_WINDOW_EXITING (1u << 2)
#define PROCBASED_TSC_OFFSET (1u << 3)
#define PROCBASED_HLT_EXITING (1u << 7)
#define PROCBASED_INVLPG_EXITING (1u << 9)
#define PROCBASED_MWAIT_EXITING (1u << 10)
#define PROCBASED_RDPMC_EXITING (1u << 11)
#define PROCBASED_RDTSC_EXITING (1u << 12)
#define PROCBASED_CR3_LOAD_EXITING (1u << 15)
#define PROCBASED_CR3_STORE_EXITING (1u << 16)
#define PROCBASED_CR8_LOAD_EXITING (1u << 19)
#define PROCBASED_CR8_STORE_EXITING (1u << 20)
#define PROCBASED_USE_TPR_SHADOW (1u << 21)
#define PROCBASED_NMI_WINDOW_EXITING (1u << 22)
#define PROCBASED_MOV_DR_EXITING (1u << 23)
#define PROCBASED_IO_EXITING (1u << 24)
#define PROCBASED_IO_BITMAPS (1u << 25)
#define PROCBASED_MTF (1u << 27)
#define PROCBASED_MSR_BITMAPS (1u << 28)
#define PROCBASED_MONITOR_EXITING (1u << 29)
#define PROCBASED_PAUSE_EXITING (1u << 30)
#define PROCBASED_SECONDARY_CONTROLS (1U << 31)
/* Secondary Processor-Based VM-Execution Controls */
#define PROCBASED2_VIRTUALIZE_APIC_ACCESSES (1u << 0)
#define PROCBASED2_ENABLE_EPT (1u << 1)
#define PROCBASED2_DESC_TABLE_EXITING (1u << 2)
#define PROCBASED2_ENABLE_RDTSCP (1u << 3)
#define PROCBASED2_VIRTUALIZE_X2APIC_MODE (1u << 4)
#define PROCBASED2_ENABLE_VPID (1u << 5)
#define PROCBASED2_WBINVD_EXITING (1u << 6)
#define PROCBASED2_UNRESTRICTED_GUEST (1u << 7)
#define PROCBASED2_APIC_REGISTER_VIRTUALIZATION (1u << 8)
#define PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY (1u << 9)
#define PROCBASED2_PAUSE_LOOP_EXITING (1u << 10)
#define PROCBASED2_RDRAND_EXITING (1u << 11)
#define PROCBASED2_ENABLE_INVPCID (1u << 12)
#define PROCBASED2_RDSEED_EXITING (1u << 16)
/* VM Exit Controls */
#define VM_EXIT_SAVE_DEBUG_CONTROLS (1u << 2)
#define VM_EXIT_HOST_LMA (1u << 9)
#define VM_EXIT_LOAD_PERF_GLOBAL_CTRL (1u << 12)
#define VM_EXIT_ACKNOWLEDGE_INTERRUPT (1u << 15)
#define VM_EXIT_SAVE_PAT (1u << 18)
#define VM_EXIT_LOAD_PAT (1u << 19)
#define VM_EXIT_SAVE_EFER (1u << 20)
#define VM_EXIT_LOAD_EFER (1u << 21)
#define VM_EXIT_SAVE_PREEMPTION_TIMER (1u << 22)
/* VM Entry Controls */
#define VM_ENTRY_LOAD_DEBUG_CONTROLS (1u << 2)
#define VM_ENTRY_GUEST_LMA (1u << 9)
#define VM_ENTRY_INTO_SMM (1u << 10)
#define VM_ENTRY_DEACTIVATE_DUAL_MONITOR (1u << 11)
#define VM_ENTRY_LOAD_PERF_GLOBAL_CTRL (1u << 13)
#define VM_ENTRY_LOAD_PAT (1u << 14)
#define VM_ENTRY_LOAD_EFER (1u << 15)

View File

@ -0,0 +1,45 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <Hypervisor/hv.h>
#include <Hypervisor/hv_vmx.h>
#include <xhyve/support/misc.h>
struct vmx;
void vmx_msr_init(void);
void vmx_msr_guest_init(struct vmx *vmx, int vcpuid);
int vmx_rdmsr(struct vmx *, int vcpuid, u_int num, uint64_t *val);
int vmx_wrmsr(struct vmx *, int vcpuid, u_int num, uint64_t val);
int vmx_set_ctlreg(hv_vmx_capability_t cap_field, uint32_t ones_mask,
uint32_t zeros_mask, uint32_t *retval);

View File

@ -0,0 +1,59 @@
/*-
* Copyright (c) 2014 Tycho Nightingale <tycho.nightingale@pluribusnetworks.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <xhyve/vmm/vmm.h>
#define IO_ICU1 0x020 /* 8259A Interrupt Controller #1 */
#define IO_ICU2 0x0a0 /* 8259A Interrupt Controller #2 */
#define ICU_IMR_OFFSET 1
#define IO_ELCR1 0x4d0
#define IO_ELCR2 0x4d1
struct vatpic *vatpic_init(struct vm *vm);
void vatpic_cleanup(struct vatpic *vatpic);
int vatpic_master_handler(struct vm *vm, int vcpuid, bool in, int port,
int bytes, uint32_t *eax);
int vatpic_slave_handler(struct vm *vm, int vcpuid, bool in, int port,
int bytes, uint32_t *eax);
int vatpic_elc_handler(struct vm *vm, int vcpuid, bool in, int port, int bytes,
uint32_t *eax);
int vatpic_assert_irq(struct vm *vm, int irq);
int vatpic_deassert_irq(struct vm *vm, int irq);
int vatpic_pulse_irq(struct vm *vm, int irq);
int vatpic_set_irq_trigger(struct vm *vm, int irq, enum vm_intr_trigger trigger);
void vatpic_pending_intr(struct vm *vm, int *vecptr);
void vatpic_intr_accepted(struct vm *vm, int vector);

View File

@ -0,0 +1,48 @@
/*-
* Copyright (c) 2014 Tycho Nightingale <tycho.nightingale@pluribusnetworks.com>
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
//#include <machine/timerreg.h>
#define NMISC_PORT 0x61
struct vm;
struct vatpit;
struct vatpit *vatpit_init(struct vm *vm);
void vatpit_cleanup(struct vatpit *vatpit);
int vatpit_handler(struct vm *vm, int vcpuid, bool in, int port, int bytes,
uint32_t *eax);
int vatpit_nmisc_handler(struct vm *vm, int vcpuid, bool in, int port,
int bytes, uint32_t *eax);

View File

@ -0,0 +1,46 @@
/*-
* Copyright (c) 2013 Tycho Nightingale <tycho.nightingale@pluribusnetworks.com>
* Copyright (c) 2013 Neel Natu <neel@freebsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#define VHPET_BASE 0xfed00000
#define VHPET_SIZE 0x400
struct vm;
struct vhpet;
struct vhpet *vhpet_init(struct vm *vm);
void vhpet_cleanup(struct vhpet *vhpet);
int vhpet_mmio_write(void *vm, int vcpuid, uint64_t gpa, uint64_t val,
int size, void *arg);
int vhpet_mmio_read(void *vm, int vcpuid, uint64_t gpa, uint64_t *val,
int size, void *arg);
int vhpet_getcap(uint32_t *cap);

View File

@ -0,0 +1,53 @@
/*-
* Copyright (c) 2013 Tycho Nightingale <tycho.nightingale@pluribusnetworks.com>
* Copyright (c) 2013 Neel Natu <neel@freebsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#define VIOAPIC_BASE 0xfec00000
#define VIOAPIC_SIZE 0x1000
struct vm;
struct vioapic;
struct vioapic *vioapic_init(struct vm *vm);
void vioapic_cleanup(struct vioapic *vioapic);
int vioapic_assert_irq(struct vm *vm, int irq);
int vioapic_deassert_irq(struct vm *vm, int irq);
int vioapic_pulse_irq(struct vm *vm, int irq);
int vioapic_mmio_write(void *vm, int vcpuid, uint64_t gpa,
uint64_t wval, int size, void *arg);
int vioapic_mmio_read(void *vm, int vcpuid, uint64_t gpa,
uint64_t *rval, int size, void *arg);
int vioapic_pincount(struct vm *vm);
void vioapic_process_eoi(struct vm *vm, int vcpuid, int vector);

View File

@ -0,0 +1,110 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <xhyve/vmm/vmm.h>
struct vm;
int vlapic_write(struct vlapic *vlapic, int mmio_access, uint64_t offset,
uint64_t data, bool *retu);
int vlapic_read(struct vlapic *vlapic, int mmio_access, uint64_t offset,
uint64_t *data, bool *retu);
/*
* Returns 0 if there is no eligible vector that can be delivered to the
* guest at this time and non-zero otherwise.
*
* If an eligible vector number is found and 'vecptr' is not NULL then it will
* be stored in the location pointed to by 'vecptr'.
*
* Note that the vector does not automatically transition to the ISR as a
* result of calling this function.
*/
int vlapic_pending_intr(struct vlapic *vlapic, int *vecptr);
/*
* Transition 'vector' from IRR to ISR. This function is called with the
* vector returned by 'vlapic_pending_intr()' when the guest is able to
* accept this interrupt (i.e. RFLAGS.IF = 1 and no conditions exist that
* block interrupt delivery).
*/
void vlapic_intr_accepted(struct vlapic *vlapic, int vector);
/*
* Returns 1 if the vcpu needs to be notified of the interrupt and 0 otherwise.
*/
int vlapic_set_intr_ready(struct vlapic *vlapic, int vector, bool level);
/*
* Post an interrupt to the vcpu running on 'hostcpu'. This will use a
* hardware assist if available (e.g. Posted Interrupt) or fall back to
* sending an 'ipinum' to interrupt the 'hostcpu'.
*/
void vlapic_post_intr(struct vlapic *vlapic, int hostcpu, int ipinum);
void vlapic_set_error(struct vlapic *vlapic, uint32_t mask);
void vlapic_fire_cmci(struct vlapic *vlapic);
int vlapic_trigger_lvt(struct vlapic *vlapic, int vector);
uint64_t vlapic_get_apicbase(struct vlapic *vlapic);
int vlapic_set_apicbase(struct vlapic *vlapic, uint64_t val);
void vlapic_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state s);
bool vlapic_enabled(struct vlapic *vlapic);
void vlapic_deliver_intr(struct vm *vm, bool level, uint32_t dest, bool phys,
int delmode, int vec);
/* Reset the trigger-mode bits for all vectors to be edge-triggered */
void vlapic_reset_tmr(struct vlapic *vlapic);
/*
* Set the trigger-mode bit associated with 'vector' to level-triggered if
* the (dest,phys,delmode) tuple resolves to an interrupt being delivered to
* this 'vlapic'.
*/
void vlapic_set_tmr_level(struct vlapic *vlapic, uint32_t dest, bool phys,
int delmode, int vector);
void vlapic_set_cr8(struct vlapic *vlapic, uint64_t val);
uint64_t vlapic_get_cr8(struct vlapic *vlapic);
/* APIC write handlers */
void vlapic_id_write_handler(struct vlapic *vlapic);
void vlapic_ldr_write_handler(struct vlapic *vlapic);
void vlapic_dfr_write_handler(struct vlapic *vlapic);
void vlapic_svr_write_handler(struct vlapic *vlapic);
void vlapic_esr_write_handler(struct vlapic *vlapic);
int vlapic_icrlo_write_handler(struct vlapic *vlapic, bool *retu);
void vlapic_icrtmr_write_handler(struct vlapic *vlapic);
void vlapic_dcr_write_handler(struct vlapic *vlapic);
void vlapic_lvt_write_handler(struct vlapic *vlapic, uint32_t offset);
void vlapic_self_ipi_handler(struct vlapic *vlapic, uint64_t val);

View File

@ -0,0 +1,186 @@
/*-
* Copyright (c) 2013 Neel Natu <neel@freebsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <xhyve/support/apicreg.h>
#include <xhyve/vmm/vmm_callout.h>
/*
* APIC Register: Offset Description
*/
#define APIC_OFFSET_ID 0x20 /* Local APIC ID */
#define APIC_OFFSET_VER 0x30 /* Local APIC Version */
#define APIC_OFFSET_TPR 0x80 /* Task Priority Register */
#define APIC_OFFSET_APR 0x90 /* Arbitration Priority */
#define APIC_OFFSET_PPR 0xA0 /* Processor Priority Register */
#define APIC_OFFSET_EOI 0xB0 /* EOI Register */
#define APIC_OFFSET_RRR 0xC0 /* Remote read */
#define APIC_OFFSET_LDR 0xD0 /* Logical Destination */
#define APIC_OFFSET_DFR 0xE0 /* Destination Format Register */
#define APIC_OFFSET_SVR 0xF0 /* Spurious Vector Register */
#define APIC_OFFSET_ISR0 0x100 /* In Service Register */
#define APIC_OFFSET_ISR1 0x110
#define APIC_OFFSET_ISR2 0x120
#define APIC_OFFSET_ISR3 0x130
#define APIC_OFFSET_ISR4 0x140
#define APIC_OFFSET_ISR5 0x150
#define APIC_OFFSET_ISR6 0x160
#define APIC_OFFSET_ISR7 0x170
#define APIC_OFFSET_TMR0 0x180 /* Trigger Mode Register */
#define APIC_OFFSET_TMR1 0x190
#define APIC_OFFSET_TMR2 0x1A0
#define APIC_OFFSET_TMR3 0x1B0
#define APIC_OFFSET_TMR4 0x1C0
#define APIC_OFFSET_TMR5 0x1D0
#define APIC_OFFSET_TMR6 0x1E0
#define APIC_OFFSET_TMR7 0x1F0
#define APIC_OFFSET_IRR0 0x200 /* Interrupt Request Register */
#define APIC_OFFSET_IRR1 0x210
#define APIC_OFFSET_IRR2 0x220
#define APIC_OFFSET_IRR3 0x230
#define APIC_OFFSET_IRR4 0x240
#define APIC_OFFSET_IRR5 0x250
#define APIC_OFFSET_IRR6 0x260
#define APIC_OFFSET_IRR7 0x270
#define APIC_OFFSET_ESR 0x280 /* Error Status Register */
#define APIC_OFFSET_CMCI_LVT 0x2F0 /* Local Vector Table (CMCI) */
#define APIC_OFFSET_ICR_LOW 0x300 /* Interrupt Command Register */
#define APIC_OFFSET_ICR_HI 0x310
#define APIC_OFFSET_TIMER_LVT 0x320 /* Local Vector Table (Timer) */
#define APIC_OFFSET_THERM_LVT 0x330 /* Local Vector Table (Thermal) */
#define APIC_OFFSET_PERF_LVT 0x340 /* Local Vector Table (PMC) */
#define APIC_OFFSET_LINT0_LVT 0x350 /* Local Vector Table (LINT0) */
#define APIC_OFFSET_LINT1_LVT 0x360 /* Local Vector Table (LINT1) */
#define APIC_OFFSET_ERROR_LVT 0x370 /* Local Vector Table (ERROR) */
#define APIC_OFFSET_TIMER_ICR 0x380 /* Timer's Initial Count */
#define APIC_OFFSET_TIMER_CCR 0x390 /* Timer's Current Count */
#define APIC_OFFSET_TIMER_DCR 0x3E0 /* Timer's Divide Configuration */
#define APIC_OFFSET_SELF_IPI 0x3F0 /* Self IPI register */
#define VLAPIC_CTR0(vlapic, format) \
VCPU_CTR0((vlapic)->vm, (vlapic)->vcpuid, format)
#define VLAPIC_CTR1(vlapic, format, p1) \
VCPU_CTR1((vlapic)->vm, (vlapic)->vcpuid, format, p1)
#define VLAPIC_CTR2(vlapic, format, p1, p2) \
VCPU_CTR2((vlapic)->vm, (vlapic)->vcpuid, format, p1, p2)
#define VLAPIC_CTR3(vlapic, format, p1, p2, p3) \
VCPU_CTR3((vlapic)->vm, (vlapic)->vcpuid, format, p1, p2, p3)
#define VLAPIC_CTR_IRR(vlapic, msg) \
do { \
uint32_t *x = &(vlapic)->apic_page->irr0; \
x[0] = x[0]; /* silence compiler */ \
VLAPIC_CTR1((vlapic), msg " irr0 0x%08x", x[0 << 2]); \
VLAPIC_CTR1((vlapic), msg " irr1 0x%08x", x[1 << 2]); \
VLAPIC_CTR1((vlapic), msg " irr2 0x%08x", x[2 << 2]); \
VLAPIC_CTR1((vlapic), msg " irr3 0x%08x", x[3 << 2]); \
VLAPIC_CTR1((vlapic), msg " irr4 0x%08x", x[4 << 2]); \
VLAPIC_CTR1((vlapic), msg " irr5 0x%08x", x[5 << 2]); \
VLAPIC_CTR1((vlapic), msg " irr6 0x%08x", x[6 << 2]); \
VLAPIC_CTR1((vlapic), msg " irr7 0x%08x", x[7 << 2]); \
} while (0)
#define VLAPIC_CTR_ISR(vlapic, msg) \
do { \
uint32_t *x = &(vlapic)->apic_page->isr0; \
x[0] = x[0]; /* silence compiler */ \
VLAPIC_CTR1((vlapic), msg " isr0 0x%08x", x[0 << 2]); \
VLAPIC_CTR1((vlapic), msg " isr1 0x%08x", x[1 << 2]); \
VLAPIC_CTR1((vlapic), msg " isr2 0x%08x", x[2 << 2]); \
VLAPIC_CTR1((vlapic), msg " isr3 0x%08x", x[3 << 2]); \
VLAPIC_CTR1((vlapic), msg " isr4 0x%08x", x[4 << 2]); \
VLAPIC_CTR1((vlapic), msg " isr5 0x%08x", x[5 << 2]); \
VLAPIC_CTR1((vlapic), msg " isr6 0x%08x", x[6 << 2]); \
VLAPIC_CTR1((vlapic), msg " isr7 0x%08x", x[7 << 2]); \
} while (0)
enum boot_state {
BS_INIT,
BS_SIPI,
BS_RUNNING
};
/*
* 16 priority levels with at most one vector injected per level.
*/
#define ISRVEC_STK_SIZE (16 + 1)
#define VLAPIC_MAXLVT_INDEX APIC_LVT_CMCI
struct vlapic;
struct vlapic_ops {
int (*set_intr_ready)(struct vlapic *vlapic, int vector, bool level);
int (*pending_intr)(struct vlapic *vlapic, int *vecptr);
void (*intr_accepted)(struct vlapic *vlapic, int vector);
void (*post_intr)(struct vlapic *vlapic, int hostcpu);
void (*set_tmr)(struct vlapic *vlapic, int vector, bool level);
void (*enable_x2apic_mode)(struct vlapic *vlapic);
};
struct vlapic {
struct vm *vm;
int vcpuid;
struct LAPIC *apic_page;
struct vlapic_ops ops;
uint32_t esr_pending;
int esr_firing;
struct callout callout; /* vlapic timer */
struct bintime timer_fire_bt; /* callout expiry time */
struct bintime timer_freq_bt; /* timer frequency */
struct bintime timer_period_bt; /* timer period */
pthread_mutex_t timer_lock;
/*
* The 'isrvec_stk' is a stack of vectors injected by the local apic.
* A vector is popped from the stack when the processor does an EOI.
* The vector on the top of the stack is used to compute the
* Processor Priority in conjunction with the TPR.
*/
uint8_t isrvec_stk[ISRVEC_STK_SIZE];
int isrvec_stk_top;
uint64_t msr_apicbase;
enum boot_state boot_state;
/*
* Copies of some registers in the virtual APIC page. We do this for
* a couple of different reasons:
* - to be able to detect what changed (e.g. svr_last)
* - to maintain a coherent snapshot of the register (e.g. lvt_last)
*/
uint32_t svr_last;
uint32_t lvt_last[VLAPIC_MAXLVT_INDEX + 1];
};
void vlapic_init(struct vlapic *vlapic);
void vlapic_cleanup(struct vlapic *vlapic);

View File

@ -0,0 +1,42 @@
/*-
* Copyright (c) 2014 Neel Natu (neel@freebsd.org)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice unmodified, this list of conditions, and the following
* disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#define IO_PMTMR 0x408
struct vm;
struct vpmtmr;
struct vpmtmr *vpmtmr_init(struct vm *vm);
void vpmtmr_cleanup(struct vpmtmr *pmtmr);
int vpmtmr_handler(struct vm *vm, int vcpuid, bool in, int port, int bytes,
uint32_t *val);

View File

@ -0,0 +1,52 @@
/*-
* Copyright (c) 2014 Neel Natu (neel@freebsd.org)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice unmodified, this list of conditions, and the following
* disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <time.h>
#define IO_RTC 0x070 /* 4990A RTC */
struct vm;
struct vrtc;
struct vrtc *vrtc_init(struct vm *vm);
void vrtc_cleanup(struct vrtc *vrtc);
void vrtc_reset(struct vrtc *vrtc);
time_t vrtc_get_time(struct vm *vm);
int vrtc_set_time(struct vm *vm, time_t secs);
int vrtc_nvram_write(struct vm *vm, int offset, uint8_t value);
int vrtc_nvram_read(struct vm *vm, int offset, uint8_t *retval);
int vrtc_addr_handler(struct vm *vm, int vcpuid, bool in, int port, int bytes,
uint32_t *val);
int vrtc_data_handler(struct vm *vm, int vcpuid, bool in, int port, int bytes,
uint32_t *val);

View File

@ -0,0 +1,315 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <xhyve/support/misc.h>
#include <xhyve/support/cpuset.h>
#include <xhyve/support/segments.h>
#include <xhyve/vmm/vmm_common.h>
#define VM_INTINFO_VECTOR(info) ((info) & 0xff)
#define VM_INTINFO_DEL_ERRCODE 0x800
#define VM_INTINFO_RSVD 0x7ffff000
#define VM_INTINFO_VALID 0x80000000
#define VM_INTINFO_TYPE 0x700
#define VM_INTINFO_HWINTR (0 << 8)
#define VM_INTINFO_NMI (2 << 8)
#define VM_INTINFO_HWEXCEPTION (3 << 8)
#define VM_INTINFO_SWINTR (4 << 8)
struct vm;
struct vm_exception;
struct vm_memory_segment;
struct seg_desc;
struct vm_exit;
struct vm_run;
struct vhpet;
struct vioapic;
struct vlapic;
struct vmspace;
struct vm_object;
struct vm_guest_paging;
struct pmap;
typedef int (*vmm_init_func_t)(void);
typedef int (*vmm_cleanup_func_t)(void);
typedef void *(*vmi_vm_init_func_t)(struct vm *vm);
typedef int (*vmi_vcpu_init_func_t)(void *vmi, int vcpu);
typedef void (*vmi_vcpu_dump_func_t)(void *vmi, int vcpu);
typedef int (*vmi_run_func_t)(void *vmi, int vcpu, register_t rip,
void *rendezvous_cookie, void *suspend_cookie);
typedef void (*vmi_vm_cleanup_func_t)(void *vmi);
typedef void (*vmi_vcpu_cleanup_func_t)(void *vmi, int vcpu);
typedef int (*vmi_get_register_t)(void *vmi, int vcpu, int num,
uint64_t *retval);
typedef int (*vmi_set_register_t)(void *vmi, int vcpu, int num,
uint64_t val);
typedef int (*vmi_get_desc_t)(void *vmi, int vcpu, int num,
struct seg_desc *desc);
typedef int (*vmi_set_desc_t)(void *vmi, int vcpu, int num,
struct seg_desc *desc);
typedef int (*vmi_get_cap_t)(void *vmi, int vcpu, int num, int *retval);
typedef int (*vmi_set_cap_t)(void *vmi, int vcpu, int num, int val);
typedef struct vlapic * (*vmi_vlapic_init)(void *vmi, int vcpu);
typedef void (*vmi_vlapic_cleanup)(void *vmi, struct vlapic *vlapic);
typedef void (*vmi_interrupt)(int vcpu);
struct vmm_ops {
vmm_init_func_t init; /* module wide initialization */
vmm_cleanup_func_t cleanup;
vmi_vm_init_func_t vm_init; /* vm-specific initialization */
vmi_vcpu_init_func_t vcpu_init;
vmi_vcpu_dump_func_t vcpu_dump;
vmi_run_func_t vmrun;
vmi_vm_cleanup_func_t vm_cleanup;
vmi_vcpu_cleanup_func_t vcpu_cleanup;
vmi_get_register_t vmgetreg;
vmi_set_register_t vmsetreg;
vmi_get_desc_t vmgetdesc;
vmi_set_desc_t vmsetdesc;
vmi_get_cap_t vmgetcap;
vmi_set_cap_t vmsetcap;
vmi_vlapic_init vlapic_init;
vmi_vlapic_cleanup vlapic_cleanup;
vmi_interrupt vcpu_interrupt;
};
extern struct vmm_ops vmm_ops_intel;
int vmm_init(void);
int vmm_cleanup(void);
int vm_create(struct vm **retvm);
void vm_signal_pause(struct vm *vm, bool pause);
void vm_check_for_unpause(struct vm *vm, int vcpuid);
int vcpu_create(struct vm *vm, int vcpu);
void vm_destroy(struct vm *vm);
void vcpu_destroy(struct vm *vm, int vcpu);
int vm_reinit(struct vm *vm);
const char *vm_name(struct vm *vm);
int vm_malloc(struct vm *vm, uint64_t gpa, size_t len);
void *vm_gpa2hva(struct vm *vm, uint64_t gpa, uint64_t len);
int vm_gpabase2memseg(struct vm *vm, uint64_t gpabase,
struct vm_memory_segment *seg);
int vm_get_memobj(struct vm *vm, uint64_t gpa, size_t len, uint64_t *offset,
void **object);
bool vm_mem_allocated(struct vm *vm, uint64_t gpa);
int vm_get_register(struct vm *vm, int vcpu, int reg, uint64_t *retval);
int vm_set_register(struct vm *vm, int vcpu, int reg, uint64_t val);
int vm_get_seg_desc(struct vm *vm, int vcpu, int reg,
struct seg_desc *ret_desc);
int vm_set_seg_desc(struct vm *vm, int vcpu, int reg, struct seg_desc *desc);
int vm_run(struct vm *vm, int vcpu, struct vm_exit *vm_exit);
int vm_suspend(struct vm *vm, enum vm_suspend_how how);
int vm_inject_nmi(struct vm *vm, int vcpu);
int vm_nmi_pending(struct vm *vm, int vcpuid);
void vm_nmi_clear(struct vm *vm, int vcpuid);
int vm_inject_extint(struct vm *vm, int vcpu);
int vm_extint_pending(struct vm *vm, int vcpuid);
void vm_extint_clear(struct vm *vm, int vcpuid);
struct vlapic *vm_lapic(struct vm *vm, int cpu);
struct vioapic *vm_ioapic(struct vm *vm);
struct vhpet *vm_hpet(struct vm *vm);
int vm_get_capability(struct vm *vm, int vcpu, int type, int *val);
int vm_set_capability(struct vm *vm, int vcpu, int type, int val);
int vm_get_x2apic_state(struct vm *vm, int vcpu, enum x2apic_state *state);
int vm_set_x2apic_state(struct vm *vm, int vcpu, enum x2apic_state state);
int vm_apicid2vcpuid(struct vm *vm, int apicid);
int vm_activate_cpu(struct vm *vm, int vcpu);
struct vm_exit *vm_exitinfo(struct vm *vm, int vcpuid);
void vm_exit_suspended(struct vm *vm, int vcpuid, uint64_t rip);
void vm_exit_rendezvous(struct vm *vm, int vcpuid, uint64_t rip);
void vm_vcpu_dump(struct vm *vm, int vcpuid);
/*
* Rendezvous all vcpus specified in 'dest' and execute 'func(arg)'.
* The rendezvous 'func(arg)' is not allowed to do anything that will
* cause the thread to be put to sleep.
*
* If the rendezvous is being initiated from a vcpu context then the
* 'vcpuid' must refer to that vcpu, otherwise it should be set to -1.
*
* The caller cannot hold any locks when initiating the rendezvous.
*
* The implementation of this API may cause vcpus other than those specified
* by 'dest' to be stalled. The caller should not rely on any vcpus making
* forward progress when the rendezvous is in progress.
*/
typedef void (*vm_rendezvous_func_t)(struct vm *vm, int vcpuid, void *arg);
void vm_smp_rendezvous(struct vm *vm, int vcpuid, cpuset_t dest,
vm_rendezvous_func_t func, void *arg);
cpuset_t vm_active_cpus(struct vm *vm);
cpuset_t vm_suspended_cpus(struct vm *vm);
static __inline int
vcpu_rendezvous_pending(void *rendezvous_cookie)
{
return (*(uintptr_t *)rendezvous_cookie != 0);
}
static __inline int
vcpu_suspended(void *suspend_cookie)
{
return (*(int *)suspend_cookie);
}
enum vcpu_state {
VCPU_IDLE,
VCPU_FROZEN,
VCPU_RUNNING,
VCPU_SLEEPING,
};
int vcpu_set_state(struct vm *vm, int vcpu, enum vcpu_state state,
bool from_idle);
enum vcpu_state vcpu_get_state(struct vm *vm, int vcpu);
static int __inline
vcpu_is_running(struct vm *vm, int vcpu)
{
return (vcpu_get_state(vm, vcpu) == VCPU_RUNNING);
}
void *vcpu_stats(struct vm *vm, int vcpu);
void vcpu_notify_event(struct vm *vm, int vcpuid, bool lapic_intr);
struct vatpic *vm_atpic(struct vm *vm);
struct vatpit *vm_atpit(struct vm *vm);
struct vpmtmr *vm_pmtmr(struct vm *vm);
struct vrtc *vm_rtc(struct vm *vm);
/*
* Inject exception 'vector' into the guest vcpu. This function returns 0 on
* success and non-zero on failure.
*
* Wrapper functions like 'vm_inject_gp()' should be preferred to calling
* this function directly because they enforce the trap-like or fault-like
* behavior of an exception.
*
* This function should only be called in the context of the thread that is
* executing this vcpu.
*/
int vm_inject_exception(struct vm *vm, int vcpuid, int vector, int err_valid,
uint32_t errcode, int restart_instruction);
/*
* This function is called after a VM-exit that occurred during exception or
* interrupt delivery through the IDT. The format of 'intinfo' is described
* in Figure 15-1, "EXITINTINFO for All Intercepts", APM, Vol 2.
*
* If a VM-exit handler completes the event delivery successfully then it
* should call vm_exit_intinfo() to extinguish the pending event. For e.g.,
* if the task switch emulation is triggered via a task gate then it should
* call this function with 'intinfo=0' to indicate that the external event
* is not pending anymore.
*
* Return value is 0 on success and non-zero on failure.
*/
int vm_exit_intinfo(struct vm *vm, int vcpuid, uint64_t intinfo);
/*
* This function is called before every VM-entry to retrieve a pending
* event that should be injected into the guest. This function combines
* nested events into a double or triple fault.
*
* Returns 0 if there are no events that need to be injected into the guest
* and non-zero otherwise.
*/
int vm_entry_intinfo(struct vm *vm, int vcpuid, uint64_t *info);
int vm_get_intinfo(struct vm *vm, int vcpuid, uint64_t *info1, uint64_t *info2);
enum vm_reg_name vm_segment_name(int seg_encoding);
struct vm_copyinfo {
uint64_t gpa;
size_t len;
void *hva;
};
/*
* Set up 'copyinfo[]' to copy to/from guest linear address space starting
* at 'gla' and 'len' bytes long. The 'prot' should be set to PROT_READ for
* a copyin or PROT_WRITE for a copyout.
*
* retval is_fault Intepretation
* 0 0 Success
* 0 1 An exception was injected into the guest
* EFAULT N/A Unrecoverable error
*
* The 'copyinfo[]' can be passed to 'vm_copyin()' or 'vm_copyout()' only if
* the return value is 0. The 'copyinfo[]' resources should be freed by calling
* 'vm_copy_teardown()' after the copy is done.
*/
int vm_copy_setup(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
uint64_t gla, size_t len, int prot, struct vm_copyinfo *copyinfo,
int num_copyinfo, int *is_fault);
void vm_copy_teardown(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo,
int num_copyinfo);
void vm_copyin(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo,
void *kaddr, size_t len);
void vm_copyout(struct vm *vm, int vcpuid, const void *kaddr,
struct vm_copyinfo *copyinfo, size_t len);
int vcpu_trace_exceptions(void);
/* APIs to inject faults into the guest */
void vm_inject_fault(void *vm, int vcpuid, int vector, int errcode_valid,
int errcode);
static __inline void
vm_inject_ud(void *vm, int vcpuid)
{
vm_inject_fault(vm, vcpuid, IDT_UD, 0, 0);
}
static __inline void
vm_inject_gp(void *vm, int vcpuid)
{
vm_inject_fault(vm, vcpuid, IDT_GP, 1, 0);
}
static __inline void
vm_inject_ac(void *vm, int vcpuid, int errcode)
{
vm_inject_fault(vm, vcpuid, IDT_AC, 1, errcode);
}
static __inline void
vm_inject_ss(void *vm, int vcpuid, int errcode)
{
vm_inject_fault(vm, vcpuid, IDT_SS, 1, errcode);
}
void vm_inject_pf(void *vm, int vcpuid, int error_code, uint64_t cr2);
int vm_restart_instruction(void *vm, int vcpuid);

View File

@ -0,0 +1,115 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <sys/time.h>
#include <xhyve/support/cpuset.h>
#include <xhyve/vmm/vmm_common.h>
struct iovec;
/*
* Different styles of mapping the memory assigned to a VM into the address
* space of the controlling process.
*/
enum vm_mmap_style {
VM_MMAP_NONE, /* no mapping */
VM_MMAP_ALL, /* fully and statically mapped */
VM_MMAP_SPARSE, /* mappings created on-demand */
};
void xh_hv_pause(int pause);
int xh_vm_create(void);
void xh_vm_destroy(void);
int xh_vcpu_create(int vcpu);
void xh_vcpu_destroy(int vcpu);
int xh_vm_get_memory_seg(uint64_t gpa, size_t *ret_len);
int xh_vm_setup_memory(size_t len, enum vm_mmap_style vms);
void *xh_vm_map_gpa(uint64_t gpa, size_t len);
int xh_vm_gla2gpa(int vcpu, struct vm_guest_paging *paging, uint64_t gla,
int prot, uint64_t *gpa, int *fault);
uint32_t xh_vm_get_lowmem_limit(void);
void xh_vm_set_lowmem_limit(uint32_t limit);
void xh_vm_set_memflags(int flags);
size_t xh_vm_get_lowmem_size(void);
size_t xh_vm_get_highmem_size(void);
int xh_vm_set_desc(int vcpu, int reg, uint64_t base, uint32_t limit,
uint32_t access);
int xh_vm_get_desc(int vcpu, int reg, uint64_t *base, uint32_t *limit,
uint32_t *access);
int xh_vm_get_seg_desc(int vcpu, int reg, struct seg_desc *seg_desc);
int xh_vm_set_register(int vcpu, int reg, uint64_t val);
int xh_vm_get_register(int vcpu, int reg, uint64_t *retval);
int xh_vm_run(int vcpu, struct vm_exit *ret_vmexit);
int xh_vm_suspend(enum vm_suspend_how how);
int xh_vm_reinit(void);
int xh_vm_apicid2vcpu(int apicid);
int xh_vm_inject_exception(int vcpu, int vector, int errcode_valid,
uint32_t errcode, int restart_instruction);
int xh_vm_lapic_irq(int vcpu, int vector);
int xh_vm_lapic_local_irq(int vcpu, int vector);
int xh_vm_lapic_msi(uint64_t addr, uint64_t msg);
int xh_vm_ioapic_assert_irq(int irq);
int xh_vm_ioapic_deassert_irq(int irq);
int xh_vm_ioapic_pulse_irq(int irq);
int xh_vm_ioapic_pincount(int *pincount);
int xh_vm_isa_assert_irq(int atpic_irq, int ioapic_irq);
int xh_vm_isa_deassert_irq(int atpic_irq, int ioapic_irq);
int xh_vm_isa_pulse_irq(int atpic_irq, int ioapic_irq);
int xh_vm_isa_set_irq_trigger(int atpic_irq, enum vm_intr_trigger trigger);
int xh_vm_inject_nmi(int vcpu);
int xh_vm_capability_name2type(const char *capname);
const char *xh_vm_capability_type2name(int type);
int xh_vm_get_capability(int vcpu, enum vm_cap_type cap, int *retval);
int xh_vm_set_capability(int vcpu, enum vm_cap_type cap, int val);
int xh_vm_get_intinfo(int vcpu, uint64_t *i1, uint64_t *i2);
int xh_vm_set_intinfo(int vcpu, uint64_t exit_intinfo);
uint64_t *xh_vm_get_stats(int vcpu, struct timeval *ret_tv, int *ret_entries);
const char *xh_vm_get_stat_desc(int index);
int xh_vm_get_x2apic_state(int vcpu, enum x2apic_state *s);
int xh_vm_set_x2apic_state(int vcpu, enum x2apic_state s);
int xh_vm_get_hpet_capabilities(uint32_t *capabilities);
int xh_vm_copy_setup(int vcpu, struct vm_guest_paging *pg, uint64_t gla,
size_t len, int prot, struct iovec *iov, int iovcnt, int *fault);
void xh_vm_copyin(struct iovec *iov, void *dst, size_t len);
void xh_vm_copyout(const void *src, struct iovec *iov, size_t len);
int xh_vm_rtc_write(int offset, uint8_t value);
int xh_vm_rtc_read(int offset, uint8_t *retval);
int xh_vm_rtc_settime(time_t secs);
int xh_vm_rtc_gettime(time_t *secs);
int xh_vcpu_reset(int vcpu);
int xh_vm_active_cpus(cpuset_t *cpus);
int xh_vm_suspended_cpus(cpuset_t *cpus);
int xh_vm_activate_cpu(int vcpu);
int xh_vm_restart_instruction(int vcpu);
int xh_vm_emulate_instruction(int vcpu, uint64_t gpa, struct vie *vie,
struct vm_guest_paging *paging, mem_region_read_t memread,
mem_region_write_t memwrite, void *memarg);
void xh_vm_vcpu_dump(int vcpu);

View File

@ -0,0 +1,117 @@
#pragma once
#include <stdint.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#define SBT_1S ((sbintime_t)1 << 32)
#define SBT_1M (SBT_1S * 60)
#define SBT_1MS (SBT_1S / 1000)
#define SBT_1US (SBT_1S / 1000000)
#define SBT_1NS (SBT_1S / 1000000000)
#define SBT_MAX 0x7fffffffffffffffLL
#define FREQ2BT(freq, bt) \
{ \
(bt)->sec = 0; \
(bt)->frac = ((uint64_t)0x8000000000000000 / (freq)) << 1; \
}
#define BT2FREQ(bt) \
(((uint64_t)0x8000000000000000 + ((bt)->frac >> 2)) / \
((bt)->frac >> 1))
struct bintime {
uint64_t sec;
uint64_t frac;
};
typedef int64_t sbintime_t;
static inline sbintime_t bttosbt(const struct bintime bt) {
return (sbintime_t) ((bt.sec << 32) + (bt.frac >> 32));
}
static inline void bintime_mul(struct bintime *bt, unsigned int x) {
uint64_t p1, p2;
p1 = (bt->frac & 0xffffffffull) * x;
p2 = (bt->frac >> 32) * x + (p1 >> 32);
bt->sec *= x;
bt->sec += (p2 >> 32);
bt->frac = (p2 << 32) | (p1 & 0xffffffffull);
}
static inline void bintime_add(struct bintime *_bt, const struct bintime *_bt2)
{
uint64_t _u;
_u = _bt->frac;
_bt->frac += _bt2->frac;
if (_u > _bt->frac)
_bt->sec++;
_bt->sec += _bt2->sec;
}
static inline void bintime_sub(struct bintime *_bt, const struct bintime *_bt2)
{
uint64_t _u;
_u = _bt->frac;
_bt->frac -= _bt2->frac;
if (_u < _bt->frac)
_bt->sec--;
_bt->sec -= _bt2->sec;
}
#define bintime_cmp(a, b, cmp) \
(((a)->sec == (b)->sec) ? \
((a)->frac cmp (b)->frac) : \
((a)->sec cmp (b)->sec))
void binuptime(struct bintime *bt);
void getmicrotime(struct timeval *tv);
static inline sbintime_t sbinuptime(void) {
struct bintime _bt;
binuptime(&_bt);
return (bttosbt(_bt));
}
struct callout {
pthread_cond_t wait;
struct callout *prev;
struct callout *next;
uint64_t timeout;
void *argument;
void (*callout)(void *);
int flags;
int queued;
};
#define C_ABSOLUTE 0x0200 /* event time is absolute */
#define CALLOUT_ACTIVE 0x0002 /* callout is currently active */
#define CALLOUT_PENDING 0x0004 /* callout is waiting for timeout */
#define CALLOUT_MPSAFE 0x0008 /* callout handler is mp safe */
#define CALLOUT_RETURNUNLOCKED 0x0010 /* handler returns with mtx unlocked */
#define CALLOUT_COMPLETED 0x0020 /* callout thread finished */
#define CALLOUT_WAITING 0x0040 /* thread waiting for callout to finish */
//#define CALLOUT_QUEUED 0x0080
void callout_system_init(void);
void callout_init(struct callout *c, int mpsafe);
int callout_reset_sbt(struct callout *c, sbintime_t sbt,
sbintime_t precision, void (*ftn)(void *), void *arg,
int flags);
int callout_stop_safe(struct callout *c, int drain);
#define callout_active(c) ((c)->flags & CALLOUT_ACTIVE)
#define callout_deactivate(c) ((c)->flags &= ~CALLOUT_ACTIVE)
#define callout_pending(c) ((c)->flags & CALLOUT_PENDING)
#define callout_completed(c) ((c)->flags & CALLOUT_COMPLETED)
#define callout_drain(c) callout_stop_safe(c, 1)
#define callout_stop(c) callout_stop_safe(c, 0)

View File

@ -0,0 +1,317 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#define VM_MAXCPU 64 /* maximum virtual cpus */
enum vm_suspend_how {
VM_SUSPEND_NONE,
VM_SUSPEND_RESET,
VM_SUSPEND_POWEROFF,
VM_SUSPEND_HALT,
VM_SUSPEND_TRIPLEFAULT,
VM_SUSPEND_LAST
};
enum vm_cap_type {
VM_CAP_HALT_EXIT,
VM_CAP_MTRAP_EXIT,
VM_CAP_PAUSE_EXIT,
VM_CAP_MAX
};
enum vm_intr_trigger {
EDGE_TRIGGER,
LEVEL_TRIGGER
};
enum x2apic_state {
X2APIC_DISABLED,
X2APIC_ENABLED,
X2APIC_STATE_LAST
};
enum vm_cpu_mode {
CPU_MODE_REAL,
CPU_MODE_PROTECTED,
CPU_MODE_COMPATIBILITY, /* IA-32E mode (CS.L = 0) */
CPU_MODE_64BIT, /* IA-32E mode (CS.L = 1) */
};
enum vm_paging_mode {
PAGING_MODE_FLAT,
PAGING_MODE_32,
PAGING_MODE_PAE,
PAGING_MODE_64,
};
struct seg_desc {
uint64_t base;
uint32_t limit;
uint32_t access;
};
#define SEG_DESC_TYPE(access) ((access) & 0x001f)
#define SEG_DESC_DPL(access) (((access) >> 5) & 0x3)
#define SEG_DESC_PRESENT(access) (((access) & 0x0080) ? 1 : 0)
#define SEG_DESC_DEF32(access) (((access) & 0x4000) ? 1 : 0)
#define SEG_DESC_GRANULARITY(access) (((access) & 0x8000) ? 1 : 0)
#define SEG_DESC_UNUSABLE(access) (((access) & 0x10000) ? 1 : 0)
struct vm_guest_paging {
uint64_t cr3;
int cpl;
enum vm_cpu_mode cpu_mode;
enum vm_paging_mode paging_mode;
};
enum vm_reg_name {
VM_REG_GUEST_RAX,
VM_REG_GUEST_RBX,
VM_REG_GUEST_RCX,
VM_REG_GUEST_RDX,
VM_REG_GUEST_RSI,
VM_REG_GUEST_RDI,
VM_REG_GUEST_RBP,
VM_REG_GUEST_R8,
VM_REG_GUEST_R9,
VM_REG_GUEST_R10,
VM_REG_GUEST_R11,
VM_REG_GUEST_R12,
VM_REG_GUEST_R13,
VM_REG_GUEST_R14,
VM_REG_GUEST_R15,
VM_REG_GUEST_CR0,
VM_REG_GUEST_CR3,
VM_REG_GUEST_CR4,
VM_REG_GUEST_DR7,
VM_REG_GUEST_RSP,
VM_REG_GUEST_RIP,
VM_REG_GUEST_RFLAGS,
VM_REG_GUEST_ES,
VM_REG_GUEST_CS,
VM_REG_GUEST_SS,
VM_REG_GUEST_DS,
VM_REG_GUEST_FS,
VM_REG_GUEST_GS,
VM_REG_GUEST_LDTR,
VM_REG_GUEST_TR,
VM_REG_GUEST_IDTR,
VM_REG_GUEST_GDTR,
VM_REG_GUEST_EFER,
VM_REG_GUEST_CR2,
VM_REG_GUEST_PDPTE0,
VM_REG_GUEST_PDPTE1,
VM_REG_GUEST_PDPTE2,
VM_REG_GUEST_PDPTE3,
VM_REG_GUEST_INTR_SHADOW,
VM_REG_LAST
};
enum vm_exitcode {
VM_EXITCODE_INOUT,
VM_EXITCODE_VMX,
VM_EXITCODE_BOGUS,
VM_EXITCODE_RDMSR,
VM_EXITCODE_WRMSR,
VM_EXITCODE_HLT,
VM_EXITCODE_MTRAP,
VM_EXITCODE_PAUSE,
VM_EXITCODE_PAGING,
VM_EXITCODE_INST_EMUL,
VM_EXITCODE_SPINUP_AP,
VM_EXITCODE_DEPRECATED1, /* used to be SPINDOWN_CPU */
VM_EXITCODE_RENDEZVOUS,
VM_EXITCODE_IOAPIC_EOI,
VM_EXITCODE_SUSPENDED,
VM_EXITCODE_INOUT_STR,
VM_EXITCODE_TASK_SWITCH,
VM_EXITCODE_MONITOR,
VM_EXITCODE_MWAIT,
VM_EXITCODE_MAX
};
struct vm_inout {
uint16_t bytes:3; /* 1 or 2 or 4 */
uint16_t in:1;
uint16_t string:1;
uint16_t rep:1;
uint16_t port;
uint32_t eax; /* valid for out */
};
struct vm_inout_str {
struct vm_inout inout; /* must be the first element */
struct vm_guest_paging paging;
uint64_t rflags;
uint64_t cr0;
uint64_t index;
uint64_t count; /* rep=1 (%rcx), rep=0 (1) */
int addrsize;
enum vm_reg_name seg_name;
struct seg_desc seg_desc;
};
struct vie_op {
uint8_t op_byte; /* actual opcode byte */
uint8_t op_type; /* type of operation (e.g. MOV) */
uint16_t op_flags;
};
#define VIE_INST_SIZE 15
struct vie {
uint8_t inst[VIE_INST_SIZE]; /* instruction bytes */
uint8_t num_valid; /* size of the instruction */
uint8_t num_processed;
uint8_t addrsize:4, opsize:4; /* address and operand sizes */
uint8_t rex_w:1, /* REX prefix */
rex_r:1,
rex_x:1,
rex_b:1,
rex_present:1,
repz_present:1, /* REP/REPE/REPZ prefix */
repnz_present:1, /* REPNE/REPNZ prefix */
opsize_override:1, /* Operand size override */
addrsize_override:1, /* Address size override */
segment_override:1; /* Segment override */
uint8_t mod:2, /* ModRM byte */
reg:4,
rm:4;
uint8_t ss:2, /* SIB byte */
index:4,
base:4;
uint8_t disp_bytes;
uint8_t imm_bytes;
uint8_t scale;
int base_register; /* VM_REG_GUEST_xyz */
int index_register; /* VM_REG_GUEST_xyz */
int segment_register; /* VM_REG_GUEST_xyz */
int64_t displacement; /* optional addr displacement */
int64_t immediate; /* optional immediate operand */
uint8_t decoded; /* set to 1 if successfully decoded */
struct vie_op op; /* opcode description */
};
enum task_switch_reason {
TSR_CALL,
TSR_IRET,
TSR_JMP,
TSR_IDT_GATE /* task gate in IDT */
};
struct vm_task_switch {
uint16_t tsssel; /* new TSS selector */
int ext; /* task switch due to external event */
uint32_t errcode;
int errcode_valid; /* push 'errcode' on the new stack */
enum task_switch_reason reason;
struct vm_guest_paging paging;
};
struct vm_exit {
enum vm_exitcode exitcode;
int inst_length; /* 0 means unknown */
uint64_t rip;
union {
struct vm_inout inout;
struct vm_inout_str inout_str;
struct {
uint64_t gpa;
int fault_type;
} paging;
struct {
uint64_t gpa;
uint64_t gla;
uint64_t cs_base;
int cs_d; /* CS.D */
struct vm_guest_paging paging;
struct vie vie;
} inst_emul;
/*
* VMX specific payload. Used when there is no "better"
* exitcode to represent the VM-exit.
*/
struct {
int status; /* vmx inst status */
/*
* 'exit_reason' and 'exit_qualification' are valid
* only if 'status' is zero.
*/
uint32_t exit_reason;
uint64_t exit_qualification;
/*
* 'inst_error' and 'inst_type' are valid
* only if 'status' is non-zero.
*/
int inst_type;
int inst_error;
} vmx;
struct {
uint32_t code; /* ecx value */
uint64_t wval;
} msr;
struct {
int vcpu;
uint64_t rip;
} spinup_ap;
struct {
uint64_t rflags;
} hlt;
struct {
int vector;
} ioapic_eoi;
struct {
enum vm_suspend_how how;
} suspended;
struct vm_task_switch task_switch;
} u;
};
/* FIXME remove */
struct vm_memory_segment {
uint64_t gpa; /* in */
size_t len;
};
typedef int (*mem_region_read_t)(void *vm, int cpuid, uint64_t gpa,
uint64_t *rval, int rsize, void *arg);
typedef int (*mem_region_write_t)(void *vm, int cpuid, uint64_t gpa,
uint64_t wval, int wsize, void *arg);
uint64_t vie_size2mask(int size);
int vie_calculate_gla(enum vm_cpu_mode cpu_mode, enum vm_reg_name seg,
struct seg_desc *desc, uint64_t off, int length, int addrsize, int prot,
uint64_t *gla);
int vie_alignment_check(int cpl, int operand_size, uint64_t cr0,
uint64_t rflags, uint64_t gla);

View File

@ -0,0 +1,41 @@
/*-
* Copyright (c) 2012 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
struct xsave_limits {
int xsave_enabled;
uint64_t xcr0_allowed;
uint32_t xsave_max_size;
};
void vmm_host_state_init(void);
const struct xsave_limits *vmm_get_xsave_limits(void);

View File

@ -0,0 +1,91 @@
/*-
* Copyright (c) 2012 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <xhyve/vmm/vmm.h>
/*
* Emulate the decoded 'vie' instruction.
*
* The callbacks 'mrr' and 'mrw' emulate reads and writes to the memory region
* containing 'gpa'. 'mrarg' is an opaque argument that is passed into the
* callback functions.
*
* 'void *vm' should be 'struct vm *' when called from kernel context and
* 'struct vmctx *' when called from user context.
* s
*/
int vmm_emulate_instruction(void *vm, int cpuid, uint64_t gpa, struct vie *vie,
struct vm_guest_paging *paging, mem_region_read_t mrr,
mem_region_write_t mrw, void *mrarg);
int vie_update_register(void *vm, int vcpuid, enum vm_reg_name reg,
uint64_t val, int size);
/* Returns 1 if the 'gla' is not canonical and 0 otherwise. */
int vie_canonical_check(enum vm_cpu_mode cpu_mode, uint64_t gla);
/*
* APIs to fetch and decode the instruction from nested page fault handler.
*
* 'vie' must be initialized before calling 'vmm_fetch_instruction()'
*/
int vmm_fetch_instruction(struct vm *vm, int cpuid,
struct vm_guest_paging *guest_paging,
uint64_t rip, int inst_length, struct vie *vie,
int *is_fault);
/*
* Translate the guest linear address 'gla' to a guest physical address.
*
* retval is_fault Interpretation
* 0 0 'gpa' contains result of the translation
* 0 1 An exception was injected into the guest
* EFAULT N/A An unrecoverable hypervisor error occurred
*/
int vm_gla2gpa(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
uint64_t gla, int prot, uint64_t *gpa, int *is_fault);
void vie_init(struct vie *vie, const char *inst_bytes, int inst_length);
/*
* Decode the instruction fetched into 'vie' so it can be emulated.
*
* 'gla' is the guest linear address provided by the hardware assist
* that caused the nested page table fault. It is used to verify that
* the software instruction decoding is in agreement with the hardware.
*
* Some hardware assists do not provide the 'gla' to the hypervisor.
* To skip the 'gla' verification for this or any other reason pass
* in VIE_INVALID_GLA instead.
*/
#define VIE_INVALID_GLA (1UL << 63) /* a non-canonical address */
int vmm_decode_instruction(struct vm *vm, int cpuid, uint64_t gla,
enum vm_cpu_mode cpu_mode, int csd, struct vie *vie);

View File

@ -0,0 +1,40 @@
/*-
* Copyright (c) 2014 Tycho Nightingale <tycho.nightingale@pluribusnetworks.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
struct vm;
struct vm_exit;
typedef int (*ioport_handler_func_t)(struct vm *vm, int vcpuid,
bool in, int port, int bytes, uint32_t *val);
int vm_handle_inout(struct vm *vm, int vcpuid, struct vm_exit *vme, bool *retu);

View File

@ -0,0 +1,72 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdio.h>
#ifdef XHYVE_CONFIG_TRACE
#define vmmtrace printf
#else
#define vmmtrace if (0) printf
#endif
struct vm;
extern const char *vm_name(struct vm *vm);
#define VCPU_CTR0(vm, vcpuid, format) \
vmmtrace("vm %s[%d]: " format "\n", vm_name((vm)), (vcpuid))
#define VCPU_CTR1(vm, vcpuid, format, p1) \
vmmtrace("vm %s[%d]: " format "\n", vm_name((vm)), (vcpuid), (p1))
#define VCPU_CTR2(vm, vcpuid, format, p1, p2) \
vmmtrace("vm %s[%d]: " format "\n", vm_name((vm)), (vcpuid), (p1), (p2))
#define VCPU_CTR3(vm, vcpuid, format, p1, p2, p3) \
vmmtrace("vm %s[%d]: " format "\n", vm_name((vm)), (vcpuid), (p1), (p2), (p3))
#define VCPU_CTR4(vm, vcpuid, format, p1, p2, p3, p4) \
vmmtrace("vm %s[%d]: " format "\n", vm_name((vm)), (vcpuid), \
(p1), (p2), (p3), (p4))
#define VM_CTR0(vm, format) \
vmmtrace("vm %s: " format "\n", vm_name((vm)))
#define VM_CTR1(vm, format, p1) \
vmmtrace("vm %s: " format "\n", vm_name((vm)), (p1))
#define VM_CTR2(vm, format, p1, p2) \
vmmtrace("vm %s: " format "\n", vm_name((vm)), (p1), (p2))
#define VM_CTR3(vm, format, p1, p2, p3) \
vmmtrace("vm %s: " format "\n", vm_name((vm)), (p1), (p2), (p3))
#define VM_CTR4(vm, format, p1, p2, p3, p4) \
vmmtrace("vm %s: " format "\n", vm_name((vm)), (p1), (p2), (p3), (p4))

View File

@ -0,0 +1,76 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <xhyve/support/misc.h>
struct vm;
bool lapic_msr(u_int num);
int lapic_rdmsr(struct vm *vm, int cpu, u_int msr, uint64_t *rval,
bool *retu);
int lapic_wrmsr(struct vm *vm, int cpu, u_int msr, uint64_t wval,
bool *retu);
int lapic_mmio_read(void *vm, int cpu, uint64_t gpa,
uint64_t *rval, int size, void *arg);
int lapic_mmio_write(void *vm, int cpu, uint64_t gpa,
uint64_t wval, int size, void *arg);
/*
* Signals to the LAPIC that an interrupt at 'vector' needs to be generated
* to the 'cpu', the state is recorded in IRR.
*/
int lapic_set_intr(struct vm *vm, int cpu, int vector, bool trig);
#define LAPIC_TRIG_LEVEL true
#define LAPIC_TRIG_EDGE false
static __inline int
lapic_intr_level(struct vm *vm, int cpu, int vector)
{
return (lapic_set_intr(vm, cpu, vector, LAPIC_TRIG_LEVEL));
}
static __inline int
lapic_intr_edge(struct vm *vm, int cpu, int vector)
{
return (lapic_set_intr(vm, cpu, vector, LAPIC_TRIG_EDGE));
}
/*
* Triggers the LAPIC local interrupt (LVT) 'vector' on 'cpu'. 'cpu' can
* be set to -1 to trigger the interrupt on all CPUs.
*/
int lapic_set_local_intr(struct vm *vm, int cpu, int vector);
int lapic_intr_msi(struct vm *vm, uint64_t addr, uint64_t msg);

View File

@ -0,0 +1,40 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <stdlib.h>
struct vmspace;
int vmm_mem_init(void);
void *vmm_mem_alloc(uint64_t gpa, size_t size);
void vmm_mem_free(uint64_t gpa, size_t size, void *object);
void vmm_mem_protect(uint64_t gpa, size_t size);
void vmm_mem_unprotect(uint64_t gpa, size_t size);

View File

@ -0,0 +1,182 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
struct vm;
#define MAX_VMM_STAT_ELEMS 64 /* arbitrary */
enum vmm_stat_scope {
VMM_STAT_SCOPE_ANY,
VMM_STAT_SCOPE_INTEL, /* Intel VMX specific statistic */
VMM_STAT_SCOPE_AMD, /* AMD SVM specific statistic */
};
struct vmm_stat_type;
typedef void (*vmm_stat_func_t)(struct vm *vm, int vcpu,
struct vmm_stat_type *stat);
struct vmm_stat_type {
int index; /* position in the stats buffer */
int nelems; /* standalone or array */
const char *desc; /* description of statistic */
vmm_stat_func_t func;
enum vmm_stat_scope scope;
};
void vmm_stat_register(void *arg);
#define VMM_STAT_FDEFINE(type, nelems, desc, func, scope) \
struct vmm_stat_type type[1] = { \
{ -1, nelems, desc, func, scope } \
}
//}; \
// SYSINIT(type##_stat, SI_SUB_KLD, SI_ORDER_ANY, vmm_stat_register, type)
#define VMM_STAT_DEFINE(type, nelems, desc, scope) \
VMM_STAT_FDEFINE(type, nelems, desc, NULL, scope)
#define VMM_STAT_DECLARE(type) \
extern struct vmm_stat_type type[1]
#define VMM_STAT(type, desc) \
VMM_STAT_DEFINE(type, 1, desc, VMM_STAT_SCOPE_ANY)
#define VMM_STAT_INTEL(type, desc) \
VMM_STAT_DEFINE(type, 1, desc, VMM_STAT_SCOPE_INTEL)
#define VMM_STAT_FUNC(type, desc, func) \
VMM_STAT_FDEFINE(type, 1, desc, func, VMM_STAT_SCOPE_ANY)
#define VMM_STAT_ARRAY(type, nelems, desc) \
VMM_STAT_DEFINE(type, nelems, desc, VMM_STAT_SCOPE_ANY)
void *vmm_stat_alloc(void);
void vmm_stat_init(void *vp);
void vmm_stat_free(void *vp);
/*
* 'buf' should be at least fit 'MAX_VMM_STAT_TYPES' entries
*/
int vmm_stat_copy(struct vm *vm, int vcpu, int *num_stats, uint64_t *buf);
int vmm_stat_desc_copy(int index, char *buf, size_t buflen);
static void __inline
vmm_stat_array_incr(struct vm *vm, int vcpu, struct vmm_stat_type *vst,
int statidx, uint64_t x)
{
#ifdef XHYVE_CONFIG_STATS
uint64_t *stats;
stats = vcpu_stats(vm, vcpu);
if (vst->index >= 0 && statidx < vst->nelems)
stats[vst->index + statidx] += x;
#else
(void) vm;
(void) vcpu;
(void) vst;
(void) statidx;
(void) x;
#endif
}
static void __inline
vmm_stat_array_set(struct vm *vm, int vcpu, struct vmm_stat_type *vst,
int statidx, uint64_t val)
{
#ifdef XHYVE_CONFIG_STATS
uint64_t *stats;
stats = vcpu_stats(vm, vcpu);
if (vst->index >= 0 && statidx < vst->nelems)
stats[vst->index + statidx] = val;
#else
(void) vm;
(void) vcpu;
(void) vst;
(void) statidx;
(void) val;
#endif
}
static void __inline
vmm_stat_incr(struct vm *vm, int vcpu, struct vmm_stat_type *vst, uint64_t x)
{
#ifdef XHYVE_CONFIG_STATS
vmm_stat_array_incr(vm, vcpu, vst, 0, x);
#else
(void) vm;
(void) vcpu;
(void) vst;
(void) x;
#endif
}
static void __inline
vmm_stat_set(struct vm *vm, int vcpu, struct vmm_stat_type *vst, uint64_t val)
{
#ifdef XHYVE_CONFIG_STATS
vmm_stat_array_set(vm, vcpu, vst, 0, val);
#else
(void) vm;
(void) vcpu;
(void) vst;
(void) val;
#endif
}
VMM_STAT_DECLARE(VCPU_MIGRATIONS);
VMM_STAT_DECLARE(VMEXIT_COUNT);
VMM_STAT_DECLARE(VMEXIT_EXTINT);
VMM_STAT_DECLARE(VMEXIT_HLT);
VMM_STAT_DECLARE(VMEXIT_CR_ACCESS);
VMM_STAT_DECLARE(VMEXIT_RDMSR);
VMM_STAT_DECLARE(VMEXIT_WRMSR);
VMM_STAT_DECLARE(VMEXIT_MTRAP);
VMM_STAT_DECLARE(VMEXIT_PAUSE);
VMM_STAT_DECLARE(VMEXIT_INTR_WINDOW);
VMM_STAT_DECLARE(VMEXIT_NMI_WINDOW);
VMM_STAT_DECLARE(VMEXIT_INOUT);
VMM_STAT_DECLARE(VMEXIT_CPUID);
VMM_STAT_DECLARE(VMEXIT_NESTED_FAULT);
VMM_STAT_DECLARE(VMEXIT_INST_EMUL);
VMM_STAT_DECLARE(VMEXIT_UNKNOWN);
VMM_STAT_DECLARE(VMEXIT_ASTPENDING);
VMM_STAT_DECLARE(VMEXIT_USERSPACE);
VMM_STAT_DECLARE(VMEXIT_RENDEZVOUS);
VMM_STAT_DECLARE(VMEXIT_EXCEPTION);

View File

@ -0,0 +1,33 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
struct trapframe;
void dump_trapframe(struct trapframe *tf);

View File

@ -0,0 +1,64 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#define CPUID_0000_0000 (0x0)
#define CPUID_0000_0001 (0x1)
#define CPUID_0000_0002 (0x2)
#define CPUID_0000_0003 (0x3)
#define CPUID_0000_0004 (0x4)
#define CPUID_0000_0006 (0x6)
#define CPUID_0000_0007 (0x7)
#define CPUID_0000_000A (0xA)
#define CPUID_0000_000B (0xB)
#define CPUID_0000_000D (0xD)
#define CPUID_8000_0000 (0x80000000)
#define CPUID_8000_0001 (0x80000001)
#define CPUID_8000_0002 (0x80000002)
#define CPUID_8000_0003 (0x80000003)
#define CPUID_8000_0004 (0x80000004)
#define CPUID_8000_0006 (0x80000006)
#define CPUID_8000_0007 (0x80000007)
#define CPUID_8000_0008 (0x80000008)
/*
* CPUID instruction Fn0000_0001:
*/
#define CPUID_0000_0001_APICID_MASK (0xff<<24)
#define CPUID_0000_0001_APICID_SHIFT 24
/*
* CPUID instruction Fn0000_0001 ECX
*/
#define CPUID_0000_0001_FEAT0_VMX (1<<5)
int x86_emulate_cpuid(struct vm *vm, int vcpu_id, uint32_t *eax, uint32_t *ebx,
uint32_t *ecx, uint32_t *edx);

View File

@ -0,0 +1,81 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
#include <xhyve/support/segments.h>
#ifndef CTASSERT /* Allow lint to override */
#define CTASSERT(x) _CTASSERT(x, __LINE__)
#define _CTASSERT(x, y) __CTASSERT(x, y)
#define __CTASSERT(x, y) typedef char __assert ## y[(x) ? 1 : -1]
#endif
#define VMEXIT_CONTINUE (0)
#define VMEXIT_ABORT (-1)
extern int guest_ncpus;
extern int print_mac;
extern char *guest_uuid_str;
extern char *vmname;
void xh_vm_inject_fault(int vcpu, int vector, int errcode_valid,
uint32_t errcode);
static __inline void
vm_inject_ud(int vcpuid)
{
xh_vm_inject_fault(vcpuid, IDT_UD, 0, 0);
}
static __inline void
vm_inject_gp(int vcpuid)
{
xh_vm_inject_fault(vcpuid, IDT_GP, 1, 0);
}
static __inline void
vm_inject_ac(int vcpuid, uint32_t errcode)
{
xh_vm_inject_fault(vcpuid, IDT_AC, 1, errcode);
}
static __inline void
vm_inject_ss(int vcpuid, uint32_t errcode)
{
xh_vm_inject_fault(vcpuid, IDT_SS, 1, errcode);
}
void *paddr_guest2host(uintptr_t addr, size_t len);
void vcpu_set_capabilities(int cpu);
void vcpu_add(int fromcpu, int newcpu, uint64_t rip);
int fbsdrun_vmexit_on_hlt(void);
int fbsdrun_vmexit_on_pause(void);
int fbsdrun_virtio_msix(void);

View File

@ -0,0 +1,35 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
int init_msr(void);
int emulate_wrmsr(int vcpu, uint32_t code, uint64_t val);
int emulate_rdmsr(int vcpu, uint32_t code, uint64_t *val);

1125
vendor/github.com/docker/hyperkit/src/lib/acpitbl.c generated vendored Normal file

File diff suppressed because it is too large Load Diff

81
vendor/github.com/docker/hyperkit/src/lib/atkbdc.c generated vendored Normal file
View File

@ -0,0 +1,81 @@
/*-
* Copyright (c) 2014 Tycho Nightingale <tycho.nightingale@pluribusnetworks.com>
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <stdint.h>
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <xhyve/support/misc.h>
#include <xhyve/vmm/vmm_api.h>
#include <xhyve/inout.h>
#include <xhyve/pci_lpc.h>
#define KBD_DATA_PORT 0x60
#define KBD_STS_CTL_PORT 0x64
#define KBD_SYS_FLAG 0x4
#define KBDC_RESET 0xfe
static int
atkbdc_data_handler(UNUSED int vcpu, UNUSED int in, UNUSED int port, int bytes,
uint32_t *eax, UNUSED void *arg)
{
if (bytes != 1)
return (-1);
*eax = 0;
return (0);
}
static int
atkbdc_sts_ctl_handler(UNUSED int vcpu, int in, UNUSED int port, int bytes,
uint32_t *eax, UNUSED void *arg)
{
int error, retval;
if (bytes != 1)
return (-1);
retval = 0;
if (in) {
*eax = KBD_SYS_FLAG; /* system passed POST */
} else {
switch (*eax) {
case KBDC_RESET: /* Pulse "reset" line. */
error = xh_vm_suspend(VM_SUSPEND_RESET);
assert(error == 0 || errno == EALREADY);
break;
}
}
return (retval);
}
INOUT_PORT(atkdbc, KBD_DATA_PORT, IOPORT_F_INOUT, atkbdc_data_handler);
SYSRES_IO(KBD_DATA_PORT, 1);
INOUT_PORT(atkbdc, KBD_STS_CTL_PORT, IOPORT_F_INOUT, atkbdc_sts_ctl_handler);
SYSRES_IO(KBD_STS_CTL_PORT, 1);

1041
vendor/github.com/docker/hyperkit/src/lib/block_if.c generated vendored Normal file

File diff suppressed because it is too large Load Diff

152
vendor/github.com/docker/hyperkit/src/lib/consport.c generated vendored Normal file
View File

@ -0,0 +1,152 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/select.h>
#include <xhyve/support/misc.h>
#include <xhyve/inout.h>
#include <xhyve/pci_lpc.h>
#define BVM_CONSOLE_PORT 0x220
#define BVM_CONS_SIG ('b' << 8 | 'v')
static struct termios tio_orig, tio_new;
static void
ttyclose(void)
{
tcsetattr(STDIN_FILENO, TCSANOW, &tio_orig);
}
static void
ttyopen(void)
{
tcgetattr(STDIN_FILENO, &tio_orig);
cfmakeraw(&tio_new);
tcsetattr(STDIN_FILENO, TCSANOW, &tio_new);
atexit(ttyclose);
}
static bool
tty_char_available(void)
{
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(STDIN_FILENO, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
if (select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv) > 0) {
return (true);
} else {
return (false);
}
}
static int
ttyread(void)
{
char rb;
if (tty_char_available()) {
read(STDIN_FILENO, &rb, 1);
return (rb & 0xff);
} else {
return (-1);
}
}
static void
ttywrite(unsigned char wb)
{
(void) write(STDOUT_FILENO, &wb, 1);
}
static int
console_handler(UNUSED int vcpu, int in, UNUSED int port, int bytes,
uint32_t *eax, UNUSED void *arg)
{
static int opened;
if (bytes == 2 && in) {
*eax = BVM_CONS_SIG;
return (0);
}
/*
* Guests might probe this port to look for old ISA devices
* using single-byte reads. Return 0xff for those.
*/
if (bytes == 1 && in) {
*eax = 0xff;
return (0);
}
if (bytes != 4)
return (-1);
if (!opened) {
ttyopen();
opened = 1;
}
if (in)
*eax = (uint32_t) ttyread();
else
ttywrite((unsigned char) *eax);
return (0);
}
SYSRES_IO(BVM_CONSOLE_PORT, 4);
static struct inout_port consport = {
"bvmcons",
BVM_CONSOLE_PORT,
1,
IOPORT_F_INOUT,
console_handler,
NULL
};
void
init_bvmcons(void)
{
register_inout(&consport);
}

142
vendor/github.com/docker/hyperkit/src/lib/dbgport.c generated vendored Normal file
View File

@ -0,0 +1,142 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/uio.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <xhyve/support/misc.h>
#include <xhyve/inout.h>
#include <xhyve/dbgport.h>
#include <xhyve/pci_lpc.h>
#define BVM_DBG_PORT 0x224
#define BVM_DBG_SIG ('B' << 8 | 'V')
static int listen_fd, conn_fd;
static struct sockaddr_in saddrin;
static int
dbg_handler(UNUSED int vcpu, int in, UNUSED int port, int bytes, uint32_t *eax,
UNUSED void *arg)
{
char ch;
int nwritten, nread, printonce;
if (bytes == 2 && in) {
*eax = BVM_DBG_SIG;
return (0);
}
if (bytes != 4)
return (-1);
again:
printonce = 0;
while (conn_fd < 0) {
if (!printonce) {
printf("Waiting for connection from gdb\r\n");
printonce = 1;
}
conn_fd = accept(listen_fd, NULL, NULL);
if (conn_fd >= 0)
fcntl(conn_fd, F_SETFL, O_NONBLOCK);
else if (errno != EINTR)
perror("accept");
}
if (in) {
nread = (int) read(conn_fd, &ch, 1);
if (nread == -1 && errno == EAGAIN)
*eax = (uint32_t) (-1);
else if (nread == 1)
*eax = (uint32_t) ch;
else {
close(conn_fd);
conn_fd = -1;
goto again;
}
} else {
ch = (char) *eax;
nwritten = (int) write(conn_fd, &ch, 1);
if (nwritten != 1) {
close(conn_fd);
conn_fd = -1;
goto again;
}
}
return (0);
}
static struct inout_port dbgport = {
"bvmdbg",
BVM_DBG_PORT,
1,
IOPORT_F_INOUT,
dbg_handler,
NULL
};
SYSRES_IO(BVM_DBG_PORT, 4);
void
init_dbgport(int sport)
{
conn_fd = -1;
if ((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
saddrin.sin_len = sizeof(saddrin);
saddrin.sin_family = AF_INET;
saddrin.sin_addr.s_addr = htonl(INADDR_ANY);
saddrin.sin_port = htons(sport);
if (bind(listen_fd, (struct sockaddr *)&saddrin, sizeof(saddrin)) < 0) {
perror("bind");
exit(1);
}
if (listen(listen_fd, 1) < 0) {
perror("listen");
exit(1);
}
register_inout(&dbgport);
}

315
vendor/github.com/docker/hyperkit/src/lib/inout.c generated vendored Normal file
View File

@ -0,0 +1,315 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <sys/uio.h>
#include <xhyve/support/misc.h>
#include <xhyve/support/linker_set.h>
#include <xhyve/support/psl.h>
#include <xhyve/support/segments.h>
#include <xhyve/vmm/vmm_api.h>
#include <xhyve/xhyve.h>
#include <xhyve/inout.h>
SET_DECLARE(inout_port_set, struct inout_port);
#define MAX_IOPORTS (1 << 16)
#define VERIFY_IOPORT(port, size) \
assert((port) >= 0 && (size) > 0 && ((port) + (size)) <= MAX_IOPORTS)
static struct {
const char *name;
int flags;
inout_func_t handler;
void *arg;
} inout_handlers[MAX_IOPORTS];
static int
default_inout(UNUSED int vcpu, int in, UNUSED int port, int bytes,
uint32_t *eax, UNUSED void *arg)
{
if (in) {
switch (bytes) {
case 4:
*eax = 0xffffffff;
break;
case 2:
*eax = 0xffff;
break;
case 1:
*eax = 0xff;
break;
}
}
return (0);
}
static void
register_default_iohandler(int start, int size)
{
struct inout_port iop;
VERIFY_IOPORT(start, size);
bzero(&iop, sizeof(iop));
iop.name = "default";
iop.port = start;
iop.size = size;
iop.flags = (int)(IOPORT_F_INOUT | IOPORT_F_DEFAULT);
iop.handler = default_inout;
register_inout(&iop);
}
static int
update_register(int vcpuid, enum vm_reg_name reg,
uint64_t val, int size)
{
int error;
uint64_t origval;
switch (size) {
case 1:
case 2:
error = xh_vm_get_register(vcpuid, reg, &origval);
if (error)
return (error);
val &= vie_size2mask(size);
val |= origval & ~vie_size2mask(size);
break;
case 4:
val &= 0xffffffffUL;
break;
case 8:
break;
default:
return (EINVAL);
}
return xh_vm_set_register(vcpuid, reg, val);
}
int
emulate_inout(int vcpu, struct vm_exit *vmexit, int strict)
{
int addrsize, bytes, flags, in, port, prot, rep;
uint32_t eax, val;
inout_func_t handler;
void *arg;
int error, fault, retval;
enum vm_reg_name idxreg;
uint64_t gla, index, iterations, count;
struct vm_inout_str *vis;
struct iovec iov[2];
bytes = vmexit->u.inout.bytes;
in = vmexit->u.inout.in;
port = vmexit->u.inout.port;
assert(port < MAX_IOPORTS);
assert(bytes == 1 || bytes == 2 || bytes == 4);
handler = inout_handlers[port].handler;
if (strict && handler == default_inout)
return (-1);
flags = inout_handlers[port].flags;
arg = inout_handlers[port].arg;
if (in) {
if (!(flags & IOPORT_F_IN))
return (-1);
} else {
if (!(flags & IOPORT_F_OUT))
return (-1);
}
retval = 0;
if (vmexit->u.inout.string) {
vis = &vmexit->u.inout_str;
rep = vis->inout.rep;
addrsize = vis->addrsize;
prot = in ? XHYVE_PROT_WRITE : XHYVE_PROT_READ;
assert(addrsize == 2 || addrsize == 4 || addrsize == 8);
/* Index register */
idxreg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
index = vis->index & vie_size2mask(addrsize);
/* Count register */
count = vis->count & vie_size2mask(addrsize);
/* Limit number of back-to-back in/out emulations to 16 */
iterations = min(count, 16);
while (iterations > 0) {
assert(retval == 0);
if (vie_calculate_gla(vis->paging.cpu_mode,
vis->seg_name, &vis->seg_desc, index, bytes,
addrsize, prot, &gla)) {
vm_inject_gp(vcpu);
break;
}
error = xh_vm_copy_setup(vcpu, &vis->paging, gla,
(size_t)bytes, prot, iov, nitems(iov), &fault);
if (error) {
retval = -1; /* Unrecoverable error */
break;
} else if (fault) {
retval = 0; /* Resume guest to handle fault */
break;
}
if (vie_alignment_check(vis->paging.cpl, bytes,
vis->cr0, vis->rflags, gla)) {
vm_inject_ac(vcpu, 0);
break;
}
val = 0;
if (!in)
xh_vm_copyin(iov, &val, (size_t)bytes);
retval = handler(vcpu, in, port, bytes, &val, arg);
if (retval != 0)
break;
if (in)
xh_vm_copyout(&val, iov, (size_t)bytes);
/* Update index */
if (vis->rflags & PSL_D)
index -= (uint64_t)bytes;
else
index += (uint64_t)bytes;
count--;
iterations--;
}
/* Update index register */
error = update_register(vcpu, idxreg, index, addrsize);
assert(error == 0);
/*
* Update count register only if the instruction had a repeat
* prefix.
*/
if (rep) {
error = update_register(vcpu, VM_REG_GUEST_RCX, count, addrsize);
assert(error == 0);
}
/* Restart the instruction if more iterations remain */
if (retval == 0 && count != 0) {
error = xh_vm_restart_instruction(vcpu);
assert(error == 0);
}
} else {
eax = vmexit->u.inout.eax;
val = eax & vie_size2mask(bytes);
retval = handler(vcpu, in, port, bytes, &val, arg);
if (retval == 0 && in) {
eax &= ~vie_size2mask(bytes);
eax |= val & vie_size2mask(bytes);
error = xh_vm_set_register(vcpu, VM_REG_GUEST_RAX, eax);
assert(error == 0);
}
}
return (retval);
}
void
init_inout(void)
{
struct inout_port **iopp, *iop;
/*
* Set up the default handler for all ports
*/
register_default_iohandler(0, MAX_IOPORTS);
/*
* Overwrite with specified handlers
*/
SET_FOREACH(iopp, inout_port_set) {
iop = *iopp;
assert(iop->port < MAX_IOPORTS);
inout_handlers[iop->port].name = iop->name;
inout_handlers[iop->port].flags = iop->flags;
inout_handlers[iop->port].handler = iop->handler;
inout_handlers[iop->port].arg = NULL;
}
}
int
register_inout(struct inout_port *iop)
{
int i;
VERIFY_IOPORT(iop->port, iop->size);
/*
* Verify that the new registration is not overwriting an already
* allocated i/o range.
*/
if (((unsigned)iop->flags & IOPORT_F_DEFAULT) == 0) {
for (i = iop->port; i < iop->port + iop->size; i++) {
if (((unsigned)inout_handlers[i].flags & IOPORT_F_DEFAULT) == 0)
return (-1);
}
}
for (i = iop->port; i < iop->port + iop->size; i++) {
inout_handlers[i].name = iop->name;
inout_handlers[i].flags = iop->flags;
inout_handlers[i].handler = iop->handler;
inout_handlers[i].arg = iop->arg;
}
return (0);
}
int
unregister_inout(struct inout_port *iop)
{
VERIFY_IOPORT(iop->port, iop->size);
assert(inout_handlers[iop->port].name == iop->name);
register_default_iohandler(iop->port, iop->size);
return (0);
}

68
vendor/github.com/docker/hyperkit/src/lib/ioapic.c generated vendored Normal file
View File

@ -0,0 +1,68 @@
/*-
* Copyright (c) 2014 Hudson River Trading LLC
* Written by: John H. Baldwin <jhb@FreeBSD.org>
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <xhyve/vmm/vmm_api.h>
#include <xhyve/ioapic.h>
/*
* Assign PCI INTx interrupts to I/O APIC pins in a round-robin
* fashion. Note that we have no idea what the HPET is using, but the
* HPET is also programmable whereas this is intended for hardwired
* PCI interrupts.
*
* This assumes a single I/O APIC where pins >= 16 are permitted for
* PCI devices.
*/
static int pci_pins;
void
ioapic_init(void)
{
if (xh_vm_ioapic_pincount(&pci_pins) < 0) {
pci_pins = 0;
return;
}
/* Ignore the first 16 pins. */
if (pci_pins <= 16) {
pci_pins = 0;
return;
}
pci_pins -= 16;
}
int
ioapic_pci_alloc_irq(void)
{
static int last_pin;
if (pci_pins == 0)
return (-1);
return (16 + (last_pin++ % pci_pins));
}

284
vendor/github.com/docker/hyperkit/src/lib/md5c.c generated vendored Normal file
View File

@ -0,0 +1,284 @@
/*-
* MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm
*
* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
* rights reserved.
*
* License to copy and use this software is granted provided that it
* is identified as the "RSA Data Security, Inc. MD5 Message-Digest
* Algorithm" in all material mentioning or referencing this software
* or this function.
*
* License is also granted to make and use derivative works provided
* that such works are identified as "derived from the RSA Data
* Security, Inc. MD5 Message-Digest Algorithm" in all material
* mentioning or referencing the derived work.
*
* RSA Data Security, Inc. makes no representations concerning either
* the merchantability of this software or the suitability of this
* software for any particular purpose. It is provided "as is"
* without express or implied warranty of any kind.
*
* These notices must be retained in any copies of any part of this
* documentation and/or software.
*
* This code is the same as the code published by RSA Inc. It has been
* edited for clarity and style only.
*/
#include <stdint.h>
#include <string.h>
#include <xhyve/support/md5.h>
static void MD5Transform(u_int32_t [4], const unsigned char [64]);
static unsigned char PADDING[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/* F, G, H and I are basic MD5 functions. */
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
/* ROTATE_LEFT rotates x left n bits. */
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/*
* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
* Rotation is separate from addition to prevent recomputation.
*/
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + (u_int32_t)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + (u_int32_t)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + (u_int32_t)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + (u_int32_t)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
/* MD5 initialization. Begins an MD5 operation, writing a new context. */
void
MD5Init(context)
MD5_CTX *context;
{
context->count[0] = context->count[1] = 0;
/* Load magic initialization constants. */
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
context->state[3] = 0x10325476;
}
/*
* MD5 block update operation. Continues an MD5 message-digest
* operation, processing another message block, and updating the
* context.
*/
void
MD5Update(context, in, inputLen)
MD5_CTX *context;
const void *in;
unsigned int inputLen;
{
unsigned int i, index, partLen;
const unsigned char *input = in;
/* Compute number of bytes mod 64 */
index = (unsigned int)((context->count[0] >> 3) & 0x3F);
/* Update number of bits */
if ((context->count[0] += ((u_int32_t)inputLen << 3))
< ((u_int32_t)inputLen << 3))
context->count[1]++;
context->count[1] += ((u_int32_t)inputLen >> 29);
partLen = 64 - index;
/* Transform as many times as possible. */
if (inputLen >= partLen) {
memcpy((void *)&context->buffer[index], (const void *)input,
partLen);
MD5Transform(context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64)
MD5Transform(context->state, &input[i]);
index = 0;
}
else
i = 0;
/* Buffer remaining input */
memcpy((void *)&context->buffer[index], (const void *)&input[i],
inputLen-i);
}
/*
* MD5 padding. Adds padding followed by original length.
*/
static void
MD5Pad(MD5_CTX *context)
{
unsigned char bits[8];
unsigned int index, padLen;
/* Save number of bits */
memcpy(bits, context->count, 8);
/* Pad out to 56 mod 64. */
index = (unsigned int)((context->count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
MD5Update(context, PADDING, padLen);
/* Append length (before padding) */
MD5Update(context, bits, 8);
}
/*
* MD5 finalization. Ends an MD5 message-digest operation, writing the
* the message digest and zeroizing the context.
*/
void
MD5Final (digest, context)
unsigned char digest[16];
MD5_CTX *context;
{
/* Do padding. */
MD5Pad(context);
/* Store state in digest */
memcpy(digest, context->state, 16);
/* Zeroize sensitive information. */
memset((void *)context, 0, sizeof (*context));
}
/* MD5 basic transformation. Transforms state based on block. */
static void
MD5Transform (state, block)
u_int32_t state[4];
const unsigned char block[64];
{
u_int32_t a = state[0], b = state[1], c = state[2], d = state[3], x[16];
memcpy(x, block, 64);
/* Round 1 */
#define S11 7
#define S12 12
#define S13 17
#define S14 22
FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
#define S21 5
#define S22 9
#define S23 14
#define S24 20
GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
#define S31 4
#define S32 11
#define S33 16
#define S34 23
HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
#define S41 6
#define S42 10
#define S43 15
#define S44 21
II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
/* Zeroize sensitive information. */
memset((void *)x, 0, sizeof (x));
}

288
vendor/github.com/docker/hyperkit/src/lib/mem.c generated vendored Normal file
View File

@ -0,0 +1,288 @@
/*-
* Copyright (c) 2012 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
/*
* Memory ranges are represented with an RB tree. On insertion, the range
* is checked for overlaps. On lookup, the key has the same base and limit
* so it can be searched within the range.
*/
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <assert.h>
#include <xhyve/support/misc.h>
#include <xhyve/support/tree.h>
#include <xhyve/vmm/vmm_api.h>
#include <xhyve/mem.h>
struct mmio_rb_range {
RB_ENTRY(mmio_rb_range) mr_link; /* RB tree links */
struct mem_range mr_param;
uint64_t mr_base;
uint64_t mr_end;
};
struct mmio_rb_tree;
RB_PROTOTYPE(mmio_rb_tree, mmio_rb_range, mr_link, mmio_rb_range_compare);
static RB_HEAD(mmio_rb_tree, mmio_rb_range) mmio_rb_root, mmio_rb_fallback;
/*
* Per-vCPU cache. Since most accesses from a vCPU will be to
* consecutive addresses in a range, it makes sense to cache the
* result of a lookup.
*/
static struct mmio_rb_range *mmio_hint[VM_MAXCPU];
static pthread_rwlock_t mmio_rwlock;
static int
mmio_rb_range_compare(struct mmio_rb_range *a, struct mmio_rb_range *b)
{
if (a->mr_end < b->mr_base)
return (-1);
else if (a->mr_base > b->mr_end)
return (1);
return (0);
}
static int
mmio_rb_lookup(struct mmio_rb_tree *rbt, uint64_t addr,
struct mmio_rb_range **entry)
{
struct mmio_rb_range find, *res;
find.mr_base = find.mr_end = addr;
res = RB_FIND(mmio_rb_tree, rbt, &find);
if (res != NULL) {
*entry = res;
return (0);
}
return (ENOENT);
}
static int
mmio_rb_add(struct mmio_rb_tree *rbt, struct mmio_rb_range *new)
{
struct mmio_rb_range *overlap;
overlap = RB_INSERT(mmio_rb_tree, rbt, new);
if (overlap != NULL) {
#ifdef RB_DEBUG
printf("overlap detected: new %lx:%lx, tree %lx:%lx\n",
new->mr_base, new->mr_end,
overlap->mr_base, overlap->mr_end);
#endif
return (EEXIST);
}
return (0);
}
#if 0
static void
mmio_rb_dump(struct mmio_rb_tree *rbt)
{
struct mmio_rb_range *np;
pthread_rwlock_rdlock(&mmio_rwlock);
RB_FOREACH(np, mmio_rb_tree, rbt) {
printf(" %lx:%lx, %s\n", np->mr_base, np->mr_end,
np->mr_param.name);
}
pthread_rwlock_unlock(&mmio_rwlock);
}
#endif
RB_GENERATE(mmio_rb_tree, mmio_rb_range, mr_link, mmio_rb_range_compare)
static int
mem_read(UNUSED void *unused, int vcpu, uint64_t gpa, uint64_t *rval, int size,
void *arg)
{
int error;
struct mem_range *mr = arg;
error = (*mr->handler)(vcpu, MEM_F_READ, gpa, size, rval, mr->arg1,
mr->arg2);
return (error);
}
static int
mem_write(UNUSED void* unused, int vcpu, uint64_t gpa, uint64_t wval, int size,
void *arg)
{
int error;
struct mem_range *mr = arg;
error = (*mr->handler)(vcpu, MEM_F_WRITE, gpa, size, &wval, mr->arg1,
mr->arg2);
return (error);
}
int
emulate_mem(int vcpu, uint64_t paddr, struct vie *vie,
struct vm_guest_paging *paging)
{
struct mmio_rb_range *entry;
int err, immutable;
pthread_rwlock_rdlock(&mmio_rwlock);
/*
* First check the per-vCPU cache
*/
if (mmio_hint[vcpu] &&
paddr >= mmio_hint[vcpu]->mr_base &&
paddr <= mmio_hint[vcpu]->mr_end) {
entry = mmio_hint[vcpu];
} else
entry = NULL;
if (entry == NULL) {
if (mmio_rb_lookup(&mmio_rb_root, paddr, &entry) == 0) {
/* Update the per-vCPU cache */
mmio_hint[vcpu] = entry;
} else if (mmio_rb_lookup(&mmio_rb_fallback, paddr, &entry)) {
pthread_rwlock_unlock(&mmio_rwlock);
return (ESRCH);
}
}
assert(entry != NULL);
/*
* An 'immutable' memory range is guaranteed to be never removed
* so there is no need to hold 'mmio_rwlock' while calling the
* handler.
*
* XXX writes to the PCIR_COMMAND register can cause register_mem()
* to be called. If the guest is using PCI extended config space
* to modify the PCIR_COMMAND register then register_mem() can
* deadlock on 'mmio_rwlock'. However by registering the extended
* config space window as 'immutable' the deadlock can be avoided.
*/
immutable = (entry->mr_param.flags & MEM_F_IMMUTABLE);
if (immutable)
pthread_rwlock_unlock(&mmio_rwlock);
err = xh_vm_emulate_instruction(vcpu, paddr, vie, paging, mem_read,
mem_write, &entry->mr_param);
if (!immutable)
pthread_rwlock_unlock(&mmio_rwlock);
return (err);
}
static int
register_mem_int(struct mmio_rb_tree *rbt, struct mem_range *memp)
{
struct mmio_rb_range *entry, *mrp;
int err;
err = 0;
mrp = malloc(sizeof(struct mmio_rb_range));
if (mrp != NULL) {
mrp->mr_param = *memp;
mrp->mr_base = memp->base;
mrp->mr_end = memp->base + memp->size - 1;
pthread_rwlock_wrlock(&mmio_rwlock);
if (mmio_rb_lookup(rbt, memp->base, &entry) != 0)
err = mmio_rb_add(rbt, mrp);
pthread_rwlock_unlock(&mmio_rwlock);
if (err)
free(mrp);
} else
err = ENOMEM;
return (err);
}
int
register_mem(struct mem_range *memp)
{
return (register_mem_int(&mmio_rb_root, memp));
}
int
register_mem_fallback(struct mem_range *memp)
{
return (register_mem_int(&mmio_rb_fallback, memp));
}
int
unregister_mem(struct mem_range *memp)
{
struct mem_range *mr;
struct mmio_rb_range *entry = NULL;
int err, i;
pthread_rwlock_wrlock(&mmio_rwlock);
err = mmio_rb_lookup(&mmio_rb_root, memp->base, &entry);
if (err == 0) {
mr = &entry->mr_param;
assert(mr->name == memp->name);
assert(mr->base == memp->base && mr->size == memp->size);
assert((mr->flags & MEM_F_IMMUTABLE) == 0);
RB_REMOVE(mmio_rb_tree, &mmio_rb_root, entry);
/* flush Per-vCPU cache */
for (i=0; i < VM_MAXCPU; i++) {
if (mmio_hint[i] == entry)
mmio_hint[i] = NULL;
}
}
pthread_rwlock_unlock(&mmio_rwlock);
if (entry)
free(entry);
return (err);
}
void
init_mem(void)
{
RB_INIT(&mmio_rb_root);
RB_INIT(&mmio_rb_fallback);
pthread_rwlock_init(&mmio_rwlock, NULL);
}

448
vendor/github.com/docker/hyperkit/src/lib/mevent.c generated vendored Normal file
View File

@ -0,0 +1,448 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
/*
* Micro event library for FreeBSD, designed for a single i/o thread
* using kqueue, and having events be persistent by default.
*/
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <xhyve/support/misc.h>
#include <xhyve/mevent.h>
#define MEVENT_MAX 64
#define MEV_ADD 1
#define MEV_ENABLE 2
#define MEV_DISABLE 3
#define MEV_DEL_PENDING 4
extern char *vmname;
static pthread_t mevent_tid;
static int mevent_timid = 43;
static int mevent_pipefd[2];
static pthread_mutex_t mevent_lmutex = PTHREAD_MUTEX_INITIALIZER;
struct mevent {
void (*me_func)(int, enum ev_type, void *);
#define me_msecs me_fd
int me_fd;
int me_timid;
enum ev_type me_type;
void *me_param;
int me_cq;
int me_state;
int me_closefd;
LIST_ENTRY(mevent) me_list;
};
static LIST_HEAD(listhead, mevent) global_head, change_head;
static void
mevent_qlock(void)
{
pthread_mutex_lock(&mevent_lmutex);
}
static void
mevent_qunlock(void)
{
pthread_mutex_unlock(&mevent_lmutex);
}
static void
mevent_pipe_read(int fd, UNUSED enum ev_type type, UNUSED void *param)
{
char buf[MEVENT_MAX];
ssize_t status;
/*
* Drain the pipe read side. The fd is non-blocking so this is
* safe to do.
*/
do {
status = read(fd, buf, sizeof(buf));
} while (status == MEVENT_MAX);
}
static void
mevent_notify(void)
{
char c;
/*
* If calling from outside the i/o thread, write a byte on the
* pipe to force the i/o thread to exit the blocking kevent call.
*/
if (mevent_pipefd[1] != 0 && pthread_self() != mevent_tid) {
write(mevent_pipefd[1], &c, 1);
}
}
static int
mevent_kq_filter(struct mevent *mevp)
{
int retval;
retval = 0;
if (mevp->me_type == EVF_READ)
retval = EVFILT_READ;
if (mevp->me_type == EVF_WRITE)
retval = EVFILT_WRITE;
if (mevp->me_type == EVF_TIMER)
retval = EVFILT_TIMER;
if (mevp->me_type == EVF_SIGNAL)
retval = EVFILT_SIGNAL;
return (retval);
}
static int
mevent_kq_flags(struct mevent *mevp)
{
int ret;
switch (mevp->me_state) {
case MEV_ADD:
ret = EV_ADD; /* implicitly enabled */
break;
case MEV_ENABLE:
ret = EV_ENABLE;
break;
case MEV_DISABLE:
ret = EV_DISABLE;
break;
case MEV_DEL_PENDING:
ret = EV_DELETE;
break;
default:
assert(0);
break;
}
return (ret);
}
static int
mevent_kq_fflags(UNUSED struct mevent *mevp)
{
/* XXX nothing yet, perhaps EV_EOF for reads ? */
return (0);
}
static int
mevent_build(UNUSED int mfd, struct kevent *kev)
{
struct mevent *mevp, *tmpp;
int i;
i = 0;
mevent_qlock();
LIST_FOREACH_SAFE(mevp, &change_head, me_list, tmpp) {
if (mevp->me_closefd) {
/*
* A close of the file descriptor will remove the
* event
*/
close(mevp->me_fd);
} else {
if (mevp->me_type == EVF_TIMER) {
kev[i].ident = (uintptr_t) mevp->me_timid;
kev[i].data = mevp->me_msecs;
} else {
kev[i].ident = (uintptr_t) mevp->me_fd;
kev[i].data = 0;
}
kev[i].filter = (int16_t) mevent_kq_filter(mevp);
kev[i].flags = (uint16_t) mevent_kq_flags(mevp);
kev[i].fflags = (uint32_t) mevent_kq_fflags(mevp);
kev[i].udata = mevp;
i++;
}
mevp->me_cq = 0;
LIST_REMOVE(mevp, me_list);
if (mevp->me_state == MEV_DEL_PENDING) {
free(mevp);
} else {
LIST_INSERT_HEAD(&global_head, mevp, me_list);
}
assert(i < MEVENT_MAX);
}
mevent_qunlock();
return (i);
}
static void
mevent_handle(struct kevent *kev, int numev)
{
struct mevent *mevp;
int i;
for (i = 0; i < numev; i++) {
mevp = kev[i].udata;
/* XXX check for EV_ERROR ? */
(*mevp->me_func)(mevp->me_fd, mevp->me_type, mevp->me_param);
}
}
struct mevent *
mevent_add(int tfd, enum ev_type type,
void (*func)(int, enum ev_type, void *), void *param)
{
struct mevent *lp, *mevp;
if (tfd < 0 || func == NULL) {
return (NULL);
}
mevp = NULL;
mevent_qlock();
/*
* Verify that the fd/type tuple is not present in any list
*/
LIST_FOREACH(lp, &global_head, me_list) {
if (type != EVF_TIMER && lp->me_fd == tfd &&
lp->me_type == type) {
goto exit;
}
}
LIST_FOREACH(lp, &change_head, me_list) {
if (type != EVF_TIMER && lp->me_fd == tfd &&
lp->me_type == type) {
goto exit;
}
}
/*
* Allocate an entry, populate it, and add it to the change list.
*/
mevp = calloc(1, sizeof(struct mevent));
if (mevp == NULL) {
goto exit;
}
if (type == EVF_TIMER) {
mevp->me_msecs = tfd;
mevp->me_timid = mevent_timid++;
} else
mevp->me_fd = tfd;
mevp->me_type = type;
mevp->me_func = func;
mevp->me_param = param;
LIST_INSERT_HEAD(&change_head, mevp, me_list);
mevp->me_cq = 1;
mevp->me_state = MEV_ADD;
mevent_notify();
exit:
mevent_qunlock();
return (mevp);
}
static int
mevent_update(struct mevent *evp, int newstate)
{
/*
* It's not possible to enable/disable a deleted event
*/
if (evp->me_state == MEV_DEL_PENDING)
return (EINVAL);
/*
* No update needed if state isn't changing
*/
if (evp->me_state == newstate)
return (0);
mevent_qlock();
evp->me_state = newstate;
/*
* Place the entry onto the changed list if not already there.
*/
if (evp->me_cq == 0) {
evp->me_cq = 1;
LIST_REMOVE(evp, me_list);
LIST_INSERT_HEAD(&change_head, evp, me_list);
mevent_notify();
}
mevent_qunlock();
return (0);
}
int
mevent_enable(struct mevent *evp)
{
return (mevent_update(evp, MEV_ENABLE));
}
int
mevent_disable(struct mevent *evp)
{
return (mevent_update(evp, MEV_DISABLE));
}
static int
mevent_delete_event(struct mevent *evp, int closefd)
{
mevent_qlock();
/*
* Place the entry onto the changed list if not already there, and
* mark as to be deleted.
*/
if (evp->me_cq == 0) {
evp->me_cq = 1;
LIST_REMOVE(evp, me_list);
LIST_INSERT_HEAD(&change_head, evp, me_list);
mevent_notify();
}
evp->me_state = MEV_DEL_PENDING;
if (closefd)
evp->me_closefd = 1;
mevent_qunlock();
return (0);
}
int
mevent_delete(struct mevent *evp)
{
return (mevent_delete_event(evp, 0));
}
int
mevent_delete_close(struct mevent *evp)
{
return (mevent_delete_event(evp, 1));
}
static void
mevent_set_name(void)
{
}
__attribute__ ((noreturn)) void
mevent_dispatch(void)
{
struct kevent changelist[MEVENT_MAX];
struct kevent eventlist[MEVENT_MAX];
struct mevent *pipev;
int mfd;
int numev;
int ret;
mevent_tid = pthread_self();
mevent_set_name();
mfd = kqueue();
assert(mfd > 0);
/*
* Open the pipe that will be used for other threads to force
* the blocking kqueue call to exit by writing to it. Set the
* descriptor to non-blocking.
*/
ret = pipe(mevent_pipefd);
if (ret < 0) {
perror("pipe");
exit(0);
}
/*
* Add internal event handler for the pipe write fd
*/
pipev = mevent_add(mevent_pipefd[0], EVF_READ, mevent_pipe_read, NULL);
assert(pipev != NULL);
for (;;) {
/*
* Build changelist if required.
* XXX the changelist can be put into the blocking call
* to eliminate the extra syscall. Currently better for
* debug.
*/
numev = mevent_build(mfd, changelist);
if (numev) {
ret = kevent(mfd, changelist, numev, NULL, 0, NULL);
if (ret == -1) {
perror("Error return from kevent change");
}
}
/*
* Block awaiting events
*/
ret = kevent(mfd, NULL, 0, eventlist, MEVENT_MAX, NULL);
if (ret == -1 && errno != EINTR) {
perror("Error return from kevent monitor");
}
/*
* Handle reported events
*/
mevent_handle(eventlist, ret);
}
}

267
vendor/github.com/docker/hyperkit/src/lib/mevent_test.c generated vendored Normal file
View File

@ -0,0 +1,267 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
/*
* Test program for the micro event library. Set up a simple TCP echo
* service.
*
* cc mevent_test.c mevent.c -lpthread
*/
#include <stdint.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <xhyve/mevent.h>
#define TEST_PORT 4321
static pthread_mutex_t accept_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t accept_condvar = PTHREAD_COND_INITIALIZER;
static struct mevent *tevp;
char *vmname = "test vm";
#define MEVENT_ECHO
/* Number of timer events to capture */
#define TEVSZ 4096
uint64_t tevbuf[TEVSZ];
static __inline uint64_t rdtsc(void)
{
unsigned a, d;
__asm__ __volatile__ ("cpuid");
__asm__ __volatile__ ("rdtsc" : "=a" (a), "=d" (d));
return (((uint64_t) a) | (((uint64_t) d) << 32));
}
static void
timer_print(void)
{
uint64_t min, max, diff, sum, tsc_freq;
size_t len;
int j;
min = UINT64_MAX;
max = 0;
sum = 0;
len = sizeof(tsc_freq);
sysctlbyname("machdep.tsc_freq", &tsc_freq, &len, NULL, 0);
for (j = 1; j < TEVSZ; j++) {
/* Convert a tsc diff into microseconds */
diff = (tevbuf[j] - tevbuf[j-1]) * 1000000 / tsc_freq;
sum += diff;
if (min > diff)
min = diff;
if (max < diff)
max = diff;
}
printf("timers done: usecs, min %llu, max %llu, mean %llu\n", min, max,
sum/(TEVSZ - 1));
}
static void
timer_callback(int fd, enum ev_type type, void *param)
{
static int i;
if (i >= TEVSZ)
abort();
tevbuf[i++] = rdtsc();
if (i == TEVSZ) {
mevent_delete(tevp);
timer_print();
}
}
#ifdef MEVENT_ECHO
struct esync {
pthread_mutex_t e_mt;
pthread_cond_t e_cond;
};
static void
echoer_callback(int fd, enum ev_type type, void *param)
{
struct esync *sync = param;
pthread_mutex_lock(&sync->e_mt);
pthread_cond_signal(&sync->e_cond);
pthread_mutex_unlock(&sync->e_mt);
}
static void *
echoer(void *param)
{
struct esync sync;
struct mevent *mev;
char buf[128];
int fd = (int)(uintptr_t) param;
int len;
pthread_mutex_init(&sync.e_mt, NULL);
pthread_cond_init(&sync.e_cond, NULL);
pthread_mutex_lock(&sync.e_mt);
mev = mevent_add(fd, EVF_READ, echoer_callback, &sync);
if (mev == NULL) {
printf("Could not allocate echoer event\n");
exit(1);
}
while (!pthread_cond_wait(&sync.e_cond, &sync.e_mt)) {
len = read(fd, buf, sizeof(buf));
if (len > 0) {
write(fd, buf, len);
write(0, buf, len);
} else {
break;
}
}
mevent_delete_close(mev);
pthread_mutex_unlock(&sync.e_mt);
pthread_mutex_destroy(&sync.e_mt);
pthread_cond_destroy(&sync.e_cond);
return (NULL);
}
#else
static void *
echoer(void *param)
{
char buf[128];
int fd = (int)(uintptr_t) param;
int len;
while ((len = read(fd, buf, sizeof(buf))) > 0) {
write(1, buf, len);
}
return (NULL);
}
#endif /* MEVENT_ECHO */
static void
acceptor_callback(int fd, enum ev_type type, void *param)
{
pthread_mutex_lock(&accept_mutex);
pthread_cond_signal(&accept_condvar);
pthread_mutex_unlock(&accept_mutex);
}
static void *
acceptor(void *param)
{
struct sockaddr_in sin;
pthread_t tid;
int news;
int s;
static int first;
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
sin.sin_len = sizeof(sin);
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(TEST_PORT);
if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
perror("bind");
exit(1);
}
if (listen(s, 1) < 0) {
perror("listen");
exit(1);
}
(void) mevent_add(s, EVF_READ, acceptor_callback, NULL);
pthread_mutex_lock(&accept_mutex);
while (!pthread_cond_wait(&accept_condvar, &accept_mutex)) {
news = accept(s, NULL, NULL);
if (news < 0) {
perror("accept error");
} else {
static int first = 1;
if (first) {
/*
* Start a timer
*/
first = 0;
tevp = mevent_add(1, EVF_TIMER, timer_callback,
NULL);
}
printf("incoming connection, spawning thread\n");
pthread_create(&tid, NULL, echoer,
(void *)(uintptr_t)news);
}
}
return (NULL);
}
int
main(void)
{
pthread_t tid;
pthread_create(&tid, NULL, acceptor, NULL);
mevent_dispatch();
return (0);
}

View File

@ -0,0 +1,273 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <caml/alloc.h>
#include <caml/threads.h>
#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/callback.h>
#include <caml/bigarray.h>
#include "mirage_block_c.h"
void
mirage_block_register_thread(){
caml_c_thread_register();
}
void
mirage_block_unregister_thread(){
caml_c_thread_unregister();
}
/* Convenience macro to cache the OCaml callback and immediately abort()
if it can't be found -- this would indicate a fundamental linking error. */
#define OCAML_NAMED_FUNCTION(name) \
static value *fn = NULL; \
if (fn == NULL) { \
fn = caml_named_value(name); \
} \
if (fn == NULL) { \
fprintf(stderr, "Callback.register for " name " not called: are all objects linked?\n"); \
abort(); \
}
/* Every call has 2 C functions:
1. static void ocaml_FOO: using the CAMLparam/CAMLreturn macros. This assumes
the runtime system lock is held. Errors are propagated back by out
parameters, since we must use CAMLreturn and yet we cannot use CAMLreturn
for regular C values.
2. plain C FOO: this acquires the runtime lock and calls the ocaml_FOO
function.
An alternative design would be to use Begin_roots and End_roots after
acquiring the runtime lock. */
static void
ocaml_mirage_block_open(const char *config, const char *options, int *out, int *err) {
CAMLparam0();
CAMLlocal4(ocaml_config, ocaml_options_opt, ocaml_string, handle);
ocaml_config = caml_copy_string(config);
if (options == NULL) {
ocaml_options_opt = Val_int(0); /* None */
} else {
ocaml_string = caml_copy_string(options);
ocaml_options_opt = caml_alloc(1, 0); /* Some */
Store_field (ocaml_options_opt, 0, ocaml_string);
}
OCAML_NAMED_FUNCTION("mirage_block_open")
handle = caml_callback2_exn(*fn, ocaml_config, ocaml_options_opt);
if (Is_exception_result(handle)){
*err = 1;
} else {
*err = 0;
*out = Int_val(handle);
}
CAMLreturn0;
}
mirage_block_handle
mirage_block_open(const char *config, const char *options) {
int result;
int err = 1;
caml_acquire_runtime_system();
ocaml_mirage_block_open(config, options, &result, &err);
caml_release_runtime_system();
if (err){
errno = EINVAL;
return (-1);
} else {
return result;
}
}
static void
ocaml_mirage_block_stat(mirage_block_handle h, struct stat *stat, struct mirage_block_stat *mbs, int *err) {
CAMLparam0();
CAMLlocal2(ocaml_handle, result);
ocaml_handle = Val_int(h);
OCAML_NAMED_FUNCTION("mirage_block_stat")
result = caml_callback_exn(*fn, ocaml_handle);
int read_write = Int_val(Field(result, 0)) != 0;
unsigned int sector_size = (unsigned int)Int_val(Field(result, 1));
uint64_t size_sectors = (uint64_t)Int64_val(Field(result, 2));
int candelete = Bool_val(Field(result, 3));
if (Is_exception_result(result)){
*err = 1;
} else {
*err = 0;
bzero(stat, sizeof(struct stat));
stat->st_dev = 0;
stat->st_ino = 0;
stat->st_mode = S_IFREG | S_IROTH | S_IRGRP | S_IRUSR | (read_write?(S_IWOTH | S_IWGRP | S_IWUSR): 0);
stat->st_nlink = 1;
stat->st_uid = 0;
stat->st_gid = 0;
stat->st_rdev = 0;
stat->st_size = (off_t)(sector_size * size_sectors);
stat->st_blocks = (blkcnt_t)size_sectors;
stat->st_blksize = (blksize_t)sector_size;
stat->st_flags = 0;
stat->st_gen = 0;
mbs->candelete = candelete;
}
CAMLreturn0;
}
int
mirage_block_stat(mirage_block_handle h, struct stat *stat, struct mirage_block_stat *mbs) {
int err = 1;
caml_acquire_runtime_system();
ocaml_mirage_block_stat(h, stat, mbs, &err);
caml_release_runtime_system();
if (err){
errno = EINVAL;
return (-1);
} else {
return 0;
}
}
static void
ocaml_mirage_block_close(int handle, int *err) {
CAMLparam0();
CAMLlocal2(ocaml_handle, result);
ocaml_handle = Val_int(handle);
OCAML_NAMED_FUNCTION("mirage_block_close")
result = caml_callback_exn(*fn, ocaml_handle);
*err = 0;
if (Is_exception_result(result)){
*err = 1;
}
CAMLreturn0;
}
int mirage_block_close(int handle){
int err = 1;
caml_acquire_runtime_system();
ocaml_mirage_block_close(handle, &err);
caml_release_runtime_system();
return err;
}
static void
ocaml_mirage_block_preadv(const int handle, const struct iovec *iov, int iovcnt, off_t ofs, ssize_t *out, int *err) {
CAMLparam0();
CAMLlocal4(ocaml_handle, ocaml_bufs, ocaml_ofs, ocaml_result);
ocaml_handle = Val_int(handle);
ocaml_bufs = caml_alloc_tuple((mlsize_t)iovcnt);
ocaml_ofs = Val_int(ofs);
for (int i = 0; i < iovcnt; i++ ){
Store_field(ocaml_bufs, (mlsize_t)i, caml_ba_alloc_dims(CAML_BA_CHAR | CAML_BA_C_LAYOUT,
1, (*(iov+i)).iov_base, (*(iov+i)).iov_len));
}
OCAML_NAMED_FUNCTION("mirage_block_preadv")
ocaml_result = caml_callback3_exn(*fn, ocaml_handle, ocaml_bufs, ocaml_ofs);
if (Is_exception_result(ocaml_result)) {
*err = 1;
} else {
*err = 0;
*out = Int_val(ocaml_result);
}
CAMLreturn0;
}
ssize_t
mirage_block_preadv(mirage_block_handle h, const struct iovec *iov, int iovcnt, off_t offset) {
ssize_t len;
int err = 1;
caml_acquire_runtime_system();
ocaml_mirage_block_preadv(h, iov, iovcnt, offset, &len, &err);
caml_release_runtime_system();
if (err){
errno = EINVAL;
return (-1);
}
return len;
}
static void
ocaml_mirage_block_pwritev(const int handle, const struct iovec *iov, int iovcnt, off_t ofs, ssize_t *out, int *err) {
CAMLparam0();
CAMLlocal4(ocaml_handle, ocaml_bufs, ocaml_ofs, ocaml_result);
ocaml_handle = Val_int(handle);
ocaml_bufs = caml_alloc_tuple((mlsize_t)iovcnt);
ocaml_ofs = Val_int(ofs);
for (int i = 0; i < iovcnt; i++ ){
Store_field(ocaml_bufs, (mlsize_t)i, caml_ba_alloc_dims(CAML_BA_CHAR | CAML_BA_C_LAYOUT,
1, (*(iov+i)).iov_base, (*(iov+i)).iov_len));
}
OCAML_NAMED_FUNCTION("mirage_block_pwritev")
ocaml_result = caml_callback3_exn(*fn, ocaml_handle, ocaml_bufs, ocaml_ofs);
if (Is_exception_result(ocaml_result)) {
*err = 1;
} else {
*err = 0;
*out = Int_val(ocaml_result);
}
CAMLreturn0;
}
ssize_t
mirage_block_pwritev(mirage_block_handle h, const struct iovec *iov, int iovcnt, off_t offset) {
ssize_t len;
int err = 1;
caml_acquire_runtime_system();
ocaml_mirage_block_pwritev(h, iov, iovcnt, offset, &len, &err);
caml_release_runtime_system();
if (err){
errno = EINVAL;
return (-1);
}
return len;
}
static void
ocaml_mirage_block_delete(int handle, off_t offset, ssize_t len, int *err) {
CAMLparam0();
CAMLlocal4(ocaml_handle, result, ocaml_offset, ocaml_len);
ocaml_handle = Val_int(handle);
ocaml_offset = caml_copy_int64(offset);
ocaml_len = caml_copy_int64(len);
OCAML_NAMED_FUNCTION("mirage_block_delete")
result = caml_callback3_exn(*fn, ocaml_handle, ocaml_offset, ocaml_len);
*err = 0;
if (Is_exception_result(result)){
errno = EINVAL;
*err = 1;
}
CAMLreturn0;
}
int
mirage_block_delete(mirage_block_handle handle, off_t offset, ssize_t len) {
int err = 1;
caml_acquire_runtime_system();
ocaml_mirage_block_delete(handle, offset, len, &err);
caml_release_runtime_system();
return err;
}
static void
ocaml_mirage_block_flush(int handle, int *err) {
CAMLparam0();
CAMLlocal2(ocaml_handle, result);
ocaml_handle = Val_int(handle);
OCAML_NAMED_FUNCTION("mirage_block_flush")
result = caml_callback_exn(*fn, ocaml_handle);
*err = 0;
if (Is_exception_result(result)){
errno = EINVAL;
*err = 1;
}
CAMLreturn0;
}
int mirage_block_flush(int handle){
int err = 1;
caml_acquire_runtime_system();
ocaml_mirage_block_flush(handle, &err);
caml_release_runtime_system();
return err;
}

View File

@ -0,0 +1,69 @@
/*
* C interface to the mirage-block subsystem
*
* Rules for usage:
* - do not mix with other libraries which embed OCaml runtimes
* - before calling any other function, call `mirage_block_init` from one
* thread: this initialises the runtime
* - before calling open, register your thread with `mirage_block_register_thread`
*/
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
/* Initialise the mirage-block subsystem. This must be called before calling
mirage_block_register_thread. */
extern void
mirage_block_init(void);
/* Every thread that uses a mirage-block device must be registered with the
runtime system. Call this on every thread you will use, after calling
mirage_block_init once in one thread. */
extern void
mirage_block_register_thread(void);
/* When a thread has finished using mirage-block devices, call this to free
associated resources. */
extern void
mirage_block_unregister_thread(void);
/* An opened mirage-block device */
typedef int mirage_block_handle;
/* Open a mirage block device with the given optional string configuration.
To use the default configuration, pass NULL for options. */
extern mirage_block_handle
mirage_block_open(const char *config, const char *options);
struct mirage_block_stat {
int candelete; /* 1 if the device supports TRIM/DELETE/DISCARD */
};
/* Query a mirage block device. */
extern int
mirage_block_stat(mirage_block_handle h, struct stat *stat, struct mirage_block_stat *buf);
/* Read data from a mirage block device. Note the offset must be sector-aligned
and the memory buffers must also be sector-aligned. */
extern ssize_t
mirage_block_preadv(mirage_block_handle h,
const struct iovec *iov, int iovcnt, off_t offset);
/* Write data to a mirage block device. Note the offset must be sector-aligned
and the memory buffers must also be sector-aligned. */
extern ssize_t
mirage_block_pwritev(mirage_block_handle h,
const struct iovec *iov, int iovcnt, off_t offset);
/* TRIM/DELETE/DISCARD the range of sectors */
extern int
mirage_block_delete(mirage_block_handle h, off_t offset, ssize_t len);
/* Flush any outstanding I/O */
extern
int mirage_block_flush(mirage_block_handle h);
/* Close an open device; subsequent I/O requests will fail. */
extern
int mirage_block_close(mirage_block_handle h);

377
vendor/github.com/docker/hyperkit/src/lib/mptbl.c generated vendored Normal file
View File

@ -0,0 +1,377 @@
/*-
* Copyright (c) 2012 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
// #include <x86/mptable.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <xhyve/support/misc.h>
#include <xhyve/support/mptable.h>
#include <xhyve/acpi.h>
#include <xhyve/xhyve.h>
#include <xhyve/mptbl.h>
#include <xhyve/pci_emul.h>
#define MPTABLE_BASE 0xF0000
/* floating pointer length + maximum length of configuration table */
#define MPTABLE_MAX_LENGTH (65536 + 16)
#define LAPIC_PADDR 0xFEE00000
#define LAPIC_VERSION 16
#define IOAPIC_PADDR 0xFEC00000
#define IOAPIC_VERSION 0x11
#define MP_SPECREV 4
#define MPFP_SIG "_MP_"
/* Configuration header defines */
#define MPCH_SIG "PCMP"
#define MPCH_OEMID "BHyVe "
#define MPCH_OEMID_LEN 8
#define MPCH_PRODID "Hypervisor "
#define MPCH_PRODID_LEN 12
/* Processor entry defines */
#define MPEP_SIG_FAMILY 6 /* XXX bhyve should supply this */
#define MPEP_SIG_MODEL 26
#define MPEP_SIG_STEPPING 5
#define MPEP_SIG \
((MPEP_SIG_FAMILY << 8) | \
(MPEP_SIG_MODEL << 4) | \
(MPEP_SIG_STEPPING))
#define MPEP_FEATURES (0xBFEBFBFF) /* XXX Intel i7 */
/* Number of local intr entries */
#define MPEII_NUM_LOCAL_IRQ 2
/* Bus entry defines */
#define MPE_NUM_BUSES 2
#define MPE_BUSNAME_LEN 6
#define MPE_BUSNAME_ISA "ISA "
#define MPE_BUSNAME_PCI "PCI "
static void *oem_tbl_start;
static int oem_tbl_size;
static uint8_t
mpt_compute_checksum(void *base, size_t len)
{
uint8_t *bytes;
uint8_t sum;
for(bytes = base, sum = 0; len > 0; len--) {
sum += *bytes++;
}
return ((uint8_t) (256 - sum));
}
static void
mpt_build_mpfp(mpfps_t mpfp, uint64_t gpa)
{
memset(mpfp, 0, sizeof(*mpfp));
memcpy(mpfp->signature, MPFP_SIG, 4);
mpfp->pap = (uint32_t) (gpa + sizeof(*mpfp));
mpfp->length = 1;
mpfp->spec_rev = MP_SPECREV;
mpfp->checksum = mpt_compute_checksum(mpfp, sizeof(*mpfp));
}
static void
mpt_build_mpch(mpcth_t mpch)
{
memset(mpch, 0, sizeof(*mpch));
memcpy(mpch->signature, MPCH_SIG, 4);
mpch->spec_rev = MP_SPECREV;
memcpy(mpch->oem_id, MPCH_OEMID, MPCH_OEMID_LEN);
memcpy(mpch->product_id, MPCH_PRODID, MPCH_PRODID_LEN);
mpch->apic_address = LAPIC_PADDR;
}
static void
mpt_build_proc_entries(proc_entry_ptr mpep, int ncpu)
{
int i;
for (i = 0; i < ncpu; i++) {
memset(mpep, 0, sizeof(*mpep));
mpep->type = MPCT_ENTRY_PROCESSOR;
mpep->apic_id = (uint8_t) i; // XXX
mpep->apic_version = LAPIC_VERSION;
mpep->cpu_flags = PROCENTRY_FLAG_EN;
if (i == 0)
mpep->cpu_flags |= PROCENTRY_FLAG_BP;
mpep->cpu_signature = MPEP_SIG;
mpep->feature_flags = MPEP_FEATURES;
mpep++;
}
}
static void
mpt_build_localint_entries(int_entry_ptr mpie)
{
/* Hardcode LINT0 as ExtINT on all CPUs. */
memset(mpie, 0, sizeof(*mpie));
mpie->type = MPCT_ENTRY_LOCAL_INT;
mpie->int_type = INTENTRY_TYPE_EXTINT;
mpie->int_flags = INTENTRY_FLAGS_POLARITY_CONFORM |
INTENTRY_FLAGS_TRIGGER_CONFORM;
mpie->dst_apic_id = 0xff;
mpie->dst_apic_int = 0;
mpie++;
/* Hardcode LINT1 as NMI on all CPUs. */
memset(mpie, 0, sizeof(*mpie));
mpie->type = MPCT_ENTRY_LOCAL_INT;
mpie->int_type = INTENTRY_TYPE_NMI;
mpie->int_flags = INTENTRY_FLAGS_POLARITY_CONFORM |
INTENTRY_FLAGS_TRIGGER_CONFORM;
mpie->dst_apic_id = 0xff;
mpie->dst_apic_int = 1;
}
static void
mpt_build_bus_entries(bus_entry_ptr mpeb)
{
memset(mpeb, 0, sizeof(*mpeb));
mpeb->type = MPCT_ENTRY_BUS;
mpeb->bus_id = 0;
memcpy(mpeb->bus_type, MPE_BUSNAME_PCI, MPE_BUSNAME_LEN);
mpeb++;
memset(mpeb, 0, sizeof(*mpeb));
mpeb->type = MPCT_ENTRY_BUS;
mpeb->bus_id = 1;
memcpy(mpeb->bus_type, MPE_BUSNAME_ISA, MPE_BUSNAME_LEN);
}
static void
mpt_build_ioapic_entries(io_apic_entry_ptr mpei, int id)
{
memset(mpei, 0, sizeof(*mpei));
mpei->type = MPCT_ENTRY_IOAPIC;
mpei->apic_id = (uint8_t) id;
mpei->apic_version = IOAPIC_VERSION;
mpei->apic_flags = IOAPICENTRY_FLAG_EN;
mpei->apic_address = IOAPIC_PADDR;
}
static int
mpt_count_ioint_entries(void)
{
int bus, count;
count = 0;
for (bus = 0; bus <= PCI_BUSMAX; bus++)
count += pci_count_lintr(bus);
/*
* Always include entries for the first 16 pins along with a entry
* for each active PCI INTx pin.
*/
return (16 + count);
}
static void
mpt_generate_pci_int(int bus, int slot, int pin, UNUSED int pirq_pin,
int ioapic_irq, void *arg)
{
int_entry_ptr *mpiep, mpie;
mpiep = arg;
mpie = *mpiep;
memset(mpie, 0, sizeof(*mpie));
/*
* This is always after another I/O interrupt entry, so cheat
* and fetch the I/O APIC ID from the prior entry.
*/
mpie->type = MPCT_ENTRY_INT;
mpie->int_type = INTENTRY_TYPE_INT;
mpie->src_bus_id = (uint8_t) bus;
mpie->src_bus_irq = (uint8_t) (slot << 2 | (pin - 1));
mpie->dst_apic_id = mpie[-1].dst_apic_id;
mpie->dst_apic_int = (uint8_t) ioapic_irq;
*mpiep = mpie + 1;
}
static void
mpt_build_ioint_entries(int_entry_ptr mpie, int id)
{
int pin, bus;
/*
* The following config is taken from kernel mptable.c
* mptable_parse_default_config_ints(...), for now
* just use the default config, tweek later if needed.
*/
/* First, generate the first 16 pins. */
for (pin = 0; pin < 16; pin++) {
memset(mpie, 0, sizeof(*mpie));
mpie->type = MPCT_ENTRY_INT;
mpie->src_bus_id = 1;
mpie->dst_apic_id = (uint8_t) id;
/*
* All default configs route IRQs from bus 0 to the first 16
* pins of the first I/O APIC with an APIC ID of 2.
*/
mpie->dst_apic_int = (uint8_t) pin;
switch (pin) {
case 0:
/* Pin 0 is an ExtINT pin. */
mpie->int_type = INTENTRY_TYPE_EXTINT;
break;
case 2:
/* IRQ 0 is routed to pin 2. */
mpie->int_type = INTENTRY_TYPE_INT;
mpie->src_bus_irq = 0;
break;
case SCI_INT:
/* ACPI SCI is level triggered and active-lo. */
mpie->int_flags = INTENTRY_FLAGS_POLARITY_ACTIVELO |
INTENTRY_FLAGS_TRIGGER_LEVEL;
mpie->int_type = INTENTRY_TYPE_INT;
mpie->src_bus_irq = SCI_INT;
break;
default:
/* All other pins are identity mapped. */
mpie->int_type = INTENTRY_TYPE_INT;
mpie->src_bus_irq = (uint8_t) pin;
break;
}
mpie++;
}
/* Next, generate entries for any PCI INTx interrupts. */
for (bus = 0; bus <= PCI_BUSMAX; bus++)
pci_walk_lintr(bus, mpt_generate_pci_int, &mpie);
}
void
mptable_add_oemtbl(void *tbl, int tblsz)
{
oem_tbl_start = tbl;
oem_tbl_size = tblsz;
}
int
mptable_build(int ncpu)
{
mpcth_t mpch;
bus_entry_ptr mpeb;
io_apic_entry_ptr mpei;
proc_entry_ptr mpep;
mpfps_t mpfp;
int_entry_ptr mpie;
int ioints, bus;
char *curraddr;
char *startaddr;
startaddr = paddr_guest2host(MPTABLE_BASE, MPTABLE_MAX_LENGTH);
if (startaddr == NULL) {
fprintf(stderr, "mptable requires mapped mem\n");
return (ENOMEM);
}
/*
* There is no way to advertise multiple PCI hierarchies via MPtable
* so require that there is no PCI hierarchy with a non-zero bus
* number.
*/
for (bus = 1; bus <= PCI_BUSMAX; bus++) {
if (pci_bus_configured(bus)) {
fprintf(stderr, "MPtable is incompatible with "
"multiple PCI hierarchies.\r\n");
fprintf(stderr, "MPtable generation can be disabled "
"by passing the -Y option to bhyve(8).\r\n");
return (EINVAL);
}
}
curraddr = startaddr;
mpfp = (mpfps_t)curraddr;
mpt_build_mpfp(mpfp, MPTABLE_BASE);
curraddr += sizeof(*mpfp);
mpch = (mpcth_t)curraddr;
mpt_build_mpch(mpch);
curraddr += sizeof(*mpch);
mpep = (proc_entry_ptr)curraddr;
mpt_build_proc_entries(mpep, ncpu);
curraddr += sizeof(*mpep) * ((uint64_t) ncpu);
mpch->entry_count += ncpu;
mpeb = (bus_entry_ptr) curraddr;
mpt_build_bus_entries(mpeb);
curraddr += sizeof(*mpeb) * MPE_NUM_BUSES;
mpch->entry_count += MPE_NUM_BUSES;
mpei = (io_apic_entry_ptr)curraddr;
mpt_build_ioapic_entries(mpei, 0);
curraddr += sizeof(*mpei);
mpch->entry_count++;
mpie = (int_entry_ptr) curraddr;
ioints = mpt_count_ioint_entries();
mpt_build_ioint_entries(mpie, 0);
curraddr += sizeof(*mpie) * ((uint64_t) ioints);
mpch->entry_count += ioints;
mpie = (int_entry_ptr)curraddr;
mpt_build_localint_entries(mpie);
curraddr += sizeof(*mpie) * MPEII_NUM_LOCAL_IRQ;
mpch->entry_count += MPEII_NUM_LOCAL_IRQ;
if (oem_tbl_start) {
mpch->oem_table_pointer =
(uint32_t) (curraddr - startaddr + MPTABLE_BASE);
mpch->oem_table_size = (uint16_t) oem_tbl_size;
memcpy(curraddr, oem_tbl_start, oem_tbl_size);
}
mpch->base_table_length = (uint16_t) (curraddr - (char *)mpch);
mpch->checksum = mpt_compute_checksum(mpch, mpch->base_table_length);
return (0);
}

2399
vendor/github.com/docker/hyperkit/src/lib/pci_ahci.c generated vendored Normal file

File diff suppressed because it is too large Load Diff

2138
vendor/github.com/docker/hyperkit/src/lib/pci_emul.c generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,68 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#include <xhyve/support/misc.h>
#include <xhyve/pci_emul.h>
static int
pci_hostbridge_init(struct pci_devinst *pi, UNUSED char *opts)
{
/* config space */
pci_set_cfgdata16(pi, PCIR_VENDOR, 0x1275); /* NetApp */
pci_set_cfgdata16(pi, PCIR_DEVICE, 0x1275); /* NetApp */
pci_set_cfgdata8(pi, PCIR_HDRTYPE, PCIM_HDRTYPE_NORMAL);
pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_BRIDGE);
pci_set_cfgdata8(pi, PCIR_SUBCLASS, PCIS_BRIDGE_HOST);
pci_emul_add_pciecap(pi, PCIEM_TYPE_ROOT_PORT);
return (0);
}
static int
pci_amd_hostbridge_init(struct pci_devinst *pi, char *opts)
{
(void) pci_hostbridge_init(pi, opts);
pci_set_cfgdata16(pi, PCIR_VENDOR, 0x1022); /* AMD */
pci_set_cfgdata16(pi, PCIR_DEVICE, 0x7432); /* made up */
return (0);
}
static struct pci_devemu pci_de_amd_hostbridge = {
.pe_emu = "amd_hostbridge",
.pe_init = pci_amd_hostbridge_init,
};
PCI_EMUL_SET(pci_de_amd_hostbridge);
static struct pci_devemu pci_de_hostbridge = {
.pe_emu = "hostbridge",
.pe_init = pci_hostbridge_init,
};
PCI_EMUL_SET(pci_de_hostbridge);

339
vendor/github.com/docker/hyperkit/src/lib/pci_irq.c generated vendored Normal file
View File

@ -0,0 +1,339 @@
/*-
* Copyright (c) 2014 Hudson River Trading LLC
* Written by: John H. Baldwin <jhb@FreeBSD.org>
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <assert.h>
#include <xhyve/support/misc.h>
#include <xhyve/vmm/vmm_api.h>
#include <xhyve/acpi.h>
#include <xhyve/inout.h>
#include <xhyve/pci_emul.h>
#include <xhyve/pci_irq.h>
#include <xhyve/pci_lpc.h>
/*
* Implement an 8 pin PCI interrupt router compatible with the router
* present on Intel's ICH10 chip.
*/
/* Fields in each PIRQ register. */
#define PIRQ_DIS 0x80
#define PIRQ_IRQ 0x0f
/* Only IRQs 3-7, 9-12, and 14-15 are permitted. */
#define PERMITTED_IRQS 0xdef8
#define IRQ_PERMITTED(irq) (((1U << (irq)) & PERMITTED_IRQS) != 0)
/* IRQ count to disable an IRQ. */
#define IRQ_DISABLED 0xff
static struct pirq {
uint8_t reg;
int use_count;
int active_count;
pthread_mutex_t lock;
} pirqs[8];
static u_char irq_counts[16];
static int pirq_cold = 1;
/*
* Returns true if this pin is enabled with a valid IRQ. Setting the
* register to a reserved IRQ causes interrupts to not be asserted as
* if the pin was disabled.
*/
static bool
pirq_valid_irq(int reg)
{
if (reg & PIRQ_DIS)
return (false);
return (IRQ_PERMITTED(reg & PIRQ_IRQ));
}
uint8_t
pirq_read(int pin)
{
assert(pin > 0 && (unsigned)pin <= nitems(pirqs));
return (pirqs[pin - 1].reg);
}
void
pirq_write(int pin, uint8_t val)
{
struct pirq *pirq;
assert(pin > 0 && (unsigned)pin <= nitems(pirqs));
pirq = &pirqs[pin - 1];
pthread_mutex_lock(&pirq->lock);
if (pirq->reg != (val & (PIRQ_DIS | PIRQ_IRQ))) {
if (pirq->active_count != 0 && pirq_valid_irq(pirq->reg))
xh_vm_isa_deassert_irq(pirq->reg & PIRQ_IRQ, -1);
pirq->reg = val & (PIRQ_DIS | PIRQ_IRQ);
if (pirq->active_count != 0 && pirq_valid_irq(pirq->reg))
xh_vm_isa_assert_irq(pirq->reg & PIRQ_IRQ, -1);
}
pthread_mutex_unlock(&pirq->lock);
}
void
pci_irq_reserve(int irq)
{
assert(irq >= 0 && (unsigned)irq < nitems(irq_counts));
assert(pirq_cold);
assert(irq_counts[irq] == 0 || irq_counts[irq] == IRQ_DISABLED);
irq_counts[irq] = IRQ_DISABLED;
}
void
pci_irq_use(int irq)
{
assert(irq >= 0 && (unsigned)irq < nitems(irq_counts));
assert(pirq_cold);
assert(irq_counts[irq] != IRQ_DISABLED);
irq_counts[irq]++;
}
void
pci_irq_init(void)
{
unsigned i;
for (i = 0; i < nitems(pirqs); i++) {
pirqs[i].reg = PIRQ_DIS;
pirqs[i].use_count = 0;
pirqs[i].active_count = 0;
pthread_mutex_init(&pirqs[i].lock, NULL);
}
for (i = 0; i < nitems(irq_counts); i++) {
if (IRQ_PERMITTED(i))
irq_counts[i] = 0;
else
irq_counts[i] = IRQ_DISABLED;
}
}
void
pci_irq_assert(struct pci_devinst *pi)
{
struct pirq *pirq;
if (pi->pi_lintr.pirq_pin > 0) {
assert((unsigned)pi->pi_lintr.pirq_pin <= nitems(pirqs));
pirq = &pirqs[pi->pi_lintr.pirq_pin - 1];
pthread_mutex_lock(&pirq->lock);
pirq->active_count++;
if (pirq->active_count == 1 && pirq_valid_irq(pirq->reg)) {
xh_vm_isa_assert_irq(pirq->reg & PIRQ_IRQ, pi->pi_lintr.ioapic_irq);
pthread_mutex_unlock(&pirq->lock);
return;
}
pthread_mutex_unlock(&pirq->lock);
}
xh_vm_ioapic_assert_irq(pi->pi_lintr.ioapic_irq);
}
void
pci_irq_deassert(struct pci_devinst *pi)
{
struct pirq *pirq;
if (pi->pi_lintr.pirq_pin > 0) {
assert((unsigned)pi->pi_lintr.pirq_pin <= nitems(pirqs));
pirq = &pirqs[pi->pi_lintr.pirq_pin - 1];
pthread_mutex_lock(&pirq->lock);
pirq->active_count--;
if (pirq->active_count == 0 && pirq_valid_irq(pirq->reg)) {
xh_vm_isa_deassert_irq(pirq->reg & PIRQ_IRQ,
pi->pi_lintr.ioapic_irq);
pthread_mutex_unlock(&pirq->lock);
return;
}
pthread_mutex_unlock(&pirq->lock);
}
xh_vm_ioapic_deassert_irq(pi->pi_lintr.ioapic_irq);
}
int
pirq_alloc_pin(void)
{
int best_count, best_irq, best_pin, irq, pin;
pirq_cold = 0;
/* First, find the least-used PIRQ pin. */
best_pin = 0;
best_count = pirqs[0].use_count;
for (pin = 1; (unsigned)pin < nitems(pirqs); pin++) {
if (pirqs[pin].use_count < best_count) {
best_pin = pin;
best_count = pirqs[pin].use_count;
}
}
pirqs[best_pin].use_count++;
/* Second, route this pin to an IRQ. */
if (pirqs[best_pin].reg == PIRQ_DIS) {
best_irq = -1;
best_count = 0;
for (irq = 0; (unsigned)irq < nitems(irq_counts); irq++) {
if (irq_counts[irq] == IRQ_DISABLED)
continue;
if (best_irq == -1 || irq_counts[irq] < best_count) {
best_irq = irq;
best_count = irq_counts[irq];
}
}
assert(best_irq >= 0);
irq_counts[best_irq]++;
pirqs[best_pin].reg = (uint8_t)best_irq;
xh_vm_isa_set_irq_trigger(best_irq, LEVEL_TRIGGER);
}
return (best_pin + 1);
}
int
pirq_irq(int pin)
{
assert(pin > 0 && (unsigned)pin <= nitems(pirqs));
return (pirqs[pin - 1].reg & PIRQ_IRQ);
}
/* XXX: Generate $PIR table. */
static void
pirq_dsdt(void)
{
char *irq_prs, *old;
int irq, pin;
irq_prs = NULL;
for (irq = 0; (unsigned)irq < nitems(irq_counts); irq++) {
if (!IRQ_PERMITTED(irq))
continue;
if (irq_prs == NULL)
asprintf(&irq_prs, "%d", irq);
else {
old = irq_prs;
asprintf(&irq_prs, "%s,%d", old, irq);
free(old);
}
}
/*
* A helper method to validate a link register's value. This
* duplicates pirq_valid_irq().
*/
dsdt_line("");
dsdt_line("Method (PIRV, 1, NotSerialized)");
dsdt_line("{");
dsdt_line(" If (And (Arg0, 0x%02X))", PIRQ_DIS);
dsdt_line(" {");
dsdt_line(" Return (0x00)");
dsdt_line(" }");
dsdt_line(" And (Arg0, 0x%02X, Local0)", PIRQ_IRQ);
dsdt_line(" If (LLess (Local0, 0x03))");
dsdt_line(" {");
dsdt_line(" Return (0x00)");
dsdt_line(" }");
dsdt_line(" If (LEqual (Local0, 0x08))");
dsdt_line(" {");
dsdt_line(" Return (0x00)");
dsdt_line(" }");
dsdt_line(" If (LEqual (Local0, 0x0D))");
dsdt_line(" {");
dsdt_line(" Return (0x00)");
dsdt_line(" }");
dsdt_line(" Return (0x01)");
dsdt_line("}");
for (pin = 0; (unsigned)pin < nitems(pirqs); pin++) {
dsdt_line("");
dsdt_line("Device (LNK%c)", 'A' + pin);
dsdt_line("{");
dsdt_line(" Name (_HID, EisaId (\"PNP0C0F\"))");
dsdt_line(" Name (_UID, 0x%02X)", pin + 1);
dsdt_line(" Method (_STA, 0, NotSerialized)");
dsdt_line(" {");
dsdt_line(" If (PIRV (PIR%c))", 'A' + pin);
dsdt_line(" {");
dsdt_line(" Return (0x0B)");
dsdt_line(" }");
dsdt_line(" Else");
dsdt_line(" {");
dsdt_line(" Return (0x09)");
dsdt_line(" }");
dsdt_line(" }");
dsdt_line(" Name (_PRS, ResourceTemplate ()");
dsdt_line(" {");
dsdt_line(" IRQ (Level, ActiveLow, Shared, )");
dsdt_line(" {%s}", irq_prs);
dsdt_line(" })");
dsdt_line(" Name (CB%02X, ResourceTemplate ()", pin + 1);
dsdt_line(" {");
dsdt_line(" IRQ (Level, ActiveLow, Shared, )");
dsdt_line(" {}");
dsdt_line(" })");
dsdt_line(" CreateWordField (CB%02X, 0x01, CIR%c)",
pin + 1, 'A' + pin);
dsdt_line(" Method (_CRS, 0, NotSerialized)");
dsdt_line(" {");
dsdt_line(" And (PIR%c, 0x%02X, Local0)", 'A' + pin,
PIRQ_DIS | PIRQ_IRQ);
dsdt_line(" If (PIRV (Local0))");
dsdt_line(" {");
dsdt_line(" ShiftLeft (0x01, Local0, CIR%c)", 'A' + pin);
dsdt_line(" }");
dsdt_line(" Else");
dsdt_line(" {");
dsdt_line(" Store (0x00, CIR%c)", 'A' + pin);
dsdt_line(" }");
dsdt_line(" Return (CB%02X)", pin + 1);
dsdt_line(" }");
dsdt_line(" Method (_DIS, 0, NotSerialized)");
dsdt_line(" {");
dsdt_line(" Store (0x80, PIR%c)", 'A' + pin);
dsdt_line(" }");
dsdt_line(" Method (_SRS, 1, NotSerialized)");
dsdt_line(" {");
dsdt_line(" CreateWordField (Arg0, 0x01, SIR%c)", 'A' + pin);
dsdt_line(" FindSetRightBit (SIR%c, Local0)", 'A' + pin);
dsdt_line(" Store (Decrement (Local0), PIR%c)", 'A' + pin);
dsdt_line(" }");
dsdt_line("}");
}
free(irq_prs);
}
LPC_DSDT(pirq_dsdt);

425
vendor/github.com/docker/hyperkit/src/lib/pci_lpc.c generated vendored Normal file
View File

@ -0,0 +1,425 @@
/*-
* Copyright (c) 2013 Neel Natu <neel@freebsd.org>
* Copyright (c) 2013 Tycho Nightingale <tycho.nightingale@pluribusnetworks.com>
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xhyve/vmm/vmm_api.h>
#include <xhyve/acpi.h>
#include <xhyve/inout.h>
#include <xhyve/dbgport.h>
#include <xhyve/pci_emul.h>
#include <xhyve/pci_irq.h>
#include <xhyve/pci_lpc.h>
#include <xhyve/uart_emul.h>
#define IO_ICU1 0x20
#define IO_ICU2 0xA0
SET_DECLARE(lpc_dsdt_set, struct lpc_dsdt);
SET_DECLARE(lpc_sysres_set, struct lpc_sysres);
#define ELCR_PORT 0x4d0
SYSRES_IO(ELCR_PORT, 2);
#define IO_TIMER1_PORT 0x40
#define NMISC_PORT 0x61
SYSRES_IO(NMISC_PORT, 1);
static struct pci_devinst *lpc_bridge;
#define LPC_UART_NUM 2
static struct lpc_uart_softc {
struct uart_softc *uart_softc;
const char *opts;
const char *name;
int iobase;
int irq;
int enabled;
} lpc_uart_softc[LPC_UART_NUM];
static const char *lpc_uart_names[LPC_UART_NUM] = { "COM1", "COM2" };
/*
* LPC device configuration is in the following form:
* <lpc_device_name>[,<options>]
* For e.g. "com1,stdio"
*/
int
lpc_device_parse(const char *opts)
{
int unit, error;
char *str, *cpy, *lpcdev;
error = -1;
str = cpy = strdup(opts);
lpcdev = strsep(&str, ",");
if (lpcdev != NULL) {
for (unit = 0; unit < LPC_UART_NUM; unit++) {
if (strcasecmp(lpcdev, lpc_uart_names[unit]) == 0) {
lpc_uart_softc[unit].opts = str;
lpc_uart_softc[unit].name = lpc_uart_names[unit];
error = 0;
goto done;
}
}
}
done:
if (error)
free(cpy);
return (error);
}
static void
lpc_uart_intr_assert(void *arg)
{
struct lpc_uart_softc *sc = arg;
assert(sc->irq >= 0);
xh_vm_isa_pulse_irq(sc->irq, sc->irq);
}
static void
lpc_uart_intr_deassert(UNUSED void *arg)
{
/*
* The COM devices on the LPC bus generate edge triggered interrupts,
* so nothing more to do here.
*/
}
static int
lpc_uart_io_handler(UNUSED int vcpu, int in, int port, int bytes, uint32_t *eax,
void *arg)
{
int offset;
struct lpc_uart_softc *sc = arg;
offset = port - sc->iobase;
switch (bytes) {
case 1:
if (in)
*eax = uart_read(sc->uart_softc, offset);
else
uart_write(sc->uart_softc, offset, (uint8_t)*eax);
break;
case 2:
if (in) {
*eax = (uint32_t)uart_read(sc->uart_softc, offset);
*eax |= (uint32_t)(uart_read(sc->uart_softc, offset + 1) << 8);
} else {
uart_write(sc->uart_softc, offset, (uint8_t)*eax);
uart_write(sc->uart_softc, offset + 1, (uint8_t)(*eax >> 8));
}
break;
default:
return (-1);
}
return (0);
}
static int
lpc_init(void)
{
struct lpc_uart_softc *sc;
struct inout_port iop;
int unit, error;
/* COM1 and COM2 */
for (unit = 0; unit < LPC_UART_NUM; unit++) {
sc = &lpc_uart_softc[unit];
if (uart_legacy_alloc(unit, &sc->iobase, &sc->irq) != 0) {
fprintf(stderr, "Unable to allocate resources for "
"LPC device %s\n", sc->name);
return (-1);
}
pci_irq_reserve(sc->irq);
sc->uart_softc = uart_init(lpc_uart_intr_assert,
lpc_uart_intr_deassert, sc);
if (uart_set_backend(sc->uart_softc, sc->opts, sc->name) != 0) {
fprintf(stderr, "Unable to initialize backend '%s' "
"for LPC device %s\n", sc->opts, sc->name);
return (-1);
}
bzero(&iop, sizeof(struct inout_port));
iop.name = sc->name;
iop.port = sc->iobase;
iop.size = UART_IO_BAR_SIZE;
iop.flags = IOPORT_F_INOUT;
iop.handler = lpc_uart_io_handler;
iop.arg = sc;
error = register_inout(&iop);
assert(error == 0);
sc->enabled = 1;
}
return (0);
}
static void
pci_lpc_write_dsdt(struct pci_devinst *pi)
{
struct lpc_dsdt **ldpp, *ldp;
dsdt_line("");
dsdt_line("Device (ISA)");
dsdt_line("{");
dsdt_line(" Name (_ADR, 0x%04X%04X)", pi->pi_slot, pi->pi_func);
dsdt_line(" OperationRegion (LPCR, PCI_Config, 0x00, 0x100)");
dsdt_line(" Field (LPCR, AnyAcc, NoLock, Preserve)");
dsdt_line(" {");
dsdt_line(" Offset (0x60),");
dsdt_line(" PIRA, 8,");
dsdt_line(" PIRB, 8,");
dsdt_line(" PIRC, 8,");
dsdt_line(" PIRD, 8,");
dsdt_line(" Offset (0x68),");
dsdt_line(" PIRE, 8,");
dsdt_line(" PIRF, 8,");
dsdt_line(" PIRG, 8,");
dsdt_line(" PIRH, 8");
dsdt_line(" }");
dsdt_line("");
dsdt_indent(1);
SET_FOREACH(ldpp, lpc_dsdt_set) {
ldp = *ldpp;
ldp->handler();
}
dsdt_line("");
dsdt_line("Device (PIC)");
dsdt_line("{");
dsdt_line(" Name (_HID, EisaId (\"PNP0000\"))");
dsdt_line(" Name (_CRS, ResourceTemplate ()");
dsdt_line(" {");
dsdt_indent(2);
dsdt_fixed_ioport(IO_ICU1, 2);
dsdt_fixed_ioport(IO_ICU2, 2);
dsdt_fixed_irq(2);
dsdt_unindent(2);
dsdt_line(" })");
dsdt_line("}");
dsdt_line("");
dsdt_line("Device (TIMR)");
dsdt_line("{");
dsdt_line(" Name (_HID, EisaId (\"PNP0100\"))");
dsdt_line(" Name (_CRS, ResourceTemplate ()");
dsdt_line(" {");
dsdt_indent(2);
dsdt_fixed_ioport(IO_TIMER1_PORT, 4);
dsdt_fixed_irq(0);
dsdt_unindent(2);
dsdt_line(" })");
dsdt_line("}");
dsdt_unindent(1);
dsdt_line("}");
}
static void
pci_lpc_sysres_dsdt(void)
{
struct lpc_sysres **lspp, *lsp;
dsdt_line("");
dsdt_line("Device (SIO)");
dsdt_line("{");
dsdt_line(" Name (_HID, EisaId (\"PNP0C02\"))");
dsdt_line(" Name (_CRS, ResourceTemplate ()");
dsdt_line(" {");
dsdt_indent(2);
SET_FOREACH(lspp, lpc_sysres_set) {
lsp = *lspp;
switch (lsp->type) {
case LPC_SYSRES_IO:
dsdt_fixed_ioport((uint16_t)lsp->base,
(uint16_t)lsp->length);
break;
case LPC_SYSRES_MEM:
dsdt_fixed_mem32(lsp->base, lsp->length);
break;
}
}
dsdt_unindent(2);
dsdt_line(" })");
dsdt_line("}");
}
LPC_DSDT(pci_lpc_sysres_dsdt);
static void
pci_lpc_uart_dsdt(void)
{
struct lpc_uart_softc *sc;
int unit;
for (unit = 0; unit < LPC_UART_NUM; unit++) {
sc = &lpc_uart_softc[unit];
if (!sc->enabled)
continue;
dsdt_line("");
dsdt_line("Device (%s)", lpc_uart_names[unit]);
dsdt_line("{");
dsdt_line(" Name (_HID, EisaId (\"PNP0501\"))");
dsdt_line(" Name (_UID, %d)", unit + 1);
dsdt_line(" Name (_CRS, ResourceTemplate ()");
dsdt_line(" {");
dsdt_indent(2);
dsdt_fixed_ioport((uint16_t)sc->iobase, UART_IO_BAR_SIZE);
dsdt_fixed_irq((uint8_t) sc->irq);
dsdt_unindent(2);
dsdt_line(" })");
dsdt_line("}");
}
}
LPC_DSDT(pci_lpc_uart_dsdt);
static int
pci_lpc_cfgwrite(UNUSED int vcpu, struct pci_devinst *pi, int coff, int bytes,
uint32_t val)
{
int pirq_pin;
if (bytes == 1) {
pirq_pin = 0;
if (coff >= 0x60 && coff <= 0x63)
pirq_pin = coff - 0x60 + 1;
if (coff >= 0x68 && coff <= 0x6b)
pirq_pin = coff - 0x68 + 5;
if (pirq_pin != 0) {
pirq_write(pirq_pin, (uint8_t)val);
pci_set_cfgdata8(pi, coff, pirq_read(pirq_pin));
return (0);
}
}
return (-1);
}
static void
pci_lpc_write(UNUSED int vcpu, UNUSED struct pci_devinst *pi, UNUSED int baridx,
UNUSED uint64_t offset, UNUSED int size, UNUSED uint64_t value)
{
}
static uint64_t
pci_lpc_read(UNUSED int vcpu, UNUSED struct pci_devinst *pi, UNUSED int baridx,
UNUSED uint64_t offset, UNUSED int size)
{
return (0);
}
#define LPC_DEV 0x7000
#define LPC_VENDOR 0x8086
static int
pci_lpc_init(struct pci_devinst *pi, UNUSED char *opts)
{
/*
* Do not allow more than one LPC bridge to be configured.
*/
if (lpc_bridge != NULL) {
fprintf(stderr, "Only one LPC bridge is allowed.\n");
return (-1);
}
/*
* Enforce that the LPC can only be configured on bus 0. This
* simplifies the ACPI DSDT because it can provide a decode for
* all legacy i/o ports behind bus 0.
*/
if (pi->pi_bus != 0) {
fprintf(stderr, "LPC bridge can be present only on bus 0.\n");
return (-1);
}
if (lpc_init() != 0)
return (-1);
/* initialize config space */
pci_set_cfgdata16(pi, PCIR_DEVICE, LPC_DEV);
pci_set_cfgdata16(pi, PCIR_VENDOR, LPC_VENDOR);
pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_BRIDGE);
pci_set_cfgdata8(pi, PCIR_SUBCLASS, PCIS_BRIDGE_ISA);
lpc_bridge = pi;
return (0);
}
char *
lpc_pirq_name(int pin)
{
char *name;
if (lpc_bridge == NULL)
return (NULL);
asprintf(&name, "\\_SB.PC00.ISA.LNK%c,", 'A' + pin - 1);
return (name);
}
void
lpc_pirq_routed(void)
{
int pin;
if (lpc_bridge == NULL)
return;
for (pin = 0; pin < 4; pin++)
pci_set_cfgdata8(lpc_bridge, 0x60 + pin, pirq_read(pin + 1));
for (pin = 0; pin < 4; pin++)
pci_set_cfgdata8(lpc_bridge, 0x68 + pin, pirq_read(pin + 5));
}
static struct pci_devemu pci_de_lpc = {
.pe_emu = "lpc",
.pe_init = pci_lpc_init,
.pe_write_dsdt = pci_lpc_write_dsdt,
.pe_cfgwrite = pci_lpc_cfgwrite,
.pe_barwrite = pci_lpc_write,
.pe_barread = pci_lpc_read
};
PCI_EMUL_SET(pci_de_lpc);

119
vendor/github.com/docker/hyperkit/src/lib/pci_uart.c generated vendored Normal file
View File

@ -0,0 +1,119 @@
/*-
* Copyright (c) 2012 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#include <stdint.h>
#include <stdio.h>
#include <xhyve/support/misc.h>
#include <xhyve/xhyve.h>
#include <xhyve/pci_emul.h>
#include <xhyve/uart_emul.h>
/*
* Pick a PCI vid/did of a chip with a single uart at
* BAR0, that most versions of FreeBSD can understand:
* Siig CyberSerial 1-port.
*/
#define COM_VENDOR 0x131f
#define COM_DEV 0x2000
static void
pci_uart_intr_assert(void *arg)
{
struct pci_devinst *pi = arg;
pci_lintr_assert(pi);
}
static void
pci_uart_intr_deassert(void *arg)
{
struct pci_devinst *pi = arg;
pci_lintr_deassert(pi);
}
static void
pci_uart_write(UNUSED int vcpu, struct pci_devinst *pi, int baridx, uint64_t offset,
int size, uint64_t value)
{
assert(baridx == 0);
assert(size == 1);
uart_write(pi->pi_arg, (int)offset, (uint8_t)value);
}
static uint64_t
pci_uart_read(UNUSED int vcpu, struct pci_devinst *pi, int baridx,
uint64_t offset, int size)
{
uint8_t val;
assert(baridx == 0);
assert(size == 1);
val = uart_read(pi->pi_arg, (int)offset);
return (val);
}
static int
pci_uart_init(struct pci_devinst *pi, char *opts)
{
struct uart_softc *sc;
char *name;
pci_emul_alloc_bar(pi, 0, PCIBAR_IO, UART_IO_BAR_SIZE);
pci_lintr_request(pi);
/* initialize config space */
pci_set_cfgdata16(pi, PCIR_DEVICE, COM_DEV);
pci_set_cfgdata16(pi, PCIR_VENDOR, COM_VENDOR);
pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_SIMPLECOMM);
sc = uart_init(pci_uart_intr_assert, pci_uart_intr_deassert, pi);
pi->pi_arg = sc;
asprintf(&name, "pci uart at %d:%d", pi->pi_slot, pi->pi_func);
if (uart_set_backend(sc, opts, name) != 0) {
fprintf(stderr, "Unable to initialize backend '%s' for %s\n", opts, name);
free(name);
return (-1);
}
free(name);
return (0);
}
static struct pci_devemu pci_de_com = {
.pe_emu = "uart",
.pe_init = pci_uart_init,
.pe_barwrite = pci_uart_write,
.pe_barread = pci_uart_read
};
PCI_EMUL_SET(pci_de_com);

View File

@ -0,0 +1,546 @@
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/uio.h>
#include <arpa/inet.h>
#include <xhyve/support/misc.h>
#include <xhyve/support/linker_set.h>
#include <xhyve/xhyve.h>
#include <xhyve/pci_emul.h>
#include <xhyve/virtio.h>
#define VIRTIO_9P_MOUNT_TAG 1
static int pci_vt9p_debug = 0;
#define DPRINTF(params) if (pci_vt9p_debug) printf params
/* XXX issues with larger buffers elsewhere in stack */
#define BUFSIZE (1 << 18)
#define MAXDESC (BUFSIZE / 4096 + 4)
#define VT9P_RINGSZ (BUFSIZE / 4096 * 4)
struct virtio_9p_config {
uint16_t tag_len;
uint8_t tag[256];
};
/*
* Per-device softc
*/
struct pci_vt9p_out {
struct iovec wiov[MAXDESC];
struct vqueue_info *vq;
int inuse;
uint16_t tag;
uint16_t idx;
uint16_t otag;
};
struct pci_vt9p_softc {
struct virtio_softc v9sc_vs;
struct vqueue_info v9sc_vq;
pthread_mutex_t v9sc_mtx;
pthread_mutex_t v9sc_mtx2;
pthread_t v9sc_thread;
struct virtio_9p_config v9sc_cfg;
struct pci_vt9p_out v9sc_out[VT9P_RINGSZ];
/* -1 means not connected yet */
int v9sc_sock;
int v9sc_inflight;
int port;
char *path;
};
static void pci_vt9p_reset(void *);
static void pci_vt9p_notify(void *, struct vqueue_info *);
static int pci_vt9p_cfgread(void *, int, int, uint32_t *);
static int pci_vt9p_cfgwrite(void *, int, int, uint32_t);
static void pci_vt9p_lazy_initialise_socket(struct pci_vt9p_softc *sc);
static void *pci_vt9p_thread(void *vsc);
static struct virtio_consts vt9p_vi_consts = {
"vt9p", /* our name */
1, /* we support 1 virtqueue */
0, /* config reg size */
pci_vt9p_reset, /* reset */
pci_vt9p_notify, /* device-wide qnotify */
pci_vt9p_cfgread, /* read virtio config */
pci_vt9p_cfgwrite, /* write virtio config */
NULL, /* apply negotiated features */
VIRTIO_9P_MOUNT_TAG, /* our capabilities */
};
static void
pci_vt9p_reset(void *vsc)
{
struct pci_vt9p_softc *sc;
sc = vsc;
DPRINTF(("vt9p: device reset requested !\n"));
vi_reset_dev(&sc->v9sc_vs);
}
/* Used to lazily initialise the socket */
static void
pci_vt9p_lazy_initialise_socket(struct pci_vt9p_softc *sc)
{
struct sockaddr_in sa_in;
struct sockaddr_un sa_un;
int so;
socklen_t sol = (socklen_t) sizeof(int);
if (sc->v9sc_sock != -1)
return;
sa_in.sin_family = AF_INET;
sa_in.sin_port = htons(sc->port);
sa_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
sa_un.sun_family = AF_UNIX;
memset(&sa_un, 0, sizeof(sa_un));
strncpy(sa_un.sun_path, sc->path, sizeof(sa_un.sun_path)-1);
int domain = (sc->port != -1)?AF_INET:AF_UNIX;
struct sockaddr *sa = (sc->port != -1)?(struct sockaddr*)&sa_in:(struct sockaddr*)&sa_un;
size_t sa_len = (sc->port != -1)?sizeof(sa_in):sizeof(sa_un);
int max_attempts = 200; /* 200 * 50ms = 10s */
do {
sc->v9sc_sock = socket(domain, SOCK_STREAM, 0);
if (sc->v9sc_sock == -1) {
if (sc->port != -1) {
fprintf(stderr, "virtio-9p: failed to connect to port %d: out of file descriptors\n", sc->port);
} else {
fprintf(stderr, "virtio-9p: failed to connect to path %s: out of file descriptors\n", sc->path);
}
/* The device won't work */
return;
}
if (connect(sc->v9sc_sock, sa, (socklen_t)sa_len) == -1) {
close(sc->v9sc_sock);
sc->v9sc_sock = -1;
usleep(50000);
}
} while ((sc->v9sc_sock == -1) && (--max_attempts > 0));
if (sc->v9sc_sock == -1) {
if (sc->port != -1) {
fprintf(stderr, "virtio-9p: failed to connect to port %d\n", sc->port);
} else {
fprintf(stderr, "virtio-9p: failed to connect to path %s\n", sc->path);
}
/* The device won't work */
}
if (getsockopt(sc->v9sc_sock, SOL_SOCKET, SO_SNDBUF, &so, &sol) != -1) {
if (so < 2 * BUFSIZE) {
so = 2 * BUFSIZE;
(void)setsockopt(sc->v9sc_sock, SOL_SOCKET, SO_SNDBUF, &so, sol);
(void)setsockopt(sc->v9sc_sock, SOL_SOCKET, SO_RCVBUF, &so, sol);
}
}
if (pthread_create(&sc->v9sc_thread, NULL, pci_vt9p_thread, sc) == -1) {
perror("pthread_create");
/* The device won't work */
}
}
static void
pci_vt9p_notify(void *vsc, struct vqueue_info *vq)
{
struct iovec iov[MAXDESC];
uint16_t flags[MAXDESC];
struct pci_vt9p_softc *sc = vsc;
uint16_t idx;
ssize_t n;
int nvec, i, freevec;
struct iovec *wiov;
int nread, nwrite;
size_t readbytes;
uint16_t tag;
uint32_t len;
uint8_t command;
uint16_t otag = 0;
int used = 0;
sc = vsc;
pci_vt9p_lazy_initialise_socket(sc);
/* will be a socket here */
if (sc->v9sc_sock < 0) {
DPRINTF(("vt9p socket invalid\r\n"));
vq_endchains(vq, 0);
return;
}
nvec = vq_getchain(vq, &idx, iov, MAXDESC, flags);
if (nvec == -1) {
DPRINTF(("vt9p bad descriptors\r\n"));
return; /* what to do? */
}
if (nvec == 0) {
DPRINTF(("vt9p got all the descriptors\r\n"));
return;
}
DPRINTF(("vt9p got %d descriptors\r\n", nvec));
wiov = NULL;
nwrite = 0;
nread = 0;
readbytes = 0;
tag = 0;
freevec = -1;
DPRINTF(("vtrnd: vt9p_notify(): %d count %d\r\n", (int)idx, nvec));
for (i = 0; i < nvec; i++) {
DPRINTF(("vt9p iovec %d len %d\r\n", i, (int)iov[i].iov_len));
if (flags[i] & VRING_DESC_F_WRITE) {
DPRINTF(("writeable\r\n"));
nwrite++;
} else {
if (nwrite == 0) {
nread++;
readbytes += iov[i].iov_len;
DPRINTF(("readable\r\n"));
} else {
DPRINTF(("ignoring readable buffers after writeable ones\r\n"));
}
}
if (wiov == NULL && (flags[i] & VRING_DESC_F_WRITE)) {
wiov = &iov[i];
DPRINTF(("vt9p wiov is %p\r\n", (void*)wiov));
}
}
/* do this properly */
if (iov[0].iov_len >= 7) {
uint8_t *ptr = (uint8_t *)iov[0].iov_base;
len = (uint32_t)ptr[0] | ((uint32_t)ptr[1] << 8) | ((uint32_t)ptr[2] << 16) | ((uint32_t)ptr[3] << 24);
command = ptr[4];
tag = (uint16_t)((uint16_t)ptr[5] | ((uint16_t)ptr[6] << 8));
DPRINTF(("vt9p len %d\r\n", (int)len));
DPRINTF(("vt9p command %d\r\n", (int)command));
DPRINTF(("vt9p tag %d\r\n", (int)tag));
otag = 0;
if (command == 108 && iov[0].iov_len >= 9) {
otag = (uint16_t)((uint16_t)ptr[7] | ((uint16_t)ptr[8] << 8));
DPRINTF(("TFlush otag %d\r\n", (int)otag));
}
/* Linux is buggy with writes over 1k, has a buggy zero copy codepath, fix up */
if (command == 118 && iov[0].iov_len >= 23) {
uint32_t wlen = (uint32_t)ptr[19] | ((uint32_t)ptr[20] << 8) | ((uint32_t)ptr[21] << 16) | ((uint32_t)ptr[22] << 24);
DPRINTF(("Twrite wlen %d readbytes %d len %d\r\n", (int)wlen, (int)readbytes, (int)len));
if (readbytes != len) {
DPRINTF(("FIXUP! len\n"));
ptr[0] = (uint8_t)(readbytes & 0xff);
ptr[1] = (uint8_t)((readbytes >> 8) & 0xff);
ptr[2] = (uint8_t)((readbytes >> 16) & 0xff);
ptr[3] = (uint8_t)((readbytes >> 24) & 0xff);
}
/* XXX not sure seeing this now */
if (wlen != readbytes - 23) {
DPRINTF(("FIXUP! wlen\n"));
wlen = (uint32_t) (readbytes - 23);
ptr[19] = (uint8_t)(wlen & 0xff);
ptr[20] = (uint8_t)((wlen >> 8) & 0xff);
ptr[21] = (uint8_t)((wlen >> 16) & 0xff);
ptr[22] = (uint8_t)((wlen >> 24) & 0xff);
}
}
} else {
DPRINTF(("vt9p oops split iovec for command - do this properly\r\n"));
}
if (nwrite == 0) {
DPRINTF(("Nowhere to write to!!\r\n"));
}
/* do something with request! */
pthread_mutex_lock(&sc->v9sc_mtx2);
sc->v9sc_inflight++;
for (i = 0; i < VT9P_RINGSZ; i++) {
if (sc->v9sc_out[i].inuse == 1) {
used++;
continue;
}
sc->v9sc_out[i].inuse = 1;
memcpy(sc->v9sc_out[i].wiov, wiov, (size_t)(sizeof(struct iovec) * (size_t)nwrite));
sc->v9sc_out[i].vq = vq;
sc->v9sc_out[i].tag = tag;
sc->v9sc_out[i].idx = idx;
sc->v9sc_out[i].otag = otag;
break;
}
if (used == VT9P_RINGSZ) {
fprintf(stderr, "virtio-9p: Ring full!\n");
_exit(1);
}
pthread_mutex_unlock(&sc->v9sc_mtx2);
i = 0;
while (readbytes) {
n = writev(sc->v9sc_sock, &iov[i], nread);
if (n <= 0) {
fprintf(stderr, "virtio-9p: unexpected EOF writing to server-- did the 9P server crash?\n");
/* Fatal error, crash VM, let us be restarted */
_exit(1);
}
DPRINTF(("vt9p: wrote to sock %d bytes\r\n", (int)n));
readbytes -= (size_t)n;
if (readbytes != 0) {
while ((size_t)n >= iov[i].iov_len) {
n -= iov[i].iov_len;
i++;
}
iov[i].iov_len -= (size_t) n;
iov[i].iov_base = (char *) iov[i].iov_base + n;
}
}
}
static void *
pci_vt9p_thread(void *vsc)
{
struct pci_vt9p_softc *sc = vsc;
ssize_t ret;
size_t n;
size_t minlen = 7;
uint32_t len;
uint16_t tag, otag;
uint8_t command;
uint8_t *ptr;
int i, ii, j;
struct iovec *wiov;
uint8_t *buf;
char ident[16];
snprintf(ident, sizeof(ident), "9p:%s", sc->v9sc_cfg.tag);
pthread_setname_np(ident);
buf = calloc(1, BUFSIZE);
if (! buf) {
fprintf(stderr, "virtio-p9: memory allocation failed\n");
_exit(1);
}
while (1) {
ptr = buf;
n = 0;
while (n < minlen) {
ret = read(sc->v9sc_sock, ptr, minlen - n);
if (ret <= 0) {
fprintf(stderr, "virtio-9p: unexpected EOF reading -- did the 9P server crash?\n");
/* Fatal error, crash VM, let us be restarted */
_exit(1);
}
n += (size_t) ret;
ptr += ret;
}
len = (uint32_t)buf[0] | ((uint32_t)buf[1] << 8) | ((uint32_t)buf[2] << 16) | ((uint32_t)buf[3] << 24);
command = buf[4];
tag = (uint16_t)((uint16_t)buf[5] | ((uint16_t)buf[6] << 8));
DPRINTF(("[thread]Got response for tag %d command %d len %d\r\n", (int)tag, (int)command, (int)len));
n = (size_t)(len - minlen);
ptr = buf + minlen;
while (n) {
assert(len <= BUFSIZE);
ret = read(sc->v9sc_sock, ptr, n);
if (ret <= 0) {
fprintf(stderr, "virtio-9p: unexpected EOF reading-- did the 9P server crash?\n");
/* Fatal error, crash the VM, let us be restarted */
_exit(1);
}
n -= (size_t) ret;
ptr += ret;
}
DPRINTF(("[thread]got complete response for tag %d len %d\r\n", (int)tag, (int)len));
if (command == 107) {
char msg[128];
uint16_t slen = (uint16_t)((uint16_t)buf[7] | ((uint16_t)buf[8] << 8));
memcpy(msg, &buf[9], slen);
msg[slen] = 0;
DPRINTF(("[thread]Rerror: %s\r\n", msg));
}
if (command == 109) { /* Rflush */
for (i = 0; i < VT9P_RINGSZ; i++) {
if (sc->v9sc_out[i].tag == tag) {
otag = sc->v9sc_out[i].otag;
for (j = 0; j < VT9P_RINGSZ; j++) {
if (sc->v9sc_out[j].tag == otag && sc->v9sc_out[j].inuse) {
pthread_mutex_lock(&sc->v9sc_mtx2);
sc->v9sc_out[j].inuse = 0;
sc->v9sc_inflight--;
vq_relchain(sc->v9sc_out[j].vq, sc->v9sc_out[j].idx, ((uint32_t) 0));
pthread_mutex_unlock(&sc->v9sc_mtx2);
break;
}
}
break;
}
}
}
for (i = 0; i < VT9P_RINGSZ; i++) {
if (sc->v9sc_out[i].tag == tag) {
wiov = sc->v9sc_out[i].wiov;
ii = 0;
ptr = buf;
n = len;
while (n) {
size_t m = n;
if (m > wiov[ii].iov_len)
m = wiov[ii].iov_len;
DPRINTF(("[thread]copy %d bytes to iov at %p\r\n", (int)m, wiov[ii].iov_base));
memcpy(wiov[ii].iov_base, ptr, m);
ptr += m;
n -= (size_t)m;
ii++;
}
DPRINTF(("[thread]release\r\n"));
pthread_mutex_lock(&sc->v9sc_mtx2);
vq_relchain(sc->v9sc_out[i].vq, sc->v9sc_out[i].idx, ((uint32_t) len));
sc->v9sc_out[i].inuse = 0;
sc->v9sc_inflight--;
/* Generate interrupt even if some requests are outstanding, because
if we're using a blocking poll then we expect one request to be
permanently outstanding at all times. */
DPRINTF(("[thread]endchain\r\n"));
vq_endchains(sc->v9sc_out[i].vq, 1);
pthread_mutex_unlock(&sc->v9sc_mtx2);
break;
}
}
}
return NULL;
}
static char *
copy_up_to_comma(const char *from)
{
char *comma = strchr(from, ',');
char *tmp = NULL;
if (comma == NULL) {
tmp = strdup(from); /* rest of string */
} else {
size_t length = (size_t)(comma - from);
tmp = strndup(from, length);
}
return tmp;
}
static int
pci_vt9p_init(struct pci_devinst *pi, char *opts)
{
struct pci_vt9p_softc *sc;
int port = -1; /* if != -1, the port is valid. path is valid otherwise */
char *path = "";
char *tag = "plan9";
sc = calloc(1, sizeof(struct pci_vt9p_softc));
if (! sc) {
return 1;
}
sc->v9sc_sock = -1;
fprintf(stdout, "virtio-9p: initialising %s\n", opts);
while (1) {
char *next;
if (! opts)
break;
next = strchr(opts, ',');
if (next)
next[0] = '\0';
if (strncmp(opts, "port=", 5) == 0) {
port = atoi(&opts[5]);
if (port == 0) {
fprintf(stderr, "bad port: %s\r\n", opts);
return 1;
}
} else if (strncmp(opts, "path=", 5) == 0) {
path = copy_up_to_comma(opts + 5);
} else if (strncmp(opts, "tag=", 4) == 0) {
tag = copy_up_to_comma(opts + 4);
} else {
fprintf(stderr, "invalid option: %s\r\n", opts);
return 1;
}
if (! next)
break;
opts = &next[1];
}
if (!((port == -1) != (strcmp(path, "") == 0))) {
fprintf(stderr, "Please pass *either* a port *or* a path. You must pass one, you must not pass both.\n");
return 1;
}
sc->port = port;
sc->path = path;
sc->v9sc_cfg.tag_len = (uint16_t) strlen(tag);
if (sc->v9sc_cfg.tag_len > 256) {
return 1;
}
memcpy(sc->v9sc_cfg.tag, tag, sc->v9sc_cfg.tag_len);
pthread_mutex_init(&sc->v9sc_mtx, NULL);
pthread_mutex_init(&sc->v9sc_mtx2, NULL);
vi_softc_linkup(&sc->v9sc_vs, &vt9p_vi_consts, sc, pi, &sc->v9sc_vq);
sc->v9sc_vs.vs_mtx = &sc->v9sc_mtx;
sc->v9sc_vq.vq_qsize = VT9P_RINGSZ;
/* initialize config space */
pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_9P);
pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_OTHER);
pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_9P);
pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
if (vi_intr_init(&sc->v9sc_vs, 1, fbsdrun_virtio_msix()))
return (1);
vi_set_io_bar(&sc->v9sc_vs, 0);
return (0);
}
static int
pci_vt9p_cfgwrite(UNUSED void *vsc, int offset, UNUSED int size,
UNUSED uint32_t value)
{
DPRINTF(("vt9p: write to reg %d\n\r", offset));
return 1;
}
static int
pci_vt9p_cfgread(void *vsc, int offset, int size, uint32_t *retval)
{
struct pci_vt9p_softc *sc = vsc;
void *ptr;
DPRINTF(("vt9p: read to reg %d\n\r", offset));
ptr = (uint8_t *)&sc->v9sc_cfg + offset;
memcpy(retval, ptr, size);
return 0;
}
static struct pci_devemu pci_de_v9p = {
.pe_emu = "virtio-9p",
.pe_init = pci_vt9p_init,
.pe_barwrite = vi_pci_write,
.pe_barread = vi_pci_read
};
PCI_EMUL_SET(pci_de_v9p);

View File

@ -0,0 +1,423 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <sys/ioctl.h>
#include <sys/disk.h>
#include <xhyve/support/misc.h>
#include <xhyve/support/linker_set.h>
#include <xhyve/support/md5.h>
#include <xhyve/xhyve.h>
#include <xhyve/pci_emul.h>
#include <xhyve/virtio.h>
#include <xhyve/block_if.h>
#define VTBLK_RINGSZ 128
#define VTBLK_S_OK 0
#define VTBLK_S_IOERR 1
#define VTBLK_S_UNSUPP 2
#define VTBLK_BLK_ID_BYTES 20 + 1
/* Capability bits */
#define VTBLK_F_SEG_MAX (1 << 2) /* Maximum request segments */
#define VTBLK_F_BLK_SIZE (1 << 6) /* cfg block size valid */
#define VTBLK_F_FLUSH (1 << 9) /* Cache flush support */
#define VTBLK_F_TOPOLOGY (1 << 10) /* Optimal I/O alignment */
/*
* Host capabilities
*/
#define VTBLK_S_HOSTCAPS \
( VTBLK_F_SEG_MAX | \
VTBLK_F_BLK_SIZE | \
VTBLK_F_FLUSH | \
VTBLK_F_TOPOLOGY | \
VIRTIO_RING_F_INDIRECT_DESC ) /* indirect descriptors */
/*
* Config space "registers"
*/
struct vtblk_config {
uint64_t vbc_capacity;
uint32_t vbc_size_max;
uint32_t vbc_seg_max;
struct {
uint16_t cylinders;
uint8_t heads;
uint8_t sectors;
} vbc_geometry;
uint32_t vbc_blk_size;
struct {
uint8_t physical_block_exp;
uint8_t alignment_offset;
uint16_t min_io_size;
uint32_t opt_io_size;
} vbc_topology;
uint8_t vbc_writeback;
} __packed;
/*
* Fixed-size block header
*/
struct virtio_blk_hdr {
#define VBH_OP_READ 0
#define VBH_OP_WRITE 1
#define VBH_OP_FLUSH 4
#define VBH_OP_FLUSH_OUT 5
#define VBH_OP_IDENT 8
#define VBH_FLAG_BARRIER 0x80000000 /* OR'ed into vbh_type */
uint32_t vbh_type;
uint32_t vbh_ioprio;
uint64_t vbh_sector;
} __packed;
/*
* Debug printf
*/
static int pci_vtblk_debug;
#define DPRINTF(params) if (pci_vtblk_debug) printf params
struct pci_vtblk_ioreq {
struct blockif_req io_req;
struct pci_vtblk_softc *io_sc;
uint8_t *io_status;
uint16_t io_idx;
};
/*
* Per-device softc
*/
struct pci_vtblk_softc {
struct virtio_softc vbsc_vs;
pthread_mutex_t vsc_mtx;
struct vqueue_info vbsc_vq;
struct vtblk_config vbsc_cfg;
struct blockif_ctxt *bc;
char vbsc_ident[VTBLK_BLK_ID_BYTES];
struct pci_vtblk_ioreq vbsc_ios[VTBLK_RINGSZ];
};
static void pci_vtblk_reset(void *);
static void pci_vtblk_notify(void *, struct vqueue_info *);
static int pci_vtblk_cfgread(void *, int, int, uint32_t *);
static int pci_vtblk_cfgwrite(void *, int, int, uint32_t);
static struct virtio_consts vtblk_vi_consts = {
"vtblk", /* our name */
1, /* we support 1 virtqueue */
sizeof(struct vtblk_config), /* config reg size */
pci_vtblk_reset, /* reset */
pci_vtblk_notify, /* device-wide qnotify */
pci_vtblk_cfgread, /* read PCI config */
pci_vtblk_cfgwrite, /* write PCI config */
NULL, /* apply negotiated features */
VTBLK_S_HOSTCAPS, /* our capabilities */
};
static void
pci_vtblk_reset(void *vsc)
{
struct pci_vtblk_softc *sc = vsc;
DPRINTF(("vtblk: device reset requested !\n"));
vi_reset_dev(&sc->vbsc_vs);
}
/* xhyve: FIXME
*
* pci_vtblk_done seems to deadlock when called from pci_vtblk_proc?
*/
static void
pci_vtblk_done_locked(struct blockif_req *br, int err)
{
struct pci_vtblk_ioreq *io = br->br_param;
struct pci_vtblk_softc *sc = io->io_sc;
/* convert errno into a virtio block error return */
if (err == EOPNOTSUPP || err == ENOSYS)
*io->io_status = VTBLK_S_UNSUPP;
else if (err != 0)
*io->io_status = VTBLK_S_IOERR;
else
*io->io_status = VTBLK_S_OK;
/*
* Return the descriptor back to the host.
* We wrote 1 byte (our status) to host.
*/
//pthread_mutex_lock(&sc->vsc_mtx);
vq_relchain(&sc->vbsc_vq, io->io_idx, 1);
vq_endchains(&sc->vbsc_vq, 0);
//pthread_mutex_unlock(&sc->vsc_mtx);
}
static void
pci_vtblk_done(struct blockif_req *br, int err) {
struct pci_vtblk_ioreq *io = br->br_param;
struct pci_vtblk_softc *sc = io->io_sc;
pthread_mutex_lock(&sc->vsc_mtx);
pci_vtblk_done_locked(br, err);
pthread_mutex_unlock(&sc->vsc_mtx);
}
static void
pci_vtblk_proc(struct pci_vtblk_softc *sc, struct vqueue_info *vq)
{
struct virtio_blk_hdr *vbh;
struct pci_vtblk_ioreq *io;
int i, n;
int err;
ssize_t iolen;
int writeop, type;
struct iovec iov[BLOCKIF_IOV_MAX + 2];
uint16_t idx, flags[BLOCKIF_IOV_MAX + 2];
n = vq_getchain(vq, &idx, iov, BLOCKIF_IOV_MAX + 2, flags);
/*
* The first descriptor will be the read-only fixed header,
* and the last is for status (hence +2 above and below).
* The remaining iov's are the actual data I/O vectors.
*
* XXX - note - this fails on crash dump, which does a
* VIRTIO_BLK_T_FLUSH with a zero transfer length
*/
assert(n >= 2 && n <= BLOCKIF_IOV_MAX + 2);
io = &sc->vbsc_ios[idx];
assert((flags[0] & VRING_DESC_F_WRITE) == 0);
assert(iov[0].iov_len == sizeof(struct virtio_blk_hdr));
vbh = iov[0].iov_base;
memcpy(&io->io_req.br_iov, &iov[1],
sizeof(struct iovec) * ((size_t)n - 2));
io->io_req.br_iovcnt = n - 2;
io->io_req.br_offset = (off_t)(vbh->vbh_sector * DEV_BSIZE);
io->io_status = iov[--n].iov_base;
assert(iov[n].iov_len == 1);
assert(flags[n] & VRING_DESC_F_WRITE);
/*
* XXX
* The guest should not be setting the BARRIER flag because
* we don't advertise the capability.
*/
type = vbh->vbh_type & ~VBH_FLAG_BARRIER;
writeop = (type == VBH_OP_WRITE);
iolen = 0;
for (i = 1; i < n; i++) {
/*
* - write op implies read-only descriptor,
* - read/ident op implies write-only descriptor,
* therefore test the inverse of the descriptor bit
* to the op.
*/
assert(((flags[i] & VRING_DESC_F_WRITE) == 0) == writeop);
iolen += iov[i].iov_len;
}
io->io_req.br_resid = iolen;
DPRINTF(("virtio-block: %s op, %zd bytes, %d segs\n\r",
writeop ? "write" : "read/ident", iolen, i - 1));
switch (type) {
case VBH_OP_READ:
err = blockif_read(sc->bc, &io->io_req);
break;
case VBH_OP_WRITE:
err = blockif_write(sc->bc, &io->io_req);
break;
case VBH_OP_FLUSH:
case VBH_OP_FLUSH_OUT:
err = blockif_flush(sc->bc, &io->io_req);
break;
case VBH_OP_IDENT:
/* Assume a single buffer */
/* S/n equal to buffer is not zero-terminated. */
memset(iov[1].iov_base, 0, iov[1].iov_len);
strncpy(iov[1].iov_base, sc->vbsc_ident,
MIN(iov[1].iov_len, sizeof(sc->vbsc_ident)));
/* xhyve: FIXME */
pci_vtblk_done_locked(&io->io_req, 0);
return;
default:
/* xhyve: FIXME */
pci_vtblk_done_locked(&io->io_req, EOPNOTSUPP);
return;
}
assert(err == 0);
}
static void
pci_vtblk_notify(void *vsc, struct vqueue_info *vq)
{
struct pci_vtblk_softc *sc = vsc;
while (vq_has_descs(vq))
pci_vtblk_proc(sc, vq);
}
static int
pci_vtblk_init(struct pci_devinst *pi, char *opts)
{
char bident[sizeof("XX:X:X")];
struct blockif_ctxt *bctxt;
MD5_CTX mdctx;
u_char digest[16];
struct pci_vtblk_softc *sc;
off_t size;
int i, sectsz, sts, sto;
if (opts == NULL) {
printf("virtio-block: backing device required\n");
return (1);
}
/*
* The supplied backing file has to exist
*/
snprintf(bident, sizeof(bident), "%d:%d", pi->pi_slot, pi->pi_func);
bctxt = blockif_open(opts, bident);
if (bctxt == NULL) {
perror("Could not open backing file");
return (1);
}
size = blockif_size(bctxt);
sectsz = blockif_sectsz(bctxt);
blockif_psectsz(bctxt, &sts, &sto);
sc = calloc(1, sizeof(struct pci_vtblk_softc));
sc->bc = bctxt;
for (i = 0; i < VTBLK_RINGSZ; i++) {
struct pci_vtblk_ioreq *io = &sc->vbsc_ios[i];
io->io_req.br_callback = pci_vtblk_done;
io->io_req.br_param = io;
io->io_sc = sc;
io->io_idx = (uint16_t)i;
}
pthread_mutex_init(&sc->vsc_mtx, NULL);
/* init virtio softc and virtqueues */
vi_softc_linkup(&sc->vbsc_vs, &vtblk_vi_consts, sc, pi, &sc->vbsc_vq);
sc->vbsc_vs.vs_mtx = &sc->vsc_mtx;
sc->vbsc_vq.vq_qsize = VTBLK_RINGSZ;
/* sc->vbsc_vq.vq_notify = we have no per-queue notify */
/*
* Create an identifier for the backing file. Use parts of the
* md5 sum of the filename
*/
MD5Init(&mdctx);
MD5Update(&mdctx, opts, (unsigned)strlen(opts));
MD5Final(digest, &mdctx);
snprintf(sc->vbsc_ident, VTBLK_BLK_ID_BYTES, "BHYVE-%02X%02X-%02X%02X-%02X%02X",
digest[0], digest[1], digest[2], digest[3], digest[4], digest[5]);
/* setup virtio block config space */
sc->vbsc_cfg.vbc_capacity =
(uint64_t)(size / DEV_BSIZE); /* 512-byte units */
sc->vbsc_cfg.vbc_size_max = 0; /* not negotiated */
sc->vbsc_cfg.vbc_seg_max = BLOCKIF_IOV_MAX;
sc->vbsc_cfg.vbc_geometry.cylinders = 0; /* no geometry */
sc->vbsc_cfg.vbc_geometry.heads = 0;
sc->vbsc_cfg.vbc_geometry.sectors = 0;
sc->vbsc_cfg.vbc_blk_size = (uint32_t)sectsz;
sc->vbsc_cfg.vbc_topology.physical_block_exp =
(uint8_t)((sts > sectsz) ? (ffsll(sts / sectsz) - 1) : 0);
sc->vbsc_cfg.vbc_topology.alignment_offset =
(uint8_t)((sto != 0) ? ((sts - sto) / sectsz) : 0);
sc->vbsc_cfg.vbc_topology.min_io_size = 0;
sc->vbsc_cfg.vbc_topology.opt_io_size = 0;
sc->vbsc_cfg.vbc_writeback = 0;
/*
* Should we move some of this into virtio.c? Could
* have the device, class, and subdev_0 as fields in
* the virtio constants structure.
*/
pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_BLOCK);
pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_STORAGE);
pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_BLOCK);
pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
if (vi_intr_init(&sc->vbsc_vs, 1, fbsdrun_virtio_msix())) {
blockif_close(sc->bc);
free(sc);
return (1);
}
vi_set_io_bar(&sc->vbsc_vs, 0);
return (0);
}
static int
pci_vtblk_cfgwrite(UNUSED void *vsc, int offset, UNUSED int size,
UNUSED uint32_t value)
{
DPRINTF(("vtblk: write to readonly reg %d\n\r", offset));
return (1);
}
static int
pci_vtblk_cfgread(void *vsc, int offset, int size, uint32_t *retval)
{
struct pci_vtblk_softc *sc = vsc;
void *ptr;
/* our caller has already verified offset and size */
ptr = (uint8_t *)&sc->vbsc_cfg + offset;
memcpy(retval, ptr, size);
return (0);
}
static struct pci_devemu pci_de_vblk = {
.pe_emu = "virtio-blk",
.pe_init = pci_vtblk_init,
.pe_barwrite = vi_pci_write,
.pe_barread = vi_pci_read
};
PCI_EMUL_SET(pci_de_vblk);

View File

@ -0,0 +1,774 @@
/*-
* Copyright (c) 2011 NetApp, Inc.
* Copyright (c) 2015 xhyve developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <sys/select.h>
#include <sys/param.h>
#include <sys/uio.h>
#include <sys/ioctl.h>
#include <net/ethernet.h>
#include <xhyve/support/misc.h>
#include <xhyve/support/atomic.h>
#include <xhyve/support/linker_set.h>
#include <xhyve/support/md5.h>
#include <xhyve/xhyve.h>
#include <xhyve/pci_emul.h>
#include <xhyve/mevent.h>
#include <xhyve/virtio.h>
#define USE_MEVENT 0
#define VTNET_RINGSZ 1024
#define VTNET_MAXSEGS 32
/*
* Host capabilities. Note that we only offer a few of these.
*/
#define VIRTIO_NET_F_CSUM (1 << 0) /* host handles partial cksum */
#define VIRTIO_NET_F_GUEST_CSUM (1 << 1) /* guest handles partial cksum */
#define VIRTIO_NET_F_MAC (1 << 5) /* host supplies MAC */
#define VIRTIO_NET_F_GSO_DEPREC (1 << 6) /* deprecated: host handles GSO */
#define VIRTIO_NET_F_GUEST_TSO4 (1 << 7) /* guest can rcv TSOv4 */
#define VIRTIO_NET_F_GUEST_TSO6 (1 << 8) /* guest can rcv TSOv6 */
#define VIRTIO_NET_F_GUEST_ECN (1 << 9) /* guest can rcv TSO with ECN */
#define VIRTIO_NET_F_GUEST_UFO (1 << 10) /* guest can rcv UFO */
#define VIRTIO_NET_F_HOST_TSO4 (1 << 11) /* host can rcv TSOv4 */
#define VIRTIO_NET_F_HOST_TSO6 (1 << 12) /* host can rcv TSOv6 */
#define VIRTIO_NET_F_HOST_ECN (1 << 13) /* host can rcv TSO with ECN */
#define VIRTIO_NET_F_HOST_UFO (1 << 14) /* host can rcv UFO */
#define VIRTIO_NET_F_MRG_RXBUF (1 << 15) /* host can merge RX buffers */
#define VIRTIO_NET_F_STATUS (1 << 16) /* config status field available */
#define VIRTIO_NET_F_CTRL_VQ (1 << 17) /* control channel available */
#define VIRTIO_NET_F_CTRL_RX (1 << 18) /* control channel RX mode support */
#define VIRTIO_NET_F_CTRL_VLAN (1 << 19) /* control channel VLAN filtering */
#define VIRTIO_NET_F_GUEST_ANNOUNCE \
(1 << 21) /* guest can send gratuitous pkts */
#define VTNET_S_HOSTCAPS \
(VIRTIO_NET_F_MAC | VIRTIO_NET_F_MRG_RXBUF | VIRTIO_NET_F_STATUS | \
VIRTIO_F_NOTIFY_ON_EMPTY)
#define ETHER_IS_MULTICAST(addr) (*(addr) & 0x01) /* is address mcast/bcast? */
/*
* PCI config-space "registers"
*/
struct virtio_net_config {
uint8_t mac[6];
uint16_t status;
} __packed;
/*
* Queue definitions.
*/
#define VTNET_RXQ 0
#define VTNET_TXQ 1
#define VTNET_CTLQ 2 /* NB: not yet supported */
#define VTNET_MAXQ 3
/*
* Fixed network header size
*/
struct virtio_net_rxhdr {
uint8_t vrh_flags;
uint8_t vrh_gso_type;
uint16_t vrh_hdr_len;
uint16_t vrh_gso_size;
uint16_t vrh_csum_start;
uint16_t vrh_csum_offset;
uint16_t vrh_bufs;
} __packed;
/*
* Debug printf
*/
static int pci_vtnet_debug;
#define DPRINTF(params) if (pci_vtnet_debug) printf params
#define WPRINTF(params) printf params
/*
* Per-device softc
*/
struct pci_vtnet_softc {
struct virtio_softc vsc_vs;
struct vqueue_info vsc_queues[VTNET_MAXQ - 1];
pthread_mutex_t vsc_mtx;
struct mevent *vsc_mevp;
int vsc_tapfd;
int vsc_rx_ready;
volatile int resetting; /* set and checked outside lock */
uint64_t vsc_features; /* negotiated features */
struct virtio_net_config vsc_config;
pthread_mutex_t rx_mtx;
int rx_in_progress;
int rx_vhdrlen;
int rx_merge; /* merged rx bufs in use */
pthread_t tx_tid;
pthread_mutex_t tx_mtx;
pthread_cond_t tx_cond;
int tx_in_progress;
};
static void pci_vtnet_reset(void *);
/* static void pci_vtnet_notify(void *, struct vqueue_info *); */
static int pci_vtnet_cfgread(void *, int, int, uint32_t *);
static int pci_vtnet_cfgwrite(void *, int, int, uint32_t);
static void pci_vtnet_neg_features(void *, uint64_t);
static struct virtio_consts vtnet_vi_consts = {
"vtnet", /* our name */
VTNET_MAXQ - 1, /* we currently support 2 virtqueues */
sizeof(struct virtio_net_config), /* config reg size */
pci_vtnet_reset, /* reset */
NULL, /* device-wide qnotify -- not used */
pci_vtnet_cfgread, /* read PCI config */
pci_vtnet_cfgwrite, /* write PCI config */
pci_vtnet_neg_features, /* apply negotiated features */
VTNET_S_HOSTCAPS, /* our capabilities */
};
/*
* If the transmit thread is active then stall until it is done.
*/
static void
pci_vtnet_txwait(struct pci_vtnet_softc *sc)
{
pthread_mutex_lock(&sc->tx_mtx);
while (sc->tx_in_progress) {
pthread_mutex_unlock(&sc->tx_mtx);
usleep(10000);
pthread_mutex_lock(&sc->tx_mtx);
}
pthread_mutex_unlock(&sc->tx_mtx);
}
/*
* If the receive thread is active then stall until it is done.
*/
static void
pci_vtnet_rxwait(struct pci_vtnet_softc *sc)
{
pthread_mutex_lock(&sc->rx_mtx);
while (sc->rx_in_progress) {
pthread_mutex_unlock(&sc->rx_mtx);
usleep(10000);
pthread_mutex_lock(&sc->rx_mtx);
}
pthread_mutex_unlock(&sc->rx_mtx);
}
static void
pci_vtnet_reset(void *vsc)
{
struct pci_vtnet_softc *sc = vsc;
DPRINTF(("vtnet: device reset requested !\n"));
sc->resetting = 1;
/*
* Wait for the transmit and receive threads to finish their
* processing.
*/
pci_vtnet_txwait(sc);
pci_vtnet_rxwait(sc);
sc->vsc_rx_ready = 0;
sc->rx_merge = 1;
sc->rx_vhdrlen = sizeof(struct virtio_net_rxhdr);
/* now reset rings, MSI-X vectors, and negotiated capabilities */
vi_reset_dev(&sc->vsc_vs);
sc->resetting = 0;
}
/*
* Called to send a buffer chain out to the tap device
*/
static void
pci_vtnet_tap_tx(struct pci_vtnet_softc *sc, struct iovec *iov, int iovcnt,
int len)
{
static char pad[60]; /* all zero bytes */
if (sc->vsc_tapfd == -1)
return;
/*
* If the length is < 60, pad out to that and add the
* extra zero'd segment to the iov. It is guaranteed that
* there is always an extra iov available by the caller.
*/
if (len < 60) {
iov[iovcnt].iov_base = pad;
iov[iovcnt].iov_len = (size_t)(60 - len);
iovcnt++;
}
(void) writev(sc->vsc_tapfd, iov, iovcnt);
}
/*
* Called when there is read activity on the tap file descriptor.
* Each buffer posted by the guest is assumed to be able to contain
* an entire ethernet frame + rx header.
* MP note: the dummybuf is only used for discarding frames, so there
* is no need for it to be per-vtnet or locked.
*/
static uint8_t dummybuf[2048];
static __inline struct iovec *
rx_iov_trim(struct iovec *iov, int *niov, int tlen)
{
struct iovec *riov;
/* XXX short-cut: assume first segment is >= tlen */
assert(iov[0].iov_len >= (size_t)tlen);
iov[0].iov_len -= (size_t)tlen;
if (iov[0].iov_len == 0) {
assert(*niov > 1);
*niov -= 1;
riov = &iov[1];
} else {
iov[0].iov_base = (void *)((uintptr_t)iov[0].iov_base +
(size_t)tlen);
riov = &iov[0];
}
return (riov);
}
static void
pci_vtnet_tap_rx(struct pci_vtnet_softc *sc)
{
struct iovec iov[VTNET_MAXSEGS], *riov;
struct vqueue_info *vq;
void *vrx;
int len, n;
uint16_t idx;
/*
* Should never be called without a valid tap fd
*/
assert(sc->vsc_tapfd != -1);
/*
* But, will be called when the rx ring hasn't yet
* been set up or the guest is resetting the device.
*/
if (!sc->vsc_rx_ready || sc->resetting) {
/*
* Drop the packet and try later.
*/
(void) read(sc->vsc_tapfd, dummybuf, sizeof(dummybuf));
return;
}
/*
* Check for available rx buffers
*/
vq = &sc->vsc_queues[VTNET_RXQ];
if (!vq_has_descs(vq)) {
/*
* Drop the packet and try later. Interrupt on
* empty, if that's negotiated.
*/
(void) read(sc->vsc_tapfd, dummybuf, sizeof(dummybuf));
vq_endchains(vq, 1);
return;
}
do {
/*
* Get descriptor chain.
*/
n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
assert(n >= 1 && n <= VTNET_MAXSEGS);
/*
* Get a pointer to the rx header, and use the
* data immediately following it for the packet buffer.
*/
vrx = iov[0].iov_base;
riov = rx_iov_trim(iov, &n, sc->rx_vhdrlen);
len = (int) readv(sc->vsc_tapfd, riov, n);
if (len < 0 && errno == EWOULDBLOCK) {
/*
* No more packets, but still some avail ring
* entries. Interrupt if needed/appropriate.
*/
vq_retchain(vq);
vq_endchains(vq, 0);
return;
}
/*
* The only valid field in the rx packet header is the
* number of buffers if merged rx bufs were negotiated.
*/
memset(vrx, 0, sc->rx_vhdrlen);
if (sc->rx_merge) {
struct virtio_net_rxhdr *vrxh;
vrxh = vrx;
vrxh->vrh_bufs = 1;
}
/*
* Release this chain and handle more chains.
*/
vq_relchain(vq, idx, (uint32_t)(len + sc->rx_vhdrlen));
} while (vq_has_descs(vq));
/* Interrupt if needed, including for NOTIFY_ON_EMPTY. */
vq_endchains(vq, 1);
}
#if USE_MEVENT
static void
pci_vtnet_tap_callback(UNUSED int fd, UNUSED enum ev_type type, void *param)
{
struct pci_vtnet_softc *sc = param;
pthread_mutex_lock(&sc->rx_mtx);
sc->rx_in_progress = 1;
pci_vtnet_tap_rx(sc);
sc->rx_in_progress = 0;
pthread_mutex_unlock(&sc->rx_mtx);
}
#else /* !USE_MEVENT */
static void *
pci_vtnet_tap_select_func(void *vsc) {
struct pci_vtnet_softc *sc;
fd_set rfd;
pthread_setname_np("net:tap:rx");
sc = vsc;
assert(sc);
assert(sc->vsc_tapfd != -1);
FD_ZERO(&rfd);
FD_SET(sc->vsc_tapfd, &rfd);
while (1) {
if (select((sc->vsc_tapfd + 1), &rfd, NULL, NULL, NULL) == -1) {
abort();
}
pthread_mutex_lock(&sc->rx_mtx);
sc->rx_in_progress = 1;
pci_vtnet_tap_rx(sc);
sc->rx_in_progress = 0;
pthread_mutex_unlock(&sc->rx_mtx);
}
return (NULL);
}
#endif
static void
pci_vtnet_ping_rxq(void *vsc, struct vqueue_info *vq)
{
struct pci_vtnet_softc *sc = vsc;
/*
* A qnotify means that the rx process can now begin
*/
if (sc->vsc_rx_ready == 0) {
sc->vsc_rx_ready = 1;
vq->vq_used->vu_flags |= VRING_USED_F_NO_NOTIFY;
}
}
static void
pci_vtnet_proctx(struct pci_vtnet_softc *sc, struct vqueue_info *vq)
{
struct iovec iov[VTNET_MAXSEGS + 1];
int i, n;
int plen, tlen;
uint16_t idx;
/*
* Obtain chain of descriptors. The first one is
* really the header descriptor, so we need to sum
* up two lengths: packet length and transfer length.
*/
n = vq_getchain(vq, &idx, iov, VTNET_MAXSEGS, NULL);
assert(n >= 1 && n <= VTNET_MAXSEGS);
plen = 0;
tlen = (int)iov[0].iov_len;
for (i = 1; i < n; i++) {
plen += iov[i].iov_len;
tlen += iov[i].iov_len;
}
DPRINTF(("virtio: packet send, %d bytes, %d segs\n\r", plen, n));
pci_vtnet_tap_tx(sc, &iov[1], n - 1, plen);
/* chain is processed, release it and set tlen */
vq_relchain(vq, idx, (uint32_t)tlen);
}
static void
pci_vtnet_ping_txq(void *vsc, struct vqueue_info *vq)
{
struct pci_vtnet_softc *sc = vsc;
/*
* Any ring entries to process?
*/
if (!vq_has_descs(vq))
return;
/* Signal the tx thread for processing */
pthread_mutex_lock(&sc->tx_mtx);
vq->vq_used->vu_flags |= VRING_USED_F_NO_NOTIFY;
if (sc->tx_in_progress == 0)
pthread_cond_signal(&sc->tx_cond);
pthread_mutex_unlock(&sc->tx_mtx);
}
/*
* Thread which will handle processing of TX desc
*/
static void *
pci_vtnet_tx_thread(void *param)
{
struct pci_vtnet_softc *sc = param;
struct vqueue_info *vq;
int error;
pthread_setname_np("net:tap:tx");
vq = &sc->vsc_queues[VTNET_TXQ];
/*
* Let us wait till the tx queue pointers get initialised &
* first tx signaled
*/
pthread_mutex_lock(&sc->tx_mtx);
error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
assert(error == 0);
for (;;) {
/* note - tx mutex is locked here */
while (sc->resetting || !vq_has_descs(vq)) {
vq->vq_used->vu_flags &= ~VRING_USED_F_NO_NOTIFY;
mb();
if (!sc->resetting && vq_has_descs(vq))
break;
sc->tx_in_progress = 0;
error = pthread_cond_wait(&sc->tx_cond, &sc->tx_mtx);
assert(error == 0);
}
vq->vq_used->vu_flags |= VRING_USED_F_NO_NOTIFY;
sc->tx_in_progress = 1;
pthread_mutex_unlock(&sc->tx_mtx);
do {
/*
* Run through entries, placing them into
* iovecs and sending when an end-of-packet
* is found
*/
pci_vtnet_proctx(sc, vq);
} while (vq_has_descs(vq));
/*
* Generate an interrupt if needed.
*/
vq_endchains(vq, 1);
pthread_mutex_lock(&sc->tx_mtx);
}
}
#ifdef notyet
static void
pci_vtnet_ping_ctlq(void *vsc, struct vqueue_info *vq)
{
DPRINTF(("vtnet: control qnotify!\n\r"));
}
#endif
static int
pci_vtnet_parsemac(char *mac_str, uint8_t *mac_addr)
{
struct ether_addr *ea;
char *tmpstr;
char zero_addr[ETHER_ADDR_LEN] = { 0, 0, 0, 0, 0, 0 };
tmpstr = strsep(&mac_str,"=");
if ((mac_str != NULL) && (!strcmp(tmpstr,"mac"))) {
ea = ether_aton(mac_str);
if (ea == NULL || ETHER_IS_MULTICAST(ea->octet) ||
memcmp(ea->octet, zero_addr, ETHER_ADDR_LEN) == 0) {
fprintf(stderr, "Invalid MAC %s\n", mac_str);
return (EINVAL);
} else
memcpy(mac_addr, ea->octet, ETHER_ADDR_LEN);
}
return (0);
}
static int
pci_vtnet_init(struct pci_devinst *pi, char *opts)
{
MD5_CTX mdctx;
unsigned char digest[16];
char nstr[80];
struct pci_vtnet_softc *sc;
char *devname;
char *vtopts;
int mac_provided;
#if !USE_MEVENT
pthread_t sthrd;
#endif
sc = calloc(1, sizeof(struct pci_vtnet_softc));
pthread_mutex_init(&sc->vsc_mtx, NULL);
vi_softc_linkup(&sc->vsc_vs, &vtnet_vi_consts, sc, pi, sc->vsc_queues);
sc->vsc_vs.vs_mtx = &sc->vsc_mtx;
sc->vsc_queues[VTNET_RXQ].vq_qsize = VTNET_RINGSZ;
sc->vsc_queues[VTNET_RXQ].vq_notify = pci_vtnet_ping_rxq;
sc->vsc_queues[VTNET_TXQ].vq_qsize = VTNET_RINGSZ;
sc->vsc_queues[VTNET_TXQ].vq_notify = pci_vtnet_ping_txq;
#ifdef notyet
sc->vsc_queues[VTNET_CTLQ].vq_qsize = VTNET_RINGSZ;
sc->vsc_queues[VTNET_CTLQ].vq_notify = pci_vtnet_ping_ctlq;
#endif
/*
* Attempt to open the tap device and read the MAC address
* if specified
*/
mac_provided = 0;
sc->vsc_tapfd = -1;
if (opts != NULL) {
char tbuf[80];
int err;
devname = vtopts = strdup(opts);
(void) strsep(&vtopts, ",");
if (vtopts != NULL) {
err = pci_vtnet_parsemac(vtopts, sc->vsc_config.mac);
if (err != 0) {
free(devname);
return (err);
}
mac_provided = 1;
}
strcpy(tbuf, "/dev/");
strlcat(tbuf, devname, sizeof(tbuf));
free(devname);
sc->vsc_tapfd = open(tbuf, O_RDWR);
if (sc->vsc_tapfd == -1) {
WPRINTF(("open of tap device %s failed\n", tbuf));
} else {
/*
* Set non-blocking and register for read
* notifications with the event loop
*/
int opt = 1;
if (ioctl(sc->vsc_tapfd, FIONBIO, &opt) < 0) {
WPRINTF(("tap device O_NONBLOCK failed\n"));
close(sc->vsc_tapfd);
sc->vsc_tapfd = -1;
}
#if USE_MEVENT
sc->vsc_mevp = mevent_add(sc->vsc_tapfd,
EVF_READ,
pci_vtnet_tap_callback,
sc);
if (sc->vsc_mevp == NULL) {
WPRINTF(("Could not register event\n"));
close(sc->vsc_tapfd);
sc->vsc_tapfd = -1;
}
#else /* !USE_MEVENT */
if (pthread_create(&sthrd, NULL, pci_vtnet_tap_select_func, sc)) {
WPRINTF(("Could not create tap receive thread\n"));
close(sc->vsc_tapfd);
sc->vsc_tapfd = -1;
}
#endif
}
}
/*
* The default MAC address is the standard NetApp OUI of 00-a0-98,
* followed by an MD5 of the PCI slot/func number and dev name
*/
if (!mac_provided) {
snprintf(nstr, sizeof(nstr), "%d-%d-%s", pi->pi_slot,
pi->pi_func, vmname);
MD5Init(&mdctx);
MD5Update(&mdctx, nstr, (unsigned int)strlen(nstr));
MD5Final(digest, &mdctx);
sc->vsc_config.mac[0] = 0x00;
sc->vsc_config.mac[1] = 0xa0;
sc->vsc_config.mac[2] = 0x98;
sc->vsc_config.mac[3] = digest[0];
sc->vsc_config.mac[4] = digest[1];
sc->vsc_config.mac[5] = digest[2];
}
/* initialize config space */
pci_set_cfgdata16(pi, PCIR_DEVICE, VIRTIO_DEV_NET);
pci_set_cfgdata16(pi, PCIR_VENDOR, VIRTIO_VENDOR);
pci_set_cfgdata8(pi, PCIR_CLASS, PCIC_NETWORK);
pci_set_cfgdata16(pi, PCIR_SUBDEV_0, VIRTIO_TYPE_NET);
pci_set_cfgdata16(pi, PCIR_SUBVEND_0, VIRTIO_VENDOR);
/* Link is up if we managed to open tap device. */
sc->vsc_config.status = (opts == NULL || sc->vsc_tapfd >= 0);
/* use BAR 1 to map MSI-X table and PBA, if we're using MSI-X */
if (vi_intr_init(&sc->vsc_vs, 1, fbsdrun_virtio_msix()))
return (1);
/* use BAR 0 to map config regs in IO space */
vi_set_io_bar(&sc->vsc_vs, 0);
sc->resetting = 0;
sc->rx_merge = 1;
sc->rx_vhdrlen = sizeof(struct virtio_net_rxhdr);
sc->rx_in_progress = 0;
pthread_mutex_init(&sc->rx_mtx, NULL);
/*
* Initialize tx semaphore & spawn TX processing thread.
* As of now, only one thread for TX desc processing is
* spawned.
*/
sc->tx_in_progress = 0;
pthread_mutex_init(&sc->tx_mtx, NULL);
pthread_cond_init(&sc->tx_cond, NULL);
pthread_create(&sc->tx_tid, NULL, pci_vtnet_tx_thread, (void *)sc);
return (0);
}
static int
pci_vtnet_cfgwrite(void *vsc, int offset, int size, uint32_t value)
{
struct pci_vtnet_softc *sc = vsc;
void *ptr;
if (offset < 6) {
assert(offset + size <= 6);
/*
* The driver is allowed to change the MAC address
*/
ptr = &sc->vsc_config.mac[offset];
memcpy(ptr, &value, size);
} else {
/* silently ignore other writes */
DPRINTF(("vtnet: write to readonly reg %d\n\r", offset));
}
return (0);
}
static int
pci_vtnet_cfgread(void *vsc, int offset, int size, uint32_t *retval)
{
struct pci_vtnet_softc *sc = vsc;
void *ptr;
ptr = (uint8_t *)&sc->vsc_config + offset;
memcpy(retval, ptr, size);
return (0);
}
static void
pci_vtnet_neg_features(void *vsc, uint64_t negotiated_features)
{
struct pci_vtnet_softc *sc = vsc;
sc->vsc_features = negotiated_features;
if (!(sc->vsc_features & VIRTIO_NET_F_MRG_RXBUF)) {
sc->rx_merge = 0;
/* non-merge rx header is 2 bytes shorter */
sc->rx_vhdrlen -= 2;
}
}
static struct pci_devemu pci_de_vnet_tap = {
.pe_emu = "virtio-tap",
.pe_init = pci_vtnet_init,
.pe_barwrite = vi_pci_write,
.pe_barread = vi_pci_read
};
PCI_EMUL_SET(pci_de_vnet_tap);

Some files were not shown because too many files have changed in this diff Show More