2 * Copyright 2012 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/experimental/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::takeOwnership(void* buf, uint32_t capacity,
123 SharedInfo* sharedInfo = NULL;
125 sharedInfo = new SharedInfo(freeFn, userData);
127 uint8_t* bufPtr = static_cast<uint8_t*>(buf);
128 return unique_ptr<IOBuf>(new IOBuf(kExtUserSupplied, kFlagFreeSharedInfo,
137 freeFn(buf, userData);
139 // The user's free function is not allowed to throw.
150 unique_ptr<IOBuf> IOBuf::wrapBuffer(const void* buf, uint32_t capacity) {
151 // We cast away the const-ness of the buffer here.
152 // This is okay since IOBuf users must use unshare() to create a copy of
153 // this buffer before writing to the buffer.
154 uint8_t* bufPtr = static_cast<uint8_t*>(const_cast<void*>(buf));
155 return unique_ptr<IOBuf>(new IOBuf(kExtUserSupplied, kFlagUserOwned,
161 IOBuf::IOBuf(uint8_t* end)
167 int_.capacity = end - int_.buf;
168 assert(int_.capacity <= kMaxInternalDataSize);
171 IOBuf::IOBuf(ExtBufTypeEnum type,
177 SharedInfo* sharedInfo)
182 flags_(kFlagExt | flags) {
183 ext_.capacity = capacity;
186 ext_.sharedInfo = sharedInfo;
189 assert(data + length <= buf + capacity);
190 assert(static_cast<bool>(flags & kFlagUserOwned) ==
191 (sharedInfo == NULL));
195 // Destroying an IOBuf destroys the entire chain.
196 // Users of IOBuf should only explicitly delete the head of any chain.
197 // The other elements in the chain will be automatically destroyed.
198 while (next_ != this) {
199 // Since unlink() returns unique_ptr() and we don't store it,
200 // it will automatically delete the unlinked element.
201 (void)next_->unlink();
204 if (flags_ & kFlagExt) {
209 bool IOBuf::empty() const {
210 const IOBuf* current = this;
212 if (current->length() != 0) {
215 current = current->next_;
216 } while (current != this);
220 uint32_t IOBuf::countChainElements() const {
221 uint32_t numElements = 1;
222 for (IOBuf* current = next_; current != this; current = current->next_) {
228 uint64_t IOBuf::computeChainDataLength() const {
229 uint64_t fullLength = length_;
230 for (IOBuf* current = next_; current != this; current = current->next_) {
231 fullLength += current->length_;
236 void IOBuf::prependChain(unique_ptr<IOBuf>&& iobuf) {
237 // Take ownership of the specified IOBuf
238 IOBuf* other = iobuf.release();
240 // Remember the pointer to the tail of the other chain
241 IOBuf* otherTail = other->prev_;
243 // Hook up prev_->next_ to point at the start of the other chain,
244 // and other->prev_ to point at prev_
245 prev_->next_ = other;
246 other->prev_ = prev_;
248 // Hook up otherTail->next_ to point at us,
249 // and prev_ to point back at otherTail,
250 otherTail->next_ = this;
254 unique_ptr<IOBuf> IOBuf::clone() const {
255 unique_ptr<IOBuf> newHead(cloneOne());
257 for (IOBuf* current = next_; current != this; current = current->next_) {
258 newHead->prependChain(current->cloneOne());
264 unique_ptr<IOBuf> IOBuf::cloneOne() const {
265 if (flags_ & kFlagExt) {
266 unique_ptr<IOBuf> iobuf(new IOBuf(static_cast<ExtBufTypeEnum>(ext_.type),
267 flags_, ext_.buf, ext_.capacity,
270 if (ext_.sharedInfo) {
271 ext_.sharedInfo->refcount.fetch_add(1, std::memory_order_acq_rel);
275 // We have an internal data buffer that cannot be shared
276 // Allocate a new IOBuf and copy the data into it.
277 unique_ptr<IOBuf> iobuf(IOBuf::create(int_.capacity));
278 assert((iobuf->flags_ & kFlagExt) == 0);
279 iobuf->data_ += headroom();
280 memcpy(iobuf->data_, data_, length_);
281 iobuf->length_ = length_;
286 void IOBuf::unshareOneSlow() {
287 // Internal buffers are always unshared, so unshareOneSlow() can only be
288 // called for external buffers
289 assert(flags_ & kFlagExt);
291 // Allocate a new buffer for the data
293 SharedInfo* sharedInfo;
294 uint32_t actualCapacity;
295 allocExtBuffer(ext_.capacity, &buf, &sharedInfo, &actualCapacity);
298 // Maintain the same amount of headroom. Since we maintained the same
299 // minimum capacity we also maintain at least the same amount of tailroom.
300 uint32_t headlen = headroom();
301 memcpy(buf + headlen, data_, length_);
303 // Release our reference on the old buffer
305 // Make sure kFlagExt is set, and kFlagUserOwned and kFlagFreeSharedInfo
309 // Update the buffer pointers to point to the new buffer
310 data_ = buf + headlen;
312 ext_.sharedInfo = sharedInfo;
315 void IOBuf::unshareChained() {
316 // unshareChained() should only be called if we are part of a chain of
317 // multiple IOBufs. The caller should have already verified this.
320 IOBuf* current = this;
322 if (current->isSharedOne()) {
323 // we have to unshare
327 current = current->next_;
328 if (current == this) {
329 // None of the IOBufs in the chain are shared,
330 // so return without doing anything
335 // We have to unshare. Let coalesceSlow() do the work.
339 void IOBuf::coalesceSlow(size_t maxLength) {
340 // coalesceSlow() should only be called if we are part of a chain of multiple
341 // IOBufs. The caller should have already verified this.
343 assert(length_ < maxLength);
345 // Compute the length of the entire chain
346 uint64_t newLength = 0;
349 newLength += end->length_;
351 } while (newLength < maxLength && end != this);
353 uint64_t newHeadroom = headroom();
354 uint64_t newTailroom = end->prev_->tailroom();
355 uint64_t newCapacity = newLength + newHeadroom + newTailroom;
356 if (newCapacity > UINT32_MAX) {
357 throw std::overflow_error("IOBuf chain too large to coalesce");
360 // Allocate space for the coalesced buffer.
361 // We always convert to an external buffer, even if we happened to be an
362 // internal buffer before.
365 uint32_t actualCapacity;
366 allocExtBuffer(newCapacity, &newBuf, &newInfo, &actualCapacity);
368 // Copy the data into the new buffer
369 uint8_t* newData = newBuf + newHeadroom;
370 uint8_t* p = newData;
371 IOBuf* current = this;
373 memcpy(p, current->data_, current->length_);
374 p += current->length_;
375 current = current->next_;
376 } while (current != end);
378 // Point at the new buffer
379 if (flags_ & kFlagExt) {
383 // Make sure kFlagExt is set, and kFlagUserOwned and kFlagFreeSharedInfo
387 ext_.capacity = actualCapacity;
388 ext_.type = kExtAllocated;
390 ext_.sharedInfo = newInfo;
394 // Separate from the rest of our chain.
395 // Since we don't store the unique_ptr returned by separateChain(),
396 // this will immediately delete the returned subchain.
397 (void)separateChain(next_, end->prev_);
399 // We should be only element left in the chain now
400 assert(length_ >= maxLength || !isChained());
403 void IOBuf::decrementRefcount() {
404 assert(flags_ & kFlagExt);
406 // Externally owned buffers don't have a SharedInfo object and aren't managed
407 // by the reference count
408 if (flags_ & kFlagUserOwned) {
409 assert(ext_.sharedInfo == NULL);
413 // Decrement the refcount
414 uint32_t newcnt = ext_.sharedInfo->refcount.fetch_sub(
415 1, std::memory_order_acq_rel);
416 // Note that fetch_sub() returns the value before we decremented.
417 // If it is 1, we were the only remaining user; if it is greater there are
418 // still other users.
423 // We were the last user. Free the buffer
424 if (ext_.sharedInfo->freeFn != NULL) {
426 ext_.sharedInfo->freeFn(ext_.buf, ext_.sharedInfo->userData);
428 // The user's free function should never throw. Otherwise we might
429 // throw from the IOBuf destructor. Other code paths like coalesce()
430 // also assume that decrementRefcount() cannot throw.
437 // Free the SharedInfo if it was allocated separately.
439 // This is only used by takeOwnership().
441 // To avoid this special case handling in decrementRefcount(), we could have
442 // takeOwnership() set a custom freeFn() that calls the user's free function
443 // then frees the SharedInfo object. (This would require that
444 // takeOwnership() store the user's free function with its allocated
445 // SharedInfo object.) However, handling this specially with a flag seems
446 // like it shouldn't be problematic.
447 if (flags_ & kFlagFreeSharedInfo) {
448 delete ext_.sharedInfo;
452 void IOBuf::reserveSlow(uint32_t minHeadroom, uint32_t minTailroom) {
453 size_t newCapacity = (size_t)length_ + minHeadroom + minTailroom;
454 CHECK_LT(newCapacity, UINT32_MAX);
456 // We'll need to reallocate the buffer.
457 // There are a few options.
458 // - If we have enough total room, move the data around in the buffer
459 // and adjust the data_ pointer.
460 // - If we're using an internal buffer, we'll switch to an external
461 // buffer with enough headroom and tailroom.
462 // - If we have enough headroom (headroom() >= minHeadroom) but not too much
463 // (so we don't waste memory), we can try one of two things, depending on
464 // whether we use jemalloc or not:
465 // - If using jemalloc, we can try to expand in place, avoiding a memcpy()
466 // - If not using jemalloc and we don't have too much to copy,
467 // we'll use realloc() (note that realloc might have to copy
468 // headroom + data + tailroom, see smartRealloc in folly/Malloc.h)
469 // - Otherwise, bite the bullet and reallocate.
470 if (headroom() + tailroom() >= minHeadroom + minTailroom) {
471 uint8_t* newData = writableBuffer() + minHeadroom;
472 memmove(newData, data_, length_);
477 size_t newAllocatedCapacity = goodExtBufferSize(newCapacity);
478 uint8_t* newBuffer = nullptr;
479 uint32_t newHeadroom = 0;
480 uint32_t oldHeadroom = headroom();
482 if ((flags_ & kFlagExt) && length_ != 0 && oldHeadroom >= minHeadroom) {
483 if (usingJEMalloc()) {
484 size_t headSlack = oldHeadroom - minHeadroom;
485 // We assume that tailroom is more useful and more important than
486 // tailroom (not least because realloc / rallocm allow us to grow the
487 // buffer at the tail, but not at the head) So, if we have more headroom
488 // than we need, we consider that "wasted". We arbitrarily define "too
489 // much" headroom to be 25% of the capacity.
490 if (headSlack * 4 <= newCapacity) {
491 size_t allocatedCapacity = capacity() + sizeof(SharedInfo);
493 if (allocatedCapacity >= jemallocMinInPlaceExpandable) {
494 int r = rallocm(&p, &newAllocatedCapacity, newAllocatedCapacity,
496 if (r == ALLOCM_SUCCESS) {
497 newBuffer = static_cast<uint8_t*>(p);
498 newHeadroom = oldHeadroom;
499 } else if (r == ALLOCM_ERR_OOM) {
500 // shouldn't happen as we don't actually allocate new memory
501 // (due to ALLOCM_NO_MOVE)
502 throw std::bad_alloc();
504 // if ALLOCM_ERR_NOT_MOVED, do nothing, fall back to
505 // malloc/memcpy/free
508 } else { // Not using jemalloc
509 size_t copySlack = capacity() - length_;
510 if (copySlack * 2 <= length_) {
511 void* p = realloc(ext_.buf, newAllocatedCapacity);
512 if (UNLIKELY(p == nullptr)) {
513 throw std::bad_alloc();
515 newBuffer = static_cast<uint8_t*>(p);
516 newHeadroom = oldHeadroom;
521 // None of the previous reallocation strategies worked (or we're using
522 // an internal buffer). malloc/copy/free.
523 if (newBuffer == nullptr) {
524 void* p = malloc(newAllocatedCapacity);
525 if (UNLIKELY(p == nullptr)) {
526 throw std::bad_alloc();
528 newBuffer = static_cast<uint8_t*>(p);
529 memcpy(newBuffer + minHeadroom, data_, length_);
530 if (flags_ & kFlagExt) {
533 newHeadroom = minHeadroom;
538 initExtBuffer(newBuffer, newAllocatedCapacity, &info, &cap);
543 ext_.type = kExtAllocated;
544 ext_.buf = newBuffer;
545 ext_.sharedInfo = info;
546 data_ = newBuffer + newHeadroom;
547 // length_ is unchanged
550 void IOBuf::allocExtBuffer(uint32_t minCapacity,
552 SharedInfo** infoReturn,
553 uint32_t* capacityReturn) {
554 size_t mallocSize = goodExtBufferSize(minCapacity);
555 uint8_t* buf = static_cast<uint8_t*>(malloc(mallocSize));
556 if (UNLIKELY(buf == NULL)) {
557 throw std::bad_alloc();
559 initExtBuffer(buf, mallocSize, infoReturn, capacityReturn);
563 size_t IOBuf::goodExtBufferSize(uint32_t minCapacity) {
564 // Determine how much space we should allocate. We'll store the SharedInfo
565 // for the external buffer just after the buffer itself. (We store it just
566 // after the buffer rather than just before so that the code can still just
567 // use free(ext_.buf) to free the buffer.)
568 size_t minSize = static_cast<size_t>(minCapacity) + sizeof(SharedInfo);
569 // Add room for padding so that the SharedInfo will be aligned on an 8-byte
571 minSize = (minSize + 7) & ~7;
573 // Use goodMallocSize() to bump up the capacity to a decent size to request
574 // from malloc, so we can use all of the space that malloc will probably give
576 return goodMallocSize(minSize);
579 void IOBuf::initExtBuffer(uint8_t* buf, size_t mallocSize,
580 SharedInfo** infoReturn,
581 uint32_t* capacityReturn) {
582 // Find the SharedInfo storage at the end of the buffer
583 // and construct the SharedInfo.
584 uint8_t* infoStart = (buf + mallocSize) - sizeof(SharedInfo);
585 SharedInfo* sharedInfo = new(infoStart) SharedInfo;
587 size_t actualCapacity = infoStart - buf;
588 // On the unlikely possibility that the actual capacity is larger than can
589 // fit in a uint32_t after adding room for the refcount and calling
590 // goodMallocSize(), truncate downwards if necessary.
591 if (actualCapacity >= UINT32_MAX) {
592 *capacityReturn = UINT32_MAX;
594 *capacityReturn = actualCapacity;
597 *infoReturn = sharedInfo;