Content-Security-Policy: default-src 'none' Content-Type: text/plain; charset=UTF-8 Content-Length: 31761 Content-Disposition: inline; filename="H5I.c" Last-Modified: Mon, 02 Sep 2024 06:23:56 GMT Expires: Thu, 31 Aug 2034 06:23:56 GMT ETag: "8697f4f7d22b54e94abcadcab32e10ec7d1faa14" /**************************************************************************** * NCSA HDF * * Software Development Group * * National Center for Supercomputing Applications * * University of Illinois at Urbana-Champaign * * 605 E. Springfield, Champaign IL 61820 * * * * For conditions of distribution and use, see the accompanying * * hdf/COPYING file. * * * ****************************************************************************/ #ifdef RCSID static char RcsId[] = "@(#)$Revision$"; #endif /* $Id$ */ /* * FILE: H5I.c - Internal storage routines for handling "IDs" * * REMARKS: ID's which allow objects (void *'s currently) to be bundled * into "groups" for more general storage. * * DESIGN: The groups are stored in an array of pointers to store each * group in an element. Each "group" node contains a link to a * hash table to manage the IDs in each group. The allowed * "groups" are stored in an enum (called group_t) in * H5Ipublic.h. * * AUTHOR: Quincey Koziol * * MODIFICATIONS: * 1/3/96 - Starting writing specs & coding prototype * 1/7/96 - Finished coding prototype * 6/10/97 - Moved into HDF5 library */ #include #include #include #include /* Interface initialialization? */ #define PABLO_MASK H5I_mask static intn interface_initialize_g = 0; #define INTERFACE_INIT H5I_init_interface static herr_t H5I_init_interface(void); /* * Define the following macro for fast hash calculations (but limited * hash sizes) */ #define HASH_SIZE_POWER_2 /* Define the following macro for atom caching over all the atoms */ #define IDS_ARE_CACHED /*-------------------- Locally scoped variables -----------------------------*/ #ifdef IDS_ARE_CACHED # define ID_CACHE_SIZE 4 /*# of previous atoms cached */ #endif /* * Number of bits to use for Group ID in each atom. Increase if H5I_NGROUPS * becomes too large (an assertion would fail in H5I_init_interface). This is * the only number that must be changed since all other bit field sizes and * masks are calculated from GROUP_BITS. */ #define GROUP_BITS 5 #define GROUP_MASK ((1<>ID_BITS) & GROUP_MASK)) #ifdef HASH_SIZE_POWER_2 /* * Map an ID to a hash location (assumes s is a power of 2 and smaller * than the ID_MASK constant). */ # define H5I_LOC(a,s) ((hid_t)((size_t)(a)&((s)-1))) #else /* * Map an ID to a hash location. */ # define H5I_LOC(a,s) (((hid_t)(a)&ID_MASK)%(s)) #endif /* Combine a Group number and an atom index into an atom */ #define H5I_MAKE(g,i) ((((hid_t)(g)&GROUP_MASK)<id_list) { n++; } } /* If no groups are used then clean up */ if (0==n) { for (grp=(H5I_type_t)0; grpnext; H5MM_xfree(curr); } } /* Mark interface closed */ interface_initialize_g = 0; } return n; } /*------------------------------------------------------------------------- * Function: H5I_init_group * * Purpose: Initialize an ID group whose ID number is specified by GRP, * If the group has already been initialized, this routine just * increments the count of number of initializations and returns * without trying to change the size of the hash table. A * specific number (RESERVED) of group entries may be reserved * to enable "constant" values to be handed out which are valid * IDs in the group, but which do not map to any data structures * and are not allocated dynamicly later. HASH_SIZE is the * minimum hash table size to use for the group. FREE_FUNC is * called with an object pointer when the object is removed from * the group. * * Return: Success: Non-negative * * Failure: Negative * * Programmer: Robb Matzke * Friday, February 19, 1999 * * Modifications: * *------------------------------------------------------------------------- */ intn H5I_init_group(H5I_type_t grp, size_t hash_size, uintn reserved, H5I_free_t free_func) { H5I_id_group_t *grp_ptr = NULL; /*ptr to the atomic group*/ intn ret_value = SUCCEED; /*return value */ FUNC_ENTER(H5I_init_group, FAIL); /* Check arguments */ if ((grp <= H5I_BADID || grp >= H5I_NGROUPS) && hash_size > 0) { HGOTO_DONE(FAIL); } #ifdef HASH_SIZE_POWER_2 /* * If anyone knows a faster test for a power of two, please change this * silly code -QAK */ if (!(hash_size == 2 || hash_size == 4 || hash_size == 8 || hash_size == 16 || hash_size == 32 || hash_size == 64 || hash_size == 128 || hash_size == 256 || hash_size == 512 || hash_size == 1024 || hash_size == 2048 || hash_size == 4096 || hash_size == 8192 || hash_size == 16374 || hash_size == 32768 || hash_size == 65536 || hash_size == 131072 || hash_size == 262144 || hash_size == 524288 || hash_size == 1048576 || hash_size == 2097152 || hash_size == 4194304 || hash_size == 8388608 || hash_size == 16777216 || hash_size == 33554432 || hash_size == 67108864 || hash_size == 134217728 || hash_size == 268435456)) HGOTO_DONE(FAIL); #endif /* HASH_SIZE_POWER_2 */ if (H5I_id_group_list_g[grp] == NULL) { /* Allocate the group information for new group */ if (NULL==(grp_ptr = H5MM_calloc(sizeof(H5I_id_group_t)))) { HGOTO_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed"); } H5I_id_group_list_g[grp] = grp_ptr; } else { /* Get the pointer to the existing group */ grp_ptr = H5I_id_group_list_g[grp]; } if (grp_ptr->count == 0) { /* Initialize the ID group structure for new groups */ grp_ptr->hash_size = hash_size; grp_ptr->reserved = reserved; grp_ptr->wrapped = 0; grp_ptr->ids = 0; grp_ptr->nextid = reserved; grp_ptr->free_func = free_func; grp_ptr->id_list = H5MM_calloc(hash_size*sizeof(H5I_id_info_t *)); if (NULL==grp_ptr->id_list) { HGOTO_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed"); } } /* Increment the count of the times this group has been initialized */ grp_ptr->count++; done: if (ret_value<0) { /* Error condition cleanup */ if (grp_ptr != NULL) { H5MM_xfree(grp_ptr->id_list); H5MM_xfree(grp_ptr); } } FUNC_LEAVE(ret_value); } /*------------------------------------------------------------------------- * Function: H5I_nmembers * * Purpose: Returns the number of members in a group. * * Return: Success: Number of members; zero if the group is empty * or has been deleted. * * Failure: Negative * * Programmer: Robb Matzke * Wednesday, March 24, 1999 * * Modifications: * *------------------------------------------------------------------------- */ intn H5I_nmembers(H5I_type_t grp) { H5I_id_group_t *grp_ptr = NULL; H5I_id_info_t *cur=NULL; intn n=0; uintn i; FUNC_ENTER(H5I_nmembers, FAIL); if (grp<=H5I_BADID || grp>=H5I_NGROUPS) { HRETURN_ERROR(H5E_ARGS, H5E_BADRANGE, FAIL, "invalid group number"); } if (NULL==(grp_ptr=H5I_id_group_list_g[grp]) || grp_ptr->count<=0) { HRETURN(0); } for (i=0; ihash_size; i++) { for (cur=grp_ptr->id_list[i]; cur; cur=cur->next) { n++; } } FUNC_LEAVE(n); } /*------------------------------------------------------------------------- * Function: H5I_clear_group * * Purpose: Removes all objects from the group, calling the free * function for each object regardless of the reference count. * * Return: Success: Non-negative * * Failure: negative * * Programmer: Robb Matzke * Wednesday, March 24, 1999 * * Modifications: * Robb Matzke, 1999-04-27 * If FORCE is zero then any item for which the free callback * failed is not removed. This function returns failure if * items could not be removed. * *------------------------------------------------------------------------- */ herr_t H5I_clear_group(H5I_type_t grp, hbool_t force) { H5I_id_group_t *grp_ptr = NULL; /* ptr to the atomic group */ H5I_id_info_t *cur=NULL, *next=NULL, *prev=NULL; intn ret_value = SUCCEED; uintn i; FUNC_ENTER(H5I_clear_group, FAIL); if (grp <= H5I_BADID || grp >= H5I_NGROUPS) { HGOTO_DONE(FAIL); } grp_ptr = H5I_id_group_list_g[grp]; if (grp_ptr == NULL || grp_ptr->count <= 0) { HGOTO_DONE(FAIL); } #ifdef IDS_ARE_CACHED /* * Remove atoms from the global atom cache. */ for (i=0; iid) == grp) { H5I_cache_g[i] = NULL; } } #endif /* IDS_ARE_CACHED */ /* * Call free method for all objects in group regardless of their reference * counts. Ignore the return value from from the free method and remove * object from group regardless if FORCE is non-zero. */ for (i=0; ihash_size; i++) { for (cur=grp_ptr->id_list[i]; cur; cur=next) { /* Free the object regardless of reference count */ if (grp_ptr->free_func && (grp_ptr->free_func)(cur->obj_ptr)<0) { if (force) { #if H5I_DEBUG if (H5DEBUG(I)) { fprintf(H5DEBUG(I), "H5I: free grp=%d obj=0x%08lx " "failure ignored\n", (int)grp, (unsigned long)(cur->obj_ptr)); } #endif /*H5I_DEBUG*/ /* Add ID struct to free list */ next = cur->next; H5I_release_id_node(cur); } else { if (prev) prev->next = cur; else grp_ptr->id_list[i] = cur; prev = cur; } } else { /* Add ID struct to free list */ next = cur->next; H5I_release_id_node(cur); } } if (!prev) grp_ptr->id_list[i]=NULL; } done: FUNC_LEAVE(ret_value); } /*------------------------------------------------------------------------- * Function: H5I_destroy_group * * Purpose: Decrements the reference count on an entire group of IDs. * If the group reference count becomes zero then the group is * destroyed along with all atoms in that group regardless of * their reference counts. Destroying IDs involves calling * the free-func for each ID's object and then adding the ID * struct to the ID free list. * * Return: Non-negative on success/Negative on failure * * Programmer: Unknown * * Modifications: * * Robb Matzke, 25 Feb 1998 * IDs are freed when a group is destroyed. * *------------------------------------------------------------------------- */ herr_t H5I_destroy_group(H5I_type_t grp) { H5I_id_group_t *grp_ptr = NULL; /* ptr to the atomic group */ intn ret_value = SUCCEED; FUNC_ENTER(H5I_destroy_group, FAIL); if (grp <= H5I_BADID || grp >= H5I_NGROUPS) { HGOTO_DONE(FAIL); } grp_ptr = H5I_id_group_list_g[grp]; if (grp_ptr == NULL || grp_ptr->count <= 0) { HGOTO_DONE(FAIL); } /* * Decrement the number of users of the atomic group. If this is the * last user of the group then release all atoms from the group. The * free function is invoked for each atom being freed. */ if (1==grp_ptr->count) { H5I_clear_group(grp, TRUE); H5E_clear(); /*don't care about errors*/ H5MM_xfree(grp_ptr->id_list); HDmemset (grp_ptr, 0, sizeof(*grp_ptr)); } else { --(grp_ptr->count); } done: FUNC_LEAVE(ret_value); } /*------------------------------------------------------------------------- * Function: H5I_register * * Purpose: Registers an OBJECT in a GROUP and returns an ID for it. * This routine does _not_ check for unique-ness of the objects, * if you register an object twice, you will get two different * IDs for it. This routine does make certain that each ID in a * group is unique. IDs are created by getting a unique number * for the group the ID is in and incorporating the group into * the ID which is returned to the user. * * Return: Success: New object id. * * Failure: Negative * * Programmer: Unknown * * Modifications: * *------------------------------------------------------------------------- */ hid_t H5I_register(H5I_type_t grp, void *object) { H5I_id_group_t *grp_ptr=NULL; /*ptr to the group */ H5I_id_info_t *id_ptr=NULL; /*ptr to the new ID information */ hid_t new_id; /*new ID */ uintn hash_loc; /*new item's hash table location*/ hid_t next_id; /*next ID to check */ hid_t ret_value=SUCCEED; /*return value */ H5I_id_info_t *curr_id; /*ptr to the current atom */ uintn i; /*counter */ FUNC_ENTER(H5I_register, FAIL); /* Check arguments */ if (grp <= H5I_BADID || grp >= H5I_NGROUPS) { HGOTO_DONE(FAIL); } grp_ptr = H5I_id_group_list_g[grp]; if (grp_ptr == NULL || grp_ptr->count <= 0) { HGOTO_DONE(FAIL); } if ((id_ptr = H5I_get_id_node()) == NULL) { HGOTO_DONE(FAIL); } /* Create the struct & it's ID */ new_id = H5I_MAKE(grp, grp_ptr->nextid); id_ptr->id = new_id; id_ptr->count = 1; /*initial reference count*/ id_ptr->obj_ptr = object; id_ptr->next = NULL; /* hash bucket already full, prepend to front of chain */ hash_loc = grp_ptr->nextid % (uintn) grp_ptr->hash_size; if (grp_ptr->id_list[hash_loc] != NULL) { id_ptr->next = grp_ptr->id_list[hash_loc]; } /* Insert into the group */ grp_ptr->id_list[hash_loc] = id_ptr; grp_ptr->ids++; grp_ptr->nextid++; /* * This next section of code checks for the 'nextid' getting too large and * wrapping around, thus necessitating checking for duplicate IDs being * handed out. */ if (grp_ptr->nextid > (uintn)ID_MASK) { grp_ptr->wrapped = 1; grp_ptr->nextid = grp_ptr->reserved; } /* * If we've wrapped around then we need to check for duplicate id's being * handed out. */ if (grp_ptr->wrapped) { /* * Make sure we check all available ID's. If we're about at the end * of the range then wrap around and check the beginning values. If * we check all possible values and didn't find any free ones *then* * we can fail. */ for (i=grp_ptr->reserved; inextid>(uintn)ID_MASK) { grp_ptr->nextid = grp_ptr->reserved; } /* new ID to check for */ next_id = H5I_MAKE(grp, grp_ptr->nextid); hash_loc = H5I_LOC (grp_ptr->nextid, grp_ptr->hash_size); curr_id = grp_ptr->id_list[hash_loc]; if (curr_id == NULL) break; /* Ha! this is not likely... */ while (curr_id) { if (curr_id->id == next_id) break; curr_id = curr_id->next; } if (!curr_id) break; /* must not have found a match */ grp_ptr->nextid++; } if (i>=(uintn)ID_MASK) { /* All the IDs are gone! */ HGOTO_DONE(FAIL); } } ret_value = new_id; done: FUNC_LEAVE(ret_value); } /*------------------------------------------------------------------------- * Function: H5I_object * * Purpose: Find an object pointer for the specified ID. * * Return: Success: Non-null object pointer associated with the * specified ID. * * Failure: NULL * * Programmer: * * Modifications: * *------------------------------------------------------------------------- */ void * H5I_object(hid_t id) { H5I_id_info_t *id_ptr = NULL; /*ptr to the new atom */ void *ret_value = NULL; /*return value */ FUNC_ENTER(H5I_object, NULL); /* General lookup of the ID */ if (NULL==(id_ptr = H5I_find_id(id))) HGOTO_DONE(NULL); /* Check if we've found the correct ID */ if (id_ptr) ret_value = id_ptr->obj_ptr; done: FUNC_LEAVE(ret_value); } /*------------------------------------------------------------------------- * Function: H5I_get_type * * Purpose: Given an object ID return the group (type) to which it * belongs. The ID need not be the ID of an object which * currently exists because the group number (type) is encoded * in the object ID. * * Return: Success: A valid group number (type) * * Failure: H5I_BADID, a negative value. * * Programmer: Robb Matzke * Friday, February 19, 1999 * * Modifications: * *------------------------------------------------------------------------- */ H5I_type_t H5I_get_type(hid_t id) { H5I_type_t ret_value = H5I_BADID; FUNC_ENTER(H5I_get_type, H5I_BADID); if (id>0) ret_value = H5I_GROUP(id); assert(ret_value>=H5I_BADID && ret_value= H5I_NGROUPS) { HGOTO_DONE(H5I_BADID); } done: FUNC_LEAVE(ret_value); } /*------------------------------------------------------------------------- * Function: H5I_remove * * Purpose: Removes the specified ID from its group. * * Return: Success: A pointer to the object that was removed, the * same pointer which would have been found by * calling H5I_object(). * * Failure: NULL * * Programmer: * * Modifications: * *------------------------------------------------------------------------- */ void * H5I_remove(hid_t id) { H5I_id_group_t *grp_ptr = NULL;/*ptr to the atomic group */ H5I_id_info_t *curr_id; /*ptr to the current atom */ H5I_id_info_t *last_id; /*ptr to the last atom */ H5I_type_t grp; /*atom's atomic group */ uintn hash_loc; /*atom's hash table location */ #ifdef IDS_ARE_CACHED uintn i; /*local counting variable */ #endif void * ret_value = NULL; /*return value */ FUNC_ENTER(H5I_remove, NULL); /* Check arguments */ grp = H5I_GROUP(id); if (grp <= H5I_BADID || grp >= H5I_NGROUPS) HGOTO_DONE(NULL); grp_ptr = H5I_id_group_list_g[grp]; if (grp_ptr == NULL || grp_ptr->count <= 0) HGOTO_DONE(NULL); /* Get the bucket in which the ID is located */ hash_loc = (uintn) H5I_LOC(id, grp_ptr->hash_size); curr_id = grp_ptr->id_list[hash_loc]; if (curr_id == NULL) HGOTO_DONE(NULL); last_id = NULL; while (curr_id != NULL) { if (curr_id->id == id) break; last_id = curr_id; curr_id = curr_id->next; } if (curr_id != NULL) { if (last_id == NULL) { /* ID is the first in the chain */ grp_ptr->id_list[hash_loc] = curr_id->next; } else { last_id->next = curr_id->next; } ret_value = curr_id->obj_ptr; H5I_release_id_node(curr_id); } else { /* couldn't find the ID in the proper place */ HGOTO_DONE(NULL); } #ifdef IDS_ARE_CACHED /* Delete object from cache */ for (i = 0; i < ID_CACHE_SIZE; i++) if (H5I_cache_g[i] && H5I_cache_g[i]->id == id) { H5I_cache_g[i] = NULL; break; /* we assume there is only one instance in the cache */ } #endif /* IDS_ARE_CACHED */ /* Decrement the number of IDs in the group */ (grp_ptr->ids)--; done: FUNC_LEAVE(ret_value); } /*------------------------------------------------------------------------- * Function: H5I_dec_ref * * Purpose: Decrements the number of references outstanding for an ID. * This will fail if the group is not a reference counted group. * The ID group's 'free' function will be called for the ID * if the reference count for the ID reaches 0 and a free * function has been defined at group creation time. * * Return: Success: New reference count. * * Failure: Negative * * Programmer: Unknown * * Modifications: * * Robb Matzke, 19 Feb 1998 * It is no longer an error when the reference count of an item reaches * zero and no `free' function has been defined. The object is still * removed from the list. * * Robb Matzke, 30 Dec 1998 * Fixed a bug where the return value was always zero instead of the new * reference count. * * Robb Matzke, 19 Feb 1999 * If the free method is defined and fails then the object is not * removed from the group and its reference count is not decremented. * The group number is now passed to the free method. * *------------------------------------------------------------------------- */ intn H5I_dec_ref(hid_t id) { H5I_type_t grp = H5I_GROUP(id); /*group the object is in*/ H5I_id_group_t *grp_ptr = NULL; /*ptr to the group */ H5I_id_info_t *id_ptr = NULL; /*ptr to the new ID */ intn ret_value = FAIL; /*return value */ FUNC_ENTER(H5I_dec_ref, FAIL); /* Check arguments */ grp_ptr = H5I_id_group_list_g[grp]; if (grp_ptr == NULL || grp_ptr->count <= 0) { HRETURN(FAIL); } /* General lookup of the ID */ if ((id_ptr=H5I_find_id(id))) { /* * If this is the last reference to the object then invoke the group's * free method on the object. If the free method is undefined or * successful then remove the object from the group; otherwise leave * the object in the group without decrementing the reference * count. If the reference count is more than one then decrement the * reference count without calling the free method. * * Beware: the free method may call other H5I functions. */ if (1==id_ptr->count) { if (!grp_ptr->free_func || (grp_ptr->free_func)(id_ptr->obj_ptr)>=0) { H5I_remove(id); ret_value = 0; } else { ret_value = 1; } } else { ret_value = --(id_ptr->count); } } FUNC_LEAVE(ret_value); } /*------------------------------------------------------------------------- * Function: H5I_search * * Purpose: Apply function FUNC to each member of group GRP and return a * pointer to the first object for which FUNC returns non-zero. * The FUNC should take a pointer to the object and the KEY as * arguments and return non-zero to terminate the search (zero * to continue). * * Limitation: Currently there is no way to start searching from where a * previous search left off. * * Return: Success: The first object in the group for which FUNC * returns non-zero. NULL if FUNC returned zero * for every object in the group. * * Failure: NULL * * Programmer: Robb Matzke * Friday, February 19, 1999 * * Modifications: * *------------------------------------------------------------------------- */ void * H5I_search(H5I_type_t grp, H5I_search_func_t func, const void *key) { H5I_id_group_t *grp_ptr = NULL; /*ptr to the group */ H5I_id_info_t *id_ptr = NULL; /*ptr to the new ID */ uintn i; /*counter */ void *ret_value = NULL; /*return value */ FUNC_ENTER(H5I_search, NULL); /* Check arguments */ if (grp <= H5I_BADID || grp >= H5I_NGROUPS) { HGOTO_DONE(NULL); } grp_ptr = H5I_id_group_list_g[grp]; if (grp_ptr == NULL || grp_ptr->count <= 0) { HGOTO_DONE(NULL); } /* Start at the beginning of the array */ for (i=0; ihash_size; i++) { id_ptr = grp_ptr->id_list[i]; while (id_ptr) { if ((*func)(id_ptr->obj_ptr, key)) { HGOTO_DONE(id_ptr->obj_ptr); /*found the item*/ } id_ptr = id_ptr->next; } } done: FUNC_LEAVE(ret_value); } /*------------------------------------------------------------------------- * Function: H5I_find_id * * Purpose: Given an object ID find the info struct that describes the * object. * * Return: Success: Ptr to the object's info struct. * * Failure: NULL * * Programmer: * * Modifications: * *------------------------------------------------------------------------- */ static H5I_id_info_t * H5I_find_id(hid_t id) { H5I_id_group_t *grp_ptr = NULL; /*ptr to the group */ H5I_id_info_t *id_ptr = NULL; /*ptr to the new ID */ H5I_type_t grp; /*ID's group */ uintn hash_loc; /*bucket pointer */ H5I_id_info_t *ret_value = NULL; /*return value */ #ifdef IDS_ARE_CACHED intn i; #endif FUNC_ENTER(H5I_find_id, NULL); /* Check arguments */ grp = H5I_GROUP(id); if (grp <= H5I_BADID || grp >= H5I_NGROUPS) { HGOTO_DONE(NULL); } grp_ptr = H5I_id_group_list_g[grp]; if (grp_ptr == NULL || grp_ptr->count <= 0) { HGOTO_DONE(NULL); } #ifdef IDS_ARE_CACHED /* * Look for the ID in the cache first. Implement a simple "move * forward" caching scheme by swapping the found cache item with the * previous cache item. This gradually migrates used cache items toward * the front of the cache and unused items toward the end. For instance, * finding `e' in the cache results in: * * Before: a b c d e f g h i j * | | | X | | | | | * After: a b c e d f g h i j */ for (i=0; iid == id) { ret_value = H5I_cache_g[i]; if (i > 0) { H5I_id_info_t *tmp = H5I_cache_g[i-1]; H5I_cache_g[i-1] = H5I_cache_g[i]; H5I_cache_g[i] = tmp; } HGOTO_DONE(ret_value); } #endif /* IDS_ARE_CACHED */ /* Get the bucket in which the ID is located */ hash_loc = (uintn)H5I_LOC(id, grp_ptr->hash_size); id_ptr = grp_ptr->id_list[hash_loc]; if (id_ptr == NULL) { HGOTO_DONE(NULL); } /* Scan the bucket's linked list for a match */ while (id_ptr) { if (id_ptr->id == id) break; id_ptr = id_ptr->next; } ret_value = id_ptr; #ifdef IDS_ARE_CACHED /* Add id to the end of the cache */ H5I_cache_g[ID_CACHE_SIZE-1] = id_ptr; #endif /* IDS_ARE_CACHED */ done: FUNC_LEAVE(ret_value); } /*------------------------------------------------------------------------- * Function: H5I_get_id_node * * Purpose: Either gets an ID node from the free list (if there is one * available) or allocate a node. * * Return: Success: ID pointer * * Failure: NULL * * Programmer: * * Modifications: * *------------------------------------------------------------------------- */ static H5I_id_info_t * H5I_get_id_node(void) { H5I_id_info_t *ret_value = NULL; FUNC_ENTER(H5I_get_id_node, NULL); if (H5I_id_free_list_g != NULL) { ret_value = H5I_id_free_list_g; H5I_id_free_list_g = H5I_id_free_list_g->next; } else if (NULL==(ret_value = H5MM_malloc(sizeof(H5I_id_info_t)))) { HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed"); } FUNC_LEAVE(ret_value); } /*------------------------------------------------------------------------- * Function: H5I_release_id_node * * Purpose: Release an ID node and return it to the free list. * * Return: Success: Non-negative * * Failure: Negative * * Programmer: * * Modifications: * *------------------------------------------------------------------------- */ static herr_t H5I_release_id_node(H5I_id_info_t *id) { FUNC_ENTER(H5I_release_id_node, FAIL); /* Insert the ID at the beginning of the free list */ id->next = H5I_id_free_list_g; H5I_id_free_list_g = id; FUNC_LEAVE(SUCCEED); } /*------------------------------------------------------------------------- * Function: H5I_debug * * Purpose: Dump the contents of a group to stderr for debugging. * * Return: Success: Non-negative * * Failure: Negative * * Programmer: Robb Matzke * Friday, February 19, 1999 * * Modifications: * *------------------------------------------------------------------------- */ static herr_t H5I_debug(H5I_type_t grp) { H5I_id_group_t *grp_ptr; H5I_id_info_t *cur; int is, js; unsigned int iu; FUNC_ENTER(H5I_debug, FAIL); fprintf(stderr, "Dumping group %d\n", (int)grp); grp_ptr = H5I_id_group_list_g[grp]; /* Header */ fprintf(stderr, " count = %u\n", grp_ptr->count); fprintf(stderr, " reserved = %u\n", grp_ptr->reserved); fprintf(stderr, " wrapped = %u\n", grp_ptr->wrapped); fprintf(stderr, " hash_size = %lu\n", (unsigned long)grp_ptr->hash_size); fprintf(stderr, " ids = %u\n", grp_ptr->ids); fprintf(stderr, " nextid = %u\n", grp_ptr->nextid); /* Cache */ fprintf(stderr, " Cache:\n"); for (is=0; isid)==grp) { fprintf(stderr, " Entry-%d, ID=%lu\n", is, (unsigned long)(H5I_cache_g[is]->id)); } } /* List */ fprintf(stderr, " List:\n"); for (iu=0; iuhash_size; iu++) { for (js=0, cur=grp_ptr->id_list[iu]; cur; cur=cur->next, js++) { fprintf(stderr, " #%u.%d\n", iu, js); fprintf(stderr, " id = %lu\n", (unsigned long)(cur->id)); fprintf(stderr, " count = %u\n", cur->count); fprintf(stderr, " obj = 0x%08lx\n", (unsigned long)(cur->obj_ptr)); } } FUNC_LEAVE(SUCCEED); } a id='n700' href='#n700'>700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
/*-------------------------------------------------------------------------
 * Copyright (C) 1997	National Center for Supercomputing Applications.
 *			All rights reserved.
 *
 *-------------------------------------------------------------------------
 *
 * Created:		H5O.c
 *			Aug  5 1997
 *			Robb Matzke <matzke@llnl.gov>
 *
 * Purpose:		Object header virtual functions.
 *
 * Modifications:	
 *
 *-------------------------------------------------------------------------
 */
