cpu_cooling.c 28.6 KB
Newer Older
1 2 3 4 5 6
/*
 *  linux/drivers/thermal/cpu_cooling.c
 *
 *  Copyright (C) 2012	Samsung Electronics Co., Ltd(http://www.samsung.com)
 *  Copyright (C) 2012  Amit Daniel <amit.kachhap@linaro.org>
 *
7 8
 *  Copyright (C) 2014  Viresh Kumar <viresh.kumar@linaro.org>
 *
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 *
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */
#include <linux/module.h>
#include <linux/thermal.h>
#include <linux/cpufreq.h>
#include <linux/err.h>
29
#include <linux/idr.h>
30
#include <linux/pm_opp.h>
31 32 33 34
#include <linux/slab.h>
#include <linux/cpu.h>
#include <linux/cpu_cooling.h>

35 36
#include <trace/events/thermal.h>

37 38 39 40 41 42 43 44 45 46 47 48 49 50
/*
 * Cooling state <-> CPUFreq frequency
 *
 * Cooling states are translated to frequencies throughout this driver and this
 * is the relation between them.
 *
 * Highest cooling state corresponds to lowest possible frequency.
 *
 * i.e.
 *	level 0 --> 1st Max Freq
 *	level 1 --> 2nd Max Freq
 *	...
 */

51
/**
52
 * struct freq_table - frequency table along with power entries
53 54 55 56
 * @frequency:	frequency in KHz
 * @power:	power in mW
 *
 * This structure is built when the cooling device registers and helps
57
 * in translating frequency to power and vice versa.
58
 */
59
struct freq_table {
60 61 62 63
	u32 frequency;
	u32 power;
};

64 65 66 67 68 69 70 71 72 73
/**
 * struct time_in_idle - Idle time stats
 * @time: previous reading of the absolute time that this cpu was idle
 * @timestamp: wall time of the last invocation of get_cpu_idle_time_us()
 */
struct time_in_idle {
	u64 time;
	u64 timestamp;
};

74
/**
75
 * struct cpufreq_cooling_device - data for cooling device with cpufreq
76 77
 * @id: unique integer value corresponding to each cpufreq_cooling_device
 *	registered.
78
 * @last_load: load measured by the latest call to cpufreq_get_requested_power()
79 80
 * @cpufreq_state: integer value representing the current state of cpufreq
 *	cooling	devices.
81
 * @clipped_freq: integer value representing the absolute value of the clipped
82
 *	frequency.
83 84
 * @max_level: maximum cooling level. One less than total number of valid
 *	cpufreq frequencies.
85 86 87 88
 * @freq_table: Freq table in descending order of frequencies
 * @cdev: thermal_cooling_device pointer to keep track of the
 *	registered cooling device.
 * @policy: cpufreq policy.
89
 * @node: list_head to link all cpufreq_cooling_device together.
90
 * @idle_time: idle time stats
91
 * @plat_get_static_power: callback to calculate the static power
92
 *
93 94
 * This structure is required for keeping information of each registered
 * cpufreq_cooling_device.
95 96 97
 */
struct cpufreq_cooling_device {
	int id;
98
	u32 last_load;
99
	unsigned int cpufreq_state;
100
	unsigned int clipped_freq;
101
	unsigned int max_level;
102
	struct freq_table *freq_table;	/* In descending order */
103 104
	struct thermal_cooling_device *cdev;
	struct cpufreq_policy *policy;
105
	struct list_head node;
106
	struct time_in_idle *idle_time;
107
	get_static_t plat_get_static_power;
108 109
};

110
static DEFINE_IDA(cpufreq_ida);
111
static DEFINE_MUTEX(cooling_list_lock);
112
static LIST_HEAD(cpufreq_cdev_list);
113 114 115 116

/* Below code defines functions to be used for cpufreq as cooling device */

/**
117
 * get_level: Find the level for a particular frequency
118
 * @cpufreq_cdev: cpufreq_cdev for which the property is required
119
 * @freq: Frequency
120
 *
121
 * Return: level corresponding to the frequency.
122
 */
123
static unsigned long get_level(struct cpufreq_cooling_device *cpufreq_cdev,
124
			       unsigned int freq)
125
{
126
	struct freq_table *freq_table = cpufreq_cdev->freq_table;
127
	unsigned long level;
128

129 130
	for (level = 1; level <= cpufreq_cdev->max_level; level++)
		if (freq > freq_table[level].frequency)
131
			break;
132

133
	return level - 1;
134 135
}

