From patchwork Sat May 4 00:30:02 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13653688 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 50CE6C25B10 for ; Sat, 4 May 2024 00:30:15 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D5FCB6B0089; Fri, 3 May 2024 20:30:14 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D10EB6B008C; Fri, 3 May 2024 20:30:14 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id BB0906B0095; Fri, 3 May 2024 20:30:14 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id 96C9C6B0089 for ; Fri, 3 May 2024 20:30:14 -0400 (EDT) Received: from smtpin08.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 0CDBB801F1 for ; Sat, 4 May 2024 00:30:14 +0000 (UTC) X-FDA: 82078831548.08.1F39338 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf01.hostedemail.com (Postfix) with ESMTP id 5CE4840018 for ; Sat, 4 May 2024 00:30:12 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=irYCdfxY; spf=pass (imf01.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=andrii@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1714782612; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=mLR6nTzoEqbjpMQV+qKzol6P628WFukhTh/ol7MsWXA=; b=pGbQySCE5VSoBMA7IP7HLiylDS5zIag+tVtD0tl4Hw4B7TYmO7SFrbjx6sL/tWfTlAwjND ueqG+HC2mCpoSHASgatctxuZOrrVeHoX3+mW2n8wTYt2nMyE5MZzdjGPI3luIfRSZmCWNZ qjVcI0/edEx/kaM58nA3AyTqeLCPOIs= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=irYCdfxY; spf=pass (imf01.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=andrii@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1714782612; a=rsa-sha256; cv=none; b=7RUTsNWts4r0eMGS7GJTt+BUGZGIDo7Ron+hPB3OKW6SUkJvx2xNdHl6Utx+AlyjpASZPD 7SUgquSSw4NgaHKqwiWp4Jl9YRFIOtzXoERIfQOm/XXSpyC9YVwT5yoHYt/W+9niwuv99U oHgzWpvaFtbHrp8XKun8FADXhHtFunw= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id A093361E38; Sat, 4 May 2024 00:30:11 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3F0E4C116B1; Sat, 4 May 2024 00:30:11 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1714782611; bh=OsmoaOeW12SHNusJpkc/eLJf6KgrIDQoVNy4kZW2PTw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=irYCdfxYU679AgBBu/x1QTRLnZGEvoju3sMUjuymybtvTRyAXO34Tu5LrJt7S78GY OYoR1xjPv5idsNALPBfT7OYYvZAVRvGMyGBnqgsAFCh5iwoF6Zj9+pOMlsxs3vOp35 ImKr2la/Wynbx9YuuVLBqCV/jZZkBNJ4eDaZdYQbwS4A3J1cMls5s+EgtK5ozteiCq /tYaIw5mCGNRgjh3VARmvmzCzLCsA9n6fr/3fi0mORhOWDmjf8DQfjEiOYKVkIq2ts GlWEUVLdgIHoayTxpXLIO+ah6hUvLFFp4Ih08ljZbPW1C39TkwvEBJbUta+rtjK4Vl QEt+UszXK9gRg== From: Andrii Nakryiko To: linux-fsdevel@vger.kernel.org, brauner@kernel.org, viro@zeniv.linux.org.uk, akpm@linux-foundation.org Cc: linux-kernel@vger.kernel.org, bpf@vger.kernel.org, gregkh@linuxfoundation.org, linux-mm@kvack.org, Andrii Nakryiko Subject: [PATCH 1/5] fs/procfs: extract logic for getting VMA name constituents Date: Fri, 3 May 2024 17:30:02 -0700 Message-ID: <20240504003006.3303334-2-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240504003006.3303334-1-andrii@kernel.org> References: <20240504003006.3303334-1-andrii@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 5CE4840018 X-Rspam-User: X-Rspamd-Server: rspam04 X-Stat-Signature: x6s13tp9mouxuy8jqunyyyrixeyhnums X-HE-Tag: 1714782612-182271 X-HE-Meta: U2FsdGVkX1+v/82Y5H/Pw96AhqN0/p8T3dQEjI8UBkxfWM6YEKXQKyh5tvgPUthB7hKuIkHUW7V+ZgVg8fKJNI3QNUcliZjzRd4R+YLPbjsCatl7fLdqW+m+co5/Ism/vfnKfCgZ3dbYZ1Ngct5Owq6IHMdYMil01pRazEO58F2IP4+A9r4X1/9Jge7IM4S8kWah13pGzhanHrdmO5Xk3H4cKVQD2L7fX6xV0UYz+n8wxpDHKqLVUsK0dRiwwSm31f54AKgvVSrnAIwL9Y4wEi6dKIo6RwvibUqjMS51lzd2buXdi5eZD5nrJAmYDYjAstDkGOoiftPixtvsY+LhE9eO1SaUFVfI7o31VHPjMaAYeJieWjqM2VBNNhBEtiMnGd02r0gepfctby9aCcsBCEV0M7Gd9jRuJ968xn64LX63/QkH78Z4o3hEJrXva4Mm7DOVwJtZDzTArk4TaNhdTZkZAQ/AzlCvq0bW/5FWMH8pRO7kRaDVP/QWd3LsL1+q4xOgwFYGXaDZ5GlNwAY8ISqmXgK1izCJU4O3iA1QRvEBrUoOuU8yOwAsrISr4QkcgXcnZeoE20HJVg9kKnAVGsytT2mXhwPsOY5NdHduUjtQEGybJkrm4plcvIkSBs9JnwzBzK+5qZvzfTeWlPOvZzLB8Ek0GN45ehNOwqf37L7phTN8EwiwdIug9AZ6iaeezi/no2QdY7mEF+X4Bqw8UpkJ6zSk7lBjr2aYwoC7WAMMoBDxFbOGW/ta6mZz3DZOCot6yPbcWKAeWXaVbpixTVQZapnpC1AGGmGRTYMhCog8KbbY9MCrlMETnQfx3yNDE729nJcxf0wfcedSMxVBryyG6x1filGTdUil7adRq2pBzswmQceDR0L4/0K+Zu/bUU5F2wSOT1hkiq050uehu6aeZ0Si1neFdOirMvM8CwMQ23dQiDULjbHQ86UWGh3P+NZpXqlnMixliHkKUOT Qq9OvZso CSNHq1k49qbl/6KFjB+GcKfvK0bGFUaDokybHO9RTFoEK0MHXrMVCnzlHyRF9m1tDDHUosGgDOhrQn3hRjLz5R5XbyRTCY/by/peuXJDtuWxzEAgWwWRtb5Dog4jZuEdWc6DVxA21nQYJFjSSzShRd9nFHzAxS6mOyAbx2dl+FWLnCnRk6k47sXh1RO5gZJwySS4xWXyGr0qM2wPFLZNsiUAL4rMEpMWkxYva6FCxTuAJg74= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Extract generic logic to fetch relevant pieces of data to describe VMA name. This could be just some string (either special constant or user-provided), or a string with some formatted wrapping text (e.g., "[anon_shmem:]"), or, commonly, file path. seq_file-based logic has different methods to handle all three cases, but they are currently mixed in with extracting underlying sources of data. This patch splits this into data fetching and data formatting, so that data fetching can be reused later on. There should be no functional changes. Signed-off-by: Andrii Nakryiko --- fs/proc/task_mmu.c | 125 +++++++++++++++++++++++++-------------------- 1 file changed, 71 insertions(+), 54 deletions(-) diff --git a/fs/proc/task_mmu.c b/fs/proc/task_mmu.c index e5a5f015ff03..8e503a1635b7 100644 --- a/fs/proc/task_mmu.c +++ b/fs/proc/task_mmu.c @@ -239,6 +239,67 @@ static int do_maps_open(struct inode *inode, struct file *file, sizeof(struct proc_maps_private)); } +static void get_vma_name(struct vm_area_struct *vma, + const struct path **path, + const char **name, + const char **name_fmt) +{ + struct anon_vma_name *anon_name = vma->vm_mm ? anon_vma_name(vma) : NULL; + + *name = NULL; + *path = NULL; + *name_fmt = NULL; + + /* + * Print the dentry name for named mappings, and a + * special [heap] marker for the heap: + */ + if (vma->vm_file) { + /* + * If user named this anon shared memory via + * prctl(PR_SET_VMA ..., use the provided name. + */ + if (anon_name) { + *name_fmt = "[anon_shmem:%s]"; + *name = anon_name->name; + } else { + *path = file_user_path(vma->vm_file); + } + return; + } + + if (vma->vm_ops && vma->vm_ops->name) { + *name = vma->vm_ops->name(vma); + if (*name) + return; + } + + *name = arch_vma_name(vma); + if (*name) + return; + + if (!vma->vm_mm) { + *name = "[vdso]"; + return; + } + + if (vma_is_initial_heap(vma)) { + *name = "[heap]"; + return; + } + + if (vma_is_initial_stack(vma)) { + *name = "[stack]"; + return; + } + + if (anon_name) { + *name_fmt = "[anon:%s]"; + *name = anon_name->name; + return; + } +} + static void show_vma_header_prefix(struct seq_file *m, unsigned long start, unsigned long end, vm_flags_t flags, unsigned long long pgoff, @@ -262,17 +323,15 @@ static void show_vma_header_prefix(struct seq_file *m, static void show_map_vma(struct seq_file *m, struct vm_area_struct *vma) { - struct anon_vma_name *anon_name = NULL; - struct mm_struct *mm = vma->vm_mm; - struct file *file = vma->vm_file; + const struct path *path; + const char *name_fmt, *name; vm_flags_t flags = vma->vm_flags; unsigned long ino = 0; unsigned long long pgoff = 0; unsigned long start, end; dev_t dev = 0; - const char *name = NULL; - if (file) { + if (vma->vm_file) { const struct inode *inode = file_user_inode(vma->vm_file); dev = inode->i_sb->s_dev; @@ -283,57 +342,15 @@ show_map_vma(struct seq_file *m, struct vm_area_struct *vma) start = vma->vm_start; end = vma->vm_end; show_vma_header_prefix(m, start, end, flags, pgoff, dev, ino); - if (mm) - anon_name = anon_vma_name(vma); - /* - * Print the dentry name for named mappings, and a - * special [heap] marker for the heap: - */ - if (file) { + get_vma_name(vma, &path, &name, &name_fmt); + if (path) { seq_pad(m, ' '); - /* - * If user named this anon shared memory via - * prctl(PR_SET_VMA ..., use the provided name. - */ - if (anon_name) - seq_printf(m, "[anon_shmem:%s]", anon_name->name); - else - seq_path(m, file_user_path(file), "\n"); - goto done; - } - - if (vma->vm_ops && vma->vm_ops->name) { - name = vma->vm_ops->name(vma); - if (name) - goto done; - } - - name = arch_vma_name(vma); - if (!name) { - if (!mm) { - name = "[vdso]"; - goto done; - } - - if (vma_is_initial_heap(vma)) { - name = "[heap]"; - goto done; - } - - if (vma_is_initial_stack(vma)) { - name = "[stack]"; - goto done; - } - - if (anon_name) { - seq_pad(m, ' '); - seq_printf(m, "[anon:%s]", anon_name->name); - } - } - -done: - if (name) { + seq_path(m, path, "\n"); + } else if (name_fmt) { + seq_pad(m, ' '); + seq_printf(m, name_fmt, name); + } else if (name) { seq_pad(m, ' '); seq_puts(m, name); } From patchwork Sat May 4 00:30:03 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13653689 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 39965C4345F for ; Sat, 4 May 2024 00:30:19 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 96D346B0095; Fri, 3 May 2024 20:30:18 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 8F4CF6B0096; Fri, 3 May 2024 20:30:18 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 76E796B0098; Fri, 3 May 2024 20:30:18 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 4F8CE6B0095 for ; Fri, 3 May 2024 20:30:18 -0400 (EDT) Received: from smtpin07.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id C59FA40628 for ; Sat, 4 May 2024 00:30:17 +0000 (UTC) X-FDA: 82078831674.07.1B8CC61 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf12.hostedemail.com (Postfix) with ESMTP id 28FC64001B for ; Sat, 4 May 2024 00:30:15 +0000 (UTC) Authentication-Results: imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=WrZP0Xur; spf=pass (imf12.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=andrii@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1714782616; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=qxANr1QWwiSTkPU2nzb5Qc8wmZTctQI5Ecgcg578qgw=; b=QL/XUuzS4mkjhNEKJR0qKEsgvXDROOVkb4IK+opESQHK77GzalcTDnRkUvRDTM86olL5jl GluEqqbVFpG5Xz1IrxfLBO2U8ZgIjU5Jlx0YDofFZWgsd0SJioZmnBwB71LFYi4NTkzU9j hHYs21akYY5I2ZS6DeVKnKs2TEdOTSE= ARC-Authentication-Results: i=1; imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=WrZP0Xur; spf=pass (imf12.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=andrii@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1714782616; a=rsa-sha256; cv=none; b=RHEzDRyOA9XBZIvXl3wEfvx8ro+wcDY9MrRvbeHAOSEmwg5PICanxUnLuLgMWRYLmii772 v5KHxgsl9PQ7HSXuQqUAGr9getitrkPF70F/omEG5x5fL2zGtosDJayMLLQXNs6YFGld4w oJLMOcJdoZyp5lmqBHrDbyAo6u96peg= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 33C5D61E3E; Sat, 4 May 2024 00:30:15 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8A6F0C4AF1A; Sat, 4 May 2024 00:30:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1714782614; bh=bA1/zohcH7zJsizG/omlxjWAua+BN8I1Y4tME/v2yWE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=WrZP0Xurp/ZbvPWVA9809rCs+L7l7mQdgZ6yIM7b3QF7cm1v8nXt0fYOnCQot2oYV Htd5hqWJbw/65G5zv7QzELJ1Bvtnm7BYXkZvSA3tEF4KIdTGk2Dk1b3JJV2Cb3JuB6 zpi/B66/gqNai2l5MacYx/9thT+2dV7eazaB5jcGfLFlFKkbzp6DAzwWCAmT6+69Fl ZoEWzDkmQ/ilrjCyJOy9DvQp3Kqxrgk22MYfhSewopFKprmBeeGEq7It8VkQzvdQLB /518wopvnYHsQ7bGeYM666wy2ecaLcENtma7+7VIQHj1kTX+FXzxhPuwXxqXWh/tgY HoNfZSLtDEqJA== From: Andrii Nakryiko To: linux-fsdevel@vger.kernel.org, brauner@kernel.org, viro@zeniv.linux.org.uk, akpm@linux-foundation.org Cc: linux-kernel@vger.kernel.org, bpf@vger.kernel.org, gregkh@linuxfoundation.org, linux-mm@kvack.org, Andrii Nakryiko Subject: [PATCH 2/5] fs/procfs: implement efficient VMA querying API for /proc//maps Date: Fri, 3 May 2024 17:30:03 -0700 Message-ID: <20240504003006.3303334-3-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240504003006.3303334-1-andrii@kernel.org> References: <20240504003006.3303334-1-andrii@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 28FC64001B X-Rspamd-Server: rspam06 X-Stat-Signature: y6fa478w9bwcyy7fztw4rmrqqbmno8mx X-HE-Tag: 1714782615-466041 X-HE-Meta: U2FsdGVkX1/DwDzB5citKQS/MrWkw/+KDEiRQWZhhdrmdd0V2pHPKbYR25xZ66FwfmEfBGPcv8XMwjWgho2LE9sOXPZcMTM9kwl6l/Wy2QoyKL3NfyxgPHeFZEMKg7pyW3BjZ4gykugZ0PO56GM9LpwfsnQwyNIVoF6VRtsGh99ll5UZpihqgvqbgZM0SdaWF4jKWHqyY7y3O/B8Tfo7l12udRicu8Ys28VyVzYmpgerhIPvcBYHCB2N8ksKKif0Ssl296ZD+tSrW+5Qaf/Qn3HrUPaB1iejzhT+hX3841OFMpAVYKtH9k0SS9Jkw/FSoUCqvPQuGv7GEvZPYP5qI3Q8G1g9mhQgvLgd+4dvV4v1d9EreagbIbitqo6CExgJxbNdzanp1Zi7Ev9NzjgjJSVC3Ue/EBJW1WvF9uEGz78Dr0W5vvhIbZSmmoWlURFtfI6l94bHmLM3uI6AaB4WigzOMVuHqghwg+fieaMpu+C4dtatNoFtyZLahVMCpniGWmuHSBzON7sUKTBfu1AExit2kNVCNWNY3NKOKi/x7qAO+G0j25W9suF7IOJKCduk6+HJhaJtWA0JTSI/SHweiyq9pm1IIV0D4oE+MqNMP3pCIWe1nbeeRgOnxVXseCZr6rtOEpZ2YdRpnZW6BKYZWXDRWknWmAQDTg9mPc4HbJPPNj4DyQefrzdiapwOcRsVm2G+3oJchtn2os3IDw+A3i/J0Jy6acjsn0JE02EmN7nJT1dRXCpBwv90jayahc0bPpUkdzpuhEeWAQ1pPeHmUE6bRq7nRCitrEgPUTwA4tsAL8qdBGrbnyhF3vu5U1FT09Efh4I0Ivtw1FqgNpJv/AEgZ03S0jGXkZUMq6zkWg+TcfZzpoSX//F7Opi9MbfGyHeNaKGNAqhq7Ive20BYvyRZLMMKBJ6dgSeEvhnpXEigHGjp0u6lsNrqjNeFCNUH0AWNXPugNDgMdOZvlfZ T5hU3OC4 gv72dfSwmqZZiFVEz1NQfmSwaV/DZIXXR+LnWULOjWsOg/Tqz6DNCktqoQVOl9xc2TKzEO5F99h9D+G3D9ptMibAMqjcTdeugzVQ1azDXMnuYn6gAMc0HESmyVKzMNM/0Ok9JOrrtDZYIOVAZf0fMhf50fJk9sQ8rdWDlezZhYTtPywUrD2TfGmP9kbxjjSJfUV4w0b+iVFLL9LifFbdDA9vyRbrDfnLywfCoGC4KlbDIaRU= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: /proc//maps file is extremely useful in practice for various tasks involving figuring out process memory layout, what files are backing any given memory range, etc. One important class of applications that absolutely rely on this are profilers/stack symbolizers. They would normally capture stack trace containing absolute memory addresses of some functions, and would then use /proc//maps file to file corresponding backing ELF files, file offsets within them, and then continue from there to get yet more information (ELF symbols, DWARF information) to get human-readable symbolic information. As such, there are both performance and correctness requirement involved. This address to VMA information translation has to be done as efficiently as possible, but also not miss any VMA (especially in the case of loading/unloading shared libraries). Unfortunately, for all the /proc//maps file universality and usefulness, it doesn't fit the above 100%. First, it's text based, which makes its programmatic use from applications and libraries unnecessarily cumbersome and slow due to the need to do text parsing to get necessary pieces of information. Second, it's main purpose is to emit all VMAs sequentially, but in practice captured addresses would fall only into a small subset of all process' VMAs, mainly containing executable text. Yet, library would need to parse most or all of the contents to find needed VMAs, as there is no way to skip VMAs that are of no use. Efficient library can do the linear pass and it is still relatively efficient, but it's definitely an overhead that can be avoided, if there was a way to do more targeted querying of the relevant VMA information. Another problem when writing generic stack trace symbolization library is an unfortunate performance-vs-correctness tradeoff that needs to be made. Library has to make a decision to either cache parsed contents of /proc//maps for service future requests (if application requests to symbolize another set of addresses, captured at some later time, which is typical for periodic/continuous profiling cases) to avoid higher costs of needed to re-parse this file or caching the contents in memory to speed up future requests. In the former case, more memory is used for the cache and there is a risk of getting stale data if application loaded/unloaded shared libraries, or otherwise changed its set of VMAs through additiona mmap() calls (and other means of altering memory address space). In the latter case, it's the performance hit that comes from re-opening the file and re-reading/re-parsing its contents all over again. This patch aims to solve this problem by providing a new API built on top of /proc//maps. It is ioctl()-based and built as a binary interface, avoiding the cost and awkwardness of textual representation for programmatic use. It's designed to be extensible and forward/backward compatible by including user-specified field size and using copy_struct_from_user() approach. But, most importantly, it allows to do point queries for specific single address, specified by user. And this is done efficiently using VMA iterator. User has a choice to pick either getting VMA that covers provided address or -ENOENT if none is found (exact, least surprising, case). Or, with an extra query flag (PROCFS_PROCMAP_EXACT_OR_NEXT_VMA), they can get either VMA that covers the address (if there is one), or the closest next VMA (i.e., VMA with the smallest vm_start > addr). The later allows more efficient use, but, given it could be a surprising behavior, requires an explicit opt-in. Basing this ioctl()-based API on top of /proc//maps's FD makes sense given it's querying the same set of VMA data. All the permissions checks performed on /proc//maps opening fit here as well. ioctl-based implementation is fetching remembered mm_struct reference, but otherwise doesn't interfere with seq_file-based implementation of /proc//maps textual interface, and so could be used together or independently without paying any price for that. There is one extra thing that /proc//maps doesn't currently provide, and that's an ability to fetch ELF build ID, if present. User has control over whether this piece of information is requested or not by either setting build_id_size field to zero or non-zero maximum buffer size they provided through build_id_addr field (which encodes user pointer as __u64 field). The need to get ELF build ID reliably is an important aspect when dealing with profiling and stack trace symbolization, and /proc//maps textual representation doesn't help with this, requiring applications to open underlying ELF binary through /proc//map_files/- symlink, which adds an extra permissions implications due giving a full access to the binary from (potentially) another process, while all application is interested in is build ID. Giving an ability to request just build ID doesn't introduce any additional security concerns, on top of what /proc//maps is already concerned with, simplifying the overall logic. Kernel already implements build ID fetching, which is used from BPF subsystem. We are reusing this code here, but plan a follow up changes to make it work better under more relaxed assumption (compared to what existing code assumes) of being called from user process context, in which page faults are allowed. BPF-specific implementation currently bails out if necessary part of ELF file is not paged in, all due to extra BPF-specific restrictions (like the need to fetch build ID in restrictive contexts such as NMI handler). Note also, that fetching VMA name (e.g., backing file path, or special hard-coded or user-provided names) is optional just like build ID. If user sets vma_name_size to zero, kernel code won't attempt to retrieve it, saving resources. Signed-off-by: Andrii Nakryiko --- fs/proc/task_mmu.c | 165 ++++++++++++++++++++++++++++++++++++++++ include/uapi/linux/fs.h | 32 ++++++++ 2 files changed, 197 insertions(+) diff --git a/fs/proc/task_mmu.c b/fs/proc/task_mmu.c index 8e503a1635b7..cb7b1ff1a144 100644 --- a/fs/proc/task_mmu.c +++ b/fs/proc/task_mmu.c @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -375,11 +376,175 @@ static int pid_maps_open(struct inode *inode, struct file *file) return do_maps_open(inode, file, &proc_pid_maps_op); } +static int do_procmap_query(struct proc_maps_private *priv, void __user *uarg) +{ + struct procfs_procmap_query karg; + struct vma_iterator iter; + struct vm_area_struct *vma; + struct mm_struct *mm; + const char *name = NULL; + char build_id_buf[BUILD_ID_SIZE_MAX], *name_buf = NULL; + __u64 usize; + int err; + + if (copy_from_user(&usize, (void __user *)uarg, sizeof(usize))) + return -EFAULT; + if (usize > PAGE_SIZE) + return -E2BIG; + if (usize < offsetofend(struct procfs_procmap_query, query_addr)) + return -EINVAL; + err = copy_struct_from_user(&karg, sizeof(karg), uarg, usize); + if (err) + return err; + + if (karg.query_flags & ~PROCFS_PROCMAP_EXACT_OR_NEXT_VMA) + return -EINVAL; + if (!!karg.vma_name_size != !!karg.vma_name_addr) + return -EINVAL; + if (!!karg.build_id_size != !!karg.build_id_addr) + return -EINVAL; + + mm = priv->mm; + if (!mm || !mmget_not_zero(mm)) + return -ESRCH; + if (mmap_read_lock_killable(mm)) { + mmput(mm); + return -EINTR; + } + + vma_iter_init(&iter, mm, karg.query_addr); + vma = vma_next(&iter); + if (!vma) { + err = -ENOENT; + goto out; + } + /* user wants covering VMA, not the closest next one */ + if (!(karg.query_flags & PROCFS_PROCMAP_EXACT_OR_NEXT_VMA) && + vma->vm_start > karg.query_addr) { + err = -ENOENT; + goto out; + } + + karg.vma_start = vma->vm_start; + karg.vma_end = vma->vm_end; + + if (vma->vm_file) { + const struct inode *inode = file_user_inode(vma->vm_file); + + karg.vma_offset = ((__u64)vma->vm_pgoff) << PAGE_SHIFT; + karg.dev_major = MAJOR(inode->i_sb->s_dev); + karg.dev_minor = MINOR(inode->i_sb->s_dev); + karg.inode = inode->i_ino; + } else { + karg.vma_offset = 0; + karg.dev_major = 0; + karg.dev_minor = 0; + karg.inode = 0; + } + + karg.vma_flags = 0; + if (vma->vm_flags & VM_READ) + karg.vma_flags |= PROCFS_PROCMAP_VMA_READABLE; + if (vma->vm_flags & VM_WRITE) + karg.vma_flags |= PROCFS_PROCMAP_VMA_WRITABLE; + if (vma->vm_flags & VM_EXEC) + karg.vma_flags |= PROCFS_PROCMAP_VMA_EXECUTABLE; + if (vma->vm_flags & VM_MAYSHARE) + karg.vma_flags |= PROCFS_PROCMAP_VMA_SHARED; + + if (karg.build_id_size) { + __u32 build_id_sz = BUILD_ID_SIZE_MAX; + + err = build_id_parse(vma, build_id_buf, &build_id_sz); + if (!err) { + if (karg.build_id_size < build_id_sz) { + err = -ENAMETOOLONG; + goto out; + } + karg.build_id_size = build_id_sz; + } + } + + if (karg.vma_name_size) { + size_t name_buf_sz = min_t(size_t, PATH_MAX, karg.vma_name_size); + const struct path *path; + const char *name_fmt; + size_t name_sz = 0; + + get_vma_name(vma, &path, &name, &name_fmt); + + if (path || name_fmt || name) { + name_buf = kmalloc(name_buf_sz, GFP_KERNEL); + if (!name_buf) { + err = -ENOMEM; + goto out; + } + } + if (path) { + name = d_path(path, name_buf, name_buf_sz); + if (IS_ERR(name)) { + err = PTR_ERR(name); + goto out; + } + name_sz = name_buf + name_buf_sz - name; + } else if (name || name_fmt) { + name_sz = 1 + snprintf(name_buf, name_buf_sz, name_fmt ?: "%s", name); + name = name_buf; + } + if (name_sz > name_buf_sz) { + err = -ENAMETOOLONG; + goto out; + } + karg.vma_name_size = name_sz; + } + + /* unlock and put mm_struct before copying data to user */ + mmap_read_unlock(mm); + mmput(mm); + + if (karg.vma_name_size && copy_to_user((void __user *)karg.vma_name_addr, + name, karg.vma_name_size)) { + kfree(name_buf); + return -EFAULT; + } + kfree(name_buf); + + if (karg.build_id_size && copy_to_user((void __user *)karg.build_id_addr, + build_id_buf, karg.build_id_size)) + return -EFAULT; + + if (copy_to_user(uarg, &karg, min_t(size_t, sizeof(karg), usize))) + return -EFAULT; + + return 0; + +out: + mmap_read_unlock(mm); + mmput(mm); + kfree(name_buf); + return err; +} + +static long procfs_procmap_ioctl(struct file *file, unsigned int cmd, unsigned long arg) +{ + struct seq_file *seq = file->private_data; + struct proc_maps_private *priv = seq->private; + + switch (cmd) { + case PROCFS_PROCMAP_QUERY: + return do_procmap_query(priv, (void __user *)arg); + default: + return -ENOIOCTLCMD; + } +} + const struct file_operations proc_pid_maps_operations = { .open = pid_maps_open, .read = seq_read, .llseek = seq_lseek, .release = proc_map_release, + .unlocked_ioctl = procfs_procmap_ioctl, + .compat_ioctl = procfs_procmap_ioctl, }; /* diff --git a/include/uapi/linux/fs.h b/include/uapi/linux/fs.h index 45e4e64fd664..fe8924a8d916 100644 --- a/include/uapi/linux/fs.h +++ b/include/uapi/linux/fs.h @@ -393,4 +393,36 @@ struct pm_scan_arg { __u64 return_mask; }; +/* /proc//maps ioctl */ +#define PROCFS_IOCTL_MAGIC 0x9f +#define PROCFS_PROCMAP_QUERY _IOWR(PROCFS_IOCTL_MAGIC, 1, struct procfs_procmap_query) + +enum procmap_query_flags { + PROCFS_PROCMAP_EXACT_OR_NEXT_VMA = 0x01, +}; + +enum procmap_vma_flags { + PROCFS_PROCMAP_VMA_READABLE = 0x01, + PROCFS_PROCMAP_VMA_WRITABLE = 0x02, + PROCFS_PROCMAP_VMA_EXECUTABLE = 0x04, + PROCFS_PROCMAP_VMA_SHARED = 0x08, +}; + +struct procfs_procmap_query { + __u64 size; + __u64 query_flags; /* in */ + __u64 query_addr; /* in */ + __u64 vma_start; /* out */ + __u64 vma_end; /* out */ + __u64 vma_flags; /* out */ + __u64 vma_offset; /* out */ + __u64 inode; /* out */ + __u32 dev_major; /* out */ + __u32 dev_minor; /* out */ + __u32 vma_name_size; /* in/out */ + __u32 build_id_size; /* in/out */ + __u64 vma_name_addr; /* in */ + __u64 build_id_addr; /* in */ +}; + #endif /* _UAPI_LINUX_FS_H */ From patchwork Sat May 4 00:30:04 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13653691 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 4FA4CC25B10 for ; Sat, 4 May 2024 00:30:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D87116B009A; Fri, 3 May 2024 20:30:26 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D375F6B009B; Fri, 3 May 2024 20:30:26 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id BD8C86B009C; Fri, 3 May 2024 20:30:26 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0013.hostedemail.com [216.40.44.13]) by kanga.kvack.org (Postfix) with ESMTP id 9E5CF6B009A for ; Fri, 3 May 2024 20:30:26 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 194DF801F1 for ; Sat, 4 May 2024 00:30:26 +0000 (UTC) X-FDA: 82078832052.28.AA90197 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf15.hostedemail.com (Postfix) with ESMTP id 149DBA0005 for ; Sat, 4 May 2024 00:30:23 +0000 (UTC) Authentication-Results: imf15.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=mEFOCn6M; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf15.hostedemail.com: domain of andrii@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=andrii@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1714782624; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=mvVGVT6MCss+2/h0HFTvcSkj9lK/aARweXx6f1UKJ7Y=; b=N1ngGT0OVfOayePWumQzpZdJV0B1CwkIqcrU0C/jsrZESNVN//HiYzwOE60eKSyeioj0Bn H54erXRkAH1IvIHATXFtNrgVhvF0tYUY9j/Cx16F0p8r1eUbdutTcKgCLGQOZxTBv0iCPW 8THeVfWrkEPumY9Q2lsmd7I3BBlPGks= ARC-Authentication-Results: i=1; imf15.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=mEFOCn6M; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf15.hostedemail.com: domain of andrii@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=andrii@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1714782624; a=rsa-sha256; cv=none; b=r9yf43K8HfW1OPsppdDvW+iJLwqE9ajVMR9ZhAEMtOfdxy252NWDCfe//YlAcLCnlx7fTH 62Si+lPWWXsy/CnamB4S490qRkMVqpP00R4+EfvsOhVX4ey8ijgU33C+s8IIFmrhVOU7uM j40tyaj1bjqXsMg+ng3Fs6gnDYPpE7w= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 0407FCE1A2E; Sat, 4 May 2024 00:30:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D2A35C4AF1A; Sat, 4 May 2024 00:30:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1714782618; bh=akE5P6xvZT48f5LRQWKFAyRAluTFD6SKWbtJB6gxXDE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=mEFOCn6M0/9FUvNcIDMh645SuA6hG0akoQKvB+ogesqfmOVkkryzy317thFixlYaT jT0pIGyWZec5FtbBb2fvSdERaUl+MA2M1GiODZsWdBqLdR2zAzt2TR1GUqAn8TgJ6c jtGuzWWJ8q5/TpHhLac5Df+dU4ptxTmZiiBA1VOXmgXkQ0+5v8eSxYTuoLpj92koNh aLG4yZedRRylNI0sepW39uw9NDJcJBauAHNY0kq9ZhmbPUPAQ5HWjbrP+A/QWCMhh4 UlFI5mCAFWYuZr40FZlblG//YUIcPds3/uSqo0HtePPOViVrumGVaDLsbMz2j7riB+ zH166DwWwqaVw== From: Andrii Nakryiko To: linux-fsdevel@vger.kernel.org, brauner@kernel.org, viro@zeniv.linux.org.uk, akpm@linux-foundation.org Cc: linux-kernel@vger.kernel.org, bpf@vger.kernel.org, gregkh@linuxfoundation.org, linux-mm@kvack.org, Andrii Nakryiko Subject: [PATCH 3/5] tools: sync uapi/linux/fs.h header into tools subdir Date: Fri, 3 May 2024 17:30:04 -0700 Message-ID: <20240504003006.3303334-4-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240504003006.3303334-1-andrii@kernel.org> References: <20240504003006.3303334-1-andrii@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam09 X-Rspamd-Queue-Id: 149DBA0005 X-Stat-Signature: qw9iq3jrum65nxbwynzb9f3mszzh9ats X-HE-Tag: 1714782623-275985 X-HE-Meta: U2FsdGVkX18RR6JfqA/Wi0ii7gsDDXgc8kR9LPnxHijP+2r/eEZgYG1ngTOXwOuJVn3wlyAttmJEqxnFRSItxnFPPbeeDH3B2jfe8zQMEi/5bjqwK58x6+xZTvbd38IYkTVrstSoarxQsKXchMAOF//u6G/Hwpxrel7Q6N9hqjTDbioSJ+xM44Vc+vZplF1LvHPVA4XQR5dZPxNk1APjQQtQAHBaNN0Kvu9YO1aCbEi0ztjeO8iaqzITtmbFTa5+070wo/IGBY/BE+xiGCnB5ZySpqV+W4TkwXq9VrPeU99y5wFasR5+STib2BtGdeX8BXe/OKQP/CCNYc/TztOKl/Oz8Bt/l3fNn2EE2tqIdVpp2fDJlF44uN1p+2V+O7JHZpOp9l4RxoWZ2aRh1o4tGtBr8hn044hKUMix9b8Nj6mesYNg/YP8AD55ikzu4C9fMAtHgBB9c2hgRo3IU6p8x9mn3m6eHNv2Kc+MGURra3zVvFUjhSNIhWiA2Wj/xTJk4McZZUuBoVgeDbG8tVX2Vt+hg0KGH1JwPGcDGNuMDlbL5xgRP8wU1j97Hedi7/OFBAYe75TgkTwtYgftIQmdXhhUobtNG1yG5U4GWFalLWmrohP/oPmTRIQlcOpPnEg6h0dgM9L7xi4gRL6WJaB80ady3CxFVti/dsC/jd/r/9I/oUp+p+D2VfXfXjMfjg+nFZF56X8mTKcZOLKZ85VrC94S22eB8pPVKl7iSEx13nb7kqIixON2WQsZZVmH5aitbU3a0IvxCq2jIahQqLYHOIUEIyP1cwQj8u3aARbivTjh1eqSRqreYUZTJEGw8wr19wX4Dcjhq0uF7+QuOYWEKRMsu3+xlQmEdmOl1kSW5glQszkK7gAgcmyVxYqr9EFHCMHW+cyLsTxLV9sMjOSESk5+l42snhDwWXBl6QgebxcMVPYYOQsk3DVtJJncbxVxz8t5U15xvfNllSXkRn8 ExYy7Qda j0BxkYIzL4J5nGy5CWtkXgYSWiISKx22MDQx32uGXnQvIpGSGcafAHEnjB8G/b30q1S33CeoPX5ljHa537R+RpMq28IfuLCsEP/+qbpxbkOtqSC3qd+WNJjmY155NFh1lSW2raTv0jOpeMKyDNrYP0NCXtjyY9MFHrtdQo7PEeY0+zrpyV8qfolaCLVPxeKg/vrLHDGfPk5cTID128QE4OQ0yFEYvIDq6BFcO7az5z9/Kcnw= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Keep them in sync for use from BPF selftests. Signed-off-by: Andrii Nakryiko --- .../perf/trace/beauty/include/uapi/linux/fs.h | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tools/perf/trace/beauty/include/uapi/linux/fs.h b/tools/perf/trace/beauty/include/uapi/linux/fs.h index 45e4e64fd664..fe8924a8d916 100644 --- a/tools/perf/trace/beauty/include/uapi/linux/fs.h +++ b/tools/perf/trace/beauty/include/uapi/linux/fs.h @@ -393,4 +393,36 @@ struct pm_scan_arg { __u64 return_mask; }; +/* /proc//maps ioctl */ +#define PROCFS_IOCTL_MAGIC 0x9f +#define PROCFS_PROCMAP_QUERY _IOWR(PROCFS_IOCTL_MAGIC, 1, struct procfs_procmap_query) + +enum procmap_query_flags { + PROCFS_PROCMAP_EXACT_OR_NEXT_VMA = 0x01, +}; + +enum procmap_vma_flags { + PROCFS_PROCMAP_VMA_READABLE = 0x01, + PROCFS_PROCMAP_VMA_WRITABLE = 0x02, + PROCFS_PROCMAP_VMA_EXECUTABLE = 0x04, + PROCFS_PROCMAP_VMA_SHARED = 0x08, +}; + +struct procfs_procmap_query { + __u64 size; + __u64 query_flags; /* in */ + __u64 query_addr; /* in */ + __u64 vma_start; /* out */ + __u64 vma_end; /* out */ + __u64 vma_flags; /* out */ + __u64 vma_offset; /* out */ + __u64 inode; /* out */ + __u32 dev_major; /* out */ + __u32 dev_minor; /* out */ + __u32 vma_name_size; /* in/out */ + __u32 build_id_size; /* in/out */ + __u64 vma_name_addr; /* in */ + __u64 build_id_addr; /* in */ +}; + #endif /* _UAPI_LINUX_FS_H */ From patchwork Sat May 4 00:30:05 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13653690 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 1B38DC4345F for ; Sat, 4 May 2024 00:30:25 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 60DFC6B0098; Fri, 3 May 2024 20:30:24 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5BDDC6B0099; Fri, 3 May 2024 20:30:24 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 45D5E6B009A; Fri, 3 May 2024 20:30:24 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 268676B0098 for ; Fri, 3 May 2024 20:30:24 -0400 (EDT) Received: from smtpin22.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id D528F1C1990 for ; Sat, 4 May 2024 00:30:23 +0000 (UTC) X-FDA: 82078831926.22.512D9C4 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf27.hostedemail.com (Postfix) with ESMTP id 3E04240005 for ; Sat, 4 May 2024 00:30:22 +0000 (UTC) Authentication-Results: imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=KEgnPpHB; spf=pass (imf27.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=andrii@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1714782622; a=rsa-sha256; cv=none; b=FdCvLWk2Eof2sghu+ks+0UtxeVNBl+sYgE1/+rBNV6pEDwA60zZ92OZx04tpf5e2LuOYJ/ 4J7NiHobjl68wKh9VvCrwUaHKi5+2/VV2qTFTe2DjHC/CPZRc1PFC/mUofV61lMdQUgxPX Wx3mMc/biWjgTZxeh8ceKaSzsCbuHwc= ARC-Authentication-Results: i=1; imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=KEgnPpHB; spf=pass (imf27.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=andrii@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1714782622; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=vXES7tPOi+ax+stziBjbPUd71B/W12XV1wdwvYVrgRw=; b=5Lr5AuhJEKW+LUATnsFiA8dTeiQ2XEjYOcLDIJnxmXDUkIZagUXU/9qybfxEB3BeuzALhb tAEqdXdJVHrDbEjkzx2A6UN8R2vrJOgCQoHO9r3KjLd5CJqLiL1TKHNm4Icdn26yZguFUv XYWsbigCWOaa6tAdiYSGar4fs53RKNU= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 68E3D61E38; Sat, 4 May 2024 00:30:21 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 08AAFC32789; Sat, 4 May 2024 00:30:21 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1714782621; bh=YxeS+sLpQRnaSgu/9E3ClWUqEPF8Db9NHuIyW1Jsti8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=KEgnPpHBAUag30KLKXRbcwwv5eSBfqoQqRe1IJe1bSxSom7XCLuXPyPJlx+VCp2A7 FRJ9upZx8QAsxZqb0ywEIr12qdiefeoYMQgEcQE3sFCkVzlo4BwwLTfVTS17gQ8pXS MJSfEPbXXyRUsJXYDTuy39AISOPZoOmP6UH+97Msw1OdtCErksIrOyWu9A8bOBR8DN gP20QGIvODzLTCLXHQhPR11wcdaZ5z/5ThA6YuXsRqoaLQMyy2i5LQBWwstFu91JBd 1cd08eKVWgqk1Iwc1kfGCnC7+S49U5eFUZNjZekrVZn2eM9uxF5rk8IdO/qkuaaxga x3SBOYcifgczw== From: Andrii Nakryiko To: linux-fsdevel@vger.kernel.org, brauner@kernel.org, viro@zeniv.linux.org.uk, akpm@linux-foundation.org Cc: linux-kernel@vger.kernel.org, bpf@vger.kernel.org, gregkh@linuxfoundation.org, linux-mm@kvack.org, Andrii Nakryiko Subject: [PATCH 4/5] selftests/bpf: make use of PROCFS_PROCMAP_QUERY ioctl, if available Date: Fri, 3 May 2024 17:30:05 -0700 Message-ID: <20240504003006.3303334-5-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240504003006.3303334-1-andrii@kernel.org> References: <20240504003006.3303334-1-andrii@kernel.org> MIME-Version: 1.0 X-Stat-Signature: 8sz7gmtgxknfujkaq5ny5k93z61afuna X-Rspam-User: X-Rspamd-Server: rspam02 X-Rspamd-Queue-Id: 3E04240005 X-HE-Tag: 1714782622-207495 X-HE-Meta: U2FsdGVkX1/tVHVAcCkk6OlOsrei9Ko9ksIypG9OO2IuFlKlVMJ37pmtSPhQZMOJNmstFmxwPs2RDCA67ZaccA0kKNuE0DwJfWX3DvH2sLF2TeYOZ5SMjctw/vtZu3WESYLtcA1gDYAWk8YA35POR7f7CXJ+FBZMkScvoBqe5rxDuSSHBiF1gW2r5qJoVlecvEuaaHLTMWWJrxVqzR/zautqWvJq51c9WEURiSxpmf7VOp2mIGTB8sxvOB/iDF2sb4fLsbTXNXXaZKyPOe35U96trNQjAKSU/yhFJNVLkJUGWQoffKliio5YtfjENBd6YTzd36uE2XFL4/3z/Tkn3H1cFgS1I7qEAr/m+Y36Kev5qMaiwvApo8p/agXcbu0/7HlFogTpnF9w4VLaAmnA9UuCcSUmSgQVyA6B93c0linzrmJHNrUGkGQyelf/O4Oa5xEUkuHwReGHDUvsC+NhL05wXIrs+RhMVLDa6bgNokebYvUH4YIBI1U+V0k3XVEAd5kMRWGZAIwuQGuOSImGlKSzUq6I7uA22SRanRY4U/jBVlK2Xc4CRO67iat1voRNa6OpnN2+d6ChpLoEcvAvsz2Z2AIutyhAYe7qwrGqxIToifvDMIanLDEvz4wd64rBnmv04lWh0vWECzxAEO1hl/GWu2GO6eYP2HuJrLNTz2gbJM6iyxYtvkBRieInuQhyLdyyV9pUGhluEZGz/VsVyjCNMPh1jcXVG2u2DzqBV86a5iTklLcksu2hTmNvjJysmbXv8z53bW9gICd72Yb+3tX9WRoOTD/YtFclv10aDvx1ZttQb+h848laMgQ6ruFCbrLuE9zq+NqDoVvTG8o9JwIomFMopOyTWYcOTEJPr6gZVcCnwzkPipUwm1pFT/8zSGaD4PC6nUClgU87lvD5g5NsCkD9sTLY3R4W3fr/2aWn0Ws5KcR5hUCAxzOXmReQJ14bhKI4mYoAzBy3PPz fXu697X0 7mhd/XwFHbkc54jygUqMjW1oXO0RM7Imi66L3umt2naEt6t+hL2tweQTlHxh6PYU53Ezxws8FhO6HJ911kidRJ64CVqIcl8yMwibjEs3ZLW3RyJ8md9TqfnoiLYH6W4zyf2Oon3iQaJOj886QBD8wsVXNVnx6u5kkHIk1cP1cPE045TxEWLn9T4iokeE08oYhfZJWym20/WsO7HyqXjO6nDD2r31l7eu7/ML6nxymxrHnW+VV/O9EEwpx/7ZjPZo4iDbH+YROS6jRMJnmoSwHZMmvNeZbsnvjATaX X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Instead of parsing text-based /proc//maps file, try to use PROCFS_PROCMAP_QUERY ioctl() to simplify and speed up data fetching. This logic is used to do uprobe file offset calculation, so any bugs in this logic would manifest as failing uprobe BPF selftests. This also serves as a simple demonstration of one of the intended uses. Signed-off-by: Andrii Nakryiko --- tools/testing/selftests/bpf/test_progs.c | 3 + tools/testing/selftests/bpf/test_progs.h | 2 + tools/testing/selftests/bpf/trace_helpers.c | 105 +++++++++++++++++--- 3 files changed, 95 insertions(+), 15 deletions(-) diff --git a/tools/testing/selftests/bpf/test_progs.c b/tools/testing/selftests/bpf/test_progs.c index 89ff704e9dad..6a19970f2531 100644 --- a/tools/testing/selftests/bpf/test_progs.c +++ b/tools/testing/selftests/bpf/test_progs.c @@ -19,6 +19,8 @@ #include #include "json_writer.h" +int env_verbosity = 0; + static bool verbose(void) { return env.verbosity > VERBOSE_NONE; @@ -848,6 +850,7 @@ static error_t parse_arg(int key, char *arg, struct argp_state *state) return -EINVAL; } } + env_verbosity = env->verbosity; if (verbose()) { if (setenv("SELFTESTS_VERBOSE", "1", 1) == -1) { diff --git a/tools/testing/selftests/bpf/test_progs.h b/tools/testing/selftests/bpf/test_progs.h index 0ba5a20b19ba..6eae7fdab0d7 100644 --- a/tools/testing/selftests/bpf/test_progs.h +++ b/tools/testing/selftests/bpf/test_progs.h @@ -95,6 +95,8 @@ struct test_state { FILE *stdout; }; +extern int env_verbosity; + struct test_env { struct test_selector test_selector; struct test_selector subtest_selector; diff --git a/tools/testing/selftests/bpf/trace_helpers.c b/tools/testing/selftests/bpf/trace_helpers.c index 70e29f316fe7..8ac71e73d173 100644 --- a/tools/testing/selftests/bpf/trace_helpers.c +++ b/tools/testing/selftests/bpf/trace_helpers.c @@ -10,6 +10,8 @@ #include #include #include +#include +#include #include #include "trace_helpers.h" #include @@ -233,29 +235,92 @@ int kallsyms_find(const char *sym, unsigned long long *addr) return err; } +#ifdef PROCFS_PROCMAP_QUERY +int env_verbosity __weak = 0; + +int procmap_query(int fd, const void *addr, size_t *start, size_t *offset, int *flags) +{ + char path_buf[PATH_MAX], build_id_buf[20]; + struct procfs_procmap_query q; + int err; + + memset(&q, 0, sizeof(q)); + q.size = sizeof(q); + q.query_addr = (__u64)addr; + q.vma_name_addr = (__u64)path_buf; + q.vma_name_size = sizeof(path_buf); + q.build_id_addr = (__u64)build_id_buf; + q.build_id_size = sizeof(build_id_buf); + + err = ioctl(fd, PROCFS_PROCMAP_QUERY, &q); + if (err < 0) { + err = -errno; + if (err == -ENOTTY) + return -EOPNOTSUPP; /* ioctl() not implemented yet */ + if (err == -ENOENT) + return -ESRCH; /* vma not found */ + return err; + } + + if (env_verbosity >= 1) { + printf("VMA FOUND (addr %08lx): %08lx-%08lx %c%c%c%c %08lx %02x:%02x %ld %s (build ID: %s, %d bytes)\n", + (long)addr, (long)q.vma_start, (long)q.vma_end, + (q.vma_flags & PROCFS_PROCMAP_VMA_READABLE) ? 'r' : '-', + (q.vma_flags & PROCFS_PROCMAP_VMA_WRITABLE) ? 'w' : '-', + (q.vma_flags & PROCFS_PROCMAP_VMA_EXECUTABLE) ? 'x' : '-', + (q.vma_flags & PROCFS_PROCMAP_VMA_SHARED) ? 's' : 'p', + (long)q.vma_offset, q.dev_major, q.dev_minor, (long)q.inode, + q.vma_name_size ? path_buf : "", + q.build_id_size ? "YES" : "NO", + q.build_id_size); + } + + *start = q.vma_start; + *offset = q.vma_offset; + *flags = q.vma_flags; + return 0; +} +#else +int procmap_query(int fd, const void *addr, size_t *start, size_t *offset, int *flags) +{ + return -EOPNOTSUPP; +} +#endif + ssize_t get_uprobe_offset(const void *addr) { - size_t start, end, base; - char buf[256]; - bool found = false; + size_t start, base, end; FILE *f; + char buf[256]; + int err, flags; f = fopen("/proc/self/maps", "r"); if (!f) return -errno; - while (fscanf(f, "%zx-%zx %s %zx %*[^\n]\n", &start, &end, buf, &base) == 4) { - if (buf[2] == 'x' && (uintptr_t)addr >= start && (uintptr_t)addr < end) { - found = true; - break; + err = procmap_query(fileno(f), addr, &start, &base, &flags); + if (err == 0) { + if (!(flags & PROCFS_PROCMAP_VMA_EXECUTABLE)) + return -ESRCH; + } else if (err != -EOPNOTSUPP) { + fclose(f); + return err; + } else if (err) { + bool found = false; + + while (fscanf(f, "%zx-%zx %s %zx %*[^\n]\n", &start, &end, buf, &base) == 4) { + if (buf[2] == 'x' && (uintptr_t)addr >= start && (uintptr_t)addr < end) { + found = true; + break; + } + } + if (!found) { + fclose(f); + return -ESRCH; } } - fclose(f); - if (!found) - return -ESRCH; - #if defined(__powerpc64__) && defined(_CALL_ELF) && _CALL_ELF == 2 #define OP_RT_RA_MASK 0xffff0000UL @@ -296,15 +361,25 @@ ssize_t get_rel_offset(uintptr_t addr) size_t start, end, offset; char buf[256]; FILE *f; + int err, flags; f = fopen("/proc/self/maps", "r"); if (!f) return -errno; - while (fscanf(f, "%zx-%zx %s %zx %*[^\n]\n", &start, &end, buf, &offset) == 4) { - if (addr >= start && addr < end) { - fclose(f); - return (size_t)addr - start + offset; + err = procmap_query(fileno(f), (const void *)addr, &start, &offset, &flags); + if (err == 0) { + fclose(f); + return (size_t)addr - start + offset; + } else if (err != -EOPNOTSUPP) { + fclose(f); + return err; + } else if (err) { + while (fscanf(f, "%zx-%zx %s %zx %*[^\n]\n", &start, &end, buf, &offset) == 4) { + if (addr >= start && addr < end) { + fclose(f); + return (size_t)addr - start + offset; + } } } From patchwork Sat May 4 00:30:06 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13653692 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 81280C4345F for ; Sat, 4 May 2024 00:30:29 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E263B6B009B; Fri, 3 May 2024 20:30:28 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D13616B009C; Fri, 3 May 2024 20:30:28 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id AC6896B009D; Fri, 3 May 2024 20:30:28 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 8A7D06B009B for ; Fri, 3 May 2024 20:30:28 -0400 (EDT) Received: from smtpin17.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 34E13C12A3 for ; Sat, 4 May 2024 00:30:28 +0000 (UTC) X-FDA: 82078832136.17.0BAC58F Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf15.hostedemail.com (Postfix) with ESMTP id A3A5CA0002 for ; Sat, 4 May 2024 00:30:25 +0000 (UTC) Authentication-Results: imf15.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="p/zUIjd+"; spf=pass (imf15.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=andrii@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1714782625; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=q/rRDDx8D3LCpv8ZTJIed2xbo4KwFqf1ci/UQ9CE65w=; b=BSCFOeKbup2sunvhh1nWMHyS50+svEGN6q8lat+9i795hk3TMPNsdrxu8EIF4WVUqpzFuT e8XrgyRr6p1CIHicFPNJQB3WP4cN5bsCauRBU3G3d56TLtm6+TyPX4FdBhUH5oPwxRtFV/ mufmoYh0LoP92X0Zn7qZegMpFeT2ohc= ARC-Authentication-Results: i=1; imf15.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="p/zUIjd+"; spf=pass (imf15.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=andrii@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1714782625; a=rsa-sha256; cv=none; b=ol06BrDYOKSIG4R8cCsyU58918sH4L38ukyHI2E/RroW6ZFc1eWBEQEvr7bL5IvK6kfzKK gFBGOLAfgYINqsuGI8l1YoIxVY4uBt1C8XbDzUlN4wJUOOcZH9/EVbBxUMk7sT9CQWeE4h kWWKqufrmkVxv/bzJ2scacHFcoJjjF0= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id D3D5261E29; Sat, 4 May 2024 00:30:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 49A96C4AF19; Sat, 4 May 2024 00:30:24 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1714782624; bh=21/1lr/MosDNysUEDGD3CRROcRa+YFl3m2iHec0XNMo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=p/zUIjd+EJG/uhzDDuN/1qq7S7QRwP4UoIbpJliZGUPyuB85/sY34OXgwKbpg+63u wQrnAtuKyV0HMkJm7QY4NpNlq32eKut7Gcb+myozTQVNUs6kAVesEe7SCDya5synuE fEvh9ODYpYPzHQXKnccnWIEKYJvBp9p7evPuODQU8bOytoQ2Tbp6LsgkQ6c05Tge4K rXGdkZrN9UC10Y7RxiVSDj++99Yv+ldhmPKQ9wO+2DG48DTgJFQgowmjtu4jc7DRo4 7DfleH/tM1K7jBw3mFAPPA5HdwSMpT3p1ijeUsM1eBrnHUm46B+ll7HtY63kU/6In2 1VBohECG2aqEg== From: Andrii Nakryiko To: linux-fsdevel@vger.kernel.org, brauner@kernel.org, viro@zeniv.linux.org.uk, akpm@linux-foundation.org Cc: linux-kernel@vger.kernel.org, bpf@vger.kernel.org, gregkh@linuxfoundation.org, linux-mm@kvack.org, Andrii Nakryiko Subject: [PATCH 5/5] selftests/bpf: a simple benchmark tool for /proc//maps APIs Date: Fri, 3 May 2024 17:30:06 -0700 Message-ID: <20240504003006.3303334-6-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240504003006.3303334-1-andrii@kernel.org> References: <20240504003006.3303334-1-andrii@kernel.org> MIME-Version: 1.0 X-Stat-Signature: gd9kqhbkn3peof37nin5pqi9drp7jni4 X-Rspamd-Queue-Id: A3A5CA0002 X-Rspamd-Server: rspam10 X-Rspam-User: X-HE-Tag: 1714782625-895940 X-HE-Meta: U2FsdGVkX1/MiDd0KEBIGATvKogQ7YfnKRFhIDzwFhq+TomQ0hfdr8DnNjowyTfmq8ckPKVhhoAbxqA6Iu+YnDavKHgSB9M7U76wiQ/czafyaCnaySXgHH5OpUvlqzZoy+jRiSySUfIOPnxsVSJ+DD6O9WanmxtYQOQTJ6S3KRVUAYE2jB3f3vUVfIwJ/x9F4N0X19r1g+jmrtbO77+6sChfdG1IoRDXmqvp5bykF1sgd82It5APdVwGof4XiTGrd43zTOf2kXDdITz4cvepI0DEjiDB7z4Q54bB9yb9bhsnY+9oeqYTB0+KLHkgW/6YILLi/zoTazgeeAVt7ogygT8CPSPqaCKiekHJm+1zwmcPnYpNR9b2IP2EVYI1/qIMVhuDf0LOYAWT87ypj7BIIw0Bskjgz/GtjZaYIXTSl8I72nLIDd8fhndOmhjhy90+PF0JISwsHtpH6q2VmWuHc06UkpI6BdXDKM0pljF5qWhXYgObatqYEyeag6i6Rg/TX+UFzJhtKIzD7w7CojJS4XGYimDdJ7KyfnmI/1uf9gIV76ZMmKd1oqwJsPeZoJ4XrxB0C3Q2uHpcP2+3iEaciISh6xa9NWZxX09p805eoXdY96GkGoaTXEbgmbv5QFNPWM+N1O6DIrMElndnNzaiGleVfAuzSOoWOgN9akruDSuL+vP3VK84/toRL4zfkQlPJ6fdvk0fANxK2KvMkzZmnf/+2jPh/Q+9xlMSGqdleb9sCFy827I/hmXfiecj5cq3tultgSU7SVQ/nXT5amZNF00Z8vzSmXtFMJdR9KrfItWE8QAVvjfql0mtT2bPNmbhSQU7u0evCBUI965L1GHq8Gm+3BBqANpFXWJkuZxd97OwwSzyhMHiEvjuCOQkzJQPj/LQTvq61nxlagQ5x4nj07uCLDFKD3zrkSvbHxqnoexv0T3gPsi+2Jj3ie+KGtGln4gKTFiuocttefvoWfv LIAB8Baz K673uIwryEGS4BzaUxU/Vr49/SHfWDeJhw3Rncv8/v1NLlCIVFsp/fGWHFQaIuJtxj3IZAEkzWP/u0dU9CL2adpx+XLQV1DRRIi7H/KzZYrsuVc96c4UCQ8ljs3AVBNYFm7WkfMNQtr8zn3whjlQe91SBa87RWjpX9NZq0W3RJX4uQ8fhp5cYC40Yb+hqAyUkvLNuNmNd9IaVP/HQ186EBd8p7TlJQRmFrysSGVrAuRB6fBg= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement a simple tool/benchmark for comparing address "resolution" logic based on textual /proc//maps interface and new binary ioctl-based PROCFS_PROCMAP_QUERY command. The tool expects a file with a list of hex addresses, relevant PID, and then provides control over whether textual or binary ioctl-based ways to process VMAs should be used. The overall logic implements as efficient way to do batched processing of a given set of (unsorted) addresses. We first sort them in increasing order (remembering their original position to restore original order, if necessary), and then process all VMAs from /proc//maps, matching addresses to VMAs and calculating file offsets, if matched. For ioctl-based approach the idea is similar, but is implemented even more efficiently, requesting only VMAs that cover all given addresses, skipping all the irrelevant VMAs altogether. To be able to compare efficiency of both APIs tool has "benchark" mode. User provides a number of processing runs to run in a tight loop, timing specifically /proc//maps parsing and processing parts of the logic only. Address sorting and re-sorting is excluded. This gives a more direct way to compare ioctl- vs text-based APIs. We used a medium-sized production application to do representative benchmark. A bunch of stack traces were captured, resulting in 4435 user space addresses (699 unique ones, but we didn't deduplicate them). Application itself had 702 VMAs reported in /proc//maps. Averaging time taken to process all addresses 10000 times, showed that: - text-based approach took 380 microseconds *per one batch run*; - ioctl-based approach took 10 microseconds *per identical batch run*. This gives about ~35x speed up to do exactly the same amoun of work (build IDs were not fetched for ioctl-based benchmark; fetching build IDs resulted in 2x slowdown compared to no-build-ID case). I also did an strace run of both cases. In text-based one the tool did 68 read() syscalls, fetching up to 4KB of data in one go. In comparison, ioctl-based implementation had to do only 6 ioctl() calls to fetch all relevant VMAs. It is projected that savings from processing big production applications would only widen the gap in favor of binary-based querying ioctl API, as bigger applications will tend to have even more non-executable VMA mappings relative to executable ones. Signed-off-by: Andrii Nakryiko --- tools/testing/selftests/bpf/.gitignore | 1 + tools/testing/selftests/bpf/Makefile | 2 +- tools/testing/selftests/bpf/procfs_query.c | 366 +++++++++++++++++++++ 3 files changed, 368 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/bpf/procfs_query.c diff --git a/tools/testing/selftests/bpf/.gitignore b/tools/testing/selftests/bpf/.gitignore index f1aebabfb017..7eaa8f417278 100644 --- a/tools/testing/selftests/bpf/.gitignore +++ b/tools/testing/selftests/bpf/.gitignore @@ -45,6 +45,7 @@ test_cpp /veristat /sign-file /uprobe_multi +/procfs_query *.ko *.tmp xskxceiver diff --git a/tools/testing/selftests/bpf/Makefile b/tools/testing/selftests/bpf/Makefile index ba28d42b74db..07e17bb89767 100644 --- a/tools/testing/selftests/bpf/Makefile +++ b/tools/testing/selftests/bpf/Makefile @@ -131,7 +131,7 @@ TEST_GEN_PROGS_EXTENDED = test_sock_addr test_skb_cgroup_id_user \ flow_dissector_load test_flow_dissector test_tcp_check_syncookie_user \ test_lirc_mode2_user xdping test_cpp runqslower bench bpf_testmod.ko \ xskxceiver xdp_redirect_multi xdp_synproxy veristat xdp_hw_metadata \ - xdp_features bpf_test_no_cfi.ko + xdp_features bpf_test_no_cfi.ko procfs_query TEST_GEN_FILES += liburandom_read.so urandom_read sign-file uprobe_multi diff --git a/tools/testing/selftests/bpf/procfs_query.c b/tools/testing/selftests/bpf/procfs_query.c new file mode 100644 index 000000000000..8ca3978244ad --- /dev/null +++ b/tools/testing/selftests/bpf/procfs_query.c @@ -0,0 +1,366 @@ +// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static bool verbose; +static bool quiet; +static bool use_ioctl; +static bool request_build_id; +static char *addrs_path; +static int pid; +static int bench_runs; + +const char *argp_program_version = "procfs_query 0.0"; +const char *argp_program_bug_address = ""; + +static inline uint64_t get_time_ns(void) +{ + struct timespec t; + + clock_gettime(CLOCK_MONOTONIC, &t); + + return (uint64_t)t.tv_sec * 1000000000 + t.tv_nsec; +} + +static const struct argp_option opts[] = { + { "verbose", 'v', NULL, 0, "Verbose mode" }, + { "quiet", 'q', NULL, 0, "Quiet mode (no output)" }, + { "pid", 'p', "PID", 0, "PID of the process" }, + { "addrs-path", 'f', "PATH", 0, "File with addresses to resolve" }, + { "benchmark", 'B', "RUNS", 0, "Benchmark mode" }, + { "query", 'Q', NULL, 0, "Use ioctl()-based point query API (by default text parsing is done)" }, + { "build-id", 'b', NULL, 0, "Fetch build ID, if available (only for ioctl mode)" }, + {}, +}; + +static error_t parse_arg(int key, char *arg, struct argp_state *state) +{ + switch (key) { + case 'v': + verbose = true; + break; + case 'q': + quiet = true; + break; + case 'i': + use_ioctl = true; + break; + case 'b': + request_build_id = true; + break; + case 'p': + pid = strtol(arg, NULL, 10); + break; + case 'f': + addrs_path = strdup(arg); + break; + case 'B': + bench_runs = strtol(arg, NULL, 10); + if (bench_runs <= 0) { + fprintf(stderr, "Invalid benchmark run count: %s\n", arg); + return -EINVAL; + } + break; + case ARGP_KEY_ARG: + argp_usage(state); + break; + default: + return ARGP_ERR_UNKNOWN; + } + return 0; +} + +static const struct argp argp = { + .options = opts, + .parser = parse_arg, +}; + +struct addr { + unsigned long long addr; + int idx; +}; + +static struct addr *addrs; +static size_t addr_cnt, addr_cap; + +struct resolved_addr { + unsigned long long file_off; + const char *vma_name; + int build_id_sz; + char build_id[20]; +}; + +static struct resolved_addr *resolved; + +static int resolve_addrs_ioctl(void) +{ + char buf[32], build_id_buf[20], vma_name[PATH_MAX]; + struct procfs_procmap_query q; + int fd, err, i; + struct addr *a = &addrs[0]; + struct resolved_addr *r; + + snprintf(buf, sizeof(buf), "/proc/%d/maps", pid); + fd = open(buf, O_RDONLY); + if (fd < 0) { + err = -errno; + fprintf(stderr, "Failed to open process map file (%s): %d\n", buf, err); + return err; + } + + memset(&q, 0, sizeof(q)); + q.size = sizeof(q); + q.query_flags = PROCFS_PROCMAP_EXACT_OR_NEXT_VMA; + q.vma_name_addr = (__u64)vma_name; + if (request_build_id) + q.build_id_addr = (__u64)build_id_buf; + + for (i = 0; i < addr_cnt; ) { + char *name = NULL; + + q.query_addr = (__u64)a->addr; + q.vma_name_size = sizeof(vma_name); + if (request_build_id) + q.build_id_size = sizeof(build_id_buf); + + err = ioctl(fd, PROCFS_PROCMAP_QUERY, &q); + if (err < 0 && errno == ENOTTY) { + close(fd); + fprintf(stderr, "PROCFS_PROCMAP_QUERY ioctl() command is not supported on this kernel!\n"); + return -EOPNOTSUPP; /* ioctl() not implemented yet */ + } + if (err < 0 && errno == ENOENT) { + fprintf(stderr, "ENOENT\n"); + i++; + a++; + continue; /* unresolved address */ + } + if (err < 0) { + err = -errno; + close(fd); + fprintf(stderr, "PROCFS_PROCMAP_QUERY ioctl() returned error: %d\n", err); + return err; + } + + /* skip addrs falling before current VMA */ + for (; i < addr_cnt && a->addr < q.vma_start; i++, a++) { + } + /* process addrs covered by current VMA */ + for (; i < addr_cnt && a->addr < q.vma_end; i++, a++) { + r = &resolved[a->idx]; + r->file_off = a->addr - q.vma_start + q.vma_offset; + + /* reuse name, if it was already strdup()'ed */ + if (q.vma_name_size) + name = name ?: strdup(vma_name); + r->vma_name = name; + + if (q.build_id_size) { + r->build_id_sz = q.build_id_size; + memcpy(r->build_id, build_id_buf, q.build_id_size); + } + } + } + + close(fd); + return 0; +} + +static int resolve_addrs_parse(void) +{ + size_t vma_start, vma_end, vma_offset, ino; + uint32_t dev_major, dev_minor; + char perms[4], buf[32], vma_name[PATH_MAX]; + FILE *f; + int err, idx = 0; + struct addr *a = &addrs[idx]; + struct resolved_addr *r; + + snprintf(buf, sizeof(buf), "/proc/%d/maps", pid); + f = fopen(buf, "r"); + if (!f) { + err = -errno; + fprintf(stderr, "Failed to open process map file (%s): %d\n", buf, err); + return err; + } + + while ((err = fscanf(f, "%zx-%zx %c%c%c%c %zx %x:%x %zu %[^\n]\n", + &vma_start, &vma_end, + &perms[0], &perms[1], &perms[2], &perms[3], + &vma_offset, &dev_major, &dev_minor, &ino, vma_name)) >= 10) { + const char *name = NULL; + + /* skip addrs before current vma, they stay unresolved */ + for (; idx < addr_cnt && a->addr < vma_start; idx++, a++) { + } + + /* resolve all addrs within current vma now */ + for (; idx < addr_cnt && a->addr < vma_end; idx++, a++) { + r = &resolved[a->idx]; + r->file_off = a->addr - vma_start + vma_offset; + + /* reuse name, if it was already strdup()'ed */ + if (err > 10) + name = name ?: strdup(vma_name); + else + name = NULL; + r->vma_name = name; + } + + /* ran out of addrs to resolve, stop early */ + if (idx >= addr_cnt) + break; + } + + fclose(f); + return 0; +} + +static int cmp_by_addr(const void *a, const void *b) +{ + const struct addr *x = a, *y = b; + + if (x->addr != y->addr) + return x->addr < y->addr ? -1 : 1; + return x->idx < y->idx ? -1 : 1; +} + +static int cmp_by_idx(const void *a, const void *b) +{ + const struct addr *x = a, *y = b; + + return x->idx < y->idx ? -1 : 1; +} + +int main(int argc, char **argv) +{ + FILE* f; + int err, i; + unsigned long long addr; + uint64_t start_ns; + double total_ns; + + /* Parse command line arguments */ + err = argp_parse(&argp, argc, argv, 0, NULL, NULL); + if (err) + return err; + + if (pid <= 0 || !addrs_path) { + fprintf(stderr, "Please provide PID and file with addresses to process!\n"); + exit(1); + } + + if (verbose) { + fprintf(stderr, "PID: %d\n", pid); + fprintf(stderr, "PATH: %s\n", addrs_path); + } + + f = fopen(addrs_path, "r"); + if (!f) { + err = -errno; + fprintf(stderr, "Failed to open '%s': %d\n", addrs_path, err); + goto out; + } + + while ((err = fscanf(f, "%llx\n", &addr)) == 1) { + if (addr_cnt == addr_cap) { + addr_cap = addr_cap == 0 ? 16 : (addr_cap * 3 / 2); + addrs = realloc(addrs, sizeof(*addrs) * addr_cap); + memset(addrs + addr_cnt, 0, (addr_cap - addr_cnt) * sizeof(*addrs)); + } + + addrs[addr_cnt].addr = addr; + addrs[addr_cnt].idx = addr_cnt; + + addr_cnt++; + } + if (verbose) + fprintf(stderr, "READ %zu addrs!\n", addr_cnt); + if (!feof(f)) { + fprintf(stderr, "Failure parsing full list of addresses at '%s'!\n", addrs_path); + err = -EINVAL; + fclose(f); + goto out; + } + fclose(f); + if (addr_cnt == 0) { + fprintf(stderr, "No addresses provided, bailing out!\n"); + err = -ENOENT; + goto out; + } + + resolved = calloc(addr_cnt, sizeof(*resolved)); + + qsort(addrs, addr_cnt, sizeof(*addrs), cmp_by_addr); + if (verbose) { + fprintf(stderr, "SORTED ADDRS (%zu):\n", addr_cnt); + for (i = 0; i < addr_cnt; i++) { + fprintf(stderr, "ADDR #%d: %#llx\n", addrs[i].idx, addrs[i].addr); + } + } + + start_ns = get_time_ns(); + for (i = bench_runs ?: 1; i > 0; i--) { + if (use_ioctl) { + err = resolve_addrs_ioctl(); + } else { + err = resolve_addrs_parse(); + } + if (err) { + fprintf(stderr, "Failed to resolve addrs: %d!\n", err); + goto out; + } + } + total_ns = get_time_ns() - start_ns; + + if (bench_runs) { + fprintf(stderr, "BENCHMARK MODE. RUNS: %d TOTAL TIME (ms): %.3lf TIME/RUN (ms): %.3lf TIME/ADDR (us): %.3lf\n", + bench_runs, total_ns / 1000000.0, total_ns / bench_runs / 1000000.0, + total_ns / bench_runs / addr_cnt / 1000.0); + } + + /* sort them back into the original order */ + qsort(addrs, addr_cnt, sizeof(*addrs), cmp_by_idx); + + if (!quiet) { + printf("RESOLVED ADDRS (%zu):\n", addr_cnt); + for (i = 0; i < addr_cnt; i++) { + const struct addr *a = &addrs[i]; + const struct resolved_addr *r = &resolved[a->idx]; + + if (r->file_off) { + printf("RESOLVED #%d: %#llx -> OFF %#llx", + a->idx, a->addr, r->file_off); + if (r->vma_name) + printf(" NAME %s", r->vma_name); + if (r->build_id_sz) { + char build_id_str[41]; + int j; + + for (j = 0; j < r->build_id_sz; j++) + sprintf(&build_id_str[j * 2], "%02hhx", r->build_id[j]); + printf(" BUILDID %s", build_id_str); + } + printf("\n"); + } else { + printf("UNRESOLVED #%d: %#llx\n", a->idx, a->addr); + } + } + } +out: + free(addrs); + free(addrs_path); + free(resolved); + + return err < 0 ? -err : 0; +}