xref: /freebsd/sys/compat/linuxkpi/common/src/linux_page.c (revision 2008043f386721d58158e37e0d7e50df8095942d)
1 /*-
2  * Copyright (c) 2010 Isilon Systems, Inc.
3  * Copyright (c) 2016 Matthew Macy (mmacy@mattmacy.io)
4  * Copyright (c) 2017 Mellanox Technologies, Ltd.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions, and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/malloc.h>
33 #include <sys/kernel.h>
34 #include <sys/sysctl.h>
35 #include <sys/lock.h>
36 #include <sys/mutex.h>
37 #include <sys/rwlock.h>
38 #include <sys/proc.h>
39 #include <sys/sched.h>
40 #include <sys/memrange.h>
41 
42 #include <machine/bus.h>
43 
44 #include <vm/vm.h>
45 #include <vm/pmap.h>
46 #include <vm/vm_param.h>
47 #include <vm/vm_kern.h>
48 #include <vm/vm_object.h>
49 #include <vm/vm_map.h>
50 #include <vm/vm_page.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_pager.h>
53 #include <vm/vm_radix.h>
54 #include <vm/vm_reserv.h>
55 #include <vm/vm_extern.h>
56 
57 #include <vm/uma.h>
58 #include <vm/uma_int.h>
59 
60 #include <linux/gfp.h>
61 #include <linux/mm.h>
62 #include <linux/preempt.h>
63 #include <linux/fs.h>
64 #include <linux/shmem_fs.h>
65 #include <linux/kernel.h>
66 #include <linux/idr.h>
67 #include <linux/io.h>
68 #include <linux/io-mapping.h>
69 
70 #ifdef __i386__
71 DEFINE_IDR(mtrr_idr);
72 static MALLOC_DEFINE(M_LKMTRR, "idr", "Linux MTRR compat");
73 extern int pat_works;
74 #endif
75 
76 void
77 si_meminfo(struct sysinfo *si)
78 {
79 	si->totalram = physmem;
80 	si->freeram = vm_free_count();
81 	si->totalhigh = 0;
82 	si->freehigh = 0;
83 	si->mem_unit = PAGE_SIZE;
84 }
85 
86 void *
87 linux_page_address(struct page *page)
88 {
89 
90 	if (page->object != kernel_object) {
91 		return (PMAP_HAS_DMAP ?
92 		    ((void *)(uintptr_t)PHYS_TO_DMAP(page_to_phys(page))) :
93 		    NULL);
94 	}
95 	return ((void *)(uintptr_t)(VM_MIN_KERNEL_ADDRESS +
96 	    IDX_TO_OFF(page->pindex)));
97 }
98 
99 struct page *
100 linux_alloc_pages(gfp_t flags, unsigned int order)
101 {
102 	struct page *page;
103 
104 	if (PMAP_HAS_DMAP) {
105 		unsigned long npages = 1UL << order;
106 		int req = VM_ALLOC_WIRED;
107 
108 		if ((flags & M_ZERO) != 0)
109 			req |= VM_ALLOC_ZERO;
110 		if (order == 0 && (flags & GFP_DMA32) == 0) {
111 			page = vm_page_alloc_noobj(req);
112 			if (page == NULL)
113 				return (NULL);
114 		} else {
115 			vm_paddr_t pmax = (flags & GFP_DMA32) ?
116 			    BUS_SPACE_MAXADDR_32BIT : BUS_SPACE_MAXADDR;
117 		retry:
118 			page = vm_page_alloc_noobj_contig(req, npages, 0, pmax,
119 			    PAGE_SIZE, 0, VM_MEMATTR_DEFAULT);
120 			if (page == NULL) {
121 				if (flags & M_WAITOK) {
122 					if (!vm_page_reclaim_contig(req,
123 					    npages, 0, pmax, PAGE_SIZE, 0)) {
124 						vm_wait(NULL);
125 					}
126 					flags &= ~M_WAITOK;
127 					goto retry;
128 				}
129 				return (NULL);
130 			}
131 		}
132 	} else {
133 		vm_offset_t vaddr;
134 
135 		vaddr = linux_alloc_kmem(flags, order);
136 		if (vaddr == 0)
137 			return (NULL);
138 
139 		page = virt_to_page((void *)vaddr);
140 
141 		KASSERT(vaddr == (vm_offset_t)page_address(page),
142 		    ("Page address mismatch"));
143 	}
144 
145 	return (page);
146 }
147 
148 static void
149 _linux_free_kmem(vm_offset_t addr, unsigned int order)
150 {
151 	size_t size = ((size_t)PAGE_SIZE) << order;
152 
153 	kmem_free((void *)addr, size);
154 }
155 
156 void
157 linux_free_pages(struct page *page, unsigned int order)
158 {
159 	if (PMAP_HAS_DMAP) {
160 		unsigned long npages = 1UL << order;
161 		unsigned long x;
162 
163 		for (x = 0; x != npages; x++) {
164 			vm_page_t pgo = page + x;
165 
166 			if (vm_page_unwire_noq(pgo))
167 				vm_page_free(pgo);
168 		}
169 	} else {
170 		vm_offset_t vaddr;
171 
172 		vaddr = (vm_offset_t)page_address(page);
173 
174 		_linux_free_kmem(vaddr, order);
175 	}
176 }
177 
178 vm_offset_t
179 linux_alloc_kmem(gfp_t flags, unsigned int order)
180 {
181 	size_t size = ((size_t)PAGE_SIZE) << order;
182 	void *addr;
183 
184 	if ((flags & GFP_DMA32) == 0) {
185 		addr = kmem_malloc(size, flags & GFP_NATIVE_MASK);
186 	} else {
187 		addr = kmem_alloc_contig(size, flags & GFP_NATIVE_MASK, 0,
188 		    BUS_SPACE_MAXADDR_32BIT, PAGE_SIZE, 0, VM_MEMATTR_DEFAULT);
189 	}
190 	return ((vm_offset_t)addr);
191 }
192 
193 void
194 linux_free_kmem(vm_offset_t addr, unsigned int order)
195 {
196 	KASSERT((addr & ~PAGE_MASK) == 0,
197 	    ("%s: addr %p is not page aligned", __func__, (void *)addr));
198 
199 	if (addr >= VM_MIN_KERNEL_ADDRESS && addr < VM_MAX_KERNEL_ADDRESS) {
200 		_linux_free_kmem(addr, order);
201 	} else {
202 		vm_page_t page;
203 
204 		page = PHYS_TO_VM_PAGE(DMAP_TO_PHYS(addr));
205 		linux_free_pages(page, order);
206 	}
207 }
208 
209 static int
210 linux_get_user_pages_internal(vm_map_t map, unsigned long start, int nr_pages,
211     int write, struct page **pages)
212 {
213 	vm_prot_t prot;
214 	size_t len;
215 	int count;
216 
217 	prot = write ? (VM_PROT_READ | VM_PROT_WRITE) : VM_PROT_READ;
218 	len = ptoa((vm_offset_t)nr_pages);
219 	count = vm_fault_quick_hold_pages(map, start, len, prot, pages, nr_pages);
220 	return (count == -1 ? -EFAULT : nr_pages);
221 }
222 
223 int
224 __get_user_pages_fast(unsigned long start, int nr_pages, int write,
225     struct page **pages)
226 {
227 	vm_map_t map;
228 	vm_page_t *mp;
229 	vm_offset_t va;
230 	vm_offset_t end;
231 	vm_prot_t prot;
232 	int count;
233 
234 	if (nr_pages == 0 || in_interrupt())
235 		return (0);
236 
237 	MPASS(pages != NULL);
238 	map = &curthread->td_proc->p_vmspace->vm_map;
239 	end = start + ptoa((vm_offset_t)nr_pages);
240 	if (!vm_map_range_valid(map, start, end))
241 		return (-EINVAL);
242 	prot = write ? (VM_PROT_READ | VM_PROT_WRITE) : VM_PROT_READ;
243 	for (count = 0, mp = pages, va = start; va < end;
244 	    mp++, va += PAGE_SIZE, count++) {
245 		*mp = pmap_extract_and_hold(map->pmap, va, prot);
246 		if (*mp == NULL)
247 			break;
248 
249 		if ((prot & VM_PROT_WRITE) != 0 &&
250 		    (*mp)->dirty != VM_PAGE_BITS_ALL) {
251 			/*
252 			 * Explicitly dirty the physical page.  Otherwise, the
253 			 * caller's changes may go unnoticed because they are
254 			 * performed through an unmanaged mapping or by a DMA
255 			 * operation.
256 			 *
257 			 * The object lock is not held here.
258 			 * See vm_page_clear_dirty_mask().
259 			 */
260 			vm_page_dirty(*mp);
261 		}
262 	}
263 	return (count);
264 }
265 
266 long
267 get_user_pages_remote(struct task_struct *task, struct mm_struct *mm,
268     unsigned long start, unsigned long nr_pages, unsigned int gup_flags,
269     struct page **pages, struct vm_area_struct **vmas)
270 {
271 	vm_map_t map;
272 
273 	map = &task->task_thread->td_proc->p_vmspace->vm_map;
274 	return (linux_get_user_pages_internal(map, start, nr_pages,
275 	    !!(gup_flags & FOLL_WRITE), pages));
276 }
277 
278 long
279 get_user_pages(unsigned long start, unsigned long nr_pages,
280     unsigned int gup_flags, struct page **pages, struct vm_area_struct **vmas)
281 {
282 	vm_map_t map;
283 
284 	map = &curthread->td_proc->p_vmspace->vm_map;
285 	return (linux_get_user_pages_internal(map, start, nr_pages,
286 	    !!(gup_flags & FOLL_WRITE), pages));
287 }
288 
289 int
290 is_vmalloc_addr(const void *addr)
291 {
292 	return (vtoslab((vm_offset_t)addr & ~UMA_SLAB_MASK) != NULL);
293 }
294 
295 vm_fault_t
296 lkpi_vmf_insert_pfn_prot_locked(struct vm_area_struct *vma, unsigned long addr,
297     unsigned long pfn, pgprot_t prot)
298 {
299 	vm_object_t vm_obj = vma->vm_obj;
300 	vm_object_t tmp_obj;
301 	vm_page_t page;
302 	vm_pindex_t pindex;
303 
304 	VM_OBJECT_ASSERT_WLOCKED(vm_obj);
305 	pindex = OFF_TO_IDX(addr - vma->vm_start);
306 	if (vma->vm_pfn_count == 0)
307 		vma->vm_pfn_first = pindex;
308 	MPASS(pindex <= OFF_TO_IDX(vma->vm_end));
309 
310 retry:
311 	page = vm_page_grab(vm_obj, pindex, VM_ALLOC_NOCREAT);
312 	if (page == NULL) {
313 		page = PHYS_TO_VM_PAGE(IDX_TO_OFF(pfn));
314 		if (!vm_page_busy_acquire(page, VM_ALLOC_WAITFAIL))
315 			goto retry;
316 		if (page->object != NULL) {
317 			tmp_obj = page->object;
318 			vm_page_xunbusy(page);
319 			VM_OBJECT_WUNLOCK(vm_obj);
320 			VM_OBJECT_WLOCK(tmp_obj);
321 			if (page->object == tmp_obj &&
322 			    vm_page_busy_acquire(page, VM_ALLOC_WAITFAIL)) {
323 				KASSERT(page->object == tmp_obj,
324 				    ("page has changed identity"));
325 				KASSERT((page->oflags & VPO_UNMANAGED) == 0,
326 				    ("page does not belong to shmem"));
327 				vm_pager_page_unswapped(page);
328 				if (pmap_page_is_mapped(page)) {
329 					vm_page_xunbusy(page);
330 					VM_OBJECT_WUNLOCK(tmp_obj);
331 					printf("%s: page rename failed: page "
332 					    "is mapped\n", __func__);
333 					VM_OBJECT_WLOCK(vm_obj);
334 					return (VM_FAULT_NOPAGE);
335 				}
336 				vm_page_remove(page);
337 			}
338 			VM_OBJECT_WUNLOCK(tmp_obj);
339 			VM_OBJECT_WLOCK(vm_obj);
340 			goto retry;
341 		}
342 		if (vm_page_insert(page, vm_obj, pindex)) {
343 			vm_page_xunbusy(page);
344 			return (VM_FAULT_OOM);
345 		}
346 		vm_page_valid(page);
347 	}
348 	pmap_page_set_memattr(page, pgprot2cachemode(prot));
349 	vma->vm_pfn_count++;
350 
351 	return (VM_FAULT_NOPAGE);
352 }
353 
354 int
355 lkpi_remap_pfn_range(struct vm_area_struct *vma, unsigned long start_addr,
356     unsigned long start_pfn, unsigned long size, pgprot_t prot)
357 {
358 	vm_object_t vm_obj;
359 	unsigned long addr, pfn;
360 	int err = 0;
361 
362 	vm_obj = vma->vm_obj;
363 
364 	VM_OBJECT_WLOCK(vm_obj);
365 	for (addr = start_addr, pfn = start_pfn;
366 	    addr < start_addr + size;
367 	    addr += PAGE_SIZE) {
368 		vm_fault_t ret;
369 retry:
370 		ret = lkpi_vmf_insert_pfn_prot_locked(vma, addr, pfn, prot);
371 
372 		if ((ret & VM_FAULT_OOM) != 0) {
373 			VM_OBJECT_WUNLOCK(vm_obj);
374 			vm_wait(NULL);
375 			VM_OBJECT_WLOCK(vm_obj);
376 			goto retry;
377 		}
378 
379 		if ((ret & VM_FAULT_ERROR) != 0) {
380 			err = -EFAULT;
381 			break;
382 		}
383 
384 		pfn++;
385 	}
386 	VM_OBJECT_WUNLOCK(vm_obj);
387 
388 	if (unlikely(err)) {
389 		zap_vma_ptes(vma, start_addr,
390 		    (pfn - start_pfn) << PAGE_SHIFT);
391 		return (err);
392 	}
393 
394 	return (0);
395 }
396 
397 int
398 lkpi_io_mapping_map_user(struct io_mapping *iomap,
399     struct vm_area_struct *vma, unsigned long addr,
400     unsigned long pfn, unsigned long size)
401 {
402 	pgprot_t prot;
403 	int ret;
404 
405 	prot = cachemode2protval(iomap->attr);
406 	ret = lkpi_remap_pfn_range(vma, addr, pfn, size, prot);
407 
408 	return (ret);
409 }
410 
411 /*
412  * Although FreeBSD version of unmap_mapping_range has semantics and types of
413  * parameters compatible with Linux version, the values passed in are different
414  * @obj should match to vm_private_data field of vm_area_struct returned by
415  *      mmap file operation handler, see linux_file_mmap_single() sources
416  * @holelen should match to size of area to be munmapped.
417  */
418 void
419 lkpi_unmap_mapping_range(void *obj, loff_t const holebegin __unused,
420     loff_t const holelen, int even_cows __unused)
421 {
422 	vm_object_t devobj;
423 	vm_page_t page;
424 	int i, page_count;
425 
426 	devobj = cdev_pager_lookup(obj);
427 	if (devobj != NULL) {
428 		page_count = OFF_TO_IDX(holelen);
429 
430 		VM_OBJECT_WLOCK(devobj);
431 retry:
432 		for (i = 0; i < page_count; i++) {
433 			page = vm_page_lookup(devobj, i);
434 			if (page == NULL)
435 				continue;
436 			if (!vm_page_busy_acquire(page, VM_ALLOC_WAITFAIL))
437 				goto retry;
438 			cdev_pager_free_page(devobj, page);
439 		}
440 		VM_OBJECT_WUNLOCK(devobj);
441 		vm_object_deallocate(devobj);
442 	}
443 }
444 
445 int
446 lkpi_arch_phys_wc_add(unsigned long base, unsigned long size)
447 {
448 #ifdef __i386__
449 	struct mem_range_desc *mrdesc;
450 	int error, id, act;
451 
452 	/* If PAT is available, do nothing */
453 	if (pat_works)
454 		return (0);
455 
456 	mrdesc = malloc(sizeof(*mrdesc), M_LKMTRR, M_WAITOK);
457 	mrdesc->mr_base = base;
458 	mrdesc->mr_len = size;
459 	mrdesc->mr_flags = MDF_WRITECOMBINE;
460 	strlcpy(mrdesc->mr_owner, "drm", sizeof(mrdesc->mr_owner));
461 	act = MEMRANGE_SET_UPDATE;
462 	error = mem_range_attr_set(mrdesc, &act);
463 	if (error == 0) {
464 		error = idr_get_new(&mtrr_idr, mrdesc, &id);
465 		MPASS(idr_find(&mtrr_idr, id) == mrdesc);
466 		if (error != 0) {
467 			act = MEMRANGE_SET_REMOVE;
468 			mem_range_attr_set(mrdesc, &act);
469 		}
470 	}
471 	if (error != 0) {
472 		free(mrdesc, M_LKMTRR);
473 		pr_warn(
474 		    "Failed to add WC MTRR for [%p-%p]: %d; "
475 		    "performance may suffer\n",
476 		    (void *)base, (void *)(base + size - 1), error);
477 	} else
478 		pr_warn("Successfully added WC MTRR for [%p-%p]\n",
479 		    (void *)base, (void *)(base + size - 1));
480 
481 	return (error != 0 ? -error : id + __MTRR_ID_BASE);
482 #else
483 	return (0);
484 #endif
485 }
486 
487 void
488 lkpi_arch_phys_wc_del(int reg)
489 {
490 #ifdef __i386__
491 	struct mem_range_desc *mrdesc;
492 	int act;
493 
494 	/* Check if arch_phys_wc_add() failed. */
495 	if (reg < __MTRR_ID_BASE)
496 		return;
497 
498 	mrdesc = idr_find(&mtrr_idr, reg - __MTRR_ID_BASE);
499 	MPASS(mrdesc != NULL);
500 	idr_remove(&mtrr_idr, reg - __MTRR_ID_BASE);
501 	act = MEMRANGE_SET_REMOVE;
502 	mem_range_attr_set(mrdesc, &act);
503 	free(mrdesc, M_LKMTRR);
504 #endif
505 }
506 
507 /*
508  * This is a highly simplified version of the Linux page_frag_cache.
509  * We only support up-to 1 single page as fragment size and we will
510  * always return a full page.  This may be wasteful on small objects
511  * but the only known consumer (mt76) is either asking for a half-page
512  * or a full page.  If this was to become a problem we can implement
513  * a more elaborate version.
514  */
515 void *
516 linuxkpi_page_frag_alloc(struct page_frag_cache *pfc,
517     size_t fragsz, gfp_t gfp)
518 {
519 	vm_page_t pages;
520 
521 	if (fragsz == 0)
522 		return (NULL);
523 
524 	KASSERT(fragsz <= PAGE_SIZE, ("%s: fragsz %zu > PAGE_SIZE not yet "
525 	    "supported", __func__, fragsz));
526 
527 	pages = alloc_pages(gfp, flsl(howmany(fragsz, PAGE_SIZE) - 1));
528 	if (pages == NULL)
529 		return (NULL);
530 	pfc->va = linux_page_address(pages);
531 
532 	/* Passed in as "count" to __page_frag_cache_drain(). Unused by us. */
533 	pfc->pagecnt_bias = 0;
534 
535 	return (pfc->va);
536 }
537 
538 void
539 linuxkpi_page_frag_free(void *addr)
540 {
541 	vm_page_t page;
542 
543 	page = virt_to_page(addr);
544 	linux_free_pages(page, 0);
545 }
546 
547 void
548 linuxkpi__page_frag_cache_drain(struct page *page, size_t count __unused)
549 {
550 
551 	linux_free_pages(page, 0);
552 }
553