136 137 138 139 140
/**
 * cpufreq_thermal_notifier - notifier callback for cpufreq policy change.
 * @nb:	struct notifier_block * with callback info.
 * @event: value showing cpufreq event for which this function invoked.
 * @data: callback-specific data
141
 *
142
 * Callback to hijack the notification on cpufreq policy transition.
143 144 145 146
 * Every time there is a change in policy, we will intercept and
 * update the cpufreq policy with thermal constraints.
 *
 * Return: 0 (success)
147 148
 */
static int cpufreq_thermal_notifier(struct notifier_block *nb,
149
				    unsigned long event, void *data)
150 151
{
	struct cpufreq_policy *policy = data;
152
	unsigned long clipped_freq;
153
	struct cpufreq_cooling_device *cpufreq_cdev;
154

155 156
	if (event != CPUFREQ_ADJUST)
		return NOTIFY_DONE;
157

158
	mutex_lock(&cooling_list_lock);
159
	list_for_each_entry(cpufreq_cdev, &cpufreq_cdev_list, node) {
160 161 162 163 164
		/*
		 * A new copy of the policy is sent to the notifier and can't
		 * compare that directly.
		 */
		if (policy->cpu != cpufreq_cdev->policy->cpu)
165
			continue;
166

167 168 169 170 171 172 173 174 175 176 177
		/*
		 * policy->max is the maximum allowed frequency defined by user
		 * and clipped_freq is the maximum that thermal constraints
		 * allow.
		 *
		 * If clipped_freq is lower than policy->max, then we need to
		 * readjust policy->max.
		 *
		 * But, if clipped_freq is greater than policy->max, we don't
		 * need to do anything.
		 */
178
		clipped_freq = cpufreq_cdev->clipped_freq;
179

180
		if (policy->max > clipped_freq)
181
			cpufreq_verify_within_limits(policy, 0, clipped_freq);
182 183
		break;
	}
184
	mutex_unlock(&cooling_list_lock);
185 186 187 188 189

	return NOTIFY_OK;
}

/**
190 191
 * update_freq_table() - Update the freq table with power numbers
 * @cpufreq_cdev:	the cpufreq cooling device in which to update the table
192 193
 * @capacitance: dynamic power coefficient for these cpus
 *
194 195 196 197
 * Update the freq table with power numbers.  This table will be used in
 * cpu_power_to_freq() and cpu_freq_to_power() to convert between power and
 * frequency efficiently.  Power is stored in mW, frequency in KHz.  The
 * resulting table is in descending order.
198
 *
199
 * Return: 0 on success, -EINVAL if there are no OPPs for any CPUs,
200
 * or -ENOMEM if we run out of memory.
201
 */
202 203
static int update_freq_table(struct cpufreq_cooling_device *cpufreq_cdev,
			     u32 capacitance)
204
{
205
	struct freq_table *freq_table = cpufreq_cdev->freq_table;
206 207
	struct dev_pm_opp *opp;
	struct device *dev = NULL;
208
	int num_opps = 0, cpu = cpufreq_cdev->policy->cpu, i;
209

210 211 212 213 214
	dev = get_cpu_device(cpu);
	if (unlikely(!dev)) {
		dev_warn(&cpufreq_cdev->cdev->device,
			 "No cpu device for cpu %d\n", cpu);
		return -ENODEV;
215
	}
216

217 218 219 220
	num_opps = dev_pm_opp_get_opp_count(dev);
	if (num_opps < 0)
		return num_opps;

221 222 223 224 225 226
	/*
	 * The cpufreq table is also built from the OPP table and so the count
	 * should match.
	 */
	if (num_opps != cpufreq_cdev->max_level + 1) {
		dev_warn(dev, "Number of OPPs not matching with max_levels\n");
227
		return -EINVAL;
228
	}
229

230 231 232
	for (i = 0; i <= cpufreq_cdev->max_level; i++) {
		unsigned long freq = freq_table[i].frequency * 1000;
		u32 freq_mhz = freq_table[i].frequency / 1000;
233
		u64 power;
234
		u32 voltage_mv;
235

236 237 238 239 240 241 242 243 244
		/*
		 * Find ceil frequency as 'freq' may be slightly lower than OPP
		 * freq due to truncation while converting to kHz.
		 */
		opp = dev_pm_opp_find_freq_ceil(dev, &freq);
		if (IS_ERR(opp)) {
			dev_err(dev, "failed to get opp for %lu frequency\n",
				freq);
			return -EINVAL;
245 246
		}

247
		voltage_mv = dev_pm_opp_get_voltage(opp) / 1000;
248
		dev_pm_opp_put(opp);
249 250 251 252 253 254 255 256 257

		/*
		 * Do the multiplication with MHz and millivolt so as
		 * to not overflow.
		 */
		power = (u64)capacitance * freq_mhz * voltage_mv * voltage_mv;
		do_div(power, 1000000000);

		/* power is stored in mW */
258
		freq_table[i].power = power;
259
	}
260

261
	return 0;
262 263
}

