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