blob: 31d7e042db037021aa11269a1c24cd2bfc4aa4d5 [file] [log] [blame]
Anders Lewisf4447b92017-06-23 15:53:59 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "util.h"
18
19#include <sched.h>
20#include <stdio.h>
21#include <string.h>
22#include <cstdlib>
23#include <vector>
24
25// This function returns a pointer less than 2 * alignment + or_mask bytes into the array.
26char *GetAlignedMemory(char *orig_ptr, size_t alignment, size_t or_mask) {
27 if ((alignment & (alignment - 1)) != 0) {
28 fprintf(stderr, "warning: alignment passed into GetAlignedMemory is not a power of two.\n");
29 std::abort();
30 }
31 if (or_mask > alignment) {
32 fprintf(stderr, "warning: or_mask passed into GetAlignedMemory is too high.\n");
33 std::abort();
34 }
35 uintptr_t ptr = reinterpret_cast<uintptr_t>(orig_ptr);
36 if (alignment > 0) {
37 // When setting the alignment, set it to exactly the alignment chosen.
38 // The pointer returned will be guaranteed not to be aligned to anything
39 // more than that.
40 ptr += alignment - (ptr & (alignment - 1));
41 ptr |= alignment | or_mask;
42 }
43
44 return reinterpret_cast<char*>(ptr);
45}
46
47char *GetAlignedPtr(std::vector<char>* buf, size_t alignment, size_t nbytes) {
48 buf->resize(nbytes + 3 * alignment);
49 return GetAlignedMemory(buf->data(), alignment, 0);
50}
51
52char *GetAlignedPtrFilled(std::vector<char>* buf, size_t alignment, size_t nbytes, char fill_byte) {
53 char* buf_aligned = GetAlignedPtr(buf, alignment, nbytes);
54 memset(buf_aligned, fill_byte, nbytes);
55 return buf_aligned;
56}
57
58bool LockToCPU(int cpu_to_lock) {
59 cpu_set_t cpuset;
60
61 CPU_ZERO(&cpuset);
62 if (sched_getaffinity(0, sizeof(cpuset), &cpuset) != 0) {
63 perror("sched_getaffinity failed");
64 return false;
65 }
66
67 if (cpu_to_lock < 0) {
68 // Lock to the last active core we find.
69 for (int i = 0; i < CPU_SETSIZE; i++) {
70 if (CPU_ISSET(i, &cpuset)) {
71 cpu_to_lock = i;
72 }
73 }
74 } else if (!CPU_ISSET(cpu_to_lock, &cpuset)) {
75 printf("Cpu %d does not exist.\n", cpu_to_lock);
76 return false;
77 }
78
79 if (cpu_to_lock < 0) {
80 printf("Cannot find any valid cpu to lock.\n");
81 return false;
82 }
83
84 CPU_ZERO(&cpuset);
85 CPU_SET(cpu_to_lock, &cpuset);
86 if (sched_setaffinity(0, sizeof(cpuset), &cpuset) != 0) {
87 perror("sched_setaffinity failed");
88 return false;
89 }
90
91 return true;
92}