Received: from gabe.freedesktop.org (gabe.freedesktop.org [131.252.210.177]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 53DE0606A31A for ; Mon, 30 Nov 2026 22:07:21 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key, unprotected) header.d=amd.com header.i=@amd.com header.a=rsa-sha256 header.s=selector1 header.b=mQ8bt3Py Received: from gabe.freedesktop.org (localhost [127.0.0.1]) by gabe.freedesktop.org (Postfix) with ESMTP id DEDDC10E3B2; Mon, 30 Nov 2026 22:07:15 +0000 (UTC) Received: from PH0PR06CU001.outbound.protection.outlook.com (mail-westus3azon11011051.outbound.protection.outlook.com [40.107.208.51]) by gabe.freedesktop.org (Postfix) with ESMTPS id 7015910E203 for ; Mon, 30 Nov 2026 22:07:08 +0000 (UTC) ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=jnUD0srYdx8KDN8PcqYDFG9CT1BG4lBKq3KebXMetD3tCQaTiFfJ9kigpwDtK+bRsj+vaKzBT4LLEGAzVPKgL+LfvdNQ/Islrif0hwURVuIgvD/C4ux5uTRIBb2lyaZUdnCq5jIshJfWSxOQJot3DvgcBAqIErA4SQBOHoj0MuXkC4fcLLEoNOWP0z20vSqTLBnRP9ZYzLUVNAFWN4tO3sRC3vUs0yHSITrtc773k4fVImqb339kyrPHWrAcvdI2Jdz1Ov+6nMsDsO3dGVBpEYB7x8ZKYl1Fu0u+IX2aVt9edjG8wNFcedXWVuE87YGGi68Ry1u38/WcYFlnBExn2Q== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=k6zzktNrJfvnhKja81mPTgvCqyVTOjleOirfqyzMNic=; b=tM2ayc+WAmqtwA0vdh0OYfJDUQbGt7My5/IRXOJV+yo9NrEjfRHovwdZKBIwMQYCw7rhpZ13QixOysC3LajRzyyJ7+yfQo0tZ42TMV/Mecq3akCr+Yat5IHdqv4vXO2LYQSOej+5Mb/tZ75onS8IYKOpZRvVELH1XBI+7l1kzfJWr9Nom+7rTsQ5Vj2+yHXOj7CT4FaSKE7m56Se9zY07g+B0dYVYOXb5KaScdQLSSyloRR+UJkDJs/B6KkhUlbL1kYHs8bTGt/Cqs7MXvQshmw6P3R4ilJ/4OPCbtwsDtf9mOCuwUqrciMyYiXIkBpD493Sf2vXPauAUKdTvlXCnQ== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=amd.com; dmarc=pass action=none header.from=amd.com; dkim=pass header.d=amd.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=amd.com; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=k6zzktNrJfvnhKja81mPTgvCqyVTOjleOirfqyzMNic=; b=mQ8bt3Pyrq0FELhKri7E3YQcW1INKnxGgFMyUyyoEIWpvhNiNBX4ag03du440U3nIx97cVbC2vpUcrh2s4nQows3TvHzeVswxiYBOgRPaFIceTHi0zExxRYcZ2+MHRfYZLxUJLHVUp1GlJ1ydXLfnHH1pS+62yzFi23ma0jqFsg= Authentication-Results: mx.microsoft.com 1; dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=amd.com; Received: from DM4PR12MB5167.namprd12.prod.outlook.com (2603:10b6:5:396::10) by IA1PR12MB7757.namprd12.prod.outlook.com (2603:10b6:208:422::17) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.662.11; Mon, 30 Nov 2026 22:06:59 +0000 Received: from DM4PR12MB5167.namprd12.prod.outlook.com ([fe80::4588:54c1:bc29:2c7c]) by DM4PR12MB5167.namprd12.prod.outlook.com ([fe80::4588:54c1:bc29:2c7c%3]) with mapi id 15.21.0662.012; Mon, 30 Nov 2026 22:06:59 +0000 Content-Type: multipart/alternative; boundary="------------qSkJ7PS69ml64xSB9kDMKxDh" Message-ID: <6aa37b81-0b7b-46cf-a0b4-261bd46d325d@amd.com> Date: Mon, 30 Nov 2026 17:06:57 -0500 User-Agent: Mozilla Thunderbird Subject: Re: [PATCH v5 1/3] drm/amdkfd: Add awareness of THP of device and system RAM in kfd svm driver To: "Chen, Xiaogang" , amd-gfx@lists.freedesktop.org References: <20261122202653.274580-1-xiaogang.chen@amd.com> <20261122202653.274580-2-xiaogang.chen@amd.com> <7affc853-ec24-4620-a883-b344f4ded38e@amd.com> Content-Language: en-US From: Philip Yang In-Reply-To: X-ClientProxiedBy: YT4PR01CA0178.CANPRD01.PROD.OUTLOOK.COM (2603:10b6:b01:110::22) To DM4PR12MB5167.namprd12.prod.outlook.com (2603:10b6:5:396::10) X-Archived-By: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: DM4PR12MB5167:EE_|IA1PR12MB7757:EE_ X-MS-Office365-Filtering-Correlation-Id: ff31c88d-08d3-4478-2860-08df4f2e40e3 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0; ARA:13230040|366016|23010399003|1800799024|376014|56012099006|261028144727099003|261102130727099003|261102123227099003|261022113327099003|261026121527099003|261026140227099003|261021121427099003|261022075727099003|261022105027099003|261021123027099003|10067099003|261009223027099003|18002099003|22082099003|4143699003|11063799006|5023799004|6133799003|8096899003; X-Microsoft-Antispam-Message-Info: xmr8vH5Ens7rbfkLW0sdI7yT2Cf48MuGMq5eP/lQoZMbAFV/DMdvxSOO9B4NjHp7InNYMJc5bzhy/1q5BknzGzzkQrWc31vs6huCqWbAvF6ECgaKl8Rh+9DegydcWT4MZveT6XMVYY50j9Y0n3KxhZglToRFIRRcQtCsy2C0ZxgLy0pFbN1jwyZoN962gVWnVUaTQ4jPdPvsBpcyZvQ8zWL0nnQBhDT+KRsbw2+xJggvWhpM/qlRvUIoT2ZAKd+V0Y9o3S9Ob2eX3gYb6dqjV+J5pWaqz8RXfNII2dezPVMbwCoGL79yZsn+0/67vLTckrd765cnVe9qt+tjIY9jQLvFbynnwutnIfy8POUIsKVFlSTGtBFhWzqfjOL9ZGzhtq08PRBqx9XNW29vIO4RjFZ45U6lTQWtOqq6srxE+NMKMTInLo/BnfoXJ3Ad12JMl0ur9ydT0SM67s4fcAPZGPNirkJDMfL2/i8jAZXoI0X+bdGmb+4gRdzMty80wAPa4/qYZIhIPyOq/K+hOZdT4i+Q3tAHnCxWwrhv0sVfi931SuXclM7N54vpBQjS3FtgFaDJjy6E/yDNz1PKCXemwUKOJg0ckQTpv6EJXrhs8Ne0n1UBBd69UG86XYr7Rc4yio+Z7pCeMDAdWw1K/2Qu8LPj7IkcpwCqw2g2bJPpCGQ= X-Forefront-Antispam-Report: CIP:255.255.255.255; CTRY:; LANG:en; SCL:1; SRV:; IPV:NLI; SFV:NSPM; H:DM4PR12MB5167.namprd12.prod.outlook.com; PTR:; CAT:NONE; SFS:(13230040)(366016)(23010399003)(1800799024)(376014)(56012099006)(261028144727099003)(261102130727099003)(261102123227099003)(261022113327099003)(261026121527099003)(261026140227099003)(261021121427099003)(261022075727099003)(261022105027099003)(261021123027099003)(10067099003)(261009223027099003)(18002099003)(22082099003)(4143699003)(11063799006)(5023799004)(6133799003)(8096899003); DIR:OUT; SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?a1Z6c2R6dXg1R3JaYzYyRU5DcE5aRW12SjBJZUdBWFBLanZHU1dwQ0pFaU93?= =?utf-8?B?Rkd3VW9CUDFUR1ZBa1JlK2NRcXRTc21xTGN2WExYQ1E5SlJQaVYrakQ5emIy?= =?utf-8?B?Q0ZtekErWUd3S0U4Umw5eFNqYTBLV09rVDhhSENrNE5tQzByb0hsdEtrVGtG?= =?utf-8?B?SjBOMWNhaTVlWEdqWHBXV2YxTmU1Rk1nRnQwc1BEYWZ1N1pVbkRKbWR0QSti?= =?utf-8?B?Mm1RdVEzYTM3dTc4VHdPS3U3elJLZFV2ODM0Q1JXTG53VWhrUlpkbGI5bTdm?= =?utf-8?B?OHJ5VzQvQWZubnR0MVViNXVHODBCa2tUUktyUWUzdHU3aGNGd084d3ZjU0dN?= =?utf-8?B?MVZhZ0pWaDlwWnIxTjMyVUVvYU94ZlpnUE5STDBKQnl6MUt6dVliZ3dhRlZa?= =?utf-8?B?YkhYR3pVd2Jxck42N3FUWnVieTJDQlNSLzkySlR2QUpYVk90dGJrekZuaVNi?= =?utf-8?B?THRVWXVUYVRxUHYrU3RMM2l2Y0FOd0UvZzlGeFpLelVEb0V6SVI1SzBFWllD?= =?utf-8?B?THBWRlI0Uy9LdzdOWHFJNEZLVXVZdFozczhWZ0dyYWs4cjVqdjBIKytDYjFi?= =?utf-8?B?dWdtVjdERDZLWXZzMXlTSUtnVkZFNStWdG01Q3lkbG1ScWxXQkQ5U3FQdHJu?= =?utf-8?B?NE9ISWF2YjJySmVLdCttVHFicGJMam1tMjhtSmlZVDZMZlFaRDQ3TEhmTXBG?= =?utf-8?B?cEtFUHJDWHFJMEkvc3JIOTEyTnNtZFJCcG9sMFZRN3AzWWlldlAzWjRUc1ZK?= =?utf-8?B?S1ArRXY5TS8xdmh4a25uTW9RNlFEbHRJY2kxSC9Ob1NDdXRXSkxQdVJ1ZFZJ?= =?utf-8?B?WnZMQXNhZlp2U05mcS9ZM2FlaUVybHg1ODYxeTdOd0JWaGtZVDVKMlc5MG1J?= =?utf-8?B?T0JReTQvT2xYNjAvMkl1QUl3ZzBjUEZGVVJGaTFYbldJbXdCY0xlYnNWWHFh?= =?utf-8?B?N1lEajdVOFNhR2kyOEFnQ292ZDM0clFCU29aWStacnBUakp0N3JpVnFaWDNw?= =?utf-8?B?akJTamNLQ0EvaFNSVlQ1WUNsbFZYZktpQjNCVTRQTFB5WExsS25kTWg4eGVK?= =?utf-8?B?TFpCZ2YyUEtJMnEvdkFKcDhVcTNIeERoWDBPSEZqUzBmdndtWUVZNE9KUldu?= =?utf-8?B?Sy8xZXpQNmpnUmFmWXJmME42bWNCZ2FMNzk1RW5zWTJ0VU5ITFNlMUVIUTFR?= =?utf-8?B?Q28rNHJVZklqTi9CSkovSzZoRTZTNjQrNG5Qc0FXK21MYjRlaCtaYkRTdTJB?= =?utf-8?B?azNnS1VOc2x5L0JFQ3BkanRXR2taTFpJTi9BRVozQ1Y3Q0pCd01Zd25MTG5I?= =?utf-8?B?MFlhcnJvMEtiMEgrZ2RSQ2ljMGtaZmJ3NTRXNitMYW9ianVrT0F0cTRXZ1Iw?= =?utf-8?B?VHROVW1GUnhKeElFa2ZSK3FOSVV1MlVHcjlnZE93T3Bva2wySnFRVGg2VjNP?= =?utf-8?B?NnJ0eGJmYTNpRlpMNlAvMXlMbC9SSjhpcFZudk5VdE9GbUlpRjdzb2F4bzkr?= =?utf-8?B?aVhjbEU1MlpZenR5ZHlxWndQRXVoRWI4ZGhiSlJpQjBoL2NKU3VaQTc0TGtm?= =?utf-8?B?bFI2dkZNemJUZFJrOXpmbGt6UGh0TE9Sem9JVFRHRWVaYWptcmY5d3JWVXla?= =?utf-8?B?dUVoZFJMS2lTd203cDUyanJXWnlrcDNsdTVhVUFNZjdyUVo1YmFTU0dLMDZp?= =?utf-8?B?NVBuOUQyd0pVQ1hXbEl6b1Q0NEVFUEk2Q1BuS1NnSVhrMUdiM09jb25KamtW?= =?utf-8?B?R1BoVG9MaCtHdkx6ZVBxVElzZmc1aFpMeVd2bk11eDIyN2creG1kS2dmbElE?= =?utf-8?B?cmhneGVvcDV0WXl6V1hRS2ZHRzNlL1BBQUhCeW5QOFUwSlpWblRoWVM3L3Fn?= =?utf-8?B?YU56emtQTTZiVU4wOEE1eERldXdoa2VXV0FPR0xaZjJxVysxTm0yaGQ3REht?= =?utf-8?B?RStjaE00YjA3eE5CREI1MjR1UW9iU2tsUlk0NXdVUXRmaVI5VW8xK1VhZXhO?= =?utf-8?B?R0ZQSzdjYUxKVUV5MC9Od2NYdXlLQndDNkxOR0Yrd3BKZEpZNFB2QjJWWjk0?= =?utf-8?B?WGpqcXlUQWdicU94RWpScksveS9JNjFreUdNQW5DRGJLV1NIS2QzbnNxM2c0?= =?utf-8?B?S0FOdEh3Nit6Vmw5KytLV2c3Y05mMkFpWENvWTdNS3FzN1c2YVcwOGhjVUFy?= =?utf-8?B?cFBjcHdlRHo0NzlFaldFaERDbzdtMDlud2theTFtb2NpQSs1S2NXTzNxS1oy?= =?utf-8?B?ZXRWa0pNbThodGd4R0txZkRIS3FjdDMrUjNNZ1U2MlV4KzJ2b1RoczhaeFg2?= =?utf-8?Q?6J3SzhJVYsNQInwBRf?= X-OriginatorOrg: amd.com X-MS-Exchange-CrossTenant-Network-Message-Id: ff31c88d-08d3-4478-2860-08df4f2e40e3 X-MS-Exchange-CrossTenant-AuthSource: DM4PR12MB5167.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Nov 2026 22:06:58.9405 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 3dd8961f-e488-4e60-8e11-a82d994e183d X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: L7XE0scHiTe4wuO36qpttR4J9zF2jAomAfAnDK0FtVOKw4D3vU1M6IFBFL9sf5K/ X-MS-Exchange-Transport-CrossTenantHeadersStamped: IA1PR12MB7757 X-BeenThere: amd-gfx@lists.freedesktop.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Discussion list for AMD gfx List-Archive: List-Post: List-Help: List-Subscribe: , Sender: "amd-gfx" X-Spam-Status: No, score=-14.3 required=3.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,HEADER_FROM_DIFFERENT_DOMAINS, HTML_MESSAGE,INCLUDES_CR_TRAILER,INCLUDES_PATCH,MAILING_LIST_MULTI, SPF_HELO_NONE,SPF_PASS,USER_AGENT_SANE_1 autolearn=ham autolearn_force=no version=4.0.1 X-Spam-Checker-Version: SpamAssassin 4.0.1 (2024-03-26) on aws-us-west-2-korg-listserv-alma10-1 --------------qSkJ7PS69ml64xSB9kDMKxDh Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit On 2026-11-30 02:36, Chen, Xiaogang wrote: > > On 11/27/2026 3:34 PM, Philip Yang wrote: >> >> >> On 2026-11-22 15:26, Xiaogang.Chen wrote: >>> From: Xiaogang Chen >>> >>> Extend kfd/svm functions to allocate HPAGE_PMD_SIZE based device >>> memory by >>> buddy allocator, each drm_buddy_block is HPAGE_PMD_SIZE aligned; and to >>> allocate THP system ram by vma_alloc_folio. >>> >>> Introduce SVM_RANGE_DMA_THP flag that indicates dma map of THP. THP dma >>> addresss will use this flag. >>> >>> Add dev_pagemap_ops->folio_split callback that is called by >>> folio_split when >>> core MM splits device memory folio. >>> >>> Reset compound folio of device memory after it got released from >>> core HMM. >>> So, TTM can reuse this VRAM as 4K pages on next range. >>> >>> These are preparations for following support for (THP) migration of >>> zone >>> device-private memory, no function change. >>> >>> Signed-off-by: Xiaogang Chen >>> --- >>>   drivers/gpu/drm/amd/amdkfd/kfd_migrate.c | 112 >>> ++++++++++++++++++++--- >>>   drivers/gpu/drm/amd/amdkfd/kfd_svm.c     |  39 ++++++-- >>>   drivers/gpu/drm/amd/amdkfd/kfd_svm.h     |  18 ++++ >>>   3 files changed, 152 insertions(+), 17 deletions(-) >>> >>> diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c >>> b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c >>> index 1eb92ac6eb05..5ead98a604b1 100644 >>> --- a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c >>> +++ b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c >>> @@ -218,17 +218,45 @@ svm_migrate_addr_to_pfn(struct amdgpu_device >>> *adev, unsigned long addr) >>>       return (addr + adev->kfd.pgmap.range.start) >> PAGE_SHIFT; >>>   } >>>   +/* >>> + * TTM can reuse a 2MB VRAM block that was previously a device THP. >>> + * Reset unused pages so the next 4K init does not see leftover >>> head/tail. >>> + */ >>> +static void svm_migrate_clear_compound_pages(struct page *page, >>> unsigned int nr, >>> +                          struct dev_pagemap *pgmap) >>> +{ >>> +    unsigned int i; >>> + >>> +    for (i = 0; i < nr; i++, page++) { >>> +        struct folio *new_folio = (struct folio *)page; >>> + >>> +        if (page_count(page)) >>> +            continue; >>> + >>> +        page->flags.f &= ~0xffUL; >>> +#ifdef NR_PAGES_IN_LARGE_FOLIO >>> +        ((struct folio *)(page - 1))->_nr_pages = 0; >>> +#endif >>> +        new_folio->mapping = NULL; >>> +        new_folio->pgmap = pgmap; >>> +        new_folio->share = 0; >>> +        page->zone_device_data = NULL; >>> +    } >>> +} >>> + >> This is not needed. Commit 12b2285bf3d1 ("mm/zone_device: reinitialize >> large zone device private folios") already makes zone_device_page_init() >> clear any leftover head/tail state when a page is handed out again. >> svm_migrate_get_vram_page() calls zone_device_folio_init() for every >> VRAM >> page it hands out, so the page is reinitialized when it is reused, as >> a 4K >> page or as part of a new THP. There is no need to clear the compound >> pages >> when the folio is freed. > no, it is needed. That part is easy to get confused. > svm_migrate_clear_compound_pages() runs because freeing the device THP > only releases the head folio. The other 511 struct pages stay linked > to that head, and TTM can hand those same VRAM pages out later as > ordinary 4K pages. > > free_zone_device_folio() clears folio->mapping on the head and calls > folio_free. It does not walk the tails. Each tail still has its > compound-tail marker, so page_folio() follows it back to the old head, > and page_pgmap() is implemented as page_folio(page)->pgmap. The tail's > own pgmap slot held the head pointer, not the dev_pagemap. The only reason the stale tail matters is that svm_migrate_get_vram_page() calls page_pgmap(). The pgmap is a single per-device structure, adev->kfd.pgmap, covering the whole VRAM, so we can pass it in directly and avoid page_pgmap() altogether: svm_migrate_copy_to_vram() { +    struct dev_pagemap *pgmap = &adev->kfd.pgmap; ... -            svm_migrate_get_vram_page(prange, dst_pfn, order); +            svm_migrate_get_vram_page(prange, dst_pfn, order, pgmap); zone_device_folio_init() then resets every page it hands out, a former tail included, without following the old head. With that, svm_migrate_clear_compound_pages() can be removed. It also open-codes writes to internal folio fields, which I would rather not have in the driver. > > Look at folio definition: pgmap and compound_info are the same word. A > tail page has bit 0 set there, so page_folio() follows it to the old > head, and page_pgmap() is page_folio(page)->pgmap. Writing the > dev_pagemap pointer clears that bit. After that, page_folio() returns > the page itself and page_pgmap() reads the pointer just stored. The > next zone_device_folio_init() does this again for the one page it is > given, but a former tail can be initialized after the old head has > already been reused. Without new_folio->pgmap = pgmap at free time, > page_pgmap() on that tail still follows the live head. > > And page->flags.f &= ~0xffUL is required too. PG_head is in the head > page's flags, and the folio order is in the low byte of the second > page's flags (folio->_flags_1). The next init clears those bits only > on the page it receives. Until the head itself is allocated again, > folio_test_large() on it is still true. > > svm_migrate_clear_compound_pages walks every page of the freed folio, > drops the head/tail flag bits and _nr_pages, and stores the real pgmap > on each page. After that, each page is a standalone zone-device page > and the next order-0 init does not follow the old THP. > > Another reason to have svm_migrate_clear_compound_pages: after kfd > driver publishes device pages to core MM. These pages are under core > MM management. So, not only kfd driver use them, other components can > use them too. At the time device pages got released by HMM to kfd > driver, before kfd driver reuse them these pages or folios need be in > clean state. So, re-users(not only kfd driver) can use them without > worrying their stale states. > > svm_migrate_clear_compound_pages  does mimic  zone_device_folio_init, > but it is on purpose. > >>>   static void >>> -svm_migrate_get_vram_page(struct svm_range *prange, unsigned long pfn) >>> +svm_migrate_get_vram_page(struct svm_range *prange, unsigned long pfn, >>> +               int order) + int order, struct dev_pagemap *pgmap) >>>   { >>> -    struct page *page; >>> +    struct page *page = pfn_to_page(pfn); >>>   -    page = pfn_to_page(pfn); >>> -    svm_range_bo_ref(prange->svm_bo); >>> +    /* Init this pfn, not page_folio() — that follows a leftover >>> tail to the old head. */ >>> +    zone_device_folio_init((struct folio *)page, page_pgmap(page), >>> order); +       zone_device_folio_init((struct folio *)page, pgmap, order); >>>       page->zone_device_data = prange->svm_bo; >> Please use folio_set_zone_device_data(page_folio(page), prange->svm_bo). >> The result is the same, since page is always the head page here, but it >> adds a sanity check and matches how other drivers do it. > I also have a version for coherent device THP support. > folio_set_zone_device_data only allows private device memory because  > currently only AMD supports coherent device memory. It is why I set > page->zone_device_data directly here. It does not affect anything but > will apply to coherent case. Agreed, folio_set_zone_device_data() warns on any page that is not device-private. Please add a comment to make that clear:     /* Not folio_set_zone_device_data(): it warns on device-coherent pages. */     page->zone_device_data = prange->svm_bo; Once a device folio is freed, nothing in core mm hands its pages out again. They only come back into use through svm_migrate_get_vram_page(), so no other code path sees the stale state. Regards, Philip >>> -    zone_device_page_init(page, page_pgmap(page), 0); >>> +    svm_range_bo_ref(prange->svm_bo); >>>   } >>>   + >>>   static void >>>   svm_migrate_put_vram_page(struct amdgpu_device *adev, unsigned >>> long addr) >>>   { >>> @@ -249,11 +277,45 @@ svm_migrate_addr(struct amdgpu_device *adev, >>> struct page *page) >>>   } >>>     static struct page * >>> -svm_migrate_get_sys_page(struct vm_area_struct *vma, unsigned long >>> addr) >>> +svm_migrate_get_sys_page(struct vm_area_struct *vma, unsigned long >>> addr, >>> +              unsigned long order) >>>   { >>>       struct page *page; >>>   -    page = alloc_page_vma(GFP_HIGHUSER, vma, addr); >>> +    if (order) { >>> +#ifdef CONFIG_TRANSPARENT_HUGEPAGE >> The caller only passes order > 0 on the THP compound page path, so this >> #ifdef is not needed. > It is defensive. if migrate->src[i] & MIGRATE_PFN_COMPOUND is true, > CONFIG_TRANSPARENT_HUGEPAGE  should have been defined by user on > kernel setting and hardware support THP. If HMM provides > MIGRATE_PFN_COMPOUND folio, but kernel does not enable THP or hardware > does not support THP driver return null for such request. >>> +        struct folio *folio; >>> +        gfp_t gfp; >>> + >>> +        /* >>> +         * Honour MADV_NOHUGEPAGE and prctl(PR_SET_THP_DISABLE). The >>> +         * sysfs THP policy (thp_vma_allowable_orders()) and >>> +         * vma_thp_gfp_mask() are not exported to modules. >>> +         */ >>> +        if (vma_thp_disabled(vma, vma->vm_flags, false)) >>> +            return NULL; >>> + >>> +        /* >>> +         * Used by every VRAM to RAM migration (CPU/GPU fault, >>> +         * prefetch, TTM eviction), and the caller falls back to 4K >>> +         * pages on failure. Fail fast like the default "madvise" >>> +         * defrag policy: no direct reclaim or compaction unless the >>> +         * VMA asked for huge pages. Eviction in particular runs under >>> +         * memory pressure, where compaction stalls are most costly. >>> +         */ >>> +        gfp = GFP_TRANSHUGE_LIGHT; >>> +        if (vma->vm_flags & VM_HUGEPAGE) >>> +            gfp |= __GFP_DIRECT_RECLAIM; >>> + >> I think this mixes up the madvise THP policy with THP page migration. >> They are separate settings. GFP_TRANSHUGE_LIGHT/GFP_TRANSHUGE are used >> internally by core mm (THP fault, khugepaged, NUMA migration), not by >> drivers. For the migration destination, please use GFP_HIGHUSER, the >> same >> flag other drivers use in their migrate-to-RAM paths. > > GFP_TRANSHUGE_LIGHT is used mostly by core MM. Here we allocate THP. > The idea is: not allocate sys THP when system has memory pressure. If > it happens fail quickly and driver falls back to normal size page > allocation by alloc_page_vma(GFP_HIGHUSER,...), there we use > GFP_HIGHUSER. > > The kernel comments on GFP_TRANSHUGE_LIGH: > >  * %GFP_TRANSHUGE and %GFP_TRANSHUGE_LIGHT are used for THP > allocations. They >  * are compound allocations that will generally fail quickly if memory > is not >  * available and will not wake kswapd/kcompactd on failure. The _LIGHT >  * version does not attempt reclaim/compaction at all and is by > default used >  * in page fault path, while the non-light is used by khugepaged. > > If we let kernel do its best to allocate THP that may trigger > kswapd/kcopactd and reclaim under memory pressure. That take much > longer time to allocate, specially this sys ram allocation is also > used by cpu page fault recovery and ttm eviction. > > So, allocate sys THP when there is no memory pressure(no reclaim). If > kernel has to do reclaim GFP_TRANSHUGE_LIGHT let kernel fail THP > allocation immediately, then driver uses GFP_HIGHUSER to allocate > normal size pages.  It is for better performance. > >> >>> +        folio = vma_alloc_folio(gfp, order, vma, addr); >>> +        page = folio ? folio_page(folio, 0) : NULL; >>> +#else >>> +        return NULL; >>> +#endif >>> +    } else { >>> +        page = alloc_page_vma(GFP_HIGHUSER, vma, addr); >>> +    } >>> + >>>       if (page) >>>           lock_page(page); >>>   @@ -267,8 +329,13 @@ static unsigned long >>> svm_migrate_successful_pages(struct migrate_vma *migrate) >>>         for (i = 0; i < migrate->npages; i++) { >>>           if (migrate->dst[i] & MIGRATE_PFN_VALID && >>> -            migrate->src[i] & MIGRATE_PFN_MIGRATE) >>> -            mpages++; >>> +            migrate->src[i] & MIGRATE_PFN_MIGRATE) { >> Wrong indentation change. > ok, >>> + >>> +            if (migrate->dst[i] & MIGRATE_PFN_COMPOUND) >>> +                mpages += SVM_HPAGE_PMD_NR; >> For a compound page, the remaining dst entries are zero, so skip them: >> >>                 i += HPAGE_PMD_NR - 1; >> >>> +            else >>> +                mpages++; >>> +        } >>>       } >>>       return mpages; >>>   } >>> @@ -312,7 +379,7 @@ svm_migrate_copy_to_vram(struct kfd_node *node, >>> struct svm_range *prange, >>>                   migrate->dst[i] = 0; >>>                   spage = NULL; >>>               } else { >>> -                svm_migrate_get_vram_page(prange, migrate->dst[i]); >>> +                svm_migrate_get_vram_page(prange, migrate->dst[i], 0); >>>                   migrate->dst[i] = migrate_pfn(migrate->dst[i]); >>>                   mpages++; >>>               } >>> @@ -626,10 +693,17 @@ svm_migrate_ram_to_vram(struct svm_range >>> *prange, uint32_t best_loc, >>>       return r < 0 ? r : 0; >>>   } >>>   +/* folio can be compound folio or single page */ >>>   static void svm_migrate_folio_free(struct folio *folio) >>>   { >>>       struct page *page = &folio->page; >>>       struct svm_range_bo *svm_bo = page->zone_device_data; >>> +    struct dev_pagemap *pgmap = folio->pgmap; >>> +    unsigned int order = folio_order(folio); >>> + >>> +    /* So TTM can reuse this VRAM as 4K pages on the next range. */ >>> +    if (order) >>> +        svm_migrate_clear_compound_pages(page, 1U << order, pgmap); >> As above, please remove this. > As explain above we need svm_migrate_clear_compound_pages. >> >>>       if (svm_bo) { >>>           pr_debug_ratelimited("ref: %d\n", kref_read(&svm_bo->kref)); >>> @@ -688,7 +762,7 @@ svm_migrate_copy_to_ram(struct amdgpu_device >>> *adev, struct svm_range *prange, >>>               j = 0; >>>           } >>>   -        dpage = svm_migrate_get_sys_page(migrate->vma, addr); >>> +        dpage = svm_migrate_get_sys_page(migrate->vma, addr, 0); >>>           if (!dpage) { >>>               pr_debug("failed get page svms 0x%p [0x%lx 0x%lx]\n", >>>                    prange->svms, prange->start, prange->last); >>> @@ -1091,9 +1165,25 @@ static vm_fault_t svm_migrate_to_ram(struct >>> vm_fault *vmf) >>>       return r ? VM_FAULT_SIGBUS : 0; >>>   } >>>   +static void svm_migrate_folio_split(struct folio *head, struct >>> folio *tail) >>> +{ >>> +    struct svm_range_bo *svm_bo; >>> + >>> +    if (tail == NULL) >>> +        return; >>> + >>> +    tail->pgmap = head->pgmap; >>> +    tail->mapping = head->mapping; >>> + >>> +    svm_bo = folio_zone_device_data(head); >>> +    folio_set_zone_device_data(tail, svm_bo); >>> +    svm_range_bo_ref(svm_bo); >>> +} >>> + >>>   static const struct dev_pagemap_ops svm_migrate_pgmap_ops = { >>>       .folio_free        = svm_migrate_folio_free, >>>       .migrate_to_ram        = svm_migrate_to_ram, >>> +    .folio_split        = svm_migrate_folio_split, >>>   }; >>>     /* Each VRAM page uses sizeof(struct page) on system memory */ >>> diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c >>> b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c >>> index 421d3f65fcf1..35cebdad5651 100644 >>> --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c >>> +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c >>> @@ -246,7 +246,16 @@ void svm_range_dma_unmap_dev(struct device >>> *dev, dma_addr_t *dma_addr, >>>           if (!svm_is_valid_dma_mapping_addr(dev, dma_addr[i])) >>>               continue; >>>           pr_debug_ratelimited("unmap 0x%llx\n", dma_addr[i] >> >>> PAGE_SHIFT); >>> -        dma_unmap_page(dev, dma_addr[i], PAGE_SIZE, dir); >>> + >>> +        /* dma unmap of THP */ >>> +        if (dma_addr[i] & SVM_RANGE_DMA_THP) { >>> +            dma_addr[i] &= ~SVM_RANGE_DMA_THP; >>> +            dma_unmap_page(dev, dma_addr[i], >>> PAGE_SIZE*SVM_HPAGE_PMD_NR, >>> +                       DMA_BIDIRECTIONAL); >> Clear the entry and skip the rest of the THP here: >> >>             dma_addr[i] = 0; >>             i += HPAGE_PMD_NR - 1; >> > ok > > Regards > > Xiaogang > >> >>> +        } else { >>> +            dma_unmap_page(dev, dma_addr[i], PAGE_SIZE, dir); >>                                    dma_addr[i] = 0; >>> +        } >>> + >>>           dma_addr[i] = 0; >> Then this line can be removed. >> >> Regards, >> Philip >>>       } >>>   } >>> @@ -579,10 +588,20 @@ svm_range_vram_node_new(struct kfd_node *node, >>> struct svm_range *prange, >>>       } >>>         memset(&bp, 0, sizeof(bp)); >>> +    /* >>> +     * Keep bp.size equal to the prange size so it matches the >>> +     * amdgpu_amdkfd_reserve_mem_limit() reservation made by the >>> caller. >>> +     * A 2MB byte_align makes the VRAM manager allocate 2MB-aligned >>> 2MB >>> +     * buddy blocks and trim only the last one to the requested >>> size, so >>> +     * every full 2MB chunk can still back a device THP. >>> +     */ >>>       bp.size = prange->npages * PAGE_SIZE; >>> +    if (SVM_THP_ENABLED && prange->npages >= SVM_HPAGE_PMD_NR) >>> +        bp.byte_align = SVM_HPAGE_PMD_SIZE; >>> +    else >>> +        bp.byte_align = PAGE_SIZE; >>>       bp.bo_ptr_size = sizeof(struct svm_range_bo); >>>       bp.destroy = svm_range_bo_destroy; >>> -    bp.byte_align = PAGE_SIZE; >>>       bp.domain = AMDGPU_GEM_DOMAIN_VRAM; >>>       bp.flags = AMDGPU_GEM_CREATE_NO_CPU_ACCESS; >>>       bp.flags |= clear ? AMDGPU_GEM_CREATE_VRAM_CLEARED : 0; >>> @@ -594,9 +613,16 @@ svm_range_vram_node_new(struct kfd_node *node, >>> struct svm_range *prange, >>>         r = amdgpu_bo_create(node->adev, &bp, &bo); >>>       if (r) { >>> -        pr_debug("failed %d to create bo\n", r); >>> -        mmput(mm); >>> -        goto create_bo_failed; >>> +        if (bp.byte_align == SVM_HPAGE_PMD_SIZE) { >>> +            /* fall back PAGE_SIZE granularity */ >>> +            bp.byte_align = PAGE_SIZE; >>> +            r = amdgpu_bo_create(node->adev, &bp, &bo); >>> +        } >>> +        if (r) { >>> +            pr_debug("failed %d to create bo\n", r); >>> +            mmput(mm); >>> +            goto create_bo_failed; >>> +        } >>>       } >>>         svm_bo = to_svm_range_bo(bo); >>> @@ -957,6 +983,7 @@ svm_range_copy_array(void *psrc, size_t size, >>> uint64_t num_elements, >>>       *vram_pages = 0; >>>       for (i = 0; i < num_elements; i++) { >>>           dma_addr_t *temp; >>> + >>>           temp = (dma_addr_t *)dst + i; >>>           *temp = *((dma_addr_t *)src + i); >>>           if (*temp&SVM_RANGE_VRAM_DOMAIN) >>> @@ -1675,7 +1702,7 @@ static int svm_range_reserve_bos(struct >>> svm_validate_context *ctx, bool intr) >>>       uint32_t gpuidx; >>>       int r; >>>   -    drm_exec_init(&ctx->exec, intr ? DRM_EXEC_INTERRUPTIBLE_WAIT: >>> 0, 0); >>> +    drm_exec_init(&ctx->exec, intr ? DRM_EXEC_INTERRUPTIBLE_WAIT : >>> 0, 0); >>>       drm_exec_until_all_locked(&ctx->exec) { >>>           for_each_set_bit(gpuidx, ctx->bitmap, MAX_GPU_INSTANCE) { >>>               pdd = kfd_process_device_from_gpuidx(ctx->process, >>> gpuidx); >>> diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.h >>> b/drivers/gpu/drm/amd/amdkfd/kfd_svm.h >>> index 38744e716f74..8767a784e679 100644 >>> --- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.h >>> +++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.h >>> @@ -35,6 +35,24 @@ >>>   #include "kfd_priv.h" >>>     #define SVM_RANGE_VRAM_DOMAIN (1UL << 0) >>> +#define SVM_RANGE_DMA_THP (1UL << 1) >>> + >>> +/* >>> + * Size of a PMD-mapped device or system THP. HPAGE_PMD_* expand to >>> + * BUILD_BUG() without CONFIG_TRANSPARENT_HUGEPAGE, so the SVM code >>> uses >>> + * these instead. Without THP, SVM_THP_ENABLED is false, no compound >>> + * migration is requested, and HMM never reports >>> MIGRATE_PFN_COMPOUND, so >>> + * the THP paths still compile but are never taken. >>> + */ >>> +#ifdef CONFIG_TRANSPARENT_HUGEPAGE >>> +#define SVM_HPAGE_PMD_ORDER    HPAGE_PMD_ORDER >>> +#else >>> +#define SVM_HPAGE_PMD_ORDER    (PMD_SHIFT - PAGE_SHIFT) >>> +#endif >>> +#define SVM_HPAGE_PMD_NR    (1UL << SVM_HPAGE_PMD_ORDER) >>> +#define SVM_HPAGE_PMD_SIZE    (PAGE_SIZE << SVM_HPAGE_PMD_ORDER) >>> +#define SVM_THP_ENABLED IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) >>> + >>>   #define SVM_ADEV_PGMAP_OWNER(adev)\ >>>               ((adev)->hive ? (void *)(adev)->hive : (void *)(adev)) >> --------------qSkJ7PS69ml64xSB9kDMKxDh Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: 8bit

On 2026-11-30 02:36, Chen, Xiaogang wrote:

On 11/27/2026 3:34 PM, Philip Yang wrote:


On 2026-11-22 15:26, Xiaogang.Chen wrote:
From: Xiaogang Chen<xiaogang.chen@amd.com>

Extend kfd/svm functions to allocate HPAGE_PMD_SIZE based device memory by
buddy allocator, each drm_buddy_block is HPAGE_PMD_SIZE aligned; and to
allocate THP system ram by vma_alloc_folio.

Introduce SVM_RANGE_DMA_THP flag that indicates dma map of THP. THP dma
addresss will use this flag.

Add dev_pagemap_ops->folio_split callback that is called by folio_split when
core MM splits device memory folio.

Reset compound folio of device memory after it got released from core HMM.
So, TTM can reuse this VRAM as 4K pages on next range.

These are preparations for following support for (THP) migration of zone
device-private memory, no function change.

Signed-off-by: Xiaogang Chen<xiaogang.chen@amd.com>
---
  drivers/gpu/drm/amd/amdkfd/kfd_migrate.c | 112 ++++++++++++++++++++---
  drivers/gpu/drm/amd/amdkfd/kfd_svm.c     |  39 ++++++--
  drivers/gpu/drm/amd/amdkfd/kfd_svm.h     |  18 ++++
  3 files changed, 152 insertions(+), 17 deletions(-)

diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c
index 1eb92ac6eb05..5ead98a604b1 100644
--- a/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c
+++ b/drivers/gpu/drm/amd/amdkfd/kfd_migrate.c
@@ -218,17 +218,45 @@ svm_migrate_addr_to_pfn(struct amdgpu_device *adev, unsigned long addr)
      return (addr + adev->kfd.pgmap.range.start) >> PAGE_SHIFT;
  }
  +/*
+ * TTM can reuse a 2MB VRAM block that was previously a device THP.
+ * Reset unused pages so the next 4K init does not see leftover head/tail.
+ */
+static void svm_migrate_clear_compound_pages(struct page *page, unsigned int nr,
+                          struct dev_pagemap *pgmap)
+{
+    unsigned int i;
+
+    for (i = 0; i < nr; i++, page++) {
+        struct folio *new_folio = (struct folio *)page;
+
+        if (page_count(page))
+            continue;
+
+        page->flags.f &= ~0xffUL;
+#ifdef NR_PAGES_IN_LARGE_FOLIO
+        ((struct folio *)(page - 1))->_nr_pages = 0;
+#endif
+        new_folio->mapping = NULL;
+        new_folio->pgmap = pgmap;
+        new_folio->share = 0;
+        page->zone_device_data = NULL;
+    }
+}
+
This is not needed. Commit 12b2285bf3d1 ("mm/zone_device: reinitialize
large zone device private folios") already makes zone_device_page_init()
clear any leftover head/tail state when a page is handed out again.
svm_migrate_get_vram_page() calls zone_device_folio_init() for every VRAM
page it hands out, so the page is reinitialized when it is reused, as a 4K
page or as part of a new THP. There is no need to clear the compound pages
when the folio is freed.
no, it is needed. That part is easy to get confused. svm_migrate_clear_compound_pages() runs because freeing the device THP only releases the head folio. The other 511 struct pages stay linked to that head, and TTM can hand those same VRAM pages out later as ordinary 4K pages.

free_zone_device_folio() clears folio->mapping on the head and calls folio_free. It does not walk the tails. Each tail still has its compound-tail marker, so page_folio() follows it back to the old head, and page_pgmap() is implemented as page_folio(page)->pgmap. The tail's own pgmap slot held the head pointer, not the dev_pagemap. 

The only reason the stale tail matters is that
svm_migrate_get_vram_page() calls page_pgmap(). The pgmap is a single
per-device structure, adev->kfd.pgmap, covering the whole VRAM, so we can
pass it in directly and avoid page_pgmap() altogether:

svm_migrate_copy_to_vram()
{
+    struct dev_pagemap *pgmap = &adev->kfd.pgmap;
...
-            svm_migrate_get_vram_page(prange, dst_pfn, order);
+            svm_migrate_get_vram_page(prange, dst_pfn, order, pgmap);

zone_device_folio_init() then resets every page it hands out, a former
tail included, without following the old head. With that,
svm_migrate_clear_compound_pages() can be removed. It also open-codes
writes to internal folio fields, which I would rather not have in the
driver.


Look at folio definition: pgmap and compound_info are the same word. A tail page has bit 0 set there, so page_folio() follows it to the old head, and page_pgmap() is page_folio(page)->pgmap. Writing the dev_pagemap pointer clears that bit. After that, page_folio() returns the page itself and page_pgmap() reads the pointer just stored. The next zone_device_folio_init() does this again for the one page it is given, but a former tail can be initialized after the old head has already been reused. Without new_folio->pgmap = pgmap at free time, page_pgmap() on that tail still follows the live head.

And page->flags.f &= ~0xffUL is required too. PG_head is in the head page's flags, and the folio order is in the low byte of the second page's flags (folio->_flags_1). The next init clears those bits only on the page it receives. Until the head itself is allocated again, folio_test_large() on it is still true.

svm_migrate_clear_compound_pages walks every page of the freed folio, drops the head/tail flag bits and _nr_pages, and stores the real pgmap on each page. After that, each page is a standalone zone-device page and the next order-0 init does not follow the old THP.

Another reason to have svm_migrate_clear_compound_pages: after kfd driver publishes device pages to core MM. These pages are under core MM management. So, not only kfd driver use them, other components can use them too. At the time device pages got released by HMM to kfd driver, before kfd driver reuse them these pages or folios need be in clean state. So, re-users(not only kfd driver) can use them without worrying their stale states.

svm_migrate_clear_compound_pages  does mimic  zone_device_folio_init, but it is on purpose.

  static void
-svm_migrate_get_vram_page(struct svm_range *prange, unsigned long pfn)
+svm_migrate_get_vram_page(struct svm_range *prange, unsigned long pfn,
+               int order) 
+ int order, struct dev_pagemap *pgmap)
  {
-    struct page *page;
+    struct page *page = pfn_to_page(pfn);
  -    page = pfn_to_page(pfn);
-    svm_range_bo_ref(prange->svm_bo);
+    /* Init this pfn, not page_folio() — that follows a leftover tail to the old head. */
+    zone_device_folio_init((struct folio *)page, page_pgmap(page), order); 
+       zone_device_folio_init((struct folio *)page, pgmap, order);
      page->zone_device_data = prange->svm_bo;
Please use folio_set_zone_device_data(page_folio(page), prange->svm_bo).
The result is the same, since page is always the head page here, but it
adds a sanity check and matches how other drivers do it.
I also have a version for coherent device THP support. folio_set_zone_device_data only allows private device memory because  currently only AMD supports coherent device memory. It is why I set page->zone_device_data directly here. It does not affect anything but will apply to coherent case. 

Agreed, folio_set_zone_device_data() warns on any page that is not
device-private. Please add a comment to make that clear:

    /* Not folio_set_zone_device_data(): it warns on device-coherent pages. */
    page->zone_device_data = prange->svm_bo; 

Once a device folio is freed, nothing in core mm hands its pages out again. They only come back into use through svm_migrate_get_vram_page(), so no other code path sees the stale state.

Regards,
Philip
-    zone_device_page_init(page, page_pgmap(page), 0);
+    svm_range_bo_ref(prange->svm_bo);
  }
  +
  static void
  svm_migrate_put_vram_page(struct amdgpu_device *adev, unsigned long addr)
  {
@@ -249,11 +277,45 @@ svm_migrate_addr(struct amdgpu_device *adev, struct page *page)
  }
    static struct page *
-svm_migrate_get_sys_page(struct vm_area_struct *vma, unsigned long addr)
+svm_migrate_get_sys_page(struct vm_area_struct *vma, unsigned long addr,
+              unsigned long order)
  {
      struct page *page;
  -    page = alloc_page_vma(GFP_HIGHUSER, vma, addr);
+    if (order) {
+#ifdef CONFIG_TRANSPARENT_HUGEPAGE
The caller only passes order > 0 on the THP compound page path, so this
#ifdef is not needed.
It is defensive. if migrate->src[i] & MIGRATE_PFN_COMPOUND is true, CONFIG_TRANSPARENT_HUGEPAGE  should have been defined by user on kernel setting and hardware support THP. If HMM provides MIGRATE_PFN_COMPOUND folio, but kernel does not enable THP or hardware does not support THP driver return null for such request.
+        struct folio *folio;
+        gfp_t gfp;
+
+        /*
+         * Honour MADV_NOHUGEPAGE and prctl(PR_SET_THP_DISABLE). The
+         * sysfs THP policy (thp_vma_allowable_orders()) and
+         * vma_thp_gfp_mask() are not exported to modules.
+         */
+        if (vma_thp_disabled(vma, vma->vm_flags, false))
+            return NULL;
+
+        /*
+         * Used by every VRAM to RAM migration (CPU/GPU fault,
+         * prefetch, TTM eviction), and the caller falls back to 4K
+         * pages on failure. Fail fast like the default "madvise"
+         * defrag policy: no direct reclaim or compaction unless the
+         * VMA asked for huge pages. Eviction in particular runs under
+         * memory pressure, where compaction stalls are most costly.
+         */
+        gfp = GFP_TRANSHUGE_LIGHT;
+        if (vma->vm_flags & VM_HUGEPAGE)
+            gfp |= __GFP_DIRECT_RECLAIM;
+
I think this mixes up the madvise THP policy with THP page migration.
They are separate settings. GFP_TRANSHUGE_LIGHT/GFP_TRANSHUGE are used
internally by core mm (THP fault, khugepaged, NUMA migration), not by
drivers. For the migration destination, please use GFP_HIGHUSER, the same
flag other drivers use in their migrate-to-RAM paths.

GFP_TRANSHUGE_LIGHT is used mostly by core MM. Here we allocate THP. The idea is: not allocate sys THP when system has memory pressure. If it happens fail quickly and driver falls back to normal size page allocation by alloc_page_vma(GFP_HIGHUSER,...), there we use GFP_HIGHUSER.

The kernel comments on GFP_TRANSHUGE_LIGH:

 * %GFP_TRANSHUGE and %GFP_TRANSHUGE_LIGHT are used for THP allocations. They
 * are compound allocations that will generally fail quickly if memory is not
 * available and will not wake kswapd/kcompactd on failure. The _LIGHT
 * version does not attempt reclaim/compaction at all and is by default used
 * in page fault path, while the non-light is used by khugepaged.

If we let kernel do its best to allocate THP that may trigger kswapd/kcopactd and reclaim under memory pressure. That take much longer time to allocate, specially this sys ram allocation is also used by cpu page fault recovery and ttm eviction.

So, allocate sys THP when there is no memory pressure(no reclaim). If kernel has to do reclaim GFP_TRANSHUGE_LIGHT let kernel fail THP allocation immediately, then driver uses GFP_HIGHUSER to allocate normal size pages.  It is for better performance.


+        folio = vma_alloc_folio(gfp, order, vma, addr);
+        page = folio ? folio_page(folio, 0) : NULL;
+#else
+        return NULL;
+#endif
+    } else {
+        page = alloc_page_vma(GFP_HIGHUSER, vma, addr);
+    }
+
      if (page)
          lock_page(page);
  @@ -267,8 +329,13 @@ static unsigned long svm_migrate_successful_pages(struct migrate_vma *migrate)
        for (i = 0; i < migrate->npages; i++) {
          if (migrate->dst[i] & MIGRATE_PFN_VALID &&
-            migrate->src[i] & MIGRATE_PFN_MIGRATE)
-            mpages++;
+            migrate->src[i] & MIGRATE_PFN_MIGRATE) {
Wrong indentation change.
ok,
+
+            if (migrate->dst[i] & MIGRATE_PFN_COMPOUND)
+                mpages += SVM_HPAGE_PMD_NR;
For a compound page, the remaining dst entries are zero, so skip them:

                i += HPAGE_PMD_NR - 1;

+            else
+                mpages++;
+        }
      }
      return mpages;
  }
@@ -312,7 +379,7 @@ svm_migrate_copy_to_vram(struct kfd_node *node, struct svm_range *prange,
                  migrate->dst[i] = 0;
                  spage = NULL;
              } else {
-                svm_migrate_get_vram_page(prange, migrate->dst[i]);
+                svm_migrate_get_vram_page(prange, migrate->dst[i], 0);
                  migrate->dst[i] = migrate_pfn(migrate->dst[i]);
                  mpages++;
              }
@@ -626,10 +693,17 @@ svm_migrate_ram_to_vram(struct svm_range *prange, uint32_t best_loc,
      return r < 0 ? r : 0;
  }
  +/* folio can be compound folio or single page */
  static void svm_migrate_folio_free(struct folio *folio)
  {
      struct page *page = &folio->page;
      struct svm_range_bo *svm_bo = page->zone_device_data;
+    struct dev_pagemap *pgmap = folio->pgmap;
+    unsigned int order = folio_order(folio);
+
+    /* So TTM can reuse this VRAM as 4K pages on the next range. */
+    if (order)
+        svm_migrate_clear_compound_pages(page, 1U << order, pgmap);
As above, please remove this.
As explain above we need svm_migrate_clear_compound_pages.

      if (svm_bo) {
          pr_debug_ratelimited("ref: %d\n", kref_read(&svm_bo->kref));
@@ -688,7 +762,7 @@ svm_migrate_copy_to_ram(struct amdgpu_device *adev, struct svm_range *prange,
              j = 0;
          }
  -        dpage = svm_migrate_get_sys_page(migrate->vma, addr);
+        dpage = svm_migrate_get_sys_page(migrate->vma, addr, 0);
          if (!dpage) {
              pr_debug("failed get page svms 0x%p [0x%lx 0x%lx]\n",
                   prange->svms, prange->start, prange->last);
@@ -1091,9 +1165,25 @@ static vm_fault_t svm_migrate_to_ram(struct vm_fault *vmf)
      return r ? VM_FAULT_SIGBUS : 0;
  }
  +static void svm_migrate_folio_split(struct folio *head, struct folio *tail)
+{
+    struct svm_range_bo *svm_bo;
+
+    if (tail == NULL)
+        return;
+
+    tail->pgmap = head->pgmap;
+    tail->mapping = head->mapping;
+
+    svm_bo = folio_zone_device_data(head);
+    folio_set_zone_device_data(tail, svm_bo);
+    svm_range_bo_ref(svm_bo);
+}
+
  static const struct dev_pagemap_ops svm_migrate_pgmap_ops = {
      .folio_free        = svm_migrate_folio_free,
      .migrate_to_ram        = svm_migrate_to_ram,
+    .folio_split        = svm_migrate_folio_split,
  };
    /* Each VRAM page uses sizeof(struct page) on system memory */
diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c
index 421d3f65fcf1..35cebdad5651 100644
--- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.c
+++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.c
@@ -246,7 +246,16 @@ void svm_range_dma_unmap_dev(struct device *dev, dma_addr_t *dma_addr,
          if (!svm_is_valid_dma_mapping_addr(dev, dma_addr[i]))
              continue;
          pr_debug_ratelimited("unmap 0x%llx\n", dma_addr[i] >> PAGE_SHIFT);
-        dma_unmap_page(dev, dma_addr[i], PAGE_SIZE, dir);
+
+        /* dma unmap of THP */
+        if (dma_addr[i] & SVM_RANGE_DMA_THP) {
+            dma_addr[i] &= ~SVM_RANGE_DMA_THP;
+            dma_unmap_page(dev, dma_addr[i], PAGE_SIZE*SVM_HPAGE_PMD_NR,
+                       DMA_BIDIRECTIONAL);
Clear the entry and skip the rest of the THP here:

            dma_addr[i] = 0;
            i += HPAGE_PMD_NR - 1;

ok

Regards

Xiaogang


+        } else {
+            dma_unmap_page(dev, dma_addr[i], PAGE_SIZE, dir);
                                   dma_addr[i] = 0;
+        }
+
          dma_addr[i] = 0;
Then this line can be removed.

Regards,
Philip
      }
  }
@@ -579,10 +588,20 @@ svm_range_vram_node_new(struct kfd_node *node, struct svm_range *prange,
      }
        memset(&bp, 0, sizeof(bp));
+    /*
+     * Keep bp.size equal to the prange size so it matches the
+     * amdgpu_amdkfd_reserve_mem_limit() reservation made by the caller.
+     * A 2MB byte_align makes the VRAM manager allocate 2MB-aligned 2MB
+     * buddy blocks and trim only the last one to the requested size, so
+     * every full 2MB chunk can still back a device THP.
+     */
      bp.size = prange->npages * PAGE_SIZE;
+    if (SVM_THP_ENABLED && prange->npages >= SVM_HPAGE_PMD_NR)
+        bp.byte_align = SVM_HPAGE_PMD_SIZE;
+    else
+        bp.byte_align = PAGE_SIZE;
      bp.bo_ptr_size = sizeof(struct svm_range_bo);
      bp.destroy = svm_range_bo_destroy;
-    bp.byte_align = PAGE_SIZE;
      bp.domain = AMDGPU_GEM_DOMAIN_VRAM;
      bp.flags = AMDGPU_GEM_CREATE_NO_CPU_ACCESS;
      bp.flags |= clear ? AMDGPU_GEM_CREATE_VRAM_CLEARED : 0;
@@ -594,9 +613,16 @@ svm_range_vram_node_new(struct kfd_node *node, struct svm_range *prange,
        r = amdgpu_bo_create(node->adev, &bp, &bo);
      if (r) {
-        pr_debug("failed %d to create bo\n", r);
-        mmput(mm);
-        goto create_bo_failed;
+        if (bp.byte_align == SVM_HPAGE_PMD_SIZE) {
+            /* fall back PAGE_SIZE granularity */
+            bp.byte_align = PAGE_SIZE;
+            r = amdgpu_bo_create(node->adev, &bp, &bo);
+        }
+        if (r) {
+            pr_debug("failed %d to create bo\n", r);
+            mmput(mm);
+            goto create_bo_failed;
+        }
      }
        svm_bo = to_svm_range_bo(bo);
@@ -957,6 +983,7 @@ svm_range_copy_array(void *psrc, size_t size, uint64_t num_elements,
      *vram_pages = 0;
      for (i = 0; i < num_elements; i++) {
          dma_addr_t *temp;
+
          temp = (dma_addr_t *)dst + i;
          *temp = *((dma_addr_t *)src + i);
          if (*temp&SVM_RANGE_VRAM_DOMAIN)
@@ -1675,7 +1702,7 @@ static int svm_range_reserve_bos(struct svm_validate_context *ctx, bool intr)
      uint32_t gpuidx;
      int r;
  -    drm_exec_init(&ctx->exec, intr ? DRM_EXEC_INTERRUPTIBLE_WAIT: 0, 0);
+    drm_exec_init(&ctx->exec, intr ? DRM_EXEC_INTERRUPTIBLE_WAIT : 0, 0);
      drm_exec_until_all_locked(&ctx->exec) {
          for_each_set_bit(gpuidx, ctx->bitmap, MAX_GPU_INSTANCE) {
              pdd = kfd_process_device_from_gpuidx(ctx->process, gpuidx);
diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_svm.h b/drivers/gpu/drm/amd/amdkfd/kfd_svm.h
index 38744e716f74..8767a784e679 100644
--- a/drivers/gpu/drm/amd/amdkfd/kfd_svm.h
+++ b/drivers/gpu/drm/amd/amdkfd/kfd_svm.h
@@ -35,6 +35,24 @@
  #include "kfd_priv.h"
    #define SVM_RANGE_VRAM_DOMAIN (1UL << 0)
+#define SVM_RANGE_DMA_THP (1UL << 1)
+
+/*
+ * Size of a PMD-mapped device or system THP. HPAGE_PMD_* expand to
+ * BUILD_BUG() without CONFIG_TRANSPARENT_HUGEPAGE, so the SVM code uses
+ * these instead. Without THP, SVM_THP_ENABLED is false, no compound
+ * migration is requested, and HMM never reports MIGRATE_PFN_COMPOUND, so
+ * the THP paths still compile but are never taken.
+ */
+#ifdef CONFIG_TRANSPARENT_HUGEPAGE
+#define SVM_HPAGE_PMD_ORDER    HPAGE_PMD_ORDER
+#else
+#define SVM_HPAGE_PMD_ORDER    (PMD_SHIFT - PAGE_SHIFT)
+#endif
+#define SVM_HPAGE_PMD_NR    (1UL << SVM_HPAGE_PMD_ORDER)
+#define SVM_HPAGE_PMD_SIZE    (PAGE_SIZE << SVM_HPAGE_PMD_ORDER)
+#define SVM_THP_ENABLED IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)
+
  #define SVM_ADEV_PGMAP_OWNER(adev)\
              ((adev)->hive ? (void *)(adev)->hive : (void *)(adev))


--------------qSkJ7PS69ml64xSB9kDMKxDh--