Convert from jemalloc's obsolete *allocm() to *allocx().
[folly.git] / folly / io / IOBuf.cpp
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #define __STDC_LIMIT_MACROS
18
19 #include <folly/io/IOBuf.h>
20
21 #include <folly/Conv.h>
22 #include <folly/Likely.h>
23 #include <folly/Malloc.h>
24 #include <folly/Memory.h>
25 #include <folly/ScopeGuard.h>
26 #include <folly/SpookyHashV2.h>
27 #include <folly/io/Cursor.h>
28
29 #include <stdexcept>
30 #include <assert.h>
31 #include <stdint.h>
32 #include <stdlib.h>
33
34 using std::unique_ptr;
35
36 namespace {
37
38 enum : uint16_t {
39   kHeapMagic = 0xa5a5,
40   // This memory segment contains an IOBuf that is still in use
41   kIOBufInUse = 0x01,
42   // This memory segment contains buffer data that is still in use
43   kDataInUse = 0x02,
44 };
45
46 enum : uint64_t {
47   // When create() is called for buffers less than kDefaultCombinedBufSize,
48   // we allocate a single combined memory segment for the IOBuf and the data
49   // together.  See the comments for createCombined()/createSeparate() for more
50   // details.
51   //
52   // (The size of 1k is largely just a guess here.  We could could probably do
53   // benchmarks of real applications to see if adjusting this number makes a
54   // difference.  Callers that know their exact use case can also explicitly
55   // call createCombined() or createSeparate().)
56   kDefaultCombinedBufSize = 1024
57 };
58
59 // Helper function for IOBuf::takeOwnership()
60 void takeOwnershipError(bool freeOnError, void* buf,
61                         folly::IOBuf::FreeFunction freeFn,
62                         void* userData) {
63   if (!freeOnError) {
64     return;
65   }
66   if (!freeFn) {
67     free(buf);
68     return;
69   }
70   try {
71     freeFn(buf, userData);
72   } catch (...) {
73     // The user's free function is not allowed to throw.
74     // (We are already in the middle of throwing an exception, so
75     // we cannot let this exception go unhandled.)
76     abort();
77   }
78 }
79
80 } // unnamed namespace
81
82 namespace folly {
83
84 struct IOBuf::HeapPrefix {
85   HeapPrefix(uint16_t flg)
86     : magic(kHeapMagic),
87       flags(flg) {}
88   ~HeapPrefix() {
89     // Reset magic to 0 on destruction.  This is solely for debugging purposes
90     // to help catch bugs where someone tries to use HeapStorage after it has
91     // been deleted.
92     magic = 0;
93   }
94
95   uint16_t magic;
96   std::atomic<uint16_t> flags;
97 };
98
99 struct IOBuf::HeapStorage {
100   HeapPrefix prefix;
101   // The IOBuf is last in the HeapStorage object.
102   // This way operator new will work even if allocating a subclass of IOBuf
103   // that requires more space.
104   folly::IOBuf buf;
105 };
106
107 struct IOBuf::HeapFullStorage {
108   // Make sure jemalloc allocates from the 64-byte class.  Putting this here
109   // because HeapStorage is private so it can't be at namespace level.
110   static_assert(sizeof(HeapStorage) <= 64,
111                 "IOBuf may not grow over 56 bytes!");
112
113   HeapStorage hs;
114   SharedInfo shared;
115   MaxAlign align;
116 };
117
118 IOBuf::SharedInfo::SharedInfo()
119   : freeFn(nullptr),
120     userData(nullptr) {
121   // Use relaxed memory ordering here.  Since we are creating a new SharedInfo,
122   // no other threads should be referring to it yet.
123   refcount.store(1, std::memory_order_relaxed);
124 }
125
126 IOBuf::SharedInfo::SharedInfo(FreeFunction fn, void* arg)
127   : freeFn(fn),
128     userData(arg) {
129   // Use relaxed memory ordering here.  Since we are creating a new SharedInfo,
130   // no other threads should be referring to it yet.
131   refcount.store(1, std::memory_order_relaxed);
132 }
133
134 void* IOBuf::operator new(size_t size) {
135   size_t fullSize = offsetof(HeapStorage, buf) + size;
136   auto* storage = static_cast<HeapStorage*>(malloc(fullSize));
137   // operator new is not allowed to return NULL
138   if (UNLIKELY(storage == nullptr)) {
139     throw std::bad_alloc();
140   }
141
142   new (&storage->prefix) HeapPrefix(kIOBufInUse);
143   return &(storage->buf);
144 }
145
146 void* IOBuf::operator new(size_t size, void* ptr) {
147   return ptr;
148 }
149
150 void IOBuf::operator delete(void* ptr) {
151   auto* storageAddr = static_cast<uint8_t*>(ptr) - offsetof(HeapStorage, buf);
152   auto* storage = reinterpret_cast<HeapStorage*>(storageAddr);
153   releaseStorage(storage, kIOBufInUse);
154 }
155
156 void IOBuf::releaseStorage(HeapStorage* storage, uint16_t freeFlags) {
157   CHECK_EQ(storage->prefix.magic, static_cast<uint16_t>(kHeapMagic));
158
159   // Use relaxed memory order here.  If we are unlucky and happen to get
160   // out-of-date data the compare_exchange_weak() call below will catch
161   // it and load new data with memory_order_acq_rel.
162   auto flags = storage->prefix.flags.load(std::memory_order_acquire);
163   DCHECK_EQ((flags & freeFlags), freeFlags);
164
165   while (true) {
166     uint16_t newFlags = (flags & ~freeFlags);
167     if (newFlags == 0) {
168       // The storage space is now unused.  Free it.
169       storage->prefix.HeapPrefix::~HeapPrefix();
170       free(storage);
171       return;
172     }
173
174     // This storage segment still contains portions that are in use.
175     // Just clear the flags specified in freeFlags for now.
176     auto ret = storage->prefix.flags.compare_exchange_weak(
177         flags, newFlags, std::memory_order_acq_rel);
178     if (ret) {
179       // We successfully updated the flags.
180       return;
181     }
182
183     // We failed to update the flags.  Some other thread probably updated them
184     // and cleared some of the other bits.  Continue around the loop to see if
185     // we are the last user now, or if we need to try updating the flags again.
186   }
187 }
188
189 void IOBuf::freeInternalBuf(void* buf, void* userData) {
190   auto* storage = static_cast<HeapStorage*>(userData);
191   releaseStorage(storage, kDataInUse);
192 }
193
194 IOBuf::IOBuf(CreateOp, uint64_t capacity)
195   : next_(this),
196     prev_(this),
197     data_(nullptr),
198     length_(0),
199     flagsAndSharedInfo_(0) {
200   SharedInfo* info;
201   allocExtBuffer(capacity, &buf_, &info, &capacity_);
202   setSharedInfo(info);
203   data_ = buf_;
204 }
205
206 IOBuf::IOBuf(CopyBufferOp op, const void* buf, uint64_t size,
207              uint64_t headroom, uint64_t minTailroom)
208   : IOBuf(CREATE, headroom + size + minTailroom) {
209   advance(headroom);
210   memcpy(writableData(), buf, size);
211   append(size);
212 }
213
214 IOBuf::IOBuf(CopyBufferOp op, ByteRange br,
215              uint64_t headroom, uint64_t minTailroom)
216   : IOBuf(op, br.data(), br.size(), headroom, minTailroom) {
217 }
218
219 unique_ptr<IOBuf> IOBuf::create(uint64_t capacity) {
220   // For smaller-sized buffers, allocate the IOBuf, SharedInfo, and the buffer
221   // all with a single allocation.
222   //
223   // We don't do this for larger buffers since it can be wasteful if the user
224   // needs to reallocate the buffer but keeps using the same IOBuf object.
225   // In this case we can't free the data space until the IOBuf is also
226   // destroyed.  Callers can explicitly call createCombined() or
227   // createSeparate() if they know their use case better, and know if they are
228   // likely to reallocate the buffer later.
229   if (capacity <= kDefaultCombinedBufSize) {
230     return createCombined(capacity);
231   }
232   return createSeparate(capacity);
233 }
234
235 unique_ptr<IOBuf> IOBuf::createCombined(uint64_t capacity) {
236   // To save a memory allocation, allocate space for the IOBuf object, the
237   // SharedInfo struct, and the data itself all with a single call to malloc().
238   size_t requiredStorage = offsetof(HeapFullStorage, align) + capacity;
239   size_t mallocSize = goodMallocSize(requiredStorage);
240   auto* storage = static_cast<HeapFullStorage*>(malloc(mallocSize));
241
242   new (&storage->hs.prefix) HeapPrefix(kIOBufInUse | kDataInUse);
243   new (&storage->shared) SharedInfo(freeInternalBuf, storage);
244
245   uint8_t* bufAddr = reinterpret_cast<uint8_t*>(&storage->align);
246   uint8_t* storageEnd = reinterpret_cast<uint8_t*>(storage) + mallocSize;
247   size_t actualCapacity = storageEnd - bufAddr;
248   unique_ptr<IOBuf> ret(new (&storage->hs.buf) IOBuf(
249         InternalConstructor(), packFlagsAndSharedInfo(0, &storage->shared),
250         bufAddr, actualCapacity, bufAddr, 0));
251   return ret;
252 }
253
254 unique_ptr<IOBuf> IOBuf::createSeparate(uint64_t capacity) {
255   return make_unique<IOBuf>(CREATE, capacity);
256 }
257
258 unique_ptr<IOBuf> IOBuf::createChain(
259     size_t totalCapacity, uint64_t maxBufCapacity) {
260   unique_ptr<IOBuf> out = create(
261       std::min(totalCapacity, size_t(maxBufCapacity)));
262   size_t allocatedCapacity = out->capacity();
263
264   while (allocatedCapacity < totalCapacity) {
265     unique_ptr<IOBuf> newBuf = create(
266         std::min(totalCapacity - allocatedCapacity, size_t(maxBufCapacity)));
267     allocatedCapacity += newBuf->capacity();
268     out->prependChain(std::move(newBuf));
269   }
270
271   return out;
272 }
273
274 IOBuf::IOBuf(TakeOwnershipOp, void* buf, uint64_t capacity, uint64_t length,
275              FreeFunction freeFn, void* userData,
276              bool freeOnError)
277   : next_(this),
278     prev_(this),
279     data_(static_cast<uint8_t*>(buf)),
280     buf_(static_cast<uint8_t*>(buf)),
281     length_(length),
282     capacity_(capacity),
283     flagsAndSharedInfo_(packFlagsAndSharedInfo(kFlagFreeSharedInfo, nullptr)) {
284   try {
285     setSharedInfo(new SharedInfo(freeFn, userData));
286   } catch (...) {
287     takeOwnershipError(freeOnError, buf, freeFn, userData);
288     throw;
289   }
290 }
291
292 unique_ptr<IOBuf> IOBuf::takeOwnership(void* buf, uint64_t capacity,
293                                        uint64_t length,
294                                        FreeFunction freeFn,
295                                        void* userData,
296                                        bool freeOnError) {
297   try {
298     // TODO: We could allocate the IOBuf object and SharedInfo all in a single
299     // memory allocation.  We could use the existing HeapStorage class, and
300     // define a new kSharedInfoInUse flag.  We could change our code to call
301     // releaseStorage(kFlagFreeSharedInfo) when this kFlagFreeSharedInfo,
302     // rather than directly calling delete.
303     //
304     // Note that we always pass freeOnError as false to the constructor.
305     // If the constructor throws we'll handle it below.  (We have to handle
306     // allocation failures from make_unique too.)
307     return make_unique<IOBuf>(TAKE_OWNERSHIP, buf, capacity, length,
308                               freeFn, userData, false);
309   } catch (...) {
310     takeOwnershipError(freeOnError, buf, freeFn, userData);
311     throw;
312   }
313 }
314
315 IOBuf::IOBuf(WrapBufferOp, const void* buf, uint64_t capacity)
316   : IOBuf(InternalConstructor(), 0,
317           // We cast away the const-ness of the buffer here.
318           // This is okay since IOBuf users must use unshare() to create a copy
319           // of this buffer before writing to the buffer.
320           static_cast<uint8_t*>(const_cast<void*>(buf)), capacity,
321           static_cast<uint8_t*>(const_cast<void*>(buf)), capacity) {
322 }
323
324 IOBuf::IOBuf(WrapBufferOp op, ByteRange br)
325   : IOBuf(op, br.data(), br.size()) {
326 }
327
328 unique_ptr<IOBuf> IOBuf::wrapBuffer(const void* buf, uint64_t capacity) {
329   return make_unique<IOBuf>(WRAP_BUFFER, buf, capacity);
330 }
331
332 IOBuf::IOBuf() noexcept {
333 }
334
335 IOBuf::IOBuf(IOBuf&& other) noexcept {
336   *this = std::move(other);
337 }
338
339 IOBuf::IOBuf(InternalConstructor,
340              uintptr_t flagsAndSharedInfo,
341              uint8_t* buf,
342              uint64_t capacity,
343              uint8_t* data,
344              uint64_t length)
345   : next_(this),
346     prev_(this),
347     data_(data),
348     buf_(buf),
349     length_(length),
350     capacity_(capacity),
351     flagsAndSharedInfo_(flagsAndSharedInfo) {
352   assert(data >= buf);
353   assert(data + length <= buf + capacity);
354 }
355
356 IOBuf::~IOBuf() {
357   // Destroying an IOBuf destroys the entire chain.
358   // Users of IOBuf should only explicitly delete the head of any chain.
359   // The other elements in the chain will be automatically destroyed.
360   while (next_ != this) {
361     // Since unlink() returns unique_ptr() and we don't store it,
362     // it will automatically delete the unlinked element.
363     (void)next_->unlink();
364   }
365
366   decrementRefcount();
367 }
368
369 IOBuf& IOBuf::operator=(IOBuf&& other) noexcept {
370   if (this == &other) {
371     return *this;
372   }
373
374   // If we are part of a chain, delete the rest of the chain.
375   while (next_ != this) {
376     // Since unlink() returns unique_ptr() and we don't store it,
377     // it will automatically delete the unlinked element.
378     (void)next_->unlink();
379   }
380
381   // Decrement our refcount on the current buffer
382   decrementRefcount();
383
384   // Take ownership of the other buffer's data
385   data_ = other.data_;
386   buf_ = other.buf_;
387   length_ = other.length_;
388   capacity_ = other.capacity_;
389   flagsAndSharedInfo_ = other.flagsAndSharedInfo_;
390   // Reset other so it is a clean state to be destroyed.
391   other.data_ = nullptr;
392   other.buf_ = nullptr;
393   other.length_ = 0;
394   other.capacity_ = 0;
395   other.flagsAndSharedInfo_ = 0;
396
397   // If other was part of the chain, assume ownership of the rest of its chain.
398   // (It's only valid to perform move assignment on the head of a chain.)
399   if (other.next_ != &other) {
400     next_ = other.next_;
401     next_->prev_ = this;
402     other.next_ = &other;
403
404     prev_ = other.prev_;
405     prev_->next_ = this;
406     other.prev_ = &other;
407   }
408
409   // Sanity check to make sure that other is in a valid state to be destroyed.
410   DCHECK_EQ(other.prev_, &other);
411   DCHECK_EQ(other.next_, &other);
412
413   return *this;
414 }
415
416 bool IOBuf::empty() const {
417   const IOBuf* current = this;
418   do {
419     if (current->length() != 0) {
420       return false;
421     }
422     current = current->next_;
423   } while (current != this);
424   return true;
425 }
426
427 size_t IOBuf::countChainElements() const {
428   size_t numElements = 1;
429   for (IOBuf* current = next_; current != this; current = current->next_) {
430     ++numElements;
431   }
432   return numElements;
433 }
434
435 uint64_t IOBuf::computeChainDataLength() const {
436   uint64_t fullLength = length_;
437   for (IOBuf* current = next_; current != this; current = current->next_) {
438     fullLength += current->length_;
439   }
440   return fullLength;
441 }
442
443 void IOBuf::prependChain(unique_ptr<IOBuf>&& iobuf) {
444   // Take ownership of the specified IOBuf
445   IOBuf* other = iobuf.release();
446
447   // Remember the pointer to the tail of the other chain
448   IOBuf* otherTail = other->prev_;
449
450   // Hook up prev_->next_ to point at the start of the other chain,
451   // and other->prev_ to point at prev_
452   prev_->next_ = other;
453   other->prev_ = prev_;
454
455   // Hook up otherTail->next_ to point at us,
456   // and prev_ to point back at otherTail,
457   otherTail->next_ = this;
458   prev_ = otherTail;
459 }
460
461 unique_ptr<IOBuf> IOBuf::clone() const {
462   unique_ptr<IOBuf> ret = make_unique<IOBuf>();
463   cloneInto(*ret);
464   return ret;
465 }
466
467 unique_ptr<IOBuf> IOBuf::cloneOne() const {
468   unique_ptr<IOBuf> ret = make_unique<IOBuf>();
469   cloneOneInto(*ret);
470   return ret;
471 }
472
473 void IOBuf::cloneInto(IOBuf& other) const {
474   IOBuf tmp;
475   cloneOneInto(tmp);
476
477   for (IOBuf* current = next_; current != this; current = current->next_) {
478     tmp.prependChain(current->cloneOne());
479   }
480
481   other = std::move(tmp);
482 }
483
484 void IOBuf::cloneOneInto(IOBuf& other) const {
485   SharedInfo* info = sharedInfo();
486   if (info) {
487     setFlags(kFlagMaybeShared);
488   }
489   other = IOBuf(InternalConstructor(),
490                 flagsAndSharedInfo_, buf_, capacity_,
491                 data_, length_);
492   if (info) {
493     info->refcount.fetch_add(1, std::memory_order_acq_rel);
494   }
495 }
496
497 void IOBuf::unshareOneSlow() {
498   // Allocate a new buffer for the data
499   uint8_t* buf;
500   SharedInfo* sharedInfo;
501   uint64_t actualCapacity;
502   allocExtBuffer(capacity_, &buf, &sharedInfo, &actualCapacity);
503
504   // Copy the data
505   // Maintain the same amount of headroom.  Since we maintained the same
506   // minimum capacity we also maintain at least the same amount of tailroom.
507   uint64_t headlen = headroom();
508   memcpy(buf + headlen, data_, length_);
509
510   // Release our reference on the old buffer
511   decrementRefcount();
512   // Make sure kFlagMaybeShared and kFlagFreeSharedInfo are all cleared.
513   setFlagsAndSharedInfo(0, sharedInfo);
514
515   // Update the buffer pointers to point to the new buffer
516   data_ = buf + headlen;
517   buf_ = buf;
518 }
519
520 void IOBuf::unshareChained() {
521   // unshareChained() should only be called if we are part of a chain of
522   // multiple IOBufs.  The caller should have already verified this.
523   assert(isChained());
524
525   IOBuf* current = this;
526   while (true) {
527     if (current->isSharedOne()) {
528       // we have to unshare
529       break;
530     }
531
532     current = current->next_;
533     if (current == this) {
534       // None of the IOBufs in the chain are shared,
535       // so return without doing anything
536       return;
537     }
538   }
539
540   // We have to unshare.  Let coalesceSlow() do the work.
541   coalesceSlow();
542 }
543
544 void IOBuf::coalesceSlow() {
545   // coalesceSlow() should only be called if we are part of a chain of multiple
546   // IOBufs.  The caller should have already verified this.
547   DCHECK(isChained());
548
549   // Compute the length of the entire chain
550   uint64_t newLength = 0;
551   IOBuf* end = this;
552   do {
553     newLength += end->length_;
554     end = end->next_;
555   } while (end != this);
556
557   coalesceAndReallocate(newLength, end);
558   // We should be only element left in the chain now
559   DCHECK(!isChained());
560 }
561
562 void IOBuf::coalesceSlow(size_t maxLength) {
563   // coalesceSlow() should only be called if we are part of a chain of multiple
564   // IOBufs.  The caller should have already verified this.
565   DCHECK(isChained());
566   DCHECK_LT(length_, maxLength);
567
568   // Compute the length of the entire chain
569   uint64_t newLength = 0;
570   IOBuf* end = this;
571   while (true) {
572     newLength += end->length_;
573     end = end->next_;
574     if (newLength >= maxLength) {
575       break;
576     }
577     if (end == this) {
578       throw std::overflow_error("attempted to coalesce more data than "
579                                 "available");
580     }
581   }
582
583   coalesceAndReallocate(newLength, end);
584   // We should have the requested length now
585   DCHECK_GE(length_, maxLength);
586 }
587
588 void IOBuf::coalesceAndReallocate(size_t newHeadroom,
589                                   size_t newLength,
590                                   IOBuf* end,
591                                   size_t newTailroom) {
592   uint64_t newCapacity = newLength + newHeadroom + newTailroom;
593   if (newCapacity > UINT32_MAX) {
594     throw std::overflow_error("IOBuf chain too large to coalesce");
595   }
596
597   // Allocate space for the coalesced buffer.
598   // We always convert to an external buffer, even if we happened to be an
599   // internal buffer before.
600   uint8_t* newBuf;
601   SharedInfo* newInfo;
602   uint64_t actualCapacity;
603   allocExtBuffer(newCapacity, &newBuf, &newInfo, &actualCapacity);
604
605   // Copy the data into the new buffer
606   uint8_t* newData = newBuf + newHeadroom;
607   uint8_t* p = newData;
608   IOBuf* current = this;
609   size_t remaining = newLength;
610   do {
611     assert(current->length_ <= remaining);
612     remaining -= current->length_;
613     memcpy(p, current->data_, current->length_);
614     p += current->length_;
615     current = current->next_;
616   } while (current != end);
617   assert(remaining == 0);
618
619   // Point at the new buffer
620   decrementRefcount();
621
622   // Make sure kFlagMaybeShared and kFlagFreeSharedInfo are all cleared.
623   setFlagsAndSharedInfo(0, newInfo);
624
625   capacity_ = actualCapacity;
626   buf_ = newBuf;
627   data_ = newData;
628   length_ = newLength;
629
630   // Separate from the rest of our chain.
631   // Since we don't store the unique_ptr returned by separateChain(),
632   // this will immediately delete the returned subchain.
633   if (isChained()) {
634     (void)separateChain(next_, current->prev_);
635   }
636 }
637
638 void IOBuf::decrementRefcount() {
639   // Externally owned buffers don't have a SharedInfo object and aren't managed
640   // by the reference count
641   SharedInfo* info = sharedInfo();
642   if (!info) {
643     return;
644   }
645
646   // Decrement the refcount
647   uint32_t newcnt = info->refcount.fetch_sub(
648       1, std::memory_order_acq_rel);
649   // Note that fetch_sub() returns the value before we decremented.
650   // If it is 1, we were the only remaining user; if it is greater there are
651   // still other users.
652   if (newcnt > 1) {
653     return;
654   }
655
656   // We were the last user.  Free the buffer
657   freeExtBuffer();
658
659   // Free the SharedInfo if it was allocated separately.
660   //
661   // This is only used by takeOwnership().
662   //
663   // To avoid this special case handling in decrementRefcount(), we could have
664   // takeOwnership() set a custom freeFn() that calls the user's free function
665   // then frees the SharedInfo object.  (This would require that
666   // takeOwnership() store the user's free function with its allocated
667   // SharedInfo object.)  However, handling this specially with a flag seems
668   // like it shouldn't be problematic.
669   if (flags() & kFlagFreeSharedInfo) {
670     delete sharedInfo();
671   }
672 }
673
674 void IOBuf::reserveSlow(uint64_t minHeadroom, uint64_t minTailroom) {
675   size_t newCapacity = (size_t)length_ + minHeadroom + minTailroom;
676   DCHECK_LT(newCapacity, UINT32_MAX);
677
678   // reserveSlow() is dangerous if anyone else is sharing the buffer, as we may
679   // reallocate and free the original buffer.  It should only ever be called if
680   // we are the only user of the buffer.
681   DCHECK(!isSharedOne());
682
683   // We'll need to reallocate the buffer.
684   // There are a few options.
685   // - If we have enough total room, move the data around in the buffer
686   //   and adjust the data_ pointer.
687   // - If we're using an internal buffer, we'll switch to an external
688   //   buffer with enough headroom and tailroom.
689   // - If we have enough headroom (headroom() >= minHeadroom) but not too much
690   //   (so we don't waste memory), we can try one of two things, depending on
691   //   whether we use jemalloc or not:
692   //   - If using jemalloc, we can try to expand in place, avoiding a memcpy()
693   //   - If not using jemalloc and we don't have too much to copy,
694   //     we'll use realloc() (note that realloc might have to copy
695   //     headroom + data + tailroom, see smartRealloc in folly/Malloc.h)
696   // - Otherwise, bite the bullet and reallocate.
697   if (headroom() + tailroom() >= minHeadroom + minTailroom) {
698     uint8_t* newData = writableBuffer() + minHeadroom;
699     memmove(newData, data_, length_);
700     data_ = newData;
701     return;
702   }
703
704   size_t newAllocatedCapacity = goodExtBufferSize(newCapacity);
705   uint8_t* newBuffer = nullptr;
706   uint64_t newHeadroom = 0;
707   uint64_t oldHeadroom = headroom();
708
709   // If we have a buffer allocated with malloc and we just need more tailroom,
710   // try to use realloc()/xallocx() to grow the buffer in place.
711   SharedInfo* info = sharedInfo();
712   if (info && (info->freeFn == nullptr) && length_ != 0 &&
713       oldHeadroom >= minHeadroom) {
714     if (usingJEMalloc()) {
715       size_t headSlack = oldHeadroom - minHeadroom;
716       // We assume that tailroom is more useful and more important than
717       // headroom (not least because realloc / xallocx allow us to grow the
718       // buffer at the tail, but not at the head)  So, if we have more headroom
719       // than we need, we consider that "wasted".  We arbitrarily define "too
720       // much" headroom to be 25% of the capacity.
721       if (headSlack * 4 <= newCapacity) {
722         size_t allocatedCapacity = capacity() + sizeof(SharedInfo);
723         void* p = buf_;
724         if (allocatedCapacity >= jemallocMinInPlaceExpandable) {
725           if (xallocx(p, newAllocatedCapacity, 0, 0) == newAllocatedCapacity) {
726             newBuffer = static_cast<uint8_t*>(p);
727             newHeadroom = oldHeadroom;
728             newAllocatedCapacity = newAllocatedCapacity;
729           }
730           // if xallocx failed, do nothing, fall back to malloc/memcpy/free
731         }
732       }
733     } else {  // Not using jemalloc
734       size_t copySlack = capacity() - length_;
735       if (copySlack * 2 <= length_) {
736         void* p = realloc(buf_, newAllocatedCapacity);
737         if (UNLIKELY(p == nullptr)) {
738           throw std::bad_alloc();
739         }
740         newBuffer = static_cast<uint8_t*>(p);
741         newHeadroom = oldHeadroom;
742       }
743     }
744   }
745
746   // None of the previous reallocation strategies worked (or we're using
747   // an internal buffer).  malloc/copy/free.
748   if (newBuffer == nullptr) {
749     void* p = malloc(newAllocatedCapacity);
750     if (UNLIKELY(p == nullptr)) {
751       throw std::bad_alloc();
752     }
753     newBuffer = static_cast<uint8_t*>(p);
754     memcpy(newBuffer + minHeadroom, data_, length_);
755     if (sharedInfo()) {
756       freeExtBuffer();
757     }
758     newHeadroom = minHeadroom;
759   }
760
761   uint64_t cap;
762   initExtBuffer(newBuffer, newAllocatedCapacity, &info, &cap);
763
764   if (flags() & kFlagFreeSharedInfo) {
765     delete sharedInfo();
766   }
767
768   setFlagsAndSharedInfo(0, info);
769   capacity_ = cap;
770   buf_ = newBuffer;
771   data_ = newBuffer + newHeadroom;
772   // length_ is unchanged
773 }
774
775 void IOBuf::freeExtBuffer() {
776   SharedInfo* info = sharedInfo();
777   DCHECK(info);
778
779   if (info->freeFn) {
780     try {
781       info->freeFn(buf_, info->userData);
782     } catch (...) {
783       // The user's free function should never throw.  Otherwise we might
784       // throw from the IOBuf destructor.  Other code paths like coalesce()
785       // also assume that decrementRefcount() cannot throw.
786       abort();
787     }
788   } else {
789     free(buf_);
790   }
791 }
792
793 void IOBuf::allocExtBuffer(uint64_t minCapacity,
794                            uint8_t** bufReturn,
795                            SharedInfo** infoReturn,
796                            uint64_t* capacityReturn) {
797   size_t mallocSize = goodExtBufferSize(minCapacity);
798   uint8_t* buf = static_cast<uint8_t*>(malloc(mallocSize));
799   if (UNLIKELY(buf == nullptr)) {
800     throw std::bad_alloc();
801   }
802   initExtBuffer(buf, mallocSize, infoReturn, capacityReturn);
803   *bufReturn = buf;
804 }
805
806 size_t IOBuf::goodExtBufferSize(uint64_t minCapacity) {
807   // Determine how much space we should allocate.  We'll store the SharedInfo
808   // for the external buffer just after the buffer itself.  (We store it just
809   // after the buffer rather than just before so that the code can still just
810   // use free(buf_) to free the buffer.)
811   size_t minSize = static_cast<size_t>(minCapacity) + sizeof(SharedInfo);
812   // Add room for padding so that the SharedInfo will be aligned on an 8-byte
813   // boundary.
814   minSize = (minSize + 7) & ~7;
815
816   // Use goodMallocSize() to bump up the capacity to a decent size to request
817   // from malloc, so we can use all of the space that malloc will probably give
818   // us anyway.
819   return goodMallocSize(minSize);
820 }
821
822 void IOBuf::initExtBuffer(uint8_t* buf, size_t mallocSize,
823                           SharedInfo** infoReturn,
824                           uint64_t* capacityReturn) {
825   // Find the SharedInfo storage at the end of the buffer
826   // and construct the SharedInfo.
827   uint8_t* infoStart = (buf + mallocSize) - sizeof(SharedInfo);
828   SharedInfo* sharedInfo = new(infoStart) SharedInfo;
829
830   *capacityReturn = infoStart - buf;
831   *infoReturn = sharedInfo;
832 }
833
834 fbstring IOBuf::moveToFbString() {
835   // malloc-allocated buffers are just fine, everything else needs
836   // to be turned into one.
837   if (!sharedInfo() ||         // user owned, not ours to give up
838       sharedInfo()->freeFn ||  // not malloc()-ed
839       headroom() != 0 ||       // malloc()-ed block doesn't start at beginning
840       tailroom() == 0 ||       // no room for NUL terminator
841       isShared() ||            // shared
842       isChained()) {           // chained
843     // We might as well get rid of all head and tailroom if we're going
844     // to reallocate; we need 1 byte for NUL terminator.
845     coalesceAndReallocate(0, computeChainDataLength(), this, 1);
846   }
847
848   // Ensure NUL terminated
849   *writableTail() = 0;
850   fbstring str(reinterpret_cast<char*>(writableData()),
851                length(),  capacity(),
852                AcquireMallocatedString());
853
854   if (flags() & kFlagFreeSharedInfo) {
855     delete sharedInfo();
856   }
857
858   // Reset to a state where we can be deleted cleanly
859   flagsAndSharedInfo_ = 0;
860   buf_ = nullptr;
861   clear();
862   return str;
863 }
864
865 IOBuf::Iterator IOBuf::cbegin() const {
866   return Iterator(this, this);
867 }
868
869 IOBuf::Iterator IOBuf::cend() const {
870   return Iterator(nullptr, nullptr);
871 }
872
873 folly::fbvector<struct iovec> IOBuf::getIov() const {
874   folly::fbvector<struct iovec> iov;
875   iov.reserve(countChainElements());
876   IOBuf const* p = this;
877   do {
878     // some code can get confused by empty iovs, so skip them
879     if (p->length() > 0) {
880       iov.push_back({(void*)p->data(), folly::to<size_t>(p->length())});
881     }
882     p = p->next();
883   } while (p != this);
884   return iov;
885 }
886
887 size_t IOBufHash::operator()(const IOBuf& buf) const {
888   folly::hash::SpookyHashV2 hasher;
889   hasher.Init(0, 0);
890   io::Cursor cursor(&buf);
891   for (;;) {
892     auto p = cursor.peek();
893     if (p.second == 0) {
894       break;
895     }
896     hasher.Update(p.first, p.second);
897     cursor.skip(p.second);
898   }
899   uint64_t h1;
900   uint64_t h2;
901   hasher.Final(&h1, &h2);
902   return h1;
903 }
904
905 bool IOBufEqual::operator()(const IOBuf& a, const IOBuf& b) const {
906   io::Cursor ca(&a);
907   io::Cursor cb(&b);
908   for (;;) {
909     auto pa = ca.peek();
910     auto pb = cb.peek();
911     if (pa.second == 0 && pb.second == 0) {
912       return true;
913     } else if (pa.second == 0 || pb.second == 0) {
914       return false;
915     }
916     size_t n = std::min(pa.second, pb.second);
917     DCHECK_GT(n, 0);
918     if (memcmp(pa.first, pb.first, n)) {
919       return false;
920     }
921     ca.skip(n);
922     cb.skip(n);
923   }
924 }
925
926 } // folly