sql_cache.cc 107 KB
Newer Older
1
/* Copyright (C) 2000 MySQL AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
unknown's avatar
unknown committed
7

unknown's avatar
unknown committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
unknown's avatar
unknown committed
12

unknown's avatar
unknown committed
13 14 15 16
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

unknown's avatar
unknown committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
/*
  Description of the query cache:

1. Query_cache object consists of
	- query cache memory pool (cache)
	- queries hash (queries)
	- tables hash (tables)
	- list of blocks ordered as they allocated in memory
(first_block)
	- list of queries block (queries_blocks)
	- list of used tables (tables_blocks)

2. Query cache memory pool (cache) consists of
	- table of steps of memory bins allocation
	- table of free memory bins
	- blocks of memory

3. Memory blocks

Every memory block has the following structure:

+----------------------------------------------------------+
|      Block header (Query_cache_block structure)	   |
+----------------------------------------------------------+
|Table of database table lists (used for queries & tables) |
+----------------------------------------------------------+
|		  Type depended header			   |
|(Query_cache_query, Query_cache_table, Query_cache_result)|
+----------------------------------------------------------+
|			Data ...			   |
+----------------------------------------------------------+

Block header consists of:
- type:
  FREE		Free memory block
  QUERY		Query block
  RESULT	Ready to send result
  RES_CONT	Result's continuation
  RES_BEG	First block of results, that is not yet complete,
		written to cache
  RES_INCOMPLETE  Allocated for results data block
  TABLE		Block with database table description
  INCOMPLETE	The destroyed block
- length of block (length)
- length of data & headers (used)
- physical list links (pnext/pprev) - used for the list of
  blocks ordered as they are allocated in physical memory
- logical list links (next/prev) - used for queries block list, tables block
  list, free memory block lists and list of results block in query
- number of elements in table of database table list (n_tables)

4. Query & results blocks

Query stored in cache consists of following blocks:

more		      more
recent+-------------+ old
<-----|Query block 1|------> double linked list of queries block
 prev |		    | next
      +-------------+
    <-|  table 0    |-> (see "Table of database table lists" description)
    <-|  table 1    |->
      |  ...	    |		+--------------------------+
      +-------------+	 +-------------------------+	   |
NET   |		    |	 |	V		   V	   |
struct|		    |	 +-+------------+   +------------+ |
<-----|query header |----->|Result block|-->|Result block|-+ doublelinked
writer|		    |result|		|<--|		 |   list of results
      +-------------+	   +------------+   +------------+
      |charset	    |	   +------------+   +------------+ no table of dbtables
      |encoding +   |	   |   result	|   |	result	 |
      |query text   |<-----|   header	|   |	header	 |------+
      +-------------+parent|		|   |		 |parent|
	    ^		   +------------+   +------------+	|
	    |		   |result data |   |result data |	|
	    |		   +------------+   +------------+	|
	    +---------------------------------------------------+

First query is registered. During the registration query block is
allocated. This query block is included in query hash and is linked
with appropriate database tables lists (if there is no appropriate
list exists it will be created).

Later when query has performed results is written into the result blocks.
A result block cannot be smaller then QUERY_CACHE_MIN_RESULT_DATA_SIZE.

When new result is written to cache it is appended to the last result
block, if no more  free space left in the last block, new block is
allocated.

5. Table of database table lists.

For quick invalidation of queries all query are linked in lists on used
database tables basis (when table will be changed (insert/delete/...)
this queries will be removed from cache).

Root of such list is table block:

     +------------+	  list of used tables (used while invalidation of
<----|	Table	  |-----> whole database)
 prev|	block	  |next			     +-----------+
     |		  |	  +-----------+      |Query block|
     |		  |	  |Query block|      +-----------+
     +------------+	  +-----------+      | ...	 |
  +->| table 0	  |------>|table 0    |----->| table N	 |---+
  |+-|		  |<------|	      |<-----|		 |<-+|
  || +------------+	  | ...       |      | ...	 |  ||
  || |table header|	  +-----------+      +-----------+  ||
  || +------------+	  | ...       |      | ...	 |  ||
  || |db name +   |	  +-----------+      +-----------+  ||
  || |table name  |					    ||
  || +------------+					    ||
  |+--------------------------------------------------------+|
  +----------------------------------------------------------+

Table block is included into the tables hash (tables).

6. Free blocks, free blocks bins & steps of freeblock bins.

When we just started only one free memory block  existed. All query
cache memory (that will be used for block allocation) were
containing in this block.
When a new block is allocated we find most suitable memory block
(minimal of >= required size). If such a block can not be found, we try
to find max block < required size (if we allocate block for results).
If there is no free memory, oldest query is removed from cache, and then
we try to allocate memory. Last step should be repeated until we find
suitable block or until there is no unlocked query found.

If the block is found and its length more then we need, it should be
split into 2 blocks.
New blocks cannot be smaller then min_allocation_unit_bytes.

When a block becomes free, its neighbor-blocks should be tested and if
there are free blocks among them, they should be joined into one block.

Free memory blocks are stored in bins according to their sizes.
The bins are stored in size-descending order.
These bins are distributed (by size) approximately logarithmically.

First bin (number 0) stores free blocks with
size <= query_cache_size>>QUERY_CACHE_MEM_BIN_FIRST_STEP_PWR2.
It is first (number 0) step.
On the next step distributed (1 + QUERY_CACHE_MEM_BIN_PARTS_INC) *
QUERY_CACHE_MEM_BIN_PARTS_MUL bins. This bins allocated in interval from
query_cache_size>>QUERY_CACHE_MEM_BIN_FIRST_STEP_PWR2 to
query_cache_size>>QUERY_CACHE_MEM_BIN_FIRST_STEP_PWR2 >>
QUERY_CACHE_MEM_BIN_STEP_PWR2
...
On each step interval decreases in 2 power of
QUERY_CACHE_MEM_BIN_STEP_PWR2
times, number of bins (that distributed on this step) increases. If on
the previous step there were N bins distributed , on the current there
would be distributed
(N + QUERY_CACHE_MEM_BIN_PARTS_INC) * QUERY_CACHE_MEM_BIN_PARTS_MUL
bins.
Last distributed bin stores blocks with size near min_allocation_unit
bytes.

For example:
	query_cache_size>>QUERY_CACHE_MEM_BIN_FIRST_STEP_PWR2 = 100,
	min_allocation_unit = 17,
	QUERY_CACHE_MEM_BIN_STEP_PWR2 = 1,
	QUERY_CACHE_MEM_BIN_PARTS_INC = 1,
	QUERY_CACHE_MEM_BIN_PARTS_MUL = 1
	(in followed picture showed right (low) bound of bin):

      |       100>>1	 50>>1	      |25>>1|
      |		 |	   |	      |  |  |
      | 100  75 50  41 33 25  21 18 15| 12  | -  bins right (low) bounds

      |\---/\-----/\--------/\--------|---/ |
      |  0     1	2	   3  |     | - steps
       \-----------------------------/ \---/
	bins that we store in cache	this bin showed for example only


Calculation of steps/bins distribution is performed only when query cache
is resized.

When we need to find appropriate bin, first we should find appropriate
step, then we should calculate number of bins that are using data
stored in Query_cache_memory_bin_step structure.

Free memory blocks are sorted in bins in lists with size-ascending order
(more small blocks needed frequently then bigger one).
unknown's avatar
unknown committed
203

unknown's avatar
unknown committed
204
7. Packing cache.
unknown's avatar
unknown committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

Query cache packing is divided into two operation:
	- pack_cache
	- join_results

pack_cache moved all blocks to "top" of cache and create one block of free
space at the "bottom":

 before pack_cache    after pack_cache
 +-------------+      +-------------+
 | query 1     |      | query 1     |
 +-------------+      +-------------+
 | table 1     |      | table 1     |
 +-------------+      +-------------+
 | results 1.1 |      | results 1.1 |
 +-------------+      +-------------+
 | free        |      | query 2     |
 +-------------+      +-------------+
 | query 2     |      | table 2     |
 +-------------+ ---> +-------------+
 | table 2     |      | results 1.2 |
 +-------------+      +-------------+
 | results 1.2 |      | results 2   |
 +-------------+      +-------------+
 | free        |      | free        |
 +-------------+      |             |
 | results 2   |      |             |
 +-------------+      |             |
 | free        |      |             |
 +-------------+      +-------------+

pack_cache scan blocks in physical address order and move every non-free
block "higher".

pack_cach remove every free block it finds. The length of the deleted block
is accumulated to the "gap". All non free blocks should be shifted with the
"gap" step.

join_results scans all complete queries. If the results of query are not
stored in the same block, join_results tries to move results so, that they
are stored in one block.

 before join_results  after join_results
 +-------------+      +-------------+
 | query 1     |      | query 1     |
 +-------------+      +-------------+
 | table 1     |      | table 1     |
 +-------------+      +-------------+
 | results 1.1 |      | free        |
 +-------------+      +-------------+
 | query 2     |      | query 2     |
 +-------------+      +-------------+
 | table 2     |      | table 2     |
 +-------------+ ---> +-------------+
 | results 1.2 |      | free        |
 +-------------+      +-------------+
 | results 2   |      | results 2   |
 +-------------+      +-------------+
 | free        |      | results 1   |
 |             |      |             |
 |             |      +-------------+
 |             |      | free        |
 |             |      |             |
 +-------------+      +-------------+

If join_results allocated new block(s) then we need call pack_cache again.
unknown's avatar
unknown committed
271 272 273 274 275 276 277 278 279 280

TODO list:

  - Delayed till after-parsing qache answer (for column rights processing)
  - Optimize cache resizing
      - if new_size < old_size then pack & shrink
      - if new_size > old_size copy cached query to new cache
  - Move MRG_MYISAM table type processing to handlers, something like:
        tables_used->table->file->register_used_filenames(callback,
                                                          first_argument);
unknown's avatar
unknown committed
281 282 283 284 285 286 287 288 289 290 291
  - Make derived tables cachable.
  - QC improvement suggested by Monty:
    - Add a counter in open_table() for how many MERGE (ISAM or MyISAM)
      tables are cached in the table cache.
      (This will be trivial when we have the new table cache in place I
      have been working on)
    - After this we can add the following test around the for loop in
      is_cacheable::

      if (thd->temp_tables || global_merge_table_count)

292
    - Another option would be to set thd->lex.safe_to_cache_query to 0
unknown's avatar
unknown committed
293 294 295
      in 'get_lock_data' if any of the tables was a tmp table or a
      MRG_ISAM table.
      (This could be done with almost no speed penalty)
unknown's avatar
unknown committed
296 297
*/

unknown's avatar
unknown committed
298
#include "mysql_priv.h"
unknown's avatar
unknown committed
299
#ifdef HAVE_QUERY_CACHE
unknown's avatar
unknown committed
300 301 302
#include <m_ctype.h>
#include <my_dir.h>
#include <hash.h>
unknown's avatar
unknown committed
303 304 305 306 307 308 309 310
#include "sql_acl.h"
#include "ha_myisammrg.h"
#ifndef MASTER
#include "../srclib/myisammrg/myrg_def.h"
#else
#include "../myisammrg/myrg_def.h"
#endif

unknown's avatar
unknown committed
311 312
#if defined(EXTRA_DEBUG) && !defined(DBUG_OFF)
#define MUTEX_LOCK(M) { DBUG_PRINT("lock", ("mutex lock 0x%lx", (ulong)(M))); \
unknown's avatar
unknown committed
313
  pthread_mutex_lock(M);}
unknown's avatar
unknown committed
314
#define MUTEX_UNLOCK(M) {DBUG_PRINT("lock", ("mutex unlock 0x%lx",\
unknown's avatar
unknown committed
315
  (ulong)(M))); pthread_mutex_unlock(M);}
unknown's avatar
unknown committed
316 317 318 319 320 321
#define RW_WLOCK(M) {DBUG_PRINT("lock", ("rwlock wlock 0x%lx",(ulong)(M))); \
  if (!rw_wrlock(M)) DBUG_PRINT("lock", ("rwlock wlock ok")) \
  else DBUG_PRINT("lock", ("rwlock wlock FAILED %d", errno)); }
#define RW_RLOCK(M) {DBUG_PRINT("lock", ("rwlock rlock 0x%lx", (ulong)(M))); \
  if (!rw_rdlock(M)) DBUG_PRINT("lock", ("rwlock rlock ok")) \
  else DBUG_PRINT("lock", ("rwlock wlock FAILED %d", errno)); }
unknown's avatar
unknown committed
322
#define RW_UNLOCK(M) {DBUG_PRINT("lock", ("rwlock unlock 0x%lx",(ulong)(M))); \
unknown's avatar
unknown committed
323 324
  if (!rw_unlock(M)) DBUG_PRINT("lock", ("rwlock unlock ok")) \
  else DBUG_PRINT("lock", ("rwlock unlock FAILED %d", errno)); }
unknown's avatar
unknown committed
325 326
#define STRUCT_LOCK(M) {DBUG_PRINT("lock", ("%d struct lock...",__LINE__)); \
  pthread_mutex_lock(M);DBUG_PRINT("lock", ("struct lock OK"));}
unknown's avatar
unknown committed
327
#define STRUCT_UNLOCK(M) { \
unknown's avatar
unknown committed
328 329 330
  DBUG_PRINT("lock", ("%d struct unlock...",__LINE__)); \
  pthread_mutex_unlock(M);DBUG_PRINT("lock", ("struct unlock OK"));}
#define BLOCK_LOCK_WR(B) {DBUG_PRINT("lock", ("%d LOCK_WR 0x%lx",\
unknown's avatar
unknown committed
331 332
  __LINE__,(ulong)(B))); \
  B->query()->lock_writing();}
unknown's avatar
unknown committed
333
#define BLOCK_LOCK_RD(B) {DBUG_PRINT("lock", ("%d LOCK_RD 0x%lx",\
unknown's avatar
unknown committed
334 335 336
  __LINE__,(ulong)(B))); \
  B->query()->lock_reading();}
#define BLOCK_UNLOCK_WR(B) { \
unknown's avatar
unknown committed
337
  DBUG_PRINT("lock", ("%d UNLOCK_WR 0x%lx",\
unknown's avatar
unknown committed
338 339
  __LINE__,(ulong)(B)));B->query()->unlock_writing();}
#define BLOCK_UNLOCK_RD(B) { \
unknown's avatar
unknown committed
340
  DBUG_PRINT("lock", ("%d UNLOCK_RD 0x%lx",\
unknown's avatar
unknown committed
341
  __LINE__,(ulong)(B)));B->query()->unlock_reading();}
unknown's avatar
unknown committed
342 343
#define DUMP(C) DBUG_EXECUTE("qcache", {\
  (C)->cache_dump(); (C)->queries_dump();(C)->tables_dump();})
unknown's avatar
unknown committed
344 345 346
#else
#define MUTEX_LOCK(M) pthread_mutex_lock(M)
#define MUTEX_UNLOCK(M) pthread_mutex_unlock(M)
unknown's avatar
unknown committed
347 348 349
#define RW_WLOCK(M) rw_wrlock(M)
#define RW_RLOCK(M) rw_rdlock(M)
#define RW_UNLOCK(M) rw_unlock(M)
unknown's avatar
unknown committed
350 351 352 353 354 355 356 357 358
#define STRUCT_LOCK(M) pthread_mutex_lock(M)
#define STRUCT_UNLOCK(M) pthread_mutex_unlock(M)
#define BLOCK_LOCK_WR(B) B->query()->lock_writing()
#define BLOCK_LOCK_RD(B) B->query()->lock_reading()
#define BLOCK_UNLOCK_WR(B) B->query()->unlock_writing()
#define BLOCK_UNLOCK_RD(B) B->query()->unlock_reading()
#define DUMP(C)
#endif

unknown's avatar
unknown committed
359 360 361 362 363 364
const char *query_cache_type_names[]= { "OFF", "ON", "DEMAND",NullS };
TYPELIB query_cache_type_typelib=
{
  array_elements(query_cache_type_names)-1,"", query_cache_type_names
};

unknown's avatar
unknown committed
365
/*****************************************************************************
unknown's avatar
unknown committed
366 367
 Query_cache_block_table method(s)
*****************************************************************************/
unknown's avatar
unknown committed
368 369 370

inline Query_cache_block * Query_cache_block_table::block()
{
unknown's avatar
unknown committed
371
  return (Query_cache_block *)(((byte*)this) -
unknown's avatar
unknown committed
372
			       ALIGN_SIZE(sizeof(Query_cache_block_table)*n) -
unknown's avatar
unknown committed
373
			       ALIGN_SIZE(sizeof(Query_cache_block)));
unknown's avatar
unknown committed
374 375 376
};

/*****************************************************************************
unknown's avatar
unknown committed
377 378
   Query_cache_block method(s)
*****************************************************************************/
unknown's avatar
unknown committed
379 380 381 382

void Query_cache_block::init(ulong block_length)
{
  DBUG_ENTER("Query_cache_block::init");
383 384
  DBUG_PRINT("qcache", ("init block 0x%lx  length: %lu", (ulong) this,
			block_length));
unknown's avatar
unknown committed
385 386 387 388 389 390 391 392 393 394
  length = block_length;
  used = 0;
  type = Query_cache_block::FREE;
  n_tables = 0;
  DBUG_VOID_RETURN;
}

void Query_cache_block::destroy()
{
  DBUG_ENTER("Query_cache_block::destroy");
unknown's avatar
unknown committed
395 396
  DBUG_PRINT("qcache", ("destroy block 0x%lx, type %d",
			(ulong) this, type));
unknown's avatar
unknown committed
397 398 399 400 401 402
  type = INCOMPLETE;
  DBUG_VOID_RETURN;
}

inline uint Query_cache_block::headers_len()
{
unknown's avatar
unknown committed
403
  return (ALIGN_SIZE(sizeof(Query_cache_block_table)*n_tables) +
unknown's avatar
unknown committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
	  ALIGN_SIZE(sizeof(Query_cache_block)));
}

inline gptr Query_cache_block::data(void)
{
  return (gptr)( ((byte*)this) + headers_len() );
}

inline Query_cache_query * Query_cache_block::query()
{
#ifndef DBUG_OFF
  if (type != QUERY)
    query_cache.wreck(__LINE__, "incorrect block type");
#endif
  return (Query_cache_query *) data();
}

inline Query_cache_table * Query_cache_block::table()
{
#ifndef DBUG_OFF
  if (type != TABLE)
    query_cache.wreck(__LINE__, "incorrect block type");
#endif
  return (Query_cache_table *) data();
}

inline Query_cache_result * Query_cache_block::result()
{
#ifndef DBUG_OFF
  if (type != RESULT && type != RES_CONT && type != RES_BEG &&
      type != RES_INCOMPLETE)
    query_cache.wreck(__LINE__, "incorrect block type");
#endif
  return (Query_cache_result *) data();
}

inline Query_cache_block_table * Query_cache_block::table(TABLE_COUNTER_TYPE n)
{
  return ((Query_cache_block_table *)
	  (((byte*)this)+ALIGN_SIZE(sizeof(Query_cache_block)) +
unknown's avatar
unknown committed
444
	   n*sizeof(Query_cache_block_table)));
unknown's avatar
unknown committed
445 446 447 448 449 450 451
}


/*****************************************************************************
 *   Query_cache_table method(s)
 *****************************************************************************/

unknown's avatar
unknown committed
452 453 454 455
extern "C"
{
byte *query_cache_table_get_key(const byte *record, uint *length,
				my_bool not_used __attribute__((unused)))
unknown's avatar
unknown committed
456 457 458 459 460 461 462 463 464 465
{
  Query_cache_block* table_block = (Query_cache_block*) record;
  *length = (table_block->used - table_block->headers_len() -
	     ALIGN_SIZE(sizeof(Query_cache_table)));
  return (((byte *) table_block->data()) +
	  ALIGN_SIZE(sizeof(Query_cache_table)));
}
}

/*****************************************************************************
unknown's avatar
unknown committed
466 467
    Query_cache_query methods
*****************************************************************************/
unknown's avatar
unknown committed
468 469

/*
unknown's avatar
unknown committed
470
   Following methods work for block read/write locking only in this
unknown's avatar
unknown committed
471 472
   particular case and in interaction with structure_guard_mutex.

unknown's avatar
unknown committed
473
   Lock for write prevents any other locking. (exclusive use)
unknown's avatar
unknown committed
474 475 476
   Lock for read prevents only locking for write.
*/

unknown's avatar
unknown committed
477
inline void Query_cache_query::lock_writing()
unknown's avatar
unknown committed
478
{
unknown's avatar
unknown committed
479
  RW_WLOCK(&lock);
unknown's avatar
unknown committed
480 481 482 483 484
}


/*
  Needed for finding queries, that we may delete from cache.
unknown's avatar
unknown committed
485 486 487
  We don't want to wait while block become unlocked. In addition,
  block locking means that query is now used and we don't need to
  remove it.
unknown's avatar
unknown committed
488 489 490 491 492
*/

