701
702 /*
703 * Allocate/realloc/free a buffer for the lua interpreter.
704 *
705 * When nsize is 0, behaves as free() and returns NULL.
706 *
707 * If ptr is NULL, behaves as malloc() and returns an allocated buffer of size
708 * at least nsize.
709 *
710 * Otherwise, behaves as realloc(), changing the allocation from osize to nsize.
711 * Shrinking the buffer size never fails.
712 *
713 * The original allocated buffer size is stored as a uint64 at the beginning of
714 * the buffer to avoid actually reallocating when shrinking a buffer, since lua
715 * requires that this operation never fail.
716 */
717 static void *
718 zcp_lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
719 {
720 zcp_alloc_arg_t *allocargs = ud;
721 int flags = (allocargs->aa_must_succeed) ?
722 KM_SLEEP : (KM_NOSLEEP | KM_NORMALPRI);
723
724 if (nsize == 0) {
725 if (ptr != NULL) {
726 int64_t *allocbuf = (int64_t *)ptr - 1;
727 int64_t allocsize = *allocbuf;
728 ASSERT3S(allocsize, >, 0);
729 ASSERT3S(allocargs->aa_alloc_remaining + allocsize, <=,
730 allocargs->aa_alloc_limit);
731 allocargs->aa_alloc_remaining += allocsize;
732 kmem_free(allocbuf, allocsize);
733 }
734 return (NULL);
735 } else if (ptr == NULL) {
736 int64_t *allocbuf;
737 int64_t allocsize = nsize + sizeof (int64_t);
738
739 if (!allocargs->aa_must_succeed &&
740 (allocsize <= 0 ||
741 allocsize > allocargs->aa_alloc_remaining)) {
742 return (NULL);
|
701
702 /*
703 * Allocate/realloc/free a buffer for the lua interpreter.
704 *
705 * When nsize is 0, behaves as free() and returns NULL.
706 *
707 * If ptr is NULL, behaves as malloc() and returns an allocated buffer of size
708 * at least nsize.
709 *
710 * Otherwise, behaves as realloc(), changing the allocation from osize to nsize.
711 * Shrinking the buffer size never fails.
712 *
713 * The original allocated buffer size is stored as a uint64 at the beginning of
714 * the buffer to avoid actually reallocating when shrinking a buffer, since lua
715 * requires that this operation never fail.
716 */
717 static void *
718 zcp_lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
719 {
720 zcp_alloc_arg_t *allocargs = ud;
721 int flags = (allocargs->aa_must_succeed) ? KM_SLEEP : KM_NOSLEEP_LAZY;
722
723 if (nsize == 0) {
724 if (ptr != NULL) {
725 int64_t *allocbuf = (int64_t *)ptr - 1;
726 int64_t allocsize = *allocbuf;
727 ASSERT3S(allocsize, >, 0);
728 ASSERT3S(allocargs->aa_alloc_remaining + allocsize, <=,
729 allocargs->aa_alloc_limit);
730 allocargs->aa_alloc_remaining += allocsize;
731 kmem_free(allocbuf, allocsize);
732 }
733 return (NULL);
734 } else if (ptr == NULL) {
735 int64_t *allocbuf;
736 int64_t allocsize = nsize + sizeof (int64_t);
737
738 if (!allocargs->aa_must_succeed &&
739 (allocsize <= 0 ||
740 allocsize > allocargs->aa_alloc_remaining)) {
741 return (NULL);
|