xref: /linux/drivers/pwm/core.c (revision 97733180fafbeb7cc3fd1c8be60d05980615f5d6)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Generic pwmlib implementation
4  *
5  * Copyright (C) 2011 Sascha Hauer <s.hauer@pengutronix.de>
6  * Copyright (C) 2011-2012 Avionic Design GmbH
7  */
8 
9 #include <linux/acpi.h>
10 #include <linux/module.h>
11 #include <linux/pwm.h>
12 #include <linux/radix-tree.h>
13 #include <linux/list.h>
14 #include <linux/mutex.h>
15 #include <linux/err.h>
16 #include <linux/slab.h>
17 #include <linux/device.h>
18 #include <linux/debugfs.h>
19 #include <linux/seq_file.h>
20 
21 #include <dt-bindings/pwm/pwm.h>
22 
23 #define CREATE_TRACE_POINTS
24 #include <trace/events/pwm.h>
25 
26 #define MAX_PWMS 1024
27 
28 static DEFINE_MUTEX(pwm_lookup_lock);
29 static LIST_HEAD(pwm_lookup_list);
30 static DEFINE_MUTEX(pwm_lock);
31 static LIST_HEAD(pwm_chips);
32 static DECLARE_BITMAP(allocated_pwms, MAX_PWMS);
33 static RADIX_TREE(pwm_tree, GFP_KERNEL);
34 
35 static struct pwm_device *pwm_to_device(unsigned int pwm)
36 {
37 	return radix_tree_lookup(&pwm_tree, pwm);
38 }
39 
40 static int alloc_pwms(unsigned int count)
41 {
42 	unsigned int start;
43 
44 	start = bitmap_find_next_zero_area(allocated_pwms, MAX_PWMS, 0,
45 					   count, 0);
46 
47 	if (start + count > MAX_PWMS)
48 		return -ENOSPC;
49 
50 	return start;
51 }
52 
53 static void free_pwms(struct pwm_chip *chip)
54 {
55 	unsigned int i;
56 
57 	for (i = 0; i < chip->npwm; i++) {
58 		struct pwm_device *pwm = &chip->pwms[i];
59 
60 		radix_tree_delete(&pwm_tree, pwm->pwm);
61 	}
62 
63 	bitmap_clear(allocated_pwms, chip->base, chip->npwm);
64 
65 	kfree(chip->pwms);
66 	chip->pwms = NULL;
67 }
68 
69 static struct pwm_chip *pwmchip_find_by_name(const char *name)
70 {
71 	struct pwm_chip *chip;
72 
73 	if (!name)
74 		return NULL;
75 
76 	mutex_lock(&pwm_lock);
77 
78 	list_for_each_entry(chip, &pwm_chips, list) {
79 		const char *chip_name = dev_name(chip->dev);
80 
81 		if (chip_name && strcmp(chip_name, name) == 0) {
82 			mutex_unlock(&pwm_lock);
83 			return chip;
84 		}
85 	}
86 
87 	mutex_unlock(&pwm_lock);
88 
89 	return NULL;
90 }
91 
92 static int pwm_device_request(struct pwm_device *pwm, const char *label)
93 {
94 	int err;
95 
96 	if (test_bit(PWMF_REQUESTED, &pwm->flags))
97 		return -EBUSY;
98 
99 	if (!try_module_get(pwm->chip->ops->owner))
100 		return -ENODEV;
101 
102 	if (pwm->chip->ops->request) {
103 		err = pwm->chip->ops->request(pwm->chip, pwm);
104 		if (err) {
105 			module_put(pwm->chip->ops->owner);
106 			return err;
107 		}
108 	}
109 
110 	if (pwm->chip->ops->get_state) {
111 		pwm->chip->ops->get_state(pwm->chip, pwm, &pwm->state);
112 		trace_pwm_get(pwm, &pwm->state);
113 
114 		if (IS_ENABLED(CONFIG_PWM_DEBUG))
115 			pwm->last = pwm->state;
116 	}
117 
118 	set_bit(PWMF_REQUESTED, &pwm->flags);
119 	pwm->label = label;
120 
121 	return 0;
122 }
123 
124 struct pwm_device *
125 of_pwm_xlate_with_flags(struct pwm_chip *pc, const struct of_phandle_args *args)
126 {
127 	struct pwm_device *pwm;
128 
129 	if (pc->of_pwm_n_cells < 2)
130 		return ERR_PTR(-EINVAL);
131 
132 	/* flags in the third cell are optional */
133 	if (args->args_count < 2)
134 		return ERR_PTR(-EINVAL);
135 
136 	if (args->args[0] >= pc->npwm)
137 		return ERR_PTR(-EINVAL);
138 
139 	pwm = pwm_request_from_chip(pc, args->args[0], NULL);
140 	if (IS_ERR(pwm))
141 		return pwm;
142 
143 	pwm->args.period = args->args[1];
144 	pwm->args.polarity = PWM_POLARITY_NORMAL;
145 
146 	if (pc->of_pwm_n_cells >= 3) {
147 		if (args->args_count > 2 && args->args[2] & PWM_POLARITY_INVERTED)
148 			pwm->args.polarity = PWM_POLARITY_INVERSED;
149 	}
150 
151 	return pwm;
152 }
153 EXPORT_SYMBOL_GPL(of_pwm_xlate_with_flags);
154 
155 struct pwm_device *
156 of_pwm_single_xlate(struct pwm_chip *pc, const struct of_phandle_args *args)
157 {
158 	struct pwm_device *pwm;
159 
160 	if (pc->of_pwm_n_cells < 1)
161 		return ERR_PTR(-EINVAL);
162 
163 	/* validate that one cell is specified, optionally with flags */
164 	if (args->args_count != 1 && args->args_count != 2)
165 		return ERR_PTR(-EINVAL);
166 
167 	pwm = pwm_request_from_chip(pc, 0, NULL);
168 	if (IS_ERR(pwm))
169 		return pwm;
170 
171 	pwm->args.period = args->args[0];
172 	pwm->args.polarity = PWM_POLARITY_NORMAL;
173 
174 	if (args->args_count == 2 && args->args[2] & PWM_POLARITY_INVERTED)
175 		pwm->args.polarity = PWM_POLARITY_INVERSED;
176 
177 	return pwm;
178 }
179 EXPORT_SYMBOL_GPL(of_pwm_single_xlate);
180 
181 static void of_pwmchip_add(struct pwm_chip *chip)
182 {
183 	if (!chip->dev || !chip->dev->of_node)
184 		return;
185 
186 	if (!chip->of_xlate) {
187 		u32 pwm_cells;
188 
189 		if (of_property_read_u32(chip->dev->of_node, "#pwm-cells",
190 					 &pwm_cells))
191 			pwm_cells = 2;
192 
193 		chip->of_xlate = of_pwm_xlate_with_flags;
194 		chip->of_pwm_n_cells = pwm_cells;
195 	}
196 
197 	of_node_get(chip->dev->of_node);
198 }
199 
200 static void of_pwmchip_remove(struct pwm_chip *chip)
201 {
202 	if (chip->dev)
203 		of_node_put(chip->dev->of_node);
204 }
205 
206 /**
207  * pwm_set_chip_data() - set private chip data for a PWM
208  * @pwm: PWM device
209  * @data: pointer to chip-specific data
210  *
211  * Returns: 0 on success or a negative error code on failure.
212  */
213 int pwm_set_chip_data(struct pwm_device *pwm, void *data)
214 {
215 	if (!pwm)
216 		return -EINVAL;
217 
218 	pwm->chip_data = data;
219 
220 	return 0;
221 }
222 EXPORT_SYMBOL_GPL(pwm_set_chip_data);
223 
224 /**
225  * pwm_get_chip_data() - get private chip data for a PWM
226  * @pwm: PWM device
227  *
228  * Returns: A pointer to the chip-private data for the PWM device.
229  */
230 void *pwm_get_chip_data(struct pwm_device *pwm)
231 {
232 	return pwm ? pwm->chip_data : NULL;
233 }
234 EXPORT_SYMBOL_GPL(pwm_get_chip_data);
235 
236 static bool pwm_ops_check(const struct pwm_chip *chip)
237 {
238 
239 	const struct pwm_ops *ops = chip->ops;
240 
241 	/* driver supports legacy, non-atomic operation */
242 	if (ops->config && ops->enable && ops->disable) {
243 		if (IS_ENABLED(CONFIG_PWM_DEBUG))
244 			dev_warn(chip->dev,
245 				 "Driver needs updating to atomic API\n");
246 
247 		return true;
248 	}
249 
250 	if (!ops->apply)
251 		return false;
252 
253 	if (IS_ENABLED(CONFIG_PWM_DEBUG) && !ops->get_state)
254 		dev_warn(chip->dev,
255 			 "Please implement the .get_state() callback\n");
256 
257 	return true;
258 }
259 
260 /**
261  * pwmchip_add() - register a new PWM chip
262  * @chip: the PWM chip to add
263  *
264  * Register a new PWM chip.
265  *
266  * Returns: 0 on success or a negative error code on failure.
267  */
268 int pwmchip_add(struct pwm_chip *chip)
269 {
270 	struct pwm_device *pwm;
271 	unsigned int i;
272 	int ret;
273 
274 	if (!chip || !chip->dev || !chip->ops || !chip->npwm)
275 		return -EINVAL;
276 
277 	if (!pwm_ops_check(chip))
278 		return -EINVAL;
279 
280 	mutex_lock(&pwm_lock);
281 
282 	ret = alloc_pwms(chip->npwm);
283 	if (ret < 0)
284 		goto out;
285 
286 	chip->base = ret;
287 
288 	chip->pwms = kcalloc(chip->npwm, sizeof(*pwm), GFP_KERNEL);
289 	if (!chip->pwms) {
290 		ret = -ENOMEM;
291 		goto out;
292 	}
293 
294 	for (i = 0; i < chip->npwm; i++) {
295 		pwm = &chip->pwms[i];
296 
297 		pwm->chip = chip;
298 		pwm->pwm = chip->base + i;
299 		pwm->hwpwm = i;
300 
301 		radix_tree_insert(&pwm_tree, pwm->pwm, pwm);
302 	}
303 
304 	bitmap_set(allocated_pwms, chip->base, chip->npwm);
305 
306 	INIT_LIST_HEAD(&chip->list);
307 	list_add(&chip->list, &pwm_chips);
308 
309 	ret = 0;
310 
311 	if (IS_ENABLED(CONFIG_OF))
312 		of_pwmchip_add(chip);
313 
314 out:
315 	mutex_unlock(&pwm_lock);
316 
317 	if (!ret)
318 		pwmchip_sysfs_export(chip);
319 
320 	return ret;
321 }
322 EXPORT_SYMBOL_GPL(pwmchip_add);
323 
324 /**
325  * pwmchip_remove() - remove a PWM chip
326  * @chip: the PWM chip to remove
327  *
328  * Removes a PWM chip. This function may return busy if the PWM chip provides
329  * a PWM device that is still requested.
330  *
331  * Returns: 0 on success or a negative error code on failure.
332  */
333 void pwmchip_remove(struct pwm_chip *chip)
334 {
335 	pwmchip_sysfs_unexport(chip);
336 
337 	mutex_lock(&pwm_lock);
338 
339 	list_del_init(&chip->list);
340 
341 	if (IS_ENABLED(CONFIG_OF))
342 		of_pwmchip_remove(chip);
343 
344 	free_pwms(chip);
345 
346 	mutex_unlock(&pwm_lock);
347 }
348 EXPORT_SYMBOL_GPL(pwmchip_remove);
349 
350 static void devm_pwmchip_remove(void *data)
351 {
352 	struct pwm_chip *chip = data;
353 
354 	pwmchip_remove(chip);
355 }
356 
357 int devm_pwmchip_add(struct device *dev, struct pwm_chip *chip)
358 {
359 	int ret;
360 
361 	ret = pwmchip_add(chip);
362 	if (ret)
363 		return ret;
364 
365 	return devm_add_action_or_reset(dev, devm_pwmchip_remove, chip);
366 }
367 EXPORT_SYMBOL_GPL(devm_pwmchip_add);
368 
369 /**
370  * pwm_request() - request a PWM device
371  * @pwm: global PWM device index
372  * @label: PWM device label
373  *
374  * This function is deprecated, use pwm_get() instead.
375  *
376  * Returns: A pointer to a PWM device or an ERR_PTR()-encoded error code on
377  * failure.
378  */
379 struct pwm_device *pwm_request(int pwm, const char *label)
380 {
381 	struct pwm_device *dev;
382 	int err;
383 
384 	if (pwm < 0 || pwm >= MAX_PWMS)
385 		return ERR_PTR(-EINVAL);
386 
387 	mutex_lock(&pwm_lock);
388 
389 	dev = pwm_to_device(pwm);
390 	if (!dev) {
391 		dev = ERR_PTR(-EPROBE_DEFER);
392 		goto out;
393 	}
394 
395 	err = pwm_device_request(dev, label);
396 	if (err < 0)
397 		dev = ERR_PTR(err);
398 
399 out:
400 	mutex_unlock(&pwm_lock);
401 
402 	return dev;
403 }
404 EXPORT_SYMBOL_GPL(pwm_request);
405 
406 /**
407  * pwm_request_from_chip() - request a PWM device relative to a PWM chip
408  * @chip: PWM chip
409  * @index: per-chip index of the PWM to request
410  * @label: a literal description string of this PWM
411  *
412  * Returns: A pointer to the PWM device at the given index of the given PWM
413  * chip. A negative error code is returned if the index is not valid for the
414  * specified PWM chip or if the PWM device cannot be requested.
415  */
416 struct pwm_device *pwm_request_from_chip(struct pwm_chip *chip,
417 					 unsigned int index,
418 					 const char *label)
419 {
420 	struct pwm_device *pwm;
421 	int err;
422 
423 	if (!chip || index >= chip->npwm)
424 		return ERR_PTR(-EINVAL);
425 
426 	mutex_lock(&pwm_lock);
427 	pwm = &chip->pwms[index];
428 
429 	err = pwm_device_request(pwm, label);
430 	if (err < 0)
431 		pwm = ERR_PTR(err);
432 
433 	mutex_unlock(&pwm_lock);
434 	return pwm;
435 }
436 EXPORT_SYMBOL_GPL(pwm_request_from_chip);
437 
438 /**
439  * pwm_free() - free a PWM device
440  * @pwm: PWM device
441  *
442  * This function is deprecated, use pwm_put() instead.
443  */
444 void pwm_free(struct pwm_device *pwm)
445 {
446 	pwm_put(pwm);
447 }
448 EXPORT_SYMBOL_GPL(pwm_free);
449 
450 static void pwm_apply_state_debug(struct pwm_device *pwm,
451 				  const struct pwm_state *state)
452 {
453 	struct pwm_state *last = &pwm->last;
454 	struct pwm_chip *chip = pwm->chip;
455 	struct pwm_state s1, s2;
456 	int err;
457 
458 	if (!IS_ENABLED(CONFIG_PWM_DEBUG))
459 		return;
460 
461 	/* No reasonable diagnosis possible without .get_state() */
462 	if (!chip->ops->get_state)
463 		return;
464 
465 	/*
466 	 * *state was just applied. Read out the hardware state and do some
467 	 * checks.
468 	 */
469 
470 	chip->ops->get_state(chip, pwm, &s1);
471 	trace_pwm_get(pwm, &s1);
472 
473 	/*
474 	 * The lowlevel driver either ignored .polarity (which is a bug) or as
475 	 * best effort inverted .polarity and fixed .duty_cycle respectively.
476 	 * Undo this inversion and fixup for further tests.
477 	 */
478 	if (s1.enabled && s1.polarity != state->polarity) {
479 		s2.polarity = state->polarity;
480 		s2.duty_cycle = s1.period - s1.duty_cycle;
481 		s2.period = s1.period;
482 		s2.enabled = s1.enabled;
483 	} else {
484 		s2 = s1;
485 	}
486 
487 	if (s2.polarity != state->polarity &&
488 	    state->duty_cycle < state->period)
489 		dev_warn(chip->dev, ".apply ignored .polarity\n");
490 
491 	if (state->enabled &&
492 	    last->polarity == state->polarity &&
493 	    last->period > s2.period &&
494 	    last->period <= state->period)
495 		dev_warn(chip->dev,
496 			 ".apply didn't pick the best available period (requested: %llu, applied: %llu, possible: %llu)\n",
497 			 state->period, s2.period, last->period);
498 
499 	if (state->enabled && state->period < s2.period)
500 		dev_warn(chip->dev,
501 			 ".apply is supposed to round down period (requested: %llu, applied: %llu)\n",
502 			 state->period, s2.period);
503 
504 	if (state->enabled &&
505 	    last->polarity == state->polarity &&
506 	    last->period == s2.period &&
507 	    last->duty_cycle > s2.duty_cycle &&
508 	    last->duty_cycle <= state->duty_cycle)
509 		dev_warn(chip->dev,
510 			 ".apply didn't pick the best available duty cycle (requested: %llu/%llu, applied: %llu/%llu, possible: %llu/%llu)\n",
511 			 state->duty_cycle, state->period,
512 			 s2.duty_cycle, s2.period,
513 			 last->duty_cycle, last->period);
514 
515 	if (state->enabled && state->duty_cycle < s2.duty_cycle)
516 		dev_warn(chip->dev,
517 			 ".apply is supposed to round down duty_cycle (requested: %llu/%llu, applied: %llu/%llu)\n",
518 			 state->duty_cycle, state->period,
519 			 s2.duty_cycle, s2.period);
520 
521 	if (!state->enabled && s2.enabled && s2.duty_cycle > 0)
522 		dev_warn(chip->dev,
523 			 "requested disabled, but yielded enabled with duty > 0\n");
524 
525 	/* reapply the state that the driver reported being configured. */
526 	err = chip->ops->apply(chip, pwm, &s1);
527 	if (err) {
528 		*last = s1;
529 		dev_err(chip->dev, "failed to reapply current setting\n");
530 		return;
531 	}
532 
533 	trace_pwm_apply(pwm, &s1);
534 
535 	chip->ops->get_state(chip, pwm, last);
536 	trace_pwm_get(pwm, last);
537 
538 	/* reapplication of the current state should give an exact match */
539 	if (s1.enabled != last->enabled ||
540 	    s1.polarity != last->polarity ||
541 	    (s1.enabled && s1.period != last->period) ||
542 	    (s1.enabled && s1.duty_cycle != last->duty_cycle)) {
543 		dev_err(chip->dev,
544 			".apply is not idempotent (ena=%d pol=%d %llu/%llu) -> (ena=%d pol=%d %llu/%llu)\n",
545 			s1.enabled, s1.polarity, s1.duty_cycle, s1.period,
546 			last->enabled, last->polarity, last->duty_cycle,
547 			last->period);
548 	}
549 }
550 
551 static int pwm_apply_legacy(struct pwm_chip *chip, struct pwm_device *pwm,
552 			    const struct pwm_state *state)
553 {
554 	int err;
555 	struct pwm_state initial_state = pwm->state;
556 
557 	if (state->polarity != pwm->state.polarity) {
558 		if (!chip->ops->set_polarity)
559 			return -EINVAL;
560 
561 		/*
562 		 * Changing the polarity of a running PWM is only allowed when
563 		 * the PWM driver implements ->apply().
564 		 */
565 		if (pwm->state.enabled) {
566 			chip->ops->disable(chip, pwm);
567 
568 			/*
569 			 * Update pwm->state already here in case
570 			 * .set_polarity() or another callback depend on that.
571 			 */
572 			pwm->state.enabled = false;
573 		}
574 
575 		err = chip->ops->set_polarity(chip, pwm, state->polarity);
576 		if (err)
577 			goto rollback;
578 
579 		pwm->state.polarity = state->polarity;
580 	}
581 
582 	if (!state->enabled) {
583 		if (pwm->state.enabled)
584 			chip->ops->disable(chip, pwm);
585 
586 		return 0;
587 	}
588 
589 	/*
590 	 * We cannot skip calling ->config even if state->period ==
591 	 * pwm->state.period && state->duty_cycle == pwm->state.duty_cycle
592 	 * because we might have exited early in the last call to
593 	 * pwm_apply_state because of !state->enabled and so the two values in
594 	 * pwm->state might not be configured in hardware.
595 	 */
596 	err = chip->ops->config(pwm->chip, pwm,
597 				state->duty_cycle,
598 				state->period);
599 	if (err)
600 		goto rollback;
601 
602 	pwm->state.period = state->period;
603 	pwm->state.duty_cycle = state->duty_cycle;
604 
605 	if (!pwm->state.enabled) {
606 		err = chip->ops->enable(chip, pwm);
607 		if (err)
608 			goto rollback;
609 	}
610 
611 	return 0;
612 
613 rollback:
614 	pwm->state = initial_state;
615 	return err;
616 }
617 
618 /**
619  * pwm_apply_state() - atomically apply a new state to a PWM device
620  * @pwm: PWM device
621  * @state: new state to apply
622  */
623 int pwm_apply_state(struct pwm_device *pwm, const struct pwm_state *state)
624 {
625 	struct pwm_chip *chip;
626 	int err;
627 
628 	/*
629 	 * Some lowlevel driver's implementations of .apply() make use of
630 	 * mutexes, also with some drivers only returning when the new
631 	 * configuration is active calling pwm_apply_state() from atomic context
632 	 * is a bad idea. So make it explicit that calling this function might
633 	 * sleep.
634 	 */
635 	might_sleep();
636 
637 	if (!pwm || !state || !state->period ||
638 	    state->duty_cycle > state->period)
639 		return -EINVAL;
640 
641 	chip = pwm->chip;
642 
643 	if (state->period == pwm->state.period &&
644 	    state->duty_cycle == pwm->state.duty_cycle &&
645 	    state->polarity == pwm->state.polarity &&
646 	    state->enabled == pwm->state.enabled &&
647 	    state->usage_power == pwm->state.usage_power)
648 		return 0;
649 
650 	if (chip->ops->apply)
651 		err = chip->ops->apply(chip, pwm, state);
652 	else
653 		err = pwm_apply_legacy(chip, pwm, state);
654 	if (err)
655 		return err;
656 
657 	trace_pwm_apply(pwm, state);
658 
659 	pwm->state = *state;
660 
661 	/*
662 	 * only do this after pwm->state was applied as some
663 	 * implementations of .get_state depend on this
664 	 */
665 	pwm_apply_state_debug(pwm, state);
666 
667 	return 0;
668 }
669 EXPORT_SYMBOL_GPL(pwm_apply_state);
670 
671 /**
672  * pwm_capture() - capture and report a PWM signal
673  * @pwm: PWM device
674  * @result: structure to fill with capture result
675  * @timeout: time to wait, in milliseconds, before giving up on capture
676  *
677  * Returns: 0 on success or a negative error code on failure.
678  */
679 int pwm_capture(struct pwm_device *pwm, struct pwm_capture *result,
680 		unsigned long timeout)
681 {
682 	int err;
683 
684 	if (!pwm || !pwm->chip->ops)
685 		return -EINVAL;
686 
687 	if (!pwm->chip->ops->capture)
688 		return -ENOSYS;
689 
690 	mutex_lock(&pwm_lock);
691 	err = pwm->chip->ops->capture(pwm->chip, pwm, result, timeout);
692 	mutex_unlock(&pwm_lock);
693 
694 	return err;
695 }
696 EXPORT_SYMBOL_GPL(pwm_capture);
697 
698 /**
699  * pwm_adjust_config() - adjust the current PWM config to the PWM arguments
700  * @pwm: PWM device
701  *
702  * This function will adjust the PWM config to the PWM arguments provided
703  * by the DT or PWM lookup table. This is particularly useful to adapt
704  * the bootloader config to the Linux one.
705  */
706 int pwm_adjust_config(struct pwm_device *pwm)
707 {
708 	struct pwm_state state;
709 	struct pwm_args pargs;
710 
711 	pwm_get_args(pwm, &pargs);
712 	pwm_get_state(pwm, &state);
713 
714 	/*
715 	 * If the current period is zero it means that either the PWM driver
716 	 * does not support initial state retrieval or the PWM has not yet
717 	 * been configured.
718 	 *
719 	 * In either case, we setup the new period and polarity, and assign a
720 	 * duty cycle of 0.
721 	 */
722 	if (!state.period) {
723 		state.duty_cycle = 0;
724 		state.period = pargs.period;
725 		state.polarity = pargs.polarity;
726 
727 		return pwm_apply_state(pwm, &state);
728 	}
729 
730 	/*
731 	 * Adjust the PWM duty cycle/period based on the period value provided
732 	 * in PWM args.
733 	 */
734 	if (pargs.period != state.period) {
735 		u64 dutycycle = (u64)state.duty_cycle * pargs.period;
736 
737 		do_div(dutycycle, state.period);
738 		state.duty_cycle = dutycycle;
739 		state.period = pargs.period;
740 	}
741 
742 	/*
743 	 * If the polarity changed, we should also change the duty cycle.
744 	 */
745 	if (pargs.polarity != state.polarity) {
746 		state.polarity = pargs.polarity;
747 		state.duty_cycle = state.period - state.duty_cycle;
748 	}
749 
750 	return pwm_apply_state(pwm, &state);
751 }
752 EXPORT_SYMBOL_GPL(pwm_adjust_config);
753 
754 static struct pwm_chip *fwnode_to_pwmchip(struct fwnode_handle *fwnode)
755 {
756 	struct pwm_chip *chip;
757 
758 	mutex_lock(&pwm_lock);
759 
760 	list_for_each_entry(chip, &pwm_chips, list)
761 		if (chip->dev && dev_fwnode(chip->dev) == fwnode) {
762 			mutex_unlock(&pwm_lock);
763 			return chip;
764 		}
765 
766 	mutex_unlock(&pwm_lock);
767 
768 	return ERR_PTR(-EPROBE_DEFER);
769 }
770 
771 static struct device_link *pwm_device_link_add(struct device *dev,
772 					       struct pwm_device *pwm)
773 {
774 	struct device_link *dl;
775 
776 	if (!dev) {
777 		/*
778 		 * No device for the PWM consumer has been provided. It may
779 		 * impact the PM sequence ordering: the PWM supplier may get
780 		 * suspended before the consumer.
781 		 */
782 		dev_warn(pwm->chip->dev,
783 			 "No consumer device specified to create a link to\n");
784 		return NULL;
785 	}
786 
787 	dl = device_link_add(dev, pwm->chip->dev, DL_FLAG_AUTOREMOVE_CONSUMER);
788 	if (!dl) {
789 		dev_err(dev, "failed to create device link to %s\n",
790 			dev_name(pwm->chip->dev));
791 		return ERR_PTR(-EINVAL);
792 	}
793 
794 	return dl;
795 }
796 
797 /**
798  * of_pwm_get() - request a PWM via the PWM framework
799  * @dev: device for PWM consumer
800  * @np: device node to get the PWM from
801  * @con_id: consumer name
802  *
803  * Returns the PWM device parsed from the phandle and index specified in the
804  * "pwms" property of a device tree node or a negative error-code on failure.
805  * Values parsed from the device tree are stored in the returned PWM device
806  * object.
807  *
808  * If con_id is NULL, the first PWM device listed in the "pwms" property will
809  * be requested. Otherwise the "pwm-names" property is used to do a reverse
810  * lookup of the PWM index. This also means that the "pwm-names" property
811  * becomes mandatory for devices that look up the PWM device via the con_id
812  * parameter.
813  *
814  * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
815  * error code on failure.
816  */
817 struct pwm_device *of_pwm_get(struct device *dev, struct device_node *np,
818 			      const char *con_id)
819 {
820 	struct pwm_device *pwm = NULL;
821 	struct of_phandle_args args;
822 	struct device_link *dl;
823 	struct pwm_chip *pc;
824 	int index = 0;
825 	int err;
826 
827 	if (con_id) {
828 		index = of_property_match_string(np, "pwm-names", con_id);
829 		if (index < 0)
830 			return ERR_PTR(index);
831 	}
832 
833 	err = of_parse_phandle_with_args(np, "pwms", "#pwm-cells", index,
834 					 &args);
835 	if (err) {
836 		pr_err("%s(): can't parse \"pwms\" property\n", __func__);
837 		return ERR_PTR(err);
838 	}
839 
840 	pc = fwnode_to_pwmchip(of_fwnode_handle(args.np));
841 	if (IS_ERR(pc)) {
842 		if (PTR_ERR(pc) != -EPROBE_DEFER)
843 			pr_err("%s(): PWM chip not found\n", __func__);
844 
845 		pwm = ERR_CAST(pc);
846 		goto put;
847 	}
848 
849 	pwm = pc->of_xlate(pc, &args);
850 	if (IS_ERR(pwm))
851 		goto put;
852 
853 	dl = pwm_device_link_add(dev, pwm);
854 	if (IS_ERR(dl)) {
855 		/* of_xlate ended up calling pwm_request_from_chip() */
856 		pwm_free(pwm);
857 		pwm = ERR_CAST(dl);
858 		goto put;
859 	}
860 
861 	/*
862 	 * If a consumer name was not given, try to look it up from the
863 	 * "pwm-names" property if it exists. Otherwise use the name of
864 	 * the user device node.
865 	 */
866 	if (!con_id) {
867 		err = of_property_read_string_index(np, "pwm-names", index,
868 						    &con_id);
869 		if (err < 0)
870 			con_id = np->name;
871 	}
872 
873 	pwm->label = con_id;
874 
875 put:
876 	of_node_put(args.np);
877 
878 	return pwm;
879 }
880 EXPORT_SYMBOL_GPL(of_pwm_get);
881 
882 /**
883  * acpi_pwm_get() - request a PWM via parsing "pwms" property in ACPI
884  * @fwnode: firmware node to get the "pwms" property from
885  *
886  * Returns the PWM device parsed from the fwnode and index specified in the
887  * "pwms" property or a negative error-code on failure.
888  * Values parsed from the device tree are stored in the returned PWM device
889  * object.
890  *
891  * This is analogous to of_pwm_get() except con_id is not yet supported.
892  * ACPI entries must look like
893  * Package () {"pwms", Package ()
894  *     { <PWM device reference>, <PWM index>, <PWM period> [, <PWM flags>]}}
895  *
896  * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
897  * error code on failure.
898  */
899 static struct pwm_device *acpi_pwm_get(const struct fwnode_handle *fwnode)
900 {
901 	struct pwm_device *pwm;
902 	struct fwnode_reference_args args;
903 	struct pwm_chip *chip;
904 	int ret;
905 
906 	memset(&args, 0, sizeof(args));
907 
908 	ret = __acpi_node_get_property_reference(fwnode, "pwms", 0, 3, &args);
909 	if (ret < 0)
910 		return ERR_PTR(ret);
911 
912 	if (args.nargs < 2)
913 		return ERR_PTR(-EPROTO);
914 
915 	chip = fwnode_to_pwmchip(args.fwnode);
916 	if (IS_ERR(chip))
917 		return ERR_CAST(chip);
918 
919 	pwm = pwm_request_from_chip(chip, args.args[0], NULL);
920 	if (IS_ERR(pwm))
921 		return pwm;
922 
923 	pwm->args.period = args.args[1];
924 	pwm->args.polarity = PWM_POLARITY_NORMAL;
925 
926 	if (args.nargs > 2 && args.args[2] & PWM_POLARITY_INVERTED)
927 		pwm->args.polarity = PWM_POLARITY_INVERSED;
928 
929 	return pwm;
930 }
931 
932 /**
933  * pwm_add_table() - register PWM device consumers
934  * @table: array of consumers to register
935  * @num: number of consumers in table
936  */
937 void pwm_add_table(struct pwm_lookup *table, size_t num)
938 {
939 	mutex_lock(&pwm_lookup_lock);
940 
941 	while (num--) {
942 		list_add_tail(&table->list, &pwm_lookup_list);
943 		table++;
944 	}
945 
946 	mutex_unlock(&pwm_lookup_lock);
947 }
948 
949 /**
950  * pwm_remove_table() - unregister PWM device consumers
951  * @table: array of consumers to unregister
952  * @num: number of consumers in table
953  */
954 void pwm_remove_table(struct pwm_lookup *table, size_t num)
955 {
956 	mutex_lock(&pwm_lookup_lock);
957 
958 	while (num--) {
959 		list_del(&table->list);
960 		table++;
961 	}
962 
963 	mutex_unlock(&pwm_lookup_lock);
964 }
965 
966 /**
967  * pwm_get() - look up and request a PWM device
968  * @dev: device for PWM consumer
969  * @con_id: consumer name
970  *
971  * Lookup is first attempted using DT. If the device was not instantiated from
972  * a device tree, a PWM chip and a relative index is looked up via a table
973  * supplied by board setup code (see pwm_add_table()).
974  *
975  * Once a PWM chip has been found the specified PWM device will be requested
976  * and is ready to be used.
977  *
978  * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
979  * error code on failure.
980  */
981 struct pwm_device *pwm_get(struct device *dev, const char *con_id)
982 {
983 	const struct fwnode_handle *fwnode = dev ? dev_fwnode(dev) : NULL;
984 	const char *dev_id = dev ? dev_name(dev) : NULL;
985 	struct pwm_device *pwm;
986 	struct pwm_chip *chip;
987 	struct device_link *dl;
988 	unsigned int best = 0;
989 	struct pwm_lookup *p, *chosen = NULL;
990 	unsigned int match;
991 	int err;
992 
993 	/* look up via DT first */
994 	if (is_of_node(fwnode))
995 		return of_pwm_get(dev, to_of_node(fwnode), con_id);
996 
997 	/* then lookup via ACPI */
998 	if (is_acpi_node(fwnode)) {
999 		pwm = acpi_pwm_get(fwnode);
1000 		if (!IS_ERR(pwm) || PTR_ERR(pwm) != -ENOENT)
1001 			return pwm;
1002 	}
1003 
1004 	/*
1005 	 * We look up the provider in the static table typically provided by
1006 	 * board setup code. We first try to lookup the consumer device by
1007 	 * name. If the consumer device was passed in as NULL or if no match
1008 	 * was found, we try to find the consumer by directly looking it up
1009 	 * by name.
1010 	 *
1011 	 * If a match is found, the provider PWM chip is looked up by name
1012 	 * and a PWM device is requested using the PWM device per-chip index.
1013 	 *
1014 	 * The lookup algorithm was shamelessly taken from the clock
1015 	 * framework:
1016 	 *
1017 	 * We do slightly fuzzy matching here:
1018 	 *  An entry with a NULL ID is assumed to be a wildcard.
1019 	 *  If an entry has a device ID, it must match
1020 	 *  If an entry has a connection ID, it must match
1021 	 * Then we take the most specific entry - with the following order
1022 	 * of precedence: dev+con > dev only > con only.
1023 	 */
1024 	mutex_lock(&pwm_lookup_lock);
1025 
1026 	list_for_each_entry(p, &pwm_lookup_list, list) {
1027 		match = 0;
1028 
1029 		if (p->dev_id) {
1030 			if (!dev_id || strcmp(p->dev_id, dev_id))
1031 				continue;
1032 
1033 			match += 2;
1034 		}
1035 
1036 		if (p->con_id) {
1037 			if (!con_id || strcmp(p->con_id, con_id))
1038 				continue;
1039 
1040 			match += 1;
1041 		}
1042 
1043 		if (match > best) {
1044 			chosen = p;
1045 
1046 			if (match != 3)
1047 				best = match;
1048 			else
1049 				break;
1050 		}
1051 	}
1052 
1053 	mutex_unlock(&pwm_lookup_lock);
1054 
1055 	if (!chosen)
1056 		return ERR_PTR(-ENODEV);
1057 
1058 	chip = pwmchip_find_by_name(chosen->provider);
1059 
1060 	/*
1061 	 * If the lookup entry specifies a module, load the module and retry
1062 	 * the PWM chip lookup. This can be used to work around driver load
1063 	 * ordering issues if driver's can't be made to properly support the
1064 	 * deferred probe mechanism.
1065 	 */
1066 	if (!chip && chosen->module) {
1067 		err = request_module(chosen->module);
1068 		if (err == 0)
1069 			chip = pwmchip_find_by_name(chosen->provider);
1070 	}
1071 
1072 	if (!chip)
1073 		return ERR_PTR(-EPROBE_DEFER);
1074 
1075 	pwm = pwm_request_from_chip(chip, chosen->index, con_id ?: dev_id);
1076 	if (IS_ERR(pwm))
1077 		return pwm;
1078 
1079 	dl = pwm_device_link_add(dev, pwm);
1080 	if (IS_ERR(dl)) {
1081 		pwm_free(pwm);
1082 		return ERR_CAST(dl);
1083 	}
1084 
1085 	pwm->args.period = chosen->period;
1086 	pwm->args.polarity = chosen->polarity;
1087 
1088 	return pwm;
1089 }
1090 EXPORT_SYMBOL_GPL(pwm_get);
1091 
1092 /**
1093  * pwm_put() - release a PWM device
1094  * @pwm: PWM device
1095  */
1096 void pwm_put(struct pwm_device *pwm)
1097 {
1098 	if (!pwm)
1099 		return;
1100 
1101 	mutex_lock(&pwm_lock);
1102 
1103 	if (!test_and_clear_bit(PWMF_REQUESTED, &pwm->flags)) {
1104 		pr_warn("PWM device already freed\n");
1105 		goto out;
1106 	}
1107 
1108 	if (pwm->chip->ops->free)
1109 		pwm->chip->ops->free(pwm->chip, pwm);
1110 
1111 	pwm_set_chip_data(pwm, NULL);
1112 	pwm->label = NULL;
1113 
1114 	module_put(pwm->chip->ops->owner);
1115 out:
1116 	mutex_unlock(&pwm_lock);
1117 }
1118 EXPORT_SYMBOL_GPL(pwm_put);
1119 
1120 static void devm_pwm_release(void *pwm)
1121 {
1122 	pwm_put(pwm);
1123 }
1124 
1125 /**
1126  * devm_pwm_get() - resource managed pwm_get()
1127  * @dev: device for PWM consumer
1128  * @con_id: consumer name
1129  *
1130  * This function performs like pwm_get() but the acquired PWM device will
1131  * automatically be released on driver detach.
1132  *
1133  * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
1134  * error code on failure.
1135  */
1136 struct pwm_device *devm_pwm_get(struct device *dev, const char *con_id)
1137 {
1138 	struct pwm_device *pwm;
1139 	int ret;
1140 
1141 	pwm = pwm_get(dev, con_id);
1142 	if (IS_ERR(pwm))
1143 		return pwm;
1144 
1145 	ret = devm_add_action_or_reset(dev, devm_pwm_release, pwm);
1146 	if (ret)
1147 		return ERR_PTR(ret);
1148 
1149 	return pwm;
1150 }
1151 EXPORT_SYMBOL_GPL(devm_pwm_get);
1152 
1153 /**
1154  * devm_of_pwm_get() - resource managed of_pwm_get()
1155  * @dev: device for PWM consumer
1156  * @np: device node to get the PWM from
1157  * @con_id: consumer name
1158  *
1159  * This function performs like of_pwm_get() but the acquired PWM device will
1160  * automatically be released on driver detach.
1161  *
1162  * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
1163  * error code on failure.
1164  */
1165 struct pwm_device *devm_of_pwm_get(struct device *dev, struct device_node *np,
1166 				   const char *con_id)
1167 {
1168 	struct pwm_device *pwm;
1169 	int ret;
1170 
1171 	pwm = of_pwm_get(dev, np, con_id);
1172 	if (IS_ERR(pwm))
1173 		return pwm;
1174 
1175 	ret = devm_add_action_or_reset(dev, devm_pwm_release, pwm);
1176 	if (ret)
1177 		return ERR_PTR(ret);
1178 
1179 	return pwm;
1180 }
1181 EXPORT_SYMBOL_GPL(devm_of_pwm_get);
1182 
1183 /**
1184  * devm_fwnode_pwm_get() - request a resource managed PWM from firmware node
1185  * @dev: device for PWM consumer
1186  * @fwnode: firmware node to get the PWM from
1187  * @con_id: consumer name
1188  *
1189  * Returns the PWM device parsed from the firmware node. See of_pwm_get() and
1190  * acpi_pwm_get() for a detailed description.
1191  *
1192  * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
1193  * error code on failure.
1194  */
1195 struct pwm_device *devm_fwnode_pwm_get(struct device *dev,
1196 				       struct fwnode_handle *fwnode,
1197 				       const char *con_id)
1198 {
1199 	struct pwm_device *pwm = ERR_PTR(-ENODEV);
1200 	int ret;
1201 
1202 	if (is_of_node(fwnode))
1203 		pwm = of_pwm_get(dev, to_of_node(fwnode), con_id);
1204 	else if (is_acpi_node(fwnode))
1205 		pwm = acpi_pwm_get(fwnode);
1206 	if (IS_ERR(pwm))
1207 		return pwm;
1208 
1209 	ret = devm_add_action_or_reset(dev, devm_pwm_release, pwm);
1210 	if (ret)
1211 		return ERR_PTR(ret);
1212 
1213 	return pwm;
1214 }
1215 EXPORT_SYMBOL_GPL(devm_fwnode_pwm_get);
1216 
1217 #ifdef CONFIG_DEBUG_FS
1218 static void pwm_dbg_show(struct pwm_chip *chip, struct seq_file *s)
1219 {
1220 	unsigned int i;
1221 
1222 	for (i = 0; i < chip->npwm; i++) {
1223 		struct pwm_device *pwm = &chip->pwms[i];
1224 		struct pwm_state state;
1225 
1226 		pwm_get_state(pwm, &state);
1227 
1228 		seq_printf(s, " pwm-%-3d (%-20.20s):", i, pwm->label);
1229 
1230 		if (test_bit(PWMF_REQUESTED, &pwm->flags))
1231 			seq_puts(s, " requested");
1232 
1233 		if (state.enabled)
1234 			seq_puts(s, " enabled");
1235 
1236 		seq_printf(s, " period: %llu ns", state.period);
1237 		seq_printf(s, " duty: %llu ns", state.duty_cycle);
1238 		seq_printf(s, " polarity: %s",
1239 			   state.polarity ? "inverse" : "normal");
1240 
1241 		if (state.usage_power)
1242 			seq_puts(s, " usage_power");
1243 
1244 		seq_puts(s, "\n");
1245 	}
1246 }
1247 
1248 static void *pwm_seq_start(struct seq_file *s, loff_t *pos)
1249 {
1250 	mutex_lock(&pwm_lock);
1251 	s->private = "";
1252 
1253 	return seq_list_start(&pwm_chips, *pos);
1254 }
1255 
1256 static void *pwm_seq_next(struct seq_file *s, void *v, loff_t *pos)
1257 {
1258 	s->private = "\n";
1259 
1260 	return seq_list_next(v, &pwm_chips, pos);
1261 }
1262 
1263 static void pwm_seq_stop(struct seq_file *s, void *v)
1264 {
1265 	mutex_unlock(&pwm_lock);
1266 }
1267 
1268 static int pwm_seq_show(struct seq_file *s, void *v)
1269 {
1270 	struct pwm_chip *chip = list_entry(v, struct pwm_chip, list);
1271 
1272 	seq_printf(s, "%s%s/%s, %d PWM device%s\n", (char *)s->private,
1273 		   chip->dev->bus ? chip->dev->bus->name : "no-bus",
1274 		   dev_name(chip->dev), chip->npwm,
1275 		   (chip->npwm != 1) ? "s" : "");
1276 
1277 	pwm_dbg_show(chip, s);
1278 
1279 	return 0;
1280 }
1281 
1282 static const struct seq_operations pwm_debugfs_sops = {
1283 	.start = pwm_seq_start,
1284 	.next = pwm_seq_next,
1285 	.stop = pwm_seq_stop,
1286 	.show = pwm_seq_show,
1287 };
1288 
1289 DEFINE_SEQ_ATTRIBUTE(pwm_debugfs);
1290 
1291 static int __init pwm_debugfs_init(void)
1292 {
1293 	debugfs_create_file("pwm", S_IFREG | 0444, NULL, NULL,
1294 			    &pwm_debugfs_fops);
1295 
1296 	return 0;
1297 }
1298 subsys_initcall(pwm_debugfs_init);
1299 #endif /* CONFIG_DEBUG_FS */
1300