xref: /rk3399_ARM-atf/lib/libc/memset.c (revision 75fab6496e5fce9a11b4e3a160ad2e797acc6ee9)
1f5402ef7SMark Dykes /*
2*75fab649SAndre Przywara  * Copyright (c) 2013-2020, ARM Limited and Contributors. All rights reserved.
3f5402ef7SMark Dykes  *
4f5402ef7SMark Dykes  * SPDX-License-Identifier: BSD-3-Clause
5f5402ef7SMark Dykes  */
6f5402ef7SMark Dykes 
7f5402ef7SMark Dykes #include <stddef.h>
8f5402ef7SMark Dykes #include <string.h>
9*75fab649SAndre Przywara #include <stdint.h>
10f5402ef7SMark Dykes 
11f5402ef7SMark Dykes void *memset(void *dst, int val, size_t count)
12f5402ef7SMark Dykes {
13f5402ef7SMark Dykes 	char *ptr = dst;
14*75fab649SAndre Przywara 	uint64_t *ptr64;
15*75fab649SAndre Przywara 	uint64_t fill = (unsigned char)val;
16f5402ef7SMark Dykes 
17*75fab649SAndre Przywara 	/* Simplify code below by making sure we write at least one byte. */
18*75fab649SAndre Przywara 	if (count == 0) {
19*75fab649SAndre Przywara 		return dst;
20*75fab649SAndre Przywara 	}
21*75fab649SAndre Przywara 
22*75fab649SAndre Przywara 	/* Handle the first part, until the pointer becomes 64-bit aligned. */
23*75fab649SAndre Przywara 	while (((uintptr_t)ptr & 7)) {
24f5402ef7SMark Dykes 		*ptr++ = val;
25*75fab649SAndre Przywara 		if (--count == 0) {
26*75fab649SAndre Przywara 			return dst;
27*75fab649SAndre Przywara 		}
28*75fab649SAndre Przywara 	}
29*75fab649SAndre Przywara 
30*75fab649SAndre Przywara 	/* Duplicate the fill byte to the rest of the 64-bit word. */
31*75fab649SAndre Przywara 	fill |= fill << 8;
32*75fab649SAndre Przywara 	fill |= fill << 16;
33*75fab649SAndre Przywara 	fill |= fill << 32;
34*75fab649SAndre Przywara 
35*75fab649SAndre Przywara 	/* Use 64-bit writes for as long as possible. */
36*75fab649SAndre Przywara 	ptr64 = (void *)ptr;
37*75fab649SAndre Przywara 	for (; count >= 8; count -= 8) {
38*75fab649SAndre Przywara 		*ptr64++ = fill;
39*75fab649SAndre Przywara 	}
40*75fab649SAndre Przywara 
41*75fab649SAndre Przywara 	/* Handle the remaining part byte-per-byte. */
42*75fab649SAndre Przywara 	ptr = (void *)ptr64;
43*75fab649SAndre Przywara 	while (count--) {
44*75fab649SAndre Przywara 		*ptr++ = val;
45*75fab649SAndre Przywara 	}
46f5402ef7SMark Dykes 
47f5402ef7SMark Dykes 	return dst;
48f5402ef7SMark Dykes }
49