Re: [PATCH 4/5] mm: gup: fix potential pgmap refcnt leak in __gup_device_huge()

From: Andrew Morton
Date: Sat Aug 07 2021 - 14:41:21 EST


On Sat, 7 Aug 2021 17:36:19 +0800 Miaohe Lin <linmiaohe@xxxxxxxxxx> wrote:

> When failed to try_grab_page, put_dev_pagemap() is missed. So pgmap
> refcnt will leak in this case. Also we remove the check for pgmap
> against NULL as it's also checked inside the put_dev_pagemap().
>
> ...
>
> --- a/mm/gup.c
> +++ b/mm/gup.c
> @@ -2253,14 +2253,14 @@ static int __gup_device_huge(unsigned long pfn, unsigned long addr,
> pages[*nr] = page;
> if (unlikely(!try_grab_page(page, flags))) {
> undo_dev_pagemap(nr, nr_start, flags, pages);
> + put_dev_pagemap(pgmap);
> return 0;
> }
> (*nr)++;
> pfn++;
> } while (addr += PAGE_SIZE, addr != end);
>
> - if (pgmap)
> - put_dev_pagemap(pgmap);
> + put_dev_pagemap(pgmap);
> return 1;
> }

We can simplify further, and remove the troublesome multiple return points?

--- a/mm/gup.c~mm-gup-fix-potential-pgmap-refcnt-leak-in-__gup_device_huge-fix
+++ a/mm/gup.c
@@ -2247,14 +2247,13 @@ static int __gup_device_huge(unsigned lo
pgmap = get_dev_pagemap(pfn, pgmap);
if (unlikely(!pgmap)) {
undo_dev_pagemap(nr, nr_start, flags, pages);
- return 0;
+ break;
}
SetPageReferenced(page);
pages[*nr] = page;
if (unlikely(!try_grab_page(page, flags))) {
undo_dev_pagemap(nr, nr_start, flags, pages);
- put_dev_pagemap(pgmap);
- return 0;
+ break;
}
(*nr)++;
pfn++;
_