• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define DEFAULT_SYMBOL_NAMESPACE "PWM"
10 
11 #include <linux/acpi.h>
12 #include <linux/module.h>
13 #include <linux/idr.h>
14 #include <linux/of.h>
15 #include <linux/pwm.h>
16 #include <linux/list.h>
17 #include <linux/mutex.h>
18 #include <linux/err.h>
19 #include <linux/slab.h>
20 #include <linux/device.h>
21 #include <linux/debugfs.h>
22 #include <linux/seq_file.h>
23 
24 #include <dt-bindings/pwm/pwm.h>
25 
26 #define CREATE_TRACE_POINTS
27 #include <trace/events/pwm.h>
28 
29 /* protects access to pwm_chips */
30 static DEFINE_MUTEX(pwm_lock);
31 
32 static DEFINE_IDR(pwm_chips);
33 
pwm_apply_debug(struct pwm_device * pwm,const struct pwm_state * state)34 static void pwm_apply_debug(struct pwm_device *pwm,
35 			    const struct pwm_state *state)
36 {
37 	struct pwm_state *last = &pwm->last;
38 	struct pwm_chip *chip = pwm->chip;
39 	struct pwm_state s1 = { 0 }, s2 = { 0 };
40 	int err;
41 
42 	if (!IS_ENABLED(CONFIG_PWM_DEBUG))
43 		return;
44 
45 	/* No reasonable diagnosis possible without .get_state() */
46 	if (!chip->ops->get_state)
47 		return;
48 
49 	/*
50 	 * *state was just applied. Read out the hardware state and do some
51 	 * checks.
52 	 */
53 
54 	err = chip->ops->get_state(chip, pwm, &s1);
55 	trace_pwm_get(pwm, &s1, err);
56 	if (err)
57 		/* If that failed there isn't much to debug */
58 		return;
59 
60 	/*
61 	 * The lowlevel driver either ignored .polarity (which is a bug) or as
62 	 * best effort inverted .polarity and fixed .duty_cycle respectively.
63 	 * Undo this inversion and fixup for further tests.
64 	 */
65 	if (s1.enabled && s1.polarity != state->polarity) {
66 		s2.polarity = state->polarity;
67 		s2.duty_cycle = s1.period - s1.duty_cycle;
68 		s2.period = s1.period;
69 		s2.enabled = s1.enabled;
70 	} else {
71 		s2 = s1;
72 	}
73 
74 	if (s2.polarity != state->polarity &&
75 	    state->duty_cycle < state->period)
76 		dev_warn(pwmchip_parent(chip), ".apply ignored .polarity\n");
77 
78 	if (state->enabled && s2.enabled &&
79 	    last->polarity == state->polarity &&
80 	    last->period > s2.period &&
81 	    last->period <= state->period)
82 		dev_warn(pwmchip_parent(chip),
83 			 ".apply didn't pick the best available period (requested: %llu, applied: %llu, possible: %llu)\n",
84 			 state->period, s2.period, last->period);
85 
86 	/*
87 	 * Rounding period up is fine only if duty_cycle is 0 then, because a
88 	 * flat line doesn't have a characteristic period.
89 	 */
90 	if (state->enabled && s2.enabled && state->period < s2.period && s2.duty_cycle)
91 		dev_warn(pwmchip_parent(chip),
92 			 ".apply is supposed to round down period (requested: %llu, applied: %llu)\n",
93 			 state->period, s2.period);
94 
95 	if (state->enabled &&
96 	    last->polarity == state->polarity &&
97 	    last->period == s2.period &&
98 	    last->duty_cycle > s2.duty_cycle &&
99 	    last->duty_cycle <= state->duty_cycle)
100 		dev_warn(pwmchip_parent(chip),
101 			 ".apply didn't pick the best available duty cycle (requested: %llu/%llu, applied: %llu/%llu, possible: %llu/%llu)\n",
102 			 state->duty_cycle, state->period,
103 			 s2.duty_cycle, s2.period,
104 			 last->duty_cycle, last->period);
105 
106 	if (state->enabled && s2.enabled && state->duty_cycle < s2.duty_cycle)
107 		dev_warn(pwmchip_parent(chip),
108 			 ".apply is supposed to round down duty_cycle (requested: %llu/%llu, applied: %llu/%llu)\n",
109 			 state->duty_cycle, state->period,
110 			 s2.duty_cycle, s2.period);
111 
112 	if (!state->enabled && s2.enabled && s2.duty_cycle > 0)
113 		dev_warn(pwmchip_parent(chip),
114 			 "requested disabled, but yielded enabled with duty > 0\n");
115 
116 	/* reapply the state that the driver reported being configured. */
117 	err = chip->ops->apply(chip, pwm, &s1);
118 	trace_pwm_apply(pwm, &s1, err);
119 	if (err) {
120 		*last = s1;
121 		dev_err(pwmchip_parent(chip), "failed to reapply current setting\n");
122 		return;
123 	}
124 
125 	*last = (struct pwm_state){ 0 };
126 	err = chip->ops->get_state(chip, pwm, last);
127 	trace_pwm_get(pwm, last, err);
128 	if (err)
129 		return;
130 
131 	/* reapplication of the current state should give an exact match */
132 	if (s1.enabled != last->enabled ||
133 	    s1.polarity != last->polarity ||
134 	    (s1.enabled && s1.period != last->period) ||
135 	    (s1.enabled && s1.duty_cycle != last->duty_cycle)) {
136 		dev_err(pwmchip_parent(chip),
137 			".apply is not idempotent (ena=%d pol=%d %llu/%llu) -> (ena=%d pol=%d %llu/%llu)\n",
138 			s1.enabled, s1.polarity, s1.duty_cycle, s1.period,
139 			last->enabled, last->polarity, last->duty_cycle,
140 			last->period);
141 	}
142 }
143 
pwm_state_valid(const struct pwm_state * state)144 static bool pwm_state_valid(const struct pwm_state *state)
145 {
146 	/*
147 	 * For a disabled state all other state description is irrelevant and
148 	 * and supposed to be ignored. So also ignore any strange values and
149 	 * consider the state ok.
150 	 */
151 	if (!state->enabled)
152 		return true;
153 
154 	if (!state->period)
155 		return false;
156 
157 	if (state->duty_cycle > state->period)
158 		return false;
159 
160 	return true;
161 }
162 
163 /**
164  * __pwm_apply() - atomically apply a new state to a PWM device
165  * @pwm: PWM device
166  * @state: new state to apply
167  */
__pwm_apply(struct pwm_device * pwm,const struct pwm_state * state)168 static int __pwm_apply(struct pwm_device *pwm, const struct pwm_state *state)
169 {
170 	struct pwm_chip *chip;
171 	int err;
172 
173 	if (!pwm || !state)
174 		return -EINVAL;
175 
176 	if (!pwm_state_valid(state)) {
177 		/*
178 		 * Allow to transition from one invalid state to another.
179 		 * This ensures that you can e.g. change the polarity while
180 		 * the period is zero. (This happens on stm32 when the hardware
181 		 * is in its poweron default state.) This greatly simplifies
182 		 * working with the sysfs API where you can only change one
183 		 * parameter at a time.
184 		 */
185 		if (!pwm_state_valid(&pwm->state)) {
186 			pwm->state = *state;
187 			return 0;
188 		}
189 
190 		return -EINVAL;
191 	}
192 
193 	chip = pwm->chip;
194 
195 	if (state->period == pwm->state.period &&
196 	    state->duty_cycle == pwm->state.duty_cycle &&
197 	    state->polarity == pwm->state.polarity &&
198 	    state->enabled == pwm->state.enabled &&
199 	    state->usage_power == pwm->state.usage_power)
200 		return 0;
201 
202 	err = chip->ops->apply(chip, pwm, state);
203 	trace_pwm_apply(pwm, state, err);
204 	if (err)
205 		return err;
206 
207 	pwm->state = *state;
208 
209 	/*
210 	 * only do this after pwm->state was applied as some
211 	 * implementations of .get_state depend on this
212 	 */
213 	pwm_apply_debug(pwm, state);
214 
215 	return 0;
216 }
217 
218 /**
219  * pwm_apply_might_sleep() - atomically apply a new state to a PWM device
220  * Cannot be used in atomic context.
221  * @pwm: PWM device
222  * @state: new state to apply
223  */
pwm_apply_might_sleep(struct pwm_device * pwm,const struct pwm_state * state)224 int pwm_apply_might_sleep(struct pwm_device *pwm, const struct pwm_state *state)
225 {
226 	int err;
227 
228 	/*
229 	 * Some lowlevel driver's implementations of .apply() make use of
230 	 * mutexes, also with some drivers only returning when the new
231 	 * configuration is active calling pwm_apply_might_sleep() from atomic context
232 	 * is a bad idea. So make it explicit that calling this function might
233 	 * sleep.
234 	 */
235 	might_sleep();
236 
237 	if (IS_ENABLED(CONFIG_PWM_DEBUG) && pwm->chip->atomic) {
238 		/*
239 		 * Catch any drivers that have been marked as atomic but
240 		 * that will sleep anyway.
241 		 */
242 		non_block_start();
243 		err = __pwm_apply(pwm, state);
244 		non_block_end();
245 	} else {
246 		err = __pwm_apply(pwm, state);
247 	}
248 
249 	return err;
250 }
251 EXPORT_SYMBOL_GPL(pwm_apply_might_sleep);
252 
253 /**
254  * pwm_apply_atomic() - apply a new state to a PWM device from atomic context
255  * Not all PWM devices support this function, check with pwm_might_sleep().
256  * @pwm: PWM device
257  * @state: new state to apply
258  */
pwm_apply_atomic(struct pwm_device * pwm,const struct pwm_state * state)259 int pwm_apply_atomic(struct pwm_device *pwm, const struct pwm_state *state)
260 {
261 	WARN_ONCE(!pwm->chip->atomic,
262 		  "sleeping PWM driver used in atomic context\n");
263 
264 	return __pwm_apply(pwm, state);
265 }
266 EXPORT_SYMBOL_GPL(pwm_apply_atomic);
267 
268 /**
269  * pwm_adjust_config() - adjust the current PWM config to the PWM arguments
270  * @pwm: PWM device
271  *
272  * This function will adjust the PWM config to the PWM arguments provided
273  * by the DT or PWM lookup table. This is particularly useful to adapt
274  * the bootloader config to the Linux one.
275  */
pwm_adjust_config(struct pwm_device * pwm)276 int pwm_adjust_config(struct pwm_device *pwm)
277 {
278 	struct pwm_state state;
279 	struct pwm_args pargs;
280 
281 	pwm_get_args(pwm, &pargs);
282 	pwm_get_state(pwm, &state);
283 
284 	/*
285 	 * If the current period is zero it means that either the PWM driver
286 	 * does not support initial state retrieval or the PWM has not yet
287 	 * been configured.
288 	 *
289 	 * In either case, we setup the new period and polarity, and assign a
290 	 * duty cycle of 0.
291 	 */
292 	if (!state.period) {
293 		state.duty_cycle = 0;
294 		state.period = pargs.period;
295 		state.polarity = pargs.polarity;
296 
297 		return pwm_apply_might_sleep(pwm, &state);
298 	}
299 
300 	/*
301 	 * Adjust the PWM duty cycle/period based on the period value provided
302 	 * in PWM args.
303 	 */
304 	if (pargs.period != state.period) {
305 		u64 dutycycle = (u64)state.duty_cycle * pargs.period;
306 
307 		do_div(dutycycle, state.period);
308 		state.duty_cycle = dutycycle;
309 		state.period = pargs.period;
310 	}
311 
312 	/*
313 	 * If the polarity changed, we should also change the duty cycle.
314 	 */
315 	if (pargs.polarity != state.polarity) {
316 		state.polarity = pargs.polarity;
317 		state.duty_cycle = state.period - state.duty_cycle;
318 	}
319 
320 	return pwm_apply_might_sleep(pwm, &state);
321 }
322 EXPORT_SYMBOL_GPL(pwm_adjust_config);
323 
324 /**
325  * pwm_capture() - capture and report a PWM signal
326  * @pwm: PWM device
327  * @result: structure to fill with capture result
328  * @timeout: time to wait, in milliseconds, before giving up on capture
329  *
330  * Returns: 0 on success or a negative error code on failure.
331  */
pwm_capture(struct pwm_device * pwm,struct pwm_capture * result,unsigned long timeout)332 static int pwm_capture(struct pwm_device *pwm, struct pwm_capture *result,
333 		       unsigned long timeout)
334 {
335 	struct pwm_chip *chip = pwm->chip;
336 	const struct pwm_ops *ops = chip->ops;
337 
338 	if (!ops->capture)
339 		return -ENOSYS;
340 
341 	guard(mutex)(&pwm_lock);
342 
343 	return ops->capture(chip, pwm, result, timeout);
344 }
345 
pwmchip_find_by_name(const char * name)346 static struct pwm_chip *pwmchip_find_by_name(const char *name)
347 {
348 	struct pwm_chip *chip;
349 	unsigned long id, tmp;
350 
351 	if (!name)
352 		return NULL;
353 
354 	guard(mutex)(&pwm_lock);
355 
356 	idr_for_each_entry_ul(&pwm_chips, chip, tmp, id) {
357 		const char *chip_name = dev_name(pwmchip_parent(chip));
358 
359 		if (chip_name && strcmp(chip_name, name) == 0)
360 			return chip;
361 	}
362 
363 	return NULL;
364 }
365 
pwm_device_request(struct pwm_device * pwm,const char * label)366 static int pwm_device_request(struct pwm_device *pwm, const char *label)
367 {
368 	int err;
369 	struct pwm_chip *chip = pwm->chip;
370 	const struct pwm_ops *ops = chip->ops;
371 
372 	if (test_bit(PWMF_REQUESTED, &pwm->flags))
373 		return -EBUSY;
374 
375 	if (!try_module_get(chip->owner))
376 		return -ENODEV;
377 
378 	if (!get_device(&chip->dev)) {
379 		err = -ENODEV;
380 		goto err_get_device;
381 	}
382 
383 	if (ops->request) {
384 		err = ops->request(chip, pwm);
385 		if (err) {
386 			put_device(&chip->dev);
387 err_get_device:
388 			module_put(chip->owner);
389 			return err;
390 		}
391 	}
392 
393 	if (ops->get_state) {
394 		/*
395 		 * Zero-initialize state because most drivers are unaware of
396 		 * .usage_power. The other members of state are supposed to be
397 		 * set by lowlevel drivers. We still initialize the whole
398 		 * structure for simplicity even though this might paper over
399 		 * faulty implementations of .get_state().
400 		 */
401 		struct pwm_state state = { 0, };
402 
403 		err = ops->get_state(chip, pwm, &state);
404 		trace_pwm_get(pwm, &state, err);
405 
406 		if (!err)
407 			pwm->state = state;
408 
409 		if (IS_ENABLED(CONFIG_PWM_DEBUG))
410 			pwm->last = pwm->state;
411 	}
412 
413 	set_bit(PWMF_REQUESTED, &pwm->flags);
414 	pwm->label = label;
415 
416 	return 0;
417 }
418 
419 /**
420  * pwm_request_from_chip() - request a PWM device relative to a PWM chip
421  * @chip: PWM chip
422  * @index: per-chip index of the PWM to request
423  * @label: a literal description string of this PWM
424  *
425  * Returns: A pointer to the PWM device at the given index of the given PWM
426  * chip. A negative error code is returned if the index is not valid for the
427  * specified PWM chip or if the PWM device cannot be requested.
428  */
pwm_request_from_chip(struct pwm_chip * chip,unsigned int index,const char * label)429 static struct pwm_device *pwm_request_from_chip(struct pwm_chip *chip,
430 						unsigned int index,
431 						const char *label)
432 {
433 	struct pwm_device *pwm;
434 	int err;
435 
436 	if (!chip || index >= chip->npwm)
437 		return ERR_PTR(-EINVAL);
438 
439 	guard(mutex)(&pwm_lock);
440 
441 	pwm = &chip->pwms[index];
442 
443 	err = pwm_device_request(pwm, label);
444 	if (err < 0)
445 		return ERR_PTR(err);
446 
447 	return pwm;
448 }
449 
450 struct pwm_device *
of_pwm_xlate_with_flags(struct pwm_chip * chip,const struct of_phandle_args * args)451 of_pwm_xlate_with_flags(struct pwm_chip *chip, const struct of_phandle_args *args)
452 {
453 	struct pwm_device *pwm;
454 
455 	/* period in the second cell and flags in the third cell are optional */
456 	if (args->args_count < 1)
457 		return ERR_PTR(-EINVAL);
458 
459 	pwm = pwm_request_from_chip(chip, args->args[0], NULL);
460 	if (IS_ERR(pwm))
461 		return pwm;
462 
463 	if (args->args_count > 1)
464 		pwm->args.period = args->args[1];
465 
466 	pwm->args.polarity = PWM_POLARITY_NORMAL;
467 	if (args->args_count > 2 && args->args[2] & PWM_POLARITY_INVERTED)
468 		pwm->args.polarity = PWM_POLARITY_INVERSED;
469 
470 	return pwm;
471 }
472 EXPORT_SYMBOL_GPL(of_pwm_xlate_with_flags);
473 
474 struct pwm_device *
of_pwm_single_xlate(struct pwm_chip * chip,const struct of_phandle_args * args)475 of_pwm_single_xlate(struct pwm_chip *chip, const struct of_phandle_args *args)
476 {
477 	struct pwm_device *pwm;
478 
479 	pwm = pwm_request_from_chip(chip, 0, NULL);
480 	if (IS_ERR(pwm))
481 		return pwm;
482 
483 	if (args->args_count > 0)
484 		pwm->args.period = args->args[0];
485 
486 	pwm->args.polarity = PWM_POLARITY_NORMAL;
487 	if (args->args_count > 1 && args->args[1] & PWM_POLARITY_INVERTED)
488 		pwm->args.polarity = PWM_POLARITY_INVERSED;
489 
490 	return pwm;
491 }
492 EXPORT_SYMBOL_GPL(of_pwm_single_xlate);
493 
494 struct pwm_export {
495 	struct device pwm_dev;
496 	struct pwm_device *pwm;
497 	struct mutex lock;
498 	struct pwm_state suspend;
499 };
500 
pwmchip_from_dev(struct device * pwmchip_dev)501 static inline struct pwm_chip *pwmchip_from_dev(struct device *pwmchip_dev)
502 {
503 	return container_of(pwmchip_dev, struct pwm_chip, dev);
504 }
505 
pwmexport_from_dev(struct device * pwm_dev)506 static inline struct pwm_export *pwmexport_from_dev(struct device *pwm_dev)
507 {
508 	return container_of(pwm_dev, struct pwm_export, pwm_dev);
509 }
510 
pwm_from_dev(struct device * pwm_dev)511 static inline struct pwm_device *pwm_from_dev(struct device *pwm_dev)
512 {
513 	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
514 
515 	return export->pwm;
516 }
517 
period_show(struct device * pwm_dev,struct device_attribute * attr,char * buf)518 static ssize_t period_show(struct device *pwm_dev,
519 			   struct device_attribute *attr,
520 			   char *buf)
521 {
522 	const struct pwm_device *pwm = pwm_from_dev(pwm_dev);
523 	struct pwm_state state;
524 
525 	pwm_get_state(pwm, &state);
526 
527 	return sysfs_emit(buf, "%llu\n", state.period);
528 }
529 
period_store(struct device * pwm_dev,struct device_attribute * attr,const char * buf,size_t size)530 static ssize_t period_store(struct device *pwm_dev,
531 			    struct device_attribute *attr,
532 			    const char *buf, size_t size)
533 {
534 	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
535 	struct pwm_device *pwm = export->pwm;
536 	struct pwm_state state;
537 	u64 val;
538 	int ret;
539 
540 	ret = kstrtou64(buf, 0, &val);
541 	if (ret)
542 		return ret;
543 
544 	guard(mutex)(&export->lock);
545 
546 	pwm_get_state(pwm, &state);
547 	state.period = val;
548 	ret = pwm_apply_might_sleep(pwm, &state);
549 
550 	return ret ? : size;
551 }
552 
duty_cycle_show(struct device * pwm_dev,struct device_attribute * attr,char * buf)553 static ssize_t duty_cycle_show(struct device *pwm_dev,
554 			       struct device_attribute *attr,
555 			       char *buf)
556 {
557 	const struct pwm_device *pwm = pwm_from_dev(pwm_dev);
558 	struct pwm_state state;
559 
560 	pwm_get_state(pwm, &state);
561 
562 	return sysfs_emit(buf, "%llu\n", state.duty_cycle);
563 }
564 
duty_cycle_store(struct device * pwm_dev,struct device_attribute * attr,const char * buf,size_t size)565 static ssize_t duty_cycle_store(struct device *pwm_dev,
566 				struct device_attribute *attr,
567 				const char *buf, size_t size)
568 {
569 	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
570 	struct pwm_device *pwm = export->pwm;
571 	struct pwm_state state;
572 	u64 val;
573 	int ret;
574 
575 	ret = kstrtou64(buf, 0, &val);
576 	if (ret)
577 		return ret;
578 
579 	guard(mutex)(&export->lock);
580 
581 	pwm_get_state(pwm, &state);
582 	state.duty_cycle = val;
583 	ret = pwm_apply_might_sleep(pwm, &state);
584 
585 	return ret ? : size;
586 }
587 
enable_show(struct device * pwm_dev,struct device_attribute * attr,char * buf)588 static ssize_t enable_show(struct device *pwm_dev,
589 			   struct device_attribute *attr,
590 			   char *buf)
591 {
592 	const struct pwm_device *pwm = pwm_from_dev(pwm_dev);
593 	struct pwm_state state;
594 
595 	pwm_get_state(pwm, &state);
596 
597 	return sysfs_emit(buf, "%d\n", state.enabled);
598 }
599 
enable_store(struct device * pwm_dev,struct device_attribute * attr,const char * buf,size_t size)600 static ssize_t enable_store(struct device *pwm_dev,
601 			    struct device_attribute *attr,
602 			    const char *buf, size_t size)
603 {
604 	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
605 	struct pwm_device *pwm = export->pwm;
606 	struct pwm_state state;
607 	int val, ret;
608 
609 	ret = kstrtoint(buf, 0, &val);
610 	if (ret)
611 		return ret;
612 
613 	guard(mutex)(&export->lock);
614 
615 	pwm_get_state(pwm, &state);
616 
617 	switch (val) {
618 	case 0:
619 		state.enabled = false;
620 		break;
621 	case 1:
622 		state.enabled = true;
623 		break;
624 	default:
625 		return -EINVAL;
626 	}
627 
628 	ret = pwm_apply_might_sleep(pwm, &state);
629 
630 	return ret ? : size;
631 }
632 
polarity_show(struct device * pwm_dev,struct device_attribute * attr,char * buf)633 static ssize_t polarity_show(struct device *pwm_dev,
634 			     struct device_attribute *attr,
635 			     char *buf)
636 {
637 	const struct pwm_device *pwm = pwm_from_dev(pwm_dev);
638 	const char *polarity = "unknown";
639 	struct pwm_state state;
640 
641 	pwm_get_state(pwm, &state);
642 
643 	switch (state.polarity) {
644 	case PWM_POLARITY_NORMAL:
645 		polarity = "normal";
646 		break;
647 
648 	case PWM_POLARITY_INVERSED:
649 		polarity = "inversed";
650 		break;
651 	}
652 
653 	return sysfs_emit(buf, "%s\n", polarity);
654 }
655 
polarity_store(struct device * pwm_dev,struct device_attribute * attr,const char * buf,size_t size)656 static ssize_t polarity_store(struct device *pwm_dev,
657 			      struct device_attribute *attr,
658 			      const char *buf, size_t size)
659 {
660 	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
661 	struct pwm_device *pwm = export->pwm;
662 	enum pwm_polarity polarity;
663 	struct pwm_state state;
664 	int ret;
665 
666 	if (sysfs_streq(buf, "normal"))
667 		polarity = PWM_POLARITY_NORMAL;
668 	else if (sysfs_streq(buf, "inversed"))
669 		polarity = PWM_POLARITY_INVERSED;
670 	else
671 		return -EINVAL;
672 
673 	guard(mutex)(&export->lock);
674 
675 	pwm_get_state(pwm, &state);
676 	state.polarity = polarity;
677 	ret = pwm_apply_might_sleep(pwm, &state);
678 
679 	return ret ? : size;
680 }
681 
capture_show(struct device * pwm_dev,struct device_attribute * attr,char * buf)682 static ssize_t capture_show(struct device *pwm_dev,
683 			    struct device_attribute *attr,
684 			    char *buf)
685 {
686 	struct pwm_device *pwm = pwm_from_dev(pwm_dev);
687 	struct pwm_capture result;
688 	int ret;
689 
690 	ret = pwm_capture(pwm, &result, jiffies_to_msecs(HZ));
691 	if (ret)
692 		return ret;
693 
694 	return sysfs_emit(buf, "%u %u\n", result.period, result.duty_cycle);
695 }
696 
697 static DEVICE_ATTR_RW(period);
698 static DEVICE_ATTR_RW(duty_cycle);
699 static DEVICE_ATTR_RW(enable);
700 static DEVICE_ATTR_RW(polarity);
701 static DEVICE_ATTR_RO(capture);
702 
703 static struct attribute *pwm_attrs[] = {
704 	&dev_attr_period.attr,
705 	&dev_attr_duty_cycle.attr,
706 	&dev_attr_enable.attr,
707 	&dev_attr_polarity.attr,
708 	&dev_attr_capture.attr,
709 	NULL
710 };
711 ATTRIBUTE_GROUPS(pwm);
712 
pwm_export_release(struct device * pwm_dev)713 static void pwm_export_release(struct device *pwm_dev)
714 {
715 	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
716 
717 	kfree(export);
718 }
719 
pwm_export_child(struct device * pwmchip_dev,struct pwm_device * pwm)720 static int pwm_export_child(struct device *pwmchip_dev, struct pwm_device *pwm)
721 {
722 	struct pwm_export *export;
723 	char *pwm_prop[2];
724 	int ret;
725 
726 	if (test_and_set_bit(PWMF_EXPORTED, &pwm->flags))
727 		return -EBUSY;
728 
729 	export = kzalloc(sizeof(*export), GFP_KERNEL);
730 	if (!export) {
731 		clear_bit(PWMF_EXPORTED, &pwm->flags);
732 		return -ENOMEM;
733 	}
734 
735 	export->pwm = pwm;
736 	mutex_init(&export->lock);
737 
738 	export->pwm_dev.release = pwm_export_release;
739 	export->pwm_dev.parent = pwmchip_dev;
740 	export->pwm_dev.devt = MKDEV(0, 0);
741 	export->pwm_dev.groups = pwm_groups;
742 	dev_set_name(&export->pwm_dev, "pwm%u", pwm->hwpwm);
743 
744 	ret = device_register(&export->pwm_dev);
745 	if (ret) {
746 		clear_bit(PWMF_EXPORTED, &pwm->flags);
747 		put_device(&export->pwm_dev);
748 		export = NULL;
749 		return ret;
750 	}
751 	pwm_prop[0] = kasprintf(GFP_KERNEL, "EXPORT=pwm%u", pwm->hwpwm);
752 	pwm_prop[1] = NULL;
753 	kobject_uevent_env(&pwmchip_dev->kobj, KOBJ_CHANGE, pwm_prop);
754 	kfree(pwm_prop[0]);
755 
756 	return 0;
757 }
758 
pwm_unexport_match(struct device * pwm_dev,void * data)759 static int pwm_unexport_match(struct device *pwm_dev, void *data)
760 {
761 	return pwm_from_dev(pwm_dev) == data;
762 }
763 
pwm_unexport_child(struct device * pwmchip_dev,struct pwm_device * pwm)764 static int pwm_unexport_child(struct device *pwmchip_dev, struct pwm_device *pwm)
765 {
766 	struct device *pwm_dev;
767 	char *pwm_prop[2];
768 
769 	if (!test_and_clear_bit(PWMF_EXPORTED, &pwm->flags))
770 		return -ENODEV;
771 
772 	pwm_dev = device_find_child(pwmchip_dev, pwm, pwm_unexport_match);
773 	if (!pwm_dev)
774 		return -ENODEV;
775 
776 	pwm_prop[0] = kasprintf(GFP_KERNEL, "UNEXPORT=pwm%u", pwm->hwpwm);
777 	pwm_prop[1] = NULL;
778 	kobject_uevent_env(&pwmchip_dev->kobj, KOBJ_CHANGE, pwm_prop);
779 	kfree(pwm_prop[0]);
780 
781 	/* for device_find_child() */
782 	put_device(pwm_dev);
783 	device_unregister(pwm_dev);
784 	pwm_put(pwm);
785 
786 	return 0;
787 }
788 
export_store(struct device * pwmchip_dev,struct device_attribute * attr,const char * buf,size_t len)789 static ssize_t export_store(struct device *pwmchip_dev,
790 			    struct device_attribute *attr,
791 			    const char *buf, size_t len)
792 {
793 	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
794 	struct pwm_device *pwm;
795 	unsigned int hwpwm;
796 	int ret;
797 
798 	ret = kstrtouint(buf, 0, &hwpwm);
799 	if (ret < 0)
800 		return ret;
801 
802 	if (hwpwm >= chip->npwm)
803 		return -ENODEV;
804 
805 	pwm = pwm_request_from_chip(chip, hwpwm, "sysfs");
806 	if (IS_ERR(pwm))
807 		return PTR_ERR(pwm);
808 
809 	ret = pwm_export_child(pwmchip_dev, pwm);
810 	if (ret < 0)
811 		pwm_put(pwm);
812 
813 	return ret ? : len;
814 }
815 static DEVICE_ATTR_WO(export);
816 
unexport_store(struct device * pwmchip_dev,struct device_attribute * attr,const char * buf,size_t len)817 static ssize_t unexport_store(struct device *pwmchip_dev,
818 			      struct device_attribute *attr,
819 			      const char *buf, size_t len)
820 {
821 	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
822 	unsigned int hwpwm;
823 	int ret;
824 
825 	ret = kstrtouint(buf, 0, &hwpwm);
826 	if (ret < 0)
827 		return ret;
828 
829 	if (hwpwm >= chip->npwm)
830 		return -ENODEV;
831 
832 	ret = pwm_unexport_child(pwmchip_dev, &chip->pwms[hwpwm]);
833 
834 	return ret ? : len;
835 }
836 static DEVICE_ATTR_WO(unexport);
837 
npwm_show(struct device * pwmchip_dev,struct device_attribute * attr,char * buf)838 static ssize_t npwm_show(struct device *pwmchip_dev, struct device_attribute *attr,
839 			 char *buf)
840 {
841 	const struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
842 
843 	return sysfs_emit(buf, "%u\n", chip->npwm);
844 }
845 static DEVICE_ATTR_RO(npwm);
846 
847 static struct attribute *pwm_chip_attrs[] = {
848 	&dev_attr_export.attr,
849 	&dev_attr_unexport.attr,
850 	&dev_attr_npwm.attr,
851 	NULL,
852 };
853 ATTRIBUTE_GROUPS(pwm_chip);
854 
855 /* takes export->lock on success */
pwm_class_get_state(struct device * pwmchip_dev,struct pwm_device * pwm,struct pwm_state * state)856 static struct pwm_export *pwm_class_get_state(struct device *pwmchip_dev,
857 					      struct pwm_device *pwm,
858 					      struct pwm_state *state)
859 {
860 	struct device *pwm_dev;
861 	struct pwm_export *export;
862 
863 	if (!test_bit(PWMF_EXPORTED, &pwm->flags))
864 		return NULL;
865 
866 	pwm_dev = device_find_child(pwmchip_dev, pwm, pwm_unexport_match);
867 	if (!pwm_dev)
868 		return NULL;
869 
870 	export = pwmexport_from_dev(pwm_dev);
871 	put_device(pwm_dev);	/* for device_find_child() */
872 
873 	mutex_lock(&export->lock);
874 	pwm_get_state(pwm, state);
875 
876 	return export;
877 }
878 
pwm_class_apply_state(struct pwm_export * export,struct pwm_device * pwm,struct pwm_state * state)879 static int pwm_class_apply_state(struct pwm_export *export,
880 				 struct pwm_device *pwm,
881 				 struct pwm_state *state)
882 {
883 	int ret = pwm_apply_might_sleep(pwm, state);
884 
885 	/* release lock taken in pwm_class_get_state */
886 	mutex_unlock(&export->lock);
887 
888 	return ret;
889 }
890 
pwm_class_resume_npwm(struct device * pwmchip_dev,unsigned int npwm)891 static int pwm_class_resume_npwm(struct device *pwmchip_dev, unsigned int npwm)
892 {
893 	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
894 	unsigned int i;
895 	int ret = 0;
896 
897 	for (i = 0; i < npwm; i++) {
898 		struct pwm_device *pwm = &chip->pwms[i];
899 		struct pwm_state state;
900 		struct pwm_export *export;
901 
902 		export = pwm_class_get_state(pwmchip_dev, pwm, &state);
903 		if (!export)
904 			continue;
905 
906 		/* If pwmchip was not enabled before suspend, do nothing. */
907 		if (!export->suspend.enabled) {
908 			/* release lock taken in pwm_class_get_state */
909 			mutex_unlock(&export->lock);
910 			continue;
911 		}
912 
913 		state.enabled = export->suspend.enabled;
914 		ret = pwm_class_apply_state(export, pwm, &state);
915 		if (ret < 0)
916 			break;
917 	}
918 
919 	return ret;
920 }
921 
pwm_class_suspend(struct device * pwmchip_dev)922 static int pwm_class_suspend(struct device *pwmchip_dev)
923 {
924 	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
925 	unsigned int i;
926 	int ret = 0;
927 
928 	for (i = 0; i < chip->npwm; i++) {
929 		struct pwm_device *pwm = &chip->pwms[i];
930 		struct pwm_state state;
931 		struct pwm_export *export;
932 
933 		export = pwm_class_get_state(pwmchip_dev, pwm, &state);
934 		if (!export)
935 			continue;
936 
937 		/*
938 		 * If pwmchip was not enabled before suspend, save
939 		 * state for resume time and do nothing else.
940 		 */
941 		export->suspend = state;
942 		if (!state.enabled) {
943 			/* release lock taken in pwm_class_get_state */
944 			mutex_unlock(&export->lock);
945 			continue;
946 		}
947 
948 		state.enabled = false;
949 		ret = pwm_class_apply_state(export, pwm, &state);
950 		if (ret < 0) {
951 			/*
952 			 * roll back the PWM devices that were disabled by
953 			 * this suspend function.
954 			 */
955 			pwm_class_resume_npwm(pwmchip_dev, i);
956 			break;
957 		}
958 	}
959 
960 	return ret;
961 }
962 
pwm_class_resume(struct device * pwmchip_dev)963 static int pwm_class_resume(struct device *pwmchip_dev)
964 {
965 	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
966 
967 	return pwm_class_resume_npwm(pwmchip_dev, chip->npwm);
968 }
969 
970 static DEFINE_SIMPLE_DEV_PM_OPS(pwm_class_pm_ops, pwm_class_suspend, pwm_class_resume);
971 
972 static struct class pwm_class = {
973 	.name = "pwm",
974 	.dev_groups = pwm_chip_groups,
975 	.pm = pm_sleep_ptr(&pwm_class_pm_ops),
976 };
977 
pwmchip_sysfs_unexport(struct pwm_chip * chip)978 static void pwmchip_sysfs_unexport(struct pwm_chip *chip)
979 {
980 	unsigned int i;
981 
982 	for (i = 0; i < chip->npwm; i++) {
983 		struct pwm_device *pwm = &chip->pwms[i];
984 
985 		if (test_bit(PWMF_EXPORTED, &pwm->flags))
986 			pwm_unexport_child(&chip->dev, pwm);
987 	}
988 }
989 
990 #define PWMCHIP_ALIGN ARCH_DMA_MINALIGN
991 
pwmchip_priv(struct pwm_chip * chip)992 static void *pwmchip_priv(struct pwm_chip *chip)
993 {
994 	return (void *)chip + ALIGN(struct_size(chip, pwms, chip->npwm), PWMCHIP_ALIGN);
995 }
996 
997 /* This is the counterpart to pwmchip_alloc() */
pwmchip_put(struct pwm_chip * chip)998 void pwmchip_put(struct pwm_chip *chip)
999 {
1000 	put_device(&chip->dev);
1001 }
1002 EXPORT_SYMBOL_GPL(pwmchip_put);
1003 
pwmchip_release(struct device * pwmchip_dev)1004 static void pwmchip_release(struct device *pwmchip_dev)
1005 {
1006 	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
1007 
1008 	kfree(chip);
1009 }
1010 
pwmchip_alloc(struct device * parent,unsigned int npwm,size_t sizeof_priv)1011 struct pwm_chip *pwmchip_alloc(struct device *parent, unsigned int npwm, size_t sizeof_priv)
1012 {
1013 	struct pwm_chip *chip;
1014 	struct device *pwmchip_dev;
1015 	size_t alloc_size;
1016 	unsigned int i;
1017 
1018 	alloc_size = size_add(ALIGN(struct_size(chip, pwms, npwm), PWMCHIP_ALIGN),
1019 			      sizeof_priv);
1020 
1021 	chip = kzalloc(alloc_size, GFP_KERNEL);
1022 	if (!chip)
1023 		return ERR_PTR(-ENOMEM);
1024 
1025 	chip->npwm = npwm;
1026 	chip->uses_pwmchip_alloc = true;
1027 
1028 	pwmchip_dev = &chip->dev;
1029 	device_initialize(pwmchip_dev);
1030 	pwmchip_dev->class = &pwm_class;
1031 	pwmchip_dev->parent = parent;
1032 	pwmchip_dev->release = pwmchip_release;
1033 
1034 	pwmchip_set_drvdata(chip, pwmchip_priv(chip));
1035 
1036 	for (i = 0; i < chip->npwm; i++) {
1037 		struct pwm_device *pwm = &chip->pwms[i];
1038 		pwm->chip = chip;
1039 		pwm->hwpwm = i;
1040 	}
1041 
1042 	return chip;
1043 }
1044 EXPORT_SYMBOL_GPL(pwmchip_alloc);
1045 
devm_pwmchip_put(void * data)1046 static void devm_pwmchip_put(void *data)
1047 {
1048 	struct pwm_chip *chip = data;
1049 
1050 	pwmchip_put(chip);
1051 }
1052 
devm_pwmchip_alloc(struct device * parent,unsigned int npwm,size_t sizeof_priv)1053 struct pwm_chip *devm_pwmchip_alloc(struct device *parent, unsigned int npwm, size_t sizeof_priv)
1054 {
1055 	struct pwm_chip *chip;
1056 	int ret;
1057 
1058 	chip = pwmchip_alloc(parent, npwm, sizeof_priv);
1059 	if (IS_ERR(chip))
1060 		return chip;
1061 
1062 	ret = devm_add_action_or_reset(parent, devm_pwmchip_put, chip);
1063 	if (ret)
1064 		return ERR_PTR(ret);
1065 
1066 	return chip;
1067 }
1068 EXPORT_SYMBOL_GPL(devm_pwmchip_alloc);
1069 
of_pwmchip_add(struct pwm_chip * chip)1070 static void of_pwmchip_add(struct pwm_chip *chip)
1071 {
1072 	if (!pwmchip_parent(chip) || !pwmchip_parent(chip)->of_node)
1073 		return;
1074 
1075 	if (!chip->of_xlate)
1076 		chip->of_xlate = of_pwm_xlate_with_flags;
1077 
1078 	of_node_get(pwmchip_parent(chip)->of_node);
1079 }
1080 
of_pwmchip_remove(struct pwm_chip * chip)1081 static void of_pwmchip_remove(struct pwm_chip *chip)
1082 {
1083 	if (pwmchip_parent(chip))
1084 		of_node_put(pwmchip_parent(chip)->of_node);
1085 }
1086 
pwm_ops_check(const struct pwm_chip * chip)1087 static bool pwm_ops_check(const struct pwm_chip *chip)
1088 {
1089 	const struct pwm_ops *ops = chip->ops;
1090 
1091 	if (!ops->apply)
1092 		return false;
1093 
1094 	if (IS_ENABLED(CONFIG_PWM_DEBUG) && !ops->get_state)
1095 		dev_warn(pwmchip_parent(chip),
1096 			 "Please implement the .get_state() callback\n");
1097 
1098 	return true;
1099 }
1100 
1101 /**
1102  * __pwmchip_add() - register a new PWM chip
1103  * @chip: the PWM chip to add
1104  * @owner: reference to the module providing the chip.
1105  *
1106  * Register a new PWM chip. @owner is supposed to be THIS_MODULE, use the
1107  * pwmchip_add wrapper to do this right.
1108  *
1109  * Returns: 0 on success or a negative error code on failure.
1110  */
__pwmchip_add(struct pwm_chip * chip,struct module * owner)1111 int __pwmchip_add(struct pwm_chip *chip, struct module *owner)
1112 {
1113 	int ret;
1114 
1115 	if (!chip || !pwmchip_parent(chip) || !chip->ops || !chip->npwm)
1116 		return -EINVAL;
1117 
1118 	/*
1119 	 * a struct pwm_chip must be allocated using (devm_)pwmchip_alloc,
1120 	 * otherwise the embedded struct device might disappear too early
1121 	 * resulting in memory corruption.
1122 	 * Catch drivers that were not converted appropriately.
1123 	 */
1124 	if (!chip->uses_pwmchip_alloc)
1125 		return -EINVAL;
1126 
1127 	if (!pwm_ops_check(chip))
1128 		return -EINVAL;
1129 
1130 	chip->owner = owner;
1131 
1132 	guard(mutex)(&pwm_lock);
1133 
1134 	ret = idr_alloc(&pwm_chips, chip, 0, 0, GFP_KERNEL);
1135 	if (ret < 0)
1136 		return ret;
1137 
1138 	chip->id = ret;
1139 
1140 	dev_set_name(&chip->dev, "pwmchip%u", chip->id);
1141 
1142 	if (IS_ENABLED(CONFIG_OF))
1143 		of_pwmchip_add(chip);
1144 
1145 	ret = device_add(&chip->dev);
1146 	if (ret)
1147 		goto err_device_add;
1148 
1149 	return 0;
1150 
1151 err_device_add:
1152 	if (IS_ENABLED(CONFIG_OF))
1153 		of_pwmchip_remove(chip);
1154 
1155 	idr_remove(&pwm_chips, chip->id);
1156 
1157 	return ret;
1158 }
1159 EXPORT_SYMBOL_GPL(__pwmchip_add);
1160 
1161 /**
1162  * pwmchip_remove() - remove a PWM chip
1163  * @chip: the PWM chip to remove
1164  *
1165  * Removes a PWM chip.
1166  */
pwmchip_remove(struct pwm_chip * chip)1167 void pwmchip_remove(struct pwm_chip *chip)
1168 {
1169 	pwmchip_sysfs_unexport(chip);
1170 
1171 	if (IS_ENABLED(CONFIG_OF))
1172 		of_pwmchip_remove(chip);
1173 
1174 	scoped_guard(mutex, &pwm_lock)
1175 		idr_remove(&pwm_chips, chip->id);
1176 
1177 	device_del(&chip->dev);
1178 }
1179 EXPORT_SYMBOL_GPL(pwmchip_remove);
1180 
devm_pwmchip_remove(void * data)1181 static void devm_pwmchip_remove(void *data)
1182 {
1183 	struct pwm_chip *chip = data;
1184 
1185 	pwmchip_remove(chip);
1186 }
1187 
__devm_pwmchip_add(struct device * dev,struct pwm_chip * chip,struct module * owner)1188 int __devm_pwmchip_add(struct device *dev, struct pwm_chip *chip, struct module *owner)
1189 {
1190 	int ret;
1191 
1192 	ret = __pwmchip_add(chip, owner);
1193 	if (ret)
1194 		return ret;
1195 
1196 	return devm_add_action_or_reset(dev, devm_pwmchip_remove, chip);
1197 }
1198 EXPORT_SYMBOL_GPL(__devm_pwmchip_add);
1199 
pwm_device_link_add(struct device * dev,struct pwm_device * pwm)1200 static struct device_link *pwm_device_link_add(struct device *dev,
1201 					       struct pwm_device *pwm)
1202 {
1203 	struct device_link *dl;
1204 
1205 	if (!dev) {
1206 		/*
1207 		 * No device for the PWM consumer has been provided. It may
1208 		 * impact the PM sequence ordering: the PWM supplier may get
1209 		 * suspended before the consumer.
1210 		 */
1211 		dev_warn(pwmchip_parent(pwm->chip),
1212 			 "No consumer device specified to create a link to\n");
1213 		return NULL;
1214 	}
1215 
1216 	dl = device_link_add(dev, pwmchip_parent(pwm->chip), DL_FLAG_AUTOREMOVE_CONSUMER);
1217 	if (!dl) {
1218 		dev_err(dev, "failed to create device link to %s\n",
1219 			dev_name(pwmchip_parent(pwm->chip)));
1220 		return ERR_PTR(-EINVAL);
1221 	}
1222 
1223 	return dl;
1224 }
1225 
fwnode_to_pwmchip(struct fwnode_handle * fwnode)1226 static struct pwm_chip *fwnode_to_pwmchip(struct fwnode_handle *fwnode)
1227 {
1228 	struct pwm_chip *chip;
1229 	unsigned long id, tmp;
1230 
1231 	guard(mutex)(&pwm_lock);
1232 
1233 	idr_for_each_entry_ul(&pwm_chips, chip, tmp, id)
1234 		if (pwmchip_parent(chip) && device_match_fwnode(pwmchip_parent(chip), fwnode))
1235 			return chip;
1236 
1237 	return ERR_PTR(-EPROBE_DEFER);
1238 }
1239 
1240 /**
1241  * of_pwm_get() - request a PWM via the PWM framework
1242  * @dev: device for PWM consumer
1243  * @np: device node to get the PWM from
1244  * @con_id: consumer name
1245  *
1246  * Returns the PWM device parsed from the phandle and index specified in the
1247  * "pwms" property of a device tree node or a negative error-code on failure.
1248  * Values parsed from the device tree are stored in the returned PWM device
1249  * object.
1250  *
1251  * If con_id is NULL, the first PWM device listed in the "pwms" property will
1252  * be requested. Otherwise the "pwm-names" property is used to do a reverse
1253  * lookup of the PWM index. This also means that the "pwm-names" property
1254  * becomes mandatory for devices that look up the PWM device via the con_id
1255  * parameter.
1256  *
1257  * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
1258  * error code on failure.
1259  */
of_pwm_get(struct device * dev,struct device_node * np,const char * con_id)1260 static struct pwm_device *of_pwm_get(struct device *dev, struct device_node *np,
1261 				     const char *con_id)
1262 {
1263 	struct pwm_device *pwm = NULL;
1264 	struct of_phandle_args args;
1265 	struct device_link *dl;
1266 	struct pwm_chip *chip;
1267 	int index = 0;
1268 	int err;
1269 
1270 	if (con_id) {
1271 		index = of_property_match_string(np, "pwm-names", con_id);
1272 		if (index < 0)
1273 			return ERR_PTR(index);
1274 	}
1275 
1276 	err = of_parse_phandle_with_args(np, "pwms", "#pwm-cells", index,
1277 					 &args);
1278 	if (err) {
1279 		pr_err("%s(): can't parse \"pwms\" property\n", __func__);
1280 		return ERR_PTR(err);
1281 	}
1282 
1283 	chip = fwnode_to_pwmchip(of_fwnode_handle(args.np));
1284 	if (IS_ERR(chip)) {
1285 		if (PTR_ERR(chip) != -EPROBE_DEFER)
1286 			pr_err("%s(): PWM chip not found\n", __func__);
1287 
1288 		pwm = ERR_CAST(chip);
1289 		goto put;
1290 	}
1291 
1292 	pwm = chip->of_xlate(chip, &args);
1293 	if (IS_ERR(pwm))
1294 		goto put;
1295 
1296 	dl = pwm_device_link_add(dev, pwm);
1297 	if (IS_ERR(dl)) {
1298 		/* of_xlate ended up calling pwm_request_from_chip() */
1299 		pwm_put(pwm);
1300 		pwm = ERR_CAST(dl);
1301 		goto put;
1302 	}
1303 
1304 	/*
1305 	 * If a consumer name was not given, try to look it up from the
1306 	 * "pwm-names" property if it exists. Otherwise use the name of
1307 	 * the user device node.
1308 	 */
1309 	if (!con_id) {
1310 		err = of_property_read_string_index(np, "pwm-names", index,
1311 						    &con_id);
1312 		if (err < 0)
1313 			con_id = np->name;
1314 	}
1315 
1316 	pwm->label = con_id;
1317 
1318 put:
1319 	of_node_put(args.np);
1320 
1321 	return pwm;
1322 }
1323 
1324 /**
1325  * acpi_pwm_get() - request a PWM via parsing "pwms" property in ACPI
1326  * @fwnode: firmware node to get the "pwms" property from
1327  *
1328  * Returns the PWM device parsed from the fwnode and index specified in the
1329  * "pwms" property or a negative error-code on failure.
1330  * Values parsed from the device tree are stored in the returned PWM device
1331  * object.
1332  *
1333  * This is analogous to of_pwm_get() except con_id is not yet supported.
1334  * ACPI entries must look like
1335  * Package () {"pwms", Package ()
1336  *     { <PWM device reference>, <PWM index>, <PWM period> [, <PWM flags>]}}
1337  *
1338  * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
1339  * error code on failure.
1340  */
acpi_pwm_get(const struct fwnode_handle * fwnode)1341 static struct pwm_device *acpi_pwm_get(const struct fwnode_handle *fwnode)
1342 {
1343 	struct pwm_device *pwm;
1344 	struct fwnode_reference_args args;
1345 	struct pwm_chip *chip;
1346 	int ret;
1347 
1348 	memset(&args, 0, sizeof(args));
1349 
1350 	ret = __acpi_node_get_property_reference(fwnode, "pwms", 0, 3, &args);
1351 	if (ret < 0)
1352 		return ERR_PTR(ret);
1353 
1354 	if (args.nargs < 2)
1355 		return ERR_PTR(-EPROTO);
1356 
1357 	chip = fwnode_to_pwmchip(args.fwnode);
1358 	if (IS_ERR(chip))
1359 		return ERR_CAST(chip);
1360 
1361 	pwm = pwm_request_from_chip(chip, args.args[0], NULL);
1362 	if (IS_ERR(pwm))
1363 		return pwm;
1364 
1365 	pwm->args.period = args.args[1];
1366 	pwm->args.polarity = PWM_POLARITY_NORMAL;
1367 
1368 	if (args.nargs > 2 && args.args[2] & PWM_POLARITY_INVERTED)
1369 		pwm->args.polarity = PWM_POLARITY_INVERSED;
1370 
1371 	return pwm;
1372 }
1373 
1374 static DEFINE_MUTEX(pwm_lookup_lock);
1375 static LIST_HEAD(pwm_lookup_list);
1376 
1377 /**
1378  * pwm_add_table() - register PWM device consumers
1379  * @table: array of consumers to register
1380  * @num: number of consumers in table
1381  */
pwm_add_table(struct pwm_lookup * table,size_t num)1382 void pwm_add_table(struct pwm_lookup *table, size_t num)
1383 {
1384 	guard(mutex)(&pwm_lookup_lock);
1385 
1386 	while (num--) {
1387 		list_add_tail(&table->list, &pwm_lookup_list);
1388 		table++;
1389 	}
1390 }
1391 
1392 /**
1393  * pwm_remove_table() - unregister PWM device consumers
1394  * @table: array of consumers to unregister
1395  * @num: number of consumers in table
1396  */
pwm_remove_table(struct pwm_lookup * table,size_t num)1397 void pwm_remove_table(struct pwm_lookup *table, size_t num)
1398 {
1399 	guard(mutex)(&pwm_lookup_lock);
1400 
1401 	while (num--) {
1402 		list_del(&table->list);
1403 		table++;
1404 	}
1405 }
1406 
1407 /**
1408  * pwm_get() - look up and request a PWM device
1409  * @dev: device for PWM consumer
1410  * @con_id: consumer name
1411  *
1412  * Lookup is first attempted using DT. If the device was not instantiated from
1413  * a device tree, a PWM chip and a relative index is looked up via a table
1414  * supplied by board setup code (see pwm_add_table()).
1415  *
1416  * Once a PWM chip has been found the specified PWM device will be requested
1417  * and is ready to be used.
1418  *
1419  * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
1420  * error code on failure.
1421  */
pwm_get(struct device * dev,const char * con_id)1422 struct pwm_device *pwm_get(struct device *dev, const char *con_id)
1423 {
1424 	const struct fwnode_handle *fwnode = dev ? dev_fwnode(dev) : NULL;
1425 	const char *dev_id = dev ? dev_name(dev) : NULL;
1426 	struct pwm_device *pwm;
1427 	struct pwm_chip *chip;
1428 	struct device_link *dl;
1429 	unsigned int best = 0;
1430 	struct pwm_lookup *p, *chosen = NULL;
1431 	unsigned int match;
1432 	int err;
1433 
1434 	/* look up via DT first */
1435 	if (is_of_node(fwnode))
1436 		return of_pwm_get(dev, to_of_node(fwnode), con_id);
1437 
1438 	/* then lookup via ACPI */
1439 	if (is_acpi_node(fwnode)) {
1440 		pwm = acpi_pwm_get(fwnode);
1441 		if (!IS_ERR(pwm) || PTR_ERR(pwm) != -ENOENT)
1442 			return pwm;
1443 	}
1444 
1445 	/*
1446 	 * We look up the provider in the static table typically provided by
1447 	 * board setup code. We first try to lookup the consumer device by
1448 	 * name. If the consumer device was passed in as NULL or if no match
1449 	 * was found, we try to find the consumer by directly looking it up
1450 	 * by name.
1451 	 *
1452 	 * If a match is found, the provider PWM chip is looked up by name
1453 	 * and a PWM device is requested using the PWM device per-chip index.
1454 	 *
1455 	 * The lookup algorithm was shamelessly taken from the clock
1456 	 * framework:
1457 	 *
1458 	 * We do slightly fuzzy matching here:
1459 	 *  An entry with a NULL ID is assumed to be a wildcard.
1460 	 *  If an entry has a device ID, it must match
1461 	 *  If an entry has a connection ID, it must match
1462 	 * Then we take the most specific entry - with the following order
1463 	 * of precedence: dev+con > dev only > con only.
1464 	 */
1465 	scoped_guard(mutex, &pwm_lookup_lock)
1466 		list_for_each_entry(p, &pwm_lookup_list, list) {
1467 			match = 0;
1468 
1469 			if (p->dev_id) {
1470 				if (!dev_id || strcmp(p->dev_id, dev_id))
1471 					continue;
1472 
1473 				match += 2;
1474 			}
1475 
1476 			if (p->con_id) {
1477 				if (!con_id || strcmp(p->con_id, con_id))
1478 					continue;
1479 
1480 				match += 1;
1481 			}
1482 
1483 			if (match > best) {
1484 				chosen = p;
1485 
1486 				if (match != 3)
1487 					best = match;
1488 				else
1489 					break;
1490 			}
1491 		}
1492 
1493 	if (!chosen)
1494 		return ERR_PTR(-ENODEV);
1495 
1496 	chip = pwmchip_find_by_name(chosen->provider);
1497 
1498 	/*
1499 	 * If the lookup entry specifies a module, load the module and retry
1500 	 * the PWM chip lookup. This can be used to work around driver load
1501 	 * ordering issues if driver's can't be made to properly support the
1502 	 * deferred probe mechanism.
1503 	 */
1504 	if (!chip && chosen->module) {
1505 		err = request_module(chosen->module);
1506 		if (err == 0)
1507 			chip = pwmchip_find_by_name(chosen->provider);
1508 	}
1509 
1510 	if (!chip)
1511 		return ERR_PTR(-EPROBE_DEFER);
1512 
1513 	pwm = pwm_request_from_chip(chip, chosen->index, con_id ?: dev_id);
1514 	if (IS_ERR(pwm))
1515 		return pwm;
1516 
1517 	dl = pwm_device_link_add(dev, pwm);
1518 	if (IS_ERR(dl)) {
1519 		pwm_put(pwm);
1520 		return ERR_CAST(dl);
1521 	}
1522 
1523 	pwm->args.period = chosen->period;
1524 	pwm->args.polarity = chosen->polarity;
1525 
1526 	return pwm;
1527 }
1528 EXPORT_SYMBOL_GPL(pwm_get);
1529 
1530 /**
1531  * pwm_put() - release a PWM device
1532  * @pwm: PWM device
1533  */
pwm_put(struct pwm_device * pwm)1534 void pwm_put(struct pwm_device *pwm)
1535 {
1536 	struct pwm_chip *chip;
1537 
1538 	if (!pwm)
1539 		return;
1540 
1541 	chip = pwm->chip;
1542 
1543 	guard(mutex)(&pwm_lock);
1544 
1545 	if (!test_and_clear_bit(PWMF_REQUESTED, &pwm->flags)) {
1546 		pr_warn("PWM device already freed\n");
1547 		return;
1548 	}
1549 
1550 	if (chip->ops->free)
1551 		pwm->chip->ops->free(pwm->chip, pwm);
1552 
1553 	pwm->label = NULL;
1554 
1555 	put_device(&chip->dev);
1556 
1557 	module_put(chip->owner);
1558 }
1559 EXPORT_SYMBOL_GPL(pwm_put);
1560 
devm_pwm_release(void * pwm)1561 static void devm_pwm_release(void *pwm)
1562 {
1563 	pwm_put(pwm);
1564 }
1565 
1566 /**
1567  * devm_pwm_get() - resource managed pwm_get()
1568  * @dev: device for PWM consumer
1569  * @con_id: consumer name
1570  *
1571  * This function performs like pwm_get() but the acquired PWM device will
1572  * automatically be released on driver detach.
1573  *
1574  * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
1575  * error code on failure.
1576  */
devm_pwm_get(struct device * dev,const char * con_id)1577 struct pwm_device *devm_pwm_get(struct device *dev, const char *con_id)
1578 {
1579 	struct pwm_device *pwm;
1580 	int ret;
1581 
1582 	pwm = pwm_get(dev, con_id);
1583 	if (IS_ERR(pwm))
1584 		return pwm;
1585 
1586 	ret = devm_add_action_or_reset(dev, devm_pwm_release, pwm);
1587 	if (ret)
1588 		return ERR_PTR(ret);
1589 
1590 	return pwm;
1591 }
1592 EXPORT_SYMBOL_GPL(devm_pwm_get);
1593 
1594 /**
1595  * devm_fwnode_pwm_get() - request a resource managed PWM from firmware node
1596  * @dev: device for PWM consumer
1597  * @fwnode: firmware node to get the PWM from
1598  * @con_id: consumer name
1599  *
1600  * Returns the PWM device parsed from the firmware node. See of_pwm_get() and
1601  * acpi_pwm_get() for a detailed description.
1602  *
1603  * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
1604  * error code on failure.
1605  */
devm_fwnode_pwm_get(struct device * dev,struct fwnode_handle * fwnode,const char * con_id)1606 struct pwm_device *devm_fwnode_pwm_get(struct device *dev,
1607 				       struct fwnode_handle *fwnode,
1608 				       const char *con_id)
1609 {
1610 	struct pwm_device *pwm = ERR_PTR(-ENODEV);
1611 	int ret;
1612 
1613 	if (is_of_node(fwnode))
1614 		pwm = of_pwm_get(dev, to_of_node(fwnode), con_id);
1615 	else if (is_acpi_node(fwnode))
1616 		pwm = acpi_pwm_get(fwnode);
1617 	if (IS_ERR(pwm))
1618 		return pwm;
1619 
1620 	ret = devm_add_action_or_reset(dev, devm_pwm_release, pwm);
1621 	if (ret)
1622 		return ERR_PTR(ret);
1623 
1624 	return pwm;
1625 }
1626 EXPORT_SYMBOL_GPL(devm_fwnode_pwm_get);
1627 
pwm_dbg_show(struct pwm_chip * chip,struct seq_file * s)1628 static void pwm_dbg_show(struct pwm_chip *chip, struct seq_file *s)
1629 {
1630 	unsigned int i;
1631 
1632 	for (i = 0; i < chip->npwm; i++) {
1633 		struct pwm_device *pwm = &chip->pwms[i];
1634 		struct pwm_state state;
1635 
1636 		pwm_get_state(pwm, &state);
1637 
1638 		seq_printf(s, " pwm-%-3d (%-20.20s):", i, pwm->label);
1639 
1640 		if (test_bit(PWMF_REQUESTED, &pwm->flags))
1641 			seq_puts(s, " requested");
1642 
1643 		if (state.enabled)
1644 			seq_puts(s, " enabled");
1645 
1646 		seq_printf(s, " period: %llu ns", state.period);
1647 		seq_printf(s, " duty: %llu ns", state.duty_cycle);
1648 		seq_printf(s, " polarity: %s",
1649 			   state.polarity ? "inverse" : "normal");
1650 
1651 		if (state.usage_power)
1652 			seq_puts(s, " usage_power");
1653 
1654 		seq_puts(s, "\n");
1655 	}
1656 }
1657 
pwm_seq_start(struct seq_file * s,loff_t * pos)1658 static void *pwm_seq_start(struct seq_file *s, loff_t *pos)
1659 {
1660 	unsigned long id = *pos;
1661 	void *ret;
1662 
1663 	mutex_lock(&pwm_lock);
1664 	s->private = "";
1665 
1666 	ret = idr_get_next_ul(&pwm_chips, &id);
1667 	*pos = id;
1668 	return ret;
1669 }
1670 
pwm_seq_next(struct seq_file * s,void * v,loff_t * pos)1671 static void *pwm_seq_next(struct seq_file *s, void *v, loff_t *pos)
1672 {
1673 	unsigned long id = *pos + 1;
1674 	void *ret;
1675 
1676 	s->private = "\n";
1677 
1678 	ret = idr_get_next_ul(&pwm_chips, &id);
1679 	*pos = id;
1680 	return ret;
1681 }
1682 
pwm_seq_stop(struct seq_file * s,void * v)1683 static void pwm_seq_stop(struct seq_file *s, void *v)
1684 {
1685 	mutex_unlock(&pwm_lock);
1686 }
1687 
pwm_seq_show(struct seq_file * s,void * v)1688 static int pwm_seq_show(struct seq_file *s, void *v)
1689 {
1690 	struct pwm_chip *chip = v;
1691 
1692 	seq_printf(s, "%s%d: %s/%s, %d PWM device%s\n",
1693 		   (char *)s->private, chip->id,
1694 		   pwmchip_parent(chip)->bus ? pwmchip_parent(chip)->bus->name : "no-bus",
1695 		   dev_name(pwmchip_parent(chip)), chip->npwm,
1696 		   (chip->npwm != 1) ? "s" : "");
1697 
1698 	pwm_dbg_show(chip, s);
1699 
1700 	return 0;
1701 }
1702 
1703 static const struct seq_operations pwm_debugfs_sops = {
1704 	.start = pwm_seq_start,
1705 	.next = pwm_seq_next,
1706 	.stop = pwm_seq_stop,
1707 	.show = pwm_seq_show,
1708 };
1709 
1710 DEFINE_SEQ_ATTRIBUTE(pwm_debugfs);
1711 
pwm_init(void)1712 static int __init pwm_init(void)
1713 {
1714 	int ret;
1715 
1716 	ret = class_register(&pwm_class);
1717 	if (ret) {
1718 		pr_err("Failed to initialize PWM class (%pe)\n", ERR_PTR(ret));
1719 		return ret;
1720 	}
1721 
1722 	if (IS_ENABLED(CONFIG_DEBUG_FS))
1723 		debugfs_create_file("pwm", 0444, NULL, NULL, &pwm_debugfs_fops);
1724 
1725 	return 0;
1726 }
1727 subsys_initcall(pwm_init);
1728