cpu-features.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. /*
  2. * Copyright (C) 2010 The Android Open Source Project
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * * Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in
  12. * the documentation and/or other materials provided with the
  13. * distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  16. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  17. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  18. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  19. * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  20. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  21. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  22. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  23. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  25. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  26. * SUCH DAMAGE.
  27. */
  28. /* ChangeLog for this library:
  29. *
  30. * NDK r7c: Fix CPU count computation. The old method only reported the
  31. * number of _active_ CPUs when the library was initialized,
  32. * which could be less than the real total.
  33. *
  34. * NDK r5: Handle buggy kernels which report a CPU Architecture number of 7
  35. * for an ARMv6 CPU (see below).
  36. *
  37. * Handle kernels that only report 'neon', and not 'vfpv3'
  38. * (VFPv3 is mandated by the ARM architecture is Neon is implemented)
  39. *
  40. * Handle kernels that only report 'vfpv3d16', and not 'vfpv3'
  41. *
  42. * Fix x86 compilation. Report ANDROID_CPU_FAMILY_X86 in
  43. * android_getCpuFamily().
  44. *
  45. * NDK r4: Initial release
  46. */
  47. #include <sys/system_properties.h>
  48. #ifdef __arm__
  49. #include <machine/cpu-features.h>
  50. #endif
  51. #include <pthread.h>
  52. #include "cpu-features.h"
  53. #include <stdio.h>
  54. #include <stdlib.h>
  55. #include <fcntl.h>
  56. #include <errno.h>
  57. static pthread_once_t g_once;
  58. static AndroidCpuFamily g_cpuFamily;
  59. static uint64_t g_cpuFeatures;
  60. static int g_cpuCount;
  61. static const int android_cpufeatures_debug = 0;
  62. #ifdef __arm__
  63. # define DEFAULT_CPU_FAMILY ANDROID_CPU_FAMILY_ARM
  64. #elif defined __i386__
  65. # define DEFAULT_CPU_FAMILY ANDROID_CPU_FAMILY_X86
  66. #else
  67. # define DEFAULT_CPU_FAMILY ANDROID_CPU_FAMILY_UNKNOWN
  68. #endif
  69. #define D(...) \
  70. do { \
  71. if (android_cpufeatures_debug) { \
  72. printf(__VA_ARGS__); fflush(stdout); \
  73. } \
  74. } while (0)
  75. #ifdef __i386__
  76. static __inline__ void x86_cpuid(int func, int values[4])
  77. {
  78. int a, b, c, d;
  79. /* We need to preserve ebx since we're compiling PIC code */
  80. /* this means we can't use "=b" for the second output register */
  81. __asm__ __volatile__ ( \
  82. "push %%ebx\n"
  83. "cpuid\n" \
  84. "mov %1, %%ebx\n"
  85. "pop %%ebx\n"
  86. : "=a" (a), "=r" (b), "=c" (c), "=d" (d) \
  87. : "a" (func) \
  88. );
  89. values[0] = a;
  90. values[1] = b;
  91. values[2] = c;
  92. values[3] = d;
  93. }
  94. #endif
  95. /* Read the content of /proc/cpuinfo into a user-provided buffer.
  96. * Return the length of the data, or -1 on error. Does *not*
  97. * zero-terminate the content. Will not read more
  98. * than 'buffsize' bytes.
  99. */
  100. static int
  101. read_file(const char* pathname, char* buffer, size_t buffsize)
  102. {
  103. int fd, len;
  104. fd = open(pathname, O_RDONLY);
  105. if (fd < 0) {
  106. return -1;
  107. }
  108. do {
  109. len = read(fd, buffer, buffsize);
  110. }
  111. while (len < 0 && errno == EINTR);
  112. close(fd);
  113. return len;
  114. }
  115. /* Extract the content of a the first occurence of a given field in
  116. * the content of /proc/cpuinfo and return it as a heap-allocated
  117. * string that must be freed by the caller.
  118. *
  119. * Return NULL if not found
  120. */
  121. static char*
  122. extract_cpuinfo_field(char* buffer, int buflen, const char* field)
  123. {
  124. int fieldlen = strlen(field);
  125. char* bufend = buffer + buflen;
  126. char* result = NULL;
  127. int len, ignore;
  128. const char *p, *q;
  129. /* Look for first field occurence, and ensures it starts the line.
  130. */
  131. p = buffer;
  132. bufend = buffer + buflen;
  133. for (;;) {
  134. p = memmem(p, bufend-p, field, fieldlen);
  135. if (p == NULL) {
  136. goto EXIT;
  137. }
  138. if (p == buffer || p[-1] == '\n') {
  139. break;
  140. }
  141. p += fieldlen;
  142. }
  143. /* Skip to the first column followed by a space */
  144. p += fieldlen;
  145. p = memchr(p, ':', bufend-p);
  146. if (p == NULL || p[1] != ' ') {
  147. goto EXIT;
  148. }
  149. /* Find the end of the line */
  150. p += 2;
  151. q = memchr(p, '\n', bufend-p);
  152. if (q == NULL) {
  153. q = bufend;
  154. }
  155. /* Copy the line into a heap-allocated buffer */
  156. len = q-p;
  157. result = malloc(len+1);
  158. if (result == NULL) {
  159. goto EXIT;
  160. }
  161. memcpy(result, p, len);
  162. result[len] = '\0';
  163. EXIT:
  164. return result;
  165. }
  166. /* Like strlen(), but for constant string literals */
  167. #define STRLEN_CONST(x) ((sizeof(x)-1)
  168. /* Checks that a space-separated list of items contains one given 'item'.
  169. * Returns 1 if found, 0 otherwise.
  170. */
  171. static int
  172. has_list_item(const char* list, const char* item)
  173. {
  174. const char* p = list;
  175. int itemlen = strlen(item);
  176. if (list == NULL) {
  177. return 0;
  178. }
  179. while (*p) {
  180. const char* q;
  181. /* skip spaces */
  182. while (*p == ' ' || *p == '\t') {
  183. p++;
  184. }
  185. /* find end of current list item */
  186. q = p;
  187. while (*q && *q != ' ' && *q != '\t') {
  188. q++;
  189. }
  190. if (itemlen == q-p && !memcmp(p, item, itemlen)) {
  191. return 1;
  192. }
  193. /* skip to next item */
  194. p = q;
  195. }
  196. return 0;
  197. }
  198. /* Parse an decimal integer starting from 'input', but not going further
  199. * than 'limit'. Return the value into '*result'.
  200. *
  201. * NOTE: Does not skip over leading spaces, or deal with sign characters.
  202. * NOTE: Ignores overflows.
  203. *
  204. * The function returns NULL in case of error (bad format), or the new
  205. * position after the decimal number in case of success (which will always
  206. * be <= 'limit').
  207. */
  208. static const char*
  209. parse_decimal(const char* input, const char* limit, int* result)
  210. {
  211. const char* p = input;
  212. int val = 0;
  213. while (p < limit) {
  214. int d = (*p - '0');
  215. if ((unsigned)d >= 10U) {
  216. break;
  217. }
  218. val = val*10 + d;
  219. p++;
  220. }
  221. if (p == input) {
  222. return NULL;
  223. }
  224. *result = val;
  225. return p;
  226. }
  227. /* This small data type is used to represent a CPU list / mask, as read
  228. * from sysfs on Linux. See http://www.kernel.org/doc/Documentation/cputopology.txt
  229. *
  230. * For now, we don't expect more than 32 cores on mobile devices, so keep
  231. * everything simple.
  232. */
  233. typedef struct {
  234. uint32_t mask;
  235. } CpuList;
  236. static __inline__ void
  237. cpulist_init(CpuList* list)
  238. {
  239. list->mask = 0;
  240. }
  241. static __inline__ void
  242. cpulist_and(CpuList* list1, CpuList* list2)
  243. {
  244. list1->mask &= list2->mask;
  245. }
  246. static __inline__ void
  247. cpulist_set(CpuList* list, int index)
  248. {
  249. if ((unsigned)index < 32) {
  250. list->mask |= (uint32_t)(1U << index);
  251. }
  252. }
  253. static __inline__ int
  254. cpulist_count(CpuList* list)
  255. {
  256. return __builtin_popcount(list->mask);
  257. }
  258. /* Parse a textual list of cpus and store the result inside a CpuList object.
  259. * Input format is the following:
  260. * - comma-separated list of items (no spaces)
  261. * - each item is either a single decimal number (cpu index), or a range made
  262. * of two numbers separated by a single dash (-). Ranges are inclusive.
  263. *
  264. * Examples: 0
  265. * 2,4-127,128-143
  266. * 0-1
  267. */
  268. static void
  269. cpulist_parse(CpuList* list, const char* line, int line_len)
  270. {
  271. const char* p = line;
  272. const char* end = p + line_len;
  273. const char* q;
  274. /* NOTE: the input line coming from sysfs typically contains a
  275. * trailing newline, so take care of it in the code below
  276. */
  277. while (p < end && *p != '\n') {
  278. int val, start_value, end_value;
  279. /* Find the end of current item, and put it into 'q' */
  280. q = memchr(p, ',', end-p);
  281. if (q == NULL) {
  282. q = end;
  283. }
  284. /* Get first value */
  285. p = parse_decimal(p, q, &start_value);
  286. if (p == NULL) {
  287. goto BAD_FORMAT;
  288. }
  289. end_value = start_value;
  290. /* If we're not at the end of the item, expect a dash and
  291. * and integer; extract end value.
  292. */
  293. if (p < q && *p == '-') {
  294. p = parse_decimal(p+1, q, &end_value);
  295. if (p == NULL) {
  296. goto BAD_FORMAT;
  297. }
  298. }
  299. /* Set bits CPU list bits */
  300. for (val = start_value; val <= end_value; val++) {
  301. cpulist_set(list, val);
  302. }
  303. /* Jump to next item */
  304. p = q;
  305. if (p < end) {
  306. p++;
  307. }
  308. }
  309. BAD_FORMAT:
  310. ;
  311. }
  312. /* Read a CPU list from one sysfs file */
  313. static void
  314. cpulist_read_from(CpuList* list, const char* filename)
  315. {
  316. char file[64];
  317. int filelen;
  318. cpulist_init(list);
  319. filelen = read_file(filename, file, sizeof file);
  320. if (filelen < 0) {
  321. D("Could not read %s: %s\n", filename, strerror(errno));
  322. return;
  323. }
  324. cpulist_parse(list, file, filelen);
  325. }
  326. /* Return the number of cpus present on a given device.
  327. *
  328. * To handle all weird kernel configurations, we need to compute the
  329. * intersection of the 'present' and 'possible' CPU lists and count
  330. * the result.
  331. */
  332. static int
  333. get_cpu_count(void)
  334. {
  335. CpuList cpus_present[1];
  336. CpuList cpus_possible[1];
  337. cpulist_read_from(cpus_present, "/sys/devices/system/cpu/present");
  338. cpulist_read_from(cpus_possible, "/sys/devices/system/cpu/possible");
  339. /* Compute the intersection of both sets to get the actual number of
  340. * CPU cores that can be used on this device by the kernel.
  341. */
  342. cpulist_and(cpus_present, cpus_possible);
  343. return cpulist_count(cpus_present);
  344. }
  345. static void
  346. android_cpuInit(void)
  347. {
  348. char cpuinfo[4096];
  349. int cpuinfo_len;
  350. g_cpuFamily = DEFAULT_CPU_FAMILY;
  351. g_cpuFeatures = 0;
  352. g_cpuCount = 1;
  353. cpuinfo_len = read_file("/proc/cpuinfo", cpuinfo, sizeof cpuinfo);
  354. D("cpuinfo_len is (%d):\n%.*s\n", cpuinfo_len,
  355. cpuinfo_len >= 0 ? cpuinfo_len : 0, cpuinfo);
  356. if (cpuinfo_len < 0) { /* should not happen */
  357. return;
  358. }
  359. /* Count the CPU cores, the value may be 0 for single-core CPUs */
  360. g_cpuCount = get_cpu_count();
  361. if (g_cpuCount == 0) {
  362. g_cpuCount = 1;
  363. }
  364. D("found cpuCount = %d\n", g_cpuCount);
  365. #ifdef __ARM_ARCH__
  366. {
  367. char* features = NULL;
  368. char* architecture = NULL;
  369. /* Extract architecture from the "CPU Architecture" field.
  370. * The list is well-known, unlike the the output of
  371. * the 'Processor' field which can vary greatly.
  372. *
  373. * See the definition of the 'proc_arch' array in
  374. * $KERNEL/arch/arm/kernel/setup.c and the 'c_show' function in
  375. * same file.
  376. */
  377. char* cpuArch = extract_cpuinfo_field(cpuinfo, cpuinfo_len, "CPU architecture");
  378. if (cpuArch != NULL) {
  379. char* end;
  380. long archNumber;
  381. int hasARMv7 = 0;
  382. D("found cpuArch = '%s'\n", cpuArch);
  383. /* read the initial decimal number, ignore the rest */
  384. archNumber = strtol(cpuArch, &end, 10);
  385. /* Here we assume that ARMv8 will be upwards compatible with v7
  386. * in the future. Unfortunately, there is no 'Features' field to
  387. * indicate that Thumb-2 is supported.
  388. */
  389. if (end > cpuArch && archNumber >= 7) {
  390. hasARMv7 = 1;
  391. }
  392. /* Unfortunately, it seems that certain ARMv6-based CPUs
  393. * report an incorrect architecture number of 7!
  394. *
  395. * See http://code.google.com/p/android/issues/detail?id=10812
  396. *
  397. * We try to correct this by looking at the 'elf_format'
  398. * field reported by the 'Processor' field, which is of the
  399. * form of "(v7l)" for an ARMv7-based CPU, and "(v6l)" for
  400. * an ARMv6-one.
  401. */
  402. if (hasARMv7) {
  403. char* cpuProc = extract_cpuinfo_field(cpuinfo, cpuinfo_len,
  404. "Processor");
  405. if (cpuProc != NULL) {
  406. D("found cpuProc = '%s'\n", cpuProc);
  407. if (has_list_item(cpuProc, "(v6l)")) {
  408. D("CPU processor and architecture mismatch!!\n");
  409. hasARMv7 = 0;
  410. }
  411. free(cpuProc);
  412. }
  413. }
  414. if (hasARMv7) {
  415. g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_ARMv7;
  416. }
  417. /* The LDREX / STREX instructions are available from ARMv6 */
  418. if (archNumber >= 6) {
  419. g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_LDREX_STREX;
  420. }
  421. free(cpuArch);
  422. }
  423. /* Extract the list of CPU features from 'Features' field */
  424. char* cpuFeatures = extract_cpuinfo_field(cpuinfo, cpuinfo_len, "Features");
  425. if (cpuFeatures != NULL) {
  426. D("found cpuFeatures = '%s'\n", cpuFeatures);
  427. if (has_list_item(cpuFeatures, "vfpv3")) {
  428. g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFPv3;
  429. }
  430. else if (has_list_item(cpuFeatures, "vfpv3d16")) {
  431. g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFPv3;
  432. }
  433. if (has_list_item(cpuFeatures, "neon")) {
  434. /* Note: Certain kernels only report neon but not vfpv3
  435. * in their features list. However, ARM mandates
  436. * that if Neon is implemented, so must be VFPv3
  437. * so always set the flag.
  438. */
  439. g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_NEON |
  440. ANDROID_CPU_ARM_FEATURE_VFPv3;
  441. }
  442. free(cpuFeatures);
  443. }
  444. }
  445. #endif /* __ARM_ARCH__ */
  446. #ifdef __i386__
  447. g_cpuFamily = ANDROID_CPU_FAMILY_X86;
  448. int regs[4];
  449. /* According to http://en.wikipedia.org/wiki/CPUID */
  450. #define VENDOR_INTEL_b 0x756e6547
  451. #define VENDOR_INTEL_c 0x6c65746e
  452. #define VENDOR_INTEL_d 0x49656e69
  453. x86_cpuid(0, regs);
  454. int vendorIsIntel = (regs[1] == VENDOR_INTEL_b &&
  455. regs[2] == VENDOR_INTEL_c &&
  456. regs[3] == VENDOR_INTEL_d);
  457. x86_cpuid(1, regs);
  458. if ((regs[2] & (1 << 9)) != 0) {
  459. g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_SSSE3;
  460. }
  461. if ((regs[2] & (1 << 23)) != 0) {
  462. g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_POPCNT;
  463. }
  464. if (vendorIsIntel && (regs[2] & (1 << 22)) != 0) {
  465. g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_MOVBE;
  466. }
  467. #endif
  468. #ifdef _MIPS_ARCH
  469. g_cpuFamily = ANDROID_CPU_FAMILY_MIPS;
  470. #endif /* _MIPS_ARCH */
  471. }
  472. AndroidCpuFamily
  473. android_getCpuFamily(void)
  474. {
  475. pthread_once(&g_once, android_cpuInit);
  476. return g_cpuFamily;
  477. }
  478. uint64_t
  479. android_getCpuFeatures(void)
  480. {
  481. pthread_once(&g_once, android_cpuInit);
  482. return g_cpuFeatures;
  483. }
  484. int
  485. android_getCpuCount(void)
  486. {
  487. pthread_once(&g_once, android_cpuInit);
  488. return g_cpuCount;
  489. }