aboutsummaryrefslogtreecommitdiffstats
path: root/fs/gfs2/rgrp.h
blob: b4106ddaaa98219362c23addea091d2ea582d53f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
 * Copyright (C) Sistina Software, Inc.  1997-2003 All rights reserved.
 * Copyright (C) 2004-2008 Red Hat, Inc.  All rights reserved.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU General Public License version 2.
 */

#ifndef __RGRP_DOT_H__
#define __RGRP_DOT_H__

struct gfs2_rgrpd;
struct gfs2_sbd;
struct gfs2_holder;

extern void gfs2_rgrp_verify(struct gfs2_rgrpd *rgd);

struct gfs2_rgrpd *gfs2_blk2rgrpd(struct gfs2_sbd *sdp, u64 blk);
struct gfs2_rgrpd *gfs2_rgrpd_get_first(struct gfs2_sbd *sdp);
struct gfs2_rgrpd *gfs2_rgrpd_get_next(struct gfs2_rgrpd *rgd);

extern void gfs2_clear_rgrpd(struct gfs2_sbd *sdp);
extern int gfs2_rindex_hold(struct gfs2_sbd *sdp, struct gfs2_holder *ri_gh);

extern int gfs2_rgrp_bh_get(struct gfs2_rgrpd *rgd);
extern void gfs2_rgrp_bh_hold(struct gfs2_rgrpd *rgd);
extern void gfs2_rgrp_bh_put(struct gfs2_rgrpd *rgd);

extern void gfs2_rgrp_repolish_clones(struct gfs2_rgrpd *rgd);

extern struct gfs2_alloc *gfs2_alloc_get(struct gfs2_inode *ip);
static inline void gfs2_alloc_put(struct gfs2_inode *ip)
{
	BUG_ON(ip->i_alloc == NULL);
	kfree(ip->i_alloc);
	ip->i_alloc = NULL;
}

extern int gfs2_inplace_reserve_i(struct gfs2_inode *ip, char *file,
				  unsigned int line);
#define gfs2_inplace_reserve(ip) \
gfs2_inplace_reserve_i((ip), __FILE__, __LINE__)

extern void gfs2_inplace_release(struct gfs2_inode *ip);

extern int gfs2_alloc_block(struct gfs2_inode *ip, u64 *bn, unsigned int *n);
extern int gfs2_alloc_di(struct gfs2_inode *ip, u64 *bn, u64 *generation);

extern void gfs2_free_data(struct gfs2_inode *ip, u64 bstart, u32 blen);
extern void gfs2_free_meta(struct gfs2_inode *ip, u64 bstart, u32 blen);
extern void gfs2_free_di(struct gfs2_rgrpd *rgd, struct gfs2_inode *ip);
extern void gfs2_unlink_di(struct inode *inode);
extern int gfs2_check_blk_type(struct gfs2_sbd *sdp, u64 no_addr,
			       unsigned int type);

struct gfs2_rgrp_list {
	unsigned int rl_rgrps;
	unsigned int rl_space;
	struct gfs2_rgrpd **rl_rgd;
	struct gfs2_holder *rl_ghs;
};

extern void gfs2_rlist_add(struct gfs2_sbd *sdp, struct gfs2_rgrp_list *rlist,
			   u64 block);
extern void gfs2_rlist_alloc(struct gfs2_rgrp_list *rlist, unsigned int state);
extern void gfs2_rlist_free(struct gfs2_rgrp_list *rlist);
extern u64 gfs2_ri_total(struct gfs2_sbd *sdp);
extern int gfs2_rgrp_dump(struct seq_file *seq, const struct gfs2_glock *gl);

#endif /* __RGRP_DOT_H__ */
9'>559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
/* Copyright 2024 Joshua Bakita
 * SPDX-License-Identifier: MIT
 *
 * File outline:
 * - Runlist, preemption, and channel control (FIFO)
 * - Basic GPU information (MC)
 * - Detailed GPU information (PTOP, FUSE, and CE)
 * - PRAMIN, BAR1/2, and page table status
 * - Helper functions for nvdebug
 *
 * This function should not depend on any Linux-internal headers, and may be
 * included outside of nvdebug.
 */
#include <linux/types.h>

// Fully defined in include/nvgpu/gk20a.h. We only pass around pointers to
// this, so declare as incomplete type to avoid pulling in the nvgpu headers.
struct gk20a;

/* Runlist Channel
  A timeslice group (TSG) is composed of channels. Each channel is a FIFO queue
  of GPU commands. These commands are typically queued from userspace.

  Prior to Volta, channels could also exist independent of a TSG. These are
  called "bare channels" in the Jetson nvgpu driver.

  `INST_PTR` points to a GPU Instance Block which contains FIFO states, virtual
  address space configuration for this context, and a pointer to the page
  tables. All channels in a TSG point to the same GPU Instance Block (?).

  "RUNQUEUE_SELECTOR determines to which runqueue the channel belongs, and
  thereby which PBDMA will run the channel.  Increasing values select
  increasingly numbered PBDMA IDs serving the runlist.  If the selector value
  exceeds the number of PBDMAs on the runlist, the hardware will silently
  reassign the channel to run on the first PBDMA as though RUNQUEUE_SELECTOR had
  been set to 0.  (In current hardware, this is used by SCG on the graphics
  runlist only to determine which FE pipe should service a given channel.  A
  value of 0 targets the first FE pipe, which can process all FE driven engines:
  Graphics, Compute, Inline2Memory, and TwoD.  A value of 1 targets the second
  FE pipe, which can only process Compute work.  Note that GRCE work is allowed
  on either runqueue." (NVIDIA) Note that it appears runqueue 1 is the default
  for CUDA work on the Jetson Xavier.

  ENTRY_TYPE (T)        : type of this entry: ENTRY_TYPE_CHAN
  CHID (ID)             : identifier of the channel to run (overlays ENTRY_ID)
  RUNQUEUE_SELECTOR (Q) : selects which PBDMA should run this channel if
                          more than one PBDMA is supported by the runlist,
                          additionally, "A value of 0 targets the first FE
                          pipe, which can process all FE driven engines:
                          Graphics, Compute, Inline2Memory, and TwoD.  A value
                          of 1 targets the second FE pipe, which can only
                          process Compute work.  Note that GRCE work is allowed
                          on either runqueue.)"

  INST_PTR_LO           : lower 20 bits of the 4k-aligned instance block pointer
  INST_PTR_HI           : upper 32 bit of instance block pointer
  INST_TARGET (TGI)     : aperture of the instance block

  USERD_PTR_LO          : upper 24 bits of the low 32 bits, of the 512-byte-aligned USERD pointer
  USERD_PTR_HI          : upper 32 bits of USERD pointer
  USERD_TARGET (TGU)    : aperture of the USERD data structure

  Channels were around since at least Fermi, but were rearranged with Volta to
  add a USERD pointer, a longer INST pointer, and a runqueue selector flag.
*/
enum ENTRY_TYPE {ENTRY_TYPE_CHAN = 0, ENTRY_TYPE_TSG = 1};
enum INST_TARGET {TARGET_VID_MEM = 0, TARGET_SYS_MEM_COHERENT = 2, TARGET_SYS_MEM_NONCOHERENT = 3};
static inline const char *target_to_text(enum INST_TARGET t) {
	switch (t) {
		case TARGET_VID_MEM:
			return "VID_MEM";
		case TARGET_SYS_MEM_COHERENT:
			return "SYS_MEM_COHERENT";
		case TARGET_SYS_MEM_NONCOHERENT:
			return "SYS_MEM_NONCOHERENT";
		default:
			return "INVALID";
	}
}

