xref: /rk3399_ARM-atf/lib/libc/memset.c (revision 005415a39a411c2c92da48409441304173884d08)
1f5402ef7SMark Dykes /*
275fab649SAndre 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>
975fab649SAndre Przywara #include <stdint.h>
10f5402ef7SMark Dykes 
11f5402ef7SMark Dykes void *memset(void *dst, int val, size_t count)
12f5402ef7SMark Dykes {
13*005415a3SAndre 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. */
18*005415a3SAndre 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. */
23*005415a3SAndre Przywara 	while (((uintptr_t)ptr & 7U) != 0U) {
24*005415a3SAndre Przywara 		*ptr = (uint8_t)val;
25*005415a3SAndre Przywara 		ptr++;
26*005415a3SAndre 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. */
37*005415a3SAndre Przywara 	ptr64 = (uint64_t *)ptr;
38*005415a3SAndre Przywara 	for (; count >= 8U; count -= 8) {
39*005415a3SAndre Przywara 		*ptr64 = fill;
40*005415a3SAndre Przywara 		ptr64++;
4175fab649SAndre Przywara 	}
4275fab649SAndre Przywara 
4375fab649SAndre Przywara 	/* Handle the remaining part byte-per-byte. */
44*005415a3SAndre Przywara 	ptr = (uint8_t *)ptr64;
45*005415a3SAndre Przywara 	while (count-- > 0U)  {
46*005415a3SAndre Przywara 		*ptr = (uint8_t)val;
47*005415a3SAndre Przywara 		ptr++;
4875fab649SAndre Przywara 	}
49f5402ef7SMark Dykes 
50f5402ef7SMark Dykes 	return dst;
51f5402ef7SMark Dykes }
52