From patchwork Tue Jun 11 11:00:49 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13693428 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 7531BC25B76 for ; Tue, 11 Jun 2024 11:01:11 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 0B96A6B00AB; Tue, 11 Jun 2024 07:01:11 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id EC2DB6B00AC; Tue, 11 Jun 2024 07:01:10 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id D44AF6B00AD; Tue, 11 Jun 2024 07:01:10 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0012.hostedemail.com [216.40.44.12]) by kanga.kvack.org (Postfix) with ESMTP id B11E66B00AB for ; Tue, 11 Jun 2024 07:01:10 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 0EA6AA26BF for ; Tue, 11 Jun 2024 11:01:10 +0000 (UTC) X-FDA: 82218315900.26.5FD46B7 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf18.hostedemail.com (Postfix) with ESMTP id A6A801C0034 for ; Tue, 11 Jun 2024 11:01:07 +0000 (UTC) Authentication-Results: imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="QC/xfWhb"; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf18.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=1718103668; 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=DaJUfAifrLY79J8y7mFq2uYCy/DQsT1bjfecVL6JVKQ=; b=vnxTkKsn2piKydfHiBMiLdEPKTDcAm8cGqszn12Rm++PNh3EDNQO4kjL8XB4mxuvJJneSX cg4NQPl+xQlaNLonfEL9sv7yWSbbDZ0fDtgN+A3QBUNQUGDDEafjGxphwyxsjdR4Zx/JTL D6/LSAQbToG/YFGrVe7uPbzz2adSChE= ARC-Authentication-Results: i=1; imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="QC/xfWhb"; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf18.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=1718103668; a=rsa-sha256; cv=none; b=QtR077Fbsqja2jpJFO2rIPt/wRHDYfLACdEZvlXWRsyfH7bT2YXXu2SLRjULiHt6RiBMqq UBqQiSLR0YEZdiAwdy88tKk4DavwRmDGZa3XJMamgJi7lQoU3LtpxwiONHyanV1xGM8UJX KNoF3YYZou40z4Mwo1L9yyeWRzNgZFY= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id B85D1CE1B04; Tue, 11 Jun 2024 11:01:04 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id DB58AC2BD10; Tue, 11 Jun 2024 11:01:03 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1718103664; bh=xq2U4bFBc0pabPUqJTbe1F2n2yJ1049NA855TclycPE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=QC/xfWhbffx+WVoSOaXHIrUnxXSkewXhaNi/hgRmiGvJI3/DD7NRSwnxWZcGj2P0s fZwVBMkKJPQvIV9uvSVKFGMo/zQJr4cq+NnXcAszq9OqX5Z9eR9kW61xhStU7C8jSS Xjyv6ECW6oPbALlEKfFzg6ExTj8YLyFAn55kvzxGtAVGVBC4ZCXBxgLaddEPKKi1wv SeBXJMNvZSWeuP78EFBAvdpOSnSE1aCiEJ2S7Km4dZNGj08/4JrN1qgX1m+t4EJE59 h9FN2MySUaisAa4ve/QoWoCW0O0Vfke5qBKLSSJuGq8mb6m2fs4PvRAK/0Q03B/y5l XSVSYe62Ibt1g== 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, liam.howlett@oracle.com, surenb@google.com, rppt@kernel.org, Andrii Nakryiko Subject: [PATCH v4 1/7] fs/procfs: extract logic for getting VMA name constituents Date: Tue, 11 Jun 2024 04:00:49 -0700 Message-ID: <20240611110058.3444968-2-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240611110058.3444968-1-andrii@kernel.org> References: <20240611110058.3444968-1-andrii@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: A6A801C0034 X-Rspamd-Server: rspam10 X-Rspam-User: X-Stat-Signature: u1kf7k1e9xz3jcbq3x58edfnwa8w6sns X-HE-Tag: 1718103667-45916 X-HE-Meta: U2FsdGVkX1+MSjK3gXOdf6e64O4sTrm9bEyd2GAarA+zdxABoSMhXfBl+p4Na5Wm8UmaFLaf8LKDSnZFeNZLU9acfLHQdg7NLeILqVxPlVPzbMvr+lP0Cb4GFL+1r34CrN/Hwz0htd0wgTnvT0lSoEyFnvRm26Sehm2cvmvH52Uw2khCQMxmHCeS6LIXhah76xjqVWVTGxPfY27jGGmV1DMlryTDZfFrjP7u93vuUN4AksfKQxhjZn5i930YMthK8oYXNyNWEz37/bUA429itO7+g/T0uqKX6CMkTpFQLbnUDfufNewD1Keza7vPmQ651K++TCHGJ+wn/0cdBPUM0f1dyswcNfI/7TVKGIFjkfWdGI/VWp5cmCPz+yoTzlqtOgkf3Si0up0sHGp3+KcY4XmKerEf2LyqgfmJv3QZTtBNnItVQnu/7hDD7YTvDZDjfgExp/L+QlNNbXNPfOQPkXwXRD/3cWn8Ly6PxJGn4LBW4g7DU2lu3wRXd5LAR3Epp8UW3eGoS/ozyJgtIM5WzqXKGrF3ccXE8Ldn31sXXIoq9C6xv1PXYii0zpvbG+We+ClAQblC/4EEoM8ZohreXfhHs1kUMtnkRe3VVNlAVQ5I6202IKDH1uomgRQUaeWOIKD849qm3t7aUaGQPtwkrIZGfBYNNniDAiMyjDFApej9kprDBlVRnqAfvSQEZLgOvebXRbhcYmWD1zvxe5nVWH6MJL06kzl4hxyYT7ziE7l6utSylnsuyhpKBfunJqPs3sOxhBepWJCUdyiCOz6BXpGyWWyUmdOqmL5g2woOStjHbM7Bcm3+KX/Z5D7AIMN8oDHMZ8gCdpDGwINdB1IaU4Kl7eU5sJUh74JyM3PS+78Hzdc0r8Fn+oZT6kmimDQYuRqXvDUuinY3hJrHRxv3MS/ZiGSVX22V6Xbr6etsofwCUlBnoGIVlCwbFKnN3okoFS9qUgjgzQvUUdoXais hbvgjDHp nhEDWK75ukxqZUBBBhwUS42rp+f1RtbSaYA34W7Hq09ctvrMJiKNJwU12c36ofclFOr65ConPQAzz4b2RH4E9Gk6SzD1Y6CGK+vng4Xsd/qmqQC522XcsMnmjpk+D7P99rI0tu32xtyD0xTWzfhXGBR8gBjTB+jpQQJ58p2CNsf7h2Gw9rdcd3/7+JWFB73ohq6zLFCPIVhd7W8gCKolGwc6J/O2cxVnGDNEQr2CRZz9XIU/DHlrSAOM4kd/vDv19NLqqpiTwn5VRbJ8tZ3hZUY5V5Awpsa/1XVEN1zHH7xg+53IOMqVHrOqm4MH8ktSIxH0X 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 5aceb3db7565..2cc6220222e2 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 Tue Jun 11 11:00:50 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13693429 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 ED1C2C25B76 for ; Tue, 11 Jun 2024 11:01:14 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 795916B00B1; Tue, 11 Jun 2024 07:01:14 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 720516B00AD; Tue, 11 Jun 2024 07:01:14 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 524C96B00B1; Tue, 11 Jun 2024 07:01:14 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 23FA46B00AC for ; Tue, 11 Jun 2024 07:01:14 -0400 (EDT) Received: from smtpin07.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id D2A4A1A13AE for ; Tue, 11 Jun 2024 11:01:13 +0000 (UTC) X-FDA: 82218316026.07.E33B6B7 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf03.hostedemail.com (Postfix) with ESMTP id 3A97420010 for ; Tue, 11 Jun 2024 11:01:10 +0000 (UTC) Authentication-Results: imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=MUZ4YPlN; spf=pass (imf03.hostedemail.com: domain of andrii@kernel.org designates 145.40.73.55 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=1718103671; 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=2T6N75J1orc7ULIEVd1guA2lpkeL/cd6WJZOlYXrxJM=; b=zT/m5W4OykWD1sEzjgVqrqvq7OBqiXqckRlA+ghT/rZdkeBRJAhq5PoP0tRKIQXJYOAQR/ GCBSZPLt7iVlz+9+rMS0MM1H1+cB4o/lq2Q2pqWkuaoz7I1JN44PFy1Bk9ohQG40MUuPQ0 Kt2izn7/dv+pfCwsAWkoz0yfkM3wQLI= ARC-Authentication-Results: i=1; imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=MUZ4YPlN; spf=pass (imf03.hostedemail.com: domain of andrii@kernel.org designates 145.40.73.55 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=1718103671; a=rsa-sha256; cv=none; b=nQw0yZ4joeug6ZweIRnR9m6c06bIZUtFIKzF/bwGSNAxaVqjFhAx7X+ewD5adqT5N13c/b S9hi0IVPsgi4w9z8lOEyiqW2ZYSK+M9/8dC22ErJnjpKyJqeBlFL/Ps1V3cYTEmy6qClQC JWrd9ZhCG2FRznhps85lJTYEuTllLrY= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 2511BCE1B0D; Tue, 11 Jun 2024 11:01:08 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 36456C2BD10; Tue, 11 Jun 2024 11:01:07 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1718103667; bh=E1P187yNUymwjqI1MKUB/C75OM0qmgXt0BTgYJ6dQQo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=MUZ4YPlNFy1Cardta9mXYcfUhzCExz/eqsB64TRuSZuDDRHcqMpvUe2Mc5vYABcDr YcNqd/DkFslq3rK6KmpnuZHemLc5VpMdaIRpUpSZgBNHgxInJcQvKhDyxrHRtzQRqy HMxvrje3aF65HAsOCEuMyaaRFtILMYvUQOp9LgamWmZHJfz1pIL4Gsgku+qZAkadpI x5EBj+x7yEs3MdgHCPCmYGpI2/7ptQLHWhjMBX2k4Y9RsD4HLODzSn9SnBrkSxH9Kf R+PRrxKxYJNOfn7QsLlf4YWQ+aVBCJsX6atw3aJ5/FAdQ95g3Cya8PNuv4ntCLqqmq w/Nm4M2oAQ/YA== 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, liam.howlett@oracle.com, surenb@google.com, rppt@kernel.org, Andrii Nakryiko Subject: [PATCH v4 2/7] fs/procfs: implement efficient VMA querying API for /proc//maps Date: Tue, 11 Jun 2024 04:00:50 -0700 Message-ID: <20240611110058.3444968-3-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240611110058.3444968-1-andrii@kernel.org> References: <20240611110058.3444968-1-andrii@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 3A97420010 X-Rspamd-Server: rspam01 X-Stat-Signature: oa4r57yewe9usxin9eon16cxf8fnxb1k X-HE-Tag: 1718103670-430194 X-HE-Meta: U2FsdGVkX19iMLlKwE2NmqYXYgB9Veq98dJHgKE/2ALBAxvNTDXu9wos429RWsqljLKAzOfaTVAkxNdtw8UAL0SdAqq49QP0c6r2X3Z6ZGyo1GfHxaccSAYVkHsHjgELEPlaYSMeTrCuga2sAanf18Pkn9KgN9dvZ/fOhzIs6KD+gF6jEa3YbCDf2PWgT0FTdmmIGjqkKtBX5OV7dtS6Ifjh7lqKUs5ufp9NQl/LsPzzY3cGKlniyDMSpkIl2OVmgstPOgxVAF2BUr9HONJDhOJ8S4NTKtNvoHLEz3PLvaUsGE1MjUAywoAl/u5sLbEaFzk5mcj6bES8f67IWznFrRfo6xG9bfpygSRcRjYywZiMZ4MhrfQGvnG42AZJMW3ZcpWagJ+kaJRmPhEnln6Atrr1A4H5dUXB07RZklF4dbMw1zRK/f45elY6tiF5k6Nr/nbATr4tzWHMAxij6Mf+wVQeuQeAiM8tGlGguMxxrbmt8KklBE+MDRcuvJ73c9f/tYlFSbK/EYyqy/ELIKcxVES/DHFhC6UYYPK4ng685Sa0RC70OPmnrzmBuLN7A3xjBLbek0U9/HS/XGmaBke+n6bu+airf6/9umNsfLgm0d95Q5Ip5Ux0LnEWCwQt5q3uhkrln5CWdYnk5bP61KZlOqVB6aGcZiLnaJ2uAdXuUG8+8o2EA7PV7UR4ag0HCtvoKzjLhU7g8l09wKDmB5aBZKHjfsqsCNfDm08OWAucWeRA8sM1xKTLHkuhgd2eUdnu9/2hlv8QlCaUUcmhJp+Fkpg5l2TpVSfUjbTxUezA/yoWoJKspgiHw47dMs2TccUiJo435G9woxR7LrjkYOuZW+8EBfPAiexJ+m9bYRCqNR5qsyXNAtuQJQf5yNfpffsyH2YDTzsZFDu4SWi077/5rmFOOLjOBCLTp4m10FQYJmkFEUG/n9ZtxrUdwRIQlHjEkguLYZkQZ5Rx7j29ABL feXPpy4c Ch/FmsgKRvCe1o6zrBBmtKn7vWZw9CD5BfUjkq40ftyFks4Tn6/0vHHWf45UCeCDEGNZFEwh7FkAQH1TyGelfhRZqpYVVL8r/ofMR+mSG3GjUyLkhhxilCZmNeQL0uZiVwKUtoFFfwVrgB/O9/mdCkF05gcCuTY/YCrSfEgzhPuArP0dKcACbzE1cxqvjQvWp6uKGbt6Ky9Nn1W4X9G+FQeCJlkPTEXmd0ZUIG70c1b/CsNg= 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 (perf tool being one of them). Patterns of use differ, but they generally would fall into two categories. In on-demand pattern, a profiler/symbolizer would normally capture stack trace containing absolute memory addresses of some functions, and would then use /proc//maps file to find corresponding backing ELF files (normally, only executable VMAs are of interest), file offsets within them, and then continue from there to get yet more information (ELF symbols, DWARF information) to get human-readable symbolic information. This pattern is used by Meta's fleet-wide profiler, as one example. In preprocessing pattern, application doesn't know the set of addresses of interest, so it has to fetch all relevant VMAs (again, probably only executable ones), store or cache them, then proceed with profiling and stack trace capture. Once done, it would do symbolization based on stored VMA information. This can happen at much later point in time. This patterns is used by perf tool, as an example. In either case, 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). In practice, correctness can't be guaranteed (due to process dying before VMA data can be captured, or shared library being unloaded, etc), but any effort to maximize the chance of finding the VMA is appreciated. Unfortunately, for all the /proc//maps file universality and usefulness, it doesn't fit the above use cases 100%. First, it's main purpose is to emit all VMAs sequentially, but in practice captured addresses would fall only into a smaller 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. Second, it's a text based interface, which makes its programmatic use from applications and libraries more cumbersome and inefficient due to the need to handle text parsing to get necessary pieces of information. The overhead is actually payed both by kernel, formatting originally binary VMA data into text, and then by user space application, parsing it back into binary data for further use. For the on-demand pattern of usage, described above, 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 (after initial processing) to service future requests (if application requests to symbolize another set of addresses (for the same process), captured at some later time, which is typical for periodic/continuous profiling cases) to avoid higher costs of re-parsing this file. Or it has to choose to cache 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 loads or unloads shared libraries, or otherwise changed its set of VMAs somehow, e.g., through additional mmap() calls. In the latter case, it's the performance hit that comes from re-opening the file and 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's meant to address both non-selectiveness and text nature of /proc//maps, by giving user more control of what sort of VMA(s) needs to be queried, and being binary-based interface eliminates the overhead of text formatting (on kernel side) and parsing (on user space side). It's also designed to be extensible and forward/backward compatible by including required struct size field, which user has to provide. We use established copy_struct_from_user() approach to handle extensibility. 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 (PROCMAP_QUERY_COVERING_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 latter allows more efficient use, but, given it could be a surprising behavior, requires an explicit opt-in. There is another query flag that is useful for some use cases. PROCMAP_QUERY_FILE_BACKED_VMA instructs this API to only return file-backed VMAs. Combining this with PROCMAP_QUERY_COVERING_OR_NEXT_VMA makes it possible to efficiently iterate only file-backed VMAs of the process, which is what profilers/symbolizers are normally interested in. All the above querying flags can be combined with (also optional) set of desired VMA permissions flags. This allows to, for example, iterate only an executable subset of VMAs, which is what preprocessing pattern, used by perf tool, would benefit from, as the assumption is that captured stack traces would have addresses of executable code. This saves time by skipping non-executable VMAs altogether efficienty. All these querying flags (modifiers) are orthogonal and can be combined in a semantically meaningful and natural way. Basing this ioctl()-based API on top of /proc//maps's FD makes sense given it's querying the same set of VMA data. It's also benefitial because permission checks for /proc//maps is performed at open time once, and the actual data read of text contents of /proc//maps is done without further permission checks. We piggyback on this pattern with ioctl()-based API as well, as that's a desired property. Both for performance reasons, but also for security and flexibility reasons. Allowing application to open an FD for /proc/self/maps without any extra capabilities, and then passing it to some sort of profiling agent through Unix-domain socket, would allow such profiling agent to not require some of the capabilities that are otherwise expected when opening /proc//maps file for *another* process. This is a desirable property for some more restricted setups. This new ioctl-based implementation 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. 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. Earlier versions of this patch set were adding per-VMA locking, which is why we have a code structure that is ready for abstracting mmap_lock vs vm_lock differences (query_vma_setup(), query_vma_teardown(), and query_vma_find_by_addr()), but given anon_vma_name() is not yet compatible with per-VMA locking, initial implementation sticks to using only mmap_lock for now. It will be easy to add back per-VMA locking once all the pieces are ready later on. Which is why we keep existing code structure with setup/teardown/query helper functions. Signed-off-by: Andrii Nakryiko --- fs/proc/task_mmu.c | 218 ++++++++++++++++++++++++++++++++++++++++ include/uapi/linux/fs.h | 128 ++++++++++++++++++++++- 2 files changed, 345 insertions(+), 1 deletion(-) diff --git a/fs/proc/task_mmu.c b/fs/proc/task_mmu.c index 2cc6220222e2..534f2dbb5175 100644 --- a/fs/proc/task_mmu.c +++ b/fs/proc/task_mmu.c @@ -375,11 +375,229 @@ static int pid_maps_open(struct inode *inode, struct file *file) return do_maps_open(inode, file, &proc_pid_maps_op); } +#define PROCMAP_QUERY_VMA_FLAGS ( \ + PROCMAP_QUERY_VMA_READABLE | \ + PROCMAP_QUERY_VMA_WRITABLE | \ + PROCMAP_QUERY_VMA_EXECUTABLE | \ + PROCMAP_QUERY_VMA_SHARED \ +) + +#define PROCMAP_QUERY_VALID_FLAGS_MASK ( \ + PROCMAP_QUERY_COVERING_OR_NEXT_VMA | \ + PROCMAP_QUERY_FILE_BACKED_VMA | \ + PROCMAP_QUERY_VMA_FLAGS \ +) + +static int query_vma_setup(struct mm_struct *mm) +{ + return mmap_read_lock_killable(mm); +} + +static void query_vma_teardown(struct mm_struct *mm, struct vm_area_struct *vma) +{ + mmap_read_unlock(mm); +} + +static struct vm_area_struct *query_vma_find_by_addr(struct mm_struct *mm, unsigned long addr) +{ + return find_vma(mm, addr); +} + +static struct vm_area_struct *query_matching_vma(struct mm_struct *mm, + unsigned long addr, u32 flags) +{ + struct vm_area_struct *vma; + +next_vma: + vma = query_vma_find_by_addr(mm, addr); + if (!vma) + goto no_vma; + + /* user requested only file-backed VMA, keep iterating */ + if ((flags & PROCMAP_QUERY_FILE_BACKED_VMA) && !vma->vm_file) + goto skip_vma; + + /* VMA permissions should satisfy query flags */ + if (flags & PROCMAP_QUERY_VMA_FLAGS) { + u32 perm = 0; + + if (flags & PROCMAP_QUERY_VMA_READABLE) + perm |= VM_READ; + if (flags & PROCMAP_QUERY_VMA_WRITABLE) + perm |= VM_WRITE; + if (flags & PROCMAP_QUERY_VMA_EXECUTABLE) + perm |= VM_EXEC; + if (flags & PROCMAP_QUERY_VMA_SHARED) + perm |= VM_MAYSHARE; + + if ((vma->vm_flags & perm) != perm) + goto skip_vma; + } + + /* found covering VMA or user is OK with the matching next VMA */ + if ((flags & PROCMAP_QUERY_COVERING_OR_NEXT_VMA) || vma->vm_start <= addr) + return vma; + +skip_vma: + /* + * If the user needs closest matching VMA, keep iterating. + */ + addr = vma->vm_end; + if (flags & PROCMAP_QUERY_COVERING_OR_NEXT_VMA) + goto next_vma; +no_vma: + return ERR_PTR(-ENOENT); +} + +static int do_procmap_query(struct proc_maps_private *priv, void __user *uarg) +{ + struct procmap_query karg; + struct vm_area_struct *vma; + struct mm_struct *mm; + const char *name = NULL; + char *name_buf = NULL; + __u64 usize; + int err; + + if (copy_from_user(&usize, (void __user *)uarg, sizeof(usize))) + return -EFAULT; + /* argument struct can never be that large, reject abuse */ + if (usize > PAGE_SIZE) + return -E2BIG; + /* argument struct should have at least query_flags and query_addr fields */ + if (usize < offsetofend(struct procmap_query, query_addr)) + return -EINVAL; + err = copy_struct_from_user(&karg, sizeof(karg), uarg, usize); + if (err) + return err; + + /* reject unknown flags */ + if (karg.query_flags & ~PROCMAP_QUERY_VALID_FLAGS_MASK) + return -EINVAL; + /* either both buffer address and size are set, or both should be zero */ + if (!!karg.vma_name_size != !!karg.vma_name_addr) + return -EINVAL; + + mm = priv->mm; + if (!mm || !mmget_not_zero(mm)) + return -ESRCH; + + err = query_vma_setup(mm); + if (err) { + mmput(mm); + return err; + } + + vma = query_matching_vma(mm, karg.query_addr, karg.query_flags); + if (IS_ERR(vma)) { + err = PTR_ERR(vma); + vma = NULL; + 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 |= PROCMAP_QUERY_VMA_READABLE; + if (vma->vm_flags & VM_WRITE) + karg.vma_flags |= PROCMAP_QUERY_VMA_WRITABLE; + if (vma->vm_flags & VM_EXEC) + karg.vma_flags |= PROCMAP_QUERY_VMA_EXECUTABLE; + if (vma->vm_flags & VM_MAYSHARE) + karg.vma_flags |= PROCMAP_QUERY_VMA_SHARED; + + 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 vma or mmap_lock, and put mm_struct before copying data to user */ + query_vma_teardown(mm, vma); + 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 (copy_to_user(uarg, &karg, min_t(size_t, sizeof(karg), usize))) + return -EFAULT; + + return 0; + +out: + query_vma_teardown(mm, vma); + 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 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..f25e7004972d 100644 --- a/include/uapi/linux/fs.h +++ b/include/uapi/linux/fs.h @@ -333,8 +333,10 @@ typedef int __bitwise __kernel_rwf_t; #define RWF_SUPPORTED (RWF_HIPRI | RWF_DSYNC | RWF_SYNC | RWF_NOWAIT |\ RWF_APPEND | RWF_NOAPPEND) +#define PROCFS_IOCTL_MAGIC 'f' + /* Pagemap ioctl */ -#define PAGEMAP_SCAN _IOWR('f', 16, struct pm_scan_arg) +#define PAGEMAP_SCAN _IOWR(PROCFS_IOCTL_MAGIC, 16, struct pm_scan_arg) /* Bitmasks provided in pm_scan_args masks and reported in page_region.categories. */ #define PAGE_IS_WPALLOWED (1 << 0) @@ -393,4 +395,128 @@ struct pm_scan_arg { __u64 return_mask; }; +/* /proc//maps ioctl */ +#define PROCMAP_QUERY _IOWR(PROCFS_IOCTL_MAGIC, 17, struct procmap_query) + +enum procmap_query_flags { + /* + * VMA permission flags. + * + * Can be used as part of procmap_query.query_flags field to look up + * only VMAs satisfying specified subset of permissions. E.g., specifying + * PROCMAP_QUERY_VMA_READABLE only will return both readable and read/write VMAs, + * while having PROCMAP_QUERY_VMA_READABLE | PROCMAP_QUERY_VMA_WRITABLE will only + * return read/write VMAs, though both executable/non-executable and + * private/shared will be ignored. + * + * PROCMAP_QUERY_VMA_* flags are also returned in procmap_query.vma_flags + * field to specify actual VMA permissions. + */ + PROCMAP_QUERY_VMA_READABLE = 0x01, + PROCMAP_QUERY_VMA_WRITABLE = 0x02, + PROCMAP_QUERY_VMA_EXECUTABLE = 0x04, + PROCMAP_QUERY_VMA_SHARED = 0x08, + /* + * Query modifier flags. + * + * By default VMA that covers provided address is returned, or -ENOENT + * is returned. With PROCMAP_QUERY_COVERING_OR_NEXT_VMA flag set, closest + * VMA with vma_start > addr will be returned if no covering VMA is + * found. + * + * PROCMAP_QUERY_FILE_BACKED_VMA instructs query to consider only VMAs that + * have file backing. Can be combined with PROCMAP_QUERY_COVERING_OR_NEXT_VMA + * to iterate all VMAs with file backing. + */ + PROCMAP_QUERY_COVERING_OR_NEXT_VMA = 0x10, + PROCMAP_QUERY_FILE_BACKED_VMA = 0x20, +}; + +/* + * Input/output argument structured passed into ioctl() call. It can be used + * to query a set of VMAs (Virtual Memory Areas) of a process. + * + * Each field can be one of three kinds, marked in a short comment to the + * right of the field: + * - "in", input argument, user has to provide this value, kernel doesn't modify it; + * - "out", output argument, kernel sets this field with VMA data; + * - "in/out", input and output argument; user provides initial value (used + * to specify maximum allowable buffer size), and kernel sets it to actual + * amount of data written (or zero, if there is no data). + * + * If matching VMA is found (according to criterias specified by + * query_addr/query_flags, all the out fields are filled out, and ioctl() + * returns 0. If there is no matching VMA, -ENOENT will be returned. + * In case of any other error, negative error code other than -ENOENT is + * returned. + * + * Most of the data is similar to the one returned as text in /proc//maps + * file, but procmap_query provides more querying flexibility. There are no + * consistency guarantees between subsequent ioctl() calls, but data returned + * for matched VMA is self-consistent. + */ +struct procmap_query { + /* Query struct size, for backwards/forward compatibility */ + __u64 size; + /* + * Query flags, a combination of enum procmap_query_flags values. + * Defines query filtering and behavior, see enum procmap_query_flags. + * + * Input argument, provided by user. Kernel doesn't modify it. + */ + __u64 query_flags; /* in */ + /* + * Query address. By default, VMA that covers this address will + * be looked up. PROCMAP_QUERY_* flags above modify this default + * behavior further. + * + * Input argument, provided by user. Kernel doesn't modify it. + */ + __u64 query_addr; /* in */ + /* VMA starting (inclusive) and ending (exclusive) address, if VMA is found. */ + __u64 vma_start; /* out */ + __u64 vma_end; /* out */ + /* VMA permissions flags. A combination of PROCMAP_QUERY_VMA_* flags. */ + __u64 vma_flags; /* out */ + /* + * VMA file offset. If VMA has file backing, this specifies offset + * within the file that VMA's start address corresponds to. + * Is set to zero if VMA has no backing file. + */ + __u64 vma_offset; /* out */ + /* Backing file's inode number, or zero, if VMA has no backing file. */ + __u64 inode; /* out */ + /* Backing file's device major/minor number, or zero, if VMA has no backing file. */ + __u32 dev_major; /* out */ + __u32 dev_minor; /* out */ + /* + * If set to non-zero value, signals the request to return VMA name + * (i.e., VMA's backing file's absolute path, with " (deleted)" suffix + * appended, if file was unlinked from FS) for matched VMA. VMA name + * can also be some special name (e.g., "[heap]", "[stack]") or could + * be even user-supplied with prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME). + * + * Kernel will set this field to zero, if VMA has no associated name. + * Otherwise kernel will return actual amount of bytes filled in + * user-supplied buffer (see vma_name_addr field below), including the + * terminating zero. + * + * If VMA name is longer that user-supplied maximum buffer size, + * -E2BIG error is returned. + * + * If this field is set to non-zero value, vma_name_addr should point + * to valid user space memory buffer of at least vma_name_size bytes. + * If set to zero, vma_name_addr should be set to zero as well + */ + __u32 vma_name_size; /* in/out */ + /* + * User-supplied address of a buffer of at least vma_name_size bytes + * for kernel to fill with matched VMA's name (see vma_name_size field + * description above for details). + * + * Should be set to zero if VMA name should not be returned. + */ + __u64 vma_name_addr; /* in */ +}; + #endif /* _UAPI_LINUX_FS_H */ From patchwork Tue Jun 11 11:00:51 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13693430 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 755B7C27C75 for ; Tue, 11 Jun 2024 11:01:17 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E50316B00AC; Tue, 11 Jun 2024 07:01:15 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id DD77B6B00AD; Tue, 11 Jun 2024 07:01:15 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id C03956B00B2; Tue, 11 Jun 2024 07:01:15 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id 998286B00AC for ; Tue, 11 Jun 2024 07:01:15 -0400 (EDT) Received: from smtpin01.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 44A32A27CF for ; Tue, 11 Jun 2024 11:01:15 +0000 (UTC) X-FDA: 82218316110.01.A8853D3 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf24.hostedemail.com (Postfix) with ESMTP id 4773C180016 for ; Tue, 11 Jun 2024 11:01:12 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DaXC3o00; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 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=1718103672; 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=zFIAdRJjcqVY4q+WP7p/dSviF8VvQtCH3OihxvuS13I=; b=rDGxSw/6reRjv6hn4qFGmSC/GWPvcOPvZvc9r4k53ick+/vHzijf0WK/b/W/60vGY2tbqH IkfOQFssYEyCIQky3FFJ5o1s26W+Ew+ky1mwY6SXzim+AUig8yGyI+sFJlMQj+Fcl5bjr9 83fD7pcR/HoGP48AdJ6qGDkLv+LNxV8= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DaXC3o00; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=andrii@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1718103672; a=rsa-sha256; cv=none; b=GTExb3BqPJBndNHzkWm00n/ccj7cjjjwpvttmndW3OMrOgyfIUSMESirleJGqGd+mKybrH WNtSk1mXpXoHsr7jg28tsQK7YH5D+HdmFneHCD6XxmzbZ00N2MvxO/0nDtUZOHlU97yDaG 2OC1dDldMG/bXLoAwHNcVWASmk+/lE8= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 12CC360C71; Tue, 11 Jun 2024 11:01:11 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8CB6DC32786; Tue, 11 Jun 2024 11:01:10 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1718103670; bh=ABTqOOEfJVePTVcWRG7oSFkHsd6dWZCvE/bT2jUog+g=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DaXC3o00deV4bsRGzIaS6LGKPgx1tlb6kfI0ATeFD8qe8eaCxLMfxs6oWUJ3NEDoZ LnwDTE5zKfKzXnSieLjOO9UxeqxOGl990nXF89pnpwx6oT3/Y7j8Dkp0+iO8WAXdu8 D2/gjoshpRHXKiEve8pTgdBmIhSzEvjhzCL7GcjLsuQnpeWbwT5LMPAHo/z2QPjJKH /I1oD8k3R2mPjOuIh0g5yvdiUzS9+OH5r66mSmaK5qK18RZ87+IVn2sZKlj2Sayux+ 6EikV3EWJemXTWuP2i4M9jgZCrnfrq0wD2oyOwayby8F2pybWGNGQSv5UBlVyO8Y6t BNAnsuQxODGLw== 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, liam.howlett@oracle.com, surenb@google.com, rppt@kernel.org, Andrii Nakryiko Subject: [PATCH v4 3/7] fs/procfs: add build ID fetching to PROCMAP_QUERY API Date: Tue, 11 Jun 2024 04:00:51 -0700 Message-ID: <20240611110058.3444968-4-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240611110058.3444968-1-andrii@kernel.org> References: <20240611110058.3444968-1-andrii@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 4773C180016 X-Rspamd-Server: rspam10 X-Rspam-User: X-Stat-Signature: rs4cdch6higr4nhac13f8gc591cqok9t X-HE-Tag: 1718103672-12046 X-HE-Meta: U2FsdGVkX18GKTmNosnixPsAHAU/imQSnIYgPkW8MPqny/QuWFzuOuFnD+v76GGzvJhjJVBhaCP5pRWkjXuN4JDOslP/tIBhBgVhGRIxxiXF2zyvNsp7wvRWhyKPLJoHAb1G+SPgiWLe9SrnUDLEBTqxpzCdqDoWEIyNhhqT7C0awetlXnYIZARVrJHdOigBKLtsIURT5J4aguEHUuCyQgceSQewHQJFRTvogHvrpt4IVCsJzZDqH3CSIegoYDD6K5j9vez7hEgVP4xfV/SYC+a2Xk28r7qwTDFIxGoX3A/prh51eeYHJ+oVgHavtAZ2hqk1tXpTY2X4KbIwwPUUsc6dDoRWNk/hXrAuFVKim90liy+jpFYXW4DZrEui16e4G706docqNdVc1NN3xU0ZweaId9Dar2o/+TPNlv4wDHsR2b7Z/QPn4v8cR1AV9y3gN9Xz3kIX3VhQZNM0j9evnY6BwvuQkTsowPI9yovAAr0kSTa6Pm5Ojuts+8z0viC1Vf2uZEabv2jrgAt0c/3ayPy+ecuLx0Ip5piZGiXOwxObT53ykf7DINBP+5AiPQVsO0nkkZc3ChrDivbOmMvPPMo/Uw+xpbZndy01i9NS6baEAXKpy72RRQtZ1NRgqNeaM8v+bfCGFbfnu4aLXhTznwv/IBu/1HtsBYuf+a+BTyY+a5qkYA64cK8wxYEQekDMV6VVrnIG8VBGr9mA/EKog6/EqhhNE2ab1gsTh7943utlASUL9IwGx9jgLa9UBEnx9gtAex4dRJwKpky1PEeAog8NLNXQv+y94mcdGiU/590eov/cCcmYS+D3EmTD9Azg5mc4x+snSq1pCg9cYvUvReT5T9Qv2I5fujrV1pqZD+prTKff74TMkXtZR1c5szX5NyjRnRkuBpi56VZ+J+WeyZOj9y/64NGnUQmAF1NW4bMCxWECZJ7D6ldxKcOYZo2NfRwdaWYjCzDT04PGeZ0 m14IgyAT SUYTS6C42FFJRyFDZSNxQA6DhfWX8c40GCbQKiOjLb3SHHpCG2HrMVsVXz43xPCaLb7Qd/x9x4TmJGYCdigjL0dDYlXXePwCO3avpDG0vynZCOYaa1VhNaAHG0PLDyaGvJTVPWWhoMzwyK5GXfvVdCJKb5eIwgzsBlzMdR8x4X3/9YzapuPWRsDy8V4NhuLO3XMgb+MU+iFERg+pi3bnz8PTBe5bI+6AFuktsCdwDPZpWxIxSa7cVpr7vRVZMiDq46u0uSAmyYg7DReehUXk3AYubQ46FFzz3XvjQ 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: 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. To get backing file's ELF build ID, application has to first resolve VMA, then use it's start/end address range to follow a special /proc//map_files/- symlink to open the ELF file (this is necessary because backing file might have been removed from the disk or was already replaced with another binary in the same file path. Such approach, beyond just adding complexity of having to do a bunch of extra work, has extra security implications. Because application opens underlying ELF file and needs read access to its entire contents (as far as kernel is concerned), kernel puts additional capable() checks on following /proc//map_files/- symlink. And that makes sense in general. But in the case of build ID, profiler/symbolizer doesn't need the contents of ELF file, per se. It's only build ID that is of interest, and ELF build ID itself doesn't provide any sensitive information. So this patch adds a way to request backing file's ELF build ID along the rest of VMA information in the same API. 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). This is a completely optional piece of information, and so has no performance implications for user cases that don't care about build ID, while improving performance and simplifying the setup for those application that do need it. 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). Signed-off-by: Andrii Nakryiko --- fs/proc/task_mmu.c | 25 ++++++++++++++++++++++++- include/uapi/linux/fs.h | 28 ++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/fs/proc/task_mmu.c b/fs/proc/task_mmu.c index 534f2dbb5175..80543aed7ddd 100644 --- a/fs/proc/task_mmu.c +++ b/fs/proc/task_mmu.c @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -445,6 +446,7 @@ static struct vm_area_struct *query_matching_vma(struct mm_struct *mm, addr = vma->vm_end; if (flags & PROCMAP_QUERY_COVERING_OR_NEXT_VMA) goto next_vma; + no_vma: return ERR_PTR(-ENOENT); } @@ -455,7 +457,7 @@ static int do_procmap_query(struct proc_maps_private *priv, void __user *uarg) struct vm_area_struct *vma; struct mm_struct *mm; const char *name = NULL; - char *name_buf = NULL; + char build_id_buf[BUILD_ID_SIZE_MAX], *name_buf = NULL; __u64 usize; int err; @@ -477,6 +479,8 @@ static int do_procmap_query(struct proc_maps_private *priv, void __user *uarg) /* either both buffer address and size are set, or both should be zero */ 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)) @@ -522,6 +526,21 @@ static int do_procmap_query(struct proc_maps_private *priv, void __user *uarg) if (vma->vm_flags & VM_MAYSHARE) karg.vma_flags |= PROCMAP_QUERY_VMA_SHARED; + if (karg.build_id_size) { + __u32 build_id_sz; + + err = build_id_parse(vma, build_id_buf, &build_id_sz); + if (err) { + karg.build_id_size = 0; + } else { + 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; @@ -566,6 +585,10 @@ static int do_procmap_query(struct proc_maps_private *priv, void __user *uarg) } 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; diff --git a/include/uapi/linux/fs.h b/include/uapi/linux/fs.h index f25e7004972d..7306022780d3 100644 --- a/include/uapi/linux/fs.h +++ b/include/uapi/linux/fs.h @@ -509,6 +509,26 @@ struct procmap_query { * If set to zero, vma_name_addr should be set to zero as well */ __u32 vma_name_size; /* in/out */ + /* + * If set to non-zero value, signals the request to extract and return + * VMA's backing file's build ID, if the backing file is an ELF file + * and it contains embedded build ID. + * + * Kernel will set this field to zero, if VMA has no backing file, + * backing file is not an ELF file, or ELF file has no build ID + * embedded. + * + * Build ID is a binary value (not a string). Kernel will set + * build_id_size field to exact number of bytes used for build ID. + * If build ID is requested and present, but needs more bytes than + * user-supplied maximum buffer size (see build_id_addr field below), + * -E2BIG error will be returned. + * + * If this field is set to non-zero value, build_id_addr should point + * to valid user space memory buffer of at least build_id_size bytes. + * If set to zero, build_id_addr should be set to zero as well + */ + __u32 build_id_size; /* in/out */ /* * User-supplied address of a buffer of at least vma_name_size bytes * for kernel to fill with matched VMA's name (see vma_name_size field @@ -517,6 +537,14 @@ struct procmap_query { * Should be set to zero if VMA name should not be returned. */ __u64 vma_name_addr; /* in */ + /* + * User-supplied address of a buffer of at least build_id_size bytes + * for kernel to fill with matched VMA's ELF build ID, if available + * (see build_id_size field description above for details). + * + * Should be set to zero if build ID should not be returned. + */ + __u64 build_id_addr; /* in */ }; #endif /* _UAPI_LINUX_FS_H */ From patchwork Tue Jun 11 11:00:52 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13693431 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 B890FC25B76 for ; Tue, 11 Jun 2024 11:01:20 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 91DBE6B00AD; Tue, 11 Jun 2024 07:01:17 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 8A8566B00B2; Tue, 11 Jun 2024 07:01:17 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 6FB286B00B3; Tue, 11 Jun 2024 07:01:17 -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 4963D6B00AD for ; Tue, 11 Jun 2024 07:01:17 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id C68794149F for ; Tue, 11 Jun 2024 11:01:16 +0000 (UTC) X-FDA: 82218316152.28.8E71F5B Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf30.hostedemail.com (Postfix) with ESMTP id 1AC1880002 for ; Tue, 11 Jun 2024 11:01:14 +0000 (UTC) Authentication-Results: imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Foktfj8Q; spf=pass (imf30.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=1718103675; a=rsa-sha256; cv=none; b=mKw3KbZYw3iOvEwuPOHpkujcSkRi++PPz94NtmkyLCIlCbQOv9eblf6fNWqoantYt24YJc GUlk8jI2Xpx7r3TTeYVyfK1G1kE9Cxo8e2dylEXw9Oe3Pp/UjXUpeHVK8lcG+QFoj+ynRC 7ztXQ/m0OULQ51eXrQ6Au+Awr7QZRU8= ARC-Authentication-Results: i=1; imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Foktfj8Q; spf=pass (imf30.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=1718103675; 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=uaSDq1lGIzGZFGTm4J0RFROnpeOyP4Nkt1fRMznsfm4=; b=ukaccj8MigbkdiXQF753zLynaEA6Ctgt4lCQsF+0vMKDOHID7ShKInX663h+MzNlDLxSxe 972AJXdkvTKNUq2qYR3/AVtctjlpD6Y3asqblriIBmgHrRzlg/jbeJ4Ll6R7FWa/dVmGMY 0H5f2ggv6SIginIOslidm8ygLCviOzc= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 3684A60DD6; Tue, 11 Jun 2024 11:01:14 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C79B1C4AF1C; Tue, 11 Jun 2024 11:01:13 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1718103674; bh=vBH/6OYdVjsNNyjp2pikvMXvKQezYlNPmAqHiQSiZF0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Foktfj8QEBkhkirvVOBKEf6XICDJq6ObR9pscnonkImbxnlWTGr+tmP5foto8XmEs JoieWu/Q+B5NF5ppUo3rK96S6DYaVxtt8zdpgPWcXb9MNP8J9Y6/imP934OE7VMnNc Rke55cMw9xbBNa0vw5kM/EP0l+vlE3ax5ezQ+Pg827CfLwaSeWk2qSXGPeiLibAZbe DHyZrsCQOX/GqneNFqoU46MnMxtUEjFcwKNRr09+xmXZMu3GHEcXqTA7vnJ/90mQ+e 0aQadq0REIZuepZIkD46DlaV2S/RRDewk1IE9M91fzJQa2ADAjjk2ifEm7ejw2KCA6 tH1SJ1l6Wg27w== 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, liam.howlett@oracle.com, surenb@google.com, rppt@kernel.org, Andrii Nakryiko Subject: [PATCH v4 4/7] docs/procfs: call out ioctl()-based PROCMAP_QUERY command existence Date: Tue, 11 Jun 2024 04:00:52 -0700 Message-ID: <20240611110058.3444968-5-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240611110058.3444968-1-andrii@kernel.org> References: <20240611110058.3444968-1-andrii@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 1AC1880002 X-Rspam-User: X-Rspamd-Server: rspam12 X-Stat-Signature: rqpbxmaj49ai9bn7ca9ugz8b7s48hoqy X-HE-Tag: 1718103674-317927 X-HE-Meta: U2FsdGVkX1+bls5/i/IINqS4CZQsuGImJ9KKc23KZwG+wK5zTcA5qcDRI8iJwn3T+INpbEVabUT897nrTjHLxT7exOgX74P1awF/MhKmH+jZ91bATHkNZ86sF2YxZgthzDziXE6wLGRoOlPOn0IsW8sdv0VnqqqWLbT6+K3nCFD7ssWOvcZICvQD7CeYtMNzcknbL5bMOPXpU2zwkbVtIBJ4ojqkjnHGisq8wcxxVaAQNlwB966qrl2nZZ/f4knene/ml90kJD9cnuCinXXt77ReVtzJJdy3nhN2iyIHV6eRCkdfq852XMJVV+am0Z17ZTJ/roxI7XQwRQiD+rSvgO2d+pCpNAwmeyO0djahVTRz72hldSWnhqOtAEz9MvS0OMqM/dWYkdl+rKCu/EWDsfNFThpvwDqC69th6lQ4/tuTmiZkpef6f11xqihNXBg7zNcqs8zGoXcaW/R61VOCEYw+e35OyHxP4IpzCIW436CDah6w9aSID5+tnQWulbjATYMPnekzEBX17H33TO8Q0+kMpQtGQinC4GT3YE8guchg6mwNKFhKGvRjVnDHXfaHRMVzW0V2xP60EDbrzuTQvXMHlVR+NwD2LXqevxJVYf6DbG/jnfb7KgfnSQiirmQ6S/rylQJ2a3SQBHn9Dic0d0L5/7esnJ3XqprK8+ej6dglMSw5l1KKZUPgsYjySPRorpAlKmu17TXD8+K3xIm5Pz2bytMeS+iLinmPN4lbRGSAOhXnoQp3Fn85phZjhMXAJYgmjWlS9Frk4T84RiaE79V7fa4GC5wc1avtbiOH26wKdUxvGyMah5v+dibnuHAuRrW+q/DLIedl5J/rwsQWFpkje2xE1jtIHuMpGG15kz66IS3aOXakeT6i/u+joeY4v6zlPhTQyLhjWnJw799I0i39Cybu3Hk/Lze0325D6MzaBJneX7hhpGZ7vRUv7QuXghvwY5M1j9eHOS0o5c0 WbAakEQJ svDVXeuEqwGzjgbbFSjthiGT3F0dZSW3YgST5xVhfvUA+yAC1kej92deshhBEQbqMx5ci5n0jVcXlpvzGd7fBNG/UtcNjAIhWjhtH+LuQMmqNyXL8FUwsXmhM/xi+AsxNjwJCFT/2tsl30/7w94VvLKE2lkTetC0/U6eTT9o2UWvcziwaF4LrdIjmXkcvi3T98wizf29J9WQfWioR0VVWCtVHKydHIl1wBGq4e9PGp1CQHVyUiuVhzZl24jXK4hN+cNX8YUn3TFC5ImcPQ8JM07fM4ab7luIZA2ar 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: Call out PROCMAP_QUERY ioctl() existence in the section describing /proc/PID/maps file in documentation. We refer user to UAPI header for low-level details of this programmatic interface. Signed-off-by: Andrii Nakryiko --- Documentation/filesystems/proc.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Documentation/filesystems/proc.rst b/Documentation/filesystems/proc.rst index 7c3a565ffbef..3a86d12c881f 100644 --- a/Documentation/filesystems/proc.rst +++ b/Documentation/filesystems/proc.rst @@ -443,6 +443,15 @@ is not associated with a file: or if empty, the mapping is anonymous. +Starting with 6.11 kernel, /proc/PID/maps provides an alternative +ioctl()-based API that gives ability to flexibly and efficiently query and +filter individual VMAs. This interface is binary and is meant for more +efficient and easy programmatic use. `struct procmap_query`, defined in +linux/fs.h UAPI header, serves as an input/output argument to the +`PROCMAP_QUERY` ioctl() command. See comments in linus/fs.h UAPI header for +details on query semantics, supported flags, data returned, and general API +usage information. + The /proc/PID/smaps is an extension based on maps, showing the memory consumption for each of the process's mappings. For each mapping (aka Virtual Memory Area, or VMA) there is a series of lines such as the following:: From patchwork Tue Jun 11 11:00:53 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13693432 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 E7548C25B76 for ; Tue, 11 Jun 2024 11:01:23 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D1A206B00B3; Tue, 11 Jun 2024 07:01:20 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id C9EA16B00B4; Tue, 11 Jun 2024 07:01:20 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id AA73A6B00B5; Tue, 11 Jun 2024 07:01:20 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id 7B9FC6B00B3 for ; Tue, 11 Jun 2024 07:01:20 -0400 (EDT) Received: from smtpin04.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 317ADC1489 for ; Tue, 11 Jun 2024 11:01:20 +0000 (UTC) X-FDA: 82218316320.04.2246A67 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf15.hostedemail.com (Postfix) with ESMTP id 80736A002A for ; Tue, 11 Jun 2024 11:01:18 +0000 (UTC) Authentication-Results: imf15.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="tP81B/tI"; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf15.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 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=1718103678; 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=OkCHTAsFlJWRbK0KwrLwuOSgEGBAJd1XNMflclCcVvc=; b=TOyPLR8KRbMY7YGlObU17j/km2NB9DlpPGNBqbDXWAeTKD+d9hjM2pRB1gaE8XOFCZlu1k r+h0tJmiF8NbWGoISpdLLQCsDighS/x/UeaPW8n9yMCtdbSC2I8DgCR8N5OyqSIvFXBSvx ot6bzt80evriqNs6ZSDR3vhV4OeOe/4= ARC-Authentication-Results: i=1; imf15.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="tP81B/tI"; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf15.hostedemail.com: domain of andrii@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=andrii@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1718103678; a=rsa-sha256; cv=none; b=sjxurHX2IDgpUzjFowy8qudKrV1l0RYzygdMOWT7fXK6JlGmhG+z0Geb/i1XYaUuQv6w9C bSLtdd7Z38uUwSEuNqoDxqztO0PXgf/x6D9y8uetaKG5ypz1evdeUomQFqHXOwb7iWRkzp cXUoN2nQ2gWvkbmOEPvLZADtvS0+2TI= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 7F2F860DD3; Tue, 11 Jun 2024 11:01:17 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 14522C32789; Tue, 11 Jun 2024 11:01:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1718103677; bh=XhT7MyIpfN/Vsi8sYrA9Vx1PIwjnTH2I6tc+o8hojXY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=tP81B/tIMOmXFuFB/8IHeIDqgEW9Euh+r5om1kwPttzwAcAJeEeS69AwTNxTF9Swf /HWLcv5OA4tBUIXlpoo05hABs+eg8SkHY/TT8rjnD88P7nSYmcxLbAtpbbJ7UWM1F0 m4boTr6jMa3O7gQ75Qf+CQW3xL2kHF8H4ceuHWUOTxfYtM47Tq8FOl9KHfvEc7C8VJ y4o4eJD23DNIWi9BKc6fegdXH32dGJVZPSJzaR8OdP+O2wOfB1bi/cN1ocf4Qo8TYY 2EQtXLXo9tTSE0IBdU9Hr4tFOEhljOUt7QMmmf9IH1wh8/ZR14eeG+FyzKz3t36RnZ bfWF6sj2hoVMw== 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, liam.howlett@oracle.com, surenb@google.com, rppt@kernel.org, Andrii Nakryiko Subject: [PATCH v4 5/7] tools: sync uapi/linux/fs.h header into tools subdir Date: Tue, 11 Jun 2024 04:00:53 -0700 Message-ID: <20240611110058.3444968-6-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240611110058.3444968-1-andrii@kernel.org> References: <20240611110058.3444968-1-andrii@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 80736A002A X-Stat-Signature: i5c9a79jd5tr1ua6qzpuopzjff4k7xam X-Rspam-User: X-HE-Tag: 1718103678-979195 X-HE-Meta: U2FsdGVkX1/KmPBT+k11sxbWOPi54FNIwbVorY+MIiytRFIK+32wHjLGFWLzPyDf1y6Gn4pZIGovDUQAfXoRTmm/iZiK4U1lvwBr/8yrIwTF493pWjv+CTP1At+BCXqc+D2GNXXcWpjlxmveuYU9/1hUtHkHNtAUUNSnkqZFXkzM2i3xN+P4Nm9VM+VCYCiyB6iIi+TzeRvK0T3fly15dP1WWslvVfZ2i9LIyIKkx7eP/oJXA/6EpwJv+Cwu/4k+bKibpeQxURdHxibzpe0nJPA8gaH2tagFIAY3/pCW5Lf09jYLCK00swAdvy54hWkPFK7vWHzL8E+oUroSIjPt4UrT0ImrpjiCfzUqiQj/u/g7ON6PHHD2D75fy2bFbmUTawjic0/oUOd2wcVkEPVO8J40SgMN8roQ5ObDcF0I9eXEjtAykUn8IanVjVYF2qMwSz8QghRyIiy4K3wmJ7NFOUyNNXTaNqsQaDoUayd8ysYCrNKNaLRc7UWblkWBC2WL6bnHGX45qZhdYWa6HWGTV+3ltXMj7DLbN5Y7xMXFRSHvLbct91BF5jg82EHVPe92NUG9cG5moep2TmGZwkGiPfPn3v9Pj2/ZNvVjkktheriZ9LeTLRrcqNtm5fqomk5aHL+7cN3Wvye73F0CgntloSDzdI7zsDANtaoA2t3vsX6uB/3NVDE3AEZfngWSRoncZGOW1YqOrfxUqyCL7JAX5eJOOLgJozUFO/84e+ZyrWDZql3mtiI7t4LbG/aQtNJ5axGQLHVDrqXS6/18E0BT3CrN5y6aBSpCH02n/3juLVy2CIGqUzMPeCMoZLpbX9rDF8wqpoaAdaJ0cQ/wX1MAqSr1pPMZ6fKH88xA/5fToK2rWI/+YJNZrzKrM/qeEDNLOtHiL1R7hCV4ml/+5CFMpwKS/H1h5pR/eWVlgweW1xdQA6ZbrsAqNHr1ZVAxh8y1az3/pWGA5KTTn0kFMte 63RHPjKC HFimiqjPp443fTfYQjsFp4YqEsBenTysG2cxbJG5Ta4QQKb5ogviUJbjrF6fmefM3ul+9leZp5EhckA71icxXD0yfRmWJ/8pBgdLMWICo3p2VTUDgj/eU2/chdMYG+aBatipzOLRz9xGcx5N3w5lxikOhYIqGEsauA1visLDFnHaievMOA4uY+JcGQFjl2pxfldLLmWYRo7qN8DrSd/AY2zOwNWEPZN7BuHDE4v9ILtAa7rX7+D64u+D7yQ== 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: We need this UAPI header in tools/include subdirectory for using it from BPF selftests. Signed-off-by: Andrii Nakryiko --- tools/include/uapi/linux/fs.h | 550 ++++++++++++++++++++++++++++++++++ 1 file changed, 550 insertions(+) create mode 100644 tools/include/uapi/linux/fs.h diff --git a/tools/include/uapi/linux/fs.h b/tools/include/uapi/linux/fs.h new file mode 100644 index 000000000000..7306022780d3 --- /dev/null +++ b/tools/include/uapi/linux/fs.h @@ -0,0 +1,550 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _UAPI_LINUX_FS_H +#define _UAPI_LINUX_FS_H + +/* + * This file has definitions for some important file table structures + * and constants and structures used by various generic file system + * ioctl's. Please do not make any changes in this file before + * sending patches for review to linux-fsdevel@vger.kernel.org and + * linux-api@vger.kernel.org. + */ + +#include +#include +#include +#ifndef __KERNEL__ +#include +#endif + +/* Use of MS_* flags within the kernel is restricted to core mount(2) code. */ +#if !defined(__KERNEL__) +#include +#endif + +/* + * It's silly to have NR_OPEN bigger than NR_FILE, but you can change + * the file limit at runtime and only root can increase the per-process + * nr_file rlimit, so it's safe to set up a ridiculously high absolute + * upper limit on files-per-process. + * + * Some programs (notably those using select()) may have to be + * recompiled to take full advantage of the new limits.. + */ + +/* Fixed constants first: */ +#undef NR_OPEN +#define INR_OPEN_CUR 1024 /* Initial setting for nfile rlimits */ +#define INR_OPEN_MAX 4096 /* Hard limit for nfile rlimits */ + +#define BLOCK_SIZE_BITS 10 +#define BLOCK_SIZE (1</maps ioctl */ +#define PROCMAP_QUERY _IOWR(PROCFS_IOCTL_MAGIC, 17, struct procmap_query) + +enum procmap_query_flags { + /* + * VMA permission flags. + * + * Can be used as part of procmap_query.query_flags field to look up + * only VMAs satisfying specified subset of permissions. E.g., specifying + * PROCMAP_QUERY_VMA_READABLE only will return both readable and read/write VMAs, + * while having PROCMAP_QUERY_VMA_READABLE | PROCMAP_QUERY_VMA_WRITABLE will only + * return read/write VMAs, though both executable/non-executable and + * private/shared will be ignored. + * + * PROCMAP_QUERY_VMA_* flags are also returned in procmap_query.vma_flags + * field to specify actual VMA permissions. + */ + PROCMAP_QUERY_VMA_READABLE = 0x01, + PROCMAP_QUERY_VMA_WRITABLE = 0x02, + PROCMAP_QUERY_VMA_EXECUTABLE = 0x04, + PROCMAP_QUERY_VMA_SHARED = 0x08, + /* + * Query modifier flags. + * + * By default VMA that covers provided address is returned, or -ENOENT + * is returned. With PROCMAP_QUERY_COVERING_OR_NEXT_VMA flag set, closest + * VMA with vma_start > addr will be returned if no covering VMA is + * found. + * + * PROCMAP_QUERY_FILE_BACKED_VMA instructs query to consider only VMAs that + * have file backing. Can be combined with PROCMAP_QUERY_COVERING_OR_NEXT_VMA + * to iterate all VMAs with file backing. + */ + PROCMAP_QUERY_COVERING_OR_NEXT_VMA = 0x10, + PROCMAP_QUERY_FILE_BACKED_VMA = 0x20, +}; + +/* + * Input/output argument structured passed into ioctl() call. It can be used + * to query a set of VMAs (Virtual Memory Areas) of a process. + * + * Each field can be one of three kinds, marked in a short comment to the + * right of the field: + * - "in", input argument, user has to provide this value, kernel doesn't modify it; + * - "out", output argument, kernel sets this field with VMA data; + * - "in/out", input and output argument; user provides initial value (used + * to specify maximum allowable buffer size), and kernel sets it to actual + * amount of data written (or zero, if there is no data). + * + * If matching VMA is found (according to criterias specified by + * query_addr/query_flags, all the out fields are filled out, and ioctl() + * returns 0. If there is no matching VMA, -ENOENT will be returned. + * In case of any other error, negative error code other than -ENOENT is + * returned. + * + * Most of the data is similar to the one returned as text in /proc//maps + * file, but procmap_query provides more querying flexibility. There are no + * consistency guarantees between subsequent ioctl() calls, but data returned + * for matched VMA is self-consistent. + */ +struct procmap_query { + /* Query struct size, for backwards/forward compatibility */ + __u64 size; + /* + * Query flags, a combination of enum procmap_query_flags values. + * Defines query filtering and behavior, see enum procmap_query_flags. + * + * Input argument, provided by user. Kernel doesn't modify it. + */ + __u64 query_flags; /* in */ + /* + * Query address. By default, VMA that covers this address will + * be looked up. PROCMAP_QUERY_* flags above modify this default + * behavior further. + * + * Input argument, provided by user. Kernel doesn't modify it. + */ + __u64 query_addr; /* in */ + /* VMA starting (inclusive) and ending (exclusive) address, if VMA is found. */ + __u64 vma_start; /* out */ + __u64 vma_end; /* out */ + /* VMA permissions flags. A combination of PROCMAP_QUERY_VMA_* flags. */ + __u64 vma_flags; /* out */ + /* + * VMA file offset. If VMA has file backing, this specifies offset + * within the file that VMA's start address corresponds to. + * Is set to zero if VMA has no backing file. + */ + __u64 vma_offset; /* out */ + /* Backing file's inode number, or zero, if VMA has no backing file. */ + __u64 inode; /* out */ + /* Backing file's device major/minor number, or zero, if VMA has no backing file. */ + __u32 dev_major; /* out */ + __u32 dev_minor; /* out */ + /* + * If set to non-zero value, signals the request to return VMA name + * (i.e., VMA's backing file's absolute path, with " (deleted)" suffix + * appended, if file was unlinked from FS) for matched VMA. VMA name + * can also be some special name (e.g., "[heap]", "[stack]") or could + * be even user-supplied with prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME). + * + * Kernel will set this field to zero, if VMA has no associated name. + * Otherwise kernel will return actual amount of bytes filled in + * user-supplied buffer (see vma_name_addr field below), including the + * terminating zero. + * + * If VMA name is longer that user-supplied maximum buffer size, + * -E2BIG error is returned. + * + * If this field is set to non-zero value, vma_name_addr should point + * to valid user space memory buffer of at least vma_name_size bytes. + * If set to zero, vma_name_addr should be set to zero as well + */ + __u32 vma_name_size; /* in/out */ + /* + * If set to non-zero value, signals the request to extract and return + * VMA's backing file's build ID, if the backing file is an ELF file + * and it contains embedded build ID. + * + * Kernel will set this field to zero, if VMA has no backing file, + * backing file is not an ELF file, or ELF file has no build ID + * embedded. + * + * Build ID is a binary value (not a string). Kernel will set + * build_id_size field to exact number of bytes used for build ID. + * If build ID is requested and present, but needs more bytes than + * user-supplied maximum buffer size (see build_id_addr field below), + * -E2BIG error will be returned. + * + * If this field is set to non-zero value, build_id_addr should point + * to valid user space memory buffer of at least build_id_size bytes. + * If set to zero, build_id_addr should be set to zero as well + */ + __u32 build_id_size; /* in/out */ + /* + * User-supplied address of a buffer of at least vma_name_size bytes + * for kernel to fill with matched VMA's name (see vma_name_size field + * description above for details). + * + * Should be set to zero if VMA name should not be returned. + */ + __u64 vma_name_addr; /* in */ + /* + * User-supplied address of a buffer of at least build_id_size bytes + * for kernel to fill with matched VMA's ELF build ID, if available + * (see build_id_size field description above for details). + * + * Should be set to zero if build ID should not be returned. + */ + __u64 build_id_addr; /* in */ +}; + +#endif /* _UAPI_LINUX_FS_H */ From patchwork Tue Jun 11 11:00:54 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13693433 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 A4305C27C5E for ; Tue, 11 Jun 2024 11:01:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 17D796B00B5; Tue, 11 Jun 2024 07:01:27 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 105D86B00B6; Tue, 11 Jun 2024 07:01:27 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E9ED56B00B7; Tue, 11 Jun 2024 07:01:26 -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 BD2156B00B5 for ; Tue, 11 Jun 2024 07:01:26 -0400 (EDT) Received: from smtpin12.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 66BB04140E for ; Tue, 11 Jun 2024 11:01:26 +0000 (UTC) X-FDA: 82218316572.12.58B438F Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf23.hostedemail.com (Postfix) with ESMTP id EAB5D14000B for ; Tue, 11 Jun 2024 11:01:23 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HAzACSc4; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf23.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=1718103684; 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=iWIeUY797J/Toq4h22cPQ/qqLpVl0jFiidUASc+TDck=; b=qWf31VDkvAxMyADnB7otRo+x3YLmoOxpfsjCBbKEJGcNdtqglFiKITyXI+PrAjjGutsyFq 18GcdRqKU4Dx565A410K0Rm+aE9QTa7Mm+RFLTZFI6EYYyE8zD2ieUEvtxAAxyb4KGv4JH UDcqoss3bSjViNlIGN+kjCV7A/fhvHo= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HAzACSc4; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf23.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=1718103684; a=rsa-sha256; cv=none; b=trJAy74RxKmPQKNwWQ4D4wyDSNvFTYj0FLapsdexGq2a1lihetnbU5xaM5hXzfrBhxZwBu iTpqyHILaEUKEkiyyOfJljcYl6MQR+yEVQ57SxL3Zov+etpUqw0w2XRK1bK2Jank6UTN9q aGQ6RfxD12x1c89suqJyJLnF60DLKKM= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id F15BDCE1B13; Tue, 11 Jun 2024 11:01:20 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6DA3EC2BD10; Tue, 11 Jun 2024 11:01:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1718103680; bh=3kUqgFqNjNH4Un7okDLhffoSH0ok4bZOeWq40FaW4a4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=HAzACSc4x79jXZLplHbLBtNC0Glv1gmrlCtS+BCpxvfhnpjxwpWgGDHsZ/+zrf1Hm xWz/Rc+CYrEAg4EfXIl8ckiApc3Vd6TdOV6ZfTo+YpIgWCOvVhqrStQagXrdKAwqY4 APSfUOUCB7Hk78TzClNwMIDwXTf4R5GqFUQreBCvWwtOBFQMqZx/IzTV61j7os+Zr3 GYGv/B9JXIT9BY31B/kCdbJ7hreETKeyEvdHNzvKsToccJEYZOI9KIoLBP4GC+5oGb 6og+PC2yhblHRr4Rbq1AEMe/1vCZJqRT/gKLlK2cUM8GNZE6d+fN3DWNa3seQphPSm 58i4YBQjD9byA== 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, liam.howlett@oracle.com, surenb@google.com, rppt@kernel.org, Andrii Nakryiko Subject: [PATCH v4 6/7] selftests/bpf: make use of PROCMAP_QUERY ioctl if available Date: Tue, 11 Jun 2024 04:00:54 -0700 Message-ID: <20240611110058.3444968-7-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240611110058.3444968-1-andrii@kernel.org> References: <20240611110058.3444968-1-andrii@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: EAB5D14000B X-Stat-Signature: b4djtjxskm8aqo9i8wmypnezw5h1fhj3 X-Rspam-User: X-HE-Tag: 1718103683-982455 X-HE-Meta: U2FsdGVkX1+KluTAEDt8TZ7HqyIeM4/ophKZeuSQWpAa7x3A+1sHa7Cs9xELhBHrzmvp2i0aCc11eingbUHi7xPupid+LqLBVW+V0ODpsI3/CQeqVbtYGwuqDsQFJG/u3GUWvKgeFXNlvuW7mTIGCGXWXe0LCuTNcfXdaxZlNolgovmJ8gn850fpsjWJvOQvPjMnUnD1Drzc4MkK48dGMgqDMudV2JnW1cnuU6zqodkDFBFnSMDj/1Vl0j47npDq7GhLrUzkYGkipx4vhnhNi5GEKkHUE2YhraGk6S02wZmQSteB8BqaEtEfyn8cMNZwIbESj377D+p6xXc9EQfV9GMozpJcRb+WNv9gD3/n4l+gFcUOU+0r4AtClhGU44r9TkK+YAfvEcgesi04sYtR4g7qyMsNoU6V6mfk6W4bohtI8l5yB87Y1Rgy4NfLwNi3YUJYxa4eQ/QeMj2m5/5TtWPHElU99PTHmH+S8TCDl5S+rFyphsyJIi7y52i+OVgDproQ3v+cCrdTUCI5jUbL+iYPgbNNcNuBYIhEmuqmwYCkWtPYDfCmiFAWmMz+lh3MQ1lQaX1ApMxHdTSRf/JwfqJqjNJPHXVkZCtXDVi7TNDOrMlLam91hciXrkYEZ67BuB/WCplnC1X+LEu2p2vaAmp8PVqf78q6WV4HtPhWd8vO3/uM88CLSaOGTsBOChSEYMQIMPgpdCvPzRtmtXz8rXBzWYJa9T+ftGoO9SKnILRZ7gYynXegI+zLkMiM4LMSxAqAbsZBUvXRXViO7IF7rbcGlMmYYXCHvk+GXQmEUL6da8OStMJceN3D5NbZ+7HcDMgjAL2pl8pYS4XDpwpQ3enaS9lbPWnaLMyYLb2VkTaOjvRR8o/3RUTGdtYoeE6duiyelK1jg/l1/jB7CkL3CddJKkzTP47U2xLxl0UbNLUBHp2j+3imlBYIm1h80vcH3R9/RXuu3VN1/LAIDbh hWhypsc5 L+ZYxWZcm+RrCE4KPY2x0YHaz2MDzgtFSXdms0xFCfU06wsymEPH4EfSb5vucPbRepmwazqS6y9QWPxtAthJaB2Z32EoqSXp2qGbSPY6bL3a9cZvhYpt7W8+4fd2z0V35eguvGnvwxGszmSdtiTKVQ6KW/53Yw6LVunEW27nDkGV/JeR2KImkH97pBzH3bMEEOmZ3ImIdbvwt9jcML+qKrfw3RGOcg3m4AHXrqNk30RNW6ozW0uS7Bo+/e8oMytIF7bj/mvqFKju7V1H5JRa+D39OnTy9ufoAL9CdQH0BXYPWO/rf1antTvYTnT/pj8iQAOR8EIqtQTBgsq2Hj39BwiVl69sDFj5NWkCHNDZZzd+R31U= 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 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 | 104 +++++++++++++++++--- 3 files changed, 94 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 465d196c7165..1bfd881c0e07 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 @@ -244,29 +246,91 @@ int kallsyms_find(const char *sym, unsigned long long *addr) return err; } +#ifdef PROCMAP_QUERY +int env_verbosity __weak = 0; + +int procmap_query(int fd, const void *addr, __u32 query_flags, size_t *start, size_t *offset, int *flags) +{ + char path_buf[PATH_MAX], build_id_buf[20]; + struct procmap_query q; + int err; + + memset(&q, 0, sizeof(q)); + q.size = sizeof(q); + q.query_flags = query_flags; + 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, 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 & PROCMAP_QUERY_VMA_READABLE) ? 'r' : '-', + (q.vma_flags & PROCMAP_QUERY_VMA_WRITABLE) ? 'w' : '-', + (q.vma_flags & PROCMAP_QUERY_VMA_EXECUTABLE) ? 'x' : '-', + (q.vma_flags & PROCMAP_QUERY_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; + /* requested executable VMA only */ + err = procmap_query(fileno(f), addr, PROCMAP_QUERY_VMA_EXECUTABLE, &start, &base, &flags); + if (err == -EOPNOTSUPP) { + 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; } + } else if (err) { + fclose(f); + return err; } - fclose(f); - if (!found) - return -ESRCH; - #if defined(__powerpc64__) && defined(_CALL_ELF) && _CALL_ELF == 2 #define OP_RT_RA_MASK 0xffff0000UL @@ -307,15 +371,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, 0, &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 Tue Jun 11 11:00:55 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Andrii Nakryiko X-Patchwork-Id: 13693434 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 7DCDAC27C5E for ; Tue, 11 Jun 2024 11:01:31 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 9E1B46B00B6; Tue, 11 Jun 2024 07:01:28 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 968976B00B7; Tue, 11 Jun 2024 07:01:28 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 796F16B00B8; Tue, 11 Jun 2024 07:01:28 -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 4A0F76B00B6 for ; Tue, 11 Jun 2024 07:01:28 -0400 (EDT) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id EB42FC14B2 for ; Tue, 11 Jun 2024 11:01:27 +0000 (UTC) X-FDA: 82218316614.02.26DF6E2 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf11.hostedemail.com (Postfix) with ESMTP id 34C9D4000B for ; Tue, 11 Jun 2024 11:01:25 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=B95v1R+V; spf=pass (imf11.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=1718103685; a=rsa-sha256; cv=none; b=ZUJ2MAgoF/E5H+fv/KoXd8yaWYEE8EsF+42Vd624aG6nCRlguBB+IUAVKAIGrkVYj2cNQ5 qZ8XMWbYXID15omUxY6/1Sy6RPqmWSbbmIiTKd0eFM13SVmU9S4d/flayK6jI+JzyAGpar yEr/7oUqWYlYlHkNCDOSjLHYt01zwXo= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=B95v1R+V; spf=pass (imf11.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=1718103685; 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=s6yu3ZgYSJkjXkNr+7yX08S0e2TkElF+R2LNo5dzq5c=; b=aCQX0P+nX/3equaL67on7azVpu2DDXqJLPDG03UJ2E9YfCzwDBVGP5PKF2kRitpUx4OKM3 jWKxBUKzQ70YUmtCyVFAgkEY9B0SpoimEGVSb3cF8Nr67PKbwp3NWIIFr5bJrFDwZlk5gb AttwPR3lb51i/TWFvvjCzqVaokZ0Cf0= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 5369560C23; Tue, 11 Jun 2024 11:01:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id BBAC2C2BD10; Tue, 11 Jun 2024 11:01:23 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1718103684; bh=NP8+W+bH6pHbXy3KBT/Ddc18s0vHb1N4SFb+qkc6u48=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=B95v1R+VGQ9gMzDafnPLIAUyWmk5wKnLsXgk+Xyrai19UYhbuHbfYiMCG2dxSHfyq xZ1BMCww9MPnY4eCIo3UqIDId/OUCDS5vdkb3juC8RA9XFTqJSZpfTS3uTO7smZiIY /V14DH1JczHHgBRkhjt5jTBIIm9gA9B8AthYSbJMWkomqbAAPM/jHA4ec6zuh7CclH ug6U6pLf5/Ps0YvkvpavXDPiyvajp/t0/L2EqN/k9Vx+j1kvr/rKTeZeHC5C19AdWD 60S7wg77YereHtQQNJ6oE5cXXAXKULug1q6zDr74OoXkweUM7ABou/8C8CBYNjhylw DaZeJ3jQFfxBA== 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, liam.howlett@oracle.com, surenb@google.com, rppt@kernel.org, Andrii Nakryiko Subject: [PATCH v4 7/7] selftests/bpf: add simple benchmark tool for /proc//maps APIs Date: Tue, 11 Jun 2024 04:00:55 -0700 Message-ID: <20240611110058.3444968-8-andrii@kernel.org> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20240611110058.3444968-1-andrii@kernel.org> References: <20240611110058.3444968-1-andrii@kernel.org> MIME-Version: 1.0 X-Stat-Signature: pbjtbak6oug1t3j9x8j4kmnegnzx1b5e X-Rspamd-Queue-Id: 34C9D4000B X-Rspamd-Server: rspam04 X-Rspam-User: X-HE-Tag: 1718103685-358111 X-HE-Meta: U2FsdGVkX18ymyCErkzbQxNLcMsJFx/2bhhw4sro3z3+85Ih8BtxDfbkhE7oBAT97mYrhYKB64HEKzFwLX3lkSC+tZr0ZjvNghvR1darBJ73H4YmCudvW3dPh0P1Ey9yOCj4FOl/ZkCJER77n5vlNVGBEkVFg8/HEYEE/rJ56QNdsfakJ7lkfoXD1alsSTt/uDfpFdPPqeg4S3Xeyp+6nN/kUe0PI96WfvoIXJp9bgl5+bWhX/itXgJLre8n/V3Yx+sTernxDK84jELck1zkd4thnRuQ5c6vtDLkEwStyp9oIlyhrquB3KYMtMbF/+TpvL/hC4hgtbnrKZDlxnwUhuPdFLSmjWiYIIXFVERYMxsW+nOuAsRbYfagIHFvX3A5+nnJc4kCvpujP2vd1buOT7x9mjaMKVdRwNKFgsmccEEMth86KNw1os4zoAwa++YsCM2i/V0Ug/tnVD3NQGtUzyWoUNomZywFkmLO6VB/DM+SKt39ChovFUp7KqHK8FDydxBISgGpK9qlrUqGFd5JxmctPImP7mdIz2jPRjU5TjR/DRlXprlGpAtQCMH3A2bUTYv2V/mFiy7Im0AIN0HLbMlAgxAjPAS89Xje608x3i0esE5k/xxEHIU5A/tDvfuuyQy8HgeAgasBtt+N7X0fA2yFXZrGCXvjoC4X/4P8asXpni/p26NVnA/artWjB/dx17YHfWXbFc6oI+A0mIGT3K17dWC7hmn1J+VsOhjnGVKrooIVbg372B1QcoWOlE5eW4Rqo1hNbquEI7xid1caughORl6O6Shzf+wgC5QQRdNIpiX1T9r2rI9D+wdJN76Bhmd1zgyZvHroMgBqLo4e1x+Ao6xWwfnNv2rqw809nvI2BbK8cqbtgoE6g42bvp1qRMF4LIb6PHnPcAH8vqFZ6fdSI88+HeE7cxiPdaI3HL+VLjvgCn313SaNhx1+fMvY5exZOpQBuo6b5R//fSb 40katn+9 XYuHYet+3hYNilSqWhuIl0I2+vlD1awpslhw9mL3NdvXAfD3HcFni/UA+/FE32E6j6yAYKHYDdpY6Sathr0vjmvoIZgzzK101VydqVXNFPeCDZhd/Ag1RebPTC0zjr7/Nc8DIlo+iHatlwRH2tpDtNjgiAfBPHQkrCT7UKp1za80V1ETa1PiC9C8jQo01jLI3xx3qwavVwgc3Lx4EC+TGzirnwmZXfFCpXY06wEtzkZAbTE/EeeQJalZk5A== 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 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 the tool has "benchark" mode. User provides a number of processing runs to run in a tight loop, only timing specifically /proc//maps parsing and processing parts of the logic. 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 3244 user space addresses (464 unique ones, but we didn't deduplicate them). Application itself had 655 VMAs reported in /proc//maps. Averaging time taken to process all addresses 10000 times, showed that: - text-based approach took 333 microseconds *per one batch run*; - ioctl-based approach took 8 microseconds *per (identical) batch run*. This gives about ~40x speed up to do exactly the same amount of work (build IDs were not fetched for ioctl-based benchmark; fetching build IDs resulted in 2x slowdown compared to no-build-ID case). The ratio will vary depending on exact set of addresses and how many VMAs they are mapped to. So 40x isn't something to take for granted, but it does show possible improvements that are achievable. I also did an strace run of both cases. In text-based one the tool did 27 read() syscalls, fetching up to 4KB of data in one go (which is seq_file limitations, bumping the buffer size has no effect, as data is always capped at 4KB). In comparison, ioctl-based implementation had to do only 5 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. E.g., one of the larger production applications in the server fleet has upwards of 20000 VMAs, which would make benchmark even more unfair to processing /proc//maps file. This tool is implementing one of the patterns of usage, referred to as "on-demand profiling" use case in the main patch implementing ioctl() API. perf is an example of the pre-processing pattern in which all (or all executable) VMAs are loaded and stored for further querying. We implemented an experimental change to perf to benchmark text-based and ioctl-based APIs, and in perf benchmarks ioctl-based interface was no worse than optimized text-based parsing benchmark. Filtering to only executable VMAs further made ioctl-based benchmarks faster, as perf would be querying about 1/3 of all VMAs only, compared to the need to read and parse all of VMAs. E.g., running `perf bench internals synthesize --mt -M 8`, we are getting. TEXT-BASED ========== # ./perf-parse bench internals synthesize --mt -M 8 # Running 'internals/synthesize' benchmark: Computing performance of multi threaded perf event synthesis by synthesizing events on CPU 0: Number of synthesis threads: 1 Average synthesis took: 10238.600 usec (+- 309.656 usec) Average num. events: 3744.000 (+- 0.000) Average time per event 2.735 usec ... Number of synthesis threads: 8 Average synthesis took: 6814.600 usec (+- 149.418 usec) Average num. events: 3744.000 (+- 0.000) Average time per event 1.820 usec IOCTL-BASED, FETCHING ALL VMAS ============================== # ./perf-ioctl-all bench internals synthesize --mt -M 8 # Running 'internals/synthesize' benchmark: Computing performance of multi threaded perf event synthesis by synthesizing events on CPU 0: Number of synthesis threads: 1 Average synthesis took: 9944.800 usec (+- 381.794 usec) Average num. events: 3593.000 (+- 0.000) Average time per event 2.768 usec ... Number of synthesis threads: 8 Average synthesis took: 6598.600 usec (+- 137.503 usec) Average num. events: 3595.000 (+- 0.000) Average time per event 1.835 usec IOCTL-BASED, FETCHING EXECUTABLE VMAS ===================================== # ./perf-ioctl-exec bench internals synthesize --mt -M 8 # Running 'internals/synthesize' benchmark: Computing performance of multi threaded perf event synthesis by synthesizing events on CPU 0: Number of synthesis threads: 1 Average synthesis took: 8539.600 usec (+- 364.875 usec) Average num. events: 3569.000 (+- 0.000) Average time per event 2.393 usec ... Number of synthesis threads: 8 Average synthesis took: 5657.600 usec (+- 107.219 usec) Average num. events: 3571.000 (+- 0.000) Average time per event 1.584 usec Signed-off-by: Andrii Nakryiko --- tools/testing/selftests/bpf/.gitignore | 1 + tools/testing/selftests/bpf/Makefile | 2 +- tools/testing/selftests/bpf/procfs_query.c | 386 +++++++++++++++++++++ 3 files changed, 388 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 5025401323af..903b14931bfe 100644 --- a/tools/testing/selftests/bpf/.gitignore +++ b/tools/testing/selftests/bpf/.gitignore @@ -44,6 +44,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 e0b3887b3d2d..0afa667a54e5 100644 --- a/tools/testing/selftests/bpf/Makefile +++ b/tools/testing/selftests/bpf/Makefile @@ -144,7 +144,7 @@ TEST_GEN_PROGS_EXTENDED = 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..63e06568f1ff --- /dev/null +++ b/tools/testing/selftests/bpf/procfs_query.c @@ -0,0 +1,386 @@ +// 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 'Q': + 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 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 = PROCMAP_QUERY_COVERING_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, PROCMAP_QUERY, &q); + if (err < 0 && errno == ENOTTY) { + close(fd); + fprintf(stderr, "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 addr %lx\n", (long)q.query_addr); + i++; + a++; + continue; /* unresolved address */ + } + if (err < 0) { + err = -errno; + close(fd); + fprintf(stderr, "PROCMAP_QUERY ioctl() returned error: %d\n", err); + return err; + } + + if (verbose) { + printf("VMA FOUND (addr %08lx): %08lx-%08lx %c%c%c%c %08lx %02x:%02x %ld %s (build ID: %s, %d bytes)\n", + (long)q.query_addr, (long)q.vma_start, (long)q.vma_end, + (q.vma_flags & PROCMAP_QUERY_VMA_READABLE) ? 'r' : '-', + (q.vma_flags & PROCMAP_QUERY_VMA_WRITABLE) ? 'w' : '-', + (q.vma_flags & PROCMAP_QUERY_VMA_EXECUTABLE) ? 'x' : '-', + (q.vma_flags & PROCMAP_QUERY_VMA_SHARED) ? 's' : 'p', + (long)q.vma_offset, q.dev_major, q.dev_minor, (long)q.inode, + q.vma_name_size ? vma_name : "", + q.build_id_size ? "YES" : "NO", + q.build_id_size); + } + + /* 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], fbuf[4096]; + 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; + } + + err = setvbuf(f, fbuf, _IOFBF, sizeof(fbuf)); + if (err) { + err = -errno; + fprintf(stderr, "Failed to set custom file buffer size: %d\n", 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; +}