// Support: Volta, Ampere, Turing
struct gv100_runlist_chan {
// 0:63
	enum ENTRY_TYPE entry_type:1;
	uint32_t runqueue_selector:1;
	 uint32_t padding:2;
	enum INST_TARGET inst_target:2;
	 uint32_t padding2:2;
	uint32_t userd_ptr_lo:24;
	uint32_t userd_ptr_hi:32;
// 64:128
	uint32_t chid:12;
	uint32_t inst_ptr_lo:20;
	uint32_t inst_ptr_hi:32;
} __attribute__((packed));

// Support: Fermi, Kepler*, Maxwell, Pascal
// *In Kepler, inst fields may be unpopulated?
struct gm107_runlist_chan {
	uint32_t chid:12;
	 uint32_t padding0:1;
	enum ENTRY_TYPE entry_type:1;
	 uint32_t padding1:18;
	uint32_t inst_ptr_lo:20;
	enum INST_TARGET inst_target:2;  // Totally guessing on this
	 uint32_t padding2:10;
} __attribute__((packed));

#define gk110_runlist_chan gm107_runlist_chan

/* Runlist TSG (TimeSlice Group)
  The runlist is composed of timeslice groups (TSG). Each TSG corresponds
  to a single virtual address space on the GPU and contains `TSG_LENGTH`
  channels. These channels and virtual address space are accessible to the GPU
  host unit for use until the timeslice expires or a TSG switch is forcibly
  initiated via a write to `NV_PFIFO_PREEMPT`.

  timeslice = (TSG_TIMESLICE_TIMEOUT << TSG_TIMESLICE_SCALE) * 1024 nanoseconds

  ENTRY_TYPE (T)      : type of this entry: ENTRY_TYPE_TSG
  TIMESLICE_SCALE     : scale factor for the TSG's timeslice
  TIMESLICE_TIMEOUT   : timeout amount for the TSG's timeslice
  TSG_LENGTH          : number of channels that are part of this timeslice group
  TSGID               : identifier of the Timeslice group (overlays ENTRY_ID)

  TSGs appear to have been introduced with Kepler and stayed the same until
  they were rearranged at the time of channel rearrangement to support longer
  GPU instance addresses with Volta.

  According to nvgpu, "timeslice is measured with PTIMER [which may be] lower
  than 1GHz."
*/

// Support: Volta, Turing*, Ampere*
// *These treat bits 4:11 (8 bits) as GFID (unused)
struct gv100_runlist_tsg {
// 0:63
	enum ENTRY_TYPE entry_type:1;
	 uint64_t padding:15;
	uint32_t timeslice_scale:4;
	 uint64_t padding2:4;
	uint32_t timeslice_timeout:8;
	uint32_t tsg_length:8;
	 uint32_t padding3:24;
// 64:128
	uint32_t tsgid:12;
	 uint64_t padding4:52;
} __attribute__((packed));
#define MAX_TSGID (1 << 12)

// Support: Kepler (v2?), Maxwell, Pascal
// Same fields as Volta except tsg_length is 6 bits rather than 8
// Last 32 bits appear to contain an undocumented inst ptr
struct gk110_runlist_tsg {
	uint32_t tsgid:12;
	 uint32_t padding0:1;
	enum ENTRY_TYPE entry_type:1;
	uint32_t timeslice_scale:4;
	uint32_t timeslice_timeout:8;
	uint32_t tsg_length:6;
	 uint32_t padding1:32;
} __attribute__((packed));


enum PREEMPT_TYPE {PREEMPT_TYPE_CHANNEL = 0, PREEMPT_TYPE_TSG = 1};

/* Preempt a TSG or Channel by ID
  ID/CHID     : Id of TSG or channel to preempt
  IS_PENDING  : Is a context switch pending? (read-only)
  TYPE        : PREEMPT_TYPE_CHANNEL or PREEMPT_TYPE_TSG

  Support: Kepler, Maxwell, Pascal, Volta, Turing
*/
#define NV_PFIFO_PREEMPT 0x00002634
typedef union {
	struct {
		uint32_t id:12;
		 uint32_t padding:8;
		bool is_pending:1;
		 uint32_t padding2:3;
		enum PREEMPT_TYPE type:2;
		 uint32_t padding3:6;
	} __attribute__((packed));
	uint32_t raw;
} pfifo_preempt_t;

/*
  "Initiate a preempt of the engine by writing the bit associated with its
  runlist to NV_PFIFO_RUNLIST_PREEMPT...  Do not poll NV_PFIFO_RUNLIST_PREEMPT
  for the preempt to complete."

  Useful for preempting multiple runlists at once.

  Appears to trigger an interrupt or some other side-effect on the Jetson
  Xavier, as the built-in nvgpu driver seems to be disturbed by writing to this.

  To select the runlist dynamically, use the BIT(nr) kernel macro.
  Example:
    runlist_preempt_t rl_preempt;
    rl_preempt.raw = nvdebug_readl(g, NV_PFIFO_RUNLIST_PREEMPT);
    rl_preempt.raw |= BIT(nr);
    nvdebug_writel(g, NV_PFIFO_RUNLIST_PREEMPT, rl_preempt.raw);

  Support: Volta, Turing
*/
#define NV_PFIFO_RUNLIST_PREEMPT 0x00002638
typedef union {
	struct {
		bool runlist_0:1;
		bool runlist_1:1;
		bool runlist_2:1;
		bool runlist_3:1;
		bool runlist_4:1;
		bool runlist_5:1;
		bool runlist_6:1;
		bool runlist_7:1;
		bool runlist_8:1;
		bool runlist_9:1;
		bool runlist_10:1;
		bool runlist_11:1;
		bool runlist_12:1;
		bool runlist_13:1;
		 uint32_t padding:18;
	} __attribute__((packed));
	uint32_t raw;
} runlist_preempt_t;

