MySQL 调优基础(二) Linux内存管理

时间:2023-03-08 23:34:24
MySQL 调优基础(二) Linux内存管理

进程的运行,必须使用内存。下图是Linux中进程中的内存的分布图:

MySQL 调优基础(二) Linux内存管理

其中最重要的 heap segment 和 stack segment。其它内存段基本是大小固定的。注意stack是向低地址增长的,和heap相反。另外进程的内存地址从0开始,是因为使用的是虚拟内存。所以存在虚拟内存到物理内存的映射。目前服务器一般都是64位的,32位的已经极少了,32为对内存有极大限制。

1. Linux 虚拟内存

Linux是通过虚拟内存的方式来管理内存的。虚拟内存和物理内存之间存在映射关系。当进程在CPU上运行时,虚拟内存就会映射到物理内存,供CPU来访问。

applications do not allocate physical memory, but request a memory map of a certain size at the Linux kernel and in exchange receive a map in virtual memory. As you can see, virtual memory does not necessarily have to be mapped into physical memory. If your application allocates a large amount of memory, some of it might be mapped to the swap file on the disk subsystem.

图示 进程虚拟内存 = 进程物理内存 + 进程swap(page out):

MySQL 调优基础(二) Linux内存管理

上图是top命令的截图,可以看到:mysqld 使用的虚拟内存为 735M,而常驻物理内存为 430M,所以其余的305M被swap out了(实际上是延迟分配)。

VIRT:The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out.

RES: Resident size (kb)。The non-swapped physical memory a task is using(常驻内存).

Linux handles the memory resource far more efficiently. The default configuration of the virtual memory manager allocates all available free
memory space as disk cache. Hence it is not unusual to see productive Linux systems that boast gigabytes of memory but only have 20 MB of that memory free. In the same context, Linux also handles swap space very efficiently. Swap space being used does not indicate a memory bottleneck but proves how efficiently Linux handles system resources.

There is no need to be alarmed if you find the swap partition filled to 50%. The fact that swap space is being used does not indicate a memory bottleneck; instead it proves how efficiently Linux handles system resources.

可见,系统显示空闲的内存很少,并不表示真的存在内存瓶颈;swap分区被使用了,也不代表存在内存瓶颈。

内存的分配

Linux 管理内存是通过内存page为单位的,一般一个page为4K。Linux通过一个维持一个free内存的列表来管理和分配内存,并且维持内存的连续,防止内存碎片的产生。该系统被称为buddy system。内存的分配和管理全依靠buddy system.

内存的回收(page frame reclaiming)

当空闲内存不足时,就涉及到内存的回收。内存的回收有两种方式:回收用于缓存磁盘文件的 page cache(disk cache);swap out/page out 其它非活跃进程的内存;而且优先回收用于文件缓存的内存(disk cache):

When kswapd reclaims pages, it would rather shrink the page cache than page out (or swap out) the pages owned by processes.

然后会扫描内存的 active list 和 inactive list,根据LRU原则将active的page移到inactive,然后将inactive list中的page swap out.

active list 和 inactive list,可以用vmstat -a 查看到:

[root@localhost ~]# vmstat -a
procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu-----
r b swpd free inact active si so bi bo in cs us sy id wa st

kswapd: kernel swap daemon

内存的两大主要用处

The pages are used mainly for two purposes: page and process address space. The page cache is pages mapped to a file on disk. The
cache pages that belong to a process address space (called anonymous memory because it is not mapped to any files, and it has no name) are used for heap and stack.

一、disk cache(page cache, file cache);

二、进程使用(anonymous memory、heap 和 stack)

kswapd 处理swap in 和swap out; 而 pdflush 处理disk cache到磁盘的刷新。

2. 如何尽量避免swap对mysql的影响

控制系统kswapd在内核中有一个专门的参数:

[root@localhost ~]# cat /proc/sys/vm/swappiness

我们把 vm.swappiness = 0 设置好,就可以在内存不足时,尽量避免系统发生swap,而尽量去 flush disk cache. 但是最新的Linux内核修改了对vm.swappingness=0 的解释,如果设置成0,可能会发生00M,而将mysqld给kill掉。新内核(2.6.32-303.el6及以后)推荐的做法是:

1)尽量保证Linux操作系统还有足够的内存;

2)最新的内核,建议把vm.swappiness设置1

3)考虑设置 /proc/$(pidof -s mysqld)/oom_adj为较小的值来尽量避免MySQL由于内存不足而被关闭;

4)还可以在 mysqld 的配置文件 my.cnf 中[mysqld]段中加入 memlock=1 ,然后重启,避免mysqld发生swap,但是可能会被Linux oom kill掉.

具体参见:http://www.woqutech.com/?p=1397

3. 如何修改 oom_adj 值

