2 * Copyright 2013 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #define __STDC_LIMIT_MACROS
19 #include "folly/io/IOBuf.h"
21 #include "folly/Malloc.h"
22 #include "folly/Likely.h"
29 using std::unique_ptr;
33 const uint32_t IOBuf::kMaxIOBufSize;
34 // Note: Applying offsetof() to an IOBuf is legal according to C++11, since
35 // IOBuf is a standard-layout class. However, this isn't legal with earlier
36 // C++ standards, which require that offsetof() only be used with POD types.
38 // This code compiles with g++ 4.6, but not with g++ 4.4 or earlier versions.
39 const uint32_t IOBuf::kMaxInternalDataSize =
40 kMaxIOBufSize - offsetof(folly::IOBuf, int_.buf);
42 IOBuf::SharedInfo::SharedInfo()
45 // Use relaxed memory ordering here. Since we are creating a new SharedInfo,
46 // no other threads should be referring to it yet.
47 refcount.store(1, std::memory_order_relaxed);
50 IOBuf::SharedInfo::SharedInfo(FreeFunction fn, void* arg)
53 // Use relaxed memory ordering here. Since we are creating a new SharedInfo,
54 // no other threads should be referring to it yet.
55 refcount.store(1, std::memory_order_relaxed);
58 void* IOBuf::operator new(size_t size) {
59 // Since IOBuf::create() manually allocates space for some IOBuf objects
60 // using malloc(), override operator new so that all IOBuf objects are
61 // always allocated using malloc(). This way operator delete can always know
62 // that free() is the correct way to deallocate the memory.
63 void* ptr = malloc(size);
65 // operator new is not allowed to return NULL
66 if (UNLIKELY(ptr == NULL)) {
67 throw std::bad_alloc();
73 void* IOBuf::operator new(size_t size, void* ptr) {
74 assert(size <= kMaxIOBufSize);
78 void IOBuf::operator delete(void* ptr) {
79 // For small buffers, IOBuf::create() manually allocates the space for the
80 // IOBuf object using malloc(). Therefore we override delete to ensure that
81 // the IOBuf space is freed using free() rather than a normal delete.
85 unique_ptr<IOBuf> IOBuf::create(uint32_t capacity) {
86 // If the desired capacity is less than kMaxInternalDataSize,
87 // just allocate a single region large enough for both the IOBuf header and
89 if (capacity <= kMaxInternalDataSize) {
90 void* buf = malloc(kMaxIOBufSize);
91 if (UNLIKELY(buf == NULL)) {
92 throw std::bad_alloc();
95 uint8_t* bufEnd = static_cast<uint8_t*>(buf) + kMaxIOBufSize;
96 unique_ptr<IOBuf> iobuf(new(buf) IOBuf(bufEnd));
97 assert(iobuf->capacity() >= capacity);
101 // Allocate an external buffer
103 SharedInfo* sharedInfo;
104 uint32_t actualCapacity;
105 allocExtBuffer(capacity, &buf, &sharedInfo, &actualCapacity);
107 // Allocate the IOBuf header
109 return unique_ptr<IOBuf>(new IOBuf(kExtAllocated, 0,
119 unique_ptr<IOBuf> IOBuf::createChain(
120 size_t totalCapacity, uint32_t maxBufCapacity) {
121 unique_ptr<IOBuf> out = create(
122 std::min(totalCapacity, size_t(maxBufCapacity)));
123 size_t allocatedCapacity = out->capacity();
125 while (allocatedCapacity < totalCapacity) {
126 unique_ptr<IOBuf> newBuf = create(
127 std::min(totalCapacity - allocatedCapacity, size_t(maxBufCapacity)));
128 allocatedCapacity += newBuf->capacity();
129 out->prependChain(std::move(newBuf));
135 unique_ptr<IOBuf> IOBuf::takeOwnership(void* buf, uint32_t capacity,
140 SharedInfo* sharedInfo = NULL;
142 sharedInfo = new SharedInfo(freeFn, userData);
144 uint8_t* bufPtr = static_cast<uint8_t*>(buf);
145 return unique_ptr<IOBuf>(new IOBuf(kExtUserSupplied, kFlagFreeSharedInfo,
154 freeFn(buf, userData);
156 // The user's free function is not allowed to throw.
167 unique_ptr<IOBuf> IOBuf::wrapBuffer(const void* buf, uint32_t capacity) {
168 // We cast away the const-ness of the buffer here.
169 // This is okay since IOBuf users must use unshare() to create a copy of
170 // this buffer before writing to the buffer.
171 uint8_t* bufPtr = static_cast<uint8_t*>(const_cast<void*>(buf));
172 return unique_ptr<IOBuf>(new IOBuf(kExtUserSupplied, kFlagUserOwned,
178 IOBuf::IOBuf(uint8_t* end)
184 assert(end - int_.buf == kMaxInternalDataSize);
185 assert(end - reinterpret_cast<uint8_t*>(this) == kMaxIOBufSize);
188 IOBuf::IOBuf(ExtBufTypeEnum type,
194 SharedInfo* sharedInfo)
199 flags_(kFlagExt | flags) {
200 ext_.capacity = capacity;
203 ext_.sharedInfo = sharedInfo;
206 assert(data + length <= buf + capacity);
207 assert(static_cast<bool>(flags & kFlagUserOwned) ==
208 (sharedInfo == NULL));
212 // Destroying an IOBuf destroys the entire chain.
213 // Users of IOBuf should only explicitly delete the head of any chain.
214 // The other elements in the chain will be automatically destroyed.
215 while (next_ != this) {
216 // Since unlink() returns unique_ptr() and we don't store it,
217 // it will automatically delete the unlinked element.
218 (void)next_->unlink();
221 if (flags_ & kFlagExt) {
226 bool IOBuf::empty() const {
227 const IOBuf* current = this;
229 if (current->length() != 0) {
232 current = current->next_;
233 } while (current != this);
237 uint32_t IOBuf::countChainElements() const {
238 uint32_t numElements = 1;
239 for (IOBuf* current = next_; current != this; current = current->next_) {
245 uint64_t IOBuf::computeChainDataLength() const {
246 uint64_t fullLength = length_;
247 for (IOBuf* current = next_; current != this; current = current->next_) {
248 fullLength += current->length_;
253 void IOBuf::prependChain(unique_ptr<IOBuf>&& iobuf) {
254 // Take ownership of the specified IOBuf
255 IOBuf* other = iobuf.release();
257 // Remember the pointer to the tail of the other chain
258 IOBuf* otherTail = other->prev_;
260 // Hook up prev_->next_ to point at the start of the other chain,
261 // and other->prev_ to point at prev_
262 prev_->next_ = other;
263 other->prev_ = prev_;
265 // Hook up otherTail->next_ to point at us,
266 // and prev_ to point back at otherTail,
267 otherTail->next_ = this;
271 unique_ptr<IOBuf> IOBuf::clone() const {
272 unique_ptr<IOBuf> newHead(cloneOne());
274 for (IOBuf* current = next_; current != this; current = current->next_) {
275 newHead->prependChain(current->cloneOne());
281 unique_ptr<IOBuf> IOBuf::cloneOne() const {
282 if (flags_ & kFlagExt) {
283 unique_ptr<IOBuf> iobuf(new IOBuf(static_cast<ExtBufTypeEnum>(ext_.type),
284 flags_, ext_.buf, ext_.capacity,
287 if (ext_.sharedInfo) {
288 ext_.sharedInfo->refcount.fetch_add(1, std::memory_order_acq_rel);
292 // We have an internal data buffer that cannot be shared
293 // Allocate a new IOBuf and copy the data into it.
294 unique_ptr<IOBuf> iobuf(IOBuf::create(kMaxInternalDataSize));
295 assert((iobuf->flags_ & kFlagExt) == 0);
296 iobuf->data_ += headroom();
297 memcpy(iobuf->data_, data_, length_);
298 iobuf->length_ = length_;
303 void IOBuf::unshareOneSlow() {
304 // Internal buffers are always unshared, so unshareOneSlow() can only be
305 // called for external buffers
306 assert(flags_ & kFlagExt);
308 // Allocate a new buffer for the data
310 SharedInfo* sharedInfo;
311 uint32_t actualCapacity;
312 allocExtBuffer(ext_.capacity, &buf, &sharedInfo, &actualCapacity);
315 // Maintain the same amount of headroom. Since we maintained the same
316 // minimum capacity we also maintain at least the same amount of tailroom.
317 uint32_t headlen = headroom();
318 memcpy(buf + headlen, data_, length_);
320 // Release our reference on the old buffer
322 // Make sure kFlagExt is set, and kFlagUserOwned and kFlagFreeSharedInfo
326 // Update the buffer pointers to point to the new buffer
327 data_ = buf + headlen;
329 ext_.sharedInfo = sharedInfo;
332 void IOBuf::unshareChained() {
333 // unshareChained() should only be called if we are part of a chain of
334 // multiple IOBufs. The caller should have already verified this.
337 IOBuf* current = this;
339 if (current->isSharedOne()) {
340 // we have to unshare
344 current = current->next_;
345 if (current == this) {
346 // None of the IOBufs in the chain are shared,
347 // so return without doing anything
352 // We have to unshare. Let coalesceSlow() do the work.
356 void IOBuf::coalesceSlow(size_t maxLength) {
357 // coalesceSlow() should only be called if we are part of a chain of multiple
358 // IOBufs. The caller should have already verified this.
360 assert(length_ < maxLength);
362 // Compute the length of the entire chain
363 uint64_t newLength = 0;
366 newLength += end->length_;
368 } while (newLength < maxLength && end != this);
370 uint64_t newHeadroom = headroom();
371 uint64_t newTailroom = end->prev_->tailroom();
372 coalesceAndReallocate(newHeadroom, newLength, end, newTailroom);
373 // We should be only element left in the chain now
374 assert(length_ >= maxLength || !isChained());
377 void IOBuf::coalesceAndReallocate(size_t newHeadroom,
380 size_t newTailroom) {
381 uint64_t newCapacity = newLength + newHeadroom + newTailroom;
382 if (newCapacity > UINT32_MAX) {
383 throw std::overflow_error("IOBuf chain too large to coalesce");
386 // Allocate space for the coalesced buffer.
387 // We always convert to an external buffer, even if we happened to be an
388 // internal buffer before.
391 uint32_t actualCapacity;
392 allocExtBuffer(newCapacity, &newBuf, &newInfo, &actualCapacity);
394 // Copy the data into the new buffer
395 uint8_t* newData = newBuf + newHeadroom;
396 uint8_t* p = newData;
397 IOBuf* current = this;
398 size_t remaining = newLength;
400 assert(current->length_ <= remaining);
401 remaining -= current->length_;
402 memcpy(p, current->data_, current->length_);
403 p += current->length_;
404 current = current->next_;
405 } while (current != end);
406 assert(remaining == 0);
408 // Point at the new buffer
409 if (flags_ & kFlagExt) {
413 // Make sure kFlagExt is set, and kFlagUserOwned and kFlagFreeSharedInfo
417 ext_.capacity = actualCapacity;
418 ext_.type = kExtAllocated;
420 ext_.sharedInfo = newInfo;
424 // Separate from the rest of our chain.
425 // Since we don't store the unique_ptr returned by separateChain(),
426 // this will immediately delete the returned subchain.
428 (void)separateChain(next_, current->prev_);
432 void IOBuf::decrementRefcount() {
433 assert(flags_ & kFlagExt);
435 // Externally owned buffers don't have a SharedInfo object and aren't managed
436 // by the reference count
437 if (flags_ & kFlagUserOwned) {
438 assert(ext_.sharedInfo == NULL);
442 // Decrement the refcount
443 uint32_t newcnt = ext_.sharedInfo->refcount.fetch_sub(
444 1, std::memory_order_acq_rel);
445 // Note that fetch_sub() returns the value before we decremented.
446 // If it is 1, we were the only remaining user; if it is greater there are
447 // still other users.
452 // We were the last user. Free the buffer
453 if (ext_.sharedInfo->freeFn != NULL) {
455 ext_.sharedInfo->freeFn(ext_.buf, ext_.sharedInfo->userData);
457 // The user's free function should never throw. Otherwise we might
458 // throw from the IOBuf destructor. Other code paths like coalesce()
459 // also assume that decrementRefcount() cannot throw.
466 // Free the SharedInfo if it was allocated separately.
468 // This is only used by takeOwnership().
470 // To avoid this special case handling in decrementRefcount(), we could have
471 // takeOwnership() set a custom freeFn() that calls the user's free function
472 // then frees the SharedInfo object. (This would require that
473 // takeOwnership() store the user's free function with its allocated
474 // SharedInfo object.) However, handling this specially with a flag seems
475 // like it shouldn't be problematic.
476 if (flags_ & kFlagFreeSharedInfo) {
477 delete ext_.sharedInfo;
481 void IOBuf::reserveSlow(uint32_t minHeadroom, uint32_t minTailroom) {
482 size_t newCapacity = (size_t)length_ + minHeadroom + minTailroom;
483 CHECK_LT(newCapacity, UINT32_MAX);
485 // We'll need to reallocate the buffer.
486 // There are a few options.
487 // - If we have enough total room, move the data around in the buffer
488 // and adjust the data_ pointer.
489 // - If we're using an internal buffer, we'll switch to an external
490 // buffer with enough headroom and tailroom.
491 // - If we have enough headroom (headroom() >= minHeadroom) but not too much
492 // (so we don't waste memory), we can try one of two things, depending on
493 // whether we use jemalloc or not:
494 // - If using jemalloc, we can try to expand in place, avoiding a memcpy()
495 // - If not using jemalloc and we don't have too much to copy,
496 // we'll use realloc() (note that realloc might have to copy
497 // headroom + data + tailroom, see smartRealloc in folly/Malloc.h)
498 // - Otherwise, bite the bullet and reallocate.
499 if (headroom() + tailroom() >= minHeadroom + minTailroom) {
500 uint8_t* newData = writableBuffer() + minHeadroom;
501 memmove(newData, data_, length_);
506 size_t newAllocatedCapacity = goodExtBufferSize(newCapacity);
507 uint8_t* newBuffer = nullptr;
508 uint32_t newHeadroom = 0;
509 uint32_t oldHeadroom = headroom();
511 if ((flags_ & kFlagExt) && length_ != 0 && oldHeadroom >= minHeadroom) {
512 if (usingJEMalloc()) {
513 size_t headSlack = oldHeadroom - minHeadroom;
514 // We assume that tailroom is more useful and more important than
515 // tailroom (not least because realloc / rallocm allow us to grow the
516 // buffer at the tail, but not at the head) So, if we have more headroom
517 // than we need, we consider that "wasted". We arbitrarily define "too
518 // much" headroom to be 25% of the capacity.
519 if (headSlack * 4 <= newCapacity) {
520 size_t allocatedCapacity = capacity() + sizeof(SharedInfo);
522 if (allocatedCapacity >= jemallocMinInPlaceExpandable) {
523 int r = rallocm(&p, &newAllocatedCapacity, newAllocatedCapacity,
525 if (r == ALLOCM_SUCCESS) {
526 newBuffer = static_cast<uint8_t*>(p);
527 newHeadroom = oldHeadroom;
528 } else if (r == ALLOCM_ERR_OOM) {
529 // shouldn't happen as we don't actually allocate new memory
530 // (due to ALLOCM_NO_MOVE)
531 throw std::bad_alloc();
533 // if ALLOCM_ERR_NOT_MOVED, do nothing, fall back to
534 // malloc/memcpy/free
537 } else { // Not using jemalloc
538 size_t copySlack = capacity() - length_;
539 if (copySlack * 2 <= length_) {
540 void* p = realloc(ext_.buf, newAllocatedCapacity);
541 if (UNLIKELY(p == nullptr)) {
542 throw std::bad_alloc();
544 newBuffer = static_cast<uint8_t*>(p);
545 newHeadroom = oldHeadroom;
550 // None of the previous reallocation strategies worked (or we're using
551 // an internal buffer). malloc/copy/free.
552 if (newBuffer == nullptr) {
553 void* p = malloc(newAllocatedCapacity);
554 if (UNLIKELY(p == nullptr)) {
555 throw std::bad_alloc();
557 newBuffer = static_cast<uint8_t*>(p);
558 memcpy(newBuffer + minHeadroom, data_, length_);
559 if (flags_ & kFlagExt) {
562 newHeadroom = minHeadroom;
567 initExtBuffer(newBuffer, newAllocatedCapacity, &info, &cap);
572 ext_.type = kExtAllocated;
573 ext_.buf = newBuffer;
574 ext_.sharedInfo = info;
575 data_ = newBuffer + newHeadroom;
576 // length_ is unchanged
579 void IOBuf::allocExtBuffer(uint32_t minCapacity,
581 SharedInfo** infoReturn,
582 uint32_t* capacityReturn) {
583 size_t mallocSize = goodExtBufferSize(minCapacity);
584 uint8_t* buf = static_cast<uint8_t*>(malloc(mallocSize));
585 if (UNLIKELY(buf == NULL)) {
586 throw std::bad_alloc();
588 initExtBuffer(buf, mallocSize, infoReturn, capacityReturn);
592 size_t IOBuf::goodExtBufferSize(uint32_t minCapacity) {
593 // Determine how much space we should allocate. We'll store the SharedInfo
594 // for the external buffer just after the buffer itself. (We store it just
595 // after the buffer rather than just before so that the code can still just
596 // use free(ext_.buf) to free the buffer.)
597 size_t minSize = static_cast<size_t>(minCapacity) + sizeof(SharedInfo);
598 // Add room for padding so that the SharedInfo will be aligned on an 8-byte
600 minSize = (minSize + 7) & ~7;
602 // Use goodMallocSize() to bump up the capacity to a decent size to request
603 // from malloc, so we can use all of the space that malloc will probably give
605 return goodMallocSize(minSize);
608 void IOBuf::initExtBuffer(uint8_t* buf, size_t mallocSize,
609 SharedInfo** infoReturn,
610 uint32_t* capacityReturn) {
611 // Find the SharedInfo storage at the end of the buffer
612 // and construct the SharedInfo.
613 uint8_t* infoStart = (buf + mallocSize) - sizeof(SharedInfo);
614 SharedInfo* sharedInfo = new(infoStart) SharedInfo;
616 size_t actualCapacity = infoStart - buf;
617 // On the unlikely possibility that the actual capacity is larger than can
618 // fit in a uint32_t after adding room for the refcount and calling
619 // goodMallocSize(), truncate downwards if necessary.
620 if (actualCapacity >= UINT32_MAX) {
621 *capacityReturn = UINT32_MAX;
623 *capacityReturn = actualCapacity;
626 *infoReturn = sharedInfo;
629 fbstring IOBuf::moveToFbString() {
630 // Externally allocated buffers (malloc) are just fine, everything else needs
631 // to be turned into one.
632 if (flags_ != kFlagExt || // not malloc()-ed
633 headroom() != 0 || // malloc()-ed block doesn't start at beginning
634 tailroom() == 0 || // no room for NUL terminator
635 isShared() || // shared
636 isChained()) { // chained
637 // We might as well get rid of all head and tailroom if we're going
638 // to reallocate; we need 1 byte for NUL terminator.
639 coalesceAndReallocate(0, computeChainDataLength(), this, 1);
642 // Ensure NUL terminated
644 fbstring str(reinterpret_cast<char*>(writableData()),
645 length(), capacity(),
646 AcquireMallocatedString());
648 // Reset to internal buffer.
654 IOBuf::Iterator IOBuf::cbegin() const {
655 return Iterator(this, this);
658 IOBuf::Iterator IOBuf::cend() const {
659 return Iterator(nullptr, nullptr);
662 folly::fbvector<struct iovec> IOBuf::getIov() const {
663 folly::fbvector<struct iovec> iov;
664 iov.reserve(countChainElements());
665 IOBuf const* p = this;
667 // some code can get confused by empty iovs, so skip them
668 if (p->length() > 0) {
669 iov.push_back({(void*)p->data(), p->length()});