1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
.. highlight:: none


.. index::
   pair: buffers; design

.. _design-buffer:


Allocation buffers and allocation points
========================================

.. mps:prefix:: design.mps.buffer


Introduction
------------

:mps:tag:`scope` This is the design of allocation buffers and allocation
points.

:mps:tag:`purpose` The purpose of this document is to record design
decisions made concerning allocation buffers and allocation points and
justify those decisions in terms of requirements.

:mps:tag:`readership` The document is intended for reading by any MPS
developer.


Glossary
--------

trapped

    :mps:tag:`def.trapped` The buffer is in a state such that the MPS gets
    to know about the next use of that buffer.


Source
------

:mps:tag:`source.mail` Much of the juicy stuff about buffers is only
floating around in mail discussions. You might like to try searching
the archives if you can't find what you want here.

.. note::

    Mail archives are only accessible to Ravenbrook staff. RHSK
    2006-06-09.

:mps:tag:`source.synchronize` For a discussion of the synchronization
issues, see `mail.richard.1995-05-19.17-10`_,
`mail.ptw.1995-05-19.19-15`_, and `mail.richard.1995-05-24.10-18`_.

.. _mail.richard.1995-05-19.17-10: https://info.ravenbrook.com/project/mps/mail/1995/05/19/17-10/0.txt
.. _mail.ptw.1995-05-19.19-15: https://info.ravenbrook.com/project/mps/mail/1995/05/19/19-15/0.txt
.. _mail.richard.1995-05-24.10-18: https://info.ravenbrook.com/project/mps/mail/1995/05/24/10-18/0.txt

.. note::

    I believe that the sequence for flip in PTW's message is
    incorrect. The operations should be in the other order. DRJ.

:mps:tag:`source.interface` For a description of the buffer interface in C
prototypes, see `mail.richard.1997-04-28.09-25`_.

.. _mail.richard.1997-04-28.09-25: https://info.ravenbrook.com/project/mps/mail/1997/04/28/09-25/0.txt

:mps:tag:`source.qa` Discussions with QA were useful in pinning down the
semantics and understanding of some obscure but important boundary
cases. See the thread with subject "notes on our allocation points
discussion" and messages `mail.richard.tucker.1997-05-12.09-45`_,
`mail.ptw.1997-05-12.12-46`_, `mail.richard.1997-05-12.13-15`_,
`mail.richard.1997-05-12.13-28`_, `mail.ptw.1997-05-13.15-15`_,
`mail.sheep.1997-05-14.11-52`_, `mail.rit.1997-05-15.09-19`_,
`mail.ptw.1997-05-15.21-22`_, `mail.ptw.1997-05-15.21-35`_,
`mail.rit.1997-05-16.08-02`_, `mail.rit.1997-05-16.08-42`_,
`mail.ptw.1997-05-16.12-36`_, `mail.ptw.1997-05-16.12-47`_,
`mail.richard.1997-05-19.15-46`_, `mail.richard.1997-05-19.15-56`_,
and `mail.ptw.1997-05-20.20-47`_.

