// 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:61-101.
 * Complete function definition; surrounding kernel context is required.
 * Source: https://github.com/torvalds/linux/blob/v6.0/mm/mlock.c#L61
 * License text: GPL-2.0.txt (in this directory).
 */
static struct lruvec *__mlock_page(struct page *page, struct lruvec *lruvec)
{
	/* There is nothing more we can do while it's off LRU */
	if (!TestClearPageLRU(page))
		return lruvec;

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

	if (unlikely(page_evictable(page))) {
		/*
		 * This is a little surprising, but quite possible:
		 * PageMlocked must have got cleared already by another CPU.
		 * Could this page be on the Unevictable LRU?  I'm not sure,
		 * but move it now if so.
		 */
		if (PageUnevictable(page)) {
			del_page_from_lru_list(page, lruvec);
			ClearPageUnevictable(page);
			add_page_to_lru_list(page, lruvec);
			__count_vm_events(UNEVICTABLE_PGRESCUED,
					  thp_nr_pages(page));
		}
		goto out;
	}

	if (PageUnevictable(page)) {
		if (PageMlocked(page))
			page->mlock_count++;
		goto out;
	}

	del_page_from_lru_list(page, lruvec);
	ClearPageActive(page);
	SetPageUnevictable(page);
	page->mlock_count = !!PageMlocked(page);
	add_page_to_lru_list(page, lruvec);
	__count_vm_events(UNEVICTABLE_PGCULLED, thp_nr_pages(page));
out:
	SetPageLRU(page);
	return lruvec;
}

