[LinuxKernel] how to get cpu max or min frequency from kernel ?

今天來講講怎麼如何取得cpu max/min frequency

這一兩周改module剛好有用到

在cpufreq policy的struct底下其實是有紀錄的

但其實並不是準的,因為Policy這個可以隨著需要而更動的。

在cpu driver init時候會call下面function,來get & validate cpufreq_table

int cpufreq_generic_init(struct cpufreq_policy *policy,
        struct cpufreq_frequency_table *table,
        unsigned int transition_latency)
{
    int ret;

    ret = cpufreq_table_validate_and_show(policy, table);
    if (ret) {
        pr_err("%s: invalid frequency table: %d\n", __func__, ret);
        return ret;
    }

    policy->cpuinfo.transition_latency = transition_latency;

    /*
     * The driver only supports the SMP configuration where all processors
     * share the clock and voltage and clock.
     */
    cpumask_setall(policy->cpus);

    return 0;
}
int cpufreq_table_validate_and_show(struct cpufreq_policy *policy,
                      struct cpufreq_frequency_table *table)
{
    int ret = cpufreq_frequency_table_cpuinfo(policy, table);

    if (!ret)
        policy->freq_table = table;

    return ret;
}
EXPORT_SYMBOL_GPL(cpufreq_table_validate_and_show);
int cpufreq_frequency_table_cpuinfo(struct cpufreq_p
int cpufreq_frequency_table_cpuinfo(struct cpufreq_policy *policy,
                    struct cpufreq_frequency_table *table)
{
    struct cpufreq_frequency_table *pos;
    unsigned int min_freq = ~0;
    unsigned int max_freq = 0;
    unsigned int freq;

    cpufreq_for_each_valid_entry(pos, table) {
        freq = pos->frequency;

        if (!cpufreq_boost_enabled()
            && (pos->flags & CPUFREQ_BOOST_FREQ))
            continue;

        pr_debug("table entry %u: %u kHz\n", (int)(pos - table), freq);
        if (freq < min_freq)
            min_freq = freq;
        if (freq > max_freq)
            max_freq = freq;
    }

    policy->min = policy->cpuinfo.min_freq = min_freq;
    policy->max = policy->cpuinfo.max_freq = max_freq;

    if (policy->min == ~0)
        return -EINVAL;
    else
        return 0;
}

在這裡policy, policy->cpuinfo的max/min frequency都會被設置一樣的

但policy在後續彈性比較多,看governor要怎麼調整。

cpuinfo沒意外就沒有再任何變動了,是個固定值。在kernel下可以透過下面這個fucntiionx來get cpu policy的pointer

cpufreq_cpu_get(cpu);

接著就能讀底下的cpuinfo.max_freq /cpuinfo.max_freq惹惹


要更保險的話就從更底層的cpufreq_frequency_table來獲得這方面的資訊

cpufreq_frequency_table的話就是從cpu driver init時被賦予value,表示該cpu支援那些頻率