xref: /linux/drivers/cpufreq/cpufreq_governor.c (revision a53fcff8fc7530f59a8171824ed586200df724a0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * drivers/cpufreq/cpufreq_governor.c
4  *
5  * CPUFREQ governors common code
6  *
7  * Copyright	(C) 2001 Russell King
8  *		(C) 2003 Venkatesh Pallipadi <venkatesh.pallipadi@intel.com>.
9  *		(C) 2003 Jun Nakajima <jun.nakajima@intel.com>
10  *		(C) 2009 Alexander Clouter <alex@digriz.org.uk>
11  *		(c) 2012 Viresh Kumar <viresh.kumar@linaro.org>
12  */
13 
14 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15 
16 #include <linux/export.h>
17 #include <linux/kernel_stat.h>
18 #include <linux/slab.h>
19 
20 #include "cpufreq_governor.h"
21 
22 #define CPUFREQ_DBS_MIN_SAMPLING_INTERVAL	(2 * TICK_NSEC / NSEC_PER_USEC)
23 
24 static DEFINE_PER_CPU(struct cpu_dbs_info, cpu_dbs);
25 
26 static DEFINE_MUTEX(gov_dbs_data_mutex);
27 
28 /* Common sysfs tunables */
29 /*
30  * sampling_rate_store - update sampling rate effective immediately if needed.
31  *
32  * If new rate is smaller than the old, simply updating
33  * dbs.sampling_rate might not be appropriate. For example, if the
34  * original sampling_rate was 1 second and the requested new sampling rate is 10
35  * ms because the user needs immediate reaction from ondemand governor, but not
36  * sure if higher frequency will be required or not, then, the governor may
37  * change the sampling rate too late; up to 1 second later. Thus, if we are
38  * reducing the sampling rate, we need to make the new value effective
39  * immediately.
40  *
41  * This must be called with dbs_data->mutex held, otherwise traversing
42  * policy_dbs_list isn't safe.
43  */
44 ssize_t sampling_rate_store(struct gov_attr_set *attr_set, const char *buf,
45 			    size_t count)
46 {
47 	struct dbs_data *dbs_data = to_dbs_data(attr_set);
48 	struct policy_dbs_info *policy_dbs;
49 	unsigned int sampling_interval;
50 	int ret;
51 
52 	ret = sscanf(buf, "%u", &sampling_interval);
53 	if (ret != 1 || sampling_interval < CPUFREQ_DBS_MIN_SAMPLING_INTERVAL)
54 		return -EINVAL;
55 
56 	dbs_data->sampling_rate = sampling_interval;
57 
58 	/*
59 	 * We are operating under dbs_data->mutex and so the list and its
60 	 * entries can't be freed concurrently.
61 	 */
62 	list_for_each_entry(policy_dbs, &attr_set->policy_list, list) {
63 		mutex_lock(&policy_dbs->update_mutex);
64 		/*
65 		 * On 32-bit architectures this may race with the
66 		 * sample_delay_ns read in dbs_update_util_handler(), but that
67 		 * really doesn't matter.  If the read returns a value that's
68 		 * too big, the sample will be skipped, but the next invocation
69 		 * of dbs_update_util_handler() (when the update has been
70 		 * completed) will take a sample.
71 		 *
72 		 * If this runs in parallel with dbs_work_handler(), we may end
73 		 * up overwriting the sample_delay_ns value that it has just
74 		 * written, but it will be corrected next time a sample is
75 		 * taken, so it shouldn't be significant.
76 		 */
77 		gov_update_sample_delay(policy_dbs, 0);
78 		mutex_unlock(&policy_dbs->update_mutex);
79 	}
80 
81 	return count;
82 }
83 EXPORT_SYMBOL_GPL(sampling_rate_store);
84 
85 /**
86  * gov_update_cpu_data - Update CPU load data.
87  * @dbs_data: Top-level governor data pointer.
88  *
89  * Update CPU load data for all CPUs in the domain governed by @dbs_data
90  * (that may be a single policy or a bunch of them if governor tunables are
91  * system-wide).
92  *
93  * Call under the @dbs_data->attr_set.update_lock. The per-policy
94  * update_mutex is acquired and released internally for each policy.
95  *
96  * Note: prev_cpu_nice is reset here unconditionally alongside prev_cpu_idle.
97  * When io_is_busy changes, both baselines must be advanced to the same
98  * timestamp so that the next dbs_update() computes idle_time and nice_delta
99  * over the same interval, preventing an artificially inflated idle_time when
100  * ignore_nice_load is enabled.
101  */
102 void gov_update_cpu_data(struct dbs_data *dbs_data)
103 {
104 	struct policy_dbs_info *policy_dbs;
105 
106 	list_for_each_entry(policy_dbs, &dbs_data->attr_set.policy_list, list) {
107 		unsigned int j;
108 
109 		mutex_lock(&policy_dbs->update_mutex);
110 		for_each_cpu(j, policy_dbs->policy->cpus) {
111 			struct cpu_dbs_info *j_cdbs = &per_cpu(cpu_dbs, j);
112 
113 			j_cdbs->prev_cpu_idle = get_cpu_idle_time(j, &j_cdbs->prev_update_time,
114 								  dbs_data->io_is_busy);
115 			j_cdbs->prev_cpu_nice = kcpustat_field(CPUTIME_NICE, j);
116 		}
117 		mutex_unlock(&policy_dbs->update_mutex);
118 	}
119 }
120 EXPORT_SYMBOL_GPL(gov_update_cpu_data);
121 
122 unsigned int dbs_update(struct cpufreq_policy *policy)
123 {
124 	struct policy_dbs_info *policy_dbs = policy->governor_data;
125 	struct dbs_data *dbs_data = policy_dbs->dbs_data;
126 	unsigned int ignore_nice = dbs_data->ignore_nice_load;
127 	unsigned int max_load = 0, idle_periods = UINT_MAX;
128 	unsigned int sampling_rate, io_busy, j;
129 	u64 cur_nice;
130 
131 	/*
132 	 * Sometimes governors may use an additional multiplier to increase
133 	 * sample delays temporarily.  Apply that multiplier to sampling_rate
134 	 * so as to keep the wake-up-from-idle detection logic a bit
135 	 * conservative.
136 	 */
137 	sampling_rate = dbs_data->sampling_rate * policy_dbs->rate_mult;
138 	/*
139 	 * For the purpose of ondemand, waiting for disk IO is an indication
140 	 * that you're performance critical, and not that the system is actually
141 	 * idle, so do not add the iowait time to the CPU idle time then.
142 	 */
143 	io_busy = dbs_data->io_is_busy;
144 
145 	/* Get Absolute Load */
146 	for_each_cpu(j, policy->cpus) {
147 		struct cpu_dbs_info *j_cdbs = &per_cpu(cpu_dbs, j);
148 		u64 update_time, cur_idle_time;
149 		unsigned int idle_time, time_elapsed;
150 		unsigned int load;
151 
152 		cur_idle_time = get_cpu_idle_time(j, &update_time, io_busy);
153 
154 		time_elapsed = update_time - j_cdbs->prev_update_time;
155 		j_cdbs->prev_update_time = update_time;
156 
157 		/*
158 		 * cur_idle_time could be smaller than j_cdbs->prev_cpu_idle if
159 		 * it's obtained from get_cpu_idle_time_jiffy() when NOHZ is
160 		 * off, where idle_time is calculated by the difference between
161 		 * time elapsed in jiffies and "busy time" obtained from CPU
162 		 * statistics.  If a CPU is 100% busy, the time elapsed and busy
163 		 * time should grow with the same amount in two consecutive
164 		 * samples, but in practice there could be a tiny difference,
165 		 * making the accumulated idle time decrease sometimes.  Hence,
166 		 * in this case, idle_time should be regarded as 0 in order to
167 		 * make the further process correct.
168 		 */
169 		if (cur_idle_time > j_cdbs->prev_cpu_idle)
170 			idle_time = cur_idle_time - j_cdbs->prev_cpu_idle;
171 		else
172 			idle_time = 0;
173 
174 		j_cdbs->prev_cpu_idle = cur_idle_time;
175 
176 		/*
177 		 * Always sample cur_nice and advance prev_cpu_nice, regardless
178 		 * of ignore_nice.  This keeps prev_cpu_nice current so that
179 		 * enabling ignore_nice_load via sysfs never produces a
180 		 * stale-baseline spike (the delta will be at most one sampling
181 		 * interval of accumulated nice time, not since boot).
182 		 */
183 		cur_nice = kcpustat_field(CPUTIME_NICE, j);
184 		if (ignore_nice)
185 			idle_time += div_u64(cur_nice - j_cdbs->prev_cpu_nice, NSEC_PER_USEC);
186 
187 		j_cdbs->prev_cpu_nice = cur_nice;
188 
189 		if (unlikely(!time_elapsed)) {
190 			/*
191 			 * That can only happen when this function is called
192 			 * twice in a row with a very short interval between the
193 			 * calls, so the previous load value can be used then.
194 			 */
195 			load = j_cdbs->prev_load;
196 		} else if (unlikely(idle_time > 2 * sampling_rate &&
197 				    j_cdbs->prev_load)) {
198 			/*
199 			 * If the CPU had gone completely idle and a task has
200 			 * just woken up on this CPU now, it would be unfair to
201 			 * calculate 'load' the usual way for this elapsed
202 			 * time-window, because it would show near-zero load,
203 			 * irrespective of how CPU intensive that task actually
204 			 * was. This is undesirable for latency-sensitive bursty
205 			 * workloads.
206 			 *
207 			 * To avoid this, reuse the 'load' from the previous
208 			 * time-window and give this task a chance to start with
209 			 * a reasonably high CPU frequency. However, that
210 			 * shouldn't be over-done, lest we get stuck at a high
211 			 * load (high frequency) for too long, even when the
212 			 * current system load has actually dropped down, so
213 			 * clear prev_load to guarantee that the load will be
214 			 * computed again next time.
215 			 *
216 			 * Detecting this situation is easy: an unusually large
217 			 * 'idle_time' (as compared to the sampling rate)
218 			 * indicates this scenario.
219 			 */
220 			load = j_cdbs->prev_load;
221 			j_cdbs->prev_load = 0;
222 		} else {
223 			if (time_elapsed > idle_time)
224 				load = 100 * (time_elapsed - idle_time) / time_elapsed;
225 			else
226 				load = 0;
227 
228 			j_cdbs->prev_load = load;
229 		}
230 
231 		if (unlikely(idle_time > 2 * sampling_rate)) {
232 			unsigned int periods = idle_time / sampling_rate;
233 
234 			if (periods < idle_periods)
235 				idle_periods = periods;
236 		}
237 
238 		if (load > max_load)
239 			max_load = load;
240 	}
241 
242 	policy_dbs->idle_periods = idle_periods;
243 
244 	return max_load;
245 }
246 EXPORT_SYMBOL_GPL(dbs_update);
247 
248 static void dbs_work_handler(struct work_struct *work)
249 {
250 	struct policy_dbs_info *policy_dbs;
251 	struct cpufreq_policy *policy;
252 	struct dbs_governor *gov;
253 
254 	policy_dbs = container_of(work, struct policy_dbs_info, work);
255 	policy = policy_dbs->policy;
256 	gov = dbs_governor_of(policy);
257 
258 	/*
259 	 * Make sure cpufreq_governor_limits() isn't evaluating load or the
260 	 * ondemand governor isn't updating the sampling rate in parallel.
261 	 */
262 	mutex_lock(&policy_dbs->update_mutex);
263 	gov_update_sample_delay(policy_dbs, gov->gov_dbs_update(policy));
264 	mutex_unlock(&policy_dbs->update_mutex);
265 
266 	/* Allow the utilization update handler to queue up more work. */
267 	atomic_set(&policy_dbs->work_count, 0);
268 	/*
269 	 * If the update below is reordered with respect to the sample delay
270 	 * modification, the utilization update handler may end up using a stale
271 	 * sample delay value.
272 	 */
273 	smp_wmb();
274 	policy_dbs->work_in_progress = false;
275 }
276 
277 static void dbs_irq_work(struct irq_work *irq_work)
278 {
279 	struct policy_dbs_info *policy_dbs;
280 
281 	policy_dbs = container_of(irq_work, struct policy_dbs_info, irq_work);
282 	schedule_work_on(smp_processor_id(), &policy_dbs->work);
283 }
284 
285 static void dbs_update_util_handler(struct update_util_data *data, u64 time,
286 				    unsigned int flags)
287 {
288 	struct cpu_dbs_info *cdbs = container_of(data, struct cpu_dbs_info, update_util);
289 	struct policy_dbs_info *policy_dbs = cdbs->policy_dbs;
290 	u64 delta_ns, lst;
291 
292 	if (!cpufreq_this_cpu_can_update(policy_dbs->policy))
293 		return;
294 
295 	/*
296 	 * The work may not be allowed to be queued up right now.
297 	 * Possible reasons:
298 	 * - Work has already been queued up or is in progress.
299 	 * - It is too early (too little time from the previous sample).
300 	 */
301 	if (policy_dbs->work_in_progress)
302 		return;
303 
304 	/*
305 	 * If the reads below are reordered before the check above, the value
306 	 * of sample_delay_ns used in the computation may be stale.
307 	 */
308 	smp_rmb();
309 	lst = READ_ONCE(policy_dbs->last_sample_time);
310 	delta_ns = time - lst;
311 	if ((s64)delta_ns < policy_dbs->sample_delay_ns)
312 		return;
313 
314 	/*
315 	 * If the policy is not shared, the irq_work may be queued up right away
316 	 * at this point.  Otherwise, we need to ensure that only one of the
317 	 * CPUs sharing the policy will do that.
318 	 */
319 	if (policy_dbs->is_shared) {
320 		if (!atomic_add_unless(&policy_dbs->work_count, 1, 1))
321 			return;
322 
323 		/*
324 		 * If another CPU updated last_sample_time in the meantime, we
325 		 * shouldn't be here, so clear the work counter and bail out.
326 		 */
327 		if (unlikely(lst != READ_ONCE(policy_dbs->last_sample_time))) {
328 			atomic_set(&policy_dbs->work_count, 0);
329 			return;
330 		}
331 	}
332 
333 	policy_dbs->last_sample_time = time;
334 	policy_dbs->work_in_progress = true;
335 	irq_work_queue(&policy_dbs->irq_work);
336 }
337 
338 static void gov_set_update_util(struct policy_dbs_info *policy_dbs,
339 				unsigned int delay_us)
340 {
341 	struct cpufreq_policy *policy = policy_dbs->policy;
342 	int cpu;
343 
344 	gov_update_sample_delay(policy_dbs, delay_us);
345 	policy_dbs->last_sample_time = 0;
346 
347 	for_each_cpu(cpu, policy->cpus) {
348 		struct cpu_dbs_info *cdbs = &per_cpu(cpu_dbs, cpu);
349 
350 		cpufreq_add_update_util_hook(cpu, &cdbs->update_util,
351 					     dbs_update_util_handler);
352 	}
353 }
354 
355 static inline void gov_clear_update_util(struct cpufreq_policy *policy)
356 {
357 	int i;
358 
359 	for_each_cpu(i, policy->cpus)
360 		cpufreq_remove_update_util_hook(i);
361 
362 	synchronize_rcu();
363 }
364 
365 static struct policy_dbs_info *alloc_policy_dbs_info(struct cpufreq_policy *policy,
366 						     struct dbs_governor *gov)
367 {
368 	struct policy_dbs_info *policy_dbs;
369 	int j;
370 
371 	/* Allocate memory for per-policy governor data. */
372 	policy_dbs = gov->alloc();
373 	if (!policy_dbs)
374 		return NULL;
375 
376 	policy_dbs->policy = policy;
377 	mutex_init(&policy_dbs->update_mutex);
378 	atomic_set(&policy_dbs->work_count, 0);
379 	init_irq_work(&policy_dbs->irq_work, dbs_irq_work);
380 	INIT_WORK(&policy_dbs->work, dbs_work_handler);
381 
382 	/* Set policy_dbs for all CPUs, online+offline */
383 	for_each_cpu(j, policy->related_cpus) {
384 		struct cpu_dbs_info *j_cdbs = &per_cpu(cpu_dbs, j);
385 
386 		j_cdbs->policy_dbs = policy_dbs;
387 	}
388 	return policy_dbs;
389 }
390 
391 static void free_policy_dbs_info(struct policy_dbs_info *policy_dbs,
392 				 struct dbs_governor *gov)
393 {
394 	int j;
395 
396 	mutex_destroy(&policy_dbs->update_mutex);
397 
398 	for_each_cpu(j, policy_dbs->policy->related_cpus) {
399 		struct cpu_dbs_info *j_cdbs = &per_cpu(cpu_dbs, j);
400 
401 		j_cdbs->policy_dbs = NULL;
402 		j_cdbs->update_util.func = NULL;
403 	}
404 	gov->free(policy_dbs);
405 }
406 
407 static void cpufreq_dbs_data_release(struct kobject *kobj)
408 {
409 	struct dbs_data *dbs_data = to_dbs_data(to_gov_attr_set(kobj));
410 	struct dbs_governor *gov = dbs_data->gov;
411 
412 	gov->exit(dbs_data);
413 	kfree(dbs_data);
414 }
415 
416 int cpufreq_dbs_governor_init(struct cpufreq_policy *policy)
417 {
418 	struct dbs_governor *gov = dbs_governor_of(policy);
419 	struct dbs_data *dbs_data;
420 	struct policy_dbs_info *policy_dbs;
421 	int ret = 0;
422 
423 	/* State should be equivalent to EXIT */
424 	if (policy->governor_data)
425 		return -EBUSY;
426 
427 	policy_dbs = alloc_policy_dbs_info(policy, gov);
428 	if (!policy_dbs)
429 		return -ENOMEM;
430 
431 	/* Protect gov->gdbs_data against concurrent updates. */
432 	mutex_lock(&gov_dbs_data_mutex);
433 
434 	dbs_data = gov->gdbs_data;
435 	if (dbs_data) {
436 		if (WARN_ON(have_governor_per_policy())) {
437 			ret = -EINVAL;
438 			goto free_policy_dbs_info;
439 		}
440 		policy_dbs->dbs_data = dbs_data;
441 		policy->governor_data = policy_dbs;
442 
443 		gov_attr_set_get(&dbs_data->attr_set, &policy_dbs->list);
444 		goto out;
445 	}
446 
447 	dbs_data = kzalloc_obj(*dbs_data);
448 	if (!dbs_data) {
449 		ret = -ENOMEM;
450 		goto free_policy_dbs_info;
451 	}
452 
453 	dbs_data->gov = gov;
454 	gov_attr_set_init(&dbs_data->attr_set, &policy_dbs->list);
455 
456 	ret = gov->init(dbs_data);
457 	if (ret)
458 		goto free_dbs_data;
459 
460 	/*
461 	 * The sampling interval should not be less than the transition latency
462 	 * of the CPU and it also cannot be too small for dbs_update() to work
463 	 * correctly.
464 	 */
465 	dbs_data->sampling_rate = max_t(unsigned int,
466 					CPUFREQ_DBS_MIN_SAMPLING_INTERVAL,
467 					cpufreq_policy_transition_delay_us(policy));
468 
469 	if (!have_governor_per_policy())
470 		gov->gdbs_data = dbs_data;
471 
472 	policy_dbs->dbs_data = dbs_data;
473 	policy->governor_data = policy_dbs;
474 
475 	gov->kobj_type.sysfs_ops = &governor_sysfs_ops;
476 	gov->kobj_type.release = cpufreq_dbs_data_release;
477 	ret = kobject_init_and_add(&dbs_data->attr_set.kobj, &gov->kobj_type,
478 				   get_governor_parent_kobj(policy),
479 				   "%s", gov->gov.name);
480 	if (!ret)
481 		goto out;
482 
483 	/* Failure, so roll back. */
484 	pr_err("initialization failed (dbs_data kobject init error %d)\n", ret);
485 
486 	policy->governor_data = NULL;
487 
488 	if (!have_governor_per_policy())
489 		gov->gdbs_data = NULL;
490 
491 	kobject_put(&dbs_data->attr_set.kobj);
492 	goto free_policy_dbs_info;
493 
494 free_dbs_data:
495 	kfree(dbs_data);
496 
497 free_policy_dbs_info:
498 	free_policy_dbs_info(policy_dbs, gov);
499 
500 out:
501 	mutex_unlock(&gov_dbs_data_mutex);
502 	return ret;
503 }
504 EXPORT_SYMBOL_GPL(cpufreq_dbs_governor_init);
505 
506 void cpufreq_dbs_governor_exit(struct cpufreq_policy *policy)
507 {
508 	struct dbs_governor *gov = dbs_governor_of(policy);
509 	struct policy_dbs_info *policy_dbs = policy->governor_data;
510 	struct dbs_data *dbs_data = policy_dbs->dbs_data;
511 	unsigned int count;
512 
513 	/* Protect gov->gdbs_data against concurrent updates. */
514 	mutex_lock(&gov_dbs_data_mutex);
515 
516 	count = gov_attr_set_put(&dbs_data->attr_set, &policy_dbs->list);
517 
518 	policy->governor_data = NULL;
519 
520 	if (!count && !have_governor_per_policy())
521 		gov->gdbs_data = NULL;
522 
523 	free_policy_dbs_info(policy_dbs, gov);
524 
525 	mutex_unlock(&gov_dbs_data_mutex);
526 }
527 EXPORT_SYMBOL_GPL(cpufreq_dbs_governor_exit);
528 
529 int cpufreq_dbs_governor_start(struct cpufreq_policy *policy)
530 {
531 	struct dbs_governor *gov = dbs_governor_of(policy);
532 	struct policy_dbs_info *policy_dbs = policy->governor_data;
533 	struct dbs_data *dbs_data = policy_dbs->dbs_data;
534 	unsigned int sampling_rate, j;
535 	unsigned int io_busy;
536 
537 	if (!policy->cur)
538 		return -EINVAL;
539 
540 	policy_dbs->is_shared = policy_is_shared(policy);
541 	policy_dbs->rate_mult = 1;
542 
543 	sampling_rate = dbs_data->sampling_rate;
544 
545 	mutex_lock(&policy_dbs->update_mutex);
546 	io_busy = dbs_data->io_is_busy;
547 	for_each_cpu(j, policy->cpus) {
548 		struct cpu_dbs_info *j_cdbs = &per_cpu(cpu_dbs, j);
549 
550 		j_cdbs->prev_cpu_idle = get_cpu_idle_time(j, &j_cdbs->prev_update_time, io_busy);
551 		/*
552 		 * Make the first invocation of dbs_update() compute the load.
553 		 */
554 		j_cdbs->prev_load = 0;
555 		j_cdbs->prev_cpu_nice = kcpustat_field(CPUTIME_NICE, j);
556 	}
557 	mutex_unlock(&policy_dbs->update_mutex);
558 
559 	gov->start(policy);
560 
561 	gov_set_update_util(policy_dbs, sampling_rate);
562 	return 0;
563 }
564 EXPORT_SYMBOL_GPL(cpufreq_dbs_governor_start);
565 
566 void cpufreq_dbs_governor_stop(struct cpufreq_policy *policy)
567 {
568 	struct policy_dbs_info *policy_dbs = policy->governor_data;
569 
570 	gov_clear_update_util(policy_dbs->policy);
571 	irq_work_sync(&policy_dbs->irq_work);
572 	cancel_work_sync(&policy_dbs->work);
573 	atomic_set(&policy_dbs->work_count, 0);
574 	policy_dbs->work_in_progress = false;
575 }
576 EXPORT_SYMBOL_GPL(cpufreq_dbs_governor_stop);
577 
578 void cpufreq_dbs_governor_limits(struct cpufreq_policy *policy)
579 {
580 	struct dbs_governor *gov = dbs_governor_of(policy);
581 	struct policy_dbs_info *policy_dbs;
582 
583 	/* Protect gov->gdbs_data against cpufreq_dbs_governor_exit() */
584 	mutex_lock(&gov_dbs_data_mutex);
585 	policy_dbs = policy->governor_data;
586 	if (!policy_dbs)
587 		goto out;
588 
589 	mutex_lock(&policy_dbs->update_mutex);
590 	cpufreq_policy_apply_limits(policy);
591 	gov_update_sample_delay(policy_dbs, 0);
592 	if (gov->limits)
593 		gov->limits(policy);
594 	mutex_unlock(&policy_dbs->update_mutex);
595 
596 out:
597 	mutex_unlock(&gov_dbs_data_mutex);
598 }
599 EXPORT_SYMBOL_GPL(cpufreq_dbs_governor_limits);
600