/* Additional information on preempting from NVIDIA's driver (commit b1d0d8ece)
 * "From h/w team
 * Engine save can be blocked by eng  stalling interrupts.
 * FIFO interrupts shouldn’t block an engine save from
 * finishing, but could block FIFO from reporting preempt done.
 * No immediate reason to reset the engine if FIFO interrupt is
 * pending.
 * The hub, priv_ring, and ltc interrupts could block context
 * switch (or memory), but doesn’t necessarily have to.
 * For Hub interrupts they just report access counters and page
 * faults. Neither of these necessarily block context switch
 * or preemption, but they could.
 * For example a page fault for graphics would prevent graphics
 * from saving out. An access counter interrupt is a
 * notification and has no effect.
 * SW should handle page faults though for preempt to complete.
 * PRI interrupt (due to a failed PRI transaction) will result
 * in ctxsw failure reported to HOST.
 * LTC interrupts are generally ECC related and if so,
 * certainly don’t block preemption/ctxsw but they could.
 * Bus interrupts shouldn’t have anything to do with preemption
 * state as they are part of the Host EXT pipe, though they may
 * exhibit a symptom that indicates that GPU is in a bad state.
 * To be completely fair, when an engine is preempting SW
 * really should just handle other interrupts as they come in.
 * It’s generally bad to just poll and wait on a preempt
 * to complete since there are many things in the GPU which may
 * cause a system to hang/stop responding."
 */

/* Runlist Metadata (up through Volta)
  "Software specifies the GPU contexts that hardware should "run" by writing a
  list of entries (known as a "runlist") to a 4k-aligned area of memory (beginning
  at NV_PFIFO_RUNLIST_BASE), and by notifying Host that a new list is available
  (by writing to NV_PFIFO_RUNLIST).

  Submission of a new runlist causes Host to expire the timeslice of all work
  scheduled by the previous runlist, allowing it to schedule the channels present
  in the new runlist once they are fetched. SW can check the status of the runlist
  by polling NV_PFIFO_ENG_RUNLIST_PENDING. (see dev_fifo.ref NV_PFIFO_RUNLIST for
  a full description of the runlist submit mechanism).

  Runlists can be stored in system memory or video memory (as specified by
  NV_PFIFO_RUNLIST_BASE_TARGET). If a runlist is stored in video memory, software
  will have to execute flush or read the last entry written before submitting the
  runlist to Host to guarantee coherency." (volta/dev_ram.ref.txt)

  We only document the *_PFIFO_ENG_RUNLIST_*(i) read-only registers here (where
  i is a runlist index). Runlists are configured via the seperate, writable
  *_PFIFO_RUNLIST_* register; see open-gpu-doc for more.

  LEN         : Number of entries in runlist
  IS_PENDING  : Is runlist committed?
  PTR         : Pointer to start of 4k-aligned runlist (upper 28 of 40 bits)
  TARGET      : Aperture of runlist (video or system memory)

  Support: Fermi*, Kepler, Maxwell, Pascal, Volta
  *Fermi may expose this information 8 bytes earlier, starting at 0x227C?
*/
#define NV_PFIFO_RUNLIST_BASE_GF100 0x00002270 // Write-only
#define NV_PFIFO_ENG_RUNLIST_BASE_GF100(i) (0x00002280+(i)*8) // Read-only
typedef union {
	struct {
		// NV_PFIFO_ENG_RUNLIST_BASE_* fields
		uint32_t ptr:28;
		enum INST_TARGET target:2;
		 uint32_t :2;
		// NV_PFIFO_ENG_RUNLIST_* fields
		uint16_t len:16;
		 uint32_t :4;
		bool is_pending:1; // Read-only from NV_PFIFO_ENG_RUNLIST...
		 uint32_t :11;
	} __attribute__((packed));
	struct {
		// NV_PFIFO_RUNLIST_* fields that differ from NV_PFIFO_ENG_RUNLIST_*
		 uint64_t :52;
		uint32_t id:4; // Write-only to NV_PFIFO_RUNLIST...
		 uint32_t :8;
	} __attribute__((packed));
	uint64_t raw;
} eng_runlist_gf100_t;

/*
  Starting with Turing, the seperate registers for reading and writing runlist
  configuration were dropped in favor of read/write indexed registers. As part
  of this, the layout was modified to allow for larger runlist pointers (upper
  52 of 64 bits).

  Support: Turing, Ampere, Lovelace?, Hopper?
*/
// Support: Turing
#define NV_PFIFO_RUNLIST_BASE_TU102(i) (0x00002B00+(i)*16) // Read/write
#define NV_PFIFO_RUNLIST_SUBMIT_TU102(i) (0x00002B08+(i)*16) // Read/write
// Derived absolute maximum number of runlists
#define MAX_RUNLISTS_TU102 80 // On Turing; another register is at 0x00003000
#define MAX_RUNLISTS_GF100 34 // On Volta-; another register is at 0x00002390
typedef union {
	struct {
		enum INST_TARGET target:2;
		 uint32_t padding:10;
		uint64_t ptr:28;
		 uint32_t padding2:24;
	} __attribute__((packed));
	uint64_t raw;
} runlist_base_tu102_t;

typedef union {
	struct {
		uint16_t len:16;
		uint16_t offset:16;
		uint32_t preempted_tsgid:14;
		bool valid_preempted_tsgid:1;
		bool is_pending:1;
		uint32_t preempted_offset:16;
	} __attribute__((packed));
	uint64_t raw;
} runlist_submit_tu102_t;

enum CHANNEL_STATUS {
	CHANNEL_STATUS_IDLE = 0,
	CHANNEL_STATUS_PENDING = 1,
	CHANNEL_STATUS_PENDING_CTX_RELOAD = 2,
	CHANNEL_STATUS_PENDING_ACQUIRE = 3,
	CHANNEL_STATUS_PENDING_ACQ_CTX_RELOAD = 4,
	CHANNEL_STATUS_ON_PBDMA = 5,
	CHANNEL_STATUS_ON_PBDMA_AND_ENG = 6,
	CHANNEL_STATUS_ON_ENG = 7,
	CHANNEL_STATUS_ON_ENG_PENDING_ACQUIRE = 8,
	CHANNEL_STATUS_ON_ENG_PENDING = 9,
	CHANNEL_STATUS_ON_PBDMA_CTX_RELOAD = 10,
	CHANNEL_STATUS_ON_PBDMA_AND_ENG_CTX_RELOAD = 11,
	CHANNEL_STATUS_ON_ENG_CTX_RELOAD = 12,
	CHANNEL_STATUS_ON_ENG_PENDING_CTX_RELOAD = 13,
	CHANNEL_STATUS_ON_ENG_PENDING_ACQ_CTX_RELOAD = 14,
};

