sync with tizen_2.2
[sdk/emulator/qemu.git] / gl / mesa / src / mesa / main / bufferobj.c
1 /*
2  * Mesa 3-D graphics library
3  * Version:  7.6
4  *
5  * Copyright (C) 1999-2008  Brian Paul   All Rights Reserved.
6  * Copyright (C) 2009  VMware, Inc.  All Rights Reserved.
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a
9  * copy of this software and associated documentation files (the "Software"),
10  * to deal in the Software without restriction, including without limitation
11  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12  * and/or sell copies of the Software, and to permit persons to whom the
13  * Software is furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included
16  * in all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
21  * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
22  * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24  */
25
26
27 /**
28  * \file bufferobj.c
29  * \brief Functions for the GL_ARB_vertex/pixel_buffer_object extensions.
30  * \author Brian Paul, Ian Romanick
31  */
32
33
34 #include "glheader.h"
35 #include "enums.h"
36 #include "hash.h"
37 #include "imports.h"
38 #include "image.h"
39 #include "context.h"
40 #include "bufferobj.h"
41 #include "fbobject.h"
42 #include "mfeatures.h"
43 #include "mtypes.h"
44 #include "texobj.h"
45
46
47 /* Debug flags */
48 /*#define VBO_DEBUG*/
49 /*#define BOUNDS_CHECK*/
50
51
52 /**
53  * Used as a placeholder for buffer objects between glGenBuffers() and
54  * glBindBuffer() so that glIsBuffer() can work correctly.
55  */
56 static struct gl_buffer_object DummyBufferObject;
57
58
59 /**
60  * Return pointer to address of a buffer object target.
61  * \param ctx  the GL context
62  * \param target  the buffer object target to be retrieved.
63  * \return   pointer to pointer to the buffer object bound to \c target in the
64  *           specified context or \c NULL if \c target is invalid.
65  */
66 static inline struct gl_buffer_object **
67 get_buffer_target(struct gl_context *ctx, GLenum target)
68 {
69    switch (target) {
70    case GL_ARRAY_BUFFER_ARB:
71       return &ctx->Array.ArrayBufferObj;
72    case GL_ELEMENT_ARRAY_BUFFER_ARB:
73       return &ctx->Array.ArrayObj->ElementArrayBufferObj;
74    case GL_PIXEL_PACK_BUFFER_EXT:
75       return &ctx->Pack.BufferObj;
76    case GL_PIXEL_UNPACK_BUFFER_EXT:
77       return &ctx->Unpack.BufferObj;
78    case GL_COPY_READ_BUFFER:
79       return &ctx->CopyReadBuffer;
80    case GL_COPY_WRITE_BUFFER:
81       return &ctx->CopyWriteBuffer;
82 #if FEATURE_EXT_transform_feedback
83    case GL_TRANSFORM_FEEDBACK_BUFFER:
84       if (ctx->Extensions.EXT_transform_feedback) {
85          return &ctx->TransformFeedback.CurrentBuffer;
86       }
87       break;
88 #endif
89    case GL_TEXTURE_BUFFER:
90       if (ctx->Extensions.ARB_texture_buffer_object) {
91          return &ctx->Texture.BufferObject;
92       }
93       break;
94    default:
95       return NULL;
96    }
97    return NULL;
98 }
99
100
101 /**
102  * Get the buffer object bound to the specified target in a GL context.
103  * \param ctx  the GL context
104  * \param target  the buffer object target to be retrieved.
105  * \return   pointer to the buffer object bound to \c target in the
106  *           specified context or \c NULL if \c target is invalid.
107  */
108 static inline struct gl_buffer_object *
109 get_buffer(struct gl_context *ctx, const char *func, GLenum target)
110 {
111    struct gl_buffer_object **bufObj = get_buffer_target(ctx, target);
112
113    if (!bufObj) {
114       _mesa_error(ctx, GL_INVALID_ENUM, "%s(target)", func);
115       return NULL;
116    }
117
118    if (!_mesa_is_bufferobj(*bufObj)) {
119       _mesa_error(ctx, GL_INVALID_OPERATION, "%s(buffer 0)", func);
120       return NULL;
121    }
122
123    return *bufObj;
124 }
125
126
127 static inline GLenum
128 default_access_mode(const struct gl_context *ctx)
129 {
130    /* Table 2.6 on page 31 (page 44 of the PDF) of the OpenGL 1.5 spec says:
131     *
132     * Name           Type  Initial Value  Legal Values
133     * ...            ...   ...            ...
134     * BUFFER_ACCESS  enum  READ_WRITE     READ_ONLY, WRITE_ONLY
135     *                                     READ_WRITE
136     *
137     * However, table 6.8 in the GL_OES_mapbuffer extension says:
138     *
139     * Get Value         Type Get Command          Value          Description
140     * ---------         ---- -----------          -----          -----------
141     * BUFFER_ACCESS_OES Z1   GetBufferParameteriv WRITE_ONLY_OES buffer map flag
142     *
143     * The difference is because GL_OES_mapbuffer only supports mapping buffers
144     * write-only.
145     */
146    return (ctx->API == API_OPENGLES)
147       ? GL_MAP_WRITE_BIT : (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT);
148 }
149
150
151 /**
152  * Convert a GLbitfield describing the mapped buffer access flags
153  * into one of GL_READ_WRITE, GL_READ_ONLY, or GL_WRITE_ONLY.
154  */
155 static GLenum
156 simplified_access_mode(GLbitfield access)
157 {
158    const GLbitfield rwFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT;
159    if ((access & rwFlags) == rwFlags)
160       return GL_READ_WRITE;
161    if ((access & GL_MAP_READ_BIT) == GL_MAP_READ_BIT)
162       return GL_READ_ONLY;
163    if ((access & GL_MAP_WRITE_BIT) == GL_MAP_WRITE_BIT)
164       return GL_WRITE_ONLY;
165    return GL_READ_WRITE; /* this should never happen, but no big deal */
166 }
167
168
169 /**
170  * Tests the subdata range parameters and sets the GL error code for
171  * \c glBufferSubDataARB and \c glGetBufferSubDataARB.
172  *
173  * \param ctx     GL context.
174  * \param target  Buffer object target on which to operate.
175  * \param offset  Offset of the first byte of the subdata range.
176  * \param size    Size, in bytes, of the subdata range.
177  * \param caller  Name of calling function for recording errors.
178  * \return   A pointer to the buffer object bound to \c target in the
179  *           specified context or \c NULL if any of the parameter or state
180  *           conditions for \c glBufferSubDataARB or \c glGetBufferSubDataARB
181  *           are invalid.
182  *
183  * \sa glBufferSubDataARB, glGetBufferSubDataARB
184  */
185 static struct gl_buffer_object *
186 buffer_object_subdata_range_good( struct gl_context * ctx, GLenum target, 
187                                   GLintptrARB offset, GLsizeiptrARB size,
188                                   const char *caller )
189 {
190    struct gl_buffer_object *bufObj;
191
192    if (size < 0) {
193       _mesa_error(ctx, GL_INVALID_VALUE, "%s(size < 0)", caller);
194       return NULL;
195    }
196
197    if (offset < 0) {
198       _mesa_error(ctx, GL_INVALID_VALUE, "%s(offset < 0)", caller);
199       return NULL;
200    }
201
202    bufObj = get_buffer(ctx, caller, target);
203    if (!bufObj)
204       return NULL;
205
206    if (offset + size > bufObj->Size) {
207       _mesa_error(ctx, GL_INVALID_VALUE,
208                   "%s(offset %lu + size %lu > buffer size %lu)", caller,
209                   (unsigned long) offset,
210                   (unsigned long) size,
211                   (unsigned long) bufObj->Size);
212       return NULL;
213    }
214    if (_mesa_bufferobj_mapped(bufObj)) {
215       /* Buffer is currently mapped */
216       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", caller);
217       return NULL;
218    }
219
220    return bufObj;
221 }
222
223
224 /**
225  * Allocate and initialize a new buffer object.
226  * 
227  * Default callback for the \c dd_function_table::NewBufferObject() hook.
228  */
229 static struct gl_buffer_object *
230 _mesa_new_buffer_object( struct gl_context *ctx, GLuint name, GLenum target )
231 {
232    struct gl_buffer_object *obj;
233
234    (void) ctx;
235
236    obj = MALLOC_STRUCT(gl_buffer_object);
237    _mesa_initialize_buffer_object(ctx, obj, name, target);
238    return obj;
239 }
240
241
242 /**
243  * Delete a buffer object.
244  * 
245  * Default callback for the \c dd_function_table::DeleteBuffer() hook.
246  */
247 static void
248 _mesa_delete_buffer_object(struct gl_context *ctx,
249                            struct gl_buffer_object *bufObj)
250 {
251    (void) ctx;
252
253    if (bufObj->Data)
254       free(bufObj->Data);
255
256    /* assign strange values here to help w/ debugging */
257    bufObj->RefCount = -1000;
258    bufObj->Name = ~0;
259
260    _glthread_DESTROY_MUTEX(bufObj->Mutex);
261    free(bufObj);
262 }
263
264
265
266 /**
267  * Set ptr to bufObj w/ reference counting.
268  * This is normally only called from the _mesa_reference_buffer_object() macro
269  * when there's a real pointer change.
270  */
271 void
272 _mesa_reference_buffer_object_(struct gl_context *ctx,
273                                struct gl_buffer_object **ptr,
274                                struct gl_buffer_object *bufObj)
275 {
276    if (*ptr) {
277       /* Unreference the old buffer */
278       GLboolean deleteFlag = GL_FALSE;
279       struct gl_buffer_object *oldObj = *ptr;
280
281       _glthread_LOCK_MUTEX(oldObj->Mutex);
282       ASSERT(oldObj->RefCount > 0);
283       oldObj->RefCount--;
284 #if 0
285       printf("BufferObj %p %d DECR to %d\n",
286              (void *) oldObj, oldObj->Name, oldObj->RefCount);
287 #endif
288       deleteFlag = (oldObj->RefCount == 0);
289       _glthread_UNLOCK_MUTEX(oldObj->Mutex);
290
291       if (deleteFlag) {
292
293          /* some sanity checking: don't delete a buffer still in use */
294 #if 0
295          /* unfortunately, these tests are invalid during context tear-down */
296          ASSERT(ctx->Array.ArrayBufferObj != bufObj);
297          ASSERT(ctx->Array.ArrayObj->ElementArrayBufferObj != bufObj);
298          ASSERT(ctx->Array.ArrayObj->Vertex.BufferObj != bufObj);
299 #endif
300
301          ASSERT(ctx->Driver.DeleteBuffer);
302          ctx->Driver.DeleteBuffer(ctx, oldObj);
303       }
304
305       *ptr = NULL;
306    }
307    ASSERT(!*ptr);
308
309    if (bufObj) {
310       /* reference new buffer */
311       _glthread_LOCK_MUTEX(bufObj->Mutex);
312       if (bufObj->RefCount == 0) {
313          /* this buffer's being deleted (look just above) */
314          /* Not sure this can every really happen.  Warn if it does. */
315          _mesa_problem(NULL, "referencing deleted buffer object");
316          *ptr = NULL;
317       }
318       else {
319          bufObj->RefCount++;
320 #if 0
321          printf("BufferObj %p %d INCR to %d\n",
322                 (void *) bufObj, bufObj->Name, bufObj->RefCount);
323 #endif
324          *ptr = bufObj;
325       }
326       _glthread_UNLOCK_MUTEX(bufObj->Mutex);
327    }
328 }
329
330
331 /**
332  * Initialize a buffer object to default values.
333  */
334 void
335 _mesa_initialize_buffer_object( struct gl_context *ctx,
336                                 struct gl_buffer_object *obj,
337                                 GLuint name, GLenum target )
338 {
339    (void) target;
340
341    memset(obj, 0, sizeof(struct gl_buffer_object));
342    _glthread_INIT_MUTEX(obj->Mutex);
343    obj->RefCount = 1;
344    obj->Name = name;
345    obj->Usage = GL_STATIC_DRAW_ARB;
346    obj->AccessFlags = default_access_mode(ctx);
347 }
348
349
350 /**
351  * Allocate space for and store data in a buffer object.  Any data that was
352  * previously stored in the buffer object is lost.  If \c data is \c NULL,
353  * memory will be allocated, but no copy will occur.
354  *
355  * This is the default callback for \c dd_function_table::BufferData()
356  * Note that all GL error checking will have been done already.
357  *
358  * \param ctx     GL context.
359  * \param target  Buffer object target on which to operate.
360  * \param size    Size, in bytes, of the new data store.
361  * \param data    Pointer to the data to store in the buffer object.  This
362  *                pointer may be \c NULL.
363  * \param usage   Hints about how the data will be used.
364  * \param bufObj  Object to be used.
365  *
366  * \return GL_TRUE for success, GL_FALSE for failure
367  * \sa glBufferDataARB, dd_function_table::BufferData.
368  */
369 static GLboolean
370 _mesa_buffer_data( struct gl_context *ctx, GLenum target, GLsizeiptrARB size,
371                    const GLvoid * data, GLenum usage,
372                    struct gl_buffer_object * bufObj )
373 {
374    void * new_data;
375
376    (void) ctx; (void) target;
377
378    new_data = _mesa_realloc( bufObj->Data, bufObj->Size, size );
379    if (new_data) {
380       bufObj->Data = (GLubyte *) new_data;
381       bufObj->Size = size;
382       bufObj->Usage = usage;
383
384       if (data) {
385          memcpy( bufObj->Data, data, size );
386       }
387
388       return GL_TRUE;
389    }
390    else {
391       return GL_FALSE;
392    }
393 }
394
395
396 /**
397  * Replace data in a subrange of buffer object.  If the data range
398  * specified by \c size + \c offset extends beyond the end of the buffer or
399  * if \c data is \c NULL, no copy is performed.
400  *
401  * This is the default callback for \c dd_function_table::BufferSubData()
402  * Note that all GL error checking will have been done already.
403  *
404  * \param ctx     GL context.
405  * \param target  Buffer object target on which to operate.
406  * \param offset  Offset of the first byte to be modified.
407  * \param size    Size, in bytes, of the data range.
408  * \param data    Pointer to the data to store in the buffer object.
409  * \param bufObj  Object to be used.
410  *
411  * \sa glBufferSubDataARB, dd_function_table::BufferSubData.
412  */
413 static void
414 _mesa_buffer_subdata( struct gl_context *ctx, GLintptrARB offset,
415                       GLsizeiptrARB size, const GLvoid * data,
416                       struct gl_buffer_object * bufObj )
417 {
418    (void) ctx;
419
420    /* this should have been caught in _mesa_BufferSubData() */
421    ASSERT(size + offset <= bufObj->Size);
422
423    if (bufObj->Data) {
424       memcpy( (GLubyte *) bufObj->Data + offset, data, size );
425    }
426 }
427
428
429 /**
430  * Retrieve data from a subrange of buffer object.  If the data range
431  * specified by \c size + \c offset extends beyond the end of the buffer or
432  * if \c data is \c NULL, no copy is performed.
433  *
434  * This is the default callback for \c dd_function_table::GetBufferSubData()
435  * Note that all GL error checking will have been done already.
436  *
437  * \param ctx     GL context.
438  * \param target  Buffer object target on which to operate.
439  * \param offset  Offset of the first byte to be fetched.
440  * \param size    Size, in bytes, of the data range.
441  * \param data    Destination for data
442  * \param bufObj  Object to be used.
443  *
444  * \sa glBufferGetSubDataARB, dd_function_table::GetBufferSubData.
445  */
446 static void
447 _mesa_buffer_get_subdata( struct gl_context *ctx, GLintptrARB offset,
448                           GLsizeiptrARB size, GLvoid * data,
449                           struct gl_buffer_object * bufObj )
450 {
451    (void) ctx;
452
453    if (bufObj->Data && ((GLsizeiptrARB) (size + offset) <= bufObj->Size)) {
454       memcpy( data, (GLubyte *) bufObj->Data + offset, size );
455    }
456 }
457
458
459 /**
460  * Default fallback for \c dd_function_table::MapBufferRange().
461  * Called via glMapBufferRange().
462  */
463 static void *
464 _mesa_buffer_map_range( struct gl_context *ctx, GLintptr offset,
465                         GLsizeiptr length, GLbitfield access,
466                         struct gl_buffer_object *bufObj )
467 {
468    (void) ctx;
469    assert(!_mesa_bufferobj_mapped(bufObj));
470    /* Just return a direct pointer to the data */
471    bufObj->Pointer = bufObj->Data + offset;
472    bufObj->Length = length;
473    bufObj->Offset = offset;
474    bufObj->AccessFlags = access;
475    return bufObj->Pointer;
476 }
477
478
479 /**
480  * Default fallback for \c dd_function_table::FlushMappedBufferRange().
481  * Called via glFlushMappedBufferRange().
482  */
483 static void
484 _mesa_buffer_flush_mapped_range( struct gl_context *ctx,
485                                  GLintptr offset, GLsizeiptr length,
486                                  struct gl_buffer_object *obj )
487 {
488    (void) ctx;
489    (void) offset;
490    (void) length;
491    (void) obj;
492    /* no-op */
493 }
494
495
496 /**
497  * Default callback for \c dd_function_table::MapBuffer().
498  *
499  * The input parameters will have been already tested for errors.
500  *
501  * \sa glUnmapBufferARB, dd_function_table::UnmapBuffer
502  */
503 static GLboolean
504 _mesa_buffer_unmap( struct gl_context *ctx, struct gl_buffer_object *bufObj )
505 {
506    (void) ctx;
507    /* XXX we might assert here that bufObj->Pointer is non-null */
508    bufObj->Pointer = NULL;
509    bufObj->Length = 0;
510    bufObj->Offset = 0;
511    bufObj->AccessFlags = 0x0;
512    return GL_TRUE;
513 }
514
515
516 /**
517  * Default fallback for \c dd_function_table::CopyBufferSubData().
518  * Called via glCopyBuffserSubData().
519  */
520 static void
521 _mesa_copy_buffer_subdata(struct gl_context *ctx,
522                           struct gl_buffer_object *src,
523                           struct gl_buffer_object *dst,
524                           GLintptr readOffset, GLintptr writeOffset,
525                           GLsizeiptr size)
526 {
527    void *srcPtr, *dstPtr;
528
529    /* the buffers should not be mapped */
530    assert(!_mesa_bufferobj_mapped(src));
531    assert(!_mesa_bufferobj_mapped(dst));
532
533    if (src == dst) {
534       srcPtr = dstPtr = ctx->Driver.MapBufferRange(ctx, 0, src->Size,
535                                                    GL_MAP_READ_BIT |
536                                                    GL_MAP_WRITE_BIT, src);
537
538       if (!srcPtr)
539          return;
540
541       srcPtr += readOffset;
542       dstPtr += writeOffset;
543    } else {
544       srcPtr = ctx->Driver.MapBufferRange(ctx, readOffset, size,
545                                           GL_MAP_READ_BIT, src);
546       dstPtr = ctx->Driver.MapBufferRange(ctx, writeOffset, size,
547                                           (GL_MAP_WRITE_BIT |
548                                            GL_MAP_INVALIDATE_RANGE_BIT), dst);
549    }
550
551    /* Note: the src and dst regions will never overlap.  Trying to do so
552     * would generate GL_INVALID_VALUE earlier.
553     */
554    if (srcPtr && dstPtr)
555       memcpy(dstPtr, srcPtr, size);
556
557    ctx->Driver.UnmapBuffer(ctx, src);
558    if (dst != src)
559       ctx->Driver.UnmapBuffer(ctx, dst);
560 }
561
562
563
564 /**
565  * Initialize the state associated with buffer objects
566  */
567 void
568 _mesa_init_buffer_objects( struct gl_context *ctx )
569 {
570    memset(&DummyBufferObject, 0, sizeof(DummyBufferObject));
571    _glthread_INIT_MUTEX(DummyBufferObject.Mutex);
572    DummyBufferObject.RefCount = 1000*1000*1000; /* never delete */
573
574    _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj,
575                                  ctx->Shared->NullBufferObj);
576
577    _mesa_reference_buffer_object(ctx, &ctx->CopyReadBuffer,
578                                  ctx->Shared->NullBufferObj);
579    _mesa_reference_buffer_object(ctx, &ctx->CopyWriteBuffer,
580                                  ctx->Shared->NullBufferObj);
581 }
582
583
584 void
585 _mesa_free_buffer_objects( struct gl_context *ctx )
586 {
587    _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj, NULL);
588
589    _mesa_reference_buffer_object(ctx, &ctx->CopyReadBuffer, NULL);
590    _mesa_reference_buffer_object(ctx, &ctx->CopyWriteBuffer, NULL);
591 }
592
593
594 /**
595  * Bind the specified target to buffer for the specified context.
596  * Called by glBindBuffer() and other functions.
597  */
598 static void
599 bind_buffer_object(struct gl_context *ctx, GLenum target, GLuint buffer)
600 {
601    struct gl_buffer_object *oldBufObj;
602    struct gl_buffer_object *newBufObj = NULL;
603    struct gl_buffer_object **bindTarget = NULL;
604
605    bindTarget = get_buffer_target(ctx, target);
606    if (!bindTarget) {
607       _mesa_error(ctx, GL_INVALID_ENUM, "glBindBufferARB(target 0x%x)", target);
608       return;
609    }
610
611    /* Get pointer to old buffer object (to be unbound) */
612    oldBufObj = *bindTarget;
613    if (oldBufObj && oldBufObj->Name == buffer && !oldBufObj->DeletePending)
614       return;   /* rebinding the same buffer object- no change */
615
616    /*
617     * Get pointer to new buffer object (newBufObj)
618     */
619    if (buffer == 0) {
620       /* The spec says there's not a buffer object named 0, but we use
621        * one internally because it simplifies things.
622        */
623       newBufObj = ctx->Shared->NullBufferObj;
624    }
625    else {
626       /* non-default buffer object */
627       newBufObj = _mesa_lookup_bufferobj(ctx, buffer);
628       if (!newBufObj || newBufObj == &DummyBufferObject) {
629          /* If this is a new buffer object id, or one which was generated but
630           * never used before, allocate a buffer object now.
631           */
632          ASSERT(ctx->Driver.NewBufferObject);
633          newBufObj = ctx->Driver.NewBufferObject(ctx, buffer, target);
634          if (!newBufObj) {
635             _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBindBufferARB");
636             return;
637          }
638          _mesa_HashInsert(ctx->Shared->BufferObjects, buffer, newBufObj);
639       }
640    }
641    
642    /* bind new buffer */
643    _mesa_reference_buffer_object(ctx, bindTarget, newBufObj);
644
645    /* Pass BindBuffer call to device driver */
646    if (ctx->Driver.BindBuffer)
647       ctx->Driver.BindBuffer( ctx, target, newBufObj );
648 }
649
650
651 /**
652  * Update the default buffer objects in the given context to reference those
653  * specified in the shared state and release those referencing the old 
654  * shared state.
655  */
656 void
657 _mesa_update_default_objects_buffer_objects(struct gl_context *ctx)
658 {
659    /* Bind the NullBufferObj to remove references to those
660     * in the shared context hash table.
661     */
662    bind_buffer_object( ctx, GL_ARRAY_BUFFER_ARB, 0);
663    bind_buffer_object( ctx, GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
664    bind_buffer_object( ctx, GL_PIXEL_PACK_BUFFER_ARB, 0);
665    bind_buffer_object( ctx, GL_PIXEL_UNPACK_BUFFER_ARB, 0);
666 }
667
668
669
670 /**
671  * Return the gl_buffer_object for the given ID.
672  * Always return NULL for ID 0.
673  */
674 struct gl_buffer_object *
675 _mesa_lookup_bufferobj(struct gl_context *ctx, GLuint buffer)
676 {
677    if (buffer == 0)
678       return NULL;
679    else
680       return (struct gl_buffer_object *)
681          _mesa_HashLookup(ctx->Shared->BufferObjects, buffer);
682 }
683
684
685 /**
686  * If *ptr points to obj, set ptr = the Null/default buffer object.
687  * This is a helper for buffer object deletion.
688  * The GL spec says that deleting a buffer object causes it to get
689  * unbound from all arrays in the current context.
690  */
691 static void
692 unbind(struct gl_context *ctx,
693        struct gl_buffer_object **ptr,
694        struct gl_buffer_object *obj)
695 {
696    if (*ptr == obj) {
697       _mesa_reference_buffer_object(ctx, ptr, ctx->Shared->NullBufferObj);
698    }
699 }
700
701
702 /**
703  * Plug default/fallback buffer object functions into the device
704  * driver hooks.
705  */
706 void
707 _mesa_init_buffer_object_functions(struct dd_function_table *driver)
708 {
709    /* GL_ARB_vertex/pixel_buffer_object */
710    driver->NewBufferObject = _mesa_new_buffer_object;
711    driver->DeleteBuffer = _mesa_delete_buffer_object;
712    driver->BindBuffer = NULL;
713    driver->BufferData = _mesa_buffer_data;
714    driver->BufferSubData = _mesa_buffer_subdata;
715    driver->GetBufferSubData = _mesa_buffer_get_subdata;
716    driver->UnmapBuffer = _mesa_buffer_unmap;
717
718    /* GL_ARB_map_buffer_range */
719    driver->MapBufferRange = _mesa_buffer_map_range;
720    driver->FlushMappedBufferRange = _mesa_buffer_flush_mapped_range;
721
722    /* GL_ARB_copy_buffer */
723    driver->CopyBufferSubData = _mesa_copy_buffer_subdata;
724 }
725
726
727
728 /**********************************************************************/
729 /* API Functions                                                      */
730 /**********************************************************************/
731
732 void GLAPIENTRY
733 _mesa_BindBufferARB(GLenum target, GLuint buffer)
734 {
735    GET_CURRENT_CONTEXT(ctx);
736    ASSERT_OUTSIDE_BEGIN_END(ctx);
737
738    if (MESA_VERBOSE & VERBOSE_API)
739       _mesa_debug(ctx, "glBindBuffer(%s, %u)\n",
740                   _mesa_lookup_enum_by_nr(target), buffer);
741
742    bind_buffer_object(ctx, target, buffer);
743 }
744
745
746 /**
747  * Delete a set of buffer objects.
748  * 
749  * \param n      Number of buffer objects to delete.
750  * \param ids    Array of \c n buffer object IDs.
751  */
752 void GLAPIENTRY
753 _mesa_DeleteBuffersARB(GLsizei n, const GLuint *ids)
754 {
755    GET_CURRENT_CONTEXT(ctx);
756    GLsizei i;
757    ASSERT_OUTSIDE_BEGIN_END(ctx);
758    FLUSH_VERTICES(ctx, 0);
759
760    if (n < 0) {
761       _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteBuffersARB(n)");
762       return;
763    }
764
765    _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
766
767    for (i = 0; i < n; i++) {
768       struct gl_buffer_object *bufObj = _mesa_lookup_bufferobj(ctx, ids[i]);
769       if (bufObj) {
770          struct gl_array_object *arrayObj = ctx->Array.ArrayObj;
771          GLuint j;
772
773          ASSERT(bufObj->Name == ids[i] || bufObj == &DummyBufferObject);
774
775          if (_mesa_bufferobj_mapped(bufObj)) {
776             /* if mapped, unmap it now */
777             ctx->Driver.UnmapBuffer(ctx, bufObj);
778             bufObj->AccessFlags = default_access_mode(ctx);
779             bufObj->Pointer = NULL;
780          }
781
782          /* unbind any vertex pointers bound to this buffer */
783          for (j = 0; j < Elements(arrayObj->VertexAttrib); j++) {
784             unbind(ctx, &arrayObj->VertexAttrib[j].BufferObj, bufObj);
785          }
786
787          if (ctx->Array.ArrayBufferObj == bufObj) {
788             _mesa_BindBufferARB( GL_ARRAY_BUFFER_ARB, 0 );
789          }
790          if (arrayObj->ElementArrayBufferObj == bufObj) {
791             _mesa_BindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, 0 );
792          }
793
794          /* unbind any pixel pack/unpack pointers bound to this buffer */
795          if (ctx->Pack.BufferObj == bufObj) {
796             _mesa_BindBufferARB( GL_PIXEL_PACK_BUFFER_EXT, 0 );
797          }
798          if (ctx->Unpack.BufferObj == bufObj) {
799             _mesa_BindBufferARB( GL_PIXEL_UNPACK_BUFFER_EXT, 0 );
800          }
801
802          /* The ID is immediately freed for re-use */
803          _mesa_HashRemove(ctx->Shared->BufferObjects, ids[i]);
804          /* Make sure we do not run into the classic ABA problem on bind.
805           * We don't want to allow re-binding a buffer object that's been
806           * "deleted" by glDeleteBuffers().
807           *
808           * The explicit rebinding to the default object in the current context
809           * prevents the above in the current context, but another context
810           * sharing the same objects might suffer from this problem.
811           * The alternative would be to do the hash lookup in any case on bind
812           * which would introduce more runtime overhead than this.
813           */
814          bufObj->DeletePending = GL_TRUE;
815          _mesa_reference_buffer_object(ctx, &bufObj, NULL);
816       }
817    }
818
819    _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
820 }
821
822
823 /**
824  * Generate a set of unique buffer object IDs and store them in \c buffer.
825  * 
826  * \param n       Number of IDs to generate.
827  * \param buffer  Array of \c n locations to store the IDs.
828  */
829 void GLAPIENTRY
830 _mesa_GenBuffersARB(GLsizei n, GLuint *buffer)
831 {
832    GET_CURRENT_CONTEXT(ctx);
833    GLuint first;
834    GLint i;
835    ASSERT_OUTSIDE_BEGIN_END(ctx);
836
837    if (MESA_VERBOSE & VERBOSE_API)
838       _mesa_debug(ctx, "glGenBuffers(%d)\n", n);
839
840    if (n < 0) {
841       _mesa_error(ctx, GL_INVALID_VALUE, "glGenBuffersARB");
842       return;
843    }
844
845    if (!buffer) {
846       return;
847    }
848
849    /*
850     * This must be atomic (generation and allocation of buffer object IDs)
851     */
852    _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
853
854    first = _mesa_HashFindFreeKeyBlock(ctx->Shared->BufferObjects, n);
855
856    /* Insert the ID and pointer to dummy buffer object into hash table */
857    for (i = 0; i < n; i++) {
858       _mesa_HashInsert(ctx->Shared->BufferObjects, first + i,
859                        &DummyBufferObject);
860       buffer[i] = first + i;
861    }
862
863    _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
864 }
865
866
867 /**
868  * Determine if ID is the name of a buffer object.
869  * 
870  * \param id  ID of the potential buffer object.
871  * \return  \c GL_TRUE if \c id is the name of a buffer object, 
872  *          \c GL_FALSE otherwise.
873  */
874 GLboolean GLAPIENTRY
875 _mesa_IsBufferARB(GLuint id)
876 {
877    struct gl_buffer_object *bufObj;
878    GET_CURRENT_CONTEXT(ctx);
879    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
880
881    _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
882    bufObj = _mesa_lookup_bufferobj(ctx, id);
883    _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
884
885    return bufObj && bufObj != &DummyBufferObject;
886 }
887
888
889 void GLAPIENTRY
890 _mesa_BufferDataARB(GLenum target, GLsizeiptrARB size,
891                     const GLvoid * data, GLenum usage)
892 {
893    GET_CURRENT_CONTEXT(ctx);
894    struct gl_buffer_object *bufObj;
895    ASSERT_OUTSIDE_BEGIN_END(ctx);
896
897    if (MESA_VERBOSE & VERBOSE_API)
898       _mesa_debug(ctx, "glBufferData(%s, %ld, %p, %s)\n",
899                   _mesa_lookup_enum_by_nr(target),
900                   (long int) size, data,
901                   _mesa_lookup_enum_by_nr(usage));
902
903    if (size < 0) {
904       _mesa_error(ctx, GL_INVALID_VALUE, "glBufferDataARB(size < 0)");
905       return;
906    }
907
908    switch (usage) {
909    case GL_STREAM_DRAW_ARB:
910    case GL_STREAM_READ_ARB:
911    case GL_STREAM_COPY_ARB:
912    case GL_STATIC_DRAW_ARB:
913    case GL_STATIC_READ_ARB:
914    case GL_STATIC_COPY_ARB:
915    case GL_DYNAMIC_DRAW_ARB:
916    case GL_DYNAMIC_READ_ARB:
917    case GL_DYNAMIC_COPY_ARB:
918       /* OK */
919       break;
920    default:
921       _mesa_error(ctx, GL_INVALID_ENUM, "glBufferDataARB(usage)");
922       return;
923    }
924
925    bufObj = get_buffer(ctx, "glBufferDataARB", target);
926    if (!bufObj)
927       return;
928
929    if (_mesa_bufferobj_mapped(bufObj)) {
930       /* Unmap the existing buffer.  We'll replace it now.  Not an error. */
931       ctx->Driver.UnmapBuffer(ctx, bufObj);
932       bufObj->AccessFlags = default_access_mode(ctx);
933       ASSERT(bufObj->Pointer == NULL);
934    }  
935
936    FLUSH_VERTICES(ctx, _NEW_BUFFER_OBJECT);
937
938    bufObj->Written = GL_TRUE;
939
940 #ifdef VBO_DEBUG
941    printf("glBufferDataARB(%u, sz %ld, from %p, usage 0x%x)\n",
942                 bufObj->Name, size, data, usage);
943 #endif
944
945 #ifdef BOUNDS_CHECK
946    size += 100;
947 #endif
948
949    ASSERT(ctx->Driver.BufferData);
950    if (!ctx->Driver.BufferData( ctx, target, size, data, usage, bufObj )) {
951       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBufferDataARB()");
952    }
953 }
954
955
956 void GLAPIENTRY
957 _mesa_BufferSubDataARB(GLenum target, GLintptrARB offset,
958                        GLsizeiptrARB size, const GLvoid * data)
959 {
960    GET_CURRENT_CONTEXT(ctx);
961    struct gl_buffer_object *bufObj;
962    ASSERT_OUTSIDE_BEGIN_END(ctx);
963
964    bufObj = buffer_object_subdata_range_good( ctx, target, offset, size,
965                                               "glBufferSubDataARB" );
966    if (!bufObj) {
967       /* error already recorded */
968       return;
969    }
970
971    if (size == 0)
972       return;
973
974    bufObj->Written = GL_TRUE;
975
976    ASSERT(ctx->Driver.BufferSubData);
977    ctx->Driver.BufferSubData( ctx, offset, size, data, bufObj );
978 }
979
980
981 void GLAPIENTRY
982 _mesa_GetBufferSubDataARB(GLenum target, GLintptrARB offset,
983                           GLsizeiptrARB size, void * data)
984 {
985    GET_CURRENT_CONTEXT(ctx);
986    struct gl_buffer_object *bufObj;
987    ASSERT_OUTSIDE_BEGIN_END(ctx);
988
989    bufObj = buffer_object_subdata_range_good( ctx, target, offset, size,
990                                               "glGetBufferSubDataARB" );
991    if (!bufObj) {
992       /* error already recorded */
993       return;
994    }
995
996    ASSERT(ctx->Driver.GetBufferSubData);
997    ctx->Driver.GetBufferSubData( ctx, offset, size, data, bufObj );
998 }
999
1000
1001 void * GLAPIENTRY
1002 _mesa_MapBufferARB(GLenum target, GLenum access)
1003 {
1004    GET_CURRENT_CONTEXT(ctx);
1005    struct gl_buffer_object * bufObj;
1006    GLbitfield accessFlags;
1007    void *map;
1008
1009    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, NULL);
1010
1011    switch (access) {
1012    case GL_READ_ONLY_ARB:
1013       accessFlags = GL_MAP_READ_BIT;
1014       break;
1015    case GL_WRITE_ONLY_ARB:
1016       accessFlags = GL_MAP_WRITE_BIT;
1017       break;
1018    case GL_READ_WRITE_ARB:
1019       accessFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT;
1020       break;
1021    default:
1022       _mesa_error(ctx, GL_INVALID_ENUM, "glMapBufferARB(access)");
1023       return NULL;
1024    }
1025
1026    bufObj = get_buffer(ctx, "glMapBufferARB", target);
1027    if (!bufObj)
1028       return NULL;
1029
1030    if (_mesa_bufferobj_mapped(bufObj)) {
1031       _mesa_error(ctx, GL_INVALID_OPERATION, "glMapBufferARB(already mapped)");
1032       return NULL;
1033    }
1034
1035    if (!bufObj->Size) {
1036       _mesa_error(ctx, GL_OUT_OF_MEMORY,
1037                   "glMapBuffer(buffer size = 0)");
1038       return NULL;
1039    }
1040
1041    ASSERT(ctx->Driver.MapBufferRange);
1042    map = ctx->Driver.MapBufferRange(ctx, 0, bufObj->Size, accessFlags, bufObj);
1043    if (!map) {
1044       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glMapBufferARB(map failed)");
1045       return NULL;
1046    }
1047    else {
1048       /* The driver callback should have set these fields.
1049        * This is important because other modules (like VBO) might call
1050        * the driver function directly.
1051        */
1052       ASSERT(bufObj->Pointer == map);
1053       ASSERT(bufObj->Length == bufObj->Size);
1054       ASSERT(bufObj->Offset == 0);
1055       bufObj->AccessFlags = accessFlags;
1056    }
1057
1058    if (access == GL_WRITE_ONLY_ARB || access == GL_READ_WRITE_ARB)
1059       bufObj->Written = GL_TRUE;
1060
1061 #ifdef VBO_DEBUG
1062    printf("glMapBufferARB(%u, sz %ld, access 0x%x)\n",
1063           bufObj->Name, bufObj->Size, access);
1064    if (access == GL_WRITE_ONLY_ARB) {
1065       GLuint i;
1066       GLubyte *b = (GLubyte *) bufObj->Pointer;
1067       for (i = 0; i < bufObj->Size; i++)
1068          b[i] = i & 0xff;
1069    }
1070 #endif
1071
1072 #ifdef BOUNDS_CHECK
1073    {
1074       GLubyte *buf = (GLubyte *) bufObj->Pointer;
1075       GLuint i;
1076       /* buffer is 100 bytes larger than requested, fill with magic value */
1077       for (i = 0; i < 100; i++) {
1078          buf[bufObj->Size - i - 1] = 123;
1079       }
1080    }
1081 #endif
1082
1083    return bufObj->Pointer;
1084 }
1085
1086
1087 GLboolean GLAPIENTRY
1088 _mesa_UnmapBufferARB(GLenum target)
1089 {
1090    GET_CURRENT_CONTEXT(ctx);
1091    struct gl_buffer_object *bufObj;
1092    GLboolean status = GL_TRUE;
1093    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
1094
1095    bufObj = get_buffer(ctx, "glUnmapBufferARB", target);
1096    if (!bufObj)
1097       return GL_FALSE;
1098
1099    if (!_mesa_bufferobj_mapped(bufObj)) {
1100       _mesa_error(ctx, GL_INVALID_OPERATION, "glUnmapBufferARB");
1101       return GL_FALSE;
1102    }
1103
1104 #ifdef BOUNDS_CHECK
1105    if (bufObj->Access != GL_READ_ONLY_ARB) {
1106       GLubyte *buf = (GLubyte *) bufObj->Pointer;
1107       GLuint i;
1108       /* check that last 100 bytes are still = magic value */
1109       for (i = 0; i < 100; i++) {
1110          GLuint pos = bufObj->Size - i - 1;
1111          if (buf[pos] != 123) {
1112             _mesa_warning(ctx, "Out of bounds buffer object write detected"
1113                           " at position %d (value = %u)\n",
1114                           pos, buf[pos]);
1115          }
1116       }
1117    }
1118 #endif
1119
1120 #ifdef VBO_DEBUG
1121    if (bufObj->AccessFlags & GL_MAP_WRITE_BIT) {
1122       GLuint i, unchanged = 0;
1123       GLubyte *b = (GLubyte *) bufObj->Pointer;
1124       GLint pos = -1;
1125       /* check which bytes changed */
1126       for (i = 0; i < bufObj->Size - 1; i++) {
1127          if (b[i] == (i & 0xff) && b[i+1] == ((i+1) & 0xff)) {
1128             unchanged++;
1129             if (pos == -1)
1130                pos = i;
1131          }
1132       }
1133       if (unchanged) {
1134          printf("glUnmapBufferARB(%u): %u of %ld unchanged, starting at %d\n",
1135                       bufObj->Name, unchanged, bufObj->Size, pos);
1136       }
1137    }
1138 #endif
1139
1140    status = ctx->Driver.UnmapBuffer( ctx, bufObj );
1141    bufObj->AccessFlags = default_access_mode(ctx);
1142    ASSERT(bufObj->Pointer == NULL);
1143    ASSERT(bufObj->Offset == 0);
1144    ASSERT(bufObj->Length == 0);
1145
1146    return status;
1147 }
1148
1149
1150 void GLAPIENTRY
1151 _mesa_GetBufferParameterivARB(GLenum target, GLenum pname, GLint *params)
1152 {
1153    GET_CURRENT_CONTEXT(ctx);
1154    struct gl_buffer_object *bufObj;
1155    ASSERT_OUTSIDE_BEGIN_END(ctx);
1156
1157    bufObj = get_buffer(ctx, "glGetBufferParameterivARB", target);
1158    if (!bufObj)
1159       return;
1160
1161    switch (pname) {
1162    case GL_BUFFER_SIZE_ARB:
1163       *params = (GLint) bufObj->Size;
1164       return;
1165    case GL_BUFFER_USAGE_ARB:
1166       *params = bufObj->Usage;
1167       return;
1168    case GL_BUFFER_ACCESS_ARB:
1169       *params = simplified_access_mode(bufObj->AccessFlags);
1170       return;
1171    case GL_BUFFER_MAPPED_ARB:
1172       *params = _mesa_bufferobj_mapped(bufObj);
1173       return;
1174    case GL_BUFFER_ACCESS_FLAGS:
1175       if (!ctx->Extensions.ARB_map_buffer_range)
1176          goto invalid_pname;
1177       *params = bufObj->AccessFlags;
1178       return;
1179    case GL_BUFFER_MAP_OFFSET:
1180       if (!ctx->Extensions.ARB_map_buffer_range)
1181          goto invalid_pname;
1182       *params = (GLint) bufObj->Offset;
1183       return;
1184    case GL_BUFFER_MAP_LENGTH:
1185       if (!ctx->Extensions.ARB_map_buffer_range)
1186          goto invalid_pname;
1187       *params = (GLint) bufObj->Length;
1188       return;
1189    default:
1190       ; /* fall-through */
1191    }
1192
1193 invalid_pname:
1194    _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferParameterivARB(pname=%s)",
1195                _mesa_lookup_enum_by_nr(pname));
1196 }
1197
1198
1199 /**
1200  * New in GL 3.2
1201  * This is pretty much a duplicate of GetBufferParameteriv() but the
1202  * GL_BUFFER_SIZE_ARB attribute will be 64-bits on a 64-bit system.
1203  */
1204 void GLAPIENTRY
1205 _mesa_GetBufferParameteri64v(GLenum target, GLenum pname, GLint64 *params)
1206 {
1207    GET_CURRENT_CONTEXT(ctx);
1208    struct gl_buffer_object *bufObj;
1209    ASSERT_OUTSIDE_BEGIN_END(ctx);
1210
1211    bufObj = get_buffer(ctx, "glGetBufferParameteri64v", target);
1212    if (!bufObj)
1213       return;
1214
1215    switch (pname) {
1216    case GL_BUFFER_SIZE_ARB:
1217       *params = bufObj->Size;
1218       return;
1219    case GL_BUFFER_USAGE_ARB:
1220       *params = bufObj->Usage;
1221       return;
1222    case GL_BUFFER_ACCESS_ARB:
1223       *params = simplified_access_mode(bufObj->AccessFlags);
1224       return;
1225    case GL_BUFFER_ACCESS_FLAGS:
1226       if (!ctx->Extensions.ARB_map_buffer_range)
1227          goto invalid_pname;
1228       *params = bufObj->AccessFlags;
1229       return;
1230    case GL_BUFFER_MAPPED_ARB:
1231       *params = _mesa_bufferobj_mapped(bufObj);
1232       return;
1233    case GL_BUFFER_MAP_OFFSET:
1234       if (!ctx->Extensions.ARB_map_buffer_range)
1235          goto invalid_pname;
1236       *params = bufObj->Offset;
1237       return;
1238    case GL_BUFFER_MAP_LENGTH:
1239       if (!ctx->Extensions.ARB_map_buffer_range)
1240          goto invalid_pname;
1241       *params = bufObj->Length;
1242       return;
1243    default:
1244       ; /* fall-through */
1245    }
1246
1247 invalid_pname:
1248    _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferParameteri64v(pname=%s)",
1249                _mesa_lookup_enum_by_nr(pname));
1250 }
1251
1252
1253 void GLAPIENTRY
1254 _mesa_GetBufferPointervARB(GLenum target, GLenum pname, GLvoid **params)
1255 {
1256    GET_CURRENT_CONTEXT(ctx);
1257    struct gl_buffer_object * bufObj;
1258    ASSERT_OUTSIDE_BEGIN_END(ctx);
1259
1260    if (pname != GL_BUFFER_MAP_POINTER_ARB) {
1261       _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferPointervARB(pname)");
1262       return;
1263    }
1264
1265    bufObj = get_buffer(ctx, "glGetBufferPointervARB", target);
1266    if (!bufObj)
1267       return;
1268
1269    *params = bufObj->Pointer;
1270 }
1271
1272
1273 void GLAPIENTRY
1274 _mesa_CopyBufferSubData(GLenum readTarget, GLenum writeTarget,
1275                         GLintptr readOffset, GLintptr writeOffset,
1276                         GLsizeiptr size)
1277 {
1278    GET_CURRENT_CONTEXT(ctx);
1279    struct gl_buffer_object *src, *dst;
1280    ASSERT_OUTSIDE_BEGIN_END(ctx);
1281
1282    src = get_buffer(ctx, "glCopyBuffserSubData", readTarget);
1283    if (!src)
1284       return;
1285
1286    dst = get_buffer(ctx, "glCopyBuffserSubData", writeTarget);
1287    if (!dst)
1288       return;
1289
1290    if (_mesa_bufferobj_mapped(src)) {
1291       _mesa_error(ctx, GL_INVALID_OPERATION,
1292                   "glCopyBuffserSubData(readBuffer is mapped)");
1293       return;
1294    }
1295
1296    if (_mesa_bufferobj_mapped(dst)) {
1297       _mesa_error(ctx, GL_INVALID_OPERATION,
1298                   "glCopyBuffserSubData(writeBuffer is mapped)");
1299       return;
1300    }
1301
1302    if (readOffset < 0) {
1303       _mesa_error(ctx, GL_INVALID_VALUE,
1304                   "glCopyBuffserSubData(readOffset = %d)", (int) readOffset);
1305       return;
1306    }
1307
1308    if (writeOffset < 0) {
1309       _mesa_error(ctx, GL_INVALID_VALUE,
1310                   "glCopyBuffserSubData(writeOffset = %d)", (int) writeOffset);
1311       return;
1312    }
1313
1314    if (readOffset + size > src->Size) {
1315       _mesa_error(ctx, GL_INVALID_VALUE,
1316                   "glCopyBuffserSubData(readOffset + size = %d)",
1317                   (int) (readOffset + size));
1318       return;
1319    }
1320
1321    if (writeOffset + size > dst->Size) {
1322       _mesa_error(ctx, GL_INVALID_VALUE,
1323                   "glCopyBuffserSubData(writeOffset + size = %d)",
1324                   (int) (writeOffset + size));
1325       return;
1326    }
1327
1328    if (src == dst) {
1329       if (readOffset + size <= writeOffset) {
1330          /* OK */
1331       }
1332       else if (writeOffset + size <= readOffset) {
1333          /* OK */
1334       }
1335       else {
1336          /* overlapping src/dst is illegal */
1337          _mesa_error(ctx, GL_INVALID_VALUE,
1338                      "glCopyBuffserSubData(overlapping src/dst)");
1339          return;
1340       }
1341    }
1342
1343    ctx->Driver.CopyBufferSubData(ctx, src, dst, readOffset, writeOffset, size);
1344 }
1345
1346
1347 /**
1348  * See GL_ARB_map_buffer_range spec
1349  */
1350 void * GLAPIENTRY
1351 _mesa_MapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length,
1352                      GLbitfield access)
1353 {
1354    GET_CURRENT_CONTEXT(ctx);
1355    struct gl_buffer_object *bufObj;
1356    void *map;
1357
1358    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, NULL);
1359
1360    if (!ctx->Extensions.ARB_map_buffer_range) {
1361       _mesa_error(ctx, GL_INVALID_OPERATION,
1362                   "glMapBufferRange(extension not supported)");
1363       return NULL;
1364    }
1365
1366    if (offset < 0) {
1367       _mesa_error(ctx, GL_INVALID_VALUE,
1368                   "glMapBufferRange(offset = %ld)", (long)offset);
1369       return NULL;
1370    }
1371
1372    if (length < 0) {
1373       _mesa_error(ctx, GL_INVALID_VALUE,
1374                   "glMapBufferRange(length = %ld)", (long)length);
1375       return NULL;
1376    }
1377
1378    if (access & ~(GL_MAP_READ_BIT |
1379                   GL_MAP_WRITE_BIT |
1380                   GL_MAP_INVALIDATE_RANGE_BIT |
1381                   GL_MAP_INVALIDATE_BUFFER_BIT |
1382                   GL_MAP_FLUSH_EXPLICIT_BIT |
1383                   GL_MAP_UNSYNCHRONIZED_BIT)) {
1384       /* generate an error if any undefind bit is set */
1385       _mesa_error(ctx, GL_INVALID_VALUE, "glMapBufferRange(access)");
1386       return NULL;
1387    }
1388
1389    if ((access & (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)) == 0) {
1390       _mesa_error(ctx, GL_INVALID_OPERATION,
1391                   "glMapBufferRange(access indicates neither read or write)");
1392       return NULL;
1393    }
1394
1395    if ((access & GL_MAP_READ_BIT) &&
1396        (access & (GL_MAP_INVALIDATE_RANGE_BIT |
1397                   GL_MAP_INVALIDATE_BUFFER_BIT |
1398                   GL_MAP_UNSYNCHRONIZED_BIT))) {
1399       _mesa_error(ctx, GL_INVALID_OPERATION,
1400                   "glMapBufferRange(invalid access flags)");
1401       return NULL;
1402    }
1403
1404    if ((access & GL_MAP_FLUSH_EXPLICIT_BIT) &&
1405        ((access & GL_MAP_WRITE_BIT) == 0)) {
1406       _mesa_error(ctx, GL_INVALID_OPERATION,
1407                   "glMapBufferRange(invalid access flags)");
1408       return NULL;
1409    }
1410
1411    bufObj = get_buffer(ctx, "glMapBufferRange", target);
1412    if (!bufObj)
1413       return NULL;
1414
1415    if (offset + length > bufObj->Size) {
1416       _mesa_error(ctx, GL_INVALID_VALUE,
1417                   "glMapBufferRange(offset + length > size)");
1418       return NULL;
1419    }
1420
1421    if (_mesa_bufferobj_mapped(bufObj)) {
1422       _mesa_error(ctx, GL_INVALID_OPERATION,
1423                   "glMapBufferRange(buffer already mapped)");
1424       return NULL;
1425    }
1426
1427    if (!bufObj->Size) {
1428       _mesa_error(ctx, GL_OUT_OF_MEMORY,
1429                   "glMapBufferRange(buffer size = 0)");
1430       return NULL;
1431    }
1432
1433    /* Mapping zero bytes should return a non-null pointer. */
1434    if (!length) {
1435       static long dummy = 0;
1436       bufObj->Pointer = &dummy;
1437       bufObj->Length = length;
1438       bufObj->Offset = offset;
1439       bufObj->AccessFlags = access;
1440       return bufObj->Pointer;
1441    }
1442
1443    ASSERT(ctx->Driver.MapBufferRange);
1444    map = ctx->Driver.MapBufferRange(ctx, offset, length, access, bufObj);
1445    if (!map) {
1446       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glMapBufferARB(map failed)");
1447    }
1448    else {
1449       /* The driver callback should have set all these fields.
1450        * This is important because other modules (like VBO) might call
1451        * the driver function directly.
1452        */
1453       ASSERT(bufObj->Pointer == map);
1454       ASSERT(bufObj->Length == length);
1455       ASSERT(bufObj->Offset == offset);
1456       ASSERT(bufObj->AccessFlags == access);
1457    }
1458
1459    return map;
1460 }
1461
1462
1463 /**
1464  * See GL_ARB_map_buffer_range spec
1465  */
1466 void GLAPIENTRY
1467 _mesa_FlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length)
1468 {
1469    GET_CURRENT_CONTEXT(ctx);
1470    struct gl_buffer_object *bufObj;
1471    ASSERT_OUTSIDE_BEGIN_END(ctx);
1472
1473    if (!ctx->Extensions.ARB_map_buffer_range) {
1474       _mesa_error(ctx, GL_INVALID_OPERATION,
1475                   "glFlushMappedBufferRange(extension not supported)");
1476       return;
1477    }
1478
1479    if (offset < 0) {
1480       _mesa_error(ctx, GL_INVALID_VALUE,
1481                   "glFlushMappedBufferRange(offset = %ld)", (long)offset);
1482       return;
1483    }
1484
1485    if (length < 0) {
1486       _mesa_error(ctx, GL_INVALID_VALUE,
1487                   "glFlushMappedBufferRange(length = %ld)", (long)length);
1488       return;
1489    }
1490
1491    bufObj = get_buffer(ctx, "glFlushMappedBufferRange", target);
1492    if (!bufObj)
1493       return;
1494
1495    if (!_mesa_bufferobj_mapped(bufObj)) {
1496       /* buffer is not mapped */
1497       _mesa_error(ctx, GL_INVALID_OPERATION,
1498                   "glFlushMappedBufferRange(buffer is not mapped)");
1499       return;
1500    }
1501
1502    if ((bufObj->AccessFlags & GL_MAP_FLUSH_EXPLICIT_BIT) == 0) {
1503       _mesa_error(ctx, GL_INVALID_OPERATION,
1504                   "glFlushMappedBufferRange(GL_MAP_FLUSH_EXPLICIT_BIT not set)");
1505       return;
1506    }
1507
1508    if (offset + length > bufObj->Length) {
1509       _mesa_error(ctx, GL_INVALID_VALUE,
1510                   "glFlushMappedBufferRange(offset %ld + length %ld > mapped length %ld)",
1511                   (long)offset, (long)length, (long)bufObj->Length);
1512       return;
1513    }
1514
1515    ASSERT(bufObj->AccessFlags & GL_MAP_WRITE_BIT);
1516
1517    if (ctx->Driver.FlushMappedBufferRange)
1518       ctx->Driver.FlushMappedBufferRange(ctx, offset, length, bufObj);
1519 }
1520
1521
1522 #if FEATURE_APPLE_object_purgeable
1523 static GLenum
1524 buffer_object_purgeable(struct gl_context *ctx, GLuint name, GLenum option)
1525 {
1526    struct gl_buffer_object *bufObj;
1527    GLenum retval;
1528
1529    bufObj = _mesa_lookup_bufferobj(ctx, name);
1530    if (!bufObj) {
1531       _mesa_error(ctx, GL_INVALID_VALUE,
1532                   "glObjectPurgeable(name = 0x%x)", name);
1533       return 0;
1534    }
1535    if (!_mesa_is_bufferobj(bufObj)) {
1536       _mesa_error(ctx, GL_INVALID_OPERATION, "glObjectPurgeable(buffer 0)" );
1537       return 0;
1538    }
1539
1540    if (bufObj->Purgeable) {
1541       _mesa_error(ctx, GL_INVALID_OPERATION,
1542                   "glObjectPurgeable(name = 0x%x) is already purgeable", name);
1543       return GL_VOLATILE_APPLE;
1544    }
1545
1546    bufObj->Purgeable = GL_TRUE;
1547
1548    retval = GL_VOLATILE_APPLE;
1549    if (ctx->Driver.BufferObjectPurgeable)
1550       retval = ctx->Driver.BufferObjectPurgeable(ctx, bufObj, option);
1551
1552    return retval;
1553 }
1554
1555
1556 static GLenum
1557 renderbuffer_purgeable(struct gl_context *ctx, GLuint name, GLenum option)
1558 {
1559    struct gl_renderbuffer *bufObj;
1560    GLenum retval;
1561
1562    bufObj = _mesa_lookup_renderbuffer(ctx, name);
1563    if (!bufObj) {
1564       _mesa_error(ctx, GL_INVALID_VALUE,
1565                   "glObjectUnpurgeable(name = 0x%x)", name);
1566       return 0;
1567    }
1568
1569    if (bufObj->Purgeable) {
1570       _mesa_error(ctx, GL_INVALID_OPERATION,
1571                   "glObjectPurgeable(name = 0x%x) is already purgeable", name);
1572       return GL_VOLATILE_APPLE;
1573    }
1574
1575    bufObj->Purgeable = GL_TRUE;
1576
1577    retval = GL_VOLATILE_APPLE;
1578    if (ctx->Driver.RenderObjectPurgeable)
1579       retval = ctx->Driver.RenderObjectPurgeable(ctx, bufObj, option);
1580
1581    return retval;
1582 }
1583
1584
1585 static GLenum
1586 texture_object_purgeable(struct gl_context *ctx, GLuint name, GLenum option)
1587 {
1588    struct gl_texture_object *bufObj;
1589    GLenum retval;
1590
1591    bufObj = _mesa_lookup_texture(ctx, name);
1592    if (!bufObj) {
1593       _mesa_error(ctx, GL_INVALID_VALUE,
1594                   "glObjectPurgeable(name = 0x%x)", name);
1595       return 0;
1596    }
1597
1598    if (bufObj->Purgeable) {
1599       _mesa_error(ctx, GL_INVALID_OPERATION,
1600                   "glObjectPurgeable(name = 0x%x) is already purgeable", name);
1601       return GL_VOLATILE_APPLE;
1602    }
1603
1604    bufObj->Purgeable = GL_TRUE;
1605
1606    retval = GL_VOLATILE_APPLE;
1607    if (ctx->Driver.TextureObjectPurgeable)
1608       retval = ctx->Driver.TextureObjectPurgeable(ctx, bufObj, option);
1609
1610    return retval;
1611 }
1612
1613
1614 GLenum GLAPIENTRY
1615 _mesa_ObjectPurgeableAPPLE(GLenum objectType, GLuint name, GLenum option)
1616 {
1617    GLenum retval;
1618
1619    GET_CURRENT_CONTEXT(ctx);
1620    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, 0);
1621
1622    if (name == 0) {
1623       _mesa_error(ctx, GL_INVALID_VALUE,
1624                   "glObjectPurgeable(name = 0x%x)", name);
1625       return 0;
1626    }
1627
1628    switch (option) {
1629    case GL_VOLATILE_APPLE:
1630    case GL_RELEASED_APPLE:
1631       /* legal */
1632       break;
1633    default:
1634       _mesa_error(ctx, GL_INVALID_ENUM,
1635                   "glObjectPurgeable(name = 0x%x) invalid option: %d",
1636                   name, option);
1637       return 0;
1638    }
1639
1640    switch (objectType) {
1641    case GL_TEXTURE:
1642       retval = texture_object_purgeable(ctx, name, option);
1643       break;
1644    case GL_RENDERBUFFER_EXT:
1645       retval = renderbuffer_purgeable(ctx, name, option);
1646       break;
1647    case GL_BUFFER_OBJECT_APPLE:
1648       retval = buffer_object_purgeable(ctx, name, option);
1649       break;
1650    default:
1651       _mesa_error(ctx, GL_INVALID_ENUM,
1652                   "glObjectPurgeable(name = 0x%x) invalid type: %d",
1653                   name, objectType);
1654       return 0;
1655    }
1656
1657    /* In strict conformance to the spec, we must only return VOLATILE when
1658     * when passed the VOLATILE option. Madness.
1659     *
1660     * XXX First fix the spec, then fix me.
1661     */
1662    return option == GL_VOLATILE_APPLE ? GL_VOLATILE_APPLE : retval;
1663 }
1664
1665
1666 static GLenum
1667 buffer_object_unpurgeable(struct gl_context *ctx, GLuint name, GLenum option)
1668 {
1669    struct gl_buffer_object *bufObj;
1670    GLenum retval;
1671
1672    bufObj = _mesa_lookup_bufferobj(ctx, name);
1673    if (!bufObj) {
1674       _mesa_error(ctx, GL_INVALID_VALUE,
1675                   "glObjectUnpurgeable(name = 0x%x)", name);
1676       return 0;
1677    }
1678
1679    if (! bufObj->Purgeable) {
1680       _mesa_error(ctx, GL_INVALID_OPERATION,
1681                   "glObjectUnpurgeable(name = 0x%x) object is "
1682                   " already \"unpurged\"", name);
1683       return 0;
1684    }
1685
1686    bufObj->Purgeable = GL_FALSE;
1687
1688    retval = option;
1689    if (ctx->Driver.BufferObjectUnpurgeable)
1690       retval = ctx->Driver.BufferObjectUnpurgeable(ctx, bufObj, option);
1691
1692    return retval;
1693 }
1694
1695
1696 static GLenum
1697 renderbuffer_unpurgeable(struct gl_context *ctx, GLuint name, GLenum option)
1698 {
1699    struct gl_renderbuffer *bufObj;
1700    GLenum retval;
1701
1702    bufObj = _mesa_lookup_renderbuffer(ctx, name);
1703    if (!bufObj) {
1704       _mesa_error(ctx, GL_INVALID_VALUE,
1705                   "glObjectUnpurgeable(name = 0x%x)", name);
1706       return 0;
1707    }
1708
1709    if (! bufObj->Purgeable) {
1710       _mesa_error(ctx, GL_INVALID_OPERATION,
1711                   "glObjectUnpurgeable(name = 0x%x) object is "
1712                   " already \"unpurged\"", name);
1713       return 0;
1714    }
1715
1716    bufObj->Purgeable = GL_FALSE;
1717
1718    retval = option;
1719    if (ctx->Driver.RenderObjectUnpurgeable)
1720       retval = ctx->Driver.RenderObjectUnpurgeable(ctx, bufObj, option);
1721
1722    return retval;
1723 }
1724
1725
1726 static GLenum
1727 texture_object_unpurgeable(struct gl_context *ctx, GLuint name, GLenum option)
1728 {
1729    struct gl_texture_object *bufObj;
1730    GLenum retval;
1731
1732    bufObj = _mesa_lookup_texture(ctx, name);
1733    if (!bufObj) {
1734       _mesa_error(ctx, GL_INVALID_VALUE,
1735                   "glObjectUnpurgeable(name = 0x%x)", name);
1736       return 0;
1737    }
1738
1739    if (! bufObj->Purgeable) {
1740       _mesa_error(ctx, GL_INVALID_OPERATION,
1741                   "glObjectUnpurgeable(name = 0x%x) object is"
1742                   " already \"unpurged\"", name);
1743       return 0;
1744    }
1745
1746    bufObj->Purgeable = GL_FALSE;
1747
1748    retval = option;
1749    if (ctx->Driver.TextureObjectUnpurgeable)
1750       retval = ctx->Driver.TextureObjectUnpurgeable(ctx, bufObj, option);
1751
1752    return retval;
1753 }
1754
1755
1756 GLenum GLAPIENTRY
1757 _mesa_ObjectUnpurgeableAPPLE(GLenum objectType, GLuint name, GLenum option)
1758 {
1759    GET_CURRENT_CONTEXT(ctx);
1760    ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, 0);
1761
1762    if (name == 0) {
1763       _mesa_error(ctx, GL_INVALID_VALUE,
1764                   "glObjectUnpurgeable(name = 0x%x)", name);
1765       return 0;
1766    }
1767
1768    switch (option) {
1769    case GL_RETAINED_APPLE:
1770    case GL_UNDEFINED_APPLE:
1771       /* legal */
1772       break;
1773    default:
1774       _mesa_error(ctx, GL_INVALID_ENUM,
1775                   "glObjectUnpurgeable(name = 0x%x) invalid option: %d",
1776                   name, option);
1777       return 0;
1778    }
1779
1780    switch (objectType) {
1781    case GL_BUFFER_OBJECT_APPLE:
1782       return buffer_object_unpurgeable(ctx, name, option);
1783    case GL_TEXTURE:
1784       return texture_object_unpurgeable(ctx, name, option);
1785    case GL_RENDERBUFFER_EXT:
1786       return renderbuffer_unpurgeable(ctx, name, option);
1787    default:
1788       _mesa_error(ctx, GL_INVALID_ENUM,
1789                   "glObjectUnpurgeable(name = 0x%x) invalid type: %d",
1790                   name, objectType);
1791       return 0;
1792    }
1793 }
1794
1795
1796 static void
1797 get_buffer_object_parameteriv(struct gl_context *ctx, GLuint name,
1798                               GLenum pname, GLint *params)
1799 {
1800    struct gl_buffer_object *bufObj = _mesa_lookup_bufferobj(ctx, name);
1801    if (!bufObj) {
1802       _mesa_error(ctx, GL_INVALID_VALUE,
1803                   "glGetObjectParameteriv(name = 0x%x) invalid object", name);
1804       return;
1805    }
1806
1807    switch (pname) {
1808    case GL_PURGEABLE_APPLE:
1809       *params = bufObj->Purgeable;
1810       break;
1811    default:
1812       _mesa_error(ctx, GL_INVALID_ENUM,
1813                   "glGetObjectParameteriv(name = 0x%x) invalid enum: %d",
1814                   name, pname);
1815       break;
1816    }
1817 }
1818
1819
1820 static void
1821 get_renderbuffer_parameteriv(struct gl_context *ctx, GLuint name,
1822                              GLenum pname, GLint *params)
1823 {
1824    struct gl_renderbuffer *rb = _mesa_lookup_renderbuffer(ctx, name);
1825    if (!rb) {
1826       _mesa_error(ctx, GL_INVALID_VALUE,
1827                   "glObjectUnpurgeable(name = 0x%x)", name);
1828       return;
1829    }
1830
1831    switch (pname) {
1832    case GL_PURGEABLE_APPLE:
1833       *params = rb->Purgeable;
1834       break;
1835    default:
1836       _mesa_error(ctx, GL_INVALID_ENUM,
1837                   "glGetObjectParameteriv(name = 0x%x) invalid enum: %d",
1838                   name, pname);
1839       break;
1840    }
1841 }
1842
1843
1844 static void
1845 get_texture_object_parameteriv(struct gl_context *ctx, GLuint name,
1846                                GLenum pname, GLint *params)
1847 {
1848    struct gl_texture_object *texObj = _mesa_lookup_texture(ctx, name);
1849    if (!texObj) {
1850       _mesa_error(ctx, GL_INVALID_VALUE,
1851                   "glObjectUnpurgeable(name = 0x%x)", name);
1852       return;
1853    }
1854
1855    switch (pname) {
1856    case GL_PURGEABLE_APPLE:
1857       *params = texObj->Purgeable;
1858       break;
1859    default:
1860       _mesa_error(ctx, GL_INVALID_ENUM,
1861                   "glGetObjectParameteriv(name = 0x%x) invalid enum: %d",
1862                   name, pname);
1863       break;
1864    }
1865 }
1866
1867
1868 void GLAPIENTRY
1869 _mesa_GetObjectParameterivAPPLE(GLenum objectType, GLuint name, GLenum pname,
1870                                 GLint *params)
1871 {
1872    GET_CURRENT_CONTEXT(ctx);
1873
1874    if (name == 0) {
1875       _mesa_error(ctx, GL_INVALID_VALUE,
1876                   "glGetObjectParameteriv(name = 0x%x)", name);
1877       return;
1878    }
1879
1880    switch (objectType) {
1881    case GL_TEXTURE:
1882       get_texture_object_parameteriv(ctx, name, pname, params);
1883       break;
1884    case GL_BUFFER_OBJECT_APPLE:
1885       get_buffer_object_parameteriv(ctx, name, pname, params);
1886       break;
1887    case GL_RENDERBUFFER_EXT:
1888       get_renderbuffer_parameteriv(ctx, name, pname, params);
1889       break;
1890    default:
1891       _mesa_error(ctx, GL_INVALID_ENUM,
1892                   "glGetObjectParameteriv(name = 0x%x) invalid type: %d",
1893                   name, objectType);
1894    }
1895 }
1896
1897 #endif /* FEATURE_APPLE_object_purgeable */