/*1* Copyright 2011 Tilera Corporation. All Rights Reserved.2*3* This program is free software; you can redistribute it and/or4* modify it under the terms of the GNU General Public License5* as published by the Free Software Foundation, version 2.6*7* This program is distributed in the hope that it will be useful, but8* WITHOUT ANY WARRANTY; without even the implied warranty of9* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or10* NON INFRINGEMENT. See the GNU General Public License for11* more details.12*/1314#include <linux/types.h>15#include <linux/string.h>16#include <linux/module.h>1718void *memchr(const void *s, int c, size_t n)19{20const uint64_t *last_word_ptr;21const uint64_t *p;22const char *last_byte_ptr;23uintptr_t s_int;24uint64_t goal, before_mask, v, bits;25char *ret;2627if (__builtin_expect(n == 0, 0)) {28/* Don't dereference any memory if the array is empty. */29return NULL;30}3132/* Get an aligned pointer. */33s_int = (uintptr_t) s;34p = (const uint64_t *)(s_int & -8);3536/* Create eight copies of the byte for which we are looking. */37goal = 0x0101010101010101ULL * (uint8_t) c;3839/* Read the first word, but munge it so that bytes before the array40* will not match goal.41*42* Note that this shift count expression works because we know43* shift counts are taken mod 64.44*/45before_mask = (1ULL << (s_int << 3)) - 1;46v = (*p | before_mask) ^ (goal & before_mask);4748/* Compute the address of the last byte. */49last_byte_ptr = (const char *)s + n - 1;5051/* Compute the address of the word containing the last byte. */52last_word_ptr = (const uint64_t *)((uintptr_t) last_byte_ptr & -8);5354while ((bits = __insn_v1cmpeq(v, goal)) == 0) {55if (__builtin_expect(p == last_word_ptr, 0)) {56/* We already read the last word in the array,57* so give up.58*/59return NULL;60}61v = *++p;62}6364/* We found a match, but it might be in a byte past the end65* of the array.66*/67ret = ((char *)p) + (__insn_ctz(bits) >> 3);68return (ret <= last_byte_ptr) ? ret : NULL;69}70EXPORT_SYMBOL(memchr);717273