/* Programmable Channel Control System RAM (PCCSR)

  512-entry array of channel control and status data structures.

  === Read/Write Fields ===
  INST_PTR             : Top 28 of 40 bits of page-aligned channel instance block.
                         Instance Block = (uint64_t)inst_ptr << 12.
  INST_TARGET          : Aperture of INST_PTR.
  INST_BIND            : Is the channel instance bound?
  NEXT                 : Is this the next channel to be scheduled in the runlist?

  === Read-Only Fields ===
  ENABLE               : Is this channel enabled? (Disabled channels are skipped
                         over by the runlist scheduler.)
  PBDMA_FAULTED^       : [UNKNOWN]
  ENG_FAULTED^         : [UNKNOWN]
  STATUS               : Status of this channel in regards to hardware. See enum
                         CHANNEL_STATUS.
  BUSY                 : [UNKNOWN]
  ^Field can be reset with a non-zero write.

  === Write-Only Fields ===
  FORCE_CTX_RELOAD     : [UNKNOWN]
  ENABLE_SET           : Enables the channel upon non-zero write.
  ENABLE_CLEAR         : Disables the channel upon non-zero write.
  FORCE_PBDMA_FAULTED* : [UNKNOWN]
  FORCE_ENG_FAULTED*   : [UNKNOWN]
  *Field only available on Turing.

  Support: Fermi, Maxwell, Pascal, Volta, Turing
*/
#define NV_PCCSR_CHANNEL_INST(i) (0x00800000+(i)*8)
#define MAX_CHID 512
typedef union {
	struct {
// 0:31
		uint32_t inst_ptr:28;
		enum INST_TARGET inst_target:2;
		 uint32_t :1;
		bool inst_bind:1;
// 32:63
		bool enable:1;
		bool next:1;
		 uint32_t :6;
		bool force_ctx_reload:1;
		 uint32_t :1;
		bool enable_set:1;
		bool enable_clear:1;
		 uint32_t :8;
		bool force_pbdma_faulted:1;
		bool force_eng_faulted:1;
		bool pbdma_faulted:1;
		bool eng_faulted:1;
		enum CHANNEL_STATUS status:4;
		bool busy:1;
		 uint32_t :3;
	} __attribute__((packed));
	uint64_t raw;
} channel_ctrl_t;

/* Control word for runlist enable/disable.

  RUNLIST_N           : Is runlist n disabled? (1 == disabled, 0 == enabled)

  To select the runlist dynamically, use the BIT(nr) kernel macro.
  Disabling example:
    runlist_disable_t rl_disable;
    rl_disable.raw = nvdebug_readl(g, NV_PFIFO_SCHED_DISABLE);
    rl_disable.raw |= BIT(nr);
    nvdebug_writel(g, NV_PFIFO_SCHED_DISABLE, rl_disable.raw);
  Enabling example:
    runlist_disable_t rl_disable;
    rl_disable.raw = nvdebug_readl(g, NV_PFIFO_SCHED_DISABLE);
    rl_disable.raw &= ~BIT(nr);
    nvdebug_writel(g, NV_PFIFO_SCHED_DISABLE, rl_disable.raw);

  Support: Fermi, Kepler, Maxwell, Pascal, Volta, Turing
*/
#define NV_PFIFO_SCHED_DISABLE 0x00002630
typedef union {
	struct {
		bool runlist_0:1;
		bool runlist_1:1;
		bool runlist_2:1;
		bool runlist_3:1;
		bool runlist_4:1;
		bool runlist_5:1;
		bool runlist_6:1;
		bool runlist_7:1;
		bool runlist_8:1;
		bool runlist_9:1;
		bool runlist_10:1;
		 uint32_t padding:21;
	} __attribute__((packed));
	uint32_t raw;
} runlist_disable_t;

/* Read GPU descriptors from the Master Controller (MC)

  MINOR_REVISION  : Legacy (only used with Celvin in Nouveau)
  MAJOR_REVISION  : Legacy (only used with Celvin in Nouveau)
  IMPLEMENTATION  : Which implementation of the GPU architecture
  ARCHITECTURE    : Which GPU architecture

  CHIP_ID = IMPLEMENTATION + ARCHITECTURE << 4
  CHIP_ID         : Unique ID of all chips since Kelvin

  Support: Kelvin, Rankline, Curie, Tesla, Fermi, Kepler, Maxwell, Pascal,
           Volta, Turing, Ampere
*/
#define NV_MC_BOOT_0 0x00000000
#define NV_CHIP_ID_GP106 0x136 // Discrete GeForce GTX 1060
#define NV_CHIP_ID_GV11B 0x15B // Jetson Xavier embedded GPU

#define NV_CHIP_ID_KEPLER 0x0E0
#define NV_CHIP_ID_MAXWELL 0x120
#define NV_CHIP_ID_PASCAL 0x130
#define NV_CHIP_ID_VOLTA 0x140
#define NV_CHIP_ID_VOLTA_INTEGRATED 0x150
#define NV_CHIP_ID_TURING 0x160
#define NV_CHIP_ID_AMPERE 0x170
#define NV_CHIP_ID_HOPPER 0x180
#define NV_CHIP_ID_ADA 0x190

inline static const char* ARCH2NAME(uint32_t arch) {
	switch (arch) {
	case 0x01:
		return "Celsius";
	case 0x02:
		return "Kelvin";
	case 0x03:
		return "Rankline";
	case 0x04:
	case 0x06: // 0x06 is (nForce 6XX integrated only)
		return "Curie";
	// 0x07 is unused/skipped
	case 0x05: // First Tesla card was released before the nForce 6XX
	case 0x08:
	case 0x09:
	case 0x0A:
		return "Tesla";
	// 0x0B is unused/skipped
	case 0x0C:
	case 0x0D:
		return "Fermi";
	case 0x0E:
	case 0x0F:
	case 0x11:
		return "Kepler";
	case 0x12:
		return "Maxwell";
	case 0x13:
		return "Pascal";
	case 0x14:
	case 0x15: // Volta integrated
		return "Volta";
	case 0x16:
		return "Turing";
	case 0x17:
		return "Ampere";
	case 0x18:
		return "Hopper";
	case 0x19:
		return "Ada Lovelace";
	case 0x20:
		return "Blackwell (?)";
	default:
		if (arch < 0x19)
			return "[unknown historical architecture]";
		else
			return "[future]";
	}
}

