xref: /netbsd-src/sys/dev/usb/usb_mem.c (revision 8ecbf5f02b752fcb7debe1a8fab1dc82602bc760)
1 /*	$NetBSD: usb_mem.c,v 1.77 2020/05/15 06:26:44 skrll Exp $	*/
2 
3 /*
4  * Copyright (c) 1998 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Lennart Augustsson (lennart@augustsson.net) at
9  * Carlstedt Research & Technology.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * USB DMA memory allocation.
35  * We need to allocate a lot of small (many 8 byte, some larger)
36  * memory blocks that can be used for DMA.  Using the bus_dma
37  * routines directly would incur large overheads in space and time.
38  */
39 
40 #include <sys/cdefs.h>
41 __KERNEL_RCSID(0, "$NetBSD: usb_mem.c,v 1.77 2020/05/15 06:26:44 skrll Exp $");
42 
43 #ifdef _KERNEL_OPT
44 #include "opt_usb.h"
45 #endif
46 
47 #include <sys/param.h>
48 #include <sys/bus.h>
49 #include <sys/cpu.h>
50 #include <sys/device.h>		/* for usbdivar.h */
51 #include <sys/kernel.h>
52 #include <sys/kmem.h>
53 #include <sys/once.h>
54 #include <sys/queue.h>
55 #include <sys/systm.h>
56 
57 #include <dev/usb/usb.h>
58 #include <dev/usb/usbdi.h>
59 #include <dev/usb/usbdivar.h>	/* just for usb_dma_t */
60 #include <dev/usb/usbhist.h>
61 #include <dev/usb/usb_mem.h>
62 
63 #define	DPRINTF(FMT,A,B,C,D)	USBHIST_LOG(usbdebug,FMT,A,B,C,D)
64 #define	DPRINTFN(N,FMT,A,B,C,D)	USBHIST_LOGN(usbdebug,N,FMT,A,B,C,D)
65 
66 #define USB_MEM_SMALL roundup(64, CACHE_LINE_SIZE)
67 #define USB_MEM_CHUNKS 64
68 #define USB_MEM_BLOCK (USB_MEM_SMALL * USB_MEM_CHUNKS)
69 
70 /* This struct is overlayed on free fragments. */
71 struct usb_frag_dma {
72 	usb_dma_block_t		*ufd_block;
73 	u_int			ufd_offs;
74 	LIST_ENTRY(usb_frag_dma) ufd_next;
75 };
76 
77 Static usbd_status	usb_block_allocmem(bus_dma_tag_t, size_t, size_t,
78 			    u_int, usb_dma_block_t **);
79 Static void		usb_block_freemem(usb_dma_block_t *);
80 
81 LIST_HEAD(usb_dma_block_qh, usb_dma_block);
82 Static struct usb_dma_block_qh usb_blk_freelist =
83 	LIST_HEAD_INITIALIZER(usb_blk_freelist);
84 kmutex_t usb_blk_lock;
85 
86 #ifdef DEBUG
87 Static struct usb_dma_block_qh usb_blk_fraglist =
88 	LIST_HEAD_INITIALIZER(usb_blk_fraglist);
89 Static struct usb_dma_block_qh usb_blk_fulllist =
90 	LIST_HEAD_INITIALIZER(usb_blk_fulllist);
91 #endif
92 Static u_int usb_blk_nfree = 0;
93 /* XXX should have different free list for different tags (for speed) */
94 Static LIST_HEAD(, usb_frag_dma) usb_frag_freelist =
95 	LIST_HEAD_INITIALIZER(usb_frag_freelist);
96 
97 Static int usb_mem_init(void);
98 
99 Static int
100 usb_mem_init(void)
101 {
102 
103 	mutex_init(&usb_blk_lock, MUTEX_DEFAULT, IPL_NONE);
104 	return 0;
105 }
106 
107 Static usbd_status
108 usb_block_allocmem(bus_dma_tag_t tag, size_t size, size_t align,
109     u_int flags, usb_dma_block_t **dmap)
110 {
111 	usb_dma_block_t *b;
112 	int error;
113 
114 	USBHIST_FUNC();
115 	USBHIST_CALLARGS(usbdebug, "size=%ju align=%ju flags=%#jx", size, align, flags, 0);
116 
117 	ASSERT_SLEEPABLE();
118 	KASSERT(size != 0);
119 	KASSERT(mutex_owned(&usb_blk_lock));
120 
121 	bool multiseg = (flags & USBMALLOC_MULTISEG) != 0;
122 	bool coherent = (flags & USBMALLOC_COHERENT) != 0;
123 	u_int dmaflags = coherent ? USB_DMA_COHERENT : 0;
124 
125 	/* First check the free list. */
126 	LIST_FOREACH(b, &usb_blk_freelist, next) {
127 		/* Don't allocate multiple segments to unwilling callers */
128 		if (b->nsegs != 1 && !multiseg)
129 			continue;
130 		if (b->tag == tag &&
131 		    b->size >= size &&
132 		    b->align >= align &&
133 		    (b->flags & USB_DMA_COHERENT) == dmaflags) {
134 			LIST_REMOVE(b, next);
135 			usb_blk_nfree--;
136 			*dmap = b;
137 			DPRINTFN(6, "free list size=%ju", b->size, 0, 0, 0);
138 			return USBD_NORMAL_COMPLETION;
139 		}
140 	}
141 
142 	DPRINTFN(6, "no freelist entry", 0, 0, 0, 0);
143 	mutex_exit(&usb_blk_lock);
144 
145 	b = kmem_zalloc(sizeof(*b), KM_SLEEP);
146 	b->tag = tag;
147 	b->size = size;
148 	b->align = align;
149 	b->flags = dmaflags;
150 
151 	if (!multiseg)
152 		/* Caller wants one segment */
153 		b->nsegs = 1;
154 	else
155 		b->nsegs = howmany(size, PAGE_SIZE);
156 
157 	b->segs = kmem_alloc(b->nsegs * sizeof(*b->segs), KM_SLEEP);
158 	b->nsegs_alloc = b->nsegs;
159 
160 	error = bus_dmamem_alloc(tag, b->size, align, 0,
161 				 b->segs, b->nsegs,
162 				 &b->nsegs, BUS_DMA_WAITOK);
163 	if (error)
164 		goto free0;
165 
166 	error = bus_dmamem_map(tag, b->segs, b->nsegs, b->size, &b->kaddr,
167 	    BUS_DMA_WAITOK | (coherent ? BUS_DMA_COHERENT : 0));
168 	if (error)
169 		goto free1;
170 
171 	error = bus_dmamap_create(tag, b->size, b->nsegs, b->size,
172 				  0, BUS_DMA_WAITOK, &b->map);
173 	if (error)
174 		goto unmap;
175 
176 	error = bus_dmamap_load(tag, b->map, b->kaddr, b->size, NULL,
177 				BUS_DMA_WAITOK);
178 	if (error)
179 		goto destroy;
180 
181 	*dmap = b;
182 #ifdef USB_FRAG_DMA_WORKAROUND
183 	memset(b->kaddr, 0, b->size);
184 #endif
185 	mutex_enter(&usb_blk_lock);
186 
187 	return USBD_NORMAL_COMPLETION;
188 
189  destroy:
190 	bus_dmamap_destroy(tag, b->map);
191  unmap:
192 	bus_dmamem_unmap(tag, b->kaddr, b->size);
193  free1:
194 	bus_dmamem_free(tag, b->segs, b->nsegs);
195  free0:
196 	kmem_free(b->segs, b->nsegs_alloc * sizeof(*b->segs));
197 	kmem_free(b, sizeof(*b));
198 	mutex_enter(&usb_blk_lock);
199 
200 	return USBD_NOMEM;
201 }
202 
203 #if 0
204 void
205 usb_block_real_freemem(usb_dma_block_t *b)
206 {
207 #ifdef DIAGNOSTIC
208 	if (cpu_softintr_p() || cpu_intr_p()) {
209 		printf("usb_block_real_freemem: in interrupt context\n");
210 		return;
211 	}
212 #endif
213 	bus_dmamap_unload(b->tag, b->map);
214 	bus_dmamap_destroy(b->tag, b->map);
215 	bus_dmamem_unmap(b->tag, b->kaddr, b->size);
216 	bus_dmamem_free(b->tag, b->segs, b->nsegs);
217 	kmem_free(b->segs, b->nsegs_alloc * sizeof(*b->segs));
218 	kmem_free(b, sizeof(*b));
219 }
220 #endif
221 
222 #ifdef DEBUG
223 static bool
224 usb_valid_block_p(usb_dma_block_t *b, struct usb_dma_block_qh *qh)
225 {
226 	usb_dma_block_t *xb;
227 	LIST_FOREACH(xb, qh, next) {
228 		if (xb == b)
229 			return true;
230 	}
231 	return false;
232 }
233 #endif
234 
235 /*
236  * Do not free the memory unconditionally since we might be called
237  * from an interrupt context and that is BAD.
238  * XXX when should we really free?
239  */
240 Static void
241 usb_block_freemem(usb_dma_block_t *b)
242 {
243 	USBHIST_FUNC();
244 	USBHIST_CALLARGS(usbdebug, "size=%ju", b->size, 0, 0, 0);
245 
246 	KASSERT(mutex_owned(&usb_blk_lock));
247 
248 #ifdef DEBUG
249 	LIST_REMOVE(b, next);
250 #endif
251 	LIST_INSERT_HEAD(&usb_blk_freelist, b, next);
252 	usb_blk_nfree++;
253 }
254 
255 usbd_status
256 usb_allocmem(struct usbd_bus *bus, size_t size, size_t align, u_int flags,
257     usb_dma_t *p)
258 {
259 	bus_dma_tag_t tag = bus->ub_dmatag;
260 	usbd_status err;
261 	struct usb_frag_dma *f;
262 	usb_dma_block_t *b;
263 	int i;
264 	static ONCE_DECL(init_control);
265 
266 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
267 
268 	ASSERT_SLEEPABLE();
269 
270 	RUN_ONCE(&init_control, usb_mem_init);
271 
272 	u_int dmaflags = (flags & USBMALLOC_COHERENT) ? USB_DMA_COHERENT : 0;
273 
274 	/* If the request is large then just use a full block. */
275 	if (size > USB_MEM_SMALL || align > USB_MEM_SMALL) {
276 		DPRINTFN(1, "large alloc %jd", size, 0, 0, 0);
277 		size = (size + USB_MEM_BLOCK - 1) & ~(USB_MEM_BLOCK - 1);
278 		mutex_enter(&usb_blk_lock);
279 		err = usb_block_allocmem(tag, size, align, flags,
280 		    &p->udma_block);
281 		if (!err) {
282 #ifdef DEBUG
283 			LIST_INSERT_HEAD(&usb_blk_fulllist, p->udma_block, next);
284 #endif
285 			p->udma_block->flags = USB_DMA_FULLBLOCK | dmaflags;
286 			p->udma_offs = 0;
287 		}
288 		mutex_exit(&usb_blk_lock);
289 		return err;
290 	}
291 
292 	mutex_enter(&usb_blk_lock);
293 	/* Check for free fragments. */
294 	LIST_FOREACH(f, &usb_frag_freelist, ufd_next) {
295 		KDASSERTMSG(usb_valid_block_p(f->ufd_block, &usb_blk_fraglist),
296 		    "%s: usb frag %p: unknown block pointer %p",
297 		    __func__, f, f->ufd_block);
298 		if (f->ufd_block->tag == tag &&
299 		    (f->ufd_block->flags & USB_DMA_COHERENT) == dmaflags)
300 			break;
301 	}
302 	if (f == NULL) {
303 		DPRINTFN(1, "adding fragments", 0, 0, 0, 0);
304 
305 		err = usb_block_allocmem(tag, USB_MEM_BLOCK, USB_MEM_SMALL,
306 		    flags, &b);
307 		if (err) {
308 			mutex_exit(&usb_blk_lock);
309 			return err;
310 		}
311 #ifdef DEBUG
312 		LIST_INSERT_HEAD(&usb_blk_fraglist, b, next);
313 #endif
314 		b->flags = 0;
315 		for (i = 0; i < USB_MEM_BLOCK; i += USB_MEM_SMALL) {
316 			f = (struct usb_frag_dma *)((char *)b->kaddr + i);
317 			f->ufd_block = b;
318 			f->ufd_offs = i;
319 			LIST_INSERT_HEAD(&usb_frag_freelist, f, ufd_next);
320 #ifdef USB_FRAG_DMA_WORKAROUND
321 			i += 1 * USB_MEM_SMALL;
322 #endif
323 		}
324 		f = LIST_FIRST(&usb_frag_freelist);
325 	}
326 	p->udma_block = f->ufd_block;
327 	p->udma_offs = f->ufd_offs;
328 #ifdef USB_FRAG_DMA_WORKAROUND
329 	p->udma_offs += USB_MEM_SMALL;
330 #endif
331 	LIST_REMOVE(f, ufd_next);
332 	mutex_exit(&usb_blk_lock);
333 	DPRINTFN(5, "use frag=%#jx size=%jd", (uintptr_t)f, size, 0, 0);
334 
335 	return USBD_NORMAL_COMPLETION;
336 }
337 
338 void
339 usb_freemem(struct usbd_bus *bus, usb_dma_t *p)
340 {
341 	struct usb_frag_dma *f;
342 
343 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
344 
345 	mutex_enter(&usb_blk_lock);
346 	if (p->udma_block->flags & USB_DMA_FULLBLOCK) {
347 		KDASSERTMSG(usb_valid_block_p(p->udma_block, &usb_blk_fulllist),
348 		    "%s: dma %p: invalid block pointer %p",
349 		    __func__, p, p->udma_block);
350 		DPRINTFN(1, "large free", 0, 0, 0, 0);
351 		usb_block_freemem(p->udma_block);
352 		mutex_exit(&usb_blk_lock);
353 		return;
354 	}
355 	KDASSERTMSG(usb_valid_block_p(p->udma_block, &usb_blk_fraglist),
356 	    "%s: dma %p: invalid block pointer %p",
357 	    __func__, p, p->udma_block);
358 	//usb_syncmem(p, 0, USB_MEM_SMALL, BUS_DMASYNC_POSTREAD);
359 	f = KERNADDR(p, 0);
360 #ifdef USB_FRAG_DMA_WORKAROUND
361 	f = (void *)((uintptr_t)f - USB_MEM_SMALL);
362 #endif
363 	f->ufd_block = p->udma_block;
364 	f->ufd_offs = p->udma_offs;
365 #ifdef USB_FRAG_DMA_WORKAROUND
366 	f->ufd_offs -= USB_MEM_SMALL;
367 #endif
368 	LIST_INSERT_HEAD(&usb_frag_freelist, f, ufd_next);
369 	mutex_exit(&usb_blk_lock);
370 	DPRINTFN(5, "frag=%#jx", (uintptr_t)f, 0, 0, 0);
371 }
372 
373 bus_addr_t
374 usb_dmaaddr(usb_dma_t *dma, unsigned int offset)
375 {
376 	unsigned int i;
377 	bus_size_t seg_offs;
378 
379 	offset += dma->udma_offs;
380 
381 	KASSERTMSG(offset < dma->udma_block->size, "offset %d vs %zu", offset,
382 	    dma->udma_block->size);
383 
384 	if (dma->udma_block->nsegs == 1) {
385 		KASSERT(dma->udma_block->map->dm_segs[0].ds_len > offset);
386 		return dma->udma_block->map->dm_segs[0].ds_addr + offset;
387 	}
388 
389 	/*
390 	 * Search for a bus_segment_t corresponding to this offset. With no
391 	 * record of the offset in the map to a particular dma_segment_t, we
392 	 * have to iterate from the start of the list each time. Could be
393 	 * improved
394 	 */
395 	seg_offs = 0;
396 	for (i = 0; i < dma->udma_block->nsegs; i++) {
397 		if (seg_offs + dma->udma_block->map->dm_segs[i].ds_len > offset)
398 			break;
399 
400 		seg_offs += dma->udma_block->map->dm_segs[i].ds_len;
401 	}
402 
403 	KASSERT(i != dma->udma_block->nsegs);
404 	offset -= seg_offs;
405 	return dma->udma_block->map->dm_segs[i].ds_addr + offset;
406 }
407 
408 void
409 usb_syncmem(usb_dma_t *p, bus_addr_t offset, bus_size_t len, int ops)
410 {
411 
412 	bus_dmamap_sync(p->udma_block->tag, p->udma_block->map,
413 	    p->udma_offs + offset, len, ops);
414 }
415