Skip to content

Commit d6c7396

Browse files
glagoligaxboe
authored andcommitted
bsg: fix race of bsg_open and bsg_unregister
The existing implementation allows races between bsg_unregister and bsg_open paths. bsg_unregister and request_queue cleanup and deletion may start and complete right after bsg_get_device (in bsg_open path) retrieves bsg_class_device and releases the mutex. Then bsg_open path touches freed memory of bsg_class_device and request_queue. One possible fix is to hold the mutex all the way through bsg_get_device instead of releasing it after bsg_class_device retrieval. Reviewed-by: Christoph Hellwig <[email protected]> Signed-Off-By: Anatoliy Glagolev <[email protected]> Signed-off-by: Jens Axboe <[email protected]>
1 parent be7f99c commit d6c7396

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

block/bsg.c

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -693,6 +693,8 @@ static struct bsg_device *bsg_add_device(struct inode *inode,
693693
struct bsg_device *bd;
694694
unsigned char buf[32];
695695

696+
lockdep_assert_held(&bsg_mutex);
697+
696698
if (!blk_get_queue(rq))
697699
return ERR_PTR(-ENXIO);
698700

@@ -707,22 +709,20 @@ static struct bsg_device *bsg_add_device(struct inode *inode,
707709
bsg_set_block(bd, file);
708710

709711
atomic_set(&bd->ref_count, 1);
710-
mutex_lock(&bsg_mutex);
711712
hlist_add_head(&bd->dev_list, bsg_dev_idx_hash(iminor(inode)));
712713

713714
strncpy(bd->name, dev_name(rq->bsg_dev.class_dev), sizeof(bd->name) - 1);
714715
bsg_dbg(bd, "bound to <%s>, max queue %d\n",
715716
format_dev_t(buf, inode->i_rdev), bd->max_queue);
716717

717-
mutex_unlock(&bsg_mutex);
718718
return bd;
719719
}
720720

721721
static struct bsg_device *__bsg_get_device(int minor, struct request_queue *q)
722722
{
723723
struct bsg_device *bd;
724724

725-
mutex_lock(&bsg_mutex);
725+
lockdep_assert_held(&bsg_mutex);
726726

727727
hlist_for_each_entry(bd, bsg_dev_idx_hash(minor), dev_list) {
728728
if (bd->queue == q) {
@@ -732,7 +732,6 @@ static struct bsg_device *__bsg_get_device(int minor, struct request_queue *q)
732732
}
733733
bd = NULL;
734734
found:
735-
mutex_unlock(&bsg_mutex);
736735
return bd;
737736
}
738737

@@ -746,17 +745,18 @@ static struct bsg_device *bsg_get_device(struct inode *inode, struct file *file)
746745
*/
747746
mutex_lock(&bsg_mutex);
748747
bcd = idr_find(&bsg_minor_idr, iminor(inode));
749-
mutex_unlock(&bsg_mutex);
750748

751-
if (!bcd)
752-
return ERR_PTR(-ENODEV);
749+
if (!bcd) {
750+
bd = ERR_PTR(-ENODEV);
751+
goto out_unlock;
752+
}
753753

754754
bd = __bsg_get_device(iminor(inode), bcd->queue);
755-
if (bd)
756-
return bd;
757-
758-
bd = bsg_add_device(inode, bcd->queue, file);
755+
if (!bd)
756+
bd = bsg_add_device(inode, bcd->queue, file);
759757

758+
out_unlock:
759+
mutex_unlock(&bsg_mutex);
760760
return bd;
761761
}
762762

0 commit comments

Comments
 (0)