Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 29 Nov 2001 11:05:55 -0800 (PST)
From:      Archie Cobbs <archie@dellroad.org>
To:        freebsd-hackers@freebsd.org
Cc:        bmilekic@freebsd.org
Subject:   kernel realloc() ?
Message-ID:  <200111291905.fATJ5tX48250@arch20m.dellroad.org>

next in thread | raw e-mail | index | archive | help
For a project I'm working on, we need a kernel version of "realloc()".
Two questions:

    #1 Does the patch below look correct?

    #2 If so, is this something worth committing?

Thanks for any comments.

-Archie

__________________________________________________________________________
Archie Cobbs     *     Packet Design     *     http://www.packetdesign.com

--- sys/malloc.h.orig	Wed Nov 28 21:56:23 2001
+++ sys/malloc.h	Thu Nov 29 10:58:30 2001
@@ -176,6 +176,8 @@
 void	*malloc __P((unsigned long size, struct malloc_type *type, int flags));
 void	malloc_init __P((void *));
 void	malloc_uninit __P((void *));
+void	*realloc __P((void *addr, unsigned long size,
+		      struct malloc_type *type, int flags));
 #endif /* _KERNEL */
 
 #endif /* !_SYS_MALLOC_H_ */
--- kern/kern_malloc.c.orig	Wed Nov 28 21:45:18 2001
+++ kern/kern_malloc.c	Wed Nov 28 22:12:07 2001
@@ -404,6 +404,43 @@
 }
 
 /*
+ *	realloc: change the size of a memory block
+ */
+void *
+realloc(addr, size, type, flags)
+	void *addr;
+	unsigned long size;
+	struct malloc_type *type;
+	int flags;
+{
+	struct kmemusage *kup;
+	long alloc;
+	void *mem;
+
+	/* Sanity checks */
+	if (type->ks_limit == 0)
+		panic("realloc with unknown type (%s)", type->ks_shortdesc);
+	KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
+	    ("realloc: address %p out of range", (void *)addr));
+
+	/* Get size of original block; reuse if appropriate */
+	kup = btokup(addr);
+	alloc = 1 << kup->ku_indx;
+	if (size <= alloc
+	    && (size >= (alloc >> 1) || alloc == MINALLOCSIZE))
+		return (addr);
+
+	/* Allocate new block */
+	if ((mem = malloc(size, type, flags)) == NULL)
+		return (NULL);
+
+	/* Copy over contents */
+	bcopy(addr, mem, alloc);
+	free(addr, type);
+	return (mem);
+}
+
+/*
  * Initialize the kernel memory allocator
  */
 /* ARGSUSED*/

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?200111291905.fATJ5tX48250>