#include <H5private.h>
#include <H5ACprivate.h>
#include <H5Eprivate.h>
#include <H5Fprivate.h>
#include <H5Iprivate.h>
#include <H5MFprivate.h>
#include <H5MMprivate.h>
#include <H5Oprivate.h>

#define PABLO_MASK	H5O_mask

/* PRIVATE PROTOTYPES */
static herr_t H5O_flush(H5F_t *f, hbool_t destroy, const haddr_t *addr,
			H5O_t *oh);
static H5O_t *H5O_load(H5F_t *f, const haddr_t *addr, const void *_udata1,
		       void *_udata2);
static intn H5O_find_in_ohdr(H5F_t *f, const haddr_t *addr,
			     const H5O_class_t **type_p, intn sequence);
static intn H5O_alloc(H5F_t *f, H5O_t *oh, const H5O_class_t *type,
		      size_t size);
static intn H5O_alloc_extend_chunk(H5O_t *oh, intn chunkno, size_t size);
static intn H5O_alloc_new_chunk(H5F_t *f, H5O_t *oh, size_t size);
static herr_t H5O_touch_oh(H5F_t *f, H5O_t *oh, hbool_t force);

/* H5O inherits cache-like properties from H5AC */
static const H5AC_class_t H5AC_OHDR[1] = {{
    H5AC_OHDR_ID,
    (void *(*)(H5F_t *, const haddr_t *, const void *, void *)) H5O_load,
    (herr_t (*)(H5F_t *, hbool_t, const haddr_t *, void *)) H5O_flush,
}};

