Skip to content

os/transaction: page align write data buffers to improve performance - version 1 - #57738

Closed
bill-scales wants to merge 1 commit into
ceph:mainfrom
bill-scales:wip-bscales-align-write-buffers-v1
Closed

bill-scales wants to merge 1 commit into
ceph:mainfrom
bill-scales:wip-bscales-align-write-buffers-v1

Conversation

@bill-scales

Copy link
Copy Markdown
Contributor

Align write data in Objectstore::Transaction encoded buffers so that RepOp and ECSubOpWrite messages align data on the receiving OSD to avoid a later memmove. Also fix ECSubOpReadReply messages in a similar way so that read data is aligned on the receiving OSD.

Version 1 - Minimal change, fixes alignment for RepOp and ECSubOpReadReply. ECSubOpWrite is only partially fixed - it splits long writes into multiple stripes, only the longest write will be aligned.

More detail

Profiling showed that bluestore was spending a lot of time realigning data buffers for write I/Os. The flamegraph below (64K sequential writes to a 2+2 erasure code pool) has a plateau on the right where memmove is being used to realign buffers. In this profile 8% CPU time was spent realigning data.

Screenshot 2024-05-28 at 08 12 13

Investigation found:

  1. Client to OSD messages will usually keep page aligned writes to RADOS objects in page aligned buffers - so nothing needs fixing here
  2. Inter-OSD messages for Erasure Code pools have never tried to align data buffers to avoid memcpy’s
  3. Inter-OSD messages for Replicated pools try to get the data buffer aligned on the receiving OSD using data_off field in the Message header, however this is ignored by ProtocolV2 and newer so has been broken for some time

Trying to fix ProtocolV2 is problematic, especially when considering newer features such as compression and encryption for data in flight (which benefit from page aligning the start of the buffer), this is probably why the data offset feature wasn’t implemented.

This pull request implements a new technique for ensuring that the majority of data is aligned (performance optimizations don’t have to be perfect - if 99% of the data is aligned you get 99% of the performance benefit). Instead of encoding/decoding a data structure such as ObjectStore::Transaction into a single buffer, a new style encode/decode interface is implemented which encodes/decodes data into a pair of buffers - the payload buffer is used for data structures, strings, etc. the second buffer is used only for data. Aligned data is placed in the data buffer first, followed by any misaligned data. Decoding uses information in the payload buffer to work out how to reassemble the data. Messages between Ceph clients/daemons already have a payload buffer and a data buffer and already guarantee that the data buffer will be page aligned on the receiver so its easy to use these two buffers with the new encode/decode methods. Long write buffers at misaligned offsets can even be efficiently encoded by splitting the data into three fragments - a misaligned prefix and suffix and an aligned middle part.

Backwards compatibility is a concern and therefore it must be possible to encode/decode objects in both a new style format using two buffers and an old style format that is backwards compatible with older code.

This is version 1 of the pull request - the merits of this version is a minimal set of changes, the changes to ObjectStore::Transaction are contained to the encoding/decoding functions. Only the largest data buffer in the transaction will be aligned (using the existing code in Transaction.h that tracks this). This is inconsequential for Replicated pools as most transactions will only have one data buffer. It is a problem for Erasure coded pools where long writes get broken into a series of chunk sized writes (defaults to 4K) in the transaction and will be encoded as <4 byte length><4 byte length>… so only one chunk will be properly aligned.

The decode function will create the same transaction regardless of whether an old or new style encoding was used, the only difference being the buffer fragments and their alignment in the data buffer list. As only the encode/decode functions are modified there is no changes needed to the iterator or other operations on transactions such as appends.

New unit tests are added to fully exercise building, encoding and decoding ObjectStore transactions and to validate the improvement in aligning buffers. The rbd bench utility is extended with extra options to provide more flexibility in generating I/O requests.

The RepOp, ECSubWriteOp and ECSubReadReplyOp messages have been modified to align the write data buffers they send. Manual testing has confirmed that these buffers are correctly page aligned on the receiving OSD.