查看mysqld的oom_ajd值:

[root@localhost ~]# cat /proc/`pidof -s mysqld`/oom_adj

[root@localhost ~]# cat /proc/$(pidof -s mysqld)/oom_adj

默认值为0. 当我们设置为-17时,对于该进程来说,就不会触发OOM机制,被杀掉。修改:

[root@localhost ~]# echo -17 > /proc/$(pidof mysqld)/oom_adj
[root@localhost ~]# cat /proc/$(pidof mysqld)/oom_adj
-

这里为什么是-17呢?这和Linux的实现有关系。在Linux内核中的oom.h文件中,可以看到下面的定义:

 /* /proc//oom_adj set to -17 protects from the oom-killer */

#define OOM_DISABLE (-17)

/* inclusive */

#define OOM_ADJUST_MIN (-16)

#define OOM_ADJUST_MAX 15 

这个oom_adj中的变量的范围为15到-16之间。越大越容易被kill。oom_score就是它计算出来的一个值,就是根据这个值来选择哪些进程被kill掉的。

总之,通过上面的分析可知,满足下面的条件后,就是启动OOM机制。

1) VM里面分配不出更多的page(注意linux kernel是延迟分配page策略,及用到的时候才alloc;所以malloc + memset才有效)。

2) 用户地址空间不足,这种情况在32bit机器上及user space超过了3GB,在64bit机器上不太可能发生。

具体参见:http://blog.chinaunix.net/uid-20788636-id-4308527.html

其实设置mysqld的oom_adj不是最好的选择,mysqld不会被kill,必然就会导致其它进程被kill掉;最好还是保障内存充足或者设置vm.swappiness=1比较好

4. 内存瓶颈的检测

Linux内存的瓶颈,主要在于查看是否有比较严重的 swap 的发生(swap out/page out)。其它空虚内存的大小,swap分区被使用都不能说明说明问题。

区分 swap out 和 page out:

Page out moves individual pages to swap space on the disk; swapping is a bigger operation that moves the entire address space of a process to swap space in one operation.(page out 是指将单独的page交换到磁盘,而swap out是指将整个进程的内存交换到磁盘)

使用 vmstat 从整个系统层面查看swap out

[root@localhost ~]# vmstat 2
procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st

其中的 swap si: 表示每秒 swap in; so:表示每秒swap out;

   Swap
si: Amount of memory swapped in from disk (/s).
so: Amount of memory swapped to disk (/s).

使用 sar -B 从整个系统层面查看page out

[root@localhost ~]# sar -B
Linux 2.6.-.el6.i686 (localhost.localdomain) // _i686_ ( CPU) :: AM LINUX RESTART :: AM pgpgin/s pgpgout/s fault/s majflt/s pgfree/s pgscank/s pgscand/s pgsteal/s %vmeff
:: AM 39.84 4.85 340.32 0.21 39.40 0.00 0.00 0.00 0.00
:: AM 0.06 2.76 10.69 0.00 3.21 0.00 0.00 0.00 0.00
:: AM 0.14 2.68 10.16 0.00 3.08 0.00 0.00 0.00 0.00
:: AM 69.58 13.07 154.16 0.01 47.29 0.00 0.00 0.00 0.00
:: AM 1.84 3.93 28.39 0.02 9.17 0.00 0.00 0.00 0.00
:: PM 0.00 3.20 19.70 0.00 10.87 0.00 0.00 0.00 0.00
:: PM 0.01 2.90 31.96 0.00 8.77 0.00 0.00 0.00 0.00
:: PM 0.06 3.06 40.04 0.00 10.98 0.00 0.00 0.00 0.00
:: PM 2.17 3.81 81.19 0.02 21.63 0.00 0.00 0.00 0.00
Average: 12.62 4.47 79.63 0.03 17.15 0.00 0.00 0.00 0.00 :: PM LINUX RESTART :: PM pgpgin/s pgpgout/s fault/s majflt/s pgfree/s pgscank/s pgscand/s pgsteal/s %vmeff
:: PM 6.22 3.99 93.05 0.04 22.89 0.00 0.00 0.00 0.00
Average: 6.22 3.99 93.05 0.04 22.89 0.00 0.00 0.00 0.00
[root@localhost ~]# sar -B 2 3
Linux 2.6.-.el6.i686 (localhost.localdomain) // _i686_ ( CPU) :: PM pgpgin/s pgpgout/s fault/s majflt/s pgfree/s pgscank/s pgscand/s pgsteal/s %vmeff
:: PM 0.00 0.00 26.63 0.00 30.15 0.00 0.00 0.00 0.00
:: PM 0.00 0.00 19.70 0.00 30.30 0.00 0.00 0.00 0.00
:: PM 0.00 0.00 15.00 0.00 30.00 0.00 0.00 0.00 0.00
Average: 0.00 0.00 20.44 0.00 30.15 0.00 0.00 0.00 0.00