/* Interface initialization */
static intn interface_initialize_g = 0;
#define INTERFACE_INIT	H5O_init_interface
static herr_t H5O_init_interface(void);

/* ID to type mapping */
static const H5O_class_t *const message_type_g[] = {
    H5O_NULL,		/*0x0000 Null					*/
    H5O_SDSPACE,	/*0x0001 Simple Dimensionality			*/
    NULL,		/*0x0002 Data space (fiber bundle?)		*/
    H5O_DTYPE,		/*0x0003 Data Type				*/
    H5O_FILL,		/*0x0004 Data storage -- fill value		*/
    NULL,		/*0x0005 Not assigned				*/
    NULL,		/*0x0006 Data storage -- compact object		*/
    H5O_EFL,		/*0x0007 Data storage -- external data files	*/
    H5O_LAYOUT,		/*0x0008 Data Layout				*/
    NULL,		/*0x0009 Not assigned				*/
    NULL,		/*0x000A Not assigned				*/
    H5O_PLINE,		/*0x000B Data storage -- filter pipeline	*/
    H5O_ATTR,		/*0x000C Attribute list				*/
    H5O_NAME,		/*0x000D Object name				*/
    H5O_MTIME,		/*0x000E Object modification date and time	*/
    NULL,		/*0x000F Shared header message			*/
    H5O_CONT,		/*0x0010 Object header continuation		*/
    H5O_STAB,		/*0x0011 Symbol table				*/
};

/*
 * An array of functions indexed by symbol table entry cache type
 * (H5G_type_t) that are called to retrieve constant messages cached in the
 * symbol table entry.
 */
static void *(*H5O_fast_g[H5G_NCACHED]) (const H5G_cache_t *,
					 const H5O_class_t *,
					 void *);

