Postgres, fsync, and OSs (specifically linux)
Hi,
I thought I'd send this separately from [0]https://archives.postgresql.org/message-id/CAMsr+YHh+5Oq4xziwwoEfhoTZgr07vdGG+hu=1adXx59aTeaoQ@mail.gmail.com as the issue has become more
general than what was mentioned in that thread, and it went off into
various weeds.
I went to LSF/MM 2018 to discuss [0]https://archives.postgresql.org/message-id/CAMsr+YHh+5Oq4xziwwoEfhoTZgr07vdGG+hu=1adXx59aTeaoQ@mail.gmail.com and related issues. Overall I'd say
it was a very productive discussion. I'll first try to recap the
current situation, updated with knowledge I gained. Secondly I'll try to
discuss the kernel changes that seem to have been agreed upon. Thirdly
I'll try to sum up what postgres needs to change.
== Current Situation ==
The fundamental problem is that postgres assumed that any IO error would
be reported at fsync time, and that the error would be reported until
resolved. That's not true in several operating systems, linux included.
There's various judgement calls leading to the current OS (specifically
linux, but the concerns are similar in other OSs) behaviour:
- By the time IO errors are treated as fatal, it's unlikely that plain
retries attempting to write exactly the same data are going to
succeed. There are retries on several layers. Some cases would be
resolved by overwriting a larger amount (so device level remapping
functionality can mask dead areas), but plain retries aren't going to
get there if they didn't the first time round.
- Retaining all the data necessary for retries would make it quite
possible to turn IO errors on some device into out of memory
errors. This is true to a far lesser degree if only enough information
were to be retained to (re-)report an error, rather than actually
retry the write.
- Continuing to re-report an error after one fsync() failed would make
it hard to recover from that fact. There'd need to be a way to "clear"
a persistent error bit, and that'd obviously be outside of posix.
- Some other databases use direct-IO and thus these paths haven't been
exercised under fire that much.
- Actually marking files as persistently failed would require filesystem
changes, and filesystem metadata IO, far from guaranteed in failure
scenarios.
Before linux v4.13 errors in kernel writeback would be reported at most
once, without a guarantee that that'd happen (IIUC memory pressure could
lead to the relevant information being evicted) - but it was pretty
likely. After v4.13 (see https://lwn.net/Articles/724307/) errors are
reported exactly once to all open file descriptors for a file with an
error - but never for files that have been opened after the error
occurred.
It's worth to note that on linux it's not well defined what contents one
would read after a writeback error. IIUC xfs will mark the pagecache
contents that triggered an error as invalid, triggering a re-read from
the underlying storage (thus either failing or returning old but
persistent contents). Whereas some other filesystems (among them ext4 I
believe) retain the modified contents of the page cache, but marking it
as clean (thereby returning new contents until the page cache contents
are evicted).
Some filesystems (prominently NFS in many configurations) perform an
implicit fsync when closing the file. While postgres checks for an error
of close() and reports it, we don't treat it as fatal. It's worth to
note that by my reading this means that an fsync error at close() will
*not* be re-reported by the time an explicit fsync() is issued. It also
means that we'll not react properly to the possible ENOSPC errors that
may be reported at close() for NFS. At least the latter isn't just the
case in linux.
Proposals for how postgres could deal with this included using syncfs(2)
- but that turns out not to work at all currently, because syncfs()
basically wouldn't return any file-level errors. It'd also imply
superflously flushing temporary files etc.
The second major type of proposal was using direct-IO. That'd generally
be a desirable feature, but a) would require some significant changes to
postgres to be performant, b) isn't really applicable for the large
percentage of installations that aren't tuned reasonably well, because
at the moment the OS page cache functions as a memory-pressure aware
extension of postgres' page cache.
Another topic brought up in this thread was the handling of ENOSPC
errors that aren't triggered on a filesystem level, but rather are
triggered by thin provisioning. On linux that currently apprently lead
to page cache contents being lost (and errors "eaten") in a lot of
places, including just when doing a write(). In a lot of cases it's
pretty much expected that the file system will just hang or react
unpredictably upon space exhaustion. My reading is that the block-layer
thin provisioning code is still pretty fresh, and should only be used
with great care. The only way to halfway reliably use it appears to
change the configuration so space exhaustion blocks until admin
intervention (at least dm-thinp provides allows that).
There's some clear need to automate some more testing in this area so
that future behaviour changes don't surprise us.
== Proposed Linux Changes ==
- Matthew Wilcox proposed (and posted a patch) that'd partially revert
behaviour to the pre v4.13 world, by *also* reporting errors to
"newer" file-descriptors if the error hasn't previously been
reported. That'd still not guarantee that the error is reported
(memory pressure could evict information without open fd), but in most
situations we'll again get the error in the checkpointer.
This seems largely be agreed upon. It's unclear whether it'll go into
the stable backports for still-maintained >= v4.13 kernels.
- syncfs() will be fixed so it reports errors properly - that'll likely
require passing it an O_PATH filedescriptor to have space to store the
errseq_t value that allows discerning already reported and new errors.
No patch has appeared yet, but the behaviour seems largely agreed
upon.
- Make per-filesystem error counts available in a uniform (i.e. same for
every supporting fs) manner. Right now it's very hard to figure out
whether errors occurred. There seemed general agreement that exporting
knowledge about such errors is desirable. Quite possibly the syncfs()
fix above will provide the necessary infrastructure. It's unclear as
of yet how the value would be exposed. Per-fs /sys/ entries and an
ioctl on O_PATH fds have been mentioned.
These'd error counts would not vanish due to memory pressure, and they
can be checked even without knowing which files in a specific
filesystem have been touched (e.g. when just untar-ing something).
There seemed to be fairly widespread agreement that this'd be a good
idea. Much less clearer whether somebody would do the work.
- Provide config knobs that allow to define the FS error behaviour in a
consistent way across supported filesystems. XFS currently has various
knobs controlling what happens in case of metadata errors [1]static const struct xfs_error_init xfs_error_meta_init[XFS_ERR_ERRNO_MAX] = { { .name = "default", .max_retries = XFS_ERR_RETRY_FOREVER, .retry_timeout = XFS_ERR_RETRY_FOREVER, }, { .name = "EIO", .max_retries = XFS_ERR_RETRY_FOREVER, .retry_timeout = XFS_ERR_RETRY_FOREVER, }, { .name = "ENOSPC", .max_retries = XFS_ERR_RETRY_FOREVER, .retry_timeout = XFS_ERR_RETRY_FOREVER, }, { .name = "ENODEV", .max_retries = 0, /* We can't recover from devices disappearing */ .retry_timeout = 0, }, }; (retry
forever, timeout, return up). It was proposed that this interface be
extended to also deal with data errors, and moved into generic support
code.
While the timeline is unclear, there seemed to be widespread support
for the idea. I believe Dave Chinner indicated that he at least has
plans to generalize the code.
- Stop inodes with unreported errors from being evicted. This will
guarantee that a later fsync (without an open FD) will see the
error. The memory pressure concerns here are lower than with keeping
all the failed pages in memory, and it could be optimized further.
I read some tentative agreement behind this idea, but I think it's the
by far most controversial one.
== Potential Postgres Changes ==
Several operating systems / file systems behave differently (See
e.g. [2]https://wiki.postgresql.org/wiki/Fsync_Errors, thanks Thomas) than we expected. Even the discussed changes to
e.g. linux don't get to where we thought we are. There's obviously also
the question of how to deal with kernels / OSs that have not been
updated.
Changes that appear to be necessary, even for kernels with the issues
addressed:
- Clearly we need to treat fsync() EIO, ENOSPC errors as a PANIC and
retry recovery. While ENODEV (underlying device went away) will be
persistent, it probably makes sense to treat it the same or even just
give up and shut down. One question I see here is whether we just
want to continue crash-recovery cycles, or whether we want to limit
that.
- We need more aggressive error checking on close(), for ENOSPC and
EIO. In both cases afaics we'll have to trigger a crash recovery
cycle. It's entirely possible to end up in a loop on NFS etc, but I
don't think there's a way around that.
Robert, on IM, wondered whether there'd be a race between some backend
doing a close(), triggering a PANIC, and a checkpoint succeeding. I
don't *think* so, because the error will only happen if there's
outstanding dirty data, and the checkpoint would have flushed that out
if it belonged to the current checkpointing cycle.
- The outstanding fsync request queue isn't persisted properly [3]https://archives.postgresql.org/message-id/87y3i1ia4w.fsf%40news-spur.riddles.org.uk. This
means that even if the kernel behaved the way we'd expected, we'd not
fail a second checkpoint :(. It's possible that we don't need to deal
with this because we'll henceforth PANIC, but I'd argue we should fix
that regardless. Seems like a time-bomb otherwise (e.g. after moving
to DIO somebody might want to relax the PANIC...).
- It might be a good idea to whitelist expected return codes for write()
and PANIC one ones that we did not expect. E.g. when hitting an EIO we
should probably PANIC, to get back to a known good state. Even though
it's likely that we'd again that error at fsync().
- Docs.
I think we also need to audit a few codepaths. I'd be surprised if we
PANICed appropriately on all fsyncs(), particularly around the SLRUs. I
think we need to be particularly careful around the WAL handling, I
think it's fairly likely that there's cases where we'd write out WAL in
one backend and then fsync() in another backend with a file descriptor
that has only been opened *after* the write occurred, which means we
might miss the error entirely.
Then there's the question of how we want to deal with kernels that
haven't been updated with the aforementioned changes. We could say that
we expect decent OS support and declare that we just can't handle this -
given that at least various linux versions, netbsd, openbsd, MacOS just
silently drop errors and we'd need different approaches for dealing with
that, that doesn't seem like an insane approach.
What we could do:
- forward file descriptors from backends to checkpointer (using
SCM_RIGHTS) when marking a segment dirty. That'd require some
optimizations (see [4]https://archives.postgresql.org/message-id/20180424180054.inih6bxfspgowjuc@alap3.anarazel.de) to avoid doing so repeatedly. That'd
guarantee correct behaviour in all linux kernels >= 4.13 (possibly
backported by distributions?), and I think it'd also make it vastly
more likely that errors are reported in earlier kernels.
This should be doable without a noticeable performance impact, I
believe. I don't think it'd be that hard either, but it'd be a bit of
a pain to backport it to all postgres versions, as well as a bit
invasive for that.
The infrastructure this'd likely end up building (hashtable of open
relfilenodes), would likely be useful for further things (like caching
file size).
- Add a pre-checkpoint hook that checks for filesystem errors *after*
fsyncing all the files, but *before* logging the checkpoint completion
record. Operating systems, filesystems, etc. all log the error format
differently, but for larger installations it'd not be too hard to
write code that checks their specific configuration.
While I'm a bit concerned adding user-code before a checkpoint, if
we'd do it as a shell command it seems pretty reasonable. And useful
even without concern for the fsync issue itself. Checking for IO
errors could e.g. also include checking for read errors - it'd not be
unreasonable to not want to complete a checkpoint if there'd been any
media errors.
- Use direct IO. Due to architectural performance issues in PG and the
fact that it'd not be applicable for all installations I don't think
this is a reasonable fix for the issue presented here. Although it's
independently something we should work on. It might be worthwhile to
provide a configuration that allows to force DIO to be enabled for WAL
even if replication is turned on.
- magic
Greetings,
Andres Freund
[1]: static const struct xfs_error_init xfs_error_meta_init[XFS_ERR_ERRNO_MAX] = { { .name = "default", .max_retries = XFS_ERR_RETRY_FOREVER, .retry_timeout = XFS_ERR_RETRY_FOREVER, }, { .name = "EIO", .max_retries = XFS_ERR_RETRY_FOREVER, .retry_timeout = XFS_ERR_RETRY_FOREVER, }, { .name = "ENOSPC", .max_retries = XFS_ERR_RETRY_FOREVER, .retry_timeout = XFS_ERR_RETRY_FOREVER, }, { .name = "ENODEV", .max_retries = 0, /* We can't recover from devices disappearing */ .retry_timeout = 0, }, };
static const struct xfs_error_init xfs_error_meta_init[XFS_ERR_ERRNO_MAX] = {
{ .name = "default",
.max_retries = XFS_ERR_RETRY_FOREVER,
.retry_timeout = XFS_ERR_RETRY_FOREVER,
},
{ .name = "EIO",
.max_retries = XFS_ERR_RETRY_FOREVER,
.retry_timeout = XFS_ERR_RETRY_FOREVER,
},
{ .name = "ENOSPC",
.max_retries = XFS_ERR_RETRY_FOREVER,
.retry_timeout = XFS_ERR_RETRY_FOREVER,
},
{ .name = "ENODEV",
.max_retries = 0, /* We can't recover from devices disappearing */
.retry_timeout = 0,
},
};
[2]: https://wiki.postgresql.org/wiki/Fsync_Errors
[3]: https://archives.postgresql.org/message-id/87y3i1ia4w.fsf%40news-spur.riddles.org.uk
[4]: https://archives.postgresql.org/message-id/20180424180054.inih6bxfspgowjuc@alap3.anarazel.de
On Fri, Apr 27, 2018 at 03:28:42PM -0700, Andres Freund wrote:
- We need more aggressive error checking on close(), for ENOSPC and
EIO. In both cases afaics we'll have to trigger a crash recovery
cycle. It's entirely possible to end up in a loop on NFS etc, but I
don't think there's a way around that.
If the no-space or write failures are persistent, as you mentioned
above, what is the point of going into crash recovery --- why not just
shut down? Also, since we can't guarantee that we can write any
persistent state to storage, we have no way of preventing infinite crash
recovery loops, which, based on inconsistent writes, might make things
worse. I think a single panic with no restart is the right solution.
An additional features we have talked about is running some kind of
notification shell script to inform administrators, similar to
archive_command. We need this too when sync replication fails.
--
Bruce Momjian <bruce@momjian.us> http://momjian.us
EnterpriseDB http://enterprisedb.com
+ As you are, so once was I. As I am, so you will be. +
+ Ancient Roman grave inscription +
Hi,
On 2018-04-27 19:04:47 -0400, Bruce Momjian wrote:
On Fri, Apr 27, 2018 at 03:28:42PM -0700, Andres Freund wrote:
- We need more aggressive error checking on close(), for ENOSPC and
EIO. In both cases afaics we'll have to trigger a crash recovery
cycle. It's entirely possible to end up in a loop on NFS etc, but I
don't think there's a way around that.If the no-space or write failures are persistent, as you mentioned
above, what is the point of going into crash recovery --- why not just
shut down?
Well, I mentioned that as an alternative in my email. But for one we
don't really have cases where we do that right now, for another we can't
really differentiate between a transient and non-transient state. It's
entirely possible that the admin on the system that ran out of space
fixes things, clearing up the problem.
Also, since we can't guarantee that we can write any persistent state
to storage, we have no way of preventing infinite crash recovery
loops, which, based on inconsistent writes, might make things worse.
How would it make things worse?
An additional features we have talked about is running some kind of
notification shell script to inform administrators, similar to
archive_command. We need this too when sync replication fails.
To me that seems like a feature independent of this thread.
Greetings,
Andres Freund
On Fri, Apr 27, 2018 at 04:10:43PM -0700, Andres Freund wrote:
Hi,
On 2018-04-27 19:04:47 -0400, Bruce Momjian wrote:
On Fri, Apr 27, 2018 at 03:28:42PM -0700, Andres Freund wrote:
- We need more aggressive error checking on close(), for ENOSPC and
EIO. In both cases afaics we'll have to trigger a crash recovery
cycle. It's entirely possible to end up in a loop on NFS etc, but I
don't think there's a way around that.If the no-space or write failures are persistent, as you mentioned
above, what is the point of going into crash recovery --- why not just
shut down?Well, I mentioned that as an alternative in my email. But for one we
don't really have cases where we do that right now, for another we can't
really differentiate between a transient and non-transient state. It's
entirely possible that the admin on the system that ran out of space
fixes things, clearing up the problem.
True, but if we get a no-space error, odds are it will not be fixed at
the time we are failing. Wouldn't the administrator check that the
server is still running after they free the space?
Also, since we can't guarantee that we can write any persistent state
to storage, we have no way of preventing infinite crash recovery
loops, which, based on inconsistent writes, might make things worse.How would it make things worse?
Uh, I can imagine some writes working and some not, and getting things
more inconsistent. I would say at least that we don't know.
An additional features we have talked about is running some kind of
notification shell script to inform administrators, similar to
archive_command. We need this too when sync replication fails.To me that seems like a feature independent of this thread.
Well, if we are introducing new panic-and-not-restart behavior, we might
need this new feature.
--
Bruce Momjian <bruce@momjian.us> http://momjian.us
EnterpriseDB http://enterprisedb.com
+ As you are, so once was I. As I am, so you will be. +
+ Ancient Roman grave inscription +
On 2018-04-27 19:38:30 -0400, Bruce Momjian wrote:
On Fri, Apr 27, 2018 at 04:10:43PM -0700, Andres Freund wrote:
Hi,
On 2018-04-27 19:04:47 -0400, Bruce Momjian wrote:
On Fri, Apr 27, 2018 at 03:28:42PM -0700, Andres Freund wrote:
- We need more aggressive error checking on close(), for ENOSPC and
EIO. In both cases afaics we'll have to trigger a crash recovery
cycle. It's entirely possible to end up in a loop on NFS etc, but I
don't think there's a way around that.If the no-space or write failures are persistent, as you mentioned
above, what is the point of going into crash recovery --- why not just
shut down?Well, I mentioned that as an alternative in my email. But for one we
don't really have cases where we do that right now, for another we can't
really differentiate between a transient and non-transient state. It's
entirely possible that the admin on the system that ran out of space
fixes things, clearing up the problem.True, but if we get a no-space error, odds are it will not be fixed at
the time we are failing. Wouldn't the administrator check that the
server is still running after they free the space?
I'd assume it's pretty common that those are separate teams. Given that
we currently don't behave that way for other cases where we *already*
can enter crash-recovery loops I don't think we need to introduce that
here. It's far more common to enter this kind of problem with pg_xlog
filling up the ordinary way. And that can lead to such loops.
Also, since we can't guarantee that we can write any persistent state
to storage, we have no way of preventing infinite crash recovery
loops, which, based on inconsistent writes, might make things worse.How would it make things worse?
Uh, I can imagine some writes working and some not, and getting things
more inconsistent. I would say at least that we don't know.
Recovery needs to fix that or we're lost anyway. And we'll retry exactly
the same writes each round.
An additional features we have talked about is running some kind of
notification shell script to inform administrators, similar to
archive_command. We need this too when sync replication fails.To me that seems like a feature independent of this thread.
Well, if we are introducing new panic-and-not-restart behavior, we might
need this new feature.
I don't see how this follows. It's easier to externally script
notification for the server having died, than doing it for crash
restarts. That's why we have restart_after_crash=false... There might
be some arguments for this type of notification, but I don't think it
should be conflated with the problem here. Nor is it guaranteed that
such a script could do much, given that disks might be failing and such.
Greetings,
Andres Freund
On 28 April 2018 at 06:28, Andres Freund <andres@anarazel.de> wrote:
Hi,
I thought I'd send this separately from [0] as the issue has become more
general than what was mentioned in that thread, and it went off into
various weeds.
Thanks very much for going and for the great summary.
- Actually marking files as persistently failed would require filesystem
changes, and filesystem metadata IO, far from guaranteed in failure
scenarios.
Yeah, I've avoided suggesting anything like that because it seems way
too likely to lead to knock-on errors.
Like malloc'ing in an OOM path, just don't.
The second major type of proposal was using direct-IO. That'd generally
be a desirable feature, but a) would require some significant changes to
postgres to be performant, b) isn't really applicable for the large
percentage of installations that aren't tuned reasonably well, because
at the moment the OS page cache functions as a memory-pressure aware
extension of postgres' page cache.
Yeah. I've avoided advocating for O_DIRECT because it's a big job
(understatement). We'd need to pay so much more attention to details
of storage layout if we couldn't rely as much on the kernel neatly
organising and queuing everything for us, too.
At the risk of displaying my relative ignorance of direct I/O: Does
O_DIRECT without O_SYNC even provide a strong guarantee that when you
close() the file, all I/O has reliably succeeded? It must've gone
through the FS layer, but don't FSes do various caching and
reorganisation too? Can the same issue arise in other ways unless we
also fsync() before close() or write O_SYNC?
At one point I looked into using AIO instead. But last I looked it was
pretty spectacularly quirky when it comes to reliably flushing, and
outright broken on some versions. In any case, our multiprocessing
model would make tracking completions annoying, likely more so than
the sort of FD handoff games we've discussed.
Another topic brought up in this thread was the handling of ENOSPC
errors that aren't triggered on a filesystem level, but rather are
triggered by thin provisioning. On linux that currently apprently lead
to page cache contents being lost (and errors "eaten") in a lot of
places, including just when doing a write().
... wow.
Is that with lvm-thin?
The thin provisioning I was mainly concerned with is SAN-based thin
provisioning, which looks like a normal iSCSI target or a normal LUN
on a HBA to Linux. Then it starts failing writes with a weird
potentially vendor-specific sense error if it runs out of backing
store. How that's handled likely depends on the specific error, the
driver, which FS you use, etc. In the case I saw, multipath+lvm+xfs,
it resulted in lost writes and fsync() errors being reported once, per
the start of the original thread.
In a lot of cases it's
pretty much expected that the file system will just hang or react
unpredictably upon space exhaustion. My reading is that the block-layer
thin provisioning code is still pretty fresh, and should only be used
with great care. The only way to halfway reliably use it appears to
change the configuration so space exhaustion blocks until admin
intervention (at least dm-thinp provides allows that).
Seems that should go in the OS-specific configuration part of the
docs, along with the advice I gave on the original thread re
configuring multipath no_path_retries.
There's some clear need to automate some more testing in this area so
that future behaviour changes don't surprise us.
We don't routinely test ENOSPC (or memory exhaustion, or crashes) in
PostgreSQL even on bog standard setups.
Like the performance farm discussion, this is something I'd like to
pick up at some point. I'm going to need to talk to the team I work
with regarding time/resources allocation, but I think it's important
that we make such testing more of a routine thing.
- Matthew Wilcox proposed (and posted a patch) that'd partially revert
behaviour to the pre v4.13 world, by *also* reporting errors to
"newer" file-descriptors if the error hasn't previously been
reported. That'd still not guarantee that the error is reported
(memory pressure could evict information without open fd), but in most
situations we'll again get the error in the checkpointer.This seems largely be agreed upon. It's unclear whether it'll go into
the stable backports for still-maintained >= v4.13 kernels.
That seems very sensible. In our case we're very unlikely to have some
other unrelated process come in and fsync() our files for us.
I'd want to be sure the report didn't get eaten by sync() or syncfs() though.
- syncfs() will be fixed so it reports errors properly - that'll likely
require passing it an O_PATH filedescriptor to have space to store the
errseq_t value that allows discerning already reported and new errors.No patch has appeared yet, but the behaviour seems largely agreed
upon.
Good, but as you noted, of limited use to us unless we want to force
users to manage space for temporary and unlogged relations completely
separately.
I wonder if we could convince the kernel to offer a file_sync_mode
xattr to control this? (Hint: I'm already running away in a mylar fire
suit).
- Make per-filesystem error counts available in a uniform (i.e. same for
every supporting fs) manner. Right now it's very hard to figure out
whether errors occurred. There seemed general agreement that exporting
knowledge about such errors is desirable. Quite possibly the syncfs()
fix above will provide the necessary infrastructure. It's unclear as
of yet how the value would be exposed. Per-fs /sys/ entries and an
ioctl on O_PATH fds have been mentioned.These'd error counts would not vanish due to memory pressure, and they
can be checked even without knowing which files in a specific
filesystem have been touched (e.g. when just untar-ing something).There seemed to be fairly widespread agreement that this'd be a good
idea. Much less clearer whether somebody would do the work.- Provide config knobs that allow to define the FS error behaviour in a
consistent way across supported filesystems. XFS currently has various
knobs controlling what happens in case of metadata errors [1] (retry
forever, timeout, return up). It was proposed that this interface be
extended to also deal with data errors, and moved into generic support
code.While the timeline is unclear, there seemed to be widespread support
for the idea. I believe Dave Chinner indicated that he at least has
plans to generalize the code.
That's great. It sounds like this has revitalised some interest in the
error reporting and might yield some more general cleanups :)
- Stop inodes with unreported errors from being evicted. This will
guarantee that a later fsync (without an open FD) will see the
error. The memory pressure concerns here are lower than with keeping
all the failed pages in memory, and it could be optimized further.I read some tentative agreement behind this idea, but I think it's the
by far most controversial one.
The main issue there would seem to be cases of whole-FS failure like
the USB-key-yank example. You're going to have to be able to get rid
of them at some point.
- Clearly we need to treat fsync() EIO, ENOSPC errors as a PANIC and
retry recovery. While ENODEV (underlying device went away) will be
persistent, it probably makes sense to treat it the same or even just
give up and shut down. One question I see here is whether we just
want to continue crash-recovery cycles, or whether we want to limit
that.
Right now, we'll panic once, then panic again in redo if the error
persists and give up.
On some systems, and everywhere that Pg is directly user-managed with
pg_ctl, that'll leave Pg down until the operator intervenes. Some init
systems will restart the postmaster automatically. Some will give up
after a few tries. Some will back off retries over time. It depends on
the init system. I'm not sure that's a great outcome.
So rather than giving up if redo fails, we might want to offer a knob
to retry, possibly with pause/backoff. I'm sure people currently
expect PostgreSQL to try to stay up and recover, like it does after a
segfault or most other errors.
Personally I prefer to run Pg with restart_after_crash=off and let the
init system launch a new postmaster, but that's not an option unless
you have a sensible init.
- We need more aggressive error checking on close(), for ENOSPC and
EIO. In both cases afaics we'll have to trigger a crash recovery
cycle. It's entirely possible to end up in a loop on NFS etc, but I
don't think there's a way around that.Robert, on IM, wondered whether there'd be a race between some backend
doing a close(), triggering a PANIC, and a checkpoint succeeding. I
don't *think* so, because the error will only happen if there's
outstanding dirty data, and the checkpoint would have flushed that out
if it belonged to the current checkpointing cycle.
Even if it's possible (which it sounds like it probably isn't), it
might also be one of those corner-cases-of-corner-cases where we just
shrug and worry about bigger fish.
- The outstanding fsync request queue isn't persisted properly [3]. This
means that even if the kernel behaved the way we'd expected, we'd not
fail a second checkpoint :(. It's possible that we don't need to deal
with this because we'll henceforth PANIC, but I'd argue we should fix
that regardless. Seems like a time-bomb otherwise (e.g. after moving
to DIO somebody might want to relax the PANIC...).
Huh! Good find. That definitely merits fixing.
- It might be a good idea to whitelist expected return codes for write()
and PANIC one ones that we did not expect. E.g. when hitting an EIO we
should probably PANIC, to get back to a known good state. Even though
it's likely that we'd again that error at fsync().- Docs.
Yep. Especially OS-specific configuration for known dangerous setups
(lvm-thin, multipath), etc. I imagine we can distill a lot of it from
the discussion and simplify a bit.
I think we also need to audit a few codepaths. I'd be surprised if we
PANICed appropriately on all fsyncs(), particularly around the SLRUs.
We _definitely_ do not, see the patch I sent on the other thread.
Then there's the question of how we want to deal with kernels that
haven't been updated with the aforementioned changes. We could say that
we expect decent OS support and declare that we just can't handle this -
given that at least various linux versions, netbsd, openbsd, MacOS just
silently drop errors and we'd need different approaches for dealing with
that, that doesn't seem like an insane approach.
What we could do:
- forward file descriptors from backends to checkpointer (using
SCM_RIGHTS) when marking a segment dirty. That'd require some
optimizations (see [4]) to avoid doing so repeatedly. That'd
guarantee correct behaviour in all linux kernels >= 4.13 (possibly
backported by distributions?), and I think it'd also make it vastly
more likely that errors are reported in earlier kernels.
It'd be interesting to see if other platforms that support fd passing
will give us the desired behaviour too. But even if it only helps on
Linux, that's a huge majority of the PostgreSQL deployments these
days.
- Add a pre-checkpoint hook that checks for filesystem errors *after*
fsyncing all the files, but *before* logging the checkpoint completion
record. Operating systems, filesystems, etc. all log the error format
differently, but for larger installations it'd not be too hard to
write code that checks their specific configuration.
I looked into using trace event file descriptors for this, btw, but
we'd need CAP_SYS_ADMIN to create one that captured events for other
processes. Plus filtering the events to find only events for the files
/ file systems of interest would be far from trivial. And I don't know
what guarantees we have about when events are delivered.
I'd love to be able to use inotify for this, but again, that'd only be
a new-kernels thing since it'd need an inotify extension to report I/O
errors.
Presumably mostly this check would land up looking at dmesg.
I'm not convinced it'd get widely deployed and widely used, or that
it'd be used correctly when people tried to use it. Look at the
hideous mess that most backup/standby creation scripts,
archive_command scripts, etc are.
- Use direct IO. Due to architectural performance issues in PG and the
fact that it'd not be applicable for all installations I don't think
this is a reasonable fix for the issue presented here. Although it's
independently something we should work on. It might be worthwhile to
provide a configuration that allows to force DIO to be enabled for WAL
even if replication is turned on.
Seems like a long term goal, but you've noted elsewhere that doing it
well would be hard. I suspect we'd need writer threads, we'd need to
know more about the underlying FS/storage layout to make better
decisions about write parallelism, etc. We get away with a lot right
now by letting the kernel and buffered I/O sort that out.
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
Greetings,
* Andres Freund (andres@anarazel.de) wrote:
On 2018-04-27 19:38:30 -0400, Bruce Momjian wrote:
On Fri, Apr 27, 2018 at 04:10:43PM -0700, Andres Freund wrote:
On 2018-04-27 19:04:47 -0400, Bruce Momjian wrote:
On Fri, Apr 27, 2018 at 03:28:42PM -0700, Andres Freund wrote:
- We need more aggressive error checking on close(), for ENOSPC and
EIO. In both cases afaics we'll have to trigger a crash recovery
cycle. It's entirely possible to end up in a loop on NFS etc, but I
don't think there's a way around that.If the no-space or write failures are persistent, as you mentioned
above, what is the point of going into crash recovery --- why not just
shut down?Well, I mentioned that as an alternative in my email. But for one we
don't really have cases where we do that right now, for another we can't
really differentiate between a transient and non-transient state. It's
entirely possible that the admin on the system that ran out of space
fixes things, clearing up the problem.True, but if we get a no-space error, odds are it will not be fixed at
the time we are failing. Wouldn't the administrator check that the
server is still running after they free the space?I'd assume it's pretty common that those are separate teams. Given that
we currently don't behave that way for other cases where we *already*
can enter crash-recovery loops I don't think we need to introduce that
here. It's far more common to enter this kind of problem with pg_xlog
filling up the ordinary way. And that can lead to such loops.
When we crash-restart, we also go through and clean things up some, no?
Seems like that gives us the potential to end up fixing things ourselves
and allowing the crash-restart to succeed.
Consider unlogged tables, temporary tables, on-disk sorts, etc. It's
entirely common for a bad query to run the system out of disk space (but
have a write of a regular table be what discovers the out-of-space
problem...) and if we crash-restart properly then we'd hopefully clean
things out, freeing up space, and allowing us to come back up.
Now, of course, ideally admins would set up temp tablespaces and
segregate WAL onto its own filesystem, etc, but...
Thanks!
Stephen
Greetings,
* Craig Ringer (craig@2ndquadrant.com) wrote:
On 28 April 2018 at 06:28, Andres Freund <andres@anarazel.de> wrote:
- Add a pre-checkpoint hook that checks for filesystem errors *after*
fsyncing all the files, but *before* logging the checkpoint completion
record. Operating systems, filesystems, etc. all log the error format
differently, but for larger installations it'd not be too hard to
write code that checks their specific configuration.I looked into using trace event file descriptors for this, btw, but
we'd need CAP_SYS_ADMIN to create one that captured events for other
processes. Plus filtering the events to find only events for the files
/ file systems of interest would be far from trivial. And I don't know
what guarantees we have about when events are delivered.I'd love to be able to use inotify for this, but again, that'd only be
a new-kernels thing since it'd need an inotify extension to report I/O
errors.Presumably mostly this check would land up looking at dmesg.
I'm not convinced it'd get widely deployed and widely used, or that
it'd be used correctly when people tried to use it. Look at the
hideous mess that most backup/standby creation scripts,
archive_command scripts, etc are.
Agree with more-or-less everything you've said here, but a big +1 on
this. If we do end up going down this route we have *got* to provide
scripts which we know work and have been tested and are well maintained
on the popular OS's for the popular filesystems and make it clear that
we've tested those and not others. We definitely shouldn't put
something in our docs that is effectively an example of the interface
but not an actual command that anyone should be using.
Thanks!
Stephen
On 27 April 2018 at 15:28, Andres Freund <andres@anarazel.de> wrote:
- Add a pre-checkpoint hook that checks for filesystem errors *after*
fsyncing all the files, but *before* logging the checkpoint completion
record. Operating systems, filesystems, etc. all log the error format
differently, but for larger installations it'd not be too hard to
write code that checks their specific configuration.While I'm a bit concerned adding user-code before a checkpoint, if
we'd do it as a shell command it seems pretty reasonable. And useful
even without concern for the fsync issue itself. Checking for IO
errors could e.g. also include checking for read errors - it'd not be
unreasonable to not want to complete a checkpoint if there'd been any
media errors.
It seems clear that we need to evaluate our compatibility not just
with an OS, as we do now, but with an OS/filesystem.
Although people have suggested some approaches, I'm more interested in
discovering how we can be certain we got it right.
And the end result seems to be that PostgreSQL will be forced, in the
short term, to declare certain combinations of OS/filesystem
unsupported, with clear warning sent out to users.
Adding a pre-checkpoint hook encourages people to fix this themselves
without reporting issues, so I initially oppose this until we have a
clearer argument as to why we need it. The answer is not to make this
issue more obscure, but to make it more public.
- Use direct IO. Due to architectural performance issues in PG and the
fact that it'd not be applicable for all installations I don't think
this is a reasonable fix for the issue presented here. Although it's
independently something we should work on. It might be worthwhile to
provide a configuration that allows to force DIO to be enabled for WAL
even if replication is turned on.
"Use DirectIO" is roughly same suggestion as "don't trust Linux filesystems".
It would be a major admission of defeat for us to take that as our
main route to a solution.
The people I've spoken to so far have encouraged us to continue
working with the filesystem layer, offering encouragement of our
decision to use filesystems.
--
Simon Riggs http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
Hi,
On Sat, Apr 28, 2018 at 11:21:20AM -0400, Stephen Frost wrote:
* Craig Ringer (craig@2ndquadrant.com) wrote:
On 28 April 2018 at 06:28, Andres Freund <andres@anarazel.de> wrote:
- Add a pre-checkpoint hook that checks for filesystem errors *after*
fsyncing all the files, but *before* logging the checkpoint completion
record. Operating systems, filesystems, etc. all log the error format
differently, but for larger installations it'd not be too hard to
write code that checks their specific configuration.I looked into using trace event file descriptors for this, btw, but
we'd need CAP_SYS_ADMIN to create one that captured events for other
processes. Plus filtering the events to find only events for the files
/ file systems of interest would be far from trivial. And I don't know
what guarantees we have about when events are delivered.I'd love to be able to use inotify for this, but again, that'd only be
a new-kernels thing since it'd need an inotify extension to report I/O
errors.Presumably mostly this check would land up looking at dmesg.
I'm not convinced it'd get widely deployed and widely used, or that
it'd be used correctly when people tried to use it. Look at the
hideous mess that most backup/standby creation scripts,
archive_command scripts, etc are.Agree with more-or-less everything you've said here, but a big +1 on
this. If we do end up going down this route we have *got* to provide
scripts which we know work and have been tested and are well maintained
on the popular OS's for the popular filesystems and make it clear that
we've tested those and not others. We definitely shouldn't put
something in our docs that is effectively an example of the interface
but not an actual command that anyone should be using.
This dmesg-checking has been mentioned several times now, but IME
enterprise distributions (or server ops teams?) seem to tighten access
to dmesg and /var/log to non-root users, including postgres.
Well, or just vanilla Debian stable apparently:
postgres@fock:~$ dmesg
dmesg: read kernel buffer failed: Operation not permitted
Is it really a useful expectation that the postgres user will be able to
trawl system logs for I/O errors? Or are we expecting the sysadmins (in
case they are distinct from the DBAs) to setup sudo and/or relax
permissions for this everywhere? We should document this requirement
properly at least then.
The netlink thing from Google that Tet Ts'O mentioned would probably
work around that, but if that is opened up it would not be deployed
anytime soon either.
Michael
--
Michael Banck
Projektleiter / Senior Berater
Tel.: +49 2166 9901-171
Fax: +49 2166 9901-100
Email: michael.banck@credativ.de
credativ GmbH, HRB M�nchengladbach 12080
USt-ID-Nummer: DE204566209
Trompeterallee 108, 41189 M�nchengladbach
Gesch�ftsf�hrung: Dr. Michael Meskes, J�rg Folz, Sascha Heuer
Hi,
On 2018-04-28 11:10:54 -0400, Stephen Frost wrote:
When we crash-restart, we also go through and clean things up some, no?
Seems like that gives us the potential to end up fixing things ourselves
and allowing the crash-restart to succeed.
Sure, there's the potential for that. But it's quite possible to be
missing a lot of free space over NFS (this really isn't much of an issue
for local FS, at least not on linux) in a workload with rapidly
expanding space usage. And even if you recover, you could just hit the
issue again shortly afterwards.
Greetings,
Andres Freund
Hi,
On 2018-04-28 17:35:48 +0200, Michael Banck wrote:
This dmesg-checking has been mentioned several times now, but IME
enterprise distributions (or server ops teams?) seem to tighten access
to dmesg and /var/log to non-root users, including postgres.Well, or just vanilla Debian stable apparently:
postgres@fock:~$ dmesg
dmesg: read kernel buffer failed: Operation not permittedIs it really a useful expectation that the postgres user will be able to
trawl system logs for I/O errors? Or are we expecting the sysadmins (in
case they are distinct from the DBAs) to setup sudo and/or relax
permissions for this everywhere? We should document this requirement
properly at least then.
I'm not a huge fan of this approach, but yes, that'd be necessary. It's
not that problematic to have to change /dev/kmsg permissions imo. Adding
a read group / acl seems quite doable.
The netlink thing from Google that Tet Ts'O mentioned would probably
work around that, but if that is opened up it would not be deployed
anytime soon either.
Yea, that seems irrelevant for now.
Greetings,
Andres Freund
Hi,
On 2018-04-28 08:25:53 -0700, Simon Riggs wrote:
- Use direct IO. Due to architectural performance issues in PG and the
fact that it'd not be applicable for all installations I don't think
this is a reasonable fix for the issue presented here. Although it's
independently something we should work on. It might be worthwhile to
provide a configuration that allows to force DIO to be enabled for WAL
even if replication is turned on."Use DirectIO" is roughly same suggestion as "don't trust Linux filesystems".
I want to emphasize that this is NOT a linux only issue. It's a problem
across a number of operating systems, including linux.
It would be a major admission of defeat for us to take that as our
main route to a solution.
Well, I think we were wrong to not engineer towards DIO. There's just
too many issues with buffered IO to not have a supported path for
DIO. But given that it's unrealistic to do so without major work, and
wouldn't be applicable for all installations (shared_buffer size becomes
critical), I don't think it matters that much for the issue discussed
here.
The people I've spoken to so far have encouraged us to continue
working with the filesystem layer, offering encouragement of our
decision to use filesystems.
There's a lot of people disagreeing with it too.
Greetings,
Andres Freund
Hi,
On 2018-04-28 20:00:25 +0800, Craig Ringer wrote:
On 28 April 2018 at 06:28, Andres Freund <andres@anarazel.de> wrote:
The second major type of proposal was using direct-IO. That'd generally
be a desirable feature, but a) would require some significant changes to
postgres to be performant, b) isn't really applicable for the large
percentage of installations that aren't tuned reasonably well, because
at the moment the OS page cache functions as a memory-pressure aware
extension of postgres' page cache.Yeah. I've avoided advocating for O_DIRECT because it's a big job
(understatement). We'd need to pay so much more attention to details
of storage layout if we couldn't rely as much on the kernel neatly
organising and queuing everything for us, too.At the risk of displaying my relative ignorance of direct I/O: Does
O_DIRECT without O_SYNC even provide a strong guarantee that when you
close() the file, all I/O has reliably succeeded? It must've gone
through the FS layer, but don't FSes do various caching and
reorganisation too? Can the same issue arise in other ways unless we
also fsync() before close() or write O_SYNC?
No, not really. There's generally two categories of IO here: Metadata IO
and data IO. The filesystem's metadata IO a) has a lot more error
checking (including things like remount-ro, stalling the filesystem on
errors etc), b) isn't direct IO itself. For some filesystem metadata
operations you'll still need fsyncs, but the *data* is flushed if use
use DIO. I'd personally use O_DSYNC | O_DIRECT, and have the metadata
operations guaranteed by fsyncs. You'd need the current fsyncs for
renaming, and probably some fsyncs for file extensions. The latter to
make sure the filesystem has written the metadata change.
At one point I looked into using AIO instead. But last I looked it was
pretty spectacularly quirky when it comes to reliably flushing, and
outright broken on some versions. In any case, our multiprocessing
model would make tracking completions annoying, likely more so than
the sort of FD handoff games we've discussed.
AIO pretty much only works sensibly with DIO.
Another topic brought up in this thread was the handling of ENOSPC
errors that aren't triggered on a filesystem level, but rather are
triggered by thin provisioning. On linux that currently apprently lead
to page cache contents being lost (and errors "eaten") in a lot of
places, including just when doing a write().... wow.
Is that with lvm-thin?
I think both dm and lvm (I typed llvm thrice) based thin
provisioning. The FS code basically didn't expect ENOSPC being returned
from storage, but suddenly the storage layer started returning it...
The thin provisioning I was mainly concerned with is SAN-based thin
provisioning, which looks like a normal iSCSI target or a normal LUN
on a HBA to Linux. Then it starts failing writes with a weird
potentially vendor-specific sense error if it runs out of backing
store. How that's handled likely depends on the specific error, the
driver, which FS you use, etc. In the case I saw, multipath+lvm+xfs,
it resulted in lost writes and fsync() errors being reported once, per
the start of the original thread.
I think the concerns are largely the same for that. You'll have to
configure the SAN to block in that case.
- Matthew Wilcox proposed (and posted a patch) that'd partially revert
behaviour to the pre v4.13 world, by *also* reporting errors to
"newer" file-descriptors if the error hasn't previously been
reported. That'd still not guarantee that the error is reported
(memory pressure could evict information without open fd), but in most
situations we'll again get the error in the checkpointer.This seems largely be agreed upon. It's unclear whether it'll go into
the stable backports for still-maintained >= v4.13 kernels.That seems very sensible. In our case we're very unlikely to have some
other unrelated process come in and fsync() our files for us.I'd want to be sure the report didn't get eaten by sync() or syncfs() though.
It doesn't. Basically every fd has an errseq_t value copied into it at
open.
- syncfs() will be fixed so it reports errors properly - that'll likely
require passing it an O_PATH filedescriptor to have space to store the
errseq_t value that allows discerning already reported and new errors.No patch has appeared yet, but the behaviour seems largely agreed
upon.Good, but as you noted, of limited use to us unless we want to force
users to manage space for temporary and unlogged relations completely
separately.
Well, I think it'd still be ok as a backstop if it had decent error
semantics. We don't checkpoint that often, and doing the syncing via
syncfs() is considerably more efficient than individual fsync()s. But
given it's currently buggy that tradeoff is moot.
I wonder if we could convince the kernel to offer a file_sync_mode
xattr to control this? (Hint: I'm already running away in a mylar fire
suit).
Err. I am fairly sure you're not going to get anywhere with that. Given
we're concerned about existing kernels, I doubt it'd help us much anyway.
- Stop inodes with unreported errors from being evicted. This will
guarantee that a later fsync (without an open FD) will see the
error. The memory pressure concerns here are lower than with keeping
all the failed pages in memory, and it could be optimized further.I read some tentative agreement behind this idea, but I think it's the
by far most controversial one.The main issue there would seem to be cases of whole-FS failure like
the USB-key-yank example. You're going to have to be able to get rid
of them at some point.
It's not actually a real problem (despite initially being brought up a
number of times by kernel people). There's a separate error for that
(ENODEV), and filesystems already handle it differently. Once that's
returned, fsyncs() etc are just shortcut to ENODEV.
What we could do:
- forward file descriptors from backends to checkpointer (using
SCM_RIGHTS) when marking a segment dirty. That'd require some
optimizations (see [4]) to avoid doing so repeatedly. That'd
guarantee correct behaviour in all linux kernels >= 4.13 (possibly
backported by distributions?), and I think it'd also make it vastly
more likely that errors are reported in earlier kernels.It'd be interesting to see if other platforms that support fd passing
will give us the desired behaviour too. But even if it only helps on
Linux, that's a huge majority of the PostgreSQL deployments these
days.
Afaict it'd not help all of them. It does provide guarantees against the
inode being evicted on pretty much all OSs, but not all of them have an
error counter there...
- Use direct IO. Due to architectural performance issues in PG and the
fact that it'd not be applicable for all installations I don't think
this is a reasonable fix for the issue presented here. Although it's
independently something we should work on. It might be worthwhile to
provide a configuration that allows to force DIO to be enabled for WAL
even if replication is turned on.Seems like a long term goal, but you've noted elsewhere that doing it
well would be hard. I suspect we'd need writer threads, we'd need to
know more about the underlying FS/storage layout to make better
decisions about write parallelism, etc. We get away with a lot right
now by letting the kernel and buffered I/O sort that out.
We're a *lot* slower due to it.
Don't think you would need writer threads, "just" a bgwriter that
actually works and provides clean buffers unless the machine is
overloaded. I've posted a patch that adds that. On the write side you
then additionally need write combining (doing one writes for several
on-disk-consecutive buffers), which isn't trivial to add currently. The
bigger issue than writes is actually doing reads nicely. There's no
readahead anymore, and we'd not have the kernel backstopping our bad
caching decisions anymore.
Greetings,
Andres Freund
On 29 April 2018 at 00:15, Andres Freund <andres@anarazel.de> wrote:
Hi,
On 2018-04-28 08:25:53 -0700, Simon Riggs wrote:
- Use direct IO. Due to architectural performance issues in PG and the
fact that it'd not be applicable for all installations I don't think
this is a reasonable fix for the issue presented here. Although it's
independently something we should work on. It might be worthwhile to
provide a configuration that allows to force DIO to be enabled for WAL
even if replication is turned on."Use DirectIO" is roughly same suggestion as "don't trust Linux filesystems".
I want to emphasize that this is NOT a linux only issue. It's a problem
across a number of operating systems, including linux.It would be a major admission of defeat for us to take that as our
main route to a solution.Well, I think we were wrong to not engineer towards DIO. There's just
too many issues with buffered IO to not have a supported path for
DIO. But given that it's unrealistic to do so without major work, and
wouldn't be applicable for all installations (shared_buffer size becomes
critical), I don't think it matters that much for the issue discussed
here.
20/20 hindsight, really. Not much to be done now.
Even with the work you and others have done on shared_buffers
scalability, there's likely still improvement needed there if it
becomes more important to evict buffers into per-device queues, etc,
too.
Personally I'd rather not have to write half the kernel's job because
the kernel doesn't feel like doing it :( . I'd kind of hoped to go in
the other direction if anything, with some kind of pseudo-write op
that let us swap a dirty shared_buffers entry from our shared_buffers
into the OS dirty buffer cache (on Linux at least) and let it handle
writeback, so we reduce double-buffering. Ha! So much for that!
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
On 28 April 2018 at 23:25, Simon Riggs <simon@2ndquadrant.com> wrote:
On 27 April 2018 at 15:28, Andres Freund <andres@anarazel.de> wrote:
- Add a pre-checkpoint hook that checks for filesystem errors *after*
fsyncing all the files, but *before* logging the checkpoint completion
record. Operating systems, filesystems, etc. all log the error format
differently, but for larger installations it'd not be too hard to
write code that checks their specific configuration.While I'm a bit concerned adding user-code before a checkpoint, if
we'd do it as a shell command it seems pretty reasonable. And useful
even without concern for the fsync issue itself. Checking for IO
errors could e.g. also include checking for read errors - it'd not be
unreasonable to not want to complete a checkpoint if there'd been any
media errors.It seems clear that we need to evaluate our compatibility not just
with an OS, as we do now, but with an OS/filesystem.Although people have suggested some approaches, I'm more interested in
discovering how we can be certain we got it right.
TBH, we can't be certain, because there are too many failure modes,
some of which we can't really simulate in practical ways, or automated
ways.
But there are definitely steps we can take:
- Test the stack of FS, LVM (if any) etc with the dmsetup 'flakey'
target and a variety of workloads designed to hit errors at various
points. Some form of torture test.
- Almost up the device and see what happens if we write() then fsync()
enough to fill it.
- Plug-pull storage and see what happens, especially for multipath/iSCSI/SAN.
Experience with pg_test_fsync shows that it can also be hard to
reliably interpret the results of tests.
Again I'd like to emphasise that this is really only a significant
risk for a few configurations. Yes, it could result in Pg not failing
a checkpoint when it should if, say, your disk has a bad block it
can't repair and remap. But as Andres has pointed out in the past,
those sorts local storage failure cases tend toward "you're kind of
screwed anyway". It's only a serious concern when I/O errors are part
of the storage's accepted operation, as in multipath with default
settings.
We _definitely_ need to warn multipath users that the defaults are insane.
- Use direct IO. Due to architectural performance issues in PG and the
fact that it'd not be applicable for all installations I don't think
this is a reasonable fix for the issue presented here. Although it's
independently something we should work on. It might be worthwhile to
provide a configuration that allows to force DIO to be enabled for WAL
even if replication is turned on."Use DirectIO" is roughly same suggestion as "don't trust Linux filesystems".
Surprisingly, that seems to be a lot of what's coming out of Linux
developers. Reliable buffered I/O? Why would you try to do that?
I know that's far from a universal position, though, and it sounds
like things were more productive in Andres's discussions at the meet.
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
On 28 April 2018 at 08:25, Simon Riggs <simon@2ndquadrant.com> wrote:
On 27 April 2018 at 15:28, Andres Freund <andres@anarazel.de> wrote:
- Add a pre-checkpoint hook that checks for filesystem errors *after*
fsyncing all the files, but *before* logging the checkpoint completion
record. Operating systems, filesystems, etc. all log the error format
differently, but for larger installations it'd not be too hard to
write code that checks their specific configuration.While I'm a bit concerned adding user-code before a checkpoint, if
we'd do it as a shell command it seems pretty reasonable. And useful
even without concern for the fsync issue itself. Checking for IO
errors could e.g. also include checking for read errors - it'd not be
unreasonable to not want to complete a checkpoint if there'd been any
media errors.It seems clear that we need to evaluate our compatibility not just
with an OS, as we do now, but with an OS/filesystem.Although people have suggested some approaches, I'm more interested in
discovering how we can be certain we got it right.And the end result seems to be that PostgreSQL will be forced, in the
short term, to declare certain combinations of OS/filesystem
unsupported, with clear warning sent out to users.Adding a pre-checkpoint hook encourages people to fix this themselves
without reporting issues, so I initially oppose this until we have a
clearer argument as to why we need it. The answer is not to make this
issue more obscure, but to make it more public.
Thinking some more, I think I understand, but please explain if not.
We need behavior that varies according to OS and filesystem, which
varies per tablespace.
We could have that variable behavior using
* a hook
* a set of GUC parameters that can be set at tablespace level
* a separate config file for each tablespace
My preference would be to avoid a hook.
--
Simon Riggs http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On 28 April 2018 at 09:15, Andres Freund <andres@anarazel.de> wrote:
Hi,
On 2018-04-28 08:25:53 -0700, Simon Riggs wrote:
- Use direct IO. Due to architectural performance issues in PG and the
fact that it'd not be applicable for all installations I don't think
this is a reasonable fix for the issue presented here. Although it's
independently something we should work on. It might be worthwhile to
provide a configuration that allows to force DIO to be enabled for WAL
even if replication is turned on."Use DirectIO" is roughly same suggestion as "don't trust Linux filesystems".
I want to emphasize that this is NOT a linux only issue. It's a problem
across a number of operating systems, including linux.
Yes, of course.
It would be a major admission of defeat for us to take that as our
main route to a solution.Well, I think we were wrong to not engineer towards DIO. There's just
too many issues with buffered IO to not have a supported path for
DIO. But given that it's unrealistic to do so without major work, and
wouldn't be applicable for all installations (shared_buffer size becomes
critical), I don't think it matters that much for the issue discussed
here.The people I've spoken to so far have encouraged us to continue
working with the filesystem layer, offering encouragement of our
decision to use filesystems.There's a lot of people disagreeing with it too.
Specific recent verbal feedback from OpenLDAP was that the project
adopted DIO and found no benefit in doing so, with regret the other
way from having tried.
The care we need to use for any technique is the same.
--
Simon Riggs http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
On Sun, Apr 29, 2018 at 10:42 PM, Simon Riggs <simon@2ndquadrant.com> wrote:
On 28 April 2018 at 09:15, Andres Freund <andres@anarazel.de> wrote:
On 2018-04-28 08:25:53 -0700, Simon Riggs wrote:
The people I've spoken to so far have encouraged us to continue
working with the filesystem layer, offering encouragement of our
decision to use filesystems.There's a lot of people disagreeing with it too.
Specific recent verbal feedback from OpenLDAP was that the project
adopted DIO and found no benefit in doing so, with regret the other
way from having tried.
I'm not sure if OpenLDAP is really comparable. The big three RDBMSs +
MySQL started like us and eventually switched to direct IO, I guess at
a time when direct IO support matured in OSs and their own IO
scheduling was thought to be superior. I'm pretty sure they did that
because they didn't like wasting RAM on double buffering and had
better ideas about IO scheduling. From some googling this morning:
DB2: The Linux/Unix/Windows edition changed its default to DIO ("NO
FILESYSTEM CACHING") in release 9.5 in 2007[1]https://www.ibm.com/support/knowledgecenter/en/SSEPGG_9.5.0/com.ibm.db2.luw.admin.dbobj.doc/doc/c0051304.html, but it can still do
buffered IO if you ask for it.
Oracle: Around the same time or earlier, in the Linux 2.4 era, Oracle
apparently supported direct IO ("FILESYSTEMIO_OPTIONS = DIRECTIO" (or
SETALL for DIRECTIO + ASYNCH)) on big iron Unix but didn't yet use it
on Linux[2]http://www.ixora.com.au/notes/direct_io.htm. There were some amusing emails from Linus Torvalds on
this topic[3]https://lkml.org/lkml/2002/5/11/58. I'm not sure what FILESYSTEMIO_OPTIONS's default value
is on each operating system today or when it changed, it's probably
SETALL everywhere by now? I wonder if they stuck with buffered IO for
a time on Linux despite the availability of direct IO because they
thought it was more reliable or more performant.
SQL Server: I couldn't find any evidence that they've even kept the
option to use buffered IO (which must have existed in the ancestral
code base). Can it? It's a different situation though, targeting a
reduced set of platforms.
MySQL: The default is still buffered ("innodb_flush_method = fsync" as
opposed to "O_DIRECT") but O_DIRECT is supported and widely
recommended, so it sounds like it's usually a win. Maybe not on
smaller systems though?
On MySQL, there are anecdotal reports of performance suffering on some
systems when you turn on O_DIRECT however. If that's true, it's
interesting to speculate about why that might be as it would probably
apply also to us in early versions (optimistic explanation: the
kernel's stretchy page cache allows people to get away with poorly
tuned buffer pool size? pessimistic explanation: the page reclamation
or IO scheduling (asynchronous write-back, write clustering,
read-ahead etc) is not as good as the OS's, but that effect is hidden
by suitably powerful disk subsystem with its own magic caching?) Note
that its O_DIRECT setting *also* calls fsync() to flush filesystem
meta-data (necessary if the file was extended); I wonder if that is
exposed to write-back error loss.
[1]: https://www.ibm.com/support/knowledgecenter/en/SSEPGG_9.5.0/com.ibm.db2.luw.admin.dbobj.doc/doc/c0051304.html
[2]: http://www.ixora.com.au/notes/direct_io.htm
[3]: https://lkml.org/lkml/2002/5/11/58
--
Thomas Munro
http://www.enterprisedb.com
On Mon, Apr 30, 2018 at 11:02 AM, Thomas Munro
<thomas.munro@enterprisedb.com> wrote:
MySQL: The default is still buffered
Someone pulled me up on this off-list: the default is buffered (fsync)
on Unix, but it's unbuffered on Windows. That's quite interesting.
https://dev.mysql.com/doc/refman/8.0/en/innodb-parameters.html#sysvar_innodb_flush_method
https://mariadb.com/kb/en/library/xtradbinnodb-server-system-variables/#innodb_flush_method
--
Thomas Munro
http://www.enterprisedb.com
On Sun, Apr 29, 2018 at 1:58 PM, Craig Ringer <craig@2ndquadrant.com> wrote:
On 28 April 2018 at 23:25, Simon Riggs <simon@2ndquadrant.com> wrote:
On 27 April 2018 at 15:28, Andres Freund <andres@anarazel.de> wrote:
While I'm a bit concerned adding user-code before a checkpoint, if
we'd do it as a shell command it seems pretty reasonable. And useful
even without concern for the fsync issue itself. Checking for IO
errors could e.g. also include checking for read errors - it'd not be
unreasonable to not want to complete a checkpoint if there'd been any
media errors.It seems clear that we need to evaluate our compatibility not just
with an OS, as we do now, but with an OS/filesystem.Although people have suggested some approaches, I'm more interested in
discovering how we can be certain we got it right.TBH, we can't be certain, because there are too many failure modes,
some of which we can't really simulate in practical ways, or automated
ways.
+1
Testing is good, but unless you have a categorical statement from the
relevant documentation or kernel team or you have the source code, I'm
not sure how you can ever really be sure about this. I think we have
a fair idea now what several open kernels do, but we still haven't got
a clue about Windows, AIX, HPUX and Solaris and we only have half the
answer for Illumos, and no "negative" test result can prove that they
can't throw away write-back errors or data.
Considering the variety in interpretation and liberties taken, I
wonder if fsync() is underspecified and someone should file an issue
over at http://www.opengroup.org/austin/ about that.
--
Thomas Munro
http://www.enterprisedb.com
On 30 April 2018 at 09:09, Thomas Munro <thomas.munro@enterprisedb.com> wrote:
Considering the variety in interpretation and liberties taken, I
wonder if fsync() is underspecified and someone should file an issue
over at http://www.opengroup.org/austin/ about that.
All it's going to achieve is adding an "is implementation-defined"
caveat, but that's at least a bit of a heads-up.
I filed patches for Linux man-pages ages ago. I'll update them and
post to LKML; apparently bugzilla has a lot of spam and many people
ignore notifications, so they might just bitrot forever otherwise.
Meanwhile, do we know if, on Linux 4.13+, if we get a buffered write
error due to dirty writeback before we close() a file we don't
fsync(), we'll get the error on close()?
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
On 2018-04-30 10:14:23 +0800, Craig Ringer wrote:
Meanwhile, do we know if, on Linux 4.13+, if we get a buffered write
error due to dirty writeback before we close() a file we don't
fsync(), we'll get the error on close()?
Not quite sure what you're getting at with "a file we don't fsync" - if
we don't, we don't care about durability anyway, no? Or do you mean
where we fsync in a different process?
Either way, the answer is mostly no: On NFS et al where close() implies
an fsync you'll get the error at that time, otherwise you'll get it at
the next fsync().
Greetings,
Andres Freund
Not quite sure what you're getting at with "a file we don't fsync" - if
we don't, we don't care about durability anyway, no? Or do you mean
where we fsync in a different process?
Right.
Either way, the answer is mostly no: On NFS et al where close() implies
an fsync you'll get the error at that time, otherwise you'll get it at
the next fsync().
Thanks.
The reason I ask is that if we got notified of already-detected
writeback errors (on 4.13+) on close() too, it'd narrow the window a
little for problems, since normal backends could PANIC if close() of a
persistent file raised EIO. Otherwise we're less likely to see the
error, since the checkpointer won't see it - it happened before the
checkpointer open()ed the file. It'd still be no help for dirty
writeback that happens after we close() in a user backend / the
bgwriter and before we re-open(), but it'd be nice if the kernel would
tell us on close() if it knows of a writeback error.
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
Hrm, something else that just came up. On 9.6+ we use sync_file_range.
It's surely going to eat errors:
rc = sync_file_range(fd, offset, nbytes,
SYNC_FILE_RANGE_WRITE);
/* don't error out, this is just a performance optimization */
if (rc != 0)
{
ereport(WARNING,
(errcode_for_file_access(),
errmsg("could not flush dirty data: %m")));
}
so that has to panic too.
I'm very suspicious about the safety of the msync() path too.
I'll post an update to my PANIC-everywhere patch that add these cases.
On 2018-04-30 13:03:24 +0800, Craig Ringer wrote:
Hrm, something else that just came up. On 9.6+ we use sync_file_range.
It's surely going to eat errors:rc = sync_file_range(fd, offset, nbytes,
SYNC_FILE_RANGE_WRITE);/* don't error out, this is just a performance optimization */
if (rc != 0)
{
ereport(WARNING,
(errcode_for_file_access(),
errmsg("could not flush dirty data: %m")));
}
It's not. Only SYNC_FILE_RANGE_WAIT_{BEFORE,AFTER} eat errors. Which
seems sensible, because they could be considered data integrity
operations.
fs/sync.c:
SYSCALL_DEFINE4(sync_file_range, int, fd, loff_t, offset, loff_t, nbytes,
unsigned int, flags)
{
...
if (flags & SYNC_FILE_RANGE_WAIT_BEFORE) {
ret = file_fdatawait_range(f.file, offset, endbyte);
if (ret < 0)
goto out_put;
}
if (flags & SYNC_FILE_RANGE_WRITE) {
ret = __filemap_fdatawrite_range(mapping, offset, endbyte,
WB_SYNC_NONE);
if (ret < 0)
goto out_put;
}
if (flags & SYNC_FILE_RANGE_WAIT_AFTER)
ret = file_fdatawait_range(f.file, offset, endbyte);
where
int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
{
struct address_space *mapping = file->f_mapping;
__filemap_fdatawait_range(mapping, start_byte, end_byte);
return file_check_and_advance_wb_err(file);
}
EXPORT_SYMBOL(file_fdatawait_range);
the critical call is file_check_and_advance_wb_err(). That's the call
that checks and clears errors.
Would be good to add a kernel xfstest (gets used on all relevant FS
these days), to make sure that doesn't change.
I'm very suspicious about the safety of the msync() path too.
That seems justified however:
SYSCALL_DEFINE3(msync, unsigned long, start, size_t, len, int, flags)
{
...
error = vfs_fsync_range(file, fstart, fend, 1);
..
*/
int vfs_fsync_range(struct file *file, loff_t start, loff_t end, int datasync)
{
...
return file->f_op->fsync(file, start, end, datasync);
}
EXPORT_SYMBOL(vfs_fsync_range);
int ext4_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
{
...
ret = file_write_and_wait_range(file, start, end);
if (ret)
return ret;
...
STATIC int
xfs_file_fsync(
struct file *file,
loff_t start,
loff_t end,
int datasync)
{
...
error = file_write_and_wait_range(file, start, end);
if (error)
return error;
int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
{
...
err2 = file_check_and_advance_wb_err(file);
if (!err)
err = err2;
return err;
}
Greetings,
Andres Freund
On 1 May 2018 at 00:09, Andres Freund <andres@anarazel.de> wrote:
It's not. Only SYNC_FILE_RANGE_WAIT_{BEFORE,AFTER} eat errors. Which
seems sensible, because they could be considered data integrity
operations.
Ah, I misread that. Thankyou.
I'm very suspicious about the safety of the msync() path too.
That seems justified however:
I'll add EIO tests there.
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
On Sat, Apr 28, 2018 at 12:28 AM, Andres Freund <andres@anarazel.de> wrote:
Before linux v4.13 errors in kernel writeback would be reported at most
once, without a guarantee that that'd happen (IIUC memory pressure could
lead to the relevant information being evicted) - but it was pretty
likely. After v4.13 (see https://lwn.net/Articles/724307/) errors are
reported exactly once to all open file descriptors for a file with an
error - but never for files that have been opened after the error
occurred.
snip
== Proposed Linux Changes ==
- Matthew Wilcox proposed (and posted a patch) that'd partially revert
behaviour to the pre v4.13 world, by *also* reporting errors to
"newer" file-descriptors if the error hasn't previously been
reported. That'd still not guarantee that the error is reported
(memory pressure could evict information without open fd), but in most
situations we'll again get the error in the checkpointer.This seems largely be agreed upon. It's unclear whether it'll go into
the stable backports for still-maintained >= v4.13 kernels.
This is now merged, if it's not reverted it will appear in v4.17.
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=fff75eb2a08c2ac96404a2d79685668f3cf5a7a3
The commit is cc-ed to stable so it should get picked up in the near future.
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=b4678df184b314a2bd47d2329feca2c2534aa12b
Hi,
On 2018-04-27 15:28:42 -0700, Andres Freund wrote:
I went to LSF/MM 2018 to discuss [0] and related issues. Overall I'd say
it was a very productive discussion. I'll first try to recap the
current situation, updated with knowledge I gained. Secondly I'll try to
discuss the kernel changes that seem to have been agreed upon. Thirdly
I'll try to sum up what postgres needs to change.
LWN summarized the discussion as well:
https://lwn.net/SubscriberLink/752952/6825e6a1ddcfb1f3/
- Andres
On 2018-05-01 09:38:03 +0800, Craig Ringer wrote:
On 1 May 2018 at 00:09, Andres Freund <andres@anarazel.de> wrote:
It's not. Only SYNC_FILE_RANGE_WAIT_{BEFORE,AFTER} eat errors. Which
seems sensible, because they could be considered data integrity
operations.Ah, I misread that. Thankyou.
I'm very suspicious about the safety of the msync() path too.
That seems justified however:
I'll add EIO tests there.
Do you have a patchset including that? I didn't find anything after a
quick search...
Greetings,
Andres Freund
On 10 May 2018 at 06:55, Andres Freund <andres@anarazel.de> wrote:
Do you have a patchset including that? I didn't find anything after a
quick search...
There was an earlier rev on the other thread but without msync checks.
I've added panic for msync in the attached, and tidied the comments a bit.
I didn't add comments on why we panic to each individual pg_fsync or
FileSync caller that panics; instead pg_fsync points to
pg_fsync_no_writethrough which explains it briefly and has links.
I looked at callers of pg_fsync, pg_fsync_no_writethrough,
pg_fsync_writethrough, mdsync, and FileSync when writing this.
WAL writing already PANIC'd on fsync failure, which helps, though we
now know that's not sufficient for complete safety.
Patch on top of v11 HEAD @ ddc1f32ee507
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
Attachments:
v2-0001-PANIC-when-we-detect-a-possible-fsync-I-O-error-i.patchtext/x-patch; charset=US-ASCII; name=v2-0001-PANIC-when-we-detect-a-possible-fsync-I-O-error-i.patchDownload
From a6cade9e1de68962d95374127841b0af8eb4cfe0 Mon Sep 17 00:00:00 2001
From: Craig Ringer <craig@2ndquadrant.com>
Date: Tue, 10 Apr 2018 14:08:32 +0800
Subject: [PATCH v2] PANIC when we detect a possible fsync I/O error instead of
retrying fsync
Panic the server on fsync failure in places where we can't simply repeat the
whole operation on retry. Most imporantly, panic when fsync fails during a
checkpoint.
This will result in log messages like:
PANIC: 58030: could not fsync file "base/12367/16386": Input/output error
LOG: 00000: checkpointer process (PID 10799) was terminated by signal 6: Aborted
and, if the condition persists during redo:
LOG: 00000: checkpoint starting: end-of-recovery immediate
PANIC: 58030: could not fsync file "base/12367/16386": Input/output error
LOG: 00000: startup process (PID 10808) was terminated by signal 6: Aborted
Why?
In a number of places PostgreSQL we responded to fsync() errors by retrying the
fsync(), expecting that this would force the operating system to repeat any
write attempts. The code assumed that fsync() would return an error on all
subsequent calls until any I/O error was resolved.
This is not what actually happens on some platforms, including Linux. The
operating system may give up and drop dirty buffers for async writes on the
floor and mark the page mapping as bad. The first fsync() clears any error flag
from the page entry and/or our file descriptor. So a subsequent fsync() returns
success, even though the data PostgreSQL wrote was really discarded.
We have no way to find out which writes failed, and no way to ask the kernel to
retry indefinitely, so all we can do is PANIC. Redo will attempt the write
again, and if it fails again, it will also PANIC.
This doesn't completely prevent fsync reliability issues, because it only
handles cases where the kernel actually reports the error to us. It's entirely
possible for a buffered write to be lost without causing fsync to report an
error at all (see discussion below). Work on addressing those issues and
documenting them is ongoing and will be committed separately.
See:
* https://www.postgresql.org/message-id/CAMsr%2BYHh%2B5Oq4xziwwoEfhoTZgr07vdGG%2Bhu%3D1adXx59aTeaoQ%40mail.gmail.com
* https://www.postgresql.org/message-id/20180427222842.in2e4mibx45zdth5@alap3.anarazel.de
* https://lwn.net/Articles/752063/
* https://lwn.net/Articles/753650/
* https://lwn.net/Articles/752952/
* https://lwn.net/Articles/752613/
---
src/backend/access/heap/rewriteheap.c | 6 +++---
src/backend/access/transam/timeline.c | 4 ++--
src/backend/access/transam/twophase.c | 2 +-
src/backend/access/transam/xlog.c | 4 ++--
src/backend/replication/logical/snapbuild.c | 3 +++
src/backend/storage/file/fd.c | 29 +++++++++++++++++++++++++++--
src/backend/storage/smgr/md.c | 22 ++++++++++++++++------
src/backend/utils/cache/relmapper.c | 2 +-
8 files changed, 55 insertions(+), 17 deletions(-)
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index 8d3c861a33..0320baffec 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -965,7 +965,7 @@ logical_end_heap_rewrite(RewriteState state)
while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status)) != NULL)
{
if (FileSync(src->vfd, WAIT_EVENT_LOGICAL_REWRITE_SYNC) != 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", src->path)));
FileClose(src->vfd);
@@ -1180,7 +1180,7 @@ heap_xlog_logical_rewrite(XLogReaderState *r)
*/
pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_MAPPING_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", path)));
pgstat_report_wait_end();
@@ -1279,7 +1279,7 @@ CheckPointLogicalRewriteHeap(void)
*/
pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_CHECKPOINT_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", path)));
pgstat_report_wait_end();
diff --git a/src/backend/access/transam/timeline.c b/src/backend/access/transam/timeline.c
index 61d36050c3..f4b8410333 100644
--- a/src/backend/access/transam/timeline.c
+++ b/src/backend/access/transam/timeline.c
@@ -406,7 +406,7 @@ writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
pgstat_report_wait_start(WAIT_EVENT_TIMELINE_HISTORY_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", tmppath)));
pgstat_report_wait_end();
@@ -485,7 +485,7 @@ writeTimeLineHistoryFile(TimeLineID tli, char *content, int size)
pgstat_report_wait_start(WAIT_EVENT_TIMELINE_HISTORY_FILE_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", tmppath)));
pgstat_report_wait_end();
diff --git a/src/backend/access/transam/twophase.c b/src/backend/access/transam/twophase.c
index 65194db70e..962412c0f4 100644
--- a/src/backend/access/transam/twophase.c
+++ b/src/backend/access/transam/twophase.c
@@ -1687,7 +1687,7 @@ RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
if (pg_fsync(fd) != 0)
{
CloseTransientFile(fd);
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync two-phase state file: %m")));
}
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index c633e11128..f3cf4c9a65 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -3269,7 +3269,7 @@ XLogFileInit(XLogSegNo logsegno, bool *use_existent, bool use_lock)
if (pg_fsync(fd) != 0)
{
close(fd);
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", tmppath)));
}
@@ -3435,7 +3435,7 @@ XLogFileCopy(XLogSegNo destsegno, TimeLineID srcTLI, XLogSegNo srcsegno,
pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", tmppath)));
pgstat_report_wait_end();
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 4123cdebcf..31ab7c1de9 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -1616,6 +1616,9 @@ SnapBuildSerialize(SnapBuild *builder, XLogRecPtr lsn)
* fsync the file before renaming so that even if we crash after this we
* have either a fully valid file or nothing.
*
+ * It's safe to just ERROR on fsync() here because we'll retry the whole
+ * operation including the writes.
+ *
* TODO: Do the fsync() via checkpoints/restartpoints, doing it here has
* some noticeable overhead since it's performed synchronously during
* decoding?
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 441f18dcf5..95f32484d2 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -353,6 +353,17 @@ pg_fsync(int fd)
/*
* pg_fsync_no_writethrough --- same as fsync except does nothing if
* enableFsync is off
+ *
+ * WARNING: It is unsafe to retry fsync() calls without repeating the preceding
+ * writes. fsync() clears the error flag on some platforms (including Linux,
+ * true up to at least 4.14) when it reports the error to the caller. A second
+ * call may return success even though writes are lost. Many callers test the
+ * return value and PANIC on failure so that redo repeats the writes. It is
+ * safe to ERROR instead if the whole operation can be retried without needing
+ * WAL redo.
+ *
+ * See https://lwn.net/Articles/752063/
+ * and https://www.postgresql.org/message-id/CAMsr%2BYHh%2B5Oq4xziwwoEfhoTZgr07vdGG%2Bhu%3D1adXx59aTeaoQ%40mail.gmail.com
*/
int
pg_fsync_no_writethrough(int fd)
@@ -443,7 +454,12 @@ pg_flush_data(int fd, off_t offset, off_t nbytes)
rc = sync_file_range(fd, offset, nbytes,
SYNC_FILE_RANGE_WRITE);
- /* don't error out, this is just a performance optimization */
+ /*
+ * Don't error out, this is just a performance optimization.
+ *
+ * sync_file_range(SYNC_FILE_RANGE_WRITE) won't clear any error flags,
+ * so we don't have to worry about this impacting fsync reliability.
+ */
if (rc != 0)
{
ereport(WARNING,
@@ -518,7 +534,12 @@ pg_flush_data(int fd, off_t offset, off_t nbytes)
rc = msync(p, (size_t) nbytes, MS_ASYNC);
if (rc != 0)
{
- ereport(WARNING,
+ /*
+ * We must panic here to preserve fsync reliability,
+ * as msync may clear the fsync error state on some
+ * OSes. See pg_fsync_no_writethrough().
+ */
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not flush dirty data: %m")));
/* NB: need to fall through to munmap()! */
@@ -3250,6 +3271,10 @@ looks_like_temp_rel_name(const char *name)
* harmless cases such as read-only files in the data directory, and that's
* not good either.
*
+ * Importantly, on Linux (true in 4.14) and some other platforms, fsync errors
+ * will consume the error, causing a subsequent fsync to succeed even though
+ * the writes did not succeed. See pg_fsync_no_writethrough().
+ *
* Note we assume we're chdir'd into PGDATA to begin with.
*/
void
diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index 2ec103e604..614fa4f3ec 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -1038,7 +1038,7 @@ mdimmedsync(SMgrRelation reln, ForkNumber forknum)
MdfdVec *v = &reln->md_seg_fds[forknum][segno - 1];
if (FileSync(v->mdfd_vfd, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC) < 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m",
FilePathName(v->mdfd_vfd))));
@@ -1265,13 +1265,22 @@ mdsync(void)
* _mdfd_getseg() and for FileSync, since fd.c might have
* closed the file behind our back.
*
- * XXX is there any point in allowing more than one retry?
- * Don't see one at the moment, but easy to change the
- * test here if so.
+ * It's unsafe to ignore failures for other errors,
+ * particularly EIO or (undocumented, but possible) ENOSPC.
+ * The first fsync() will clear any error flag on dirty
+ * buffers pending writeback and/or the file descriptor, so
+ * a second fsync report success despite the buffers
+ * possibly not being written. (Verified on Linux 4.14).
+ * To cope with this we must PANIC and redo all writes
+ * since the last successful checkpoint. See discussion at:
+ *
+ * https://www.postgresql.org/message-id/CAMsr%2BYHh%2B5Oq4xziwwoEfhoTZgr07vdGG%2Bhu%3D1adXx59aTeaoQ%40mail.gmail.com
+ *
+ * for details.
*/
if (!FILE_POSSIBLY_DELETED(errno) ||
failures > 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m",
path)));
@@ -1280,6 +1289,7 @@ mdsync(void)
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\" but retrying: %m",
path)));
+
pfree(path);
/*
@@ -1444,7 +1454,7 @@ register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
(errmsg("could not forward fsync request because request queue is full")));
if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m",
FilePathName(seg->mdfd_vfd))));
diff --git a/src/backend/utils/cache/relmapper.c b/src/backend/utils/cache/relmapper.c
index 99d095f2df..f8ff793a66 100644
--- a/src/backend/utils/cache/relmapper.c
+++ b/src/backend/utils/cache/relmapper.c
@@ -795,7 +795,7 @@ write_relmap_file(bool shared, RelMapFile *newmap,
*/
pgstat_report_wait_start(WAIT_EVENT_RELATION_MAP_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync relation mapping file \"%s\": %m",
mapfilename)));
--
2.14.3
Hi,
On 2018-05-10 09:50:03 +0800, Craig Ringer wrote:
while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status)) != NULL)
{
if (FileSync(src->vfd, WAIT_EVENT_LOGICAL_REWRITE_SYNC) != 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", src->path)));
To me this (and the other callers) doesn't quite look right. First, I
think we should probably be a bit more restrictive about when PANIC
out. It seems like we should PANIC on ENOSPC and EIO, but possibly not
others. Secondly, I think we should centralize the error handling. It
seems likely that we'll acrue some platform specific workarounds, and I
don't want to copy that knowledge everywhere.
Also, don't we need the same on close()?
- Andres
On Thu, May 17, 2018 at 12:44 PM, Andres Freund <andres@anarazel.de> wrote:
Hi,
On 2018-05-10 09:50:03 +0800, Craig Ringer wrote:
while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status)) != NULL)
{
if (FileSync(src->vfd, WAIT_EVENT_LOGICAL_REWRITE_SYNC) != 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", src->path)));To me this (and the other callers) doesn't quite look right. First, I
think we should probably be a bit more restrictive about when PANIC
out. It seems like we should PANIC on ENOSPC and EIO, but possibly not
others. Secondly, I think we should centralize the error handling. It
seems likely that we'll acrue some platform specific workarounds, and I
don't want to copy that knowledge everywhere.
Maybe something like:
ereport(promote_eio_to_panic(ERROR), ...)
?
--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company
On Thu, May 17, 2018 at 11:45 PM, Robert Haas <robertmhaas@gmail.com> wrote:
On Thu, May 17, 2018 at 12:44 PM, Andres Freund <andres@anarazel.de> wrote:
Hi,
On 2018-05-10 09:50:03 +0800, Craig Ringer wrote:
while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status)) != NULL)
{
if (FileSync(src->vfd, WAIT_EVENT_LOGICAL_REWRITE_SYNC) != 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", src->path)));To me this (and the other callers) doesn't quite look right. First, I
think we should probably be a bit more restrictive about when PANIC
out. It seems like we should PANIC on ENOSPC and EIO, but possibly not
others. Secondly, I think we should centralize the error handling. It
seems likely that we'll acrue some platform specific workarounds, and I
don't want to copy that knowledge everywhere.Maybe something like:
ereport(promote_eio_to_panic(ERROR), ...)
Well, searching for places where error is reported with level PANIC,
using word PANIC would miss these instances. People will have to
remember to search with promote_eio_to_panic. May be handle the errors
inside FileSync() itself or a wrapper around that.
--
Best Wishes,
Ashutosh Bapat
EnterpriseDB Corporation
The Postgres Database Company
Hi,
On 2018-04-27 15:28:42 -0700, Andres Freund wrote:
== Potential Postgres Changes ==
Several operating systems / file systems behave differently (See
e.g. [2], thanks Thomas) than we expected. Even the discussed changes to
e.g. linux don't get to where we thought we are. There's obviously also
the question of how to deal with kernels / OSs that have not been
updated.Changes that appear to be necessary, even for kernels with the issues
addressed:- Clearly we need to treat fsync() EIO, ENOSPC errors as a PANIC and
retry recovery. While ENODEV (underlying device went away) will be
persistent, it probably makes sense to treat it the same or even just
give up and shut down. One question I see here is whether we just
want to continue crash-recovery cycles, or whether we want to limit
that.
Craig has a patch for this, although I'm not yet 100% happy with it.
- We need more aggressive error checking on close(), for ENOSPC and
EIO. In both cases afaics we'll have to trigger a crash recovery
cycle. It's entirely possible to end up in a loop on NFS etc, but I
don't think there's a way around that.
This needs to be handled.
- The outstanding fsync request queue isn't persisted properly [3]. This
means that even if the kernel behaved the way we'd expected, we'd not
fail a second checkpoint :(. It's possible that we don't need to deal
with this because we'll henceforth PANIC, but I'd argue we should fix
that regardless. Seems like a time-bomb otherwise (e.g. after moving
to DIO somebody might want to relax the PANIC...).
What we could do:
- forward file descriptors from backends to checkpointer (using
SCM_RIGHTS) when marking a segment dirty. That'd require some
optimizations (see [4]) to avoid doing so repeatedly. That'd
guarantee correct behaviour in all linux kernels >= 4.13 (possibly
backported by distributions?), and I think it'd also make it vastly
more likely that errors are reported in earlier kernels.This should be doable without a noticeable performance impact, I
believe. I don't think it'd be that hard either, but it'd be a bit of
a pain to backport it to all postgres versions, as well as a bit
invasive for that.The infrastructure this'd likely end up building (hashtable of open
relfilenodes), would likely be useful for further things (like caching
file size).
I've written a patch series for this. Took me quite a bit longer than I
had hoped.
The attached patchseries consists out of a few preparatory patches:
- freespace optimization to not call smgrexists() unnecessarily
- register_dirty_segment() optimization to not queue requests for
segments that locally are known to already have been dirtied. This
seems like a good optimization regardless of further changes. Doesn't
yet deal with the mdsync counter wrapping around (which is unlikely to
ever happen in practice, it's 32bit).
- some fd.c changes, I don't think they're quite right yet
- new functions to send/recv data over a unix domain socket, *including*
a file descriptor.
The main patch guarantees that fsync requests are forwarded from
backends to the checkpointer, including the file descriptor. As we do so
immediately at mdwrite() time, that guarantees that the fd has been open
from before the write started, therefore linux will guarantee that that
FD will see errors.
The design of the patch went through a few iterations. I initially
attempted to make the fsync request hashtable shared, but that turned
out to be a lot harder to do reliably *and* fast than I was anticipating
(we'd need to hold a lock for the entirety of mdsync(), dynahash doesn't
allow iteration while other backends modify).
So what I instead did was to replace the shared memory fsync request
queue with a unix domain socket (created in postmaster, using
socketpair()). CheckpointerRequest structs are written to that queue,
including the associated file descriptor. The checkpointer absorbs
those requests, and updates the local pending requests hashtable in
local process memory. To facilitate that mdsync() has read all requests
from the last cycle, checkpointer self-enqueues a token, which allows
to detect the end of the relevant portion of the queue.
The biggest complication in all this scheme is that checkpointer now
needs to keep a file descriptor open for every segment. That obviously
requires adding a few new fields to the hashtable entry. But the bigger
issue is that it's now possible that pending requests need to be
processed earlier than the next checkpoint, because of file descriptor
limits. To address that absorbing the fsync request queue will now do a
mdsync() style pass, doing the necessary fsyncs.
Because mdsync() (or rather its new workhorse mdsyncpass()) will now not
open files itself, there's no need to do deal with retries for files
that have been deleted. For the cases where we didn't yet receive a
fsync cancel request, we'll just fsync the fd. That's unnecessary, but
harmless.
Obviously this is currently heavily unix specific (according to my
research all our unix platforms support say that they support sending
fds across unix domain sockets w/ SCM_RIGHTS). It's unclear whether any
OS but linux benefits from not closing file descriptors before fsync().
We could make this work for windows, without *too* much trouble (one can
just open fds in another process, using that process' handle).
I think there's some advantage in using the same approach
everywhere. For one not maintaining two radically different approaches
for complicated code. It'd also allow us to offload more fsyncs to
checkpointer, not just the ones for normal relation files, which does
seem advantageous. Not having ugly retry logic around deleted files in
mdsync() also seems nice. But there's cases where this is likely
slower, due to the potential of having to wait for checkpointer when the
queue is full.
I'll note that I think the new mdsync() is considerably simpler. Even if
we do not decide to use an approach as presented here, I think we should
make some of those changes. Specifically not unlinking the pending
requests bitmap in mdsync() seems like it both resolves existing bug
(see upthread) and makes the code simpler.
I plan to switch to working on something else for a day or two next
week, and then polish this further. I'd greatly appreciate comments till
then.
I didn't want to do this now, but I think we should also consider
removing all awareness of segments from the fsync request queue. Instead
it should deal with individual files, and the segmentation should be
handled by md.c. That'll allow us to move all the necessary code to
smgr.c (or checkpointer?); Thomas said that'd be helpful for further
work. I personally think it'd be a lot simpler, because having to have
long bitmaps with only the last bit set for large append only relations
isn't a particularly sensible approach imo. The only thing that that'd
make more complicated is that the file/database unlink requests get more
expensive (as they'd likely need to search the whole table), but that
seems like a sensible tradeoff. Alternatively using a tree structure
would be an alternative obviously. Personally I was thinking that we
should just make the hashtable be over a pathname, that seems most
generic.
Greetings,
Andres Freund
Attachments:
v1-0002-Add-functions-to-send-receive-data-FD-over-a-unix.patchtext/x-diff; charset=us-asciiDownload
From 8c16dcb5f341651e5ae19ea9d5f935b23f52d902 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Fri, 18 May 2018 12:38:25 -0700
Subject: [PATCH v1 2/7] Add functions to send/receive data & FD over a unix
domain socket.
This'll be used by a followup patch changing how the fsync request
queue works, to make it safe on linux.
TODO: This probably should live elsewhere.
Author: Andres Freund
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/storage/file/fd.c | 102 ++++++++++++++++++++++++++++++++++
src/include/storage/fd.h | 4 ++
2 files changed, 106 insertions(+)
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 441f18dcf56..65e46483a44 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -3572,3 +3572,105 @@ MakePGDirectory(const char *directoryName)
{
return mkdir(directoryName, pg_dir_create_mode);
}
+
+/*
+ * Send data over a unix domain socket, optionally (when fd != -1) including a
+ * file descriptor.
+ */
+ssize_t
+pg_uds_send_with_fd(int sock, void *buf, ssize_t buflen, int fd)
+{
+ ssize_t size;
+ struct msghdr msg = {0};
+ struct iovec iov;
+ /* cmsg header, union for correct alignment */
+ union
+ {
+ struct cmsghdr cmsghdr;
+ char control[CMSG_SPACE(sizeof (int))];
+ } cmsgu;
+ struct cmsghdr *cmsg;
+
+ iov.iov_base = buf;
+ iov.iov_len = buflen;
+
+ msg.msg_name = NULL;
+ msg.msg_namelen = 0;
+ msg.msg_iov = &iov;
+ msg.msg_iovlen = 1;
+
+ if (fd >= 0)
+ {
+ msg.msg_control = cmsgu.control;
+ msg.msg_controllen = sizeof(cmsgu.control);
+
+ cmsg = CMSG_FIRSTHDR(&msg);
+ cmsg->cmsg_len = CMSG_LEN(sizeof (int));
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+
+ *((int *) CMSG_DATA(cmsg)) = fd;
+ }
+
+ size = sendmsg(sock, &msg, 0);
+
+ /* errors are returned directly */
+ return size;
+}
+
+/*
+ * Receive data from a unix domain socket. If a file is sent over the socket,
+ * store it in *fd.
+ */
+ssize_t
+pg_uds_recv_with_fd(int sock, void *buf, ssize_t bufsize, int *fd)
+{
+ ssize_t size;
+ struct msghdr msg;
+ struct iovec iov;
+ /* cmsg header, union for correct alignment */
+ union
+ {
+ struct cmsghdr cmsghdr;
+ char control[CMSG_SPACE(sizeof (int))];
+ } cmsgu;
+ struct cmsghdr *cmsg;
+
+ Assert(fd != NULL);
+
+ iov.iov_base = buf;
+ iov.iov_len = bufsize;
+
+ msg.msg_name = NULL;
+ msg.msg_namelen = 0;
+ msg.msg_iov = &iov;
+ msg.msg_iovlen = 1;
+ msg.msg_control = cmsgu.control;
+ msg.msg_controllen = sizeof(cmsgu.control);
+
+ size = recvmsg (sock, &msg, 0);
+
+ if (size < 0)
+ {
+ *fd = -1;
+ return size;
+ }
+
+ cmsg = CMSG_FIRSTHDR(&msg);
+ if (cmsg && cmsg->cmsg_len == CMSG_LEN(sizeof(int)))
+ {
+ if (cmsg->cmsg_level != SOL_SOCKET)
+ elog(FATAL, "unexpected cmsg_level");
+
+ if (cmsg->cmsg_type != SCM_RIGHTS)
+ elog(FATAL, "unexpected cmsg_type");
+
+ *fd = *((int *) CMSG_DATA(cmsg));
+
+ /* FIXME: check / handle additional cmsg structures */
+ }
+ else
+ *fd = -1;
+
+ return size;
+}
diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h
index 8e7c9728f4b..5e016d69a5a 100644
--- a/src/include/storage/fd.h
+++ b/src/include/storage/fd.h
@@ -143,4 +143,8 @@ extern void SyncDataDirectory(void);
#define PG_TEMP_FILES_DIR "pgsql_tmp"
#define PG_TEMP_FILE_PREFIX "pgsql_tmp"
+/* XXX; This should probably go elsewhere */
+ssize_t pg_uds_send_with_fd(int sock, void *buf, ssize_t buflen, int fd);
+ssize_t pg_uds_recv_with_fd(int sock, void *buf, ssize_t bufsize, int *fd);
+
#endif /* FD_H */
--
2.17.0.rc1.dirty
v1-0001-freespace-Don-t-constantly-close-files-when-readi.patchtext/x-diff; charset=us-asciiDownload
From ecb3bce411622780bb27bb0c17eb0af2e6a0a3b3 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Fri, 18 May 2018 12:33:12 -0700
Subject: [PATCH v1 1/7] freespace: Don't constantly close files when reading
buffer.
fsm_readbuf() used to always do an smgrexists() when reading a buffer
beyond the known file size. That currently implies closing the md.c
handle, loosing all the data cached therein. Change this to only
check for file existance when not already known to be larger than 0
blocks.
Author: Andres Freund
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/storage/freespace/freespace.c | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/src/backend/storage/freespace/freespace.c b/src/backend/storage/freespace/freespace.c
index 65c4e74999f..d7569cec5ed 100644
--- a/src/backend/storage/freespace/freespace.c
+++ b/src/backend/storage/freespace/freespace.c
@@ -556,7 +556,7 @@ fsm_readbuf(Relation rel, FSMAddress addr, bool extend)
* not on extension.)
*/
if (rel->rd_smgr->smgr_fsm_nblocks == InvalidBlockNumber ||
- blkno >= rel->rd_smgr->smgr_fsm_nblocks)
+ rel->rd_smgr->smgr_fsm_nblocks == 0)
{
if (smgrexists(rel->rd_smgr, FSM_FORKNUM))
rel->rd_smgr->smgr_fsm_nblocks = smgrnblocks(rel->rd_smgr,
@@ -564,6 +564,9 @@ fsm_readbuf(Relation rel, FSMAddress addr, bool extend)
else
rel->rd_smgr->smgr_fsm_nblocks = 0;
}
+ else if (blkno >= rel->rd_smgr->smgr_fsm_nblocks)
+ rel->rd_smgr->smgr_fsm_nblocks = smgrnblocks(rel->rd_smgr,
+ FSM_FORKNUM);
/* Handle requests beyond EOF */
if (blkno >= rel->rd_smgr->smgr_fsm_nblocks)
--
2.17.0.rc1.dirty
v1-0003-Make-FileGetRawDesc-ensure-there-s-an-associated-.patchtext/x-diff; charset=us-asciiDownload
From 298bcf50f8cac7b8955f9f25b997cc4c4b65fbd0 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Fri, 18 May 2018 12:40:05 -0700
Subject: [PATCH v1 3/7] Make FileGetRawDesc() ensure there's an associated
kernel FD.
Author: Andres Freund
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/storage/file/fd.c | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 65e46483a44..8ae13a51ec1 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -2232,6 +2232,10 @@ int
FileGetRawDesc(File file)
{
Assert(FileIsValid(file));
+
+ if (FileAccess(file))
+ return -1;
+
return VfdCache[file].fd;
}
--
2.17.0.rc1.dirty
v1-0004-WIP-Allow-to-create-a-transient-file-for-a-previo.patchtext/x-diff; charset=us-asciiDownload
From 786fafb408ba0b9080941170eedcb6a58c2df8d1 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Fri, 18 May 2018 12:42:32 -0700
Subject: [PATCH v1 4/7] WIP: Allow to create a transient file for a previously
openend FD.
It might be better to extend the normal vfd files instead, adding a
flag that prohibits closing the underlying file (and removing them
from the LRU).
Author: Andres Freund
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/storage/file/fd.c | 32 ++++++++++++++++++++++++++++++++
src/include/storage/fd.h | 2 ++
2 files changed, 34 insertions(+)
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 8ae13a51ec1..e2492ce94d5 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -2430,6 +2430,38 @@ OpenTransientFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
return -1; /* failure */
}
+void
+ReserveTransientFile(void)
+{
+ if (!reserveAllocatedDesc())
+ ereport(PANIC,
+ (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
+ errmsg("exceeded maxAllocatedDescs (%d) while trying to open file",
+ maxAllocatedDescs)));
+
+ /* Close excess kernel FDs. */
+ ReleaseLruFiles();
+
+ Assert(nfile + numAllocatedDescs <= max_safe_fds);
+}
+
+void
+RegisterTransientFile(int fd)
+{
+ AllocateDesc *desc;
+
+ /* make sure ReserveTransientFile was called sufficiently recently */
+ Assert(fd >= 0);
+ Assert(nfile + numAllocatedDescs <= max_safe_fds);
+ Assert(numAllocatedDescs < maxAllocatedDescs);
+
+ desc = &allocatedDescs[numAllocatedDescs];
+ desc->kind = AllocateDescRawFD;
+ desc->desc.fd = fd;
+ desc->create_subid = GetCurrentSubTransactionId();
+ numAllocatedDescs++;
+}
+
/*
* Routines that want to initiate a pipe stream should use OpenPipeStream
* rather than plain popen(). This lets fd.c deal with freeing FDs if
diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h
index 5e016d69a5a..9bb32771602 100644
--- a/src/include/storage/fd.h
+++ b/src/include/storage/fd.h
@@ -105,6 +105,8 @@ extern int FreeDir(DIR *dir);
/* Operations to allow use of a plain kernel FD, with automatic cleanup */
extern int OpenTransientFile(const char *fileName, int fileFlags);
extern int OpenTransientFilePerm(const char *fileName, int fileFlags, mode_t fileMode);
+extern void ReserveTransientFile(void);
+extern void RegisterTransientFile(int fd);
extern int CloseTransientFile(int fd);
/* If you've really really gotta have a plain kernel FD, use this */
--
2.17.0.rc1.dirty
v1-0005-WIP-Allow-more-transient-files-and-allow-to-query.patchtext/x-diff; charset=us-asciiDownload
From 53ded3d52f792c58ad3550ffb2244cec19981b66 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Fri, 18 May 2018 12:43:40 -0700
Subject: [PATCH v1 5/7] WIP: Allow more transient files and allow to query the
max.
Author: Andres Freund
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/storage/file/fd.c | 10 ++++++++--
src/include/storage/fd.h | 1 +
2 files changed, 9 insertions(+), 2 deletions(-)
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index e2492ce94d5..b0db997edc7 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -2299,10 +2299,10 @@ reserveAllocatedDesc(void)
*
* We mustn't let allocated descriptors hog all the available FDs, and in
* practice we'd better leave a reasonable number of FDs for VFD use. So
- * set the maximum to max_safe_fds / 2. (This should certainly be at
+ * set the maximum to 80% of max_safe_fds. (This should certainly be at
* least as large as the initial size, FD_MINFREE / 2.)
*/
- newMax = max_safe_fds / 2;
+ newMax = MaxTransientFiles(); // XXX: more accurate name
if (newMax > maxAllocatedDescs)
{
newDescs = (AllocateDesc *) realloc(allocatedDescs,
@@ -2610,6 +2610,12 @@ CloseTransientFile(int fd)
return close(fd);
}
+int
+MaxTransientFiles(void)
+{
+ return (max_safe_fds * 8) / 10;
+}
+
/*
* Routines that want to use <dirent.h> (ie, DIR*) should use AllocateDir
* rather than plain opendir(). This lets fd.c deal with freeing FDs if
diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h
index 9bb32771602..2c3055e77cd 100644
--- a/src/include/storage/fd.h
+++ b/src/include/storage/fd.h
@@ -108,6 +108,7 @@ extern int OpenTransientFilePerm(const char *fileName, int fileFlags, mode_t fil
extern void ReserveTransientFile(void);
extern void RegisterTransientFile(int fd);
extern int CloseTransientFile(int fd);
+extern int MaxTransientFiles(void);
/* If you've really really gotta have a plain kernel FD, use this */
extern int BasicOpenFile(const char *fileName, int fileFlags);
--
2.17.0.rc1.dirty
v1-0006-WIP-Optimize-register_dirty_segment-to-not-repeat.patchtext/x-diff; charset=us-asciiDownload
From 36df35480f033ddc02d463959ed6e764afcf63ad Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Fri, 18 May 2018 12:47:33 -0700
Subject: [PATCH v1 6/7] WIP: Optimize register_dirty_segment() to not
repeatedly queue fsync requests.
Author: Andres Freund
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/postmaster/checkpointer.c | 36 ++++++++++++-------
src/backend/storage/smgr/md.c | 50 +++++++++++++++++++--------
src/include/postmaster/bgwriter.h | 3 ++
3 files changed, 63 insertions(+), 26 deletions(-)
diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c
index 0950ada6019..333eb91c9de 100644
--- a/src/backend/postmaster/checkpointer.c
+++ b/src/backend/postmaster/checkpointer.c
@@ -46,6 +46,7 @@
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
+#include "port/atomics.h"
#include "postmaster/bgwriter.h"
#include "replication/syncrep.h"
#include "storage/bufmgr.h"
@@ -126,8 +127,9 @@ typedef struct
int ckpt_flags; /* checkpoint flags, as defined in xlog.h */
- uint32 num_backend_writes; /* counts user backend buffer writes */
- uint32 num_backend_fsync; /* counts user backend fsync calls */
+ pg_atomic_uint32 num_backend_writes; /* counts user backend buffer writes */
+ pg_atomic_uint32 num_backend_fsync; /* counts user backend fsync calls */
+ pg_atomic_uint32 ckpt_cycle; /* cycle */
int num_requests; /* current # of requests */
int max_requests; /* allocated array size */
@@ -943,6 +945,9 @@ CheckpointerShmemInit(void)
MemSet(CheckpointerShmem, 0, size);
SpinLockInit(&CheckpointerShmem->ckpt_lck);
CheckpointerShmem->max_requests = NBuffers;
+ pg_atomic_init_u32(&CheckpointerShmem->ckpt_cycle, 0);
+ pg_atomic_init_u32(&CheckpointerShmem->num_backend_writes, 0);
+ pg_atomic_init_u32(&CheckpointerShmem->num_backend_fsync, 0);
}
}
@@ -1133,10 +1138,6 @@ ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
- /* Count all backend writes regardless of if they fit in the queue */
- if (!AmBackgroundWriterProcess())
- CheckpointerShmem->num_backend_writes++;
-
/*
* If the checkpointer isn't running or the request queue is full, the
* backend will have to perform its own fsync request. But before forcing
@@ -1151,7 +1152,7 @@ ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
* fsync
*/
if (!AmBackgroundWriterProcess())
- CheckpointerShmem->num_backend_fsync++;
+ pg_atomic_fetch_add_u32(&CheckpointerShmem->num_backend_fsync, 1);
LWLockRelease(CheckpointerCommLock);
return false;
}
@@ -1312,11 +1313,10 @@ AbsorbFsyncRequests(void)
LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
/* Transfer stats counts into pending pgstats message */
- BgWriterStats.m_buf_written_backend += CheckpointerShmem->num_backend_writes;
- BgWriterStats.m_buf_fsync_backend += CheckpointerShmem->num_backend_fsync;
-
- CheckpointerShmem->num_backend_writes = 0;
- CheckpointerShmem->num_backend_fsync = 0;
+ BgWriterStats.m_buf_written_backend +=
+ pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_writes, 0);
+ BgWriterStats.m_buf_fsync_backend +=
+ pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_fsync, 0);
/*
* We try to avoid holding the lock for a long time by copying the request
@@ -1390,3 +1390,15 @@ FirstCallSinceLastCheckpoint(void)
return FirstCall;
}
+
+uint32
+GetCheckpointSyncCycle(void)
+{
+ return pg_atomic_read_u32(&CheckpointerShmem->ckpt_cycle);
+}
+
+uint32
+IncCheckpointSyncCycle(void)
+{
+ return pg_atomic_fetch_add_u32(&CheckpointerShmem->ckpt_cycle, 1);
+}
diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index 2ec103e6047..555774320b5 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -109,6 +109,7 @@ typedef struct _MdfdVec
{
File mdfd_vfd; /* fd number in fd.c's pool */
BlockNumber mdfd_segno; /* segment number, from 0 */
+ uint32 mdfd_dirtied_cycle;
} MdfdVec;
static MemoryContext MdCxt; /* context for all MdfdVec objects */
@@ -133,12 +134,12 @@ static MemoryContext MdCxt; /* context for all MdfdVec objects */
* (Regular backends do not track pending operations locally, but forward
* them to the checkpointer.)
*/
-typedef uint16 CycleCtr; /* can be any convenient integer size */
+typedef uint32 CycleCtr; /* can be any convenient integer size */
typedef struct
{
RelFileNode rnode; /* hash table key (must be first!) */
- CycleCtr cycle_ctr; /* mdsync_cycle_ctr of oldest request */
+ CycleCtr cycle_ctr; /* sync cycle of oldest request */
/* requests[f] has bit n set if we need to fsync segment n of fork f */
Bitmapset *requests[MAX_FORKNUM + 1];
/* canceled[f] is true if we canceled fsyncs for fork "recently" */
@@ -155,7 +156,6 @@ static HTAB *pendingOpsTable = NULL;
static List *pendingUnlinks = NIL;
static MemoryContext pendingOpsCxt; /* context for the above */
-static CycleCtr mdsync_cycle_ctr = 0;
static CycleCtr mdckpt_cycle_ctr = 0;
@@ -333,6 +333,7 @@ mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
mdfd = &reln->md_seg_fds[forkNum][0];
mdfd->mdfd_vfd = fd;
mdfd->mdfd_segno = 0;
+ mdfd->mdfd_dirtied_cycle = GetCheckpointSyncCycle() - 1;
}
/*
@@ -614,6 +615,7 @@ mdopen(SMgrRelation reln, ForkNumber forknum, int behavior)
mdfd = &reln->md_seg_fds[forknum][0];
mdfd->mdfd_vfd = fd;
mdfd->mdfd_segno = 0;
+ mdfd->mdfd_dirtied_cycle = GetCheckpointSyncCycle() - 1;
Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
@@ -1089,9 +1091,9 @@ mdsync(void)
* To avoid excess fsync'ing (in the worst case, maybe a never-terminating
* checkpoint), we want to ignore fsync requests that are entered into the
* hashtable after this point --- they should be processed next time,
- * instead. We use mdsync_cycle_ctr to tell old entries apart from new
- * ones: new ones will have cycle_ctr equal to the incremented value of
- * mdsync_cycle_ctr.
+ * instead. We use GetCheckpointSyncCycle() to tell old entries apart
+ * from new ones: new ones will have cycle_ctr equal to
+ * IncCheckpointSyncCycle().
*
* In normal circumstances, all entries present in the table at this point
* will have cycle_ctr exactly equal to the current (about to be old)
@@ -1115,16 +1117,16 @@ mdsync(void)
hash_seq_init(&hstat, pendingOpsTable);
while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
{
- entry->cycle_ctr = mdsync_cycle_ctr;
+ entry->cycle_ctr = GetCheckpointSyncCycle();
}
}
- /* Advance counter so that new hashtable entries are distinguishable */
- mdsync_cycle_ctr++;
-
/* Set flag to detect failure if we don't reach the end of the loop */
mdsync_in_progress = true;
+ /* Advance counter so that new hashtable entries are distinguishable */
+ IncCheckpointSyncCycle();
+
/* Now scan the hashtable for fsync requests to process */
absorb_counter = FSYNCS_PER_ABSORB;
hash_seq_init(&hstat, pendingOpsTable);
@@ -1137,11 +1139,11 @@ mdsync(void)
* contain multiple fsync-request bits, but they are all new. Note
* "continue" bypasses the hash-remove call at the bottom of the loop.
*/
- if (entry->cycle_ctr == mdsync_cycle_ctr)
+ if (entry->cycle_ctr == GetCheckpointSyncCycle())
continue;
/* Else assert we haven't missed it */
- Assert((CycleCtr) (entry->cycle_ctr + 1) == mdsync_cycle_ctr);
+ Assert((CycleCtr) (entry->cycle_ctr + 1) == GetCheckpointSyncCycle());
/*
* Scan over the forks and segments represented by the entry.
@@ -1308,7 +1310,7 @@ mdsync(void)
break;
}
if (forknum <= MAX_FORKNUM)
- entry->cycle_ctr = mdsync_cycle_ctr;
+ entry->cycle_ctr = GetCheckpointSyncCycle();
else
{
/* Okay to remove it */
@@ -1427,18 +1429,37 @@ mdpostckpt(void)
static void
register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
{
+ uint32 cycle;
+
/* Temp relations should never be fsync'd */
Assert(!SmgrIsTemp(reln));
+ pg_memory_barrier();
+ cycle = GetCheckpointSyncCycle();
+
+ /*
+ * Don't repeatedly register the same segment as dirty.
+ *
+ * FIXME: This doesn't correctly deal with overflows yet! We could
+ * e.g. emit an smgr invalidation every now and then, or use a 64bit
+ * counter. Or just error out if the cycle reaches UINT32_MAX.
+ */
+ if (seg->mdfd_dirtied_cycle == cycle)
+ return;
+
if (pendingOpsTable)
{
/* push it into local pending-ops table */
RememberFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno);
+ seg->mdfd_dirtied_cycle = cycle;
}
else
{
if (ForwardFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno))
+ {
+ seg->mdfd_dirtied_cycle = cycle;
return; /* passed it off successfully */
+ }
ereport(DEBUG1,
(errmsg("could not forward fsync request because request queue is full")));
@@ -1623,7 +1644,7 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
/* if new entry, initialize it */
if (!found)
{
- entry->cycle_ctr = mdsync_cycle_ctr;
+ entry->cycle_ctr = GetCheckpointSyncCycle();
MemSet(entry->requests, 0, sizeof(entry->requests));
MemSet(entry->canceled, 0, sizeof(entry->canceled));
}
@@ -1793,6 +1814,7 @@ _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
v = &reln->md_seg_fds[forknum][segno];
v->mdfd_vfd = fd;
v->mdfd_segno = segno;
+ v->mdfd_dirtied_cycle = GetCheckpointSyncCycle() - 1;
Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
diff --git a/src/include/postmaster/bgwriter.h b/src/include/postmaster/bgwriter.h
index 941c6aba7d1..87a5cfad415 100644
--- a/src/include/postmaster/bgwriter.h
+++ b/src/include/postmaster/bgwriter.h
@@ -38,6 +38,9 @@ extern void AbsorbFsyncRequests(void);
extern Size CheckpointerShmemSize(void);
extern void CheckpointerShmemInit(void);
+extern uint32 GetCheckpointSyncCycle(void);
+extern uint32 IncCheckpointSyncCycle(void);
+
extern bool FirstCallSinceLastCheckpoint(void);
#endif /* _BGWRITER_H */
--
2.17.0.rc1.dirty
v1-0007-Heavily-WIP-Send-file-descriptors-to-checkpointer.patchtext/x-diff; charset=us-asciiDownload
From 1c99e98386a763de70326e96fb9b7cfa72373e5f Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Fri, 18 May 2018 13:05:42 -0700
Subject: [PATCH v1 7/7] Heavily-WIP: Send file descriptors to checkpointer for
fsyncing.
This addresses the issue that, at least on linux, fsyncs only reliably
see errors that occurred after they've been opeend.
Author:
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/access/transam/xlog.c | 7 +-
src/backend/postmaster/checkpointer.c | 358 +++++++----------
src/backend/postmaster/postmaster.c | 38 ++
src/backend/storage/smgr/md.c | 545 ++++++++++++++++----------
src/include/postmaster/bgwriter.h | 8 +-
src/include/postmaster/postmaster.h | 5 +
src/include/storage/smgr.h | 3 +-
7 files changed, 542 insertions(+), 422 deletions(-)
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index adbd6a21264..427774152eb 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -8634,8 +8634,10 @@ CreateCheckPoint(int flags)
* Note: because it is possible for log_checkpoints to change while a
* checkpoint proceeds, we always accumulate stats, even if
* log_checkpoints is currently off.
+ *
+ * Note #2: this is reset at the end of the checkpoint, not here, because
+ * we might have to fsync before getting here (see mdsync()).
*/
- MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
/*
@@ -8999,6 +9001,9 @@ CreateCheckPoint(int flags)
CheckpointStats.ckpt_segs_recycled);
LWLockRelease(CheckpointLock);
+
+ /* reset stats */
+ MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
}
/*
diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c
index 333eb91c9de..1bce610336a 100644
--- a/src/backend/postmaster/checkpointer.c
+++ b/src/backend/postmaster/checkpointer.c
@@ -48,6 +48,7 @@
#include "pgstat.h"
#include "port/atomics.h"
#include "postmaster/bgwriter.h"
+#include "postmaster/postmaster.h"
#include "replication/syncrep.h"
#include "storage/bufmgr.h"
#include "storage/condition_variable.h"
@@ -102,19 +103,21 @@
*
* The requests array holds fsync requests sent by backends and not yet
* absorbed by the checkpointer.
- *
- * Unlike the checkpoint fields, num_backend_writes, num_backend_fsync, and
- * the requests fields are protected by CheckpointerCommLock.
*----------
*/
typedef struct
{
+ uint32 type;
RelFileNode rnode;
ForkNumber forknum;
BlockNumber segno; /* see md.c for special values */
+ bool contains_fd;
/* might add a real request-type field later; not needed yet */
} CheckpointerRequest;
+#define CKPT_REQUEST_RNODE 1
+#define CKPT_REQUEST_SYN 2
+
typedef struct
{
pid_t checkpointer_pid; /* PID (0 if not started) */
@@ -131,8 +134,6 @@ typedef struct
pg_atomic_uint32 num_backend_fsync; /* counts user backend fsync calls */
pg_atomic_uint32 ckpt_cycle; /* cycle */
- int num_requests; /* current # of requests */
- int max_requests; /* allocated array size */
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER];
} CheckpointerShmemStruct;
@@ -168,13 +169,17 @@ static double ckpt_cached_elapsed;
static pg_time_t last_checkpoint_time;
static pg_time_t last_xlog_switch_time;
+static BlockNumber next_syn_rqst;
+static BlockNumber received_syn_rqst;
+
/* Prototypes for private functions */
static void CheckArchiveTimeout(void);
static bool IsCheckpointOnSchedule(double progress);
static bool ImmediateCheckpointRequested(void);
-static bool CompactCheckpointerRequestQueue(void);
static void UpdateSharedMemoryConfig(void);
+static void SendFsyncRequest(CheckpointerRequest *request, int fd);
+static bool AbsorbFsyncRequest(void);
/* Signal handlers */
@@ -557,10 +562,11 @@ CheckpointerMain(void)
cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
}
- rc = WaitLatch(MyLatch,
- WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
- cur_timeout * 1000L /* convert to ms */ ,
- WAIT_EVENT_CHECKPOINTER_MAIN);
+ rc = WaitLatchOrSocket(MyLatch,
+ WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE,
+ fsync_fds[FSYNC_FD_PROCESS],
+ cur_timeout * 1000L /* convert to ms */ ,
+ WAIT_EVENT_CHECKPOINTER_MAIN);
/*
* Emergency bailout if postmaster has died. This is to avoid the
@@ -910,12 +916,7 @@ CheckpointerShmemSize(void)
{
Size size;
- /*
- * Currently, the size of the requests[] array is arbitrarily set equal to
- * NBuffers. This may prove too large or small ...
- */
size = offsetof(CheckpointerShmemStruct, requests);
- size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
return size;
}
@@ -938,13 +939,10 @@ CheckpointerShmemInit(void)
if (!found)
{
/*
- * First time through, so initialize. Note that we zero the whole
- * requests array; this is so that CompactCheckpointerRequestQueue can
- * assume that any pad bytes in the request structs are zeroes.
+ * First time through, so initialize.
*/
MemSet(CheckpointerShmem, 0, size);
SpinLockInit(&CheckpointerShmem->ckpt_lck);
- CheckpointerShmem->max_requests = NBuffers;
pg_atomic_init_u32(&CheckpointerShmem->ckpt_cycle, 0);
pg_atomic_init_u32(&CheckpointerShmem->num_backend_writes, 0);
pg_atomic_init_u32(&CheckpointerShmem->num_backend_fsync, 0);
@@ -1124,176 +1122,61 @@ RequestCheckpoint(int flags)
* the queue is full and contains no duplicate entries. In that case, we
* let the backend know by returning false.
*/
-bool
-ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
+void
+ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno,
+ File file)
{
- CheckpointerRequest *request;
- bool too_full;
+ CheckpointerRequest request = {0};
if (!IsUnderPostmaster)
- return false; /* probably shouldn't even get here */
+ elog(ERROR, "ForwardFsyncRequest must not be called in single user mode");
if (AmCheckpointerProcess())
elog(ERROR, "ForwardFsyncRequest must not be called in checkpointer");
- LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
+ request.type = CKPT_REQUEST_RNODE;
+ request.rnode = rnode;
+ request.forknum = forknum;
+ request.segno = segno;
+ request.contains_fd = file != -1;
- /*
- * If the checkpointer isn't running or the request queue is full, the
- * backend will have to perform its own fsync request. But before forcing
- * that to happen, we can try to compact the request queue.
- */
- if (CheckpointerShmem->checkpointer_pid == 0 ||
- (CheckpointerShmem->num_requests >= CheckpointerShmem->max_requests &&
- !CompactCheckpointerRequestQueue()))
- {
- /*
- * Count the subset of writes where backends have to do their own
- * fsync
- */
- if (!AmBackgroundWriterProcess())
- pg_atomic_fetch_add_u32(&CheckpointerShmem->num_backend_fsync, 1);
- LWLockRelease(CheckpointerCommLock);
- return false;
- }
-
- /* OK, insert request */
- request = &CheckpointerShmem->requests[CheckpointerShmem->num_requests++];
- request->rnode = rnode;
- request->forknum = forknum;
- request->segno = segno;
-
- /* If queue is more than half full, nudge the checkpointer to empty it */
- too_full = (CheckpointerShmem->num_requests >=
- CheckpointerShmem->max_requests / 2);
-
- LWLockRelease(CheckpointerCommLock);
-
- /* ... but not till after we release the lock */
- if (too_full && ProcGlobal->checkpointerLatch)
- SetLatch(ProcGlobal->checkpointerLatch);
-
- return true;
-}
-
-/*
- * CompactCheckpointerRequestQueue
- * Remove duplicates from the request queue to avoid backend fsyncs.
- * Returns "true" if any entries were removed.
- *
- * Although a full fsync request queue is not common, it can lead to severe
- * performance problems when it does happen. So far, this situation has
- * only been observed to occur when the system is under heavy write load,
- * and especially during the "sync" phase of a checkpoint. Without this
- * logic, each backend begins doing an fsync for every block written, which
- * gets very expensive and can slow down the whole system.
- *
- * Trying to do this every time the queue is full could lose if there
- * aren't any removable entries. But that should be vanishingly rare in
- * practice: there's one queue entry per shared buffer.
- */
-static bool
-CompactCheckpointerRequestQueue(void)
-{
- struct CheckpointerSlotMapping
- {
- CheckpointerRequest request;
- int slot;
- };
-
- int n,
- preserve_count;
- int num_skipped = 0;
- HASHCTL ctl;
- HTAB *htab;
- bool *skip_slot;
-
- /* must hold CheckpointerCommLock in exclusive mode */
- Assert(LWLockHeldByMe(CheckpointerCommLock));
-
- /* Initialize skip_slot array */
- skip_slot = palloc0(sizeof(bool) * CheckpointerShmem->num_requests);
-
- /* Initialize temporary hash table */
- MemSet(&ctl, 0, sizeof(ctl));
- ctl.keysize = sizeof(CheckpointerRequest);
- ctl.entrysize = sizeof(struct CheckpointerSlotMapping);
- ctl.hcxt = CurrentMemoryContext;
-
- htab = hash_create("CompactCheckpointerRequestQueue",
- CheckpointerShmem->num_requests,
- &ctl,
- HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
-
- /*
- * The basic idea here is that a request can be skipped if it's followed
- * by a later, identical request. It might seem more sensible to work
- * backwards from the end of the queue and check whether a request is
- * *preceded* by an earlier, identical request, in the hopes of doing less
- * copying. But that might change the semantics, if there's an
- * intervening FORGET_RELATION_FSYNC or FORGET_DATABASE_FSYNC request, so
- * we do it this way. It would be possible to be even smarter if we made
- * the code below understand the specific semantics of such requests (it
- * could blow away preceding entries that would end up being canceled
- * anyhow), but it's not clear that the extra complexity would buy us
- * anything.
- */
- for (n = 0; n < CheckpointerShmem->num_requests; n++)
- {
- CheckpointerRequest *request;
- struct CheckpointerSlotMapping *slotmap;
- bool found;
-
- /*
- * We use the request struct directly as a hashtable key. This
- * assumes that any padding bytes in the structs are consistently the
- * same, which should be okay because we zeroed them in
- * CheckpointerShmemInit. Note also that RelFileNode had better
- * contain no pad bytes.
- */
- request = &CheckpointerShmem->requests[n];
- slotmap = hash_search(htab, request, HASH_ENTER, &found);
- if (found)
- {
- /* Duplicate, so mark the previous occurrence as skippable */
- skip_slot[slotmap->slot] = true;
- num_skipped++;
- }
- /* Remember slot containing latest occurrence of this request value */
- slotmap->slot = n;
- }
-
- /* Done with the hash table. */
- hash_destroy(htab);
-
- /* If no duplicates, we're out of luck. */
- if (!num_skipped)
- {
- pfree(skip_slot);
- return false;
- }
-
- /* We found some duplicates; remove them. */
- preserve_count = 0;
- for (n = 0; n < CheckpointerShmem->num_requests; n++)
- {
- if (skip_slot[n])
- continue;
- CheckpointerShmem->requests[preserve_count++] = CheckpointerShmem->requests[n];
- }
- ereport(DEBUG1,
- (errmsg("compacted fsync request queue from %d entries to %d entries",
- CheckpointerShmem->num_requests, preserve_count)));
- CheckpointerShmem->num_requests = preserve_count;
-
- /* Cleanup. */
- pfree(skip_slot);
- return true;
+ SendFsyncRequest(&request, request.contains_fd ? FileGetRawDesc(file) : -1);
}
/*
* AbsorbFsyncRequests
- * Retrieve queued fsync requests and pass them to local smgr.
+ * Retrieve queued fsync requests and pass them to local smgr. Stop when
+ * resources would be exhausted by absorbing more.
+ *
+ * This is exported because we want to continue accepting requests during
+ * mdsync().
+ */
+void
+AbsorbFsyncRequests(void)
+{
+ if (!AmCheckpointerProcess())
+ return;
+
+ /* Transfer stats counts into pending pgstats message */
+ BgWriterStats.m_buf_written_backend +=
+ pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_writes, 0);
+ BgWriterStats.m_buf_fsync_backend +=
+ pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_fsync, 0);
+
+ while (true)
+ {
+ if (!FlushFsyncRequestQueueIfNecessary())
+ break;
+
+ if (!AbsorbFsyncRequest())
+ break;
+ }
+}
+
+/*
+ * AbsorbAllFsyncRequests
+ * Retrieve all already pending fsync requests and pass them to local
+ * smgr.
*
* This is exported because it must be called during CreateCheckPoint;
* we have to be sure we have accepted all pending requests just before
@@ -1301,17 +1184,13 @@ CompactCheckpointerRequestQueue(void)
* non-checkpointer processes, do nothing if not checkpointer.
*/
void
-AbsorbFsyncRequests(void)
+AbsorbAllFsyncRequests(void)
{
- CheckpointerRequest *requests = NULL;
- CheckpointerRequest *request;
- int n;
+ CheckpointerRequest request = {0};
if (!AmCheckpointerProcess())
return;
- LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
-
/* Transfer stats counts into pending pgstats message */
BgWriterStats.m_buf_written_backend +=
pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_writes, 0);
@@ -1319,35 +1198,61 @@ AbsorbFsyncRequests(void)
pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_fsync, 0);
/*
- * We try to avoid holding the lock for a long time by copying the request
- * array, and processing the requests after releasing the lock.
- *
- * Once we have cleared the requests from shared memory, we have to PANIC
- * if we then fail to absorb them (eg, because our hashtable runs out of
- * memory). This is because the system cannot run safely if we are unable
- * to fsync what we have been told to fsync. Fortunately, the hashtable
- * is so small that the problem is quite unlikely to arise in practice.
+ * For mdsync()'s guarantees to work, all pending fsync requests need to
+ * be executed. But we don't want to absorb requests till the queue is
+ * empty, as that could take a long while. So instead we enqueue
*/
- n = CheckpointerShmem->num_requests;
- if (n > 0)
+ request.type = CKPT_REQUEST_SYN;
+ request.segno = ++next_syn_rqst;
+ SendFsyncRequest(&request, -1);
+
+ received_syn_rqst = next_syn_rqst + 1;
+ while (received_syn_rqst != request.segno)
{
- requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
- memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
+ if (!FlushFsyncRequestQueueIfNecessary())
+ elog(FATAL, "may not happen");
+
+ if (!AbsorbFsyncRequest())
+ break;
+ }
+}
+
+/*
+ * AbsorbFsyncRequest
+ * Retrieve one queued fsync request and pass them to local smgr.
+ */
+static bool
+AbsorbFsyncRequest(void)
+{
+ CheckpointerRequest req;
+ int fd;
+ int ret;
+
+ /* FIXME, this should be a critical section */
+ ReserveTransientFile();
+
+ ret = pg_uds_recv_with_fd(fsync_fds[FSYNC_FD_PROCESS], &req, sizeof(req), &fd);
+ if (ret < 0 && (errno == EWOULDBLOCK || errno == EAGAIN))
+ return false;
+ else if (ret < 0)
+ elog(FATAL, "recvmsg failed: %m");
+
+ if (req.contains_fd != (fd != -1))
+ {
+ elog(FATAL, "message should have fd associated, but doesn't");
}
- START_CRIT_SECTION();
+ if (req.type == CKPT_REQUEST_SYN)
+ {
+ received_syn_rqst = req.segno;
+ Assert(fd == -1);
+ }
+ else
+ {
+ RememberFsyncRequest(req.rnode, req.forknum, req.segno, fd);
+ }
- CheckpointerShmem->num_requests = 0;
-
- LWLockRelease(CheckpointerCommLock);
-
- for (request = requests; n > 0; request++, n--)
- RememberFsyncRequest(request->rnode, request->forknum, request->segno);
-
- END_CRIT_SECTION();
-
- if (requests)
- pfree(requests);
+ return true;
}
/*
@@ -1402,3 +1307,42 @@ IncCheckpointSyncCycle(void)
{
return pg_atomic_fetch_add_u32(&CheckpointerShmem->ckpt_cycle, 1);
}
+
+void
+CountBackendWrite(void)
+{
+ pg_atomic_fetch_add_u32(&CheckpointerShmem->num_backend_writes, 1);
+}
+
+static void
+SendFsyncRequest(CheckpointerRequest *request, int fd)
+{
+ ssize_t ret;
+
+ while (true)
+ {
+ ret = pg_uds_send_with_fd(fsync_fds[FSYNC_FD_SUBMIT], request, sizeof(*request),
+ request->contains_fd ? fd : -1);
+
+ if (ret >= 0)
+ {
+ /*
+ * Don't think short reads will ever happen in realistic
+ * implementations, but better make sure that's true...
+ */
+ if (ret != sizeof(*request))
+ elog(FATAL, "oops, gotta do better");
+ break;
+ }
+ else if (errno == EWOULDBLOCK || errno == EAGAIN)
+ {
+ /* blocked on write - wait for socket to become readable */
+ /* FIXME: postmaster death? Other interrupts? */
+ WaitLatchOrSocket(NULL, WL_SOCKET_WRITEABLE, fsync_fds[FSYNC_FD_SUBMIT], -1, 0);
+ }
+ else
+ {
+ ereport(FATAL, (errmsg("could not receive fsync request: %m")));
+ }
+ }
+}
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index a4b53b33cdd..135aa29bfeb 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -70,6 +70,7 @@
#include <time.h>
#include <sys/wait.h>
#include <ctype.h>
+#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
@@ -434,6 +435,7 @@ static pid_t StartChildProcess(AuxProcType type);
static void StartAutovacuumWorker(void);
static void MaybeStartWalReceiver(void);
static void InitPostmasterDeathWatchHandle(void);
+static void InitFsyncFdSocketPair(void);
/*
* Archiver is allowed to start up at the current postmaster state?
@@ -568,6 +570,8 @@ int postmaster_alive_fds[2] = {-1, -1};
HANDLE PostmasterHandle;
#endif
+int fsync_fds[2] = {-1, -1};
+
/*
* Postmaster main entry point
*/
@@ -1195,6 +1199,11 @@ PostmasterMain(int argc, char *argv[])
*/
InitPostmasterDeathWatchHandle();
+ /*
+ * Initialize socket pair used to transport file descriptors over.
+ */
+ InitFsyncFdSocketPair();
+
#ifdef WIN32
/*
@@ -6443,3 +6452,32 @@ InitPostmasterDeathWatchHandle(void)
GetLastError())));
#endif /* WIN32 */
}
+
+/* Create socket used for requesting fsyncs by checkpointer */
+static void
+InitFsyncFdSocketPair(void)
+{
+ Assert(MyProcPid == PostmasterPid);
+ if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, fsync_fds) < 0)
+ ereport(FATAL,
+ (errcode_for_file_access(),
+ errmsg_internal("could not create fsync sockets: %m")));
+
+ /*
+ * Set O_NONBLOCK on both fds.
+ */
+ if (fcntl(fsync_fds[FSYNC_FD_PROCESS], F_SETFL, O_NONBLOCK) == -1)
+ ereport(FATAL,
+ (errcode_for_socket_access(),
+ errmsg_internal("could not set fsync process socket to nonblocking mode: %m")));
+
+ if (fcntl(fsync_fds[FSYNC_FD_SUBMIT], F_SETFL, O_NONBLOCK) == -1)
+ ereport(FATAL,
+ (errcode_for_socket_access(),
+ errmsg_internal("could not set fsync submit socket to nonblocking mode: %m")));
+
+ /*
+ * FIXME: do DuplicateHandle dance for windows - can that work
+ * trivially?
+ */
+}
diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index 555774320b5..e24b0e9ec39 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -142,8 +142,8 @@ typedef struct
CycleCtr cycle_ctr; /* sync cycle of oldest request */
/* requests[f] has bit n set if we need to fsync segment n of fork f */
Bitmapset *requests[MAX_FORKNUM + 1];
- /* canceled[f] is true if we canceled fsyncs for fork "recently" */
- bool canceled[MAX_FORKNUM + 1];
+ int *syncfds[MAX_FORKNUM + 1];
+ int syncfd_len[MAX_FORKNUM + 1];
} PendingOperationEntry;
typedef struct
@@ -152,6 +152,8 @@ typedef struct
CycleCtr cycle_ctr; /* mdckpt_cycle_ctr when request was made */
} PendingUnlinkEntry;
+static uint32 open_fsync_queue_files = 0;
+static bool mdsync_in_progress = false;
static HTAB *pendingOpsTable = NULL;
static List *pendingUnlinks = NIL;
static MemoryContext pendingOpsCxt; /* context for the above */
@@ -196,6 +198,8 @@ static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
BlockNumber blkno, bool skipFsync, int behavior);
static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
MdfdVec *seg);
+static char *mdpath(RelFileNode rnode, ForkNumber forknum, BlockNumber segno);
+static void mdsyncpass(bool include_current);
/*
@@ -1049,43 +1053,28 @@ mdimmedsync(SMgrRelation reln, ForkNumber forknum)
}
/*
- * mdsync() -- Sync previous writes to stable storage.
+ * Do one pass over the the fsync request hashtable and perform the necessary
+ * fsyncs. Increments the mdsync cycle counter.
+ *
+ * If include_current is true perform all fsyncs (this is done if too many
+ * files are open), otherwise only perform the fsyncs belonging to the cycle
+ * valid at call time.
*/
-void
-mdsync(void)
+static void
+mdsyncpass(bool include_current)
{
- static bool mdsync_in_progress = false;
-
HASH_SEQ_STATUS hstat;
PendingOperationEntry *entry;
int absorb_counter;
/* Statistics on sync times */
- int processed = 0;
instr_time sync_start,
sync_end,
sync_diff;
uint64 elapsed;
- uint64 longest = 0;
- uint64 total_elapsed = 0;
-
- /*
- * This is only called during checkpoints, and checkpoints should only
- * occur in processes that have created a pendingOpsTable.
- */
- if (!pendingOpsTable)
- elog(ERROR, "cannot sync without a pendingOpsTable");
-
- /*
- * If we are in the checkpointer, the sync had better include all fsync
- * requests that were queued by backends up to this point. The tightest
- * race condition that could occur is that a buffer that must be written
- * and fsync'd for the checkpoint could have been dumped by a backend just
- * before it was visited by BufferSync(). We know the backend will have
- * queued an fsync request before clearing the buffer's dirtybit, so we
- * are safe as long as we do an Absorb after completing BufferSync().
- */
- AbsorbFsyncRequests();
+ int processed = CheckpointStats.ckpt_sync_rels;
+ uint64 longest = CheckpointStats.ckpt_longest_sync;
+ uint64 total_elapsed = CheckpointStats.ckpt_agg_sync_time;
/*
* To avoid excess fsync'ing (in the worst case, maybe a never-terminating
@@ -1133,17 +1122,27 @@ mdsync(void)
while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
{
ForkNumber forknum;
+ bool has_remaining;
/*
- * If the entry is new then don't process it this time; it might
- * contain multiple fsync-request bits, but they are all new. Note
- * "continue" bypasses the hash-remove call at the bottom of the loop.
+ * If processing fsync requests because of too may file handles, close
+ * regardless of cycle. Otherwise nothing to be closed might be found,
+ * and we want to make room as quickly as possible so more requests
+ * can be absorbed.
*/
- if (entry->cycle_ctr == GetCheckpointSyncCycle())
- continue;
+ if (!include_current)
+ {
+ /*
+ * If the entry is new then don't process it this time; it might
+ * contain multiple fsync-request bits, but they are all new. Note
+ * "continue" bypasses the hash-remove call at the bottom of the loop.
+ */
+ if (entry->cycle_ctr == GetCheckpointSyncCycle())
+ continue;
- /* Else assert we haven't missed it */
- Assert((CycleCtr) (entry->cycle_ctr + 1) == GetCheckpointSyncCycle());
+ /* Else assert we haven't missed it */
+ Assert((CycleCtr) (entry->cycle_ctr + 1) == GetCheckpointSyncCycle());
+ }
/*
* Scan over the forks and segments represented by the entry.
@@ -1158,158 +1157,151 @@ mdsync(void)
*/
for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
{
- Bitmapset *requests = entry->requests[forknum];
int segno;
- entry->requests[forknum] = NULL;
- entry->canceled[forknum] = false;
-
- while ((segno = bms_first_member(requests)) >= 0)
+ segno = -1;
+ while ((segno = bms_next_member(entry->requests[forknum], segno)) >= 0)
{
- int failures;
+ char *path;
+ int returnCode;
+
+ /*
+ * Temporarily mark as processed. Have to do so before
+ * absorbing further requests, otherwise we might delete a new
+ * requests in a new cycle.
+ */
+ bms_del_member(entry->requests[forknum], segno);
+
+ if (entry->syncfd_len[forknum] <= segno ||
+ entry->syncfds[forknum][segno] == -1)
+ {
+ /*
+ * Optionally open file, if we want to support not
+ * transporting fds as well.
+ */
+ elog(FATAL, "file not opened");
+ }
/*
* If fsync is off then we don't have to bother opening the
* file at all. (We delay checking until this point so that
* changing fsync on the fly behaves sensibly.)
+ *
+ * XXX: Why is that an important goal? Doesn't give any
+ * interesting guarantees afaict?
*/
- if (!enableFsync)
- continue;
-
- /*
- * If in checkpointer, we want to absorb pending requests
- * every so often to prevent overflow of the fsync request
- * queue. It is unspecified whether newly-added entries will
- * be visited by hash_seq_search, but we don't care since we
- * don't need to process them anyway.
- */
- if (--absorb_counter <= 0)
+ if (enableFsync)
{
- AbsorbFsyncRequests();
- absorb_counter = FSYNCS_PER_ABSORB;
- }
-
- /*
- * The fsync table could contain requests to fsync segments
- * that have been deleted (unlinked) by the time we get to
- * them. Rather than just hoping an ENOENT (or EACCES on
- * Windows) error can be ignored, what we do on error is
- * absorb pending requests and then retry. Since mdunlink()
- * queues a "cancel" message before actually unlinking, the
- * fsync request is guaranteed to be marked canceled after the
- * absorb if it really was this case. DROP DATABASE likewise
- * has to tell us to forget fsync requests before it starts
- * deletions.
- */
- for (failures = 0;; failures++) /* loop exits at "break" */
- {
- SMgrRelation reln;
- MdfdVec *seg;
- char *path;
- int save_errno;
-
/*
- * Find or create an smgr hash entry for this relation.
- * This may seem a bit unclean -- md calling smgr? But
- * it's really the best solution. It ensures that the
- * open file reference isn't permanently leaked if we get
- * an error here. (You may say "but an unreferenced
- * SMgrRelation is still a leak!" Not really, because the
- * only case in which a checkpoint is done by a process
- * that isn't about to shut down is in the checkpointer,
- * and it will periodically do smgrcloseall(). This fact
- * justifies our not closing the reln in the success path
- * either, which is a good thing since in non-checkpointer
- * cases we couldn't safely do that.)
+ * The fsync table could contain requests to fsync
+ * segments that have been deleted (unlinked) by the time
+ * we get to them. That used to be problematic, but now
+ * we have a filehandle to the deleted file. That means we
+ * might fsync an empty file superfluously, in a
+ * relatively tight window, which is acceptable.
*/
- reln = smgropen(entry->rnode, InvalidBackendId);
- /* Attempt to open and fsync the target segment */
- seg = _mdfd_getseg(reln, forknum,
- (BlockNumber) segno * (BlockNumber) RELSEG_SIZE,
- false,
- EXTENSION_RETURN_NULL
- | EXTENSION_DONT_CHECK_SIZE);
+ path = mdpath(entry->rnode, forknum, segno);
INSTR_TIME_SET_CURRENT(sync_start);
- if (seg != NULL &&
- FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) >= 0)
+ pgstat_report_wait_start(WAIT_EVENT_DATA_FILE_SYNC);
+ returnCode = pg_fsync(entry->syncfds[forknum][segno]);
+ pgstat_report_wait_end();
+
+ if (returnCode < 0)
{
- /* Success; update statistics about sync timing */
- INSTR_TIME_SET_CURRENT(sync_end);
- sync_diff = sync_end;
- INSTR_TIME_SUBTRACT(sync_diff, sync_start);
- elapsed = INSTR_TIME_GET_MICROSEC(sync_diff);
- if (elapsed > longest)
- longest = elapsed;
- total_elapsed += elapsed;
- processed++;
- if (log_checkpoints)
- elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f msec",
- processed,
- FilePathName(seg->mdfd_vfd),
- (double) elapsed / 1000);
+ /* XXX: decide on policy */
+ bms_add_member(entry->requests[forknum], segno);
- break; /* out of retry loop */
- }
-
- /* Compute file name for use in message */
- save_errno = errno;
- path = _mdfd_segpath(reln, forknum, (BlockNumber) segno);
- errno = save_errno;
-
- /*
- * It is possible that the relation has been dropped or
- * truncated since the fsync request was entered.
- * Therefore, allow ENOENT, but only if we didn't fail
- * already on this file. This applies both for
- * _mdfd_getseg() and for FileSync, since fd.c might have
- * closed the file behind our back.
- *
- * XXX is there any point in allowing more than one retry?
- * Don't see one at the moment, but easy to change the
- * test here if so.
- */
- if (!FILE_POSSIBLY_DELETED(errno) ||
- failures > 0)
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m",
path)));
- else
+ }
+
+ /* Success; update statistics about sync timing */
+ INSTR_TIME_SET_CURRENT(sync_end);
+ sync_diff = sync_end;
+ INSTR_TIME_SUBTRACT(sync_diff, sync_start);
+ elapsed = INSTR_TIME_GET_MICROSEC(sync_diff);
+ if (elapsed > longest)
+ longest = elapsed;
+ total_elapsed += elapsed;
+ processed++;
+ if (log_checkpoints)
ereport(DEBUG1,
- (errcode_for_file_access(),
- errmsg("could not fsync file \"%s\" but retrying: %m",
- path)));
+ (errmsg("checkpoint sync: number=%d file=%s time=%.3f msec",
+ processed,
+ path,
+ (double) elapsed / 1000),
+ errhidestmt(true),
+ errhidecontext(true)));
+
pfree(path);
+ }
+ /*
+ * It shouldn't be possible for a new request to arrive during
+ * the fsync (on error this will not be reached).
+ */
+ Assert(!bms_is_member(segno, entry->requests[forknum]));
+
+ /*
+ * Close file. XXX: centralize code.
+ */
+ {
+ open_fsync_queue_files--;
+ CloseTransientFile(entry->syncfds[forknum][segno]);
+ entry->syncfds[forknum][segno] = -1;
+ }
+
+ /*
+ * If in checkpointer, we want to absorb pending requests every so
+ * often to prevent overflow of the fsync request queue. It is
+ * unspecified whether newly-added entries will be visited by
+ * hash_seq_search, but we don't care since we don't need to process
+ * them anyway.
+ */
+ if (absorb_counter-- <= 0)
+ {
/*
- * Absorb incoming requests and check to see if a cancel
- * arrived for this relation fork.
+ * Don't absorb if too many files are open. This pass will
+ * soon close some, so check again later.
*/
- AbsorbFsyncRequests();
- absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */
-
- if (entry->canceled[forknum])
- break;
- } /* end retry loop */
+ if (open_fsync_queue_files < ((MaxTransientFiles() * 8) / 10))
+ AbsorbFsyncRequests();
+ absorb_counter = FSYNCS_PER_ABSORB;
+ }
}
- bms_free(requests);
}
/*
- * We've finished everything that was requested before we started to
- * scan the entry. If no new requests have been inserted meanwhile,
- * remove the entry. Otherwise, update its cycle counter, as all the
- * requests now in it must have arrived during this cycle.
+ * We've finished everything for the file that was requested before we
+ * started to scan the entry. If no new requests have been inserted
+ * meanwhile, remove the entry. Otherwise, update its cycle counter,
+ * as all the requests now in it must have arrived during this cycle.
+ *
+ * This needs to be checked separately from the above for-each-fork
+ * loop, as new requests for this relation could have been absorbed.
*/
+ has_remaining = false;
for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
{
- if (entry->requests[forknum] != NULL)
- break;
+ if (bms_is_empty(entry->requests[forknum]))
+ {
+ if (entry->syncfds[forknum])
+ {
+ pfree(entry->syncfds[forknum]);
+ entry->syncfds[forknum] = NULL;
+ }
+ bms_free(entry->requests[forknum]);
+ entry->requests[forknum] = NULL;
+ }
+ else
+ has_remaining = true;
}
- if (forknum <= MAX_FORKNUM)
+ if (has_remaining)
entry->cycle_ctr = GetCheckpointSyncCycle();
else
{
@@ -1320,13 +1312,66 @@ mdsync(void)
}
} /* end loop over hashtable entries */
- /* Return sync performance metrics for report at checkpoint end */
+ /* Flag successful completion of mdsync */
+ mdsync_in_progress = false;
+
+ /* Maintain sync performance metrics for report at checkpoint end */
CheckpointStats.ckpt_sync_rels = processed;
CheckpointStats.ckpt_longest_sync = longest;
CheckpointStats.ckpt_agg_sync_time = total_elapsed;
+}
- /* Flag successful completion of mdsync */
- mdsync_in_progress = false;
+/*
+ * mdsync() -- Sync previous writes to stable storage.
+ */
+void
+mdsync(void)
+{
+ /*
+ * This is only called during checkpoints, and checkpoints should only
+ * occur in processes that have created a pendingOpsTable.
+ */
+ if (!pendingOpsTable)
+ elog(ERROR, "cannot sync without a pendingOpsTable");
+
+ /*
+ * If we are in the checkpointer, the sync had better include all fsync
+ * requests that were queued by backends up to this point. The tightest
+ * race condition that could occur is that a buffer that must be written
+ * and fsync'd for the checkpoint could have been dumped by a backend just
+ * before it was visited by BufferSync(). We know the backend will have
+ * queued an fsync request before clearing the buffer's dirtybit, so we
+ * are safe as long as we do an Absorb after completing BufferSync().
+ */
+ AbsorbAllFsyncRequests();
+
+ mdsyncpass(false);
+}
+
+/*
+ * Flush the fsync request queue enough to make sure there's room for at least
+ * one more entry.
+ */
+bool
+FlushFsyncRequestQueueIfNecessary(void)
+{
+ if (mdsync_in_progress)
+ return false;
+
+ while (true)
+ {
+ if (open_fsync_queue_files >= ((MaxTransientFiles() * 8) / 10))
+ {
+ elog(DEBUG1,
+ "flush fsync request queue due to %u open files",
+ open_fsync_queue_files);
+ mdsyncpass(true);
+ }
+ else
+ break;
+ }
+
+ return true;
}
/*
@@ -1411,12 +1456,38 @@ mdpostckpt(void)
*/
if (--absorb_counter <= 0)
{
- AbsorbFsyncRequests();
+ /* XXX: Centralize this condition */
+ if (open_fsync_queue_files < ((MaxTransientFiles() * 8) / 10))
+ AbsorbFsyncRequests();
absorb_counter = UNLINKS_PER_ABSORB;
}
}
}
+
+/*
+ * Return the filename for the specified segment of the relation. The
+ * returned string is palloc'd.
+ */
+static char *
+mdpath(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
+{
+ char *path,
+ *fullpath;
+
+ path = relpathperm(rnode, forknum);
+
+ if (segno > 0)
+ {
+ fullpath = psprintf("%s.%u", path, segno);
+ pfree(path);
+ }
+ else
+ fullpath = path;
+
+ return fullpath;
+}
+
/*
* register_dirty_segment() -- Mark a relation segment as needing fsync
*
@@ -1437,6 +1508,13 @@ register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
pg_memory_barrier();
cycle = GetCheckpointSyncCycle();
+ /*
+ * For historical reasons checkpointer keeps track of the number of time
+ * backends perform writes themselves.
+ */
+ if (!AmBackgroundWriterProcess())
+ CountBackendWrite();
+
/*
* Don't repeatedly register the same segment as dirty.
*
@@ -1449,27 +1527,23 @@ register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
if (pendingOpsTable)
{
- /* push it into local pending-ops table */
- RememberFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno);
- seg->mdfd_dirtied_cycle = cycle;
+ int fd;
+
+ /*
+ * Push it into local pending-ops table.
+ *
+ * Gotta duplicate the fd - we can't have fd.c close it behind our
+ * back, as that'd lead to loosing error reporting guarantees on
+ * linux. RememberFsyncRequest() will manage the lifetime.
+ */
+ ReserveTransientFile();
+ fd = dup(FileGetRawDesc(seg->mdfd_vfd));
+ if (fd < 0)
+ elog(ERROR, "couldn't dup: %m");
+ RememberFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno, fd);
}
else
- {
- if (ForwardFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno))
- {
- seg->mdfd_dirtied_cycle = cycle;
- return; /* passed it off successfully */
- }
-
- ereport(DEBUG1,
- (errmsg("could not forward fsync request because request queue is full")));
-
- if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
- ereport(ERROR,
- (errcode_for_file_access(),
- errmsg("could not fsync file \"%s\": %m",
- FilePathName(seg->mdfd_vfd))));
- }
+ ForwardFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno, seg->mdfd_vfd);
}
/*
@@ -1491,21 +1565,14 @@ register_unlink(RelFileNodeBackend rnode)
{
/* push it into local pending-ops table */
RememberFsyncRequest(rnode.node, MAIN_FORKNUM,
- UNLINK_RELATION_REQUEST);
+ UNLINK_RELATION_REQUEST,
+ -1);
}
else
{
- /*
- * Notify the checkpointer about it. If we fail to queue the request
- * message, we have to sleep and try again, because we can't simply
- * delete the file now. Ugly, but hopefully won't happen often.
- *
- * XXX should we just leave the file orphaned instead?
- */
+ /* Notify the checkpointer about it. */
Assert(IsUnderPostmaster);
- while (!ForwardFsyncRequest(rnode.node, MAIN_FORKNUM,
- UNLINK_RELATION_REQUEST))
- pg_usleep(10000L); /* 10 msec seems a good number */
+ ForwardFsyncRequest(rnode.node, MAIN_FORKNUM, UNLINK_RELATION_REQUEST, -1);
}
}
@@ -1531,7 +1598,7 @@ register_unlink(RelFileNodeBackend rnode)
* heavyweight operation anyhow, so we'll live with it.)
*/
void
-RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
+RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno, int fd)
{
Assert(pendingOpsTable);
@@ -1549,18 +1616,28 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
/*
* We can't just delete the entry since mdsync could have an
* active hashtable scan. Instead we delete the bitmapsets; this
- * is safe because of the way mdsync is coded. We also set the
- * "canceled" flags so that mdsync can tell that a cancel arrived
- * for the fork(s).
+ * is safe because of the way mdsync is coded.
*/
if (forknum == InvalidForkNumber)
{
/* remove requests for all forks */
for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
{
+ int segno;
+
bms_free(entry->requests[forknum]);
entry->requests[forknum] = NULL;
- entry->canceled[forknum] = true;
+
+ for (segno = 0; segno < entry->syncfd_len[forknum]; segno++)
+ {
+ if (entry->syncfds[forknum][segno] != -1)
+ {
+ open_fsync_queue_files--;
+ CloseTransientFile(entry->syncfds[forknum][segno]);
+ entry->syncfds[forknum][segno] = -1;
+ }
+ }
+
}
}
else
@@ -1568,7 +1645,16 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
/* remove requests for single fork */
bms_free(entry->requests[forknum]);
entry->requests[forknum] = NULL;
- entry->canceled[forknum] = true;
+
+ for (segno = 0; segno < entry->syncfd_len[forknum]; segno++)
+ {
+ if (entry->syncfds[forknum][segno] != -1)
+ {
+ open_fsync_queue_files--;
+ CloseTransientFile(entry->syncfds[forknum][segno]);
+ entry->syncfds[forknum][segno] = -1;
+ }
+ }
}
}
}
@@ -1592,7 +1678,6 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
{
bms_free(entry->requests[forknum]);
entry->requests[forknum] = NULL;
- entry->canceled[forknum] = true;
}
}
}
@@ -1646,7 +1731,8 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
{
entry->cycle_ctr = GetCheckpointSyncCycle();
MemSet(entry->requests, 0, sizeof(entry->requests));
- MemSet(entry->canceled, 0, sizeof(entry->canceled));
+ MemSet(entry->syncfds, 0, sizeof(entry->syncfds));
+ MemSet(entry->syncfd_len, 0, sizeof(entry->syncfd_len));
}
/*
@@ -1658,6 +1744,55 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
entry->requests[forknum] = bms_add_member(entry->requests[forknum],
(int) segno);
+ if (fd >= 0)
+ {
+ /* make space for entry */
+ if (entry->syncfds[forknum] == NULL)
+ {
+ int i;
+
+ entry->syncfds[forknum] = palloc(sizeof(int*) * (segno + 1));
+ entry->syncfd_len[forknum] = segno + 1;
+
+ for (i = 0; i <= segno; i++)
+ entry->syncfds[forknum][i] = -1;
+ }
+ else if (entry->syncfd_len[forknum] <= segno)
+ {
+ int i;
+
+ entry->syncfds[forknum] = repalloc(entry->syncfds[forknum],
+ sizeof(int*) * (segno + 1));
+
+ /* initialize newly created entries */
+ for (i = entry->syncfd_len[forknum]; i <= segno; i++)
+ entry->syncfds[forknum][i] = -1;
+
+ entry->syncfd_len[forknum] = segno + 1;
+ }
+
+ if (entry->syncfds[forknum][segno] == -1)
+ {
+ open_fsync_queue_files++;
+ /* caller must have reserved entry */
+ RegisterTransientFile(fd);
+ entry->syncfds[forknum][segno] = fd;
+ }
+ else
+ {
+ /*
+ * File is already open. Have to keep the older fd, errors
+ * might only be reported to it, thus close the one we just
+ * got.
+ *
+ * XXX: check for errrors.
+ */
+ close(fd);
+ }
+
+ FlushFsyncRequestQueueIfNecessary();
+ }
+
MemoryContextSwitchTo(oldcxt);
}
}
@@ -1674,22 +1809,12 @@ ForgetRelationFsyncRequests(RelFileNode rnode, ForkNumber forknum)
if (pendingOpsTable)
{
/* standalone backend or startup process: fsync state is local */
- RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC);
+ RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC, -1);
}
else if (IsUnderPostmaster)
{
- /*
- * Notify the checkpointer about it. If we fail to queue the cancel
- * message, we have to sleep and try again ... ugly, but hopefully
- * won't happen often.
- *
- * XXX should we CHECK_FOR_INTERRUPTS in this loop? Escaping with an
- * error would leave the no-longer-used file still present on disk,
- * which would be bad, so I'm inclined to assume that the checkpointer
- * will always empty the queue soon.
- */
- while (!ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC))
- pg_usleep(10000L); /* 10 msec seems a good number */
+ /* Notify the checkpointer about it. */
+ ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC, -1);
/*
* Note we don't wait for the checkpointer to actually absorb the
@@ -1713,14 +1838,12 @@ ForgetDatabaseFsyncRequests(Oid dbid)
if (pendingOpsTable)
{
/* standalone backend or startup process: fsync state is local */
- RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC);
+ RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC, -1);
}
else if (IsUnderPostmaster)
{
/* see notes in ForgetRelationFsyncRequests */
- while (!ForwardFsyncRequest(rnode, InvalidForkNumber,
- FORGET_DATABASE_FSYNC))
- pg_usleep(10000L); /* 10 msec seems a good number */
+ ForwardFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC, -1);
}
}
diff --git a/src/include/postmaster/bgwriter.h b/src/include/postmaster/bgwriter.h
index 87a5cfad415..58ba671a907 100644
--- a/src/include/postmaster/bgwriter.h
+++ b/src/include/postmaster/bgwriter.h
@@ -16,6 +16,7 @@
#define _BGWRITER_H
#include "storage/block.h"
+#include "storage/fd.h"
#include "storage/relfilenode.h"
@@ -31,9 +32,10 @@ extern void CheckpointerMain(void) pg_attribute_noreturn();
extern void RequestCheckpoint(int flags);
extern void CheckpointWriteDelay(int flags, double progress);
-extern bool ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum,
- BlockNumber segno);
+extern void ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum,
+ BlockNumber segno, File file);
extern void AbsorbFsyncRequests(void);
+extern void AbsorbAllFsyncRequests(void);
extern Size CheckpointerShmemSize(void);
extern void CheckpointerShmemInit(void);
@@ -43,4 +45,6 @@ extern uint32 IncCheckpointSyncCycle(void);
extern bool FirstCallSinceLastCheckpoint(void);
+extern void CountBackendWrite(void);
+
#endif /* _BGWRITER_H */
diff --git a/src/include/postmaster/postmaster.h b/src/include/postmaster/postmaster.h
index 1877eef2391..e2ba64e8984 100644
--- a/src/include/postmaster/postmaster.h
+++ b/src/include/postmaster/postmaster.h
@@ -44,6 +44,11 @@ extern int postmaster_alive_fds[2];
#define POSTMASTER_FD_OWN 1 /* kept open by postmaster only */
#endif
+#define FSYNC_FD_SUBMIT 0
+#define FSYNC_FD_PROCESS 1
+
+extern int fsync_fds[2];
+
extern PGDLLIMPORT const char *progname;
extern void PostmasterMain(int argc, char *argv[]) pg_attribute_noreturn();
diff --git a/src/include/storage/smgr.h b/src/include/storage/smgr.h
index 558e4d8518b..798a9652927 100644
--- a/src/include/storage/smgr.h
+++ b/src/include/storage/smgr.h
@@ -140,7 +140,8 @@ extern void mdpostckpt(void);
extern void SetForwardFsyncRequests(void);
extern void RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum,
- BlockNumber segno);
+ BlockNumber segno, int fd);
+extern bool FlushFsyncRequestQueueIfNecessary(void);
extern void ForgetRelationFsyncRequests(RelFileNode rnode, ForkNumber forknum);
extern void ForgetDatabaseFsyncRequests(Oid dbid);
--
2.17.0.rc1.dirty
Greetings,
* Ashutosh Bapat (ashutosh.bapat@enterprisedb.com) wrote:
On Thu, May 17, 2018 at 11:45 PM, Robert Haas <robertmhaas@gmail.com> wrote:
On Thu, May 17, 2018 at 12:44 PM, Andres Freund <andres@anarazel.de> wrote:
Hi,
On 2018-05-10 09:50:03 +0800, Craig Ringer wrote:
while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status)) != NULL)
{
if (FileSync(src->vfd, WAIT_EVENT_LOGICAL_REWRITE_SYNC) != 0)
- ereport(ERROR,
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", src->path)));To me this (and the other callers) doesn't quite look right. First, I
think we should probably be a bit more restrictive about when PANIC
out. It seems like we should PANIC on ENOSPC and EIO, but possibly not
others. Secondly, I think we should centralize the error handling. It
seems likely that we'll acrue some platform specific workarounds, and I
don't want to copy that knowledge everywhere.Maybe something like:
ereport(promote_eio_to_panic(ERROR), ...)
Well, searching for places where error is reported with level PANIC,
using word PANIC would miss these instances. People will have to
remember to search with promote_eio_to_panic. May be handle the errors
inside FileSync() itself or a wrapper around that.
No, that search wouldn't miss those instances- such a search would find
promote_eio_to_panic() and then someone would go look up the uses of
that function. That hardly seems like a serious issue for folks hacking
on PG.
I'm not saying that having a wrapper around FileSync() would be bad or
having it handle things, but I don't agree with the general notion that
we can't have a function which handles the complicated bits about the
kind of error because someone grep'ing the source for PANIC might have
to do an additional lookup.
Thanks!
Stephen
At 2018-05-18 20:27:57 -0400, sfrost@snowman.net wrote:
I don't agree with the general notion that we can't have a function
which handles the complicated bits about the kind of error because
someone grep'ing the source for PANIC might have to do an additional
lookup.
Or we could just name the function promote_eio_to_PANIC.
(I understood the objection to be about how 'grep PANIC' wouldn't find
these lines at all, not that there would be an additional lookup.)
-- Abhijit
Greetings,
* Abhijit Menon-Sen (ams@2ndQuadrant.com) wrote:
At 2018-05-18 20:27:57 -0400, sfrost@snowman.net wrote:
I don't agree with the general notion that we can't have a function
which handles the complicated bits about the kind of error because
someone grep'ing the source for PANIC might have to do an additional
lookup.Or we could just name the function promote_eio_to_PANIC.
Ugh, I'm not thrilled with that either.
(I understood the objection to be about how 'grep PANIC' wouldn't find
these lines at all, not that there would be an additional lookup.)
... and my point was that 'grep PANIC' would, almost certainly, find the
function promote_eio_to_panic(), and someone could trivially look up all
the callers of that function then.
Thanks!
Stephen
On Sat, May 19, 2018 at 9:03 AM, Andres Freund <andres@anarazel.de> wrote:
I've written a patch series for this. Took me quite a bit longer than I
had hoped.
Great.
I plan to switch to working on something else for a day or two next
week, and then polish this further. I'd greatly appreciate comments till
then.
Took it for a spin on macOS and FreeBSD. First problem:
+ if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, fsync_fds) < 0)
SOCK_CLOEXEC isn't portable (FreeBSD yes since 10, macOS no, others
who knows). Adding FD_CLOEXEC to your later fcntl() calls is probably
the way to do it? I understand from reading the Linux man pages that
there are race conditions with threads but that doesn't apply here.
Next, make check hangs in initdb on both of my pet OSes when md.c
raises an error (fseek fails) and we raise and error while raising and
error and deadlock against ourselves. Backtrace here:
https://paste.debian.net/1025336/
Apparently the initial error was that mdextend() called _mdnblocks()
which called FileSeek() on vfd 43 == fd 30, pathname "base/1/2704",
but when I check my operating system open file descriptor table I find
that there is no fd 30: there is a 29 and a 31, so it has already been
unexpectedly closed.
I could dig further and/or provide a shell on a system with dev tools.
I didn't want to do this now, but I think we should also consider
removing all awareness of segments from the fsync request queue. Instead
it should deal with individual files, and the segmentation should be
handled by md.c. That'll allow us to move all the necessary code to
smgr.c (or checkpointer?); Thomas said that'd be helpful for further
work. I personally think it'd be a lot simpler, because having to have
long bitmaps with only the last bit set for large append only relations
isn't a particularly sensible approach imo. The only thing that that'd
make more complicated is that the file/database unlink requests get more
expensive (as they'd likely need to search the whole table), but that
seems like a sensible tradeoff. Alternatively using a tree structure
would be an alternative obviously. Personally I was thinking that we
should just make the hashtable be over a pathname, that seems most
generic.
+1
I'll be posting a patch shortly that also needs similar machinery, but
can't easily share with md.c due to technical details. I'd love there
to be just one of those, and for it to be simpler and general.
--
Thomas Munro
http://www.enterprisedb.com
On Sat, May 19, 2018 at 4:51 PM, Thomas Munro
<thomas.munro@enterprisedb.com> wrote:
Next, make check hangs in initdb on both of my pet OSes when md.c
raises an error (fseek fails) and we raise and error while raising and
error and deadlock against ourselves. Backtrace here:
https://paste.debian.net/1025336/
Ah, I see now that something similar is happening on Linux too, so I
guess you already knew this.
https://travis-ci.org/postgresql-cfbot/postgresql/builds/380913223
--
Thomas Munro
http://www.enterprisedb.com
On Sat, May 19, 2018 at 6:31 AM, Stephen Frost <sfrost@snowman.net> wrote:
Greetings,
* Abhijit Menon-Sen (ams@2ndQuadrant.com) wrote:
At 2018-05-18 20:27:57 -0400, sfrost@snowman.net wrote:
I don't agree with the general notion that we can't have a function
which handles the complicated bits about the kind of error because
someone grep'ing the source for PANIC might have to do an additional
lookup.Or we could just name the function promote_eio_to_PANIC.
Ugh, I'm not thrilled with that either.
(I understood the objection to be about how 'grep PANIC' wouldn't find
these lines at all, not that there would be an additional lookup.)... and my point was that 'grep PANIC' would, almost certainly, find the
function promote_eio_to_panic(), and someone could trivially look up all
the callers of that function then.
It's not just grep, but tools like cscope, tag. Although, I agree,
that adding a function, if all necessary, is more important than
convenience of finding all the instances of a certain token easily.
--
Best Wishes,
Ashutosh Bapat
EnterpriseDB Corporation
The Postgres Database Company
On 18 May 2018 at 00:44, Andres Freund <andres@anarazel.de> wrote:
Hi,
On 2018-05-10 09:50:03 +0800, Craig Ringer wrote:
while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status))
!= NULL)
{
if (FileSync(src->vfd, WAIT_EVENT_LOGICAL_REWRITE_SYNC)!= 0)
- ereport(ERROR, + ereport(PANIC, (errcode_for_file_access(), errmsg("could not fsync file\"%s\": %m", src->path)));
To me this (and the other callers) doesn't quite look right. First, I
think we should probably be a bit more restrictive about when PANIC
out. It seems like we should PANIC on ENOSPC and EIO, but possibly not
others. Secondly, I think we should centralize the error handling. It
seems likely that we'll acrue some platform specific workarounds, and I
don't want to copy that knowledge everywhere.Also, don't we need the same on close()?
Yes, we do, and that expands the scope a bit.
I agree with Robert that some sort of filter/macro is wise, though naming
it clearly will be tricky.
I'll have a look.
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
On 21 May 2018 at 12:57, Craig Ringer <craig@2ndquadrant.com> wrote:
On 18 May 2018 at 00:44, Andres Freund <andres@anarazel.de> wrote:
Hi,
On 2018-05-10 09:50:03 +0800, Craig Ringer wrote:
while ((src = (RewriteMappingFile *)
hash_seq_search(&seq_status)) != NULL)
{
if (FileSync(src->vfd, WAIT_EVENT_LOGICAL_REWRITE_SYNC)!= 0)
- ereport(ERROR, + ereport(PANIC, (errcode_for_file_access(), errmsg("could not fsync file\"%s\": %m", src->path)));
To me this (and the other callers) doesn't quite look right. First, I
think we should probably be a bit more restrictive about when PANIC
out. It seems like we should PANIC on ENOSPC and EIO, but possibly not
others. Secondly, I think we should centralize the error handling. It
seems likely that we'll acrue some platform specific workarounds, and I
don't want to copy that knowledge everywhere.Also, don't we need the same on close()?
Yes, we do, and that expands the scope a bit.
I agree with Robert that some sort of filter/macro is wise, though naming
it clearly will be tricky.I'll have a look.
On the queue for tomorrow.
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
On 2018-05-19 18:12:52 +1200, Thomas Munro wrote:
On Sat, May 19, 2018 at 4:51 PM, Thomas Munro
<thomas.munro@enterprisedb.com> wrote:Next, make check hangs in initdb on both of my pet OSes when md.c
raises an error (fseek fails) and we raise and error while raising and
error and deadlock against ourselves. Backtrace here:
https://paste.debian.net/1025336/Ah, I see now that something similar is happening on Linux too, so I
guess you already knew this.
I didn't. I cleaned something up and only tested installcheck
after... Singleuser mode was broken.
Attached is a new version.
I've changed my previous attempt at using transient files to using File
type files, but unliked from the LRU so that they're kept open. Not sure
if that's perfect, but seems cleaner.
Greetings,
Andres Freund
Attachments:
v2-0001-freespace-Don-t-constantly-close-files-when-readi.patchtext/x-diff; charset=us-asciiDownload
From 96435b05c9546b6da829043fb10b2a7309216bd2 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Mon, 21 May 2018 15:43:30 -0700
Subject: [PATCH v2 1/6] freespace: Don't constantly close files when reading
buffer.
fsm_readbuf() used to always do an smgrexists() when reading a buffer
beyond the known file size. That currently implies closing the md.c
handle, loosing all the data cached therein. Change this to only
check for file existance when not already known to be larger than 0
blocks.
Author: Andres Freund
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/storage/freespace/freespace.c | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/src/backend/storage/freespace/freespace.c b/src/backend/storage/freespace/freespace.c
index 65c4e74999f..d7569cec5ed 100644
--- a/src/backend/storage/freespace/freespace.c
+++ b/src/backend/storage/freespace/freespace.c
@@ -556,7 +556,7 @@ fsm_readbuf(Relation rel, FSMAddress addr, bool extend)
* not on extension.)
*/
if (rel->rd_smgr->smgr_fsm_nblocks == InvalidBlockNumber ||
- blkno >= rel->rd_smgr->smgr_fsm_nblocks)
+ rel->rd_smgr->smgr_fsm_nblocks == 0)
{
if (smgrexists(rel->rd_smgr, FSM_FORKNUM))
rel->rd_smgr->smgr_fsm_nblocks = smgrnblocks(rel->rd_smgr,
@@ -564,6 +564,9 @@ fsm_readbuf(Relation rel, FSMAddress addr, bool extend)
else
rel->rd_smgr->smgr_fsm_nblocks = 0;
}
+ else if (blkno >= rel->rd_smgr->smgr_fsm_nblocks)
+ rel->rd_smgr->smgr_fsm_nblocks = smgrnblocks(rel->rd_smgr,
+ FSM_FORKNUM);
/* Handle requests beyond EOF */
if (blkno >= rel->rd_smgr->smgr_fsm_nblocks)
--
2.17.0.rc1.dirty
v2-0002-Add-functions-to-send-receive-data-FD-over-a-unix.patchtext/x-diff; charset=us-asciiDownload
From aa533828e6164731006dab92665fa92b7b058d6f Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Mon, 21 May 2018 15:43:30 -0700
Subject: [PATCH v2 2/6] Add functions to send/receive data & FD over a unix
domain socket.
This'll be used by a followup patch changing how the fsync request
queue works, to make it safe on linux.
TODO: This probably should live elsewhere.
Author: Andres Freund
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/storage/file/fd.c | 102 ++++++++++++++++++++++++++++++++++
src/include/storage/fd.h | 4 ++
2 files changed, 106 insertions(+)
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 441f18dcf56..65e46483a44 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -3572,3 +3572,105 @@ MakePGDirectory(const char *directoryName)
{
return mkdir(directoryName, pg_dir_create_mode);
}
+
+/*
+ * Send data over a unix domain socket, optionally (when fd != -1) including a
+ * file descriptor.
+ */
+ssize_t
+pg_uds_send_with_fd(int sock, void *buf, ssize_t buflen, int fd)
+{
+ ssize_t size;
+ struct msghdr msg = {0};
+ struct iovec iov;
+ /* cmsg header, union for correct alignment */
+ union
+ {
+ struct cmsghdr cmsghdr;
+ char control[CMSG_SPACE(sizeof (int))];
+ } cmsgu;
+ struct cmsghdr *cmsg;
+
+ iov.iov_base = buf;
+ iov.iov_len = buflen;
+
+ msg.msg_name = NULL;
+ msg.msg_namelen = 0;
+ msg.msg_iov = &iov;
+ msg.msg_iovlen = 1;
+
+ if (fd >= 0)
+ {
+ msg.msg_control = cmsgu.control;
+ msg.msg_controllen = sizeof(cmsgu.control);
+
+ cmsg = CMSG_FIRSTHDR(&msg);
+ cmsg->cmsg_len = CMSG_LEN(sizeof (int));
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+
+ *((int *) CMSG_DATA(cmsg)) = fd;
+ }
+
+ size = sendmsg(sock, &msg, 0);
+
+ /* errors are returned directly */
+ return size;
+}
+
+/*
+ * Receive data from a unix domain socket. If a file is sent over the socket,
+ * store it in *fd.
+ */
+ssize_t
+pg_uds_recv_with_fd(int sock, void *buf, ssize_t bufsize, int *fd)
+{
+ ssize_t size;
+ struct msghdr msg;
+ struct iovec iov;
+ /* cmsg header, union for correct alignment */
+ union
+ {
+ struct cmsghdr cmsghdr;
+ char control[CMSG_SPACE(sizeof (int))];
+ } cmsgu;
+ struct cmsghdr *cmsg;
+
+ Assert(fd != NULL);
+
+ iov.iov_base = buf;
+ iov.iov_len = bufsize;
+
+ msg.msg_name = NULL;
+ msg.msg_namelen = 0;
+ msg.msg_iov = &iov;
+ msg.msg_iovlen = 1;
+ msg.msg_control = cmsgu.control;
+ msg.msg_controllen = sizeof(cmsgu.control);
+
+ size = recvmsg (sock, &msg, 0);
+
+ if (size < 0)
+ {
+ *fd = -1;
+ return size;
+ }
+
+ cmsg = CMSG_FIRSTHDR(&msg);
+ if (cmsg && cmsg->cmsg_len == CMSG_LEN(sizeof(int)))
+ {
+ if (cmsg->cmsg_level != SOL_SOCKET)
+ elog(FATAL, "unexpected cmsg_level");
+
+ if (cmsg->cmsg_type != SCM_RIGHTS)
+ elog(FATAL, "unexpected cmsg_type");
+
+ *fd = *((int *) CMSG_DATA(cmsg));
+
+ /* FIXME: check / handle additional cmsg structures */
+ }
+ else
+ *fd = -1;
+
+ return size;
+}
diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h
index 8e7c9728f4b..5e016d69a5a 100644
--- a/src/include/storage/fd.h
+++ b/src/include/storage/fd.h
@@ -143,4 +143,8 @@ extern void SyncDataDirectory(void);
#define PG_TEMP_FILES_DIR "pgsql_tmp"
#define PG_TEMP_FILE_PREFIX "pgsql_tmp"
+/* XXX; This should probably go elsewhere */
+ssize_t pg_uds_send_with_fd(int sock, void *buf, ssize_t buflen, int fd);
+ssize_t pg_uds_recv_with_fd(int sock, void *buf, ssize_t bufsize, int *fd);
+
#endif /* FD_H */
--
2.17.0.rc1.dirty
v2-0003-Make-FileGetRawDesc-ensure-there-s-an-associated-.patchtext/x-diff; charset=us-asciiDownload
From 87a6fa9b8d478504b0a4323a3e104b353a239f1a Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Mon, 21 May 2018 15:43:30 -0700
Subject: [PATCH v2 3/6] Make FileGetRawDesc() ensure there's an associated
kernel FD.
Author: Andres Freund
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/storage/file/fd.c | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 65e46483a44..8ae13a51ec1 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -2232,6 +2232,10 @@ int
FileGetRawDesc(File file)
{
Assert(FileIsValid(file));
+
+ if (FileAccess(file))
+ return -1;
+
return VfdCache[file].fd;
}
--
2.17.0.rc1.dirty
v2-0004-WIP-Add-FileOpenForFd.patchtext/x-diff; charset=us-asciiDownload
From 4cdfdef2ff441f5db01dc989a90aecce4dc6b272 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Mon, 21 May 2018 15:43:30 -0700
Subject: [PATCH v2 4/6] WIP: Add FileOpenForFd().
Author: Andres Freund
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/storage/file/fd.c | 68 +++++++++++++++++++++++++++++++----
src/include/storage/fd.h | 2 ++
2 files changed, 64 insertions(+), 6 deletions(-)
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 8ae13a51ec1..50a1cb930f6 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -180,6 +180,7 @@ int max_safe_fds = 32; /* default if not changed */
#define FD_DELETE_AT_CLOSE (1 << 0) /* T = delete when closed */
#define FD_CLOSE_AT_EOXACT (1 << 1) /* T = close at eoXact */
#define FD_TEMP_FILE_LIMIT (1 << 2) /* T = respect temp_file_limit */
+#define FD_NOT_IN_LRU (1 << 3) /* T = not in LRU */
typedef struct vfd
{
@@ -304,7 +305,6 @@ static void LruDelete(File file);
static void Insert(File file);
static int LruInsert(File file);
static bool ReleaseLruFile(void);
-static void ReleaseLruFiles(void);
static File AllocateVfd(void);
static void FreeVfd(File file);
@@ -1176,7 +1176,7 @@ ReleaseLruFile(void)
* Release kernel FDs as needed to get under the max_safe_fds limit.
* After calling this, it's OK to try to open another file.
*/
-static void
+void
ReleaseLruFiles(void)
{
while (nfile + numAllocatedDescs >= max_safe_fds)
@@ -1289,9 +1289,11 @@ FileAccess(File file)
* We now know that the file is open and that it is not the last one
* accessed, so we need to move it to the head of the Lru ring.
*/
-
- Delete(file);
- Insert(file);
+ if (!(VfdCache[file].fdstate & FD_NOT_IN_LRU))
+ {
+ Delete(file);
+ Insert(file);
+ }
}
return 0;
@@ -1414,6 +1416,56 @@ PathNameOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
return file;
}
+/*
+ * Open a File for a pre-existing file descriptor.
+ *
+ * Note that these files will not be closed in an LRU basis, therefore the
+ * caller is responsible for limiting the number of open file descriptors.
+ *
+ * The passed in name is purely for informational purposes.
+ */
+File
+FileOpenForFd(int fd, const char *fileName)
+{
+ char *fnamecopy;
+ File file;
+ Vfd *vfdP;
+
+ /*
+ * We need a malloc'd copy of the file name; fail cleanly if no room.
+ */
+ fnamecopy = strdup(fileName);
+ if (fnamecopy == NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_OUT_OF_MEMORY),
+ errmsg("out of memory")));
+
+ file = AllocateVfd();
+ vfdP = &VfdCache[file];
+
+ /* Close excess kernel FDs. */
+ ReleaseLruFiles();
+
+ vfdP->fd = fd;
+ ++nfile;
+
+ DO_DB(elog(LOG, "FileOpenForFd: success %d/%d (%s)",
+ file, fd, fnamecopy));
+
+ /* NB: Explicitly not inserted into LRU! */
+
+ vfdP->fileName = fnamecopy;
+ /* Saved flags are adjusted to be OK for re-opening file */
+ vfdP->fileFlags = 0;
+ vfdP->fileMode = 0;
+ vfdP->seekPos = 0;
+ vfdP->fileSize = 0;
+ vfdP->fdstate = FD_NOT_IN_LRU;
+ vfdP->resowner = NULL;
+
+ return file;
+}
+
/*
* Create directory 'directory'. If necessary, create 'basedir', which must
* be the directory above it. This is designed for creating the top-level
@@ -1760,7 +1812,11 @@ FileClose(File file)
vfdP->fd = VFD_CLOSED;
/* remove the file from the lru ring */
- Delete(file);
+ if (!(vfdP->fdstate & FD_NOT_IN_LRU))
+ {
+ vfdP->fdstate &= ~FD_NOT_IN_LRU;
+ Delete(file);
+ }
}
if (vfdP->fdstate & FD_TEMP_FILE_LIMIT)
diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h
index 5e016d69a5a..e96e8b13982 100644
--- a/src/include/storage/fd.h
+++ b/src/include/storage/fd.h
@@ -65,6 +65,7 @@ extern int max_safe_fds;
/* Operations on virtual Files --- equivalent to Unix kernel file ops */
extern File PathNameOpenFile(const char *fileName, int fileFlags);
extern File PathNameOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode);
+extern File FileOpenForFd(int fd, const char *fileName);
extern File OpenTemporaryFile(bool interXact);
extern void FileClose(File file);
extern int FilePrefetch(File file, off_t offset, int amount, uint32 wait_event_info);
@@ -127,6 +128,7 @@ extern void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid,
SubTransactionId parentSubid);
extern void RemovePgTempFiles(void);
extern bool looks_like_temp_rel_name(const char *name);
+extern void ReleaseLruFiles(void);
extern int pg_fsync(int fd);
extern int pg_fsync_no_writethrough(int fd);
--
2.17.0.rc1.dirty
v2-0005-WIP-Optimize-register_dirty_segment-to-not-repeat.patchtext/x-diff; charset=us-asciiDownload
From bd7dcdafa752802566d0fef3ac9c126c41f276e4 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Mon, 21 May 2018 15:43:30 -0700
Subject: [PATCH v2 5/6] WIP: Optimize register_dirty_segment() to not
repeatedly queue fsync requests.
Author: Andres Freund
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/postmaster/checkpointer.c | 36 ++++++++++++-------
src/backend/storage/smgr/md.c | 50 +++++++++++++++++++--------
src/include/postmaster/bgwriter.h | 3 ++
3 files changed, 63 insertions(+), 26 deletions(-)
diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c
index 0950ada6019..333eb91c9de 100644
--- a/src/backend/postmaster/checkpointer.c
+++ b/src/backend/postmaster/checkpointer.c
@@ -46,6 +46,7 @@
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
+#include "port/atomics.h"
#include "postmaster/bgwriter.h"
#include "replication/syncrep.h"
#include "storage/bufmgr.h"
@@ -126,8 +127,9 @@ typedef struct
int ckpt_flags; /* checkpoint flags, as defined in xlog.h */
- uint32 num_backend_writes; /* counts user backend buffer writes */
- uint32 num_backend_fsync; /* counts user backend fsync calls */
+ pg_atomic_uint32 num_backend_writes; /* counts user backend buffer writes */
+ pg_atomic_uint32 num_backend_fsync; /* counts user backend fsync calls */
+ pg_atomic_uint32 ckpt_cycle; /* cycle */
int num_requests; /* current # of requests */
int max_requests; /* allocated array size */
@@ -943,6 +945,9 @@ CheckpointerShmemInit(void)
MemSet(CheckpointerShmem, 0, size);
SpinLockInit(&CheckpointerShmem->ckpt_lck);
CheckpointerShmem->max_requests = NBuffers;
+ pg_atomic_init_u32(&CheckpointerShmem->ckpt_cycle, 0);
+ pg_atomic_init_u32(&CheckpointerShmem->num_backend_writes, 0);
+ pg_atomic_init_u32(&CheckpointerShmem->num_backend_fsync, 0);
}
}
@@ -1133,10 +1138,6 @@ ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
- /* Count all backend writes regardless of if they fit in the queue */
- if (!AmBackgroundWriterProcess())
- CheckpointerShmem->num_backend_writes++;
-
/*
* If the checkpointer isn't running or the request queue is full, the
* backend will have to perform its own fsync request. But before forcing
@@ -1151,7 +1152,7 @@ ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
* fsync
*/
if (!AmBackgroundWriterProcess())
- CheckpointerShmem->num_backend_fsync++;
+ pg_atomic_fetch_add_u32(&CheckpointerShmem->num_backend_fsync, 1);
LWLockRelease(CheckpointerCommLock);
return false;
}
@@ -1312,11 +1313,10 @@ AbsorbFsyncRequests(void)
LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
/* Transfer stats counts into pending pgstats message */
- BgWriterStats.m_buf_written_backend += CheckpointerShmem->num_backend_writes;
- BgWriterStats.m_buf_fsync_backend += CheckpointerShmem->num_backend_fsync;
-
- CheckpointerShmem->num_backend_writes = 0;
- CheckpointerShmem->num_backend_fsync = 0;
+ BgWriterStats.m_buf_written_backend +=
+ pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_writes, 0);
+ BgWriterStats.m_buf_fsync_backend +=
+ pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_fsync, 0);
/*
* We try to avoid holding the lock for a long time by copying the request
@@ -1390,3 +1390,15 @@ FirstCallSinceLastCheckpoint(void)
return FirstCall;
}
+
+uint32
+GetCheckpointSyncCycle(void)
+{
+ return pg_atomic_read_u32(&CheckpointerShmem->ckpt_cycle);
+}
+
+uint32
+IncCheckpointSyncCycle(void)
+{
+ return pg_atomic_fetch_add_u32(&CheckpointerShmem->ckpt_cycle, 1);
+}
diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index 2ec103e6047..555774320b5 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -109,6 +109,7 @@ typedef struct _MdfdVec
{
File mdfd_vfd; /* fd number in fd.c's pool */
BlockNumber mdfd_segno; /* segment number, from 0 */
+ uint32 mdfd_dirtied_cycle;
} MdfdVec;
static MemoryContext MdCxt; /* context for all MdfdVec objects */
@@ -133,12 +134,12 @@ static MemoryContext MdCxt; /* context for all MdfdVec objects */
* (Regular backends do not track pending operations locally, but forward
* them to the checkpointer.)
*/
-typedef uint16 CycleCtr; /* can be any convenient integer size */
+typedef uint32 CycleCtr; /* can be any convenient integer size */
typedef struct
{
RelFileNode rnode; /* hash table key (must be first!) */
- CycleCtr cycle_ctr; /* mdsync_cycle_ctr of oldest request */
+ CycleCtr cycle_ctr; /* sync cycle of oldest request */
/* requests[f] has bit n set if we need to fsync segment n of fork f */
Bitmapset *requests[MAX_FORKNUM + 1];
/* canceled[f] is true if we canceled fsyncs for fork "recently" */
@@ -155,7 +156,6 @@ static HTAB *pendingOpsTable = NULL;
static List *pendingUnlinks = NIL;
static MemoryContext pendingOpsCxt; /* context for the above */
-static CycleCtr mdsync_cycle_ctr = 0;
static CycleCtr mdckpt_cycle_ctr = 0;
@@ -333,6 +333,7 @@ mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
mdfd = &reln->md_seg_fds[forkNum][0];
mdfd->mdfd_vfd = fd;
mdfd->mdfd_segno = 0;
+ mdfd->mdfd_dirtied_cycle = GetCheckpointSyncCycle() - 1;
}
/*
@@ -614,6 +615,7 @@ mdopen(SMgrRelation reln, ForkNumber forknum, int behavior)
mdfd = &reln->md_seg_fds[forknum][0];
mdfd->mdfd_vfd = fd;
mdfd->mdfd_segno = 0;
+ mdfd->mdfd_dirtied_cycle = GetCheckpointSyncCycle() - 1;
Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
@@ -1089,9 +1091,9 @@ mdsync(void)
* To avoid excess fsync'ing (in the worst case, maybe a never-terminating
* checkpoint), we want to ignore fsync requests that are entered into the
* hashtable after this point --- they should be processed next time,
- * instead. We use mdsync_cycle_ctr to tell old entries apart from new
- * ones: new ones will have cycle_ctr equal to the incremented value of
- * mdsync_cycle_ctr.
+ * instead. We use GetCheckpointSyncCycle() to tell old entries apart
+ * from new ones: new ones will have cycle_ctr equal to
+ * IncCheckpointSyncCycle().
*
* In normal circumstances, all entries present in the table at this point
* will have cycle_ctr exactly equal to the current (about to be old)
@@ -1115,16 +1117,16 @@ mdsync(void)
hash_seq_init(&hstat, pendingOpsTable);
while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
{
- entry->cycle_ctr = mdsync_cycle_ctr;
+ entry->cycle_ctr = GetCheckpointSyncCycle();
}
}
- /* Advance counter so that new hashtable entries are distinguishable */
- mdsync_cycle_ctr++;
-
/* Set flag to detect failure if we don't reach the end of the loop */
mdsync_in_progress = true;
+ /* Advance counter so that new hashtable entries are distinguishable */
+ IncCheckpointSyncCycle();
+
/* Now scan the hashtable for fsync requests to process */
absorb_counter = FSYNCS_PER_ABSORB;
hash_seq_init(&hstat, pendingOpsTable);
@@ -1137,11 +1139,11 @@ mdsync(void)
* contain multiple fsync-request bits, but they are all new. Note
* "continue" bypasses the hash-remove call at the bottom of the loop.
*/
- if (entry->cycle_ctr == mdsync_cycle_ctr)
+ if (entry->cycle_ctr == GetCheckpointSyncCycle())
continue;
/* Else assert we haven't missed it */
- Assert((CycleCtr) (entry->cycle_ctr + 1) == mdsync_cycle_ctr);
+ Assert((CycleCtr) (entry->cycle_ctr + 1) == GetCheckpointSyncCycle());
/*
* Scan over the forks and segments represented by the entry.
@@ -1308,7 +1310,7 @@ mdsync(void)
break;
}
if (forknum <= MAX_FORKNUM)
- entry->cycle_ctr = mdsync_cycle_ctr;
+ entry->cycle_ctr = GetCheckpointSyncCycle();
else
{
/* Okay to remove it */
@@ -1427,18 +1429,37 @@ mdpostckpt(void)
static void
register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
{
+ uint32 cycle;
+
/* Temp relations should never be fsync'd */
Assert(!SmgrIsTemp(reln));
+ pg_memory_barrier();
+ cycle = GetCheckpointSyncCycle();
+
+ /*
+ * Don't repeatedly register the same segment as dirty.
+ *
+ * FIXME: This doesn't correctly deal with overflows yet! We could
+ * e.g. emit an smgr invalidation every now and then, or use a 64bit
+ * counter. Or just error out if the cycle reaches UINT32_MAX.
+ */
+ if (seg->mdfd_dirtied_cycle == cycle)
+ return;
+
if (pendingOpsTable)
{
/* push it into local pending-ops table */
RememberFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno);
+ seg->mdfd_dirtied_cycle = cycle;
}
else
{
if (ForwardFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno))
+ {
+ seg->mdfd_dirtied_cycle = cycle;
return; /* passed it off successfully */
+ }
ereport(DEBUG1,
(errmsg("could not forward fsync request because request queue is full")));
@@ -1623,7 +1644,7 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
/* if new entry, initialize it */
if (!found)
{
- entry->cycle_ctr = mdsync_cycle_ctr;
+ entry->cycle_ctr = GetCheckpointSyncCycle();
MemSet(entry->requests, 0, sizeof(entry->requests));
MemSet(entry->canceled, 0, sizeof(entry->canceled));
}
@@ -1793,6 +1814,7 @@ _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
v = &reln->md_seg_fds[forknum][segno];
v->mdfd_vfd = fd;
v->mdfd_segno = segno;
+ v->mdfd_dirtied_cycle = GetCheckpointSyncCycle() - 1;
Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
diff --git a/src/include/postmaster/bgwriter.h b/src/include/postmaster/bgwriter.h
index 941c6aba7d1..87a5cfad415 100644
--- a/src/include/postmaster/bgwriter.h
+++ b/src/include/postmaster/bgwriter.h
@@ -38,6 +38,9 @@ extern void AbsorbFsyncRequests(void);
extern Size CheckpointerShmemSize(void);
extern void CheckpointerShmemInit(void);
+extern uint32 GetCheckpointSyncCycle(void);
+extern uint32 IncCheckpointSyncCycle(void);
+
extern bool FirstCallSinceLastCheckpoint(void);
#endif /* _BGWRITER_H */
--
2.17.0.rc1.dirty
v2-0006-Heavily-WIP-Send-file-descriptors-to-checkpointer.patchtext/x-diff; charset=us-asciiDownload
From 306975ba3856c5be31eca5d8efe6d7fe9eee06c6 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Mon, 21 May 2018 15:43:30 -0700
Subject: [PATCH v2 6/6] Heavily-WIP: Send file descriptors to checkpointer for
fsyncing.
This addresses the issue that, at least on linux, fsyncs only reliably
see errors that occurred after they've been opeend.
Author:
Reviewed-By:
Discussion: https://postgr.es/m/
Backpatch:
---
src/backend/access/transam/xlog.c | 7 +-
src/backend/postmaster/checkpointer.c | 354 +++++++----------
src/backend/postmaster/postmaster.c | 38 ++
src/backend/storage/smgr/md.c | 549 ++++++++++++++++----------
src/include/postmaster/bgwriter.h | 8 +-
src/include/postmaster/postmaster.h | 5 +
src/include/storage/smgr.h | 3 +-
7 files changed, 543 insertions(+), 421 deletions(-)
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index adbd6a21264..427774152eb 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -8634,8 +8634,10 @@ CreateCheckPoint(int flags)
* Note: because it is possible for log_checkpoints to change while a
* checkpoint proceeds, we always accumulate stats, even if
* log_checkpoints is currently off.
+ *
+ * Note #2: this is reset at the end of the checkpoint, not here, because
+ * we might have to fsync before getting here (see mdsync()).
*/
- MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
/*
@@ -8999,6 +9001,9 @@ CreateCheckPoint(int flags)
CheckpointStats.ckpt_segs_recycled);
LWLockRelease(CheckpointLock);
+
+ /* reset stats */
+ MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
}
/*
diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c
index 333eb91c9de..c2be529bca4 100644
--- a/src/backend/postmaster/checkpointer.c
+++ b/src/backend/postmaster/checkpointer.c
@@ -48,6 +48,7 @@
#include "pgstat.h"
#include "port/atomics.h"
#include "postmaster/bgwriter.h"
+#include "postmaster/postmaster.h"
#include "replication/syncrep.h"
#include "storage/bufmgr.h"
#include "storage/condition_variable.h"
@@ -102,19 +103,21 @@
*
* The requests array holds fsync requests sent by backends and not yet
* absorbed by the checkpointer.
- *
- * Unlike the checkpoint fields, num_backend_writes, num_backend_fsync, and
- * the requests fields are protected by CheckpointerCommLock.
*----------
*/
typedef struct
{
+ uint32 type;
RelFileNode rnode;
ForkNumber forknum;
BlockNumber segno; /* see md.c for special values */
+ bool contains_fd;
/* might add a real request-type field later; not needed yet */
} CheckpointerRequest;
+#define CKPT_REQUEST_RNODE 1
+#define CKPT_REQUEST_SYN 2
+
typedef struct
{
pid_t checkpointer_pid; /* PID (0 if not started) */
@@ -131,8 +134,6 @@ typedef struct
pg_atomic_uint32 num_backend_fsync; /* counts user backend fsync calls */
pg_atomic_uint32 ckpt_cycle; /* cycle */
- int num_requests; /* current # of requests */
- int max_requests; /* allocated array size */
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER];
} CheckpointerShmemStruct;
@@ -168,13 +169,17 @@ static double ckpt_cached_elapsed;
static pg_time_t last_checkpoint_time;
static pg_time_t last_xlog_switch_time;
+static BlockNumber next_syn_rqst;
+static BlockNumber received_syn_rqst;
+
/* Prototypes for private functions */
static void CheckArchiveTimeout(void);
static bool IsCheckpointOnSchedule(double progress);
static bool ImmediateCheckpointRequested(void);
-static bool CompactCheckpointerRequestQueue(void);
static void UpdateSharedMemoryConfig(void);
+static void SendFsyncRequest(CheckpointerRequest *request, int fd);
+static bool AbsorbFsyncRequest(void);
/* Signal handlers */
@@ -557,10 +562,11 @@ CheckpointerMain(void)
cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
}
- rc = WaitLatch(MyLatch,
- WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
- cur_timeout * 1000L /* convert to ms */ ,
- WAIT_EVENT_CHECKPOINTER_MAIN);
+ rc = WaitLatchOrSocket(MyLatch,
+ WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH | WL_SOCKET_READABLE,
+ fsync_fds[FSYNC_FD_PROCESS],
+ cur_timeout * 1000L /* convert to ms */ ,
+ WAIT_EVENT_CHECKPOINTER_MAIN);
/*
* Emergency bailout if postmaster has died. This is to avoid the
@@ -910,12 +916,7 @@ CheckpointerShmemSize(void)
{
Size size;
- /*
- * Currently, the size of the requests[] array is arbitrarily set equal to
- * NBuffers. This may prove too large or small ...
- */
size = offsetof(CheckpointerShmemStruct, requests);
- size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
return size;
}
@@ -938,13 +939,10 @@ CheckpointerShmemInit(void)
if (!found)
{
/*
- * First time through, so initialize. Note that we zero the whole
- * requests array; this is so that CompactCheckpointerRequestQueue can
- * assume that any pad bytes in the request structs are zeroes.
+ * First time through, so initialize.
*/
MemSet(CheckpointerShmem, 0, size);
SpinLockInit(&CheckpointerShmem->ckpt_lck);
- CheckpointerShmem->max_requests = NBuffers;
pg_atomic_init_u32(&CheckpointerShmem->ckpt_cycle, 0);
pg_atomic_init_u32(&CheckpointerShmem->num_backend_writes, 0);
pg_atomic_init_u32(&CheckpointerShmem->num_backend_fsync, 0);
@@ -1124,176 +1122,61 @@ RequestCheckpoint(int flags)
* the queue is full and contains no duplicate entries. In that case, we
* let the backend know by returning false.
*/
-bool
-ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
+void
+ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno,
+ File file)
{
- CheckpointerRequest *request;
- bool too_full;
+ CheckpointerRequest request = {0};
if (!IsUnderPostmaster)
- return false; /* probably shouldn't even get here */
+ elog(ERROR, "ForwardFsyncRequest must not be called in single user mode");
if (AmCheckpointerProcess())
elog(ERROR, "ForwardFsyncRequest must not be called in checkpointer");
- LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
+ request.type = CKPT_REQUEST_RNODE;
+ request.rnode = rnode;
+ request.forknum = forknum;
+ request.segno = segno;
+ request.contains_fd = file != -1;
- /*
- * If the checkpointer isn't running or the request queue is full, the
- * backend will have to perform its own fsync request. But before forcing
- * that to happen, we can try to compact the request queue.
- */
- if (CheckpointerShmem->checkpointer_pid == 0 ||
- (CheckpointerShmem->num_requests >= CheckpointerShmem->max_requests &&
- !CompactCheckpointerRequestQueue()))
- {
- /*
- * Count the subset of writes where backends have to do their own
- * fsync
- */
- if (!AmBackgroundWriterProcess())
- pg_atomic_fetch_add_u32(&CheckpointerShmem->num_backend_fsync, 1);
- LWLockRelease(CheckpointerCommLock);
- return false;
- }
-
- /* OK, insert request */
- request = &CheckpointerShmem->requests[CheckpointerShmem->num_requests++];
- request->rnode = rnode;
- request->forknum = forknum;
- request->segno = segno;
-
- /* If queue is more than half full, nudge the checkpointer to empty it */
- too_full = (CheckpointerShmem->num_requests >=
- CheckpointerShmem->max_requests / 2);
-
- LWLockRelease(CheckpointerCommLock);
-
- /* ... but not till after we release the lock */
- if (too_full && ProcGlobal->checkpointerLatch)
- SetLatch(ProcGlobal->checkpointerLatch);
-
- return true;
-}
-
-/*
- * CompactCheckpointerRequestQueue
- * Remove duplicates from the request queue to avoid backend fsyncs.
- * Returns "true" if any entries were removed.
- *
- * Although a full fsync request queue is not common, it can lead to severe
- * performance problems when it does happen. So far, this situation has
- * only been observed to occur when the system is under heavy write load,
- * and especially during the "sync" phase of a checkpoint. Without this
- * logic, each backend begins doing an fsync for every block written, which
- * gets very expensive and can slow down the whole system.
- *
- * Trying to do this every time the queue is full could lose if there
- * aren't any removable entries. But that should be vanishingly rare in
- * practice: there's one queue entry per shared buffer.
- */
-static bool
-CompactCheckpointerRequestQueue(void)
-{
- struct CheckpointerSlotMapping
- {
- CheckpointerRequest request;
- int slot;
- };
-
- int n,
- preserve_count;
- int num_skipped = 0;
- HASHCTL ctl;
- HTAB *htab;
- bool *skip_slot;
-
- /* must hold CheckpointerCommLock in exclusive mode */
- Assert(LWLockHeldByMe(CheckpointerCommLock));
-
- /* Initialize skip_slot array */
- skip_slot = palloc0(sizeof(bool) * CheckpointerShmem->num_requests);
-
- /* Initialize temporary hash table */
- MemSet(&ctl, 0, sizeof(ctl));
- ctl.keysize = sizeof(CheckpointerRequest);
- ctl.entrysize = sizeof(struct CheckpointerSlotMapping);
- ctl.hcxt = CurrentMemoryContext;
-
- htab = hash_create("CompactCheckpointerRequestQueue",
- CheckpointerShmem->num_requests,
- &ctl,
- HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
-
- /*
- * The basic idea here is that a request can be skipped if it's followed
- * by a later, identical request. It might seem more sensible to work
- * backwards from the end of the queue and check whether a request is
- * *preceded* by an earlier, identical request, in the hopes of doing less
- * copying. But that might change the semantics, if there's an
- * intervening FORGET_RELATION_FSYNC or FORGET_DATABASE_FSYNC request, so
- * we do it this way. It would be possible to be even smarter if we made
- * the code below understand the specific semantics of such requests (it
- * could blow away preceding entries that would end up being canceled
- * anyhow), but it's not clear that the extra complexity would buy us
- * anything.
- */
- for (n = 0; n < CheckpointerShmem->num_requests; n++)
- {
- CheckpointerRequest *request;
- struct CheckpointerSlotMapping *slotmap;
- bool found;
-
- /*
- * We use the request struct directly as a hashtable key. This
- * assumes that any padding bytes in the structs are consistently the
- * same, which should be okay because we zeroed them in
- * CheckpointerShmemInit. Note also that RelFileNode had better
- * contain no pad bytes.
- */
- request = &CheckpointerShmem->requests[n];
- slotmap = hash_search(htab, request, HASH_ENTER, &found);
- if (found)
- {
- /* Duplicate, so mark the previous occurrence as skippable */
- skip_slot[slotmap->slot] = true;
- num_skipped++;
- }
- /* Remember slot containing latest occurrence of this request value */
- slotmap->slot = n;
- }
-
- /* Done with the hash table. */
- hash_destroy(htab);
-
- /* If no duplicates, we're out of luck. */
- if (!num_skipped)
- {
- pfree(skip_slot);
- return false;
- }
-
- /* We found some duplicates; remove them. */
- preserve_count = 0;
- for (n = 0; n < CheckpointerShmem->num_requests; n++)
- {
- if (skip_slot[n])
- continue;
- CheckpointerShmem->requests[preserve_count++] = CheckpointerShmem->requests[n];
- }
- ereport(DEBUG1,
- (errmsg("compacted fsync request queue from %d entries to %d entries",
- CheckpointerShmem->num_requests, preserve_count)));
- CheckpointerShmem->num_requests = preserve_count;
-
- /* Cleanup. */
- pfree(skip_slot);
- return true;
+ SendFsyncRequest(&request, request.contains_fd ? FileGetRawDesc(file) : -1);
}
/*
* AbsorbFsyncRequests
- * Retrieve queued fsync requests and pass them to local smgr.
+ * Retrieve queued fsync requests and pass them to local smgr. Stop when
+ * resources would be exhausted by absorbing more.
+ *
+ * This is exported because we want to continue accepting requests during
+ * mdsync().
+ */
+void
+AbsorbFsyncRequests(void)
+{
+ if (!AmCheckpointerProcess())
+ return;
+
+ /* Transfer stats counts into pending pgstats message */
+ BgWriterStats.m_buf_written_backend +=
+ pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_writes, 0);
+ BgWriterStats.m_buf_fsync_backend +=
+ pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_fsync, 0);
+
+ while (true)
+ {
+ if (!FlushFsyncRequestQueueIfNecessary())
+ break;
+
+ if (!AbsorbFsyncRequest())
+ break;
+ }
+}
+
+/*
+ * AbsorbAllFsyncRequests
+ * Retrieve all already pending fsync requests and pass them to local
+ * smgr.
*
* This is exported because it must be called during CreateCheckPoint;
* we have to be sure we have accepted all pending requests just before
@@ -1301,17 +1184,13 @@ CompactCheckpointerRequestQueue(void)
* non-checkpointer processes, do nothing if not checkpointer.
*/
void
-AbsorbFsyncRequests(void)
+AbsorbAllFsyncRequests(void)
{
- CheckpointerRequest *requests = NULL;
- CheckpointerRequest *request;
- int n;
+ CheckpointerRequest request = {0};
if (!AmCheckpointerProcess())
return;
- LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
-
/* Transfer stats counts into pending pgstats message */
BgWriterStats.m_buf_written_backend +=
pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_writes, 0);
@@ -1319,35 +1198,65 @@ AbsorbFsyncRequests(void)
pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_fsync, 0);
/*
- * We try to avoid holding the lock for a long time by copying the request
- * array, and processing the requests after releasing the lock.
- *
- * Once we have cleared the requests from shared memory, we have to PANIC
- * if we then fail to absorb them (eg, because our hashtable runs out of
- * memory). This is because the system cannot run safely if we are unable
- * to fsync what we have been told to fsync. Fortunately, the hashtable
- * is so small that the problem is quite unlikely to arise in practice.
+ * For mdsync()'s guarantees to work, all pending fsync requests need to
+ * be executed. But we don't want to absorb requests till the queue is
+ * empty, as that could take a long while. So instead we enqueue
*/
- n = CheckpointerShmem->num_requests;
- if (n > 0)
+ request.type = CKPT_REQUEST_SYN;
+ request.segno = ++next_syn_rqst;
+ SendFsyncRequest(&request, -1);
+
+ received_syn_rqst = next_syn_rqst + 1;
+ while (received_syn_rqst != request.segno)
{
- requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
- memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
+ if (!FlushFsyncRequestQueueIfNecessary())
+ elog(FATAL, "may not happen");
+
+ if (!AbsorbFsyncRequest())
+ break;
}
+}
+
+/*
+ * AbsorbFsyncRequest
+ * Retrieve one queued fsync request and pass them to local smgr.
+ */
+static bool
+AbsorbFsyncRequest(void)
+{
+ CheckpointerRequest req;
+ int fd;
+ int ret;
+
+ ReleaseLruFiles();
START_CRIT_SECTION();
+ ret = pg_uds_recv_with_fd(fsync_fds[FSYNC_FD_PROCESS], &req, sizeof(req), &fd);
+ if (ret < 0 && (errno == EWOULDBLOCK || errno == EAGAIN))
+ {
+ END_CRIT_SECTION();
+ return false;
+ }
+ else if (ret < 0)
+ elog(ERROR, "recvmsg failed: %m");
- CheckpointerShmem->num_requests = 0;
-
- LWLockRelease(CheckpointerCommLock);
-
- for (request = requests; n > 0; request++, n--)
- RememberFsyncRequest(request->rnode, request->forknum, request->segno);
+ if (req.contains_fd != (fd != -1))
+ {
+ elog(FATAL, "message should have fd associated, but doesn't");
+ }
+ if (req.type == CKPT_REQUEST_SYN)
+ {
+ received_syn_rqst = req.segno;
+ Assert(fd == -1);
+ }
+ else
+ {
+ RememberFsyncRequest(req.rnode, req.forknum, req.segno, fd);
+ }
END_CRIT_SECTION();
- if (requests)
- pfree(requests);
+ return true;
}
/*
@@ -1402,3 +1311,42 @@ IncCheckpointSyncCycle(void)
{
return pg_atomic_fetch_add_u32(&CheckpointerShmem->ckpt_cycle, 1);
}
+
+void
+CountBackendWrite(void)
+{
+ pg_atomic_fetch_add_u32(&CheckpointerShmem->num_backend_writes, 1);
+}
+
+static void
+SendFsyncRequest(CheckpointerRequest *request, int fd)
+{
+ ssize_t ret;
+
+ while (true)
+ {
+ ret = pg_uds_send_with_fd(fsync_fds[FSYNC_FD_SUBMIT], request, sizeof(*request),
+ request->contains_fd ? fd : -1);
+
+ if (ret >= 0)
+ {
+ /*
+ * Don't think short reads will ever happen in realistic
+ * implementations, but better make sure that's true...
+ */
+ if (ret != sizeof(*request))
+ elog(FATAL, "oops, gotta do better");
+ break;
+ }
+ else if (errno == EWOULDBLOCK || errno == EAGAIN)
+ {
+ /* blocked on write - wait for socket to become readable */
+ /* FIXME: postmaster death? Other interrupts? */
+ WaitLatchOrSocket(NULL, WL_SOCKET_WRITEABLE, fsync_fds[FSYNC_FD_SUBMIT], -1, 0);
+ }
+ else
+ {
+ ereport(FATAL, (errmsg("could not receive fsync request: %m")));
+ }
+ }
+}
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index a4b53b33cdd..135aa29bfeb 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -70,6 +70,7 @@
#include <time.h>
#include <sys/wait.h>
#include <ctype.h>
+#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
@@ -434,6 +435,7 @@ static pid_t StartChildProcess(AuxProcType type);
static void StartAutovacuumWorker(void);
static void MaybeStartWalReceiver(void);
static void InitPostmasterDeathWatchHandle(void);
+static void InitFsyncFdSocketPair(void);
/*
* Archiver is allowed to start up at the current postmaster state?
@@ -568,6 +570,8 @@ int postmaster_alive_fds[2] = {-1, -1};
HANDLE PostmasterHandle;
#endif
+int fsync_fds[2] = {-1, -1};
+
/*
* Postmaster main entry point
*/
@@ -1195,6 +1199,11 @@ PostmasterMain(int argc, char *argv[])
*/
InitPostmasterDeathWatchHandle();
+ /*
+ * Initialize socket pair used to transport file descriptors over.
+ */
+ InitFsyncFdSocketPair();
+
#ifdef WIN32
/*
@@ -6443,3 +6452,32 @@ InitPostmasterDeathWatchHandle(void)
GetLastError())));
#endif /* WIN32 */
}
+
+/* Create socket used for requesting fsyncs by checkpointer */
+static void
+InitFsyncFdSocketPair(void)
+{
+ Assert(MyProcPid == PostmasterPid);
+ if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, fsync_fds) < 0)
+ ereport(FATAL,
+ (errcode_for_file_access(),
+ errmsg_internal("could not create fsync sockets: %m")));
+
+ /*
+ * Set O_NONBLOCK on both fds.
+ */
+ if (fcntl(fsync_fds[FSYNC_FD_PROCESS], F_SETFL, O_NONBLOCK) == -1)
+ ereport(FATAL,
+ (errcode_for_socket_access(),
+ errmsg_internal("could not set fsync process socket to nonblocking mode: %m")));
+
+ if (fcntl(fsync_fds[FSYNC_FD_SUBMIT], F_SETFL, O_NONBLOCK) == -1)
+ ereport(FATAL,
+ (errcode_for_socket_access(),
+ errmsg_internal("could not set fsync submit socket to nonblocking mode: %m")));
+
+ /*
+ * FIXME: do DuplicateHandle dance for windows - can that work
+ * trivially?
+ */
+}
diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index 555774320b5..ae3a5bf023f 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -142,8 +142,8 @@ typedef struct
CycleCtr cycle_ctr; /* sync cycle of oldest request */
/* requests[f] has bit n set if we need to fsync segment n of fork f */
Bitmapset *requests[MAX_FORKNUM + 1];
- /* canceled[f] is true if we canceled fsyncs for fork "recently" */
- bool canceled[MAX_FORKNUM + 1];
+ File *syncfds[MAX_FORKNUM + 1];
+ int syncfd_len[MAX_FORKNUM + 1];
} PendingOperationEntry;
typedef struct
@@ -152,6 +152,8 @@ typedef struct
CycleCtr cycle_ctr; /* mdckpt_cycle_ctr when request was made */
} PendingUnlinkEntry;
+static uint32 open_fsync_queue_files = 0;
+static bool mdsync_in_progress = false;
static HTAB *pendingOpsTable = NULL;
static List *pendingUnlinks = NIL;
static MemoryContext pendingOpsCxt; /* context for the above */
@@ -196,6 +198,8 @@ static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
BlockNumber blkno, bool skipFsync, int behavior);
static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
MdfdVec *seg);
+static char *mdpath(RelFileNode rnode, ForkNumber forknum, BlockNumber segno);
+static void mdsyncpass(bool include_current);
/*
@@ -1049,43 +1053,28 @@ mdimmedsync(SMgrRelation reln, ForkNumber forknum)
}
/*
- * mdsync() -- Sync previous writes to stable storage.
+ * Do one pass over the the fsync request hashtable and perform the necessary
+ * fsyncs. Increments the mdsync cycle counter.
+ *
+ * If include_current is true perform all fsyncs (this is done if too many
+ * files are open), otherwise only perform the fsyncs belonging to the cycle
+ * valid at call time.
*/
-void
-mdsync(void)
+static void
+mdsyncpass(bool include_current)
{
- static bool mdsync_in_progress = false;
-
HASH_SEQ_STATUS hstat;
PendingOperationEntry *entry;
int absorb_counter;
/* Statistics on sync times */
- int processed = 0;
instr_time sync_start,
sync_end,
sync_diff;
uint64 elapsed;
- uint64 longest = 0;
- uint64 total_elapsed = 0;
-
- /*
- * This is only called during checkpoints, and checkpoints should only
- * occur in processes that have created a pendingOpsTable.
- */
- if (!pendingOpsTable)
- elog(ERROR, "cannot sync without a pendingOpsTable");
-
- /*
- * If we are in the checkpointer, the sync had better include all fsync
- * requests that were queued by backends up to this point. The tightest
- * race condition that could occur is that a buffer that must be written
- * and fsync'd for the checkpoint could have been dumped by a backend just
- * before it was visited by BufferSync(). We know the backend will have
- * queued an fsync request before clearing the buffer's dirtybit, so we
- * are safe as long as we do an Absorb after completing BufferSync().
- */
- AbsorbFsyncRequests();
+ int processed = CheckpointStats.ckpt_sync_rels;
+ uint64 longest = CheckpointStats.ckpt_longest_sync;
+ uint64 total_elapsed = CheckpointStats.ckpt_agg_sync_time;
/*
* To avoid excess fsync'ing (in the worst case, maybe a never-terminating
@@ -1133,17 +1122,27 @@ mdsync(void)
while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
{
ForkNumber forknum;
+ bool has_remaining;
/*
- * If the entry is new then don't process it this time; it might
- * contain multiple fsync-request bits, but they are all new. Note
- * "continue" bypasses the hash-remove call at the bottom of the loop.
+ * If processing fsync requests because of too may file handles, close
+ * regardless of cycle. Otherwise nothing to be closed might be found,
+ * and we want to make room as quickly as possible so more requests
+ * can be absorbed.
*/
- if (entry->cycle_ctr == GetCheckpointSyncCycle())
- continue;
+ if (!include_current)
+ {
+ /*
+ * If the entry is new then don't process it this time; it might
+ * contain multiple fsync-request bits, but they are all new. Note
+ * "continue" bypasses the hash-remove call at the bottom of the loop.
+ */
+ if (entry->cycle_ctr == GetCheckpointSyncCycle())
+ continue;
- /* Else assert we haven't missed it */
- Assert((CycleCtr) (entry->cycle_ctr + 1) == GetCheckpointSyncCycle());
+ /* Else assert we haven't missed it */
+ Assert((CycleCtr) (entry->cycle_ctr + 1) == GetCheckpointSyncCycle());
+ }
/*
* Scan over the forks and segments represented by the entry.
@@ -1158,158 +1157,144 @@ mdsync(void)
*/
for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
{
- Bitmapset *requests = entry->requests[forknum];
int segno;
- entry->requests[forknum] = NULL;
- entry->canceled[forknum] = false;
-
- while ((segno = bms_first_member(requests)) >= 0)
+ segno = -1;
+ while ((segno = bms_next_member(entry->requests[forknum], segno)) >= 0)
{
- int failures;
+ int returnCode;
+
+ /*
+ * Temporarily mark as processed. Have to do so before
+ * absorbing further requests, otherwise we might delete a new
+ * requests in a new cycle.
+ */
+ bms_del_member(entry->requests[forknum], segno);
+
+ if (entry->syncfd_len[forknum] <= segno ||
+ entry->syncfds[forknum][segno] == -1)
+ {
+ /*
+ * Optionally open file, if we want to support not
+ * transporting fds as well.
+ */
+ elog(FATAL, "file not opened");
+ }
/*
* If fsync is off then we don't have to bother opening the
* file at all. (We delay checking until this point so that
* changing fsync on the fly behaves sensibly.)
+ *
+ * XXX: Why is that an important goal? Doesn't give any
+ * interesting guarantees afaict?
*/
- if (!enableFsync)
- continue;
-
- /*
- * If in checkpointer, we want to absorb pending requests
- * every so often to prevent overflow of the fsync request
- * queue. It is unspecified whether newly-added entries will
- * be visited by hash_seq_search, but we don't care since we
- * don't need to process them anyway.
- */
- if (--absorb_counter <= 0)
+ if (enableFsync)
{
- AbsorbFsyncRequests();
- absorb_counter = FSYNCS_PER_ABSORB;
- }
-
- /*
- * The fsync table could contain requests to fsync segments
- * that have been deleted (unlinked) by the time we get to
- * them. Rather than just hoping an ENOENT (or EACCES on
- * Windows) error can be ignored, what we do on error is
- * absorb pending requests and then retry. Since mdunlink()
- * queues a "cancel" message before actually unlinking, the
- * fsync request is guaranteed to be marked canceled after the
- * absorb if it really was this case. DROP DATABASE likewise
- * has to tell us to forget fsync requests before it starts
- * deletions.
- */
- for (failures = 0;; failures++) /* loop exits at "break" */
- {
- SMgrRelation reln;
- MdfdVec *seg;
- char *path;
- int save_errno;
-
/*
- * Find or create an smgr hash entry for this relation.
- * This may seem a bit unclean -- md calling smgr? But
- * it's really the best solution. It ensures that the
- * open file reference isn't permanently leaked if we get
- * an error here. (You may say "but an unreferenced
- * SMgrRelation is still a leak!" Not really, because the
- * only case in which a checkpoint is done by a process
- * that isn't about to shut down is in the checkpointer,
- * and it will periodically do smgrcloseall(). This fact
- * justifies our not closing the reln in the success path
- * either, which is a good thing since in non-checkpointer
- * cases we couldn't safely do that.)
+ * The fsync table could contain requests to fsync
+ * segments that have been deleted (unlinked) by the time
+ * we get to them. That used to be problematic, but now
+ * we have a filehandle to the deleted file. That means we
+ * might fsync an empty file superfluously, in a
+ * relatively tight window, which is acceptable.
*/
- reln = smgropen(entry->rnode, InvalidBackendId);
-
- /* Attempt to open and fsync the target segment */
- seg = _mdfd_getseg(reln, forknum,
- (BlockNumber) segno * (BlockNumber) RELSEG_SIZE,
- false,
- EXTENSION_RETURN_NULL
- | EXTENSION_DONT_CHECK_SIZE);
INSTR_TIME_SET_CURRENT(sync_start);
- if (seg != NULL &&
- FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) >= 0)
+ returnCode = FileSync(entry->syncfds[forknum][segno], WAIT_EVENT_DATA_FILE_SYNC);
+
+ if (returnCode < 0)
{
- /* Success; update statistics about sync timing */
- INSTR_TIME_SET_CURRENT(sync_end);
- sync_diff = sync_end;
- INSTR_TIME_SUBTRACT(sync_diff, sync_start);
- elapsed = INSTR_TIME_GET_MICROSEC(sync_diff);
- if (elapsed > longest)
- longest = elapsed;
- total_elapsed += elapsed;
- processed++;
- if (log_checkpoints)
- elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f msec",
- processed,
- FilePathName(seg->mdfd_vfd),
- (double) elapsed / 1000);
+ /* XXX: decide on policy */
+ bms_add_member(entry->requests[forknum], segno);
- break; /* out of retry loop */
- }
-
- /* Compute file name for use in message */
- save_errno = errno;
- path = _mdfd_segpath(reln, forknum, (BlockNumber) segno);
- errno = save_errno;
-
- /*
- * It is possible that the relation has been dropped or
- * truncated since the fsync request was entered.
- * Therefore, allow ENOENT, but only if we didn't fail
- * already on this file. This applies both for
- * _mdfd_getseg() and for FileSync, since fd.c might have
- * closed the file behind our back.
- *
- * XXX is there any point in allowing more than one retry?
- * Don't see one at the moment, but easy to change the
- * test here if so.
- */
- if (!FILE_POSSIBLY_DELETED(errno) ||
- failures > 0)
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m",
- path)));
- else
+ FilePathName(entry->syncfds[forknum][segno]))));
+ }
+
+ /* Success; update statistics about sync timing */
+ INSTR_TIME_SET_CURRENT(sync_end);
+ sync_diff = sync_end;
+ INSTR_TIME_SUBTRACT(sync_diff, sync_start);
+ elapsed = INSTR_TIME_GET_MICROSEC(sync_diff);
+ if (elapsed > longest)
+ longest = elapsed;
+ total_elapsed += elapsed;
+ processed++;
+ if (log_checkpoints)
ereport(DEBUG1,
- (errcode_for_file_access(),
- errmsg("could not fsync file \"%s\" but retrying: %m",
- path)));
- pfree(path);
+ (errmsg("checkpoint sync: number=%d file=%s time=%.3f msec",
+ processed,
+ FilePathName(entry->syncfds[forknum][segno]),
+ (double) elapsed / 1000),
+ errhidestmt(true),
+ errhidecontext(true)));
+ }
+ /*
+ * It shouldn't be possible for a new request to arrive during
+ * the fsync (on error this will not be reached).
+ */
+ Assert(!bms_is_member(segno, entry->requests[forknum]));
+
+ /*
+ * Close file. XXX: centralize code.
+ */
+ {
+ open_fsync_queue_files--;
+ FileClose(entry->syncfds[forknum][segno]);
+ entry->syncfds[forknum][segno] = -1;
+ }
+
+ /*
+ * If in checkpointer, we want to absorb pending requests every so
+ * often to prevent overflow of the fsync request queue. It is
+ * unspecified whether newly-added entries will be visited by
+ * hash_seq_search, but we don't care since we don't need to process
+ * them anyway.
+ */
+ if (absorb_counter-- <= 0)
+ {
/*
- * Absorb incoming requests and check to see if a cancel
- * arrived for this relation fork.
+ * Don't absorb if too many files are open. This pass will
+ * soon close some, so check again later.
*/
- AbsorbFsyncRequests();
- absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */
-
- if (entry->canceled[forknum])
- break;
- } /* end retry loop */
+ if (open_fsync_queue_files < ((max_safe_fds * 7) / 10))
+ AbsorbFsyncRequests();
+ absorb_counter = FSYNCS_PER_ABSORB;
+ }
}
- bms_free(requests);
}
/*
- * We've finished everything that was requested before we started to
- * scan the entry. If no new requests have been inserted meanwhile,
- * remove the entry. Otherwise, update its cycle counter, as all the
- * requests now in it must have arrived during this cycle.
+ * We've finished everything for the file that was requested before we
+ * started to scan the entry. If no new requests have been inserted
+ * meanwhile, remove the entry. Otherwise, update its cycle counter,
+ * as all the requests now in it must have arrived during this cycle.
+ *
+ * This needs to be checked separately from the above for-each-fork
+ * loop, as new requests for this relation could have been absorbed.
*/
+ has_remaining = false;
for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
{
- if (entry->requests[forknum] != NULL)
- break;
+ if (bms_is_empty(entry->requests[forknum]))
+ {
+ if (entry->syncfds[forknum])
+ {
+ pfree(entry->syncfds[forknum]);
+ entry->syncfds[forknum] = NULL;
+ }
+ bms_free(entry->requests[forknum]);
+ entry->requests[forknum] = NULL;
+ }
+ else
+ has_remaining = true;
}
- if (forknum <= MAX_FORKNUM)
+ if (has_remaining)
entry->cycle_ctr = GetCheckpointSyncCycle();
else
{
@@ -1320,13 +1305,69 @@ mdsync(void)
}
} /* end loop over hashtable entries */
- /* Return sync performance metrics for report at checkpoint end */
+ /* Flag successful completion of mdsync */
+ mdsync_in_progress = false;
+
+ /* Maintain sync performance metrics for report at checkpoint end */
CheckpointStats.ckpt_sync_rels = processed;
CheckpointStats.ckpt_longest_sync = longest;
CheckpointStats.ckpt_agg_sync_time = total_elapsed;
+}
- /* Flag successful completion of mdsync */
- mdsync_in_progress = false;
+/*
+ * mdsync() -- Sync previous writes to stable storage.
+ */
+void
+mdsync(void)
+{
+ /*
+ * This is only called during checkpoints, and checkpoints should only
+ * occur in processes that have created a pendingOpsTable.
+ */
+ if (!pendingOpsTable)
+ elog(ERROR, "cannot sync without a pendingOpsTable");
+
+ /*
+ * If we are in the checkpointer, the sync had better include all fsync
+ * requests that were queued by backends up to this point. The tightest
+ * race condition that could occur is that a buffer that must be written
+ * and fsync'd for the checkpoint could have been dumped by a backend just
+ * before it was visited by BufferSync(). We know the backend will have
+ * queued an fsync request before clearing the buffer's dirtybit, so we
+ * are safe as long as we do an Absorb after completing BufferSync().
+ */
+ AbsorbAllFsyncRequests();
+
+ mdsyncpass(false);
+}
+
+/*
+ * Flush the fsync request queue enough to make sure there's room for at least
+ * one more entry.
+ */
+bool
+FlushFsyncRequestQueueIfNecessary(void)
+{
+ if (mdsync_in_progress)
+ return false;
+
+ while (true)
+ {
+ if (open_fsync_queue_files >= ((max_safe_fds * 7) / 10))
+ {
+ elog(DEBUG1,
+ "flush fsync request queue due to %u open files",
+ open_fsync_queue_files);
+ mdsyncpass(true);
+ elog(DEBUG1,
+ "flushed fsync request, now at %u open files",
+ open_fsync_queue_files);
+ }
+ else
+ break;
+ }
+
+ return true;
}
/*
@@ -1411,12 +1452,38 @@ mdpostckpt(void)
*/
if (--absorb_counter <= 0)
{
- AbsorbFsyncRequests();
+ /* XXX: Centralize this condition */
+ if (open_fsync_queue_files < ((max_safe_fds * 7) / 10))
+ AbsorbFsyncRequests();
absorb_counter = UNLINKS_PER_ABSORB;
}
}
}
+
+/*
+ * Return the filename for the specified segment of the relation. The
+ * returned string is palloc'd.
+ */
+static char *
+mdpath(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
+{
+ char *path,
+ *fullpath;
+
+ path = relpathperm(rnode, forknum);
+
+ if (segno > 0)
+ {
+ fullpath = psprintf("%s.%u", path, segno);
+ pfree(path);
+ }
+ else
+ fullpath = path;
+
+ return fullpath;
+}
+
/*
* register_dirty_segment() -- Mark a relation segment as needing fsync
*
@@ -1437,6 +1504,13 @@ register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
pg_memory_barrier();
cycle = GetCheckpointSyncCycle();
+ /*
+ * For historical reasons checkpointer keeps track of the number of time
+ * backends perform writes themselves.
+ */
+ if (!AmBackgroundWriterProcess())
+ CountBackendWrite();
+
/*
* Don't repeatedly register the same segment as dirty.
*
@@ -1449,27 +1523,23 @@ register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
if (pendingOpsTable)
{
- /* push it into local pending-ops table */
- RememberFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno);
- seg->mdfd_dirtied_cycle = cycle;
+ int fd;
+
+ /*
+ * Push it into local pending-ops table.
+ *
+ * Gotta duplicate the fd - we can't have fd.c close it behind our
+ * back, as that'd lead to loosing error reporting guarantees on
+ * linux. RememberFsyncRequest() will manage the lifetime.
+ */
+ ReleaseLruFiles();
+ fd = dup(FileGetRawDesc(seg->mdfd_vfd));
+ if (fd < 0)
+ elog(ERROR, "couldn't dup: %m");
+ RememberFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno, fd);
}
else
- {
- if (ForwardFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno))
- {
- seg->mdfd_dirtied_cycle = cycle;
- return; /* passed it off successfully */
- }
-
- ereport(DEBUG1,
- (errmsg("could not forward fsync request because request queue is full")));
-
- if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
- ereport(ERROR,
- (errcode_for_file_access(),
- errmsg("could not fsync file \"%s\": %m",
- FilePathName(seg->mdfd_vfd))));
- }
+ ForwardFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno, seg->mdfd_vfd);
}
/*
@@ -1491,21 +1561,14 @@ register_unlink(RelFileNodeBackend rnode)
{
/* push it into local pending-ops table */
RememberFsyncRequest(rnode.node, MAIN_FORKNUM,
- UNLINK_RELATION_REQUEST);
+ UNLINK_RELATION_REQUEST,
+ -1);
}
else
{
- /*
- * Notify the checkpointer about it. If we fail to queue the request
- * message, we have to sleep and try again, because we can't simply
- * delete the file now. Ugly, but hopefully won't happen often.
- *
- * XXX should we just leave the file orphaned instead?
- */
+ /* Notify the checkpointer about it. */
Assert(IsUnderPostmaster);
- while (!ForwardFsyncRequest(rnode.node, MAIN_FORKNUM,
- UNLINK_RELATION_REQUEST))
- pg_usleep(10000L); /* 10 msec seems a good number */
+ ForwardFsyncRequest(rnode.node, MAIN_FORKNUM, UNLINK_RELATION_REQUEST, -1);
}
}
@@ -1531,7 +1594,7 @@ register_unlink(RelFileNodeBackend rnode)
* heavyweight operation anyhow, so we'll live with it.)
*/
void
-RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
+RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno, int fd)
{
Assert(pendingOpsTable);
@@ -1549,18 +1612,28 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
/*
* We can't just delete the entry since mdsync could have an
* active hashtable scan. Instead we delete the bitmapsets; this
- * is safe because of the way mdsync is coded. We also set the
- * "canceled" flags so that mdsync can tell that a cancel arrived
- * for the fork(s).
+ * is safe because of the way mdsync is coded.
*/
if (forknum == InvalidForkNumber)
{
/* remove requests for all forks */
for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
{
+ int segno;
+
bms_free(entry->requests[forknum]);
entry->requests[forknum] = NULL;
- entry->canceled[forknum] = true;
+
+ for (segno = 0; segno < entry->syncfd_len[forknum]; segno++)
+ {
+ if (entry->syncfds[forknum][segno] != -1)
+ {
+ open_fsync_queue_files--;
+ FileClose(entry->syncfds[forknum][segno]);
+ entry->syncfds[forknum][segno] = -1;
+ }
+ }
+
}
}
else
@@ -1568,7 +1641,16 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
/* remove requests for single fork */
bms_free(entry->requests[forknum]);
entry->requests[forknum] = NULL;
- entry->canceled[forknum] = true;
+
+ for (segno = 0; segno < entry->syncfd_len[forknum]; segno++)
+ {
+ if (entry->syncfds[forknum][segno] != -1)
+ {
+ open_fsync_queue_files--;
+ FileClose(entry->syncfds[forknum][segno]);
+ entry->syncfds[forknum][segno] = -1;
+ }
+ }
}
}
}
@@ -1592,7 +1674,6 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
{
bms_free(entry->requests[forknum]);
entry->requests[forknum] = NULL;
- entry->canceled[forknum] = true;
}
}
}
@@ -1646,7 +1727,8 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
{
entry->cycle_ctr = GetCheckpointSyncCycle();
MemSet(entry->requests, 0, sizeof(entry->requests));
- MemSet(entry->canceled, 0, sizeof(entry->canceled));
+ MemSet(entry->syncfds, 0, sizeof(entry->syncfds));
+ MemSet(entry->syncfd_len, 0, sizeof(entry->syncfd_len));
}
/*
@@ -1658,6 +1740,57 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
entry->requests[forknum] = bms_add_member(entry->requests[forknum],
(int) segno);
+ if (fd >= 0)
+ {
+ /* make space for entry */
+ if (entry->syncfds[forknum] == NULL)
+ {
+ int i;
+
+ entry->syncfds[forknum] = palloc(sizeof(File) * (segno + 1));
+ entry->syncfd_len[forknum] = segno + 1;
+
+ for (i = 0; i <= segno; i++)
+ entry->syncfds[forknum][i] = -1;
+ }
+ else if (entry->syncfd_len[forknum] <= segno)
+ {
+ int i;
+
+ entry->syncfds[forknum] = repalloc(entry->syncfds[forknum],
+ sizeof(File) * (segno + 1));
+
+ /* initialize newly created entries */
+ for (i = entry->syncfd_len[forknum]; i <= segno; i++)
+ entry->syncfds[forknum][i] = -1;
+
+ entry->syncfd_len[forknum] = segno + 1;
+ }
+
+ if (entry->syncfds[forknum][segno] == -1)
+ {
+ char *path = mdpath(entry->rnode, forknum, segno);
+ open_fsync_queue_files++;
+ /* caller must have reserved entry */
+ entry->syncfds[forknum][segno] =
+ FileOpenForFd(fd, path);
+ pfree(path);
+ }
+ else
+ {
+ /*
+ * File is already open. Have to keep the older fd, errors
+ * might only be reported to it, thus close the one we just
+ * got.
+ *
+ * XXX: check for errrors.
+ */
+ close(fd);
+ }
+
+ FlushFsyncRequestQueueIfNecessary();
+ }
+
MemoryContextSwitchTo(oldcxt);
}
}
@@ -1674,22 +1807,12 @@ ForgetRelationFsyncRequests(RelFileNode rnode, ForkNumber forknum)
if (pendingOpsTable)
{
/* standalone backend or startup process: fsync state is local */
- RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC);
+ RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC, -1);
}
else if (IsUnderPostmaster)
{
- /*
- * Notify the checkpointer about it. If we fail to queue the cancel
- * message, we have to sleep and try again ... ugly, but hopefully
- * won't happen often.
- *
- * XXX should we CHECK_FOR_INTERRUPTS in this loop? Escaping with an
- * error would leave the no-longer-used file still present on disk,
- * which would be bad, so I'm inclined to assume that the checkpointer
- * will always empty the queue soon.
- */
- while (!ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC))
- pg_usleep(10000L); /* 10 msec seems a good number */
+ /* Notify the checkpointer about it. */
+ ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC, -1);
/*
* Note we don't wait for the checkpointer to actually absorb the
@@ -1713,14 +1836,12 @@ ForgetDatabaseFsyncRequests(Oid dbid)
if (pendingOpsTable)
{
/* standalone backend or startup process: fsync state is local */
- RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC);
+ RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC, -1);
}
else if (IsUnderPostmaster)
{
/* see notes in ForgetRelationFsyncRequests */
- while (!ForwardFsyncRequest(rnode, InvalidForkNumber,
- FORGET_DATABASE_FSYNC))
- pg_usleep(10000L); /* 10 msec seems a good number */
+ ForwardFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC, -1);
}
}
diff --git a/src/include/postmaster/bgwriter.h b/src/include/postmaster/bgwriter.h
index 87a5cfad415..58ba671a907 100644
--- a/src/include/postmaster/bgwriter.h
+++ b/src/include/postmaster/bgwriter.h
@@ -16,6 +16,7 @@
#define _BGWRITER_H
#include "storage/block.h"
+#include "storage/fd.h"
#include "storage/relfilenode.h"
@@ -31,9 +32,10 @@ extern void CheckpointerMain(void) pg_attribute_noreturn();
extern void RequestCheckpoint(int flags);
extern void CheckpointWriteDelay(int flags, double progress);
-extern bool ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum,
- BlockNumber segno);
+extern void ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum,
+ BlockNumber segno, File file);
extern void AbsorbFsyncRequests(void);
+extern void AbsorbAllFsyncRequests(void);
extern Size CheckpointerShmemSize(void);
extern void CheckpointerShmemInit(void);
@@ -43,4 +45,6 @@ extern uint32 IncCheckpointSyncCycle(void);
extern bool FirstCallSinceLastCheckpoint(void);
+extern void CountBackendWrite(void);
+
#endif /* _BGWRITER_H */
diff --git a/src/include/postmaster/postmaster.h b/src/include/postmaster/postmaster.h
index 1877eef2391..e2ba64e8984 100644
--- a/src/include/postmaster/postmaster.h
+++ b/src/include/postmaster/postmaster.h
@@ -44,6 +44,11 @@ extern int postmaster_alive_fds[2];
#define POSTMASTER_FD_OWN 1 /* kept open by postmaster only */
#endif
+#define FSYNC_FD_SUBMIT 0
+#define FSYNC_FD_PROCESS 1
+
+extern int fsync_fds[2];
+
extern PGDLLIMPORT const char *progname;
extern void PostmasterMain(int argc, char *argv[]) pg_attribute_noreturn();
diff --git a/src/include/storage/smgr.h b/src/include/storage/smgr.h
index 558e4d8518b..798a9652927 100644
--- a/src/include/storage/smgr.h
+++ b/src/include/storage/smgr.h
@@ -140,7 +140,8 @@ extern void mdpostckpt(void);
extern void SetForwardFsyncRequests(void);
extern void RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum,
- BlockNumber segno);
+ BlockNumber segno, int fd);
+extern bool FlushFsyncRequestQueueIfNecessary(void);
extern void ForgetRelationFsyncRequests(RelFileNode rnode, ForkNumber forknum);
extern void ForgetDatabaseFsyncRequests(Oid dbid);
--
2.17.0.rc1.dirty
On 22 May 2018 at 03:08, Andres Freund <andres@anarazel.de> wrote:
On 2018-05-19 18:12:52 +1200, Thomas Munro wrote:On Sat, May 19, 2018 at 4:51 PM, Thomas Munro
<thomas.munro@enterprisedb.com> wrote:Next, make check hangs in initdb on both of my pet OSes when md.c
raises an error (fseek fails) and we raise and error while raising and
error and deadlock against ourselves. Backtrace here:
https://paste.debian.net/1025336/Ah, I see now that something similar is happening on Linux too, so I
guess you already knew this.I didn't. I cleaned something up and only tested installcheck
after... Singleuser mode was broken.Attached is a new version.
I've changed my previous attempt at using transient files to using File
type files, but unliked from the LRU so that they're kept open. Not sure
if that's perfect, but seems cleaner.
Thanks for the patch. Out of curiosity I tried to play with it a bit.
`pgbench -i -s 100` actually hang on my machine, because the
copy process ended up with waiting after `pg_uds_send_with_fd`
had
errno == EWOULDBLOCK || errno == EAGAIN
as well as the checkpointer process. Looks like with the default
configuration and `max_wal_size=1GB` it writes more than reads to a
socket, and a buffer eventually becomes full. I've increased
SO_RCVBUF/SO_SNDBUF and `max_wal_size` independently to
check it, and in both cases the problem disappeared (but I assume
only for this particular scale). Is it something that was already considered?
Hi,
On 2018-05-22 17:37:28 +0200, Dmitry Dolgov wrote:
Thanks for the patch. Out of curiosity I tried to play with it a bit.
Thanks.
`pgbench -i -s 100` actually hang on my machine, because the
copy process ended up with waiting after `pg_uds_send_with_fd`
had
Hm, that had worked at some point...
errno == EWOULDBLOCK || errno == EAGAIN
as well as the checkpointer process.
What do you mean with that latest sentence?
Looks like with the default
configuration and `max_wal_size=1GB` it writes more than reads to a
socket, and a buffer eventually becomes full.
That's intended to then wake up the checkpointer immediately, so it can
absorb the requests. So something isn't right yet.
I've increased SO_RCVBUF/SO_SNDBUF and `max_wal_size` independently to
check it, and in both cases the problem disappeared (but I assume only
for this particular scale). Is it something that was already
considered?
It's considered. Tuning up those might help with performance, but
shouldn't required from a correctness POV. Hm.
Greetings,
Andres Freund
On 2018-05-22 08:57:18 -0700, Andres Freund wrote:
Hi,
On 2018-05-22 17:37:28 +0200, Dmitry Dolgov wrote:
Thanks for the patch. Out of curiosity I tried to play with it a bit.
Thanks.
`pgbench -i -s 100` actually hang on my machine, because the
copy process ended up with waiting after `pg_uds_send_with_fd`
hadHm, that had worked at some point...
errno == EWOULDBLOCK || errno == EAGAIN
as well as the checkpointer process.
What do you mean with that latest sentence?
Looks like with the default
configuration and `max_wal_size=1GB` it writes more than reads to a
socket, and a buffer eventually becomes full.That's intended to then wake up the checkpointer immediately, so it can
absorb the requests. So something isn't right yet.
Doesn't hang here, but it's way too slow. Reason for that is that I've
wrongly resolved a merge conflict. Attached is a fixup patch - does that
address the issue for you?
Greetings,
Andres Freund
Attachments:
0001-Fix-and-improve-pg_atomic_flag-fallback-implementati.patchtext/x-diff; charset=us-asciiDownload
From 3b98662adf5e0f82375b50833bc618403614a461 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Fri, 6 Apr 2018 16:17:01 -0700
Subject: [PATCH 1/2] Fix and improve pg_atomic_flag fallback implementation.
The atomics fallback implementation for pg_atomic_flag was broken,
returning the inverted value from pg_atomic_test_set_flag(). This was
unnoticed because a) atomic flags were unused until recently b) the
test code wasn't run when the fallback implementation was in
use (because it didn't allow to test for some edge cases).
Fix the bug, and improve the fallback so it has the same behaviour as
the non-fallback implementation in the problematic edge cases. That
breaks ABI compatibility in the back branches when fallbacks are in
use, but given they were broken until now...
Author: Andres Freund
Reported-by: Daniel Gustafsson
Discussion: https://postgr.es/m/FB948276-7B32-4B77-83E6-D00167F8EEB4@yesql.se
Backpatch: 9.5-, where the atomics abstraction was introduced.
---
src/backend/port/atomics.c | 21 +++++++++++++++++++--
src/include/port/atomics/fallback.h | 13 ++-----------
src/test/regress/regress.c | 14 --------------
3 files changed, 21 insertions(+), 27 deletions(-)
diff --git a/src/backend/port/atomics.c b/src/backend/port/atomics.c
index e4e4734dd23..caa84bf2b62 100644
--- a/src/backend/port/atomics.c
+++ b/src/backend/port/atomics.c
@@ -68,18 +68,35 @@ pg_atomic_init_flag_impl(volatile pg_atomic_flag *ptr)
#else
SpinLockInit((slock_t *) &ptr->sema);
#endif
+
+ ptr->value = false;
}
bool
pg_atomic_test_set_flag_impl(volatile pg_atomic_flag *ptr)
{
- return TAS((slock_t *) &ptr->sema);
+ uint32 oldval;
+
+ SpinLockAcquire((slock_t *) &ptr->sema);
+ oldval = ptr->value;
+ ptr->value = true;
+ SpinLockRelease((slock_t *) &ptr->sema);
+
+ return oldval == 0;
}
void
pg_atomic_clear_flag_impl(volatile pg_atomic_flag *ptr)
{
- S_UNLOCK((slock_t *) &ptr->sema);
+ SpinLockAcquire((slock_t *) &ptr->sema);
+ ptr->value = false;
+ SpinLockRelease((slock_t *) &ptr->sema);
+}
+
+bool
+pg_atomic_unlocked_test_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ return ptr->value == 0;
}
#endif /* PG_HAVE_ATOMIC_FLAG_SIMULATION */
diff --git a/src/include/port/atomics/fallback.h b/src/include/port/atomics/fallback.h
index 7b9dcad8073..88a967ad5b9 100644
--- a/src/include/port/atomics/fallback.h
+++ b/src/include/port/atomics/fallback.h
@@ -80,6 +80,7 @@ typedef struct pg_atomic_flag
#else
int sema;
#endif
+ volatile bool value;
} pg_atomic_flag;
#endif /* PG_HAVE_ATOMIC_FLAG_SUPPORT */
@@ -132,17 +133,7 @@ extern bool pg_atomic_test_set_flag_impl(volatile pg_atomic_flag *ptr);
extern void pg_atomic_clear_flag_impl(volatile pg_atomic_flag *ptr);
#define PG_HAVE_ATOMIC_UNLOCKED_TEST_FLAG
-static inline bool
-pg_atomic_unlocked_test_flag_impl(volatile pg_atomic_flag *ptr)
-{
- /*
- * Can't do this efficiently in the semaphore based implementation - we'd
- * have to try to acquire the semaphore - so always return true. That's
- * correct, because this is only an unlocked test anyway. Do this in the
- * header so compilers can optimize the test away.
- */
- return true;
-}
+extern bool pg_atomic_unlocked_test_flag_impl(volatile pg_atomic_flag *ptr);
#endif /* PG_HAVE_ATOMIC_FLAG_SIMULATION */
diff --git a/src/test/regress/regress.c b/src/test/regress/regress.c
index e14322c798a..8bc562ee4f0 100644
--- a/src/test/regress/regress.c
+++ b/src/test/regress/regress.c
@@ -633,7 +633,6 @@ wait_pid(PG_FUNCTION_ARGS)
PG_RETURN_VOID();
}
-#ifndef PG_HAVE_ATOMIC_FLAG_SIMULATION
static void
test_atomic_flag(void)
{
@@ -663,7 +662,6 @@ test_atomic_flag(void)
pg_atomic_clear_flag(&flag);
}
-#endif /* PG_HAVE_ATOMIC_FLAG_SIMULATION */
static void
test_atomic_uint32(void)
@@ -846,19 +844,7 @@ PG_FUNCTION_INFO_V1(test_atomic_ops);
Datum
test_atomic_ops(PG_FUNCTION_ARGS)
{
- /* ---
- * Can't run the test under the semaphore emulation, it doesn't handle
- * checking two edge cases well:
- * - pg_atomic_unlocked_test_flag() always returns true
- * - locking a already locked flag blocks
- * it seems better to not test the semaphore fallback here, than weaken
- * the checks for the other cases. The semaphore code will be the same
- * everywhere, whereas the efficient implementations wont.
- * ---
- */
-#ifndef PG_HAVE_ATOMIC_FLAG_SIMULATION
test_atomic_flag();
-#endif
test_atomic_uint32();
--
2.17.0.rc1.dirty
On 22 May 2018 at 18:47, Andres Freund <andres@anarazel.de> wrote:
On 2018-05-22 08:57:18 -0700, Andres Freund wrote:Hi,
On 2018-05-22 17:37:28 +0200, Dmitry Dolgov wrote:
Thanks for the patch. Out of curiosity I tried to play with it a bit.
Thanks.
`pgbench -i -s 100` actually hang on my machine, because the
copy process ended up with waiting after `pg_uds_send_with_fd`
hadHm, that had worked at some point...
errno == EWOULDBLOCK || errno == EAGAIN
as well as the checkpointer process.
What do you mean with that latest sentence?
To investigate what's happening I attached with gdb to two processes, COPY
process from pgbench and checkpointer (since I assumed it may be involved).
Both were waiting in WaitLatchOrSocket right after SendFsyncRequest.
Looks like with the default
configuration and `max_wal_size=1GB` it writes more than reads to a
socket, and a buffer eventually becomes full.That's intended to then wake up the checkpointer immediately, so it can
absorb the requests. So something isn't right yet.Doesn't hang here, but it's way too slow.
Yep, in my case it was also getting slower, but eventually hang.
Reason for that is that I've wrongly resolved a merge conflict. Attached is a
fixup patch - does that address the issue for you?
Hm...is it a correct patch? I see the same committed in
8c3debbbf61892dabd8b6f3f8d55e600a7901f2b, so I can't really apply it.
On 2018-05-22 20:54:46 +0200, Dmitry Dolgov wrote:
On 22 May 2018 at 18:47, Andres Freund <andres@anarazel.de> wrote:
On 2018-05-22 08:57:18 -0700, Andres Freund wrote:Hi,
On 2018-05-22 17:37:28 +0200, Dmitry Dolgov wrote:
Thanks for the patch. Out of curiosity I tried to play with it a bit.
Thanks.
`pgbench -i -s 100` actually hang on my machine, because the
copy process ended up with waiting after `pg_uds_send_with_fd`
hadHm, that had worked at some point...
errno == EWOULDBLOCK || errno == EAGAIN
as well as the checkpointer process.
What do you mean with that latest sentence?
To investigate what's happening I attached with gdb to two processes, COPY
process from pgbench and checkpointer (since I assumed it may be involved).
Both were waiting in WaitLatchOrSocket right after SendFsyncRequest.
Huh? Checkpointer was in SendFsyncRequest()? Coudl you share the
backtrace?
Looks like with the default
configuration and `max_wal_size=1GB` it writes more than reads to a
socket, and a buffer eventually becomes full.That's intended to then wake up the checkpointer immediately, so it can
absorb the requests. So something isn't right yet.Doesn't hang here, but it's way too slow.
Yep, in my case it was also getting slower, but eventually hang.
Reason for that is that I've wrongly resolved a merge conflict. Attached is a
fixup patch - does that address the issue for you?Hm...is it a correct patch? I see the same committed in
8c3debbbf61892dabd8b6f3f8d55e600a7901f2b, so I can't really apply it.
Yea, sorry for that. Too many files in my patch directory... Right one
attached.
Greetings,
Andres Freund
Attachments:
0001-fixup-WIP-Optimize-register_dirty_segment-to-not-rep.patchtext/x-diff; charset=us-asciiDownload
From 483b98fd21b40e2997a1f164155cae698204ec25 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Tue, 22 May 2018 09:38:58 -0700
Subject: [PATCH] fixup! WIP: Optimize register_dirty_segment() to not
repeatedly queue fsync requests.
Merge failure.
---
src/backend/storage/smgr/md.c | 2 ++
1 file changed, 2 insertions(+)
diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index ae3a5bf023f..942e2dcf788 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -1540,6 +1540,8 @@ register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
}
else
ForwardFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno, seg->mdfd_vfd);
+
+ seg->mdfd_dirtied_cycle = cycle;
}
/*
--
2.17.0.rc1.dirty
On 22 May 2018 at 20:59, Andres Freund <andres@anarazel.de> wrote:
On 2018-05-22 20:54:46 +0200, Dmitry Dolgov wrote:On 22 May 2018 at 18:47, Andres Freund <andres@anarazel.de> wrote:
On 2018-05-22 08:57:18 -0700, Andres Freund wrote:Hi,
On 2018-05-22 17:37:28 +0200, Dmitry Dolgov wrote:
Thanks for the patch. Out of curiosity I tried to play with it a bit.
Thanks.
`pgbench -i -s 100` actually hang on my machine, because the
copy process ended up with waiting after `pg_uds_send_with_fd`
hadHm, that had worked at some point...
errno == EWOULDBLOCK || errno == EAGAIN
as well as the checkpointer process.
What do you mean with that latest sentence?
To investigate what's happening I attached with gdb to two processes, COPY
process from pgbench and checkpointer (since I assumed it may be involved).
Both were waiting in WaitLatchOrSocket right after SendFsyncRequest.Huh? Checkpointer was in SendFsyncRequest()? Coudl you share the
backtrace?
Well, that's what I've got from gdb:
#0 0x00007fae03fae9f3 in __epoll_wait_nocancel () at
../sysdeps/unix/syscall-template.S:84
#1 0x000000000077a979 in WaitEventSetWaitBlock (nevents=1,
occurred_events=0x7ffe37529ec0, cur_timeout=-1, set=0x23cddf8) at
latch.c:1048
#2 WaitEventSetWait (set=set@entry=0x23cddf8,
timeout=timeout@entry=-1,
occurred_events=occurred_events@entry=0x7ffe37529ec0,
nevents=nevents@entry=1, wait_event_info=wait_event_info@entry=0) at
latch.c:1000
#3 0x000000000077ad08 in WaitLatchOrSocket
(latch=latch@entry=0x0, wakeEvents=wakeEvents@entry=4, sock=8,
timeout=timeout@entry=-1, wait_event_info=wait_event_info@entry=0) at
latch.c:385
#4 0x00000000007152cb in SendFsyncRequest
(request=request@entry=0x7ffe37529f40, fd=fd@entry=-1) at
checkpointer.c:1345
#5 0x0000000000716223 in AbsorbAllFsyncRequests () at checkpointer.c:1207
#6 0x000000000079a5f0 in mdsync () at md.c:1339
#7 0x000000000079c672 in smgrsync () at smgr.c:766
#8 0x000000000076dd53 in CheckPointBuffers (flags=flags@entry=64)
at bufmgr.c:2581
#9 0x000000000051c681 in CheckPointGuts
(checkPointRedo=722254352, flags=flags@entry=64) at xlog.c:9079
#10 0x0000000000523c4a in CreateCheckPoint (flags=flags@entry=64)
at xlog.c:8863
#11 0x0000000000715f41 in CheckpointerMain () at checkpointer.c:494
#12 0x00000000005329f4 in AuxiliaryProcessMain (argc=argc@entry=2,
argv=argv@entry=0x7ffe3752a220) at bootstrap.c:451
#13 0x0000000000720c28 in StartChildProcess
(type=type@entry=CheckpointerProcess) at postmaster.c:5340
#14 0x0000000000721c23 in reaper (postgres_signal_arg=<optimized
out>) at postmaster.c:2875
#15 <signal handler called>
#16 0x00007fae03fa45b3 in __select_nocancel () at
../sysdeps/unix/syscall-template.S:84
#17 0x0000000000722968 in ServerLoop () at postmaster.c:1679
#18 0x0000000000723cde in PostmasterMain (argc=argc@entry=3,
argv=argv@entry=0x23a00e0) at postmaster.c:1388
#19 0x000000000068979f in main (argc=3, argv=0x23a00e0) at main.c:228
Looks like with the default
configuration and `max_wal_size=1GB` it writes more than reads to a
socket, and a buffer eventually becomes full.That's intended to then wake up the checkpointer immediately, so it can
absorb the requests. So something isn't right yet.Doesn't hang here, but it's way too slow.
Yep, in my case it was also getting slower, but eventually hang.
Reason for that is that I've wrongly resolved a merge conflict. Attached is a
fixup patch - does that address the issue for you?Hm...is it a correct patch? I see the same committed in
8c3debbbf61892dabd8b6f3f8d55e600a7901f2b, so I can't really apply it.Yea, sorry for that. Too many files in my patch directory... Right one
attached.
Yes, this patch solves the problem, thanks.
On 2018-05-22 21:58:06 +0200, Dmitry Dolgov wrote:
On 22 May 2018 at 20:59, Andres Freund <andres@anarazel.de> wrote:
On 2018-05-22 20:54:46 +0200, Dmitry Dolgov wrote:
Huh? Checkpointer was in SendFsyncRequest()? Coudl you share the
backtrace?Well, that's what I've got from gdb:
#3 0x000000000077ad08 in WaitLatchOrSocket
(latch=latch@entry=0x0, wakeEvents=wakeEvents@entry=4, sock=8,
timeout=timeout@entry=-1, wait_event_info=wait_event_info@entry=0) at
latch.c:385
#4 0x00000000007152cb in SendFsyncRequest
(request=request@entry=0x7ffe37529f40, fd=fd@entry=-1) at
checkpointer.c:1345
#5 0x0000000000716223 in AbsorbAllFsyncRequests () at checkpointer.c:1207
Oh, I see. That makes sense. So it's possible to self-deadlock
here. Should be easy to fix... Thanks for finding that one.
Yes, this patch solves the problem, thanks.
Just avoids it, I'm afraid... It probably can't be hit easily, but the
issue is there...
- Andres
On 21 May 2018 at 15:50, Craig Ringer <craig@2ndquadrant.com> wrote:
On 21 May 2018 at 12:57, Craig Ringer <craig@2ndquadrant.com> wrote:
On 18 May 2018 at 00:44, Andres Freund <andres@anarazel.de> wrote:
Hi,
On 2018-05-10 09:50:03 +0800, Craig Ringer wrote:
while ((src = (RewriteMappingFile *)
hash_seq_search(&seq_status)) != NULL)
{
if (FileSync(src->vfd, WAIT_EVENT_LOGICAL_REWRITE_SYNC)!= 0)
- ereport(ERROR, + ereport(PANIC, (errcode_for_file_access(), errmsg("could not fsync file\"%s\": %m", src->path)));
To me this (and the other callers) doesn't quite look right. First, I
think we should probably be a bit more restrictive about when PANIC
out. It seems like we should PANIC on ENOSPC and EIO, but possibly not
others. Secondly, I think we should centralize the error handling. It
seems likely that we'll acrue some platform specific workarounds, and I
don't want to copy that knowledge everywhere.Also, don't we need the same on close()?
Yes, we do, and that expands the scope a bit.
I agree with Robert that some sort of filter/macro is wise, though naming
it clearly will be tricky.I'll have a look.
On the queue for tomorrow.
Hi all.
I've revised the fsync patch with the cleanups discussed and gone through
the close() calls.
AFAICS either socket closes, temp file closes, or (for WAL) already PANIC
on close. It's mainly fd.c that needs amendment. Which I've done per the
attached revised patch.
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
Attachments:
v3-0001-PANIC-when-we-detect-a-possible-fsync-I-O-error-i.patchtext/x-patch; charset=US-ASCII; name=v3-0001-PANIC-when-we-detect-a-possible-fsync-I-O-error-i.patchDownload
From 952e6fbab1a735f677d8e6e92ba0aa8d53d9ab3e Mon Sep 17 00:00:00 2001
From: Craig Ringer <craig@2ndquadrant.com>
Date: Tue, 10 Apr 2018 14:08:32 +0800
Subject: [PATCH v3] PANIC when we detect a possible fsync I/O error instead of
retrying fsync
Panic the server on fsync failure in places where we can't simply repeat the
whole operation on retry. Most imporantly, panic when fsync fails during a
checkpoint.
This will result in log messages like:
PANIC: 58030: could not fsync file "base/12367/16386": Input/output error
LOG: 00000: checkpointer process (PID 10799) was terminated by signal 6: Aborted
and, if the condition persists during redo:
LOG: 00000: checkpoint starting: end-of-recovery immediate
PANIC: 58030: could not fsync file "base/12367/16386": Input/output error
LOG: 00000: startup process (PID 10808) was terminated by signal 6: Aborted
Why?
In a number of places PostgreSQL we responded to fsync() errors by retrying the
fsync(), expecting that this would force the operating system to repeat any
write attempts. The code assumed that fsync() would return an error on all
subsequent calls until any I/O error was resolved.
This is not what actually happens on some platforms, including Linux. The
operating system may give up and drop dirty buffers for async writes on the
floor and mark the page mapping as bad. The first fsync() clears any error flag
from the page entry and/or our file descriptor. So a subsequent fsync() returns
success, even though the data PostgreSQL wrote was really discarded.
We have no way to find out which writes failed, and no way to ask the kernel to
retry indefinitely, so all we can do is PANIC. Redo will attempt the write
again, and if it fails again, it will also PANIC.
This doesn't completely prevent fsync reliability issues, because it only
handles cases where the kernel actually reports the error to us. It's entirely
possible for a buffered write to be lost without causing fsync to report an
error at all (see discussion below). Work on addressing those issues and
documenting them is ongoing and will be committed separately.
Because NFS on Linux performs an implicit fsync() on close(), we also PANIC on
close() failures for non-temporary files managed by fd.c.
See:
* https://www.postgresql.org/message-id/CAMsr%2BYHh%2B5Oq4xziwwoEfhoTZgr07vdGG%2Bhu%3D1adXx59aTeaoQ%40mail.gmail.com
* https://www.postgresql.org/message-id/20180427222842.in2e4mibx45zdth5@alap3.anarazel.de
* https://lwn.net/Articles/752063/
* https://lwn.net/Articles/753650/
* https://lwn.net/Articles/752952/
* https://lwn.net/Articles/752613/
---
src/backend/access/heap/rewriteheap.c | 6 ++--
src/backend/access/transam/timeline.c | 4 +--
src/backend/access/transam/twophase.c | 2 +-
src/backend/access/transam/xlog.c | 9 +++++-
src/backend/replication/logical/snapbuild.c | 3 ++
src/backend/storage/file/fd.c | 50 +++++++++++++++++++++++++----
src/backend/storage/smgr/md.c | 22 +++++++++----
src/backend/utils/cache/relmapper.c | 2 +-
src/backend/utils/error/elog.c | 11 +++++++
src/include/utils/elog.h | 3 +-
10 files changed, 91 insertions(+), 21 deletions(-)
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index 8d3c861a33..a86a2f3824 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -965,7 +965,7 @@ logical_end_heap_rewrite(RewriteState state)
while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status)) != NULL)
{
if (FileSync(src->vfd, WAIT_EVENT_LOGICAL_REWRITE_SYNC) != 0)
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", src->path)));
FileClose(src->vfd);
@@ -1180,7 +1180,7 @@ heap_xlog_logical_rewrite(XLogReaderState *r)
*/
pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_MAPPING_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", path)));
pgstat_report_wait_end();
@@ -1279,7 +1279,7 @@ CheckPointLogicalRewriteHeap(void)
*/
pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_CHECKPOINT_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", path)));
pgstat_report_wait_end();
diff --git a/src/backend/access/transam/timeline.c b/src/backend/access/transam/timeline.c
index 61d36050c3..65e5ff6a82 100644
--- a/src/backend/access/transam/timeline.c
+++ b/src/backend/access/transam/timeline.c
@@ -406,7 +406,7 @@ writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI,
pgstat_report_wait_start(WAIT_EVENT_TIMELINE_HISTORY_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", tmppath)));
pgstat_report_wait_end();
@@ -485,7 +485,7 @@ writeTimeLineHistoryFile(TimeLineID tli, char *content, int size)
pgstat_report_wait_start(WAIT_EVENT_TIMELINE_HISTORY_FILE_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", tmppath)));
pgstat_report_wait_end();
diff --git a/src/backend/access/transam/twophase.c b/src/backend/access/transam/twophase.c
index 65194db70e..350238e2fb 100644
--- a/src/backend/access/transam/twophase.c
+++ b/src/backend/access/transam/twophase.c
@@ -1687,7 +1687,7 @@ RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
if (pg_fsync(fd) != 0)
{
CloseTransientFile(fd);
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync two-phase state file: %m")));
}
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index adbd6a2126..c6c6b64826 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -3268,7 +3268,14 @@ XLogFileInit(XLogSegNo logsegno, bool *use_existent, bool use_lock)
pgstat_report_wait_start(WAIT_EVENT_WAL_INIT_SYNC);
if (pg_fsync(fd) != 0)
{
+ int save_errno = errno;
+ unlink(tmppath);
close(fd);
+ errno = save_errno;
+ /*
+ * This fsync failure is not PANIC-worthy because it's still a temp
+ * file at this time.
+ */
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", tmppath)));
@@ -3435,7 +3442,7 @@ XLogFileCopy(XLogSegNo destsegno, TimeLineID srcTLI, XLogSegNo srcsegno,
pgstat_report_wait_start(WAIT_EVENT_WAL_COPY_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", tmppath)));
pgstat_report_wait_end();
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 4123cdebcf..31ab7c1de9 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -1616,6 +1616,9 @@ SnapBuildSerialize(SnapBuild *builder, XLogRecPtr lsn)
* fsync the file before renaming so that even if we crash after this we
* have either a fully valid file or nothing.
*
+ * It's safe to just ERROR on fsync() here because we'll retry the whole
+ * operation including the writes.
+ *
* TODO: Do the fsync() via checkpoints/restartpoints, doing it here has
* some noticeable overhead since it's performed synchronously during
* decoding?
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 441f18dcf5..9a29eaef7b 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -353,6 +353,17 @@ pg_fsync(int fd)
/*
* pg_fsync_no_writethrough --- same as fsync except does nothing if
* enableFsync is off
+ *
+ * WARNING: It is unsafe to retry fsync() calls without repeating the preceding
+ * writes. fsync() clears the error flag on some platforms (including Linux,
+ * true up to at least 4.14) when it reports the error to the caller. A second
+ * call may return success even though writes are lost. Many callers test the
+ * return value and PANIC on failure so that redo repeats the writes. It is
+ * safe to ERROR instead if the whole operation can be retried without needing
+ * WAL redo.
+ *
+ * See https://lwn.net/Articles/752063/
+ * and https://www.postgresql.org/message-id/CAMsr%2BYHh%2B5Oq4xziwwoEfhoTZgr07vdGG%2Bhu%3D1adXx59aTeaoQ%40mail.gmail.com
*/
int
pg_fsync_no_writethrough(int fd)
@@ -443,7 +454,12 @@ pg_flush_data(int fd, off_t offset, off_t nbytes)
rc = sync_file_range(fd, offset, nbytes,
SYNC_FILE_RANGE_WRITE);
- /* don't error out, this is just a performance optimization */
+ /*
+ * Don't error out, this is just a performance optimization.
+ *
+ * sync_file_range(SYNC_FILE_RANGE_WRITE) won't clear any error flags,
+ * so we don't have to worry about this impacting fsync reliability.
+ */
if (rc != 0)
{
ereport(WARNING,
@@ -518,7 +534,12 @@ pg_flush_data(int fd, off_t offset, off_t nbytes)
rc = msync(p, (size_t) nbytes, MS_ASYNC);
if (rc != 0)
{
- ereport(WARNING,
+ /*
+ * We must panic here to preserve fsync reliability,
+ * as msync may clear the fsync error state on some
+ * OSes. See pg_fsync_no_writethrough().
+ */
+ ereport(PANIC,
(errcode_for_file_access(),
errmsg("could not flush dirty data: %m")));
/* NB: need to fall through to munmap()! */
@@ -1046,11 +1067,17 @@ LruDelete(File file)
}
/*
- * Close the file. We aren't expecting this to fail; if it does, better
- * to leak the FD than to mess up our internal state.
+ * Close the file. We aren't expecting this to fail; if it does, we need
+ * to PANIC on I/O errors for non-temporary files in case it's an an
+ * important file. That's because NFS on Linux may do an implicit fsync()
+ * on close() which can cause similar issues to those discussed in the
+ * comments on pg_fsync.
+ *
+ * Otherwise, better to leak the FD than to mess up our internal state.
*/
if (close(vfdP->fd))
- elog(LOG, "could not close file \"%s\": %m", vfdP->fileName);
+ elog(vfdP->fdstate & FD_DELETE_AT_CLOSE ? LOG : promote_ioerr_to_panic(LOG),
+ "could not close file \"%s\": %m", vfdP->fileName);
vfdP->fd = VFD_CLOSED;
--nfile;
@@ -1754,7 +1781,14 @@ FileClose(File file)
{
/* close the file */
if (close(vfdP->fd))
- elog(LOG, "could not close file \"%s\": %m", vfdP->fileName);
+ {
+ /*
+ * We must panic on failure to close non-temporary files; see
+ * LruDelete.
+ */
+ elog(vfdP->fdstate & FD_DELETE_AT_CLOSE ? LOG : promote_ioerr_to_panic(LOG),
+ "could not close file \"%s\": %m", vfdP->fileName);
+ }
--nfile;
vfdP->fd = VFD_CLOSED;
@@ -3250,6 +3284,10 @@ looks_like_temp_rel_name(const char *name)
* harmless cases such as read-only files in the data directory, and that's
* not good either.
*
+ * Importantly, on Linux (true in 4.14) and some other platforms, fsync errors
+ * will consume the error, causing a subsequent fsync to succeed even though
+ * the writes did not succeed. See pg_fsync_no_writethrough().
+ *
* Note we assume we're chdir'd into PGDATA to begin with.
*/
void
diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index 2ec103e604..c604ec4e28 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -1038,7 +1038,7 @@ mdimmedsync(SMgrRelation reln, ForkNumber forknum)
MdfdVec *v = &reln->md_seg_fds[forknum][segno - 1];
if (FileSync(v->mdfd_vfd, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC) < 0)
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m",
FilePathName(v->mdfd_vfd))));
@@ -1265,13 +1265,22 @@ mdsync(void)
* _mdfd_getseg() and for FileSync, since fd.c might have
* closed the file behind our back.
*
- * XXX is there any point in allowing more than one retry?
- * Don't see one at the moment, but easy to change the
- * test here if so.
+ * It's unsafe to ignore failures for other errors,
+ * particularly EIO or (undocumented, but possible) ENOSPC.
+ * The first fsync() will clear any error flag on dirty
+ * buffers pending writeback and/or the file descriptor, so
+ * a second fsync report success despite the buffers
+ * possibly not being written. (Verified on Linux 4.14).
+ * To cope with this we must PANIC and redo all writes
+ * since the last successful checkpoint. See discussion at:
+ *
+ * https://www.postgresql.org/message-id/CAMsr%2BYHh%2B5Oq4xziwwoEfhoTZgr07vdGG%2Bhu%3D1adXx59aTeaoQ%40mail.gmail.com
+ *
+ * for details.
*/
if (!FILE_POSSIBLY_DELETED(errno) ||
failures > 0)
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m",
path)));
@@ -1280,6 +1289,7 @@ mdsync(void)
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\" but retrying: %m",
path)));
+
pfree(path);
/*
@@ -1444,7 +1454,7 @@ register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
(errmsg("could not forward fsync request because request queue is full")));
if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m",
FilePathName(seg->mdfd_vfd))));
diff --git a/src/backend/utils/cache/relmapper.c b/src/backend/utils/cache/relmapper.c
index 99d095f2df..662812b799 100644
--- a/src/backend/utils/cache/relmapper.c
+++ b/src/backend/utils/cache/relmapper.c
@@ -795,7 +795,7 @@ write_relmap_file(bool shared, RelMapFile *newmap,
*/
pgstat_report_wait_start(WAIT_EVENT_RELATION_MAP_SYNC);
if (pg_fsync(fd) != 0)
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync relation mapping file \"%s\": %m",
mapfilename)));
diff --git a/src/backend/utils/error/elog.c b/src/backend/utils/error/elog.c
index 16531f7a0f..e202094642 100644
--- a/src/backend/utils/error/elog.c
+++ b/src/backend/utils/error/elog.c
@@ -692,6 +692,17 @@ errcode_for_socket_access(void)
return 0; /* return value does not matter */
}
+/*
+ * PostgreSQL needs to PANIC on EIO in some cases to preserve data integrity.
+ * See explanation on pg_fsync for details. This keeps that logic in one place.
+ */
+int
+promote_ioerr_to_panic(int elevel)
+{
+ ErrorData *edata = &errordata[errordata_stack_depth];
+ return (edata->saved_errno == EIO || edata->saved_errno == ENOSPC) ? elevel : PANIC;
+}
+
/*
* This macro handles expansion of a format string and associated parameters;
diff --git a/src/include/utils/elog.h b/src/include/utils/elog.h
index 7a9ba7f2ff..abd078075c 100644
--- a/src/include/utils/elog.h
+++ b/src/include/utils/elog.h
@@ -133,6 +133,8 @@ extern int errcode(int sqlerrcode);
extern int errcode_for_file_access(void);
extern int errcode_for_socket_access(void);
+extern int promote_ioerr_to_panic(int elevel);
+
extern int errmsg(const char *fmt,...) pg_attribute_printf(1, 2);
extern int errmsg_internal(const char *fmt,...) pg_attribute_printf(1, 2);
@@ -182,7 +184,6 @@ extern int geterrcode(void);
extern int geterrposition(void);
extern int getinternalerrposition(void);
-
/*----------
* Old-style error reporting API: to be used in this way:
* elog(ERROR, "portal \"%s\" not found", stmt->portalname);
--
2.14.3
On Wed, May 23, 2018 at 8:02 AM, Andres Freund <andres@anarazel.de> wrote:
[patches]
Hi Andres,
Obviously there is more work to be done here but the basic idea in
your clone-fd-checkpointer branch as of today seems OK to me. I think
Craig and I both had similar ideas (sending file descriptors that have
an old enough f_wb_err) but we thought rlimit management was going to
be hard (shared memory counters + deduplication, bleugh). You made it
look easy. Nice work.
First, let me describe in my own words what's going on, mostly to make
sure I really understand this:
1. We adopt a new fd lifecycle that is carefully tailored to avoid
error loss on Linux, and can't hurt on other OSes. By sending the
file descriptor used for every write to the checkpointer, we guarantee
that (1) the inode stays pinned (the file is "in flight" in the
socket, even if the sender closes it before the checkpointer receives
it) so Linux won't be tempted to throw away the precious information
in i_mapping->wb_err, and (2) the checkpointer finishes up with a file
descriptor that points to the very same "struct file" with the
f_wb_err value that was originally sampled before the write, by the
sender. So we can't miss any write-back errors. Wahey! However,
errors are still reported only once, so we probably need to panic.
Hmm... Is there any way that the *sender* could finish up in
file_check_and_advance_wb_err() for the same struct file, before the
checkpointer manages to call fsync() on its dup'd fd? I don't
immediately see how (it looks like you have to call one of the various
sync functions to reach that, and your patch removes the fallback
just-call-FileSync()-myself code from register_dirty_segment()). I
guess it would be bad if, say, close() were to do that in some future
Linux release because then we'd have no race-free way to tell the
checkpointer that the file is borked before it runs fsync() and
potentially gets an OK response and reports a successful checkpoint
(even if we panicked, with sufficiently bad timing it might manage to
report a successful checkpoint).
2. In order to make sure that we don't exceed our soft limit on the
number of file descriptors per process, you use a simple backend-local
counter in the checkpointer, on the theory that we don't care about
fds (or, technically, the files they point to) waiting in the socket
buffer, we care only about how many the checkpointer has actually
received but not yet closed. As long as we make sure there is space
for at least one more before we read one message, everything should be
fine. Good and simple.
One reason I thought this would be harder is because I had no model of
how RLIMIT_NOFILE would apply when you start flinging fds around
between processes (considering there can be moments when neither end
has the file open), so I feared the worst and thought we would need to
maintain a counter in shared memory and have senders and receiver
cooperate to respect it. My intuition that this was murky and
required pessimism wasn't too far from the truth actually: apparently
the kernel didn't do a great job at accounting for that until a
patch[1]https://github.com/torvalds/linux/commit/712f4aad406bb1ed67f3f98d04c044191f0ff593 landed for CVE-2013-4312.
The behaviour in older releases is super lax, so no problem there.
The behaviour from 4.9 onward (or is it 4.4.1?) is that you get a
separate per-user RLIMIT_NOFILE allowance for in-flight fds. So
effectively the sender doesn't have to worry about about fds it has
sent but closed and the receiver doesn't have to care about fds it
hasn't received yet, so your counting scheme seems OK. As for
exceeding RLIMIT_NOFILE with in-flight fds, it's at least bounded by
the fact that the socket would block/EWOULDBLOCK if the receiver isn't
draining it fast enough and can only hold a small and finite amount of
data and thus file descriptors, so we can probably just ignore that.
If you did manage to exceed it, I think you'd find out about that with
ETOOMANYREFS at send time (curiously absent from the sendmsg() man
page, but there in black and white in the source for
unix_attach_fds()), and then you'd just raise an error (currently
FATAL in your patch). I have no idea how the rlimit for SCM-ified
files works on other Unixoid systems though.
Some actual code feedback:
+ if (entry->syncfds[forknum][segno] == -1)
+ {
+ char *path = mdpath(entry->rnode,
forknum, segno);
+ open_fsync_queue_files++;
+ /* caller must have reserved entry */
+ entry->syncfds[forknum][segno] =
+ FileOpenForFd(fd, path);
+ pfree(path);
+ }
+ else
+ {
+ /*
+ * File is already open. Have to keep
the older fd, errors
+ * might only be reported to it, thus
close the one we just
+ * got.
+ *
+ * XXX: check for errrors.
+ */
+ close(fd);
+ }
Wait... it's not guaranteed to be older in open() time, is it? It's
just older in sendmsg() time. Those might be different:
A: open("base/42/1234")
A: write()
kernel: inode->i_mapping->wb_err++
B: open("base/42/1234")
B: write()
B: sendmsg()
A: sendmsg()
C: recvmsg() /* clone B's fd */
C: recvmsg() /* clone A's fd, throw it away because we already have B's */
C: fsync()
I think that would eat an error under the 4.13 code. I think it might
be OK under the new 4.17 code, because the new "must report it to at
least one caller" thing would save the day. So now I'm wondering if
that's getting backported to the 4.14 long term kernel.
Aha, yes it has been already[2]https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git/commit/lib/errseq.c?h=linux-4.14.y&id=0799a0ea96e4923f52f85fe315b62e9176a3319c.
So... if you don't have to worry about kernels without that patch, I
suspect the exact ordering doesn't matter anymore, as long as
*someone* held the file open at all times beween write and fsync() to
keep the inode around, which this patch achieves. (And of course no
other process sets the ERRSEQ_SEEN flag, for example some other kind
of backend or random other program that opened our data file and
called one of the sync syscalls, or any future syscalls that start
calling file_check_and_advance_wb_err()).
+ /*
+ * FIXME: do DuplicateHandle dance for windows - can that work
+ * trivially?
+ */
I don't know, I guess something like CreatePipe() and then
write_duplicate_handle()? And some magic (maybe our own LWLock) to
allow atomic messages?
A more interesting question is: how will you cap the number file
handles you send through that pipe? On that OS you call
DuplicateHandle() to fling handles into another process's handle table
directly. Then you send the handle number as plain old data to the
other process via carrier pigeon, smoke signals, a pipe etc. That's
interesting because the handle allocation is asynchronous from the
point of view of the receiver. Unlike the Unix case where the
receiver can count handles and make sure there is space for one more
before it reads a potentially-SCM-containing message, here the
*senders* will somehow need to make sure they don't create too many in
the receiving process. I guess that would involve a shared counter,
and a strategy for what to do when the number is too high (probably
just wait).
Hmm. I wonder if that would be a safer approach on all operating systems.
+ if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, fsync_fds) < 0)
...
+ size = sendmsg(sock, &msg, 0);
Here you are relying on atomic sending and receiving of whole messages
over a stream socket. For example, in Linux's unix_stream_sendmsg()
it's going to be chopped into buffers of size (sk->sk_sndbuf >> 1) -
64 (I have no clue how big that is) that are appended one at a time to
the receiving socket's queue, with no locking in between, so a
concurrently send messages can be interleaved with yours. How big is
big enough for that to happen? There doesn't seem to be an equivalent
of PIPE_BUF for Unix domain sockets. These tiny messages are almost
certainly safe, but I wonder if we should be using SOCK_SEQPACKET
instead of SOCK_STREAM?
Might be a less theoretical problem if we switch to variable sized
messages containing file paths as you once contemplated in an off-list
chat.
Presumably for EXEC_BACKEND we'll need to open
PGDATA/something/something/socket or similar.
+ if (returnCode < 0)
+ {
+ /* XXX: decide on policy */
+
bms_add_member(entry->requests[forknum], segno);
Obviously this is pseudocode (doesn't even keep the return value), but
just BTW, I think that if we decide not to PANIC unconditionally on
any kind of fsync() failure, we definitely can't use bms_add_member()
here (it might fail to allocate, and then we forget the segment, raise
and error and won't try again). It's got to be PANIC or no-fail code
(like the patch I proposed in another thread).
+SendFsyncRequest(CheckpointerRequest *request, int fd)
...
+ * Don't think short reads will ever happen in realistic
...
+ ereport(FATAL, (errmsg("could not receive
fsync request: %m")));
Short *writes*, could not *send*.
+ * back, as that'd lead to loosing error reporting guarantees on
s/loosing/losing/
[1]: https://github.com/torvalds/linux/commit/712f4aad406bb1ed67f3f98d04c044191f0ff593
[2]: https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git/commit/lib/errseq.c?h=linux-4.14.y&id=0799a0ea96e4923f52f85fe315b62e9176a3319c
--
Thomas Munro
http://www.enterprisedb.com
On Tue, May 29, 2018 at 4:53 AM, Craig Ringer <craig@2ndquadrant.com> wrote:
I've revised the fsync patch with the cleanups discussed and gone through
the close() calls.AFAICS either socket closes, temp file closes, or (for WAL) already PANIC on
close. It's mainly fd.c that needs amendment. Which I've done per the
attached revised patch.
I think we should have a separate thread for this patch vs. Andres's
patch to do magic things with the checkpointer and file-descriptor
forwarding. Meanwhile, here's some review.
1. No longer applies cleanly.
2. I don't like promote_ioerr_to_panic() very much, partly because the
same pattern gets repeated over and over, and partly because it would
be awkwardly-named if we discovered that another 2 or 3 errors needed
similar handling (or some other variant handling). I suggest instead
having a function like report_critical_fsync_failure(char *path) that
does something like this:
int elevel = ERROR;
if (errno == EIO)
elevel = PANIC;
ereport(elevel,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m", path);
And similarly I'd add report_critical_close_failure. In some cases,
this would remove wording variations (e.g. in twophase.c) but I think
that's fine, and maybe an improvement, as discussed on another recent
thread.
3. slru.c calls pg_fsync() but isn't changed by the patch. That looks wrong.
4. The comment changes in snapbuild.c interact with the TODO that
immediately follows. I think more adjustment is needed here.
5. It seems odd that you adjusted the comment for
pg_fsync_no_writethrough() but not pg_fsync_writethrough() or
pg_fsync(). Either pg_fsync_writethrough() doesn't have the same
problem, in which case, awesome, but let's add a comment, or it does,
in which case it should refer to the other one. And I think
pg_fsync() itself needs a comment saying that every caller must be
careful to use promote_ioerr_to_panic() or
report_critical_fsync_failure() or whatever we end up calling it
unless the fsync is not critical for data integrity.
6. In md.c, there's a stray blank line added. But more importantly,
the code just above that looks like this:
if (!FILE_POSSIBLY_DELETED(errno) ||
failures > 0)
- ereport(ERROR,
+ ereport(promote_ioerr_to_panic(ERROR),
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\": %m",
path)));
else
ereport(DEBUG1,
(errcode_for_file_access(),
errmsg("could not fsync file \"%s\"
but retrying: %m",
path)));
I might be all wet here, but it seems like if we enter the bottom
branch, we still need the promote-to-panic behavior.
7. The comment adjustment for SyncDataDirectory mentions an
"important" fact about fsync behavior, but then doesn't seem to change
any logic on that basis. I think in general a number of these
comments need a little more thought, but in this particular case, I
think we also need to consider what the behavior should be (and the
comment should reflect our considered judgement on that point, and the
implementation should match).
8. Andres suggested to me off-list that we should have a GUC to
disable the promote-to-panic behavior in case it turns out to be a
show-stopper for some user. I think that's probably a good idea.
Adding many new ways to PANIC in a minor release without providing any
way to go back to the old behavior sounds unfriendly. Surely, anyone
who suffers much from this has really serious other problems anyway,
but all the same I think we should provide an escape hatch.
--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company
On Thu, Jul 19, 2018 at 7:23 AM, Robert Haas <robertmhaas@gmail.com> wrote:
2. I don't like promote_ioerr_to_panic() very much, partly because the
same pattern gets repeated over and over, and partly because it would
be awkwardly-named if we discovered that another 2 or 3 errors needed
similar handling (or some other variant handling). I suggest instead
having a function like report_critical_fsync_failure(char *path) that
...
Note that if we don't cover *all* errno values, or ...
8. Andres suggested to me off-list that we should have a GUC to
disable the promote-to-panic behavior in case it turns out to be a
show-stopper for some user.
... we let the user turn this off, then we also have to fix this:
/messages/by-id/87y3i1ia4w.fsf@news-spur.riddles.org.uk
--
Thomas Munro
http://www.enterprisedb.com
On Thu, Jun 14, 2018 at 5:30 PM, Thomas Munro
<thomas.munro@enterprisedb.com> wrote:
On Wed, May 23, 2018 at 8:02 AM, Andres Freund <andres@anarazel.de> wrote:
[patches]
A more interesting question is: how will you cap the number file
handles you send through that pipe? On that OS you call
DuplicateHandle() to fling handles into another process's handle table
directly. Then you send the handle number as plain old data to the
other process via carrier pigeon, smoke signals, a pipe etc. That's
interesting because the handle allocation is asynchronous from the
point of view of the receiver. Unlike the Unix case where the
receiver can count handles and make sure there is space for one more
before it reads a potentially-SCM-containing message, here the
*senders* will somehow need to make sure they don't create too many in
the receiving process. I guess that would involve a shared counter,
and a strategy for what to do when the number is too high (probably
just wait).Hmm. I wonder if that would be a safer approach on all operating systems.
As a way of poking this thread, here are some more thoughts. Buffer
stealing currently look something like this:
Evicting backend:
lseek(fd)
write(fd)
...enqueue-fsync-request via shm...
Checkpointer:
...push into hash table...
With the patch it presumably looks something like this:
Evicting backend:
lseek(fd)
write(fd)
sendmsg(fsync_socket) /* passes fd */
Checkpointer:
recvmsg(fsync_socket) /* gets a copy of fd */
...push into hash table...
close(fd) /* for all but the first one received for the same file */
That takes us from 2 syscalls to 5 per evicted buffer. I suppose it's
possible that on some operating systems that might hurt a bit, given
that it's happening at the granularity of 1GB data files that could
have a lot of backends working in them concurrently. I have no idea
if it's really a problem on any particular OS. Admittedly on Linux
it's probably just a bunch of fast atomic ops and RCU stuff...
probably only the existing write() actually takes the inode lock or
anything that heavy, and that's probably lost in the noise in an
evict-heavy workload. I don't know, I guess it's probably not a
problem, but I thought I'd mention that.
Contention on the new fsync socket doesn't seem to be a new problem
per se since it replaces a contention point we already had:
CheckpointerCommLock. If that was acceptable today then perhaps that
indicates that any in-kernel contention created by the new syscalls is
also OK.
My feeling so far is that I'd probably go for sender-collapses model
(and it might even be necessary on Windows?) if doing this as a new
feature, but I fully understand your desire to do it in a much simpler
way that could be back-patched more easily. I'm just slightly
concerned about the unintended consequence risk that comes with
exercising an operating system feature that not all operating system
authors probably intended to be used at high frequency. Nothing that
can't be assuaged by testing.
* the queue is full and contains no duplicate entries. In that case, we
* let the backend know by returning false.
*/
-bool
-ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
+void
+ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno,
+ File file)
Comment out of date.
--
Thomas Munro
http://www.enterprisedb.com
On Sun, Jul 29, 2018 at 6:14 PM, Thomas Munro
<thomas.munro@enterprisedb.com> wrote:
As a way of poking this thread, here are some more thoughts.
I am keen to move this forward, not only because it is something we
need to get fixed, but also because I have some other pending patches
in this area and I want this sorted out first.
Here are some small fix-up patches for Andres's patchset:
1. Use FD_CLOEXEC instead of the non-portable Linuxism SOCK_CLOEXEC.
2. Fix the self-deadlock hazard reported by Dmitry Dolgov. Instead
of the checkpoint trying to send itself a CKPT_REQUEST_SYN message
through the socket (whose buffer may be full), I included the
ckpt_started counter in all messages. When AbsorbAllFsyncRequests()
drains the socket, it stops at messages with the current ckpt_started
value.
3. Handle postmaster death while waiting.
4. I discovered that macOS would occasionally return EMSGSIZE for
sendmsg(), but treating that just like EAGAIN seems to work the next
time around. I couldn't make that happen on FreeBSD (I mention that
because the implementation is somehow related). So handle that weird
case on macOS only for now.
Testing on other Unixoid systems would be useful. The case that
produced occasional EMSGSIZE on macOS was: shared_buffers=1MB,
max_files_per_process=32, installcheck-parallel. Based on man pages
that seems to imply an error in the client code but I don't see it.
(I also tried to use SOCK_SEQPACKET instead of SOCK_STREAM, but it's
not supported on macOS. I also tried to use SOCK_DGRAM, but that
produced occasional ENOBUFS errors and retrying didn't immediately
succeed leading to busy syscall churn. This is all rather
unsatisfying, since SOCK_STREAM is not guaranteed by any standard to
be atomic, and we're writing messages from many backends into the
socket so we're assuming atomicity. I don't have a better idea that
is portable.)
There are a couple of FIXMEs remaining, and I am aware of three more problems:
* Andres mentioned to me off-list that there may be a deadlock risk
where the checkpointer gets stuck waiting for an IO lock. I'm going
to look into that.
* Windows. Patch soon.
* The ordering problem that I mentioned earlier: the patchset wants to
keep the *oldest* fd, but it's really the oldest it has received. An
idea Andres and I discussed is to use a shared atomic counter to
assign a number to all file descriptors just before their first write,
and send that along with it to the checkpointer. Patch soon.
--
Thomas Munro
http://www.enterprisedb.com
Attachments:
0001-Use-portable-close-on-exec-syscalls.patchapplication/octet-stream; name=0001-Use-portable-close-on-exec-syscalls.patchDownload
From 6f278a123caa395f0f487a2b04d7992e573a5fc6 Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@enterprisedb.com>
Date: Thu, 9 Aug 2018 15:38:17 +0530
Subject: [PATCH 1/4] Use portable close-on-exec syscalls.
---
src/backend/postmaster/postmaster.c | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index 135aa29bfeb..42134d4ed28 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -6458,7 +6458,7 @@ static void
InitFsyncFdSocketPair(void)
{
Assert(MyProcPid == PostmasterPid);
- if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, fsync_fds) < 0)
+ if (socketpair(AF_UNIX, SOCK_STREAM, 0, fsync_fds) < 0)
ereport(FATAL,
(errcode_for_file_access(),
errmsg_internal("could not create fsync sockets: %m")));
@@ -6470,11 +6470,19 @@ InitFsyncFdSocketPair(void)
ereport(FATAL,
(errcode_for_socket_access(),
errmsg_internal("could not set fsync process socket to nonblocking mode: %m")));
+ if (fcntl(fsync_fds[FSYNC_FD_PROCESS], F_SETFD, FD_CLOEXEC) == -1)
+ ereport(FATAL,
+ (errcode_for_socket_access(),
+ errmsg_internal("could not set fsync process socket to close-on-exec mode: %m")));
if (fcntl(fsync_fds[FSYNC_FD_SUBMIT], F_SETFL, O_NONBLOCK) == -1)
ereport(FATAL,
(errcode_for_socket_access(),
errmsg_internal("could not set fsync submit socket to nonblocking mode: %m")));
+ if (fcntl(fsync_fds[FSYNC_FD_SUBMIT], F_SETFD, FD_CLOEXEC) == -1)
+ ereport(FATAL,
+ (errcode_for_socket_access(),
+ errmsg_internal("could not set fsync submit socket to close-on-exec mode: %m")));
/*
* FIXME: do DuplicateHandle dance for windows - can that work
--
2.17.0
0002-Fix-deadlock-in-AbsorbAllFsyncRequests.patchapplication/octet-stream; name=0002-Fix-deadlock-in-AbsorbAllFsyncRequests.patchDownload
From 806bee1efdde958bb3d819626e0cfaf624cf2055 Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@enterprisedb.com>
Date: Thu, 9 Aug 2018 16:57:57 +0530
Subject: [PATCH 2/4] Fix deadlock in AbsorbAllFsyncRequests().
---
src/backend/postmaster/checkpointer.c | 54 +++++++++++++--------------
1 file changed, 25 insertions(+), 29 deletions(-)
diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c
index 9ef56db97bc..6250cb21946 100644
--- a/src/backend/postmaster/checkpointer.c
+++ b/src/backend/postmaster/checkpointer.c
@@ -112,6 +112,7 @@ typedef struct
ForkNumber forknum;
BlockNumber segno; /* see md.c for special values */
bool contains_fd;
+ int ckpt_started;
/* might add a real request-type field later; not needed yet */
} CheckpointerRequest;
@@ -169,9 +170,6 @@ static double ckpt_cached_elapsed;
static pg_time_t last_checkpoint_time;
static pg_time_t last_xlog_switch_time;
-static BlockNumber next_syn_rqst;
-static BlockNumber received_syn_rqst;
-
/* Prototypes for private functions */
static void CheckArchiveTimeout(void);
@@ -179,7 +177,7 @@ static bool IsCheckpointOnSchedule(double progress);
static bool ImmediateCheckpointRequested(void);
static void UpdateSharedMemoryConfig(void);
static void SendFsyncRequest(CheckpointerRequest *request, int fd);
-static bool AbsorbFsyncRequest(void);
+static bool AbsorbFsyncRequest(bool stop_at_current_cycle);
/* Signal handlers */
@@ -1105,6 +1103,11 @@ RequestCheckpoint(int flags)
* is theoretically possible a backend fsync might still be necessary, if
* the queue is full and contains no duplicate entries. In that case, we
* let the backend know by returning false.
+ *
+ * We add the cycle counter to the message. That is an unsynchronized read
+ * of the shared memory counter, but it doesn't matter if it is arbitrarily
+ * old since it is only used to limit unnecessary extra queue draining in
+ * AbsorbAllFsyncRequests().
*/
void
ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno,
@@ -1124,6 +1127,15 @@ ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno,
request.segno = segno;
request.contains_fd = file != -1;
+ /*
+ * We read ckpt_started without synchronization. It is used to prevent
+ * AbsorbAllFsyncRequests() from reading new values from after a
+ * checkpoint began. A slightly out-of-date value here will only cause
+ * it to do a little bit more work than strictly necessary, but that's
+ * OK.
+ */
+ request.ckpt_started = CheckpointerShmem->ckpt_started;
+
SendFsyncRequest(&request, request.contains_fd ? FileGetRawDesc(file) : -1);
}
@@ -1152,7 +1164,7 @@ AbsorbFsyncRequests(void)
if (!FlushFsyncRequestQueueIfNecessary())
break;
- if (!AbsorbFsyncRequest())
+ if (!AbsorbFsyncRequest(false))
break;
}
}
@@ -1170,8 +1182,6 @@ AbsorbFsyncRequests(void)
void
AbsorbAllFsyncRequests(void)
{
- CheckpointerRequest request = {0};
-
if (!AmCheckpointerProcess())
return;
@@ -1181,22 +1191,12 @@ AbsorbAllFsyncRequests(void)
BgWriterStats.m_buf_fsync_backend +=
pg_atomic_exchange_u32(&CheckpointerShmem->num_backend_fsync, 0);
- /*
- * For mdsync()'s guarantees to work, all pending fsync requests need to
- * be executed. But we don't want to absorb requests till the queue is
- * empty, as that could take a long while. So instead we enqueue
- */
- request.type = CKPT_REQUEST_SYN;
- request.segno = ++next_syn_rqst;
- SendFsyncRequest(&request, -1);
-
- received_syn_rqst = next_syn_rqst + 1;
- while (received_syn_rqst != request.segno)
+ for (;;)
{
if (!FlushFsyncRequestQueueIfNecessary())
elog(FATAL, "may not happen");
- if (!AbsorbFsyncRequest())
+ if (!AbsorbFsyncRequest(true))
break;
}
}
@@ -1206,7 +1206,7 @@ AbsorbAllFsyncRequests(void)
* Retrieve one queued fsync request and pass them to local smgr.
*/
static bool
-AbsorbFsyncRequest(void)
+AbsorbFsyncRequest(bool stop_at_current_cycle)
{
CheckpointerRequest req;
int fd;
@@ -1229,17 +1229,13 @@ AbsorbFsyncRequest(void)
elog(FATAL, "message should have fd associated, but doesn't");
}
- if (req.type == CKPT_REQUEST_SYN)
- {
- received_syn_rqst = req.segno;
- Assert(fd == -1);
- }
- else
- {
- RememberFsyncRequest(req.rnode, req.forknum, req.segno, fd);
- }
+ RememberFsyncRequest(req.rnode, req.forknum, req.segno, fd);
END_CRIT_SECTION();
+ if (stop_at_current_cycle &&
+ req.ckpt_started == CheckpointerShmem->ckpt_started)
+ return false;
+
return true;
}
--
2.17.0
0003-Handle-postmaster-death-CFI-improve-error-messages-a.patchapplication/octet-stream; name=0003-Handle-postmaster-death-CFI-improve-error-messages-a.patchDownload
From 005bd50afb94e9876962edbb8d8d32a2843f9feb Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@enterprisedb.com>
Date: Fri, 10 Aug 2018 10:49:57 +0530
Subject: [PATCH 3/4] Handle postmaster death, CFI, improve error messages and
comments.
---
src/backend/postmaster/checkpointer.c | 14 +++++++++-----
1 file changed, 9 insertions(+), 5 deletions(-)
diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c
index 6250cb21946..16a57090fe7 100644
--- a/src/backend/postmaster/checkpointer.c
+++ b/src/backend/postmaster/checkpointer.c
@@ -1302,9 +1302,12 @@ static void
SendFsyncRequest(CheckpointerRequest *request, int fd)
{
ssize_t ret;
+ int rc;
while (true)
{
+ CHECK_FOR_INTERRUPTS();
+
ret = pg_uds_send_with_fd(fsync_fds[FSYNC_FD_SUBMIT], request, sizeof(*request),
request->contains_fd ? fd : -1);
@@ -1315,18 +1318,19 @@ SendFsyncRequest(CheckpointerRequest *request, int fd)
* implementations, but better make sure that's true...
*/
if (ret != sizeof(*request))
- elog(FATAL, "oops, gotta do better");
+ elog(FATAL, "unexpected short write to fsync request socket");
break;
}
else if (errno == EWOULDBLOCK || errno == EAGAIN)
{
/* blocked on write - wait for socket to become readable */
- /* FIXME: postmaster death? Other interrupts? */
- WaitLatchOrSocket(NULL, WL_SOCKET_WRITEABLE, fsync_fds[FSYNC_FD_SUBMIT], -1, 0);
+ rc = WaitLatchOrSocket(NULL,
+ WL_SOCKET_WRITEABLE | WL_POSTMASTER_DEATH,
+ fsync_fds[FSYNC_FD_SUBMIT], -1, 0);
+ if (rc & WL_POSTMASTER_DEATH)
+ exit(1);
}
else
- {
ereport(FATAL, (errmsg("could not receive fsync request: %m")));
- }
}
}
--
2.17.0
0004-Handle-EMSGSIZE-on-macOS.-Fix-misleading-error-messa.patchapplication/octet-stream; name=0004-Handle-EMSGSIZE-on-macOS.-Fix-misleading-error-messa.patchDownload
From 5cc52ace3e31f9492fe6f2e4441f386c2b21837e Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@enterprisedb.com>
Date: Fri, 10 Aug 2018 12:54:05 +0530
Subject: [PATCH 4/4] Handle EMSGSIZE on macOS. Fix misleading error message.
Also zero-initialize a couple of structs passed to the kernel just in case
there is padding on some system somewhere that could be a problem (based on
a rumor about EMSGSIZE errors which didn't turn out to help).
---
src/backend/postmaster/checkpointer.c | 15 +++++++++++++--
src/backend/storage/file/fd.c | 3 ++-
2 files changed, 15 insertions(+), 3 deletions(-)
diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c
index 16a57090fe7..714f1522f15 100644
--- a/src/backend/postmaster/checkpointer.c
+++ b/src/backend/postmaster/checkpointer.c
@@ -1321,8 +1321,19 @@ SendFsyncRequest(CheckpointerRequest *request, int fd)
elog(FATAL, "unexpected short write to fsync request socket");
break;
}
- else if (errno == EWOULDBLOCK || errno == EAGAIN)
+ else if (errno == EWOULDBLOCK || errno == EAGAIN
+#ifdef __darwin__
+ || errno == EMSGSIZE || errno == ENOBUFS
+#endif
+ )
{
+ /*
+ * Testing on macOS 10.13 showed occasional EMSGSIZE or
+ * ENOBUFS errors, which could be handled by retrying. Unless
+ * the problem also shows up on other systems, let's handle those
+ * only for that OS.
+ */
+
/* blocked on write - wait for socket to become readable */
rc = WaitLatchOrSocket(NULL,
WL_SOCKET_WRITEABLE | WL_POSTMASTER_DEATH,
@@ -1331,6 +1342,6 @@ SendFsyncRequest(CheckpointerRequest *request, int fd)
exit(1);
}
else
- ereport(FATAL, (errmsg("could not receive fsync request: %m")));
+ ereport(FATAL, (errmsg("could not send fsync request: %m")));
}
}
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 7135a57df57..d45e15a9e41 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -3642,7 +3642,7 @@ pg_uds_send_with_fd(int sock, void *buf, ssize_t buflen, int fd)
{
ssize_t size;
struct msghdr msg = {0};
- struct iovec iov;
+ struct iovec iov = {0};
/* cmsg header, union for correct alignment */
union
{
@@ -3651,6 +3651,7 @@ pg_uds_send_with_fd(int sock, void *buf, ssize_t buflen, int fd)
} cmsgu;
struct cmsghdr *cmsg;
+ memset(&cmsgu, 0, sizeof(cmsgu));
iov.iov_base = buf;
iov.iov_len = buflen;
--
2.17.0
I was looking at the commitfest entry for feature
(https://commitfest.postgresql.org/19/1639/) for the most recent list
of patches to try out. The list doesn't look correct/complete. Can
someone please check?
Asim
On Wed, Aug 15, 2018 at 11:08 AM, Asim R P <apraveen@pivotal.io> wrote:
I was looking at the commitfest entry for feature
(https://commitfest.postgresql.org/19/1639/) for the most recent list
of patches to try out. The list doesn't look correct/complete. Can
someone please check?
Hi Asim,
This thread is a bit tangled up. There are two related patchsets in it:
1. Craig Ringer's PANIC-on-EIO patch set, to cope with the fact that
Linux throws away buffers and errors after reporting an error, so the
checkpointer shouldn't retry as it does today. The latest is here:
/messages/by-id/CAMsr+YFPeKVaQ57PwHqmRNjPCPABsdbV=L85he2dVBcr6yS1mA@mail.gmail.com
2. Andres Freund's fd-sending fsync queue, to cope with the fact that
some versions of Linux only report writeback errors that occurred
after you opened the file, and all versions of Linux and some other
operating systems might forget about writeback errors while no one has
it open.
Here is the original patchset:
/messages/by-id/20180522010823.z5bdq7wnlsna5qoo@alap3.anarazel.de
Here is a fix-up you need:
/messages/by-id/20180522185951.5sdudzl46spktyyz@alap3.anarazel.de
Here are some more fix-up patches that I propose:
/messages/by-id/CAEepm=2WSPP03-20XHpxohSd2UyG_dvw5zWS1v7Eas8Rd=5e4A@mail.gmail.com
I will soon post some more fix-up patches that add EXEC_BACKEND
support, Windows support, and a counting scheme to fix the timing
issue that I mentioned in my first review. I will probably squash it
all down to a tidy patch-set after that.
--
Thomas Munro
http://www.enterprisedb.com
On 15 August 2018 at 07:32, Thomas Munro <thomas.munro@enterprisedb.com>
wrote:
On Wed, Aug 15, 2018 at 11:08 AM, Asim R P <apraveen@pivotal.io> wrote:
I was looking at the commitfest entry for feature
(https://commitfest.postgresql.org/19/1639/) for the most recent list
of patches to try out. The list doesn't look correct/complete. Can
someone please check?Hi Asim,
This thread is a bit tangled up. There are two related patchsets in it:
1. Craig Ringer's PANIC-on-EIO patch set, to cope with the fact that
Linux throws away buffers and errors after reporting an error, so the
checkpointer shouldn't retry as it does today. The latest is here:/messages/by-id/CAMsr+YFPeKVaQ57PwHqmRNjPCPABsdbV%25
3DL85he2dVBcr6yS1mA%40mail.gmail.com2. Andres Freund's fd-sending fsync queue, to cope with the fact that
some versions of Linux only report writeback errors that occurred
after you opened the file, and all versions of Linux and some other
operating systems might forget about writeback errors while no one has
it open.Here is the original patchset:
/messages/by-id/20180522010823.
z5bdq7wnlsna5qoo%40alap3.anarazel.deHere is a fix-up you need:
/messages/by-id/20180522185951.
5sdudzl46spktyyz%40alap3.anarazel.deHere are some more fix-up patches that I propose:
/messages/by-id/CAEepm=2WSPP03-20XHpxohSd2UyG_
dvw5zWS1v7Eas8Rd%3D5e4A%40mail.gmail.comI will soon post some more fix-up patches that add EXEC_BACKEND
support, Windows support, and a counting scheme to fix the timing
issue that I mentioned in my first review. I will probably squash it
all down to a tidy patch-set after that.
Thanks very much Tomas.
I've had to back off from this a bit after posting my initial
panic-for-safety patch, as the changes Andres proposed are a bit out of my
current depth and time capacity.
I still think the panic patch is needed and appropriate, but agree it's not
*sufficient*.
On Thu, Aug 30, 2018 at 2:44 PM Craig Ringer <craig@2ndquadrant.com> wrote:
On 15 August 2018 at 07:32, Thomas Munro <thomas.munro@enterprisedb.com> wrote:
I will soon post some more fix-up patches that add EXEC_BACKEND
support, Windows support, and a counting scheme to fix the timing
issue that I mentioned in my first review. I will probably squash it
all down to a tidy patch-set after that.
I went down a bit of a rabbit hole with the Windows support for
Andres's patch set. I have something that works as far as I can tell,
but my Windows environment consists of throwing things at Appveyor and
seeing what sticks, so I'm hoping that someone with a real Windows
system and knowledge will be able to comment.
New patches in this WIP patch set:
0012: Fix for EXEC_BACKEND.
0013: Windows. This involved teaching latch.c to deal with Windows
asynchronous IO events, since you can't wait for pipe readiness via
WSAEventSelect. Pipes and sockets exist in different dimensions on
Windows, and there are no "Unix" domain sockets (well, there are but
they aren't usable yet[1]https://blogs.msdn.microsoft.com/commandline/2017/12/19/af_unix-comes-to-windows/). An alternative would be to use TCP
sockets for this, and then the code would look more like the Unix
code, but that seems a bit strange. Note that the Windows version
doesn't actually hand off file handles like the Unix code (it could
fairly easily, but there is no reason to think that would actually be
useful on that platform). I may be way off here...
The 0013 patch also fixes a mistake in the 0010 patch: it is not
appropriate to call CFI() while waiting to notify the checkpointer of
a dirty segment, because then ^C could cause the following checkpoint
not to flush dirty data. SendFsyncRequest() is essentially blocking,
except that it uses non-blocking IO so that it multiplex postmaster
death detection.
0014: Fix the ordering race condition mentioned upthread[2]/messages/by-id/CAEepm=04ZCG_8N3m61kXZP-7Ecr02HUNNG-QsAhwyFLim4su2g@mail.gmail.com. All
files are assigned an increasing sequence number after [re]opening (ie
before their first write), so that the checkpointer process can track
the fd that must have the oldest Linux f_wb_err that could be relevant
for writes done by PostgreSQL.
The other patches in this tarball are all as posted already, but are
now rebased and assembled in one place. Also pushed to
https://github.com/macdice/postgres/tree/fsyncgate .
Thoughts?
[1]: https://blogs.msdn.microsoft.com/commandline/2017/12/19/af_unix-comes-to-windows/
[2]: /messages/by-id/CAEepm=04ZCG_8N3m61kXZP-7Ecr02HUNNG-QsAhwyFLim4su2g@mail.gmail.com
--
Thomas Munro
http://www.enterprisedb.com
Attachments:
fsyncgate-v3.tgzapplication/x-gzip; name=fsyncgate-v3.tgzDownload
� ���[ ��iw�F�(z�J���^�Is��V��,��V���$���oH��$� �du������P A����'\�E�B
��<T*�4�|?��}���K�R?�Sw<����0�K�`����+\�|����������k�O�Ri��
���
�[��o�����rj�F��l�j57[5��Te�����L#�h6�����`��>�E���!��Q8R���hUzn���4<�iT[-�3h{�A�k���N�����z���?QNKU*��?U��n^�����z�����w��_������e��as��������:��{�;m�4^�k�jU��*���Y�_~�J��t�b�'Uq���/���+��b�@U�� U!�*�M��
~T����.^���������r�7�m�<�6V��2�?�4�v7��~6{�m��^���8��;U��/��+5�"���&� ��c�>���W�o^�����|����N]�w�W>� ��qY�=h~��� �����&4�R�0�����q��A��)��C��A�s=_
�����'�je�7��bX����*���o�����+��}����Y�����N'����IO/��o��7���O�^m�J�MG��\���v<
#���6��|+�����
����M�&�U]������8W����}��+�77�`0P��e ��^�����nc���Z���9�z�S/���z�]��n���m8���`�{�Q�����h4�-U�?p��3��� ������]�2V.�-�^F������P/ B�9]�]-��m�7�tS�!��xJ?��]|��AF�~����0�������`�������� N��Z��#�Y����5�o�?
�:���4������x��'������Jw�������������������*;��,>�p�O��+fO[��j��`P�/�O��` ��|� %x���m6k��f�������N&���`Zr�*�?�$��� +V�-
f�>���4,� �������/!Q*��/��~TrK�q����O���*��<�W�5��������^��i��A�^i�:-��t:~���z=������A����q�_��?�Se�Y��m�Sf�����
!6��M`�Fn �
���Q/��v�X��-4��ax3�(�jf@�1�
o�1�����}���8�0�q#��������Tu�g��U'�'��PM�����'������&0bD�7��}K���G|�S��������p��I?^�J��w����]U�o��9�f��[�e3\� �����=���V���������u*����i;f� WPk����*�_��@��=l���� �����L�K����z��|`�����,��'��K5(��e�t��iL��(�|���l�_n�o;��1�[@����
'�� T���O={�JN^�6��A����q?
&0�2^��,�(�t������x��7���;�r�xJ�*��0��K���J�@)i����F`�
�w�o�����i4�O�(���"�_�G������$��|�������pb>�Z0y8n(��W���r<����A
�/Bw����/����|`�Q8�����w������:f����O|��g�`M�/��n����w{.0t�qqv���P|�p{x��w� p�������e~�b_����sY$�*�ud,0~ ����%�me���fU��;m�O^�\�u��������{{xv~���Y�9\������_Y jxtp�^����>����{~�������� .���������.�e</s�/������]x>��&����� ��v�a^�%�� �(
#`�#d��,�s���N��@�}|�lZ5@��u���p�D �&�����;�"9��b)�<��K�RKN/��z���������������H�r�9���u�e����^������ @����<$�c��-D������$j����X;����y��!x3����)D���$�T^����?*�����<����<��Q�\��Y���e��!�!��rL$����=����+�
�m��BT-L��1���U����s{����L�����f��V�����^���+N�kv����vev�p\����r��"�������T`"����Q�M�.����_<�}u��{q��@�����x��&�����t4��n�==;��O7D��~������}7��e�p�6�U�e�v�zGHP���� ��w�!����_�A�[ E��[�6���3�f���?����
Q�K���� p&^��=����W*���F�����[|H�3h���m�7��Z�u�zu����F�������q���NUNsy�����1Z�H�T �c`���A:��b������t!�r��ktju��9_C1R���h/��N�5���������&/�G{R��Z�&�����8�[��,�Q��}���������2Jv�P�? ����z���)� p�O&��m������~�
�� 8:i��4�����[|�����;
���Z^��r+��_i�n������~�w�8�_'�p��� )@��� ��l��=/�~V���������C��?�k�?��fXd�\n9���hy�F�k��]A��ZB0@0���hG!m����* ����m��� KD�g-��8�ptpq�������l��=*)����O\d�_h�z;88�yw�BzpL�e�N�������'�����C�x�<��5�G�.�Fw��xY��\t��Gg6���������o*T3���P�i+Y+*ut�U��pP�4���x��i5,���nr86�y�>n���9A�������D��%�%�&���
u�;�}�@���Sp��^jbN�|f�/\���"�,�H�E�$c5�am�M���*@)��MA)�a�z�L�E���+�A�Wz�7�d���.�SCdYi���vje6�o�1�ts�����,��l�W�Cn+FU�=�<�I��)v`M�����X<���m���G@�����ol��P�L�D<��z�� ��]�|���������ie�v^�W�B��
���"X�2w���E���pA�P.���Yn�����@l0�'I�8�3^Y��9���������!!��,6�����+����N�h�2b�l�#��z;t/`����+����
/ S�-
'�|PP��� ��$� �e������o64���C����1d�;L�����$h
B��/�w�d�|Dp0��'����]��&�Kp37�8�4������hB)oxK�c�w��Bn �cm������jE��b���@�_���pr�[��ll��6 �6�
��Sm��� L�p��������f����au}w�>�H�T��2���\3 T�O#o6���je��F���3� �����L��r~�������A���E��m���������������8��?
������h��S��������q3��="��g<�n-�D�����,�@Zl6�
c������#�������J��+�������<��.�o�a���"�Y�|b�;~�J|��~��<&��C�)xF#O)��C��z;w����i2���@�`��(�2V<
����$}J����2������?��M���c_T�:�
�p���1Uc�J��h�Q �H���]A_��|}QVh���#nt��@�4{Qv,�_��
���������D@W���� k�hw%"��q�4�����h����o;U��P��:����}v~���|"T�$�����)�O4��Qz�W�������]����$d _���9�4�TV ����7M��sj�v���@Md^�o��!�is6;�H
#�}�@N����a�����M�p?��]0mi8![�~��<_��#�����3��v���psC��.@���ni^��C~�r���9��C�4����[����4*%t��btL�1��p6��3�Q��7�v����]��y���-b������`v�'�����d���#�6�
n^D�8v�Q��S�[�xE��2��`�b�5�����K\���"����0��0� �e;�T��������t���Ojq'�]r@��`���8��D���^E���*i������O�Ri���d2^��~)�/Av�#�D��vc��r�+�!�;A��
���W�W�������������:�Z�o�+~����
��v�g�������6�V���:�?N��H��PU6���H�T7���[��)/�o��
G.r��y&!�X���j^U�T��4�9��0h���}.���\�5��%��H���+U#�smA�\��>W�V?/�wo�v�^:n�V�tj�F�\��z��T�~}�:zy��j��m��7����pS�E�Rm
�������(������}s��z�`<w}r��8^,XAT�v��(�����v,��U�w����\
=�� �o2k�,���jqd[Z�Bi�aA�]_wHJ����"*HYiMz�� �T�V�������x6���3w� ��G&0��H�m �U�����^��U �>����8`�x���q>fDwt������o� b������eS�m���8�X��6&8�#��A%�������"@��� pt���T;{��8����q0�:���������ZU�H�"���q> �Ga�=�|�u�������g4�'�Z�7�11 ��*�wV�.�������"�<������/�V���u� |y�
6 ������8��c�)J
�� ���o���|�����q� ��>�>��A������tD�G�?�}8?���"%R�!@S��g9@�a�C�����bBf*��0���L�����K�Q��G�l�QH��|U(k�@� b
�r<�!kYm<!��fc���l�(�Q���CRjsGfv� �rQ�����Y }�o3e���PcN:q���ixKk
6?�����;J��6�H����|�*S����oJ������y�u��5�����������>�&[�&���puZ�b�����g/���=�)��T���b����w�.� KL�c5B��� ��K^�s�U�U�
X��X��*�^D�Y����?���� ��z/+��l��/J�������g�3�s�Y�G��F�~��k��Kz��p�i�3L��
C��|+E[�n�CG �k�:F�_��Z�(��v=��?�/���hZ��@f6�|�9���Cz'��KzH��A3�:�I��:����F6�v���
�e�l�s_d�A����@�-���[�4���w��$=-wqI�0`G\\�|5�����w���|�4��R�z�1�=���4�(�r�E�&�p$To�z��?)��<^d�EEb����gPz|O�N (%�� ����^}�B���S
��?PLyV�$����tj �U��M�Q�1Z��z^���a�)�� Dp� �01
�;������SWpLG�
!%��;C�.��T�{�H����t�������q���`��c�>��H>?>l��y\�����h���Y
m��"�gy�]z����#�j���~�!�)��e���CbL���mkL��9�G�zp�� ���e��0�1��="w�r��'��zi�|���Ne�
��e�_��\IC��WbV�h����~[�)��-[�g �:m���<N������b��z)�w2�/h��)U�:
p����0S���C�M�p$=�!Qsg��-�"�Kzg����,6K���L��Z��\�!4hM���������3^`b���K����������=����/����a;���Q�R� �� ��z
���%2�JSI���������i����~����j��DFwNu�L5q���<+-��L����_�\��5yuvpt~��{~���g�J�B�e�N��r�%G��?�G���s"-���@D�����`�@��`L�~�,A��"��-��O4��e_'����k�#�!�d,��e[cmr$�J��i���2��_�(���)�T ~�#����El�c�0C�;q�)����=�c?~�?��%�&]�����Y� 5�����Q.�4?�4Z�R�Y:d�H��>C�'�p��2m�����.a�k�g#Nt��G�]�f�1Kv���Z���e��K�����z� ��T|v`�y��i�X;��_�}!
����=�BL[Tst�E^����l��+w�[ �r@7^���4���%���&J���$|�xj����
�A�V{��^h�����$&#��IC H���={�5q�Wt����%�u��������?�t��$��\�@��W�u(���0'���q��%�k{Mt�W��fR�X���^f�����#W�11s(+����������Z�=����y����������
���p'�6kU�zE<���X1���)F��4@�hI3r����O�$g7�#�o ����t�������19x�fJ�a���7�^8�������\����y����x�sA=��� 3��D7�� ���V������4[��x;��������OK'a�-p�`g2� ���}[xjT�
"��X|���e��*�xk��y�4�ll��~2h�]U��@>�b��_I����;w���K��3�*����hS��J�&�Br�zn�k�2�����e_�s���%r%2�
t9�nDp���!��w�
.��G��a�O/� @�&v�����W���w��i�}�������������2�K��?.�-������F�8����bv���0����?}��I'�������1fF����D����6���Q �P�*27�j�Qq7�B=�D
�r9��BR�)����
�����j�7q��D(�e6���;��Uy_��y\�S���Of ���@�Ts��?q���>f+eL`��n���{�x��@�k�$4@��G�dc�2f�������0K)),t� yj�o4�H"&q�5n��o>�s�0�=��|�B�J�a8k}!(�t���G�U��r���6���G�{`�0 �C3�i ��o���h���o�
j#�<��c����j�K���V^��>Xs8~�Q�������.2^Xg�����:�#i�:CT����Y)���_OP�^KJ_���������;���s[�S.�[n�?p���X�����?xv;RE�I�fUC�Ax�Y0�����^�oI=�p� �*m�������7^eG!�a��m&"x����}�����H &������on�'������ F��G�
�C�_�$R<Y�g�Vsj�B�����?����? �n�U�k��^���T;-��t��^���W�-��j��w��^\����{\J���~�ia�JJ�I ��+�������UG��.�����x���J����$G``_qJ��`R��R�@@*7����bJM �}�� ~�1�E�@�����s.j���@~"��o�������,
��8����}�f���h���&n�O�h����S�jm�+f�dg��>��5��T�tK��N�������t�������?�R�n��mf������o�%��c��U��������t������WZ�:Jg�[��6:��.�W�4z�r�i6�-�s����-:4d�C���j������#G�/rJ��q�*_A���X���e7�D9�T��u�����5����G����g����A��
�1�L���K`I�� mm������-��O�f�R1'I������*��WS�O���x^�S
_��9D(�U��5�"+YN3�<�DX�������2w��M�S=x.�0��h�K<��#������<���7��~�I�,��fu�_�xJl6/?���l������`�+���hz�N���&�$���I�zLB!���c��q��9 n������&��R-:dz���Yql���U�����u/�7����w��������a�l{I���U�,��������@2�!"�,���Cx5u6���}�m0����X�<[)��MDI1��4�x����L'"tL3j�
Q8��9�i�3v<�"g��1�Q��-%Y6��@8��4A_#B���)��C=w����+D��m�������}I����$���J{;�������s�{|� v��?��1��� ��l5 ��s�'���5��8=�W��NUE�p]� �P�
9�d��<a�IF_�LJ�0)�7�DmdlQ��������7G�����`z�7g���o-kjh���I�]t����):-��g�`����^�����x>����C�Xd�tyi;d���M�.��p� M����!]��n�+�cV)`���(��)����@|�F�&)����v.,Z���"Ig���Y�I:��5=�����~NL����|/����m����^� `����f���=3����o8�T��Apitbvc�R��,�������(��2
=(�OR�G��T%��!;��N/b��=�7�4
� mL��{�g])���������h�����G�~��
�G(�����"��)�����������_���������������9��v/~���������8^��sv�(�e�����_t�~: Dzrx�]��=<fSz�'�9U�H��+���|�����������P�O������������_R����=��SO��F~t����gC16&ly�z��Y�nL�z����aW�NE��W���X���
. �^;���e�"pM�Pc��/��QY�� �X�5�\����C�C�FH� ��(ZbcL����2=�4AJNp������E3&��&Oa0~�q�{����M�(`�B^�G�*$�/Y%�������22msk.4|����B$5%�KLw�%�$��G��v��/����#�j7�;P-:6KOn�F�6�5���Ib��x�iC'�$�t��(���S���B�hv���(Q��(���\����0$ $���$�b�a�2M�2���)c5I5����s��%3��������{�SWC_\����|��[��D��0^O'�D��Yz�hGN�Yx�N5&O�%/e����@�c[W �
�VW5�����0������
�
{��t�@t�!}�"5G�
g�S[�C��LVG��H��Xyz��������wG����Q��������? H�d���-=e�/u�I5C�g2A�#*���}F��������P���I����rV{[��T�w!����><��g�S1y�����E�z� !�\��U��zD���V:�@�R����@�'N.��<J��Hu��������F��d��;��P�e'��sH��Xw���ket5��9�;�#s2F�� �����g���V��H4���W����n�d��.��VU9�k�QAO�,� �>v���Lnd�crs��G���Z�$��g\�K����%Gi
QDl�v�D���D\`V��sT ��
�,���(:�j�L��)/��3��6���Fr������=���WXi�R��A�D*��<Q`0LI���Lcp#�4_qYw����NkE,�r����O��M^���N��������i@s:(�<