>From 5c448b8dfd831c7bc501d9543d48b2077ee1ba7b Mon Sep 17 00:00:00 2001
From: Peter Rosin <peda@axentia.se>
Date: Tue, 24 Jan 2017 16:58:58 +0100
Subject: [PATCH] mux: fix cleanup for simplified bindings

---
 drivers/mux/mux-core.c | 19 ++++++++++++++++++-
 include/linux/mux.h    |  2 ++
 2 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/drivers/mux/mux-core.c b/drivers/mux/mux-core.c
index 0caafd6f5a77..53954bd12709 100644
--- a/drivers/mux/mux-core.c
+++ b/drivers/mux/mux-core.c
@@ -321,9 +321,12 @@ struct mux_control *mux_control_get(struct device *dev, const char *mux_name)
 	if (ret == -ENOENT && !mux_name) {
 		mux_chip = mux_gpio_alloc(dev);
 		if (!IS_ERR(mux_chip)) {
+			mux_chip->private = true;
 			ret = devm_mux_chip_register(dev, mux_chip);
-			if (ret < 0)
+			if (ret < 0) {
+				devm_mux_chip_free(dev, mux_chip);
 				return ERR_PTR(ret);
+			}
 			get_device(&mux_chip->dev);
 			return mux_chip->mux;
 		}
@@ -344,6 +347,12 @@ struct mux_control *mux_control_get(struct device *dev, const char *mux_name)
 	if (!mux_chip)
 		return ERR_PTR(-EPROBE_DEFER);
 
+	if (mux_chip->private) {
+		dev_err(dev, "%s: private mux chip specified in %s\n",
+			np->full_name, args.np->full_name);
+		return ERR_PTR(-EBUSY);
+	}
+
 	if (args.args_count > 1 ||
 	    (!args.args_count && (mux_chip->controllers > 1))) {
 		dev_err(dev, "%s: wrong #mux-control-cells for %s\n",
@@ -368,7 +377,15 @@ EXPORT_SYMBOL_GPL(mux_control_get);
 
 void mux_control_put(struct mux_control *mux)
 {
+	bool private = mux->chip->private;
+	struct device *parent = mux->chip->dev.parent;
+
 	put_device(&mux->chip->dev);
+
+	if (private) {
+		devm_mux_chip_unregister(parent, mux->chip);
+		devm_mux_chip_free(parent, mux->chip);
+	}
 }
 EXPORT_SYMBOL_GPL(mux_control_put);
 
diff --git a/include/linux/mux.h b/include/linux/mux.h
index ec9e605d8acf..3ad2e475c9dd 100644
--- a/include/linux/mux.h
+++ b/include/linux/mux.h
@@ -49,6 +49,7 @@ struct mux_control {
  * @mux:		Array of mux controllers that is handled.
  * @dev:		Device structure.
  * @id:			Used to identify the device internally.
+ * @private:		The mux chip is implicitly allocated by a single user.
  * @ops:		Mux controller operations.
  */
 struct mux_chip {
@@ -56,6 +57,7 @@ struct mux_chip {
 	struct mux_control *mux;
 	struct device dev;
 	int id;
+	bool private;
 
 	const struct mux_control_ops *ops;
 };
-- 
2.1.4