typedef union {
	// Fields as defined in the NVIDIA reference
	struct {
		uint32_t minor_revision:4;
		uint32_t major_revision:4;
		 uint32_t reserved:4;
		 uint32_t padding0:8;
		uint32_t implementation:4;
		uint32_t architecture:5;
		 uint32_t padding1:3;
	} __attribute__((packed));
	uint32_t raw;
	// Arch << 4 + impl is also often used
	struct {
		 uint32_t padding2:20;
		uint32_t chip_id:9;
		 uint32_t padding3:3;
	} __attribute__((packed));
} mc_boot_0_t;

/* GPU engine information and control register offsets (GPU TOPology)
  Each engine is described by one or more entries (terminated by an entry with
  the `has_next_entry` flag unset) in the fixed-size PTOP_DEVICE_INFO table. A
  typical device, such as the graphics/compute engine and any copy engines, are
  described by three entries, one of each type.

  The PTOP_DEVICE_INFO table is sparsely populated (entries of type
  INFO_TYPE_NOT_VALID may be intermingled with valid entries), so any traversal
  code should check all NV_PTOP_DEVICE_INFO__SIZE_1 entries and not terminate
  upon reaching the first entry of INFO_TYPE_NOT_VALID.

  The fields for the Ampere version of the GPU are a strict subset of those for
  the earlier versions.

  INFO_TYPE          : Is this a DATA, ENUM, or ENGINE_TYPE table entry?
  HAS_NEXT_ENTRY     : Does the following entry refer to the same engine?

  == INFO_TYPE_DATA fields ==
  PRI_BASE           : BAR0 base = (PRI_BASE << 12) aka 4k aligned.
  INST_ID            : "Note that some instanced [engines] (such as logical copy
                       engines aka LCE) share a PRI_BASE across all [engines] of
                       the same engine type; such [engines] require an additional
                       offset: instanced base = BAR0 base + stride * INST_ID.
  FAULT_ID_IS_VALID  : Does this engine have its own bind point and fault ID
                       with the MMU?
  FAULT_ID           : "The MMU fault id used by this [engine]. These IDs
                       correspond to the NV_PFAULT_MMU_ENG_ID define list."

  == INFO_TYPE_ENUM fields ==
  ENGINE_IS_VALID    : Is this engine a host engine?
  ENGINE_ENUM        : "[T]he host engine ID for the current [engine] if it is
                       a host engine, meaning Host can send methods to the
                       engine. This id is used to index into any register array
                       whose __SIZE_1 is equal to NV_HOST_NUM_ENGINES.  A given
                       ENGINE_ENUM can be present for at most one device in the
                       table.  Devices corresponding to all ENGINE_ENUM ids 0
                       through NV_HOST_NUM_ENGINES - 1 must be present in the
                       device info table."
  RUNLIST_IS_VALID   : Is this engine a host engine with a runlist?
  RUNLIST_ENUM       : "[T]he Host runlist ID on which methods for the current
                       [engine] should be submitted... The runlist id is used to
                       index into any register array whose __SIZE_1 is equal to
                       NV_HOST_NUM_RUNLISTS. [Engines] corresponding to all
                       RUNLIST_ENUM ids 0 through NV_HOST_NUM_RUNLISTS - 1 must
                       be present in the device info table."
  INTR_IS_VALID      : Does this device have an interrupt?
  INTR_ENUM          : Interrupt ID for use with "the NV_PMC_INTR_*_DEVICE
                       register bitfields."
  RESET_IS_VALID     : Does this engine have a reset ID?
  RESET_ENUM         : Reset ID for use indexing the "NV_PMC_ENABLE_DEVICE(i)
                       and NV_PMC_ELPG_ENABLE_DEVICE(i) register bitfields."

  == INFO_TYPE_ENGINE_TYPE fields ==
  ENGINE_TYPE        : What type of engine is this? (see ENGINE_TYPES_NAMES) 

  Support: Kepler, Maxwell, Pascal, Volta, Turing, Ampere
  See dev_top.ref.txt of NVIDIA's open-gpu-doc for more info.
*/

#define NV_PTOP_DEVICE_INFO_GA100(i) (0x00022800+(i)*4)
#define NV_PTOP_DEVICE_INFO_GK104(i) (0x00022700+(i)*4)
#define NV_PTOP_DEVICE_INFO__SIZE_1_GA100(g) (nvdebug_readl(g, 0x0224fc) >> 20)
#define NV_PTOP_DEVICE_INFO__SIZE_1_GK104 64
enum DEVICE_INFO_TYPE {INFO_TYPE_NOT_VALID = 0, INFO_TYPE_DATA = 1, INFO_TYPE_ENUM = 2, INFO_TYPE_ENGINE_TYPE = 3};
enum ENGINE_TYPES {
	ENGINE_GRAPHICS = 0, // GRAPHICS [/compute]
	ENGINE_COPY0 = 1, // [raw/physical] COPY #0
	ENGINE_COPY1 = 2, // [raw/physical] COPY #1
	ENGINE_COPY2 = 3, // [raw/physical] COPY #2

	ENGINE_MSPDEC = 8, // Picture DECoder
	ENGINE_MSPPP = 9, // [Video] Picture Post Processor
	ENGINE_MSVLD = 10, // [Video] Variable Length Decoder
	ENGINE_MSENC = 11, // [Video] ENCoding
	ENGINE_VIC = 12, // Video Image Compositor
	ENGINE_SEC = 13, // SEquenCer [?]
	ENGINE_NVENC0 = 14, // Nvidia Video ENCoder #0
	ENGINE_NVENC1 = 15, // Nvidia Video ENCoder #1
	ENGINE_NVDEC = 16, // Nvidia Video DECoder

	ENGINE_IOCTRL = 18, // I/O ConTRoLler [of NVLINK at least]
	ENGINE_LCE = 19, // Logical Copy Engine
	ENGINE_GSP = 20, // Gpu System Processor (Volta+)
	ENGINE_NVJPG = 21, // NVidia JPeG [Decoder] (Turing+)
	ENGINE_OFA = 22, // Optical Flow Accelerator (Turing+)
	ENGINE_FLA = 23, // [NVLink] Fabric Logical Addressing [?]
};
#define ENGINE_TYPES_LEN 24
static const char* const ENGINE_TYPES_NAMES[ENGINE_TYPES_LEN] = {
	"Graphics/Compute",
	"COPY0",
	"COPY1",
	"COPY2",
	"Unknown Engine ID#4",
	"Unknown Engine ID#5",
	"Unknown Engine ID#6",
	"Unknown Engine ID#7",
	"MSPDEC: Picture Decoder",
	"MSPPP: Post Processing",
	"MSVLD: Variable Length Decoder",
	"MSENC: Encoder",
	"VIC: Video Image Compositor",
	"SEC: Sequencer",
	"NVENC0: NVIDIA Video Encoder #0",
	"NVENC1: NVIDIA Video Encoder #1",
	"NVDEC: NVIDIA Video Decoder",
	"Unknown Engine ID#17",
	"IOCTRL: I/O Controller",
	"LCE: Logical Copy Engine",
	"GSP: GPU System Processor",
	"NVJPG: NVIDIA JPEG Decoder",
	"OFA: Optical Flow Accelerator",
	"FLA: Fabric Logical Addressing",
};

