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