264
static u32 cpu_freq_to_power(struct cpufreq_cooling_device *cpufreq_cdev,
265 266 267
			     u32 freq)
{
	int i;
268
	struct freq_table *freq_table = cpufreq_cdev->freq_table;
269

270 271
	for (i = 1; i <= cpufreq_cdev->max_level; i++)
		if (freq > freq_table[i].frequency)
272 273
			break;

274
	return freq_table[i - 1].power;
275 276
}

277
static u32 cpu_power_to_freq(struct cpufreq_cooling_device *cpufreq_cdev,
278 279 280
			     u32 power)
{
	int i;
281
	struct freq_table *freq_table = cpufreq_cdev->freq_table;
282

283 284
	for (i = 1; i <= cpufreq_cdev->max_level; i++)
		if (power > freq_table[i].power)
285 286
			break;

287
	return freq_table[i - 1].frequency;
288 289 290 291
}

/**
 * get_load() - get load for a cpu since last updated
292
 * @cpufreq_cdev:	&struct cpufreq_cooling_device for this cpu
293
 * @cpu:	cpu number
294
 * @cpu_idx:	index of the cpu in time_in_idle*
295 296 297 298
 *
 * Return: The average load of cpu @cpu in percentage since this
 * function was last called.
 */
299
static u32 get_load(struct cpufreq_cooling_device *cpufreq_cdev, int cpu,
300
		    int cpu_idx)
301 302 303
{
	u32 load;
	u64 now, now_idle, delta_time, delta_idle;
304
	struct time_in_idle *idle_time = &cpufreq_cdev->idle_time[cpu_idx];
305 306

	now_idle = get_cpu_idle_time(cpu, &now, 0);
307 308
	delta_idle = now_idle - idle_time->time;
	delta_time = now - idle_time->timestamp;
309 310 311 312 313 314

	if (delta_time <= delta_idle)
		load = 0;
	else
		load = div64_u64(100 * (delta_time - delta_idle), delta_time);

315 316
	idle_time->time = now_idle;
	idle_time->timestamp = now;
317 318 319 320 321 322

	return load;
}

/**
 * get_static_power() - calculate the static power consumed by the cpus
323
 * @cpufreq_cdev:	struct &cpufreq_cooling_device for this cpu cdev
324 325 326 327 328 329 330 331 332 333 334 335
 * @tz:		thermal zone device in which we're operating
 * @freq:	frequency in KHz
 * @power:	pointer in which to store the calculated static power
 *
 * Calculate the static power consumed by the cpus described by
 * @cpu_actor running at frequency @freq.  This function relies on a
 * platform specific function that should have been provided when the
 * actor was registered.  If it wasn't, the static power is assumed to
 * be negligible.  The calculated static power is stored in @power.
 *
 * Return: 0 on success, -E* on failure.
 */
336
static int get_static_power(struct cpufreq_cooling_device *cpufreq_cdev,
337 338 339 340 341
			    struct thermal_zone_device *tz, unsigned long freq,
			    u32 *power)
{
	struct dev_pm_opp *opp;
	unsigned long voltage;
342 343
	struct cpufreq_policy *policy = cpufreq_cdev->policy;
	struct cpumask *cpumask = policy->related_cpus;
344
	unsigned long freq_hz = freq * 1000;
345
	struct device *dev;
346

347
	if (!cpufreq_cdev->plat_get_static_power) {
348 349 350 351
		*power = 0;
		return 0;
	}

352 353 354 355
	dev = get_cpu_device(policy->cpu);
	WARN_ON(!dev);

	opp = dev_pm_opp_find_freq_exact(dev, freq_hz, true);
356
	if (IS_ERR(opp)) {
357
		dev_warn_ratelimited(dev, "Failed to find OPP for frequency %lu: %ld\n",
358 359 360 361
				     freq_hz, PTR_ERR(opp));
		return -EINVAL;
	}

362
	voltage = dev_pm_opp_get_voltage(opp);
363
	dev_pm_opp_put(opp);
364 365

	if (voltage == 0) {
366
		dev_err_ratelimited(dev, "Failed to get voltage for frequency %lu\n",
367
				    freq_hz);
368 369 370
		return -EINVAL;
	}

371 372
	return cpufreq_cdev->plat_get_static_power(cpumask, tz->passive_delay,
						  voltage, power);
373 374 375 376
}

