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