xref: /linux/drivers/md/dm-cache-policy-smq.c (revision b1cbabe84ca1381a004fb91ee1791a1a53bce44e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2015 Red Hat. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7 
8 #include "dm-cache-background-tracker.h"
9 #include "dm-cache-policy-internal.h"
10 #include "dm-cache-policy.h"
11 #include "dm.h"
12 
13 #include <linux/hash.h>
14 #include <linux/jiffies.h>
15 #include <linux/module.h>
16 #include <linux/mutex.h>
17 #include <linux/vmalloc.h>
18 #include <linux/math64.h>
19 
20 #define DM_MSG_PREFIX "cache-policy-smq"
21 
22 /*----------------------------------------------------------------*/
23 
24 /*
25  * Maximum number of concurrent background work items (promotions,
26  * demotions, writebacks) that can be queued in the background tracker.
27  * Tuneable via the module parameter smq_max_background_work.
28  * Only affects newly created cache devices.
29  */
30 static unsigned int smq_max_background_work = 4096;
31 module_param(smq_max_background_work, uint, 0644);
32 MODULE_PARM_DESC(smq_max_background_work, "Max concurrent background work items");
33 
34 /*
35  * Safe division functions that return zero on divide by zero.
36  */
37 static unsigned int safe_div(unsigned int n, unsigned int d)
38 {
39 	return d ? n / d : 0u;
40 }
41 
42 static unsigned int safe_mod(unsigned int n, unsigned int d)
43 {
44 	return d ? n % d : 0u;
45 }
46 
47 /*----------------------------------------------------------------*/
48 
49 struct entry {
50 	unsigned int hash_next:28;
51 	unsigned int prev:28;
52 	unsigned int next:28;
53 	unsigned int level:6;
54 	bool dirty:1;
55 	bool allocated:1;
56 	bool sentinel:1;
57 	bool pending_work:1;
58 
59 	dm_oblock_t oblock;
60 };
61 
62 /*----------------------------------------------------------------*/
63 
64 #define INDEXER_NULL ((1u << 28u) - 1u)
65 
66 /*
67  * An entry_space manages a set of entries that we use for the queues.
68  * The clean and dirty queues share entries, so this object is separate
69  * from the queue itself.
70  */
71 struct entry_space {
72 	struct entry *begin;
73 	struct entry *end;
74 };
75 
76 static int space_init(struct entry_space *es, unsigned int nr_entries)
77 {
78 	if (!nr_entries) {
79 		es->begin = es->end = NULL;
80 		return 0;
81 	}
82 
83 	es->begin = vzalloc(array_size(nr_entries, sizeof(struct entry)));
84 	if (!es->begin)
85 		return -ENOMEM;
86 
87 	es->end = es->begin + nr_entries;
88 	return 0;
89 }
90 
91 static void space_exit(struct entry_space *es)
92 {
93 	vfree(es->begin);
94 }
95 
96 static struct entry *__get_entry(struct entry_space *es, unsigned int block)
97 {
98 	struct entry *e;
99 
100 	e = es->begin + block;
101 	BUG_ON(e >= es->end);
102 
103 	return e;
104 }
105 
106 static unsigned int to_index(struct entry_space *es, struct entry *e)
107 {
108 	BUG_ON(e < es->begin || e >= es->end);
109 	return e - es->begin;
110 }
111 
112 static struct entry *to_entry(struct entry_space *es, unsigned int block)
113 {
114 	if (block == INDEXER_NULL)
115 		return NULL;
116 
117 	return __get_entry(es, block);
118 }
119 
120 /*----------------------------------------------------------------*/
121 
122 struct ilist {
123 	unsigned int nr_elts;	/* excluding sentinel entries */
124 	unsigned int head, tail;
125 };
126 
127 static void l_init(struct ilist *l)
128 {
129 	l->nr_elts = 0;
130 	l->head = l->tail = INDEXER_NULL;
131 }
132 
133 static struct entry *l_head(struct entry_space *es, struct ilist *l)
134 {
135 	return to_entry(es, l->head);
136 }
137 
138 static struct entry *l_tail(struct entry_space *es, struct ilist *l)
139 {
140 	return to_entry(es, l->tail);
141 }
142 
143 static struct entry *l_next(struct entry_space *es, struct entry *e)
144 {
145 	return to_entry(es, e->next);
146 }
147 
148 static struct entry *l_prev(struct entry_space *es, struct entry *e)
149 {
150 	return to_entry(es, e->prev);
151 }
152 
153 static bool l_empty(struct ilist *l)
154 {
155 	return l->head == INDEXER_NULL;
156 }
157 
158 static void l_add_head(struct entry_space *es, struct ilist *l, struct entry *e)
159 {
160 	struct entry *head = l_head(es, l);
161 
162 	e->next = l->head;
163 	e->prev = INDEXER_NULL;
164 
165 	if (head)
166 		head->prev = l->head = to_index(es, e);
167 	else
168 		l->head = l->tail = to_index(es, e);
169 
170 	if (!e->sentinel)
171 		l->nr_elts++;
172 }
173 
174 static void l_add_tail(struct entry_space *es, struct ilist *l, struct entry *e)
175 {
176 	struct entry *tail = l_tail(es, l);
177 
178 	e->next = INDEXER_NULL;
179 	e->prev = l->tail;
180 
181 	if (tail)
182 		tail->next = l->tail = to_index(es, e);
183 	else
184 		l->head = l->tail = to_index(es, e);
185 
186 	if (!e->sentinel)
187 		l->nr_elts++;
188 }
189 
190 static void l_add_before(struct entry_space *es, struct ilist *l,
191 			 struct entry *old, struct entry *e)
192 {
193 	struct entry *prev = l_prev(es, old);
194 
195 	if (!prev)
196 		l_add_head(es, l, e);
197 
198 	else {
199 		e->prev = old->prev;
200 		e->next = to_index(es, old);
201 		prev->next = old->prev = to_index(es, e);
202 
203 		if (!e->sentinel)
204 			l->nr_elts++;
205 	}
206 }
207 
208 static void l_del(struct entry_space *es, struct ilist *l, struct entry *e)
209 {
210 	struct entry *prev = l_prev(es, e);
211 	struct entry *next = l_next(es, e);
212 
213 	if (prev)
214 		prev->next = e->next;
215 	else
216 		l->head = e->next;
217 
218 	if (next)
219 		next->prev = e->prev;
220 	else
221 		l->tail = e->prev;
222 
223 	if (!e->sentinel)
224 		l->nr_elts--;
225 }
226 
227 static struct entry *l_pop_head(struct entry_space *es, struct ilist *l)
228 {
229 	struct entry *e;
230 
231 	for (e = l_head(es, l); e; e = l_next(es, e))
232 		if (!e->sentinel) {
233 			l_del(es, l, e);
234 			return e;
235 		}
236 
237 	return NULL;
238 }
239 
240 static struct entry *l_pop_tail(struct entry_space *es, struct ilist *l)
241 {
242 	struct entry *e;
243 
244 	for (e = l_tail(es, l); e; e = l_prev(es, e))
245 		if (!e->sentinel) {
246 			l_del(es, l, e);
247 			return e;
248 		}
249 
250 	return NULL;
251 }
252 
253 /*----------------------------------------------------------------*/
254 
255 /*
256  * The stochastic-multi-queue is a set of lru lists stacked into levels.
257  * Entries are moved up levels when they are used, which loosely orders the
258  * most accessed entries in the top levels and least in the bottom.  This
259  * structure is *much* better than a single lru list.
260  */
261 #define MAX_LEVELS 64u
262 
263 struct queue {
264 	struct entry_space *es;
265 
266 	unsigned int nr_elts;
267 	unsigned int nr_levels;
268 	struct ilist qs[MAX_LEVELS];
269 
270 	/*
271 	 * We maintain a count of the number of entries we would like in each
272 	 * level.
273 	 */
274 	unsigned int last_target_nr_elts;
275 	unsigned int nr_top_levels;
276 	unsigned int nr_in_top_levels;
277 	unsigned int target_count[MAX_LEVELS];
278 };
279 
280 static void q_init(struct queue *q, struct entry_space *es, unsigned int nr_levels)
281 {
282 	unsigned int i;
283 
284 	q->es = es;
285 	q->nr_elts = 0;
286 	q->nr_levels = nr_levels;
287 
288 	for (i = 0; i < q->nr_levels; i++) {
289 		l_init(q->qs + i);
290 		q->target_count[i] = 0u;
291 	}
292 
293 	q->last_target_nr_elts = 0u;
294 	q->nr_top_levels = 0u;
295 	q->nr_in_top_levels = 0u;
296 }
297 
298 static unsigned int q_size(struct queue *q)
299 {
300 	return q->nr_elts;
301 }
302 
303 /*
304  * Insert an entry to the back of the given level.
305  */
306 static void q_push(struct queue *q, struct entry *e)
307 {
308 	BUG_ON(e->pending_work);
309 
310 	if (!e->sentinel)
311 		q->nr_elts++;
312 
313 	l_add_tail(q->es, q->qs + e->level, e);
314 }
315 
316 static void q_push_front(struct queue *q, struct entry *e)
317 {
318 	BUG_ON(e->pending_work);
319 
320 	if (!e->sentinel)
321 		q->nr_elts++;
322 
323 	l_add_head(q->es, q->qs + e->level, e);
324 }
325 
326 static void q_push_before(struct queue *q, struct entry *old, struct entry *e)
327 {
328 	BUG_ON(e->pending_work);
329 
330 	if (!e->sentinel)
331 		q->nr_elts++;
332 
333 	l_add_before(q->es, q->qs + e->level, old, e);
334 }
335 
336 static void q_del(struct queue *q, struct entry *e)
337 {
338 	l_del(q->es, q->qs + e->level, e);
339 	if (!e->sentinel)
340 		q->nr_elts--;
341 }
342 
343 /*
344  * Return the oldest entry of the lowest populated level.
345  */
346 static struct entry *q_peek(struct queue *q, unsigned int max_level, bool can_cross_sentinel)
347 {
348 	unsigned int level;
349 	struct entry *e;
350 
351 	max_level = min(max_level, q->nr_levels);
352 
353 	for (level = 0; level < max_level; level++)
354 		for (e = l_head(q->es, q->qs + level); e; e = l_next(q->es, e)) {
355 			if (e->sentinel) {
356 				if (can_cross_sentinel)
357 					continue;
358 				else
359 					break;
360 			}
361 
362 			return e;
363 		}
364 
365 	return NULL;
366 }
367 
368 static struct entry *q_pop(struct queue *q)
369 {
370 	struct entry *e = q_peek(q, q->nr_levels, true);
371 
372 	if (e)
373 		q_del(q, e);
374 
375 	return e;
376 }
377 
378 /*
379  * This function assumes there is a non-sentinel entry to pop.  It's only
380  * used by redistribute, so we know this is true.  It also doesn't adjust
381  * the q->nr_elts count.
382  */
383 static struct entry *__redist_pop_from(struct queue *q, unsigned int level)
384 {
385 	struct entry *e;
386 
387 	for (; level < q->nr_levels; level++)
388 		for (e = l_head(q->es, q->qs + level); e; e = l_next(q->es, e))
389 			if (!e->sentinel) {
390 				l_del(q->es, q->qs + e->level, e);
391 				return e;
392 			}
393 
394 	return NULL;
395 }
396 
397 static void q_set_targets_subrange_(struct queue *q, unsigned int nr_elts,
398 				    unsigned int lbegin, unsigned int lend)
399 {
400 	unsigned int level, nr_levels, entries_per_level, remainder;
401 
402 	BUG_ON(lbegin > lend);
403 	BUG_ON(lend > q->nr_levels);
404 	nr_levels = lend - lbegin;
405 	entries_per_level = safe_div(nr_elts, nr_levels);
406 	remainder = safe_mod(nr_elts, nr_levels);
407 
408 	for (level = lbegin; level < lend; level++)
409 		q->target_count[level] =
410 			(level < (lbegin + remainder)) ? entries_per_level + 1u : entries_per_level;
411 }
412 
413 /*
414  * Typically we have fewer elements in the top few levels which allows us
415  * to adjust the promote threshold nicely.
416  */
417 static void q_set_targets(struct queue *q)
418 {
419 	if (q->last_target_nr_elts == q->nr_elts)
420 		return;
421 
422 	q->last_target_nr_elts = q->nr_elts;
423 
424 	if (q->nr_top_levels > q->nr_levels)
425 		q_set_targets_subrange_(q, q->nr_elts, 0, q->nr_levels);
426 
427 	else {
428 		q_set_targets_subrange_(q, q->nr_in_top_levels,
429 					q->nr_levels - q->nr_top_levels, q->nr_levels);
430 
431 		if (q->nr_in_top_levels < q->nr_elts)
432 			q_set_targets_subrange_(q, q->nr_elts - q->nr_in_top_levels,
433 						0, q->nr_levels - q->nr_top_levels);
434 		else
435 			q_set_targets_subrange_(q, 0, 0, q->nr_levels - q->nr_top_levels);
436 	}
437 }
438 
439 static void q_redistribute(struct queue *q)
440 {
441 	unsigned int target, level;
442 	struct ilist *l, *l_above;
443 	struct entry *e;
444 
445 	q_set_targets(q);
446 
447 	for (level = 0u; level < q->nr_levels - 1u; level++) {
448 		l = q->qs + level;
449 		target = q->target_count[level];
450 
451 		/*
452 		 * Pull down some entries from the level above.
453 		 */
454 		while (l->nr_elts < target) {
455 			e = __redist_pop_from(q, level + 1u);
456 			if (!e) {
457 				/* bug in nr_elts */
458 				break;
459 			}
460 
461 			e->level = level;
462 			l_add_tail(q->es, l, e);
463 		}
464 
465 		/*
466 		 * Push some entries up.
467 		 */
468 		l_above = q->qs + level + 1u;
469 		while (l->nr_elts > target) {
470 			e = l_pop_tail(q->es, l);
471 
472 			if (!e)
473 				/* bug in nr_elts */
474 				break;
475 
476 			e->level = level + 1u;
477 			l_add_tail(q->es, l_above, e);
478 		}
479 	}
480 }
481 
482 static void q_requeue(struct queue *q, struct entry *e, unsigned int extra_levels,
483 		      struct entry *s1, struct entry *s2)
484 {
485 	struct entry *de;
486 	unsigned int sentinels_passed = 0;
487 	unsigned int new_level = min(q->nr_levels - 1u, e->level + extra_levels);
488 
489 	/* try and find an entry to swap with */
490 	if (extra_levels && (e->level < q->nr_levels - 1u)) {
491 		for (de = l_head(q->es, q->qs + new_level); de && de->sentinel; de = l_next(q->es, de))
492 			sentinels_passed++;
493 
494 		if (de) {
495 			q_del(q, de);
496 			de->level = e->level;
497 			if (s1) {
498 				switch (sentinels_passed) {
499 				case 0:
500 					q_push_before(q, s1, de);
501 					break;
502 
503 				case 1:
504 					q_push_before(q, s2, de);
505 					break;
506 
507 				default:
508 					q_push(q, de);
509 				}
510 			} else
511 				q_push(q, de);
512 		}
513 	}
514 
515 	q_del(q, e);
516 	e->level = new_level;
517 	q_push(q, e);
518 }
519 
520 /*----------------------------------------------------------------*/
521 
522 #define FP_SHIFT 8
523 #define SIXTEENTH (1u << (FP_SHIFT - 4u))
524 #define EIGHTH (1u << (FP_SHIFT - 3u))
525 
526 struct stats {
527 	unsigned int hit_threshold;
528 	unsigned int hits;
529 	unsigned int misses;
530 };
531 
532 enum performance {
533 	Q_POOR,
534 	Q_FAIR,
535 	Q_WELL
536 };
537 
538 static void stats_init(struct stats *s, unsigned int nr_levels)
539 {
540 	s->hit_threshold = (nr_levels * 3u) / 4u;
541 	s->hits = 0u;
542 	s->misses = 0u;
543 }
544 
545 static void stats_reset(struct stats *s)
546 {
547 	s->hits = s->misses = 0u;
548 }
549 
550 static void stats_level_accessed(struct stats *s, unsigned int level)
551 {
552 	if (level >= s->hit_threshold)
553 		s->hits++;
554 	else
555 		s->misses++;
556 }
557 
558 static void stats_miss(struct stats *s)
559 {
560 	s->misses++;
561 }
562 
563 /*
564  * There are times when we don't have any confidence in the hotspot queue.
565  * Such as when a fresh cache is created and the blocks have been spread
566  * out across the levels, or if an io load changes.  We detect this by
567  * seeing how often a lookup is in the top levels of the hotspot queue.
568  */
569 static enum performance stats_assess(struct stats *s)
570 {
571 	unsigned int confidence = safe_div(s->hits << FP_SHIFT, s->hits + s->misses);
572 
573 	if (confidence < SIXTEENTH)
574 		return Q_POOR;
575 
576 	else if (confidence < EIGHTH)
577 		return Q_FAIR;
578 
579 	else
580 		return Q_WELL;
581 }
582 
583 /*----------------------------------------------------------------*/
584 
585 struct smq_hash_table {
586 	struct entry_space *es;
587 	unsigned long long hash_bits;
588 	unsigned int *buckets;
589 };
590 
591 /*
592  * All cache entries are stored in a chained hash table.  To save space we
593  * use indexing again, and only store indexes to the next entry.
594  */
595 static int h_init(struct smq_hash_table *ht, struct entry_space *es, unsigned int nr_entries)
596 {
597 	unsigned int i, nr_buckets;
598 
599 	ht->es = es;
600 	nr_buckets = roundup_pow_of_two(max(nr_entries / 4u, 16u));
601 	ht->hash_bits = __ffs(nr_buckets);
602 
603 	ht->buckets = vmalloc_array(nr_buckets, sizeof(*ht->buckets));
604 	if (!ht->buckets)
605 		return -ENOMEM;
606 
607 	for (i = 0; i < nr_buckets; i++)
608 		ht->buckets[i] = INDEXER_NULL;
609 
610 	return 0;
611 }
612 
613 static void h_exit(struct smq_hash_table *ht)
614 {
615 	vfree(ht->buckets);
616 }
617 
618 static struct entry *h_head(struct smq_hash_table *ht, unsigned int bucket)
619 {
620 	return to_entry(ht->es, ht->buckets[bucket]);
621 }
622 
623 static struct entry *h_next(struct smq_hash_table *ht, struct entry *e)
624 {
625 	return to_entry(ht->es, e->hash_next);
626 }
627 
628 static void __h_insert(struct smq_hash_table *ht, unsigned int bucket, struct entry *e)
629 {
630 	e->hash_next = ht->buckets[bucket];
631 	ht->buckets[bucket] = to_index(ht->es, e);
632 }
633 
634 static void h_insert(struct smq_hash_table *ht, struct entry *e)
635 {
636 	unsigned int h = hash_64(from_oblock(e->oblock), ht->hash_bits);
637 
638 	__h_insert(ht, h, e);
639 }
640 
641 static struct entry *__h_lookup(struct smq_hash_table *ht, unsigned int h, dm_oblock_t oblock,
642 				struct entry **prev)
643 {
644 	struct entry *e;
645 
646 	*prev = NULL;
647 	for (e = h_head(ht, h); e; e = h_next(ht, e)) {
648 		if (e->oblock == oblock)
649 			return e;
650 
651 		*prev = e;
652 	}
653 
654 	return NULL;
655 }
656 
657 static void __h_unlink(struct smq_hash_table *ht, unsigned int h,
658 		       struct entry *e, struct entry *prev)
659 {
660 	if (prev)
661 		prev->hash_next = e->hash_next;
662 	else
663 		ht->buckets[h] = e->hash_next;
664 }
665 
666 /*
667  * Also moves each entry to the front of the bucket.
668  */
669 static struct entry *h_lookup(struct smq_hash_table *ht, dm_oblock_t oblock)
670 {
671 	struct entry *e, *prev;
672 	unsigned int h = hash_64(from_oblock(oblock), ht->hash_bits);
673 
674 	e = __h_lookup(ht, h, oblock, &prev);
675 	if (e && prev) {
676 		/*
677 		 * Move to the front because this entry is likely
678 		 * to be hit again.
679 		 */
680 		__h_unlink(ht, h, e, prev);
681 		__h_insert(ht, h, e);
682 	}
683 
684 	return e;
685 }
686 
687 static void h_remove(struct smq_hash_table *ht, struct entry *e)
688 {
689 	unsigned int h = hash_64(from_oblock(e->oblock), ht->hash_bits);
690 	struct entry *prev;
691 
692 	/*
693 	 * The down side of using a singly linked list is we have to
694 	 * iterate the bucket to remove an item.
695 	 */
696 	e = __h_lookup(ht, h, e->oblock, &prev);
697 	if (e)
698 		__h_unlink(ht, h, e, prev);
699 }
700 
701 /*----------------------------------------------------------------*/
702 
703 struct entry_alloc {
704 	struct entry_space *es;
705 	unsigned int begin;
706 
707 	unsigned int nr_allocated;
708 	struct ilist free;
709 };
710 
711 static void init_allocator(struct entry_alloc *ea, struct entry_space *es,
712 			   unsigned int begin, unsigned int end)
713 {
714 	unsigned int i;
715 
716 	ea->es = es;
717 	ea->nr_allocated = 0u;
718 	ea->begin = begin;
719 
720 	l_init(&ea->free);
721 	for (i = begin; i != end; i++)
722 		l_add_tail(ea->es, &ea->free, __get_entry(ea->es, i));
723 }
724 
725 static void init_entry(struct entry *e)
726 {
727 	/*
728 	 * We can't memset because that would clear the hotspot and
729 	 * sentinel bits which remain constant.
730 	 */
731 	e->hash_next = INDEXER_NULL;
732 	e->next = INDEXER_NULL;
733 	e->prev = INDEXER_NULL;
734 	e->level = 0u;
735 	e->dirty = true;	/* FIXME: audit */
736 	e->allocated = true;
737 	e->sentinel = false;
738 	e->pending_work = false;
739 }
740 
741 static struct entry *alloc_entry(struct entry_alloc *ea)
742 {
743 	struct entry *e;
744 
745 	if (l_empty(&ea->free))
746 		return NULL;
747 
748 	e = l_pop_head(ea->es, &ea->free);
749 	init_entry(e);
750 	ea->nr_allocated++;
751 
752 	return e;
753 }
754 
755 /*
756  * This assumes the cblock hasn't already been allocated.
757  */
758 static struct entry *alloc_particular_entry(struct entry_alloc *ea, unsigned int i)
759 {
760 	struct entry *e = __get_entry(ea->es, ea->begin + i);
761 
762 	BUG_ON(e->allocated);
763 
764 	l_del(ea->es, &ea->free, e);
765 	init_entry(e);
766 	ea->nr_allocated++;
767 
768 	return e;
769 }
770 
771 static void free_entry(struct entry_alloc *ea, struct entry *e)
772 {
773 	BUG_ON(!ea->nr_allocated);
774 	BUG_ON(!e->allocated);
775 
776 	ea->nr_allocated--;
777 	e->allocated = false;
778 	l_add_tail(ea->es, &ea->free, e);
779 }
780 
781 static bool allocator_empty(struct entry_alloc *ea)
782 {
783 	return l_empty(&ea->free);
784 }
785 
786 static unsigned int get_index(struct entry_alloc *ea, struct entry *e)
787 {
788 	return to_index(ea->es, e) - ea->begin;
789 }
790 
791 static struct entry *get_entry(struct entry_alloc *ea, unsigned int index)
792 {
793 	return __get_entry(ea->es, ea->begin + index);
794 }
795 
796 /*----------------------------------------------------------------*/
797 
798 #define NR_HOTSPOT_LEVELS 64u
799 #define NR_CACHE_LEVELS 64u
800 
801 #define WRITEBACK_PERIOD (10ul * HZ)
802 #define DEMOTE_PERIOD (60ul * HZ)
803 
804 #define HOTSPOT_UPDATE_PERIOD (HZ)
805 #define CACHE_UPDATE_PERIOD (60ul * HZ)
806 
807 struct smq_policy {
808 	struct dm_cache_policy policy;
809 
810 	/* protects everything */
811 	spinlock_t lock;
812 	dm_cblock_t cache_size;
813 	sector_t cache_block_size;
814 
815 	sector_t hotspot_block_size;
816 	unsigned int nr_hotspot_blocks;
817 	unsigned int cache_blocks_per_hotspot_block;
818 	unsigned int hotspot_level_jump;
819 
820 	struct entry_space es;
821 	struct entry_alloc writeback_sentinel_alloc;
822 	struct entry_alloc demote_sentinel_alloc;
823 	struct entry_alloc hotspot_alloc;
824 	struct entry_alloc cache_alloc;
825 
826 	unsigned long *hotspot_hit_bits;
827 	unsigned long *cache_hit_bits;
828 
829 	/*
830 	 * We maintain three queues of entries.  The cache proper,
831 	 * consisting of a clean and dirty queue, containing the currently
832 	 * active mappings.  The hotspot queue uses a larger block size to
833 	 * track blocks that are being hit frequently and potential
834 	 * candidates for promotion to the cache.
835 	 */
836 	struct queue hotspot;
837 	struct queue clean;
838 	struct queue dirty;
839 
840 	struct stats hotspot_stats;
841 	struct stats cache_stats;
842 
843 	/*
844 	 * Keeps track of time, incremented by the core.  We use this to
845 	 * avoid attributing multiple hits within the same tick.
846 	 */
847 	unsigned int tick;
848 
849 	/*
850 	 * The hash tables allows us to quickly find an entry by origin
851 	 * block.
852 	 */
853 	struct smq_hash_table table;
854 	struct smq_hash_table hotspot_table;
855 
856 	bool current_writeback_sentinels;
857 	unsigned long next_writeback_period;
858 
859 	bool current_demote_sentinels;
860 	unsigned long next_demote_period;
861 
862 	unsigned int write_promote_level;
863 	unsigned int read_promote_level;
864 
865 	unsigned long next_hotspot_period;
866 	unsigned long next_cache_period;
867 
868 	struct background_tracker *bg_work;
869 
870 	bool migrations_allowed:1;
871 
872 	/*
873 	 * If this is set the policy will try and clean the whole cache
874 	 * even if the device is not idle.
875 	 */
876 	bool cleaner:1;
877 };
878 
879 /*----------------------------------------------------------------*/
880 
881 static struct entry *get_sentinel(struct entry_alloc *ea, unsigned int level, bool which)
882 {
883 	return get_entry(ea, which ? level : NR_CACHE_LEVELS + level);
884 }
885 
886 static struct entry *writeback_sentinel(struct smq_policy *mq, unsigned int level)
887 {
888 	return get_sentinel(&mq->writeback_sentinel_alloc, level, mq->current_writeback_sentinels);
889 }
890 
891 static struct entry *demote_sentinel(struct smq_policy *mq, unsigned int level)
892 {
893 	return get_sentinel(&mq->demote_sentinel_alloc, level, mq->current_demote_sentinels);
894 }
895 
896 static void __update_writeback_sentinels(struct smq_policy *mq)
897 {
898 	unsigned int level;
899 	struct queue *q = &mq->dirty;
900 	struct entry *sentinel;
901 
902 	for (level = 0; level < q->nr_levels; level++) {
903 		sentinel = writeback_sentinel(mq, level);
904 		q_del(q, sentinel);
905 		q_push(q, sentinel);
906 	}
907 }
908 
909 static void __update_demote_sentinels(struct smq_policy *mq)
910 {
911 	unsigned int level;
912 	struct queue *q = &mq->clean;
913 	struct entry *sentinel;
914 
915 	for (level = 0; level < q->nr_levels; level++) {
916 		sentinel = demote_sentinel(mq, level);
917 		q_del(q, sentinel);
918 		q_push(q, sentinel);
919 	}
920 }
921 
922 static void update_sentinels(struct smq_policy *mq)
923 {
924 	if (time_after(jiffies, mq->next_writeback_period)) {
925 		mq->next_writeback_period = jiffies + WRITEBACK_PERIOD;
926 		mq->current_writeback_sentinels = !mq->current_writeback_sentinels;
927 		__update_writeback_sentinels(mq);
928 	}
929 
930 	if (time_after(jiffies, mq->next_demote_period)) {
931 		mq->next_demote_period = jiffies + DEMOTE_PERIOD;
932 		mq->current_demote_sentinels = !mq->current_demote_sentinels;
933 		__update_demote_sentinels(mq);
934 	}
935 }
936 
937 static void __sentinels_init(struct smq_policy *mq)
938 {
939 	unsigned int level;
940 	struct entry *sentinel;
941 
942 	for (level = 0; level < NR_CACHE_LEVELS; level++) {
943 		sentinel = writeback_sentinel(mq, level);
944 		sentinel->level = level;
945 		q_push(&mq->dirty, sentinel);
946 
947 		sentinel = demote_sentinel(mq, level);
948 		sentinel->level = level;
949 		q_push(&mq->clean, sentinel);
950 	}
951 }
952 
953 static void sentinels_init(struct smq_policy *mq)
954 {
955 	mq->next_writeback_period = jiffies + WRITEBACK_PERIOD;
956 	mq->next_demote_period = jiffies + DEMOTE_PERIOD;
957 
958 	mq->current_writeback_sentinels = false;
959 	mq->current_demote_sentinels = false;
960 	__sentinels_init(mq);
961 
962 	mq->current_writeback_sentinels = !mq->current_writeback_sentinels;
963 	mq->current_demote_sentinels = !mq->current_demote_sentinels;
964 	__sentinels_init(mq);
965 }
966 
967 /*----------------------------------------------------------------*/
968 
969 static void del_queue(struct smq_policy *mq, struct entry *e)
970 {
971 	q_del(e->dirty ? &mq->dirty : &mq->clean, e);
972 }
973 
974 static void push_queue(struct smq_policy *mq, struct entry *e)
975 {
976 	if (e->dirty)
977 		q_push(&mq->dirty, e);
978 	else
979 		q_push(&mq->clean, e);
980 }
981 
982 // !h, !q, a -> h, q, a
983 static void push(struct smq_policy *mq, struct entry *e)
984 {
985 	h_insert(&mq->table, e);
986 	if (!e->pending_work)
987 		push_queue(mq, e);
988 }
989 
990 static void push_queue_front(struct smq_policy *mq, struct entry *e)
991 {
992 	if (e->dirty)
993 		q_push_front(&mq->dirty, e);
994 	else
995 		q_push_front(&mq->clean, e);
996 }
997 
998 static void push_front(struct smq_policy *mq, struct entry *e)
999 {
1000 	h_insert(&mq->table, e);
1001 	if (!e->pending_work)
1002 		push_queue_front(mq, e);
1003 }
1004 
1005 static dm_cblock_t infer_cblock(struct smq_policy *mq, struct entry *e)
1006 {
1007 	return to_cblock(get_index(&mq->cache_alloc, e));
1008 }
1009 
1010 static void requeue(struct smq_policy *mq, struct entry *e)
1011 {
1012 	/*
1013 	 * Pending work has temporarily been taken out of the queues.
1014 	 */
1015 	if (e->pending_work)
1016 		return;
1017 
1018 	if (!test_and_set_bit(from_cblock(infer_cblock(mq, e)), mq->cache_hit_bits)) {
1019 		if (!e->dirty) {
1020 			q_requeue(&mq->clean, e, 1u, NULL, NULL);
1021 			return;
1022 		}
1023 
1024 		q_requeue(&mq->dirty, e, 1u,
1025 			  get_sentinel(&mq->writeback_sentinel_alloc, e->level, !mq->current_writeback_sentinels),
1026 			  get_sentinel(&mq->writeback_sentinel_alloc, e->level, mq->current_writeback_sentinels));
1027 	}
1028 }
1029 
1030 static unsigned int default_promote_level(struct smq_policy *mq)
1031 {
1032 	/*
1033 	 * The promote level depends on the current performance of the
1034 	 * cache.
1035 	 *
1036 	 * If the cache is performing badly, then we can't afford
1037 	 * to promote much without causing performance to drop below that
1038 	 * of the origin device.
1039 	 *
1040 	 * If the cache is performing well, then we don't need to promote
1041 	 * much.  If it isn't broken, don't fix it.
1042 	 *
1043 	 * If the cache is middling then we promote more.
1044 	 *
1045 	 * This scheme reminds me of a graph of entropy vs probability of a
1046 	 * binary variable.
1047 	 */
1048 	static const unsigned int table[] = {
1049 		1, 1, 1, 2, 4, 6, 7, 8, 7, 6, 4, 4, 3, 3, 2, 2, 1
1050 	};
1051 
1052 	unsigned int hits = mq->cache_stats.hits;
1053 	unsigned int misses = mq->cache_stats.misses;
1054 	unsigned int index = safe_div(hits << 4u, hits + misses);
1055 	return table[index];
1056 }
1057 
1058 static void update_promote_levels(struct smq_policy *mq)
1059 {
1060 	/*
1061 	 * If there are unused cache entries then we want to be really
1062 	 * eager to promote.
1063 	 */
1064 	unsigned int threshold_level = allocator_empty(&mq->cache_alloc) ?
1065 		default_promote_level(mq) : (NR_HOTSPOT_LEVELS / 2u);
1066 
1067 	threshold_level = max(threshold_level, NR_HOTSPOT_LEVELS);
1068 
1069 	/*
1070 	 * If the hotspot queue is performing badly then we have little
1071 	 * confidence that we know which blocks to promote.  So we cut down
1072 	 * the amount of promotions.
1073 	 */
1074 	switch (stats_assess(&mq->hotspot_stats)) {
1075 	case Q_POOR:
1076 		threshold_level /= 4u;
1077 		break;
1078 
1079 	case Q_FAIR:
1080 		threshold_level /= 2u;
1081 		break;
1082 
1083 	case Q_WELL:
1084 		break;
1085 	}
1086 
1087 	mq->read_promote_level = NR_HOTSPOT_LEVELS - threshold_level;
1088 	mq->write_promote_level = (NR_HOTSPOT_LEVELS - threshold_level);
1089 }
1090 
1091 /*
1092  * If the hotspot queue is performing badly, then we try and move entries
1093  * around more quickly.
1094  */
1095 static void update_level_jump(struct smq_policy *mq)
1096 {
1097 	switch (stats_assess(&mq->hotspot_stats)) {
1098 	case Q_POOR:
1099 		mq->hotspot_level_jump = 4u;
1100 		break;
1101 
1102 	case Q_FAIR:
1103 		mq->hotspot_level_jump = 2u;
1104 		break;
1105 
1106 	case Q_WELL:
1107 		mq->hotspot_level_jump = 1u;
1108 		break;
1109 	}
1110 }
1111 
1112 static void end_hotspot_period(struct smq_policy *mq)
1113 {
1114 	clear_bitset(mq->hotspot_hit_bits, mq->nr_hotspot_blocks);
1115 	update_promote_levels(mq);
1116 
1117 	if (time_after(jiffies, mq->next_hotspot_period)) {
1118 		update_level_jump(mq);
1119 		q_redistribute(&mq->hotspot);
1120 		stats_reset(&mq->hotspot_stats);
1121 		mq->next_hotspot_period = jiffies + HOTSPOT_UPDATE_PERIOD;
1122 	}
1123 }
1124 
1125 static void end_cache_period(struct smq_policy *mq)
1126 {
1127 	if (time_after(jiffies, mq->next_cache_period)) {
1128 		clear_bitset(mq->cache_hit_bits, from_cblock(mq->cache_size));
1129 
1130 		q_redistribute(&mq->dirty);
1131 		q_redistribute(&mq->clean);
1132 		stats_reset(&mq->cache_stats);
1133 
1134 		mq->next_cache_period = jiffies + CACHE_UPDATE_PERIOD;
1135 	}
1136 }
1137 
1138 /*----------------------------------------------------------------*/
1139 
1140 /*
1141  * Targets are given as a percentage.
1142  */
1143 #define CLEAN_TARGET 25u
1144 #define FREE_TARGET 25u
1145 
1146 static unsigned int percent_to_target(struct smq_policy *mq, unsigned int p)
1147 {
1148 	return from_cblock(mq->cache_size) * p / 100u;
1149 }
1150 
1151 static bool clean_target_met(struct smq_policy *mq, bool idle)
1152 {
1153 	/*
1154 	 * Cache entries may not be populated.  So we cannot rely on the
1155 	 * size of the clean queue.
1156 	 */
1157 	if (idle || mq->cleaner) {
1158 		/*
1159 		 * We'd like to clean everything.
1160 		 */
1161 		return q_size(&mq->dirty) == 0u;
1162 	}
1163 
1164 	/*
1165 	 * If we're busy we don't worry about cleaning at all.
1166 	 */
1167 	return true;
1168 }
1169 
1170 static bool free_target_met(struct smq_policy *mq)
1171 {
1172 	unsigned int nr_free;
1173 
1174 	nr_free = from_cblock(mq->cache_size) - mq->cache_alloc.nr_allocated;
1175 	return (nr_free + btracker_nr_demotions_queued(mq->bg_work)) >=
1176 		percent_to_target(mq, FREE_TARGET);
1177 }
1178 
1179 /*----------------------------------------------------------------*/
1180 
1181 static void mark_pending(struct smq_policy *mq, struct entry *e)
1182 {
1183 	BUG_ON(e->sentinel);
1184 	BUG_ON(!e->allocated);
1185 	BUG_ON(e->pending_work);
1186 	e->pending_work = true;
1187 }
1188 
1189 static void clear_pending(struct smq_policy *mq, struct entry *e)
1190 {
1191 	BUG_ON(!e->pending_work);
1192 	e->pending_work = false;
1193 }
1194 
1195 static void queue_writeback(struct smq_policy *mq, bool idle)
1196 {
1197 	int r;
1198 	struct policy_work work;
1199 	struct entry *e;
1200 
1201 	e = q_peek(&mq->dirty, mq->dirty.nr_levels, idle);
1202 	if (e) {
1203 		mark_pending(mq, e);
1204 		q_del(&mq->dirty, e);
1205 
1206 		work.op = POLICY_WRITEBACK;
1207 		work.oblock = e->oblock;
1208 		work.cblock = infer_cblock(mq, e);
1209 
1210 		r = btracker_queue(mq->bg_work, &work, NULL);
1211 		if (r) {
1212 			clear_pending(mq, e);
1213 			q_push_front(&mq->dirty, e);
1214 		}
1215 	}
1216 }
1217 
1218 static void queue_demotion(struct smq_policy *mq)
1219 {
1220 	int r;
1221 	struct policy_work work;
1222 	struct entry *e;
1223 
1224 	if (WARN_ON_ONCE(!mq->migrations_allowed))
1225 		return;
1226 
1227 	e = q_peek(&mq->clean, mq->clean.nr_levels / 2, true);
1228 	if (!e) {
1229 		if (!clean_target_met(mq, true))
1230 			queue_writeback(mq, false);
1231 		return;
1232 	}
1233 
1234 	mark_pending(mq, e);
1235 	q_del(&mq->clean, e);
1236 
1237 	work.op = POLICY_DEMOTE;
1238 	work.oblock = e->oblock;
1239 	work.cblock = infer_cblock(mq, e);
1240 	r = btracker_queue(mq->bg_work, &work, NULL);
1241 	if (r) {
1242 		clear_pending(mq, e);
1243 		q_push_front(&mq->clean, e);
1244 	}
1245 }
1246 
1247 static void queue_promotion(struct smq_policy *mq, dm_oblock_t oblock,
1248 			    struct policy_work **workp)
1249 {
1250 	int r;
1251 	struct entry *e;
1252 	struct policy_work work;
1253 
1254 	if (!mq->migrations_allowed)
1255 		return;
1256 
1257 	if (allocator_empty(&mq->cache_alloc)) {
1258 		/*
1259 		 * We always claim to be 'idle' to ensure some demotions happen
1260 		 * with continuous loads.
1261 		 */
1262 		if (!free_target_met(mq))
1263 			queue_demotion(mq);
1264 		return;
1265 	}
1266 
1267 	if (btracker_promotion_already_present(mq->bg_work, oblock))
1268 		return;
1269 
1270 	/*
1271 	 * We allocate the entry now to reserve the cblock.  If the
1272 	 * background work is aborted we must remember to free it.
1273 	 */
1274 	e = alloc_entry(&mq->cache_alloc);
1275 	BUG_ON(!e);
1276 	e->pending_work = true;
1277 	work.op = POLICY_PROMOTE;
1278 	work.oblock = oblock;
1279 	work.cblock = infer_cblock(mq, e);
1280 	r = btracker_queue(mq->bg_work, &work, workp);
1281 	if (r)
1282 		free_entry(&mq->cache_alloc, e);
1283 }
1284 
1285 /*----------------------------------------------------------------*/
1286 
1287 enum promote_result {
1288 	PROMOTE_NOT,
1289 	PROMOTE_TEMPORARY,
1290 	PROMOTE_PERMANENT
1291 };
1292 
1293 /*
1294  * Converts a boolean into a promote result.
1295  */
1296 static enum promote_result maybe_promote(bool promote)
1297 {
1298 	return promote ? PROMOTE_PERMANENT : PROMOTE_NOT;
1299 }
1300 
1301 static enum promote_result should_promote(struct smq_policy *mq, struct entry *hs_e,
1302 					  int data_dir, bool fast_promote)
1303 {
1304 	if (data_dir == WRITE) {
1305 		if (!allocator_empty(&mq->cache_alloc) && fast_promote)
1306 			return PROMOTE_TEMPORARY;
1307 
1308 		return maybe_promote(hs_e->level >= mq->write_promote_level);
1309 	} else
1310 		return maybe_promote(hs_e->level >= mq->read_promote_level);
1311 }
1312 
1313 static dm_oblock_t to_hblock(struct smq_policy *mq, dm_oblock_t b)
1314 {
1315 	sector_t r = from_oblock(b);
1316 	(void) sector_div(r, mq->cache_blocks_per_hotspot_block);
1317 	return to_oblock(r);
1318 }
1319 
1320 static struct entry *update_hotspot_queue(struct smq_policy *mq, dm_oblock_t b)
1321 {
1322 	unsigned int hi;
1323 	dm_oblock_t hb = to_hblock(mq, b);
1324 	struct entry *e = h_lookup(&mq->hotspot_table, hb);
1325 
1326 	if (e) {
1327 		stats_level_accessed(&mq->hotspot_stats, e->level);
1328 
1329 		hi = get_index(&mq->hotspot_alloc, e);
1330 		q_requeue(&mq->hotspot, e,
1331 			  test_and_set_bit(hi, mq->hotspot_hit_bits) ?
1332 			  0u : mq->hotspot_level_jump,
1333 			  NULL, NULL);
1334 
1335 	} else {
1336 		stats_miss(&mq->hotspot_stats);
1337 
1338 		e = alloc_entry(&mq->hotspot_alloc);
1339 		if (!e) {
1340 			e = q_pop(&mq->hotspot);
1341 			if (e) {
1342 				h_remove(&mq->hotspot_table, e);
1343 				hi = get_index(&mq->hotspot_alloc, e);
1344 				clear_bit(hi, mq->hotspot_hit_bits);
1345 			}
1346 
1347 		}
1348 
1349 		if (e) {
1350 			e->oblock = hb;
1351 			q_push(&mq->hotspot, e);
1352 			h_insert(&mq->hotspot_table, e);
1353 		}
1354 	}
1355 
1356 	return e;
1357 }
1358 
1359 /*----------------------------------------------------------------*/
1360 
1361 /*
1362  * Public interface, via the policy struct.  See dm-cache-policy.h for a
1363  * description of these.
1364  */
1365 
1366 static struct smq_policy *to_smq_policy(struct dm_cache_policy *p)
1367 {
1368 	return container_of(p, struct smq_policy, policy);
1369 }
1370 
1371 static void smq_destroy(struct dm_cache_policy *p)
1372 {
1373 	struct smq_policy *mq = to_smq_policy(p);
1374 
1375 	btracker_destroy(mq->bg_work);
1376 	h_exit(&mq->hotspot_table);
1377 	h_exit(&mq->table);
1378 	free_bitset(mq->hotspot_hit_bits);
1379 	free_bitset(mq->cache_hit_bits);
1380 	space_exit(&mq->es);
1381 	kfree(mq);
1382 }
1383 
1384 /*----------------------------------------------------------------*/
1385 
1386 static int __lookup(struct smq_policy *mq, dm_oblock_t oblock, dm_cblock_t *cblock,
1387 		    int data_dir, bool fast_copy,
1388 		    struct policy_work **work, bool *background_work)
1389 {
1390 	struct entry *e, *hs_e;
1391 	enum promote_result pr;
1392 
1393 	*background_work = false;
1394 
1395 	e = h_lookup(&mq->table, oblock);
1396 	if (e) {
1397 		stats_level_accessed(&mq->cache_stats, e->level);
1398 
1399 		requeue(mq, e);
1400 		*cblock = infer_cblock(mq, e);
1401 		return 0;
1402 
1403 	} else {
1404 		stats_miss(&mq->cache_stats);
1405 
1406 		/*
1407 		 * The hotspot queue only gets updated with misses.
1408 		 */
1409 		hs_e = update_hotspot_queue(mq, oblock);
1410 
1411 		pr = should_promote(mq, hs_e, data_dir, fast_copy);
1412 		if (pr != PROMOTE_NOT) {
1413 			queue_promotion(mq, oblock, work);
1414 			*background_work = true;
1415 		}
1416 
1417 		return -ENOENT;
1418 	}
1419 }
1420 
1421 static int smq_lookup(struct dm_cache_policy *p, dm_oblock_t oblock, dm_cblock_t *cblock,
1422 		      int data_dir, bool fast_copy,
1423 		      bool *background_work)
1424 {
1425 	int r;
1426 	unsigned long flags;
1427 	struct smq_policy *mq = to_smq_policy(p);
1428 
1429 	spin_lock_irqsave(&mq->lock, flags);
1430 	r = __lookup(mq, oblock, cblock,
1431 		     data_dir, fast_copy,
1432 		     NULL, background_work);
1433 	spin_unlock_irqrestore(&mq->lock, flags);
1434 
1435 	return r;
1436 }
1437 
1438 static int smq_lookup_with_work(struct dm_cache_policy *p,
1439 				dm_oblock_t oblock, dm_cblock_t *cblock,
1440 				int data_dir, bool fast_copy,
1441 				struct policy_work **work)
1442 {
1443 	int r;
1444 	bool background_queued;
1445 	unsigned long flags;
1446 	struct smq_policy *mq = to_smq_policy(p);
1447 
1448 	spin_lock_irqsave(&mq->lock, flags);
1449 	r = __lookup(mq, oblock, cblock, data_dir, fast_copy, work, &background_queued);
1450 	spin_unlock_irqrestore(&mq->lock, flags);
1451 
1452 	return r;
1453 }
1454 
1455 static int smq_get_background_work(struct dm_cache_policy *p, bool idle,
1456 				   struct policy_work **result)
1457 {
1458 	int r;
1459 	unsigned long flags;
1460 	struct smq_policy *mq = to_smq_policy(p);
1461 
1462 	spin_lock_irqsave(&mq->lock, flags);
1463 	r = btracker_issue(mq->bg_work, result);
1464 	if (r == -ENODATA) {
1465 		if (!clean_target_met(mq, idle)) {
1466 			queue_writeback(mq, idle);
1467 			r = btracker_issue(mq->bg_work, result);
1468 		}
1469 	}
1470 	spin_unlock_irqrestore(&mq->lock, flags);
1471 
1472 	return r;
1473 }
1474 
1475 /*
1476  * We need to clear any pending work flags that have been set, and in the
1477  * case of promotion free the entry for the destination cblock.
1478  */
1479 static void __complete_background_work(struct smq_policy *mq,
1480 				       struct policy_work *work,
1481 				       bool success)
1482 {
1483 	struct entry *e = get_entry(&mq->cache_alloc,
1484 				    from_cblock(work->cblock));
1485 
1486 	switch (work->op) {
1487 	case POLICY_PROMOTE:
1488 		// !h, !q, a
1489 		clear_pending(mq, e);
1490 		if (success) {
1491 			e->oblock = work->oblock;
1492 			e->level = NR_CACHE_LEVELS - 1;
1493 			push(mq, e);
1494 			// h, q, a
1495 		} else {
1496 			free_entry(&mq->cache_alloc, e);
1497 			// !h, !q, !a
1498 		}
1499 		break;
1500 
1501 	case POLICY_DEMOTE:
1502 		// h, !q, a
1503 		if (success) {
1504 			h_remove(&mq->table, e);
1505 			free_entry(&mq->cache_alloc, e);
1506 			// !h, !q, !a
1507 		} else {
1508 			clear_pending(mq, e);
1509 			push_queue(mq, e);
1510 			// h, q, a
1511 		}
1512 		break;
1513 
1514 	case POLICY_WRITEBACK:
1515 		// h, !q, a
1516 		clear_pending(mq, e);
1517 		push_queue(mq, e);
1518 		// h, q, a
1519 		break;
1520 	}
1521 
1522 	btracker_complete(mq->bg_work, work);
1523 }
1524 
1525 static void smq_complete_background_work(struct dm_cache_policy *p,
1526 					 struct policy_work *work,
1527 					 bool success)
1528 {
1529 	unsigned long flags;
1530 	struct smq_policy *mq = to_smq_policy(p);
1531 
1532 	spin_lock_irqsave(&mq->lock, flags);
1533 	__complete_background_work(mq, work, success);
1534 	spin_unlock_irqrestore(&mq->lock, flags);
1535 }
1536 
1537 // in_hash(oblock) -> in_hash(oblock)
1538 static void __smq_set_clear_dirty(struct smq_policy *mq, dm_cblock_t cblock, bool set)
1539 {
1540 	struct entry *e = get_entry(&mq->cache_alloc, from_cblock(cblock));
1541 
1542 	if (e->pending_work)
1543 		e->dirty = set;
1544 	else {
1545 		del_queue(mq, e);
1546 		e->dirty = set;
1547 		push_queue(mq, e);
1548 	}
1549 }
1550 
1551 static void smq_set_dirty(struct dm_cache_policy *p, dm_cblock_t cblock)
1552 {
1553 	unsigned long flags;
1554 	struct smq_policy *mq = to_smq_policy(p);
1555 
1556 	spin_lock_irqsave(&mq->lock, flags);
1557 	__smq_set_clear_dirty(mq, cblock, true);
1558 	spin_unlock_irqrestore(&mq->lock, flags);
1559 }
1560 
1561 static void smq_clear_dirty(struct dm_cache_policy *p, dm_cblock_t cblock)
1562 {
1563 	struct smq_policy *mq = to_smq_policy(p);
1564 	unsigned long flags;
1565 
1566 	spin_lock_irqsave(&mq->lock, flags);
1567 	__smq_set_clear_dirty(mq, cblock, false);
1568 	spin_unlock_irqrestore(&mq->lock, flags);
1569 }
1570 
1571 static unsigned int random_level(dm_cblock_t cblock)
1572 {
1573 	return hash_32(from_cblock(cblock), 9) & (NR_CACHE_LEVELS - 1);
1574 }
1575 
1576 static int smq_load_mapping(struct dm_cache_policy *p,
1577 			    dm_oblock_t oblock, dm_cblock_t cblock,
1578 			    bool dirty, uint32_t hint, bool hint_valid)
1579 {
1580 	struct smq_policy *mq = to_smq_policy(p);
1581 	struct entry *e;
1582 
1583 	e = alloc_particular_entry(&mq->cache_alloc, from_cblock(cblock));
1584 	e->oblock = oblock;
1585 	e->dirty = dirty;
1586 	e->level = hint_valid ? min(hint, NR_CACHE_LEVELS - 1) : random_level(cblock);
1587 	e->pending_work = false;
1588 
1589 	/*
1590 	 * When we load mappings we push ahead of both sentinels in order to
1591 	 * allow demotions and cleaning to occur immediately.
1592 	 */
1593 	push_front(mq, e);
1594 
1595 	return 0;
1596 }
1597 
1598 static int smq_invalidate_mapping(struct dm_cache_policy *p, dm_cblock_t cblock)
1599 {
1600 	struct smq_policy *mq = to_smq_policy(p);
1601 	struct entry *e = get_entry(&mq->cache_alloc, from_cblock(cblock));
1602 	unsigned long flags;
1603 	int r = 0;
1604 
1605 	spin_lock_irqsave(&mq->lock, flags);
1606 	if (!e->allocated) {
1607 		r = -ENODATA;
1608 		goto out;
1609 	}
1610 	// FIXME: what if this block has pending background work?
1611 	del_queue(mq, e);
1612 	h_remove(&mq->table, e);
1613 	free_entry(&mq->cache_alloc, e);
1614 
1615 out:
1616 	spin_unlock_irqrestore(&mq->lock, flags);
1617 
1618 	return r;
1619 }
1620 
1621 static uint32_t smq_get_hint(struct dm_cache_policy *p, dm_cblock_t cblock)
1622 {
1623 	struct smq_policy *mq = to_smq_policy(p);
1624 	struct entry *e = get_entry(&mq->cache_alloc, from_cblock(cblock));
1625 
1626 	if (!e->allocated)
1627 		return 0;
1628 
1629 	return e->level;
1630 }
1631 
1632 static dm_cblock_t smq_residency(struct dm_cache_policy *p)
1633 {
1634 	dm_cblock_t r;
1635 	unsigned long flags;
1636 	struct smq_policy *mq = to_smq_policy(p);
1637 
1638 	spin_lock_irqsave(&mq->lock, flags);
1639 	r = to_cblock(mq->cache_alloc.nr_allocated);
1640 	spin_unlock_irqrestore(&mq->lock, flags);
1641 
1642 	return r;
1643 }
1644 
1645 static void smq_tick(struct dm_cache_policy *p, bool can_block)
1646 {
1647 	struct smq_policy *mq = to_smq_policy(p);
1648 	unsigned long flags;
1649 
1650 	spin_lock_irqsave(&mq->lock, flags);
1651 	mq->tick++;
1652 	update_sentinels(mq);
1653 	end_hotspot_period(mq);
1654 	end_cache_period(mq);
1655 	spin_unlock_irqrestore(&mq->lock, flags);
1656 }
1657 
1658 static void smq_allow_migrations(struct dm_cache_policy *p, bool allow)
1659 {
1660 	struct smq_policy *mq = to_smq_policy(p);
1661 
1662 	mq->migrations_allowed = allow;
1663 }
1664 
1665 /*
1666  * smq has no config values, but the old mq policy did.  To avoid breaking
1667  * software we continue to accept these configurables for the mq policy,
1668  * but they have no effect.
1669  */
1670 static int mq_set_config_value(struct dm_cache_policy *p,
1671 			       const char *key, const char *value)
1672 {
1673 	unsigned long tmp;
1674 
1675 	if (kstrtoul(value, 10, &tmp))
1676 		return -EINVAL;
1677 
1678 	if (!strcasecmp(key, "random_threshold") ||
1679 	    !strcasecmp(key, "sequential_threshold") ||
1680 	    !strcasecmp(key, "discard_promote_adjustment") ||
1681 	    !strcasecmp(key, "read_promote_adjustment") ||
1682 	    !strcasecmp(key, "write_promote_adjustment")) {
1683 		DMWARN("tunable '%s' no longer has any effect, mq policy is now an alias for smq", key);
1684 		return 0;
1685 	}
1686 
1687 	return -EINVAL;
1688 }
1689 
1690 static int mq_emit_config_values(struct dm_cache_policy *p, char *result,
1691 				 unsigned int maxlen, ssize_t *sz_ptr)
1692 {
1693 	ssize_t sz = *sz_ptr;
1694 
1695 	DMEMIT("10 random_threshold 0 "
1696 	       "sequential_threshold 0 "
1697 	       "discard_promote_adjustment 0 "
1698 	       "read_promote_adjustment 0 "
1699 	       "write_promote_adjustment 0 ");
1700 
1701 	*sz_ptr = sz;
1702 	return 0;
1703 }
1704 
1705 /* Init the policy plugin interface function pointers. */
1706 static void init_policy_functions(struct smq_policy *mq, bool mimic_mq)
1707 {
1708 	mq->policy.destroy = smq_destroy;
1709 	mq->policy.lookup = smq_lookup;
1710 	mq->policy.lookup_with_work = smq_lookup_with_work;
1711 	mq->policy.get_background_work = smq_get_background_work;
1712 	mq->policy.complete_background_work = smq_complete_background_work;
1713 	mq->policy.set_dirty = smq_set_dirty;
1714 	mq->policy.clear_dirty = smq_clear_dirty;
1715 	mq->policy.load_mapping = smq_load_mapping;
1716 	mq->policy.invalidate_mapping = smq_invalidate_mapping;
1717 	mq->policy.get_hint = smq_get_hint;
1718 	mq->policy.residency = smq_residency;
1719 	mq->policy.tick = smq_tick;
1720 	mq->policy.allow_migrations = smq_allow_migrations;
1721 
1722 	if (mimic_mq) {
1723 		mq->policy.set_config_value = mq_set_config_value;
1724 		mq->policy.emit_config_values = mq_emit_config_values;
1725 	}
1726 }
1727 
1728 static bool too_many_hotspot_blocks(sector_t origin_size,
1729 				    sector_t hotspot_block_size,
1730 				    unsigned int nr_hotspot_blocks)
1731 {
1732 	return (hotspot_block_size * nr_hotspot_blocks) > origin_size;
1733 }
1734 
1735 static void calc_hotspot_params(sector_t origin_size,
1736 				sector_t cache_block_size,
1737 				unsigned int nr_cache_blocks,
1738 				sector_t *hotspot_block_size,
1739 				unsigned int *nr_hotspot_blocks)
1740 {
1741 	*hotspot_block_size = cache_block_size * 16u;
1742 	*nr_hotspot_blocks = max(nr_cache_blocks / 4u, 1024u);
1743 
1744 	while ((*hotspot_block_size > cache_block_size) &&
1745 	       too_many_hotspot_blocks(origin_size, *hotspot_block_size, *nr_hotspot_blocks))
1746 		*hotspot_block_size /= 2u;
1747 }
1748 
1749 static struct dm_cache_policy *
1750 __smq_create(dm_cblock_t cache_size, sector_t origin_size, sector_t cache_block_size,
1751 	     bool mimic_mq, bool migrations_allowed, bool cleaner)
1752 {
1753 	unsigned int i;
1754 	unsigned int nr_sentinels_per_queue = 2u * NR_CACHE_LEVELS;
1755 	unsigned int total_sentinels = 2u * nr_sentinels_per_queue;
1756 	struct smq_policy *mq = kzalloc_obj(*mq);
1757 
1758 	if (!mq)
1759 		return NULL;
1760 
1761 	init_policy_functions(mq, mimic_mq);
1762 	mq->cache_size = cache_size;
1763 	mq->cache_block_size = cache_block_size;
1764 
1765 	calc_hotspot_params(origin_size, cache_block_size, from_cblock(cache_size),
1766 			    &mq->hotspot_block_size, &mq->nr_hotspot_blocks);
1767 
1768 	mq->cache_blocks_per_hotspot_block = div64_u64(mq->hotspot_block_size, mq->cache_block_size);
1769 	mq->hotspot_level_jump = 1u;
1770 	if (space_init(&mq->es, total_sentinels + mq->nr_hotspot_blocks + from_cblock(cache_size))) {
1771 		DMERR("couldn't initialize entry space");
1772 		goto bad_pool_init;
1773 	}
1774 
1775 	init_allocator(&mq->writeback_sentinel_alloc, &mq->es, 0, nr_sentinels_per_queue);
1776 	for (i = 0; i < nr_sentinels_per_queue; i++)
1777 		get_entry(&mq->writeback_sentinel_alloc, i)->sentinel = true;
1778 
1779 	init_allocator(&mq->demote_sentinel_alloc, &mq->es, nr_sentinels_per_queue, total_sentinels);
1780 	for (i = 0; i < nr_sentinels_per_queue; i++)
1781 		get_entry(&mq->demote_sentinel_alloc, i)->sentinel = true;
1782 
1783 	init_allocator(&mq->hotspot_alloc, &mq->es, total_sentinels,
1784 		       total_sentinels + mq->nr_hotspot_blocks);
1785 
1786 	init_allocator(&mq->cache_alloc, &mq->es,
1787 		       total_sentinels + mq->nr_hotspot_blocks,
1788 		       total_sentinels + mq->nr_hotspot_blocks + from_cblock(cache_size));
1789 
1790 	mq->hotspot_hit_bits = alloc_bitset(mq->nr_hotspot_blocks);
1791 	if (!mq->hotspot_hit_bits) {
1792 		DMERR("couldn't allocate hotspot hit bitset");
1793 		goto bad_hotspot_hit_bits;
1794 	}
1795 	clear_bitset(mq->hotspot_hit_bits, mq->nr_hotspot_blocks);
1796 
1797 	if (from_cblock(cache_size)) {
1798 		mq->cache_hit_bits = alloc_bitset(from_cblock(cache_size));
1799 		if (!mq->cache_hit_bits) {
1800 			DMERR("couldn't allocate cache hit bitset");
1801 			goto bad_cache_hit_bits;
1802 		}
1803 		clear_bitset(mq->cache_hit_bits, from_cblock(mq->cache_size));
1804 	} else
1805 		mq->cache_hit_bits = NULL;
1806 
1807 	mq->tick = 0;
1808 	spin_lock_init(&mq->lock);
1809 
1810 	q_init(&mq->hotspot, &mq->es, NR_HOTSPOT_LEVELS);
1811 	mq->hotspot.nr_top_levels = 8;
1812 	mq->hotspot.nr_in_top_levels = min(mq->nr_hotspot_blocks / NR_HOTSPOT_LEVELS,
1813 					   from_cblock(mq->cache_size) / mq->cache_blocks_per_hotspot_block);
1814 
1815 	q_init(&mq->clean, &mq->es, NR_CACHE_LEVELS);
1816 	q_init(&mq->dirty, &mq->es, NR_CACHE_LEVELS);
1817 
1818 	stats_init(&mq->hotspot_stats, NR_HOTSPOT_LEVELS);
1819 	stats_init(&mq->cache_stats, NR_CACHE_LEVELS);
1820 
1821 	if (h_init(&mq->table, &mq->es, from_cblock(cache_size)))
1822 		goto bad_alloc_table;
1823 
1824 	if (h_init(&mq->hotspot_table, &mq->es, mq->nr_hotspot_blocks))
1825 		goto bad_alloc_hotspot_table;
1826 
1827 	sentinels_init(mq);
1828 	mq->write_promote_level = mq->read_promote_level = NR_HOTSPOT_LEVELS;
1829 
1830 	mq->next_hotspot_period = jiffies;
1831 	mq->next_cache_period = jiffies;
1832 
1833 	mq->bg_work = btracker_create(max(1u, smq_max_background_work));
1834 	if (!mq->bg_work)
1835 		goto bad_btracker;
1836 
1837 	mq->migrations_allowed = migrations_allowed;
1838 	mq->cleaner = cleaner;
1839 
1840 	return &mq->policy;
1841 
1842 bad_btracker:
1843 	h_exit(&mq->hotspot_table);
1844 bad_alloc_hotspot_table:
1845 	h_exit(&mq->table);
1846 bad_alloc_table:
1847 	free_bitset(mq->cache_hit_bits);
1848 bad_cache_hit_bits:
1849 	free_bitset(mq->hotspot_hit_bits);
1850 bad_hotspot_hit_bits:
1851 	space_exit(&mq->es);
1852 bad_pool_init:
1853 	kfree(mq);
1854 
1855 	return NULL;
1856 }
1857 
1858 static struct dm_cache_policy *smq_create(dm_cblock_t cache_size,
1859 					  sector_t origin_size,
1860 					  sector_t cache_block_size)
1861 {
1862 	return __smq_create(cache_size, origin_size, cache_block_size,
1863 			    false, true, false);
1864 }
1865 
1866 static struct dm_cache_policy *mq_create(dm_cblock_t cache_size,
1867 					 sector_t origin_size,
1868 					 sector_t cache_block_size)
1869 {
1870 	return __smq_create(cache_size, origin_size, cache_block_size,
1871 			    true, true, false);
1872 }
1873 
1874 static struct dm_cache_policy *cleaner_create(dm_cblock_t cache_size,
1875 					      sector_t origin_size,
1876 					      sector_t cache_block_size)
1877 {
1878 	return __smq_create(cache_size, origin_size, cache_block_size,
1879 			    false, false, true);
1880 }
1881 
1882 /*----------------------------------------------------------------*/
1883 
1884 static struct dm_cache_policy_type smq_policy_type = {
1885 	.name = "smq",
1886 	.version = {2, 0, 0},
1887 	.hint_size = 4,
1888 	.owner = THIS_MODULE,
1889 	.create = smq_create
1890 };
1891 
1892 static struct dm_cache_policy_type mq_policy_type = {
1893 	.name = "mq",
1894 	.version = {2, 0, 0},
1895 	.hint_size = 4,
1896 	.owner = THIS_MODULE,
1897 	.create = mq_create,
1898 };
1899 
1900 static struct dm_cache_policy_type cleaner_policy_type = {
1901 	.name = "cleaner",
1902 	.version = {2, 0, 0},
1903 	.hint_size = 4,
1904 	.owner = THIS_MODULE,
1905 	.create = cleaner_create,
1906 };
1907 
1908 static struct dm_cache_policy_type default_policy_type = {
1909 	.name = "default",
1910 	.version = {2, 0, 0},
1911 	.hint_size = 4,
1912 	.owner = THIS_MODULE,
1913 	.create = smq_create,
1914 	.real = &smq_policy_type
1915 };
1916 
1917 static int __init smq_init(void)
1918 {
1919 	int r;
1920 
1921 	r = dm_cache_policy_register(&smq_policy_type);
1922 	if (r) {
1923 		DMERR("register failed %d", r);
1924 		return -ENOMEM;
1925 	}
1926 
1927 	r = dm_cache_policy_register(&mq_policy_type);
1928 	if (r) {
1929 		DMERR("register failed (as mq) %d", r);
1930 		goto out_mq;
1931 	}
1932 
1933 	r = dm_cache_policy_register(&cleaner_policy_type);
1934 	if (r) {
1935 		DMERR("register failed (as cleaner) %d", r);
1936 		goto out_cleaner;
1937 	}
1938 
1939 	r = dm_cache_policy_register(&default_policy_type);
1940 	if (r) {
1941 		DMERR("register failed (as default) %d", r);
1942 		goto out_default;
1943 	}
1944 
1945 	return 0;
1946 
1947 out_default:
1948 	dm_cache_policy_unregister(&cleaner_policy_type);
1949 out_cleaner:
1950 	dm_cache_policy_unregister(&mq_policy_type);
1951 out_mq:
1952 	dm_cache_policy_unregister(&smq_policy_type);
1953 
1954 	return -ENOMEM;
1955 }
1956 
1957 static void __exit smq_exit(void)
1958 {
1959 	dm_cache_policy_unregister(&cleaner_policy_type);
1960 	dm_cache_policy_unregister(&smq_policy_type);
1961 	dm_cache_policy_unregister(&mq_policy_type);
1962 	dm_cache_policy_unregister(&default_policy_type);
1963 }
1964 
1965 module_init(smq_init);
1966 module_exit(smq_exit);
1967 
1968 MODULE_AUTHOR("Joe Thornber <dm-devel@lists.linux.dev>");
1969 MODULE_LICENSE("GPL");
1970 MODULE_DESCRIPTION("smq cache policy");
1971 
1972 MODULE_ALIAS("dm-cache-default");
1973 MODULE_ALIAS("dm-cache-mq");
1974 MODULE_ALIAS("dm-cache-cleaner");
1975