/**
 * get_dynamic_power() - calculate the dynamic power
377
 * @cpufreq_cdev:	&cpufreq_cooling_device for this cdev
378 379 380
 * @freq:	current frequency
 *
 * Return: the dynamic power consumed by the cpus described by
381
 * @cpufreq_cdev.
382
 */
383
static u32 get_dynamic_power(struct cpufreq_cooling_device *cpufreq_cdev,
384 385 386 387
			     unsigned long freq)
{
	u32 raw_cpu_power;

388 389
	raw_cpu_power = cpu_freq_to_power(cpufreq_cdev, freq);
	return (raw_cpu_power * cpufreq_cdev->last_load) / 100;
390 391
}

392
/* cpufreq cooling device callback functions are defined below */
393 394 395 396 397

/**
 * cpufreq_get_max_state - callback function to get the max cooling state.
 * @cdev: thermal cooling device pointer.
 * @state: fill this variable with the max cooling state.
398 399 400 401 402
 *
 * Callback for the thermal cooling device to return the cpufreq
 * max cooling state.
 *
 * Return: 0 on success, an error code otherwise.
403 404 405 406
 */
static int cpufreq_get_max_state(struct thermal_cooling_device *cdev,
				 unsigned long *state)
{
407
	struct cpufreq_cooling_device *cpufreq_cdev = cdev->devdata;
408

409
	*state = cpufreq_cdev->max_level;
410
	return 0;
411 412 413 414 415 416
}

/**
 * cpufreq_get_cur_state - callback function to get the current cooling state.
 * @cdev: thermal cooling device pointer.
 * @state: fill this variable with the current cooling state.
417 418 419 420 421
 *
 * Callback for the thermal cooling device to return the cpufreq
 * current cooling state.
 *
 * Return: 0 on success, an error code otherwise.
422 423 424 425
 */
static int cpufreq_get_cur_state(struct thermal_cooling_device *cdev,
				 unsigned long *state)
{
426
	struct cpufreq_cooling_device *cpufreq_cdev = cdev->devdata;
427

428
	*state = cpufreq_cdev->cpufreq_state;
429

430
	return 0;
431 432 433 434 435 436
}

/**
 * cpufreq_set_cur_state - callback function to set the current cooling state.
 * @cdev: thermal cooling device pointer.
 * @state: set this variable to the current cooling state.
437 438 439 440 441
 *
 * Callback for the thermal cooling device to change the cpufreq
 * current cooling state.
 *
 * Return: 0 on success, an error code otherwise.
442 443 444 445
 */
static int cpufreq_set_cur_state(struct thermal_cooling_device *cdev,
				 unsigned long state)
{
446
	struct cpufreq_cooling_device *cpufreq_cdev = cdev->devdata;
447
	unsigned int clip_freq;
448 449

	/* Request state should be less than max_level */
450
	if (WARN_ON(state > cpufreq_cdev->max_level))
451
		return -EINVAL;
452 453

	/* Check if the old cooling action is same as new cooling action */
454
	if (cpufreq_cdev->cpufreq_state == state)
455
		return 0;
456

457
	clip_freq = cpufreq_cdev->freq_table[state].frequency;
458 459
	cpufreq_cdev->cpufreq_state = state;
	cpufreq_cdev->clipped_freq = clip_freq;
460

461
	cpufreq_update_policy(cpufreq_cdev->policy->cpu);
462 463

	return 0;
464 465
}

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
/**
 * cpufreq_get_requested_power() - get the current power
 * @cdev:	&thermal_cooling_device pointer
 * @tz:		a valid thermal zone device pointer
 * @power:	pointer in which to store the resulting power
 *
 * Calculate the current power consumption of the cpus in milliwatts
 * and store it in @power.  This function should actually calculate
 * the requested power, but it's hard to get the frequency that
 * cpufreq would have assigned if there were no thermal limits.
 * Instead, we calculate the current power on the assumption that the
 * immediate future will look like the immediate past.
 *
 * We use the current frequency and the average load since this
 * function was last called.  In reality, there could have been
 * multiple opps since this function was last called and that affects
 * the load calculation.  While it's not perfectly accurate, this
 * simplification is good enough and works.  REVISIT this, as more
 * complex code may be needed if experiments show that it's not
 * accurate enough.
 *
 * Return: 0 on success, -E* if getting the static power failed.
 */
