Subject: Re: Generic DMA interface and bus_dma()
To: None <mjacob@feral.com>
From: Jason Thorpe <thorpej@nas.nasa.gov>
List: tech-kern
Date: 08/11/1997 11:27:51
On Mon, 11 Aug 1997 08:32:21 -0700 
 Matthew Jacob <mjacob@feral.com> wrote:

 > I have an old version of it- but I would assume he's updated it since
 > my last copy.

Yes, I have.  The final version is attached below.  Perry said he was
going to nroff it, but he apparently hasn't had time yet.


$Id: busdma.doc,v 1.28 1997/06/06 19:28:55 thorpej Exp $

Copyright (c) 1996, 1997 The NetBSD Foundation, Inc.
All rights reserved.

This code is derived from software contributed to The NetBSD Foundation
by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
NASA Ames Research Center.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
	This product includes software developed by the NetBSD
	Foundation, Inc. and its contributors.
4. Neither the name of The NetBSD Foundation nor the names of its
   contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.



PURPOSE
-------

The purpose of this document is to describe a bus- and machine-independent
DMA mapping interface.


All data structures, function prototypes, and macros will be defined
by the port-specific header <machine/bus.h>.  Note that this document
assumes the existence of types already defined by the current "bus.h"
interface.


Unless otherwise noted, all function calls in this interface may be
defined as CPP macros.



DATA TYPES
----------

Individual implementations may name these structures whatever they
wish, providing that the external representations are:

	bus_dma_tag_t		A machine-dependent opaque type
				describing the implementation of
				DMA for a given bus.

	bus_dma_segment_t	A structure with at least the following
				members:

			bus_addr_t	ds_addr;
			bus_size_t	ds_len;

				The structure may have machine-dependent
				members and arbitrary layout.  The values
				in "ds_addr" and "ds_len" are suitable for
				programming into DMA controller address
				and length registers.

	bus_dmamap_t		A pointer to a structure with at least the
				following members:

			bus_dma_segment_t *dm_segs;
			int	dm_nsegs;

				The structure may have machine-dependent
				members and arbitrary layout.  The "dm_segs"
				member may be an array of segments or
				a pointer to an array of segments.  The
				"dm_nsegs" member indicates the number
				of segments in "dm_segs".  A value of 0
				indicates the mapping is invalid.

	bus_dmasync_op_t	An enumerated type providing the following
				unique values:

		BUS_DMASYNC_PREREAD
		BUS_DMASYNC_POSTREAD
		BUS_DMASYNC_PREWRITE
		BUS_DMASYNC_POSTWRITE

				See bus_dmamap_sync() for more details.




FUNCTIONS
---------

int	bus_dmamap_create __P((bus_dma_tag_t tag, bus_size_t size,
	    int nsegments, bus_size_t maxsegsz, bus_size_t boundary,
	    int flags, bus_dmamap_t *dmamp));

	bus_dmamap_create() allocates a dma handle and initializes
	it according to the paramters provided.  Arguments are
	as follows:

	tag		This is the bus_dma_tag_t passed down from the
			parent driver via <bus>_attach_args.

	size		This is the maximum DMA transfer that can
			be mapped by the handle.

	nsegments	Number of segments the device can support
			in a single DMA transaction.  This may
			be the number of scatter-gather descriptors
			supported by the device.

	maxsegsz	The maximum number of bytes that may be
			transfered by any given DMA segment.

	boundary	Some DMA controllers are not able to transfer
			data that crosses a particular boundary.  This
			argument allows this boundary to be specified.
			The boundary lines begin at 0, and occur every
			"boundary" bytes.  Mappings may begin on a
			boundary line but may not end on or cross a
			boundary line.  If no boundary condition needs
			to be observed, an "boundary" arguement of 0
			should be used.

	flags		Flags are defined as follows:

		BUS_DMA_WAITOK		It is safe to wait (sleep)
					for resouces during this call.

		BUS_DMA_NOWAIT		It is not safe to wait (sleep)
					for resources during this call.

		BUS_DMA_ALLOCNOW	Perform any resource allocation
					this handle may need now.
					If this is not specified, the
					allocation may be deferred to
					bus_dmamap_load().  If this flag
					is specified, bus_dmamap_load()
					will not block on resource
					allocation.

		BUS_DMA_BUS[1-4]	These flags are placeholders,
					and may be used by busses to
					provide bus-dependent functionality.

	dmamp		This is a pointer to a bus_dmamap_t.
			A dma map will be allocated and pointed to by
			*dmamp upon sucessful completion of this routine.

	Behavior is not defined if invalid arguments are passed to
	bus_dmamap_create().

	RETURN VALUES

	Returns 0 on success or an error code to indicate mode of failure.



