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