.. _mail.richard.tucker.1997-05-12.09-45: https://info.ravenbrook.com/project/mps/mail/1997/05/12/09-45/0.txt
.. _mail.ptw.1997-05-12.12-46: https://info.ravenbrook.com/project/mps/mail/1997/05/12/12-46/1.txt
.. _mail.richard.1997-05-12.13-15: https://info.ravenbrook.com/project/mps/mail/1997/05/12/13-15/0.txt
.. _mail.richard.1997-05-12.13-28: https://info.ravenbrook.com/project/mps/mail/1997/05/12/13-28/0.txt
.. _mail.ptw.1997-05-13.15-15: https://info.ravenbrook.com/project/mps/mail/1997/05/13/15-15/0.txt
.. _mail.sheep.1997-05-14.11-52: https://info.ravenbrook.com/project/mps/mail/1997/05/14/11-52/0.txt
.. _mail.rit.1997-05-15.09-19: https://info.ravenbrook.com/project/mps/mail/1997/05/15/09-19/0.txt
.. _mail.ptw.1997-05-15.21-22: https://info.ravenbrook.com/project/mps/mail/1997/05/15/21-22/0.txt
.. _mail.ptw.1997-05-15.21-35: https://info.ravenbrook.com/project/mps/mail/1997/05/15/21-35/0.txt
.. _mail.rit.1997-05-16.08-02: https://info.ravenbrook.com/project/mps/mail/1997/05/16/08-02/0.txt
.. _mail.rit.1997-05-16.08-42: https://info.ravenbrook.com/project/mps/mail/1997/05/16/08-42/0.txt
.. _mail.ptw.1997-05-16.12-36: https://info.ravenbrook.com/project/mps/mail/1997/05/16/12-36/0.txt
.. _mail.ptw.1997-05-16.12-47: https://info.ravenbrook.com/project/mps/mail/1997/05/16/12-47/0.txt
.. _mail.richard.1997-05-19.15-46: https://info.ravenbrook.com/project/mps/mail/1997/05/19/15-46/0.txt
.. _mail.richard.1997-05-19.15-56: https://info.ravenbrook.com/project/mps/mail/1997/05/19/15-56/0.txt
.. _mail.ptw.1997-05-20.20-47: https://info.ravenbrook.com/project/mps/mail/1997/05/20/20-47/0.txt



Requirements
------------

:mps:tag:`req.fast` Allocation must be very fast.

:mps:tag:`req.thread-safe` Must run safely in a multi-threaded environment.

:mps:tag:`req.no-synch` Must avoid the use of thread-synchronization.
(:mps:ref:`.req.fast`)

:mps:tag:`req.manual` Support manual memory management.

:mps:tag:`req.exact` Support exact collectors.

:mps:tag:`req.ambig` Support ambiguous collectors.

:mps:tag:`req.count` Must record (approximately) the amount of allocation (in bytes).

.. note::

    Actually not a requirement any more, but once was put forward as a
    Dylan requirement. Bits of the code still reflect this
    requirement. See request.dylan.170554_.

.. _request.dylan.170554: https://info.ravenbrook.com/project/mps/import/2001-11-05/mmprevol/request/dylan/170554


Classes
-------

:mps:tag:`class.hierarchy` The :c:type:`Buffer` data structure is designed to be
subclassable (see design.mps.protocol_).

.. _design.mps.protocol: protocol.html

:mps:tag:`class.hierarchy.buffer` The basic buffer class (:c:type:`BufferClass`)
supports basic allocation-point buffering, and is appropriate for
those manual pools which don't use segments (:mps:ref:`.req.manual`). The
:c:type:`Buffer` class doesn't support reference ranks (that is, the buffers
have ``RankSetEMPTY``). Clients may use :c:type:`BufferClass` directly, or
create their own subclasses (see :mps:ref:`.subclassing`).

:mps:tag:`class.hierarchy.segbuf` Class :c:type:`SegBufClass` is also provided for
the use of pools which additionally need to associate buffers with
segments. :c:type:`SegBufClass` is a subclass of :c:type:`BufferClass`. Manual
pools may find it convenient to use :c:type:`SegBufClass`, but it is
primarily intended for automatic pools (:mps:ref:`.req.exact`, :mps:ref:`.req.ambig`).
An instance of :c:type:`SegBufClass` may be attached to a region of memory
that lies within a single segment. The segment is associated with the
buffer, and may be accessed with the :c:func:`BufferSeg()` function.
:c:type:`SegBufClass` also supports references at any rank set. Hence this
class or one of its subclasses should be used by all automatic pools
(with the possible exception of leaf pools). The rank sets of buffers
and the segments they are attached to must match. Clients may use
:c:type:`SegBufClass` directly, or create their own subclasses (see
:mps:ref:`.subclassing`).

:mps:tag:`class.hierarchy.rankbuf` Class :c:type:`RankBufClass` is also provided
as a subclass of :c:type:`SegBufClass`. The only way in which this differs
from its superclass is that the rankset of a :c:type:`RankBufClass` is set
during initialization to the singleton rank passed as an additional
parameter to :c:func:`BufferCreate()`. Instances of :c:type:`RankBufClass` are of
the same type as instances of :c:type:`SegBufClass`, that is, :c:type:`SegBuf`.
Clients may use :c:type:`RankBufClass` directly, or create their own
subclasses (see :mps:ref:`.subclassing`).