void	bus_dmamap_destroy __P((bus_dma_tag_t tag, bus_dmamap_t dmam));

	bus_dmamap_destroy() frees all resources associated with a
	given dma handle.  Arguments are as follows:

	tag		This is the bus_dma_tag_t passed down from the
			parent driver via <bus>_attach_args.

	dmam		The dma handle to destroy.

	In the event that the dma handle contains a valid mapping,
	the mapping will be unloaded via the same mechanism used
	by bus_dmamap_unload().

	Behavior is not defined if invalid arguments are passed
	to bus_dmamap_destroy().

	RETURN VALUES

	If given valid arguments, bus_dmamap_destroy() always suceeds.



int	bus_dmamap_load __P((bus_dma_tag_t tag, bus_dmamap_t dmam,
	    void *buf, bus_size_t buflen, struct proc *p, int flags));

	bus_dmamap_load() loads a dma handle with mappings for a
	DMA transfer.  bus_dmamap_load() assumes that all pages
	involved in a DMA transfer are wired.

	Arguments are as follows:

	tag		This is the bus_dma_tag_t passed down from the
			parent driver via <bus>_attach_args.

	dmam		The dma handle with which to map the
			transfer.

	buf		The buffer to be used for the DMA transfer.

	buflen		The size of the buffer.

	p		Used to indicate the address space in which
			the buffer is located.  If NULL, the buffer is
			assumed to be in kernel space.  Otherwise, the
			buffer is assumed to be in process "p"'s address
			space.

	flags		Flags are defined as follows:

		BUS_DMA_WAITOK		It is safe to wait (sleep)
					for resources during this call.

		BUS_DMA_NOWAIT		It is not safe to wait (sleep)
					for resources during this call.

		BUS_DMA_BUS[1-4]	These flags are placeholders,
					and may be used by busses to
					provide bus-dependent functionality.

	As noted above, if a dma handle is created with
	BUS_DMA_ALLOCNOW, bus_dmamap_load() will never block.

	If a call to bus_dmamap_load() fails, the mapping in
	the dma handle will be invalid.  It is the responsibility
	of the caller to clean up any inconsistent device state
	resulting from incomplete iteration through the uio.

	Behavior is not defined if invalid arguments are passed to
	bus_dmamap_load().

	RETURN VALUES

	Returns 0 on success or an error code to indicate mode of failure.



int	bus_dmamap_load_mbuf __P((bus_dma_tag_t tag, bus_dmamap_t dmam,
	    struct mbuf *chain, int flags));

	This is a variation of bus_dmamap_load() which maps mbuf chains
	for DMA transfers.  mbuf chains are assumed to be in kernel
	virtual address space.



int	bus_dmamap_load_uio __P((bus_dma_tag_t tag, bus_dmamap_t dmam,
	    struct uio *uio, int flags));

	This is a variation of bus_dmamap_load() which maps buffers
	pointed to be "uio" for DMA transfers.  The value of
	"uio->uio_segflg" will determine if the buffers are in user
	or kernel virtual address space.  If the buffers are in user
	address space, the buffers are assumed to be in "uio->uio_procp"'s
	address space.



int	bus_dmamap_load_raw __P((bus_dma_tag_t tag, bus_dmamap_t dmam,
	    bus_dma_segment_t *segs, int nsegs, bus_size_t size,
	    int flags));

	This is a variation of bus_dmamap_load() which maps buffers
	allocated by bus_dmamem_alloc() (see below).  The "segs"
	argument is an array of bus_dma_segment_t's filled in
	by bus_dmamem_alloc().  The "nsegs" arguement is the
	number of segments in the array.  The "size" argument
	is the size of the DMA transfer.



void	bus_dmamap_unload __P((bus_dma_tag_t tag, bus_dmamap_t dmam));

	bus_dmamap_unload() deletes the mappings for a given
	dma handle.  Arguments are as follows:

	tag		This is the bus_dma_tag_t passed down from the
			parent driver via <bus>_attach_args.

	dmam		The dma handle containing the mappings
			which are to be deleted.

	If the dma handle was created with BUS_DMA_ALLOCNOW,
	bus_dmamap_unload() will not free the corresponding
	resources which were allocated by bus_dmamap_create().
	This is to ensure that bus_dmamap_load() will never block
	on resources if the handle was created with BUS_DMA_ALLOCNOW.

	Behavior is not defined if invalid arguments are passed to
	bus_dmamap_unload().

	RETURN VALUES

	If given valid arguments, bus_dmamap_unload() always suceeds.



