关于Transparent Hugepage

来源:互联网 发布:哪些端口不是敏感端口 编辑:程序博客网 时间:2024/04/17 04:40
1= Transparent Hugepage Support =23== Objective ==45Performance critical computing applications dealing with large memory6working sets are already running on top of libhugetlbfs and in turn7hugetlbfs. Transparent Hugepage Support is an alternative means of8using huge pages for the backing of virtual memory with huge pages9that supports the automatic promotion and demotion of page sizes and10without the shortcomings of hugetlbfs.1112Currently it only works for anonymous memory mappings but in the13future it can expand over the pagecache layer starting with tmpfs.1415The reason applications are running faster is because of two16factors. The first factor is almost completely irrelevant and it's not17of significant interest because it'll also have the downside of18requiring larger clear-page copy-page in page faults which is a19potentially negative effect. The first factor consists in taking a20single page fault for each 2M virtual region touched by userland (so21reducing the enter/exit kernel frequency by a 512 times factor). This22only matters the first time the memory is accessed for the lifetime of23a memory mapping. The second long lasting and much more important24factor will affect all subsequent accesses to the memory for the whole25runtime of the application. The second factor consist of two26components: 1) the TLB miss will run faster (especially with27virtualization using nested pagetables but almost always also on bare28metal without virtualization) and 2) a single TLB entry will be29mapping a much larger amount of virtual memory in turn reducing the30number of TLB misses. With virtualization and nested pagetables the31TLB can be mapped of larger size only if both KVM and the Linux guest32are using hugepages but a significant speedup already happens if only33one of the two is using hugepages just because of the fact the TLB34miss is going to run faster.3536== Design ==3738- "graceful fallback": mm components which don't have transparent39  hugepage knowledge fall back to breaking a transparent hugepage and40  working on the regular pages and their respective regular pmd/pte41  mappings4243- if a hugepage allocation fails because of memory fragmentation,44  regular pages should be gracefully allocated instead and mixed in45  the same vma without any failure or significant delay and without46  userland noticing4748- if some task quits and more hugepages become available (either49  immediately in the buddy or through the VM), guest physical memory50  backed by regular pages should be relocated on hugepages51  automatically (with khugepaged)5253- it doesn't require memory reservation and in turn it uses hugepages54  whenever possible (the only possible reservation here is kernelcore=55  to avoid unmovable pages to fragment all the memory but such a tweak56  is not specific to transparent hugepage support and it's a generic57  feature that applies to all dynamic high order allocations in the58  kernel)5960- this initial support only offers the feature in the anonymous memory61  regions but it'd be ideal to move it to tmpfs and the pagecache62  later6364Transparent Hugepage Support maximizes the usefulness of free memory65if compared to the reservation approach of hugetlbfs by allowing all66unused memory to be used as cache or other movable (or even unmovable67entities). It doesn't require reservation to prevent hugepage68allocation failures to be noticeable from userland. It allows paging69and all other advanced VM features to be available on the70hugepages. It requires no modifications for applications to take71advantage of it.7273Applications however can be further optimized to take advantage of74this feature, like for example they've been optimized before to avoid75a flood of mmap system calls for every malloc(4k). Optimizing userland76is by far not mandatory and khugepaged already can take care of long77lived page allocations even for hugepage unaware applications that78deals with large amounts of memory.7980In certain cases when hugepages are enabled system wide, application81may end up allocating more memory resources. An application may mmap a82large region but only touch 1 byte of it, in that case a 2M page might83be allocated instead of a 4k page for no good. This is why it's84possible to disable hugepages system-wide and to only have them inside85MADV_HUGEPAGE madvise regions.8687Embedded systems should enable hugepages only inside madvise regions88to eliminate any risk of wasting any precious byte of memory and to89only run faster.9091Applications that gets a lot of benefit from hugepages and that don't92risk to lose memory by using hugepages, should use93madvise(MADV_HUGEPAGE) on their critical mmapped regions.9495== sysfs ==9697Transparent Hugepage Support can be entirely disabled (mostly for98debugging purposes) or only enabled inside MADV_HUGEPAGE regions (to99avoid the risk of consuming more memory resources) or enabled system100wide. This can be achieved with one of:101102echo always >/sys/kernel/mm/transparent_hugepage/enabled103echo madvise >/sys/kernel/mm/transparent_hugepage/enabled104echo never >/sys/kernel/mm/transparent_hugepage/enabled105106It's also possible to limit defrag efforts in the VM to generate107hugepages in case they're not immediately free to madvise regions or108to never try to defrag memory and simply fallback to regular pages109unless hugepages are immediately available. Clearly if we spend CPU110time to defrag memory, we would expect to gain even more by the fact111we use hugepages later instead of regular pages. This isn't always112guaranteed, but it may be more likely in case the allocation is for a113MADV_HUGEPAGE region.114115echo always >/sys/kernel/mm/transparent_hugepage/defrag116echo madvise >/sys/kernel/mm/transparent_hugepage/defrag117echo never >/sys/kernel/mm/transparent_hugepage/defrag118119By default kernel tries to use huge zero page on read page fault.120It's possible to disable huge zero page by writing 0 or enable it121back by writing 1:122123echo 0 >/sys/kernel/mm/transparent_hugepage/khugepaged/use_zero_page124echo 1 >/sys/kernel/mm/transparent_hugepage/khugepaged/use_zero_page125126khugepaged will be automatically started when127transparent_hugepage/enabled is set to "always" or "madvise, and it'll128be automatically shutdown if it's set to "never".129130khugepaged runs usually at low frequency so while one may not want to131invoke defrag algorithms synchronously during the page faults, it132should be worth invoking defrag at least in khugepaged. However it's133also possible to disable defrag in khugepaged by writing 0 or enable134defrag in khugepaged by writing 1:135136echo 0 >/sys/kernel/mm/transparent_hugepage/khugepaged/defrag137echo 1 >/sys/kernel/mm/transparent_hugepage/khugepaged/defrag138139You can also control how many pages khugepaged should scan at each140pass:141142/sys/kernel/mm/transparent_hugepage/khugepaged/pages_to_scan143144and how many milliseconds to wait in khugepaged between each pass (you145can set this to 0 to run khugepaged at 100% utilization of one core):146147/sys/kernel/mm/transparent_hugepage/khugepaged/scan_sleep_millisecs148149and how many milliseconds to wait in khugepaged if there's an hugepage150allocation failure to throttle the next allocation attempt.151152/sys/kernel/mm/transparent_hugepage/khugepaged/alloc_sleep_millisecs153154The khugepaged progress can be seen in the number of pages collapsed:155156/sys/kernel/mm/transparent_hugepage/khugepaged/pages_collapsed157158for each pass:159160/sys/kernel/mm/transparent_hugepage/khugepaged/full_scans161162== Boot parameter ==163164You can change the sysfs boot time defaults of Transparent Hugepage165Support by passing the parameter "transparent_hugepage=always" or166"transparent_hugepage=madvise" or "transparent_hugepage=never"167(without "") to the kernel command line.168169== Need of application restart ==170171The transparent_hugepage/enabled values only affect future172behavior. So to make them effective you need to restart any173application that could have been using hugepages. This also applies to174the regions registered in khugepaged.175176== Monitoring usage ==177178The number of transparent huge pages currently used by the system is179available by reading the AnonHugePages field in /proc/meminfo. To180identify what applications are using transparent huge pages, it is181necessary to read /proc/PID/smaps and count the AnonHugePages fields182for each mapping. Note that reading the smaps file is expensive and183reading it frequently will incur overhead.184185There are a number of counters in /proc/vmstat that may be used to186monitor how successfully the system is providing huge pages for use.187188thp_fault_alloc is incremented every time a huge page is successfully189allocated to handle a page fault. This applies to both the190first time a page is faulted and for COW faults.191192thp_collapse_alloc is incremented by khugepaged when it has found193a range of pages to collapse into one huge page and has194successfully allocated a new huge page to store the data.195196thp_fault_fallback is incremented if a page fault fails to allocate197a huge page and instead falls back to using small pages.198199thp_collapse_alloc_failed is incremented if khugepaged found a range200of pages that should be collapsed into one huge page but failed201the allocation.202203thp_split is incremented every time a huge page is split into base204pages. This can happen for a variety of reasons but a common205reason is that a huge page is old and is being reclaimed.206207thp_zero_page_alloc is incremented every time a huge zero page is208successfully allocated. It includes allocations which where209dropped due race with other allocation. Note, it doesn't count210every map of the huge zero page, only its allocation.211212thp_zero_page_alloc_failed is incremented if kernel fails to allocate213huge zero page and falls back to using small pages.214215As the system ages, allocating huge pages may be expensive as the216system uses memory compaction to copy data around memory to free a217huge page for use. There are some counters in /proc/vmstat to help218monitor this overhead.219220compact_stall is incremented every time a process stalls to run221memory compaction so that a huge page is free for use.222223compact_success is incremented if the system compacted memory and224freed a huge page for use.225226compact_fail is incremented if the system tries to compact memory227but failed.228229compact_pages_moved is incremented each time a page is moved. If230this value is increasing rapidly, it implies that the system231is copying a lot of data to satisfy the huge page allocation.232It is possible that the cost of copying exceeds any savings233from reduced TLB misses.234235compact_pagemigrate_failed is incremented when the underlying mechanism236for moving a page failed.237238compact_blocks_moved is incremented each time memory compaction examines239a huge page aligned range of pages.240241It is possible to establish how long the stalls were using the function242tracer to record how long was spent in __alloc_pages_nodemask and243using the mm_page_alloc tracepoint to identify which allocations were244for huge pages.245246== get_user_pages and follow_page ==247248get_user_pages and follow_page if run on a hugepage, will return the249head or tail pages as usual (exactly as they would do on250hugetlbfs). Most gup users will only care about the actual physical251address of the page and its temporary pinning to release after the I/O252is complete, so they won't ever notice the fact the page is huge. But253if any driver is going to mangle over the page structure of the tail254page (like for checking page->mapping or other bits that are relevant255for the head page and not the tail page), it should be updated to jump256to check head page instead (while serializing properly against257split_huge_page() to avoid the head and tail pages to disappear from258under it, see the futex code to see an example of that, hugetlbfs also259needed special handling in futex code for similar reasons).260261NOTE: these aren't new constraints to the GUP API, and they match the262same constrains that applies to hugetlbfs too, so any driver capable263of handling GUP on hugetlbfs will also work fine on transparent264hugepage backed mappings.265266In case you can't handle compound pages if they're returned by267follow_page, the FOLL_SPLIT bit can be specified as parameter to268follow_page, so that it will split the hugepages before returning269them. Migration for example passes FOLL_SPLIT as parameter to270follow_page because it's not hugepage aware and in fact it can't work271at all on hugetlbfs (but it instead works fine on transparent272hugepages thanks to FOLL_SPLIT). migration simply can't deal with273hugepages being returned (as it's not only checking the pfn of the274page and pinning it during the copy but it pretends to migrate the275memory in regular page sizes and with regular pte/pmd mappings).276277== Optimizing the applications ==278279To be guaranteed that the kernel will map a 2M page immediately in any280memory region, the mmap region has to be hugepage naturally281aligned. posix_memalign() can provide that guarantee.282283== Hugetlbfs ==284285You can use hugetlbfs on a kernel that has transparent hugepage286support enabled just fine as always. No difference can be noted in287hugetlbfs other than there will be less overall fragmentation. All288usual features belonging to hugetlbfs are preserved and289unaffected. libhugetlbfs will also work fine as usual.290291== Graceful fallback ==292293Code walking pagetables but unware about huge pmds can simply call294split_huge_page_pmd(vma, addr, pmd) where the pmd is the one returned by295pmd_offset. It's trivial to make the code transparent hugepage aware296by just grepping for "pmd_offset" and adding split_huge_page_pmd where297missing after pmd_offset returns the pmd. Thanks to the graceful298fallback design, with a one liner change, you can avoid to write299hundred if not thousand of lines of complex code to make your code300hugepage aware.301302If you're not walking pagetables but you run into a physical hugepage303but you can't handle it natively in your code, you can split it by304calling split_huge_page(page). This is what the Linux VM does before305it tries to swapout the hugepage for example.306307Example to make mremap.c transparent hugepage aware with a one liner308change:309310diff --git a/mm/mremap.c b/mm/mremap.c311--- a/mm/mremap.c312+++ b/mm/mremap.c313@@ -41,6 +41,7 @@ static pmd_t *get_old_pmd(struct mm_stru314return NULL;315316pmd = pmd_offset(pud, addr);317+split_huge_page_pmd(vma, addr, pmd);318if (pmd_none_or_clear_bad(pmd))319return NULL;320321== Locking in hugepage aware code ==322323We want as much code as possible hugepage aware, as calling324split_huge_page() or split_huge_page_pmd() has a cost.325326To make pagetable walks huge pmd aware, all you need to do is to call327pmd_trans_huge() on the pmd returned by pmd_offset. You must hold the328mmap_sem in read (or write) mode to be sure an huge pmd cannot be329created from under you by khugepaged (khugepaged collapse_huge_page330takes the mmap_sem in write mode in addition to the anon_vma lock). If331pmd_trans_huge returns false, you just fallback in the old code332paths. If instead pmd_trans_huge returns true, you have to take the333mm->page_table_lock and re-run pmd_trans_huge. Taking the334page_table_lock will prevent the huge pmd to be converted into a335regular pmd from under you (split_huge_page can run in parallel to the336pagetable walk). If the second pmd_trans_huge returns false, you337should just drop the page_table_lock and fallback to the old code as338before. Otherwise you should run pmd_trans_splitting on the pmd. In339case pmd_trans_splitting returns true, it means split_huge_page is340already in the middle of splitting the page. So if pmd_trans_splitting341returns true it's enough to drop the page_table_lock and call342wait_split_huge_page and then fallback the old code paths. You are343guaranteed by the time wait_split_huge_page returns, the pmd isn't344huge anymore. If pmd_trans_splitting returns false, you can proceed to345process the huge pmd and the hugepage natively. Once finished you can346drop the page_table_lock.347348== compound_lock, get_user_pages and put_page ==349350split_huge_page internally has to distribute the refcounts in the head351page to the tail pages before clearing all PG_head/tail bits from the352page structures. It can do that easily for refcounts taken by huge pmd353mappings. But the GUI API as created by hugetlbfs (that returns head354and tail pages if running get_user_pages on an address backed by any355hugepage), requires the refcount to be accounted on the tail pages and356not only in the head pages, if we want to be able to run357split_huge_page while there are gup pins established on any tail358page. Failure to be able to run split_huge_page if there's any gup pin359on any tail page, would mean having to split all hugepages upfront in360get_user_pages which is unacceptable as too many gup users are361performance critical and they must work natively on hugepages like362they work natively on hugetlbfs already (hugetlbfs is simpler because363hugetlbfs pages cannot be splitted so there wouldn't be requirement of364accounting the pins on the tail pages for hugetlbfs). If we wouldn't365account the gup refcounts on the tail pages during gup, we won't know366anymore which tail page is pinned by gup and which is not while we run367split_huge_page. But we still have to add the gup pin to the head page368too, to know when we can free the compound page in case it's never369splitted during its lifetime. That requires changing not just370get_page, but put_page as well so that when put_page runs on a tail371page (and only on a tail page) it will find its respective head page,372and then it will decrease the head page refcount in addition to the373tail page refcount. To obtain a head page reliably and to decrease its374refcount without race conditions, put_page has to serialize against375__split_huge_page_refcount using a special per-page lock called376compound_lock.
原创粉丝点击