2 * (c) 2009 Alexander Warg <warg@os.inf.tu-dresden.de>
3 * economic rights: Technische Universität Dresden (Germany)
5 * This file is part of TUD:OS and distributed under the terms of the
6 * GNU General Public License 2.
7 * Please see the COPYING-GPL-2 file for details.
22 { GC_register_finalizer_ignore_self(GC_base(this), 0, 0, 0, 0); }
24 static void GC_CALLBACK finalizer(void *obj, void *displ)
25 { reinterpret_cast<Finalized*>((char *)obj + (ptrdiff_t)displ)->~Finalized(); }
29 void *base = GC_base((void*)this);
32 GC_register_finalizer_ignore_self(base, finalizer, (void *)((char *)this - (char *)base), 0, 0);
40 explicit Quota(size_t limit) : _limit(limit), _used(0) {}
43 if (_limit && (s > _limit))
46 if (_limit && (_used > _limit - s))
48 GC_gcollect_and_unmap();
49 if (_used > _limit - s)
54 //printf("Q: alloc(%zx) -> %zx\n", s, _used);
61 //printf("Q: free(%zx) -> %zx\n", s, _used);
64 size_t limit() const { return _limit; }
65 size_t used() const { return _used; }
77 Quota_guard(Quota *q, size_t amount) : q(q), amount(amount)
79 if (!q->alloc(amount))
80 throw L4::Out_of_memory();
94 template< typename T >
102 namespace Q_object_tr {
103 template< typename T, bool B >
107 class Q_object : public Finalized
110 Quota *quota() const { return _quota; }
113 template< typename T, bool B >
114 friend class Q_object_tr::Qtr;
118 namespace Q_object_tr {
119 template< typename T, bool B >
122 struct Obj : public T
126 static Quota *quota(T *o) { return static_cast<Obj*>(o)->_q; }
127 static void quota(T *o, Quota *q) { static_cast<Obj*>(o)->_q = q; }
130 template< typename T >
134 static Quota *quota(T *o) { return static_cast<Q_object*>(o)->_quota; }
135 static void quota(T *o, Quota *q) { static_cast<Q_object*>(o)->_quota = q; }
139 template< typename Type, template <typename T > class Alloc >
143 static int __is_qobject__(Q_object *) { return 0; }
144 static char __is_qobject__(...) { return 0; }
145 typedef Q_object_tr::Qtr<Type, sizeof(__is_qobject__((Type*)0)) == sizeof(int)> Qtr;
146 typedef typename Qtr::Obj Obj;
147 typedef Alloc<Obj> Allocator;
150 typedef Type Obj_type;
152 Obj_type *alloc(Quota *quota, size_t extra = 0)
154 Quota_guard g(quota, sizeof(Obj) + extra);
156 Obj *o = _alloc.alloc();
159 Qtr::quota(o, quota);
164 throw L4::Out_of_memory();
167 void free(Obj_type *o) throw()
169 Obj *io = static_cast<Obj*>(o);
170 Qtr::quota(o)->free(sizeof(Obj));
179 template< typename Alloc >
180 struct Q_alloc_static
182 static void *_alloc(Quota *q, unsigned long size, unsigned long align)
184 Quota_guard g(q, size);
185 return g.done(Alloc::_alloc(size, align));
188 static void _free(Quota *q, void *p, unsigned long size) throw()
190 Alloc::_free(p, size);