// These field are from nvgpu/include/nvgpu/hw/ga100/hw_top_ga100.h
typedef union {
	// _info type fields
	struct {
		uint32_t fault_id:11;
		 uint32_t padding0:5;
		uint32_t inst_id:8;
		enum ENGINE_TYPES engine_type:7; // "type_enum"
		bool has_next_entry:1;
	} __attribute__((packed));
	// _info2 type fields
	struct {
		uint32_t reset_id:8;
		uint32_t pri_base:18; // "device_pri_base"
		 uint32_t padding1:4;
		uint32_t is_engine:1;
		 uint32_t padding2:1;
	} __attribute__((packed));
	struct {
		uint32_t rleng_id:2;
		 uint32_t padding3:8;
		uint32_t runlist_pri_base:16;
		 uint32_t padding4:6;
	} __attribute__((packed));
	uint32_t raw;
} ptop_device_info_ga100_t;

// These field are from open-gpu-doc/manuals/volta/gv100/dev_top.ref.txt
typedef union {
	// DATA type fields
	struct {
		enum DEVICE_INFO_TYPE info_type:2;
		bool fault_id_is_valid:1;
		uint32_t fault_id:7;
		 uint32_t padding0:2;
		uint32_t pri_base:12;
		 uint32_t padding1:2;
		uint32_t inst_id:4;
		uint32_t is_not_enum2:1;
		bool has_next_entry:1;
	} __attribute__((packed));
	// ENUM type fields
	struct {
		 uint32_t padding2:2;
		bool reset_is_valid:1;
		bool intr_is_valid:1;
		bool runlist_is_valid:1;
		bool engine_is_valid:1;
		 uint32_t padding3:3;
		uint32_t reset_enum:5;
		 uint32_t padding4:1;
		uint32_t intr_enum:5;
		 uint32_t padding5:1;
		uint32_t runlist_enum:4;
		 uint32_t padding6:1;
		uint32_t engine_enum:4;
		 uint32_t padding7:2;
	} __attribute__((packed));
	// ENGINE_TYPE type fields
	struct {
		 uint32_t padding8:2;
		enum ENGINE_TYPES engine_type:29;
		 uint32_t padding9:1;
	} __attribute__((packed));
	uint32_t raw;
} ptop_device_info_gk104_t;

/* Graphics Processing Cluster (GPC) on-chip information
  The GPU's Compute/Graphics engine is subdivided into Graphics Processing
  Clusters (also known as GPU Processing Clusters, starting with Ampere).

  Each GPC is subdivided into Texture Processing Clusters (TPCs) which contain
  Streaming Multiprocessors (SMs).

  The number of these units etched onto the chip may vary from the number
  enabled and software-visible. These registers expose the number of on-chip
  GPCs, the number of on-chip TPCs inside a GPC.

  Support: Fermi through (at least) Blackwell
*/
#define NV_PTOP_SCAL_NUM_GPCS 0x00022430
#define NV_PTOP_SCAL_NUM_TPC_PER_GPC 0x00022434

/* Graphics Processing Cluster (GPC) enablement information
  (See above for a description of GPCs and TPCs.)

  The number of on-chip GPCs and TPCs enabled is driven by:
  1) Manufacturing errors which make some units nonfunctional.
  2) Commercialization decisions about how many units should be enabled for a
     specific GPU model.

  Generally, reason (1) drives disablement early in product manufacturing,
  whereas, as the manufacturing process matures, (2) steps in to ensure
  consistency between early-manufactured and late-manufactured products.

  On-chip fuses are used to dictate which units are enabled and disabled. These
  registers expose the fuse configuration for GPCs, and the TPCs in each GPC.

  FUSE_GPC            : Bitmask of which GPCs are enabled
  FUSE_TPC_FOR_GPC(i) : Bitmask of which TPCs are enabled for GPC i

  Support: Maxwell through Blackwell
           Note the registers were relocated starting with Ampere.
*/
#define NV_FUSE_GPC_GM107 0x00021c1c
#define NV_FUSE_TPC_FOR_GPC_GM107(i) (0x00021c38+(i)*4)
#define NV_FUSE_GPC_GA100 0x00820c1c
#define NV_FUSE_TPC_FOR_GPC_GA100(i) (0x00820c38+(i)*4)

/* Logical Copy Engine (LCE) Information
  Every GPU has some number of copy engines which can process transfers to,
  from, or within a GPU. Up until Maxwell, the hardware engines were directly
  accessible, and this register exposes how many there are.

  Starting with Pascal, an additional layer of indirection was added---logical
  copy engines. Only logical copy engines can be directly dispatched to, and
  there are normally more logical copy engines than there are physical ones. On
  Pascal+ this register stores the number of logical copy engines.

  SCAL_NUM_CES : Number of externally accessible copy engines

  Errata: Incorrectly reports "3" on Jetson TX1 and TX2. Should report "1" to be
  consistent with PTOP data.

  Support: Kepler through (at least) Blackwell
  Also see dev_ce.ref.txt of NVIDIA's open-gpu-doc for info.
*/
#define NV_PTOP_SCAL_NUM_CES 0x00022444
// Defined max number of GRCEs for a GPU (TX2 has only one)
# define NV_GRCE_MAX 2
// Defined GRCE->CE mapping offsets from nvgpu
#define NV_GRCE_FOR_CE_GP100(i) (0x00104034+(i)*4)
#define NV_GRCE_FOR_CE_GA100(i) (0x001041c0+(i)*4)
// Defined LCE->PCE mapping offset from nvgpu (same as ce_pce2lce_config_r(i) in nvgpu)
#define NV_LCE_FOR_PCE_GP100 0x0010402c
#define NV_LCE_FOR_PCE_GV100(i) (0x00104040+(i)*4)
#define NV_LCE_FOR_PCE_GA100(i) (0x00104100+(i)*4)
// Struct for use with nvdebug_reg_range_read()
union reg_range {
	struct {
		uint32_t offset;
		uint8_t start_bit;
		uint8_t stop_bit;
	};
	uint64_t raw;
};

