xref: /netbsd-src/sys/dev/usb/usb_mem.c (revision e6c7e151de239c49d2e38720a061ed9d1fa99309)
1 /*	$NetBSD: usb_mem.c,v 1.75 2020/03/15 14:19:04 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.75 2020/03/15 14:19:04 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 					   usb_dma_block_t **, bool);
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 		   usb_dma_block_t **dmap, bool multiseg)
110 {
111 	usb_dma_block_t *b;
112 	int error;
113 
114 	USBHIST_FUNC();
115 	USBHIST_CALLARGS(usbdebug, "size=%ju align=%ju", size, align, 0, 0);
116 
117 	ASSERT_SLEEPABLE();
118 	KASSERT(size != 0);
119 	KASSERT(mutex_owned(&usb_blk_lock));
120 
121 	/* First check the free list. */
122 	LIST_FOREACH(b, &usb_blk_freelist, next) {
123 		/* Don't allocate multiple segments to unwilling callers */
124 		if (b->nsegs != 1 && !multiseg)
125 			continue;
126 		if (b->tag == tag && b->size >= size && b->align >= align) {
127 			LIST_REMOVE(b, next);
128 			usb_blk_nfree--;
129 			*dmap = b;
130 			DPRINTFN(6, "free list size=%ju", b->size, 0, 0, 0);
131 			return USBD_NORMAL_COMPLETION;
132 		}
133 	}
134 
135 	DPRINTFN(6, "no freelist entry", 0, 0, 0, 0);
136 	mutex_exit(&usb_blk_lock);
137 
138 	b = kmem_zalloc(sizeof(*b), KM_SLEEP);
139 	b->tag = tag;
140 	b->size = size;
141 	b->align = align;
142 
143 	if (!multiseg)
144 		/* Caller wants one segment */
145 		b->nsegs = 1;
146 	else
147 		b->nsegs = (size + (PAGE_SIZE-1)) / PAGE_SIZE;
148 
149 	b->segs = kmem_alloc(b->nsegs * sizeof(*b->segs), KM_SLEEP);
150 	b->nsegs_alloc = b->nsegs;
151 
152 	error = bus_dmamem_alloc(tag, b->size, align, 0,
153 				 b->segs, b->nsegs,
154 				 &b->nsegs, BUS_DMA_WAITOK);
155 	if (error)
156 		goto free0;
157 
158 	error = bus_dmamem_map(tag, b->segs, b->nsegs, b->size,
159 			       &b->kaddr, BUS_DMA_WAITOK|BUS_DMA_COHERENT);
160 	if (error)
161 		goto free1;
162 
163 	error = bus_dmamap_create(tag, b->size, b->nsegs, b->size,
164 				  0, BUS_DMA_WAITOK, &b->map);
165 	if (error)
166 		goto unmap;
167 
168 	error = bus_dmamap_load(tag, b->map, b->kaddr, b->size, NULL,
169 				BUS_DMA_WAITOK);
170 	if (error)
171 		goto destroy;
172 
173 	*dmap = b;
174 #ifdef USB_FRAG_DMA_WORKAROUND
175 	memset(b->kaddr, 0, b->size);
176 #endif
177 	mutex_enter(&usb_blk_lock);
178 
179 	return USBD_NORMAL_COMPLETION;
180 
181  destroy:
182 	bus_dmamap_destroy(tag, b->map);
183  unmap:
184 	bus_dmamem_unmap(tag, b->kaddr, b->size);
185  free1:
186 	bus_dmamem_free(tag, b->segs, b->nsegs);
187  free0:
188 	kmem_free(b->segs, b->nsegs_alloc * sizeof(*b->segs));
189 	kmem_free(b, sizeof(*b));
190 	mutex_enter(&usb_blk_lock);
191 
192 	return USBD_NOMEM;
193 }
194 
195 #if 0
196 void
197 usb_block_real_freemem(usb_dma_block_t *b)
198 {
199 #ifdef DIAGNOSTIC
200 	if (cpu_softintr_p() || cpu_intr_p()) {
201 		printf("usb_block_real_freemem: in interrupt context\n");
202 		return;
203 	}
204 #endif
205 	bus_dmamap_unload(b->tag, b->map);
206 	bus_dmamap_destroy(b->tag, b->map);
207 	bus_dmamem_unmap(b->tag, b->kaddr, b->size);
208 	bus_dmamem_free(b->tag, b->segs, b->nsegs);
209 	kmem_free(b->segs, b->nsegs_alloc * sizeof(*b->segs));
210 	kmem_free(b, sizeof(*b));
211 }
212 #endif
213 
214 #ifdef DEBUG
215 static bool
216 usb_valid_block_p(usb_dma_block_t *b, struct usb_dma_block_qh *qh)
217 {
218 	usb_dma_block_t *xb;
219 	LIST_FOREACH(xb, qh, next) {
220 		if (xb == b)
221 			return true;
222 	}
223 	return false;
224 }
225 #endif
226 
227 /*
228  * Do not free the memory unconditionally since we might be called
229  * from an interrupt context and that is BAD.
230  * XXX when should we really free?
231  */
232 Static void
233 usb_block_freemem(usb_dma_block_t *b)
234 {
235 	USBHIST_FUNC();
236 	USBHIST_CALLARGS(usbdebug, "size=%ju", b->size, 0, 0, 0);
237 
238 	KASSERT(mutex_owned(&usb_blk_lock));
239 
240 #ifdef DEBUG
241 	LIST_REMOVE(b, next);
242 #endif
243 	LIST_INSERT_HEAD(&usb_blk_freelist, b, next);
244 	usb_blk_nfree++;
245 }
246 
247 usbd_status
248 usb_allocmem(struct usbd_bus *bus, size_t size, size_t align, usb_dma_t *p)
249 {
250 
251 	return usb_allocmem_flags(bus, size, align, p, 0);
252 }
253 
254 usbd_status
255 usb_allocmem_flags(struct usbd_bus *bus, size_t size, size_t align, usb_dma_t *p,
256 		   int flags)
257 {
258 	bus_dma_tag_t tag = bus->ub_dmatag;
259 	usbd_status err;
260 	struct usb_frag_dma *f;
261 	usb_dma_block_t *b;
262 	int i;
263 	static ONCE_DECL(init_control);
264 	bool frag;
265 
266 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
267 
268 	ASSERT_SLEEPABLE();
269 
270 	RUN_ONCE(&init_control, usb_mem_init);
271 
272 	frag = (flags & USBMALLOC_MULTISEG);
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, &p->udma_block, frag);
280 		if (!err) {
281 #ifdef DEBUG
282 			LIST_INSERT_HEAD(&usb_blk_fulllist, p->udma_block, next);
283 #endif
284 			p->udma_block->flags = USB_DMA_FULLBLOCK;
285 			p->udma_offs = 0;
286 		}
287 		mutex_exit(&usb_blk_lock);
288 		return err;
289 	}
290 
291 	mutex_enter(&usb_blk_lock);
292 	/* Check for free fragments. */
293 	LIST_FOREACH(f, &usb_frag_freelist, ufd_next) {
294 		KDASSERTMSG(usb_valid_block_p(f->ufd_block, &usb_blk_fraglist),
295 		    "%s: usb frag %p: unknown block pointer %p",
296 		    __func__, f, f->ufd_block);
297 		if (f->ufd_block->tag == tag)
298 			break;
299 	}
300 	if (f == NULL) {
301 		DPRINTFN(1, "adding fragments", 0, 0, 0, 0);
302 		err = usb_block_allocmem(tag, USB_MEM_BLOCK, USB_MEM_SMALL, &b,
303 					 false);
304 		if (err) {
305 			mutex_exit(&usb_blk_lock);
306 			return err;
307 		}
308 #ifdef DEBUG
309 		LIST_INSERT_HEAD(&usb_blk_fraglist, b, next);
310 #endif
311 		b->flags = 0;
312 		for (i = 0; i < USB_MEM_BLOCK; i += USB_MEM_SMALL) {
313 			f = (struct usb_frag_dma *)((char *)b->kaddr + i);
314 			f->ufd_block = b;
315 			f->ufd_offs = i;
316 			LIST_INSERT_HEAD(&usb_frag_freelist, f, ufd_next);
317 #ifdef USB_FRAG_DMA_WORKAROUND
318 			i += 1 * USB_MEM_SMALL;
319 #endif
320 		}
321 		f = LIST_FIRST(&usb_frag_freelist);
322 	}
323 	p->udma_block = f->ufd_block;
324 	p->udma_offs = f->ufd_offs;
325 #ifdef USB_FRAG_DMA_WORKAROUND
326 	p->udma_offs += USB_MEM_SMALL;
327 #endif
328 	LIST_REMOVE(f, ufd_next);
329 	mutex_exit(&usb_blk_lock);
330 	DPRINTFN(5, "use frag=%#jx size=%jd", (uintptr_t)f, size, 0, 0);
331 
332 	return USBD_NORMAL_COMPLETION;
333 }
334 
335 void
336 usb_freemem(struct usbd_bus *bus, usb_dma_t *p)
337 {
338 	struct usb_frag_dma *f;
339 
340 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
341 
342 	mutex_enter(&usb_blk_lock);
343 	if (p->udma_block->flags & USB_DMA_FULLBLOCK) {
344 		KDASSERTMSG(usb_valid_block_p(p->udma_block, &usb_blk_fulllist),
345 		    "%s: dma %p: invalid block pointer %p",
346 		    __func__, p, p->udma_block);
347 		DPRINTFN(1, "large free", 0, 0, 0, 0);
348 		usb_block_freemem(p->udma_block);
349 		mutex_exit(&usb_blk_lock);
350 		return;
351 	}
352 	KDASSERTMSG(usb_valid_block_p(p->udma_block, &usb_blk_fraglist),
353 	    "%s: dma %p: invalid block pointer %p",
354 	    __func__, p, p->udma_block);
355 	//usb_syncmem(p, 0, USB_MEM_SMALL, BUS_DMASYNC_POSTREAD);
356 	f = KERNADDR(p, 0);
357 #ifdef USB_FRAG_DMA_WORKAROUND
358 	f = (void *)((uintptr_t)f - USB_MEM_SMALL);
359 #endif
360 	f->ufd_block = p->udma_block;
361 	f->ufd_offs = p->udma_offs;
362 #ifdef USB_FRAG_DMA_WORKAROUND
363 	f->ufd_offs -= USB_MEM_SMALL;
364 #endif
365 	LIST_INSERT_HEAD(&usb_frag_freelist, f, ufd_next);
366 	mutex_exit(&usb_blk_lock);
367 	DPRINTFN(5, "frag=%#jx", (uintptr_t)f, 0, 0, 0);
368 }
369 
370 bus_addr_t
371 usb_dmaaddr(usb_dma_t *dma, unsigned int offset)
372 {
373 	unsigned int i;
374 	bus_size_t seg_offs;
375 
376 	offset += dma->udma_offs;
377 
378 	KASSERTMSG(offset < dma->udma_block->size, "offset %d vs %zu", offset,
379 	    dma->udma_block->size);
380 
381 	if (dma->udma_block->nsegs == 1) {
382 		KASSERT(dma->udma_block->map->dm_segs[0].ds_len > offset);
383 		return dma->udma_block->map->dm_segs[0].ds_addr + offset;
384 	}
385 
386 	/*
387 	 * Search for a bus_segment_t corresponding to this offset. With no
388 	 * record of the offset in the map to a particular dma_segment_t, we
389 	 * have to iterate from the start of the list each time. Could be
390 	 * improved
391 	 */
392 	seg_offs = 0;
393 	for (i = 0; i < dma->udma_block->nsegs; i++) {
394 		if (seg_offs + dma->udma_block->map->dm_segs[i].ds_len > offset)
395 			break;
396 
397 		seg_offs += dma->udma_block->map->dm_segs[i].ds_len;
398 	}
399 
400 	KASSERT(i != dma->udma_block->nsegs);
401 	offset -= seg_offs;
402 	return dma->udma_block->map->dm_segs[i].ds_addr + offset;
403 }
404 
405 void
406 usb_syncmem(usb_dma_t *p, bus_addr_t offset, bus_size_t len, int ops)
407 {
408 
409 	bus_dmamap_sync(p->udma_block->tag, p->udma_block->map, p->udma_offs + offset,
410 	    len, ops);
411 }
412