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