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