static int cpufreq_get_requested_power(struct thermal_cooling_device *cdev,
				       struct thermal_zone_device *tz,
				       u32 *power)
{
	unsigned long freq;
494
	int i = 0, cpu, ret;
495
	u32 static_power, dynamic_power, total_load = 0;
496
	struct cpufreq_cooling_device *cpufreq_cdev = cdev->devdata;
497
	struct cpufreq_policy *policy = cpufreq_cdev->policy;
498
	u32 *load_cpu = NULL;
499

500
	freq = cpufreq_quick_get(policy->cpu);
501

502
	if (trace_thermal_power_cpu_get_power_enabled()) {
503
		u32 ncpus = cpumask_weight(policy->related_cpus);
504

505
		load_cpu = kcalloc(ncpus, sizeof(*load_cpu), GFP_KERNEL);
506 507
	}

508
	for_each_cpu(cpu, policy->related_cpus) {
509 510 511
		u32 load;

		if (cpu_online(cpu))
512
			load = get_load(cpufreq_cdev, cpu, i);
513 514 515 516
		else
			load = 0;

		total_load += load;
517 518 519 520
		if (trace_thermal_power_cpu_limit_enabled() && load_cpu)
			load_cpu[i] = load;

		i++;
521 522
	}

523
	cpufreq_cdev->last_load = total_load;
524

525 526
	dynamic_power = get_dynamic_power(cpufreq_cdev, freq);
	ret = get_static_power(cpufreq_cdev, tz, freq, &static_power);
527
	if (ret) {
528
		kfree(load_cpu);
529
		return ret;
530 531 532
	}

	if (load_cpu) {
533 534 535
		trace_thermal_power_cpu_get_power(policy->related_cpus, freq,
						  load_cpu, i, dynamic_power,
						  static_power);
536

537
		kfree(load_cpu);
538
	}
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565

	*power = static_power + dynamic_power;
	return 0;
}

/**
 * cpufreq_state2power() - convert a cpu cdev state to power consumed
 * @cdev:	&thermal_cooling_device pointer
 * @tz:		a valid thermal zone device pointer
 * @state:	cooling device state to be converted
 * @power:	pointer in which to store the resulting power
 *
 * Convert cooling device state @state into power consumption in
 * milliwatts assuming 100% load.  Store the calculated power in
 * @power.
 *
 * Return: 0 on success, -EINVAL if the cooling device state could not
 * be converted into a frequency or other -E* if there was an error
 * when calculating the static power.
 */
static int cpufreq_state2power(struct thermal_cooling_device *cdev,
			       struct thermal_zone_device *tz,
			       unsigned long state, u32 *power)
{
	unsigned int freq, num_cpus;
	u32 static_power, dynamic_power;
	int ret;
566
	struct cpufreq_cooling_device *cpufreq_cdev = cdev->devdata;
567

568 569 570 571
	/* Request state should be less than max_level */
	if (WARN_ON(state > cpufreq_cdev->max_level))
		return -EINVAL;

572
	num_cpus = cpumask_weight(cpufreq_cdev->policy->cpus);
573

574
	freq = cpufreq_cdev->freq_table[state].frequency;
575 576
	dynamic_power = cpu_freq_to_power(cpufreq_cdev, freq) * num_cpus;
	ret = get_static_power(cpufreq_cdev, tz, freq, &static_power);
577
	if (ret)
578
		return ret;
579 580

	*power = static_power + dynamic_power;
581
	return ret;
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
}

/**
 * cpufreq_power2state() - convert power to a cooling device state
 * @cdev:	&thermal_cooling_device pointer
 * @tz:		a valid thermal zone device pointer
 * @power:	power in milliwatts to be converted
 * @state:	pointer in which to store the resulting state
 *
 * Calculate a cooling device state for the cpus described by @cdev
 * that would allow them to consume at most @power mW and store it in
 * @state.  Note that this calculation depends on external factors
 * such as the cpu load or the current static power.  Calling this
 * function with the same power as input can yield different cooling
 * device states depending on those external factors.
 *
 * Return: 0 on success, -ENODEV if no cpus are online or -EINVAL if
 * the calculated frequency could not be converted to a valid state.
 * The latter should not happen unless the frequencies available to
 * cpufreq have changed since the initialization of the cpu cooling
 * device.
 */
static int cpufreq_power2state(struct thermal_cooling_device *cdev,
			       struct thermal_zone_device *tz, u32 power,
			       unsigned long *state)
{
608
	unsigned int cur_freq, target_freq;
609 610 611
	int ret;
	s32 dyn_power;
	u32 last_load, normalised_power, static_power;
612
	struct cpufreq_cooling_device *cpufreq_cdev = cdev->devdata;
613
	struct cpufreq_policy *policy = cpufreq_cdev->policy;
614

615
	cur_freq = cpufreq_quick_get(policy->cpu);
616
	ret = get_static_power(cpufreq_cdev, tz, cur_freq, &static_power);
617 618 619 620 621
	if (ret)
		return ret;

	dyn_power = power - static_power;
	dyn_power = dyn_power > 0 ? dyn_power : 0;
622
	last_load = cpufreq_cdev->last_load ?: 1;
623
	normalised_power = (dyn_power * 100) / last_load;
624
	target_freq = cpu_power_to_freq(cpufreq_cdev, normalised_power);
625

626
	*state = get_level(cpufreq_cdev, target_freq);
627 628
	trace_thermal_power_cpu_limit(policy->related_cpus, target_freq, *state,
				      power);
629 630 631
	return 0;
}