The performance benchmark ceph_perf_objectstore was run on old and new code and shows negligible difference in performance for the typical set of operations performed on ObjectStore::Transaction’s.

Contribution Guidelines

  • To sign and title your commits, please refer to Submitting Patches to Ceph.

  • If you are submitting a fix for a stable branch (e.g. "quincy"), please refer to Submitting Patches to Ceph - Backports for the proper workflow.

  • When filling out the below checklist, you may click boxes directly in the GitHub web UI. When entering or editing the entire PR message in the GitHub web UI editor, you may also select a checklist item by adding an x between the brackets: [x]. Spaces and capitalization matter when checking off items this way.

Checklist

  • Tracker (select at least one)
    • References tracker ticket
    • Very recent bug; references commit where it was introduced
    • New feature (ticket optional)
    • Doc update (no ticket needed)
    • Code cleanup (no ticket needed)
  • Component impact
    • Affects Dashboard, opened tracker ticket
    • Affects Orchestrator, opened tracker ticket
    • No impact that needs to be tracked
  • Documentation (select at least one)
    • Updates relevant documentation
    • No doc update is appropriate
  • Tests (select at least one)
Show available Jenkins commands
  • jenkins retest this please
  • jenkins test classic perf
  • jenkins test crimson perf
  • jenkins test signed
  • jenkins test make check
  • jenkins test make check arm64
  • jenkins test submodules
  • jenkins test dashboard
  • jenkins test dashboard cephadm
  • jenkins test api
  • jenkins test docs
  • jenkins render docs
  • jenkins test ceph-volume all
  • jenkins test ceph-volume tox
  • jenkins test windows
  • jenkins test rook e2e

Align write data in Objectstore::Transaction encoded buffers so that
RepOp and ECSubOpWrite messages align data on the receiving OSD to
avoid a later memmove.  Also fix ECSubOpReadReply messages in a
similar way so that read data is aligned on the receiving OSD.

Signed-off-by: Bill Scales <[email protected]>
@idryomov

Copy link
Copy Markdown
Contributor

3. Inter-OSD messages for Replicated pools try to get the data buffer aligned on the receiving OSD using data_off field in the Message header, however this is ignored by ProtocolV2 and newer so has been broken for some time

Trying to fix ProtocolV2 is problematic

Can you elaborate on this? Why fixing ProtocolV2 is problematic? To me, the messenger layer seems like the perfect place to do this -- you read some data off the wire, break it down and place the pieces into suitably-aligned buffers. A copy from the socket buffer to the application buffer has to happen anyway, so piggy backing on it for aligning seems only natural.

especially when considering newer features such as compression and encryption for data in flight (which benefit from page aligning the start of the buffer), this is probably why the data offset feature wasn’t implemented.

I might be missing something, but I don't think that is the case. Each message has up to four segments, with the data segment being the last one (if present at all). Each segment is read off the wire separately, with a separate destination bufferlist allocated for it. The allocation is supposed to respect the alignment requested by the sender of the message:

rx_buffer_t rx_buffer;
uint16_t align = rx_frame_asm.get_segment_align(seg_idx);
try {
rx_buffer = ceph::buffer::ptr_node::create(ceph::buffer::create_aligned(
onwire_len, align));
} catch (const ceph::buffer::bad_alloc&) {
// Catching because of potential issues with satisfying alignment.
ldout(cct, 1) << __func__ << " can't allocate aligned rx_buffer"
<< " len=" << onwire_len
<< " align=" << align
<< dendl;
return _fault();
}
return READ_RXBUF(std::move(rx_buffer), handle_read_frame_segment);

Depending on how decompression or decryption are done, that alignment can be lost, but my recollection is that both are done in place, so I would expect it to be preserved.

@idryomov idryomov left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only RBD bit here is additions to rbd bench command, which are completely orthogonal. I'd suggest breaking that out into a separate PR so that this one remains pure RADOS.

@bill-scales

Copy link
Copy Markdown
Contributor Author

Trying to fix ProtocolV2 is problematic