/* Physical Copy Engine (PCE) information
  On Pascal GPUs or newer, this register complements the above information by
  exposing which, and how many, physical copy engines are enabled on the GPU.

  CE_PCE_MAP : A bitmask, where a set bit indicates that the PCE for that index
               is enabled (not floorswept) on this GPU. Count the number of set
               bits to get the number of PCEs. Note that this may be bogus if
               the GPU has not been used since reset.

  Support: Pascal through (at least) Blackwell
  Also see dev_ce.ref.txt of NVIDIA's open-gpu-doc for info.
*/
#define NV_CE_PCE_MAP 0x00104028
#define NV_CE_PCE_MAP_SIZE 32


/* Location of the 1Kb instance block with page tables for BAR1 and BAR2.
  Support: Fermi+ (?), Pascal
*/
#define NV_PBUS_BAR1_BLOCK 0x00001704
#define NV_PBUS_BAR2_BLOCK 0x00001714
typedef union {
	struct {
		uint32_t ptr:28;
		enum INST_TARGET target:2;
		 uint32_t padding0:1;
		bool is_virtual:1;
	} __attribute__((packed));
	uint32_t raw;
	struct {
		uint32_t map:30;
		 uint32_t padding1:2;
	} __attribute__((packed));
} bar_config_block_t;

/* BAR0 PRAMIN (Private RAM Instance) window configuration
  One of the oldest ways to access video memory on NVIDIA GPUs is by using
  a configurable 1MB window into VRAM which is mapped into BAR0 (register)
  space starting at offset NV_PRAMIN. This is still supported on NVIDIA GPUs
  and appear to be used today to bootstrap page table configuration.

  Why is it mapped at a location called NVIDIA Private RAM Instance? Because
  this used to point to the entirety of intance RAM, which was seperate from
  VRAM on older NVIDIA GPUs.

  BASE    : Base of window >> 16 in [TARGET] virtual address space
  TARGET  : Which address space BASE points into

  Note: This seems to be set to 0x0bff00000 - 0x0c0000000 at least sometimes

  Support: Tesla 2.0, Fermi, Kepler, Maxwell, Pascal, Turing, Ampere
*/
#define NV_PBUS_BAR0_WINDOW 0x00001700
#define NV_PRAMIN 0x00700000  // Goes until 0x00800000 (1MB window)
#define NV_PRAMIN_LEN 0x00100000
typedef union {
	struct {
		uint32_t base:24;
		enum INST_TARGET target:2;
		 uint32_t padding0:6;
	} __attribute__((packed));
	uint32_t raw;
} bar0_window_t;

// Support: Tesla 2.0, Fermi, Kepler, Maxwell, Pascal, Turing, Ampere
#define NV_PRAMIN_PDB_CONFIG_OFF 0x200
typedef union {
	struct {
		uint32_t target:2;
		uint32_t is_volatile:1;
		 uint32_t padding0:1;
		uint32_t fault_replay_tex:1;
		uint32_t fault_replay_gcc:1;
		 uint32_t padding1:4;
		bool is_ver2:1;
		bool is_64k_big_page:1;  // 128Kb otherwise
		uint32_t page_dir_lo:20;
		uint32_t page_dir_hi:32;
	} __attribute__((packed));
	struct {
		uint32_t pad:12;
		uint64_t page_dir:52; // Confirmed working on Xavier and tama
	} __attribute__((packed));
	uint64_t raw;
} page_dir_config_t;

/* NVIDIA GMMU (GPU Memory Management Unit) uses page tables that are mostly
  straight-forward starting with Pascal ("page table version 2"), except for a
  few quirks (like 16-byte PDE0 entries, but all other entries are 8 bytes).

  All you really need to know is that any given Page Directory Entry (PDE)
  contains a pointer to the start of a 4k page densely filled with PDEs or Page
  Table Entries (PTEs).

  == Page Table Refresher ==
  Page tables convert virtual addresses to physical addresses, and they do this
  via a tree structure. Leafs (PTEs) contain a physical address, and the path
  from root to leaf is defined by the virtual address. Non-leaf nodes are PDEs.
  When decending, the virtual address is sliced into pieces, and one slice is
  used at each level (as an index) to select the next-visited node (in level+1).

  V2 of NVIDIA's page table format uses 4 levels of PDEs and a final level of
  PTEs. How the virtual address is sliced to yield an index into each level and
  a page offset is shown by Fig 1.

  == Figure 1 ==
  Page Offset (12 bits) <---------------------------------------+
  Page Table Entry (PTE) (9 bits) <--------------------+        |
  Page Directory Entry (PDE) 0 (8 bits) <-----+        |        |
  PDE1 (9 bits) <--------------------+        |        |        |
  PDE2 (9 bits) <-----------+        |        |        |        |
  PDE3 (2 bits) <--+        |        |        |        |        |
                   ^        ^        ^        ^        ^        ^
  Virtual addr: [48, 47] [46, 38] [37, 29] [28, 21] [20, 12] [11, 0]

  The following arrays merely represent different projections of Fig. 1, and
  only one is strictly needed to reconstruct all the others. However, due to
  the complexity of page tables, we include all of these to aid in readability.

  Support: Pascal, Volta, Turing, Ampere, Ada, Ampere, Hopper*, Blackwell*
  Note: *Hopper introduces Version 3 Page Tables, but is backwards-compatible.
         The newer version adds a PD4 level to support 57-bit virtual
         addresses, and slightly shifts the PDE and PTE fields.

  See also: gp100-mmu-format.pdf in open-gpu-doc. In open-gpu-kernel-modules
            this is synonymously the "NEW" and "VER2" layout.
*/
// How many nodes/entries per level in V2 of NVIDIA's page table format
static const int NV_MMU_PT_V2_SZ[5] = {4, 512, 512, 256, 512};
// Size in bytes of an entry at a particular level
static const int NV_MMU_PT_V2_ENTRY_SZ[5] = {8, 8, 8, 16, 8};
// Which bit index is the least significant in indexing each page level
static const int NV_MMU_PT_V2_LSB[5] = {47, 38, 29, 21, 12};

