xref: /dragonfly/sys/dev/drm/ttm/ttm_page_alloc.c (revision d4ef6694)
1 /*
2  * Copyright (c) Red Hat Inc.
3 
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sub license,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the
12  * next paragraph) shall be included in all copies or substantial portions
13  * of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: Dave Airlie <airlied@redhat.com>
24  *          Jerome Glisse <jglisse@redhat.com>
25  *          Pauli Nieminen <suokkos@gmail.com>
26  */
27 /*
28  * Copyright (c) 2013 The FreeBSD Foundation
29  * All rights reserved.
30  *
31  * Portions of this software were developed by Konstantin Belousov
32  * <kib@FreeBSD.org> under sponsorship from the FreeBSD Foundation.
33  *
34  * $FreeBSD: head/sys/dev/drm2/ttm/ttm_page_alloc.c 247849 2013-03-05 16:15:34Z kib $
35  */
36 
37 /* simple list based uncached page pool
38  * - Pool collects resently freed pages for reuse
39  * - Use page->lru to keep a free list
40  * - doesn't track currently in use pages
41  */
42 
43 #include <sys/eventhandler.h>
44 
45 #include <drm/drmP.h>
46 #include <drm/ttm/ttm_bo_driver.h>
47 #include <drm/ttm/ttm_page_alloc.h>
48 
49 #ifdef TTM_HAS_AGP
50 #include <asm/agp.h>
51 #endif
52 
53 #define NUM_PAGES_TO_ALLOC		(PAGE_SIZE/sizeof(vm_page_t))
54 #define SMALL_ALLOCATION		16
55 #define FREE_ALL_PAGES			(~0U)
56 /* times are in msecs */
57 #define PAGE_FREE_INTERVAL		1000
58 
59 /**
60  * struct ttm_page_pool - Pool to reuse recently allocated uc/wc pages.
61  *
62  * @lock: Protects the shared pool from concurrnet access. Must be used with
63  * irqsave/irqrestore variants because pool allocator maybe called from
64  * delayed work.
65  * @fill_lock: Prevent concurrent calls to fill.
66  * @list: Pool of free uc/wc pages for fast reuse.
67  * @gfp_flags: Flags to pass for alloc_page.
68  * @npages: Number of pages in pool.
69  */
70 struct ttm_page_pool {
71 	struct lock		lock;
72 	bool			fill_lock;
73 	bool			dma32;
74 	struct pglist		list;
75 	int			ttm_page_alloc_flags;
76 	unsigned		npages;
77 	char			*name;
78 	unsigned long		nfrees;
79 	unsigned long		nrefills;
80 };
81 
82 /**
83  * Limits for the pool. They are handled without locks because only place where
84  * they may change is in sysfs store. They won't have immediate effect anyway
85  * so forcing serialization to access them is pointless.
86  */
87 
88 struct ttm_pool_opts {
89 	unsigned	alloc_size;
90 	unsigned	max_size;
91 	unsigned	small;
92 };
93 
94 #define NUM_POOLS 4
95 
96 /**
97  * struct ttm_pool_manager - Holds memory pools for fst allocation
98  *
99  * Manager is read only object for pool code so it doesn't need locking.
100  *
101  * @free_interval: minimum number of jiffies between freeing pages from pool.
102  * @page_alloc_inited: reference counting for pool allocation.
103  * @work: Work that is used to shrink the pool. Work is only run when there is
104  * some pages to free.
105  * @small_allocation: Limit in number of pages what is small allocation.
106  *
107  * @pools: All pool objects in use.
108  **/
109 struct ttm_pool_manager {
110 	unsigned int kobj_ref;
111 	eventhandler_tag lowmem_handler;
112 	struct ttm_pool_opts	options;
113 
114 	union {
115 		struct ttm_page_pool	u_pools[NUM_POOLS];
116 		struct _utag {
117 			struct ttm_page_pool	u_wc_pool;
118 			struct ttm_page_pool	u_uc_pool;
119 			struct ttm_page_pool	u_wc_pool_dma32;
120 			struct ttm_page_pool	u_uc_pool_dma32;
121 		} _ut;
122 	} _u;
123 };
124 
125 #define	pools _u.u_pools
126 #define	wc_pool _u._ut.u_wc_pool
127 #define	uc_pool _u._ut.u_uc_pool
128 #define	wc_pool_dma32 _u._ut.u_wc_pool_dma32
129 #define	uc_pool_dma32 _u._ut.u_uc_pool_dma32
130 
131 static void
132 ttm_vm_page_free(vm_page_t m)
133 {
134 
135 	KASSERT(m->object == NULL, ("ttm page %p is owned", m));
136 	KASSERT(m->wire_count == 1, ("ttm lost wire %p", m));
137 	KASSERT((m->flags & PG_FICTITIOUS) != 0, ("ttm lost fictitious %p", m));
138 #if 0
139 	KASSERT((m->oflags & VPO_UNMANAGED) == 0, ("ttm got unmanaged %p", m));
140 	m->oflags |= VPO_UNMANAGED;
141 #endif
142 	m->flags &= ~PG_FICTITIOUS;
143 	vm_page_busy_wait(m, FALSE, "ttmvpf");
144 	vm_page_wakeup(m);
145 	vm_page_free_contig(m, PAGE_SIZE);
146 	/*
147 	vm_page_unwire(m, 0);
148 	vm_page_free(m);
149 	*/
150 }
151 
152 static vm_memattr_t
153 ttm_caching_state_to_vm(enum ttm_caching_state cstate)
154 {
155 
156 	switch (cstate) {
157 	case tt_uncached:
158 		return (VM_MEMATTR_UNCACHEABLE);
159 	case tt_wc:
160 		return (VM_MEMATTR_WRITE_COMBINING);
161 	case tt_cached:
162 		return (VM_MEMATTR_WRITE_BACK);
163 	}
164 	panic("caching state %d\n", cstate);
165 }
166 
167 static void ttm_pool_kobj_release(struct ttm_pool_manager *m)
168 {
169 
170 	drm_free(m, M_DRM);
171 }
172 
173 #if 0
174 /* XXXKIB sysctl */
175 static ssize_t ttm_pool_store(struct ttm_pool_manager *m,
176 		struct attribute *attr, const char *buffer, size_t size)
177 {
178 	int chars;
179 	unsigned val;
180 	chars = sscanf(buffer, "%u", &val);
181 	if (chars == 0)
182 		return size;
183 
184 	/* Convert kb to number of pages */
185 	val = val / (PAGE_SIZE >> 10);
186 
187 	if (attr == &ttm_page_pool_max)
188 		m->options.max_size = val;
189 	else if (attr == &ttm_page_pool_small)
190 		m->options.small = val;
191 	else if (attr == &ttm_page_pool_alloc_size) {
192 		if (val > NUM_PAGES_TO_ALLOC*8) {
193 			pr_err("Setting allocation size to %lu is not allowed. Recommended size is %lu\n",
194 			       NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 7),
195 			       NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
196 			return size;
197 		} else if (val > NUM_PAGES_TO_ALLOC) {
198 			pr_warn("Setting allocation size to larger than %lu is not recommended\n",
199 				NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
200 		}
201 		m->options.alloc_size = val;
202 	}
203 
204 	return size;
205 }
206 
207 static ssize_t ttm_pool_show(struct ttm_pool_manager *m,
208 		struct attribute *attr, char *buffer)
209 {
210 	unsigned val = 0;
211 
212 	if (attr == &ttm_page_pool_max)
213 		val = m->options.max_size;
214 	else if (attr == &ttm_page_pool_small)
215 		val = m->options.small;
216 	else if (attr == &ttm_page_pool_alloc_size)
217 		val = m->options.alloc_size;
218 
219 	val = val * (PAGE_SIZE >> 10);
220 
221 	return snprintf(buffer, PAGE_SIZE, "%u\n", val);
222 }
223 #endif
224 
225 static struct ttm_pool_manager *_manager;
226 
227 static int set_pages_array_wb(vm_page_t *pages, int addrinarray)
228 {
229 	vm_page_t m;
230 	int i;
231 
232 	for (i = 0; i < addrinarray; i++) {
233 		m = pages[i];
234 #ifdef TTM_HAS_AGP
235 		unmap_page_from_agp(m);
236 #endif
237 		pmap_page_set_memattr(m, VM_MEMATTR_WRITE_BACK);
238 	}
239 	return 0;
240 }
241 
242 static int set_pages_array_wc(vm_page_t *pages, int addrinarray)
243 {
244 	vm_page_t m;
245 	int i;
246 
247 	for (i = 0; i < addrinarray; i++) {
248 		m = pages[i];
249 #ifdef TTM_HAS_AGP
250 		map_page_into_agp(pages[i]);
251 #endif
252 		pmap_page_set_memattr(m, VM_MEMATTR_WRITE_COMBINING);
253 	}
254 	return 0;
255 }
256 
257 static int set_pages_array_uc(vm_page_t *pages, int addrinarray)
258 {
259 	vm_page_t m;
260 	int i;
261 
262 	for (i = 0; i < addrinarray; i++) {
263 		m = pages[i];
264 #ifdef TTM_HAS_AGP
265 		map_page_into_agp(pages[i]);
266 #endif
267 		pmap_page_set_memattr(m, VM_MEMATTR_UNCACHEABLE);
268 	}
269 	return 0;
270 }
271 
272 /**
273  * Select the right pool or requested caching state and ttm flags. */
274 static struct ttm_page_pool *ttm_get_pool(int flags,
275 		enum ttm_caching_state cstate)
276 {
277 	int pool_index;
278 
279 	if (cstate == tt_cached)
280 		return NULL;
281 
282 	if (cstate == tt_wc)
283 		pool_index = 0x0;
284 	else
285 		pool_index = 0x1;
286 
287 	if (flags & TTM_PAGE_FLAG_DMA32)
288 		pool_index |= 0x2;
289 
290 	return &_manager->pools[pool_index];
291 }
292 
293 /* set memory back to wb and free the pages. */
294 static void ttm_pages_put(vm_page_t *pages, unsigned npages)
295 {
296 	unsigned i;
297 
298 	/* Our VM handles vm memattr automatically on the page free. */
299 	if (set_pages_array_wb(pages, npages))
300 		kprintf("[TTM] Failed to set %d pages to wb!\n", npages);
301 	for (i = 0; i < npages; ++i)
302 		ttm_vm_page_free(pages[i]);
303 }
304 
305 static void ttm_pool_update_free_locked(struct ttm_page_pool *pool,
306 		unsigned freed_pages)
307 {
308 	pool->npages -= freed_pages;
309 	pool->nfrees += freed_pages;
310 }
311 
312 /**
313  * Free pages from pool.
314  *
315  * To prevent hogging the ttm_swap process we only free NUM_PAGES_TO_ALLOC
316  * number of pages in one go.
317  *
318  * @pool: to free the pages from
319  * @free_all: If set to true will free all pages in pool
320  **/
321 static int ttm_page_pool_free(struct ttm_page_pool *pool, unsigned nr_free)
322 {
323 	vm_page_t p, p1;
324 	vm_page_t *pages_to_free;
325 	unsigned freed_pages = 0,
326 		 npages_to_free = nr_free;
327 	unsigned i;
328 
329 	if (NUM_PAGES_TO_ALLOC < nr_free)
330 		npages_to_free = NUM_PAGES_TO_ALLOC;
331 
332 	pages_to_free = kmalloc(npages_to_free * sizeof(vm_page_t),
333 	    M_TEMP, M_WAITOK | M_ZERO);
334 
335 restart:
336 	lockmgr(&pool->lock, LK_EXCLUSIVE);
337 
338 	TAILQ_FOREACH_REVERSE_MUTABLE(p, &pool->list, pglist, pageq, p1) {
339 		if (freed_pages >= npages_to_free)
340 			break;
341 
342 		pages_to_free[freed_pages++] = p;
343 		/* We can only remove NUM_PAGES_TO_ALLOC at a time. */
344 		if (freed_pages >= NUM_PAGES_TO_ALLOC) {
345 			/* remove range of pages from the pool */
346 			for (i = 0; i < freed_pages; i++)
347 				TAILQ_REMOVE(&pool->list, pages_to_free[i], pageq);
348 
349 			ttm_pool_update_free_locked(pool, freed_pages);
350 			/**
351 			 * Because changing page caching is costly
352 			 * we unlock the pool to prevent stalling.
353 			 */
354 			lockmgr(&pool->lock, LK_RELEASE);
355 
356 			ttm_pages_put(pages_to_free, freed_pages);
357 			if (likely(nr_free != FREE_ALL_PAGES))
358 				nr_free -= freed_pages;
359 
360 			if (NUM_PAGES_TO_ALLOC >= nr_free)
361 				npages_to_free = nr_free;
362 			else
363 				npages_to_free = NUM_PAGES_TO_ALLOC;
364 
365 			freed_pages = 0;
366 
367 			/* free all so restart the processing */
368 			if (nr_free)
369 				goto restart;
370 
371 			/* Not allowed to fall through or break because
372 			 * following context is inside spinlock while we are
373 			 * outside here.
374 			 */
375 			goto out;
376 
377 		}
378 	}
379 
380 	/* remove range of pages from the pool */
381 	if (freed_pages) {
382 		for (i = 0; i < freed_pages; i++)
383 			TAILQ_REMOVE(&pool->list, pages_to_free[i], pageq);
384 
385 		ttm_pool_update_free_locked(pool, freed_pages);
386 		nr_free -= freed_pages;
387 	}
388 
389 	lockmgr(&pool->lock, LK_RELEASE);
390 
391 	if (freed_pages)
392 		ttm_pages_put(pages_to_free, freed_pages);
393 out:
394 	drm_free(pages_to_free, M_TEMP);
395 	return nr_free;
396 }
397 
398 /* Get good estimation how many pages are free in pools */
399 static int ttm_pool_get_num_unused_pages(void)
400 {
401 	unsigned i;
402 	int total = 0;
403 	for (i = 0; i < NUM_POOLS; ++i)
404 		total += _manager->pools[i].npages;
405 
406 	return total;
407 }
408 
409 /**
410  * Callback for mm to request pool to reduce number of page held.
411  */
412 static int ttm_pool_mm_shrink(void *arg)
413 {
414 	static unsigned int start_pool = 0;
415 	unsigned i;
416 	unsigned pool_offset = atomic_fetchadd_int(&start_pool, 1);
417 	struct ttm_page_pool *pool;
418 	int shrink_pages = 100; /* XXXKIB */
419 
420 	pool_offset = pool_offset % NUM_POOLS;
421 	/* select start pool in round robin fashion */
422 	for (i = 0; i < NUM_POOLS; ++i) {
423 		unsigned nr_free = shrink_pages;
424 		if (shrink_pages == 0)
425 			break;
426 		pool = &_manager->pools[(i + pool_offset)%NUM_POOLS];
427 		shrink_pages = ttm_page_pool_free(pool, nr_free);
428 	}
429 	/* return estimated number of unused pages in pool */
430 	return ttm_pool_get_num_unused_pages();
431 }
432 
433 static void ttm_pool_mm_shrink_init(struct ttm_pool_manager *manager)
434 {
435 
436 	manager->lowmem_handler = EVENTHANDLER_REGISTER(vm_lowmem,
437 	    ttm_pool_mm_shrink, manager, EVENTHANDLER_PRI_ANY);
438 }
439 
440 static void ttm_pool_mm_shrink_fini(struct ttm_pool_manager *manager)
441 {
442 
443 	EVENTHANDLER_DEREGISTER(vm_lowmem, manager->lowmem_handler);
444 }
445 
446 static int ttm_set_pages_caching(vm_page_t *pages,
447 		enum ttm_caching_state cstate, unsigned cpages)
448 {
449 	int r = 0;
450 	/* Set page caching */
451 	switch (cstate) {
452 	case tt_uncached:
453 		r = set_pages_array_uc(pages, cpages);
454 		if (r)
455 			kprintf("[TTM] Failed to set %d pages to uc!\n", cpages);
456 		break;
457 	case tt_wc:
458 		r = set_pages_array_wc(pages, cpages);
459 		if (r)
460 			kprintf("[TTM] Failed to set %d pages to wc!\n", cpages);
461 		break;
462 	default:
463 		break;
464 	}
465 	return r;
466 }
467 
468 /**
469  * Free pages the pages that failed to change the caching state. If there is
470  * any pages that have changed their caching state already put them to the
471  * pool.
472  */
473 static void ttm_handle_caching_state_failure(struct pglist *pages,
474 		int ttm_flags, enum ttm_caching_state cstate,
475 		vm_page_t *failed_pages, unsigned cpages)
476 {
477 	unsigned i;
478 	/* Failed pages have to be freed */
479 	for (i = 0; i < cpages; ++i) {
480 		TAILQ_REMOVE(pages, failed_pages[i], pageq);
481 		ttm_vm_page_free(failed_pages[i]);
482 	}
483 }
484 
485 /**
486  * Allocate new pages with correct caching.
487  *
488  * This function is reentrant if caller updates count depending on number of
489  * pages returned in pages array.
490  */
491 static int ttm_alloc_new_pages(struct pglist *pages, int ttm_alloc_flags,
492 		int ttm_flags, enum ttm_caching_state cstate, unsigned count)
493 {
494 	vm_page_t *caching_array;
495 	vm_page_t p;
496 	int r = 0;
497 	unsigned i, cpages, aflags;
498 	unsigned max_cpages = min(count,
499 			(unsigned)(PAGE_SIZE/sizeof(vm_page_t)));
500 
501 	aflags = VM_ALLOC_NORMAL |
502 	    ((ttm_alloc_flags & TTM_PAGE_FLAG_ZERO_ALLOC) != 0 ?
503 	    VM_ALLOC_ZERO : 0);
504 
505 	/* allocate array for page caching change */
506 	caching_array = kmalloc(max_cpages * sizeof(vm_page_t), M_TEMP,
507 	    M_WAITOK | M_ZERO);
508 
509 	for (i = 0, cpages = 0; i < count; ++i) {
510 		p = vm_page_alloc_contig(0,
511 		    (ttm_alloc_flags & TTM_PAGE_FLAG_DMA32) ? 0xffffffff :
512 		    VM_MAX_ADDRESS, PAGE_SIZE, 0,
513 		    1*PAGE_SIZE, ttm_caching_state_to_vm(cstate));
514 		if (!p) {
515 			kprintf("[TTM] Unable to get page %u\n", i);
516 
517 			/* store already allocated pages in the pool after
518 			 * setting the caching state */
519 			if (cpages) {
520 				r = ttm_set_pages_caching(caching_array,
521 							  cstate, cpages);
522 				if (r)
523 					ttm_handle_caching_state_failure(pages,
524 						ttm_flags, cstate,
525 						caching_array, cpages);
526 			}
527 			r = -ENOMEM;
528 			goto out;
529 		}
530 #if 0
531 		p->oflags &= ~VPO_UNMANAGED;
532 #endif
533 		p->flags |= PG_FICTITIOUS;
534 
535 #ifdef CONFIG_HIGHMEM /* KIB: nop */
536 		/* gfp flags of highmem page should never be dma32 so we
537 		 * we should be fine in such case
538 		 */
539 		if (!PageHighMem(p))
540 #endif
541 		{
542 			caching_array[cpages++] = p;
543 			if (cpages == max_cpages) {
544 
545 				r = ttm_set_pages_caching(caching_array,
546 						cstate, cpages);
547 				if (r) {
548 					ttm_handle_caching_state_failure(pages,
549 						ttm_flags, cstate,
550 						caching_array, cpages);
551 					goto out;
552 				}
553 				cpages = 0;
554 			}
555 		}
556 
557 		TAILQ_INSERT_HEAD(pages, p, pageq);
558 	}
559 
560 	if (cpages) {
561 		r = ttm_set_pages_caching(caching_array, cstate, cpages);
562 		if (r)
563 			ttm_handle_caching_state_failure(pages,
564 					ttm_flags, cstate,
565 					caching_array, cpages);
566 	}
567 out:
568 	drm_free(caching_array, M_TEMP);
569 
570 	return r;
571 }
572 
573 /**
574  * Fill the given pool if there aren't enough pages and the requested number of
575  * pages is small.
576  */
577 static void ttm_page_pool_fill_locked(struct ttm_page_pool *pool,
578     int ttm_flags, enum ttm_caching_state cstate, unsigned count)
579 {
580 	vm_page_t p;
581 	int r;
582 	unsigned cpages = 0;
583 	/**
584 	 * Only allow one pool fill operation at a time.
585 	 * If pool doesn't have enough pages for the allocation new pages are
586 	 * allocated from outside of pool.
587 	 */
588 	if (pool->fill_lock)
589 		return;
590 
591 	pool->fill_lock = true;
592 
593 	/* If allocation request is small and there are not enough
594 	 * pages in a pool we fill the pool up first. */
595 	if (count < _manager->options.small
596 		&& count > pool->npages) {
597 		struct pglist new_pages;
598 		unsigned alloc_size = _manager->options.alloc_size;
599 
600 		/**
601 		 * Can't change page caching if in irqsave context. We have to
602 		 * drop the pool->lock.
603 		 */
604 		lockmgr(&pool->lock, LK_RELEASE);
605 
606 		TAILQ_INIT(&new_pages);
607 		r = ttm_alloc_new_pages(&new_pages, pool->ttm_page_alloc_flags,
608 		    ttm_flags, cstate, alloc_size);
609 		lockmgr(&pool->lock, LK_EXCLUSIVE);
610 
611 		if (!r) {
612 			TAILQ_CONCAT(&pool->list, &new_pages, pageq);
613 			++pool->nrefills;
614 			pool->npages += alloc_size;
615 		} else {
616 			kprintf("[TTM] Failed to fill pool (%p)\n", pool);
617 			/* If we have any pages left put them to the pool. */
618 			TAILQ_FOREACH(p, &pool->list, pageq) {
619 				++cpages;
620 			}
621 			TAILQ_CONCAT(&pool->list, &new_pages, pageq);
622 			pool->npages += cpages;
623 		}
624 
625 	}
626 	pool->fill_lock = false;
627 }
628 
629 /**
630  * Cut 'count' number of pages from the pool and put them on the return list.
631  *
632  * @return count of pages still required to fulfill the request.
633  */
634 static unsigned ttm_page_pool_get_pages(struct ttm_page_pool *pool,
635 					struct pglist *pages,
636 					int ttm_flags,
637 					enum ttm_caching_state cstate,
638 					unsigned count)
639 {
640 	vm_page_t p;
641 	unsigned i;
642 
643 	lockmgr(&pool->lock, LK_EXCLUSIVE);
644 	ttm_page_pool_fill_locked(pool, ttm_flags, cstate, count);
645 
646 	if (count >= pool->npages) {
647 		/* take all pages from the pool */
648 		TAILQ_CONCAT(pages, &pool->list, pageq);
649 		count -= pool->npages;
650 		pool->npages = 0;
651 		goto out;
652 	}
653 	for (i = 0; i < count; i++) {
654 		p = TAILQ_FIRST(&pool->list);
655 		TAILQ_REMOVE(&pool->list, p, pageq);
656 		TAILQ_INSERT_TAIL(pages, p, pageq);
657 	}
658 	pool->npages -= count;
659 	count = 0;
660 out:
661 	lockmgr(&pool->lock, LK_RELEASE);
662 	return count;
663 }
664 
665 /* Put all pages in pages list to correct pool to wait for reuse */
666 static void ttm_put_pages(vm_page_t *pages, unsigned npages, int flags,
667 			  enum ttm_caching_state cstate)
668 {
669 	struct ttm_page_pool *pool = ttm_get_pool(flags, cstate);
670 	unsigned i;
671 
672 	if (pool == NULL) {
673 		/* No pool for this memory type so free the pages */
674 		for (i = 0; i < npages; i++) {
675 			if (pages[i]) {
676 				ttm_vm_page_free(pages[i]);
677 				pages[i] = NULL;
678 			}
679 		}
680 		return;
681 	}
682 
683 	lockmgr(&pool->lock, LK_EXCLUSIVE);
684 	for (i = 0; i < npages; i++) {
685 		if (pages[i]) {
686 			TAILQ_INSERT_TAIL(&pool->list, pages[i], pageq);
687 			pages[i] = NULL;
688 			pool->npages++;
689 		}
690 	}
691 	/* Check that we don't go over the pool limit */
692 	npages = 0;
693 	if (pool->npages > _manager->options.max_size) {
694 		npages = pool->npages - _manager->options.max_size;
695 		/* free at least NUM_PAGES_TO_ALLOC number of pages
696 		 * to reduce calls to set_memory_wb */
697 		if (npages < NUM_PAGES_TO_ALLOC)
698 			npages = NUM_PAGES_TO_ALLOC;
699 	}
700 	lockmgr(&pool->lock, LK_RELEASE);
701 	if (npages)
702 		ttm_page_pool_free(pool, npages);
703 }
704 
705 /*
706  * On success pages list will hold count number of correctly
707  * cached pages.
708  */
709 static int ttm_get_pages(vm_page_t *pages, unsigned npages, int flags,
710 			 enum ttm_caching_state cstate)
711 {
712 	struct ttm_page_pool *pool = ttm_get_pool(flags, cstate);
713 	struct pglist plist;
714 	vm_page_t p = NULL;
715 	int gfp_flags, aflags;
716 	unsigned count;
717 	int r;
718 
719 	aflags = VM_ALLOC_NORMAL |
720 	    ((flags & TTM_PAGE_FLAG_ZERO_ALLOC) != 0 ? VM_ALLOC_ZERO : 0);
721 
722 	/* No pool for cached pages */
723 	if (pool == NULL) {
724 		for (r = 0; r < npages; ++r) {
725 			p = vm_page_alloc_contig(0,
726 			    (flags & TTM_PAGE_FLAG_DMA32) ? 0xffffffff :
727 			    VM_MAX_ADDRESS, PAGE_SIZE,
728 			    0, 1*PAGE_SIZE, ttm_caching_state_to_vm(cstate));
729 			if (!p) {
730 				kprintf("[TTM] Unable to allocate page\n");
731 				return -ENOMEM;
732 			}
733 #if 0
734 			p->oflags &= ~VPO_UNMANAGED;
735 #endif
736 			p->flags |= PG_FICTITIOUS;
737 			pages[r] = p;
738 		}
739 		return 0;
740 	}
741 
742 	/* combine zero flag to pool flags */
743 	gfp_flags = flags | pool->ttm_page_alloc_flags;
744 
745 	/* First we take pages from the pool */
746 	TAILQ_INIT(&plist);
747 	npages = ttm_page_pool_get_pages(pool, &plist, flags, cstate, npages);
748 	count = 0;
749 	TAILQ_FOREACH(p, &plist, pageq) {
750 		pages[count++] = p;
751 	}
752 
753 	/* clear the pages coming from the pool if requested */
754 	if (flags & TTM_PAGE_FLAG_ZERO_ALLOC) {
755 		TAILQ_FOREACH(p, &plist, pageq) {
756 			pmap_zero_page(VM_PAGE_TO_PHYS(p));
757 		}
758 	}
759 
760 	/* If pool didn't have enough pages allocate new one. */
761 	if (npages > 0) {
762 		/* ttm_alloc_new_pages doesn't reference pool so we can run
763 		 * multiple requests in parallel.
764 		 **/
765 		TAILQ_INIT(&plist);
766 		r = ttm_alloc_new_pages(&plist, gfp_flags, flags, cstate,
767 		    npages);
768 		TAILQ_FOREACH(p, &plist, pageq) {
769 			pages[count++] = p;
770 		}
771 		if (r) {
772 			/* If there is any pages in the list put them back to
773 			 * the pool. */
774 			kprintf("[TTM] Failed to allocate extra pages for large request\n");
775 			ttm_put_pages(pages, count, flags, cstate);
776 			return r;
777 		}
778 	}
779 
780 	return 0;
781 }
782 
783 static void ttm_page_pool_init_locked(struct ttm_page_pool *pool, int flags,
784 				      char *name)
785 {
786 	lockinit(&pool->lock, "ttmpool", 0, LK_CANRECURSE);
787 	pool->fill_lock = false;
788 	TAILQ_INIT(&pool->list);
789 	pool->npages = pool->nfrees = 0;
790 	pool->ttm_page_alloc_flags = flags;
791 	pool->name = name;
792 }
793 
794 int ttm_page_alloc_init(struct ttm_mem_global *glob, unsigned max_pages)
795 {
796 
797 	if (_manager != NULL)
798 		kprintf("[TTM] manager != NULL\n");
799 	kprintf("[TTM] Initializing pool allocator\n");
800 
801 	_manager = kmalloc(sizeof(*_manager), M_DRM, M_WAITOK | M_ZERO);
802 
803 	ttm_page_pool_init_locked(&_manager->wc_pool, 0, "wc");
804 	ttm_page_pool_init_locked(&_manager->uc_pool, 0, "uc");
805 	ttm_page_pool_init_locked(&_manager->wc_pool_dma32,
806 	    TTM_PAGE_FLAG_DMA32, "wc dma");
807 	ttm_page_pool_init_locked(&_manager->uc_pool_dma32,
808 	    TTM_PAGE_FLAG_DMA32, "uc dma");
809 
810 	_manager->options.max_size = max_pages;
811 	_manager->options.small = SMALL_ALLOCATION;
812 	_manager->options.alloc_size = NUM_PAGES_TO_ALLOC;
813 
814 	refcount_init(&_manager->kobj_ref, 1);
815 	ttm_pool_mm_shrink_init(_manager);
816 
817 	return 0;
818 }
819 
820 void ttm_page_alloc_fini(void)
821 {
822 	int i;
823 
824 	kprintf("[TTM] Finalizing pool allocator\n");
825 	ttm_pool_mm_shrink_fini(_manager);
826 
827 	for (i = 0; i < NUM_POOLS; ++i)
828 		ttm_page_pool_free(&_manager->pools[i], FREE_ALL_PAGES);
829 
830 	if (refcount_release(&_manager->kobj_ref))
831 		ttm_pool_kobj_release(_manager);
832 	_manager = NULL;
833 }
834 
835 int ttm_pool_populate(struct ttm_tt *ttm)
836 {
837 	struct ttm_mem_global *mem_glob = ttm->glob->mem_glob;
838 	unsigned i;
839 	int ret;
840 
841 	if (ttm->state != tt_unpopulated)
842 		return 0;
843 
844 	for (i = 0; i < ttm->num_pages; ++i) {
845 		ret = ttm_get_pages(&ttm->pages[i], 1,
846 				    ttm->page_flags,
847 				    ttm->caching_state);
848 		if (ret != 0) {
849 			ttm_pool_unpopulate(ttm);
850 			return -ENOMEM;
851 		}
852 
853 		ret = ttm_mem_global_alloc_page(mem_glob, ttm->pages[i],
854 						false, false);
855 		if (unlikely(ret != 0)) {
856 			ttm_pool_unpopulate(ttm);
857 			return -ENOMEM;
858 		}
859 	}
860 
861 	if (unlikely(ttm->page_flags & TTM_PAGE_FLAG_SWAPPED)) {
862 		ret = ttm_tt_swapin(ttm);
863 		if (unlikely(ret != 0)) {
864 			ttm_pool_unpopulate(ttm);
865 			return ret;
866 		}
867 	}
868 
869 	ttm->state = tt_unbound;
870 	return 0;
871 }
872 
873 void ttm_pool_unpopulate(struct ttm_tt *ttm)
874 {
875 	unsigned i;
876 
877 	for (i = 0; i < ttm->num_pages; ++i) {
878 		if (ttm->pages[i]) {
879 			ttm_mem_global_free_page(ttm->glob->mem_glob,
880 						 ttm->pages[i]);
881 			ttm_put_pages(&ttm->pages[i], 1,
882 				      ttm->page_flags,
883 				      ttm->caching_state);
884 		}
885 	}
886 	ttm->state = tt_unpopulated;
887 }
888 
889 #if 0
890 /* XXXKIB sysctl */
891 int ttm_page_alloc_debugfs(struct seq_file *m, void *data)
892 {
893 	struct ttm_page_pool *p;
894 	unsigned i;
895 	char *h[] = {"pool", "refills", "pages freed", "size"};
896 	if (!_manager) {
897 		seq_printf(m, "No pool allocator running.\n");
898 		return 0;
899 	}
900 	seq_printf(m, "%6s %12s %13s %8s\n",
901 			h[0], h[1], h[2], h[3]);
902 	for (i = 0; i < NUM_POOLS; ++i) {
903 		p = &_manager->pools[i];
904 
905 		seq_printf(m, "%6s %12ld %13ld %8d\n",
906 				p->name, p->nrefills,
907 				p->nfrees, p->npages);
908 	}
909 	return 0;
910 }
911 #endif
912