]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_locking.c
93a6ebed3aba25ebf2873845d02d9b5da0510a3d
[bcachefs-tools-debian] / libbcachefs / btree_locking.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "bcachefs.h"
4 #include "btree_locking.h"
5 #include "btree_types.h"
6
7 struct lock_class_key bch2_btree_node_lock_key;
8
9 /* Btree node locking: */
10
11 static inline void six_lock_readers_add(struct six_lock *lock, int nr)
12 {
13         if (lock->readers)
14                 this_cpu_add(*lock->readers, nr);
15         else if (nr > 0)
16                 atomic64_add(__SIX_VAL(read_lock, nr), &lock->state.counter);
17         else
18                 atomic64_sub(__SIX_VAL(read_lock, -nr), &lock->state.counter);
19 }
20
21 struct six_lock_count bch2_btree_node_lock_counts(struct btree_trans *trans,
22                                                   struct btree_path *skip,
23                                                   struct btree_bkey_cached_common *b,
24                                                   unsigned level)
25 {
26         struct btree_path *path;
27         struct six_lock_count ret;
28
29         memset(&ret, 0, sizeof(ret));
30
31         if (IS_ERR_OR_NULL(b))
32                 return ret;
33
34         trans_for_each_path(trans, path)
35                 if (path != skip && &path->l[level].b->c == b) {
36                         int t = btree_node_locked_type(path, level);
37
38                         if (t != BTREE_NODE_UNLOCKED)
39                                 ret.n[t]++;
40                 }
41
42         return ret;
43 }
44
45 /* unlock */
46
47 void bch2_btree_node_unlock_write(struct btree_trans *trans,
48                         struct btree_path *path, struct btree *b)
49 {
50         bch2_btree_node_unlock_write_inlined(trans, path, b);
51 }
52
53 /* lock */
54
55 /*
56  * @trans wants to lock @b with type @type
57  */
58 struct trans_waiting_for_lock {
59         struct btree_trans              *trans;
60         struct btree_bkey_cached_common *node_want;
61         enum six_lock_type              lock_want;
62
63         /* for iterating over held locks :*/
64         u8                              path_idx;
65         u8                              level;
66         u64                             lock_start_time;
67 };
68
69 struct lock_graph {
70         struct trans_waiting_for_lock   g[8];
71         unsigned                        nr;
72 };
73
74 static noinline void print_cycle(struct printbuf *out, struct lock_graph *g)
75 {
76         struct trans_waiting_for_lock *i;
77
78         prt_printf(out, "Found lock cycle (%u entries):", g->nr);
79         prt_newline(out);
80
81         for (i = g->g; i < g->g + g->nr; i++)
82                 bch2_btree_trans_to_text(out, i->trans);
83 }
84
85 static noinline void print_chain(struct printbuf *out, struct lock_graph *g)
86 {
87         struct trans_waiting_for_lock *i;
88
89         for (i = g->g; i != g->g + g->nr; i++) {
90                 if (i != g->g)
91                         prt_str(out, "<- ");
92                 prt_printf(out, "%u ", i->trans->locking_wait.task->pid);
93         }
94         prt_newline(out);
95 }
96
97 static void lock_graph_up(struct lock_graph *g)
98 {
99         closure_put(&g->g[--g->nr].trans->ref);
100 }
101
102 static void lock_graph_down(struct lock_graph *g, struct btree_trans *trans)
103 {
104         closure_get(&trans->ref);
105
106         g->g[g->nr++] = (struct trans_waiting_for_lock) {
107                 .trans          = trans,
108                 .node_want      = trans->locking,
109                 .lock_want      = trans->locking_wait.lock_want,
110         };
111 }
112
113 static bool lock_graph_remove_non_waiters(struct lock_graph *g)
114 {
115         struct trans_waiting_for_lock *i;
116
117         for (i = g->g + 1; i < g->g + g->nr; i++)
118                 if (i->trans->locking != i->node_want ||
119                     i->trans->locking_wait.start_time != i[-1].lock_start_time) {
120                         while (g->g + g->nr > i)
121                                 lock_graph_up(g);
122                         return true;
123                 }
124
125         return false;
126 }
127
128 static int abort_lock(struct lock_graph *g, struct trans_waiting_for_lock *i)
129 {
130         if (i == g->g) {
131                 trace_and_count(i->trans->c, trans_restart_would_deadlock, i->trans, _RET_IP_);
132                 return btree_trans_restart(i->trans, BCH_ERR_transaction_restart_would_deadlock);
133         } else {
134                 i->trans->lock_must_abort = true;
135                 wake_up_process(i->trans->locking_wait.task);
136                 return 0;
137         }
138 }
139
140 static int btree_trans_abort_preference(struct btree_trans *trans)
141 {
142         if (trans->lock_may_not_fail)
143                 return 0;
144         if (trans->locking_wait.lock_want == SIX_LOCK_write)
145                 return 1;
146         if (!trans->in_traverse_all)
147                 return 2;
148         return 3;
149 }
150
151 static noinline int break_cycle(struct lock_graph *g, struct printbuf *cycle)
152 {
153         struct trans_waiting_for_lock *i, *abort = NULL;
154         unsigned best = 0, pref;
155         int ret;
156
157         if (lock_graph_remove_non_waiters(g))
158                 return 0;
159
160         /* Only checking, for debugfs: */
161         if (cycle) {
162                 print_cycle(cycle, g);
163                 ret = -1;
164                 goto out;
165         }
166
167         for (i = g->g; i < g->g + g->nr; i++) {
168                 pref = btree_trans_abort_preference(i->trans);
169                 if (pref > best) {
170                         abort = i;
171                         best = pref;
172                 }
173         }
174
175         if (unlikely(!best)) {
176                 struct bch_fs *c = g->g->trans->c;
177                 struct printbuf buf = PRINTBUF;
178
179                 bch_err(c, "cycle of nofail locks");
180
181                 for (i = g->g; i < g->g + g->nr; i++) {
182                         struct btree_trans *trans = i->trans;
183
184                         bch2_btree_trans_to_text(&buf, trans);
185
186                         prt_printf(&buf, "backtrace:");
187                         prt_newline(&buf);
188                         printbuf_indent_add(&buf, 2);
189                         bch2_prt_backtrace(&buf, trans->locking_wait.task);
190                         printbuf_indent_sub(&buf, 2);
191                         prt_newline(&buf);
192                 }
193
194                 bch2_print_string_as_lines(KERN_ERR, buf.buf);
195                 printbuf_exit(&buf);
196                 BUG();
197         }
198
199         ret = abort_lock(g, abort);
200 out:
201         if (ret)
202                 while (g->nr)
203                         lock_graph_up(g);
204         return ret;
205 }
206
207 static int lock_graph_descend(struct lock_graph *g, struct btree_trans *trans,
208                               struct printbuf *cycle)
209 {
210         struct btree_trans *orig_trans = g->g->trans;
211         struct trans_waiting_for_lock *i;
212
213         for (i = g->g; i < g->g + g->nr; i++)
214                 if (i->trans == trans)
215                         return break_cycle(g, cycle);
216
217         if (g->nr == ARRAY_SIZE(g->g)) {
218                 if (orig_trans->lock_may_not_fail)
219                         return 0;
220
221                 while (g->nr)
222                         lock_graph_up(g);
223                 trace_and_count(trans->c, trans_restart_would_deadlock_recursion_limit, trans, _RET_IP_);
224                 return btree_trans_restart(orig_trans, BCH_ERR_transaction_restart_deadlock_recursion_limit);
225         }
226
227         lock_graph_down(g, trans);
228         return 0;
229 }
230
231 static bool lock_type_conflicts(enum six_lock_type t1, enum six_lock_type t2)
232 {
233         return t1 + t2 > 1;
234 }
235
236 int bch2_check_for_deadlock(struct btree_trans *trans, struct printbuf *cycle)
237 {
238         struct lock_graph g;
239         struct trans_waiting_for_lock *top;
240         struct btree_bkey_cached_common *b;
241         struct btree_path *path;
242         int ret;
243
244         if (trans->lock_must_abort) {
245                 trace_and_count(trans->c, trans_restart_would_deadlock, trans, _RET_IP_);
246                 return btree_trans_restart(trans, BCH_ERR_transaction_restart_would_deadlock);
247         }
248
249         g.nr = 0;
250         lock_graph_down(&g, trans);
251 next:
252         if (!g.nr)
253                 return 0;
254
255         top = &g.g[g.nr - 1];
256
257         trans_for_each_path_from(top->trans, path, top->path_idx) {
258                 if (!path->nodes_locked)
259                         continue;
260
261                 if (top->path_idx != path->idx) {
262                         top->path_idx           = path->idx;
263                         top->level              = 0;
264                         top->lock_start_time    = 0;
265                 }
266
267                 for (;
268                      top->level < BTREE_MAX_DEPTH;
269                      top->level++, top->lock_start_time = 0) {
270                         int lock_held = btree_node_locked_type(path, top->level);
271
272                         if (lock_held == BTREE_NODE_UNLOCKED)
273                                 continue;
274
275                         b = &READ_ONCE(path->l[top->level].b)->c;
276
277                         if (unlikely(IS_ERR_OR_NULL(b))) {
278                                 BUG_ON(!lock_graph_remove_non_waiters(&g));
279                                 goto next;
280                         }
281
282                         if (list_empty_careful(&b->lock.wait_list))
283                                 continue;
284
285                         raw_spin_lock(&b->lock.wait_lock);
286                         list_for_each_entry(trans, &b->lock.wait_list, locking_wait.list) {
287                                 BUG_ON(b != trans->locking);
288
289                                 if (top->lock_start_time &&
290                                     time_after_eq64(top->lock_start_time, trans->locking_wait.start_time))
291                                         continue;
292
293                                 top->lock_start_time = trans->locking_wait.start_time;
294
295                                 /* Don't check for self deadlock: */
296                                 if (trans == top->trans ||
297                                     !lock_type_conflicts(lock_held, trans->locking_wait.lock_want))
298                                         continue;
299
300                                 ret = lock_graph_descend(&g, trans, cycle);
301                                 raw_spin_unlock(&b->lock.wait_lock);
302
303                                 if (ret)
304                                         return ret;
305                                 goto next;
306
307                         }
308                         raw_spin_unlock(&b->lock.wait_lock);
309                 }
310         }
311
312         if (g.nr > 1 && cycle)
313                 print_chain(cycle, &g);
314         lock_graph_up(&g);
315         goto next;
316 }
317
318 int bch2_six_check_for_deadlock(struct six_lock *lock, void *p)
319 {
320         struct btree_trans *trans = p;
321
322         return bch2_check_for_deadlock(trans, NULL);
323 }
324
325 int __bch2_btree_node_lock_write(struct btree_trans *trans, struct btree_path *path,
326                                  struct btree_bkey_cached_common *b,
327                                  bool lock_may_not_fail)
328 {
329         int readers = bch2_btree_node_lock_counts(trans, NULL, b, b->level).n[SIX_LOCK_read];
330         int ret;
331
332         /*
333          * Must drop our read locks before calling six_lock_write() -
334          * six_unlock() won't do wakeups until the reader count
335          * goes to 0, and it's safe because we have the node intent
336          * locked:
337          */
338         six_lock_readers_add(&b->lock, -readers);
339         ret = __btree_node_lock_nopath(trans, b, SIX_LOCK_write, lock_may_not_fail);
340         six_lock_readers_add(&b->lock, readers);
341
342         if (ret)
343                 mark_btree_node_locked_noreset(path, b->level, SIX_LOCK_intent);
344
345         return ret;
346 }
347
348 /* relock */
349
350 static inline bool btree_path_get_locks(struct btree_trans *trans,
351                                         struct btree_path *path,
352                                         bool upgrade)
353 {
354         unsigned l = path->level;
355         int fail_idx = -1;
356
357         do {
358                 if (!btree_path_node(path, l))
359                         break;
360
361                 if (!(upgrade
362                       ? bch2_btree_node_upgrade(trans, path, l)
363                       : bch2_btree_node_relock(trans, path, l)))
364                         fail_idx = l;
365
366                 l++;
367         } while (l < path->locks_want);
368
369         /*
370          * When we fail to get a lock, we have to ensure that any child nodes
371          * can't be relocked so bch2_btree_path_traverse has to walk back up to
372          * the node that we failed to relock:
373          */
374         if (fail_idx >= 0) {
375                 __bch2_btree_path_unlock(trans, path);
376                 btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
377
378                 do {
379                         path->l[fail_idx].b = upgrade
380                                 ? ERR_PTR(-BCH_ERR_no_btree_node_upgrade)
381                                 : ERR_PTR(-BCH_ERR_no_btree_node_relock);
382                         --fail_idx;
383                 } while (fail_idx >= 0);
384         }
385
386         if (path->uptodate == BTREE_ITER_NEED_RELOCK)
387                 path->uptodate = BTREE_ITER_UPTODATE;
388
389         bch2_trans_verify_locks(trans);
390
391         return path->uptodate < BTREE_ITER_NEED_RELOCK;
392 }
393
394 bool __bch2_btree_node_relock(struct btree_trans *trans,
395                               struct btree_path *path, unsigned level,
396                               bool trace)
397 {
398         struct btree *b = btree_path_node(path, level);
399         int want = __btree_lock_want(path, level);
400
401         if (race_fault())
402                 goto fail;
403
404         if (six_relock_type(&b->c.lock, want, path->l[level].lock_seq) ||
405             (btree_node_lock_seq_matches(path, b, level) &&
406              btree_node_lock_increment(trans, &b->c, level, want))) {
407                 mark_btree_node_locked(trans, path, level, want);
408                 return true;
409         }
410 fail:
411         if (trace)
412                 trace_and_count(trans->c, btree_path_relock_fail, trans, _RET_IP_, path, level);
413         return false;
414 }
415
416 /* upgrade */
417
418 bool bch2_btree_node_upgrade(struct btree_trans *trans,
419                              struct btree_path *path, unsigned level)
420 {
421         struct btree *b = path->l[level].b;
422         struct six_lock_count count = bch2_btree_node_lock_counts(trans, path, &b->c, level);
423
424         if (!is_btree_node(path, level))
425                 return false;
426
427         switch (btree_lock_want(path, level)) {
428         case BTREE_NODE_UNLOCKED:
429                 BUG_ON(btree_node_locked(path, level));
430                 return true;
431         case BTREE_NODE_READ_LOCKED:
432                 BUG_ON(btree_node_intent_locked(path, level));
433                 return bch2_btree_node_relock(trans, path, level);
434         case BTREE_NODE_INTENT_LOCKED:
435                 break;
436         case BTREE_NODE_WRITE_LOCKED:
437                 BUG();
438         }
439
440         if (btree_node_intent_locked(path, level))
441                 return true;
442
443         if (race_fault())
444                 return false;
445
446         if (btree_node_locked(path, level)) {
447                 bool ret;
448
449                 six_lock_readers_add(&b->c.lock, -count.n[SIX_LOCK_read]);
450                 ret = six_lock_tryupgrade(&b->c.lock);
451                 six_lock_readers_add(&b->c.lock, count.n[SIX_LOCK_read]);
452
453                 if (ret)
454                         goto success;
455         } else {
456                 if (six_relock_type(&b->c.lock, SIX_LOCK_intent, path->l[level].lock_seq))
457                         goto success;
458         }
459
460         /*
461          * Do we already have an intent lock via another path? If so, just bump
462          * lock count:
463          */
464         if (btree_node_lock_seq_matches(path, b, level) &&
465             btree_node_lock_increment(trans, &b->c, level, BTREE_NODE_INTENT_LOCKED)) {
466                 btree_node_unlock(trans, path, level);
467                 goto success;
468         }
469
470         trace_and_count(trans->c, btree_path_upgrade_fail, trans, _RET_IP_, path, level);
471         return false;
472 success:
473         mark_btree_node_locked_noreset(path, level, SIX_LOCK_intent);
474         return true;
475 }
476
477 /* Btree path locking: */
478
479 /*
480  * Only for btree_cache.c - only relocks intent locks
481  */
482 int bch2_btree_path_relock_intent(struct btree_trans *trans,
483                                   struct btree_path *path)
484 {
485         unsigned l;
486
487         for (l = path->level;
488              l < path->locks_want && btree_path_node(path, l);
489              l++) {
490                 if (!bch2_btree_node_relock(trans, path, l)) {
491                         __bch2_btree_path_unlock(trans, path);
492                         btree_path_set_dirty(path, BTREE_ITER_NEED_TRAVERSE);
493                         trace_and_count(trans->c, trans_restart_relock_path_intent, trans, _RET_IP_, path);
494                         return btree_trans_restart(trans, BCH_ERR_transaction_restart_relock_path_intent);
495                 }
496         }
497
498         return 0;
499 }
500
501 __flatten
502 bool bch2_btree_path_relock_norestart(struct btree_trans *trans,
503                         struct btree_path *path, unsigned long trace_ip)
504 {
505         return btree_path_get_locks(trans, path, false);
506 }
507
508 __flatten
509 bool bch2_btree_path_upgrade_norestart(struct btree_trans *trans,
510                         struct btree_path *path, unsigned long trace_ip)
511 {
512         return btree_path_get_locks(trans, path, true);
513 }
514
515 bool bch2_btree_path_upgrade_noupgrade_sibs(struct btree_trans *trans,
516                                struct btree_path *path,
517                                unsigned new_locks_want)
518 {
519         EBUG_ON(path->locks_want >= new_locks_want);
520
521         path->locks_want = new_locks_want;
522
523         return btree_path_get_locks(trans, path, true);
524 }
525
526 bool __bch2_btree_path_upgrade(struct btree_trans *trans,
527                                struct btree_path *path,
528                                unsigned new_locks_want)
529 {
530         struct btree_path *linked;
531
532         if (bch2_btree_path_upgrade_noupgrade_sibs(trans, path, new_locks_want))
533                 return true;
534
535         /*
536          * XXX: this is ugly - we'd prefer to not be mucking with other
537          * iterators in the btree_trans here.
538          *
539          * On failure to upgrade the iterator, setting iter->locks_want and
540          * calling get_locks() is sufficient to make bch2_btree_path_traverse()
541          * get the locks we want on transaction restart.
542          *
543          * But if this iterator was a clone, on transaction restart what we did
544          * to this iterator isn't going to be preserved.
545          *
546          * Possibly we could add an iterator field for the parent iterator when
547          * an iterator is a copy - for now, we'll just upgrade any other
548          * iterators with the same btree id.
549          *
550          * The code below used to be needed to ensure ancestor nodes get locked
551          * before interior nodes - now that's handled by
552          * bch2_btree_path_traverse_all().
553          */
554         if (!path->cached && !trans->in_traverse_all)
555                 trans_for_each_path(trans, linked)
556                         if (linked != path &&
557                             linked->cached == path->cached &&
558                             linked->btree_id == path->btree_id &&
559                             linked->locks_want < new_locks_want) {
560                                 linked->locks_want = new_locks_want;
561                                 btree_path_get_locks(trans, linked, true);
562                         }
563
564         return false;
565 }
566
567 void __bch2_btree_path_downgrade(struct btree_trans *trans,
568                                  struct btree_path *path,
569                                  unsigned new_locks_want)
570 {
571         unsigned l;
572
573         EBUG_ON(path->locks_want < new_locks_want);
574
575         path->locks_want = new_locks_want;
576
577         while (path->nodes_locked &&
578                (l = btree_path_highest_level_locked(path)) >= path->locks_want) {
579                 if (l > path->level) {
580                         btree_node_unlock(trans, path, l);
581                 } else {
582                         if (btree_node_intent_locked(path, l)) {
583                                 six_lock_downgrade(&path->l[l].b->c.lock);
584                                 mark_btree_node_locked_noreset(path, l, SIX_LOCK_read);
585                         }
586                         break;
587                 }
588         }
589
590         bch2_btree_path_verify_locks(path);
591 }
592
593 /* Btree transaction locking: */
594
595 void bch2_trans_downgrade(struct btree_trans *trans)
596 {
597         struct btree_path *path;
598
599         trans_for_each_path(trans, path)
600                 bch2_btree_path_downgrade(trans, path);
601 }
602
603 int bch2_trans_relock(struct btree_trans *trans)
604 {
605         struct btree_path *path;
606
607         if (unlikely(trans->restarted))
608                 return - ((int) trans->restarted);
609
610         trans_for_each_path(trans, path)
611                 if (path->should_be_locked &&
612                     !bch2_btree_path_relock_norestart(trans, path, _RET_IP_)) {
613                         trace_and_count(trans->c, trans_restart_relock, trans, _RET_IP_, path);
614                         return btree_trans_restart(trans, BCH_ERR_transaction_restart_relock);
615                 }
616         return 0;
617 }
618
619 void bch2_trans_unlock(struct btree_trans *trans)
620 {
621         struct btree_path *path;
622
623         trans_for_each_path(trans, path)
624                 __bch2_btree_path_unlock(trans, path);
625
626         /*
627          * bch2_gc_btree_init_recurse() doesn't use btree iterators for walking
628          * btree nodes, it implements its own walking:
629          */
630         EBUG_ON(!trans->is_initial_gc &&
631                 lock_class_is_held(&bch2_btree_node_lock_key));
632 }
633
634 bool bch2_trans_locked(struct btree_trans *trans)
635 {
636         struct btree_path *path;
637
638         trans_for_each_path(trans, path)
639                 if (path->nodes_locked)
640                         return true;
641         return false;
642 }
643
644 /* Debug */
645
646 #ifdef CONFIG_BCACHEFS_DEBUG
647
648 void bch2_btree_path_verify_locks(struct btree_path *path)
649 {
650         unsigned l;
651
652         if (!path->nodes_locked) {
653                 BUG_ON(path->uptodate == BTREE_ITER_UPTODATE &&
654                        btree_path_node(path, path->level));
655                 return;
656         }
657
658         for (l = 0; l < BTREE_MAX_DEPTH; l++) {
659                 int want = btree_lock_want(path, l);
660                 int have = btree_node_locked_type(path, l);
661
662                 BUG_ON(!is_btree_node(path, l) && have != BTREE_NODE_UNLOCKED);
663
664                 BUG_ON(is_btree_node(path, l) &&
665                        (want == BTREE_NODE_UNLOCKED ||
666                         have != BTREE_NODE_WRITE_LOCKED) &&
667                        want != have);
668         }
669 }
670
671 void bch2_trans_verify_locks(struct btree_trans *trans)
672 {
673         struct btree_path *path;
674
675         trans_for_each_path(trans, path)
676                 bch2_btree_path_verify_locks(path);
677 }
678
679 #endif