void	bus_dmamap_sync __P((bus_dma_tag_t tag, bus_dmamap_t dmam,
	    bus_dmasync_op_t op));

	bus_dmamap_sync() performs pre- and post-DMA operation
	cache and/or buffer synchronization.  Arguments are as follows:

	tag		This is the bus_dma_tag_t passed down from the
			parent driver via <bus>_attach_args.

	dmam		The DMA mapping to be synchronized.

	op		The synchronization operation to perform.

	The following DMA synchronization operations are defined:

	BUS_DMASYNC_PREREAD		Perform any pre-read DMA cache
					and/or bounce operations.

	BUS_DMASYNC_POSTREAD		Perform any post-read DMA cache
					and/or bounce operations.

	BUS_DMASYNC_PREWRITE		Perform any pre-write DMA cache
					and/or bounce operations.

	BUS_DMASYNC_POSTWRITE		Perform any post-write DMA cache
					and/or bounce operations.

	This function exists so that multiple read and write transfers
	can be performed with the same buffer, and so that drivers can
	explicitly inform the bus DMA code when their data is 'ready'
	in its DMA buffer.

	An example of multiple read-write use of a single mapping
	might look like:

	bus_dmamap_load(...);

	while (not done) {
		/* invalidate soon-to-be-stale cache blocks */
		bus_dmamap_sync(..., BUS_DMASYNC_PREREAD);

		[ do read DMA ]

		/* copy from bounce */
		bus_dmamap_sync(..., BUS_DMASYNC_POSTREAD);

		/* read data now in driver-provided buffer */

		[ computation ]

		/* data to be written now in driver-provided buffer */

		/* flush write buffers and writeback, copy to bounce */
		bus_dmamap_sync(..., BUS_DMASYNC_PREWRITE);

		[ do write DMA ]

		/* probably a no-op, but provided for consistency */
		bus_dmamap_sync(..., BUS_DMASYNC_POSTWRITE);
	}

	bus_dmamap_unload(...);


	If DMA read and write operations are not preceeded and followed
	by the apropriate synchronization operations, behavior is
	undefined.

	Behavior is not defined if invalid arguments are passed to
	bus_dmamap_sync().

	RETURN VALUES

	If given valid arguments, bus_dmamap_sync() always succeeds.



int	bus_dmamem_alloc __P((bus_dma_tag_t tag, bus_size_t size,
	    bus_size_t alignment, bus_size_t boundary,
	    bus_dma_segment_t *segs, int nsegs, int *rsegs, int flags));

	bus_dmamem_alloc() allocates memory that is "DMA safe"
	for the bus corresponding to the given tag.  The mapping
	of this memory is machine-dependent (or "opaque"); machine-
	independent code is not to assume that the addresses returned
	are valid in kernel virtual address space, or that the addresses
	returned are system physical addresses.

	Allocations will always be rounded to the hardware page size.
	Callers may wish to take advantage of this, and cluster allocation
	of small data structures.

	Arguments are as follows:

	tag		The is the bus_dma_tag_t passed down from the
			parent driver via <bus>_attach_args.

	size		The amount of memory to allocate.

	alignment	Each segment in the allocated memory will be
			aligned to this value.  If the alignment is
			less than a hardware page size, it will be
			rounded up to the hardware page size.  This
			value must be a power of two.

	boundary	Each segment in the allocated memory must not
			cross this boundary (relative to zero).  This
			value must be a power of two.  A boundary value
			less than the size of the allocation is invalid.

	segs		An array of bus_dma_segment_t's, filled in
			as memory is allocated, representing the
			opaque addresses of the memory chunks.

	nsegs		Specifies the number of segments in "segs", and
			this the maximum number of segments that the
			allocated memory may map to.

	rsegs		Used to return the actual number of segments
			the memory is composed of.

	flags		Flags are defined as follows:

		BUS_DMA_WAITOK		It is safe to wait (sleep)
					for resources during this call.

		BUS_DMA_NOWAIT		It is not safe to wait (sleep)
					for resources during this call.

		BUS_DMA_BUS[1-4]	These flags are placeholders,
					and may be used by busses to
					provide bus-dependent functionality.

	All pages allocated by bus_dmamem_alloc() will be wired down
	until they are freed by bus_dmamem_free().

	Behavior is undefined if invalid arguments are passed to
	bus_dmamem_alloc().

	RETURN VALUES

	Returns 0 on success or an error code indicating mode of
	failure.



