Line data Source code
1 : /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 : /* vim: set sw=2 ts=8 et ft=cpp : */
3 : /* This Source Code Form is subject to the terms of the Mozilla Public
4 : * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 : * You can obtain one at http://mozilla.org/MPL/2.0/. */
6 :
7 : #include "mozilla/Assertions.h"
8 : #include "mozilla/Logging.h"
9 : #include "mozilla/ShmemPool.h"
10 : #include "mozilla/Move.h"
11 :
12 : namespace mozilla {
13 :
14 0 : ShmemPool::ShmemPool(size_t aPoolSize)
15 : : mMutex("mozilla::ShmemPool"),
16 : mPoolFree(aPoolSize)
17 : #ifdef DEBUG
18 0 : ,mMaxPoolUse(0)
19 : #endif
20 : {
21 0 : mShmemPool.SetLength(aPoolSize);
22 0 : }
23 :
24 0 : mozilla::ShmemBuffer ShmemPool::GetIfAvailable(size_t aSize)
25 : {
26 0 : MutexAutoLock lock(mMutex);
27 :
28 : // Pool is empty, don't block caller.
29 0 : if (mPoolFree == 0) {
30 : // This isn't initialized, so will be understood as an error.
31 0 : return ShmemBuffer();
32 : }
33 :
34 0 : ShmemBuffer& res = mShmemPool[mPoolFree - 1];
35 :
36 0 : if (!res.mInitialized) {
37 0 : LOG(("No free preallocated Shmem"));
38 0 : return ShmemBuffer();
39 : }
40 :
41 0 : MOZ_ASSERT(res.mShmem.IsWritable(), "Pool in Shmem is not writable?");
42 :
43 0 : if (res.mShmem.Size<uint8_t>() < aSize) {
44 0 : LOG(("Free Shmem but not of the right size"));
45 0 : return ShmemBuffer();
46 : }
47 :
48 0 : mPoolFree--;
49 : #ifdef DEBUG
50 0 : size_t poolUse = mShmemPool.Length() - mPoolFree;
51 0 : if (poolUse > mMaxPoolUse) {
52 0 : mMaxPoolUse = poolUse;
53 0 : LOG(("Maximum ShmemPool use increased: %" PRIuSIZE " buffers", mMaxPoolUse));
54 : }
55 : #endif
56 0 : return Move(res);
57 : }
58 :
59 0 : void ShmemPool::Put(ShmemBuffer&& aShmem)
60 : {
61 0 : MutexAutoLock lock(mMutex);
62 0 : MOZ_ASSERT(mPoolFree < mShmemPool.Length());
63 0 : mShmemPool[mPoolFree] = Move(aShmem);
64 0 : mPoolFree++;
65 : #ifdef DEBUG
66 0 : size_t poolUse = mShmemPool.Length() - mPoolFree;
67 0 : if (poolUse > 0) {
68 0 : LOG_VERBOSE(("ShmemPool usage reduced to %" PRIuSIZE " buffers", poolUse));
69 : }
70 : #endif
71 0 : }
72 :
73 0 : ShmemPool::~ShmemPool()
74 : {
75 : #ifdef DEBUG
76 0 : for (size_t i = 0; i < mShmemPool.Length(); i++) {
77 0 : MOZ_ASSERT(!mShmemPool[i].Valid());
78 : }
79 : #endif
80 0 : }
81 :
82 : } // namespace mozilla
|