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