/*-------------------------------------------------------------------------
 * Function:	H5O_init_interface
 *
 * Purpose:	Initialize the H5O interface.
 *
 * Return:	Non-negative on success/Negative on failure
 *
 * Programmer:	Robb Matzke
 *		Tuesday, January  6, 1998
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
static herr_t
H5O_init_interface(void)
{
    FUNC_ENTER(H5O_init_interface, FAIL);

    /*
     * Initialize functions that decode messages from symbol table entries.
     */
    H5O_fast_g[H5G_CACHED_STAB] = H5O_stab_fast;

    FUNC_LEAVE(SUCCEED);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_create
 *
 * Purpose:	Creates a new object header, sets the link count
 *		to 0, and caches the header.  The object header is opened for
 *		write access and should eventually be closed by calling
 *		H5O_close().
 *
 * Return:	Success:	Non-negative, the ENT argument contains
 *				information about the object header,
 *				including its address.
 *
 *		Failure:	Negative
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug  5 1997
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_create(H5F_t *f, size_t size_hint, H5G_entry_t *ent/*out*/)
{
    size_t	size;	/*total size of object header	*/
    H5O_t	*oh = NULL;
    haddr_t	tmp_addr;

    FUNC_ENTER(H5O_create, FAIL);

    /* check args */
    assert(f);
    assert(ent);
    HDmemset(ent, 0, sizeof(H5G_entry_t));
    size_hint = H5O_ALIGN (MAX (H5O_MIN_SIZE, size_hint));

    /* allocate disk space for header and first chunk */
    size = H5O_SIZEOF_HDR(f) + size_hint;
    ent->file = f;
    if (H5MF_alloc(f, H5MF_META, (hsize_t)size, &(ent->header)/*out*/) < 0) {
	HRETURN_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL,
		      "file allocation failed for object header header");
    }
    
    /* allocate the object header and fill in header fields */
    if (NULL==(oh = H5MM_calloc(sizeof(H5O_t)))) {
	HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
		       "memory allocation failed");
    }
    oh->dirty = TRUE;
    oh->version = H5O_VERSION;
    oh->nlink = 0;

    /* create the chunk list and initialize the first chunk */
    oh->nchunks = 1;
    oh->alloc_nchunks = H5O_NCHUNKS;
    if (NULL==(oh->chunk=H5MM_malloc(oh->alloc_nchunks*sizeof(H5O_chunk_t)))) {
	HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
		       "memory allocation failed");
    }
    tmp_addr = ent->header;
    H5F_addr_inc(&tmp_addr, (hsize_t)H5O_SIZEOF_HDR(f));
    oh->chunk[0].dirty = TRUE;
    oh->chunk[0].addr = tmp_addr;
    oh->chunk[0].size = size_hint;
    if (NULL==(oh->chunk[0].image = H5MM_calloc(size_hint))) {
	HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
		       "memory allocation failed");
    }
    
    /* create the message list and initialize the first message */
    oh->nmesgs = 1;
    oh->alloc_nmesgs = H5O_NMESGS;
    if (NULL==(oh->mesg=H5MM_calloc(oh->alloc_nmesgs*sizeof(H5O_mesg_t)))) {
	HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
		       "memory allocation failed");
    }
    oh->mesg[0].type = H5O_NULL;
    oh->mesg[0].dirty = TRUE;
    oh->mesg[0].native = NULL;
    oh->mesg[0].raw = oh->chunk[0].image + H5O_SIZEOF_MSGHDR(f);
    oh->mesg[0].raw_size = size_hint - H5O_SIZEOF_MSGHDR(f);
    oh->mesg[0].chunkno = 0;

    /* cache it */
    if (H5AC_set(f, H5AC_OHDR, &(ent->header), oh) < 0) {
	H5MM_xfree(oh);
	HRETURN_ERROR(H5E_OHDR, H5E_CANTINIT, FAIL,
		      "unable to cache object header");
    }

    /* open it */
    if (H5O_open(ent) < 0) {
	HRETURN_ERROR(H5E_OHDR, H5E_CANTOPENOBJ, FAIL,
		      "unable to open object header");
    }
    FUNC_LEAVE(SUCCEED);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_open
 *
 * Purpose:	Opens an object header which is described by the symbol table
 *		entry OBJ_ENT.
 *
 * Return:	Non-negative on success/Negative on failure
 *
 * Programmer:	Robb Matzke
 *		Monday, January	 5, 1998
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_open(H5G_entry_t *obj_ent)
{
    FUNC_ENTER(H5O_open, FAIL);

    /* Check args */
    assert(obj_ent);
    assert(obj_ent->file);

#ifdef H5O_DEBUG
    if (H5DEBUG(O)) {
	HDfprintf(H5DEBUG(O), "> %a\n", &(obj_ent->header));
    }
#endif

    /* Increment open-lock counters */
    obj_ent->file->nopen_objs++;
    FUNC_LEAVE(SUCCEED);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_close
 *
 * Purpose:	Closes an object header that was previously open.
 *
 * Return:	Non-negative on success/Negative on failure
 *
 * Programmer:	Robb Matzke
 *		Monday, January	 5, 1998
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_close(H5G_entry_t *obj_ent)
{
    FUNC_ENTER(H5O_close, FAIL);

    /* Check args */
    assert(obj_ent);
    assert(obj_ent->file);
    assert(obj_ent->file->nopen_objs > 0);

    /* Decrement open-lock counters */
    --obj_ent->file->nopen_objs;

#ifdef H5O_DEBUG
    if (H5DEBUG(O)) {
	if (obj_ent->file->closing && 1==obj_ent->file->shared->nrefs) {
	    HDfprintf(H5DEBUG(O), "< %a auto %lu remaining\n",
		      &(obj_ent->header),
		      (unsigned long)(obj_ent->file->nopen_objs));
	} else {
	    HDfprintf(H5DEBUG(O), "< %a\n", &(obj_ent->header));
	}
    }
#endif
    
    /*
     * If the file open-lock count has reached zero and the file has a close
     * pending then close the file and remove it from the H5I_FILE_CLOSING ID
     * group.
     */
    if (0==obj_ent->file->nopen_objs && obj_ent->file->closing) {
	H5I_dec_ref(obj_ent->file->closing);
    }

    FUNC_LEAVE(SUCCEED);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_load
 *
 * Purpose:	Loads an object header from disk.
 *
 * Return:	Success:	Pointer to the new object header.
 *
 *		Failure:	NULL
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug  5 1997
 *
 * Modifications:
 *
 *	Robb Matzke, 30 Aug 1997
 *	Plugged memory leaks that occur during error handling.
 *
 *	Robb Matzke, 7 Jan 1998
 *	Able to distinguish between constant and variable messages.
 *
 *-------------------------------------------------------------------------
 */
static H5O_t *
H5O_load(H5F_t *f, const haddr_t *addr, const void UNUSED *_udata1,
	 void UNUSED *_udata2)
{
    H5O_t	*oh = NULL;
    H5O_t	*ret_value = NULL;
    uint8_t	buf[16], *p;
    size_t	hdr_size, mesg_size;
    uintn	id;
    intn	mesgno, chunkno, curmesg = 0, nmesgs;
    haddr_t	chunk_addr;
    size_t	chunk_size;
    H5O_cont_t	*cont = NULL;
    uint8_t	flags;

    FUNC_ENTER(H5O_load, NULL);

    /* check args */
    assert(f);
    assert(addr && H5F_addr_defined(addr));
    assert(!_udata1);
    assert(!_udata2);

    /* allocate ohdr and init chunk list */
    if (NULL==(oh = H5MM_calloc(sizeof(H5O_t)))) {
	HGOTO_ERROR (H5E_RESOURCE, H5E_NOSPACE, NULL,
		     "memory allocation failed");
    }

    /* read fixed-lenth part of object header */
    hdr_size = H5O_SIZEOF_HDR(f);
    if (H5F_block_read(f, addr, (hsize_t)hdr_size, &H5F_xfer_dflt, buf) < 0) {
	HGOTO_ERROR(H5E_OHDR, H5E_READERROR, NULL,
		    "unable to read object header");
    }
    p = buf;

    /* decode version */
    oh->version = *p++;
    if (H5O_VERSION != oh->version) {
	HGOTO_ERROR(H5E_OHDR, H5E_VERSION, NULL,
		    "bad object header version number");
    }
    
    /* reserved */
    p++;
    
    /* decode number of messages */
    UINT16DECODE(p, nmesgs);

    /* decode link count */
    UINT32DECODE(p, oh->nlink);

    /* decode first chunk info */
    chunk_addr = *addr;
    H5F_addr_inc(&chunk_addr, (hsize_t)H5O_SIZEOF_HDR(f));
    UINT32DECODE(p, chunk_size);

    /* build the message array */
    oh->alloc_nmesgs = MAX(H5O_NMESGS, nmesgs);
    if (NULL==(oh->mesg=H5MM_calloc(oh->alloc_nmesgs*sizeof(H5O_mesg_t)))) {
	HGOTO_ERROR (H5E_RESOURCE, H5E_NOSPACE, NULL,
		     "memory allocation failed");
    }

    /* read each chunk from disk */
    while (H5F_addr_defined(&chunk_addr)) {

	/* increase chunk array size */
	if (oh->nchunks >= oh->alloc_nchunks) {
	    size_t na = oh->alloc_nchunks + H5O_NCHUNKS;
	    H5O_chunk_t *x = H5MM_realloc (oh->chunk, na*sizeof(H5O_chunk_t));
	    if (!x) {
		HGOTO_ERROR (H5E_RESOURCE, H5E_NOSPACE, NULL,
			     "memory allocation failed");
	    }
	    oh->alloc_nchunks = (intn)na;
	    oh->chunk = x;
	}
	
	/* read the chunk raw data */
	chunkno = oh->nchunks++;
	oh->chunk[chunkno].dirty = FALSE;
	oh->chunk[chunkno].addr = chunk_addr;
	oh->chunk[chunkno].size = chunk_size;
	if (NULL==(oh->chunk[chunkno].image = H5MM_malloc(chunk_size))) {
	    HGOTO_ERROR (H5E_RESOURCE, H5E_NOSPACE, NULL,
			 "memory allocation failed");
	}
	if (H5F_block_read(f, &chunk_addr, (hsize_t)chunk_size, &H5F_xfer_dflt,
			   oh->chunk[chunkno].image) < 0) {
	    HGOTO_ERROR(H5E_OHDR, H5E_READERROR, NULL,
			"unable to read object header data");
	}
	
	/* load messages from this chunk */
	for (p = oh->chunk[chunkno].image;
	     p < oh->chunk[chunkno].image + chunk_size;
	     p += mesg_size) {
	    UINT16DECODE(p, id);
	    UINT16DECODE(p, mesg_size);
	    assert (mesg_size==H5O_ALIGN (mesg_size));
	    flags = *p++;
	    p += 3; /*reserved*/

	    if (id >= NELMTS(message_type_g) || NULL == message_type_g[id]) {
		HGOTO_ERROR(H5E_OHDR, H5E_BADMESG, NULL,
			    "corrupt object header");
	    }
	    if (p + mesg_size > oh->chunk[chunkno].image + chunk_size) {
		HGOTO_ERROR(H5E_OHDR, H5E_CANTINIT, NULL,
			    "corrupt object header");
	    }
	    if (H5O_NULL_ID == id && oh->nmesgs > 0 &&
		H5O_NULL_ID == oh->mesg[oh->nmesgs - 1].type->id &&
		oh->mesg[oh->nmesgs - 1].chunkno == chunkno) {
		/* combine adjacent null messages */
		mesgno = oh->nmesgs - 1;
		oh->mesg[mesgno].raw_size += H5O_SIZEOF_MSGHDR(f) + mesg_size;
	    } else {
		/* new message */
		if (oh->nmesgs >= nmesgs) {
		    HGOTO_ERROR(H5E_OHDR, H5E_CANTLOAD, NULL,
				"corrupt object header");
		}
		mesgno = oh->nmesgs++;
		oh->mesg[mesgno].type = message_type_g[id];
		oh->mesg[mesgno].dirty = FALSE;
		oh->mesg[mesgno].flags = flags;
		oh->mesg[mesgno].native = NULL;
		oh->mesg[mesgno].raw = p;
		oh->mesg[mesgno].raw_size = mesg_size;
		oh->mesg[mesgno].chunkno = chunkno;
	    }
	}
	assert(p == oh->chunk[chunkno].image + chunk_size);

	/* decode next object header continuation message */
	for (H5F_addr_undef(&chunk_addr);
	     !H5F_addr_defined(&chunk_addr) && curmesg < oh->nmesgs;
	     curmesg++) {
	    if (H5O_CONT_ID == oh->mesg[curmesg].type->id) {
		uint8_t *p2 = oh->mesg[curmesg].raw;
		cont = (H5O_CONT->decode) (f, p2, NULL);
		oh->mesg[curmesg].native = cont;
		chunk_addr = cont->addr;
		chunk_size = cont->size;
		cont->chunkno = oh->nchunks;	/*the next chunk to allocate */
	    }
	}
    }
    ret_value = oh;

  done:
    if (!ret_value && oh) {
	/*
	 * Free resources.
	 */
	int i;
	for (i = 0; i < oh->nchunks; i++) {
	    oh->chunk[i].image = H5MM_xfree(oh->chunk[i].image);
	}
	oh->chunk = H5MM_xfree(oh->chunk);
	oh->mesg = H5MM_xfree(oh->mesg);
	oh = H5MM_xfree(oh);
    }
    FUNC_LEAVE(ret_value);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_flush
 *
 * Purpose:	Flushes (and destroys) an object header.
 *
 * Return:	Non-negative on success/Negative on failure
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug  5 1997
 *
 * Modifications:
 *
 *	Robb Matzke, 7 Jan 1998
 *	Handles constant vs non-constant messages.
 *
 *      rky 980828 Only p0 writes metadata to disk.
 *
 *-------------------------------------------------------------------------
 */
static herr_t
H5O_flush(H5F_t *f, hbool_t destroy, const haddr_t *addr, H5O_t *oh)
{
    uint8_t	buf[16], *p;
    intn	i, id;
    H5O_cont_t	*cont = NULL;
    herr_t	(*encode)(H5F_t*, uint8_t*, const void*) = NULL;

    FUNC_ENTER(H5O_flush, FAIL);

    /* check args */
    assert(f);
    assert(addr && H5F_addr_defined(addr));
    assert(oh);

    /* flush */
    if (oh->dirty) {
	p = buf;

	/* encode version */
	*p++ = oh->version;

	/* reserved */
	*p++ = 0;

	/* encode number of messages */
	UINT16ENCODE(p, oh->nmesgs);

	/* encode link count */
	UINT32ENCODE(p, oh->nlink);

	/* encode body size */
	UINT32ENCODE(p, oh->chunk[0].size);

	/* zero to alignment */
	HDmemset (p, 0, H5O_SIZEOF_HDR(f)-12);

	/* write the object header header */
#ifdef HAVE_PARALLEL
	H5F_mpio_tas_allsame( f->shared->lf, TRUE );	/* only p0 will write */
#endif /* HAVE_PARALLEL */
	if (H5F_block_write(f, addr, (hsize_t)H5O_SIZEOF_HDR(f), 
			    &H5F_xfer_dflt, buf) < 0) {
	    HRETURN_ERROR(H5E_OHDR, H5E_WRITEERROR, FAIL,
			  "unable to write object header hdr to disk");
	}
	
	/* encode messages */
	for (i = 0; i < oh->nmesgs; i++) {
	    if (oh->mesg[i].dirty) {
		p = oh->mesg[i].raw - H5O_SIZEOF_MSGHDR(f);

		id = oh->mesg[i].type->id;
		UINT16ENCODE(p, id);
		assert (oh->mesg[i].raw_size<65536);
		UINT16ENCODE(p, oh->mesg[i].raw_size);
		*p++ = oh->mesg[i].flags;
		*p++ = 0; /*reserved*/
		*p++ = 0; /*reserved*/
		*p++ = 0; /*reserved*/
		
		if (oh->mesg[i].native) {
		    assert(oh->mesg[i].type->encode);

		    /* allocate file space for chunks that have none yet */
		    if (H5O_CONT_ID == oh->mesg[i].type->id &&
			!H5F_addr_defined(&(((H5O_cont_t *)
					     (oh->mesg[i].native))->addr))) {
			cont = (H5O_cont_t *) (oh->mesg[i].native);
			assert(cont->chunkno >= 0);
			assert(cont->chunkno < oh->nchunks);
			assert(!H5F_addr_defined(&(oh->chunk[cont->chunkno].addr)));
			cont->size = oh->chunk[cont->chunkno].size;
			if (H5MF_alloc(f, H5MF_META, (hsize_t)(cont->size),
				       &(cont->addr)/*out*/) < 0) {
			    HRETURN_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL,
				      "unable to allocate space for object "
					  "header data");
			}
			oh->chunk[cont->chunkno].addr = cont->addr;
		    }
		    
		    /*
		     * Encode the message.  If the message is shared then we
		     * encode a Shared Object message instead of the object
		     * which is being shared.
		     */
		    assert(oh->mesg[i].raw >=
			   oh->chunk[oh->mesg[i].chunkno].image);
		    assert (oh->mesg[i].raw_size ==
			    H5O_ALIGN (oh->mesg[i].raw_size));
		    assert(oh->mesg[i].raw + oh->mesg[i].raw_size <=
			   oh->chunk[oh->mesg[i].chunkno].image +
			   oh->chunk[oh->mesg[i].chunkno].size);
		    if (oh->mesg[i].flags & H5O_FLAG_SHARED) {
			encode = H5O_SHARED->encode;
		    } else {
			encode = oh->mesg[i].type->encode;
		    }
		    if ((encode)(f, oh->mesg[i].raw, oh->mesg[i].native)<0) {
			HRETURN_ERROR(H5E_OHDR, H5E_CANTENCODE, FAIL,
				  "unable to encode object header message");
		    }
		}
		oh->mesg[i].dirty = FALSE;
		oh->chunk[oh->mesg[i].chunkno].dirty = TRUE;
	    }
	}

	/* write each chunk to disk */
	for (i = 0; i < oh->nchunks; i++) {
	    if (oh->chunk[i].dirty) {
		assert(H5F_addr_defined(&(oh->chunk[i].addr)));
#ifdef HAVE_PARALLEL
		H5F_mpio_tas_allsame( f->shared->lf, TRUE ); /* only p0 write */
#endif /* HAVE_PARALLEL */
		if (H5F_block_write(f, &(oh->chunk[i].addr),
				    (hsize_t)(oh->chunk[i].size),
				    &H5F_xfer_dflt, oh->chunk[i].image) < 0) {
		    HRETURN_ERROR(H5E_OHDR, H5E_WRITEERROR, FAIL,
			      "unable to write object header data to disk");
		}
		oh->chunk[i].dirty = FALSE;
	    }
	}
	oh->dirty = FALSE;
    }

    if (destroy) {
	/* destroy chunks */
	for (i = 0; i < oh->nchunks; i++) {
	    oh->chunk[i].image = H5MM_xfree(oh->chunk[i].image);
	}
	oh->chunk = H5MM_xfree(oh->chunk);

	/* destroy messages */
	for (i = 0; i < oh->nmesgs; i++) {
	    if (oh->mesg[i].flags & H5O_FLAG_SHARED) {
		H5O_reset (H5O_SHARED, oh->mesg[i].native);
	    } else {
		H5O_reset(oh->mesg[i].type, oh->mesg[i].native);
	    }
	    oh->mesg[i].native = H5MM_xfree(oh->mesg[i].native);
	}
	oh->mesg = H5MM_xfree(oh->mesg);

	/* destroy object header */
	H5MM_xfree(oh);
    }
    FUNC_LEAVE(SUCCEED);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_reset
 *
 * Purpose:	Some message data structures have internal fields that
 *		need to be freed.  This function does that if appropriate
 *		but doesn't free NATIVE.
 *
 * Return:	Non-negative on success/Negative on failure
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug 12 1997
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_reset(const H5O_class_t *type, void *native)
{
    FUNC_ENTER(H5O_reset, FAIL);

    if (native) {
	if (type->reset) {
	    if ((type->reset) (native) < 0) {
		HRETURN_ERROR(H5E_OHDR, H5E_CANTINIT, FAIL,
			      "reset method failed");
	    }
	} else {
	    HDmemset(native, 0, type->native_size);
	}
    }
    FUNC_LEAVE(SUCCEED);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_free
 *
 * Purpose:	Similar to H5O_reset() except it also frees the message
 *		pointer.
 *
 * Return:	Success:	NULL
 *
 *		Failure:	NULL
 *
 * Programmer:	Robb Matzke
 *              Thursday, May 21, 1998
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
void *
H5O_free (const H5O_class_t *type, void *mesg)
{
    FUNC_ENTER (H5O_free, NULL);
    
    if (mesg) {
	H5O_reset (type, mesg);
	H5MM_xfree (mesg);
    }

    FUNC_LEAVE (NULL);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_copy
 *
 * Purpose:	Copies a message.  If MESG is is the null pointer then a null
 *		pointer is returned with no error.
 *
 * Return:	Success:	Ptr to the new message
 *
 *		Failure:	NULL
 *
 * Programmer:	Robb Matzke
 *              Thursday, May 21, 1998
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
void *
H5O_copy (const H5O_class_t *type, const void *mesg, void *dst)
{
    void	*ret_value = NULL;
    
    FUNC_ENTER (H5O_copy, NULL);

    assert (type);
    assert (type->copy);

    if (mesg) {
	if (NULL==(ret_value=(type->copy)(mesg, dst))) {
	    HRETURN_ERROR (H5E_OHDR, H5E_CANTINIT, NULL,
			   "unable to copy object header message");
	}
    }

    FUNC_LEAVE (ret_value);
}



/*-------------------------------------------------------------------------
 * Function:	H5O_link
 *
 * Purpose:	Adjust the link count for an object header by adding
 *		ADJUST to the link count.
 *
 * Return:	Success:	New link count
 *
 *		Failure:	Negative
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug  5 1997
 *
 * Modifications:
 *
 * 	Robb Matzke, 1998-08-27
 *	This function can also be used to obtain the current number of links
 *	if zero is passed for ADJUST.  If that's the case then we don't check
 *	for write access on the file.
 *
 *-------------------------------------------------------------------------
 */
intn
H5O_link(H5G_entry_t *ent, intn adjust)
{
    H5O_t	*oh = NULL;
    intn	ret_value = FAIL;

    FUNC_ENTER(H5O_link, FAIL);

    /* check args */
    assert(ent);
    assert(ent->file);
    assert(H5F_addr_defined(&(ent->header)));
    if (adjust!=0 && 0==(ent->file->intent & H5F_ACC_RDWR)) {
	HGOTO_ERROR (H5E_OHDR, H5E_WRITEERROR, FAIL,
		     "no write intent on file");
    }

    /* get header */
    if (NULL == (oh = H5AC_protect(ent->file, H5AC_OHDR, &(ent->header),
				   NULL, NULL))) {
	HGOTO_ERROR(H5E_OHDR, H5E_CANTLOAD, FAIL,
		    "unable to load object header");
    }

    /* adjust link count */
    if (adjust<0) {
	if (oh->nlink + adjust < 0) {
	    HGOTO_ERROR(H5E_OHDR, H5E_LINKCOUNT, FAIL,
			"link count would be negative");
	}
	oh->nlink += adjust;
	oh->dirty = TRUE;
    } else if (adjust>0) {
	oh->nlink += adjust;
	oh->dirty = TRUE;
    }

    ret_value = oh->nlink;
  done:
    if (oh && H5AC_unprotect(ent->file, H5AC_OHDR, &(ent->header), oh) < 0) {
	HRETURN_ERROR(H5E_OHDR, H5E_PROTECT, FAIL,
		      "unable to release object header");
    }
    FUNC_LEAVE(ret_value);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_count
 *
 * Purpose:	Counts the number of messages in an object header which are a
 *		certain type.
 *
 * Return:	Success:	Number of messages of specified type.
 *
 *		Failure:	Negative
 *
 * Programmer:	Robb Matzke
 *              Tuesday, April 21, 1998
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
intn
H5O_count (H5G_entry_t *ent, const H5O_class_t *type)
{
    H5O_t	*oh = NULL;
    intn	i, acc;
    
    FUNC_ENTER (H5O_count, FAIL);

    /* Check args */
    assert (ent);
    assert (ent->file);
    assert (H5F_addr_defined (&(ent->header)));
    assert (type);

    /* Load the object header */
    if (NULL==(oh=H5AC_find (ent->file, H5AC_OHDR, &(ent->header),
			     NULL, NULL))) {
	HRETURN_ERROR (H5E_OHDR, H5E_CANTLOAD, FAIL,
		       "unable to load object header");
    }

    for (i=acc=0; i<oh->nmesgs; i++) {
	if (oh->mesg[i].type==type) acc++;
    }

    FUNC_LEAVE (acc);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_exists
 *
 * Purpose:	Determines if a particular message exists in an object
 *		header without trying to decode the message.
 *
 * Return:	Success:	FALSE if the message does not exist; TRUE if
 *				th message exists.
 *
 *		Failure:	FAIL if the existence of the message could
 *				not be determined due to some error such as
 *				not being able to read the object header.
 *
 * Programmer:	Robb Matzke
 *              Monday, November  2, 1998
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
htri_t
H5O_exists(H5G_entry_t *ent, const H5O_class_t *type, intn sequence)
{
    H5O_t	*oh=NULL;
    intn	i;
    
    FUNC_ENTER(H5O_exists, FAIL);
    assert(ent);
    assert(ent->file);
    assert(type);
    assert(sequence>=0);

    /* Load the object header */
    if (NULL==(oh=H5AC_find(ent->file, H5AC_OHDR, &(ent->header),
			    NULL, NULL))) {
	HRETURN_ERROR(H5E_OHDR, H5E_CANTLOAD, FAIL,
		      "unable to load object header");
    }

    /* Scan through the messages looking for the right one */
    for (i=0; i<oh->nmesgs; i++) {
	if (type->id!=oh->mesg[i].type->id) continue;
	if (--sequence<0) break;
    }

    FUNC_LEAVE(sequence<0);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_read
 *
 * Purpose:	Reads a message from an object header and returns a pointer
 *		to it.	The caller will usually supply the memory through
 *		MESG and the return value will be MESG.	 But if MESG is
 *		the null pointer, then this function will malloc() memory
 *		to hold the result and return its pointer instead.
 *
 * Return:	Success:	Ptr to message in native format.  The message
 *				should be freed by calling H5O_reset().  If
 *				MESG is a null pointer then the caller should
 *				also call H5MM_xfree() on the return value
 *				after calling H5O_reset().
 *
 *		Failure:	NULL
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug  6 1997
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
void *
H5O_read(H5G_entry_t *ent, const H5O_class_t *type, intn sequence, void *mesg)
{
    H5O_t		*oh = NULL;
    void		*ret_value = NULL;
    intn		idx;
    H5G_cache_t		*cache = NULL;
    H5G_type_t		cache_type;

    FUNC_ENTER(H5O_read, NULL);

    /* check args */
    assert(ent);
    assert(ent->file);
    assert(H5F_addr_defined(&(ent->header)));
    assert(type);
    assert(sequence >= 0);

    /* can we get it from the symbol table entry? */
    cache = H5G_ent_cache(ent, &cache_type);
    if (H5O_fast_g[cache_type]) {
	ret_value = (H5O_fast_g[cache_type]) (cache, type, mesg);
	if (ret_value)
	    HRETURN(ret_value);
	H5E_clear(); /*don't care, try reading from header */
    }

    /* can we get it from the object header? */
    if ((idx = H5O_find_in_ohdr(ent->file, &(ent->header), &type,
				sequence)) < 0) {
	HRETURN_ERROR(H5E_OHDR, H5E_NOTFOUND, NULL,
		      "unable to find message in object header");
    }

    /* copy the message to the user-supplied buffer */
    if (NULL == (oh = H5AC_protect(ent->file, H5AC_OHDR, &(ent->header),
				   NULL, NULL))) {
	HRETURN_ERROR(H5E_OHDR, H5E_CANTLOAD, NULL,
		      "unable to load object header");
    }
    if (oh->mesg[idx].flags & H5O_FLAG_SHARED) {
	/*
	 * If the message is shared then then the native pointer points to an
	 * H5O_SHARED message.  We use that information to look up the real
	 * message in the global heap or some other object header.
	 */
	H5O_shared_t *shared;
	void *tmp_buf, *tmp_mesg;

	shared = (H5O_shared_t *)(oh->mesg[idx].native);
	if (shared->in_gh) {
	    if (NULL==(tmp_buf = H5HG_read (ent->file, &(shared->u.gh),
					    NULL))) {
		HGOTO_ERROR (H5E_OHDR, H5E_CANTLOAD, NULL,
			     "unable to read shared message from global heap");
	    }
	    tmp_mesg = (type->decode)(ent->file, tmp_buf, shared);
	    tmp_buf = H5MM_xfree (tmp_buf);
	    if (!tmp_mesg) {
		HGOTO_ERROR (H5E_OHDR, H5E_CANTLOAD, NULL,
			     "unable to decode object header shared message");
	    }
	    if (mesg) {
		HDmemcpy (mesg, tmp_mesg, type->native_size);
		H5MM_xfree (tmp_mesg);
	    } else {
		ret_value = tmp_mesg;
	    }
	} else {
	    ret_value = H5O_read (&(shared->u.ent), type, 0, mesg);
	    if (type->set_share &&
		(type->set_share)(ent->file, ret_value, shared)<0) {
		HGOTO_ERROR (H5E_OHDR, H5E_CANTINIT, NULL,
			     "unable to set sharing information");
	    }
	}
    } else {
	/*
	 * The message is not shared, but rather exists in the object
	 * header.  The object header caches the native message (along with
	 * the raw message) so we must copy the native message before
	 * returning.
	 */
	if (NULL==(ret_value = (type->copy) (oh->mesg[idx].native, mesg))) {
	    HGOTO_ERROR (H5E_OHDR, H5E_CANTINIT, NULL,
			 "unable to copy message to user space");
	}
    }

 done:
    if (H5AC_unprotect(ent->file, H5AC_OHDR, &(ent->header), oh) < 0) {
	HRETURN_ERROR(H5E_OHDR, H5E_PROTECT, NULL,
		      "unable to release object header");
    }
    oh = NULL;
    FUNC_LEAVE(ret_value);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_find_in_ohdr
 *
 * Purpose:	Find a message in the object header without consulting
 *		a symbol table entry.
 *
 * Return:	Success:	Index number of message.
 *
 *		Failure:	Negative
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug  6 1997
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
static intn
H5O_find_in_ohdr(H5F_t *f, const haddr_t *addr, const H5O_class_t **type_p,
		 intn sequence)
{
    H5O_t		*oh = NULL;
    int			i;
    const H5O_class_t	*type = NULL;

    FUNC_ENTER(H5O_find_in_ohdr, FAIL);

    /* Check args */
    assert(f);
    assert(addr && H5F_addr_defined(addr));
    assert(type_p);

    /* Load the object header */
    if (NULL == (oh = H5AC_find(f, H5AC_OHDR, addr, NULL, NULL))) {
	HRETURN_ERROR(H5E_OHDR, H5E_CANTLOAD, FAIL,
		      "unable to load object header");
    }

    /* Scan through the messages looking for the right one */
    for (i = 0; i < oh->nmesgs; i++) {
	if (*type_p && (*type_p)->id != oh->mesg[i].type->id) continue;
	if (--sequence < 0) break;
    }
    if (sequence >= 0) {
	HRETURN_ERROR(H5E_OHDR, H5E_NOTFOUND, FAIL,
		      "unable to find object header message");
    }

    /*
     * Decode the message if necessary.  If the message is shared then decode
     * a shared message, ignoring the message type.
     */
    if (oh->mesg[i].flags & H5O_FLAG_SHARED) {
	type = H5O_SHARED;
    } else {
	type = oh->mesg[i].type;
    }
    if (NULL == oh->mesg[i].native) {
	assert(type->decode);
	oh->mesg[i].native = (type->decode) (f, oh->mesg[i].raw, NULL);
	if (NULL == oh->mesg[i].native) {
	    HRETURN_ERROR(H5E_OHDR, H5E_CANTDECODE, FAIL,
			  "unable to decode message");
	}
    }

    /*
     * Return the message type. If this is a shared message then return the
     * pointed-to type.
     */
    *type_p = oh->mesg[i].type;
    FUNC_LEAVE(i);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_modify
 *
 * Purpose:	Modifies an existing message or creates a new message.
 *		The cache fields in that symbol table entry ENT are *not*
 *		updated, you must do that separately because they often
 *		depend on multiple object header messages.  Besides, we
 *		don't know which messages will be constant and which will
 *		not.
 *
 *		The OVERWRITE argument is either a sequence number of a
 *		message to overwrite (usually zero) or the constant
 *		H5O_NEW_MESG (-1) to indicate that a new message is to
 *		be created.  If the message to overwrite doesn't exist then
 *		it is created (but only if it can be inserted so its sequence
 *		number is OVERWRITE; that is, you can create a message with
 *		the sequence number 5 if there is no message with sequence
 *		number 4).
 *
 * Return:	Success:	The sequence number of the message that
 *				was modified or created.
 *
 *		Failure:	Negative
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug  6 1997
 *
 * Modifications:
 *
 *	Robb Matzke, 7 Jan 1998
 *	Handles constant vs non-constant messages.  Once a message is made
 *	constant it can never become non-constant.  Constant messages cannot
 *	be modified.
 *
 *-------------------------------------------------------------------------
 */
intn
H5O_modify(H5G_entry_t *ent, const H5O_class_t *type, intn overwrite,
	   uintn flags, const void *mesg)
{
    H5O_t		*oh = NULL;
    intn		idx, sequence;
    intn		ret_value = FAIL;
    size_t		size = 0;
    H5O_shared_t	*sh_mesg = NULL;

    FUNC_ENTER(H5O_modify, FAIL);

    /* check args */
    assert(ent);
    assert(ent->file);
    assert(H5F_addr_defined(&(ent->header)));
    assert(type);
    assert(mesg);
    assert (0==(flags & ~H5O_FLAG_BITS));
    if (0==(ent->file->intent & H5F_ACC_RDWR)) {
	HGOTO_ERROR (H5E_OHDR, H5E_WRITEERROR, FAIL,
		     "no write intent on file");
    }

    if (NULL == (oh = H5AC_protect(ent->file, H5AC_OHDR, &(ent->header),
				   NULL, NULL))) {
	HGOTO_ERROR(H5E_OHDR, H5E_CANTLOAD, FAIL,
		    "unable to load object header");
    }

    /* Count similar messages */
    for (idx = 0, sequence = -1; idx < oh->nmesgs; idx++) {
	if (type->id != oh->mesg[idx].type->id) continue;
	if (++sequence == overwrite) break;
    }

    /* Was the right message found? */
    if (overwrite >= 0 &&
	(idx >= oh->nmesgs || sequence != overwrite)) {

	/* But can we insert a new one with this sequence number? */
	if (overwrite == sequence + 1) {
	    overwrite = -1;
	} else {
	    HGOTO_ERROR(H5E_OHDR, H5E_NOTFOUND, FAIL, "message not found");
	}
    }
    if (overwrite < 0) {
	/* Allocate space for the new message */
	if (flags & H5O_FLAG_SHARED) {
	    if (NULL==type->get_share) {
		HGOTO_ERROR (H5E_OHDR, H5E_UNSUPPORTED, FAIL,
			     "message class is not sharable");
	    }
	    if (NULL==(sh_mesg = H5MM_calloc (sizeof *sh_mesg))) {
		HGOTO_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
			     "memory allocation failed");
	    }
	    if ((type->get_share)(ent->file, mesg, sh_mesg/*out*/)<0) {
		/*
		 * If the message isn't shared then turn off the shared bit
		 * and treat it as an unshared message.
		 */
		H5E_clear ();
		flags &= ~H5O_FLAG_SHARED;
	    } else if (sh_mesg->in_gh) {
		/*
		 * The shared message is stored in the global heap.
		 * Increment the reference count on the global heap message.
		 */
		if (H5HG_link (ent->file, &(sh_mesg->u.gh), 1)<0) {
		    HGOTO_ERROR (H5E_OHDR, H5E_LINK, FAIL,
				 "unable to adjust shared object link count");
		}
		size = (H5O_SHARED->raw_size)(ent->file, sh_mesg);
	    } else {
		/*
		 * The shared message is stored in some other object header.
		 * The other object header must be in the same file as the
		 * new object header. Increment the reference count on that
		 * object header.
		 */
		if (sh_mesg->u.ent.file->shared != ent->file->shared) {
		    HGOTO_ERROR(H5E_OHDR, H5E_LINK, FAIL,
				"interfile hard links are not allowed");
		}
		if (H5O_link (&(sh_mesg->u.ent), 1)<0) {
		    HGOTO_ERROR (H5E_OHDR, H5E_LINK, FAIL,
				 "unable to adjust shared object link count");
		}
		size = (H5O_SHARED->raw_size)(ent->file, sh_mesg);
	    }
	}
	if (0==(flags & H5O_FLAG_SHARED)) {
	    size = (type->raw_size) (ent->file, mesg);
	    if (size>=65536) {
		HGOTO_ERROR (H5E_OHDR, H5E_CANTINIT, FAIL,
			     "object header message is too large (16k max)");
	    }
	}
	size = H5O_ALIGN(size);
	idx = H5O_alloc(ent->file, oh, type, size);
	if (idx < 0) {
	    HGOTO_ERROR(H5E_OHDR, H5E_CANTINIT, FAIL,
			"unable to allocate space for message");
	}
	sequence++;
	    
    } else if (oh->mesg[idx].flags & H5O_FLAG_CONSTANT) {
	HGOTO_ERROR(H5E_OHDR, H5E_WRITEERROR, FAIL,
		    "unable to modify constant message");
    } else if (oh->mesg[idx].flags & H5O_FLAG_SHARED) {
	HGOTO_ERROR (H5E_OHDR, H5E_WRITEERROR, FAIL,
		     "unable to modify shared (constant) message");
    }
    

    /* Copy the native value into the object header */
    if (flags & H5O_FLAG_SHARED) {
	oh->mesg[idx].native = sh_mesg;
	sh_mesg = NULL;
    } else {
	if (oh->mesg[idx].native) {
	    H5O_reset (oh->mesg[idx].type, oh->mesg[idx].native);
	}
	oh->mesg[idx].native = (type->copy) (mesg, oh->mesg[idx].native);
	if (NULL == oh->mesg[idx].native) {
	    HGOTO_ERROR(H5E_OHDR, H5E_CANTINIT, FAIL,
			"unable to copy message to object header");
	}
    }

    /* Update the modification time message if any */
    H5O_touch_oh(ent->file, oh, FALSE);
    
    oh->mesg[idx].flags = flags;
    oh->mesg[idx].dirty = TRUE;
    oh->dirty = TRUE;
    ret_value = sequence;

  done:
    H5MM_xfree(sh_mesg);
    if (oh && H5AC_unprotect(ent->file, H5AC_OHDR, &(ent->header), oh) < 0) {
	HRETURN_ERROR(H5E_OHDR, H5E_PROTECT, FAIL,
		      "unable to release object header");
    }
    
    FUNC_LEAVE(ret_value);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_touch_oh
 *
 * Purpose:	If FORCE is non-zero then create a modification time message
 *		unless one already exists.  Then update any existing
 *		modification time message with the current time.
 *
 * Return:	Non-negative on success/Negative on failure
 *
 * Programmer:	Robb Matzke
 *              Monday, July 27, 1998
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
static herr_t
H5O_touch_oh(H5F_t *f, H5O_t *oh, hbool_t force)
{
    intn	idx;
    time_t	now = HDtime(NULL);
    size_t	size;
    
    FUNC_ENTER(H5O_touch_oh, FAIL);
    assert(oh);

    /* Look for existing message */
    for (idx=0; idx<oh->nmesgs; idx++) {
	if (H5O_MTIME==oh->mesg[idx].type) break;
    }

    /* Create a new message */
    if (idx==oh->nmesgs) {
	if (!force) HRETURN(SUCCEED); /*nothing to do*/
	size = (H5O_MTIME->raw_size)(f, &now);
	size = H5O_ALIGN(size);
	if ((idx=H5O_alloc(f, oh, H5O_MTIME, size))<0) {
	    HRETURN_ERROR(H5E_OHDR, H5E_CANTINIT, FAIL,
			  "unable to allocate space for modification time "
			  "message");
	}
    }

    /* Update the native part */
    if (NULL==oh->mesg[idx].native) {
	if (NULL==(oh->mesg[idx].native = H5MM_malloc(sizeof(time_t)))) {
	    HRETURN_ERROR(H5E_OHDR, H5E_CANTINIT, FAIL,
			  "memory allocation failed for modification time "
			  "message");
	}
    }
    *((time_t*)(oh->mesg[idx].native)) = now;
    oh->mesg[idx].dirty = TRUE;
    oh->dirty = TRUE;

    FUNC_LEAVE(SUCCEED);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_touch
 *
 * Purpose:	Touch an object by setting the modification time to the
 *		current time and marking the object as dirty.  Unless FORCE
 *		is non-zero, nothing happens if there is no MTIME message in
 *		the object header.
 *
 * Return:	Non-negative on success/Negative on failure
 *
 * Programmer:	Robb Matzke
 *              Monday, July 27, 1998
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_touch(H5G_entry_t *ent, hbool_t force)
{
    H5O_t	*oh = NULL;
    herr_t	ret_value = FAIL;
    
    FUNC_ENTER(H5O_touch, FAIL);

    /* check args */
    assert(ent);
    assert(ent->file);
    assert(H5F_addr_defined(&(ent->header)));
    if (0==(ent->file->intent & H5F_ACC_RDWR)) {
	HGOTO_ERROR(H5E_OHDR, H5E_WRITEERROR, FAIL,
		    "no write intent on file");
    }

    /* Get the object header */
    if (NULL==(oh=H5AC_protect(ent->file, H5AC_OHDR, &(ent->header),
			       NULL, NULL))) {
	HGOTO_ERROR(H5E_OHDR, H5E_CANTLOAD, FAIL,
		    "unable to load object header");
    }

    /* Create/Update the modification time message */
    if (H5O_touch_oh(ent->file, oh, force)<0) {
	HGOTO_ERROR(H5E_OHDR, H5E_CANTINIT, FAIL,
		    "unable to update object modificaton time");
    }
    ret_value = SUCCEED;

 done:
    if (oh && H5AC_unprotect(ent->file, H5AC_OHDR, &(ent->header), oh)<0) {
	HRETURN_ERROR(H5E_OHDR, H5E_PROTECT, FAIL,
		      "unable to release object header");
    }
    FUNC_LEAVE(ret_value);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_remove
 *
 * Purpose:	Removes the specified message from the object header.
 *		If sequence is H5O_ALL (-1) then all messages of the
 *		specified type are removed.  Removing a message causes
 *		the sequence numbers to change for subsequent messages of
 *		the same type.
 *
 *		No attempt is made to join adjacent free areas of the
 *		object header into a single larger free area.
 *
 * Return:	Non-negative on success/Negative on failure
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug 28 1997
 *
 * Modifications:
 *
 *	Robb Matzke, 7 Jan 1998
 *	Does not remove constant messages.
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_remove(H5G_entry_t *ent, const H5O_class_t *type, intn sequence)
{
    H5O_t		*oh = NULL;
    intn		i, seq, nfailed = 0;
    herr_t		ret_value = FAIL;
    H5O_shared_t	*sh_mesg = NULL;

    FUNC_ENTER(H5O_remove, FAIL);

    /* check args */
    assert(ent);
    assert(ent->file);
    assert(H5F_addr_defined(&(ent->header)));
    assert(type);
    if (0==(ent->file->intent & H5F_ACC_RDWR)) {
	HRETURN_ERROR (H5E_HEAP, H5E_WRITEERROR, FAIL,
		       "no write intent on file");
    }

    /* load the object header */
    if (NULL == (oh = H5AC_protect(ent->file, H5AC_OHDR, &(ent->header),
				   NULL, NULL))) {
	HGOTO_ERROR(H5E_OHDR, H5E_CANTLOAD, FAIL,
		    "unable to load object header");
    }
    
    for (i = seq = 0; i < oh->nmesgs; i++) {
	if (type->id != oh->mesg[i].type->id) continue;
	if (seq++ == sequence || H5O_ALL == sequence) {
	    /*
	     * Keep track of how many times we failed trying to remove constant
	     * messages.
	     */
	    if (oh->mesg[i].flags & H5O_FLAG_CONSTANT) {
		nfailed++;
		continue;
	    }

	    if (oh->mesg[i].flags & H5O_FLAG_SHARED) {
		if (NULL==oh->mesg[i].native) {
		    sh_mesg = (H5O_SHARED->decode)(ent->file, oh->mesg[i].raw,
						   NULL);
		    if (NULL==(oh->mesg[i].native = sh_mesg)) {
			HGOTO_ERROR (H5E_OHDR, H5E_CANTDECODE, FAIL,
				     "unable to decode shared message info");
		    }
		}
		if (sh_mesg->in_gh) {
		    if (H5HG_link (ent->file, &(sh_mesg->u.gh), -1)<0) {
			HGOTO_ERROR (H5E_OHDR, H5E_LINK, FAIL,
				     "unable to decrement link count on "
				     "shared message");
		    }
		} else {
		    if (H5O_link (&(sh_mesg->u.ent), -1)<0) {
			HGOTO_ERROR (H5E_OHDR, H5E_LINK, FAIL,
				     "unable to decrement link count on "
				     "shared message");
		    }
		}
	    }

	    /* change message type to nil and zero it */
	    oh->mesg[i].type = H5O_NULL;
	    HDmemset(oh->mesg[i].raw, 0, oh->mesg[i].raw_size);
	    oh->mesg[i].native = H5O_free (type, oh->mesg[i].native);
	    oh->mesg[i].dirty = TRUE;
	    oh->dirty = TRUE;
	    H5O_touch_oh(ent->file, oh, FALSE);
	}
    }

    /* Fail if we tried to remove any constant messages */
    if (nfailed) {
	HGOTO_ERROR(H5E_OHDR, H5E_CANTINIT, FAIL,
		    "unable to remove constant message(s)");
    }
    ret_value = SUCCEED;

  done:
    if (oh && H5AC_unprotect(ent->file, H5AC_OHDR, &(ent->header), oh) < 0) {
	HRETURN_ERROR(H5E_OHDR, H5E_PROTECT, FAIL,
		      "unable to release object header");
    }
    FUNC_LEAVE(ret_value);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_alloc_extend_chunk
 *
 * Purpose:	Extends a chunk which hasn't been allocated on disk yet
 *		to make the chunk large enough to contain a message whose
 *		data size is at least SIZE bytes.
 *
 *		If the last message of the chunk is the null message, then
 *		that message will be extended with the chunk.  Otherwise a
 *		new null message is created.
 *
 * Return:	Success:	Message index for null message which
 *				is large enough to hold SIZE bytes.
 *
 *		Failure:	Negative
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug  7 1997
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
static intn
H5O_alloc_extend_chunk(H5O_t *oh, intn chunkno, size_t size)
{
    intn	idx, i;
    size_t	delta;
    uint8_t	*old_addr;

    FUNC_ENTER(H5O_alloc_extend_chunk, FAIL);

    /* check args */
    assert(oh);
    assert(chunkno >= 0 && chunkno < oh->nchunks);
    assert(size > 0);
    assert (size==H5O_ALIGN (size));

    if (H5F_addr_defined(&(oh->chunk[chunkno].addr))) {
	HRETURN_ERROR(H5E_OHDR, H5E_NOSPACE, FAIL, "chunk is on disk");
    }

    /* try to extend a null message */
    for (idx=0; idx<oh->nmesgs; idx++) {
	if (H5O_NULL_ID == oh->mesg[idx].type->id &&
	    (oh->mesg[idx].raw + oh->mesg[idx].raw_size ==
	     oh->chunk[chunkno].image + oh->chunk[chunkno].size)) {

	    delta = MAX (H5O_MIN_SIZE, size - oh->mesg[idx].raw_size);
	    assert (delta=H5O_ALIGN (delta));
	    oh->mesg[idx].dirty = TRUE;
	    oh->mesg[idx].raw_size += delta;

	    old_addr = oh->chunk[chunkno].image;

	    /* Be careful not to indroduce garbage */
	    oh->chunk[chunkno].image = H5MM_realloc(old_addr,
						    (oh->chunk[chunkno].size +
						     delta));
	    if (NULL==oh->chunk[chunkno].image) {
		HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
			       "memory allocation failed");
	    }
	    HDmemset(oh->chunk[chunkno].image + oh->chunk[chunkno].size,
		     0, delta);
	    oh->chunk[chunkno].size += delta;

	    /* adjust raw addresses for messages of this chunk */
	    if (old_addr != oh->chunk[chunkno].image) {
		for (i = 0; i < oh->nmesgs; i++) {
		    if (oh->mesg[i].chunkno == chunkno) {
			oh->mesg[i].raw = oh->chunk[chunkno].image +
					  (oh->mesg[i].raw - old_addr);
		    }
		}
	    }
	    HRETURN(idx);
	}
    }

    /* create a new null message */
    if (oh->nmesgs >= oh->alloc_nmesgs) {
	size_t na = oh->alloc_nmesgs + H5O_NMESGS;
	H5O_mesg_t *x = H5MM_realloc (oh->mesg, na*sizeof(H5O_mesg_t));
	if (NULL==x) {
	    HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
			   "memory allocation failed");
	}
	oh->alloc_nmesgs = (intn)na;
	oh->mesg = x;
    }
    delta = MAX(H5O_MIN_SIZE, size+H5O_SIZEOF_MSGHDR(f));
    delta = H5O_ALIGN(delta);
    idx = oh->nmesgs++;
    oh->mesg[idx].type = H5O_NULL;
    oh->mesg[idx].dirty = TRUE;
    oh->mesg[idx].native = NULL;
    oh->mesg[idx].raw = oh->chunk[chunkno].image +
			oh->chunk[chunkno].size +
			H5O_SIZEOF_MSGHDR(f);
    oh->mesg[idx].raw_size = delta - H5O_SIZEOF_MSGHDR(f);
    oh->mesg[idx].chunkno = chunkno;

    old_addr = oh->chunk[chunkno].image;
    oh->chunk[chunkno].size += delta;
    oh->chunk[chunkno].image = H5MM_realloc(old_addr,
					    oh->chunk[chunkno].size);
    if (NULL==oh->chunk[chunkno].image) {
	HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
		       "memory allocation failed");
    }
    
    /* adjust raw addresses for messages of this chunk */
    if (old_addr != oh->chunk[chunkno].image) {
	for (i = 0; i < oh->nmesgs; i++) {
	    if (oh->mesg[i].chunkno == chunkno) {
		oh->mesg[i].raw = oh->chunk[chunkno].image +
		    (oh->mesg[i].raw - old_addr);
	    }
	}
    }
    FUNC_LEAVE(idx);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_alloc_new_chunk
 *
 * Purpose:	Allocates a new chunk for the object header but doen't
 *		give the new chunk a file address yet.	One of the other
 *		chunks will get an object continuation message.	 If there
 *		isn't room in any other chunk for the object continuation
 *		message, then some message from another chunk is moved into
 *		this chunk to make room.
 *
 * Return:	Success:	Index number of the null message for the
 *				new chunk.  The null message will be at
 *				least SIZE bytes not counting the message
 *				ID or size fields.
 *
 *		Failure:	Negative
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug  7 1997
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
static intn
H5O_alloc_new_chunk(H5F_t *f, H5O_t *oh, size_t size)
{
    size_t	cont_size;		/*continuation message size	*/
    intn	found_null = (-1);	/*best fit null message		*/
    intn	found_other = (-1);	/*best fit other message	*/
    intn	idx = FAIL;		/*message number return value	*/
    uint8_t	*p = NULL;		/*ptr into new chunk		*/
    H5O_cont_t	*cont = NULL;		/*native continuation message	*/
    intn	i, chunkno;

    FUNC_ENTER(H5O_alloc_new_chunk, FAIL);

    /* check args */
    assert (oh);
    assert (size > 0);
    assert (size == H5O_ALIGN (size));

    /*
     * Find the smallest null message that will hold an object
     * continuation message.  Failing that, find the smallest message
     * that could be moved to make room for the continuation message.
     * Don't ever move continuation message from one chunk to another.
     */
    cont_size = H5O_ALIGN (H5F_SIZEOF_ADDR(f) + H5F_SIZEOF_SIZE(f));
    for (i=0; i<oh->nmesgs; i++) {
	if (H5O_NULL_ID == oh->mesg[i].type->id) {
	    if (cont_size == oh->mesg[i].raw_size) {
		found_null = i;
		break;
	    } else if (oh->mesg[i].raw_size >= cont_size &&
		       (found_null < 0 ||
			(oh->mesg[i].raw_size <
			 oh->mesg[found_null].raw_size))) {
		found_null = i;
	    }
	} else if (H5O_CONT_ID == oh->mesg[i].type->id) {
	    /*don't consider continuation messages */
	} else if (oh->mesg[i].raw_size >= cont_size &&
		   (found_other < 0 ||
		    oh->mesg[i].raw_size < oh->mesg[found_other].raw_size)) {
	    found_other = i;
	}
    }
    assert(found_null >= 0 || found_other >= 0);

    /*
     * If we must move some other message to make room for the null
     * message, then make sure the new chunk has enough room for that
     * other message.
     */
    if (found_null < 0)
	size += H5O_SIZEOF_MSGHDR(f) + oh->mesg[found_other].raw_size;

    /*
     * The total chunk size must include the requested space plus enough
     * for the message header.	This must be at least some minimum and a
     * multiple of the alignment size.
     */
    size = MAX(H5O_MIN_SIZE, size + H5O_SIZEOF_MSGHDR(f));
    assert (size == H5O_ALIGN (size));

    /*
     * Create the new chunk without giving it a file address.
     */
    if (oh->nchunks >= oh->alloc_nchunks) {
	size_t na = oh->alloc_nchunks + H5O_NCHUNKS;
	H5O_chunk_t *x = H5MM_realloc (oh->chunk, na*sizeof(H5O_chunk_t));
	if (!x) {
	    HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
			   "memory allocation failed");
	}
	oh->alloc_nchunks = (intn)na;
	oh->chunk = x;
    }
    chunkno = oh->nchunks++;
    oh->chunk[chunkno].dirty = TRUE;
    H5F_addr_undef(&(oh->chunk[chunkno].addr));
    oh->chunk[chunkno].size = size;
    if (NULL==(oh->chunk[chunkno].image = p = H5MM_calloc(size))) {
	HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
		       "memory allocation failed");
    }
    
    /*
     * Make sure we have enough space for all possible new messages
     * that could be generated below.
     */
    if (oh->nmesgs + 3 > oh->alloc_nmesgs) {
        int old_alloc=oh->alloc_nmesgs;
	size_t na = oh->alloc_nmesgs + MAX (H5O_NMESGS, 3);
	H5O_mesg_t *x = H5MM_realloc (oh->mesg, na*sizeof(H5O_mesg_t));
	if (!x) {
	    HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
			   "memory allocation failed");
	}
        oh->alloc_nmesgs = (intn)na;
        oh->mesg = x;

        /* Set new object header info to zeros */
        HDmemset(&oh->mesg[old_alloc], 0,
		 (oh->alloc_nmesgs-old_alloc)*sizeof(H5O_mesg_t));
    }

    /*
     * Describe the messages of the new chunk.
     */
    if (found_null < 0) {
	found_null = i = oh->nmesgs++;
	oh->mesg[i].type = H5O_NULL;
	oh->mesg[i].dirty = TRUE;
	oh->mesg[i].native = NULL;
	oh->mesg[i].raw = oh->mesg[found_other].raw;
	oh->mesg[i].raw_size = oh->mesg[found_other].raw_size;
	oh->mesg[i].chunkno = oh->mesg[found_other].chunkno;

	oh->mesg[found_other].dirty = TRUE;
	oh->mesg[found_other].raw = p + H5O_SIZEOF_MSGHDR(f);
	oh->mesg[found_other].chunkno = chunkno;
	p += H5O_SIZEOF_MSGHDR(f) + oh->mesg[found_other].raw_size;
	size -= H5O_SIZEOF_MSGHDR(f) + oh->mesg[found_other].raw_size;
    }
    idx = oh->nmesgs++;
    oh->mesg[idx].type = H5O_NULL;
    oh->mesg[idx].dirty = TRUE;
    oh->mesg[idx].native = NULL;
    oh->mesg[idx].raw = p + H5O_SIZEOF_MSGHDR(f);
    oh->mesg[idx].raw_size = size - H5O_SIZEOF_MSGHDR(f);
    oh->mesg[idx].chunkno = chunkno;

    /*
     * If the null message that will receive the continuation message
     * is larger than the continuation message, then split it into
     * two null messages.
     */
    if (oh->mesg[found_null].raw_size > cont_size) {
	i = oh->nmesgs++;
	oh->mesg[i].type = H5O_NULL;
	oh->mesg[i].dirty = TRUE;
	oh->mesg[i].native = NULL;
	oh->mesg[i].raw = oh->mesg[found_null].raw +
			  cont_size +
			  H5O_SIZEOF_MSGHDR(f);
	oh->mesg[i].raw_size = oh->mesg[found_null].raw_size -
			       (cont_size + H5O_SIZEOF_MSGHDR(f));
	oh->mesg[i].chunkno = oh->mesg[found_null].chunkno;

	oh->mesg[found_null].dirty = TRUE;
	oh->mesg[found_null].raw_size = cont_size;
    }

    /*
     * Initialize the continuation message.
     */
    oh->mesg[found_null].type = H5O_CONT;
    oh->mesg[found_null].dirty = TRUE;
    if (NULL==(cont = H5MM_calloc(sizeof(H5O_cont_t)))) {
	HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
		       "memory allocation failed");
    }
    H5F_addr_undef(&(cont->addr));
    cont->size = 0;
    cont->chunkno = chunkno;
    oh->mesg[found_null].native = cont;

    FUNC_LEAVE(idx);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_alloc
 *
 * Purpose:	Allocate enough space in the object header for this message.
 *
 * Return:	Success:	Index of message
 *
 *		Failure:	Negative
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug  6 1997
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
static intn
H5O_alloc(H5F_t *f, H5O_t *oh, const H5O_class_t *type, size_t size)
{
    intn	chunkno;
    intn	idx;
    intn	null_idx;

    FUNC_ENTER(H5O_alloc, FAIL);

    /* check args */
    assert (oh);
    assert (type);
    assert (size == H5O_ALIGN (size));

    /* look for a null message which is large enough */
    for (idx = 0; idx < oh->nmesgs; idx++) {
	if (H5O_NULL_ID == oh->mesg[idx].type->id &&
	    oh->mesg[idx].raw_size >= size)
	    break;
    }

#ifdef LATER
    /*
     * Perhaps if we join adjacent null messages we could make one
     * large enough... we leave this as an exercise for future
     * programmers :-)	This isn't a high priority because when an
     * object header is read from disk the null messages are combined
     * anyway.
     */
#endif

    /* if we didn't find one, then allocate more header space */
    if (idx >= oh->nmesgs) {
	/*
	 * Look for a chunk which hasn't had disk space allocated yet
	 * since we can just increase the size of that chunk.
	 */
	for (chunkno = 0; chunkno < oh->nchunks; chunkno++) {
	    if ((idx = H5O_alloc_extend_chunk(oh, chunkno, size)) >= 0) {
		break;
	    }
	    H5E_clear();
	}

	/*
	 * Create a new chunk
	 */
	if (idx < 0) {
	    if ((idx = H5O_alloc_new_chunk(f, oh, size)) < 0) {
		HRETURN_ERROR(H5E_OHDR, H5E_NOSPACE, FAIL,
			 "unable to create a new object header data chunk");
	    }
	}
    }

    /* do we need to split the null message? */
    if (oh->mesg[idx].raw_size > size) {
	assert(oh->mesg[idx].raw_size - size >= H5O_SIZEOF_MSGHDR(f));

	if (oh->nmesgs >= oh->alloc_nmesgs) {
	    int old_alloc=oh->alloc_nmesgs;
	    size_t na = oh->alloc_nmesgs + H5O_NMESGS;
	    H5O_mesg_t *x = H5MM_realloc (oh->mesg, na*sizeof(H5O_mesg_t));
	    if (!x) {
		HRETURN_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
			       "memory allocation failed");
	    }
	    oh->alloc_nmesgs = (intn)na;
	    oh->mesg = x;

	    /* Set new object header info to zeros */
	    HDmemset(&oh->mesg[old_alloc],0,
		     (oh->alloc_nmesgs-old_alloc)*sizeof(H5O_mesg_t));
	}
	null_idx = oh->nmesgs++;
	oh->mesg[null_idx].type = H5O_NULL;
	oh->mesg[null_idx].dirty = TRUE;
	oh->mesg[null_idx].native = NULL;
	oh->mesg[null_idx].raw = oh->mesg[idx].raw +
				 size +
				 H5O_SIZEOF_MSGHDR(f);
	oh->mesg[null_idx].raw_size = oh->mesg[idx].raw_size -
				      (size + H5O_SIZEOF_MSGHDR(f));
	oh->mesg[null_idx].chunkno = oh->mesg[idx].chunkno;
	oh->mesg[idx].raw_size = size;
    }

    /* initialize the new message */
    oh->mesg[idx].type = type;
    oh->mesg[idx].dirty = TRUE;
    oh->mesg[idx].native = NULL;

    oh->dirty = TRUE;
    FUNC_LEAVE(idx);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_share
 *
 * Purpose:	Writes a message to the global heap.
 *
 * Return:	Success:	Non-negative, and HOBJ describes the global heap
 *				object.
 *
 *		Failure:	Negative
 *
 * Programmer:	Robb Matzke
 *              Thursday, April  2, 1998
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_share (H5F_t *f, const H5O_class_t *type, const void *mesg,
	   H5HG_t *hobj/*out*/)
{
    size_t	size;
    void	*buf = NULL;
    herr_t	ret_value = FAIL;
    
    FUNC_ENTER (H5O_share, FAIL);

    /* Check args */
    assert (f);
    assert (type);
    assert (mesg);
    assert (hobj);

    /* Encode the message put it in the global heap */
    if ((size = (type->raw_size)(f, mesg))>0) {
	if (NULL==(buf = H5MM_malloc (size))) {
	    HGOTO_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
			 "memory allocation failed");
	}
	if ((type->encode)(f, buf, mesg)<0) {
	    HGOTO_ERROR (H5E_OHDR, H5E_CANTENCODE, FAIL,
			 "unable to encode message");
	}
	if (H5HG_insert (f, size, buf, hobj)<0) {
	    HGOTO_ERROR (H5E_OHDR, H5E_CANTINIT, FAIL,
			 "unable to store message in global heap");
	}
    }
    ret_value = SUCCEED;

 done:
    H5MM_xfree (buf);
    FUNC_LEAVE (ret_value);
}


/*-------------------------------------------------------------------------
 * Function:	H5O_debug
 *
 * Purpose:	Prints debugging info about an object header.
 *
 * Return:	Non-negative on success/Negative on failure
 *
 * Programmer:	Robb Matzke
 *		matzke@llnl.gov
 *		Aug  6 1997
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
herr_t
H5O_debug(H5F_t *f, const haddr_t *addr, FILE * stream, intn indent,
	  intn fwidth)
{
    H5O_t	*oh = NULL;
    intn	i, chunkno;
    size_t	mesg_total = 0, chunk_total = 0;
    int		*sequence;
    haddr_t	tmp_addr;
    herr_t	ret_value = FAIL;
    void	*(*decode)(H5F_t*, const uint8_t*, H5O_shared_t*);
    herr_t      (*debug)(H5F_t*, const void*, FILE*, intn, intn)=NULL;

    FUNC_ENTER(H5O_debug, FAIL);

    /* check args */
    assert(f);
    assert(addr && H5F_addr_defined(addr));
    assert(stream);
    assert(indent >= 0);
    assert(fwidth >= 0);

    if (NULL == (oh = H5AC_protect(f, H5AC_OHDR, addr, NULL, NULL))) {
	HGOTO_ERROR(H5E_OHDR, H5E_CANTLOAD, FAIL,
		    "unable to load object header");
    }

    /* debug */
    fprintf(stream, "%*sObject Header...\n", indent, "");

    fprintf(stream, "%*s%-*s %d\n", indent, "", fwidth,
	    "Dirty:",
	    (int) (oh->dirty));
    fprintf(stream, "%*s%-*s %d\n", indent, "", fwidth,
	    "Version:",
	    (int) (oh->version));
    fprintf(stream, "%*s%-*s %d\n", indent, "", fwidth,
	    "Number of links:",
	    (int) (oh->nlink));
    fprintf(stream, "%*s%-*s %d (%d)\n", indent, "", fwidth,
	    "Number of messages (allocated):",
	    (int) (oh->nmesgs), (int) (oh->alloc_nmesgs));
    fprintf(stream, "%*s%-*s %d (%d)\n", indent, "", fwidth,
	    "Number of chunks (allocated):",
	    (int) (oh->nchunks), (int) (oh->alloc_nchunks));

    /* debug each chunk */
    for (i=0, chunk_total=0; i<oh->nchunks; i++) {
	chunk_total += oh->chunk[i].size;
	fprintf(stream, "%*sChunk %d...\n", indent, "", i);

	fprintf(stream, "%*s%-*s %d\n", indent + 3, "", MAX(0, fwidth - 3),
		"Dirty:",
		(int) (oh->chunk[i].dirty));

	fprintf(stream, "%*s%-*s ", indent + 3, "", MAX(0, fwidth - 3),
		"Address:");
	H5F_addr_print(stream, &(oh->chunk[i].addr));
	fprintf(stream, "\n");

	tmp_addr = *addr;
	H5F_addr_inc(&tmp_addr, (hsize_t)H5O_SIZEOF_HDR(f));
	if (0 == i && H5F_addr_ne(&(oh->chunk[i].addr), &tmp_addr)) {
	    fprintf(stream, "*** WRONG ADDRESS!\n");
	}
	fprintf(stream, "%*s%-*s %lu\n", indent + 3, "", MAX(0, fwidth - 3),
		"Size in bytes:",
		(unsigned long) (oh->chunk[i].size));
    }

    /* debug each message */
    if (NULL==(sequence = H5MM_calloc(NELMTS(message_type_g)*sizeof(int)))) {
	HGOTO_ERROR (H5E_RESOURCE, H5E_NOSPACE, FAIL,
		     "memory allocation failed");
    }
    for (i=0, mesg_total=0; i<oh->nmesgs; i++) {
	mesg_total += H5O_SIZEOF_MSGHDR(f) + oh->mesg[i].raw_size;
	fprintf(stream, "%*sMessage %d...\n", indent, "", i);

	/* check for bad message id */
	if (oh->mesg[i].type->id < 0 ||
	    oh->mesg[i].type->id >= (intn)NELMTS(message_type_g)) {
	    fprintf(stream, "*** BAD MESSAGE ID 0x%04x\n",
		    oh->mesg[i].type->id);
	    continue;
	}

	/* message name and size */
	fprintf(stream, "%*s%-*s 0x%04x %s(%d)\n",
		indent + 3, "", MAX(0, fwidth - 3),
		"Message ID:",
		(unsigned) (oh->mesg[i].type->id),
		oh->mesg[i].type->name,
		sequence[oh->mesg[i].type->id]++);
	fprintf (stream, "%*s%-*s %s\n", indent+3, "", MAX (0, fwidth-3),
		 "Shared message:",
		 (oh->mesg[i].flags & H5O_FLAG_SHARED) ? "Yes" : "No");
	fprintf(stream, "%*s%-*s %s\n", indent + 3, "", MAX(0, fwidth - 3),
		"Constant:",
		(oh->mesg[i].flags & H5O_FLAG_CONSTANT) ? "Yes" : "No");
	if (oh->mesg[i].flags & ~H5O_FLAG_BITS) {
	    fprintf (stream, "%*s%-*s 0x%02x\n", indent+3,"",MAX(0,fwidth-3), 
		     "*** ADDITIONAL UNKNOWN FLAGS --->",
		     oh->mesg[i].flags & ~H5O_FLAG_BITS);
	}
	fprintf(stream, "%*s%-*s %lu bytes\n", indent+3, "", MAX(0,fwidth-3),
		"Raw size in obj header:",
		(unsigned long) (oh->mesg[i].raw_size));
	fprintf(stream, "%*s%-*s %d\n", indent + 3, "", MAX(0, fwidth - 3),
		"Chunk number:",
		(int) (oh->mesg[i].chunkno));
	chunkno = oh->mesg[i].chunkno;
	if (chunkno < 0 || chunkno >= oh->nchunks) {
	    fprintf(stream, "*** BAD CHUNK NUMBER\n");
	}
	
	/* check the size */
	if ((oh->mesg[i].raw + oh->mesg[i].raw_size >
	     oh->chunk[chunkno].image + oh->chunk[chunkno].size) ||
	    (oh->mesg[i].raw < oh->chunk[chunkno].image)) {
	    fprintf(stream, "*** BAD MESSAGE RAW ADDRESS\n");
	}
	
	/* decode the message */
	if (oh->mesg[i].flags & H5O_FLAG_SHARED) {
	    decode = H5O_SHARED->decode;
	    debug = H5O_SHARED->debug;
	} else {
	    decode = oh->mesg[i].type->decode;
	    debug = oh->mesg[i].type->debug;
	}
	if (NULL==oh->mesg[i].native && oh->mesg[i].type->decode) {
	    oh->mesg[i].native = (decode)(f, oh->mesg[i].raw, NULL);
	}
	if (NULL==oh->mesg[i].native) {
	    debug = NULL;
	}
	
	/* print the message */
	if (debug) {
	    (debug)(f, oh->mesg[i].native, stream, indent+3, MAX(0, fwidth-3));
	} else {
	    fprintf(stream, "%*sNo info for this message.\n", indent + 3, "");
	}

	/* If the message is shared then also print the pointed-to message */
	if (oh->mesg[i].flags & H5O_FLAG_SHARED) {
	    H5O_shared_t *shared = (H5O_shared_t*)(oh->mesg[i].native);
	    void *mesg = NULL;
	    if (shared->in_gh) {
		void *p = H5HG_read (f, oh->mesg[i].native, NULL);
		mesg = (oh->mesg[i].type->decode)(f, p, oh->mesg[i].native);
		H5MM_xfree (p);
	    } else {
		mesg = H5O_read (&(shared->u.ent), oh->mesg[i].type, 0, NULL);
	    }
	    if (oh->mesg[i].type->debug) {
		(oh->mesg[i].type->debug)(f, mesg, stream, indent+3,
					  MAX (0, fwidth-3));
	    }
	    H5O_free (oh->mesg[i].type, mesg);
	}
    }
    sequence = H5MM_xfree(sequence);

    if (mesg_total != chunk_total) {
	fprintf(stream, "*** TOTAL SIZE DOES NOT MATCH ALLOCATED SIZE!\n");
    }
    ret_value = SUCCEED;

  done:
    if (oh && H5AC_unprotect(f, H5AC_OHDR, addr, oh) < 0) {
	HRETURN_ERROR(H5E_OHDR, H5E_PROTECT, FAIL,
		      "unable to release object header");
    }
    FUNC_LEAVE(ret_value);
}