xref: /openbmc/linux/drivers/video/backlight/pwm_bl.c (revision 06ba8020)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Simple PWM based backlight control, board code has to setup
4  * 1) pin configuration so PWM waveforms can output
5  * 2) platform_data being correctly configured
6  */
7 
8 #include <linux/delay.h>
9 #include <linux/gpio/consumer.h>
10 #include <linux/module.h>
11 #include <linux/kernel.h>
12 #include <linux/init.h>
13 #include <linux/platform_device.h>
14 #include <linux/fb.h>
15 #include <linux/backlight.h>
16 #include <linux/err.h>
17 #include <linux/pwm.h>
18 #include <linux/pwm_backlight.h>
19 #include <linux/regulator/consumer.h>
20 #include <linux/slab.h>
21 
22 struct pwm_bl_data {
23 	struct pwm_device	*pwm;
24 	struct device		*dev;
25 	unsigned int		lth_brightness;
26 	unsigned int		*levels;
27 	bool			enabled;
28 	struct regulator	*power_supply;
29 	struct gpio_desc	*enable_gpio;
30 	unsigned int		scale;
31 	unsigned int		post_pwm_on_delay;
32 	unsigned int		pwm_off_delay;
33 	int			(*notify)(struct device *,
34 					  int brightness);
35 	void			(*notify_after)(struct device *,
36 					int brightness);
37 	int			(*check_fb)(struct device *, struct fb_info *);
38 	void			(*exit)(struct device *);
39 };
40 
41 static void pwm_backlight_power_on(struct pwm_bl_data *pb)
42 {
43 	int err;
44 
45 	if (pb->enabled)
46 		return;
47 
48 	if (pb->power_supply) {
49 		err = regulator_enable(pb->power_supply);
50 		if (err < 0)
51 			dev_err(pb->dev, "failed to enable power supply\n");
52 	}
53 
54 	if (pb->post_pwm_on_delay)
55 		msleep(pb->post_pwm_on_delay);
56 
57 	if (pb->enable_gpio)
58 		gpiod_set_value_cansleep(pb->enable_gpio, 1);
59 
60 	pb->enabled = true;
61 }
62 
63 static void pwm_backlight_power_off(struct pwm_bl_data *pb)
64 {
65 	if (!pb->enabled)
66 		return;
67 
68 	if (pb->enable_gpio)
69 		gpiod_set_value_cansleep(pb->enable_gpio, 0);
70 
71 	if (pb->pwm_off_delay)
72 		msleep(pb->pwm_off_delay);
73 
74 	if (pb->power_supply)
75 		regulator_disable(pb->power_supply);
76 	pb->enabled = false;
77 }
78 
79 static int compute_duty_cycle(struct pwm_bl_data *pb, int brightness, struct pwm_state *state)
80 {
81 	unsigned int lth = pb->lth_brightness;
82 	u64 duty_cycle;
83 
84 	if (pb->levels)
85 		duty_cycle = pb->levels[brightness];
86 	else
87 		duty_cycle = brightness;
88 
89 	duty_cycle *= state->period - lth;
90 	do_div(duty_cycle, pb->scale);
91 
92 	return duty_cycle + lth;
93 }
94 
95 static int pwm_backlight_update_status(struct backlight_device *bl)
96 {
97 	struct pwm_bl_data *pb = bl_get_data(bl);
98 	int brightness = backlight_get_brightness(bl);
99 	struct pwm_state state;
100 
101 	if (pb->notify)
102 		brightness = pb->notify(pb->dev, brightness);
103 
104 	if (brightness > 0) {
105 		pwm_get_state(pb->pwm, &state);
106 		state.duty_cycle = compute_duty_cycle(pb, brightness, &state);
107 		state.enabled = true;
108 		pwm_apply_state(pb->pwm, &state);
109 
110 		pwm_backlight_power_on(pb);
111 	} else {
112 		pwm_backlight_power_off(pb);
113 
114 		pwm_get_state(pb->pwm, &state);
115 		state.duty_cycle = 0;
116 		/*
117 		 * We cannot assume a disabled PWM to drive its output to the
118 		 * inactive state. If we have an enable GPIO and/or a regulator
119 		 * we assume that this isn't relevant and we can disable the PWM
120 		 * to save power. If however there is neither an enable GPIO nor
121 		 * a regulator keep the PWM on be sure to get a constant
122 		 * inactive output.
123 		 */
124 		state.enabled = !pb->power_supply && !pb->enable_gpio;
125 		pwm_apply_state(pb->pwm, &state);
126 	}
127 
128 	if (pb->notify_after)
129 		pb->notify_after(pb->dev, brightness);
130 
131 	return 0;
132 }
133 
134 static int pwm_backlight_check_fb(struct backlight_device *bl,
135 				  struct fb_info *info)
136 {
137 	struct pwm_bl_data *pb = bl_get_data(bl);
138 
139 	return !pb->check_fb || pb->check_fb(pb->dev, info);
140 }
141 
142 static const struct backlight_ops pwm_backlight_ops = {
143 	.update_status	= pwm_backlight_update_status,
144 	.check_fb	= pwm_backlight_check_fb,
145 };
146 
147 #ifdef CONFIG_OF
148 #define PWM_LUMINANCE_SHIFT	16
149 #define PWM_LUMINANCE_SCALE	(1 << PWM_LUMINANCE_SHIFT) /* luminance scale */
150 
151 /*
152  * CIE lightness to PWM conversion.
153  *
154  * The CIE 1931 lightness formula is what actually describes how we perceive
155  * light:
156  *          Y = (L* / 903.3)           if L* ≤ 8
157  *          Y = ((L* + 16) / 116)^3    if L* > 8
158  *
159  * Where Y is the luminance, the amount of light coming out of the screen, and
160  * is a number between 0.0 and 1.0; and L* is the lightness, how bright a human
161  * perceives the screen to be, and is a number between 0 and 100.
162  *
163  * The following function does the fixed point maths needed to implement the
164  * above formula.
165  */
166 static u64 cie1931(unsigned int lightness)
167 {
168 	u64 retval;
169 
170 	/*
171 	 * @lightness is given as a number between 0 and 1, expressed
172 	 * as a fixed-point number in scale
173 	 * PWM_LUMINANCE_SCALE. Convert to a percentage, still
174 	 * expressed as a fixed-point number, so the above formulas
175 	 * can be applied.
176 	 */
177 	lightness *= 100;
178 	if (lightness <= (8 * PWM_LUMINANCE_SCALE)) {
179 		retval = DIV_ROUND_CLOSEST(lightness * 10, 9033);
180 	} else {
181 		retval = (lightness + (16 * PWM_LUMINANCE_SCALE)) / 116;
182 		retval *= retval * retval;
183 		retval += 1ULL << (2*PWM_LUMINANCE_SHIFT - 1);
184 		retval >>= 2*PWM_LUMINANCE_SHIFT;
185 	}
186 
187 	return retval;
188 }
189 
190 /*
191  * Create a default correction table for PWM values to create linear brightness
192  * for LED based backlights using the CIE1931 algorithm.
193  */
194 static
195 int pwm_backlight_brightness_default(struct device *dev,
196 				     struct platform_pwm_backlight_data *data,
197 				     unsigned int period)
198 {
199 	unsigned int i;
200 	u64 retval;
201 
202 	/*
203 	 * Once we have 4096 levels there's little point going much higher...
204 	 * neither interactive sliders nor animation benefits from having
205 	 * more values in the table.
206 	 */
207 	data->max_brightness =
208 		min((int)DIV_ROUND_UP(period, fls(period)), 4096);
209 
210 	data->levels = devm_kcalloc(dev, data->max_brightness,
211 				    sizeof(*data->levels), GFP_KERNEL);
212 	if (!data->levels)
213 		return -ENOMEM;
214 
215 	/* Fill the table using the cie1931 algorithm */
216 	for (i = 0; i < data->max_brightness; i++) {
217 		retval = cie1931((i * PWM_LUMINANCE_SCALE) /
218 				 data->max_brightness) * period;
219 		retval = DIV_ROUND_CLOSEST_ULL(retval, PWM_LUMINANCE_SCALE);
220 		if (retval > UINT_MAX)
221 			return -EINVAL;
222 		data->levels[i] = (unsigned int)retval;
223 	}
224 
225 	data->dft_brightness = data->max_brightness / 2;
226 	data->max_brightness--;
227 
228 	return 0;
229 }
230 
231 static int pwm_backlight_parse_dt(struct device *dev,
232 				  struct platform_pwm_backlight_data *data)
233 {
234 	struct device_node *node = dev->of_node;
235 	unsigned int num_levels;
236 	unsigned int num_steps = 0;
237 	struct property *prop;
238 	unsigned int *table;
239 	int length;
240 	u32 value;
241 	int ret;
242 
243 	if (!node)
244 		return -ENODEV;
245 
246 	memset(data, 0, sizeof(*data));
247 
248 	/*
249 	 * These values are optional and set as 0 by default, the out values
250 	 * are modified only if a valid u32 value can be decoded.
251 	 */
252 	of_property_read_u32(node, "post-pwm-on-delay-ms",
253 			     &data->post_pwm_on_delay);
254 	of_property_read_u32(node, "pwm-off-delay-ms", &data->pwm_off_delay);
255 
256 	/*
257 	 * Determine the number of brightness levels, if this property is not
258 	 * set a default table of brightness levels will be used.
259 	 */
260 	prop = of_find_property(node, "brightness-levels", &length);
261 	if (!prop)
262 		return 0;
263 
264 	num_levels = length / sizeof(u32);
265 
266 	/* read brightness levels from DT property */
267 	if (num_levels > 0) {
268 		data->levels = devm_kcalloc(dev, num_levels,
269 					    sizeof(*data->levels), GFP_KERNEL);
270 		if (!data->levels)
271 			return -ENOMEM;
272 
273 		ret = of_property_read_u32_array(node, "brightness-levels",
274 						 data->levels,
275 						 num_levels);
276 		if (ret < 0)
277 			return ret;
278 
279 		ret = of_property_read_u32(node, "default-brightness-level",
280 					   &value);
281 		if (ret < 0)
282 			return ret;
283 
284 		data->dft_brightness = value;
285 
286 		/*
287 		 * This property is optional, if is set enables linear
288 		 * interpolation between each of the values of brightness levels
289 		 * and creates a new pre-computed table.
290 		 */
291 		of_property_read_u32(node, "num-interpolated-steps",
292 				     &num_steps);
293 
294 		/*
295 		 * Make sure that there is at least two entries in the
296 		 * brightness-levels table, otherwise we can't interpolate
297 		 * between two points.
298 		 */
299 		if (num_steps) {
300 			unsigned int num_input_levels = num_levels;
301 			unsigned int i;
302 			u32 x1, x2, x, dx;
303 			u32 y1, y2;
304 			s64 dy;
305 
306 			if (num_input_levels < 2) {
307 				dev_err(dev, "can't interpolate\n");
308 				return -EINVAL;
309 			}
310 
311 			/*
312 			 * Recalculate the number of brightness levels, now
313 			 * taking in consideration the number of interpolated
314 			 * steps between two levels.
315 			 */
316 			num_levels = (num_input_levels - 1) * num_steps + 1;
317 			dev_dbg(dev, "new number of brightness levels: %d\n",
318 				num_levels);
319 
320 			/*
321 			 * Create a new table of brightness levels with all the
322 			 * interpolated steps.
323 			 */
324 			table = devm_kcalloc(dev, num_levels, sizeof(*table),
325 					     GFP_KERNEL);
326 			if (!table)
327 				return -ENOMEM;
328 			/*
329 			 * Fill the interpolated table[x] = y
330 			 * by draw lines between each (x1, y1) to (x2, y2).
331 			 */
332 			dx = num_steps;
333 			for (i = 0; i < num_input_levels - 1; i++) {
334 				x1 = i * dx;
335 				x2 = x1 + dx;
336 				y1 = data->levels[i];
337 				y2 = data->levels[i + 1];
338 				dy = (s64)y2 - y1;
339 
340 				for (x = x1; x < x2; x++) {
341 					table[x] = y1 +
342 						div_s64(dy * (x - x1), dx);
343 				}
344 			}
345 			/* Fill in the last point, since no line starts here. */
346 			table[x2] = y2;
347 
348 			/*
349 			 * As we use interpolation lets remove current
350 			 * brightness levels table and replace for the
351 			 * new interpolated table.
352 			 */
353 			devm_kfree(dev, data->levels);
354 			data->levels = table;
355 		}
356 
357 		data->max_brightness = num_levels - 1;
358 	}
359 
360 	return 0;
361 }
362 
363 static const struct of_device_id pwm_backlight_of_match[] = {
364 	{ .compatible = "pwm-backlight" },
365 	{ }
366 };
367 
368 MODULE_DEVICE_TABLE(of, pwm_backlight_of_match);
369 #else
370 static int pwm_backlight_parse_dt(struct device *dev,
371 				  struct platform_pwm_backlight_data *data)
372 {
373 	return -ENODEV;
374 }
375 
376 static
377 int pwm_backlight_brightness_default(struct device *dev,
378 				     struct platform_pwm_backlight_data *data,
379 				     unsigned int period)
380 {
381 	return -ENODEV;
382 }
383 #endif
384 
385 static bool pwm_backlight_is_linear(struct platform_pwm_backlight_data *data)
386 {
387 	unsigned int nlevels = data->max_brightness + 1;
388 	unsigned int min_val = data->levels[0];
389 	unsigned int max_val = data->levels[nlevels - 1];
390 	/*
391 	 * Multiplying by 128 means that even in pathological cases such
392 	 * as (max_val - min_val) == nlevels the error at max_val is less
393 	 * than 1%.
394 	 */
395 	unsigned int slope = (128 * (max_val - min_val)) / nlevels;
396 	unsigned int margin = (max_val - min_val) / 20; /* 5% */
397 	int i;
398 
399 	for (i = 1; i < nlevels; i++) {
400 		unsigned int linear_value = min_val + ((i * slope) / 128);
401 		unsigned int delta = abs(linear_value - data->levels[i]);
402 
403 		if (delta > margin)
404 			return false;
405 	}
406 
407 	return true;
408 }
409 
410 static int pwm_backlight_initial_power_state(const struct pwm_bl_data *pb)
411 {
412 	struct device_node *node = pb->dev->of_node;
413 	bool active = true;
414 
415 	/*
416 	 * If the enable GPIO is present, observable (either as input
417 	 * or output) and off then the backlight is not currently active.
418 	 * */
419 	if (pb->enable_gpio && gpiod_get_value_cansleep(pb->enable_gpio) == 0)
420 		active = false;
421 
422 	if (pb->power_supply && !regulator_is_enabled(pb->power_supply))
423 		active = false;
424 
425 	if (!pwm_is_enabled(pb->pwm))
426 		active = false;
427 
428 	/*
429 	 * Synchronize the enable_gpio with the observed state of the
430 	 * hardware.
431 	 */
432 	if (pb->enable_gpio)
433 		gpiod_direction_output(pb->enable_gpio, active);
434 
435 	/*
436 	 * Do not change pb->enabled here! pb->enabled essentially
437 	 * tells us if we own one of the regulator's use counts and
438 	 * right now we do not.
439 	 */
440 
441 	/* Not booted with device tree or no phandle link to the node */
442 	if (!node || !node->phandle)
443 		return FB_BLANK_UNBLANK;
444 
445 	/*
446 	 * If the driver is probed from the device tree and there is a
447 	 * phandle link pointing to the backlight node, it is safe to
448 	 * assume that another driver will enable the backlight at the
449 	 * appropriate time. Therefore, if it is disabled, keep it so.
450 	 */
451 	return active ? FB_BLANK_UNBLANK: FB_BLANK_POWERDOWN;
452 }
453 
454 static int pwm_backlight_probe(struct platform_device *pdev)
455 {
456 	struct platform_pwm_backlight_data *data = dev_get_platdata(&pdev->dev);
457 	struct platform_pwm_backlight_data defdata;
458 	struct backlight_properties props;
459 	struct backlight_device *bl;
460 	struct pwm_bl_data *pb;
461 	struct pwm_state state;
462 	unsigned int i;
463 	int ret;
464 
465 	if (!data) {
466 		ret = pwm_backlight_parse_dt(&pdev->dev, &defdata);
467 		if (ret < 0) {
468 			dev_err(&pdev->dev, "failed to find platform data\n");
469 			return ret;
470 		}
471 
472 		data = &defdata;
473 	}
474 
475 	if (data->init) {
476 		ret = data->init(&pdev->dev);
477 		if (ret < 0)
478 			return ret;
479 	}
480 
481 	pb = devm_kzalloc(&pdev->dev, sizeof(*pb), GFP_KERNEL);
482 	if (!pb) {
483 		ret = -ENOMEM;
484 		goto err_alloc;
485 	}
486 
487 	pb->notify = data->notify;
488 	pb->notify_after = data->notify_after;
489 	pb->check_fb = data->check_fb;
490 	pb->exit = data->exit;
491 	pb->dev = &pdev->dev;
492 	pb->enabled = false;
493 	pb->post_pwm_on_delay = data->post_pwm_on_delay;
494 	pb->pwm_off_delay = data->pwm_off_delay;
495 
496 	pb->enable_gpio = devm_gpiod_get_optional(&pdev->dev, "enable",
497 						  GPIOD_ASIS);
498 	if (IS_ERR(pb->enable_gpio)) {
499 		ret = PTR_ERR(pb->enable_gpio);
500 		goto err_alloc;
501 	}
502 
503 	pb->power_supply = devm_regulator_get_optional(&pdev->dev, "power");
504 	if (IS_ERR(pb->power_supply)) {
505 		ret = PTR_ERR(pb->power_supply);
506 		if (ret == -ENODEV)
507 			pb->power_supply = NULL;
508 		else
509 			goto err_alloc;
510 	}
511 
512 	pb->pwm = devm_pwm_get(&pdev->dev, NULL);
513 	if (IS_ERR(pb->pwm)) {
514 		ret = PTR_ERR(pb->pwm);
515 		if (ret != -EPROBE_DEFER)
516 			dev_err(&pdev->dev, "unable to request PWM\n");
517 		goto err_alloc;
518 	}
519 
520 	dev_dbg(&pdev->dev, "got pwm for backlight\n");
521 
522 	/* Sync up PWM state. */
523 	pwm_init_state(pb->pwm, &state);
524 
525 	/*
526 	 * The DT case will set the pwm_period_ns field to 0 and store the
527 	 * period, parsed from the DT, in the PWM device. For the non-DT case,
528 	 * set the period from platform data if it has not already been set
529 	 * via the PWM lookup table.
530 	 */
531 	if (!state.period && (data->pwm_period_ns > 0))
532 		state.period = data->pwm_period_ns;
533 
534 	ret = pwm_apply_state(pb->pwm, &state);
535 	if (ret) {
536 		dev_err(&pdev->dev, "failed to apply initial PWM state: %d\n",
537 			ret);
538 		goto err_alloc;
539 	}
540 
541 	memset(&props, 0, sizeof(struct backlight_properties));
542 
543 	if (data->levels) {
544 		pb->levels = data->levels;
545 
546 		/*
547 		 * For the DT case, only when brightness levels is defined
548 		 * data->levels is filled. For the non-DT case, data->levels
549 		 * can come from platform data, however is not usual.
550 		 */
551 		for (i = 0; i <= data->max_brightness; i++)
552 			if (data->levels[i] > pb->scale)
553 				pb->scale = data->levels[i];
554 
555 		if (pwm_backlight_is_linear(data))
556 			props.scale = BACKLIGHT_SCALE_LINEAR;
557 		else
558 			props.scale = BACKLIGHT_SCALE_NON_LINEAR;
559 	} else if (!data->max_brightness) {
560 		/*
561 		 * If no brightness levels are provided and max_brightness is
562 		 * not set, use the default brightness table. For the DT case,
563 		 * max_brightness is set to 0 when brightness levels is not
564 		 * specified. For the non-DT case, max_brightness is usually
565 		 * set to some value.
566 		 */
567 
568 		/* Get the PWM period (in nanoseconds) */
569 		pwm_get_state(pb->pwm, &state);
570 
571 		ret = pwm_backlight_brightness_default(&pdev->dev, data,
572 						       state.period);
573 		if (ret < 0) {
574 			dev_err(&pdev->dev,
575 				"failed to setup default brightness table\n");
576 			goto err_alloc;
577 		}
578 
579 		for (i = 0; i <= data->max_brightness; i++) {
580 			if (data->levels[i] > pb->scale)
581 				pb->scale = data->levels[i];
582 
583 			pb->levels = data->levels;
584 		}
585 
586 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
587 	} else {
588 		/*
589 		 * That only happens for the non-DT case, where platform data
590 		 * sets the max_brightness value.
591 		 */
592 		pb->scale = data->max_brightness;
593 	}
594 
595 	pb->lth_brightness = data->lth_brightness * (div_u64(state.period,
596 				pb->scale));
597 
598 	props.type = BACKLIGHT_RAW;
599 	props.max_brightness = data->max_brightness;
600 	bl = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, pb,
601 				       &pwm_backlight_ops, &props);
602 	if (IS_ERR(bl)) {
603 		dev_err(&pdev->dev, "failed to register backlight\n");
604 		ret = PTR_ERR(bl);
605 		goto err_alloc;
606 	}
607 
608 	if (data->dft_brightness > data->max_brightness) {
609 		dev_warn(&pdev->dev,
610 			 "invalid default brightness level: %u, using %u\n",
611 			 data->dft_brightness, data->max_brightness);
612 		data->dft_brightness = data->max_brightness;
613 	}
614 
615 	bl->props.brightness = data->dft_brightness;
616 	bl->props.power = pwm_backlight_initial_power_state(pb);
617 	backlight_update_status(bl);
618 
619 	platform_set_drvdata(pdev, bl);
620 	return 0;
621 
622 err_alloc:
623 	if (data->exit)
624 		data->exit(&pdev->dev);
625 	return ret;
626 }
627 
628 static void pwm_backlight_remove(struct platform_device *pdev)
629 {
630 	struct backlight_device *bl = platform_get_drvdata(pdev);
631 	struct pwm_bl_data *pb = bl_get_data(bl);
632 
633 	backlight_device_unregister(bl);
634 	pwm_backlight_power_off(pb);
635 
636 	if (pb->exit)
637 		pb->exit(&pdev->dev);
638 }
639 
640 static void pwm_backlight_shutdown(struct platform_device *pdev)
641 {
642 	struct backlight_device *bl = platform_get_drvdata(pdev);
643 	struct pwm_bl_data *pb = bl_get_data(bl);
644 
645 	pwm_backlight_power_off(pb);
646 }
647 
648 #ifdef CONFIG_PM_SLEEP
649 static int pwm_backlight_suspend(struct device *dev)
650 {
651 	struct backlight_device *bl = dev_get_drvdata(dev);
652 	struct pwm_bl_data *pb = bl_get_data(bl);
653 
654 	if (pb->notify)
655 		pb->notify(pb->dev, 0);
656 
657 	pwm_backlight_power_off(pb);
658 
659 	if (pb->notify_after)
660 		pb->notify_after(pb->dev, 0);
661 
662 	return 0;
663 }
664 
665 static int pwm_backlight_resume(struct device *dev)
666 {
667 	struct backlight_device *bl = dev_get_drvdata(dev);
668 
669 	backlight_update_status(bl);
670 
671 	return 0;
672 }
673 #endif
674 
675 static const struct dev_pm_ops pwm_backlight_pm_ops = {
676 #ifdef CONFIG_PM_SLEEP
677 	.suspend = pwm_backlight_suspend,
678 	.resume = pwm_backlight_resume,
679 	.poweroff = pwm_backlight_suspend,
680 	.restore = pwm_backlight_resume,
681 #endif
682 };
683 
684 static struct platform_driver pwm_backlight_driver = {
685 	.driver		= {
686 		.name		= "pwm-backlight",
687 		.pm		= &pwm_backlight_pm_ops,
688 		.of_match_table	= of_match_ptr(pwm_backlight_of_match),
689 	},
690 	.probe		= pwm_backlight_probe,
691 	.remove_new	= pwm_backlight_remove,
692 	.shutdown	= pwm_backlight_shutdown,
693 };
694 
695 module_platform_driver(pwm_backlight_driver);
696 
697 MODULE_DESCRIPTION("PWM based Backlight Driver");
698 MODULE_LICENSE("GPL v2");
699 MODULE_ALIAS("platform:pwm-backlight");
700