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