1// SPDX-License-Identifier: GPL-2.0
2//
3// Register cache access API
4//
5// Copyright 2011 Wolfson Microelectronics plc
6//
7// Author: Dimitris Papastamos <dp@opensource.wolfsonmicro.com>
8
9#include <linux/bsearch.h>
10#include <linux/device.h>
11#include <linux/export.h>
12#include <linux/slab.h>
13#include <linux/sort.h>
14
15#include "trace.h"
16#include "internal.h"
17
18static const struct regcache_ops *cache_types[] = {
19	&regcache_rbtree_ops,
20	&regcache_maple_ops,
21	&regcache_flat_ops,
22};
23
24static int regcache_hw_init(struct regmap *map)
25{
26	int i, j;
27	int ret;
28	int count;
29	unsigned int reg, val;
30	void *tmp_buf;
31
32	if (!map->num_reg_defaults_raw)
33		return -EINVAL;
34
35	/* calculate the size of reg_defaults */
36	for (count = 0, i = 0; i < map->num_reg_defaults_raw; i++)
37		if (regmap_readable(map, i * map->reg_stride) &&
38		    !regmap_volatile(map, i * map->reg_stride))
39			count++;
40
41	/* all registers are unreadable or volatile, so just bypass */
42	if (!count) {
43		map->cache_bypass = true;
44		return 0;
45	}
46
47	map->num_reg_defaults = count;
48	map->reg_defaults = kmalloc_array(count, sizeof(struct reg_default),
49					  GFP_KERNEL);
50	if (!map->reg_defaults)
51		return -ENOMEM;
52
53	if (!map->reg_defaults_raw) {
54		bool cache_bypass = map->cache_bypass;
55		dev_warn(map->dev, "No cache defaults, reading back from HW\n");
56
57		/* Bypass the cache access till data read from HW */
58		map->cache_bypass = true;
59		tmp_buf = kmalloc(map->cache_size_raw, GFP_KERNEL);
60		if (!tmp_buf) {
61			ret = -ENOMEM;
62			goto err_free;
63		}
64		ret = regmap_raw_read(map, 0, tmp_buf,
65				      map->cache_size_raw);
66		map->cache_bypass = cache_bypass;
67		if (ret == 0) {
68			map->reg_defaults_raw = tmp_buf;
69			map->cache_free = true;
70		} else {
71			kfree(tmp_buf);
72		}
73	}
74
75	/* fill the reg_defaults */
76	for (i = 0, j = 0; i < map->num_reg_defaults_raw; i++) {
77		reg = i * map->reg_stride;
78
79		if (!regmap_readable(map, reg))
80			continue;
81
82		if (regmap_volatile(map, reg))
83			continue;
84
85		if (map->reg_defaults_raw) {
86			val = regcache_get_val(map, map->reg_defaults_raw, i);
87		} else {
88			bool cache_bypass = map->cache_bypass;
89
90			map->cache_bypass = true;
91			ret = regmap_read(map, reg, &val);
92			map->cache_bypass = cache_bypass;
93			if (ret != 0) {
94				dev_err(map->dev, "Failed to read %d: %d\n",
95					reg, ret);
96				goto err_free;
97			}
98		}
99
100		map->reg_defaults[j].reg = reg;
101		map->reg_defaults[j].def = val;
102		j++;
103	}
104
105	return 0;
106
107err_free:
108	kfree(map->reg_defaults);
109
110	return ret;
111}
112
113int regcache_init(struct regmap *map, const struct regmap_config *config)
114{
115	int ret;
116	int i;
117	void *tmp_buf;
118
119	if (map->cache_type == REGCACHE_NONE) {
120		if (config->reg_defaults || config->num_reg_defaults_raw)
121			dev_warn(map->dev,
122				 "No cache used with register defaults set!\n");
123
124		map->cache_bypass = true;
125		return 0;
126	}
127
128	if (config->reg_defaults && !config->num_reg_defaults) {
129		dev_err(map->dev,
130			 "Register defaults are set without the number!\n");
131		return -EINVAL;
132	}
133
134	if (config->num_reg_defaults && !config->reg_defaults) {
135		dev_err(map->dev,
136			"Register defaults number are set without the reg!\n");
137		return -EINVAL;
138	}
139
140	for (i = 0; i < config->num_reg_defaults; i++)
141		if (config->reg_defaults[i].reg % map->reg_stride)
142			return -EINVAL;
143
144	for (i = 0; i < ARRAY_SIZE(cache_types); i++)
145		if (cache_types[i]->type == map->cache_type)
146			break;
147
148	if (i == ARRAY_SIZE(cache_types)) {
149		dev_err(map->dev, "Could not match cache type: %d\n",
150			map->cache_type);
151		return -EINVAL;
152	}
153
154	map->num_reg_defaults = config->num_reg_defaults;
155	map->num_reg_defaults_raw = config->num_reg_defaults_raw;
156	map->reg_defaults_raw = config->reg_defaults_raw;
157	map->cache_word_size = DIV_ROUND_UP(config->val_bits, 8);
158	map->cache_size_raw = map->cache_word_size * config->num_reg_defaults_raw;
159
160	map->cache = NULL;
161	map->cache_ops = cache_types[i];
162
163	if (!map->cache_ops->read ||
164	    !map->cache_ops->write ||
165	    !map->cache_ops->name)
166		return -EINVAL;
167
168	/* We still need to ensure that the reg_defaults
169	 * won't vanish from under us.  We'll need to make
170	 * a copy of it.
171	 */
172	if (config->reg_defaults) {
173		tmp_buf = kmemdup(config->reg_defaults, map->num_reg_defaults *
174				  sizeof(struct reg_default), GFP_KERNEL);
175		if (!tmp_buf)
176			return -ENOMEM;
177		map->reg_defaults = tmp_buf;
178	} else if (map->num_reg_defaults_raw) {
179		/* Some devices such as PMICs don't have cache defaults,
180		 * we cope with this by reading back the HW registers and
181		 * crafting the cache defaults by hand.
182		 */
183		ret = regcache_hw_init(map);
184		if (ret < 0)
185			return ret;
186		if (map->cache_bypass)
187			return 0;
188	}
189
190	if (!map->max_register_is_set && map->num_reg_defaults_raw) {
191		map->max_register = (map->num_reg_defaults_raw  - 1) * map->reg_stride;
192		map->max_register_is_set = true;
193	}
194
195	if (map->cache_ops->init) {
196		dev_dbg(map->dev, "Initializing %s cache\n",
197			map->cache_ops->name);
198		ret = map->cache_ops->init(map);
199		if (ret)
200			goto err_free;
201	}
202	return 0;
203
204err_free:
205	kfree(map->reg_defaults);
206	if (map->cache_free)
207		kfree(map->reg_defaults_raw);
208
209	return ret;
210}
211
212void regcache_exit(struct regmap *map)
213{
214	if (map->cache_type == REGCACHE_NONE)
215		return;
216
217	BUG_ON(!map->cache_ops);
218
219	kfree(map->reg_defaults);
220	if (map->cache_free)
221		kfree(map->reg_defaults_raw);
222
223	if (map->cache_ops->exit) {
224		dev_dbg(map->dev, "Destroying %s cache\n",
225			map->cache_ops->name);
226		map->cache_ops->exit(map);
227	}
228}
229
230/**
231 * regcache_read - Fetch the value of a given register from the cache.
232 *
233 * @map: map to configure.
234 * @reg: The register index.
235 * @value: The value to be returned.
236 *
237 * Return a negative value on failure, 0 on success.
238 */
239int regcache_read(struct regmap *map,
240		  unsigned int reg, unsigned int *value)
241{
242	int ret;
243
244	if (map->cache_type == REGCACHE_NONE)
245		return -EINVAL;
246
247	BUG_ON(!map->cache_ops);
248
249	if (!regmap_volatile(map, reg)) {
250		ret = map->cache_ops->read(map, reg, value);
251
252		if (ret == 0)
253			trace_regmap_reg_read_cache(map, reg, *value);
254
255		return ret;
256	}
257
258	return -EINVAL;
259}
260
261/**
262 * regcache_write - Set the value of a given register in the cache.
263 *
264 * @map: map to configure.
265 * @reg: The register index.
266 * @value: The new register value.
267 *
268 * Return a negative value on failure, 0 on success.
269 */
270int regcache_write(struct regmap *map,
271		   unsigned int reg, unsigned int value)
272{
273	if (map->cache_type == REGCACHE_NONE)
274		return 0;
275
276	BUG_ON(!map->cache_ops);
277
278	if (!regmap_volatile(map, reg))
279		return map->cache_ops->write(map, reg, value);
280
281	return 0;
282}
283
284bool regcache_reg_needs_sync(struct regmap *map, unsigned int reg,
285			     unsigned int val)
286{
287	int ret;
288
289	if (!regmap_writeable(map, reg))
290		return false;
291
292	/* If we don't know the chip just got reset, then sync everything. */
293	if (!map->no_sync_defaults)
294		return true;
295
296	/* Is this the hardware default?  If so skip. */
297	ret = regcache_lookup_reg(map, reg);
298	if (ret >= 0 && val == map->reg_defaults[ret].def)
299		return false;
300	return true;
301}
302
303static int regcache_default_sync(struct regmap *map, unsigned int min,
304				 unsigned int max)
305{
306	unsigned int reg;
307
308	for (reg = min; reg <= max; reg += map->reg_stride) {
309		unsigned int val;
310		int ret;
311
312		if (regmap_volatile(map, reg) ||
313		    !regmap_writeable(map, reg))
314			continue;
315
316		ret = regcache_read(map, reg, &val);
317		if (ret == -ENOENT)
318			continue;
319		if (ret)
320			return ret;
321
322		if (!regcache_reg_needs_sync(map, reg, val))
323			continue;
324
325		map->cache_bypass = true;
326		ret = _regmap_write(map, reg, val);
327		map->cache_bypass = false;
328		if (ret) {
329			dev_err(map->dev, "Unable to sync register %#x. %d\n",
330				reg, ret);
331			return ret;
332		}
333		dev_dbg(map->dev, "Synced register %#x, value %#x\n", reg, val);
334	}
335
336	return 0;
337}
338
339static int rbtree_all(const void *key, const struct rb_node *node)
340{
341	return 0;
342}
343
344/**
345 * regcache_sync - Sync the register cache with the hardware.
346 *
347 * @map: map to configure.
348 *
349 * Any registers that should not be synced should be marked as
350 * volatile.  In general drivers can choose not to use the provided
351 * syncing functionality if they so require.
352 *
353 * Return a negative value on failure, 0 on success.
354 */
355int regcache_sync(struct regmap *map)
356{
357	int ret = 0;
358	unsigned int i;
359	const char *name;
360	bool bypass;
361	struct rb_node *node;
362
363	if (WARN_ON(map->cache_type == REGCACHE_NONE))
364		return -EINVAL;
365
366	BUG_ON(!map->cache_ops);
367
368	map->lock(map->lock_arg);
369	/* Remember the initial bypass state */
370	bypass = map->cache_bypass;
371	dev_dbg(map->dev, "Syncing %s cache\n",
372		map->cache_ops->name);
373	name = map->cache_ops->name;
374	trace_regcache_sync(map, name, "start");
375
376	if (!map->cache_dirty)
377		goto out;
378
379	/* Apply any patch first */
380	map->cache_bypass = true;
381	for (i = 0; i < map->patch_regs; i++) {
382		ret = _regmap_write(map, map->patch[i].reg, map->patch[i].def);
383		if (ret != 0) {
384			dev_err(map->dev, "Failed to write %x = %x: %d\n",
385				map->patch[i].reg, map->patch[i].def, ret);
386			goto out;
387		}
388	}
389	map->cache_bypass = false;
390
391	if (map->cache_ops->sync)
392		ret = map->cache_ops->sync(map, 0, map->max_register);
393	else
394		ret = regcache_default_sync(map, 0, map->max_register);
395
396	if (ret == 0)
397		map->cache_dirty = false;
398
399out:
400	/* Restore the bypass state */
401	map->cache_bypass = bypass;
402	map->no_sync_defaults = false;
403
404	/*
405	 * If we did any paging with cache bypassed and a cached
406	 * paging register then the register and cache state might
407	 * have gone out of sync, force writes of all the paging
408	 * registers.
409	 */
410	rb_for_each(node, 0, &map->range_tree, rbtree_all) {
411		struct regmap_range_node *this =
412			rb_entry(node, struct regmap_range_node, node);
413
414		/* If there's nothing in the cache there's nothing to sync */
415		if (regcache_read(map, this->selector_reg, &i) != 0)
416			continue;
417
418		ret = _regmap_write(map, this->selector_reg, i);
419		if (ret != 0) {
420			dev_err(map->dev, "Failed to write %x = %x: %d\n",
421				this->selector_reg, i, ret);
422			break;
423		}
424	}
425
426	map->unlock(map->lock_arg);
427
428	regmap_async_complete(map);
429
430	trace_regcache_sync(map, name, "stop");
431
432	return ret;
433}
434EXPORT_SYMBOL_GPL(regcache_sync);
435
436/**
437 * regcache_sync_region - Sync part  of the register cache with the hardware.
438 *
439 * @map: map to sync.
440 * @min: first register to sync
441 * @max: last register to sync
442 *
443 * Write all non-default register values in the specified region to
444 * the hardware.
445 *
446 * Return a negative value on failure, 0 on success.
447 */
448int regcache_sync_region(struct regmap *map, unsigned int min,
449			 unsigned int max)
450{
451	int ret = 0;
452	const char *name;
453	bool bypass;
454
455	if (WARN_ON(map->cache_type == REGCACHE_NONE))
456		return -EINVAL;
457
458	BUG_ON(!map->cache_ops);
459
460	map->lock(map->lock_arg);
461
462	/* Remember the initial bypass state */
463	bypass = map->cache_bypass;
464
465	name = map->cache_ops->name;
466	dev_dbg(map->dev, "Syncing %s cache from %d-%d\n", name, min, max);
467
468	trace_regcache_sync(map, name, "start region");
469
470	if (!map->cache_dirty)
471		goto out;
472
473	map->async = true;
474
475	if (map->cache_ops->sync)
476		ret = map->cache_ops->sync(map, min, max);
477	else
478		ret = regcache_default_sync(map, min, max);
479
480out:
481	/* Restore the bypass state */
482	map->cache_bypass = bypass;
483	map->async = false;
484	map->no_sync_defaults = false;
485	map->unlock(map->lock_arg);
486
487	regmap_async_complete(map);
488
489	trace_regcache_sync(map, name, "stop region");
490
491	return ret;
492}
493EXPORT_SYMBOL_GPL(regcache_sync_region);
494
495/**
496 * regcache_drop_region - Discard part of the register cache
497 *
498 * @map: map to operate on
499 * @min: first register to discard
500 * @max: last register to discard
501 *
502 * Discard part of the register cache.
503 *
504 * Return a negative value on failure, 0 on success.
505 */
506int regcache_drop_region(struct regmap *map, unsigned int min,
507			 unsigned int max)
508{
509	int ret = 0;
510
511	if (!map->cache_ops || !map->cache_ops->drop)
512		return -EINVAL;
513
514	map->lock(map->lock_arg);
515
516	trace_regcache_drop_region(map, min, max);
517
518	ret = map->cache_ops->drop(map, min, max);
519
520	map->unlock(map->lock_arg);
521
522	return ret;
523}
524EXPORT_SYMBOL_GPL(regcache_drop_region);
525
526/**
527 * regcache_cache_only - Put a register map into cache only mode
528 *
529 * @map: map to configure
530 * @enable: flag if changes should be written to the hardware
531 *
532 * When a register map is marked as cache only writes to the register
533 * map API will only update the register cache, they will not cause
534 * any hardware changes.  This is useful for allowing portions of
535 * drivers to act as though the device were functioning as normal when
536 * it is disabled for power saving reasons.
537 */
538void regcache_cache_only(struct regmap *map, bool enable)
539{
540	map->lock(map->lock_arg);
541	WARN_ON(map->cache_type != REGCACHE_NONE &&
542		map->cache_bypass && enable);
543	map->cache_only = enable;
544	trace_regmap_cache_only(map, enable);
545	map->unlock(map->lock_arg);
546}
547EXPORT_SYMBOL_GPL(regcache_cache_only);
548
549/**
550 * regcache_mark_dirty - Indicate that HW registers were reset to default values
551 *
552 * @map: map to mark
553 *
554 * Inform regcache that the device has been powered down or reset, so that
555 * on resume, regcache_sync() knows to write out all non-default values
556 * stored in the cache.
557 *
558 * If this function is not called, regcache_sync() will assume that
559 * the hardware state still matches the cache state, modulo any writes that
560 * happened when cache_only was true.
561 */
562void regcache_mark_dirty(struct regmap *map)
563{
564	map->lock(map->lock_arg);
565	map->cache_dirty = true;
566	map->no_sync_defaults = true;
567	map->unlock(map->lock_arg);
568}
569EXPORT_SYMBOL_GPL(regcache_mark_dirty);
570
571/**
572 * regcache_cache_bypass - Put a register map into cache bypass mode
573 *
574 * @map: map to configure
575 * @enable: flag if changes should not be written to the cache
576 *
577 * When a register map is marked with the cache bypass option, writes
578 * to the register map API will only update the hardware and not
579 * the cache directly.  This is useful when syncing the cache back to
580 * the hardware.
581 */
582void regcache_cache_bypass(struct regmap *map, bool enable)
583{
584	map->lock(map->lock_arg);
585	WARN_ON(map->cache_only && enable);
586	map->cache_bypass = enable;
587	trace_regmap_cache_bypass(map, enable);
588	map->unlock(map->lock_arg);
589}
590EXPORT_SYMBOL_GPL(regcache_cache_bypass);
591
592/**
593 * regcache_reg_cached - Check if a register is cached
594 *
595 * @map: map to check
596 * @reg: register to check
597 *
598 * Reports if a register is cached.
599 */
600bool regcache_reg_cached(struct regmap *map, unsigned int reg)
601{
602	unsigned int val;
603	int ret;
604
605	map->lock(map->lock_arg);
606
607	ret = regcache_read(map, reg, &val);
608
609	map->unlock(map->lock_arg);
610
611	return ret == 0;
612}
613EXPORT_SYMBOL_GPL(regcache_reg_cached);
614
615void regcache_set_val(struct regmap *map, void *base, unsigned int idx,
616		      unsigned int val)
617{
618	/* Use device native format if possible */
619	if (map->format.format_val) {
620		map->format.format_val(base + (map->cache_word_size * idx),
621				       val, 0);
622		return;
623	}
624
625	switch (map->cache_word_size) {
626	case 1: {
627		u8 *cache = base;
628
629		cache[idx] = val;
630		break;
631	}
632	case 2: {
633		u16 *cache = base;
634
635		cache[idx] = val;
636		break;
637	}
638	case 4: {
639		u32 *cache = base;
640
641		cache[idx] = val;
642		break;
643	}
644	default:
645		BUG();
646	}
647}
648
649unsigned int regcache_get_val(struct regmap *map, const void *base,
650			      unsigned int idx)
651{
652	if (!base)
653		return -EINVAL;
654
655	/* Use device native format if possible */
656	if (map->format.parse_val)
657		return map->format.parse_val(regcache_get_val_addr(map, base,
658								   idx));
659
660	switch (map->cache_word_size) {
661	case 1: {
662		const u8 *cache = base;
663
664		return cache[idx];
665	}
666	case 2: {
667		const u16 *cache = base;
668
669		return cache[idx];
670	}
671	case 4: {
672		const u32 *cache = base;
673
674		return cache[idx];
675	}
676	default:
677		BUG();
678	}
679	/* unreachable */
680	return -1;
681}
682
683static int regcache_default_cmp(const void *a, const void *b)
684{
685	const struct reg_default *_a = a;
686	const struct reg_default *_b = b;
687
688	return _a->reg - _b->reg;
689}
690
691int regcache_lookup_reg(struct regmap *map, unsigned int reg)
692{
693	struct reg_default key;
694	struct reg_default *r;
695
696	key.reg = reg;
697	key.def = 0;
698
699	r = bsearch(&key, map->reg_defaults, map->num_reg_defaults,
700		    sizeof(struct reg_default), regcache_default_cmp);
701
702	if (r)
703		return r - map->reg_defaults;
704	else
705		return -ENOENT;
706}
707
708static bool regcache_reg_present(unsigned long *cache_present, unsigned int idx)
709{
710	if (!cache_present)
711		return true;
712
713	return test_bit(idx, cache_present);
714}
715
716int regcache_sync_val(struct regmap *map, unsigned int reg, unsigned int val)
717{
718	int ret;
719
720	if (!regcache_reg_needs_sync(map, reg, val))
721		return 0;
722
723	map->cache_bypass = true;
724
725	ret = _regmap_write(map, reg, val);
726
727	map->cache_bypass = false;
728
729	if (ret != 0) {
730		dev_err(map->dev, "Unable to sync register %#x. %d\n",
731			reg, ret);
732		return ret;
733	}
734	dev_dbg(map->dev, "Synced register %#x, value %#x\n",
735		reg, val);
736
737	return 0;
738}
739
740static int regcache_sync_block_single(struct regmap *map, void *block,
741				      unsigned long *cache_present,
742				      unsigned int block_base,
743				      unsigned int start, unsigned int end)
744{
745	unsigned int i, regtmp, val;
746	int ret;
747
748	for (i = start; i < end; i++) {
749		regtmp = block_base + (i * map->reg_stride);
750
751		if (!regcache_reg_present(cache_present, i) ||
752		    !regmap_writeable(map, regtmp))
753			continue;
754
755		val = regcache_get_val(map, block, i);
756		ret = regcache_sync_val(map, regtmp, val);
757		if (ret != 0)
758			return ret;
759	}
760
761	return 0;
762}
763
764static int regcache_sync_block_raw_flush(struct regmap *map, const void **data,
765					 unsigned int base, unsigned int cur)
766{
767	size_t val_bytes = map->format.val_bytes;
768	int ret, count;
769
770	if (*data == NULL)
771		return 0;
772
773	count = (cur - base) / map->reg_stride;
774
775	dev_dbg(map->dev, "Writing %zu bytes for %d registers from 0x%x-0x%x\n",
776		count * val_bytes, count, base, cur - map->reg_stride);
777
778	map->cache_bypass = true;
779
780	ret = _regmap_raw_write(map, base, *data, count * val_bytes, false);
781	if (ret)
782		dev_err(map->dev, "Unable to sync registers %#x-%#x. %d\n",
783			base, cur - map->reg_stride, ret);
784
785	map->cache_bypass = false;
786
787	*data = NULL;
788
789	return ret;
790}
791
792static int regcache_sync_block_raw(struct regmap *map, void *block,
793			    unsigned long *cache_present,
794			    unsigned int block_base, unsigned int start,
795			    unsigned int end)
796{
797	unsigned int i, val;
798	unsigned int regtmp = 0;
799	unsigned int base = 0;
800	const void *data = NULL;
801	int ret;
802
803	for (i = start; i < end; i++) {
804		regtmp = block_base + (i * map->reg_stride);
805
806		if (!regcache_reg_present(cache_present, i) ||
807		    !regmap_writeable(map, regtmp)) {
808			ret = regcache_sync_block_raw_flush(map, &data,
809							    base, regtmp);
810			if (ret != 0)
811				return ret;
812			continue;
813		}
814
815		val = regcache_get_val(map, block, i);
816		if (!regcache_reg_needs_sync(map, regtmp, val)) {
817			ret = regcache_sync_block_raw_flush(map, &data,
818							    base, regtmp);
819			if (ret != 0)
820				return ret;
821			continue;
822		}
823
824		if (!data) {
825			data = regcache_get_val_addr(map, block, i);
826			base = regtmp;
827		}
828	}
829
830	return regcache_sync_block_raw_flush(map, &data, base, regtmp +
831			map->reg_stride);
832}
833
834int regcache_sync_block(struct regmap *map, void *block,
835			unsigned long *cache_present,
836			unsigned int block_base, unsigned int start,
837			unsigned int end)
838{
839	if (regmap_can_raw_write(map) && !map->use_single_write)
840		return regcache_sync_block_raw(map, block, cache_present,
841					       block_base, start, end);
842	else
843		return regcache_sync_block_single(map, block, cache_present,
844						  block_base, start, end);
845}
846