// Important: Aperture keys are different with PDEs
enum PD_TARGET {
	PD_AND_TARGET_INVALID = 0,  // b000
	PD_AND_TARGET_VID_MEM = 2,  // b010
	PD_AND_TARGET_SYS_MEM_COHERENT = 4,  // b100
	PD_AND_TARGET_SYS_MEM_NONCOHERENT = 6,  // b110
	PTE_AND_TARGET_VID_MEM = 1,  // b001
	PTE_AND_TARGET_PEER = 3,  // b011
	PTE_AND_TARGET_SYS_MEM_COHERENT = 5,  // b101
	PTE_AND_TARGET_SYS_MEM_NONCOHERENT = 7,  // b111
};
// The low bit is unset on page directory (PD) targets
#define IS_PD_TARGET(target) (!(target & 0x1u))
// Convert from an enum INST_TARGET to an enum PD_TARGET
#define INST2PD_TARGET(target) ((target & 0x2) ? (target << 1) : (!target) << 1)
// Convert from an enum V1_PD_TARGET to an enum PD_TARGET
#define V12PD_TARGET(target) (target << 1)
static inline const char *pd_target_to_text(enum PD_TARGET t) {
	switch (t) {
		case PD_AND_TARGET_INVALID:
			return "INVALID";
		case PD_AND_TARGET_VID_MEM:
		case PTE_AND_TARGET_VID_MEM:
			return "VID_MEM";
		case PTE_AND_TARGET_PEER:
			return "PEER";
		case PD_AND_TARGET_SYS_MEM_COHERENT:
		case PTE_AND_TARGET_SYS_MEM_COHERENT:
			return "SYS_MEM_COHERENT";
		case PD_AND_TARGET_SYS_MEM_NONCOHERENT:
		case PTE_AND_TARGET_SYS_MEM_NONCOHERENT:
			return "SYS_MEM_NONCOHERENT";
		default:
			return "UNKNOWN";
	}
}

// Page Directory Entry/Page Table Entry V2 type
// Note: As the meaning of target (bits 2:1) at a PDE-level changes if the
//       entry is a large-page PTE or not. To simply the logic, we combine them
//       into a single target field to simplify comparisons.
#define TARGET_PEER 1
typedef union {
	// Page Directory Entry (PDE)
	struct {
		enum PD_TARGET target:3;
		bool is_volatile:1;
		 uint32_t padding1:4;
		uint32_t addr:24;
		 uint32_t __unused1;
	} __attribute__((packed));
	// Page Table Entry (PTE)
	struct {
		bool is_pte:1;
		enum INST_TARGET aperture:2;
		 uint32_t __is_volatile:1;
		bool is_encrypted:1;
		bool is_privileged:1;
		bool is_readonly:1;
		bool atomics_disabled:1;
		 uint32_t __addr:24;
		 uint32_t __unused2;
	} __attribute__((packed));
	// For wide addresses in PTEs or PDEs; only used if target is SYS_MEM
	struct {
		 uint32_t __overlap:8;
		uint64_t addr_w:46;
		 uint32_t __unused3:10;
	} __attribute__((packed));
	uint64_t raw_w;
} page_dir_entry_t;

/* GMMU Page Tables Version 1
  These page tables contain 2 levels and are used in the Fermi, Kepler, and
  Maxwell architectures to support a 40-bit virtual address space.

  Version 1 Page Tables may be configured to support either 64 KiB or 128 KiB
  large pages. Table addressing differs between the modes---even if the table
  contains no large pages. The format for 4 KiB pages in each mode is shown
  below.

  V1 of NVIDIA's page table format uses 1 level of PDEs and a level of PTEs.
  How the virtual address is sliced to yield an index into each level and a
  page offset is shown by Fig 1 and Fig 2 (for 64 KiB and 128 KiB large page
  modes respectively).

  == Figure 1: 64 KiB mode ==
  Page Offset (12 bits) <----------------------------------+
  Page Table Entry (PTE) (13 bits) <--------------+        |
  Page Directory Entry (PDE) (13 bits) <-+        |        |
                                         ^        ^        ^
                     Virtual address: [39, 26] [25, 12] [11, 0]

  == Figure 2: 128 KiB mode ==
  Page Offset (12 bits) <----------------------------------+
  Page Table Entry (PTE) (14 bits) <--------------+        |
  Page Directory Entry (PDE) (12 bits) <-+        |        |
                                         ^        ^        ^
                     Virtual address: [39, 27] [26, 12] [11, 0]


  Support: Fermi, Kepler, Maxwell, Pascal*
  Note: *Pascal introduces Version 2 Page Tables, but is backwards-compatible.
  Note: We only implement the 128-KiB-large-page mode in nvdebug.

  See also: mm_gk20a.c in nvgpu (Jetson GPU driver) and kern_gmmu_fmt_gm10x.c
            in open-gpu-kernel-modules (open-source NVRM variant). This is
            synonymously the "VER1" and unversioned layout in
            open-gpu-kernel-modules, with some differences noted in Appdx 1.

  == Appdx 1 ==
  In open-gpu-kernel-modules, the unversioned MMU layout adds:
  - Bit 35: NV_MMU_PTE_LOCK synonym for NV_MMU_PTE_ATOMIC_DISABLE
  - Bit 62: NV_MMU_PTE_READ_DISABLE overlapping NV_MMU_PTE_COMPTAGLINE
  - Bit 63: NV_MMU_PTE_WRITE_DISABLE overlapping NV_MMU_PTE_COMPTAGLINE
  And removes:
  - Bit 40, 41, 42, 43 from NV_MMU_PTE_KIND
  The PDE layouts are identical. Given that the unversioned defines seem to
  predate renaming and/or field extension/relocation, they are likely artifacts
  from the page table development process, and have no meaning now.
*/
// Number of entries in the PDE and PTE levels
static const int NV_MMU_PT_V1_SZ[2] = {4096, 16384}; // 2^12 and 2^14
// Which bit index is the least significant in indexing each page level
static const int NV_MMU_PT_V1_LSB[2] = {27, 12};

// V1 Page Directory Entry target
enum V1_PD_TARGET {
	PD_TARGET_INVALID = 0,
	PD_TARGET_VID_MEM = 1,
	PD_TARGET_SYS_MEM_COHERENT = 2,
	PD_TARGET_SYS_MEM_NONCOHERENT = 3,
};
// V1 Page Directory Entry (PDE)
typedef union {
// Large page fields
	struct {
// 0:32
		enum V1_PD_TARGET target:2;
		 uint32_t padding0:2; // Documented as "PDE_SIZE"?
		uint64_t addr:28;  // May be wider?
// 32:63
		 uint32_t padding2:3;
		uint32_t is_volatile:1; // Might have counted wrong?
		 uint32_t padding3:28;
	} __attribute__((packed));
// Small page fields
	struct {
// 0:32
		 uint32_t padding00:32;
// 32:63
		enum V1_PD_TARGET alt_target:2;
		uint32_t alt_is_volatile:1; // Might have counted wrong?
		 uint32_t padding03:1;
		uint64_t alt_addr:28;
	} __attribute__((packed));
	uint64_t raw;
} page_dir_entry_v1_t;

// V1 Page Table Entry (PTE)
typedef union {
	struct {
// 0:32
		bool is_present:1;