sar -B 取的是从系统启动到目前的平均值;sar -B 2 3 是指每隔2秒取值,总共取值3次。输出字段的含义如下:

       -B     Report  paging  statistics. Some of the metrics below are available only with post 2.5
kernels. The following values are displayed: pgpgin/s
Total number of kilobytes the system paged in from disk per second. Note: With
old kernels (2.2.x) this value is a number of blocks per second (and not kilo-
bytes). pgpgout/s
Total number of kilobytes the system paged out to disk per second. Note: With
old kernels (2.2.x) this value is a number of blocks per second (and not kilo-
bytes). fault/s
Number of page faults (major + minor) made by the system per second. This is
not a count of page faults that generate I/O, because some page faults can be
resolved without I/O. majflt/s
Number of major faults the system has made per second, those which have
required loading a memory page from disk. pgfree/s
Number of pages placed on the free list by the system per second. pgscank/s
Number of pages scanned by the kswapd daemon per second. pgscand/s
Number of pages scanned directly per second. pgsteal/s
Number of pages the system has reclaimed from cache (pagecache and swapcache)
per second to satisfy its memory demands. %vmeff
Calculated as pgsteal / pgscan, this is a metric of the efficiency of page
reclaim. If it is near % then almost every page coming off the tail of the
inactive list is being reaped. If it gets too low (e.g. less than %) then the
virtual memory is having some difficulty. This field is displayed as zero if
no pages have been scanned during the interval of time.

pgpgout/s 表示就是每秒的page out 的KB数量。majflt/s 也是极为重要的指标,该指标涉及到虚拟内存的 page fault机制。

虚拟内存的 page fault机制

linux 使用虚拟内存层来映射物理地址空间,这种映射在某种意义上是说当一个进程开始运行,内核仅仅映射其需要的那部分,内核首先会搜索 CPU缓存和物理内存,如果没有找到内核则开始一次 MPF, 一次 MPF 即是一次对磁盘子系统的请求,它将数据页从磁盘和缓存读入 RAM。一旦内存页被映射到高速缓冲区,内核便会试图使用这些页,被称作 MnPF,MnPF 通过重复使用内存页而缩短了内核时间。

文件缓冲区(disk cache)可使内核减少对 MPFs 和 MnPFs 的使用, 随着系统不断地 IO 操作, 缓冲区会随之增大, 直至内存空闲空间不足并开始回收.

使用 free 查看空闲内存

[root@localhost ~]# free
total used free shared buffers cached
Mem:
-/+ buffers/cache:
Swap:
[root@localhost ~]# free -m
total used free shared buffers cached
Mem:
-/+ buffers/cache:
Swap:

1g的内存,1g的swap分区,使用了616M,空闲390M; swap分区没有被使用,全部空闲。

其实free内存很小不能说明问题,但是free比较大,却能说明内存充足。

swap如果大部分被使用,或者全部使用也能说明 swap 严重,当然最好结合 vmstat 来综合考虑。

使用  ps -mp 1959 -o THREAD,pmem,rss,vsz,tid,pid 查看mysqld的内存和CPU使用情况

[root@localhost ~]# pidof -s mysqld

[root@localhost ~]# ps -mp 1959 -o THREAD,pmem,rss,vsz,tid,pid
USER %CPU PRI SCNT WCHAN USER SYSTEM %MEM RSS VSZ TID PID
mysql 0.6 - - - - - 42.8 -
mysql 0.1 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -
mysql 0.0 - - - - - - - -

使用 pmap 查看进程的内存分布情况

The pmap command reports the memory map of a process or processes.

