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