<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Linux | Easton Man's Blog</title>
	<atom:link href="https://blog.eastonman.com/blog/tag/linux/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.eastonman.com</link>
	<description>临渊羡鱼，不如退而结网</description>
	<lastBuildDate>Sat, 07 Jan 2023 07:06:18 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.6</generator>

<image>
	<url>https://blog.eastonman.com/wp-content/uploads/2021/02/cropped-Logo-e1613298891313-32x32.png</url>
	<title>Linux | Easton Man's Blog</title>
	<link>https://blog.eastonman.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Bash History的使用技巧</title>
		<link>https://blog.eastonman.com/blog/2021/06/bash-history-tricks/</link>
					<comments>https://blog.eastonman.com/blog/2021/06/bash-history-tricks/#comments</comments>
		
		<dc:creator><![CDATA[Easton Man]]></dc:creator>
		<pubDate>Thu, 10 Jun 2021 14:51:35 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[Bash]]></category>
		<guid isPermaLink="false">https://blog.eastonman.com/?p=792</guid>

					<description><![CDATA[<p>Bash是常见的shell环境，大多数Linux发行版也都带有Bash，因此高效地利用history可以节省手动输入重复命令的时间。本文分享一下几个我自己使用的技巧和配置。</p>
The post <a href="https://blog.eastonman.com/blog/2021/06/bash-history-tricks/">Bash History的使用技巧</a> first appeared on <a href="https://blog.eastonman.com">Easton Man's Blog</a>.]]></description>
										<content:encoded><![CDATA[<p class="wpwc-reading-time">预计阅读时间： 3 分钟</p>
<p>Bash是常见的shell环境，大多数Linux发行版也都带有Bash，因此高效地利用history可以节省手动输入重复命令的时间。本文分享一下几个我自己使用的技巧和配置。</p>



<h3 class="wp-block-heading">搜索</h3>



<p>这个技巧大家应该多少都知道，就是在输入界面按<code>Ctrl-R</code>就可以进行搜索了，返回的结果是最近一个匹配的命令，然后按回车就可以执行。</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="526" height="220" src="https://blog.eastonman.com/wp-content/uploads/2021/06/image.png" alt="" class="wp-image-794" srcset="https://blog.eastonman.com/wp-content/uploads/2021/06/image.png 526w, https://blog.eastonman.com/wp-content/uploads/2021/06/image-300x125.png 300w" sizes="(max-width: 526px) 100vw, 526px" /><figcaption>Ctrl-R</figcaption></figure></div>



<p>但是有的时候搜索结果只是与我想要的很相近，但又不完全一样，我希望能够在执行之前对命令做小的修改，那怎么办?其实此时按Esc就可以退出并且编辑。</p>



<p>还有一个方式是利用<code>:p</code>，<code>:p</code>在Bash中表示打印但不执行，因此如果我们想要查看某个前缀的命令，就可以使用<code>!prefix:p</code>来打印。</p>



<h3 class="wp-block-heading">HISTIGNORE</h3>



<p>HISTIGNORE是一个环境变量，它指示Bash什么样的命令不要加入history中，例如这样的一个变量。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">export HISTIGNORE='pwd:exit:fg:bg:top:clear:history:ls:uptime:df'</pre>



<p>就可以把无意义的交互命令从history中去除了。如果你经常使用<code>ll</code>或者<code>la</code>这样的简写，那么把他们加入HISTIGNORE中或许是一个不错的选择。</p>



<h3 class="wp-block-heading">HISTCONTROL</h3>



<p>HISTCONTROL也是一个环境变量，它有几个选择</p>



<ul class="wp-block-list"><li>ignorespace：以空格开头的所有命令都不会加入history中</li><li>ignoredups：重复的命令不会加入history中</li><li>ignoreboth：打开以上的两个特性</li></ul>



<p>通常一些发行版已经带有ignoredups的选项，如果你想要避免某些特定的命令计入history中，那么可以打开ignorespace选项。</p>



<h3 class="wp-block-heading">并行的窗口之间的history问题</h3>



<p>这个问题相信很多同学也会有，在远程管理服务器的时候，通常为了某些监视任务或者耗时长的任务不阻塞人的操作，会使用各种窗口复用工具，比如<code>tmux</code>或者<code>screen</code>，那么由于Bash在关闭的时候才会将history写入<code>.bash_history</code>文件，那么大多数时候当我们关闭这些窗口以后就只有最后一个关闭的窗口的History被记录了下来。</p>



<p>我们可以使用</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">shopt -s histappend</pre>



<p>来指示Bash讲history附加到原本的history上而不是覆盖。</p>



<h3 class="wp-block-heading">使用!来执行history中的命令</h3>



<p>!可以用来执行命令，比如!10就是执行history中的第10条命令。当然也可以执行最近的第几条命令，比如!-3就是倒数第三条命令。</p>



<p>这里还可以结合<code>:p</code>使用，以避免直接执行带来的风险。</p>



<p>如果你一定要避免所有的风险，每次都希望检查命令再执行，而又不想输入<code>:p</code>，那么Bash还有一个选项可以做到这一点：<code>shopt -s histverify</code>。这个选项会使得所有用!执行的命令都需要按Enter键确认才会执行。</p>



<h3 class="wp-block-heading">使用上一个命令的参数</h3>



<p>!$和!*分别会将上一个命令的最后一个参数和所有参数填补到这个位置，例如</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ mv list.txt items.txt
$ vim !$
vim items.txt
$ cp !$ shopping.txt
cp items.txt shopping.txt</pre>



<p></p>The post <a href="https://blog.eastonman.com/blog/2021/06/bash-history-tricks/">Bash History的使用技巧</a> first appeared on <a href="https://blog.eastonman.com">Easton Man's Blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.eastonman.com/blog/2021/06/bash-history-tricks/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Git: Failed sending HTTP2 data解决办法</title>
		<link>https://blog.eastonman.com/blog/2021/04/git-failed-sending-http2-data/</link>
					<comments>https://blog.eastonman.com/blog/2021/04/git-failed-sending-http2-data/#comments</comments>
		
		<dc:creator><![CDATA[Easton Man]]></dc:creator>
		<pubDate>Sun, 25 Apr 2021 12:47:30 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[Git]]></category>
		<guid isPermaLink="false">https://blog.eastonman.com/?p=556</guid>

					<description><![CDATA[<p>预计阅读时间： 5 分钟 最近一段时间发现手中的Debian机器在Git Clone的时候出现奇怪的错误，经过 [&#8230;]</p>
The post <a href="https://blog.eastonman.com/blog/2021/04/git-failed-sending-http2-data/">Git: Failed sending HTTP2 data解决办法</a> first appeared on <a href="https://blog.eastonman.com">Easton Man's Blog</a>.]]></description>
										<content:encoded><![CDATA[<p class="wpwc-reading-time">预计阅读时间： 5 分钟</p>
<p>最近一段时间发现手中的Debian机器在Git Clone的时候出现奇怪的错误，经过一番Google，最终发现是libcurl3-gnutls这个库的bug。</p>



<p></p>



<p>2021-10-01 Update: Buster-backports仍未修复此问题，但是Bullseye已经合入了新的版本，修复了此问题。</p>



<p>2021-06-19 Update: 修复补丁仍未合入backports中，问题的原因似乎是libcurl-guntls的TLSv1.3实现有问题。</p>



<p>2021-08-03 Update: Curl 7.76.1修复了此问题，但尚未合并进入Buster backports, Bullseye也未更新。</p>



<h2 class="wp-block-heading">现象</h2>



<p>在使用https协议进行git clone的时候，出现HTTP2报错</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">xxxxx$> git clone https://github.com/TechMinerApps/portier
Cloning into 'portier'...
fatal: unable to access 'https://github.com/TechMinerApps/portier/': Failed sending HTTP2 data</pre>



<p>起初我以为和GitHub即将禁止Basic Auth的https操作有关，但是使用<code>GIT_TRACE2=2 GIT_CURL_VERBOSE=1</code>进行调试的时候，发现是curl中的问题。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">20:35:22.968833 http.c:756              == Info: Couldn't find host github.com in the .netrc file; using defaults
20:35:22.973819 http.c:756              == Info:   Trying 192.30.255.113:443...
20:35:23.144791 http.c:756              == Info: Connected to github.com (192.30.255.113) port 443 (#0)
20:35:23.168789 http.c:756              == Info: found 411 certificates in /etc/ssl/certs
20:35:23.169022 http.c:756              == Info: ALPN, offering h2
20:35:23.169092 http.c:756              == Info: ALPN, offering http/1.1
20:35:23.341023 http.c:756              == Info: SSL connection using TLS1.3 / ECDHE_RSA_AES_128_GCM_SHA256
20:35:23.341674 http.c:756              == Info:         server certificate verification OK
20:35:23.341682 http.c:756              == Info:         server certificate status verification SKIPPED
20:35:23.341750 http.c:756              == Info:         common name: github.com (matched)
20:35:23.341754 http.c:756              == Info:         server certificate expiration date OK
20:35:23.341757 http.c:756              == Info:         server certificate activation date OK
20:35:23.341763 http.c:756              == Info:         certificate public key: EC/ECDSA
20:35:23.341766 http.c:756              == Info:         certificate version: #3
20:35:23.341786 http.c:756              == Info:         subject: C=US,ST=California,L=San Francisco,O=GitHub\, Inc.,CN=github.com
20:35:23.341791 http.c:756              == Info:         start date: Thu, 25 Mar 2021 00:00:00 GMT
20:35:23.341795 http.c:756              == Info:         expire date: Wed, 30 Mar 2022 23:59:59 GMT
20:35:23.341807 http.c:756              == Info:         issuer: C=US,O=DigiCert\, Inc.,CN=DigiCert High Assurance TLS Hybrid ECC SHA256 2020 CA1
20:35:23.341818 http.c:756              == Info: ALPN, server accepted to use h2
20:35:23.341851 http.c:756              == Info: Using HTTP2, server supports multi-use
20:35:23.341853 http.c:756              == Info: Connection state changed (HTTP/2 confirmed)
20:35:23.341858 http.c:756              == Info: Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
20:35:23.341866 http.c:756              == Info: Failed sending HTTP2 data
20:35:23.341873 http.c:756              == Info: Connection #0 to host github.com left intact</pre>



<p>随即Google了一番后找到了Debian Bug Tracker中的一个提交 <a href="https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=987187" target="_blank" rel="noreferrer noopener" title="https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=987187">libcurl3-gnutls from debian backports breaks git http operations</a></p>



<p>原文如下，完全一模一样。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Package: libcurl3-gnutls
Version: 7.74.0-1.2~bpo10+1
Severity: important
|X-Debbugs-CC: |debian-backports@lists.debian.org

After upgrading the Debian system from "backports" any git http operations (clone/fetch ...) has stopped working, bringing libcurl3-gnutls to the previous version (7.74.0-1.2~bpo10+1) fix the problem:

Output of git command
> git clone https://github.com/git/git
Cloning into 'git'...
fatal: unable to access 'https://github.com/git/git/': Failed sending HTTP2 data
>

-- apt-cache policy libcurl3-gnutls
libcurl3-gnutls:
  Installato: 7.74.0-1.2~bpo10+1
  Candidato:  7.74.0-1.2~bpo10+1
  Tabella versione:
 *** 7.74.0-1.2~bpo10+1 100
        100 https://deb.debian.org/debian buster-backports/main amd64 Packages
        100 /var/lib/dpkg/status
     7.64.0-4+deb10u2 500
        500 https://deb.debian.org/debian-security buster/updates/main amd64 Packages
     7.64.0-4+deb10u1 500
        500 https://deb.debian.org/debian buster/main amd64 Packages

-- Extra detailed informations:
- Output of GIT_CURL_VERBOSE=1 GIT_TRACE2=1 git clone https://github.com/git/git
13:03:36.251941 common-main.c:48                  version 2.29.2
13:03:36.251960 common-main.c:49                  start git clone https://github.com/git/git
13:03:36.251981 git.c:445                         cmd_name clone (clone)
13:03:36.252185 repository.c:130                  worktree /tmp/gh/git
Clone in 'git' in corso...
13:03:36.253276 run-command.c:735                 child_start[0] git remote-https origin https://github.com/git/git
13:03:36.254468 common-main.c:48                  version 2.29.2
13:03:36.254485 common-main.c:49                  start /usr/lib/git-core/git remote-https origin https://github.com/git/git
13:03:36.254572 git.c:723                         cmd_name _run_dashed_ (clone/_run_dashed_)
13:03:36.254586 run-command.c:735                 child_start[0] git-remote-https origin https://github.com/git/git
13:03:36.259050 common-main.c:48                  version 2.29.2
13:03:36.259065 common-main.c:49                  start /usr/lib/git-core/git-remote-https origin https://github.com/git/git
13:03:36.259138 repository.c:130                  worktree /tmp/gh
13:03:36.259176 remote-curl.c:1482                cmd_name remote-curl (clone/_run_dashed_/remote-curl)
13:03:36.259581 http.c:756              == Info: Couldn't find host github.com in the .netrc file; using defaults
13:03:36.469244 http.c:756              == Info:   Trying 140.82.121.3:443...
13:03:36.520476 http.c:756              == Info: Connected to github.com (140.82.121.3) port 443 (#0)
13:03:36.544248 http.c:756              == Info: found 381 certificates in /etc/ssl/certs
13:03:36.544365 http.c:756              == Info: ALPN, offering h2
13:03:36.544371 http.c:756              == Info: ALPN, offering http/1.1
13:03:36.595957 http.c:756              == Info: SSL connection using TLS1.3 / ECDHE_RSA_AES_128_GCM_SHA256
13:03:36.596671 http.c:756              == Info: 	 server certificate verification OK
13:03:36.596680 http.c:756              == Info: 	 server certificate status verification SKIPPED
13:03:36.596778 http.c:756              == Info: 	 common name: github.com (matched)
13:03:36.596786 http.c:756              == Info: 	 server certificate expiration date OK
13:03:36.596790 http.c:756              == Info: 	 server certificate activation date OK
13:03:36.596799 http.c:756              == Info: 	 certificate public key: EC/ECDSA
13:03:36.596804 http.c:756              == Info: 	 certificate version: #3
13:03:36.596838 http.c:756              == Info: 	 subject: C=US,ST=California,L=San Francisco,O=GitHub\, Inc.,CN=github.com
13:03:36.596854 http.c:756              == Info: 	 start date: Thu, 25 Mar 2021 00:00:00 GMT
13:03:36.596868 http.c:756              == Info: 	 expire date: Wed, 30 Mar 2022 23:59:59 GMT
13:03:36.596884 http.c:756              == Info: 	 issuer: C=US,O=DigiCert\, Inc.,CN=DigiCert High Assurance TLS Hybrid ECC SHA256 2020 CA1
13:03:36.596914 http.c:756              == Info: ALPN, server accepted to use h2
13:03:36.596955 http.c:756              == Info: Using HTTP2, server supports multi-use
13:03:36.596960 http.c:756              == Info: Connection state changed (HTTP/2 confirmed)
13:03:36.596974 http.c:756              == Info: Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
13:03:36.596984 http.c:756              == Info: Failed sending HTTP2 data
13:03:36.596993 http.c:756              == Info: Connection #0 to host github.com left intact
13:03:36.597168 usage.c:64                        error impossibile accedere a 'https://github.com/git/git/': Failed sending HTTP2 data
fatal: impossibile accedere a 'https://github.com/git/git/': Failed sending HTTP2 data
13:03:36.597194 usage.c:68                        exit elapsed:0.338490 code:128
13:03:36.597203 trace2/tr2_tgt_normal.c:123       atexit elapsed:0.338501 code:128
13:03:36.598095 run-command.c:990                 child_exit[0] pid:179509 code:128 elapsed:0.343497
13:03:36.598114 git.c:745                         exit elapsed:0.343919 code:128
13:03:36.598155 trace2/tr2_tgt_normal.c:123       atexit elapsed:0.343959 code:128
13:03:36.598389 transport-helper.c:581            exit elapsed:0.346748 code:128
13:03:36.598639 trace2/tr2_tgt_normal.c:123       atexit elapsed:0.347003 code:128</pre>



<h2 class="wp-block-heading">解决方法</h2>



<p>既然是Debian官方源中的问题，那除了等官方解决以外，就只能降级这个库了。</p>



<p>降级到stable，也就是buster的命令如下。APT会自动降级有依赖关系的库，如libcurl4</p>



<p>2021-10-01 Update：Debian 11发布后Buster不再是Stable，因此在Debian 10遇到此问题需要降级到buster或者oldstable，推荐升级至Debian 11解决此问题。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Downgrade command
sudo apt reinstall libcurl3-gnutls/buster
</pre>



<p></p>The post <a href="https://blog.eastonman.com/blog/2021/04/git-failed-sending-http2-data/">Git: Failed sending HTTP2 data解决办法</a> first appeared on <a href="https://blog.eastonman.com">Easton Man's Blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.eastonman.com/blog/2021/04/git-failed-sending-http2-data/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Linux内核页面置换算法</title>
		<link>https://blog.eastonman.com/blog/2021/04/linux-multi-lru/</link>
					<comments>https://blog.eastonman.com/blog/2021/04/linux-multi-lru/#respond</comments>
		
		<dc:creator><![CDATA[Easton Man]]></dc:creator>
		<pubDate>Sat, 03 Apr 2021 12:23:02 +0000</pubDate>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[Kernel]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Linux内核]]></category>
		<guid isPermaLink="false">https://blog.eastonman.com/?p=523</guid>

					<description><![CDATA[<p>预计阅读时间： 9 分钟 最近来自Google的Yu Zhao向Linux内核提交了一个Patch，修改了内核 [&#8230;]</p>
The post <a href="https://blog.eastonman.com/blog/2021/04/linux-multi-lru/">Linux内核页面置换算法</a> first appeared on <a href="https://blog.eastonman.com">Easton Man's Blog</a>.]]></description>
										<content:encoded><![CDATA[<p class="wpwc-reading-time">预计阅读时间： 9 分钟</p>
<p>最近来自Google的Yu Zhao向Linux内核提交了一个Patch，修改了内核内存管理模块中的页面置换算法，提出了多级LRU，本文带你了解页面置换算法和多级LRU的优势。</p>



<h2 class="wp-block-heading">什么是页和页面置换</h2>



<p>我们知道，在几乎所有的现代操作系统和处理器上都使用了<strong>内存分页机制</strong>。某些嵌入式操作系统和特殊情况下，处理器资源很紧张，不需要考虑进程间安全问题，甚至没有线程这一概念时，内存分页也就没有必要了。内存分页是为了<strong>虚拟内存机制</strong>而提出的，大多数现代操作系统上为了进程间的隔离，每个进程拥有自己独立的地址空间，这就是虚拟内存。虚拟内存需要与物理内存有一个映射，但是问题来了，这个映射表是需要占用内存空间的，尤其是64位处理器上，需要映射的地址空间非常庞大，如果对地址做一一映射，映射表将会比物理内存还要大。这时就需要对内存进行<strong>分页映射</strong>，即将内存分为一定大小，如4KB大小的页，这些页面与物理内存中的4KB大小的页面一一对应，这就是内存分页机制。但是页表仍然很大，现代体系结构中一般使用<strong>多级页表</strong>来大幅减少页表所占用的空间，例如Linux中的四级页表：</p>



<figure class="wp-block-image aligncenter size-large"><img decoding="async" width="701" height="351" src="https://blog.eastonman.com/wp-content/uploads/2021/04/e043a1db694a5145a434eecd98fe1d0b1603800172716.png" alt="" class="wp-image-526" srcset="https://blog.eastonman.com/wp-content/uploads/2021/04/e043a1db694a5145a434eecd98fe1d0b1603800172716.png 701w, https://blog.eastonman.com/wp-content/uploads/2021/04/e043a1db694a5145a434eecd98fe1d0b1603800172716-300x150.png 300w" sizes="(max-width: 701px) 100vw, 701px" /><figcaption class="wp-element-caption">Linux四级页表</figcaption></figure>



<p>其中PGD、PUD等分别是一、二、三、四级页表项，Offset是页内部的地址。Linux在最新的Intel Xeon处理器上甚至使用了五级页表，具体处理器支持就不赘述了。值得注意的是，<strong>页表需要硬件支持，也就是CPU的内存管理单元（MMU）的支持</strong>。以下是一个Intel Xeon Gold 6230的MMU支持，可以看到40 bits physical，也就值它的MMU支持40位的硬件寻址，48 bits physical也就是目前Linux四级页表所支持的虚拟地址空间大小。</p>



<figure class="wp-block-image aligncenter size-large"><img decoding="async" width="687" height="161" src="https://blog.eastonman.com/wp-content/uploads/2021/04/image.png" alt="" class="wp-image-527" srcset="https://blog.eastonman.com/wp-content/uploads/2021/04/image.png 687w, https://blog.eastonman.com/wp-content/uploads/2021/04/image-300x70.png 300w" sizes="(max-width: 687px) 100vw, 687px" /></figure>



<p>那页面置换又是什么？</p>



<p>页面置换也来自一个几乎所有的现代操作系统都拥有的功能——<strong>交换机制。</strong>当物理内存接近满的时候，操作系统为了使整个系统仍然可用，会将一部分不常使用的页面移到磁盘上，为更经常使用的页面腾出空间。当然，这样的做的代价是会降低性能，这个机制也不是万能的，当活跃使用的内存也借近物理内存大小的时候，系统依然会变得几乎不可用，不过至少这样的机制使得系统有机会自己恢复，而不是不得不由OOM Killer杀死一些进程。这个交换机制显然需要一个优秀的算法来判断哪一部分页面是“陈旧的”，这就引出了这篇文章的主题——<strong>页面置换算法。</strong></p>



<h2 class="wp-block-heading">页面置换算法</h2>



<p>操作系统发展了50年，页面置换算法也在不断地改进，我们先来盘点一下曾经出现过的页面置换算法有哪一些。</p>



<ul class="wp-block-list">
<li><strong><s>最优算法</s>：</strong>想得真美，甚至关于“最优”定义也取决于实际场景。</li>



<li><strong>NRU（最近未使用）算法：</strong>一个简易的算法，维护一个链表，每次淘汰末端的页，每次读取时将页面移至表头。是可以接受的算法，实现简易，性能损耗小。</li>



<li><strong>FIFO：</strong>维护一个队列，每次直接清理队列头的页面。几乎无性能开销，但是效果不好。</li>



<li><strong>Second Chance FIFO：</strong>维护一个循环队列，每次清理访问标志位为0的页面，每次访问后将标志位置为1，这样只要周期内页面有访问，就会免遭清理，除非所有的页都为1。由于使用循环队列，内存操作较多，故一般使用下面一个算法。</li>



<li><strong>时钟算法：</strong>指针和环形链表/队列实现SCFIFO，消除了内存操作，也是较为常用的算法，效果较好，比较NRU有较大改善。</li>



<li><strong>LRU（最近最少使用）算法：</strong>对于最优算法在大多数情况下很好的近似，效果优异，但是较难实现，目前的算法要不就是时间复杂度较高，要不就是空间复杂度较高。大多数时候还需要硬件支持。</li>



<li><strong>NFU算法：</strong>由软件模拟的LRU，使用的频度Freq由系统时钟中断处理程序统计，效果较好，但是有一定的性能开销，且没有实现“最近”。</li>



<li><strong>老化算法：</strong>在NFU基础上加入频度老化，实现了“最近”，越久的使用次数权重越低。</li>
</ul>



<p>Linux内核现在使用的页面置换算法是<strong>两级的软件LRU</strong>，也就是分为active和inactive类型的两个链表，并实现软件LRU（NFU）算法，由于基于硬件的LRU在当今的体系结构中无法实现，下文中我们把这一种算法简称为LRU。</p>



<h2 class="wp-block-heading">两级LRU的问题</h2>



<h3 class="wp-block-heading">TL;DR</h3>



<p>现行的算法CPU开销太大，而且经常做出错误的决策。</p>



<h3 class="wp-block-heading">粒度</h3>



<p>Active/Inactive这两种分类在现在的硬件环境下，实在是一个相当粗的粒度。要知道，Linux统治的服务器领域中，内存上T的并不少见，甚至是很常见。Intel近几年推广的傲腾内存更是对内存调度提出了更高的要求。这个活动/非活动的分类并不是一个好的分类方法，像文件存取这样的情境下，经常会有周期性的内存操作，而这时页面会在两个表中来回移动，并不能很好表现这个页面是否是活跃的。而许多正在执行的可执行文件的代码段常常被移除，仅仅是因为它们在相当短的一段时间内没有被使用。这导致了在安卓和ChromeOS上交互进程的反应延迟。</p>



<h3 class="wp-block-heading">倒排页表扫描的性能问题</h3>



<p>由于LRU算法需要周期性地根据倒排页表（rmap）以更新页面的访问计数器，但是，rmap拥有相当复杂的数据结构，局部性很差，导致在扫描rmap的时候CPU缓存命中率很不理想。现代CPU的缓存命中率对执行速度由极大的影响，缓存命中率低下可以使CPU的执行速度下降到峰值的10%甚至更低。</p>



<h2 class="wp-block-heading">多级LRU</h2>



<p>Yu Zhao最近提交的Patch中提出了Multigenerational LRU算法，旨在解决现在内核使用的两级LRU的问题。这个多级LRU借鉴了老化算法的思路，按照<strong>页面的生成（分配）时间将LRU表分为若干Generation</strong>。在LRU页面扫面的时候，使用增量的方式扫描，根据周期内访问过的页面对<strong>页表</strong>进行扫描，除非这段时间内访问的内存分布非常稀疏，通常<strong>页表相对于倒排页表有更好的局部性</strong>，进而可以提升CPU的缓存命中率。</p>



<p>在邮件列表中Yu Zhao说明了他使用更改后的算法在几个模拟场景中的情况：</p>



<ul class="wp-block-list">
<li>Android：减少了18%的low memory kill，进而减少了16%的冷启动。</li>



<li>Borg（Google的云资源编排系统）：活跃内存占用降低了。</li>



<li>ChromeOS：非活跃页面减少了96%的内存占用，减少了59%的OOM Kill。</li>
</ul>



<h2 class="wp-block-heading">结语</h2>



<p>Linux内核页面置换算法的修改影响非常巨大，哪怕只是“微小”的调整。因为Linux的使用场景并不仅限于常用的几种情况，因此这个Patch需要经过相当长的一段讨论和各个开发者的测试才可能最终被合并进入主线。虽然大部分的内核开发者还没有发表对此的意见，但已有部分人对这个新算法持有积极的态度和较好的评价，所以我也认为这个Patch将会最终进入Linux内核主线。</p>



<p>[2023-01-07] Update: MLRU 已在 Linux 6.2 合并进入主线内核</p>



<h2 class="wp-block-heading">深入阅读</h2>



<ul class="wp-block-list">
<li><a href="https://lwn.net/SubscriberLink/851184/01351eb745a6405d/" title="https://lwn.net/SubscriberLink/851184/01351eb745a6405d/" target="_blank" rel="noreferrer noopener">The multi-generational LRU</a></li>



<li><a href="https://lwn.net/ml/linux-kernel/20210313075747.3781593-1-yuzhao@google.com/" target="_blank" rel="noreferrer noopener" title="https://lwn.net/ml/linux-kernel/20210313075747.3781593-1-yuzhao@google.com/">[PATCH v1 00/14] Multigenerational LRU</a></li>



<li>Long-term SLOs for reclaimed cloud computing resources    <a href="https://research.google/pubs/pub43017/" target="_blank" rel="noreferrer noopener">https://research.google/pubs/pub43017/</a> </li>



<li>Profiling a warehouse-scale computer    <a href="https://research.google/pubs/pub44271/" target="_blank" rel="noreferrer noopener">https://research.google/pubs/pub44271/</a> </li>



<li>Evaluation of NUMA-Aware Scheduling in Warehouse-Scale Clusters    <a href="https://research.google/pubs/pub48329/" target="_blank" rel="noreferrer noopener">https://research.google/pubs/pub48329/</a> </li>



<li>Software-defined far memory in warehouse-scale computers    <a href="https://research.google/pubs/pub48551/" target="_blank" rel="noreferrer noopener">https://research.google/pubs/pub48551/</a> </li>



<li>Borg: the Next Generation    <a href="https://research.google/pubs/pub49065/" target="_blank" rel="noreferrer noopener">https://research.google/pubs/pub49065/</a></li>
</ul>



<p></p>The post <a href="https://blog.eastonman.com/blog/2021/04/linux-multi-lru/">Linux内核页面置换算法</a> first appeared on <a href="https://blog.eastonman.com">Easton Man's Blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.eastonman.com/blog/2021/04/linux-multi-lru/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Linux内核CFS调度器的实现</title>
		<link>https://blog.eastonman.com/blog/2021/02/cfs/</link>
					<comments>https://blog.eastonman.com/blog/2021/02/cfs/#respond</comments>
		
		<dc:creator><![CDATA[Easton Man]]></dc:creator>
		<pubDate>Fri, 26 Feb 2021 14:24:47 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[CFS]]></category>
		<category><![CDATA[Kernel]]></category>
		<category><![CDATA[Scheduler]]></category>
		<guid isPermaLink="false">https://blog.eastonman.com/?p=477</guid>

					<description><![CDATA[<p>预计阅读时间： 5 分钟 本文简易而快速地介绍了Linux内核中完全公平类调度类CFS调度器的原理和实现。 原 [&#8230;]</p>
The post <a href="https://blog.eastonman.com/blog/2021/02/cfs/">Linux内核CFS调度器的实现</a> first appeared on <a href="https://blog.eastonman.com">Easton Man's Blog</a>.]]></description>
										<content:encoded><![CDATA[<p class="wpwc-reading-time">预计阅读时间： 5 分钟</p>
<p>本文简易而快速地介绍了Linux内核中完全公平类调度类CFS调度器的原理和实现。</p>



<h2 class="wp-block-heading">原理</h2>



<p>其实CFS（Completely Fair Scheduler）的核心原理很简单，就是使得每个进程都尽可能“公平”地获得运行时间。因此每次都选择过去运行得最少得进程运行。当然，作为一个调度器，它要满足的需求远不止于此。Linux的抢占式进程和在完全公平类<code>fair_sched_class</code>中支持优先级等一系列特性，使得CFS的设计变得比简单的选出运行时间最少要复杂得多。但是不要着急，我们一步一步来理解CFS的原理。</p>



<h2 class="wp-block-heading">最小运行时间</h2>



<p>为了避免过度频繁的抢占发生，Linux内核设置了每个Task（进程）的最小运行时间（或称运行时间粒度），在这个时间内，这个进程的CPU资源是不可被抢占的。除非进程主动让出CPU或者执行了阻塞的系统调用，一般而言进程都可以执行最少执行完这个时间。最小运行时间可以通过内核参数<code>sched_min_granularity_ns</code>来查看。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cat /proc/sys/kernel/sched_min_granularity_ns
3000000</pre>



<h2 class="wp-block-heading">时间片</h2>



<p>CFS通过引入权重来保证高优先级的进程能够获得更多的CPU时间，进程间按照权重比例分配时间片。调度周期内分配给进程的运行时间按照这个公式计算：</p>



<p class="has-text-align-center"><strong>运行时间tn=调度周期T * 进程权重w / 运行队列中全部进程的权重之和S</strong></p>



<p>权重是一个和nice值有关的量，现在在Linux内核中的定义位于<a href="https://github.com/torvalds/linux/blob/2c87f7a38f930ef6f6a7bdd04aeb82ce3971b54b/kernel/sched/core.c#L9516" target="_blank" rel="noreferrer noopener" title="https://github.com/torvalds/linux/blob/2c87f7a38f930ef6f6a7bdd04aeb82ce3971b54b/kernel/sched/core.c#L9516">kernel/sched/core.c#L9516</a>（文章发布时），数值如下：</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const int sched_prio_to_weight[40] = {
 /* -20 */     88761,     71755,     56483,     46273,     36291,
 /* -15 */     29154,     23254,     18705,     14949,     11916,
 /* -10 */      9548,      7620,      6100,      4904,      3906,
 /*  -5 */      3121,      2501,      1991,      1586,      1277,
 /*   0 */      1024,       820,       655,       526,       423,
 /*   5 */       335,       272,       215,       172,       137,
 /*  10 */       110,        87,        70,        56,        45,
 /*  15 */        36,        29,        23,        18,        15,
};</pre>



<p>其中nice值为0的权重NICE_0_LOAD=1024，nice值每差1，权重大约差1.25倍。这里的1.25计算依据来源于nice值差1，运行时间相差10%这样的设计。</p>



<h2 class="wp-block-heading">虚拟运行时间</h2>



<p>解决完每次分配多少时间的问题后，还有一个问题需要解决，就是下一个运行的进程是谁？CFS实现的原则是“完全的公平”，那么高优先级的进程如何保证多一点的运行时间？这就要引入一个概念，叫“虚拟运行时间”了。假设我们希望有如下的情况出现：</p>



<p class="has-text-align-center"><strong>高优先级进程运行15ms=低优先级运行5ms</strong></p>



<p>那么我们就将这个相等的量设置为一个“虚拟运行时间”，这样就可以保证高优先级进程运行的时间几乎总是低优先级的3倍。在Linux中，这个虚拟运行时间与实际运行时间的关系就是刚刚提到的权重：</p>



<p class="has-text-align-center"><strong>虚拟运行时间=真实运行时间 * NICE_0_LOAD / 进程的权重</strong></p>



<p>Linux在调度元素中定义了vruntime变量（<a href="https://github.com/torvalds/linux/blob/66f73fb3facd42d0a7c899d7f4c712332b28499a/include/linux/sched.h#L453" target="_blank" rel="noreferrer noopener" title="https://github.com/torvalds/linux/blob/66f73fb3facd42d0a7c899d7f4c712332b28499a/include/linux/sched.h#L453">include/linux/sched.h#L453</a>），用于记录进程的累计虚拟运行时间，代码如下：</p>



<pre class="EnlighterJSRAW" data-enlighter-language="c" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">struct sched_entity {
	/* For load-balancing: */
	struct load_weight		load;
	struct rb_node			run_node;
	struct list_head		group_node;
	unsigned int			on_rq;

	u64				exec_start;
	u64				sum_exec_runtime;
	u64				vruntime;
	u64				prev_sum_exec_runtime;

	u64				nr_migrations;

	struct sched_statistics		statistics;
        ...
}</pre>



<p>进程每次运行完毕后就会更新vruntime变量，至于如何挑选出vruntime最少的进程，这将由红黑树完成。</p>



<h2 class="wp-block-heading">红黑树</h2>



<p>红黑树是一种自平衡的二叉树，最左的叶子节点永远是key最小的节点。红黑树通过插入（更新）和删除时的操作保证这些原子操作之间红黑树永远是平衡的。</p>



<p>具体的操作参见<a href="https://www.jianshu.com/p/e136ec79235c" title="https://www.jianshu.com/p/e136ec79235c">https://www.jianshu.com/p/e136ec79235c</a></p>



<p>内核将调度队列上的进程按照vruntime排列成红黑树，这样选取最小vruntime的进程就变为了简单地选出最左边的叶子节点了。</p>



<h2 class="wp-block-heading">最小vruntime</h2>



<p>内核除了红黑树以外还维护一个min_vruntime变量，以记录此时最小的虚拟运行时间。</p>



<p>为什么需要这个min_vruntime？我们设想以下几种状况：</p>



<ul class="wp-block-list"><li>新的进程加入了红黑树，那么它的vruntime应当是多少？</li><li>休眠了10万年的进程等待到了它要求的事件，现在被唤醒了，它还保持原有的vruntime吗？</li><li>进程被负载均衡迁移到另一个CPU上（另一个调度队列），那么它的vruntime如何改变？</li></ul>



<p>由此可以看出，min_vruntime的作用就是帮助Linux内核解决这些情况。</p>



<h2 class="wp-block-heading">深入阅读</h2>



<ul class="wp-block-list"><li><a href="https://github.com/torvalds/linux/tree/master/kernel/sched" target="_blank" rel="noreferrer noopener" title="https://github.com/torvalds/linux/tree/master/kernel/sched">https://github.com/torvalds/linux/tree/master/kernel/sched</a></li><li><a href="https://www.kernel.org/doc/html/latest/scheduler/sched-design-CFS.html" target="_blank" rel="noreferrer noopener" title="https://www.kernel.org/doc/html/latest/scheduler/sched-design-CFS.html">https://www.kernel.org/doc/html/latest/scheduler/sched-design-CFS.html</a></li><li>有意思的BFS<a href="https://www.utappia.org/2012/02/bfs-vs-cfs-some-personal-observations.html" target="_blank" rel="noreferrer noopener" title="https://www.utappia.org/2012/02/bfs-vs-cfs-some-personal-observations.html">https://www.utappia.org/2012/02/bfs-vs-cfs-some-personal-observations.html</a></li></ul>



<p></p>The post <a href="https://blog.eastonman.com/blog/2021/02/cfs/">Linux内核CFS调度器的实现</a> first appeared on <a href="https://blog.eastonman.com">Easton Man's Blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.eastonman.com/blog/2021/02/cfs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