my_bool Query_cache_query::try_lock_writing()
{
  DBUG_ENTER("Query_cache_block::try_lock_writing");
unknown's avatar
unknown committed
493
  if (rw_trywrlock(&lock)!=0)
unknown's avatar
unknown committed
494
  {
unknown's avatar
unknown committed
495
    DBUG_PRINT("info", ("can't lock rwlock"));
unknown's avatar
unknown committed
496 497
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
498
  DBUG_PRINT("info", ("rwlock 0x%lx locked", (ulong) &lock));
unknown's avatar
unknown committed
499 500 501 502
  DBUG_RETURN(1);
}


unknown's avatar
unknown committed
503
inline void Query_cache_query::lock_reading()
unknown's avatar
unknown committed
504
{
unknown's avatar
unknown committed
505
  RW_RLOCK(&lock);
unknown's avatar
unknown committed
506 507 508
}


unknown's avatar
unknown committed
509
inline void Query_cache_query::unlock_writing()
unknown's avatar
unknown committed
510
{
unknown's avatar
unknown committed
511
  RW_UNLOCK(&lock);
unknown's avatar
unknown committed
512 513 514
}


unknown's avatar
unknown committed
515
inline void Query_cache_query::unlock_reading()
unknown's avatar
unknown committed
516
{
unknown's avatar
unknown committed
517
  RW_UNLOCK(&lock);
unknown's avatar
unknown committed
518 519
}

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547

void Query_cache_query::init_n_lock()
{
  DBUG_ENTER("Query_cache_query::init_n_lock");
  res=0; wri = 0; len = 0;
  my_rwlock_init(&lock, NULL);
  lock_writing();
  DBUG_PRINT("qcache", ("inited & locked query for block 0x%lx",
			((byte*) this)-ALIGN_SIZE(sizeof(Query_cache_block))));
  DBUG_VOID_RETURN;
}


void Query_cache_query::unlock_n_destroy()
{
  DBUG_ENTER("Query_cache_query::unlock_n_destroy");
  DBUG_PRINT("qcache", ("destroyed & unlocked query for block 0x%lx",
			((byte*)this)-ALIGN_SIZE(sizeof(Query_cache_block))));
  /*
    The following call is not needed on system where one can destroy an
    active semaphore
  */
  this->unlock_writing();
  rwlock_destroy(&lock);
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
548 549 550 551
extern "C"
{
byte *query_cache_query_get_key(const byte *record, uint *length,
				my_bool not_used)
unknown's avatar
unknown committed
552
{
unknown's avatar
unknown committed
553
  Query_cache_block *query_block = (Query_cache_block*) record;
unknown's avatar
unknown committed
554 555
  *length = (query_block->used - query_block->headers_len() -
	     ALIGN_SIZE(sizeof(Query_cache_query)));
unknown's avatar
unknown committed
556
  return (((byte *) query_block->data()) +
unknown's avatar
unknown committed
557 558 559 560 561
	  ALIGN_SIZE(sizeof(Query_cache_query)));
}
}

/*****************************************************************************
562
  Functions to store things into the query cache
unknown's avatar
unknown committed
563
*****************************************************************************/
unknown's avatar
unknown committed
564

565 566 567 568 569
/*
  Insert the packet into the query cache.
  This should only be called if net->query_cache_query != 0
*/

unknown's avatar
unknown committed
570 571 572 573 574
void query_cache_insert(NET *net, const char *packet, ulong length)
{
  DBUG_ENTER("query_cache_insert");

#ifndef DBUG_OFF
unknown's avatar
unknown committed
575
  // Check if we have called query_cache.wreck() (which disables the cache)
unknown's avatar
unknown committed
576 577 578 579
  if (query_cache.query_cache_size == 0)
    DBUG_VOID_RETURN;
#endif

580 581 582 583
  STRUCT_LOCK(&query_cache.structure_guard_mutex);
  Query_cache_block *query_block = ((Query_cache_block*)
				    net->query_cache_query);
  if (query_block)
unknown's avatar
unknown committed
584
  {
585 586
    Query_cache_query *header = query_block->query();
    Query_cache_block *result = header->result();
unknown's avatar
unknown committed
587

588 589 590
    DUMP(&query_cache);
    BLOCK_LOCK_WR(query_block);
    DBUG_PRINT("qcache", ("insert packet %lu bytes long",length));
unknown's avatar
unknown committed
591

592 593 594 595 596 597 598 599 600 601
    /*
      On success STRUCT_UNLOCK(&query_cache.structure_guard_mutex) will be
      done by query_cache.append_result_data if success (if not we need
      query_cache.structure_guard_mutex locked to free query)
    */
    if (!query_cache.append_result_data(&result, length, (gptr) packet,
					query_block))
    {
      query_cache.refused++;
      DBUG_PRINT("warning", ("Can't append data"));
unknown's avatar
unknown committed
602
      header->result(result);
603 604 605 606
      DBUG_PRINT("qcache", ("free query 0x%lx", (ulong) query_block));
      // The following call will remove the lock on query_block
      query_cache.free_query(query_block);
      // append_result_data no success => we need unlock
unknown's avatar
unknown committed
607
      STRUCT_UNLOCK(&query_cache.structure_guard_mutex);
608 609 610 611
      DBUG_VOID_RETURN;
    }
    header->result(result);
    BLOCK_UNLOCK_WR(query_block);
unknown's avatar
unknown committed
612
  }
613 614
  else
    STRUCT_UNLOCK(&query_cache.structure_guard_mutex);
615
  DBUG_EXECUTE("check_querycache",query_cache.check_integrity(0););
unknown's avatar
unknown committed
616 617 618
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
619

unknown's avatar
unknown committed
620 621 622 623 624
void query_cache_abort(NET *net)
{
  DBUG_ENTER("query_cache_abort");

#ifndef DBUG_OFF
unknown's avatar
unknown committed
625
  // Check if we have called query_cache.wreck() (which disables the cache)
unknown's avatar
unknown committed
626 627 628
  if (query_cache.query_cache_size == 0)
    DBUG_VOID_RETURN;
#endif
unknown's avatar
unknown committed
629
  if (net->query_cache_query != 0)	// Quick check on unlocked structure
unknown's avatar
unknown committed
630 631
  {
    STRUCT_LOCK(&query_cache.structure_guard_mutex);
unknown's avatar
unknown committed
632
    Query_cache_block *query_block = ((Query_cache_block*)
unknown's avatar
unknown committed
633
				       net->query_cache_query);
unknown's avatar
unknown committed
634
    if (query_block)			// Test if changed by other thread
unknown's avatar
unknown committed
635
    {
unknown's avatar
unknown committed
636
      DUMP(&query_cache);
unknown's avatar
unknown committed
637
      BLOCK_LOCK_WR(query_block);
unknown's avatar
unknown committed
638
      // The following call will remove the lock on query_block
unknown's avatar
unknown committed
639 640
      query_cache.free_query(query_block);
    }
641
    net->query_cache_query=0;
unknown's avatar
unknown committed
642
    DBUG_EXECUTE("check_querycache",query_cache.check_integrity(1););
unknown's avatar
unknown committed
643 644 645 646 647
    STRUCT_UNLOCK(&query_cache.structure_guard_mutex);
  }
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
648 649

void query_cache_end_of_result(NET *net)
unknown's avatar
unknown committed
650 651 652 653
{
  DBUG_ENTER("query_cache_end_of_result");

#ifndef DBUG_OFF
unknown's avatar
unknown committed
654
  // Check if we have called query_cache.wreck() (which disables the cache)
unknown's avatar
unknown committed
655 656 657
  if (query_cache.query_cache_size == 0) DBUG_VOID_RETURN;
#endif

unknown's avatar
unknown committed
658
  if (net->query_cache_query != 0)	// Quick check on unlocked structure
unknown's avatar
unknown committed
659 660
  {
    STRUCT_LOCK(&query_cache.structure_guard_mutex);
unknown's avatar
unknown committed
661 662 663
    Query_cache_block *query_block = ((Query_cache_block*)
				      net->query_cache_query);
    if (query_block)
unknown's avatar
unknown committed
664
    {
unknown's avatar
unknown committed
665
      DUMP(&query_cache);
unknown's avatar
unknown committed
666
      BLOCK_LOCK_WR(query_block);
667 668 669 670 671 672
      Query_cache_query *header = query_block->query();
      Query_cache_block *last_result_block = header->result()->prev;
      ulong allign_size = ALIGN_SIZE(last_result_block->used);
      ulong len = max(query_cache.min_allocation_unit, allign_size);
      if (last_result_block->length >= query_cache.min_allocation_unit + len)
	query_cache.split_block(last_result_block,len);
unknown's avatar
unknown committed
673 674 675
      STRUCT_UNLOCK(&query_cache.structure_guard_mutex);

#ifndef DBUG_OFF
unknown's avatar
unknown committed
676
      if (header->result() == 0)
unknown's avatar
unknown committed
677 678 679 680 681 682 683
      {
	DBUG_PRINT("error", ("end of data whith no result. query '%s'",
			     header->query()));
	query_cache.wreck(__LINE__, "");
	DBUG_VOID_RETURN;
      }
#endif
unknown's avatar
unknown committed
684 685
      header->found_rows(current_thd->limit_found_rows);
      header->result()->type = Query_cache_block::RESULT;
unknown's avatar
unknown committed
686 687 688 689 690
      header->writer(0);
      BLOCK_UNLOCK_WR(query_block);
    }
    else
    {
unknown's avatar
unknown committed
691
      // Cache was flushed or resized and query was deleted => do nothing
unknown's avatar
unknown committed
692 693 694
      STRUCT_UNLOCK(&query_cache.structure_guard_mutex);
    }
    net->query_cache_query=0;
695
    DBUG_EXECUTE("check_querycache",query_cache.check_integrity(0););
unknown's avatar
unknown committed
696 697 698 699
  }
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
700
void query_cache_invalidate_by_MyISAM_filename(const char *filename)
unknown's avatar
unknown committed
701 702
{
  query_cache.invalidate_by_MyISAM_filename(filename);
703
  DBUG_EXECUTE("check_querycache",query_cache.check_integrity(0););
unknown's avatar
unknown committed
704 705 706 707
}


/*****************************************************************************
unknown's avatar
unknown committed
708 709
   Query_cache methods
*****************************************************************************/
unknown's avatar
unknown committed
710

711 712 713 714 715
Query_cache::Query_cache(ulong query_cache_limit_arg,
			 ulong min_allocation_unit_arg,
			 ulong min_result_data_size_arg,
			 uint def_query_hash_size_arg,
			 uint def_table_hash_size_arg)
unknown's avatar
unknown committed
716
  :query_cache_size(0),
717
   query_cache_limit(query_cache_limit_arg),
unknown's avatar
unknown committed
718
   queries_in_cache(0), hits(0), inserts(0), refused(0),
719
   total_blocks(0), lowmem_prunes(0),
720 721 722 723
   min_allocation_unit(ALIGN_SIZE(min_allocation_unit_arg)),
   min_result_data_size(ALIGN_SIZE(min_result_data_size_arg)),
   def_query_hash_size(ALIGN_SIZE(def_query_hash_size_arg)),
   def_table_hash_size(ALIGN_SIZE(def_table_hash_size_arg)),
unknown's avatar
unknown committed
724 725
   initialized(0)
{
unknown's avatar
unknown committed
726 727 728
  ulong min_needed= (ALIGN_SIZE(sizeof(Query_cache_block)) +
		     ALIGN_SIZE(sizeof(Query_cache_block_table)) +
		     ALIGN_SIZE(sizeof(Query_cache_query)) + 3);
unknown's avatar
unknown committed
729
  set_if_bigger(min_allocation_unit,min_needed);
unknown's avatar
unknown committed
730
  this->min_allocation_unit= ALIGN_SIZE(min_allocation_unit);
unknown's avatar
unknown committed
731
  set_if_bigger(this->min_result_data_size,min_allocation_unit);
unknown's avatar
unknown committed
732 733
}

unknown's avatar
unknown committed
734

unknown's avatar
unknown committed
735
ulong Query_cache::resize(ulong query_cache_size_arg)
unknown's avatar
unknown committed
736 737
{
  DBUG_ENTER("Query_cache::resize");
unknown's avatar
unknown committed
738 739
  DBUG_PRINT("qcache", ("from %lu to %lu",query_cache_size,
			query_cache_size_arg));
unknown's avatar
unknown committed
740
  free_cache(0);
unknown's avatar
unknown committed
741
  query_cache_size= query_cache_size_arg;
unknown's avatar
unknown committed
742 743 744
  DBUG_RETURN(init_cache());
}

unknown's avatar
unknown committed
745

746 747 748 749 750 751 752 753
ulong Query_cache::set_min_res_unit(ulong size)
{
  if (size < min_allocation_unit)
    size= min_allocation_unit;
  return (min_result_data_size= ALIGN_SIZE(size));
}


unknown's avatar
unknown committed
754 755
void Query_cache::store_query(THD *thd, TABLE_LIST *tables_used)
{
756
  TABLE_COUNTER_TYPE local_tables;
757
  ulong tot_length;
unknown's avatar
unknown committed
758 759 760
  DBUG_ENTER("Query_cache::store_query");
  if (query_cache_size == 0)
    DBUG_VOID_RETURN;
unknown's avatar
unknown committed
761
  uint8 tables_type= 0;
unknown's avatar
unknown committed
762

763
  if ((local_tables = is_cacheable(thd, thd->query_length,
764 765
			     thd->query, &thd->lex, tables_used,
			     &tables_type)))
unknown's avatar
unknown committed
766
  {
767
    NET *net= &thd->net;
unknown's avatar
unknown committed
768
    byte flags = (thd->client_capabilities & CLIENT_LONG_FLAG ? 0x80 : 0);
unknown's avatar
unknown committed
769
    STRUCT_LOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
770

unknown's avatar
unknown committed
771 772 773 774
    if (query_cache_size == 0)
      DBUG_VOID_RETURN;
    DUMP(this);

775 776 777
    /* Key is query + database + flag */
    if (thd->db_length)
    {
778
      memcpy(thd->query+thd->query_length+1, thd->db, thd->db_length);
779 780 781 782 783 784 785
      DBUG_PRINT("qcache", ("database : %s length %u",
			    thd->db, thd->db_length)); 
    }
    else
    {
      DBUG_PRINT("qcache", ("No active database"));
    }
unknown's avatar
unknown committed
786
    /*
unknown's avatar
unknown committed
787 788 789
       Prepare flags:
       most significant bit - CLIENT_LONG_FLAG,
       other - charset number (0 no charset convertion)
unknown's avatar
unknown committed
790
    */
unknown's avatar
unknown committed
791 792
    flags|= (byte) thd->charset()->number;
    DBUG_ASSERT(thd->charset()->number < 128);
793
    tot_length=thd->query_length+thd->db_length+2;
794
    thd->query[tot_length-1] = (char) flags;
unknown's avatar
unknown committed
795

unknown's avatar
unknown committed
796
    /* Check if another thread is processing the same query? */
unknown's avatar
unknown committed
797
    Query_cache_block *competitor = (Query_cache_block *)
798
      hash_search(&queries, (byte*) thd->query, tot_length);
unknown's avatar
unknown committed
799
    DBUG_PRINT("qcache", ("competitor 0x%lx, flags %x", (ulong) competitor,
unknown's avatar
unknown committed
800 801 802
			flags));
    if (competitor == 0)
    {
unknown's avatar
unknown committed
803 804
      /* Query is not in cache and no one is working with it; Store it */
      Query_cache_block *query_block;
805
      query_block= write_block_data(tot_length, (gptr) thd->query,
unknown's avatar
unknown committed
806
				    ALIGN_SIZE(sizeof(Query_cache_query)),
807
				    Query_cache_block::QUERY, local_tables, 1);
unknown's avatar
unknown committed
808 809
      if (query_block != 0)
      {
unknown's avatar
unknown committed
810 811
	DBUG_PRINT("qcache", ("query block 0x%lx allocated, %lu",
			    (ulong) query_block, query_block->used));
unknown's avatar
unknown committed
812

unknown's avatar
unknown committed
813
	Query_cache_query *header = query_block->query();
unknown's avatar
unknown committed
814
	header->init_n_lock();
unknown's avatar
unknown committed
815
	if (hash_insert(&queries, (byte*) query_block))
unknown's avatar
unknown committed
816 817
	{
	  refused++;
unknown's avatar
unknown committed
818
	  DBUG_PRINT("qcache", ("insertion in query hash"));
unknown's avatar
unknown committed
819 820 821
	  header->unlock_n_destroy();
	  free_memory_block(query_block);
	  STRUCT_UNLOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
822
	  goto end;
unknown's avatar
unknown committed
823
	}
824
	if (!register_all_tables(query_block, tables_used, local_tables))
unknown's avatar
unknown committed
825 826
	{
	  refused++;
unknown's avatar
unknown committed
827
	  DBUG_PRINT("warning", ("tables list including failed"));
unknown's avatar
unknown committed
828
	  hash_delete(&queries, (byte *) query_block);
unknown's avatar
unknown committed
829 830 831
	  header->unlock_n_destroy();
	  free_memory_block(query_block);
	  STRUCT_UNLOCK(&structure_guard_mutex);
832
	  goto end;
unknown's avatar
unknown committed
833
	}
unknown's avatar
unknown committed
834
	double_linked_list_simple_include(query_block, &queries_blocks);
unknown's avatar
unknown committed
835 836 837
	inserts++;
	queries_in_cache++;
	STRUCT_UNLOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
838

unknown's avatar
unknown committed
839
	net->query_cache_query= (gptr) query_block;
unknown's avatar
unknown committed
840
	header->writer(net);
841
	header->tables_type(tables_type);
unknown's avatar
unknown committed
842 843 844 845 846 847
	// init_n_lock make query block locked
	BLOCK_UNLOCK_WR(query_block);
      }
      else
      {
	// We have not enough memory to store query => do nothing
unknown's avatar
unknown committed
848
	refused++;
unknown's avatar
unknown committed
849 850 851 852 853 854
	STRUCT_UNLOCK(&structure_guard_mutex);
	DBUG_PRINT("warning", ("Can't allocate query"));
      }
    }
    else
    {
unknown's avatar
unknown committed
855
      // Another thread is processing the same query => do nothing
unknown's avatar
unknown committed
856 857
      refused++;
      STRUCT_UNLOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
858
      DBUG_PRINT("qcache", ("Another thread process same query"));
unknown's avatar
unknown committed
859 860 861
    }
  }
  else
unknown's avatar
unknown committed
862
    statistic_increment(refused, &structure_guard_mutex);
unknown's avatar
unknown committed
863 864

end:
unknown's avatar
unknown committed
865 866
  DBUG_VOID_RETURN;
}
unknown's avatar
unknown committed
867

868

869 870 871 872 873 874 875 876 877 878
/*
  Check if the query is in the cache. If it was cached, send it
  to the user.

  RESULTS
        1	Query was not cached.
	0	The query was cached and user was sent the result.
	-1	The query was cached but we didn't have rights to use it.
		No error is sent to the client yet.
*/
unknown's avatar
unknown committed
879

880
int
unknown's avatar
unknown committed
881 882 883 884 885
Query_cache::send_result_to_client(THD *thd, char *sql, uint query_length)
{
  Query_cache_query *query;
  Query_cache_block *first_result_block, *result_block;
  Query_cache_block_table *block_table, *block_table_end;
886
  ulong tot_length;
unknown's avatar
unknown committed
887
  byte flags;
888
  bool check_tables;
unknown's avatar
unknown committed
889 890
  DBUG_ENTER("Query_cache::send_result_to_client");

891
  if (query_cache_size == 0 || thd->variables.query_cache_type == 0)
unknown's avatar
unknown committed
892

unknown's avatar
unknown committed
893
    goto err;
894 895 896 897

  /* Check that we haven't forgot to reset the query cache variables */
  DBUG_ASSERT(thd->net.query_cache_query == 0);

898
  if (!thd->lex.safe_to_cache_query)
unknown's avatar
unknown committed
899
  {
unknown's avatar
unknown committed
900
    DBUG_PRINT("qcache", ("SELECT is non-cacheable"));
unknown's avatar
unknown committed
901
    goto err;
unknown's avatar
unknown committed
902 903
  }

904 905 906 907
  /*
    Test if the query is a SELECT
    (pre-space is removed in dispatch_command)
  */
908 909 910
  if (my_toupper(system_charset_info, sql[0]) != 'S' || 
      my_toupper(system_charset_info, sql[1]) != 'E' ||
      my_toupper(system_charset_info,sql[2]) !='L')
unknown's avatar
unknown committed
911
  {
unknown's avatar
unknown committed
912 913
    DBUG_PRINT("qcache", ("The statement is not a SELECT; Not cached"));
    goto err;
unknown's avatar
unknown committed
914 915 916 917 918
  }

  STRUCT_LOCK(&structure_guard_mutex);
  if (query_cache_size == 0)
  {
919 920
    DBUG_PRINT("qcache", ("query cache disabled"));
    goto err_unlock;
unknown's avatar
unknown committed
921
  }
unknown's avatar
unknown committed
922
  Query_cache_block *query_block;
unknown's avatar
unknown committed
923

924
  tot_length=query_length+thd->db_length+2;
925 926
  if (thd->db_length)
  {
927
    memcpy(sql+query_length+1, thd->db, thd->db_length);
928 929 930 931 932 933 934
    DBUG_PRINT("qcache", ("database: '%s' length %u",
			  thd->db, thd->db_length));
  }
  else
  {
    DBUG_PRINT("qcache", ("No active database"));
  }
unknown's avatar
unknown committed
935 936
  /*
     prepare flags:
unknown's avatar
unknown committed
937 938
     Most significant bit - CLIENT_LONG_FLAG,
     Other - charset number (0 no charset convertion)
unknown's avatar
unknown committed
939
  */
unknown's avatar
unknown committed
940
  flags = (thd->client_capabilities & CLIENT_LONG_FLAG ? 0x80 : 0);
unknown's avatar
unknown committed
941 942
  flags |= (byte) thd->charset()->number;
  DBUG_ASSERT(thd->charset()->number < 128);
943
  sql[tot_length-1] = (char) flags;
unknown's avatar
unknown committed
944
  query_block = (Query_cache_block *)  hash_search(&queries, (byte*) sql,
945
						   tot_length);
unknown's avatar
unknown committed
946
  /* Quick abort on unlocked data */
unknown's avatar
unknown committed
947 948 949 950
  if (query_block == 0 ||
      query_block->query()->result() == 0 ||
      query_block->query()->result()->type != Query_cache_block::RESULT)
  {
unknown's avatar
unknown committed
951
    DBUG_PRINT("qcache", ("No query in query hash or no results"));
952
    goto err_unlock;
unknown's avatar
unknown committed
953
  }
unknown's avatar
unknown committed
954
  DBUG_PRINT("qcache", ("Query in query hash 0x%lx", (ulong)query_block));
unknown's avatar
unknown committed
955

unknown's avatar
unknown committed
956
  /* Now lock and test that nothing changed while blocks was unlocked */
unknown's avatar
unknown committed
957 958
  BLOCK_LOCK_RD(query_block);

unknown's avatar
unknown committed
959 960 961 962 963 964 965
  query = query_block->query();
  result_block= first_result_block= query->result();

  if (result_block == 0 || result_block->type != Query_cache_block::RESULT)
  {
    /* The query is probably yet processed */
    DBUG_PRINT("qcache", ("query found, but no data or data incomplete"));
unknown's avatar
unknown committed
966
    BLOCK_UNLOCK_RD(query_block);
967
    goto err_unlock;
unknown's avatar
unknown committed
968
  }
unknown's avatar
unknown committed
969 970
  DBUG_PRINT("qcache", ("Query have result 0x%lx", (ulong) query));

971
  check_tables= query->tables_type() & HA_CACHE_TBL_ASKTRANSACT;
unknown's avatar
unknown committed
972 973 974
  // Check access;
  block_table= query_block->table(0);
  block_table_end= block_table+query_block->n_tables;
975
  for (; block_table != block_table_end; block_table++)
unknown's avatar
unknown committed
976 977 978
  {
    TABLE_LIST table_list;
    bzero((char*) &table_list,sizeof(table_list));
unknown's avatar
unknown committed
979

unknown's avatar
unknown committed
980 981
    Query_cache_table *table = block_table->parent;
    table_list.db = table->db();
982
    table_list.alias= table_list.real_name= table->table();
983
    if (check_table_access(thd,SELECT_ACL,&table_list,1))
unknown's avatar
unknown committed
984 985 986
    {
      DBUG_PRINT("qcache",
		 ("probably no SELECT access to %s.%s =>  return to normal processing",
987
		  table_list.db, table_list.alias));
988
      refused++;				// This is actually a hit
unknown's avatar
unknown committed
989
      STRUCT_UNLOCK(&structure_guard_mutex);
990
      thd->lex.safe_to_cache_query=0;		// Don't try to cache this
991 992 993 994 995 996
      BLOCK_UNLOCK_RD(query_block);
      DBUG_RETURN(-1);				// Privilege error
    }
    if (table_list.grant.want_privilege)
    {
      DBUG_PRINT("qcache", ("Need to check column privileges for %s.%s",
997
			    table_list.db, table_list.alias));
998
      BLOCK_UNLOCK_RD(query_block);
unknown's avatar
unknown committed
999
      thd->lex.safe_to_cache_query= 0;		// Don't try to cache this
1000
      goto err_unlock;				// Parse query
unknown's avatar
unknown committed
1001
    }
1002 1003 1004 1005
    if (check_tables && !handler::caching_allowed(thd, table->db(), 
						  table->key_length(),
						  table->type()))
    {
1006
      DBUG_PRINT("qcache", ("Handler does not allow caching for %s.%s",
1007 1008
			    table_list.db, table_list.alias));
      BLOCK_UNLOCK_RD(query_block);
unknown's avatar
unknown committed
1009
      thd->lex.safe_to_cache_query= 0;          // Don't try to cache this
1010
      goto err_unlock;				// Parse query
unknown's avatar
unknown committed
1011
    }
1012 1013 1014
    else
      DBUG_PRINT("qcache", ("handler allow caching (%d) %s,%s",
			    check_tables, table_list.db, table_list.alias));
unknown's avatar
unknown committed
1015
  }
unknown's avatar
unknown committed
1016 1017
  move_to_query_list_end(query_block);
  hits++;
unknown's avatar
unknown committed
1018 1019
  STRUCT_UNLOCK(&structure_guard_mutex);

unknown's avatar
unknown committed
1020 1021 1022
  /*
    Send cached result to client
  */
unknown's avatar
unknown committed
1023 1024
  do
  {
unknown's avatar
unknown committed
1025
    DBUG_PRINT("qcache", ("Results  (len %lu, used %lu, headers %lu)",
unknown's avatar
unknown committed
1026 1027 1028 1029
			result_block->length, result_block->used,
			result_block->headers_len()+
			ALIGN_SIZE(sizeof(Query_cache_result))));

unknown's avatar
unknown committed
1030
    Query_cache_result *result = result_block->result();
unknown's avatar
SCRUM  
unknown committed
1031
#ifndef EMBEDDED_LIBRARY   /* TODO query cache in embedded library*/
unknown's avatar
unknown committed
1032 1033 1034 1035 1036
    if (net_real_write(&thd->net, result->data(),
		       result_block->used -
		       result_block->headers_len() -
		       ALIGN_SIZE(sizeof(Query_cache_result))))
      break;					// Client aborted
1037
#endif
unknown's avatar
unknown committed
1038 1039 1040 1041 1042 1043
    result_block = result_block->next;
  } while (result_block != first_result_block);

  thd->limit_found_rows = query->found_rows();

  BLOCK_UNLOCK_RD(query_block);
1044
  DBUG_RETURN(1);				// Result sent to client
unknown's avatar
unknown committed
1045

1046 1047
err_unlock:
  STRUCT_UNLOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
1048
err:
1049
  DBUG_RETURN(0);				// Query was not cached
unknown's avatar
unknown committed
1050 1051
}

1052

unknown's avatar
unknown committed
1053 1054 1055 1056
/*
  Remove all cached queries that uses any of the tables in the list
*/

1057 1058
void Query_cache::invalidate(THD *thd, TABLE_LIST *tables_used,
			     my_bool using_transactions)
unknown's avatar
unknown committed
1059 1060 1061 1062 1063 1064 1065 1066
{
  DBUG_ENTER("Query_cache::invalidate (table list)");
  if (query_cache_size > 0)
  {
    STRUCT_LOCK(&structure_guard_mutex);
    if (query_cache_size > 0)
    {
      DUMP(this);
1067 1068

      using_transactions = using_transactions &&
unknown's avatar
unknown committed
1069
	(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN));
1070
      for (; tables_used; tables_used=tables_used->next)
1071 1072
      {
	DBUG_ASSERT(!using_transactions || tables_used->table!=0);
unknown's avatar
unknown committed
1073 1074
	if (tables_used->derived)
	  continue;
1075
	if (using_transactions && 
1076 1077
	   (tables_used->table->file->table_cache_type() == 
	    HA_CACHE_TBL_TRANSACT))
1078 1079 1080 1081 1082 1083 1084 1085 1086
	  /* 
	     Tables_used->table can't be 0 in transaction.
	     Only 'drop' invalidate not opened table, but 'drop' 
	     force transaction finish.
	  */
	  thd->add_changed_table(tables_used->table);
	else
	  invalidate_table(tables_used);
      }
unknown's avatar
unknown committed
1087 1088 1089 1090 1091 1092
    }
    STRUCT_UNLOCK(&structure_guard_mutex);
  }
  DBUG_VOID_RETURN;
}

1093
void Query_cache::invalidate(CHANGED_TABLE_LIST *tables_used)
unknown's avatar
unknown committed
1094
{
1095 1096
  DBUG_ENTER("Query_cache::invalidate (changed table list)");
  if (query_cache_size > 0 && tables_used)
unknown's avatar
unknown committed
1097 1098 1099
  {
    STRUCT_LOCK(&structure_guard_mutex);
    if (query_cache_size > 0)
1100 1101
    {
      DUMP(this);
1102
      for (; tables_used; tables_used=tables_used->next)
1103
      {
1104
	invalidate_table((byte*) tables_used->key, tables_used->key_length);
1105
	DBUG_PRINT("qcache", (" db %s, table %s", tables_used->key,
1106 1107
			      tables_used->key+
			      strlen(tables_used->key)+1));
1108 1109
      }
    }
unknown's avatar
unknown committed
1110 1111 1112
    STRUCT_UNLOCK(&structure_guard_mutex);
  }
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1113 1114
}

unknown's avatar
unknown committed
1115
/*
1116
  Remove all cached queries that uses the given table
unknown's avatar
unknown committed
1117 1118
*/

1119 1120
void Query_cache::invalidate(THD *thd, TABLE *table, 
			     my_bool using_transactions)
unknown's avatar
unknown committed
1121
{
1122 1123
  DBUG_ENTER("Query_cache::invalidate (table)");
  
unknown's avatar
unknown committed
1124 1125 1126
  if (query_cache_size > 0)
  {
    STRUCT_LOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
1127
    if (query_cache_size > 0)
unknown's avatar
unknown committed
1128
    {
1129
      using_transactions = using_transactions &&
unknown's avatar
unknown committed
1130
	(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN));
1131 1132
      if (using_transactions && 
	  (table->file->table_cache_type() == HA_CACHE_TBL_TRANSACT))
1133 1134 1135
	thd->add_changed_table(table);
      else
	invalidate_table(table);
unknown's avatar
unknown committed
1136 1137 1138 1139
    }
    STRUCT_UNLOCK(&structure_guard_mutex);
  }
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1140 1141
}

unknown's avatar
unknown committed
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
void Query_cache::invalidate(THD *thd, const char *key, uint32  key_length,
			     my_bool using_transactions)
{
  DBUG_ENTER("Query_cache::invalidate (key)");
  
  if (query_cache_size > 0)
  {
    using_transactions = using_transactions &&
      (thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN));
    if (using_transactions) // used for innodb => has_transactions() is TRUE
      thd->add_changed_table(key, key_length);
    else
    {
      STRUCT_LOCK(&structure_guard_mutex);
      if (query_cache_size > 0)
	invalidate_table((byte*)key, key_length);
      STRUCT_UNLOCK(&structure_guard_mutex);  
    }
  }
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
1164 1165 1166 1167
/*
  Remove all cached queries that uses the given database
*/

unknown's avatar
unknown committed
1168
void Query_cache::invalidate(char *db)
unknown's avatar
unknown committed
1169
{
unknown's avatar
unknown committed
1170 1171
  DBUG_ENTER("Query_cache::invalidate (db)");
  if (query_cache_size > 0)
unknown's avatar
unknown committed
1172
  {
unknown's avatar
unknown committed
1173 1174 1175 1176
    STRUCT_LOCK(&structure_guard_mutex);
    if (query_cache_size > 0)
    {
      DUMP(this);
unknown's avatar
unknown committed
1177
	/* invalidate_table reduce list while only root of list remain */
1178 1179
      while (tables_blocks !=0 )
	invalidate_table(tables_blocks);
unknown's avatar
unknown committed
1180 1181
    }
    STRUCT_UNLOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
1182
  }
unknown's avatar
unknown committed
1183
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1184 1185
}

unknown's avatar
unknown committed
1186 1187

void Query_cache::invalidate_by_MyISAM_filename(const char *filename)
unknown's avatar
unknown committed
1188 1189 1190 1191
{
  DBUG_ENTER("Query_cache::invalidate_by_MyISAM_filename");
  if (query_cache_size > 0)
  {
unknown's avatar
unknown committed
1192 1193
    /* Calculate the key outside the lock to make the lock shorter */
    char key[MAX_DBKEY_LENGTH];
1194 1195
    uint32 db_length;
    uint key_length= filename_2_table_key(key, filename, &db_length);
unknown's avatar
unknown committed
1196
    STRUCT_LOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
1197
    if (query_cache_size > 0)			// Safety if cache removed
unknown's avatar
unknown committed
1198
    {
unknown's avatar
unknown committed
1199
      Query_cache_block *table_block;
unknown's avatar
unknown committed
1200 1201
      if ((table_block = (Query_cache_block*) hash_search(&tables,
							  (byte*) key,
unknown's avatar
unknown committed
1202 1203
							  key_length)))
	invalidate_table(table_block);
unknown's avatar
unknown committed
1204 1205 1206 1207 1208
    }
    STRUCT_UNLOCK(&structure_guard_mutex);
  }
  DBUG_VOID_RETURN;
}
unknown's avatar
unknown committed
1209

unknown's avatar
unknown committed
1210
  /* Remove all queries from cache */
unknown's avatar
unknown committed
1211

unknown's avatar
unknown committed
1212
void Query_cache::flush()
unknown's avatar
unknown committed
1213
{
unknown's avatar
unknown committed
1214
  DBUG_ENTER("Query_cache::flush");
unknown's avatar
unknown committed
1215
  STRUCT_LOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
1216 1217 1218 1219 1220 1221
  if (query_cache_size > 0)
  {
    DUMP(this);
    flush_cache();
    DUMP(this);
  }
unknown's avatar
unknown committed
1222 1223

  DBUG_EXECUTE("check_querycache",query_cache.check_integrity(1););
unknown's avatar
unknown committed
1224
  STRUCT_UNLOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
1225
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1226 1227
}

unknown's avatar
unknown committed
1228 1229
  /* Join result in cache in 1 block (if result length > join_limit) */

unknown's avatar
unknown committed
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
void Query_cache::pack(ulong join_limit, uint iteration_limit)
{
  DBUG_ENTER("Query_cache::pack");
  uint i = 0;
  do
  {
    pack_cache();
  } while ((++i < iteration_limit) && join_results(join_limit));
  DBUG_VOID_RETURN;
}
unknown's avatar
unknown committed
1240

unknown's avatar
unknown committed
1241

unknown's avatar
unknown committed
1242
void Query_cache::destroy()
unknown's avatar
unknown committed
1243
{
1244 1245
  DBUG_ENTER("Query_cache::destroy");
  if (!initialized)
unknown's avatar
unknown committed
1246 1247 1248
  {
    DBUG_PRINT("qcache", ("Query Cache not initialized"));
  }
1249 1250 1251 1252 1253 1254
  else
  {
    free_cache(1);
    pthread_mutex_destroy(&structure_guard_mutex);
    initialized = 0;
  }
unknown's avatar
unknown committed
1255 1256
  DBUG_VOID_RETURN;
}
unknown's avatar
unknown committed
1257

unknown's avatar
unknown committed
1258 1259

/*****************************************************************************
unknown's avatar
unknown committed
1260 1261
  init/destroy
*****************************************************************************/
unknown's avatar
unknown committed
1262 1263 1264 1265 1266 1267 1268 1269 1270

void Query_cache::init()
{
  DBUG_ENTER("Query_cache::init");
  pthread_mutex_init(&structure_guard_mutex,MY_MUTEX_INIT_FAST);
  initialized = 1;
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
1271

unknown's avatar
unknown committed
1272 1273
ulong Query_cache::init_cache()
{
unknown's avatar
unknown committed
1274 1275 1276
  uint mem_bin_count, num, step;
  ulong mem_bin_size, prev_size, inc;
  ulong additional_data_size, max_mem_bin_size, approx_additional_data_size;
unknown's avatar
unknown committed
1277
  int align;
unknown's avatar
unknown committed
1278

unknown's avatar
unknown committed
1279 1280 1281
  DBUG_ENTER("Query_cache::init_cache");
  if (!initialized)
    init();
unknown's avatar
unknown committed
1282 1283 1284
  approx_additional_data_size = (sizeof(Query_cache) +
				 sizeof(gptr)*(def_query_hash_size+
					       def_query_hash_size));
unknown's avatar
unknown committed
1285
  if (query_cache_size < approx_additional_data_size)
unknown's avatar
unknown committed
1286
    goto err;
unknown's avatar
unknown committed
1287

unknown's avatar
unknown committed
1288 1289
  query_cache_size-= approx_additional_data_size;
  align= query_cache_size % ALIGN_SIZE(1);
1290 1291 1292 1293 1294
  if (align)
  {
    query_cache_size-= align;
    approx_additional_data_size+= align;
  }
unknown's avatar
unknown committed
1295

unknown's avatar
unknown committed
1296 1297 1298 1299
  /*
    Count memory bins number.
    Check section 6. in start comment for the used algorithm.
  */
unknown's avatar
unknown committed
1300

unknown's avatar
unknown committed
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
  max_mem_bin_size = query_cache_size >> QUERY_CACHE_MEM_BIN_FIRST_STEP_PWR2;
  mem_bin_count = (uint)  ((1 + QUERY_CACHE_MEM_BIN_PARTS_INC) *
			   QUERY_CACHE_MEM_BIN_PARTS_MUL);
  mem_bin_num = 1;
  mem_bin_steps = 1;
  mem_bin_size = max_mem_bin_size >> QUERY_CACHE_MEM_BIN_STEP_PWR2;
  prev_size = 0;
  while (mem_bin_size > min_allocation_unit)
  {
    mem_bin_num += mem_bin_count;
    prev_size = mem_bin_size;
    mem_bin_size >>= QUERY_CACHE_MEM_BIN_STEP_PWR2;
unknown's avatar
unknown committed
1313
    mem_bin_steps++;
unknown's avatar
unknown committed
1314 1315 1316 1317 1318 1319
    mem_bin_count += QUERY_CACHE_MEM_BIN_PARTS_INC;
    mem_bin_count = (uint) (mem_bin_count * QUERY_CACHE_MEM_BIN_PARTS_MUL);

    // Prevent too small bins spacing
    if (mem_bin_count > (mem_bin_size >> QUERY_CACHE_MEM_BIN_SPC_LIM_PWR2))
      mem_bin_count= (mem_bin_size >> QUERY_CACHE_MEM_BIN_SPC_LIM_PWR2);
unknown's avatar
unknown committed
1320
  }
unknown's avatar
unknown committed
1321 1322 1323 1324 1325 1326 1327 1328
  inc = (prev_size - mem_bin_size) / mem_bin_count;
  mem_bin_num += (mem_bin_count - (min_allocation_unit - mem_bin_size)/inc);
  mem_bin_steps++;
  additional_data_size = ((mem_bin_num+1) *
			  ALIGN_SIZE(sizeof(Query_cache_memory_bin))+
			  (mem_bin_steps *
			   ALIGN_SIZE(sizeof(Query_cache_memory_bin_step))));

unknown's avatar
unknown committed
1329
  if (query_cache_size < additional_data_size)
unknown's avatar
unknown committed
1330 1331
    goto err;
  query_cache_size -= additional_data_size;
unknown's avatar
unknown committed
1332 1333

  STRUCT_LOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
1334
  if (max_mem_bin_size	<= min_allocation_unit)
unknown's avatar
unknown committed
1335
  {
unknown's avatar
unknown committed
1336
    DBUG_PRINT("qcache",
unknown's avatar
unknown committed
1337 1338
	       (" max bin size (%lu) <= min_allocation_unit => cache disabled",
		max_mem_bin_size));
unknown's avatar
unknown committed
1339 1340
    STRUCT_UNLOCK(&structure_guard_mutex);
    goto err;
unknown's avatar
unknown committed
1341
  }
unknown's avatar
unknown committed
1342 1343 1344

  if (!(cache = (byte *)
	 my_malloc_lock(query_cache_size+additional_data_size, MYF(0))))
unknown's avatar
unknown committed
1345
  {
unknown's avatar
unknown committed
1346 1347 1348
    STRUCT_UNLOCK(&structure_guard_mutex);
    goto err;
  }
unknown's avatar
unknown committed
1349

unknown's avatar
unknown committed
1350 1351
  DBUG_PRINT("qcache", ("cache length %lu, min unit %lu, %u bins",
		      query_cache_size, min_allocation_unit, mem_bin_num));
unknown's avatar
unknown committed
1352

unknown's avatar
unknown committed
1353 1354 1355 1356
  steps = (Query_cache_memory_bin_step *) cache;
  bins = ((Query_cache_memory_bin *)
	  (cache + mem_bin_steps *
	   ALIGN_SIZE(sizeof(Query_cache_memory_bin_step))));
unknown's avatar
unknown committed
1357

unknown's avatar
unknown committed
1358 1359
  first_block = (Query_cache_block *) (cache + additional_data_size);
  first_block->init(query_cache_size);
unknown's avatar
unknown committed
1360
  total_blocks++;
unknown's avatar
unknown committed
1361 1362
  first_block->pnext=first_block->pprev=first_block;
  first_block->next=first_block->prev=first_block;
unknown's avatar
unknown committed
1363

unknown's avatar
unknown committed
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
  /* Prepare bins */

  bins[0].init(max_mem_bin_size);
  steps[0].init(max_mem_bin_size,0,0);
  mem_bin_count = (uint) ((1 + QUERY_CACHE_MEM_BIN_PARTS_INC) *
			  QUERY_CACHE_MEM_BIN_PARTS_MUL);
  num= step= 1;
  mem_bin_size = max_mem_bin_size >> QUERY_CACHE_MEM_BIN_STEP_PWR2;
  while (mem_bin_size > min_allocation_unit)
  {
    ulong incr = (steps[step-1].size - mem_bin_size) / mem_bin_count;
    unsigned long size = mem_bin_size;
    for (uint i= mem_bin_count; i > 0; i--)
    {
      bins[num+i-1].init(size);
      size += incr;
unknown's avatar
unknown committed
1380
    }
unknown's avatar
unknown committed
1381 1382 1383 1384 1385 1386 1387 1388
    num += mem_bin_count;
    steps[step].init(mem_bin_size, num-1, incr);
    mem_bin_size >>= QUERY_CACHE_MEM_BIN_STEP_PWR2;
    step++;
    mem_bin_count += QUERY_CACHE_MEM_BIN_PARTS_INC;
    mem_bin_count = (uint) (mem_bin_count * QUERY_CACHE_MEM_BIN_PARTS_MUL);
    if (mem_bin_count > (mem_bin_size >> QUERY_CACHE_MEM_BIN_SPC_LIM_PWR2))
      mem_bin_count=(mem_bin_size >> QUERY_CACHE_MEM_BIN_SPC_LIM_PWR2);
unknown's avatar
unknown committed
1389
  }
unknown's avatar
unknown committed
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
  inc = (steps[step-1].size - mem_bin_size) / mem_bin_count;

  /*
    num + mem_bin_count > mem_bin_num, but index never be > mem_bin_num
    because block with size < min_allocated_unit never will be requested
  */

  steps[step].init(mem_bin_size, num + mem_bin_count - 1, inc);
  {
    uint skiped = (min_allocation_unit - mem_bin_size)/inc;
    ulong size = mem_bin_size + inc*skiped;
    uint i = mem_bin_count - skiped;
    while (i-- > 0)
    {
      bins[num+i].init(size);
      size += inc;
    }
  }
unknown's avatar
unknown committed
1408 1409
  bins[mem_bin_num].number = 1;	// For easy end test in get_free_block
  free_memory = free_memory_blocks = 0;
unknown's avatar
unknown committed
1410 1411 1412 1413
  insert_into_free_memory_list(first_block);

  DUMP(this);

unknown's avatar
unknown committed
1414
  VOID(hash_init(&queries,system_charset_info,def_query_hash_size, 0, 0,
unknown's avatar
unknown committed
1415
		 query_cache_query_get_key, 0, 0));
1416
#ifndef FN_NO_CASE_SENCE
unknown's avatar
unknown committed
1417
  VOID(hash_init(&tables,system_charset_info,def_table_hash_size, 0, 0,
unknown's avatar
unknown committed
1418
		 query_cache_table_get_key, 0, 0));
unknown's avatar
unknown committed
1419
#else
1420
  // windows, OS/2 or other case insensitive file names work around
unknown's avatar
unknown committed
1421 1422 1423
  VOID(hash_init(&tables,
		 lower_case_table_names ? &my_charset_bin : system_charset_info,
		 def_table_hash_size, 0, 0,query_cache_table_get_key, 0, 0));
unknown's avatar
unknown committed
1424
#endif
unknown's avatar
unknown committed
1425

unknown's avatar
unknown committed
1426 1427 1428 1429 1430
  queries_in_cache = 0;
  queries_blocks = 0;
  STRUCT_UNLOCK(&structure_guard_mutex);
  DBUG_RETURN(query_cache_size +
	      additional_data_size + approx_additional_data_size);
unknown's avatar
unknown committed
1431 1432 1433 1434

err:
  make_disabled();
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1435 1436
}

unknown's avatar
unknown committed
1437 1438 1439

/* Disable the use of the query cache */

unknown's avatar
unknown committed
1440 1441 1442
void Query_cache::make_disabled()
{
  DBUG_ENTER("Query_cache::make_disabled");
unknown's avatar
unknown committed
1443 1444 1445 1446 1447 1448 1449 1450
  query_cache_size= 0;
  free_memory= 0;
  bins= 0;
  steps= 0;
  cache= 0;
  mem_bin_num= mem_bin_steps= 0;
  queries_in_cache= 0;
  first_block= 0;
unknown's avatar
unknown committed
1451 1452 1453
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
1454

unknown's avatar
unknown committed
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
void Query_cache::free_cache(my_bool destruction)
{
  DBUG_ENTER("Query_cache::free_cache");
  if (query_cache_size > 0)
  {
    if (!destruction)
      STRUCT_LOCK(&structure_guard_mutex);

    flush_cache();
#ifndef DBUG_OFF
    if (bins[0].free_blocks == 0)
    {
      wreck(__LINE__,"no free memory found in (bins[0].free_blocks");
unknown's avatar
unknown committed
1468
      DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1469 1470 1471
    }
#endif

unknown's avatar
unknown committed
1472 1473
    /* Becasue we did a flush, all cache memory must be in one this block */
    bins[0].free_blocks->destroy();
unknown's avatar
unknown committed
1474
    total_blocks--;
1475 1476 1477 1478 1479
#ifndef DBUG_OFF
    if (free_memory != query_cache_size)
      DBUG_PRINT("qcache", ("free memory %lu (should be %lu)",
			    free_memory , query_cache_size));
#endif
unknown's avatar
unknown committed
1480 1481
    my_free((gptr) cache, MYF(MY_ALLOW_ZERO_PTR));
    make_disabled();
unknown's avatar
unknown committed
1482 1483 1484 1485 1486 1487 1488 1489 1490
    hash_free(&queries);
    hash_free(&tables);
    if (!destruction)
      STRUCT_UNLOCK(&structure_guard_mutex);
  }
  DBUG_VOID_RETURN;
}

/*****************************************************************************
unknown's avatar
unknown committed
1491
  Free block data
unknown's avatar
unknown committed
1492 1493 1494 1495 1496
*****************************************************************************/

/*
  The following assumes we have a lock on the cache
*/
unknown's avatar
unknown committed
1497 1498 1499

void Query_cache::flush_cache()
{
unknown's avatar
unknown committed
1500 1501
  while (queries_blocks != 0)
  {
unknown's avatar
unknown committed
1502 1503 1504 1505 1506
    BLOCK_LOCK_WR(queries_blocks);
    free_query(queries_blocks);
  }
}

unknown's avatar
unknown committed
1507 1508 1509 1510 1511
/*
  Free oldest query that is not in use by another thread.
  Returns 1 if we couldn't remove anything
*/

unknown's avatar
unknown committed
1512 1513 1514
my_bool Query_cache::free_old_query()
{
  DBUG_ENTER("Query_cache::free_old_query");
unknown's avatar
unknown committed
1515
  if (queries_blocks)
unknown's avatar
unknown committed
1516
  {
unknown's avatar
unknown committed
1517 1518 1519 1520 1521 1522 1523
    /*
      try_lock_writing used to prevent client because here lock
      sequence is breached.
      Also we don't need remove locked queries at this point.
    */
    Query_cache_block *query_block = 0;
    if (queries_blocks != 0)
unknown's avatar
unknown committed
1524
    {
unknown's avatar
unknown committed
1525 1526 1527
      Query_cache_block *block = queries_blocks;
      /* Search until we find first query that we can remove */
      do
unknown's avatar
unknown committed
1528
      {
unknown's avatar
unknown committed
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
	Query_cache_query *header = block->query();
	if (header->result() != 0 &&
	    header->result()->type == Query_cache_block::RESULT &&
	    block->query()->try_lock_writing())
	{
	  query_block = block;
	  break;
	}
      } while ((block=block->next) != queries_blocks );
    }
unknown's avatar
unknown committed
1539

unknown's avatar
unknown committed
1540 1541 1542
    if (query_block != 0)
    {
      free_query(query_block);
1543
      lowmem_prunes++;
unknown's avatar
unknown committed
1544 1545
      DBUG_RETURN(0);
    }
unknown's avatar
unknown committed
1546
  }
unknown's avatar
unknown committed
1547
  DBUG_RETURN(1);				// Nothing to remove
unknown's avatar
unknown committed
1548 1549
}

unknown's avatar
unknown committed
1550 1551 1552 1553 1554 1555 1556
/*
  Free query from query cache.
  query_block must be locked for writing.
  This function will remove (and destroy) the lock for the query.
*/

void Query_cache::free_query(Query_cache_block *query_block)
unknown's avatar
unknown committed
1557 1558
{
  DBUG_ENTER("Query_cache::free_query");
unknown's avatar
unknown committed
1559 1560
  DBUG_PRINT("qcache", ("free query 0x%lx %lu bytes result",
		      (ulong) query_block,
unknown's avatar
unknown committed
1561
		      query_block->query()->length() ));
unknown's avatar
unknown committed
1562

unknown's avatar
unknown committed
1563 1564 1565
  queries_in_cache--;
  hash_delete(&queries,(byte *) query_block);

unknown's avatar
unknown committed
1566 1567
  Query_cache_query *query = query_block->query();

unknown's avatar
unknown committed
1568 1569
  if (query->writer() != 0)
  {
unknown's avatar
unknown committed
1570
    /* Tell MySQL that this query should not be cached anymore */
unknown's avatar
unknown committed
1571 1572 1573
    query->writer()->query_cache_query = 0;
    query->writer(0);
  }
unknown's avatar
unknown committed
1574 1575 1576 1577 1578
  double_linked_list_exclude(query_block, &queries_blocks);
  Query_cache_block_table *table=query_block->table(0);

  for (TABLE_COUNTER_TYPE i=0; i < query_block->n_tables; i++)
    unlink_table(table++);
unknown's avatar
unknown committed
1579
  Query_cache_block *result_block = query->result();
unknown's avatar
unknown committed
1580 1581 1582 1583 1584

  /*
    The following is true when query destruction was called and no results
    in query . (query just registered and then abort/pack/flush called)
  */
unknown's avatar
unknown committed
1585 1586
  if (result_block != 0)
  {
unknown's avatar
unknown committed
1587
    Query_cache_block *block = result_block;
unknown's avatar
unknown committed
1588 1589
    do
    {
unknown's avatar
unknown committed
1590
      Query_cache_block *current = block;
unknown's avatar
unknown committed
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
      block = block->next;
      free_memory_block(current);
    } while (block != result_block);
  }

  query->unlock_n_destroy();
  free_memory_block(query_block);

  DBUG_VOID_RETURN;
}

/*****************************************************************************
unknown's avatar
unknown committed
1603 1604
 Query data creation
*****************************************************************************/
unknown's avatar
unknown committed
1605 1606 1607 1608 1609 1610 1611 1612

Query_cache_block *
Query_cache::write_block_data(ulong data_len, gptr data,
			      ulong header_len,
			      Query_cache_block::block_type type,
			      TABLE_COUNTER_TYPE ntab,
			      my_bool under_guard)
{
unknown's avatar
unknown committed
1613 1614 1615 1616
  ulong all_headers_len = (ALIGN_SIZE(sizeof(Query_cache_block)) +
			   ALIGN_SIZE(ntab*sizeof(Query_cache_block_table)) +
			   header_len);
  ulong len = data_len + all_headers_len;
1617
  ulong align_len= ALIGN_SIZE(len);
unknown's avatar
unknown committed
1618
  DBUG_ENTER("Query_cache::write_block_data");
unknown's avatar
unknown committed
1619
  DBUG_PRINT("qcache", ("data: %ld, header: %ld, all header: %ld",
unknown's avatar
unknown committed
1620
		      data_len, header_len, all_headers_len));
1621 1622
  Query_cache_block *block = allocate_block(max(align_len, 
						min_allocation_unit),
unknown's avatar
unknown committed
1623
					    1, 0, under_guard);
unknown's avatar
unknown committed
1624 1625 1626 1627 1628 1629
  if (block != 0)
  {
    block->type = type;
    block->n_tables = ntab;
    block->used = len;

unknown's avatar
unknown committed
1630 1631
    memcpy((void*) (((byte *) block)+ all_headers_len),
	   (void*) data, data_len);
unknown's avatar
unknown committed
1632 1633 1634 1635
  }
  DBUG_RETURN(block);
}

unknown's avatar
unknown committed
1636 1637 1638 1639 1640

/*
  On success STRUCT_UNLOCK(&query_cache.structure_guard_mutex) will be done.
*/

unknown's avatar
unknown committed
1641
my_bool
unknown's avatar
unknown committed
1642
Query_cache::append_result_data(Query_cache_block **current_block,
unknown's avatar
unknown committed
1643
				ulong data_len, gptr data,
unknown's avatar
unknown committed
1644
				Query_cache_block *query_block)
unknown's avatar
unknown committed
1645
{
unknown's avatar
unknown committed
1646 1647 1648 1649
  DBUG_ENTER("Query_cache::append_result_data");
  DBUG_PRINT("qcache", ("append %lu bytes to 0x%lx query",
		      data_len, query_block));

unknown's avatar
unknown committed
1650 1651
  if (query_block->query()->add(data_len) > query_cache_limit)
  {
unknown's avatar
unknown committed
1652
    DBUG_PRINT("qcache", ("size limit reached %lu > %lu",
unknown's avatar
unknown committed
1653 1654 1655 1656
			query_block->query()->length(),
			query_cache_limit));
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
1657
  if (*current_block == 0)
unknown's avatar
unknown committed
1658
  {
unknown's avatar
unknown committed
1659
    DBUG_PRINT("qcache", ("allocated first result data block %lu", data_len));
unknown's avatar
unknown committed
1660
    /*
unknown's avatar
unknown committed
1661 1662
      STRUCT_UNLOCK(&structure_guard_mutex) Will be done by
      write_result_data if success;
unknown's avatar
unknown committed
1663
    */
unknown's avatar
unknown committed
1664
    DBUG_RETURN(write_result_data(current_block, data_len, data, query_block,
unknown's avatar
unknown committed
1665 1666
				  Query_cache_block::RES_BEG));
  }
unknown's avatar
unknown committed
1667
  Query_cache_block *last_block = (*current_block)->prev;
unknown's avatar
unknown committed
1668

unknown's avatar
unknown committed
1669 1670
  DBUG_PRINT("qcache", ("lastblock 0x%lx len %lu used %lu",
		      (ulong) last_block, last_block->length,
unknown's avatar
unknown committed
1671 1672
		      last_block->used));
  my_bool success = 1;
unknown's avatar
unknown committed
1673
  ulong last_block_free_space= last_block->length - last_block->used;
unknown's avatar
unknown committed
1674

unknown's avatar
unknown committed
1675 1676 1677 1678 1679
  /*
    We will first allocate and write the 'tail' of data, that doesn't fit
    in the 'last_block'.  Only if this succeeds, we will fill the last_block.
    This saves us a memcpy if the query doesn't fit in the query cache.
  */
unknown's avatar
unknown committed
1680

unknown's avatar
unknown committed
1681
  // Try join blocks if physically next block is free...
1682 1683
  ulong tail = data_len - last_block_free_space;
  ulong append_min = get_min_append_result_data_size();
unknown's avatar
unknown committed
1684 1685
  if (last_block_free_space < data_len &&
      append_next_free_block(last_block,
1686
			     max(tail, append_min)))
unknown's avatar
unknown committed
1687
    last_block_free_space = last_block->length - last_block->used;
unknown's avatar
unknown committed
1688
  // If no space in last block (even after join) allocate new block
unknown's avatar
unknown committed
1689 1690
  if (last_block_free_space < data_len)
  {
unknown's avatar
unknown committed
1691
    DBUG_PRINT("qcache", ("allocate new block for %lu bytes",
unknown's avatar
unknown committed
1692 1693 1694
			data_len-last_block_free_space));
    Query_cache_block *new_block = 0;
    /*
unknown's avatar
unknown committed
1695 1696
      On success STRUCT_UNLOCK(&structure_guard_mutex) will be done
      by the next call
unknown's avatar
unknown committed
1697
    */
unknown's avatar
unknown committed
1698
    success = write_result_data(&new_block, data_len-last_block_free_space,
unknown's avatar
unknown committed
1699 1700 1701 1702
				(gptr)(((byte*)data)+last_block_free_space),
				query_block,
				Query_cache_block::RES_CONT);
    /*
unknown's avatar
unknown committed
1703 1704
       new_block may be != 0 even !success (if write_result_data
       allocate a small block but failed to allocate continue)
unknown's avatar
unknown committed
1705 1706 1707 1708 1709
    */
    if (new_block != 0)
      double_linked_list_join(last_block, new_block);
  }
  else
unknown's avatar
unknown committed
1710 1711
  {
    // It is success (nobody can prevent us write data)
unknown's avatar
unknown committed
1712
    STRUCT_UNLOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
1713
  }
unknown's avatar
unknown committed
1714

unknown's avatar
unknown committed
1715 1716
  // Now finally write data to the last block
  if (success && last_block_free_space > 0)
unknown's avatar
unknown committed
1717 1718
  {
    ulong to_copy = min(data_len,last_block_free_space);
unknown's avatar
unknown committed
1719
    DBUG_PRINT("qcache", ("use free space %lub at block 0x%lx to copy %lub",
unknown's avatar
unknown committed
1720
			last_block_free_space, (ulong)last_block, to_copy));
unknown's avatar
unknown committed
1721 1722
    memcpy((void*) (((byte*) last_block) + last_block->used), (void*) data,
	   to_copy);
unknown's avatar
unknown committed
1723 1724 1725 1726 1727
    last_block->used+=to_copy;
  }
  DBUG_RETURN(success);
}

unknown's avatar
unknown committed
1728 1729

my_bool Query_cache::write_result_data(Query_cache_block **result_block,
unknown's avatar
unknown committed
1730
				       ulong data_len, gptr data,
unknown's avatar
unknown committed
1731
				       Query_cache_block *query_block,
unknown's avatar
unknown committed
1732 1733 1734
				       Query_cache_block::block_type type)
{
  DBUG_ENTER("Query_cache::write_result_data");
unknown's avatar
unknown committed
1735
  DBUG_PRINT("qcache", ("data_len %lu",data_len));
unknown's avatar
unknown committed
1736

unknown's avatar
unknown committed
1737 1738 1739 1740 1741 1742 1743 1744 1745
  /*
    Reserve block(s) for filling
    During data allocation we must have structure_guard_mutex locked.
    As data copy is not a fast operation, it's better if we don't have
    structure_guard_mutex locked during data coping.
    Thus we first allocate space and lock query, then unlock
    structure_guard_mutex and copy data.
  */

1746 1747
  my_bool success = allocate_data_chain(result_block, data_len, query_block,
					type == Query_cache_block::RES_BEG);
unknown's avatar
unknown committed
1748 1749
  if (success)
  {
unknown's avatar
unknown committed
1750
    // It is success (nobody can prevent us write data)
unknown's avatar
unknown committed
1751
    STRUCT_UNLOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
1752 1753 1754 1755 1756
    byte *rest = (byte*) data;
    Query_cache_block *block = *result_block;
    uint headers_len = (ALIGN_SIZE(sizeof(Query_cache_block)) +
			ALIGN_SIZE(sizeof(Query_cache_result)));
    // Now fill list of blocks that created by allocate_data_chain
unknown's avatar
unknown committed
1757 1758 1759 1760
    do
    {
      block->type = type;
      ulong length = block->used - headers_len;
unknown's avatar
unknown committed
1761
      DBUG_PRINT("qcache", ("write %lu byte in block 0x%lx",length,
unknown's avatar
unknown committed
1762
			  (ulong)block));
unknown's avatar
unknown committed
1763
      memcpy((void*)(((byte*) block)+headers_len), (void*) rest, length);
unknown's avatar
unknown committed
1764 1765 1766
      rest += length;
      block = block->next;
      type = Query_cache_block::RES_CONT;
unknown's avatar
unknown committed
1767
    } while (block != *result_block);
unknown's avatar
unknown committed
1768 1769 1770
  }
  else
  {
unknown's avatar
unknown committed
1771
    if (*result_block != 0)
unknown's avatar
unknown committed
1772
    {
unknown's avatar
unknown committed
1773 1774
      // Destroy list of blocks that was created & locked by lock_result_data
      Query_cache_block *block = *result_block;
unknown's avatar
unknown committed
1775 1776
      do
      {
unknown's avatar
unknown committed
1777
	Query_cache_block *current = block;
unknown's avatar
unknown committed
1778 1779
	block = block->next;
	free_memory_block(current);
unknown's avatar
unknown committed
1780 1781
      } while (block != *result_block);
      *result_block = 0;
unknown's avatar
unknown committed
1782
      /*
unknown's avatar
unknown committed
1783 1784
	It is not success => not unlock structure_guard_mutex (we need it to
	free query)
unknown's avatar
unknown committed
1785 1786 1787
      */
    }
  }
unknown's avatar
unknown committed
1788
  DBUG_PRINT("qcache", ("success %d", (int) success));
unknown's avatar
unknown committed
1789 1790 1791
  DBUG_RETURN(success);
}

1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
inline ulong Query_cache::get_min_first_result_data_size()
{
  if (queries_in_cache < QUERY_CACHE_MIN_ESTIMATED_QUERIES_NUMBER)
    return min_result_data_size;
  ulong avg_result = (query_cache_size - free_memory) / queries_in_cache;
  avg_result = min(avg_result, query_cache_limit);
  return max(min_result_data_size, avg_result);
}

inline ulong Query_cache::get_min_append_result_data_size()
{
  return min_result_data_size;
}

unknown's avatar
unknown committed
1806 1807 1808 1809 1810
/*
  Allocate one or more blocks to hold data
*/

my_bool Query_cache::allocate_data_chain(Query_cache_block **result_block,
unknown's avatar
unknown committed
1811
					 ulong data_len,
1812
					 Query_cache_block *query_block,
1813
					 my_bool first_block_arg)
unknown's avatar
unknown committed
1814
{
unknown's avatar
unknown committed
1815 1816
  ulong all_headers_len = (ALIGN_SIZE(sizeof(Query_cache_block)) +
			   ALIGN_SIZE(sizeof(Query_cache_result)));
1817 1818
  ulong len= data_len + all_headers_len;
  ulong align_len= ALIGN_SIZE(len);
unknown's avatar
unknown committed
1819 1820
  DBUG_ENTER("Query_cache::allocate_data_chain");
  DBUG_PRINT("qcache", ("data_len %lu, all_headers_len %lu",
unknown's avatar
unknown committed
1821 1822
		      data_len, all_headers_len));

1823
  ulong min_size = (first_block_arg ?
1824 1825
		    get_min_first_result_data_size():
		    get_min_append_result_data_size());
1826
  *result_block = allocate_block(max(min_size, align_len),
unknown's avatar
unknown committed
1827 1828 1829 1830
				 min_result_data_size == 0,
				 all_headers_len + min_result_data_size,
				 1);
  my_bool success = (*result_block != 0);
unknown's avatar
unknown committed
1831 1832
  if (success)
  {
unknown's avatar
unknown committed
1833 1834 1835 1836 1837 1838
    Query_cache_block *new_block= *result_block;
    new_block->n_tables = 0;
    new_block->used = 0;
    new_block->type = Query_cache_block::RES_INCOMPLETE;
    new_block->next = new_block->prev = new_block;
    Query_cache_result *header = new_block->result();
unknown's avatar
unknown committed
1839 1840
    header->parent(query_block);

unknown's avatar
unknown committed
1841
    if (new_block->length < len)
unknown's avatar
unknown committed
1842 1843
    {
      /*
unknown's avatar
unknown committed
1844 1845
	We got less memory then we need (no big memory blocks) =>
	Continue to allocated more blocks until we got everything we need.
unknown's avatar
unknown committed
1846
      */
unknown's avatar
unknown committed
1847 1848 1849
      Query_cache_block *next_block;
      if ((success = allocate_data_chain(&next_block,
					 len - new_block->length,
1850
					 query_block, first_block_arg)))
unknown's avatar
unknown committed
1851
	double_linked_list_join(new_block, next_block);
unknown's avatar
unknown committed
1852 1853 1854
    }
    if (success)
    {
unknown's avatar
unknown committed
1855
      new_block->used = min(len, new_block->length);
unknown's avatar
unknown committed
1856

unknown's avatar
unknown committed
1857 1858
      DBUG_PRINT("qcache", ("Block len %lu used %lu",
			  new_block->length, new_block->used));
unknown's avatar
unknown committed
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
    }
    else
      DBUG_PRINT("warning", ("Can't allocate block for continue"));
  }
  else
    DBUG_PRINT("warning", ("Can't allocate block for results"));
  DBUG_RETURN(success);
}

/*****************************************************************************
unknown's avatar
unknown committed
1869 1870 1871 1872 1873 1874
  Tables management
*****************************************************************************/

/*
  Invalidate the first table in the table_list
*/
unknown's avatar
unknown committed
1875 1876 1877 1878

void Query_cache::invalidate_table(TABLE_LIST *table_list)
{
  if (table_list->table != 0)
unknown's avatar
unknown committed
1879
    invalidate_table(table_list->table);	// Table is open
unknown's avatar
unknown committed
1880 1881
  else
  {
unknown's avatar
unknown committed
1882
    char key[MAX_DBKEY_LENGTH];
unknown's avatar
unknown committed
1883 1884 1885 1886 1887
    uint key_length;
    Query_cache_block *table_block;
    key_length=(uint) (strmov(strmov(key,table_list->db)+1,
			      table_list->real_name) -key)+ 1;

unknown's avatar
unknown committed
1888
    // We don't store temporary tables => no key_length+=4 ...
unknown's avatar
unknown committed
1889
    if ((table_block = (Query_cache_block*)
unknown's avatar
unknown committed
1890
	 hash_search(&tables,(byte*) key,key_length)))
unknown's avatar
unknown committed
1891 1892 1893 1894 1895
      invalidate_table(table_block);
  }
}

void Query_cache::invalidate_table(TABLE *table)
1896 1897 1898 1899 1900
{
  invalidate_table((byte*) table->table_cache_key, table->key_length);
}

void Query_cache::invalidate_table(byte * key, uint32  key_length)
unknown's avatar
unknown committed
1901 1902
{
  Query_cache_block *table_block;
unknown's avatar
unknown committed
1903
  if ((table_block = ((Query_cache_block*)
1904
		      hash_search(&tables, key, key_length))))
unknown's avatar
unknown committed
1905 1906 1907 1908 1909
    invalidate_table(table_block);
}

void Query_cache::invalidate_table(Query_cache_block *table_block)
{
unknown's avatar
unknown committed
1910 1911
  Query_cache_block_table *list_root =	table_block->table(0);
  while (list_root->next != list_root)
unknown's avatar
unknown committed
1912
  {
unknown's avatar
unknown committed
1913
    Query_cache_block *query_block = list_root->next->block();
unknown's avatar
unknown committed
1914 1915 1916 1917 1918
    BLOCK_LOCK_WR(query_block);
    free_query(query_block);
  }
}

1919 1920 1921 1922 1923 1924 1925 1926 1927
/*
  Store all used tables

  SYNOPSIS
    register_all_tables()
    block		Store tables in this block
    tables_used		List if used tables
    tables_arg		Not used ?
*/
unknown's avatar
unknown committed
1928 1929 1930

my_bool Query_cache::register_all_tables(Query_cache_block *block,
					 TABLE_LIST *tables_used,
1931
					 TABLE_COUNTER_TYPE tables_arg)
unknown's avatar
unknown committed
1932
{
unknown's avatar
unknown committed
1933 1934
  TABLE_COUNTER_TYPE n;
  DBUG_PRINT("qcache", ("register tables block 0x%lx, n %d, header %x",
1935
		      (ulong) block, (int) tables_arg,
unknown's avatar
unknown committed
1936
		      (int) ALIGN_SIZE(sizeof(Query_cache_block))));
unknown's avatar
unknown committed
1937

unknown's avatar
unknown committed
1938 1939 1940
  Query_cache_block_table *block_table = block->table(0);

  for (n=0; tables_used; tables_used=tables_used->next, n++, block_table++)
unknown's avatar
unknown committed
1941
  {
unknown's avatar
unknown committed
1942
    DBUG_PRINT("qcache",
unknown's avatar
unknown committed
1943
	       ("table %s, db %s, openinfo at 0x%lx, keylen %u, key at 0x%lx",
unknown's avatar
unknown committed
1944 1945 1946 1947
		tables_used->real_name, tables_used->db,
		(ulong) tables_used->table,
		tables_used->table->key_length,
		(ulong) tables_used->table->table_cache_key));
unknown's avatar
unknown committed
1948
    block_table->n=n;
unknown's avatar
unknown committed
1949 1950
    if (!insert_table(tables_used->table->key_length,
		      tables_used->table->table_cache_key, block_table,
1951 1952
		      tables_used->db_length,
		      tables_used->table->file->table_cache_type()))
unknown's avatar
unknown committed
1953
      break;
unknown's avatar
unknown committed
1954 1955

    if (tables_used->table->db_type == DB_TYPE_MRG_MYISAM)
unknown's avatar
unknown committed
1956
    {
unknown's avatar
unknown committed
1957
      ha_myisammrg *handler = (ha_myisammrg *) tables_used->table->file;
unknown's avatar
unknown committed
1958
      MYRG_INFO *file = handler->myrg_info();
unknown's avatar
unknown committed
1959 1960 1961
      for (MYRG_TABLE *table = file->open_tables;
	   table != file->end_table ;
	   table++)
unknown's avatar
unknown committed
1962 1963
      {
	char key[MAX_DBKEY_LENGTH];
1964
	uint32 db_length;
1965
	uint key_length= filename_2_table_key(key, table->table->filename,
1966
					      &db_length);
unknown's avatar
unknown committed
1967
	(++block_table)->n= ++n;
unknown's avatar
unknown committed
1968
	if (!insert_table(key_length, key, block_table,
1969 1970
			  db_length,
			  tables_used->table->file->table_cache_type()))
unknown's avatar
unknown committed
1971 1972 1973 1974
	  goto err;
      }
    }
  }
unknown's avatar
unknown committed
1975

unknown's avatar
unknown committed
1976
err:
unknown's avatar
unknown committed
1977 1978 1979 1980 1981 1982 1983 1984
  if (tables_used)
  {
    DBUG_PRINT("qcache", ("failed at table %d", (int) n));
    /* Unlink the tables we allocated above */
    for (Query_cache_block_table *tmp = block->table(0) ;
	 tmp != block_table;
	 tmp++)
      unlink_table(tmp);
unknown's avatar
unknown committed
1985
  }
unknown's avatar
unknown committed
1986
  return (tables_used == 0);
unknown's avatar
unknown committed
1987 1988
}

unknown's avatar
unknown committed
1989 1990 1991 1992 1993 1994 1995 1996
/*
  Insert used tablename in cache
  Returns 0 on error
*/

my_bool
Query_cache::insert_table(uint key_len, char *key,
			  Query_cache_block_table *node,
1997
			  uint32 db_length, uint8 cache_type)
unknown's avatar
unknown committed
1998 1999
{
  DBUG_ENTER("Query_cache::insert_table");
unknown's avatar
unknown committed
2000
  DBUG_PRINT("qcache", ("insert table node 0x%lx, len %d",
unknown's avatar
unknown committed
2001
		      (ulong)node, key_len));
unknown's avatar
unknown committed
2002 2003

  Query_cache_block *table_block = ((Query_cache_block *)
unknown's avatar
unknown committed
2004 2005
				    hash_search(&tables, (byte*) key,
						key_len));
unknown's avatar
unknown committed
2006 2007 2008

  if (table_block == 0)
  {
unknown's avatar
unknown committed
2009 2010
    DBUG_PRINT("qcache", ("new table block from 0x%lx (%u)",
			(ulong) key, (int) key_len));
unknown's avatar
unknown committed
2011 2012 2013 2014 2015 2016
    table_block = write_block_data(key_len, (gptr) key,
				   ALIGN_SIZE(sizeof(Query_cache_table)),
				   Query_cache_block::TABLE,
				   1, 1);
    if (table_block == 0)
    {
unknown's avatar
unknown committed
2017
      DBUG_PRINT("qcache", ("Can't write table name to cache"));
unknown's avatar
unknown committed
2018 2019
      DBUG_RETURN(0);
    }
unknown's avatar
unknown committed
2020
    Query_cache_table *header = table_block->table();
unknown's avatar
unknown committed
2021
    double_linked_list_simple_include(table_block,
2022
				      &tables_blocks);
unknown's avatar
unknown committed
2023
    Query_cache_block_table *list_root = table_block->table(0);
unknown's avatar
unknown committed
2024 2025
    list_root->n = 0;
    list_root->next = list_root->prev = list_root;
unknown's avatar
unknown committed
2026
    if (hash_insert(&tables, (const byte *) table_block))
unknown's avatar
unknown committed
2027
    {
unknown's avatar
unknown committed
2028
      DBUG_PRINT("qcache", ("Can't insert table to hash"));
unknown's avatar
unknown committed
2029 2030 2031 2032
      // write_block_data return locked block
      free_memory_block(table_block);
      DBUG_RETURN(0);
    }
unknown's avatar
unknown committed
2033
    char *db = header->db();
2034
    header->table(db + db_length + 1);
2035 2036
    header->key_length(key_len);
    header->type(cache_type);
unknown's avatar
unknown committed
2037 2038
  }

unknown's avatar
unknown committed
2039 2040 2041 2042 2043
  Query_cache_block_table *list_root = table_block->table(0);
  node->next = list_root->next;
  list_root->next = node;
  node->next->prev = node;
  node->prev = list_root;
unknown's avatar
unknown committed
2044 2045 2046 2047
  node->parent = table_block->table();
  DBUG_RETURN(1);
}

unknown's avatar
unknown committed
2048 2049

void Query_cache::unlink_table(Query_cache_block_table *node)
unknown's avatar
unknown committed
2050
{
unknown's avatar
unknown committed
2051
  DBUG_ENTER("Query_cache::unlink_table");
unknown's avatar
unknown committed
2052 2053 2054
  node->prev->next = node->next;
  node->next->prev = node->prev;
  Query_cache_block_table *neighbour = node->next;
unknown's avatar
unknown committed
2055 2056
  if (neighbour->next == neighbour)
  {
unknown's avatar
unknown committed
2057 2058
    // list is empty (neighbor is root of list)
    Query_cache_block *table_block = neighbour->block();
unknown's avatar
unknown committed
2059
    double_linked_list_exclude(table_block,
2060
			       &tables_blocks);
unknown's avatar
unknown committed
2061 2062 2063
    hash_delete(&tables,(byte *) table_block);
    free_memory_block(table_block);
  }
unknown's avatar
unknown committed
2064
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
2065 2066 2067
}

/*****************************************************************************
unknown's avatar
unknown committed
2068 2069
  Free memory management
*****************************************************************************/
unknown's avatar
unknown committed
2070

unknown's avatar
unknown committed
2071 2072 2073
Query_cache_block *
Query_cache::allocate_block(ulong len, my_bool not_less, ulong min,
			    my_bool under_guard)
unknown's avatar
unknown committed
2074
{
2075
  DBUG_ENTER("Query_cache::allocate_block");
unknown's avatar
unknown committed
2076
  DBUG_PRINT("qcache", ("len %lu, not less %d, min %lu, uder_guard %d",
unknown's avatar
unknown committed
2077 2078 2079 2080
		      len, not_less,min,under_guard));

  if (len >= min(query_cache_size, query_cache_limit))
  {
unknown's avatar
unknown committed
2081
    DBUG_PRINT("qcache", ("Query cache hase only %lu memory and limit %lu",
unknown's avatar
unknown committed
2082 2083 2084 2085
			query_cache_size, query_cache_limit));
    DBUG_RETURN(0); // in any case we don't have such piece of memory
  }

unknown's avatar
unknown committed
2086 2087
  if (!under_guard)
    STRUCT_LOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
2088

unknown's avatar
unknown committed
2089 2090 2091
  /* Free old queries until we have enough memory to store this block */
  Query_cache_block *block;
  do
unknown's avatar
unknown committed
2092
  {
unknown's avatar
unknown committed
2093
    block= get_free_block(len, not_less, min);
unknown's avatar
unknown committed
2094
  }
unknown's avatar
unknown committed
2095
  while (block == 0 && !free_old_query());
unknown's avatar
unknown committed
2096

unknown's avatar
unknown committed
2097
  if (block != 0)				// If we found a suitable block
unknown's avatar
unknown committed
2098
  {
2099
    if (block->length >= ALIGN_SIZE(len) + min_allocation_unit)
unknown's avatar
unknown committed
2100 2101 2102
      split_block(block,ALIGN_SIZE(len));
  }

unknown's avatar
unknown committed
2103 2104
  if (!under_guard)
    STRUCT_UNLOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
2105 2106 2107
  DBUG_RETURN(block);
}

unknown's avatar
unknown committed
2108 2109 2110

Query_cache_block *
Query_cache::get_free_block(ulong len, my_bool not_less, ulong min)
unknown's avatar
unknown committed
2111 2112
{
  Query_cache_block *block = 0, *first = 0;
unknown's avatar
unknown committed
2113 2114
  DBUG_ENTER("Query_cache::get_free_block");
  DBUG_PRINT("qcache",("length %lu, not_less %d, min %lu", len,
unknown's avatar
unknown committed
2115 2116
		     (int)not_less, min));

unknown's avatar
unknown committed
2117
  /* Find block with minimal size > len  */
unknown's avatar
unknown committed
2118 2119 2120 2121
  uint start = find_bin(len);
  // try matching bin
  if (bins[start].number != 0)
  {
unknown's avatar
unknown committed
2122
    Query_cache_block *list = bins[start].free_blocks;
unknown's avatar
unknown committed
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
    if (list->prev->length >= len) // check block with max size 
    { 
      first = list;
      uint n = 0;
      while ( n < QUERY_CACHE_MEM_BIN_TRY &&
	      first->length < len) //we don't need irst->next != list
      {
	first=first->next;
	n++;
      }
      if (first->length >= len)
	block=first;
      else // we don't need if (first->next != list)
      {
	n = 0;
	block = list->prev;
	while (n < QUERY_CACHE_MEM_BIN_TRY &&
	       block->length > len)
	{
	  block=block->prev;
	  n++;
	}
2145
	if (block->length < len)
unknown's avatar
unknown committed
2146 2147 2148 2149 2150
	  block=block->next;
      }
    }
    else
      first = list->prev;
unknown's avatar
unknown committed
2151 2152 2153
  }
  if (block == 0 && start > 0)
  {
unknown's avatar
unknown committed
2154 2155
    DBUG_PRINT("qcache",("Try bins with bigger block size"));
    // Try more big bins
unknown's avatar
unknown committed
2156
    int i = start - 1;
unknown's avatar
unknown committed
2157
    while (i > 0 && bins[i].number == 0)
unknown's avatar
unknown committed
2158 2159 2160 2161
      i--;
    if (bins[i].number > 0)
      block = bins[i].free_blocks;
  }
unknown's avatar
unknown committed
2162 2163

  // If no big blocks => try less size (if it is possible)
unknown's avatar
unknown committed
2164 2165
  if (block == 0 && ! not_less)
  {
unknown's avatar
unknown committed
2166
    DBUG_PRINT("qcache",("Try to allocate a smaller block"));
unknown's avatar
unknown committed
2167 2168 2169 2170 2171
    if (first != 0 && first->length > min)
      block = first;
    else
    {
      uint i = start + 1;
unknown's avatar
unknown committed
2172 2173 2174
      /* bins[mem_bin_num].number contains 1 for easy end test */
      for (i= start+1 ; bins[i].number == 0 ; i++) ;
      if (i < mem_bin_num && bins[i].free_blocks->prev->length >= min)
unknown's avatar
unknown committed
2175 2176 2177 2178 2179 2180
	block = bins[i].free_blocks->prev;
    }
  }
  if (block != 0)
    exclude_from_free_memory_list(block);

unknown's avatar
unknown committed
2181
  DBUG_PRINT("qcache",("getting block 0x%lx", (ulong) block));
unknown's avatar
unknown committed
2182 2183 2184
  DBUG_RETURN(block);
}

unknown's avatar
unknown committed
2185 2186

void Query_cache::free_memory_block(Query_cache_block *block)
unknown's avatar
unknown committed
2187
{
unknown's avatar
unknown committed
2188
  DBUG_ENTER("Query_cache::free_memory_block");
unknown's avatar
unknown committed
2189
  block->used=0;
unknown's avatar
unknown committed
2190
  DBUG_PRINT("qcache",("first_block 0x%lx, block 0x%lx, pnext 0x%lx pprev 0x%lx",
unknown's avatar
unknown committed
2191 2192
		     (ulong) first_block, (ulong) block,block->pnext,
		     (ulong) block->pprev));
unknown's avatar
unknown committed
2193

unknown's avatar
unknown committed
2194 2195 2196 2197 2198 2199 2200 2201
  if (block->pnext != first_block && block->pnext->is_free())
    block = join_free_blocks(block, block->pnext);
  if (block != first_block && block->pprev->is_free())
    block = join_free_blocks(block->pprev, block->pprev);
  insert_into_free_memory_list(block);
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
2202

2203
void Query_cache::split_block(Query_cache_block *block, ulong len)
unknown's avatar
unknown committed
2204 2205
{
  DBUG_ENTER("Query_cache::split_block");
unknown's avatar
unknown committed
2206
  Query_cache_block *new_block = (Query_cache_block*)(((byte*) block)+len);
unknown's avatar
unknown committed
2207 2208

  new_block->init(block->length - len);
unknown's avatar
unknown committed
2209
  total_blocks++;
unknown's avatar
unknown committed
2210
  block->length=len;
unknown's avatar
unknown committed
2211 2212 2213 2214
  new_block->pnext = block->pnext;
  block->pnext = new_block;
  new_block->pprev = block;
  new_block->pnext->pprev = new_block;
unknown's avatar
unknown committed
2215

2216
  if (block->type == Query_cache_block::FREE)
2217
  {
2218 2219
    // if block was free then it already joined with all free neighbours
    insert_into_free_memory_list(new_block);
2220
  }
2221 2222
  else
    free_memory_block(new_block);
unknown's avatar
unknown committed
2223

unknown's avatar
unknown committed
2224
  DBUG_PRINT("qcache", ("split 0x%lx (%lu) new 0x%lx",
unknown's avatar
unknown committed
2225 2226 2227 2228
		      (ulong) block, len, (ulong) new_block));
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
2229

unknown's avatar
unknown committed
2230
Query_cache_block *
2231
Query_cache::join_free_blocks(Query_cache_block *first_block_arg,
unknown's avatar
unknown committed
2232
			      Query_cache_block *block_in_list)
unknown's avatar
unknown committed
2233
{
unknown's avatar
unknown committed
2234
  Query_cache_block *second_block;
unknown's avatar
unknown committed
2235
  DBUG_ENTER("Query_cache::join_free_blocks");
unknown's avatar
unknown committed
2236
  DBUG_PRINT("qcache",
unknown's avatar
unknown committed
2237
	     ("join first 0x%lx, pnext 0x%lx, in list 0x%lx",
2238
	      (ulong) first_block_arg, (ulong) first_block_arg->pnext,
unknown's avatar
unknown committed
2239 2240
	      (ulong) block_in_list));

unknown's avatar
unknown committed
2241
  exclude_from_free_memory_list(block_in_list);
2242
  second_block = first_block_arg->pnext;
unknown's avatar
unknown committed
2243 2244
  // May be was not free block
  second_block->used=0;
unknown's avatar
unknown committed
2245
  second_block->destroy();
unknown's avatar
unknown committed
2246
  total_blocks--;
unknown's avatar
unknown committed
2247

2248 2249 2250
  first_block_arg->length += second_block->length;
  first_block_arg->pnext = second_block->pnext;
  second_block->pnext->pprev = first_block_arg;
unknown's avatar
unknown committed
2251

2252
  DBUG_RETURN(first_block_arg);
unknown's avatar
unknown committed
2253 2254
}

unknown's avatar
unknown committed
2255 2256

my_bool Query_cache::append_next_free_block(Query_cache_block *block,
unknown's avatar
unknown committed
2257 2258
					    ulong add_size)
{
unknown's avatar
unknown committed
2259
  Query_cache_block *next_block = block->pnext;
unknown's avatar
unknown committed
2260 2261 2262
  DBUG_ENTER("Query_cache::append_next_free_block");
  DBUG_PRINT("enter", ("block 0x%lx, add_size %lu", (ulong) block,
		       add_size));
unknown's avatar
unknown committed
2263

unknown's avatar
unknown committed
2264
  if (next_block != first_block && next_block->is_free())
unknown's avatar
unknown committed
2265 2266
  {
    ulong old_len = block->length;
unknown's avatar
unknown committed
2267
    exclude_from_free_memory_list(next_block);
unknown's avatar
unknown committed
2268
    next_block->destroy();
unknown's avatar
unknown committed
2269
    total_blocks--;
unknown's avatar
unknown committed
2270 2271 2272 2273 2274

    block->length += next_block->length;
    block->pnext = next_block->pnext;
    next_block->pnext->pprev = block;

unknown's avatar
unknown committed
2275
    if (block->length > ALIGN_SIZE(old_len + add_size) + min_allocation_unit)
unknown's avatar
unknown committed
2276 2277 2278 2279
      split_block(block,ALIGN_SIZE(old_len + add_size));
    DBUG_PRINT("exit", ("block was appended"));
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
2280
  DBUG_RETURN(0);
unknown's avatar
unknown committed
2281 2282
}

unknown's avatar
unknown committed
2283 2284

void Query_cache::exclude_from_free_memory_list(Query_cache_block *free_block)
unknown's avatar
unknown committed
2285 2286
{
  DBUG_ENTER("Query_cache::exclude_from_free_memory_list");
unknown's avatar
unknown committed
2287 2288 2289
  Query_cache_memory_bin *bin = *((Query_cache_memory_bin **)
				  free_block->data());
  double_linked_list_exclude(free_block, &bin->free_blocks);
unknown's avatar
unknown committed
2290 2291
  bin->number--;
  free_memory-=free_block->length;
unknown's avatar
unknown committed
2292
  free_memory_blocks--;
unknown's avatar
unknown committed
2293 2294
  DBUG_PRINT("qcache",("exclude block 0x%lx, bin 0x%lx", (ulong) free_block,
		     (ulong) bin));
unknown's avatar
unknown committed
2295 2296 2297
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
2298
void Query_cache::insert_into_free_memory_list(Query_cache_block *free_block)
unknown's avatar
unknown committed
2299 2300 2301
{
  DBUG_ENTER("Query_cache::insert_into_free_memory_list");
  uint idx = find_bin(free_block->length);
unknown's avatar
unknown committed
2302
  insert_into_free_memory_sorted_list(free_block, &bins[idx].free_blocks);
unknown's avatar
unknown committed
2303
  /*
unknown's avatar
unknown committed
2304
    We have enough memory in block for storing bin reference due to
unknown's avatar
unknown committed
2305 2306
    min_allocation_unit choice
  */
unknown's avatar
unknown committed
2307 2308 2309 2310 2311 2312
  Query_cache_memory_bin **bin_ptr = ((Query_cache_memory_bin**)
				      free_block->data());
  *bin_ptr = bins+idx;
  (*bin_ptr)->number++;
  DBUG_PRINT("qcache",("insert block 0x%lx, bin[%d] 0x%lx",
		     (ulong) free_block, idx, (ulong) *bin_ptr));
unknown's avatar
unknown committed
2313 2314 2315 2316 2317 2318
  DBUG_VOID_RETURN;
}

uint Query_cache::find_bin(ulong size)
{
  DBUG_ENTER("Query_cache::find_bin");
unknown's avatar
unknown committed
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
  // Binary search
  int left = 0, right = mem_bin_steps;
  do
  {
    int middle = (left + right) / 2;
    if (steps[middle].size > size)
      left = middle+1;
    else
      right = middle;
  } while (left < right);
  if (left == 0)
unknown's avatar
unknown committed
2330 2331
  {
    // first bin not subordinate of common rules
unknown's avatar
unknown committed
2332
    DBUG_PRINT("qcache", ("first bin (# 0), size %lu",size));
unknown's avatar
unknown committed
2333 2334
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
2335 2336
  uint bin =  steps[left].idx - 
    (uint)((size - steps[left].size)/steps[left].increment);
2337
#ifndef DBUG_OFF
unknown's avatar
unknown committed
2338
  bins_dump();
2339
#endif
unknown's avatar
unknown committed
2340 2341
  DBUG_PRINT("qcache", ("bin %u step %u, size %lu step size %lu",
			bin, left, size, steps[left].size));
unknown's avatar
unknown committed
2342 2343 2344
  DBUG_RETURN(bin);
}

unknown's avatar
unknown committed
2345

unknown's avatar
unknown committed
2346
/*****************************************************************************
unknown's avatar
unknown committed
2347 2348
 Lists management
*****************************************************************************/
unknown's avatar
unknown committed
2349

unknown's avatar
unknown committed
2350
void Query_cache::move_to_query_list_end(Query_cache_block *query_block)
unknown's avatar
unknown committed
2351 2352
{
  DBUG_ENTER("Query_cache::move_to_query_list_end");
unknown's avatar
unknown committed
2353 2354
  double_linked_list_exclude(query_block, &queries_blocks);
  double_linked_list_simple_include(query_block, &queries_blocks);
unknown's avatar
unknown committed
2355 2356 2357
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
2358

unknown's avatar
unknown committed
2359 2360
void Query_cache::insert_into_free_memory_sorted_list(Query_cache_block *
						      new_block,
unknown's avatar
unknown committed
2361 2362
						      Query_cache_block **
						      list)
unknown's avatar
unknown committed
2363 2364 2365 2366
{
  DBUG_ENTER("Query_cache::insert_into_free_memory_sorted_list");
  /*
     list sorted by size in ascendant order, because we need small blocks
unknown's avatar
unknown committed
2367
     more frequently than bigger ones
unknown's avatar
unknown committed
2368 2369 2370 2371 2372 2373
  */

  new_block->used = 0;
  new_block->n_tables = 0;
  new_block->type = Query_cache_block::FREE;

unknown's avatar
unknown committed
2374
  if (*list == 0)
unknown's avatar
unknown committed
2375
  {
unknown's avatar
unknown committed
2376 2377
    *list = new_block->next=new_block->prev=new_block;
    DBUG_PRINT("qcache", ("inserted into empty list"));
unknown's avatar
unknown committed
2378 2379 2380
  }
  else
  {
unknown's avatar
unknown committed
2381
    Query_cache_block *point = *list;
unknown's avatar
unknown committed
2382 2383 2384
    if (point->length >= new_block->length)
    {
      point = point->prev;
unknown's avatar
unknown committed
2385
      *list = new_block;
unknown's avatar
unknown committed
2386 2387 2388
    }
    else
    {
unknown's avatar
unknown committed
2389 2390 2391
      /* Find right position in sorted list to put block */
      while (point->next != *list &&
	     point->next->length < new_block->length)
unknown's avatar
unknown committed
2392 2393
	point=point->next;
    }
unknown's avatar
unknown committed
2394 2395 2396 2397
    new_block->prev = point;
    new_block->next = point->next;
    new_block->next->prev = new_block;
    point->next = new_block;
unknown's avatar
unknown committed
2398 2399
  }
  free_memory+=new_block->length;
unknown's avatar
unknown committed
2400
  free_memory_blocks++;
unknown's avatar
unknown committed
2401 2402 2403 2404 2405
  DBUG_VOID_RETURN;
}


void
unknown's avatar
unknown committed
2406 2407 2408
Query_cache::double_linked_list_simple_include(Query_cache_block *point,
						Query_cache_block **
						list_pointer)
unknown's avatar
unknown committed
2409 2410
{
  DBUG_ENTER("Query_cache::double_linked_list_simple_include");
unknown's avatar
unknown committed
2411 2412 2413
  DBUG_PRINT("qcache", ("including block 0x%lx", (ulong) point));
  if (*list_pointer == 0)
    *list_pointer=point->next=point->prev=point;
unknown's avatar
unknown committed
2414 2415
  else
  {
unknown's avatar
unknown committed
2416
    // insert to the end of list
unknown's avatar
unknown committed
2417 2418
    point->next = (*list_pointer);
    point->prev = (*list_pointer)->prev;
unknown's avatar
unknown committed
2419
    point->prev->next = point;
unknown's avatar
unknown committed
2420
    (*list_pointer)->prev = point;
unknown's avatar
unknown committed
2421 2422 2423 2424 2425 2426
  }
  DBUG_VOID_RETURN;
}

void
Query_cache::double_linked_list_exclude(Query_cache_block *point,
unknown's avatar
unknown committed
2427
					Query_cache_block **list_pointer)
unknown's avatar
unknown committed
2428 2429
{
  DBUG_ENTER("Query_cache::double_linked_list_exclude");
unknown's avatar
unknown committed
2430
  DBUG_PRINT("qcache", ("excluding block 0x%lx, list 0x%lx",
unknown's avatar
unknown committed
2431 2432
		      (ulong) point, (ulong) list_pointer));
  if (point->next == point)
unknown's avatar
unknown committed
2433
    *list_pointer = 0;				// empty list
unknown's avatar
unknown committed
2434 2435 2436 2437
  else
  {
    point->next->prev = point->prev;
    point->prev->next = point->next;
unknown's avatar
unknown committed
2438 2439
    if (point == *list_pointer)
      *list_pointer = point->next;
unknown's avatar
unknown committed
2440 2441 2442 2443
  }
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
2444

unknown's avatar
unknown committed
2445 2446 2447 2448
void Query_cache::double_linked_list_join(Query_cache_block *head_tail,
					  Query_cache_block *tail_head)
{
  Query_cache_block *head_head = head_tail->next,
unknown's avatar
unknown committed
2449
		    *tail_tail	= tail_head->prev;
unknown's avatar
unknown committed
2450 2451 2452 2453 2454 2455 2456
  head_head->prev = tail_tail;
  head_tail->next = tail_head;
  tail_head->prev = head_tail;
  tail_tail->next = head_head;
}

/*****************************************************************************
unknown's avatar
unknown committed
2457 2458
 Query
*****************************************************************************/
unknown's avatar
unknown committed
2459 2460

/*
2461
  If query is cacheable return number tables in query
unknown's avatar
unknown committed
2462
  (query without tables are not cached)
unknown's avatar
unknown committed
2463
*/
unknown's avatar
unknown committed
2464 2465 2466

TABLE_COUNTER_TYPE Query_cache::is_cacheable(THD *thd, uint32 query_len,
					     char *query,
2467 2468 2469
					     LEX *lex,
					     TABLE_LIST *tables_used,
					     uint8 *tables_type)
unknown's avatar
unknown committed
2470
{
2471
  TABLE_COUNTER_TYPE table_count = 0;
unknown's avatar
unknown committed
2472 2473
  DBUG_ENTER("Query_cache::is_cacheable");

unknown's avatar
unknown committed
2474
  if (lex->sql_command == SQLCOM_SELECT &&
unknown's avatar
unknown committed
2475
      (thd->variables.query_cache_type == 1 ||
2476
       (thd->variables.query_cache_type == 2 && (lex->select_lex.options &
unknown's avatar
unknown committed
2477
						 OPTION_TO_QUERY_CACHE))) &&
2478
      lex->safe_to_cache_query)
unknown's avatar
unknown committed
2479
  {
unknown's avatar
unknown committed
2480
    DBUG_PRINT("qcache", ("options %lx %lx, type %u",
unknown's avatar
unknown committed
2481
			OPTION_TO_QUERY_CACHE,
2482
			lex->select_lex.options,
unknown's avatar
unknown committed
2483
			(int) thd->variables.query_cache_type));
unknown's avatar
unknown committed
2484

2485
    for (; tables_used; tables_used= tables_used->next)
unknown's avatar
unknown committed
2486
    {
2487
      table_count++;
unknown's avatar
unknown committed
2488 2489 2490
      DBUG_PRINT("qcache", ("table %s, db %s, type %u",
			  tables_used->real_name,
			  tables_used->db, tables_used->table->db_type));
2491
      *tables_type|= tables_used->table->file->table_cache_type();
unknown's avatar
unknown committed
2492

2493
      if (tables_used->table->db_type == DB_TYPE_MRG_ISAM ||
2494
	  tables_used->table->tmp_table != NO_TMP_TABLE ||
2495 2496
	  (tables_used->db_length == 5 &&
#ifdef FN_NO_CASE_SENCE
unknown's avatar
unknown committed
2497 2498
	   my_strnncoll(system_charset_info, (uchar*)tables_used->db, 6,
					     (uchar*)"mysql",6) == 0
2499 2500 2501 2502 2503 2504 2505 2506
#else
	   tables_used->db[0]=='m' &&
	   tables_used->db[1]=='y' &&
	   tables_used->db[2]=='s' &&
	   tables_used->db[3]=='q' &&
	   tables_used->db[4]=='l'
#endif
	   ))
unknown's avatar
unknown committed
2507
      {
2508
	DBUG_PRINT("qcache", 
2509
		   ("select not cacheable: used MRG_ISAM, temporary or system table(s)"));
unknown's avatar
unknown committed
2510 2511
	DBUG_RETURN(0);
      }
unknown's avatar
unknown committed
2512
      if (tables_used->table->db_type == DB_TYPE_MRG_MYISAM)
unknown's avatar
unknown committed
2513
      {
unknown's avatar
unknown committed
2514
	ha_myisammrg *handler = (ha_myisammrg *)tables_used->table->file;
unknown's avatar
unknown committed
2515
	MYRG_INFO *file = handler->myrg_info();
2516
	table_count+= (file->end_table - file->open_tables);
unknown's avatar
unknown committed
2517 2518 2519
      }
    }

unknown's avatar
unknown committed
2520
    if ((thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) &&
2521
	((*tables_type)&HA_CACHE_TBL_TRANSACT))
unknown's avatar
unknown committed
2522
    {
unknown's avatar
unknown committed
2523
      DBUG_PRINT("qcache", ("not in autocommin mode"));
unknown's avatar
unknown committed
2524 2525
      DBUG_RETURN(0);
    }
2526 2527
    DBUG_PRINT("qcache", ("select is using %d tables", table_count));
    DBUG_RETURN(table_count);
unknown's avatar
unknown committed
2528
  }
unknown's avatar
unknown committed
2529 2530 2531

  DBUG_PRINT("qcache",
	     ("not interesting query: %d or not cacheable, options %lx %lx, type %u",
unknown's avatar
unknown committed
2532 2533
	      (int) lex->sql_command,
	      OPTION_TO_QUERY_CACHE,
2534
	      lex->select_lex.options,
unknown's avatar
unknown committed
2535
	      (int) thd->variables.query_cache_type));
unknown's avatar
unknown committed
2536 2537 2538
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
2539

unknown's avatar
unknown committed
2540
/*****************************************************************************
unknown's avatar
unknown committed
2541 2542
  Packing
*****************************************************************************/
unknown's avatar
unknown committed
2543 2544 2545

void Query_cache::pack_cache()
{
unknown's avatar
unknown committed
2546
  DBUG_ENTER("Query_cache::pack_cache");
unknown's avatar
unknown committed
2547
  STRUCT_LOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
2548 2549
  DBUG_EXECUTE("check_querycache",query_cache.check_integrity(1););

unknown's avatar
unknown committed
2550 2551
  byte *border = 0;
  Query_cache_block *before = 0;
unknown's avatar
unknown committed
2552 2553
  ulong gap = 0;
  my_bool ok = 1;
unknown's avatar
unknown committed
2554
  Query_cache_block *block = first_block;
unknown's avatar
unknown committed
2555 2556
  DUMP(this);

unknown's avatar
unknown committed
2557
  if (first_block)
unknown's avatar
unknown committed
2558
  {
unknown's avatar
unknown committed
2559 2560
    do
    {
unknown's avatar
unknown committed
2561
      Query_cache_block *next=block->pnext;
unknown's avatar
unknown committed
2562
      ok = move_by_type(&border, &before, &gap, block);
unknown's avatar
unknown committed
2563
      block = next;
unknown's avatar
unknown committed
2564
    } while (ok && block != first_block);
unknown's avatar
unknown committed
2565

unknown's avatar
unknown committed
2566 2567 2568 2569
    if (border != 0)
    {
      Query_cache_block *new_block = (Query_cache_block *) border;
      new_block->init(gap);
unknown's avatar
unknown committed
2570
      total_blocks++;
unknown's avatar
unknown committed
2571 2572 2573 2574 2575 2576 2577
      new_block->pnext = before->pnext;
      before->pnext = new_block;
      new_block->pprev = before;
      new_block->pnext->pprev = new_block;
      insert_into_free_memory_list(new_block);
    }
    DUMP(this);
unknown's avatar
unknown committed
2578
  }
unknown's avatar
unknown committed
2579 2580

  DBUG_EXECUTE("check_querycache",query_cache.check_integrity(1););
unknown's avatar
unknown committed
2581 2582 2583 2584
  STRUCT_UNLOCK(&structure_guard_mutex);
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
2585 2586 2587 2588

my_bool Query_cache::move_by_type(byte **border,
				  Query_cache_block **before, ulong *gap,
				  Query_cache_block *block)
unknown's avatar
unknown committed
2589 2590
{
  DBUG_ENTER("Query_cache::move_by_type");
unknown's avatar
unknown committed
2591

unknown's avatar
unknown committed
2592
  my_bool ok = 1;
unknown's avatar
unknown committed
2593
  switch (block->type) {
unknown's avatar
unknown committed
2594
  case Query_cache_block::FREE:
unknown's avatar
unknown committed
2595 2596 2597
  {
    DBUG_PRINT("qcache", ("block 0x%lx FREE", (ulong) block));
    if (*border == 0)
unknown's avatar
unknown committed
2598
    {
unknown's avatar
unknown committed
2599 2600 2601
      *border = (byte *) block;
      *before = block->pprev;
      DBUG_PRINT("qcache", ("gap beginning here"));
unknown's avatar
unknown committed
2602
    }
unknown's avatar
unknown committed
2603 2604 2605 2606 2607
    exclude_from_free_memory_list(block);
    *gap +=block->length;
    block->pprev->pnext=block->pnext;
    block->pnext->pprev=block->pprev;
    block->destroy();
unknown's avatar
unknown committed
2608
    total_blocks--;
unknown's avatar
unknown committed
2609 2610 2611
    DBUG_PRINT("qcache", ("added to gap (%lu)", *gap));
    break;
  }
unknown's avatar
unknown committed
2612
  case Query_cache_block::TABLE:
unknown's avatar
unknown committed
2613 2614 2615
  {
    DBUG_PRINT("qcache", ("block 0x%lx TABLE", (ulong) block));
    if (*border == 0)
unknown's avatar
unknown committed
2616
      break;
unknown's avatar
unknown committed
2617 2618 2619 2620 2621 2622 2623 2624 2625
    ulong len = block->length, used = block->used;
    Query_cache_block_table *list_root = block->table(0);
    Query_cache_block_table *tprev = list_root->prev,
			    *tnext = list_root->next;
    Query_cache_block *prev = block->prev,
		      *next = block->next,
		      *pprev = block->pprev,
		      *pnext = block->pnext,
		      *new_block =(Query_cache_block *) *border;
2626
    uint tablename_offset = block->table()->table() - block->table()->db();
unknown's avatar
unknown committed
2627 2628 2629
    char *data = (char*) block->data();
    byte *key;
    uint key_length;
unknown's avatar
unknown committed
2630
    key=query_cache_table_get_key((byte*) block, &key_length, 0);
unknown's avatar
unknown committed
2631
    hash_search(&tables, (byte*) key, key_length);
unknown's avatar
unknown committed
2632 2633 2634 2635 2636 2637

    block->destroy();
    new_block->init(len);
    new_block->type=Query_cache_block::TABLE;
    new_block->used=used;
    new_block->n_tables=1;
2638
    memmove((char*) new_block->data(), data, len-new_block->headers_len());
unknown's avatar
unknown committed
2639
    relink(block, new_block, next, prev, pnext, pprev);
2640 2641
    if (tables_blocks == block)
      tables_blocks = new_block;
unknown's avatar
unknown committed
2642 2643 2644

    Query_cache_block_table *nlist_root = new_block->table(0);
    nlist_root->n = 0;
unknown's avatar
unknown committed
2645 2646 2647 2648 2649 2650 2651 2652
    nlist_root->next = tnext;
    tnext->prev = nlist_root;
    nlist_root->prev = tprev;
    tprev->next = nlist_root;
    DBUG_PRINT("qcache",
	       ("list_root: 0x%lx tnext 0x%lx tprev 0x%lx tprev->next 0x%lx tnext->prev 0x%lx",
		(ulong) list_root, (ulong) tnext, (ulong) tprev,
		(ulong)tprev->next, (ulong)tnext->prev));
2653 2654 2655 2656 2657
    /*
      Go through all queries that uses this table and change them to
      point to the new table object
    */
    Query_cache_table *new_block_table=new_block->table();
unknown's avatar
unknown committed
2658
    for (;tnext != nlist_root; tnext=tnext->next)
2659
      tnext->parent= new_block_table;
unknown's avatar
unknown committed
2660 2661
    *border += len;
    *before = new_block;
2662 2663
    /* Fix pointer to table name */
    new_block->table()->table(new_block->table()->db() + tablename_offset);
unknown's avatar
unknown committed
2664 2665 2666 2667 2668 2669 2670
    /* Fix hash to point at moved block */
    hash_replace(&tables, tables.current_record, (byte*) new_block);

    DBUG_PRINT("qcache", ("moved %lu bytes to 0x%lx, new gap at 0x%lx",
			len, (ulong) new_block, (ulong) *border));
    break;
  }
unknown's avatar
unknown committed
2671
  case Query_cache_block::QUERY:
unknown's avatar
unknown committed
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
  {
    DBUG_PRINT("qcache", ("block 0x%lx QUERY", (ulong) block));
    if (*border == 0)
      break;
    BLOCK_LOCK_WR(block);
    ulong len = block->length, used = block->used;
    TABLE_COUNTER_TYPE n_tables = block->n_tables;
    Query_cache_block	*prev = block->prev,
			*next = block->next,
			*pprev = block->pprev,
			*pnext = block->pnext,
			*new_block =(Query_cache_block*) *border;
    char *data = (char*) block->data();
    Query_cache_block *first_result_block = ((Query_cache_query *)
					     block->data())->result();
    byte *key;
    uint key_length;
unknown's avatar
unknown committed
2689
    key=query_cache_query_get_key((byte*) block, &key_length, 0);
unknown's avatar
unknown committed
2690
    hash_search(&queries, (byte*) key, key_length);
2691 2692
    // Move table of used tables 
    memmove((char*) new_block->table(0), (char*) block->table(0),
unknown's avatar
unknown committed
2693 2694 2695 2696 2697 2698 2699
	   ALIGN_SIZE(n_tables*sizeof(Query_cache_block_table)));
    block->query()->unlock_n_destroy();
    block->destroy();
    new_block->init(len);
    new_block->type=Query_cache_block::QUERY;
    new_block->used=used;
    new_block->n_tables=n_tables;
2700
    memmove((char*) new_block->data(), data, len - new_block->headers_len());
unknown's avatar
unknown committed
2701 2702 2703 2704
    relink(block, new_block, next, prev, pnext, pprev);
    if (queries_blocks == block)
      queries_blocks = new_block;
    for (TABLE_COUNTER_TYPE j=0; j < n_tables; j++)
unknown's avatar
unknown committed
2705
    {
unknown's avatar
unknown committed
2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717
      Query_cache_block_table *block_table = new_block->table(j);
      block_table->next->prev = block_table;
      block_table->prev->next = block_table;
    }
    DBUG_PRINT("qcache", ("after circle tt"));
    *border += len;
    *before = new_block;
    new_block->query()->result(first_result_block);
    if (first_result_block != 0)
    {
      Query_cache_block *result_block = first_result_block;
      do
unknown's avatar
unknown committed
2718
      {
unknown's avatar
unknown committed
2719 2720 2721 2722
	result_block->result()->parent(new_block);
	result_block = result_block->next;
      } while ( result_block != first_result_block );
    }
unknown's avatar
unknown committed
2723
    Query_cache_query *new_query= ((Query_cache_query *) new_block->data());
unknown's avatar
unknown committed
2724
    my_rwlock_init(&new_query->lock, NULL);
2725

2726 2727 2728 2729
    /* 
      If someone is writing to this block, inform the writer that the block
      has been moved.
    */
unknown's avatar
unknown committed
2730 2731 2732
    NET *net = new_block->query()->writer();
    if (net != 0)
    {
2733
      net->query_cache_query= (gptr) new_block;
unknown's avatar
unknown committed
2734
    }
unknown's avatar
unknown committed
2735 2736 2737 2738 2739 2740
    /* Fix hash to point at moved block */
    hash_replace(&queries, queries.current_record, (byte*) new_block);
    DBUG_PRINT("qcache", ("moved %lu bytes to 0x%lx, new gap at 0x%lx",
			len, (ulong) new_block, (ulong) *border));
    break;
  }
unknown's avatar
unknown committed
2741 2742 2743 2744
  case Query_cache_block::RES_INCOMPLETE:
  case Query_cache_block::RES_BEG:
  case Query_cache_block::RES_CONT:
  case Query_cache_block::RESULT:
unknown's avatar
unknown committed
2745 2746 2747 2748
  {
    DBUG_PRINT("qcache", ("block 0x%lx RES* (%d)", (ulong) block,
			(int) block->type));
    if (*border == 0)
unknown's avatar
unknown committed
2749
      break;
unknown's avatar
unknown committed
2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
    Query_cache_block *query_block = block->result()->parent(),
		      *next = block->next,
		      *prev = block->prev;
    Query_cache_block::block_type type = block->type;
    BLOCK_LOCK_WR(query_block);
    ulong len = block->length, used = block->used;
    Query_cache_block *pprev = block->pprev,
		      *pnext = block->pnext,
		      *new_block =(Query_cache_block*) *border;
    char *data = (char*) block->data();
    block->destroy();
    new_block->init(len);
    new_block->type=type;
    new_block->used=used;
2764
    memmove((char*) new_block->data(), data, len - new_block->headers_len());
unknown's avatar
unknown committed
2765 2766 2767 2768 2769 2770 2771 2772
    relink(block, new_block, next, prev, pnext, pprev);
    new_block->result()->parent(query_block);
    Query_cache_query *query = query_block->query();
    if (query->result() == block)
      query->result(new_block);
    *border += len;
    *before = new_block;
    /* If result writing complete && we have free space in block */
unknown's avatar
unknown committed
2773 2774
    ulong free_space= new_block->length - new_block->used;
    free_space-= free_space % ALIGN_SIZE(1);
unknown's avatar
unknown committed
2775 2776 2777 2778 2779
    if (query->result()->type == Query_cache_block::RESULT &&
	new_block->length > new_block->used &&
	*gap + free_space > min_allocation_unit &&
	new_block->length - free_space > min_allocation_unit)
    {
unknown's avatar
unknown committed
2780 2781 2782 2783
      *border-= free_space;
      *gap+= free_space;
      DBUG_PRINT("qcache",
		 ("rest of result free space added to gap (%lu)", *gap));
unknown's avatar
unknown committed
2784
      new_block->length -= free_space;
unknown's avatar
unknown committed
2785
    }
unknown's avatar
unknown committed
2786 2787 2788 2789 2790
    BLOCK_UNLOCK_WR(query_block);
    DBUG_PRINT("qcache", ("moved %lu bytes to 0x%lx, new gap at 0x%lx",
			len, (ulong) new_block, (ulong) *border));
    break;
  }
unknown's avatar
unknown committed
2791
  default:
unknown's avatar
unknown committed
2792 2793
    DBUG_PRINT("error", ("unexpected block type %d, block 0x%lx",
			 (int)block->type, (ulong) block));
unknown's avatar
unknown committed
2794 2795 2796 2797 2798
    ok = 0;
  }
  DBUG_RETURN(ok);
}

unknown's avatar
unknown committed
2799 2800 2801 2802 2803

void Query_cache::relink(Query_cache_block *oblock,
			 Query_cache_block *nblock,
			 Query_cache_block *next, Query_cache_block *prev,
			 Query_cache_block *pnext, Query_cache_block *pprev)
unknown's avatar
unknown committed
2804
{
unknown's avatar
unknown committed
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
  if (prev == oblock) //check pointer to himself
  {
    nblock->prev = nblock;
    nblock->next = nblock;
  }
  else
  {
    nblock->prev = prev;
    prev->next=nblock;
  }
  if (next != oblock)
  {
    nblock->next = next;
    next->prev=nblock;
  }
unknown's avatar
unknown committed
2820
  nblock->pprev = pprev; // Physical pointer to himself have only 1 free block
unknown's avatar
unknown committed
2821 2822 2823 2824 2825
  nblock->pnext = pnext;
  pprev->pnext=nblock;
  pnext->pprev=nblock;
}

unknown's avatar
unknown committed
2826

unknown's avatar
unknown committed
2827 2828 2829
my_bool Query_cache::join_results(ulong join_limit)
{
  my_bool has_moving = 0;
unknown's avatar
unknown committed
2830 2831
  DBUG_ENTER("Query_cache::join_results");

unknown's avatar
unknown committed
2832 2833 2834
  STRUCT_LOCK(&structure_guard_mutex);
  if (queries_blocks != 0)
  {
unknown's avatar
unknown committed
2835
    Query_cache_block *block = queries_blocks;
unknown's avatar
unknown committed
2836 2837
    do
    {
unknown's avatar
unknown committed
2838
      Query_cache_query *header = block->query();
unknown's avatar
unknown committed
2839 2840 2841 2842 2843
      if (header->result() != 0 &&
	  header->result()->type == Query_cache_block::RESULT &&
	  header->length() > join_limit)
      {
	Query_cache_block *new_result_block =
unknown's avatar
unknown committed
2844
	  get_free_block(ALIGN_SIZE(header->length()) +
unknown's avatar
unknown committed
2845 2846 2847 2848 2849 2850
			 ALIGN_SIZE(sizeof(Query_cache_block)) +
			 ALIGN_SIZE(sizeof(Query_cache_result)), 1, 0);
	if (new_result_block != 0)
	{
	  has_moving = 1;
	  Query_cache_block *first_result = header->result();
unknown's avatar
unknown committed
2851 2852 2853
	  ulong new_len = (header->length() +
			   ALIGN_SIZE(sizeof(Query_cache_block)) +
			   ALIGN_SIZE(sizeof(Query_cache_result)));
unknown's avatar
unknown committed
2854 2855
	  if (new_result_block->length >
	      ALIGN_SIZE(new_len) + min_allocation_unit)
unknown's avatar
unknown committed
2856 2857
	    split_block(new_result_block, ALIGN_SIZE(new_len));
	  BLOCK_LOCK_WR(block);
unknown's avatar
unknown committed
2858 2859 2860 2861 2862 2863
	  header->result(new_result_block);
	  new_result_block->type = Query_cache_block::RESULT;
	  new_result_block->n_tables = 0;
	  new_result_block->used = new_len;

	  new_result_block->next = new_result_block->prev = new_result_block;
unknown's avatar
unknown committed
2864
	  DBUG_PRINT("qcache", ("new block %lu/%lu (%lu)",
unknown's avatar
unknown committed
2865 2866 2867 2868 2869
			      new_result_block->length,
			      new_result_block->used,
			      header->length()));

	  Query_cache_result *new_result = new_result_block->result();
unknown's avatar
unknown committed
2870
	  new_result->parent(block);
unknown's avatar
unknown committed
2871 2872 2873 2874
	  byte *write_to = (byte*) new_result->data();
	  Query_cache_block *result_block = first_result;
	  do
	  {
unknown's avatar
unknown committed
2875 2876
	    ulong len = (result_block->used - result_block->headers_len() -
			 ALIGN_SIZE(sizeof(Query_cache_result)));
unknown's avatar
unknown committed
2877 2878 2879 2880 2881 2882 2883 2884
	    DBUG_PRINT("loop", ("add block %lu/%lu (%lu)",
				result_block->length,
				result_block->used,
				len));
	    memcpy((char *) write_to,
		   (char*) result_block->result()->data(),
		   len);
	    write_to += len;
unknown's avatar
unknown committed
2885
	    Query_cache_block *old_result_block = result_block;
unknown's avatar
unknown committed
2886 2887 2888
	    result_block = result_block->next;
	    free_memory_block(old_result_block);
	  } while (result_block != first_result);
unknown's avatar
unknown committed
2889
	  BLOCK_UNLOCK_WR(block);
unknown's avatar
unknown committed
2890 2891
	}
      }
unknown's avatar
unknown committed
2892 2893
      block = block->next;
    } while ( block != queries_blocks );
unknown's avatar
unknown committed
2894 2895 2896 2897 2898
  }
  STRUCT_UNLOCK(&structure_guard_mutex);
  DBUG_RETURN(has_moving);
}

unknown's avatar
unknown committed
2899

2900 2901
uint Query_cache::filename_2_table_key (char *key, const char *path,
					uint32 *db_length)
unknown's avatar
unknown committed
2902
{
unknown's avatar
unknown committed
2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
  char tablename[FN_REFLEN+2], *filename, *dbname;
  DBUG_ENTER("Query_cache::filename_2_table_key");

  /* Safety if filename didn't have a directory name */
  tablename[0]= FN_LIBCHAR;
  tablename[1]= FN_LIBCHAR;
  /* Convert filename to this OS's format in tablename */
  fn_format(tablename + 2, path, "", "", MY_REPLACE_EXT);
  filename=  tablename + dirname_length(tablename + 2) + 2;
  /* Find start of databasename */
  for (dbname= filename - 2 ; dbname[-1] != FN_LIBCHAR ; dbname--) ;
2914 2915
  *db_length= (filename - dbname) - 1;
  DBUG_PRINT("qcache", ("table '%-.*s.%s'", *db_length, dbname, filename));
unknown's avatar
unknown committed
2916

2917
  DBUG_RETURN((uint) (strmov(strmake(key, dbname, *db_length) + 1,
unknown's avatar
unknown committed
2918 2919 2920 2921 2922 2923 2924
			     filename) -key) + 1);
}

/****************************************************************************
  Functions to be used when debugging
****************************************************************************/

2925 2926 2927 2928 2929 2930 2931
#if defined(DBUG_OFF) && !defined(USE_QUERY_CACHE_INTEGRITY_CHECK)

void wreck(uint line, const char *message) {}
void bins_dump() {}
void cache_dump() {}
void queries_dump() {}
void tables_dump() {}
2932
my_bool check_integrity(bool not_locked) { return 0; }
2933 2934 2935 2936 2937
my_bool in_list(Query_cache_block * root, Query_cache_block * point,
		const char *name) { return 0;}
my_bool in_blocks(Query_cache_block * point) { return 0; }

#else
unknown's avatar
unknown committed
2938 2939 2940

void Query_cache::wreck(uint line, const char *message)
{
unknown's avatar
unknown committed
2941
  THD *thd=current_thd;
unknown's avatar
unknown committed
2942 2943 2944 2945 2946 2947 2948
  DBUG_ENTER("Query_cache::wreck");
  query_cache_size = 0;
  if (*message)
    DBUG_PRINT("error", (" %s", message));
  DBUG_PRINT("warning", ("=================================="));
  DBUG_PRINT("warning", ("%5d QUERY CACHE WRECK => DISABLED",line));
  DBUG_PRINT("warning", ("=================================="));
unknown's avatar
unknown committed
2949 2950
  if (thd)
    thd->killed = 1;
unknown's avatar
unknown committed
2951
  cache_dump();
2952
  /* check_integrity(0); */ /* Can't call it here because of locks */
unknown's avatar
unknown committed
2953
  bins_dump();
unknown's avatar
unknown committed
2954 2955 2956 2957 2958 2959 2960
  DBUG_VOID_RETURN;
}


void Query_cache::bins_dump()
{
  uint i;
unknown's avatar
unknown committed
2961
  
2962
  if (!initialized || query_cache_size == 0)
unknown's avatar
unknown committed
2963 2964 2965 2966 2967
  {
    DBUG_PRINT("qcache", ("Query Cache not initialized"));
    return;
  }

unknown's avatar
unknown committed
2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002
  DBUG_PRINT("qcache", ("mem_bin_num=%u, mem_bin_steps=%u",
		      mem_bin_num, mem_bin_steps));
  DBUG_PRINT("qcache", ("-------------------------"));
  DBUG_PRINT("qcache", ("      size idx       step"));
  DBUG_PRINT("qcache", ("-------------------------"));
  for (i=0; i < mem_bin_steps; i++)
  {
    DBUG_PRINT("qcache", ("%10lu %3d %10lu", steps[i].size, steps[i].idx,
			steps[i].increment));
  }
  DBUG_PRINT("qcache", ("-------------------------"));
  DBUG_PRINT("qcache", ("      size num"));
  DBUG_PRINT("qcache", ("-------------------------"));
  for (i=0; i < mem_bin_num; i++)
  {
    DBUG_PRINT("qcache", ("%10lu %3d 0x%lx", bins[i].size, bins[i].number,
			(ulong)&(bins[i])));
    if (bins[i].free_blocks)
    {
      Query_cache_block *block = bins[i].free_blocks;
      do{
	DBUG_PRINT("qcache", ("\\-- %lu 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx",
			    block->length, (ulong)block,
			    (ulong)block->next, (ulong)block->prev,
			    (ulong)block->pnext, (ulong)block->pprev));
	block = block->next;
      } while ( block != bins[i].free_blocks );
    }
  }
  DBUG_PRINT("qcache", ("-------------------------"));
}


void Query_cache::cache_dump()
{
3003
  if (!initialized || query_cache_size == 0)
unknown's avatar
unknown committed
3004 3005 3006 3007 3008
  {
    DBUG_PRINT("qcache", ("Query Cache not initialized"));
    return;
  }

unknown's avatar
unknown committed
3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025
  DBUG_PRINT("qcache", ("-------------------------------------"));
  DBUG_PRINT("qcache", ("    length       used t nt"));
  DBUG_PRINT("qcache", ("-------------------------------------"));
  Query_cache_block *i = first_block;
  do
  {
    DBUG_PRINT("qcache",
	       ("%10lu %10lu %1d %2d 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx",
		i->length, i->used, (int)i->type,
		i->n_tables, (ulong)i,
		(ulong)i->next, (ulong)i->prev, (ulong)i->pnext,
		(ulong)i->pprev));
    i = i->pnext;
  } while ( i != first_block );
  DBUG_PRINT("qcache", ("-------------------------------------"));
}

unknown's avatar
unknown committed
3026

unknown's avatar
unknown committed
3027 3028
void Query_cache::queries_dump()
{
unknown's avatar
unknown committed
3029

3030
  if (!initialized)
unknown's avatar
unknown committed
3031 3032 3033 3034 3035
  {
    DBUG_PRINT("qcache", ("Query Cache not initialized"));
    return;
  }

unknown's avatar
unknown committed
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045
  DBUG_PRINT("qcache", ("------------------"));
  DBUG_PRINT("qcache", (" QUERIES"));
  DBUG_PRINT("qcache", ("------------------"));
  if (queries_blocks != 0)
  {
    Query_cache_block *block = queries_blocks;
    do
    {
      uint len;
      char *str = (char*) query_cache_query_get_key((byte*) block, &len, 0);
3046 3047 3048 3049
      len--;					// Point at flags
      uint flags = (uint) (uchar) str[len];
      str[len]=0;
      DBUG_PRINT("qcache", ("%u (%u,%u) '%s' '%s'",
unknown's avatar
unknown committed
3050
			  ((flags & QUERY_CACHE_CLIENT_LONG_FLAG_MASK)? 1:0),
3051 3052
			  (flags & QUERY_CACHE_CHARSET_CONVERT_MASK), len,
			    str,strend(str)+1));
unknown's avatar
unknown committed
3053 3054 3055
      DBUG_PRINT("qcache", ("-b- 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx", (ulong) block,
			    (ulong) block->next, (ulong) block->prev,
			    (ulong)block->pnext, (ulong)block->pprev));
3056
      str[len]=(char) flags;
unknown's avatar
unknown committed
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087
      for (TABLE_COUNTER_TYPE t = 0; t < block->n_tables; t++)
      {
	Query_cache_table *table = block->table(t)->parent;
	DBUG_PRINT("qcache", ("-t- '%s' '%s'", table->db(), table->table()));
      }
      Query_cache_query *header = block->query();
      if (header->result())
      {
	Query_cache_block *result_block = header->result();
	Query_cache_block *result_beg = result_block;
	do
	{
	  DBUG_PRINT("qcache", ("-r- %u %lu/%lu 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx",
			      (uint) result_block->type,
			      result_block->length, result_block->used,
			      (ulong) result_block,
			      (ulong) result_block->next,
			      (ulong) result_block->prev,
			      (ulong) result_block->pnext,
			      (ulong) result_block->pprev));
	  result_block = result_block->next;
	} while ( result_block != result_beg );
      }
    } while ((block=block->next) != queries_blocks);
  }
  else
  {
    DBUG_PRINT("qcache", ("no queries in list"));
  }
  DBUG_PRINT("qcache", ("------------------"));
}
unknown's avatar
unknown committed
3088 3089


unknown's avatar
unknown committed
3090 3091
void Query_cache::tables_dump()
{
3092
  if (!initialized || query_cache_size == 0)
unknown's avatar
unknown committed
3093 3094 3095 3096 3097
  {
    DBUG_PRINT("qcache", ("Query Cache not initialized"));
    return;
  }

unknown's avatar
unknown committed
3098 3099 3100
  DBUG_PRINT("qcache", ("--------------------"));
  DBUG_PRINT("qcache", ("TABLES"));
  DBUG_PRINT("qcache", ("--------------------"));
3101
  if (tables_blocks != 0)
unknown's avatar
unknown committed
3102
  {
3103 3104
    Query_cache_block *table_block = tables_blocks;
    do
unknown's avatar
unknown committed
3105
    {
3106 3107 3108 3109
      Query_cache_table *table = table_block->table();
      DBUG_PRINT("qcache", ("'%s' '%s'", table->db(), table->table()));
      table_block = table_block->next;
    } while ( table_block != tables_blocks);
unknown's avatar
unknown committed
3110
  }
3111 3112
  else
    DBUG_PRINT("qcache", ("no tables in list"));
unknown's avatar
unknown committed
3113
  DBUG_PRINT("qcache", ("--------------------"));
unknown's avatar
unknown committed
3114
}
unknown's avatar
unknown committed
3115 3116


3117
my_bool Query_cache::check_integrity(bool not_locked)
unknown's avatar
unknown committed
3118 3119 3120
{
  my_bool result = 0;
  uint i;
3121
  DBUG_ENTER("check_integrity");
unknown's avatar
unknown committed
3122

unknown's avatar
unknown committed
3123
  if (query_cache_size == 0)
unknown's avatar
unknown committed
3124 3125
  {
    DBUG_PRINT("qcache", ("Query Cache not initialized"));
unknown's avatar
merge  
unknown committed
3126
    DBUG_RETURN(0);
unknown's avatar
unknown committed
3127
  }
3128 3129
  if (!not_locked)
    STRUCT_LOCK(&structure_guard_mutex);
unknown's avatar
unknown committed
3130

unknown's avatar
unknown committed
3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149
  if (hash_check(&queries))
  {
    DBUG_PRINT("error", ("queries hash is damaged"));
    result = 1;
  }

  if (hash_check(&tables))
  {
    DBUG_PRINT("error", ("tables hash is damaged"));
    result = 1;
  }

  DBUG_PRINT("qcache", ("physical address check ..."));
  ulong free=0, used=0;
  Query_cache_block * block = first_block;
  do
  {
    DBUG_PRINT("qcache", ("block 0x%lx, type %u...", 
			  (ulong) block, (uint) block->type));  
3150
    // Check allignment
3151 3152
    if ((((long)block) % (long) ALIGN_SIZE(1)) !=
	(((long)first_block) % (long)ALIGN_SIZE(1)))
3153 3154 3155 3156 3157 3158
    {
      DBUG_PRINT("error",
		 ("block 0x%lx do not aligned by %d", (ulong) block,
		  ALIGN_SIZE(1)));
      result = 1;
    }
unknown's avatar
unknown committed
3159 3160 3161
    // Check memory allocation
    if (block->pnext == first_block) // Is it last block?
    {
3162 3163
      if (((byte*)block) + block->length != 
	  ((byte*)first_block) + query_cache_size)
unknown's avatar
unknown committed
3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182
      {
	DBUG_PRINT("error", 
		   ("block 0x%lx, type %u, ended at 0x%lx, but cache ended at 0x%lx",
		    (ulong) block, (uint) block->type, 
		    (ulong) (((byte*)block) + block->length),
		    (ulong) (((byte*)first_block) + query_cache_size)));
	result = 1;
      }
    }
    else
      if (((byte*)block) + block->length != ((byte*)block->pnext))
      {
	DBUG_PRINT("error", 
		   ("block 0x%lx, type %u, ended at 0x%lx, but next block begining at 0x%lx",
		    (ulong) block, (uint) block->type, 
		    (ulong) (((byte*)block) + block->length),
		    (ulong) ((byte*)block->pnext)));
      }
    if (block->type == Query_cache_block::FREE)
3183
      free+= block->length;
unknown's avatar
unknown committed
3184
    else
3185
      used+= block->length;
unknown's avatar
unknown committed
3186 3187 3188 3189 3190 3191
    switch(block->type) {
    case Query_cache_block::FREE:
    {
      Query_cache_memory_bin *bin = *((Query_cache_memory_bin **)
				      block->data());
      //is it correct pointer?
3192
      if (((byte*)bin) < ((byte*)bins) ||
unknown's avatar
unknown committed
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
	  ((byte*)bin) >= ((byte*)first_block))
      {
	DBUG_PRINT("error", 
		   ("free block 0x%lx have bin pointer 0x%lx beyaond of bins array bounds [0x%lx,0x%lx]",
		    (ulong) block, 
		    (ulong) bin,
		    (ulong) bins,
		    (ulong) first_block));
	result = 1;
      }
      else
      {
	int idx = (((byte*)bin) - ((byte*)bins)) /
	  sizeof(Query_cache_memory_bin);
	if (in_list(bins[idx].free_blocks, block, "free memory"))
	  result = 1;
      }
      break;
    }
    case Query_cache_block::TABLE:
3213
      if (in_list(tables_blocks, block, "tables"))
unknown's avatar
unknown committed
3214
	result = 1;
unknown's avatar
unknown committed
3215 3216
      if (in_table_list(block->table(0),  block->table(0), "table list root"))
	result = 1;
unknown's avatar
unknown committed
3217 3218
      break;
    case Query_cache_block::QUERY:
unknown's avatar
unknown committed
3219
    {
unknown's avatar
unknown committed
3220 3221
      if (in_list(queries_blocks, block, "query"))
	result = 1;
unknown's avatar
unknown committed
3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232
      for (TABLE_COUNTER_TYPE j=0; j < block->n_tables; j++)
      {
	Query_cache_block_table *block_table = block->table(j);
	Query_cache_block_table *block_table_root = 
	  (Query_cache_block_table *) 
	  (((byte*)block_table->parent) -
	   ALIGN_SIZE(sizeof(Query_cache_block_table)));
	
    	if (in_table_list(block_table, block_table_root, "table list"))
    	  result = 1;
      }
unknown's avatar
unknown committed
3233
      break;
unknown's avatar
unknown committed
3234
    }
unknown's avatar
unknown committed
3235
    case Query_cache_block::RES_INCOMPLETE:
3236 3237
      // This type of block can be not lincked yet (in multithread environment)
      break;
unknown's avatar
unknown committed
3238 3239 3240 3241 3242
    case Query_cache_block::RES_BEG:
    case Query_cache_block::RES_CONT:
    case Query_cache_block::RESULT:
    {
      Query_cache_block * query_block = block->result()->parent();
3243
      if (((byte*)query_block) < ((byte*)first_block) ||
unknown's avatar
unknown committed
3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255
	  ((byte*)query_block) >= (((byte*)first_block) + query_cache_size))
      {
	DBUG_PRINT("error", 
		   ("result block 0x%lx have query block pointer 0x%lx beyaond of block pool bounds [0x%lx,0x%lx]",
		    (ulong) block,
		    (ulong) query_block,
		    (ulong) first_block,
		    (ulong) (((byte*)first_block) + query_cache_size)));
	result = 1;
      }
      else
      {
3256
	BLOCK_LOCK_RD(query_block);
unknown's avatar
unknown committed
3257 3258 3259 3260 3261
	if (in_list(queries_blocks, query_block, "query from results"))
	  result = 1;
	if (in_list(query_block->query()->result(), block,
		    "results"))
	  result = 1;
3262
	BLOCK_UNLOCK_RD(query_block);
unknown's avatar
unknown committed
3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327
      }
      break;
    }
    default:
      DBUG_PRINT("error",
		 ("block 0x%lx have incorrect type %u",
		  block, block->type));
      result = 1;
    }
    
    block = block->pnext;
  } while (block != first_block);
  
  if (used + free != query_cache_size)
  {
    DBUG_PRINT("error",
	       ("used memory (%lu) + free memory (%lu) !=  query_cache_size (%lu)",
		used, free, query_cache_size));
    result = 1;
  }
  
  if (free != free_memory)
  {
    DBUG_PRINT("error",
	       ("free memory (%lu) != free_memory (%lu)",
		free, free_memory));
    result = 1;
  }

  DBUG_PRINT("qcache", ("check queries ..."));
  if ((block = queries_blocks))
  {
    do
    {
      DBUG_PRINT("qcache", ("block 0x%lx, type %u...", 
			    (ulong) block, (uint) block->type));
      uint length;
      byte *key = query_cache_query_get_key((byte*) block, &length, 0);
      gptr val = hash_search(&queries, key, length);
      if (((gptr)block) != val)
      {
	DBUG_PRINT("error", ("block 0x%lx found in queries hash like 0x%lx",
			     (ulong) block, (ulong) val));
      }
      if (in_blocks(block))
	result = 1;
      Query_cache_block * results = block->query()->result();
      if (results)
      {
	Query_cache_block * result_block = results;
	do
	{
	  DBUG_PRINT("qcache", ("block 0x%lx, type %u...", 
				(ulong) block, (uint) block->type));
	  if (in_blocks(result_block))
	    result = 1;

	  result_block = result_block->next;
	} while (result_block != results);
      }
      block = block->next;
    } while (block != queries_blocks);
  }

  DBUG_PRINT("qcache", ("check tables ..."));
3328
  if ((block = tables_blocks))
unknown's avatar
unknown committed
3329
  {
3330
    do
unknown's avatar
unknown committed
3331
    {
3332 3333 3334 3335 3336 3337
      DBUG_PRINT("qcache", ("block 0x%lx, type %u...", 
			    (ulong) block, (uint) block->type));
      uint length;
      byte *key = query_cache_table_get_key((byte*) block, &length, 0);
      gptr val = hash_search(&tables, key, length);
      if (((gptr)block) != val)
unknown's avatar
unknown committed
3338
      {
3339 3340 3341 3342 3343 3344 3345 3346
	DBUG_PRINT("error", ("block 0x%lx found in tables hash like 0x%lx",
			     (ulong) block, (ulong) val));
      }
      
      if (in_blocks(block))
	result = 1;
      block=block->next;
    } while (block != tables_blocks);
unknown's avatar
unknown committed
3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
  }

  DBUG_PRINT("qcache", ("check free blocks"));
  for (i = 0; i < mem_bin_num; i++)
  {
    if ((block = bins[i].free_blocks))
    {
      uint count = 0;
      do
      {
	DBUG_PRINT("qcache", ("block 0x%lx, type %u...", 
			      (ulong) block, (uint) block->type));
	if (in_blocks(block))
	  result = 1;
	
	count++;
	block=block->next;
      } while (block != bins[i].free_blocks);
      if (count != bins[i].number)
      {
3367 3368
	DBUG_PRINT("error", ("bin[%d].number is %d, but bin have %d blocks",
			     bins[i].number,  count));
unknown's avatar
unknown committed
3369 3370 3371 3372 3373
	result = 1;
      }
    }
  }
  DBUG_ASSERT(result == 0);
3374 3375
  if (!not_locked)
    STRUCT_UNLOCK(&structure_guard_mutex);
3376
  DBUG_RETURN(result);
unknown's avatar
unknown committed
3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
}


my_bool Query_cache::in_blocks(Query_cache_block * point)
{
  my_bool result = 0;
  Query_cache_block *block = point;
  //back
  do
  {
    if (block->pprev->pnext != block)
    {
      DBUG_PRINT("error",
		 ("block 0x%lx in physical list is incorrect linked, prev block 0x%lx refered as next to 0x%lx (check from 0x%lx)",
		  (ulong) block, (ulong) block->pprev,
		  (ulong) block->pprev->pnext,
		  (ulong) point));
      //back trace
3395
      for (; block != point; block = block->pnext)
unknown's avatar
unknown committed
3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422
	    DBUG_PRINT("error", ("back trace 0x%lx", (ulong) block));
      result = 1;
      goto err1;
    }
    block = block->pprev;
  } while (block != first_block && block != point);
  if (block != first_block)
  {
    DBUG_PRINT("error",
	       ("block 0x%lx (0x%lx<-->0x%lx) not owned by pysical list",
		(ulong) block, (ulong) block->pprev, (ulong )block->pnext));
    return 1;
  }

err1:
  //forward
  block = point;
  do
  {
    if (block->pnext->pprev != block)
    {
      DBUG_PRINT("error",
		 ("block 0x%lx in physicel list is incorrect linked, next block 0x%lx refered as prev to 0x%lx (check from 0x%lx)",
		  (ulong) block, (ulong) block->pnext,
		  (ulong) block->pnext->pprev,
		  (ulong) point));
      //back trace
3423
      for (; block != point; block = block->pprev)
unknown's avatar
unknown committed
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451
	    DBUG_PRINT("error", ("back trace 0x%lx", (ulong) block));
      result = 1;
      goto err2;
    }
    block = block->pnext;
  } while (block != first_block);
err2:
  return result;
}


my_bool Query_cache::in_list(Query_cache_block * root,
			     Query_cache_block * point,
			     const char *name)
{
  my_bool result = 0;
  Query_cache_block *block = point;
  //back
  do
  {
    if (block->prev->next != block)
    {
      DBUG_PRINT("error",
		 ("block 0x%lx in list '%s' 0x%lx is incorrect linked, prev block 0x%lx refered as next to 0x%lx (check from 0x%lx)",
		  (ulong) block, name, (ulong) root, (ulong) block->prev,
		  (ulong) block->prev->next,
		  (ulong) point));
      //back trace
3452
      for (; block != point; block = block->next)
unknown's avatar
unknown committed
3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491
	    DBUG_PRINT("error", ("back trace 0x%lx", (ulong) block));
      result = 1;
      goto err1;
    }
    block = block->prev;
  } while (block != root && block != point);
  if (block != root)
  {
    DBUG_PRINT("error",
	       ("block 0x%lx (0x%lx<-->0x%lx) not owned by list '%s' 0x%lx",
		(ulong) block, 
		(ulong) block->prev, (ulong) block->next,
		name, (ulong) root));
    return 1;
  }
err1:
  // forward
  block = point;
  do
  {
    if (block->next->prev != block)
    {
      DBUG_PRINT("error",
		 ("block 0x%lx in list '%s' 0x%lx is incorrect linked, next block 0x%lx refered as prev to 0x%lx (check from 0x%lx)",
		  (ulong) block, name, (ulong) root, (ulong) block->next,
		  (ulong) block->next->prev,
		  (ulong) point));
      //back trace
      for (; block != point; block = block->prev)
	    DBUG_PRINT("error", ("back trace 0x%lx", (ulong) block));
      result = 1;
      goto err2;
    }
    block = block->next;
  } while (block != root);
err2:
  return result;
}

unknown's avatar
unknown committed
3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525
void dump_node(Query_cache_block_table * node, 
	       const char * call, const char * descr)
{
  DBUG_PRINT("qcache", ("%s: %s: node: 0x%lx", call, descr, (ulong) node));
  DBUG_PRINT("qcache", ("%s: %s: node block: 0x%lx",
			call, descr, (ulong) node->block()));
  DBUG_PRINT("qcache", ("%s: %s: next: 0x%lx", call, descr,
			(ulong) node->next));
  DBUG_PRINT("qcache", ("%s: %s: prev: 0x%lx", call, descr,
			(ulong) node->prev));
}

my_bool Query_cache::in_table_list(Query_cache_block_table * root,
				   Query_cache_block_table * point,
				   const char *name)
{
  my_bool result = 0;
  Query_cache_block_table *table = point;
  dump_node(root, name, "parameter root");
  //back
  do
  {
    dump_node(table, name, "list element << ");
    if (table->prev->next != table)
    {
      DBUG_PRINT("error",
		 ("table 0x%lx(0x%lx) in list '%s' 0x%lx(0x%lx) is incorrect linked, prev table 0x%lx(0x%lx) refered as next to 0x%lx(0x%lx) (check from 0x%lx(0x%lx))",
		  (ulong) table, (ulong) table->block(), name, 
		  (ulong) root, (ulong) root->block(),
		  (ulong) table->prev, (ulong) table->prev->block(),
		  (ulong) table->prev->next, 
		  (ulong) table->prev->next->block(),
		  (ulong) point, (ulong) point->block()));
      //back trace
3526
      for (; table != point; table = table->next)
unknown's avatar
unknown committed
3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572
	    DBUG_PRINT("error", ("back trace 0x%lx(0x%lx)", 
				 (ulong) table, (ulong) table->block()));
      result = 1;
      goto err1;
    }
    table = table->prev;
  } while (table != root && table != point);
  if (table != root)
  {
    DBUG_PRINT("error",
	       ("table 0x%lx(0x%lx) (0x%lx(0x%lx)<-->0x%lx(0x%lx)) not owned by list '%s' 0x%lx(0x%lx)",
		(ulong) table, (ulong) table->block(),
		(ulong) table->prev, (ulong) table->prev->block(),
		(ulong) table->next, (ulong) table->next->block(),
		name, (ulong) root, (ulong) root->block()));
    return 1;
  }
err1:
  // forward
  table = point;
  do
  {
    dump_node(table, name, "list element >> ");
    if (table->next->prev != table)
    {
      DBUG_PRINT("error",
		 ("table 0x%lx(0x%lx) in list '%s' 0x%lx(0x%lx) is incorrect linked, next table 0x%lx(0x%lx) refered as prev to 0x%lx(0x%lx) (check from 0x%lx(0x%lx))",
		  (ulong) table, (ulong) table->block(),
		  name, (ulong) root, (ulong) root->block(),
		  (ulong) table->next, (ulong) table->next->block(),
		  (ulong) table->next->prev,
		  (ulong) table->next->prev->block(),
		  (ulong) point, (ulong) point->block()));
      //back trace
      for (; table != point; table = table->prev)
	    DBUG_PRINT("error", ("back trace 0x%lx(0x%lx)",
				 (ulong) table, (ulong) table->block()));
      result = 1;
      goto err2;
    }
    table = table->next;
  } while (table != root);
err2:
  return result;
}

unknown's avatar
unknown committed
3573
#endif /* DBUG_OFF */
unknown's avatar
unknown committed
3574 3575

#endif /*HAVE_QUERY_CACHE*/