]> git.ipfire.org Git - thirdparty/squid.git/blame - src/DiskIO/IpcIo/IpcIoFile.cc
SourceFormat Enforcement
[thirdparty/squid.git] / src / DiskIO / IpcIo / IpcIoFile.cc
CommitLineData
254912f3 1/*
bbc27441
AJ
2 * Copyright (C) 1996-2014 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
254912f3
AR
7 */
8
bbc27441
AJ
9/* DEBUG: section 47 Store Directory Routines */
10
f7f3304a 11#include "squid.h"
f5591061 12#include "base/RunnersRegistry.h"
254912f3 13#include "base/TextException.h"
602d9612 14#include "disk.h"
254912f3
AR
15#include "DiskIO/IORequestor.h"
16#include "DiskIO/IpcIo/IpcIoFile.h"
17#include "DiskIO/ReadRequest.h"
18#include "DiskIO/WriteRequest.h"
c4ad1349 19#include "fd.h"
582c2af2 20#include "globals.h"
21d845b1 21#include "ipc/mem/Pages.h"
254912f3
AR
22#include "ipc/Messages.h"
23#include "ipc/Port.h"
f5591061 24#include "ipc/Queue.h"
9a51593d 25#include "ipc/StrandSearch.h"
254912f3 26#include "ipc/UdsOp.h"
7015a149 27#include "SBuf.h"
4d5904f7 28#include "SquidConfig.h"
21d845b1
FC
29#include "SquidTime.h"
30#include "StatCounters.h"
5bed43d6 31#include "tools.h"
254912f3 32
1a30fdf5
AJ
33#include <cerrno>
34
254912f3
AR
35CBDATA_CLASS_INIT(IpcIoFile);
36
f5591061
DK
37/// shared memory segment path to use for IpcIoFile maps
38static const char *const ShmLabel = "io_file";
ea2cdeb6
DK
39/// a single worker-to-disker or disker-to-worker queue capacity; up
40/// to 2*QueueCapacity I/O requests queued between a single worker and
41/// a single disker
42// TODO: make configurable or compute from squid.conf settings if possible
43static const int QueueCapacity = 1024;
f5591061 44
fa61cefe 45const double IpcIoFile::Timeout = 7; // seconds; XXX: ALL,9 may require more
b2aa0934
DK
46IpcIoFile::IpcIoFileList IpcIoFile::WaitingForOpen;
47IpcIoFile::IpcIoFilesMap IpcIoFile::IpcIoFiles;
f5591061 48std::auto_ptr<IpcIoFile::Queue> IpcIoFile::queue;
254912f3 49
c792f7fc
AR
50bool IpcIoFile::DiskerHandleMoreRequestsScheduled = false;
51
7015a149
AR
52static bool DiskerOpen(const SBuf &path, int flags, mode_t mode);
53static void DiskerClose(const SBuf &path);
254912f3 54
fa61cefe
AR
55/// IpcIo wrapper for debugs() streams; XXX: find a better class name
56struct SipcIo {
57 SipcIo(int aWorker, const IpcIoMsg &aMsg, int aDisker):
f53969cc 58 worker(aWorker), msg(aMsg), disker(aDisker) {}
fa61cefe
AR
59
60 int worker;
61 const IpcIoMsg &msg;
62 int disker;
63};
64
65std::ostream &
66operator <<(std::ostream &os, const SipcIo &sio)
67{
68 return os << "ipcIo" << sio.worker << '.' << sio.msg.requestId <<
9199139f 69 (sio.msg.command == IpcIo::cmdRead ? 'r' : 'w') << sio.disker;
fa61cefe
AR
70}
71
254912f3 72IpcIoFile::IpcIoFile(char const *aDb):
f53969cc
SM
73 dbName(aDb), diskId(-1), error_(false), lastRequestId(0),
74 olderRequests(&requestMap1), newerRequests(&requestMap2),
75 timeoutCheckScheduled(false)
254912f3
AR
76{
77}
78
79IpcIoFile::~IpcIoFile()
80{
b2aa0934
DK
81 if (diskId >= 0) {
82 const IpcIoFilesMap::iterator i = IpcIoFiles.find(diskId);
83 // XXX: warn and continue?
84 Must(i != IpcIoFiles.end());
85 Must(i->second == this);
86 IpcIoFiles.erase(i);
87 }
254912f3
AR
88}
89
43ebbac3
AR
90void
91IpcIoFile::configure(const Config &cfg)
92{
93 DiskFile::configure(cfg);
94 config = cfg;
95}
96
254912f3
AR
97void
98IpcIoFile::open(int flags, mode_t mode, RefCount<IORequestor> callback)
99{
100 ioRequestor = callback;
101 Must(diskId < 0); // we do not know our disker yet
f5591061
DK
102
103 if (!queue.get())
104 queue.reset(new Queue(ShmLabel, IamWorkerProcess() ? Queue::groupA : Queue::groupB, KidIdentifier));
254912f3
AR
105
106 if (IamDiskProcess()) {
7015a149 107 error_ = !DiskerOpen(SBuf(dbName.termedBuf()), flags, mode);
f7091279
DK
108 if (error_)
109 return;
110
b2aa0934
DK
111 diskId = KidIdentifier;
112 const bool inserted =
113 IpcIoFiles.insert(std::make_pair(diskId, this)).second;
114 Must(inserted);
9a51593d 115
df881a0f
AR
116 queue->localRateLimit() =
117 static_cast<Ipc::QueueReader::Rate::Value>(config.ioRate);
118
f7091279
DK
119 Ipc::HereIamMessage ann(Ipc::StrandCoord(KidIdentifier, getpid()));
120 ann.strand.tag = dbName;
121 Ipc::TypedMsgHdr message;
122 ann.pack(message);
1ee292b7 123 SendMessage(Ipc::Port::CoordinatorAddr(), message);
f7091279 124
e528e570 125 ioRequestor->ioCompletedNotification();
254912f3 126 return;
9a51593d 127 }
254912f3 128
9a51593d
DK
129 Ipc::StrandSearchRequest request;
130 request.requestorId = KidIdentifier;
131 request.tag = dbName;
254912f3 132
9a51593d
DK
133 Ipc::TypedMsgHdr msg;
134 request.pack(msg);
1ee292b7 135 Ipc::SendMessage(Ipc::Port::CoordinatorAddr(), msg);
9a51593d 136
b2aa0934
DK
137 WaitingForOpen.push_back(this);
138
139 eventAdd("IpcIoFile::OpenTimeout", &IpcIoFile::OpenTimeout,
140 this, Timeout, 0, false); // "this" pointer is used as id
254912f3
AR
141}
142
143void
9199139f
AR
144IpcIoFile::openCompleted(const Ipc::StrandSearchResponse *const response)
145{
9a51593d 146 Must(diskId < 0); // we do not know our disker yet
9a51593d
DK
147
148 if (!response) {
82ed74dc
AR
149 debugs(79, DBG_IMPORTANT, "ERROR: " << dbName << " communication " <<
150 "channel establishment timeout");
caca86d7 151 error_ = true;
9a51593d
DK
152 } else {
153 diskId = response->strand.kidId;
154 if (diskId >= 0) {
b2aa0934
DK
155 const bool inserted =
156 IpcIoFiles.insert(std::make_pair(diskId, this)).second;
157 Must(inserted);
9a51593d 158 } else {
254912f3 159 error_ = true;
82ed74dc
AR
160 debugs(79, DBG_IMPORTANT, "ERROR: no disker claimed " <<
161 "responsibility for " << dbName);
9a51593d
DK
162 }
163 }
254912f3
AR
164
165 ioRequestor->ioCompletedNotification();
166}
167
168/**
169 * Alias for IpcIoFile::open(...)
170 \copydoc IpcIoFile::open(int flags, mode_t mode, RefCount<IORequestor> callback)
171 */
172void
173IpcIoFile::create(int flags, mode_t mode, RefCount<IORequestor> callback)
174{
175 assert(false); // check
176 /* We use the same logic path for open */
177 open(flags, mode, callback);
178}
179
180void
181IpcIoFile::close()
182{
183 assert(ioRequestor != NULL);
184
185 if (IamDiskProcess())
7015a149 186 DiskerClose(SBuf(dbName.termedBuf()));
9a51593d 187 // XXX: else nothing to do?
254912f3
AR
188
189 ioRequestor->closeCompleted();
190}
191
192bool
193IpcIoFile::canRead() const
194{
7e2d5ef6 195 return diskId >= 0 && !error_ && canWait();
254912f3
AR
196}
197
198bool
199IpcIoFile::canWrite() const
200{
7e2d5ef6 201 return diskId >= 0 && !error_ && canWait();
254912f3
AR
202}
203
204bool
205IpcIoFile::error() const
206{
207 return error_;
208}
209
210void
211IpcIoFile::read(ReadRequest *readRequest)
212{
213 debugs(79,3, HERE << "(disker" << diskId << ", " << readRequest->len << ", " <<
9199139f 214 readRequest->offset << ")");
254912f3
AR
215
216 assert(ioRequestor != NULL);
254912f3
AR
217 assert(readRequest->offset >= 0);
218 Must(!error_);
219
220 //assert(minOffset < 0 || minOffset <= readRequest->offset);
221 //assert(maxOffset < 0 || readRequest->offset + readRequest->len <= (uint64_t)maxOffset);
222
9a51593d 223 IpcIoPendingRequest *const pending = new IpcIoPendingRequest(this);
254912f3 224 pending->readRequest = readRequest;
7a907247 225 push(pending);
254912f3
AR
226}
227
228void
229IpcIoFile::readCompleted(ReadRequest *readRequest,
8ed94021 230 IpcIoMsg *const response)
254912f3 231{
caca86d7 232 bool ioError = false;
9a51593d 233 if (!response) {
0ef0509e 234 debugs(79, 3, HERE << "error: timeout");
caca86d7 235 ioError = true; // I/O timeout does not warrant setting error_?
9a51593d 236 } else {
70e3f706 237 if (response->xerrno) {
82ed74dc
AR
238 debugs(79, DBG_IMPORTANT, "ERROR: " << dbName << " read: " <<
239 xstrerr(response->xerrno));
70e3f706 240 ioError = error_ = true;
9199139f 241 } else if (!response->page) {
82ed74dc
AR
242 debugs(79, DBG_IMPORTANT, "ERROR: " << dbName << " read ran " <<
243 "out of shared memory pages");
70e3f706
DK
244 ioError = true;
245 } else {
246 const char *const buf = Ipc::Mem::PagePointer(response->page);
247 memcpy(readRequest->buf, buf, response->len);
248 }
254912f3 249
70e3f706
DK
250 Ipc::Mem::PutPage(response->page);
251 }
8ed94021 252
caca86d7 253 const ssize_t rlen = ioError ? -1 : (ssize_t)readRequest->len;
9199139f 254 const int errflag = ioError ? DISK_ERROR :DISK_OK;
20b0e1fe 255 ioRequestor->readCompleted(readRequest->buf, rlen, errflag, readRequest);
254912f3
AR
256}
257
258void
259IpcIoFile::write(WriteRequest *writeRequest)
260{
261 debugs(79,3, HERE << "(disker" << diskId << ", " << writeRequest->len << ", " <<
9199139f 262 writeRequest->offset << ")");
254912f3
AR
263
264 assert(ioRequestor != NULL);
254912f3
AR
265 assert(writeRequest->len > 0); // TODO: work around mmap failures on zero-len?
266 assert(writeRequest->offset >= 0);
267 Must(!error_);
268
269 //assert(minOffset < 0 || minOffset <= writeRequest->offset);
270 //assert(maxOffset < 0 || writeRequest->offset + writeRequest->len <= (uint64_t)maxOffset);
271
9a51593d 272 IpcIoPendingRequest *const pending = new IpcIoPendingRequest(this);
254912f3 273 pending->writeRequest = writeRequest;
7a907247 274 push(pending);
254912f3
AR
275}
276
277void
278IpcIoFile::writeCompleted(WriteRequest *writeRequest,
9a51593d 279 const IpcIoMsg *const response)
254912f3 280{
caca86d7 281 bool ioError = false;
9a51593d 282 if (!response) {
4e4f7fd9 283 debugs(79, 3, "disker " << diskId << " timeout");
caca86d7 284 ioError = true; // I/O timeout does not warrant setting error_?
9199139f 285 } else if (response->xerrno) {
4e4f7fd9
AR
286 debugs(79, DBG_IMPORTANT, "ERROR: disker " << diskId <<
287 " error writing " << writeRequest->len << " bytes at " <<
288 writeRequest->offset << ": " << xstrerr(response->xerrno) <<
289 "; this worker will stop using " << dbName);
9a51593d 290 ioError = error_ = true;
9199139f 291 } else if (response->len != writeRequest->len) {
4e4f7fd9
AR
292 debugs(79, DBG_IMPORTANT, "ERROR: disker " << diskId << " wrote " <<
293 response->len << " instead of " << writeRequest->len <<
294 " bytes (offset " << writeRequest->offset << "); " <<
295 "this worker will stop using " << dbName);
254912f3
AR
296 error_ = true;
297 }
298
299 if (writeRequest->free_func)
300 (writeRequest->free_func)(const_cast<char*>(writeRequest->buf)); // broken API?
301
caca86d7 302 if (!ioError) {
254912f3 303 debugs(79,5, HERE << "wrote " << writeRequest->len << " to disker" <<
9199139f
AR
304 diskId << " at " << writeRequest->offset);
305 }
254912f3 306
caca86d7 307 const ssize_t rlen = ioError ? 0 : (ssize_t)writeRequest->len;
9199139f 308 const int errflag = ioError ? DISK_ERROR :DISK_OK;
254912f3
AR
309 ioRequestor->writeCompleted(errflag, rlen, writeRequest);
310}
311
312bool
313IpcIoFile::ioInProgress() const
314{
9a51593d 315 return !olderRequests->empty() || !newerRequests->empty();
254912f3
AR
316}
317
9a51593d 318/// track a new pending request
254912f3 319void
28bd45ba 320IpcIoFile::trackPendingRequest(const unsigned int id, IpcIoPendingRequest *const pending)
254912f3 321{
28bd45ba
AR
322 const std::pair<RequestMap::iterator,bool> result =
323 newerRequests->insert(std::make_pair(id, pending));
324 Must(result.second); // failures means that id was not unique
9a51593d
DK
325 if (!timeoutCheckScheduled)
326 scheduleTimeoutCheck();
327}
254912f3 328
9a51593d
DK
329/// push an I/O request to disker
330void
7a907247 331IpcIoFile::push(IpcIoPendingRequest *const pending)
9a51593d 332{
fa61cefe 333 // prevent queue overflows: check for responses to earlier requests
28bd45ba 334 // warning: this call may result in indirect push() recursion
f5591061 335 HandleResponses("before push");
fa61cefe 336
a1c98830 337 debugs(47, 7, HERE);
9a51593d 338 Must(diskId >= 0);
7a907247
DK
339 Must(pending);
340 Must(pending->readRequest || pending->writeRequest);
9a51593d
DK
341
342 IpcIoMsg ipcIo;
8ed94021 343 try {
28bd45ba
AR
344 if (++lastRequestId == 0) // don't use zero value as requestId
345 ++lastRequestId;
8ed94021 346 ipcIo.requestId = lastRequestId;
0a11e039 347 ipcIo.start = current_time;
8ed94021
DK
348 if (pending->readRequest) {
349 ipcIo.command = IpcIo::cmdRead;
350 ipcIo.offset = pending->readRequest->offset;
351 ipcIo.len = pending->readRequest->len;
352 } else { // pending->writeRequest
353 Must(pending->writeRequest->len <= Ipc::Mem::PageSize());
551f8a18 354 if (!Ipc::Mem::GetPage(Ipc::Mem::PageId::ioPage, ipcIo.page)) {
8ed94021 355 ipcIo.len = 0;
551f8a18 356 throw TexcHere("run out of shared memory pages for IPC I/O");
8ed94021
DK
357 }
358 ipcIo.command = IpcIo::cmdWrite;
359 ipcIo.offset = pending->writeRequest->offset;
360 ipcIo.len = pending->writeRequest->len;
361 char *const buf = Ipc::Mem::PagePointer(ipcIo.page);
362 memcpy(buf, pending->writeRequest->buf, ipcIo.len); // optimize away
363 }
254912f3 364
f5591061 365 debugs(47, 7, HERE << "pushing " << SipcIo(KidIdentifier, ipcIo, diskId));
fa61cefe 366
f5591061 367 if (queue->push(diskId, ipcIo))
fa61cefe 368 Notify(diskId); // must notify disker
28bd45ba 369 trackPendingRequest(ipcIo.requestId, pending);
f5591061 370 } catch (const Queue::Full &) {
82ed74dc
AR
371 debugs(47, DBG_IMPORTANT, "ERROR: worker I/O push queue for " <<
372 dbName << " overflow: " <<
fa61cefe
AR
373 SipcIo(KidIdentifier, ipcIo, diskId)); // TODO: report queue len
374 // TODO: grow queue size
9199139f 375
0ef0509e 376 pending->completeIo(NULL);
8ed94021
DK
377 delete pending;
378 } catch (const TextException &e) {
82ed74dc 379 debugs(47, DBG_IMPORTANT, "ERROR: " << dbName << " exception: " << e.what());
0ef0509e 380 pending->completeIo(NULL);
7a907247 381 delete pending;
9a51593d 382 }
254912f3
AR
383}
384
0a11e039
AR
385/// whether we think there is enough time to complete the I/O
386bool
9199139f
AR
387IpcIoFile::canWait() const
388{
43ebbac3 389 if (!config.ioTimeout)
0a11e039
AR
390 return true; // no timeout specified
391
392 IpcIoMsg oldestIo;
5aac671b 393 if (!queue->findOldest(diskId, oldestIo) || oldestIo.start.tv_sec <= 0)
0a11e039
AR
394 return true; // we cannot estimate expected wait time; assume it is OK
395
55939a01
AR
396 const int oldestWait = tvSubMsec(oldestIo.start, current_time);
397
398 int rateWait = -1; // time in millisecons
399 const Ipc::QueueReader::Rate::Value ioRate = queue->rateLimit(diskId);
400 if (ioRate > 0) {
401 // if there are N requests pending, the new one will wait at
402 // least N/max-swap-rate seconds
75017bc9 403 rateWait = static_cast<int>(1e3 * queue->outSize(diskId) / ioRate);
55939a01
AR
404 // adjust N/max-swap-rate value based on the queue "balance"
405 // member, in case we have been borrowing time against future
406 // I/O already
407 rateWait += queue->balance(diskId);
408 }
409
410 const int expectedWait = max(oldestWait, rateWait);
0a11e039 411 if (expectedWait < 0 ||
43ebbac3 412 static_cast<time_msec_t>(expectedWait) < config.ioTimeout)
0a11e039
AR
413 return true; // expected wait time is acceptible
414
c792f7fc
AR
415 debugs(47,2, HERE << "cannot wait: " << expectedWait <<
416 " oldest: " << SipcIo(KidIdentifier, oldestIo, diskId));
0a11e039
AR
417 return false; // do not want to wait that long
418}
419
9a51593d 420/// called when coordinator responds to worker open request
254912f3 421void
9a51593d 422IpcIoFile::HandleOpenResponse(const Ipc::StrandSearchResponse &response)
254912f3 423{
9a51593d 424 debugs(47, 7, HERE << "coordinator response to open request");
b2aa0934 425 for (IpcIoFileList::iterator i = WaitingForOpen.begin();
9199139f 426 i != WaitingForOpen.end(); ++i) {
b2aa0934
DK
427 if (response.strand.tag == (*i)->dbName) {
428 (*i)->openCompleted(&response);
429 WaitingForOpen.erase(i);
430 return;
431 }
432 }
433
434 debugs(47, 4, HERE << "LATE disker response to open for " <<
435 response.strand.tag);
436 // nothing we can do about it; completeIo() has been called already
9a51593d 437}
254912f3 438
9a51593d 439void
f5591061 440IpcIoFile::HandleResponses(const char *const when)
fa61cefe
AR
441{
442 debugs(47, 4, HERE << "popping all " << when);
fa61cefe
AR
443 IpcIoMsg ipcIo;
444 // get all responses we can: since we are not pushing, this will stop
f5591061
DK
445 int diskId;
446 while (queue->pop(diskId, ipcIo)) {
447 const IpcIoFilesMap::const_iterator i = IpcIoFiles.find(diskId);
448 Must(i != IpcIoFiles.end()); // TODO: warn but continue
449 i->second->handleResponse(ipcIo);
450 }
9a51593d 451}
254912f3 452
9a51593d 453void
8ed94021 454IpcIoFile::handleResponse(IpcIoMsg &ipcIo)
9a51593d
DK
455{
456 const int requestId = ipcIo.requestId;
fa61cefe 457 debugs(47, 7, HERE << "popped disker response: " <<
9199139f 458 SipcIo(KidIdentifier, ipcIo, diskId));
fa61cefe 459
9a51593d
DK
460 Must(requestId);
461 if (IpcIoPendingRequest *const pending = dequeueRequest(requestId)) {
462 pending->completeIo(&ipcIo);
caca86d7
AR
463 delete pending; // XXX: leaking if throwing
464 } else {
9a51593d
DK
465 debugs(47, 4, HERE << "LATE disker response to " << ipcIo.command <<
466 "; ipcIo" << KidIdentifier << '.' << requestId);
caca86d7
AR
467 // nothing we can do about it; completeIo() has been called already
468 }
254912f3
AR
469}
470
254912f3 471void
9a51593d 472IpcIoFile::Notify(const int peerId)
254912f3 473{
fa61cefe 474 // TODO: Count and report the total number of notifications, pops, pushes.
a1c98830 475 debugs(47, 7, HERE << "kid" << peerId);
9a51593d
DK
476 Ipc::TypedMsgHdr msg;
477 msg.setType(Ipc::mtIpcIoNotification); // TODO: add proper message type?
478 msg.putInt(KidIdentifier);
1ee292b7 479 const String addr = Ipc::Port::MakeAddr(Ipc::strandAddrLabel, peerId);
9a51593d
DK
480 Ipc::SendMessage(addr, msg);
481}
482
483void
484IpcIoFile::HandleNotification(const Ipc::TypedMsgHdr &msg)
485{
fa61cefe
AR
486 const int from = msg.getInt();
487 debugs(47, 7, HERE << "from " << from);
f5591061
DK
488 queue->clearReaderSignal(from);
489 if (IamDiskProcess())
490 DiskerHandleRequests();
491 else
492 HandleResponses("after notification");
9a51593d
DK
493}
494
b2aa0934
DK
495/// handles open request timeout
496void
497IpcIoFile::OpenTimeout(void *const param)
498{
499 Must(param);
500 // the pointer is used for comparison only and not dereferenced
501 const IpcIoFile *const ipcIoFile =
502 reinterpret_cast<const IpcIoFile *>(param);
503 for (IpcIoFileList::iterator i = WaitingForOpen.begin();
9199139f 504 i != WaitingForOpen.end(); ++i) {
b2aa0934
DK
505 if (*i == ipcIoFile) {
506 (*i)->openCompleted(NULL);
507 WaitingForOpen.erase(i);
508 break;
509 }
510 }
511}
512
9a51593d
DK
513/// IpcIoFile::checkTimeouts wrapper
514void
515IpcIoFile::CheckTimeouts(void *const param)
516{
9a51593d 517 Must(param);
b2aa0934
DK
518 const int diskId = reinterpret_cast<uintptr_t>(param);
519 debugs(47, 7, HERE << "diskId=" << diskId);
520 const IpcIoFilesMap::const_iterator i = IpcIoFiles.find(diskId);
521 if (i != IpcIoFiles.end())
522 i->second->checkTimeouts();
9a51593d
DK
523}
524
525void
526IpcIoFile::checkTimeouts()
527{
9a51593d 528 timeoutCheckScheduled = false;
254912f3 529
0ef0509e
AR
530 // last chance to recover in case a notification message was lost, etc.
531 const RequestMap::size_type timeoutsBefore = olderRequests->size();
532 HandleResponses("before timeout");
533 const RequestMap::size_type timeoutsNow = olderRequests->size();
534
535 if (timeoutsBefore > timeoutsNow) { // some requests were rescued
536 // notification message lost or significantly delayed?
82ed74dc
AR
537 debugs(47, DBG_IMPORTANT, "WARNING: communication with " << dbName <<
538 " may be too slow or disrupted for about " <<
0ef0509e
AR
539 Timeout << "s; rescued " << (timeoutsBefore - timeoutsNow) <<
540 " out of " << timeoutsBefore << " I/Os");
541 }
542
543 if (timeoutsNow) {
544 debugs(47, DBG_IMPORTANT, "WARNING: abandoning " <<
82ed74dc 545 timeoutsNow << ' ' << dbName << " I/Os after at least " <<
0ef0509e
AR
546 Timeout << "s timeout");
547 }
548
caca86d7
AR
549 // any old request would have timed out by now
550 typedef RequestMap::const_iterator RMCI;
9a51593d
DK
551 for (RMCI i = olderRequests->begin(); i != olderRequests->end(); ++i) {
552 IpcIoPendingRequest *const pending = i->second;
254912f3 553
b2aa0934 554 const unsigned int requestId = i->first;
caca86d7 555 debugs(47, 7, HERE << "disker timeout; ipcIo" <<
b2aa0934 556 KidIdentifier << '.' << requestId);
254912f3 557
caca86d7
AR
558 pending->completeIo(NULL); // no response
559 delete pending; // XXX: leaking if throwing
9a51593d
DK
560 }
561 olderRequests->clear();
caca86d7 562
9a51593d 563 swap(olderRequests, newerRequests); // switches pointers around
0ef0509e 564 if (!olderRequests->empty() && !timeoutCheckScheduled)
9a51593d 565 scheduleTimeoutCheck();
254912f3
AR
566}
567
caca86d7 568/// prepare to check for timeouts in a little while
254912f3 569void
9a51593d 570IpcIoFile::scheduleTimeoutCheck()
254912f3 571{
b2aa0934 572 // we check all older requests at once so some may be wait for 2*Timeout
caca86d7 573 eventAdd("IpcIoFile::CheckTimeouts", &IpcIoFile::CheckTimeouts,
b2aa0934 574 reinterpret_cast<void *>(diskId), Timeout, 0, false);
9a51593d 575 timeoutCheckScheduled = true;
254912f3
AR
576}
577
578/// returns and forgets the right IpcIoFile pending request
579IpcIoPendingRequest *
9a51593d 580IpcIoFile::dequeueRequest(const unsigned int requestId)
254912f3 581{
254912f3 582 Must(requestId != 0);
caca86d7 583
9a51593d
DK
584 RequestMap *map = NULL;
585 RequestMap::iterator i = requestMap1.find(requestId);
caca86d7 586
9a51593d
DK
587 if (i != requestMap1.end())
588 map = &requestMap1;
caca86d7 589 else {
9a51593d
DK
590 i = requestMap2.find(requestId);
591 if (i != requestMap2.end())
592 map = &requestMap2;
caca86d7
AR
593 }
594
595 if (!map) // not found in both maps
596 return NULL;
597
598 IpcIoPendingRequest *pending = i->second;
599 map->erase(i);
600 return pending;
254912f3
AR
601}
602
603int
9a51593d 604IpcIoFile::getFD() const
254912f3
AR
605{
606 assert(false); // not supported; TODO: remove this method from API
607 return -1;
608}
609
9a51593d 610/* IpcIoMsg */
254912f3 611
9a51593d 612IpcIoMsg::IpcIoMsg():
f53969cc
SM
613 requestId(0),
614 offset(0),
615 len(0),
616 command(IpcIo::cmdNone),
617 xerrno(0)
254912f3 618{
0a11e039 619 start.tv_sec = 0;
e19994df 620 start.tv_usec = 0;
254912f3
AR
621}
622
caca86d7 623/* IpcIoPendingRequest */
254912f3
AR
624
625IpcIoPendingRequest::IpcIoPendingRequest(const IpcIoFile::Pointer &aFile):
f53969cc 626 file(aFile), readRequest(NULL), writeRequest(NULL)
254912f3
AR
627{
628}
629
caca86d7 630void
8ed94021 631IpcIoPendingRequest::completeIo(IpcIoMsg *const response)
caca86d7 632{
caca86d7
AR
633 if (readRequest)
634 file->readCompleted(readRequest, response);
9199139f 635 else if (writeRequest)
caca86d7 636 file->writeCompleted(writeRequest, response);
9a51593d
DK
637 else {
638 Must(!response); // only timeouts are handled here
639 file->openCompleted(NULL);
640 }
caca86d7
AR
641}
642
254912f3
AR
643/* XXX: disker code that should probably be moved elsewhere */
644
7015a149 645static SBuf DbName; ///< full db file name
254912f3
AR
646static int TheFile = -1; ///< db file descriptor
647
9a51593d
DK
648static void
649diskerRead(IpcIoMsg &ipcIo)
254912f3 650{
551f8a18 651 if (!Ipc::Mem::GetPage(Ipc::Mem::PageId::ioPage, ipcIo.page)) {
8ed94021 652 ipcIo.len = 0;
c792f7fc 653 debugs(47,2, HERE << "run out of shared memory pages for IPC I/O");
8ed94021
DK
654 return;
655 }
656
657 char *const buf = Ipc::Mem::PagePointer(ipcIo.page);
658 const ssize_t read = pread(TheFile, buf, min(ipcIo.len, Ipc::Mem::PageSize()), ipcIo.offset);
e4f1fdae 659 ++statCounter.syscalls.disk.reads;
2d338731
AR
660 fd_bytes(TheFile, read, FD_READ);
661
254912f3 662 if (read >= 0) {
9a51593d
DK
663 ipcIo.xerrno = 0;
664 const size_t len = static_cast<size_t>(read); // safe because read > 0
254912f3 665 debugs(47,8, HERE << "disker" << KidIdentifier << " read " <<
9199139f 666 (len == ipcIo.len ? "all " : "just ") << read);
9a51593d
DK
667 ipcIo.len = len;
668 } else {
669 ipcIo.xerrno = errno;
670 ipcIo.len = 0;
254912f3 671 debugs(47,5, HERE << "disker" << KidIdentifier << " read error: " <<
9199139f 672 ipcIo.xerrno);
9a51593d 673 }
254912f3
AR
674}
675
9d4e9cfb 676/// Tries to write buffer to disk (a few times if needed);
4e4f7fd9 677/// sets ipcIo results, but does no cleanup. The caller must cleanup.
9a51593d 678static void
4e4f7fd9
AR
679diskerWriteAttempts(IpcIoMsg &ipcIo)
680{
681 const char *buf = Ipc::Mem::PagePointer(ipcIo.page);
682 size_t toWrite = min(ipcIo.len, Ipc::Mem::PageSize());
683 size_t wroteSoFar = 0;
684 off_t offset = ipcIo.offset;
685 // Partial writes to disk do happen. It is unlikely that the caller can
686 // handle partial writes by doing something other than writing leftovers
687 // again, so we try to write them ourselves to minimize overheads.
688 const int attemptLimit = 10;
689 for (int attempts = 1; attempts <= attemptLimit; ++attempts) {
690 const ssize_t result = pwrite(TheFile, buf, toWrite, offset);
691 ++statCounter.syscalls.disk.writes;
692 fd_bytes(TheFile, result, FD_WRITE);
693
694 if (result < 0) {
695 ipcIo.xerrno = errno;
696 assert(ipcIo.xerrno);
82ed74dc
AR
697 debugs(47, DBG_IMPORTANT, "ERROR: " << DbName << " failure" <<
698 " writing " << toWrite << '/' << ipcIo.len <<
4e4f7fd9
AR
699 " at " << ipcIo.offset << '+' << wroteSoFar <<
700 " on " << attempts << " try: " << xstrerr(ipcIo.xerrno));
701 ipcIo.len = wroteSoFar;
702 return; // bail on error
703 }
2d338731 704
4e4f7fd9 705 const size_t wroteNow = static_cast<size_t>(result); // result >= 0
9a51593d 706 ipcIo.xerrno = 0;
4e4f7fd9
AR
707
708 debugs(47,3, "disker" << KidIdentifier << " wrote " <<
709 (wroteNow >= toWrite ? "all " : "just ") << wroteNow <<
710 " out of " << toWrite << '/' << ipcIo.len << " at " <<
711 ipcIo.offset << '+' << wroteSoFar << " on " << attempts <<
712 " try");
713
714 wroteSoFar += wroteNow;
715
716 if (wroteNow >= toWrite) {
717 ipcIo.xerrno = 0;
718 ipcIo.len = wroteSoFar;
719 return; // wrote everything there was to write
720 }
721
722 buf += wroteNow;
723 offset += wroteNow;
724 toWrite -= wroteNow;
9a51593d 725 }
8ed94021 726
82ed74dc
AR
727 debugs(47, DBG_IMPORTANT, "ERROR: " << DbName << " exhausted all " <<
728 attemptLimit << " attempts while writing " <<
4e4f7fd9
AR
729 toWrite << '/' << ipcIo.len << " at " << ipcIo.offset << '+' <<
730 wroteSoFar);
731 return; // not a fatal I/O error, unless the caller treats it as such
732}
733
734static void
735diskerWrite(IpcIoMsg &ipcIo)
736{
737 diskerWriteAttempts(ipcIo); // may fail
8ed94021 738 Ipc::Mem::PutPage(ipcIo.page);
254912f3
AR
739}
740
c792f7fc 741void
df881a0f 742IpcIoFile::DiskerHandleMoreRequests(void *source)
c792f7fc 743{
df881a0f
AR
744 debugs(47, 7, HERE << "resuming handling requests after " <<
745 static_cast<const char *>(source));
c792f7fc
AR
746 DiskerHandleMoreRequestsScheduled = false;
747 IpcIoFile::DiskerHandleRequests();
748}
749
df881a0f
AR
750bool
751IpcIoFile::WaitBeforePop()
752{
753 const Ipc::QueueReader::Rate::Value ioRate = queue->localRateLimit();
754 const double maxRate = ioRate/1e3; // req/ms
755
756 // do we need to enforce configured I/O rate?
757 if (maxRate <= 0)
758 return false;
759
760 // is there an I/O request we could potentially delay?
1e614370
DK
761 int processId;
762 IpcIoMsg ipcIo;
763 if (!queue->peek(processId, ipcIo)) {
764 // unlike pop(), peek() is not reliable and does not block reader
df881a0f
AR
765 // so we must proceed with pop() even if it is likely to fail
766 return false;
767 }
768
9a585a30 769 static timeval LastIo = current_time;
df881a0f
AR
770
771 const double ioDuration = 1.0 / maxRate; // ideal distance between two I/Os
772 // do not accumulate more than 100ms or 100 I/Os, whichever is smaller
773 const int64_t maxImbalance = min(static_cast<int64_t>(100), static_cast<int64_t>(100 * ioDuration));
774
775 const double credit = ioDuration; // what the last I/O should have cost us
776 const double debit = tvSubMsec(LastIo, current_time); // actual distance from the last I/O
777 LastIo = current_time;
778
779 Ipc::QueueReader::Balance &balance = queue->localBalance();
780 balance += static_cast<int64_t>(credit - debit);
781
782 debugs(47, 7, HERE << "rate limiting balance: " << balance << " after +" << credit << " -" << debit);
783
1e614370
DK
784 if (ipcIo.command == IpcIo::cmdWrite && balance > maxImbalance) {
785 // if the next request is (likely) write and we accumulated
786 // too much time for future slow I/Os, then shed accumulated
787 // time to keep just half of the excess
df881a0f 788 const int64_t toSpend = balance - maxImbalance/2;
69321ae9
AR
789
790 if (toSpend/1e3 > Timeout)
82ed74dc
AR
791 debugs(47, DBG_IMPORTANT, "WARNING: " << DbName << " delays " <<
792 "I/O requests for " << (toSpend/1e3) << " seconds " <<
793 "to obey " << ioRate << "/sec rate limit");
69321ae9 794
df881a0f
AR
795 debugs(47, 3, HERE << "rate limiting by " << toSpend << " ms to get" <<
796 (1e3*maxRate) << "/sec rate");
797 eventAdd("IpcIoFile::DiskerHandleMoreRequests",
798 &IpcIoFile::DiskerHandleMoreRequests,
799 const_cast<char*>("rate limiting"),
800 toSpend/1e3, 0, false);
801 DiskerHandleMoreRequestsScheduled = true;
802 return true;
e29ccb57 803 } else if (balance < -maxImbalance) {
df881a0f
AR
804 // do not owe "too much" to avoid "too large" bursts of I/O
805 balance = -maxImbalance;
806 }
807
808 return false;
809}
810
254912f3 811void
f5591061 812IpcIoFile::DiskerHandleRequests()
254912f3 813{
c792f7fc 814 // Balance our desire to maximize the number of concurrent I/O requests
fdb3059b 815 // (reordred by OS to minimize seek time) with a requirement to
c792f7fc 816 // send 1st-I/O notification messages, process Coordinator events, etc.
fdb3059b
AR
817 const int maxSpentMsec = 10; // keep small: most RAM I/Os are under 1ms
818 const timeval loopStart = current_time;
819
c792f7fc 820 int popped = 0;
fa61cefe
AR
821 int workerId = 0;
822 IpcIoMsg ipcIo;
df881a0f 823 while (!WaitBeforePop() && queue->pop(workerId, ipcIo)) {
fdb3059b
AR
824 ++popped;
825
826 // at least one I/O per call is guaranteed if the queue is not empty
fa61cefe
AR
827 DiskerHandleRequest(workerId, ipcIo);
828
fdb3059b
AR
829 getCurrentTime();
830 const double elapsedMsec = tvSubMsec(loopStart, current_time);
831 if (elapsedMsec > maxSpentMsec || elapsedMsec < 0) {
832 if (!DiskerHandleMoreRequestsScheduled) {
833 // the gap must be positive for select(2) to be given a chance
834 const double minBreakSecs = 0.001;
835 eventAdd("IpcIoFile::DiskerHandleMoreRequests",
9199139f 836 &IpcIoFile::DiskerHandleMoreRequests,
df881a0f
AR
837 const_cast<char*>("long I/O loop"),
838 minBreakSecs, 0, false);
fdb3059b
AR
839 DiskerHandleMoreRequestsScheduled = true;
840 }
841 debugs(47, 3, HERE << "pausing after " << popped << " I/Os in " <<
9199139f 842 elapsedMsec << "ms; " << (elapsedMsec/popped) << "ms per I/O");
fdb3059b
AR
843 break;
844 }
c792f7fc
AR
845 }
846
fdb3059b 847 // TODO: consider using O_DIRECT with "elevator" optimization where we pop
fa61cefe
AR
848 // requests first, then reorder the popped requests to optimize seek time,
849 // then do I/O, then take a break, and come back for the next set of I/O
850 // requests.
9a51593d 851}
254912f3 852
9a51593d
DK
853/// called when disker receives an I/O request
854void
855IpcIoFile::DiskerHandleRequest(const int workerId, IpcIoMsg &ipcIo)
856{
9a51593d 857 if (ipcIo.command != IpcIo::cmdRead && ipcIo.command != IpcIo::cmdWrite) {
82ed74dc 858 debugs(0, DBG_CRITICAL, "ERROR: " << DbName <<
9a51593d
DK
859 " should not receive " << ipcIo.command <<
860 " ipcIo" << workerId << '.' << ipcIo.requestId);
861 return;
862 }
863
864 debugs(47,5, HERE << "disker" << KidIdentifier <<
865 (ipcIo.command == IpcIo::cmdRead ? " reads " : " writes ") <<
866 ipcIo.len << " at " << ipcIo.offset <<
867 " ipcIo" << workerId << '.' << ipcIo.requestId);
868
869 if (ipcIo.command == IpcIo::cmdRead)
870 diskerRead(ipcIo);
871 else // ipcIo.command == IpcIo::cmdWrite
872 diskerWrite(ipcIo);
873
f5591061 874 debugs(47, 7, HERE << "pushing " << SipcIo(workerId, ipcIo, KidIdentifier));
fa61cefe 875
7a907247 876 try {
f5591061 877 if (queue->push(workerId, ipcIo))
5e44782e 878 Notify(workerId); // must notify worker
f5591061 879 } catch (const Queue::Full &) {
fa61cefe
AR
880 // The worker queue should not overflow because the worker should pop()
881 // before push()ing and because if disker pops N requests at a time,
882 // we should make sure the worker pop() queue length is the worker
883 // push queue length plus N+1. XXX: implement the N+1 difference.
82ed74dc
AR
884 debugs(47, DBG_IMPORTANT, "BUG: Worker I/O pop queue for " <<
885 DbName << " overflow: " <<
5e44782e 886 SipcIo(workerId, ipcIo, KidIdentifier)); // TODO: report queue len
fa61cefe
AR
887
888 // the I/O request we could not push will timeout
7a907247 889 }
254912f3
AR
890}
891
892static bool
7015a149 893DiskerOpen(const SBuf &path, int flags, mode_t mode)
254912f3
AR
894{
895 assert(TheFile < 0);
896
82ed74dc 897 DbName = path;
7015a149 898 TheFile = file_open(DbName.c_str(), flags);
254912f3
AR
899
900 if (TheFile < 0) {
901 const int xerrno = errno;
82ed74dc 902 debugs(47, DBG_CRITICAL, "ERROR: cannot open " << DbName << ": " <<
254912f3
AR
903 xstrerr(xerrno));
904 return false;
9a51593d 905 }
254912f3 906
cb4185f1 907 ++store_open_disk_fd;
7015a149 908 debugs(79,3, "rock db opened " << DbName << ": FD " << TheFile);
9a51593d 909 return true;
254912f3
AR
910}
911
912static void
7015a149 913DiskerClose(const SBuf &path)
254912f3
AR
914{
915 if (TheFile >= 0) {
916 file_close(TheFile);
917 debugs(79,3, HERE << "rock db closed " << path << ": FD " << TheFile);
918 TheFile = -1;
5e263176 919 --store_open_disk_fd;
a1c98830 920 }
7015a149 921 DbName.clear();
254912f3 922}
f5591061 923
ea2cdeb6 924/// reports our needs for shared memory pages to Ipc::Mem::Pages
21b7990f
AR
925/// and initializes shared memory segments used by IpcIoFile
926class IpcIoRr: public Ipc::Mem::RegisteredRunner
ea2cdeb6
DK
927{
928public:
929 /* RegisteredRunner API */
21b7990f
AR
930 IpcIoRr(): owner(NULL) {}
931 virtual ~IpcIoRr();
932 virtual void claimMemoryNeeds();
933
934protected:
935 /* Ipc::Mem::RegisteredRunner API */
936 virtual void create();
937
938private:
939 Ipc::FewToFewBiQueue::Owner *owner;
ea2cdeb6
DK
940};
941
21b7990f 942RunnerRegistrationEntry(IpcIoRr);
ea2cdeb6 943
ea2cdeb6 944void
21b7990f 945IpcIoRr::claimMemoryNeeds()
ea2cdeb6
DK
946{
947 const int itemsCount = Ipc::FewToFewBiQueue::MaxItemsCount(
c11211d9 948 ::Config.workers, ::Config.cacheSwap.n_strands, QueueCapacity);
ea2cdeb6
DK
949 // the maximum number of shared I/O pages is approximately the
950 // number of queue slots, we add a fudge factor to that to account
951 // for corner cases where I/O pages are created before queue
952 // limits are checked or destroyed long after the I/O is dequeued
29a9ff4e
DK
953 Ipc::Mem::NotePageNeed(Ipc::Mem::PageId::ioPage,
954 static_cast<int>(itemsCount * 1.1));
ea2cdeb6
DK
955}
956
21b7990f
AR
957void
958IpcIoRr::create()
f5591061 959{
e9f68413 960 if (Config.cacheSwap.n_strands <= 0)
f5591061
DK
961 return;
962
4404f1c5 963 Must(!owner);
4404f1c5 964 owner = Ipc::FewToFewBiQueue::Init(ShmLabel, Config.workers, 1,
3b581957 965 Config.cacheSwap.n_strands,
4404f1c5 966 1 + Config.workers, sizeof(IpcIoMsg),
ea2cdeb6 967 QueueCapacity);
f5591061
DK
968}
969
970IpcIoRr::~IpcIoRr()
971{
972 delete owner;
973}
f53969cc 974