blob: ecf4044db85471e212ad427e2a4655d6a9270aae [file] [log] [blame]
Tomasz Wasilczyk87329672019-07-12 11:43:00 -07001/*
2 * Copyright (C) 2019 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 "CanSocket.h"
18
19#include <android-base/logging.h>
20#include <libnetdevice/can.h>
21#include <libnetdevice/libnetdevice.h>
22#include <linux/can.h>
23#include <utils/SystemClock.h>
24
25#include <chrono>
26
27namespace android {
28namespace hardware {
29namespace automotive {
30namespace can {
31namespace V1_0 {
32namespace implementation {
33
34using namespace std::chrono_literals;
35
36/**
37 * How frequently the read thread checks whether the interface was asked to be down.
38 *
39 * Note: This does *not* affect read timing or bandwidth, just CPU load vs time to
40 * down the interface.
41 */
42static constexpr auto kReadPooling = 100ms;
43
44std::unique_ptr<CanSocket> CanSocket::open(const std::string& ifname, ReadCallback rdcb,
45 ErrorCallback errcb) {
46 auto sock = netdevice::can::socket(ifname);
47 if (!sock.ok()) {
48 LOG(ERROR) << "Can't open CAN socket on " << ifname;
49 return nullptr;
50 }
51
52 // Can't use std::make_unique due to private CanSocket constructor.
53 return std::unique_ptr<CanSocket>(new CanSocket(std::move(sock), rdcb, errcb));
54}
55
56CanSocket::CanSocket(base::unique_fd socket, ReadCallback rdcb, ErrorCallback errcb)
57 : mReadCallback(rdcb),
58 mErrorCallback(errcb),
59 mSocket(std::move(socket)),
60 mReaderThread(&CanSocket::readerThread, this) {}
61
62CanSocket::~CanSocket() {
63 mStopReaderThread = true;
Tomasz Wasilczyka9061962019-11-04 12:53:09 -080064
65 /* CanSocket can be brought down as a result of read failure, from the same thread,
66 * so let's just detach and let it finish on its own. */
67 if (mReaderThreadFinished) {
68 mReaderThread.detach();
69 } else {
70 mReaderThread.join();
71 }
Tomasz Wasilczyk87329672019-07-12 11:43:00 -070072}
73
74bool CanSocket::send(const struct canfd_frame& frame) {
75 const auto res = write(mSocket.get(), &frame, CAN_MTU);
76 if (res < 0) {
77 LOG(DEBUG) << "CanSocket send failed: " << errno;
78 return false;
79 }
80 if (res != CAN_MTU) {
81 LOG(DEBUG) << "CanSocket sent wrong number of bytes: " << res;
82 return false;
83 }
84 return true;
85}
86
87static struct timeval toTimeval(std::chrono::microseconds t) {
88 struct timeval tv;
89 tv.tv_sec = t / 1s;
90 tv.tv_usec = (t % 1s) / 1us;
91 return tv;
92}
93
94static int selectRead(const base::unique_fd& fd, std::chrono::microseconds timeout) {
95 auto timeouttv = toTimeval(timeout);
96 fd_set readfds;
97 FD_ZERO(&readfds);
98 FD_SET(fd.get(), &readfds);
99 return select(fd.get() + 1, &readfds, nullptr, nullptr, &timeouttv);
100}
101
102void CanSocket::readerThread() {
103 LOG(VERBOSE) << "Reader thread started";
Tomasz Wasilczyka9061962019-11-04 12:53:09 -0800104 int errnoCopy = 0;
Tomasz Wasilczyk87329672019-07-12 11:43:00 -0700105
106 while (!mStopReaderThread) {
107 /* The ideal would be to have a blocking read(3) call and interrupt it with shutdown(3).
108 * This is unfortunately not supported for SocketCAN, so we need to rely on select(3).
109 */
110 const auto sel = selectRead(mSocket, kReadPooling);
111 if (sel == 0) continue; // timeout
112 if (sel == -1) {
113 LOG(ERROR) << "Select failed: " << errno;
114 break;
115 }
116
117 struct canfd_frame frame;
118 const auto nbytes = read(mSocket.get(), &frame, CAN_MTU);
119
120 /* We could use SIOCGSTAMP to get a precise UNIX timestamp for a given packet, but what
121 * we really need is a time since boot. There is no direct way to convert between these
122 * clocks. We could implement a class to calculate the difference between the clocks
123 * (querying both several times and picking the smallest difference); apply the difference
124 * to a SIOCGSTAMP returned value; re-synchronize if the elapsed time is too much in the
125 * past (indicating the UNIX timestamp might have been adjusted).
126 *
127 * Apart from the added complexity, it's possible the added calculations and system calls
128 * would add so much time to the processing pipeline so the precision of the reported time
129 * was buried under the subsystem latency. Let's just use a local time since boot here and
130 * leave precise hardware timestamps for custom proprietary implementations (if needed).
131 */
132 const std::chrono::nanoseconds ts(elapsedRealtimeNano());
133
134 if (nbytes != CAN_MTU) {
135 if (nbytes >= 0) {
136 LOG(ERROR) << "Failed to read CAN packet, got " << nbytes << " bytes";
137 break;
138 }
139 if (errno == EAGAIN) continue;
140
Tomasz Wasilczyka9061962019-11-04 12:53:09 -0800141 errnoCopy = errno;
142 LOG(ERROR) << "Failed to read CAN packet: " << strerror(errno) << " (" << errno << ")";
Tomasz Wasilczyk87329672019-07-12 11:43:00 -0700143 break;
144 }
145
146 mReadCallback(frame, ts);
147 }
148
Tomasz Wasilczyka9061962019-11-04 12:53:09 -0800149 bool failed = !mStopReaderThread;
150 auto errCb = mErrorCallback;
151 mReaderThreadFinished = true;
152
153 // Don't access any fields from here, see CanSocket::~CanSocket comment about detached thread
154 if (failed) errCb(errnoCopy);
Tomasz Wasilczyk87329672019-07-12 11:43:00 -0700155
156 LOG(VERBOSE) << "Reader thread stopped";
157}
158
159} // namespace implementation
160} // namespace V1_0
161} // namespace can
162} // namespace automotive
163} // namespace hardware
164} // namespace android