<?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>Soul Of Free Loop &#187; kernel</title>
	<atom:link href="https://zohead.com/archives/category/technology/linux/kernel/feed/" rel="self" type="application/rss+xml" />
	<link>https://zohead.com</link>
	<description>Uranus Zhou&#039;s Blog</description>
	<lastBuildDate>Sat, 19 Jul 2025 15:42:46 +0000</lastBuildDate>
	<language>zh-CN</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.8</generator>
	<item>
		<title>Linux下USB 3.0移动硬盘读写错误问题分析</title>
		<link>https://zohead.com/archives/linux-usbhdd-err/</link>
		<comments>https://zohead.com/archives/linux-usbhdd-err/#comments</comments>
		<pubDate>Tue, 08 Mar 2016 19:09:23 +0000</pubDate>
		<dc:creator><![CDATA[Uranus Zhou]]></dc:creator>
				<category><![CDATA[kernel]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[barrier]]></category>
		<category><![CDATA[Chromebook]]></category>
		<category><![CDATA[ext4]]></category>
		<category><![CDATA[FUA]]></category>
		<category><![CDATA[JMicron]]></category>
		<category><![CDATA[journal]]></category>
		<category><![CDATA[SCSI]]></category>
		<category><![CDATA[USB]]></category>
		<category><![CDATA[移动硬盘]]></category>

		<guid isPermaLink="false">https://zohead.com/?p=1188</guid>
		<description><![CDATA[为了解决 Chromebook 上自带 SSD 空间不足的问题，之前我在淘宝上购入了一个绿帆 F200 USB 3.0 移动硬盘盒，该硬盘盒使用的是 JMicron JMS567 这款使用还比较广泛的 SATA 6.0Gbps to USB 3.0 桥接芯片，准备配上 N 年前的神船笔记本淘汰下来的 2.5 寸硬盘给 Chromebook 使用，这样我就可以在 Chromebook 上安装的 Crouton Ubuntu 系统里无碍的使用各种编译开发环境了。 移动硬盘问题说明 首先我在宏碁 W700 Windows 10 平板上接上此移动硬盘建了一个 NTFS 分区并做各种读写拷贝大文件之类的 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>为了解决 Chromebook 上自带 SSD 空间不足的问题，之前我在淘宝上购入了一个绿帆 F200 USB 3.0 移动硬盘盒，该硬盘盒使用的是 JMicron JMS567 这款使用还比较广泛的 SATA 6.0Gbps to USB 3.0 桥接芯片，准备配上 N 年前的神船笔记本淘汰下来的 2.5 寸硬盘给 Chromebook 使用，这样我就可以在 Chromebook 上安装的 Crouton Ubuntu 系统里无碍的使用各种编译开发环境了。</p>
<h2 id="移动硬盘问题说明">移动硬盘问题说明</h2>
<p>首先我在宏碁 W700 Windows 10 平板上接上此移动硬盘建了一个 NTFS 分区并做各种读写拷贝大文件之类的测试没有任何问题；但是我把移动硬盘换到 Chromebook 上之后发现移动硬盘上新建的 ext4 分区读写会报错，无法做任何拷贝文件操作，先看看 Linux kernel 看到的 USB 3.0 移动硬盘的信息：</p>
<pre class="brush: bash; title: ; notranslate">
[ 9934.612465] usb 2-1: new SuperSpeed USB device number 2 using xhci_hcd
[ 9934.624741] usb 2-1: New USB device found, idVendor=152d, idProduct=0567
[ 9934.624768] usb 2-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 9934.624787] usb 2-1: Product: lvfan USB3.0 storage
[ 9934.624802] usb 2-1: Manufacturer: JMicron
[ 9934.624817] usb 2-1: SerialNumber: 3224043AA81395
[ 9934.626473] scsi2 : usb-storage 2-1:1.0
[ 9935.627536] scsi 2:0:0:0: Direct-Access     lvfan                     0117 PQ: 0 ANSI: 6
[ 9935.629174] sd 2:0:0:0: [sdb] Spinning up disk...
[ 9936.629940] ...ready
[ 9938.634171] sd 2:0:0:0: [sdb] 312581808 512-byte logical blocks: (160 GB/149 GiB)
[ 9938.634552] sd 2:0:0:0: [sdb] Write Protect is off
[ 9938.634580] sd 2:0:0:0: [sdb] Mode Sense: 47 00 10 08
[ 9938.634955] sd 2:0:0:0: [sdb] Write cache: enabled, read cache: enabled, supports DPO and FUA
[ 9938.659685]  sdb: sdb1 sdb2
[ 9938.661548] sd 2:0:0:0: [sdb] Attached SCSI disk
</pre>
<p>这个是拷贝文件出错时候的内核日志：</p>
<pre class="brush: bash; title: ; notranslate">
[ 9910.412002] EXT4-fs (sdb2): mounted filesystem with ordered data mode. Opts: (null)
[ 9918.500515] sd 2:0:0:0: [sdb] Invalid command failure
[ 9918.500530] sd 2:0:0:0: [sdb]  
[ 9918.500537] Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
[ 9918.500547] sd 2:0:0:0: [sdb]  
[ 9918.500554] Sense Key : Illegal Request [current] 
[ 9918.500570] sd 2:0:0:0: [sdb]  
[ 9918.500577] Add. Sense: Invalid field in cdb
[ 9918.500589] sd 2:0:0:0: [sdb] CDB: 
[ 9918.500596] Write(10): 2a 08 04 58 18 30 00 00 08 00
[ 9918.500641] end_request: critical target error, dev sdb, sector 72882224
[ 9918.500654] end_request: critical target error, dev sdb, sector 72882224
[ 9918.500695] Aborting journal on device sdb2-8.
[ 9922.109415] EXT4-fs error (device sdb2): ext4_journal_start_sb:349: Detected aborted journal
[ 9922.109439] EXT4-fs (sdb2): Remounting filesystem read-only
</pre>
<p>看起来是报某个扇区写操作出错，那么我先在 Chromebook 上用 dd 命令直接写对应报错的扇区：</p>
<pre class="brush: bash; title: ; notranslate">
chronos@localhost ~ $ sudo dd if=/dev/zero of=/dev/sdb bs=512 count=10 seek=72882224
10+0 records in
10+0 records out
5120 bytes (5.1 kB) copied, 0.0185829 s, 276 kB/s
</pre>
<p>可以看到写之前报错的扇区其实是没有问题的，而且我使用的 SATA 笔记本硬盘之前经过 mhdd 扫描测试没有发现坏道之类的。</p>
<p>无奈我删掉这个 ext4 分区，重新创建了 ext3 分区并格式化拷贝文件但还是存在类似的错误，最后更换为 ext2 或者 FAT32 文件系统才能正常写入文件，这个就非常奇怪了，接着我把移动硬盘换到 Remix OS PC 版 4.0.9 kernel 下挂载 ext4 读写还是有一样的问题，这样我们就必须要具体分析上面的报错信息了。</p>
<h2 id="读写错误问题分析">读写错误问题分析</h2>
<p>从上面的 kernel 日志中可以看到报错的 SCSI CDB 是：<code>2a 08 04 58 18 30 00 00 08 00</code>，而 0x2A 是 SCSI WRITE 10 命令，参考 SCSI 协议可以知道其命令格式为：</p>
<p><img src="http://res.cloudinary.com/digwht2y0/image/upload/v1737442940/scsi-rw-cmd.jpg" alt="SCSI WRITE 10命令" title="SCSI WRITE 10命令"></p>
<p>我们可以从上图知道 <code>04 58 18 30</code> 是写操作的实际扇区地址（也就是上面报错的 72882224 扇区），<code>08</code> 是写命令的标志位表示这个写命令启用了 <code>FUA</code>。</p>
<p>这里我对 <code>FUA</code>（Force Unit Access）做个简单的介绍：</p>
<ul>
<li>
<p>由于在 Linux 操作系统中从上层到下层多个地方都存在着缓存：page cache（vfs cache）-&gt; HBA/RAID卡自带的 cache -&gt; 磁盘自身的缓存，这样文件系统在写日志等关键的操作时就需要保证写入的数据被真实写到磁盘等物理介质中，而不是存留在各层 cache 里，这样可以防止系统掉电等情况导致数据不一致。</p>
</li>
<li>
<p>Linux kernel 中比较新的文件系统像 ext4、xfs、reiserfs 等则引入了 barrier 特性，遇到带 barrier 标志的写请求（或者 fsync 刷新请求）的时候必须保证之前的所有请求都已经写入到物理介质才能继续。老的 SCSI 或 SAS 磁盘支持通过 <code>SYNCHRONIZE CACHE</code> 命令刷新缓存数据，只不过这样会有额外的影响；新的 kernel 中对于支持 <code>FUA</code> 的设备则是通过发送带 <code>FUA</code> 标志的写请求来实现。</p>
</li>
<li>
<p>SCSI CDB 中的 <code>FUA</code> 标志位如果被置上则表示该请求必须通过访问物理介质实现，如果是带 <code>FUA</code> 的写命令就表示写到物理介质命令才算完成，带 <code>FUA</code> 的读命令则表示直接从物理介质读取绕过缓存。</p>
</li>
</ul>
<p>这样分析下来基本就可以推断出原因了：</p>
<p>由于 ext4、ext3 等文件系统在 kernel 中是默认启用和日志（journal）和 barrier 的，拷贝文件时需要更新文件系统日志，从最上面 kernel 报上来的移动硬盘信息显示是支持 <code>FUA</code> 的，如此日志的写入就是通过发送带 <code>FUA</code> 的写命令实现，然而我的 USB 3.0 移动硬盘响应带 <code>FUA</code> 标志的写命令出现问题导致 ext4、ext3 文件系统变为只读状态无法写入；而 ext2 和 FAT32 文件系统则是完全不带日志的，这样拷贝文件反而就没有问题。</p>
<blockquote>
<p><strong>提示</strong></p>
<p>有关我的移动硬盘使用的 JMicron JMS567 桥接芯片的详细信息请参考 <a href="http://www.jmicron.com/PDF/brief/jms567.pdf">JMicron 技术文档</a>。</p>
</blockquote>
<h2 id="解决方案">解决方案</h2>
<p>如果要顺利使用 ext4 分区，解决方案也有几种，一般的用户建议参考第二种解决方案，下面简单说明下：</p>
<h3 id="禁用-ext4-文件系统日志">禁用 ext4 文件系统日志</h3>
<p>这是比较简单粗暴的解决方案，ext4 文件系统相对 ext3 其中一个改进就是可以手工关闭日志，先卸载已挂载的 ext4 文件系统，然后运行下面的命令：</p>
<pre class="brush: bash; title: ; notranslate">
sudo tune2fs -O ^has_journal /dev/sdb2
</pre>
<p>这样就可以直接关闭 ext4 文件系统默认启用的日志功能，日志被禁用之后基本就类似 ext2 不需要专门发送带 <code>FUA</code> 的写请求了；当然这里我不建议这样做，因为日志功能对于移动硬盘这种热插拔频繁的设备还是相当有用的，可以减少文件出错或丢失的可能。</p>
<h3 id="关闭-ext4-文件系统-barrier">关闭 ext4 文件系统 barrier</h3>
<p>对于不愿意修改或者编译 Linux kernel 的用户这是比较好的解决方案咯，只是关闭 ext4 文件系统 barrier 特性可以保留最有用的日志功能，虽然相比默认启用 barrier 的情况仍然会有一点导致数据不一致的可能，但好处是修改之后就算把移动硬盘接到其它 Linux 机器上基本也能起作用，这样就比较划算了，具体运行下面的命令：</p>
<pre class="brush: bash; title: ; notranslate">
sudo tune2fs -o nobarrier /dev/sdb2
</pre>
<p>然后重新挂载 ext4 分区，一般的 Linux 系统都会在挂载该文件系统时自动禁用 barrier，Chromebook 上自带文件管理器的自动挂载磁盘功能实测有效。</p>
<h3 id="修改-kernel-禁用移动硬盘-fua">修改 kernel 禁用移动硬盘 FUA</h3>
<p>这种解决方案比较适合对编译 kernel 比较熟悉而且相对追求完美（^_^）的用户，不过相对的是需要依赖使用的 Linux 主机 kernel。</p>
<p>由于只禁用 ext4 文件系统的 barrier 还不能完全保证不会有什么别的地方需要用到带 <code>FUA</code> 的读写命令，如果能够修改 kernel 直接让我的这款移动硬盘设备报到系统中时就显示为不支持 <code>FUA</code>，这样就算遇到例如使用 barrier 等场合也可以通过 <code>SYNCHRONIZE CACHE</code> 命令来解决。</p>
<p>Linux kernel USB mass storage 驱动中内置了一个 unusual USB 设备列表，里面包含各种用户已经发现的有问题的 USB 设备及对应处理标志，该列表由 kernel 源代码中的 <code>drivers/usb/storage/unusual_devs.h</code> 文件负责维护。</p>
<p>我们可以先检查下 Chromebook 当前使用的 3.8.11 版本内核和 Remix OS PC 版使用的 4.0.9 版本内核源代码，却都能看到已经有用户报告的我的移动硬盘使用的 JMicron JMS567 芯片的 <code>FUA</code> 问题了：</p>
<pre class="brush: cpp; title: drivers/usb/storage/unusual_devs.h; notranslate">
UNUSUAL_DEV(  0x152d, 0x0567, 0x0114, 0x0114,
		&quot;JMicron&quot;,
		&quot;USB to ATA/ATAPI Bridge&quot;,
		USB_SC_DEVICE, USB_PR_DEVICE, NULL,
		US_FL_BROKEN_FUA ),
</pre>
<p>这个稍微有点奇怪，kernel 碰到带 <code>US_FL_BROKEN_FUA</code> 标志的 USB 设备会自动禁用 <code>FUA</code>，按说报上来的移动硬盘设备应该显示为不支持 <code>FUA</code> 的；不过稍微看下就发现上面的 <code>UNUSUAL_DEV</code> 条目限制了有问题的 USB 设备的 BCD 码固定为 <code>0x0114</code>，我们可以通过 <code>lsusb -v</code> 命令确认下移动硬盘设备的详细 USB 信息：</p>
<pre class="brush: bash; title: ; notranslate">
Bus 002 Device 004: ID 152d:0567 JMicron Technology Corp. / JMicron USA Technology Corp. 
Couldn't open device, some information will be missing
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               3.00
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0 
  bDeviceProtocol         0 
  bMaxPacketSize0         9
  idVendor           0x152d JMicron Technology Corp. / JMicron USA Technology Corp.
  idProduct          0x0567 
  bcdDevice            1.17
</pre>
<p>可以看到移动硬盘的 USB 设备 BCD 码是 1.17 也就是 <code>0x0117</code>，这样 kernel 就不会认为我这款绿帆移动硬盘是有问题的 USB 设备进而做特殊处理了。</p>
<p>同样我们可以看看最新的 Linux 4.5-rc7 版本 kernel 中异常 USB 设备列表中的 JMS567 条目：</p>
<pre class="brush: cpp; title: drivers/usb/storage/unusual_devs.h; notranslate">
UNUSUAL_DEV(  0x152d, 0x0567, 0x0114, 0x0116,
		&quot;JMicron&quot;,
		&quot;USB to ATA/ATAPI Bridge&quot;,
		USB_SC_DEVICE, USB_PR_DEVICE, NULL,
		US_FL_BROKEN_FUA ),
</pre>
<p>稍微有点无奈最新的 Linux kernel 中的 BCD 码范围是从 0x0114 到 0x0116，还是不包含我这款移动硬盘。</p>
<p>解决步骤也就比较简单了，检出对应的内核源代码，修改 <code>drivers/usb/storage/unusual_devs.h</code> 文件可以把 JMS567 USB 设备的 BCD 码范围改为 0x0114 到 0x0117，也可以彻底点直接改成 0x0000 到 0x9999。</p>
<p>unusual_devs.h 文件修改完成后替换 usb-storage 模块并重新启动，顺利的话就可以看到报上来的 SCSI 磁盘设备显示为：</p>
<pre class="brush: bash; title: ; notranslate">
[ 7205.597952] sd 2:0:0:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
</pre>
<blockquote>
<p><strong>提示</strong></p>
<p>由于 Chromebook 和 Remix OS 中的 usb-storage 驱动都是直接集成在 kernel 中的，无法只编译 usb-storage 模块进行简单替换，因此需要完整编译出 kernel bzImage 直接替换。</p>
</blockquote>
<p><br/>
<p>这样 ext4 文件系统的日志还有 barrier 特性就能愉快的继续使用了，祝各位玩的开心～～～。</p>
]]></content:encoded>
			<wfw:commentRss>https://zohead.com/archives/linux-usbhdd-err/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>修改Remix OS kernel支持Chromebook触控板</title>
		<link>https://zohead.com/archives/remixos-cb-trackpad/</link>
		<comments>https://zohead.com/archives/remixos-cb-trackpad/#comments</comments>
		<pubDate>Tue, 01 Mar 2016 18:16:13 +0000</pubDate>
		<dc:creator><![CDATA[Uranus Zhou]]></dc:creator>
				<category><![CDATA[Chrome]]></category>
		<category><![CDATA[kernel]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[Chromebook]]></category>
		<category><![CDATA[chromeos_laptop]]></category>
		<category><![CDATA[cyapa]]></category>
		<category><![CDATA[cyapatp]]></category>
		<category><![CDATA[I2C]]></category>
		<category><![CDATA[Remix OS]]></category>
		<category><![CDATA[触控板]]></category>

		<guid isPermaLink="false">https://zohead.com/?p=1183</guid>
		<description><![CDATA[继续接着上一篇文章「修改Remix OS适配Chromebook键盘」的修改之后在我的 Dell Chromebook 11 上使用 ext4 U 盘形式的 Remix OS PC 版已经是比较顺利了，那么剩下最大的问题就是触控板问题了，要知道之前我使用 Remix OS 的时候都是必须插着一个 USB 鼠标的。 Chromebook 的触控板由于比较特殊之前很多网友安装的 Ubuntu 系统里经常也用不了，这里我以 Dell Chromebook 11 为例子对 Remix OS PC 版内核模块做一些修改可以实现 Remix OS 下基本的触控功能，对于在 Chromebook 上单独安装 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>继续接着上一篇文章「<a href="https://zohead.com/archives/remixos-cb-keyboard/">修改Remix OS适配Chromebook键盘</a>」的修改之后在我的 Dell Chromebook 11 上使用 ext4 U 盘形式的 Remix OS PC 版已经是比较顺利了，那么剩下最大的问题就是触控板问题了，要知道之前我使用 Remix OS 的时候都是必须插着一个 USB 鼠标的。</p>
<p>Chromebook 的触控板由于比较特殊之前很多网友安装的 Ubuntu 系统里经常也用不了，这里我以 Dell Chromebook 11 为例子对 Remix OS PC 版内核模块做一些修改可以实现 Remix OS 下基本的触控功能，对于在 Chromebook 上单独安装的 Linux 系统下想使用触控板的用户也能做一个参考。</p>
<p>下面的篇幅有很大一部分是对 Remix OS 不能使用 Chromebook 触控板的原因分析，不想了解技术细节的话可以直接拖到最后「<em>修改 Remix OS 系统文件</em>」部分下载并使用我修改编译出来的适合 Remix OS 的内核模块哦。</p>
<blockquote>
<p>编写这篇文章时我使用的是 Remix OS PC 版 2016-02-01 alpha 版本，对应 Android x86 5.1.1 版本，Linux kernel 版本 4.0.9； <br />
  我使用的 Chrome OS 版本是 48.0.2564.116 正式版，Linux kernel 版本 3.8.11。</p>
</blockquote>
<h2 id="触控板问题分析">触控板问题分析</h2>
<p>首先确认能正常工作的 Chrome OS 下的 Chromebook 触控板相关信息，看看 Linux 输入设备中的触控板设备：</p>
<pre class="brush: bash; title: ; notranslate">
I: Bus=0018 Vendor=0000 Product=0000 Version=0001
N: Name=&quot;Cypress APA Trackpad (cyapa)&quot;
P: Phys=i2c-9-0067/input0
S: Sysfs=/devices/pci0000:00/0000:00:15.1/i2c-9/9-0067/input/input7
U: Uniq=
H: Handlers=event7 
B: PROP=5
B: EV=b
B: KEY=e520 10000 0 0 0 0
B: ABS=660800001000003
</pre>
<p>可以看到 Dell Chromebook 11 上的触控板其实用的是 Cypress 家的 APA I2C 输入设备，Chrome OS 上对应 i2c-9 适配器，I2C 地址是 67，对应的 I2C 输入设备驱动为 <code>cyapa</code>。</p>
<blockquote>
<p><strong>提示</strong></p>
<p>其它也有不少三星、HP 之类的 Chromebook 设备用的是 I2C 触控板，但不一定是同一厂商的，有的是使用 ELAN 等 I2C 触控板； <br />
  另外具体机器上 I2C 地址是固定的，i2c-9 适配器则是 Linux kernel 自动生成的并不固定。</p>
</blockquote>
<p>接下来看看 I2C 适配器实际对应的设备位置和名称：</p>
<pre class="brush: bash; title: ; notranslate">
chronos@localhost ~ $ cd /sys/class/i2c-adapter/
chronos@localhost /sys/class/i2c-adapter $ ls -dl *
lrwxrwxrwx 1 root root 0 Mar  1 22:38 i2c-0 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-0
lrwxrwxrwx 1 root root 0 Mar  1 22:38 i2c-1 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-1
lrwxrwxrwx 1 root root 0 Mar  1 22:38 i2c-10 -&gt; ../../devices/pci0000:00/0000:00:15.2/i2c-10
lrwxrwxrwx 1 root root 0 Mar  1 22:38 i2c-2 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-2
lrwxrwxrwx 1 root root 0 Mar  1 22:38 i2c-3 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-3
lrwxrwxrwx 1 root root 0 Mar  1 22:38 i2c-4 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-4
lrwxrwxrwx 1 root root 0 Mar  1 22:38 i2c-5 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-5
lrwxrwxrwx 1 root root 0 Mar  1 22:38 i2c-6 -&gt; ../../devices/pci0000:00/0000:00:02.0/drm/card0/card0-eDP-1/i2c-6
lrwxrwxrwx 1 root root 0 Mar  1 22:38 i2c-7 -&gt; ../../devices/pci0000:00/0000:00:02.0/drm/card0/card0-DP-1/i2c-7
lrwxrwxrwx 1 root root 0 Mar  1 22:38 i2c-8 -&gt; ../../devices/pci0000:00/0000:00:1f.3/i2c-8
lrwxrwxrwx 1 root root 0 Mar  1 22:38 i2c-9 -&gt; ../../devices/pci0000:00/0000:00:15.1/i2c-9
chronos@localhost /sys/class/i2c-adapter $ cat i2c-*/name
i915 gmbus ssc
i2c-designware-pci-1
i915 gmbus vga
i915 gmbus panel
i915 gmbus dpc
i915 gmbus dpb
i915 gmbus dpd
DPDDC-A
DPDDC-B
SMBus I801 adapter at 0400
i2c-designware-pci-0
</pre>
<p>可以看到触控板的 I2C 适配器 i2c-9 在 PCI 设备 0000:00:15.1 上，名称为：<code>i2c-designware-pci-0</code>，另外系统里还有 i2c-10 适配器在 0000:00:15.2 上，名称为：<code>i2c-designware-pci-1</code>，这两个适配器对应的 I2C 总线驱动是：<code>i2c-designware-pci</code>。</p>
<p>下面就可以在 Chromebook 上启动 Remix OS 确认其内核下 I2C 设备信息是否正确：</p>
<pre class="brush: bash; title: ; notranslate">
chronos@localhost ~ $ cd /sys/class/i2c-adapter/
root@remix_cn_x86_64:/sys/class/i2c-adapter # ls -dl *
lrwxrwxrwx root     root              2016-03-01 00:24 i2c-0 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-0
lrwxrwxrwx root     root              2016-03-01 00:24 i2c-1 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-1
lrwxrwxrwx root     root              2016-03-01 00:24 i2c-10 -&gt; ../../devices/pci0000:00/0000:00:1f.3/i2c-10
lrwxrwxrwx root     root              2016-03-01 00:24 i2c-2 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-2
lrwxrwxrwx root     root              2016-03-01 00:24 i2c-3 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-3
lrwxrwxrwx root     root              2016-03-01 00:24 i2c-4 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-4
lrwxrwxrwx root     root              2016-03-01 00:24 i2c-5 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-5
lrwxrwxrwx root     root              2016-03-01 00:24 i2c-6 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-6
lrwxrwxrwx root     root              2016-03-01 00:24 i2c-7 -&gt; ../../devices/pci0000:00/0000:00:02.0/i2c-7
lrwxrwxrwx root     root              2016-03-01 00:24 i2c-8 -&gt; ../../devices/pci0000:00/0000:00:15.1/i2c-8
lrwxrwxrwx root     root              2016-03-01 00:24 i2c-9 -&gt; ../../devices/pci0000:00/0000:00:15.2/i2c-9
root@remix_cn_x86_64:/sys/class/i2c-adapter # cat i2c-*/name
i915 gmbus ssc
i915 gmbus vga
SMBus I801 adapter at 0400
i915 gmbus panel
i915 gmbus dpc
i915 gmbus dpb
i915 gmbus dpd
DPDDC-A
DPDDC-B
i2c-designware-pci
i2c-designware-pci
</pre>
<p>这样可以发现 Remix OS 内核下两个 I2C 适配器为 i2c-8 和 i2c-9，虽然 i2c-8 是触控板设备但是使用起来应该是没有影响的，I2C 总线驱动也是正确的，但适配器名称都是一样的 <code>i2c-designware-pci</code>。</p>
<p>同时进一步确认之后发现 Remix OS 内核下虽然没有 Chrome OS 里直接使用的 <code>cyapa</code> 驱动，但其默认集成了新的 Linux kernel 里自带的 <code>cyapatp</code> 驱动。<code>cyapa</code> 是 Google 为 Chromebook 内核专门修改的 Cypress Gen3 系列触控板驱动，而查看源代码之后发现 <code>cyapatp</code> 驱动不但支持 Cypress Gen3 系列触控板，也支持新的 Gen5 系列触控板，这样按说 <code>cyapatp</code> 直接就是支持我的 Chromebook 触控板设备的。</p>
<p>比较郁闷的是我直接在 Remix OS 终端里运行 <code>modprobe cyapatp</code> 命令虽然能成功加载驱动，但系统中并没有注册任何新的输入设备。</p>
<h2 id="chromebook-kernel-研究">Chromebook kernel 研究</h2>
<p>没办法就只能先检出 Chrome OS 当前使用的 3.8.11 版本内核源代码研究下了，检出方法可以参考我之前写的「<a href="https://zohead.com/archives/koding-chromebook/">在Koding云平台上编译Chromebook kernel</a>」这篇文章，Chrome OS kernel 分支可以在这里看到：</p>
<p><a href="https://chromium.googlesource.com/chromiumos/third_party/kernel/">https://chromium.googlesource.com/chromiumos/third_party/kernel/</a></p>
<p>稍微研究后发现原来 Chrome OS kernel 里增加了一个 <code>chromeos_laptop</code> 平台相关的驱动，Chrome OS 系统启动时会加载这个驱动（实际上是直接编译到 Chrome OS kernel 中的），<code>chromeos_laptop</code> 中会自动尝试查找并实例化 Chromebook 上的 I2C/SMBus 设备，看看其中的部分代码：</p>
<pre class="brush: cpp; title: chromeos_laptop.c; notranslate">
#define CYAPA_TP_I2C_ADDR	0x67

const char *i2c_adapter_names[] = {
	&quot;SMBus I801 adapter&quot;,
	&quot;i915 gmbus vga&quot;,
	&quot;i915 gmbus panel&quot;,
	&quot;i2c-designware-pci-0&quot;,
	&quot;i2c-designware-pci-1&quot;,
};

/* Keep this enum consistent with i2c_adapter_names */
enum i2c_adapter_type {
	I2C_ADAPTER_SMBUS = 0,
	I2C_ADAPTER_VGADDC,
	I2C_ADAPTER_PANEL,
	I2C_ADAPTER_I2C0,
	I2C_ADAPTER_I2C1,
};

static struct i2c_board_info cyapa_device = {
	I2C_BOARD_INFO(&quot;cyapa&quot;, CYAPA_TP_I2C_ADDR),
	.flags		= I2C_CLIENT_WAKE,
};

static struct chromeos_laptop wolf = {
	.i2c_peripherals = {
		/* Touchpad. */
		{ .add = setup_cyapa_tp, I2C_ADAPTER_I2C0 },
		/* Elan Touchpad option. */
		{ .add = setup_elantech_tp, I2C_ADAPTER_I2C0 },
	},
};

static struct i2c_client *add_i2c_device(const char *name,
						enum i2c_adapter_type type,
						struct i2c_board_info *info)
{
	const unsigned short addr_list[] = { info-&gt;addr, I2C_CLIENT_END };
	return __add_probed_i2c_device(name,
				       find_i2c_adapter_num(type),
				       info,
				       addr_list);
}

static int setup_cyapa_tp(enum i2c_adapter_type type)
{
	if (tp)
		return 0;

	/* add cyapa touchpad */
	tp = add_i2c_device(&quot;trackpad&quot;, type, &amp;cyapa_device);
	return (!tp) ? -EAGAIN : 0;
}
</pre>
<p>稍微分析下可以看到 <code>chromeos_laptop</code> 驱动是根据名称找到当前系统中的 I2C 适配器的，找到之后最后根据 I2C 地址调用 <code>i2c_new_probed_device</code> 函数实例化 I2C 设备，而这里 <code>cyapa</code> 触控板驱动使用的 I2C 适配器名称固定为 <code>i2c-designware-pci-0</code>。</p>
<p>这样就有 Remix OS 下使用触控板的解决思路了，我们可以修改 <code>i2c-designware-pci</code> 驱动使其报上来的两个 I2C 适配器使用不同的名称，并加入 <code>chromeos_laptop</code> 驱动这样就可以正常使用新的 <code>cyapatp</code> 驱动；或者也可以不修改 <code>i2c-designware-pci</code> 而直接加入并修改 <code>chromeos_laptop</code> 中的触控板 I2C 适配器名称，为了后续 I2C 的区分我决定用第一种方法。</p>
<h2 id="remix-os-kernel-修改">Remix OS kernel 修改</h2>
<p>首先我们就要检出技德不久前开放的 Remix OS kernel 代码了，地址在这里：</p>
<p><a href="https://github.com/jide-opensource/remixos-kernel/">https://github.com/jide-opensource/remixos-kernel/</a></p>
<p>值得一提的是 Remix OS 内核基本就是使用的默认 android-x86_64_defconfig 配置，先开始修改 <code>i2c-designware-pcidrv.c</code> 代码以支持使用不同的 I2C 适配器名称：</p>
<pre class="brush: diff; title: ; notranslate">
--- a/i2c-designware-pcidrv.c	2016-03-02 01:04:19.330843871 +0800
+++ b/i2c-designware-pcidrv.c	2016-03-01 00:18:04.502977140 +0800
@@ -48,7 +48,8 @@ enum dw_pci_ctl_id_t {
 	medfield_5,
 
 	baytrail,
-	haswell,
+	haswell_0,
+	haswell_1,
 };
 
 struct dw_scl_sda_cfg {
@@ -148,7 +149,15 @@ static struct dw_pci_controller dw_pci_c
 		.functionality = I2C_FUNC_10BIT_ADDR,
 		.scl_sda_cfg = &amp;byt_config,
 	},
-	[haswell] = {
+	[haswell_0] = {
+		.bus_num = -1,
+		.bus_cfg = INTEL_MID_STD_CFG | DW_IC_CON_SPEED_FAST,
+		.tx_fifo_depth = 32,
+		.rx_fifo_depth = 32,
+		.functionality = I2C_FUNC_10BIT_ADDR,
+		.scl_sda_cfg = &amp;hsw_config,
+	},
+	[haswell_1] = {
 		.bus_num = -1,
 		.bus_cfg = INTEL_MID_STD_CFG | DW_IC_CON_SPEED_FAST,
 		.tx_fifo_depth = 32,
@@ -258,7 +267,8 @@ static int i2c_dw_pci_probe(struct pci_d
 	adap-&gt;dev.parent = &amp;pdev-&gt;dev;
 	adap-&gt;nr = controller-&gt;bus_num;
 
-	snprintf(adap-&gt;name, sizeof(adap-&gt;name), &quot;i2c-designware-pci&quot;);
+	snprintf(adap-&gt;name, sizeof(adap-&gt;name), &quot;i2c-designware-pci-%ld&quot;,
+		(adap-&gt;nr &lt; 0) ? id-&gt;driver_data - haswell_0 : adap-&gt;nr);
 
 	r = devm_request_irq(&amp;pdev-&gt;dev, pdev-&gt;irq, i2c_dw_isr, IRQF_SHARED,
 			adap-&gt;name, dev);
@@ -314,8 +324,8 @@ static const struct pci_device_id i2_des
 	{ PCI_VDEVICE(INTEL, 0x0F46), baytrail },
 	{ PCI_VDEVICE(INTEL, 0x0F47), baytrail },
 	/* Haswell */
-	{ PCI_VDEVICE(INTEL, 0x9c61), haswell },
-	{ PCI_VDEVICE(INTEL, 0x9c62), haswell },
+	{ PCI_VDEVICE(INTEL, 0x9c61), haswell_0 },
+	{ PCI_VDEVICE(INTEL, 0x9c62), haswell_1 },
 	/* Braswell / Cherrytrail */
 	{ PCI_VDEVICE(INTEL, 0x22C1), baytrail },
 	{ PCI_VDEVICE(INTEL, 0x22C2), baytrail },
</pre>
<p>然后将 Chrome OS 3.8.11 版本 kernel 中的 <code>chromeos_laptop</code> 平台相关驱动加到 Remix OS 4.0.9 版本 kernel 中，最后开始编译内核 bzImage 和对应的内核模块文件，实际上编译 bzImage 只是为了生成需要的 Module.symvers 符号文件，真正要使用的是新编译生成的 <code>i2c-designware-pci.ko</code> 和 <code>chromeos_laptop.ko</code> 文件。</p>
<blockquote>
<p><strong>提示</strong></p>
<p>我是在 Chromebook Crouton 64 位 Ubuntu 14.04 环境中检出并修改 Remix OS kernel 进行编译的，实际 kernel 修改、加入新驱动修改 Makefile 和 Kconfig 等还有编译操作步骤什么的这里就不说明了，编译中间可能会有无线驱动报错，稍微修改下内核配置就可以通过了。</p>
</blockquote>
<h2 id="修改-remix-os-系统文件">修改 Remix OS 系统文件</h2>
<p>我编译好的两个内核模块文件下载地址（只适用于 Remix OS PC 版 alpha 4.0.9 内核）：</p>
<p><a href="https://zohead.com/downloads/cbtp-remixos-20160201alpha.zip">https://zohead.com/downloads/cbtp-remixos-20160201alpha.zip</a></p>
<p>首先可以在 Chromebook 上将新的内核模块文件放到 Remix OS U 盘中，如果你使用的是按照我之前的「<a href="https://zohead.com/archives/cb-ext4-remixos/">Chromebook使用ext4 U盘运行Remix OS</a>」文章介绍的方法生成的 ext4 格式 U 盘，那么修改替换 Remix OS 系统文件还是非常简单的。</p>
<pre class="brush: bash; title: ; notranslate">
(trusty)zzm@localhost:~$ sudo cp i2c-designware-pci.ko /media/removable/Android-x86/android-2016-02-02/system/lib/modules/4.0.9-android-x86_64+/kernel/drivers/i2c/busses/
(trusty)zzm@localhost:~$ sudo cp chromeos_laptop.ko /media/removable/Android-x86/android-2016-02-02/system/lib/modules/4.0.9-android-x86_64+/kernel/drivers/platform/x86/
</pre>
<blockquote>
<p><strong>注意</strong></p>
<p>上面的命令例子中假定 Remix OS U 盘已经自动被 Chrome OS 挂载到 <code>/media/removable/Android-x86</code> 目录了，<code>android-2016-02-02</code> 是 Remix OS 系统路径，实际的挂载和系统路径不完全相同请自行检查。</p>
</blockquote>
<p>下面是使用 <code>depmod</code> 命令重新生成新的模块依赖关系等文件，这样 Remix OS 系统在启动的时候就会自动尝试加载 <code>chromeos_laptop</code> 驱动，接着自动加载 <code>cyapatp</code> 驱动成功之后就可以直接 Chromebook 触控板了。</p>
<pre class="brush: bash; title: ; notranslate">
sudo depmod -A -b /media/removable/Android-x86/android-2016-02-02/system 4.0.9-android-x86_64+
</pre>
<p>最后说下我简单测试之后 Remix OS 中 Chromebook 触控板的使用效果：</p>
<ul>
<li>基本的移动、点击等操作可以正常工作；</li>
<li>看起来也是支持简单的多点触控的；</li>
<li>Remix OS 桌面图标的双击功能不起作用；</li>
<li>Chrome OS 下特色的两指上下滚动功能也可以正常使用（不过由于 Android 的自然滚动方式所以方向和 Chrome OS 下是相反的）；</li>
<li>某些 App 下面支持三指同时长按然后放开之后出现右键菜单；</li>
<li>Chrome OS 下特色的两指同时点击呼出右键菜单功能无效。</li>
</ul>
<p>总之虽然触控版的使用不像 Chrome OS 下那样完美但基本还是能满足需求的，本文中有任何错误或疑问欢迎提出指正哦，祝玩的开心～～～。</p>
]]></content:encoded>
			<wfw:commentRss>https://zohead.com/archives/remixos-cb-trackpad/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>在Koding云平台上编译Chromebook kernel</title>
		<link>https://zohead.com/archives/koding-chromebook/</link>
		<comments>https://zohead.com/archives/koding-chromebook/#comments</comments>
		<pubDate>Sat, 21 Mar 2015 16:39:08 +0000</pubDate>
		<dc:creator><![CDATA[Uranus Zhou]]></dc:creator>
				<category><![CDATA[kernel]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[ARM]]></category>
		<category><![CDATA[binfmt_misc]]></category>
		<category><![CDATA[Chrome OS]]></category>
		<category><![CDATA[Chromebook]]></category>
		<category><![CDATA[cifs]]></category>
		<category><![CDATA[Koding]]></category>
		<category><![CDATA[Secure Shell]]></category>
		<category><![CDATA[内核模块]]></category>

		<guid isPermaLink="false">http://zohead.com/?p=880</guid>
		<description><![CDATA[最近从淘宝收了一台三星的 Series 3 ARM Chromebook，平时当作上网本用起来还是可以的，可以运行一些 Chrome packaged 原生 App，Chrome OS 的运行速度也还凑合，主要电池续航比一般的笔记本要给力多了，这篇博文的编辑及实际 kernel 编译操作我都是在 Chromebook 上完成的。 由于 Chromebook 底层使用的还是 Linux 内核，装了 Crouton 插件之后可以在 Chromebook 里以 chroot 的方式跑另外的 Ubuntu 系统，只不过 Chromebook 自带的内核模块有些缺失，比如我需要的 binfmt_misc [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>最近从淘宝收了一台三星的 Series 3 ARM Chromebook，平时当作上网本用起来还是可以的，可以运行一些 Chrome packaged 原生 App，Chrome OS 的运行速度也还凑合，主要电池续航比一般的笔记本要给力多了，这篇博文的编辑及实际 kernel 编译操作我都是在 Chromebook 上完成的。</p>
<p>由于 Chromebook 底层使用的还是 Linux 内核，装了 Crouton 插件之后可以在 Chromebook 里以 chroot 的方式跑另外的 Ubuntu 系统，只不过 Chromebook 自带的内核模块有些缺失，比如我需要的 binfmt_misc 和 cifs 模块都是没有的，特别是很有用的 cifs 模块用于挂载 Windows 机器上的共享目录。因此想自己编译 Chromebook 的 kernel 加入需要的内核模块。</p>
<p>三星 Series 3 ARM Chromebook 自带的 16GB SSD 毕竟有点小，ARM 系统里装一堆开发环境还是嫌麻烦，还有比较重要的一点是国内的网络环境 git clone 出 Google Source 上的 kernel 源代码速度实在是太慢了，于是就想着用之前注册的 Koding 云端开发平台上跑交叉编译器来编译 Chromebook 的 kernel。</p>
<p><a href="http://www.koding.com/R/zohead" target="_blank">Koding</a> 云端开发平台默认自带了 Node.js、Python、Ruby、Go 等开发环境支持，Koding 默认给了一个很强大的 Web IDE 编辑工具，可以在 Web 上直接登录 Shell 操作，而且 Koding 提供的 Linux 虚拟环境默认就安装了 gcc、Makefile 等工具，其免费套餐提供的 1GB RAM、3GB 硬盘空间用来编译 kernel 也勉强够用了。</p>
<p>先在 Chromebook 里按 Ctrl +Alt + T 键切换到 crosh Shell 里确认当前 kernel 版本：</p>
<pre class="brush: bash; title: ; notranslate">
chronos@localhost / $ cat /proc/version
Linux version 3.8.11 (chrome-bot@build44-m2) (gcc version 4.9.x-google 20140827 (prerelease) (4.9.1_cos_gg_2f9796c_4.9.1-r82) ) #1 SMP Sat Mar 7 06:47:35 PST 2015
</pre>
<p>可以看到现在用的是最新 Linux 3.8.11 版本，从 Google 官方提供的 kernel 版本库里确认需要使用的 kernel 分支：</p>
<p><a href="https://chromium.googlesource.com/chromiumos/third_party/kernel/" target="_blank">https://chromium.googlesource.com/chromiumos/third_party/kernel/</a></p>
<p>我需要的 3.8.11 版本就可以直接使用 chromeos-3.8 分支，现在可以 SSH 远程登录到 Koding Linux 系统上，幸运的是我们还可以在 Chromebook 安装 <a href="https://chrome.google.com/webstore/detail/secure-shell/pnhechapfaindjhompbnflcldabbghjo" target="_blank">Secure Shell</a> 这一牛叉 App 直接进行 SSH 登录，Secure Shell 支持 Koding 的 SSH 证书（需要自己登录到 Koding 的 Web Shell 里生成哈）形式，不过选择证书时需要注意把公钥和私钥文件同时选上。</p>
<p>Koding 云端开发平台默认使用的是 Ubuntu 14.04 LTS 64 位系统，这样也比较好，ARM 交叉编译器安装起来也很方便了，先 clone 出 kernel 源代码：</p>
<pre class="brush: bash; title: ; notranslate">
git clone https://chromium.googlesource.com/chromiumos/third_party/kernel -b chromeos-3.8
</pre>
<p>然后运行 <strong>sudo apt-get install gcc-arm-linux-gnueabi</strong> 安装交叉编译器，Ubuntu 提供的 ARM gcc 编译器是 4.7.2 版本。</p>
<p>接着需要把 Chromebook 当前的 kernel 配置导出来，在 Chromebook 上切换到 Shell，运行 <strong>sudo modprobe configs</strong> 命令，然后拷贝 <strong>/proc/config.gz</strong> 文件并解压缩，通过 scp 命令将解压缩出来的 <strong>config</strong> 文件拷贝到 Koding Linux 系统中。</p>
<p>在 Koding Linux 系统中进入刚才 clone 出来的 Linux kernel 源代码目录，将 Chromebook 上拷贝过来的 <strong>config</strong> 文件重命名为 <strong>.config</strong>，然后运行下面的命令进行 kernel 配置：</p>
<pre class="brush: bash; title: ; notranslate">
cd ~/kernel
make ARCH=arm CROSS_COMPILE=arm-linux-gnueabi- menuconfig
</pre>
<p>我们可以在 Network Filesystem 中启用 cifs 模块，同时可以启用 binfmt_misc 模块，保存 kernel 配置，运行下面的命令直接开始内核编译：</p>
<pre class="brush: bash; title: ; notranslate">
cd ~/kernel
make ARCH=arm CROSS_COMPILE=arm-linux-gnueabi-
</pre>
<p>如果你不想编译完整的 Chromebook kernel，也可以使用这两个命令只编译需要的 binfmt_misc 和 cifs 模块，这样可以节省时间：</p>
<pre class="brush: bash; title: ; notranslate">
make ARCH=arm CROSS_COMPILE=arm-linux-gnueabi- M=fs/cifs
make ARCH=arm CROSS_COMPILE=arm-linux-gnueabi- fs/binfmt_misc.ko
</pre>
<p>需要注意的是这样编译出来的 cifs.ko 模块文件还是依赖 md4.ko 文件（会自动编译出来）的。</p>
<p>下面就是通过 scp 把编译出来的 cifs.ko、md4.ko、binfmt_misc.ko 文件拷贝到 Chromebook 系统中，我们可以将这 3 个文件放到 Linux 内核模块目录中（不过这一步需要在 Chromebook 的开发模式中禁用 Chrome OS 的 rootfs 分区锁定功能）：</p>
<pre class="brush: bash; title: ; notranslate">
mkdir /lib/modules/3.8.11/kernel/fs/cifs
mv cifs.ko /lib/modules/3.8.11/kernel/fs/cifs
mv binfmt_misc.ko /lib/modules/3.8.11/kernel/fs
mv md4.ko /lib/modules/3.8.11/kernel/crypto
</pre>
<p>然后可以运行 sudo depmod -a 命令让系统自动生成内核模块依赖关系。</p>
<p>需要注意的是如果你把新编译出来的 ko 模块文件放在不是 rootfs 分区里（未禁用 Chrome OS 的 rootfs 分区保护等情况），这样 insmod binfmt_misc.ko 等命令加载模块会报错失败：</p>
<pre class="brush: plain; title: ; notranslate">
Chromium OS LSM: init_module denied module=&quot;/home/chronos/user/Downloads/binfmt_misc.ko&quot; pid=12499 cmdline=&quot;insmod binfmt_misc.ko&quot;
</pre>
<p>这是由于 Chrome OS 默认做了限制即不允许加载放在 rootfs 分区以外的文件系统上的内核模块文件，我们也可以运行下面的命令解除这个限制：</p>
<pre class="brush: bash; title: ; notranslate">
echo 0 &gt; /proc/sys/kernel/chromiumos/module_locking
</pre>
<p>当然如果你将模块拷贝到上面提到的标准内核模块目录中的话就不会有这个问题了。</p>
<p>经过测试这样的方法编译的模块使用起来还是没有问题的，当然还是有一个不爽之处就是如果 Chrome OS 升级之后内核版本也升级了，但这些模块也需要重新编译了，文中有任何问题还是欢迎提出指正哦，祝玩的开心 ^_^</p>
]]></content:encoded>
			<wfw:commentRss>https://zohead.com/archives/koding-chromebook/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NFS读写块大小问题分析</title>
		<link>https://zohead.com/archives/nfs-rwsize/</link>
		<comments>https://zohead.com/archives/nfs-rwsize/#comments</comments>
		<pubDate>Sat, 05 Jul 2014 14:44:32 +0000</pubDate>
		<dc:creator><![CDATA[Uranus Zhou]]></dc:creator>
				<category><![CDATA[kernel]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[存储]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[NFS]]></category>
		<category><![CDATA[TCP]]></category>
		<category><![CDATA[UDP]]></category>
		<category><![CDATA[块大小]]></category>

		<guid isPermaLink="false">http://zohead.com/?p=723</guid>
		<description><![CDATA[本文同步自（最佳显示效果请点击）：https://zohead.com/archives/nfs-rwsize/ Linux NFS 客户端在挂载服务器的 NFS 共享时可以使用 rsize 和 wsize 参数指定 NFS 读写的块大小，但实际使用时发现并不完全凑效，下面简单分析一下。 我先在一台 RHEL6 客户端上挂载另一台 RHEL6 服务器上的 NFS 共享： 从上面可以看到不指定 rsize 和 wsize 参数时，默认的读写块大小都是 256KB（rsize=262144），而且使用的是 TCP 协议（proto=tcp）。 下面使用 UDP 协议挂载 NFS 共享： 从结果可以 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>本文同步自（最佳显示效果请点击）：<a href="https://zohead.com/archives/nfs-rwsize/" target="_blank">https://zohead.com/archives/nfs-rwsize/</a></p>
<p>Linux NFS 客户端在挂载服务器的 NFS 共享时可以使用 rsize 和 wsize 参数指定 NFS 读写的块大小，但实际使用时发现并不完全凑效，下面简单分析一下。</p>
<p>我先在一台 RHEL6 客户端上挂载另一台 RHEL6 服务器上的 NFS 共享：</p>
<p><pre class="brush: bash; title: ; notranslate">
[root@localhost ~]# mount -t nfs 192.168.1.122:/nfs/share /mnt/nfs
[root@localhost ~]# grep /mnt/nfs /proc/mounts
192.168.1.122:/nfs/share /mnt/nfs nfs rw,relatime,vers=3,rsize=262144,wsize=262144,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,mountaddr=192.168.1.122,mountvers=3,mountport=892,mountproto=udp,local_lock=none,addr=192.168.1.122 0 0
</pre>
</p>
<p>从上面可以看到不指定 rsize 和 wsize 参数时，默认的读写块大小都是 256KB（rsize=262144），而且使用的是 TCP 协议（proto=tcp）。</p>
<p>下面使用 UDP 协议挂载 NFS 共享：</p>
<p><pre class="brush: bash; title: ; notranslate">
[root@localhost ~]# mount -t nfs -o udp 192.168.1.122:/nfs/share /mnt/nfs
[root@localhost ~]# grep /mnt/nfs /proc/mounts
192.168.1.122:/nfs/share /mnt/nfs nfs rw,relatime,vers=3,rsize=32768,wsize=32768,namlen=255,hard,proto=udp,timeo=11,retrans=3,sec=sys,mountaddr=192.168.1.122,mountvers=3,mountport=892,mountproto=udp,local_lock=none,addr=192.168.1.122 0 0
</pre>
</p>
<p>从结果可以看出，使用 UDP 协议时块大小就只有 32KB 了。</p>
<p>准备在客户端这边修改 mount 参数将 NFS TCP 方式的读写块大小增加到 1MB：</p>
<p><pre class="brush: bash; title: ; notranslate">
[root@localhost ~]# mount -t nfs -o rsize=1048576,wsize=1048576 192.168.1.122:/nfs/share /mnt/nfs
[root@localhost ~]# grep /mnt/nfs /proc/mounts
192.168.1.122:/nfs/share /mnt/nfs nfs rw,relatime,vers=3,rsize=262144,wsize=262144,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,mountaddr=192.168.1.122,mountvers=3,mountport=892,mountproto=udp,local_lock=none,addr=192.168.1.122 0 0
</pre>
</p>
<p>但从上面的结果来看，实际使用的块大小还是 256KB。</p>
<p>在客户端这边修改 mount 参数将 NFS UDP 方式的读写块大小增加到 256KB：</p>
<p><pre class="brush: bash; title: ; notranslate">
[root@localhost ~]# mount -t nfs -o udp,rsize=262144,wsize=262144 192.168.1.122:/nfs/share /mnt/nfs
[root@localhost ~]# grep /mnt/nfs /proc/mounts
192.168.1.122:/nfs/share /mnt/nfs nfs rw,relatime,vers=3,rsize=32768,wsize=32768,namlen=255,hard,proto=udp,timeo=11,retrans=3,sec=sys,mountaddr=192.168.1.122,mountvers=3,mountport=892,mountproto=udp,local_lock=none,addr=192.168.1.122 0 0
</pre>
</p>
<p>UDP 模式下读写的块大小也无法修改，客户端似乎已经使用了最大的读写块大小。</p>
<p>没办法，下面来看看 Linux kernel 源代码，找出真正的原因，先在 include/linux/nfs_xdr.h 文件中找到了 NFS I/O 块大小的定义：</p>
<p><pre class="brush: cpp; title: include/linux/nfs_xdr.h; notranslate">
/*
 * To change the maximum rsize and wsize supported by the NFS client, adjust
 * NFS_MAX_FILE_IO_SIZE.  64KB is a typical maximum, but some servers can
 * support a megabyte or more.  The default is left at 4096 bytes, which is
 * reasonable for NFS over UDP.
 */
#define NFS_MAX_FILE_IO_SIZE    (1048576U)
#define NFS_DEF_FILE_IO_SIZE    (4096U)
#define NFS_MIN_FILE_IO_SIZE    (1024U)
</pre>
</p>
<p>这里可以看到 NFS 默认使用 4KB 块大小，客户端实际挂载时会做调整，最小 1KB，最大 1MB。</p>
<p>NFS 客户端在挂载时会与 NFS 服务器协商适合的读写块大小值，我们来看看 fs/nfs/client.c 文件中协商设置 NFS 文件系统信息的代码：</p>
<p><pre class="brush: cpp; highlight: [0,11,12,13,14]; title: fs/nfs/client.c; notranslate">
static void nfs_server_set_fsinfo(struct nfs_server *server, struct nfs_fsinfo *fsinfo)
{
	unsigned long max_rpc_payload;

	/* Work out a lot of parameters */
	if (server-&gt;rsize == 0)
		server-&gt;rsize = nfs_block_size(fsinfo-&gt;rtpref, NULL);
	if (server-&gt;wsize == 0)
		server-&gt;wsize = nfs_block_size(fsinfo-&gt;wtpref, NULL);

	if (fsinfo-&gt;rtmax &gt;= 512 &amp;&amp; server-&gt;rsize &gt; fsinfo-&gt;rtmax)
		server-&gt;rsize = nfs_block_size(fsinfo-&gt;rtmax, NULL);
	if (fsinfo-&gt;wtmax &gt;= 512 &amp;&amp; server-&gt;wsize &gt; fsinfo-&gt;wtmax)
		server-&gt;wsize = nfs_block_size(fsinfo-&gt;wtmax, NULL);

	max_rpc_payload = nfs_block_size(rpc_max_payload(server-&gt;client), NULL);
	if (server-&gt;rsize &gt; max_rpc_payload)
		server-&gt;rsize = max_rpc_payload;
	if (server-&gt;rsize &gt; NFS_MAX_FILE_IO_SIZE)
		server-&gt;rsize = NFS_MAX_FILE_IO_SIZE;
	server-&gt;rpages = (server-&gt;rsize + PAGE_CACHE_SIZE - 1) &gt;&gt; PAGE_CACHE_SHIFT;

	server-&gt;backing_dev_info.name = &quot;nfs&quot;;
	server-&gt;backing_dev_info.ra_pages = server-&gt;rpages * NFS_MAX_READAHEAD;

	if (server-&gt;wsize &gt; max_rpc_payload)
		server-&gt;wsize = max_rpc_payload;
	if (server-&gt;wsize &gt; NFS_MAX_FILE_IO_SIZE)
		server-&gt;wsize = NFS_MAX_FILE_IO_SIZE;
	/*......*/
}
</pre>
</p>
<p>从上面 nfs_server_set_fsinfo 函数的代码可以看到 NFS 客户端实际参考了服务器返回的 rtmax 和 wtmax 值，而这个值可以在挂载 NFS 文件系统时用抓包工具看到（NFS 使用的 RPC 协议）。</p>
<p>下面的图片中显示的就是 NFS 客户端中指定 rsize 和 wsize 参数为 1MB 时 Wireshark 上抓到的 NFS FSINFO 请求的实际数据；</p>
<div style="width: 513px" class="wp-caption alignnone"><a href="http://zohead.com/wp-content/uploads/nfs-mount-cap.jpg" target="_blank"><img alt="挂载NFS的网络抓包" src="http://zohead.com/wp-content/uploads/nfs-mount-cap.jpg" width="503" height="231" /></a><p class="wp-caption-text">挂载NFS的网络抓包</p></div>
<p>上面图片里小椭圆圈表示的是 NFS FSINFO 请求，大椭圆圈里就是服务器传过来的 rtmax 和 wtmax 值了，我们可以看到值就是 256KB。这样也就能解释了为什么客户端增大 NFS 读写块大小也不起作用了。</p>
<p>我们后台登陆到 NFS 服务器上，可以从 /proc/fs/nfsd/max_block_size 文件中看到当前 NFS 服务器的最大块大小，然后尝试修改它：</p>
<p><pre class="brush: bash; title: ; notranslate">
~ # cat /proc/fs/nfsd/max_block_size
262144
~ # echo 524288 &gt; /proc/fs/nfsd/max_block_size
~ # cat /proc/fs/nfsd/max_block_size
262144
</pre>
</p>
<p>可以看到当前 NFS 服务器的最大读写块大小确实是 256KB，但是我们想修改它的值的时候，却似乎又修改不了。这样只能再看看修改 max_block_size 的 kernel 源代码了，对应的代码在 nfsd/nfsctl.c 文件中：</p>
<p><pre class="brush: cpp; highlight: [14,15,18]; title: nfsd/nfsctl.c; notranslate">
static ssize_t write_maxblksize(struct file *file, char *buf, size_t size)
{
	char *mesg = buf;
	if (size &gt; 0) {
		int bsize;
		int rv = get_int(&amp;mesg, &amp;bsize);
		if (rv)
			return rv;
		/* force bsize into allowed range and
		 * required alignment.
		 */
		if (bsize &lt; 1024)
			bsize = 1024;
		if (bsize &gt; NFSSVC_MAXBLKSIZE)
			bsize = NFSSVC_MAXBLKSIZE;
		bsize &amp;= ~(1024-1);
		mutex_lock(&amp;nfsd_mutex);
		if (nfsd_serv &amp;&amp; nfsd_serv-&gt;sv_nrthreads) {
			mutex_unlock(&amp;nfsd_mutex);
			return -EBUSY;
		}
		nfsd_max_blksize = bsize;
		mutex_unlock(&amp;nfsd_mutex);
	}

	return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, &quot;%d\n&quot;,
							nfsd_max_blksize);
}
</pre>
</p>
<p>write_maxblksize 函数中判断了传入的参数，如果写入的值超过 NFSSVC_MAXBLKSIZE 值则固定为 NFSSVC_MAXBLKSIZE 值，那我们来看看 NFSSVC_MAXBLKSIZE 的定义：</p>
<p><pre class="brush: cpp; title: linux/nfsd/const.h; notranslate">
/*
 * Maximum blocksizes supported by daemon under various circumstances.
 */
#define NFSSVC_MAXBLKSIZE   RPCSVC_MAXPAYLOAD
/* NFSv2 is limited by the protocol specification, see RFC 1094 */
#define NFSSVC_MAXBLKSIZE_V2    (8*1024)
</pre>
</p>
<p>linux/nfsd/const.h 中 NFSSVC_MAXBLKSIZE 定义为了 RPCSVC_MAXPAYLOAD 的值，那看看 linux/sunrpc/svc.h 中 RPCSVC_MAXPAYLOAD 的实际值：</p>
<p><pre class="brush: cpp; title: linux/sunrpc/svc.h; notranslate">
/*
 * Maximum payload size supported by a kernel RPC server.
 * This is use to determine the max number of pages nfsd is
 * willing to return in a single READ operation.
 *
 * These happen to all be powers of 2, which is not strictly
 * necessary but helps enforce the real limitation, which is
 * that they should be multiples of PAGE_CACHE_SIZE.
 *
 * For UDP transports, a block plus NFS,RPC, and UDP headers
 * has to fit into the IP datagram limit of 64K.  The largest
 * feasible number for all known page sizes is probably 48K,
 * but we choose 32K here.  This is the same as the historical
 * Linux limit; someone who cares more about NFS/UDP performance
 * can test a larger number.
 *
 * For TCP transports we have more freedom.  A size of 1MB is
 * chosen to match the client limit.  Other OSes are known to
 * have larger limits, but those numbers are probably beyond
 * the point of diminishing returns.
 */
#define RPCSVC_MAXPAYLOAD   (1*1024*1024u)
#define RPCSVC_MAXPAYLOAD_TCP   RPCSVC_MAXPAYLOAD
#define RPCSVC_MAXPAYLOAD_UDP   (32*1024u)
</pre>
</p>
<p>从 linux/sunrpc/svc.h 中可以看到 NFS 读写块大小必须为 2 的幂，这样也大概知道读写块大小限制的原因了：</p>
<p>对于 UDP 来说，由于一个 UDP 包最大才 64KB，因此使用 UDP 协议的 NFS 读写块大小最大不超过 48KB，而 kernel 中则直接限制为 32KB 了；而使用 TCP 协议的 NFS 由于没有这个限制允许更大的读写块大小，但 Linux kernel 还是将其限制为 1MB 了。</p>
<p>至于 max_block_size 值不能直接修改的现象也找到原因了，在 nfsd/nfsctl.c 文件中高亮显示的第 18 行代码里判断了 NFS 服务器是否在启动运行，如果在运行则不允许修改。</p>
<p>下面就好办了，先卸载 NFS 共享的挂载，停止服务器的 NFS 服务，修改 max_block_size 值，然后重新启动 NFS 服务，</p>
<p><pre class="brush: bash; title: ; notranslate">
~ # service nfs stop
Shutting down NFS mountd:                                  [  OK  ]
Shutting down NFS daemon:                                  [  OK  ]
Shutting down NFS services:                                [  OK  ]
~ # echo 1048576 &gt; /proc/fs/nfsd/max_block_size
~ # cat /proc/fs/nfsd/max_block_size
1048576
~ # service nfs start
</pre>
</p>
<p>可以看到现在 NFS 的最大块大小可以修改了，接着在客户端中指定读写块大小并重新挂载 NFS 共享，这个时候客户端也能正确使用更大的块大小了：</p>
<p><pre class="brush: bash; title: ; notranslate">
[root@localhost fs]# mount -t nfs -o rsize=1048576,wsize=1048576 192.168.1.122:/nfs/share /mnt/nfs
[root@localhost fs]# grep /mnt/nfs /proc/mounts
192.168.1.122:/nfs/share /mnt/nfs nfs rw,relatime,vers=3,rsize=1048576,wsize=1048576,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,mountaddr=192.168.1.122,mountvers=3,mountport=892,mountproto=udp,local_lock=none,addr=192.168.1.122 0 0
</pre>
</p>
<p>如果要深究一下 NFS 服务器初始的最大块大小只有 256KB 的原因，可以看看 kernel 中 nfsd/nfssvc.c 文件中的代码：</p>
<p><pre class="brush: cpp; highlight: [13,20,22,23,24]; title: nfsd/nfssvc.c; notranslate">
int nfsd_create_serv(void)
{
	int err = 0;

	WARN_ON(!mutex_is_locked(&amp;nfsd_mutex));
	if (nfsd_serv) {
		svc_get(nfsd_serv);
		return 0;
	}
	if (nfsd_max_blksize == 0) {
		/* choose a suitable default */
		struct sysinfo i;
		si_meminfo(&amp;i);
		/* Aim for 1/4096 of memory per thread
		 * This gives 1MB on 4Gig machines
		 * But only uses 32K on 128M machines.
		 * Bottom out at 8K on 32M and smaller.
		 * Of course, this is only a default.
		 */
		nfsd_max_blksize = NFSSVC_MAXBLKSIZE;
		i.totalram &lt;&lt;= PAGE_SHIFT - 12;
		while (nfsd_max_blksize &gt; i.totalram &amp;&amp;
		       nfsd_max_blksize &gt;= 8*1024*2)
			nfsd_max_blksize /= 2;
	}

	nfsd_serv = svc_create_pooled(&amp;nfsd_program, nfsd_max_blksize,
				      nfsd_last_thread, nfsd, THIS_MODULE);
	if (nfsd_serv == NULL)
		err = -ENOMEM;
	else
		set_max_drc();

	do_gettimeofday(&amp;nfssvc_boot);		/* record boot time */
	return err;
}
</pre>
</p>
<p>从上面的可以看到，NFS 服务器在决定默认的最大读写块大小时考虑到内存占用情况，每个 NFS 内核线程最多只使用 1/4096 的物理内存大小，对于物理内存超过 4GB 的机器才使用最大的 1MB 读写块大小。</p>
<p>来看看我们使用的 NFS 服务器的内存情况，可以看到服务器只使用了 2GB 的内存：</p>
<p><pre class="brush: bash; title: ; notranslate">
~ # free
             total       used       free     shared    buffers     cached
Mem:       2040272     335476    1704796          0       2360      70076
-/+ buffers/cache:     263040    1777232
Swap:            0          0          0
</pre>
</p>
<p>按照 nfsd/nfssvc.c 文件中的代码，i.totalram 实际值为所有可用的物理内存的页数量，我们这里就是 2040272 / 4KB（默认的 PAGE_SIZE 页大小），按照高亮的第 22 - 24 行代码计算出来的默认最大块大小值就是 262144 了。</p>
<p>本文为个人经过测试及分析 Linux kernel 源代码得出的分析结果，如果其中存在错误还请提出指正哦~~~ ^_^</p>
]]></content:encoded>
			<wfw:commentRss>https://zohead.com/archives/nfs-rwsize/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>构建Lava XOLO X900非官方kernel</title>
		<link>https://zohead.com/archives/xolo-x900-kernel/</link>
		<comments>https://zohead.com/archives/xolo-x900-kernel/#comments</comments>
		<pubDate>Thu, 20 Dec 2012 13:38:43 +0000</pubDate>
		<dc:creator><![CDATA[Uranus Zhou]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[kernel]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[手机]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[Atom]]></category>
		<category><![CDATA[cifs]]></category>
		<category><![CDATA[config]]></category>
		<category><![CDATA[Intel]]></category>
		<category><![CDATA[K800]]></category>
		<category><![CDATA[Lava]]></category>
		<category><![CDATA[OTG]]></category>
		<category><![CDATA[U盘]]></category>
		<category><![CDATA[x86]]></category>
		<category><![CDATA[X900]]></category>
		<category><![CDATA[XOLO]]></category>
		<category><![CDATA[Z2460]]></category>
		<category><![CDATA[印度]]></category>
		<category><![CDATA[模块]]></category>
		<category><![CDATA[联想]]></category>

		<guid isPermaLink="false">http://zohead.com/?p=371</guid>
		<description><![CDATA[本文同步自（最佳显示效果请点击）：https://zohead.com/archives/xolo-x900-kernel/ 本文目标为 Lava XOLO X900 这一印度咖喱味手机，同样 Intel Atom Z2460 的芯，移植 kernel 的方法和之前的联想 K800 手机基本一致，具体请移步下面的链接： https://zohead.com/archives/k800-kernel-otg-udisk/ 经过确认 XOLO X900 默认也是 Android 4.0.4 ROM，同样 3.0.8 kernel，当然硬件会有所不同，不过 OTG U盘所需要使用的 usb-stor [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>本文同步自（最佳显示效果请点击）：<a href="https://zohead.com/archives/xolo-x900-kernel/" target="_blank">https://zohead.com/archives/xolo-x900-kernel/</a></p>
<p>本文目标为 Lava XOLO X900 这一印度咖喱味手机，同样 Intel Atom Z2460 的芯，移植 kernel 的方法和之前的联想 K800 手机基本一致，具体请移步下面的链接：</p>
<p><a href="https://zohead.com/archives/k800-kernel-otg-udisk/" target="_blank">https://zohead.com/archives/k800-kernel-otg-udisk/</a></p>
<p>经过确认 XOLO X900 默认也是 Android 4.0.4 ROM，同样 3.0.8 kernel，当然硬件会有所不同，不过 OTG U盘所需要使用的 usb-storage 模块也是和 K800 一样默认没有开启的。</p>
<p>基于基本相同的 kernel source，先使用 Medfield 默认的配置 i386_mfld_defconfig，发现与现有的 kernel 差距比较多，然后用 Moto 的 i386_mfld_moto_defconfig 编译出的模块加载依然 panic。没办法，硬着头皮与实际运行中 kernel 情况进行对比，发现基于默认配置 i386_mfld_defconfig 进行修改是比较好的方法，而且看得出 XOLO 相对联想还是做了一定的优化，去掉了像 CONFIG_DEBUG_KERNEL 之类的很多调试选项，默认允许了 tun 驱动等。另外声卡相关的配置不同的地方也比较多，经过最终改动和确认，编译之后，先已能成功加载并使用之前在 K800 上编译的那些模块。</p>
<p>XOLO X900 的内核模块和配置文件的下载地址：</p>
<p><a href="http://miseal.googlecode.com/files/x900-kernel-config-modules.7z" target="_blank">http://miseal.googlecode.com/files/x900-kernel-config-modules.7z</a></p>
<p>使用方法和 K800 的基本一致，只是 CIFS 文件系统的使用上有变动：</p>
<p>insmod des_generic.ko<br />
insmod md4.ko<br />
insmod cifs.ko</p>
<p>ASIX Electronics 的 USB 以太网卡的驱动 asix.ko 也已经更新到官方最新的版本（kernel 自带的版本无法使用）。</p>
<p>现已基本可以确认我改动之后的 kernel 和 X900 现有 kernel 的相似性已有 90% 或以上了，不过由于 X900 手机悲剧滴将 bootloader 给锁了，无法刷未签名的 kernel，暂时还没有太好的办法来直接替换 kernel 进行测试哦。</p>
<p>另外有一些需要说明的地方：</p>
<ol>
<li>XOLO X900 现有 kernel 中支持 Kineto GAN 虚拟网卡驱动（支持 VOIP 网络电话的），Moto Razr i 公开的 kernel source 中却并没有这个的支持，为此我手工增加了这个的驱动（上面下载的 kernel configuration 中也有的）；</li>
<li>目前还有 apwr3_0、pax、sep3_7 这三个非免费开源的内核模块没有源代码，暂时也没有办法在网上找到，不过从现在来看，似乎 X900 实际运行时也未使用这三个模块。</li>
</ol>
<p>同样我不对任何导致你的手机 panic 挂掉的后果承担责任，有任何问题欢迎提出指正哦 ^_^</p>
]]></content:encoded>
			<wfw:commentRss>https://zohead.com/archives/xolo-x900-kernel/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>密码保护：使用DM thin-provisioning提高存储利用率</title>
		<link>https://zohead.com/archives/dm-thin-provision/</link>
		<comments>https://zohead.com/archives/dm-thin-provision/#comments</comments>
		<pubDate>Fri, 14 Dec 2012 15:35:38 +0000</pubDate>
		<dc:creator><![CDATA[Uranus Zhou]]></dc:creator>
				<category><![CDATA[Device mapper]]></category>
		<category><![CDATA[kernel]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[存储]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[DM]]></category>
		<category><![CDATA[dmsetup]]></category>
		<category><![CDATA[LVM]]></category>
		<category><![CDATA[LVM2]]></category>
		<category><![CDATA[thin]]></category>
		<category><![CDATA[回滚]]></category>
		<category><![CDATA[快照]]></category>
		<category><![CDATA[自动精简配置]]></category>

		<guid isPermaLink="false">http://zohead.com/?p=356</guid>
		<description><![CDATA[无法提供摘要。这是一篇受保护的文章。]]></description>
				<content:encoded><![CDATA[<form action="https://zohead.com/wp-login-zohead.php?action=postpass" class="post-password-form" method="post">
<p>这是一篇受密码保护的文章，您需要提供访问密码：</p>
<p><label for="pwbox-356">密码： <input name="post_password" id="pwbox-356" type="password" size="20" /></label> <input type="submit" name="Submit" value="提交" /></p>
</p></form>
]]></content:encoded>
			<wfw:commentRss>https://zohead.com/archives/dm-thin-provision/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>构建联想K800非官方kernel支持OTG U盘</title>
		<link>https://zohead.com/archives/k800-kernel-otg-udisk/</link>
		<comments>https://zohead.com/archives/k800-kernel-otg-udisk/#comments</comments>
		<pubDate>Tue, 27 Nov 2012 15:33:48 +0000</pubDate>
		<dc:creator><![CDATA[Uranus Zhou]]></dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[kernel]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[cifs]]></category>
		<category><![CDATA[config]]></category>
		<category><![CDATA[Intel]]></category>
		<category><![CDATA[K800]]></category>
		<category><![CDATA[Motorola]]></category>
		<category><![CDATA[OTG]]></category>
		<category><![CDATA[RAZR i]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[U盘]]></category>
		<category><![CDATA[手机]]></category>
		<category><![CDATA[模块]]></category>
		<category><![CDATA[源代码]]></category>
		<category><![CDATA[编译]]></category>
		<category><![CDATA[联想]]></category>

		<guid isPermaLink="false">http://zohead.com/?p=348</guid>
		<description><![CDATA[本文同步自（最佳显示效果请点击）：https://zohead.com/archives/k800-kernel-otg-udisk/ 这几天专门入了个二手的联想 K800 的 Android 手机，看中的就是它是 x86 的 CPU，其采用 Intel Medfield Atom 平台，具体处理器型号为 Intel Atom Z2460，用的 Android 4.0.4 系统，具体其它配置我就不多说的。 优点： 使用 Intel x86 CPU，方便程序的移植（相对 ARM 而言）； 4.5 寸的 1280 x 720 的 IPS 高清屏幕，主要分辨率够给力； 支持 USB OTG； 支持  [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>本文同步自（最佳显示效果请点击）：<a href="https://zohead.com/archives/k800-kernel-otg-udisk/" target="_blank">https://zohead.com/archives/k800-kernel-otg-udisk/</a></p>
<p>这几天专门入了个二手的联想 K800 的 Android 手机，看中的就是它是 x86 的 CPU，其采用 Intel Medfield Atom 平台，具体处理器型号为 Intel Atom Z2460，用的 Android 4.0.4 系统，具体其它配置我就不多说的。</p>
<p>优点：</p>
<ul>
<li>使用 Intel x86 CPU，方便程序的移植（相对 ARM 而言）；</li>
<li>4.5 寸的 1280 x 720 的 IPS 高清屏幕，主要分辨率够给力；</li>
<li>支持 USB OTG；</li>
<li>支持 MHL 视频输出（缺点也在这，下面再说）；</li>
<li>耗电没想象中的那么严重；</li>
<li>使用的 Intel Atom Z2460 CPU 支持 EM64T 64 位指令；</li>
<li>使用的 Intel Atom Z2460 CPU 支持 Intel VT-x 虚拟化技术（不过这个好像在 Android 4.1 中用处才发挥出来，暂时也用不上）；</li>
<li>很便宜。</li>
</ul>
<p>缺点：</p>
<ul>
<li>没有单独的 HDMI 接口，视频输出需要占用 MicroUSB，OTG 与 MHL 无法同时使用；</li>
<li>OTG 不支持 U 盘（也是本文要解决的）；</li>
<li>恶心的乐 Phone，联想没有公开 kernel 源代码。</li>
</ul>
<p>上面说的缺点里，最后一条不公开 kernel source 是联想一贯悠久的恶劣传统，也是我最忍受不了的一条。</p>
<p>一番努力搜寻之后，我终于找到了曲线救国的神主：Motorola。对，就是他，虽然摩托似乎从来就没有开放的基因，但被 Google 收购之后，摩托在其推出的 Intel 手机 Moto RAZR i 上终于有良心了一把：公布了 Moto RAZR i 的 kernel source。由于 Moto RAZR i 与联想 K800 同样采用 Intel Medfield 平台，因此我就赌了一把其 kernel source 会有很大程度上的相似性，结果很幸运小成功了。</p>
<p><strong><span style="color: #ff0000;">1、获取源码：</span></strong></p>
<p>首先在 SourceForge 上抓取 Moto RAZR i 的 kernel source：</p>
<p><a href="http://sourceforge.net/projects/razr-i.motorola/files/" target="_blank">http://sourceforge.net/projects/razr-i.motorola/files/</a></p>
<p>一共 100 多MB，咱先解压，打开 Makefile，确定 kernel version 是 3.0.8 版本。</p>
<p>给联想 K800 root，装 adb 驱动，用 adb shell 连上看，运行 <strong>uname -a</strong> 查看 K800 手机的 kernel version 是 3.0.8-g37de913，啊哈，除了后缀版本一致。然后尝试读取 /proc/config.gz，无奈联想又是没有把 kernel configuration 给导出，找不到 /proc/config.gz 文件，没办法，只能自己根据当前手机 kernel 判断 K800 当前的 kernel configuration 了。</p>
<p>运行：<strong>egrep '(vmx|svm)' /proc/cpuinfo</strong>，确定 CPU 支持 Intel VT-x 虚拟化技术，有点小兴奋。</p>
<p><strong><span style="color: #ff0000;">2、准备编译环境：</span></strong></p>
<p>接着在手机上查看 <strong>/proc/version</strong>，确定联想 K800 kernel 使用的 gcc 版本为 4.3.3，刚好与 Moto 介绍的一致。然后使用 git clone 从下面的地址得到编译 kernel 的 android x86 toolchain：</p>
<p><a href="https://android.googlesource.com/platform/prebuilts/gcc/linux-x86/x86/i686-android-linux-4.4.3/" target="_blank">https://android.googlesource.com/platform/prebuilts/gcc/linux-x86/x86/i686-android-linux-4.4.3/</a></p>
<p>需要注意 git 得到的代码中默认已经把 gcc 4.3.3 给移除了，不过运行 git log 可以看到之前的提交日志里是有的，那好办，运行下面命令回滚到最新可用的版本：</p>
<p><strong>git checkout 286506f01f8ca64d6eb0e33bafb475a5cf10ff37</strong></p>
<p>终于有了编译 kernel 的正确环境了（不是完整开发环境哈）。</p>
<p><strong><span style="color: #ff0000;">3、编译 kernel：</span></strong></p>
<p>Moto 提供的 kernel source 中有几个适合 Intel Medfield 平台的 config 文件，SourceForge 网站上推荐使用 i386_mfld_moto_defconfig，编译时指定 CROSS_COMPILE，但我实际编译之后的模块加载会 kernel panic。好吧，我来尝试应该是 Intel 原始推荐的 i386_mfld_defconfig 默认配置，无法编译通过，排除原因，发现 i386_mfld_defconfig 中启用的几个选项在 K800 中并没有开启，遂决定去掉，同时去掉了 Moto 特有的加密模块。</p>
<p>修改配置之后，能编译了，但编译到 android USB gadget 代码时又有报错，查看代码，发现 Moto 对 android USB gadget 代码做了特殊改动，好吧，这我暂时不需要修改，根据 Moto 增加的 define 修改 drivers/usb/gadget/android.c，去掉 Moto 特有的改动，尽量使代码默认 Intel 原生（看来联想对 Intel 的代码改动很少，这是个好处，嘿嘿，下面也有悲催的地方），再次开始编译。</p>
<p>这次终于比较顺利了，能编译到链接 kernel image 的地方了，但又有报错，这时就不管了，因为我压根就不指望这个编译出来的 zImage 能直接用在联想 K800 手机上，而且联想也没开放制作其 boot image 的工具和方法，就算 zImage 有了也不知道怎么刷到手机上。</p>
<p>接下来编译 kernel modules，这步比较顺利，我把 CIFS、USB Mass Storage（包括 scsi disk 支持）、usbnet、usb serial converter、tun 等需要的模块都选中，都正确编译出来了。</p>
<p><strong><span style="color: #ff0000;">4、修改调试：</span></strong></p>
<p>拿到手机上加载 cifs.ko，正常，/proc/filesystems 中已经有了 cifs，但挂载文件系统时发现 dmesg 里有 out of memory 报错，一会就 kernel panic 了。</p>
<p>强制重启手机，这时才发现 cifs.ko 大小有 3MB 多，明显太大，查看 config 发现默认启用了 debug kernel，Moto 的默认配置中未启用，不得不说联想真是够懒的，这个影响性能的东西竟然木有去掉。</p>
<p>本来想禁用 CONFIG_DEBUG_KERNEL，但无意发现手机里有 /proc/sched_debug 调度器调试文件，这个是依赖 CONFIG_DEBUG_KERNEL 的，说明 debug kernel 必须启用了。最后发现 i386_mfld_defconfig 中默认的 SLUB debug 等几个选项在联想 K800 kernel 中是关闭的，保存 config 重新编译。由于启用了 debug kernel，编译出来的模块不可避免的都很大，不得不用 <strong>strip --strip-unneeded *.ko</strong> 来去除没用的东西。</p>
<p>再次拷贝到手机上，insmod cifs.ko，正常，mount 挂载 Windows 共享目录终于不 panic 了，但用户验证失败，看 dmesg 发现 kernel 缺少 md4 支持，将 md4 模块也编译拷到手机上开始测试：</p>
<p><strong>insmod md4.ko</strong><br />
<strong>insmod cifs.ko</strong><br />
<strong>mount -t cifs -o username=xxx,password=xxx //192.168.1.xxx/share /mnt</strong></p>
<p>挂载终于正常了。小激动人心，灰常不容易，总不辜负我 panic 了好几次的 K800 手机。话说每次 panic 都得强制抠电池再开机滴啊，555。</p>
<p>下面开始测试外接 U 盘（必须要有 USB OTG 线哦）：</p>
<p><strong>insmod scsi_mod.ko</strong><br />
<strong>insmod sd_mod.ko</strong><br />
<strong>insmod usb-storage.ko</strong></p>
<p>插上 U 盘，手机没任何反应，不过在 dmesg 里已经能看到上来的 sda 设备，运行 fdisk -l 命令可成功看到分区，看来只是手机系统没有做自动挂载外置 U 盘的处理（也正常，本来就不支持），自动挂载可以考虑装 StickMount 之类的软件哦。</p>
<p>使用 USB 转 串口（和实际芯片有关）：</p>
<p><strong>insmod usbserial.ko</strong><br />
<strong>insmod pl2303.ko</strong></p>
<p>使用 USB 有线网卡（和实际芯片有关）：</p>
<p><strong>insmod usbnet.ko</strong><br />
<strong>insmod asix.ko</strong></p>
<p><strong><span style="color: #ff0000;">5、总结：</span></strong></p>
<p>到这地步对我来说已经是颇有进展了，我暂时只看重 U 盘支持这个模块，嘿嘿。其它东西等有关时再来折腾了。</p>
<p>下面是我放出的压缩包下载链接：</p>
<p><a href="http://miseal.googlecode.com/files/k800-kernel-config-modules.7z" target="_blank">http://miseal.googlecode.com/files/k800-kernel-config-modules.7z</a></p>
<p>里面包含我现在编译 kernel 使用的 config 和编译出来的一些有用的 kernel modules，不想自己编译的哥们就自行使用，由于这根本不是官方 kernel，我不对任何导致你的 K800 手机 panic 挂掉的后果承担责任，哈哈。</p>
]]></content:encoded>
			<wfw:commentRss>https://zohead.com/archives/k800-kernel-otg-udisk/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>密码保护：Linux kernel dm-log-userspace介绍及使用</title>
		<link>https://zohead.com/archives/dm-log-userspace/</link>
		<comments>https://zohead.com/archives/dm-log-userspace/#comments</comments>
		<pubDate>Sat, 27 Oct 2012 15:23:37 +0000</pubDate>
		<dc:creator><![CDATA[Uranus Zhou]]></dc:creator>
				<category><![CDATA[Device mapper]]></category>
		<category><![CDATA[kernel]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[cmirrord]]></category>
		<category><![CDATA[connector]]></category>
		<category><![CDATA[dm-log-userspace]]></category>
		<category><![CDATA[dm-mirror]]></category>
		<category><![CDATA[netlink]]></category>
		<category><![CDATA[同步]]></category>

		<guid isPermaLink="false">http://zohead.com/?p=329</guid>
		<description><![CDATA[无法提供摘要。这是一篇受保护的文章。]]></description>
				<content:encoded><![CDATA[<form action="https://zohead.com/wp-login-zohead.php?action=postpass" class="post-password-form" method="post">
<p>这是一篇受密码保护的文章，您需要提供访问密码：</p>
<p><label for="pwbox-329">密码： <input name="post_password" id="pwbox-329" type="password" size="20" /></label> <input type="submit" name="Submit" value="提交" /></p>
</p></form>
]]></content:encoded>
			<wfw:commentRss>https://zohead.com/archives/dm-log-userspace/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>使用Linux kernel dm-mirror实现设备间同步</title>
		<link>https://zohead.com/archives/dm-mirror-sync-device/</link>
		<comments>https://zohead.com/archives/dm-mirror-sync-device/#comments</comments>
		<pubDate>Thu, 11 Oct 2012 02:41:42 +0000</pubDate>
		<dc:creator><![CDATA[Uranus Zhou]]></dc:creator>
				<category><![CDATA[Device mapper]]></category>
		<category><![CDATA[kernel]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[DM]]></category>
		<category><![CDATA[dm-log]]></category>
		<category><![CDATA[dm-mirror]]></category>
		<category><![CDATA[dmsetup]]></category>
		<category><![CDATA[DRBD]]></category>
		<category><![CDATA[kcopyd]]></category>
		<category><![CDATA[loop]]></category>
		<category><![CDATA[SAN]]></category>
		<category><![CDATA[同步]]></category>

		<guid isPermaLink="false">http://zohead.com/?p=311</guid>
		<description><![CDATA[本文同步自（最佳显示效果请点击）：https://zohead.com/archives/dm-mirror-sync-device/ 在某些场合下，用户需要在 Linux 系统中实现直接的块设备同步方式，需要将一个裸设备中的内容完全同步到另一个裸设备，有时甚至需要能自定义位移和大小进行同步，这时 Linux 自带的 dm-mirror 模块很可能是比较好的实现方案。 dm-mirror 是 Linux kernel 中 device-mapper（DM）模块（device-mapper 内部称为 target）中的一个，可以实现多个块设备间的数据同步，并支持通过 dm-log 模块保存同步时 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>本文同步自（最佳显示效果请点击）：<a href="https://zohead.com/archives/dm-mirror-sync-device/" target="_blank">https://zohead.com/archives/dm-mirror-sync-device/</a></p>
<p>在某些场合下，用户需要在 Linux 系统中实现直接的块设备同步方式，需要将一个裸设备中的内容完全同步到另一个裸设备，有时甚至需要能自定义位移和大小进行同步，这时 Linux 自带的 dm-mirror 模块很可能是比较好的实现方案。</p>
<p>dm-mirror 是 Linux kernel 中 device-mapper（DM）模块（device-mapper 内部称为 target）中的一个，可以实现多个块设备间的数据同步，并支持通过 dm-log 模块保存同步时的元数据信息，方便在关机和重启之后能够继续之前的进度进行同步，而且 dm-mirror 的元数据可以选择保存在内存中或者固定的块设备中。LVM 逻辑卷管理中的 pvmove 命令可以在卷组中替换物理卷，pvmove 命令正是基于 dm-mirror 模块实现的。Linux kernel 中还包含了其它的一些 device-mapper target 模块，例如 dm-linear（用于实现 LVM 逻辑卷管理）、dm-crypt（加密数据）、dm-snapshot（用于实现即时快照）等。</p>
<p>dm-mirror 的主要实现代码在 Linux kernel 代码树的 drivers/md/dm-raid1.c 中，dm-mirror 的日志元数据记录功能通过 dm-log 模块实现，同步的区块划分由 dm-region-hash 模块实现，底层的同步实现则由 kcopyd 来实现。kcopyd 的功能就是从一个块设备拷贝一定扇区的数据到另一个或多个块设备，kcopyd 支持异步的完成通知功能，目前主要被 dm-snapshot 和 dm-mirror 模块使用。有关 Linux kernel 中 kcopyd 的说明请参考这里：<a href="http://www.kernel.org/doc/Documentation/device-mapper/kcopyd.txt" target="_blank">http://www.kernel.org/doc/Documentation/device-mapper/kcopyd.txt</a>。</p>
<p>dm-mirror 设备的装载通过 dmsetup 命令来实现，以下说明的地址都是以扇区为单位（固定为 512 个字节），先看看 dm-mirror target 的 table 格式：</p>
<p><strong>start length mirror log_type #logargs logarg1 ... logargN #devs device1 offset1 ... deviceN offsetN [#features &lt;features&gt;]</strong></p>
<p>对每个值分别说明如下：</p>
<ul>
<li>start 为虚拟设备起始扇区地址，一般固定为 0</li>
<li>length 为 dm-mirror 设备的大小，也就是同步的总扇区大小</li>
<li>mirror 值固定，表示这是一个 dm-mirror 设备</li>
<li>log_type 指定日志元数据类型，常用的是 core 和 disk 两种类型</li>
<li>#logargs 表示后面的 logarg1 ... logargN 一共有多少个</li>
<li>#devs 表示需要同步的设备个数，每个设备都有一个 device 值和一个 offset 值</li>
<li>deviceN offsetN 为每个需要同步的设备的设备路径（或者设备号）和偏移地址</li>
<li>#features 和 features 为可选的值，#features 表示可选项个数</li>
<li>如果指定了 #features，则必须为 1，且 features 必须为 handle_errors（表示 dm-mirror 会自动进行错误处理，即同步出错时自动停止同步并删除 dm-mirror 虚拟设备）</li>
</ul>
<p>然后是 core 和 disk 两种日志元数据类型的介绍（另外有 clustered_core 和 clustered_disk 两种适用于集群的日志类型，有兴趣可以自己去了解下哦）：</p>
<ul>
<li>core 类型（内存）：<br />
日志保存在内存中，关机或者重启之后会丢失，因此安全性较差，但由于元数据存放在内存中，性能相对 disk 类型来说是非常好的。#logargs 个数为 1-2 个，日志参数格式为：<br />
<strong>regionsize [[no]sync]</strong>regionsize 为日志区块的大小（512 个字节的扇区为单位），可选的 sync 和 nosync 用于指定 dm-mirror 是否已经同步过。</li>
<li>disk 类型（磁盘）：<br />
日志保存在磁盘（块设备）中，因此可以在关机或重启之后继续之前的同步进度，当然性能比 core 类型肯定是要差一些的。#logargs 个数为 2-3 个，日志参数格式为：<br />
<strong>logdevice regionsize [[no]sync]</strong>logdevice 指定日志元数据存放在哪个块设备上，可以使用设备路径或者主从设备号形式，其它参数与 core 类型相同。</li>
</ul>
<p>Linux 系统中 dm-mirror 具体使用步骤举例如下：</p>
<ol>
<li>首先加载 dm-mirror 模块：<br />
<strong>modprobe dm-mirror</strong></li>
<li> 准备好需要同步的设备，假设是实际应用中的一种常见需求：Linux 系统盘为 /dev/sda，系统中另外有个数据盘 /dev/sdb。但由于磁盘 /dev/sdb 寿命快到了，需要将 /dev/sdb 磁盘上的数据同步到 /dev/sdc 上，/dev/sdc 的容量比 /dev/sdb 要大。<br/><br/>先得到 /dev/sdb 和 /dev/sdc 的容量大小（以 512 个字节的扇区为单位）：<br />
<strong>blockdev --getsz /dev/sdb</strong><br />
<strong>blockdev --getsz /dev/sdc</strong><br/></br>假设分别为 <strong>209715200</strong>（100G） 和 <strong>314572800</strong>（150G）。</li>
<li>在系统中通过文件方式产生 loop 设备用作 dm-mirror 同步存放日志元数据的设备，防止关机或重启之后同步进度丢失，1MB 的文件已完全足够保存日志元数据：<br/><br/><strong>dd if=/dev/zero of=meta.dat bs=1024k count=1</strong><br/>运行完成将产生一个 1MB 大小的 meta.dat 文件。</li>
<li>准备 loop 设备：<br/><br/><strong>losetup -f</strong><br />
得到空闲的 loop 设备名，假设为 <strong>/dev/loop0</strong>；<br/><br/><strong>losetup /dev/loop0 meta.dat</strong><br />
装载 loop 设备。</li>
<li>运行 dmsetup create 命令创建 dm-mirror 设备进行同步：<br/><br/><strong>echo "<span style="color: #008000;">0 209715200 mirror disk 2 /dev/loop0 16384 2 /dev/sdb 0 /dev/sdc 0 1 handle_errors</span>" | dmsetup create mirror0</strong><br/><br/>运行成功之后将产生名称为 mirror0 的虚拟 dm-mirror 设备。<br/><br/>echo 中间的字符串即为 dm-mirror 的 table 格式：209715200 为同步的大小，disk 指定元数据保存在磁盘中，/dev/loop0 为元数据设备，16384 为区块大小（这里指定为 8MB 为提高同步性能），后面的参数指定将 /dev/sdb（源设备，起始地址为 0）的数据同步到 /dev/sdc（目标设备，起始地址为 0），1 和 handle_errors 表示不忽略同步错误。</li>
<li>查询同步状态和进度：<br/><br/><strong>dmsetup status mirror0</strong><br/><br/>输出类似下面：<br/><br/><strong><span style="color: #008000;">mirror0: 0 209715200 mirror 2 8:16 8:32 417/12800 1 AA 3 disk 7:0 A</span></strong><br/><br/>8:16 和 8:32 为 /dev/sdb 和 /dev/sdc 的设备号，209715200 个扇区的数据以 16384 个扇区为单位可得到需要划分为 12800 个区块，现在已经同步了 417 个区块，AA 表示两个要同步的设备都正常，7:0 为日志元数据设备 /dev/loop0 的设备号。</li>
<li>定期运行 <strong>dmsetup status mirror0</strong> 查看进度，同步完成时，进步部分将显示为：12800/12800，表示所有区块都已经同步好了；</li>
<li>删除没有用了的 dm-mirror 设备：<br />
<strong>dmsetup remove mirror0</strong></li>
<li>删除没有用了的 loop 设备：<br />
<strong>losetup -d /dev/loop0</strong></li>
<li type="_moz">至此两块磁盘间的同步操作已经完成，在此过程中间即使有非正常的重启或者关机操作，也只需要在重新启动之后，再运行第 4 和 第 5 步就可以继续重启之前的进度进行同步。</li>
</ol>
<p>从上面的例子可以看出 dm-mirror 在 Linux 系统中还是很有用处的。实际上上面的例子中在同步完成之后就把 dm-mirror 设备删除了，如果不删除的话，是可以直接继续对 dm-mirror 设备（上面例子中的 dm-mirror 设备的实际路径为：/dev/mapper/mirror0）进行读写的，dm-mirror 设备在写时会自动将下面的设备数据进行同步，这样实际上就是类似 RAID1 磁盘阵列的效果了。</p>
<p>另外一种比较典型的应用是利用 dm-mirror 实现两个 SAN 网络设备间的同步，这看起来比较类似于 DRBD 的功能，但在实现上远比 DRBD 要简单和透明的多。可以实现单独的服务器分别连接两个不同的 SAN target（光纤、Infiniband 或者 iSCSI 都可以），得到两个不同的 SCSI 设备，然后就可以使用 dm-mirror 创建新的虚拟设备，在这个新的虚拟设备上的读写操作会在 Linux kernel 底层自动同步到对应的两个 SAN 设备中。</p>
<p>由于 dm-mirror 没有比较正式的官方文档，以上为个人参考 Linux kernel 源码和相关说明总结出来的，其中有任何问题欢迎提出指正，玩的开心 ^_^</p>
]]></content:encoded>
			<wfw:commentRss>https://zohead.com/archives/dm-mirror-sync-device/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Linux kernel学习-进程地址空间</title>
		<link>https://zohead.com/archives/linux-kernel-learning-process-address-space/</link>
		<comments>https://zohead.com/archives/linux-kernel-learning-process-address-space/#comments</comments>
		<pubDate>Fri, 06 Jul 2012 19:12:14 +0000</pubDate>
		<dc:creator><![CDATA[Uranus Zhou]]></dc:creator>
				<category><![CDATA[kernel]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[代码分析]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[brk]]></category>
		<category><![CDATA[malloc]]></category>
		<category><![CDATA[mmap]]></category>
		<category><![CDATA[mm_struct]]></category>
		<category><![CDATA[VMA]]></category>
		<category><![CDATA[内存]]></category>
		<category><![CDATA[地址空间]]></category>
		<category><![CDATA[线程]]></category>
		<category><![CDATA[进程]]></category>
		<category><![CDATA[页表]]></category>

		<guid isPermaLink="false">http://zohead.com/?p=266</guid>
		<description><![CDATA[本文同步自（如浏览不正常请点击跳转）：https://zohead.com/archives/linux-kernel-learning-process-address-space/ 看完 Linux kernel block I/O 层之后来到进程地址空间管理部分，本文中的很多知识和之前的 [进程基本]、[进程调度]、[内存管理] 等章节的知识相关。 1、基础知识： Linux kernel 给每个进程提供的进程地址空间一般是 32 位或 64 位（硬件相关）的平坦地址空间，但进程是没有权限访问这段地址空间中的所有地址的，能访问的一般是很多的内存地址区间。这种内存地址区间被称为内存区域，进程 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>本文同步自（如浏览不正常请点击跳转）：<a href="https://zohead.com/archives/linux-kernel-learning-process-address-space/" target="_blank">https://zohead.com/archives/linux-kernel-learning-process-address-space/</a></p>
<p>看完 Linux kernel block I/O 层之后来到进程地址空间管理部分，本文中的很多知识和之前的 [<a href="https://zohead.com/archives/linux-kernel-learning-process/" target="_blank">进程基本</a>]、[<a href="https://zohead.com/archives/linux-kernel-learning-process-scheduling/" target="_blank">进程调度</a>]、[<a href="https://zohead.com/archives/linux-kernel-learning-memory-management/" target="_blank">内存管理</a>] 等章节的知识相关。</p>
<p><strong><span style="color: #ff0000;">1、基础知识：</span></strong></p>
<p>Linux kernel 给每个进程提供的进程地址空间一般是 32 位或 64 位（硬件相关）的平坦地址空间，但进程是没有权限访问这段地址空间中的所有地址的，能访问的一般是很多的内存地址区间。这种内存地址区间被称为内存区域，进程可以动态添加和删除内存区域到它的地址空间中。内存区域可以有不同的权限，相关进程必须遵守这些权限，例如可读、可写、可执行等。如果进程访问的地址不在一个有效的内存区域中，或者访问时的权限不正确，kernel 将会杀掉进程并给出常见的 "Segmentation Fault" 段错误日志。</p>
<p>内存区域通常包括：</p>
<ul>
<li>可执行文件的代码段，称为 text 段；</li>
<li>可执行文件的已初始化全局变量段，称为 data 段；</li>
<li>未初始化全局变量段（通常以 0 page 填充），称为 bss 段；</li>
<li>进程的用户空间栈（通常以 0 page 填充）；</li>
<li>每个共享库文件的额外 text、data、bss 段，也被装入进程的地址空间；</li>
<li>内存映射文件；</li>
<li>共享内存区域；</li>
<li>匿名内存映射（新版本的 malloc 函数就除了 brk 之外也通过 mmap 实现）；</li>
<li>应用程序中的堆</li>
</ul>
<p><strong><span style="color: #ff0000;">2、内存描述符：</span></strong></p>
<p>kernel 使用 mm_struct 内存描述符结构来表示进程的地址空间信息，它定义在 &lt;linux/mm_types.h&gt; 头文件中，这也是一个非常大的结构。</p>
<pre class="brush: cpp; title: &lt;linux/mm_types.h&gt;; notranslate">
struct vm_area_struct {
	struct mm_struct * vm_mm;	/* The address space we belong to. */
	unsigned long vm_start;		/* Our start address within vm_mm. */
	unsigned long vm_end;		/* The first byte after our end address
					   within vm_mm. */

	/* linked list of VM areas per task, sorted by address */
	struct vm_area_struct *vm_next;

	pgprot_t vm_page_prot;		/* Access permissions of this VMA. */
	unsigned long vm_flags;		/* Flags, see mm.h. */

	struct rb_node vm_rb;

	/*
	 * For areas with an address space and backing store,
	 * linkage into the address_space-&gt;i_mmap prio tree, or
	 * linkage to the list of like vmas hanging off its node, or
	 * linkage of vma in the address_space-&gt;i_mmap_nonlinear list.
	 */
	union {
		struct {
			struct list_head list;
			void *parent;	/* aligns with prio_tree_node parent */
			struct vm_area_struct *head;
		} vm_set;

		struct raw_prio_tree_node prio_tree_node;
	} shared;

	/*
	 * A file's MAP_PRIVATE vma can be in both i_mmap tree and anon_vma
	 * list, after a COW of one of the file pages.	A MAP_SHARED vma
	 * can only be in the i_mmap tree.  An anonymous MAP_PRIVATE, stack
	 * or brk vma (with NULL file) can only be in an anon_vma list.
	 */
	struct list_head anon_vma_chain; /* Serialized by mmap_sem &amp;
					  * page_table_lock */
	struct anon_vma *anon_vma;	/* Serialized by page_table_lock */

	/* Function pointers to deal with this struct. */
	const struct vm_operations_struct *vm_ops;

	/* Information about our backing store: */
	unsigned long vm_pgoff;		/* Offset (within vm_file) in PAGE_SIZE
					   units, *not* PAGE_CACHE_SIZE */
	struct file * vm_file;		/* File we map to (can be NULL). */
	void * vm_private_data;		/* was vm_pte (shared mem) */
	unsigned long vm_truncate_count;/* truncate_count or restart_addr */

#ifndef CONFIG_MMU
	struct vm_region *vm_region;	/* NOMMU mapping region */
#endif
#ifdef CONFIG_NUMA
	struct mempolicy *vm_policy;	/* NUMA policy for the VMA */
#endif
};

struct mm_struct {
	struct vm_area_struct * mmap;		/* list of VMAs */
	struct rb_root mm_rb;
	struct vm_area_struct * mmap_cache;	/* last find_vma result */
#ifdef CONFIG_MMU
	unsigned long (*get_unmapped_area) (struct file *filp,
				unsigned long addr, unsigned long len,
				unsigned long pgoff, unsigned long flags);
	void (*unmap_area) (struct mm_struct *mm, unsigned long addr);
#endif
	unsigned long mmap_base;		/* base of mmap area */
	unsigned long task_size;		/* size of task vm space */
	unsigned long cached_hole_size; 	/* if non-zero, the largest hole below free_area_cache */
	unsigned long free_area_cache;		/* first hole of size cached_hole_size or larger */
	pgd_t * pgd;
	atomic_t mm_users;			/* How many users with user space? */
	atomic_t mm_count;			/* How many references to &quot;struct mm_struct&quot; (users count as 1) */
	int map_count;				/* number of VMAs */
	struct rw_semaphore mmap_sem;
	spinlock_t page_table_lock;		/* Protects page tables and some counters */

	struct list_head mmlist;		/* List of maybe swapped mm's.	These are globally strung
						 * together off init_mm.mmlist, and are protected
						 * by mmlist_lock
						 */

	unsigned long hiwater_rss;	/* High-watermark of RSS usage */
	unsigned long hiwater_vm;	/* High-water virtual memory usage */

	unsigned long total_vm, locked_vm, shared_vm, exec_vm;
	unsigned long stack_vm, reserved_vm, def_flags, nr_ptes;
	unsigned long start_code, end_code, start_data, end_data;
	unsigned long start_brk, brk, start_stack;
	unsigned long arg_start, arg_end, env_start, env_end;

	unsigned long saved_auxv[AT_VECTOR_SIZE]; /* for /proc/PID/auxv */

	/*
	 * Special counters, in some configurations protected by the
	 * page_table_lock, in other configurations by being atomic.
	 */
	struct mm_rss_stat rss_stat;

	struct linux_binfmt *binfmt;

	cpumask_t cpu_vm_mask;

	/* Architecture-specific MM context */
	mm_context_t context;

	/* Swap token stuff */
	/*
	 * Last value of global fault stamp as seen by this process.
	 * In other words, this value gives an indication of how long
	 * it has been since this task got the token.
	 * Look at mm/thrash.c
	 */
	unsigned int faultstamp;
	unsigned int token_priority;
	unsigned int last_interval;

	unsigned long flags; /* Must use atomic bitops to access the bits */

	struct core_state *core_state; /* coredumping support */
#ifdef CONFIG_AIO
	spinlock_t		ioctx_lock;
	struct hlist_head	ioctx_list;
#endif
#ifdef CONFIG_MM_OWNER
	/*
	 * &quot;owner&quot; points to a task that is regarded as the canonical
	 * user/owner of this mm. All of the following must be true in
	 * order for it to be changed:
	 *
	 * current == mm-&gt;owner
	 * current-&gt;mm != mm
	 * new_owner-&gt;mm == mm
	 * new_owner-&gt;alloc_lock is held
	 */
	struct task_struct *owner;
#endif

#ifdef CONFIG_PROC_FS
	/* store ref to file /proc/&lt;pid&gt;/exe symlink points to */
	struct file *exe_file;
	unsigned long num_exe_file_vmas;
#endif
#ifdef CONFIG_MMU_NOTIFIER
	struct mmu_notifier_mm *mmu_notifier_mm;
#endif
};
</pre>
<p>结构的注释中已经包含比较多的注解了哦。mmap 为地址空间的内存区域（用 vm_area_struct 结构来表示啦，也是上面的代码中）链表，mm_rb 则将其以红黑树的形式进行存储，链表形式方便遍历，红黑树形式方便查找。mm_users 为以原子变量形式保护的使用此地址空间的进程数量值（例如：如果有 4 个线程共享此地址空间，则 mm_users 值为 4），mm_count 为引用计数（所有 mm_users 等于一个引用计数），当 mm_count 值为 0 时表示没有再被使用，可以被释放。total_vm 成员表示所有内存区域的数量。</p>
<p>所有的 mm_struct 结构以链表的形式存在 mm_struct 的 mmlist 成员中，该链表的第一个成员就是 init 进程的 mm_struct ：init_mm，该链表被 mmlist_lock 锁保护。</p>
<p>进程的内存描述符是在 task_struct 的 mm 成员中的。fork() 进行创建进程时调用 copy_mm 函数将父进程的内存描述符拷贝给子进程，调用 clone() 函数时如果指定 CLONE_VM 参数将使父进程和子进程地址空间共享（实际上将 mm_users 计数加 1），这种子进程就被称为线程。mm_struct 结构一般是通过 alloc_mm 宏从名为 mm_cachep 的 Slab cache 中分配。</p>
<p>进程退出时调用 exit_mm 函数，该函数再调用 mmput() 函数，此函数中减小地址空间的 mm_users 计数，如果 mm_users 变为 0，调用 mmdrop() 函数减小 mm_count 计数，如果 mm_count 变为 0，则最终调用 free_mm() 宏来释放内存描述符（回归到 Slab cache 中）。</p>
<p>另外需要说明的是 kernel 线程是没有地址空间，也就没有对应的 mm_struct（值为 NULL），kernel 线程使用之前运行的进程的内存描述符，有关 kernel 线程请参考之前的 [<a href="https://zohead.com/archives/linux-kernel-learning-process/" target="_blank">进程基本</a>] 文章。</p>
<p><strong><span style="color: #ff0000;">3、VMA 概念：</span></strong></p>
<p>vm_area_struct 结构即内存区域常被称为虚拟内存区域（简写为 VMA），表示的是在一个地址空间中的一个连续内存地址区间，每个内存区域是一个惟一的对象。vm_area_struct 中的 vm_mm 成员指向关联的内存描述符，vm_ops 成员为非常重要的关联的操作函数结构，vm_start 为起始地址，vm_end 为结束地址之后第一个字节的地址，即地址范围为：[vm_start, vm_end)。每个 VMA 对于它关联的内存描述符来说是惟一的，因此如果两个单独的进程映射相同的文件到各自的地址空间，它们的 VMA 也是不同的。</p>
<p>VMA 中的 vm_flags 表示内存区域中的页的行为状态，常见的状态有：VM_READ（页可读）、VM_WRITE（页可写）、VM_EXEC（页可被执行）、VM_SHARED（页被共享，被设置了称为共享映射，未设置称为私有映射）、VM_SHM（此区域被用作共享内存）、VM_LOCKED（页被锁）、VM_IO（此区域用于映射设备 I/O 空间）、VM_RESERVED（表示内存区域不可被交换出去）、VM_SEQ_READ（连续读，增强 readahead）、VM_RAND_READ（随机读，减弱 readahead）等。VM_SEQ_READ 和 VM_RAND_READ 标志可以通过 madvise() 系统调用来设置。</p>
<p>看看 vm_ops 操作函数结构的 vm_operations_struct 的定义，它在 &lt;linux/mm.h&gt; 头文件中：</p>
<pre class="brush: cpp; title: &lt;linux/mm.h&gt;; notranslate">
struct vm_operations_struct {
	void (*open)(struct vm_area_struct * area);
	void (*close)(struct vm_area_struct * area);
	int (*fault)(struct vm_area_struct *vma, struct vm_fault *vmf);

	/* notification that a previously read-only page is about to become
	 * writable, if an error is returned it will cause a SIGBUS */
	int (*page_mkwrite)(struct vm_area_struct *vma, struct vm_fault *vmf);

	/* called by access_process_vm when get_user_pages() fails, typically
	 * for use by special VMAs that can switch between memory and hardware
	 */
	int (*access)(struct vm_area_struct *vma, unsigned long addr,
		      void *buf, int len, int write);
#ifdef CONFIG_NUMA
	/*
	 * set_policy() op must add a reference to any non-NULL @new mempolicy
	 * to hold the policy upon return.  Caller should pass NULL @new to
	 * remove a policy and fall back to surrounding context--i.e. do not
	 * install a MPOL_DEFAULT policy, nor the task or system default
	 * mempolicy.
	 */
	int (*set_policy)(struct vm_area_struct *vma, struct mempolicy *new);

	/*
	 * get_policy() op must add reference [mpol_get()] to any policy at
	 * (vma,addr) marked as MPOL_SHARED.  The shared policy infrastructure
	 * in mm/mempolicy.c will do this automatically.
	 * get_policy() must NOT add a ref if the policy at (vma,addr) is not
	 * marked as MPOL_SHARED. vma policies are protected by the mmap_sem.
	 * If no [shared/vma] mempolicy exists at the addr, get_policy() op
	 * must return NULL--i.e., do not &quot;fallback&quot; to task or system default
	 * policy.
	 */
	struct mempolicy *(*get_policy)(struct vm_area_struct *vma,
					unsigned long addr);
	int (*migrate)(struct vm_area_struct *vma, const nodemask_t *from,
		const nodemask_t *to, unsigned long flags);
#endif
};
</pre>
<p>当指定的内存区域被添加到地址空间时，open 函数被调用，反之移除时 close 函数被调用。如果一个不在内存中的页被访问，将触发缺页异常， fault 函数被缺页异常处理函数调用。当一个只读的页变为可写的时候，page_mkwrite 函数也被缺页异常处理函数调用。</p>
<p>mm_struct 中的 mmap 为内存区域链表，通过 VMA 的 vm_next 成员指向下一个内存区域，而且链表中的内存区域是按地址上升排序的，链表中最后一个 VMA 值为 NULL。而对于 mm_struct 的 mm_rb 红黑树，mm_rb 为红黑树的根，每个 VMA 通过其 vm_rb 红黑树节点类型链到红黑树中。</p>
<p>在应用层中可以通过 cat /proc/&lt;pid&gt;/maps 或者 pmap 程序等方法查看应用程序的内存区域列表。</p>
<p><strong>操作 VMA：</strong></p>
<p>kernel 提供 find_vma() 函数用于查找指定的内存地址在哪个 VMA 上，它的实现在 mm/mmap.c 文件中，输入参数为内存描述符和内存地址：</p>
<pre class="brush: cpp; title: mm/mmap.c; notranslate">
struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
{
	struct vm_area_struct *vma = NULL;

	if (mm) {
		/* Check the cache first. */
		/* (Cache hit rate is typically around 35%.) */
		vma = mm-&gt;mmap_cache;
		if (!(vma &amp;&amp; vma-&gt;vm_end &gt; addr &amp;&amp; vma-&gt;vm_start &lt;= addr)) {
			struct rb_node * rb_node;

			rb_node = mm-&gt;mm_rb.rb_node;
			vma = NULL;

			while (rb_node) {
				struct vm_area_struct * vma_tmp;

				vma_tmp = rb_entry(rb_node,
						struct vm_area_struct, vm_rb);

				if (vma_tmp-&gt;vm_end &gt; addr) {
					vma = vma_tmp;
					if (vma_tmp-&gt;vm_start &lt;= addr)
						break;
					rb_node = rb_node-&gt;rb_left;
				} else
					rb_node = rb_node-&gt;rb_right;
			}
			if (vma)
				mm-&gt;mmap_cache = vma;
		}
	}
	return vma;
}
</pre>
<p>如果找不到对应的 VMA 则返回 NULL。需要注意的是返回的 VMA 的开始地址可能比指定的内存地址大。find_vma() 函数返回的结果会被缓存到内存描述符的 mmap_cache 成员中用于提高之后的查找性能，因为后续的操作很可能还是在同样的 VMA 上。如果在 mmap_cache 中找不到则通过红黑树进行查找。</p>
<p>find_vma_prev() 函数与 find_vma() 函数类似，不过它也会返回指定地址之前的最后一个 VMA：</p>
<p><span style="color: #008000;">struct vm_area_struct * find_vma_prev(struct mm_struct *mm, unsigned long addr,<br />
struct vm_area_struct **pprev)</span></p>
<p>kernel 另外还提供了 find_vma_intersection() 函数返回符合 find_vma() 的条件并且其开始地址不在指定内存结束地址之后的 VMA。</p>
<p><strong><span style="color: #ff0000;">4、mmap 和 munmap：</span></strong></p>
<p>kernel 提供 do_mmap() 函数创建新的线性地址区间，这是用户层 mmap() 函数的底层实现，它用于将一段地址区间添加到进程的地址空间中。</p>
<p><span style="color: #008000;">unsigned long do_mmap(struct file *file, unsigned long addr, </span><span style="color: #008000;">unsigned long len,<br />
unsigned long prot, </span><span style="color: #008000;">unsigned long flag, unsigned long offset)</span></p>
<p>do_mmap 映射 file 参数指定的文件，并最终返回新创建的地址区间的初始地址。</p>
<p>offset 和 len 指定偏移量和长度。如果 file 为 NULL 并且 offset 为 0 则表示该映射后端不是基于文件的，这种映射被称为匿名映射，否则被称为基于文件的映射。prot 参数指定内存区域中页的访问权限，值可以为：PROT_READ（对应 VM_READ）、PROT_WRITE、PROT_EXEC、PROT_NONE 等。flag 指定 VMA 的其它标志，常用的有：MAP_SHARED（此映射可被共享）、MAP_PRIVATE（私有不可共享）、MAP_ANONYMOUS（指定匿名映射）、MAP_LOCKED 等。</p>
<p>如果可能的话，do_mmap 返回的内存区间会尽量和已有邻近的 VMA 合并（调整 VMA 大小），否则就创建一个新的 VMA。新的 VMA 从名为 vm_area_cachep 的 Slab cache 中分配，并通过 vma_link() 函数被加入到进程地址空间的链表和红黑树中，对应的 mm_struct 的 total_vm 成员也被更新。</p>
<p>do_mmap 是调用 do_mmap_pgoff() 函数完成真正的映射操作的。现在用户层使用的 mmap() 函数实际上是在用户层调用 mmap2() 系统调用并最终通过 do_mmap 来实现的。</p>
<p>do_munmap 用于从地址空间移除指定的地址区间：</p>
<p><span style="color: #008000;">int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)</span></p>
<p>do_munmap 导出给用户层就是 munmap() 函数了。</p>
<p><strong><span style="color: #ff0000;">5、页表及应用程序 VMA：</span></strong></p>
<p>Linux kernel 使用页式内存管理，应用程序给出的内存地址是虚拟地址，它需要经过若干级页表一级一级的变换，才变成真正的物理地址。有关 Linux 的分级页表结构等相关的知识请参考之前的 [<a href="https://zohead.com/archives/linux-kernel-learning-memory-addressing/" target="_blank">内存寻址</a>] 文章。</p>
<p>每个进程有自己的 task_struct，task_struct 中的 mm 指向其内存描述符，每个 mm 又有自己单独的页表（进程中的线程会进行共享），本文最上面介绍的内存描述符 mm_struct 中的 pgd_t * pgd 就指向进程的 PGD，对页表的操作和遍历等操作也需要用到 mm_struct 中的 page_table_lock 自旋锁成员。</p>
<p>应用程序中对内存的操作例如 malloc 分配内存等一般是改变了某个 VMA，不会直接改变页表。假设用户分配了内存，然后访问这块内存，由于页表里面并没有记录相关的映射，CPU 产生一次缺页异常，内核捕捉到异常，检查产生异常的地址是不是存在于一个合法的 VMA 中，如果不是，则给进程一个 "Segmentation Fault" 段错误，使其崩溃；如果是，则分配一个物理页，并为之建立映射。</p>
<p>应用程序中的堆是一个一端固定、一端可伸缩的 VMA，其大小可以通过 brk 系统调用进行调整，libc 的 malloc 函数就是基于 brk 来实现的（如果需要分配的内存很大时，libc 会通过 mmap 系统调用映射一个新的 VMA 以节省对堆 VMA 的一系列调整操作）。应用程序的栈也是一个 VMA，只是它是一端固定、一端可伸不能缩的，而且它是自动伸展的。另外需要说明的是线程的栈 VMA 明显不是和其它线程共享的，一般是在线程创建时通过 mmap 创建新的 VMA 并以此作为线程的栈。</p>
<p>本文只是对 Linux kernel 的进程地址空间的基础涉及，其中有任何问题，欢迎提出指正哦，玩的开心~~~ ^_^</p>
]]></content:encoded>
			<wfw:commentRss>https://zohead.com/archives/linux-kernel-learning-process-address-space/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
