gem5  v22.1.0.0
shared_memory_server.cc
Go to the documentation of this file.
1 /*
2  * Copyright 2022 Google, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met: redistributions of source code must retain the above copyright
7  * notice, this list of conditions and the following disclaimer;
8  * redistributions in binary form must reproduce the above copyright
9  * notice, this list of conditions and the following disclaimer in the
10  * documentation and/or other materials provided with the distribution;
11  * neither the name of the copyright holders nor the names of its
12  * contributors may be used to endorse or promote products derived from
13  * this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
29 
30 #include <arpa/inet.h>
31 #include <fcntl.h>
32 #include <poll.h>
33 #include <sys/mman.h>
34 #include <sys/socket.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <sys/un.h>
38 #include <unistd.h>
39 
40 #include <algorithm>
41 #include <cerrno>
42 #include <cstring>
43 
44 #include "base/logging.hh"
45 #include "base/output.hh"
46 #include "base/pollevent.hh"
47 #include "base/socket.hh"
48 
49 namespace gem5
50 {
51 namespace memory
52 {
53 
54 SharedMemoryServer::SharedMemoryServer(const SharedMemoryServerParams& params)
55  : SimObject(params), unixSocketPath(simout.resolve(params.server_path)),
56  system(params.system), serverFd(-1)
57 {
58  fatal_if(system == nullptr, "Requires a system to share memory from!");
59  // Create a new unix socket.
60  serverFd = ListenSocket::socketCloexec(AF_UNIX, SOCK_STREAM, 0);
61  panic_if(serverFd < 0, "%s: cannot create unix socket: %s", name(),
62  strerror(errno));
63  // Bind to the specified path.
64  sockaddr_un serv_addr = {};
65  serv_addr.sun_family = AF_UNIX;
66  strncpy(serv_addr.sun_path, unixSocketPath.c_str(),
67  sizeof(serv_addr.sun_path) - 1);
68  // If the target path is truncated, warn the user that the actual path is
69  // different and update the target path.
70  if (strlen(serv_addr.sun_path) != unixSocketPath.size()) {
71  warn("%s: unix socket path truncated, expect '%s' but get '%s'",
72  name(), unixSocketPath, serv_addr.sun_path);
73  unixSocketPath = serv_addr.sun_path;
74  }
75  // Ensure the unix socket path to use is not occupied. Also, if there's
76  // actually anything to be removed, warn the user something might be off.
77  bool old_sock_removed = unlink(unixSocketPath.c_str()) == 0;
78  warn_if(old_sock_removed,
79  "%s: the server path %s was occupied and will be replaced. Please "
80  "make sure there is no other server using the same path.",
81  name(), unixSocketPath);
82  int bind_retv = bind(serverFd, reinterpret_cast<sockaddr*>(&serv_addr),
83  sizeof(serv_addr));
84  fatal_if(bind_retv != 0, "%s: cannot bind unix socket: %s", name(),
85  strerror(errno));
86  // Start listening.
87  int listen_retv = listen(serverFd, 1);
88  fatal_if(listen_retv != 0, "%s: listen failed: %s", name(),
89  strerror(errno));
90  listenSocketEvent.reset(new ListenSocketEvent(serverFd, this));
92  inform("%s: listening at %s", name(), unixSocketPath);
93 }
94 
96 {
97  int unlink_retv = unlink(unixSocketPath.c_str());
98  warn_if(unlink_retv != 0, "%s: cannot unlink unix socket: %s", name(),
99  strerror(errno));
100  int close_retv = close(serverFd);
101  warn_if(close_retv != 0, "%s: cannot close unix socket: %s", name(),
102  strerror(errno));
103 }
104 
106  int fd, SharedMemoryServer* shm_server)
107  : PollEvent(fd, POLLIN), shmServer(shm_server),
108  eventName(shmServer->name() + ".fd" + std::to_string(fd))
109 {
110 }
111 
112 const std::string&
114 {
115  return eventName;
116 }
117 
118 bool
120 {
121  char* char_buffer = reinterpret_cast<char*>(buffer);
122  for (size_t offset = 0; offset < size;) {
123  ssize_t retv = recv(pfd.fd, char_buffer + offset, size - offset, 0);
124  if (retv >= 0) {
125  offset += retv;
126  } else if (errno != EINTR) {
127  warn("%s: recv failed: %s", name(), strerror(errno));
128  return false;
129  }
130  }
131  return true;
132 }
133 
134 void
136 {
137  panic_if(revents & (POLLERR | POLLNVAL), "%s: listen socket is broken",
138  name());
139  int cli_fd = ListenSocket::acceptCloexec(pfd.fd, nullptr, nullptr);
140  panic_if(cli_fd < 0, "%s: accept failed: %s", name(), strerror(errno));
141  inform("%s: accept new connection %d", name(), cli_fd);
142  shmServer->clientSocketEvents[cli_fd].reset(
143  new ClientSocketEvent(cli_fd, shmServer));
144  pollQueue.schedule(shmServer->clientSocketEvents[cli_fd].get());
145 }
146 
147 void
149 {
150  do {
151  // Ensure the connection is not closed nor broken.
152  if (revents & (POLLHUP | POLLERR | POLLNVAL)) {
153  break;
154  }
155 
156  // Receive a request packet. We ignore the endianness as unix socket
157  // only allows communication on the same system anyway.
158  RequestType req_type;
159  struct
160  {
161  uint64_t start;
162  uint64_t end;
163  } request;
164  if (!tryReadAll(&req_type, sizeof(req_type))) {
165  break;
166  }
167  if (req_type != RequestType::kGetPhysRange) {
168  warn("%s: receive unknown request: %d", name(),
169  static_cast<int>(req_type));
170  break;
171  }
172  if (!tryReadAll(&request, sizeof(request))) {
173  break;
174  }
175  AddrRange range(request.start, request.end);
176  inform("%s: receive request: %s", name(), range.to_string());
177 
178  // Identify the backing store.
179  const auto& stores = shmServer->system->getPhysMem().getBackingStore();
180  auto it = std::find_if(
181  stores.begin(), stores.end(), [&](const BackingStoreEntry& entry) {
182  return entry.shmFd >= 0 && range.isSubset(entry.range);
183  });
184  if (it == stores.end()) {
185  warn("%s: cannot find backing store for %s", name(),
186  range.to_string());
187  break;
188  }
189  inform("%s: find shared backing store for %s at %s, shm=%d:%lld",
190  name(), range.to_string(), it->range.to_string(), it->shmFd,
191  (unsigned long long)it->shmOffset);
192 
193  // Populate response message.
194  // mmap fd @ offset <===> [start, end] in simulated phys mem.
195  msghdr msg = {};
196  // Setup iovec for fields other than fd. We ignore the endianness as
197  // unix socket only allows communication on the same system anyway.
198  struct
199  {
200  off_t offset;
201  } response;
202  // (offset of the request range in shared memory) =
203  // (offset of the full range in shared memory) +
204  // (offset of the request range in the full range)
205  response.offset = it->shmOffset + (range.start() - it->range.start());
206  iovec ios = {.iov_base = &response, .iov_len = sizeof(response)};
207  msg.msg_iov = &ios;
208  msg.msg_iovlen = 1;
209  // Setup fd as an ancillary data.
210  union
211  {
212  char buf[CMSG_SPACE(sizeof(it->shmFd))];
213  struct cmsghdr align;
214  } cmsgs;
215  msg.msg_control = cmsgs.buf;
216  msg.msg_controllen = sizeof(cmsgs.buf);
217  cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
218  cmsg->cmsg_level = SOL_SOCKET;
219  cmsg->cmsg_type = SCM_RIGHTS;
220  cmsg->cmsg_len = CMSG_LEN(sizeof(it->shmFd));
221  memcpy(CMSG_DATA(cmsg), &it->shmFd, sizeof(it->shmFd));
222  // Send the response.
223  int retv = sendmsg(pfd.fd, &msg, 0);
224  if (retv < 0) {
225  warn("%s: sendmsg failed: %s", name(), strerror(errno));
226  break;
227  }
228  if (retv != sizeof(response)) {
229  warn("%s: failed to send all response at once", name());
230  break;
231  }
232 
233  // Request done.
234  inform("%s: request done", name());
235  return;
236  } while (false);
237 
238  // If we ever reach here, our client either close the connection or is
239  // somehow broken. We'll just close the connection and move on.
240  inform("%s: closing connection", name());
241  close(pfd.fd);
242  shmServer->clientSocketEvents.erase(pfd.fd);
243 }
244 
245 } // namespace memory
246 } // namespace gem5
The AddrRange class encapsulates an address range, and supports a number of tests to check if two ran...
Definition: addr_range.hh:82
static int socketCloexec(int domain, int type, int protocol)
Definition: socket.cc:87
static int acceptCloexec(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
Definition: socket.cc:96
virtual std::string name() const
Definition: named.hh:47
Abstract superclass for simulation objects.
Definition: sim_object.hh:148
A single entry for the backing store.
Definition: physical.hh:65
BaseShmPollEvent(int fd, SharedMemoryServer *shm_server)
SharedMemoryServer(const SharedMemoryServerParams &params)
std::unique_ptr< ListenSocketEvent > listenSocketEvent
Addr start() const
Get the start address of the range.
Definition: addr_range.hh:343
std::string to_string() const
Get a string representation of the range.
Definition: addr_range.hh:360
#define fatal_if(cond,...)
Conditional fatal macro that checks the supplied condition and only causes a fatal error if the condi...
Definition: logging.hh:226
#define panic_if(cond,...)
Conditional panic macro that checks the supplied condition and only panics if the condition is true a...
Definition: logging.hh:204
PollQueue pollQueue
Definition: pollevent.cc:55
void schedule(PollEvent *event)
Definition: pollevent.cc:159
#define warn(...)
Definition: logging.hh:246
#define warn_if(cond,...)
Conditional warning macro that checks the supplied condition and only prints a warning if the conditi...
Definition: logging.hh:273
#define inform(...)
Definition: logging.hh:247
Bitfield< 14, 12 > fd
Definition: types.hh:150
Bitfield< 23, 0 > offset
Definition: types.hh:144
Bitfield< 15 > system
Definition: misc.hh:1004
const Info * resolve(const std::string &name)
Definition: statistics.cc:319
Reference material can be found at the JEDEC website: UFS standard http://www.jedec....
OutputDirectory simout
Definition: output.cc:62
void align(const scfx_rep &lhs, const scfx_rep &rhs, int &new_wp, int &len_mant, scfx_mant_ref &lhs_mant, scfx_mant_ref &rhs_mant)
Definition: scfx_rep.cc:2051
const std::string to_string(sc_enc enc)
Definition: sc_fxdefs.cc:60
Overload hash function for BasicBlockRange type.
Definition: misc.hh:2826
Definition: mem.h:38
const std::string & name()
Definition: trace.cc:49

Generated on Wed Dec 21 2022 10:22:39 for gem5 by doxygen 1.9.1