blob: f8196b3a950ef4f6fc8b97e615b7d4cd1e352e55 [file] [log] [blame]
Chris Metcalf18aecc22011-05-04 14:38:26 -04001/*
2 * Copyright 2011 Tilera Corporation. All Rights Reserved.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation, version 2.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
11 * NON INFRINGEMENT. See the GNU General Public License for
12 * more details.
13 */
14
15#include <linux/types.h>
16#include <linux/string.h>
17#include <linux/module.h>
Chris Metcalf1efea402012-03-29 13:30:31 -040018#include "string-endian.h"
Chris Metcalf18aecc22011-05-04 14:38:26 -040019
20void *memchr(const void *s, int c, size_t n)
21{
22 const uint64_t *last_word_ptr;
23 const uint64_t *p;
24 const char *last_byte_ptr;
25 uintptr_t s_int;
26 uint64_t goal, before_mask, v, bits;
27 char *ret;
28
29 if (__builtin_expect(n == 0, 0)) {
30 /* Don't dereference any memory if the array is empty. */
31 return NULL;
32 }
33
34 /* Get an aligned pointer. */
35 s_int = (uintptr_t) s;
36 p = (const uint64_t *)(s_int & -8);
37
38 /* Create eight copies of the byte for which we are looking. */
Chris Metcalfc53c70a2013-08-01 15:52:17 -040039 goal = copy_byte(c);
Chris Metcalf18aecc22011-05-04 14:38:26 -040040
41 /* Read the first word, but munge it so that bytes before the array
42 * will not match goal.
Chris Metcalf18aecc22011-05-04 14:38:26 -040043 */
Chris Metcalf1efea402012-03-29 13:30:31 -040044 before_mask = MASK(s_int);
Chris Metcalf18aecc22011-05-04 14:38:26 -040045 v = (*p | before_mask) ^ (goal & before_mask);
46
47 /* Compute the address of the last byte. */
48 last_byte_ptr = (const char *)s + n - 1;
49
50 /* Compute the address of the word containing the last byte. */
51 last_word_ptr = (const uint64_t *)((uintptr_t) last_byte_ptr & -8);
52
53 while ((bits = __insn_v1cmpeq(v, goal)) == 0) {
54 if (__builtin_expect(p == last_word_ptr, 0)) {
55 /* We already read the last word in the array,
56 * so give up.
57 */
58 return NULL;
59 }
60 v = *++p;
61 }
62
63 /* We found a match, but it might be in a byte past the end
64 * of the array.
65 */
Chris Metcalf1efea402012-03-29 13:30:31 -040066 ret = ((char *)p) + (CFZ(bits) >> 3);
Chris Metcalf18aecc22011-05-04 14:38:26 -040067 return (ret <= last_byte_ptr) ? ret : NULL;
68}
69EXPORT_SYMBOL(memchr);