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