2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "fec_private.h"
31 static void * __process(void *cookie)
33 process_info *p = static_cast<process_info *>(cookie);
35 debug("thread %d: [%" PRIu64 ", %" PRIu64 ")", p->id, p->offset,
36 p->offset + p->count);
38 p->rc = p->func(p->f, p->buf, p->count, p->offset, &p->errors);
42 /* launches a maximum number of threads to process a read */
43 ssize_t process(fec_handle *f, uint8_t *buf, size_t count, uint64_t offset,
54 int threads = sysconf(_SC_NPROCESSORS_ONLN);
56 if (threads < WORK_MIN_THREADS) {
57 threads = WORK_MIN_THREADS;
58 } else if (threads > WORK_MAX_THREADS) {
59 threads = WORK_MAX_THREADS;
62 uint64_t start = (offset / FEC_BLOCKSIZE) * FEC_BLOCKSIZE;
63 size_t blocks = fec_div_round_up(count, FEC_BLOCKSIZE);
65 size_t count_per_thread = fec_div_round_up(blocks, threads) * FEC_BLOCKSIZE;
66 size_t max_threads = fec_div_round_up(count, count_per_thread);
68 if ((size_t)threads > max_threads) {
69 threads = (int)max_threads;
73 uint64_t pos = offset;
74 uint64_t end = start + count_per_thread;
76 debug("%d threads, %zu bytes per thread (total %zu)", threads,
77 count_per_thread, count);
79 std::vector<pthread_t> handles;
80 process_info info[threads];
83 /* start threads to process queue */
84 for (int i = 0; i < threads; ++i) {
89 info[i].buf = &buf[pos - offset];
90 info[i].count = (size_t)(end - pos);
96 if (info[i].count > left) {
102 if (pthread_create(&thread, NULL, __process, &info[i]) != 0) {
103 error("failed to create thread: %s", strerror(errno));
106 handles.push_back(thread);
110 end += count_per_thread;
111 left -= info[i].count;
118 /* wait for all threads to complete */
119 for (auto thread : handles) {
120 process_info *p = NULL;
122 if (pthread_join(thread, (void **)&p) != 0) {
123 error("failed to join thread: %s", strerror(errno));
125 } else if (!p || p->rc == -1) {
129 f->errors += p->errors;