From ee8e7cfe9d330d6f1ce0b9b1620d6df5d9cf6b70 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 10:56:19 +1000 Subject: Make asm-x86/bootparam.h includable from userspace. To actually write a bootloader (or, say, the lguest launcher) currently requires duplication of these structures. Making them includable from userspace is much nicer. We merge the common userspace-required definitions of e820_32/64.h into e820.h for export. Signed-off-by: Rusty Russell --- include/linux/Kbuild | 2 + include/linux/apm_bios.h | 30 +++++----- include/linux/edd.h | 137 ++++++++++++++++++++++---------------------- include/linux/screen_info.h | 81 +++++++++++++++----------- 4 files changed, 132 insertions(+), 118 deletions(-) (limited to 'include/linux') diff --git a/include/linux/Kbuild b/include/linux/Kbuild index e3ffd14a3f0b..758834538a19 100644 --- a/include/linux/Kbuild +++ b/include/linux/Kbuild @@ -186,6 +186,7 @@ unifdef-y += cyclades.h unifdef-y += dccp.h unifdef-y += dirent.h unifdef-y += dlm.h +unifdef-y += edd.h unifdef-y += elfcore.h unifdef-y += errno.h unifdef-y += errqueue.h @@ -306,6 +307,7 @@ unifdef-y += rtc.h unifdef-y += rtnetlink.h unifdef-y += scc.h unifdef-y += sched.h +unifdef-y += screen_info.h unifdef-y += sdla.h unifdef-y += selinux_netlink.h unifdef-y += sem.h diff --git a/include/linux/apm_bios.h b/include/linux/apm_bios.h index 5f921c84827a..9754baa14921 100644 --- a/include/linux/apm_bios.h +++ b/include/linux/apm_bios.h @@ -16,29 +16,29 @@ * General Public License for more details. */ -typedef unsigned short apm_event_t; -typedef unsigned short apm_eventinfo_t; +#include + +struct apm_bios_info { + __u16 version; + __u16 cseg; + __u32 offset; + __u16 cseg_16; + __u16 dseg; + __u16 flags; + __u16 cseg_len; + __u16 cseg_16_len; + __u16 dseg_len; +}; #ifdef __KERNEL__ -#include +typedef unsigned short apm_event_t; +typedef unsigned short apm_eventinfo_t; #define APM_CS (GDT_ENTRY_APMBIOS_BASE * 8) #define APM_CS_16 (APM_CS + 8) #define APM_DS (APM_CS_16 + 8) -struct apm_bios_info { - u16 version; - u16 cseg; - u32 offset; - u16 cseg_16; - u16 dseg; - u16 flags; - u16 cseg_len; - u16 cseg_16_len; - u16 dseg_len; -}; - /* Results of APM Installation Check */ #define APM_16_BIT_SUPPORT 0x0001 #define APM_32_BIT_SUPPORT 0x0002 diff --git a/include/linux/edd.h b/include/linux/edd.h index 7b647822d6dc..5d747c5cd0fe 100644 --- a/include/linux/edd.h +++ b/include/linux/edd.h @@ -67,113 +67,113 @@ #define EDD_INFO_USE_INT13_FN50 (1 << 7) struct edd_device_params { - u16 length; - u16 info_flags; - u32 num_default_cylinders; - u32 num_default_heads; - u32 sectors_per_track; - u64 number_of_sectors; - u16 bytes_per_sector; - u32 dpte_ptr; /* 0xFFFFFFFF for our purposes */ - u16 key; /* = 0xBEDD */ - u8 device_path_info_length; /* = 44 */ - u8 reserved2; - u16 reserved3; - u8 host_bus_type[4]; - u8 interface_type[8]; + __u16 length; + __u16 info_flags; + __u32 num_default_cylinders; + __u32 num_default_heads; + __u32 sectors_per_track; + __u64 number_of_sectors; + __u16 bytes_per_sector; + __u32 dpte_ptr; /* 0xFFFFFFFF for our purposes */ + __u16 key; /* = 0xBEDD */ + __u8 device_path_info_length; /* = 44 */ + __u8 reserved2; + __u16 reserved3; + __u8 host_bus_type[4]; + __u8 interface_type[8]; union { struct { - u16 base_address; - u16 reserved1; - u32 reserved2; + __u16 base_address; + __u16 reserved1; + __u32 reserved2; } __attribute__ ((packed)) isa; struct { - u8 bus; - u8 slot; - u8 function; - u8 channel; - u32 reserved; + __u8 bus; + __u8 slot; + __u8 function; + __u8 channel; + __u32 reserved; } __attribute__ ((packed)) pci; /* pcix is same as pci */ struct { - u64 reserved; + __u64 reserved; } __attribute__ ((packed)) ibnd; struct { - u64 reserved; + __u64 reserved; } __attribute__ ((packed)) xprs; struct { - u64 reserved; + __u64 reserved; } __attribute__ ((packed)) htpt; struct { - u64 reserved; + __u64 reserved; } __attribute__ ((packed)) unknown; } interface_path; union { struct { - u8 device; - u8 reserved1; - u16 reserved2; - u32 reserved3; - u64 reserved4; + __u8 device; + __u8 reserved1; + __u16 reserved2; + __u32 reserved3; + __u64 reserved4; } __attribute__ ((packed)) ata; struct { - u8 device; - u8 lun; - u8 reserved1; - u8 reserved2; - u32 reserved3; - u64 reserved4; + __u8 device; + __u8 lun; + __u8 reserved1; + __u8 reserved2; + __u32 reserved3; + __u64 reserved4; } __attribute__ ((packed)) atapi; struct { - u16 id; - u64 lun; - u16 reserved1; - u32 reserved2; + __u16 id; + __u64 lun; + __u16 reserved1; + __u32 reserved2; } __attribute__ ((packed)) scsi; struct { - u64 serial_number; - u64 reserved; + __u64 serial_number; + __u64 reserved; } __attribute__ ((packed)) usb; struct { - u64 eui; - u64 reserved; + __u64 eui; + __u64 reserved; } __attribute__ ((packed)) i1394; struct { - u64 wwid; - u64 lun; + __u64 wwid; + __u64 lun; } __attribute__ ((packed)) fibre; struct { - u64 identity_tag; - u64 reserved; + __u64 identity_tag; + __u64 reserved; } __attribute__ ((packed)) i2o; struct { - u32 array_number; - u32 reserved1; - u64 reserved2; + __u32 array_number; + __u32 reserved1; + __u64 reserved2; } __attribute__ ((packed)) raid; struct { - u8 device; - u8 reserved1; - u16 reserved2; - u32 reserved3; - u64 reserved4; + __u8 device; + __u8 reserved1; + __u16 reserved2; + __u32 reserved3; + __u64 reserved4; } __attribute__ ((packed)) sata; struct { - u64 reserved1; - u64 reserved2; + __u64 reserved1; + __u64 reserved2; } __attribute__ ((packed)) unknown; } device_path; - u8 reserved4; - u8 checksum; + __u8 reserved4; + __u8 checksum; } __attribute__ ((packed)); struct edd_info { - u8 device; - u8 version; - u16 interface_support; - u16 legacy_max_cylinder; - u8 legacy_max_head; - u8 legacy_sectors_per_track; + __u8 device; + __u8 version; + __u16 interface_support; + __u16 legacy_max_cylinder; + __u8 legacy_max_head; + __u8 legacy_sectors_per_track; struct edd_device_params params; } __attribute__ ((packed)); @@ -184,8 +184,9 @@ struct edd { unsigned char edd_info_nr; }; +#ifdef __KERNEL__ extern struct edd edd; - +#endif /* __KERNEL__ */ #endif /*!__ASSEMBLY__ */ #endif /* _LINUX_EDD_H */ diff --git a/include/linux/screen_info.h b/include/linux/screen_info.h index ba81ffe9958a..827b85bbf388 100644 --- a/include/linux/screen_info.h +++ b/include/linux/screen_info.h @@ -8,45 +8,43 @@ */ struct screen_info { - u8 orig_x; /* 0x00 */ - u8 orig_y; /* 0x01 */ - u16 ext_mem_k; /* 0x02 */ - u16 orig_video_page; /* 0x04 */ - u8 orig_video_mode; /* 0x06 */ - u8 orig_video_cols; /* 0x07 */ - u16 unused2; /* 0x08 */ - u16 orig_video_ega_bx; /* 0x0a */ - u16 unused3; /* 0x0c */ - u8 orig_video_lines; /* 0x0e */ - u8 orig_video_isVGA; /* 0x0f */ - u16 orig_video_points; /* 0x10 */ + __u8 orig_x; /* 0x00 */ + __u8 orig_y; /* 0x01 */ + __u16 ext_mem_k; /* 0x02 */ + __u16 orig_video_page; /* 0x04 */ + __u8 orig_video_mode; /* 0x06 */ + __u8 orig_video_cols; /* 0x07 */ + __u16 unused2; /* 0x08 */ + __u16 orig_video_ega_bx;/* 0x0a */ + __u16 unused3; /* 0x0c */ + __u8 orig_video_lines; /* 0x0e */ + __u8 orig_video_isVGA; /* 0x0f */ + __u16 orig_video_points;/* 0x10 */ /* VESA graphic mode -- linear frame buffer */ - u16 lfb_width; /* 0x12 */ - u16 lfb_height; /* 0x14 */ - u16 lfb_depth; /* 0x16 */ - u32 lfb_base; /* 0x18 */ - u32 lfb_size; /* 0x1c */ - u16 cl_magic, cl_offset; /* 0x20 */ - u16 lfb_linelength; /* 0x24 */ - u8 red_size; /* 0x26 */ - u8 red_pos; /* 0x27 */ - u8 green_size; /* 0x28 */ - u8 green_pos; /* 0x29 */ - u8 blue_size; /* 0x2a */ - u8 blue_pos; /* 0x2b */ - u8 rsvd_size; /* 0x2c */ - u8 rsvd_pos; /* 0x2d */ - u16 vesapm_seg; /* 0x2e */ - u16 vesapm_off; /* 0x30 */ - u16 pages; /* 0x32 */ - u16 vesa_attributes; /* 0x34 */ - u32 capabilities; /* 0x36 */ - u8 _reserved[6]; /* 0x3a */ + __u16 lfb_width; /* 0x12 */ + __u16 lfb_height; /* 0x14 */ + __u16 lfb_depth; /* 0x16 */ + __u32 lfb_base; /* 0x18 */ + __u32 lfb_size; /* 0x1c */ + __u16 cl_magic, cl_offset; /* 0x20 */ + __u16 lfb_linelength; /* 0x24 */ + __u8 red_size; /* 0x26 */ + __u8 red_pos; /* 0x27 */ + __u8 green_size; /* 0x28 */ + __u8 green_pos; /* 0x29 */ + __u8 blue_size; /* 0x2a */ + __u8 blue_pos; /* 0x2b */ + __u8 rsvd_size; /* 0x2c */ + __u8 rsvd_pos; /* 0x2d */ + __u16 vesapm_seg; /* 0x2e */ + __u16 vesapm_off; /* 0x30 */ + __u16 pages; /* 0x32 */ + __u16 vesa_attributes; /* 0x34 */ + __u32 capabilities; /* 0x36 */ + __u8 _reserved[6]; /* 0x3a */ } __attribute__((packed)); -extern struct screen_info screen_info; - #define VIDEO_TYPE_MDA 0x10 /* Monochrome Text Display */ #define VIDEO_TYPE_CGA 0x11 /* CGA Display */ #define VIDEO_TYPE_EGAM 0x20 /* EGA/VGA in Monochrome Mode */ @@ -65,4 +63,17 @@ extern struct screen_info screen_info; #define VIDEO_TYPE_PMAC 0x60 /* PowerMacintosh frame buffer. */ +#ifdef __KERNEL__ +extern struct screen_info screen_info; + +#define ORIG_X (screen_info.orig_x) +#define ORIG_Y (screen_info.orig_y) +#define ORIG_VIDEO_MODE (screen_info.orig_video_mode) +#define ORIG_VIDEO_COLS (screen_info.orig_video_cols) +#define ORIG_VIDEO_EGA_BX (screen_info.orig_video_ega_bx) +#define ORIG_VIDEO_LINES (screen_info.orig_video_lines) +#define ORIG_VIDEO_ISVGA (screen_info.orig_video_isVGA) +#define ORIG_VIDEO_POINTS (screen_info.orig_video_points) +#endif /* __KERNEL__ */ + #endif /* _SCREEN_INFO_H */ -- cgit v1.2.3-71-gd317 From b45d8cb054d7677d75176ae22a584fd84e4650e9 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 10:56:24 +1000 Subject: Make lguest_launcher.h types userspace-friendly lguest_launcher.h uses "u32" not "__u32", which sets a bad example. Fix that, and include . This means we need to use -I on the Launcher build line so types.h is found. Signed-off-by: Rusty Russell --- Documentation/lguest/Makefile | 2 +- Documentation/lguest/lguest.c | 4 ++-- include/linux/lguest_launcher.h | 21 +++++++++++---------- 3 files changed, 14 insertions(+), 13 deletions(-) (limited to 'include/linux') diff --git a/Documentation/lguest/Makefile b/Documentation/lguest/Makefile index c0b7a4556390..526c15fd83af 100644 --- a/Documentation/lguest/Makefile +++ b/Documentation/lguest/Makefile @@ -11,7 +11,7 @@ endif include $(KBUILD_OUTPUT)/.config LGUEST_GUEST_TOP := ($(CONFIG_PAGE_OFFSET) - 0x08000000) -CFLAGS:=-Wall -Wmissing-declarations -Wmissing-prototypes -O3 -Wl,-T,lguest.lds +CFLAGS:=-Wall -Wmissing-declarations -Wmissing-prototypes -O3 -I../../include -Wl,-T,lguest.lds LDLIBS:=-lz # Removing this works for some versions of ld.so (eg. Ubuntu Feisty) and # not others (eg. FC7). diff --git a/Documentation/lguest/lguest.c b/Documentation/lguest/lguest.c index 276f2f651286..fa838e2eb656 100644 --- a/Documentation/lguest/lguest.c +++ b/Documentation/lguest/lguest.c @@ -45,8 +45,8 @@ typedef unsigned long long u64; typedef uint32_t u32; typedef uint16_t u16; typedef uint8_t u8; -#include "../../include/linux/lguest_launcher.h" -#include "../../include/asm-x86/e820.h" +#include "linux/lguest_launcher.h" +#include "asm-x86/e820.h" /*:*/ #define PAGE_PRESENT 0x7 /* Present, RW, Execute */ diff --git a/include/linux/lguest_launcher.h b/include/linux/lguest_launcher.h index 641670579446..736e19a510c1 100644 --- a/include/linux/lguest_launcher.h +++ b/include/linux/lguest_launcher.h @@ -1,6 +1,7 @@ #ifndef _ASM_LGUEST_USER #define _ASM_LGUEST_USER /* Everything the "lguest" userspace program needs to know. */ +#include /* They can register up to 32 arrays of lguest_dma. */ #define LGUEST_MAX_DMA 32 /* At most we can dma 16 lguest_dma in one op. */ @@ -37,9 +38,9 @@ struct lguest_dma { /* 0 if free to be used, filled by the Host. */ - u32 used_len; + __u32 used_len; + __u16 len[LGUEST_MAX_DMA_SECTIONS]; unsigned long addr[LGUEST_MAX_DMA_SECTIONS]; - u16 len[LGUEST_MAX_DMA_SECTIONS]; }; /*:*/ @@ -52,11 +53,11 @@ struct lguest_block_page { /* 0 is a read, 1 is a write. */ int type; - u32 sector; /* Offset in device = sector * 512. */ - u32 bytes; /* Length expected to be read/written in bytes */ + __u32 sector; /* Offset in device = sector * 512. */ + __u32 bytes; /* Length expected to be read/written in bytes */ /* 0 = pending, 1 = done, 2 = done, error */ int result; - u32 num_sectors; /* Disk length = num_sectors * 512 */ + __u32 num_sectors; /* Disk length = num_sectors * 512 */ }; /*D:520 The network device is basically a memory page where all the Guests on @@ -86,21 +87,21 @@ struct lguest_net */ struct lguest_device_desc { /* The device type: console, network, disk etc. */ - u16 type; + __u16 type; #define LGUEST_DEVICE_T_CONSOLE 1 #define LGUEST_DEVICE_T_NET 2 #define LGUEST_DEVICE_T_BLOCK 3 /* The specific features of this device: these depends on device type * except for LGUEST_DEVICE_F_RANDOMNESS. */ - u16 features; + __u16 features; #define LGUEST_NET_F_NOCSUM 0x4000 /* Don't bother checksumming */ #define LGUEST_DEVICE_F_RANDOMNESS 0x8000 /* IRQ is fairly random */ /* This is how the Guest reports status of the device: the Host can set * LGUEST_DEVICE_S_REMOVED to indicate removal, but the rest are only * ever manipulated by the Guest, and only ever set. */ - u16 status; + __u16 status; /* 256 and above are device specific. */ #define LGUEST_DEVICE_S_ACKNOWLEDGE 1 /* We have seen device. */ #define LGUEST_DEVICE_S_DRIVER 2 /* We have found a driver */ @@ -111,8 +112,8 @@ struct lguest_device_desc { /* Each device exists somewhere in Guest physical memory, over some * number of pages. */ - u16 num_pages; - u32 pfn; + __u16 num_pages; + __u32 pfn; }; /*:*/ -- cgit v1.2.3-71-gd317 From c37ae93d597fc63bae979db76b527dcc7740dc9d Mon Sep 17 00:00:00 2001 From: Jes Sorensen Date: Mon, 22 Oct 2007 10:56:26 +1000 Subject: Move lguest hcalls to arch-specific header Move architecture specific portion of lg_hcall code to asm-i386/lg_hcall.h and have it included from linux/lguest.h. [Changed to asm-i386/lguest_hcall.h so documentation finds it -RR] Signed-off-by: Jes Sorensen Signed-off-by: Rusty Russell Cc: Jes Sorensen --- include/asm-x86/lguest_hcall.h | 67 ++++++++++++++++++++++++++++++++++++++++ include/linux/lguest.h | 69 +++--------------------------------------- 2 files changed, 71 insertions(+), 65 deletions(-) create mode 100644 include/asm-x86/lguest_hcall.h (limited to 'include/linux') diff --git a/include/asm-x86/lguest_hcall.h b/include/asm-x86/lguest_hcall.h new file mode 100644 index 000000000000..7859cfe0ebb2 --- /dev/null +++ b/include/asm-x86/lguest_hcall.h @@ -0,0 +1,67 @@ +/* Architecture specific portion of the lguest hypercalls */ +#ifndef _X86_LGUEST_HCALL_H +#define _X86_LGUEST_HCALL_H + +#define LHCALL_FLUSH_ASYNC 0 +#define LHCALL_LGUEST_INIT 1 +#define LHCALL_CRASH 2 +#define LHCALL_LOAD_GDT 3 +#define LHCALL_NEW_PGTABLE 4 +#define LHCALL_FLUSH_TLB 5 +#define LHCALL_LOAD_IDT_ENTRY 6 +#define LHCALL_SET_STACK 7 +#define LHCALL_TS 8 +#define LHCALL_SET_CLOCKEVENT 9 +#define LHCALL_HALT 10 +#define LHCALL_BIND_DMA 12 +#define LHCALL_SEND_DMA 13 +#define LHCALL_SET_PTE 14 +#define LHCALL_SET_PMD 15 +#define LHCALL_LOAD_TLS 16 + +/*G:031 First, how does our Guest contact the Host to ask for privileged + * operations? There are two ways: the direct way is to make a "hypercall", + * to make requests of the Host Itself. + * + * Our hypercall mechanism uses the highest unused trap code (traps 32 and + * above are used by real hardware interrupts). Seventeen hypercalls are + * available: the hypercall number is put in the %eax register, and the + * arguments (when required) are placed in %edx, %ebx and %ecx. If a return + * value makes sense, it's returned in %eax. + * + * Grossly invalid calls result in Sudden Death at the hands of the vengeful + * Host, rather than returning failure. This reflects Winston Churchill's + * definition of a gentleman: "someone who is only rude intentionally". */ +#define LGUEST_TRAP_ENTRY 0x1F + +static inline unsigned long +hcall(unsigned long call, + unsigned long arg1, unsigned long arg2, unsigned long arg3) +{ + /* "int" is the Intel instruction to trigger a trap. */ + asm volatile("int $" __stringify(LGUEST_TRAP_ENTRY) + /* The call is in %eax (aka "a"), and can be replaced */ + : "=a"(call) + /* The other arguments are in %eax, %edx, %ebx & %ecx */ + : "a"(call), "d"(arg1), "b"(arg2), "c"(arg3) + /* "memory" means this might write somewhere in memory. + * This isn't true for all calls, but it's safe to tell + * gcc that it might happen so it doesn't get clever. */ + : "memory"); + return call; +} +/*:*/ + +void async_hcall(unsigned long call, + unsigned long arg1, unsigned long arg2, unsigned long arg3); + +/* Can't use our min() macro here: needs to be a constant */ +#define LGUEST_IRQS (NR_IRQS < 32 ? NR_IRQS: 32) + +#define LHCALL_RING_SIZE 64 +struct hcall_ring +{ + u32 eax, edx, ebx, ecx; +}; + +#endif /* _I386_LGUEST_HCALL_H */ diff --git a/include/linux/lguest.h b/include/linux/lguest.h index 157ad64aa7ce..d4d94a127f35 100644 --- a/include/linux/lguest.h +++ b/include/linux/lguest.h @@ -1,76 +1,15 @@ /* Things the lguest guest needs to know. Note: like all lguest interfaces, * this is subject to wild and random change between versions. */ -#ifndef _ASM_LGUEST_H -#define _ASM_LGUEST_H +#ifndef _LINUX_LGUEST_H +#define _LINUX_LGUEST_H #ifndef __ASSEMBLY__ #include - -#define LHCALL_FLUSH_ASYNC 0 -#define LHCALL_LGUEST_INIT 1 -#define LHCALL_CRASH 2 -#define LHCALL_LOAD_GDT 3 -#define LHCALL_NEW_PGTABLE 4 -#define LHCALL_FLUSH_TLB 5 -#define LHCALL_LOAD_IDT_ENTRY 6 -#define LHCALL_SET_STACK 7 -#define LHCALL_TS 8 -#define LHCALL_SET_CLOCKEVENT 9 -#define LHCALL_HALT 10 -#define LHCALL_BIND_DMA 12 -#define LHCALL_SEND_DMA 13 -#define LHCALL_SET_PTE 14 -#define LHCALL_SET_PMD 15 -#define LHCALL_LOAD_TLS 16 +#include #define LG_CLOCK_MIN_DELTA 100UL #define LG_CLOCK_MAX_DELTA ULONG_MAX -/*G:031 First, how does our Guest contact the Host to ask for privileged - * operations? There are two ways: the direct way is to make a "hypercall", - * to make requests of the Host Itself. - * - * Our hypercall mechanism uses the highest unused trap code (traps 32 and - * above are used by real hardware interrupts). Seventeen hypercalls are - * available: the hypercall number is put in the %eax register, and the - * arguments (when required) are placed in %edx, %ebx and %ecx. If a return - * value makes sense, it's returned in %eax. - * - * Grossly invalid calls result in Sudden Death at the hands of the vengeful - * Host, rather than returning failure. This reflects Winston Churchill's - * definition of a gentleman: "someone who is only rude intentionally". */ -#define LGUEST_TRAP_ENTRY 0x1F - -static inline unsigned long -hcall(unsigned long call, - unsigned long arg1, unsigned long arg2, unsigned long arg3) -{ - /* "int" is the Intel instruction to trigger a trap. */ - asm volatile("int $" __stringify(LGUEST_TRAP_ENTRY) - /* The call is in %eax (aka "a"), and can be replaced */ - : "=a"(call) - /* The other arguments are in %eax, %edx, %ebx & %ecx */ - : "a"(call), "d"(arg1), "b"(arg2), "c"(arg3) - /* "memory" means this might write somewhere in memory. - * This isn't true for all calls, but it's safe to tell - * gcc that it might happen so it doesn't get clever. */ - : "memory"); - return call; -} -/*:*/ - -void async_hcall(unsigned long call, - unsigned long arg1, unsigned long arg2, unsigned long arg3); - -/* Can't use our min() macro here: needs to be a constant */ -#define LGUEST_IRQS (NR_IRQS < 32 ? NR_IRQS: 32) - -#define LHCALL_RING_SIZE 64 -struct hcall_ring -{ - u32 eax, edx, ebx, ecx; -}; - /*G:032 The second method of communicating with the Host is to via "struct * lguest_data". The Guest's very first hypercall is to tell the Host where * this is, and then the Guest and Host both publish information in it. :*/ @@ -113,4 +52,4 @@ struct lguest_data }; extern struct lguest_data lguest_data; #endif /* __ASSEMBLY__ */ -#endif /* _ASM_LGUEST_H */ +#endif /* _LINUX_LGUEST_H */ -- cgit v1.2.3-71-gd317 From 48245cc0708d49d1d0566b9fa617ad6c5f4c6934 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 11:03:27 +1000 Subject: Remove fixed limit on number of guests, and lguests array. Back when we had all the Guest state in the switcher, we had a fixed array of them. This is no longer necessary. If we switch the network code to using random_ether_addr (46 bits is enough to avoid clashes), we can get rid of the concept of "guest id" altogether. Signed-off-by: Rusty Russell --- drivers/lguest/core.c | 14 -------------- drivers/lguest/hypercalls.c | 4 +--- drivers/lguest/io.c | 10 +++++----- drivers/lguest/lg.h | 5 +---- drivers/lguest/lguest_user.c | 17 ++++++----------- drivers/net/lguest_net.c | 7 +------ include/linux/lguest.h | 2 -- 7 files changed, 14 insertions(+), 45 deletions(-) (limited to 'include/linux') diff --git a/drivers/lguest/core.c b/drivers/lguest/core.c index eb95860cf098..ca581ef591e8 100644 --- a/drivers/lguest/core.c +++ b/drivers/lguest/core.c @@ -47,10 +47,6 @@ static struct { DEFINE_MUTEX(lguest_lock); static DEFINE_PER_CPU(struct lguest *, last_guest); -/* FIXME: Make dynamic. */ -#define MAX_LGUEST_GUESTS 16 -struct lguest lguests[MAX_LGUEST_GUESTS]; - /* Offset from where switcher.S was compiled to where we've copied it */ static unsigned long switcher_offset(void) { @@ -660,16 +656,6 @@ int run_guest(struct lguest *lg, unsigned long __user *user) * deliver_trap() and demand_page(). After all those, we'll be ready to * examine the Switcher, and our philosophical understanding of the Host/Guest * duality will be complete. :*/ - -int find_free_guest(void) -{ - unsigned int i; - for (i = 0; i < MAX_LGUEST_GUESTS; i++) - if (!lguests[i].tsk) - return i; - return -1; -} - static void adjust_pge(void *on) { if (on) diff --git a/drivers/lguest/hypercalls.c b/drivers/lguest/hypercalls.c index 02e67b49ea4f..8bde20934f91 100644 --- a/drivers/lguest/hypercalls.c +++ b/drivers/lguest/hypercalls.c @@ -225,9 +225,7 @@ static void initialize(struct lguest *lg) /* We tell the Guest that it can't use the top 4MB of virtual * addresses used by the Switcher. */ || put_user(4U*1024*1024, &lg->lguest_data->reserve_mem) - || put_user(tsc_speed, &lg->lguest_data->tsc_khz) - /* We also give the Guest a unique id, as used in lguest_net.c. */ - || put_user(lg->guestid, &lg->lguest_data->guestid)) + || put_user(tsc_speed, &lg->lguest_data->tsc_khz)) kill_guest(lg, "bad guest page %p", lg->lguest_data); /* We write the current time into the Guest's data page once now. */ diff --git a/drivers/lguest/io.c b/drivers/lguest/io.c index 3a845335fee8..0e842e9caf68 100644 --- a/drivers/lguest/io.c +++ b/drivers/lguest/io.c @@ -212,7 +212,7 @@ int bind_dma(struct lguest *lg, lg->dma[i].num_dmas = numdmas; lg->dma[i].next_dma = 0; lg->dma[i].key = key; - lg->dma[i].guestid = lg->guestid; + lg->dma[i].owner = lg; lg->dma[i].interrupt = interrupt; /* Now we add it to the hash table: the position @@ -412,7 +412,7 @@ static int dma_transfer(struct lguest *srclg, /* From the "struct lguest_dma_info" we found in the hash, grab the * Guest. */ - dstlg = &lguests[dst->guestid]; + dstlg = dst->owner; /* Read in the source "struct lguest_dma" handed to SEND_DMA. */ lgread(srclg, &src_dma, udma, sizeof(src_dma)); @@ -506,8 +506,8 @@ again: struct lguest_dma_info *i; /* Look through the hash for other Guests. */ list_for_each_entry(i, &dma_hash[hash(&key)], list) { - /* Don't send to ourselves. */ - if (i->guestid == lg->guestid) + /* Don't send to ourselves (would deadlock). */ + if (i->owner->mm == lg->mm) continue; if (!key_eq(&key, &i->key)) continue; @@ -594,7 +594,7 @@ unsigned long get_dma_buffer(struct lguest *lg, * send to its own Guest for the moment, so the entry must be for this * Guest) */ list_for_each_entry(i, &dma_hash[hash(&key)], list) { - if (key_eq(&key, &i->key) && i->guestid == lg->guestid) { + if (key_eq(&key, &i->key) && i->owner == lg) { unsigned int j; /* Look through the registered DMA array for an * available buffer. */ diff --git a/drivers/lguest/lg.h b/drivers/lguest/lg.h index 54f2c2472bec..c9d1dc29490d 100644 --- a/drivers/lguest/lg.h +++ b/drivers/lguest/lg.h @@ -51,9 +51,9 @@ struct lguest_dma_info struct list_head list; union futex_key key; unsigned long dmas; + struct lguest *owner; u16 next_dma; u16 num_dmas; - u16 guestid; u8 interrupt; /* 0 when not registered */ }; @@ -140,7 +140,6 @@ struct lguest struct lguest_data __user *lguest_data; struct task_struct *tsk; struct mm_struct *mm; /* == tsk->mm, but that becomes NULL on exit */ - u16 guestid; u32 pfn_limit; /* This provides the offset to the base of guest-physical * memory in the Launcher. */ @@ -195,7 +194,6 @@ struct lguest DECLARE_BITMAP(irqs_pending, LGUEST_IRQS); }; -extern struct lguest lguests[]; extern struct mutex lguest_lock; /* core.c: */ @@ -203,7 +201,6 @@ u32 lgread_u32(struct lguest *lg, unsigned long addr); void lgwrite_u32(struct lguest *lg, unsigned long addr, u32 val); void lgread(struct lguest *lg, void *buf, unsigned long addr, unsigned len); void lgwrite(struct lguest *lg, unsigned long, const void *buf, unsigned len); -int find_free_guest(void); int lguest_address_ok(const struct lguest *lg, unsigned long addr, unsigned long len); int run_guest(struct lguest *lg, unsigned long __user *user); diff --git a/drivers/lguest/lguest_user.c b/drivers/lguest/lguest_user.c index 816d4d12a801..5632ed82798a 100644 --- a/drivers/lguest/lguest_user.c +++ b/drivers/lguest/lguest_user.c @@ -167,11 +167,11 @@ static int initialize(struct file *file, const u32 __user *input) /* "struct lguest" contains everything we (the Host) know about a * Guest. */ struct lguest *lg; - int err, i; + int err; u32 args[5]; - /* We grab the Big Lguest lock, which protects the global array - * "lguests" and multiple simultaneous initializations. */ + /* We grab the Big Lguest lock, which protects against multiple + * simultaneous initializations. */ mutex_lock(&lguest_lock); /* You can't initialize twice! Close the device and start again... */ if (file->private_data) { @@ -184,18 +184,13 @@ static int initialize(struct file *file, const u32 __user *input) goto unlock; } - /* Find an unused guest. */ - i = find_free_guest(); - if (i < 0) { - err = -ENOSPC; + lg = kzalloc(sizeof(*lg), GFP_KERNEL); + if (!lg) { + err = -ENOMEM; goto unlock; } - /* OK, we have an index into the "lguest" array: "lg" is a convenient - * pointer. */ - lg = &lguests[i]; /* Populate the easy fields of our "struct lguest" */ - lg->guestid = i; lg->mem_base = (void __user *)(long)args[0]; lg->pfn_limit = args[1]; lg->page_offset = args[4]; diff --git a/drivers/net/lguest_net.c b/drivers/net/lguest_net.c index abce2ee8430a..e255476f224f 100644 --- a/drivers/net/lguest_net.c +++ b/drivers/net/lguest_net.c @@ -463,12 +463,7 @@ static int lguestnet_probe(struct lguest_device *lgdev) /* Ethernet defaults with some changes */ ether_setup(dev); dev->set_mac_address = NULL; - - dev->dev_addr[0] = 0x02; /* set local assignment bit (IEEE802) */ - dev->dev_addr[1] = 0x00; - memcpy(&dev->dev_addr[2], &lguest_data.guestid, 2); - dev->dev_addr[4] = 0x00; - dev->dev_addr[5] = 0x00; + random_ether_addr(dev->dev_addr); dev->open = lguestnet_open; dev->stop = lguestnet_close; diff --git a/include/linux/lguest.h b/include/linux/lguest.h index d4d94a127f35..8e959deed412 100644 --- a/include/linux/lguest.h +++ b/include/linux/lguest.h @@ -41,8 +41,6 @@ struct lguest_data /* Fields initialized by the Host at boot: */ /* Memory not to try to access */ unsigned long reserve_mem; - /* ID of this Guest (used by network driver to set ethernet address) */ - u16 guestid; /* KHz for the TSC clock. */ u32 tsc_khz; -- cgit v1.2.3-71-gd317 From b410e7b1499c49513cab18275db8a8ab549d9e09 Mon Sep 17 00:00:00 2001 From: Jes Sorensen Date: Mon, 22 Oct 2007 11:03:31 +1000 Subject: Make hypercalls arch-independent. Clean up the hypercall code to make the code in hypercalls.c architecture independent. First process the common hypercalls and then call lguest_arch_do_hcall() if the call hasn't been handled. Rename struct hcall_ring to hcall_args. This patch requires the previous patch which reorganize the layout of struct lguest_regs on i386 so they match the layout of struct hcall_args. Signed-off-by: Jes Sorensen Signed-off-by: Rusty Russell --- arch/x86/lguest/boot.c | 8 ++-- drivers/lguest/hypercalls.c | 104 ++++++++++++----------------------------- drivers/lguest/lg.h | 4 +- drivers/lguest/x86/core.c | 62 +++++++++++++++++++++++- include/asm-x86/lguest_hcall.h | 8 ++-- include/linux/lguest.h | 2 +- 6 files changed, 104 insertions(+), 84 deletions(-) (limited to 'include/linux') diff --git a/arch/x86/lguest/boot.c b/arch/x86/lguest/boot.c index c7ebc131fe2c..1040f9b2f997 100644 --- a/arch/x86/lguest/boot.c +++ b/arch/x86/lguest/boot.c @@ -146,10 +146,10 @@ void async_hcall(unsigned long call, /* Table full, so do normal hcall which will flush table. */ hcall(call, arg1, arg2, arg3); } else { - lguest_data.hcalls[next_call].eax = call; - lguest_data.hcalls[next_call].edx = arg1; - lguest_data.hcalls[next_call].ebx = arg2; - lguest_data.hcalls[next_call].ecx = arg3; + lguest_data.hcalls[next_call].arg0 = call; + lguest_data.hcalls[next_call].arg1 = arg1; + lguest_data.hcalls[next_call].arg2 = arg2; + lguest_data.hcalls[next_call].arg3 = arg3; /* Arguments must all be written before we mark it to go */ wmb(); lguest_data.hcall_status[next_call] = 0; diff --git a/drivers/lguest/hypercalls.c b/drivers/lguest/hypercalls.c index 0175a9f03347..2859a7687288 100644 --- a/drivers/lguest/hypercalls.c +++ b/drivers/lguest/hypercalls.c @@ -25,17 +25,13 @@ #include #include #include -#include #include "lg.h" -/*H:120 This is the core hypercall routine: where the Guest gets what it - * wants. Or gets killed. Or, in the case of LHCALL_CRASH, both. - * - * Remember from the Guest: %eax == which call to make, and the arguments are - * packed into %edx, %ebx and %ecx if needed. */ -static void do_hcall(struct lguest *lg, struct lguest_regs *regs) +/*H:120 This is the core hypercall routine: where the Guest gets what it wants. + * Or gets killed. Or, in the case of LHCALL_CRASH, both. */ +static void do_hcall(struct lguest *lg, struct hcall_args *args) { - switch (regs->eax) { + switch (args->arg0) { case LHCALL_FLUSH_ASYNC: /* This call does nothing, except by breaking out of the Guest * it makes us process all the asynchronous hypercalls. */ @@ -51,7 +47,7 @@ static void do_hcall(struct lguest *lg, struct lguest_regs *regs) char msg[128]; /* If the lgread fails, it will call kill_guest() itself; the * kill_guest() with the message will be ignored. */ - lgread(lg, msg, regs->edx, sizeof(msg)); + lgread(lg, msg, args->arg1, sizeof(msg)); msg[sizeof(msg)-1] = '\0'; kill_guest(lg, "CRASH: %s", msg); break; @@ -59,7 +55,7 @@ static void do_hcall(struct lguest *lg, struct lguest_regs *regs) case LHCALL_FLUSH_TLB: /* FLUSH_TLB comes in two flavors, depending on the * argument: */ - if (regs->edx) + if (args->arg1) guest_pagetable_clear_all(lg); else guest_pagetable_flush_user(lg); @@ -71,55 +67,47 @@ static void do_hcall(struct lguest *lg, struct lguest_regs *regs) * it here. This can legitimately fail, since we currently * place a limit on the number of DMA pools a Guest can have. * So we return true or false from this call. */ - regs->eax = bind_dma(lg, regs->edx, regs->ebx, - regs->ecx >> 8, regs->ecx & 0xFF); + args->arg0 = bind_dma(lg, args->arg1, args->arg2, + args->arg3 >> 8, args->arg3 & 0xFF); break; /* All these calls simply pass the arguments through to the right * routines. */ case LHCALL_SEND_DMA: - send_dma(lg, regs->edx, regs->ebx); - break; - case LHCALL_LOAD_GDT: - load_guest_gdt(lg, regs->edx, regs->ebx); - break; - case LHCALL_LOAD_IDT_ENTRY: - load_guest_idt_entry(lg, regs->edx, regs->ebx, regs->ecx); + send_dma(lg, args->arg1, args->arg2); break; case LHCALL_NEW_PGTABLE: - guest_new_pagetable(lg, regs->edx); + guest_new_pagetable(lg, args->arg1); break; case LHCALL_SET_STACK: - guest_set_stack(lg, regs->edx, regs->ebx, regs->ecx); + guest_set_stack(lg, args->arg1, args->arg2, args->arg3); break; case LHCALL_SET_PTE: - guest_set_pte(lg, regs->edx, regs->ebx, mkgpte(regs->ecx)); + guest_set_pte(lg, args->arg1, args->arg2, mkgpte(args->arg3)); break; case LHCALL_SET_PMD: - guest_set_pmd(lg, regs->edx, regs->ebx); - break; - case LHCALL_LOAD_TLS: - guest_load_tls(lg, regs->edx); + guest_set_pmd(lg, args->arg1, args->arg2); break; case LHCALL_SET_CLOCKEVENT: - guest_set_clockevent(lg, regs->edx); + guest_set_clockevent(lg, args->arg1); break; - case LHCALL_TS: /* This sets the TS flag, as we saw used in run_guest(). */ - lg->ts = regs->edx; + lg->ts = args->arg1; break; case LHCALL_HALT: /* Similarly, this sets the halted flag for run_guest(). */ lg->halted = 1; break; default: - kill_guest(lg, "Bad hypercall %li\n", regs->eax); + if (lguest_arch_do_hcall(lg, args)) + kill_guest(lg, "Bad hypercall %li\n", args->arg0); } } +/*:*/ -/* Asynchronous hypercalls are easy: we just look in the array in the Guest's - * "struct lguest_data" and see if there are any new ones marked "ready". +/*H:124 Asynchronous hypercalls are easy: we just look in the array in the + * Guest's "struct lguest_data" to see if any new ones are marked "ready". * * We are careful to do these in order: obviously we respect the order the * Guest put them in the ring, but we also promise the Guest that they will @@ -134,10 +122,9 @@ static void do_async_hcalls(struct lguest *lg) if (copy_from_user(&st, &lg->lguest_data->hcall_status, sizeof(st))) return; - /* We process "struct lguest_data"s hcalls[] ring once. */ for (i = 0; i < ARRAY_SIZE(st); i++) { - struct lguest_regs regs; + struct hcall_args args; /* We remember where we were up to from last time. This makes * sure that the hypercalls are done in the order the Guest * places them in the ring. */ @@ -152,18 +139,16 @@ static void do_async_hcalls(struct lguest *lg) if (++lg->next_hcall == LHCALL_RING_SIZE) lg->next_hcall = 0; - /* We copy the hypercall arguments into a fake register - * structure. This makes life simple for do_hcall(). */ - if (get_user(regs.eax, &lg->lguest_data->hcalls[n].eax) - || get_user(regs.edx, &lg->lguest_data->hcalls[n].edx) - || get_user(regs.ecx, &lg->lguest_data->hcalls[n].ecx) - || get_user(regs.ebx, &lg->lguest_data->hcalls[n].ebx)) { + /* Copy the hypercall arguments into a local copy of + * the hcall_args struct. */ + if (copy_from_user(&args, &lg->lguest_data->hcalls[n], + sizeof(struct hcall_args))) { kill_guest(lg, "Fetching async hypercalls"); break; } /* Do the hypercall, same as a normal one. */ - do_hcall(lg, ®s); + do_hcall(lg, &args); /* Mark the hypercall done. */ if (put_user(0xFF, &lg->lguest_data->hcall_status[n])) { @@ -182,41 +167,16 @@ static void do_async_hcalls(struct lguest *lg) * Guest makes a hypercall, we end up here to set things up: */ static void initialize(struct lguest *lg) { - u32 tsc_speed; /* You can't do anything until you're initialized. The Guest knows the * rules, so we're unforgiving here. */ - if (lg->regs->eax != LHCALL_LGUEST_INIT) { - kill_guest(lg, "hypercall %li before LGUEST_INIT", - lg->regs->eax); + if (lg->hcall->arg0 != LHCALL_LGUEST_INIT) { + kill_guest(lg, "hypercall %li before INIT", lg->hcall->arg0); return; } - /* We insist that the Time Stamp Counter exist and doesn't change with - * cpu frequency. Some devious chip manufacturers decided that TSC - * changes could be handled in software. I decided that time going - * backwards might be good for benchmarks, but it's bad for users. - * - * We also insist that the TSC be stable: the kernel detects unreliable - * TSCs for its own purposes, and we use that here. */ - if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC) && !check_tsc_unstable()) - tsc_speed = tsc_khz; - else - tsc_speed = 0; - - /* The pointer to the Guest's "struct lguest_data" is the only - * argument. We check that address now. */ - if (!lguest_address_ok(lg, lg->regs->edx, sizeof(*lg->lguest_data))) { + if (lguest_arch_init_hypercalls(lg)) kill_guest(lg, "bad guest page %p", lg->lguest_data); - return; - } - - /* Having checked it, we simply set lg->lguest_data to point straight - * into the Launcher's memory at the right place and then use - * copy_to_user/from_user from now on, instead of lgread/write. I put - * this in to show that I'm not immune to writing stupid - * optimizations. */ - lg->lguest_data = lg->mem_base + lg->regs->edx; /* The Guest tells us where we're not to deliver interrupts by putting * the range of addresses into "struct lguest_data". */ @@ -224,8 +184,7 @@ static void initialize(struct lguest *lg) || get_user(lg->noirq_end, &lg->lguest_data->noirq_end) /* We tell the Guest that it can't use the top 4MB of virtual * addresses used by the Switcher. */ - || put_user(4U*1024*1024, &lg->lguest_data->reserve_mem) - || put_user(tsc_speed, &lg->lguest_data->tsc_khz)) + || put_user(4U*1024*1024, &lg->lguest_data->reserve_mem)) kill_guest(lg, "bad guest page %p", lg->lguest_data); /* We write the current time into the Guest's data page once now. */ @@ -237,9 +196,6 @@ static void initialize(struct lguest *lg) * page. */ guest_pagetable_clear_all(lg); } -/* Now we've examined the hypercall code; our Guest can make requests. There - * is one other way we can do things for the Guest, as we see in - * emulate_insn(). */ /*H:100 * Hypercalls diff --git a/drivers/lguest/lg.h b/drivers/lguest/lg.h index 662994b776cc..00c869bd9f79 100644 --- a/drivers/lguest/lg.h +++ b/drivers/lguest/lg.h @@ -107,7 +107,7 @@ struct lguest u8 ss1; /* If a hypercall was asked for, this points to the arguments. */ - struct lguest_regs *hcall; + struct hcall_args *hcall; /* Do we need to stop what we're doing and return to userspace? */ int break_out; @@ -197,6 +197,8 @@ void lguest_arch_host_init(void); void lguest_arch_host_fini(void); void lguest_arch_run_guest(struct lguest *lg); void lguest_arch_handle_trap(struct lguest *lg); +int lguest_arch_init_hypercalls(struct lguest *lg); +int lguest_arch_do_hcall(struct lguest *lg, struct hcall_args *args); /* /switcher.S: */ extern char start_switcher_text[], end_switcher_text[], switch_to_guest[]; diff --git a/drivers/lguest/x86/core.c b/drivers/lguest/x86/core.c index 0cc251cbc72a..2ef64a2734d3 100644 --- a/drivers/lguest/x86/core.c +++ b/drivers/lguest/x86/core.c @@ -323,7 +323,9 @@ void lguest_arch_handle_trap(struct lguest *lg) cond_resched(); return; case LGUEST_TRAP_ENTRY: - lg->hcall = lg->regs; + /* Our 'struct hcall_args' maps directly over our regs: we set + * up the pointer now to indicate a hypercall is pending. */ + lg->hcall = (struct hcall_args *)lg->regs; return; } @@ -475,3 +477,61 @@ void __exit lguest_arch_host_fini(void) } unlock_cpu_hotplug(); } + + +/*H:122 The i386-specific hypercalls simply farm out to the right functions. */ +int lguest_arch_do_hcall(struct lguest *lg, struct hcall_args *args) +{ + switch (args->arg0) { + case LHCALL_LOAD_GDT: + load_guest_gdt(lg, args->arg1, args->arg2); + break; + case LHCALL_LOAD_IDT_ENTRY: + load_guest_idt_entry(lg, args->arg1, args->arg2, args->arg3); + break; + case LHCALL_LOAD_TLS: + guest_load_tls(lg, args->arg1); + break; + default: + /* Bad Guest. Bad! */ + return -EIO; + } + return 0; +} + +/*H:126 i386-specific hypercall initialization: */ +int lguest_arch_init_hypercalls(struct lguest *lg) +{ + u32 tsc_speed; + + /* The pointer to the Guest's "struct lguest_data" is the only + * argument. We check that address now. */ + if (!lguest_address_ok(lg, lg->hcall->arg1, sizeof(*lg->lguest_data))) + return -EFAULT; + + /* Having checked it, we simply set lg->lguest_data to point straight + * into the Launcher's memory at the right place and then use + * copy_to_user/from_user from now on, instead of lgread/write. I put + * this in to show that I'm not immune to writing stupid + * optimizations. */ + lg->lguest_data = lg->mem_base + lg->hcall->arg1; + + /* We insist that the Time Stamp Counter exist and doesn't change with + * cpu frequency. Some devious chip manufacturers decided that TSC + * changes could be handled in software. I decided that time going + * backwards might be good for benchmarks, but it's bad for users. + * + * We also insist that the TSC be stable: the kernel detects unreliable + * TSCs for its own purposes, and we use that here. */ + if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC) && !check_tsc_unstable()) + tsc_speed = tsc_khz; + else + tsc_speed = 0; + if (put_user(tsc_speed, &lg->lguest_data->tsc_khz)) + return -EFAULT; + + return 0; +} +/* Now we've examined the hypercall code; our Guest can make requests. There + * is one other way we can do things for the Guest, as we see in + * emulate_insn(). :*/ diff --git a/include/asm-x86/lguest_hcall.h b/include/asm-x86/lguest_hcall.h index 7859cfe0ebb2..8f2a1edc4fe2 100644 --- a/include/asm-x86/lguest_hcall.h +++ b/include/asm-x86/lguest_hcall.h @@ -2,6 +2,8 @@ #ifndef _X86_LGUEST_HCALL_H #define _X86_LGUEST_HCALL_H +#include + #define LHCALL_FLUSH_ASYNC 0 #define LHCALL_LGUEST_INIT 1 #define LHCALL_CRASH 2 @@ -59,9 +61,9 @@ void async_hcall(unsigned long call, #define LGUEST_IRQS (NR_IRQS < 32 ? NR_IRQS: 32) #define LHCALL_RING_SIZE 64 -struct hcall_ring +struct hcall_args { - u32 eax, edx, ebx, ecx; + /* These map directly onto eax, ebx, ecx, edx in struct lguest_regs */ + unsigned long arg0, arg2, arg3, arg1; }; - #endif /* _I386_LGUEST_HCALL_H */ diff --git a/include/linux/lguest.h b/include/linux/lguest.h index 8e959deed412..ea335c8f86c3 100644 --- a/include/linux/lguest.h +++ b/include/linux/lguest.h @@ -36,7 +36,7 @@ struct lguest_data /* 0xFF == done (set by Host), 0 == pending (set by Guest). */ u8 hcall_status[LHCALL_RING_SIZE]; /* The actual registers for the hypercalls. */ - struct hcall_ring hcalls[LHCALL_RING_SIZE]; + struct hcall_args hcalls[LHCALL_RING_SIZE]; /* Fields initialized by the Host at boot: */ /* Memory not to try to access */ -- cgit v1.2.3-71-gd317 From 47aee45ae3c708ab678e09abfba0efaf6ca0e87a Mon Sep 17 00:00:00 2001 From: Jes Sorensen Date: Mon, 22 Oct 2007 11:03:33 +1000 Subject: lguest.h declares a struct timespec, make it include linux/time.h Signed-off-by: Jes Sorensen Signed-off-by: Rusty Russell --- include/linux/lguest.h | 1 + 1 file changed, 1 insertion(+) (limited to 'include/linux') diff --git a/include/linux/lguest.h b/include/linux/lguest.h index ea335c8f86c3..9ddac2f0a97c 100644 --- a/include/linux/lguest.h +++ b/include/linux/lguest.h @@ -4,6 +4,7 @@ #define _LINUX_LGUEST_H #ifndef __ASSEMBLY__ +#include #include #include -- cgit v1.2.3-71-gd317 From c18acd73ffc209def08003a1927473096f66c5ad Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 11:03:35 +1000 Subject: Allow guest to specify syscall vector to use. (Based on Ron Minnich's LGUEST_PLAN9_SYSCALL patch). This patch allows Guests to specify what system call vector they want, and we try to reserve it. We only allow one non-Linux system call vector, to try to avoid DoS on the Host. Signed-off-by: Rusty Russell --- arch/x86/lguest/boot.c | 1 + drivers/lguest/core.c | 30 ++++++++++++++------- drivers/lguest/interrupts_and_traps.c | 49 ++++++++++++++++++++++++++++++++++- drivers/lguest/lg.h | 3 +++ drivers/lguest/x86/core.c | 4 +++ include/linux/lguest.h | 3 +++ 6 files changed, 79 insertions(+), 11 deletions(-) (limited to 'include/linux') diff --git a/arch/x86/lguest/boot.c b/arch/x86/lguest/boot.c index 1040f9b2f997..3a06b51c98ad 100644 --- a/arch/x86/lguest/boot.c +++ b/arch/x86/lguest/boot.c @@ -87,6 +87,7 @@ struct lguest_data lguest_data = { .noirq_start = (u32)lguest_noirq_start, .noirq_end = (u32)lguest_noirq_end, .blocked_interrupts = { 1 }, /* Block timer interrupts */ + .syscall_vec = SYSCALL_VECTOR, }; static cycle_t clock_base; diff --git a/drivers/lguest/core.c b/drivers/lguest/core.c index 02556bae9e9f..41b26e592d38 100644 --- a/drivers/lguest/core.c +++ b/drivers/lguest/core.c @@ -281,37 +281,47 @@ static int __init init(void) /* First we put the Switcher up in very high virtual memory. */ err = map_switcher(); if (err) - return err; + goto out; /* Now we set up the pagetable implementation for the Guests. */ err = init_pagetables(switcher_page, SHARED_SWITCHER_PAGES); - if (err) { - unmap_switcher(); - return err; - } + if (err) + goto unmap; /* The I/O subsystem needs some things initialized. */ lguest_io_init(); + /* We might need to reserve an interrupt vector. */ + err = init_interrupts(); + if (err) + goto free_pgtables; + /* /dev/lguest needs to be registered. */ err = lguest_device_init(); - if (err) { - free_pagetables(); - unmap_switcher(); - return err; - } + if (err) + goto free_interrupts; /* Finally we do some architecture-specific setup. */ lguest_arch_host_init(); /* All good! */ return 0; + +free_interrupts: + free_interrupts(); +free_pgtables: + free_pagetables(); +unmap: + unmap_switcher(); +out: + return err; } /* Cleaning up is just the same code, backwards. With a little French. */ static void __exit fini(void) { lguest_device_remove(); + free_interrupts(); free_pagetables(); unmap_switcher(); diff --git a/drivers/lguest/interrupts_and_traps.c b/drivers/lguest/interrupts_and_traps.c index fdefc0afc38c..a57d757eab6e 100644 --- a/drivers/lguest/interrupts_and_traps.c +++ b/drivers/lguest/interrupts_and_traps.c @@ -12,8 +12,14 @@ * them first, so we also have a way of "reflecting" them into the Guest as if * they had been delivered to it directly. :*/ #include +#include +#include #include "lg.h" +/* Allow Guests to use a non-128 (ie. non-Linux) syscall trap. */ +static unsigned int syscall_vector = SYSCALL_VECTOR; +module_param(syscall_vector, uint, 0444); + /* The address of the interrupt handler is split into two bits: */ static unsigned long idt_address(u32 lo, u32 hi) { @@ -183,6 +189,47 @@ void maybe_do_interrupt(struct lguest *lg) * timer interrupt. */ write_timestamp(lg); } +/*:*/ + +/* Linux uses trap 128 for system calls. Plan9 uses 64, and Ron Minnich sent + * me a patch, so we support that too. It'd be a big step for lguest if half + * the Plan 9 user base were to start using it. + * + * Actually now I think of it, it's possible that Ron *is* half the Plan 9 + * userbase. Oh well. */ +static bool could_be_syscall(unsigned int num) +{ + /* Normal Linux SYSCALL_VECTOR or reserved vector? */ + return num == SYSCALL_VECTOR || num == syscall_vector; +} + +/* The syscall vector it wants must be unused by Host. */ +bool check_syscall_vector(struct lguest *lg) +{ + u32 vector; + + if (get_user(vector, &lg->lguest_data->syscall_vec)) + return false; + + return could_be_syscall(vector); +} + +int init_interrupts(void) +{ + /* If they want some strange system call vector, reserve it now */ + if (syscall_vector != SYSCALL_VECTOR + && test_and_set_bit(syscall_vector, used_vectors)) { + printk("lg: couldn't reserve syscall %u\n", syscall_vector); + return -EBUSY; + } + return 0; +} + +void free_interrupts(void) +{ + if (syscall_vector != SYSCALL_VECTOR) + clear_bit(syscall_vector, used_vectors); +} /*H:220 Now we've got the routines to deliver interrupts, delivering traps * like page fault is easy. The only trick is that Intel decided that some @@ -224,7 +271,7 @@ static int direct_trap(unsigned int num) { /* Hardware interrupts don't go to the Guest at all (except system * call). */ - if (num >= FIRST_EXTERNAL_VECTOR && num != SYSCALL_VECTOR) + if (num >= FIRST_EXTERNAL_VECTOR && !could_be_syscall(num)) return 0; /* The Host needs to see page faults (for shadow paging and to save the diff --git a/drivers/lguest/lg.h b/drivers/lguest/lg.h index f921684dbe5c..7408cebe995e 100644 --- a/drivers/lguest/lg.h +++ b/drivers/lguest/lg.h @@ -141,6 +141,9 @@ void copy_traps(const struct lguest *lg, struct desc_struct *idt, const unsigned long *def); void guest_set_clockevent(struct lguest *lg, unsigned long delta); void init_clockdev(struct lguest *lg); +bool check_syscall_vector(struct lguest *lg); +int init_interrupts(void); +void free_interrupts(void); /* segments.c: */ void setup_default_gdt_entries(struct lguest_ro_state *state); diff --git a/drivers/lguest/x86/core.c b/drivers/lguest/x86/core.c index 84c09082f27f..a125109446dc 100644 --- a/drivers/lguest/x86/core.c +++ b/drivers/lguest/x86/core.c @@ -530,6 +530,10 @@ int lguest_arch_init_hypercalls(struct lguest *lg) if (put_user(tsc_speed, &lg->lguest_data->tsc_khz)) return -EFAULT; + /* The interrupt code might not like the system call vector. */ + if (!check_syscall_vector(lg)) + kill_guest(lg, "bad syscall vector"); + return 0; } /* Now we've examined the hypercall code; our Guest can make requests. There diff --git a/include/linux/lguest.h b/include/linux/lguest.h index 9ddac2f0a97c..083052236db9 100644 --- a/include/linux/lguest.h +++ b/include/linux/lguest.h @@ -48,6 +48,9 @@ struct lguest_data /* Fields initialized by the Guest at boot: */ /* Instruction range to suppress interrupts even if enabled */ unsigned long noirq_start, noirq_end; + + /* The vector to try to use for system calls (0x40 or 0x80). */ + unsigned int syscall_vec; }; extern struct lguest_data lguest_data; #endif /* __ASSEMBLY__ */ -- cgit v1.2.3-71-gd317 From 47436aa4ad054c1c7c8231618e86ebd9305308dc Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 11:03:36 +1000 Subject: Boot with virtual == physical to get closer to native Linux. 1) This allows us to get alot closer to booting bzImages. 2) It means we don't have to know page_offset. 3) The Guest needs to modify the boot pagetables to create the PAGE_OFFSET mapping before jumping to C code. 4) guest_pa() walks the page tables rather than using page_offset. 5) We don't use page_offset to figure out whether to emulate: it was always kinda quesationable, and won't work for instructions done before remapping (bzImage unpacking in particular). 6) We still want the kernel address for tlb flushing: have the initial hypercall give us that, too. Signed-off-by: Rusty Russell --- Documentation/lguest/lguest.c | 134 ++++++++-------------------------- arch/x86/kernel/asm-offsets_32.c | 1 + arch/x86/lguest/boot.c | 7 +- arch/x86/lguest/i386_head.S | 41 +++++++++-- drivers/lguest/hypercalls.c | 8 +- drivers/lguest/interrupts_and_traps.c | 13 +++- drivers/lguest/lg.h | 8 +- drivers/lguest/lguest_user.c | 11 +-- drivers/lguest/page_tables.c | 47 ++++++++++-- drivers/lguest/x86/core.c | 7 +- include/asm-x86/lguest_hcall.h | 7 +- include/linux/lguest.h | 5 +- 12 files changed, 141 insertions(+), 148 deletions(-) (limited to 'include/linux') diff --git a/Documentation/lguest/lguest.c b/Documentation/lguest/lguest.c index 4950b03514e6..32c2eaf94c4d 100644 --- a/Documentation/lguest/lguest.c +++ b/Documentation/lguest/lguest.c @@ -178,19 +178,16 @@ static void *get_pages(unsigned int num) /* To find out where to start we look for the magic Guest string, which marks * the code we see in lguest_asm.S. This is a hack which we are currently * plotting to replace with the normal Linux entry point. */ -static unsigned long entry_point(const void *start, const void *end, - unsigned long page_offset) +static unsigned long entry_point(const void *start, const void *end) { const void *p; - /* The scan gives us the physical starting address. We want the - * virtual address in this case, and fortunately, we already figured - * out the physical-virtual difference and passed it here in - * "page_offset". */ + /* The scan gives us the physical starting address. We boot with + * pagetables set up with virtual and physical the same, so that's + * OK. */ for (p = start; p < end; p++) if (memcmp(p, "GenuineLguest", strlen("GenuineLguest")) == 0) - return to_guest_phys(p + strlen("GenuineLguest")) - + page_offset; + return to_guest_phys(p + strlen("GenuineLguest")); errx(1, "Is this image a genuine lguest?"); } @@ -224,14 +221,11 @@ static void map_at(int fd, void *addr, unsigned long offset, unsigned long len) * by all modern binaries on Linux including the kernel. * * The ELF headers give *two* addresses: a physical address, and a virtual - * address. The Guest kernel expects to be placed in memory at the physical - * address, and the page tables set up so it will correspond to that virtual - * address. We return the difference between the virtual and physical - * addresses in the "page_offset" pointer. + * address. We use the physical address; the Guest will map itself to the + * virtual address. * * We return the starting address. */ -static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr, - unsigned long *page_offset) +static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr) { void *start = (void *)-1, *end = NULL; Elf32_Phdr phdr[ehdr->e_phnum]; @@ -255,9 +249,6 @@ static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr, if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr)) err(1, "Reading program headers"); - /* We don't know page_offset yet. */ - *page_offset = 0; - /* Try all the headers: there are usually only three. A read-only one, * a read-write one, and a "note" section which isn't loadable. */ for (i = 0; i < ehdr->e_phnum; i++) { @@ -268,14 +259,6 @@ static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr, verbose("Section %i: size %i addr %p\n", i, phdr[i].p_memsz, (void *)phdr[i].p_paddr); - /* We expect a simple linear address space: every segment must - * have the same difference between virtual (p_vaddr) and - * physical (p_paddr) address. */ - if (!*page_offset) - *page_offset = phdr[i].p_vaddr - phdr[i].p_paddr; - else if (*page_offset != phdr[i].p_vaddr - phdr[i].p_paddr) - errx(1, "Page offset of section %i different", i); - /* We track the first and last address we mapped, so we can * tell entry_point() where to scan. */ if (from_guest_phys(phdr[i].p_paddr) < start) @@ -288,50 +271,13 @@ static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr, phdr[i].p_offset, phdr[i].p_filesz); } - return entry_point(start, end, *page_offset); -} - -/*L:170 Prepare to be SHOCKED and AMAZED. And possibly a trifle nauseated. - * - * We know that CONFIG_PAGE_OFFSET sets what virtual address the kernel expects - * to be. We don't know what that option was, but we can figure it out - * approximately by looking at the addresses in the code. I chose the common - * case of reading a memory location into the %eax register: - * - * movl , %eax - * - * This gets encoded as five bytes: "0xA1 <4-byte-address>". For example, - * "0xA1 0x18 0x60 0x47 0xC0" reads the address 0xC0476018 into %eax. - * - * In this example can guess that the kernel was compiled with - * CONFIG_PAGE_OFFSET set to 0xC0000000 (it's always a round number). If the - * kernel were larger than 16MB, we might see 0xC1 addresses show up, but our - * kernel isn't that bloated yet. - * - * Unfortunately, x86 has variable-length instructions, so finding this - * particular instruction properly involves writing a disassembler. Instead, - * we rely on statistics. We look for "0xA1" and tally the different bytes - * which occur 4 bytes later (the "0xC0" in our example above). When one of - * those bytes appears three times, we can be reasonably confident that it - * forms the start of CONFIG_PAGE_OFFSET. - * - * This is amazingly reliable. */ -static unsigned long intuit_page_offset(unsigned char *img, unsigned long len) -{ - unsigned int i, possibilities[256] = { 0 }; - - for (i = 0; i + 4 < len; i++) { - /* mov 0xXXXXXXXX,%eax */ - if (img[i] == 0xA1 && ++possibilities[img[i+4]] > 3) - return (unsigned long)img[i+4] << 24; - } - errx(1, "could not determine page offset"); + return entry_point(start, end); } /*L:160 Unfortunately the entire ELF image isn't compressed: the segments * which need loading are extracted and compressed raw. This denies us the * information we need to make a fully-general loader. */ -static unsigned long unpack_bzimage(int fd, unsigned long *page_offset) +static unsigned long unpack_bzimage(int fd) { gzFile f; int ret, len = 0; @@ -352,12 +298,7 @@ static unsigned long unpack_bzimage(int fd, unsigned long *page_offset) verbose("Unpacked size %i addr %p\n", len, img); - /* Without the ELF header, we can't tell virtual-physical gap. This is - * CONFIG_PAGE_OFFSET, and people do actually change it. Fortunately, - * I have a clever way of figuring it out from the code itself. */ - *page_offset = intuit_page_offset(img, len); - - return entry_point(img, img + len, *page_offset); + return entry_point(img, img + len); } /*L:150 A bzImage, unlike an ELF file, is not meant to be loaded. You're @@ -368,7 +309,7 @@ static unsigned long unpack_bzimage(int fd, unsigned long *page_offset) * The bzImage is formed by putting the decompressing code in front of the * compressed kernel code. So we can simple scan through it looking for the * first "gzip" header, and start decompressing from there. */ -static unsigned long load_bzimage(int fd, unsigned long *page_offset) +static unsigned long load_bzimage(int fd) { unsigned char c; int state = 0; @@ -396,7 +337,7 @@ static unsigned long load_bzimage(int fd, unsigned long *page_offset) if (c != 0x03) state = -1; else - return unpack_bzimage(fd, page_offset); + return unpack_bzimage(fd); } } errx(1, "Could not find kernel in bzImage"); @@ -405,7 +346,7 @@ static unsigned long load_bzimage(int fd, unsigned long *page_offset) /*L:140 Loading the kernel is easy when it's a "vmlinux", but most kernels * come wrapped up in the self-decompressing "bzImage" format. With some funky * coding, we can load those, too. */ -static unsigned long load_kernel(int fd, unsigned long *page_offset) +static unsigned long load_kernel(int fd) { Elf32_Ehdr hdr; @@ -415,10 +356,10 @@ static unsigned long load_kernel(int fd, unsigned long *page_offset) /* If it's an ELF file, it starts with "\177ELF" */ if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0) - return map_elf(fd, &hdr, page_offset); + return map_elf(fd, &hdr); /* Otherwise we assume it's a bzImage, and try to unpack it */ - return load_bzimage(fd, page_offset); + return load_bzimage(fd); } /* This is a trivial little helper to align pages. Andi Kleen hated it because @@ -463,27 +404,20 @@ static unsigned long load_initrd(const char *name, unsigned long mem) return len; } -/* Once we know the address the Guest kernel expects, we can construct simple - * linear page tables for all of memory which will get the Guest far enough +/* Once we know how much memory we have, we can construct simple linear page + * tables which set virtual == physical which will get the Guest far enough * into the boot to create its own. * * We lay them out of the way, just below the initrd (which is why we need to * know its size). */ static unsigned long setup_pagetables(unsigned long mem, - unsigned long initrd_size, - unsigned long page_offset) + unsigned long initrd_size) { unsigned long *pgdir, *linear; unsigned int mapped_pages, i, linear_pages; unsigned int ptes_per_page = getpagesize()/sizeof(void *); - /* Ideally we map all physical memory starting at page_offset. - * However, if page_offset is 0xC0000000 we can only map 1G of physical - * (0xC0000000 + 1G overflows). */ - if (mem <= -page_offset) - mapped_pages = mem/getpagesize(); - else - mapped_pages = -page_offset/getpagesize(); + mapped_pages = mem/getpagesize(); /* Each PTE page can map ptes_per_page pages: how many do we need? */ linear_pages = (mapped_pages + ptes_per_page-1)/ptes_per_page; @@ -500,11 +434,9 @@ static unsigned long setup_pagetables(unsigned long mem, for (i = 0; i < mapped_pages; i++) linear[i] = ((i * getpagesize()) | PAGE_PRESENT); - /* The top level points to the linear page table pages above. The - * entry representing page_offset points to the first one, and they - * continue from there. */ + /* The top level points to the linear page table pages above. */ for (i = 0; i < mapped_pages; i += ptes_per_page) { - pgdir[(i + page_offset/getpagesize())/ptes_per_page] + pgdir[i/ptes_per_page] = ((to_guest_phys(linear) + i*sizeof(void *)) | PAGE_PRESENT); } @@ -535,15 +467,12 @@ static void concat(char *dst, char *args[]) /* This is where we actually tell the kernel to initialize the Guest. We saw * the arguments it expects when we looked at initialize() in lguest_user.c: * the base of guest "physical" memory, the top physical page to allow, the - * top level pagetable, the entry point and the page_offset constant for the - * Guest. */ -static int tell_kernel(unsigned long pgdir, unsigned long start, - unsigned long page_offset) + * top level pagetable and the entry point for the Guest. */ +static int tell_kernel(unsigned long pgdir, unsigned long start) { unsigned long args[] = { LHREQ_INITIALIZE, (unsigned long)guest_base, - guest_limit / getpagesize(), - pgdir, start, page_offset }; + guest_limit / getpagesize(), pgdir, start }; int fd; verbose("Guest: %p - %p (%#lx)\n", @@ -1424,9 +1353,9 @@ static void usage(void) /*L:105 The main routine is where the real work begins: */ int main(int argc, char *argv[]) { - /* Memory, top-level pagetable, code startpoint, PAGE_OFFSET and size - * of the (optional) initrd. */ - unsigned long mem = 0, pgdir, start, page_offset, initrd_size = 0; + /* Memory, top-level pagetable, code startpoint and size of the + * (optional) initrd. */ + unsigned long mem = 0, pgdir, start, initrd_size = 0; /* A temporary and the /dev/lguest file descriptor. */ int i, c, lguest_fd; /* The list of Guest devices, based on command line arguments. */ @@ -1500,8 +1429,7 @@ int main(int argc, char *argv[]) setup_console(&device_list); /* Now we load the kernel */ - start = load_kernel(open_or_die(argv[optind+1], O_RDONLY), - &page_offset); + start = load_kernel(open_or_die(argv[optind+1], O_RDONLY)); /* Boot information is stashed at physical address 0 */ boot = from_guest_phys(0); @@ -1518,7 +1446,7 @@ int main(int argc, char *argv[]) } /* Set up the initial linear pagetables, starting below the initrd. */ - pgdir = setup_pagetables(mem, initrd_size, page_offset); + pgdir = setup_pagetables(mem, initrd_size); /* The Linux boot header contains an "E820" memory map: ours is a * simple, single region. */ @@ -1535,7 +1463,7 @@ int main(int argc, char *argv[]) /* We tell the kernel to initialize the Guest: this returns the open * /dev/lguest file descriptor. */ - lguest_fd = tell_kernel(pgdir, start, page_offset); + lguest_fd = tell_kernel(pgdir, start); /* We fork off a child process, which wakes the Launcher whenever one * of the input file descriptors needs attention. Otherwise we would diff --git a/arch/x86/kernel/asm-offsets_32.c b/arch/x86/kernel/asm-offsets_32.c index f8764716b0c0..0e45981b2dd7 100644 --- a/arch/x86/kernel/asm-offsets_32.c +++ b/arch/x86/kernel/asm-offsets_32.c @@ -136,6 +136,7 @@ void foo(void) #ifdef CONFIG_LGUEST_GUEST BLANK(); OFFSET(LGUEST_DATA_irq_enabled, lguest_data, irq_enabled); + OFFSET(LGUEST_DATA_pgdir, lguest_data, pgdir); OFFSET(LGUEST_PAGES_host_gdt_desc, lguest_pages, state.host_gdt_desc); OFFSET(LGUEST_PAGES_host_idt_desc, lguest_pages, state.host_idt_desc); OFFSET(LGUEST_PAGES_host_cr3, lguest_pages, state.host_cr3); diff --git a/arch/x86/lguest/boot.c b/arch/x86/lguest/boot.c index 3a06b51c98ad..090f30cbf24c 100644 --- a/arch/x86/lguest/boot.c +++ b/arch/x86/lguest/boot.c @@ -86,6 +86,7 @@ struct lguest_data lguest_data = { .hcall_status = { [0 ... LHCALL_RING_SIZE-1] = 0xFF }, .noirq_start = (u32)lguest_noirq_start, .noirq_end = (u32)lguest_noirq_end, + .kernel_address = PAGE_OFFSET, .blocked_interrupts = { 1 }, /* Block timer interrupts */ .syscall_vec = SYSCALL_VECTOR, }; @@ -1033,11 +1034,7 @@ __init void lguest_init(void *boot) /*G:070 Now we've seen all the paravirt_ops, we return to * lguest_init() where the rest of the fairly chaotic boot setup - * occurs. - * - * The Host expects our first hypercall to tell it where our "struct - * lguest_data" is, so we do that first. */ - hcall(LHCALL_LGUEST_INIT, __pa(&lguest_data), 0, 0); + * occurs. */ /* The native boot code sets up initial page tables immediately after * the kernel itself, and sets init_pg_tables_end so they're not diff --git a/arch/x86/lguest/i386_head.S b/arch/x86/lguest/i386_head.S index 6d7a74f07c41..ba4282eba5bf 100644 --- a/arch/x86/lguest/i386_head.S +++ b/arch/x86/lguest/i386_head.S @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -8,18 +9,48 @@ * looks for. The plan is that the Linux boot protocol will be extended with a * "platform type" field which will guide us here from the normal entry point, * but for the moment this suffices. The normal boot code uses %esi for the - * boot header, so we do too. We convert it to a virtual address by adding - * PAGE_OFFSET, and hand it to lguest_init() as its argument (ie. %eax). + * boot header, so we do too. + * + * WARNING: be very careful here! We're running at addresses equal to physical + * addesses (around 0), not above PAGE_OFFSET as most code expectes + * (eg. 0xC0000000). Jumps are relative, so they're OK, but we can't touch any + * data. * * The .section line puts this code in .init.text so it will be discarded after * boot. */ .section .init.text, "ax", @progbits .ascii "GenuineLguest" - /* Set up initial stack. */ - movl $(init_thread_union+THREAD_SIZE),%esp + /* Make initial hypercall now, so we can set up the pagetables. */ + movl $LHCALL_LGUEST_INIT, %eax + movl $lguest_data - __PAGE_OFFSET, %edx + int $LGUEST_TRAP_ENTRY + + /* Set up boot information pointer to hand to lguest_init(): it wants + * a virtual address. */ movl %esi, %eax addl $__PAGE_OFFSET, %eax - jmp lguest_init + + /* The Host put the toplevel pagetable in lguest_data.pgdir. The movsl + * instruction uses %esi, so we needed to save it above. */ + movl lguest_data - __PAGE_OFFSET + LGUEST_DATA_pgdir, %esi + + /* Copy first 32 entries of page directory to __PAGE_OFFSET entries. + * This means the first 128M of kernel memory will be mapped at + * PAGE_OFFSET where the kernel expects to run. This will get it far + * enough through boot to switch to its own pagetables. */ + movl $32, %ecx + movl %esi, %edi + addl $((__PAGE_OFFSET >> 22) * 4), %edi + rep + movsl + + /* Set up the initial stack so we can run C code. */ + movl $(init_thread_union+THREAD_SIZE),%esp + + + /* Jumps are relative, and we're running __PAGE_OFFSET too low at the + * moment. */ + jmp lguest_init+__PAGE_OFFSET /*G:055 We create a macro which puts the assembler code between lgstart_ and * lgend_ markers. These templates are put in the .text section: they can't be diff --git a/drivers/lguest/hypercalls.c b/drivers/lguest/hypercalls.c index 02d0ae268267..13b5f2f813de 100644 --- a/drivers/lguest/hypercalls.c +++ b/drivers/lguest/hypercalls.c @@ -181,15 +181,15 @@ static void initialize(struct lguest *lg) /* The Guest tells us where we're not to deliver interrupts by putting * the range of addresses into "struct lguest_data". */ if (get_user(lg->noirq_start, &lg->lguest_data->noirq_start) - || get_user(lg->noirq_end, &lg->lguest_data->noirq_end) - /* We tell the Guest that it can't use the top 4MB of virtual - * addresses used by the Switcher. */ - || put_user(4U*1024*1024, &lg->lguest_data->reserve_mem)) + || get_user(lg->noirq_end, &lg->lguest_data->noirq_end)) kill_guest(lg, "bad guest page %p", lg->lguest_data); /* We write the current time into the Guest's data page once now. */ write_timestamp(lg); + /* page_tables.c will also do some setup. */ + page_table_guest_data_init(lg); + /* This is the one case where the above accesses might have been the * first write to a Guest page. This may have caused a copy-on-write * fault, but the Guest might be referring to the old (read-only) diff --git a/drivers/lguest/interrupts_and_traps.c b/drivers/lguest/interrupts_and_traps.c index a57d757eab6e..3271c0031a1b 100644 --- a/drivers/lguest/interrupts_and_traps.c +++ b/drivers/lguest/interrupts_and_traps.c @@ -62,8 +62,9 @@ static void push_guest_stack(struct lguest *lg, unsigned long *gstack, u32 val) * it). */ static void set_guest_interrupt(struct lguest *lg, u32 lo, u32 hi, int has_err) { - unsigned long gstack; + unsigned long gstack, origstack; u32 eflags, ss, irq_enable; + unsigned long virtstack; /* There are two cases for interrupts: one where the Guest is already * in the kernel, and a more complex one where the Guest is in @@ -71,8 +72,10 @@ static void set_guest_interrupt(struct lguest *lg, u32 lo, u32 hi, int has_err) if ((lg->regs->ss&0x3) != GUEST_PL) { /* The Guest told us their kernel stack with the SET_STACK * hypercall: both the virtual address and the segment */ - gstack = guest_pa(lg, lg->esp1); + virtstack = lg->esp1; ss = lg->ss1; + + origstack = gstack = guest_pa(lg, virtstack); /* We push the old stack segment and pointer onto the new * stack: when the Guest does an "iret" back from the interrupt * handler the CPU will notice they're dropping privilege @@ -81,8 +84,10 @@ static void set_guest_interrupt(struct lguest *lg, u32 lo, u32 hi, int has_err) push_guest_stack(lg, &gstack, lg->regs->esp); } else { /* We're staying on the same Guest (kernel) stack. */ - gstack = guest_pa(lg, lg->regs->esp); + virtstack = lg->regs->esp; ss = lg->regs->ss; + + origstack = gstack = guest_pa(lg, virtstack); } /* Remember that we never let the Guest actually disable interrupts, so @@ -108,7 +113,7 @@ static void set_guest_interrupt(struct lguest *lg, u32 lo, u32 hi, int has_err) /* Now we've pushed all the old state, we change the stack, the code * segment and the address to execute. */ lg->regs->ss = ss; - lg->regs->esp = gstack + lg->page_offset; + lg->regs->esp = virtstack + (gstack - origstack); lg->regs->cs = (__KERNEL_CS|GUEST_PL); lg->regs->eip = idt_address(lo, hi); diff --git a/drivers/lguest/lg.h b/drivers/lguest/lg.h index 7408cebe995e..e4845d7f0688 100644 --- a/drivers/lguest/lg.h +++ b/drivers/lguest/lg.h @@ -63,7 +63,7 @@ struct lguest /* This provides the offset to the base of guest-physical * memory in the Launcher. */ void __user *mem_base; - u32 page_offset; + unsigned long kernel_address; u32 cr2; int halted; int ts; @@ -165,6 +165,8 @@ void guest_set_pte(struct lguest *lg, unsigned long gpgdir, void map_switcher_in_guest(struct lguest *lg, struct lguest_pages *pages); int demand_page(struct lguest *info, unsigned long cr2, int errcode); void pin_page(struct lguest *lg, unsigned long vaddr); +unsigned long guest_pa(struct lguest *lg, unsigned long vaddr); +void page_table_guest_data_init(struct lguest *lg); /* /core.c: */ void lguest_arch_host_init(void); @@ -229,9 +231,5 @@ do { \ } while(0) /* (End of aside) :*/ -static inline unsigned long guest_pa(struct lguest *lg, unsigned long vaddr) -{ - return vaddr - lg->page_offset; -} #endif /* __ASSEMBLY__ */ #endif /* _LGUEST_H */ diff --git a/drivers/lguest/lguest_user.c b/drivers/lguest/lguest_user.c index b184652e45d7..61b177e1e649 100644 --- a/drivers/lguest/lguest_user.c +++ b/drivers/lguest/lguest_user.c @@ -111,7 +111,7 @@ static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o) return run_guest(lg, (unsigned long __user *)user); } -/*L:020 The initialization write supplies 5 pointer sized (32 or 64 bit) +/*L:020 The initialization write supplies 4 pointer sized (32 or 64 bit) * values (in addition to the LHREQ_INITIALIZE value). These are: * * base: The start of the Guest-physical memory inside the Launcher memory. @@ -124,12 +124,6 @@ static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o) * pagetables (which are set up by the Launcher). * * start: The first instruction to execute ("eip" in x86-speak). - * - * page_offset: The PAGE_OFFSET constant in the Guest kernel. We should - * probably wean the code off this, but it's a very useful constant! Any - * address above this is within the Guest kernel, and any kernel address can - * quickly converted from physical to virtual by adding PAGE_OFFSET. It's - * 0xC0000000 (3G) by default, but it's configurable at kernel build time. */ static int initialize(struct file *file, const unsigned long __user *input) { @@ -137,7 +131,7 @@ static int initialize(struct file *file, const unsigned long __user *input) * Guest. */ struct lguest *lg; int err; - unsigned long args[5]; + unsigned long args[4]; /* We grab the Big Lguest lock, which protects against multiple * simultaneous initializations. */ @@ -162,7 +156,6 @@ static int initialize(struct file *file, const unsigned long __user *input) /* Populate the easy fields of our "struct lguest" */ lg->mem_base = (void __user *)(long)args[0]; lg->pfn_limit = args[1]; - lg->page_offset = args[4]; /* We need a complete page for the Guest registers: they are accessible * to the Guest and we can only grant it access to whole pages. */ diff --git a/drivers/lguest/page_tables.c b/drivers/lguest/page_tables.c index bfe3650b28d6..fe3c7575647b 100644 --- a/drivers/lguest/page_tables.c +++ b/drivers/lguest/page_tables.c @@ -13,6 +13,7 @@ #include #include #include +#include #include "lg.h" /*M:008 We hold reference to pages, which prevents them from being swapped. @@ -345,7 +346,7 @@ static void flush_user_mappings(struct lguest *lg, int idx) { unsigned int i; /* Release every pgd entry up to the kernel's address. */ - for (i = 0; i < pgd_index(lg->page_offset); i++) + for (i = 0; i < pgd_index(lg->kernel_address); i++) release_pgd(lg, lg->pgdirs[idx].pgdir + i); } @@ -358,6 +359,25 @@ void guest_pagetable_flush_user(struct lguest *lg) } /*:*/ +/* We walk down the guest page tables to get a guest-physical address */ +unsigned long guest_pa(struct lguest *lg, unsigned long vaddr) +{ + pgd_t gpgd; + pte_t gpte; + + /* First step: get the top-level Guest page table entry. */ + gpgd = __pgd(lgread_u32(lg, gpgd_addr(lg, vaddr))); + /* Toplevel not present? We can't map it in. */ + if (!(pgd_flags(gpgd) & _PAGE_PRESENT)) + kill_guest(lg, "Bad address %#lx", vaddr); + + gpte = __pte(lgread_u32(lg, gpte_addr(lg, gpgd, vaddr))); + if (!(pte_flags(gpte) & _PAGE_PRESENT)) + kill_guest(lg, "Bad address %#lx", vaddr); + + return pte_pfn(gpte) * PAGE_SIZE | (vaddr & ~PAGE_MASK); +} + /* We keep several page tables. This is a simple routine to find the page * table (if any) corresponding to this top-level address the Guest has given * us. */ @@ -500,7 +520,7 @@ void guest_set_pte(struct lguest *lg, { /* Kernel mappings must be changed on all top levels. Slow, but * doesn't happen often. */ - if (vaddr >= lg->page_offset) { + if (vaddr >= lg->kernel_address) { unsigned int i; for (i = 0; i < ARRAY_SIZE(lg->pgdirs); i++) if (lg->pgdirs[i].pgdir) @@ -550,11 +570,6 @@ void guest_set_pmd(struct lguest *lg, unsigned long gpgdir, u32 idx) * its first page table is. We set some things up here: */ int init_guest_pagetable(struct lguest *lg, unsigned long pgtable) { - /* In flush_user_mappings() we loop from 0 to - * "pgd_index(lg->page_offset)". This assumes it won't hit - * the Switcher mappings, so check that now. */ - if (pgd_index(lg->page_offset) >= SWITCHER_PGD_INDEX) - return -EINVAL; /* We start on the first shadow page table, and give it a blank PGD * page. */ lg->pgdidx = 0; @@ -565,6 +580,24 @@ int init_guest_pagetable(struct lguest *lg, unsigned long pgtable) return 0; } +/* When the Guest calls LHCALL_LGUEST_INIT we do more setup. */ +void page_table_guest_data_init(struct lguest *lg) +{ + /* We get the kernel address: above this is all kernel memory. */ + if (get_user(lg->kernel_address, &lg->lguest_data->kernel_address) + /* We tell the Guest that it can't use the top 4MB of virtual + * addresses used by the Switcher. */ + || put_user(4U*1024*1024, &lg->lguest_data->reserve_mem) + || put_user(lg->pgdirs[lg->pgdidx].gpgdir,&lg->lguest_data->pgdir)) + kill_guest(lg, "bad guest page %p", lg->lguest_data); + + /* In flush_user_mappings() we loop from 0 to + * "pgd_index(lg->kernel_address)". This assumes it won't hit the + * Switcher mappings, so check that now. */ + if (pgd_index(lg->kernel_address) >= SWITCHER_PGD_INDEX) + kill_guest(lg, "bad kernel address %#lx", lg->kernel_address); +} + /* When a Guest dies, our cleanup is fairly simple. */ void free_guest_pagetable(struct lguest *lg) { diff --git a/drivers/lguest/x86/core.c b/drivers/lguest/x86/core.c index a125109446dc..39f64c95de18 100644 --- a/drivers/lguest/x86/core.c +++ b/drivers/lguest/x86/core.c @@ -216,9 +216,10 @@ static int emulate_insn(struct lguest *lg) * guest_pa just subtracts the Guest's page_offset. */ unsigned long physaddr = guest_pa(lg, lg->regs->eip); - /* The guest_pa() function only works for Guest kernel addresses, but - * that's all we're trying to do anyway. */ - if (lg->regs->eip < lg->page_offset) + /* This must be the Guest kernel trying to do something, not userspace! + * The bottom two bits of the CS segment register are the privilege + * level. */ + if ((lg->regs->cs & 3) != GUEST_PL) return 0; /* Decoding x86 instructions is icky. */ diff --git a/include/asm-x86/lguest_hcall.h b/include/asm-x86/lguest_hcall.h index 8f2a1edc4fe2..0c553ef36240 100644 --- a/include/asm-x86/lguest_hcall.h +++ b/include/asm-x86/lguest_hcall.h @@ -2,8 +2,6 @@ #ifndef _X86_LGUEST_HCALL_H #define _X86_LGUEST_HCALL_H -#include - #define LHCALL_FLUSH_ASYNC 0 #define LHCALL_LGUEST_INIT 1 #define LHCALL_CRASH 2 @@ -36,6 +34,9 @@ * definition of a gentleman: "someone who is only rude intentionally". */ #define LGUEST_TRAP_ENTRY 0x1F +#ifndef __ASSEMBLY__ +#include + static inline unsigned long hcall(unsigned long call, unsigned long arg1, unsigned long arg2, unsigned long arg3) @@ -66,4 +67,6 @@ struct hcall_args /* These map directly onto eax, ebx, ecx, edx in struct lguest_regs */ unsigned long arg0, arg2, arg3, arg1; }; + +#endif /* !__ASSEMBLY__ */ #endif /* _I386_LGUEST_HCALL_H */ diff --git a/include/linux/lguest.h b/include/linux/lguest.h index 083052236db9..8beb29134626 100644 --- a/include/linux/lguest.h +++ b/include/linux/lguest.h @@ -44,11 +44,14 @@ struct lguest_data unsigned long reserve_mem; /* KHz for the TSC clock. */ u32 tsc_khz; + /* Page where the top-level pagetable is */ + unsigned long pgdir; /* Fields initialized by the Guest at boot: */ /* Instruction range to suppress interrupts even if enabled */ unsigned long noirq_start, noirq_end; - + /* Address above which page tables are all identical. */ + unsigned long kernel_address; /* The vector to try to use for system calls (0x40 or 0x80). */ unsigned int syscall_vec; }; -- cgit v1.2.3-71-gd317 From ec3d41c4db4c21164332826ea8d812f94f2f6886 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 11:03:36 +1000 Subject: Virtio interface This attempts to implement a "virtual I/O" layer which should allow common drivers to be efficiently used across most virtual I/O mechanisms. It will no-doubt need further enhancement. The virtio drivers add buffers to virtio queues; as the buffers are consumed the driver "interrupt" callbacks are invoked. There is also a generic implementation of config space which drivers can query to get setup information from the host. Signed-off-by: Rusty Russell Cc: Dor Laor Cc: Arnd Bergmann --- drivers/Kconfig | 2 + drivers/Makefile | 1 + drivers/virtio/Kconfig | 3 + drivers/virtio/Makefile | 1 + drivers/virtio/config.c | 13 +++ drivers/virtio/virtio.c | 171 ++++++++++++++++++++++++++++++++++++++++ include/linux/Kbuild | 1 + include/linux/mod_devicetable.h | 6 ++ include/linux/virtio.h | 110 ++++++++++++++++++++++++++ include/linux/virtio_config.h | 111 ++++++++++++++++++++++++++ 10 files changed, 419 insertions(+) create mode 100644 drivers/virtio/Kconfig create mode 100644 drivers/virtio/Makefile create mode 100644 drivers/virtio/config.c create mode 100644 drivers/virtio/virtio.c create mode 100644 include/linux/virtio.h create mode 100644 include/linux/virtio_config.h (limited to 'include/linux') diff --git a/drivers/Kconfig b/drivers/Kconfig index d945ffc57c25..f4076d9e9902 100644 --- a/drivers/Kconfig +++ b/drivers/Kconfig @@ -93,4 +93,6 @@ source "drivers/auxdisplay/Kconfig" source "drivers/kvm/Kconfig" source "drivers/uio/Kconfig" + +source "drivers/virtio/Kconfig" endmenu diff --git a/drivers/Makefile b/drivers/Makefile index cfe38ffff28a..560496b43306 100644 --- a/drivers/Makefile +++ b/drivers/Makefile @@ -91,3 +91,4 @@ obj-$(CONFIG_HID) += hid/ obj-$(CONFIG_PPC_PS3) += ps3/ obj-$(CONFIG_OF) += of/ obj-$(CONFIG_SSB) += ssb/ +obj-$(CONFIG_VIRTIO) += virtio/ diff --git a/drivers/virtio/Kconfig b/drivers/virtio/Kconfig new file mode 100644 index 000000000000..bce84b56a659 --- /dev/null +++ b/drivers/virtio/Kconfig @@ -0,0 +1,3 @@ +# Virtio always gets selected by whoever wants it. +config VIRTIO + bool diff --git a/drivers/virtio/Makefile b/drivers/virtio/Makefile new file mode 100644 index 000000000000..af0d57dad3eb --- /dev/null +++ b/drivers/virtio/Makefile @@ -0,0 +1 @@ +obj-$(CONFIG_VIRTIO) += virtio.o diff --git a/drivers/virtio/config.c b/drivers/virtio/config.c new file mode 100644 index 000000000000..983d482fba40 --- /dev/null +++ b/drivers/virtio/config.c @@ -0,0 +1,13 @@ +/* Configuration space parsing helpers for virtio. + * + * The configuration is [type][len][... len bytes ...] fields. + * + * Copyright 2007 Rusty Russell, IBM Corporation. + * GPL v2 or later. + */ +#include +#include +#include +#include +#include + diff --git a/drivers/virtio/virtio.c b/drivers/virtio/virtio.c new file mode 100644 index 000000000000..f640e0b732b7 --- /dev/null +++ b/drivers/virtio/virtio.c @@ -0,0 +1,171 @@ +#include +#include +#include + +static ssize_t device_show(struct device *_d, + struct device_attribute *attr, char *buf) +{ + struct virtio_device *dev = container_of(_d,struct virtio_device,dev); + return sprintf(buf, "%hu", dev->id.device); +} +static ssize_t vendor_show(struct device *_d, + struct device_attribute *attr, char *buf) +{ + struct virtio_device *dev = container_of(_d,struct virtio_device,dev); + return sprintf(buf, "%hu", dev->id.vendor); +} +static ssize_t status_show(struct device *_d, + struct device_attribute *attr, char *buf) +{ + struct virtio_device *dev = container_of(_d,struct virtio_device,dev); + return sprintf(buf, "0x%08x", dev->config->get_status(dev)); +} +static struct device_attribute virtio_dev_attrs[] = { + __ATTR_RO(device), + __ATTR_RO(vendor), + __ATTR_RO(status), + __ATTR_NULL +}; + +static inline int virtio_id_match(const struct virtio_device *dev, + const struct virtio_device_id *id) +{ + if (id->device != dev->id.device) + return 0; + + return id->vendor == VIRTIO_DEV_ANY_ID || id->vendor != dev->id.vendor; +} + +/* This looks through all the IDs a driver claims to support. If any of them + * match, we return 1 and the kernel will call virtio_dev_probe(). */ +static int virtio_dev_match(struct device *_dv, struct device_driver *_dr) +{ + unsigned int i; + struct virtio_device *dev = container_of(_dv,struct virtio_device,dev); + const struct virtio_device_id *ids; + + ids = container_of(_dr, struct virtio_driver, driver)->id_table; + for (i = 0; ids[i].device; i++) + if (virtio_id_match(dev, &ids[i])) + return 1; + return 0; +} + +static struct bus_type virtio_bus = { + .name = "virtio", + .match = virtio_dev_match, + .dev_attrs = virtio_dev_attrs, +}; + +static void add_status(struct virtio_device *dev, unsigned status) +{ + dev->config->set_status(dev, dev->config->get_status(dev) | status); +} + +static int virtio_dev_probe(struct device *_d) +{ + int err; + struct virtio_device *dev = container_of(_d,struct virtio_device,dev); + struct virtio_driver *drv = container_of(dev->dev.driver, + struct virtio_driver, driver); + + add_status(dev, VIRTIO_CONFIG_S_DRIVER); + err = drv->probe(dev); + if (err) + add_status(dev, VIRTIO_CONFIG_S_FAILED); + else + add_status(dev, VIRTIO_CONFIG_S_DRIVER_OK); + return err; +} + +int register_virtio_driver(struct virtio_driver *driver) +{ + driver->driver.bus = &virtio_bus; + driver->driver.probe = virtio_dev_probe; + return driver_register(&driver->driver); +} +EXPORT_SYMBOL_GPL(register_virtio_driver); + +void unregister_virtio_driver(struct virtio_driver *driver) +{ + driver_unregister(&driver->driver); +} +EXPORT_SYMBOL_GPL(unregister_virtio_driver); + +int register_virtio_device(struct virtio_device *dev) +{ + int err; + + dev->dev.bus = &virtio_bus; + sprintf(dev->dev.bus_id, "%u", dev->index); + + /* Acknowledge that we've seen the device. */ + add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE); + + /* device_register() causes the bus infrastructure to look for a + * matching driver. */ + err = device_register(&dev->dev); + if (err) + add_status(dev, VIRTIO_CONFIG_S_FAILED); + return err; +} +EXPORT_SYMBOL_GPL(register_virtio_device); + +void unregister_virtio_device(struct virtio_device *dev) +{ + device_unregister(&dev->dev); +} +EXPORT_SYMBOL_GPL(unregister_virtio_device); + +int __virtio_config_val(struct virtio_device *vdev, + u8 type, void *val, size_t size) +{ + void *token; + unsigned int len; + + token = vdev->config->find(vdev, type, &len); + if (!token) + return -ENOENT; + + if (len != size) + return -EIO; + + vdev->config->get(vdev, token, val, size); + return 0; +} +EXPORT_SYMBOL_GPL(__virtio_config_val); + +int virtio_use_bit(struct virtio_device *vdev, + void *token, unsigned int len, unsigned int bitnum) +{ + unsigned long bits[16]; + + /* This makes it convenient to pass-through find() results. */ + if (!token) + return 0; + + /* bit not in range of this bitfield? */ + if (bitnum * 8 >= len / 2) + return 0; + + /* Giant feature bitfields are silly. */ + BUG_ON(len > sizeof(bits)); + vdev->config->get(vdev, token, bits, len); + + if (!test_bit(bitnum, bits)) + return 0; + + /* Set acknowledge bit, and write it back. */ + set_bit(bitnum + len * 8 / 2, bits); + vdev->config->set(vdev, token, bits, len); + return 1; +} +EXPORT_SYMBOL_GPL(virtio_use_bit); + +static int virtio_init(void) +{ + if (bus_register(&virtio_bus) != 0) + panic("virtio bus registration failed"); + return 0; +} +core_initcall(virtio_init); diff --git a/include/linux/Kbuild b/include/linux/Kbuild index 758834538a19..e5208f283a67 100644 --- a/include/linux/Kbuild +++ b/include/linux/Kbuild @@ -343,6 +343,7 @@ unifdef-y += user.h unifdef-y += utsname.h unifdef-y += videodev2.h unifdef-y += videodev.h +unifdef-y += virtio_config.h unifdef-y += wait.h unifdef-y += wanrouter.h unifdef-y += watchdog.h diff --git a/include/linux/mod_devicetable.h b/include/linux/mod_devicetable.h index 522b0dd836cf..e9fddb42f26c 100644 --- a/include/linux/mod_devicetable.h +++ b/include/linux/mod_devicetable.h @@ -361,4 +361,10 @@ struct ssb_device_id { #define SSB_ANY_ID 0xFFFF #define SSB_ANY_REV 0xFF +struct virtio_device_id { + __u32 device; + __u32 vendor; +}; +#define VIRTIO_DEV_ANY_ID 0xffffffff + #endif /* LINUX_MOD_DEVICETABLE_H */ diff --git a/include/linux/virtio.h b/include/linux/virtio.h new file mode 100644 index 000000000000..14e1379876d3 --- /dev/null +++ b/include/linux/virtio.h @@ -0,0 +1,110 @@ +#ifndef _LINUX_VIRTIO_H +#define _LINUX_VIRTIO_H +/* Everything a virtio driver needs to work with any particular virtio + * implementation. */ +#include +#include +#include +#include +#include + +/** + * virtqueue - a queue to register buffers for sending or receiving. + * @callback: the function to call when buffers are consumed (can be NULL). + * If this returns false, callbacks are suppressed until vq_ops->restart + * is called. + * @vdev: the virtio device this queue was created for. + * @vq_ops: the operations for this virtqueue (see below). + * @priv: a pointer for the virtqueue implementation to use. + */ +struct virtqueue +{ + bool (*callback)(struct virtqueue *vq); + struct virtio_device *vdev; + struct virtqueue_ops *vq_ops; + void *priv; +}; + +/** + * virtqueue_ops - operations for virtqueue abstraction layer + * @add_buf: expose buffer to other end + * vq: the struct virtqueue we're talking about. + * sg: the description of the buffer(s). + * out_num: the number of sg readable by other side + * in_num: the number of sg which are writable (after readable ones) + * data: the token identifying the buffer. + * Returns 0 or an error. + * @kick: update after add_buf + * vq: the struct virtqueue + * After one or more add_buf calls, invoke this to kick the other side. + * @get_buf: get the next used buffer + * vq: the struct virtqueue we're talking about. + * len: the length written into the buffer + * Returns NULL or the "data" token handed to add_buf. + * @restart: restart callbacks after callback returned false. + * vq: the struct virtqueue we're talking about. + * This returns "false" (and doesn't re-enable) if there are pending + * buffers in the queue, to avoid a race. + * @shutdown: "unadd" all buffers. + * vq: the struct virtqueue we're talking about. + * Remove everything from the queue. + * + * Locking rules are straightforward: the driver is responsible for + * locking. No two operations may be invoked simultaneously. + * + * All operations can be called in any context. + */ +struct virtqueue_ops { + int (*add_buf)(struct virtqueue *vq, + struct scatterlist sg[], + unsigned int out_num, + unsigned int in_num, + void *data); + + void (*kick)(struct virtqueue *vq); + + void *(*get_buf)(struct virtqueue *vq, unsigned int *len); + + bool (*restart)(struct virtqueue *vq); + + void (*shutdown)(struct virtqueue *vq); +}; + +/** + * virtio_device - representation of a device using virtio + * @index: unique position on the virtio bus + * @dev: underlying device. + * @id: the device type identification (used to match it with a driver). + * @config: the configuration ops for this device. + * @priv: private pointer for the driver's use. + */ +struct virtio_device +{ + int index; + struct device dev; + struct virtio_device_id id; + struct virtio_config_ops *config; + void *priv; +}; + +int register_virtio_device(struct virtio_device *dev); +void unregister_virtio_device(struct virtio_device *dev); + +/** + * virtio_driver - operations for a virtio I/O driver + * @driver: underlying device driver (populate name and owner). + * @id_table: the ids serviced by this driver. + * @probe: the function to call when a device is found. Returns a token for + * remove, or PTR_ERR(). + * @remove: the function when a device is removed. + */ +struct virtio_driver { + struct device_driver driver; + const struct virtio_device_id *id_table; + int (*probe)(struct virtio_device *dev); + void (*remove)(struct virtio_device *dev); +}; + +int register_virtio_driver(struct virtio_driver *drv); +void unregister_virtio_driver(struct virtio_driver *drv); +#endif /* _LINUX_VIRTIO_H */ diff --git a/include/linux/virtio_config.h b/include/linux/virtio_config.h new file mode 100644 index 000000000000..bcc01888df78 --- /dev/null +++ b/include/linux/virtio_config.h @@ -0,0 +1,111 @@ +#ifndef _LINUX_VIRTIO_CONFIG_H +#define _LINUX_VIRTIO_CONFIG_H +/* Virtio devices use a standardized configuration space to define their + * features and pass configuration information, but each implementation can + * store and access that space differently. */ +#include + +/* Status byte for guest to report progress, and synchronize config. */ +/* We have seen device and processed generic fields (VIRTIO_CONFIG_F_VIRTIO) */ +#define VIRTIO_CONFIG_S_ACKNOWLEDGE 1 +/* We have found a driver for the device. */ +#define VIRTIO_CONFIG_S_DRIVER 2 +/* Driver has used its parts of the config, and is happy */ +#define VIRTIO_CONFIG_S_DRIVER_OK 4 +/* We've given up on this device. */ +#define VIRTIO_CONFIG_S_FAILED 0x80 + +/* Feature byte (actually 7 bits availabe): */ +/* Requirements/features of the virtio implementation. */ +#define VIRTIO_CONFIG_F_VIRTIO 1 +/* Requirements/features of the virtqueue (may have more than one). */ +#define VIRTIO_CONFIG_F_VIRTQUEUE 2 + +#ifdef __KERNEL__ +struct virtio_device; + +/** + * virtio_config_ops - operations for configuring a virtio device + * @find: search for the next configuration field of the given type. + * vdev: the virtio_device + * type: the feature type + * len: the (returned) length of the field if found. + * Returns a token if found, or NULL. Never returnes the same field twice + * (ie. it's used up). + * @get: read the value of a configuration field after find(). + * vdev: the virtio_device + * token: the token returned from find(). + * buf: the buffer to write the field value into. + * len: the length of the buffer (given by find()). + * Note that contents are conventionally little-endian. + * @set: write the value of a configuration field after find(). + * vdev: the virtio_device + * token: the token returned from find(). + * buf: the buffer to read the field value from. + * len: the length of the buffer (given by find()). + * Note that contents are conventionally little-endian. + * @get_status: read the status byte + * vdev: the virtio_device + * Returns the status byte + * @set_status: write the status byte + * vdev: the virtio_device + * status: the new status byte + * @find_vq: find the first VIRTIO_CONFIG_F_VIRTQUEUE and create a virtqueue. + * vdev: the virtio_device + * callback: the virqtueue callback + * Returns the new virtqueue or ERR_PTR(). + * @del_vq: free a virtqueue found by find_vq(). + */ +struct virtio_config_ops +{ + void *(*find)(struct virtio_device *vdev, u8 type, unsigned *len); + void (*get)(struct virtio_device *vdev, void *token, + void *buf, unsigned len); + void (*set)(struct virtio_device *vdev, void *token, + const void *buf, unsigned len); + u8 (*get_status)(struct virtio_device *vdev); + void (*set_status)(struct virtio_device *vdev, u8 status); + struct virtqueue *(*find_vq)(struct virtio_device *vdev, + bool (*callback)(struct virtqueue *)); + void (*del_vq)(struct virtqueue *vq); +}; + +/** + * virtio_config_val - get a single virtio config and mark it used. + * @config: the virtio config space + * @type: the type to search for. + * @val: a pointer to the value to fill in. + * + * Once used, the config type is marked with VIRTIO_CONFIG_F_USED so it can't + * be found again. This version does endian conversion. */ +#define virtio_config_val(vdev, type, v) ({ \ + int _err = __virtio_config_val((vdev),(type),(v),sizeof(*(v))); \ + \ + BUILD_BUG_ON(sizeof(*(v)) != 1 && sizeof(*(v)) != 2 \ + && sizeof(*(v)) != 4 && sizeof(*(v)) != 8); \ + if (!_err) { \ + switch (sizeof(*(v))) { \ + case 2: le16_to_cpus((__u16 *) v); break; \ + case 4: le32_to_cpus((__u32 *) v); break; \ + case 8: le64_to_cpus((__u64 *) v); break; \ + } \ + } \ + _err; \ +}) + +int __virtio_config_val(struct virtio_device *dev, + u8 type, void *val, size_t size); + +/** + * virtio_use_bit - helper to use a feature bit in a bitfield value. + * @dev: the virtio device + * @token: the token as returned from vdev->config->find(). + * @len: the length of the field. + * @bitnum: the bit to test. + * + * If handed a NULL token, it returns false, otherwise returns bit status. + * If it's one, it sets the mirroring acknowledgement bit. */ +int virtio_use_bit(struct virtio_device *vdev, + void *token, unsigned int len, unsigned int bitnum); +#endif /* __KERNEL__ */ +#endif /* _LINUX_VIRTIO_CONFIG_H */ -- cgit v1.2.3-71-gd317 From 296f96fcfc160e29c01819c0c7b20c2dc8320edd Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 11:03:37 +1000 Subject: Net driver using virtio The network driver uses two virtqueues: one for input packets and one for output packets. This has nice locking properties (ie. we don't do any for recv vs send). TODO: 1) Big packets. 2) Multi-client devices (maybe separate driver?). 3) Resolve freeing of old xmit skbs (Christian Borntraeger) Signed-off-by: Rusty Russell Cc: Christian Borntraeger Cc: Herbert Xu Cc: netdev@vger.kernel.org --- drivers/net/Kconfig | 6 + drivers/net/Makefile | 1 + drivers/net/virtio_net.c | 435 +++++++++++++++++++++++++++++++++++++++++++++ include/linux/Kbuild | 1 + include/linux/virtio_net.h | 36 ++++ 5 files changed, 479 insertions(+) create mode 100644 drivers/net/virtio_net.c create mode 100644 include/linux/virtio_net.h (limited to 'include/linux') diff --git a/drivers/net/Kconfig b/drivers/net/Kconfig index ce34b539bf38..2538816817aa 100644 --- a/drivers/net/Kconfig +++ b/drivers/net/Kconfig @@ -3100,4 +3100,10 @@ config NETPOLL_TRAP config NET_POLL_CONTROLLER def_bool NETPOLL +config VIRTIO_NET + tristate "Virtio network driver (EXPERIMENTAL)" + depends on EXPERIMENTAL && VIRTIO + ---help--- + This is the virtual network driver for lguest. Say Y or M. + endif # NETDEVICES diff --git a/drivers/net/Makefile b/drivers/net/Makefile index 22f78cbd126b..6745feb690ff 100644 --- a/drivers/net/Makefile +++ b/drivers/net/Makefile @@ -243,3 +243,4 @@ obj-$(CONFIG_FS_ENET) += fs_enet/ obj-$(CONFIG_NETXEN_NIC) += netxen/ obj-$(CONFIG_NIU) += niu.o +obj-$(CONFIG_VIRTIO_NET) += virtio_net.o diff --git a/drivers/net/virtio_net.c b/drivers/net/virtio_net.c new file mode 100644 index 000000000000..e396c9d2af8d --- /dev/null +++ b/drivers/net/virtio_net.c @@ -0,0 +1,435 @@ +/* A simple network driver using virtio. + * + * Copyright 2007 Rusty Russell IBM Corporation + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +//#define DEBUG +#include +#include +#include +#include +#include +#include + +/* FIXME: MTU in config. */ +#define MAX_PACKET_LEN (ETH_HLEN+ETH_DATA_LEN) + +struct virtnet_info +{ + struct virtio_device *vdev; + struct virtqueue *rvq, *svq; + struct net_device *dev; + struct napi_struct napi; + + /* Number of input buffers, and max we've ever had. */ + unsigned int num, max; + + /* Receive & send queues. */ + struct sk_buff_head recv; + struct sk_buff_head send; +}; + +static inline struct virtio_net_hdr *skb_vnet_hdr(struct sk_buff *skb) +{ + return (struct virtio_net_hdr *)skb->cb; +} + +static inline void vnet_hdr_to_sg(struct scatterlist *sg, struct sk_buff *skb) +{ + sg_init_one(sg, skb_vnet_hdr(skb), sizeof(struct virtio_net_hdr)); +} + +static bool skb_xmit_done(struct virtqueue *rvq) +{ + struct virtnet_info *vi = rvq->vdev->priv; + + /* In case we were waiting for output buffers. */ + netif_wake_queue(vi->dev); + return true; +} + +static void receive_skb(struct net_device *dev, struct sk_buff *skb, + unsigned len) +{ + struct virtio_net_hdr *hdr = skb_vnet_hdr(skb); + + if (unlikely(len < sizeof(struct virtio_net_hdr) + ETH_HLEN)) { + pr_debug("%s: short packet %i\n", dev->name, len); + dev->stats.rx_length_errors++; + goto drop; + } + len -= sizeof(struct virtio_net_hdr); + BUG_ON(len > MAX_PACKET_LEN); + + skb_trim(skb, len); + skb->protocol = eth_type_trans(skb, dev); + pr_debug("Receiving skb proto 0x%04x len %i type %i\n", + ntohs(skb->protocol), skb->len, skb->pkt_type); + dev->stats.rx_bytes += skb->len; + dev->stats.rx_packets++; + + if (hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) { + pr_debug("Needs csum!\n"); + skb->ip_summed = CHECKSUM_PARTIAL; + skb->csum_start = hdr->csum_start; + skb->csum_offset = hdr->csum_offset; + if (skb->csum_start > skb->len - 2 + || skb->csum_offset > skb->len - 2) { + if (net_ratelimit()) + printk(KERN_WARNING "%s: csum=%u/%u len=%u\n", + dev->name, skb->csum_start, + skb->csum_offset, skb->len); + goto frame_err; + } + } + + if (hdr->gso_type != VIRTIO_NET_HDR_GSO_NONE) { + pr_debug("GSO!\n"); + switch (hdr->gso_type) { + case VIRTIO_NET_HDR_GSO_TCPV4: + skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4; + break; + case VIRTIO_NET_HDR_GSO_TCPV4_ECN: + skb_shinfo(skb)->gso_type = SKB_GSO_TCP_ECN; + break; + case VIRTIO_NET_HDR_GSO_UDP: + skb_shinfo(skb)->gso_type = SKB_GSO_UDP; + break; + case VIRTIO_NET_HDR_GSO_TCPV6: + skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6; + break; + default: + if (net_ratelimit()) + printk(KERN_WARNING "%s: bad gso type %u.\n", + dev->name, hdr->gso_type); + goto frame_err; + } + + skb_shinfo(skb)->gso_size = hdr->gso_size; + if (skb_shinfo(skb)->gso_size == 0) { + if (net_ratelimit()) + printk(KERN_WARNING "%s: zero gso size.\n", + dev->name); + goto frame_err; + } + + /* Header must be checked, and gso_segs computed. */ + skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY; + skb_shinfo(skb)->gso_segs = 0; + } + + netif_receive_skb(skb); + return; + +frame_err: + dev->stats.rx_frame_errors++; +drop: + dev_kfree_skb(skb); +} + +static void try_fill_recv(struct virtnet_info *vi) +{ + struct sk_buff *skb; + struct scatterlist sg[1+MAX_SKB_FRAGS]; + int num, err; + + for (;;) { + skb = netdev_alloc_skb(vi->dev, MAX_PACKET_LEN); + if (unlikely(!skb)) + break; + + skb_put(skb, MAX_PACKET_LEN); + vnet_hdr_to_sg(sg, skb); + num = skb_to_sgvec(skb, sg+1, 0, skb->len) + 1; + skb_queue_head(&vi->recv, skb); + + err = vi->rvq->vq_ops->add_buf(vi->rvq, sg, 0, num, skb); + if (err) { + skb_unlink(skb, &vi->recv); + kfree_skb(skb); + break; + } + vi->num++; + } + if (unlikely(vi->num > vi->max)) + vi->max = vi->num; + vi->rvq->vq_ops->kick(vi->rvq); +} + +static bool skb_recv_done(struct virtqueue *rvq) +{ + struct virtnet_info *vi = rvq->vdev->priv; + netif_rx_schedule(vi->dev, &vi->napi); + /* Suppress further interrupts. */ + return false; +} + +static int virtnet_poll(struct napi_struct *napi, int budget) +{ + struct virtnet_info *vi = container_of(napi, struct virtnet_info, napi); + struct sk_buff *skb = NULL; + unsigned int len, received = 0; + +again: + while (received < budget && + (skb = vi->rvq->vq_ops->get_buf(vi->rvq, &len)) != NULL) { + __skb_unlink(skb, &vi->recv); + receive_skb(vi->dev, skb, len); + vi->num--; + received++; + } + + /* FIXME: If we oom and completely run out of inbufs, we need + * to start a timer trying to fill more. */ + if (vi->num < vi->max / 2) + try_fill_recv(vi); + + /* All done? */ + if (!skb) { + netif_rx_complete(vi->dev, napi); + if (unlikely(!vi->rvq->vq_ops->restart(vi->rvq)) + && netif_rx_reschedule(vi->dev, napi)) + goto again; + } + + return received; +} + +static void free_old_xmit_skbs(struct virtnet_info *vi) +{ + struct sk_buff *skb; + unsigned int len; + + while ((skb = vi->svq->vq_ops->get_buf(vi->svq, &len)) != NULL) { + pr_debug("Sent skb %p\n", skb); + __skb_unlink(skb, &vi->send); + vi->dev->stats.tx_bytes += len; + vi->dev->stats.tx_packets++; + kfree_skb(skb); + } +} + +static int start_xmit(struct sk_buff *skb, struct net_device *dev) +{ + struct virtnet_info *vi = netdev_priv(dev); + int num, err; + struct scatterlist sg[1+MAX_SKB_FRAGS]; + struct virtio_net_hdr *hdr; + const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest; + DECLARE_MAC_BUF(mac); + + pr_debug("%s: xmit %p %s\n", dev->name, skb, print_mac(mac, dest)); + + free_old_xmit_skbs(vi); + + /* Encode metadata header at front. */ + hdr = skb_vnet_hdr(skb); + if (skb->ip_summed == CHECKSUM_PARTIAL) { + hdr->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; + hdr->csum_start = skb->csum_start - skb_headroom(skb); + hdr->csum_offset = skb->csum_offset; + } else { + hdr->flags = 0; + hdr->csum_offset = hdr->csum_start = 0; + } + + if (skb_is_gso(skb)) { + hdr->gso_size = skb_shinfo(skb)->gso_size; + if (skb_shinfo(skb)->gso_type & SKB_GSO_TCP_ECN) + hdr->gso_type = VIRTIO_NET_HDR_GSO_TCPV4_ECN; + else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) + hdr->gso_type = VIRTIO_NET_HDR_GSO_TCPV4; + else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) + hdr->gso_type = VIRTIO_NET_HDR_GSO_TCPV6; + else if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP) + hdr->gso_type = VIRTIO_NET_HDR_GSO_UDP; + else + BUG(); + } else { + hdr->gso_type = VIRTIO_NET_HDR_GSO_NONE; + hdr->gso_size = 0; + } + + vnet_hdr_to_sg(sg, skb); + num = skb_to_sgvec(skb, sg+1, 0, skb->len) + 1; + __skb_queue_head(&vi->send, skb); + err = vi->svq->vq_ops->add_buf(vi->svq, sg, num, 0, skb); + if (err) { + pr_debug("%s: virtio not prepared to send\n", dev->name); + skb_unlink(skb, &vi->send); + netif_stop_queue(dev); + return NETDEV_TX_BUSY; + } + vi->svq->vq_ops->kick(vi->svq); + + return 0; +} + +static int virtnet_open(struct net_device *dev) +{ + struct virtnet_info *vi = netdev_priv(dev); + + try_fill_recv(vi); + + /* If we didn't even get one input buffer, we're useless. */ + if (vi->num == 0) + return -ENOMEM; + + napi_enable(&vi->napi); + return 0; +} + +static int virtnet_close(struct net_device *dev) +{ + struct virtnet_info *vi = netdev_priv(dev); + struct sk_buff *skb; + + napi_disable(&vi->napi); + + /* networking core has neutered skb_xmit_done/skb_recv_done, so don't + * worry about races vs. get(). */ + vi->rvq->vq_ops->shutdown(vi->rvq); + while ((skb = __skb_dequeue(&vi->recv)) != NULL) { + kfree_skb(skb); + vi->num--; + } + vi->svq->vq_ops->shutdown(vi->svq); + while ((skb = __skb_dequeue(&vi->send)) != NULL) + kfree_skb(skb); + + BUG_ON(vi->num != 0); + return 0; +} + +static int virtnet_probe(struct virtio_device *vdev) +{ + int err; + unsigned int len; + struct net_device *dev; + struct virtnet_info *vi; + void *token; + + /* Allocate ourselves a network device with room for our info */ + dev = alloc_etherdev(sizeof(struct virtnet_info)); + if (!dev) + return -ENOMEM; + + /* Set up network device as normal. */ + ether_setup(dev); + dev->open = virtnet_open; + dev->stop = virtnet_close; + dev->hard_start_xmit = start_xmit; + dev->features = NETIF_F_HIGHDMA; + SET_NETDEV_DEV(dev, &vdev->dev); + + /* Do we support "hardware" checksums? */ + token = vdev->config->find(vdev, VIRTIO_CONFIG_NET_F, &len); + if (virtio_use_bit(vdev, token, len, VIRTIO_NET_F_NO_CSUM)) { + /* This opens up the world of extra features. */ + dev->features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST; + if (virtio_use_bit(vdev, token, len, VIRTIO_NET_F_TSO4)) + dev->features |= NETIF_F_TSO; + if (virtio_use_bit(vdev, token, len, VIRTIO_NET_F_UFO)) + dev->features |= NETIF_F_UFO; + if (virtio_use_bit(vdev, token, len, VIRTIO_NET_F_TSO4_ECN)) + dev->features |= NETIF_F_TSO_ECN; + if (virtio_use_bit(vdev, token, len, VIRTIO_NET_F_TSO6)) + dev->features |= NETIF_F_TSO6; + } + + /* Configuration may specify what MAC to use. Otherwise random. */ + token = vdev->config->find(vdev, VIRTIO_CONFIG_NET_MAC_F, &len); + if (token) { + dev->addr_len = len; + vdev->config->get(vdev, token, dev->dev_addr, len); + } else + random_ether_addr(dev->dev_addr); + + /* Set up our device-specific information */ + vi = netdev_priv(dev); + netif_napi_add(dev, &vi->napi, virtnet_poll, 16); + vi->dev = dev; + vi->vdev = vdev; + + /* We expect two virtqueues, receive then send. */ + vi->rvq = vdev->config->find_vq(vdev, skb_recv_done); + if (IS_ERR(vi->rvq)) { + err = PTR_ERR(vi->rvq); + goto free; + } + + vi->svq = vdev->config->find_vq(vdev, skb_xmit_done); + if (IS_ERR(vi->svq)) { + err = PTR_ERR(vi->svq); + goto free_recv; + } + + /* Initialize our empty receive and send queues. */ + skb_queue_head_init(&vi->recv); + skb_queue_head_init(&vi->send); + + err = register_netdev(dev); + if (err) { + pr_debug("virtio_net: registering device failed\n"); + goto free_send; + } + pr_debug("virtnet: registered device %s\n", dev->name); + vdev->priv = vi; + return 0; + +free_send: + vdev->config->del_vq(vi->svq); +free_recv: + vdev->config->del_vq(vi->rvq); +free: + free_netdev(dev); + return err; +} + +static void virtnet_remove(struct virtio_device *vdev) +{ + unregister_netdev(vdev->priv); + free_netdev(vdev->priv); +} + +static struct virtio_device_id id_table[] = { + { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID }, + { 0 }, +}; + +static struct virtio_driver virtio_net = { + .driver.name = KBUILD_MODNAME, + .driver.owner = THIS_MODULE, + .id_table = id_table, + .probe = virtnet_probe, + .remove = __devexit_p(virtnet_remove), +}; + +static int __init init(void) +{ + return register_virtio_driver(&virtio_net); +} + +static void __exit fini(void) +{ + unregister_virtio_driver(&virtio_net); +} +module_init(init); +module_exit(fini); + +MODULE_DEVICE_TABLE(virtio, id_table); +MODULE_DESCRIPTION("Virtio network driver"); +MODULE_LICENSE("GPL"); diff --git a/include/linux/Kbuild b/include/linux/Kbuild index e5208f283a67..b101588a4b5a 100644 --- a/include/linux/Kbuild +++ b/include/linux/Kbuild @@ -344,6 +344,7 @@ unifdef-y += utsname.h unifdef-y += videodev2.h unifdef-y += videodev.h unifdef-y += virtio_config.h +unifdef-y += virtio_net.h unifdef-y += wait.h unifdef-y += wanrouter.h unifdef-y += watchdog.h diff --git a/include/linux/virtio_net.h b/include/linux/virtio_net.h new file mode 100644 index 000000000000..ae469ae55d36 --- /dev/null +++ b/include/linux/virtio_net.h @@ -0,0 +1,36 @@ +#ifndef _LINUX_VIRTIO_NET_H +#define _LINUX_VIRTIO_NET_H +#include + +/* The ID for virtio_net */ +#define VIRTIO_ID_NET 1 + +/* The bitmap of config for virtio net */ +#define VIRTIO_CONFIG_NET_F 0x40 +#define VIRTIO_NET_F_NO_CSUM 0 +#define VIRTIO_NET_F_TSO4 1 +#define VIRTIO_NET_F_UFO 2 +#define VIRTIO_NET_F_TSO4_ECN 3 +#define VIRTIO_NET_F_TSO6 4 + +/* The config defining mac address. */ +#define VIRTIO_CONFIG_NET_MAC_F 0x41 + +/* This is the first element of the scatter-gather list. If you don't + * specify GSO or CSUM features, you can simply ignore the header. */ +struct virtio_net_hdr +{ +#define VIRTIO_NET_HDR_F_NEEDS_CSUM 1 // Use csum_start, csum_offset + __u8 flags; +#define VIRTIO_NET_HDR_GSO_NONE 0 // Not a GSO frame +#define VIRTIO_NET_HDR_GSO_TCPV4 1 // GSO frame, IPv4 TCP (TSO) +/* FIXME: Do we need this? If they said they can handle ECN, do they care? */ +#define VIRTIO_NET_HDR_GSO_TCPV4_ECN 2 // GSO frame, IPv4 TCP w/ ECN +#define VIRTIO_NET_HDR_GSO_UDP 3 // GSO frame, IPv4 UDP (UFO) +#define VIRTIO_NET_HDR_GSO_TCPV6 4 // GSO frame, IPv6 TCP + __u8 gso_type; + __u16 gso_size; + __u16 csum_start; + __u16 csum_offset; +}; +#endif /* _LINUX_VIRTIO_NET_H */ -- cgit v1.2.3-71-gd317 From e467cde238184d1b0923db2cd61ae1c5a6dc15aa Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 11:03:38 +1000 Subject: Block driver using virtio. The block driver uses scatter-gather lists with sg[0] being the request information (struct virtio_blk_outhdr) with the type, sector and inbuf id. The next N sg entries are the bio itself, then the last sg is the status byte. Whether the N entries are in or out depends on whether it's a read or a write. We accept the normal (SCSI) ioctls: they get handed through to the other side which can then handle it or reply that it's unsupported. It's not clear that this actually works in general, since I don't know if blk_pc_request() requests have an accurate rq_data_dir(). Although we try to reply -ENOTTY on unsupported commands, ioctl(fd, CDROMEJECT) returns success to userspace. This needs a separate patch. Signed-off-by: Rusty Russell Cc: Jens Axboe --- drivers/block/Kconfig | 6 + drivers/block/Makefile | 1 + drivers/block/virtio_blk.c | 308 +++++++++++++++++++++++++++++++++++++++++++++ include/linux/Kbuild | 1 + include/linux/virtio_blk.h | 51 ++++++++ 5 files changed, 367 insertions(+) create mode 100644 drivers/block/virtio_blk.c create mode 100644 include/linux/virtio_blk.h (limited to 'include/linux') diff --git a/drivers/block/Kconfig b/drivers/block/Kconfig index ce4b1e484e64..4d0119ea9e35 100644 --- a/drivers/block/Kconfig +++ b/drivers/block/Kconfig @@ -425,4 +425,10 @@ config XEN_BLKDEV_FRONTEND block device driver. It communicates with a back-end driver in another domain which drives the actual block device. +config VIRTIO_BLK + tristate "Virtio block driver (EXPERIMENTAL)" + depends on EXPERIMENTAL && VIRTIO + ---help--- + This is the virtual block driver for lguest. Say Y or M. + endif # BLK_DEV diff --git a/drivers/block/Makefile b/drivers/block/Makefile index 014e72121b5a..d199eba7a080 100644 --- a/drivers/block/Makefile +++ b/drivers/block/Makefile @@ -25,6 +25,7 @@ obj-$(CONFIG_SUNVDC) += sunvdc.o obj-$(CONFIG_BLK_DEV_UMEM) += umem.o obj-$(CONFIG_BLK_DEV_NBD) += nbd.o obj-$(CONFIG_BLK_DEV_CRYPTOLOOP) += cryptoloop.o +obj-$(CONFIG_VIRTIO_BLK) += virtio_blk.o obj-$(CONFIG_VIODASD) += viodasd.o obj-$(CONFIG_BLK_DEV_SX8) += sx8.o diff --git a/drivers/block/virtio_blk.c b/drivers/block/virtio_blk.c new file mode 100644 index 000000000000..a901eee64ba5 --- /dev/null +++ b/drivers/block/virtio_blk.c @@ -0,0 +1,308 @@ +//#define DEBUG +#include +#include +#include +#include +#include +#include + +static unsigned char virtblk_index = 'a'; +struct virtio_blk +{ + spinlock_t lock; + + struct virtio_device *vdev; + struct virtqueue *vq; + + /* The disk structure for the kernel. */ + struct gendisk *disk; + + /* Request tracking. */ + struct list_head reqs; + + mempool_t *pool; + + /* Scatterlist: can be too big for stack. */ + struct scatterlist sg[3+MAX_PHYS_SEGMENTS]; +}; + +struct virtblk_req +{ + struct list_head list; + struct request *req; + struct virtio_blk_outhdr out_hdr; + struct virtio_blk_inhdr in_hdr; +}; + +static bool blk_done(struct virtqueue *vq) +{ + struct virtio_blk *vblk = vq->vdev->priv; + struct virtblk_req *vbr; + unsigned int len; + unsigned long flags; + + spin_lock_irqsave(&vblk->lock, flags); + while ((vbr = vblk->vq->vq_ops->get_buf(vblk->vq, &len)) != NULL) { + int uptodate; + switch (vbr->in_hdr.status) { + case VIRTIO_BLK_S_OK: + uptodate = 1; + break; + case VIRTIO_BLK_S_UNSUPP: + uptodate = -ENOTTY; + break; + default: + uptodate = 0; + break; + } + + end_dequeued_request(vbr->req, uptodate); + list_del(&vbr->list); + mempool_free(vbr, vblk->pool); + } + /* In case queue is stopped waiting for more buffers. */ + blk_start_queue(vblk->disk->queue); + spin_unlock_irqrestore(&vblk->lock, flags); + return true; +} + +static bool do_req(struct request_queue *q, struct virtio_blk *vblk, + struct request *req) +{ + unsigned long num, out, in; + struct virtblk_req *vbr; + + vbr = mempool_alloc(vblk->pool, GFP_ATOMIC); + if (!vbr) + /* When another request finishes we'll try again. */ + return false; + + vbr->req = req; + if (blk_fs_request(vbr->req)) { + vbr->out_hdr.type = 0; + vbr->out_hdr.sector = vbr->req->sector; + vbr->out_hdr.ioprio = vbr->req->ioprio; + } else if (blk_pc_request(vbr->req)) { + vbr->out_hdr.type = VIRTIO_BLK_T_SCSI_CMD; + vbr->out_hdr.sector = 0; + vbr->out_hdr.ioprio = vbr->req->ioprio; + } else { + /* We don't put anything else in the queue. */ + BUG(); + } + + if (blk_barrier_rq(vbr->req)) + vbr->out_hdr.type |= VIRTIO_BLK_T_BARRIER; + + /* We have to zero this, otherwise blk_rq_map_sg gets upset. */ + memset(vblk->sg, 0, sizeof(vblk->sg)); + sg_set_buf(&vblk->sg[0], &vbr->out_hdr, sizeof(vbr->out_hdr)); + num = blk_rq_map_sg(q, vbr->req, vblk->sg+1); + sg_set_buf(&vblk->sg[num+1], &vbr->in_hdr, sizeof(vbr->in_hdr)); + + if (rq_data_dir(vbr->req) == WRITE) { + vbr->out_hdr.type |= VIRTIO_BLK_T_OUT; + out = 1 + num; + in = 1; + } else { + vbr->out_hdr.type |= VIRTIO_BLK_T_IN; + out = 1; + in = 1 + num; + } + + if (vblk->vq->vq_ops->add_buf(vblk->vq, vblk->sg, out, in, vbr)) { + mempool_free(vbr, vblk->pool); + return false; + } + + list_add_tail(&vbr->list, &vblk->reqs); + return true; +} + +static void do_virtblk_request(struct request_queue *q) +{ + struct virtio_blk *vblk = NULL; + struct request *req; + unsigned int issued = 0; + + while ((req = elv_next_request(q)) != NULL) { + vblk = req->rq_disk->private_data; + BUG_ON(req->nr_phys_segments > ARRAY_SIZE(vblk->sg)); + + /* If this request fails, stop queue and wait for something to + finish to restart it. */ + if (!do_req(q, vblk, req)) { + blk_stop_queue(q); + break; + } + blkdev_dequeue_request(req); + issued++; + } + + if (issued) + vblk->vq->vq_ops->kick(vblk->vq); +} + +static int virtblk_ioctl(struct inode *inode, struct file *filp, + unsigned cmd, unsigned long data) +{ + return scsi_cmd_ioctl(filp, inode->i_bdev->bd_disk->queue, + inode->i_bdev->bd_disk, cmd, + (void __user *)data); +} + +static struct block_device_operations virtblk_fops = { + .ioctl = virtblk_ioctl, + .owner = THIS_MODULE, +}; + +static int virtblk_probe(struct virtio_device *vdev) +{ + struct virtio_blk *vblk; + int err, major; + void *token; + unsigned int len; + u64 cap; + u32 v; + + vdev->priv = vblk = kmalloc(sizeof(*vblk), GFP_KERNEL); + if (!vblk) { + err = -ENOMEM; + goto out; + } + + INIT_LIST_HEAD(&vblk->reqs); + spin_lock_init(&vblk->lock); + vblk->vdev = vdev; + + /* We expect one virtqueue, for output. */ + vblk->vq = vdev->config->find_vq(vdev, blk_done); + if (IS_ERR(vblk->vq)) { + err = PTR_ERR(vblk->vq); + goto out_free_vblk; + } + + vblk->pool = mempool_create_kmalloc_pool(1,sizeof(struct virtblk_req)); + if (!vblk->pool) { + err = -ENOMEM; + goto out_free_vq; + } + + major = register_blkdev(0, "virtblk"); + if (major < 0) { + err = major; + goto out_mempool; + } + + /* FIXME: How many partitions? How long is a piece of string? */ + vblk->disk = alloc_disk(1 << 4); + if (!vblk->disk) { + err = -ENOMEM; + goto out_unregister_blkdev; + } + + vblk->disk->queue = blk_init_queue(do_virtblk_request, &vblk->lock); + if (!vblk->disk->queue) { + err = -ENOMEM; + goto out_put_disk; + } + + sprintf(vblk->disk->disk_name, "vd%c", virtblk_index++); + vblk->disk->major = major; + vblk->disk->first_minor = 0; + vblk->disk->private_data = vblk; + vblk->disk->fops = &virtblk_fops; + + /* If barriers are supported, tell block layer that queue is ordered */ + token = vdev->config->find(vdev, VIRTIO_CONFIG_BLK_F, &len); + if (virtio_use_bit(vdev, token, len, VIRTIO_BLK_F_BARRIER)) + blk_queue_ordered(vblk->disk->queue, QUEUE_ORDERED_TAG, NULL); + + err = virtio_config_val(vdev, VIRTIO_CONFIG_BLK_F_CAPACITY, &cap); + if (err) { + dev_err(&vdev->dev, "Bad/missing capacity in config\n"); + goto out_put_disk; + } + + /* If capacity is too big, truncate with warning. */ + if ((sector_t)cap != cap) { + dev_warn(&vdev->dev, "Capacity %llu too large: truncating\n", + (unsigned long long)cap); + cap = (sector_t)-1; + } + set_capacity(vblk->disk, cap); + + err = virtio_config_val(vdev, VIRTIO_CONFIG_BLK_F_SIZE_MAX, &v); + if (!err) + blk_queue_max_segment_size(vblk->disk->queue, v); + else if (err != -ENOENT) { + dev_err(&vdev->dev, "Bad SIZE_MAX in config\n"); + goto out_put_disk; + } + + err = virtio_config_val(vdev, VIRTIO_CONFIG_BLK_F_SEG_MAX, &v); + if (!err) + blk_queue_max_hw_segments(vblk->disk->queue, v); + else if (err != -ENOENT) { + dev_err(&vdev->dev, "Bad SEG_MAX in config\n"); + goto out_put_disk; + } + + add_disk(vblk->disk); + return 0; + +out_put_disk: + put_disk(vblk->disk); +out_unregister_blkdev: + unregister_blkdev(major, "virtblk"); +out_mempool: + mempool_destroy(vblk->pool); +out_free_vq: + vdev->config->del_vq(vblk->vq); +out_free_vblk: + kfree(vblk); +out: + return err; +} + +static void virtblk_remove(struct virtio_device *vdev) +{ + struct virtio_blk *vblk = vdev->priv; + int major = vblk->disk->major; + + BUG_ON(!list_empty(&vblk->reqs)); + blk_cleanup_queue(vblk->disk->queue); + put_disk(vblk->disk); + unregister_blkdev(major, "virtblk"); + mempool_destroy(vblk->pool); + kfree(vblk); +} + +static struct virtio_device_id id_table[] = { + { VIRTIO_ID_BLOCK, VIRTIO_DEV_ANY_ID }, + { 0 }, +}; + +static struct virtio_driver virtio_blk = { + .driver.name = KBUILD_MODNAME, + .driver.owner = THIS_MODULE, + .id_table = id_table, + .probe = virtblk_probe, + .remove = __devexit_p(virtblk_remove), +}; + +static int __init init(void) +{ + return register_virtio_driver(&virtio_blk); +} + +static void __exit fini(void) +{ + unregister_virtio_driver(&virtio_blk); +} +module_init(init); +module_exit(fini); + +MODULE_DEVICE_TABLE(virtio, id_table); +MODULE_DESCRIPTION("Virtio block driver"); +MODULE_LICENSE("GPL"); diff --git a/include/linux/Kbuild b/include/linux/Kbuild index b101588a4b5a..6a65231bc785 100644 --- a/include/linux/Kbuild +++ b/include/linux/Kbuild @@ -344,6 +344,7 @@ unifdef-y += utsname.h unifdef-y += videodev2.h unifdef-y += videodev.h unifdef-y += virtio_config.h +unifdef-y += virtio_blk.h unifdef-y += virtio_net.h unifdef-y += wait.h unifdef-y += wanrouter.h diff --git a/include/linux/virtio_blk.h b/include/linux/virtio_blk.h new file mode 100644 index 000000000000..7bd2bce0cfd9 --- /dev/null +++ b/include/linux/virtio_blk.h @@ -0,0 +1,51 @@ +#ifndef _LINUX_VIRTIO_BLK_H +#define _LINUX_VIRTIO_BLK_H +#include + +/* The ID for virtio_block */ +#define VIRTIO_ID_BLOCK 2 + +/* Feature bits */ +#define VIRTIO_CONFIG_BLK_F 0x40 +#define VIRTIO_BLK_F_BARRIER 1 /* Does host support barriers? */ + +/* The capacity (in 512-byte sectors). */ +#define VIRTIO_CONFIG_BLK_F_CAPACITY 0x41 +/* The maximum segment size. */ +#define VIRTIO_CONFIG_BLK_F_SIZE_MAX 0x42 +/* The maximum number of segments. */ +#define VIRTIO_CONFIG_BLK_F_SEG_MAX 0x43 + +/* These two define direction. */ +#define VIRTIO_BLK_T_IN 0 +#define VIRTIO_BLK_T_OUT 1 + +/* This bit says it's a scsi command, not an actual read or write. */ +#define VIRTIO_BLK_T_SCSI_CMD 2 + +/* Barrier before this op. */ +#define VIRTIO_BLK_T_BARRIER 0x80000000 + +/* This is the first element of the read scatter-gather list. */ +struct virtio_blk_outhdr +{ + /* VIRTIO_BLK_T* */ + __u32 type; + /* io priority. */ + __u32 ioprio; + /* Sector (ie. 512 byte offset) */ + __u64 sector; + /* Where to put reply. */ + __u64 id; +}; + +#define VIRTIO_BLK_S_OK 0 +#define VIRTIO_BLK_S_IOERR 1 +#define VIRTIO_BLK_S_UNSUPP 2 + +/* This is the first element of the write scatter-gather list */ +struct virtio_blk_inhdr +{ + unsigned char status; +}; +#endif /* _LINUX_VIRTIO_BLK_H */ -- cgit v1.2.3-71-gd317 From 31610434bc3523c0b01a10917a1185096a03c4c8 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 11:03:39 +1000 Subject: Virtio console driver This is an hvc-based virtio console driver. It's suboptimal becuase hvc expects to have raw access to interrupts and virtio doesn't assume that, so it currently polls. There are two solutions: expose hvc's "kick" interface, or wean off hvc. Signed-off-by: Rusty Russell --- drivers/char/Kconfig | 4 + drivers/char/Makefile | 1 + drivers/char/virtio_console.c | 225 +++++++++++++++++++++++++++++++++++++++++ include/linux/virtio_console.h | 12 +++ 4 files changed, 242 insertions(+) create mode 100644 drivers/char/virtio_console.c create mode 100644 include/linux/virtio_console.h (limited to 'include/linux') diff --git a/drivers/char/Kconfig b/drivers/char/Kconfig index 65491103e0fb..bf18d757b876 100644 --- a/drivers/char/Kconfig +++ b/drivers/char/Kconfig @@ -613,6 +613,10 @@ config HVC_XEN help Xen virtual console device driver +config VIRTIO_CONSOLE + bool + select HVC_DRIVER + config HVCS tristate "IBM Hypervisor Virtual Console Server support" depends on PPC_PSERIES diff --git a/drivers/char/Makefile b/drivers/char/Makefile index c78ff26647ee..057c8bbd7723 100644 --- a/drivers/char/Makefile +++ b/drivers/char/Makefile @@ -50,6 +50,7 @@ obj-$(CONFIG_HVC_RTAS) += hvc_rtas.o obj-$(CONFIG_HVC_BEAT) += hvc_beat.o obj-$(CONFIG_HVC_DRIVER) += hvc_console.o obj-$(CONFIG_HVC_XEN) += hvc_xen.o +obj-$(CONFIG_VIRTIO_CONSOLE) += virtio_console.o obj-$(CONFIG_RAW_DRIVER) += raw.o obj-$(CONFIG_SGI_SNSC) += snsc.o snsc_event.o obj-$(CONFIG_MSPEC) += mspec.o diff --git a/drivers/char/virtio_console.c b/drivers/char/virtio_console.c new file mode 100644 index 000000000000..100e8a201e3a --- /dev/null +++ b/drivers/char/virtio_console.c @@ -0,0 +1,225 @@ +/*D:300 + * The Guest console driver + * + * Writing console drivers is one of the few remaining Dark Arts in Linux. + * Fortunately for us, the path of virtual consoles has been well-trodden by + * the PowerPC folks, who wrote "hvc_console.c" to generically support any + * virtual console. We use that infrastructure which only requires us to write + * the basic put_chars and get_chars functions and call the right register + * functions. + :*/ + +/*M:002 The console can be flooded: while the Guest is processing input the + * Host can send more. Buffering in the Host could alleviate this, but it is a + * difficult problem in general. :*/ +/* Copyright (C) 2006, 2007 Rusty Russell, IBM Corporation + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include +#include +#include +#include +#include "hvc_console.h" + +/*D:340 These represent our input and output console queues, and the virtio + * operations for them. */ +static struct virtqueue *in_vq, *out_vq; +static struct virtio_device *vdev; + +/* This is our input buffer, and how much data is left in it. */ +static unsigned int in_len; +static char *in, *inbuf; + +/* The operations for our console. */ +static struct hv_ops virtio_cons; + +/*D:310 The put_chars() callback is pretty straightforward. + * + * We turn the characters into a scatter-gather list, add it to the output + * queue and then kick the Host. Then we sit here waiting for it to finish: + * inefficient in theory, but in practice implementations will do it + * immediately (lguest's Launcher does). */ +static int put_chars(u32 vtermno, const char *buf, int count) +{ + struct scatterlist sg[1]; + unsigned int len; + + /* This is a convenient routine to initialize a single-elem sg list */ + sg_init_one(sg, buf, count); + + /* add_buf wants a token to identify this buffer: we hand it any + * non-NULL pointer, since there's only ever one buffer. */ + if (out_vq->vq_ops->add_buf(out_vq, sg, 1, 0, (void *)1) == 0) { + /* Tell Host to go! */ + out_vq->vq_ops->kick(out_vq); + /* Chill out until it's done with the buffer. */ + while (!out_vq->vq_ops->get_buf(out_vq, &len)) + cpu_relax(); + } + + /* We're expected to return the amount of data we wrote: all of it. */ + return count; +} + +/* Create a scatter-gather list representing our input buffer and put it in the + * queue. */ +static void add_inbuf(void) +{ + struct scatterlist sg[1]; + sg_init_one(sg, inbuf, PAGE_SIZE); + + /* We should always be able to add one buffer to an empty queue. */ + if (in_vq->vq_ops->add_buf(in_vq, sg, 0, 1, inbuf) != 0) + BUG(); + in_vq->vq_ops->kick(in_vq); +} + +/*D:350 get_chars() is the callback from the hvc_console infrastructure when + * an interrupt is received. + * + * Most of the code deals with the fact that the hvc_console() infrastructure + * only asks us for 16 bytes at a time. We keep in_offset and in_used fields + * for partially-filled buffers. */ +static int get_chars(u32 vtermno, char *buf, int count) +{ + /* If we don't have an input queue yet, we can't get input. */ + BUG_ON(!in_vq); + + /* No buffer? Try to get one. */ + if (!in_len) { + in = in_vq->vq_ops->get_buf(in_vq, &in_len); + if (!in) + return 0; + } + + /* You want more than we have to give? Well, try wanting less! */ + if (in_len < count) + count = in_len; + + /* Copy across to their buffer and increment offset. */ + memcpy(buf, in, count); + in += count; + in_len -= count; + + /* Finished? Re-register buffer so Host will use it again. */ + if (in_len == 0) + add_inbuf(); + + return count; +} +/*:*/ + +/*D:320 Console drivers are initialized very early so boot messages can go out, + * so we do things slightly differently from the generic virtio initialization + * of the net and block drivers. + * + * At this stage, the console is output-only. It's too early to set up a + * virtqueue, so we let the drivers do some boutique early-output thing. */ +int __init virtio_cons_early_init(int (*put_chars)(u32, const char *, int)) +{ + virtio_cons.put_chars = put_chars; + return hvc_instantiate(0, 0, &virtio_cons); +} + +/*D:370 Once we're further in boot, we get probed like any other virtio device. + * At this stage we set up the output virtqueue. + * + * To set up and manage our virtual console, we call hvc_alloc(). Since we + * never remove the console device we never need this pointer again. + * + * Finally we put our input buffer in the input queue, ready to receive. */ +static int virtcons_probe(struct virtio_device *dev) +{ + int err; + struct hvc_struct *hvc; + + vdev = dev; + + /* This is the scratch page we use to receive console input */ + inbuf = kmalloc(PAGE_SIZE, GFP_KERNEL); + if (!inbuf) { + err = -ENOMEM; + goto fail; + } + + /* Find the input queue. */ + /* FIXME: This is why we want to wean off hvc: we do nothing + * when input comes in. */ + in_vq = vdev->config->find_vq(vdev, NULL); + if (IS_ERR(in_vq)) { + err = PTR_ERR(in_vq); + goto free; + } + + out_vq = vdev->config->find_vq(vdev, NULL); + if (IS_ERR(out_vq)) { + err = PTR_ERR(out_vq); + goto free_in_vq; + } + + /* Start using the new console output. */ + virtio_cons.get_chars = get_chars; + virtio_cons.put_chars = put_chars; + + /* The first argument of hvc_alloc() is the virtual console number, so + * we use zero. The second argument is the interrupt number; we + * currently leave this as zero: it would be better not to use the + * hvc mechanism and fix this (FIXME!). + * + * The third argument is a "struct hv_ops" containing the put_chars() + * and get_chars() pointers. The final argument is the output buffer + * size: we can do any size, so we put PAGE_SIZE here. */ + hvc = hvc_alloc(0, 0, &virtio_cons, PAGE_SIZE); + if (IS_ERR(hvc)) { + err = PTR_ERR(hvc); + goto free_out_vq; + } + + /* Register the input buffer the first time. */ + add_inbuf(); + return 0; + +free_out_vq: + vdev->config->del_vq(out_vq); +free_in_vq: + vdev->config->del_vq(in_vq); +free: + kfree(inbuf); +fail: + return err; +} + +static struct virtio_device_id id_table[] = { + { VIRTIO_ID_CONSOLE, VIRTIO_DEV_ANY_ID }, + { 0 }, +}; + +static struct virtio_driver virtio_console = { + .driver.name = KBUILD_MODNAME, + .driver.owner = THIS_MODULE, + .id_table = id_table, + .probe = virtcons_probe, +}; + +static int __init init(void) +{ + return register_virtio_driver(&virtio_console); +} +module_init(init); + +MODULE_DEVICE_TABLE(virtio, id_table); +MODULE_DESCRIPTION("Virtio console driver"); +MODULE_LICENSE("GPL"); diff --git a/include/linux/virtio_console.h b/include/linux/virtio_console.h new file mode 100644 index 000000000000..ed2d4ead7eb7 --- /dev/null +++ b/include/linux/virtio_console.h @@ -0,0 +1,12 @@ +#ifndef _LINUX_VIRTIO_CONSOLE_H +#define _LINUX_VIRTIO_CONSOLE_H +#include + +/* The ID for virtio console */ +#define VIRTIO_ID_CONSOLE 3 + +#ifdef __KERNEL__ +int __init virtio_cons_early_init(int (*put_chars)(u32, const char *, int)); +#endif /* __KERNEL__ */ + +#endif /* _LINUX_VIRTIO_CONSOLE_H */ -- cgit v1.2.3-71-gd317 From 0a8a69dd77ddbd4513b21363021ecde7e1025502 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 11:03:40 +1000 Subject: Virtio helper routines for a descriptor ringbuffer implementation These helper routines supply most of the virtqueue_ops for hypervisors which want to use a ring for virtio. Unlike the previous lguest implementation: 1) The rings are variable sized (2^n-1 elements). 2) They have an unfortunate limit of 65535 bytes per sg element. 3) The page numbers are always 64 bit (PAE anyone?) 4) They no longer place used[] on a separate page, just a separate cacheline. 5) We do a modulo on a variable. We could be tricky if we cared. 6) Interrupts and notifies are suppressed using flags within the rings. Users need only get the ring pages and provide a notify hook (KVM wants the guest to allocate the rings, lguest does it sanely). Signed-off-by: Rusty Russell Cc: Dor Laor --- arch/x86/lguest/Kconfig | 1 + drivers/virtio/Kconfig | 5 + drivers/virtio/Makefile | 1 + drivers/virtio/virtio_ring.c | 313 +++++++++++++++++++++++++++++++++++++++++++ include/linux/virtio_ring.h | 119 ++++++++++++++++ 5 files changed, 439 insertions(+) create mode 100644 drivers/virtio/virtio_ring.c create mode 100644 include/linux/virtio_ring.h (limited to 'include/linux') diff --git a/arch/x86/lguest/Kconfig b/arch/x86/lguest/Kconfig index 0fabf87db998..44dccfd845f8 100644 --- a/arch/x86/lguest/Kconfig +++ b/arch/x86/lguest/Kconfig @@ -2,6 +2,7 @@ config LGUEST_GUEST bool "Lguest guest support" select PARAVIRT depends on !X86_PAE + select VIRTIO_RING help Lguest is a tiny in-kernel hypervisor. Selecting this will allow your kernel to boot under lguest. This option will increase diff --git a/drivers/virtio/Kconfig b/drivers/virtio/Kconfig index bce84b56a659..9e33fc4da875 100644 --- a/drivers/virtio/Kconfig +++ b/drivers/virtio/Kconfig @@ -1,3 +1,8 @@ # Virtio always gets selected by whoever wants it. config VIRTIO bool + +# Similarly the virtio ring implementation. +config VIRTIO_RING + bool + depends on VIRTIO diff --git a/drivers/virtio/Makefile b/drivers/virtio/Makefile index af0d57dad3eb..f70e40971dd9 100644 --- a/drivers/virtio/Makefile +++ b/drivers/virtio/Makefile @@ -1 +1,2 @@ obj-$(CONFIG_VIRTIO) += virtio.o +obj-$(CONFIG_VIRTIO_RING) += virtio_ring.o diff --git a/drivers/virtio/virtio_ring.c b/drivers/virtio/virtio_ring.c new file mode 100644 index 000000000000..0e4baca21b8f --- /dev/null +++ b/drivers/virtio/virtio_ring.c @@ -0,0 +1,313 @@ +/* Virtio ring implementation. + * + * Copyright 2007 Rusty Russell IBM Corporation + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include +#include +#include + +#ifdef DEBUG +/* For development, we want to crash whenever the ring is screwed. */ +#define BAD_RING(vq, fmt...) \ + do { dev_err(&vq->vq.vdev->dev, fmt); BUG(); } while(0) +#define START_USE(vq) \ + do { if ((vq)->in_use) panic("in_use = %i\n", (vq)->in_use); (vq)->in_use = __LINE__; mb(); } while(0) +#define END_USE(vq) \ + do { BUG_ON(!(vq)->in_use); (vq)->in_use = 0; mb(); } while(0) +#else +#define BAD_RING(vq, fmt...) \ + do { dev_err(&vq->vq.vdev->dev, fmt); (vq)->broken = true; } while(0) +#define START_USE(vq) +#define END_USE(vq) +#endif + +struct vring_virtqueue +{ + struct virtqueue vq; + + /* Actual memory layout for this queue */ + struct vring vring; + + /* Other side has made a mess, don't try any more. */ + bool broken; + + /* Number of free buffers */ + unsigned int num_free; + /* Head of free buffer list. */ + unsigned int free_head; + /* Number we've added since last sync. */ + unsigned int num_added; + + /* Last used index we've seen. */ + unsigned int last_used_idx; + + /* How to notify other side. FIXME: commonalize hcalls! */ + void (*notify)(struct virtqueue *vq); + +#ifdef DEBUG + /* They're supposed to lock for us. */ + unsigned int in_use; +#endif + + /* Tokens for callbacks. */ + void *data[]; +}; + +#define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq) + +static int vring_add_buf(struct virtqueue *_vq, + struct scatterlist sg[], + unsigned int out, + unsigned int in, + void *data) +{ + struct vring_virtqueue *vq = to_vvq(_vq); + unsigned int i, avail, head, uninitialized_var(prev); + + BUG_ON(data == NULL); + BUG_ON(out + in > vq->vring.num); + BUG_ON(out + in == 0); + + START_USE(vq); + + if (vq->num_free < out + in) { + pr_debug("Can't add buf len %i - avail = %i\n", + out + in, vq->num_free); + END_USE(vq); + return -ENOSPC; + } + + /* We're about to use some buffers from the free list. */ + vq->num_free -= out + in; + + head = vq->free_head; + for (i = vq->free_head; out; i = vq->vring.desc[i].next, out--) { + vq->vring.desc[i].flags = VRING_DESC_F_NEXT; + vq->vring.desc[i].addr = (page_to_pfn(sg_page(sg))<offset; + vq->vring.desc[i].len = sg->length; + prev = i; + sg++; + } + for (; in; i = vq->vring.desc[i].next, in--) { + vq->vring.desc[i].flags = VRING_DESC_F_NEXT|VRING_DESC_F_WRITE; + vq->vring.desc[i].addr = (page_to_pfn(sg_page(sg))<offset; + vq->vring.desc[i].len = sg->length; + prev = i; + sg++; + } + /* Last one doesn't continue. */ + vq->vring.desc[prev].flags &= ~VRING_DESC_F_NEXT; + + /* Update free pointer */ + vq->free_head = i; + + /* Set token. */ + vq->data[head] = data; + + /* Put entry in available array (but don't update avail->idx until they + * do sync). FIXME: avoid modulus here? */ + avail = (vq->vring.avail->idx + vq->num_added++) % vq->vring.num; + vq->vring.avail->ring[avail] = head; + + pr_debug("Added buffer head %i to %p\n", head, vq); + END_USE(vq); + return 0; +} + +static void vring_kick(struct virtqueue *_vq) +{ + struct vring_virtqueue *vq = to_vvq(_vq); + START_USE(vq); + /* Descriptors and available array need to be set before we expose the + * new available array entries. */ + wmb(); + + vq->vring.avail->idx += vq->num_added; + vq->num_added = 0; + + /* Need to update avail index before checking if we should notify */ + mb(); + + if (!(vq->vring.used->flags & VRING_USED_F_NO_NOTIFY)) + /* Prod other side to tell it about changes. */ + vq->notify(&vq->vq); + + END_USE(vq); +} + +static void detach_buf(struct vring_virtqueue *vq, unsigned int head) +{ + unsigned int i; + + /* Clear data ptr. */ + vq->data[head] = NULL; + + /* Put back on free list: find end */ + i = head; + while (vq->vring.desc[i].flags & VRING_DESC_F_NEXT) { + i = vq->vring.desc[i].next; + vq->num_free++; + } + + vq->vring.desc[i].next = vq->free_head; + vq->free_head = head; + /* Plus final descriptor */ + vq->num_free++; +} + +/* FIXME: We need to tell other side about removal, to synchronize. */ +static void vring_shutdown(struct virtqueue *_vq) +{ + struct vring_virtqueue *vq = to_vvq(_vq); + unsigned int i; + + for (i = 0; i < vq->vring.num; i++) + detach_buf(vq, i); +} + +static inline bool more_used(const struct vring_virtqueue *vq) +{ + return vq->last_used_idx != vq->vring.used->idx; +} + +static void *vring_get_buf(struct virtqueue *_vq, unsigned int *len) +{ + struct vring_virtqueue *vq = to_vvq(_vq); + void *ret; + unsigned int i; + + START_USE(vq); + + if (!more_used(vq)) { + pr_debug("No more buffers in queue\n"); + END_USE(vq); + return NULL; + } + + i = vq->vring.used->ring[vq->last_used_idx%vq->vring.num].id; + *len = vq->vring.used->ring[vq->last_used_idx%vq->vring.num].len; + + if (unlikely(i >= vq->vring.num)) { + BAD_RING(vq, "id %u out of range\n", i); + return NULL; + } + if (unlikely(!vq->data[i])) { + BAD_RING(vq, "id %u is not a head!\n", i); + return NULL; + } + + /* detach_buf clears data, so grab it now. */ + ret = vq->data[i]; + detach_buf(vq, i); + vq->last_used_idx++; + END_USE(vq); + return ret; +} + +static bool vring_restart(struct virtqueue *_vq) +{ + struct vring_virtqueue *vq = to_vvq(_vq); + + START_USE(vq); + BUG_ON(!(vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)); + + /* We optimistically turn back on interrupts, then check if there was + * more to do. */ + vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT; + mb(); + if (unlikely(more_used(vq))) { + vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT; + END_USE(vq); + return false; + } + + END_USE(vq); + return true; +} + +irqreturn_t vring_interrupt(int irq, void *_vq) +{ + struct vring_virtqueue *vq = to_vvq(_vq); + + if (!more_used(vq)) { + pr_debug("virtqueue interrupt with no work for %p\n", vq); + return IRQ_NONE; + } + + if (unlikely(vq->broken)) + return IRQ_HANDLED; + + pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback); + if (vq->vq.callback && !vq->vq.callback(&vq->vq)) + vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT; + + return IRQ_HANDLED; +} + +static struct virtqueue_ops vring_vq_ops = { + .add_buf = vring_add_buf, + .get_buf = vring_get_buf, + .kick = vring_kick, + .restart = vring_restart, + .shutdown = vring_shutdown, +}; + +struct virtqueue *vring_new_virtqueue(unsigned int num, + struct virtio_device *vdev, + void *pages, + void (*notify)(struct virtqueue *), + bool (*callback)(struct virtqueue *)) +{ + struct vring_virtqueue *vq; + unsigned int i; + + vq = kmalloc(sizeof(*vq) + sizeof(void *)*num, GFP_KERNEL); + if (!vq) + return NULL; + + vring_init(&vq->vring, num, pages); + vq->vq.callback = callback; + vq->vq.vdev = vdev; + vq->vq.vq_ops = &vring_vq_ops; + vq->notify = notify; + vq->broken = false; + vq->last_used_idx = 0; + vq->num_added = 0; +#ifdef DEBUG + vq->in_use = false; +#endif + + /* No callback? Tell other side not to bother us. */ + if (!callback) + vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT; + + /* Put everything in free lists. */ + vq->num_free = num; + vq->free_head = 0; + for (i = 0; i < num-1; i++) + vq->vring.desc[i].next = i+1; + + return &vq->vq; +} + +void vring_del_virtqueue(struct virtqueue *vq) +{ + kfree(to_vvq(vq)); +} + diff --git a/include/linux/virtio_ring.h b/include/linux/virtio_ring.h new file mode 100644 index 000000000000..ac69e7bb5a14 --- /dev/null +++ b/include/linux/virtio_ring.h @@ -0,0 +1,119 @@ +#ifndef _LINUX_VIRTIO_RING_H +#define _LINUX_VIRTIO_RING_H +/* An interface for efficient virtio implementation, currently for use by KVM + * and lguest, but hopefully others soon. Do NOT change this since it will + * break existing servers and clients. + * + * This header is BSD licensed so anyone can use the definitions to implement + * compatible drivers/servers. + * + * Copyright Rusty Russell IBM Corporation 2007. */ +#include + +/* This marks a buffer as continuing via the next field. */ +#define VRING_DESC_F_NEXT 1 +/* This marks a buffer as write-only (otherwise read-only). */ +#define VRING_DESC_F_WRITE 2 + +/* This means don't notify other side when buffer added. */ +#define VRING_USED_F_NO_NOTIFY 1 +/* This means don't interrupt guest when buffer consumed. */ +#define VRING_AVAIL_F_NO_INTERRUPT 1 + +/* Virtio ring descriptors: 16 bytes. These can chain together via "next". */ +struct vring_desc +{ + /* Address (guest-physical). */ + __u64 addr; + /* Length. */ + __u32 len; + /* The flags as indicated above. */ + __u16 flags; + /* We chain unused descriptors via this, too */ + __u16 next; +}; + +struct vring_avail +{ + __u16 flags; + __u16 idx; + __u16 ring[]; +}; + +/* u32 is used here for ids for padding reasons. */ +struct vring_used_elem +{ + /* Index of start of used descriptor chain. */ + __u32 id; + /* Total length of the descriptor chain which was used (written to) */ + __u32 len; +}; + +struct vring_used +{ + __u16 flags; + __u16 idx; + struct vring_used_elem ring[]; +}; + +struct vring { + unsigned int num; + + struct vring_desc *desc; + + struct vring_avail *avail; + + struct vring_used *used; +}; + +/* The standard layout for the ring is a continuous chunk of memory which looks + * like this. The used fields will be aligned to a "num+1" boundary. + * + * struct vring + * { + * // The actual descriptors (16 bytes each) + * struct vring_desc desc[num]; + * + * // A ring of available descriptor heads with free-running index. + * __u16 avail_flags; + * __u16 avail_idx; + * __u16 available[num]; + * + * // Padding so a correctly-chosen num value will cache-align used_idx. + * char pad[sizeof(struct vring_desc) - sizeof(avail_flags)]; + * + * // A ring of used descriptor heads with free-running index. + * __u16 used_flags; + * __u16 used_idx; + * struct vring_used_elem used[num]; + * }; + */ +static inline void vring_init(struct vring *vr, unsigned int num, void *p) +{ + vr->num = num; + vr->desc = p; + vr->avail = p + num*sizeof(struct vring); + vr->used = p + (num+1)*(sizeof(struct vring) + sizeof(__u16)); +} + +static inline unsigned vring_size(unsigned int num) +{ + return (num + 1) * (sizeof(struct vring_desc) + sizeof(__u16)) + + sizeof(__u32) + num * sizeof(struct vring_used_elem); +} + +#ifdef __KERNEL__ +#include +struct virtio_device; +struct virtqueue; + +struct virtqueue *vring_new_virtqueue(unsigned int num, + struct virtio_device *vdev, + void *pages, + void (*notify)(struct virtqueue *vq), + bool (*callback)(struct virtqueue *vq)); +void vring_del_virtqueue(struct virtqueue *vq); + +irqreturn_t vring_interrupt(int irq, void *_vq); +#endif /* __KERNEL__ */ +#endif /* _LINUX_VIRTIO_RING_H */ -- cgit v1.2.3-71-gd317 From 0ca49ca946409f87a8cd0b14d5acb6dea58de6f3 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 11:20:02 +1000 Subject: Remove old lguest bus and drivers. This gets rid of the lguest bus, drivers and DMA mechanism, to make way for a generic virtio mechanism. Signed-off-by: Rusty Russell --- arch/x86/lguest/boot.c | 41 --- drivers/block/Makefile | 1 - drivers/block/lguest_blk.c | 421 ------------------------------ drivers/char/Makefile | 1 - drivers/char/hvc_lguest.c | 177 ------------- drivers/lguest/Kconfig | 10 - drivers/lguest/Makefile | 3 - drivers/lguest/lguest_bus.c | 220 ---------------- drivers/lguest/x86/core.c | 1 - drivers/net/Makefile | 1 - drivers/net/lguest_net.c | 550 ---------------------------------------- include/linux/lguest_bus.h | 51 ---- include/linux/lguest_launcher.h | 26 -- 13 files changed, 1503 deletions(-) delete mode 100644 drivers/block/lguest_blk.c delete mode 100644 drivers/char/hvc_lguest.c delete mode 100644 drivers/lguest/lguest_bus.c delete mode 100644 drivers/net/lguest_net.c delete mode 100644 include/linux/lguest_bus.h (limited to 'include/linux') diff --git a/arch/x86/lguest/boot.c b/arch/x86/lguest/boot.c index 090f30cbf24c..959aeebb02f5 100644 --- a/arch/x86/lguest/boot.c +++ b/arch/x86/lguest/boot.c @@ -55,7 +55,6 @@ #include #include #include -#include #include #include #include @@ -162,46 +161,6 @@ void async_hcall(unsigned long call, } /*:*/ -/* Wrappers for the SEND_DMA and BIND_DMA hypercalls. This is mainly because - * Jeff Garzik complained that __pa() should never appear in drivers, and this - * helps remove most of them. But also, it wraps some ugliness. */ -void lguest_send_dma(unsigned long key, struct lguest_dma *dma) -{ - /* The hcall might not write this if something goes wrong */ - dma->used_len = 0; - hcall(LHCALL_SEND_DMA, key, __pa(dma), 0); -} - -int lguest_bind_dma(unsigned long key, struct lguest_dma *dmas, - unsigned int num, u8 irq) -{ - /* This is the only hypercall which actually wants 5 arguments, and we - * only support 4. Fortunately the interrupt number is always less - * than 256, so we can pack it with the number of dmas in the final - * argument. */ - if (!hcall(LHCALL_BIND_DMA, key, __pa(dmas), (num << 8) | irq)) - return -ENOMEM; - return 0; -} - -/* Unbinding is the same hypercall as binding, but with 0 num & irq. */ -void lguest_unbind_dma(unsigned long key, struct lguest_dma *dmas) -{ - hcall(LHCALL_BIND_DMA, key, __pa(dmas), 0); -} - -/* For guests, device memory can be used as normal memory, so we cast away the - * __iomem to quieten sparse. */ -void *lguest_map(unsigned long phys_addr, unsigned long pages) -{ - return (__force void *)ioremap(phys_addr, PAGE_SIZE*pages); -} - -void lguest_unmap(void *addr) -{ - iounmap((__force void __iomem *)addr); -} - /*G:033 * Here are our first native-instruction replacements: four functions for * interrupt control. diff --git a/drivers/block/Makefile b/drivers/block/Makefile index d199eba7a080..7691505a2e12 100644 --- a/drivers/block/Makefile +++ b/drivers/block/Makefile @@ -32,4 +32,3 @@ obj-$(CONFIG_BLK_DEV_SX8) += sx8.o obj-$(CONFIG_BLK_DEV_UB) += ub.o obj-$(CONFIG_XEN_BLKDEV_FRONTEND) += xen-blkfront.o -obj-$(CONFIG_LGUEST_BLOCK) += lguest_blk.o diff --git a/drivers/block/lguest_blk.c b/drivers/block/lguest_blk.c deleted file mode 100644 index fa8e42341b87..000000000000 --- a/drivers/block/lguest_blk.c +++ /dev/null @@ -1,421 +0,0 @@ -/*D:400 - * The Guest block driver - * - * This is a simple block driver, which appears as /dev/lgba, lgbb, lgbc etc. - * The mechanism is simple: we place the information about the request in the - * device page, then use SEND_DMA (containing the data for a write, or an empty - * "ping" DMA for a read). - :*/ -/* Copyright 2006 Rusty Russell IBM Corporation - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -//#define DEBUG -#include -#include -#include -#include -#include - -static char next_block_index = 'a'; - -/*D:420 Here is the structure which holds all the information we need about - * each Guest block device. - * - * I'm sure at this stage, you're wondering "hey, where was the adventure I was - * promised?" and thinking "Rusty sucks, I shall say nasty things about him on - * my blog". I think Real adventures have boring bits, too, and you're in the - * middle of one. But it gets better. Just not quite yet. */ -struct blockdev -{ - /* The block queue infrastructure wants a spinlock: it is held while it - * calls our block request function. We grab it in our interrupt - * handler so the responses don't mess with new requests. */ - spinlock_t lock; - - /* The disk structure registered with kernel. */ - struct gendisk *disk; - - /* The major device number for this disk, and the interrupt. We only - * really keep them here for completeness; we'd need them if we - * supported device unplugging. */ - int major; - int irq; - - /* The physical address of this device's memory page */ - unsigned long phys_addr; - /* The mapped memory page for convenient acces. */ - struct lguest_block_page *lb_page; - - /* We only have a single request outstanding at a time: this is it. */ - struct lguest_dma dma; - struct request *req; -}; - -/*D:495 We originally used end_request() throughout the driver, but it turns - * out that end_request() is deprecated, and doesn't actually end the request - * (which seems like a good reason to deprecate it!). It simply ends the first - * bio. So if we had 3 bios in a "struct request" we would do all 3, - * end_request(), do 2, end_request(), do 1 and end_request(): twice as much - * work as we needed to do. - * - * This reinforced to me that I do not understand the block layer. - * - * Nonetheless, Jens Axboe gave me this nice helper to end all chunks of a - * request. This improved disk speed by 130%. */ -static void end_entire_request(struct request *req, int uptodate) -{ - if (end_that_request_first(req, uptodate, req->hard_nr_sectors)) - BUG(); - add_disk_randomness(req->rq_disk); - blkdev_dequeue_request(req); - end_that_request_last(req, uptodate); -} - -/* I'm told there are only two stories in the world worth telling: love and - * hate. So there used to be a love scene here like this: - * - * Launcher: We could make beautiful I/O together, you and I. - * Guest: My, that's a big disk! - * - * Unfortunately, it was just too raunchy for our otherwise-gentle tale. */ - -/*D:490 This is the interrupt handler, called when a block read or write has - * been completed for us. */ -static irqreturn_t lgb_irq(int irq, void *_bd) -{ - /* We handed our "struct blockdev" as the argument to request_irq(), so - * it is passed through to us here. This tells us which device we're - * dealing with in case we have more than one. */ - struct blockdev *bd = _bd; - unsigned long flags; - - /* We weren't doing anything? Strange, but could happen if we shared - * interrupts (we don't!). */ - if (!bd->req) { - pr_debug("No work!\n"); - return IRQ_NONE; - } - - /* Not done yet? That's equally strange. */ - if (!bd->lb_page->result) { - pr_debug("No result!\n"); - return IRQ_NONE; - } - - /* We have to grab the lock before ending the request. */ - spin_lock_irqsave(&bd->lock, flags); - /* "result" is 1 for success, 2 for failure: end_entire_request() wants - * to know whether this succeeded or not. */ - end_entire_request(bd->req, bd->lb_page->result == 1); - /* Clear out request, it's done. */ - bd->req = NULL; - /* Reset incoming DMA for next time. */ - bd->dma.used_len = 0; - /* Ready for more reads or writes */ - blk_start_queue(bd->disk->queue); - spin_unlock_irqrestore(&bd->lock, flags); - - /* The interrupt was for us, we dealt with it. */ - return IRQ_HANDLED; -} - -/*D:480 The block layer's "struct request" contains a number of "struct bio"s, - * each of which contains "struct bio_vec"s, each of which contains a page, an - * offset and a length. - * - * Fortunately there are iterators to help us walk through the "struct - * request". Even more fortunately, there were plenty of places to steal the - * code from. We pack the "struct request" into our "struct lguest_dma" and - * return the total length. */ -static unsigned int req_to_dma(struct request *req, struct lguest_dma *dma) -{ - unsigned int i = 0, len = 0; - struct req_iterator iter; - struct bio_vec *bvec; - - rq_for_each_segment(bvec, req, iter) { - /* We told the block layer not to give us too many. */ - BUG_ON(i == LGUEST_MAX_DMA_SECTIONS); - /* If we had a zero-length segment, it would look like - * the end of the data referred to by the "struct - * lguest_dma", so make sure that doesn't happen. */ - BUG_ON(!bvec->bv_len); - /* Convert page & offset to a physical address */ - dma->addr[i] = page_to_phys(bvec->bv_page) - + bvec->bv_offset; - dma->len[i] = bvec->bv_len; - len += bvec->bv_len; - i++; - } - /* If the array isn't full, we mark the end with a 0 length */ - if (i < LGUEST_MAX_DMA_SECTIONS) - dma->len[i] = 0; - return len; -} - -/* This creates an empty DMA, useful for prodding the Host without sending data - * (ie. when we want to do a read) */ -static void empty_dma(struct lguest_dma *dma) -{ - dma->len[0] = 0; -} - -/*D:470 Setting up a request is fairly easy: */ -static void setup_req(struct blockdev *bd, - int type, struct request *req, struct lguest_dma *dma) -{ - /* The type is 1 (write) or 0 (read). */ - bd->lb_page->type = type; - /* The sector on disk where the read or write starts. */ - bd->lb_page->sector = req->sector; - /* The result is initialized to 0 (unfinished). */ - bd->lb_page->result = 0; - /* The current request (so we can end it in the interrupt handler). */ - bd->req = req; - /* The number of bytes: returned as a side-effect of req_to_dma(), - * which packs the block layer's "struct request" into our "struct - * lguest_dma" */ - bd->lb_page->bytes = req_to_dma(req, dma); -} - -/*D:450 Write is pretty straightforward: we pack the request into a "struct - * lguest_dma", then use SEND_DMA to send the request. */ -static void do_write(struct blockdev *bd, struct request *req) -{ - struct lguest_dma send; - - pr_debug("lgb: WRITE sector %li\n", (long)req->sector); - setup_req(bd, 1, req, &send); - - lguest_send_dma(bd->phys_addr, &send); -} - -/* Read is similar to write, except we pack the request into our receive - * "struct lguest_dma" and send through an empty DMA just to tell the Host that - * there's a request pending. */ -static void do_read(struct blockdev *bd, struct request *req) -{ - struct lguest_dma ping; - - pr_debug("lgb: READ sector %li\n", (long)req->sector); - setup_req(bd, 0, req, &bd->dma); - - empty_dma(&ping); - lguest_send_dma(bd->phys_addr, &ping); -} - -/*D:440 This where requests come in: we get handed the request queue and are - * expected to pull a "struct request" off it until we've finished them or - * we're waiting for a reply: */ -static void do_lgb_request(struct request_queue *q) -{ - struct blockdev *bd; - struct request *req; - -again: - /* This sometimes returns NULL even on the very first time around. I - * wonder if it's something to do with letting elves handle the request - * queue... */ - req = elv_next_request(q); - if (!req) - return; - - /* We attached the struct blockdev to the disk: get it back */ - bd = req->rq_disk->private_data; - /* Sometimes we get repeated requests after blk_stop_queue(), but we - * can only handle one at a time. */ - if (bd->req) - return; - - /* We only do reads and writes: no tricky business! */ - if (!blk_fs_request(req)) { - pr_debug("Got non-command 0x%08x\n", req->cmd_type); - req->errors++; - end_entire_request(req, 0); - goto again; - } - - if (rq_data_dir(req) == WRITE) - do_write(bd, req); - else - do_read(bd, req); - - /* We've put out the request, so stop any more coming in until we get - * an interrupt, which takes us to lgb_irq() to re-enable the queue. */ - blk_stop_queue(q); -} - -/*D:430 This is the "struct block_device_operations" we attach to the disk at - * the end of lguestblk_probe(). It doesn't seem to want much. */ -static struct block_device_operations lguestblk_fops = { - .owner = THIS_MODULE, -}; - -/*D:425 Setting up a disk device seems to involve a lot of code. I'm not sure - * quite why. I do know that the IDE code sent two or three of the maintainers - * insane, perhaps this is the fringe of the same disease? - * - * As in the console code, the probe function gets handed the generic - * lguest_device from lguest_bus.c: */ -static int lguestblk_probe(struct lguest_device *lgdev) -{ - struct blockdev *bd; - int err; - int irqflags = IRQF_SHARED; - - /* First we allocate our own "struct blockdev" and initialize the easy - * fields. */ - bd = kmalloc(sizeof(*bd), GFP_KERNEL); - if (!bd) - return -ENOMEM; - - spin_lock_init(&bd->lock); - bd->irq = lgdev_irq(lgdev); - bd->req = NULL; - bd->dma.used_len = 0; - bd->dma.len[0] = 0; - /* The descriptor in the lguest_devices array provided by the Host - * gives the Guest the physical page number of the device's page. */ - bd->phys_addr = (lguest_devices[lgdev->index].pfn << PAGE_SHIFT); - - /* We use lguest_map() to get a pointer to the device page */ - bd->lb_page = lguest_map(bd->phys_addr, 1); - if (!bd->lb_page) { - err = -ENOMEM; - goto out_free_bd; - } - - /* We need a major device number: 0 means "assign one dynamically". */ - bd->major = register_blkdev(0, "lguestblk"); - if (bd->major < 0) { - err = bd->major; - goto out_unmap; - } - - /* This allocates a "struct gendisk" where we pack all the information - * about the disk which the rest of Linux sees. The argument is the - * number of minor devices desired: we need one minor for the main - * disk, and one for each partition. Of course, we can't possibly know - * how many partitions are on the disk (add_disk does that). - */ - bd->disk = alloc_disk(16); - if (!bd->disk) { - err = -ENOMEM; - goto out_unregister_blkdev; - } - - /* Every disk needs a queue for requests to come in: we set up the - * queue with a callback function (the core of our driver) and the lock - * to use. */ - bd->disk->queue = blk_init_queue(do_lgb_request, &bd->lock); - if (!bd->disk->queue) { - err = -ENOMEM; - goto out_put_disk; - } - - /* We can only handle a certain number of pointers in our SEND_DMA - * call, so we set that with blk_queue_max_hw_segments(). This is not - * to be confused with blk_queue_max_phys_segments() of course! I - * know, who could possibly confuse the two? - * - * Well, it's simple to tell them apart: this one seems to work and the - * other one didn't. */ - blk_queue_max_hw_segments(bd->disk->queue, LGUEST_MAX_DMA_SECTIONS); - - /* Due to technical limitations of our Host (and simple coding) we - * can't have a single buffer which crosses a page boundary. Tell it - * here. This means that our maximum request size is 16 - * (LGUEST_MAX_DMA_SECTIONS) pages. */ - blk_queue_segment_boundary(bd->disk->queue, PAGE_SIZE-1); - - /* We name our disk: this becomes the device name when udev does its - * magic thing and creates the device node, such as /dev/lgba. - * next_block_index is a global which starts at 'a'. Unfortunately - * this simple increment logic means that the 27th disk will be called - * "/dev/lgb{". In that case, I recommend having at least 29 disks, so - * your /dev directory will be balanced. */ - sprintf(bd->disk->disk_name, "lgb%c", next_block_index++); - - /* We look to the device descriptor again to see if this device's - * interrupts are expected to be random. If they are, we tell the irq - * subsystem. At the moment this bit is always set. */ - if (lguest_devices[lgdev->index].features & LGUEST_DEVICE_F_RANDOMNESS) - irqflags |= IRQF_SAMPLE_RANDOM; - - /* Now we have the name and irqflags, we can request the interrupt; we - * give it the "struct blockdev" we have set up to pass to lgb_irq() - * when there is an interrupt. */ - err = request_irq(bd->irq, lgb_irq, irqflags, bd->disk->disk_name, bd); - if (err) - goto out_cleanup_queue; - - /* We bind our one-entry DMA pool to the key for this block device so - * the Host can reply to our requests. The key is equal to the - * physical address of the device's page, which is conveniently - * unique. */ - err = lguest_bind_dma(bd->phys_addr, &bd->dma, 1, bd->irq); - if (err) - goto out_free_irq; - - /* We finish our disk initialization and add the disk to the system. */ - bd->disk->major = bd->major; - bd->disk->first_minor = 0; - bd->disk->private_data = bd; - bd->disk->fops = &lguestblk_fops; - /* This is initialized to the disk size by the Launcher. */ - set_capacity(bd->disk, bd->lb_page->num_sectors); - add_disk(bd->disk); - - printk(KERN_INFO "%s: device %i at major %d\n", - bd->disk->disk_name, lgdev->index, bd->major); - - /* We don't need to keep the "struct blockdev" around, but if we ever - * implemented device removal, we'd need this. */ - lgdev->private = bd; - return 0; - -out_free_irq: - free_irq(bd->irq, bd); -out_cleanup_queue: - blk_cleanup_queue(bd->disk->queue); -out_put_disk: - put_disk(bd->disk); -out_unregister_blkdev: - unregister_blkdev(bd->major, "lguestblk"); -out_unmap: - lguest_unmap(bd->lb_page); -out_free_bd: - kfree(bd); - return err; -} - -/*D:410 The boilerplate code for registering the lguest block driver is just - * like the console: */ -static struct lguest_driver lguestblk_drv = { - .name = "lguestblk", - .owner = THIS_MODULE, - .device_type = LGUEST_DEVICE_T_BLOCK, - .probe = lguestblk_probe, -}; - -static __init int lguestblk_init(void) -{ - return register_lguest_driver(&lguestblk_drv); -} -module_init(lguestblk_init); - -MODULE_DESCRIPTION("Lguest block driver"); -MODULE_LICENSE("GPL"); diff --git a/drivers/char/Makefile b/drivers/char/Makefile index 057c8bbd7723..07304d50e0cb 100644 --- a/drivers/char/Makefile +++ b/drivers/char/Makefile @@ -42,7 +42,6 @@ obj-$(CONFIG_SYNCLINK_GT) += synclink_gt.o obj-$(CONFIG_N_HDLC) += n_hdlc.o obj-$(CONFIG_AMIGA_BUILTIN_SERIAL) += amiserial.o obj-$(CONFIG_SX) += sx.o generic_serial.o -obj-$(CONFIG_LGUEST_GUEST) += hvc_lguest.o obj-$(CONFIG_RIO) += rio/ generic_serial.o obj-$(CONFIG_HVC_CONSOLE) += hvc_vio.o hvsi.o obj-$(CONFIG_HVC_ISERIES) += hvc_iseries.o diff --git a/drivers/char/hvc_lguest.c b/drivers/char/hvc_lguest.c deleted file mode 100644 index efccb2155830..000000000000 --- a/drivers/char/hvc_lguest.c +++ /dev/null @@ -1,177 +0,0 @@ -/*D:300 - * The Guest console driver - * - * This is a trivial console driver: we use lguest's DMA mechanism to send - * bytes out, and register a DMA buffer to receive bytes in. It is assumed to - * be present and available from the very beginning of boot. - * - * Writing console drivers is one of the few remaining Dark Arts in Linux. - * Fortunately for us, the path of virtual consoles has been well-trodden by - * the PowerPC folks, who wrote "hvc_console.c" to generically support any - * virtual console. We use that infrastructure which only requires us to write - * the basic put_chars and get_chars functions and call the right register - * functions. - :*/ - -/*M:002 The console can be flooded: while the Guest is processing input the - * Host can send more. Buffering in the Host could alleviate this, but it is a - * difficult problem in general. :*/ -/* Copyright (C) 2006 Rusty Russell, IBM Corporation - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -#include -#include -#include -#include -#include "hvc_console.h" - -/*D:340 This is our single console input buffer, with associated "struct - * lguest_dma" referring to it. Note the 0-terminated length array, and the - * use of physical address for the buffer itself. */ -static char inbuf[256]; -static struct lguest_dma cons_input = { .used_len = 0, - .addr[0] = __pa(inbuf), - .len[0] = sizeof(inbuf), - .len[1] = 0 }; - -/*D:310 The put_chars() callback is pretty straightforward. - * - * First we put the pointer and length in a "struct lguest_dma": we only have - * one pointer, so we set the second length to 0. Then we use SEND_DMA to send - * the data to (Host) buffers attached to the console key. Usually a device's - * key is a physical address within the device's memory, but because the - * console device doesn't have any associated physical memory, we use the - * LGUEST_CONSOLE_DMA_KEY constant (aka 0). */ -static int put_chars(u32 vtermno, const char *buf, int count) -{ - struct lguest_dma dma; - - /* FIXME: DMA buffers in a "struct lguest_dma" are not allowed - * to go over page boundaries. This never seems to happen, - * but if it did we'd need to fix this code. */ - dma.len[0] = count; - dma.len[1] = 0; - dma.addr[0] = __pa(buf); - - lguest_send_dma(LGUEST_CONSOLE_DMA_KEY, &dma); - /* We're expected to return the amount of data we wrote: all of it. */ - return count; -} - -/*D:350 get_chars() is the callback from the hvc_console infrastructure when - * an interrupt is received. - * - * Firstly we see if our buffer has been filled: if not, we return. The rest - * of the code deals with the fact that the hvc_console() infrastructure only - * asks us for 16 bytes at a time. We keep a "cons_offset" variable for - * partially-read buffers. */ -static int get_chars(u32 vtermno, char *buf, int count) -{ - static int cons_offset; - - /* Nothing left to see here... */ - if (!cons_input.used_len) - return 0; - - /* You want more than we have to give? Well, try wanting less! */ - if (cons_input.used_len - cons_offset < count) - count = cons_input.used_len - cons_offset; - - /* Copy across to their buffer and increment offset. */ - memcpy(buf, inbuf + cons_offset, count); - cons_offset += count; - - /* Finished? Zero offset, and reset cons_input so Host will use it - * again. */ - if (cons_offset == cons_input.used_len) { - cons_offset = 0; - cons_input.used_len = 0; - } - return count; -} -/*:*/ - -static struct hv_ops lguest_cons = { - .get_chars = get_chars, - .put_chars = put_chars, -}; - -/*D:320 Console drivers are initialized very early so boot messages can go - * out. At this stage, the console is output-only. Our driver checks we're a - * Guest, and if so hands hvc_instantiate() the console number (0), priority - * (0), and the struct hv_ops containing the put_chars() function. */ -static int __init cons_init(void) -{ - if (strcmp(pv_info.name, "lguest") != 0) - return 0; - - return hvc_instantiate(0, 0, &lguest_cons); -} -console_initcall(cons_init); - -/*D:370 To set up and manage our virtual console, we call hvc_alloc() and - * stash the result in the private pointer of the "struct lguest_device". - * Since we never remove the console device we never need this pointer again, - * but using ->private is considered good form, and you never know who's going - * to copy your driver. - * - * Once the console is set up, we bind our input buffer ready for input. */ -static int lguestcons_probe(struct lguest_device *lgdev) -{ - int err; - - /* The first argument of hvc_alloc() is the virtual console number, so - * we use zero. The second argument is the interrupt number. - * - * The third argument is a "struct hv_ops" containing the put_chars() - * and get_chars() pointers. The final argument is the output buffer - * size: we use 256 and expect the Host to have room for us to send - * that much. */ - lgdev->private = hvc_alloc(0, lgdev_irq(lgdev), &lguest_cons, 256); - if (IS_ERR(lgdev->private)) - return PTR_ERR(lgdev->private); - - /* We bind a single DMA buffer at key LGUEST_CONSOLE_DMA_KEY. - * "cons_input" is that statically-initialized global DMA buffer we saw - * above, and we also give the interrupt we want. */ - err = lguest_bind_dma(LGUEST_CONSOLE_DMA_KEY, &cons_input, 1, - lgdev_irq(lgdev)); - if (err) - printk("lguest console: failed to bind buffer.\n"); - return err; -} -/* Note the use of lgdev_irq() for the interrupt number. We tell hvc_alloc() - * to expect input when this interrupt is triggered, and then tell - * lguest_bind_dma() that is the interrupt to send us when input comes in. */ - -/*D:360 From now on the console driver follows standard Guest driver form: - * register_lguest_driver() registers the device type and probe function, and - * the probe function sets up the device. - * - * The standard "struct lguest_driver": */ -static struct lguest_driver lguestcons_drv = { - .name = "lguestcons", - .owner = THIS_MODULE, - .device_type = LGUEST_DEVICE_T_CONSOLE, - .probe = lguestcons_probe, -}; - -/* The standard init function */ -static int __init hvc_lguest_init(void) -{ - return register_lguest_driver(&lguestcons_drv); -} -module_init(hvc_lguest_init); diff --git a/drivers/lguest/Kconfig b/drivers/lguest/Kconfig index 3ec5cc803a09..7eb9ecff8f4a 100644 --- a/drivers/lguest/Kconfig +++ b/drivers/lguest/Kconfig @@ -17,13 +17,3 @@ config LGUEST_GUEST The guest needs code built-in, even if the host has lguest support as a module. The drivers are tiny, so we build them in too. - -config LGUEST_NET - tristate - default y - depends on LGUEST_GUEST && NET - -config LGUEST_BLOCK - tristate - default y - depends on LGUEST_GUEST && BLOCK diff --git a/drivers/lguest/Makefile b/drivers/lguest/Makefile index d330f5b8c456..8c28236ee1ae 100644 --- a/drivers/lguest/Makefile +++ b/drivers/lguest/Makefile @@ -1,6 +1,3 @@ -# Guest requires the bus driver. -obj-$(CONFIG_LGUEST_GUEST) += lguest_bus.o - # Host requires the other files, which can be a module. obj-$(CONFIG_LGUEST) += lg.o lg-y = core.o hypercalls.o page_tables.o interrupts_and_traps.o \ diff --git a/drivers/lguest/lguest_bus.c b/drivers/lguest/lguest_bus.c deleted file mode 100644 index 2e9a202be44e..000000000000 --- a/drivers/lguest/lguest_bus.c +++ /dev/null @@ -1,220 +0,0 @@ -/*P:050 Lguest guests use a very simple bus for devices. It's a simple array - * of device descriptors contained just above the top of normal memory. The - * lguest bus is 80% tedious boilerplate code. :*/ -#include -#include -#include -#include -#include - -struct lguest_device_desc *lguest_devices; - -static ssize_t type_show(struct device *_dev, - struct device_attribute *attr, char *buf) -{ - struct lguest_device *dev = container_of(_dev,struct lguest_device,dev); - return sprintf(buf, "%hu", lguest_devices[dev->index].type); -} -static ssize_t features_show(struct device *_dev, - struct device_attribute *attr, char *buf) -{ - struct lguest_device *dev = container_of(_dev,struct lguest_device,dev); - return sprintf(buf, "%hx", lguest_devices[dev->index].features); -} -static ssize_t pfn_show(struct device *_dev, - struct device_attribute *attr, char *buf) -{ - struct lguest_device *dev = container_of(_dev,struct lguest_device,dev); - return sprintf(buf, "%u", lguest_devices[dev->index].pfn); -} -static ssize_t status_show(struct device *_dev, - struct device_attribute *attr, char *buf) -{ - struct lguest_device *dev = container_of(_dev,struct lguest_device,dev); - return sprintf(buf, "%hx", lguest_devices[dev->index].status); -} -static ssize_t status_store(struct device *_dev, struct device_attribute *attr, - const char *buf, size_t count) -{ - struct lguest_device *dev = container_of(_dev,struct lguest_device,dev); - if (sscanf(buf, "%hi", &lguest_devices[dev->index].status) != 1) - return -EINVAL; - return count; -} -static struct device_attribute lguest_dev_attrs[] = { - __ATTR_RO(type), - __ATTR_RO(features), - __ATTR_RO(pfn), - __ATTR(status, 0644, status_show, status_store), - __ATTR_NULL -}; - -/*D:130 The generic bus infrastructure requires a function which says whether a - * device matches a driver. For us, it is simple: "struct lguest_driver" - * contains a "device_type" field which indicates what type of device it can - * handle, so we just cast the args and compare: */ -static int lguest_dev_match(struct device *_dev, struct device_driver *_drv) -{ - struct lguest_device *dev = container_of(_dev,struct lguest_device,dev); - struct lguest_driver *drv = container_of(_drv,struct lguest_driver,drv); - - return (drv->device_type == lguest_devices[dev->index].type); -} -/*:*/ - -struct lguest_bus { - struct bus_type bus; - struct device dev; -}; - -static struct lguest_bus lguest_bus = { - .bus = { - .name = "lguest", - .match = lguest_dev_match, - .dev_attrs = lguest_dev_attrs, - }, - .dev = { - .parent = NULL, - .bus_id = "lguest", - } -}; - -/*D:140 This is the callback which occurs once the bus infrastructure matches - * up a device and driver, ie. in response to add_lguest_device() calling - * device_register(), or register_lguest_driver() calling driver_register(). - * - * At the moment it's always the latter: the devices are added first, since - * scan_devices() is called from a "core_initcall", and the drivers themselves - * called later as a normal "initcall". But it would work the other way too. - * - * So now we have the happy couple, we add the status bit to indicate that we - * found a driver. If the driver truly loves the device, it will return - * happiness from its probe function (ok, perhaps this wasn't my greatest - * analogy), and we set the final "driver ok" bit so the Host sees it's all - * green. */ -static int lguest_dev_probe(struct device *_dev) -{ - int ret; - struct lguest_device*dev = container_of(_dev,struct lguest_device,dev); - struct lguest_driver*drv = container_of(dev->dev.driver, - struct lguest_driver, drv); - - lguest_devices[dev->index].status |= LGUEST_DEVICE_S_DRIVER; - ret = drv->probe(dev); - if (ret == 0) - lguest_devices[dev->index].status |= LGUEST_DEVICE_S_DRIVER_OK; - return ret; -} - -/* The last part of the bus infrastructure is the function lguest drivers use - * to register themselves. Firstly, we do nothing if there's no lguest bus - * (ie. this is not a Guest), otherwise we fill in the embedded generic "struct - * driver" fields and call the generic driver_register(). */ -int register_lguest_driver(struct lguest_driver *drv) -{ - if (!lguest_devices) - return 0; - - drv->drv.bus = &lguest_bus.bus; - drv->drv.name = drv->name; - drv->drv.owner = drv->owner; - drv->drv.probe = lguest_dev_probe; - - return driver_register(&drv->drv); -} - -/* At the moment we build all the drivers into the kernel because they're so - * simple: 8144 bytes for all three of them as I type this. And as the console - * really needs to be built in, it's actually only 3527 bytes for the network - * and block drivers. - * - * If they get complex it will make sense for them to be modularized, so we - * need to explicitly export the symbol. - * - * I don't think non-GPL modules make sense, so it's a GPL-only export. - */ -EXPORT_SYMBOL_GPL(register_lguest_driver); - -/*D:120 This is the core of the lguest bus: actually adding a new device. - * It's a separate function because it's neater that way, and because an - * earlier version of the code supported hotplug and unplug. They were removed - * early on because they were never used. - * - * As Andrew Tridgell says, "Untested code is buggy code". - * - * It's worth reading this carefully: we start with an index into the array of - * "struct lguest_device_desc"s indicating the device which is new: */ -static void add_lguest_device(unsigned int index) -{ - struct lguest_device *new; - - /* Each "struct lguest_device_desc" has a "status" field, which the - * Guest updates as the device is probed. In the worst case, the Host - * can look at these bits to tell what part of device setup failed, - * even if the console isn't available. */ - lguest_devices[index].status |= LGUEST_DEVICE_S_ACKNOWLEDGE; - new = kmalloc(sizeof(struct lguest_device), GFP_KERNEL); - if (!new) { - printk(KERN_EMERG "Cannot allocate lguest device %u\n", index); - lguest_devices[index].status |= LGUEST_DEVICE_S_FAILED; - return; - } - - /* The "struct lguest_device" setup is pretty straight-forward example - * code. */ - new->index = index; - new->private = NULL; - memset(&new->dev, 0, sizeof(new->dev)); - new->dev.parent = &lguest_bus.dev; - new->dev.bus = &lguest_bus.bus; - sprintf(new->dev.bus_id, "%u", index); - - /* device_register() causes the bus infrastructure to look for a - * matching driver. */ - if (device_register(&new->dev) != 0) { - printk(KERN_EMERG "Cannot register lguest device %u\n", index); - lguest_devices[index].status |= LGUEST_DEVICE_S_FAILED; - kfree(new); - } -} - -/*D:110 scan_devices() simply iterates through the device array. The type 0 - * is reserved to mean "no device", and anything else means we have found a - * device: add it. */ -static void scan_devices(void) -{ - unsigned int i; - - for (i = 0; i < LGUEST_MAX_DEVICES; i++) - if (lguest_devices[i].type) - add_lguest_device(i); -} - -/*D:100 Fairly early in boot, lguest_bus_init() is called to set up the lguest - * bus. We check that we are a Guest by checking paravirt_ops.name: there are - * other ways of checking, but this seems most obvious to me. - * - * So we can access the array of "struct lguest_device_desc"s easily, we map - * that memory and store the pointer in the global "lguest_devices". Then we - * register the bus with the core. Doing two registrations seems clunky to me, - * but it seems to be the correct sysfs incantation. - * - * Finally we call scan_devices() which adds all the devices found in the - * "struct lguest_device_desc" array. */ -static int __init lguest_bus_init(void) -{ - if (strcmp(pv_info.name, "lguest") != 0) - return 0; - - /* Devices are in a single page above top of "normal" mem */ - lguest_devices = lguest_map(max_pfn< #include #include -#include #include #include #include diff --git a/drivers/net/Makefile b/drivers/net/Makefile index 6745feb690ff..593262065c9b 100644 --- a/drivers/net/Makefile +++ b/drivers/net/Makefile @@ -183,7 +183,6 @@ obj-$(CONFIG_ZORRO8390) += zorro8390.o obj-$(CONFIG_HPLANCE) += hplance.o 7990.o obj-$(CONFIG_MVME147_NET) += mvme147.o 7990.o obj-$(CONFIG_EQUALIZER) += eql.o -obj-$(CONFIG_LGUEST_NET) += lguest_net.o obj-$(CONFIG_MIPS_JAZZ_SONIC) += jazzsonic.o obj-$(CONFIG_MIPS_AU1X00_ENET) += au1000_eth.o obj-$(CONFIG_MIPS_SIM_NET) += mipsnet.o diff --git a/drivers/net/lguest_net.c b/drivers/net/lguest_net.c deleted file mode 100644 index e255476f224f..000000000000 --- a/drivers/net/lguest_net.c +++ /dev/null @@ -1,550 +0,0 @@ -/*D:500 - * The Guest network driver. - * - * This is very simple a virtual network driver, and our last Guest driver. - * The only trick is that it can talk directly to multiple other recipients - * (ie. other Guests on the same network). It can also be used with only the - * Host on the network. - :*/ - -/* Copyright 2006 Rusty Russell IBM Corporation - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -//#define DEBUG -#include -#include -#include -#include -#include -#include - -#define SHARED_SIZE PAGE_SIZE -#define MAX_LANS 4 -#define NUM_SKBS 8 - -/*M:011 Network code master Jeff Garzik points out numerous shortcomings in - * this driver if it aspires to greatness. - * - * Firstly, it doesn't use "NAPI": the networking's New API, and is poorer for - * it. As he says "NAPI means system-wide load leveling, across multiple - * network interfaces. Lack of NAPI can mean competition at higher loads." - * - * He also points out that we don't implement set_mac_address, so users cannot - * change the devices hardware address. When I asked why one would want to: - * "Bonding, and situations where you /do/ want the MAC address to "leak" out - * of the host onto the wider net." - * - * Finally, he would like module unloading: "It is not unrealistic to think of - * [un|re|]loading the net support module in an lguest guest. And, adding - * module support makes the programmer more responsible, because they now have - * to learn to clean up after themselves. Any driver that cannot clean up - * after itself is an incomplete driver in my book." - :*/ - -/*D:530 The "struct lguestnet_info" contains all the information we need to - * know about the network device. */ -struct lguestnet_info -{ - /* The mapped device page(s) (an array of "struct lguest_net"). */ - struct lguest_net *peer; - /* The physical address of the device page(s) */ - unsigned long peer_phys; - /* The size of the device page(s). */ - unsigned long mapsize; - - /* The lguest_device I come from */ - struct lguest_device *lgdev; - - /* My peerid (ie. my slot in the array). */ - unsigned int me; - - /* Receive queue: the network packets waiting to be filled. */ - struct sk_buff *skb[NUM_SKBS]; - struct lguest_dma dma[NUM_SKBS]; -}; -/*:*/ - -/* How many bytes left in this page. */ -static unsigned int rest_of_page(void *data) -{ - return PAGE_SIZE - ((unsigned long)data % PAGE_SIZE); -} - -/*D:570 Each peer (ie. Guest or Host) on the network binds their receive - * buffers to a different key: we simply use the physical address of the - * device's memory page plus the peer number. The Host insists that all keys - * be a multiple of 4, so we multiply the peer number by 4. */ -static unsigned long peer_key(struct lguestnet_info *info, unsigned peernum) -{ - return info->peer_phys + 4 * peernum; -} - -/* This is the routine which sets up a "struct lguest_dma" to point to a - * network packet, similar to req_to_dma() in lguest_blk.c. The structure of a - * "struct sk_buff" has grown complex over the years: it consists of a "head" - * linear section pointed to by "skb->data", and possibly an array of - * "fragments" in the case of a non-linear packet. - * - * Our receive buffers don't use fragments at all but outgoing skbs might, so - * we handle it. */ -static void skb_to_dma(const struct sk_buff *skb, unsigned int headlen, - struct lguest_dma *dma) -{ - unsigned int i, seg; - - /* First, we put the linear region into the "struct lguest_dma". Each - * entry can't go over a page boundary, so even though all our packets - * are 1514 bytes or less, we might need to use two entries here: */ - for (i = seg = 0; i < headlen; seg++, i += rest_of_page(skb->data+i)) { - dma->addr[seg] = virt_to_phys(skb->data + i); - dma->len[seg] = min((unsigned)(headlen - i), - rest_of_page(skb->data + i)); - } - - /* Now we handle the fragments: at least they're guaranteed not to go - * over a page. skb_shinfo(skb) returns a pointer to the structure - * which tells us about the number of fragments and the fragment - * array. */ - for (i = 0; i < skb_shinfo(skb)->nr_frags; i++, seg++) { - const skb_frag_t *f = &skb_shinfo(skb)->frags[i]; - /* Should not happen with MTU less than 64k - 2 * PAGE_SIZE. */ - if (seg == LGUEST_MAX_DMA_SECTIONS) { - /* We will end up sending a truncated packet should - * this ever happen. Plus, a cool log message! */ - printk("Woah dude! Megapacket!\n"); - break; - } - dma->addr[seg] = page_to_phys(f->page) + f->page_offset; - dma->len[seg] = f->size; - } - - /* If after all that we didn't use the entire "struct lguest_dma" - * array, we terminate it with a 0 length. */ - if (seg < LGUEST_MAX_DMA_SECTIONS) - dma->len[seg] = 0; -} - -/* - * Packet transmission. - * - * Our packet transmission is a little unusual. A real network card would just - * send out the packet and leave the receivers to decide if they're interested. - * Instead, we look through the network device memory page and see if any of - * the ethernet addresses match the packet destination, and if so we send it to - * that Guest. - * - * This is made a little more complicated in two cases. The first case is - * broadcast packets: for that we send the packet to all Guests on the network, - * one at a time. The second case is "promiscuous" mode, where a Guest wants - * to see all the packets on the network. We need a way for the Guest to tell - * us it wants to see all packets, so it sets the "multicast" bit on its - * published MAC address, which is never valid in a real ethernet address. - */ -#define PROMISC_BIT 0x01 - -/* This is the callback which is summoned whenever the network device's - * multicast or promiscuous state changes. If the card is in promiscuous mode, - * we advertise that in our ethernet address in the device's memory. We do the - * same if Linux wants any or all multicast traffic. */ -static void lguestnet_set_multicast(struct net_device *dev) -{ - struct lguestnet_info *info = netdev_priv(dev); - - if ((dev->flags & (IFF_PROMISC|IFF_ALLMULTI)) || dev->mc_count) - info->peer[info->me].mac[0] |= PROMISC_BIT; - else - info->peer[info->me].mac[0] &= ~PROMISC_BIT; -} - -/* A simple test function to see if a peer wants to see all packets.*/ -static int promisc(struct lguestnet_info *info, unsigned int peer) -{ - return info->peer[peer].mac[0] & PROMISC_BIT; -} - -/* Another simple function to see if a peer's advertised ethernet address - * matches a packet's destination ethernet address. */ -static int mac_eq(const unsigned char mac[ETH_ALEN], - struct lguestnet_info *info, unsigned int peer) -{ - /* Ignore multicast bit, which peer turns on to mean promisc. */ - if ((info->peer[peer].mac[0] & (~PROMISC_BIT)) != mac[0]) - return 0; - return memcmp(mac+1, info->peer[peer].mac+1, ETH_ALEN-1) == 0; -} - -/* This is the function which actually sends a packet once we've decided a - * peer wants it: */ -static void transfer_packet(struct net_device *dev, - struct sk_buff *skb, - unsigned int peernum) -{ - struct lguestnet_info *info = netdev_priv(dev); - struct lguest_dma dma; - - /* We use our handy "struct lguest_dma" packing function to prepare - * the skb for sending. */ - skb_to_dma(skb, skb_headlen(skb), &dma); - pr_debug("xfer length %04x (%u)\n", htons(skb->len), skb->len); - - /* This is the actual send call which copies the packet. */ - lguest_send_dma(peer_key(info, peernum), &dma); - - /* Check that the entire packet was transmitted. If not, it could mean - * that the other Guest registered a short receive buffer, but this - * driver should never do that. More likely, the peer is dead. */ - if (dma.used_len != skb->len) { - dev->stats.tx_carrier_errors++; - pr_debug("Bad xfer to peer %i: %i of %i (dma %p/%i)\n", - peernum, dma.used_len, skb->len, - (void *)dma.addr[0], dma.len[0]); - } else { - /* On success we update the stats. */ - dev->stats.tx_bytes += skb->len; - dev->stats.tx_packets++; - } -} - -/* Another helper function to tell is if a slot in the device memory is unused. - * Since we always set the Local Assignment bit in the ethernet address, the - * first byte can never be 0. */ -static int unused_peer(const struct lguest_net peer[], unsigned int num) -{ - return peer[num].mac[0] == 0; -} - -/* Finally, here is the routine which handles an outgoing packet. It's called - * "start_xmit" for traditional reasons. */ -static int lguestnet_start_xmit(struct sk_buff *skb, struct net_device *dev) -{ - unsigned int i; - int broadcast; - struct lguestnet_info *info = netdev_priv(dev); - /* Extract the destination ethernet address from the packet. */ - const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest; - DECLARE_MAC_BUF(mac); - - pr_debug("%s: xmit %s\n", dev->name, print_mac(mac, dest)); - - /* If it's a multicast packet, we broadcast to everyone. That's not - * very efficient, but there are very few applications which actually - * use multicast, which is a shame really. - * - * As etherdevice.h points out: "By definition the broadcast address is - * also a multicast address." So we don't have to test for broadcast - * packets separately. */ - broadcast = is_multicast_ether_addr(dest); - - /* Look through all the published ethernet addresses to see if we - * should send this packet. */ - for (i = 0; i < info->mapsize/sizeof(struct lguest_net); i++) { - /* We don't send to ourselves (we actually can't SEND_DMA to - * ourselves anyway), and don't send to unused slots.*/ - if (i == info->me || unused_peer(info->peer, i)) - continue; - - /* If it's broadcast we send it. If they want every packet we - * send it. If the destination matches their address we send - * it. Otherwise we go to the next peer. */ - if (!broadcast && !promisc(info, i) && !mac_eq(dest, info, i)) - continue; - - pr_debug("lguestnet %s: sending from %i to %i\n", - dev->name, info->me, i); - /* Our routine which actually does the transfer. */ - transfer_packet(dev, skb, i); - } - - /* An xmit routine is expected to dispose of the packet, so we do. */ - dev_kfree_skb(skb); - - /* As per kernel convention, 0 means success. This is why I love - * networking: even if we never sent to anyone, that's still - * success! */ - return 0; -} - -/*D:560 - * Packet receiving. - * - * First, here's a helper routine which fills one of our array of receive - * buffers: */ -static int fill_slot(struct net_device *dev, unsigned int slot) -{ - struct lguestnet_info *info = netdev_priv(dev); - - /* We can receive ETH_DATA_LEN (1500) byte packets, plus a standard - * ethernet header of ETH_HLEN (14) bytes. */ - info->skb[slot] = netdev_alloc_skb(dev, ETH_HLEN + ETH_DATA_LEN); - if (!info->skb[slot]) { - printk("%s: could not fill slot %i\n", dev->name, slot); - return -ENOMEM; - } - - /* skb_to_dma() is a helper which sets up the "struct lguest_dma" to - * point to the data in the skb: we also use it for sending out a - * packet. */ - skb_to_dma(info->skb[slot], ETH_HLEN + ETH_DATA_LEN, &info->dma[slot]); - - /* This is a Write Memory Barrier: it ensures that the entry in the - * receive buffer array is written *before* we set the "used_len" entry - * to 0. If the Host were looking at the receive buffer array from a - * different CPU, it could potentially see "used_len = 0" and not see - * the updated receive buffer information. This would be a horribly - * nasty bug, so make sure the compiler and CPU know this has to happen - * first. */ - wmb(); - /* Writing 0 to "used_len" tells the Host it can use this receive - * buffer now. */ - info->dma[slot].used_len = 0; - return 0; -} - -/* This is the actual receive routine. When we receive an interrupt from the - * Host to tell us a packet has been delivered, we arrive here: */ -static irqreturn_t lguestnet_rcv(int irq, void *dev_id) -{ - struct net_device *dev = dev_id; - struct lguestnet_info *info = netdev_priv(dev); - unsigned int i, done = 0; - - /* Look through our entire receive array for an entry which has data - * in it. */ - for (i = 0; i < ARRAY_SIZE(info->dma); i++) { - unsigned int length; - struct sk_buff *skb; - - length = info->dma[i].used_len; - if (length == 0) - continue; - - /* We've found one! Remember the skb (we grabbed the length - * above), and immediately refill the slot we've taken it - * from. */ - done++; - skb = info->skb[i]; - fill_slot(dev, i); - - /* This shouldn't happen: micropackets could be sent by a - * badly-behaved Guest on the network, but the Host will never - * stuff more data in the buffer than the buffer length. */ - if (length < ETH_HLEN || length > ETH_HLEN + ETH_DATA_LEN) { - pr_debug(KERN_WARNING "%s: unbelievable skb len: %i\n", - dev->name, length); - dev_kfree_skb(skb); - continue; - } - - /* skb_put(), what a great function! I've ranted about this - * function before (http://lkml.org/lkml/1999/9/26/24). You - * call it after you've added data to the end of an skb (in - * this case, it was the Host which wrote the data). */ - skb_put(skb, length); - - /* The ethernet header contains a protocol field: we use the - * standard helper to extract it, and place the result in - * skb->protocol. The helper also sets up skb->pkt_type and - * eats up the ethernet header from the front of the packet. */ - skb->protocol = eth_type_trans(skb, dev); - - /* If this device doesn't need checksums for sending, we also - * don't need to check the packets when they come in. */ - if (dev->features & NETIF_F_NO_CSUM) - skb->ip_summed = CHECKSUM_UNNECESSARY; - - /* As a last resort for debugging the driver or the lguest I/O - * subsystem, you can uncomment the "#define DEBUG" at the top - * of this file, which turns all the pr_debug() into printk() - * and floods the logs. */ - pr_debug("Receiving skb proto 0x%04x len %i type %i\n", - ntohs(skb->protocol), skb->len, skb->pkt_type); - - /* Update the packet and byte counts (visible from ifconfig, - * and good for debugging). */ - dev->stats.rx_bytes += skb->len; - dev->stats.rx_packets++; - - /* Hand our fresh network packet into the stack's "network - * interface receive" routine. That will free the packet - * itself when it's finished. */ - netif_rx(skb); - } - - /* If we found any packets, we assume the interrupt was for us. */ - return done ? IRQ_HANDLED : IRQ_NONE; -} - -/*D:550 This is where we start: when the device is brought up by dhcpd or - * ifconfig. At this point we advertise our MAC address to the rest of the - * network, and register receive buffers ready for incoming packets. */ -static int lguestnet_open(struct net_device *dev) -{ - int i; - struct lguestnet_info *info = netdev_priv(dev); - - /* Copy our MAC address into the device page, so others on the network - * can find us. */ - memcpy(info->peer[info->me].mac, dev->dev_addr, ETH_ALEN); - - /* We might already be in promisc mode (dev->flags & IFF_PROMISC). Our - * set_multicast callback handles this already, so we call it now. */ - lguestnet_set_multicast(dev); - - /* Allocate packets and put them into our "struct lguest_dma" array. - * If we fail to allocate all the packets we could still limp along, - * but it's a sign of real stress so we should probably give up now. */ - for (i = 0; i < ARRAY_SIZE(info->dma); i++) { - if (fill_slot(dev, i) != 0) - goto cleanup; - } - - /* Finally we tell the Host where our array of "struct lguest_dma" - * receive buffers is, binding it to the key corresponding to the - * device's physical memory plus our peerid. */ - if (lguest_bind_dma(peer_key(info,info->me), info->dma, - NUM_SKBS, lgdev_irq(info->lgdev)) != 0) - goto cleanup; - return 0; - -cleanup: - while (--i >= 0) - dev_kfree_skb(info->skb[i]); - return -ENOMEM; -} -/*:*/ - -/* The close routine is called when the device is no longer in use: we clean up - * elegantly. */ -static int lguestnet_close(struct net_device *dev) -{ - unsigned int i; - struct lguestnet_info *info = netdev_priv(dev); - - /* Clear all trace of our existence out of the device memory by setting - * the slot which held our MAC address to 0 (unused). */ - memset(&info->peer[info->me], 0, sizeof(info->peer[info->me])); - - /* Unregister our array of receive buffers */ - lguest_unbind_dma(peer_key(info, info->me), info->dma); - for (i = 0; i < ARRAY_SIZE(info->dma); i++) - dev_kfree_skb(info->skb[i]); - return 0; -} - -/*D:510 The network device probe function is basically a standard ethernet - * device setup. It reads the "struct lguest_device_desc" and sets the "struct - * net_device". Oh, the line-by-line excitement! Let's skip over it. :*/ -static int lguestnet_probe(struct lguest_device *lgdev) -{ - int err, irqf = IRQF_SHARED; - struct net_device *dev; - struct lguestnet_info *info; - struct lguest_device_desc *desc = &lguest_devices[lgdev->index]; - - pr_debug("lguest_net: probing for device %i\n", lgdev->index); - - dev = alloc_etherdev(sizeof(struct lguestnet_info)); - if (!dev) - return -ENOMEM; - - /* Ethernet defaults with some changes */ - ether_setup(dev); - dev->set_mac_address = NULL; - random_ether_addr(dev->dev_addr); - - dev->open = lguestnet_open; - dev->stop = lguestnet_close; - dev->hard_start_xmit = lguestnet_start_xmit; - - /* We don't actually support multicast yet, but turning on/off - * promisc also calls dev->set_multicast_list. */ - dev->set_multicast_list = lguestnet_set_multicast; - SET_NETDEV_DEV(dev, &lgdev->dev); - - /* The network code complains if you have "scatter-gather" capability - * if you don't also handle checksums (it seem that would be - * "illogical"). So we use a lie of omission and don't tell it that we - * can handle scattered packets unless we also don't want checksums, - * even though to us they're completely independent. */ - if (desc->features & LGUEST_NET_F_NOCSUM) - dev->features = NETIF_F_SG|NETIF_F_NO_CSUM; - - info = netdev_priv(dev); - info->mapsize = PAGE_SIZE * desc->num_pages; - info->peer_phys = ((unsigned long)desc->pfn << PAGE_SHIFT); - info->lgdev = lgdev; - info->peer = lguest_map(info->peer_phys, desc->num_pages); - if (!info->peer) { - err = -ENOMEM; - goto free; - } - - /* This stores our peerid (upper bits reserved for future). */ - info->me = (desc->features & (info->mapsize-1)); - - err = register_netdev(dev); - if (err) { - pr_debug("lguestnet: registering device failed\n"); - goto unmap; - } - - if (lguest_devices[lgdev->index].features & LGUEST_DEVICE_F_RANDOMNESS) - irqf |= IRQF_SAMPLE_RANDOM; - if (request_irq(lgdev_irq(lgdev), lguestnet_rcv, irqf, "lguestnet", - dev) != 0) { - pr_debug("lguestnet: cannot get irq %i\n", lgdev_irq(lgdev)); - goto unregister; - } - - pr_debug("lguestnet: registered device %s\n", dev->name); - /* Finally, we put the "struct net_device" in the generic "struct - * lguest_device"s private pointer. Again, it's not necessary, but - * makes sure the cool kernel kids don't tease us. */ - lgdev->private = dev; - return 0; - -unregister: - unregister_netdev(dev); -unmap: - lguest_unmap(info->peer); -free: - free_netdev(dev); - return err; -} - -static struct lguest_driver lguestnet_drv = { - .name = "lguestnet", - .owner = THIS_MODULE, - .device_type = LGUEST_DEVICE_T_NET, - .probe = lguestnet_probe, -}; - -static __init int lguestnet_init(void) -{ - return register_lguest_driver(&lguestnet_drv); -} -module_init(lguestnet_init); - -MODULE_DESCRIPTION("Lguest network driver"); -MODULE_LICENSE("GPL"); - -/*D:580 - * This is the last of the Drivers, and with this we have covered the many and - * wonderous and fine (and boring) details of the Guest. - * - * "make Launcher" beckons, where we answer questions like "Where do Guests - * come from?", and "What do you do when someone asks for optimization?" - */ diff --git a/include/linux/lguest_bus.h b/include/linux/lguest_bus.h deleted file mode 100644 index d27853ddc644..000000000000 --- a/include/linux/lguest_bus.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef _ASM_LGUEST_DEVICE_H -#define _ASM_LGUEST_DEVICE_H -/* Everything you need to know about lguest devices. */ -#include -#include -#include - -struct lguest_device { - /* Unique busid, and index into lguest_page->devices[] */ - unsigned int index; - - struct device dev; - - /* Driver can hang data off here. */ - void *private; -}; - -/*D:380 Since interrupt numbers are arbitrary, we use a convention: each device - * can use the interrupt number corresponding to its index. The +1 is because - * interrupt 0 is not usable (it's actually the timer interrupt). */ -static inline int lgdev_irq(const struct lguest_device *dev) -{ - return dev->index + 1; -} -/*:*/ - -/* dma args must not be vmalloced! */ -void lguest_send_dma(unsigned long key, struct lguest_dma *dma); -int lguest_bind_dma(unsigned long key, struct lguest_dma *dmas, - unsigned int num, u8 irq); -void lguest_unbind_dma(unsigned long key, struct lguest_dma *dmas); - -/* Map the virtual device space */ -void *lguest_map(unsigned long phys_addr, unsigned long pages); -void lguest_unmap(void *); - -struct lguest_driver { - const char *name; - struct module *owner; - u16 device_type; - int (*probe)(struct lguest_device *dev); - void (*remove)(struct lguest_device *dev); - - struct device_driver drv; -}; - -extern int register_lguest_driver(struct lguest_driver *drv); -extern void unregister_lguest_driver(struct lguest_driver *drv); - -extern struct lguest_device_desc *lguest_devices; /* Just past max_pfn */ -#endif /* _ASM_LGUEST_DEVICE_H */ diff --git a/include/linux/lguest_launcher.h b/include/linux/lguest_launcher.h index 736e19a510c1..b6603f3fbff8 100644 --- a/include/linux/lguest_launcher.h +++ b/include/linux/lguest_launcher.h @@ -44,32 +44,6 @@ struct lguest_dma }; /*:*/ -/*D:460 This is the layout of a block device memory page. The Launcher sets up - * the num_sectors initially to tell the Guest the size of the disk. The Guest - * puts the type, sector and length of the request in the first three fields, - * then DMAs to the Host. The Host processes the request, sets up the result, - * then DMAs back to the Guest. */ -struct lguest_block_page -{ - /* 0 is a read, 1 is a write. */ - int type; - __u32 sector; /* Offset in device = sector * 512. */ - __u32 bytes; /* Length expected to be read/written in bytes */ - /* 0 = pending, 1 = done, 2 = done, error */ - int result; - __u32 num_sectors; /* Disk length = num_sectors * 512 */ -}; - -/*D:520 The network device is basically a memory page where all the Guests on - * the network publish their MAC (ethernet) addresses: it's an array of "struct - * lguest_net": */ -struct lguest_net -{ - /* Simply the mac address (with multicast bit meaning promisc). */ - unsigned char mac[6]; -}; -/*:*/ - /* Where the Host expects the Guest to SEND_DMA console output to. */ #define LGUEST_CONSOLE_DMA_KEY 0 -- cgit v1.2.3-71-gd317 From 15045275c32bf6d15d32c2eca8157be9c0ba6e45 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 11:24:10 +1000 Subject: Remove old lguest I/O infrrasructure. This patch gets rid of the old lguest host I/O infrastructure and replaces it with a single hypercall "LHCALL_NOTIFY" which takes an address. The main change is the removal of io.c: that mainly did inter-guest I/O, which virtio doesn't yet support. Signed-off-by: Rusty Russell --- drivers/lguest/Makefile | 2 +- drivers/lguest/core.c | 12 +- drivers/lguest/hypercalls.c | 26 +- drivers/lguest/io.c | 628 ---------------------------------------- drivers/lguest/lg.h | 27 +- drivers/lguest/lguest_user.c | 39 +-- include/asm-x86/lguest_hcall.h | 3 +- include/linux/lguest_launcher.h | 36 +-- 8 files changed, 21 insertions(+), 752 deletions(-) delete mode 100644 drivers/lguest/io.c (limited to 'include/linux') diff --git a/drivers/lguest/Makefile b/drivers/lguest/Makefile index 8c28236ee1ae..a63f75dc41a1 100644 --- a/drivers/lguest/Makefile +++ b/drivers/lguest/Makefile @@ -1,7 +1,7 @@ # Host requires the other files, which can be a module. obj-$(CONFIG_LGUEST) += lg.o lg-y = core.o hypercalls.o page_tables.o interrupts_and_traps.o \ - segments.o io.o lguest_user.o + segments.o lguest_user.o lg-$(CONFIG_X86_32) += x86/switcher_32.o x86/core.o diff --git a/drivers/lguest/core.c b/drivers/lguest/core.c index 41b26e592d38..3aec29ec7715 100644 --- a/drivers/lguest/core.c +++ b/drivers/lguest/core.c @@ -202,13 +202,12 @@ int run_guest(struct lguest *lg, unsigned long __user *user) if (lg->hcall) do_hypercalls(lg); - /* It's possible the Guest did a SEND_DMA hypercall to the + /* It's possible the Guest did a NOTIFY hypercall to the * Launcher, in which case we return from the read() now. */ - if (lg->dma_is_pending) { - if (put_user(lg->pending_dma, user) || - put_user(lg->pending_key, user+1)) + if (lg->pending_notify) { + if (put_user(lg->pending_notify, user)) return -EFAULT; - return sizeof(unsigned long)*2; + return sizeof(lg->pending_notify); } /* Check for signals */ @@ -288,9 +287,6 @@ static int __init init(void) if (err) goto unmap; - /* The I/O subsystem needs some things initialized. */ - lguest_io_init(); - /* We might need to reserve an interrupt vector. */ err = init_interrupts(); if (err) diff --git a/drivers/lguest/hypercalls.c b/drivers/lguest/hypercalls.c index 13b5f2f813de..3a53788ba450 100644 --- a/drivers/lguest/hypercalls.c +++ b/drivers/lguest/hypercalls.c @@ -60,22 +60,9 @@ static void do_hcall(struct lguest *lg, struct hcall_args *args) else guest_pagetable_flush_user(lg); break; - case LHCALL_BIND_DMA: - /* BIND_DMA really wants four arguments, but it's the only call - * which does. So the Guest packs the number of buffers and - * the interrupt number into the final argument, and we decode - * it here. This can legitimately fail, since we currently - * place a limit on the number of DMA pools a Guest can have. - * So we return true or false from this call. */ - args->arg0 = bind_dma(lg, args->arg1, args->arg2, - args->arg3 >> 8, args->arg3 & 0xFF); - break; /* All these calls simply pass the arguments through to the right * routines. */ - case LHCALL_SEND_DMA: - send_dma(lg, args->arg1, args->arg2); - break; case LHCALL_NEW_PGTABLE: guest_new_pagetable(lg, args->arg1); break; @@ -99,6 +86,9 @@ static void do_hcall(struct lguest *lg, struct hcall_args *args) /* Similarly, this sets the halted flag for run_guest(). */ lg->halted = 1; break; + case LHCALL_NOTIFY: + lg->pending_notify = args->arg1; + break; default: if (lguest_arch_do_hcall(lg, args)) kill_guest(lg, "Bad hypercall %li\n", args->arg0); @@ -156,9 +146,9 @@ static void do_async_hcalls(struct lguest *lg) break; } - /* Stop doing hypercalls if we've just done a DMA to the - * Launcher: it needs to service this first. */ - if (lg->dma_is_pending) + /* Stop doing hypercalls if they want to notify the Launcher: + * it needs to service this first. */ + if (lg->pending_notify) break; } } @@ -220,9 +210,9 @@ void do_hypercalls(struct lguest *lg) do_async_hcalls(lg); /* If we stopped reading the hypercall ring because the Guest did a - * SEND_DMA to the Launcher, we want to return now. Otherwise we do + * NOTIFY to the Launcher, we want to return now. Otherwise we do * the hypercall. */ - if (!lg->dma_is_pending) { + if (!lg->pending_notify) { do_hcall(lg, lg->hcall); /* Tricky point: we reset the hcall pointer to mark the * hypercall as "done". We use the hcall pointer rather than diff --git a/drivers/lguest/io.c b/drivers/lguest/io.c deleted file mode 100644 index 0e842e9caf68..000000000000 --- a/drivers/lguest/io.c +++ /dev/null @@ -1,628 +0,0 @@ -/*P:300 The I/O mechanism in lguest is simple yet flexible, allowing the Guest - * to talk to the Launcher or directly to another Guest. It uses familiar - * concepts of DMA and interrupts, plus some neat code stolen from - * futexes... :*/ - -/* Copyright (C) 2006 Rusty Russell IBM Corporation - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ -#include -#include -#include -#include -#include -#include -#include "lg.h" - -/*L:300 - * I/O - * - * Getting data in and out of the Guest is quite an art. There are numerous - * ways to do it, and they all suck differently. We try to keep things fairly - * close to "real" hardware so our Guest's drivers don't look like an alien - * visitation in the middle of the Linux code, and yet make sure that Guests - * can talk directly to other Guests, not just the Launcher. - * - * To do this, the Guest gives us a key when it binds or sends DMA buffers. - * The key corresponds to a "physical" address inside the Guest (ie. a virtual - * address inside the Launcher process). We don't, however, use this key - * directly. - * - * We want Guests which share memory to be able to DMA to each other: two - * Launchers can mmap memory the same file, then the Guests can communicate. - * Fortunately, the futex code provides us with a way to get a "union - * futex_key" corresponding to the memory lying at a virtual address: if the - * two processes share memory, the "union futex_key" for that memory will match - * even if the memory is mapped at different addresses in each. So we always - * convert the keys to "union futex_key"s to compare them. - * - * Before we dive into this though, we need to look at another set of helper - * routines used throughout the Host kernel code to access Guest memory. - :*/ -static struct list_head dma_hash[61]; - -/* An unfortunate side effect of the Linux double-linked list implementation is - * that there's no good way to statically initialize an array of linked - * lists. */ -void lguest_io_init(void) -{ - unsigned int i; - - for (i = 0; i < ARRAY_SIZE(dma_hash); i++) - INIT_LIST_HEAD(&dma_hash[i]); -} - -/* FIXME: allow multi-page lengths. */ -static int check_dma_list(struct lguest *lg, const struct lguest_dma *dma) -{ - unsigned int i; - - for (i = 0; i < LGUEST_MAX_DMA_SECTIONS; i++) { - if (!dma->len[i]) - return 1; - if (!lguest_address_ok(lg, dma->addr[i], dma->len[i])) - goto kill; - if (dma->len[i] > PAGE_SIZE) - goto kill; - /* We could do over a page, but is it worth it? */ - if ((dma->addr[i] % PAGE_SIZE) + dma->len[i] > PAGE_SIZE) - goto kill; - } - return 1; - -kill: - kill_guest(lg, "bad DMA entry: %u@%#lx", dma->len[i], dma->addr[i]); - return 0; -} - -/*L:330 This is our hash function, using the wonderful Jenkins hash. - * - * The futex key is a union with three parts: an unsigned long word, a pointer, - * and an int "offset". We could use jhash_2words() which takes three u32s. - * (Ok, the hash functions are great: the naming sucks though). - * - * It's nice to be portable to 64-bit platforms, so we use the more generic - * jhash2(), which takes an array of u32, the number of u32s, and an initial - * u32 to roll in. This is uglier, but breaks down to almost the same code on - * 32-bit platforms like this one. - * - * We want a position in the array, so we modulo ARRAY_SIZE(dma_hash) (ie. 61). - */ -static unsigned int hash(const union futex_key *key) -{ - return jhash2((u32*)&key->both.word, - (sizeof(key->both.word)+sizeof(key->both.ptr))/4, - key->both.offset) - % ARRAY_SIZE(dma_hash); -} - -/* This is a convenience routine to compare two keys. It's a much bemoaned C - * weakness that it doesn't allow '==' on structures or unions, so we have to - * open-code it like this. */ -static inline int key_eq(const union futex_key *a, const union futex_key *b) -{ - return (a->both.word == b->both.word - && a->both.ptr == b->both.ptr - && a->both.offset == b->both.offset); -} - -/*L:360 OK, when we need to actually free up a Guest's DMA array we do several - * things, so we have a convenient function to do it. - * - * The caller must hold a read lock on dmainfo owner's current->mm->mmap_sem - * for the drop_futex_key_refs(). */ -static void unlink_dma(struct lguest_dma_info *dmainfo) -{ - /* You locked this too, right? */ - BUG_ON(!mutex_is_locked(&lguest_lock)); - /* This is how we know that the entry is free. */ - dmainfo->interrupt = 0; - /* Remove it from the hash table. */ - list_del(&dmainfo->list); - /* Drop the references we were holding (to the inode or mm). */ - drop_futex_key_refs(&dmainfo->key); -} - -/*L:350 This is the routine which we call when the Guest asks to unregister a - * DMA array attached to a given key. Returns true if the array was found. */ -static int unbind_dma(struct lguest *lg, - const union futex_key *key, - unsigned long dmas) -{ - int i, ret = 0; - - /* We don't bother with the hash table, just look through all this - * Guest's DMA arrays. */ - for (i = 0; i < LGUEST_MAX_DMA; i++) { - /* In theory it could have more than one array on the same key, - * or one array on multiple keys, so we check both */ - if (key_eq(key, &lg->dma[i].key) && dmas == lg->dma[i].dmas) { - unlink_dma(&lg->dma[i]); - ret = 1; - break; - } - } - return ret; -} - -/*L:340 BIND_DMA: this is the hypercall which sets up an array of "struct - * lguest_dma" for receiving I/O. - * - * The Guest wants to bind an array of "struct lguest_dma"s to a particular key - * to receive input. This only happens when the Guest is setting up a new - * device, so it doesn't have to be very fast. - * - * It returns 1 on a successful registration (it can fail if we hit the limit - * of registrations for this Guest). - */ -int bind_dma(struct lguest *lg, - unsigned long ukey, unsigned long dmas, u16 numdmas, u8 interrupt) -{ - unsigned int i; - int ret = 0; - union futex_key key; - /* Futex code needs the mmap_sem. */ - struct rw_semaphore *fshared = ¤t->mm->mmap_sem; - - /* Invalid interrupt? (We could kill the guest here). */ - if (interrupt >= LGUEST_IRQS) - return 0; - - /* We need to grab the Big Lguest Lock, because other Guests may be - * trying to look through this Guest's DMAs to send something while - * we're doing this. */ - mutex_lock(&lguest_lock); - down_read(fshared); - if (get_futex_key(lg->mem_base + ukey, fshared, &key) != 0) { - kill_guest(lg, "bad dma key %#lx", ukey); - goto unlock; - } - - /* We want to keep this key valid once we drop mmap_sem, so we have to - * hold a reference. */ - get_futex_key_refs(&key); - - /* If the Guest specified an interrupt of 0, that means they want to - * unregister this array of "struct lguest_dma"s. */ - if (interrupt == 0) - ret = unbind_dma(lg, &key, dmas); - else { - /* Look through this Guest's dma array for an unused entry. */ - for (i = 0; i < LGUEST_MAX_DMA; i++) { - /* If the interrupt is non-zero, the entry is already - * used. */ - if (lg->dma[i].interrupt) - continue; - - /* OK, a free one! Fill on our details. */ - lg->dma[i].dmas = dmas; - lg->dma[i].num_dmas = numdmas; - lg->dma[i].next_dma = 0; - lg->dma[i].key = key; - lg->dma[i].owner = lg; - lg->dma[i].interrupt = interrupt; - - /* Now we add it to the hash table: the position - * depends on the futex key that we got. */ - list_add(&lg->dma[i].list, &dma_hash[hash(&key)]); - /* Success! */ - ret = 1; - goto unlock; - } - } - /* If we didn't find a slot to put the key in, drop the reference - * again. */ - drop_futex_key_refs(&key); -unlock: - /* Unlock and out. */ - up_read(fshared); - mutex_unlock(&lguest_lock); - return ret; -} - -/*L:385 Note that our routines to access a different Guest's memory are called - * lgread_other() and lgwrite_other(): these names emphasize that they are only - * used when the Guest is *not* the current Guest. - * - * The interface for copying from another process's memory is called - * access_process_vm(), with a final argument of 0 for a read, and 1 for a - * write. - * - * We need lgread_other() to read the destination Guest's "struct lguest_dma" - * array. */ -static int lgread_other(struct lguest *lg, - void *buf, u32 addr, unsigned bytes) -{ - if (!lguest_address_ok(lg, addr, bytes) - || access_process_vm(lg->tsk, (unsigned long)lg->mem_base + addr, - buf, bytes, 0) != bytes) { - memset(buf, 0, bytes); - kill_guest(lg, "bad address in registered DMA struct"); - return 0; - } - return 1; -} - -/* "lgwrite()" to another Guest: used to update the destination "used_len" once - * we've transferred data into the buffer. */ -static int lgwrite_other(struct lguest *lg, u32 addr, - const void *buf, unsigned bytes) -{ - if (!lguest_address_ok(lg, addr, bytes) - || access_process_vm(lg->tsk, (unsigned long)lg->mem_base + addr, - (void *)buf, bytes, 1) != bytes) { - kill_guest(lg, "bad address writing to registered DMA"); - return 0; - } - return 1; -} - -/*L:400 This is the generic engine which copies from a source "struct - * lguest_dma" from this Guest into another Guest's "struct lguest_dma". The - * destination Guest's pages have already been mapped, as contained in the - * pages array. - * - * If you're wondering if there's a nice "copy from one process to another" - * routine, so was I. But Linux isn't really set up to copy between two - * unrelated processes, so we have to write it ourselves. - */ -static u32 copy_data(struct lguest *srclg, - const struct lguest_dma *src, - const struct lguest_dma *dst, - struct page *pages[]) -{ - unsigned int totlen, si, di, srcoff, dstoff; - void *maddr = NULL; - - /* We return the total length transferred. */ - totlen = 0; - - /* We keep indexes into the source and destination "struct lguest_dma", - * and an offset within each region. */ - si = di = 0; - srcoff = dstoff = 0; - - /* We loop until the source or destination is exhausted. */ - while (si < LGUEST_MAX_DMA_SECTIONS && src->len[si] - && di < LGUEST_MAX_DMA_SECTIONS && dst->len[di]) { - /* We can only transfer the rest of the src buffer, or as much - * as will fit into the destination buffer. */ - u32 len = min(src->len[si] - srcoff, dst->len[di] - dstoff); - - /* For systems using "highmem" we need to use kmap() to access - * the page we want. We often use the same page over and over, - * so rather than kmap() it on every loop, we set the maddr - * pointer to NULL when we need to move to the next - * destination page. */ - if (!maddr) - maddr = kmap(pages[di]); - - /* Copy directly from (this Guest's) source address to the - * destination Guest's kmap()ed buffer. Note that maddr points - * to the start of the page: we need to add the offset of the - * destination address and offset within the buffer. */ - - /* FIXME: This is not completely portable. I looked at - * copy_to_user_page(), and some arch's seem to need special - * flushes. x86 is fine. */ - if (copy_from_user(maddr + (dst->addr[di] + dstoff)%PAGE_SIZE, - srclg->mem_base+src->addr[si], len) != 0) { - /* If a copy failed, it's the source's fault. */ - kill_guest(srclg, "bad address in sending DMA"); - totlen = 0; - break; - } - - /* Increment the total and src & dst offsets */ - totlen += len; - srcoff += len; - dstoff += len; - - /* Presumably we reached the end of the src or dest buffers: */ - if (srcoff == src->len[si]) { - /* Move to the next buffer at offset 0 */ - si++; - srcoff = 0; - } - if (dstoff == dst->len[di]) { - /* We need to unmap that destination page and reset - * maddr ready for the next one. */ - kunmap(pages[di]); - maddr = NULL; - di++; - dstoff = 0; - } - } - - /* If we still had a page mapped at the end, unmap now. */ - if (maddr) - kunmap(pages[di]); - - return totlen; -} - -/*L:390 This is how we transfer a "struct lguest_dma" from the source Guest - * (the current Guest which called SEND_DMA) to another Guest. */ -static u32 do_dma(struct lguest *srclg, const struct lguest_dma *src, - struct lguest *dstlg, const struct lguest_dma *dst) -{ - int i; - u32 ret; - struct page *pages[LGUEST_MAX_DMA_SECTIONS]; - - /* We check that both source and destination "struct lguest_dma"s are - * within the bounds of the source and destination Guests */ - if (!check_dma_list(dstlg, dst) || !check_dma_list(srclg, src)) - return 0; - - /* We need to map the pages which correspond to each parts of - * destination buffer. */ - for (i = 0; i < LGUEST_MAX_DMA_SECTIONS; i++) { - if (dst->len[i] == 0) - break; - /* get_user_pages() is a complicated function, especially since - * we only want a single page. But it works, and returns the - * number of pages. Note that we're holding the destination's - * mmap_sem, as get_user_pages() requires. */ - if (get_user_pages(dstlg->tsk, dstlg->mm, - (unsigned long)dstlg->mem_base+dst->addr[i], - 1, 1, 1, pages+i, NULL) - != 1) { - /* This means the destination gave us a bogus buffer */ - kill_guest(dstlg, "Error mapping DMA pages"); - ret = 0; - goto drop_pages; - } - } - - /* Now copy the data until we run out of src or dst. */ - ret = copy_data(srclg, src, dst, pages); - -drop_pages: - while (--i >= 0) - put_page(pages[i]); - return ret; -} - -/*L:380 Transferring data from one Guest to another is not as simple as I'd - * like. We've found the "struct lguest_dma_info" bound to the same address as - * the send, we need to copy into it. - * - * This function returns true if the destination array was empty. */ -static int dma_transfer(struct lguest *srclg, - unsigned long udma, - struct lguest_dma_info *dst) -{ - struct lguest_dma dst_dma, src_dma; - struct lguest *dstlg; - u32 i, dma = 0; - - /* From the "struct lguest_dma_info" we found in the hash, grab the - * Guest. */ - dstlg = dst->owner; - /* Read in the source "struct lguest_dma" handed to SEND_DMA. */ - lgread(srclg, &src_dma, udma, sizeof(src_dma)); - - /* We need the destination's mmap_sem, and we already hold the source's - * mmap_sem for the futex key lookup. Normally this would suggest that - * we could deadlock if the destination Guest was trying to send to - * this source Guest at the same time, which is another reason that all - * I/O is done under the big lguest_lock. */ - down_read(&dstlg->mm->mmap_sem); - - /* Look through the destination DMA array for an available buffer. */ - for (i = 0; i < dst->num_dmas; i++) { - /* We keep a "next_dma" pointer which often helps us avoid - * looking at lots of previously-filled entries. */ - dma = (dst->next_dma + i) % dst->num_dmas; - if (!lgread_other(dstlg, &dst_dma, - dst->dmas + dma * sizeof(struct lguest_dma), - sizeof(dst_dma))) { - goto fail; - } - if (!dst_dma.used_len) - break; - } - - /* If we found a buffer, we do the actual data copy. */ - if (i != dst->num_dmas) { - unsigned long used_lenp; - unsigned int ret; - - ret = do_dma(srclg, &src_dma, dstlg, &dst_dma); - /* Put used length in the source "struct lguest_dma"'s used_len - * field. It's a little tricky to figure out where that is, - * though. */ - lgwrite_u32(srclg, - udma+offsetof(struct lguest_dma, used_len), ret); - /* Tranferring 0 bytes is OK if the source buffer was empty. */ - if (ret == 0 && src_dma.len[0] != 0) - goto fail; - - /* The destination Guest might be running on a different CPU: - * we have to make sure that it will see the "used_len" field - * change to non-zero *after* it sees the data we copied into - * the buffer. Hence a write memory barrier. */ - wmb(); - /* Figuring out where the destination's used_len field for this - * "struct lguest_dma" in the array is also a little ugly. */ - used_lenp = dst->dmas - + dma * sizeof(struct lguest_dma) - + offsetof(struct lguest_dma, used_len); - lgwrite_other(dstlg, used_lenp, &ret, sizeof(ret)); - /* Move the cursor for next time. */ - dst->next_dma++; - } - up_read(&dstlg->mm->mmap_sem); - - /* We trigger the destination interrupt, even if the destination was - * empty and we didn't transfer anything: this gives them a chance to - * wake up and refill. */ - set_bit(dst->interrupt, dstlg->irqs_pending); - /* Wake up the destination process. */ - wake_up_process(dstlg->tsk); - /* If we passed the last "struct lguest_dma", the receive had no - * buffers left. */ - return i == dst->num_dmas; - -fail: - up_read(&dstlg->mm->mmap_sem); - return 0; -} - -/*L:370 This is the counter-side to the BIND_DMA hypercall; the SEND_DMA - * hypercall. We find out who's listening, and send to them. */ -void send_dma(struct lguest *lg, unsigned long ukey, unsigned long udma) -{ - union futex_key key; - int empty = 0; - struct rw_semaphore *fshared = ¤t->mm->mmap_sem; - -again: - mutex_lock(&lguest_lock); - down_read(fshared); - /* Get the futex key for the key the Guest gave us */ - if (get_futex_key(lg->mem_base + ukey, fshared, &key) != 0) { - kill_guest(lg, "bad sending DMA key"); - goto unlock; - } - /* Since the key must be a multiple of 4, the futex key uses the lower - * bit of the "offset" field (which would always be 0) to indicate a - * mapping which is shared with other processes (ie. Guests). */ - if (key.shared.offset & 1) { - struct lguest_dma_info *i; - /* Look through the hash for other Guests. */ - list_for_each_entry(i, &dma_hash[hash(&key)], list) { - /* Don't send to ourselves (would deadlock). */ - if (i->owner->mm == lg->mm) - continue; - if (!key_eq(&key, &i->key)) - continue; - - /* If dma_transfer() tells us the destination has no - * available buffers, we increment "empty". */ - empty += dma_transfer(lg, udma, i); - break; - } - /* If the destination is empty, we release our locks and - * give the destination Guest a brief chance to restock. */ - if (empty == 1) { - /* Give any recipients one chance to restock. */ - up_read(¤t->mm->mmap_sem); - mutex_unlock(&lguest_lock); - /* Next time, we won't try again. */ - empty++; - goto again; - } - } else { - /* Private mapping: Guest is sending to its Launcher. We set - * the "dma_is_pending" flag so that the main loop will exit - * and the Launcher's read() from /dev/lguest will return. */ - lg->dma_is_pending = 1; - lg->pending_dma = udma; - lg->pending_key = ukey; - } -unlock: - up_read(fshared); - mutex_unlock(&lguest_lock); -} -/*:*/ - -void release_all_dma(struct lguest *lg) -{ - unsigned int i; - - BUG_ON(!mutex_is_locked(&lguest_lock)); - - down_read(&lg->mm->mmap_sem); - for (i = 0; i < LGUEST_MAX_DMA; i++) { - if (lg->dma[i].interrupt) - unlink_dma(&lg->dma[i]); - } - up_read(&lg->mm->mmap_sem); -} - -/*M:007 We only return a single DMA buffer to the Launcher, but it would be - * more efficient to return a pointer to the entire array of DMA buffers, which - * it can cache and choose one whenever it wants. - * - * Currently the Launcher uses a write to /dev/lguest, and the return value is - * the address of the DMA structure with the interrupt number placed in - * dma->used_len. If we wanted to return the entire array, we need to return - * the address, array size and interrupt number: this seems to require an - * ioctl(). :*/ - -/*L:320 This routine looks for a DMA buffer registered by the Guest on the - * given key (using the BIND_DMA hypercall). */ -unsigned long get_dma_buffer(struct lguest *lg, - unsigned long ukey, unsigned long *interrupt) -{ - unsigned long ret = 0; - union futex_key key; - struct lguest_dma_info *i; - struct rw_semaphore *fshared = ¤t->mm->mmap_sem; - - /* Take the Big Lguest Lock to stop other Guests sending this Guest DMA - * at the same time. */ - mutex_lock(&lguest_lock); - /* To match between Guests sharing the same underlying memory we steal - * code from the futex infrastructure. This requires that we hold the - * "mmap_sem" for our process (the Launcher), and pass it to the futex - * code. */ - down_read(fshared); - - /* This can fail if it's not a valid address, or if the address is not - * divisible by 4 (the futex code needs that, we don't really). */ - if (get_futex_key(lg->mem_base + ukey, fshared, &key) != 0) { - kill_guest(lg, "bad registered DMA buffer"); - goto unlock; - } - /* Search the hash table for matching entries (the Launcher can only - * send to its own Guest for the moment, so the entry must be for this - * Guest) */ - list_for_each_entry(i, &dma_hash[hash(&key)], list) { - if (key_eq(&key, &i->key) && i->owner == lg) { - unsigned int j; - /* Look through the registered DMA array for an - * available buffer. */ - for (j = 0; j < i->num_dmas; j++) { - struct lguest_dma dma; - - ret = i->dmas + j * sizeof(struct lguest_dma); - lgread(lg, &dma, ret, sizeof(dma)); - if (dma.used_len == 0) - break; - } - /* Store the interrupt the Guest wants when the buffer - * is used. */ - *interrupt = i->interrupt; - break; - } - } -unlock: - up_read(fshared); - mutex_unlock(&lguest_lock); - return ret; -} -/*:*/ - -/*L:410 This really has completed the Launcher. Not only have we now finished - * the longest chapter in our journey, but this also means we are over halfway - * through! - * - * Enough prevaricating around the bush: it is time for us to dive into the - * core of the Host, in "make Host". - */ diff --git a/drivers/lguest/lg.h b/drivers/lguest/lg.h index e4845d7f0688..4d45b7036e82 100644 --- a/drivers/lguest/lg.h +++ b/drivers/lguest/lg.h @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -17,17 +16,6 @@ void free_pagetables(void); int init_pagetables(struct page **switcher_page, unsigned int pages); -struct lguest_dma_info -{ - struct list_head list; - union futex_key key; - unsigned long dmas; - struct lguest *owner; - u16 next_dma; - u16 num_dmas; - u8 interrupt; /* 0 when not registered */ -}; - struct pgdir { unsigned long gpgdir; @@ -90,15 +78,11 @@ struct lguest struct task_struct *wake; unsigned long noirq_start, noirq_end; - int dma_is_pending; - unsigned long pending_dma; /* struct lguest_dma */ - unsigned long pending_key; /* address they're sending to */ + unsigned long pending_notify; /* pfn from LHCALL_NOTIFY */ unsigned int stack_pages; u32 tsc_khz; - struct lguest_dma_info dma[LGUEST_MAX_DMA]; - /* Dead? */ const char *dead; @@ -184,15 +168,6 @@ extern char start_switcher_text[], end_switcher_text[], switch_to_guest[]; int lguest_device_init(void); void lguest_device_remove(void); -/* io.c: */ -void lguest_io_init(void); -int bind_dma(struct lguest *lg, - unsigned long key, unsigned long udma, u16 numdmas, u8 interrupt); -void send_dma(struct lguest *info, unsigned long key, unsigned long udma); -void release_all_dma(struct lguest *lg); -unsigned long get_dma_buffer(struct lguest *lg, unsigned long key, - unsigned long *interrupt); - /* hypercalls.c: */ void do_hypercalls(struct lguest *lg); void write_timestamp(struct lguest *lg); diff --git a/drivers/lguest/lguest_user.c b/drivers/lguest/lguest_user.c index 61b177e1e649..ee405b38383d 100644 --- a/drivers/lguest/lguest_user.c +++ b/drivers/lguest/lguest_user.c @@ -2,37 +2,12 @@ * controls and communicates with the Guest. For example, the first write will * tell us the Guest's memory layout, pagetable, entry point and kernel address * offset. A read will run the Guest until something happens, such as a signal - * or the Guest doing a DMA out to the Launcher. Writes are also used to get a - * DMA buffer registered by the Guest and to send the Guest an interrupt. :*/ + * or the Guest doing a NOTIFY out to the Launcher. :*/ #include #include #include #include "lg.h" -/*L:310 To send DMA into the Guest, the Launcher needs to be able to ask for a - * DMA buffer. This is done by writing LHREQ_GETDMA and the key to - * /dev/lguest. */ -static long user_get_dma(struct lguest *lg, const unsigned long __user *input) -{ - unsigned long key, udma, irq; - - /* Fetch the key they wrote to us. */ - if (get_user(key, input) != 0) - return -EFAULT; - /* Look for a free Guest DMA buffer bound to that key. */ - udma = get_dma_buffer(lg, key, &irq); - if (!udma) - return -ENOENT; - - /* We need to tell the Launcher what interrupt the Guest expects after - * the buffer is filled. We stash it in udma->used_len. */ - lgwrite_u32(lg, udma + offsetof(struct lguest_dma, used_len), irq); - - /* The (guest-physical) address of the DMA buffer is returned from - * the write(). */ - return udma; -} - /*L:315 To force the Guest to stop running and return to the Launcher, the * Waker sets writes LHREQ_BREAK and the value "1" to /dev/lguest. The * Launcher then writes LHREQ_BREAK and "0" to release the Waker. */ @@ -102,10 +77,10 @@ static ssize_t read(struct file *file, char __user *user, size_t size,loff_t*o) return len; } - /* If we returned from read() last time because the Guest sent DMA, + /* If we returned from read() last time because the Guest notified, * clear the flag. */ - if (lg->dma_is_pending) - lg->dma_is_pending = 0; + if (lg->pending_notify) + lg->pending_notify = 0; /* Run the Guest until something interesting happens. */ return run_guest(lg, (unsigned long __user *)user); @@ -216,7 +191,7 @@ unlock: /*L:010 The first operation the Launcher does must be a write. All writes * start with a 32 bit number: for the first write this must be * LHREQ_INITIALIZE to set up the Guest. After that the Launcher can use - * writes of other values to get DMA buffers and send interrupts. */ + * writes of other values to send interrupts. */ static ssize_t write(struct file *file, const char __user *in, size_t size, loff_t *off) { @@ -245,8 +220,6 @@ static ssize_t write(struct file *file, const char __user *in, switch (req) { case LHREQ_INITIALIZE: return initialize(file, input); - case LHREQ_GETDMA: - return user_get_dma(lg, input); case LHREQ_IRQ: return user_send_irq(lg, input); case LHREQ_BREAK: @@ -276,8 +249,6 @@ static int close(struct inode *inode, struct file *file) mutex_lock(&lguest_lock); /* Cancels the hrtimer set via LHCALL_SET_CLOCKEVENT. */ hrtimer_cancel(&lg->hrt); - /* Free any DMA buffers the Guest had bound. */ - release_all_dma(lg); /* Free up the shadow page tables for the Guest. */ free_guest_pagetable(lg); /* Now all the memory cleanups are done, it's safe to release the diff --git a/include/asm-x86/lguest_hcall.h b/include/asm-x86/lguest_hcall.h index 0c553ef36240..f948491eb56a 100644 --- a/include/asm-x86/lguest_hcall.h +++ b/include/asm-x86/lguest_hcall.h @@ -13,11 +13,10 @@ #define LHCALL_TS 8 #define LHCALL_SET_CLOCKEVENT 9 #define LHCALL_HALT 10 -#define LHCALL_BIND_DMA 12 -#define LHCALL_SEND_DMA 13 #define LHCALL_SET_PTE 14 #define LHCALL_SET_PMD 15 #define LHCALL_LOAD_TLS 16 +#define LHCALL_NOTIFY 17 /*G:031 First, how does our Guest contact the Host to ask for privileged * operations? There are two ways: the direct way is to make a "hypercall", diff --git a/include/linux/lguest_launcher.h b/include/linux/lguest_launcher.h index b6603f3fbff8..5ec04a225e4f 100644 --- a/include/linux/lguest_launcher.h +++ b/include/linux/lguest_launcher.h @@ -10,40 +10,6 @@ /* How many devices? Assume each one wants up to two dma arrays per device. */ #define LGUEST_MAX_DEVICES (LGUEST_MAX_DMA/2) -/*D:200 - * Lguest I/O - * - * The lguest I/O mechanism is the only way Guests can talk to devices. There - * are two hypercalls involved: SEND_DMA for output and BIND_DMA for input. In - * each case, "struct lguest_dma" describes the buffer: this contains 16 - * addr/len pairs, and if there are fewer buffer elements the len array is - * terminated with a 0. - * - * I/O is organized by keys: BIND_DMA attaches buffers to a particular key, and - * SEND_DMA transfers to buffers bound to particular key. By convention, keys - * correspond to a physical address within the device's page. This means that - * devices will never accidentally end up with the same keys, and allows the - * Host use The Futex Trick (as we'll see later in our journey). - * - * SEND_DMA simply indicates a key to send to, and the physical address of the - * "struct lguest_dma" to send. The Host will write the number of bytes - * transferred into the "struct lguest_dma"'s used_len member. - * - * BIND_DMA indicates a key to bind to, a pointer to an array of "struct - * lguest_dma"s ready for receiving, the size of that array, and an interrupt - * to trigger when data is received. The Host will only allow transfers into - * buffers with a used_len of zero: it then sets used_len to the number of - * bytes transferred and triggers the interrupt for the Guest to process the - * new input. */ -struct lguest_dma -{ - /* 0 if free to be used, filled by the Host. */ - __u32 used_len; - __u16 len[LGUEST_MAX_DMA_SECTIONS]; - unsigned long addr[LGUEST_MAX_DMA_SECTIONS]; -}; -/*:*/ - /* Where the Host expects the Guest to SEND_DMA console output to. */ #define LGUEST_CONSOLE_DMA_KEY 0 @@ -95,7 +61,7 @@ struct lguest_device_desc { enum lguest_req { LHREQ_INITIALIZE, /* + pfnlimit, pgdir, start, pageoffset */ - LHREQ_GETDMA, /* + addr (returns &lguest_dma, irq in ->used_len) */ + LHREQ_GETDMA, /* No longer used */ LHREQ_IRQ, /* + irq */ LHREQ_BREAK, /* + on/off flag (on blocks until someone does off) */ }; -- cgit v1.2.3-71-gd317 From 19f1537b7b8a9a82665db3ad8210a9d954d13acd Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 22 Oct 2007 11:24:21 +1000 Subject: Lguest support for Virtio This makes lguest able to use the virtio devices. We change the device descriptor page from a simple array to a variable length "type, config_len, status, config data..." format, and implement virtio_config_ops to read from that config data. We use the virtio ring implementation for an efficient Guest <-> Host virtqueue mechanism, and the new LHCALL_NOTIFY hypercall to kick the host when it changes. We also use LHCALL_NOTIFY on kernel addresses for very very early console output. We could have another hypercall, but this hack works quite well. Signed-off-by: Rusty Russell --- arch/x86/lguest/Kconfig | 5 + arch/x86/lguest/boot.c | 21 +++ drivers/lguest/Makefile | 3 + drivers/lguest/lguest_device.c | 373 ++++++++++++++++++++++++++++++++++++++++ include/linux/lguest_launcher.h | 47 ++--- 5 files changed, 421 insertions(+), 28 deletions(-) create mode 100644 drivers/lguest/lguest_device.c (limited to 'include/linux') diff --git a/arch/x86/lguest/Kconfig b/arch/x86/lguest/Kconfig index 44dccfd845f8..c4dffbeea5e1 100644 --- a/arch/x86/lguest/Kconfig +++ b/arch/x86/lguest/Kconfig @@ -2,8 +2,13 @@ config LGUEST_GUEST bool "Lguest guest support" select PARAVIRT depends on !X86_PAE + select VIRTIO select VIRTIO_RING + select VIRTIO_CONSOLE help Lguest is a tiny in-kernel hypervisor. Selecting this will allow your kernel to boot under lguest. This option will increase your kernel size by about 6k. If in doubt, say N. + + If you say Y here, make sure you say Y (or M) to the virtio block + and net drivers which lguest needs. diff --git a/arch/x86/lguest/boot.c b/arch/x86/lguest/boot.c index 959aeebb02f5..495e46a1f111 100644 --- a/arch/x86/lguest/boot.c +++ b/arch/x86/lguest/boot.c @@ -55,6 +55,7 @@ #include #include #include +#include #include #include #include @@ -849,6 +850,23 @@ static __init char *lguest_memory_setup(void) return "LGUEST"; } +/* Before virtqueues are set up, we use LHCALL_NOTIFY on normal memory to + * produce console output. */ +static __init int early_put_chars(u32 vtermno, const char *buf, int count) +{ + char scratch[17]; + unsigned int len = count; + + if (len > sizeof(scratch) - 1) + len = sizeof(scratch) - 1; + scratch[len] = '\0'; + memcpy(scratch, buf, len); + hcall(LHCALL_NOTIFY, __pa(scratch), 0, 0); + + /* This routine returns the number of bytes actually written. */ + return len; +} + /*G:050 * Patching (Powerfully Placating Performance Pedants) * @@ -1048,6 +1066,9 @@ __init void lguest_init(void *boot) * adapted for lguest's use. */ add_preferred_console("hvc", 0, NULL); + /* Register our very early console. */ + virtio_cons_early_init(early_put_chars); + /* Last of all, we set the power management poweroff hook to point to * the Guest routine to power off. */ pm_power_off = lguest_power_off; diff --git a/drivers/lguest/Makefile b/drivers/lguest/Makefile index a63f75dc41a1..5e8272d296d8 100644 --- a/drivers/lguest/Makefile +++ b/drivers/lguest/Makefile @@ -1,3 +1,6 @@ +# Guest requires the device configuration and probing code. +obj-$(CONFIG_LGUEST_GUEST) += lguest_device.o + # Host requires the other files, which can be a module. obj-$(CONFIG_LGUEST) += lg.o lg-y = core.o hypercalls.o page_tables.o interrupts_and_traps.o \ diff --git a/drivers/lguest/lguest_device.c b/drivers/lguest/lguest_device.c new file mode 100644 index 000000000000..71c64837b437 --- /dev/null +++ b/drivers/lguest/lguest_device.c @@ -0,0 +1,373 @@ +/*P:050 Lguest guests use a very simple method to describe devices. It's a + * series of device descriptors contained just above the top of normal + * memory. + * + * We use the standard "virtio" device infrastructure, which provides us with a + * console, a network and a block driver. Each one expects some configuration + * information and a "virtqueue" mechanism to send and receive data. :*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* The pointer to our (page) of device descriptions. */ +static void *lguest_devices; + +/* Unique numbering for lguest devices. */ +static unsigned int dev_index; + +/* For Guests, device memory can be used as normal memory, so we cast away the + * __iomem to quieten sparse. */ +static inline void *lguest_map(unsigned long phys_addr, unsigned long pages) +{ + return (__force void *)ioremap(phys_addr, PAGE_SIZE*pages); +} + +static inline void lguest_unmap(void *addr) +{ + iounmap((__force void __iomem *)addr); +} + +/*D:100 Each lguest device is just a virtio device plus a pointer to its entry + * in the lguest_devices page. */ +struct lguest_device { + struct virtio_device vdev; + + /* The entry in the lguest_devices page for this device. */ + struct lguest_device_desc *desc; +}; + +/* Since the virtio infrastructure hands us a pointer to the virtio_device all + * the time, it helps to have a curt macro to get a pointer to the struct + * lguest_device it's enclosed in. */ +#define to_lgdev(vdev) container_of(vdev, struct lguest_device, vdev) + +/*D:130 + * Device configurations + * + * The configuration information for a device consists of a series of fields. + * The device will look for these fields during setup. + * + * For us these fields come immediately after that device's descriptor in the + * lguest_devices page. + * + * Each field starts with a "type" byte, a "length" byte, then that number of + * bytes of configuration information. The device descriptor tells us the + * total configuration length so we know when we've reached the last field. */ + +/* type + length bytes */ +#define FHDR_LEN 2 + +/* This finds the first field of a given type for a device's configuration. */ +static void *lg_find(struct virtio_device *vdev, u8 type, unsigned int *len) +{ + struct lguest_device_desc *desc = to_lgdev(vdev)->desc; + int i; + + for (i = 0; i < desc->config_len; i += FHDR_LEN + desc->config[i+1]) { + if (desc->config[i] == type) { + /* Mark it used, so Host can know we looked at it, and + * also so we won't find the same one twice. */ + desc->config[i] |= 0x80; + /* Remember, the second byte is the length. */ + *len = desc->config[i+1]; + /* We return a pointer to the field header. */ + return desc->config + i; + } + } + + /* Not found: return NULL for failure. */ + return NULL; +} + +/* Once they've found a field, getting a copy of it is easy. */ +static void lg_get(struct virtio_device *vdev, void *token, + void *buf, unsigned len) +{ + /* Check they didn't ask for more than the length of the field! */ + BUG_ON(len > ((u8 *)token)[1]); + memcpy(buf, token + FHDR_LEN, len); +} + +/* Setting the contents is also trivial. */ +static void lg_set(struct virtio_device *vdev, void *token, + const void *buf, unsigned len) +{ + BUG_ON(len > ((u8 *)token)[1]); + memcpy(token + FHDR_LEN, buf, len); +} + +/* The operations to get and set the status word just access the status field + * of the device descriptor. */ +static u8 lg_get_status(struct virtio_device *vdev) +{ + return to_lgdev(vdev)->desc->status; +} + +static void lg_set_status(struct virtio_device *vdev, u8 status) +{ + to_lgdev(vdev)->desc->status = status; +} + +/* + * Virtqueues + * + * The other piece of infrastructure virtio needs is a "virtqueue": a way of + * the Guest device registering buffers for the other side to read from or + * write into (ie. send and receive buffers). Each device can have multiple + * virtqueues: for example the console has one queue for sending and one for + * receiving. + * + * Fortunately for us, a very fast shared-memory-plus-descriptors virtqueue + * already exists in virtio_ring.c. We just need to connect it up. + * + * We start with the information we need to keep about each virtqueue. + */ + +/*D:140 This is the information we remember about each virtqueue. */ +struct lguest_vq_info +{ + /* A copy of the information contained in the device config. */ + struct lguest_vqconfig config; + + /* The address where we mapped the virtio ring, so we can unmap it. */ + void *pages; +}; + +/* When the virtio_ring code wants to prod the Host, it calls us here and we + * make a hypercall. We hand the page number of the virtqueue so the Host + * knows which virtqueue we're talking about. */ +static void lg_notify(struct virtqueue *vq) +{ + /* We store our virtqueue information in the "priv" pointer of the + * virtqueue structure. */ + struct lguest_vq_info *lvq = vq->priv; + + hcall(LHCALL_NOTIFY, lvq->config.pfn << PAGE_SHIFT, 0, 0); +} + +/* This routine finds the first virtqueue described in the configuration of + * this device and sets it up. + * + * This is kind of an ugly duckling. It'd be nicer to have a standard + * representation of a virtqueue in the configuration space, but it seems that + * everyone wants to do it differently. The KVM guys want the Guest to + * allocate its own pages and tell the Host where they are, but for lguest it's + * simpler for the Host to simply tell us where the pages are. + * + * So we provide devices with a "find virtqueue and set it up" function. */ +static struct virtqueue *lg_find_vq(struct virtio_device *vdev, + bool (*callback)(struct virtqueue *vq)) +{ + struct lguest_vq_info *lvq; + struct virtqueue *vq; + unsigned int len; + void *token; + int err; + + /* Look for a field of the correct type to mark a virtqueue. Note that + * if this succeeds, then the type will be changed so it won't be found + * again, and future lg_find_vq() calls will find the next + * virtqueue (if any). */ + token = vdev->config->find(vdev, VIRTIO_CONFIG_F_VIRTQUEUE, &len); + if (!token) + return ERR_PTR(-ENOENT); + + lvq = kmalloc(sizeof(*lvq), GFP_KERNEL); + if (!lvq) + return ERR_PTR(-ENOMEM); + + /* Note: we could use a configuration space inside here, just like we + * do for the device. This would allow expansion in future, because + * our configuration system is designed to be expansible. But this is + * way easier. */ + if (len != sizeof(lvq->config)) { + dev_err(&vdev->dev, "Unexpected virtio config len %u\n", len); + err = -EIO; + goto free_lvq; + } + /* Make a copy of the "struct lguest_vqconfig" field. We need a copy + * because the config space might not be aligned correctly. */ + vdev->config->get(vdev, token, &lvq->config, sizeof(lvq->config)); + + /* Figure out how many pages the ring will take, and map that memory */ + lvq->pages = lguest_map((unsigned long)lvq->config.pfn << PAGE_SHIFT, + DIV_ROUND_UP(vring_size(lvq->config.num), + PAGE_SIZE)); + if (!lvq->pages) { + err = -ENOMEM; + goto free_lvq; + } + + /* OK, tell virtio_ring.c to set up a virtqueue now we know its size + * and we've got a pointer to its pages. */ + vq = vring_new_virtqueue(lvq->config.num, vdev, lvq->pages, + lg_notify, callback); + if (!vq) { + err = -ENOMEM; + goto unmap; + } + + /* Tell the interrupt for this virtqueue to go to the virtio_ring + * interrupt handler. */ + /* FIXME: We used to have a flag for the Host to tell us we could use + * the interrupt as a source of randomness: it'd be nice to have that + * back.. */ + err = request_irq(lvq->config.irq, vring_interrupt, IRQF_SHARED, + vdev->dev.bus_id, vq); + if (err) + goto destroy_vring; + + /* Last of all we hook up our 'struct lguest_vq_info" to the + * virtqueue's priv pointer. */ + vq->priv = lvq; + return vq; + +destroy_vring: + vring_del_virtqueue(vq); +unmap: + lguest_unmap(lvq->pages); +free_lvq: + kfree(lvq); + return ERR_PTR(err); +} +/*:*/ + +/* Cleaning up a virtqueue is easy */ +static void lg_del_vq(struct virtqueue *vq) +{ + struct lguest_vq_info *lvq = vq->priv; + + /* Tell virtio_ring.c to free the virtqueue. */ + vring_del_virtqueue(vq); + /* Unmap the pages containing the ring. */ + lguest_unmap(lvq->pages); + /* Free our own queue information. */ + kfree(lvq); +} + +/* The ops structure which hooks everything together. */ +static struct virtio_config_ops lguest_config_ops = { + .find = lg_find, + .get = lg_get, + .set = lg_set, + .get_status = lg_get_status, + .set_status = lg_set_status, + .find_vq = lg_find_vq, + .del_vq = lg_del_vq, +}; + +/* The root device for the lguest virtio devices. This makes them appear as + * /sys/devices/lguest/0,1,2 not /sys/devices/0,1,2. */ +static struct device lguest_root = { + .parent = NULL, + .bus_id = "lguest", +}; + +/*D:120 This is the core of the lguest bus: actually adding a new device. + * It's a separate function because it's neater that way, and because an + * earlier version of the code supported hotplug and unplug. They were removed + * early on because they were never used. + * + * As Andrew Tridgell says, "Untested code is buggy code". + * + * It's worth reading this carefully: we start with a pointer to the new device + * descriptor in the "lguest_devices" page. */ +static void add_lguest_device(struct lguest_device_desc *d) +{ + struct lguest_device *ldev; + + ldev = kzalloc(sizeof(*ldev), GFP_KERNEL); + if (!ldev) { + printk(KERN_EMERG "Cannot allocate lguest dev %u\n", + dev_index++); + return; + } + + /* This devices' parent is the lguest/ dir. */ + ldev->vdev.dev.parent = &lguest_root; + /* We have a unique device index thanks to the dev_index counter. */ + ldev->vdev.index = dev_index++; + /* The device type comes straight from the descriptor. There's also a + * device vendor field in the virtio_device struct, which we leave as + * 0. */ + ldev->vdev.id.device = d->type; + /* We have a simple set of routines for querying the device's + * configuration information and setting its status. */ + ldev->vdev.config = &lguest_config_ops; + /* And we remember the device's descriptor for lguest_config_ops. */ + ldev->desc = d; + + /* register_virtio_device() sets up the generic fields for the struct + * virtio_device and calls device_register(). This makes the bus + * infrastructure look for a matching driver. */ + if (register_virtio_device(&ldev->vdev) != 0) { + printk(KERN_ERR "Failed to register lguest device %u\n", + ldev->vdev.index); + kfree(ldev); + } +} + +/*D:110 scan_devices() simply iterates through the device page. The type 0 is + * reserved to mean "end of devices". */ +static void scan_devices(void) +{ + unsigned int i; + struct lguest_device_desc *d; + + /* We start at the page beginning, and skip over each entry. */ + for (i = 0; i < PAGE_SIZE; i += sizeof(*d) + d->config_len) { + d = lguest_devices + i; + + /* Once we hit a zero, stop. */ + if (d->type == 0) + break; + + add_lguest_device(d); + } +} + +/*D:105 Fairly early in boot, lguest_devices_init() is called to set up the + * lguest device infrastructure. We check that we are a Guest by checking + * pv_info.name: there are other ways of checking, but this seems most + * obvious to me. + * + * So we can access the "struct lguest_device_desc"s easily, we map that memory + * and store the pointer in the global "lguest_devices". Then we register a + * root device from which all our devices will hang (this seems to be the + * correct sysfs incantation). + * + * Finally we call scan_devices() which adds all the devices found in the + * lguest_devices page. */ +static int __init lguest_devices_init(void) +{ + if (strcmp(pv_info.name, "lguest") != 0) + return 0; + + if (device_register(&lguest_root) != 0) + panic("Could not register lguest root"); + + /* Devices are in a single page above top of "normal" mem */ + lguest_devices = lguest_map(max_pfn<