blob: c5bac8d0f8f852e8dabb073decdab26cdc9df02b [file] [log] [blame]
Mark Dykesad5ab072020-08-19 19:11:33 +00001/*
Govindraj Rajaeee28e72023-08-01 15:52:40 -05002 * Copyright (c) 2013-2020, Arm Limited and Contributors. All rights reserved.
Mark Dykesad5ab072020-08-19 19:11:33 +00003 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
7#include <stddef.h>
8#include <string.h>
Andre Przywara16e7bcf2020-09-03 11:04:39 +01009#include <stdint.h>
Mark Dykesad5ab072020-08-19 19:11:33 +000010
11void *memset(void *dst, int val, size_t count)
12{
Andre Przywara6c3675b2020-09-24 15:50:40 +010013 uint8_t *ptr = dst;
Andre Przywara16e7bcf2020-09-03 11:04:39 +010014 uint64_t *ptr64;
15 uint64_t fill = (unsigned char)val;
Mark Dykesad5ab072020-08-19 19:11:33 +000016
Andre Przywara16e7bcf2020-09-03 11:04:39 +010017 /* Simplify code below by making sure we write at least one byte. */
Andre Przywara6c3675b2020-09-24 15:50:40 +010018 if (count == 0U) {
Andre Przywara16e7bcf2020-09-03 11:04:39 +010019 return dst;
20 }
21
22 /* Handle the first part, until the pointer becomes 64-bit aligned. */
Andre Przywara6c3675b2020-09-24 15:50:40 +010023 while (((uintptr_t)ptr & 7U) != 0U) {
24 *ptr = (uint8_t)val;
25 ptr++;
26 if (--count == 0U) {
Andre Przywara16e7bcf2020-09-03 11:04:39 +010027 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. */
Andre Przywara6c3675b2020-09-24 15:50:40 +010037 ptr64 = (uint64_t *)ptr;
38 for (; count >= 8U; count -= 8) {
39 *ptr64 = fill;
40 ptr64++;
Andre Przywara16e7bcf2020-09-03 11:04:39 +010041 }
42
43 /* Handle the remaining part byte-per-byte. */
Andre Przywara6c3675b2020-09-24 15:50:40 +010044 ptr = (uint8_t *)ptr64;
45 while (count-- > 0U) {
46 *ptr = (uint8_t)val;
47 ptr++;
Andre Przywara16e7bcf2020-09-03 11:04:39 +010048 }
Mark Dykesad5ab072020-08-19 19:11:33 +000049
50 return dst;
51}