File Index
Files and directories
Sign in
FILE

core.c

File preview with syntax highlighting.

linux-6.19.14/drivers/pwm/core.c 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#define DEFAULT_SYMBOL_NAMESPACE "PWM"
  10
  11#include <linux/acpi.h>
  12#include <linux/module.h>
  13#include <linux/idr.h>
  14#include <linux/of.h>
  15#include <linux/pwm.h>
  16#include <linux/list.h>
  17#include <linux/mutex.h>
  18#include <linux/err.h>
  19#include <linux/slab.h>
  20#include <linux/device.h>
  21#include <linux/debugfs.h>
  22#include <linux/seq_file.h>
  23
  24#include <dt-bindings/pwm/pwm.h>
  25
  26#include <uapi/linux/pwm.h>
  27
  28#define CREATE_TRACE_POINTS
  29#include <trace/events/pwm.h>
  30
  31#define PWM_MINOR_COUNT 256
  32
  33/* protects access to pwm_chips */
  34static DEFINE_MUTEX(pwm_lock);
  35
  36static DEFINE_IDR(pwm_chips);
  37
  38static void pwmchip_lock(struct pwm_chip *chip)
  39{
  40	if (chip->atomic)
  41		spin_lock(&chip->atomic_lock);
  42	else
  43		mutex_lock(&chip->nonatomic_lock);
  44}
  45
  46static void pwmchip_unlock(struct pwm_chip *chip)
  47{
  48	if (chip->atomic)
  49		spin_unlock(&chip->atomic_lock);
  50	else
  51		mutex_unlock(&chip->nonatomic_lock);
  52}
  53
  54DEFINE_GUARD(pwmchip, struct pwm_chip *, pwmchip_lock(_T), pwmchip_unlock(_T))
  55
  56static bool pwm_wf_valid(const struct pwm_waveform *wf)
  57{
  58	/*
  59	 * For now restrict waveforms to period_length_ns <= S64_MAX to provide
  60	 * some space for future extensions. One possibility is to simplify
  61	 * representing waveforms with inverted polarity using negative values
  62	 * somehow.
  63	 */
  64	if (wf->period_length_ns > S64_MAX)
  65		return false;
  66
  67	if (wf->duty_length_ns > wf->period_length_ns)
  68		return false;
  69
  70	/*
  71	 * .duty_offset_ns is supposed to be smaller than .period_length_ns, apart
  72	 * from the corner case .duty_offset_ns == 0 && .period_length_ns == 0.
  73	 */
  74	if (wf->duty_offset_ns && wf->duty_offset_ns >= wf->period_length_ns)
  75		return false;
  76
  77	return true;
  78}
  79
  80static void pwm_wf2state(const struct pwm_waveform *wf, struct pwm_state *state)
  81{
  82	if (wf->period_length_ns) {
  83		if (wf->duty_length_ns + wf->duty_offset_ns < wf->period_length_ns)
  84			*state = (struct pwm_state){
  85				.enabled = true,
  86				.polarity = PWM_POLARITY_NORMAL,
  87				.period = wf->period_length_ns,
  88				.duty_cycle = wf->duty_length_ns,
  89			};
  90		else
  91			*state = (struct pwm_state){
  92				.enabled = true,
  93				.polarity = PWM_POLARITY_INVERSED,
  94				.period = wf->period_length_ns,
  95				.duty_cycle = wf->period_length_ns - wf->duty_length_ns,
  96			};
  97	} else {
  98		*state = (struct pwm_state){
  99			.enabled = false,
 100		};
 101	}
 102}
 103
 104static void pwm_state2wf(const struct pwm_state *state, struct pwm_waveform *wf)
 105{
 106	if (state->enabled) {
 107		if (state->polarity == PWM_POLARITY_NORMAL)
 108			*wf = (struct pwm_waveform){
 109				.period_length_ns = state->period,
 110				.duty_length_ns = state->duty_cycle,
 111				.duty_offset_ns = 0,
 112			};
 113		else
 114			*wf = (struct pwm_waveform){
 115				.period_length_ns = state->period,
 116				.duty_length_ns = state->period - state->duty_cycle,
 117				.duty_offset_ns = state->duty_cycle,
 118			};
 119	} else {
 120		*wf = (struct pwm_waveform){
 121			.period_length_ns = 0,
 122		};
 123	}
 124}
 125
 126static int pwmwfcmp(const struct pwm_waveform *a, const struct pwm_waveform *b)
 127{
 128	if (a->period_length_ns > b->period_length_ns)
 129		return 1;
 130
 131	if (a->period_length_ns < b->period_length_ns)
 132		return -1;
 133
 134	if (a->duty_length_ns > b->duty_length_ns)
 135		return 1;
 136
 137	if (a->duty_length_ns < b->duty_length_ns)
 138		return -1;
 139
 140	if (a->duty_offset_ns > b->duty_offset_ns)
 141		return 1;
 142
 143	if (a->duty_offset_ns < b->duty_offset_ns)
 144		return -1;
 145
 146	return 0;
 147}
 148
 149static bool pwm_check_rounding(const struct pwm_waveform *wf,
 150			       const struct pwm_waveform *wf_rounded)
 151{
 152	if (!wf->period_length_ns)
 153		return true;
 154
 155	if (wf->period_length_ns < wf_rounded->period_length_ns)
 156		return false;
 157
 158	if (wf->duty_length_ns < wf_rounded->duty_length_ns)
 159		return false;
 160
 161	if (wf->duty_offset_ns < wf_rounded->duty_offset_ns)
 162		return false;
 163
 164	return true;
 165}
 166
 167static int __pwm_round_waveform_tohw(struct pwm_chip *chip, struct pwm_device *pwm,
 168				     const struct pwm_waveform *wf, void *wfhw)
 169{
 170	const struct pwm_ops *ops = chip->ops;
 171	int ret;
 172
 173	ret = ops->round_waveform_tohw(chip, pwm, wf, wfhw);
 174	trace_pwm_round_waveform_tohw(pwm, wf, wfhw, ret);
 175
 176	return ret;
 177}
 178
 179static int __pwm_round_waveform_fromhw(struct pwm_chip *chip, struct pwm_device *pwm,
 180				       const void *wfhw, struct pwm_waveform *wf)
 181{
 182	const struct pwm_ops *ops = chip->ops;
 183	int ret;
 184
 185	ret = ops->round_waveform_fromhw(chip, pwm, wfhw, wf);
 186	trace_pwm_round_waveform_fromhw(pwm, wfhw, wf, ret);
 187
 188	return ret;
 189}
 190
 191static int __pwm_read_waveform(struct pwm_chip *chip, struct pwm_device *pwm, void *wfhw)
 192{
 193	const struct pwm_ops *ops = chip->ops;
 194	int ret;
 195
 196	ret = ops->read_waveform(chip, pwm, wfhw);
 197	trace_pwm_read_waveform(pwm, wfhw, ret);
 198
 199	return ret;
 200}
 201
 202static int __pwm_write_waveform(struct pwm_chip *chip, struct pwm_device *pwm, const void *wfhw)
 203{
 204	const struct pwm_ops *ops = chip->ops;
 205	int ret;
 206
 207	ret = ops->write_waveform(chip, pwm, wfhw);
 208	trace_pwm_write_waveform(pwm, wfhw, ret);
 209
 210	return ret;
 211}
 212
 213/**
 214 * pwm_round_waveform_might_sleep - Query hardware capabilities
 215 * Cannot be used in atomic context.
 216 * @pwm: PWM device
 217 * @wf: waveform to round and output parameter
 218 *
 219 * Typically a given waveform cannot be implemented exactly by hardware, e.g.
 220 * because hardware only supports coarse period resolution or no duty_offset.
 221 * This function returns the actually implemented waveform if you pass @wf to
 222 * pwm_set_waveform_might_sleep() now.
 223 *
 224 * Note however that the world doesn't stop turning when you call it, so when
 225 * doing::
 226 *
 227 *   pwm_round_waveform_might_sleep(mypwm, &wf);
 228 *   pwm_set_waveform_might_sleep(mypwm, &wf, true);
 229 *
 230 * the latter might fail, e.g. because an input clock changed its rate between
 231 * these two calls and the waveform determined by
 232 * pwm_round_waveform_might_sleep() cannot be implemented any more.
 233 *
 234 * Usually all values passed in @wf are rounded down to the nearest possible
 235 * value (in the order period_length_ns, duty_length_ns and then
 236 * duty_offset_ns). Only if this isn't possible, a value might grow. See the
 237 * documentation for pwm_set_waveform_might_sleep() for a more formal
 238 * description.
 239 *
 240 * Returns: 0 on success, 1 if at least one value had to be rounded up or a
 241 * negative errno.
 242 * Context: May sleep.
 243 */
 244int pwm_round_waveform_might_sleep(struct pwm_device *pwm, struct pwm_waveform *wf)
 245{
 246	struct pwm_chip *chip = pwm->chip;
 247	const struct pwm_ops *ops = chip->ops;
 248	struct pwm_waveform wf_req = *wf;
 249	char wfhw[PWM_WFHWSIZE];
 250	int ret_tohw, ret_fromhw;
 251
 252	BUG_ON(PWM_WFHWSIZE < ops->sizeof_wfhw);
 253
 254	if (!pwmchip_supports_waveform(chip))
 255		return -EOPNOTSUPP;
 256
 257	if (!pwm_wf_valid(wf))
 258		return -EINVAL;
 259
 260	guard(pwmchip)(chip);
 261
 262	if (!chip->operational)
 263		return -ENODEV;
 264
 265	ret_tohw = __pwm_round_waveform_tohw(chip, pwm, wf, wfhw);
 266	if (ret_tohw < 0)
 267		return ret_tohw;
 268
 269	if (IS_ENABLED(CONFIG_PWM_DEBUG) && ret_tohw > 1)
 270		dev_err(&chip->dev, "Unexpected return value from __pwm_round_waveform_tohw: requested %llu/%llu [+%llu], return value %d\n",
 271			wf_req.duty_length_ns, wf_req.period_length_ns, wf_req.duty_offset_ns, ret_tohw);
 272
 273	ret_fromhw = __pwm_round_waveform_fromhw(chip, pwm, wfhw, wf);
 274	if (ret_fromhw < 0)
 275		return ret_fromhw;
 276
 277	if (IS_ENABLED(CONFIG_PWM_DEBUG) && ret_fromhw > 0)
 278		dev_err(&chip->dev, "Unexpected return value from __pwm_round_waveform_fromhw: requested %llu/%llu [+%llu], return value %d\n",
 279			wf_req.duty_length_ns, wf_req.period_length_ns, wf_req.duty_offset_ns, ret_fromhw);
 280
 281	if (IS_ENABLED(CONFIG_PWM_DEBUG) &&
 282	    (ret_tohw == 0) != pwm_check_rounding(&wf_req, wf))
 283		dev_err(&chip->dev, "Wrong rounding: requested %llu/%llu [+%llu], result %llu/%llu [+%llu], ret: %d\n",
 284			wf_req.duty_length_ns, wf_req.period_length_ns, wf_req.duty_offset_ns,
 285			wf->duty_length_ns, wf->period_length_ns, wf->duty_offset_ns, ret_tohw);
 286
 287	return ret_tohw;
 288}
 289EXPORT_SYMBOL_GPL(pwm_round_waveform_might_sleep);
 290
 291/**
 292 * pwm_get_waveform_might_sleep - Query hardware about current configuration
 293 * Cannot be used in atomic context.
 294 * @pwm: PWM device
 295 * @wf: output parameter
 296 *
 297 * Stores the current configuration of the PWM in @wf. Note this is the
 298 * equivalent of pwm_get_state_hw() (and not pwm_get_state()) for pwm_waveform.
 299 *
 300 * Returns: 0 on success or a negative errno
 301 * Context: May sleep.
 302 */
 303int pwm_get_waveform_might_sleep(struct pwm_device *pwm, struct pwm_waveform *wf)
 304{
 305	struct pwm_chip *chip = pwm->chip;
 306	const struct pwm_ops *ops = chip->ops;
 307	char wfhw[PWM_WFHWSIZE];
 308	int err;
 309
 310	BUG_ON(PWM_WFHWSIZE < ops->sizeof_wfhw);
 311
 312	if (!pwmchip_supports_waveform(chip) || !ops->read_waveform)
 313		return -EOPNOTSUPP;
 314
 315	guard(pwmchip)(chip);
 316
 317	if (!chip->operational)
 318		return -ENODEV;
 319
 320	err = __pwm_read_waveform(chip, pwm, &wfhw);
 321	if (err)
 322		return err;
 323
 324	return __pwm_round_waveform_fromhw(chip, pwm, &wfhw, wf);
 325}
 326EXPORT_SYMBOL_GPL(pwm_get_waveform_might_sleep);
 327
 328/* Called with the pwmchip lock held */
 329static int __pwm_set_waveform(struct pwm_device *pwm,
 330			      const struct pwm_waveform *wf,
 331			      bool exact)
 332{
 333	struct pwm_chip *chip = pwm->chip;
 334	const struct pwm_ops *ops = chip->ops;
 335	char wfhw[PWM_WFHWSIZE];
 336	struct pwm_waveform wf_rounded;
 337	int err, ret_tohw;
 338
 339	BUG_ON(PWM_WFHWSIZE < ops->sizeof_wfhw);
 340
 341	if (!pwmchip_supports_waveform(chip))
 342		return -EOPNOTSUPP;
 343
 344	if (!pwm_wf_valid(wf))
 345		return -EINVAL;
 346
 347	ret_tohw = __pwm_round_waveform_tohw(chip, pwm, wf, &wfhw);
 348	if (ret_tohw < 0)
 349		return ret_tohw;
 350
 351	if ((IS_ENABLED(CONFIG_PWM_DEBUG) || exact) && wf->period_length_ns) {
 352		err = __pwm_round_waveform_fromhw(chip, pwm, &wfhw, &wf_rounded);
 353		if (err)
 354			return err;
 355
 356		if (IS_ENABLED(CONFIG_PWM_DEBUG) && (ret_tohw == 0) != pwm_check_rounding(wf, &wf_rounded))
 357			dev_err(&chip->dev, "Wrong rounding: requested %llu/%llu [+%llu], result %llu/%llu [+%llu], ret: %d\n",
 358				wf->duty_length_ns, wf->period_length_ns, wf->duty_offset_ns,
 359				wf_rounded.duty_length_ns, wf_rounded.period_length_ns, wf_rounded.duty_offset_ns, ret_tohw);
 360
 361		if (exact && pwmwfcmp(wf, &wf_rounded)) {
 362			dev_dbg(&chip->dev, "Requested no rounding, but %llu/%llu [+%llu] -> %llu/%llu [+%llu]\n",
 363				wf->duty_length_ns, wf->period_length_ns, wf->duty_offset_ns,
 364				wf_rounded.duty_length_ns, wf_rounded.period_length_ns, wf_rounded.duty_offset_ns);
 365
 366			return 1;
 367		}
 368	}
 369
 370	err = __pwm_write_waveform(chip, pwm, &wfhw);
 371	if (err)
 372		return err;
 373
 374	/* update .state */
 375	pwm_wf2state(wf, &pwm->state);
 376
 377	if (IS_ENABLED(CONFIG_PWM_DEBUG) && ops->read_waveform && wf->period_length_ns) {
 378		struct pwm_waveform wf_set;
 379
 380		err = __pwm_read_waveform(chip, pwm, &wfhw);
 381		if (err)
 382			/* maybe ignore? */
 383			return err;
 384
 385		err = __pwm_round_waveform_fromhw(chip, pwm, &wfhw, &wf_set);
 386		if (err)
 387			/* maybe ignore? */
 388			return err;
 389
 390		if (pwmwfcmp(&wf_set, &wf_rounded) != 0)
 391			dev_err(&chip->dev,
 392				"Unexpected setting: requested %llu/%llu [+%llu], expected %llu/%llu [+%llu], set %llu/%llu [+%llu]\n",
 393				wf->duty_length_ns, wf->period_length_ns, wf->duty_offset_ns,
 394				wf_rounded.duty_length_ns, wf_rounded.period_length_ns, wf_rounded.duty_offset_ns,
 395				wf_set.duty_length_ns, wf_set.period_length_ns, wf_set.duty_offset_ns);
 396	}
 397
 398	return ret_tohw;
 399}
 400
 401/**
 402 * pwm_set_waveform_might_sleep - Apply a new waveform
 403 * Cannot be used in atomic context.
 404 * @pwm: PWM device
 405 * @wf: The waveform to apply
 406 * @exact: If true no rounding is allowed
 407 *
 408 * Typically a requested waveform cannot be implemented exactly, e.g. because
 409 * you requested .period_length_ns = 100 ns, but the hardware can only set
 410 * periods that are a multiple of 8.5 ns. With that hardware passing @exact =
 411 * true results in pwm_set_waveform_might_sleep() failing and returning -EDOM.
 412 * If @exact = false you get a period of 93.5 ns (i.e. the biggest period not
 413 * bigger than the requested value).
 414 * Note that even with @exact = true, some rounding by less than 1 ns is
 415 * possible/needed. In the above example requesting .period_length_ns = 94 and
 416 * @exact = true, you get the hardware configured with period = 93.5 ns.
 417 *
 418 * Let C be the set of possible hardware configurations for a given PWM device,
 419 * consisting of tuples (p, d, o) where p is the period length, d is the duty
 420 * length and o the duty offset.
 421 *
 422 * The following algorithm is implemented to pick the hardware setting
 423 * (p, d, o) ∈ C for a given request (p', d', o') with @exact = false::
 424 *
 425 *   p = max( { ṗ | ∃ ḋ, ȯ : (ṗ, ḋ, ȯ) ∈ C ∧ ṗ ≤ p' } ∪ { min({ ṗ | ∃ ḋ, ȯ : (ṗ, ḋ, ȯ) ∈ C }) })
 426 *   d = max( { ḋ | ∃ ȯ : (p, ḋ, ȯ) ∈ C ∧ ḋ ≤ d' } ∪ { min({ ḋ | ∃ ȯ : (p, ḋ, ȯ) ∈ C }) })
 427 *   o = max( { ȯ | (p, d, ȯ) ∈ C ∧ ȯ ≤ o' } ∪ { min({ ȯ | (p, d, ȯ) ∈ C }) })
 428 *
 429 * In words: The chosen period length is the maximal possible period length not
 430 * bigger than the requested period length and if that doesn't exist, the
 431 * minimal period length. The chosen duty length is the maximal possible duty
 432 * length that is compatible with the chosen period length and isn't bigger than
 433 * the requested duty length. Again if such a value doesn't exist, the minimal
 434 * duty length compatible with the chosen period is picked. After that the duty
 435 * offset compatible with the chosen period and duty length is chosen in the
 436 * same way.
 437 *
 438 * Returns: 0 on success, -EDOM if setting failed due to the exact waveform not
 439 * being possible (if @exact), or a different negative errno on failure.
 440 * Context: May sleep.
 441 */
 442int pwm_set_waveform_might_sleep(struct pwm_device *pwm,
 443				 const struct pwm_waveform *wf, bool exact)
 444{
 445	struct pwm_chip *chip = pwm->chip;
 446	int err;
 447
 448	might_sleep();
 449
 450	guard(pwmchip)(chip);
 451
 452	if (!chip->operational)
 453		return -ENODEV;
 454
 455	if (IS_ENABLED(CONFIG_PWM_DEBUG) && chip->atomic) {
 456		/*
 457		 * Catch any drivers that have been marked as atomic but
 458		 * that will sleep anyway.
 459		 */
 460		non_block_start();
 461		err = __pwm_set_waveform(pwm, wf, exact);
 462		non_block_end();
 463	} else {
 464		err = __pwm_set_waveform(pwm, wf, exact);
 465	}
 466
 467	/*
 468	 * map err == 1 to -EDOM for exact requests and 0 for !exact ones. Also
 469	 * make sure that -EDOM is only returned in exactly that case. Note that
 470	 * __pwm_set_waveform() should never return -EDOM which justifies the
 471	 * unlikely().
 472	 */
 473	if (unlikely(err == -EDOM))
 474		err = -EINVAL;
 475	else if (exact && err == 1)
 476		err = -EDOM;
 477	else if (err == 1)
 478		err = 0;
 479
 480	return err;
 481}
 482EXPORT_SYMBOL_GPL(pwm_set_waveform_might_sleep);
 483
 484static void pwm_apply_debug(struct pwm_device *pwm,
 485			    const struct pwm_state *state)
 486{
 487	struct pwm_state *last = &pwm->last;
 488	struct pwm_chip *chip = pwm->chip;
 489	struct pwm_state s1 = { 0 }, s2 = { 0 };
 490	int err;
 491
 492	if (!IS_ENABLED(CONFIG_PWM_DEBUG))
 493		return;
 494
 495	/* No reasonable diagnosis possible without .get_state() */
 496	if (!chip->ops->get_state)
 497		return;
 498
 499	/*
 500	 * If a disabled PWM was requested the result is unspecified, so nothing
 501	 * to check.
 502	 */
 503	if (!state->enabled)
 504		return;
 505
 506	/*
 507	 * *state was just applied. Read out the hardware state and do some
 508	 * checks.
 509	 */
 510
 511	err = chip->ops->get_state(chip, pwm, &s1);
 512	trace_pwm_get(pwm, &s1, err);
 513	if (err)
 514		/* If that failed there isn't much to debug */
 515		return;
 516
 517	/*
 518	 * If the PWM was disabled that's maybe strange but there is nothing
 519	 * that can be sensibly checked then. So return early.
 520	 */
 521	if (!s1.enabled)
 522		return;
 523
 524	/*
 525	 * The lowlevel driver either ignored .polarity (which is a bug) or as
 526	 * best effort inverted .polarity and fixed .duty_cycle respectively.
 527	 * Undo this inversion and fixup for further tests.
 528	 */
 529	if (s1.polarity != state->polarity) {
 530		s2.polarity = state->polarity;
 531		s2.duty_cycle = s1.period - s1.duty_cycle;
 532		s2.period = s1.period;
 533		s2.enabled = true;
 534	} else {
 535		s2 = s1;
 536	}
 537
 538	if (s2.polarity != state->polarity &&
 539	    s2.duty_cycle < s2.period)
 540		dev_warn(pwmchip_parent(chip), ".apply ignored .polarity\n");
 541
 542	if (last->polarity == state->polarity &&
 543	    last->period > s2.period &&
 544	    last->period <= state->period)
 545		dev_warn(pwmchip_parent(chip),
 546			 ".apply didn't pick the best available period (requested: %llu, applied: %llu, possible: %llu)\n",
 547			 state->period, s2.period, last->period);
 548
 549	/*
 550	 * Rounding period up is fine only if duty_cycle is 0 then, because a
 551	 * flat line doesn't have a characteristic period.
 552	 */
 553	if (state->period < s2.period && s2.duty_cycle)
 554		dev_warn(pwmchip_parent(chip),
 555			 ".apply is supposed to round down period (requested: %llu, applied: %llu)\n",
 556			 state->period, s2.period);
 557
 558	if (last->polarity == state->polarity &&
 559	    last->period == s2.period &&
 560	    last->duty_cycle > s2.duty_cycle &&
 561	    last->duty_cycle <= state->duty_cycle)
 562		dev_warn(pwmchip_parent(chip),
 563			 ".apply didn't pick the best available duty cycle (requested: %llu/%llu, applied: %llu/%llu, possible: %llu/%llu)\n",
 564			 state->duty_cycle, state->period,
 565			 s2.duty_cycle, s2.period,
 566			 last->duty_cycle, last->period);
 567
 568	if (state->duty_cycle < s2.duty_cycle)
 569		dev_warn(pwmchip_parent(chip),
 570			 ".apply is supposed to round down duty_cycle (requested: %llu/%llu, applied: %llu/%llu)\n",
 571			 state->duty_cycle, state->period,
 572			 s2.duty_cycle, s2.period);
 573
 574	/* reapply the state that the driver reported being configured. */
 575	err = chip->ops->apply(chip, pwm, &s1);
 576	trace_pwm_apply(pwm, &s1, err);
 577	if (err) {
 578		*last = s1;
 579		dev_err(pwmchip_parent(chip), "failed to reapply current setting\n");
 580		return;
 581	}
 582
 583	*last = (struct pwm_state){ 0 };
 584	err = chip->ops->get_state(chip, pwm, last);
 585	trace_pwm_get(pwm, last, err);
 586	if (err)
 587		return;
 588
 589	/* reapplication of the current state should give an exact match */
 590	if (s1.enabled != last->enabled ||
 591	    s1.polarity != last->polarity ||
 592	    (s1.enabled && s1.period != last->period) ||
 593	    (s1.enabled && s1.duty_cycle != last->duty_cycle)) {
 594		dev_err(pwmchip_parent(chip),
 595			".apply is not idempotent (ena=%d pol=%d %llu/%llu) -> (ena=%d pol=%d %llu/%llu)\n",
 596			s1.enabled, s1.polarity, s1.duty_cycle, s1.period,
 597			last->enabled, last->polarity, last->duty_cycle,
 598			last->period);
 599	}
 600}
 601
 602static bool pwm_state_valid(const struct pwm_state *state)
 603{
 604	/*
 605	 * For a disabled state all other state description is irrelevant and
 606	 * and supposed to be ignored. So also ignore any strange values and
 607	 * consider the state ok.
 608	 */
 609	if (!state->enabled)
 610		return true;
 611
 612	if (!state->period)
 613		return false;
 614
 615	if (state->duty_cycle > state->period)
 616		return false;
 617
 618	return true;
 619}
 620
 621static int __pwm_apply(struct pwm_device *pwm, const struct pwm_state *state)
 622{
 623	struct pwm_chip *chip;
 624	const struct pwm_ops *ops;
 625	int err;
 626
 627	if (!pwm || !state)
 628		return -EINVAL;
 629
 630	if (!pwm_state_valid(state)) {
 631		/*
 632		 * Allow to transition from one invalid state to another.
 633		 * This ensures that you can e.g. change the polarity while
 634		 * the period is zero. (This happens on stm32 when the hardware
 635		 * is in its poweron default state.) This greatly simplifies
 636		 * working with the sysfs API where you can only change one
 637		 * parameter at a time.
 638		 */
 639		if (!pwm_state_valid(&pwm->state)) {
 640			pwm->state = *state;
 641			return 0;
 642		}
 643
 644		return -EINVAL;
 645	}
 646
 647	chip = pwm->chip;
 648	ops = chip->ops;
 649
 650	if (state->period == pwm->state.period &&
 651	    state->duty_cycle == pwm->state.duty_cycle &&
 652	    state->polarity == pwm->state.polarity &&
 653	    state->enabled == pwm->state.enabled &&
 654	    state->usage_power == pwm->state.usage_power)
 655		return 0;
 656
 657	if (pwmchip_supports_waveform(chip)) {
 658		struct pwm_waveform wf;
 659		char wfhw[PWM_WFHWSIZE];
 660
 661		BUG_ON(PWM_WFHWSIZE < ops->sizeof_wfhw);
 662
 663		pwm_state2wf(state, &wf);
 664
 665		/*
 666		 * The rounding is wrong here for states with inverted polarity.
 667		 * While .apply() rounds down duty_cycle (which represents the
 668		 * time from the start of the period to the inner edge),
 669		 * .round_waveform_tohw() rounds down the time the PWM is high.
 670		 * Can be fixed if the need arises, until reported otherwise
 671		 * let's assume that consumers don't care.
 672		 */
 673
 674		err = __pwm_round_waveform_tohw(chip, pwm, &wf, &wfhw);
 675		if (err) {
 676			if (err > 0)
 677				/*
 678				 * This signals an invalid request, typically
 679				 * the requested period (or duty_offset) is
 680				 * smaller than possible with the hardware.
 681				 */
 682				return -EINVAL;
 683
 684			return err;
 685		}
 686
 687		if (IS_ENABLED(CONFIG_PWM_DEBUG)) {
 688			struct pwm_waveform wf_rounded;
 689
 690			err = __pwm_round_waveform_fromhw(chip, pwm, &wfhw, &wf_rounded);
 691			if (err)
 692				return err;
 693
 694			if (!pwm_check_rounding(&wf, &wf_rounded))
 695				dev_err(&chip->dev, "Wrong rounding: requested %llu/%llu [+%llu], result %llu/%llu [+%llu]\n",
 696					wf.duty_length_ns, wf.period_length_ns, wf.duty_offset_ns,
 697					wf_rounded.duty_length_ns, wf_rounded.period_length_ns, wf_rounded.duty_offset_ns);
 698		}
 699
 700		err = __pwm_write_waveform(chip, pwm, &wfhw);
 701		if (err)
 702			return err;
 703
 704		pwm->state = *state;
 705
 706	} else {
 707		err = ops->apply(chip, pwm, state);
 708		trace_pwm_apply(pwm, state, err);
 709		if (err)
 710			return err;
 711
 712		pwm->state = *state;
 713
 714		/*
 715		 * only do this after pwm->state was applied as some
 716		 * implementations of .get_state() depend on this
 717		 */
 718		pwm_apply_debug(pwm, state);
 719	}
 720
 721	return 0;
 722}
 723
 724/**
 725 * pwm_apply_might_sleep() - atomically apply a new state to a PWM device
 726 * Cannot be used in atomic context.
 727 * @pwm: PWM device
 728 * @state: new state to apply
 729 *
 730 * Returns: 0 on success, or a negative errno
 731 * Context: May sleep.
 732 */
 733int pwm_apply_might_sleep(struct pwm_device *pwm, const struct pwm_state *state)
 734{
 735	int err;
 736	struct pwm_chip *chip = pwm->chip;
 737
 738	/*
 739	 * Some lowlevel driver's implementations of .apply() make use of
 740	 * mutexes, also with some drivers only returning when the new
 741	 * configuration is active calling pwm_apply_might_sleep() from atomic context
 742	 * is a bad idea. So make it explicit that calling this function might
 743	 * sleep.
 744	 */
 745	might_sleep();
 746
 747	guard(pwmchip)(chip);
 748
 749	if (!chip->operational)
 750		return -ENODEV;
 751
 752	if (IS_ENABLED(CONFIG_PWM_DEBUG) && chip->atomic) {
 753		/*
 754		 * Catch any drivers that have been marked as atomic but
 755		 * that will sleep anyway.
 756		 */
 757		non_block_start();
 758		err = __pwm_apply(pwm, state);
 759		non_block_end();
 760	} else {
 761		err = __pwm_apply(pwm, state);
 762	}
 763
 764	return err;
 765}
 766EXPORT_SYMBOL_GPL(pwm_apply_might_sleep);
 767
 768/**
 769 * pwm_apply_atomic() - apply a new state to a PWM device from atomic context
 770 * Not all PWM devices support this function, check with pwm_might_sleep().
 771 * @pwm: PWM device
 772 * @state: new state to apply
 773 *
 774 * Returns: 0 on success, or a negative errno
 775 * Context: Any
 776 */
 777int pwm_apply_atomic(struct pwm_device *pwm, const struct pwm_state *state)
 778{
 779	struct pwm_chip *chip = pwm->chip;
 780
 781	WARN_ONCE(!chip->atomic,
 782		  "sleeping PWM driver used in atomic context\n");
 783
 784	guard(pwmchip)(chip);
 785
 786	if (!chip->operational)
 787		return -ENODEV;
 788
 789	return __pwm_apply(pwm, state);
 790}
 791EXPORT_SYMBOL_GPL(pwm_apply_atomic);
 792
 793/**
 794 * pwm_get_state_hw() - get the current PWM state from hardware
 795 * @pwm: PWM device
 796 * @state: state to fill with the current PWM state
 797 *
 798 * Similar to pwm_get_state() but reads the current PWM state from hardware
 799 * instead of the requested state.
 800 *
 801 * Returns: 0 on success or a negative error code on failure.
 802 * Context: May sleep.
 803 */
 804int pwm_get_state_hw(struct pwm_device *pwm, struct pwm_state *state)
 805{
 806	struct pwm_chip *chip = pwm->chip;
 807	const struct pwm_ops *ops = chip->ops;
 808	int ret = -EOPNOTSUPP;
 809
 810	might_sleep();
 811
 812	guard(pwmchip)(chip);
 813
 814	if (!chip->operational)
 815		return -ENODEV;
 816
 817	if (pwmchip_supports_waveform(chip) && ops->read_waveform) {
 818		char wfhw[PWM_WFHWSIZE];
 819		struct pwm_waveform wf;
 820
 821		BUG_ON(PWM_WFHWSIZE < ops->sizeof_wfhw);
 822
 823		ret = __pwm_read_waveform(chip, pwm, &wfhw);
 824		if (ret)
 825			return ret;
 826
 827		ret = __pwm_round_waveform_fromhw(chip, pwm, &wfhw, &wf);
 828		if (ret)
 829			return ret;
 830
 831		pwm_wf2state(&wf, state);
 832
 833	} else if (ops->get_state) {
 834		ret = ops->get_state(chip, pwm, state);
 835		trace_pwm_get(pwm, state, ret);
 836	}
 837
 838	return ret;
 839}
 840EXPORT_SYMBOL_GPL(pwm_get_state_hw);
 841
 842/**
 843 * pwm_adjust_config() - adjust the current PWM config to the PWM arguments
 844 * @pwm: PWM device
 845 *
 846 * This function will adjust the PWM config to the PWM arguments provided
 847 * by the DT or PWM lookup table. This is particularly useful to adapt
 848 * the bootloader config to the Linux one.
 849 *
 850 * Returns: 0 on success or a negative error code on failure.
 851 * Context: May sleep.
 852 */
 853int pwm_adjust_config(struct pwm_device *pwm)
 854{
 855	struct pwm_state state;
 856	struct pwm_args pargs;
 857
 858	pwm_get_args(pwm, &pargs);
 859	pwm_get_state(pwm, &state);
 860
 861	/*
 862	 * If the current period is zero it means that either the PWM driver
 863	 * does not support initial state retrieval or the PWM has not yet
 864	 * been configured.
 865	 *
 866	 * In either case, we setup the new period and polarity, and assign a
 867	 * duty cycle of 0.
 868	 */
 869	if (!state.period) {
 870		state.duty_cycle = 0;
 871		state.period = pargs.period;
 872		state.polarity = pargs.polarity;
 873
 874		return pwm_apply_might_sleep(pwm, &state);
 875	}
 876
 877	/*
 878	 * Adjust the PWM duty cycle/period based on the period value provided
 879	 * in PWM args.
 880	 */
 881	if (pargs.period != state.period) {
 882		u64 dutycycle = (u64)state.duty_cycle * pargs.period;
 883
 884		do_div(dutycycle, state.period);
 885		state.duty_cycle = dutycycle;
 886		state.period = pargs.period;
 887	}
 888
 889	/*
 890	 * If the polarity changed, we should also change the duty cycle.
 891	 */
 892	if (pargs.polarity != state.polarity) {
 893		state.polarity = pargs.polarity;
 894		state.duty_cycle = state.period - state.duty_cycle;
 895	}
 896
 897	return pwm_apply_might_sleep(pwm, &state);
 898}
 899EXPORT_SYMBOL_GPL(pwm_adjust_config);
 900
 901/**
 902 * pwm_capture() - capture and report a PWM signal
 903 * @pwm: PWM device
 904 * @result: structure to fill with capture result
 905 * @timeout: time to wait, in milliseconds, before giving up on capture
 906 *
 907 * Returns: 0 on success or a negative error code on failure.
 908 */
 909static int pwm_capture(struct pwm_device *pwm, struct pwm_capture *result,
 910		       unsigned long timeout)
 911{
 912	struct pwm_chip *chip = pwm->chip;
 913	const struct pwm_ops *ops = chip->ops;
 914
 915	if (!ops->capture)
 916		return -ENOSYS;
 917
 918	/*
 919	 * Holding the pwm_lock is probably not needed. If you use pwm_capture()
 920	 * and you're interested to speed it up, please convince yourself it's
 921	 * really not needed, test and then suggest a patch on the mailing list.
 922	 */
 923	guard(mutex)(&pwm_lock);
 924
 925	guard(pwmchip)(chip);
 926
 927	if (!chip->operational)
 928		return -ENODEV;
 929
 930	return ops->capture(chip, pwm, result, timeout);
 931}
 932
 933static struct pwm_chip *pwmchip_find_by_name(const char *name)
 934{
 935	struct pwm_chip *chip;
 936	unsigned long id, tmp;
 937
 938	if (!name)
 939		return NULL;
 940
 941	guard(mutex)(&pwm_lock);
 942
 943	idr_for_each_entry_ul(&pwm_chips, chip, tmp, id) {
 944		if (device_match_name(pwmchip_parent(chip), name))
 945			return chip;
 946	}
 947
 948	return NULL;
 949}
 950
 951static int pwm_device_request(struct pwm_device *pwm, const char *label)
 952{
 953	int err;
 954	struct pwm_chip *chip = pwm->chip;
 955	const struct pwm_ops *ops = chip->ops;
 956
 957	if (test_bit(PWMF_REQUESTED, &pwm->flags))
 958		return -EBUSY;
 959
 960	/*
 961	 * This function is called while holding pwm_lock. As .operational only
 962	 * changes while holding this lock, checking it here without holding the
 963	 * chip lock is fine.
 964	 */
 965	if (!chip->operational)
 966		return -ENODEV;
 967
 968	if (!try_module_get(chip->owner))
 969		return -ENODEV;
 970
 971	if (!get_device(&chip->dev)) {
 972		err = -ENODEV;
 973		goto err_get_device;
 974	}
 975
 976	if (ops->request) {
 977		err = ops->request(chip, pwm);
 978		if (err) {
 979			put_device(&chip->dev);
 980err_get_device:
 981			module_put(chip->owner);
 982			return err;
 983		}
 984	}
 985
 986	if (ops->read_waveform || ops->get_state) {
 987		/*
 988		 * Zero-initialize state because most drivers are unaware of
 989		 * .usage_power. The other members of state are supposed to be
 990		 * set by lowlevel drivers. We still initialize the whole
 991		 * structure for simplicity even though this might paper over
 992		 * faulty implementations of .get_state().
 993		 */
 994		struct pwm_state state = { 0, };
 995
 996		err = pwm_get_state_hw(pwm, &state);
 997		if (!err)
 998			pwm->state = state;
 999
1000		if (IS_ENABLED(CONFIG_PWM_DEBUG))
1001			pwm->last = pwm->state;
1002	}
1003
1004	set_bit(PWMF_REQUESTED, &pwm->flags);
1005	pwm->label = label;
1006
1007	return 0;
1008}
1009
1010/**
1011 * pwm_request_from_chip() - request a PWM device relative to a PWM chip
1012 * @chip: PWM chip
1013 * @index: per-chip index of the PWM to request
1014 * @label: a literal description string of this PWM
1015 *
1016 * Returns: A pointer to the PWM device at the given index of the given PWM
1017 * chip. A negative error code is returned if the index is not valid for the
1018 * specified PWM chip or if the PWM device cannot be requested.
1019 */
1020static struct pwm_device *pwm_request_from_chip(struct pwm_chip *chip,
1021						unsigned int index,
1022						const char *label)
1023{
1024	struct pwm_device *pwm;
1025	int err;
1026
1027	if (!chip || index >= chip->npwm)
1028		return ERR_PTR(-EINVAL);
1029
1030	guard(mutex)(&pwm_lock);
1031
1032	pwm = &chip->pwms[index];
1033
1034	err = pwm_device_request(pwm, label);
1035	if (err < 0)
1036		return ERR_PTR(err);
1037
1038	return pwm;
1039}
1040
1041struct pwm_device *
1042of_pwm_xlate_with_flags(struct pwm_chip *chip, const struct of_phandle_args *args)
1043{
1044	struct pwm_device *pwm;
1045
1046	/* period in the second cell and flags in the third cell are optional */
1047	if (args->args_count < 1)
1048		return ERR_PTR(-EINVAL);
1049
1050	pwm = pwm_request_from_chip(chip, args->args[0], NULL);
1051	if (IS_ERR(pwm))
1052		return pwm;
1053
1054	if (args->args_count > 1)
1055		pwm->args.period = args->args[1];
1056
1057	pwm->args.polarity = PWM_POLARITY_NORMAL;
1058	if (args->args_count > 2 && args->args[2] & PWM_POLARITY_INVERTED)
1059		pwm->args.polarity = PWM_POLARITY_INVERSED;
1060
1061	return pwm;
1062}
1063EXPORT_SYMBOL_GPL(of_pwm_xlate_with_flags);
1064
1065/*
1066 * This callback is used for PXA PWM chips that only have a single PWM line.
1067 * For such chips you could argue that passing the line number (i.e. the first
1068 * parameter in the common case) is useless as it's always zero. So compared to
1069 * the default xlate function of_pwm_xlate_with_flags() the first parameter is
1070 * the default period and the second are flags.
1071 *
1072 * Note that if #pwm-cells = <3>, the semantic is the same as for
1073 * of_pwm_xlate_with_flags() to allow converting the affected driver to
1074 * #pwm-cells = <3> without breaking the legacy binding.
1075 *
1076 * Don't use for new drivers.
1077 */
1078struct pwm_device *
1079of_pwm_single_xlate(struct pwm_chip *chip, const struct of_phandle_args *args)
1080{
1081	struct pwm_device *pwm;
1082
1083	if (args->args_count >= 3)
1084		return of_pwm_xlate_with_flags(chip, args);
1085
1086	pwm = pwm_request_from_chip(chip, 0, NULL);
1087	if (IS_ERR(pwm))
1088		return pwm;
1089
1090	if (args->args_count > 0)
1091		pwm->args.period = args->args[0];
1092
1093	pwm->args.polarity = PWM_POLARITY_NORMAL;
1094	if (args->args_count > 1 && args->args[1] & PWM_POLARITY_INVERTED)
1095		pwm->args.polarity = PWM_POLARITY_INVERSED;
1096
1097	return pwm;
1098}
1099EXPORT_SYMBOL_GPL(of_pwm_single_xlate);
1100
1101struct pwm_export {
1102	struct device pwm_dev;
1103	struct pwm_device *pwm;
1104	struct mutex lock;
1105	struct pwm_state suspend;
1106};
1107
1108static inline struct pwm_chip *pwmchip_from_dev(struct device *pwmchip_dev)
1109{
1110	return container_of(pwmchip_dev, struct pwm_chip, dev);
1111}
1112
1113static inline struct pwm_export *pwmexport_from_dev(struct device *pwm_dev)
1114{
1115	return container_of(pwm_dev, struct pwm_export, pwm_dev);
1116}
1117
1118static inline struct pwm_device *pwm_from_dev(struct device *pwm_dev)
1119{
1120	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
1121
1122	return export->pwm;
1123}
1124
1125static ssize_t period_show(struct device *pwm_dev,
1126			   struct device_attribute *attr,
1127			   char *buf)
1128{
1129	const struct pwm_device *pwm = pwm_from_dev(pwm_dev);
1130	struct pwm_state state;
1131
1132	pwm_get_state(pwm, &state);
1133
1134	return sysfs_emit(buf, "%llu\n", state.period);
1135}
1136
1137static ssize_t period_store(struct device *pwm_dev,
1138			    struct device_attribute *attr,
1139			    const char *buf, size_t size)
1140{
1141	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
1142	struct pwm_device *pwm = export->pwm;
1143	struct pwm_state state;
1144	u64 val;
1145	int ret;
1146
1147	ret = kstrtou64(buf, 0, &val);
1148	if (ret)
1149		return ret;
1150
1151	guard(mutex)(&export->lock);
1152
1153	pwm_get_state(pwm, &state);
1154	state.period = val;
1155	ret = pwm_apply_might_sleep(pwm, &state);
1156
1157	return ret ? : size;
1158}
1159
1160static ssize_t duty_cycle_show(struct device *pwm_dev,
1161			       struct device_attribute *attr,
1162			       char *buf)
1163{
1164	const struct pwm_device *pwm = pwm_from_dev(pwm_dev);
1165	struct pwm_state state;
1166
1167	pwm_get_state(pwm, &state);
1168
1169	return sysfs_emit(buf, "%llu\n", state.duty_cycle);
1170}
1171
1172static ssize_t duty_cycle_store(struct device *pwm_dev,
1173				struct device_attribute *attr,
1174				const char *buf, size_t size)
1175{
1176	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
1177	struct pwm_device *pwm = export->pwm;
1178	struct pwm_state state;
1179	u64 val;
1180	int ret;
1181
1182	ret = kstrtou64(buf, 0, &val);
1183	if (ret)
1184		return ret;
1185
1186	guard(mutex)(&export->lock);
1187
1188	pwm_get_state(pwm, &state);
1189	state.duty_cycle = val;
1190	ret = pwm_apply_might_sleep(pwm, &state);
1191
1192	return ret ? : size;
1193}
1194
1195static ssize_t enable_show(struct device *pwm_dev,
1196			   struct device_attribute *attr,
1197			   char *buf)
1198{
1199	const struct pwm_device *pwm = pwm_from_dev(pwm_dev);
1200	struct pwm_state state;
1201
1202	pwm_get_state(pwm, &state);
1203
1204	return sysfs_emit(buf, "%d\n", state.enabled);
1205}
1206
1207static ssize_t enable_store(struct device *pwm_dev,
1208			    struct device_attribute *attr,
1209			    const char *buf, size_t size)
1210{
1211	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
1212	struct pwm_device *pwm = export->pwm;
1213	struct pwm_state state;
1214	int val, ret;
1215
1216	ret = kstrtoint(buf, 0, &val);
1217	if (ret)
1218		return ret;
1219
1220	guard(mutex)(&export->lock);
1221
1222	pwm_get_state(pwm, &state);
1223
1224	switch (val) {
1225	case 0:
1226		state.enabled = false;
1227		break;
1228	case 1:
1229		state.enabled = true;
1230		break;
1231	default:
1232		return -EINVAL;
1233	}
1234
1235	ret = pwm_apply_might_sleep(pwm, &state);
1236
1237	return ret ? : size;
1238}
1239
1240static ssize_t polarity_show(struct device *pwm_dev,
1241			     struct device_attribute *attr,
1242			     char *buf)
1243{
1244	const struct pwm_device *pwm = pwm_from_dev(pwm_dev);
1245	const char *polarity = "unknown";
1246	struct pwm_state state;
1247
1248	pwm_get_state(pwm, &state);
1249
1250	switch (state.polarity) {
1251	case PWM_POLARITY_NORMAL:
1252		polarity = "normal";
1253		break;
1254
1255	case PWM_POLARITY_INVERSED:
1256		polarity = "inversed";
1257		break;
1258	}
1259
1260	return sysfs_emit(buf, "%s\n", polarity);
1261}
1262
1263static ssize_t polarity_store(struct device *pwm_dev,
1264			      struct device_attribute *attr,
1265			      const char *buf, size_t size)
1266{
1267	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
1268	struct pwm_device *pwm = export->pwm;
1269	enum pwm_polarity polarity;
1270	struct pwm_state state;
1271	int ret;
1272
1273	if (sysfs_streq(buf, "normal"))
1274		polarity = PWM_POLARITY_NORMAL;
1275	else if (sysfs_streq(buf, "inversed"))
1276		polarity = PWM_POLARITY_INVERSED;
1277	else
1278		return -EINVAL;
1279
1280	guard(mutex)(&export->lock);
1281
1282	pwm_get_state(pwm, &state);
1283	state.polarity = polarity;
1284	ret = pwm_apply_might_sleep(pwm, &state);
1285
1286	return ret ? : size;
1287}
1288
1289static ssize_t capture_show(struct device *pwm_dev,
1290			    struct device_attribute *attr,
1291			    char *buf)
1292{
1293	struct pwm_device *pwm = pwm_from_dev(pwm_dev);
1294	struct pwm_capture result;
1295	int ret;
1296
1297	ret = pwm_capture(pwm, &result, jiffies_to_msecs(HZ));
1298	if (ret)
1299		return ret;
1300
1301	return sysfs_emit(buf, "%u %u\n", result.period, result.duty_cycle);
1302}
1303
1304static DEVICE_ATTR_RW(period);
1305static DEVICE_ATTR_RW(duty_cycle);
1306static DEVICE_ATTR_RW(enable);
1307static DEVICE_ATTR_RW(polarity);
1308static DEVICE_ATTR_RO(capture);
1309
1310static struct attribute *pwm_attrs[] = {
1311	&dev_attr_period.attr,
1312	&dev_attr_duty_cycle.attr,
1313	&dev_attr_enable.attr,
1314	&dev_attr_polarity.attr,
1315	&dev_attr_capture.attr,
1316	NULL
1317};
1318ATTRIBUTE_GROUPS(pwm);
1319
1320static void pwm_export_release(struct device *pwm_dev)
1321{
1322	struct pwm_export *export = pwmexport_from_dev(pwm_dev);
1323
1324	kfree(export);
1325}
1326
1327static int pwm_export_child(struct device *pwmchip_dev, struct pwm_device *pwm)
1328{
1329	struct pwm_export *export;
1330	char *pwm_prop[2];
1331	int ret;
1332
1333	if (test_and_set_bit(PWMF_EXPORTED, &pwm->flags))
1334		return -EBUSY;
1335
1336	export = kzalloc(sizeof(*export), GFP_KERNEL);
1337	if (!export) {
1338		clear_bit(PWMF_EXPORTED, &pwm->flags);
1339		return -ENOMEM;
1340	}
1341
1342	export->pwm = pwm;
1343	mutex_init(&export->lock);
1344
1345	export->pwm_dev.release = pwm_export_release;
1346	export->pwm_dev.parent = pwmchip_dev;
1347	export->pwm_dev.devt = MKDEV(0, 0);
1348	export->pwm_dev.groups = pwm_groups;
1349	dev_set_name(&export->pwm_dev, "pwm%u", pwm->hwpwm);
1350
1351	ret = device_register(&export->pwm_dev);
1352	if (ret) {
1353		clear_bit(PWMF_EXPORTED, &pwm->flags);
1354		put_device(&export->pwm_dev);
1355		export = NULL;
1356		return ret;
1357	}
1358	pwm_prop[0] = kasprintf(GFP_KERNEL, "EXPORT=pwm%u", pwm->hwpwm);
1359	pwm_prop[1] = NULL;
1360	kobject_uevent_env(&pwmchip_dev->kobj, KOBJ_CHANGE, pwm_prop);
1361	kfree(pwm_prop[0]);
1362
1363	return 0;
1364}
1365
1366static int pwm_unexport_match(struct device *pwm_dev, const void *data)
1367{
1368	return pwm_from_dev(pwm_dev) == data;
1369}
1370
1371static int pwm_unexport_child(struct device *pwmchip_dev, struct pwm_device *pwm)
1372{
1373	struct device *pwm_dev;
1374	char *pwm_prop[2];
1375
1376	if (!test_and_clear_bit(PWMF_EXPORTED, &pwm->flags))
1377		return -ENODEV;
1378
1379	pwm_dev = device_find_child(pwmchip_dev, pwm, pwm_unexport_match);
1380	if (!pwm_dev)
1381		return -ENODEV;
1382
1383	pwm_prop[0] = kasprintf(GFP_KERNEL, "UNEXPORT=pwm%u", pwm->hwpwm);
1384	pwm_prop[1] = NULL;
1385	kobject_uevent_env(&pwmchip_dev->kobj, KOBJ_CHANGE, pwm_prop);
1386	kfree(pwm_prop[0]);
1387
1388	/* for device_find_child() */
1389	put_device(pwm_dev);
1390	device_unregister(pwm_dev);
1391	pwm_put(pwm);
1392
1393	return 0;
1394}
1395
1396static ssize_t export_store(struct device *pwmchip_dev,
1397			    struct device_attribute *attr,
1398			    const char *buf, size_t len)
1399{
1400	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
1401	struct pwm_device *pwm;
1402	unsigned int hwpwm;
1403	int ret;
1404
1405	ret = kstrtouint(buf, 0, &hwpwm);
1406	if (ret < 0)
1407		return ret;
1408
1409	if (hwpwm >= chip->npwm)
1410		return -ENODEV;
1411
1412	pwm = pwm_request_from_chip(chip, hwpwm, "sysfs");
1413	if (IS_ERR(pwm))
1414		return PTR_ERR(pwm);
1415
1416	ret = pwm_export_child(pwmchip_dev, pwm);
1417	if (ret < 0)
1418		pwm_put(pwm);
1419
1420	return ret ? : len;
1421}
1422static DEVICE_ATTR_WO(export);
1423
1424static ssize_t unexport_store(struct device *pwmchip_dev,
1425			      struct device_attribute *attr,
1426			      const char *buf, size_t len)
1427{
1428	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
1429	unsigned int hwpwm;
1430	int ret;
1431
1432	ret = kstrtouint(buf, 0, &hwpwm);
1433	if (ret < 0)
1434		return ret;
1435
1436	if (hwpwm >= chip->npwm)
1437		return -ENODEV;
1438
1439	ret = pwm_unexport_child(pwmchip_dev, &chip->pwms[hwpwm]);
1440
1441	return ret ? : len;
1442}
1443static DEVICE_ATTR_WO(unexport);
1444
1445static ssize_t npwm_show(struct device *pwmchip_dev, struct device_attribute *attr,
1446			 char *buf)
1447{
1448	const struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
1449
1450	return sysfs_emit(buf, "%u\n", chip->npwm);
1451}
1452static DEVICE_ATTR_RO(npwm);
1453
1454static struct attribute *pwm_chip_attrs[] = {
1455	&dev_attr_export.attr,
1456	&dev_attr_unexport.attr,
1457	&dev_attr_npwm.attr,
1458	NULL,
1459};
1460ATTRIBUTE_GROUPS(pwm_chip);
1461
1462/* takes export->lock on success */
1463static struct pwm_export *pwm_class_get_state(struct device *pwmchip_dev,
1464					      struct pwm_device *pwm,
1465					      struct pwm_state *state)
1466{
1467	struct device *pwm_dev;
1468	struct pwm_export *export;
1469
1470	if (!test_bit(PWMF_EXPORTED, &pwm->flags))
1471		return NULL;
1472
1473	pwm_dev = device_find_child(pwmchip_dev, pwm, pwm_unexport_match);
1474	if (!pwm_dev)
1475		return NULL;
1476
1477	export = pwmexport_from_dev(pwm_dev);
1478	put_device(pwm_dev);	/* for device_find_child() */
1479
1480	mutex_lock(&export->lock);
1481	pwm_get_state(pwm, state);
1482
1483	return export;
1484}
1485
1486static int pwm_class_apply_state(struct pwm_export *export,
1487				 struct pwm_device *pwm,
1488				 struct pwm_state *state)
1489{
1490	int ret = pwm_apply_might_sleep(pwm, state);
1491
1492	/* release lock taken in pwm_class_get_state */
1493	mutex_unlock(&export->lock);
1494
1495	return ret;
1496}
1497
1498static int pwm_class_resume_npwm(struct device *pwmchip_dev, unsigned int npwm)
1499{
1500	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
1501	unsigned int i;
1502	int ret = 0;
1503
1504	for (i = 0; i < npwm; i++) {
1505		struct pwm_device *pwm = &chip->pwms[i];
1506		struct pwm_state state;
1507		struct pwm_export *export;
1508
1509		export = pwm_class_get_state(pwmchip_dev, pwm, &state);
1510		if (!export)
1511			continue;
1512
1513		/* If pwmchip was not enabled before suspend, do nothing. */
1514		if (!export->suspend.enabled) {
1515			/* release lock taken in pwm_class_get_state */
1516			mutex_unlock(&export->lock);
1517			continue;
1518		}
1519
1520		state.enabled = export->suspend.enabled;
1521		ret = pwm_class_apply_state(export, pwm, &state);
1522		if (ret < 0)
1523			break;
1524	}
1525
1526	return ret;
1527}
1528
1529static int pwm_class_suspend(struct device *pwmchip_dev)
1530{
1531	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
1532	unsigned int i;
1533	int ret = 0;
1534
1535	for (i = 0; i < chip->npwm; i++) {
1536		struct pwm_device *pwm = &chip->pwms[i];
1537		struct pwm_state state;
1538		struct pwm_export *export;
1539
1540		export = pwm_class_get_state(pwmchip_dev, pwm, &state);
1541		if (!export)
1542			continue;
1543
1544		/*
1545		 * If pwmchip was not enabled before suspend, save
1546		 * state for resume time and do nothing else.
1547		 */
1548		export->suspend = state;
1549		if (!state.enabled) {
1550			/* release lock taken in pwm_class_get_state */
1551			mutex_unlock(&export->lock);
1552			continue;
1553		}
1554
1555		state.enabled = false;
1556		ret = pwm_class_apply_state(export, pwm, &state);
1557		if (ret < 0) {
1558			/*
1559			 * roll back the PWM devices that were disabled by
1560			 * this suspend function.
1561			 */
1562			pwm_class_resume_npwm(pwmchip_dev, i);
1563			break;
1564		}
1565	}
1566
1567	return ret;
1568}
1569
1570static int pwm_class_resume(struct device *pwmchip_dev)
1571{
1572	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
1573
1574	return pwm_class_resume_npwm(pwmchip_dev, chip->npwm);
1575}
1576
1577static DEFINE_SIMPLE_DEV_PM_OPS(pwm_class_pm_ops, pwm_class_suspend, pwm_class_resume);
1578
1579static struct class pwm_class = {
1580	.name = "pwm",
1581	.dev_groups = pwm_chip_groups,
1582	.pm = pm_sleep_ptr(&pwm_class_pm_ops),
1583};
1584
1585static void pwmchip_sysfs_unexport(struct pwm_chip *chip)
1586{
1587	unsigned int i;
1588
1589	for (i = 0; i < chip->npwm; i++) {
1590		struct pwm_device *pwm = &chip->pwms[i];
1591
1592		if (test_bit(PWMF_EXPORTED, &pwm->flags))
1593			pwm_unexport_child(&chip->dev, pwm);
1594	}
1595}
1596
1597#define PWMCHIP_ALIGN ARCH_DMA_MINALIGN
1598
1599static void *pwmchip_priv(struct pwm_chip *chip)
1600{
1601	return (void *)chip + ALIGN(struct_size(chip, pwms, chip->npwm), PWMCHIP_ALIGN);
1602}
1603
1604/* This is the counterpart to pwmchip_alloc() */
1605void pwmchip_put(struct pwm_chip *chip)
1606{
1607	put_device(&chip->dev);
1608}
1609EXPORT_SYMBOL_GPL(pwmchip_put);
1610
1611void pwmchip_release(struct device *pwmchip_dev)
1612{
1613	struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev);
1614
1615	kfree(chip);
1616}
1617EXPORT_SYMBOL_GPL(pwmchip_release);
1618
1619struct pwm_chip *pwmchip_alloc(struct device *parent, unsigned int npwm, size_t sizeof_priv)
1620{
1621	struct pwm_chip *chip;
1622	struct device *pwmchip_dev;
1623	size_t alloc_size;
1624	unsigned int i;
1625
1626	alloc_size = size_add(ALIGN(struct_size(chip, pwms, npwm), PWMCHIP_ALIGN),
1627			      sizeof_priv);
1628
1629	chip = kzalloc(alloc_size, GFP_KERNEL);
1630	if (!chip)
1631		return ERR_PTR(-ENOMEM);
1632
1633	chip->npwm = npwm;
1634	chip->uses_pwmchip_alloc = true;
1635	chip->operational = false;
1636
1637	pwmchip_dev = &chip->dev;
1638	device_initialize(pwmchip_dev);
1639	pwmchip_dev->class = &pwm_class;
1640	pwmchip_dev->parent = parent;
1641	pwmchip_dev->release = pwmchip_release;
1642
1643	pwmchip_set_drvdata(chip, pwmchip_priv(chip));
1644
1645	for (i = 0; i < chip->npwm; i++) {
1646		struct pwm_device *pwm = &chip->pwms[i];
1647		pwm->chip = chip;
1648		pwm->hwpwm = i;
1649	}
1650
1651	return chip;
1652}
1653EXPORT_SYMBOL_GPL(pwmchip_alloc);
1654
1655static void devm_pwmchip_put(void *data)
1656{
1657	struct pwm_chip *chip = data;
1658
1659	pwmchip_put(chip);
1660}
1661
1662struct pwm_chip *devm_pwmchip_alloc(struct device *parent, unsigned int npwm, size_t sizeof_priv)
1663{
1664	struct pwm_chip *chip;
1665	int ret;
1666
1667	chip = pwmchip_alloc(parent, npwm, sizeof_priv);
1668	if (IS_ERR(chip))
1669		return chip;
1670
1671	ret = devm_add_action_or_reset(parent, devm_pwmchip_put, chip);
1672	if (ret)
1673		return ERR_PTR(ret);
1674
1675	return chip;
1676}
1677EXPORT_SYMBOL_GPL(devm_pwmchip_alloc);
1678
1679static void of_pwmchip_add(struct pwm_chip *chip)
1680{
1681	if (!pwmchip_parent(chip) || !pwmchip_parent(chip)->of_node)
1682		return;
1683
1684	if (!chip->of_xlate)
1685		chip->of_xlate = of_pwm_xlate_with_flags;
1686
1687	of_node_get(pwmchip_parent(chip)->of_node);
1688}
1689
1690static void of_pwmchip_remove(struct pwm_chip *chip)
1691{
1692	if (pwmchip_parent(chip))
1693		of_node_put(pwmchip_parent(chip)->of_node);
1694}
1695
1696static bool pwm_ops_check(const struct pwm_chip *chip)
1697{
1698	const struct pwm_ops *ops = chip->ops;
1699
1700	if (ops->write_waveform) {
1701		if (!ops->round_waveform_tohw ||
1702		    !ops->round_waveform_fromhw ||
1703		    !ops->write_waveform)
1704			return false;
1705
1706		if (PWM_WFHWSIZE < ops->sizeof_wfhw) {
1707			dev_warn(pwmchip_parent(chip), "PWM_WFHWSIZE < %zu\n", ops->sizeof_wfhw);
1708			return false;
1709		}
1710	} else {
1711		if (!ops->apply)
1712			return false;
1713
1714		if (IS_ENABLED(CONFIG_PWM_DEBUG) && !ops->get_state)
1715			dev_warn(pwmchip_parent(chip),
1716				 "Please implement the .get_state() callback\n");
1717	}
1718
1719	return true;
1720}
1721
1722static struct device_link *pwm_device_link_add(struct device *dev,
1723					       struct pwm_device *pwm)
1724{
1725	struct device_link *dl;
1726
1727	if (!dev) {
1728		/*
1729		 * No device for the PWM consumer has been provided. It may
1730		 * impact the PM sequence ordering: the PWM supplier may get
1731		 * suspended before the consumer.
1732		 */
1733		dev_warn(pwmchip_parent(pwm->chip),
1734			 "No consumer device specified to create a link to\n");
1735		return NULL;
1736	}
1737
1738	dl = device_link_add(dev, pwmchip_parent(pwm->chip), DL_FLAG_AUTOREMOVE_CONSUMER);
1739	if (!dl) {
1740		dev_err(dev, "failed to create device link to %s\n",
1741			dev_name(pwmchip_parent(pwm->chip)));
1742		return ERR_PTR(-EINVAL);
1743	}
1744
1745	return dl;
1746}
1747
1748static struct pwm_chip *fwnode_to_pwmchip(struct fwnode_handle *fwnode)
1749{
1750	struct pwm_chip *chip;
1751	unsigned long id, tmp;
1752
1753	guard(mutex)(&pwm_lock);
1754
1755	idr_for_each_entry_ul(&pwm_chips, chip, tmp, id)
1756		if (pwmchip_parent(chip) && device_match_fwnode(pwmchip_parent(chip), fwnode))
1757			return chip;
1758
1759	return ERR_PTR(-EPROBE_DEFER);
1760}
1761
1762/**
1763 * of_pwm_get() - request a PWM via the PWM framework
1764 * @dev: device for PWM consumer
1765 * @np: device node to get the PWM from
1766 * @con_id: consumer name
1767 *
1768 * Returns the PWM device parsed from the phandle and index specified in the
1769 * "pwms" property of a device tree node or a negative error-code on failure.
1770 * Values parsed from the device tree are stored in the returned PWM device
1771 * object.
1772 *
1773 * If con_id is NULL, the first PWM device listed in the "pwms" property will
1774 * be requested. Otherwise the "pwm-names" property is used to do a reverse
1775 * lookup of the PWM index. This also means that the "pwm-names" property
1776 * becomes mandatory for devices that look up the PWM device via the con_id
1777 * parameter.
1778 *
1779 * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
1780 * error code on failure.
1781 */
1782static struct pwm_device *of_pwm_get(struct device *dev, struct device_node *np,
1783				     const char *con_id)
1784{
1785	struct pwm_device *pwm = NULL;
1786	struct of_phandle_args args;
1787	struct device_link *dl;
1788	struct pwm_chip *chip;
1789	int index = 0;
1790	int err;
1791
1792	if (con_id) {
1793		index = of_property_match_string(np, "pwm-names", con_id);
1794		if (index < 0)
1795			return ERR_PTR(index);
1796	}
1797
1798	err = of_parse_phandle_with_args_map(np, "pwms", "pwm", index, &args);
1799	if (err) {
1800		pr_err("%s(): can't parse \"pwms\" property\n", __func__);
1801		return ERR_PTR(err);
1802	}
1803
1804	chip = fwnode_to_pwmchip(of_fwnode_handle(args.np));
1805	if (IS_ERR(chip)) {
1806		if (PTR_ERR(chip) != -EPROBE_DEFER)
1807			pr_err("%s(): PWM chip not found\n", __func__);
1808
1809		pwm = ERR_CAST(chip);
1810		goto put;
1811	}
1812
1813	pwm = chip->of_xlate(chip, &args);
1814	if (IS_ERR(pwm))
1815		goto put;
1816
1817	dl = pwm_device_link_add(dev, pwm);
1818	if (IS_ERR(dl)) {
1819		/* of_xlate ended up calling pwm_request_from_chip() */
1820		pwm_put(pwm);
1821		pwm = ERR_CAST(dl);
1822		goto put;
1823	}
1824
1825	/*
1826	 * If a consumer name was not given, try to look it up from the
1827	 * "pwm-names" property if it exists. Otherwise use the name of
1828	 * the user device node.
1829	 */
1830	if (!con_id) {
1831		err = of_property_read_string_index(np, "pwm-names", index,
1832						    &con_id);
1833		if (err < 0)
1834			con_id = np->name;
1835	}
1836
1837	pwm->label = con_id;
1838
1839put:
1840	of_node_put(args.np);
1841
1842	return pwm;
1843}
1844
1845/**
1846 * acpi_pwm_get() - request a PWM via parsing "pwms" property in ACPI
1847 * @fwnode: firmware node to get the "pwms" property from
1848 *
1849 * Returns the PWM device parsed from the fwnode and index specified in the
1850 * "pwms" property or a negative error-code on failure.
1851 * Values parsed from the device tree are stored in the returned PWM device
1852 * object.
1853 *
1854 * This is analogous to of_pwm_get() except con_id is not yet supported.
1855 * ACPI entries must look like
1856 * Package () {"pwms", Package ()
1857 *     { <PWM device reference>, <PWM index>, <PWM period> [, <PWM flags>]}}
1858 *
1859 * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
1860 * error code on failure.
1861 */
1862static struct pwm_device *acpi_pwm_get(const struct fwnode_handle *fwnode)
1863{
1864	struct pwm_device *pwm;
1865	struct fwnode_reference_args args;
1866	struct pwm_chip *chip;
1867	int ret;
1868
1869	memset(&args, 0, sizeof(args));
1870
1871	ret = __acpi_node_get_property_reference(fwnode, "pwms", 0, 3, &args);
1872	if (ret < 0)
1873		return ERR_PTR(ret);
1874
1875	if (args.nargs < 2)
1876		return ERR_PTR(-EPROTO);
1877
1878	chip = fwnode_to_pwmchip(args.fwnode);
1879	if (IS_ERR(chip))
1880		return ERR_CAST(chip);
1881
1882	pwm = pwm_request_from_chip(chip, args.args[0], NULL);
1883	if (IS_ERR(pwm))
1884		return pwm;
1885
1886	pwm->args.period = args.args[1];
1887	pwm->args.polarity = PWM_POLARITY_NORMAL;
1888
1889	if (args.nargs > 2 && args.args[2] & PWM_POLARITY_INVERTED)
1890		pwm->args.polarity = PWM_POLARITY_INVERSED;
1891
1892	return pwm;
1893}
1894
1895static DEFINE_MUTEX(pwm_lookup_lock);
1896static LIST_HEAD(pwm_lookup_list);
1897
1898/**
1899 * pwm_get() - look up and request a PWM device
1900 * @dev: device for PWM consumer
1901 * @con_id: consumer name
1902 *
1903 * Lookup is first attempted using DT. If the device was not instantiated from
1904 * a device tree, a PWM chip and a relative index is looked up via a table
1905 * supplied by board setup code (see pwm_add_table()).
1906 *
1907 * Once a PWM chip has been found the specified PWM device will be requested
1908 * and is ready to be used.
1909 *
1910 * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
1911 * error code on failure.
1912 */
1913struct pwm_device *pwm_get(struct device *dev, const char *con_id)
1914{
1915	const struct fwnode_handle *fwnode = dev ? dev_fwnode(dev) : NULL;
1916	const char *dev_id = dev ? dev_name(dev) : NULL;
1917	struct pwm_device *pwm;
1918	struct pwm_chip *chip;
1919	struct device_link *dl;
1920	unsigned int best = 0;
1921	struct pwm_lookup *p, *chosen = NULL;
1922	unsigned int match;
1923	int err;
1924
1925	/* look up via DT first */
1926	if (is_of_node(fwnode))
1927		return of_pwm_get(dev, to_of_node(fwnode), con_id);
1928
1929	/* then lookup via ACPI */
1930	if (is_acpi_node(fwnode)) {
1931		pwm = acpi_pwm_get(fwnode);
1932		if (!IS_ERR(pwm) || PTR_ERR(pwm) != -ENOENT)
1933			return pwm;
1934	}
1935
1936	/*
1937	 * We look up the provider in the static table typically provided by
1938	 * board setup code. We first try to lookup the consumer device by
1939	 * name. If the consumer device was passed in as NULL or if no match
1940	 * was found, we try to find the consumer by directly looking it up
1941	 * by name.
1942	 *
1943	 * If a match is found, the provider PWM chip is looked up by name
1944	 * and a PWM device is requested using the PWM device per-chip index.
1945	 *
1946	 * The lookup algorithm was shamelessly taken from the clock
1947	 * framework:
1948	 *
1949	 * We do slightly fuzzy matching here:
1950	 *  An entry with a NULL ID is assumed to be a wildcard.
1951	 *  If an entry has a device ID, it must match
1952	 *  If an entry has a connection ID, it must match
1953	 * Then we take the most specific entry - with the following order
1954	 * of precedence: dev+con > dev only > con only.
1955	 */
1956	scoped_guard(mutex, &pwm_lookup_lock)
1957		list_for_each_entry(p, &pwm_lookup_list, list) {
1958			match = 0;
1959
1960			if (p->dev_id) {
1961				if (!dev_id || strcmp(p->dev_id, dev_id))
1962					continue;
1963
1964				match += 2;
1965			}
1966
1967			if (p->con_id) {
1968				if (!con_id || strcmp(p->con_id, con_id))
1969					continue;
1970
1971				match += 1;
1972			}
1973
1974			if (match > best) {
1975				chosen = p;
1976
1977				if (match != 3)
1978					best = match;
1979				else
1980					break;
1981			}
1982		}
1983
1984	if (!chosen)
1985		return ERR_PTR(-ENODEV);
1986
1987	chip = pwmchip_find_by_name(chosen->provider);
1988
1989	/*
1990	 * If the lookup entry specifies a module, load the module and retry
1991	 * the PWM chip lookup. This can be used to work around driver load
1992	 * ordering issues if driver's can't be made to properly support the
1993	 * deferred probe mechanism.
1994	 */
1995	if (!chip && chosen->module) {
1996		err = request_module(chosen->module);
1997		if (err == 0)
1998			chip = pwmchip_find_by_name(chosen->provider);
1999	}
2000
2001	if (!chip)
2002		return ERR_PTR(-EPROBE_DEFER);
2003
2004	pwm = pwm_request_from_chip(chip, chosen->index, con_id ?: dev_id);
2005	if (IS_ERR(pwm))
2006		return pwm;
2007
2008	dl = pwm_device_link_add(dev, pwm);
2009	if (IS_ERR(dl)) {
2010		pwm_put(pwm);
2011		return ERR_CAST(dl);
2012	}
2013
2014	pwm->args.period = chosen->period;
2015	pwm->args.polarity = chosen->polarity;
2016
2017	return pwm;
2018}
2019EXPORT_SYMBOL_GPL(pwm_get);
2020
2021static void __pwm_put(struct pwm_device *pwm)
2022{
2023	struct pwm_chip *chip = pwm->chip;
2024
2025	/*
2026	 * Trigger a warning if a consumer called pwm_put() twice.
2027	 * If the chip isn't operational, PWMF_REQUESTED was already cleared in
2028	 * pwmchip_remove(). So don't warn in this case.
2029	 */
2030	if (chip->operational && !test_and_clear_bit(PWMF_REQUESTED, &pwm->flags)) {
2031		pr_warn("PWM device already freed\n");
2032		return;
2033	}
2034
2035	if (chip->operational && chip->ops->free)
2036		pwm->chip->ops->free(pwm->chip, pwm);
2037
2038	pwm->label = NULL;
2039
2040	put_device(&chip->dev);
2041
2042	module_put(chip->owner);
2043}
2044
2045/**
2046 * pwm_put() - release a PWM device
2047 * @pwm: PWM device
2048 */
2049void pwm_put(struct pwm_device *pwm)
2050{
2051	if (!pwm)
2052		return;
2053
2054	guard(mutex)(&pwm_lock);
2055
2056	__pwm_put(pwm);
2057}
2058EXPORT_SYMBOL_GPL(pwm_put);
2059
2060static void devm_pwm_release(void *pwm)
2061{
2062	pwm_put(pwm);
2063}
2064
2065/**
2066 * devm_pwm_get() - resource managed pwm_get()
2067 * @dev: device for PWM consumer
2068 * @con_id: consumer name
2069 *
2070 * This function performs like pwm_get() but the acquired PWM device will
2071 * automatically be released on driver detach.
2072 *
2073 * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
2074 * error code on failure.
2075 */
2076struct pwm_device *devm_pwm_get(struct device *dev, const char *con_id)
2077{
2078	struct pwm_device *pwm;
2079	int ret;
2080
2081	pwm = pwm_get(dev, con_id);
2082	if (IS_ERR(pwm))
2083		return pwm;
2084
2085	ret = devm_add_action_or_reset(dev, devm_pwm_release, pwm);
2086	if (ret)
2087		return ERR_PTR(ret);
2088
2089	return pwm;
2090}
2091EXPORT_SYMBOL_GPL(devm_pwm_get);
2092
2093/**
2094 * devm_fwnode_pwm_get() - request a resource managed PWM from firmware node
2095 * @dev: device for PWM consumer
2096 * @fwnode: firmware node to get the PWM from
2097 * @con_id: consumer name
2098 *
2099 * Returns the PWM device parsed from the firmware node. See of_pwm_get() and
2100 * acpi_pwm_get() for a detailed description.
2101 *
2102 * Returns: A pointer to the requested PWM device or an ERR_PTR()-encoded
2103 * error code on failure.
2104 */
2105struct pwm_device *devm_fwnode_pwm_get(struct device *dev,
2106				       struct fwnode_handle *fwnode,
2107				       const char *con_id)
2108{
2109	struct pwm_device *pwm = ERR_PTR(-ENODEV);
2110	int ret;
2111
2112	if (is_of_node(fwnode))
2113		pwm = of_pwm_get(dev, to_of_node(fwnode), con_id);
2114	else if (is_acpi_node(fwnode))
2115		pwm = acpi_pwm_get(fwnode);
2116	if (IS_ERR(pwm))
2117		return pwm;
2118
2119	ret = devm_add_action_or_reset(dev, devm_pwm_release, pwm);
2120	if (ret)
2121		return ERR_PTR(ret);
2122
2123	return pwm;
2124}
2125EXPORT_SYMBOL_GPL(devm_fwnode_pwm_get);
2126
2127struct pwm_cdev_data {
2128	struct pwm_chip *chip;
2129	struct pwm_device *pwm[];
2130};
2131
2132static int pwm_cdev_open(struct inode *inode, struct file *file)
2133{
2134	struct pwm_chip *chip = container_of(inode->i_cdev, struct pwm_chip, cdev);
2135	struct pwm_cdev_data *cdata;
2136
2137	guard(mutex)(&pwm_lock);
2138
2139	if (!chip->operational)
2140		return -ENXIO;
2141
2142	cdata = kzalloc(struct_size(cdata, pwm, chip->npwm), GFP_KERNEL);
2143	if (!cdata)
2144		return -ENOMEM;
2145
2146	cdata->chip = chip;
2147
2148	file->private_data = cdata;
2149
2150	return nonseekable_open(inode, file);
2151}
2152
2153static int pwm_cdev_release(struct inode *inode, struct file *file)
2154{
2155	struct pwm_cdev_data *cdata = file->private_data;
2156	unsigned int i;
2157
2158	for (i = 0; i < cdata->chip->npwm; ++i) {
2159		struct pwm_device *pwm = cdata->pwm[i];
2160
2161		if (pwm) {
2162			const char *label = pwm->label;
2163
2164			pwm_put(cdata->pwm[i]);
2165			kfree(label);
2166		}
2167	}
2168	kfree(cdata);
2169
2170	return 0;
2171}
2172
2173static int pwm_cdev_request(struct pwm_cdev_data *cdata, unsigned int hwpwm)
2174{
2175	struct pwm_chip *chip = cdata->chip;
2176
2177	if (hwpwm >= chip->npwm)
2178		return -EINVAL;
2179
2180	if (!cdata->pwm[hwpwm]) {
2181		struct pwm_device *pwm = &chip->pwms[hwpwm];
2182		const char *label;
2183		int ret;
2184
2185		label = kasprintf(GFP_KERNEL, "pwm-cdev (pid=%d)", current->pid);
2186		if (!label)
2187			return -ENOMEM;
2188
2189		ret = pwm_device_request(pwm, label);
2190		if (ret < 0) {
2191			kfree(label);
2192			return ret;
2193		}
2194
2195		cdata->pwm[hwpwm] = pwm;
2196	}
2197
2198	return 0;
2199}
2200
2201static int pwm_cdev_free(struct pwm_cdev_data *cdata, unsigned int hwpwm)
2202{
2203	struct pwm_chip *chip = cdata->chip;
2204
2205	if (hwpwm >= chip->npwm)
2206		return -EINVAL;
2207
2208	if (cdata->pwm[hwpwm]) {
2209		struct pwm_device *pwm = cdata->pwm[hwpwm];
2210		const char *label = pwm->label;
2211
2212		__pwm_put(pwm);
2213
2214		kfree(label);
2215
2216		cdata->pwm[hwpwm] = NULL;
2217	}
2218
2219	return 0;
2220}
2221
2222static struct pwm_device *pwm_cdev_get_requested_pwm(struct pwm_cdev_data *cdata,
2223						     u32 hwpwm)
2224{
2225	struct pwm_chip *chip = cdata->chip;
2226
2227	if (hwpwm >= chip->npwm)
2228		return ERR_PTR(-EINVAL);
2229
2230	if (cdata->pwm[hwpwm])
2231		return cdata->pwm[hwpwm];
2232
2233	return ERR_PTR(-EINVAL);
2234}
2235
2236static long pwm_cdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2237{
2238	int ret = 0;
2239	struct pwm_cdev_data *cdata = file->private_data;
2240	struct pwm_chip *chip = cdata->chip;
2241
2242	guard(mutex)(&pwm_lock);
2243
2244	if (!chip->operational)
2245		return -ENODEV;
2246
2247	switch (cmd) {
2248	case PWM_IOCTL_REQUEST:
2249		{
2250			unsigned int hwpwm = arg;
2251
2252			return pwm_cdev_request(cdata, hwpwm);
2253		}
2254
2255	case PWM_IOCTL_FREE:
2256		{
2257			unsigned int hwpwm = arg;
2258
2259			return pwm_cdev_free(cdata, hwpwm);
2260		}
2261
2262	case PWM_IOCTL_ROUNDWF:
2263		{
2264			struct pwmchip_waveform cwf;
2265			struct pwm_waveform wf;
2266			struct pwm_device *pwm;
2267
2268			ret = copy_from_user(&cwf,
2269					     (struct pwmchip_waveform __user *)arg,
2270					     sizeof(cwf));
2271			if (ret)
2272				return -EFAULT;
2273
2274			if (cwf.__pad != 0)
2275				return -EINVAL;
2276
2277			pwm = pwm_cdev_get_requested_pwm(cdata, cwf.hwpwm);
2278			if (IS_ERR(pwm))
2279				return PTR_ERR(pwm);
2280
2281			wf = (struct pwm_waveform) {
2282				.period_length_ns = cwf.period_length_ns,
2283				.duty_length_ns = cwf.duty_length_ns,
2284				.duty_offset_ns = cwf.duty_offset_ns,
2285			};
2286
2287			ret = pwm_round_waveform_might_sleep(pwm, &wf);
2288			if (ret < 0)
2289				return ret;
2290
2291			cwf = (struct pwmchip_waveform) {
2292				.hwpwm = cwf.hwpwm,
2293				.period_length_ns = wf.period_length_ns,
2294				.duty_length_ns = wf.duty_length_ns,
2295				.duty_offset_ns = wf.duty_offset_ns,
2296			};
2297
2298			ret = copy_to_user((struct pwmchip_waveform __user *)arg,
2299					   &cwf, sizeof(cwf));
2300			return ret ? -EFAULT : 0;
2301		}
2302
2303	case PWM_IOCTL_GETWF:
2304		{
2305			struct pwmchip_waveform cwf;
2306			struct pwm_waveform wf;
2307			struct pwm_device *pwm;
2308
2309			ret = copy_from_user(&cwf,
2310					     (struct pwmchip_waveform __user *)arg,
2311					     sizeof(cwf));
2312			if (ret)
2313				return -EFAULT;
2314
2315			if (cwf.__pad != 0)
2316				return -EINVAL;
2317
2318			pwm = pwm_cdev_get_requested_pwm(cdata, cwf.hwpwm);
2319			if (IS_ERR(pwm))
2320				return PTR_ERR(pwm);
2321
2322			ret = pwm_get_waveform_might_sleep(pwm, &wf);
2323			if (ret)
2324				return ret;
2325
2326			cwf = (struct pwmchip_waveform) {
2327				.hwpwm = cwf.hwpwm,
2328				.period_length_ns = wf.period_length_ns,
2329				.duty_length_ns = wf.duty_length_ns,
2330				.duty_offset_ns = wf.duty_offset_ns,
2331			};
2332
2333			ret = copy_to_user((struct pwmchip_waveform __user *)arg,
2334					   &cwf, sizeof(cwf));
2335			return ret ? -EFAULT : 0;
2336		}
2337
2338	case PWM_IOCTL_SETROUNDEDWF:
2339	case PWM_IOCTL_SETEXACTWF:
2340		{
2341			struct pwmchip_waveform cwf;
2342			struct pwm_waveform wf;
2343			struct pwm_device *pwm;
2344
2345			ret = copy_from_user(&cwf,
2346					     (struct pwmchip_waveform __user *)arg,
2347					     sizeof(cwf));
2348			if (ret)
2349				return -EFAULT;
2350
2351			if (cwf.__pad != 0)
2352				return -EINVAL;
2353
2354			wf = (struct pwm_waveform){
2355				.period_length_ns = cwf.period_length_ns,
2356				.duty_length_ns = cwf.duty_length_ns,
2357				.duty_offset_ns = cwf.duty_offset_ns,
2358			};
2359
2360			if (!pwm_wf_valid(&wf))
2361				return -EINVAL;
2362
2363			pwm = pwm_cdev_get_requested_pwm(cdata, cwf.hwpwm);
2364			if (IS_ERR(pwm))
2365				return PTR_ERR(pwm);
2366
2367			ret = pwm_set_waveform_might_sleep(pwm, &wf,
2368							   cmd == PWM_IOCTL_SETEXACTWF);
2369
2370			/*
2371			 * If userspace cares about rounding deviations it has
2372			 * to check the values anyhow, so simplify handling for
2373			 * them and don't signal uprounding. This matches the
2374			 * behaviour of PWM_IOCTL_ROUNDWF which also returns 0
2375			 * in that case.
2376			 */
2377			if (ret == 1)
2378				ret = 0;
2379
2380			return ret;
2381		}
2382
2383	default:
2384		return -ENOTTY;
2385	}
2386}
2387
2388static const struct file_operations pwm_cdev_fileops = {
2389	.open = pwm_cdev_open,
2390	.release = pwm_cdev_release,
2391	.owner = THIS_MODULE,
2392	.unlocked_ioctl = pwm_cdev_ioctl,
2393};
2394
2395static dev_t pwm_devt;
2396
2397static int pwm_gpio_request(struct gpio_chip *gc, unsigned int offset)
2398{
2399	struct pwm_chip *chip = gpiochip_get_data(gc);
2400	struct pwm_device *pwm;
2401
2402	pwm = pwm_request_from_chip(chip, offset, "pwm-gpio");
2403	if (IS_ERR(pwm))
2404		return PTR_ERR(pwm);
2405
2406	return 0;
2407}
2408
2409static void pwm_gpio_free(struct gpio_chip *gc, unsigned int offset)
2410{
2411	struct pwm_chip *chip = gpiochip_get_data(gc);
2412
2413	pwm_put(&chip->pwms[offset]);
2414}
2415
2416static int pwm_gpio_get_direction(struct gpio_chip *gc, unsigned int offset)
2417{
2418	return GPIO_LINE_DIRECTION_OUT;
2419}
2420
2421static int pwm_gpio_set(struct gpio_chip *gc, unsigned int offset, int value)
2422{
2423	struct pwm_chip *chip = gpiochip_get_data(gc);
2424	struct pwm_device *pwm = &chip->pwms[offset];
2425	int ret;
2426	struct pwm_waveform wf = {
2427		.period_length_ns = 1,
2428	};
2429
2430	ret = pwm_round_waveform_might_sleep(pwm, &wf);
2431	if (ret < 0)
2432		return ret;
2433
2434	if (value)
2435		wf.duty_length_ns = wf.period_length_ns;
2436	else
2437		wf.duty_length_ns = 0;
2438
2439	return pwm_set_waveform_might_sleep(pwm, &wf, true);
2440}
2441
2442/**
2443 * __pwmchip_add() - register a new PWM chip
2444 * @chip: the PWM chip to add
2445 * @owner: reference to the module providing the chip.
2446 *
2447 * Register a new PWM chip. @owner is supposed to be THIS_MODULE, use the
2448 * pwmchip_add wrapper to do this right.
2449 *
2450 * Returns: 0 on success or a negative error code on failure.
2451 */
2452int __pwmchip_add(struct pwm_chip *chip, struct module *owner)
2453{
2454	int ret;
2455
2456	if (!chip || !pwmchip_parent(chip) || !chip->ops || !chip->npwm)
2457		return -EINVAL;
2458
2459	/*
2460	 * a struct pwm_chip must be allocated using (devm_)pwmchip_alloc,
2461	 * otherwise the embedded struct device might disappear too early
2462	 * resulting in memory corruption.
2463	 * Catch drivers that were not converted appropriately.
2464	 */
2465	if (!chip->uses_pwmchip_alloc)
2466		return -EINVAL;
2467
2468	if (!pwm_ops_check(chip))
2469		return -EINVAL;
2470
2471	chip->owner = owner;
2472
2473	if (chip->atomic)
2474		spin_lock_init(&chip->atomic_lock);
2475	else
2476		mutex_init(&chip->nonatomic_lock);
2477
2478	guard(mutex)(&pwm_lock);
2479
2480	ret = idr_alloc(&pwm_chips, chip, 0, 0, GFP_KERNEL);
2481	if (ret < 0)
2482		return ret;
2483
2484	chip->id = ret;
2485
2486	dev_set_name(&chip->dev, "pwmchip%u", chip->id);
2487
2488	if (IS_ENABLED(CONFIG_OF))
2489		of_pwmchip_add(chip);
2490
2491	scoped_guard(pwmchip, chip)
2492		chip->operational = true;
2493
2494	if (chip->ops->write_waveform) {
2495		if (chip->id < PWM_MINOR_COUNT)
2496			chip->dev.devt = MKDEV(MAJOR(pwm_devt), chip->id);
2497		else
2498			dev_warn(&chip->dev, "chip id too high to create a chardev\n");
2499	}
2500
2501	cdev_init(&chip->cdev, &pwm_cdev_fileops);
2502	chip->cdev.owner = owner;
2503
2504	ret = cdev_device_add(&chip->cdev, &chip->dev);
2505	if (ret)
2506		goto err_device_add;
2507
2508	if (IS_ENABLED(CONFIG_PWM_PROVIDE_GPIO) && chip->ops->write_waveform) {
2509		struct device *parent = pwmchip_parent(chip);
2510
2511		chip->gpio = (typeof(chip->gpio)){
2512			.label = dev_name(parent),
2513			.parent = parent,
2514			.request = pwm_gpio_request,
2515			.free = pwm_gpio_free,
2516			.get_direction = pwm_gpio_get_direction,
2517			.set = pwm_gpio_set,
2518			.base = -1,
2519			.ngpio = chip->npwm,
2520			.can_sleep = true,
2521		};
2522
2523		ret = gpiochip_add_data(&chip->gpio, chip);
2524		if (ret)
2525			goto err_gpiochip_add;
2526	}
2527
2528	return 0;
2529
2530err_gpiochip_add:
2531
2532	cdev_device_del(&chip->cdev, &chip->dev);
2533err_device_add:
2534
2535	scoped_guard(pwmchip, chip)
2536		chip->operational = false;
2537
2538	if (IS_ENABLED(CONFIG_OF))
2539		of_pwmchip_remove(chip);
2540
2541	idr_remove(&pwm_chips, chip->id);
2542
2543	return ret;
2544}
2545EXPORT_SYMBOL_GPL(__pwmchip_add);
2546
2547/**
2548 * pwmchip_remove() - remove a PWM chip
2549 * @chip: the PWM chip to remove
2550 *
2551 * Removes a PWM chip.
2552 */
2553void pwmchip_remove(struct pwm_chip *chip)
2554{
2555	if (IS_ENABLED(CONFIG_PWM_PROVIDE_GPIO) && chip->ops->write_waveform)
2556		gpiochip_remove(&chip->gpio);
2557
2558	pwmchip_sysfs_unexport(chip);
2559
2560	scoped_guard(mutex, &pwm_lock) {
2561		unsigned int i;
2562
2563		scoped_guard(pwmchip, chip)
2564			chip->operational = false;
2565
2566		for (i = 0; i < chip->npwm; ++i) {
2567			struct pwm_device *pwm = &chip->pwms[i];
2568
2569			if (test_and_clear_bit(PWMF_REQUESTED, &pwm->flags)) {
2570				dev_warn(&chip->dev, "Freeing requested PWM #%u\n", i);
2571				if (pwm->chip->ops->free)
2572					pwm->chip->ops->free(pwm->chip, pwm);
2573			}
2574		}
2575
2576		if (IS_ENABLED(CONFIG_OF))
2577			of_pwmchip_remove(chip);
2578
2579		idr_remove(&pwm_chips, chip->id);
2580	}
2581
2582	cdev_device_del(&chip->cdev, &chip->dev);
2583}
2584EXPORT_SYMBOL_GPL(pwmchip_remove);
2585
2586static void devm_pwmchip_remove(void *data)
2587{
2588	struct pwm_chip *chip = data;
2589
2590	pwmchip_remove(chip);
2591}
2592
2593int __devm_pwmchip_add(struct device *dev, struct pwm_chip *chip, struct module *owner)
2594{
2595	int ret;
2596
2597	ret = __pwmchip_add(chip, owner);
2598	if (ret)
2599		return ret;
2600
2601	return devm_add_action_or_reset(dev, devm_pwmchip_remove, chip);
2602}
2603EXPORT_SYMBOL_GPL(__devm_pwmchip_add);
2604
2605/**
2606 * pwm_add_table() - register PWM device consumers
2607 * @table: array of consumers to register
2608 * @num: number of consumers in table
2609 */
2610void pwm_add_table(struct pwm_lookup *table, size_t num)
2611{
2612	guard(mutex)(&pwm_lookup_lock);
2613
2614	while (num--) {
2615		list_add_tail(&table->list, &pwm_lookup_list);
2616		table++;
2617	}
2618}
2619
2620/**
2621 * pwm_remove_table() - unregister PWM device consumers
2622 * @table: array of consumers to unregister
2623 * @num: number of consumers in table
2624 */
2625void pwm_remove_table(struct pwm_lookup *table, size_t num)
2626{
2627	guard(mutex)(&pwm_lookup_lock);
2628
2629	while (num--) {
2630		list_del(&table->list);
2631		table++;
2632	}
2633}
2634
2635static void pwm_dbg_show(struct pwm_chip *chip, struct seq_file *s)
2636{
2637	unsigned int i;
2638
2639	for (i = 0; i < chip->npwm; i++) {
2640		struct pwm_device *pwm = &chip->pwms[i];
2641		struct pwm_state state, hwstate;
2642
2643		pwm_get_state(pwm, &state);
2644		pwm_get_state_hw(pwm, &hwstate);
2645
2646		seq_printf(s, " pwm-%-3d (%-20.20s):", i, pwm->label);
2647
2648		if (test_bit(PWMF_REQUESTED, &pwm->flags))
2649			seq_puts(s, " requested");
2650
2651		seq_puts(s, "\n");
2652
2653		seq_printf(s, "  requested configuration: %3sabled, %llu/%llu ns, %s polarity",
2654			   state.enabled ? "en" : "dis", state.duty_cycle, state.period,
2655			   state.polarity ? "inverse" : "normal");
2656		if (state.usage_power)
2657			seq_puts(s, ", usage_power");
2658		seq_puts(s, "\n");
2659
2660		seq_printf(s, "  actual configuration:    %3sabled, %llu/%llu ns, %s polarity",
2661			   hwstate.enabled ? "en" : "dis", hwstate.duty_cycle, hwstate.period,
2662			   hwstate.polarity ? "inverse" : "normal");
2663
2664		seq_puts(s, "\n");
2665	}
2666}
2667
2668static void *pwm_seq_start(struct seq_file *s, loff_t *pos)
2669{
2670	unsigned long id = *pos;
2671	void *ret;
2672
2673	mutex_lock(&pwm_lock);
2674	s->private = "";
2675
2676	ret = idr_get_next_ul(&pwm_chips, &id);
2677	*pos = id;
2678	return ret;
2679}
2680
2681static void *pwm_seq_next(struct seq_file *s, void *v, loff_t *pos)
2682{
2683	unsigned long id = *pos + 1;
2684	void *ret;
2685
2686	s->private = "\n";
2687
2688	ret = idr_get_next_ul(&pwm_chips, &id);
2689	*pos = id;
2690	return ret;
2691}
2692
2693static void pwm_seq_stop(struct seq_file *s, void *v)
2694{
2695	mutex_unlock(&pwm_lock);
2696}
2697
2698static int pwm_seq_show(struct seq_file *s, void *v)
2699{
2700	struct pwm_chip *chip = v;
2701
2702	seq_printf(s, "%s%u: %s/%s, npwm: %u\n",
2703		   (char *)s->private, chip->id,
2704		   pwmchip_parent(chip)->bus ? pwmchip_parent(chip)->bus->name : "no-bus",
2705		   dev_name(pwmchip_parent(chip)), chip->npwm);
2706
2707	pwm_dbg_show(chip, s);
2708
2709	return 0;
2710}
2711
2712static const struct seq_operations pwm_debugfs_sops = {
2713	.start = pwm_seq_start,
2714	.next = pwm_seq_next,
2715	.stop = pwm_seq_stop,
2716	.show = pwm_seq_show,
2717};
2718
2719DEFINE_SEQ_ATTRIBUTE(pwm_debugfs);
2720
2721static int __init pwm_init(void)
2722{
2723	int ret;
2724
2725	ret = alloc_chrdev_region(&pwm_devt, 0, PWM_MINOR_COUNT, "pwm");
2726	if (ret) {
2727		pr_err("Failed to initialize chrdev region for PWM usage\n");
2728		return ret;
2729	}
2730
2731	ret = class_register(&pwm_class);
2732	if (ret) {
2733		pr_err("Failed to initialize PWM class (%pe)\n", ERR_PTR(ret));
2734		unregister_chrdev_region(pwm_devt, 256);
2735		return ret;
2736	}
2737
2738	if (IS_ENABLED(CONFIG_DEBUG_FS))
2739		debugfs_create_file("pwm", 0444, NULL, NULL, &pwm_debugfs_fops);
2740
2741	return 0;
2742}
2743subsys_initcall(pwm_init);
~/ Read-only file preview.