Can you elaborate on this? Why fixing ProtocolV2 is problematic? To me, the messenger layer seems like the perfect place to do this -- you read some data off the wire, break it down and place the pieces into suitably-aligned buffers. A copy from the socket buffer to the application buffer has to happen anyway, so piggy backing on it for aligning seems only natural.

You are right that there has to be a copy from the socket buffer to the application buffer, so this is the best place to try and realigned data. Both ProtocoV1 and ProtocolV2 will by by default copy the received data into a page aligned buffer. However ProtocolV1 also honors the data_off field in the message header and if this is set to a non-zero value will use this to allocate a deliberately misaligned buffer. This allows the sender to ensure that a specific region of the data buffer (e.g. offset 37, length 16384) is page aligned. Here's the code that does that:

static void alloc_aligned_buffer(ceph::buffer::list &data, unsigned len, unsigned off) {
// create a buffer to read into that matches the data alignment
unsigned alloc_len = 0;
unsigned left = len;
unsigned head = 0;
if (off & ~CEPH_PAGE_MASK) {
// head
alloc_len += CEPH_PAGE_SIZE;
head = std::min<uint64_t>(CEPH_PAGE_SIZE - (off & ~CEPH_PAGE_MASK), left);
left -= head;
}
alloc_len += left;
ceph::bufferptr ptr(ceph::buffer::create_small_page_aligned(alloc_len));
if (head) ptr.set_offset(CEPH_PAGE_SIZE - head);
data.push_back(std::move(ptr));
}

There are drawbacks with doing this:

  1. While the middle of the data buffer is aligned, the start is not. That means that operations such as decryption and decompression have to suffer the performance penalty of using a misaligned buffer. If they stage data into another buffer rather than overwrite in place then this buffer needs to preserve the same misalignment.

  2. This technique only allows one region of the buffer to be aligned on the receiver. ECSubOpWrite messages are generating a data bufferlist that looks like this <4 byte length><4K data><4 byte length><4K data>... for longer writes. Using data_off = page size -4 will align the 1st 4K of data on the receiving OSD, but the subsequent blocks of write data will still be misaligned.

  3. Fractionally more memory is needed on the receiver (not a significant concern)

@idryomov

Copy link
Copy Markdown
Contributor

Thanks for the additional details. It shouldn't be hard to make ProtocolV2 respect data_off field -- I think there was some confusion there with regards to what data_off does and why it is needed because the per-segment align fields that were added to the frame preamble in v2 aren't particularly useful. But it wouldn't help the case of multi-"chunk" ECSubOpWrite messages of course.

I wonder why ECSubOpWrite ended up that way. For example, for a sparse read, the data segment of the OSD reply message looks like <4 byte extent count><8 byte offset><8 byte length><8 byte offset><8 byte length>...<4 byte length><data> (i.e. the map that describes the data for all extents is prepended to the bufferlist).

@bill-scales

Copy link
Copy Markdown
Contributor Author

Profiling shows that the version 1 fix does NOT improve performance - while it avoids a memmove to realign the data buffer being written it introduces an equally bad memmove when decoding the transaction:

Screenshot 2024-05-31 at 13 49 47

The version 1 fix decodes a Transaction message received from another node like this:



        // Aligned data is at the front of the buffer
        bufferlist before;
        bufferlist remainder;
        decode(remainder, p_bl, d_bl);
        decode(before, p_bl, d_bl);
        data_bl.append(before);
        data_bl.append(remainder);

Which results in data_bl being a bufferlist with two buffer pointers. The transaction is then submitted to BlueStore which uses an iterator to decode and apply each opcode of the transaction.

The write data is nicely page aligned so we eliminate the memmove to realign that data. However the majority of transactions will include an update to the object_info_t attribute that contains the last modification time and version number, and hence include an OP_SETATTR opcode which encodes the new attrset into the data_bl buffer. On the receiving OSD the function Transaction::decode_attrset(std::mapstd::string,ceph::buffer::ptr& aset) is called to retrieve the new attrset and decode it from the data_bl buffer.
 This function calls ‘decode(aset, data_bl_p);’ which is implemented by this template:

ceph/src/include/denc.h