:mps:tag:`class.create` The buffer creation functions (:c:func:`BufferCreate()`
and :c:func:`BufferCreateV()`) take a ``class`` parameter, which determines
the class of buffer to be created.

:mps:tag:`class.choice` Pools which support buffered allocation should
specify a default class for buffers. This class will be used when a
buffer is created in the normal fashion by MPS clients (for example by
a call to :c:func:`mps_ap_create()`). Pools specify the default class by
means of the ``bufferClass`` field in the pool class object. This
should be a pointer to a function of type :c:type:`PoolBufferClassMethod`.
The normal class "Ensure" function (for example
:c:func:`EnsureBufferClass()`) has the appropriate type.

:mps:tag:`subclassing` Pools may create their own subclasses of the standard
buffer classes. This is sometimes useful if the pool needs to add an
extra field to the buffer. The convenience macro
:c:func:`DEFINE_BUFFER_CLASS()` may be used to define subclasses of buffer
classes. See design.mps.protocol.int.define-special_.

.. _design.mps.protocol.int.define-special: protocol.html#design.mps.protocol.int.define-special

:mps:tag:`replay` To work with the allocation replayer (see
design.mps.telemetry.replayer_), the buffer class has to emit an event
for each call to an external interface, containing all the parameters
passed by the user. If a new event type is required to carry this
information, the replayer (impl.c.eventrep) must then be extended to
recreate the call.

.. _design.mps.telemetry.replayer: telemetry.html#design.mps.telemetry.replayer

:mps:tag:`replay.pool-buffer` The replayer must also be updated if the
association of buffer class to pool or the buffer class hierarchy is
changed.

:mps:tag:`class.method` Buffer classes provide the following methods (these
should not be confused with the pool class methods related to the
buffer protocol, described in :mps:ref:`.method.create` and following
sections):

.. c:type:: Res (*BufferInitMethod)(Buffer buffer, Pool pool, ArgList args)

:mps:tag:`class.method.init` :c:func:`init()` is a class-specific initialization
method called from :c:func:`BufferInit()`. It receives the keyword arguments
passed to to :c:func:`BufferInit()`. Client-defined methods must call their
superclass method (via a next-method call) before performing any
class-specific behaviour. :mps:tag:`replay.init` The :c:func:`init()` method
should emit a ``BufferInit<foo>`` event (if there aren't any extra
parameters, ``<foo> = ""``).

.. c:type:: void (*BufferAttachMethod)(Buffer buffer, Addr base, Addr limit, Addr init, Size size)

:mps:tag:`class.method.attach` :c:func:`attach()` is a class-specific method
called whenever a buffer is attached to memory, via
:c:func:`BufferAttach()`. Client-defined methods must call their superclass
method (via a next-method call) before performing any class-specific
behaviour.

.. c:type:: void (*BufferDetachMethod)(Buffer buffer)

:mps:tag:`class.method.detach` :c:func:`detach()` is a class-specific method
called whenever a buffer is detached from memory, via
:c:func:`BufferDetach()`. Client-defined methods must call their superclass
method (via a next-method call) after performing any class-specific
behaviour.

.. c:type:: Seg (*BufferSegMethod)(Buffer buffer)

