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