blob: 7e8789aa2a163ec3baa1b699d30c0a3022d63162 [file] [log] [blame]
Finn Williams2ed809c2020-04-20 21:21:07 +01001//
2// Copyright © 2020 Arm Ltd. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5
Finn Williams9937f932020-04-29 12:00:24 +01006#include "BasePipeServer.hpp"
7
Finn Williamse09fc822020-04-29 13:17:30 +01008#include "common/include/Constants.hpp"
9
Finn Williams2ed809c2020-04-20 21:21:07 +010010#include <iostream>
11#include <boost/cast.hpp>
12#include <vector>
13#include <iomanip>
Finn Williams2ed809c2020-04-20 21:21:07 +010014
15using namespace armnnUtils;
16
17namespace armnnProfiling
18{
19
20bool BasePipeServer::ReadFromSocket(uint8_t* packetData, uint32_t expectedLength)
21{
22 // This is a blocking read until either expectedLength has been received or an error is detected.
23 long totalBytesRead = 0;
24 while (boost::numeric_cast<uint32_t>(totalBytesRead) < expectedLength)
25 {
26 long bytesRead = Sockets::Read(m_ClientConnection, packetData, expectedLength);
27 if (bytesRead < 0)
28 {
29 std::cerr << ": Failure when reading from client socket: " << strerror(errno) << std::endl;
30 return false;
31 }
32 if (bytesRead == 0)
33 {
34 std::cerr << ": EOF while reading from client socket." << std::endl;
35 return false;
36 }
37 totalBytesRead += bytesRead;
38 }
39 return true;
40};
41
42bool BasePipeServer::WaitForStreamMetaData()
43{
44 if (m_EchoPackets)
45 {
46 std::cout << "Waiting for stream meta data..." << std::endl;
47 }
48 // The start of the stream metadata is 2x32bit words, 0 and packet length.
49 uint8_t header[8];
50 if (!ReadFromSocket(header, 8))
51 {
52 return false;
53 }
54 EchoPacket(PacketDirection::ReceivedHeader, header, 8);
55 // The first word, stream_metadata_identifer, should always be 0.
56 if (ToUint32(&header[0], TargetEndianness::BeWire) != 0)
57 {
58 std::cerr << ": Protocol error. The stream_metadata_identifer was not 0." << std::endl;
59 return false;
60 }
61
62 uint8_t pipeMagic[4];
63 if (!ReadFromSocket(pipeMagic, 4))
64 {
65 return false;
66 }
67 EchoPacket(PacketDirection::ReceivedData, pipeMagic, 4);
68
69 // Before we interpret the length we need to read the pipe_magic word to determine endianness.
Finn Williamse09fc822020-04-29 13:17:30 +010070 if (ToUint32(&pipeMagic[0], TargetEndianness::BeWire) == armnnProfiling::PIPE_MAGIC)
Finn Williams2ed809c2020-04-20 21:21:07 +010071 {
72 m_Endianness = TargetEndianness::BeWire;
73 }
Finn Williamse09fc822020-04-29 13:17:30 +010074 else if (ToUint32(&pipeMagic[0], TargetEndianness::LeWire) == armnnProfiling::PIPE_MAGIC)
Finn Williams2ed809c2020-04-20 21:21:07 +010075 {
76 m_Endianness = TargetEndianness::LeWire;
77 }
78 else
79 {
80 std::cerr << ": Protocol read error. Unable to read PIPE_MAGIC value." << std::endl;
81 return false;
82 }
83 // Now we know the endianness we can get the length from the header.
84 // Remember we already read the pipe magic 4 bytes.
85 uint32_t metaDataLength = ToUint32(&header[4], m_Endianness) - 4;
86 // Read the entire packet.
87 std::vector<uint8_t> packetData(metaDataLength);
88 if (metaDataLength !=
89 boost::numeric_cast<uint32_t>(Sockets::Read(m_ClientConnection, packetData.data(), metaDataLength)))
90 {
91 std::cerr << ": Protocol read error. Data length mismatch." << std::endl;
92 return false;
93 }
94 EchoPacket(PacketDirection::ReceivedData, packetData.data(), metaDataLength);
95 m_StreamMetaDataVersion = ToUint32(&packetData[0], m_Endianness);
96 m_StreamMetaDataMaxDataLen = ToUint32(&packetData[4], m_Endianness);
97 m_StreamMetaDataPid = ToUint32(&packetData[8], m_Endianness);
98
99 return true;
100}
101
102armnn::profiling::Packet BasePipeServer::WaitForPacket(uint32_t timeoutMs)
103{
104 // Is there currently more than a headers worth of data waiting to be read?
105 int bytes_available;
106 Sockets::Ioctl(m_ClientConnection, FIONREAD, &bytes_available);
107 if (bytes_available > 8)
108 {
109 // Yes there is. Read it:
110 return ReceivePacket();
111 }
112 else
113 {
114 // No there's not. Poll for more data.
115 struct pollfd pollingFd[1]{};
116 pollingFd[0].fd = m_ClientConnection;
117 int pollResult = Sockets::Poll(pollingFd, 1, static_cast<int>(timeoutMs));
118
119 switch (pollResult)
120 {
121 // Error
122 case -1:
123 throw armnn::RuntimeException(std::string("File descriptor reported an error during polling: ") +
124 strerror(errno));
125
126 // Timeout
127 case 0:
128 throw armnn::TimeoutException("Timeout while waiting to receive packet.");
129
130 // Normal poll return. It could still contain an error signal
131 default:
132 // Check if the socket reported an error
133 if (pollingFd[0].revents & (POLLNVAL | POLLERR | POLLHUP))
134 {
135 if (pollingFd[0].revents == POLLNVAL)
136 {
137 throw armnn::RuntimeException(std::string("Error while polling receiving socket: POLLNVAL"));
138 }
139 if (pollingFd[0].revents == POLLERR)
140 {
141 throw armnn::RuntimeException(std::string("Error while polling receiving socket: POLLERR: ") +
142 strerror(errno));
143 }
144 if (pollingFd[0].revents == POLLHUP)
145 {
146 throw armnn::RuntimeException(std::string("Connection closed by remote client: POLLHUP"));
147 }
148 }
149
150 // Check if there is data to read
151 if (!(pollingFd[0].revents & (POLLIN)))
152 {
153 // This is a corner case. The socket as been woken up but not with any data.
154 // We'll throw a timeout exception to loop around again.
155 throw armnn::TimeoutException("File descriptor was polled but no data was available to receive.");
156 }
157 return ReceivePacket();
158 }
159 }
160}
161
162armnn::profiling::Packet BasePipeServer::ReceivePacket()
163{
164 uint32_t header[2];
165 if (!ReadHeader(header))
166 {
167 return armnn::profiling::Packet();
168 }
169 // Read data_length bytes from the socket.
170 std::unique_ptr<unsigned char[]> uniquePacketData = std::make_unique<unsigned char[]>(header[1]);
171 unsigned char* packetData = reinterpret_cast<unsigned char*>(uniquePacketData.get());
172
173 if (!ReadFromSocket(packetData, header[1]))
174 {
175 return armnn::profiling::Packet();
176 }
177
178 EchoPacket(PacketDirection::ReceivedData, packetData, header[1]);
179
180 // Construct received packet
181 armnn::profiling::Packet packetRx = armnn::profiling::Packet(header[0], header[1], uniquePacketData);
182 if (m_EchoPackets)
183 {
184 std::cout << "Processing packet ID= " << packetRx.GetPacketId() << " Length=" << packetRx.GetLength()
185 << std::endl;
186 }
187
188 return packetRx;
189}
190
191bool BasePipeServer::SendPacket(uint32_t packetFamily, uint32_t packetId, const uint8_t* data, uint32_t dataLength)
192{
193 // Construct a packet from the id and data given and send it to the client.
194 // Encode the header.
195 uint32_t header[2];
196 header[0] = packetFamily << 26 | packetId << 16;
197 header[1] = dataLength;
198 // Add the header to the packet.
199 std::vector<uint8_t> packet(8 + dataLength);
200 InsertU32(header[0], packet.data(), m_Endianness);
201 InsertU32(header[1], packet.data() + 4, m_Endianness);
202 // And the rest of the data if there is any.
203 if (dataLength > 0)
204 {
205 memcpy((packet.data() + 8), data, dataLength);
206 }
207 EchoPacket(PacketDirection::Sending, packet.data(), packet.size());
208 if (-1 == armnnUtils::Sockets::Write(m_ClientConnection, packet.data(), packet.size()))
209 {
210 std::cerr << ": Failure when writing to client socket: " << strerror(errno) << std::endl;
211 return false;
212 }
213 return true;
214}
215
216bool BasePipeServer::ReadHeader(uint32_t headerAsWords[2])
217{
218 // The header will always be 2x32bit words.
219 uint8_t header[8];
220 if (!ReadFromSocket(header, 8))
221 {
222 return false;
223 }
224 EchoPacket(PacketDirection::ReceivedHeader, header, 8);
225 headerAsWords[0] = ToUint32(&header[0], m_Endianness);
226 headerAsWords[1] = ToUint32(&header[4], m_Endianness);
227 return true;
228}
229
230void BasePipeServer::EchoPacket(PacketDirection direction, uint8_t* packet, size_t lengthInBytes)
231{
232 // If enabled print the contents of the data packet to the console.
233 if (m_EchoPackets)
234 {
235 if (direction == PacketDirection::Sending)
236 {
237 std::cout << "TX " << std::dec << lengthInBytes << " bytes : ";
238 }
239 else if (direction == PacketDirection::ReceivedHeader)
240 {
241 std::cout << "RX Header " << std::dec << lengthInBytes << " bytes : ";
242 }
243 else
244 {
245 std::cout << "RX Data " << std::dec << lengthInBytes << " bytes : ";
246 }
247 for (unsigned int i = 0; i < lengthInBytes; i++)
248 {
249 if ((i % 10) == 0)
250 {
251 std::cout << std::endl;
252 }
253 std::cout << "0x" << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned int>(packet[i])
254 << " ";
255 }
256 std::cout << std::endl;
257 }
258}
259
260uint32_t BasePipeServer::ToUint32(uint8_t* data, TargetEndianness endianness)
261{
262 // Extract the first 4 bytes starting at data and push them into a 32bit integer based on the
263 // specified endianness.
264 if (endianness == TargetEndianness::BeWire)
265 {
266 return static_cast<uint32_t>(data[0]) << 24 | static_cast<uint32_t>(data[1]) << 16 |
267 static_cast<uint32_t>(data[2]) << 8 | static_cast<uint32_t>(data[3]);
268 }
269 else
270 {
271 return static_cast<uint32_t>(data[3]) << 24 | static_cast<uint32_t>(data[2]) << 16 |
272 static_cast<uint32_t>(data[1]) << 8 | static_cast<uint32_t>(data[0]);
273 }
274}
275
276void BasePipeServer::InsertU32(uint32_t value, uint8_t* data, TargetEndianness endianness)
277{
278 // Take the bytes of a 32bit integer and copy them into char array starting at data considering
279 // the endianness value.
280 if (endianness == TargetEndianness::BeWire)
281 {
282 *data = static_cast<uint8_t>((value >> 24) & 0xFF);
283 *(data + 1) = static_cast<uint8_t>((value >> 16) & 0xFF);
284 *(data + 2) = static_cast<uint8_t>((value >> 8) & 0xFF);
285 *(data + 3) = static_cast<uint8_t>(value & 0xFF);
286 }
287 else
288 {
289 *(data + 3) = static_cast<uint8_t>((value >> 24) & 0xFF);
290 *(data + 2) = static_cast<uint8_t>((value >> 16) & 0xFF);
291 *(data + 1) = static_cast<uint8_t>((value >> 8) & 0xFF);
292 *data = static_cast<uint8_t>(value & 0xFF);
293 }
294}
295
296} // namespace armnnProfiling