From nobody Thu Nov 14 05:36:23 2024 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id DA83FC04FE2 for ; Tue, 8 Aug 2023 16:18:44 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S232318AbjHHQSV (ORCPT ); Tue, 8 Aug 2023 12:18:21 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:51544 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232384AbjHHQQP (ORCPT ); Tue, 8 Aug 2023 12:16:15 -0400 Received: from mailgw01.mediatek.com (unknown [60.244.123.138]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 682D730DF; Tue, 8 Aug 2023 08:48:13 -0700 (PDT) X-UUID: d511d7ce35c511ee9cb5633481061a41-20230808 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=mediatek.com; s=dk; h=Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:CC:To:From; bh=sTBXTXgg1FJwPGo4j7K5vvqI1OKJzEYPfvBF8BSajHY=; b=Ss9WLDIA+9Z/G6ps45Ui37MZVX7CCWy4l7FgVrVmBNoH4PrDjC5NDwt5R5TY5yz3LzfhVM6TSnGgLuHRQuV3jLPKvaNsCr9xOrx+4oj6Zq4/fuAwEPRfc+aI7QJPVN0UwoRP+YbjHT2eY8888kozS2EsquM8d/zdB7gUjE6CgZ8=; X-CID-P-RULE: Release_Ham X-CID-O-INFO: VERSION:1.1.31,REQID:11beb84a-1321-43d3-82e3-40f56c4b19c5,IP:0,U RL:0,TC:0,Content:-5,EDM:0,RT:0,SF:0,FILE:0,BULK:0,RULE:Release_Ham,ACTION :release,TS:-5 X-CID-META: VersionHash:0ad78a4,CLOUDID:4eb5f042-d291-4e62-b539-43d7d78362ba,B ulkID:nil,BulkQuantity:0,Recheck:0,SF:102,TC:nil,Content:0,EDM:-3,IP:nil,U RL:11|1,File:nil,Bulk:nil,QS:nil,BEC:nil,COL:0,OSI:0,OSA:0,AV:0,LES:1,SPR: NO,DKR:0,DKP:0,BRR:0,BRE:0 X-CID-BVR: 0,NGT X-CID-BAS: 0,NGT,0,_ X-CID-FACTOR: TF_CID_SPAM_SNR,TF_CID_SPAM_ULN X-UUID: d511d7ce35c511ee9cb5633481061a41-20230808 Received: from mtkmbs11n2.mediatek.inc [(172.21.101.187)] by mailgw01.mediatek.com (envelope-from ) (Generic MTA with TLSv1.2 ECDHE-RSA-AES256-GCM-SHA384 256/256) with ESMTP id 766388302; Tue, 08 Aug 2023 16:30:29 +0800 Received: from mtkmbs13n2.mediatek.inc (172.21.101.108) by mtkmbs10n1.mediatek.inc (172.21.101.34) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.1118.26; Tue, 8 Aug 2023 16:30:28 +0800 Received: from mtksdccf07.mediatek.inc (172.21.84.99) by mtkmbs13n2.mediatek.inc (172.21.101.73) with Microsoft SMTP Server id 15.2.1118.26 via Frontend Transport; Tue, 8 Aug 2023 16:30:28 +0800 From: Kuan-Ying Lee To: Jan Kiszka , Kieran Bingham , Matthias Brugger , AngeloGioacchino Del Regno CC: , , , , , , , Kuan-Ying Lee , , Subject: [PATCH v2 1/8] scripts/gdb/symbols: add specific ko module load command Date: Tue, 8 Aug 2023 16:30:11 +0800 Message-ID: <20230808083020.22254-2-Kuan-Ying.Lee@mediatek.com> X-Mailer: git-send-email 2.18.0 In-Reply-To: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> References: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> MIME-Version: 1.0 X-MTK: N Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add lx-symbols command to support add specific ko module. Example output like below: (gdb) lx-symbols mm/kasan/kasan_test.ko loading @0xffff800002d30000: mm/kasan/kasan_test.ko Signed-off-by: Kuan-Ying Lee Reported-by: Johannes Berg --- scripts/gdb/linux/symbols.py | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/scripts/gdb/linux/symbols.py b/scripts/gdb/linux/symbols.py index c8047f4441e6..5179edd1b627 100644 --- a/scripts/gdb/linux/symbols.py +++ b/scripts/gdb/linux/symbols.py @@ -111,11 +111,12 @@ lx-symbols command.""" return "{textaddr} {sections}".format( textaddr=3Dtextaddr, sections=3D"".join(args)) =20 - def load_module_symbols(self, module): + def load_module_symbols(self, module, module_file=3DNone): module_name =3D module['name'].string() module_addr =3D str(module['mem'][constants.LX_MOD_TEXT]['base']).= split()[0] =20 - module_file =3D self._get_module_file(module_name) + if not module_file: + module_file =3D self._get_module_file(module_name) if not module_file and not self.module_files_updated: self._update_module_files() module_file =3D self._get_module_file(module_name) @@ -138,6 +139,19 @@ lx-symbols command.""" else: gdb.write("no module object found for '{0}'\n".format(module_n= ame)) =20 + def load_ko_symbols(self, mod_path): + self.loaded_modules =3D [] + module_list =3D modules.module_list() + + for module in module_list: + module_name =3D module['name'].string() + module_pattern =3D ".*/{0}\.ko(?:.debug)?$".format( + module_name.replace("_", r"[_\-]")) + if re.match(module_pattern, mod_path) and os.path.exists(mod_p= ath): + self.load_module_symbols(module, mod_path) + return + raise gdb.GdbError("%s is not a valid .ko\n" % mod_path) + def load_all_symbols(self): gdb.write("loading vmlinux\n") =20 @@ -176,6 +190,11 @@ lx-symbols command.""" self.module_files =3D [] self.module_files_updated =3D False =20 + argv =3D gdb.string_to_argv(arg) + if len(argv) =3D=3D 1: + self.load_ko_symbols(argv[0]) + return + self.load_all_symbols() =20 if hasattr(gdb, 'Breakpoint'): --=20 2.18.0 From nobody Thu Nov 14 05:36:23 2024 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 8F922C001B0 for ; Tue, 8 Aug 2023 16:16:01 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S232231AbjHHQPb (ORCPT ); Tue, 8 Aug 2023 12:15:31 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:51580 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232217AbjHHQNn (ORCPT ); Tue, 8 Aug 2023 12:13:43 -0400 Received: from mailgw02.mediatek.com (unknown [210.61.82.184]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 958AD7EEC; Tue, 8 Aug 2023 08:47:51 -0700 (PDT) X-UUID: d651f6a035c511eeb20a276fd37b9834-20230808 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=mediatek.com; s=dk; h=Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:CC:To:From; bh=YAbalPSkEKWf6qATM+/2up2V7102RaSYQU2gp24pvGE=; b=Y9Tr3jyMnBdD4FjjZj5r7r92qYZxj9h9z2NDRhjdRY4g58Qn3e+i+E2E/p3MiZPmaTYB0BxVy9aFsORUw8kBzfWFpSJrIOYyYZYMjaUz44DTFQhCKiZBzQ/VutYvb7VXKr/WE4h5r+DsQg6oYKnB0uTUsR2YDOC3dGw0xuN5U+A=; X-CID-P-RULE: Release_Ham X-CID-O-INFO: VERSION:1.1.31,REQID:dc741943-75d7-4461-9c85-3e8892d586a3,IP:0,U RL:0,TC:0,Content:0,EDM:0,RT:1,SF:0,FILE:0,BULK:0,RULE:Release_Ham,ACTION: release,TS:1 X-CID-META: VersionHash:0ad78a4,CLOUDID:c03a04a1-0933-4333-8d4f-6c3c53ebd55b,B ulkID:nil,BulkQuantity:0,Recheck:0,SF:102,TC:nil,Content:0,EDM:-3,IP:nil,U RL:11|1,File:nil,Bulk:nil,QS:nil,BEC:nil,COL:0,OSI:0,OSA:0,AV:0,LES:1,SPR: NO,DKR:0,DKP:0,BRR:0,BRE:0 X-CID-BVR: 0 X-CID-BAS: 0,_,0,_ X-CID-FACTOR: TF_CID_SPAM_SNR,TF_CID_SPAM_ULN X-UUID: d651f6a035c511eeb20a276fd37b9834-20230808 Received: from mtkmbs11n2.mediatek.inc [(172.21.101.187)] by mailgw02.mediatek.com (envelope-from ) (Generic MTA with TLSv1.2 ECDHE-RSA-AES256-GCM-SHA384 256/256) with ESMTP id 128710964; Tue, 08 Aug 2023 16:30:31 +0800 Received: from mtkmbs13n2.mediatek.inc (172.21.101.108) by mtkmbs10n1.mediatek.inc (172.21.101.34) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.1118.26; Tue, 8 Aug 2023 16:30:30 +0800 Received: from mtksdccf07.mediatek.inc (172.21.84.99) by mtkmbs13n2.mediatek.inc (172.21.101.73) with Microsoft SMTP Server id 15.2.1118.26 via Frontend Transport; Tue, 8 Aug 2023 16:30:30 +0800 From: Kuan-Ying Lee To: Jan Kiszka , Kieran Bingham , Matthias Brugger , AngeloGioacchino Del Regno CC: , , , , , , , Kuan-Ying Lee , , Subject: [PATCH v2 2/8] scripts/gdb/modules: add get module text support Date: Tue, 8 Aug 2023 16:30:12 +0800 Message-ID: <20230808083020.22254-3-Kuan-Ying.Lee@mediatek.com> X-Mailer: git-send-email 2.18.0 In-Reply-To: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> References: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> MIME-Version: 1.0 X-MTK: N Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" When we get an text address from coredump and we cannot find this address in vmlinux, it might located in kernel module. We want to know which kernel module it located in. This GDB scripts can help us to find the target kernel module. (gdb) lx-getmod-by-textaddr 0xffff800002d305ac 0xffff800002d305ac is in kasan_test.ko Signed-off-by: Kuan-Ying Lee --- scripts/gdb/linux/modules.py | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/scripts/gdb/linux/modules.py b/scripts/gdb/linux/modules.py index f76a43bfa15f..298dfcc25eae 100644 --- a/scripts/gdb/linux/modules.py +++ b/scripts/gdb/linux/modules.py @@ -97,5 +97,35 @@ class LxLsmod(gdb.Command): =20 gdb.write("\n") =20 - LxLsmod() + +def help(): + t =3D """Usage: lx-getmod-by-textaddr [Heximal Address] + Example: lx-getmod-by-textaddr 0xffff800002d305ac\n""" + gdb.write("Unrecognized command\n") + raise gdb.GdbError(t) + +class LxFindTextAddrinMod(gdb.Command): + '''Look up loaded kernel module by text address.''' + + def __init__(self): + super(LxFindTextAddrinMod, self).__init__('lx-getmod-by-textaddr',= gdb.COMMAND_SUPPORT) + + def invoke(self, arg, from_tty): + args =3D gdb.string_to_argv(arg) + + if len(args) !=3D 1: + help() + + addr =3D gdb.Value(int(args[0], 16)).cast(utils.get_ulong_type()) + for mod in module_list(): + mod_text_start =3D mod['mem'][constants.LX_MOD_TEXT]['base'] + mod_text_end =3D mod_text_start + mod['mem'][constants.LX_MOD_= TEXT]['size'].cast(utils.get_ulong_type()) + + if addr >=3D mod_text_start and addr < mod_text_end: + s =3D "0x%x" % addr + " is in " + mod['name'].string() + "= .ko\n" + gdb.write(s) + return + gdb.write("0x%x is not in any module text section\n" % addr) + +LxFindTextAddrinMod() --=20 2.18.0 From nobody Thu Nov 14 05:36:23 2024 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id BEFA6C04FDF for ; Tue, 8 Aug 2023 16:20:20 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S232136AbjHHQTt (ORCPT ); Tue, 8 Aug 2023 12:19:49 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:52866 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232400AbjHHQSD (ORCPT ); Tue, 8 Aug 2023 12:18:03 -0400 Received: from mailgw01.mediatek.com (unknown [60.244.123.138]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 8A3726A77; Tue, 8 Aug 2023 08:48:36 -0700 (PDT) X-UUID: d824fe3c35c511ee9cb5633481061a41-20230808 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=mediatek.com; s=dk; h=Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:CC:To:From; bh=of+Yq84+TCPrRdlX79cImaBtdd9LrIudC8T+juj2xpM=; b=HbqK8pPdZoJOnHhDY/nJ7xMYe/pfAjXTB82e027MUDyFkgfO+wWgJ+EvzpC9v1zDaVSkRP55FrN9UaalAMgz2gbBeNlDxdA/XavIlRb9we9yGSGGcQVuqUjaeZ4jAhupeccHExHXW4LJlIPL7qumh7+SmP+Qkc6YMXKEyu9rMhI=; X-CID-P-RULE: Release_Ham X-CID-O-INFO: VERSION:1.1.31,REQID:df494657-af38-46eb-b513-6039c93ef14b,IP:0,U RL:0,TC:0,Content:0,EDM:0,RT:0,SF:95,FILE:0,BULK:0,RULE:Release_Ham,ACTION :release,TS:95 X-CID-INFO: VERSION:1.1.31,REQID:df494657-af38-46eb-b513-6039c93ef14b,IP:0,URL :0,TC:0,Content:0,EDM:0,RT:0,SF:95,FILE:0,BULK:0,RULE:Spam_GS981B3D,ACTION :quarantine,TS:95 X-CID-META: VersionHash:0ad78a4,CLOUDID:d93a04a1-0933-4333-8d4f-6c3c53ebd55b,B ulkID:230808163036TTTRMJO3,BulkQuantity:1,Recheck:0,SF:48|38|29|28|17|19,T C:nil,Content:0,EDM:-3,IP:nil,URL:11|1,File:nil,Bulk:40,QS:nil,BEC:nil,COL :0,OSI:0,OSA:0,AV:0,LES:1,SPR:NO,DKR:0,DKP:0,BRR:0,BRE:0 X-CID-BVR: 0,NGT X-CID-BAS: 0,NGT,0,_ X-CID-FACTOR: TF_CID_SPAM_FSD,TF_CID_SPAM_ULN,TF_CID_SPAM_SNR,TF_CID_SPAM_SDM, TF_CID_SPAM_ASC,TF_CID_SPAM_FAS X-UUID: d824fe3c35c511ee9cb5633481061a41-20230808 Received: from mtkmbs14n1.mediatek.inc [(172.21.101.75)] by mailgw01.mediatek.com (envelope-from ) (Generic MTA with TLSv1.2 ECDHE-RSA-AES256-GCM-SHA384 256/256) with ESMTP id 53193084; Tue, 08 Aug 2023 16:30:34 +0800 Received: from mtkmbs13n2.mediatek.inc (172.21.101.108) by mtkmbs10n1.mediatek.inc (172.21.101.34) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.1118.26; Tue, 8 Aug 2023 16:30:33 +0800 Received: from mtksdccf07.mediatek.inc (172.21.84.99) by mtkmbs13n2.mediatek.inc (172.21.101.73) with Microsoft SMTP Server id 15.2.1118.26 via Frontend Transport; Tue, 8 Aug 2023 16:30:33 +0800 From: Kuan-Ying Lee To: Jan Kiszka , Kieran Bingham , Matthias Brugger , AngeloGioacchino Del Regno CC: , , , , , , , Kuan-Ying Lee , , Subject: [PATCH v2 3/8] scripts/gdb/utils: add common type usage Date: Tue, 8 Aug 2023 16:30:13 +0800 Message-ID: <20230808083020.22254-4-Kuan-Ying.Lee@mediatek.com> X-Mailer: git-send-email 2.18.0 In-Reply-To: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> References: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> MIME-Version: 1.0 X-MTK: N Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Since we often use 'unsigned long', 'size_t', 'usigned int' and 'struct page', we add these common types to utils. Signed-off-by: Kuan-Ying Lee --- scripts/gdb/linux/utils.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/scripts/gdb/linux/utils.py b/scripts/gdb/linux/utils.py index 9f44df13761e..7d5278d815fa 100644 --- a/scripts/gdb/linux/utils.py +++ b/scripts/gdb/linux/utils.py @@ -35,12 +35,32 @@ class CachedType: =20 =20 long_type =3D CachedType("long") +ulong_type =3D CachedType("unsigned long") +uint_type =3D CachedType("unsigned int") atomic_long_type =3D CachedType("atomic_long_t") +size_t_type =3D CachedType("size_t") +struct_page_type =3D CachedType("struct page") + +def get_uint_type(): + global uint_type + return uint_type.get_type() + +def get_page_type(): + global struct_page_type + return struct_page_type.get_type() =20 def get_long_type(): global long_type return long_type.get_type() =20 +def get_ulong_type(): + global ulong_type + return ulong_type.get_type() + +def get_size_t_type(): + global size_t_type + return size_t_type.get_type() + def offset_of(typeobj, field): element =3D gdb.Value(0).cast(typeobj) return int(str(element[field].address).split()[0], 16) --=20 2.18.0 From nobody Thu Nov 14 05:36:23 2024 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 2A211C04FE2 for ; Tue, 8 Aug 2023 16:16:34 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S232411AbjHHQQG (ORCPT ); Tue, 8 Aug 2023 12:16:06 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:51684 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232253AbjHHQOW (ORCPT ); Tue, 8 Aug 2023 12:14:22 -0400 Received: from mailgw02.mediatek.com (unknown [210.61.82.184]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 4C0D183D0; Tue, 8 Aug 2023 08:48:02 -0700 (PDT) X-UUID: d995d2a035c511eeb20a276fd37b9834-20230808 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=mediatek.com; s=dk; h=Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:CC:To:From; bh=KkKl47yr9p1LdaLrQw4ux4p7T6jvHHScktOtGmDcFH0=; b=Be3erY+BCgnclOYey5Lmx4RH4YB+tTD1dGRVXk3st2OruxqOClkmWCvvK6xcc+OuIhaR7cc5DKKjliDsLIot/azLE9VMfO6Od2CZP3zpIVaAytref8WQ/IH//JW2oB/f6F+4mtw16eHKyXDbCM3eStuErKdYBaestdpRr76Lk6w=; X-CID-P-RULE: Release_Ham X-CID-O-INFO: VERSION:1.1.31,REQID:22775343-9ffc-4a68-a5b0-369fc9784842,IP:0,U RL:0,TC:0,Content:0,EDM:0,RT:0,SF:0,FILE:0,BULK:0,RULE:Release_Ham,ACTION: release,TS:0 X-CID-META: VersionHash:0ad78a4,CLOUDID:203b04a1-0933-4333-8d4f-6c3c53ebd55b,B ulkID:nil,BulkQuantity:0,Recheck:0,SF:102,TC:nil,Content:0,EDM:-3,IP:nil,U RL:11|1,File:nil,Bulk:nil,QS:nil,BEC:nil,COL:0,OSI:0,OSA:0,AV:0,LES:1,SPR: NO,DKR:0,DKP:0,BRR:0,BRE:0 X-CID-BVR: 0,NGT X-CID-BAS: 0,NGT,0,_ X-CID-FACTOR: TF_CID_SPAM_ULN,TF_CID_SPAM_SNR X-UUID: d995d2a035c511eeb20a276fd37b9834-20230808 Received: from mtkmbs11n1.mediatek.inc [(172.21.101.185)] by mailgw02.mediatek.com (envelope-from ) (Generic MTA with TLSv1.2 ECDHE-RSA-AES256-GCM-SHA384 256/256) with ESMTP id 978280723; Tue, 08 Aug 2023 16:30:37 +0800 Received: from mtkmbs13n2.mediatek.inc (172.21.101.108) by mtkmbs10n1.mediatek.inc (172.21.101.34) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.1118.26; Tue, 8 Aug 2023 16:30:36 +0800 Received: from mtksdccf07.mediatek.inc (172.21.84.99) by mtkmbs13n2.mediatek.inc (172.21.101.73) with Microsoft SMTP Server id 15.2.1118.26 via Frontend Transport; Tue, 8 Aug 2023 16:30:36 +0800 From: Kuan-Ying Lee To: Jan Kiszka , Kieran Bingham , Matthias Brugger , AngeloGioacchino Del Regno CC: , , , , , , , Kuan-Ying Lee , , Subject: [PATCH v2 4/8] scripts/gdb/aarch64: add aarch64 page operation helper commands and configs Date: Tue, 8 Aug 2023 16:30:14 +0800 Message-ID: <20230808083020.22254-5-Kuan-Ying.Lee@mediatek.com> X-Mailer: git-send-email 2.18.0 In-Reply-To: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> References: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> MIME-Version: 1.0 X-MTK: N Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 1. Move page table debugging from mm.py to pgtable.py. 2. Add aarch64 kernel config and memory constants value. 3. Add below aarch64 page operation helper commands. page_to_pfn, page_to_phys, pfn_to_page, page_address, virt_to_phys, sym_to_pfn, pfn_to_kaddr, virt_to_page. 4. Only support CONFIG_SPARSEMEM_VMEMMAP=3Dy now. Signed-off-by: Kuan-Ying Lee --- scripts/gdb/linux/constants.py.in | 23 ++ scripts/gdb/linux/mm.py | 582 +++++++++++++++++++----------- scripts/gdb/linux/pgtable.py | 222 ++++++++++++ scripts/gdb/vmlinux-gdb.py | 3 +- 4 files changed, 626 insertions(+), 204 deletions(-) create mode 100644 scripts/gdb/linux/pgtable.py diff --git a/scripts/gdb/linux/constants.py.in b/scripts/gdb/linux/constant= s.py.in index fab74ca9df6f..0805aeab3dcd 100644 --- a/scripts/gdb/linux/constants.py.in +++ b/scripts/gdb/linux/constants.py.in @@ -105,3 +105,26 @@ LX_CONFIG(CONFIG_X86_MCE_AMD) LX_CONFIG(CONFIG_X86_MCE) LX_CONFIG(CONFIG_X86_IO_APIC) LX_CONFIG(CONFIG_HAVE_KVM) +LX_CONFIG(CONFIG_NUMA) +LX_CONFIG(CONFIG_ARM64) +LX_CONFIG(CONFIG_ARM64_4K_PAGES) +LX_CONFIG(CONFIG_ARM64_16K_PAGES) +LX_CONFIG(CONFIG_ARM64_64K_PAGES) +if IS_BUILTIN(CONFIG_ARM64): + LX_VALUE(CONFIG_ARM64_PA_BITS) + LX_VALUE(CONFIG_ARM64_VA_BITS) + LX_VALUE(CONFIG_ARM64_PAGE_SHIFT) + LX_VALUE(CONFIG_ARCH_FORCE_MAX_ORDER) +LX_CONFIG(CONFIG_SPARSEMEM) +LX_CONFIG(CONFIG_SPARSEMEM_EXTREME) +LX_CONFIG(CONFIG_SPARSEMEM_VMEMMAP) +LX_CONFIG(CONFIG_KASAN) +LX_CONFIG(CONFIG_KASAN_GENERIC) +LX_CONFIG(CONFIG_KASAN_SW_TAGS) +LX_CONFIG(CONFIG_KASAN_HW_TAGS) +if IS_BUILTIN(CONFIG_KASAN_GENERIC) or IS_BUILTIN(CONFIG_KASAN_SW_TAGS): + LX_VALUE(CONFIG_KASAN_SHADOW_OFFSET) +LX_CONFIG(CONFIG_VMAP_STACK) +if IS_BUILTIN(CONFIG_NUMA): + LX_VALUE(CONFIG_NODES_SHIFT) +LX_CONFIG(CONFIG_DEBUG_VIRTUAL) diff --git a/scripts/gdb/linux/mm.py b/scripts/gdb/linux/mm.py index 30d837f3dfae..ad5641dcb068 100644 --- a/scripts/gdb/linux/mm.py +++ b/scripts/gdb/linux/mm.py @@ -1,222 +1,398 @@ -# SPDX-License-Identifier: GPL-2.0-only +# SPDX-License-Identifier: GPL-2.0 # -# gdb helper commands and functions for Linux kernel debugging -# -# routines to introspect page table +# Copyright (c) 2023 MediaTek Inc. # # Authors: -# Dmitrii Bundin +# Kuan-Ying Lee # =20 import gdb +import math +from linux import utils, constants + +def DIV_ROUND_UP(n,d): + return ((n) + (d) - 1) // (d) =20 -from linux import utils +def test_bit(nr, addr): + if addr.dereference() & (0x1 << nr): + return True + else: + return False =20 -PHYSICAL_ADDRESS_MASK =3D gdb.parse_and_eval('0xfffffffffffff') +class page_ops(): + ops =3D None + def __init__(self): + if not constants.LX_CONFIG_SPARSEMEM_VMEMMAP: + raise gdb.GdbError('Only support CONFIG_SPARSEMEM_VMEMMAP now') + if constants.LX_CONFIG_ARM64 and utils.is_target_arch('aarch64'): + self.ops =3D aarch64_page_ops() + else: + raise gdb.GdbError('Only support aarch64 now') =20 +class aarch64_page_ops(): + def __init__(self): + self.SUBSECTION_SHIFT =3D 21 + self.SEBSECTION_SIZE =3D 1 << self.SUBSECTION_SHIFT + self.MODULES_VSIZE =3D 128 * 1024 * 1024 =20 -def page_mask(level=3D1): - # 4KB - if level =3D=3D 1: - return gdb.parse_and_eval('(u64) ~0xfff') - # 2MB - elif level =3D=3D 2: - return gdb.parse_and_eval('(u64) ~0x1fffff') - # 1GB - elif level =3D=3D 3: - return gdb.parse_and_eval('(u64) ~0x3fffffff') - else: - raise Exception(f'Unknown page level: {level}') - - -#page_offset_base in case CONFIG_DYNAMIC_MEMORY_LAYOUT is disabled -POB_NO_DYNAMIC_MEM_LAYOUT =3D '0xffff888000000000' -def _page_offset_base(): - pob_symbol =3D gdb.lookup_global_symbol('page_offset_base') - pob =3D pob_symbol.name if pob_symbol else POB_NO_DYNAMIC_MEM_LAYOUT - return gdb.parse_and_eval(pob) - - -def is_bit_defined_tupled(data, offset): - return offset, bool(data >> offset & 1) - -def content_tupled(data, bit_start, bit_end): - return (bit_start, bit_end), data >> bit_start & ((1 << (1 + bit_end -= bit_start)) - 1) - -def entry_va(level, phys_addr, translating_va): - def start_bit(level): - if level =3D=3D 5: - return 48 - elif level =3D=3D 4: - return 39 - elif level =3D=3D 3: - return 30 - elif level =3D=3D 2: - return 21 - elif level =3D=3D 1: - return 12 + if constants.LX_CONFIG_ARM64_64K_PAGES: + self.SECTION_SIZE_BITS =3D 29 + else: + self.SECTION_SIZE_BITS =3D 27 + self.MAX_PHYSMEM_BITS =3D constants.LX_CONFIG_ARM64_VA_BITS + + self.PAGE_SHIFT =3D constants.LX_CONFIG_ARM64_PAGE_SHIFT + self.PAGE_SIZE =3D 1 << self.PAGE_SHIFT + self.PAGE_MASK =3D (~(self.PAGE_SIZE - 1)) & ((1 << 64) - 1) + + self.VA_BITS =3D constants.LX_CONFIG_ARM64_VA_BITS + if self.VA_BITS > 48: + self.VA_BITS_MIN =3D 48 + self.vabits_actual =3D gdb.parse_and_eval('vabits_actual') + else: + self.VA_BITS_MIN =3D self.VA_BITS + self.vabits_actual =3D self.VA_BITS + self.kimage_voffset =3D gdb.parse_and_eval('kimage_voffset') & ((1= << 64) - 1) + + self.SECTIONS_SHIFT =3D self.MAX_PHYSMEM_BITS - self.SECTION_SIZE_= BITS + + if str(constants.LX_CONFIG_ARCH_FORCE_MAX_ORDER).isdigit(): + self.MAX_ORDER =3D constants.LX_CONFIG_ARCH_FORCE_MAX_ORDER + else: + self.MAX_ORDER =3D 11 + + self.MAX_ORDER_NR_PAGES =3D 1 << (self.MAX_ORDER - 1) + self.PFN_SECTION_SHIFT =3D self.SECTION_SIZE_BITS - self.PAGE_SHIFT + self.NR_MEM_SECTIONS =3D 1 << self.SECTIONS_SHIFT + self.PAGES_PER_SECTION =3D 1 << self.PFN_SECTION_SHIFT + self.PAGE_SECTION_MASK =3D (~(self.PAGES_PER_SECTION - 1)) & ((1 <= < 64) - 1) + + if constants.LX_CONFIG_SPARSEMEM_EXTREME: + self.SECTIONS_PER_ROOT =3D self.PAGE_SIZE // gdb.lookup_type("= struct mem_section").sizeof + else: + self.SECTIONS_PER_ROOT =3D 1 + + self.NR_SECTION_ROOTS =3D DIV_ROUND_UP(self.NR_MEM_SECTIONS, self.= SECTIONS_PER_ROOT) + self.SECTION_ROOT_MASK =3D self.SECTIONS_PER_ROOT - 1 + self.SUBSECTION_SHIFT =3D 21 + self.SEBSECTION_SIZE =3D 1 << self.SUBSECTION_SHIFT + self.PFN_SUBSECTION_SHIFT =3D self.SUBSECTION_SHIFT - self.PAGE_SH= IFT + self.PAGES_PER_SUBSECTION =3D 1 << self.PFN_SUBSECTION_SHIFT + + self.SECTION_HAS_MEM_MAP =3D 1 << int(gdb.parse_and_eval('SECTION_= HAS_MEM_MAP_BIT')) + self.SECTION_IS_EARLY =3D 1 << int(gdb.parse_and_eval('SECTION_IS_= EARLY_BIT')) + + self.struct_page_size =3D utils.get_page_type().sizeof + self.STRUCT_PAGE_MAX_SHIFT =3D (int)(math.log(self.struct_page_siz= e, 2)) + + self.PAGE_OFFSET =3D self._PAGE_OFFSET(self.VA_BITS) + self.MODULES_VADDR =3D self._PAGE_END(self.VA_BITS_MIN) + self.MODULES_END =3D self.MODULES_VADDR + self.MODULES_VSIZE + + self.VMEMMAP_SHIFT =3D (self.PAGE_SHIFT - self.STRUCT_PAGE_MAX_SHI= FT) + self.VMEMMAP_SIZE =3D ((self._PAGE_END(self.VA_BITS_MIN) - self.PA= GE_OFFSET) >> self.VMEMMAP_SHIFT) + self.VMEMMAP_START =3D (-(1 << (self.VA_BITS - self.VMEMMAP_SHIFT)= )) & 0xffffffffffffffff + self.VMEMMAP_END =3D self.VMEMMAP_START + self.VMEMMAP_SIZE + + self.VMALLOC_START =3D self.MODULES_END + self.VMALLOC_END =3D self.VMEMMAP_START - 256 * 1024 * 1024 + + self.memstart_addr =3D gdb.parse_and_eval("memstart_addr") + self.PHYS_OFFSET =3D self.memstart_addr + self.vmemmap =3D gdb.Value(self.VMEMMAP_START).cast(utils.get_page= _type().pointer()) - (self.memstart_addr >> self.PAGE_SHIFT) + + self.KERNEL_START =3D gdb.parse_and_eval("_text") + self.KERNEL_END =3D gdb.parse_and_eval("_end") + + if constants.LX_CONFIG_KASAN_GENERIC or constants.LX_CONFIG_KASAN_= SW_TAGS: + if constants.LX_CONFIG_KASAN_GENERIC: + self.KASAN_SHADOW_SCALE_SHIFT =3D 3 else: - raise Exception(f'Unknown level {level}') - - entry_offset =3D ((translating_va >> start_bit(level)) & 511) * 8 - entry_va =3D _page_offset_base() + phys_addr + entry_offset - return entry_va - -class Cr3(): - def __init__(self, cr3, page_levels): - self.cr3 =3D cr3 - self.page_levels =3D page_levels - self.page_level_write_through =3D is_bit_defined_tupled(cr3, 3) - self.page_level_cache_disabled =3D is_bit_defined_tupled(cr3, 4) - self.next_entry_physical_address =3D cr3 & PHYSICAL_ADDRESS_MASK &= page_mask() - - def next_entry(self, va): - next_level =3D self.page_levels - return PageHierarchyEntry(entry_va(next_level, self.next_entry_phy= sical_address, va), next_level) - - def mk_string(self): - return f"""\ -cr3: - {'cr3 binary data': <30} {hex(self.cr3)} - {'next entry physical address': <30} {hex(self.next_entry_physical_add= ress)} - --- - {'bit' : <4} {self.page_level_write_through[0]: <10} {'page level writ= e through': <30} {self.page_level_write_through[1]} - {'bit' : <4} {self.page_level_cache_disabled[0]: <10} {'page level cac= he disabled': <30} {self.page_level_cache_disabled[1]} -""" - - -class PageHierarchyEntry(): - def __init__(self, address, level): - data =3D int.from_bytes( - memoryview(gdb.selected_inferior().read_memory(address, 8)), - "little" - ) - if level =3D=3D 1: - self.is_page =3D True - self.entry_present =3D is_bit_defined_tupled(data, 0) - self.read_write =3D is_bit_defined_tupled(data, 1) - self.user_access_allowed =3D is_bit_defined_tupled(data, 2) - self.page_level_write_through =3D is_bit_defined_tupled(data, = 3) - self.page_level_cache_disabled =3D is_bit_defined_tupled(data,= 4) - self.entry_was_accessed =3D is_bit_defined_tupled(data, 5) - self.dirty =3D is_bit_defined_tupled(data, 6) - self.pat =3D is_bit_defined_tupled(data, 7) - self.global_translation =3D is_bit_defined_tupled(data, 8) - self.page_physical_address =3D data & PHYSICAL_ADDRESS_MASK & = page_mask(level) - self.next_entry_physical_address =3D None - self.hlat_restart_with_ordinary =3D is_bit_defined_tupled(data= , 11) - self.protection_key =3D content_tupled(data, 59, 62) - self.executed_disable =3D is_bit_defined_tupled(data, 63) + self.KASAN_SHADOW_SCALE_SHIFT =3D 4 + self.KASAN_SHADOW_OFFSET =3D constants.LX_CONFIG_KASAN_SHADOW_= OFFSET + self.KASAN_SHADOW_END =3D (1 << (64 - self.KASAN_SHADOW_SCALE_= SHIFT)) + self.KASAN_SHADOW_OFFSET + self.PAGE_END =3D self.KASAN_SHADOW_END - (1 << (self.vabits_a= ctual - self.KASAN_SHADOW_SCALE_SHIFT)) + else: + self.PAGE_END =3D self._PAGE_END(self.VA_BITS_MIN) + + if constants.LX_CONFIG_NUMA and constants.LX_CONFIG_NODES_SHIFT: + self.NODE_SHIFT =3D constants.LX_CONFIG_NODES_SHIFT + else: + self.NODE_SHIFT =3D 0 + + self.MAX_NUMNODES =3D 1 << self.NODE_SHIFT + + def SECTION_NR_TO_ROOT(self, sec): + return sec // self.SECTIONS_PER_ROOT + + def __nr_to_section(self, nr): + root =3D self.SECTION_NR_TO_ROOT(nr) + mem_section =3D gdb.parse_and_eval("mem_section") + return mem_section[root][nr & self.SECTION_ROOT_MASK] + + def pfn_to_section_nr(self, pfn): + return pfn >> self.PFN_SECTION_SHIFT + + def section_nr_to_pfn(self, sec): + return sec << self.PFN_SECTION_SHIFT + + def __pfn_to_section(self, pfn): + return self.__nr_to_section(self.pfn_to_section_nr(pfn)) + + def pfn_to_section(self, pfn): + return self.__pfn_to_section(pfn) + + def subsection_map_index(self, pfn): + return (pfn & ~(self.PAGE_SECTION_MASK)) // self.PAGES_PER_SUBSECT= ION + + def pfn_section_valid(self, ms, pfn): + if constants.LX_CONFIG_SPARSEMEM_VMEMMAP: + idx =3D self.subsection_map_index(pfn) + return test_bit(idx, ms['usage']['subsection_map']) + else: + return True + + def valid_section(self, mem_section): + if mem_section !=3D None and (mem_section['section_mem_map'] & sel= f.SECTION_HAS_MEM_MAP): + return True + return False + + def early_section(self, mem_section): + if mem_section !=3D None and (mem_section['section_mem_map'] & sel= f.SECTION_IS_EARLY): + return True + return False + + def pfn_valid(self, pfn): + ms =3D None + if self.PHYS_PFN(self.PFN_PHYS(pfn)) !=3D pfn: + return False + if self.pfn_to_section_nr(pfn) >=3D self.NR_MEM_SECTIONS: + return False + ms =3D self.__pfn_to_section(pfn) + + if not self.valid_section(ms): + return False + return self.early_section(ms) or self.pfn_section_valid(ms, pfn) + + def _PAGE_OFFSET(self, va): + return (-(1 << (va))) & 0xffffffffffffffff + + def _PAGE_END(self, va): + return (-(1 << (va - 1))) & 0xffffffffffffffff + + def kasan_reset_tag(self, addr): + if constants.LX_CONFIG_KASAN_SW_TAGS or constants.LX_CONFIG_KASAN_= HW_TAGS: + return int(addr) | (0xff << 56) + else: + return addr + + def __is_lm_address(self, addr): + if (addr - self.PAGE_OFFSET) < (self.PAGE_END - self.PAGE_OFFSET): + return True + else: + return False + def __lm_to_phys(self, addr): + return addr - self.PAGE_OFFSET + self.PHYS_OFFSET + + def __kimg_to_phys(self, addr): + return addr - self.kimage_voffset + + def __virt_to_phys_nodebug(self, va): + untagged_va =3D self.kasan_reset_tag(va) + if self.__is_lm_address(untagged_va): + return self.__lm_to_phys(untagged_va) + else: + return self.__kimg_to_phys(untagged_va) + + def __virt_to_phys(self, va): + if constants.LX_CONFIG_DEBUG_VIRTUAL: + if not self.__is_lm_address(self.kasan_reset_tag(va)): + raise gdb.GdbError("Warning: virt_to_phys used for non-lin= ear address: 0x%lx\n" % va) + return self.__virt_to_phys_nodebug(va) + + def virt_to_phys(self, va): + return self.__virt_to_phys(va) + + def PFN_PHYS(self, pfn): + return pfn << self.PAGE_SHIFT + + def PHYS_PFN(self, phys): + return phys >> self.PAGE_SHIFT + + def __phys_to_virt(self, pa): + return (pa - self.PHYS_OFFSET) | self.PAGE_OFFSET + + def __phys_to_pfn(self, pa): + return self.PHYS_PFN(pa) + + def __pfn_to_phys(self, pfn): + return self.PFN_PHYS(pfn) + + def __pa_symbol_nodebug(self, x): + return self.__kimg_to_phys(x) + + def __phys_addr_symbol(self, x): + if constants.LX_CONFIG_DEBUG_VIRTUAL: + if x < self.KERNEL_START or x > self.KERNEL_END: + raise gdb.GdbError("0x%x exceed kernel range" % x) + return self.__pa_symbol_nodebug(x) + + def __pa_symbol(self, x): + return self.__phys_addr_symbol(x) + + def __va(self, pa): + return self.__phys_to_virt(pa) + + def pfn_to_kaddr(self, pfn): + return self.__va(pfn << self.PAGE_SHIFT) + + def virt_to_pfn(self, va): + return self.__phys_to_pfn(self.__virt_to_phys(va)) + + def sym_to_pfn(self, x): + return self.__phys_to_pfn(self.__pa_symbol(x)) + + def page_to_pfn(self, page): + return int(page.cast(utils.get_page_type().pointer()) - self.vmemm= ap.cast(utils.get_page_type().pointer())) + + def page_to_phys(self, page): + return self.__pfn_to_phys(self.page_to_pfn(page)) + + def pfn_to_page(self, pfn): + return (self.vmemmap + pfn).cast(utils.get_page_type().pointer()) + + def page_to_virt(self, page): + if constants.LX_CONFIG_DEBUG_VIRTUAL: + return self.__va(self.page_to_phys(page)) else: - page_size =3D is_bit_defined_tupled(data, 7) - page_size_bit =3D page_size[1] - self.is_page =3D page_size_bit - self.entry_present =3D is_bit_defined_tupled(data, 0) - self.read_write =3D is_bit_defined_tupled(data, 1) - self.user_access_allowed =3D is_bit_defined_tupled(data, 2) - self.page_level_write_through =3D is_bit_defined_tupled(data, = 3) - self.page_level_cache_disabled =3D is_bit_defined_tupled(data,= 4) - self.entry_was_accessed =3D is_bit_defined_tupled(data, 5) - self.page_size =3D page_size - self.dirty =3D is_bit_defined_tupled( - data, 6) if page_size_bit else None - self.global_translation =3D is_bit_defined_tupled( - data, 8) if page_size_bit else None - self.pat =3D is_bit_defined_tupled( - data, 12) if page_size_bit else None - self.page_physical_address =3D data & PHYSICAL_ADDRESS_MASK & = page_mask(level) if page_size_bit else None - self.next_entry_physical_address =3D None if page_size_bit els= e data & PHYSICAL_ADDRESS_MASK & page_mask() - self.hlat_restart_with_ordinary =3D is_bit_defined_tupled(data= , 11) - self.protection_key =3D content_tupled(data, 59, 62) if page_s= ize_bit else None - self.executed_disable =3D is_bit_defined_tupled(data, 63) - self.address =3D address - self.page_entry_binary_data =3D data - self.page_hierarchy_level =3D level - - def next_entry(self, va): - if self.is_page or not self.entry_present[1]: - return None - - next_level =3D self.page_hierarchy_level - 1 - return PageHierarchyEntry(entry_va(next_level, self.next_entry_phy= sical_address, va), next_level) - - - def mk_string(self): - if not self.entry_present[1]: - return f"""\ -level {self.page_hierarchy_level}: - {'entry address': <30} {hex(self.address)} - {'page entry binary data': <30} {hex(self.page_entry_binary_data)} - --- - PAGE ENTRY IS NOT PRESENT! -""" - elif self.is_page: - def page_size_line(ps_bit, ps, level): - return "" if level =3D=3D 1 else f"{'bit': <3} {ps_bit: <5= } {'page size': <30} {ps}" - - return f"""\ -level {self.page_hierarchy_level}: - {'entry address': <30} {hex(self.address)} - {'page entry binary data': <30} {hex(self.page_entry_binary_data)} - {'page size': <30} {'1GB' if self.page_hierarchy_level =3D=3D 3 else '= 2MB' if self.page_hierarchy_level =3D=3D 2 else '4KB' if self.page_hierarch= y_level =3D=3D 1 else 'Unknown page size for level:' + self.page_hierarchy_= level} - {'page physical address': <30} {hex(self.page_physical_address)} - --- - {'bit': <4} {self.entry_present[0]: <10} {'entry present': <30} {self.= entry_present[1]} - {'bit': <4} {self.read_write[0]: <10} {'read/write access allowed': <3= 0} {self.read_write[1]} - {'bit': <4} {self.user_access_allowed[0]: <10} {'user access allowed':= <30} {self.user_access_allowed[1]} - {'bit': <4} {self.page_level_write_through[0]: <10} {'page level write= through': <30} {self.page_level_write_through[1]} - {'bit': <4} {self.page_level_cache_disabled[0]: <10} {'page level cach= e disabled': <30} {self.page_level_cache_disabled[1]} - {'bit': <4} {self.entry_was_accessed[0]: <10} {'entry has been accesse= d': <30} {self.entry_was_accessed[1]} - {"" if self.page_hierarchy_level =3D=3D 1 else f"{'bit': <4} {self.pag= e_size[0]: <10} {'page size': <30} {self.page_size[1]}"} - {'bit': <4} {self.dirty[0]: <10} {'page dirty': <30} {self.dirty[1]} - {'bit': <4} {self.global_translation[0]: <10} {'global translation': <= 30} {self.global_translation[1]} - {'bit': <4} {self.hlat_restart_with_ordinary[0]: <10} {'restart to ord= inary': <30} {self.hlat_restart_with_ordinary[1]} - {'bit': <4} {self.pat[0]: <10} {'pat': <30} {self.pat[1]} - {'bits': <4} {str(self.protection_key[0]): <10} {'protection key': <30= } {self.protection_key[1]} - {'bit': <4} {self.executed_disable[0]: <10} {'execute disable': <30} {= self.executed_disable[1]} -""" + __idx =3D int((page.cast(gdb.lookup_type("unsigned long")) - s= elf.VMEMMAP_START).cast(utils.get_ulong_type())) // self.struct_page_size + return self.PAGE_OFFSET + (__idx * self.PAGE_SIZE) + + def virt_to_page(self, va): + if constants.LX_CONFIG_DEBUG_VIRTUAL: + return self.pfn_to_page(self.virt_to_pfn(va)) else: - return f"""\ -level {self.page_hierarchy_level}: - {'entry address': <30} {hex(self.address)} - {'page entry binary data': <30} {hex(self.page_entry_binary_data)} - {'next entry physical address': <30} {hex(self.next_entry_physical_add= ress)} - --- - {'bit': <4} {self.entry_present[0]: <10} {'entry present': <30} {self.= entry_present[1]} - {'bit': <4} {self.read_write[0]: <10} {'read/write access allowed': <3= 0} {self.read_write[1]} - {'bit': <4} {self.user_access_allowed[0]: <10} {'user access allowed':= <30} {self.user_access_allowed[1]} - {'bit': <4} {self.page_level_write_through[0]: <10} {'page level write= through': <30} {self.page_level_write_through[1]} - {'bit': <4} {self.page_level_cache_disabled[0]: <10} {'page level cach= e disabled': <30} {self.page_level_cache_disabled[1]} - {'bit': <4} {self.entry_was_accessed[0]: <10} {'entry has been accesse= d': <30} {self.entry_was_accessed[1]} - {'bit': <4} {self.page_size[0]: <10} {'page size': <30} {self.page_siz= e[1]} - {'bit': <4} {self.hlat_restart_with_ordinary[0]: <10} {'restart to ord= inary': <30} {self.hlat_restart_with_ordinary[1]} - {'bit': <4} {self.executed_disable[0]: <10} {'execute disable': <30} {= self.executed_disable[1]} -""" - - -class TranslateVM(gdb.Command): - """Prints the entire paging structure used to translate a given virtua= l address. - -Having an address space of the currently executed process translates the v= irtual address -and prints detailed information of all paging structure levels used for th= e transaltion. -Currently supported arch: x86""" + __idx =3D int(self.kasan_reset_tag(va) - self.PAGE_OFFSET) // = self.PAGE_SIZE + addr =3D self.VMEMMAP_START + (__idx * self.struct_page_size) + return gdb.Value(addr).cast(utils.get_page_type().pointer()) + + def page_address(self, page): + return self.page_to_virt(page) + + def folio_address(self, folio): + return self.page_address(folio['page'].address) + +class LxPFN2Page(gdb.Command): + """PFN to struct page""" =20 def __init__(self): - super(TranslateVM, self).__init__('translate-vm', gdb.COMMAND_USER) + super(LxPFN2Page, self).__init__("lx-pfn_to_page", gdb.COMMAND_USE= R) =20 def invoke(self, arg, from_tty): - if utils.is_target_arch("x86"): - vm_address =3D gdb.parse_and_eval(f'{arg}') - cr3_data =3D gdb.parse_and_eval('$cr3') - cr4 =3D gdb.parse_and_eval('$cr4') - page_levels =3D 5 if cr4 & (1 << 12) else 4 - page_entry =3D Cr3(cr3_data, page_levels) - while page_entry: - gdb.write(page_entry.mk_string()) - page_entry =3D page_entry.next_entry(vm_address) - else: - gdb.GdbError("Virtual address translation is not" - "supported for this arch") + argv =3D gdb.string_to_argv(arg) + pfn =3D int(argv[0]) + page =3D page_ops().ops.pfn_to_page(pfn) + gdb.write("pfn_to_page(0x%x) =3D 0x%x\n" % (pfn, page)) + +LxPFN2Page() + +class LxPage2PFN(gdb.Command): + """struct page to PFN""" + + def __init__(self): + super(LxPage2PFN, self).__init__("lx-page_to_pfn", gdb.COMMAND_USE= R) + + def invoke(self, arg, from_tty): + argv =3D gdb.string_to_argv(arg) + struct_page_addr =3D int(argv[0], 16) + page =3D gdb.Value(struct_page_addr).cast(utils.get_page_type().po= inter()) + pfn =3D page_ops().ops.page_to_pfn(page) + gdb.write("page_to_pfn(0x%x) =3D 0x%x\n" % (page, pfn)) + +LxPage2PFN() + +class LxPageAddress(gdb.Command): + """struct page to linear mapping address""" + + def __init__(self): + super(LxPageAddress, self).__init__("lx-page_address", gdb.COMMAND= _USER) + + def invoke(self, arg, from_tty): + argv =3D gdb.string_to_argv(arg) + struct_page_addr =3D int(argv[0], 16) + page =3D gdb.Value(struct_page_addr).cast(utils.get_page_type().po= inter()) + addr =3D page_ops().ops.page_address(page) + gdb.write("page_address(0x%x) =3D 0x%x\n" % (page, addr)) =20 +LxPageAddress() + +class LxPage2Phys(gdb.Command): + """struct page to physical address""" + + def __init__(self): + super(LxPage2Phys, self).__init__("lx-page_to_phys", gdb.COMMAND_U= SER) + + def invoke(self, arg, from_tty): + argv =3D gdb.string_to_argv(arg) + struct_page_addr =3D int(argv[0], 16) + page =3D gdb.Value(struct_page_addr).cast(utils.get_page_type().po= inter()) + phys_addr =3D page_ops().ops.page_to_phys(page) + gdb.write("page_to_phys(0x%x) =3D 0x%x\n" % (page, phys_addr)) + +LxPage2Phys() + +class LxVirt2Phys(gdb.Command): + """virtual address to physical address""" + + def __init__(self): + super(LxVirt2Phys, self).__init__("lx-virt_to_phys", gdb.COMMAND_U= SER) + + def invoke(self, arg, from_tty): + argv =3D gdb.string_to_argv(arg) + linear_addr =3D int(argv[0], 16) + phys_addr =3D page_ops().ops.virt_to_phys(linear_addr) + gdb.write("virt_to_phys(0x%x) =3D 0x%x\n" % (linear_addr, phys_add= r)) + +LxVirt2Phys() + +class LxVirt2Page(gdb.Command): + """virtual address to struct page""" + + def __init__(self): + super(LxVirt2Page, self).__init__("lx-virt_to_page", gdb.COMMAND_U= SER) + + def invoke(self, arg, from_tty): + argv =3D gdb.string_to_argv(arg) + linear_addr =3D int(argv[0], 16) + page =3D page_ops().ops.virt_to_page(linear_addr) + gdb.write("virt_to_page(0x%x) =3D 0x%x\n" % (linear_addr, page)) + +LxVirt2Page() + +class LxSym2PFN(gdb.Command): + """symbol address to PFN""" + + def __init__(self): + super(LxSym2PFN, self).__init__("lx-sym_to_pfn", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + argv =3D gdb.string_to_argv(arg) + sym_addr =3D int(argv[0], 16) + pfn =3D page_ops().ops.sym_to_pfn(sym_addr) + gdb.write("sym_to_pfn(0x%x) =3D %d\n" % (sym_addr, pfn)) + +LxSym2PFN() + +class LxPFN2Kaddr(gdb.Command): + """PFN to kernel address""" + + def __init__(self): + super(LxPFN2Kaddr, self).__init__("lx-pfn_to_kaddr", gdb.COMMAND_U= SER) + + def invoke(self, arg, from_tty): + argv =3D gdb.string_to_argv(arg) + pfn =3D int(argv[0]) + kaddr =3D page_ops().ops.pfn_to_kaddr(pfn) + gdb.write("pfn_to_kaddr(%d) =3D 0x%x\n" % (pfn, kaddr)) =20 -TranslateVM() +LxPFN2Kaddr() diff --git a/scripts/gdb/linux/pgtable.py b/scripts/gdb/linux/pgtable.py new file mode 100644 index 000000000000..30d837f3dfae --- /dev/null +++ b/scripts/gdb/linux/pgtable.py @@ -0,0 +1,222 @@ +# SPDX-License-Identifier: GPL-2.0-only +# +# gdb helper commands and functions for Linux kernel debugging +# +# routines to introspect page table +# +# Authors: +# Dmitrii Bundin +# + +import gdb + +from linux import utils + +PHYSICAL_ADDRESS_MASK =3D gdb.parse_and_eval('0xfffffffffffff') + + +def page_mask(level=3D1): + # 4KB + if level =3D=3D 1: + return gdb.parse_and_eval('(u64) ~0xfff') + # 2MB + elif level =3D=3D 2: + return gdb.parse_and_eval('(u64) ~0x1fffff') + # 1GB + elif level =3D=3D 3: + return gdb.parse_and_eval('(u64) ~0x3fffffff') + else: + raise Exception(f'Unknown page level: {level}') + + +#page_offset_base in case CONFIG_DYNAMIC_MEMORY_LAYOUT is disabled +POB_NO_DYNAMIC_MEM_LAYOUT =3D '0xffff888000000000' +def _page_offset_base(): + pob_symbol =3D gdb.lookup_global_symbol('page_offset_base') + pob =3D pob_symbol.name if pob_symbol else POB_NO_DYNAMIC_MEM_LAYOUT + return gdb.parse_and_eval(pob) + + +def is_bit_defined_tupled(data, offset): + return offset, bool(data >> offset & 1) + +def content_tupled(data, bit_start, bit_end): + return (bit_start, bit_end), data >> bit_start & ((1 << (1 + bit_end -= bit_start)) - 1) + +def entry_va(level, phys_addr, translating_va): + def start_bit(level): + if level =3D=3D 5: + return 48 + elif level =3D=3D 4: + return 39 + elif level =3D=3D 3: + return 30 + elif level =3D=3D 2: + return 21 + elif level =3D=3D 1: + return 12 + else: + raise Exception(f'Unknown level {level}') + + entry_offset =3D ((translating_va >> start_bit(level)) & 511) * 8 + entry_va =3D _page_offset_base() + phys_addr + entry_offset + return entry_va + +class Cr3(): + def __init__(self, cr3, page_levels): + self.cr3 =3D cr3 + self.page_levels =3D page_levels + self.page_level_write_through =3D is_bit_defined_tupled(cr3, 3) + self.page_level_cache_disabled =3D is_bit_defined_tupled(cr3, 4) + self.next_entry_physical_address =3D cr3 & PHYSICAL_ADDRESS_MASK &= page_mask() + + def next_entry(self, va): + next_level =3D self.page_levels + return PageHierarchyEntry(entry_va(next_level, self.next_entry_phy= sical_address, va), next_level) + + def mk_string(self): + return f"""\ +cr3: + {'cr3 binary data': <30} {hex(self.cr3)} + {'next entry physical address': <30} {hex(self.next_entry_physical_add= ress)} + --- + {'bit' : <4} {self.page_level_write_through[0]: <10} {'page level writ= e through': <30} {self.page_level_write_through[1]} + {'bit' : <4} {self.page_level_cache_disabled[0]: <10} {'page level cac= he disabled': <30} {self.page_level_cache_disabled[1]} +""" + + +class PageHierarchyEntry(): + def __init__(self, address, level): + data =3D int.from_bytes( + memoryview(gdb.selected_inferior().read_memory(address, 8)), + "little" + ) + if level =3D=3D 1: + self.is_page =3D True + self.entry_present =3D is_bit_defined_tupled(data, 0) + self.read_write =3D is_bit_defined_tupled(data, 1) + self.user_access_allowed =3D is_bit_defined_tupled(data, 2) + self.page_level_write_through =3D is_bit_defined_tupled(data, = 3) + self.page_level_cache_disabled =3D is_bit_defined_tupled(data,= 4) + self.entry_was_accessed =3D is_bit_defined_tupled(data, 5) + self.dirty =3D is_bit_defined_tupled(data, 6) + self.pat =3D is_bit_defined_tupled(data, 7) + self.global_translation =3D is_bit_defined_tupled(data, 8) + self.page_physical_address =3D data & PHYSICAL_ADDRESS_MASK & = page_mask(level) + self.next_entry_physical_address =3D None + self.hlat_restart_with_ordinary =3D is_bit_defined_tupled(data= , 11) + self.protection_key =3D content_tupled(data, 59, 62) + self.executed_disable =3D is_bit_defined_tupled(data, 63) + else: + page_size =3D is_bit_defined_tupled(data, 7) + page_size_bit =3D page_size[1] + self.is_page =3D page_size_bit + self.entry_present =3D is_bit_defined_tupled(data, 0) + self.read_write =3D is_bit_defined_tupled(data, 1) + self.user_access_allowed =3D is_bit_defined_tupled(data, 2) + self.page_level_write_through =3D is_bit_defined_tupled(data, = 3) + self.page_level_cache_disabled =3D is_bit_defined_tupled(data,= 4) + self.entry_was_accessed =3D is_bit_defined_tupled(data, 5) + self.page_size =3D page_size + self.dirty =3D is_bit_defined_tupled( + data, 6) if page_size_bit else None + self.global_translation =3D is_bit_defined_tupled( + data, 8) if page_size_bit else None + self.pat =3D is_bit_defined_tupled( + data, 12) if page_size_bit else None + self.page_physical_address =3D data & PHYSICAL_ADDRESS_MASK & = page_mask(level) if page_size_bit else None + self.next_entry_physical_address =3D None if page_size_bit els= e data & PHYSICAL_ADDRESS_MASK & page_mask() + self.hlat_restart_with_ordinary =3D is_bit_defined_tupled(data= , 11) + self.protection_key =3D content_tupled(data, 59, 62) if page_s= ize_bit else None + self.executed_disable =3D is_bit_defined_tupled(data, 63) + self.address =3D address + self.page_entry_binary_data =3D data + self.page_hierarchy_level =3D level + + def next_entry(self, va): + if self.is_page or not self.entry_present[1]: + return None + + next_level =3D self.page_hierarchy_level - 1 + return PageHierarchyEntry(entry_va(next_level, self.next_entry_phy= sical_address, va), next_level) + + + def mk_string(self): + if not self.entry_present[1]: + return f"""\ +level {self.page_hierarchy_level}: + {'entry address': <30} {hex(self.address)} + {'page entry binary data': <30} {hex(self.page_entry_binary_data)} + --- + PAGE ENTRY IS NOT PRESENT! +""" + elif self.is_page: + def page_size_line(ps_bit, ps, level): + return "" if level =3D=3D 1 else f"{'bit': <3} {ps_bit: <5= } {'page size': <30} {ps}" + + return f"""\ +level {self.page_hierarchy_level}: + {'entry address': <30} {hex(self.address)} + {'page entry binary data': <30} {hex(self.page_entry_binary_data)} + {'page size': <30} {'1GB' if self.page_hierarchy_level =3D=3D 3 else '= 2MB' if self.page_hierarchy_level =3D=3D 2 else '4KB' if self.page_hierarch= y_level =3D=3D 1 else 'Unknown page size for level:' + self.page_hierarchy_= level} + {'page physical address': <30} {hex(self.page_physical_address)} + --- + {'bit': <4} {self.entry_present[0]: <10} {'entry present': <30} {self.= entry_present[1]} + {'bit': <4} {self.read_write[0]: <10} {'read/write access allowed': <3= 0} {self.read_write[1]} + {'bit': <4} {self.user_access_allowed[0]: <10} {'user access allowed':= <30} {self.user_access_allowed[1]} + {'bit': <4} {self.page_level_write_through[0]: <10} {'page level write= through': <30} {self.page_level_write_through[1]} + {'bit': <4} {self.page_level_cache_disabled[0]: <10} {'page level cach= e disabled': <30} {self.page_level_cache_disabled[1]} + {'bit': <4} {self.entry_was_accessed[0]: <10} {'entry has been accesse= d': <30} {self.entry_was_accessed[1]} + {"" if self.page_hierarchy_level =3D=3D 1 else f"{'bit': <4} {self.pag= e_size[0]: <10} {'page size': <30} {self.page_size[1]}"} + {'bit': <4} {self.dirty[0]: <10} {'page dirty': <30} {self.dirty[1]} + {'bit': <4} {self.global_translation[0]: <10} {'global translation': <= 30} {self.global_translation[1]} + {'bit': <4} {self.hlat_restart_with_ordinary[0]: <10} {'restart to ord= inary': <30} {self.hlat_restart_with_ordinary[1]} + {'bit': <4} {self.pat[0]: <10} {'pat': <30} {self.pat[1]} + {'bits': <4} {str(self.protection_key[0]): <10} {'protection key': <30= } {self.protection_key[1]} + {'bit': <4} {self.executed_disable[0]: <10} {'execute disable': <30} {= self.executed_disable[1]} +""" + else: + return f"""\ +level {self.page_hierarchy_level}: + {'entry address': <30} {hex(self.address)} + {'page entry binary data': <30} {hex(self.page_entry_binary_data)} + {'next entry physical address': <30} {hex(self.next_entry_physical_add= ress)} + --- + {'bit': <4} {self.entry_present[0]: <10} {'entry present': <30} {self.= entry_present[1]} + {'bit': <4} {self.read_write[0]: <10} {'read/write access allowed': <3= 0} {self.read_write[1]} + {'bit': <4} {self.user_access_allowed[0]: <10} {'user access allowed':= <30} {self.user_access_allowed[1]} + {'bit': <4} {self.page_level_write_through[0]: <10} {'page level write= through': <30} {self.page_level_write_through[1]} + {'bit': <4} {self.page_level_cache_disabled[0]: <10} {'page level cach= e disabled': <30} {self.page_level_cache_disabled[1]} + {'bit': <4} {self.entry_was_accessed[0]: <10} {'entry has been accesse= d': <30} {self.entry_was_accessed[1]} + {'bit': <4} {self.page_size[0]: <10} {'page size': <30} {self.page_siz= e[1]} + {'bit': <4} {self.hlat_restart_with_ordinary[0]: <10} {'restart to ord= inary': <30} {self.hlat_restart_with_ordinary[1]} + {'bit': <4} {self.executed_disable[0]: <10} {'execute disable': <30} {= self.executed_disable[1]} +""" + + +class TranslateVM(gdb.Command): + """Prints the entire paging structure used to translate a given virtua= l address. + +Having an address space of the currently executed process translates the v= irtual address +and prints detailed information of all paging structure levels used for th= e transaltion. +Currently supported arch: x86""" + + def __init__(self): + super(TranslateVM, self).__init__('translate-vm', gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + if utils.is_target_arch("x86"): + vm_address =3D gdb.parse_and_eval(f'{arg}') + cr3_data =3D gdb.parse_and_eval('$cr3') + cr4 =3D gdb.parse_and_eval('$cr4') + page_levels =3D 5 if cr4 & (1 << 12) else 4 + page_entry =3D Cr3(cr3_data, page_levels) + while page_entry: + gdb.write(page_entry.mk_string()) + page_entry =3D page_entry.next_entry(vm_address) + else: + gdb.GdbError("Virtual address translation is not" + "supported for this arch") + + +TranslateVM() diff --git a/scripts/gdb/vmlinux-gdb.py b/scripts/gdb/vmlinux-gdb.py index 2d32308c3f7a..fd24574bcec9 100644 --- a/scripts/gdb/vmlinux-gdb.py +++ b/scripts/gdb/vmlinux-gdb.py @@ -41,6 +41,7 @@ else: import linux.genpd import linux.device import linux.vfs - import linux.mm + import linux.pgtable import linux.radixtree import linux.interrupts + import linux.mm --=20 2.18.0 From nobody Thu Nov 14 05:36:23 2024 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 19BF2C04FE2 for ; Tue, 8 Aug 2023 16:16:02 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S232391AbjHHQPg (ORCPT ); Tue, 8 Aug 2023 12:15:36 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:34718 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232110AbjHHQOA (ORCPT ); Tue, 8 Aug 2023 12:14:00 -0400 Received: from mailgw01.mediatek.com (unknown [60.244.123.138]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 88B0383C2; Tue, 8 Aug 2023 08:47:57 -0700 (PDT) X-UUID: db792dec35c511ee9cb5633481061a41-20230808 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=mediatek.com; s=dk; h=Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:CC:To:From; bh=jLRXZ8JkZ/uttlc+rpLNlOjkZ+tu1NjDBwbmdqcEaJA=; b=dzdvMumbhw19h7492B6v/eP9viSV4gcUZ/n5cjocP4ijzWdEF+smOI7mXs7i29KAKQ61KP+S9ABMsQDQ4U2ylWM+sH/0gQgvHAW4sAnfZ7/dO5ofNemdBKRM7bm5Nw8VMwa5oaC32qDt7pjFUUFTjheFgwGFmmQzHvr8BLQOiLs=; X-CID-P-RULE: Release_Ham X-CID-O-INFO: VERSION:1.1.31,REQID:455cbb54-1471-4810-8799-1f4cc848a486,IP:0,U RL:0,TC:0,Content:0,EDM:0,RT:0,SF:0,FILE:0,BULK:0,RULE:Release_Ham,ACTION: release,TS:0 X-CID-META: VersionHash:0ad78a4,CLOUDID:846146b4-a467-4aa9-9e04-f584452e3794,B ulkID:nil,BulkQuantity:0,Recheck:0,SF:102,TC:nil,Content:0,EDM:-3,IP:nil,U RL:11|1,File:nil,Bulk:nil,QS:nil,BEC:nil,COL:0,OSI:0,OSA:0,AV:0,LES:1,SPR: NO,DKR:0,DKP:0,BRR:0,BRE:0 X-CID-BVR: 0 X-CID-BAS: 0,_,0,_ X-CID-FACTOR: TF_CID_SPAM_SNR,TF_CID_SPAM_ULN X-UUID: db792dec35c511ee9cb5633481061a41-20230808 Received: from mtkmbs11n2.mediatek.inc [(172.21.101.187)] by mailgw01.mediatek.com (envelope-from ) (Generic MTA with TLSv1.2 ECDHE-RSA-AES256-GCM-SHA384 256/256) with ESMTP id 321645413; Tue, 08 Aug 2023 16:30:40 +0800 Received: from mtkmbs13n2.mediatek.inc (172.21.101.108) by mtkmbs10n1.mediatek.inc (172.21.101.34) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.1118.26; Tue, 8 Aug 2023 16:30:38 +0800 Received: from mtksdccf07.mediatek.inc (172.21.84.99) by mtkmbs13n2.mediatek.inc (172.21.101.73) with Microsoft SMTP Server id 15.2.1118.26 via Frontend Transport; Tue, 8 Aug 2023 16:30:38 +0800 From: Kuan-Ying Lee To: Jan Kiszka , Kieran Bingham , Matthias Brugger , AngeloGioacchino Del Regno CC: , , , , , , , Kuan-Ying Lee , , Subject: [PATCH v2 5/8] scripts/gdb/stackdepot: Add stackdepot support Date: Tue, 8 Aug 2023 16:30:15 +0800 Message-ID: <20230808083020.22254-6-Kuan-Ying.Lee@mediatek.com> X-Mailer: git-send-email 2.18.0 In-Reply-To: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> References: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> MIME-Version: 1.0 X-MTK: N Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add support for printing the backtrace of stackdepot handle. This is the preparation patch for dumping page_owner, slabtrace usage. Signed-off-by: Kuan-Ying Lee --- scripts/gdb/linux/constants.py.in | 1 + scripts/gdb/linux/stackdepot.py | 55 +++++++++++++++++++++++++++++++ scripts/gdb/vmlinux-gdb.py | 1 + 3 files changed, 57 insertions(+) create mode 100644 scripts/gdb/linux/stackdepot.py diff --git a/scripts/gdb/linux/constants.py.in b/scripts/gdb/linux/constant= s.py.in index 0805aeab3dcd..f33be26253d2 100644 --- a/scripts/gdb/linux/constants.py.in +++ b/scripts/gdb/linux/constants.py.in @@ -128,3 +128,4 @@ LX_CONFIG(CONFIG_VMAP_STACK) if IS_BUILTIN(CONFIG_NUMA): LX_VALUE(CONFIG_NODES_SHIFT) LX_CONFIG(CONFIG_DEBUG_VIRTUAL) +LX_CONFIG(CONFIG_STACKDEPOT) diff --git a/scripts/gdb/linux/stackdepot.py b/scripts/gdb/linux/stackdepot= .py new file mode 100644 index 000000000000..047d329a6a12 --- /dev/null +++ b/scripts/gdb/linux/stackdepot.py @@ -0,0 +1,55 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Copyright (c) 2023 MediaTek Inc. +# +# Authors: +# Kuan-Ying Lee +# + +import gdb +from linux import utils, constants + +if constants.LX_CONFIG_STACKDEPOT: + stack_record_type =3D utils.CachedType('struct stack_record') + DEPOT_STACK_ALIGN =3D 4 + +def stack_depot_fetch(handle): + global DEPOT_STACK_ALIGN + global stack_record_type + + stack_depot_disabled =3D gdb.parse_and_eval('stack_depot_disabled') + + if stack_depot_disabled: + raise gdb.GdbError("stack_depot_disabled\n") + + handle_parts_t =3D gdb.lookup_type("union handle_parts") + parts =3D handle.cast(handle_parts_t) + offset =3D parts['offset'] << DEPOT_STACK_ALIGN + pool_index_cached =3D gdb.parse_and_eval('pool_index') + + if parts['pool_index'] > pool_index_cached: + gdb.write("pool index %d out of bounds (%d) for stack id 0x%08x\n"= % (parts['pool_index'], pool_index_cached, handle)) + return gdb.Value(0), 0 + + stack_pools =3D gdb.parse_and_eval('stack_pools') + + try: + pool =3D stack_pools[parts['pool_index']] + stack =3D (pool + gdb.Value(offset).cast(utils.get_size_t_type()))= .cast(stack_record_type.get_type().pointer()) + size =3D int(stack['size'].cast(utils.get_ulong_type())) + return stack['entries'], size + except Exception as e: + gdb.write("%s\n" % e) + return gdb.Value(0), 0 + +def stack_depot_print(handle): + if not constants.LX_CONFIG_STACKDEPOT: + raise gdb.GdbError("CONFIG_STACKDEPOT is not enabled") + + entries, nr_entries =3D stack_depot_fetch(handle) + if nr_entries > 0: + for i in range(0, nr_entries): + try: + gdb.execute("x /i 0x%x" % (int(entries[i]))) + except Exception as e: + gdb.write("%s\n" % e) diff --git a/scripts/gdb/vmlinux-gdb.py b/scripts/gdb/vmlinux-gdb.py index fd24574bcec9..24f149694b81 100644 --- a/scripts/gdb/vmlinux-gdb.py +++ b/scripts/gdb/vmlinux-gdb.py @@ -45,3 +45,4 @@ else: import linux.radixtree import linux.interrupts import linux.mm + import linux.stackdepot --=20 2.18.0 From nobody Thu Nov 14 05:36:23 2024 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 7DBA7C05052 for ; Tue, 8 Aug 2023 16:18:13 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S232373AbjHHQRt (ORCPT ); Tue, 8 Aug 2023 12:17:49 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:45156 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232110AbjHHQPk (ORCPT ); Tue, 8 Aug 2023 12:15:40 -0400 Received: from mailgw01.mediatek.com (unknown [60.244.123.138]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 69EF983DB; Tue, 8 Aug 2023 08:48:04 -0700 (PDT) X-UUID: ddfef96635c511ee9cb5633481061a41-20230808 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=mediatek.com; s=dk; h=Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:CC:To:From; bh=Z/V/cug+yRVLoW4a8oKn71hM6nDUiC44a/iWC7mxXGg=; b=apSLlkmnSGmmDUfpyzp+Gh3oErlUdheBYpcAJECWkuGF7Q2JsR7fYe/3I7U/5ha2PlFostjoP50oH9YsHOqoRKa2m651cQwiuvtSBnSWHFqQXCd/4VUxBGYD2nKRN5wlIT3/ZYbdw2oC0F+fbGKRpeL++jxWRIqKDLjmsS9vksc=; X-CID-P-RULE: Release_Ham X-CID-O-INFO: VERSION:1.1.31,REQID:05ca33ab-c3d5-499d-8ab5-722c41ac493d,IP:0,U RL:0,TC:0,Content:0,EDM:0,RT:0,SF:95,FILE:0,BULK:0,RULE:Release_Ham,ACTION :release,TS:95 X-CID-INFO: VERSION:1.1.31,REQID:05ca33ab-c3d5-499d-8ab5-722c41ac493d,IP:0,URL :0,TC:0,Content:0,EDM:0,RT:0,SF:95,FILE:0,BULK:0,RULE:Spam_GS981B3D,ACTION :quarantine,TS:95 X-CID-META: VersionHash:0ad78a4,CLOUDID:7ae7cfd2-cd77-4e67-bbfd-aa4eaace762f,B ulkID:230808163045V7DYIVP9,BulkQuantity:1,Recheck:0,SF:19|48|38|29|28|17,T C:nil,Content:0,EDM:-3,IP:nil,URL:11|1,File:nil,Bulk:40,QS:nil,BEC:nil,COL :0,OSI:0,OSA:0,AV:0,LES:1,SPR:NO,DKR:0,DKP:0,BRR:0,BRE:0 X-CID-BVR: 0 X-CID-BAS: 0,_,0,_ X-CID-FACTOR: TF_CID_SPAM_SDM,TF_CID_SPAM_ASC,TF_CID_SPAM_FAS,TF_CID_SPAM_FSD, TF_CID_SPAM_ULN,TF_CID_SPAM_SNR X-UUID: ddfef96635c511ee9cb5633481061a41-20230808 Received: from mtkmbs14n2.mediatek.inc [(172.21.101.76)] by mailgw01.mediatek.com (envelope-from ) (Generic MTA with TLSv1.2 ECDHE-RSA-AES256-GCM-SHA384 256/256) with ESMTP id 615150699; Tue, 08 Aug 2023 16:30:44 +0800 Received: from mtkmbs13n2.mediatek.inc (172.21.101.108) by mtkmbs10n2.mediatek.inc (172.21.101.183) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.1118.26; Tue, 8 Aug 2023 16:30:43 +0800 Received: from mtksdccf07.mediatek.inc (172.21.84.99) by mtkmbs13n2.mediatek.inc (172.21.101.73) with Microsoft SMTP Server id 15.2.1118.26 via Frontend Transport; Tue, 8 Aug 2023 16:30:43 +0800 From: Kuan-Ying Lee To: Jan Kiszka , Kieran Bingham , Matthias Brugger , AngeloGioacchino Del Regno CC: , , , , , , , Kuan-Ying Lee , , Subject: [PATCH v2 6/8] scripts/gdb/page_owner: add page owner support Date: Tue, 8 Aug 2023 16:30:16 +0800 Message-ID: <20230808083020.22254-7-Kuan-Ying.Lee@mediatek.com> X-Mailer: git-send-email 2.18.0 In-Reply-To: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> References: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> MIME-Version: 1.0 X-MTK: N Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This GDB scripts print page owner information for user to analyze the memory usage or memory corruption issue. Example output from an aarch64 system: (gdb) lx-dump-page-owner --pfn 655360 page_owner tracks the page as allocated Page last allocated via order 0, gfp_mask: 0x8, pid: 1, tgid: 1 ("swapper/0= \000\000\000\000\000\000"), ts 1295948880 ns, free_ts 1011852016 ns PFN: 655360, Flags: 0x3fffc0000000000 0xffff8000086ab964 : ldp x19, x20, [sp, #16] 0xffff80000862e4e0 : cbnz w22, 0xffff80000862= e57c 0xffff8000086370c4 : mov x0, x27 0xffff8000086bc1cc : mov x24, x0 0xffff80000877d6d8 : mov w1, w0 0xffff8000082c8d18 : ldr x19, [sp, #= 16] 0xffff8000082ce0e8 : mov x19, x0 0xffff80000c1e41b4 <__dma_atomic_pool_init+172>: Cannot access memor= y at address 0xffff80000c1e41b4 0xffff80000c1e4298 : Cannot access memor= y at address 0xffff80000c1e4298 0xffff8000080161d4 : mov w21, w0 0xffff80000c1c1b50 : Cannot access memor= y at address 0xffff80000c1c1b50 0xffff80000acf87dc : bl 0xffff8000081ab100 0xffff800008018d00 : mrs x28, sp_el0 page last free stack trace: 0xffff8000086a6e8c : mov w2, w23 0xffff8000086aee1c : tst w0, #0xff 0xffff8000086af3f8 <__free_pages+292>: ldp x19, x20, [sp, #16] 0xffff80000c1f3214 : Cannot acce= ss memory at address 0xffff80000c1f3214 0xffff80000c20363c : Cannot access memor= y at address 0xffff80000c20363c 0xffff8000080161d4 : mov w21, w0 0xffff80000c1c1b50 : Cannot access memor= y at address 0xffff80000c1c1b50 0xffff80000acf87dc : bl 0xffff8000081ab100 0xffff800008018d00 : mrs x28, sp_el0 Signed-off-by: Kuan-Ying Lee --- scripts/gdb/linux/constants.py.in | 7 ++ scripts/gdb/linux/page_owner.py | 190 ++++++++++++++++++++++++++++++ scripts/gdb/vmlinux-gdb.py | 1 + 3 files changed, 198 insertions(+) create mode 100644 scripts/gdb/linux/page_owner.py diff --git a/scripts/gdb/linux/constants.py.in b/scripts/gdb/linux/constant= s.py.in index f33be26253d2..52f61d65f430 100644 --- a/scripts/gdb/linux/constants.py.in +++ b/scripts/gdb/linux/constants.py.in @@ -18,6 +18,7 @@ #include #include #include +#include #include #include =20 @@ -89,6 +90,11 @@ LX_GDBPARSED(RADIX_TREE_MAP_SIZE) LX_GDBPARSED(RADIX_TREE_MAP_SHIFT) LX_GDBPARSED(RADIX_TREE_MAP_MASK) =20 +/* linux/page_ext.h */ +if IS_BUILTIN(CONFIG_PAGE_OWNER): + LX_GDBPARSED(PAGE_EXT_OWNER) + LX_GDBPARSED(PAGE_EXT_OWNER_ALLOCATED) + /* Kernel Configs */ LX_CONFIG(CONFIG_GENERIC_CLOCKEVENTS) LX_CONFIG(CONFIG_GENERIC_CLOCKEVENTS_BROADCAST) @@ -129,3 +135,4 @@ if IS_BUILTIN(CONFIG_NUMA): LX_VALUE(CONFIG_NODES_SHIFT) LX_CONFIG(CONFIG_DEBUG_VIRTUAL) LX_CONFIG(CONFIG_STACKDEPOT) +LX_CONFIG(CONFIG_PAGE_OWNER) diff --git a/scripts/gdb/linux/page_owner.py b/scripts/gdb/linux/page_owner= .py new file mode 100644 index 000000000000..844fd5d0c912 --- /dev/null +++ b/scripts/gdb/linux/page_owner.py @@ -0,0 +1,190 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Copyright (c) 2023 MediaTek Inc. +# +# Authors: +# Kuan-Ying Lee +# + +import gdb +from linux import utils, stackdepot, constants, mm + +if constants.LX_CONFIG_PAGE_OWNER: + page_ext_t =3D utils.CachedType('struct page_ext') + page_owner_t =3D utils.CachedType('struct page_owner') + + PAGE_OWNER_STACK_DEPTH =3D 16 + PAGE_EXT_OWNER =3D constants.LX_PAGE_EXT_OWNER + PAGE_EXT_INVALID =3D 0x1 + PAGE_EXT_OWNER_ALLOCATED =3D constants.LX_PAGE_EXT_OWNER_ALLOCATED + +def help(): + t =3D """Usage: lx-dump-page-owner [Option] + Option: + --pfn [Decimal pfn] + Example: + lx-dump-page-owner --pfn 655360\n""" + gdb.write("Unrecognized command\n") + raise gdb.GdbError(t) + +class DumpPageOwner(gdb.Command): + """Dump page owner""" + + min_pfn =3D None + max_pfn =3D None + p_ops =3D None + migrate_reason_names =3D None + + def __init__(self): + super(DumpPageOwner, self).__init__("lx-dump-page-owner", gdb.COMM= AND_SUPPORT) + + def invoke(self, args, from_tty): + if not constants.LX_CONFIG_PAGE_OWNER: + raise gdb.GdbError('CONFIG_PAGE_OWNER does not enable') + + page_owner_inited =3D gdb.parse_and_eval('page_owner_inited') + if page_owner_inited['key']['enabled']['counter'] !=3D 0x1: + raise gdb.GdbError('page_owner_inited is not enabled') + + self.p_ops =3D mm.page_ops().ops + self.get_page_owner_info() + argv =3D gdb.string_to_argv(args) + if len(argv) =3D=3D 0: + self.read_page_owner() + elif len(argv) =3D=3D 2: + if argv[0] =3D=3D "--pfn": + pfn =3D int(argv[1]) + self.read_page_owner_by_addr(self.p_ops.pfn_to_page(pfn)) + else: + help() + else: + help() + + def get_page_owner_info(self): + self.min_pfn =3D int(gdb.parse_and_eval("min_low_pfn")) + self.max_pfn =3D int(gdb.parse_and_eval("max_pfn")) + self.page_ext_size =3D int(gdb.parse_and_eval("page_ext_size")) + self.migrate_reason_names =3D gdb.parse_and_eval('migrate_reason_n= ames') + + def page_ext_invalid(self, page_ext): + if page_ext =3D=3D gdb.Value(0): + return True + if page_ext.cast(utils.get_ulong_type()) & PAGE_EXT_INVALID =3D=3D= PAGE_EXT_INVALID: + return True + return False + + def get_entry(self, base, index): + return (base.cast(utils.get_ulong_type()) + self.page_ext_size * i= ndex).cast(page_ext_t.get_type().pointer()) + + def lookup_page_ext(self, page): + pfn =3D self.p_ops.page_to_pfn(page) + section =3D self.p_ops.pfn_to_section(pfn) + page_ext =3D section["page_ext"] + if self.page_ext_invalid(page_ext): + return gdb.Value(0) + return self.get_entry(page_ext, pfn) + + def page_ext_get(self, page): + page_ext =3D self.lookup_page_ext(page) + if page_ext !=3D gdb.Value(0): + return page_ext + else: + return gdb.Value(0) + + def get_page_owner(self, page_ext): + addr =3D page_ext.cast(utils.get_ulong_type()) + gdb.parse_and_eva= l("page_owner_ops")["offset"].cast(utils.get_ulong_type()) + return addr.cast(page_owner_t.get_type().pointer()) + + def read_page_owner_by_addr(self, struct_page_addr): + page =3D gdb.Value(struct_page_addr).cast(utils.get_page_type().po= inter()) + pfn =3D self.p_ops.page_to_pfn(page) + + if pfn < self.min_pfn or pfn > self.max_pfn or (not self.p_ops.pfn= _valid(pfn)): + gdb.write("pfn is invalid\n") + return + + page =3D self.p_ops.pfn_to_page(pfn) + page_ext =3D self.page_ext_get(page) + + if page_ext =3D=3D gdb.Value(0): + gdb.write("page_ext is null\n") + return + + if not (page_ext['flags'] & (1 << PAGE_EXT_OWNER)): + gdb.write("page_owner flag is invalid\n") + raise gdb.GdbError('page_owner info is not present (never set?= )\n') + + if mm.test_bit(PAGE_EXT_OWNER_ALLOCATED, page_ext['flags'].address= ): + gdb.write('page_owner tracks the page as allocated\n') + else: + gdb.write('page_owner tracks the page as freed\n') + + if not (page_ext['flags'] & (1 << PAGE_EXT_OWNER_ALLOCATED)): + gdb.write("page_owner is not allocated\n") + + try: + page_owner =3D self.get_page_owner(page_ext) + gdb.write("Page last allocated via order %d, gfp_mask: 0x%x, p= id: %d, tgid: %d (%s), ts %u ns, free_ts %u ns\n" %\ + (page_owner["order"], page_owner["gfp_mask"],\ + page_owner["pid"], page_owner["tgid"], page_owner["com= m"],\ + page_owner["ts_nsec"], page_owner["free_ts_nsec"])) + gdb.write("PFN: %d, Flags: 0x%x\n" % (pfn, page['flags'])) + if page_owner["handle"] =3D=3D 0: + gdb.write('page_owner allocation stack trace missing\n') + else: + stackdepot.stack_depot_print(page_owner["handle"]) + + if page_owner["free_handle"] =3D=3D 0: + gdb.write('page_owner free stack trace missing\n') + else: + gdb.write('page last free stack trace:\n') + stackdepot.stack_depot_print(page_owner["free_handle"]) + if page_owner['last_migrate_reason'] !=3D -1: + gdb.write('page has been migrated, last migrate reason: %s= \n' % self.migrate_reason_names[page_owner['last_migrate_reason']]) + except: + gdb.write("\n") + + def read_page_owner(self): + pfn =3D self.min_pfn + + # Find a valid PFN or the start of a MAX_ORDER_NR_PAGES area + while ((not self.p_ops.pfn_valid(pfn)) and (pfn & (self.p_ops.MAX_= ORDER_NR_PAGES - 1))) !=3D 0: + pfn +=3D 1 + + while pfn < self.max_pfn: + # + # If the new page is in a new MAX_ORDER_NR_PAGES area, + # validate the area as existing, skip it if not + # + if ((pfn & (self.p_ops.MAX_ORDER_NR_PAGES - 1)) =3D=3D 0) and = (not self.p_ops.pfn_valid(pfn)): + pfn +=3D (self.p_ops.MAX_ORDER_NR_PAGES - 1) + continue; + + page =3D self.p_ops.pfn_to_page(pfn) + page_ext =3D self.page_ext_get(page) + if page_ext =3D=3D gdb.Value(0): + pfn +=3D 1 + continue + + if not (page_ext['flags'] & (1 << PAGE_EXT_OWNER)): + pfn +=3D 1 + continue + if not (page_ext['flags'] & (1 << PAGE_EXT_OWNER_ALLOCATED)): + pfn +=3D 1 + continue + + try: + page_owner =3D self.get_page_owner(page_ext) + gdb.write("Page allocated via order %d, gfp_mask: 0x%x, pi= d: %d, tgid: %d (%s), ts %u ns, free_ts %u ns\n" %\ + (page_owner["order"], page_owner["gfp_mask"],\ + page_owner["pid"], page_owner["tgid"], page_owner[= "comm"],\ + page_owner["ts_nsec"], page_owner["free_ts_nsec"])) + gdb.write("PFN: %d, Flags: 0x%x\n" % (pfn, page['flags'])) + stackdepot.stack_depot_print(page_owner["handle"]) + pfn +=3D (1 << page_owner["order"]) + continue + except: + gdb.write("\n") + pfn +=3D 1 + +DumpPageOwner() diff --git a/scripts/gdb/vmlinux-gdb.py b/scripts/gdb/vmlinux-gdb.py index 24f149694b81..89465f0de548 100644 --- a/scripts/gdb/vmlinux-gdb.py +++ b/scripts/gdb/vmlinux-gdb.py @@ -46,3 +46,4 @@ else: import linux.interrupts import linux.mm import linux.stackdepot + import linux.page_owner --=20 2.18.0 From nobody Thu Nov 14 05:36:23 2024 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 1A54CC05051 for ; Tue, 8 Aug 2023 16:16:34 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S232279AbjHHQQE (ORCPT ); Tue, 8 Aug 2023 12:16:04 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57472 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232146AbjHHQOQ (ORCPT ); Tue, 8 Aug 2023 12:14:16 -0400 Received: from mailgw02.mediatek.com (unknown [210.61.82.184]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 8DF3983CC; Tue, 8 Aug 2023 08:48:01 -0700 (PDT) X-UUID: df44968235c511eeb20a276fd37b9834-20230808 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=mediatek.com; s=dk; h=Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:CC:To:From; bh=hGt7NeNlML1MGMWhcOV6ROE/8hYT1LCj/C58WEanJig=; b=UZ0fwCL3Iktwnfr82e/B9uUO+D5oysKiU41pabgBiutGFgNf2EmQ9+oPahLoLuHK/RRAcgW7dbBchZjQIpws2LGR+3LR9ZVGBrGLI0dlVUQ1CNIVvaLy7q1JrKphyTkWXaatelcvo2YSXfFCE2ZKhuZY+6So5IL/gCHfYSVBuFk=; X-CID-P-RULE: Release_Ham X-CID-O-INFO: VERSION:1.1.31,REQID:7fafc22f-d69e-45df-8b80-e2b30dc585fc,IP:0,U RL:0,TC:0,Content:0,EDM:0,RT:0,SF:95,FILE:0,BULK:0,RULE:Release_Ham,ACTION :release,TS:95 X-CID-INFO: VERSION:1.1.31,REQID:7fafc22f-d69e-45df-8b80-e2b30dc585fc,IP:0,URL :0,TC:0,Content:0,EDM:0,RT:0,SF:95,FILE:0,BULK:0,RULE:Spam_GS981B3D,ACTION :quarantine,TS:95 X-CID-META: VersionHash:0ad78a4,CLOUDID:a8e7cfd2-cd77-4e67-bbfd-aa4eaace762f,B ulkID:230808163049VCAOXA3Y,BulkQuantity:0,Recheck:0,SF:28|17|19|48|38|29,T C:nil,Content:0,EDM:-3,IP:nil,URL:11|1,File:nil,Bulk:nil,QS:nil,BEC:nil,CO L:0,OSI:0,OSA:0,AV:0,LES:1,SPR:NO,DKR:0,DKP:0,BRR:0,BRE:0 X-CID-BVR: 0 X-CID-BAS: 0,_,0,_ X-CID-FACTOR: TF_CID_SPAM_SNR,TF_CID_SPAM_SDM,TF_CID_SPAM_ASC,TF_CID_SPAM_FAS, TF_CID_SPAM_FSD,TF_CID_SPAM_ULN X-UUID: df44968235c511eeb20a276fd37b9834-20230808 Received: from mtkmbs10n1.mediatek.inc [(172.21.101.34)] by mailgw02.mediatek.com (envelope-from ) (Generic MTA with TLSv1.2 ECDHE-RSA-AES256-GCM-SHA384 256/256) with ESMTP id 1422125080; Tue, 08 Aug 2023 16:30:46 +0800 Received: from mtkmbs13n2.mediatek.inc (172.21.101.108) by mtkmbs10n2.mediatek.inc (172.21.101.183) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.1118.26; Tue, 8 Aug 2023 16:30:45 +0800 Received: from mtksdccf07.mediatek.inc (172.21.84.99) by mtkmbs13n2.mediatek.inc (172.21.101.73) with Microsoft SMTP Server id 15.2.1118.26 via Frontend Transport; Tue, 8 Aug 2023 16:30:45 +0800 From: Kuan-Ying Lee To: Jan Kiszka , Kieran Bingham , Matthias Brugger , AngeloGioacchino Del Regno CC: , , , , , , , Kuan-Ying Lee , , Subject: [PATCH v2 7/8] scripts/gdb/slab: Add slab support Date: Tue, 8 Aug 2023 16:30:17 +0800 Message-ID: <20230808083020.22254-8-Kuan-Ying.Lee@mediatek.com> X-Mailer: git-send-email 2.18.0 In-Reply-To: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> References: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> MIME-Version: 1.0 X-MTK: N Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add 'lx-slabinfo' and 'lx-slabtrace' support. This GDB scripts print slabinfo and slabtrace for user to analyze slab memory usage. Example output like below: (gdb) lx-slabinfo Pointer | name | active_objs | num_objs | o= bjsize | objperslab | pagesperslab ------------------ | -------------------- | ------------ | ------------ | -= ------- | ----------- | ------------- 0xffff0000c59df480 | p9_req_t | 0 | 0 | 2= 80 | 29 | 2 0xffff0000c59df280 | isp1760_qh | 0 | 0 | 1= 60 | 25 | 1 0xffff0000c59df080 | isp1760_qtd | 0 | 0 | 1= 84 | 22 | 1 0xffff0000c59dee80 | isp1760_urb_listite | 0 | 0 | 1= 36 | 30 | 1 0xffff0000c59dec80 | asd_sas_event | 0 | 0 | 2= 56 | 32 | 2 0xffff0000c59dea80 | sas_task | 0 | 0 | 4= 48 | 36 | 4 0xffff0000c59de880 | bio-120 | 18 | 21 | 3= 84 | 21 | 2 0xffff0000c59de680 | io_kiocb | 0 | 0 | 4= 48 | 36 | 4 0xffff0000c59de480 | bfq_io_cq | 0 | 0 | 1= 504 | 21 | 8 0xffff0000c59de280 | bfq_queue | 0 | 0 | 7= 20 | 22 | 4 0xffff0000c59de080 | mqueue_inode_cache | 1 | 28 | 1= 152 | 28 | 8 0xffff0000c59dde80 | v9fs_inode_cache | 0 | 0 | 8= 32 | 39 | 8 ... (gdb) lx-slabtrace --cache_name kmalloc-1k 63 waste=3D16632/264 age=3D46856/46871/46888= pid=3D1 cpus=3D6, 0xffff800008720240 <__kmem_cache_alloc_node+236>: mov x22, x0 0xffff80000862a4fc : mov x21, x0 0xffff8000095d086c : mov x19, x0 0xffff8000095d0f98 : cmn x0, #0x1, l= sl #12 0xffff80000c2677e8 : Cannot access memory at address 0xf= fff80000c2677e8 0xffff80000c265a10 : Cannot access memory at address 0xf= fff80000c265a10 0xffff80000c26d3c4 : Cannot access memory at add= ress 0xffff80000c26d3c4 0xffff8000080161d4 : mov w21, w0 0xffff80000c1c1b58 : Cannot access memor= y at address 0xffff80000c1c1b58 0xffff80000acf1334 : bl 0xffff8000081ac040 0xffff800008018d00 : mrs x28, sp_el0 (gdb) lx-slabtrace --cache_name kmalloc-1k --free 428 age=3D4294958600 pid=3D0 cpus=3D0, Signed-off-by: Kuan-Ying Lee --- scripts/gdb/linux/constants.py.in | 13 ++ scripts/gdb/linux/slab.py | 326 ++++++++++++++++++++++++++++++ scripts/gdb/vmlinux-gdb.py | 1 + 3 files changed, 340 insertions(+) create mode 100644 scripts/gdb/linux/slab.py diff --git a/scripts/gdb/linux/constants.py.in b/scripts/gdb/linux/constant= s.py.in index 52f61d65f430..03fa6d2cfe01 100644 --- a/scripts/gdb/linux/constants.py.in +++ b/scripts/gdb/linux/constants.py.in @@ -20,6 +20,7 @@ #include #include #include +#include #include =20 /* We need to stringify expanded macros so that they can be parsed */ @@ -95,6 +96,16 @@ if IS_BUILTIN(CONFIG_PAGE_OWNER): LX_GDBPARSED(PAGE_EXT_OWNER) LX_GDBPARSED(PAGE_EXT_OWNER_ALLOCATED) =20 +/* linux/slab.h */ +LX_GDBPARSED(SLAB_RED_ZONE) +LX_GDBPARSED(SLAB_POISON) +LX_GDBPARSED(SLAB_KMALLOC) +LX_GDBPARSED(SLAB_HWCACHE_ALIGN) +LX_GDBPARSED(SLAB_CACHE_DMA) +LX_GDBPARSED(SLAB_CACHE_DMA32) +LX_GDBPARSED(SLAB_STORE_USER) +LX_GDBPARSED(SLAB_PANIC) + /* Kernel Configs */ LX_CONFIG(CONFIG_GENERIC_CLOCKEVENTS) LX_CONFIG(CONFIG_GENERIC_CLOCKEVENTS_BROADCAST) @@ -136,3 +147,5 @@ if IS_BUILTIN(CONFIG_NUMA): LX_CONFIG(CONFIG_DEBUG_VIRTUAL) LX_CONFIG(CONFIG_STACKDEPOT) LX_CONFIG(CONFIG_PAGE_OWNER) +LX_CONFIG(CONFIG_SLUB_DEBUG) +LX_CONFIG(CONFIG_SLAB_FREELIST_HARDENED) diff --git a/scripts/gdb/linux/slab.py b/scripts/gdb/linux/slab.py new file mode 100644 index 000000000000..f012ba38c7d9 --- /dev/null +++ b/scripts/gdb/linux/slab.py @@ -0,0 +1,326 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Copyright (c) 2023 MediaTek Inc. +# +# Authors: +# Kuan-Ying Lee +# + +import gdb +import re +import traceback +from linux import lists, utils, stackdepot, constants, mm + +SLAB_RED_ZONE =3D constants.LX_SLAB_RED_ZONE +SLAB_POISON =3D constants.LX_SLAB_POISON +SLAB_KMALLOC =3D constants.LX_SLAB_KMALLOC +SLAB_HWCACHE_ALIGN =3D constants.LX_SLAB_HWCACHE_ALIGN +SLAB_CACHE_DMA =3D constants.LX_SLAB_CACHE_DMA +SLAB_CACHE_DMA32 =3D constants.LX_SLAB_CACHE_DMA32 +SLAB_STORE_USER =3D constants.LX_SLAB_STORE_USER +SLAB_PANIC =3D constants.LX_SLAB_PANIC + +OO_SHIFT =3D 16 +OO_MASK =3D (1 << OO_SHIFT) - 1 + +if constants.LX_CONFIG_SLUB_DEBUG: + slab_type =3D utils.CachedType("struct slab") + slab_ptr_type =3D slab_type.get_type().pointer() + kmem_cache_type =3D utils.CachedType("struct kmem_cache") + kmem_cache_ptr_type =3D kmem_cache_type.get_type().pointer() + freeptr_t =3D utils.CachedType("freeptr_t") + freeptr_t_ptr =3D freeptr_t.get_type().pointer() + + track_type =3D gdb.lookup_type('struct track') + track_alloc =3D int(gdb.parse_and_eval('TRACK_ALLOC')) + track_free =3D int(gdb.parse_and_eval('TRACK_FREE')) + +def slab_folio(slab): + return slab.cast(gdb.lookup_type("struct folio").pointer()) + +def slab_address(slab): + p_ops =3D mm.page_ops().ops + folio =3D slab_folio(slab) + return p_ops.folio_address(folio) + +def for_each_object(cache, addr, slab_objects): + p =3D addr + if cache['flags'] & SLAB_RED_ZONE: + p +=3D int(cache['red_left_pad']) + while p < addr + (slab_objects * cache['size']): + yield p + p =3D p + int(cache['size']) + +def get_info_end(cache): + if (cache['offset'] >=3D cache['inuse']): + return cache['inuse'] + gdb.lookup_type("void").pointer().sizeof + else: + return cache['inuse'] + +def get_orig_size(cache, obj): + if cache['flags'] & SLAB_STORE_USER and cache['flags'] & SLAB_KMALLOC: + p =3D mm.page_ops().ops.kasan_reset_tag(obj) + p +=3D get_info_end(cache) + p +=3D gdb.lookup_type('struct track').sizeof * 2 + p =3D p.cast(utils.get_uint_type().pointer()) + return p.dereference() + else: + return cache['object_size'] + +def get_track(cache, object_pointer, alloc): + p =3D object_pointer + get_info_end(cache) + p +=3D (alloc * track_type.sizeof) + return p + +def oo_objects(x): + return int(x['x']) & OO_MASK + +def oo_order(x): + return int(x['x']) >> OO_SHIFT + +def reciprocal_divide(a, R): + t =3D (a * int(R['m'])) >> 32 + return (t + ((a - t) >> int(R['sh1']))) >> int(R['sh2']) + +def __obj_to_index(cache, addr, obj): + return reciprocal_divide(int(mm.page_ops().ops.kasan_reset_tag(obj)) -= addr, cache['reciprocal_size']) + +def swab64(x): + result =3D (((x & 0x00000000000000ff) << 56) | \ + ((x & 0x000000000000ff00) << 40) | \ + ((x & 0x0000000000ff0000) << 24) | \ + ((x & 0x00000000ff000000) << 8) | \ + ((x & 0x000000ff00000000) >> 8) | \ + ((x & 0x0000ff0000000000) >> 24) | \ + ((x & 0x00ff000000000000) >> 40) | \ + ((x & 0xff00000000000000) >> 56)) + return result + +def freelist_ptr_decode(cache, ptr, ptr_addr): + if constants.LX_CONFIG_SLAB_FREELIST_HARDENED: + return ptr['v'] ^ cache['random'] ^ swab64(int(ptr_addr)) + else: + return ptr['v'] + +def get_freepointer(cache, obj): + obj =3D mm.page_ops().ops.kasan_reset_tag(obj) + ptr_addr =3D obj + cache['offset'] + p =3D ptr_addr.cast(freeptr_t_ptr).dereference() + return freelist_ptr_decode(cache, p, ptr_addr) + +def loc_exist(loc_track, addr, handle, waste): + for loc in loc_track: + if loc['addr'] =3D=3D addr and loc['handle'] =3D=3D handle and loc= ['waste'] =3D=3D waste: + return loc + return None + +def add_location(loc_track, cache, track, orig_size): + jiffies =3D gdb.parse_and_eval("jiffies_64") + age =3D jiffies - track['when'] + handle =3D 0 + waste =3D cache['object_size'] - int(orig_size) + pid =3D int(track['pid']) + cpuid =3D int(track['cpu']) + addr =3D track['addr'] + if constants.LX_CONFIG_STACKDEPOT: + handle =3D track['handle'] + + loc =3D loc_exist(loc_track, addr, handle, waste) + if loc: + loc['count'] +=3D 1 + if track['when']: + loc['sum_time'] +=3D age + loc['min_time'] =3D min(loc['min_time'], age) + loc['max_time'] =3D max(loc['max_time'], age) + loc['min_pid'] =3D min(loc['min_pid'], pid) + loc['max_pid'] =3D max(loc['max_pid'], pid) + loc['cpus'].add(cpuid) + else: + loc_track.append({ + 'count' : 1, + 'addr' : addr, + 'sum_time' : age, + 'min_time' : age, + 'max_time' : age, + 'min_pid' : pid, + 'max_pid' : pid, + 'handle' : handle, + 'waste' : waste, + 'cpus' : {cpuid} + } + ) + +def slabtrace(alloc, cache_name): + + def __fill_map(obj_map, cache, slab): + p =3D slab['freelist'] + addr =3D slab_address(slab) + while p !=3D gdb.Value(0): + index =3D __obj_to_index(cache, addr, p) + obj_map[index] =3D True # free objects + p =3D get_freepointer(cache, p) + + # process every slab page on the slab_list (partial and full list) + def process_slab(loc_track, slab_list, alloc, cache): + for slab in lists.list_for_each_entry(slab_list, slab_ptr_type, "s= lab_list"): + obj_map[:] =3D [False] * oo_objects(cache['oo']) + __fill_map(obj_map, cache, slab) + addr =3D slab_address(slab) + for object_pointer in for_each_object(cache, addr, slab['objec= ts']): + if obj_map[__obj_to_index(cache, addr, object_pointer)] = =3D=3D True: + continue + p =3D get_track(cache, object_pointer, alloc) + track =3D gdb.Value(p).cast(track_type.pointer()) + if alloc =3D=3D track_alloc: + size =3D get_orig_size(cache, object_pointer) + else: + size =3D cache['object_size'] + add_location(loc_track, cache, track, size) + continue + + slab_caches =3D gdb.parse_and_eval("slab_caches") + if mm.page_ops().ops.MAX_NUMNODES > 1: + nr_node_ids =3D int(gdb.parse_and_eval("nr_node_ids")) + else: + nr_node_ids =3D 1 + + target_cache =3D None + loc_track =3D [] + + for cache in lists.list_for_each_entry(slab_caches, kmem_cache_ptr_typ= e, 'list'): + if cache['name'].string() =3D=3D cache_name: + target_cache =3D cache + break + + obj_map =3D [False] * oo_objects(target_cache['oo']) + + if target_cache['flags'] & SLAB_STORE_USER: + for i in range(0, nr_node_ids): + cache_node =3D target_cache['node'][i] + if cache_node['nr_slabs']['counter'] =3D=3D 0: + continue + process_slab(loc_track, cache_node['partial'], alloc, target_c= ache) + process_slab(loc_track, cache_node['full'], alloc, target_cach= e) + else: + raise gdb.GdbError("SLAB_STORE_USER is not set in %s" % target_cac= he['name'].string()) + + for loc in sorted(loc_track, key=3Dlambda x:x['count'], reverse=3DTrue= ): + if loc['addr']: + addr =3D loc['addr'].cast(utils.get_ulong_type().pointer()) + gdb.write("%d %s" % (loc['count'], str(addr).split(' ')[-1])) + else: + gdb.write("%d " % loc['count']) + + if loc['waste']: + gdb.write(" waste=3D%d/%d" % (loc['count'] * loc['waste'], loc= ['waste'])) + + if loc['sum_time'] !=3D loc['min_time']: + gdb.write(" age=3D%d/%d/%d" % (loc['min_time'], loc['sum_time'= ]/loc['count'], loc['max_time'])) + else: + gdb.write(" age=3D%d" % loc['min_time']) + + if loc['min_pid'] !=3D loc['max_pid']: + gdb.write(" pid=3D%d-%d" % (loc['min_pid'], loc['max_pid'])) + else: + gdb.write(" pid=3D%d" % loc['min_pid']) + + if constants.LX_NR_CPUS > 1: + nr_cpu =3D gdb.parse_and_eval('__num_online_cpus')['counter'] + if nr_cpu > 1: + gdb.write(" cpus=3D") + for i in loc['cpus']: + gdb.write("%d," % i) + gdb.write("\n") + if constants.LX_CONFIG_STACKDEPOT: + if loc['handle']: + stackdepot.stack_depot_print(loc['handle']) + gdb.write("\n") + +def help(): + t =3D """Usage: lx-slabtrace --cache_name [cache_name] [Options] + Options: + --alloc + print information of allocation trace of the allocated objects + --free + print information of freeing trace of the allocated objects + Example: + lx-slabtrace --cache_name kmalloc-1k --alloc + lx-slabtrace --cache_name kmalloc-1k --free\n""" + gdb.write("Unrecognized command\n") + raise gdb.GdbError(t) + +class LxSlabTrace(gdb.Command): + """Show specific cache slabtrace""" + + def __init__(self): + super(LxSlabTrace, self).__init__("lx-slabtrace", gdb.COMMAND_DATA) + + def invoke(self, arg, from_tty): + if not constants.LX_CONFIG_SLUB_DEBUG: + raise gdb.GdbError("CONFIG_SLUB_DEBUG is not enabled") + + argv =3D gdb.string_to_argv(arg) + alloc =3D track_alloc # default show alloc_traces + + if len(argv) =3D=3D 3: + if argv[2] =3D=3D '--alloc': + alloc =3D track_alloc + elif argv[2] =3D=3D '--free': + alloc =3D track_free + else: + help() + if len(argv) >=3D 2 and argv[0] =3D=3D '--cache_name': + slabtrace(alloc, argv[1]) + else: + help() +LxSlabTrace() + +def slabinfo(): + nr_node_ids =3D None + + if not constants.LX_CONFIG_SLUB_DEBUG: + raise gdb.GdbError("CONFIG_SLUB_DEBUG is not enabled") + + def count_free(slab): + total_free =3D 0 + for slab in lists.list_for_each_entry(slab, slab_ptr_type, 'slab_l= ist'): + total_free +=3D int(slab['objects'] - slab['inuse']) + return total_free + + gdb.write("{:^18} | {:^20} | {:^12} | {:^12} | {:^8} | {:^11} | {:^13}= \n".format('Pointer', 'name', 'active_objs', 'num_objs', 'objsize', 'objper= slab', 'pagesperslab')) + gdb.write("{:-^18} | {:-^20} | {:-^12} | {:-^12} | {:-^8} | {:-^11} | = {:-^13}\n".format('', '', '', '', '', '', '')) + + slab_caches =3D gdb.parse_and_eval("slab_caches") + if mm.page_ops().ops.MAX_NUMNODES > 1: + nr_node_ids =3D int(gdb.parse_and_eval("nr_node_ids")) + else: + nr_node_ids =3D 1 + + for cache in lists.list_for_each_entry(slab_caches, kmem_cache_ptr_typ= e, 'list'): + nr_objs =3D 0 + nr_free =3D 0 + nr_slabs =3D 0 + for i in range(0, nr_node_ids): + cache_node =3D cache['node'][i] + try: + nr_slabs +=3D cache_node['nr_slabs']['counter'] + nr_objs =3D int(cache_node['total_objects']['counter']) + nr_free =3D count_free(cache_node['partial']) + except: + raise gdb.GdbError(traceback.format_exc()) + active_objs =3D nr_objs - nr_free + num_objs =3D nr_objs + active_slabs =3D nr_slabs + objects_per_slab =3D oo_objects(cache['oo']) + cache_order =3D oo_order(cache['oo']) + gdb.write("{:18s} | {:20.19s} | {:12} | {:12} | {:8} | {:11} | {:1= 3}\n".format(hex(cache), cache['name'].string(), str(active_objs), str(num_= objs), str(cache['size']), str(objects_per_slab), str(1 << cache_order))) + +class LxSlabInfo(gdb.Command): + """Show slabinfo""" + + def __init__(self): + super(LxSlabInfo, self).__init__("lx-slabinfo", gdb.COMMAND_DATA) + + def invoke(self, arg, from_tty): + slabinfo() +LxSlabInfo() diff --git a/scripts/gdb/vmlinux-gdb.py b/scripts/gdb/vmlinux-gdb.py index 89465f0de548..2526364f31fd 100644 --- a/scripts/gdb/vmlinux-gdb.py +++ b/scripts/gdb/vmlinux-gdb.py @@ -47,3 +47,4 @@ else: import linux.mm import linux.stackdepot import linux.page_owner + import linux.slab --=20 2.18.0 From nobody Thu Nov 14 05:36:23 2024 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 5FF50C04FE0 for ; Tue, 8 Aug 2023 16:18:13 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S232320AbjHHQRp (ORCPT ); Tue, 8 Aug 2023 12:17:45 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57610 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232249AbjHHQQC (ORCPT ); Tue, 8 Aug 2023 12:16:02 -0400 Received: from mailgw01.mediatek.com (unknown [60.244.123.138]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 67D48E62; Tue, 8 Aug 2023 08:48:07 -0700 (PDT) X-UUID: e0ad852e35c511ee9cb5633481061a41-20230808 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=mediatek.com; s=dk; h=Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:CC:To:From; bh=3bTI4ezWT0dRlseV1XH1auN5umDiuiT9sp0ElLkplnk=; b=qyrZII5nSYfDgdidaw0URf4ZofwG1EVXxfgB82I25iLr1fGG5VBErD7TvzBhg96A9B5+kb/ogGfTQ4OCbf6AoR+58kbRMDd7K0JiOR/BAjneLgRzr2OohbVyf9EijJM8VpITHX4ggUNOukzOB5mkO2uy5lmhSBaUbapqtcfdldM=; X-CID-P-RULE: Release_Ham X-CID-O-INFO: VERSION:1.1.31,REQID:7ff864a1-1a3f-46a3-8abc-b4524e19721c,IP:0,U RL:0,TC:0,Content:0,EDM:0,RT:0,SF:95,FILE:0,BULK:0,RULE:Release_Ham,ACTION :release,TS:95 X-CID-INFO: VERSION:1.1.31,REQID:7ff864a1-1a3f-46a3-8abc-b4524e19721c,IP:0,URL :0,TC:0,Content:0,EDM:0,RT:0,SF:95,FILE:0,BULK:0,RULE:Spam_GS981B3D,ACTION :quarantine,TS:95 X-CID-META: VersionHash:0ad78a4,CLOUDID:59b6f042-d291-4e62-b539-43d7d78362ba,B ulkID:230808163051S0PE58AX,BulkQuantity:0,Recheck:0,SF:38|29|28|17|19|48,T C:nil,Content:0,EDM:-3,IP:nil,URL:11|1,File:nil,Bulk:nil,QS:nil,BEC:nil,CO L:0,OSI:0,OSA:0,AV:0,LES:1,SPR:NO,DKR:0,DKP:0,BRR:0,BRE:0 X-CID-BVR: 0 X-CID-BAS: 0,_,0,_ X-CID-FACTOR: TF_CID_SPAM_SNR,TF_CID_SPAM_SDM,TF_CID_SPAM_ASC,TF_CID_SPAM_FAS, TF_CID_SPAM_FSD,TF_CID_SPAM_ULN X-UUID: e0ad852e35c511ee9cb5633481061a41-20230808 Received: from mtkmbs14n1.mediatek.inc [(172.21.101.75)] by mailgw01.mediatek.com (envelope-from ) (Generic MTA with TLSv1.2 ECDHE-RSA-AES256-GCM-SHA384 256/256) with ESMTP id 996264844; Tue, 08 Aug 2023 16:30:48 +0800 Received: from mtkmbs13n2.mediatek.inc (172.21.101.108) by mtkmbs10n2.mediatek.inc (172.21.101.183) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.1118.26; Tue, 8 Aug 2023 16:30:47 +0800 Received: from mtksdccf07.mediatek.inc (172.21.84.99) by mtkmbs13n2.mediatek.inc (172.21.101.73) with Microsoft SMTP Server id 15.2.1118.26 via Frontend Transport; Tue, 8 Aug 2023 16:30:47 +0800 From: Kuan-Ying Lee To: Jan Kiszka , Kieran Bingham , Matthias Brugger , AngeloGioacchino Del Regno CC: , , , , , , , Kuan-Ying Lee , , , Subject: [PATCH v2 8/8] scripts/gdb/vmalloc: add vmallocinfo support Date: Tue, 8 Aug 2023 16:30:18 +0800 Message-ID: <20230808083020.22254-9-Kuan-Ying.Lee@mediatek.com> X-Mailer: git-send-email 2.18.0 In-Reply-To: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> References: <20230808083020.22254-1-Kuan-Ying.Lee@mediatek.com> MIME-Version: 1.0 X-MTK: N Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This GDB script shows the vmallocinfo for user to analyze the vmalloc memory usage. Example output: 0xffff800008000000-0xffff800008009000 36864 pages= =3D8 vmalloc 0xffff800008009000-0xffff80000800b000 8192 phys= =3D0x8020000 ioremap 0xffff80000800b000-0xffff80000800d000 8192 pages=3D1 vmalloc 0xffff80000800d000-0xffff80000800f000 8192 pa= ges=3D1 vmalloc 0xffff800008010000-0xffff80000ad30000 47316992 phys=3D0= x40210000 vmap 0xffff80000ad30000-0xffff80000c1c0000 21561344 phys=3D0= x42f30000 vmap 0xffff80000c1c0000-0xffff80000c370000 1769472 phys=3D0= x443c0000 vmap 0xffff80000c370000-0xffff80000de90000 28442624 phys=3D0= x44570000 vmap 0xffff80000de90000-0xffff80000f4c1000 23269376 phys=3D0= x46090000 vmap 0xffff80000f4c1000-0xffff80000f4c3000 8192 p= ages=3D1 vmalloc 0xffff80000f4c3000-0xffff80000f4c5000 8192 p= ages=3D1 vmalloc 0xffff80000f4c5000-0xffff80000f4c7000 8192 p= ages=3D1 vmalloc Signed-off-by: Kuan-Ying Lee --- scripts/gdb/linux/constants.py.in | 8 +++++ scripts/gdb/linux/vmalloc.py | 56 +++++++++++++++++++++++++++++++ scripts/gdb/vmlinux-gdb.py | 1 + 3 files changed, 65 insertions(+) create mode 100644 scripts/gdb/linux/vmalloc.py diff --git a/scripts/gdb/linux/constants.py.in b/scripts/gdb/linux/constant= s.py.in index 03fa6d2cfe01..e3517d4ab8ec 100644 --- a/scripts/gdb/linux/constants.py.in +++ b/scripts/gdb/linux/constants.py.in @@ -22,6 +22,7 @@ #include #include #include +#include =20 /* We need to stringify expanded macros so that they can be parsed */ =20 @@ -91,6 +92,13 @@ LX_GDBPARSED(RADIX_TREE_MAP_SIZE) LX_GDBPARSED(RADIX_TREE_MAP_SHIFT) LX_GDBPARSED(RADIX_TREE_MAP_MASK) =20 +/* linux/vmalloc.h */ +LX_VALUE(VM_IOREMAP) +LX_VALUE(VM_ALLOC) +LX_VALUE(VM_MAP) +LX_VALUE(VM_USERMAP) +LX_VALUE(VM_DMA_COHERENT) + /* linux/page_ext.h */ if IS_BUILTIN(CONFIG_PAGE_OWNER): LX_GDBPARSED(PAGE_EXT_OWNER) diff --git a/scripts/gdb/linux/vmalloc.py b/scripts/gdb/linux/vmalloc.py new file mode 100644 index 000000000000..48e4a4fae7bb --- /dev/null +++ b/scripts/gdb/linux/vmalloc.py @@ -0,0 +1,56 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Copyright (c) 2023 MediaTek Inc. +# +# Authors: +# Kuan-Ying Lee +# + +import gdb +import re +from linux import lists, utils, stackdepot, constants, mm + +vmap_area_type =3D utils.CachedType('struct vmap_area') +vmap_area_ptr_type =3D vmap_area_type.get_type().pointer() + +def is_vmalloc_addr(x): + pg_ops =3D mm.page_ops().ops + addr =3D pg_ops.kasan_reset_tag(x) + return addr >=3D pg_ops.VMALLOC_START and addr < pg_ops.VMALLOC_END + +class LxVmallocInfo(gdb.Command): + """Show vmallocinfo""" + + def __init__(self): + super(LxVmallocInfo, self).__init__("lx-vmallocinfo", gdb.COMMAND_= DATA) + + def invoke(self, arg, from_tty): + vmap_area_list =3D gdb.parse_and_eval('vmap_area_list') + for vmap_area in lists.list_for_each_entry(vmap_area_list, vmap_ar= ea_ptr_type, "list"): + if not vmap_area['vm']: + gdb.write("0x%x-0x%x %10d vm_map_ram\n" % (vmap_area['va_s= tart'], vmap_area['va_end'], + vmap_area['va_end'] - vmap_area['va_start'])) + continue + v =3D vmap_area['vm'] + gdb.write("0x%x-0x%x %10d" % (v['addr'], v['addr'] + v['size']= , v['size'])) + if v['caller']: + gdb.write(" %s" % str(v['caller']).split(' ')[-1]) + if v['nr_pages']: + gdb.write(" pages=3D%d" % v['nr_pages']) + if v['phys_addr']: + gdb.write(" phys=3D0x%x" % v['phys_addr']) + if v['flags'] & constants.LX_VM_IOREMAP: + gdb.write(" ioremap") + if v['flags'] & constants.LX_VM_ALLOC: + gdb.write(" vmalloc") + if v['flags'] & constants.LX_VM_MAP: + gdb.write(" vmap") + if v['flags'] & constants.LX_VM_USERMAP: + gdb.write(" user") + if v['flags'] & constants.LX_VM_DMA_COHERENT: + gdb.write(" dma-coherent") + if is_vmalloc_addr(v['pages']): + gdb.write(" vpages") + gdb.write("\n") + +LxVmallocInfo() diff --git a/scripts/gdb/vmlinux-gdb.py b/scripts/gdb/vmlinux-gdb.py index 2526364f31fd..fc53cdf286f1 100644 --- a/scripts/gdb/vmlinux-gdb.py +++ b/scripts/gdb/vmlinux-gdb.py @@ -48,3 +48,4 @@ else: import linux.stackdepot import linux.page_owner import linux.slab + import linux.vmalloc --=20 2.18.0