Line data Source code
1 : #![allow(non_upper_case_globals)]
2 : #![allow(non_camel_case_types)]
3 : #![allow(non_snake_case)]
4 : // bindgen creates some unsafe code with no doc comments.
5 : #![allow(clippy::missing_safety_doc)]
6 : // noted at 1.63 that in many cases there's u32 -> u32 transmutes in bindgen code.
7 : #![allow(clippy::useless_transmute)]
8 : // modules included with the postgres_ffi macro depend on the types of the specific version's
9 : // types, and trigger a too eager lint.
10 : #![allow(clippy::duplicate_mod)]
11 : #![deny(clippy::undocumented_unsafe_blocks)]
12 :
13 : use bytes::Bytes;
14 : use utils::bin_ser::SerializeError;
15 : use utils::lsn::Lsn;
16 :
17 : macro_rules! postgres_ffi {
18 : ($version:ident) => {
19 : #[path = "."]
20 : pub mod $version {
21 : pub mod bindings {
22 : // bindgen generates bindings for a lot of stuff we don't need
23 : #![allow(dead_code)]
24 : #![allow(clippy::undocumented_unsafe_blocks)]
25 :
26 : use serde::{Deserialize, Serialize};
27 : include!(concat!(
28 : env!("OUT_DIR"),
29 : "/bindings_",
30 : stringify!($version),
31 : ".rs"
32 : ));
33 :
34 : include!(concat!("pg_constants_", stringify!($version), ".rs"));
35 : }
36 : pub mod controlfile_utils;
37 : pub mod nonrelfile_utils;
38 : pub mod wal_craft_test_export;
39 : pub mod waldecoder_handler;
40 : pub mod xlog_utils;
41 :
42 : pub const PG_MAJORVERSION: &str = stringify!($version);
43 :
44 : // Re-export some symbols from bindings
45 : pub use bindings::DBState_DB_SHUTDOWNED;
46 : pub use bindings::{CheckPoint, ControlFileData, XLogRecord};
47 : }
48 : };
49 : }
50 :
51 : #[macro_export]
52 : macro_rules! for_all_postgres_versions {
53 : ($macro:tt) => {
54 : $macro!(v14);
55 : $macro!(v15);
56 : $macro!(v16);
57 : };
58 : }
59 :
60 : for_all_postgres_versions! { postgres_ffi }
61 :
62 : /// dispatch_pgversion
63 : ///
64 : /// Run a code block in a context where the postgres_ffi bindings for a
65 : /// specific (supported) PostgreSQL version are `use`-ed in scope under the pgv
66 : /// identifier.
67 : /// If the provided pg_version is not supported, we panic!(), unless the
68 : /// optional third argument was provided (in which case that code will provide
69 : /// the default handling instead).
70 : ///
71 : /// Use like
72 : ///
73 : /// dispatch_pgversion!(my_pgversion, { pgv::constants::XLOG_DBASE_CREATE })
74 : /// dispatch_pgversion!(my_pgversion, pgv::constants::XLOG_DBASE_CREATE)
75 : ///
76 : /// Other uses are for macro-internal purposes only and strictly unsupported.
77 : ///
78 : #[macro_export]
79 : macro_rules! dispatch_pgversion {
80 : ($version:expr, $code:expr) => {
81 : dispatch_pgversion!($version, $code, panic!("Unknown PostgreSQL version {}", $version))
82 : };
83 : ($version:expr, $code:expr, $invalid_pgver_handling:expr) => {
84 : dispatch_pgversion!(
85 : $version => $code,
86 : default = $invalid_pgver_handling,
87 : pgversions = [
88 : 14 : v14,
89 : 15 : v15,
90 : 16 : v16,
91 : ]
92 : )
93 : };
94 : ($pgversion:expr => $code:expr,
95 : default = $default:expr,
96 : pgversions = [$($sv:literal : $vsv:ident),+ $(,)?]) => {
97 : match ($pgversion) {
98 : $($sv => {
99 : use $crate::$vsv as pgv;
100 : $code
101 : },)+
102 : _ => {
103 : $default
104 : }
105 : }
106 : };
107 : }
108 :
109 : pub mod pg_constants;
110 : pub mod relfile_utils;
111 :
112 : // Export some widely used datatypes that are unlikely to change across Postgres versions
113 : pub use v14::bindings::RepOriginId;
114 : pub use v14::bindings::{uint32, uint64, Oid};
115 : pub use v14::bindings::{BlockNumber, OffsetNumber};
116 : pub use v14::bindings::{MultiXactId, TransactionId};
117 : pub use v14::bindings::{TimeLineID, TimestampTz, XLogRecPtr, XLogSegNo};
118 :
119 : // Likewise for these, although the assumption that these don't change is a little more iffy.
120 : pub use v14::bindings::{MultiXactOffset, MultiXactStatus};
121 : pub use v14::bindings::{PageHeaderData, XLogRecord};
122 : pub use v14::xlog_utils::{
123 : XLOG_SIZE_OF_XLOG_LONG_PHD, XLOG_SIZE_OF_XLOG_RECORD, XLOG_SIZE_OF_XLOG_SHORT_PHD,
124 : };
125 :
126 : pub use v14::bindings::{CheckPoint, ControlFileData};
127 :
128 : // from pg_config.h. These can be changed with configure options --with-blocksize=BLOCKSIZE and
129 : // --with-segsize=SEGSIZE, but assume the defaults for now.
130 : pub const BLCKSZ: u16 = 8192;
131 : pub const RELSEG_SIZE: u32 = 1024 * 1024 * 1024 / (BLCKSZ as u32);
132 : pub const XLOG_BLCKSZ: usize = 8192;
133 : pub const WAL_SEGMENT_SIZE: usize = 16 * 1024 * 1024;
134 :
135 : pub const MAX_SEND_SIZE: usize = XLOG_BLCKSZ * 16;
136 :
137 : // Export some version independent functions that are used outside of this mod
138 : pub use v14::xlog_utils::encode_logical_message;
139 : pub use v14::xlog_utils::from_pg_timestamp;
140 : pub use v14::xlog_utils::get_current_timestamp;
141 : pub use v14::xlog_utils::to_pg_timestamp;
142 : pub use v14::xlog_utils::XLogFileName;
143 :
144 : pub use v14::bindings::DBState_DB_SHUTDOWNED;
145 :
146 84 : pub fn bkpimage_is_compressed(bimg_info: u8, version: u32) -> anyhow::Result<bool> {
147 84 : dispatch_pgversion!(version, Ok(pgv::bindings::bkpimg_is_compressed(bimg_info)))
148 84 : }
149 :
150 0 : pub fn generate_wal_segment(
151 0 : segno: u64,
152 0 : system_id: u64,
153 0 : pg_version: u32,
154 0 : lsn: Lsn,
155 0 : ) -> Result<Bytes, SerializeError> {
156 0 : assert_eq!(segno, lsn.segment_number(WAL_SEGMENT_SIZE));
157 :
158 : dispatch_pgversion!(
159 0 : pg_version,
160 0 : pgv::xlog_utils::generate_wal_segment(segno, system_id, lsn),
161 0 : Err(SerializeError::BadInput)
162 : )
163 0 : }
164 :
165 0 : pub fn generate_pg_control(
166 0 : pg_control_bytes: &[u8],
167 0 : checkpoint_bytes: &[u8],
168 0 : lsn: Lsn,
169 0 : pg_version: u32,
170 0 : ) -> anyhow::Result<(Bytes, u64)> {
171 0 : dispatch_pgversion!(
172 0 : pg_version,
173 0 : pgv::xlog_utils::generate_pg_control(pg_control_bytes, checkpoint_bytes, lsn),
174 0 : anyhow::bail!("Unknown version {}", pg_version)
175 : )
176 0 : }
177 :
178 : // PG timeline is always 1, changing it doesn't have any useful meaning in Neon.
179 : //
180 : // NOTE: this is not to be confused with Neon timelines; different concept!
181 : //
182 : // It's a shaky assumption, that it's always 1. We might import a
183 : // PostgreSQL data directory that has gone through timeline bumps,
184 : // for example. FIXME later.
185 : pub const PG_TLI: u32 = 1;
186 :
187 : // See TransactionIdIsNormal in transam.h
188 0 : pub const fn transaction_id_is_normal(id: TransactionId) -> bool {
189 0 : id > pg_constants::FIRST_NORMAL_TRANSACTION_ID
190 0 : }
191 :
192 : // See TransactionIdPrecedes in transam.c
193 0 : pub const fn transaction_id_precedes(id1: TransactionId, id2: TransactionId) -> bool {
194 0 : /*
195 0 : * If either ID is a permanent XID then we can just do unsigned
196 0 : * comparison. If both are normal, do a modulo-2^32 comparison.
197 0 : */
198 0 :
199 0 : if !(transaction_id_is_normal(id1)) || !transaction_id_is_normal(id2) {
200 0 : return id1 < id2;
201 0 : }
202 0 :
203 0 : let diff = id1.wrapping_sub(id2) as i32;
204 0 : diff < 0
205 0 : }
206 :
207 : // Check if page is not yet initialized (port of Postgres PageIsInit() macro)
208 24 : pub fn page_is_new(pg: &[u8]) -> bool {
209 24 : pg[14] == 0 && pg[15] == 0 // pg_upper == 0
210 24 : }
211 :
212 : // ExtractLSN from page header
213 0 : pub fn page_get_lsn(pg: &[u8]) -> Lsn {
214 0 : Lsn(
215 0 : ((u32::from_le_bytes(pg[0..4].try_into().unwrap()) as u64) << 32)
216 0 : | u32::from_le_bytes(pg[4..8].try_into().unwrap()) as u64,
217 0 : )
218 0 : }
219 :
220 18 : pub fn page_set_lsn(pg: &mut [u8], lsn: Lsn) {
221 18 : pg[0..4].copy_from_slice(&((lsn.0 >> 32) as u32).to_le_bytes());
222 18 : pg[4..8].copy_from_slice(&(lsn.0 as u32).to_le_bytes());
223 18 : }
224 :
225 : // This is port of function with the same name from freespace.c.
226 : // The only difference is that it does not have "level" parameter because XLogRecordPageWithFreeSpace
227 : // always call it with level=FSM_BOTTOM_LEVEL
228 0 : pub fn fsm_logical_to_physical(addr: BlockNumber) -> BlockNumber {
229 0 : let mut leafno = addr;
230 0 : const FSM_TREE_DEPTH: u32 = if pg_constants::SLOTS_PER_FSM_PAGE >= 1626 {
231 0 : 3
232 0 : } else {
233 0 : 4
234 0 : };
235 0 :
236 0 : /* Count upper level nodes required to address the leaf page */
237 0 : let mut pages: BlockNumber = 0;
238 0 : for _l in 0..FSM_TREE_DEPTH {
239 0 : pages += leafno + 1;
240 0 : leafno /= pg_constants::SLOTS_PER_FSM_PAGE;
241 0 : }
242 : /* Turn the page count into 0-based block number */
243 0 : pages - 1
244 0 : }
245 :
246 : pub mod waldecoder {
247 : use bytes::{Buf, Bytes, BytesMut};
248 : use std::num::NonZeroU32;
249 : use thiserror::Error;
250 : use utils::lsn::Lsn;
251 :
252 : pub enum State {
253 : WaitingForRecord,
254 : ReassemblingRecord {
255 : recordbuf: BytesMut,
256 : contlen: NonZeroU32,
257 : },
258 : SkippingEverything {
259 : skip_until_lsn: Lsn,
260 : },
261 : }
262 :
263 : pub struct WalStreamDecoder {
264 : pub lsn: Lsn,
265 : pub pg_version: u32,
266 : pub inputbuf: BytesMut,
267 : pub state: State,
268 : }
269 :
270 0 : #[derive(Error, Debug, Clone)]
271 : #[error("{msg} at {lsn}")]
272 : pub struct WalDecodeError {
273 : pub msg: String,
274 : pub lsn: Lsn,
275 : }
276 :
277 : impl WalStreamDecoder {
278 80137 : pub fn new(lsn: Lsn, pg_version: u32) -> WalStreamDecoder {
279 80137 : WalStreamDecoder {
280 80137 : lsn,
281 80137 : pg_version,
282 80137 : inputbuf: BytesMut::new(),
283 80137 : state: State::WaitingForRecord,
284 80137 : }
285 80137 : }
286 :
287 : // The latest LSN position fed to the decoder.
288 4053 : pub fn available(&self) -> Lsn {
289 4053 : self.lsn + self.inputbuf.remaining() as u64
290 4053 : }
291 :
292 508144 : pub fn feed_bytes(&mut self, buf: &[u8]) {
293 508144 : self.inputbuf.extend_from_slice(buf);
294 508144 : }
295 :
296 733586 : pub fn poll_decode(&mut self) -> Result<Option<(Lsn, Bytes)>, WalDecodeError> {
297 733586 : dispatch_pgversion!(
298 733586 : self.pg_version,
299 : {
300 : use pgv::waldecoder_handler::WalStreamDecoderHandler;
301 8334 : self.poll_decode_internal()
302 : },
303 0 : Err(WalDecodeError {
304 0 : msg: format!("Unknown version {}", self.pg_version),
305 0 : lsn: self.lsn,
306 0 : })
307 : )
308 733586 : }
309 : }
310 : }
|