xref: /rk3399_ARM-atf/lib/libc/memset.c (revision 25002a0042382f641f228e7045f55539d7d1103b)
1f5402ef7SMark Dykes /*
2*34d7f196SBoyan Karatotev  * Copyright (c) 2013-2025, 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>
8*34d7f196SBoyan Karatotev #include <string_private.h>
975fab649SAndre Przywara #include <stdint.h>
10f5402ef7SMark Dykes 
memset(void * dst,int val,size_t count)11f5402ef7SMark Dykes void *memset(void *dst, int val, size_t count)
12f5402ef7SMark Dykes {
13005415a3SAndre Przywara 	uint8_t *ptr = dst;
1475fab649SAndre Przywara 	uint64_t *ptr64;
1575fab649SAndre Przywara 	uint64_t fill = (unsigned char)val;
16f5402ef7SMark Dykes 
1775fab649SAndre Przywara 	/* Simplify code below by making sure we write at least one byte. */
18005415a3SAndre Przywara 	if (count == 0U) {
1975fab649SAndre Przywara 		return dst;
2075fab649SAndre Przywara 	}
2175fab649SAndre Przywara 
2275fab649SAndre Przywara 	/* Handle the first part, until the pointer becomes 64-bit aligned. */
23005415a3SAndre Przywara 	while (((uintptr_t)ptr & 7U) != 0U) {
24005415a3SAndre Przywara 		*ptr = (uint8_t)val;
25005415a3SAndre Przywara 		ptr++;
26005415a3SAndre Przywara 		if (--count == 0U) {
2775fab649SAndre Przywara 			return dst;
2875fab649SAndre Przywara 		}
2975fab649SAndre Przywara 	}
3075fab649SAndre Przywara 
3175fab649SAndre Przywara 	/* Duplicate the fill byte to the rest of the 64-bit word. */
3275fab649SAndre Przywara 	fill |= fill << 8;
3375fab649SAndre Przywara 	fill |= fill << 16;
3475fab649SAndre Przywara 	fill |= fill << 32;
3575fab649SAndre Przywara 
3675fab649SAndre Przywara 	/* Use 64-bit writes for as long as possible. */
37005415a3SAndre Przywara 	ptr64 = (uint64_t *)ptr;
38005415a3SAndre Przywara 	for (; count >= 8U; count -= 8) {
39005415a3SAndre Przywara 		*ptr64 = fill;
40005415a3SAndre Przywara 		ptr64++;
4175fab649SAndre Przywara 	}
4275fab649SAndre Przywara 
4375fab649SAndre Przywara 	/* Handle the remaining part byte-per-byte. */
44005415a3SAndre Przywara 	ptr = (uint8_t *)ptr64;
45005415a3SAndre Przywara 	while (count-- > 0U)  {
46005415a3SAndre Przywara 		*ptr = (uint8_t)val;
47005415a3SAndre Przywara 		ptr++;
4875fab649SAndre Przywara 	}
49f5402ef7SMark Dykes 
50f5402ef7SMark Dykes 	return dst;
51f5402ef7SMark Dykes }
52