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