632
/* Bind cpufreq callbacks to thermal cooling device ops */
633

634
static struct thermal_cooling_device_ops cpufreq_cooling_ops = {
635 636 637 638 639
	.get_max_state = cpufreq_get_max_state,
	.get_cur_state = cpufreq_get_cur_state,
	.set_cur_state = cpufreq_set_cur_state,
};

640 641 642 643 644 645 646 647 648
static struct thermal_cooling_device_ops cpufreq_power_cooling_ops = {
	.get_max_state		= cpufreq_get_max_state,
	.get_cur_state		= cpufreq_get_cur_state,
	.set_cur_state		= cpufreq_set_cur_state,
	.get_requested_power	= cpufreq_get_requested_power,
	.state2power		= cpufreq_state2power,
	.power2state		= cpufreq_power2state,
};

649 650 651 652 653
/* Notifier for cpufreq policy change */
static struct notifier_block thermal_cpufreq_notifier_block = {
	.notifier_call = cpufreq_thermal_notifier,
};

654 655 656 657 658 659 660 661 662 663 664 665 666 667
static unsigned int find_next_max(struct cpufreq_frequency_table *table,
				  unsigned int prev_max)
{
	struct cpufreq_frequency_table *pos;
	unsigned int max = 0;

	cpufreq_for_each_valid_entry(pos, table) {
		if (pos->frequency > max && pos->frequency < prev_max)
			max = pos->frequency;
	}

	return max;
}

668
/**
669 670
 * __cpufreq_cooling_register - helper function to create cpufreq cooling device
 * @np: a valid struct device_node to the cooling device device tree node
671
 * @policy: cpufreq policy
672
 * Normally this should be same as cpufreq policy->related_cpus.
673 674 675
 * @capacitance: dynamic power coefficient for these cpus
 * @plat_static_func: function to calculate the static power consumed by these
 *                    cpus (optional)
676 677 678
 *
 * This interface function registers the cpufreq cooling device with the name
 * "thermal-cpufreq-%x". This api can support multiple instances of cpufreq
679 680
 * cooling devices. It also gives the opportunity to link the cooling device
 * with a device tree node, in order to bind it via the thermal DT code.
681 682 683
 *
 * Return: a valid struct thermal_cooling_device pointer on success,
 * on failure, it returns a corresponding ERR_PTR().
684
 */
685 686
static struct thermal_cooling_device *
__cpufreq_cooling_register(struct device_node *np,
687
			struct cpufreq_policy *policy, u32 capacitance,
688
			get_static_t plat_static_func)