void	bus_dmamem_free __P((bus_dma_tag_t tag, bus_dma_segment_t *segs,
	    int nsegs));

	bus_dmamem_free() and frees memory previously allocated
	by bus_dmamem_alloc().  Any mappings will be invalidated.
	Arguements are as follows:

	tag		This is the bus_dma_tag_t passed down from the
			parent driver via <bus>_attach_args.

	segs		The array of bus_dma_segment_t's filled in
			by bus_dmamem_alloc().

	nsegs		The number of segments in "segs".

	Behavior is undefined if invalid arguments are passed to
	bus_dmamem_free().

	RETURN VALUES

	If given valid arguments, bus_dmamem_free() always succeeds.



int	bus_dmamem_map __P((bus_dma_tag_t tag, bus_dma_segment_t *segs,
	    int nsegs, size_t size, caddr_t *kvap, flags));

	bus_dmamem_map() maps memory allocated with bus_dmamem_alloc()
	into kernel virtual address space.  Arguements are as follows:

	tag		This is the bus_dma_tag_t passed down from the
			parent driver via <bus>_attach_args.

	segs		The array of bus_dma_segment_t's filled in
			by bus_dmamem_alloc(), representing the
			memory regions to map.

	nsegs		The number of segments in "segs".

	size		The size of the mapping.

	kvap		Filled in to specifiy the kernel virtual address
			where the memory is mapped.

	flags		Flags are defined as follows:

		BUS_DMA_WAITOK		It is safe to wait (sleep)
					for resources during this call.

		BUS_DMA_NOWAIT		It is not safe to wait (sleep)
					for resources during this call.

		BUS_DMA_BUS[1-4]	These flags are placeholders,
					and may be used by busses to
					provide bus-dependent functionality.

		BUS_DMAMEM_NOSYNC	Map the memory in such a way that
					synchronization of the map
					with bus_dmamap_sync() will not
					be required.  This is especially
					useful in the case of descriptor
					blocks which are occasionally
					read/written by the device and
					host as a means of command/status
					communications, for which map
					synchronization would be unecessarily
					expensive.  This flag should be
					used with care.

	Behavior is undefined if invalid arguements are passed to
	bus_dmamem_map().

	RETURN VALUES

	Returns 0 on success or an error code indicating mode of
	failure.



void	bus_dmamem_unmap __P((bus_dma_tag_t tag, caddr_t kva,
	    size_t size));

	bus_dmamem_unmap() unmaps memory previously mapped with
	bus_dmamem_map(), freeing the kernel virtual address
	space used by the mapping.  The arguments are as follows:

	tag		This is the bus_dma_tag_t passed down from the
			parent driver via <bus>_attach_args.

	kva		The kernel virtual address of the mapped
			memory.

	size		The size of the mapping.

	Behavior is undefined if invalid arguements are passed to
	bus_dmamem_unmap().

	RETURN VALUES

	If given valid arguments, bus_dmamem_unmap() always succeeds.



int	bus_dmamem_mmap __P((bus_dma_tag_t tag, bus_dma_segment_t *segs,
	    int nsegs, int off, int prot, int flags));

	bus_dmamem_mmap() provides support for user mmap(2)'ing of
	DMA-safe memory.  This function is to be called by a device
	driver's (*d_mmap)() entry point, which is called by the
	device pager for each page to be mapped.  The arguements are
	as follows:

	tag		This is the bus_dma_tag_t passed down from the
			parent driver via <bus>_attach_args.

	segs		The array of bus_dma_segment_t's filled in
			by bus_dmamem_alloc(), representing the
			memory to me mmap(2)'ed.

	nsegs		The number of elements in the "segs" array.

	off		The offset of the page in DMA memory which
			is to be mapped.

	prot		The protection codes for the mapping.

	flags		Flags are defined as follows:

		BUS_DMA_WAITOK		It is safe to wait (sleep)
					for resources during this call.

		BUS_DMA_NOWAIT		It is not safe to wait (sleep)
					for resources during this call.

		BUS_DMA_BUS[1-4]	These flags are placeholders,
					and may be used by busses to
					provide bus-dependent functionality.

		BUS_DMAMEM_NOSYNC	Map the memory in such a way that
					synchronization of the map
					with bus_dmamap_sync() will not
					be required.  This is especially
					useful in the case of descriptor
					blocks which are occasionally
					read/written by the device and
					host as a means of command/status
					communications, for which map
					synchronization would be unecessarily
					expensive.  This flag should be
					used with care.

	Behavior is undefined if invalid arguments are passed
	to bus_dmamem_mmap().

	RETURN VALUES

	Returns -1 to indicate failure.  Otherwise, returns an opaque
	value to be interpreted by the device pager.