bch2_trans_unlock(trans);
        cond_resched();
-       trans->locked = true;
+       trans_set_locked(trans);
 
        if (unlikely(trans->memory_allocation_failure)) {
                struct closure cl;
                bch2_trans_srcu_unlock(trans);
 
        trans->last_begin_ip = _RET_IP_;
-       trans->locked  = true;
+
+       trans_set_locked(trans);
 
        if (trans->restarted) {
                bch2_btree_path_traverse_all(trans);
        trans->last_begin_time  = local_clock();
        trans->fn_idx           = fn_idx;
        trans->locking_wait.task = current;
-       trans->locked           = true;
        trans->journal_replay_not_finished =
                unlikely(!test_bit(JOURNAL_replay_done, &c->journal.flags)) &&
                atomic_inc_not_zero(&c->journal_keys.ref);
        trans->srcu_idx         = srcu_read_lock(&c->btree_trans_barrier);
        trans->srcu_lock_time   = jiffies;
        trans->srcu_held        = true;
+       trans_set_locked(trans);
 
        closure_init_stack_release(&trans->ref);
        return trans;
 
                        return bch2_trans_relock_fail(trans, path, &f, trace);
        }
 
-       trans->locked = true;
+       trans_set_locked(trans);
 out:
        bch2_trans_verify_locks(trans);
        return 0;
 {
        __bch2_trans_unlock(trans);
 
-       trans->locked = false;
-       trans->last_unlock_ip = _RET_IP_;
+       trans_set_unlocked(trans);
 }
 
 void bch2_trans_unlock(struct btree_trans *trans)
 {
        __bch2_trans_unlock(trans);
 
-       trans->locked = false;
-       trans->last_unlock_ip = _RET_IP_;
+       trans_set_unlocked(trans);
 }
 
 void bch2_trans_unlock_long(struct btree_trans *trans)
 
 
 /* lock: */
 
+static inline void trans_set_locked(struct btree_trans *trans)
+{
+       if (!trans->locked) {
+               trans->locked = true;
+               trans->last_unlock_ip = 0;
+
+               trans->pf_memalloc_nofs = (current->flags & PF_MEMALLOC_NOFS) != 0;
+               current->flags |= PF_MEMALLOC_NOFS;
+       }
+}
+
+static inline void trans_set_unlocked(struct btree_trans *trans)
+{
+       if (trans->locked) {
+               trans->locked = false;
+               trans->last_unlock_ip = _RET_IP_;
+
+               if (!trans->pf_memalloc_nofs)
+                       current->flags &= ~PF_MEMALLOC_NOFS;
+       }
+}
+
 static inline int __btree_node_lock_nopath(struct btree_trans *trans,
                                         struct btree_bkey_cached_common *b,
                                         enum six_lock_type type,
 
        bool                    lock_may_not_fail:1;
        bool                    srcu_held:1;
        bool                    locked:1;
+       bool                    pf_memalloc_nofs:1;
        bool                    write_locked:1;
        bool                    used_mempool:1;
        bool                    in_traverse_all:1;