689
{
690
	struct thermal_cooling_device *cdev;
691
	struct cpufreq_cooling_device *cpufreq_cdev;
692
	char dev_name[THERMAL_NAME_LENGTH];
693
	unsigned int freq, i, num_cpus;
694
	int ret;
695
	struct thermal_cooling_device_ops *cooling_ops;
696
	bool first;
697

698 699 700
	if (IS_ERR_OR_NULL(policy)) {
		pr_err("%s: cpufreq policy isn't valid: %p", __func__, policy);
		return ERR_PTR(-EINVAL);
701 702
	}

703 704 705 706
	i = cpufreq_table_count_valid_entries(policy);
	if (!i) {
		pr_debug("%s: CPUFreq table not found or has no valid entries\n",
			 __func__);
707
		return ERR_PTR(-ENODEV);
708
	}
709

710
	cpufreq_cdev = kzalloc(sizeof(*cpufreq_cdev), GFP_KERNEL);
711 712
	if (!cpufreq_cdev)
		return ERR_PTR(-ENOMEM);
713

714
	cpufreq_cdev->policy = policy;
715
	num_cpus = cpumask_weight(policy->related_cpus);
716 717 718 719
	cpufreq_cdev->idle_time = kcalloc(num_cpus,
					 sizeof(*cpufreq_cdev->idle_time),
					 GFP_KERNEL);
	if (!cpufreq_cdev->idle_time) {
720
		cdev = ERR_PTR(-ENOMEM);
721 722 723
		goto free_cdev;
	}

724 725
	/* max_level is an index, not a counter */
	cpufreq_cdev->max_level = i - 1;
726

727 728 729
	cpufreq_cdev->freq_table = kmalloc_array(i,
					sizeof(*cpufreq_cdev->freq_table),
					GFP_KERNEL);
730
	if (!cpufreq_cdev->freq_table) {
731
		cdev = ERR_PTR(-ENOMEM);
732
		goto free_idle_time;
733 734
	}

735 736
	ret = ida_simple_get(&cpufreq_ida, 0, 0, GFP_KERNEL);
	if (ret < 0) {
737
		cdev = ERR_PTR(ret);
738
		goto free_table;
739
	}
740
	cpufreq_cdev->id = ret;
741

742 743 744
	snprintf(dev_name, sizeof(dev_name), "thermal-cpufreq-%d",
		 cpufreq_cdev->id);

745
	/* Fill freq-table in descending order of frequencies */
746
	for (i = 0, freq = -1; i <= cpufreq_cdev->max_level; i++) {
747
		freq = find_next_max(policy->freq_table, freq);
748
		cpufreq_cdev->freq_table[i].frequency = freq;
749 750 751 752 753 754

		/* Warn for duplicate entries */
		if (!freq)
			pr_warn("%s: table has duplicate entries\n", __func__);
		else
			pr_debug("%s: freq:%u KHz\n", __func__, freq);
755
	}
756

757 758 759 760 761 762 763 764 765 766 767 768 769
	if (capacitance) {
		cpufreq_cdev->plat_get_static_power = plat_static_func;

		ret = update_freq_table(cpufreq_cdev, capacitance);
		if (ret) {
			cdev = ERR_PTR(ret);
			goto remove_ida;
		}

		cooling_ops = &cpufreq_power_cooling_ops;
	} else {
		cooling_ops = &cpufreq_cooling_ops;
	}
770

771 772 773
	cdev = thermal_of_cooling_device_register(np, dev_name, cpufreq_cdev,
						  cooling_ops);
	if (IS_ERR(cdev))
774
		goto remove_ida;
775

776
	cpufreq_cdev->clipped_freq = cpufreq_cdev->freq_table[0].frequency;
777
	cpufreq_cdev->cdev = cdev;
778

779
	mutex_lock(&cooling_list_lock);
780
	/* Register the notifier for first cpufreq cooling device */
781 782
	first = list_empty(&cpufreq_cdev_list);
	list_add(&cpufreq_cdev->node, &cpufreq_cdev_list);
783
	mutex_unlock(&cooling_list_lock);
784

785
	if (first)
786
		cpufreq_register_notifier(&thermal_cpufreq_notifier_block,
787
					  CPUFREQ_POLICY_NOTIFIER);
788

789
	return cdev;
790

791
remove_ida:
792
	ida_simple_remove(&cpufreq_ida, cpufreq_cdev->id);
793
free_table:
794
	kfree(cpufreq_cdev->freq_table);
795 796
free_idle_time:
	kfree(cpufreq_cdev->idle_time);
797
free_cdev:
798
	kfree(cpufreq_cdev);
799
	return cdev;
800
}
801 802 803

/**
 * cpufreq_cooling_register - function to create cpufreq cooling device.
804
 * @policy: cpufreq policy
805 806 807 808 809 810 811 812 813
 *
 * This interface function registers the cpufreq cooling device with the name
 * "thermal-cpufreq-%x". This api can support multiple instances of cpufreq
 * cooling devices.
 *
 * Return: a valid struct thermal_cooling_device pointer on success,
 * on failure, it returns a corresponding ERR_PTR().
 */
struct thermal_cooling_device *
814
cpufreq_cooling_register(struct cpufreq_policy *policy)
815
{
816
	return __cpufreq_cooling_register(NULL, policy, 0, NULL);
817
}
818
EXPORT_SYMBOL_GPL(cpufreq_cooling_register);
819

820 821 822
/**
 * of_cpufreq_cooling_register - function to create cpufreq cooling device.
 * @np: a valid struct device_node to the cooling device device tree node
823
 * @policy: cpufreq policy
824 825 826 827 828 829 830 831 832 833 834
 *
 * This interface function registers the cpufreq cooling device with the name
 * "thermal-cpufreq-%x". This api can support multiple instances of cpufreq
 * cooling devices. Using this API, the cpufreq cooling device will be
 * linked to the device tree node provided.
 *
 * Return: a valid struct thermal_cooling_device pointer on success,
 * on failure, it returns a corresponding ERR_PTR().
 */
struct thermal_cooling_device *
of_cpufreq_cooling_register(struct device_node *np,
835
			    struct cpufreq_policy *policy)