[root@localhost ~]# pmap -x 1959
: /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/var/lib/mysql --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=/var/log/mysqld.log --pid-file=/var/mysql/mysqld.pid --socket=/var/lib/mysql/mysql.sock
Address Kbytes RSS Dirty Mode Mapping
r-x-- [ anon ]
002e0000 r-x-- libnss_files-2.12.so
002ec000 r---- libnss_files-2.12.so
002ed000 rw--- libnss_files-2.12.so
003fb000 r-x-- libgcc_s-4.4.-.so.
rw--- libgcc_s-4.4.-.so.
0041b000 r-x-- libcrypt-2.12.so
r---- libcrypt-2.12.so
rw--- libcrypt-2.12.so
rw--- [ anon ]
0044d000 r-x-- libfreebl3.so
004a9000 ----- libfreebl3.so
004aa000 r---- libfreebl3.so
004ab000 rw--- libfreebl3.so
004ac000 rw--- [ anon ]
0053e000 r-x-- ld-2.12.so
0055c000 r---- ld-2.12.so
0055d000 rw--- ld-2.12.so
r-x-- libaio.so.1.0.
rw--- libaio.so.1.0.
r-x-- libc-2.12.so
006f4000 r---- libc-2.12.so
006f6000 rw--- libc-2.12.so
006f7000 rw--- [ anon ]
006fc000 r-x-- libpthread-2.12.so
r---- libpthread-2.12.so
rw--- libpthread-2.12.so
rw--- [ anon ]
r-x-- libdl-2.12.so
0071c000 r---- libdl-2.12.so
0071d000 rw--- libdl-2.12.so
r-x-- librt-2.12.so
r---- librt-2.12.so
rw--- librt-2.12.so
0072b000 r-x-- libm-2.12.so
r---- libm-2.12.so
rw--- libm-2.12.so
07b14000 r-x-- libstdc++.so.6.0.
07bf5000 r---- libstdc++.so.6.0.
07bf9000 rw--- libstdc++.so.6.0.
07bfb000 rw--- [ anon ]
r-x-- mysqld
08c18000 rw--- mysqld
08d4a000 rw--- [ anon ]
0a809000 rw--- [ anon ]
8abfd000 ----- [ anon ]
8abfe000 rw--- [ anon ]
8b5fe000 ----- [ anon ]
8b5ff000 rw--- [ anon ]
8bfff000 ----- [ anon ]
8c000000 rw--- [ anon ]
8ca00000 rw--- [ anon ]
8cbf7000 ----- [ anon ]
8cbf8000 rw--- [ anon ]
8d5f8000 ----- [ anon ]
8d5f9000 rw--- [ anon ]
8dff9000 ----- [ anon ]
8dffa000 rw--- [ anon ]
8e9fa000 ----- [ anon ]
8e9fb000 rw--- [ anon ]
8f3fb000 ----- [ anon ]
8f3fc000 rw--- [ anon ]
8fdfc000 ----- [ anon ]
8fdfd000 rw--- [ anon ]
90c00000 rw--- [ anon ]
90c21000 ----- [ anon ]
90d04000 ----- [ anon ]
90d05000 rw--- [ anon ]
90d35000 ----- [ anon ]
90d36000 rw--- [ anon ]
----- [ anon ]
rw--- [ anon ]
----- [ anon ]
rw--- [ anon ]
92b38000 ----- [ anon ]
92b39000 rw--- [ anon ]
----- [ anon ]
9353a000 rw--- [ anon ]
93f3a000 ----- [ anon ]
93f3b000 rw--- [ anon ]
9493b000 ----- [ anon ]
9493c000 rw--- [ anon ]
9533c000 ----- [ anon ]
9533d000 rw--- [ anon ]
95d3d000 ----- [ anon ]
95d3e000 rw--- [ anon ]
9673e000 ----- [ anon ]
9673f000 rw--- [ anon ]
9e9ab000 rw--- [ anon ]
b774b000 rw--- [ anon ]
bfc28000 rw--- [ stack ]
-------- ------- ------- ------- -------
total kB - - -

上面字段的含义:

EXTENDED AND DEVICE FORMAT FIELDS
Address: start address of map
Kbytes: size of map in kilobytes
RSS: resident set size in kilobytes
Dirty: dirty pages (both shared and private) in kilobytes
Mode: permissions on map: read, write, execute, shared, private (copy on write)
Mapping: file backing the map, or ’[ anon ]’ for allocated memory, or ’[ stack ]’ for the program stack
Offset: offset into the file
Device: device name (major:minor)

Mapping 字段说明是通过文件map使用的内存,还是[ anon ] 实际分配的内存,还是[ stack ] 栈使用的内存。

最后一行的 total KB 752740 的结果 和上面一条命令中 VSZ: 752744(虚拟内存) 是一致的。

5. 内存的调优

上面我们说到内存的瓶颈,主要看 swap out, page out, major page fault. 它们会极大的影响性能,特别是swap out. 所以内存调优也就是减少和防止它们的出现。

1)使用 hugepage 可以避免swap out; 但是 huagepage也是有代价的(导致page争用加剧),一定要事先测试;

2)修改 vm.swapingness, 优先flush disk cache,尽量减少page out 和 swap out; 但是flush disk cache又可能会导致 major page fault的产生;

3)disk cache刷新到磁盘有两个内核参数调节:vm.dirty_background_ratio=10; 默认值为10,表示disk cache中的脏页数量达到10%时,pdflush内核

线程会被调用,异步刷新disk cache; vm.dirty_ratio=20; 默认值20,表示disk cache中的脏页数量达到20%时,会进行同步的disk cache刷新,从而

阻塞系统中应用进程的IO操作!我们可以调低vm.dirty_background_ratio来降低disk cache对mysql使用内存的影响,但是可能会增加磁盘IO;

4)加内存;