/*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>1718#undef strchr1920char *strchr(const char *s, int c)21{22int z, g;2324/* Get an aligned pointer. */25const uintptr_t s_int = (uintptr_t) s;26const uint64_t *p = (const uint64_t *)(s_int & -8);2728/* Create eight copies of the byte for which we are looking. */29const uint64_t goal = 0x0101010101010101ULL * (uint8_t) c;3031/* Read the first aligned word, but force bytes before the string to32* match neither zero nor goal (we make sure the high bit of each33* byte is 1, and the low 7 bits are all the opposite of the goal34* byte).35*36* Note that this shift count expression works because we know shift37* counts are taken mod 64.38*/39const uint64_t before_mask = (1ULL << (s_int << 3)) - 1;40uint64_t v = (*p | before_mask) ^41(goal & __insn_v1shrsi(before_mask, 1));4243uint64_t zero_matches, goal_matches;44while (1) {45/* Look for a terminating '\0'. */46zero_matches = __insn_v1cmpeqi(v, 0);4748/* Look for the goal byte. */49goal_matches = __insn_v1cmpeq(v, goal);5051if (__builtin_expect((zero_matches | goal_matches) != 0, 0))52break;5354v = *++p;55}5657z = __insn_ctz(zero_matches);58g = __insn_ctz(goal_matches);5960/* If we found c before '\0' we got a match. Note that if c == '\0'61* then g == z, and we correctly return the address of the '\0'62* rather than NULL.63*/64return (g <= z) ? ((char *)p) + (g >> 3) : NULL;65}66EXPORT_SYMBOL(strchr);676869