836 837 838 839
{
	if (!np)
		return ERR_PTR(-EINVAL);

840
	return __cpufreq_cooling_register(np, policy, 0, NULL);
841 842 843
}
EXPORT_SYMBOL_GPL(of_cpufreq_cooling_register);

844 845
/**
 * cpufreq_power_cooling_register() - create cpufreq cooling device with power extensions
846
 * @policy:		cpufreq policy
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
 * @capacitance:	dynamic power coefficient for these cpus
 * @plat_static_func:	function to calculate the static power consumed by these
 *			cpus (optional)
 *
 * This interface function registers the cpufreq cooling device with
 * the name "thermal-cpufreq-%x".  This api can support multiple
 * instances of cpufreq cooling devices.  Using this function, the
 * cooling device will implement the power extensions by using a
 * simple cpu power model.  The cpus must have registered their OPPs
 * using the OPP library.
 *
 * An optional @plat_static_func may be provided to calculate the
 * static power consumed by these cpus.  If the platform's static
 * power consumption is unknown or negligible, make it NULL.
 *
 * Return: a valid struct thermal_cooling_device pointer on success,
 * on failure, it returns a corresponding ERR_PTR().
 */
struct thermal_cooling_device *
866
cpufreq_power_cooling_register(struct cpufreq_policy *policy, u32 capacitance,
867 868
			       get_static_t plat_static_func)
{
869
	return __cpufreq_cooling_register(NULL, policy, capacitance,
870 871 872 873 874 875 876
				plat_static_func);
}
EXPORT_SYMBOL(cpufreq_power_cooling_register);

/**
 * of_cpufreq_power_cooling_register() - create cpufreq cooling device with power extensions
 * @np:	a valid struct device_node to the cooling device device tree node
877
 * @policy: cpufreq policy
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
 * @capacitance:	dynamic power coefficient for these cpus
 * @plat_static_func:	function to calculate the static power consumed by these
 *			cpus (optional)
 *
 * This interface function registers the cpufreq cooling device with
 * the name "thermal-cpufreq-%x".  This api can support multiple
 * instances of cpufreq cooling devices.  Using this API, the cpufreq
 * cooling device will be linked to the device tree node provided.
 * Using this function, the cooling device will implement the power
 * extensions by using a simple cpu power model.  The cpus must have
 * registered their OPPs using the OPP library.
 *
 * An optional @plat_static_func may be provided to calculate the
 * static power consumed by these cpus.  If the platform's static
 * power consumption is unknown or negligible, make it NULL.
 *
 * Return: a valid struct thermal_cooling_device pointer on success,
 * on failure, it returns a corresponding ERR_PTR().
 */
struct thermal_cooling_device *
of_cpufreq_power_cooling_register(struct device_node *np,
899
				  struct cpufreq_policy *policy,
900 901 902 903 904 905
				  u32 capacitance,
				  get_static_t plat_static_func)
{
	if (!np)
		return ERR_PTR(-EINVAL);

906
	return __cpufreq_cooling_register(np, policy, capacitance,
907 908 909 910
				plat_static_func);
}
EXPORT_SYMBOL(of_cpufreq_power_cooling_register);

911 912 913
/**
 * cpufreq_cooling_unregister - function to remove cpufreq cooling device.
 * @cdev: thermal cooling device pointer.
914 915
 *
 * This interface function unregisters the "thermal-cpufreq-%x" cooling device.
916 917 918
 */
void cpufreq_cooling_unregister(struct thermal_cooling_device *cdev)
{
919
	struct cpufreq_cooling_device *cpufreq_cdev;
920
	bool last;
921

922 923 924
	if (!cdev)
		return;

925
	cpufreq_cdev = cdev->devdata;
926

927
	mutex_lock(&cooling_list_lock);
928
	list_del(&cpufreq_cdev->node);
929
	/* Unregister the notifier for the last cpufreq cooling device */
930
	last = list_empty(&cpufreq_cdev_list);
931 932 933
	mutex_unlock(&cooling_list_lock);

	if (last)
934
		cpufreq_unregister_notifier(&thermal_cpufreq_notifier_block,
935
					    CPUFREQ_POLICY_NOTIFIER);
936

937
	thermal_cooling_device_unregister(cpufreq_cdev->cdev);
938
	ida_simple_remove(&cpufreq_ida, cpufreq_cdev->id);
939
	kfree(cpufreq_cdev->idle_time);
940 941
	kfree(cpufreq_cdev->freq_table);
	kfree(cpufreq_cdev);
942
}
943
EXPORT_SYMBOL_GPL(cpufreq_cooling_unregister);