shithub: riscv

Download patch

ref: c558a99e0be506a9abdf677f0ca4490644e05fc1
parent: e5888a1ffdae813d7575f5fb02275c6bb07e5199
author: Taru Karttunen <[email protected]>
date: Wed Mar 30 12:47:56 EDT 2011

Import sources from 2011-03-30 iso image - sys/include

--- /dev/null
+++ b/sys/include/9p.h
@@ -1,0 +1,253 @@
+#pragma src "/sys/src/lib9p"
+#pragma lib "lib9p.a"
+
+/*
+ * Maps from ulongs to void*s.
+ */
+typedef struct Intmap	Intmap;
+
+#pragma incomplete Intmap
+
+Intmap*	allocmap(void (*inc)(void*));
+void		freemap(Intmap*, void (*destroy)(void*));
+void*	lookupkey(Intmap*, ulong);
+void*	insertkey(Intmap*, ulong, void*);
+int		caninsertkey(Intmap*, ulong, void*);
+void*	deletekey(Intmap*, ulong);
+
+/*
+ * Fid and Request structures.
+ */
+typedef struct Fid		Fid;
+typedef struct Req		Req;
+typedef struct Fidpool	Fidpool;
+typedef struct Reqpool	Reqpool;
+typedef struct File		File;
+typedef struct Filelist	Filelist;
+typedef struct Tree		Tree;
+typedef struct Readdir	Readdir;
+typedef struct Srv Srv;
+
+#pragma incomplete Filelist
+#pragma incomplete Readdir
+
+struct Fid
+{
+	ulong	fid;
+	char		omode;	/* -1 = not open */
+	File*		file;
+	char*	uid;
+	Qid		qid;
+	void*	aux;
+
+/* below is implementation-specific; don't use */
+	Readdir*	rdir;
+	Ref		ref;
+	Fidpool*	pool;
+	vlong	diroffset;
+	long		dirindex;
+};
+
+struct Req
+{
+	ulong	tag;
+	void*	aux;
+	Fcall		ifcall;
+	Fcall		ofcall;
+	Dir		d;
+	Req*		oldreq;
+	Fid*		fid;
+	Fid*		afid;
+	Fid*		newfid;
+	Srv*		srv;
+
+/* below is implementation-specific; don't use */
+	QLock	lk;
+	Ref		ref;
+	Reqpool*	pool;
+	uchar*	buf;
+	uchar	type;
+	uchar	responded;
+	char*	error;
+	void*	rbuf;
+	Req**	flush;
+	int		nflush;
+};
+
+/*
+ * Pools to maintain Fid <-> fid and Req <-> tag maps.
+ */
+
+struct Fidpool {
+	Intmap	*map;
+	void		(*destroy)(Fid*);
+	Srv		*srv;
+};
+
+struct Reqpool {
+	Intmap	*map;
+	void		(*destroy)(Req*);
+	Srv		*srv;
+};
+
+Fidpool*	allocfidpool(void (*destroy)(Fid*));
+void		freefidpool(Fidpool*);
+Fid*		allocfid(Fidpool*, ulong);
+Fid*		lookupfid(Fidpool*, ulong);
+void		closefid(Fid*);
+Fid*		removefid(Fidpool*, ulong);
+
+Reqpool*	allocreqpool(void (*destroy)(Req*));
+void		freereqpool(Reqpool*);
+Req*		allocreq(Reqpool*, ulong);
+Req*		lookupreq(Reqpool*, ulong);
+void		closereq(Req*);
+Req*		removereq(Reqpool*, ulong);
+
+typedef	int	Dirgen(int, Dir*, void*);
+void		dirread9p(Req*, Dirgen*, void*);
+
+/*
+ * File trees.
+ */
+struct File {
+	Ref;
+	Dir;
+	File *parent;
+	void *aux;
+
+/* below is implementation-specific; don't use */
+	RWLock;
+	Filelist *filelist;
+	Tree *tree;
+	int nchild;
+	int allocd;
+	int nxchild;
+	Ref readers;
+};
+
+struct Tree {
+	File *root;
+	void	(*destroy)(File *file);
+
+/* below is implementation-specific; don't use */
+	Lock genlock;
+	ulong qidgen;
+	ulong dirqidgen;
+};
+
+Tree*	alloctree(char*, char*, ulong, void(*destroy)(File*));
+void		freetree(Tree*);
+File*		createfile(File*, char*, char*, ulong, void*);
+int		removefile(File*);
+void		closefile(File*);
+File*		walkfile(File*, char*);
+Readdir*	opendirfile(File*);
+long		readdirfile(Readdir*, uchar*, long);
+void		closedirfile(Readdir*);
+
+/*
+ * Kernel-style command parser
+ */
+typedef struct Cmdbuf Cmdbuf;
+typedef struct Cmdtab Cmdtab;
+Cmdbuf*		parsecmd(char *a, int n);
+void		respondcmderror(Req*, Cmdbuf*, char*, ...);
+Cmdtab*	lookupcmd(Cmdbuf*, Cmdtab*, int);
+#pragma varargck argpos respondcmderr 3
+struct Cmdbuf
+{
+	char	*buf;
+	char	**f;
+	int	nf;
+};
+
+struct Cmdtab
+{
+	int	index;	/* used by client to switch on result */
+	char	*cmd;	/* command name */
+	int	narg;	/* expected #args; 0 ==> variadic */
+};
+
+/*
+ * File service loop.
+ */
+struct Srv {
+	Tree*	tree;
+	void		(*destroyfid)(Fid*);
+	void		(*destroyreq)(Req*);
+	void		(*end)(Srv*);
+	void*	aux;
+
+	void		(*attach)(Req*);
+	void		(*auth)(Req*);
+	void		(*open)(Req*);
+	void		(*create)(Req*);
+	void		(*read)(Req*);
+	void		(*write)(Req*);
+	void		(*remove)(Req*);
+	void		(*flush)(Req*);
+	void		(*stat)(Req*);
+	void		(*wstat)(Req*);
+	void		(*walk)(Req*);
+	char*	(*clone)(Fid*, Fid*);
+	char*	(*walk1)(Fid*, char*, Qid*);
+
+	int		infd;
+	int		outfd;
+	int		nopipe;
+	int		srvfd;
+	int		leavefdsopen;	/* magic for acme win */
+	char*	keyspec;
+
+/* below is implementation-specific; don't use */
+	Fidpool*	fpool;
+	Reqpool*	rpool;
+	uint		msize;
+
+	uchar*	rbuf;
+	QLock	rlock;
+	uchar*	wbuf;
+	QLock	wlock;
+	
+	char*	addr;
+};
+
+void		srv(Srv*);
+void		postmountsrv(Srv*, char*, char*, int);
+void		_postmountsrv(Srv*, char*, char*, int);
+void		listensrv(Srv*, char*);
+void		_listensrv(Srv*, char*);
+int 		postfd(char*, int);
+int		chatty9p;
+void		respond(Req*, char*);
+void		responderror(Req*);
+void		threadpostmountsrv(Srv*, char*, char*, int);
+void		threadlistensrv(Srv *s, char *addr);
+
+/*
+ * Helper.  Assumes user is same as group.
+ */
+int		hasperm(File*, char*, int);
+
+void*	emalloc9p(ulong);
+void*	erealloc9p(void*, ulong);
+char*	estrdup9p(char*);
+
+enum {
+	OMASK = 3
+};
+
+void		readstr(Req*, char*);
+void		readbuf(Req*, void*, long);
+void		walkandclone(Req*, char*(*walk1)(Fid*,char*,void*), 
+			char*(*clone)(Fid*,Fid*,void*), void*);
+
+void		auth9p(Req*);
+void		authread(Req*);
+void		authwrite(Req*);
+void		authdestroy(Fid*);
+int		authattach(Req*);
+
+extern void (*_forker)(void (*)(void*), void*, int);
+
--- /dev/null
+++ b/sys/include/String.h
@@ -1,0 +1,45 @@
+#pragma	src	"/sys/src/libString"
+#pragma	lib	"libString.a"
+
+/* extensible Strings */
+typedef struct String {
+	Lock;
+	char	*base;	/* base of String */
+	char	*end;	/* end of allocated space+1 */
+	char	*ptr;	/* ptr into String */
+	short	ref;
+	uchar	fixed;
+} String;
+
+#define s_clone(s) s_copy((s)->base)
+#define s_to_c(s) ((s)->base)
+#define s_len(s) ((s)->ptr-(s)->base)
+
+extern String*	s_append(String*, char*);
+extern String*	s_array(char*, int);
+extern String*	s_copy(char*);
+extern void	s_free(String*);
+extern String*	s_incref(String*);	
+extern String*	s_memappend(String*, char*, int);
+extern String*	s_nappend(String*, char*, int);
+extern String*	s_new(void);
+extern String*	s_newalloc(int);
+extern String*	s_parse(String*, String*);
+extern String*	s_reset(String*);
+extern String*	s_restart(String*);
+extern void	s_terminate(String*);
+extern void	s_tolower(String*);
+extern void	s_putc(String*, int);
+extern String*	s_unique(String*);
+extern String*	s_grow(String*, int);
+
+#ifdef BGETC
+extern int	s_read(Biobuf*, String*, int);
+extern char	*s_read_line(Biobuf*, String*);
+extern char	*s_getline(Biobuf*, String*);
+typedef struct Sinstack Sinstack;
+#pragma incomplete Sinstack
+extern char	*s_rdinstack(Sinstack*, String*);
+extern Sinstack	*s_allocinstack(char*);
+extern void	s_freeinstack(Sinstack*);
+#endif BGETC
--- /dev/null
+++ b/sys/include/a.out.h
@@ -1,0 +1,46 @@
+typedef	struct	Exec	Exec;
+struct	Exec
+{
+	long	magic;		/* magic number */
+	long	text;	 	/* size of text segment */
+	long	data;	 	/* size of initialized data */
+	long	bss;	  	/* size of uninitialized data */
+	long	syms;	 	/* size of symbol table */
+	long	entry;	 	/* entry point */
+	long	spsz;		/* size of pc/sp offset table */
+	long	pcsz;		/* size of pc/line number table */
+};
+
+#define HDR_MAGIC	0x00008000		/* header expansion */
+
+#define	_MAGIC(f, b)	((f)|((((4*(b))+0)*(b))+7))
+#define	A_MAGIC		_MAGIC(0, 8)		/* 68020 */
+#define	I_MAGIC		_MAGIC(0, 11)		/* intel 386 */
+#define	J_MAGIC		_MAGIC(0, 12)		/* intel 960 (retired) */
+#define	K_MAGIC		_MAGIC(0, 13)		/* sparc */
+#define	V_MAGIC		_MAGIC(0, 16)		/* mips 3000 BE */
+#define	X_MAGIC		_MAGIC(0, 17)		/* att dsp 3210 (retired) */
+#define	M_MAGIC		_MAGIC(0, 18)		/* mips 4000 BE */
+#define	D_MAGIC		_MAGIC(0, 19)		/* amd 29000 (retired) */
+#define	E_MAGIC		_MAGIC(0, 20)		/* arm */
+#define	Q_MAGIC		_MAGIC(0, 21)		/* powerpc */
+#define	N_MAGIC		_MAGIC(0, 22)		/* mips 4000 LE */
+#define	L_MAGIC		_MAGIC(0, 23)		/* dec alpha */
+#define	P_MAGIC		_MAGIC(0, 24)		/* mips 3000 LE */
+#define	U_MAGIC		_MAGIC(0, 25)		/* sparc64 */
+#define	S_MAGIC		_MAGIC(HDR_MAGIC, 26)	/* amd64 */
+#define	T_MAGIC		_MAGIC(HDR_MAGIC, 27)	/* powerpc64 */
+
+#define	MIN_MAGIC	8
+#define	MAX_MAGIC	27			/* <= 90 */
+
+#define	DYN_MAGIC	0x80000000		/* dlm */
+
+typedef	struct	Sym	Sym;
+struct	Sym
+{
+	vlong	value;
+	uint	sig;
+	char	type;
+	char	*name;
+};
--- /dev/null
+++ b/sys/include/ape/Plan9libnet.h
@@ -1,0 +1,20 @@
+#ifndef __LIBNET_H
+#define __LIBNET_H
+#ifndef _NET_EXTENSION
+   This header file is not defined in ANSI or POSIX
+#endif
+#pragma lib "/$M/lib/ape/libnet.a"
+
+#define NETPATHLEN 40
+
+extern	int	accept(int, char*);
+extern	int	announce(char*, char*);
+extern	int	dial(char*, char*, char*, int*);
+extern	int	hangup(int);
+extern	int	listen(char*, char*);
+extern	char*	netmkaddr(char*, char*, char*);
+extern	int	reject(int, char*, char *);
+
+extern char    dialerrstr[64];
+
+#endif /* __LIBNET_H */
--- /dev/null
+++ b/sys/include/ape/ar.h
@@ -1,0 +1,24 @@
+#ifndef __AR_H
+#define __AR_H
+#ifndef _RESEARCH_SOURCE
+   This header file is not defined in ANSI or POSIX
+#endif
+
+#define	ARMAG	"!<arch>\n"
+#define	SARMAG	8
+
+#define	ARFMAG	"`\n"
+
+struct	ar_hdr
+{
+	char	ar_name[16];
+	char	ar_date[12];
+	char	ar_uid[6];
+	char	ar_gid[6];
+	char	ar_mode[8];
+	char	ar_size[10];
+	char	ar_fmag[2];
+};
+#define	SAR_HDR	60
+
+#endif
--- /dev/null
+++ b/sys/include/ape/arpa/inet.h
@@ -1,0 +1,146 @@
+#ifndef __netinet_in__
+#define __netinet_in__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Copyright (c) 1982, 1986, 1990 Regents of the University of California.
+ * All rights reserved.
+ *
+ * Redistribution is only permitted until one year after the first shipment
+ * of 4.4BSD by the Regents.  Otherwise, redistribution and use in source and
+ * binary forms are permitted provided that: (1) source distributions retain
+ * this entire copyright notice and comment, and (2) distributions including
+ * binaries display the following acknowledgement:  This product includes
+ * software developed by the University of California, Berkeley and its
+ * contributors'' in the documentation or other materials provided with the
+ * distribution and in all advertising materials mentioning features or use
+ * of this software.  Neither the name of the University nor the names of
+ * its contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ * THIS SOFTWARE IS PROVIDED AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ *	@(#)in.h	7.10 (Berkeley) 6/28/90 plus MULTICAST 1.1
+ */
+
+/*
+ * Constants and structures defined by the internet system,
+ * Per RFC 790, September 1981.
+ */
+
+/*
+ * Protocols
+ */
+#define	IPPROTO_IP		0		/* dummy for IP */
+#define	IPPROTO_ICMP		1		/* control message protocol */
+#define	IPPROTO_GGP		3		/* gateway^2 (deprecated) */
+#define	IPPROTO_TCP		6		/* tcp */
+#define	IPPROTO_EGP		8		/* exterior gateway protocol */
+#define	IPPROTO_PUP		12		/* pup */
+#define	IPPROTO_UDP		17		/* user datagram protocol */
+#define	IPPROTO_IDP		22		/* xns idp */
+#define	IPPROTO_TP		29 		/* tp-4 w/ class negotiation */
+#define	IPPROTO_EON		80		/* ISO cnlp */
+
+#define	IPPROTO_RAW		255		/* raw IP packet */
+#define	IPPROTO_MAX		256
+
+
+/*
+ * Local port number conventions:
+ * Ports < IPPORT_RESERVED are reserved for
+ * privileged processes (e.g. root).
+ * Ports > IPPORT_USERRESERVED are reserved
+ * for servers, not necessarily privileged.
+ */
+#define	IPPORT_RESERVED		1024
+#define	IPPORT_USERRESERVED	5000
+
+/*
+ * Internet address (a structure for historical reasons)
+ */
+struct in_addr {
+	unsigned long s_addr;
+};
+
+/*
+ * Definitions of bits in internet address integers.
+ * On subnets, the decomposition of addresses to host and net parts
+ * is done according to subnet mask, not the masks here.
+ */
+#define	IN_CLASSA(i)		(((long)(i) & 0x80000000) == 0)
+#define	IN_CLASSA_NET		0xff000000
+#define	IN_CLASSA_NSHIFT	24
+#define	IN_CLASSA_HOST		0x00ffffff
+#define	IN_CLASSA_MAX		128
+
+#define	IN_CLASSB(i)		(((long)(i) & 0xc0000000) == 0x80000000)
+#define	IN_CLASSB_NET		0xffff0000
+#define	IN_CLASSB_NSHIFT	16
+#define	IN_CLASSB_HOST		0x0000ffff
+#define	IN_CLASSB_MAX		65536
+
+#define	IN_CLASSC(i)		(((long)(i) & 0xe0000000) == 0xc0000000)
+#define	IN_CLASSC_NET		0xffffff00
+#define	IN_CLASSC_NSHIFT	8
+#define	IN_CLASSC_HOST		0x000000ff
+
+#define	IN_CLASSD(i)		(((long)(i) & 0xf0000000) == 0xe0000000)
+#define	IN_MULTICAST(i)		IN_CLASSD(i)
+
+#define	IN_EXPERIMENTAL(i)	(((long)(i) & 0xe0000000) == 0xe0000000)
+#define	IN_BADCLASS(i)		(((long)(i) & 0xf0000000) == 0xf0000000)
+
+#define	INADDR_ANY		(unsigned long)0x00000000
+#define	INADDR_BROADCAST	(unsigned long)0xffffffff	/* must be masked */
+
+#define	IN_LOOPBACKNET		127			/* official! */
+
+/*
+ * Socket address, internet style.
+ */
+struct sockaddr_in {
+	short	sin_family;
+	unsigned short	sin_port;
+	struct	in_addr sin_addr;
+	char	sin_zero[8];
+};
+
+/*
+ * Structure used to describe IP options.
+ * Used to store options internally, to pass them to a process,
+ * or to restore options retrieved earlier.
+ * The ip_dst is used for the first-hop gateway when using a source route
+ * (this gets put into the header proper).
+ */
+struct ip_opts {
+	struct	in_addr ip_dst;		/* first hop, 0 w/o src rt */
+	char	ip_opts[40];		/* actually variable in size */
+};
+
+/*
+ * Options for use with [gs]etsockopt at the IP level.
+ * First word of comment is data type; bool is stored in int.
+ */
+#define	IP_OPTIONS	1	/* buf/ip_opts; set/get IP per-packet options */
+#define	IP_HDRINCL	7	/* int; header is included with data (raw) */
+#define	IP_TOS		8	/* int; IP type of service and precedence */
+#define	IP_TTL		9	/* int; IP time to live */
+
+extern unsigned long	ntohl(unsigned long x);
+extern unsigned short	ntohs(unsigned short x);
+extern unsigned long	htonl(unsigned long x);
+extern unsigned short	htons(unsigned short x);
+extern unsigned long	inet_addr(char*);
+extern char*		inet_ntoa(struct in_addr);
+extern unsigned long	nptohl(void*);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __netinet_in__ */
--- /dev/null
+++ b/sys/include/ape/assert.h
@@ -1,0 +1,17 @@
+#pragma lib "/$M/lib/ape/libap.a"
+
+#undef assert
+#ifdef NDEBUG
+#define assert(ignore) ((void)0)
+#else
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern void _assert(char *, unsigned);
+
+#ifdef __cplusplus
+}
+#endif
+#define assert(e) {if(!(e))_assert(__FILE__, __LINE__);}
+#endif /* NDEBUG */
--- /dev/null
+++ b/sys/include/ape/bsd.h
@@ -1,0 +1,56 @@
+#ifndef _BSD_EXTENSION
+    This header file is an extension to ANSI/POSIX
+#endif
+
+#ifndef __BSD_H_
+#define __BSD_H_
+#pragma src "/sys/src/ape/lib/bsd"
+#pragma lib "/$M/lib/ape/libbsd.a"
+
+#ifndef __TYPES_H
+#include <sys/types.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef _SIZE_T
+#define _SIZE_T
+typedef unsigned long size_t;
+#endif
+
+/* ifndefs because X11 stuff (ugh) */
+#ifndef bcopy
+extern void	bcopy(void*, void*, size_t);
+#endif
+#ifndef bcmp
+extern int	bcmp(void*, void*, size_t);
+#endif
+#ifndef bzero
+extern void	bzero(void*, size_t);
+#endif
+extern int	ffs(unsigned int);
+extern void	bhappy(void*);
+extern int	rresvport(int*);
+extern int	rcmd(char**, int, char*, char*, char*, int*);
+extern char*	strdup(char*);
+extern int	strcasecmp(char*, char*);
+extern int 	putenv(char*);
+extern int	strncasecmp(char*, char*,int);
+extern void* memccpy(void*, void*, int, size_t);
+
+extern int	getopt(int, char**, char*);
+extern int	opterr;
+extern int	optind;
+extern int	optopt;
+extern char	*optarg;
+extern char	*mktemp(char *);
+extern char	*sys_errlist[];
+extern int		sys_nerr;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/ctype.h
@@ -1,0 +1,55 @@
+#ifndef __CTYPE
+#define __CTYPE
+#pragma lib "/$M/lib/ape/libap.a"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int isalnum(int);
+extern int isalpha(int);
+extern int iscntrl(int);
+extern int isdigit(int);
+extern int isgraph(int);
+extern int islower(int);
+extern int isprint(int);
+extern int ispunct(int);
+extern int isspace(int);
+extern int isupper(int);
+extern int isxdigit(int);
+extern int tolower(int);
+extern int toupper(int);
+
+#ifdef __cplusplus
+}
+#endif
+enum
+{
+  _ISupper = 01,	/* UPPERCASE.  */
+  _ISlower = 02,	/* lowercase.  */
+  _ISdigit = 04,	/* Numeric.  */
+  _ISspace = 010,	/* Whitespace.  */
+  _ISpunct = 020,	/* Punctuation.  */
+  _IScntrl = 040,	/* Control character.  */
+  _ISblank = 0100,	/* Blank (usually SPC and TAB).  */
+  _ISxdigit = 0200,	/* Hexadecimal numeric.  */
+};
+
+extern unsigned char _ctype[];
+#define	isalnum(c)	(_ctype[(unsigned char)(c)]&(_ISupper|_ISlower|_ISdigit))
+#define	isalpha(c)	(_ctype[(unsigned char)(c)]&(_ISupper|_ISlower))
+#define	iscntrl(c)	(_ctype[(unsigned char)(c)]&_IScntrl)
+#define	isdigit(c)	(_ctype[(unsigned char)(c)]&_ISdigit)
+#define	isgraph(c)	(_ctype[(unsigned char)(c)]&(_ISpunct|_ISupper|_ISlower|_ISdigit))
+#define	islower(c)	(_ctype[(unsigned char)(c)]&_ISlower)
+#define	isprint(c)	(_ctype[(unsigned char)(c)]&(_ISpunct|_ISupper|_ISlower|_ISdigit|_ISblank))
+#define	ispunct(c)	(_ctype[(unsigned char)(c)]&_ISpunct)
+#define	isspace(c)	(_ctype[(unsigned char)(c)]&_ISspace)
+#define	isupper(c)	(_ctype[(unsigned char)(c)]&_ISupper)
+#define	isxdigit(c)	(_ctype[(unsigned char)(c)]&_ISxdigit)
+
+#ifdef _BSD_EXTENSION
+#define	isascii(c) (((unsigned int)(c))<0x80)
+#endif
+
+#endif /* __CTYPE */
--- /dev/null
+++ b/sys/include/ape/cursor.h
@@ -1,0 +1,10 @@
+#ifndef _PLAN9_SOURCE
+  This header file is an extension to ANSI/POSIX
+#endif
+
+#ifndef	__CURSOR_H_
+#define	__CURSOR_H_
+#include "/sys/include/cursor.h"
+
+#endif
+
--- /dev/null
+++ b/sys/include/ape/dirent.h
@@ -1,0 +1,40 @@
+#ifndef	__DIRENT_H
+#define	__DIRENT_H
+#pragma lib "/$M/lib/ape/libap.a"
+/*
+ * this must be a power of 2 and a multiple of all the ones in the system
+ */
+#define MAXNAMLEN 255
+
+struct	dirent {
+	char	d_name[MAXNAMLEN + 1];
+};
+
+typedef struct _dirdesc {
+	int	dd_fd;		/* file descriptor */
+	long	dd_loc;		/* buf offset of entry from last readdir() */
+	long	dd_size;	/* amount of valid data in buffer */
+	char	*dd_buf;	/* directory data buffer */
+	void *dirs;
+	int	dirsize;
+	int	dirloc;
+} DIR;
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * functions defined on directories
+ */
+DIR		*opendir(const char *);
+struct dirent	*readdir(DIR *);
+void		rewinddir(DIR *);
+int		closedir(DIR *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/draw.h
@@ -1,0 +1,539 @@
+#ifndef _PLAN9_SOURCE
+  This header file is an extension to ANSI/POSIX
+#endif
+
+#ifndef	__DRAW_H_
+#define	__DRAW_H_
+#pragma src "/sys/src/ape/lib/draw"
+#pragma lib "/$M/lib/ape/libdraw.a"
+
+#include <u.h>
+#include <fmt.h>
+#include <qlock.h>
+
+typedef struct	Cachefont Cachefont;
+typedef struct	Cacheinfo Cacheinfo;
+typedef struct	Cachesubf Cachesubf;
+typedef struct	Display Display;
+typedef struct	Font Font;
+typedef struct	Fontchar Fontchar;
+typedef struct	Image Image;
+typedef struct	Mouse Mouse;
+typedef struct	Point Point;
+typedef struct	Rectangle Rectangle;
+typedef struct	RGB RGB;
+typedef struct	Screen Screen;
+typedef struct	Subfont Subfont;
+
+#pragma varargck	type	"R"	Rectangle
+#pragma varargck	type	"P"	Point
+extern	int	Rfmt(Fmt*);
+extern	int	Pfmt(Fmt*);
+
+enum
+{
+	DOpaque		= 0xFFFFFFFF,
+	DTransparent	= 0x00000000,		/* only useful for allocimage, memfillcolor */
+	DBlack		= 0x000000FF,
+	DWhite		= 0xFFFFFFFF,
+	DRed		= 0xFF0000FF,
+	DGreen		= 0x00FF00FF,
+	DBlue		= 0x0000FFFF,
+	DCyan		= 0x00FFFFFF,
+	DMagenta		= 0xFF00FFFF,
+	DYellow		= 0xFFFF00FF,
+	DPaleyellow	= 0xFFFFAAFF,
+	DDarkyellow	= 0xEEEE9EFF,
+	DDarkgreen	= 0x448844FF,
+	DPalegreen	= 0xAAFFAAFF,
+	DMedgreen	= 0x88CC88FF,
+	DDarkblue	= 0x000055FF,
+	DPalebluegreen= 0xAAFFFFFF,
+	DPaleblue		= 0x0000BBFF,
+	DBluegreen	= 0x008888FF,
+	DGreygreen	= 0x55AAAAFF,
+	DPalegreygreen	= 0x9EEEEEFF,
+	DYellowgreen	= 0x99994CFF,
+	DMedblue		= 0x000099FF,
+	DGreyblue	= 0x005DBBFF,
+	DPalegreyblue	= 0x4993DDFF,
+	DPurpleblue	= 0x8888CCFF,
+
+	DNotacolor	= 0xFFFFFF00,
+	DNofill		= DNotacolor,
+	
+};
+
+enum
+{
+	Displaybufsize	= 8000,
+	ICOSSCALE	= 1024,
+	Borderwidth =	4,
+};
+
+enum
+{
+	/* refresh methods */
+	Refbackup	= 0,
+	Refnone		= 1,
+	Refmesg		= 2
+};
+#define	NOREFRESH	((void*)-1)
+
+enum
+{
+	/* line ends */
+	Endsquare	= 0,
+	Enddisc		= 1,
+	Endarrow	= 2,
+	Endmask		= 0x1F
+};
+
+#define	ARROW(a, b, c)	(Endarrow|((a)<<5)|((b)<<14)|((c)<<23))
+
+typedef enum
+{
+	/* Porter-Duff compositing operators */
+	Clear	= 0,
+
+	SinD	= 8,
+	DinS	= 4,
+	SoutD	= 2,
+	DoutS	= 1,
+
+	S		= SinD|SoutD,
+	SoverD	= SinD|SoutD|DoutS,
+	SatopD	= SinD|DoutS,
+	SxorD	= SoutD|DoutS,
+
+	D		= DinS|DoutS,
+	DoverS	= DinS|DoutS|SoutD,
+	DatopS	= DinS|SoutD,
+	DxorS	= DoutS|SoutD,	/* == SxorD */
+
+	Ncomp = 12,
+} Drawop;
+
+/*
+ * image channel descriptors 
+ */
+enum {
+	CRed = 0,
+	CGreen,
+	CBlue,
+	CGrey,
+	CAlpha,
+	CMap,
+	CIgnore,
+	NChan,
+};
+
+#define __DC(type, nbits)	((((type)&15)<<4)|((nbits)&15))
+#define CHAN1(a,b)	__DC(a,b)
+#define CHAN2(a,b,c,d)	(CHAN1((a),(b))<<8|__DC((c),(d)))
+#define CHAN3(a,b,c,d,e,f)	(CHAN2((a),(b),(c),(d))<<8|__DC((e),(f)))
+#define CHAN4(a,b,c,d,e,f,g,h)	(CHAN3((a),(b),(c),(d),(e),(f))<<8|__DC((g),(h)))
+
+#define NBITS(c) ((c)&15)
+#define TYPE(c) (((c)>>4)&15)
+
+enum {
+	GREY1	= CHAN1(CGrey, 1),
+	GREY2	= CHAN1(CGrey, 2),
+	GREY4	= CHAN1(CGrey, 4),
+	GREY8	= CHAN1(CGrey, 8),
+	CMAP8	= CHAN1(CMap, 8),
+	RGB15	= CHAN4(CIgnore, 1, CRed, 5, CGreen, 5, CBlue, 5),
+	RGB16	= CHAN3(CRed, 5, CGreen, 6, CBlue, 5),
+	RGB24	= CHAN3(CRed, 8, CGreen, 8, CBlue, 8),
+	RGBA32	= CHAN4(CRed, 8, CGreen, 8, CBlue, 8, CAlpha, 8),
+	ARGB32	= CHAN4(CAlpha, 8, CRed, 8, CGreen, 8, CBlue, 8),	/* stupid VGAs */
+	XRGB32	= CHAN4(CIgnore, 8, CRed, 8, CGreen, 8, CBlue, 8),
+	BGR24	= CHAN3(CBlue, 8, CGreen, 8, CRed, 8),
+	ABGR32	= CHAN4(CAlpha, 8, CBlue, 8, CGreen, 8, CRed, 8),
+	XBGR32	= CHAN4(CIgnore, 8, CBlue, 8, CGreen, 8, CRed, 8),
+};
+
+extern	char*	chantostr(char*, ulong);
+extern	ulong	strtochan(char*);
+extern	int		chantodepth(ulong);
+
+struct	Point
+{
+	int	x;
+	int	y;
+};
+
+struct Rectangle
+{
+	Point	min;
+	Point	max;
+};
+
+typedef void	(*Reffn)(Image*, Rectangle, void*);
+
+struct Screen
+{
+	Display	*display;	/* display holding data */
+	int	id;		/* id of system-held Screen */
+	Image	*image;		/* unused; for reference only */
+	Image	*fill;		/* color to paint behind windows */
+};
+
+struct Display
+{
+	QLock	qlock;
+	int		locking;	/*program is using lockdisplay */
+	int		dirno;
+	int		fd;
+	int		reffd;
+	int		ctlfd;
+	int		imageid;
+	int		local;
+	void		(*error)(Display*, char*);
+	char		*devdir;
+	char		*windir;
+	char		oldlabel[64];
+	ulong		dataqid;
+	Image		*white;
+	Image		*black;
+	Image		*opaque;
+	Image		*transparent;
+	Image		*image;
+	uchar		*buf;
+	int			bufsize;
+	uchar		*bufp;
+	Font		*defaultfont;
+	Subfont		*defaultsubfont;
+	Image		*windows;
+	Image		*screenimage;
+	int			_isnewdisplay;
+};
+
+struct Image
+{
+	Display		*display;	/* display holding data */
+	int		id;		/* id of system-held Image */
+	Rectangle	r;		/* rectangle in data area, local coords */
+	Rectangle 	clipr;		/* clipping region */
+	int		depth;		/* number of bits per pixel */
+	ulong	chan;
+	int		repl;		/* flag: data replicates to tile clipr */
+	Screen		*screen;	/* 0 if not a window */
+	Image		*next;	/* next in list of windows */
+};
+
+struct RGB
+{
+	ulong	red;
+	ulong	green;
+	ulong	blue;
+};
+
+/*
+ * Subfonts
+ *
+ * given char c, Subfont *f, Fontchar *i, and Point p, one says
+ *	i = f->info+c;
+ *	draw(b, Rect(p.x+i->left, p.y+i->top,
+ *		p.x+i->left+((i+1)->x-i->x), p.y+i->bottom),
+ *		color, f->bits, Pt(i->x, i->top));
+ *	p.x += i->width;
+ * to draw characters in the specified color (itself an Image) in Image b.
+ */
+
+struct	Fontchar
+{
+	int		x;		/* left edge of bits */
+	uchar		top;		/* first non-zero scan-line */
+	uchar		bottom;		/* last non-zero scan-line + 1 */
+	char		left;		/* offset of baseline */
+	uchar		width;		/* width of baseline */
+};
+
+struct	Subfont
+{
+	char		*name;
+	short		n;		/* number of chars in font */
+	uchar		height;		/* height of image */
+	char		ascent;		/* top of image to baseline */
+	Fontchar 	*info;		/* n+1 character descriptors */
+	Image		*bits;		/* of font */
+	int		ref;
+};
+
+enum
+{
+	/* starting values */
+	LOG2NFCACHE =	6,
+	NFCACHE =	(1<<LOG2NFCACHE),	/* #chars cached */
+	NFLOOK =	5,			/* #chars to scan in cache */
+	NFSUBF =	2,			/* #subfonts to cache */
+	/* max value */
+	MAXFCACHE =	1024+NFLOOK,		/* upper limit */
+	MAXSUBF =	50,			/* generous upper limit */
+	/* deltas */
+	DSUBF = 	4,
+	/* expiry ages */
+	SUBFAGE	=	10000,
+	CACHEAGE =	10000
+};
+
+struct Cachefont
+{
+	Rune		min;	/* lowest rune value to be taken from subfont */
+	Rune		max;	/* highest rune value+1 to be taken from subfont */
+	int		offset;	/* position in subfont of character at min */
+	char		*name;			/* stored in font */
+	char		*subfontname;		/* to access subfont */
+};
+
+struct Cacheinfo
+{
+	ushort		x;		/* left edge of bits */
+	uchar		width;		/* width of baseline */
+	schar		left;		/* offset of baseline */
+	Rune		value;	/* value of character at this slot in cache */
+	ushort		age;
+};
+
+struct Cachesubf
+{
+	ulong		age;	/* for replacement */
+	Cachefont	*cf;	/* font info that owns us */
+	Subfont		*f;	/* attached subfont */
+};
+
+struct Font
+{
+	char		*name;
+	Display		*display;
+	short		height;	/* max height of image, interline spacing */
+	short		ascent;	/* top of image to baseline */
+	short		width;	/* widest so far; used in caching only */	
+	short		nsub;	/* number of subfonts */
+	ulong		age;	/* increasing counter; used for LRU */
+	int		maxdepth;	/* maximum depth of all loaded subfonts */
+	int		ncache;	/* size of cache */
+	int		nsubf;	/* size of subfont list */
+	Cacheinfo	*cache;
+	Cachesubf	*subf;
+	Cachefont	**sub;	/* as read from file */
+	Image		*cacheimage;
+};
+
+#define	Dx(r)	((r).max.x-(r).min.x)
+#define	Dy(r)	((r).max.y-(r).min.y)
+
+#ifdef	__cplusplus
+extern "C" { 
+#endif
+
+/*
+ * Image management
+ */
+extern Image*	_allocimage(Image*, Display*, Rectangle, ulong, int, ulong, int, int);
+extern Image*	allocimage(Display*, Rectangle, ulong, int, ulong);
+extern uchar*	bufimage(Display*, int);
+extern int	bytesperline(Rectangle, int);
+extern void	closedisplay(Display*);
+extern void	drawerror(Display*, char*);
+extern int	flushimage(Display*, int);
+extern int	freeimage(Image*);
+extern int	_freeimage1(Image*);
+extern int	geninitdraw(char*, void(*)(Display*, char*), char*, char*, char*, int);
+extern int	initdraw(void(*)(Display*, char*), char*, char*);
+extern int	newwindow(char*);
+extern Display*	initdisplay(char*, char*, void(*)(Display*, char*));
+extern int	loadimage(Image*, Rectangle, uchar*, int);
+extern int	cloadimage(Image*, Rectangle, uchar*, int);
+extern int	getwindow(Display*, int);
+extern int	gengetwindow(Display*, char*, Image**, Screen**, int);
+extern Image* readimage(Display*, int, int);
+extern Image* creadimage(Display*, int, int);
+extern int	unloadimage(Image*, Rectangle, uchar*, int);
+extern int	wordsperline(Rectangle, int);
+extern int	writeimage(int, Image*, int);
+extern Image*	namedimage(Display*, char*);
+extern int	nameimage(Image*, char*, int);
+extern Image* allocimagemix(Display*, ulong, ulong);
+
+/*
+ * Colors
+ */
+extern	void	readcolmap(Display*, RGB*);
+extern	void	writecolmap(Display*, RGB*);
+extern	ulong	setalpha(ulong, uchar);
+
+/*
+ * Windows
+ */
+extern Screen*	allocscreen(Image*, Image*, int);
+extern Image*	_allocwindow(Image*, Screen*, Rectangle, int, ulong);
+extern Image*	allocwindow(Screen*, Rectangle, int, ulong);
+extern void	bottomnwindows(Image**, int);
+extern void	bottomwindow(Image*);
+extern int	freescreen(Screen*);
+extern Screen*	publicscreen(Display*, int, ulong);
+extern void	topnwindows(Image**, int);
+extern void	topwindow(Image*);
+extern int	originwindow(Image*, Point, Point);
+
+/*
+ * Geometry
+ */
+extern Point		Pt(int, int);
+extern Rectangle	Rect(int, int, int, int);
+extern Rectangle	Rpt(Point, Point);
+extern Point		addpt(Point, Point);
+extern Point		subpt(Point, Point);
+extern Point		divpt(Point, int);
+extern Point		mulpt(Point, int);
+extern int		eqpt(Point, Point);
+extern int		eqrect(Rectangle, Rectangle);
+extern Rectangle	insetrect(Rectangle, int);
+extern Rectangle	rectaddpt(Rectangle, Point);
+extern Rectangle	rectsubpt(Rectangle, Point);
+extern Rectangle	canonrect(Rectangle);
+extern int		rectXrect(Rectangle, Rectangle);
+extern int		rectinrect(Rectangle, Rectangle);
+extern void		combinerect(Rectangle*, Rectangle);
+extern int		rectclip(Rectangle*, Rectangle);
+extern int		ptinrect(Point, Rectangle);
+extern void		replclipr(Image*, int, Rectangle);
+extern int		drawreplxy(int, int, int);	/* used to be drawsetxy */
+extern Point	drawrepl(Rectangle, Point);
+extern int		rgb2cmap(int, int, int);
+extern int		cmap2rgb(int);
+extern int		cmap2rgba(int);
+extern void		icossin(int, int*, int*);
+extern void		icossin2(int, int, int*, int*);
+
+/*
+ * Graphics
+ */
+extern void	draw(Image*, Rectangle, Image*, Image*, Point);
+extern void	drawop(Image*, Rectangle, Image*, Image*, Point, Drawop);
+extern void	gendraw(Image*, Rectangle, Image*, Point, Image*, Point);
+extern void	gendrawop(Image*, Rectangle, Image*, Point, Image*, Point, Drawop);
+extern void	line(Image*, Point, Point, int, int, int, Image*, Point);
+extern void	lineop(Image*, Point, Point, int, int, int, Image*, Point, Drawop);
+extern void	poly(Image*, Point*, int, int, int, int, Image*, Point);
+extern void	polyop(Image*, Point*, int, int, int, int, Image*, Point, Drawop);
+extern void	fillpoly(Image*, Point*, int, int, Image*, Point);
+extern void	fillpolyop(Image*, Point*, int, int, Image*, Point, Drawop);
+extern Point	string(Image*, Point, Image*, Point, Font*, char*);
+extern Point	stringop(Image*, Point, Image*, Point, Font*, char*, Drawop);
+extern Point	stringn(Image*, Point, Image*, Point, Font*, char*, int);
+extern Point	stringnop(Image*, Point, Image*, Point, Font*, char*, int, Drawop);
+extern Point	runestring(Image*, Point, Image*, Point, Font*, Rune*);
+extern Point	runestringop(Image*, Point, Image*, Point, Font*, Rune*, Drawop);
+extern Point	runestringn(Image*, Point, Image*, Point, Font*, Rune*, int);
+extern Point	runestringnop(Image*, Point, Image*, Point, Font*, Rune*, int, Drawop);
+extern Point	stringbg(Image*, Point, Image*, Point, Font*, char*, Image*, Point);
+extern Point	stringbgop(Image*, Point, Image*, Point, Font*, char*, Image*, Point, Drawop);
+extern Point	stringnbg(Image*, Point, Image*, Point, Font*, char*, int, Image*, Point);
+extern Point	stringnbgop(Image*, Point, Image*, Point, Font*, char*, int, Image*, Point, Drawop);
+extern Point	runestringbg(Image*, Point, Image*, Point, Font*, Rune*, Image*, Point);
+extern Point	runestringbgop(Image*, Point, Image*, Point, Font*, Rune*, Image*, Point, Drawop);
+extern Point	runestringnbg(Image*, Point, Image*, Point, Font*, Rune*, int, Image*, Point);
+extern Point	runestringnbgop(Image*, Point, Image*, Point, Font*, Rune*, int, Image*, Point, Drawop);
+extern Point	_string(Image*, Point, Image*, Point, Font*, char*, Rune*, int, Rectangle, Image*, Point, Drawop);
+extern Point	stringsubfont(Image*, Point, Image*, Subfont*, char*);
+extern int		bezier(Image*, Point, Point, Point, Point, int, int, int, Image*, Point);
+extern int		bezierop(Image*, Point, Point, Point, Point, int, int, int, Image*, Point, Drawop);
+extern int		bezspline(Image*, Point*, int, int, int, int, Image*, Point);
+extern int		bezsplineop(Image*, Point*, int, int, int, int, Image*, Point, Drawop);
+extern int		bezsplinepts(Point*, int, Point**);
+extern int		fillbezier(Image*, Point, Point, Point, Point, int, Image*, Point);
+extern int		fillbezierop(Image*, Point, Point, Point, Point, int, Image*, Point, Drawop);
+extern int		fillbezspline(Image*, Point*, int, int, Image*, Point);
+extern int		fillbezsplineop(Image*, Point*, int, int, Image*, Point, Drawop);
+extern void	ellipse(Image*, Point, int, int, int, Image*, Point);
+extern void	ellipseop(Image*, Point, int, int, int, Image*, Point, Drawop);
+extern void	fillellipse(Image*, Point, int, int, Image*, Point);
+extern void	fillellipseop(Image*, Point, int, int, Image*, Point, Drawop);
+extern void	arc(Image*, Point, int, int, int, Image*, Point, int, int);
+extern void	arcop(Image*, Point, int, int, int, Image*, Point, int, int, Drawop);
+extern void	fillarc(Image*, Point, int, int, Image*, Point, int, int);
+extern void	fillarcop(Image*, Point, int, int, Image*, Point, int, int, Drawop);
+extern void	border(Image*, Rectangle, int, Image*, Point);
+extern void	borderop(Image*, Rectangle, int, Image*, Point, Drawop);
+
+/*
+ * Font management
+ */
+extern Font*	openfont(Display*, char*);
+extern Font*	buildfont(Display*, char*, char*);
+extern void	freefont(Font*);
+extern Font*	mkfont(Subfont*, Rune);
+extern int	cachechars(Font*, char**, Rune**, ushort*, int, int*, char**);
+extern void	agefont(Font*);
+extern Subfont*	allocsubfont(char*, int, int, int, Fontchar*, Image*);
+extern Subfont*	lookupsubfont(Display*, char*);
+extern void	installsubfont(char*, Subfont*);
+extern void	uninstallsubfont(Subfont*);
+extern void	freesubfont(Subfont*);
+extern Subfont*	readsubfont(Display*, char*, int, int);
+extern Subfont*	readsubfonti(Display*, char*, int, Image*, int);
+extern int	writesubfont(int, Subfont*);
+extern void	_unpackinfo(Fontchar*, uchar*, int);
+extern Point	stringsize(Font*, char*);
+extern int	stringwidth(Font*, char*);
+extern int	stringnwidth(Font*, char*, int);
+extern Point	runestringsize(Font*, Rune*);
+extern int	runestringwidth(Font*, Rune*);
+extern int	runestringnwidth(Font*, Rune*, int);
+extern Point	strsubfontwidth(Subfont*, char*);
+extern int	loadchar(Font*, Rune, Cacheinfo*, int, int, char**);
+extern char*	subfontname(char*, char*, int);
+extern Subfont*	_getsubfont(Display*, char*);
+extern Subfont*	getdefont(Display*);
+extern void		lockdisplay(Display*);
+extern void	unlockdisplay(Display*);
+extern int		drawlsetrefresh(ulong, int, void*, void*);
+
+/*
+ * Predefined 
+ */
+extern	uchar	defontdata[];
+extern	int		sizeofdefont;
+extern	Point		ZP;
+extern	Rectangle	ZR;
+
+/*
+ * Set up by initdraw()
+ */
+extern	Display	*display;
+extern	Font		*font;
+extern	Image	*screen;
+extern	Screen	*_screen;
+extern	int	_cursorfd;
+extern	int	_drawdebug;	/* set to 1 to see errors from flushimage */
+extern	void	_setdrawop(Display*, Drawop);
+
+#define	BGSHORT(p)		(((p)[0]<<0) | ((p)[1]<<8))
+#define	BGLONG(p)		((BGSHORT(p)<<0) | (BGSHORT(p+2)<<16))
+#define	BPSHORT(p, v)		((p)[0]=(v), (p)[1]=((v)>>8))
+#define	BPLONG(p, v)		(BPSHORT(p, (v)), BPSHORT(p+2, (v)>>16))
+
+/*
+ * Compressed image file parameters and helper routines
+ */
+#define	NMATCH	3		/* shortest match possible */
+#define	NRUN	(NMATCH+31)	/* longest match possible */
+#define	NMEM	1024		/* window size */
+#define	NDUMP	128		/* maximum length of dump */
+#define	NCBLOCK	6000		/* size of compressed blocks */
+extern	void	_twiddlecompressed(uchar*, int);
+extern	int	_compblocksize(Rectangle, int);
+
+/* XXX backwards helps; should go */
+extern	ulong	drawld2chan[];
+extern	void		drawsetdebug(int);
+
+#ifdef	__cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/errno.h
@@ -1,0 +1,83 @@
+#ifndef __ERRNO
+#define __ERRNO
+#pragma lib "/$M/lib/ape/libap.a"
+
+extern int errno;
+
+#define EDOM	1000
+#define ERANGE	1001
+#define EPLAN9	1002
+
+#ifdef _POSIX_SOURCE
+
+#define E2BIG	1
+#define EACCES	2
+#define	EAGAIN	3
+#define EBADF	4
+#define EBUSY	5
+#define ECHILD	6
+#define EDEADLK	7
+#define EEXIST	8
+#define EFAULT	9
+#define EFBIG	10
+#define EINTR	11
+#define EINVAL	12
+#define EIO	13
+#define EISDIR	14
+#define EMFILE	15
+#define EMLINK	16
+#define ENAMETOOLONG	17
+#define ENFILE	18
+#define ENODEV	19
+#define ENOENT	20
+#define ENOEXEC	21
+#define ENOLCK	22
+#define ENOMEM	23
+#define ENOSPC	24
+#define ENOSYS	25
+#define ENOTDIR	26
+#define ENOTEMPTY	27
+#define ENOTTY	28
+#define ENXIO	29
+#define EPERM	30
+#define EPIPE	31
+#define EROFS	32
+#define ESPIPE	33
+#define ESRCH	34
+#define EXDEV	35
+
+/* bsd networking software */
+#define ENOTSOCK	36
+#define EPROTONOSUPPORT	37
+#define EPROTOTYPE	37	/* two names for 37 */
+#define ECONNREFUSED	38
+#define EAFNOSUPPORT	39
+#define ENOBUFS		40
+#define EOPNOTSUPP	41
+#define EADDRINUSE	42
+#define EDESTADDRREQ	43
+#define EMSGSIZE	44
+#define ENOPROTOOPT	45
+#define ESOCKTNOSUPPORT	46
+#define EPFNOSUPPORT	47
+#define EADDRNOTAVAIL	48
+#define ENETDOWN	49
+#define ENETUNREACH	50
+#define ENETRESET	51
+#define ECONNABORTED	52
+#define EISCON	53
+#define ENOTCONN	54
+#define ESHUTDOWN	55
+#define ETOOMANYREFS	56
+#define ETIMEDOUT	57
+#define EHOSTDOWN	58
+#define EHOSTUNREACH	59
+#define EGREG		60
+
+/* These added in 1003.1b-1993 */
+#define ECANCELED	61
+#define EINPROGRESS	62
+
+#endif /* _POSIX_SOURCE */
+
+#endif /* __ERRNO */
--- /dev/null
+++ b/sys/include/ape/error.h
@@ -1,0 +1,19 @@
+#ifndef __ERROR_H
+#define __ERROR_H
+#ifndef _RESEARCH_SOURCE
+   This header file is not defined in pure ANSI or POSIX
+#endif
+#pragma lib "/$M/lib/ape/libv.a"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern char *_progname;		/* program name */
+extern void _perror(char *);	/* perror but with _progname */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _ERROR_H */
--- /dev/null
+++ b/sys/include/ape/event.h
@@ -1,0 +1,10 @@
+#ifndef _PLAN9_SOURCE
+  This header file is an extension to ANSI/POSIX
+#endif
+
+#ifndef	__EVENT_H_
+#define	__EVENT_H_
+#include "/sys/include/event.h"
+
+#endif
+
--- /dev/null
+++ b/sys/include/ape/fcntl.h
@@ -1,0 +1,59 @@
+#ifndef __FCNTL_H
+#define __FCNTL_H
+#ifndef _POSIX_SOURCE
+   This header file is not defined in pure ANSI
+#endif
+#pragma lib "/$M/lib/ape/libap.a"
+
+#include	<sys/types.h>
+
+#define	O_RDONLY 0
+#define	O_WRONLY 1
+#define	O_RDWR	 2
+#define O_ACCMODE	0x003
+#define O_NONBLOCK	0x004
+#define O_APPEND	0x008
+#define O_CREAT		0x100
+#define O_TRUNC		0x200
+#define O_EXCL		0x400
+#define O_NOCTTY	0x800
+#define O_DSYNC		0x1000
+#define	O_RSYNC		0x2000
+#define O_SYNC		0x4000
+
+#define	F_DUPFD		0	/* Duplicate fildes */
+#define	F_GETFD		1	/* Get fildes flags */
+#define	F_SETFD		2	/* Set fildes flags */
+#define	F_GETFL		3	/* Get file flags */
+#define	F_SETFL		4	/* Set file flags */
+#define	F_GETLK		5	/* Get file lock */
+#define	F_SETLK		6	/* Set file lock */
+#define	F_SETLKW	7	/* Set file lock and wait */
+
+#define FD_CLOEXEC	1
+
+struct flock {
+	short	l_type;
+	short	l_whence;
+	off_t	l_start;
+	off_t	l_len;
+	pid_t	l_pid;
+};
+
+#define F_RDLCK		1	/* shared or read lock */
+#define F_UNLCK		2	/* unlock */
+#define F_WRLCK		3	/* exclusive or write lock */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int fcntl(int, int, ...);
+extern int open(const char *, int, ...);
+extern int creat(const char *, mode_t);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/fmt.h
@@ -1,0 +1,114 @@
+#ifndef _PLAN9_SOURCE
+  This header file is an extension to ANSI/POSIX
+#endif
+
+#ifndef __FMT_H_
+#define __FMT_H_
+#pragma src "/sys/src/ape/lib/fmt"
+#pragma lib "/$M/lib/ape/libfmt.a"
+
+#include <u.h>
+
+/*
+ * The authors of this software are Rob Pike and Ken Thompson.
+ *              Copyright (c) 2002 by Lucent Technologies.
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose without fee is hereby granted, provided that this entire notice
+ * is included in all copies of any software which is or includes a copy
+ * or modification of this software and in all copies of the supporting
+ * documentation for such software.
+ * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
+ * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHORS NOR LUCENT TECHNOLOGIES MAKE ANY
+ * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
+ * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
+ */
+
+#include <stdarg.h>
+#include <utf.h>
+
+typedef struct Fmt	Fmt;
+struct Fmt{
+	unsigned char	runes;		/* output buffer is runes or chars? */
+	void	*start;			/* of buffer */
+	void	*to;			/* current place in the buffer */
+	void	*stop;			/* end of the buffer; overwritten if flush fails */
+	int	(*flush)(Fmt *);	/* called when to == stop */
+	void	*farg;			/* to make flush a closure */
+	int	nfmt;			/* num chars formatted so far */
+	va_list	args;			/* args passed to dofmt */
+	int	r;			/* % format Rune */
+	int	width;
+	int	prec;
+	unsigned long	flags;
+};
+
+enum{
+	FmtWidth	= 1,
+	FmtLeft		= FmtWidth << 1,
+	FmtPrec		= FmtLeft << 1,
+	FmtSharp	= FmtPrec << 1,
+	FmtSpace	= FmtSharp << 1,
+	FmtSign		= FmtSpace << 1,
+	FmtZero		= FmtSign << 1,
+	FmtUnsigned	= FmtZero << 1,
+	FmtShort	= FmtUnsigned << 1,
+	FmtLong		= FmtShort << 1,
+	FmtVLong	= FmtLong << 1,
+	FmtComma	= FmtVLong << 1,
+	FmtByte		= FmtComma << 1,
+	FmtLDouble	= FmtByte << 1,
+
+	FmtFlag		= FmtLDouble << 1
+};
+
+#ifdef	__cplusplus
+extern "C" { 
+#endif
+
+extern	int	print(char*, ...);
+extern	char*	seprint(char*, char*, char*, ...);
+extern	char*	vseprint(char*, char*, char*, va_list);
+extern	int	snprint(char*, int, char*, ...);
+extern	int	vsnprint(char*, int, char*, va_list);
+extern	char*	smprint(char*, ...);
+extern	char*	vsmprint(char*, va_list);
+extern	int	sprint(char*, char*, ...);
+extern	int	fprint(int, char*, ...);
+extern	int	vfprint(int, char*, va_list);
+
+extern	int	runesprint(Rune*, char*, ...);
+extern	int	runesnprint(Rune*, int, char*, ...);
+extern	int	runevsnprint(Rune*, int, char*, va_list);
+extern	Rune*	runeseprint(Rune*, Rune*, char*, ...);
+extern	Rune*	runevseprint(Rune*, Rune*, char*, va_list);
+extern	Rune*	runesmprint(char*, ...);
+extern	Rune*	runevsmprint(char*, va_list);
+
+extern	int	fmtfdinit(Fmt*, int, char*, int);
+extern	int	fmtfdflush(Fmt*);
+extern	int	fmtstrinit(Fmt*);
+extern	char*	fmtstrflush(Fmt*);
+extern	int	runefmtstrinit(Fmt*);
+
+extern	int	quotestrfmt(Fmt *f);
+extern	void	quotefmtinstall(void);
+extern	int	(*fmtdoquote)(int);
+
+
+extern	int	fmtinstall(int, int (*)(Fmt*));
+extern	int	dofmt(Fmt*, char*);
+extern	int	fmtprint(Fmt*, char*, ...);
+extern	int	fmtvprint(Fmt*, char*, va_list);
+extern	int	fmtrune(Fmt*, int);
+extern	int	fmtstrcpy(Fmt*, char*);
+
+extern	double	fmtstrtod(const char *, char **);
+extern	double	fmtcharstod(int(*)(void*), void*);
+
+extern	void	werrstr(const char*, ...);
+
+#ifdef	__cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/grp.h
@@ -1,0 +1,26 @@
+#ifndef __GRP
+#define __GRP
+#ifndef _POSIX_SOURCE
+   This header file is not defined in pure ANSI
+#endif
+#pragma lib "/$M/lib/ape/libap.a"
+#include <sys/types.h>
+
+struct	group {
+	char	*gr_name;
+	gid_t	gr_gid;
+	char	**gr_mem;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct group *getgrgid(gid_t);
+extern struct group *getgrnam(const char *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/inttypes.h
@@ -1,0 +1,23 @@
+#ifndef _SUSV2_SOURCE
+#error "inttypes.h is SUSV2"
+#endif
+
+#ifndef _INTTYPES_H_
+#define _INTTYPES_H_ 1
+
+typedef int _intptr_t;
+typedef unsigned int _uintptr_t;
+
+
+typedef char int8_t;
+typedef short int16_t;
+typedef int int32_t;
+typedef long long int64_t;
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;
+typedef unsigned int uint32_t;
+typedef unsigned long long uint64_t;
+typedef _intptr_t intptr_t;
+typedef _uintptr_t uintptr_t;
+
+#endif
--- /dev/null
+++ b/sys/include/ape/keyboard.h
@@ -1,0 +1,6 @@
+#ifndef _PLAN9_SOURCE
+  This header file is an extension to ANSI/POSIX
+#endif
+
+#include "/sys/include/keyboard.h"
+
--- /dev/null
+++ b/sys/include/ape/lib9.h
@@ -1,0 +1,78 @@
+#ifndef __LIB9_H
+#define __LIB9_H
+#if !defined(_RESEARCH_SOURCE) && !defined(_PLAN9_SOURCE)
+    This header file is an extension to ANSI/POSIX
+#endif
+#pragma lib "/$M/lib/ape/lib9.a"
+
+#include <u.h>		/* ick; need Rune defined below */
+
+#define	MORDER	0x0003	/* mask for bits defining order of mounting */
+#define	MREPL	0x0000	/* mount replaces object */
+#define	MBEFORE	0x0001	/* mount goes before others in union directory */
+#define	MAFTER	0x0002	/* mount goes after others in union directory */
+#define	MCREATE	0x0004	/* permit creation in mounted directory */
+#define MRECOV	0x0008	/* perform recovery if mount channel is lost */
+#define MCACHE	0x0010	/* cache some data */
+#define	MMASK	0x0007	/* all bits on */
+
+#define	FORKPG		1
+#define	FORKEG		2
+#define	FORKFD		4
+
+#define	SG_RONLY	0040	/* read only */
+#define	SG_CEXEC	0100	/* detach on exec */
+
+enum
+{
+	RFNAMEG		= (1<<0),
+	RFENVG		= (1<<1),
+	RFFDG		= (1<<2),
+	RFNOTEG		= (1<<3),
+	RFPROC		= (1<<4),
+	RFMEM		= (1<<5),
+	RFNOWAIT	= (1<<6),
+	RFCNAMEG	= (1<<10),
+	RFCENVG		= (1<<11),
+	RFCFDG		= (1<<12),
+	RFREND		= (1<<13)
+};
+
+extern char *argv0;
+#define	ARGBEGIN	for((argv0||(argv0=*argv)),argv++,argc--;\
+			    argv[0] && argv[0][0]=='-' && argv[0][1];\
+			    argc--, argv++) {\
+				char *_args, *_argt;\
+				Rune _argc;\
+				_args = &argv[0][1];\
+				if(_args[0]=='-' && _args[1]==0){\
+					argc--; argv++; break;\
+				}\
+				_argc = 0;\
+				while(*_args && (_args += chartorune(&_argc, _args)))\
+				switch(_argc)
+#define	ARGEND		SET(_argt);USED(_argt,_argc,_args);}USED(argv, argc);
+#define	ARGF()		(_argt=_args, _args="",\
+				(*_argt? _argt: argv[1]? (argc--, *++argv): 0))
+#define	EARGF(x)	(_argt=_args, _args="",\
+				(*_argt? _argt: argv[1]? (argc--, *++argv): ((x), abort(), (char*)0)))
+
+#define	ARGC()		_argc
+
+extern	int	errstr(char*, unsigned int);
+extern	int	bind(char*, char*, int);
+extern	int	mount(int, int, char*, int, char*);
+extern	int	unmount(char*, char*);
+extern	int	rfork(int);
+extern	int	segattach(int, char*, void*, unsigned long);
+extern	int	segbrk(void*, void*);
+extern	int	segdetach(void*);
+extern	int	segflush(void*, unsigned long);
+extern	int	segfree(void*, unsigned long);
+extern	unsigned long	rendezvous(unsigned long, unsigned long);
+extern	unsigned long	getfcr(void);
+extern	unsigned long	getfsr(void);
+extern	void		setfcr(unsigned long);
+extern	void		setfsr(unsigned long);
+
+#endif
--- /dev/null
+++ b/sys/include/ape/libl.h
@@ -1,0 +1,15 @@
+#ifndef __LIBL_H
+#define __LIBL_H
+#ifndef _RESEARCH_SOURCE
+   This header file is not defined in ANSI or POSIX
+#endif
+#pragma lib "/$M/lib/ape/libl.a"
+
+extern int printable(int);
+extern void allprint(char);
+extern int yyracc(int);
+extern int yyreject(void);
+extern void yyless(int);
+extern int yywrap(void);
+
+#endif /* __LIBV_L */
--- /dev/null
+++ b/sys/include/ape/libnet.h
@@ -1,0 +1,20 @@
+#ifndef __LIBNET_H
+#define __LIBNET_H
+#ifndef _NET_EXTENSION
+   This header file is not defined in ANSI or POSIX
+#endif
+#pragma lib "/$M/lib/ape/libnet.a"
+
+#define NETPATHLEN 40
+
+extern	int	accept(int, char*);
+extern	int	announce(char*, char*);
+extern	int	dial(char*, char*, char*, int*);
+extern	int	hangup(int);
+extern	int	listen(char*, char*);
+extern	char*	netmkaddr(char*, char*, char*);
+extern	int	reject(int, char*, char *);
+
+extern char    dialerrstr[64];
+
+#endif /* __LIBNET_H */
--- /dev/null
+++ b/sys/include/ape/libv.h
@@ -1,0 +1,39 @@
+#ifndef __LIBV_H
+#define __LIBV_H
+#ifndef _RESEARCH_SOURCE
+   This header file is not defined in ANSI or POSIX
+#endif
+#pragma lib "/$M/lib/ape/libv.a"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern void	srand(unsigned int);
+extern int	rand(void);
+extern int	nrand(int);
+extern long	lrand(void);
+extern double	frand(void);
+
+extern char	*getpass(char *);
+extern int	tty_echoon(int);
+extern int	tty_echooff(int);
+
+extern int	min(int, int);
+extern int	max(int, int);
+
+extern void	_perror(char *);
+extern char	*_progname;
+
+extern int	nap(int);
+
+extern char	*setfields(char *);
+extern int	getfields(char *, char **, int);
+extern int	getmfields(char *, char **, int);
+
+
+#ifdef __cplusplus
+};
+#endif
+
+#endif /* __LIBV_H */
--- /dev/null
+++ b/sys/include/ape/limits.h
@@ -1,0 +1,85 @@
+#ifndef __LIMITS
+#define __LIMITS
+/* 8 bit chars (signed), 16 bit shorts, 32 bit ints/longs */
+
+#define CHAR_BIT	8
+#define MB_LEN_MAX	3
+
+#define UCHAR_MAX	0xff
+#define USHRT_MAX	0xffff
+#define UINT_MAX	0xffffffffU
+#define ULONG_MAX	0xffffffffUL
+
+#define CHAR_MAX	SCHAR_MAX
+#define SCHAR_MAX	0x7f
+#define SHRT_MAX	0x7fff
+#define INT_MAX		0x7fffffff
+#define LONG_MAX	0x7fffffffL
+
+#define CHAR_MIN	SCHAR_MIN
+#define SCHAR_MIN	(-SCHAR_MAX-1)
+#define SHRT_MIN	(-SHRT_MAX-1)
+#define INT_MIN		(-INT_MAX-1)
+#define LONG_MIN	(-LONG_MAX-1)
+
+#ifdef _POSIX_SOURCE
+
+#define _POSIX_AIO_LISTIO_MAX	2
+#define _POSIX_AIO_MAX			1
+#define _POSIX_ARG_MAX			4096
+#define _POSIX_CHILD_MAX		6
+#define	_POSIX_CLOCKRES_MIN		20000000
+#define	_POSIX_DELAYTIMER_MAX	32
+#define _POSIX_LINK_MAX			8
+#define _POSIX_MAX_CANON		255
+#define _POSIX_MAX_INPUT		255
+#define _POSIX_MQ_OPEN_MAX		8
+#define	_POSIX_MQ_PRIO_MAX		32
+#define _POSIX_NAME_MAX			14
+#define _POSIX_NGROUPS_MAX		0
+#define _POSIX_OPEN_MAX			16
+#define _POSIX_PATH_MAX			255
+#define _POSIX_PIPE_BUF			512
+#define	_POSIX_RTSIG_MAX		8
+#define	_POSIX_SEM_NSEMS_MAX	256
+#define	_POSIX_SEM_VALUE_MAX	32767
+#define	_POSIX_SIGQUEUE_MAX		32
+#define _POSIX_SSIZE_MAX		32767
+#define _POSIX_STREAM_MAX		8
+#define	_POSIX_TIMER_MAX		32
+#define _POSIX_TZNAME_MAX		3
+
+/* pedagogy: those that standard allows omitting are commented out */
+/*#define AIO_LIST_MAX _POSIX_AIO_LIST_MAX */
+/*#define AIO_MAX _POSIX_AIO_MAX */
+/*#define AIO_PRIO_DELTA_MAX 0 */
+/*#define ARG_MAX _POSIX_ARG_MAX */
+/*#define CHILD_MAX _POSIX_CHILD_MAX */
+/*#define DELAYTIMER_MAX _POSIX_DELAYTIMER_MAX */
+/*#define LINK_MAX _POSIX_LINK_MAX */
+/*#define MAX_CANON _POSIX_MAX_CANON */
+/*#define MAX_INPUT _POSIX_MAX_INPUT */
+/*#define MQ_OPEN_MAX _POSIX_MQ_OPEN_MAX */
+/*#define MQ_PRIO_MAX _POSIX_MQ_PRIO_MAX */
+/*#define NAME_MAX _POSIX_NAME_MAX */
+#define NGROUPS_MAX 10
+/*#define OPEN_MAX _POSIX_OPEN_MAX */
+/*#define PAGESIZE 1 */
+/*#define PATH_MAX _POSIX_PATH_MAX */
+/*#define PIPE_BUF _POSIX_PIPE_BUF */
+/*#define RTSIG_MAX _POSIX_RTSIG_MAX */
+/*#define SEM_NSEMS_MAX _POSIX_SEM_NSEMS_MAX */
+/*#define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX */
+/*#define SIGQUEUE_MAX _POSIX_SIGQUEUE_MAX */
+#define SSIZE_MAX LONG_MAX
+/*#define STREAM_MAX _POSIX_STREAM_MAX */
+/*#define TIMER_MAX _POSIX_TIMER_MAX */
+#define TZNAME_MAX _POSIX_TZNAME_MAX
+
+#ifdef _LIMITS_EXTENSION
+/* some things are just too big for pedagogy (X!) */
+#include <sys/limits.h>
+#endif
+#endif /* _POSIX_SOURCE */
+
+#endif /* __LIMITS */
--- /dev/null
+++ b/sys/include/ape/locale.h
@@ -1,0 +1,46 @@
+#ifndef __LOCALE
+#define __LOCALE
+#pragma lib "/$M/lib/ape/libap.a"
+
+#include <stddef.h>
+
+#define LC_ALL		0
+#define LC_COLLATE	1
+#define LC_CTYPE	2
+#define LC_MONETARY	3
+#define LC_NUMERIC	4
+#define LC_TIME		5
+
+struct lconv {
+	char *decimal_point;
+	char *thousands_sep;
+	char *grouping;
+	char *int_curr_symbol;
+	char *currency_symbol;
+	char *mon_decimal_point;
+	char *mon_thousands_sep;
+	char *mon_grouping;
+	char *positive_sign;
+	char *negative_sign;
+	char int_frac_digits;
+	char frac_digits;
+	char p_cs_precedes;
+	char p_sep_by_space;
+	char n_cs_precedes;
+	char n_sep_by_space;
+	char p_sign_posn;
+	char n_sign_posn;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern char *setlocale(int, const char *);
+extern struct lconv *localeconv(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __LOCALE */
--- /dev/null
+++ b/sys/include/ape/lock.h
@@ -1,0 +1,29 @@
+#if !defined(_RESEARCH_SOURCE) && !defined(_PLAN9_SOURCE)
+   This header file is an extension of ANSI/POSIX
+#endif
+
+#ifndef __LOCK_H
+#define __LOCK_H
+#pragma lib "/$M/lib/ape/libap.a"
+
+#include <u.h>
+
+typedef struct
+{
+	int	val;
+} Lock;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern	void	lock(Lock*);
+extern	void	unlock(Lock*);
+extern	int	canlock(Lock*);
+extern	int	tas(int*);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/mouse.h
@@ -1,0 +1,6 @@
+#ifndef _PLAN9_SOURCE
+  This header file is an extension to ANSI/POSIX
+#endif
+
+#include "/sys/include/mouse.h"
+
--- /dev/null
+++ b/sys/include/ape/netdb.h
@@ -1,0 +1,121 @@
+#ifndef __NETDB_H__
+#define __NETDB_H__
+
+#ifndef _BSD_EXTENSION
+    This header file is an extension to ANSI/POSIX
+#endif
+
+#pragma lib "/$M/lib/ape/libbsd.a"
+
+/*-
+ * Copyright (c) 1980, 1983, 1988 Regents of the University of California.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms are permitted
+ * provided that: (1) source distributions retain this entire copyright
+ * notice and comment, and (2) distributions including binaries display
+ * the following acknowledgement:  ``This product includes software
+ * developed by the University of California, Berkeley and its contributors''
+ * in the documentation or other materials provided with the distribution
+ * and in all advertising materials mentioning features or use of this
+ * software. Neither the name of the University nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ *	@(#)netdb.h	5.11 (Berkeley) 5/21/90
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Structures returned by network data base library.  All addresses are
+ * supplied in host order, and returned in network order (suitable for
+ * use in system calls).
+ */
+struct	hostent {
+	char	*h_name;	/* official name of host */
+	char	**h_aliases;	/* alias list */
+	int	h_addrtype;	/* host address type */
+	int	h_length;	/* length of address */
+	char	**h_addr_list;	/* list of addresses from name server */
+#define	h_addr	h_addr_list[0]	/* address, for backward compatiblity */
+};
+
+/*
+ * Assumption here is that a network number
+ * fits in 32 bits -- probably a poor one.
+ */
+struct	netent {
+	char		*n_name;	/* official name of net */
+	char		**n_aliases;	/* alias list */
+	int		n_addrtype;	/* net address type */
+	unsigned long	n_net;		/* network # */
+};
+
+struct	servent {
+	char	*s_name;	/* official service name */
+	char	**s_aliases;	/* alias list */
+	int	s_port;		/* port # */
+	char	*s_proto;	/* protocol to use */
+};
+
+struct	protoent {
+	char	*p_name;	/* official protocol name */
+	char	**p_aliases;	/* alias list */
+	int	p_proto;	/* protocol # */
+};
+
+/* from 4.0 RPCSRC */
+struct rpcent {
+	char	*r_name;	/* name of server for this rpc program */
+	char	**r_aliases;	/* alias list */
+	int	r_number;	/* rpc program number */
+};
+
+extern struct hostent	*gethostbyname(const char *),
+			*gethostbyaddr(const void *, int, int),
+			*gethostent(void);
+extern struct netent	*getnetbyname(const char *),
+			*getnetbyaddr(long, int),
+			*getnetent(void);
+extern struct servent	*getservbyname(const char *, const char *),
+			*getservbyport(int, const char *),
+			*getservent(void);
+extern struct protoent	*getprotobyname(const char *),
+			*getprotobynumber(int),
+			*getprotoent(void);
+extern struct rpcent	*getrpcbyname(const char *), 
+			*getrpcbynumber(int), 
+			*getrpcent(void);
+extern void sethostent(int),  endhostent(void),
+	    setnetent(int),   endnetent(void),
+	    setservent(int),  endservent(void),
+	    setprotoent(int), endprotoent(void),
+	    setrpcent(int),   endrpcent(void);
+
+/*
+ * Error return codes from gethostbyname() and gethostbyaddr()
+ * (left in extern int h_errno).
+ */
+extern int h_errno;
+extern void herror(const char *);
+extern char *hstrerror(int);
+
+#define	HOST_NOT_FOUND	1 /* Authoritative Answer Host not found */
+#define	TRY_AGAIN	2 /* Non-Authoritive Host not found, or SERVERFAIL */
+#define	NO_RECOVERY	3 /* Non recoverable errors, FORMERR, REFUSED, NOTIMP */
+#define	NO_DATA		4 /* Valid name, no data record of requested type */
+#define	NO_ADDRESS	NO_DATA		/* no address, look for MX record */
+
+#define __HOST_SVC_NOT_AVAIL 99		/* libc internal use only */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !__NETDB_H__ */
--- /dev/null
+++ b/sys/include/ape/netinet/in.h
@@ -1,0 +1,147 @@
+#ifndef __netinet_in__
+#define __netinet_in__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Copyright (c) 1982, 1986, 1990 Regents of the University of California.
+ * All rights reserved.
+ *
+ * Redistribution is only permitted until one year after the first shipment
+ * of 4.4BSD by the Regents.  Otherwise, redistribution and use in source and
+ * binary forms are permitted provided that: (1) source distributions retain
+ * this entire copyright notice and comment, and (2) distributions including
+ * binaries display the following acknowledgement:  This product includes
+ * software developed by the University of California, Berkeley and its
+ * contributors'' in the documentation or other materials provided with the
+ * distribution and in all advertising materials mentioning features or use
+ * of this software.  Neither the name of the University nor the names of
+ * its contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ * THIS SOFTWARE IS PROVIDED AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ *	@(#)in.h	7.10 (Berkeley) 6/28/90 plus MULTICAST 1.1
+ */
+
+/*
+ * Constants and structures defined by the internet system,
+ * Per RFC 790, September 1981.
+ */
+
+/*
+ * Protocols
+ */
+#define	IPPROTO_IP		0		/* dummy for IP */
+#define	IPPROTO_ICMP		1		/* control message protocol */
+#define	IPPROTO_GGP		3		/* gateway^2 (deprecated) */
+#define	IPPROTO_TCP		6		/* tcp */
+#define	IPPROTO_EGP		8		/* exterior gateway protocol */
+#define	IPPROTO_PUP		12		/* pup */
+#define	IPPROTO_UDP		17		/* user datagram protocol */
+#define	IPPROTO_IDP		22		/* xns idp */
+#define	IPPROTO_TP		29 		/* tp-4 w/ class negotiation */
+#define	IPPROTO_EON		80		/* ISO cnlp */
+
+#define	IPPROTO_RAW		255		/* raw IP packet */
+#define	IPPROTO_MAX		256
+
+
+/*
+ * Local port number conventions:
+ * Ports < IPPORT_RESERVED are reserved for
+ * privileged processes (e.g. root).
+ * Ports > IPPORT_USERRESERVED are reserved
+ * for servers, not necessarily privileged.
+ */
+#define	IPPORT_RESERVED		1024
+#define	IPPORT_USERRESERVED	5000
+
+/*
+ * Internet address (a structure for historical reasons)
+ */
+struct in_addr {
+	unsigned long s_addr;
+};
+
+/*
+ * Definitions of bits in internet address integers.
+ * On subnets, the decomposition of addresses to host and net parts
+ * is done according to subnet mask, not the masks here.
+ */
+#define	IN_CLASSA(i)		(((long)(i) & 0x80000000) == 0)
+#define	IN_CLASSA_NET		0xff000000
+#define	IN_CLASSA_NSHIFT	24
+#define	IN_CLASSA_HOST		0x00ffffff
+#define	IN_CLASSA_MAX		128
+
+#define	IN_CLASSB(i)		(((long)(i) & 0xc0000000) == 0x80000000)
+#define	IN_CLASSB_NET		0xffff0000
+#define	IN_CLASSB_NSHIFT	16
+#define	IN_CLASSB_HOST		0x0000ffff
+#define	IN_CLASSB_MAX		65536
+
+#define	IN_CLASSC(i)		(((long)(i) & 0xe0000000) == 0xc0000000)
+#define	IN_CLASSC_NET		0xffffff00
+#define	IN_CLASSC_NSHIFT	8
+#define	IN_CLASSC_HOST		0x000000ff
+
+#define	IN_CLASSD(i)		(((long)(i) & 0xf0000000) == 0xe0000000)
+#define	IN_MULTICAST(i)		IN_CLASSD(i)
+
+#define	IN_EXPERIMENTAL(i)	(((long)(i) & 0xe0000000) == 0xe0000000)
+#define	IN_BADCLASS(i)		(((long)(i) & 0xf0000000) == 0xf0000000)
+
+#define	INADDR_ANY		(unsigned long)0x00000000
+#define	INADDR_BROADCAST	(unsigned long)0xffffffff	/* must be masked */
+#define INADDR_NONE		(unsigned long)0xffffffff	/* -1 return */
+
+#define	IN_LOOPBACKNET		127			/* official! */
+
+/*
+ * Socket address, internet style.
+ */
+struct sockaddr_in {
+	short	sin_family;
+	unsigned short	sin_port;
+	struct	in_addr sin_addr;
+	char	sin_zero[8];
+};
+
+/*
+ * Structure used to describe IP options.
+ * Used to store options internally, to pass them to a process,
+ * or to restore options retrieved earlier.
+ * The ip_dst is used for the first-hop gateway when using a source route
+ * (this gets put into the header proper).
+ */
+struct ip_opts {
+	struct	in_addr ip_dst;		/* first hop, 0 w/o src rt */
+	char	ip_opts[40];		/* actually variable in size */
+};
+
+/*
+ * Options for use with [gs]etsockopt at the IP level.
+ * First word of comment is data type; bool is stored in int.
+ */
+#define	IP_OPTIONS	1	/* buf/ip_opts; set/get IP per-packet options */
+#define	IP_HDRINCL	7	/* int; header is included with data (raw) */
+#define	IP_TOS		8	/* int; IP type of service and precedence */
+#define	IP_TTL		9	/* int; IP time to live */
+
+extern unsigned long	ntohl(unsigned long x);
+extern unsigned short	ntohs(unsigned short x);
+extern unsigned long	htonl(unsigned long x);
+extern unsigned short	htons(unsigned short x);
+extern unsigned long	inet_addr(char*);
+extern char*		inet_ntoa(struct in_addr);
+extern unsigned long	nptohl(void*);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __netinet_in__ */
--- /dev/null
+++ b/sys/include/ape/pwd.h
@@ -1,0 +1,28 @@
+#ifndef __PWD
+#define __PWD
+#ifndef _POSIX_SOURCE
+   This header file is not defined in pure ANSI
+#endif
+#pragma lib "/$M/lib/ape/libap.a"
+#include <sys/types.h>
+
+struct passwd {
+	char	*pw_name;
+	uid_t	pw_uid;
+	gid_t	pw_gid;
+	char	*pw_dir;
+	char	*pw_shell;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct passwd *getpwuid(uid_t);
+extern struct passwd *getpwnam(const char *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/qlock.h
@@ -1,0 +1,41 @@
+#ifndef _PLAN9_SOURCE
+  This header file is an extension to ANSI/POSIX
+#endif
+
+#ifndef __QLOCK_H_
+#define __QLOCK_H_
+#pragma lib "/$M/lib/ape/lib9.a"
+
+#include <u.h>
+#include <lock.h>
+
+typedef struct QLp QLp;
+struct QLp
+{
+	int	inuse;
+	QLp	*next;
+	char	state;
+};
+
+typedef
+struct QLock
+{
+	Lock	lock;
+	int	locked;
+	QLp	*head;
+	QLp 	*tail;
+} QLock;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern	void	qlock(QLock*);
+extern	void	qunlock(QLock*);
+extern	int	canqlock(QLock*);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/regexp.h
@@ -1,0 +1,77 @@
+#ifndef __REGEXP_H
+#define __REGEXP_H
+#ifndef _REGEXP_EXTENSION
+    This header file is an extension to ANSI/POSIX
+#endif
+#pragma lib "/$M/lib/ape/libregexp.a"
+
+#ifdef	UTF
+#define	Runeself	0xA0
+#else
+#define	Runeself	0
+#endif
+
+typedef struct Resub		Resub;
+typedef struct Reclass		Reclass;
+typedef struct Reinst		Reinst;
+typedef struct Reprog		Reprog;
+
+/*
+ *	Sub expression matches
+ */
+struct Resub{
+	union
+	{
+		char *sp;
+		wchar_t *rsp;
+	} s;
+	union
+	{
+		char *ep;
+		wchar_t *rep;
+	} e;
+};
+
+/*
+ *	character class, each pair of rune's defines a range
+ */
+struct Reclass{
+	wchar_t	*end;
+	wchar_t	spans[64];
+};
+
+/*
+ *	Machine instructions
+ */
+struct Reinst{
+	int	type;			/* < 0200 ==> literal, otherwise action */
+	union	{
+		Reclass	*cp;		/* class pointer */
+		wchar_t	r;		/* character */
+		int	subid;		/* sub-expression id for RBRA and LBRA */
+		Reinst	*right;		/* right child of OR */
+	} r;
+	union {	/* regexp relies on these two being in the same union */
+		Reinst *left;		/* left child of OR */
+		Reinst *next;		/* next instruction for CAT & LBRA */
+	} l;
+};
+
+/*
+ *	Reprogram definition
+ */
+struct Reprog{
+	Reinst	*startinst;	/* start pc */
+	Reclass	class[16];	/* .data */
+	Reinst	firstinst[5];	/* .text */
+};
+
+extern Reprog	*regcomp(char*);
+extern Reprog	*regcomplit(char*);
+extern Reprog	*regcompnl(char*);
+extern void	regerror(char*);
+extern int	regexec(Reprog*, char*, Resub*, int);
+extern void	regsub(char*, char*, int, Resub*, int);
+extern int	rregexec(Reprog*, wchar_t*, Resub*, int);
+extern void	rregsub(wchar_t*, wchar_t*, int, Resub*, int);
+#endif
--- /dev/null
+++ b/sys/include/ape/select.h
@@ -1,0 +1,34 @@
+#ifndef __SELECT_H
+#define __SELECT_H
+#ifndef _BSD_EXTENSION
+    This header file is an extension to ANSI/POSIX
+#endif
+#pragma lib "/$M/lib/ape/libap.a"
+
+#ifndef _FD_SET_T
+#define _FD_SET_T
+/* BSD select, and adjunct types and macros */
+
+/* assume 96 fds is sufficient for fdset size */
+
+typedef struct fd_set {
+	long fds_bits[3];
+} fd_set;
+
+#define FD_SET(n,p)	((p)->fds_bits[(n)>>5] |= (1 << ((n) &0x1f)))
+#define FD_CLR(n,p)	((p)->fds_bits[(n)>>5] &= ~(1 << ((n) &0x1f)))
+#define FD_ISSET(n,p)	((p)->fds_bits[(n)>>5] & (1 << ((n) &0x1f)))
+#define FD_ZERO(p)	((p)->fds_bits[0] =0, (p)->fds_bits[1] =0, (p)->fds_bits[2] =0)
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int select(int, fd_set*, fd_set*, fd_set*, struct timeval *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/setjmp.h
@@ -1,0 +1,26 @@
+#ifndef __SETJMP_H
+#define __SETJMP_H
+#pragma lib "/$M/lib/ape/libap.a"
+
+typedef int jmp_buf[10];
+#ifdef _POSIX_SOURCE
+typedef int sigjmp_buf[10];
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int setjmp(jmp_buf);
+extern void longjmp(jmp_buf, int);
+
+#ifdef _POSIX_SOURCE
+extern int sigsetjmp(sigjmp_buf, int);
+extern void siglongjmp(sigjmp_buf, int);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __SETJMP_H */
--- /dev/null
+++ b/sys/include/ape/signal.h
@@ -1,0 +1,95 @@
+#ifndef __SIGNAL_H
+#define __SIGNAL_H
+#pragma lib "/$M/lib/ape/libap.a"
+
+typedef int sig_atomic_t;
+
+/*
+ * We don't give arg types for signal handlers, in spite of ANSI requirement
+ * that it be 'int' (the signal number), because some programs need an
+ * additional context argument.  So the real type of signal handlers is
+ *      void handler(int sig, char *, struct Ureg *)
+ * where the char * is the Plan 9 message and Ureg is defined in <ureg.h>
+ */
+#define SIG_DFL ((void (*)())0)
+#define SIG_ERR ((void (*)())-1)
+#define SIG_IGN ((void (*)())1)
+
+#define	SIGHUP	1	/* hangup */
+#define	SIGINT	2	/* interrupt */
+#define	SIGQUIT	3	/* quit */
+#define	SIGILL	4	/* illegal instruction (not reset when caught)*/
+#define SIGABRT 5	/* used by abort */
+#define	SIGFPE	6	/* floating point exception */
+#define	SIGKILL	7	/* kill (cannot be caught or ignored) */
+#define	SIGSEGV	8	/* segmentation violation */
+#define	SIGPIPE	9	/* write on a pipe with no one to read it */
+#define	SIGALRM	10	/* alarm clock */
+#define	SIGTERM	11	/* software termination signal from kill */
+#define	SIGUSR1	12	/* user defined signal 1 */
+#define	SIGUSR2	13	/* user defined signal 2 */
+#define	SIGBUS	14	/* bus error */
+
+/* The following symbols must be defined, but the signals needn't be supported */
+#define SIGCHLD	15	/* child process terminated or stopped */
+#define SIGCONT 16	/* continue if stopped */
+#define SIGSTOP 17	/* stop */
+#define SIGTSTP	18	/* interactive stop */
+#define SIGTTIN	19	/* read from ctl tty by member of background */
+#define SIGTTOU	20	/* write to ctl tty by member of background */
+
+#ifdef _BSD_EXTENSION
+#define NSIG 21
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern void (*signal(int, void (*)()))();
+extern int raise(int);
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef _POSIX_SOURCE
+
+typedef long sigset_t;
+struct sigaction {
+	void		(*sa_handler)();
+	sigset_t	sa_mask;
+	int		sa_flags;
+};
+/* values for sa_flags */
+#define SA_NOCLDSTOP	1
+
+/* first argument to sigprocmask */
+#define SIG_BLOCK	1
+#define SIG_UNBLOCK	2
+#define SIG_SETMASK	3
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef __TYPES_H
+extern int kill(pid_t, int);
+#endif
+extern int sigemptyset(sigset_t *);
+extern int sigfillset(sigset_t *);
+extern int sigaddset(sigset_t *, int);
+extern int sigdelset(sigset_t *, int);
+extern int sigismember(const sigset_t *, int);
+extern int sigaction(int, const struct sigaction *, struct sigaction *);
+extern int sigprocmask(int, sigset_t *, sigset_t *);
+extern int sigpending(sigset_t *);
+extern int sigsuspend(const sigset_t *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _POSIX_SOURCE */
+
+#endif /* __SIGNAL_H */
--- /dev/null
+++ b/sys/include/ape/stddef.h
@@ -1,0 +1,23 @@
+#ifndef __STDDEF_H
+#define __STDDEF_H
+
+#ifndef NULL
+#ifdef __cplusplus
+#define NULL 0
+#else
+#define NULL ((void*)0)
+#endif
+#endif
+#define offsetof(ty,mem) ((size_t) &(((ty *)0)->mem))
+
+typedef long ptrdiff_t;
+#ifndef _SIZE_T
+#define _SIZE_T
+typedef unsigned long size_t;
+#endif
+#ifndef _WCHAR_T
+#define _WCHAR_T
+typedef unsigned short wchar_t;
+#endif
+
+#endif /* __STDDEF_H */
--- /dev/null
+++ b/sys/include/ape/stdio.h
@@ -1,0 +1,157 @@
+#ifndef	_STDIO_H_
+#define	_STDIO_H_
+#pragma lib "/$M/lib/ape/libap.a"
+
+/*
+ * pANS stdio.h
+ */
+#include <stdarg.h>
+#include <stddef.h>
+#include <sys/types.h>
+/*
+ * According to X3J11, there is only one i/o buffer
+ * and it must not be occupied by both input and output data.
+ *	If rp<wp, we must have state==RD and
+ *	if wp<rp, we must have state==WR, so that getc and putc work correctly.
+ *	On open, rp, wp and buf are set to 0, so first getc or putc will call _IO_getc
+ *	or _IO_putc, which will allocate the buffer.
+ *	If setvbuf(., ., _IONBF, .) is called, bufl is set to 0 and
+ *	buf, rp and wp are pointed at unbuf.
+ *	If setvbuf(., ., _IOLBF, .) is called, _IO_putc leaves wp and rp pointed at the
+ *	end of the buffer so that it can be called on each putc to check whether it's got
+ *	a newline.  This nonsense is in order to avoid impacting performance of the other
+ *	buffering modes more than necessary -- putting the test in putc adds many
+ *	instructions that are wasted in non-_IOLBF mode:
+ *	#define putc(c, f)	(_IO_ctmp=(c),\
+ *				(f)->wp>=(f)->rp || (f)->flags&LINEBUF && _IO_ctmp=='\n'\
+ *					?_IO_putc(_IO_ctmp, f)\
+ *					:*(f)->wp++=_IO_ctmp)
+ *				
+ */
+typedef struct{
+	int fd;		/* UNIX file pointer */
+	char flags;	/* bits for must free buffer on close, line-buffered */
+	char state;	/* last operation was read, write, position, error, eof */
+	char *buf;	/* pointer to i/o buffer */
+	char *rp;	/* read pointer (or write end-of-buffer) */
+	char *wp;	/* write pointer (or read end-of-buffer) */
+	char *lp;	/* actual write pointer used when line-buffering */
+	size_t bufl;	/* actual length of buffer */
+	char unbuf[1];	/* tiny buffer for unbuffered io (used for ungetc?) */
+}FILE;
+typedef long long fpos_t;
+#ifndef NULL
+#ifdef __cplusplus
+#define NULL 0
+#else
+#define NULL ((void*)0)
+#endif
+#endif
+/*
+ * Third arg of setvbuf
+ */
+#define	_IOFBF	1			/* block-buffered */
+#define	_IOLBF	2			/* line-buffered */
+#define	_IONBF	3			/* unbuffered */
+#define	BUFSIZ	4096			/* size of setbuf buffer */
+#define	EOF	(-1)			/* returned on end of file */
+#define	FOPEN_MAX	90		/* max files open */
+#define	FILENAME_MAX	BUFSIZ		/* silly filename length */
+#define	L_tmpnam	20		/* sizeof "/tmp/abcdefghij9999 */
+#define	L_cuserid	32		/* maximum size user name */
+#define	L_ctermid	32		/* size of name of controlling tty */
+#define	SEEK_CUR	1
+#define	SEEK_END	2
+#define	SEEK_SET	0
+#define	TMP_MAX		64		/* very hard to set correctly */
+#define	stderr	(&_IO_stream[2])
+#define	stdin	(&_IO_stream[0])
+#define	stdout	(&_IO_stream[1])
+#define	_IO_CHMASK	0377		/* mask for 8 bit characters */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int remove(const char *);
+extern int rename(const char *, const char *);
+extern FILE *tmpfile(void);
+extern char *tmpnam(char *);
+extern int fclose(FILE *);
+extern int fflush(FILE *);
+extern FILE *fopen(const char *, const char *);
+extern FILE *freopen(const char *, const char *, FILE *);
+extern void setbuf(FILE *, char *);
+extern int setvbuf(FILE *, char *, int, size_t);
+extern int fprintf(FILE *, const char *, ...);
+extern int fscanf(FILE *, const char *, ...);
+extern int printf(const char *, ...);
+extern int scanf(const char *, ...);
+extern int sprintf(char *, const char *, ...);
+#ifdef _C99_SNPRINTF_EXTENSION /* user knows about c99 out-of-bounds returns */
+extern int snprintf(char *, size_t, const char *, ...);
+extern int vsnprintf(char *, size_t, const char *, va_list);
+#else
+/* draw errors on any attempt to use *snprintf value so old code gets changed */
+extern void snprintf(char *, size_t, const char *, ...);
+extern void vsnprintf(char *, size_t, const char *, va_list);
+#endif
+extern int sscanf(const char *, const char *, ...);
+extern int vfprintf(FILE *, const char *, va_list);
+extern int vprintf(const char *, va_list);
+extern int vsprintf(char *, const char *, va_list);
+extern int vfscanf(FILE *, const char *, va_list);
+extern int fgetc(FILE *);
+extern char *fgets(char *, int, FILE *);
+extern int fputc(int, FILE *);
+extern int fputs(const char *, FILE *);
+extern int getc(FILE *);
+#define	getc(f)	((f)->rp>=(f)->wp?_IO_getc(f):*(f)->rp++&_IO_CHMASK)
+extern int _IO_getc(FILE *f);
+extern int getchar(void);
+#define	getchar()	getc(stdin)
+extern char *gets(char *);
+extern int putc(int, FILE *);
+#define	putc(c, f) ((f)->wp>=(f)->rp?_IO_putc(c, f):(*(f)->wp++=c)&_IO_CHMASK)
+extern int _IO_putc(int, FILE *);
+extern int putchar(int);
+#define	putchar(c)	putc(c, stdout)
+extern int puts(const char *);
+extern int ungetc(int, FILE *);
+extern size_t fread(void *, size_t, size_t, FILE *);
+extern size_t fwrite(const void *, size_t, size_t, FILE *);
+extern int fgetpos(FILE *, fpos_t *);
+extern int fseek(FILE *, long, int);
+extern int fseeko(FILE *, off_t, int);
+extern int fsetpos(FILE *, const fpos_t *);
+extern long ftell(FILE *);
+extern off_t ftello(FILE *);
+extern void rewind(FILE *);
+extern void clearerr(FILE *);
+extern int feof(FILE *);
+extern int ferror(FILE *);
+extern void perror(const char *);
+extern FILE _IO_stream[FOPEN_MAX];
+
+#ifdef _POSIX_SOURCE
+extern int fileno(FILE *);
+extern FILE* fdopen(int, const char*);
+extern char *ctermid(char *);
+#endif
+
+#ifdef _REENTRANT_SOURCE
+extern char *tmpnam_r(char *);
+extern char *ctermid_r(char *);
+#endif
+
+#ifdef _BSD_EXTENSION
+#pragma lib "/$M/lib/ape/libbsd.a"
+extern FILE *popen(char *, char *);
+extern int	pclose(FILE *);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/stdlib.h
@@ -1,0 +1,55 @@
+#ifndef __STDLIB_H
+#define __STDLIB_H
+#pragma lib "/$M/lib/ape/libap.a"
+
+#include <stddef.h>
+
+#define EXIT_FAILURE 1
+#define EXIT_SUCCESS 0
+#define MB_CUR_MAX 3
+#define RAND_MAX 32767
+
+typedef struct { int quot, rem; } div_t;
+typedef struct { long quot, rem; } ldiv_t;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern double atof(const char *);
+extern int atoi(const char *);
+extern long int atol(const char *);
+extern long long atoll(const char *);
+extern double strtod(const char *, char **);
+extern long int strtol(const char *, char **, int);
+extern unsigned long int strtoul(const char *, char **, int);
+extern long long int strtoll(const char *, char **, int);
+extern unsigned long long int strtoull(const char *, char **, int);
+extern int rand(void);
+extern void srand(unsigned int seed);
+extern void *calloc(size_t, size_t);
+extern void free(void *);
+extern void *malloc(size_t);
+extern void *realloc(void *, size_t);
+extern void abort(void);
+extern int atexit(void (*func)(void));
+extern void exit(int);
+extern char *getenv(const char *);
+extern int system(const char *);
+extern void *bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *));
+extern void qsort(void *, size_t, size_t, int (*)(const void *, const void *));
+extern int abs(int);
+extern div_t div(int, int);
+extern long int labs(long int);
+extern ldiv_t ldiv(long int, long int);
+extern int mblen(const char *, size_t);
+extern int mbtowc(wchar_t *, const char *, size_t);
+extern int wctomb(char *, wchar_t);
+extern size_t mbstowcs(wchar_t *, const char *, size_t);
+extern size_t wcstombs(char *, const wchar_t *, size_t);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __STDLIB_H */
--- /dev/null
+++ b/sys/include/ape/string.h
@@ -1,0 +1,47 @@
+#ifndef __STRING_H_
+#define __STRING_H_
+#pragma lib "/$M/lib/ape/libap.a"
+
+#include <stddef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern void *memcpy(void *, const void *, size_t);
+extern void *memmove(void *, const void *, size_t);
+extern char *strcpy(char *, const char *);
+extern char *strncpy(char *, const char *, size_t);
+extern char *strcat(char *, const char *);
+extern char *strncat(char *, const char *, size_t);
+extern int memcmp(const void *, const void *, size_t);
+extern int strcmp(const char *, const char *);
+extern int strcoll(const char *, const char *);
+extern int strncmp(const char *, const char *, size_t);
+extern size_t strxfrm(char *, const char *, size_t);
+extern void *memchr(const void *, int, size_t);
+extern char *strchr(const char *, int);
+extern size_t strcspn(const char *, const char *);
+extern char *strpbrk(const char *, const char *);
+extern char *strrchr(const char *, int);
+extern size_t strspn(const char *, const char *);
+extern char *strstr(const char *, const char *);
+extern char *strtok(char *, const char *);
+extern void *memset(void *, int, size_t);
+extern char *strerror(int);
+extern size_t strlen(const char *);
+
+#ifdef _REENTRANT_SOURCE
+extern char *strerror_r(int, const char *, int);
+extern char *strtok_r(char *, const char *, char **);
+#endif
+
+#ifdef _BSD_EXTENSION
+#include <bsd.h>
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/sys/ioctl.h
@@ -1,0 +1,22 @@
+#ifndef __IOCTL_H__
+#define __IOCTL_H__
+
+#ifndef _BSD_EXTENSION
+    This header file is an extension to ANSI/POSIX
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* FIONREAD: return number of bytes readable in *(long*)arg */
+#define FIONREAD 1
+
+int ioctl(int, unsigned long, void*);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* !__IOCTL_H__ */
--- /dev/null
+++ b/sys/include/ape/sys/limits.h
@@ -1,0 +1,28 @@
+/*
+	local limits
+*/
+
+#undef	ARG_MAX
+#define	ARG_MAX		16384
+#undef	CHILD_MAX
+#define	CHILD_MAX	75
+#undef	OPEN_MAX
+#define	OPEN_MAX	96
+#undef	LINK_MAX
+#define	LINK_MAX	1
+#undef	NAME_MAX
+#define	NAME_MAX	27
+#undef	PATH_MAX
+#define	PATH_MAX	1023
+#undef	NGROUPS_MAX
+#define	NGROUPS_MAX	32
+#undef	MAX_CANON
+#define	MAX_CANON	1023
+#undef	MAX_INPUT
+#define	MAX_INPUT	1023
+#undef	PIPE_BUF
+#define	PIPE_BUF	8192
+
+#define	_POSIX_SAVED_IDS		1
+#define	_POSIX_CHOWN_RESTRICTED		1
+#define	_POSIX_NO_TRUNC			1
--- /dev/null
+++ b/sys/include/ape/sys/param.h
@@ -1,0 +1,18 @@
+#ifndef __PARAM_H__
+#define __PARAM_H__
+
+#ifndef _BSD_EXTENSION
+    This header file is an extension to ANSI/POSIX
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define NOFILES_MAX 100
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !__PARAM_H__ */
--- /dev/null
+++ b/sys/include/ape/sys/pty.h
@@ -1,0 +1,18 @@
+/*
+ * Pty support
+ */
+#ifndef __SYS_PTY_H__
+#define __SYS_PTY_H__
+
+#ifndef _BSD_EXTENSION
+    This header file is an extension to ANSI/POSIX
+#endif
+
+#pragma lib "/$M/lib/ape/libbsd.a"
+
+char*	ptsname(int);
+char*	ptmname(int);
+
+int	_getpty(void);
+
+#endif /* !__SYS_UIO_H__ */
--- /dev/null
+++ b/sys/include/ape/sys/resource.h
@@ -1,0 +1,29 @@
+#ifndef __RESOURCE_H__
+#define __RESOURCE_H__
+
+#ifndef _BSD_EXTENSION
+    This header file is an extension to ANSI/POSIX
+#endif
+
+struct rusage {
+	struct timeval ru_utime;	/* user time used */
+	struct timeval ru_stime;	/* system time used */
+	long	ru_maxrss;		/* max resident set size */
+#define	ru_first	ru_ixrss
+	long	ru_ixrss;		/* integral shared memory size */
+	long	ru_idrss;		/* integral unshared data " */
+	long	ru_isrss;		/* integral unshared stack " */
+	long	ru_minflt;		/* page reclaims */
+	long	ru_majflt;		/* page faults */
+	long	ru_nswap;		/* swaps */
+	long	ru_inblock;		/* block input operations */
+	long	ru_oublock;		/* block output operations */
+	long	ru_msgsnd;		/* messages sent */
+	long	ru_msgrcv;		/* messages received */
+	long	ru_nsignals;		/* signals received */
+	long	ru_nvcsw;		/* voluntary context switches */
+	long	ru_nivcsw;		/* involuntary " */
+#define	ru_last		ru_nivcsw
+};
+
+#endif /* !__RESOURCE_H__ */
--- /dev/null
+++ b/sys/include/ape/sys/select.h
@@ -1,0 +1,34 @@
+#ifndef __SELECT_H
+#define __SELECT_H
+#ifndef _BSD_EXTENSION
+    This header file is an extension to ANSI/POSIX
+#endif
+#pragma lib "/$M/lib/ape/libap.a"
+
+#ifndef _FD_SET_T
+#define _FD_SET_T
+/* BSD select, and adjunct types and macros */
+
+/* assume 96 fds is sufficient for fdset size */
+
+typedef struct fd_set {
+	long fds_bits[3];
+} fd_set;
+
+#define FD_SET(n,p)	((p)->fds_bits[(n)>>5] |= (1 << ((n) &0x1f)))
+#define FD_CLR(n,p)	((p)->fds_bits[(n)>>5] &= ~(1 << ((n) &0x1f)))
+#define FD_ISSET(n,p)	((p)->fds_bits[(n)>>5] & (1 << ((n) &0x1f)))
+#define FD_ZERO(p)	((p)->fds_bits[0] =0, (p)->fds_bits[1] =0, (p)->fds_bits[2] =0)
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int select(int, fd_set*, fd_set*, fd_set*, struct timeval *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/sys/socket.h
@@ -1,0 +1,196 @@
+#ifndef __SYS_SOCKET_H__
+#define __SYS_SOCKET_H__
+
+#ifndef _BSD_EXTENSION
+    This header file is an extension to ANSI/POSIX
+#endif
+
+#pragma lib "/$M/lib/ape/libbsd.a"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Copyright (c) 1982,1985, 1986 Regents of the University of California.
+ * All rights reserved.  The Berkeley software License Agreement
+ * specifies the terms and conditions for redistribution.
+ *
+ *	@(#)socket.h	7.1 (Berkeley) 6/4/86
+ */
+
+/*
+ * Definitions related to sockets: types, address families, options.
+ */
+
+/*
+ * Types
+ */
+#define	SOCK_STREAM	1		/* stream socket */
+#define	SOCK_DGRAM	2		/* datagram socket */
+#define	SOCK_RAW	3		/* raw-protocol interface */
+#define	SOCK_RDM	4		/* reliably-delivered message */
+#define	SOCK_SEQPACKET	5		/* sequenced packet stream */
+
+/*
+ * Option flags per-socket.
+ */
+#ifdef HAVE_SOCK_OPTS
+#define	SO_DEBUG	0x0001		/* turn on debugging info recording */
+#define	SO_ACCEPTCONN	0x0002		/* socket has had listen() */
+#define	SO_REUSEADDR	0x0004		/* allow local address reuse */
+#define	SO_KEEPALIVE	0x0008		/* keep connections alive */
+#define	SO_DONTROUTE	0x0010		/* just use interface addresses */
+#define	SO_BROADCAST	0x0020		/* permit sending of broadcast msgs */
+#define	SO_USELOOPBACK	0x0040		/* bypass hardware when possible */
+#define	SO_LINGER	0x0080		/* linger on close if data present */
+#define	SO_OOBINLINE	0x0100		/* leave received OOB data in line */
+#endif
+
+/*
+ * Additional options, not kept in so_options.
+ */
+#define SO_SNDBUF	0x1001		/* send buffer size */
+#define SO_RCVBUF	0x1002		/* receive buffer size */
+#define SO_SNDLOWAT	0x1003		/* send low-water mark */
+#define SO_RCVLOWAT	0x1004		/* receive low-water mark */
+#define SO_SNDTIMEO	0x1005		/* send timeout */
+#define SO_RCVTIMEO	0x1006		/* receive timeout */
+#define	SO_ERROR	0x1007		/* get error status and clear */
+#define	SO_TYPE		0x1008		/* get socket type */
+
+/*
+ * Structure used for manipulating linger option.
+ */
+struct	linger {
+	int	l_onoff;		/* option on/off */
+	int	l_linger;		/* linger time */
+};
+
+/*
+ * Level number for (get/set)sockopt() to apply to socket itself.
+ */
+#define	SOL_SOCKET	0xffff		/* options for socket level */
+
+/*
+ * Address families.
+ * XTP really is not an address family, but is included here to take
+ * up space, because other AF_ entries are numerically equal to their
+ * PF_ counterparts.
+ */
+#define	AF_UNSPEC	0		/* unspecified */
+#define	AF_UNIX		1		/* local to host (pipes, portals) */
+#define	AF_INET		2		/* internetwork: UDP, TCP, etc. */
+#define	AF_IMPLINK	3		/* arpanet imp addresses */
+#define	AF_PUP		4		/* pup protocols: e.g. BSP */
+#define	AF_CHAOS	5		/* mit CHAOS protocols */
+#define	AF_NS		6		/* XEROX NS protocols */
+#define	AF_ISO		7		/* ISO protocols */
+#define	AF_OSI		AF_ISO
+#define	AF_ECMA		8		/* european computer manufacturers */
+#define	AF_DATAKIT	9		/* datakit protocols */
+#define	AF_CCITT	10		/* CCITT protocols, X.25 etc */
+#define	AF_SNA		11		/* IBM SNA */
+#define AF_DECnet	12		/* DECnet */
+#define AF_DLI		13		/* DEC Direct data link interface */
+#define AF_LAT		14		/* LAT */
+#define	AF_HYLINK	15		/* NSC Hyperchannel */
+#define	AF_APPLETALK	16		/* Apple Talk */
+#define	AF_ROUTE	17		/* Internal Routing Protocol */
+#define	AF_LINK		18		/* Link layer interface */
+#define	pseudo_AF_XTP	19		/* eXpress Transfer Protocol (no AF) */
+#define AF_INET6	24		/* IP version 6 */
+#define	AF_MAX		30
+
+/*
+ * Structure used by kernel to store most
+ * addresses.
+ */
+struct sockaddr {
+	unsigned short	sa_family;	/* address family */
+	char	sa_data[108];
+};
+
+/*
+ * Structure used by kernel to pass protocol
+ * information in raw sockets.
+ */
+struct sockproto {
+	unsigned short	sp_family;		/* address family */
+	unsigned short	sp_protocol;		/* protocol */
+};
+
+/*
+ * Protocol families, same as address families for now.
+ */
+#define	PF_UNSPEC	AF_UNSPEC
+#define	PF_UNIX		AF_UNIX
+#define	PF_INET		AF_INET
+#define	PF_IMPLINK	AF_IMPLINK
+#define	PF_PUP		AF_PUP
+#define	PF_CHAOS	AF_CHAOS
+#define	PF_NS		AF_NS
+#define	PF_ISO		AF_ISO
+#define	PF_OSI		AF_ISO
+#define	PF_ECMA		AF_ECMA
+#define	PF_DATAKIT	AF_DATAKIT
+#define	PF_CCITT	AF_CCITT
+#define	PF_SNA		AF_SNA
+#define PF_DECnet	AF_DECnet
+#define PF_DLI		AF_DLI
+#define PF_LAT		AF_LAT
+#define	PF_HYLINK	AF_HYLINK
+#define	PF_APPLETALK	AF_APPLETALK
+#define	PF_ROUTE	AF_ROUTE
+#define	PF_LINK		AF_LINK
+#define	PF_XTP		pseudo_AF_XTP	/* really just proto family, no AF */
+#define	PF_INET6	AF_INET6
+
+#define	PF_MAX		AF_MAX
+
+/*
+ * Maximum queue length specifiable by listen.
+ */
+#define	SOMAXCONN	5
+
+/*
+ * Message header for recvmsg and sendmsg calls.
+ */
+struct msghdr {
+	char	*msg_name;		/* optional address */
+	int	msg_namelen;		/* size of address */
+	struct	iovec *msg_iov;		/* scatter/gather array */
+	int	msg_iovlen;		/* # elements in msg_iov */
+	char	*msg_accrights;		/* access rights sent/received */
+	int	msg_accrightslen;
+};
+
+#define	MSG_OOB		0x1		/* process out-of-band data */
+#define	MSG_PEEK	0x2		/* peek at incoming message */
+#define	MSG_DONTROUTE	0x4		/* send without using routing tables */
+
+#define	MSG_MAXIOVLEN	16
+
+extern int accept(int, void *, int *);
+extern int bind(int, void *, int);
+extern int connect(int, void *, int);
+extern int getpeername(int, void *, int *);
+extern int getsockname(int, void *, int *);
+extern int getsockopt(int, int, int, void *, int *);
+extern int setsockopt(int, int, int, void *, int);
+extern int listen(int, int);
+extern int recv(int, void *, int, int);
+extern int recvfrom(int, void *, int, int, void *, int *);
+extern int recvmsg(int, struct msghdr *, int);
+extern int send(int, void *, int, int);
+extern int sendto(int, void *, int, int, void *, int);
+extern int sendmsg(int, struct msghdr *, int);
+extern int shutdown(int, int);
+extern int socket(int, int, int);
+extern int socketpair(int, int, int, int *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !__SYS_SOCKET_H__ */
--- /dev/null
+++ b/sys/include/ape/sys/stat.h
@@ -1,0 +1,84 @@
+#ifndef __STAT_H
+#define __STAT_H
+
+#ifndef __TYPES_H
+#include <sys/types.h>
+#endif
+
+#pragma lib "/$M/lib/ape/libap.a"
+
+/*
+ * stat structure, used by stat(2) and fstat(2)
+ */
+struct	stat {
+	dev_t	st_dev;
+	ino_t	st_ino;
+	mode_t 	st_mode;
+	nlink_t	st_nlink;
+	uid_t 	st_uid;
+	gid_t 	st_gid;
+	off_t	st_size;
+	time_t	st_atime;
+	time_t	st_mtime;
+	time_t	st_ctime;
+};
+
+#define	S__MASK		     0170000
+#ifdef _RESEARCH_SOURCE
+#define S_ISLNK(m)	(((m)&S__MASK) == 0120000)
+#endif
+#define S_ISREG(m)	(((m)&S__MASK) == 0100000)
+#define S_ISDIR(m)	(((m)&S__MASK) == 0040000)
+#define S_ISCHR(m)	(((m)&S__MASK) == 0020000)
+#define S_ISBLK(m)	(((m)&S__MASK) == 0060000)
+#define S_ISFIFO(m)	(((m)&S__MASK) == 0010000)
+
+#define	S_ISUID	04000		/* set user id on execution */
+#define	S_ISGID	02000		/* set group id on execution */
+#define	S_IRWXU	00700		/* read, write, execute: owner */
+#define	S_IRUSR	00400		/* read permission: owner */
+#define	S_IWUSR	00200		/* write permission: owner */
+#define	S_IXUSR	00100		/* execute permission: owner */
+#define	S_IRWXG	00070		/* read, write, execute: group */
+#define	S_IRGRP	00040		/* read permission: group */
+#define	S_IWGRP	00020		/* write permission: group */
+#define	S_IXGRP	00010		/* execute permission: group */
+#define	S_IRWXO	00007		/* read, write, execute: other */
+#define	S_IROTH	00004		/* read permission: other */
+#define	S_IWOTH	00002		/* write permission: other */
+#define	S_IXOTH	00001		/* execute permission: other */
+
+#ifdef _BSD_EXTENSION
+#define S_IFMT S__MASK
+#define S_IFDIR 0040000
+#define S_IFCHR 0020000
+#define S_IFBLK 0060000
+#define S_IFREG 0100000
+#define S_IFIFO 0010000
+#define S_IFLNK 0120000
+#define S_IFSOCK S_IFIFO
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern mode_t umask(mode_t);
+extern int mkdir(const char *, mode_t);
+extern int mkfifo(const char *, mode_t);
+extern int stat(const char *, struct stat *);
+extern int fstat(int, struct stat *);
+extern int chmod(const char *, mode_t);
+
+#ifdef _BSD_EXTENSION
+#pragma lib "/$M/lib/ape/libbsd.a"
+extern int	lstat(char *, struct stat *);
+extern int	symlink(char *, char *);
+extern int	readlink(char *, char*, int);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/sys/time.h
@@ -1,0 +1,22 @@
+#ifndef __SYSTIME_H
+#define __SYSTIME_H
+#pragma lib "/$M/lib/ape/libap.a"
+
+#ifndef __TIMEVAL__
+#define __TIMEVAL__
+struct timeval {
+	long	tv_sec;
+	long	tv_usec;
+};
+
+#ifdef _BSD_EXTENSION
+struct timezone {
+	int	tz_minuteswest;
+	int	tz_dsttime;
+};
+#endif
+#endif /* __TIMEVAL__ */
+
+extern int gettimeofday(struct timeval *, struct timezone *);
+
+#endif /* __SYSTIME_H */
--- /dev/null
+++ b/sys/include/ape/sys/times.h
@@ -1,0 +1,27 @@
+#ifndef __TIMES_H
+#define __TIMES_H
+#pragma lib "/$M/lib/ape/libap.a"
+
+#ifndef _CLOCK_T
+#define _CLOCK_T
+typedef long clock_t;
+#endif
+
+struct tms {
+	clock_t	tms_utime;
+	clock_t	tms_stime;
+	clock_t	tms_cutime;
+	clock_t	tms_cstime;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+clock_t times(struct tms *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/sys/types.h
@@ -1,0 +1,46 @@
+#ifndef __TYPES_H
+#define __TYPES_H
+
+#pragma lib "/$M/lib/ape/libap.a"
+typedef	unsigned short	ino_t;
+typedef	unsigned short	dev_t;
+typedef	long long		off_t;
+typedef unsigned short	mode_t;
+typedef short		uid_t;
+typedef short		gid_t;
+typedef short		nlink_t;
+typedef int		pid_t;
+
+#ifndef _SIZE_T
+#define _SIZE_T
+typedef unsigned long size_t;
+#endif
+#ifndef _SSIZE_T
+#define _SSIZE_T
+typedef long ssize_t;
+#endif
+
+#ifndef _TIME_T
+#define _TIME_T
+typedef long time_t;
+#endif
+
+#ifdef _BSD_EXTENSION
+#ifndef _CADDR_T
+#define _CADDR_T
+typedef char * caddr_t;
+#endif
+#ifndef _FD_SET_T
+#define _FD_SET_T
+/* also cf <select.h> */
+typedef struct fd_set {
+	long fds_bits[3];
+} fd_set;
+#define FD_SET(n,p)	((p)->fds_bits[(n)>>5] |= (1 << ((n) &0x1f)))
+#define FD_CLR(n,p)	((p)->fds_bits[(n)>>5] &= ~(1 << ((n) &0x1f)))
+#define FD_ISSET(n,p)	((p)->fds_bits[(n)>>5] & (1 << ((n) &0x1f)))
+#define FD_ZERO(p)	((p)->fds_bits[0] =0, (p)->fds_bits[1] =0, (p)->fds_bits[2] =0)
+#endif
+#endif
+
+#endif /* __TYPES_H */
--- /dev/null
+++ b/sys/include/ape/sys/uio.h
@@ -1,0 +1,34 @@
+#ifndef __SYS_UIO_H__
+#define __SYS_UIO_H__
+
+#ifndef _BSD_EXTENSION
+    This header file is an extension to ANSI/POSIX
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#pragma lib "/$M/lib/ape/libbsd.a"
+
+/*
+ * Copyright (c) 1982, 1986 Regents of the University of California.
+ * All rights reserved.  The Berkeley software License Agreement
+ * specifies the terms and conditions for redistribution.
+ *
+ *	@(#)uio.h	7.1 (Berkeley) 6/4/86
+ */
+
+struct iovec {
+	char	*iov_base;
+	int	iov_len;
+};
+
+extern int writev(int, struct iovec*, int);
+extern int readv(int, struct iovec*, int);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !__SYS_UIO_H__ */
--- /dev/null
+++ b/sys/include/ape/sys/un.h
@@ -1,0 +1,26 @@
+/*
+ * Copyright (c) 1982, 1986 Regents of the University of California.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms are permitted
+ * provided that the above copyright notice and this paragraph are
+ * duplicated in all such forms and that any documentation,
+ * advertising materials, and other materials related to such
+ * distribution and use acknowledge that the software was developed
+ * by the University of California, Berkeley.  The name of the
+ * University may not be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
+ * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ *	@(#)un.h	7.3 (Berkeley) 6/27/88
+ */
+
+/*
+ * Definitions for UNIX IPC domain.
+ */
+struct	sockaddr_un {
+	short	sun_family;		/* AF_UNIX */
+	char	sun_path[108];		/* path name (gag) */
+};
--- /dev/null
+++ b/sys/include/ape/sys/utsname.h
@@ -1,0 +1,23 @@
+#ifndef __UTSNAME
+#define __UTSNAME
+#pragma lib "/$M/lib/ape/libap.a"
+
+struct utsname {
+	char	*sysname;
+	char	*nodename;
+	char	*release;
+	char	*version;
+	char	*machine;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int uname(struct utsname *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/sys/wait.h
@@ -1,0 +1,35 @@
+#ifndef __WAIT_H
+#define __WAIT_H
+#pragma lib "/$M/lib/ape/libap.a"
+
+/* flag bits for third argument of waitpid */
+#define WNOHANG		0x1
+#define WUNTRACED	0x2
+
+/* macros for examining status returned */
+#ifndef WIFEXITED
+#define WIFEXITED(s)	(((s) & 0xFF) == 0)
+#define WEXITSTATUS(s)	((s>>8)&0xFF)
+#define WIFSIGNALED(s)	(((s) & 0xFF) != 0)
+#define WTERMSIG(s)	((s) & 0xFF)
+#define WIFSTOPPED(s)	(0)
+#define WSTOPSIG(s)	(0)
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+pid_t wait(int *);
+pid_t waitpid(pid_t, int *, int);
+#ifdef _BSD_EXTENSION
+struct rusage;
+pid_t wait3(int *, int, struct rusage *);
+pid_t wait4(pid_t, int *, int, struct rusage *);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ape/termios.h
@@ -1,0 +1,132 @@
+#pragma lib "/$M/lib/ape/libap.a"
+/* input modes */
+#define BRKINT	0x001
+#define ICRNL	0x002
+#define IGNBRK	0x004
+#define IGNCR	0x008
+#define IGNPAR	0x010
+#define INLCR	0x020
+#define INPCK	0x040
+#define ISTRIP	0x080
+#define IXOFF	0x100
+#define IXON	0x200
+#define PARMRK	0x400
+
+/* output modes: ONLCR, TAB3 are an extension to POSIX! */
+#define	OPOST	0000001
+#define	OLCUC	0000002
+#define	ONLCR	0000004
+#define	OCRNL	0000010
+#define	ONOCR	0000020
+#define	ONLRET	0000040
+#define	OFILL	0000100
+#define	OFDEL	0000200
+#define	NLDLY	0000400
+#define	NL0	0
+#define	NL1	0000400
+#define	CRDLY	0003000
+#define	CR0	0
+#define	CR1	0001000
+#define	CR2	0002000
+#define	CR3	0003000
+#define	TABDLY	0014000
+#define	TAB0	0
+#define	TAB1	0004000
+#define	TAB2	0010000
+#define	TAB3	0014000
+#define	BSDLY	0020000
+#define	BS0	0
+#define	BS1	0020000
+#define	VTDLY	0040000
+#define	VT0	0
+#define	VT1	0040000
+#define	FFDLY	0100000
+#define	FF0	0
+#define	FF1	0100000
+
+/* control modes */
+#define CLOCAL	0x001
+#define CREAD	0x002
+#define CSIZE	0x01C
+#define CS5	0x004
+#define CS6	0x008
+#define CS7	0x00C
+#define CS8	0x010
+#define CSTOPB	0x020
+#define HUPCL	0x040
+#define PARENB	0x080
+#define PARODD	0x100
+
+/* local modes */
+#define ECHO	0x001
+#define ECHOE	0x002
+#define ECHOK	0x004
+#define ECHONL	0x008
+#define ICANON	0x010
+#define IEXTEN	0x020
+#define ISIG	0x040
+#define NOFLSH	0x080
+#define TOSTOP	0x100
+
+/* control characters */
+#define VEOF	0
+#define VEOL	1
+#define VERASE	2
+#define VINTR	3
+#define VKILL	4
+#define VMIN	5
+#define VQUIT	6
+#define VSUSP	7
+#define VTIME	8
+#define VSTART	9
+#define VSTOP	10
+#define NCCS	11
+
+/* baud rates */
+#define B0	0
+#define B50	1
+#define B75	2
+#define B110	3
+#define B134	4
+#define B150	5
+#define B200	6
+#define B300	7
+#define B600	8
+#define B1200	9
+#define B1800	10
+#define B2400	11
+#define B4800	12
+#define B9600	13
+#define B19200	14
+#define B38400	15
+
+/* optional actions for tcsetattr */
+#define TCSANOW	  1
+#define TCSADRAIN 2
+#define TCSAFLUSH 3
+
+typedef unsigned long tcflag_t;
+typedef unsigned long speed_t;
+typedef unsigned char cc_t;
+
+struct termios {
+	tcflag_t	c_iflag;	/* input modes */
+	tcflag_t	c_oflag;	/* output modes */
+	tcflag_t	c_cflag;	/* control modes */
+	tcflag_t	c_lflag;	/* local modes */
+	cc_t		c_cc[NCCS];	/* control characters */
+};
+
+extern speed_t cfgetospeed(const struct termios *);
+extern int cfsetospeed(struct termios *, speed_t);
+extern speed_t cfgetispeed(const struct termios *);
+extern int cfsetispeed(struct termios *, speed_t);
+extern int tcgetattr(int, struct termios *);
+extern int tcsetattr(int, int, const struct termios *);
+#ifdef __TYPES_H
+extern pid_t tcgetpgrp(int);
+extern int tcsetpgrp(int, pid_t);
+#endif
+extern int tcdrain(int);
+extern int tcflush(int, int);
+extern int tcflow(int, int);
--- /dev/null
+++ b/sys/include/ape/time.h
@@ -1,0 +1,65 @@
+#ifndef __TIME_H
+#define __TIME_H
+#pragma lib "/$M/lib/ape/libap.a"
+
+#include <stddef.h>
+
+#define CLOCKS_PER_SEC 1000
+
+/* obsolsecent, but required */
+#define CLK_TCK CLOCKS_PER_SEC
+
+#ifndef _CLOCK_T
+#define _CLOCK_T
+typedef long clock_t;
+#endif
+#ifndef _TIME_T
+#define _TIME_T
+typedef long time_t;
+#endif
+
+struct tm {
+	int	tm_sec;
+	int	tm_min;
+	int	tm_hour;
+	int	tm_mday;
+	int	tm_mon;
+	int	tm_year;
+	int	tm_wday;
+	int	tm_yday;
+	int	tm_isdst;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern clock_t clock(void);
+extern double difftime(time_t, time_t);
+extern time_t mktime(struct tm *);
+extern time_t time(time_t *);
+extern char *asctime(const struct tm *);
+extern char *ctime(const time_t *);
+extern struct tm *gmtime(const time_t *);
+extern struct tm *localtime(const time_t *);
+extern size_t strftime(char *, size_t, const char *, const struct tm *);
+
+#ifdef _REENTRANT_SOURCE
+extern struct tm *gmtime_r(const time_t *, struct tm *);
+extern struct tm *localtime_r(const time_t *, struct tm *);
+extern char *ctime_r(const time_t *, char *);
+#endif
+
+#ifdef _POSIX_SOURCE
+extern void tzset(void);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef _POSIX_SOURCE
+extern char *tzname[2];
+#endif
+
+#endif /* __TIME_H */
--- /dev/null
+++ b/sys/include/ape/u.h
@@ -1,0 +1,19 @@
+#ifndef __U_H
+#define __U_H
+#ifndef _PLAN9_SOURCE
+   This header file is an extension to ANSI/POSIX
+#endif
+
+#define nil		((void*)0)
+typedef	unsigned short	ushort;
+typedef	unsigned char	uchar;
+typedef unsigned long	ulong;
+typedef unsigned int	uint;
+typedef   signed char	schar;
+typedef	long long	vlong;
+typedef	unsigned long long uvlong;
+typedef	ushort		Rune;
+typedef 	union FPdbleword FPdbleword;
+typedef	char*	p9va_list;
+
+#endif
--- /dev/null
+++ b/sys/include/ape/unistd.h
@@ -1,0 +1,168 @@
+#ifndef	__UNISTD_H
+#define	__UNISTD_H
+#ifndef _POSIX_SOURCE
+   This header file is not defined in pure ANSI
+#endif
+#pragma lib "/$M/lib/ape/libap.a"
+
+#define _POSIX_VERSION	199309L
+#define _POSIX_ASYNC_IO -1
+#define _POSIX_CHOWN_RESTRICTED 1
+#define _POSIX_NO_TRUNC 1
+#define _POSIX_PRIO_IO -1
+#define _POSIX_SYNC_IO -1
+#define _POSIX_VDISABLE -1
+
+#ifndef _SIZE_T
+#define _SIZE_T
+typedef unsigned long size_t;
+#endif
+#ifndef _SSIZE_T
+#define _SSIZE_T
+typedef long ssize_t;
+#endif
+#ifndef NULL
+#ifndef NULL
+#ifdef __cplusplus
+#define NULL 0
+#else
+#define NULL ((void*)0)
+#endif
+#endif
+#endif
+
+/* access */
+#define	R_OK		4
+#define	W_OK		2
+#define	X_OK		1
+#define	F_OK		0	/* test for existence */
+
+/* lockf */
+#define	F_ULOCK		0	/* unlock a previously locked region */
+#define	F_LOCK		1	/* lock a region for exclusive use */
+#define	F_TLOCK		2	/* test and lock a region for exclusive use */
+#define	F_TEST		3	/* test a region for a previous lock */
+
+/* lseek */
+#ifndef SEEK_SET		/* also defined in stdio.h */
+#define	SEEK_SET	0
+#define	SEEK_CUR	1
+#define	SEEK_END	2
+#endif
+
+/* sysconf argument */
+#define	_SC_ARG_MAX		1	/* max chars in args to exec */
+#define	_SC_CHILD_MAX		2	/* max child process per process */
+#define	_SC_CLK_TCK		3	/* number of clock() units per second */
+#define	_SC_NGROUPS_MAX		4	/* max supplementary groups per process */
+#define	_SC_OPEN_MAX		5
+#define _SC_STREAM_MAX		6
+#define _SC_TZNAME_MAX		7
+#define	_SC_JOB_CONTROL		8	/* posix job control */
+#define	_SC_SAVED_IDS		9	/* saved suid/sgid per process */
+#define	_SC_VERSION		10	/* this version */
+#define _SC_LOGIN_NAME_MAX	11	/* max length of a login name */
+
+/* pathconf argument */
+#define _PC_LINK_MAX		1
+#define _PC_MAX_CANON		2
+#define _PC_MAX_INPUT		3
+#define _PC_NAME_MAX		4
+#define _PC_PATH_MAX		5
+#define _PC_PIPE_BUF		6
+#define _PC_CHOWN_RESTRICTED	7
+#define _PC_NO_TRUNC		8
+#define _PC_VDISABLE		9
+
+/* standard filenos */
+#define STDIN_FILENO		0
+#define STDOUT_FILENO		1
+#define STDERR_FILENO		2
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* process primitives */
+extern int execl(const char *, const char *, ...);
+extern int execv(const char *, const char **);
+extern int execle(const char *, const char *, const char *,  ...);
+extern int execve(const char *, const char **, const char **);
+extern int execlp(const char *, const char *, ...);
+extern int execvp(const char *, const char **);
+extern void _exit(int);
+extern unsigned int alarm(unsigned int);
+extern int pause(void);
+extern unsigned int sleep(unsigned int);
+#ifdef __TYPES_H
+extern pid_t fork(void);
+#endif
+
+/* process environment */
+extern char *getlogin(void);
+extern char *cuserid(char *);
+extern char *ttyname(int);
+extern int isatty(int);
+extern long sysconf(int);
+#ifdef __TYPES_H
+extern pid_t getpid(void);
+extern pid_t getppid(void);
+extern uid_t getuid(void);
+extern uid_t geteuid(void);
+extern gid_t getgid(void);
+extern gid_t getegid(void);
+extern int setuid(uid_t);
+extern int setgid(gid_t);
+extern int getgroups(int, gid_t *);
+extern pid_t getpgrp(void);
+extern int setpgid(pid_t, pid_t);
+extern pid_t setsid(void);
+#endif
+
+/* files and directories */
+extern int chdir(const char *);
+extern int link(const char *, const char *);
+extern char *getcwd(char *, size_t);
+extern int unlink(const char *);
+extern int rmdir(const char *);
+extern int rename(const char *, const char *);
+extern int access(const char *, int);
+extern long pathconf(const char *, int);
+extern long fpathconf(int, int);
+#ifdef __TYPES_H
+extern int chown(const char *, uid_t, gid_t);
+#endif
+
+/* input and output primitives */
+extern int pipe(int *);
+extern int dup(int);
+extern int dup2(int, int);
+extern int close(int);
+extern ssize_t read(int, void *, size_t);
+extern ssize_t write(int, const void *, size_t);
+#ifdef __TYPES_H
+extern int ftruncate(int, off_t);
+extern off_t lseek(int, off_t, int);
+#endif
+
+/* device- and class-specific functions */
+#ifdef __TYPES_H
+extern pid_t tcgetpgrp(int);
+extern int tcsetpgrp(int, pid_t);
+#endif
+
+#ifdef _REENTRANT_SOURCE
+extern char *getlogin_r(char *, int);
+#endif
+
+/* berkeley specific functions */
+#ifdef _BSD_EXTENSION
+#include <bsd.h>
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif
--- /dev/null
+++ b/sys/include/ape/utf.h
@@ -1,0 +1,60 @@
+#ifndef _UTF_H_
+#define _UTF_H_ 1
+#pragma lib "/$M/lib/ape/libutf.a"
+#pragma src "/sys/src/ape/lib/utf"
+
+#if defined(__cplusplus)
+extern "C" { 
+#endif
+
+typedef unsigned short Rune;	/* 16 bits */
+
+enum
+{
+	UTFmax		= 3,		/* maximum bytes per rune */
+	Runesync	= 0x80,		/* cannot represent part of a UTF sequence (<) */
+	Runeself	= 0x80,		/* rune and UTF sequences are the same (<) */
+	Runeerror	= 0x80,		/* decoding error in UTF */
+};
+
+/*
+ * rune routines
+ */
+extern	int	runetochar(char*, Rune*);
+extern	int	chartorune(Rune*, char*);
+extern	int	runelen(long);
+extern	int	runenlen(Rune*, int);
+extern	int	fullrune(char*, int);
+extern	int	utflen(char*);
+extern	int	utfnlen(char*, long);
+extern	char*	utfrune(char*, long);
+extern	char*	utfrrune(char*, long);
+extern	char*	utfutf(char*, char*);
+extern	char*	utfecpy(char*, char*, char*);
+
+extern	Rune*	runestrcat(Rune*, Rune*);
+extern	Rune*	runestrchr(Rune*, Rune);
+extern	int	runestrcmp(Rune*, Rune*);
+extern	Rune*	runestrcpy(Rune*, Rune*);
+extern	Rune*	runestrncpy(Rune*, Rune*, long);
+extern	Rune*	runestrecpy(Rune*, Rune*, Rune*);
+extern	Rune*	runestrdup(Rune*);
+extern	Rune*	runestrncat(Rune*, Rune*, long);
+extern	int	runestrncmp(Rune*, Rune*, long);
+extern	Rune*	runestrrchr(Rune*, Rune);
+extern	long	runestrlen(Rune*);
+extern	Rune*	runestrstr(Rune*, Rune*);
+
+extern	Rune	tolowerrune(Rune);
+extern	Rune	totitlerune(Rune);
+extern	Rune	toupperrune(Rune);
+extern	int	isalpharune(Rune);
+extern	int	islowerrune(Rune);
+extern	int	isspacerune(Rune);
+extern	int	istitlerune(Rune);
+extern	int	isupperrune(Rune);
+
+#if defined(__cplusplus)
+}
+#endif
+#endif
--- /dev/null
+++ b/sys/include/ape/utime.h
@@ -1,0 +1,22 @@
+#ifndef __UTIME_H
+#define __UTIME_H
+
+#pragma lib "/$M/lib/ape/libap.a"
+
+struct utimbuf
+{
+	time_t actime;
+	time_t modtime;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int utime(const char *, const struct utimbuf *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+++ b/sys/include/ar.h
@@ -1,0 +1,17 @@
+#define	ARMAG	"!<arch>\n"
+#define	SARMAG	8
+
+#define	ARFMAG	"`\n"
+#define SARNAME	16
+
+struct	ar_hdr
+{
+	char	name[SARNAME];
+	char	date[12];
+	char	uid[6];
+	char	gid[6];
+	char	mode[8];
+	char	size[10];
+	char	fmag[2];
+};
+#define	SAR_HDR	(SARNAME+44)
--- /dev/null
+++ b/sys/include/auth.h
@@ -1,0 +1,143 @@
+#pragma	src	"/sys/src/libauth"
+#pragma	lib	"libauth.a"
+
+/*
+ * Interface for typical callers.
+ */
+
+typedef struct	AuthInfo	AuthInfo;
+typedef struct	Chalstate	Chalstate;
+typedef struct	Chapreply	Chapreply;
+typedef struct	MSchapreply	MSchapreply;
+typedef struct	UserPasswd	UserPasswd;
+typedef struct	AuthRpc		AuthRpc;
+
+enum
+{
+	MAXCHLEN=	256,		/* max challenge length	*/
+	MAXNAMELEN=	256,		/* maximum name length */
+	MD5LEN=		16,
+
+	ARok = 0,			/* rpc return values */
+	ARdone,
+	ARerror,
+	ARneedkey,
+	ARbadkey,
+	ARwritenext,
+	ARtoosmall,
+	ARtoobig,
+	ARrpcfailure,
+	ARphase,
+
+	AuthRpcMax = 4096,
+};
+
+struct AuthRpc
+{
+	int afd;
+	char ibuf[AuthRpcMax];
+	char obuf[AuthRpcMax];
+	char *arg;
+	uint narg;
+};
+
+struct AuthInfo
+{
+	char	*cuid;		/* caller id */
+	char	*suid;		/* server id */
+	char	*cap;		/* capability (only valid on server side) */
+	int	nsecret;	/* length of secret */
+	uchar	*secret;	/* secret */
+};
+
+struct Chalstate
+{
+	char	*user;
+	char	chal[MAXCHLEN];
+	int	nchal;
+	void	*resp;
+	int	nresp;
+
+/* for implementation only */
+	int	afd;			/* to factotum */
+	AuthRpc	*rpc;			/* to factotum */
+	char	userbuf[MAXNAMELEN];	/* temp space if needed */
+	int	userinchal;		/* user was sent to obtain challenge */
+};
+
+struct	Chapreply		/* for protocol "chap" */
+{
+	uchar	id;
+	char	resp[MD5LEN];
+};
+
+struct	MSchapreply	/* for protocol "mschap" */
+{
+	char	LMresp[24];		/* Lan Manager response */
+	char	NTresp[24];		/* NT response */
+};
+
+struct	UserPasswd
+{
+	char	*user;
+	char	*passwd;
+};
+
+extern	int	newns(char*, char*);
+extern	int	addns(char*, char*);
+
+extern	int	noworld(char*);
+extern	int	amount(int, char*, int, char*);
+
+/* these two may get generalized away -rsc */
+extern	int	login(char*, char*, char*);
+extern	int	httpauth(char*, char*);
+
+typedef struct Attr Attr;
+enum {
+	AttrNameval,		/* name=val -- when matching, must have name=val */
+	AttrQuery,		/* name? -- when matching, must be present */
+	AttrDefault,		/* name:=val -- when matching, if present must match INTERNAL */
+};
+struct Attr
+{
+	int type;
+	Attr *next;
+	char *name;
+	char *val;
+};
+
+typedef int AuthGetkey(char*);
+
+int	_attrfmt(Fmt*);
+Attr	*_copyattr(Attr*);
+Attr	*_delattr(Attr*, char*);
+Attr	*_findattr(Attr*, char*);
+void	_freeattr(Attr*);
+Attr	*_mkattr(int, char*, char*, Attr*);
+Attr	*_parseattr(char*);
+char	*_strfindattr(Attr*, char*);
+#pragma varargck type "A" Attr*
+
+extern AuthInfo*	fauth_proxy(int, AuthRpc *rpc, AuthGetkey *getkey, char *params);
+extern AuthInfo*	auth_proxy(int fd, AuthGetkey *getkey, char *fmt, ...);
+extern int		auth_getkey(char*);
+extern int		(*amount_getkey)(char*);
+extern void		auth_freeAI(AuthInfo *ai);
+extern int		auth_chuid(AuthInfo *ai, char *ns);
+extern Chalstate	*auth_challenge(char*, ...);
+extern AuthInfo*	auth_response(Chalstate*);
+extern int		auth_respond(void*, uint, char*, uint, void*, uint, AuthGetkey *getkey, char*, ...);
+extern void		auth_freechal(Chalstate*);
+extern AuthInfo*	auth_userpasswd(char *user, char *passwd);
+extern UserPasswd*	auth_getuserpasswd(AuthGetkey *getkey, char*, ...);
+extern AuthInfo*	auth_getinfo(AuthRpc *rpc);
+extern AuthRpc*		auth_allocrpc(int afd);
+extern Attr*		auth_attr(AuthRpc *rpc);
+extern void		auth_freerpc(AuthRpc *rpc);
+extern uint		auth_rpc(AuthRpc *rpc, char *verb, void *a, int n);
+extern int		auth_wep(char*, char*, ...);
+#pragma varargck argpos auth_proxy 3
+#pragma varargck argpos auth_challenge 1
+#pragma varargck argpos auth_respond 8
+#pragma varargck argpos auth_getuserpasswd 2
--- /dev/null
+++ b/sys/include/authsrv.h
@@ -1,0 +1,173 @@
+#pragma	src	"/sys/src/libauthsrv"
+#pragma	lib	"libauthsrv.a"
+
+/*
+ * Interface for talking to authentication server.
+ */
+typedef struct	Ticket		Ticket;
+typedef struct	Ticketreq	Ticketreq;
+typedef struct	Authenticator	Authenticator;
+typedef struct	Nvrsafe		Nvrsafe;
+typedef struct	Passwordreq	Passwordreq;
+typedef struct	OChapreply	OChapreply;
+typedef struct	OMSchapreply	OMSchapreply;
+
+enum
+{
+	ANAMELEN=	28,	/* name max size in previous proto */
+	AERRLEN=	64,	/* errstr max size in previous proto */
+	DOMLEN=		48,	/* authentication domain name length */
+	DESKEYLEN=	7,	/* encrypt/decrypt des key length */
+	CHALLEN=	8,	/* plan9 sk1 challenge length */
+	NETCHLEN=	16,	/* max network challenge length (used in AS protocol) */
+	CONFIGLEN=	14,
+	SECRETLEN=	32,	/* secret max size */
+
+	KEYDBOFF=	8,	/* bytes of random data at key file's start */
+	OKEYDBLEN=	ANAMELEN+DESKEYLEN+4+2,	/* old key file entry length */
+	KEYDBLEN=	OKEYDBLEN+SECRETLEN,	/* key file entry length */
+	OMD5LEN=	16,
+};
+
+/* encryption numberings (anti-replay) */
+enum
+{
+	AuthTreq=1,	/* ticket request */
+	AuthChal=2,	/* challenge box request */
+	AuthPass=3,	/* change password */
+	AuthOK=4,	/* fixed length reply follows */
+	AuthErr=5,	/* error follows */
+	AuthMod=6,	/* modify user */
+	AuthApop=7,	/* apop authentication for pop3 */
+	AuthOKvar=9,	/* variable length reply follows */
+	AuthChap=10,	/* chap authentication for ppp */
+	AuthMSchap=11,	/* MS chap authentication for ppp */
+	AuthCram=12,	/* CRAM verification for IMAP (RFC2195 & rfc2104) */
+	AuthHttp=13,	/* http domain login */
+	AuthVNC=14,	/* VNC server login (deprecated) */
+
+
+	AuthTs=64,	/* ticket encrypted with server's key */
+	AuthTc,		/* ticket encrypted with client's key */
+	AuthAs,		/* server generated authenticator */
+	AuthAc,		/* client generated authenticator */
+	AuthTp,		/* ticket encrypted with client's key for password change */
+	AuthHr,		/* http reply */
+};
+
+struct Ticketreq
+{
+	char	type;
+	char	authid[ANAMELEN];	/* server's encryption id */
+	char	authdom[DOMLEN];	/* server's authentication domain */
+	char	chal[CHALLEN];		/* challenge from server */
+	char	hostid[ANAMELEN];	/* host's encryption id */
+	char	uid[ANAMELEN];		/* uid of requesting user on host */
+};
+#define	TICKREQLEN	(3*ANAMELEN+CHALLEN+DOMLEN+1)
+
+struct Ticket
+{
+	char	num;			/* replay protection */
+	char	chal[CHALLEN];		/* server challenge */
+	char	cuid[ANAMELEN];		/* uid on client */
+	char	suid[ANAMELEN];		/* uid on server */
+	char	key[DESKEYLEN];		/* nonce DES key */
+};
+#define	TICKETLEN	(CHALLEN+2*ANAMELEN+DESKEYLEN+1)
+
+struct Authenticator
+{
+	char	num;			/* replay protection */
+	char	chal[CHALLEN];
+	ulong	id;			/* authenticator id, ++'d with each auth */
+};
+#define	AUTHENTLEN	(CHALLEN+4+1)
+
+struct Passwordreq
+{
+	char	num;
+	char	old[ANAMELEN];
+	char	new[ANAMELEN];
+	char	changesecret;
+	char	secret[SECRETLEN];	/* new secret */
+};
+#define	PASSREQLEN	(2*ANAMELEN+1+1+SECRETLEN)
+
+struct	OChapreply
+{
+	uchar	id;
+	char	uid[ANAMELEN];
+	char	resp[OMD5LEN];
+};
+
+struct	OMSchapreply
+{
+	char	uid[ANAMELEN];
+	char	LMresp[24];		/* Lan Manager response */
+	char	NTresp[24];		/* NT response */
+};
+
+/*
+ *  convert to/from wire format
+ */
+extern	int	convT2M(Ticket*, char*, char*);
+extern	void	convM2T(char*, Ticket*, char*);
+extern	void	convM2Tnoenc(char*, Ticket*);
+extern	int	convA2M(Authenticator*, char*, char*);
+extern	void	convM2A(char*, Authenticator*, char*);
+extern	int	convTR2M(Ticketreq*, char*);
+extern	void	convM2TR(char*, Ticketreq*);
+extern	int	convPR2M(Passwordreq*, char*, char*);
+extern	void	convM2PR(char*, Passwordreq*, char*);
+
+/*
+ *  convert ascii password to DES key
+ */
+extern	int	opasstokey(char*, char*);
+extern	int	passtokey(char*, char*);
+
+/*
+ *  Nvram interface
+ */
+enum {
+	NVread		= 0,	/* just read */
+	NVwrite		= 1<<0,	/* always prompt and rewrite nvram */
+	NVwriteonerr	= 1<<1,	/* prompt and rewrite nvram when corrupt */
+	NVwritemem	= 1<<2,	/* don't prompt, write nvram from argument */
+};
+
+/* storage layout */
+struct Nvrsafe
+{
+	char	machkey[DESKEYLEN];	/* was file server's authid's des key */
+	uchar	machsum;
+	char	authkey[DESKEYLEN];	/* authid's des key from password */
+	uchar	authsum;
+	/*
+	 * file server config string of device holding full configuration;
+	 * secstore key on non-file-servers.
+	 */
+	char	config[CONFIGLEN];
+	uchar	configsum;
+	char	authid[ANAMELEN];	/* auth userid, e.g., bootes */
+	uchar	authidsum;
+	char	authdom[DOMLEN]; /* auth domain, e.g., cs.bell-labs.com */
+	uchar	authdomsum;
+};
+
+extern	uchar	nvcsum(void*, int);
+extern int	readnvram(Nvrsafe*, int);
+
+/*
+ *  call up auth server
+ */
+extern	int	authdial(char *netroot, char *authdom);
+
+/*
+ *  exchange messages with auth server
+ */
+extern	int	_asgetticket(int, char*, char*);
+extern	int	_asrdresp(int, char*, int);
+extern	int	sslnegotiate(int, Ticket*, char**, char**);
+extern	int	srvsslnegotiate(int, Ticket*, char**, char**);
--- /dev/null
+++ b/sys/include/avl.h
@@ -1,0 +1,26 @@
+#pragma	lib	"libavl.a"
+#pragma src "/sys/src/libavl"
+
+typedef struct Avl	Avl;
+typedef struct Avltree	Avltree;
+typedef struct Avlwalk	Avlwalk;
+
+#pragma incomplete Avltree
+#pragma incomplete Avlwalk
+
+struct Avl
+{
+	Avl	*p;		/* parent */
+	Avl	*n[2];		/* children */
+	int	bal;		/* balance bits */
+};
+
+Avl	*avlnext(Avlwalk *walk);
+Avl	*avlprev(Avlwalk *walk);
+Avlwalk	*avlwalk(Avltree *tree);
+void	deleteavl(Avltree *tree, Avl *key, Avl **oldp);
+void	endwalk(Avlwalk *walk);
+void	insertavl(Avltree *tree, Avl *new, Avl **oldp);
+Avl	*lookupavl(Avltree *tree, Avl *key);
+Avltree	*mkavltree(int(*cmp)(Avl*, Avl*));
+Avl*	searchavl(Avltree *tree, Avl *key, int neighbor);
--- /dev/null
+++ b/sys/include/bin.h
@@ -1,0 +1,10 @@
+#pragma	lib	"libbin.a"
+#pragma	src	"/sys/src/libbin"
+
+typedef struct Bin	Bin;
+
+#pragma incomplete Bin
+
+void	*binalloc(Bin **, ulong size, int zero);
+void	*bingrow(Bin **, void *op, ulong osize, ulong size, int zero);
+void	binfree(Bin **);
--- /dev/null
+++ b/sys/include/bio.h
@@ -1,0 +1,74 @@
+#pragma	src	"/sys/src/libbio"
+#pragma	lib	"libbio.a"
+
+typedef	struct	Biobuf	Biobuf;
+typedef	struct	Biobufhdr	Biobufhdr;
+
+enum
+{
+	Bsize		= 8*1024,
+	Bungetsize	= 4,		/* space for ungetc */
+	Bmagic		= 0x314159,
+	Beof		= -1,
+	Bbad		= -2,
+
+	Binactive	= 0,		/* states */
+	Bractive,
+	Bwactive,
+	Bracteof,
+};
+
+struct	Biobufhdr
+{
+	int	icount;		/* neg num of bytes at eob */
+	int	ocount;		/* num of bytes at bob */
+	int	rdline;		/* num of bytes after rdline */
+	int	runesize;	/* num of bytes of last getrune */
+	int	state;		/* r/w/inactive */
+	int	fid;		/* open file */
+	int	flag;		/* magic if malloc'ed */
+	vlong	offset;		/* offset of buffer in file */
+	int	bsize;		/* size of buffer */
+	uchar*	bbuf;		/* pointer to beginning of buffer */
+	uchar*	ebuf;		/* pointer to end of buffer */
+	uchar*	gbuf;		/* pointer to good data in buf */
+};
+
+struct	Biobuf
+{
+	Biobufhdr;
+	uchar	b[Bungetsize+Bsize];
+};
+
+/* Dregs, redefined as functions for backwards compatibility */
+#define	BGETC(bp)	Bgetc(bp)
+#define	BPUTC(bp,c)	Bputc(bp,c)
+#define	BOFFSET(bp)	Boffset(bp)
+#define	BLINELEN(bp)	Blinelen(bp)
+#define	BFILDES(bp)	Bfildes(bp)
+
+int	Bbuffered(Biobufhdr*);
+int	Bfildes(Biobufhdr*);
+int	Bflush(Biobufhdr*);
+int	Bgetc(Biobufhdr*);
+int	Bgetd(Biobufhdr*, double*);
+long	Bgetrune(Biobufhdr*);
+int	Binit(Biobuf*, int, int);
+int	Binits(Biobufhdr*, int, int, uchar*, int);
+int	Blinelen(Biobufhdr*);
+vlong	Boffset(Biobufhdr*);
+Biobuf*	Bopen(char*, int);
+int	Bprint(Biobufhdr*, char*, ...);
+int	Bvprint(Biobufhdr*, char*, va_list);
+int	Bputc(Biobufhdr*, int);
+int	Bputrune(Biobufhdr*, long);
+void*	Brdline(Biobufhdr*, int);
+char*	Brdstr(Biobufhdr*, int, int);
+long	Bread(Biobufhdr*, void*, long);
+vlong	Bseek(Biobufhdr*, vlong, int);
+int	Bterm(Biobufhdr*);
+int	Bungetc(Biobufhdr*);
+int	Bungetrune(Biobufhdr*);
+long	Bwrite(Biobufhdr*, void*, long);
+
+#pragma	varargck	argpos	Bprint	2
--- /dev/null
+++ b/sys/include/bootexec.h
@@ -1,0 +1,137 @@
+struct coffsect
+{
+	char	name[8];
+	ulong	phys;
+	ulong	virt;
+	ulong	size;
+	ulong	fptr;
+	ulong	fptrreloc;
+	ulong	fptrlineno;
+	ulong	nrelocnlineno;
+	ulong	flags;
+};
+
+/*
+ * proprietary exec headers, needed to bootstrap various machines
+ */
+struct mipsexec
+{
+	short	mmagic;		/* (0x160) mips magic number */
+	short	nscns;		/* (unused) number of sections */
+	long	timdat;		/* (unused) time & date stamp */
+	long	symptr;		/* offset to symbol table */
+	long	nsyms;		/* size of symbol table */
+	short	opthdr;		/* (0x38) sizeof(optional hdr) */
+	short	pcszs;		/* flags */
+	short	amagic;		/* see above */
+	short	vstamp;		/* version stamp */
+	long	tsize;		/* text size in bytes */
+	long	dsize;		/* initialized data */
+	long	bsize;		/* uninitialized data */
+	long	mentry;		/* entry pt.				*/
+	long	text_start;	/* base of text used for this file	*/
+	long	data_start;	/* base of data used for this file	*/
+	long	bss_start;	/* base of bss used for this file	*/
+	long	gprmask;	/* general purpose register mask	*/
+union{
+	long	cprmask[4];	/* co-processor register masks		*/
+	long	pcsize;
+};
+	long	gp_value;	/* the gp value used for this object    */
+};
+
+struct mips4kexec
+{
+	struct mipsexec	h;
+	struct coffsect	itexts;
+	struct coffsect idatas;
+	struct coffsect ibsss;
+};
+
+struct sparcexec
+{
+	short	sjunk;		/* dynamic bit and version number */
+	short	smagic;		/* 0407 */
+	ulong	stext;
+	ulong	sdata;
+	ulong	sbss;
+	ulong	ssyms;
+	ulong	sentry;
+	ulong	strsize;
+	ulong	sdrsize;
+};
+
+struct nextexec
+{
+	struct	nexthdr{
+		ulong	nmagic;
+		ulong	ncputype;
+		ulong	ncpusubtype;
+		ulong	nfiletype;
+		ulong	ncmds;
+		ulong	nsizeofcmds;
+		ulong	nflags;
+	};
+
+	struct nextcmd{
+		ulong	cmd;
+		ulong	cmdsize;
+		uchar	segname[16];
+		ulong	vmaddr;
+		ulong	vmsize;
+		ulong	fileoff;
+		ulong	filesize;
+		ulong	maxprot;
+		ulong	initprot;
+		ulong	nsects;
+		ulong	flags;
+	}textc;
+	struct nextsect{
+		char	sectname[16];
+		char	segname[16];
+		ulong	addr;
+		ulong	size;
+		ulong	offset;
+		ulong	align;
+		ulong	reloff;
+		ulong	nreloc;
+		ulong	flags;
+		ulong	reserved1;
+		ulong	reserved2;
+	}texts;
+	struct nextcmd	datac;
+	struct nextsect	datas;
+	struct nextsect	bsss;
+	struct nextsym{
+		ulong	cmd;
+		ulong	cmdsize;
+		ulong	symoff;
+		ulong	nsyms;
+		ulong	spoff;
+		ulong	pcoff;
+	}symc;
+};
+
+struct i386exec
+{
+	struct	i386coff{
+		ulong	isectmagic;
+		ulong	itime;
+		ulong	isyms;
+		ulong	insyms;
+		ulong	iflags;
+	};
+	struct	i386hdr{
+		ulong	imagic;
+		ulong	itextsize;
+		ulong	idatasize;
+		ulong	ibsssize;
+		ulong	ientry;
+		ulong	itextstart;
+		ulong	idatastart;
+	};
+	struct coffsect	itexts;
+	struct coffsect idatas;
+	struct coffsect ibsss;
+	struct coffsect icomments;
+};
--- /dev/null
+++ b/sys/include/complete.h
@@ -1,0 +1,16 @@
+#pragma	lib	"libcomplete.a"
+#pragma src "/sys/src/libcomplete"
+
+typedef struct Completion Completion;
+
+struct Completion{
+	uchar advance;		/* whether forward progress has been made */
+	uchar complete;	/* whether the completion now represents a file or directory */
+	char *string;		/* the string to advance, suffixed " " or "/" for file or directory */
+	int nmatch;		/* number of files that matched */
+	int nfile;			/* number of files returned */
+	char **filename;	/* their names */
+};
+
+Completion* complete(char *dir, char *s);
+void freecompletion(Completion*);
--- /dev/null
+++ b/sys/include/control.h
@@ -1,0 +1,213 @@
+#pragma src "/sys/src/libcontrol"
+#pragma lib "libcontrol.a"
+
+#pragma	varargck	argpos	ctlprint	2
+#pragma varargck	argpos	_ctlprint	2
+
+typedef struct Control Control;
+typedef struct Controlset Controlset;
+typedef struct CParse CParse;
+typedef struct CCache CCache;
+typedef struct CCache CImage;
+typedef struct CCache CFont;
+
+enum	/* types */
+{
+	Ctlunknown,
+	Ctlbox,
+	Ctlbutton,
+	Ctlentry,
+	Ctlkeyboard,
+	Ctllabel,
+	Ctlmenu,
+	Ctlradio,
+	Ctlscribble,
+	Ctlslider,
+	Ctltabs,
+	Ctltext,
+	Ctltextbutton,
+	Ctltextbutton3,
+	Ctlgroup,		/* divider between controls and metacontrols */
+	Ctlboxbox,
+	Ctlcolumn,
+	Ctlrow,
+	Ctlstack,
+	Ctltab,
+	Ntypes,
+};
+
+struct Controlset
+{
+	Control		*controls;
+	Image		*screen;
+	Control		*actives;
+	Control		*focus;
+	Channel		*ctl;
+	Channel		*data;		/* currently only for sync */
+	Channel		*kbdc;
+	Channel		*mousec;
+	Channel		*resizec;
+	Channel		*resizeexitc;
+	Channel		*csexitc;
+	Keyboardctl	*keyboardctl;	/* will be nil if user supplied keyboard */
+	Mousectl	*mousectl;	/* will be nil if user supplied mouse */
+	int		clicktotype;	/* flag */
+};
+
+struct Control
+{
+	/* known to client */
+	char		*name;
+	Rectangle	rect;
+	Rectangle	size;		/* minimum/maximum Dx, Dy (not a rect) */
+	Channel		*event;		/* chan(char*) to client */
+	Channel		*data;		/* chan(char*) to client */
+
+	/* internal to control set */
+	int		type;
+	int		hidden;		/* hide hides, show unhides (and redraws) */
+	Controlset	*controlset;
+	Image		*screen;	/* where Control appears */
+	char		*format;	/* used to generate events */
+	char		wevent;		/* event channel rewired */
+	char		wdata;		/* data channel rewired */
+
+	/* method table */
+	void		(*ctl)(Control*, CParse*);
+	void		(*mouse)(Control*, Mouse*);
+	void		(*key)(Control*, Rune*);
+	void		(*exit)(Control*);
+	void		(*setsize)(Control*);
+	void		(*activate)(Control*, int);
+	Control		*nextactive;
+	Control		*next;
+};
+
+struct CCache
+{
+	union{
+		Image	*image;
+		Font	*font;
+	};
+	char		*name;
+	int		index;		/* entry number in cache */
+	int		ref;		/* one for client, plus one for each use */
+};
+
+struct CParse
+{
+	char	str[256];
+	char	*sender;
+	char	*receiver;
+	int	cmd;
+	char	*pargs[32];
+	int	iargs[32];
+	char	**args;
+	int	nargs;
+};
+
+enum	/* alignments */
+{
+	Aupperleft = 0,
+	Auppercenter,
+	Aupperright,
+	Acenterleft,
+	Acenter,
+	Acenterright,
+	Alowerleft,
+	Alowercenter,
+	Alowerright,
+	Nalignments
+};
+
+enum
+{
+	_Ctlmaxsize = 10000,
+};
+
+extern char *ctltypenames[];
+
+/* Functions used internally */
+void		_ctladdgroup(Control*, Control*);
+void		_ctlargcount(Control*, CParse*, int);
+Control*	_createctl(Controlset*, char*, uint, char*);
+Rune*		_ctlrunestr(char*);
+char*		_ctlstrrune(Rune*);
+void		_ctlputsnarf(Rune*);
+Rune*		_ctlgetsnarf(void);
+int		_ctlalignment(char*);
+Point		_ctlalignpoint(Rectangle, int, int, int);
+void		_ctlfocus(Control*, int);
+void		_activategroup(Control*);
+void		_deactivategroup(Control*);
+int		_ctllookup(char *s, char *tab[], int ntab);
+void		_ctlprint(Control *c, char *fmt, ...);
+
+/* images */
+CImage*		_getctlimage(char*);
+void		_setctlimage(Control*, CImage**, char*);
+void		_putctlimage(CImage*);
+CFont*		_getctlfont(char*);
+void		_putctlfont(CFont*);
+
+/* fonts */
+CImage*		_getctlfont(char*);
+void		_setctlfont(Control*, CImage**, char*);
+void		_putctlfont(CImage*);
+CFont*		_getctlfont(char*);
+void		_putctlfont(CFont*);
+
+/* Public functions */
+
+/* images */
+int		namectlimage(Image*, char*);
+int		freectlimage(char*);
+
+/* fonts */
+int		namectlfont(Font*, char*);
+int		freectlfont(char*);
+
+/* commands */
+int		ctlprint(Control*, char*, ...);
+
+/* general */
+void		initcontrols(void);
+Controlset*	newcontrolset(Image*, Channel*, Channel*, Channel*);
+void		closecontrolset(Controlset*);
+void		closecontrol(Control*);
+void		ctlerror(char*, ...);
+Control*	controlcalled(char*);
+
+/* publicly visible error-checking allocation routines */
+void*		ctlmalloc(uint);
+void*		ctlrealloc(void*, uint);
+char*		ctlstrdup(char*);
+
+/* creation */
+void		controlwire(Control*, char*, Channel*);
+void		activate(Control*);
+void		deactivate(Control*);
+Control*	createbox(Controlset*, char*);
+Control*	createbutton(Controlset*, char*);
+Control*	createcolumn(Controlset*, char*);
+Control*	createboxbox(Controlset*, char*);
+Control*	createentry(Controlset*, char*);
+Control*	createkeyboard(Controlset*, char*);
+Control*	createlabel(Controlset*, char*);
+Control*	createmenu(Controlset*, char*);
+Control*	createradiobutton(Controlset*, char*);
+Control*	createrow(Controlset*, char*);
+Control*	createscribble(Controlset*, char*);
+Control*	createslider(Controlset*, char*);
+Control*	createstack(Controlset*, char*);
+Control*	createtab(Controlset*, char*);
+Control*	createtext(Controlset*, char*);
+Control*	createtextbutton(Controlset*, char*);
+Control*	createtextbutton3(Controlset*, char*);
+
+/* user-supplied */
+void		resizecontrolset(Controlset*);
+
+int		_ctlsnarffd;
+char		*alignnames[];
+int		ctldeletequits;
--- /dev/null
+++ b/sys/include/ctype.h
@@ -1,0 +1,29 @@
+#pragma	src	"/sys/src/libc/port"
+#pragma	lib	"libc.a"
+
+#define	_U	01
+#define	_L	02
+#define	_N	04
+#define	_S	010
+#define	_P	020
+#define	_C	040
+#define	_B	0100
+#define	_X	0200
+
+extern unsigned char	_ctype[];
+
+#define	isalpha(c)	(_ctype[(unsigned char)(c)]&(_U|_L))
+#define	isupper(c)	(_ctype[(unsigned char)(c)]&_U)
+#define	islower(c)	(_ctype[(unsigned char)(c)]&_L)
+#define	isdigit(c)	(_ctype[(unsigned char)(c)]&_N)
+#define	isxdigit(c)	(_ctype[(unsigned char)(c)]&_X)
+#define	isspace(c)	(_ctype[(unsigned char)(c)]&_S)
+#define	ispunct(c)	(_ctype[(unsigned char)(c)]&_P)
+#define	isalnum(c)	(_ctype[(unsigned char)(c)]&(_U|_L|_N))
+#define	isprint(c)	(_ctype[(unsigned char)(c)]&(_P|_U|_L|_N|_B))
+#define	isgraph(c)	(_ctype[(unsigned char)(c)]&(_P|_U|_L|_N))
+#define	iscntrl(c)	(_ctype[(unsigned char)(c)]&_C)
+#define	isascii(c)	((unsigned char)(c)<=0177)
+#define	_toupper(c)	((c)-'a'+'A')
+#define	_tolower(c)	((c)-'A'+'a')
+#define	toascii(c)	((c)&0177)
--- /dev/null
+++ b/sys/include/cursor.h
@@ -1,0 +1,8 @@
+#pragma src "/sys/src/libdraw"
+
+struct	Cursor
+{
+	Point	offset;
+	uchar	clr[2*16];
+	uchar	set[2*16];
+};
--- /dev/null
+++ b/sys/include/disk.h
@@ -1,0 +1,66 @@
+#pragma src "/sys/src/libdisk"
+#pragma lib "libdisk.a"
+
+/* SCSI interface */
+typedef struct Scsi Scsi;
+struct Scsi {
+	QLock;
+	char*	inquire;
+	int	rawfd;
+	int	nchange;
+	ulong	changetime;
+};
+
+enum {
+	Sread = 0,
+	Swrite,
+	Snone,
+};
+
+char*	scsierror(int, int);
+int		scsicmd(Scsi*, uchar*, int, void*, int, int);
+int		scsi(Scsi*, uchar*, int, void*, int, int);
+Scsi*		openscsi(char*);
+void		closescsi(Scsi*);
+int		scsiready(Scsi*);
+
+extern int		scsiverbose;
+
+/* disk partition interface */
+typedef struct Disk Disk;
+struct Disk {
+	char *prefix;
+	char *part;
+	int fd;
+	int wfd;
+	int ctlfd;
+	int rdonly;
+	int type;
+
+	vlong secs;
+	vlong secsize;
+	vlong size;
+	vlong offset;	/* within larger disk, perhaps */
+	int width;	/* of disk size in bytes as decimal string */
+	int c;
+	int h;
+	int s;
+	int chssrc;
+};
+
+Disk*	opendisk(char*, int, int);
+
+enum {
+	Tfile = 0,
+	Tsd,
+	Tfloppy,
+
+	Gpart = 0,	/* partition info source */
+	Gdisk,
+	Gguess,
+};
+
+/* proto file parsing */
+typedef void Protoenum(char *new, char *old, Dir *d, void *a);
+typedef void Protowarn(char *msg, void *a);
+int rdproto(char*, char*, Protoenum*, Protowarn*, void*);
--- /dev/null
+++ b/sys/include/draw.h
@@ -1,0 +1,527 @@
+#pragma src "/sys/src/libdraw"
+#pragma lib "libdraw.a"
+
+typedef struct	Cachefont Cachefont;
+typedef struct	Cacheinfo Cacheinfo;
+typedef struct	Cachesubf Cachesubf;
+typedef struct	Display Display;
+typedef struct	Font Font;
+typedef struct	Fontchar Fontchar;
+typedef struct	Image Image;
+typedef struct	Mouse Mouse;
+typedef struct	Point Point;
+typedef struct	Rectangle Rectangle;
+typedef struct	RGB RGB;
+typedef struct	Screen Screen;
+typedef struct	Subfont Subfont;
+
+#pragma incomplete Mouse
+
+#pragma varargck	type	"R"	Rectangle
+#pragma varargck	type	"P"	Point
+extern	int	Rfmt(Fmt*);
+extern	int	Pfmt(Fmt*);
+
+enum
+{
+	DOpaque		= 0xFFFFFFFF,
+	DTransparent	= 0x00000000,		/* only useful for allocimage, memfillcolor */
+	DBlack		= 0x000000FF,
+	DWhite		= 0xFFFFFFFF,
+	DRed		= 0xFF0000FF,
+	DGreen		= 0x00FF00FF,
+	DBlue		= 0x0000FFFF,
+	DCyan		= 0x00FFFFFF,
+	DMagenta		= 0xFF00FFFF,
+	DYellow		= 0xFFFF00FF,
+	DPaleyellow	= 0xFFFFAAFF,
+	DDarkyellow	= 0xEEEE9EFF,
+	DDarkgreen	= 0x448844FF,
+	DPalegreen	= 0xAAFFAAFF,
+	DMedgreen	= 0x88CC88FF,
+	DDarkblue	= 0x000055FF,
+	DPalebluegreen= 0xAAFFFFFF,
+	DPaleblue		= 0x0000BBFF,
+	DBluegreen	= 0x008888FF,
+	DGreygreen	= 0x55AAAAFF,
+	DPalegreygreen	= 0x9EEEEEFF,
+	DYellowgreen	= 0x99994CFF,
+	DMedblue		= 0x000099FF,
+	DGreyblue	= 0x005DBBFF,
+	DPalegreyblue	= 0x4993DDFF,
+	DPurpleblue	= 0x8888CCFF,
+
+	DNotacolor	= 0xFFFFFF00,
+	DNofill		= DNotacolor,
+	
+};
+
+enum
+{
+	Displaybufsize	= 8000,
+	ICOSSCALE	= 1024,
+	Borderwidth =	4,
+};
+
+enum
+{
+	/* refresh methods */
+	Refbackup	= 0,
+	Refnone		= 1,
+	Refmesg		= 2
+};
+#define	NOREFRESH	((void*)-1)
+
+enum
+{
+	/* line ends */
+	Endsquare	= 0,
+	Enddisc		= 1,
+	Endarrow	= 2,
+	Endmask		= 0x1F
+};
+
+#define	ARROW(a, b, c)	(Endarrow|((a)<<5)|((b)<<14)|((c)<<23))
+
+typedef enum
+{
+	/* Porter-Duff compositing operators */
+	Clear	= 0,
+
+	SinD	= 8,
+	DinS	= 4,
+	SoutD	= 2,
+	DoutS	= 1,
+
+	S		= SinD|SoutD,
+	SoverD	= SinD|SoutD|DoutS,
+	SatopD	= SinD|DoutS,
+	SxorD	= SoutD|DoutS,
+
+	D		= DinS|DoutS,
+	DoverS	= DinS|DoutS|SoutD,
+	DatopS	= DinS|SoutD,
+	DxorS	= DoutS|SoutD,	/* == SxorD */
+
+	Ncomp = 12,
+} Drawop;
+
+/*
+ * image channel descriptors 
+ */
+enum {
+	CRed = 0,
+	CGreen,
+	CBlue,
+	CGrey,
+	CAlpha,
+	CMap,
+	CIgnore,
+	NChan,
+};
+
+#define __DC(type, nbits)	((((type)&15)<<4)|((nbits)&15))
+#define CHAN1(a,b)	__DC(a,b)
+#define CHAN2(a,b,c,d)	(CHAN1((a),(b))<<8|__DC((c),(d)))
+#define CHAN3(a,b,c,d,e,f)	(CHAN2((a),(b),(c),(d))<<8|__DC((e),(f)))
+#define CHAN4(a,b,c,d,e,f,g,h)	(CHAN3((a),(b),(c),(d),(e),(f))<<8|__DC((g),(h)))
+
+#define NBITS(c) ((c)&15)
+#define TYPE(c) (((c)>>4)&15)
+
+enum {
+	GREY1	= CHAN1(CGrey, 1),
+	GREY2	= CHAN1(CGrey, 2),
+	GREY4	= CHAN1(CGrey, 4),
+	GREY8	= CHAN1(CGrey, 8),
+	CMAP8	= CHAN1(CMap, 8),
+	RGB15	= CHAN4(CIgnore, 1, CRed, 5, CGreen, 5, CBlue, 5),
+	RGB16	= CHAN3(CRed, 5, CGreen, 6, CBlue, 5),
+	RGB24	= CHAN3(CRed, 8, CGreen, 8, CBlue, 8),
+	RGBA32	= CHAN4(CRed, 8, CGreen, 8, CBlue, 8, CAlpha, 8),
+	ARGB32	= CHAN4(CAlpha, 8, CRed, 8, CGreen, 8, CBlue, 8),	/* stupid VGAs */
+	XRGB32	= CHAN4(CIgnore, 8, CRed, 8, CGreen, 8, CBlue, 8),
+	BGR24	= CHAN3(CBlue, 8, CGreen, 8, CRed, 8),
+	ABGR32	= CHAN4(CAlpha, 8, CBlue, 8, CGreen, 8, CRed, 8),
+	XBGR32	= CHAN4(CIgnore, 8, CBlue, 8, CGreen, 8, CRed, 8),
+};
+
+extern	char*	chantostr(char*, ulong);
+extern	ulong	strtochan(char*);
+extern	int		chantodepth(ulong);
+
+struct	Point
+{
+	int	x;
+	int	y;
+};
+
+struct Rectangle
+{
+	Point	min;
+	Point	max;
+};
+
+typedef void	(*Reffn)(Image*, Rectangle, void*);
+
+struct Screen
+{
+	Display	*display;	/* display holding data */
+	int	id;		/* id of system-held Screen */
+	Image	*image;		/* unused; for reference only */
+	Image	*fill;		/* color to paint behind windows */
+};
+
+struct Display
+{
+	QLock		qlock;
+	int		locking;	/*program is using lockdisplay */
+	int		dirno;
+	int		fd;
+	int		reffd;
+	int		ctlfd;
+	int		imageid;
+	int		local;
+	void		(*error)(Display*, char*);
+	char		*devdir;
+	char		*windir;
+	char		oldlabel[64];
+	ulong		dataqid;
+	Image		*white;
+	Image		*black;
+	Image		*opaque;
+	Image		*transparent;
+	Image		*image;
+	uchar		*buf;
+	int		bufsize;
+	uchar		*bufp;
+	Font		*defaultfont;
+	Subfont		*defaultsubfont;
+	Image		*windows;
+	Image		*screenimage;
+	int		_isnewdisplay;
+};
+
+struct Image
+{
+	Display		*display;	/* display holding data */
+	int		id;		/* id of system-held Image */
+	Rectangle	r;		/* rectangle in data area, local coords */
+	Rectangle 	clipr;		/* clipping region */
+	int		depth;		/* number of bits per pixel */
+	ulong		chan;
+	int		repl;		/* flag: data replicates to tile clipr */
+	Screen		*screen;	/* 0 if not a window */
+	Image		*next;	/* next in list of windows */
+};
+
+struct RGB
+{
+	ulong	red;
+	ulong	green;
+	ulong	blue;
+};
+
+/*
+ * Subfonts
+ *
+ * given char c, Subfont *f, Fontchar *i, and Point p, one says
+ *	i = f->info+c;
+ *	draw(b, Rect(p.x+i->left, p.y+i->top,
+ *		p.x+i->left+((i+1)->x-i->x), p.y+i->bottom),
+ *		color, f->bits, Pt(i->x, i->top));
+ *	p.x += i->width;
+ * to draw characters in the specified color (itself an Image) in Image b.
+ */
+
+struct	Fontchar
+{
+	int		x;		/* left edge of bits */
+	uchar		top;		/* first non-zero scan-line */
+	uchar		bottom;		/* last non-zero scan-line + 1 */
+	char		left;		/* offset of baseline */
+	uchar		width;		/* width of baseline */
+};
+
+struct	Subfont
+{
+	char		*name;
+	short		n;		/* number of chars in font */
+	uchar		height;		/* height of image */
+	char		ascent;		/* top of image to baseline */
+	Fontchar 	*info;		/* n+1 character descriptors */
+	Image		*bits;		/* of font */
+	int		ref;
+};
+
+enum
+{
+	/* starting values */
+	LOG2NFCACHE =	6,
+	NFCACHE =	(1<<LOG2NFCACHE),	/* #chars cached */
+	NFLOOK =	5,			/* #chars to scan in cache */
+	NFSUBF =	2,			/* #subfonts to cache */
+	/* max value */
+	MAXFCACHE =	1024+NFLOOK,		/* upper limit */
+	MAXSUBF =	50,			/* generous upper limit */
+	/* deltas */
+	DSUBF = 	4,
+	/* expiry ages */
+	SUBFAGE	=	10000,
+	CACHEAGE =	10000
+};
+
+struct Cachefont
+{
+	Rune		min;	/* lowest rune value to be taken from subfont */
+	Rune		max;	/* highest rune value+1 to be taken from subfont */
+	int		offset;	/* position in subfont of character at min */
+	char		*name;			/* stored in font */
+	char		*subfontname;		/* to access subfont */
+};
+
+struct Cacheinfo
+{
+	ushort		x;		/* left edge of bits */
+	uchar		width;		/* width of baseline */
+	schar		left;		/* offset of baseline */
+	Rune		value;	/* value of character at this slot in cache */
+	ushort		age;
+};
+
+struct Cachesubf
+{
+	ulong		age;	/* for replacement */
+	Cachefont	*cf;	/* font info that owns us */
+	Subfont		*f;	/* attached subfont */
+};
+
+struct Font
+{
+	char		*name;
+	Display		*display;
+	short		height;	/* max height of image, interline spacing */
+	short		ascent;	/* top of image to baseline */
+	short		width;	/* widest so far; used in caching only */	
+	short		nsub;	/* number of subfonts */
+	ulong		age;	/* increasing counter; used for LRU */
+	int		maxdepth;	/* maximum depth of all loaded subfonts */
+	int		ncache;	/* size of cache */
+	int		nsubf;	/* size of subfont list */
+	Cacheinfo	*cache;
+	Cachesubf	*subf;
+	Cachefont	**sub;	/* as read from file */
+	Image		*cacheimage;
+};
+
+#define	Dx(r)	((r).max.x-(r).min.x)
+#define	Dy(r)	((r).max.y-(r).min.y)
+
+/*
+ * One of a kind
+ */
+extern int		mousescrollsize(int);
+
+/*
+ * Image management
+ */
+extern Image*	_allocimage(Image*, Display*, Rectangle, ulong, int, ulong, int, int);
+extern Image*	allocimage(Display*, Rectangle, ulong, int, ulong);
+extern uchar*	bufimage(Display*, int);
+extern int	bytesperline(Rectangle, int);
+extern void	closedisplay(Display*);
+extern void	drawerror(Display*, char*);
+extern int	flushimage(Display*, int);
+extern int	freeimage(Image*);
+extern int	_freeimage1(Image*);
+extern int	geninitdraw(char*, void(*)(Display*, char*), char*, char*, char*, int);
+extern int	initdraw(void(*)(Display*, char*), char*, char*);
+extern int	newwindow(char*);
+extern Display*	initdisplay(char*, char*, void(*)(Display*, char*));
+extern int	loadimage(Image*, Rectangle, uchar*, int);
+extern int	cloadimage(Image*, Rectangle, uchar*, int);
+extern int	getwindow(Display*, int);
+extern int	gengetwindow(Display*, char*, Image**, Screen**, int);
+extern Image* readimage(Display*, int, int);
+extern Image* creadimage(Display*, int, int);
+extern int	unloadimage(Image*, Rectangle, uchar*, int);
+extern int	wordsperline(Rectangle, int);
+extern int	writeimage(int, Image*, int);
+extern Image*	namedimage(Display*, char*);
+extern int	nameimage(Image*, char*, int);
+extern Image* allocimagemix(Display*, ulong, ulong);
+
+/*
+ * Colors
+ */
+extern	void	readcolmap(Display*, RGB*);
+extern	void	writecolmap(Display*, RGB*);
+extern	ulong	setalpha(ulong, uchar);
+
+/*
+ * Windows
+ */
+extern Screen*	allocscreen(Image*, Image*, int);
+extern Image*	_allocwindow(Image*, Screen*, Rectangle, int, ulong);
+extern Image*	allocwindow(Screen*, Rectangle, int, ulong);
+extern void	bottomnwindows(Image**, int);
+extern void	bottomwindow(Image*);
+extern int	freescreen(Screen*);
+extern Screen*	publicscreen(Display*, int, ulong);
+extern void	topnwindows(Image**, int);
+extern void	topwindow(Image*);
+extern int	originwindow(Image*, Point, Point);
+
+/*
+ * Geometry
+ */
+extern Point		Pt(int, int);
+extern Rectangle	Rect(int, int, int, int);
+extern Rectangle	Rpt(Point, Point);
+extern Point		addpt(Point, Point);
+extern Point		subpt(Point, Point);
+extern Point		divpt(Point, int);
+extern Point		mulpt(Point, int);
+extern int		eqpt(Point, Point);
+extern int		eqrect(Rectangle, Rectangle);
+extern Rectangle	insetrect(Rectangle, int);
+extern Rectangle	rectaddpt(Rectangle, Point);
+extern Rectangle	rectsubpt(Rectangle, Point);
+extern Rectangle	canonrect(Rectangle);
+extern int		rectXrect(Rectangle, Rectangle);
+extern int		rectinrect(Rectangle, Rectangle);
+extern void		combinerect(Rectangle*, Rectangle);
+extern int		rectclip(Rectangle*, Rectangle);
+extern int		ptinrect(Point, Rectangle);
+extern void		replclipr(Image*, int, Rectangle);
+extern int		drawreplxy(int, int, int);	/* used to be drawsetxy */
+extern Point	drawrepl(Rectangle, Point);
+extern int		rgb2cmap(int, int, int);
+extern int		cmap2rgb(int);
+extern int		cmap2rgba(int);
+extern void		icossin(int, int*, int*);
+extern void		icossin2(int, int, int*, int*);
+
+/*
+ * Graphics
+ */
+extern void	draw(Image*, Rectangle, Image*, Image*, Point);
+extern void	drawop(Image*, Rectangle, Image*, Image*, Point, Drawop);
+extern void	gendraw(Image*, Rectangle, Image*, Point, Image*, Point);
+extern void	gendrawop(Image*, Rectangle, Image*, Point, Image*, Point, Drawop);
+extern void	line(Image*, Point, Point, int, int, int, Image*, Point);
+extern void	lineop(Image*, Point, Point, int, int, int, Image*, Point, Drawop);
+extern void	poly(Image*, Point*, int, int, int, int, Image*, Point);
+extern void	polyop(Image*, Point*, int, int, int, int, Image*, Point, Drawop);
+extern void	fillpoly(Image*, Point*, int, int, Image*, Point);
+extern void	fillpolyop(Image*, Point*, int, int, Image*, Point, Drawop);
+extern Point	string(Image*, Point, Image*, Point, Font*, char*);
+extern Point	stringop(Image*, Point, Image*, Point, Font*, char*, Drawop);
+extern Point	stringn(Image*, Point, Image*, Point, Font*, char*, int);
+extern Point	stringnop(Image*, Point, Image*, Point, Font*, char*, int, Drawop);
+extern Point	runestring(Image*, Point, Image*, Point, Font*, Rune*);
+extern Point	runestringop(Image*, Point, Image*, Point, Font*, Rune*, Drawop);
+extern Point	runestringn(Image*, Point, Image*, Point, Font*, Rune*, int);
+extern Point	runestringnop(Image*, Point, Image*, Point, Font*, Rune*, int, Drawop);
+extern Point	stringbg(Image*, Point, Image*, Point, Font*, char*, Image*, Point);
+extern Point	stringbgop(Image*, Point, Image*, Point, Font*, char*, Image*, Point, Drawop);
+extern Point	stringnbg(Image*, Point, Image*, Point, Font*, char*, int, Image*, Point);
+extern Point	stringnbgop(Image*, Point, Image*, Point, Font*, char*, int, Image*, Point, Drawop);
+extern Point	runestringbg(Image*, Point, Image*, Point, Font*, Rune*, Image*, Point);
+extern Point	runestringbgop(Image*, Point, Image*, Point, Font*, Rune*, Image*, Point, Drawop);
+extern Point	runestringnbg(Image*, Point, Image*, Point, Font*, Rune*, int, Image*, Point);
+extern Point	runestringnbgop(Image*, Point, Image*, Point, Font*, Rune*, int, Image*, Point, Drawop);
+extern Point	_string(Image*, Point, Image*, Point, Font*, char*, Rune*, int, Rectangle, Image*, Point, Drawop);
+extern Point	stringsubfont(Image*, Point, Image*, Subfont*, char*);
+extern int		bezier(Image*, Point, Point, Point, Point, int, int, int, Image*, Point);
+extern int		bezierop(Image*, Point, Point, Point, Point, int, int, int, Image*, Point, Drawop);
+extern int		bezspline(Image*, Point*, int, int, int, int, Image*, Point);
+extern int		bezsplineop(Image*, Point*, int, int, int, int, Image*, Point, Drawop);
+extern int		bezsplinepts(Point*, int, Point**);
+extern int		fillbezier(Image*, Point, Point, Point, Point, int, Image*, Point);
+extern int		fillbezierop(Image*, Point, Point, Point, Point, int, Image*, Point, Drawop);
+extern int		fillbezspline(Image*, Point*, int, int, Image*, Point);
+extern int		fillbezsplineop(Image*, Point*, int, int, Image*, Point, Drawop);
+extern void	ellipse(Image*, Point, int, int, int, Image*, Point);
+extern void	ellipseop(Image*, Point, int, int, int, Image*, Point, Drawop);
+extern void	fillellipse(Image*, Point, int, int, Image*, Point);
+extern void	fillellipseop(Image*, Point, int, int, Image*, Point, Drawop);
+extern void	arc(Image*, Point, int, int, int, Image*, Point, int, int);
+extern void	arcop(Image*, Point, int, int, int, Image*, Point, int, int, Drawop);
+extern void	fillarc(Image*, Point, int, int, Image*, Point, int, int);
+extern void	fillarcop(Image*, Point, int, int, Image*, Point, int, int, Drawop);
+extern void	border(Image*, Rectangle, int, Image*, Point);
+extern void	borderop(Image*, Rectangle, int, Image*, Point, Drawop);
+
+/*
+ * Font management
+ */
+extern Font*	openfont(Display*, char*);
+extern Font*	buildfont(Display*, char*, char*);
+extern void	freefont(Font*);
+extern Font*	mkfont(Subfont*, Rune);
+extern int	cachechars(Font*, char**, Rune**, ushort*, int, int*, char**);
+extern void	agefont(Font*);
+extern Subfont*	allocsubfont(char*, int, int, int, Fontchar*, Image*);
+extern Subfont*	lookupsubfont(Display*, char*);
+extern void	installsubfont(char*, Subfont*);
+extern void	uninstallsubfont(Subfont*);
+extern void	freesubfont(Subfont*);
+extern Subfont*	readsubfont(Display*, char*, int, int);
+extern Subfont*	readsubfonti(Display*, char*, int, Image*, int);
+extern int	writesubfont(int, Subfont*);
+extern void	_unpackinfo(Fontchar*, uchar*, int);
+extern Point	stringsize(Font*, char*);
+extern int	stringwidth(Font*, char*);
+extern int	stringnwidth(Font*, char*, int);
+extern Point	runestringsize(Font*, Rune*);
+extern int	runestringwidth(Font*, Rune*);
+extern int	runestringnwidth(Font*, Rune*, int);
+extern Point	strsubfontwidth(Subfont*, char*);
+extern int	loadchar(Font*, Rune, Cacheinfo*, int, int, char**);
+extern char*	subfontname(char*, char*, int);
+extern Subfont*	_getsubfont(Display*, char*);
+extern Subfont*	getdefont(Display*);
+extern void		lockdisplay(Display*);
+extern void	unlockdisplay(Display*);
+extern int		drawlsetrefresh(ulong, int, void*, void*);
+
+/*
+ * Predefined 
+ */
+extern	uchar	defontdata[];
+extern	int		sizeofdefont;
+extern	Point		ZP;
+extern	Rectangle	ZR;
+
+/*
+ * Set up by initdraw()
+ */
+extern	Display	*display;
+extern	Font		*font;
+extern	Image	*screen;
+extern	Screen	*_screen;
+extern	int	_cursorfd;
+extern	int	_drawdebug;	/* set to 1 to see errors from flushimage */
+extern	void	_setdrawop(Display*, Drawop);
+
+#define	BGSHORT(p)		(((p)[0]<<0) | ((p)[1]<<8))
+#define	BGLONG(p)		((BGSHORT(p)<<0) | (BGSHORT(p+2)<<16))
+#define	BPSHORT(p, v)		((p)[0]=(v), (p)[1]=((v)>>8))
+#define	BPLONG(p, v)		(BPSHORT(p, (v)), BPSHORT(p+2, (v)>>16))
+
+/*
+ * Compressed image file parameters and helper routines
+ */
+#define	NMATCH	3		/* shortest match possible */
+#define	NRUN	(NMATCH+31)	/* longest match possible */
+#define	NMEM	1024		/* window size */
+#define	NDUMP	128		/* maximum length of dump */
+#define	NCBLOCK	6000		/* size of compressed blocks */
+extern	void	_twiddlecompressed(uchar*, int);
+extern	int	_compblocksize(Rectangle, int);
+
+/* XXX backwards helps; should go */
+// extern	int		log2[];	/* was used by libmemlayer/line.c */
+extern	ulong	drawld2chan[];
+extern	void		drawsetdebug(int);
--- /dev/null
+++ b/sys/include/event.h
@@ -1,0 +1,66 @@
+#pragma src "/sys/src/libdraw"
+#pragma lib "libdraw.a"
+
+typedef struct	Cursor Cursor;
+typedef struct	Event Event;
+typedef struct	Menu Menu;
+
+enum
+{
+	Emouse		= 1,
+	Ekeyboard	= 2,
+};
+
+enum
+{
+	MAXSLAVE = 32,
+	EMAXMSG = 128+8192,	/* size of 9p header+data */
+};
+
+struct	Mouse
+{
+	int	buttons;	/* bit array: LMR=124 */
+	Point	xy;
+	ulong	msec;
+};
+
+struct	Event
+{
+	int	kbdc;
+	Mouse	mouse;
+	int	n;		/* number of characters in message */
+	void	*v;		/* data unpacked by general event-handling function */
+	uchar	data[EMAXMSG];	/* message from an arbitrary file descriptor */
+};
+
+struct Menu
+{
+	char	**item;
+	char	*(*gen)(int);
+	int	lasthit;
+};
+
+/*
+ * Events
+ */
+extern void	 einit(ulong);
+extern ulong	 estart(ulong, int, int);
+extern ulong	 estartfn(ulong, int, int, int (*fn)(int, Event*, uchar*, int));
+extern ulong	 etimer(ulong, int);
+extern ulong	 event(Event*);
+extern ulong	 eread(ulong, Event*);
+extern Mouse	 emouse(void);
+extern int	 ekbd(void);
+extern int	 ecanread(ulong);
+extern int	 ecanmouse(void);
+extern int	 ecankbd(void);
+extern void	 eresized(int);	/* supplied by user */
+extern int	 emenuhit(int, Mouse*, Menu*);
+extern int	eatomouse(Mouse*, char*, int);
+extern Rectangle	getrect(int, Mouse*);
+extern void	 esetcursor(Cursor*);
+extern void	 emoveto(Point);
+extern Rectangle	egetrect(int, Mouse*);
+extern void		edrawgetrect(Rectangle, int);
+extern int		ereadmouse(Mouse*);
+extern int		eatomouse(Mouse*, char*, int);
--- /dev/null
+++ b/sys/include/fcall.h
@@ -1,0 +1,140 @@
+#pragma	src	"/sys/src/libc/9sys"
+#pragma	lib	"libc.a"
+
+#define	VERSION9P	"9P2000"
+
+#define	MAXWELEM	16
+
+typedef
+struct	Fcall
+{
+	uchar	type;
+	u32int	fid;
+	ushort	tag;
+	union {
+		struct {
+			u32int	msize;		/* Tversion, Rversion */
+			char	*version;	/* Tversion, Rversion */
+		};
+		struct {
+			ushort	oldtag;		/* Tflush */
+		};
+		struct {
+			char	*ename;		/* Rerror */
+		};
+		struct {
+			Qid	qid;		/* Rattach, Ropen, Rcreate */
+			u32int	iounit;		/* Ropen, Rcreate */
+		};
+		struct {
+			Qid	aqid;		/* Rauth */
+		};
+		struct {
+			u32int	afid;		/* Tauth, Tattach */
+			char	*uname;		/* Tauth, Tattach */
+			char	*aname;		/* Tauth, Tattach */
+		};
+		struct {
+			u32int	perm;		/* Tcreate */ 
+			char	*name;		/* Tcreate */
+			uchar	mode;		/* Tcreate, Topen */
+		};
+		struct {
+			u32int	newfid;		/* Twalk */
+			ushort	nwname;		/* Twalk */
+			char	*wname[MAXWELEM];	/* Twalk */
+		};
+		struct {
+			ushort	nwqid;		/* Rwalk */
+			Qid	wqid[MAXWELEM];		/* Rwalk */
+		};
+		struct {
+			vlong	offset;		/* Tread, Twrite */
+			u32int	count;		/* Tread, Twrite, Rread */
+			char	*data;		/* Twrite, Rread */
+		};
+		struct {
+			ushort	nstat;		/* Twstat, Rstat */
+			uchar	*stat;		/* Twstat, Rstat */
+		};
+	};
+} Fcall;
+
+
+#define	GBIT8(p)	((p)[0])
+#define	GBIT16(p)	((p)[0]|((p)[1]<<8))
+#define	GBIT32(p)	((p)[0]|((p)[1]<<8)|((p)[2]<<16)|((p)[3]<<24))
+#define	GBIT64(p)	((u32int)((p)[0]|((p)[1]<<8)|((p)[2]<<16)|((p)[3]<<24)) |\
+				((vlong)((p)[4]|((p)[5]<<8)|((p)[6]<<16)|((p)[7]<<24)) << 32))
+
+#define	PBIT8(p,v)	(p)[0]=(v)
+#define	PBIT16(p,v)	(p)[0]=(v);(p)[1]=(v)>>8
+#define	PBIT32(p,v)	(p)[0]=(v);(p)[1]=(v)>>8;(p)[2]=(v)>>16;(p)[3]=(v)>>24
+#define	PBIT64(p,v)	(p)[0]=(v);(p)[1]=(v)>>8;(p)[2]=(v)>>16;(p)[3]=(v)>>24;\
+			(p)[4]=(v)>>32;(p)[5]=(v)>>40;(p)[6]=(v)>>48;(p)[7]=(v)>>56
+
+#define	BIT8SZ		1
+#define	BIT16SZ		2
+#define	BIT32SZ		4
+#define	BIT64SZ		8
+#define	QIDSZ	(BIT8SZ+BIT32SZ+BIT64SZ)
+
+/* STATFIXLEN includes leading 16-bit count */
+/* The count, however, excludes itself; total size is BIT16SZ+count */
+#define STATFIXLEN	(BIT16SZ+QIDSZ+5*BIT16SZ+4*BIT32SZ+1*BIT64SZ)	/* amount of fixed length data in a stat buffer */
+
+#define	NOTAG		(ushort)~0U	/* Dummy tag */
+#define	NOFID		(u32int)~0U	/* Dummy fid */
+#define	IOHDRSZ		24	/* ample room for Twrite/Rread header (iounit) */
+
+enum
+{
+	Tversion =	100,
+	Rversion,
+	Tauth =		102,
+	Rauth,
+	Tattach =	104,
+	Rattach,
+	Terror =	106,	/* illegal */
+	Rerror,
+	Tflush =	108,
+	Rflush,
+	Twalk =		110,
+	Rwalk,
+	Topen =		112,
+	Ropen,
+	Tcreate =	114,
+	Rcreate,
+	Tread =		116,
+	Rread,
+	Twrite =	118,
+	Rwrite,
+	Tclunk =	120,
+	Rclunk,
+	Tremove =	122,
+	Rremove,
+	Tstat =		124,
+	Rstat,
+	Twstat =	126,
+	Rwstat,
+	Tmax,
+};
+
+uint	convM2S(uchar*, uint, Fcall*);
+uint	convS2M(Fcall*, uchar*, uint);
+uint	sizeS2M(Fcall*);
+
+int	statcheck(uchar *abuf, uint nbuf);
+uint	convM2D(uchar*, uint, Dir*, char*);
+uint	convD2M(Dir*, uchar*, uint);
+uint	sizeD2M(Dir*);
+
+int	fcallfmt(Fmt*);
+int	dirfmt(Fmt*);
+int	dirmodefmt(Fmt*);
+
+int	read9pmsg(int, void*, uint);
+
+#pragma	varargck	type	"F"	Fcall*
+#pragma	varargck	type	"M"	ulong
+#pragma	varargck	type	"D"	Dir*
--- /dev/null
+++ b/sys/include/flate.h
@@ -1,0 +1,39 @@
+#pragma	lib	"libflate.a"
+#pragma	src	"/sys/src/libflate"
+
+/*
+ * errors from deflate, deflateinit, deflateblock,
+ * inflate, inflateinit, inflateblock.
+ * convertable to a string by flateerr
+ */
+enum
+{
+	FlateOk			= 0,
+	FlateNoMem		= -1,
+	FlateInputFail		= -2,
+	FlateOutputFail		= -3,
+	FlateCorrupted		= -4,
+	FlateInternal		= -5,
+};
+
+int	deflateinit(void);
+int	deflate(void *wr, int (*w)(void*, void*, int), void *rr, int (*r)(void*, void*, int), int level, int debug);
+
+int	inflateinit(void);
+int	inflate(void *wr, int (*w)(void*, void*, int), void *getr, int (*get)(void*));
+
+int	inflateblock(uchar *dst, int dsize, uchar *src, int ssize);
+int	deflateblock(uchar *dst, int dsize, uchar *src, int ssize, int level, int debug);
+
+int	deflatezlib(void *wr, int (*w)(void*, void*, int), void *rr, int (*r)(void*, void*, int), int level, int debug);
+int	inflatezlib(void *wr, int (*w)(void*, void*, int), void *getr, int (*get)(void*));
+
+int	inflatezlibblock(uchar *dst, int dsize, uchar *src, int ssize);
+int	deflatezlibblock(uchar *dst, int dsize, uchar *src, int ssize, int level, int debug);
+
+char	*flateerr(int err);
+
+ulong	*mkcrctab(ulong);
+ulong	blockcrc(ulong *tab, ulong crc, void *buf, int n);
+
+ulong	adler32(ulong adler, void *buf, int n);
--- /dev/null
+++ b/sys/include/frame.h
@@ -1,0 +1,93 @@
+#pragma	src	"/sys/src/libframe"
+#pragma	lib	"libframe.a"
+
+typedef struct Frbox Frbox;
+typedef struct Frame Frame;
+
+enum{
+	BACK,
+	HIGH,
+	BORD,
+	TEXT,
+	HTEXT,
+	NCOL
+};
+
+#define	FRTICKW	3
+
+struct Frbox
+{
+	long		wid;		/* in pixels */
+	long		nrune;		/* <0 ==> negate and treat as break char */
+	union{
+		uchar	*ptr;
+		struct{
+			short	bc;	/* break char */
+			short	minwid;
+		};
+	};
+};
+
+struct Frame
+{
+	Font		*font;		/* of chars in the frame */
+	Display		*display;	/* on which frame appears */
+	Image		*b;		/* on which frame appears */
+	Image		*cols[NCOL];	/* text and background colors */
+	Rectangle	r;		/* in which text appears */
+	Rectangle	entire;		/* of full frame */
+	void			(*scroll)(Frame*, int);	/* scroll function provided by application */
+	Frbox		*box;
+	ulong		p0, p1;		/* selection */
+	ushort		nbox, nalloc;
+	ushort		maxtab;		/* max size of tab, in pixels */
+	ushort		nchars;		/* # runes in frame */
+	ushort		nlines;		/* # lines with text */
+	ushort		maxlines;	/* total # lines in frame */
+	ushort		lastlinefull;	/* last line fills frame */
+	ushort		modified;	/* changed since frselect() */
+	Image		*tick;	/* typing tick */
+	Image		*tickback;	/* saved image under tick */
+	int			ticked;	/* flag: is tick onscreen? */
+};
+
+ulong	frcharofpt(Frame*, Point);
+Point	frptofchar(Frame*, ulong);
+int	frdelete(Frame*, ulong, ulong);
+void	frinsert(Frame*, Rune*, Rune*, ulong);
+void	frselect(Frame*, Mousectl*);
+void	frselectpaint(Frame*, Point, Point, Image*);
+void	frdrawsel(Frame*, Point, ulong, ulong, int);
+Point frdrawsel0(Frame*, Point, ulong, ulong, Image*, Image*);
+void	frinit(Frame*, Rectangle, Font*, Image*, Image**);
+void	frsetrects(Frame*, Rectangle, Image*);
+void	frclear(Frame*, int);
+
+uchar	*_frallocstr(Frame*, unsigned);
+void	_frinsure(Frame*, int, unsigned);
+Point	_frdraw(Frame*, Point);
+void	_frgrowbox(Frame*, int);
+void	_frfreebox(Frame*, int, int);
+void	_frmergebox(Frame*, int);
+void	_frdelbox(Frame*, int, int);
+void	_frsplitbox(Frame*, int, int);
+int	_frfindbox(Frame*, int, ulong, ulong);
+void	_frclosebox(Frame*, int, int);
+int	_frcanfit(Frame*, Point, Frbox*);
+void	_frcklinewrap(Frame*, Point*, Frbox*);
+void	_frcklinewrap0(Frame*, Point*, Frbox*);
+void	_fradvance(Frame*, Point*, Frbox*);
+int	_frnewwid(Frame*, Point, Frbox*);
+int	_frnewwid0(Frame*, Point, Frbox*);
+void	_frclean(Frame*, Point, int, int);
+void	_frdrawtext(Frame*, Point, Image*, Image*);
+void	_fraddbox(Frame*, int, int);
+Point	_frptofcharptb(Frame*, ulong, Point, int);
+Point	_frptofcharnb(Frame*, ulong, int);
+int	_frstrlen(Frame*, int);
+void	frtick(Frame*, Point, int);
+void	frinittick(Frame*);
+void	frredraw(Frame*);
+
+#define	NRUNE(b)	((b)->nrune<0? 1 : (b)->nrune)
+#define	NBYTE(b)	strlen((char*)(b)->ptr)
--- /dev/null
+++ b/sys/include/geometry.h
@@ -1,0 +1,89 @@
+#pragma lib "libgeometry.a"
+#pragma src "/sys/src/libgeometry"
+typedef double Matrix[4][4];
+typedef struct Point3 Point3;
+typedef struct Quaternion Quaternion;
+typedef struct Space Space;
+struct Point3{
+	double x, y, z, w;
+};
+struct Quaternion{
+	double r, i, j, k;
+};
+struct Space{
+	Matrix t;
+	Matrix tinv;
+	Space *next;
+};
+/*
+ * 3-d point arithmetic
+ */
+Point3 add3(Point3 a, Point3 b);
+Point3 sub3(Point3 a, Point3 b);
+Point3 neg3(Point3 a);
+Point3 div3(Point3 a, double b);
+Point3 mul3(Point3 a, double b);
+int eqpt3(Point3 p, Point3 q);
+int closept3(Point3 p, Point3 q, double eps);
+double dot3(Point3 p, Point3 q);
+Point3 cross3(Point3 p, Point3 q);
+double len3(Point3 p);
+double dist3(Point3 p, Point3 q);
+Point3 unit3(Point3 p);
+Point3 midpt3(Point3 p, Point3 q);
+Point3 lerp3(Point3 p, Point3 q, double alpha);
+Point3 reflect3(Point3 p, Point3 p0, Point3 p1);
+Point3 nearseg3(Point3 p0, Point3 p1, Point3 testp);
+double pldist3(Point3 p, Point3 p0, Point3 p1);
+double vdiv3(Point3 a, Point3 b);
+Point3 vrem3(Point3 a, Point3 b);
+Point3 pn2f3(Point3 p, Point3 n);
+Point3 ppp2f3(Point3 p0, Point3 p1, Point3 p2);
+Point3 fff2p3(Point3 f0, Point3 f1, Point3 f2);
+Point3 pdiv4(Point3 a);
+Point3 add4(Point3 a, Point3 b);
+Point3 sub4(Point3 a, Point3 b);
+/*
+ * Quaternion arithmetic
+ */
+void qtom(Matrix, Quaternion);
+Quaternion mtoq(Matrix);
+Quaternion qadd(Quaternion, Quaternion);
+Quaternion qsub(Quaternion, Quaternion);
+Quaternion qneg(Quaternion);
+Quaternion qmul(Quaternion, Quaternion);
+Quaternion qdiv(Quaternion, Quaternion);
+Quaternion qunit(Quaternion);
+Quaternion qinv(Quaternion);
+double qlen(Quaternion);
+Quaternion slerp(Quaternion, Quaternion, double);
+Quaternion qmid(Quaternion, Quaternion);
+Quaternion qsqrt(Quaternion);
+void qball(Rectangle, Mouse *, Quaternion *, void (*)(void), Quaternion *);
+/*
+ * Matrix arithmetic
+ */
+void ident(Matrix);
+void matmul(Matrix, Matrix);
+void matmulr(Matrix, Matrix);
+double determinant(Matrix);
+void adjoint(Matrix, Matrix);
+double invertmat(Matrix, Matrix);
+/*
+ * Space stack routines
+ */
+Space *pushmat(Space *);
+Space *popmat(Space *);
+void rot(Space *, double, int);
+void qrot(Space *, Quaternion);
+void scale(Space *, double, double, double);
+void move(Space *, double, double, double);
+void xform(Space *, Matrix);
+void ixform(Space *, Matrix, Matrix);
+void look(Space *, Point3, Point3, Point3);
+int persp(Space *, double, double, double);
+void viewport(Space *, Rectangle, double);
+Point3 xformpoint(Point3, Space *, Space *);
+Point3 xformpointd(Point3, Space *, Space *);
+Point3 xformplane(Point3, Space *, Space *);
+#define	radians(d)	((d)*.01745329251994329572)
--- /dev/null
+++ b/sys/include/html.h
@@ -1,0 +1,634 @@
+#pragma lib "libhtml.a"
+#pragma src "/sys/src/libhtml"
+
+/* UTILS */
+extern uchar*	fromStr(Rune* buf, int n, int chset);
+extern Rune*	toStr(uchar* buf, int n, int chset);
+
+/* Common LEX and BUILD enums */
+
+/* Media types */
+enum
+{
+	ApplMsword,
+	ApplOctets,
+	ApplPdf,
+	ApplPostscript,
+	ApplRtf,
+	ApplFramemaker,
+	ApplMsexcel,
+	ApplMspowerpoint,
+	UnknownType,
+	Audio32kadpcm,
+	AudioBasic,
+	ImageCgm,
+	ImageG3fax,
+	ImageGif,
+	ImageIef,
+	ImageJpeg,
+	ImagePng,
+	ImageTiff,
+	ImageXBit,
+	ImageXBit2,
+	ImageXBitmulti,
+	ImageXXBitmap,
+	ModelVrml,
+	MultiDigest,
+	MultiMixed,
+	TextCss,
+	TextEnriched,
+	TextHtml,
+	TextJavascript,
+	TextPlain,
+	TextRichtext,
+	TextSgml,
+	TextTabSeparatedValues,
+	TextXml,
+	VideoMpeg,
+	VideoQuicktime,
+	NMEDIATYPES
+};
+
+/* HTTP methods */
+enum
+{
+	HGet,
+	HPost
+};
+
+/* Charsets */
+enum
+{
+	UnknownCharset,
+	US_Ascii,
+	ISO_8859_1,
+	UTF_8,
+	Unicode,
+	NCHARSETS
+};
+
+/* Frame Target IDs */
+enum {
+	FTtop,
+	FTself,
+	FTparent,
+	FTblank
+};
+
+/* LEX */
+typedef struct Token Token;
+typedef struct Attr Attr;
+
+#pragma incomplete Token
+
+/* BUILD */
+
+typedef struct Item Item;
+typedef struct Itext Itext;
+typedef struct Irule Irule;
+typedef struct Iimage Iimage;
+typedef struct Iformfield Iformfield;
+typedef struct Itable Itable;
+typedef struct Ifloat Ifloat;
+typedef struct Ispacer Ispacer;
+typedef struct Genattr Genattr;
+typedef struct SEvent SEvent;
+typedef struct Formfield Formfield;
+typedef struct Option Option;
+typedef struct Form Form;
+typedef struct Table Table;
+typedef struct Tablecol Tablecol;
+typedef struct Tablerow Tablerow;
+typedef struct Tablecell Tablecell;
+typedef struct Align Align;
+typedef struct Dimen Dimen;
+typedef struct Anchor Anchor;
+typedef struct DestAnchor DestAnchor;
+typedef struct Map Map;
+typedef struct Area Area;
+typedef struct Background Background;
+typedef struct Kidinfo Kidinfo;
+typedef struct Docinfo Docinfo;
+typedef struct Stack Stack;
+typedef struct Pstate Pstate;
+typedef struct ItemSource ItemSource;
+typedef struct Lay Lay;		/* defined in Layout module */
+
+#pragma incomplete Lay
+
+
+/* Alignment types */
+enum {
+	ALnone = 0, ALleft, ALcenter, ALright, ALjustify,
+	ALchar, ALtop, ALmiddle, ALbottom, ALbaseline,
+};
+
+struct Align
+{
+	uchar	halign;		/* one of ALnone, ALleft, etc. */
+	uchar	valign;		/* one of ALnone, ALtop, etc. */
+};
+
+/*
+ * A Dimen holds a dimension specification, especially for those
+ * cases when a number can be followed by a % or a * to indicate
+ * percentage of total or relative weight.
+ * Dnone means no dimension was specified
+ */
+
+/* To fit in a word, use top bits to identify kind, rest for value */
+enum {
+	Dnone =		0,
+	Dpixels =	(1<<29),
+	Dpercent =	(2<<29),
+	Drelative =	(3<<29),
+	Dkindmask =	(3<<29),
+	Dspecmask =	(~Dkindmask)
+};
+
+struct Dimen
+{
+	int	kindspec;	/* kind | spec */
+};
+
+/*
+ * Background is either an image or a color.
+ * If both are set, the image has precedence.
+ */
+struct Background
+{
+	Rune*	image;		/* url */
+	int	color;
+};
+
+
+/*
+ * There are about a half dozen Item variants.
+ * The all look like this at the start (using Plan 9 C's
+ * anonymous structure member mechanism),
+ * and then the tag field dictates what extra fields there are.
+ */
+struct Item
+{
+	Item*	next;		/* successor in list of items */
+	int	width;		/* width in pixels (0 for floating items) */
+	int	height;		/* height in pixels */
+	int	ascent;		/* ascent (from top to baseline) in pixels */
+	int	anchorid;	/* if nonzero, which anchor we're in */
+	int	state;		/* flags and values (see below) */
+	Genattr*genattr;	/* generic attributes and events */
+	int	tag;		/* variant discriminator: Itexttag, etc. */
+};
+
+/* Item variant tags */
+enum {
+	Itexttag,
+	Iruletag,
+	Iimagetag,
+	Iformfieldtag,
+	Itabletag,
+	Ifloattag,
+	Ispacertag
+};
+
+struct Itext
+{
+	Item;			/* (with tag ==Itexttag) */
+	Rune*	s;		/* the characters */
+	int	fnt;		/* style*NumSize+size (see font stuff, below) */
+	int	fg;		/* Pixel (color) for text */
+	uchar	voff; /* Voffbias+vertical offset from baseline, in pixels (+ve == down) */
+	uchar	ul;		/* ULnone, ULunder, or ULmid */
+};
+
+struct Irule
+{
+	Item;			/* (with tag ==Iruletag) */
+	uchar	align;		/* alignment spec */
+	uchar	noshade;	/* if true, don't shade */
+	int	size;		/* size attr (rule height) */
+	int	color;		/* color attr */
+	Dimen	wspec;		/* width spec */
+};
+
+
+struct Iimage
+{
+	Item;			/* (with tag ==Iimagetag) */
+	Rune*	imsrc;		/* image src url */
+	int	imwidth;	/* spec width (actual, if no spec) */
+	int	imheight;	/* spec height (actual, if no spec) */
+	Rune*	altrep;		/* alternate representation, in absence of image */
+	Map*	map;		/* if non-nil, client side map */
+	int	ctlid;		/* if animated */
+	uchar	align;		/* vertical alignment */
+	uchar	hspace;		/* in pixels; buffer space on each side */
+	uchar	vspace;		/* in pixels; buffer space on top and bottom */
+	uchar	border;		/* in pixels: border width to draw around image */
+	Iimage*	nextimage;	/* next in list of document's images */
+	void*	aux;
+};
+
+
+struct Iformfield
+{
+	Item;			/* (with tag ==Iformfieldtag) */
+	Formfield*formfield;
+	void*	aux;
+};
+
+
+struct Itable
+{
+	Item;			/* (with tag ==Itabletag) */
+	Table*	table;
+};
+
+
+struct Ifloat
+{
+	Item;			/* (with tag ==Ifloattag) */
+	Item*	item;		/* table or image item that floats */
+	int	x;		/* x coord of top (from right, if ALright) */
+	int	y;		/* y coord of top */
+	uchar	side;		/* margin it floats to: ALleft or ALright */
+	uchar	infloats;	/* true if this has been added to a lay.floats */
+	Ifloat*	nextfloat;	/* in list of floats */
+};
+
+
+struct Ispacer
+{
+	Item;			/* (with tag ==Ispacertag) */
+	int	spkind;		/* ISPnull, etc. */
+};
+
+/* Item state flags and value fields */
+enum {
+	IFbrk	= 0x80000000,	/* forced break before this item */
+	IFbrksp	= 0x40000000,	/* add 1 line space to break (IFbrk set too) */
+	IFnobrk	= 0x20000000,	/* break not allowed before this item */
+	IFcleft	= 0x10000000,	/* clear left floats (IFbrk set too) */
+	IFcright= 0x08000000,	/* clear right floats (IFbrk set too) */
+	IFwrap	= 0x04000000,	/* in a wrapping (non-pre) line */
+	IFhang	= 0x02000000,	/* in a hanging (into left indent) item */
+	IFrjust	= 0x01000000,	/* right justify current line */
+	IFcjust	= 0x00800000,	/* center justify current line */
+	IFsmap	= 0x00400000,	/* image is server-side map */
+	IFindentshift	= 8,
+	IFindentmask	= (255<<IFindentshift),	/* current indent, in tab stops */
+	IFhangmask	= 255	/* current hang into left indent, in 1/10th tabstops */
+};
+
+/* Bias added to Itext's voff field */
+enum { Voffbias = 128 };
+
+/* Spacer kinds */
+enum {
+	ISPnull,	/* 0 height and width */
+	ISPvline,	/* height and ascent of current font */
+	ISPhspace,	/* width of space in current font */
+	ISPgeneral	/* other purposes (e.g., between markers and list) */
+};
+
+/* Generic attributes and events (not many elements will have any of these set) */
+struct Genattr
+{
+	Rune*	id;
+	Rune*	class;
+	Rune*	style;
+	Rune*	title;
+	SEvent*	events;
+};
+
+struct SEvent
+{
+	SEvent*	next;		/* in list of events */
+	int	type;		/* SEonblur, etc. */
+	Rune*	script;
+};
+
+enum {
+	SEonblur, SEonchange, SEonclick, SEondblclick,
+	SEonfocus, SEonkeypress, SEonkeyup, SEonload,
+	SEonmousedown, SEonmousemove, SEonmouseout,
+	SEonmouseover, SEonmouseup, SEonreset, SEonselect,
+	SEonsubmit, SEonunload,
+	Numscriptev
+};
+
+/* Form field types */
+enum {
+	Ftext,
+	Fpassword,
+	Fcheckbox,
+	Fradio,
+	Fsubmit,
+	Fhidden,
+	Fimage,
+	Freset,
+	Ffile,
+	Fbutton,
+	Fselect,
+	Ftextarea
+};
+
+/* Information about a field in a form */
+struct Formfield
+{
+	Formfield*next;		/* in list of fields for a form */
+	int	ftype;		/* Ftext, Fpassword, etc. */
+	int	fieldid;	/* serial no. of field within its form */
+	Form*	form;		/* containing form */
+	Rune*	name;		/* name attr */
+	Rune*	value;		/* value attr */
+	int	size;		/* size attr */
+	int	maxlength;	/* maxlength attr */
+	int	rows;		/* rows attr */
+	int	cols;		/* cols attr */
+	uchar	flags;		/* FFchecked, etc. */
+	Option*	options;	/* for Fselect fields */
+	Item*	image;		/* image item, for Fimage fields */
+	int	ctlid;		/* identifies control for this field in layout */
+	SEvent*	events;		/* same as genattr->events of containing item */
+};
+
+enum {
+	FFchecked =	(1<<7),
+	FFmultiple =	(1<<6)
+};
+
+/* Option holds info about an option in a "select" form field */
+struct Option
+{
+	Option*	next;		/* next in list of options for a field */
+	int	selected;	/* true if selected initially */
+	Rune*	value;		/* value attr */
+	Rune*	display;	/* display string */
+};
+
+/* Form holds info about a form */
+struct Form
+{
+	Form*	next;		/* in list of forms for document */
+	int	formid;		/* serial no. of form within its doc */
+	Rune*	name;	/* name or id attr (netscape uses name, HTML 4.0 uses id) */
+	Rune*	action;		/* action attr */
+	int	target;		/* target attr as targetid */
+	int	method;		/* HGet or HPost */
+	int	nfields;	/* number of fields */
+	Formfield*fields;	/* field's forms, in input order */
+};
+
+/* Flags used in various table structures */
+enum {
+	TFparsing =	(1<<7),
+	TFnowrap =	(1<<6),
+	TFisth =	(1<<5)
+};
+
+
+/* Information about a table */
+struct Table
+{
+	Table*	next;		/* next in list of document's tables */
+	int	tableid;	/* serial no. of table within its doc */
+	Tablerow*rows;		/* array of row specs (list during parsing) */
+	int	nrow;		/* total number of rows */
+	Tablecol*cols;		/* array of column specs */
+	int	ncol;		/* total number of columns */
+	Tablecell*cells;	/* list of unique cells */
+	int	ncell;		/* total number of cells */
+	Tablecell***grid;	/* 2-D array of cells */
+	Align	align;		/* alignment spec for whole table */
+	Dimen	width;		/* width spec for whole table */
+	int	border;		/* border attr */
+	int	cellspacing;	/* cellspacing attr */
+	int	cellpadding;	/* cellpadding attr */
+	Background background;	/* table background */
+	Item*	caption;	/* linked list of Items, giving caption */
+	uchar	caption_place;	/* ALtop or ALbottom */
+	Lay*	caption_lay;	/* layout of caption */
+	int	totw;		/* total width */
+	int	toth;		/* total height */
+	int	caph;		/* caption height */
+	int	availw;		/* used for previous 3 sizes */
+	Token*	tabletok;	/* token that started the table */
+	uchar	flags;		/* Lchanged, perhaps */
+};
+
+
+struct Tablecol
+{
+	int	width;
+	Align	align;
+	Point	pos;
+};
+
+
+struct Tablerow
+{
+	Tablerow*next;		/* Next in list of rows, during parsing */
+	Tablecell*cells;	/* Cells in row, linked through nextinrow */
+	int	height;
+	int	ascent;
+	Align	align;
+	Background background;
+	Point	pos;
+	uchar	flags;		/* 0 or TFparsing */
+};
+
+/*
+ * A Tablecell is one cell of a table.
+ * It may span multiple rows and multiple columns.
+ * Cells are linked on two lists: the list for all the cells of
+ * a document (the next pointers), and the list of all the
+ * cells that start in a given row (the nextinrow pointers)
+ */
+struct Tablecell
+{
+	Tablecell*next;		/* next in list of table's cells */
+	Tablecell*nextinrow;	/* next in list of row's cells */
+	int	cellid;		/* serial no. of cell within table */
+	Item*	content;	/* contents before layout */
+	Lay*	lay;		/* layout of cell */
+	int	rowspan;	/* number of rows spanned by this cell */
+	int	colspan;	/* number of cols spanned by this cell */
+	Align	align;		/* alignment spec */
+	uchar	flags;		/* TFparsing, TFnowrap, TFisth */
+	Dimen	wspec;		/* suggested width */
+	int	hspec;		/* suggested height */
+	Background background;	/* cell background */
+	int	minw;		/* minimum possible width */
+	int	maxw;		/* maximum width */
+	int	ascent;		/* cell's ascent */
+	int	row;		/* row of upper left corner */
+	int	col;		/* col of upper left corner */
+	Point	pos;		/* nw corner of cell contents, in cell */
+};
+
+/* Anchor is for info about hyperlinks that go somewhere */
+struct Anchor
+{
+	Anchor*	next;		/* next in list of document's anchors */
+	int	index;		/* serial no. of anchor within its doc */
+	Rune*	name;		/* name attr */
+	Rune*	href;		/* href attr */
+	int	target;		/* target attr as targetid */
+};
+
+
+/* DestAnchor is for info about hyperlinks that are destinations */
+struct DestAnchor
+{
+	DestAnchor*next;	/* next in list of document's destanchors */
+	int	index;		/* serial no. of anchor within its doc */
+	Rune*	name;		/* name attr */
+	Item*	item;		/* the destination */
+};
+
+
+/* Maps (client side) */
+struct Map
+{
+	Map*	next;		/* next in list of document's maps */
+	Rune*	name;		/* map name */
+	Area*	areas;		/* list of map areas */
+};
+
+
+struct Area
+{
+	Area*	next;		/* next in list of a map's areas */
+	int	shape;		/* SHrect, etc. */
+	Rune*	href;		/* associated hypertext link */
+	int	target;		/* associated target frame */
+	Dimen*	coords;		/* array of coords for shape */
+	int	ncoords;	/* size of coords array */
+};
+
+/* Area shapes */
+enum {
+	SHrect, SHcircle, SHpoly
+};
+
+/* Fonts are represented by integers: style*NumSize + size */
+
+/* Font styles */
+enum {
+	FntR,		/* roman */
+	FntI,		/* italic */
+	FntB,		/* bold */
+	FntT,		/* typewriter */
+	NumStyle
+};
+
+/* Font sizes */
+enum {
+	Tiny,
+	Small,
+	Normal,
+	Large,
+	Verylarge,
+	NumSize
+};
+
+enum {
+	NumFnt = NumStyle*NumSize,
+	DefFnt = FntR*NumSize+Normal,
+};
+
+/* Lines are needed through some text items, for underlining or strikethrough */
+enum {
+	ULnone, ULunder, ULmid
+};
+
+/* Kidinfo flags */
+enum {
+	FRnoresize =	(1<<0),
+	FRnoscroll =	(1<<1),
+	FRhscroll = 	(1<<2),
+	FRvscroll =	(1<<3),
+	FRhscrollauto = (1<<4),
+	FRvscrollauto =	(1<<5)
+};
+
+/* Information about child frame or frameset */
+struct Kidinfo
+{
+	Kidinfo*next;		/* in list of kidinfos for a frameset */
+	int	isframeset;
+
+	/* fields for "frame" */
+	Rune*	src;		/* only nil if a "dummy" frame or this is frameset */
+	Rune*	name;		/* always non-empty if this isn't frameset */
+	int	marginw;
+	int	marginh;
+	int	framebd;
+	int	flags;
+
+	/* fields for "frameset" */
+	Dimen*	rows;		/* array of row dimensions */
+	int	nrows;		/* length of rows */
+	Dimen*	cols;		/* array of col dimensions */
+	int	ncols;		/* length of cols */
+	Kidinfo*kidinfos;
+	Kidinfo*nextframeset;	/* parsing stack */
+};
+
+
+/* Document info (global information about HTML page) */
+struct Docinfo
+{
+	/* stuff from HTTP headers, doc head, and body tag */
+	Rune*	src;		/* original source of doc */
+	Rune*	base;		/* base URL of doc */
+	Rune*	doctitle;	/* from <title> element */
+	Background background;	/* background specification */
+	Iimage*	backgrounditem;	/* Image Item for doc background image, or nil */
+	int	text;		/* doc foreground (text) color */
+	int	link;		/* unvisited hyperlink color */
+	int	vlink;		/* visited hyperlink color */
+	int	alink;		/* highlighting hyperlink color */
+	int	target;		/* target frame default */
+	int	chset;		/* ISO_8859, etc. */
+	int	mediatype;	/* TextHtml, etc. */
+	int	scripttype;	/* TextJavascript, etc. */
+	int	hasscripts;	/* true if scripts used */
+	Rune*	refresh;	/* content of <http-equiv=Refresh ...> */
+	Kidinfo*kidinfo;	/* if a frameset */
+	int	frameid;	/* id of document frame */
+
+	/* info needed to respond to user actions */
+	Anchor*	anchors;	/* list of href anchors */
+	DestAnchor*dests;	/* list of destination anchors */
+	Form*	forms;		/* list of forms */
+	Table*	tables;		/* list of tables */
+	Map*	maps;		/* list of maps */
+	Iimage*	images;		/* list of image items (through nextimage links) */
+};
+
+extern int	dimenkind(Dimen d);
+extern int	dimenspec(Dimen d);
+extern void	freedocinfo(Docinfo* d);
+extern void	freeitems(Item* ithead);
+extern Item*	parsehtml(uchar* data, int datalen, Rune* src, int mtype, int chset, Docinfo** pdi);
+extern void	printitems(Item* items, char* msg);
+extern int	targetid(Rune* s);
+extern Rune*	targetname(int targid);
+extern int	validitems(Item* i);
+
+#pragma varargck	type "I"	Item*
+
+/* Control print output */
+extern int	warn;
+extern int	dbglex;
+extern int	dbgbuild;
+
+/*
+ * To be provided by caller
+ * emalloc and erealloc should not return if can't get memory.
+ * emalloc should zero its memory.
+ */
+extern void*	emalloc(ulong);
+extern void*	erealloc(void* p, ulong size);
--- /dev/null
+++ b/sys/include/httpd.h
@@ -1,0 +1,281 @@
+#pragma	lib	"libhttpd.a"
+#pragma	src	"/sys/src/libhttpd"
+
+typedef struct HConnect		HConnect;
+typedef struct HContent		HContent;
+typedef struct HContents	HContents;
+typedef struct HETag		HETag;
+typedef struct HFields		HFields;
+typedef struct Hio		Hio;
+typedef struct Htmlesc		Htmlesc;
+typedef struct HttpHead		HttpHead;
+typedef struct HttpReq		HttpReq;
+typedef struct HRange		HRange;
+typedef struct HSPairs		HSPairs;
+
+typedef struct Bin		Bin;
+
+#pragma incomplete Bin
+
+enum
+{
+	HMaxWord	= 32*1024,
+	HBufSize	= 32*1024,
+
+	/*
+	 * error messages
+	 */
+	HInternal	= 0,
+	HTempFail,
+	HUnimp,
+	HBadReq,
+	HBadSearch,
+	HNotFound,
+	HUnauth,
+	HSyntax,
+	HNoSearch,
+	HNoData,
+	HExpectFail,
+	HUnkVers,
+	HBadCont,
+	HOK,
+};
+
+/*
+ * table of html character escape codes
+ */
+struct Htmlesc
+{
+	char		*name;
+	Rune		value;
+};
+
+struct HContent
+{
+	HContent	*next;
+	char		*generic;
+	char		*specific;
+	float		q;		/* desirability of this kind of file */
+	int		mxb;		/* max uchars until worthless */
+};
+
+struct HContents
+{
+	HContent	*type;
+	HContent	 *encoding;
+};
+
+/*
+ * generic http header with a list of tokens,
+ * each with an optional list of parameters
+ */
+struct HFields
+{
+	char		*s;
+	HSPairs		*params;
+	HFields		*next;
+};
+
+/*
+ * list of pairs a strings
+ * used for tag=val pairs for a search or form submission,
+ * and attribute=value pairs in headers.
+ */
+struct HSPairs
+{
+	char		*s;
+	char		*t;
+	HSPairs		*next;
+};
+
+/*
+ * byte ranges within a file
+ */
+struct HRange
+{
+	int		suffix;			/* is this a suffix request? */
+	ulong		start;
+	ulong		stop;			/* ~0UL -> not given */
+	HRange		*next;
+};
+
+/*
+ * list of http/1.1 entity tags
+ */
+struct HETag
+{
+	char		*etag;
+	int		weak;
+	HETag		*next;
+};
+
+/*
+ * HTTP custom IO
+ * supports chunked transfer encoding
+ * and initialization of the input buffer from a string.
+ */
+enum
+{
+	Hnone,
+	Hread,
+	Hend,
+	Hwrite,
+	Herr,
+
+	Hsize = HBufSize
+};
+
+struct Hio {
+	Hio		*hh; /* next lower layer Hio, or nil if reads from fd */
+	int		fd;		/* associated file descriptor */
+	ulong		seek;		/* of start */
+	uchar		state;		/* state of the file */
+	uchar		xferenc;	/* chunked transfer encoding state */
+	uchar		*pos;		/* current position in the buffer */
+	uchar		*stop;		/* last character active in the buffer */
+	uchar		*start;		/* start of data buffer */
+	ulong		bodylen;	/* remaining length of message body */
+	uchar		buf[Hsize+32];
+};
+
+/*
+ * request line
+ */
+struct HttpReq
+{
+	char		*meth;
+	char		*uri;
+	char		*urihost;
+	char		*search;
+	int		vermaj;
+	int		vermin;
+	HSPairs		*searchpairs;
+};
+
+/*
+ * header lines
+ */
+struct HttpHead
+{
+	int	closeit;	/* http1.1 close connection after this request? */
+	uchar	persist;	/* http/1.1 requests a persistent connection */
+
+	uchar	expectcont;	/* expect a 100-continue */
+	uchar	expectother; /* expect anything else; should reject with ExpectFail */
+	ulong	contlen;	/* if != ~0UL, length of included message body */
+	HFields	*transenc;  /* if present, encoding of included message body */
+	char	*client;
+	char	*host;
+	HContent *okencode;
+	HContent *oklang;
+	HContent *oktype;
+	HContent *okchar;
+	ulong	ifmodsince;
+	ulong	ifunmodsince;
+	ulong	ifrangedate;
+	HETag	*ifmatch;
+	HETag	*ifnomatch;
+	HETag	*ifrangeetag;
+	HRange	*range;
+	char	*authuser;		/* authorization info */
+	char	*authpass;
+	HSPairs	*cookie;	/* if present, list of cookies */
+	HSPairs		*authinfo;		/* digest authorization */
+
+	/*
+	 * experimental headers
+	 */
+	int	fresh_thresh;
+	int	fresh_have;
+};
+
+/*
+ * all of the state for a particular connection
+ */
+struct HConnect
+{
+	void	*private;		/* for the library clients */
+	void	(*replog)(HConnect*, char*, ...); /* called when reply sent */
+
+	char	*scheme;		/* "http" vs. "https" */
+	char	*port;		/* may be arbitrary, i.e., neither 80 nor 443 */
+
+	HttpReq	req;
+	HttpHead head;
+
+	Bin	*bin;
+
+	ulong	reqtime;		/* time at start of request */
+	char	xferbuf[HBufSize]; /* buffer for making up or transferring data */
+	uchar	header[HBufSize + 2];	/* room for \n\0 */
+	uchar	*hpos;
+	uchar	*hstop;
+	Hio	hin;
+	Hio	hout;
+};
+
+/*
+ * configuration for all connections within the server
+ */
+extern	char*		hmydomain;
+extern	char*		hversion;
+extern	Htmlesc		htmlesc[];
+
+/*
+ * .+2,/^$/ | sort -bd +1
+ */
+void			*halloc(HConnect *c, ulong size);
+Hio			*hbodypush(Hio *hh, ulong len, HFields *te);
+int			hbuflen(Hio *h, void *p);
+int			hcheckcontent(HContent*, HContent*, char*, int);
+void			hclose(Hio*);
+ulong			hdate2sec(char*);
+int			hdatefmt(Fmt*);
+int			hfail(HConnect*, int, ...);
+int			hflush(Hio*);
+int			hgetc(Hio*);
+int			hgethead(HConnect *c, int many);
+int			hinit(Hio*, int, int);
+int			hiserror(Hio *h);
+int			hlflush(Hio*);
+int			hload(Hio*, char*);
+char			*hlower(char*);
+HContent		*hmkcontent(HConnect *c, char *generic, char *specific, HContent *next);
+HFields			*hmkhfields(HConnect *c, char *s, HSPairs *p, HFields *next);
+char			*hmkmimeboundary(HConnect *c);
+HSPairs			*hmkspairs(HConnect *c, char *s, char *t, HSPairs *next);
+int			hmoved(HConnect *c, char *uri);
+void			hokheaders(HConnect *c);
+int			hparseheaders(HConnect*, int timeout);
+HSPairs			*hparsequery(HConnect *c, char *search);
+int			hparsereq(HConnect *c, int timeout);
+int			hprint(Hio*, char*, ...);
+int			hputc(Hio*, int);
+void			*hreadbuf(Hio *h, void *vsave);
+int			hredirected(HConnect *c, char *how, char *uri);
+void			hreqcleanup(HConnect *c);
+HFields			*hrevhfields(HFields *hf);
+HSPairs			*hrevspairs(HSPairs *sp);
+char			*hstrdup(HConnect *c, char *s);
+int			http11(HConnect*);
+int			httpfmt(Fmt*);
+char			*httpunesc(HConnect *c, char *s);
+int			hunallowed(HConnect *, char *allowed);
+int			hungetc(Hio *h);
+char			*hunload(Hio*);
+int			hurlfmt(Fmt*);
+char			*hurlunesc(HConnect *c, char *s);
+int			hwrite(Hio*, void*, int);
+int			hxferenc(Hio*, int);
+
+#pragma			varargck	argpos	hprint	2
+
+/*
+ * D is httpd format date conversion
+ * U is url escape convertsion
+ * H is html escape conversion
+ */
+#pragma	varargck	type	"D"	long
+#pragma	varargck	type	"D"	ulong
+#pragma	varargck	type	"U"	char*
+#pragma	varargck	type	"H"	char*
--- /dev/null
+++ b/sys/include/ip.h
@@ -1,0 +1,202 @@
+#pragma	src	"/sys/src/libip"
+#pragma	lib	"libip.a"
+
+enum 
+{
+	IPaddrlen=	16,
+	IPv4addrlen=	4,
+	IPv4off=	12,
+	IPllen=		4,
+	IPV4HDR_LEN=	20,
+
+	/* vihl & vcf[0] values */
+	IP_VER4= 	0x40,
+	IP_VER6=	0x60,
+};
+
+/*
+ *  for reading /net/ipifc
+ */
+typedef struct Ipifc Ipifc;
+typedef struct Iplifc Iplifc;
+typedef struct Ipv6rp Ipv6rp;
+
+/* local address */
+struct Iplifc
+{
+	Iplifc	*next;
+
+	/* per address on the ip interface */
+	uchar	ip[IPaddrlen];
+	uchar	mask[IPaddrlen];
+	uchar	net[IPaddrlen];		/* ip & mask */
+	ulong	preflt;			/* preferred lifetime */
+	ulong	validlt;		/* valid lifetime */
+};
+
+/* default values, one per stack */
+struct Ipv6rp
+{
+	int	mflag;
+	int	oflag;
+	int 	maxraint;
+	int	minraint;
+	int	linkmtu;
+	int	reachtime;
+	int	rxmitra;
+	int	ttl;
+	int	routerlt;	
+};
+
+/* actual interface */
+struct Ipifc
+{
+	Ipifc	*next;
+	Iplifc	*lifc;
+
+	/* per ip interface */
+	int	index;			/* number of interface in ipifc dir */
+	char	dev[64];
+	uchar	sendra6;		/* on == send router adv */
+	uchar	recvra6;		/* on == rcv router adv */
+	int	mtu;
+	ulong	pktin;
+	ulong	pktout;
+	ulong	errin;
+	ulong	errout;
+	Ipv6rp	rp;
+};
+
+#define ISIPV6MCAST(addr)	((addr)[0] == 0xff)
+#define ISIPV6LINKLOCAL(addr) ((addr)[0] == 0xfe && ((addr)[1] & 0xc0) == 0x80)
+
+/*
+ * ipv6 constants
+ * `ra' is `router advertisement', `rs' is `router solicitation'.
+ * `na' is `neighbour advertisement'.
+ */
+enum {
+	IPV6HDR_LEN	= 40,
+
+	/* neighbour discovery option types */
+	V6nd_srclladdr	= 1,
+	V6nd_targlladdr	= 2,
+	V6nd_pfxinfo	= 3,
+	V6nd_redirhdr	= 4,
+	V6nd_mtu	= 5,
+	/* new since rfc2461; see iana.org/assignments/icmpv6-parameters */
+	V6nd_home	= 8,
+	V6nd_srcaddrs	= 9,		/* rfc3122 */
+	V6nd_ip		= 17,
+	/* /lib/rfc/drafts/draft-jeong-dnsop-ipv6-dns-discovery-12.txt */
+	V6nd_rdns	= 25,
+	/* plan 9 extensions */
+	V6nd_9fs	= 250,
+	V6nd_9auth	= 251,
+
+	/* Router constants (all times in ms.) */
+	Maxv6initraintvl= 16000,
+	Maxv6initras	= 3,
+	Maxv6finalras	= 3,
+	Minv6interradelay= 3000,
+	Maxv6radelay	= 500,
+
+	/* Host constants */
+	Maxv6rsdelay	= 1000,
+	V6rsintvl	= 4000,
+	Maxv6rss	= 3,
+
+	/* Node constants */
+	Maxv6mcastrss	= 3,
+	Maxv6unicastrss	= 3,
+	Maxv6anycastdelay= 1000,
+	Maxv6na		= 3,
+	V6reachabletime	= 30000,
+	V6retranstimer	= 1000,
+	V6initprobedelay= 5000,
+};
+
+/* V6 header on the wire */
+typedef struct Ip6hdr Ip6hdr;
+struct Ip6hdr {
+	uchar	vcf[4];		/* version:4, traffic class:8, flow label:20 */
+	uchar	ploadlen[2];	/* payload length: packet length - 40 */
+	uchar	proto;		/* next header type */
+	uchar	ttl;		/* hop limit */
+	uchar	src[IPaddrlen];	/* source address */
+	uchar	dst[IPaddrlen];	/* destination address */
+	uchar	payload[];
+};
+
+/*
+ *  user-level icmpv6 with control message "headers"
+ */
+typedef struct Icmp6hdr Icmp6hdr;
+struct Icmp6hdr {
+	uchar	_0_[8];
+	uchar	laddr[IPaddrlen];	/* local address */
+	uchar	raddr[IPaddrlen];	/* remote address */
+};
+
+/*
+ *  user level udp headers with control message "headers"
+ */
+enum 
+{
+	Udphdrsize=	52,	/* size of a Udphdr */
+};
+
+typedef struct Udphdr Udphdr;
+struct Udphdr
+{
+	uchar	raddr[IPaddrlen];	/* V6 remote address */
+	uchar	laddr[IPaddrlen];	/* V6 local address */
+	uchar	ifcaddr[IPaddrlen];	/* V6 ifc addr msg was received on */
+	uchar	rport[2];		/* remote port */
+	uchar	lport[2];		/* local port */
+};
+
+uchar*	defmask(uchar*);
+void	maskip(uchar*, uchar*, uchar*);
+int	eipfmt(Fmt*);
+int	isv4(uchar*);
+vlong	parseip(uchar*, char*);
+vlong	parseipmask(uchar*, char*);
+char*	v4parseip(uchar*, char*);
+char*	v4parsecidr(uchar*, uchar*, char*);
+int	parseether(uchar*, char*);
+int	myipaddr(uchar*, char*);
+int	myetheraddr(uchar*, char*);
+int	equivip4(uchar*, uchar*);
+int	equivip6(uchar*, uchar*);
+
+Ipifc*	readipifc(char*, Ipifc*, int);
+
+void	hnputv(void*, uvlong);
+void	hnputl(void*, uint);
+void	hnputs(void*, ushort);
+uvlong	nhgetv(void*);
+uint	nhgetl(void*);
+ushort	nhgets(void*);
+ushort	ptclbsum(uchar*, int);
+
+int	v6tov4(uchar*, uchar*);
+void	v4tov6(uchar*, uchar*);
+
+#define	ipcmp(x, y) memcmp(x, y, IPaddrlen)
+#define	ipmove(x, y) memmove(x, y, IPaddrlen)
+
+extern uchar IPv4bcast[IPaddrlen];
+extern uchar IPv4bcastobs[IPaddrlen];
+extern uchar IPv4allsys[IPaddrlen];
+extern uchar IPv4allrouter[IPaddrlen];
+extern uchar IPnoaddr[IPaddrlen];
+extern uchar v4prefix[IPaddrlen];
+extern uchar IPallbits[IPaddrlen];
+
+#define CLASS(p) ((*(uchar*)(p))>>6)
+
+#pragma	varargck	type	"I"	uchar*
+#pragma	varargck	type	"V"	uchar*
+#pragma	varargck	type	"E"	uchar*
+#pragma	varargck	type	"M"	uchar*
--- /dev/null
+++ b/sys/include/keyboard.h
@@ -1,0 +1,46 @@
+#pragma src "/sys/src/libdraw"
+#pragma lib "libdraw.a"
+
+typedef struct 	Keyboardctl Keyboardctl;
+typedef struct	Channel	Channel;
+
+struct	Keyboardctl
+{
+	Channel	*c;	/* chan(Rune)[20] */
+
+	char		*file;
+	int		consfd;		/* to cons file */
+	int		ctlfd;		/* to ctl file */
+	int		pid;		/* of slave proc */
+};
+
+
+extern	Keyboardctl*	initkeyboard(char*);
+extern	int		ctlkeyboard(Keyboardctl*, char*);
+extern	void		closekeyboard(Keyboardctl*);
+
+enum {
+	KF=	0xF000,	/* Rune: beginning of private Unicode space */
+	Spec=	0xF800,
+	/* KF|1, KF|2, ..., KF|0xC is F1, F2, ..., F12 */
+	Khome=	KF|0x0D,
+	Kup=	KF|0x0E,
+	Kpgup=	KF|0x0F,
+	Kprint=	KF|0x10,
+	Kleft=	KF|0x11,
+	Kright=	KF|0x12,
+	Kdown=	Spec|0x00,
+	Kview=	Spec|0x00,
+	Kpgdown=	KF|0x13,
+	Kins=	KF|0x14,
+	Kend=	KF|0x18,
+
+	Kalt=		KF|0x15,
+	Kshift=	KF|0x16,
+	Kctl=		KF|0x17,
+
+	Kbs=	0x08,
+	Kdel=	0x7f,
+	Kesc=	0x1b,
+	Keof=	0x04,
+};
--- /dev/null
+++ b/sys/include/libc.h
@@ -1,0 +1,716 @@
+#pragma	lib	"libc.a"
+#pragma	src	"/sys/src/libc"
+
+#define	nelem(x)	(sizeof(x)/sizeof((x)[0]))
+#define	offsetof(s, m)	(ulong)(&(((s*)0)->m))
+#define	assert(x)	if(x){}else _assert("x")
+
+/*
+ * mem routines
+ */
+extern	void*	memccpy(void*, void*, int, ulong);
+extern	void*	memset(void*, int, ulong);
+extern	int	memcmp(void*, void*, ulong);
+extern	void*	memcpy(void*, void*, ulong);
+extern	void*	memmove(void*, void*, ulong);
+extern	void*	memchr(void*, int, ulong);
+
+/*
+ * string routines
+ */
+extern	char*	strcat(char*, char*);
+extern	char*	strchr(char*, int);
+extern	int	strcmp(char*, char*);
+extern	char*	strcpy(char*, char*);
+extern	char*	strecpy(char*, char*, char*);
+extern	char*	strdup(char*);
+extern	char*	strncat(char*, char*, long);
+extern	char*	strncpy(char*, char*, long);
+extern	int	strncmp(char*, char*, long);
+extern	char*	strpbrk(char*, char*);
+extern	char*	strrchr(char*, int);
+extern	char*	strtok(char*, char*);
+extern	long	strlen(char*);
+extern	long	strspn(char*, char*);
+extern	long	strcspn(char*, char*);
+extern	char*	strstr(char*, char*);
+extern	int	cistrncmp(char*, char*, int);
+extern	int	cistrcmp(char*, char*);
+extern	char*	cistrstr(char*, char*);
+extern	int	tokenize(char*, char**, int);
+
+enum
+{
+	UTFmax		= 3,		/* maximum bytes per rune */
+	Runesync	= 0x80,		/* cannot represent part of a UTF sequence (<) */
+	Runeself	= 0x80,		/* rune and UTF sequences are the same (<) */
+	Runeerror	= 0xFFFD,	/* decoding error in UTF */
+};
+
+/*
+ * rune routines
+ */
+extern	int	runetochar(char*, Rune*);
+extern	int	chartorune(Rune*, char*);
+extern	int	runelen(long);
+extern	int	runenlen(Rune*, int);
+extern	int	fullrune(char*, int);
+extern	int	utflen(char*);
+extern	int	utfnlen(char*, long);
+extern	char*	utfrune(char*, long);
+extern	char*	utfrrune(char*, long);
+extern	char*	utfutf(char*, char*);
+extern	char*	utfecpy(char*, char*, char*);
+
+extern	Rune*	runestrcat(Rune*, Rune*);
+extern	Rune*	runestrchr(Rune*, Rune);
+extern	int	runestrcmp(Rune*, Rune*);
+extern	Rune*	runestrcpy(Rune*, Rune*);
+extern	Rune*	runestrncpy(Rune*, Rune*, long);
+extern	Rune*	runestrecpy(Rune*, Rune*, Rune*);
+extern	Rune*	runestrdup(Rune*);
+extern	Rune*	runestrncat(Rune*, Rune*, long);
+extern	int	runestrncmp(Rune*, Rune*, long);
+extern	Rune*	runestrrchr(Rune*, Rune);
+extern	long	runestrlen(Rune*);
+extern	Rune*	runestrstr(Rune*, Rune*);
+
+extern	Rune	tolowerrune(Rune);
+extern	Rune	totitlerune(Rune);
+extern	Rune	toupperrune(Rune);
+extern	int	isalpharune(Rune);
+extern	int	islowerrune(Rune);
+extern	int	isspacerune(Rune);
+extern	int	istitlerune(Rune);
+extern	int	isupperrune(Rune);
+extern	int	isdigitrune(Rune);
+
+/*
+ * malloc
+ */
+extern	void*	malloc(ulong);
+extern	void*	mallocz(ulong, int);
+extern	void	free(void*);
+extern	ulong	msize(void*);
+extern	void*	mallocalign(ulong, ulong, long, ulong);
+extern	void*	calloc(ulong, ulong);
+extern	void*	realloc(void*, ulong);
+extern	void	setmalloctag(void*, ulong);
+extern	void	setrealloctag(void*, ulong);
+extern	ulong	getmalloctag(void*);
+extern	ulong	getrealloctag(void*);
+extern	void*	malloctopoolblock(void*);
+
+/*
+ * print routines
+ */
+typedef struct Fmt	Fmt;
+struct Fmt{
+	uchar	runes;			/* output buffer is runes or chars? */
+	void	*start;			/* of buffer */
+	void	*to;			/* current place in the buffer */
+	void	*stop;			/* end of the buffer; overwritten if flush fails */
+	int	(*flush)(Fmt *);	/* called when to == stop */
+	void	*farg;			/* to make flush a closure */
+	int	nfmt;			/* num chars formatted so far */
+	va_list	args;			/* args passed to dofmt */
+	int	r;			/* % format Rune */
+	int	width;
+	int	prec;
+	ulong	flags;
+};
+
+enum{
+	FmtWidth	= 1,
+	FmtLeft		= FmtWidth << 1,
+	FmtPrec		= FmtLeft << 1,
+	FmtSharp	= FmtPrec << 1,
+	FmtSpace	= FmtSharp << 1,
+	FmtSign		= FmtSpace << 1,
+	FmtZero		= FmtSign << 1,
+	FmtUnsigned	= FmtZero << 1,
+	FmtShort	= FmtUnsigned << 1,
+	FmtLong		= FmtShort << 1,
+	FmtVLong	= FmtLong << 1,
+	FmtComma	= FmtVLong << 1,
+	FmtByte		= FmtComma << 1,
+
+	FmtFlag		= FmtByte << 1
+};
+
+extern	int	print(char*, ...);
+extern	char*	seprint(char*, char*, char*, ...);
+extern	char*	vseprint(char*, char*, char*, va_list);
+extern	int	snprint(char*, int, char*, ...);
+extern	int	vsnprint(char*, int, char*, va_list);
+extern	char*	smprint(char*, ...);
+extern	char*	vsmprint(char*, va_list);
+extern	int	sprint(char*, char*, ...);
+extern	int	fprint(int, char*, ...);
+extern	int	vfprint(int, char*, va_list);
+
+extern	int	runesprint(Rune*, char*, ...);
+extern	int	runesnprint(Rune*, int, char*, ...);
+extern	int	runevsnprint(Rune*, int, char*, va_list);
+extern	Rune*	runeseprint(Rune*, Rune*, char*, ...);
+extern	Rune*	runevseprint(Rune*, Rune*, char*, va_list);
+extern	Rune*	runesmprint(char*, ...);
+extern	Rune*	runevsmprint(char*, va_list);
+
+extern	int	fmtfdinit(Fmt*, int, char*, int);
+extern	int	fmtfdflush(Fmt*);
+extern	int	fmtstrinit(Fmt*);
+extern	char*	fmtstrflush(Fmt*);
+extern	int	runefmtstrinit(Fmt*);
+extern	Rune*	runefmtstrflush(Fmt*);
+
+#pragma	varargck	argpos	fmtprint	2
+#pragma	varargck	argpos	fprint		2
+#pragma	varargck	argpos	print		1
+#pragma	varargck	argpos	runeseprint	3
+#pragma	varargck	argpos	runesmprint	1
+#pragma	varargck	argpos	runesnprint	3
+#pragma	varargck	argpos	runesprint	2
+#pragma	varargck	argpos	seprint		3
+#pragma	varargck	argpos	smprint		1
+#pragma	varargck	argpos	snprint		3
+#pragma	varargck	argpos	sprint		2
+
+#pragma	varargck	type	"lld"	vlong
+#pragma	varargck	type	"llx"	vlong
+#pragma	varargck	type	"lld"	uvlong
+#pragma	varargck	type	"llx"	uvlong
+#pragma	varargck	type	"ld"	long
+#pragma	varargck	type	"lx"	long
+#pragma	varargck	type	"lb"	long
+#pragma	varargck	type	"ld"	ulong
+#pragma	varargck	type	"lx"	ulong
+#pragma	varargck	type	"lb"	ulong
+#pragma	varargck	type	"d"	int
+#pragma	varargck	type	"x"	int
+#pragma	varargck	type	"c"	int
+#pragma	varargck	type	"C"	int
+#pragma	varargck	type	"b"	int
+#pragma	varargck	type	"d"	uint
+#pragma	varargck	type	"x"	uint
+#pragma	varargck	type	"c"	uint
+#pragma	varargck	type	"C"	uint
+#pragma	varargck	type	"b"	uint
+#pragma	varargck	type	"f"	double
+#pragma	varargck	type	"e"	double
+#pragma	varargck	type	"g"	double
+#pragma	varargck	type	"s"	char*
+#pragma	varargck	type	"q"	char*
+#pragma	varargck	type	"S"	Rune*
+#pragma	varargck	type	"Q"	Rune*
+#pragma	varargck	type	"r"	void
+#pragma	varargck	type	"%"	void
+#pragma	varargck	type	"n"	int*
+#pragma	varargck	type	"p"	uintptr
+#pragma	varargck	type	"p"	void*
+#pragma	varargck	flag	','
+#pragma	varargck	flag	' '
+#pragma	varargck	flag	'h'
+#pragma varargck	type	"<"	void*
+#pragma varargck	type	"["	void*
+#pragma varargck	type	"H"	void*
+#pragma varargck	type	"lH"	void*
+
+extern	int	fmtinstall(int, int (*)(Fmt*));
+extern	int	dofmt(Fmt*, char*);
+extern	int	dorfmt(Fmt*, Rune*);
+extern	int	fmtprint(Fmt*, char*, ...);
+extern	int	fmtvprint(Fmt*, char*, va_list);
+extern	int	fmtrune(Fmt*, int);
+extern	int	fmtstrcpy(Fmt*, char*);
+extern	int	fmtrunestrcpy(Fmt*, Rune*);
+/*
+ * error string for %r
+ * supplied on per os basis, not part of fmt library
+ */
+extern	int	errfmt(Fmt *f);
+
+/*
+ * quoted strings
+ */
+extern	char	*unquotestrdup(char*);
+extern	Rune	*unquoterunestrdup(Rune*);
+extern	char	*quotestrdup(char*);
+extern	Rune	*quoterunestrdup(Rune*);
+extern	int	quotestrfmt(Fmt*);
+extern	int	quoterunestrfmt(Fmt*);
+extern	void	quotefmtinstall(void);
+extern	int	(*doquote)(int);
+extern	int	needsrcquote(int);
+
+/*
+ * random number
+ */
+extern	void	srand(long);
+extern	int	rand(void);
+extern	int	nrand(int);
+extern	long	lrand(void);
+extern	long	lnrand(long);
+extern	double	frand(void);
+extern	ulong	truerand(void);			/* uses /dev/random */
+extern	ulong	ntruerand(ulong);		/* uses /dev/random */
+
+/*
+ * math
+ */
+extern	ulong	getfcr(void);
+extern	void	setfsr(ulong);
+extern	ulong	getfsr(void);
+extern	void	setfcr(ulong);
+extern	double	NaN(void);
+extern	double	Inf(int);
+extern	int	isNaN(double);
+extern	int	isInf(double, int);
+extern	ulong	umuldiv(ulong, ulong, ulong);
+extern	long	muldiv(long, long, long);
+
+extern	double	pow(double, double);
+extern	double	atan2(double, double);
+extern	double	fabs(double);
+extern	double	atan(double);
+extern	double	log(double);
+extern	double	log10(double);
+extern	double	exp(double);
+extern	double	floor(double);
+extern	double	ceil(double);
+extern	double	hypot(double, double);
+extern	double	sin(double);
+extern	double	cos(double);
+extern	double	tan(double);
+extern	double	asin(double);
+extern	double	acos(double);
+extern	double	sinh(double);
+extern	double	cosh(double);
+extern	double	tanh(double);
+extern	double	sqrt(double);
+extern	double	fmod(double, double);
+
+#define	HUGE	3.4028234e38
+#define	PIO2	1.570796326794896619231e0
+#define	PI	(PIO2+PIO2)
+
+/*
+ * Time-of-day
+ */
+
+typedef
+struct Tm
+{
+	int	sec;
+	int	min;
+	int	hour;
+	int	mday;
+	int	mon;
+	int	year;
+	int	wday;
+	int	yday;
+	char	zone[4];
+	int	tzoff;
+} Tm;
+
+extern	Tm*	gmtime(long);
+extern	Tm*	localtime(long);
+extern	char*	asctime(Tm*);
+extern	char*	ctime(long);
+extern	double	cputime(void);
+extern	long	times(long*);
+extern	long	tm2sec(Tm*);
+extern	vlong	nsec(void);
+
+extern	void	cycles(uvlong*);	/* 64-bit value of the cycle counter if there is one, 0 if there isn't */
+
+/*
+ * one-of-a-kind
+ */
+enum
+{
+	PNPROC		= 1,
+	PNGROUP		= 2,
+};
+
+extern	void	_assert(char*);
+extern	int	abs(int);
+extern	int	atexit(void(*)(void));
+extern	void	atexitdont(void(*)(void));
+extern	int	atnotify(int(*)(void*, char*), int);
+extern	double	atof(char*);
+extern	int	atoi(char*);
+extern	long	atol(char*);
+extern	vlong	atoll(char*);
+extern	double	charstod(int(*)(void*), void*);
+extern	char*	cleanname(char*);
+extern	int	decrypt(void*, void*, int);
+extern	int	encrypt(void*, void*, int);
+extern	int	dec64(uchar*, int, char*, int);
+extern	int	enc64(char*, int, uchar*, int);
+extern	int	dec32(uchar*, int, char*, int);
+extern	int	enc32(char*, int, uchar*, int);
+extern	int	dec16(uchar*, int, char*, int);
+extern	int	enc16(char*, int, uchar*, int);
+extern	int	encodefmt(Fmt*);
+extern	void	exits(char*);
+extern	double	frexp(double, int*);
+extern	uintptr	getcallerpc(void*);
+extern	char*	getenv(char*);
+extern	int	getfields(char*, char**, int, int, char*);
+extern	int	gettokens(char *, char **, int, char *);
+extern	char*	getuser(void);
+extern	char*	getwd(char*, int);
+extern	int	iounit(int);
+extern	long	labs(long);
+extern	double	ldexp(double, int);
+extern	void	longjmp(jmp_buf, int);
+extern	char*	mktemp(char*);
+extern	double	modf(double, double*);
+extern	int	netcrypt(void*, void*);
+extern	void	notejmp(void*, jmp_buf, int);
+extern	void	perror(char*);
+extern	int	postnote(int, int, char *);
+extern	double	pow10(int);
+extern	int	putenv(char*, char*);
+extern	void	qsort(void*, long, long, int (*)(void*, void*));
+extern	int	setjmp(jmp_buf);
+extern	double	strtod(char*, char**);
+extern	long	strtol(char*, char**, int);
+extern	ulong	strtoul(char*, char**, int);
+extern	vlong	strtoll(char*, char**, int);
+extern	uvlong	strtoull(char*, char**, int);
+extern	void	sysfatal(char*, ...);
+#pragma	varargck	argpos	sysfatal	1
+extern	void	syslog(int, char*, char*, ...);
+#pragma	varargck	argpos	syslog	3
+extern	long	time(long*);
+extern	int	tolower(int);
+extern	int	toupper(int);
+
+/*
+ *  profiling
+ */
+enum {
+	Profoff,		/* No profiling */
+	Profuser,		/* Measure user time only (default) */
+	Profkernel,		/* Measure user + kernel time */
+	Proftime,		/* Measure total time */
+	Profsample,		/* Use clock interrupt to sample (default when there is no cycle counter) */
+}; /* what */
+extern	void	prof(void (*fn)(void*), void *arg, int entries, int what);
+
+/*
+ *  synchronization
+ */
+typedef
+struct Lock {
+	int	val;
+} Lock;
+
+extern int	_tas(int*);
+
+extern	void	lock(Lock*);
+extern	void	unlock(Lock*);
+extern	int	canlock(Lock*);
+
+typedef struct QLp QLp;
+struct QLp
+{
+	int	inuse;
+	QLp	*next;
+	char	state;
+};
+
+typedef
+struct QLock
+{
+	Lock	lock;
+	int	locked;
+	QLp	*head;
+	QLp 	*tail;
+} QLock;
+
+extern	void	qlock(QLock*);
+extern	void	qunlock(QLock*);
+extern	int	canqlock(QLock*);
+extern	void	_qlockinit(void* (*)(void*, void*));	/* called only by the thread library */
+
+typedef
+struct RWLock
+{
+	Lock	lock;
+	int	readers;	/* number of readers */
+	int	writer;		/* number of writers */
+	QLp	*head;		/* list of waiting processes */
+	QLp	*tail;
+} RWLock;
+
+extern	void	rlock(RWLock*);
+extern	void	runlock(RWLock*);
+extern	int	canrlock(RWLock*);
+extern	void	wlock(RWLock*);
+extern	void	wunlock(RWLock*);
+extern	int	canwlock(RWLock*);
+
+typedef
+struct Rendez
+{
+	QLock	*l;
+	QLp	*head;
+	QLp	*tail;
+} Rendez;
+
+extern	void	rsleep(Rendez*);	/* unlocks r->l, sleeps, locks r->l again */
+extern	int	rwakeup(Rendez*);
+extern	int	rwakeupall(Rendez*);
+extern	void**	privalloc(void);
+extern	void	privfree(void**);
+
+/*
+ *  network dialing
+ */
+#define NETPATHLEN 40
+extern	int	accept(int, char*);
+extern	int	announce(char*, char*);
+extern	int	dial(char*, char*, char*, int*);
+extern	void	setnetmtpt(char*, int, char*);
+extern	int	hangup(int);
+extern	int	listen(char*, char*);
+extern	char*	netmkaddr(char*, char*, char*);
+extern	int	reject(int, char*, char*);
+
+/*
+ *  encryption
+ */
+extern	int	pushssl(int, char*, char*, char*, int*);
+extern	int	pushtls(int, char*, char*, int, char*, char*);
+
+/*
+ *  network services
+ */
+typedef struct NetConnInfo NetConnInfo;
+struct NetConnInfo
+{
+	char	*dir;		/* connection directory */
+	char	*root;		/* network root */
+	char	*spec;		/* binding spec */
+	char	*lsys;		/* local system */
+	char	*lserv;		/* local service */
+	char	*rsys;		/* remote system */
+	char	*rserv;		/* remote service */
+	char	*laddr;		/* local address */
+	char	*raddr;		/* remote address */
+};
+extern	NetConnInfo*	getnetconninfo(char*, int);
+extern	void		freenetconninfo(NetConnInfo*);
+
+/*
+ * system calls
+ *
+ */
+#define	STATMAX	65535U	/* max length of machine-independent stat structure */
+#define	DIRMAX	(sizeof(Dir)+STATMAX)	/* max length of Dir structure */
+#define	ERRMAX	128	/* max length of error string */
+
+#define	MORDER	0x0003	/* mask for bits defining order of mounting */
+#define	MREPL	0x0000	/* mount replaces object */
+#define	MBEFORE	0x0001	/* mount goes before others in union directory */
+#define	MAFTER	0x0002	/* mount goes after others in union directory */
+#define	MCREATE	0x0004	/* permit creation in mounted directory */
+#define	MCACHE	0x0010	/* cache some data */
+#define	MMASK	0x0017	/* all bits on */
+
+#define	OREAD	0	/* open for read */
+#define	OWRITE	1	/* write */
+#define	ORDWR	2	/* read and write */
+#define	OEXEC	3	/* execute, == read but check execute permission */
+#define	OTRUNC	16	/* or'ed in (except for exec), truncate file first */
+#define	OCEXEC	32	/* or'ed in, close on exec */
+#define	ORCLOSE	64	/* or'ed in, remove on close */
+#define	OEXCL	0x1000	/* or'ed in, exclusive use (create only) */
+
+#define	AEXIST	0	/* accessible: exists */
+#define	AEXEC	1	/* execute access */
+#define	AWRITE	2	/* write access */
+#define	AREAD	4	/* read access */
+
+/* Segattch */
+#define	SG_RONLY	0040	/* read only */
+#define	SG_CEXEC	0100	/* detach on exec */
+
+#define	NCONT	0	/* continue after note */
+#define	NDFLT	1	/* terminate after note */
+#define	NSAVE	2	/* clear note but hold state */
+#define	NRSTR	3	/* restore saved state */
+
+/* bits in Qid.type */
+#define QTDIR		0x80		/* type bit for directories */
+#define QTAPPEND	0x40		/* type bit for append only files */
+#define QTEXCL		0x20		/* type bit for exclusive use files */
+#define QTMOUNT		0x10		/* type bit for mounted channel */
+#define QTAUTH		0x08		/* type bit for authentication file */
+#define QTTMP		0x04		/* type bit for not-backed-up file */
+#define QTFILE		0x00		/* plain file */
+
+/* bits in Dir.mode */
+#define DMDIR		0x80000000	/* mode bit for directories */
+#define DMAPPEND	0x40000000	/* mode bit for append only files */
+#define DMEXCL		0x20000000	/* mode bit for exclusive use files */
+#define DMMOUNT		0x10000000	/* mode bit for mounted channel */
+#define DMAUTH		0x08000000	/* mode bit for authentication file */
+#define DMTMP		0x04000000	/* mode bit for non-backed-up files */
+#define DMREAD		0x4		/* mode bit for read permission */
+#define DMWRITE		0x2		/* mode bit for write permission */
+#define DMEXEC		0x1		/* mode bit for execute permission */
+
+/* rfork */
+enum
+{
+	RFNAMEG		= (1<<0),
+	RFENVG		= (1<<1),
+	RFFDG		= (1<<2),
+	RFNOTEG		= (1<<3),
+	RFPROC		= (1<<4),
+	RFMEM		= (1<<5),
+	RFNOWAIT	= (1<<6),
+	RFCNAMEG	= (1<<10),
+	RFCENVG		= (1<<11),
+	RFCFDG		= (1<<12),
+	RFREND		= (1<<13),
+	RFNOMNT		= (1<<14)
+};
+
+typedef
+struct Qid
+{
+	uvlong	path;
+	ulong	vers;
+	uchar	type;
+} Qid;
+
+typedef
+struct Dir {
+	/* system-modified data */
+	ushort	type;	/* server type */
+	uint	dev;	/* server subtype */
+	/* file data */
+	Qid	qid;	/* unique id from server */
+	ulong	mode;	/* permissions */
+	ulong	atime;	/* last read time */
+	ulong	mtime;	/* last write time */
+	vlong	length;	/* file length */
+	char	*name;	/* last element of path */
+	char	*uid;	/* owner name */
+	char	*gid;	/* group name */
+	char	*muid;	/* last modifier name */
+} Dir;
+
+/* keep /sys/src/ape/lib/ap/plan9/sys9.h in sync with this -rsc */
+typedef
+struct Waitmsg
+{
+	int	pid;		/* of loved one */
+	ulong	time[3];	/* of loved one & descendants */
+	char	*msg;
+} Waitmsg;
+
+typedef
+struct IOchunk
+{
+	void	*addr;
+	ulong	len;
+} IOchunk;
+
+extern	void	_exits(char*);
+
+extern	void	abort(void);
+extern	int	access(char*, int);
+extern	long	alarm(ulong);
+extern	int	await(char*, int);
+extern	int	bind(char*, char*, int);
+extern	int	brk(void*);
+extern	int	chdir(char*);
+extern	int	close(int);
+extern	int	create(char*, int, ulong);
+extern	int	dup(int, int);
+extern	int	errstr(char*, uint);
+extern	int	exec(char*, char*[]);
+extern	int	execl(char*, ...);
+extern	int	fork(void);
+extern	int	rfork(int);
+extern	int	fauth(int, char*);
+extern	int	fstat(int, uchar*, int);
+extern	int	fwstat(int, uchar*, int);
+extern	int	fversion(int, int, char*, int);
+extern	int	mount(int, int, char*, int, char*);
+extern	int	unmount(char*, char*);
+extern	int	noted(int);
+extern	int	notify(void(*)(void*, char*));
+extern	int	open(char*, int);
+extern	int	fd2path(int, char*, int);
+extern	int	pipe(int*);
+extern	long	pread(int, void*, long, vlong);
+extern	long	preadv(int, IOchunk*, int, vlong);
+extern	long	pwrite(int, void*, long, vlong);
+extern	long	pwritev(int, IOchunk*, int, vlong);
+extern	long	read(int, void*, long);
+extern	long	readn(int, void*, long);
+extern	long	readv(int, IOchunk*, int);
+extern	int	remove(char*);
+extern	void*	sbrk(ulong);
+extern	long	oseek(int, long, int);
+extern	vlong	seek(int, vlong, int);
+extern	void*	segattach(int, char*, void*, ulong);
+extern	void*	segbrk(void*, void*);
+extern	int	segdetach(void*);
+extern	int	segflush(void*, ulong);
+extern	int	segfree(void*, ulong);
+extern	int	semacquire(long*, int);
+extern	long	semrelease(long*, long);
+extern	int	sleep(long);
+extern	int	stat(char*, uchar*, int);
+extern	Waitmsg*	wait(void);
+extern	int	waitpid(void);
+extern	long	write(int, void*, long);
+extern	long	writev(int, IOchunk*, int);
+extern	int	wstat(char*, uchar*, int);
+extern	void*	rendezvous(void*, void*);
+
+extern	Dir*	dirstat(char*);
+extern	Dir*	dirfstat(int);
+extern	int	dirwstat(char*, Dir*);
+extern	int	dirfwstat(int, Dir*);
+extern	long	dirread(int, Dir**);
+extern	void	nulldir(Dir*);
+extern	long	dirreadall(int, Dir**);
+extern	int	getpid(void);
+extern	int	getppid(void);
+extern	void	rerrstr(char*, uint);
+extern	char*	sysname(void);
+extern	void	werrstr(char*, ...);
+#pragma	varargck	argpos	werrstr	1
+
+extern char *argv0;
+#define	ARGBEGIN	for((argv0||(argv0=*argv)),argv++,argc--;\
+			    argv[0] && argv[0][0]=='-' && argv[0][1];\
+			    argc--, argv++) {\
+				char *_args, *_argt;\
+				Rune _argc;\
+				_args = &argv[0][1];\
+				if(_args[0]=='-' && _args[1]==0){\
+					argc--; argv++; break;\
+				}\
+				_argc = 0;\
+				while(*_args && (_args += chartorune(&_argc, _args)))\
+				switch(_argc)
+#define	ARGEND		SET(_argt);USED(_argt,_argc,_args);}USED(argv, argc);
+#define	ARGF()		(_argt=_args, _args="",\
+				(*_argt? _argt: argv[1]? (argc--, *++argv): 0))
+#define	EARGF(x)	(_argt=_args, _args="",\
+				(*_argt? _argt: argv[1]? (argc--, *++argv): ((x), abort(), (char*)0)))
+
+#define	ARGC()		_argc
+
+/* this is used by sbrk and brk,  it's a really bad idea to redefine it */
+extern	char	end[];
--- /dev/null
+++ b/sys/include/libsec.h
@@ -1,0 +1,402 @@
+#pragma	lib	"libsec.a"
+#pragma	src	"/sys/src/libsec"
+
+
+#ifndef _MPINT
+typedef struct mpint mpint;
+#endif
+
+/*
+ * AES definitions
+ */
+
+enum
+{
+	AESbsize=	16,
+	AESmaxkey=	32,
+	AESmaxrounds=	14
+};
+
+typedef struct AESstate AESstate;
+struct AESstate
+{
+	ulong	setup;
+	int	rounds;
+	int	keybytes;
+	uint	ctrsz;
+	uchar	key[AESmaxkey];			/* unexpanded key */
+	ulong	ekey[4*(AESmaxrounds + 1)];	/* encryption key */
+	ulong	dkey[4*(AESmaxrounds + 1)];	/* decryption key */
+	uchar	ivec[AESbsize];			/* initialization vector */
+	uchar	mackey[3 * AESbsize];		/* 3 XCBC mac 96 keys */
+};
+
+/* block ciphers */
+void	aes_encrypt(ulong rk[], int Nr, uchar pt[16], uchar ct[16]);
+void	aes_decrypt(ulong rk[], int Nr, uchar ct[16], uchar pt[16]);
+
+void	setupAESstate(AESstate *s, uchar key[], int keybytes, uchar *ivec);
+void	aesCBCencrypt(uchar *p, int len, AESstate *s);
+void	aesCBCdecrypt(uchar *p, int len, AESstate *s);
+void	aesCTRdecrypt(uchar *p, int len, AESstate *s);
+void	aesCTRencrypt(uchar *p, int len, AESstate *s);
+
+void	setupAESXCBCstate(AESstate *s);
+uchar*	aesXCBCmac(uchar *p, int len, AESstate *s);
+
+/*
+ * Blowfish Definitions
+ */
+
+enum
+{
+	BFbsize	= 8,
+	BFrounds= 16
+};
+
+/* 16-round Blowfish */
+typedef struct BFstate BFstate;
+struct BFstate
+{
+	ulong	setup;
+
+	uchar	key[56];
+	uchar	ivec[8];
+
+	u32int 	pbox[BFrounds+2];
+	u32int	sbox[1024];
+};
+
+void	setupBFstate(BFstate *s, uchar key[], int keybytes, uchar *ivec);
+void	bfCBCencrypt(uchar*, int, BFstate*);
+void	bfCBCdecrypt(uchar*, int, BFstate*);
+void	bfECBencrypt(uchar*, int, BFstate*);
+void	bfECBdecrypt(uchar*, int, BFstate*);
+
+/*
+ * DES definitions
+ */
+
+enum
+{
+	DESbsize=	8
+};
+
+/* single des */
+typedef struct DESstate DESstate;
+struct DESstate
+{
+	ulong	setup;
+	uchar	key[8];		/* unexpanded key */
+	ulong	expanded[32];	/* expanded key */
+	uchar	ivec[8];	/* initialization vector */
+};
+
+void	setupDESstate(DESstate *s, uchar key[8], uchar *ivec);
+void	des_key_setup(uchar[8], ulong[32]);
+void	block_cipher(ulong*, uchar*, int);
+void	desCBCencrypt(uchar*, int, DESstate*);
+void	desCBCdecrypt(uchar*, int, DESstate*);
+void	desECBencrypt(uchar*, int, DESstate*);
+void	desECBdecrypt(uchar*, int, DESstate*);
+
+/* for backward compatibility with 7-byte DES key format */
+void	des56to64(uchar *k56, uchar *k64);
+void	des64to56(uchar *k64, uchar *k56);
+void	key_setup(uchar[7], ulong[32]);
+
+/* triple des encrypt/decrypt orderings */
+enum {
+	DES3E=		0,
+	DES3D=		1,
+	DES3EEE=	0,
+	DES3EDE=	2,
+	DES3DED=	5,
+	DES3DDD=	7
+};
+
+typedef struct DES3state DES3state;
+struct DES3state
+{
+	ulong	setup;
+	uchar	key[3][8];		/* unexpanded key */
+	ulong	expanded[3][32];	/* expanded key */
+	uchar	ivec[8];		/* initialization vector */
+};
+
+void	setupDES3state(DES3state *s, uchar key[3][8], uchar *ivec);
+void	triple_block_cipher(ulong keys[3][32], uchar*, int);
+void	des3CBCencrypt(uchar*, int, DES3state*);
+void	des3CBCdecrypt(uchar*, int, DES3state*);
+void	des3ECBencrypt(uchar*, int, DES3state*);
+void	des3ECBdecrypt(uchar*, int, DES3state*);
+
+/*
+ * digests
+ */
+
+enum
+{
+	SHA1dlen=	20,	/* SHA digest length */
+	SHA2_224dlen=	28,	/* SHA-224 digest length */
+	SHA2_256dlen=	32,	/* SHA-256 digest length */
+	SHA2_384dlen=	48,	/* SHA-384 digest length */
+	SHA2_512dlen=	64,	/* SHA-512 digest length */
+	MD4dlen=	16,	/* MD4 digest length */
+	MD5dlen=	16,	/* MD5 digest length */
+	AESdlen=	16,	/* TODO: see rfc */
+
+	Hmacblksz	= 64,	/* in bytes; from rfc2104 */
+};
+
+typedef struct DigestState DigestState;
+struct DigestState
+{
+	uvlong	len;
+	union {
+		u32int	state[8];
+		u64int	bstate[8];
+	};
+	uchar	buf[256];
+	int	blen;
+	char	malloced;
+	char	seeded;
+};
+typedef struct DigestState SHAstate;	/* obsolete name */
+typedef struct DigestState SHA1state;
+typedef struct DigestState SHA2_224state;
+typedef struct DigestState SHA2_256state;
+typedef struct DigestState SHA2_384state;
+typedef struct DigestState SHA2_512state;
+typedef struct DigestState MD5state;
+typedef struct DigestState MD4state;
+typedef struct DigestState AEShstate;
+
+DigestState*	md4(uchar*, ulong, uchar*, DigestState*);
+DigestState*	md5(uchar*, ulong, uchar*, DigestState*);
+DigestState*	sha1(uchar*, ulong, uchar*, DigestState*);
+DigestState*	sha2_224(uchar*, ulong, uchar*, DigestState*);
+DigestState*	sha2_256(uchar*, ulong, uchar*, DigestState*);
+DigestState*	sha2_384(uchar*, ulong, uchar*, DigestState*);
+DigestState*	sha2_512(uchar*, ulong, uchar*, DigestState*);
+DigestState*	aes(uchar*, ulong, uchar*, DigestState*);
+DigestState*	hmac_x(uchar *p, ulong len, uchar *key, ulong klen,
+			uchar *digest, DigestState *s,
+			DigestState*(*x)(uchar*, ulong, uchar*, DigestState*),
+			int xlen);
+DigestState*	hmac_md5(uchar*, ulong, uchar*, ulong, uchar*, DigestState*);
+DigestState*	hmac_sha1(uchar*, ulong, uchar*, ulong, uchar*, DigestState*);
+DigestState*	hmac_sha2_224(uchar*, ulong, uchar*, ulong, uchar*, DigestState*);
+DigestState*	hmac_sha2_256(uchar*, ulong, uchar*, ulong, uchar*, DigestState*);
+DigestState*	hmac_sha2_384(uchar*, ulong, uchar*, ulong, uchar*, DigestState*);
+DigestState*	hmac_sha2_512(uchar*, ulong, uchar*, ulong, uchar*, DigestState*);
+DigestState*	hmac_aes(uchar*, ulong, uchar*, ulong, uchar*, DigestState*);
+char*		md5pickle(MD5state*);
+MD5state*	md5unpickle(char*);
+char*		sha1pickle(SHA1state*);
+SHA1state*	sha1unpickle(char*);
+
+/*
+ * random number generation
+ */
+void	genrandom(uchar *buf, int nbytes);
+void	prng(uchar *buf, int nbytes);
+ulong	fastrand(void);
+ulong	nfastrand(ulong);
+
+/*
+ * primes
+ */
+void	genprime(mpint *p, int n, int accuracy); /* generate n-bit probable prime */
+void	gensafeprime(mpint *p, mpint *alpha, int n, int accuracy); /* prime & generator */
+void	genstrongprime(mpint *p, int n, int accuracy); /* generate n-bit strong prime */
+void	DSAprimes(mpint *q, mpint *p, uchar seed[SHA1dlen]);
+int	probably_prime(mpint *n, int nrep);	/* miller-rabin test */
+int	smallprimetest(mpint *p);  /* returns -1 if not prime, 0 otherwise */
+
+/*
+ * rc4
+ */
+typedef struct RC4state RC4state;
+struct RC4state
+{
+	 uchar	state[256];
+	 uchar	x;
+	 uchar	y;
+};
+
+void	setupRC4state(RC4state*, uchar*, int);
+void	rc4(RC4state*, uchar*, int);
+void	rc4skip(RC4state*, int);
+void	rc4back(RC4state*, int);
+
+/*
+ * rsa
+ */
+typedef struct RSApub RSApub;
+typedef struct RSApriv RSApriv;
+typedef struct PEMChain PEMChain;
+
+/* public/encryption key */
+struct RSApub
+{
+	mpint	*n;	/* modulus */
+	mpint	*ek;	/* exp (encryption key) */
+};
+
+/* private/decryption key */
+struct RSApriv
+{
+	RSApub	pub;
+
+	mpint	*dk;	/* exp (decryption key) */
+
+	/* precomputed values to help with chinese remainder theorem calc */
+	mpint	*p;
+	mpint	*q;
+	mpint	*kp;	/* dk mod p-1 */
+	mpint	*kq;	/* dk mod q-1 */
+	mpint	*c2;	/* (inv p) mod q */
+};
+
+struct PEMChain{
+	PEMChain*next;
+	uchar	*pem;
+	int	pemlen;
+};
+
+RSApriv*	rsagen(int nlen, int elen, int rounds);
+RSApriv*	rsafill(mpint *n, mpint *e, mpint *d, mpint *p, mpint *q);
+mpint*		rsaencrypt(RSApub *k, mpint *in, mpint *out);
+mpint*		rsadecrypt(RSApriv *k, mpint *in, mpint *out);
+RSApub*		rsapuballoc(void);
+void		rsapubfree(RSApub*);
+RSApriv*	rsaprivalloc(void);
+void		rsaprivfree(RSApriv*);
+RSApub*		rsaprivtopub(RSApriv*);
+RSApub*		X509toRSApub(uchar*, int, char*, int);
+RSApriv*	asn1toRSApriv(uchar*, int);
+void		asn1dump(uchar *der, int len);
+uchar*		decodePEM(char *s, char *type, int *len, char **new_s);
+PEMChain*	decodepemchain(char *s, char *type);
+uchar*		X509gen(RSApriv *priv, char *subj, ulong valid[2], int *certlen);
+uchar*		X509req(RSApriv *priv, char *subj, int *certlen);
+char*		X509verify(uchar *cert, int ncert, RSApub *pk);
+void		X509dump(uchar *cert, int ncert);
+
+/*
+ * elgamal
+ */
+typedef struct EGpub EGpub;
+typedef struct EGpriv EGpriv;
+typedef struct EGsig EGsig;
+
+/* public/encryption key */
+struct EGpub
+{
+	mpint	*p;	/* modulus */
+	mpint	*alpha;	/* generator */
+	mpint	*key;	/* (encryption key) alpha**secret mod p */
+};
+
+/* private/decryption key */
+struct EGpriv
+{
+	EGpub	pub;
+	mpint	*secret;	/* (decryption key) */
+};
+
+/* signature */
+struct EGsig
+{
+	mpint	*r, *s;
+};
+
+EGpriv*		eggen(int nlen, int rounds);
+mpint*		egencrypt(EGpub *k, mpint *in, mpint *out);	/* deprecated */
+mpint*		egdecrypt(EGpriv *k, mpint *in, mpint *out);
+EGsig*		egsign(EGpriv *k, mpint *m);
+int		egverify(EGpub *k, EGsig *sig, mpint *m);
+EGpub*		egpuballoc(void);
+void		egpubfree(EGpub*);
+EGpriv*		egprivalloc(void);
+void		egprivfree(EGpriv*);
+EGsig*		egsigalloc(void);
+void		egsigfree(EGsig*);
+EGpub*		egprivtopub(EGpriv*);
+
+/*
+ * dsa
+ */
+typedef struct DSApub DSApub;
+typedef struct DSApriv DSApriv;
+typedef struct DSAsig DSAsig;
+
+/* public/encryption key */
+struct DSApub
+{
+	mpint	*p;	/* modulus */
+	mpint	*q;	/* group order, q divides p-1 */
+	mpint	*alpha;	/* group generator */
+	mpint	*key;	/* (encryption key) alpha**secret mod p */
+};
+
+/* private/decryption key */
+struct DSApriv
+{
+	DSApub	pub;
+	mpint	*secret;	/* (decryption key) */
+};
+
+/* signature */
+struct DSAsig
+{
+	mpint	*r, *s;
+};
+
+DSApriv*	dsagen(DSApub *opub);	/* opub not checked for consistency! */
+DSAsig*		dsasign(DSApriv *k, mpint *m);
+int		dsaverify(DSApub *k, DSAsig *sig, mpint *m);
+DSApub*		dsapuballoc(void);
+void		dsapubfree(DSApub*);
+DSApriv*	dsaprivalloc(void);
+void		dsaprivfree(DSApriv*);
+DSAsig*		dsasigalloc(void);
+void		dsasigfree(DSAsig*);
+DSApub*		dsaprivtopub(DSApriv*);
+DSApriv*	asn1toDSApriv(uchar*, int);
+
+/*
+ * TLS
+ */
+typedef struct Thumbprint{
+	struct Thumbprint *next;
+	uchar	sha1[SHA1dlen];
+} Thumbprint;
+
+typedef struct TLSconn{
+	char	dir[40];	/* connection directory */
+	uchar	*cert;	/* certificate (local on input, remote on output) */
+	uchar	*sessionID;
+	int	certlen;
+	int	sessionIDlen;
+	int	(*trace)(char*fmt, ...);
+	PEMChain*chain;	/* optional extra certificate evidence for servers to present */
+	char	*sessionType;
+	uchar	*sessionKey;
+	int	sessionKeylen;
+	char	*sessionConst;
+} TLSconn;
+
+/* tlshand.c */
+int tlsClient(int fd, TLSconn *c);
+int tlsServer(int fd, TLSconn *c);
+
+/* thumb.c */
+Thumbprint* initThumbprints(char *ok, char *crl);
+void	freeThumbprints(Thumbprint *ok);
+int	okThumbprint(uchar *sha1, Thumbprint *ok);
+
+/* readcert.c */
+uchar	*readcert(char *filename, int *pcertlen);
+PEMChain*readcertchain(char *filename);
--- /dev/null
+++ b/sys/include/mach.h
@@ -1,0 +1,316 @@
+/*
+ *	Architecture-dependent application data
+ */
+#include "a.out.h"
+#pragma	src	"/sys/src/libmach"
+#pragma	lib	"libmach.a"
+/*
+ *	Supported architectures:
+ *		mips,
+ *		68020,
+ *		i386,
+ *		amd64,
+ *		sparc,
+ *		sparc64,
+ *		mips2 (R4000)
+ *		arm
+ *		powerpc,
+ *		powerpc64
+ *		alpha
+ */
+enum
+{
+	MMIPS,			/* machine types */
+	MSPARC,
+	M68020,
+	MI386,
+	MI960,			/* retired */
+	M3210,			/* retired */
+	MMIPS2,
+	NMIPS2,
+	M29000,			/* retired */
+	MARM,
+	MPOWER,
+	MALPHA,
+	NMIPS,
+	MSPARC64,
+	MAMD64,
+	MPOWER64,
+				/* types of executables */
+	FNONE = 0,		/* unidentified */
+	FMIPS,			/* v.out */
+	FMIPSB,			/* mips bootable */
+	FSPARC,			/* k.out */
+	FSPARCB,		/* Sparc bootable */
+	F68020,			/* 2.out */
+	F68020B,		/* 68020 bootable */
+	FNEXTB,			/* Next bootable */
+	FI386,			/* 8.out */
+	FI386B,			/* I386 bootable */
+	FI960,			/* retired */
+	FI960B,			/* retired */
+	F3210,			/* retired */
+	FMIPS2BE,		/* 4.out */
+	F29000,			/* retired */
+	FARM,			/* 5.out */
+	FARMB,			/* ARM bootable */
+	FPOWER,			/* q.out */
+	FPOWERB,		/* power pc bootable */
+	FMIPS2LE,		/* 0.out */
+	FALPHA,			/* 7.out */
+	FALPHAB,		/* DEC Alpha bootable */
+	FMIPSLE,		/* 3k little endian */
+	FSPARC64,		/* u.out */
+	FAMD64,			/* 6.out */
+	FAMD64B,		/* 6.out bootable */
+	FPOWER64,		/* 9.out */
+	FPOWER64B,		/* 9.out bootable */
+
+	ANONE = 0,		/* dissembler types */
+	AMIPS,
+	AMIPSCO,		/* native mips */
+	ASPARC,
+	ASUNSPARC,		/* native sun */
+	A68020,
+	AI386,
+	AI8086,			/* oh god */
+	AI960,			/* retired */
+	A29000,			/* retired */
+	AARM,
+	APOWER,
+	AALPHA,
+	ASPARC64,
+	AAMD64,
+	APOWER64,
+				/* object file types */
+	Obj68020 = 0,		/* .2 */
+	ObjSparc,		/* .k */
+	ObjMips,		/* .v */
+	Obj386,			/* .8 */
+	Obj960,			/* retired */
+	Obj3210,		/* retired */
+	ObjMips2,		/* .4 */
+	Obj29000,		/* retired */
+	ObjArm,			/* .5 */
+	ObjPower,		/* .q */
+	ObjMips2le,		/* .0 */
+	ObjAlpha,		/* .7 */
+	ObjSparc64,		/* .u */
+	ObjAmd64,		/* .6 */
+	ObjSpim,		/* .0 */
+	ObjPower64,		/* .9 */
+	Maxobjtype,
+
+	CNONE  = 0,		/* symbol table classes */
+	CAUTO,
+	CPARAM,
+	CSTAB,
+	CTEXT,
+	CDATA,
+	CANY,			/* to look for any class */
+};
+
+typedef	struct	Map	Map;
+typedef struct	Symbol	Symbol;
+typedef	struct	Reglist	Reglist;
+typedef	struct	Mach	Mach;
+typedef	struct	Machdata Machdata;
+
+/*
+ * 	Structure to map a segment to a position in a file
+ */
+struct Map {
+	int	nsegs;			/* number of segments */
+	struct segment {		/* per-segment map */
+		char	*name;		/* the segment name */
+		int	fd;		/* file descriptor */
+		int	inuse;		/* in use - not in use */
+		int	cache;		/* should cache reads? */
+		uvlong	b;		/* base */
+		uvlong	e;		/* end */
+		vlong	f;		/* offset within file */
+	} seg[1];			/* actually n of these */
+};
+
+/*
+ *	Internal structure describing a symbol table entry
+ */
+struct Symbol {
+	void 	*handle;		/* used internally - owning func */
+	struct {
+		char	*name;
+		vlong	value;		/* address or stack offset */
+		char	type;		/* as in a.out.h */
+		char	class;		/* as above */
+		int	index;		/* in findlocal, globalsym, textsym */
+	};
+};
+
+/*
+ *	machine register description
+ */
+struct Reglist {
+	char	*rname;			/* register name */
+	short	roffs;			/* offset in u-block */
+	char	rflags;			/* INTEGER/FLOAT, WRITABLE */
+	char	rformat;		/* print format: 'x', 'X', 'f', '8', '3', 'Y', 'W' */
+};
+
+enum {					/* bits in rflags field */
+	RINT	= (0<<0),
+	RFLT	= (1<<0),
+	RRDONLY	= (1<<1),
+};
+
+/*
+ *	Machine-dependent data is stored in two structures:
+ *		Mach  - miscellaneous general parameters
+ *		Machdata - jump vector of service functions used by debuggers
+ *
+ *	Mach is defined in ?.c and set in executable.c
+ *
+ *	Machdata is defined in ?db.c
+ *		and set in the debugger startup.
+ */
+struct Mach{
+	char	*name;
+	int	mtype;			/* machine type code */
+	Reglist *reglist;		/* register set */
+	long	regsize;		/* sizeof registers in bytes */
+	long	fpregsize;		/* sizeof fp registers in bytes */
+	char	*pc;			/* pc name */
+	char	*sp;			/* sp name */
+	char	*link;			/* link register name */
+	char	*sbreg;			/* static base register name */
+	uvlong	sb;			/* static base register value */
+	int	pgsize;			/* page size */
+	uvlong	kbase;			/* kernel base address */
+	uvlong	ktmask;			/* ktzero = kbase & ~ktmask */
+	uvlong	utop;			/* user stack top */
+	int	pcquant;		/* quantization of pc */
+	int	szaddr;			/* sizeof(void*) */
+	int	szreg;			/* sizeof(register) */
+	int	szfloat;		/* sizeof(float) */
+	int	szdouble;		/* sizeof(double) */
+};
+
+extern	Mach	*mach;			/* Current machine */
+
+typedef uvlong	(*Rgetter)(Map*, char*);
+typedef	void	(*Tracer)(Map*, uvlong, uvlong, Symbol*);
+
+struct	Machdata {		/* Machine-dependent debugger support */
+	uchar	bpinst[4];			/* break point instr. */
+	short	bpsize;				/* size of break point instr. */
+
+	ushort	(*swab)(ushort);		/* ushort to local byte order */
+	ulong	(*swal)(ulong);			/* ulong to local byte order */
+	uvlong	(*swav)(uvlong);		/* uvlong to local byte order */
+	int	(*ctrace)(Map*, uvlong, uvlong, uvlong, Tracer); /* C traceback */
+	uvlong	(*findframe)(Map*, uvlong, uvlong, uvlong, uvlong);/* frame finder */
+	char*	(*excep)(Map*, Rgetter);	/* last exception */
+	ulong	(*bpfix)(uvlong);		/* breakpoint fixup */
+	int	(*sftos)(char*, int, void*);	/* single precision float */
+	int	(*dftos)(char*, int, void*);	/* double precision float */
+	int	(*foll)(Map*, uvlong, Rgetter, uvlong*);/* follow set */
+	int	(*das)(Map*, uvlong, char, char*, int);	/* symbolic disassembly */
+	int	(*hexinst)(Map*, uvlong, char*, int); 	/* hex disassembly */
+	int	(*instsize)(Map*, uvlong);	/* instruction size */
+};
+
+/*
+ *	Common a.out header describing all architectures
+ */
+typedef struct Fhdr
+{
+	char	*name;		/* identifier of executable */
+	uchar	type;		/* file type - see codes above */
+	uchar	hdrsz;		/* header size */
+	uchar	_magic;		/* _MAGIC() magic */
+	uchar	spare;
+	long	magic;		/* magic number */
+	uvlong	txtaddr;	/* text address */
+	vlong	txtoff;		/* start of text in file */
+	uvlong	dataddr;	/* start of data segment */
+	vlong	datoff;		/* offset to data seg in file */
+	vlong	symoff;		/* offset of symbol table in file */
+	uvlong	entry;		/* entry point */
+	vlong	sppcoff;	/* offset of sp-pc table in file */
+	vlong	lnpcoff;	/* offset of line number-pc table in file */
+	long	txtsz;		/* text size */
+	long	datsz;		/* size of data seg */
+	long	bsssz;		/* size of bss */
+	long	symsz;		/* size of symbol table */
+	long	sppcsz;		/* size of sp-pc table */
+	long	lnpcsz;		/* size of line number-pc table */
+} Fhdr;
+
+extern	int	asstype;	/* dissembler type - machdata.c */
+extern	Machdata *machdata;	/* jump vector - machdata.c */
+
+Map*		attachproc(int, int, int, Fhdr*);
+int		beieee80ftos(char*, int, void*);
+int		beieeesftos(char*, int, void*);
+int		beieeedftos(char*, int, void*);
+ushort		beswab(ushort);
+ulong		beswal(ulong);
+uvlong		beswav(uvlong);
+uvlong		ciscframe(Map*, uvlong, uvlong, uvlong, uvlong);
+int		cisctrace(Map*, uvlong, uvlong, uvlong, Tracer);
+int		crackhdr(int fd, Fhdr*);
+uvlong		file2pc(char*, long);
+int		fileelem(Sym**, uchar *, char*, int);
+long		fileline(char*, int, uvlong);
+int		filesym(int, char*, int);
+int		findlocal(Symbol*, char*, Symbol*);
+int		findseg(Map*, char*);
+int		findsym(uvlong, int, Symbol *);
+int		fnbound(uvlong, uvlong*);
+int		fpformat(Map*, Reglist*, char*, int, int);
+int		get1(Map*, uvlong, uchar*, int);
+int		get2(Map*, uvlong, ushort*);
+int		get4(Map*, uvlong, ulong*);
+int		get8(Map*, uvlong, uvlong*);
+int		geta(Map*, uvlong, uvlong*);
+int		getauto(Symbol*, int, int, Symbol*);
+Sym*		getsym(int);
+int		globalsym(Symbol *, int);
+char*		_hexify(char*, ulong, int);
+int		ieeesftos(char*, int, ulong);
+int		ieeedftos(char*, int, ulong, ulong);
+int		isar(Biobuf*);
+int		leieee80ftos(char*, int, void*);
+int		leieeesftos(char*, int, void*);
+int		leieeedftos(char*, int, void*);
+ushort		leswab(ushort);
+ulong		leswal(ulong);
+uvlong		leswav(uvlong);
+uvlong		line2addr(long, uvlong, uvlong);
+Map*		loadmap(Map*, int, Fhdr*);
+int		localaddr(Map*, char*, char*, uvlong*, Rgetter);
+int		localsym(Symbol*, int);
+int		lookup(char*, char*, Symbol*);
+void		machbytype(int);
+int		machbyname(char*);
+int		nextar(Biobuf*, int, char*);
+Map*		newmap(Map*, int);
+void		objtraverse(void(*)(Sym*, void*), void*);
+int		objtype(Biobuf*, char**);
+uvlong		pc2sp(uvlong);
+long		pc2line(uvlong);
+int		put1(Map*, uvlong, uchar*, int);
+int		put2(Map*, uvlong, ushort);
+int		put4(Map*, uvlong, ulong);
+int		put8(Map*, uvlong, uvlong);
+int		puta(Map*, uvlong, uvlong);
+int		readar(Biobuf*, int, vlong, int);
+int		readobj(Biobuf*, int);
+uvlong		riscframe(Map*, uvlong, uvlong, uvlong, uvlong);
+int		risctrace(Map*, uvlong, uvlong, uvlong, Tracer);
+int		setmap(Map*, int, uvlong, uvlong, vlong, char*);
+Sym*		symbase(long*);
+int		syminit(int, Fhdr*);
+int		symoff(char*, int, uvlong, int);
+void		textseg(uvlong, Fhdr*);
+int		textsym(Symbol*, int);
+void		unusemap(Map*, int);
--- /dev/null
+++ b/sys/include/memdraw.h
@@ -1,0 +1,194 @@
+#pragma	src	"/sys/src/libmemdraw"
+#pragma	lib	"libmemdraw.a"
+
+typedef struct	Memimage Memimage;
+typedef struct	Memdata Memdata;
+typedef struct	Memsubfont Memsubfont;
+typedef struct	Memlayer Memlayer;
+typedef struct	Memcmap Memcmap;
+typedef struct	Memdrawparam	Memdrawparam;
+
+#pragma incomplete Memlayer
+
+/*
+ * Memdata is allocated from main pool, but .data from the image pool.
+ * Memdata is allocated separately to permit patching its pointer after
+ * compaction when windows share the image data.
+ * The first word of data is a back pointer to the Memdata, to find
+ * The word to patch.
+ */
+
+struct Memdata
+{
+	ulong	*base;	/* allocated data pointer */
+	uchar	*bdata;	/* pointer to first byte of actual data; word-aligned */
+	int		ref;		/* number of Memimages using this data */
+	void*	imref;
+	int		allocd;	/* is this malloc'd? */
+};
+
+enum {
+	Frepl		= 1<<0,	/* is replicated */
+	Fsimple	= 1<<1,	/* is 1x1 */
+	Fgrey	= 1<<2,	/* is grey */
+	Falpha	= 1<<3,	/* has explicit alpha */
+	Fcmap	= 1<<4,	/* has cmap channel */
+	Fbytes	= 1<<5,	/* has only 8-bit channels */
+};
+
+struct Memimage
+{
+	Rectangle	r;		/* rectangle in data area, local coords */
+	Rectangle	clipr;		/* clipping region */
+	int		depth;	/* number of bits of storage per pixel */
+	int		nchan;	/* number of channels */
+	ulong	chan;	/* channel descriptions */
+	Memcmap	*cmap;
+
+	Memdata	*data;	/* pointer to data; shared by windows in this image */
+	int		zero;		/* data->bdata+zero==&byte containing (0,0) */
+	ulong	width;	/* width in words of a single scan line */
+	Memlayer	*layer;	/* nil if not a layer*/
+	ulong	flags;
+
+	int		shift[NChan];
+	int		mask[NChan];
+	int		nbits[NChan];
+};
+
+struct Memcmap
+{
+	uchar	cmap2rgb[3*256];
+	uchar	rgb2cmap[16*16*16];
+};
+
+/*
+ * Subfonts
+ *
+ * given char c, Subfont *f, Fontchar *i, and Point p, one says
+ *	i = f->info+c;
+ *	draw(b, Rect(p.x+i->left, p.y+i->top,
+ *		p.x+i->left+((i+1)->x-i->x), p.y+i->bottom),
+ *		color, f->bits, Pt(i->x, i->top));
+ *	p.x += i->width;
+ * to draw characters in the specified color (itself a Memimage) in Memimage b.
+ */
+
+struct	Memsubfont
+{
+	char		*name;
+	short	n;		/* number of chars in font */
+	uchar	height;		/* height of bitmap */
+	char	ascent;		/* top of bitmap to baseline */
+	Fontchar *info;		/* n+1 character descriptors */
+	Memimage	*bits;		/* of font */
+};
+
+/*
+ * Encapsulated parameters and information for sub-draw routines.
+ */
+enum {
+	Simplesrc=1<<0,
+	Simplemask=1<<1,
+	Replsrc=1<<2,
+	Replmask=1<<3,
+	Fullmask=1<<4,
+};
+struct	Memdrawparam
+{
+	Memimage *dst;
+	Rectangle	r;
+	Memimage *src;
+	Rectangle sr;
+	Memimage *mask;
+	Rectangle mr;
+	int op;
+
+	ulong state;
+	ulong mval;	/* if Simplemask, the mask pixel in mask format */
+	ulong mrgba;	/* mval in rgba */
+	ulong sval;	/* if Simplesrc, the source pixel in src format */
+	ulong srgba;	/* sval in rgba */
+	ulong sdval;	/* sval in dst format */
+};
+
+/*
+ * Memimage management
+ */
+
+extern Memimage*	allocmemimage(Rectangle, ulong);
+extern Memimage*	allocmemimaged(Rectangle, ulong, Memdata*);
+extern Memimage*	readmemimage(int);
+extern Memimage*	creadmemimage(int);
+extern int	writememimage(int, Memimage*);
+extern void	freememimage(Memimage*);
+extern int		loadmemimage(Memimage*, Rectangle, uchar*, int);
+extern int		cloadmemimage(Memimage*, Rectangle, uchar*, int);
+extern int		unloadmemimage(Memimage*, Rectangle, uchar*, int);
+extern ulong*	wordaddr(Memimage*, Point);
+extern uchar*	byteaddr(Memimage*, Point);
+extern int		drawclip(Memimage*, Rectangle*, Memimage*, Point*, Memimage*, Point*, Rectangle*, Rectangle*);
+extern void	memfillcolor(Memimage*, ulong);
+extern int		memsetchan(Memimage*, ulong);
+
+/*
+ * Graphics
+ */
+extern void	memdraw(Memimage*, Rectangle, Memimage*, Point, Memimage*, Point, int);
+extern void	memline(Memimage*, Point, Point, int, int, int, Memimage*, Point, int);
+extern void	mempoly(Memimage*, Point*, int, int, int, int, Memimage*, Point, int);
+extern void	memfillpoly(Memimage*, Point*, int, int, Memimage*, Point, int);
+extern void	_memfillpolysc(Memimage*, Point*, int, int, Memimage*, Point, int, int, int, int);
+extern void	memimagedraw(Memimage*, Rectangle, Memimage*, Point, Memimage*, Point, int);
+extern int	hwdraw(Memdrawparam*);
+extern void	memimageline(Memimage*, Point, Point, int, int, int, Memimage*, Point, int);
+extern void	_memimageline(Memimage*, Point, Point, int, int, int, Memimage*, Point, Rectangle, int);
+extern Point	memimagestring(Memimage*, Point, Memimage*, Point, Memsubfont*, char*);
+extern void	memellipse(Memimage*, Point, int, int, int, Memimage*, Point, int);
+extern void	memarc(Memimage*, Point, int, int, int, Memimage*, Point, int, int, int);
+extern Rectangle	memlinebbox(Point, Point, int, int, int);
+extern int	memlineendsize(int);
+extern void	_memmkcmap(void);
+extern void	memimageinit(void);
+
+/*
+ * Subfont management
+ */
+extern Memsubfont*	allocmemsubfont(char*, int, int, int, Fontchar*, Memimage*);
+extern Memsubfont*	openmemsubfont(char*);
+extern void	freememsubfont(Memsubfont*);
+extern Point	memsubfontwidth(Memsubfont*, char*);
+extern Memsubfont*	getmemdefont(void);
+
+/*
+ * Predefined 
+ */
+extern	Memimage*	memwhite;
+extern	Memimage*	memblack;
+extern	Memimage*	memopaque;
+extern	Memimage*	memtransparent;
+extern	Memcmap	*memdefcmap;
+
+/*
+ * Kernel interface
+ */
+void		memimagemove(void*, void*);
+
+/*
+ * Kernel cruft
+ */
+extern void	rdb(void);
+extern int		iprint(char*, ...);
+#pragma varargck argpos iprint 1
+extern int		drawdebug;
+
+/*
+ * doprint interface: numbconv bit strings
+ */
+#pragma varargck type "llb" vlong
+#pragma varargck type "llb" uvlong
+#pragma varargck type "lb" long
+#pragma varargck type "lb" ulong
+#pragma varargck type "b" int
+#pragma varargck type "b" uint
+
--- /dev/null
+++ b/sys/include/memlayer.h
@@ -1,0 +1,51 @@
+#pragma src "/sys/src/libmemlayer"
+#pragma lib "libmemlayer.a"
+
+typedef struct Memscreen Memscreen;
+typedef void (*Refreshfn)(Memimage*, Rectangle, void*);
+
+struct Memscreen
+{
+	Memimage	*frontmost;	/* frontmost layer on screen */
+	Memimage	*rearmost;	/* rearmost layer on screen */
+	Memimage	*image;		/* upon which all layers are drawn */
+	Memimage	*fill;			/* if non-zero, picture to use when repainting */
+};
+
+struct Memlayer
+{
+	Rectangle		screenr;	/* true position of layer on screen */
+	Point			delta;	/* add delta to go from image coords to screen */
+	Memscreen	*screen;	/* screen this layer belongs to */
+	Memimage	*front;	/* window in front of this one */
+	Memimage	*rear;	/* window behind this one*/
+	int		clear;	/* layer is fully visible */
+	Memimage	*save;	/* save area for obscured parts */
+	Refreshfn	refreshfn;		/* function to call to refresh obscured parts if save==nil */
+	void		*refreshptr;	/* argument to refreshfn */
+};
+
+/*
+ * These functions accept local coordinates
+ */
+int			memload(Memimage*, Rectangle, uchar*, int, int);
+int			memunload(Memimage*, Rectangle, uchar*, int);
+
+/*
+ * All these functions accept screen coordinates, not local ones.
+ */
+void			_memlayerop(void (*fn)(Memimage*, Rectangle, Rectangle, void*, int), Memimage*, Rectangle, Rectangle, void*);
+Memimage*	memlalloc(Memscreen*, Rectangle, Refreshfn, void*, ulong);
+void			memldelete(Memimage*);
+void			memlfree(Memimage*);
+void			memltofront(Memimage*);
+void			memltofrontn(Memimage**, int);
+void			_memltofrontfill(Memimage*, int);
+void			memltorear(Memimage*);
+void			memltorearn(Memimage**, int);
+int			memlsetrefresh(Memimage*, Refreshfn, void*);
+void			memlhide(Memimage*, Rectangle);
+void			memlexpose(Memimage*, Rectangle);
+void			_memlsetclear(Memscreen*);
+int			memlorigin(Memimage*, Point, Point);
+void			memlnorefresh(Memimage*, Rectangle, void*);
--- /dev/null
+++ b/sys/include/mouse.h
@@ -1,0 +1,46 @@
+#pragma src "/sys/src/libdraw"
+
+typedef struct	Channel Channel;
+typedef struct	Cursor Cursor;
+typedef struct	Menu Menu;
+typedef struct 	Mousectl Mousectl;
+
+struct	Mouse
+{
+	int	buttons;	/* bit array: LMR=124 */
+	Point	xy;
+	ulong	msec;
+};
+
+struct Mousectl
+{
+	Mouse;
+	Channel	*c;	/* chan(Mouse) */
+	Channel	*resizec;	/* chan(int)[2] */
+			/* buffered in case client is waiting for a mouse action before handling resize */
+
+	char		*file;
+	int		mfd;		/* to mouse file */
+	int		cfd;		/* to cursor file */
+	int		pid;		/* of slave proc */
+	Image*	image;	/* of associated window/display */
+};
+
+struct Menu
+{
+	char	**item;
+	char	*(*gen)(int);
+	int	lasthit;
+};
+
+/*
+ * Mouse
+ */
+extern Mousectl*	initmouse(char*, Image*);
+extern void		moveto(Mousectl*, Point);
+extern int			readmouse(Mousectl*);
+extern void		closemouse(Mousectl*);
+extern void		setcursor(Mousectl*, Cursor*);
+extern void		drawgetrect(Rectangle, int);
+extern Rectangle	getrect(int, Mousectl*);
+extern int	 		menuhit(int, Mousectl*, Menu*, Screen*);
--- /dev/null
+++ b/sys/include/mp.h
@@ -1,0 +1,143 @@
+#pragma	src	"/sys/src/libmp"
+#pragma	lib	"libmp.a"
+
+#define _MPINT 1
+
+/*
+ * the code assumes mpdigit to be at least an int
+ * mpdigit must be an atomic type.  mpdigit is defined
+ * in the architecture specific u.h
+ */
+
+typedef struct mpint mpint;
+
+struct mpint
+{
+	int	sign;	/* +1 or -1 */
+	int	size;	/* allocated digits */
+	int	top;	/* significant digits */
+	mpdigit	*p;
+	char	flags;
+};
+
+enum
+{
+	MPstatic=	0x01,
+	Dbytes=		sizeof(mpdigit),	/* bytes per digit */
+	Dbits=		Dbytes*8		/* bits per digit */
+};
+
+/* allocation */
+void	mpsetminbits(int n);	/* newly created mpint's get at least n bits */
+mpint*	mpnew(int n);		/* create a new mpint with at least n bits */
+void	mpfree(mpint *b);
+void	mpbits(mpint *b, int n);	/* ensure that b has at least n bits */
+void	mpnorm(mpint *b);		/* dump leading zeros */
+mpint*	mpcopy(mpint *b);
+void	mpassign(mpint *old, mpint *new);
+
+/* random bits */
+mpint*	mprand(int bits, void (*gen)(uchar*, int), mpint *b);
+
+/* conversion */
+mpint*	strtomp(char*, char**, int, mpint*);	/* ascii */
+int	mpfmt(Fmt*);
+char*	mptoa(mpint*, int, char*, int);
+mpint*	letomp(uchar*, uint, mpint*);	/* byte array, little-endian */
+int	mptole(mpint*, uchar*, uint, uchar**);
+mpint*	betomp(uchar*, uint, mpint*);	/* byte array, little-endian */
+int	mptobe(mpint*, uchar*, uint, uchar**);
+uint	mptoui(mpint*);			/* unsigned int */
+mpint*	uitomp(uint, mpint*);
+int	mptoi(mpint*);			/* int */
+mpint*	itomp(int, mpint*);
+uvlong	mptouv(mpint*);			/* unsigned vlong */
+mpint*	uvtomp(uvlong, mpint*);
+vlong	mptov(mpint*);			/* vlong */
+mpint*	vtomp(vlong, mpint*);
+
+/* divide 2 digits by one */
+void	mpdigdiv(mpdigit *dividend, mpdigit divisor, mpdigit *quotient);
+
+/* in the following, the result mpint may be */
+/* the same as one of the inputs. */
+void	mpadd(mpint *b1, mpint *b2, mpint *sum);	/* sum = b1+b2 */
+void	mpsub(mpint *b1, mpint *b2, mpint *diff);	/* diff = b1-b2 */
+void	mpleft(mpint *b, int shift, mpint *res);	/* res = b<<shift */
+void	mpright(mpint *b, int shift, mpint *res);	/* res = b>>shift */
+void	mpmul(mpint *b1, mpint *b2, mpint *prod);	/* prod = b1*b2 */
+void	mpexp(mpint *b, mpint *e, mpint *m, mpint *res);	/* res = b**e mod m */
+void	mpmod(mpint *b, mpint *m, mpint *remainder);	/* remainder = b mod m */
+
+/* quotient = dividend/divisor, remainder = dividend % divisor */
+void	mpdiv(mpint *dividend, mpint *divisor,  mpint *quotient, mpint *remainder);
+
+/* return neg, 0, pos as b1-b2 is neg, 0, pos */
+int	mpcmp(mpint *b1, mpint *b2);
+
+/* extended gcd return d, x, and y, s.t. d = gcd(a,b) and ax+by = d */
+void	mpextendedgcd(mpint *a, mpint *b, mpint *d, mpint *x, mpint *y);
+
+/* res = b**-1 mod m */
+void	mpinvert(mpint *b, mpint *m, mpint *res);
+
+/* bit counting */
+int	mpsignif(mpint*);	/* number of sigificant bits in mantissa */
+int	mplowbits0(mpint*);	/* k, where n = 2**k * q for odd q */
+
+/* well known constants */
+extern mpint	*mpzero, *mpone, *mptwo;
+
+/* sum[0:alen] = a[0:alen-1] + b[0:blen-1] */
+/* prereq: alen >= blen, sum has room for alen+1 digits */
+void	mpvecadd(mpdigit *a, int alen, mpdigit *b, int blen, mpdigit *sum);
+
+/* diff[0:alen-1] = a[0:alen-1] - b[0:blen-1] */
+/* prereq: alen >= blen, diff has room for alen digits */
+void	mpvecsub(mpdigit *a, int alen, mpdigit *b, int blen, mpdigit *diff);
+
+/* p[0:n] += m * b[0:n-1] */
+/* prereq: p has room for n+1 digits */
+void	mpvecdigmuladd(mpdigit *b, int n, mpdigit m, mpdigit *p);
+
+/* p[0:n] -= m * b[0:n-1] */
+/* prereq: p has room for n+1 digits */
+int	mpvecdigmulsub(mpdigit *b, int n, mpdigit m, mpdigit *p);
+
+/* p[0:alen*blen-1] = a[0:alen-1] * b[0:blen-1] */
+/* prereq: alen >= blen, p has room for m*n digits */
+void	mpvecmul(mpdigit *a, int alen, mpdigit *b, int blen, mpdigit *p);
+
+/* sign of a - b or zero if the same */
+int	mpveccmp(mpdigit *a, int alen, mpdigit *b, int blen);
+
+/* divide the 2 digit dividend by the one digit divisor and stick in quotient */
+/* we assume that the result is one digit - overflow is all 1's */
+void	mpdigdiv(mpdigit *dividend, mpdigit divisor, mpdigit *quotient);
+
+/* playing with magnitudes */
+int	mpmagcmp(mpint *b1, mpint *b2);
+void	mpmagadd(mpint *b1, mpint *b2, mpint *sum);	/* sum = b1+b2 */
+void	mpmagsub(mpint *b1, mpint *b2, mpint *sum);	/* sum = b1+b2 */
+
+/* chinese remainder theorem */
+typedef struct CRTpre	CRTpre;		/* precomputed values for converting */
+					/*  twixt residues and mpint */
+typedef struct CRTres	CRTres;		/* residue form of an mpint */
+
+#pragma incomplete CRTpre
+
+struct CRTres
+{
+	int	n;		/* number of residues */
+	mpint	*r[1];		/* residues */
+};
+
+CRTpre*	crtpre(int, mpint**);			/* precompute conversion values */
+CRTres*	crtin(CRTpre*, mpint*);			/* convert mpint to residues */
+void	crtout(CRTpre*, CRTres*, mpint*);	/* convert residues to mpint */
+void	crtprefree(CRTpre*);
+void	crtresfree(CRTres*);
+
+
+#pragma	varargck	type	"B"	mpint*
--- /dev/null
+++ b/sys/include/ndb.h
@@ -1,0 +1,154 @@
+#pragma	src	"/sys/src/libndb"
+#pragma	lib	"libndb.a"
+
+/*
+ *  this include file requires includes of <u.h> and <bio.h>
+ */
+typedef struct Ndb	Ndb;
+typedef struct Ndbtuple	Ndbtuple;
+typedef struct Ndbhf	Ndbhf;
+typedef struct Ndbs	Ndbs;
+typedef struct Ndbcache	Ndbcache;
+
+#pragma incomplete Ndbhf
+#pragma incomplete Ndbcache
+
+enum
+{
+	Ndbalen=	32,	/* max attribute length */
+	Ndbvlen=	64,	/* max value length */
+};
+
+/*
+ *  the database
+ */
+struct Ndb
+{
+	Ndb		*next;
+
+	Biobufhdr	b;		/* buffered input file */
+	uchar		buf[256];	/* and its buffer */
+
+	ulong		mtime;		/* mtime of db file */
+	Qid		qid;		/* qid of db file */
+	char		file[128];/* path name of db file */
+	ulong		length;		/* length of db file */
+
+	int		nohash;		/* don't look for hash files */
+	Ndbhf		*hf;		/* open hash files */
+
+	int		ncache;		/* size of tuple cache */
+	Ndbcache	*cache;		/* cached entries */
+};
+
+/*
+ *  a parsed entry, doubly linked
+ */
+struct Ndbtuple
+{
+	char		attr[Ndbalen];		/* attribute name */
+	char		*val;			/* value(s) */
+	Ndbtuple	*entry;			/* next tuple in this entry */
+	Ndbtuple	*line;			/* next tuple on this line */
+	ulong		ptr;			/* (for the application - starts 0) */
+	char		valbuf[Ndbvlen];	/* initial allocation for value */
+};
+
+/*
+ *  each hash file is of the form
+ *
+ *		+---------------------------------------+
+ *		|	mtime of db file (4 bytes)	|
+ *		+---------------------------------------+
+ *		|  size of table (in entries - 4 bytes)	|
+ *		+---------------------------------------+
+ *		|		hash table		|
+ *		+---------------------------------------+
+ *		|		hash chains		|
+ *		+---------------------------------------+
+ *
+ *  hash collisions are resolved using chained entries added to the
+ *  the end of the hash table.
+ *
+ *  Hash entries are of the form
+ *
+ *		+-------------------------------+
+ *		|	offset	(3 bytes) 	|
+ *		+-------------------------------+
+ *
+ *  Chain entries are of the form
+ *
+ *		+-------------------------------+
+ *		|	offset1	(3 bytes) 	|
+ *		+-------------------------------+
+ *		|	offset2	(3 bytes) 	|
+ *		+-------------------------------+
+ *
+ *  The top bit of an offset set to 1 indicates a pointer to a hash chain entry.
+ */
+#define NDBULLEN	4		/* unsigned long length in bytes */
+#define NDBPLEN		3		/* pointer length in bytes */
+#define NDBHLEN		(2*NDBULLEN)	/* hash file header length in bytes */
+
+/*
+ *  finger pointing to current point in a search
+ */
+struct Ndbs
+{
+	Ndb	*db;	/* data base file being searched */
+	Ndbhf	*hf;	/* hash file being searched */
+	int	type;
+	ulong	ptr;	/* current pointer */
+	ulong	ptr1;	/* next pointer */
+	Ndbtuple *t;	/* last attribute value pair found */
+};
+
+/*
+ *  bit defs for pointers in hash files
+ */
+#define NDBSPEC 	(1<<23)
+#define NDBCHAIN	NDBSPEC		/* points to a collision chain */
+#define NDBNAP		(NDBSPEC|1)	/* not a pointer */
+
+/*
+ *  macros for packing and unpacking pointers
+ */
+#define NDBPUTP(v,a) { (a)[0] = v; (a)[1] = (v)>>8; (a)[2] = (v)>>16; }
+#define NDBGETP(a) ((a)[0] | ((a)[1]<<8) | ((a)[2]<<16))
+
+/*
+ *  macros for packing and unpacking unsigned longs
+ */
+#define NDBPUTUL(v,a) { (a)[0] = v; (a)[1] = (v)>>8; (a)[2] = (v)>>16; (a)[3] = (v)>>24; }
+#define NDBGETUL(a) ((a)[0] | ((a)[1]<<8) | ((a)[2]<<16) | ((a)[3]<<24))
+
+#define NDB_IPlen 16
+
+Ndbtuple*	csgetval(char*, char*, char*, char*, char*);
+char*		csgetvalue(char*, char*, char*, char*, Ndbtuple**);
+Ndbtuple*	csipinfo(char*, char*, char*, char**, int);
+Ndbtuple*	dnsquery(char*, char*, char*);
+char*		ipattr(char*);
+Ndb*		ndbcat(Ndb*, Ndb*);
+int		ndbchanged(Ndb*);
+void		ndbclose(Ndb*);
+Ndbtuple*	ndbconcatenate(Ndbtuple*, Ndbtuple*);
+Ndbtuple*	ndbdiscard(Ndbtuple*, Ndbtuple*);
+void		ndbfree(Ndbtuple*);
+Ndbtuple*	ndbgetipaddr(Ndb*, char*);
+Ndbtuple*	ndbgetval(Ndb*, Ndbs*, char*, char*, char*, char*);
+char*		ndbgetvalue(Ndb*, Ndbs*, char*, char*, char*, Ndbtuple**);
+Ndbtuple*	ndbfindattr(Ndbtuple*, Ndbtuple*, char*);
+ulong		ndbhash(char*, int);
+Ndbtuple*	ndbipinfo(Ndb*, char*, char*, char**, int);
+Ndbtuple*	ndblookval(Ndbtuple*, Ndbtuple*, char*, char*);
+Ndbtuple*	ndbnew(char*, char*);
+Ndb*		ndbopen(char*);
+Ndbtuple*	ndbparse(Ndb*);
+int		ndbreopen(Ndb*);
+Ndbtuple*	ndbreorder(Ndbtuple*, Ndbtuple*);
+Ndbtuple*	ndbsearch(Ndb*, Ndbs*, char*, char*);
+void		ndbsetval(Ndbtuple*, char*, int);
+Ndbtuple*	ndbsnext(Ndbs*, char*, char*);
+Ndbtuple*	ndbsubstitute(Ndbtuple*, Ndbtuple*, Ndbtuple*);
+void		ndbsetmalloctag(Ndbtuple*, uintptr);
--- /dev/null
+++ b/sys/include/nfs3.h
@@ -1,0 +1,811 @@
+/* 
+ * NFS mounter V3;  see RFC 1813
+ */
+
+#pragma lib "libsunrpc.a"
+#pragma src "/sys/src/libsunrpc"
+
+enum {
+	NfsMount1HandleSize = 32,
+	NfsMount3MaxPathSize = 1024,
+	NfsMount3MaxNameSize = 255,
+	NfsMount3MaxHandleSize = 64,
+	NfsMount3Program = 100005,
+	NfsMount3Version = 3,
+	NfsMount1Program = 100005,
+	NfsMount1Version = 1
+};
+typedef struct NfsMount3TNull NfsMount3TNull;
+typedef struct NfsMount3RNull NfsMount3RNull;
+typedef struct NfsMount3TMnt NfsMount3TMnt;
+typedef struct NfsMount3RMnt NfsMount3RMnt;
+typedef struct NfsMount3TDump NfsMount3TDump;
+typedef struct NfsMount3Entry NfsMount3Entry;
+typedef struct NfsMount3RDump NfsMount3RDump;
+typedef struct NfsMount3TUmnt NfsMount3TUmnt;
+typedef struct NfsMount3RUmnt NfsMount3RUmnt;
+typedef struct NfsMount3Export NfsMount3Export;
+typedef struct NfsMount3TUmntall NfsMount3TUmntall;
+typedef struct NfsMount3RUmntall NfsMount3RUmntall;
+typedef struct NfsMount3TExport NfsMount3TExport;
+typedef struct NfsMount3RExport NfsMount3RExport;
+
+typedef enum
+{
+	NfsMount3CallTNull,
+	NfsMount3CallRNull,
+	NfsMount3CallTMnt,
+	NfsMount3CallRMnt,
+	NfsMount3CallTDump,
+	NfsMount3CallRDump,
+	NfsMount3CallTUmnt,
+	NfsMount3CallRUmnt,
+	NfsMount3CallTUmntall,
+	NfsMount3CallRUmntall,
+	NfsMount3CallTExport,
+	NfsMount3CallRExport
+} NfsMount3CallType;
+
+typedef struct NfsMount3Call NfsMount3Call;
+struct NfsMount3Call {
+	SunRpc rpc;
+	NfsMount3CallType type;
+};
+
+struct NfsMount3TNull {
+	NfsMount3Call call;
+};
+
+struct NfsMount3RNull {
+	NfsMount3Call call;
+};
+
+struct NfsMount3TMnt {
+	NfsMount3Call call;
+	char *path;
+};
+
+struct NfsMount3RMnt {
+	NfsMount3Call call;
+	uint status;
+	uchar *handle;
+	uint len;
+	u32int *auth;
+	u32int nauth;
+};
+
+struct NfsMount3TDump {
+	NfsMount3Call call;
+};
+
+struct NfsMount3Entry {
+	char *host;
+	char *path;
+};
+
+struct NfsMount3RDump {
+	NfsMount3Call call;
+	uchar *data;
+	u32int count;
+};
+
+struct NfsMount3TUmnt {
+	NfsMount3Call call;
+	char *path;
+};
+
+struct NfsMount3RUmnt {
+	NfsMount3Call call;
+};
+
+struct NfsMount3Export {
+	char *path;
+	char **g;
+	u32int ng;
+};
+
+struct NfsMount3TUmntall {
+	NfsMount3Call call;
+};
+
+struct NfsMount3RUmntall {
+	NfsMount3Call call;
+};
+
+struct NfsMount3TExport {
+	NfsMount3Call call;
+};
+
+struct NfsMount3RExport {
+	NfsMount3Call call;
+	uchar *data;
+	u32int count;
+};
+
+uint nfsMount3ExportGroupSize(uchar*);
+uint nfsMount3ExportSize(NfsMount3Export*);
+int nfsMount3ExportPack(uchar*, uchar*, uchar**, NfsMount3Export*);
+int nfsMount3ExportUnpack(uchar*, uchar*, uchar**, char**, char***, NfsMount3Export*);
+int nfsMount3EntryPack(uchar*, uchar*, uchar**, NfsMount3Entry*);
+int nfsMount3EntryUnpack(uchar*, uchar*, uchar**, NfsMount3Entry*);
+uint nfsMount3EntrySize(NfsMount3Entry*);
+
+extern SunProg nfsMount3Prog;
+
+/*
+ * NFS V3; see RFC 1813
+ */
+enum {
+	Nfs3MaxHandleSize = 64,
+	Nfs3CookieVerfSize = 8,
+	Nfs3CreateVerfSize = 8,
+	Nfs3WriteVerfSize = 8,
+	Nfs3AccessRead = 1,
+	Nfs3AccessLookup = 2,
+	Nfs3AccessModify = 4,
+	Nfs3AccessExtend = 8,
+	Nfs3AccessDelete = 16,
+	Nfs3AccessExecute = 32,
+	Nfs3FsHasLinks = 1,
+	Nfs3FsHasSymlinks = 2,
+	Nfs3FsHomogeneous = 8,
+	Nfs3FsCanSetTime = 16,
+
+	Nfs3Version = 3,	
+	Nfs3Program = 100003,
+};
+typedef enum
+{
+	Nfs3Ok = 0,
+	Nfs3ErrNotOwner = 1,
+	Nfs3ErrNoEnt = 2,
+	Nfs3ErrIo = 5,
+	Nfs3ErrNxio = 6,
+	Nfs3ErrNoMem = 12,
+	Nfs3ErrAcces = 13,
+	Nfs3ErrExist = 17,
+	Nfs3ErrXDev = 18,
+	Nfs3ErrNoDev = 19,
+	Nfs3ErrNotDir = 20,
+	Nfs3ErrIsDir = 21,
+	Nfs3ErrInval = 22,
+	Nfs3ErrFbig = 27,
+	Nfs3ErrNoSpc = 28,
+	Nfs3ErrRoFs = 30,
+	Nfs3ErrMLink = 31,
+	Nfs3ErrNameTooLong = 63,
+	Nfs3ErrNotEmpty = 66,
+	Nfs3ErrDQuot = 69,
+	Nfs3ErrStale = 70,
+	Nfs3ErrRemote = 71,
+	Nfs3ErrBadHandle = 10001,
+	Nfs3ErrNotSync = 10002,
+	Nfs3ErrBadCookie = 10003,
+	Nfs3ErrNotSupp = 10004,
+	Nfs3ErrTooSmall = 10005,
+	Nfs3ErrServerFault = 10006,
+	Nfs3ErrBadType = 10007,
+	Nfs3ErrJukebox = 10008,
+	Nfs3ErrFprintNotFound = 10009,
+	Nfs3ErrAborted = 10010,
+} Nfs3Status;
+
+void nfs3Errstr(Nfs3Status);
+
+typedef enum
+{
+	Nfs3FileReg = 1,
+	Nfs3FileDir = 2,
+	Nfs3FileBlock = 3,
+	Nfs3FileChar = 4,
+	Nfs3FileSymlink = 5,
+	Nfs3FileSocket = 6,
+	Nfs3FileFifo = 7,
+} Nfs3FileType;
+
+enum
+{
+	Nfs3ModeSetUid = 0x800,
+	Nfs3ModeSetGid = 0x400,
+	Nfs3ModeSticky = 0x200,
+};
+
+typedef enum
+{
+	Nfs3CallTNull,
+	Nfs3CallRNull,
+	Nfs3CallTGetattr,
+	Nfs3CallRGetattr,
+	Nfs3CallTSetattr,
+	Nfs3CallRSetattr,
+	Nfs3CallTLookup,
+	Nfs3CallRLookup,
+	Nfs3CallTAccess,
+	Nfs3CallRAccess,
+	Nfs3CallTReadlink,
+	Nfs3CallRReadlink,
+	Nfs3CallTRead,
+	Nfs3CallRRead,
+	Nfs3CallTWrite,
+	Nfs3CallRWrite,
+	Nfs3CallTCreate,
+	Nfs3CallRCreate,
+	Nfs3CallTMkdir,
+	Nfs3CallRMkdir,
+	Nfs3CallTSymlink,
+	Nfs3CallRSymlink,
+	Nfs3CallTMknod,
+	Nfs3CallRMknod,
+	Nfs3CallTRemove,
+	Nfs3CallRRemove,
+	Nfs3CallTRmdir,
+	Nfs3CallRRmdir,
+	Nfs3CallTRename,
+	Nfs3CallRRename,
+	Nfs3CallTLink,
+	Nfs3CallRLink,
+	Nfs3CallTReadDir,
+	Nfs3CallRReadDir,
+	Nfs3CallTReadDirPlus,
+	Nfs3CallRReadDirPlus,
+	Nfs3CallTFsStat,
+	Nfs3CallRFsStat,
+	Nfs3CallTFsInfo,
+	Nfs3CallRFsInfo,
+	Nfs3CallTPathconf,
+	Nfs3CallRPathconf,
+	Nfs3CallTCommit,
+	Nfs3CallRCommit,
+} Nfs3CallType;
+
+typedef struct Nfs3Call Nfs3Call;
+typedef struct Nfs3Handle Nfs3Handle;
+typedef struct Nfs3Time Nfs3Time;
+typedef struct Nfs3Attr Nfs3Attr;
+typedef struct Nfs3WccAttr Nfs3WccAttr;
+typedef struct Nfs3Wcc Nfs3Wcc;
+typedef enum
+{
+	Nfs3SetTimeDont = 0,
+	Nfs3SetTimeServer = 1,
+	Nfs3SetTimeClient = 2,
+} Nfs3SetTime;
+
+typedef struct Nfs3SetAttr Nfs3SetAttr;
+typedef struct Nfs3TNull Nfs3TNull;
+typedef struct Nfs3RNull Nfs3RNull;
+typedef struct Nfs3TGetattr Nfs3TGetattr;
+typedef struct Nfs3RGetattr Nfs3RGetattr;
+typedef struct Nfs3TSetattr Nfs3TSetattr;
+typedef struct Nfs3RSetattr Nfs3RSetattr;
+typedef struct Nfs3TLookup Nfs3TLookup;
+typedef struct Nfs3RLookup Nfs3RLookup;
+typedef struct Nfs3TAccess Nfs3TAccess;
+typedef struct Nfs3RAccess Nfs3RAccess;
+typedef struct Nfs3TReadlink Nfs3TReadlink;
+typedef struct Nfs3RReadlink Nfs3RReadlink;
+typedef struct Nfs3TRead Nfs3TRead;
+typedef struct Nfs3RRead Nfs3RRead;
+typedef enum
+{
+	Nfs3SyncNone = 0,
+	Nfs3SyncData = 1,
+	Nfs3SyncFile = 2,
+} Nfs3Sync;
+
+typedef struct Nfs3TWrite Nfs3TWrite;
+typedef struct Nfs3RWrite Nfs3RWrite;
+typedef enum
+{
+	Nfs3CreateUnchecked = 0,
+	Nfs3CreateGuarded = 1,
+	Nfs3CreateExclusive = 2,
+} Nfs3Create;
+
+typedef struct Nfs3TCreate Nfs3TCreate;
+typedef struct Nfs3RCreate Nfs3RCreate;
+typedef struct Nfs3TMkdir Nfs3TMkdir;
+typedef struct Nfs3RMkdir Nfs3RMkdir;
+typedef struct Nfs3TSymlink Nfs3TSymlink;
+typedef struct Nfs3RSymlink Nfs3RSymlink;
+typedef struct Nfs3TMknod Nfs3TMknod;
+typedef struct Nfs3RMknod Nfs3RMknod;
+typedef struct Nfs3TRemove Nfs3TRemove;
+typedef struct Nfs3RRemove Nfs3RRemove;
+typedef struct Nfs3TRmdir Nfs3TRmdir;
+typedef struct Nfs3RRmdir Nfs3RRmdir;
+typedef struct Nfs3TRename Nfs3TRename;
+typedef struct Nfs3RRename Nfs3RRename;
+typedef struct Nfs3TLink Nfs3TLink;
+typedef struct Nfs3RLink Nfs3RLink;
+typedef struct Nfs3TReadDir Nfs3TReadDir;
+typedef struct Nfs3Entry Nfs3Entry;
+typedef struct Nfs3RReadDir Nfs3RReadDir;
+typedef struct Nfs3TReadDirPlus Nfs3TReadDirPlus;
+typedef struct Nfs3EntryPlus Nfs3EntryPlus;
+typedef struct Nfs3RReadDirPlus Nfs3RReadDirPlus;
+typedef struct Nfs3TFsStat Nfs3TFsStat;
+typedef struct Nfs3RFsStat Nfs3RFsStat;
+typedef struct Nfs3TFsInfo Nfs3TFsInfo;
+typedef struct Nfs3RFsInfo Nfs3RFsInfo;
+typedef struct Nfs3TPathconf Nfs3TPathconf;
+typedef struct Nfs3RPathconf Nfs3RPathconf;
+typedef struct Nfs3TCommit Nfs3TCommit;
+typedef struct Nfs3RCommit Nfs3RCommit;
+
+struct Nfs3Call {
+	SunRpc rpc;
+	Nfs3CallType type;
+};
+
+struct Nfs3Handle {
+	uchar h[Nfs3MaxHandleSize];
+	u32int len;
+};
+
+struct Nfs3Time {
+	u32int sec;
+	u32int nsec;
+};
+
+struct Nfs3Attr {
+	Nfs3FileType type;
+	u32int mode;
+	u32int nlink;
+	u32int uid;
+	u32int gid;
+	u64int size;
+	u64int used;
+	u32int major;
+	u32int minor;
+	u64int fsid;
+	u64int fileid;
+	Nfs3Time atime;
+	Nfs3Time mtime;
+	Nfs3Time ctime;
+};
+
+struct Nfs3WccAttr {
+	u64int size;
+	Nfs3Time mtime;
+	Nfs3Time ctime;
+};
+
+struct Nfs3Wcc {
+	u1int haveWccAttr;
+	Nfs3WccAttr wccAttr;
+	u1int haveAttr;
+	Nfs3Attr attr;
+};
+
+struct Nfs3SetAttr {
+	u1int setMode;
+	u32int mode;
+	u1int setUid;
+	u32int uid;
+	u1int setGid;
+	u32int gid;
+	u1int setSize;
+	u64int size;
+	Nfs3SetTime setAtime;
+	Nfs3Time atime;
+	Nfs3SetTime setMtime;
+	Nfs3Time mtime;
+};
+
+struct Nfs3TNull {
+	Nfs3Call call;
+};
+
+struct Nfs3RNull {
+	Nfs3Call call;
+};
+
+struct Nfs3TGetattr {
+	Nfs3Call call;
+	Nfs3Handle handle;
+};
+
+struct Nfs3RGetattr {
+	Nfs3Call call;
+	Nfs3Status status;
+	Nfs3Attr attr;
+};
+
+struct Nfs3TSetattr {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	Nfs3SetAttr attr;
+	u1int checkCtime;
+	Nfs3Time ctime;
+};
+
+struct Nfs3RSetattr {
+	Nfs3Call call;
+	Nfs3Status status;
+	Nfs3Wcc wcc;
+};
+
+struct Nfs3TLookup {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	char *name;
+};
+
+struct Nfs3RLookup {
+	Nfs3Call call;
+	Nfs3Status status;
+	Nfs3Handle handle;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	u1int haveDirAttr;
+	Nfs3Attr dirAttr;
+};
+
+struct Nfs3TAccess {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	u32int access;
+};
+
+struct Nfs3RAccess {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	u32int access;
+};
+
+struct Nfs3TReadlink {
+	Nfs3Call call;
+	Nfs3Handle handle;
+};
+
+struct Nfs3RReadlink {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	char *data;
+};
+
+struct Nfs3TRead {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	u64int offset;
+	u32int count;
+};
+
+struct Nfs3RRead {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	u32int count;
+	u1int eof;
+	uchar *data;
+	u32int ndata;
+};
+
+struct Nfs3TWrite {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	u64int offset;
+	u32int count;
+	Nfs3Sync stable;
+	uchar *data;
+	u32int ndata;
+};
+
+struct Nfs3RWrite {
+	Nfs3Call call;
+	Nfs3Status status;
+	Nfs3Wcc wcc;
+	u32int count;
+	Nfs3Sync committed;
+	uchar verf[Nfs3WriteVerfSize];
+};
+
+struct Nfs3TCreate {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	char *name;
+	Nfs3Create mode;
+	Nfs3SetAttr attr;
+	uchar verf[Nfs3CreateVerfSize];
+};
+
+struct Nfs3RCreate {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveHandle;
+	Nfs3Handle handle;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	Nfs3Wcc dirWcc;
+};
+
+struct Nfs3TMkdir {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	char *name;
+	Nfs3SetAttr attr;
+};
+
+struct Nfs3RMkdir {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveHandle;
+	Nfs3Handle handle;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	Nfs3Wcc dirWcc;
+};
+
+struct Nfs3TSymlink {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	char *name;
+	Nfs3SetAttr attr;
+	char *data;
+};
+
+struct Nfs3RSymlink {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveHandle;
+	Nfs3Handle handle;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	Nfs3Wcc dirWcc;
+};
+
+struct Nfs3TMknod {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	char *name;
+	Nfs3FileType type;
+	Nfs3SetAttr attr;
+	u32int major;
+	u32int minor;
+};
+
+struct Nfs3RMknod {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveHandle;
+	Nfs3Handle handle;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	Nfs3Wcc dirWcc;
+};
+
+struct Nfs3TRemove {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	char *name;
+};
+
+struct Nfs3RRemove {
+	Nfs3Call call;
+	Nfs3Status status;
+	Nfs3Wcc wcc;
+};
+
+struct Nfs3TRmdir {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	char *name;
+};
+
+struct Nfs3RRmdir {
+	Nfs3Call call;
+	Nfs3Status status;
+	Nfs3Wcc wcc;
+};
+
+struct Nfs3TRename {
+	Nfs3Call call;
+	struct {
+		Nfs3Handle handle;
+		char *name;
+	} from;
+	struct {
+		Nfs3Handle handle;
+		char *name;
+	} to;
+};
+
+struct Nfs3RRename {
+	Nfs3Call call;
+	Nfs3Status status;
+	Nfs3Wcc fromWcc;
+	Nfs3Wcc toWcc;
+};
+
+struct Nfs3TLink {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	struct {
+		Nfs3Handle handle;
+		char *name;
+	} link;
+};
+
+struct Nfs3RLink {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	Nfs3Wcc dirWcc;
+};
+
+struct Nfs3TReadDir {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	u64int cookie;
+	uchar verf[Nfs3CookieVerfSize];
+	u32int count;
+};
+
+struct Nfs3RReadDir {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	uchar verf[Nfs3CookieVerfSize];
+	uchar *data;
+	u32int count;
+	u1int eof;
+};
+
+struct Nfs3TReadDirPlus {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	u64int cookie;
+	uchar verf[Nfs3CookieVerfSize];
+	u32int dirCount;
+	u32int maxCount;
+};
+
+struct Nfs3Entry {
+	u64int fileid;
+	char *name;
+	u64int cookie;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	u1int haveHandle;
+	Nfs3Handle handle;
+};
+
+struct Nfs3RReadDirPlus {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	uchar verf[Nfs3CookieVerfSize];
+	uchar *data;
+	u32int count;
+	u1int eof;
+};
+
+struct Nfs3TFsStat {
+	Nfs3Call call;
+	Nfs3Handle handle;
+};
+
+struct Nfs3RFsStat {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	u64int totalBytes;
+	u64int freeBytes;
+	u64int availBytes;
+	u64int totalFiles;
+	u64int freeFiles;
+	u64int availFiles;
+	u32int invarSec;
+};
+
+struct Nfs3TFsInfo {
+	Nfs3Call call;
+	Nfs3Handle handle;
+};
+
+struct Nfs3RFsInfo {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	u32int readMax;
+	u32int readPref;
+	u32int readMult;
+	u32int writeMax;
+	u32int writePref;
+	u32int writeMult;
+	u32int readDirPref;
+	u64int maxFileSize;
+	Nfs3Time timePrec;
+	u32int flags;
+};
+
+struct Nfs3TPathconf {
+	Nfs3Call call;
+	Nfs3Handle handle;
+};
+
+struct Nfs3RPathconf {
+	Nfs3Call call;
+	Nfs3Status status;
+	u1int haveAttr;
+	Nfs3Attr attr;
+	u32int maxLink;
+	u32int maxName;
+	u1int noTrunc;
+	u1int chownRestricted;
+	u1int caseInsensitive;
+	u1int casePreserving;
+};
+
+struct Nfs3TCommit {
+	Nfs3Call call;
+	Nfs3Handle handle;
+	u64int offset;
+	u32int count;
+};
+
+struct Nfs3RCommit {
+	Nfs3Call call;
+	Nfs3Status status;
+	Nfs3Wcc wcc;
+	uchar verf[Nfs3WriteVerfSize];
+};
+
+char *nfs3StatusStr(Nfs3Status);
+char *nfs3TypeStr(Nfs3CallType);
+char *nfs3SetTimeStr(Nfs3SetTime);
+char *nfs3SyncStr(Nfs3Sync);
+
+void nfs3HandlePrint(Fmt*, Nfs3Handle*);
+u32int nfs3HandleSize(Nfs3Handle*);
+int nfs3HandlePack(uchar*, uchar*, uchar**, Nfs3Handle*);
+int nfs3HandleUnpack(uchar*, uchar*, uchar**, Nfs3Handle*);
+
+void nfs3TimePrint(Fmt*, Nfs3Time*);
+u32int nfs3TimeSize(Nfs3Time*);
+int nfs3TimePack(uchar*, uchar*, uchar**, Nfs3Time*);
+int nfs3TimeUnpack(uchar*, uchar*, uchar**, Nfs3Time*);
+
+void nfs3AttrPrint(Fmt*, Nfs3Attr*);
+u32int nfs3AttrSize(Nfs3Attr*);
+int nfs3AttrPack(uchar*, uchar*, uchar**, Nfs3Attr*);
+int nfs3AttrUnpack(uchar*, uchar*, uchar**, Nfs3Attr*);
+
+void nfs3WccAttrPrint(Fmt*, Nfs3WccAttr*);
+u32int nfs3WccAttrSize(Nfs3WccAttr*);
+int nfs3WccAttrPack(uchar*, uchar*, uchar**, Nfs3WccAttr*);
+int nfs3WccAttrUnpack(uchar*, uchar*, uchar**, Nfs3WccAttr*);
+
+void nfs3WccPrint(Fmt*, Nfs3Wcc*);
+u32int nfs3WccSize(Nfs3Wcc*);
+int nfs3WccPack(uchar*, uchar*, uchar**, Nfs3Wcc*);
+int nfs3WccUnpack(uchar*, uchar*, uchar**, Nfs3Wcc*);
+
+void nfs3SetAttrPrint(Fmt*, Nfs3SetAttr*);
+u32int nfs3SetAttrSize(Nfs3SetAttr*);
+int nfs3SetAttrPack(uchar*, uchar*, uchar**, Nfs3SetAttr*);
+int nfs3SetAttrUnpack(uchar*, uchar*, uchar**, Nfs3SetAttr*);
+
+extern SunProg nfs3Prog;
+
+void nfs3EntryPrint(Fmt*, Nfs3Entry*);
+u32int nfs3EntrySize(Nfs3Entry*);
+int nfs3EntryPack(uchar*, uchar*, uchar**, Nfs3Entry*);
+int nfs3EntryUnpack(uchar*, uchar*, uchar**, Nfs3Entry*);
+
+void nfs3EntryPlusPrint(Fmt*, Nfs3Entry*);
+u32int nfs3EntryPlusSize(Nfs3Entry*);
+int nfs3EntryPlusPack(uchar*, uchar*, uchar**, Nfs3Entry*);
+int nfs3EntryPlusUnpack(uchar*, uchar*, uchar**, Nfs3Entry*);
+
--- /dev/null
+++ b/sys/include/oventi.h
@@ -1,0 +1,271 @@
+#pragma	lib	"liboventi.a"
+#pragma	src	"/sys/src/liboventi"
+
+typedef struct VtSession	VtSession;
+typedef struct VtSha1		VtSha1;
+typedef struct Packet		Packet;
+typedef struct VtLock 		VtLock;
+typedef struct VtRendez		VtRendez;
+typedef struct VtRoot		VtRoot;
+typedef struct VtEntry		VtEntry;
+typedef struct VtServerVtbl	VtServerVtbl;
+
+#pragma incomplete VtSession
+#pragma incomplete VtSha1
+#pragma incomplete Packet
+#pragma incomplete VtLock
+#pragma incomplete VtRendez
+
+enum {
+	VtScoreSize	= 20, /* Venti */
+	VtMaxLumpSize	= 56*1024,
+	VtPointerDepth	= 7,	
+	VtEntrySize	= 40,
+	VtRootSize 	= 300,
+	VtMaxStringSize	= 1000,
+	VtAuthSize 	= 1024,  /* size of auth group - in bits - must be multiple of 8 */
+	MaxFragSize 	= 9*1024,
+	VtMaxFileSize	= (1ULL<<48) - 1,
+	VtRootVersion	= 2,
+};
+
+/* crypto strengths */
+enum {
+	VtCryptoStrengthNone,
+	VtCryptoStrengthAuth,
+	VtCryptoStrengthWeak,
+	VtCryptoStrengthStrong,
+};
+
+/* crypto suites */
+enum {
+	VtCryptoNone,
+	VtCryptoSSL3,
+	VtCryptoTLS1,
+
+	VtCryptoMax
+};
+
+/* codecs */
+enum {
+	VtCodecNone,
+
+	VtCodecDeflate,
+	VtCodecThwack,
+
+	VtCodecMax
+};
+
+/* Lump Types */
+enum {
+	VtErrType,		/* illegal */
+
+	VtRootType,
+	VtDirType,
+	VtPointerType0,
+	VtPointerType1,
+	VtPointerType2,
+	VtPointerType3,
+	VtPointerType4,
+	VtPointerType5,
+	VtPointerType6,
+	VtPointerType7,		/* not used */
+	VtPointerType8,		/* not used */
+	VtPointerType9,		/* not used */
+	VtDataType,
+
+	VtMaxType
+};
+
+/* Dir Entry flags */
+enum {
+	VtEntryActive = (1<<0),		/* entry is in use */
+	VtEntryDir = (1<<1),		/* a directory */
+	VtEntryDepthShift = 2,		/* shift for pointer depth */
+	VtEntryDepthMask = (0x7<<2),	/* mask for pointer depth */
+	VtEntryLocal = (1<<5),		/* used for local storage: should not be set for Venti blocks */
+	VtEntryNoArchive = (1<<6),	/* used for local storage: should not be set for Venti blocks */
+};
+
+struct VtRoot {
+	ushort version;
+	char name[128];
+	char type[128];
+	uchar score[VtScoreSize];	/* to a Dir block */
+	ushort blockSize;		/* maximum block size */
+	uchar prev[VtScoreSize];	/* last root block */
+};
+
+struct VtEntry {
+	ulong gen;			/* generation number */
+	ushort psize;			/* pointer block size */
+	ushort dsize;			/* data block size */
+	uchar depth;			/* unpacked from flags */
+	uchar flags;
+	uvlong size;
+	uchar score[VtScoreSize];
+};
+
+struct VtServerVtbl {
+	Packet *(*read)(VtSession*, uchar score[VtScoreSize], int type, int n);
+	int (*write)(VtSession*, uchar score[VtScoreSize], int type, Packet *p);
+	void (*closing)(VtSession*, int clean);
+	void (*sync)(VtSession*);
+};
+
+/* versions */
+enum {
+	/* experimental versions */
+	VtVersion01 = 1,
+	VtVersion02,
+};
+
+/* score of zero length block */
+extern uchar vtZeroScore[VtScoreSize];	
+
+/* both sides */
+void vtAttach(void);
+void vtDetach(void);
+void vtClose(VtSession *s);
+void vtFree(VtSession *s);
+char *vtGetUid(VtSession *s);
+char *vtGetSid(VtSession *s);
+int vtSetDebug(VtSession *s, int);
+int vtGetDebug(VtSession *s);
+int vtSetFd(VtSession *s, int fd);
+int vtGetFd(VtSession *s);
+int vtConnect(VtSession *s, char *password);
+int vtSetCryptoStrength(VtSession *s, int);
+int vtGetCryptoStrength(VtSession *s);
+int vtSetCompression(VtSession *s, int);
+int vtGetCompression(VtSession *s);
+int vtGetCrypto(VtSession *s);
+int vtGetCodec(VtSession *s);
+char *vtGetVersion(VtSession *s);
+char *vtGetError(void);
+int vtErrFmt(Fmt *fmt);
+void vtDebug(VtSession*, char *, ...);
+void vtDebugMesg(VtSession *z, Packet *p, char *s);
+
+/* internal */
+VtSession *vtAlloc(void);
+void vtReset(VtSession*);
+int vtAddString(Packet*, char*);
+int vtGetString(Packet*, char**);
+int vtSendPacket(VtSession*, Packet*);
+Packet *vtRecvPacket(VtSession*);
+void vtDisconnect(VtSession*, int);
+int vtHello(VtSession*);
+
+/* client side */
+VtSession *vtClientAlloc(void);
+VtSession *vtDial(char *server, int canfail);
+int vtRedial(VtSession*, char *server);
+VtSession *vtStdioServer(char *server);
+int vtPing(VtSession *s);
+int vtSetUid(VtSession*, char *uid);
+int vtRead(VtSession*, uchar score[VtScoreSize], int type, uchar *buf, int n);
+int vtWrite(VtSession*, uchar score[VtScoreSize], int type, uchar *buf, int n);
+Packet *vtReadPacket(VtSession*, uchar score[VtScoreSize], int type, int n);
+int vtWritePacket(VtSession*, uchar score[VtScoreSize], int type, Packet *p);
+int vtSync(VtSession *s);
+
+int vtZeroExtend(int type, uchar *buf, int n, int nn);
+int vtZeroTruncate(int type, uchar *buf, int n);
+int vtParseScore(char*, uint, uchar[VtScoreSize]);
+
+void vtRootPack(VtRoot*, uchar*);
+int vtRootUnpack(VtRoot*, uchar*);
+void vtEntryPack(VtEntry*, uchar*, int index);
+int vtEntryUnpack(VtEntry*, uchar*, int index);
+
+/* server side */
+VtSession *vtServerAlloc(VtServerVtbl*);
+int vtSetSid(VtSession *s, char *sid);
+int vtExport(VtSession *s);
+
+/* sha1 */
+VtSha1* vtSha1Alloc(void);
+void vtSha1Free(VtSha1*);
+void vtSha1Init(VtSha1*);
+void vtSha1Update(VtSha1*, uchar *, int n);
+void vtSha1Final(VtSha1*, uchar sha1[VtScoreSize]);
+void vtSha1(uchar score[VtScoreSize], uchar *, int);
+int vtSha1Check(uchar score[VtScoreSize], uchar *, int);
+int vtScoreFmt(Fmt *fmt);
+
+/* Packet */
+Packet *packetAlloc(void);
+void packetFree(Packet*);
+Packet *packetForeign(uchar *buf, int n, void (*free)(void *a), void *a);
+Packet *packetDup(Packet*, int offset, int n);
+Packet *packetSplit(Packet*, int n);
+int packetConsume(Packet*, uchar *buf, int n);
+int packetTrim(Packet*, int offset, int n);
+uchar *packetHeader(Packet*, int n);
+uchar *packetTrailer(Packet*, int n);
+int packetPrefix(Packet*, uchar *buf, int n);
+int packetAppend(Packet*, uchar *buf, int n);
+int packetConcat(Packet*, Packet*);
+uchar *packetPeek(Packet*, uchar *buf, int offset, int n);
+int packetCopy(Packet*, uchar *buf, int offset, int n);
+int packetFragments(Packet*, IOchunk*, int nio, int offset);
+int packetSize(Packet*);
+int packetAllocatedSize(Packet*);
+void packetSha1(Packet*, uchar sha1[VtScoreSize]);
+int packetCompact(Packet*);
+int packetCmp(Packet*, Packet*);
+void packetStats(void);
+
+/* portability stuff - should be a seperate library */
+
+void vtMemFree(void *);
+void *vtMemAlloc(int);
+void *vtMemAllocZ(int);
+void *vtMemRealloc(void *p, int);
+void *vtMemBrk(int n);
+char *vtStrDup(char *);
+void vtFatal(char *, ...);
+char *vtGetError(void);
+char *vtSetError(char *, ...);
+char *vtOSError(void);
+
+/* locking/threads */
+int vtThread(void (*f)(void*), void *rock);
+void vtThreadSetName(char*);
+
+VtLock *vtLockAlloc(void);
+/* void vtLockInit(VtLock**); */
+void vtLock(VtLock*);
+int vtCanLock(VtLock*);
+void vtRLock(VtLock*);
+int vtCanRLock(VtLock*);
+void vtUnlock(VtLock*);
+void vtRUnlock(VtLock*);
+void vtLockFree(VtLock*);
+
+VtRendez *vtRendezAlloc(VtLock*);
+void vtRendezFree(VtRendez*);
+int vtSleep(VtRendez*);
+int vtWakeup(VtRendez*);
+int vtWakeupAll(VtRendez*);
+
+/* fd functions - really network (socket) functions */
+void vtFdClose(int);
+int vtFdRead(int, uchar*, int);
+int vtFdReadFully(int, uchar*, int);
+int vtFdWrite(int, uchar*, int);
+
+/*
+ * formatting
+ * other than noted, these formats all ignore
+ * the width and precision arguments, and all flags
+ *
+ * V	a venti score
+ * R	venti error
+ */
+#pragma	varargck	type	"V"		uchar*
+#pragma	varargck	type	"R"		void
+
+#pragma	varargck	argpos	vtSetError	1
+
--- /dev/null
+++ b/sys/include/plumb.h
@@ -1,0 +1,49 @@
+#pragma	lib	"libplumb.a"
+#pragma	src	"/sys/src/libplumb"
+
+/*
+ * Message format:
+ *	source application\n
+ *	destination port\n
+ *	working directory\n
+ *	type\n
+ *	attributes\n
+ *	nbytes\n
+ *	n bytes of data
+ */
+
+typedef struct Plumbattr Plumbattr;
+typedef struct Plumbmsg Plumbmsg;
+
+struct Plumbmsg
+{
+	char		*src;
+	char		*dst;
+	char		*wdir;
+	char		*type;
+	Plumbattr	*attr;
+	int		ndata;
+	char		*data;
+};
+
+struct Plumbattr
+{
+	char		*name;
+	char		*value;
+	Plumbattr	*next;
+};
+
+int			plumbsend(int, Plumbmsg*);
+int			plumbsendtext(int, char*, char*, char*, char*);
+Plumbmsg*	plumbrecv(int);
+char*		plumbpack(Plumbmsg*, int*);
+Plumbmsg*	plumbunpack(char*, int);
+Plumbmsg*	plumbunpackpartial(char*, int, int*);
+char*		plumbpackattr(Plumbattr*);
+Plumbattr*	plumbunpackattr(char*);
+Plumbattr*	plumbaddattr(Plumbattr*, Plumbattr*);
+Plumbattr*	plumbdelattr(Plumbattr*, char*);
+void			plumbfree(Plumbmsg*);
+char*		plumblookup(Plumbattr*, char*);
+int			plumbopen(char*, int);
+int			eplumb(int, char*);
--- /dev/null
+++ b/sys/include/pool.h
@@ -1,0 +1,54 @@
+typedef struct Pool Pool;
+struct Pool {
+	char*	name;
+	ulong	maxsize;
+
+	ulong	cursize;
+	ulong	curfree;
+	ulong	curalloc;
+
+	ulong	minarena;	/* smallest size of new arena */
+	ulong	quantum;	/* allocated blocks should be multiple of */
+	ulong	minblock;	/* smallest newly allocated block */
+
+	void*	freeroot;	/* actually Free* */
+	void*	arenalist;	/* actually Arena* */
+
+	void*	(*alloc)(ulong);
+	int	(*merge)(void*, void*);
+	void	(*move)(void* from, void* to);
+
+	int	flags;
+	int	nfree;
+	int	lastcompact;
+
+	void	(*lock)(Pool*);
+	void	(*unlock)(Pool*);
+	void	(*print)(Pool*, char*, ...);
+	void	(*panic)(Pool*, char*, ...);
+	void	(*logstack)(Pool*);
+
+	void*	private;
+};
+
+extern void*	poolalloc(Pool*, ulong);
+extern void*	poolallocalign(Pool*, ulong, ulong, long, ulong);
+extern void	poolfree(Pool*, void*);
+extern ulong	poolmsize(Pool*, void*);
+extern void*	poolrealloc(Pool*, void*, ulong);
+extern void	poolcheck(Pool*);
+extern int	poolcompact(Pool*);
+extern void	poolblockcheck(Pool*, void*);
+
+extern Pool*	mainmem;
+extern Pool*	imagmem;
+
+enum {	/* flags */
+	POOL_ANTAGONISM	= 1<<0,
+	POOL_PARANOIA	= 1<<1,
+	POOL_VERBOSITY	= 1<<2,
+	POOL_DEBUGGING	= 1<<3,
+	POOL_LOGGING	= 1<<4,
+	POOL_TOLERANCE	= 1<<5,
+	POOL_NOREUSE	= 1<<6,
+};
--- /dev/null
+++ b/sys/include/rdbg.h
@@ -1,0 +1,10 @@
+/* Remote kernel debug protocol */
+enum
+{
+	Terr='0',
+	Rerr,
+	Tmget,
+	Rmget,
+	Tmput,
+	Rmput,
+};
--- /dev/null
+++ b/sys/include/regexp.h
@@ -1,0 +1,66 @@
+#pragma	src	"/sys/src/libregexp"
+#pragma	lib	"libregexp.a"
+
+typedef struct Resub		Resub;
+typedef struct Reclass		Reclass;
+typedef struct Reinst		Reinst;
+typedef struct Reprog		Reprog;
+
+/*
+ *	Sub expression matches
+ */
+struct Resub{
+	union
+	{
+		char *sp;
+		Rune *rsp;
+	};
+	union
+	{
+		char *ep;
+		Rune *rep;
+	};
+};
+
+/*
+ *	character class, each pair of rune's defines a range
+ */
+struct Reclass{
+	Rune	*end;
+	Rune	spans[64];
+};
+
+/*
+ *	Machine instructions
+ */
+struct Reinst{
+	int	type;
+	union	{
+		Reclass	*cp;		/* class pointer */
+		Rune	r;		/* character */
+		int	subid;		/* sub-expression id for RBRA and LBRA */
+		Reinst	*right;		/* right child of OR */
+	};
+	union {	/* regexp relies on these two being in the same union */
+		Reinst *left;		/* left child of OR */
+		Reinst *next;		/* next instruction for CAT & LBRA */
+	};
+};
+
+/*
+ *	Reprogram definition
+ */
+struct Reprog{
+	Reinst	*startinst;	/* start pc */
+	Reclass	class[16];	/* .data */
+	Reinst	firstinst[5];	/* .text */
+};
+
+extern Reprog	*regcomp(char*);
+extern Reprog	*regcomplit(char*);
+extern Reprog	*regcompnl(char*);
+extern void	regerror(char*);
+extern int	regexec(Reprog*, char*, Resub*, int);
+extern void	regsub(char*, char*, int, Resub*, int);
+extern int	rregexec(Reprog*, Rune*, Resub*, int);
+extern void	rregsub(Rune*, Rune*, int, Resub*, int);
--- /dev/null
+++ b/sys/include/scribble.h
@@ -1,0 +1,39 @@
+#pragma src "/sys/src/libscribble"
+#pragma lib "libscribble.a"
+
+#pragma incomplete struct graffiti
+
+typedef struct Scribble Scribble;
+typedef struct graffiti Graffiti;
+
+typedef struct pen_point {
+	Point;
+	long	chaincode;
+} pen_point;
+
+typedef struct Stroke {
+	uint			npts;	/*Number of pen_point in array.*/
+	pen_point*	pts;	/*Array of points.*/
+} Stroke;
+
+#define CS_LETTERS     0
+#define CS_DIGITS      1
+#define CS_PUNCTUATION 2
+
+struct Scribble {
+	/* private state */
+	Point		*pt;
+	int			ppasize;
+	Stroke	    	ps;
+	Graffiti	*graf;
+	int			capsLock;
+	int			puncShift;
+	int			tmpShift;
+	int			ctrlShift;
+	int			curCharSet;
+};
+
+Rune		recognize(Scribble *);
+Scribble *	scribblealloc(void);
+
+extern int ScribbleDebug;
--- /dev/null
+++ b/sys/include/stdio.h
@@ -1,0 +1,118 @@
+#pragma	src	"/sys/src/libstdio"
+#pragma	lib	"libstdio.a"
+
+/*
+ * pANS astdio.h
+ */
+/*
+ * According to X3J11, there is only one i/o buffer
+ * and it must not be occupied by both input and output data.
+ *	If rp<wp, we must have state==RD and
+ *	if wp<rp, we must have state==WR, so that getc and putc work correctly.
+ *	On open, rp, wp and buf are set to 0, so first getc or putc will call _IO_getc
+ *	or _IO_putc, which will allocate the buffer.
+ *	If setvbuf(., ., _IONBF, .) is called, bufl is set to 0 and
+ *	buf, rp and wp are pointed at unbuf.
+ *	If setvbuf(., ., _IOLBF, .) is called, _IO_putc leaves wp and rp pointed at the
+ *	end of the buffer so that it can be called on each putc to check whether it's got
+ *	a newline.  This nonsense is in order to avoid impacting performance of the other
+ *	buffering modes more than necessary -- putting the test in putc adds many
+ *	instructions that are wasted in non-_IOLBF mode:
+ *	#define putc(c, f)	(_IO_ctmp=(c),\
+ *				(f)->wp>=(f)->rp || (f)->flags&LINEBUF && _IO_ctmp=='\n'\
+ *					?_IO_putc(_IO_ctmp, f)\
+ *					:*(f)->wp++=_IO_ctmp)
+ *				
+ */
+typedef struct{
+	int fd;		/* UNIX file pointer */
+	char flags;	/* bits for must free buffer on close, line-buffered */
+	char state;	/* last operation was read, write, position, error, eof */
+	char *buf;	/* pointer to i/o buffer */
+	char *rp;	/* read pointer (or write end-of-buffer) */
+	char *wp;	/* write pointer (or read end-of-buffer) */
+	char *lp;	/* actual write pointer used when line-buffering */
+	long bufl;	/* actual length of buffer */
+	char unbuf[1];	/* tiny buffer for unbuffered io (used for ungetc?) */
+}FILE;
+typedef long fpos_t;
+#ifndef NULL
+#define	NULL	((void*)0)
+#endif
+/*
+ * Third arg of setvbuf
+ */
+#define	_IOFBF	1			/* block-buffered */
+#define	_IOLBF	2			/* line-buffered */
+#define	_IONBF	3			/* unbuffered */
+#define	BUFSIZ	4096			/* size of setbuf buffer */
+#define	EOF	(-1)			/* returned on end of file */
+#define	FOPEN_MAX	100		/* max files open */
+#define	FILENAME_MAX	BUFSIZ		/* silly filename length */
+#define	L_tmpnam	20		/* sizeof "/tmp/abcdefghij9999 */
+#ifndef SEEK_SET			/* also defined in unistd.h */
+#define	SEEK_CUR	1
+#define	SEEK_END	2
+#define	SEEK_SET	0
+#endif
+#define	TMP_MAX		64		/* very hard to set correctly */
+#define	stderr	(&_IO_stream[2])
+#define	stdin	(&_IO_stream[0])
+#define	stdout	(&_IO_stream[1])
+#define	_IO_CHMASK	0377		/* mask for 8 bit characters */
+FILE *tmpfile(void);
+char *tmpnam(char *);
+int fclose(FILE *);
+int fflush(FILE *);
+FILE *fopen(const char *, const char *);
+FILE *fdopen(const int, const char *);
+FILE *freopen(const char *, const char *, FILE *);
+void setbuf(FILE *, char *);
+int setvbuf(FILE *, char *, int, long);
+int fprintf(FILE *, const char *, ...);
+int fscanf(FILE *, const char *, ...);
+int printf(const char *, ...);
+int scanf(const char *, ...);
+int sprintf(char *, const char *, ...);
+int snprintf(char *, int, const char *, ...);
+int sscanf(const char *, const char *, ...);
+int vfprintf(FILE *, const char *, va_list);
+int vprintf(const char *, va_list);
+int vsprintf(char *, const char *, va_list);
+int vsnprintf(char *, int, const char *, va_list);
+int vfscanf(FILE *, const char *, va_list);
+int fgetc(FILE *);
+char *fgets(char *, int, FILE *);
+int fputc(int, FILE *);
+int fputs(const char *, FILE *);
+int getc(FILE *);
+#define	getc(f)	((f)->rp>=(f)->wp?_IO_getc(f):*(f)->rp++&_IO_CHMASK)
+int _IO_getc(FILE *f);
+int getchar(void);
+#define	getchar()	getc(stdin)
+char *gets(char *);
+int putc(int, FILE *);
+#define	putc(c, f) ((f)->wp>=(f)->rp?_IO_putc(c, f):(*(f)->wp++=c)&_IO_CHMASK)
+int _IO_putc(int, FILE *);
+int putchar(int);
+#define	putchar(c)	putc(c, stdout)
+int puts(const char *);
+int ungetc(int, FILE *);
+long fread(void *, long, long, FILE *);
+long fwrite(const void *, long, long, FILE *);
+int fgetpos(FILE *, fpos_t *);
+int fseek(FILE *, long, int);
+int fseeko(FILE *, long long, int);
+int fsetpos(FILE *, const fpos_t *);
+long ftell(FILE *);
+long long ftello(FILE *);
+void rewind(FILE *);
+void clearerr(FILE *);
+int feof(FILE *);
+int ferror(FILE *);
+void perror(const char *);
+extern FILE _IO_stream[FOPEN_MAX];
+FILE *sopenr(const char *);
+FILE *sopenw(void);
+char *sclose(FILE *);
+int fileno(FILE *);
--- /dev/null
+++ b/sys/include/sunrpc.h
@@ -1,0 +1,396 @@
+/*
+ * Sun RPC; see RFC 1057
+ */
+
+#pragma lib "libsunrpc.a"
+#pragma src "/sys/src/libsunrpc"
+
+typedef uchar u1int;
+
+typedef struct SunAuthInfo SunAuthInfo;
+typedef struct SunAuthUnix SunAuthUnix;
+typedef struct SunRpc SunRpc;
+typedef struct SunCall SunCall;
+
+enum
+{
+	/* Authinfo.flavor */
+	SunAuthNone = 0,
+	SunAuthSys,
+	SunAuthShort,
+	SunAuthDes,
+};
+
+typedef enum {
+	SunAcceptError = 0x10000,
+	SunRejectError = 0x20000,
+	SunAuthError = 0x40000,
+
+	/* Reply.status */
+	SunSuccess = 0,
+
+	SunProgUnavail = SunAcceptError | 1,
+	SunProgMismatch,
+	SunProcUnavail,
+	SunGarbageArgs,
+	SunSystemErr,
+
+	SunRpcMismatch = SunRejectError | 0,
+
+	SunAuthBadCred = SunAuthError | 1,
+	SunAuthRejectedCred,
+	SunAuthBadVerf,
+	SunAuthRejectedVerf,
+	SunAuthTooWeak,
+	SunAuthInvalidResp,
+	SunAuthFailed,
+} SunStatus;
+
+struct SunAuthInfo
+{
+	uint flavor;
+	uchar *data;
+	uint ndata;
+};
+
+struct SunAuthUnix
+{
+	u32int stamp;
+	char *sysname;
+	u32int uid;
+	u32int gid;
+	u32int g[16];
+	u32int ng;
+};
+
+struct SunRpc
+{
+	u32int xid;
+	uint iscall;
+
+	/*
+	 * only sent on wire in call
+	 * caller fills in for the reply unpackers.
+	 */
+	u32int proc;
+
+	/* call */
+	// uint proc;
+	u32int prog, vers;
+	SunAuthInfo cred;
+	SunAuthInfo verf;
+	uchar *data;
+	uint ndata;
+
+	/* reply */
+	u32int status;
+	// SunAuthInfo verf;
+	u32int low, high;
+	// uchar *data;
+	// uint ndata;
+};
+
+typedef enum
+{
+	SunCallTypeTNull,
+	SunCallTypeRNull,
+} SunCallType;
+
+struct SunCall
+{
+	SunRpc rpc;
+	SunCallType type;
+};
+
+void sunErrstr(SunStatus);
+
+void sunRpcPrint(Fmt*, SunRpc*);
+uint sunRpcSize(SunRpc*);
+SunStatus sunRpcPack(uchar*, uchar*, uchar**, SunRpc*);
+SunStatus sunRpcUnpack(uchar*, uchar*, uchar**, SunRpc*);
+
+void sunAuthInfoPrint(Fmt*, SunAuthInfo*);
+uint sunAuthInfoSize(SunAuthInfo*);
+int sunAuthInfoPack(uchar*, uchar*, uchar**, SunAuthInfo*);
+int sunAuthInfoUnpack(uchar*, uchar*, uchar**, SunAuthInfo*);
+
+void sunAuthUnixPrint(Fmt*, SunAuthUnix*);
+uint sunAuthUnixSize(SunAuthUnix*);
+int sunAuthUnixPack(uchar*, uchar*, uchar**, SunAuthUnix*);
+int sunAuthUnixUnpack(uchar*, uchar*, uchar**, SunAuthUnix*);
+
+int sunEnumPack(uchar*, uchar*, uchar**, int*);
+int sunEnumUnpack(uchar*, uchar*, uchar**, int*);
+int sunUint1Pack(uchar*, uchar*, uchar**, u1int*);
+int sunUint1Unpack(uchar*, uchar*, uchar**, u1int*);
+
+int sunStringPack(uchar*, uchar*, uchar**, char**, u32int);
+int sunStringUnpack(uchar*, uchar*, uchar**, char**, u32int);
+uint sunStringSize(char*);
+
+int sunUint32Pack(uchar*, uchar*, uchar**, u32int*);
+int sunUint32Unpack(uchar*, uchar*, uchar**, u32int*);
+int sunUint64Pack(uchar*, uchar*, uchar**, u64int*);
+int sunUint64Unpack(uchar*, uchar*, uchar**, u64int*);
+
+int sunVarOpaquePack(uchar*, uchar*, uchar**, uchar**, u32int*, u32int);
+int sunVarOpaqueUnpack(uchar*, uchar*, uchar**, uchar**, u32int*, u32int);
+uint sunVarOpaqueSize(u32int);
+
+int sunFixedOpaquePack(uchar*, uchar*, uchar**, uchar*, u32int);
+int sunFixedOpaqueUnpack(uchar*, uchar*, uchar**, uchar*, u32int);
+uint sunFixedOpaqueSize(u32int);
+
+/*
+ * Sun RPC Program
+ */
+typedef struct SunProc SunProc;
+typedef struct SunProg SunProg;
+struct SunProg
+{
+	uint prog;
+	uint vers;
+	SunProc *proc;
+	int nproc;
+};
+
+struct SunProc
+{
+	int (*pack)(uchar*, uchar*, uchar**, SunCall*);
+	int (*unpack)(uchar*, uchar*, uchar**, SunCall*);
+	uint (*size)(SunCall*);
+	void (*fmt)(Fmt*, SunCall*);
+	uint sizeoftype;
+};
+
+SunStatus sunCallPack(SunProg*, uchar*, uchar*, uchar**, SunCall*);
+SunStatus sunCallUnpack(SunProg*, uchar*, uchar*, uchar**, SunCall*);
+SunStatus sunCallUnpackAlloc(SunProg*, SunCallType, uchar*, uchar*, uchar**, SunCall**);
+uint sunCallSize(SunProg*, SunCall*);
+void sunCallSetup(SunCall*, SunProg*, uint);
+
+/*
+ * Formatting
+ */
+#pragma varargck type "B" SunRpc*
+#pragma varargck type "C" SunCall*
+
+int	sunRpcFmt(Fmt*);
+int	sunCallFmt(Fmt*);
+void	sunFmtInstall(SunProg*);
+
+
+/*
+ * Sun RPC Server
+ */
+typedef struct SunMsg SunMsg;
+typedef struct SunSrv SunSrv;
+
+enum
+{
+	SunStackSize = 8192,
+};
+
+struct SunMsg
+{
+	uchar *data;
+	int count;
+	SunSrv *srv;
+	SunRpc rpc;
+	SunProg *pg;
+	SunCall *call;
+	Channel *creply;	/* chan(SunMsg*) */
+};
+
+struct SunSrv
+{
+	int chatty;
+	int cacheReplies;
+	int alwaysReject;
+	SunProg **map;
+	Channel *crequest;
+
+/* implementation use only */
+	Channel **cdispatch;
+	SunProg **prog;
+	int nprog;
+	void *cache;
+	Channel *creply;
+	Channel *cthread;
+};
+
+SunSrv *sunSrv(void);
+
+void	sunSrvProg(SunSrv *srv, SunProg *prog, Channel *c);
+int	sunSrvAnnounce(SunSrv *srv, char *address);
+int	sunSrvUdp(SunSrv *srv, char *address);
+int	sunSrvNet(SunSrv *srv, char *address);
+int	sunSrvFd(SunSrv *srv, int fd);
+void	sunSrvThreadCreate(SunSrv *srv, void (*fn)(void*), void*);
+void	sunSrvClose(SunSrv*);
+
+int	sunMsgReply(SunMsg*, SunCall*);
+int	sunMsgDrop(SunMsg*);
+int	sunMsgReplyError(SunMsg*, SunStatus);
+
+/*
+ * Sun RPC Client
+ */
+typedef struct SunClient SunClient;
+
+struct SunClient
+{
+	int		fd;
+	int		chatty;
+	int		needcount;
+	ulong	maxwait;
+	ulong	xidgen;
+	int		nsend;
+	int		nresend;
+	struct {
+		ulong min;
+		ulong max;
+		ulong avg;
+	} rtt;
+	Channel	*dying;
+	Channel	*rpcchan;
+	Channel	*timerchan;
+	Channel	*flushchan;
+	Channel	*readchan;
+	SunProg	**prog;
+	int		nprog;
+	int 		timertid;
+	int 		nettid;
+};
+
+SunClient	*sunDial(char*);
+
+int	sunClientRpc(SunClient*, ulong, SunCall*, SunCall*, uchar**);
+void	sunClientClose(SunClient*);
+void	sunClientFlushRpc(SunClient*, ulong);
+void	sunClientProg(SunClient*, SunProg*);
+
+
+/*
+ * Provided by callers.
+ * Should remove dependence on this, but hard.
+ */
+void	*emalloc(ulong);
+void *erealloc(void*, ulong);
+
+
+/*
+ * Sun RPC port mapper; see RFC 1057 Appendix A
+ */
+
+typedef struct PortMap PortMap;
+typedef struct PortTNull PortTNull;
+typedef struct PortRNull PortRNull;
+typedef struct PortTSet PortTSet;
+typedef struct PortRSet PortRSet;
+typedef struct PortTUnset PortTUnset;
+typedef struct PortRUnset PortRUnset;
+typedef struct PortTGetport PortTGetport;
+typedef struct PortRGetport PortRGetport;
+typedef struct PortTDump PortTDump;
+typedef struct PortRDump PortRDump;
+typedef struct PortTCallit PortTCallit;
+typedef struct PortRCallit PortRCallit;
+
+typedef enum
+{
+	PortCallTNull,
+	PortCallRNull,
+	PortCallTSet,
+	PortCallRSet,
+	PortCallTUnset,
+	PortCallRUnset,
+	PortCallTGetport,
+	PortCallRGetport,
+	PortCallTDump,
+	PortCallRDump,
+	PortCallTCallit,
+	PortCallRCallit,
+} PortCallType;
+
+enum
+{
+	PortProgram	= 100000,
+	PortVersion	= 2,
+
+	PortProtoTcp	= 6,	/* protocol number for TCP/IP */
+	PortProtoUdp	= 17	/* protocol number for UDP/IP */
+};
+
+struct PortMap {
+	u32int prog;
+	u32int vers;
+	u32int prot;
+	u32int port;
+};
+
+struct PortTNull {
+	SunCall call;
+};
+
+struct PortRNull {
+	SunCall call;
+};
+
+struct PortTSet {
+	SunCall call;
+	PortMap map;
+};
+
+struct PortRSet {
+	SunCall call;
+	u1int b;
+};
+
+struct PortTUnset {
+	SunCall call;
+	PortMap map;
+};
+
+struct PortRUnset {
+	SunCall call;
+	u1int b;
+};
+
+struct PortTGetport {
+	SunCall call;
+	PortMap map;
+};
+
+struct PortRGetport {
+	SunCall call;
+	u32int port;
+};
+
+struct PortTDump {
+	SunCall call;
+};
+
+struct PortRDump {
+	SunCall call;
+	PortMap *map;
+	int nmap;
+};
+
+struct PortTCallit {
+	SunCall call;
+	u32int prog;
+	u32int vers;
+	u32int proc;
+	uchar *data;
+	u32int count;
+};
+
+struct PortRCallit {
+	SunCall call;
+	u32int port;
+	uchar *data;
+	u32int count;
+};
+
+extern SunProg portProg;
--- /dev/null
+++ b/sys/include/thread.h
@@ -1,0 +1,133 @@
+#pragma src "/sys/src/libthread"
+#pragma lib "libthread.a"
+
+#pragma	varargck	argpos	chanprint	2
+
+typedef struct Alt	Alt;
+typedef struct Channel	Channel;
+typedef struct Ref	Ref;
+
+/*
+ * Channel structure.  S is the size of the buffer.  For unbuffered channels
+ * s is zero.  v is an array of s values.  If s is zero, v is unused.
+ * f and n represent the state of the queue pointed to by v.
+ */
+
+enum {
+	Nqwds = 2,
+	Nqshift = 5,		/* log₂ # of bits in long */
+	Nqmask =  -1,
+	Nqbits = (1 << Nqshift) * 2,
+};
+
+struct Channel {
+	int	s;		/* Size of the channel (may be zero) */
+	uint	f;		/* Extraction point (insertion pt: (f+n) % s) */
+	uint	n;		/* Number of values in the channel */
+	int	e;		/* Element size */
+	int	freed;		/* Set when channel is being deleted */
+	volatile Alt **qentry;	/* Receivers/senders waiting (malloc) */
+	volatile int nentry;	/* # of entries malloc-ed */
+	volatile int closed;	/* channel is closed */
+	uchar	v[1];		/* Array of s values in the channel */
+};
+
+
+/* Channel operations for alt: */
+typedef enum {
+	CHANEND,
+	CHANSND,
+	CHANRCV,
+	CHANNOP,
+	CHANNOBLK,
+} ChanOp;
+
+struct Alt {
+	Channel	*c;		/* channel */
+	void	*v;		/* pointer to value */
+	ChanOp	op;		/* operation */
+	char	*err;		/* did the op fail? */
+	/*
+	 * the next variables are used internally to alt
+	 * they need not be initialized
+	 */
+	Channel	**tag;		/* pointer to rendez-vous tag */
+	int	entryno;	/* entry number */
+};
+
+struct Ref {
+	long	ref;
+};
+
+int	alt(Alt alts[]);
+int	chanclose(Channel*);
+int	chanclosing(Channel *c);
+Channel*chancreate(int elemsize, int bufsize);
+int	chaninit(Channel *c, int elemsize, int elemcnt);
+void	chanfree(Channel *c);
+int	chanprint(Channel *, char *, ...);
+long	decref(Ref *r);			/* returns 0 iff value is now zero */
+void	incref(Ref *r);
+int	nbrecv(Channel *c, void *v);
+void*	nbrecvp(Channel *c);
+ulong	nbrecvul(Channel *c);
+int	nbsend(Channel *c, void *v);
+int	nbsendp(Channel *c, void *v);
+int	nbsendul(Channel *c, ulong v);
+void	needstack(int);
+int	proccreate(void (*f)(void *arg), void *arg, uint stacksize);
+int	procrfork(void (*f)(void *arg), void *arg, uint stacksize, int flag);
+void**	procdata(void);
+void	procexec(Channel *, char *, char *[]);
+void	procexecl(Channel *, char *, ...);
+int	recv(Channel *c, void *v);
+void*	recvp(Channel *c);
+ulong	recvul(Channel *c);
+int	send(Channel *c, void *v);
+int	sendp(Channel *c, void *v);
+int	sendul(Channel *c, ulong v);
+int	threadcreate(void (*f)(void *arg), void *arg, uint stacksize);
+void**	threaddata(void);
+void	threadexits(char *);
+void	threadexitsall(char *);
+int	threadgetgrp(void);	/* return thread group of current thread */
+char*	threadgetname(void);
+void	threadint(int);		/* interrupt thread */
+void	threadintgrp(int);	/* interrupt threads in grp */
+void	threadkill(int);	/* kill thread */
+void	threadkillgrp(int);	/* kill threads in group */
+void	threadmain(int argc, char *argv[]);
+void	threadnonotes(void);
+int	threadnotify(int (*f)(void*, char*), int in);
+int	threadid(void);
+int	threadpid(int);
+int	threadsetgrp(int);		/* set thread group, return old */
+void	threadsetname(char *fmt, ...);
+Channel*threadwaitchan(void);
+int	tprivalloc(void);
+void	tprivfree(int);
+void	**tprivaddr(int);
+void	yield(void);
+
+extern	int	mainstacksize;
+
+/* slave I/O processes */
+typedef struct Ioproc Ioproc;
+
+#pragma incomplete Ioproc
+
+
+Ioproc*	ioproc(void);
+void	closeioproc(Ioproc*);
+void	iointerrupt(Ioproc*);
+
+int	ioclose(Ioproc*, int);
+int	iodial(Ioproc*, char*, char*, char*, int*);
+int	ioopen(Ioproc*, char*, int);
+long	ioread(Ioproc*, int, void*, long);
+long	ioreadn(Ioproc*, int, void*, long);
+long	iowrite(Ioproc*, int, void*, long);
+int	iosleep(Ioproc*, long);
+
+long	iocall(Ioproc*, long (*)(va_list*), ...);
+void	ioret(Ioproc*, int);
--- /dev/null
+++ b/sys/include/tos.h
@@ -1,0 +1,24 @@
+typedef struct Tos Tos;
+typedef struct Plink Plink;
+
+#pragma incomplete Plink
+
+struct Tos {
+	struct			/* Per process profiling */
+	{
+		Plink	*pp;	/* known to be 0(ptr) */
+		Plink	*next;	/* known to be 4(ptr) */
+		Plink	*last;
+		Plink	*first;
+		ulong	pid;
+		ulong	what;
+	} prof;
+	uvlong	cyclefreq;	/* cycle clock frequency if there is one, 0 otherwise */
+	vlong	kcycles;	/* cycles spent in kernel */
+	vlong	pcycles;	/* cycles spent in process (kernel + user) */
+	ulong	pid;		/* might as well put the pid here */
+	ulong	clock;
+	/* top of stack is here */
+};
+
+extern Tos *_tos;
--- /dev/null
+++ b/sys/include/trace.h
@@ -1,0 +1,24 @@
+typedef enum Tevent {
+	SAdmit = 0,	/* Edf admit */
+	SRelease,	/* Edf release, waiting to be scheduled */
+	SEdf,		/* running under EDF */
+	SRun,		/* running best effort */
+	SReady,		/* runnable but not running  */
+	SSleep,		/* blocked */
+	SYield,		/* blocked waiting for release */
+	SSlice,		/* slice exhausted */
+	SDeadline,	/* proc's deadline */
+	SExpel,		/* Edf expel */
+	SDead,		/* proc dies */
+	SInts,		/* Interrupt start */
+	SInte,		/* Interrupt end */
+	SUser,		/* user event */
+	Nevent,
+} Tevent;
+
+typedef struct Traceevent	Traceevent;
+struct Traceevent {
+	ulong	pid;	
+	ulong	etype;	/* Event type */
+	vlong	time;	/* time stamp  */
+};
--- /dev/null
+++ b/sys/include/venti.h
@@ -1,0 +1,496 @@
+#pragma lib "libventi.a"
+#pragma src "/sys/src/libventi"
+
+
+/* XXX should be own library? */
+/*
+ * Packets
+ */
+enum
+{
+	MaxFragSize = 9*1024
+};
+
+typedef struct Packet Packet;
+#pragma incomplete Packet
+
+Packet*	packetalloc(void);
+void	packetappend(Packet*, uchar *buf, int n);
+uint	packetasize(Packet*);
+int	packetcmp(Packet*, Packet*);
+int	packetcompact(Packet*);
+void	packetconcat(Packet*, Packet*);
+int	packetconsume(Packet*, uchar *buf, int n);
+int	packetcopy(Packet*, uchar *buf, int offset, int n);
+Packet*	packetdup(Packet*, int offset, int n);
+Packet*	packetforeign(uchar *buf, int n, void (*free)(void *a), void *a);
+int	packetfragments(Packet*, IOchunk*, int nio, int offset);
+void	packetfree(Packet*);
+uchar*	packetheader(Packet*, int n);
+uchar*	packetpeek(Packet*, uchar *buf, int offset, int n);
+void	packetprefix(Packet*, uchar *buf, int n);
+void	packetsha1(Packet*, uchar sha1[20]);
+uint	packetsize(Packet*);
+Packet*	packetsplit(Packet*, int n);
+void	packetstats(void);
+uchar*	packettrailer(Packet*, int n);
+int	packettrim(Packet*, int offset, int n);
+
+/* XXX should be own library? */
+/*
+ * Logging
+ */
+typedef struct VtLog VtLog;
+typedef struct VtLogChunk VtLogChunk;
+
+struct VtLog
+{
+	VtLog	*next;		/* in hash table */
+	char	*name;
+	VtLogChunk *chunk;
+	uint	nchunk;
+	VtLogChunk *w;
+	QLock	lk;
+	int	ref;
+};
+
+struct VtLogChunk
+{
+	char	*p;
+	char	*ep;
+	char	*wp;
+};
+
+VtLog*	vtlogopen(char *name, uint size);
+void	vtlogprint(VtLog *log, char *fmt, ...);
+void	vtlog(char *name, char *fmt, ...);
+void	vtlogclose(VtLog*);
+void	vtlogremove(char *name);
+char**	vtlognames(int*);
+void	vtlogdump(int fd, VtLog*);
+
+/* XXX begin actual venti.h */
+
+typedef struct VtFcall VtFcall;
+typedef struct VtConn VtConn;
+typedef struct VtEntry VtEntry;
+typedef struct VtRoot VtRoot;
+
+/*
+ * Fundamental constants.
+ */
+enum
+{
+	VtScoreSize	= 20,
+	VtMaxStringSize = 1024,
+	VtMaxLumpSize	= 56*1024,
+	VtPointerDepth	= 7
+};
+#define VtMaxFileSize ((1ULL<<48)-1)
+
+
+/* 
+ * Strings in packets.
+ */
+int vtputstring(Packet*, char*);
+int vtgetstring(Packet*, char**);
+
+/*
+ * Block types.
+ * 
+ * The initial Venti protocol had a much
+ * less regular list of block types.
+ * VtToDiskType converts from new to old.
+ */
+enum
+{
+	VtDataType	= 0<<3,
+	/* VtDataType+1, ... */
+	VtDirType	= 1<<3,
+	/* VtDirType+1, ... */
+	VtRootType	= 2<<3,
+	VtMaxType,
+	VtCorruptType = 0xFF,
+
+	VtTypeDepthMask = 7,
+	VtTypeBaseMask = ~VtTypeDepthMask
+};
+
+/* convert to/from on-disk type numbers */
+uint vttodisktype(uint);
+uint vtfromdisktype(uint);
+
+/*
+ * VtEntry describes a Venti stream
+ *
+ * The _ enums are only used on the wire.
+ * They are not present in the VtEntry structure
+ * and should not be used by client programs.
+ * (The info is in the type field.)
+ */
+enum
+{
+	VtEntryActive = 1<<0,		/* entry is in use */
+	_VtEntryDir = 1<<1,		/* a directory */
+	_VtEntryDepthShift = 2,		/* shift for pointer depth */
+	_VtEntryDepthMask = 7<<2,	/* mask for pointer depth */
+	VtEntryLocal = 1<<5		/* for local storage only */
+};
+enum
+{
+	VtEntrySize = 40
+};
+struct VtEntry
+{
+	ulong	gen;			/* generation number */
+	ushort	psize;			/* pointer block size */
+	ushort	dsize;			/* data block size */
+	uchar	type;
+	uchar	flags;
+	uvlong	size;
+	uchar	score[VtScoreSize];
+};
+
+void vtentrypack(VtEntry*, uchar*, int index);
+int vtentryunpack(VtEntry*, uchar*, int index);
+
+struct VtRoot
+{
+	char	name[128];
+	char	type[128];
+	uchar	score[VtScoreSize];	/* to a Dir block */
+	ushort	blocksize;		/* maximum block size */
+	uchar	prev[VtScoreSize];	/* last root block */
+};
+
+enum
+{
+	VtRootSize = 300,
+	VtRootVersion = 2
+};
+
+void vtrootpack(VtRoot*, uchar*);
+int vtrootunpack(VtRoot*, uchar*);
+
+/*
+ * score of zero length block
+ */
+extern uchar vtzeroscore[VtScoreSize];
+
+/*
+ * zero extend and truncate blocks
+ */
+void vtzeroextend(int type, uchar *buf, uint n, uint nn);
+uint vtzerotruncate(int type, uchar *buf, uint n);
+
+/*
+ * parse score: mungs s
+ */
+int vtparsescore(char *s, char **prefix, uchar[VtScoreSize]);
+
+/*
+ * formatting
+ * other than noted, these formats all ignore
+ * the width and precision arguments, and all flags
+ *
+ * V	a venti score
+ */
+#pragma	varargck	type	"V"	uchar*
+#pragma	varargck	type	"F"	VtFcall*
+#pragma	varargck	type	"T"	void
+#pragma	varargck	type	"lT"	void
+
+int vtscorefmt(Fmt*);
+
+/*
+ * error-checking malloc et al.
+ */
+void	vtfree(void *);
+void*	vtmalloc(int);
+void*	vtmallocz(int);
+void*	vtrealloc(void *p, int);
+void*	vtbrk(int n);
+char*	vtstrdup(char *);
+
+/*
+ * Venti protocol
+ */
+
+/*
+ * Crypto strengths
+ */
+enum
+{
+	VtCryptoStrengthNone,
+	VtCryptoStrengthAuth,
+	VtCryptoStrengthWeak,
+	VtCryptoStrengthStrong
+};
+
+/*
+ * Crypto suites
+ */
+enum
+{
+	VtCryptoNone,
+	VtCryptoSSL3,
+	VtCryptoTLS1,
+	VtCryptoMax
+};
+
+/* 
+ * Codecs
+ */
+enum
+{
+	VtCodecNone,
+	VtCodecDeflate,
+	VtCodecThwack,
+	VtCodecMax
+};
+
+enum
+{
+	VtRerror	= 1,
+	VtTping		= 2,
+	VtRping,
+	VtThello	= 4,
+	VtRhello,
+	VtTgoodbye	= 6,
+	VtRgoodbye,	/* not used */
+	VtTauth0	= 8,
+	VtRauth0,
+	VtTauth1	= 10,
+	VtRauth1,
+	VtTread		= 12,
+	VtRread,
+	VtTwrite	= 14,
+	VtRwrite,
+	VtTsync		= 16,
+	VtRsync,
+
+	VtTmax
+};
+
+struct VtFcall
+{
+	uchar	msgtype;
+	uchar	tag;
+
+	char	*error;		/* Rerror */
+
+	char	*version;	/* Thello */
+	char	*uid;		/* Thello */
+	uchar	strength;	/* Thello */
+	uchar	*crypto;	/* Thello */
+	uint	ncrypto;	/* Thello */
+	uchar	*codec;		/* Thello */
+	uint	ncodec;		/* Thello */
+	char	*sid;		/* Rhello */
+	uchar	rcrypto;	/* Rhello */
+	uchar	rcodec;		/* Rhello */
+	uchar	*auth;		/* TauthX, RauthX */
+	uint	nauth;		/* TauthX, RauthX */
+	uchar	score[VtScoreSize];	/* Tread, Rwrite */
+	uchar	blocktype;	/* Tread, Twrite */
+	ushort	count;		/* Tread */
+	Packet	*data;		/* Rread, Twrite */
+};
+
+Packet*	vtfcallpack(VtFcall*);
+int	vtfcallunpack(VtFcall*, Packet*);
+void	vtfcallclear(VtFcall*);
+int	vtfcallfmt(Fmt*);
+
+enum
+{
+	VtStateAlloc,
+	VtStateConnected,
+	VtStateClosed
+};
+
+struct VtConn
+{
+	QLock	lk;
+	QLock	inlk;
+	QLock	outlk;
+	int	debug;
+	int	infd;
+	int	outfd;
+	int	muxer;
+	void	*writeq;
+	void	*readq;
+	int	state;
+	void	*wait[256];
+	uint	ntag;
+	uint	nsleep;
+	Packet	*part;
+	Rendez	tagrend;
+	Rendez	rpcfork;
+	char	*version;
+	char	*uid;
+	char	*sid;
+	char	addr[256];	/* address of other side */
+};
+
+VtConn*	vtconn(int infd, int outfd);
+VtConn*	vtdial(char*);
+void	vtfreeconn(VtConn*);
+int	vtsend(VtConn*, Packet*);
+Packet*	vtrecv(VtConn*);
+int	vtversion(VtConn* z);
+void	vtdebug(VtConn* z, char*, ...);
+void	vthangup(VtConn* z);
+int	vtgoodbye(VtConn* z);
+
+/* #pragma varargck argpos vtdebug 2 */
+
+/* server */
+typedef struct VtSrv VtSrv;
+#pragma incomplete VtSrv
+typedef struct VtReq VtReq;
+struct VtReq
+{
+	VtFcall	tx;
+	VtFcall	rx;
+/* private */
+	VtSrv	*srv;
+	void	*sc;
+};
+
+int	vtsrvhello(VtConn*);
+VtSrv*	vtlisten(char *addr);
+VtReq*	vtgetreq(VtSrv*);
+void	vtrespond(VtReq*);
+
+/* client */
+Packet*	vtrpc(VtConn*, Packet*);
+Packet*	_vtrpc(VtConn*, Packet*, VtFcall*);
+void	vtrecvproc(void*);	/* VtConn */
+void	vtsendproc(void*);	/* VtConn */
+
+int	vtconnect(VtConn*);
+int	vthello(VtConn*);
+int	vtread(VtConn*, uchar score[VtScoreSize], uint type, uchar *buf, int n);
+int	vtwrite(VtConn*, uchar score[VtScoreSize], uint type, uchar *buf, int n);
+Packet*	vtreadpacket(VtConn*, uchar score[VtScoreSize], uint type, int n);
+int	vtwritepacket(VtConn*, uchar score[VtScoreSize], uint type, Packet *p);
+int	vtsync(VtConn*);
+int	vtping(VtConn*);
+
+/*
+ * Data blocks and block cache.
+ */
+enum
+{
+	NilBlock = ~0
+};
+
+typedef struct VtBlock VtBlock;
+typedef struct VtCache VtCache;
+#pragma incomplete VtCache
+
+struct VtBlock
+{
+	VtCache	*c;
+	QLock	lk;
+
+	uchar	*data;
+	uchar	score[VtScoreSize];
+	uchar	type;			/* BtXXX */
+
+	/* internal to cache */
+	int	nlock;
+	int	iostate;
+	int	ref;
+	u32int	heap;
+	VtBlock	*next;
+	VtBlock	**prev;
+	u32int	used;
+	u32int	used2;
+	u32int	addr;
+	uintptr	pc;
+};
+
+u32int	vtglobaltolocal(uchar[VtScoreSize]);
+void	vtlocaltoglobal(u32int, uchar[VtScoreSize]);
+
+VtCache*vtcachealloc(VtConn*, int blocksize, ulong nblocks);
+void	vtcachefree(VtCache*);
+VtBlock*vtcachelocal(VtCache*, u32int addr, int type);
+VtBlock*vtcacheglobal(VtCache*, uchar[VtScoreSize], int type);
+VtBlock*vtcacheallocblock(VtCache*, int type);
+void	vtcachesetwrite(VtCache*,
+	int(*)(VtConn*, uchar[VtScoreSize], uint, uchar*, int));
+void	vtblockput(VtBlock*);
+u32int	vtcacheblocksize(VtCache*);
+int	vtblockwrite(VtBlock*);
+VtBlock*vtblockcopy(VtBlock*);
+void	vtblockduplock(VtBlock*);
+
+extern int vtcachencopy, vtcachenread, vtcachenwrite;
+extern int vttracelevel;
+
+/*
+ * Hash tree file tree.
+ */
+typedef struct VtFile VtFile;
+struct VtFile
+{
+	QLock	lk;
+	int	ref;
+	int	local;
+	VtBlock	*b;			/* block containing this file */
+	uchar	score[VtScoreSize];	/* score of block containing this file */
+
+/* immutable */
+	VtCache	*c;
+	int	mode;
+	u32int	gen;
+	int	dsize;
+	int	psize;
+	int	dir;
+	VtFile	*parent;
+	int	epb;			/* entries per block in parent */
+	u32int	offset; 		/* entry offset in parent */
+};
+
+enum
+{
+	VtOREAD,
+	VtOWRITE,
+	VtORDWR
+};
+
+VtBlock*vtfileblock(VtFile*, u32int, int mode);
+int	vtfileblockscore(VtFile*, u32int, uchar[VtScoreSize]);
+void	vtfileclose(VtFile*);
+VtFile*	_vtfilecreate(VtFile*, int offset, int psize, int dsize, int dir);
+VtFile*	vtfilecreate(VtFile*, int psize, int dsize, int dir);
+VtFile*	vtfilecreateroot(VtCache*, int psize, int dsize, int type);
+int	vtfileflush(VtFile*);
+int	vtfileflushbefore(VtFile*, u64int);
+u32int	vtfilegetdirsize(VtFile*);
+int	vtfilegetentry(VtFile*, VtEntry*);
+uvlong	vtfilegetsize(VtFile*);
+void	vtfileincref(VtFile*);
+int	vtfilelock2(VtFile*, VtFile*, int);
+int	vtfilelock(VtFile*, int);
+VtFile*	vtfileopen(VtFile*, u32int, int);
+VtFile*	vtfileopenroot(VtCache*, VtEntry*);
+long	vtfileread(VtFile*, void*, long, vlong);
+int	vtfileremove(VtFile*);
+int	vtfilesetdirsize(VtFile*, u32int);
+int	vtfilesetentry(VtFile*, VtEntry*);
+int	vtfilesetsize(VtFile*, u64int);
+int	vtfiletruncate(VtFile*);
+void	vtfileunlock(VtFile*);
+long	vtfilewrite(VtFile*, void*, long, vlong);
+
+int	vttimefmt(Fmt*);
+
+extern int chattyventi;
+extern int ventidoublechecksha1;
+extern int ventilogging;
+
+extern char *VtServerLog;