]> git.ipfire.org Git - thirdparty/squid.git/blame - src/store.cc
Convert Vary handling to SBuf
[thirdparty/squid.git] / src / store.cc
CommitLineData
30a4f2a8 1/*
ef57eb7b 2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
e25c139f 3 *
bbc27441
AJ
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.
c943f331 7 */
090089c4 8
bbc27441
AJ
9/* DEBUG: section 20 Storage Manager */
10
582c2af2 11#include "squid.h"
b814e8d4 12#include "CacheDigest.h"
ec20038e
AJ
13#include "CacheManager.h"
14#include "comm/Connection.h"
7e66d5e2 15#include "comm/Read.h"
81a94152 16#include "ETag.h"
a553a5a3 17#include "event.h"
04f55905 18#include "fde.h"
af69c635 19#include "globals.h"
582c2af2 20#include "http.h"
528b2c61 21#include "HttpReply.h"
22#include "HttpRequest.h"
528b2c61 23#include "mem_node.h"
582c2af2
FC
24#include "MemObject.h"
25#include "mgr/Registration.h"
26#include "mgr/StoreIoAction.h"
27#include "profiler/Profiler.h"
e452f48d 28#include "repl_modules.h"
f206b652 29#include "RequestFlags.h"
4d5904f7 30#include "SquidConfig.h"
582c2af2 31#include "SquidTime.h"
e4f1fdae 32#include "StatCounters.h"
582c2af2 33#include "stmem.h"
602d9612 34#include "Store.h"
b3f7fd88
AR
35#include "store/Controller.h"
36#include "store/Disk.h"
37#include "store/Disks.h"
35a28a37 38#include "store_digest.h"
fb548aaf 39#include "store_key_md5.h"
e87137f1 40#include "store_key_md5.h"
10818c0a 41#include "store_log.h"
687f5275 42#include "store_rebuild.h"
e87137f1
FC
43#include "StoreClient.h"
44#include "StoreIOState.h"
45#include "StoreMeta.h"
46#include "StrList.h"
582c2af2 47#include "swap_log_op.h"
5bed43d6 48#include "tools.h"
9a0a18de 49#if USE_DELAY_POOLS
b67e2c8c 50#include "DelayPools.h"
51#endif
090089c4 52
ed6e9fb9
AJ
53/** StoreEntry uses explicit new/delete operators, which set pool chunk size to 2MB
54 * XXX: convert to MEMPROXY_CLASS() API
55 */
56#include "mem/Pool.h"
57
074d6a40 58#include <climits>
cfb88efb 59#include <stack>
06e91875 60
090089c4 61#define REBUILD_TIMESTAMP_DELTA_MAX 2
227fbb74 62
c21ad0f5 63#define STORE_IN_MEM_BUCKETS (229)
090089c4 64
4b981814
AJ
65/** \todo Convert these string constants to enum string-arrays generated */
66
26ac0430
AJ
67const char *memStatusStr[] = {
68 "NOT_IN_MEMORY",
69 "IN_MEMORY"
70};
71
72const char *pingStatusStr[] = {
73 "PING_NONE",
74 "PING_WAITING",
75 "PING_DONE"
76};
77
78const char *storeStatusStr[] = {
79 "STORE_OK",
80 "STORE_PENDING"
81};
82
83const char *swapStatusStr[] = {
84 "SWAPOUT_NONE",
85 "SWAPOUT_WRITING",
86 "SWAPOUT_DONE"
87};
9dfb6c1c 88
25b6a907 89/*
90 * This defines an repl type
91 */
92
93typedef struct _storerepl_entry storerepl_entry_t;
94
26ac0430 95struct _storerepl_entry {
25b6a907 96 const char *typestr;
97 REMOVALPOLICYCREATE *create;
98};
99
100static storerepl_entry_t *storerepl_list = NULL;
101
e3ef2b09 102/*
103 * local function prototypes
104 */
007b8be4 105static int getKeyCounter(void);
8423ff74 106static OBJH storeCheckCachableStats;
e42d5181 107static EVH storeLateRelease;
a21fbb54 108
e3ef2b09 109/*
110 * local variables
111 */
cfb88efb 112static std::stack<StoreEntry*> LateReleaseStack;
04eb0689 113MemAllocator *StoreEntry::pool = NULL;
e6ccf245 114
c8f4eac4 115void
116Store::Stats(StoreEntry * output)
117{
ced8def3 118 assert(output);
c8f4eac4 119 Root().stat(*output);
120}
121
0b934349
AJ
122// XXX: new/delete operators need to be replaced with MEMPROXY_CLASS
123// definitions but doing so exposes bug 4370, and maybe 4354 and 4355
124void *
125StoreEntry::operator new (size_t bytecount)
126{
127 assert(bytecount == sizeof (StoreEntry));
128
129 if (!pool) {
130 pool = memPoolCreate ("StoreEntry", bytecount);
131 }
132
133 return pool->alloc();
134}
135
136void
137StoreEntry::operator delete (void *address)
138{
139 pool->freeOne(address);
140}
141
5ed72359 142void
143StoreEntry::makePublic()
144{
145 /* This object can be cached for a long time */
146
6919be24 147 if (!EBIT_TEST(flags, RELEASE_REQUEST))
d88e3c49 148 setPublicKey();
5ed72359 149}
150
151void
152StoreEntry::makePrivate()
153{
154 /* This object should never be cached at all */
d88e3c49 155 expireNow();
156 releaseRequest(); /* delete object when not used */
5ed72359 157}
158
159void
160StoreEntry::cacheNegatively()
161{
162 /* This object may be negatively cached */
d88e3c49 163 negativeCache();
6919be24 164 makePublic();
5ed72359 165}
166
e6ccf245 167size_t
3b13a8fd 168StoreEntry::inUseCount()
e6ccf245 169{
170 if (!pool)
62e76326 171 return 0;
9f9e06f3 172 return pool->getInUseCount();
e6ccf245 173}
174
332dafa2 175const char *
3b13a8fd 176StoreEntry::getMD5Text() const
332dafa2 177{
178 return storeKeyText((const cache_key *)key);
179}
180
a46d2c0e 181#include "comm.h"
182
183void
184StoreEntry::DeferReader(void *theContext, CommRead const &aRead)
e6ccf245 185{
a46d2c0e 186 StoreEntry *anEntry = (StoreEntry *)theContext;
3e4bebf8 187 anEntry->delayAwareRead(aRead.conn,
a46d2c0e 188 aRead.buf,
189 aRead.len,
65517dc8 190 aRead.callback);
e6ccf245 191}
66cedb85 192
a46d2c0e 193void
3e4bebf8 194StoreEntry::delayAwareRead(const Comm::ConnectionPointer &conn, char *buf, int len, AsyncCall::Pointer callback)
a46d2c0e 195{
196 size_t amountToRead = bytesWanted(Range<size_t>(0, len));
197 /* sketch: readdeferer* = getdeferer.
65517dc8 198 * ->deferRead (fd, buf, len, callback, DelayAwareRead, this)
a46d2c0e 199 */
200
201 if (amountToRead == 0) {
202 assert (mem_obj);
203 /* read ahead limit */
204 /* Perhaps these two calls should both live in MemObject */
9a0a18de 205#if USE_DELAY_POOLS
a46d2c0e 206 if (!mem_obj->readAheadPolicyCanRead()) {
a5f42284 207#endif
3e4bebf8 208 mem_obj->delayRead(DeferredRead(DeferReader, this, CommRead(conn, buf, len, callback)));
a46d2c0e 209 return;
9a0a18de 210#if USE_DELAY_POOLS
a46d2c0e 211 }
212
213 /* delay id limit */
3e4bebf8 214 mem_obj->mostBytesAllowed().delayRead(DeferredRead(DeferReader, this, CommRead(conn, buf, len, callback)));
a46d2c0e 215 return;
a5f42284 216
217#endif
218
a46d2c0e 219 }
220
109cf61c 221 if (fd_table[conn->fd].closing()) {
f5f9e44c
AR
222 // Readers must have closing callbacks if they want to be notified. No
223 // readers appeared to care around 2009/12/14 as they skipped reading
224 // for other reasons. Closing may already be true at the delyaAwareRead
225 // call time or may happen while we wait after delayRead() above.
109cf61c 226 debugs(20, 3, HERE << "wont read from closing " << conn << " for " <<
f5f9e44c
AR
227 callback);
228 return; // the read callback will never be called
229 }
230
3e4bebf8 231 comm_read(conn, buf, amountToRead, callback);
a46d2c0e 232}
233
234size_t
384a7590 235StoreEntry::bytesWanted (Range<size_t> const aRange, bool ignoreDelayPools) const
528b2c61 236{
528b2c61 237 if (mem_obj == NULL)
4dc2b072 238 return aRange.end;
62e76326 239
bc87dc25 240#if URL_CHECKSUM_DEBUG
62e76326 241
528b2c61 242 mem_obj->checkUrlChecksum();
62e76326 243
528b2c61 244#endif
62e76326 245
a46d2c0e 246 if (!mem_obj->readAheadPolicyCanRead())
247 return 0;
62e76326 248
384a7590 249 return mem_obj->mostBytesWanted(aRange.end, ignoreDelayPools);
a46d2c0e 250}
62e76326 251
a46d2c0e 252bool
ced8def3 253StoreEntry::checkDeferRead(int) const
a46d2c0e 254{
255 return (bytesWanted(Range<size_t>(0,INT_MAX)) == 0);
256}
62e76326 257
a46d2c0e 258void
ced8def3 259StoreEntry::setNoDelay(bool const newValue)
a46d2c0e 260{
261 if (mem_obj)
262 mem_obj->setNoDelay(newValue);
528b2c61 263}
bc87dc25 264
f25d697f
AR
265// XXX: Type names mislead. STORE_DISK_CLIENT actually means that we should
266// open swapin file, aggressively trim memory, and ignore read-ahead gap.
267// It does not mean we will read from disk exclusively (or at all!).
268// XXX: May create STORE_DISK_CLIENT with no disk caching configured.
269// XXX: Collapsed clients cannot predict their type.
528b2c61 270store_client_t
271StoreEntry::storeClientType() const
227fbb74 272{
7d31d5fa 273 /* The needed offset isn't in memory
274 * XXX TODO: this is wrong for range requests
275 * as the needed offset may *not* be 0, AND
276 * offset 0 in the memory object is the HTTP headers.
277 */
278
9487bae9
AR
279 assert(mem_obj);
280
528b2c61 281 if (mem_obj->inmem_lo)
62e76326 282 return STORE_DISK_CLIENT;
283
528b2c61 284 if (EBIT_TEST(flags, ENTRY_ABORTED)) {
62e76326 285 /* I don't think we should be adding clients to aborted entries */
e0236918 286 debugs(20, DBG_IMPORTANT, "storeClientType: adding to ENTRY_ABORTED entry");
62e76326 287 return STORE_MEM_CLIENT;
528b2c61 288 }
62e76326 289
528b2c61 290 if (store_status == STORE_OK) {
7d31d5fa 291 /* the object has completed. */
292
344a9006 293 if (mem_obj->inmem_lo == 0 && !isEmpty()) {
47ce0a58 294 if (swap_status == SWAPOUT_DONE) {
e2851fe7 295 debugs(20,7, HERE << mem_obj << " lo: " << mem_obj->inmem_lo << " hi: " << mem_obj->endOffset() << " size: " << mem_obj->object_sz);
e1381638 296 if (mem_obj->endOffset() == mem_obj->object_sz) {
f25d697f 297 /* hot object fully swapped in (XXX: or swapped out?) */
e1381638
AJ
298 return STORE_MEM_CLIENT;
299 }
47ce0a58 300 } else {
e1381638
AJ
301 /* Memory-only, or currently being swapped out */
302 return STORE_MEM_CLIENT;
47ce0a58
HN
303 }
304 }
305 return STORE_DISK_CLIENT;
528b2c61 306 }
62e76326 307
528b2c61 308 /* here and past, entry is STORE_PENDING */
309 /*
310 * If this is the first client, let it be the mem client
311 */
312 if (mem_obj->nclients == 1)
62e76326 313 return STORE_MEM_CLIENT;
314
528b2c61 315 /*
316 * If there is no disk file to open yet, we must make this a
317 * mem client. If we can't open the swapin file before writing
318 * to the client, there is no guarantee that we will be able
319 * to open it later when we really need it.
320 */
321 if (swap_status == SWAPOUT_NONE)
62e76326 322 return STORE_MEM_CLIENT;
323
528b2c61 324 /*
325 * otherwise, make subsequent clients read from disk so they
326 * can not delay the first, and vice-versa.
327 */
328 return STORE_DISK_CLIENT;
227fbb74 329}
330
8ebae981 331StoreEntry::StoreEntry() :
f53969cc
SM
332 mem_obj(NULL),
333 timestamp(-1),
334 lastref(-1),
335 expires(-1),
336 lastmod(-1),
337 swap_file_sz(0),
338 refcount(0),
339 flags(0),
340 swap_filen(-1),
341 swap_dirn(-1),
342 mem_status(NOT_IN_MEMORY),
343 ping_status(PING_NONE),
344 store_status(STORE_PENDING),
345 swap_status(SWAPOUT_NONE),
346 lock_count(0)
090089c4 347{
539283df 348 debugs(20, 5, "StoreEntry constructed, this=" << this);
c8f4eac4 349}
62e76326 350
6d8d05b5
DK
351StoreEntry::~StoreEntry()
352{
539283df 353 debugs(20, 5, "StoreEntry destructed, this=" << this);
6d8d05b5
DK
354}
355
0ad2b63b
CT
356#if USE_ADAPTATION
357void
358StoreEntry::deferProducer(const AsyncCall::Pointer &producer)
359{
360 if (!deferredProducer)
361 deferredProducer = producer;
362 else
e83cdc25 363 debugs(20, 5, HERE << "Deferred producer call is allready set to: " <<
0ad2b63b
CT
364 *deferredProducer << ", requested call: " << *producer);
365}
366
367void
368StoreEntry::kickProducer()
369{
e83cdc25 370 if (deferredProducer != NULL) {
0ad2b63b
CT
371 ScheduleCallHere(deferredProducer);
372 deferredProducer = NULL;
373 }
374}
375#endif
376
3900307b 377void
378StoreEntry::destroyMemObject()
090089c4 379{
3900307b 380 debugs(20, 3, HERE << "destroyMemObject " << mem_obj);
29c56e41
AR
381
382 if (MemObject *mem = mem_obj) {
383 // Store::Root() is FATALly missing during shutdown
384 if (mem->xitTable.index >= 0 && !shutting_down)
385 Store::Root().transientsDisconnect(*mem);
386 if (mem->memCache.index >= 0 && !shutting_down)
387 Store::Root().memoryDisconnect(*this);
388
389 setMemStatus(NOT_IN_MEMORY);
390 mem_obj = NULL;
391 delete mem;
392 }
090089c4 393}
394
c8f4eac4 395void
528b2c61 396destroyStoreEntry(void *data)
090089c4 397{
59dbbc5c 398 debugs(20, 3, HERE << "destroyStoreEntry: destroying " << data);
c8f4eac4 399 StoreEntry *e = static_cast<StoreEntry *>(static_cast<hash_link *>(data));
9e975e4e 400 assert(e != NULL);
62e76326 401
e6ccf245 402 if (e == NullStoreEntry::getInstance())
62e76326 403 return;
404
fa6d2c65 405 // Store::Root() is FATALly missing during shutdown
2745fea5
AR
406 if (e->swap_filen >= 0 && !shutting_down)
407 e->disk().disconnect(*e);
fa6d2c65 408
3900307b 409 e->destroyMemObject();
62e76326 410
3900307b 411 e->hashDelete();
62e76326 412
332dafa2 413 assert(e->key == NULL);
62e76326 414
e6ccf245 415 delete e;
227fbb74 416}
090089c4 417
090089c4 418/* ----- INTERFACE BETWEEN STORAGE MANAGER AND HASH TABLE FUNCTIONS --------- */
419
f09f5b26 420void
3900307b 421StoreEntry::hashInsert(const cache_key * someKey)
090089c4 422{
4475555f 423 debugs(20, 3, "StoreEntry::hashInsert: Inserting Entry " << *this << " key '" << storeKeyText(someKey) << "'");
3900307b 424 key = storeKeyDup(someKey);
425 hash_join(store_table, this);
090089c4 426}
427
3900307b 428void
429StoreEntry::hashDelete()
090089c4 430{
cb868059
AR
431 if (key) { // some test cases do not create keys and do not hashInsert()
432 hash_remove_link(store_table, this);
433 storeKeyFree((const cache_key *)key);
434 key = NULL;
435 }
090089c4 436}
437
090089c4 438/* -------------------------------------------------------------------------- */
439
090089c4 440/* get rid of memory copy of the object */
d88e3c49 441void
442StoreEntry::purgeMem()
090089c4 443{
d88e3c49 444 if (mem_obj == NULL)
62e76326 445 return;
446
bf8fe701 447 debugs(20, 3, "StoreEntry::purgeMem: Freeing memory-copy of " << getMD5Text());
62e76326 448
ce49546e 449 Store::Root().memoryUnlink(*this);
62e76326 450
d88e3c49 451 if (swap_status != SWAPOUT_DONE)
452 release();
090089c4 453}
454
6a566b9c 455void
18994992 456StoreEntry::lock(const char *context)
6a566b9c 457{
5db6bf73 458 ++lock_count;
18994992
AR
459 debugs(20, 3, context << " locked key " << getMD5Text() << ' ' << *this);
460}
461
462void
9d4e9cfb
AR
463StoreEntry::touch()
464{
c21ad0f5 465 lastref = squid_curtime;
090089c4 466}
467
43ae1d95 468void
469StoreEntry::setReleaseFlag()
470{
471 if (EBIT_TEST(flags, RELEASE_REQUEST))
472 return;
473
bf8fe701 474 debugs(20, 3, "StoreEntry::setReleaseFlag: '" << getMD5Text() << "'");
43ae1d95 475
476 EBIT_SET(flags, RELEASE_REQUEST);
1bfe9ade
AR
477
478 Store::Root().markForUnlink(*this);
43ae1d95 479}
480
b8d8561b 481void
d88e3c49 482StoreEntry::releaseRequest()
2285407f 483{
d88e3c49 484 if (EBIT_TEST(flags, RELEASE_REQUEST))
62e76326 485 return;
486
6919be24 487 setReleaseFlag(); // makes validToSend() false, preventing future hits
62e76326 488
d88e3c49 489 setPrivateKey();
2285407f 490}
491
b8d8561b 492int
18994992 493StoreEntry::unlock(const char *context)
090089c4 494{
18994992
AR
495 debugs(20, 3, (context ? context : "somebody") <<
496 " unlocking key " << getMD5Text() << ' ' << *this);
c47b98ac 497 assert(lock_count > 0);
5e263176 498 --lock_count;
62e76326 499
c21ad0f5 500 if (lock_count)
501 return (int) lock_count;
62e76326 502
c21ad0f5 503 if (store_status == STORE_PENDING)
504 setReleaseFlag();
62e76326 505
c21ad0f5 506 assert(storePendingNClients(this) == 0);
62e76326 507
9199139f 508 if (EBIT_TEST(flags, RELEASE_REQUEST)) {
5f33b71d 509 this->release();
984f9874
AR
510 return 0;
511 }
512
9487bae9 513 if (EBIT_TEST(flags, KEY_PRIVATE))
e0236918 514 debugs(20, DBG_IMPORTANT, "WARNING: " << __FILE__ << ":" << __LINE__ << ": found KEY_PRIVATE");
62e76326 515
9487bae9 516 Store::Root().handleIdleEntry(*this); // may delete us
6c895381 517 return 0;
090089c4 518}
519
e6ccf245 520void
60745f24 521StoreEntry::getPublicByRequestMethod (StoreClient *aClient, HttpRequest * request, const HttpRequestMethod& method)
e6ccf245 522{
523 assert (aClient);
3b13a8fd 524 StoreEntry *result = storeGetPublicByRequestMethod( request, method);
62e76326 525
e6ccf245 526 if (!result)
62e76326 527 aClient->created (NullStoreEntry::getInstance());
e6ccf245 528 else
62e76326 529 aClient->created (result);
e6ccf245 530}
531
532void
190154cf 533StoreEntry::getPublicByRequest (StoreClient *aClient, HttpRequest * request)
e6ccf245 534{
535 assert (aClient);
3b13a8fd 536 StoreEntry *result = storeGetPublicByRequest (request);
62e76326 537
e6ccf245 538 if (!result)
62e76326 539 result = NullStoreEntry::getInstance();
540
e6ccf245 541 aClient->created (result);
542}
543
544void
60745f24 545StoreEntry::getPublic (StoreClient *aClient, const char *uri, const HttpRequestMethod& method)
e6ccf245 546{
547 assert (aClient);
3b13a8fd 548 StoreEntry *result = storeGetPublic (uri, method);
62e76326 549
e6ccf245 550 if (!result)
62e76326 551 result = NullStoreEntry::getInstance();
552
e6ccf245 553 aClient->created (result);
554}
555
08e5d64f 556StoreEntry *
60745f24 557storeGetPublic(const char *uri, const HttpRequestMethod& method)
08e5d64f 558{
c8f4eac4 559 return Store::Root().get(storeKeyPublic(uri, method));
08e5d64f 560}
561
f66a9ef4 562StoreEntry *
60745f24 563storeGetPublicByRequestMethod(HttpRequest * req, const HttpRequestMethod& method)
f66a9ef4 564{
c8f4eac4 565 return Store::Root().get(storeKeyPublicByRequestMethod(req, method));
f66a9ef4 566}
567
568StoreEntry *
190154cf 569storeGetPublicByRequest(HttpRequest * req)
f66a9ef4 570{
571 StoreEntry *e = storeGetPublicByRequestMethod(req, req->method);
62e76326 572
c2a7cefd 573 if (e == NULL && req->method == Http::METHOD_HEAD)
62e76326 574 /* We can generate a HEAD reply from a cached GET object */
c2a7cefd 575 e = storeGetPublicByRequestMethod(req, Http::METHOD_GET);
62e76326 576
f66a9ef4 577 return e;
578}
579
007b8be4 580static int
581getKeyCounter(void)
04e8dbaa 582{
007b8be4 583 static int key_counter = 0;
62e76326 584
007b8be4 585 if (++key_counter < 0)
62e76326 586 key_counter = 1;
587
007b8be4 588 return key_counter;
04e8dbaa 589}
590
c8f4eac4 591/* RBC 20050104 AFAICT this should become simpler:
592 * rather than reinserting with a special key it should be marked
593 * as 'released' and then cleaned up when refcounting indicates.
594 * the StoreHashIndex could well implement its 'released' in the
595 * current manner.
596 * Also, clean log writing should skip over ia,t
597 * Otherwise, we need a 'remove from the index but not the store
598 * concept'.
599 */
6c57e268 600void
d88e3c49 601StoreEntry::setPrivateKey()
227fbb74 602{
9fb13bb6 603 const cache_key *newkey;
62e76326 604
d88e3c49 605 if (key && EBIT_TEST(flags, KEY_PRIVATE))
c21ad0f5 606 return; /* is already private */
62e76326 607
d88e3c49 608 if (key) {
6919be24
AR
609 setReleaseFlag(); // will markForUnlink(); all caches/workers will know
610
611 // TODO: move into SwapDir::markForUnlink() already called by Root()
d88e3c49 612 if (swap_filen > -1)
613 storeDirSwapLog(this, SWAP_LOG_DEL);
62e76326 614
3900307b 615 hashDelete();
b109de6b 616 }
62e76326 617
c877c0bc 618 if (mem_obj && mem_obj->hasUris()) {
d88e3c49 619 mem_obj->id = getKeyCounter();
c877c0bc 620 newkey = storeKeyPrivate(mem_obj->storeId(), mem_obj->method, mem_obj->id);
9fb13bb6 621 } else {
c2a7cefd 622 newkey = storeKeyPrivate("JUNK", Http::METHOD_NONE, getKeyCounter());
9fb13bb6 623 }
62e76326 624
9fb13bb6 625 assert(hash_lookup(store_table, newkey) == NULL);
d88e3c49 626 EBIT_SET(flags, KEY_PRIVATE);
3900307b 627 hashInsert(newkey);
227fbb74 628}
629
b8d8561b 630void
d88e3c49 631StoreEntry::setPublicKey()
227fbb74 632{
9fb13bb6 633 const cache_key *newkey;
62e76326 634
d88e3c49 635 if (key && !EBIT_TEST(flags, KEY_PRIVATE))
c21ad0f5 636 return; /* is already public */
62e76326 637
d88e3c49 638 assert(mem_obj);
62e76326 639
f3e570e9 640 /*
641 * We can't make RELEASE_REQUEST objects public. Depending on
642 * when RELEASE_REQUEST gets set, we might not be swapping out
643 * the object. If we're not swapping out, then subsequent
644 * store clients won't be able to access object data which has
645 * been freed from memory.
d87ebd78 646 *
6919be24 647 * If RELEASE_REQUEST is set, setPublicKey() should not be called.
f3e570e9 648 */
6a566b9c 649#if MORE_DEBUG_OUTPUT
62e76326 650
d88e3c49 651 if (EBIT_TEST(flags, RELEASE_REQUEST))
e0236918 652 debugs(20, DBG_IMPORTANT, "assertion failed: RELEASE key " << key << ", url " << mem_obj->url);
62e76326 653
2b906e48 654#endif
62e76326 655
d88e3c49 656 assert(!EBIT_TEST(flags, RELEASE_REQUEST));
62e76326 657
d88e3c49 658 if (mem_obj->request) {
659 HttpRequest *request = mem_obj->request;
62e76326 660
90ab8f20 661 if (mem_obj->vary_headers.isEmpty()) {
62e76326 662 /* First handle the case where the object no longer varies */
90ab8f20 663 request->vary_headers.clear();
62e76326 664 } else {
90ab8f20 665 if (!request->vary_headers.isEmpty() && request->vary_headers.cmp(mem_obj->vary_headers) != 0) {
62e76326 666 /* Oops.. the variance has changed. Kill the base object
667 * to record the new variance key
668 */
90ab8f20 669 request->vary_headers.clear(); /* free old "bad" variance key */
c877c0bc 670 if (StoreEntry *pe = storeGetPublic(mem_obj->storeId(), mem_obj->method))
5f33b71d 671 pe->release();
62e76326 672 }
673
674 /* Make sure the request knows the variance status */
90ab8f20
AJ
675 if (request->vary_headers.isEmpty())
676 request->vary_headers = httpMakeVaryMark(request, mem_obj->getReply());
62e76326 677 }
678
9487bae9
AR
679 // TODO: storeGetPublic() calls below may create unlocked entries.
680 // We should add/use storeHas() API or lock/unlock those entries.
90ab8f20 681 if (!mem_obj->vary_headers.isEmpty() && !storeGetPublic(mem_obj->storeId(), mem_obj->method)) {
62e76326 682 /* Create "vary" base object */
30abd221 683 String vary;
c877c0bc 684 StoreEntry *pe = storeCreateEntry(mem_obj->storeId(), mem_obj->logUri(), request->flags, request->method);
62e76326 685 /* We are allowed to do this typecast */
eab8dcfa 686 HttpReply *rep = new HttpReply;
955394ce 687 rep->setHeaders(Http::scOkay, "Internal marker object", "x-squid-internal/vary", -1, -1, squid_curtime + 100000);
789217a2 688 vary = mem_obj->getReply()->header.getList(Http::HdrType::VARY);
62e76326 689
30abd221 690 if (vary.size()) {
62e76326 691 /* Again, we own this structure layout */
789217a2 692 rep->header.putStr(Http::HdrType::VARY, vary.termedBuf());
30abd221 693 vary.clean();
62e76326 694 }
695
f66a9ef4 696#if X_ACCELERATOR_VARY
789217a2 697 vary = mem_obj->getReply()->header.getList(Http::HdrType::HDR_X_ACCELERATOR_VARY);
62e76326 698
b38b26cb 699 if (vary.size() > 0) {
62e76326 700 /* Again, we own this structure layout */
789217a2 701 rep->header.putStr(Http::HdrType::HDR_X_ACCELERATOR_VARY, vary.termedBuf());
30abd221 702 vary.clean();
62e76326 703 }
704
f66a9ef4 705#endif
b8a899c0 706 pe->replaceHttpReply(rep, false); // no write until key is public
62e76326 707
3900307b 708 pe->timestampsSet();
ba27c9a0 709
eab8dcfa 710 pe->makePublic();
62e76326 711
b8a899c0
AR
712 pe->startWriting(); // after makePublic()
713
62e76326 714 pe->complete();
eab8dcfa 715
1bfe9ade 716 pe->unlock("StoreEntry::setPublicKey+Vary");
62e76326 717 }
718
d88e3c49 719 newkey = storeKeyPublicByRequest(mem_obj->request);
f66a9ef4 720 } else
c877c0bc 721 newkey = storeKeyPublic(mem_obj->storeId(), mem_obj->method);
62e76326 722
c877c0bc
AR
723 if (StoreEntry *e2 = (StoreEntry *)hash_lookup(store_table, newkey)) {
724 debugs(20, 3, "Making old " << *e2 << " private.");
d88e3c49 725 e2->setPrivateKey();
5f33b71d 726 e2->release();
62e76326 727
d88e3c49 728 if (mem_obj->request)
729 newkey = storeKeyPublicByRequest(mem_obj->request);
62e76326 730 else
c877c0bc 731 newkey = storeKeyPublic(mem_obj->storeId(), mem_obj->method);
6eb42cae 732 }
62e76326 733
d88e3c49 734 if (key)
3900307b 735 hashDelete();
62e76326 736
d88e3c49 737 EBIT_CLR(flags, KEY_PRIVATE);
62e76326 738
3900307b 739 hashInsert(newkey);
62e76326 740
d88e3c49 741 if (swap_filen > -1)
742 storeDirSwapLog(this, SWAP_LOG_ADD);
227fbb74 743}
744
b8d8561b 745StoreEntry *
1bfe9ade 746storeCreatePureEntry(const char *url, const char *log_url, const RequestFlags &flags, const HttpRequestMethod& method)
090089c4 747{
090089c4 748 StoreEntry *e = NULL;
bf8fe701 749 debugs(20, 3, "storeCreateEntry: '" << url << "'");
090089c4 750
c877c0bc 751 e = new StoreEntry();
c877c0bc
AR
752 e->makeMemObject();
753 e->mem_obj->setUris(url, log_url, method);
62e76326 754
45e5102d 755 if (flags.cachable) {
62e76326 756 EBIT_CLR(e->flags, RELEASE_REQUEST);
090089c4 757 } else {
d88e3c49 758 e->releaseRequest();
090089c4 759 }
62e76326 760
234967c9 761 e->store_status = STORE_PENDING;
090089c4 762 e->refcount = 0;
b8de7ebe 763 e->lastref = squid_curtime;
3900307b 764 e->timestamp = -1; /* set in StoreEntry::timestampsSet() */
30a4f2a8 765 e->ping_status = PING_NONE;
d46a87a8 766 EBIT_SET(e->flags, ENTRY_VALIDATED);
090089c4 767 return e;
768}
769
1bfe9ade
AR
770StoreEntry *
771storeCreateEntry(const char *url, const char *logUrl, const RequestFlags &flags, const HttpRequestMethod& method)
772{
773 StoreEntry *e = storeCreatePureEntry(url, logUrl, flags, method);
774 e->lock("storeCreateEntry");
775
776 if (neighbors_do_private_keys || !flags.hierarchical)
777 e->setPrivateKey();
778 else
779 e->setPublicKey();
780
781 return e;
782}
783
6eb42cae 784/* Mark object as expired */
b8d8561b 785void
d88e3c49 786StoreEntry::expireNow()
9174e204 787{
bf8fe701 788 debugs(20, 3, "StoreEntry::expireNow: '" << getMD5Text() << "'");
d88e3c49 789 expires = squid_curtime;
9174e204 790}
791
528b2c61 792void
793StoreEntry::write (StoreIOBuffer writeBuffer)
794{
795 assert(mem_obj != NULL);
528b2c61 796 /* This assert will change when we teach the store to update */
d2639a5b 797 PROF_start(StoreEntry_write);
528b2c61 798 assert(store_status == STORE_PENDING);
62e76326 799
55759ffb
AR
800 // XXX: caller uses content offset, but we also store headers
801 if (const HttpReply *reply = mem_obj->getReply())
802 writeBuffer.offset += reply->hdr_sz;
803
d2639a5b 804 debugs(20, 5, "storeWrite: writing " << writeBuffer.length << " bytes for '" << getMD5Text() << "'");
805 PROF_stop(StoreEntry_write);
528b2c61 806 storeGetMemSpace(writeBuffer.length);
55759ffb
AR
807 mem_obj->write(writeBuffer);
808
809 if (!EBIT_TEST(flags, DELAY_SENDING))
810 invokeHandlers();
528b2c61 811}
812
c21ad0f5 813/* Append incoming data from a primary server to an entry. */
814void
815StoreEntry::append(char const *buf, int len)
816{
817 assert(mem_obj != NULL);
3a1c3e2f 818 assert(len >= 0);
c21ad0f5 819 assert(store_status == STORE_PENDING);
528b2c61 820
821 StoreIOBuffer tempBuffer;
822 tempBuffer.data = (char *)buf;
823 tempBuffer.length = len;
aa18a4ca 824 /*
825 * XXX sigh, offset might be < 0 here, but it gets "corrected"
826 * later. This offset crap is such a mess.
827 */
c21ad0f5 828 tempBuffer.offset = mem_obj->endOffset() - (getReply() ? getReply()->hdr_sz : 0);
829 write(tempBuffer);
090089c4 830}
831
0f33a01d
AJ
832void
833StoreEntry::vappendf(const char *fmt, va_list vargs)
834{
835 LOCAL_ARRAY(char, buf, 4096);
836 *buf = 0;
837 int x;
838
bd746807
AJ
839#ifdef VA_COPY
840 va_args ap;
841 /* Fix of bug 753r. The value of vargs is undefined
842 * after vsnprintf() returns. Make a copy of vargs
843 * incase we loop around and call vsnprintf() again.
844 */
845 VA_COPY(ap,vargs);
846 errno = 0;
847 if ((x = vsnprintf(buf, sizeof(buf), fmt, ap)) < 0) {
1fab8344 848 fatal(xstrerr(errno));
bd746807
AJ
849 return;
850 }
851 va_end(ap);
852#else /* VA_COPY */
0f33a01d
AJ
853 errno = 0;
854 if ((x = vsnprintf(buf, sizeof(buf), fmt, vargs)) < 0) {
1fab8344 855 fatal(xstrerr(errno));
0f33a01d
AJ
856 return;
857 }
bd746807 858#endif /*VA_COPY*/
0f33a01d 859
1fab8344 860 if (x < static_cast<int>(sizeof(buf))) {
0f33a01d
AJ
861 append(buf, x);
862 return;
863 }
864
865 // okay, do it the slow way.
866 char *buf2 = new char[x+1];
867 int y = vsnprintf(buf2, x+1, fmt, vargs);
868 assert(y >= 0 && y == x);
869 append(buf2, y);
870 delete[] buf2;
871}
872
873// deprecated. use StoreEntry::appendf() instead.
b8d8561b 874void
fe4e214f 875storeAppendPrintf(StoreEntry * e, const char *fmt,...)
15c05bb0 876{
62d32805 877 va_list args;
878 va_start(args, fmt);
0f33a01d 879 e->vappendf(fmt, args);
cb69b4c7 880 va_end(args);
881}
882
0f33a01d 883// deprecated. use StoreEntry::appendf() instead.
cb69b4c7 884void
885storeAppendVPrintf(StoreEntry * e, const char *fmt, va_list vargs)
886{
0f33a01d 887 e->vappendf(fmt, vargs);
c30c5a73 888}
889
26ac0430 890struct _store_check_cachable_hist {
62e76326 891
26ac0430 892 struct {
62e76326 893 int non_get;
894 int not_entry_cachable;
895 int wrong_content_length;
896 int negative_cached;
897 int too_big;
898 int too_small;
899 int private_key;
900 int too_many_open_files;
901 int too_many_open_fds;
d48fa91c 902 int missing_parts;
2fadd50d 903 } no;
62e76326 904
26ac0430 905 struct {
62e76326 906 int Default;
2fadd50d
HN
907 } yes;
908} store_check_cachable_hist;
8423ff74 909
c47511fd 910int
911storeTooManyDiskFilesOpen(void)
912{
913 if (Config.max_open_disk_fds == 0)
62e76326 914 return 0;
915
83a29c95 916 if (store_open_disk_fd > Config.max_open_disk_fds)
62e76326 917 return 1;
918
c47511fd 919 return 0;
920}
921
3900307b 922int
923StoreEntry::checkTooSmall()
d20b1cd0 924{
3900307b 925 if (EBIT_TEST(flags, ENTRY_SPECIAL))
62e76326 926 return 0;
927
3900307b 928 if (STORE_OK == store_status)
41afe8b2 929 if (mem_obj->object_sz >= 0 &&
26ac0430 930 mem_obj->object_sz < Config.Store.minObjectSize)
62e76326 931 return 1;
3900307b 932 if (getReply()->content_length > -1)
47f6e231 933 if (getReply()->content_length < Config.Store.minObjectSize)
62e76326 934 return 1;
d20b1cd0 935 return 0;
936}
937
2be042f6
AR
938bool
939StoreEntry::checkTooBig() const
940{
941 if (mem_obj->endOffset() > store_maxobjsize)
942 return true;
943
944 if (getReply()->content_length < 0)
945 return false;
946
947 return (getReply()->content_length > store_maxobjsize);
948}
949
ddc9b32c 950// TODO: move "too many open..." checks outside -- we are called too early/late
7015a149 951bool
3900307b 952StoreEntry::checkCachable()
6602e70e 953{
97754f5a
AR
954 // XXX: This method is used for both memory and disk caches, but some
955 // checks are specific to disk caches. Move them to mayStartSwapOut().
956
957 // XXX: This method may be called several times, sometimes with different
958 // outcomes, making store_check_cachable_hist counters misleading.
959
960 // check this first to optimize handling of repeated calls for uncachables
961 if (EBIT_TEST(flags, RELEASE_REQUEST)) {
962 debugs(20, 2, "StoreEntry::checkCachable: NO: not cachable");
963 ++store_check_cachable_hist.no.not_entry_cachable; // TODO: rename?
964 return 0; // avoid rerequesting release below
965 }
966
2ac237e2 967#if CACHE_ALL_METHODS
62e76326 968
c2a7cefd 969 if (mem_obj->method != Http::METHOD_GET) {
bf8fe701 970 debugs(20, 2, "StoreEntry::checkCachable: NO: non-GET method");
5db6bf73 971 ++store_check_cachable_hist.no.non_get;
2ac237e2 972 } else
973#endif
3900307b 974 if (store_status == STORE_OK && EBIT_TEST(flags, ENTRY_BAD_LENGTH)) {
bf8fe701 975 debugs(20, 2, "StoreEntry::checkCachable: NO: wrong content-length");
5db6bf73 976 ++store_check_cachable_hist.no.wrong_content_length;
3900307b 977 } else if (EBIT_TEST(flags, ENTRY_NEGCACHED)) {
bf8fe701 978 debugs(20, 3, "StoreEntry::checkCachable: NO: negative cached");
5db6bf73 979 ++store_check_cachable_hist.no.negative_cached;
c21ad0f5 980 return 0; /* avoid release call below */
2be042f6
AR
981 } else if (!mem_obj || !getReply()) {
982 // XXX: In bug 4131, we forgetHit() without mem_obj, so we need
983 // this segfault protection, but how can we get such a HIT?
2be042f6 984 debugs(20, 2, "StoreEntry::checkCachable: NO: missing parts: " << *this);
d48fa91c 985 ++store_check_cachable_hist.no.missing_parts;
2be042f6 986 } else if (checkTooBig()) {
bf8fe701 987 debugs(20, 2, "StoreEntry::checkCachable: NO: too big");
5db6bf73 988 ++store_check_cachable_hist.no.too_big;
3900307b 989 } else if (checkTooSmall()) {
bf8fe701 990 debugs(20, 2, "StoreEntry::checkCachable: NO: too small");
5db6bf73 991 ++store_check_cachable_hist.no.too_small;
3900307b 992 } else if (EBIT_TEST(flags, KEY_PRIVATE)) {
bf8fe701 993 debugs(20, 3, "StoreEntry::checkCachable: NO: private key");
5db6bf73 994 ++store_check_cachable_hist.no.private_key;
3900307b 995 } else if (swap_status != SWAPOUT_NONE) {
62e76326 996 /*
997 * here we checked the swap_status because the remaining
998 * cases are only relevant only if we haven't started swapping
999 * out the object yet.
1000 */
1001 return 1;
1002 } else if (storeTooManyDiskFilesOpen()) {
bf8fe701 1003 debugs(20, 2, "StoreEntry::checkCachable: NO: too many disk files open");
5db6bf73 1004 ++store_check_cachable_hist.no.too_many_open_files;
62e76326 1005 } else if (fdNFree() < RESERVED_FD) {
bf8fe701 1006 debugs(20, 2, "StoreEntry::checkCachable: NO: too many FD's open");
5db6bf73 1007 ++store_check_cachable_hist.no.too_many_open_fds;
62e76326 1008 } else {
5db6bf73 1009 ++store_check_cachable_hist.yes.Default;
62e76326 1010 return 1;
1011 }
1012
3900307b 1013 releaseRequest();
6602e70e 1014 return 0;
1015}
1016
3900307b 1017void
1018storeCheckCachableStats(StoreEntry *sentry)
8423ff74 1019{
c40acff3 1020 storeAppendPrintf(sentry, "Category\t Count\n");
1021
a0cd8f99 1022#if CACHE_ALL_METHODS
62e76326 1023
8423ff74 1024 storeAppendPrintf(sentry, "no.non_get\t%d\n",
62e76326 1025 store_check_cachable_hist.no.non_get);
a0cd8f99 1026#endif
62e76326 1027
8423ff74 1028 storeAppendPrintf(sentry, "no.not_entry_cachable\t%d\n",
62e76326 1029 store_check_cachable_hist.no.not_entry_cachable);
8423ff74 1030 storeAppendPrintf(sentry, "no.wrong_content_length\t%d\n",
62e76326 1031 store_check_cachable_hist.no.wrong_content_length);
8423ff74 1032 storeAppendPrintf(sentry, "no.negative_cached\t%d\n",
62e76326 1033 store_check_cachable_hist.no.negative_cached);
d48fa91c
AJ
1034 storeAppendPrintf(sentry, "no.missing_parts\t%d\n",
1035 store_check_cachable_hist.no.missing_parts);
8423ff74 1036 storeAppendPrintf(sentry, "no.too_big\t%d\n",
62e76326 1037 store_check_cachable_hist.no.too_big);
d20b1cd0 1038 storeAppendPrintf(sentry, "no.too_small\t%d\n",
62e76326 1039 store_check_cachable_hist.no.too_small);
8423ff74 1040 storeAppendPrintf(sentry, "no.private_key\t%d\n",
62e76326 1041 store_check_cachable_hist.no.private_key);
c5f627c2 1042 storeAppendPrintf(sentry, "no.too_many_open_files\t%d\n",
62e76326 1043 store_check_cachable_hist.no.too_many_open_files);
59ffcdf8 1044 storeAppendPrintf(sentry, "no.too_many_open_fds\t%d\n",
62e76326 1045 store_check_cachable_hist.no.too_many_open_fds);
8423ff74 1046 storeAppendPrintf(sentry, "yes.default\t%d\n",
62e76326 1047 store_check_cachable_hist.yes.Default);
8423ff74 1048}
1049
7224ca5a
AR
1050void
1051StoreEntry::lengthWentBad(const char *reason)
1052{
1053 debugs(20, 3, "because " << reason << ": " << *this);
1054 EBIT_SET(flags, ENTRY_BAD_LENGTH);
1055 releaseRequest();
1056}
1057
b8d8561b 1058void
528b2c61 1059StoreEntry::complete()
090089c4 1060{
bf8fe701 1061 debugs(20, 3, "storeComplete: '" << getMD5Text() << "'");
62e76326 1062
528b2c61 1063 if (store_status != STORE_PENDING) {
62e76326 1064 /*
1065 * if we're not STORE_PENDING, then probably we got aborted
1066 * and there should be NO clients on this entry
1067 */
1068 assert(EBIT_TEST(flags, ENTRY_ABORTED));
1069 assert(mem_obj->nclients == 0);
1070 return;
b6403fac 1071 }
62e76326 1072
7d31d5fa 1073 /* This is suspect: mem obj offsets include the headers. do we adjust for that
1074 * in use of object_sz?
1075 */
528b2c61 1076 mem_obj->object_sz = mem_obj->endOffset();
7d31d5fa 1077
528b2c61 1078 store_status = STORE_OK;
7d31d5fa 1079
528b2c61 1080 assert(mem_status == NOT_IN_MEMORY);
62e76326 1081
7224ca5a
AR
1082 if (!EBIT_TEST(flags, ENTRY_BAD_LENGTH) && !validLength())
1083 lengthWentBad("!validLength() in complete()");
62e76326 1084
6cfa8966 1085#if USE_CACHE_DIGESTS
528b2c61 1086 if (mem_obj->request)
62e76326 1087 mem_obj->request->hier.store_complete_stop = current_time;
1088
39edba21 1089#endif
d20b1cd0 1090 /*
d88e3c49 1091 * We used to call invokeHandlers, then storeSwapOut. However,
d20b1cd0 1092 * Madhukar Reddy <myreddy@persistence.com> reported that
1093 * responses without content length would sometimes get released
1094 * in client_side, thinking that the response is incomplete.
1095 */
d88e3c49 1096 invokeHandlers();
7e3e1d01 1097}
1098
090089c4 1099/*
474cac1b 1100 * Someone wants to abort this transfer. Set the reason in the
d5430dc8 1101 * request structure, call the callback and mark the
2b906e48 1102 * entry for releasing
090089c4 1103 */
b8d8561b 1104void
bfb55b6f 1105StoreEntry::abort()
090089c4 1106{
5db6bf73 1107 ++statCounter.aborted_requests;
bfb55b6f 1108 assert(store_status == STORE_PENDING);
1109 assert(mem_obj != NULL);
bf8fe701 1110 debugs(20, 6, "storeAbort: " << getMD5Text());
34266cde 1111
1bfe9ade 1112 lock("StoreEntry::abort"); /* lock while aborting */
d88e3c49 1113 negativeCache();
34266cde 1114
d88e3c49 1115 releaseRequest();
34266cde 1116
bfb55b6f 1117 EBIT_SET(flags, ENTRY_ABORTED);
34266cde 1118
3900307b 1119 setMemStatus(NOT_IN_MEMORY);
34266cde 1120
bfb55b6f 1121 store_status = STORE_OK;
34266cde 1122
474cac1b 1123 /* Notify the server side */
62e76326 1124
8ea67c2b 1125 /*
1126 * DPW 2007-05-07
1127 * Should we check abort.data for validity?
1128 */
bfb55b6f 1129 if (mem_obj->abort.callback) {
26ac0430 1130 if (!cbdataReferenceValid(mem_obj->abort.data))
e0236918 1131 debugs(20, DBG_IMPORTANT,HERE << "queueing event when abort.data is not valid");
bfb55b6f 1132 eventAdd("mem_obj->abort.callback",
1133 mem_obj->abort.callback,
1134 mem_obj->abort.data,
62e76326 1135 0.0,
8ea67c2b 1136 true);
26ac0430 1137 unregisterAbort();
bfcaf585 1138 }
62e76326 1139
1140 /* XXX Should we reverse these two, so that there is no
26ac0430 1141 * unneeded disk swapping triggered?
528b2c61 1142 */
474cac1b 1143 /* Notify the client side */
d88e3c49 1144 invokeHandlers();
62e76326 1145
aa1a691e
AR
1146 // abort swap out, invalidating what was created so far (release follows)
1147 swapOutFileClose(StoreIOState::writerGone);
62e76326 1148
1bfe9ade 1149 unlock("StoreEntry::abort"); /* unlock */
090089c4 1150}
1151
6d3c2758
HN
1152/**
1153 * Clear Memory storage to accommodate the given object len
1154 */
1155void
d4432957 1156storeGetMemSpace(int size)
090089c4 1157{
1d5161bd 1158 PROF_start(storeGetMemSpace);
b32508fb 1159 StoreEntry *e = NULL;
20cba4b4 1160 int released = 0;
b32508fb 1161 static time_t last_check = 0;
528b2c61 1162 size_t pages_needed;
6a566b9c 1163 RemovalPurgeWalker *walker;
62e76326 1164
1d5161bd 1165 if (squid_curtime == last_check) {
1166 PROF_stop(storeGetMemSpace);
62e76326 1167 return;
1d5161bd 1168 }
62e76326 1169
b32508fb 1170 last_check = squid_curtime;
62e76326 1171
2ad51840 1172 pages_needed = (size + SM_PAGE_SIZE-1) / SM_PAGE_SIZE;
62e76326 1173
1d5161bd 1174 if (mem_node::InUseCount() + pages_needed < store_pages_max) {
1175 PROF_stop(storeGetMemSpace);
62e76326 1176 return;
1d5161bd 1177 }
62e76326 1178
e4049756 1179 debugs(20, 2, "storeGetMemSpace: Starting, need " << pages_needed <<
1180 " pages");
62e76326 1181
6a566b9c 1182 /* XXX what to set as max_scan here? */
1183 walker = mem_policy->PurgeInit(mem_policy, 100000);
62e76326 1184
c1dd71ae 1185 while ((e = walker->Next(walker))) {
d88e3c49 1186 e->purgeMem();
5db6bf73 1187 ++released;
62e76326 1188
1189 if (mem_node::InUseCount() + pages_needed < store_pages_max)
1190 break;
8350fe9b 1191 }
62e76326 1192
6a566b9c 1193 walker->Done(walker);
bf8fe701 1194 debugs(20, 3, "storeGetMemSpace stats:");
1195 debugs(20, 3, " " << std::setw(6) << hot_obj_count << " HOT objects");
1196 debugs(20, 3, " " << std::setw(6) << released << " were released");
1d5161bd 1197 PROF_stop(storeGetMemSpace);
090089c4 1198}
1199
c8f4eac4 1200/* thunk through to Store::Root().maintain(). Note that this would be better still
26ac0430
AJ
1201 * if registered against the root store itself, but that requires more complex
1202 * update logic - bigger fish to fry first. Long term each store when
c8f4eac4 1203 * it becomes active will self register
1204 */
1205void
ced8def3 1206Store::Maintain(void *)
c8f4eac4 1207{
1208 Store::Root().maintain();
1209
1210 /* Reregister a maintain event .. */
1211 eventAdd("MaintainSwapSpace", Maintain, NULL, 1.0, 1);
1212
1213}
1214
090089c4 1215/* The maximum objects to scan for maintain storage space */
c21ad0f5 1216#define MAINTAIN_MAX_SCAN 1024
1217#define MAINTAIN_MAX_REMOVE 64
090089c4 1218
090089c4 1219/* release an object from a cache */
6c78a099 1220void
5f33b71d 1221StoreEntry::release()
090089c4 1222{
88bfe092 1223 PROF_start(storeRelease);
1bfe9ade 1224 debugs(20, 3, "releasing " << *this << ' ' << getMD5Text());
090089c4 1225 /* If, for any reason we can't discard this object because of an
1226 * outstanding request, mark it for pending release */
62e76326 1227
3900307b 1228 if (locked()) {
d88e3c49 1229 expireNow();
bf8fe701 1230 debugs(20, 3, "storeRelease: Only setting RELEASE_REQUEST bit");
d88e3c49 1231 releaseRequest();
62e76326 1232 PROF_stop(storeRelease);
1233 return;
090089c4 1234 }
62e76326 1235
2745fea5
AR
1236 if (Store::Controller::store_dirs_rebuilding && swap_filen > -1) {
1237 /* TODO: Teach disk stores to handle releases during rebuild instead. */
ce49546e 1238
2745fea5 1239 Store::Root().memoryUnlink(*this);
62e76326 1240
2745fea5 1241 setPrivateKey();
22c25cbb 1242
2745fea5
AR
1243 // lock the entry until rebuilding is done
1244 lock("storeLateRelease");
1245 setReleaseFlag();
1246 LateReleaseStack.push(this);
22c25cbb 1247 return;
43d9cf56 1248 }
62e76326 1249
5f33b71d 1250 storeLog(STORE_LOG_RELEASE, this);
2745fea5 1251 if (swap_filen > -1 && !EBIT_TEST(flags, KEY_PRIVATE)) {
f58bb2f4 1252 // log before unlink() below clears swap_filen
2745fea5 1253 storeDirSwapLog(this, SWAP_LOG_DEL);
090089c4 1254 }
62e76326 1255
2745fea5 1256 Store::Root().unlink(*this);
5f33b71d 1257 destroyStoreEntry(static_cast<hash_link *>(this));
88bfe092 1258 PROF_stop(storeRelease);
090089c4 1259}
1260
e42d5181 1261static void
ced8def3 1262storeLateRelease(void *)
e42d5181 1263{
1264 StoreEntry *e;
e42d5181 1265 static int n = 0;
62e76326 1266
2745fea5 1267 if (Store::Controller::store_dirs_rebuilding) {
62e76326 1268 eventAdd("storeLateRelease", storeLateRelease, NULL, 1.0, 1);
1269 return;
e42d5181 1270 }
62e76326 1271
cfb88efb
AR
1272 // TODO: this works but looks unelegant.
1273 for (int i = 0; i < 10; ++i) {
1274 if (LateReleaseStack.empty()) {
24b14da9
FC
1275 debugs(20, DBG_IMPORTANT, "storeLateRelease: released " << n << " objects");
1276 return;
cfb88efb
AR
1277 } else {
1278 e = LateReleaseStack.top();
1279 LateReleaseStack.pop();
3aa53107 1280 }
62e76326 1281
1bfe9ade 1282 e->unlock("storeLateRelease");
5db6bf73 1283 ++n;
e42d5181 1284 }
62e76326 1285
e42d5181 1286 eventAdd("storeLateRelease", storeLateRelease, NULL, 0.0, 1);
1287}
1288
090089c4 1289/* return 1 if a store entry is locked */
cd748f27 1290int
3900307b 1291StoreEntry::locked() const
090089c4 1292{
3900307b 1293 if (lock_count)
62e76326 1294 return 1;
1295
b8890359 1296 /*
1bfe9ade
AR
1297 * SPECIAL, PUBLIC entries should be "locked";
1298 * XXX: Their owner should lock them then instead of relying on this hack.
b8890359 1299 */
3900307b 1300 if (EBIT_TEST(flags, ENTRY_SPECIAL))
1301 if (!EBIT_TEST(flags, KEY_PRIVATE))
62e76326 1302 return 1;
1303
30a4f2a8 1304 return 0;
090089c4 1305}
1306
528b2c61 1307bool
1308StoreEntry::validLength() const
6602e70e 1309{
47f6e231 1310 int64_t diff;
d8b249ef 1311 const HttpReply *reply;
528b2c61 1312 assert(mem_obj != NULL);
1313 reply = getReply();
bf8fe701 1314 debugs(20, 3, "storeEntryValidLength: Checking '" << getMD5Text() << "'");
e4049756 1315 debugs(20, 5, "storeEntryValidLength: object_len = " <<
707fdc47 1316 objectLen());
bf8fe701 1317 debugs(20, 5, "storeEntryValidLength: hdr_sz = " << reply->hdr_sz);
1318 debugs(20, 5, "storeEntryValidLength: content_length = " << reply->content_length);
62e76326 1319
d8b249ef 1320 if (reply->content_length < 0) {
bf8fe701 1321 debugs(20, 5, "storeEntryValidLength: Unspecified content length: " << getMD5Text());
62e76326 1322 return 1;
ffe4a367 1323 }
62e76326 1324
07304bf9 1325 if (reply->hdr_sz == 0) {
bf8fe701 1326 debugs(20, 5, "storeEntryValidLength: Zero header size: " << getMD5Text());
62e76326 1327 return 1;
ffe4a367 1328 }
62e76326 1329
c2a7cefd 1330 if (mem_obj->method == Http::METHOD_HEAD) {
bf8fe701 1331 debugs(20, 5, "storeEntryValidLength: HEAD request: " << getMD5Text());
62e76326 1332 return 1;
ffe4a367 1333 }
62e76326 1334
9b769c67 1335 if (reply->sline.status() == Http::scNotModified)
62e76326 1336 return 1;
1337
9b769c67 1338 if (reply->sline.status() == Http::scNoContent)
62e76326 1339 return 1;
1340
707fdc47 1341 diff = reply->hdr_sz + reply->content_length - objectLen();
62e76326 1342
ebf4efff 1343 if (diff == 0)
62e76326 1344 return 1;
1345
bf8fe701 1346 debugs(20, 3, "storeEntryValidLength: " << (diff < 0 ? -diff : diff) << " bytes too " << (diff < 0 ? "big" : "small") <<"; '" << getMD5Text() << "'" );
62e76326 1347
ebf4efff 1348 return 0;
ffe4a367 1349}
6602e70e 1350
6b7d87bb
FC
1351static void
1352storeRegisterWithCacheManager(void)
1353{
8822ebee
AR
1354 Mgr::RegisterAction("storedir", "Store Directory Stats", Store::Stats, 0, 1);
1355 Mgr::RegisterAction("store_io", "Store IO Interface Stats", &Mgr::StoreIoAction::Create, 0, 1);
1356 Mgr::RegisterAction("store_check_cachable_stats", "storeCheckCachable() Stats",
d9fc6862 1357 storeCheckCachableStats, 0, 1);
6b7d87bb
FC
1358}
1359
b8d8561b 1360void
1361storeInit(void)
c943f331 1362{
25535cbe 1363 storeKeyInit();
6a566b9c 1364 mem_policy = createRemovalPolicy(Config.memPolicy);
8638fc66 1365 storeDigestInit();
e3ef2b09 1366 storeLogOpen();
e42d5181 1367 eventAdd("storeLateRelease", storeLateRelease, NULL, 1.0, 1);
c8f4eac4 1368 Store::Root().init();
b2c141d4 1369 storeRebuildStart();
d120ed12
FC
1370
1371 storeRegisterWithCacheManager();
62ee09ca 1372}
1373
3c856e95
AR
1374/// computes maximum size of a cachable object
1375/// larger objects are rejected by all (disk and memory) cache stores
1376static int64_t
1377storeCalcMaxObjSize()
1378{
1379 int64_t ms = 0; // nothing can be cached without at least one store consent
1380
1381 // global maximum is at least the disk store maximum
1382 for (int i = 0; i < Config.cacheSwap.n_configured; ++i) {
1383 assert (Config.cacheSwap.swapDirs[i].getRaw());
1384 const int64_t storeMax = dynamic_cast<SwapDir *>(Config.cacheSwap.swapDirs[i].getRaw())->maxObjectSize();
1385 if (ms < storeMax)
1386 ms = storeMax;
1387 }
1388
1389 // global maximum is at least the memory store maximum
1390 // TODO: move this into a memory cache class when we have one
1391 const int64_t memMax = static_cast<int64_t>(min(Config.Store.maxInMemObjSize, Config.memMaxSize));
1392 if (ms < memMax)
1393 ms = memMax;
1394
1395 return ms;
1396}
1397
b8d8561b 1398void
1399storeConfigure(void)
b1c0cc67 1400{
c8f4eac4 1401 store_swap_high = (long) (((float) Store::Root().maxSize() *
62e76326 1402 (float) Config.Swap.highWaterMark) / (float) 100);
c8f4eac4 1403 store_swap_low = (long) (((float) Store::Root().maxSize() *
62e76326 1404 (float) Config.Swap.lowWaterMark) / (float) 100);
505d4821 1405 store_pages_max = Config.memMaxSize / sizeof(mem_node);
3c856e95
AR
1406
1407 store_maxobjsize = storeCalcMaxObjSize();
090089c4 1408}
1409
9487bae9 1410bool
97754f5a 1411StoreEntry::memoryCachable()
56f29785 1412{
97754f5a
AR
1413 if (!checkCachable())
1414 return 0;
1415
3900307b 1416 if (mem_obj == NULL)
62e76326 1417 return 0;
1418
3900307b 1419 if (mem_obj->data_hdr.size() == 0)
62e76326 1420 return 0;
1421
19fdd3f3 1422 if (mem_obj->inmem_lo != 0)
e1381638 1423 return 0;
19fdd3f3 1424
d227e181 1425 if (!Config.onoff.memory_cache_first && swap_status == SWAPOUT_DONE && refcount == 1)
e1381638 1426 return 0;
19fdd3f3
HN
1427
1428 return 1;
56f29785 1429}
1430
edce4d98 1431int
3900307b 1432StoreEntry::checkNegativeHit() const
edce4d98 1433{
3900307b 1434 if (!EBIT_TEST(flags, ENTRY_NEGCACHED))
62e76326 1435 return 0;
1436
3900307b 1437 if (expires <= squid_curtime)
62e76326 1438 return 0;
1439
3900307b 1440 if (store_status != STORE_OK)
62e76326 1441 return 0;
1442
edce4d98 1443 return 1;
1444}
1445
ac9cc053
AJ
1446/**
1447 * Set object for negative caching.
1448 * Preserves any expiry information given by the server.
1449 * In absence of proper expiry info it will set to expire immediately,
1450 * or with HTTP-violations enabled the configured negative-TTL is observed
1451 */
b8d8561b 1452void
d88e3c49 1453StoreEntry::negativeCache()
79b5cc5f 1454{
da03a7e0
AJ
1455 // XXX: should make the default for expires 0 instead of -1
1456 // so we can distinguish "Expires: -1" from nothing.
1457 if (expires <= 0)
626096be 1458#if USE_HTTP_VIOLATIONS
ac9cc053
AJ
1459 expires = squid_curtime + Config.negativeTtl;
1460#else
1461 expires = squid_curtime;
1462#endif
d88e3c49 1463 EBIT_SET(flags, ENTRY_NEGCACHED);
79b5cc5f 1464}
0a21bd84 1465
1466void
1467storeFreeMemory(void)
1468{
2745fea5 1469 Store::FreeMemory();
9bc73deb 1470#if USE_CACHE_DIGESTS
a901d0b4 1471 delete store_digest;
c68e9c6b 1472#endif
8638fc66 1473 store_digest = NULL;
0a21bd84 1474}
a7e59001 1475
1476int
1477expiresMoreThan(time_t expires, time_t when)
1478{
c21ad0f5 1479 if (expires < 0) /* No Expires given */
62e76326 1480 return 1;
1481
48f44632 1482 return (expires > (squid_curtime + when));
a7e59001 1483}
fe54d06d 1484
1485int
3900307b 1486StoreEntry::validToSend() const
fe54d06d 1487{
3900307b 1488 if (EBIT_TEST(flags, RELEASE_REQUEST))
62e76326 1489 return 0;
1490
3900307b 1491 if (EBIT_TEST(flags, ENTRY_NEGCACHED))
1492 if (expires <= squid_curtime)
62e76326 1493 return 0;
1494
3900307b 1495 if (EBIT_TEST(flags, ENTRY_ABORTED))
62e76326 1496 return 0;
1497
22696a16
AR
1498 // now check that the entry has a cache backing or is collapsed
1499 if (swap_filen > -1) // backed by a disk cache
1500 return 1;
1501
1502 if (swappingOut()) // will be backed by a disk cache
1503 return 1;
1504
1505 if (!mem_obj) // not backed by a memory cache and not collapsed
1506 return 0;
1507
22696a16 1508 // StoreEntry::storeClientType() assumes DISK_CLIENT here, but there is no
a4b04ff8
AR
1509 // disk cache backing that store_client constructor will assert. XXX: This
1510 // is wrong for range requests (that could feed off nibbled memory) and for
1511 // entries backed by the shared memory cache (that could, in theory, get
1512 // nibbled bytes from that cache, but there is no such "memoryIn" code).
1513 if (mem_obj->inmem_lo) // in memory cache, but got nibbled at
22696a16
AR
1514 return 0;
1515
a4b04ff8
AR
1516 // The following check is correct but useless at this position. TODO: Move
1517 // it up when the shared memory cache can either replenish locally nibbled
1518 // bytes or, better, does not use local RAM copy at all.
1519 // if (mem_obj->memCache.index >= 0) // backed by a shared memory cache
1520 // return 1;
1521
fe54d06d 1522 return 1;
1523}
62663274 1524
ca98227c 1525void
3900307b 1526StoreEntry::timestampsSet()
ca98227c 1527{
3900307b 1528 const HttpReply *reply = getReply();
2f58241d 1529 time_t served_date = reply->date;
789217a2 1530 int age = reply->header.getInt(Http::HdrType::AGE);
31d36bfd 1531 /* Compute the timestamp, mimicking RFC2616 section 13.2.3. */
2f58241d 1532 /* make sure that 0 <= served_date <= squid_curtime */
62e76326 1533
2f58241d 1534 if (served_date < 0 || served_date > squid_curtime)
62e76326 1535 served_date = squid_curtime;
1536
525bf9dc
BD
1537 /* Bug 1791:
1538 * If the returned Date: is more than 24 hours older than
1539 * the squid_curtime, then one of us needs to use NTP to set our
1540 * clock. We'll pretend that our clock is right.
1541 */
1542 else if (served_date < (squid_curtime - 24 * 60 * 60) )
1543 served_date = squid_curtime;
62e76326 1544
efd900cb 1545 /*
212cbb48 1546 * Compensate with Age header if origin server clock is ahead
1547 * of us and there is a cache in between us and the origin
1548 * server. But DONT compensate if the age value is larger than
1549 * squid_curtime because it results in a negative served_date.
efd900cb 1550 */
1551 if (age > squid_curtime - served_date)
62e76326 1552 if (squid_curtime > age)
1553 served_date = squid_curtime - age;
1554
31d36bfd
AR
1555 // compensate for Squid-to-server and server-to-Squid delays
1556 if (mem_obj && mem_obj->request) {
1557 const time_t request_sent =
1558 mem_obj->request->hier.peer_http_request_sent.tv_sec;
1559 if (0 < request_sent && request_sent < squid_curtime)
1560 served_date -= (squid_curtime - request_sent);
1561 }
1562
0d465a25 1563 if (reply->expires > 0 && reply->date > -1)
26ac0430 1564 expires = served_date + (reply->expires - reply->date);
0d465a25 1565 else
26ac0430 1566 expires = reply->expires;
62e76326 1567
3900307b 1568 lastmod = reply->last_modified;
62e76326 1569
3900307b 1570 timestamp = served_date;
ca98227c 1571}
429fdbec 1572
bfcaf585 1573void
3900307b 1574StoreEntry::registerAbort(STABH * cb, void *data)
bfcaf585 1575{
3900307b 1576 assert(mem_obj);
1577 assert(mem_obj->abort.callback == NULL);
1578 mem_obj->abort.callback = cb;
8ea67c2b 1579 mem_obj->abort.data = cbdataReference(data);
bfcaf585 1580}
1581
1582void
3900307b 1583StoreEntry::unregisterAbort()
bfcaf585 1584{
3900307b 1585 assert(mem_obj);
8ea67c2b 1586 if (mem_obj->abort.callback) {
26ac0430
AJ
1587 mem_obj->abort.callback = NULL;
1588 cbdataReferenceDone(mem_obj->abort.data);
8ea67c2b 1589 }
bfcaf585 1590}
88738790 1591
f09f5b26 1592void
3900307b 1593StoreEntry::dump(int l) const
1594{
bf8fe701 1595 debugs(20, l, "StoreEntry->key: " << getMD5Text());
1596 debugs(20, l, "StoreEntry->next: " << next);
1597 debugs(20, l, "StoreEntry->mem_obj: " << mem_obj);
4a7a3d56 1598 debugs(20, l, "StoreEntry->timestamp: " << timestamp);
1599 debugs(20, l, "StoreEntry->lastref: " << lastref);
1600 debugs(20, l, "StoreEntry->expires: " << expires);
1601 debugs(20, l, "StoreEntry->lastmod: " << lastmod);
1602 debugs(20, l, "StoreEntry->swap_file_sz: " << swap_file_sz);
bf8fe701 1603 debugs(20, l, "StoreEntry->refcount: " << refcount);
1604 debugs(20, l, "StoreEntry->flags: " << storeEntryFlags(this));
4a7a3d56 1605 debugs(20, l, "StoreEntry->swap_dirn: " << swap_dirn);
1606 debugs(20, l, "StoreEntry->swap_filen: " << swap_filen);
1607 debugs(20, l, "StoreEntry->lock_count: " << lock_count);
1608 debugs(20, l, "StoreEntry->mem_status: " << mem_status);
1609 debugs(20, l, "StoreEntry->ping_status: " << ping_status);
1610 debugs(20, l, "StoreEntry->store_status: " << store_status);
1611 debugs(20, l, "StoreEntry->swap_status: " << swap_status);
d377699f 1612}
1613
1f38f50a 1614/*
1615 * NOTE, this function assumes only two mem states
1616 */
f09f5b26 1617void
3900307b 1618StoreEntry::setMemStatus(mem_status_t new_status)
8350fe9b 1619{
3900307b 1620 if (new_status == mem_status)
62e76326 1621 return;
1622
6ebe9a4c
AR
1623 // are we using a shared memory cache?
1624 if (Config.memShared && IamWorkerProcess()) {
9487bae9
AR
1625 // This method was designed to update replacement policy, not to
1626 // actually purge something from the memory cache (TODO: rename?).
1627 // Shared memory cache does not have a policy that needs updates.
1628 mem_status = new_status;
1629 return;
1630 }
1631
3900307b 1632 assert(mem_obj != NULL);
62e76326 1633
b93bcace 1634 if (new_status == IN_MEMORY) {
3900307b 1635 assert(mem_obj->inmem_lo == 0);
62e76326 1636
3900307b 1637 if (EBIT_TEST(flags, ENTRY_SPECIAL)) {
c877c0bc 1638 debugs(20, 4, "not inserting special " << *this << " into policy");
62e76326 1639 } else {
3900307b 1640 mem_policy->Add(mem_policy, this, &mem_obj->repl);
c877c0bc 1641 debugs(20, 4, "inserted " << *this << " key: " << getMD5Text());
62e76326 1642 }
1643
5db6bf73 1644 ++hot_obj_count; // TODO: maintain for the shared hot cache as well
b93bcace 1645 } else {
3900307b 1646 if (EBIT_TEST(flags, ENTRY_SPECIAL)) {
c877c0bc 1647 debugs(20, 4, "not removing special " << *this << " from policy");
62e76326 1648 } else {
3900307b 1649 mem_policy->Remove(mem_policy, this, &mem_obj->repl);
c877c0bc 1650 debugs(20, 4, "removed " << *this);
62e76326 1651 }
1652
5e263176 1653 --hot_obj_count;
b93bcace 1654 }
62e76326 1655
3900307b 1656 mem_status = new_status;
8350fe9b 1657}
6e86c3e8 1658
9fb13bb6 1659const char *
3900307b 1660StoreEntry::url() const
9fb13bb6 1661{
328a07ab 1662 if (mem_obj == NULL)
62e76326 1663 return "[null_mem_obj]";
9fb13bb6 1664 else
c877c0bc 1665 return mem_obj->storeId();
9fb13bb6 1666}
24ffafb4 1667
c877c0bc
AR
1668MemObject *
1669StoreEntry::makeMemObject()
24ffafb4 1670{
c877c0bc
AR
1671 if (!mem_obj)
1672 mem_obj = new MemObject();
1673 return mem_obj;
1674}
9487bae9 1675
c877c0bc
AR
1676void
1677StoreEntry::createMemObject(const char *aUrl, const char *aLogUrl, const HttpRequestMethod &aMethod)
1678{
1679 makeMemObject();
1680 mem_obj->setUris(aUrl, aLogUrl, aMethod);
c21ad0f5 1681}
1682
7e10ac87
AJ
1683/** disable sending content to the clients.
1684 *
1685 * This just sets DELAY_SENDING.
1686 */
c21ad0f5 1687void
1688StoreEntry::buffer()
1689{
1690 EBIT_SET(flags, DELAY_SENDING);
1691}
1692
7e10ac87
AJ
1693/** flush any buffered content.
1694 *
1695 * This just clears DELAY_SENDING and Invokes the handlers
1696 * to begin sending anything that may be buffered.
1697 */
438fc1e3 1698void
c21ad0f5 1699StoreEntry::flush()
438fc1e3 1700{
c21ad0f5 1701 if (EBIT_TEST(flags, DELAY_SENDING)) {
1702 EBIT_CLR(flags, DELAY_SENDING);
d88e3c49 1703 invokeHandlers();
b66315e4 1704 }
25535cbe 1705}
07304bf9 1706
47f6e231 1707int64_t
707fdc47 1708StoreEntry::objectLen() const
07304bf9 1709{
707fdc47 1710 assert(mem_obj != NULL);
1711 return mem_obj->object_sz;
07304bf9 1712}
1713
47f6e231 1714int64_t
b37bde1e 1715StoreEntry::contentLen() const
07304bf9 1716{
b37bde1e 1717 assert(mem_obj != NULL);
1718 assert(getReply() != NULL);
1719 return objectLen() - getReply()->hdr_sz;
07304bf9 1720}
f3986a15 1721
528b2c61 1722HttpReply const *
1723StoreEntry::getReply () const
f3986a15 1724{
528b2c61 1725 if (NULL == mem_obj)
62e76326 1726 return NULL;
1727
528b2c61 1728 return mem_obj->getReply();
f3986a15 1729}
db1cd23c 1730
1731void
3900307b 1732StoreEntry::reset()
db1cd23c 1733{
3900307b 1734 assert (mem_obj);
bf8fe701 1735 debugs(20, 3, "StoreEntry::reset: " << url());
3900307b 1736 mem_obj->reset();
1737 HttpReply *rep = (HttpReply *) getReply(); // bypass const
06a5ae20 1738 rep->reset();
3900307b 1739 expires = lastmod = timestamp = -1;
db1cd23c 1740}
2b906e48 1741
cd748f27 1742/*
1743 * storeFsInit
1744 *
1745 * This routine calls the SETUP routine for each fs type.
1746 * I don't know where the best place for this is, and I'm not going to shuffle
1747 * around large chunks of code right now (that can be done once its working.)
1748 */
1749void
1750storeFsInit(void)
1751{
22d38e05 1752 storeReplSetup();
cd748f27 1753}
1754
22d38e05 1755/*
1756 * called to add another store removal policy module
1757 */
1758void
a2c963ae 1759storeReplAdd(const char *type, REMOVALPOLICYCREATE * create)
22d38e05 1760{
1761 int i;
62e76326 1762
d64c1498 1763 /* find the number of currently known repl types */
5db6bf73 1764 for (i = 0; storerepl_list && storerepl_list[i].typestr; ++i) {
d64c1498 1765 if (strcmp(storerepl_list[i].typestr, type) == 0) {
e0236918 1766 debugs(20, DBG_IMPORTANT, "WARNING: Trying to load store replacement policy " << type << " twice.");
d64c1498
AJ
1767 return;
1768 }
22d38e05 1769 }
62e76326 1770
22d38e05 1771 /* add the new type */
e6ccf245 1772 storerepl_list = static_cast<storerepl_entry_t *>(xrealloc(storerepl_list, (i + 2) * sizeof(storerepl_entry_t)));
62e76326 1773
22d38e05 1774 memset(&storerepl_list[i + 1], 0, sizeof(storerepl_entry_t));
62e76326 1775
22d38e05 1776 storerepl_list[i].typestr = type;
62e76326 1777
22d38e05 1778 storerepl_list[i].create = create;
1779}
1780
1781/*
1782 * Create a removal policy instance
1783 */
1784RemovalPolicy *
1785createRemovalPolicy(RemovalPolicySettings * settings)
1786{
1787 storerepl_entry_t *r;
62e76326 1788
5db6bf73 1789 for (r = storerepl_list; r && r->typestr; ++r) {
62e76326 1790 if (strcmp(r->typestr, settings->type) == 0)
1791 return r->create(settings->args);
22d38e05 1792 }
62e76326 1793
e0236918
FC
1794 debugs(20, DBG_IMPORTANT, "ERROR: Unknown policy " << settings->type);
1795 debugs(20, DBG_IMPORTANT, "ERROR: Be sure to have set cache_replacement_policy");
1796 debugs(20, DBG_IMPORTANT, "ERROR: and memory_replacement_policy in squid.conf!");
0c5ccf11 1797 fatalf("ERROR: Unknown policy %s\n", settings->type);
c21ad0f5 1798 return NULL; /* NOTREACHED */
22d38e05 1799}
1800
cd748f27 1801#if 0
fc8b9fc0 1802void
1803storeSwapFileNumberSet(StoreEntry * e, sfileno filn)
1804{
1805 if (e->swap_file_number == filn)
62e76326 1806 return;
1807
fc8b9fc0 1808 if (filn < 0) {
62e76326 1809 assert(-1 == filn);
1810 storeDirMapBitReset(e->swap_file_number);
1811 storeDirLRUDelete(e);
1812 e->swap_file_number = -1;
fc8b9fc0 1813 } else {
62e76326 1814 assert(-1 == e->swap_file_number);
1815 storeDirMapBitSet(e->swap_file_number = filn);
1816 storeDirLRUAdd(e);
fc8b9fc0 1817 }
1818}
62e76326 1819
cd748f27 1820#endif
e6ccf245 1821
eacfca83
AR
1822void
1823StoreEntry::storeErrorResponse(HttpReply *reply)
1824{
1825 lock("StoreEntry::storeErrorResponse");
1826 buffer();
1827 replaceHttpReply(reply);
1828 flush();
1829 complete();
1830 negativeCache();
1831 releaseRequest();
1832 unlock("StoreEntry::storeErrorResponse");
1833}
1834
db237875 1835/*
1836 * Replace a store entry with
528b2c61 1837 * a new reply. This eats the reply.
1838 */
4a56ee8d 1839void
3756e5c0 1840StoreEntry::replaceHttpReply(HttpReply *rep, bool andStartWriting)
4a56ee8d 1841{
bf8fe701 1842 debugs(20, 3, "StoreEntry::replaceHttpReply: " << url());
62e76326 1843
4a56ee8d 1844 if (!mem_obj) {
fa84c01d 1845 debugs(20, DBG_CRITICAL, "Attempt to replace object with no in-memory representation");
62e76326 1846 return;
528b2c61 1847 }
62e76326 1848
4a56ee8d 1849 mem_obj->replaceHttpReply(rep);
1850
3756e5c0
AR
1851 if (andStartWriting)
1852 startWriting();
1853}
1854
3756e5c0
AR
1855void
1856StoreEntry::startWriting()
1857{
691ad095 1858 /* TODO: when we store headers separately remove the header portion */
528b2c61 1859 /* TODO: mark the length of the headers ? */
1860 /* We ONLY want the headers */
62e76326 1861
4a56ee8d 1862 assert (isEmpty());
3756e5c0 1863 assert(mem_obj);
9199139f 1864
3756e5c0
AR
1865 const HttpReply *rep = getReply();
1866 assert(rep);
62e76326 1867
15179984
AJ
1868 buffer();
1869 rep->packHeadersInto(this);
3756e5c0 1870 mem_obj->markEndOfReplyHeaders();
4475555f 1871 EBIT_CLR(flags, ENTRY_FWD_HDR_WAIT);
62e76326 1872
15179984 1873 rep->body.packInto(this);
691ad095 1874 flush();
528b2c61 1875}
62e76326 1876
528b2c61 1877char const *
1878StoreEntry::getSerialisedMetaData()
1879{
1880 StoreMeta *tlv_list = storeSwapMetaBuild(this);
1881 int swap_hdr_sz;
1882 char *result = storeSwapMetaPack(tlv_list, &swap_hdr_sz);
1883 storeSwapTLVFree(tlv_list);
aa1a691e
AR
1884 assert (swap_hdr_sz >= 0);
1885 mem_obj->swap_hdr_sz = (size_t) swap_hdr_sz;
528b2c61 1886 return result;
1887}
1888
0cdcf3d7
AR
1889/**
1890 * Abandon the transient entry our worker has created if neither the shared
1891 * memory cache nor the disk cache wants to store it. Collapsed requests, if
1892 * any, should notice and use Plan B instead of getting stuck waiting for us
1893 * to start swapping the entry out.
1894 */
1895void
2da4bfe6
A
1896StoreEntry::transientsAbandonmentCheck()
1897{
0cdcf3d7 1898 if (mem_obj && !mem_obj->smpCollapsed && // this worker is responsible
2da4bfe6
A
1899 mem_obj->xitTable.index >= 0 && // other workers may be interested
1900 mem_obj->memCache.index < 0 && // rejected by the shared memory cache
1901 mem_obj->swapout.decision == MemObject::SwapOut::swImpossible) {
0cdcf3d7
AR
1902 debugs(20, 7, "cannot be shared: " << *this);
1903 if (!shutting_down) // Store::Root() is FATALly missing during shutdown
1904 Store::Root().transientsAbandon(*this);
1905 }
1906}
1907
1908void
ced8def3 1909StoreEntry::memOutDecision(const bool)
2da4bfe6 1910{
0cdcf3d7
AR
1911 transientsAbandonmentCheck();
1912}
1913
1914void
2da4bfe6
A
1915StoreEntry::swapOutDecision(const MemObject::SwapOut::Decision &decision)
1916{
0cdcf3d7
AR
1917 // Abandon our transient entry if neither shared memory nor disk wants it.
1918 assert(mem_obj);
1919 mem_obj->swapout.decision = decision;
1920 transientsAbandonmentCheck();
1921}
1922
528b2c61 1923void
5b55f1f1 1924StoreEntry::trimMemory(const bool preserveSwappable)
528b2c61 1925{
7fef2365 1926 /*
1927 * DPW 2007-05-09
1928 * Bug #1943. We must not let go any data for IN_MEMORY
1929 * objects. We have to wait until the mem_status changes.
1930 */
1931 if (mem_status == IN_MEMORY)
26ac0430 1932 return;
7fef2365 1933
c5426f8f
AR
1934 if (EBIT_TEST(flags, ENTRY_SPECIAL))
1935 return; // cannot trim because we do not load them again
1936
99921d9d
AR
1937 if (preserveSwappable)
1938 mem_obj->trimSwappable();
1939 else
1940 mem_obj->trimUnSwappable();
1941
1942 debugs(88, 7, *this << " inmem_lo=" << mem_obj->inmem_lo);
528b2c61 1943}
62e76326 1944
0655fa4d 1945bool
190154cf 1946StoreEntry::modifiedSince(HttpRequest * request) const
0655fa4d 1947{
1948 int object_length;
1949 time_t mod_time = lastmod;
1950
1951 if (mod_time < 0)
1952 mod_time = timestamp;
1953
bf8fe701 1954 debugs(88, 3, "modifiedSince: '" << url() << "'");
0655fa4d 1955
4a7a3d56 1956 debugs(88, 3, "modifiedSince: mod_time = " << mod_time);
0655fa4d 1957
1958 if (mod_time < 0)
1959 return true;
1960
1961 /* Find size of the object */
1962 object_length = getReply()->content_length;
1963
1964 if (object_length < 0)
b37bde1e 1965 object_length = contentLen();
0655fa4d 1966
1967 if (mod_time > request->ims) {
bf8fe701 1968 debugs(88, 3, "--> YES: entry newer than client");
0655fa4d 1969 return true;
1970 } else if (mod_time < request->ims) {
bf8fe701 1971 debugs(88, 3, "--> NO: entry older than client");
0655fa4d 1972 return false;
1973 } else if (request->imslen < 0) {
bf8fe701 1974 debugs(88, 3, "--> NO: same LMT, no client length");
0655fa4d 1975 return false;
1976 } else if (request->imslen == object_length) {
bf8fe701 1977 debugs(88, 3, "--> NO: same LMT, same length");
0655fa4d 1978 return false;
1979 } else {
bf8fe701 1980 debugs(88, 3, "--> YES: same LMT, different length");
0655fa4d 1981 return true;
1982 }
1983}
1984
46017fdd
CT
1985bool
1986StoreEntry::hasEtag(ETag &etag) const
1987{
1988 if (const HttpReply *reply = getReply()) {
789217a2 1989 etag = reply->header.getETag(Http::HdrType::ETAG);
46017fdd
CT
1990 if (etag.str)
1991 return true;
1992 }
1993 return false;
1994}
1995
79c8035e
AR
1996bool
1997StoreEntry::hasIfMatchEtag(const HttpRequest &request) const
1998{
789217a2 1999 const String reqETags = request.header.getList(Http::HdrType::IF_MATCH);
79c8035e
AR
2000 return hasOneOfEtags(reqETags, false);
2001}
2002
2003bool
2004StoreEntry::hasIfNoneMatchEtag(const HttpRequest &request) const
2005{
789217a2 2006 const String reqETags = request.header.getList(Http::HdrType::IF_NONE_MATCH);
79c8035e 2007 // weak comparison is allowed only for HEAD or full-body GET requests
450fe1cb 2008 const bool allowWeakMatch = !request.flags.isRanged &&
c2a7cefd 2009 (request.method == Http::METHOD_GET || request.method == Http::METHOD_HEAD);
79c8035e
AR
2010 return hasOneOfEtags(reqETags, allowWeakMatch);
2011}
2012
2013/// whether at least one of the request ETags matches entity ETag
2014bool
2015StoreEntry::hasOneOfEtags(const String &reqETags, const bool allowWeakMatch) const
2016{
789217a2 2017 const ETag repETag = getReply()->header.getETag(Http::HdrType::ETAG);
79c8035e
AR
2018 if (!repETag.str)
2019 return strListIsMember(&reqETags, "*", ',');
2020
2021 bool matched = false;
2022 const char *pos = NULL;
2023 const char *item;
2024 int ilen;
2025 while (!matched && strListGetItem(&reqETags, ',', &item, &ilen, &pos)) {
2026 if (!strncmp(item, "*", ilen))
2027 matched = true;
2028 else {
2029 String str;
2030 str.append(item, ilen);
2031 ETag reqETag;
2032 if (etagParseInit(&reqETag, str.termedBuf())) {
2033 matched = allowWeakMatch ? etagIsWeakEqual(repETag, reqETag) :
b59e6847 2034 etagIsStrongEqual(repETag, reqETag);
79c8035e
AR
2035 }
2036 }
2037 }
2038 return matched;
2039}
2040
2745fea5
AR
2041Store::Disk &
2042StoreEntry::disk() const
c8f4eac4 2043{
2044 assert(0 <= swap_dirn && swap_dirn < Config.cacheSwap.n_configured);
2745fea5
AR
2045 const RefCount<Store::Disk> &sd = INDEXSD(swap_dirn);
2046 assert(sd);
2047 return *sd;
c8f4eac4 2048}
0655fa4d 2049
aa18a4ca 2050/*
2051 * return true if the entry is in a state where
2052 * it can accept more data (ie with write() method)
2053 */
2054bool
2055StoreEntry::isAccepting() const
2056{
2057 if (STORE_PENDING != store_status)
2058 return false;
2059
2060 if (EBIT_TEST(flags, ENTRY_ABORTED))
2061 return false;
2062
2063 return true;
2064}
2065
2c4cd1ad
AR
2066std::ostream &operator <<(std::ostream &os, const StoreEntry &e)
2067{
c0280457
AR
2068 os << "e:";
2069
99921d9d
AR
2070 if (e.mem_obj) {
2071 if (e.mem_obj->xitTable.index > -1)
2072 os << 't' << e.mem_obj->xitTable.index;
2073 if (e.mem_obj->memCache.index > -1)
2074 os << 'm' << e.mem_obj->memCache.index;
2075 }
c0280457 2076 if (e.swap_filen > -1 || e.swap_dirn > -1)
99921d9d 2077 os << 'd' << e.swap_filen << '@' << e.swap_dirn;
4475555f
AR
2078
2079 os << '=';
c0280457
AR
2080
2081 // print only non-default status values, using unique letters
2082 if (e.mem_status != NOT_IN_MEMORY ||
9d4e9cfb
AR
2083 e.store_status != STORE_PENDING ||
2084 e.swap_status != SWAPOUT_NONE ||
2085 e.ping_status != PING_NONE) {
c0280457
AR
2086 if (e.mem_status != NOT_IN_MEMORY) os << 'm';
2087 if (e.store_status != STORE_PENDING) os << 's';
2088 if (e.swap_status != SWAPOUT_NONE) os << 'w' << e.swap_status;
2089 if (e.ping_status != PING_NONE) os << 'p' << e.ping_status;
c0280457
AR
2090 }
2091
2092 // print only set flags, using unique letters
2093 if (e.flags) {
2094 if (EBIT_TEST(e.flags, ENTRY_SPECIAL)) os << 'S';
2095 if (EBIT_TEST(e.flags, ENTRY_REVALIDATE)) os << 'R';
99921d9d 2096 if (EBIT_TEST(e.flags, DELAY_SENDING)) os << 'P';
c0280457
AR
2097 if (EBIT_TEST(e.flags, RELEASE_REQUEST)) os << 'X';
2098 if (EBIT_TEST(e.flags, REFRESH_REQUEST)) os << 'F';
c0280457
AR
2099 if (EBIT_TEST(e.flags, ENTRY_DISPATCHED)) os << 'D';
2100 if (EBIT_TEST(e.flags, KEY_PRIVATE)) os << 'I';
2101 if (EBIT_TEST(e.flags, ENTRY_FWD_HDR_WAIT)) os << 'W';
2102 if (EBIT_TEST(e.flags, ENTRY_NEGCACHED)) os << 'N';
2103 if (EBIT_TEST(e.flags, ENTRY_VALIDATED)) os << 'V';
2104 if (EBIT_TEST(e.flags, ENTRY_BAD_LENGTH)) os << 'L';
2105 if (EBIT_TEST(e.flags, ENTRY_ABORTED)) os << 'A';
c0280457
AR
2106 }
2107
4475555f
AR
2108 if (e.mem_obj && e.mem_obj->smpCollapsed)
2109 os << 'O';
2110
1bfe9ade 2111 return os << '/' << &e << '*' << e.locks();
2c4cd1ad
AR
2112}
2113
e6ccf245 2114/* NullStoreEntry */
2115
2116NullStoreEntry NullStoreEntry::_instance;
2117
2118NullStoreEntry *
2119NullStoreEntry::getInstance()
2120{
2121 return &_instance;
2122}
332dafa2 2123
2124char const *
2125NullStoreEntry::getMD5Text() const
2126{
2127 return "N/A";
2128}
528b2c61 2129
43ae1d95 2130void
2131NullStoreEntry::operator delete(void*)
2132{
2133 fatal ("Attempt to delete NullStoreEntry\n");
2134}
2135
528b2c61 2136char const *
2137NullStoreEntry::getSerialisedMetaData()
2138{
2139 return NULL;
2140}
7d84d4ca 2141