// SPDX-License-Identifier: GPL-2.0
/*
 *	linux/mm/mlock.c
 *
 *  (C) Copyright 1995 Linus Torvalds
 *  (C) Copyright 2002 Christoph Hellwig
 */

/* Extracted unchanged from Linux v6.0, mm/mlock.c:122-162.
 * Complete function definition; surrounding kernel context is required.
 * Source: https://github.com/torvalds/linux/blob/v6.0/mm/mlock.c#L122
 * License text: GPL-2.0.txt (in this directory).
 */
static struct lruvec *__munlock_page(struct page *page, struct lruvec *lruvec)
{
	int nr_pages = thp_nr_pages(page);
	bool isolated = false;

	if (!TestClearPageLRU(page))
		goto munlock;

	isolated = true;
	lruvec = folio_lruvec_relock_irq(page_folio(page), lruvec);

	if (PageUnevictable(page)) {
		/* Then mlock_count is maintained, but might undercount */
		if (page->mlock_count)
			page->mlock_count--;
		if (page->mlock_count)
			goto out;
	}
	/* else assume that was the last mlock: reclaim will fix it if not */

munlock:
	if (TestClearPageMlocked(page)) {
		__mod_zone_page_state(page_zone(page), NR_MLOCK, -nr_pages);
		if (isolated || !PageUnevictable(page))
			__count_vm_events(UNEVICTABLE_PGMUNLOCKED, nr_pages);
		else
			__count_vm_events(UNEVICTABLE_PGSTRANDED, nr_pages);
	}

	/* page_evictable() has to be checked *after* clearing Mlocked */
	if (isolated && PageUnevictable(page) && page_evictable(page)) {
		del_page_from_lru_list(page, lruvec);
		ClearPageUnevictable(page);
		add_page_to_lru_list(page, lruvec);
		__count_vm_events(UNEVICTABLE_PGRESCUED, nr_pages);
	}
out:
	if (isolated)
		SetPageLRU(page);
	return lruvec;
}

