Re: [PATCH v4 2/4] blk-cgroup: fix race bet ween policy activation and blkg destruction
Tao Cui <[email protected]> Sun, 02 Aug 2026 19:46:06 +0800
| Newsgroups | org.kernel.vger.cgroups,org.kernel.vger.linux-block,org.kernel.vger.linux-kernel |
|---|---|
| Message-ID | <[email protected]> |
=E4=BA=8E 2026=E5=B9=B48=E6=9C=882=E6=97=A5 GMT+08:00 19:25:18=EF=BC=8CYu K=
uai <yukuai@kernel=2Eorg> =E5=86=99=E9=81=93=EF=BC=9A
>From: Zheng Qixing <zhengqixing@huawei=2Ecom>
>
>When switching an IO scheduler on a block device, blkcg_activate_policy()
>allocates blkg_policy_data (pd) for all blkgs attached to the queue=2E
>However, blkcg_activate_policy() may race with concurrent blkcg deletion,
>leading to use-after-free and memory leak issues=2E
>
>The use-after-free occurs in the following race:
>
>T1 (blkcg_activate_policy):
> - Successfully allocates pd for blkg1 (loop0->queue, blkcgA)
> - Fails to allocate pd for blkg2 (loop0->queue, blkcgB)
> - Enters the enomem rollback path to release blkg1 resources
>
>T2 (blkcg deletion):
> - blkcgA is deleted concurrently
> - blkg1 is freed via blkg_free_workfn()
> - blkg1->pd is freed
>
>T1 (continued):
> - Rollback path accesses blkg1->pd->online after pd is freed
> - Triggers use-after-free
>
>In addition, blkg_free_workfn() frees pd before removing the blkg from
>q->blkg_list=2E This allows blkcg_activate_policy() to allocate a new pd
>for a blkg that is being destroyed, leaving the newly allocated pd
>unreachable when the blkg is finally freed=2E
>
>Fix these races by extending blkcg_mutex coverage to serialize
>blkcg_activate_policy() rollback and blkg destruction, ensuring pd
>lifecycle is synchronized with blkg list visibility=2E
>
>Fixes: f1c006f1c685 ("blk-cgroup: synchronize pd_free_fn() from blkg_free=
_workfn() and blkcg_deactivate_policy()")
>Signed-off-by: Zheng Qixing <zhengqixing@huawei=2Ecom>
>Reviewed-by: Tang Yizhou <yizhou=2Etang@shopee=2Ecom>
>Signed-off-by: Yu Kuai <yukuai@fygo=2Eio>
>---
> block/blk-cgroup=2Ec | 3 +++
> 1 file changed, 3 insertions(+)
>
>diff --git a/block/blk-cgroup=2Ec b/block/blk-cgroup=2Ec
>index eb0cfb10b859=2E=2E047bb42c282b 100644
>--- a/block/blk-cgroup=2Ec
>+++ b/block/blk-cgroup=2Ec
>@@ -1566,6 +1566,8 @@ int blkcg_activate_policy(struct gendisk *disk, con=
st struct blkcg_policy *pol)
>=20
> if (queue_is_mq(q))
> memflags =3D blk_mq_freeze_queue(q);
>+
>+ mutex_lock(&q->blkcg_mutex);
> retry:
> spin_lock_irq(&q->queue_lock);
>=20
>@@ -1628,6 +1630,7 @@ int blkcg_activate_policy(struct gendisk *disk, con=
st struct blkcg_policy *pol)
>=20
> spin_unlock_irq(&q->queue_lock);
> out:
>+ mutex_unlock(&q->blkcg_mutex);
> if (queue_is_mq(q))
> blk_mq_unfreeze_queue(q, memflags);
> if (pinned_blkg)
Reviewed-by: Tao Cui <cuitao@kylinos=2Ecn>