:mps:tag:`class.method.seg` :c:func:`seg()` is a class-specific accessor method
which returns the segment attached to a buffer (or :c:macro:`NULL` if there
isn't one). It is called from :c:func:`BufferSeg()`. Clients should not need
to define their own methods for this.

.. c:type:: RankSet (*BufferRankSetMethod)(Buffer buffer)

:mps:tag:`class.method.rankSet` :c:func:`rankSet()` is a class-specific accessor
method which returns the rank set of a buffer. It is called from
:c:func:`BufferRankSet()`. Clients should not need to define their own
methods for this.

.. c:type:: void (*BufferSetRankSetMethod)(Buffer buffer, RankSet rankSet)

:mps:tag:`class.method.setRankSet` :c:func:`setRankSet()` is a class-specific
setter method which sets the rank set of a buffer. It is called from
:c:func:`BufferSetRankSet()`. Clients should not need to define their own
methods for this.


Logging
-------

:mps:tag:`logging.control` Buffers have a separate control for whether they
are logged or not, this is because they are particularly high volume.
This is a Boolean flag (``bufferLogging``) in the :c:type:`ArenaStruct`.


Measurement
-----------

:mps:tag:`count` Counting the allocation volume is done by maintaining two
fields in the buffer struct:

:mps:tag:`count.fields` ``fillSize``, ``emptySize``.

:mps:tag:`count.monotonic` both of these fields are monotonically
increasing.

:mps:tag:`count.fillsize` ``fillSize`` is an accumulated total of the size
of all the fills (as a result of calling the :c:type:`PoolClass`
:c:func:`BufferFill()` method) that happen on the buffer.

:mps:tag:`count.emptysize` ``emptySize`` is an accumulated total of the size of
all the empties than happen on the buffer (which are notified to the
pool using the :c:type:`PoolClass` :c:func:`BufferEmpty()` method).

:mps:tag:`count.generic` These fields are maintained by the generic buffer
code in :c:func:`BufferAttach()` and :c:func:`BufferDetach()`.

:mps:tag:`count.other` Similar count fields are maintained in the arena.
They are maintained on an internal (buffers used internally by the
MPS) and external (buffers used for mutator allocation points) basis.
The fields are also updated by the buffer code. The fields are:

- in the arena, ``fillMutatorSize``, ``fillInternalSize``,
  ``emptyMutatorSize``, ``emptyInternalSize``, and
  ``allocMutatorSize`` (5 fields).

:mps:tag:`count.alloc.how` The amount of allocation in the buffer just
after an empty is ``fillSize - emptySize``. At other times this
computation will include space that the buffer has the use of (between
base and init) but which may not get allocated in (because the
remaining space may be too large for the next reserve so some or all
of it may get emptied). The arena field ``allocMutatorSize`` is
incremented by the allocated size (between base and init)
whenever a buffer is detached. Symmetrically this field is decremented
by by the pre-allocated size (between base and init) whenever
a buffer is attached. The overall count is asymptotically correct.

:mps:tag:`count.type` All the count fields are type double.

:mps:tag:`count.type.justify` This is because double is the type most likely
to give us enough precision. Because of the lack of genuine
requirements the type isn't so important. It's nice to have it more
precise than long. Which double usually is.


Notes from the whiteboard
-------------------------

Requirements

- atomic update of words
- guarantee order of reads and write to certain memory locations.

Flip

- limit:=0
- record init for scanner

Commit

- init:=alloc
- if(limit = 0) ...
- L written only by MM
- A written only by client (except during synchronized MM op)
- I ditto
- I read by MM during flip

States

- busy
- ready
- trapped
- reset

.. note::

    There are many more states. DRJ.

Misc

- During buffer ops all field values can change. Might trash perfectly
  good ("valid"?) object if pool isn't careful.


Synchronization
---------------

Buffers provide a loose form of synchronization between the mutator
and the collector.

The crucial synchronization issues are between the operation the pool
performs on flip and the mutator's commit operation.

Commit

- read init
- write init
- Memory Barrier
- read ``limit``

Flip

- write ``limit``
- Memory Barrier
- read init

Commit consists of two parts. The first is the update to init.
This is a declaration that the new object just before init is now
correctly formatted and can be scanned. The second is a check to see
if the buffer has been "tripped". The ordering of the two parts is
crucial.

Note that the declaration that the object is correctly formatted is
independent of whether the buffer has been tripped or not. In
particular a pool can scan up to the init pointer (including the newly
declared object) whether or not the pool will cause the commit to
fail. In the case where the pool scans the object, but then causes the
commit to fail (and presumably the allocation to occur somewhere
else), the pool will have scanned a "dead" object, but this is just
another example of conservatism in the general sense.

Not that the read of init in the Flip sequence can in fact be
arbitrarily delayed (as long as it is read before a buffered segment
is scanned).

On processors with Relaxed Memory Order (such as the DEC Alpha),
Memory Barriers will need to be placed at the points indicated.

::

 * DESIGN
 *
 * An allocation buffer is an interface to a pool which provides
 * very fast allocation, and defers the need for synchronization in
 * a multi-threaded environment.
 *
 * Pools which contain formatted objects must be synchronized so
 * that the pool can know when an object is valid.  Allocation from
 * such pools is done in two stages: reserve and commit.  The client
 * first reserves memory, then initializes it, then commits.
 * Committing the memory declares that it contains a valid formatted
 * object.  Under certain conditions, some pools may cause the
 * commit operation to fail.  (See the documentation for the pool.)
 * Failure to commit indicates that the whole allocation failed and
 * must be restarted.  When using a pool which introduces the
 * possibility of commit failing, the allocation sequence could look
 * something like this:
 *
 * do {
 *   res = BufferReserve(&p, buffer, size);
 *   if(res != ResOK) return res;       // allocation fails, reason res
 *   initialize(p);                     // p now points at valid object
 * } while(!BufferCommit(buffer, p, size));
 *
 * Pools which do not contain formatted objects can use a one-step
 * allocation as usual.  Effectively any random rubbish counts as a
 * "valid object" to such pools.
 *
 * An allocation buffer is an area of memory which is pre-allocated
 * from a pool, plus a buffer descriptor, which contains, inter
 * alia, four pointers: base, init, alloc, and limit.  Base points
 * to the base address of the area, limit to the last address plus
 * one.  Init points to the first uninitialized address in the
 * buffer, and alloc points to the first unallocated address.
 *
 *    L . - - - - - .         ^
 *      |           |     Higher addresses -'
 *      |   junk    |
 *      |           |       the "busy" state, after Reserve
 *    A |-----------|
 *      |  uninit   |
 *    I |-----------|
 *      |   init    |
 *      |           |     Lower addresses  -.
 *    B `-----------'         v
 *
 *    L . - - - - - .         ^
 *      |           |     Higher addresses -'
 *      |   junk    |
 *      |           |       the "ready" state, after Commit
 *  A=I |-----------|
 *      |           |
 *      |           |
 *      |   init    |
 *      |           |     Lower addresses  -.
 *    B `-----------'         v
 *
 * Access to these pointers is restricted in order to allow
 * synchronization between the pool and the client.  The client may
 * only write to init and alloc, but in a restricted and atomic way
 * detailed below.  The pool may read the contents of the buffer
 * descriptor at _any_ time.  During calls to the fill and trip
 * methods, the pool may update any or all of the fields
 * in the buffer descriptor.  The pool may update the limit at _any_
 * time.
 *
 * Access to buffers by these methods is not synchronized.  If a buffer
 * is to be used by more than one thread then it is the client's
 * responsibility to ensure exclusive access.  It is recommended that
 * a buffer be used by only a single thread.
 *
 * [Only one thread may use a buffer at once, unless the client
 * places a mutual exclusion around the buffer access in the usual
 * way.  In such cases it is usually better to create one buffer for
 * each thread.]
 *
 * Here are pseudo-code descriptions of the reserve and commit
 * operations.  These may be implemented in-line by the client.
 * Note that the client is responsible for ensuring that the size
 * (and therefore the alloc and init pointers) are aligned according
 * to the buffer's alignment.
 *
 * Reserve(buf, size)                   ; size must be aligned to pool
 *   if buf->limit - buf->alloc >= size then
 *     buf->alloc +=size                ; must be atomic update
 *     p = buf->init
 *   else
 *     res = BufferFill(&p, buf, size)  ; buf contents may change
 *
 * Commit(buf, p, size)
 *   buf->init = buf->alloc             ; must be atomic update
 *   if buf->limit == 0 then
 *     res = BufferTrip(buf, p, size)   ; buf contents may change
 *   else
 *     res = True
 * (returns True on successful commit)
 *
 * The pool must allocate the buffer descriptor and initialize it by
 * calling BufferInit.  The descriptor this creates will fall
 * through to the fill method on the first allocation.  In general,
 * pools should not assign resources to the buffer until the first
 * allocation, since the buffer may never be used.
 *
 * The pool may update the base, init, alloc, and limit fields when
 * the fallback methods are called.  In addition, the pool may set
 * the limit to zero at any time.  The effect of this is either:
 *
 *   1. cause the _next_ allocation in the buffer to fall through to
 *      the buffer fill method, and allow the buffer to be flushed
 *      and relocated;
 *
 *   2. cause the buffer trip method to be called if the client was
 *      between reserve and commit.
 *
 * A buffer may not be relocated under other circumstances because
 * there is a race between updating the descriptor and the client
 * allocation sequence.


Interface
---------

.. c:function:: Res BufferCreate(Buffer *bufferReturn, BufferClass class, Pool pool, Bool isMutator, ArgList args)

:mps:tag:`method.create` Create an allocation buffer in a pool. The buffer
is created in the "ready" state.

A buffer structure is allocated from the space control pool and
partially initialized (in particularly neither the signature nor the
serial field are initialized). The pool class's :c:func:`bufferCreate()`
method is then called. This method can update (some undefined subset
of) the fields of the structure; it should return with the buffer in
the "ready" state (or fail). The remainder of the initialization then
occurs.

If and only if successful then a valid buffer is returned.

.. c:function:: void BufferDestroy(Buffer buffer)

:mps:tag:`method.destroy` Free a buffer descriptor. The buffer must be in
the "ready" state, that is, not between a Reserve and Commit.
Allocation in the area of memory to which the descriptor refers must
cease after :c:func:`BufferDestroy()` is called.

Destroying an allocation buffer does not affect objects which have
been allocated, it just frees resources associated with the buffer
itself.

The pool class's :c:func:`bufferDestroy()` method is called and then the
buffer structure is uninitialized and freed.

.. c:function:: Bool BufferCheck(Buffer buffer)

:mps:tag:`method.check` The check method is straightforward, the non-trivial dependencies checked are:

- The ordering constraints between base, init, alloc, and limit.
- The alignment constraints on base, init, alloc, and limit.
- That the buffer's rank is identical to the segment's rank.

.. c:function:: void BufferAttach(Buffer buffer, Addr base, Addr limit, Addr init, Size size)

:mps:tag:`method.attach` Set the base, init, alloc, and limit fields so that
the buffer is ready to start allocating in area of memory. The alloc
field is set to ``init + size``.

:mps:tag:`method.attach.unbusy` :c:func:`BufferAttach()` must only be applied to
buffers that are not busy.

.. c:function:: void BufferDetach(Buffer buffer, Pool pool)

:mps:tag:`method.detach` Set the seg, base, init, alloc, and limit fields to
zero, so that the next reserve request will call the fill method.

:mps:tag:`method.detach.unbusy` :c:func:`BufferDetach()` must only be applied to
buffers that are not busy.

.. c:function:: Bool BufferIsReset(Buffer buffer)

:mps:tag:`method.isreset` Returns :c:macro:`TRUE` if and only if the buffer is in the
reset state, that is, with base, init, alloc, and limit all set to
zero.

.. c:function:: Bool BufferIsReady(Buffer buffer)

:mps:tag:`method.isready` Returns :c:macro:`TRUE` if and only if the buffer is not
between a reserve and commit. The result is only reliable if the
client is not currently using the buffer, since it may update the
alloc and init pointers asynchronously.

.. c:function:: mps_ap_t BufferAP(Buffer buffer)

Returns the :c:type:`APStruct` substructure of a buffer.

.. c:function:: Buffer BufferOfAP(mps_ap_t ap)

:mps:tag:`method.ofap` Return the buffer which owns an :c:type:`APStruct`.

:mps:tag:`method.ofap.thread-safe` :c:func:`BufferOfAP()` must be thread safe (see
impl.c.mpsi.thread-safety). This is achieved simply because the
underlying operation involved is simply a subtraction.

.. c:function:: Arena BufferArena(Buffer buffer)

:mps:tag:`method.arena` Returns the arena which owns a buffer.

:mps:tag:`method.arena.thread-safe` :c:func:`BufferArena()` must be thread safe
(see impl.c.mpsi.thread-safety). This is achieved simple because the
underlying operation is a read of shared-non-mutable data (see
design.mps.thread-safety_).

.. _design.mps.thread-safety: thread-safety.html

.. c:function:: Pool BufferPool(Buffer buffer)

Returns the pool to which a buffer is attached.

.. c:function:: Res BufferReserve(Addr *pReturn, Buffer buffer, Size size)

:mps:tag:`method.reserve` Reserves memory from an allocation buffer.

This is a provided version of the reserve procedure described above.
The size must be aligned according to the buffer alignment. If
successful, ``ResOK`` is returned and ``*pReturn`` is updated with a
pointer to the reserved memory. Otherwise ``*pReturn`` is not touched.
The reserved memory is not guaranteed to have any particular contents.
The memory must be initialized with a valid object (according to the
pool to which the buffer belongs) and then passed to the
:c:func:`BufferCommit()` method (see below). ``BufferReserve(0`` may not be
applied twice to a buffer without a :c:func:`BufferCommit()` in-between. In
other words, Reserve/Commit pairs do not nest.

.. c:function:: Res BufferFill(Addr *pReturn, Buffer buffer, Size size)

:mps:tag:`method.fill` Refills an empty buffer. If there is not enough space
in a buffer to allocate in-line, :c:func:`BufferFill()` must be called to
"refill" the buffer.

.. c:function:: Bool BufferCommit(Buffer buffer, Addr p, Size size)

:mps:tag:`method.commit` Commit memory previously reserved.

:c:func:`BufferCommit()` notifies the pool that memory which has been
previously reserved (see above) has been initialized with a valid
object (according to the pool to which the buffer belongs). The
pointer ``p`` must be the same as that returned by
:c:func:`BufferReserve()`, and the size must match the size passed to
:c:func:`BufferReserve()`.

:c:func:`BufferCommit()` may not be applied twice to a buffer without a
reserve in between. In other words, objects must be reserved,
initialized, then committed only once.

Commit returns :c:macro:`TRUE` if successful, :c:macro:`FALSE` otherwise. If commit
fails and returns :c:macro:`FALSE`, the client may try to allocate again by
going back to the reserve stage, and may not use the memory at ``p``
again for any purpose.

Some classes of pool may cause commit to fail under rare
circumstances.

.. c:function:: void BufferTrip(Buffer buffer, Addr p, Size size)

:mps:tag:`method.trip` Act on a tripped buffer. The pool which owns a buffer
may asynchronously set the buffer limit to zero in order to get
control over the buffer. If this occurs after a :c:func:`BufferReserve()`
(but before the corresponding commit), then the :c:func:`BufferCommit()`
method calls :c:func:`BufferTrip()` and the :c:func:`BufferCommit()` method
returns with the return value of :c:func:`BufferTrip()`.

:mps:tag:`method.trip.precondition` At the time trip is called, from
:c:func:`BufferCommit()`, the following are true:

- :mps:tag:`method.trip.precondition.limit` ``limit == 0``
- :mps:tag:`method.trip.precondition.init` ``init == alloc``
- :mps:tag:`method.trip.precondition.p` ``p + size == alloc``


Diagrams
--------

Here are a number of diagrams showing how buffers behave. In general,
the horizontal axis corresponds to mutator action (reserve, commit)
and the vertical axis corresponds to collector action. I'm not sure
which of the diagrams are the same as each other, and which are best
or most complete when they are different, but they all attempt to show
essentially the same information. It's very difficult to get all the
details in. These diagrams were drawn by Richard Brooksby, Richard
Tucker, Gavin Matthews, and others in April 1997. In general, the
later diagrams are, I suspect, more correct, complete and useful than
the earlier ones. I have put them all here for the record. Richard
Tucker, 1998-02-09.

Buffer Diagram:
Buffer States

Buffer States (3-column)
Buffer States (4-column)
Buffer States (gavinised)
Buffer States (interleaved)
Buffer States (richardized)

[missing diagrams]