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