Linux的Cache Memory(缓存内存)机制

旭灿 2011-03-03

当前一个项目中需要用到音频,用到的音频芯片是CS4344,驱动是从linux内核自带的AT73C213音频IC驱动移植过来的。

在用自己写的应用程序播放音频文件的时候,发现随着播放不同的音频文件,内存的使用越来越多,甚至高达27或28M(总共内存是32M)。由于在这之前没有关注过linux的cache机制,判断内存是用top命令的used的值来判断的,因此将这个问题判断为内存问题。

由于音频驱动是alsa架构,而播放音频的应用程序是直接用系统函数写的,开始判断为是应用程序导致的内存问题。于是移植了alsa-lib和alsa-utils,但用aplay测试的时候,总是不能设置参数,提示:Invalid argument,后面自己写的基于alsa-lib的测试程序也是出现这个问题,google了好多资料,也无济于事。

于是怀疑是不是音频驱动的问题,经查,原来移植驱动的时候,把采样频率的最大值最小值设定为同一个值,如下所示的14,15行:

static int snd_at73c213_pcm_open(struct snd_pcm_substream *substream)  
{  
    // 从子流获得芯片特定数据  
    struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);  
    // 获得PCM运行时信息指针  
    struct snd_pcm_runtime *runtime = substream->runtime;  
    int err;  
 
    /* ensure buffer_size is a multiple of period_size */ 
    err = snd_pcm_hw_constraint_integer(runtime,  
                    SNDRV_PCM_HW_PARAM_PERIODS);  
    if (err < 0)  
        return err;  
    snd_at73c213_playback_hw.rate_min = chip->bitrate;  
    snd_at73c213_playback_hw.rate_max = chip->bitrate;  
    // 初始化runtime-hw字段  
    runtime->hw = snd_at73c213_playback_hw;  
    chip->substream = substream;  
 
    return 0;  

static int snd_at73c213_pcm_open(struct snd_pcm_substream *substream)
{
 // 从子流获得芯片特定数据
 struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
 // 获得PCM运行时信息指针
 struct snd_pcm_runtime *runtime = substream->runtime;
 int err;

 /* ensure buffer_size is a multiple of period_size */
 err = snd_pcm_hw_constraint_integer(runtime,
     SNDRV_PCM_HW_PARAM_PERIODS);
 if (err < 0)
  return err;
 snd_at73c213_playback_hw.rate_min = chip->bitrate;
 snd_at73c213_playback_hw.rate_max = chip->bitrate;
 // 初始化runtime-hw字段
 runtime->hw = snd_at73c213_playback_hw;
 chip->substream = substream;

 return 0;
}

屏蔽掉后,就可以设参数了。

但用aplay依旧不能播放出声音,到是用自己写的测试程序可以播放出声音,只是声音不正常。这没关系,只是想观察下内存的使用情况。

发现,同样会内存增加。

到现在,头大了,到底是什么问题引起的呢?驱动?咱最怕的就是内存问题~~~~

正愁眉不展的时候,发现top中的cache一项,也在增加,而且很大,这引起了我的注意,为什么会这样呢?在linux中cache表示什么?

带着这些疑问,google了下,原来,这不是内存问题,而是linux中的一种机制,看如下所述:

先看网上的一篇文章:

Linux与Windows不同,会存在缓存内存,通常叫做Cache Memory。有些时候你会发现没有什么程序在运行,但是使用top或free命令看到可用内存会很少。

相关推荐