From patchwork Thu Oct 17 20:42:35 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Lorenzo Stoakes X-Patchwork-Id: 13840800 Received: from mx0b-00069f02.pphosted.com (mx0b-00069f02.pphosted.com [205.220.177.32]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9443925779; Thu, 17 Oct 2024 20:43:23 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=205.220.177.32 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1729197805; cv=fail; b=di0JyinZM5Cb4tKkGVC2BbGm2CAhEuRaq9gnCRP1dK2BFMiZ6FQGmx3+0B2cm0KH7WpLqf4Qvmcxyrd+NtX3KBwDL6NfVF0bvb5IJ/fOkMc52v/EsXpQEmLBLIymJFiuOD4uA1B+/CepNyeEIpO2McCLkZVaFZwTSOn/NoystZY= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1729197805; c=relaxed/simple; bh=r1rIS4+tl2D1x4fXZD5fIAKB7CebxPDKwcDZdqEPq3M=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: Content-Type:MIME-Version; b=ptPP4n2ll+Uo5ACs5+N/XYuDyQAA+q7wNmWkQ8k/QbQ6y4fOPjgZBgsLd5h1xmHS6WKn/yiNWqTduAS6+HLcEx7lupG/0PFZzb1C3n7ZrcfYbM6U5YHqeOEhMt+yt16Nl8a4HycJ5Tionp6odODOAn3F0GClryzmrrX7Mj5CSMY= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=oracle.com; spf=pass smtp.mailfrom=oracle.com; dkim=pass (2048-bit key) header.d=oracle.com header.i=@oracle.com header.b=hlT25oPZ; dkim=pass (1024-bit key) header.d=oracle.onmicrosoft.com header.i=@oracle.onmicrosoft.com header.b=gzq9/D8b; arc=fail smtp.client-ip=205.220.177.32 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=oracle.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=oracle.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=oracle.com header.i=@oracle.com header.b="hlT25oPZ"; dkim=pass (1024-bit key) header.d=oracle.onmicrosoft.com header.i=@oracle.onmicrosoft.com header.b="gzq9/D8b" Received: from pps.filterd (m0246630.ppops.net [127.0.0.1]) by mx0b-00069f02.pphosted.com (8.18.1.2/8.18.1.2) with ESMTP id 49HFBvq6024561; Thu, 17 Oct 2024 20:42:50 GMT DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=oracle.com; h=cc :content-transfer-encoding:content-type:date:from:in-reply-to :message-id:mime-version:references:subject:to; s= corp-2023-11-20; bh=0XL9Kp1iOKvA/fmdS4PltUGMSZ22lYarbZRleGRG5kI=; b= hlT25oPZy1L/mjEIi8zdIfEKciZwx4k39RHCN3wyKVdiX1YyKaWLEkKZRNslnwN4 rwSDk5xO9VYPGCGb9okL3zsWcvr0WtNWfeMZTmA1PhlvN0YfrczvZFrlf7eBJeNz cHVSZ4IcIjUokwMJVty3ADEgqJ5/pXygG/uw0gCKXLjMpHOLJ53kCnSWY2rusRGz 56IY5c9KV9znXEe0G21hCBBd7/h+ZqAMAhkU7qushIV/iGziFxm5vdeTg+kUxYsm W9d5Eq7VR1J+Xh2TndlvPmg5pX2Woa7Bvs3ytkmgNuQQFwqvOq6yjwUtbYmrKgSY Kv6lTGKIugKiXLxMQg+gFQ== Received: from phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com (phxpaimrmta03.appoci.oracle.com [138.1.37.129]) by mx0b-00069f02.pphosted.com (PPS) with ESMTPS id 427fhcpyqv-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Thu, 17 Oct 2024 20:42:50 +0000 (GMT) Received: from pps.filterd (phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com [127.0.0.1]) by phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com (8.18.1.2/8.18.1.2) with ESMTP id 49HKWWwc013877; Thu, 17 Oct 2024 20:42:49 GMT Received: from nam10-mw2-obe.outbound.protection.outlook.com (mail-mw2nam10lp2042.outbound.protection.outlook.com [104.47.55.42]) by phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com (PPS) with ESMTPS id 427fjarehs-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Thu, 17 Oct 2024 20:42:49 +0000 ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=dLjNnzJ5Edc1BweFrwDNAIuIlFNTilaIK5xkWGdbHkCYszr2A0ZjjAmgaOsadrfd62cFWyXRj/jGeLIPGuBCyHT5xWTJweyUcM9ZXyKCY9YKCo8HYEDhUgnyHs9aW7i/mMwN8lN7cHmVJvvYNDTPmOp1VpoVxjZ8+ipFB9UzWW11nHdVbUlPuEVxdAw3i+KFptTWKNerBbcLkRd/qNXY3+aDSCqlNkmQI5c1hWZjbKUmTjRTcTPq1Oh4x/gfeYkcujYdaxiQa48DlWXW3m4v1Bp5c8AaQo+ZSWJpdZgxJPpneB0+WEWqSwAaupkfhqC/YaAkNow6SSvIn5ZBwRhQcA== 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=0XL9Kp1iOKvA/fmdS4PltUGMSZ22lYarbZRleGRG5kI=; b=N1BsIwOsAUvU1+RDCIPxK8GtEkdBkPyNFVDrND31tROetjqy6V/w18EzXObkvlCSHHB1MtcKL6woh7rX7eQBox8nIYxqIJjk1r5bGf6t+EfRmN4zKI9oW61YLMkhyp7YGh9c2ZZKqifN6yB7nM6rZiJVTJJEQTvNBtlMt9Oqg8D4uW/+m05gV2rOwKZnUAXa7+wBwNQb2FGo60Bea/kUwIYK79qU3irdT64nkdhAJbDBpGU+EMA+ZSEgJw8KJji7FPVO8coFq4stHqyjVEI6zvu1LeJAXLV6wjvXLcx8nE3LVD28PGcE29lLPYZHSo3FTIz1kug7ojhnCdKMZ/YiSg== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=oracle.com; dmarc=pass action=none header.from=oracle.com; dkim=pass header.d=oracle.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=oracle.onmicrosoft.com; s=selector2-oracle-onmicrosoft-com; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=0XL9Kp1iOKvA/fmdS4PltUGMSZ22lYarbZRleGRG5kI=; b=gzq9/D8bv/W6o7Qp8Y/kllE+/dSDIUl9plZXwBN5GbnrBuy7IXAp7D+2Pkc2jXss46YioWYh5whe6YnGssOBEEdhu1117+uHGQqkW7o6+jSBr6uTeuV2HpHuhq2vhhA0qoe6sBz5tWl2HWX6YJ97wjUEeV0bEoUYaBaO8gecJEo= Received: from SJ0PR10MB5613.namprd10.prod.outlook.com (2603:10b6:a03:3d0::5) by DS7PR10MB5974.namprd10.prod.outlook.com (2603:10b6:8:9e::10) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.8069.18; Thu, 17 Oct 2024 20:42:46 +0000 Received: from SJ0PR10MB5613.namprd10.prod.outlook.com ([fe80::4239:cf6f:9caa:940e]) by SJ0PR10MB5613.namprd10.prod.outlook.com ([fe80::4239:cf6f:9caa:940e%5]) with mapi id 15.20.8069.016; Thu, 17 Oct 2024 20:42:46 +0000 From: Lorenzo Stoakes To: Andrew Morton Cc: Suren Baghdasaryan , "Liam R . Howlett" , Matthew Wilcox , Vlastimil Babka , "Paul E . McKenney" , Jann Horn , David Hildenbrand , linux-mm@kvack.org, linux-kernel@vger.kernel.org, Muchun Song , Richard Henderson , Ivan Kokshaysky , Matt Turner , Thomas Bogendoerfer , "James E . J . Bottomley" , Helge Deller , Chris Zankel , Max Filippov , Arnd Bergmann , linux-alpha@vger.kernel.org, linux-mips@vger.kernel.org, linux-parisc@vger.kernel.org, linux-arch@vger.kernel.org, Shuah Khan , Christian Brauner , linux-kselftest@vger.kernel.org, Sidhartha Kumar , Jeff Xu , Christoph Hellwig Subject: [PATCH 1/4] mm: pagewalk: add the ability to install PTEs Date: Thu, 17 Oct 2024 21:42:35 +0100 Message-ID: <7e246193f60298f08e5ee1f1341f780e0a6a9712.1729196871.git.lorenzo.stoakes@oracle.com> X-Mailer: git-send-email 2.46.2 In-Reply-To: References: X-ClientProxiedBy: LO4P265CA0177.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:312::20) To SJ0PR10MB5613.namprd10.prod.outlook.com (2603:10b6:a03:3d0::5) Precedence: bulk X-Mailing-List: linux-parisc@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SJ0PR10MB5613:EE_|DS7PR10MB5974:EE_ X-MS-Office365-Filtering-Correlation-Id: 5df2e69f-e981-4e3e-0a82-08dceeec416b X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|7416014|376014|366016|1800799024; X-Microsoft-Antispam-Message-Info: u0qkm7rjh1tD1oa6U2YqU1iEt7u0R89TrWEorHcge2iE/TtoDSwxwYkIohRArjGlhT3Q7/3UgvsSIYDxKUTyX6jovnB2rcWhO64botoInpb+r1NQNpj1ILHXqF8LWfT4zoXludFjye2CO+bx9zPvkg+8TlPD3OZZcRcj8U2mj/b8ps20nI3V7bNodfKb2D+yFlPJK6DF77BNDNLsgFY5niMh1bdC6G1CIO5D/b1Rymb3fQS78i47Y/86WZlaOFnBu31N6FcLsFXEAQFmMZMAsAL5GdYnTyq8j4/tqzM25Q8Kf590BkRyd3KpjF6qq0TYBzbWyCsbwr43P2i9OjYc0fFcgv3Rjc1GHUsF7iWvGxYdDpGxSqvoLtk4fDtVxW1qo0BvrDw9z/2zxWtp2pKiN5Fh+d359EN27mk7Qtth9n5LZ240pBpVeyhnGppWuk8DH//7oYgtQRLAJlb/8G0g8p4UBrAF39L1kVM4EdHql2rqnIKIFDKbI5u/Y5EdaVHRO8QJhj+RGNvo//Ch6KS7gFVDfNUJf4yUrgkVx3jPfE4hDVQjjrNcxQOcWma+PuRou4d0KCFlqZvN5T3azVVv1To8qSP1EkYGj8aOb9Xx0qj7JFbvYYGhgWvPH1iWhbJVT54yZk2AR3iqfnRdErhmsM7JUCTAsnH+9ny7WjKXE9Os7HXRBp2hLtrnBSxMpMdGGCbkOGwey0CHYkhc/6YEp/kZIZ4pJBSNcGVUDBa9zptdROAhbujroBWp7bLawlvdBF7TfUDBKj7p7pLlsBpZVV2FxI33dyGDpNZfWdzcy+/RTU5iLQ7rXlOvSpbbq/7xtafs5ubpdVn585+s5tXZMNddtZZ8mm/e73TsCPSVfncSpVRG54vY+rnMnaco6RSLERY+dmSqPCJaCioX4lim2CL4xu6VOvFNBbCvThpwgCCzJyC9YRD3tl/E97RCqGmgqFQ2UbOfBQ8GY9d1gn4wbBpwmG7MJNsLkI8PezUrby0I2ub0DHQ8JO/H7iYDoelR8BhWcHyIAdeDzlXQ3PFDAO/VdQYPWT5tjQtuv/UyydKofEWhzyWzPQ8/ubNxweZ5NJOccnwIIydyi1BwVwlXF1Fg8virOmBvtaztJGL/iVyxBgVbq86GjWjUOybZQs0GDi0+AjQ02yEik4IfyXdV0mCgKM9gXVT8B48fPnwbNIbUXeRXHm2oDuJQLqEnO090PFcTsxAmj2DfpMNLMTyvRywgAQjrm9pLlA0lPWselLcII+wr/GABCGqVPXMCYiTaRLenb21EZ/Rq2czc7+5uUr4gNasdIjkb7G21qxacF64A6n9MuEQTYURvL4rFkh1Y X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SJ0PR10MB5613.namprd10.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(7416014)(376014)(366016)(1800799024);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: 64JICuhaT03EPmMftusg4jDlrxQV0bij5Q6Eht1U5446KTrW3X6qmP90uZsfc7s6gI2NzVwaP/sfzaAQ16IO2o7NE+JmtL2EnVyC6Ab/Ny9pEAGBrjlIb4vuDrSuCfaNWMfxoM5p9s/k/JjbfXqYCntQ0Z0qSnyszpQl45P7P4cBOS6guE012wlxtHwQ7j6kB/ljwTd4+h1QhdoqpfHbaagyMKOqnbSBPjJHxvXnWPptFUibkYlTBiPElKxWOE1DgrASmCQwcVkUhcethqCMeDXcQC4mCXIHrHh9AE18C+GzrydSCJKXrDHi0M5y1IpYjvmEmyzP4AClxkgD4Anb2vp0KzPWs1gEAbDpI0AlYnox4hVBHAr+Sfyfjie19lcc5BXP67HBATy6S33TNdbsKC0vyk3f0SJXc5JDdXgSdzobc26llTaM2tgCZEOBEC8mC4ZF9ApStgcxl2j/4aZHCu53EoH/Iof2McB479EbHp/dLG/Dg7DPE+FI9ZFW+wB4mRY50VkcjGPcj+fnwzjJEdGXF7O3Q4jI8W4X5N5BK9QJXu0NkQgnB3Ee+O8x5Yg5aeBECHQA+lZeXXj2gnqdJUtoh6ib/uGXbWk3LMSTWuHbte1mm4hsa2kk84Uc+LjCTEPx6/sHdBPy7nl+YcdLeYaz2kV2F1iU6rYwJbYSSyeykkXrDXnp1n9lCVTAcIg3f/n87frCkhXFROeXjUnGNyOPoq+qKwUHUgQdC/7pxbPBhMJKJz6wh0Phm7BqlUV37AhtdfKH9MGbEfJ5ldq4L8YnXvqhcNJAY+lT5ZrkR4fRliU3/eGa6tpb70Ne/ZDv0BP81As+xxuQhRZxiiIa3ML/SI1vG1f3p6eozeyS82PxxXcUOWPPLi0DCKem1wBiS9uuV+RBfrS54kgwST2EpxVoGLL+LASlwkK1InItLTZM6sFDV3F4SFWhJhI6JAdL3v69l+OzhcEEZO09riRqY9l3cp7PtFqc6vmvbaQ6CEqa3Lx54qU0oxh0VcdyPOuURL1qbahQ6JyRPjvetFdM2aWoR6kLm1QBl4x3FuK7HKcHwTxbENhyPnBsCHsXylzhvkRxdHUUpXGWCgqi44JgNSBYE3HgavhbaSWr/y8hiQTDDqaNPeBUfRDBiztoms25DMY1reqozNVkBcO4WdrJuE0R8ms7wAOOdhNm14N/Jhf4CV/Y1MMMTGLgS0/SONnZaCu8VRwqjeDOvKz01SfAeSDmhdtU0oBxHacaMAicgkUM4s9M19fymIEJHCEnAEP0lUBqyZ4QlUAqs9YWy/jyw9jmC+q20t40Ris26gpuXOgzc4/USl6ZeWB0JSeCyY8yPj/jT5m1JpXe8qmR/uMkQp0dSXJ9CJ9TF8H1athM8pg3g9DdlxL1vYKQZEj04ixpIdudj7jXwxN5nd3gYpMWhUF9kGfcVWBViIpvyxQvhrOLFKbhBzgyh8b7+o8jNSmXcJ7OXLbbd7RWLlIIrf86JxLVq76mzskN3dI0r8O0PHN4KKDQ6XukrXMPHMlBloEvG7uPLCCwt6OluOo/XfTB/e8ryZ1On8TwrLOXnCzujO53GiE0kqYZ57kPit+q5peTzs0m6IkmR7V625epKdzc3Q== X-MS-Exchange-AntiSpam-ExternalHop-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-ExternalHop-MessageData-0: WsJ35mcqrmAk/goU3TJQOeR/93rTeZeBY8Yf26epZjd7jhTT4O84s7CV9G6yxjVOJ7pu3XIhPS9E/lT1dlOhlYgrXWuAQNYG7do0NoOUANx33bZBlqnElK01taPpcEVRyCw7u90C37LKAy7cTP2yQS+WvALGpK154YRCObEzxRF7oq0p+Uumq8IpaDuXoMuDDataVP9i74LL65HlLFR3OuH5FAV/LzxjwOOG9qZ/Z1TTrgPg1GBm2MCc092DbhDyBOqt44jPRHzI5mfRdZimNkrcnhsvA/VgGU5v8ys6T2AxiBXDWVtrhZd82biVhk1He/4xE0nNcARYukDKKwcZNR27PzFxJ64VDVI73fzLnxNwnuKbuJfkDfUPViIg2qwZix7i7hq4052+H720DDwnYFE4okgeB+CHNWKbihnKJvx8x5cdVJkrjFhxzAMX978jRC9dPSJKUbUHhp5b5e6nlhGe4h7QmkYpQY6fE04zAwJUnT+HIFySXTxiToKktQ1khTidlBQhIAhbjO/KTCJA4XeXci8jvw7FdIHJ6oZeYMRqSunv51hwFvljupiYVydtROPOftTak962bPrP7fFf+VdTdIb/qkByWfcfCEfBJVs= X-OriginatorOrg: oracle.com X-MS-Exchange-CrossTenant-Network-Message-Id: 5df2e69f-e981-4e3e-0a82-08dceeec416b X-MS-Exchange-CrossTenant-AuthSource: SJ0PR10MB5613.namprd10.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 17 Oct 2024 20:42:46.0080 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 4e2c6054-71cb-48f1-bd6c-3a9705aca71b X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: P5Su4uE3LK4b3WVzqktJH31/s43FHK+fhCowwBEDzFiJRGbcwo7UeB2Cp0IDLQdDK8qJYp7wOgTbYVJ++ric4NQjEawhOCit8E11+vzVf3Q= X-MS-Exchange-Transport-CrossTenantHeadersStamped: DS7PR10MB5974 X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.293,Aquarius:18.0.1051,Hydra:6.0.680,FMLib:17.12.62.30 definitions=2024-10-17_23,2024-10-17_01,2024-09-30_01 X-Proofpoint-Spam-Details: rule=notspam policy=default score=0 malwarescore=0 phishscore=0 mlxscore=0 mlxlogscore=999 bulkscore=0 spamscore=0 suspectscore=0 adultscore=0 classifier=spam adjust=0 reason=mlx scancount=1 engine=8.12.0-2409260000 definitions=main-2410170139 X-Proofpoint-GUID: zvMkzT1Kk4r1NblzgsNfPkHZ0S4crHuO X-Proofpoint-ORIG-GUID: zvMkzT1Kk4r1NblzgsNfPkHZ0S4crHuO The existing generic pagewalk logic permits the walking of page tables, invoking callbacks at individual page table levels via user-provided mm_walk_ops callbacks. This is useful for traversing existing page table entries, but precludes the ability to establish new ones. Existing mechanism for performing a walk which also installs page table entries if necessary are heavily duplicated throughout the kernel, each with semantic differences from one another and largely unavailable for use elsewhere. Rather than add yet another implementation, we extend the generic pagewalk logic to enable the installation of page table entries by adding a new install_pte() callback in mm_walk_ops. If this is specified, then upon encountering a missing page table entry, we allocate and install a new one and continue the traversal. If a THP huge page is encountered, we make use of existing logic to split it. Then once we reach the PTE level, we invoke the install_pte() callback which provides a PTE entry to install. We do not support hugetlb at this stage. If this function returns an error, or an allocation fails during the operation, we abort the operation altogether. It is up to the caller to deal appropriately with partially populated page table ranges. If install_pte() is defined, the semantics of pte_entry() change - this callback is then only invoked if the entry already exists. This is a useful property, as it allows a caller to handle existing PTEs while installing new ones where necessary in the specified range. If install_pte() is not defined, then there is no functional difference to this patch, so all existing logic will work precisely as it did before. As we only permit the installation of PTEs where a mapping does not already exist there is no need for TLB management, however we do invoke update_mmu_cache() for architectures which require manual maintenance of mappings for other CPUs. We explicitly do not allow the existing page walk API to expose this feature as it is dangerous and intended for internal mm use only. Therefore we provide a new walk_page_range_mm() function exposed only to mm/internal.h. Reviewed-by: Jann Horn Signed-off-by: Lorenzo Stoakes --- include/linux/pagewalk.h | 18 +++- mm/internal.h | 6 ++ mm/pagewalk.c | 200 ++++++++++++++++++++++++++++----------- 3 files changed, 165 insertions(+), 59 deletions(-) diff --git a/include/linux/pagewalk.h b/include/linux/pagewalk.h index f5eb5a32aeed..9700a29f8afb 100644 --- a/include/linux/pagewalk.h +++ b/include/linux/pagewalk.h @@ -25,12 +25,15 @@ enum page_walk_lock { * this handler is required to be able to handle * pmd_trans_huge() pmds. They may simply choose to * split_huge_page() instead of handling it explicitly. - * @pte_entry: if set, called for each PTE (lowest-level) entry, - * including empty ones + * @pte_entry: if set, called for each PTE (lowest-level) entry + * including empty ones, except if @install_pte is set. + * If @install_pte is set, @pte_entry is called only for + * existing PTEs. * @pte_hole: if set, called for each hole at all levels, * depth is -1 if not known, 0:PGD, 1:P4D, 2:PUD, 3:PMD. * Any folded depths (where PTRS_PER_P?D is equal to 1) - * are skipped. + * are skipped. If @install_pte is specified, this will + * not trigger for any populated ranges. * @hugetlb_entry: if set, called for each hugetlb entry. This hook * function is called with the vma lock held, in order to * protect against a concurrent freeing of the pte_t* or @@ -51,6 +54,13 @@ enum page_walk_lock { * @pre_vma: if set, called before starting walk on a non-null vma. * @post_vma: if set, called after a walk on a non-null vma, provided * that @pre_vma and the vma walk succeeded. + * @install_pte: if set, missing page table entries are installed and + * thus all levels are always walked in the specified + * range. This callback is then invoked at the PTE level + * (having split any THP pages prior), providing the PTE to + * install. If allocations fail, the walk is aborted. This + * operation is only available for userland memory. Not + * usable for hugetlb ranges. * * p?d_entry callbacks are called even if those levels are folded on a * particular architecture/configuration. @@ -76,6 +86,8 @@ struct mm_walk_ops { int (*pre_vma)(unsigned long start, unsigned long end, struct mm_walk *walk); void (*post_vma)(struct mm_walk *walk); + int (*install_pte)(unsigned long addr, unsigned long next, + pte_t *ptep, struct mm_walk *walk); enum page_walk_lock walk_lock; }; diff --git a/mm/internal.h b/mm/internal.h index 508f7802dd2b..fb1fb0c984e4 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -1451,4 +1452,9 @@ static inline void accept_page(struct page *page) } #endif /* CONFIG_UNACCEPTED_MEMORY */ +/* pagewalk.c */ +int walk_page_range_mm(struct mm_struct *mm, unsigned long start, + unsigned long end, const struct mm_walk_ops *ops, + void *private); + #endif /* __MM_INTERNAL_H */ diff --git a/mm/pagewalk.c b/mm/pagewalk.c index 5f9f01532e67..261cd5f2de38 100644 --- a/mm/pagewalk.c +++ b/mm/pagewalk.c @@ -3,9 +3,14 @@ #include #include #include +#include #include #include +#include + +#include "internal.h" + /* * We want to know the real level where a entry is located ignoring any * folding of levels which may be happening. For example if p4d is folded then @@ -29,9 +34,23 @@ static int walk_pte_range_inner(pte_t *pte, unsigned long addr, int err = 0; for (;;) { - err = ops->pte_entry(pte, addr, addr + PAGE_SIZE, walk); - if (err) - break; + if (ops->install_pte && pte_none(ptep_get(pte))) { + pte_t new_pte; + + err = ops->install_pte(addr, addr + PAGE_SIZE, &new_pte, + walk); + if (err) + break; + + set_pte_at(walk->mm, addr, pte, new_pte); + /* Non-present before, so for arches that need it. */ + if (!WARN_ON_ONCE(walk->no_vma)) + update_mmu_cache(walk->vma, addr, pte); + } else { + err = ops->pte_entry(pte, addr, addr + PAGE_SIZE, walk); + if (err) + break; + } if (addr >= end - PAGE_SIZE) break; addr += PAGE_SIZE; @@ -89,11 +108,14 @@ static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end, again: next = pmd_addr_end(addr, end); if (pmd_none(*pmd)) { - if (ops->pte_hole) + if (ops->install_pte) + err = __pte_alloc(walk->mm, pmd); + else if (ops->pte_hole) err = ops->pte_hole(addr, next, depth, walk); if (err) break; - continue; + if (!ops->install_pte) + continue; } walk->action = ACTION_SUBTREE; @@ -116,7 +138,7 @@ static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end, */ if ((!walk->vma && (pmd_leaf(*pmd) || !pmd_present(*pmd))) || walk->action == ACTION_CONTINUE || - !(ops->pte_entry)) + !(ops->pte_entry || ops->install_pte)) continue; if (walk->vma) @@ -148,11 +170,14 @@ static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end, again: next = pud_addr_end(addr, end); if (pud_none(*pud)) { - if (ops->pte_hole) + if (ops->install_pte) + err = __pmd_alloc(walk->mm, pud, addr); + else if (ops->pte_hole) err = ops->pte_hole(addr, next, depth, walk); if (err) break; - continue; + if (!ops->install_pte) + continue; } walk->action = ACTION_SUBTREE; @@ -167,7 +192,7 @@ static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end, if ((!walk->vma && (pud_leaf(*pud) || !pud_present(*pud))) || walk->action == ACTION_CONTINUE || - !(ops->pmd_entry || ops->pte_entry)) + !(ops->pmd_entry || ops->pte_entry || ops->install_pte)) continue; if (walk->vma) @@ -196,18 +221,22 @@ static int walk_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end, do { next = p4d_addr_end(addr, end); if (p4d_none_or_clear_bad(p4d)) { - if (ops->pte_hole) + if (ops->install_pte) + err = __pud_alloc(walk->mm, p4d, addr); + else if (ops->pte_hole) err = ops->pte_hole(addr, next, depth, walk); if (err) break; - continue; + if (!ops->install_pte) + continue; } if (ops->p4d_entry) { err = ops->p4d_entry(p4d, addr, next, walk); if (err) break; } - if (ops->pud_entry || ops->pmd_entry || ops->pte_entry) + if (ops->pud_entry || ops->pmd_entry || ops->pte_entry || + ops->install_pte) err = walk_pud_range(p4d, addr, next, walk); if (err) break; @@ -231,18 +260,22 @@ static int walk_pgd_range(unsigned long addr, unsigned long end, do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(pgd)) { - if (ops->pte_hole) + if (ops->install_pte) + err = __p4d_alloc(walk->mm, pgd, addr); + else if (ops->pte_hole) err = ops->pte_hole(addr, next, 0, walk); if (err) break; - continue; + if (!ops->install_pte) + continue; } if (ops->pgd_entry) { err = ops->pgd_entry(pgd, addr, next, walk); if (err) break; } - if (ops->p4d_entry || ops->pud_entry || ops->pmd_entry || ops->pte_entry) + if (ops->p4d_entry || ops->pud_entry || ops->pmd_entry || + ops->pte_entry || ops->install_pte) err = walk_p4d_range(pgd, addr, next, walk); if (err) break; @@ -334,6 +367,11 @@ static int __walk_page_range(unsigned long start, unsigned long end, int err = 0; struct vm_area_struct *vma = walk->vma; const struct mm_walk_ops *ops = walk->ops; + bool is_hugetlb = is_vm_hugetlb_page(vma); + + /* We do not support hugetlb PTE installation. */ + if (ops->install_pte && is_hugetlb) + return -EINVAL; if (ops->pre_vma) { err = ops->pre_vma(start, end, walk); @@ -341,7 +379,7 @@ static int __walk_page_range(unsigned long start, unsigned long end, return err; } - if (is_vm_hugetlb_page(vma)) { + if (is_hugetlb) { if (ops->hugetlb_entry) err = walk_hugetlb_range(start, end, walk); } else @@ -380,47 +418,14 @@ static inline void process_vma_walk_lock(struct vm_area_struct *vma, #endif } -/** - * walk_page_range - walk page table with caller specific callbacks - * @mm: mm_struct representing the target process of page table walk - * @start: start address of the virtual address range - * @end: end address of the virtual address range - * @ops: operation to call during the walk - * @private: private data for callbacks' usage - * - * Recursively walk the page table tree of the process represented by @mm - * within the virtual address range [@start, @end). During walking, we can do - * some caller-specific works for each entry, by setting up pmd_entry(), - * pte_entry(), and/or hugetlb_entry(). If you don't set up for some of these - * callbacks, the associated entries/pages are just ignored. - * The return values of these callbacks are commonly defined like below: - * - * - 0 : succeeded to handle the current entry, and if you don't reach the - * end address yet, continue to walk. - * - >0 : succeeded to handle the current entry, and return to the caller - * with caller specific value. - * - <0 : failed to handle the current entry, and return to the caller - * with error code. - * - * Before starting to walk page table, some callers want to check whether - * they really want to walk over the current vma, typically by checking - * its vm_flags. walk_page_test() and @ops->test_walk() are used for this - * purpose. - * - * If operations need to be staged before and committed after a vma is walked, - * there are two callbacks, pre_vma() and post_vma(). Note that post_vma(), - * since it is intended to handle commit-type operations, can't return any - * errors. - * - * struct mm_walk keeps current values of some common data like vma and pmd, - * which are useful for the access from callbacks. If you want to pass some - * caller-specific data to callbacks, @private should be helpful. +/* + * See the comment for walk_page_range(), this performs the heavy lifting of the + * operation, only sets no restrictions on how the walk proceeds. * - * Locking: - * Callers of walk_page_range() and walk_page_vma() should hold @mm->mmap_lock, - * because these function traverse vma list and/or access to vma's data. + * We usually restrict the ability to install PTEs, but this functionality is + * available to internal memory management code and provided in mm/internal.h. */ -int walk_page_range(struct mm_struct *mm, unsigned long start, +int walk_page_range_mm(struct mm_struct *mm, unsigned long start, unsigned long end, const struct mm_walk_ops *ops, void *private) { @@ -479,6 +484,80 @@ int walk_page_range(struct mm_struct *mm, unsigned long start, return err; } +/* + * Determine if the walk operations specified are permitted to be used for a + * page table walk. + * + * This check is performed on all functions which are parameterised by walk + * operations and exposed in include/linux/pagewalk.h. + * + * Internal memory management code can use the walk_page_range_mm() function to + * be able to use all page walking operations. + */ +static bool check_ops_valid(const struct mm_walk_ops *ops) +{ + /* + * The installation of PTEs is solely under the control of memory + * management logic and subject to many subtle locking, security and + * cache considerations so we cannot permit other users to do so, and + * certainly not for exported symbols. + */ + if (ops->install_pte) + return false; + + return true; +} + +/** + * walk_page_range - walk page table with caller specific callbacks + * @mm: mm_struct representing the target process of page table walk + * @start: start address of the virtual address range + * @end: end address of the virtual address range + * @ops: operation to call during the walk + * @private: private data for callbacks' usage + * + * Recursively walk the page table tree of the process represented by @mm + * within the virtual address range [@start, @end). During walking, we can do + * some caller-specific works for each entry, by setting up pmd_entry(), + * pte_entry(), and/or hugetlb_entry(). If you don't set up for some of these + * callbacks, the associated entries/pages are just ignored. + * The return values of these callbacks are commonly defined like below: + * + * - 0 : succeeded to handle the current entry, and if you don't reach the + * end address yet, continue to walk. + * - >0 : succeeded to handle the current entry, and return to the caller + * with caller specific value. + * - <0 : failed to handle the current entry, and return to the caller + * with error code. + * + * Before starting to walk page table, some callers want to check whether + * they really want to walk over the current vma, typically by checking + * its vm_flags. walk_page_test() and @ops->test_walk() are used for this + * purpose. + * + * If operations need to be staged before and committed after a vma is walked, + * there are two callbacks, pre_vma() and post_vma(). Note that post_vma(), + * since it is intended to handle commit-type operations, can't return any + * errors. + * + * struct mm_walk keeps current values of some common data like vma and pmd, + * which are useful for the access from callbacks. If you want to pass some + * caller-specific data to callbacks, @private should be helpful. + * + * Locking: + * Callers of walk_page_range() and walk_page_vma() should hold @mm->mmap_lock, + * because these function traverse vma list and/or access to vma's data. + */ +int walk_page_range(struct mm_struct *mm, unsigned long start, + unsigned long end, const struct mm_walk_ops *ops, + void *private) +{ + if (!check_ops_valid(ops)) + return -EINVAL; + + return walk_page_range_mm(mm, start, end, ops, private); +} + /** * walk_page_range_novma - walk a range of pagetables not backed by a vma * @mm: mm_struct representing the target process of page table walk @@ -494,7 +573,7 @@ int walk_page_range(struct mm_struct *mm, unsigned long start, * walking the kernel pages tables or page tables for firmware. * * Note: Be careful to walk the kernel pages tables, the caller may be need to - * take other effective approache (mmap lock may be insufficient) to prevent + * take other effective approaches (mmap lock may be insufficient) to prevent * the intermediate kernel page tables belonging to the specified address range * from being freed (e.g. memory hot-remove). */ @@ -513,6 +592,8 @@ int walk_page_range_novma(struct mm_struct *mm, unsigned long start, if (start >= end || !walk.mm) return -EINVAL; + if (!check_ops_valid(ops)) + return -EINVAL; /* * 1) For walking the user virtual address space: @@ -556,6 +637,8 @@ int walk_page_range_vma(struct vm_area_struct *vma, unsigned long start, return -EINVAL; if (start < vma->vm_start || end > vma->vm_end) return -EINVAL; + if (!check_ops_valid(ops)) + return -EINVAL; process_mm_walk_lock(walk.mm, ops->walk_lock); process_vma_walk_lock(vma, ops->walk_lock); @@ -574,6 +657,8 @@ int walk_page_vma(struct vm_area_struct *vma, const struct mm_walk_ops *ops, if (!walk.mm) return -EINVAL; + if (!check_ops_valid(ops)) + return -EINVAL; process_mm_walk_lock(walk.mm, ops->walk_lock); process_vma_walk_lock(vma, ops->walk_lock); @@ -623,6 +708,9 @@ int walk_page_mapping(struct address_space *mapping, pgoff_t first_index, unsigned long start_addr, end_addr; int err = 0; + if (!check_ops_valid(ops)) + return -EINVAL; + lockdep_assert_held(&mapping->i_mmap_rwsem); vma_interval_tree_foreach(vma, &mapping->i_mmap, first_index, first_index + nr - 1) { From patchwork Thu Oct 17 20:42:36 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Lorenzo Stoakes X-Patchwork-Id: 13840804 Received: from mx0a-00069f02.pphosted.com (mx0a-00069f02.pphosted.com [205.220.165.32]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 55B01229134; Thu, 17 Oct 2024 20:43:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=205.220.165.32 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1729197814; cv=fail; b=EGrYLFhgdxGvQqgGjD0oTge6tWavxDDDDYqCNKeqT4rea4pQBQgWxYgaXS5HFwDjH5MO4GccMAfo38XmbqcvNOW6W+kq13dt7SpKVHLfXfwOdQmMtPJYi4jTqOvSsOXgwIFnMdVwmOuW6Qxb3jAoUtLWDMSD4cTV3gmaUCpUPwk= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1729197814; c=relaxed/simple; bh=weJnfCo8iCo0onxne+DIwlybazXwHadMOFndAz3D9YI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: Content-Type:MIME-Version; b=kuSNrWtA6c2YaapoozKBhR4kIf5BILpKXIYjIfiP18v5vk8xHApQ+yyVHqJih2x3/jyqwPr+4HbtR/9awTKibecdY60KvQZoQ+EGiF/ls6v/dBhluehoUAHOyEKGU+I4xQDuN2YtqPFPfOCYvXh1x/JgGoerpYkGI+LN+YUlUII= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=oracle.com; spf=pass smtp.mailfrom=oracle.com; dkim=pass (2048-bit key) header.d=oracle.com header.i=@oracle.com header.b=TNfhDw5c; dkim=pass (1024-bit key) header.d=oracle.onmicrosoft.com header.i=@oracle.onmicrosoft.com header.b=kzExMkDu; arc=fail smtp.client-ip=205.220.165.32 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=oracle.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=oracle.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=oracle.com header.i=@oracle.com header.b="TNfhDw5c"; dkim=pass (1024-bit key) header.d=oracle.onmicrosoft.com header.i=@oracle.onmicrosoft.com header.b="kzExMkDu" Received: from pps.filterd (m0246629.ppops.net [127.0.0.1]) by mx0b-00069f02.pphosted.com (8.18.1.2/8.18.1.2) with ESMTP id 49HFBems000334; Thu, 17 Oct 2024 20:42:54 GMT DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=oracle.com; h=cc :content-transfer-encoding:content-type:date:from:in-reply-to :message-id:mime-version:references:subject:to; s= corp-2023-11-20; bh=5MFnXUdslOqsT6J/eW5S/+20CDpOLupPW1WBkk3fQsA=; b= TNfhDw5cHMWroI1NEZSqe24Rb+N7pcAwxDBrd10Ys7LMV934viVlH7PVByvwxWRu BX5B+DKCTwY9PAyJPUqPQtKATXU7+bwdPNABYPyTiTK2QAn3BpIgZvFtGLw/2SLB DCnvUYqffZBF3q5QPjvWu8jowop9Hc08BzvjMmWRV7yAr8mAySf0/ZhhC8IDL+gV Mk2q4nMDuFZTVMWuBys0BtvrFiLUOoMoEnDMwwZvRPu0XvP6eiP5+NjqjCOiVYFu Je76HbaQ4BNtfKdGvWNOPPkRycUaWWxERkBLIj7pH1qOt7/UEhdaHCFh9OX7uXse TUY6q3yBqlVJ8HSfKQP/OQ== Received: from phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com (phxpaimrmta03.appoci.oracle.com [138.1.37.129]) by mx0b-00069f02.pphosted.com (PPS) with ESMTPS id 427h09ptq7-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Thu, 17 Oct 2024 20:42:53 +0000 (GMT) Received: from pps.filterd (phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com [127.0.0.1]) by phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com (8.18.1.2/8.18.1.2) with ESMTP id 49HJNIiF013980; Thu, 17 Oct 2024 20:42:53 GMT Received: from nam12-mw2-obe.outbound.protection.outlook.com (mail-mw2nam12lp2041.outbound.protection.outlook.com [104.47.66.41]) by phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com (PPS) with ESMTPS id 427fjarenb-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Thu, 17 Oct 2024 20:42:53 +0000 ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=V2bXZKytxnfXrluUFupx8e3HwlZ10KzhSSqjU5X1kjyFQISKyxYaJ+qnJOoXIHP962TQqPFixvTfsbGItQJ5WxjR62otbv0+5X8qgz3iaGZR0ukhEhf80iC4moNJFcQ2BW3E3eNz5tRfG6+K2GcBgO+H1jwKG5Zzq+JL5qf78zw7QUMnMPaUR/EuSrIosukXWgp1+uqG/rputxHpfdneo2YVnkh42V8g447Iazq/gLLYOcd7R3EEEY9AHhrPkwkrB6GypwCbsvqdYGPJb4BMT/Rddvm2shSu7Ilo0XNsaepCJCE7/5INmh5syG6QUGscYTg0JSnxPkY+yIEYEtWz1g== 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=5MFnXUdslOqsT6J/eW5S/+20CDpOLupPW1WBkk3fQsA=; b=TRVokPCeZ6Y2uiCRlqPb+YAyH8F+sGQz2VnxS7GX6q/jMlLTDvsiHmPUwpXXyxk1eKYnOaWJykHcmyBsFX3VduigzTJndQ9aKr8EtTu7LNLA/DVXnz1PJ6A/1Dg0PhIKWtAKVx2d0o4ToAjiQwQAuTJIIghR1GvFpm1KNvyAM+wl8kh2ksaLHESL8PKSnK3ifz1tgVuLVi8aiku1bQuNrZHdB7wQ355L2p62xlNHAIou8HJu2TDEqaEg88rud9FjkvhNB8H8a4jBWpBjvO6Cd65i4yotI3Q9ttncoReH6yic8eOL9NJAyBZJOBVFwl2RA0X05zgqHhCafaZECtpnCg== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=oracle.com; dmarc=pass action=none header.from=oracle.com; dkim=pass header.d=oracle.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=oracle.onmicrosoft.com; s=selector2-oracle-onmicrosoft-com; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=5MFnXUdslOqsT6J/eW5S/+20CDpOLupPW1WBkk3fQsA=; b=kzExMkDuoRD8CmKAXj2dX2Pg8cE9HVJayAbJxt6lPLyFOjOTO4xsbF2qZJt9p98dKDDX1jFbbRopUTQa1Np5gtY7YznNIV2RxLNQAuJjvdmRMLK+cdGi21egtQb1ookbvPXSGahlyd0q0Ch6U5Fw6X51Dw0PyRXhAjNvboerF3Y= Received: from SJ0PR10MB5613.namprd10.prod.outlook.com (2603:10b6:a03:3d0::5) by DS7PR10MB5974.namprd10.prod.outlook.com (2603:10b6:8:9e::10) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.8069.18; Thu, 17 Oct 2024 20:42:49 +0000 Received: from SJ0PR10MB5613.namprd10.prod.outlook.com ([fe80::4239:cf6f:9caa:940e]) by SJ0PR10MB5613.namprd10.prod.outlook.com ([fe80::4239:cf6f:9caa:940e%5]) with mapi id 15.20.8069.016; Thu, 17 Oct 2024 20:42:48 +0000 From: Lorenzo Stoakes To: Andrew Morton Cc: Suren Baghdasaryan , "Liam R . Howlett" , Matthew Wilcox , Vlastimil Babka , "Paul E . McKenney" , Jann Horn , David Hildenbrand , linux-mm@kvack.org, linux-kernel@vger.kernel.org, Muchun Song , Richard Henderson , Ivan Kokshaysky , Matt Turner , Thomas Bogendoerfer , "James E . J . Bottomley" , Helge Deller , Chris Zankel , Max Filippov , Arnd Bergmann , linux-alpha@vger.kernel.org, linux-mips@vger.kernel.org, linux-parisc@vger.kernel.org, linux-arch@vger.kernel.org, Shuah Khan , Christian Brauner , linux-kselftest@vger.kernel.org, Sidhartha Kumar , Jeff Xu , Christoph Hellwig Subject: [PATCH 2/4] mm: add PTE_MARKER_GUARD PTE marker Date: Thu, 17 Oct 2024 21:42:36 +0100 Message-ID: <4dcba8f8e3b6624c45eedc96345395002b052126.1729196871.git.lorenzo.stoakes@oracle.com> X-Mailer: git-send-email 2.46.2 In-Reply-To: References: X-ClientProxiedBy: LO2P265CA0424.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:a0::28) To SJ0PR10MB5613.namprd10.prod.outlook.com (2603:10b6:a03:3d0::5) Precedence: bulk X-Mailing-List: linux-parisc@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SJ0PR10MB5613:EE_|DS7PR10MB5974:EE_ X-MS-Office365-Filtering-Correlation-Id: 6e92e92c-56cf-4de2-1032-08dceeec432f X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|7416014|376014|366016|1800799024; X-Microsoft-Antispam-Message-Info: 2z4ynNtYO50I4pb5/7AUa9GP0zEXrlNhCrOe1mA/8lu9ih6Uu1vW+faL0E5VQWJeZuHmRmkvo5/BeVMFI0kG8z+QpCNeNBJYNLmxkhXliz0pTapywJjSUGGmbekoN1/FO0YaMsgWV0i49HsT9uIMRg04hpRAgjU8TczBffWPqrWA17aZxQB5E1YbPWJnPTaoxaLos8AETAnIUB/iBqbOo2ltuzXq6+n+3L3pQ+lJX1T847kdFNXFb9yXBOcncTc8G7KIDNry3caETRAqfqitnQIsOqmkbxmFKpF7U3d47TVfRKuiWMuFZSGLDZ4nr3oBhfic5LA7wjHSEPrgxA9Nk4t4co+zDY0Oi1oKOu5ZZ3gy+XsaORrkohOVhj5Rvf/G/C4JNp1nOktYretwLS4/7X49VsrEFF3mREI1JL82J2pLTwnaMCWpkTB/FWa42IHckcujiWS8bakTTi0uEviLDahCp1J9ysP0jdZjXTvlaQIjEUQhH1KLiR68W+AeBo1kfIkaA8iCHck382zyg/JX9wpwDR8fToGNyv2gK+6sEz3BOC0alsWZSwFs1/msDjW8z/MOcCJgteLKUjXzaDNAXE790yHPMx5Rlm7JdAfWIxTm8+9QKO5iNSQCDv6FcuV++FL4br1vhdMMUHS9kSXGmvROVx7+/AzksGNtHtjz9cGAj9LNy/E7dXFuM4NAaHhZbCcNMtVoADkgvSwWSKA+CqXqHvmHDKhMgOm/XZYgAgP3HDLtxY75zRs1BQiwzHMGKzDN9WWrVc//efGioxOidaG7k7cGVjGaPkFJp9bQPOYi4pm0LA+CfAs03jTTPj6icV4xXqDL3UK9e8PWmJB9BfNr+OUGMK+COxi0ukei1BsPLE4k632y2ZgXCUFhWLXlmPFWaOCDUggWftiSj5oRuGH1UGujfetBNdv5RpFqm6MRptwJmbHo5AeEtFByQgKjt7eo5meO8iouThF5nolKgPBMnYmvI/lUJk+IXV2weB6wwC78galBPkEHLYczv/A1NgeJduWbz8pB8QduG+pYP1CPtx9Ldd9HaDa8X5W9VEQzxruAWZHghoSJYesLAXXuEs5J8stvE7FvBnfu8dAp+rEwVdR2rG6EmRZKgGsiSylkP0cHzT7T8SLlEEZNdIqp0VSpPPv1J3IdnSnXAaY18fx1oVOjDQXmNYVzk/pzFTBMpF2ZvCBA2+cDH9JcE6d612J/TcR7yXf4gm12/lwrFogTH2MhUrP8XS52JtNfz0KjAHJ7prQEivyOGbGw+cf4HjL131hk5UPG/FwalTnWx9iBrtQBL3uXWAyHtm/bYnA= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SJ0PR10MB5613.namprd10.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(7416014)(376014)(366016)(1800799024);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: R6i2khowzCHSfqb+tBqqVLvGlAdu0wceJOwRFrytQGhyxPgtXmxWVs9r31ObHt7EoLdvS/vY9d4+Ixeueikt2b8J6qXbvqjiC7K3riJbDOY1s7VGON8PvA2TpINL97+kmsfvSziyB97/mVvR6zjozkAkm58JTfGlDX5g4otv9L5mzOqA5sbWz5vFSiXQH/2ALuGDuJ6nhVbUF9ntO7N6kF+jd6dJSPBLqvyjoDy5qO3QmdmUgLJq8PDonRRlLe/vUL09Iu4rrVeGsvvpw9DzP8PvGyPVbuL7oXMfMM8HYyevmK7Cb3ecUp2O3Oh+Bx7sPpSvOSYyIer7no83izvi2B7/UvubZwuz2S+LHwZeYgbCtLicVdtPpvsw2sk12RhSJe8ODRpyWNMCA86y3GCKmDHZqa0D9VEUJpiELsM1AjwhhxZ2OxmWGHvBvSjkIu1rBE9VW3u+WjZ3eGSkuA1EnZPjpYLKbFK5oTghVxnXYB8DMrpjAdvsWkTt+fmoNoZJZXkP+DAm8HbSR4iF4WEm3sq456NGo9lWt1J1a4DVxwA+27mG9x5MZvLnTKu4C6yXTbxxv6osvd5yx3KgIQigyVYqv8Eiw2eWcHlUmTDk/5wPVstj9guCIEC2U0M9YWbHqe1am8hTihmE9oMHUXPN94N851W6kNrFxXzi41myQopIasCZ4ooykzFQIih/xdZ8shPy204z8VQbNJQQXpHWgRY+7cPTHIvGJjX/5MWf2zGIRuSXd+Gug9tFO4OFz0Ez8Jx6SVarLsvl9tvCbJhtO5cuYNaNPAhDqY8ZfaZ7grDiuzAZvyt4KQNDvH2ipZgYz8OPKgPn3DKctgll147YeiLsw7GTNIY6e2C09dBGp0H/6HRv7WLeRfUGvN6xJ3CCuydycXI4uXN2zmeHtOOHEV5ZKV7uWEn+iS/IceGQf4Lm8mDi/9u9OZQq8aYXYolBthr1c30Dl7V20Rfli68K76xn3sQGvMy3x+frF5maElRjcZINhxruRpG7xzTWWkuwTdgTgmZTEu49o429h5EwZQJYPLAFYoICItZawocGbdzJxOe149WNUXAswumm5mq/1+quaazA2/BsYrMAEonkdL45SPsGLxzKjxgbRIDtr8SXJaECsGFfbFCuscLE8d8WlA0mxYdxWRCn8eV9aqUllEtQrByILYKmXh984cnGQ2Nr16YirpjutP3wdPA8zSCKYhr4Koxc2Dt18h8bGcemYQ4/apC8xGVrQZGz+rDjui3VC5iyTDy03ApGlN/EIi4TRTC6hqihRFoXSxx3mVPNxvWOFeA8CSQ2oJEgJxU6kZ3/dCjyh8Lxs6KYjtOyxTuzxA5gzUkEtC19QayY8gRe28rXT9x8nXYjXOw40kr2HZmRNmxEpFmETOP17kBlaXBmgifd1n+J1oGEYbkxU2cYvuKRDPDq38BPiqm46lZzy3OvocwlgfmQ/q7Jc4R3jnlLvUkKYsZhG7QSDI/mRt4NYN5kv+rFq1lMmSxeDUdwLrW5szjKXi9D9MK5Gk+Fu0pozYTx6XoFGaGskB81MmaqFw/CT9FJ5ahXMUjerf6Tpxl/s0VEKP21vtK5ueeMv6NXOcqgPPaix6r7ZPifnJZETQ== X-MS-Exchange-AntiSpam-ExternalHop-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-ExternalHop-MessageData-0: 0DLXAEGk6vW+JzF6GXJCbzKEJVG32ekdGh4nyCHA2TDh1mdd7I8Y3kFX5qT28DP4iMDI+zV0WxCplhtePzjKK4KKgnIjiGZln2i45j4yriaWojbmzXdjyFOjAD/W6rFv87uNNt9Drz51mk7jFj0qn7DDr9InOMK9QDGtZf+jyxe3UHPtBzDorEVAzeejpI9xh337Ht16D9y8CS4VjxrDML7GgC5baq4q5c0VEXC8dCCTtKsCjp+Y9cOoGpNqADjljyaRVNfEd2cISCp81C07xoX07Zr6c5HrZba+fMLnaMlwFc4Msw7Qu7D0I6UXoaacAh3VkaGEeHVJkgtfsuY9VeIE7btyCzN7EqsChA8g6fP/GO0SwIN6aKrtMs7QrS/EVuGTPiN3AuYLNvARPw+1WCpL1LFpW8YL2II883u1C82bw6GySe1HHhXOimf9bBI/rNsP3iqHPbsAvOpmwo9pwued6/RNg8K5ScQZh0yZFMEn24keG14X5fFlLaA8PDyoYAk2ofVwiEAsQv7agzdk1LDhNDvK0uKj7GenTOgkpHEbe98pRLg4seNrzXthFSOn692QUzMkbLA1KyejBG7UWkX285dncFfl+xwI1b3vd+w= X-OriginatorOrg: oracle.com X-MS-Exchange-CrossTenant-Network-Message-Id: 6e92e92c-56cf-4de2-1032-08dceeec432f X-MS-Exchange-CrossTenant-AuthSource: SJ0PR10MB5613.namprd10.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 17 Oct 2024 20:42:48.8848 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 4e2c6054-71cb-48f1-bd6c-3a9705aca71b X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: PGZoLiN38AfyZVTCXrOFoI+2nkjXh/CfnlG7LlNHXqM15YpqISWUw3lYCfYxdG0k18m/pm8fbKBr77mQ84OseJrbOhDxDBS89nG0rj27J4s= X-MS-Exchange-Transport-CrossTenantHeadersStamped: DS7PR10MB5974 X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.293,Aquarius:18.0.1051,Hydra:6.0.680,FMLib:17.12.62.30 definitions=2024-10-17_23,2024-10-17_01,2024-09-30_01 X-Proofpoint-Spam-Details: rule=notspam policy=default score=0 malwarescore=0 phishscore=0 mlxscore=0 mlxlogscore=999 bulkscore=0 spamscore=0 suspectscore=0 adultscore=0 classifier=spam adjust=0 reason=mlx scancount=1 engine=8.12.0-2409260000 definitions=main-2410170139 X-Proofpoint-GUID: YMsQOtJjLOBjYwyIJcXcyy4ZWW7gcLEO X-Proofpoint-ORIG-GUID: YMsQOtJjLOBjYwyIJcXcyy4ZWW7gcLEO Add a new PTE marker that results in any access causing the accessing process to segfault. This is preferable to PTE_MARKER_POISONED, which results in the same handling as hardware poisoned memory, and is thus undesirable for cases where we simply wish to 'soft' poison a range. This is in preparation for implementing the ability to specify guard pages at the page table level, i.e. ranges that, when accessed, should cause process termination. Additionally, rename zap_drop_file_uffd_wp() to zap_drop_markers() - the function checks the ZAP_FLAG_DROP_MARKER flag so naming it for this single purpose was simply incorrect. We then reuse the same logic to determine whether a zap should clear a guard entry - this should only be performed on teardown and never on MADV_DONTNEED or the like. Signed-off-by: Lorenzo Stoakes --- include/linux/mm_inline.h | 2 +- include/linux/swapops.h | 26 ++++++++++++++++++++++++-- mm/hugetlb.c | 3 +++ mm/memory.c | 18 +++++++++++++++--- 4 files changed, 43 insertions(+), 6 deletions(-) diff --git a/include/linux/mm_inline.h b/include/linux/mm_inline.h index 6f801c7b36e2..0d97a14bf051 100644 --- a/include/linux/mm_inline.h +++ b/include/linux/mm_inline.h @@ -531,7 +531,7 @@ static inline pte_marker copy_pte_marker( { pte_marker srcm = pte_marker_get(entry); /* Always copy error entries. */ - pte_marker dstm = srcm & PTE_MARKER_POISONED; + pte_marker dstm = srcm & (PTE_MARKER_POISONED | PTE_MARKER_GUARD); /* Only copy PTE markers if UFFD register matches. */ if ((srcm & PTE_MARKER_UFFD_WP) && userfaultfd_wp(dst_vma)) diff --git a/include/linux/swapops.h b/include/linux/swapops.h index cb468e418ea1..4d0606df0791 100644 --- a/include/linux/swapops.h +++ b/include/linux/swapops.h @@ -426,9 +426,15 @@ typedef unsigned long pte_marker; * "Poisoned" here is meant in the very general sense of "future accesses are * invalid", instead of referring very specifically to hardware memory errors. * This marker is meant to represent any of various different causes of this. + * + * Note that, when encountered by the faulting logic, PTEs with this marker will + * result in VM_FAULT_HWPOISON and thus regardless trigger hardware memory error + * logic. */ #define PTE_MARKER_POISONED BIT(1) -#define PTE_MARKER_MASK (BIT(2) - 1) +/* Indicates that, on fault, this PTE will case a SIGSEGV signal to be sent. */ +#define PTE_MARKER_GUARD BIT(2) +#define PTE_MARKER_MASK (BIT(3) - 1) static inline swp_entry_t make_pte_marker_entry(pte_marker marker) { @@ -461,9 +467,25 @@ static inline swp_entry_t make_poisoned_swp_entry(void) } static inline int is_poisoned_swp_entry(swp_entry_t entry) +{ + /* + * We treat guard pages as poisoned too as these have the same semantics + * as poisoned ranges, only with different fault handling. + */ + return is_pte_marker_entry(entry) && + (pte_marker_get(entry) & + (PTE_MARKER_POISONED | PTE_MARKER_GUARD)); +} + +static inline swp_entry_t make_guard_swp_entry(void) +{ + return make_pte_marker_entry(PTE_MARKER_GUARD); +} + +static inline int is_guard_swp_entry(swp_entry_t entry) { return is_pte_marker_entry(entry) && - (pte_marker_get(entry) & PTE_MARKER_POISONED); + (pte_marker_get(entry) & PTE_MARKER_GUARD); } /* diff --git a/mm/hugetlb.c b/mm/hugetlb.c index 906294ac85dc..50e3f6ed73ac 100644 --- a/mm/hugetlb.c +++ b/mm/hugetlb.c @@ -6353,6 +6353,9 @@ vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma, ret = VM_FAULT_HWPOISON_LARGE | VM_FAULT_SET_HINDEX(hstate_index(h)); goto out_mutex; + } else if (marker & PTE_MARKER_GUARD) { + ret = VM_FAULT_SIGSEGV; + goto out_mutex; } } diff --git a/mm/memory.c b/mm/memory.c index 0f614523b9f4..551455cd453f 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -1455,7 +1455,7 @@ static inline bool should_zap_folio(struct zap_details *details, return !folio_test_anon(folio); } -static inline bool zap_drop_file_uffd_wp(struct zap_details *details) +static inline bool zap_drop_markers(struct zap_details *details) { if (!details) return false; @@ -1476,7 +1476,7 @@ zap_install_uffd_wp_if_needed(struct vm_area_struct *vma, if (vma_is_anonymous(vma)) return; - if (zap_drop_file_uffd_wp(details)) + if (zap_drop_markers(details)) return; for (;;) { @@ -1671,7 +1671,15 @@ static unsigned long zap_pte_range(struct mmu_gather *tlb, * drop the marker if explicitly requested. */ if (!vma_is_anonymous(vma) && - !zap_drop_file_uffd_wp(details)) + !zap_drop_markers(details)) + continue; + } else if (is_guard_swp_entry(entry)) { + /* + * Ordinary zapping should not remove guard PTE + * markers. Only do so if we should remove PTE markers + * in general. + */ + if (!zap_drop_markers(details)) continue; } else if (is_hwpoison_entry(entry) || is_poisoned_swp_entry(entry)) { @@ -4003,6 +4011,10 @@ static vm_fault_t handle_pte_marker(struct vm_fault *vmf) if (marker & PTE_MARKER_POISONED) return VM_FAULT_HWPOISON; + /* Hitting a guard page is always a fatal condition. */ + if (marker & PTE_MARKER_GUARD) + return VM_FAULT_SIGSEGV; + if (pte_marker_entry_uffd_wp(entry)) return pte_marker_handle_uffd_wp(vmf); From patchwork Thu Oct 17 20:42:37 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Lorenzo Stoakes X-Patchwork-Id: 13840803 Received: from mx0b-00069f02.pphosted.com (mx0b-00069f02.pphosted.com [205.220.177.32]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0037F229112; Thu, 17 Oct 2024 20:43:25 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=205.220.177.32 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1729197813; cv=fail; b=acPq+baPX8T5QM1VZ8pp1rTcTgpqLXyUe9gZnYNebtpal/nLFot2Z1rwyoy6uY25geov2laTp5PoJjTOj54P8CvkhHvBGF+wkIrVwXJgQrAifahPwbsgNAZL02vEIy/KaDlc4UQOlDaekGqCzDFDzuQeLERv02qWstkQSdU+M3s= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1729197813; c=relaxed/simple; bh=Oy7/o8wglmfF+9x1fu9vxrSv41Vr5NIQB/kW7G1fAU4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: Content-Type:MIME-Version; b=igko6vZ2r/uf60drocZeC1MJ65c9nl65sMieChFuW2KtgxYmQtiAoMLMRWcgSj2zPBcjkoGoRbRctAOGB0bU+dyXMl08IzhD9/3ERbLauMR2TmSKOoPLCp0Jo1pCLpPd6C0PNOZYBq+ee/Opuq24E6e9eXwdAlfArYqilhOEcRk= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=oracle.com; spf=pass smtp.mailfrom=oracle.com; dkim=pass (2048-bit key) header.d=oracle.com header.i=@oracle.com header.b=AI0E0RHH; dkim=pass (1024-bit key) header.d=oracle.onmicrosoft.com header.i=@oracle.onmicrosoft.com header.b=Yem/bXVV; arc=fail smtp.client-ip=205.220.177.32 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=oracle.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=oracle.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=oracle.com header.i=@oracle.com header.b="AI0E0RHH"; dkim=pass (1024-bit key) header.d=oracle.onmicrosoft.com header.i=@oracle.onmicrosoft.com header.b="Yem/bXVV" Received: from pps.filterd (m0246631.ppops.net [127.0.0.1]) by mx0b-00069f02.pphosted.com (8.18.1.2/8.18.1.2) with ESMTP id 49HFBn6O002180; Thu, 17 Oct 2024 20:42:58 GMT DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=oracle.com; h=cc :content-transfer-encoding:content-type:date:from:in-reply-to :message-id:mime-version:references:subject:to; s= corp-2023-11-20; bh=aC0TTOTg08sqzeqXSpodjeivk2FlCOxNysvsPwgWW5A=; b= AI0E0RHHUqviPaOoe9JpGs1GtBwzSs1RpBa5Qw/EbYMR5LvctZZbUalg1E4WNNk7 qFP7pYEak343VXgW7VT2VpdtAxdZrPnl4WBEgivxDKXgh5KVgLfHlkzVViwQEGKR iOSmAbl2KwIXppv0XYoJyORyXVqrHNPl0CCeucnNDS3UF2YpVP/M1tMoSmRYw3tD 0COK9aqrTaJiWHRTyhm1zy7q6Ijvk6reD04dCgo/XmvltMLkYaBtakJzxkw5Wlik Wf2loMu+MSlFgIOkaCgO+htexLIA3A1SYlIDbz4tSMX5QfD/u/SqjjHqsVIjqizJ q1Jn86l02rel5OSH724u2A== Received: from phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com (phxpaimrmta03.appoci.oracle.com [138.1.37.129]) by mx0b-00069f02.pphosted.com (PPS) with ESMTPS id 427fw2qh6r-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Thu, 17 Oct 2024 20:42:57 +0000 (GMT) Received: from pps.filterd (phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com [127.0.0.1]) by phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com (8.18.1.2/8.18.1.2) with ESMTP id 49HJD1MX013983; Thu, 17 Oct 2024 20:42:57 GMT Received: from nam10-mw2-obe.outbound.protection.outlook.com (mail-mw2nam10lp2049.outbound.protection.outlook.com [104.47.55.49]) by phxpaimrmta03.imrmtpd1.prodappphxaev1.oraclevcn.com (PPS) with ESMTPS id 427fjares3-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Thu, 17 Oct 2024 20:42:56 +0000 ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=Hyi1Rv7n741QVgpMaZEjp0ZLq2ppQwStWINMIt6aSToQyBepKpeOfX/aGfUH3QxvleEdTxqAkoqfRiv5ygWo2mteeJMZN6Fvst6/VZd2KwcFwf7WoDZmdjuLX2CAjCIp38Q7G+4yLtxEqlUQf5n6i5l3aPk0kqG+rAtmiTLoorZ8bqg6NHCJu3p9nDWX+yOl7AQNkvObLvDdcZ+jHubXL9zK0lREye8+ASLooHWJzY5duGRq3rUl/mLPIWblss5SRVH9zOibDrvcc1SfQ4UK/0UjozhP5OmaI6cZlCbYZ35IU5VrQVJ0qSg5JPaoEGCkvBSuYOW3FQy+1Mp8BrsR2w== 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=aC0TTOTg08sqzeqXSpodjeivk2FlCOxNysvsPwgWW5A=; b=I4fDKW8X/GJsQz/qwD+VogYTjVwRHRJZOyha8PRUI8qZPK/JlOFnbsdcf0C99VeUR+CtZaxffu4QfhtKE/GAeazJZjeaMdAKbbUh+cC3k1knQwtvWMKfdSezvIjpcl7Ra/yajM353VemxBB4ZOwv0iXFKkZX3DrqecrpX3+j4eYkYEKY04ne0zywGc9RV2Oj5st0/7tnNAv2vgu39k6L2q9F5r02AlnS3TP1h0+4CZo45+P7+3+jTXAWP6jw8eB6dKUrwwKMQ4aF8mWverWc5WBbA8oOWce/GUTD4Ufa32n8hbx3iSmwZ+7rIoIegOut2UT77+5E727GgeCm+RBXIw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=oracle.com; dmarc=pass action=none header.from=oracle.com; dkim=pass header.d=oracle.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=oracle.onmicrosoft.com; s=selector2-oracle-onmicrosoft-com; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=aC0TTOTg08sqzeqXSpodjeivk2FlCOxNysvsPwgWW5A=; b=Yem/bXVVd00EPHcTQu9i8zSqRpKKZ8ROXFw1oIO2tsPgP+UhvgV/VqCpgMXVQe+OSv+ucJoNfGk3nBxgPThQbW49ebyIHLeYhl663EcovcJIAv37iTzY0OdPhbQNC5Bu6jUoiNEtnlWypeJgwLW6XrCrukk4iK4SJFD03fJ6E7U= Received: from SJ0PR10MB5613.namprd10.prod.outlook.com (2603:10b6:a03:3d0::5) by DS7PR10MB5974.namprd10.prod.outlook.com (2603:10b6:8:9e::10) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.8069.18; Thu, 17 Oct 2024 20:42:52 +0000 Received: from SJ0PR10MB5613.namprd10.prod.outlook.com ([fe80::4239:cf6f:9caa:940e]) by SJ0PR10MB5613.namprd10.prod.outlook.com ([fe80::4239:cf6f:9caa:940e%5]) with mapi id 15.20.8069.016; Thu, 17 Oct 2024 20:42:51 +0000 From: Lorenzo Stoakes To: Andrew Morton Cc: Suren Baghdasaryan , "Liam R . Howlett" , Matthew Wilcox , Vlastimil Babka , "Paul E . McKenney" , Jann Horn , David Hildenbrand , linux-mm@kvack.org, linux-kernel@vger.kernel.org, Muchun Song , Richard Henderson , Ivan Kokshaysky , Matt Turner , Thomas Bogendoerfer , "James E . J . Bottomley" , Helge Deller , Chris Zankel , Max Filippov , Arnd Bergmann , linux-alpha@vger.kernel.org, linux-mips@vger.kernel.org, linux-parisc@vger.kernel.org, linux-arch@vger.kernel.org, Shuah Khan , Christian Brauner , linux-kselftest@vger.kernel.org, Sidhartha Kumar , Jeff Xu , Christoph Hellwig Subject: [PATCH 3/4] mm: madvise: implement lightweight guard page mechanism Date: Thu, 17 Oct 2024 21:42:37 +0100 Message-ID: X-Mailer: git-send-email 2.46.2 In-Reply-To: References: X-ClientProxiedBy: LO6P123CA0059.GBRP123.PROD.OUTLOOK.COM (2603:10a6:600:310::17) To SJ0PR10MB5613.namprd10.prod.outlook.com (2603:10b6:a03:3d0::5) Precedence: bulk X-Mailing-List: linux-parisc@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SJ0PR10MB5613:EE_|DS7PR10MB5974:EE_ X-MS-Office365-Filtering-Correlation-Id: 63058d18-695a-414b-4903-08dceeec44ee X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|7416014|376014|366016|1800799024; X-Microsoft-Antispam-Message-Info: gkqvje2KSh2LWletVpNujG+eklovnmEYZiGu5yKlZDywNbf70+cV28kKuF5rCOocnYJYWZiZzSL9qS69AWOMTT4slgzKxu5HW84tBEpyvrpU4vLyC7q7SN25Agb7LVyTORphcJRC8K7ti6Z6zdbTTsv1+DKLTIP2QWbfHqmBOlV/PhmKMR+WKwRND9H9q5xXSSD6V/sPMyIjfIKk3C7EoUECVXhmK7NA/mLLPyw06AgydADhXKrDz1KZPZPbSk4+lXqnxNouD7dR2JrhB3YomWxSohBJaWUTuCJjNiDRWRUsbn9a9ZTbWDvgX9jyC/XffhNAIDN6pI/VUHKMh4G32ql/CDG4huY4KL3sL1DsEl3mluIk3/csjeswQze59GMqwGpAlRWbsxPwy2YoMY507sYK6R/D+8crkAOs8G3PQ9tv827Ipn+FdUQrnJDwgLGQWCaMl+0Aa8BYka7EoyHfRp7LBI5LuzwzPyuNHqctZKnxGVTULpjtqWj3vHF9gstnfQpKfZTC09azM3l74EFJMfPT7OFgjUE+pNCicRwq1f6YOz4kuAqedP9fbNeK4oCG1G2nJtwPv7/fFEcNONjSXB5ZYvkNA0aYnfeNWPHJtNiWagTAZf4ALwYq4kvxhF7MJ5o5jKyZgAcvAKXCl7AR6jyl/UEBdPtte33IYeRwBr0HLaOr+KVJEcUpS6qncmphqm5O3eoU8mAgo0/nF5mGjo+MIBR1NpeOurhPeOkU1Z9YfY3v9UUl2Vn1gi2SBUNOUamFNB077idvSUcZQfIPThHS0wbFAqpQUysp5rgTEKL0tWd9LSOE6Vmccd1YS6egdpOGyYypmMeEPrkOS4Uvv9mfhpcbJ/VQ5FtHnVh9AMrTkD/wylItFnQxyI2sYOIs2kfLRlcc1q3f5c8u5OKbOJ/UnJDG5rGmzskpAywvm6/zk5DW1XXG7OGxxNwYnxZSDZf/TGgPov2CCN3efA1VEVgJpgY3swspWRHe0ZSrTcqohous/CsSB7NBhvJo6T76kFji9KwsQGhdt5eP7K/LI/b9ii19QemIdzGTjcYq0n6sPFdXfPZt0yVgH9Cu2B5IxNLZlo12675+grJTdMrH+ouyZqRtjm3ac+GAwkF8sPl4OYHuJUz6dPYXAuM0JGOtHayqETdNwzxXKEWeerbLwr/boc2P7w06V/dbC0rk/emMjQNqouJNFTgdT1w1XdhO5FImZ2wy2vB7UPoeyPcgyKlBTkYNskgH4U2+wVdns91A7OJbuqNXj/cq3xelQESG5DFekDfLVDHEPPnZY+KygBkGuvKcLuG0qGmYy5bEA8u6qgmPra2NBFZ0nxr4QvXw X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SJ0PR10MB5613.namprd10.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(7416014)(376014)(366016)(1800799024);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: cTSVOH0IuCLIutZbQqBfRrRhxxXXeyMm4Sf3uPbtfqJeNA95ZFahnp45UQ61ebI7pKtfrDPse1fK9p/EIMH0SAP7reosRb1nU7Jp9d+2J71Q9VqF8xAFRbEkkuYaQP1/ALaGrU7DCnvFOFSbnKsI3aLvaNIRWhhOgZNoK2vkRcdbrrCXps41iihE1QVJjnCG0o27/LkikGpXODczwd7FAbhGCpC8VCQwBELhRrArcUbjOlx1rEYuy4eJDGfxIUHyFebO82tlWwpkMiuRJVFHeyLiEppy+jEhdooQEJe7DpzJp2OzUwnN+3q8kKJnZ7rLxZEgZ3oGrF2K2WZn6svf5FylugHqxLPKfAZ1ToCqFi2BFRRPTY3hNgglWspoEcbUoFr7Fbi8Agf/13mbXSnLB185vuKK7MrCAjyDYjuMyhyFmDVGfe+0jldnDtOB0nNzB6QLaekTKzJTTYpJlp7KLaUoODyhi7xWeeYomYIdAuHr40L5er/ZfukNmSQbYH5WKxaSdMDphKU3Mq+x5IX/bpRYQHBn2egGLGG2oVZnhITZsgCXfWaewPG4pToYJONhrJQT7pGnNUvPw7kcvHWXPXko/gkbIvuXQHFcVZI5NMtTD1dT5ntNAjuzCXDuqJVZXjXzKkSiiPKvRizfgYZP198mcIOkdKxi0bo/ODeRAjKoxDXl5IixO6Pprp/9Yd4cOb6ICInM1LXrruJ33VSaVQ7WKI63owT4cLWaMPgfE9190iuwmY2c/rWV8Cvn+YyyMa2CPz6V5pD7g0PxcW51iVzXo3tKk5SofO1GHV48OKqtPLmG8EzzyeNIIuxqwXrOMNyEPPXpcZfhuNSRN73ovQrmaDtvyEb6A7PBto+vUD8dcU8+uyQyOR6rNpRYuh+pvtC5vfwIdNu2PbNUsQjYJeB+Vx+O9PjLWsb4tEVaAHX910GOShIkmAlx6/V3JyWCe082OxjMETr9/SPUatuCNQOqQQgWpteTPJWnKcSaQVWJs4vpc1wg2DtCqX/SkLDF715KRCLQ+1bBTQIDHyOmXejB6VRXpwPkd+WY3BY8LNDPsRsm79FkkKOLCwdeomyiom8jiR5v4z0zhw9N9qo62149vfYQHM2AOcT9JWOuvDdhlWhMdn2LiY0YfDLSQS6XBMYMI6GvB61wSaZiu8EC27CP25jEOSUw3y7Gkk+bGxwSXKNDwyBQ/ObG3PnIKUBKL1LysvU55l1oCh49CMnHr79zyK2SlpMEYpo1S0LAS5SyDVoYoA0+qFZaBe8KABPx8w6l+O9QQ7662JwDmZZqlEDgF1uhqRoIygn5spAB+7JPw/+X8GH0RJIqqs3sdfCX4Nggd7fRp2LQe4RF0OrcmTNiFs5c/Rlb2iWrF/SWrwRTs9POArshk9q5NdgXVNwsnJ07TsuS6nRstKs0kG5zEMfoZXZzymCBJXXBJ5U8qm2ADonj4P3nb9BKAofvrftj6btGmayQ4BDmNStrVt6ss8KZw1qvYnta6P7JIL2OcUwSdcm0tXzEgeTvHm3MQyHL9tdvUk9MP7Q9orUeNgAsZ+0VsBtIlPQeeT1f0JMs0WQLeNk7DbuzzEp1H9uGqy4N7AcMHynppYZq7OkXDzrzIw== X-MS-Exchange-AntiSpam-ExternalHop-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-ExternalHop-MessageData-0: uBpO6uM/PBH9/iEHY6tB83dbgwHV0r6+QrccPURvydGJQckWUyOe5xnHhUNqe+LO/5yEAyTiaMbXa8hwdFInOSYfq46h84fuW/ytLc9ms7LPgUlv9D73psC/3imogt0GiZ7s2PM1l9C5EOP+mxmARDuY8yEF3t5wUfxI09ci9vPGvD0oDfWW52dc2w2B4d3lRyv7p1DmPCM+YWkvWppMZblJDaQbOEAQ1L8IlH4h3H4BIDxiFi9jqMD6IHxPxlp7DMjSP4TGEmDJuPzyQSwkx9Iot0GjWO2lvKACfWhWBrz6P+uAM1ThVAoh7pqZwwPagDybEyr0FB0EGkhqozkREDoauLNmtn4scD5/S2/ztTnWVVafVGlTQhtP8Geo0WMP43bN1pqReWjA1OhPS4Lmr5WcnHp8zXcnb9uy1q4wdWCp4yRy49Lzd/z+HkSgbtnvFByoB++1Ms/CgoV2TlVBBWcLk2AP0g1DXTrHKnFyDcTC0XkRTW6o+v6Yzox6vBxOxKDMQYrryHAmpJk3UUzR4pJGiUwt7deBLpLfeHEffitMAFX3RKJA5gj0iKH8mOpRFhKZCAbUHiFoP8N24wbhYJYLhBD46jhbZnl3Nr3d5g8= X-OriginatorOrg: oracle.com X-MS-Exchange-CrossTenant-Network-Message-Id: 63058d18-695a-414b-4903-08dceeec44ee X-MS-Exchange-CrossTenant-AuthSource: SJ0PR10MB5613.namprd10.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 17 Oct 2024 20:42:51.8594 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 4e2c6054-71cb-48f1-bd6c-3a9705aca71b X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: ROjkHTqRQ+o6oGFA2/TnQABLv1NEJaF6X4Sq35P61sCemeU2bmV5gsPRbIgrN26SMukoeeV+PsGgh352ZMrwFuOK19SCOWIb4znby0mmEgw= X-MS-Exchange-Transport-CrossTenantHeadersStamped: DS7PR10MB5974 X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.293,Aquarius:18.0.1051,Hydra:6.0.680,FMLib:17.12.62.30 definitions=2024-10-17_23,2024-10-17_01,2024-09-30_01 X-Proofpoint-Spam-Details: rule=notspam policy=default score=0 malwarescore=0 phishscore=0 mlxscore=0 mlxlogscore=947 bulkscore=0 spamscore=0 suspectscore=0 adultscore=0 classifier=spam adjust=0 reason=mlx scancount=1 engine=8.12.0-2409260000 definitions=main-2410170139 X-Proofpoint-GUID: ZykuiTcn5RW2iX6RsIbwktgQtKIiNe7R X-Proofpoint-ORIG-GUID: ZykuiTcn5RW2iX6RsIbwktgQtKIiNe7R Implement a new lightweight guard page feature, that is regions of userland virtual memory that, when accessed, cause a fatal signal to arise. Currently users must establish PROT_NONE ranges to achieve this. However this is very costly memory-wise - we need a VMA for each and every one of these regions AND they become unmergeable with surrounding VMAs. In addition repeated mmap() calls require repeated kernel context switches and contention of the mmap lock to install these ranges, potentially also having to unmap memory if installed over existing ranges. The lightweight guard approach eliminates the VMA cost altogether - rather than establishing a PROT_NONE VMA, it operates at the level of page table entries - poisoning PTEs such that accesses to them cause a fault followed by a SIGSGEV signal being raised. This is achieved through the PTE marker mechanism, which a previous commit in this series extended to permit this to be done, installed via the generic page walking logic, also extended by a prior commit for this purpose. These poison ranges are established with MADV_GUARD_POISON, and if the range in which they are installed contain any existing mappings, they will be zapped, i.e. free the range and unmap memory (thus mimicking the behaviour of MADV_DONTNEED in this respect). Any existing poison entries will be left untouched. There is no nesting of poisoned pages. Poisoned ranges are NOT cleared by MADV_DONTNEED, as this would be rather unexpected behaviour, but are cleared on process teardown or unmapping of memory ranges. Ranges can have the poison property removed by MADV_GUARD_UNPOISON - 'remedying' the poisoning. The ranges over which this is applied, should they contain non-poison entries, will be untouched, only poison entries will be cleared. We permit this operation on anonymous memory only, and only VMAs which are non-special, non-huge and not mlock()'d (if we permitted this we'd have to drop locked pages which would be rather counterintuitive). Suggested-by: Vlastimil Babka Suggested-by: Jann Horn Suggested-by: David Hildenbrand Signed-off-by: Lorenzo Stoakes --- arch/alpha/include/uapi/asm/mman.h | 3 + arch/mips/include/uapi/asm/mman.h | 3 + arch/parisc/include/uapi/asm/mman.h | 3 + arch/xtensa/include/uapi/asm/mman.h | 3 + include/uapi/asm-generic/mman-common.h | 3 + mm/madvise.c | 168 +++++++++++++++++++++++++ mm/mprotect.c | 3 +- mm/mseal.c | 1 + 8 files changed, 186 insertions(+), 1 deletion(-) diff --git a/arch/alpha/include/uapi/asm/mman.h b/arch/alpha/include/uapi/asm/mman.h index 763929e814e9..71e13f27742d 100644 --- a/arch/alpha/include/uapi/asm/mman.h +++ b/arch/alpha/include/uapi/asm/mman.h @@ -78,6 +78,9 @@ #define MADV_COLLAPSE 25 /* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102 /* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103 /* revoke guard poisoning */ + /* compatibility flags */ #define MAP_FILE 0 diff --git a/arch/mips/include/uapi/asm/mman.h b/arch/mips/include/uapi/asm/mman.h index 9c48d9a21aa0..1a2222322f77 100644 --- a/arch/mips/include/uapi/asm/mman.h +++ b/arch/mips/include/uapi/asm/mman.h @@ -105,6 +105,9 @@ #define MADV_COLLAPSE 25 /* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102 /* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103 /* revoke guard poisoning */ + /* compatibility flags */ #define MAP_FILE 0 diff --git a/arch/parisc/include/uapi/asm/mman.h b/arch/parisc/include/uapi/asm/mman.h index 68c44f99bc93..380905522397 100644 --- a/arch/parisc/include/uapi/asm/mman.h +++ b/arch/parisc/include/uapi/asm/mman.h @@ -75,6 +75,9 @@ #define MADV_HWPOISON 100 /* poison a page for testing */ #define MADV_SOFT_OFFLINE 101 /* soft offline page for testing */ +#define MADV_GUARD_POISON 102 /* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103 /* revoke guard poisoning */ + /* compatibility flags */ #define MAP_FILE 0 diff --git a/arch/xtensa/include/uapi/asm/mman.h b/arch/xtensa/include/uapi/asm/mman.h index 1ff0c858544f..e8d5affceb28 100644 --- a/arch/xtensa/include/uapi/asm/mman.h +++ b/arch/xtensa/include/uapi/asm/mman.h @@ -113,6 +113,9 @@ #define MADV_COLLAPSE 25 /* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102 /* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103 /* revoke guard poisoning */ + /* compatibility flags */ #define MAP_FILE 0 diff --git a/include/uapi/asm-generic/mman-common.h b/include/uapi/asm-generic/mman-common.h index 6ce1f1ceb432..5dfd3d442de4 100644 --- a/include/uapi/asm-generic/mman-common.h +++ b/include/uapi/asm-generic/mman-common.h @@ -79,6 +79,9 @@ #define MADV_COLLAPSE 25 /* Synchronous hugepage collapse */ +#define MADV_GUARD_POISON 102 /* fatal signal on access to range */ +#define MADV_GUARD_UNPOISON 103 /* revoke guard poisoning */ + /* compatibility flags */ #define MAP_FILE 0 diff --git a/mm/madvise.c b/mm/madvise.c index e871a72a6c32..7b9a357b84d2 100644 --- a/mm/madvise.c +++ b/mm/madvise.c @@ -60,6 +60,8 @@ static int madvise_need_mmap_write(int behavior) case MADV_POPULATE_READ: case MADV_POPULATE_WRITE: case MADV_COLLAPSE: + case MADV_GUARD_POISON: + case MADV_GUARD_UNPOISON: return 0; default: /* be safe, default to 1. list exceptions explicitly */ @@ -1017,6 +1019,166 @@ static long madvise_remove(struct vm_area_struct *vma, return error; } +static bool is_valid_guard_vma(struct vm_area_struct *vma, bool allow_locked) +{ + vm_flags_t disallowed = VM_SPECIAL | VM_HUGETLB; + + /* + * A user could lock after poisoning but that's fine, as they'd not be + * able to fault in. The issue arises when we try to zap existing locked + * VMAs. We don't want to do that. + */ + if (!allow_locked) + disallowed |= VM_LOCKED; + + if (!vma_is_anonymous(vma)) + return false; + + if ((vma->vm_flags & (VM_MAYWRITE | disallowed)) != VM_MAYWRITE) + return false; + + return true; +} + +static bool is_guard_pte_marker(pte_t ptent) +{ + return is_pte_marker(ptent) && + is_guard_swp_entry(pte_to_swp_entry(ptent)); +} + +static int guard_poison_pud_entry(pud_t *pud, unsigned long addr, unsigned long next, + struct mm_walk *walk) +{ + pud_t pudval = pudp_get(pud); + + /* Do not split a huge pud - we do nothing with these so just ignore. */ + if (pud_trans_huge(pudval) || pud_devmap(pudval)) + walk->action = ACTION_CONTINUE; + + return 0; +} + +static int guard_poison_pmd_entry(pmd_t *pmd, unsigned long addr, unsigned long next, + struct mm_walk *walk) +{ + pmd_t pmdval = pmdp_get(pmd); + + /* Do not split a huge pmd - we do nothing with these so just ignore. */ + if (pmd_trans_huge(pmdval) || pmd_devmap(pmdval)) + walk->action = ACTION_CONTINUE; + + return 0; +} + +static int guard_poison_pte_entry(pte_t *pte, unsigned long addr, + unsigned long next, struct mm_walk *walk) +{ + pte_t pteval = ptep_get(pte); + + /* + * If not a guard marker, simply abort the operation. We return a value + * > 0 indicating a non-error abort. + */ + return !is_guard_pte_marker(pteval); +} + +static int guard_poison_install_pte(unsigned long addr, unsigned long next, + pte_t *ptep, struct mm_walk *walk) +{ + /* Simply install a PTE marker, this causes segfault on access. */ + *ptep = make_pte_marker(PTE_MARKER_GUARD); + + return 0; +} + +static const struct mm_walk_ops guard_poison_walk_ops = { + .pud_entry = guard_poison_pud_entry, + .pmd_entry = guard_poison_pmd_entry, + .pte_entry = guard_poison_pte_entry, + .install_pte = guard_poison_install_pte, + .walk_lock = PGWALK_RDLOCK, +}; + +static long madvise_guard_poison(struct vm_area_struct *vma, + struct vm_area_struct **prev, + unsigned long start, unsigned long end) +{ + long err; + + *prev = vma; + if (!is_valid_guard_vma(vma, /* allow_locked = */false)) + return -EINVAL; + + /* + * If we install poison markers, then the range is no longer + * empty from a page table perspective and therefore it's + * appropriate to have an anon_vma. + * + * This ensures that on fork, we copy page tables correctly. + */ + err = anon_vma_prepare(vma); + if (err) + return err; + + /* + * Optimistically try to install the guard poison pages first. If any + * non-guard pages are encountered, give up and zap the range before + * trying again. + */ + while (true) { + /* Returns < 0 on error, == 0 if success, > 0 if zap needed. */ + err = walk_page_range_mm(vma->vm_mm, start, end, + &guard_poison_walk_ops, NULL); + if (err <= 0) + return err; + + /* + * OK some of the range have non-guard pages mapped, zap + * them. This leaves existing guard pages in place. + */ + zap_page_range_single(vma, start, end - start, NULL); + + if (fatal_signal_pending(current)) + return -EINTR; + cond_resched(); + } +} + +static int guard_unpoison_pte_entry(pte_t *pte, unsigned long addr, + unsigned long next, struct mm_walk *walk) +{ + pte_t ptent = ptep_get(pte); + + if (is_guard_pte_marker(ptent)) { + /* Simply clear the PTE marker. */ + pte_clear_not_present_full(walk->mm, addr, pte, false); + update_mmu_cache(walk->vma, addr, pte); + } + + return 0; +} + +static const struct mm_walk_ops guard_unpoison_walk_ops = { + .pte_entry = guard_unpoison_pte_entry, + .walk_lock = PGWALK_RDLOCK, +}; + +static long madvise_guard_unpoison(struct vm_area_struct *vma, + struct vm_area_struct **prev, + unsigned long start, unsigned long end) +{ + *prev = vma; + /* + * We're ok with unpoisoning mlock()'d ranges, as this is a + * non-destructive action. + */ + if (!is_valid_guard_vma(vma, /* allow_locked = */true)) + return -EINVAL; + + return walk_page_range(vma->vm_mm, start, end, + &guard_unpoison_walk_ops, NULL); +} + /* * Apply an madvise behavior to a region of a vma. madvise_update_vma * will handle splitting a vm area into separate areas, each area with its own @@ -1098,6 +1260,10 @@ static int madvise_vma_behavior(struct vm_area_struct *vma, break; case MADV_COLLAPSE: return madvise_collapse(vma, prev, start, end); + case MADV_GUARD_POISON: + return madvise_guard_poison(vma, prev, start, end); + case MADV_GUARD_UNPOISON: + return madvise_guard_unpoison(vma, prev, start, end); } anon_name = anon_vma_name(vma); @@ -1197,6 +1363,8 @@ madvise_behavior_valid(int behavior) case MADV_DODUMP: case MADV_WIPEONFORK: case MADV_KEEPONFORK: + case MADV_GUARD_POISON: + case MADV_GUARD_UNPOISON: #ifdef CONFIG_MEMORY_FAILURE case MADV_SOFT_OFFLINE: case MADV_HWPOISON: diff --git a/mm/mprotect.c b/mm/mprotect.c index 0c5d6d06107d..d0e3ebfadef8 100644 --- a/mm/mprotect.c +++ b/mm/mprotect.c @@ -236,7 +236,8 @@ static long change_pte_range(struct mmu_gather *tlb, } else if (is_pte_marker_entry(entry)) { /* * Ignore error swap entries unconditionally, - * because any access should sigbus anyway. + * because any access should sigbus/sigsegv + * anyway. */ if (is_poisoned_swp_entry(entry)) continue; diff --git a/mm/mseal.c b/mm/mseal.c index ece977bd21e1..21bf5534bcf5 100644 --- a/mm/mseal.c +++ b/mm/mseal.c @@ -30,6 +30,7 @@ static bool is_madv_discard(int behavior) case MADV_REMOVE: case MADV_DONTFORK: case MADV_WIPEONFORK: + case MADV_GUARD_POISON: return true; } From patchwork Thu Oct 17 20:42:38 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Lorenzo Stoakes X-Patchwork-Id: 13840802 Received: from mx0b-00069f02.pphosted.com (mx0b-00069f02.pphosted.com [205.220.177.32]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CA196229118; Thu, 17 Oct 2024 20:43:29 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=205.220.177.32 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1729197812; cv=fail; b=Ngnk8j4HvufyaY5Lc9Mo2o5KCDXEW6fMC+zm/ILG5qXvEj90v+6OE+QDzqjKerokmaGSDNCQSL9fT/oobL4wuaP+CeJwjesSHnk/8rNeICOouXcyA3199e1Fgox557Zj1kFvv4kaDHoxzi2klJFqZ0sStcOvwDJMpKVQo49bhuU= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1729197812; c=relaxed/simple; bh=i2BWEZvg5N6ekd6YZfDt4VKQbhuivxhjme7fb8k90S0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: Content-Type:MIME-Version; b=VKO/wxuAavm6+CS1m3tPqAL9W3HPuC1vEk+IDl6pw/5eFBOOMFqBSvpMo8CWOSqY9u5e9pogRgf0xl7loVbI3nvCRgXxa7xRhUop2DMAPflIirxkpnRJobyOLLMH56Sam8s26qDjnn9WShCi+ZO6i0M/v66dvBRiSjx5nyPc2lE= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=oracle.com; spf=pass smtp.mailfrom=oracle.com; dkim=pass (2048-bit key) header.d=oracle.com header.i=@oracle.com header.b=OAp/1SyS; dkim=pass (1024-bit key) header.d=oracle.onmicrosoft.com header.i=@oracle.onmicrosoft.com header.b=iRSr+/+j; arc=fail smtp.client-ip=205.220.177.32 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=oracle.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=oracle.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=oracle.com header.i=@oracle.com header.b="OAp/1SyS"; dkim=pass (1024-bit key) header.d=oracle.onmicrosoft.com header.i=@oracle.onmicrosoft.com header.b="iRSr+/+j" Received: from pps.filterd (m0246630.ppops.net [127.0.0.1]) by mx0b-00069f02.pphosted.com (8.18.1.2/8.18.1.2) with ESMTP id 49HFBvsg024511; Thu, 17 Oct 2024 20:43:02 GMT DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=oracle.com; h=cc :content-transfer-encoding:content-type:date:from:in-reply-to :message-id:mime-version:references:subject:to; s= corp-2023-11-20; bh=mjxjOr5wbvhvGFQe1h5NBiR5xNC7dPyxjLQzSwUhIwM=; b= OAp/1SySMGppl18V/KhFgU2tOSo3vG/Sy80u2kK5aWj6JYi6ePtpuNbE8XIi0d9K JS4L037IWJ3PfmLcMyJvdFZSJDk0COugmTu9QxDTlnPVr8ehFQPeZTLIZBCZNIac iPm0wG1UFKO7se2yj4vl6xXH+/euuBmUC6IRgjUqQxF8k/bHrFpGDH5khUB6lDWA RhAINtscNMxmvGqPwr5OmVBoQR4cRXaJ4K7bkuSBxy9qFEhna0osOiIabBIZFxug fSD8uf/vPdJcTilLXUwUE3Ha1SVetW+qDwBfDKick32G9eN2L0+POoi3bYKm5z3L JImrUwlhvnxjoDPbhIqLPQ== Received: from iadpaimrmta03.imrmtpd1.prodappiadaev1.oraclevcn.com (iadpaimrmta03.appoci.oracle.com [130.35.103.27]) by mx0b-00069f02.pphosted.com (PPS) with ESMTPS id 427fhcpyra-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Thu, 17 Oct 2024 20:43:01 +0000 (GMT) Received: from pps.filterd (iadpaimrmta03.imrmtpd1.prodappiadaev1.oraclevcn.com [127.0.0.1]) by iadpaimrmta03.imrmtpd1.prodappiadaev1.oraclevcn.com (8.18.1.2/8.18.1.2) with ESMTP id 49HJMt9V010406; Thu, 17 Oct 2024 20:43:01 GMT Received: from nam10-mw2-obe.outbound.protection.outlook.com (mail-mw2nam10lp2043.outbound.protection.outlook.com [104.47.55.43]) by iadpaimrmta03.imrmtpd1.prodappiadaev1.oraclevcn.com (PPS) with ESMTPS id 427fjh3tdj-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Thu, 17 Oct 2024 20:43:00 +0000 ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=Uy+INrThlIIDsngA/8TMuSKYW13u9bphqdMPddFOvrOiZOKPTVrNtlarMhXfo8RlAcNtvj02YBTMw2kvEKbht8DN+A97L5i8oXAcxwgNXkwO1NvV/CHOdYn9QCb5czlOEZIX4gYZclvnFFqk9rlTNVFPVQKfTL9EOQOAma2a8lCYmdj0PtBQU7+2wOxo4vuZS8J26lKQwnbjqEdhvbezKzSDZT/vl0yEFX6f9OfRRYodMzLHZXI8/jOyvzYNx2VTomFneL6oH2dmLrpdVhrWFDA3/1KSv+FQVwPXnSqlncwKmAcBnw1RR7s58naxB6xroyUYgdh7OZeARhAy77G9ew== 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=mjxjOr5wbvhvGFQe1h5NBiR5xNC7dPyxjLQzSwUhIwM=; b=JODkMTEJQ++0A/yyBIW0WuTvt9hnfrEqsjuOMcsOyL3cQ7EiPIlJYZoIGtKex2ZbqiJ6ZSmg+wUdqhb8np28fZWGt7T1hswc+X52bj59M47Drg9xCctfIl+fItDkcnsBklgJHyk9cV82gHAFf0V6UX+zecOVBT0QpnOk2WKuHOnMkrfIj2ixLoBMOx7Bdfk3+/RDzYp6pYmXUxoYnzmY2vI4dyCwQTlY9vWmL+zx1VArupvgHzgKBrvTNpTwQzm6rzkFGpLGtBRN/oDdmcwpIpcxH/VnJfjbxJTKi/2bDXEF0/5LMxK4sWcJksVYfeD0Fr9b9m0Y0jRWGbuws5KGvw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=oracle.com; dmarc=pass action=none header.from=oracle.com; dkim=pass header.d=oracle.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=oracle.onmicrosoft.com; s=selector2-oracle-onmicrosoft-com; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=mjxjOr5wbvhvGFQe1h5NBiR5xNC7dPyxjLQzSwUhIwM=; b=iRSr+/+jPHC4uEpBBTPosZgS0zvqAscXYOjYRk+jEJOMZCnbUIhvVpvExgvXMKaIM1N//bS7lHRsEhTTVX5nikqn+plHbBiQEJaxZBSkb2ZFBdnOimyLXGoYaxqNcTAaVbhl0yLax8JHK3r5pht9ICozLUhSJU2bllmky+ninbE= Received: from SJ0PR10MB5613.namprd10.prod.outlook.com (2603:10b6:a03:3d0::5) by DS7PR10MB5974.namprd10.prod.outlook.com (2603:10b6:8:9e::10) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.8069.18; Thu, 17 Oct 2024 20:42:56 +0000 Received: from SJ0PR10MB5613.namprd10.prod.outlook.com ([fe80::4239:cf6f:9caa:940e]) by SJ0PR10MB5613.namprd10.prod.outlook.com ([fe80::4239:cf6f:9caa:940e%5]) with mapi id 15.20.8069.016; Thu, 17 Oct 2024 20:42:56 +0000 From: Lorenzo Stoakes To: Andrew Morton Cc: Suren Baghdasaryan , "Liam R . Howlett" , Matthew Wilcox , Vlastimil Babka , "Paul E . McKenney" , Jann Horn , David Hildenbrand , linux-mm@kvack.org, linux-kernel@vger.kernel.org, Muchun Song , Richard Henderson , Ivan Kokshaysky , Matt Turner , Thomas Bogendoerfer , "James E . J . Bottomley" , Helge Deller , Chris Zankel , Max Filippov , Arnd Bergmann , linux-alpha@vger.kernel.org, linux-mips@vger.kernel.org, linux-parisc@vger.kernel.org, linux-arch@vger.kernel.org, Shuah Khan , Christian Brauner , linux-kselftest@vger.kernel.org, Sidhartha Kumar , Jeff Xu , Christoph Hellwig Subject: [PATCH 4/4] selftests/mm: add self tests for guard page feature Date: Thu, 17 Oct 2024 21:42:38 +0100 Message-ID: <8b1add3c511effb62d68183cae8a954d8339286c.1729196871.git.lorenzo.stoakes@oracle.com> X-Mailer: git-send-email 2.46.2 In-Reply-To: References: X-ClientProxiedBy: LO4P123CA0105.GBRP123.PROD.OUTLOOK.COM (2603:10a6:600:191::20) To SJ0PR10MB5613.namprd10.prod.outlook.com (2603:10b6:a03:3d0::5) Precedence: bulk X-Mailing-List: linux-parisc@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SJ0PR10MB5613:EE_|DS7PR10MB5974:EE_ X-MS-Office365-Filtering-Correlation-Id: 0568faa4-f6f6-48a9-f027-08dceeec4756 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|7416014|376014|366016|1800799024; X-Microsoft-Antispam-Message-Info: KlXYLE+sqEfFMwDgDjumHLO9Z1J6CvRpcvTLMgjRsFgbaTk+WL0ZkDyZtTWzSrd8KqfbsujSRLt9Ie7eA6tpDKXQDLarhBPQxHF1PnoJIM7qXSXKweNsqshFXpLoTsbaWCa9nZj1ke8icMgeBYz1n9PwvMGiBcfd+D5fUX/2gRLG1EZSPLE0ictngLts2DJZgLhzIhah9vEvPUIsMa6fD8Mv9FjAuGgizH1uCjvtrk7ikY1MNfxOruJeN8+ACq12O9ExNVBJpfuQzGzdnFleisoTrfxx5k/2jh4h4DFKNFDNAuUqlDoK6IreC8AbtUXSpWp2YDglQTXD6ZOtZdmMSyY2UNulnBDh5MAh7g23LW394dHinBBA0N8RkFLSHqZGqJIjsbnMvAobq21SqT22rtP0YZchV6SwjOShlv72APTt43kIPe9kBeDrubd5FvwEiLAOdQviJM0Prk1FYJt/6VHLUk+BfWt5TI0nCxcp3vYrNOP9uL2Jw9/IFng2qslwTF2BTARSwTt/iAZ/WeAFlMQ2EKvd/icM3prj6V7vFQ0yYCS1sMJ22LCXN0GpjmY64xhMAf1eJA5+VGy4jjTLFhbOpvUl0IaxxvCIqmqPPZniNRLFMM35neEaSI8j9rDXMUea6mHzx5tGZBHfPQS8767g9Ng6Tj/NKkwnKI+eSagdQgdQXmuFFFFIshGygd/+Gt2GiMiN7w1rgnjY48N2JtseE/+X6UUkVThXbChZpyBKT6ATr/n+5xpGM35hDNHD0YaYdzNl/oD7GyD8hAGgt9MKUXVCqZI9FhBZG+fBBYNFbwiPCKkTtBU0akbemgGadsdQOe9Sz0AdVmuWDITNMFkp/1oGHxoMd9Quem5lWlNJ41eYeMIRUyq9fMi6xOtTW0wDo3r8M3MSlO8GJU+JPsySreOts3feu4JqzjnP4F1PJifamCq5D7mjQ/ZG+MXSdATDFJTDhKUHUEdz+Wo069DOK1OdyWEAKLrmd5Co98bdxUcXqk1hNxhz0xC/g1St/W0/ClKzvu6L7gXIzqdx+SuYa2CQaYQumTJKZum/LSF/5jTHf6TQ/uXrbfFREPApJEKFEvMuDFFT95WsgwcNdMEUCEt3C2eWipSCBGITS21eBkiC0RGBjTqmq0aHLadwjLF1COs5ltJLdZgs/H1N8aLcAlaAU22vcXhREuFnMVkywAC+IuWYqVTg3W/1Q/0Ch3AbGq6W6NmQRnSfRyG0YhhO4IkTMwapA0kJ4bu9SaOFtBxdS7bGXJ9z1CSkXIcy5yEF347ZUR+wQ+ZF83l1nR0X4mwYK0vIp/THa5x19LfubLI6pSbkKfZHntXX6pLh X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SJ0PR10MB5613.namprd10.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(7416014)(376014)(366016)(1800799024);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: FWVj69PC51iEuYP4xFt1a76f16tPuuYvQGD9aw55ZwnFr0jGO+8hnPj75/TaHP5Xa3yGuHW60WWS6z1XN2YKsmR610gGUNN7fA7aCOtHqfE6OJornn8Li+7OgDEb56GzIhd3e7IVfLUNTSND1TBeaTRWuJ98HRQOJmsee8WrI8j5IpJ+rQ+jqS49om1/dV2GdyFKpzmTrzNGNHWjpOPUQuYq28CxT4lDGFiKKkxSkxEFISPRRswMDf9gKGdAJrslGJcsc2qn5ArX2LggFCpTUD2d+zam+SqjHHO87Fnid8rFTjfBycmMrazdDRk3VdPZiqy2eVR1vhUdf8PygJJH1/vhNS8uOo66OZgVWVYe4aS8fCwSuXhq6SNOGgB4VUEq5KIbzBTiBw4yk8b6EAbtW/Uc0hU1LZxkzXdRbZOiGlYAZpA5waZVn7T2GxSRAPggEGSH6UygRp95/b+/52HKTdEsrbUgaj5dG0Ed/jKvizZ/uBsouzZFEBKGtFJgfv2xoKf8DGdtColg4T6I+FMZLCEy/uUpv7sGVX/Ky06d2kB92vj9OD5V/EkgAJVi+0CsHbZag6StgWrtBk1IxNO4d5zA0c5lYyd/hfJKZ9bSUlN921BZG0aCnKZ4zXfjV/xws1IeNZd+QDmWuVChT2shKgNBorNiqWS5JjQdZ2w30pJCkVtKoQLuYV9KQudPc6eRS698iqZdsTTHJ0btZf+U+4Lp2MtjDtcGbrTU0gjnlvbftWBcY16ncfiboWeHk0Z6Egth5yh0YaFCTNnw/EZsGKzeMerO9A+B0+GFaihGIHGgEnfQ6vTuducQB3ns7Bf0cUqjalMSUUBqof5TUOepFf5ukm3b8KFRbenaD7eGCP9/36f+jK7OfksCD5QxDfYEq43X4OVlo6dHpi4fxI4lp9gN6gWsQC7cdClANIryWEmKdzMVyupZuqxnsSFixsmZrVrunC+Ssb5UhaikVpg5YwgWMbLPovpz3Gb28yaWAi3f99NZtFFyBUHq1FnGNs2w4CfedZaxY3cOaBvnLO9A5uyNi3WGtjVJ3O2HOmBXYknOEmMTfZJuXRYB5zVT4snJASPMZkfr/RjkhVZ/TfGNPMfD8AQ+jrmcnchWiq6Pg06cJozOGuZp7ITVwYZnIu7ykhXib+LDdbaDEnjqmRlEw4cn/5CJpMknXEHU6uJALFoNfEM3D474M9wv8yJoxIZksVOs7T410GwlmOIgbeLHGNVBx/nicQUtFCxTBn+H3/MkQVC8c0dMflNplQ7bAvi2kszDWIvrRgyMXwEUEmRrU25TVXrNZJcbQYuFr6cjALct3z3lq3FdteJUULYb2v7oyfY9TLjbFfwyRIURAuTo9yVrlGeCf0v5L+g2Rxs2fwvI31tlHrnr9n/II35Tnhh5ZzvKU1KjFLU2pDiRlWY1iiiEvXg2g1h7VrlncJTNfV/KiYldhlzYhIk7oTgdNbn9bB034kIHflp7hfvWw/DJyvURGFDotXj/Pu45IB5ybSOBD8tn5AJ6OfJKaVMwAefdaBIPRxMukhkKeLXCBOCpt+XVF9exF2PhjwAF/kL/9CufJOo6qFN+BQrzdBPUczW01cSwDeH7mLLqlx+uibuSrg== X-MS-Exchange-AntiSpam-ExternalHop-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-ExternalHop-MessageData-0: 04IdAJTyJc6CGpLI/yDpzFed1E2pY9pCFLXiEQEbR8YvY3uMzrvz5+r7cIivnXKRlWemHh8AD+rOxs85M2xNVUpDjVmUYemJN6fZSD5Lm4JFOAKwQOMGFdjtoLVpshG1F/ov6CkUP1g+9UwWcmmlpMywUta+3nN8hX4MvzNCuh9pCULRYYpSxN3tex50ub8YiWvcHkl/hG19RTLUPqbFt2kBhpunYHzVacoLcvvZunT43EGSbKarBg1x5rSl2wE7Odhr0/qUqOMabEawot4xfZ4JVdQxCetZR7zzVjeVrIELo1mB7LduvtlKnj0IXy2mZp2Z3zJ1o6kymoTj0B4Cnr/ahpOJZ1HXfvfRJmgDzF43XZpypyrXT1VMv7JTasL+QI46WkMfsoYO/CskT+ecDr1o3uuLiUBRB74vUtfcTGWwokTJk5epILzo++Ihm/JwI3H2N4Gcwja9dsbd7LtXLWwuI+l2Gm0zI+MBgZzeJFGJ8FNmHPZq4lpTwF9jr6zHTSTS+Jm23ccBp1z7po79X1jVd79wakTqYJelwfnfqobPMpr/msJBv2f2UwiSdJR875YkPhEBHAGm2kt2juOZZ6mqkUJ5fcXFATyfWTAdS1c= X-OriginatorOrg: oracle.com X-MS-Exchange-CrossTenant-Network-Message-Id: 0568faa4-f6f6-48a9-f027-08dceeec4756 X-MS-Exchange-CrossTenant-AuthSource: SJ0PR10MB5613.namprd10.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 17 Oct 2024 20:42:56.0310 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 4e2c6054-71cb-48f1-bd6c-3a9705aca71b X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: EUF5vtC6Y9VQoLi62ktxGtokhKhnN3FvZFMVLA3AWylfF2Dy3ilOsOSBHMN0o4Zm0rDT1rRDfLFNmHUcQ4g/85lIiK9wN1qCa2fpO89fV6E= X-MS-Exchange-Transport-CrossTenantHeadersStamped: DS7PR10MB5974 X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.293,Aquarius:18.0.1051,Hydra:6.0.680,FMLib:17.12.62.30 definitions=2024-10-17_23,2024-10-17_01,2024-09-30_01 X-Proofpoint-Spam-Details: rule=notspam policy=default score=0 phishscore=0 malwarescore=0 adultscore=0 spamscore=0 mlxscore=0 suspectscore=0 bulkscore=0 mlxlogscore=999 classifier=spam adjust=0 reason=mlx scancount=1 engine=8.12.0-2409260000 definitions=main-2410170139 X-Proofpoint-GUID: N2SY7OGOE6phBldDY_DAovJ8Y1yR9Xii X-Proofpoint-ORIG-GUID: N2SY7OGOE6phBldDY_DAovJ8Y1yR9Xii Utilise the kselftest harmness to implement tests for the guard page implementation. We start by implement basic tests asserting that guard pages can be established (poisoned), cleared (remedied) and that touching poisoned pages result in SIGSEGV. We also assert that, in remedying a range, non-poison pages remain intact. We then examine different operations on regions containing poison markers behave to ensure correct behaviour: * Operations over multiple VMAs operate as expected. * Invoking MADV_GUARD_POISION / MADV_GUARD_REMEDY via process_madvise() in batches works correctly. * Ensuring that munmap() correctly tears down poison markers. * Using mprotect() to adjust protection bits does not in any way override or cause issues with poison markers. * Ensuring that splitting and merging VMAs around poison markers causes no issue - i.e. that a marker which 'belongs' to one VMA can function just as well 'belonging' to another. * Ensuring that madvise(..., MADV_DONTNEED) does not remove poison markers. * Ensuring that mlock()'ing a range containing poison markers does not cause issues. * Ensuring that mremap() can move a poisoned range and retain poison markers. * Ensuring that mremap() can expand a poisoned range and retain poison markers (perhaps moving the range). * Ensuring that mremap() can shrink a poisoned range and retain poison markers. * Ensuring that forking a process correctly retains poison markers. * Ensuring that forking a VMA with VM_WIPEONFORK set behaves sanely. * Ensuring that lazyfree simply clears poison markers. * Ensuring that userfaultfd can co-exist with guard pages. * Ensuring that madvise(..., MADV_POPULATE_READ) and madvise(..., MADV_POPULATE_WRITE) error out when encountering poison markers. * Ensuring that madvise(..., MADV_COLD) and madvise(..., MADV_PAGEOUT) do not remove poison markers. Signed-off-by: Lorenzo Stoakes --- tools/testing/selftests/mm/.gitignore | 1 + tools/testing/selftests/mm/Makefile | 1 + tools/testing/selftests/mm/guard-pages.c | 1168 ++++++++++++++++++++++ 3 files changed, 1170 insertions(+) create mode 100644 tools/testing/selftests/mm/guard-pages.c diff --git a/tools/testing/selftests/mm/.gitignore b/tools/testing/selftests/mm/.gitignore index 689bbd520296..8f01f4da1c0d 100644 --- a/tools/testing/selftests/mm/.gitignore +++ b/tools/testing/selftests/mm/.gitignore @@ -54,3 +54,4 @@ droppable hugetlb_dio pkey_sighandler_tests_32 pkey_sighandler_tests_64 +guard-pages diff --git a/tools/testing/selftests/mm/Makefile b/tools/testing/selftests/mm/Makefile index 02e1204971b0..15c734d6cfec 100644 --- a/tools/testing/selftests/mm/Makefile +++ b/tools/testing/selftests/mm/Makefile @@ -79,6 +79,7 @@ TEST_GEN_FILES += hugetlb_fault_after_madv TEST_GEN_FILES += hugetlb_madv_vs_map TEST_GEN_FILES += hugetlb_dio TEST_GEN_FILES += droppable +TEST_GEN_FILES += guard-pages ifneq ($(ARCH),arm64) TEST_GEN_FILES += soft-dirty diff --git a/tools/testing/selftests/mm/guard-pages.c b/tools/testing/selftests/mm/guard-pages.c new file mode 100644 index 000000000000..2ab0ff3ba5a0 --- /dev/null +++ b/tools/testing/selftests/mm/guard-pages.c @@ -0,0 +1,1168 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#define _GNU_SOURCE +#include "../kselftest_harness.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* These may not yet be available in the uAPI so define if not. */ + +#ifndef MADV_GUARD_POISON +#define MADV_GUARD_POISON 102 +#endif + +#ifndef MADV_GUARD_UNPOISON +#define MADV_GUARD_UNPOISON 103 +#endif + +volatile bool signal_jump_set; +sigjmp_buf signal_jmp_buf; + +static int userfaultfd(int flags) +{ + return syscall(SYS_userfaultfd, flags); +} + +static void handle_fatal(int c) +{ + if (!signal_jump_set) + return; + + siglongjmp(signal_jmp_buf, c); +} + +static int pidfd_open(pid_t pid, unsigned int flags) +{ + return syscall(SYS_pidfd_open, pid, flags); +} + +/* + * Enable our signal catcher and try to read/write the specified buffer. The + * return value indicates whether the read/write succeeds without a fatal + * signal. + */ +static bool try_access_buf(char *ptr, bool write) +{ + bool failed; + + /* Tell signal handler to jump back here on fatal signal. */ + signal_jump_set = true; + /* If a fatal signal arose, we will jump back here and failed is set. */ + failed = sigsetjmp(signal_jmp_buf, 0) != 0; + + if (!failed) { + if (write) { + *ptr = 'x'; + } else { + const volatile char *chr = ptr; + + /* Force read. */ + (void)*chr; + } + } + + signal_jump_set = false; + return !failed; +} + +/* Try and read from a buffer, return true if no fatal signal. */ +static bool try_read_buf(char *ptr) +{ + return try_access_buf(ptr, false); +} + +/* Try and write to a buffer, return true if no fatal signal. */ +static bool try_write_buf(char *ptr) +{ + return try_access_buf(ptr, true); +} + +/* + * Try and BOTH read from AND write to a buffer, return true if BOTH operations + * succeed. + */ +static bool try_read_write_buf(char *ptr) +{ + return try_read_buf(ptr) && try_write_buf(ptr); +} + +FIXTURE(guard_pages) +{ + unsigned long page_size; +}; + +FIXTURE_SETUP(guard_pages) +{ + struct sigaction act = { + .sa_handler = &handle_fatal, + .sa_flags = SA_NODEFER, + }; + + sigemptyset(&act.sa_mask); + if (sigaction(SIGSEGV, &act, NULL)) { + perror("sigaction"); + ksft_exit_fail(); + } + + self->page_size = (unsigned long)sysconf(_SC_PAGESIZE); +}; + +FIXTURE_TEARDOWN(guard_pages) +{ + struct sigaction act = { + .sa_handler = SIG_DFL, + .sa_flags = SA_NODEFER, + }; + + sigemptyset(&act.sa_mask); + sigaction(SIGSEGV, &act, NULL); +} + +TEST_F(guard_pages, basic) +{ + const unsigned long NUM_PAGES = 10; + const unsigned long page_size = self->page_size; + char *ptr; + int i; + + ptr = mmap(NULL, NUM_PAGES * page_size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Trivially assert we can touch the first page. */ + ASSERT_TRUE(try_read_write_buf(ptr)); + + ASSERT_EQ(madvise(ptr, page_size, MADV_GUARD_POISON), 0); + + /* Establish that 1st page SIGSEGV's. */ + ASSERT_FALSE(try_read_write_buf(ptr)); + + /* Ensure we can touch everything else.*/ + for (i = 1; i < NUM_PAGES; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Establish a guard page at the end of the mapping. */ + ASSERT_EQ(madvise(&ptr[(NUM_PAGES - 1) * page_size], page_size, + MADV_GUARD_POISON), 0); + + /* Check that both guard pages result in SIGSEGV. */ + ASSERT_FALSE(try_read_write_buf(ptr)); + ASSERT_FALSE(try_read_write_buf(&ptr[(NUM_PAGES - 1) * page_size])); + + /* Unpoison the first. */ + ASSERT_FALSE(madvise(ptr, page_size, MADV_GUARD_UNPOISON)); + + /* Make sure we can touch it. */ + ASSERT_TRUE(try_read_write_buf(ptr)); + + /* Unpoison the last. */ + ASSERT_FALSE(madvise(&ptr[(NUM_PAGES - 1) * page_size], page_size, + MADV_GUARD_UNPOISON)); + + /* Make sure we can touch it. */ + ASSERT_TRUE(try_read_write_buf(&ptr[(NUM_PAGES - 1) * page_size])); + + /* + * Test setting a _range_ of pages, namely the first 3. The first of + * these be faulted in, so this also tests that we can poison backed + * pages. + */ + ASSERT_EQ(madvise(ptr, 3 * page_size, MADV_GUARD_POISON), 0); + + /* Make sure they are all poisoned. */ + for (i = 0; i < 3; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Make sure the rest are not. */ + for (i = 3; i < NUM_PAGES; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Unpoison them. */ + ASSERT_EQ(madvise(ptr, NUM_PAGES * page_size, MADV_GUARD_UNPOISON), 0); + + /* Now make sure we can touch everything. */ + for (i = 0; i < NUM_PAGES; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Now unpoison everything, make sure we don't remove existing entries */ + ASSERT_EQ(madvise(ptr, NUM_PAGES * page_size, MADV_GUARD_UNPOISON), 0); + + for (i = 0; i < NUM_PAGES * page_size; i += page_size) { + ASSERT_EQ(ptr[i], 'x'); + } + + ASSERT_EQ(munmap(ptr, NUM_PAGES * page_size), 0); +} + +/* Assert that operations applied across multiple VMAs work as expected. */ +TEST_F(guard_pages, multi_vma) +{ + const unsigned long page_size = self->page_size; + char *ptr_region, *ptr, *ptr1, *ptr2, *ptr3; + int i; + + /* Reserve a 100 page region over which we can install VMAs. */ + ptr_region = mmap(NULL, 100 * page_size, PROT_NONE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr_region, MAP_FAILED); + + /* Place a VMA of 10 pages size at the start of the region. */ + ptr1 = mmap(ptr_region, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr1, MAP_FAILED); + + /* Place a VMA of 5 pages size 50 pages into the region. */ + ptr2 = mmap(&ptr_region[50 * page_size], 5 * page_size, + PROT_READ | PROT_WRITE, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr2, MAP_FAILED); + + /* Place a VMA of 20 pages size at the end of the region. */ + ptr3 = mmap(&ptr_region[80 * page_size], 20 * page_size, + PROT_READ | PROT_WRITE, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr3, MAP_FAILED); + + /* Unmap gaps. */ + ASSERT_EQ(munmap(&ptr_region[10 * page_size], 40 * page_size), 0); + ASSERT_EQ(munmap(&ptr_region[55 * page_size], 25 * page_size), 0); + + /* + * We end up with VMAs like this: + * + * 0 10 .. 50 55 .. 80 100 + * [---] [---] [---] + */ + + /* Now poison the whole range and make sure all VMAs are poisoned. */ + + /* + * madvise() is certifiable and lets you perform operations over gaps, + * everything works, but it indicates an error and errno is set to + * -ENOMEM. Also if anything runs out of memory it is set to + * -ENOMEM. You are meant to guess which is which. + */ + ASSERT_EQ(madvise(ptr_region, 100 * page_size, MADV_GUARD_POISON), -1); + ASSERT_EQ(errno, ENOMEM); + + for (i = 0; i < 10; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr1[i * page_size])); + } + + for (i = 0; i < 5; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr2[i * page_size])); + } + + for (i = 0; i < 20; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr3[i * page_size])); + } + + /* Now unpoison the range and assert the opposite. */ + + ASSERT_EQ(madvise(ptr_region, 100 * page_size, MADV_GUARD_UNPOISON), -1); + ASSERT_EQ(errno, ENOMEM); + + for (i = 0; i < 10; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr1[i * page_size])); + } + + for (i = 0; i < 5; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr2[i * page_size])); + } + + for (i = 0; i < 20; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr3[i * page_size])); + } + + /* Now map incompatible VMAs in the gaps. */ + ptr = mmap(&ptr_region[10 * page_size], 40 * page_size, + PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + ptr = mmap(&ptr_region[55 * page_size], 25 * page_size, + PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* + * We end up with VMAs like this: + * + * 0 10 .. 50 55 .. 80 100 + * [---][xxxx][---][xxxx][---] + * + * Where 'x' signifies VMAs that cannot be merged with those adjacent to + * them. + */ + + /* Multiple VMAs adjacent to one another should result in no error. */ + ASSERT_EQ(madvise(ptr_region, 100 * page_size, MADV_GUARD_POISON), 0); + for (i = 0; i < 100; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr_region[i * page_size])); + } + ASSERT_EQ(madvise(ptr_region, 100 * page_size, MADV_GUARD_UNPOISON), 0); + for (i = 0; i < 100; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr_region[i * page_size])); + } + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr_region, 100 * page_size), 0); +} + +/* + * Assert that batched operations performed using process_madvise() work as + * expected. + */ +TEST_F(guard_pages, process_madvise) +{ + const unsigned long page_size = self->page_size; + pid_t pid = getpid(); + int pidfd = pidfd_open(pid, 0); + char *ptr_region, *ptr1, *ptr2, *ptr3; + ssize_t count; + struct iovec vec[6]; + + ASSERT_NE(pidfd, -1); + + /* Reserve region to map over. */ + ptr_region = mmap(NULL, 100 * page_size, PROT_NONE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr_region, MAP_FAILED); + + /* 10 pages offset 1 page into reserve region. */ + ptr1 = mmap(&ptr_region[page_size], 10 * page_size, + PROT_READ | PROT_WRITE, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr1, MAP_FAILED); + /* We want poison markers at start/end of each VMA. */ + vec[0].iov_base = ptr1; + vec[0].iov_len = page_size; + vec[1].iov_base = &ptr1[9 * page_size]; + vec[1].iov_len = page_size; + + /* 5 pages offset 50 pages into reserve region. */ + ptr2 = mmap(&ptr_region[50 * page_size], 5 * page_size, + PROT_READ | PROT_WRITE, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr2, MAP_FAILED); + vec[2].iov_base = ptr2; + vec[2].iov_len = page_size; + vec[3].iov_base = &ptr2[4 * page_size]; + vec[3].iov_len = page_size; + + /* 20 pages offset 79 pages into reserve region. */ + ptr3 = mmap(&ptr_region[79 * page_size], 20 * page_size, + PROT_READ | PROT_WRITE, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr3, MAP_FAILED); + vec[4].iov_base = ptr3; + vec[4].iov_len = page_size; + vec[5].iov_base = &ptr3[19 * page_size]; + vec[5].iov_len = page_size; + + /* Free surrounding VMAs. */ + ASSERT_EQ(munmap(ptr_region, page_size), 0); + ASSERT_EQ(munmap(&ptr_region[11 * page_size], 39 * page_size), 0); + ASSERT_EQ(munmap(&ptr_region[55 * page_size], 24 * page_size), 0); + ASSERT_EQ(munmap(&ptr_region[99 * page_size], page_size), 0); + + /* Now poison in one step. */ + count = process_madvise(pidfd, vec, 6, MADV_GUARD_POISON, 0); + + /* OK we don't have permission to do this, skip. */ + if (count == -1 && errno == EPERM) + ksft_exit_skip("No process_madvise() permissions\n"); + + /* Returns the number of bytes advised. */ + ASSERT_EQ(count, 6 * page_size); + + /* Now make sure the poisoning was applied. */ + + ASSERT_FALSE(try_read_write_buf(ptr1)); + ASSERT_FALSE(try_read_write_buf(&ptr1[9 * page_size])); + + ASSERT_FALSE(try_read_write_buf(ptr2)); + ASSERT_FALSE(try_read_write_buf(&ptr2[4 * page_size])); + + ASSERT_FALSE(try_read_write_buf(ptr3)); + ASSERT_FALSE(try_read_write_buf(&ptr3[19 * page_size])); + + /* Now do the same with unpoison... */ + count = process_madvise(pidfd, vec, 6, MADV_GUARD_UNPOISON, 0); + + /* ...and everything should now succeed. */ + + ASSERT_TRUE(try_read_write_buf(ptr1)); + ASSERT_TRUE(try_read_write_buf(&ptr1[9 * page_size])); + + ASSERT_TRUE(try_read_write_buf(ptr2)); + ASSERT_TRUE(try_read_write_buf(&ptr2[4 * page_size])); + + ASSERT_TRUE(try_read_write_buf(ptr3)); + ASSERT_TRUE(try_read_write_buf(&ptr3[19 * page_size])); + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr1, 10 * page_size), 0); + ASSERT_EQ(munmap(ptr2, 5 * page_size), 0); + ASSERT_EQ(munmap(ptr3, 20 * page_size), 0); + close(pidfd); +} + +/* Assert that unmapping ranges does not leave poison behind. */ +TEST_F(guard_pages, munmap) +{ + const unsigned long page_size = self->page_size; + char *ptr, *ptr_new1, *ptr_new2; + + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Poison first and last pages. */ + ASSERT_EQ(madvise(ptr, page_size, MADV_GUARD_POISON), 0); + ASSERT_EQ(madvise(&ptr[9 * page_size], page_size, MADV_GUARD_POISON), 0); + + /* Assert that they are poisoned. */ + ASSERT_FALSE(try_read_write_buf(ptr)); + ASSERT_FALSE(try_read_write_buf(&ptr[9 * page_size])); + + /* Unmap them. */ + ASSERT_EQ(munmap(ptr, page_size), 0); + ASSERT_EQ(munmap(&ptr[9 * page_size], page_size), 0); + + /* Map over them.*/ + ptr_new1 = mmap(ptr, page_size, PROT_READ | PROT_WRITE, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr_new1, MAP_FAILED); + ptr_new2 = mmap(&ptr[9 * page_size], page_size, PROT_READ | PROT_WRITE, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr_new2, MAP_FAILED); + + /* Assert that they are now not poisoned. */ + ASSERT_TRUE(try_read_write_buf(ptr_new1)); + ASSERT_TRUE(try_read_write_buf(ptr_new2)); + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr, 10 * page_size), 0); +} + +/* Assert that mprotect() operations have no bearing on guard poison markers. */ +TEST_F(guard_pages, mprotect) +{ + const unsigned long page_size = self->page_size; + char *ptr; + int i; + + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Poison the middle of the range. */ + ASSERT_EQ(madvise(&ptr[5 * page_size], 2 * page_size, + MADV_GUARD_POISON), 0); + + /* Assert that it is indeed poisoned. */ + ASSERT_FALSE(try_read_write_buf(&ptr[5 * page_size])); + ASSERT_FALSE(try_read_write_buf(&ptr[6 * page_size])); + + /* Now make these pages read-only. */ + ASSERT_EQ(mprotect(&ptr[5 * page_size], 2 * page_size, PROT_READ), 0); + + /* Make sure the range is still poisoned. */ + ASSERT_FALSE(try_read_buf(&ptr[5 * page_size])); + ASSERT_FALSE(try_read_buf(&ptr[6 * page_size])); + + /* Make sure we can poison again without issue.*/ + ASSERT_EQ(madvise(&ptr[5 * page_size], 2 * page_size, + MADV_GUARD_POISON), 0); + + /* Make sure the range is, yet again, still poisoned. */ + ASSERT_FALSE(try_read_buf(&ptr[5 * page_size])); + ASSERT_FALSE(try_read_buf(&ptr[6 * page_size])); + + /* Now unpoison the whole range. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_GUARD_UNPOISON), 0); + + /* Make sure the whole range is readable. */ + for (i = 0; i < 10; i++) { + ASSERT_TRUE(try_read_buf(&ptr[i * page_size])); + } + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr, 10 * page_size), 0); +} + +/* Split and merge VMAs and make sure guard pages still behave. */ +TEST_F(guard_pages, split_merge) +{ + const unsigned long page_size = self->page_size; + char *ptr, *ptr_new; + int i; + + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Poison the whole range. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_GUARD_POISON), 0); + + /* Make sure the whole range is poisoned. */ + for (i = 0; i < 10; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Now unmap some pages in the range so we split. */ + ASSERT_EQ(munmap(&ptr[2 * page_size], page_size), 0); + ASSERT_EQ(munmap(&ptr[5 * page_size], page_size), 0); + ASSERT_EQ(munmap(&ptr[8 * page_size], page_size), 0); + + /* Make sure the remaining ranges are poisoned post-split. */ + for (i = 0; i < 2; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + for (i = 2; i < 5; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + for (i = 6; i < 8; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + for (i = 9; i < 10; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Now map them again - the unmap will have cleared the poison. */ + ptr_new = mmap(&ptr[2 * page_size], page_size, PROT_READ | PROT_WRITE, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr_new, MAP_FAILED); + ptr_new = mmap(&ptr[5 * page_size], page_size, PROT_READ | PROT_WRITE, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr_new, MAP_FAILED); + ptr_new = mmap(&ptr[8 * page_size], page_size, PROT_READ | PROT_WRITE, + MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr_new, MAP_FAILED); + + /* Now make sure poisoning is as expected. */ + for (i = 0; i < 10; i++) { + bool result = try_read_write_buf(&ptr[i * page_size]); + + if (i == 2 || i == 5 || i == 8) { + ASSERT_TRUE(result); + } else { + ASSERT_FALSE(result); + } + } + + /* Now poison everything again. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_GUARD_POISON), 0); + + /* Make sure the whole range is poisoned. */ + for (i = 0; i < 10; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Now split the range into three. */ + ASSERT_EQ(mprotect(ptr, 3 * page_size, PROT_READ), 0); + ASSERT_EQ(mprotect(&ptr[7 * page_size], 3 * page_size, PROT_READ), 0); + + /* Make sure the whole range is poisoned for read. */ + for (i = 0; i < 10; i++) { + ASSERT_FALSE(try_read_buf(&ptr[i * page_size])); + } + + /* Now reset protection bits so we merge the whole thing. */ + ASSERT_EQ(mprotect(ptr, 3 * page_size, PROT_READ | PROT_WRITE), 0); + ASSERT_EQ(mprotect(&ptr[7 * page_size], 3 * page_size, + PROT_READ | PROT_WRITE), 0); + + /* Make sure the whole range is still poisoned. */ + for (i = 0; i < 10; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Split range into 3 again... */ + ASSERT_EQ(mprotect(ptr, 3 * page_size, PROT_READ), 0); + ASSERT_EQ(mprotect(&ptr[7 * page_size], 3 * page_size, PROT_READ), 0); + + /* ...and unpoison the whole range. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_GUARD_UNPOISON), 0); + + /* Make sure the whole range is remedied for read. */ + for (i = 0; i < 10; i++) { + ASSERT_TRUE(try_read_buf(&ptr[i * page_size])); + } + + /* Merge them again. */ + ASSERT_EQ(mprotect(ptr, 3 * page_size, PROT_READ | PROT_WRITE), 0); + ASSERT_EQ(mprotect(&ptr[7 * page_size], 3 * page_size, + PROT_READ | PROT_WRITE), 0); + + /* Now ensure the merged range is remedied for read/write. */ + for (i = 0; i < 10; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr, 10 * page_size), 0); +} + +/* Assert that MADV_DONTNEED does not remove guard poison markers. */ +TEST_F(guard_pages, dontneed) +{ + const unsigned long page_size = self->page_size; + char *ptr; + int i; + + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Back the whole range. */ + for (i = 0; i < 10; i++) { + ptr[i * page_size] = 'y'; + } + + /* Poison every other page. */ + for (i = 0; i < 10; i += 2) { + ASSERT_EQ(madvise(&ptr[i * page_size], + page_size, MADV_GUARD_POISON), 0); + } + + /* Indicate that we don't need any of the range. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_DONTNEED), 0); + + /* Check to ensure poison markers are still in place. */ + for (i = 0; i < 10; i++) { + bool result = try_read_buf(&ptr[i * page_size]); + + if (i % 2 == 0) { + ASSERT_FALSE(result); + } else { + ASSERT_TRUE(result); + /* Make sure we really did get reset to zero page. */ + ASSERT_EQ(ptr[i * page_size], '\0'); + } + + /* Now write... */ + result = try_write_buf(&ptr[i * page_size]); + + /* ...and make sure same result. */ + if (i % 2 == 0) { + ASSERT_FALSE(result); + } else { + ASSERT_TRUE(result); + } + } + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr, 10 * page_size), 0); +} + +/* Assert that mlock()'ed pages work correctly with poison markers. */ +TEST_F(guard_pages, mlock) +{ + const unsigned long page_size = self->page_size; + char *ptr; + int i; + + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Populate. */ + for (i = 0; i < 10; i++) { + ptr[i * page_size] = 'y'; + } + + /* Lock. */ + ASSERT_EQ(mlock(ptr, 10 * page_size), 0); + + /* Now try to poison, should fail with EINVAL. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_GUARD_POISON), -1); + ASSERT_EQ(errno, EINVAL); + + /* OK unlock. */ + ASSERT_EQ(munlock(ptr, 10 * page_size), 0); + + /* Poison first half of range, should now succeed. */ + ASSERT_EQ(madvise(ptr, 5 * page_size, MADV_GUARD_POISON), 0); + + /* Make sure poison works. */ + for (i = 0; i < 10; i++) { + bool result = try_read_write_buf(&ptr[i * page_size]); + + if (i < 5) { + ASSERT_FALSE(result); + } else { + ASSERT_TRUE(result); + ASSERT_EQ(ptr[i * page_size], 'x'); + } + } + + /* + * Now lock the latter part of the range. We can't lock the poisoned + * pages, as this would result in the pages being populated and the + * poisoning would cause this to error out. + */ + ASSERT_EQ(mlock(&ptr[5 * page_size], 5 * page_size), 0); + + /* + * Now unpoison, we do not permit mlock()'d ranges to be remedied as it is + * a non-destructive operation. + */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_GUARD_UNPOISON), 0); + + /* Now check that everything is remedied. */ + for (i = 0; i < 10; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr, 10 * page_size), 0); +} + +/* + * Assert that moving, extending and shrinking memory via mremap() retains + * poison markers where possible. + * + * - Moving a mapping alone should retain markers as they are. + */ +TEST_F(guard_pages, mremap_move) +{ + const unsigned long page_size = self->page_size; + char *ptr, *ptr_new; + + /* Map 5 pages. */ + ptr = mmap(NULL, 5 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Place poison markers at both ends of the 5 page span. */ + ASSERT_EQ(madvise(ptr, page_size, MADV_GUARD_POISON), 0); + ASSERT_EQ(madvise(&ptr[4 * page_size], page_size, MADV_GUARD_POISON), 0); + + /* Make sure the poison is in effect. */ + ASSERT_FALSE(try_read_write_buf(ptr)); + ASSERT_FALSE(try_read_write_buf(&ptr[4 * page_size])); + + /* Map a new region we will move this range into. Doing this ensures + * that we have reserved a range to map into. + */ + ptr_new = mmap(NULL, 5 * page_size, PROT_NONE, MAP_ANON | MAP_PRIVATE, + -1, 0); + ASSERT_NE(ptr_new, MAP_FAILED); + + ASSERT_EQ(mremap(ptr, 5 * page_size, 5 * page_size, + MREMAP_MAYMOVE | MREMAP_FIXED, ptr_new), ptr_new); + + /* Make sure the poison is retained. */ + ASSERT_FALSE(try_read_write_buf(ptr_new)); + ASSERT_FALSE(try_read_write_buf(&ptr_new[4 * page_size])); + + /* + * Clean up - we only need reference the new pointer as we overwrote the + * PROT_NONE range and moved the existing one. + */ + munmap(ptr_new, 5 * page_size); +} + +/* + * Assert that moving, extending and shrinking memory via mremap() retains + * poison markers where possible. + * + * - Expanding should retain, only now in different position. The user will have + * to unpoison manually to fix up (they'd have to do the same if it were a + * PROT_NONE mapping) + */ +TEST_F(guard_pages, mremap_expand) +{ + const unsigned long page_size = self->page_size; + char *ptr, *ptr_new; + + /* Map 10 pages... */ + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + /* ...But unmap the last 5 so we can ensure we can expand into them. */ + ASSERT_EQ(munmap(&ptr[5 * page_size], 5 * page_size), 0); + + /* Place poison markers at both ends of the 5 page span. */ + ASSERT_EQ(madvise(ptr, page_size, MADV_GUARD_POISON), 0); + ASSERT_EQ(madvise(&ptr[4 * page_size], page_size, MADV_GUARD_POISON), 0); + + /* Make sure the poison is in effect. */ + ASSERT_FALSE(try_read_write_buf(ptr)); + ASSERT_FALSE(try_read_write_buf(&ptr[4 * page_size])); + + /* Now expand to 10 pages. */ + ptr = mremap(ptr, 5 * page_size, 10 * page_size, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Make sure the poison is retained in its original positions. */ + ASSERT_FALSE(try_read_write_buf(ptr)); + ASSERT_FALSE(try_read_write_buf(&ptr[4 * page_size])); + + /* Reserve a region which we can move to and expand into. */ + ptr_new = mmap(NULL, 20 * page_size, PROT_NONE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr_new, MAP_FAILED); + + /* Now move and expand into it. */ + ptr = mremap(ptr, 10 * page_size, 20 * page_size, + MREMAP_MAYMOVE | MREMAP_FIXED, ptr_new); + ASSERT_EQ(ptr, ptr_new); + + /* Again, make sure the poison is retained in its original + * positions. */ + ASSERT_FALSE(try_read_write_buf(ptr)); + ASSERT_FALSE(try_read_write_buf(&ptr[4 * page_size])); + + /* + * A real user would have to unpoison, but would reasonably expect all + * characteristics of the mapping to be retained, including poison + * markers. + */ + + /* Cleanup. */ + munmap(ptr, 20 * page_size); +} +/* + * Assert that moving, extending and shrinking memory via mremap() retains + * poison markers where possible. + * + * - Shrinking will result in markers that are shrunk over being removed. Again, + * if the user were using a PROT_NONE mapping they'd have to manually fix this + * up also so this is OK. + */ +TEST_F(guard_pages, mremap_shrink) +{ + const unsigned long page_size = self->page_size; + char *ptr; + int i; + + /* Map 5 pages. */ + ptr = mmap(NULL, 5 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Place poison markers at both ends of the 5 page span. */ + ASSERT_EQ(madvise(ptr, page_size, MADV_GUARD_POISON), 0); + ASSERT_EQ(madvise(&ptr[4 * page_size], page_size, MADV_GUARD_POISON), 0); + + /* Make sure the poison is in effect. */ + ASSERT_FALSE(try_read_write_buf(ptr)); + ASSERT_FALSE(try_read_write_buf(&ptr[4 * page_size])); + + /* Now shrink to 3 pages. */ + ptr = mremap(ptr, 5 * page_size, 3 * page_size, MREMAP_MAYMOVE); + ASSERT_NE(ptr, MAP_FAILED); + + /* We expect the poison marker at the start to be retained... */ + ASSERT_FALSE(try_read_write_buf(ptr)); + + /* ...But remaining pages will not have poison markers. */ + for (i = 1; i < 3; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr[i + page_size])); + } + + /* + * As with expansion, a real user would have to unpoison and fixup. But + * you'd have to do similar manual things with PROT_NONE mappings too. + */ + + /* + * If we expand back to the original size, the end marker will, of + * course, no longer be present. + */ + ptr = mremap(ptr, 3 * page_size, 5 * page_size, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Again, we expect the poison marker at the start to be retained... */ + ASSERT_FALSE(try_read_write_buf(ptr)); + + /* ...But remaining pages will not have poison markers. */ + for (i = 1; i < 5; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr[i + page_size])); + } + + /* Cleanup. */ + munmap(ptr, 5 * page_size); +} + +/* + * Assert that forking a process with VMAs that do not have VM_WIPEONFORK set + * retain guard pages. + */ +TEST_F(guard_pages, fork) +{ + const unsigned long page_size = self->page_size; + char *ptr; + pid_t pid; + int i; + + /* Map 10 pages. */ + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Poison the first 5 pages. */ + ASSERT_EQ(madvise(ptr, 5 * page_size, MADV_GUARD_POISON), 0); + + pid = fork(); + ASSERT_NE(pid, -1); + if (!pid) { + /* This is the child process now. */ + + /* Assert that the poisoning is in effect. */ + for (i = 0; i < 10; i++) { + bool result = try_read_write_buf(&ptr[i * page_size]); + + if (i < 5) { + ASSERT_FALSE(result); + } else { + ASSERT_TRUE(result); + } + } + + /* Now unpoison the range.*/ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_GUARD_UNPOISON), 0); + + exit(0); + } + + /* Parent process. */ + + /* Parent simply waits on child. */ + waitpid(pid, NULL, 0); + + /* Child unpoison does not impact parent page table state. */ + for (i = 0; i < 10; i++) { + bool result = try_read_write_buf(&ptr[i * page_size]); + + if (i < 5) { + ASSERT_FALSE(result); + } else { + ASSERT_TRUE(result); + } + } + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr, 10 * page_size), 0); +} + +/* + * Assert that forking a process with VMAs that do have VM_WIPEONFORK set + * behave as expected. + */ +TEST_F(guard_pages, fork_wipeonfork) +{ + const unsigned long page_size = self->page_size; + char *ptr; + pid_t pid; + int i; + + /* Map 10 pages. */ + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Mark wipe on fork. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_WIPEONFORK), 0); + + /* Poison the first 5 pages. */ + ASSERT_EQ(madvise(ptr, 5 * page_size, MADV_GUARD_POISON), 0); + + pid = fork(); + ASSERT_NE(pid, -1); + if (!pid) { + /* This is the child process now. */ + + /* Poison will have been wiped. */ + for (i = 0; i < 10; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr[i * page_size])); + } + + exit(0); + } + + /* Parent process. */ + + waitpid(pid, NULL, 0); + + /* Poison should be in effect.*/ + for (i = 0; i < 10; i++) { + bool result = try_read_write_buf(&ptr[i * page_size]); + + if (i < 5) { + ASSERT_FALSE(result); + } else { + ASSERT_TRUE(result); + } + } + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr, 10 * page_size), 0); +} + +/* Ensure that MADV_FREE frees poison entries as expected. */ +TEST_F(guard_pages, lazyfree) +{ + const unsigned long page_size = self->page_size; + char *ptr; + int i; + + /* Map 10 pages. */ + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Poison range. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_GUARD_POISON), 0); + + /* Ensure poisoned. */ + for (i = 0; i < 10; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Lazyfree range. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_FREE), 0); + + /* This should simply clear the poison markers. */ + for (i = 0; i < 10; i++) { + ASSERT_TRUE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr, 10 * page_size), 0); +} + +/* Ensure that MADV_POPULATE_READ, MADV_POPULATE_WRITE behave as expected. */ +TEST_F(guard_pages, populate) +{ + const unsigned long page_size = self->page_size; + char *ptr; + + /* Map 10 pages. */ + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Poison range. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_GUARD_POISON), 0); + + /* Populate read should error out... */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_POPULATE_READ), -1); + ASSERT_EQ(errno, EFAULT); + + /* ...as should populate write. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_POPULATE_WRITE), -1); + ASSERT_EQ(errno, EFAULT); + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr, 10 * page_size), 0); +} + +/* Ensure that MADV_COLD, MADV_PAGEOUT do not remove poison markers. */ +TEST_F(guard_pages, cold_pageout) +{ + const unsigned long page_size = self->page_size; + char *ptr; + int i; + + /* Map 10 pages. */ + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Poison range. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_GUARD_POISON), 0); + + /* Ensured poisoned. */ + for (i = 0; i < 10; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Now mark cold. This should have no impact on poison markers. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_COLD), 0); + + /* Should remain poisoned. */ + for (i = 0; i < 10; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + + /* OK, now page out. This should equally, have no effect on markers. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_PAGEOUT), 0); + + /* Should remain poisoned. */ + for (i = 0; i < 10; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Cleanup. */ + ASSERT_EQ(munmap(ptr, 10 * page_size), 0); +} + +/* Ensure that guard pages do not break userfaultd. */ +TEST_F(guard_pages, uffd) +{ + const unsigned long page_size = self->page_size; + int uffd; + char *ptr; + int i; + struct uffdio_api api = { + .api = UFFD_API, + .features = 0, + }; + struct uffdio_register reg; + struct uffdio_range range; + + /* Set up uffd. */ + uffd = userfaultfd(0); + if (uffd == -1 && errno == EPERM) + ksft_exit_skip("No uffd permissions\n"); + ASSERT_NE(uffd, -1); + + ASSERT_EQ(ioctl(uffd, UFFDIO_API, &api), 0); + + /* Map 10 pages. */ + ptr = mmap(NULL, 10 * page_size, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_PRIVATE, -1, 0); + ASSERT_NE(ptr, MAP_FAILED); + + /* Register the range with uffd. */ + range.start = (unsigned long)ptr; + range.len = 10 * page_size; + reg.range = range; + reg.mode = UFFDIO_REGISTER_MODE_MISSING; + ASSERT_EQ(ioctl(uffd, UFFDIO_REGISTER, ®), 0); + + /* Poison the range. This should not trigger the uffd. */ + ASSERT_EQ(madvise(ptr, 10 * page_size, MADV_GUARD_POISON), 0); + + /* The poisoning should behave as usual with no uffd intervention. */ + for (i = 0; i < 10; i++) { + ASSERT_FALSE(try_read_write_buf(&ptr[i * page_size])); + } + + /* Cleanup. */ + ASSERT_EQ(ioctl(uffd, UFFDIO_UNREGISTER, &range), 0); + close(uffd); + ASSERT_EQ(munmap(ptr, 10 * page_size), 0); +} + +TEST_HARNESS_MAIN