xref: /netbsd-src/sys/dev/usb/usb_mem.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: usb_mem.c,v 1.70 2017/10/28 00:37:12 pgoyette 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.70 2017/10/28 00:37:12 pgoyette Exp $");
42 
43 #ifdef _KERNEL_OPT
44 #include "opt_usb.h"
45 #endif
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/kernel.h>
50 #include <sys/kmem.h>
51 #include <sys/queue.h>
52 #include <sys/device.h>		/* for usbdivar.h */
53 #include <sys/bus.h>
54 #include <sys/cpu.h>
55 #include <sys/once.h>
56 
57 #ifdef DIAGNOSTIC
58 #include <sys/proc.h>
59 #endif
60 
61 #include <dev/usb/usb.h>
62 #include <dev/usb/usbdi.h>
63 #include <dev/usb/usbdivar.h>	/* just for usb_dma_t */
64 #include <dev/usb/usb_mem.h>
65 #include <dev/usb/usbhist.h>
66 
67 #define	DPRINTF(FMT,A,B,C,D)	USBHIST_LOG(usbdebug,FMT,A,B,C,D)
68 #define	DPRINTFN(N,FMT,A,B,C,D)	USBHIST_LOGN(usbdebug,N,FMT,A,B,C,D)
69 
70 #define USB_MEM_SMALL roundup(64, CACHE_LINE_SIZE)
71 #define USB_MEM_CHUNKS 64
72 #define USB_MEM_BLOCK (USB_MEM_SMALL * USB_MEM_CHUNKS)
73 
74 /* This struct is overlayed on free fragments. */
75 struct usb_frag_dma {
76 	usb_dma_block_t		*ufd_block;
77 	u_int			ufd_offs;
78 	LIST_ENTRY(usb_frag_dma) ufd_next;
79 };
80 
81 Static usbd_status	usb_block_allocmem(bus_dma_tag_t, size_t, size_t,
82 					   usb_dma_block_t **, bool);
83 Static void		usb_block_freemem(usb_dma_block_t *);
84 
85 LIST_HEAD(usb_dma_block_qh, usb_dma_block);
86 Static struct usb_dma_block_qh usb_blk_freelist =
87 	LIST_HEAD_INITIALIZER(usb_blk_freelist);
88 kmutex_t usb_blk_lock;
89 
90 #ifdef DEBUG
91 Static struct usb_dma_block_qh usb_blk_fraglist =
92 	LIST_HEAD_INITIALIZER(usb_blk_fraglist);
93 Static struct usb_dma_block_qh usb_blk_fulllist =
94 	LIST_HEAD_INITIALIZER(usb_blk_fulllist);
95 #endif
96 Static u_int usb_blk_nfree = 0;
97 /* XXX should have different free list for different tags (for speed) */
98 Static LIST_HEAD(, usb_frag_dma) usb_frag_freelist =
99 	LIST_HEAD_INITIALIZER(usb_frag_freelist);
100 
101 Static int usb_mem_init(void);
102 
103 Static int
104 usb_mem_init(void)
105 {
106 
107 	mutex_init(&usb_blk_lock, MUTEX_DEFAULT, IPL_NONE);
108 	return 0;
109 }
110 
111 Static usbd_status
112 usb_block_allocmem(bus_dma_tag_t tag, size_t size, size_t align,
113 		   usb_dma_block_t **dmap, bool multiseg)
114 {
115 	usb_dma_block_t *b;
116 	int error;
117 
118 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
119 	DPRINTFN(5, "size=%ju align=%ju", size, align, 0, 0);
120 
121 	ASSERT_SLEEPABLE();
122 	KASSERT(size != 0);
123 	KASSERT(mutex_owned(&usb_blk_lock));
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 && b->size >= size && b->align >= align) {
131 			LIST_REMOVE(b, next);
132 			usb_blk_nfree--;
133 			*dmap = b;
134 			DPRINTFN(6, "free list size=%ju", b->size, 0, 0, 0);
135 			return USBD_NORMAL_COMPLETION;
136 		}
137 	}
138 
139 	DPRINTFN(6, "no free", 0, 0, 0, 0);
140 	mutex_exit(&usb_blk_lock);
141 
142 	b = kmem_zalloc(sizeof(*b), KM_SLEEP);
143 	b->tag = tag;
144 	b->size = size;
145 	b->align = align;
146 
147 	if (!multiseg)
148 		/* Caller wants one segment */
149 		b->nsegs = 1;
150 	else
151 		b->nsegs = (size + (PAGE_SIZE-1)) / PAGE_SIZE;
152 
153 	b->segs = kmem_alloc(b->nsegs * sizeof(*b->segs), KM_SLEEP);
154 	b->nsegs_alloc = b->nsegs;
155 
156 	error = bus_dmamem_alloc(tag, b->size, align, 0,
157 				 b->segs, b->nsegs,
158 				 &b->nsegs, BUS_DMA_WAITOK);
159 	if (error)
160 		goto free0;
161 
162 	error = bus_dmamem_map(tag, b->segs, b->nsegs, b->size,
163 			       &b->kaddr, BUS_DMA_WAITOK|BUS_DMA_COHERENT);
164 	if (error)
165 		goto free1;
166 
167 	error = bus_dmamap_create(tag, b->size, b->nsegs, b->size,
168 				  0, BUS_DMA_WAITOK, &b->map);
169 	if (error)
170 		goto unmap;
171 
172 	error = bus_dmamap_load(tag, b->map, b->kaddr, b->size, NULL,
173 				BUS_DMA_WAITOK);
174 	if (error)
175 		goto destroy;
176 
177 	*dmap = b;
178 #ifdef USB_FRAG_DMA_WORKAROUND
179 	memset(b->kaddr, 0, b->size);
180 #endif
181 	mutex_enter(&usb_blk_lock);
182 
183 	return USBD_NORMAL_COMPLETION;
184 
185  destroy:
186 	bus_dmamap_destroy(tag, b->map);
187  unmap:
188 	bus_dmamem_unmap(tag, b->kaddr, b->size);
189  free1:
190 	bus_dmamem_free(tag, b->segs, b->nsegs);
191  free0:
192 	kmem_free(b->segs, b->nsegs_alloc * sizeof(*b->segs));
193 	kmem_free(b, sizeof(*b));
194 	mutex_enter(&usb_blk_lock);
195 
196 	return USBD_NOMEM;
197 }
198 
199 #if 0
200 void
201 usb_block_real_freemem(usb_dma_block_t *b)
202 {
203 #ifdef DIAGNOSTIC
204 	if (cpu_softintr_p() || cpu_intr_p()) {
205 		printf("usb_block_real_freemem: in interrupt context\n");
206 		return;
207 	}
208 #endif
209 	bus_dmamap_unload(b->tag, b->map);
210 	bus_dmamap_destroy(b->tag, b->map);
211 	bus_dmamem_unmap(b->tag, b->kaddr, b->size);
212 	bus_dmamem_free(b->tag, b->segs, b->nsegs);
213 	kmem_free(b->segs, b->nsegs_alloc * sizeof(*b->segs));
214 	kmem_free(b, sizeof(*b));
215 }
216 #endif
217 
218 #ifdef DEBUG
219 static bool
220 usb_valid_block_p(usb_dma_block_t *b, struct usb_dma_block_qh *qh)
221 {
222 	usb_dma_block_t *xb;
223 	LIST_FOREACH(xb, qh, next) {
224 		if (xb == b)
225 			return true;
226 	}
227 	return false;
228 }
229 #endif
230 
231 /*
232  * Do not free the memory unconditionally since we might be called
233  * from an interrupt context and that is BAD.
234  * XXX when should we really free?
235  */
236 Static void
237 usb_block_freemem(usb_dma_block_t *b)
238 {
239 
240 	KASSERT(mutex_owned(&usb_blk_lock));
241 
242 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
243 	DPRINTFN(6, "size=%ju", b->size, 0, 0, 0);
244 #ifdef DEBUG
245 	LIST_REMOVE(b, next);
246 #endif
247 	LIST_INSERT_HEAD(&usb_blk_freelist, b, next);
248 	usb_blk_nfree++;
249 }
250 
251 usbd_status
252 usb_allocmem(struct usbd_bus *bus, size_t size, size_t align, usb_dma_t *p)
253 {
254 
255 	return usb_allocmem_flags(bus, size, align, p, 0);
256 }
257 
258 usbd_status
259 usb_allocmem_flags(struct usbd_bus *bus, size_t size, size_t align, usb_dma_t *p,
260 		   int flags)
261 {
262 	bus_dma_tag_t tag = bus->ub_dmatag;
263 	usbd_status err;
264 	struct usb_frag_dma *f;
265 	usb_dma_block_t *b;
266 	int i;
267 	static ONCE_DECL(init_control);
268 	bool frag;
269 
270 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
271 
272 	ASSERT_SLEEPABLE();
273 
274 	RUN_ONCE(&init_control, usb_mem_init);
275 
276 	frag = (flags & USBMALLOC_MULTISEG);
277 
278 	/* If the request is large then just use a full block. */
279 	if (size > USB_MEM_SMALL || align > USB_MEM_SMALL) {
280 		DPRINTFN(1, "large alloc %jd", size, 0, 0, 0);
281 		size = (size + USB_MEM_BLOCK - 1) & ~(USB_MEM_BLOCK - 1);
282 		mutex_enter(&usb_blk_lock);
283 		err = usb_block_allocmem(tag, size, align, &p->udma_block, frag);
284 		if (!err) {
285 #ifdef DEBUG
286 			LIST_INSERT_HEAD(&usb_blk_fulllist, p->udma_block, next);
287 #endif
288 			p->udma_block->flags = USB_DMA_FULLBLOCK;
289 			p->udma_offs = 0;
290 		}
291 		mutex_exit(&usb_blk_lock);
292 		return err;
293 	}
294 
295 	mutex_enter(&usb_blk_lock);
296 	/* Check for free fragments. */
297 	LIST_FOREACH(f, &usb_frag_freelist, ufd_next) {
298 		KDASSERTMSG(usb_valid_block_p(f->ufd_block, &usb_blk_fraglist),
299 		    "%s: usb frag %p: unknown block pointer %p",
300 		    __func__, f, f->ufd_block);
301 		if (f->ufd_block->tag == tag)
302 			break;
303 	}
304 	if (f == NULL) {
305 		DPRINTFN(1, "adding fragments", 0, 0, 0, 0);
306 		err = usb_block_allocmem(tag, USB_MEM_BLOCK, USB_MEM_SMALL, &b,
307 					 false);
308 		if (err) {
309 			mutex_exit(&usb_blk_lock);
310 			return err;
311 		}
312 #ifdef DEBUG
313 		LIST_INSERT_HEAD(&usb_blk_fraglist, b, next);
314 #endif
315 		b->flags = 0;
316 		for (i = 0; i < USB_MEM_BLOCK; i += USB_MEM_SMALL) {
317 			f = (struct usb_frag_dma *)((char *)b->kaddr + i);
318 			f->ufd_block = b;
319 			f->ufd_offs = i;
320 			LIST_INSERT_HEAD(&usb_frag_freelist, f, ufd_next);
321 #ifdef USB_FRAG_DMA_WORKAROUND
322 			i += 1 * USB_MEM_SMALL;
323 #endif
324 		}
325 		f = LIST_FIRST(&usb_frag_freelist);
326 	}
327 	p->udma_block = f->ufd_block;
328 	p->udma_offs = f->ufd_offs;
329 #ifdef USB_FRAG_DMA_WORKAROUND
330 	p->udma_offs += USB_MEM_SMALL;
331 #endif
332 	LIST_REMOVE(f, ufd_next);
333 	mutex_exit(&usb_blk_lock);
334 	DPRINTFN(5, "use frag=%#jx size=%jd", (uintptr_t)f, size, 0, 0);
335 
336 	return USBD_NORMAL_COMPLETION;
337 }
338 
339 void
340 usb_freemem(struct usbd_bus *bus, usb_dma_t *p)
341 {
342 	struct usb_frag_dma *f;
343 
344 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
345 
346 	mutex_enter(&usb_blk_lock);
347 	if (p->udma_block->flags & USB_DMA_FULLBLOCK) {
348 		KDASSERTMSG(usb_valid_block_p(p->udma_block, &usb_blk_fulllist),
349 		    "%s: dma %p: invalid block pointer %p",
350 		    __func__, p, p->udma_block);
351 		DPRINTFN(1, "large free", 0, 0, 0, 0);
352 		usb_block_freemem(p->udma_block);
353 		mutex_exit(&usb_blk_lock);
354 		return;
355 	}
356 	KDASSERTMSG(usb_valid_block_p(p->udma_block, &usb_blk_fraglist),
357 	    "%s: dma %p: invalid block pointer %p",
358 	    __func__, p, p->udma_block);
359 	//usb_syncmem(p, 0, USB_MEM_SMALL, BUS_DMASYNC_POSTREAD);
360 	f = KERNADDR(p, 0);
361 #ifdef USB_FRAG_DMA_WORKAROUND
362 	f = (void *)((uintptr_t)f - USB_MEM_SMALL);
363 #endif
364 	f->ufd_block = p->udma_block;
365 	f->ufd_offs = p->udma_offs;
366 #ifdef USB_FRAG_DMA_WORKAROUND
367 	f->ufd_offs -= USB_MEM_SMALL;
368 #endif
369 	LIST_INSERT_HEAD(&usb_frag_freelist, f, ufd_next);
370 	mutex_exit(&usb_blk_lock);
371 	DPRINTFN(5, "frag=%#jx", (uintptr_t)f, 0, 0, 0);
372 }
373 
374 bus_addr_t
375 usb_dmaaddr(usb_dma_t *dma, unsigned int offset)
376 {
377 	unsigned int i;
378 	bus_size_t seg_offs;
379 
380 	offset += dma->udma_offs;
381 
382 	KASSERTMSG(offset < dma->udma_block->size, "offset %d vs %zu", offset,
383 	    dma->udma_block->size);
384 
385 	if (dma->udma_block->nsegs == 1) {
386 		KASSERT(dma->udma_block->map->dm_segs[0].ds_len > offset);
387 		return dma->udma_block->map->dm_segs[0].ds_addr + offset;
388 	}
389 
390 	/*
391 	 * Search for a bus_segment_t corresponding to this offset. With no
392 	 * record of the offset in the map to a particular dma_segment_t, we
393 	 * have to iterate from the start of the list each time. Could be
394 	 * improved
395 	 */
396 	seg_offs = 0;
397 	for (i = 0; i < dma->udma_block->nsegs; i++) {
398 		if (seg_offs + dma->udma_block->map->dm_segs[i].ds_len > offset)
399 			break;
400 
401 		seg_offs += dma->udma_block->map->dm_segs[i].ds_len;
402 	}
403 
404 	KASSERT(i != dma->udma_block->nsegs);
405 	offset -= seg_offs;
406 	return dma->udma_block->map->dm_segs[i].ds_addr + offset;
407 }
408 
409 void
410 usb_syncmem(usb_dma_t *p, bus_addr_t offset, bus_size_t len, int ops)
411 {
412 
413 	bus_dmamap_sync(p->udma_block->tag, p->udma_block->map, p->udma_offs + offset,
414 	    len, ops);
415 }
416