VirtualBox

source: vbox/trunk/src/VBox/Runtime/r0drv/linux/memobj-r0drv-linux.c@ 100356

Last change on this file since 100356 was 100356, checked in by vboxsync, 17 months ago

Runtime/RTR0MemObj*: Add PhysHighest parameter to RTR0MemObjAllocCont to indicate the maximum allowed physical address for an allocation, bugref:10457 [revert due to build failures]

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Rev Revision
File size: 71.2 KB
Line 
1/* $Id: memobj-r0drv-linux.c 100356 2023-07-04 06:41:38Z vboxsync $ */
2/** @file
3 * IPRT - Ring-0 Memory Objects, Linux.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#include "the-linux-kernel.h"
42
43#include <iprt/memobj.h>
44#include <iprt/assert.h>
45#include <iprt/err.h>
46#include <iprt/log.h>
47#include <iprt/mem.h>
48#include <iprt/process.h>
49#include <iprt/string.h>
50#include "internal/memobj.h"
51#include "internal/iprt.h"
52
53
54/*********************************************************************************************************************************
55* Defined Constants And Macros *
56*********************************************************************************************************************************/
57/* early 2.6 kernels */
58#ifndef PAGE_SHARED_EXEC
59# define PAGE_SHARED_EXEC PAGE_SHARED
60#endif
61#ifndef PAGE_READONLY_EXEC
62# define PAGE_READONLY_EXEC PAGE_READONLY
63#endif
64
65/** @def IPRT_USE_ALLOC_VM_AREA_FOR_EXEC
66 * Whether we use alloc_vm_area (3.2+) for executable memory.
67 * This is a must for 5.8+, but we enable it all the way back to 3.2.x for
68 * better W^R compliance (fExecutable flag). */
69#if RTLNX_VER_RANGE(3,2,0, 5,10,0) || defined(DOXYGEN_RUNNING)
70# define IPRT_USE_ALLOC_VM_AREA_FOR_EXEC
71#endif
72/** @def IPRT_USE_APPLY_TO_PAGE_RANGE_FOR_EXEC
73 * alloc_vm_area was removed with 5.10 so we have to resort to a different way
74 * to allocate executable memory.
75 * It would be possible to remove IPRT_USE_ALLOC_VM_AREA_FOR_EXEC and use
76 * this path execlusively for 3.2+ but no time to test it really works on every
77 * supported kernel, so better play safe for now.
78 */
79#if RTLNX_VER_MIN(5,10,0) || defined(DOXYGEN_RUNNING)
80# define IPRT_USE_APPLY_TO_PAGE_RANGE_FOR_EXEC
81#endif
82
83/*
84 * 2.6.29+ kernels don't work with remap_pfn_range() anymore because
85 * track_pfn_vma_new() is apparently not defined for non-RAM pages.
86 * It should be safe to use vm_insert_page() older kernels as well.
87 */
88#if RTLNX_VER_MIN(2,6,23)
89# define VBOX_USE_INSERT_PAGE
90#endif
91#if defined(CONFIG_X86_PAE) \
92 && ( defined(HAVE_26_STYLE_REMAP_PAGE_RANGE) \
93 || RTLNX_VER_RANGE(2,6,0, 2,6,11) )
94# define VBOX_USE_PAE_HACK
95#endif
96
97/* gfp_t was introduced in 2.6.14, define it for earlier. */
98#if RTLNX_VER_MAX(2,6,14)
99# define gfp_t unsigned
100#endif
101
102/*
103 * Wrappers around mmap_lock/mmap_sem difference.
104 */
105#if RTLNX_VER_MIN(5,8,0)
106# define LNX_MM_DOWN_READ(a_pMm) down_read(&(a_pMm)->mmap_lock)
107# define LNX_MM_UP_READ(a_pMm) up_read(&(a_pMm)->mmap_lock)
108# define LNX_MM_DOWN_WRITE(a_pMm) down_write(&(a_pMm)->mmap_lock)
109# define LNX_MM_UP_WRITE(a_pMm) up_write(&(a_pMm)->mmap_lock)
110#else
111# define LNX_MM_DOWN_READ(a_pMm) down_read(&(a_pMm)->mmap_sem)
112# define LNX_MM_UP_READ(a_pMm) up_read(&(a_pMm)->mmap_sem)
113# define LNX_MM_DOWN_WRITE(a_pMm) down_write(&(a_pMm)->mmap_sem)
114# define LNX_MM_UP_WRITE(a_pMm) up_write(&(a_pMm)->mmap_sem)
115#endif
116
117
118/*********************************************************************************************************************************
119* Structures and Typedefs *
120*********************************************************************************************************************************/
121/**
122 * The Linux version of the memory object structure.
123 */
124typedef struct RTR0MEMOBJLNX
125{
126 /** The core structure. */
127 RTR0MEMOBJINTERNAL Core;
128 /** Set if the allocation is contiguous.
129 * This means it has to be given back as one chunk. */
130 bool fContiguous;
131 /** Set if executable allocation. */
132 bool fExecutable;
133 /** Set if we've vmap'ed the memory into ring-0. */
134 bool fMappedToRing0;
135 /** This is non-zero if large page allocation. */
136 uint8_t cLargePageOrder;
137#ifdef IPRT_USE_ALLOC_VM_AREA_FOR_EXEC
138 /** Return from alloc_vm_area() that we now need to use for executable
139 * memory. */
140 struct vm_struct *pArea;
141 /** PTE array that goes along with pArea (must be freed). */
142 pte_t **papPtesForArea;
143#endif
144 /** The pages in the apPages array. */
145 size_t cPages;
146 /** Array of struct page pointers. (variable size) */
147 struct page *apPages[1];
148} RTR0MEMOBJLNX;
149/** Pointer to the linux memory object. */
150typedef RTR0MEMOBJLNX *PRTR0MEMOBJLNX;
151
152
153static void rtR0MemObjLinuxFreePages(PRTR0MEMOBJLNX pMemLnx);
154
155
156/**
157 * Helper that converts from a RTR0PROCESS handle to a linux task.
158 *
159 * @returns The corresponding Linux task.
160 * @param R0Process IPRT ring-0 process handle.
161 */
162static struct task_struct *rtR0ProcessToLinuxTask(RTR0PROCESS R0Process)
163{
164 /** @todo fix rtR0ProcessToLinuxTask!! */
165 /** @todo many (all?) callers currently assume that we return 'current'! */
166 return R0Process == RTR0ProcHandleSelf() ? current : NULL;
167}
168
169
170/**
171 * Compute order. Some functions allocate 2^order pages.
172 *
173 * @returns order.
174 * @param cPages Number of pages.
175 */
176static int rtR0MemObjLinuxOrder(size_t cPages)
177{
178 int iOrder;
179 size_t cTmp;
180
181 for (iOrder = 0, cTmp = cPages; cTmp >>= 1; ++iOrder)
182 ;
183 if (cPages & ~((size_t)1 << iOrder))
184 ++iOrder;
185
186 return iOrder;
187}
188
189
190/**
191 * Converts from RTMEM_PROT_* to Linux PAGE_*.
192 *
193 * @returns Linux page protection constant.
194 * @param fProt The IPRT protection mask.
195 * @param fKernel Whether it applies to kernel or user space.
196 */
197static pgprot_t rtR0MemObjLinuxConvertProt(unsigned fProt, bool fKernel)
198{
199 switch (fProt)
200 {
201 default:
202 AssertMsgFailed(("%#x %d\n", fProt, fKernel)); RT_FALL_THRU();
203 case RTMEM_PROT_NONE:
204 return PAGE_NONE;
205
206 case RTMEM_PROT_READ:
207 return fKernel ? PAGE_KERNEL_RO : PAGE_READONLY;
208
209 case RTMEM_PROT_WRITE:
210 case RTMEM_PROT_WRITE | RTMEM_PROT_READ:
211 return fKernel ? PAGE_KERNEL : PAGE_SHARED;
212
213 case RTMEM_PROT_EXEC:
214 case RTMEM_PROT_EXEC | RTMEM_PROT_READ:
215#if defined(RT_ARCH_X86) || defined(RT_ARCH_AMD64)
216 if (fKernel)
217 {
218 pgprot_t fPg = MY_PAGE_KERNEL_EXEC;
219 pgprot_val(fPg) &= ~_PAGE_RW;
220 return fPg;
221 }
222 return PAGE_READONLY_EXEC;
223#else
224 return fKernel ? MY_PAGE_KERNEL_EXEC : PAGE_READONLY_EXEC;
225#endif
226
227 case RTMEM_PROT_WRITE | RTMEM_PROT_EXEC:
228 case RTMEM_PROT_WRITE | RTMEM_PROT_EXEC | RTMEM_PROT_READ:
229 return fKernel ? MY_PAGE_KERNEL_EXEC : PAGE_SHARED_EXEC;
230 }
231}
232
233
234/**
235 * Worker for rtR0MemObjNativeReserveUser and rtR0MemObjNativerMapUser that creates
236 * an empty user space mapping.
237 *
238 * We acquire the mmap_sem/mmap_lock of the task!
239 *
240 * @returns Pointer to the mapping.
241 * (void *)-1 on failure.
242 * @param R3PtrFixed (RTR3PTR)-1 if anywhere, otherwise a specific location.
243 * @param cb The size of the mapping.
244 * @param uAlignment The alignment of the mapping.
245 * @param pTask The Linux task to create this mapping in.
246 * @param fProt The RTMEM_PROT_* mask.
247 */
248static void *rtR0MemObjLinuxDoMmap(RTR3PTR R3PtrFixed, size_t cb, size_t uAlignment, struct task_struct *pTask, unsigned fProt)
249{
250 unsigned fLnxProt;
251 unsigned long ulAddr;
252
253 Assert(pTask == current); /* do_mmap */
254 RT_NOREF_PV(pTask);
255
256 /*
257 * Convert from IPRT protection to mman.h PROT_ and call do_mmap.
258 */
259 fProt &= (RTMEM_PROT_NONE | RTMEM_PROT_READ | RTMEM_PROT_WRITE | RTMEM_PROT_EXEC);
260 if (fProt == RTMEM_PROT_NONE)
261 fLnxProt = PROT_NONE;
262 else
263 {
264 fLnxProt = 0;
265 if (fProt & RTMEM_PROT_READ)
266 fLnxProt |= PROT_READ;
267 if (fProt & RTMEM_PROT_WRITE)
268 fLnxProt |= PROT_WRITE;
269 if (fProt & RTMEM_PROT_EXEC)
270 fLnxProt |= PROT_EXEC;
271 }
272
273 if (R3PtrFixed != (RTR3PTR)-1)
274 {
275#if RTLNX_VER_MIN(3,5,0)
276 ulAddr = vm_mmap(NULL, R3PtrFixed, cb, fLnxProt, MAP_SHARED | MAP_ANONYMOUS | MAP_FIXED, 0);
277#else
278 LNX_MM_DOWN_WRITE(pTask->mm);
279 ulAddr = do_mmap(NULL, R3PtrFixed, cb, fLnxProt, MAP_SHARED | MAP_ANONYMOUS | MAP_FIXED, 0);
280 LNX_MM_UP_WRITE(pTask->mm);
281#endif
282 }
283 else
284 {
285#if RTLNX_VER_MIN(3,5,0)
286 ulAddr = vm_mmap(NULL, 0, cb, fLnxProt, MAP_SHARED | MAP_ANONYMOUS, 0);
287#else
288 LNX_MM_DOWN_WRITE(pTask->mm);
289 ulAddr = do_mmap(NULL, 0, cb, fLnxProt, MAP_SHARED | MAP_ANONYMOUS, 0);
290 LNX_MM_UP_WRITE(pTask->mm);
291#endif
292 if ( !(ulAddr & ~PAGE_MASK)
293 && (ulAddr & (uAlignment - 1)))
294 {
295 /** @todo implement uAlignment properly... We'll probably need to make some dummy mappings to fill
296 * up alignment gaps. This is of course complicated by fragmentation (which we might have cause
297 * ourselves) and further by there begin two mmap strategies (top / bottom). */
298 /* For now, just ignore uAlignment requirements... */
299 }
300 }
301
302
303 if (ulAddr & ~PAGE_MASK) /* ~PAGE_MASK == PAGE_OFFSET_MASK */
304 return (void *)-1;
305 return (void *)ulAddr;
306}
307
308
309/**
310 * Worker that destroys a user space mapping.
311 * Undoes what rtR0MemObjLinuxDoMmap did.
312 *
313 * We acquire the mmap_sem/mmap_lock of the task!
314 *
315 * @param pv The ring-3 mapping.
316 * @param cb The size of the mapping.
317 * @param pTask The Linux task to destroy this mapping in.
318 */
319static void rtR0MemObjLinuxDoMunmap(void *pv, size_t cb, struct task_struct *pTask)
320{
321#if RTLNX_VER_MIN(3,5,0)
322 Assert(pTask == current); RT_NOREF_PV(pTask);
323 vm_munmap((unsigned long)pv, cb);
324#elif defined(USE_RHEL4_MUNMAP)
325 LNX_MM_DOWN_WRITE(pTask->mm);
326 do_munmap(pTask->mm, (unsigned long)pv, cb, 0); /* should it be 1 or 0? */
327 LNX_MM_UP_WRITE(pTask->mm);
328#else
329 LNX_MM_DOWN_WRITE(pTask->mm);
330 do_munmap(pTask->mm, (unsigned long)pv, cb);
331 LNX_MM_UP_WRITE(pTask->mm);
332#endif
333}
334
335
336/**
337 * Internal worker that allocates physical pages and creates the memory object for them.
338 *
339 * @returns IPRT status code.
340 * @param ppMemLnx Where to store the memory object pointer.
341 * @param enmType The object type.
342 * @param cb The number of bytes to allocate.
343 * @param uAlignment The alignment of the physical memory.
344 * Only valid if fContiguous == true, ignored otherwise.
345 * @param fFlagsLnx The page allocation flags (GPFs).
346 * @param fContiguous Whether the allocation must be contiguous.
347 * @param fExecutable Whether the memory must be executable.
348 * @param rcNoMem What to return when we're out of pages.
349 * @param pszTag Allocation tag used for statistics and such.
350 */
351static int rtR0MemObjLinuxAllocPages(PRTR0MEMOBJLNX *ppMemLnx, RTR0MEMOBJTYPE enmType, size_t cb,
352 size_t uAlignment, gfp_t fFlagsLnx, bool fContiguous, bool fExecutable, int rcNoMem,
353 const char *pszTag)
354{
355 size_t iPage;
356 size_t const cPages = cb >> PAGE_SHIFT;
357 struct page *paPages;
358
359 /*
360 * Allocate a memory object structure that's large enough to contain
361 * the page pointer array.
362 */
363 PRTR0MEMOBJLNX pMemLnx = (PRTR0MEMOBJLNX)rtR0MemObjNew(RT_UOFFSETOF_DYN(RTR0MEMOBJLNX, apPages[cPages]), enmType,
364 NULL, cb, pszTag);
365 if (!pMemLnx)
366 return VERR_NO_MEMORY;
367 pMemLnx->Core.fFlags |= RTR0MEMOBJ_FLAGS_UNINITIALIZED_AT_ALLOC;
368 pMemLnx->cPages = cPages;
369
370 if (cPages > 255)
371 {
372# ifdef __GFP_REPEAT
373 /* Try hard to allocate the memory, but the allocation attempt might fail. */
374 fFlagsLnx |= __GFP_REPEAT;
375# endif
376# ifdef __GFP_NOMEMALLOC
377 /* Introduced with Linux 2.6.12: Don't use emergency reserves */
378 fFlagsLnx |= __GFP_NOMEMALLOC;
379# endif
380 }
381
382 /*
383 * Allocate the pages.
384 * For small allocations we'll try contiguous first and then fall back on page by page.
385 */
386#if RTLNX_VER_MIN(2,4,22)
387 if ( fContiguous
388 || cb <= PAGE_SIZE * 2)
389 {
390# ifdef VBOX_USE_INSERT_PAGE
391 paPages = alloc_pages(fFlagsLnx | __GFP_COMP | __GFP_NOWARN, rtR0MemObjLinuxOrder(cPages));
392# else
393 paPages = alloc_pages(fFlagsLnx | __GFP_NOWARN, rtR0MemObjLinuxOrder(cPages));
394# endif
395 if (paPages)
396 {
397 fContiguous = true;
398 for (iPage = 0; iPage < cPages; iPage++)
399 pMemLnx->apPages[iPage] = &paPages[iPage];
400 }
401 else if (fContiguous)
402 {
403 rtR0MemObjDelete(&pMemLnx->Core);
404 return rcNoMem;
405 }
406 }
407
408 if (!fContiguous)
409 {
410 /** @todo Try use alloc_pages_bulk_array when available, it should be faster
411 * than a alloc_page loop. Put it in #ifdefs similar to
412 * IPRT_USE_APPLY_TO_PAGE_RANGE_FOR_EXEC. */
413 for (iPage = 0; iPage < cPages; iPage++)
414 {
415 pMemLnx->apPages[iPage] = alloc_page(fFlagsLnx | __GFP_NOWARN);
416 if (RT_UNLIKELY(!pMemLnx->apPages[iPage]))
417 {
418 while (iPage-- > 0)
419 __free_page(pMemLnx->apPages[iPage]);
420 rtR0MemObjDelete(&pMemLnx->Core);
421 return rcNoMem;
422 }
423 }
424 }
425
426#else /* < 2.4.22 */
427 /** @todo figure out why we didn't allocate page-by-page on 2.4.21 and older... */
428 paPages = alloc_pages(fFlagsLnx, rtR0MemObjLinuxOrder(cPages));
429 if (!paPages)
430 {
431 rtR0MemObjDelete(&pMemLnx->Core);
432 return rcNoMem;
433 }
434 for (iPage = 0; iPage < cPages; iPage++)
435 {
436 pMemLnx->apPages[iPage] = &paPages[iPage];
437 if (fExecutable)
438 MY_SET_PAGES_EXEC(pMemLnx->apPages[iPage], 1);
439 if (PageHighMem(pMemLnx->apPages[iPage]))
440 BUG();
441 }
442
443 fContiguous = true;
444#endif /* < 2.4.22 */
445 pMemLnx->fContiguous = fContiguous;
446 pMemLnx->fExecutable = fExecutable;
447
448#if RTLNX_VER_MAX(4,5,0)
449 /*
450 * Reserve the pages.
451 *
452 * Linux >= 4.5 with CONFIG_DEBUG_VM panics when setting PG_reserved on compound
453 * pages. According to Michal Hocko this shouldn't be necessary anyway because
454 * as pages which are not on the LRU list are never evictable.
455 */
456 for (iPage = 0; iPage < cPages; iPage++)
457 SetPageReserved(pMemLnx->apPages[iPage]);
458#endif
459
460 /*
461 * Note that the physical address of memory allocated with alloc_pages(flags, order)
462 * is always 2^(PAGE_SHIFT+order)-aligned.
463 */
464 if ( fContiguous
465 && uAlignment > PAGE_SIZE)
466 {
467 /*
468 * Check for alignment constraints. The physical address of memory allocated with
469 * alloc_pages(flags, order) is always 2^(PAGE_SHIFT+order)-aligned.
470 */
471 if (RT_UNLIKELY(page_to_phys(pMemLnx->apPages[0]) & (uAlignment - 1)))
472 {
473 /*
474 * This should never happen!
475 */
476 printk("rtR0MemObjLinuxAllocPages(cb=0x%lx, uAlignment=0x%lx): alloc_pages(..., %d) returned physical memory at 0x%lx!\n",
477 (unsigned long)cb, (unsigned long)uAlignment, rtR0MemObjLinuxOrder(cPages), (unsigned long)page_to_phys(pMemLnx->apPages[0]));
478 rtR0MemObjLinuxFreePages(pMemLnx);
479 return rcNoMem;
480 }
481 }
482
483 *ppMemLnx = pMemLnx;
484 return VINF_SUCCESS;
485}
486
487
488/**
489 * Frees the physical pages allocated by the rtR0MemObjLinuxAllocPages() call.
490 *
491 * This method does NOT free the object.
492 *
493 * @param pMemLnx The object which physical pages should be freed.
494 */
495static void rtR0MemObjLinuxFreePages(PRTR0MEMOBJLNX pMemLnx)
496{
497 size_t iPage = pMemLnx->cPages;
498 if (iPage > 0)
499 {
500 /*
501 * Restore the page flags.
502 */
503 while (iPage-- > 0)
504 {
505#if RTLNX_VER_MAX(4,5,0)
506 /* See SetPageReserved() in rtR0MemObjLinuxAllocPages() */
507 ClearPageReserved(pMemLnx->apPages[iPage]);
508#endif
509#if RTLNX_VER_MAX(2,4,22)
510 if (pMemLnx->fExecutable)
511 MY_SET_PAGES_NOEXEC(pMemLnx->apPages[iPage], 1);
512#endif
513 }
514
515 /*
516 * Free the pages.
517 */
518#if RTLNX_VER_MIN(2,4,22)
519 if (!pMemLnx->fContiguous)
520 {
521 iPage = pMemLnx->cPages;
522 while (iPage-- > 0)
523 __free_page(pMemLnx->apPages[iPage]);
524 }
525 else
526#endif
527 __free_pages(pMemLnx->apPages[0], rtR0MemObjLinuxOrder(pMemLnx->cPages));
528
529 pMemLnx->cPages = 0;
530 }
531}
532
533
534#ifdef IPRT_USE_APPLY_TO_PAGE_RANGE_FOR_EXEC
535/**
536 * User data passed to the apply_to_page_range() callback.
537 */
538typedef struct LNXAPPLYPGRANGE
539{
540 /** Pointer to the memory object. */
541 PRTR0MEMOBJLNX pMemLnx;
542 /** The page protection flags to apply. */
543 pgprot_t fPg;
544} LNXAPPLYPGRANGE;
545/** Pointer to the user data. */
546typedef LNXAPPLYPGRANGE *PLNXAPPLYPGRANGE;
547/** Pointer to the const user data. */
548typedef const LNXAPPLYPGRANGE *PCLNXAPPLYPGRANGE;
549
550/**
551 * Callback called in apply_to_page_range().
552 *
553 * @returns Linux status code.
554 * @param pPte Pointer to the page table entry for the given address.
555 * @param uAddr The address to apply the new protection to.
556 * @param pvUser The opaque user data.
557 */
558static int rtR0MemObjLinuxApplyPageRange(pte_t *pPte, unsigned long uAddr, void *pvUser)
559{
560 PCLNXAPPLYPGRANGE pArgs = (PCLNXAPPLYPGRANGE)pvUser;
561 PRTR0MEMOBJLNX pMemLnx = pArgs->pMemLnx;
562 size_t idxPg = (uAddr - (unsigned long)pMemLnx->Core.pv) >> PAGE_SHIFT;
563
564 set_pte(pPte, mk_pte(pMemLnx->apPages[idxPg], pArgs->fPg));
565 return 0;
566}
567#endif
568
569
570/**
571 * Maps the allocation into ring-0.
572 *
573 * This will update the RTR0MEMOBJLNX::Core.pv and RTR0MEMOBJ::fMappedToRing0 members.
574 *
575 * Contiguous mappings that isn't in 'high' memory will already be mapped into kernel
576 * space, so we'll use that mapping if possible. If execute access is required, we'll
577 * play safe and do our own mapping.
578 *
579 * @returns IPRT status code.
580 * @param pMemLnx The linux memory object to map.
581 * @param fExecutable Whether execute access is required.
582 */
583static int rtR0MemObjLinuxVMap(PRTR0MEMOBJLNX pMemLnx, bool fExecutable)
584{
585 int rc = VINF_SUCCESS;
586
587 /*
588 * Choose mapping strategy.
589 */
590 bool fMustMap = fExecutable
591 || !pMemLnx->fContiguous;
592 if (!fMustMap)
593 {
594 size_t iPage = pMemLnx->cPages;
595 while (iPage-- > 0)
596 if (PageHighMem(pMemLnx->apPages[iPage]))
597 {
598 fMustMap = true;
599 break;
600 }
601 }
602
603 Assert(!pMemLnx->Core.pv);
604 Assert(!pMemLnx->fMappedToRing0);
605
606 if (fMustMap)
607 {
608 /*
609 * Use vmap - 2.4.22 and later.
610 */
611#if RTLNX_VER_MIN(2,4,22) && (defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86))
612 pgprot_t fPg;
613 pgprot_val(fPg) = _PAGE_PRESENT | _PAGE_RW;
614# ifdef _PAGE_NX
615 if (!fExecutable)
616 pgprot_val(fPg) |= _PAGE_NX;
617# endif
618
619# ifdef IPRT_USE_ALLOC_VM_AREA_FOR_EXEC
620 if (fExecutable)
621 {
622# if RTLNX_VER_MIN(3,2,51)
623 pte_t **papPtes = (pte_t **)kmalloc_array(pMemLnx->cPages, sizeof(papPtes[0]), GFP_KERNEL);
624# else
625 pte_t **papPtes = (pte_t **)kmalloc(pMemLnx->cPages * sizeof(papPtes[0]), GFP_KERNEL);
626# endif
627 if (papPtes)
628 {
629 pMemLnx->pArea = alloc_vm_area(pMemLnx->Core.cb, papPtes); /* Note! pArea->nr_pages is not set. */
630 if (pMemLnx->pArea)
631 {
632 size_t i;
633 Assert(pMemLnx->pArea->size >= pMemLnx->Core.cb); /* Note! includes guard page. */
634 Assert(pMemLnx->pArea->addr);
635# ifdef _PAGE_NX
636 pgprot_val(fPg) |= _PAGE_NX; /* Uses RTR0MemObjProtect to clear NX when memory ready, W^X fashion. */
637# endif
638 pMemLnx->papPtesForArea = papPtes;
639 for (i = 0; i < pMemLnx->cPages; i++)
640 *papPtes[i] = mk_pte(pMemLnx->apPages[i], fPg);
641 pMemLnx->Core.pv = pMemLnx->pArea->addr;
642 pMemLnx->fMappedToRing0 = true;
643 }
644 else
645 {
646 kfree(papPtes);
647 rc = VERR_MAP_FAILED;
648 }
649 }
650 else
651 rc = VERR_MAP_FAILED;
652 }
653 else
654# endif
655 {
656# if defined(IPRT_USE_APPLY_TO_PAGE_RANGE_FOR_EXEC)
657 if (fExecutable)
658 pgprot_val(fPg) |= _PAGE_NX; /* Uses RTR0MemObjProtect to clear NX when memory ready, W^X fashion. */
659# endif
660
661# ifdef VM_MAP
662 pMemLnx->Core.pv = vmap(&pMemLnx->apPages[0], pMemLnx->cPages, VM_MAP, fPg);
663# else
664 pMemLnx->Core.pv = vmap(&pMemLnx->apPages[0], pMemLnx->cPages, VM_ALLOC, fPg);
665# endif
666 if (pMemLnx->Core.pv)
667 pMemLnx->fMappedToRing0 = true;
668 else
669 rc = VERR_MAP_FAILED;
670 }
671#else /* < 2.4.22 */
672 rc = VERR_NOT_SUPPORTED;
673#endif
674 }
675 else
676 {
677 /*
678 * Use the kernel RAM mapping.
679 */
680 pMemLnx->Core.pv = phys_to_virt(page_to_phys(pMemLnx->apPages[0]));
681 Assert(pMemLnx->Core.pv);
682 }
683
684 return rc;
685}
686
687
688/**
689 * Undoes what rtR0MemObjLinuxVMap() did.
690 *
691 * @param pMemLnx The linux memory object.
692 */
693static void rtR0MemObjLinuxVUnmap(PRTR0MEMOBJLNX pMemLnx)
694{
695#if RTLNX_VER_MIN(2,4,22)
696# ifdef IPRT_USE_ALLOC_VM_AREA_FOR_EXEC
697 if (pMemLnx->pArea)
698 {
699# if 0
700 pte_t **papPtes = pMemLnx->papPtesForArea;
701 size_t i;
702 for (i = 0; i < pMemLnx->cPages; i++)
703 *papPtes[i] = 0;
704# endif
705 free_vm_area(pMemLnx->pArea);
706 kfree(pMemLnx->papPtesForArea);
707 pMemLnx->pArea = NULL;
708 pMemLnx->papPtesForArea = NULL;
709 }
710 else
711# endif
712 if (pMemLnx->fMappedToRing0)
713 {
714 Assert(pMemLnx->Core.pv);
715 vunmap(pMemLnx->Core.pv);
716 pMemLnx->fMappedToRing0 = false;
717 }
718#else /* < 2.4.22 */
719 Assert(!pMemLnx->fMappedToRing0);
720#endif
721 pMemLnx->Core.pv = NULL;
722}
723
724
725DECLHIDDEN(int) rtR0MemObjNativeFree(RTR0MEMOBJ pMem)
726{
727 IPRT_LINUX_SAVE_EFL_AC();
728 PRTR0MEMOBJLNX pMemLnx = (PRTR0MEMOBJLNX)pMem;
729
730 /*
731 * Release any memory that we've allocated or locked.
732 */
733 switch (pMemLnx->Core.enmType)
734 {
735 case RTR0MEMOBJTYPE_PAGE:
736 case RTR0MEMOBJTYPE_LOW:
737 case RTR0MEMOBJTYPE_CONT:
738 case RTR0MEMOBJTYPE_PHYS:
739 case RTR0MEMOBJTYPE_PHYS_NC:
740 rtR0MemObjLinuxVUnmap(pMemLnx);
741 rtR0MemObjLinuxFreePages(pMemLnx);
742 break;
743
744 case RTR0MEMOBJTYPE_LARGE_PAGE:
745 {
746 uint32_t const cLargePages = pMemLnx->Core.cb >> (pMemLnx->cLargePageOrder + PAGE_SHIFT);
747 uint32_t iLargePage;
748 for (iLargePage = 0; iLargePage < cLargePages; iLargePage++)
749 __free_pages(pMemLnx->apPages[iLargePage << pMemLnx->cLargePageOrder], pMemLnx->cLargePageOrder);
750 pMemLnx->cPages = 0;
751
752#ifdef IPRT_USE_ALLOC_VM_AREA_FOR_EXEC
753 Assert(!pMemLnx->pArea);
754 Assert(!pMemLnx->papPtesForArea);
755#endif
756 break;
757 }
758
759 case RTR0MEMOBJTYPE_LOCK:
760 if (pMemLnx->Core.u.Lock.R0Process != NIL_RTR0PROCESS)
761 {
762 struct task_struct *pTask = rtR0ProcessToLinuxTask(pMemLnx->Core.u.Lock.R0Process);
763 size_t iPage;
764 Assert(pTask);
765 if (pTask && pTask->mm)
766 LNX_MM_DOWN_READ(pTask->mm);
767
768 iPage = pMemLnx->cPages;
769 while (iPage-- > 0)
770 {
771 if (!PageReserved(pMemLnx->apPages[iPage]))
772 SetPageDirty(pMemLnx->apPages[iPage]);
773#if RTLNX_VER_MIN(4,6,0)
774 put_page(pMemLnx->apPages[iPage]);
775#else
776 page_cache_release(pMemLnx->apPages[iPage]);
777#endif
778 }
779
780 if (pTask && pTask->mm)
781 LNX_MM_UP_READ(pTask->mm);
782 }
783 /* else: kernel memory - nothing to do here. */
784 break;
785
786 case RTR0MEMOBJTYPE_RES_VIRT:
787 Assert(pMemLnx->Core.pv);
788 if (pMemLnx->Core.u.ResVirt.R0Process != NIL_RTR0PROCESS)
789 {
790 struct task_struct *pTask = rtR0ProcessToLinuxTask(pMemLnx->Core.u.Lock.R0Process);
791 Assert(pTask);
792 if (pTask && pTask->mm)
793 rtR0MemObjLinuxDoMunmap(pMemLnx->Core.pv, pMemLnx->Core.cb, pTask);
794 }
795 else
796 {
797 vunmap(pMemLnx->Core.pv);
798
799 Assert(pMemLnx->cPages == 1 && pMemLnx->apPages[0] != NULL);
800 __free_page(pMemLnx->apPages[0]);
801 pMemLnx->apPages[0] = NULL;
802 pMemLnx->cPages = 0;
803 }
804 pMemLnx->Core.pv = NULL;
805 break;
806
807 case RTR0MEMOBJTYPE_MAPPING:
808 Assert(pMemLnx->cPages == 0); Assert(pMemLnx->Core.pv);
809 if (pMemLnx->Core.u.ResVirt.R0Process != NIL_RTR0PROCESS)
810 {
811 struct task_struct *pTask = rtR0ProcessToLinuxTask(pMemLnx->Core.u.Lock.R0Process);
812 Assert(pTask);
813 if (pTask && pTask->mm)
814 rtR0MemObjLinuxDoMunmap(pMemLnx->Core.pv, pMemLnx->Core.cb, pTask);
815 }
816 else
817 vunmap(pMemLnx->Core.pv);
818 pMemLnx->Core.pv = NULL;
819 break;
820
821 default:
822 AssertMsgFailed(("enmType=%d\n", pMemLnx->Core.enmType));
823 return VERR_INTERNAL_ERROR;
824 }
825 IPRT_LINUX_RESTORE_EFL_ONLY_AC();
826 return VINF_SUCCESS;
827}
828
829
830DECLHIDDEN(int) rtR0MemObjNativeAllocPage(PPRTR0MEMOBJINTERNAL ppMem, size_t cb, bool fExecutable, const char *pszTag)
831{
832 IPRT_LINUX_SAVE_EFL_AC();
833 PRTR0MEMOBJLNX pMemLnx;
834 int rc;
835
836#if RTLNX_VER_MIN(2,4,22)
837 rc = rtR0MemObjLinuxAllocPages(&pMemLnx, RTR0MEMOBJTYPE_PAGE, cb, PAGE_SIZE, GFP_HIGHUSER,
838 false /* non-contiguous */, fExecutable, VERR_NO_MEMORY, pszTag);
839#else
840 rc = rtR0MemObjLinuxAllocPages(&pMemLnx, RTR0MEMOBJTYPE_PAGE, cb, PAGE_SIZE, GFP_USER,
841 false /* non-contiguous */, fExecutable, VERR_NO_MEMORY, pszTag);
842#endif
843 if (RT_SUCCESS(rc))
844 {
845 rc = rtR0MemObjLinuxVMap(pMemLnx, fExecutable);
846 if (RT_SUCCESS(rc))
847 {
848 *ppMem = &pMemLnx->Core;
849 IPRT_LINUX_RESTORE_EFL_AC();
850 return rc;
851 }
852
853 rtR0MemObjLinuxFreePages(pMemLnx);
854 rtR0MemObjDelete(&pMemLnx->Core);
855 }
856
857 IPRT_LINUX_RESTORE_EFL_AC();
858 return rc;
859}
860
861
862DECLHIDDEN(int) rtR0MemObjNativeAllocLarge(PPRTR0MEMOBJINTERNAL ppMem, size_t cb, size_t cbLargePage, uint32_t fFlags,
863 const char *pszTag)
864{
865#ifdef GFP_TRANSHUGE
866 /*
867 * Allocate a memory object structure that's large enough to contain
868 * the page pointer array.
869 */
870# ifdef __GFP_MOVABLE
871 unsigned const fGfp = (GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE;
872# else
873 unsigned const fGfp = (GFP_TRANSHUGE | __GFP_ZERO);
874# endif
875 size_t const cPagesPerLarge = cbLargePage >> PAGE_SHIFT;
876 unsigned const cLargePageOrder = rtR0MemObjLinuxOrder(cPagesPerLarge);
877 size_t const cLargePages = cb >> (cLargePageOrder + PAGE_SHIFT);
878 size_t const cPages = cb >> PAGE_SHIFT;
879 PRTR0MEMOBJLNX pMemLnx;
880
881 Assert(RT_BIT_64(cLargePageOrder + PAGE_SHIFT) == cbLargePage);
882 pMemLnx = (PRTR0MEMOBJLNX)rtR0MemObjNew(RT_UOFFSETOF_DYN(RTR0MEMOBJLNX, apPages[cPages]),
883 RTR0MEMOBJTYPE_LARGE_PAGE, NULL, cb, pszTag);
884 if (pMemLnx)
885 {
886 size_t iLargePage;
887
888 pMemLnx->Core.fFlags |= RTR0MEMOBJ_FLAGS_ZERO_AT_ALLOC;
889 pMemLnx->cLargePageOrder = cLargePageOrder;
890 pMemLnx->cPages = cPages;
891
892 /*
893 * Allocate the requested number of large pages.
894 */
895 for (iLargePage = 0; iLargePage < cLargePages; iLargePage++)
896 {
897 struct page *paPages = alloc_pages(fGfp, cLargePageOrder);
898 if (paPages)
899 {
900 size_t const iPageBase = iLargePage << cLargePageOrder;
901 size_t iPage = cPagesPerLarge;
902 while (iPage-- > 0)
903 pMemLnx->apPages[iPageBase + iPage] = &paPages[iPage];
904 }
905 else
906 {
907 /*Log(("rtR0MemObjNativeAllocLarge: cb=%#zx cPages=%#zx cLargePages=%#zx cLargePageOrder=%u cPagesPerLarge=%#zx iLargePage=%#zx -> failed!\n",
908 cb, cPages, cLargePages, cLargePageOrder, cPagesPerLarge, iLargePage, paPages));*/
909 while (iLargePage-- > 0)
910 __free_pages(pMemLnx->apPages[iLargePage << (cLargePageOrder - PAGE_SHIFT)], cLargePageOrder);
911 rtR0MemObjDelete(&pMemLnx->Core);
912 return VERR_NO_MEMORY;
913 }
914 }
915 *ppMem = &pMemLnx->Core;
916 return VINF_SUCCESS;
917 }
918 return VERR_NO_MEMORY;
919
920#else
921 /*
922 * We don't call rtR0MemObjFallbackAllocLarge here as it can be a really
923 * bad idea to trigger the swap daemon and whatnot. So, just fail.
924 */
925 RT_NOREF(ppMem, cb, cbLargePage, fFlags, pszTag);
926 return VERR_NOT_SUPPORTED;
927#endif
928}
929
930
931DECLHIDDEN(int) rtR0MemObjNativeAllocLow(PPRTR0MEMOBJINTERNAL ppMem, size_t cb, bool fExecutable, const char *pszTag)
932{
933 IPRT_LINUX_SAVE_EFL_AC();
934 PRTR0MEMOBJLNX pMemLnx;
935 int rc;
936
937 /* Try to avoid GFP_DMA. GFM_DMA32 was introduced with Linux 2.6.15. */
938#if (defined(RT_ARCH_AMD64) || defined(CONFIG_X86_PAE)) && defined(GFP_DMA32)
939 /* ZONE_DMA32: 0-4GB */
940 rc = rtR0MemObjLinuxAllocPages(&pMemLnx, RTR0MEMOBJTYPE_LOW, cb, PAGE_SIZE, GFP_DMA32,
941 false /* non-contiguous */, fExecutable, VERR_NO_LOW_MEMORY, pszTag);
942 if (RT_FAILURE(rc))
943#endif
944#ifdef RT_ARCH_AMD64
945 /* ZONE_DMA: 0-16MB */
946 rc = rtR0MemObjLinuxAllocPages(&pMemLnx, RTR0MEMOBJTYPE_LOW, cb, PAGE_SIZE, GFP_DMA,
947 false /* non-contiguous */, fExecutable, VERR_NO_LOW_MEMORY, pszTag);
948#else
949# ifdef CONFIG_X86_PAE
950# endif
951 /* ZONE_NORMAL: 0-896MB */
952 rc = rtR0MemObjLinuxAllocPages(&pMemLnx, RTR0MEMOBJTYPE_LOW, cb, PAGE_SIZE, GFP_USER,
953 false /* non-contiguous */, fExecutable, VERR_NO_LOW_MEMORY, pszTag);
954#endif
955 if (RT_SUCCESS(rc))
956 {
957 rc = rtR0MemObjLinuxVMap(pMemLnx, fExecutable);
958 if (RT_SUCCESS(rc))
959 {
960 *ppMem = &pMemLnx->Core;
961 IPRT_LINUX_RESTORE_EFL_AC();
962 return rc;
963 }
964
965 rtR0MemObjLinuxFreePages(pMemLnx);
966 rtR0MemObjDelete(&pMemLnx->Core);
967 }
968
969 IPRT_LINUX_RESTORE_EFL_AC();
970 return rc;
971}
972
973
974DECLHIDDEN(int) rtR0MemObjNativeAllocCont(PPRTR0MEMOBJINTERNAL ppMem, size_t cb, bool fExecutable, const char *pszTag)
975{
976 IPRT_LINUX_SAVE_EFL_AC();
977 PRTR0MEMOBJLNX pMemLnx;
978 int rc;
979
980#if (defined(RT_ARCH_AMD64) || defined(RT_ARCH_ARM64) || defined(CONFIG_X86_PAE)) && defined(GFP_DMA32)
981 /* ZONE_DMA32: 0-4GB */
982 rc = rtR0MemObjLinuxAllocPages(&pMemLnx, RTR0MEMOBJTYPE_CONT, cb, PAGE_SIZE, GFP_DMA32,
983 true /* contiguous */, fExecutable, VERR_NO_CONT_MEMORY, pszTag);
984 if (RT_FAILURE(rc))
985#endif
986#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_ARM64)
987 /* ZONE_DMA: 0-16MB */
988 rc = rtR0MemObjLinuxAllocPages(&pMemLnx, RTR0MEMOBJTYPE_CONT, cb, PAGE_SIZE, GFP_DMA,
989 true /* contiguous */, fExecutable, VERR_NO_CONT_MEMORY, pszTag);
990#else
991 /* ZONE_NORMAL (32-bit hosts): 0-896MB */
992 rc = rtR0MemObjLinuxAllocPages(&pMemLnx, RTR0MEMOBJTYPE_CONT, cb, PAGE_SIZE, GFP_USER,
993 true /* contiguous */, fExecutable, VERR_NO_CONT_MEMORY, pszTag);
994#endif
995 if (RT_SUCCESS(rc))
996 {
997 rc = rtR0MemObjLinuxVMap(pMemLnx, fExecutable);
998 if (RT_SUCCESS(rc))
999 {
1000#if defined(RT_STRICT) && (defined(RT_ARCH_AMD64) || defined(CONFIG_HIGHMEM64G))
1001 size_t iPage = pMemLnx->cPages;
1002 while (iPage-- > 0)
1003 Assert(page_to_phys(pMemLnx->apPages[iPage]) < _4G);
1004#endif
1005 pMemLnx->Core.u.Cont.Phys = page_to_phys(pMemLnx->apPages[0]);
1006 *ppMem = &pMemLnx->Core;
1007 IPRT_LINUX_RESTORE_EFL_AC();
1008 return rc;
1009 }
1010
1011 rtR0MemObjLinuxFreePages(pMemLnx);
1012 rtR0MemObjDelete(&pMemLnx->Core);
1013 }
1014
1015 IPRT_LINUX_RESTORE_EFL_AC();
1016 return rc;
1017}
1018
1019
1020/**
1021 * Worker for rtR0MemObjLinuxAllocPhysSub that tries one allocation strategy.
1022 *
1023 * @returns IPRT status code.
1024 * @param ppMemLnx Where to
1025 * @param enmType The object type.
1026 * @param cb The size of the allocation.
1027 * @param uAlignment The alignment of the physical memory.
1028 * Only valid for fContiguous == true, ignored otherwise.
1029 * @param PhysHighest See rtR0MemObjNativeAllocPhys.
1030 * @param pszTag Allocation tag used for statistics and such.
1031 * @param fGfp The Linux GFP flags to use for the allocation.
1032 */
1033static int rtR0MemObjLinuxAllocPhysSub2(PPRTR0MEMOBJINTERNAL ppMem, RTR0MEMOBJTYPE enmType,
1034 size_t cb, size_t uAlignment, RTHCPHYS PhysHighest, const char *pszTag, gfp_t fGfp)
1035{
1036 PRTR0MEMOBJLNX pMemLnx;
1037 int rc = rtR0MemObjLinuxAllocPages(&pMemLnx, enmType, cb, uAlignment, fGfp,
1038 enmType == RTR0MEMOBJTYPE_PHYS /* contiguous / non-contiguous */,
1039 false /*fExecutable*/, VERR_NO_PHYS_MEMORY, pszTag);
1040 if (RT_FAILURE(rc))
1041 return rc;
1042
1043 /*
1044 * Check the addresses if necessary. (Can be optimized a bit for PHYS.)
1045 */
1046 if (PhysHighest != NIL_RTHCPHYS)
1047 {
1048 size_t iPage = pMemLnx->cPages;
1049 while (iPage-- > 0)
1050 if (page_to_phys(pMemLnx->apPages[iPage]) > PhysHighest)
1051 {
1052 rtR0MemObjLinuxFreePages(pMemLnx);
1053 rtR0MemObjDelete(&pMemLnx->Core);
1054 return VERR_NO_MEMORY;
1055 }
1056 }
1057
1058 /*
1059 * Complete the object.
1060 */
1061 if (enmType == RTR0MEMOBJTYPE_PHYS)
1062 {
1063 pMemLnx->Core.u.Phys.PhysBase = page_to_phys(pMemLnx->apPages[0]);
1064 pMemLnx->Core.u.Phys.fAllocated = true;
1065 }
1066 *ppMem = &pMemLnx->Core;
1067 return rc;
1068}
1069
1070
1071/**
1072 * Worker for rtR0MemObjNativeAllocPhys and rtR0MemObjNativeAllocPhysNC.
1073 *
1074 * @returns IPRT status code.
1075 * @param ppMem Where to store the memory object pointer on success.
1076 * @param enmType The object type.
1077 * @param cb The size of the allocation.
1078 * @param uAlignment The alignment of the physical memory.
1079 * Only valid for enmType == RTR0MEMOBJTYPE_PHYS, ignored otherwise.
1080 * @param PhysHighest See rtR0MemObjNativeAllocPhys.
1081 * @param pszTag Allocation tag used for statistics and such.
1082 */
1083static int rtR0MemObjLinuxAllocPhysSub(PPRTR0MEMOBJINTERNAL ppMem, RTR0MEMOBJTYPE enmType,
1084 size_t cb, size_t uAlignment, RTHCPHYS PhysHighest, const char *pszTag)
1085{
1086 int rc;
1087 IPRT_LINUX_SAVE_EFL_AC();
1088
1089 /*
1090 * There are two clear cases and that's the <=16MB and anything-goes ones.
1091 * When the physical address limit is somewhere in-between those two we'll
1092 * just have to try, starting with HIGHUSER and working our way thru the
1093 * different types, hoping we'll get lucky.
1094 *
1095 * We should probably move this physical address restriction logic up to
1096 * the page alloc function as it would be more efficient there. But since
1097 * we don't expect this to be a performance issue just yet it can wait.
1098 */
1099 if (PhysHighest == NIL_RTHCPHYS)
1100 /* ZONE_HIGHMEM: the whole physical memory */
1101 rc = rtR0MemObjLinuxAllocPhysSub2(ppMem, enmType, cb, uAlignment, PhysHighest, pszTag, GFP_HIGHUSER);
1102 else if (PhysHighest <= _1M * 16)
1103 /* ZONE_DMA: 0-16MB */
1104 rc = rtR0MemObjLinuxAllocPhysSub2(ppMem, enmType, cb, uAlignment, PhysHighest, pszTag, GFP_DMA);
1105 else
1106 {
1107 rc = VERR_NO_MEMORY;
1108 if (RT_FAILURE(rc))
1109 /* ZONE_HIGHMEM: the whole physical memory */
1110 rc = rtR0MemObjLinuxAllocPhysSub2(ppMem, enmType, cb, uAlignment, PhysHighest, pszTag, GFP_HIGHUSER);
1111 if (RT_FAILURE(rc))
1112 /* ZONE_NORMAL: 0-896MB */
1113 rc = rtR0MemObjLinuxAllocPhysSub2(ppMem, enmType, cb, uAlignment, PhysHighest, pszTag, GFP_USER);
1114#ifdef GFP_DMA32
1115 if (RT_FAILURE(rc))
1116 /* ZONE_DMA32: 0-4GB */
1117 rc = rtR0MemObjLinuxAllocPhysSub2(ppMem, enmType, cb, uAlignment, PhysHighest, pszTag, GFP_DMA32);
1118#endif
1119 if (RT_FAILURE(rc))
1120 /* ZONE_DMA: 0-16MB */
1121 rc = rtR0MemObjLinuxAllocPhysSub2(ppMem, enmType, cb, uAlignment, PhysHighest, pszTag, GFP_DMA);
1122 }
1123 IPRT_LINUX_RESTORE_EFL_AC();
1124 return rc;
1125}
1126
1127
1128/**
1129 * Translates a kernel virtual address to a linux page structure by walking the
1130 * page tables.
1131 *
1132 * @note We do assume that the page tables will not change as we are walking
1133 * them. This assumption is rather forced by the fact that I could not
1134 * immediately see any way of preventing this from happening. So, we
1135 * take some extra care when accessing them.
1136 *
1137 * Because of this, we don't want to use this function on memory where
1138 * attribute changes to nearby pages is likely to cause large pages to
1139 * be used or split up. So, don't use this for the linear mapping of
1140 * physical memory.
1141 *
1142 * @returns Pointer to the page structur or NULL if it could not be found.
1143 * @param pv The kernel virtual address.
1144 */
1145RTDECL(struct page *) rtR0MemObjLinuxVirtToPage(void *pv)
1146{
1147#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
1148 unsigned long ulAddr = (unsigned long)pv;
1149 unsigned long pfn;
1150 struct page *pPage;
1151 pte_t *pEntry;
1152 union
1153 {
1154 pgd_t Global;
1155# if RTLNX_VER_MIN(4,12,0)
1156 p4d_t Four;
1157# endif
1158# if RTLNX_VER_MIN(2,6,11)
1159 pud_t Upper;
1160# endif
1161 pmd_t Middle;
1162 pte_t Entry;
1163 } u;
1164
1165 /* Should this happen in a situation this code will be called in? And if
1166 * so, can it change under our feet? See also
1167 * "Documentation/vm/active_mm.txt" in the kernel sources. */
1168 if (RT_UNLIKELY(!current->active_mm))
1169 return NULL;
1170 u.Global = *pgd_offset(current->active_mm, ulAddr);
1171 if (RT_UNLIKELY(pgd_none(u.Global)))
1172 return NULL;
1173# if RTLNX_VER_MIN(2,6,11)
1174# if RTLNX_VER_MIN(4,12,0)
1175 u.Four = *p4d_offset(&u.Global, ulAddr);
1176 if (RT_UNLIKELY(p4d_none(u.Four)))
1177 return NULL;
1178 if (p4d_large(u.Four))
1179 {
1180 pPage = p4d_page(u.Four);
1181 AssertReturn(pPage, NULL);
1182 pfn = page_to_pfn(pPage); /* doing the safe way... */
1183 AssertCompile(P4D_SHIFT - PAGE_SHIFT < 31);
1184 pfn += (ulAddr >> PAGE_SHIFT) & ((UINT32_C(1) << (P4D_SHIFT - PAGE_SHIFT)) - 1);
1185 return pfn_to_page(pfn);
1186 }
1187 u.Upper = *pud_offset(&u.Four, ulAddr);
1188# else /* < 4.12 */
1189 u.Upper = *pud_offset(&u.Global, ulAddr);
1190# endif /* < 4.12 */
1191 if (RT_UNLIKELY(pud_none(u.Upper)))
1192 return NULL;
1193# if RTLNX_VER_MIN(2,6,25)
1194 if (pud_large(u.Upper))
1195 {
1196 pPage = pud_page(u.Upper);
1197 AssertReturn(pPage, NULL);
1198 pfn = page_to_pfn(pPage); /* doing the safe way... */
1199 pfn += (ulAddr >> PAGE_SHIFT) & ((UINT32_C(1) << (PUD_SHIFT - PAGE_SHIFT)) - 1);
1200 return pfn_to_page(pfn);
1201 }
1202# endif
1203 u.Middle = *pmd_offset(&u.Upper, ulAddr);
1204# else /* < 2.6.11 */
1205 u.Middle = *pmd_offset(&u.Global, ulAddr);
1206# endif /* < 2.6.11 */
1207 if (RT_UNLIKELY(pmd_none(u.Middle)))
1208 return NULL;
1209# if RTLNX_VER_MIN(2,6,0)
1210 if (pmd_large(u.Middle))
1211 {
1212 pPage = pmd_page(u.Middle);
1213 AssertReturn(pPage, NULL);
1214 pfn = page_to_pfn(pPage); /* doing the safe way... */
1215 pfn += (ulAddr >> PAGE_SHIFT) & ((UINT32_C(1) << (PMD_SHIFT - PAGE_SHIFT)) - 1);
1216 return pfn_to_page(pfn);
1217 }
1218# endif
1219
1220# if RTLNX_VER_MIN(2,5,5) || defined(pte_offset_map) /* As usual, RHEL 3 had pte_offset_map earlier. */
1221 pEntry = pte_offset_map(&u.Middle, ulAddr);
1222# else
1223 pEntry = pte_offset(&u.Middle, ulAddr);
1224# endif
1225 if (RT_UNLIKELY(!pEntry))
1226 return NULL;
1227 u.Entry = *pEntry;
1228# if RTLNX_VER_MIN(2,5,5) || defined(pte_offset_map)
1229 pte_unmap(pEntry);
1230# endif
1231
1232 if (RT_UNLIKELY(!pte_present(u.Entry)))
1233 return NULL;
1234 return pte_page(u.Entry);
1235#else /* !defined(RT_ARCH_AMD64) && !defined(RT_ARCH_X86) */
1236 return virt_to_page(pv);
1237#endif
1238}
1239RT_EXPORT_SYMBOL(rtR0MemObjLinuxVirtToPage);
1240
1241
1242DECLHIDDEN(int) rtR0MemObjNativeAllocPhys(PPRTR0MEMOBJINTERNAL ppMem, size_t cb, RTHCPHYS PhysHighest, size_t uAlignment,
1243 const char *pszTag)
1244{
1245 return rtR0MemObjLinuxAllocPhysSub(ppMem, RTR0MEMOBJTYPE_PHYS, cb, uAlignment, PhysHighest, pszTag);
1246}
1247
1248
1249DECLHIDDEN(int) rtR0MemObjNativeAllocPhysNC(PPRTR0MEMOBJINTERNAL ppMem, size_t cb, RTHCPHYS PhysHighest, const char *pszTag)
1250{
1251 return rtR0MemObjLinuxAllocPhysSub(ppMem, RTR0MEMOBJTYPE_PHYS_NC, cb, PAGE_SIZE, PhysHighest, pszTag);
1252}
1253
1254
1255DECLHIDDEN(int) rtR0MemObjNativeEnterPhys(PPRTR0MEMOBJINTERNAL ppMem, RTHCPHYS Phys, size_t cb, uint32_t uCachePolicy,
1256 const char *pszTag)
1257{
1258 IPRT_LINUX_SAVE_EFL_AC();
1259
1260 /*
1261 * All we need to do here is to validate that we can use
1262 * ioremap on the specified address (32/64-bit dma_addr_t).
1263 */
1264 PRTR0MEMOBJLNX pMemLnx;
1265 dma_addr_t PhysAddr = Phys;
1266 AssertMsgReturn(PhysAddr == Phys, ("%#llx\n", (unsigned long long)Phys), VERR_ADDRESS_TOO_BIG);
1267
1268 pMemLnx = (PRTR0MEMOBJLNX)rtR0MemObjNew(sizeof(*pMemLnx), RTR0MEMOBJTYPE_PHYS, NULL, cb, pszTag);
1269 if (!pMemLnx)
1270 {
1271 IPRT_LINUX_RESTORE_EFL_AC();
1272 return VERR_NO_MEMORY;
1273 }
1274
1275 pMemLnx->Core.u.Phys.PhysBase = PhysAddr;
1276 pMemLnx->Core.u.Phys.fAllocated = false;
1277 pMemLnx->Core.u.Phys.uCachePolicy = uCachePolicy;
1278 Assert(!pMemLnx->cPages);
1279 *ppMem = &pMemLnx->Core;
1280 IPRT_LINUX_RESTORE_EFL_AC();
1281 return VINF_SUCCESS;
1282}
1283
1284/* openSUSE Leap 42.3 detection :-/ */
1285#if RTLNX_VER_RANGE(4,4,0, 4,6,0) && defined(FAULT_FLAG_REMOTE)
1286# define GET_USER_PAGES_API KERNEL_VERSION(4, 10, 0) /* no typo! */
1287#else
1288# define GET_USER_PAGES_API LINUX_VERSION_CODE
1289#endif
1290
1291DECLHIDDEN(int) rtR0MemObjNativeLockUser(PPRTR0MEMOBJINTERNAL ppMem, RTR3PTR R3Ptr, size_t cb, uint32_t fAccess,
1292 RTR0PROCESS R0Process, const char *pszTag)
1293{
1294 IPRT_LINUX_SAVE_EFL_AC();
1295 const int cPages = cb >> PAGE_SHIFT;
1296 struct task_struct *pTask = rtR0ProcessToLinuxTask(R0Process);
1297 struct vm_area_struct **papVMAs;
1298 PRTR0MEMOBJLNX pMemLnx;
1299 int rc = VERR_NO_MEMORY;
1300 int const fWrite = fAccess & RTMEM_PROT_WRITE ? 1 : 0;
1301
1302 /*
1303 * Check for valid task and size overflows.
1304 */
1305 if (!pTask)
1306 return VERR_NOT_SUPPORTED;
1307 if (((size_t)cPages << PAGE_SHIFT) != cb)
1308 return VERR_OUT_OF_RANGE;
1309
1310 /*
1311 * Allocate the memory object and a temporary buffer for the VMAs.
1312 */
1313 pMemLnx = (PRTR0MEMOBJLNX)rtR0MemObjNew(RT_UOFFSETOF_DYN(RTR0MEMOBJLNX, apPages[cPages]), RTR0MEMOBJTYPE_LOCK,
1314 (void *)R3Ptr, cb, pszTag);
1315 if (!pMemLnx)
1316 {
1317 IPRT_LINUX_RESTORE_EFL_AC();
1318 return VERR_NO_MEMORY;
1319 }
1320
1321 papVMAs = (struct vm_area_struct **)RTMemAlloc(sizeof(*papVMAs) * cPages);
1322 if (papVMAs)
1323 {
1324 LNX_MM_DOWN_READ(pTask->mm);
1325
1326 /*
1327 * Get user pages.
1328 */
1329/** @todo r=bird: Should we not force read access too? */
1330#if GET_USER_PAGES_API >= KERNEL_VERSION(4, 6, 0)
1331 if (R0Process == RTR0ProcHandleSelf())
1332 rc = get_user_pages(R3Ptr, /* Where from. */
1333 cPages, /* How many pages. */
1334# if GET_USER_PAGES_API >= KERNEL_VERSION(4, 9, 0)
1335 fWrite ? FOLL_WRITE | /* Write to memory. */
1336 FOLL_FORCE /* force write access. */
1337 : 0, /* Write to memory. */
1338# else
1339 fWrite, /* Write to memory. */
1340 fWrite, /* force write access. */
1341# endif
1342 &pMemLnx->apPages[0], /* Page array. */
1343 papVMAs); /* vmas */
1344 /*
1345 * Actually this should not happen at the moment as call this function
1346 * only for our own process.
1347 */
1348 else
1349 rc = get_user_pages_remote(
1350# if GET_USER_PAGES_API < KERNEL_VERSION(5, 9, 0)
1351 pTask, /* Task for fault accounting. */
1352# endif
1353 pTask->mm, /* Whose pages. */
1354 R3Ptr, /* Where from. */
1355 cPages, /* How many pages. */
1356# if GET_USER_PAGES_API >= KERNEL_VERSION(4, 9, 0)
1357 fWrite ? FOLL_WRITE | /* Write to memory. */
1358 FOLL_FORCE /* force write access. */
1359 : 0, /* Write to memory. */
1360# else
1361 fWrite, /* Write to memory. */
1362 fWrite, /* force write access. */
1363# endif
1364 &pMemLnx->apPages[0], /* Page array. */
1365 papVMAs /* vmas */
1366# if GET_USER_PAGES_API >= KERNEL_VERSION(4, 10, 0)
1367 , NULL /* locked */
1368# endif
1369 );
1370#else /* GET_USER_PAGES_API < KERNEL_VERSION(4, 6, 0) */
1371 rc = get_user_pages(pTask, /* Task for fault accounting. */
1372 pTask->mm, /* Whose pages. */
1373 R3Ptr, /* Where from. */
1374 cPages, /* How many pages. */
1375/* The get_user_pages API change was back-ported to 4.4.168. */
1376# if RTLNX_VER_RANGE(4,4,168, 4,5,0)
1377 fWrite ? FOLL_WRITE | /* Write to memory. */
1378 FOLL_FORCE /* force write access. */
1379 : 0, /* Write to memory. */
1380# else
1381 fWrite, /* Write to memory. */
1382 fWrite, /* force write access. */
1383# endif
1384 &pMemLnx->apPages[0], /* Page array. */
1385 papVMAs); /* vmas */
1386#endif /* GET_USER_PAGES_API < KERNEL_VERSION(4, 6, 0) */
1387 if (rc == cPages)
1388 {
1389 /*
1390 * Flush dcache (required?), protect against fork and _really_ pin the page
1391 * table entries. get_user_pages() will protect against swapping out the
1392 * pages but it will NOT protect against removing page table entries. This
1393 * can be achieved with
1394 * - using mlock / mmap(..., MAP_LOCKED, ...) from userland. This requires
1395 * an appropriate limit set up with setrlimit(..., RLIMIT_MEMLOCK, ...).
1396 * Usual Linux distributions support only a limited size of locked pages
1397 * (e.g. 32KB).
1398 * - setting the PageReserved bit (as we do in rtR0MemObjLinuxAllocPages()
1399 * or by
1400 * - setting the VM_LOCKED flag. This is the same as doing mlock() without
1401 * a range check.
1402 */
1403 /** @todo The Linux fork() protection will require more work if this API
1404 * is to be used for anything but locking VM pages. */
1405 while (rc-- > 0)
1406 {
1407 flush_dcache_page(pMemLnx->apPages[rc]);
1408#if RTLNX_VER_MIN(6,3,0)
1409 vm_flags_set(papVMAs[rc], VM_DONTCOPY | VM_LOCKED);
1410#else
1411 papVMAs[rc]->vm_flags |= VM_DONTCOPY | VM_LOCKED;
1412#endif
1413 }
1414
1415 LNX_MM_UP_READ(pTask->mm);
1416
1417 RTMemFree(papVMAs);
1418
1419 pMemLnx->Core.u.Lock.R0Process = R0Process;
1420 pMemLnx->cPages = cPages;
1421 Assert(!pMemLnx->fMappedToRing0);
1422 *ppMem = &pMemLnx->Core;
1423
1424 IPRT_LINUX_RESTORE_EFL_AC();
1425 return VINF_SUCCESS;
1426 }
1427
1428 /*
1429 * Failed - we need to unlock any pages that we succeeded to lock.
1430 */
1431 while (rc-- > 0)
1432 {
1433 if (!PageReserved(pMemLnx->apPages[rc]))
1434 SetPageDirty(pMemLnx->apPages[rc]);
1435#if RTLNX_VER_MIN(4,6,0)
1436 put_page(pMemLnx->apPages[rc]);
1437#else
1438 page_cache_release(pMemLnx->apPages[rc]);
1439#endif
1440 }
1441
1442 LNX_MM_UP_READ(pTask->mm);
1443
1444 RTMemFree(papVMAs);
1445 rc = VERR_LOCK_FAILED;
1446 }
1447
1448 rtR0MemObjDelete(&pMemLnx->Core);
1449 IPRT_LINUX_RESTORE_EFL_AC();
1450 return rc;
1451}
1452
1453
1454DECLHIDDEN(int) rtR0MemObjNativeLockKernel(PPRTR0MEMOBJINTERNAL ppMem, void *pv, size_t cb, uint32_t fAccess, const char *pszTag)
1455{
1456 IPRT_LINUX_SAVE_EFL_AC();
1457 void *pvLast = (uint8_t *)pv + cb - 1;
1458 size_t const cPages = cb >> PAGE_SHIFT;
1459 PRTR0MEMOBJLNX pMemLnx;
1460 bool fLinearMapping;
1461 int rc;
1462 uint8_t *pbPage;
1463 size_t iPage;
1464 NOREF(fAccess);
1465
1466 if ( !RTR0MemKernelIsValidAddr(pv)
1467 || !RTR0MemKernelIsValidAddr(pv + cb))
1468 return VERR_INVALID_PARAMETER;
1469
1470 /*
1471 * The lower part of the kernel memory has a linear mapping between
1472 * physical and virtual addresses. So we take a short cut here. This is
1473 * assumed to be the cleanest way to handle those addresses (and the code
1474 * is well tested, though the test for determining it is not very nice).
1475 * If we ever decide it isn't we can still remove it.
1476 */
1477#if 0
1478 fLinearMapping = (unsigned long)pvLast < VMALLOC_START;
1479#else
1480 fLinearMapping = (unsigned long)pv >= (unsigned long)__va(0)
1481 && (unsigned long)pvLast < (unsigned long)high_memory;
1482#endif
1483
1484 /*
1485 * Allocate the memory object.
1486 */
1487 pMemLnx = (PRTR0MEMOBJLNX)rtR0MemObjNew(RT_UOFFSETOF_DYN(RTR0MEMOBJLNX, apPages[cPages]), RTR0MEMOBJTYPE_LOCK,
1488 pv, cb, pszTag);
1489 if (!pMemLnx)
1490 {
1491 IPRT_LINUX_RESTORE_EFL_AC();
1492 return VERR_NO_MEMORY;
1493 }
1494
1495 /*
1496 * Gather the pages.
1497 * We ASSUME all kernel pages are non-swappable and non-movable.
1498 */
1499 rc = VINF_SUCCESS;
1500 pbPage = (uint8_t *)pvLast;
1501 iPage = cPages;
1502 if (!fLinearMapping)
1503 {
1504 while (iPage-- > 0)
1505 {
1506 struct page *pPage = rtR0MemObjLinuxVirtToPage(pbPage);
1507 if (RT_UNLIKELY(!pPage))
1508 {
1509 rc = VERR_LOCK_FAILED;
1510 break;
1511 }
1512 pMemLnx->apPages[iPage] = pPage;
1513 pbPage -= PAGE_SIZE;
1514 }
1515 }
1516 else
1517 {
1518 while (iPage-- > 0)
1519 {
1520 pMemLnx->apPages[iPage] = virt_to_page(pbPage);
1521 pbPage -= PAGE_SIZE;
1522 }
1523 }
1524 if (RT_SUCCESS(rc))
1525 {
1526 /*
1527 * Complete the memory object and return.
1528 */
1529 pMemLnx->Core.u.Lock.R0Process = NIL_RTR0PROCESS;
1530 pMemLnx->cPages = cPages;
1531 Assert(!pMemLnx->fMappedToRing0);
1532 *ppMem = &pMemLnx->Core;
1533
1534 IPRT_LINUX_RESTORE_EFL_AC();
1535 return VINF_SUCCESS;
1536 }
1537
1538 rtR0MemObjDelete(&pMemLnx->Core);
1539 IPRT_LINUX_RESTORE_EFL_AC();
1540 return rc;
1541}
1542
1543
1544DECLHIDDEN(int) rtR0MemObjNativeReserveKernel(PPRTR0MEMOBJINTERNAL ppMem, void *pvFixed, size_t cb, size_t uAlignment,
1545 const char *pszTag)
1546{
1547#if RTLNX_VER_MIN(2,4,22)
1548 IPRT_LINUX_SAVE_EFL_AC();
1549 const size_t cPages = cb >> PAGE_SHIFT;
1550 struct page *pDummyPage;
1551 struct page **papPages;
1552
1553 /* check for unsupported stuff. */
1554 AssertMsgReturn(pvFixed == (void *)-1, ("%p\n", pvFixed), VERR_NOT_SUPPORTED);
1555 if (uAlignment > PAGE_SIZE)
1556 return VERR_NOT_SUPPORTED;
1557
1558 /*
1559 * Allocate a dummy page and create a page pointer array for vmap such that
1560 * the dummy page is mapped all over the reserved area.
1561 */
1562 pDummyPage = alloc_page(GFP_HIGHUSER | __GFP_NOWARN);
1563 if (pDummyPage)
1564 {
1565 papPages = RTMemAlloc(sizeof(*papPages) * cPages);
1566 if (papPages)
1567 {
1568 void *pv;
1569 size_t iPage = cPages;
1570 while (iPage-- > 0)
1571 papPages[iPage] = pDummyPage;
1572# ifdef VM_MAP
1573 pv = vmap(papPages, cPages, VM_MAP, PAGE_KERNEL_RO);
1574# else
1575 pv = vmap(papPages, cPages, VM_ALLOC, PAGE_KERNEL_RO);
1576# endif
1577 RTMemFree(papPages);
1578 if (pv)
1579 {
1580 PRTR0MEMOBJLNX pMemLnx = (PRTR0MEMOBJLNX)rtR0MemObjNew(sizeof(*pMemLnx), RTR0MEMOBJTYPE_RES_VIRT, pv, cb, pszTag);
1581 if (pMemLnx)
1582 {
1583 pMemLnx->Core.u.ResVirt.R0Process = NIL_RTR0PROCESS;
1584 pMemLnx->cPages = 1;
1585 pMemLnx->apPages[0] = pDummyPage;
1586 *ppMem = &pMemLnx->Core;
1587 IPRT_LINUX_RESTORE_EFL_AC();
1588 return VINF_SUCCESS;
1589 }
1590 vunmap(pv);
1591 }
1592 }
1593 __free_page(pDummyPage);
1594 }
1595 IPRT_LINUX_RESTORE_EFL_AC();
1596 return VERR_NO_MEMORY;
1597
1598#else /* < 2.4.22 */
1599 /*
1600 * Could probably use ioremap here, but the caller is in a better position than us
1601 * to select some safe physical memory.
1602 */
1603 return VERR_NOT_SUPPORTED;
1604#endif
1605}
1606
1607
1608DECLHIDDEN(int) rtR0MemObjNativeReserveUser(PPRTR0MEMOBJINTERNAL ppMem, RTR3PTR R3PtrFixed, size_t cb, size_t uAlignment,
1609 RTR0PROCESS R0Process, const char *pszTag)
1610{
1611 IPRT_LINUX_SAVE_EFL_AC();
1612 PRTR0MEMOBJLNX pMemLnx;
1613 void *pv;
1614 struct task_struct *pTask = rtR0ProcessToLinuxTask(R0Process);
1615 if (!pTask)
1616 return VERR_NOT_SUPPORTED;
1617
1618 /*
1619 * Check that the specified alignment is supported.
1620 */
1621 if (uAlignment > PAGE_SIZE)
1622 return VERR_NOT_SUPPORTED;
1623
1624 /*
1625 * Let rtR0MemObjLinuxDoMmap do the difficult bits.
1626 */
1627 pv = rtR0MemObjLinuxDoMmap(R3PtrFixed, cb, uAlignment, pTask, RTMEM_PROT_NONE);
1628 if (pv == (void *)-1)
1629 {
1630 IPRT_LINUX_RESTORE_EFL_AC();
1631 return VERR_NO_MEMORY;
1632 }
1633
1634 pMemLnx = (PRTR0MEMOBJLNX)rtR0MemObjNew(sizeof(*pMemLnx), RTR0MEMOBJTYPE_RES_VIRT, pv, cb, pszTag);
1635 if (!pMemLnx)
1636 {
1637 rtR0MemObjLinuxDoMunmap(pv, cb, pTask);
1638 IPRT_LINUX_RESTORE_EFL_AC();
1639 return VERR_NO_MEMORY;
1640 }
1641
1642 pMemLnx->Core.u.ResVirt.R0Process = R0Process;
1643 *ppMem = &pMemLnx->Core;
1644 IPRT_LINUX_RESTORE_EFL_AC();
1645 return VINF_SUCCESS;
1646}
1647
1648
1649DECLHIDDEN(int) rtR0MemObjNativeMapKernel(PPRTR0MEMOBJINTERNAL ppMem, RTR0MEMOBJ pMemToMap, void *pvFixed, size_t uAlignment,
1650 unsigned fProt, size_t offSub, size_t cbSub, const char *pszTag)
1651{
1652 int rc = VERR_NO_MEMORY;
1653 PRTR0MEMOBJLNX pMemLnxToMap = (PRTR0MEMOBJLNX)pMemToMap;
1654 PRTR0MEMOBJLNX pMemLnx;
1655 IPRT_LINUX_SAVE_EFL_AC();
1656
1657 /* Fail if requested to do something we can't. */
1658 AssertMsgReturn(pvFixed == (void *)-1, ("%p\n", pvFixed), VERR_NOT_SUPPORTED);
1659 if (uAlignment > PAGE_SIZE)
1660 return VERR_NOT_SUPPORTED;
1661
1662 /*
1663 * Create the IPRT memory object.
1664 */
1665 if (!cbSub)
1666 cbSub = pMemLnxToMap->Core.cb - offSub;
1667 pMemLnx = (PRTR0MEMOBJLNX)rtR0MemObjNew(sizeof(*pMemLnx), RTR0MEMOBJTYPE_MAPPING, NULL, cbSub, pszTag);
1668 if (pMemLnx)
1669 {
1670 if (pMemLnxToMap->cPages)
1671 {
1672#if RTLNX_VER_MIN(2,4,22)
1673 /*
1674 * Use vmap - 2.4.22 and later.
1675 */
1676 pgprot_t fPg = rtR0MemObjLinuxConvertProt(fProt, true /* kernel */);
1677 /** @todo We don't really care too much for EXEC here... 5.8 always adds NX. */
1678 Assert(((offSub + cbSub) >> PAGE_SHIFT) <= pMemLnxToMap->cPages);
1679# ifdef VM_MAP
1680 pMemLnx->Core.pv = vmap(&pMemLnxToMap->apPages[offSub >> PAGE_SHIFT], cbSub >> PAGE_SHIFT, VM_MAP, fPg);
1681# else
1682 pMemLnx->Core.pv = vmap(&pMemLnxToMap->apPages[offSub >> PAGE_SHIFT], cbSub >> PAGE_SHIFT, VM_ALLOC, fPg);
1683# endif
1684 if (pMemLnx->Core.pv)
1685 {
1686 pMemLnx->fMappedToRing0 = true;
1687 rc = VINF_SUCCESS;
1688 }
1689 else
1690 rc = VERR_MAP_FAILED;
1691
1692#else /* < 2.4.22 */
1693 /*
1694 * Only option here is to share mappings if possible and forget about fProt.
1695 */
1696 if (rtR0MemObjIsRing3(pMemToMap))
1697 rc = VERR_NOT_SUPPORTED;
1698 else
1699 {
1700 rc = VINF_SUCCESS;
1701 if (!pMemLnxToMap->Core.pv)
1702 rc = rtR0MemObjLinuxVMap(pMemLnxToMap, !!(fProt & RTMEM_PROT_EXEC));
1703 if (RT_SUCCESS(rc))
1704 {
1705 Assert(pMemLnxToMap->Core.pv);
1706 pMemLnx->Core.pv = (uint8_t *)pMemLnxToMap->Core.pv + offSub;
1707 }
1708 }
1709#endif
1710 }
1711 else
1712 {
1713 /*
1714 * MMIO / physical memory.
1715 */
1716 Assert(pMemLnxToMap->Core.enmType == RTR0MEMOBJTYPE_PHYS && !pMemLnxToMap->Core.u.Phys.fAllocated);
1717#if RTLNX_VER_MIN(2,6,25)
1718 /*
1719 * ioremap() defaults to no caching since the 2.6 kernels.
1720 * ioremap_nocache() has been removed finally in 5.6-rc1.
1721 */
1722 pMemLnx->Core.pv = pMemLnxToMap->Core.u.Phys.uCachePolicy == RTMEM_CACHE_POLICY_MMIO
1723 ? ioremap(pMemLnxToMap->Core.u.Phys.PhysBase + offSub, cbSub)
1724 : ioremap_cache(pMemLnxToMap->Core.u.Phys.PhysBase + offSub, cbSub);
1725#else /* KERNEL_VERSION < 2.6.25 */
1726 pMemLnx->Core.pv = pMemLnxToMap->Core.u.Phys.uCachePolicy == RTMEM_CACHE_POLICY_MMIO
1727 ? ioremap_nocache(pMemLnxToMap->Core.u.Phys.PhysBase + offSub, cbSub)
1728 : ioremap(pMemLnxToMap->Core.u.Phys.PhysBase + offSub, cbSub);
1729#endif /* KERNEL_VERSION < 2.6.25 */
1730 if (pMemLnx->Core.pv)
1731 {
1732 /** @todo fix protection. */
1733 rc = VINF_SUCCESS;
1734 }
1735 }
1736 if (RT_SUCCESS(rc))
1737 {
1738 pMemLnx->Core.u.Mapping.R0Process = NIL_RTR0PROCESS;
1739 *ppMem = &pMemLnx->Core;
1740 IPRT_LINUX_RESTORE_EFL_AC();
1741 return VINF_SUCCESS;
1742 }
1743 rtR0MemObjDelete(&pMemLnx->Core);
1744 }
1745
1746 IPRT_LINUX_RESTORE_EFL_AC();
1747 return rc;
1748}
1749
1750
1751#ifdef VBOX_USE_PAE_HACK
1752/**
1753 * Replace the PFN of a PTE with the address of the actual page.
1754 *
1755 * The caller maps a reserved dummy page at the address with the desired access
1756 * and flags.
1757 *
1758 * This hack is required for older Linux kernels which don't provide
1759 * remap_pfn_range().
1760 *
1761 * @returns 0 on success, -ENOMEM on failure.
1762 * @param mm The memory context.
1763 * @param ulAddr The mapping address.
1764 * @param Phys The physical address of the page to map.
1765 */
1766static int rtR0MemObjLinuxFixPte(struct mm_struct *mm, unsigned long ulAddr, RTHCPHYS Phys)
1767{
1768 int rc = -ENOMEM;
1769 pgd_t *pgd;
1770
1771 spin_lock(&mm->page_table_lock);
1772
1773 pgd = pgd_offset(mm, ulAddr);
1774 if (!pgd_none(*pgd) && !pgd_bad(*pgd))
1775 {
1776 pmd_t *pmd = pmd_offset(pgd, ulAddr);
1777 if (!pmd_none(*pmd))
1778 {
1779 pte_t *ptep = pte_offset_map(pmd, ulAddr);
1780 if (ptep)
1781 {
1782 pte_t pte = *ptep;
1783 pte.pte_high &= 0xfff00000;
1784 pte.pte_high |= ((Phys >> 32) & 0x000fffff);
1785 pte.pte_low &= 0x00000fff;
1786 pte.pte_low |= (Phys & 0xfffff000);
1787 set_pte(ptep, pte);
1788 pte_unmap(ptep);
1789 rc = 0;
1790 }
1791 }
1792 }
1793
1794 spin_unlock(&mm->page_table_lock);
1795 return rc;
1796}
1797#endif /* VBOX_USE_PAE_HACK */
1798
1799
1800DECLHIDDEN(int) rtR0MemObjNativeMapUser(PPRTR0MEMOBJINTERNAL ppMem, RTR0MEMOBJ pMemToMap, RTR3PTR R3PtrFixed, size_t uAlignment,
1801 unsigned fProt, RTR0PROCESS R0Process, size_t offSub, size_t cbSub, const char *pszTag)
1802{
1803 struct task_struct *pTask = rtR0ProcessToLinuxTask(R0Process);
1804 PRTR0MEMOBJLNX pMemLnxToMap = (PRTR0MEMOBJLNX)pMemToMap;
1805 int rc = VERR_NO_MEMORY;
1806 PRTR0MEMOBJLNX pMemLnx;
1807#ifdef VBOX_USE_PAE_HACK
1808 struct page *pDummyPage;
1809 RTHCPHYS DummyPhys;
1810#endif
1811 IPRT_LINUX_SAVE_EFL_AC();
1812
1813 /*
1814 * Check for restrictions.
1815 */
1816 if (!pTask)
1817 return VERR_NOT_SUPPORTED;
1818 if (uAlignment > PAGE_SIZE)
1819 return VERR_NOT_SUPPORTED;
1820
1821#ifdef VBOX_USE_PAE_HACK
1822 /*
1823 * Allocate a dummy page for use when mapping the memory.
1824 */
1825 pDummyPage = alloc_page(GFP_USER | __GFP_NOWARN);
1826 if (!pDummyPage)
1827 {
1828 IPRT_LINUX_RESTORE_EFL_AC();
1829 return VERR_NO_MEMORY;
1830 }
1831 SetPageReserved(pDummyPage);
1832 DummyPhys = page_to_phys(pDummyPage);
1833#endif
1834
1835 /*
1836 * Create the IPRT memory object.
1837 */
1838 Assert(!offSub || cbSub);
1839 if (cbSub == 0)
1840 cbSub = pMemLnxToMap->Core.cb;
1841 pMemLnx = (PRTR0MEMOBJLNX)rtR0MemObjNew(sizeof(*pMemLnx), RTR0MEMOBJTYPE_MAPPING, NULL, cbSub, pszTag);
1842 if (pMemLnx)
1843 {
1844 /*
1845 * Allocate user space mapping.
1846 */
1847 void *pv;
1848 pv = rtR0MemObjLinuxDoMmap(R3PtrFixed, cbSub, uAlignment, pTask, fProt);
1849 if (pv != (void *)-1)
1850 {
1851 /*
1852 * Map page by page into the mmap area.
1853 * This is generic, paranoid and not very efficient.
1854 */
1855 pgprot_t fPg = rtR0MemObjLinuxConvertProt(fProt, false /* user */);
1856 unsigned long ulAddrCur = (unsigned long)pv;
1857 const size_t cPages = (offSub + cbSub) >> PAGE_SHIFT;
1858 size_t iPage;
1859
1860 LNX_MM_DOWN_WRITE(pTask->mm);
1861
1862 rc = VINF_SUCCESS;
1863 if (pMemLnxToMap->cPages)
1864 {
1865 for (iPage = offSub >> PAGE_SHIFT; iPage < cPages; iPage++, ulAddrCur += PAGE_SIZE)
1866 {
1867#if RTLNX_VER_MAX(2,6,11)
1868 RTHCPHYS Phys = page_to_phys(pMemLnxToMap->apPages[iPage]);
1869#endif
1870#if RTLNX_VER_MIN(2,6,0) || defined(HAVE_26_STYLE_REMAP_PAGE_RANGE)
1871 struct vm_area_struct *vma = find_vma(pTask->mm, ulAddrCur); /* this is probably the same for all the pages... */
1872 AssertBreakStmt(vma, rc = VERR_INTERNAL_ERROR);
1873#endif
1874#if RTLNX_VER_MAX(2,6,0) && defined(RT_ARCH_X86)
1875 /* remap_page_range() limitation on x86 */
1876 AssertBreakStmt(Phys < _4G, rc = VERR_NO_MEMORY);
1877#endif
1878
1879#if defined(VBOX_USE_INSERT_PAGE) && RTLNX_VER_MIN(2,6,22)
1880 rc = vm_insert_page(vma, ulAddrCur, pMemLnxToMap->apPages[iPage]);
1881 /* Thes flags help making 100% sure some bad stuff wont happen (swap, core, ++).
1882 * See remap_pfn_range() in mm/memory.c */
1883
1884#if RTLNX_VER_MIN(6,3,0)
1885 vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP);
1886#elif RTLNX_VER_MIN(3,7,0)
1887 vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
1888#else
1889 vma->vm_flags |= VM_RESERVED;
1890#endif
1891#elif RTLNX_VER_MIN(2,6,11)
1892 rc = remap_pfn_range(vma, ulAddrCur, page_to_pfn(pMemLnxToMap->apPages[iPage]), PAGE_SIZE, fPg);
1893#elif defined(VBOX_USE_PAE_HACK)
1894 rc = remap_page_range(vma, ulAddrCur, DummyPhys, PAGE_SIZE, fPg);
1895 if (!rc)
1896 rc = rtR0MemObjLinuxFixPte(pTask->mm, ulAddrCur, Phys);
1897#elif RTLNX_VER_MIN(2,6,0) || defined(HAVE_26_STYLE_REMAP_PAGE_RANGE)
1898 rc = remap_page_range(vma, ulAddrCur, Phys, PAGE_SIZE, fPg);
1899#else /* 2.4 */
1900 rc = remap_page_range(ulAddrCur, Phys, PAGE_SIZE, fPg);
1901#endif
1902 if (rc)
1903 {
1904 rc = VERR_NO_MEMORY;
1905 break;
1906 }
1907 }
1908 }
1909 else
1910 {
1911 RTHCPHYS Phys;
1912 if (pMemLnxToMap->Core.enmType == RTR0MEMOBJTYPE_PHYS)
1913 Phys = pMemLnxToMap->Core.u.Phys.PhysBase;
1914 else if (pMemLnxToMap->Core.enmType == RTR0MEMOBJTYPE_CONT)
1915 Phys = pMemLnxToMap->Core.u.Cont.Phys;
1916 else
1917 {
1918 AssertMsgFailed(("%d\n", pMemLnxToMap->Core.enmType));
1919 Phys = NIL_RTHCPHYS;
1920 }
1921 if (Phys != NIL_RTHCPHYS)
1922 {
1923 for (iPage = offSub >> PAGE_SHIFT; iPage < cPages; iPage++, ulAddrCur += PAGE_SIZE, Phys += PAGE_SIZE)
1924 {
1925#if RTLNX_VER_MIN(2,6,0) || defined(HAVE_26_STYLE_REMAP_PAGE_RANGE)
1926 struct vm_area_struct *vma = find_vma(pTask->mm, ulAddrCur); /* this is probably the same for all the pages... */
1927 AssertBreakStmt(vma, rc = VERR_INTERNAL_ERROR);
1928#endif
1929#if RTLNX_VER_MAX(2,6,0) && defined(RT_ARCH_X86)
1930 /* remap_page_range() limitation on x86 */
1931 AssertBreakStmt(Phys < _4G, rc = VERR_NO_MEMORY);
1932#endif
1933
1934#if RTLNX_VER_MIN(2,6,11)
1935 rc = remap_pfn_range(vma, ulAddrCur, Phys, PAGE_SIZE, fPg);
1936#elif defined(VBOX_USE_PAE_HACK)
1937 rc = remap_page_range(vma, ulAddrCur, DummyPhys, PAGE_SIZE, fPg);
1938 if (!rc)
1939 rc = rtR0MemObjLinuxFixPte(pTask->mm, ulAddrCur, Phys);
1940#elif RTLNX_VER_MIN(2,6,0) || defined(HAVE_26_STYLE_REMAP_PAGE_RANGE)
1941 rc = remap_page_range(vma, ulAddrCur, Phys, PAGE_SIZE, fPg);
1942#else /* 2.4 */
1943 rc = remap_page_range(ulAddrCur, Phys, PAGE_SIZE, fPg);
1944#endif
1945 if (rc)
1946 {
1947 rc = VERR_NO_MEMORY;
1948 break;
1949 }
1950 }
1951 }
1952 }
1953
1954#ifdef CONFIG_NUMA_BALANCING
1955# if RTLNX_VER_MAX(3,13,0) && RTLNX_RHEL_MAX(7,0)
1956# define VBOX_NUMA_HACK_OLD
1957# endif
1958 if (RT_SUCCESS(rc))
1959 {
1960 /** @todo Ugly hack! But right now we have no other means to
1961 * disable automatic NUMA page balancing. */
1962# ifdef RT_OS_X86
1963# ifdef VBOX_NUMA_HACK_OLD
1964 pTask->mm->numa_next_reset = jiffies + 0x7fffffffUL;
1965# endif
1966 pTask->mm->numa_next_scan = jiffies + 0x7fffffffUL;
1967# else
1968# ifdef VBOX_NUMA_HACK_OLD
1969 pTask->mm->numa_next_reset = jiffies + 0x7fffffffffffffffUL;
1970# endif
1971 pTask->mm->numa_next_scan = jiffies + 0x7fffffffffffffffUL;
1972# endif
1973 }
1974#endif /* CONFIG_NUMA_BALANCING */
1975
1976 LNX_MM_UP_WRITE(pTask->mm);
1977
1978 if (RT_SUCCESS(rc))
1979 {
1980#ifdef VBOX_USE_PAE_HACK
1981 __free_page(pDummyPage);
1982#endif
1983 pMemLnx->Core.pv = pv;
1984 pMemLnx->Core.u.Mapping.R0Process = R0Process;
1985 *ppMem = &pMemLnx->Core;
1986 IPRT_LINUX_RESTORE_EFL_AC();
1987 return VINF_SUCCESS;
1988 }
1989
1990 /*
1991 * Bail out.
1992 */
1993 rtR0MemObjLinuxDoMunmap(pv, cbSub, pTask);
1994 }
1995 rtR0MemObjDelete(&pMemLnx->Core);
1996 }
1997#ifdef VBOX_USE_PAE_HACK
1998 __free_page(pDummyPage);
1999#endif
2000
2001 IPRT_LINUX_RESTORE_EFL_AC();
2002 return rc;
2003}
2004
2005
2006DECLHIDDEN(int) rtR0MemObjNativeProtect(PRTR0MEMOBJINTERNAL pMem, size_t offSub, size_t cbSub, uint32_t fProt)
2007{
2008# ifdef IPRT_USE_ALLOC_VM_AREA_FOR_EXEC
2009 /*
2010 * Currently only supported when we've got addresses PTEs from the kernel.
2011 */
2012 PRTR0MEMOBJLNX pMemLnx = (PRTR0MEMOBJLNX)pMem;
2013 if (pMemLnx->pArea && pMemLnx->papPtesForArea)
2014 {
2015 pgprot_t const fPg = rtR0MemObjLinuxConvertProt(fProt, true /*fKernel*/);
2016 size_t const cPages = (offSub + cbSub) >> PAGE_SHIFT;
2017 pte_t **papPtes = pMemLnx->papPtesForArea;
2018 size_t i;
2019
2020 for (i = offSub >> PAGE_SHIFT; i < cPages; i++)
2021 {
2022 set_pte(papPtes[i], mk_pte(pMemLnx->apPages[i], fPg));
2023 }
2024 preempt_disable();
2025 __flush_tlb_all();
2026 preempt_enable();
2027 return VINF_SUCCESS;
2028 }
2029# elif defined(IPRT_USE_APPLY_TO_PAGE_RANGE_FOR_EXEC)
2030 PRTR0MEMOBJLNX pMemLnx = (PRTR0MEMOBJLNX)pMem;
2031 if ( pMemLnx->fExecutable
2032 && pMemLnx->fMappedToRing0)
2033 {
2034 LNXAPPLYPGRANGE Args;
2035 Args.pMemLnx = pMemLnx;
2036 Args.fPg = rtR0MemObjLinuxConvertProt(fProt, true /*fKernel*/);
2037 int rcLnx = apply_to_page_range(current->active_mm, (unsigned long)pMemLnx->Core.pv + offSub, cbSub,
2038 rtR0MemObjLinuxApplyPageRange, (void *)&Args);
2039 if (rcLnx)
2040 return VERR_NOT_SUPPORTED;
2041
2042 return VINF_SUCCESS;
2043 }
2044# endif
2045
2046 NOREF(pMem);
2047 NOREF(offSub);
2048 NOREF(cbSub);
2049 NOREF(fProt);
2050 return VERR_NOT_SUPPORTED;
2051}
2052
2053
2054DECLHIDDEN(RTHCPHYS) rtR0MemObjNativeGetPagePhysAddr(PRTR0MEMOBJINTERNAL pMem, size_t iPage)
2055{
2056 PRTR0MEMOBJLNX pMemLnx = (PRTR0MEMOBJLNX)pMem;
2057
2058 if (pMemLnx->cPages)
2059 return page_to_phys(pMemLnx->apPages[iPage]);
2060
2061 switch (pMemLnx->Core.enmType)
2062 {
2063 case RTR0MEMOBJTYPE_CONT:
2064 return pMemLnx->Core.u.Cont.Phys + (iPage << PAGE_SHIFT);
2065
2066 case RTR0MEMOBJTYPE_PHYS:
2067 return pMemLnx->Core.u.Phys.PhysBase + (iPage << PAGE_SHIFT);
2068
2069 /* the parent knows */
2070 case RTR0MEMOBJTYPE_MAPPING:
2071 return rtR0MemObjNativeGetPagePhysAddr(pMemLnx->Core.uRel.Child.pParent, iPage);
2072
2073 /* cPages > 0 */
2074 case RTR0MEMOBJTYPE_LOW:
2075 case RTR0MEMOBJTYPE_LOCK:
2076 case RTR0MEMOBJTYPE_PHYS_NC:
2077 case RTR0MEMOBJTYPE_PAGE:
2078 case RTR0MEMOBJTYPE_LARGE_PAGE:
2079 default:
2080 AssertMsgFailed(("%d\n", pMemLnx->Core.enmType));
2081 RT_FALL_THROUGH();
2082
2083 case RTR0MEMOBJTYPE_RES_VIRT:
2084 return NIL_RTHCPHYS;
2085 }
2086}
2087
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette