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 wal_generator;
40 : pub mod waldecoder_handler;
41 : pub mod xlog_utils;
42 :
43 : pub const PG_MAJORVERSION: &str = stringify!($version);
44 :
45 : // Re-export some symbols from bindings
46 : pub use bindings::DBState_DB_SHUTDOWNED;
47 : pub use bindings::{CheckPoint, ControlFileData, XLogRecord};
48 :
49 : pub const ZERO_CHECKPOINT: bytes::Bytes =
50 : bytes::Bytes::from_static(&[0u8; xlog_utils::SIZEOF_CHECKPOINT]);
51 : }
52 : };
53 : }
54 :
55 : #[macro_export]
56 : macro_rules! for_all_postgres_versions {
57 : ($macro:tt) => {
58 : $macro!(v14);
59 : $macro!(v15);
60 : $macro!(v16);
61 : $macro!(v17);
62 : };
63 : }
64 :
65 : for_all_postgres_versions! { postgres_ffi }
66 :
67 : /// dispatch_pgversion
68 : ///
69 : /// Run a code block in a context where the postgres_ffi bindings for a
70 : /// specific (supported) PostgreSQL version are `use`-ed in scope under the pgv
71 : /// identifier.
72 : /// If the provided pg_version is not supported, we panic!(), unless the
73 : /// optional third argument was provided (in which case that code will provide
74 : /// the default handling instead).
75 : ///
76 : /// Use like
77 : ///
78 : /// dispatch_pgversion!(my_pgversion, { pgv::constants::XLOG_DBASE_CREATE })
79 : /// dispatch_pgversion!(my_pgversion, pgv::constants::XLOG_DBASE_CREATE)
80 : ///
81 : /// Other uses are for macro-internal purposes only and strictly unsupported.
82 : ///
83 : #[macro_export]
84 : macro_rules! dispatch_pgversion {
85 : ($version:expr, $code:expr) => {
86 : dispatch_pgversion!($version, $code, panic!("Unknown PostgreSQL version {}", $version))
87 : };
88 : ($version:expr, $code:expr, $invalid_pgver_handling:expr) => {
89 : dispatch_pgversion!(
90 : $version => $code,
91 : default = $invalid_pgver_handling,
92 : pgversions = [
93 : 14 : v14,
94 : 15 : v15,
95 : 16 : v16,
96 : 17 : v17,
97 : ]
98 : )
99 : };
100 : ($pgversion:expr => $code:expr,
101 : default = $default:expr,
102 : pgversions = [$($sv:literal : $vsv:ident),+ $(,)?]) => {
103 : match ($pgversion) {
104 : $($sv => {
105 : use $crate::$vsv as pgv;
106 : $code
107 : },)+
108 : _ => {
109 : $default
110 : }
111 : }
112 : };
113 : }
114 :
115 : #[macro_export]
116 : macro_rules! enum_pgversion_dispatch {
117 : ($name:expr, $typ:ident, $bind:ident, $code:block) => {
118 : enum_pgversion_dispatch!(
119 : name = $name,
120 : bind = $bind,
121 : typ = $typ,
122 : code = $code,
123 : pgversions = [
124 : V14 : v14,
125 : V15 : v15,
126 : V16 : v16,
127 : V17 : v17,
128 : ]
129 : )
130 : };
131 : (name = $name:expr,
132 : bind = $bind:ident,
133 : typ = $typ:ident,
134 : code = $code:block,
135 : pgversions = [$($variant:ident : $md:ident),+ $(,)?]) => {
136 : match $name {
137 : $(
138 : self::$typ::$variant($bind) => {
139 : use $crate::$md as pgv;
140 : $code
141 : }
142 : ),+,
143 : }
144 : };
145 : }
146 :
147 : #[macro_export]
148 : macro_rules! enum_pgversion {
149 : {$name:ident, pgv :: $t:ident} => {
150 : enum_pgversion!{
151 : name = $name,
152 : typ = $t,
153 : pgversions = [
154 : V14 : v14,
155 : V15 : v15,
156 : V16 : v16,
157 : V17 : v17,
158 : ]
159 : }
160 : };
161 : {$name:ident, pgv :: $p:ident :: $t:ident} => {
162 : enum_pgversion!{
163 : name = $name,
164 : path = $p,
165 : typ = $t,
166 : pgversions = [
167 : V14 : v14,
168 : V15 : v15,
169 : V16 : v16,
170 : V17 : v17,
171 : ]
172 : }
173 : };
174 : {name = $name:ident,
175 : typ = $t:ident,
176 : pgversions = [$($variant:ident : $md:ident),+ $(,)?]} => {
177 : pub enum $name {
178 : $($variant ( $crate::$md::$t )),+
179 : }
180 : impl self::$name {
181 0 : pub fn pg_version(&self) -> u32 {
182 0 : enum_pgversion_dispatch!(self, $name, _ign, {
183 0 : pgv::bindings::PG_MAJORVERSION_NUM
184 : })
185 0 : }
186 0 : }
187 0 : $(
188 0 : impl Into<self::$name> for $crate::$md::$t {
189 12 : fn into(self) -> self::$name {
190 12 : self::$name::$variant (self)
191 12 : }
192 : }
193 : )+
194 : };
195 : {name = $name:ident,
196 : path = $p:ident,
197 : typ = $t:ident,
198 : pgversions = [$($variant:ident : $md:ident),+ $(,)?]} => {
199 : pub enum $name {
200 : $($variant ($crate::$md::$p::$t)),+
201 : }
202 : impl $name {
203 : pub fn pg_version(&self) -> u32 {
204 : enum_pgversion_dispatch!(self, $name, _ign, {
205 : pgv::bindings::PG_MAJORVERSION_NUM
206 : })
207 : }
208 : }
209 : $(
210 : impl Into<$name> for $crate::$md::$p::$t {
211 : fn into(self) -> $name {
212 : $name::$variant (self)
213 : }
214 : }
215 : )+
216 : };
217 : }
218 :
219 : pub mod pg_constants;
220 : pub mod relfile_utils;
221 : pub mod walrecord;
222 :
223 : // Export some widely used datatypes that are unlikely to change across Postgres versions
224 : pub use v14::bindings::RepOriginId;
225 : pub use v14::bindings::{uint32, uint64, Oid};
226 : pub use v14::bindings::{BlockNumber, OffsetNumber};
227 : pub use v14::bindings::{MultiXactId, TransactionId};
228 : pub use v14::bindings::{TimeLineID, TimestampTz, XLogRecPtr, XLogSegNo};
229 :
230 : // Likewise for these, although the assumption that these don't change is a little more iffy.
231 : pub use v14::bindings::{MultiXactOffset, MultiXactStatus};
232 : pub use v14::bindings::{PageHeaderData, XLogRecord};
233 : pub use v14::xlog_utils::{
234 : XLOG_SIZE_OF_XLOG_LONG_PHD, XLOG_SIZE_OF_XLOG_RECORD, XLOG_SIZE_OF_XLOG_SHORT_PHD,
235 : };
236 :
237 : pub use v14::bindings::{CheckPoint, ControlFileData};
238 :
239 : // from pg_config.h. These can be changed with configure options --with-blocksize=BLOCKSIZE and
240 : // --with-segsize=SEGSIZE, but assume the defaults for now.
241 : pub const BLCKSZ: u16 = 8192;
242 : pub const RELSEG_SIZE: u32 = 1024 * 1024 * 1024 / (BLCKSZ as u32);
243 : pub const XLOG_BLCKSZ: usize = 8192;
244 : pub const WAL_SEGMENT_SIZE: usize = 16 * 1024 * 1024;
245 :
246 : pub const MAX_SEND_SIZE: usize = XLOG_BLCKSZ * 16;
247 :
248 : // Export some version independent functions that are used outside of this mod
249 : pub use v14::xlog_utils::encode_logical_message;
250 : pub use v14::xlog_utils::get_current_timestamp;
251 : pub use v14::xlog_utils::to_pg_timestamp;
252 : pub use v14::xlog_utils::try_from_pg_timestamp;
253 : pub use v14::xlog_utils::XLogFileName;
254 :
255 : pub use v14::bindings::DBState_DB_SHUTDOWNED;
256 :
257 108 : pub fn bkpimage_is_compressed(bimg_info: u8, version: u32) -> bool {
258 108 : dispatch_pgversion!(version, pgv::bindings::bkpimg_is_compressed(bimg_info))
259 108 : }
260 :
261 0 : pub fn generate_wal_segment(
262 0 : segno: u64,
263 0 : system_id: u64,
264 0 : pg_version: u32,
265 0 : lsn: Lsn,
266 0 : ) -> Result<Bytes, SerializeError> {
267 0 : assert_eq!(segno, lsn.segment_number(WAL_SEGMENT_SIZE));
268 :
269 : dispatch_pgversion!(
270 0 : pg_version,
271 0 : pgv::xlog_utils::generate_wal_segment(segno, system_id, lsn),
272 0 : Err(SerializeError::BadInput)
273 : )
274 0 : }
275 :
276 0 : pub fn generate_pg_control(
277 0 : pg_control_bytes: &[u8],
278 0 : checkpoint_bytes: &[u8],
279 0 : lsn: Lsn,
280 0 : pg_version: u32,
281 0 : ) -> anyhow::Result<(Bytes, u64)> {
282 0 : dispatch_pgversion!(
283 0 : pg_version,
284 0 : pgv::xlog_utils::generate_pg_control(pg_control_bytes, checkpoint_bytes, lsn),
285 0 : anyhow::bail!("Unknown version {}", pg_version)
286 : )
287 0 : }
288 :
289 : // PG timeline is always 1, changing it doesn't have any useful meaning in Neon.
290 : //
291 : // NOTE: this is not to be confused with Neon timelines; different concept!
292 : //
293 : // It's a shaky assumption, that it's always 1. We might import a
294 : // PostgreSQL data directory that has gone through timeline bumps,
295 : // for example. FIXME later.
296 : pub const PG_TLI: u32 = 1;
297 :
298 : // See TransactionIdIsNormal in transam.h
299 0 : pub const fn transaction_id_is_normal(id: TransactionId) -> bool {
300 0 : id > pg_constants::FIRST_NORMAL_TRANSACTION_ID
301 0 : }
302 :
303 : // See TransactionIdPrecedes in transam.c
304 0 : pub const fn transaction_id_precedes(id1: TransactionId, id2: TransactionId) -> bool {
305 0 : /*
306 0 : * If either ID is a permanent XID then we can just do unsigned
307 0 : * comparison. If both are normal, do a modulo-2^32 comparison.
308 0 : */
309 0 :
310 0 : if !(transaction_id_is_normal(id1)) || !transaction_id_is_normal(id2) {
311 0 : return id1 < id2;
312 0 : }
313 0 :
314 0 : let diff = id1.wrapping_sub(id2) as i32;
315 0 : diff < 0
316 0 : }
317 :
318 : // Check if page is not yet initialized (port of Postgres PageIsInit() macro)
319 24 : pub fn page_is_new(pg: &[u8]) -> bool {
320 24 : pg[14] == 0 && pg[15] == 0 // pg_upper == 0
321 24 : }
322 :
323 : // ExtractLSN from page header
324 0 : pub fn page_get_lsn(pg: &[u8]) -> Lsn {
325 0 : Lsn(
326 0 : ((u32::from_le_bytes(pg[0..4].try_into().unwrap()) as u64) << 32)
327 0 : | u32::from_le_bytes(pg[4..8].try_into().unwrap()) as u64,
328 0 : )
329 0 : }
330 :
331 18 : pub fn page_set_lsn(pg: &mut [u8], lsn: Lsn) {
332 18 : pg[0..4].copy_from_slice(&((lsn.0 >> 32) as u32).to_le_bytes());
333 18 : pg[4..8].copy_from_slice(&(lsn.0 as u32).to_le_bytes());
334 18 : }
335 :
336 : // This is port of function with the same name from freespace.c.
337 : // The only difference is that it does not have "level" parameter because XLogRecordPageWithFreeSpace
338 : // always call it with level=FSM_BOTTOM_LEVEL
339 0 : pub fn fsm_logical_to_physical(addr: BlockNumber) -> BlockNumber {
340 0 : let mut leafno = addr;
341 : const FSM_TREE_DEPTH: u32 = if pg_constants::SLOTS_PER_FSM_PAGE >= 1626 {
342 : 3
343 : } else {
344 : 4
345 : };
346 :
347 : /* Count upper level nodes required to address the leaf page */
348 0 : let mut pages: BlockNumber = 0;
349 0 : for _l in 0..FSM_TREE_DEPTH {
350 0 : pages += leafno + 1;
351 0 : leafno /= pg_constants::SLOTS_PER_FSM_PAGE;
352 0 : }
353 : /* Turn the page count into 0-based block number */
354 0 : pages - 1
355 0 : }
356 :
357 : pub mod waldecoder {
358 : use bytes::{Buf, Bytes, BytesMut};
359 : use std::num::NonZeroU32;
360 : use thiserror::Error;
361 : use utils::lsn::Lsn;
362 :
363 : pub enum State {
364 : WaitingForRecord,
365 : ReassemblingRecord {
366 : recordbuf: BytesMut,
367 : contlen: NonZeroU32,
368 : },
369 : SkippingEverything {
370 : skip_until_lsn: Lsn,
371 : },
372 : }
373 :
374 : pub struct WalStreamDecoder {
375 : pub lsn: Lsn,
376 : pub pg_version: u32,
377 : pub inputbuf: BytesMut,
378 : pub state: State,
379 : }
380 :
381 0 : #[derive(Error, Debug, Clone)]
382 : #[error("{msg} at {lsn}")]
383 : pub struct WalDecodeError {
384 : pub msg: String,
385 : pub lsn: Lsn,
386 : }
387 :
388 : impl WalStreamDecoder {
389 10407 : pub fn new(lsn: Lsn, pg_version: u32) -> WalStreamDecoder {
390 10407 : WalStreamDecoder {
391 10407 : lsn,
392 10407 : pg_version,
393 10407 : inputbuf: BytesMut::new(),
394 10407 : state: State::WaitingForRecord,
395 10407 : }
396 10407 : }
397 :
398 : // The latest LSN position fed to the decoder.
399 730 : pub fn available(&self) -> Lsn {
400 730 : self.lsn + self.inputbuf.remaining() as u64
401 730 : }
402 :
403 492538 : pub fn feed_bytes(&mut self, buf: &[u8]) {
404 492538 : self.inputbuf.extend_from_slice(buf);
405 492538 : }
406 :
407 662781 : pub fn poll_decode(&mut self) -> Result<Option<(Lsn, Bytes)>, WalDecodeError> {
408 662781 : dispatch_pgversion!(
409 662781 : self.pg_version,
410 : {
411 : use pgv::waldecoder_handler::WalStreamDecoderHandler;
412 4167 : self.poll_decode_internal()
413 : },
414 0 : Err(WalDecodeError {
415 0 : msg: format!("Unknown version {}", self.pg_version),
416 0 : lsn: self.lsn,
417 0 : })
418 : )
419 662781 : }
420 : }
421 : }
|