Lines 1715 to 1731 in df637ab

inline std::enable_if_t<traits::supported && traits::need_contiguous> decode(
T& o,
ceph::buffer::list::const_iterator& p)
{
if (p.end())
throw ceph::buffer::end_of_buffer();
// ensure we get a contigous buffer... until the end of the
// ceph::buffer::list. we don't really know how much we'll need here,
// unfortunately. hopefully it is already contiguous and we're just
// bumping the raw ref and initializing the ptr tmp fields.
ceph::buffer::ptr tmp;
auto t = p;
t.copy_shallow(p.get_bl().length() - p.get_off(), tmp);
auto cp = std::cbegin(tmp);
traits::decode(o, cp);
p += cp.get_offset();
}

Now we see what the problem is - the data for attrset is in the first buffer of data_bl, followed by another (large) buffer containing the write data. However the decode function doesn’t know how big the data for attrset is, and requires the data to be decoded to be in a single contiguous buffer. The “hope” that input bufferlist being decoded is in a single buffer is sadly not met and we pay the penalty of having to copy the remainder of the bufferlist (including all the write data!) into a temporary buffer so we can then decode the few bytes of data in the attrset.

This calls copy_shallow that calls copy that calls copy_out where the memcpy occurs:

ceph/src/common/buffer.cc

Lines 492 to 498 in df637ab

void buffer::ptr::copy_out(unsigned o, unsigned l, char *dest) const {
ceph_assert(_raw);
if (o+l > _len)
throw end_of_buffer();
char* src = _raw->get_data() + _off + o;
maybe_inline_memcpy(dest, src, l, 8);
}

Version 2 of the fix has a different approach of keeping aligned and misaligned data in separate buffer lists. This avoids this issue on OSDs that receive a message from the Primary OSD because each bufferlist has a single contiguous buffer.

However what about the existing code - this encodes and decodes the Transaction on the primary OSD and because it avoids sending the Transaction via messenger for local writes this means the Transaction decode is again dealing with a multi-buffer bufferlist. Does this have the same problem of copying the entire write data payload to decode the xattr update? Checking with gdb on an unmodifed build the answer is yes!

By accident the version 2 fix helps here as well. The Primary OSD ends up with two buffer lists - one which contains the write data payload (can be large) and one that contains the xattr update and other parts of the transaction. The second buffer list consists of multiple buffers (it was encoded with multiple buffers and hasn't been sent via messenger) so memcpy is required to decode this buffer, however the buffer is typically small so the overheads of the copy are less concerning.

@bill-scales

Copy link
Copy Markdown
Contributor Author

Here is a flamegraph of unmodified code, showing 64K sequential writes at queue depth=1 to a Replicated Pool with just one OSD. The purpose of this test was to verify that the Transaction that gets built (encoded) and then applied (decoded) by BlueStore on the local OSD does end up memcpy'ing the write data buffer:

Screenshot 2024-06-04 at 07 23 30

The plateau on the right shows 9% of CPU time is indeed being spent doing the memmove. With longer write I/Os this overhead will be higher because more data will be copied, for shorter writes it will be smaller. However in a more normal configuration such as a Replicated Pool with 3 copies this overhead will be diluted because only 1/3rd of the BlueStore work will be for local Transactions, the other 2/3rds will be for Transactions that have been sent inter-OSD and these will be decoded from a single sequential buffer and will avoid the copy.

A flamegraph for the version 1 fix (this PR) running the same test shows the same result, however the flaw in the version 1 fix means that the same effect happens for Transactions sent between OSDs, so there is no dilution in more normal configurations.

@bill-scales

Copy link
Copy Markdown
Contributor Author

I'm closing this pull request - testing has showed that this technique eliminates the memcpy to realign the data buffer, but adds an equally bad memcpy in the decode Transaction code path. This is because decoding a map containing the xattr update cannot cope with a bufferlist and needs to create a contiguous buffer. There isn't any simple change that can be made to fix this.

The version 2 fix - #57740 takes a different approach and does not have this problem, the code is a little more complex but more future proof.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants