btr0btr.cc 145 KB
Newer Older
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1 2
/*****************************************************************************

3 4
Copyright (c) 1994, 2013, Oracle and/or its affiliates. All Rights Reserved.
Copyright (c) 2012, Facebook Inc.
Vadim Tkachenko's avatar
Vadim Tkachenko committed
5 6 7 8 9 10 11 12 13 14

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; version 2 of the License.

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.

You should have received a copy of the GNU General Public License along with
Sergei Golubchik's avatar
Sergei Golubchik committed
15 16
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
Vadim Tkachenko's avatar
Vadim Tkachenko committed
17 18 19

*****************************************************************************/

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
20
/**************************************************//**
21
@file btr/btr0btr.cc
22 23 24 25 26 27 28 29 30 31 32 33 34 35
The B-tree

Created 6/2/1994 Heikki Tuuri
*******************************************************/

#include "btr0btr.h"

#ifdef UNIV_NONINL
#include "btr0btr.ic"
#endif

#include "fsp0fsp.h"
#include "page0page.h"
#include "page0zip.h"
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
36 37

#ifndef UNIV_HOTBACKUP
38 39 40 41 42 43 44
#include "btr0cur.h"
#include "btr0sea.h"
#include "btr0pcur.h"
#include "rem0cmp.h"
#include "lock0lock.h"
#include "ibuf0ibuf.h"
#include "trx0trx.h"
45
#include "srv0mon.h"
46

47 48 49 50 51 52 53 54 55 56 57 58 59
/**************************************************************//**
Checks if the page in the cursor can be merged with given page.
If necessary, re-organize the merge_page.
@return	TRUE if possible to merge. */
UNIV_INTERN
ibool
btr_can_merge_with_page(
/*====================*/
	btr_cur_t*	cursor,		/*!< in: cursor on the page to merge */
	ulint		page_no,	/*!< in: a sibling page */
	buf_block_t**	merge_block,	/*!< out: the merge block */
	mtr_t*		mtr);		/*!< in: mini-transaction */

60
#endif /* UNIV_HOTBACKUP */
61

Sergei Golubchik's avatar
Sergei Golubchik committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/**************************************************************//**
Report that an index page is corrupted. */
UNIV_INTERN
void
btr_corruption_report(
/*==================*/
	const buf_block_t*	block,	/*!< in: corrupted block */
	const dict_index_t*	index)	/*!< in: index tree */
{
	fprintf(stderr, "InnoDB: flag mismatch in space %u page %u"
		" index %s of table %s\n",
		(unsigned) buf_block_get_space(block),
		(unsigned) buf_block_get_page_no(block),
		index->name, index->table_name);
	if (block->page.zip.data) {
		buf_page_print(block->page.zip.data,
			       buf_block_get_zip_size(block),
			       BUF_PAGE_PRINT_NO_CRASH);
	}
	buf_page_print(buf_block_get_frame(block), 0, 0);
}

84
#ifndef UNIV_HOTBACKUP
Sergei Golubchik's avatar
Sergei Golubchik committed
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
#ifdef UNIV_BLOB_DEBUG
# include "srv0srv.h"
# include "ut0rbt.h"

/** TRUE when messages about index->blobs modification are enabled. */
static ibool btr_blob_dbg_msg;

/** Issue a message about an operation on index->blobs.
@param op	operation
@param b	the entry being subjected to the operation
@param ctx	the context of the operation */
#define btr_blob_dbg_msg_issue(op, b, ctx)			\
	fprintf(stderr, op " %u:%u:%u->%u %s(%u,%u,%u)\n",	\
		(b)->ref_page_no, (b)->ref_heap_no,		\
		(b)->ref_field_no, (b)->blob_page_no, ctx,	\
		(b)->owner, (b)->always_owner, (b)->del)

/** Insert to index->blobs a reference to an off-page column.
@param index	the index tree
@param b	the reference
@param ctx	context (for logging) */
UNIV_INTERN
void
btr_blob_dbg_rbt_insert(
/*====================*/
	dict_index_t*		index,	/*!< in/out: index tree */
	const btr_blob_dbg_t*	b,	/*!< in: the reference */
	const char*		ctx)	/*!< in: context (for logging) */
{
	if (btr_blob_dbg_msg) {
		btr_blob_dbg_msg_issue("insert", b, ctx);
	}
	mutex_enter(&index->blobs_mutex);
	rbt_insert(index->blobs, b, b);
	mutex_exit(&index->blobs_mutex);
}

/** Remove from index->blobs a reference to an off-page column.
@param index	the index tree
@param b	the reference
@param ctx	context (for logging) */
UNIV_INTERN
void
btr_blob_dbg_rbt_delete(
/*====================*/
	dict_index_t*		index,	/*!< in/out: index tree */
	const btr_blob_dbg_t*	b,	/*!< in: the reference */
	const char*		ctx)	/*!< in: context (for logging) */
{
	if (btr_blob_dbg_msg) {
		btr_blob_dbg_msg_issue("delete", b, ctx);
	}
	mutex_enter(&index->blobs_mutex);
	ut_a(rbt_delete(index->blobs, b));
	mutex_exit(&index->blobs_mutex);
}

/**************************************************************//**
Comparator for items (btr_blob_dbg_t) in index->blobs.
The key in index->blobs is (ref_page_no, ref_heap_no, ref_field_no).
@return negative, 0 or positive if *a<*b, *a=*b, *a>*b */
static
int
btr_blob_dbg_cmp(
/*=============*/
	const void*	a,	/*!< in: first btr_blob_dbg_t to compare */
	const void*	b)	/*!< in: second btr_blob_dbg_t to compare */
{
153 154
	const btr_blob_dbg_t*	aa = static_cast<const btr_blob_dbg_t*>(a);
	const btr_blob_dbg_t*	bb = static_cast<const btr_blob_dbg_t*>(b);
Sergei Golubchik's avatar
Sergei Golubchik committed
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 203 204 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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 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

	ut_ad(aa != NULL);
	ut_ad(bb != NULL);

	if (aa->ref_page_no != bb->ref_page_no) {
		return(aa->ref_page_no < bb->ref_page_no ? -1 : 1);
	}
	if (aa->ref_heap_no != bb->ref_heap_no) {
		return(aa->ref_heap_no < bb->ref_heap_no ? -1 : 1);
	}
	if (aa->ref_field_no != bb->ref_field_no) {
		return(aa->ref_field_no < bb->ref_field_no ? -1 : 1);
	}
	return(0);
}

/**************************************************************//**
Add a reference to an off-page column to the index->blobs map. */
UNIV_INTERN
void
btr_blob_dbg_add_blob(
/*==================*/
	const rec_t*	rec,		/*!< in: clustered index record */
	ulint		field_no,	/*!< in: off-page column number */
	ulint		page_no,	/*!< in: start page of the column */
	dict_index_t*	index,		/*!< in/out: index tree */
	const char*	ctx)		/*!< in: context (for logging) */
{
	btr_blob_dbg_t	b;
	const page_t*	page	= page_align(rec);

	ut_a(index->blobs);

	b.blob_page_no = page_no;
	b.ref_page_no = page_get_page_no(page);
	b.ref_heap_no = page_rec_get_heap_no(rec);
	b.ref_field_no = field_no;
	ut_a(b.ref_field_no >= index->n_uniq);
	b.always_owner = b.owner = TRUE;
	b.del = FALSE;
	ut_a(!rec_get_deleted_flag(rec, page_is_comp(page)));
	btr_blob_dbg_rbt_insert(index, &b, ctx);
}

/**************************************************************//**
Add to index->blobs any references to off-page columns from a record.
@return number of references added */
UNIV_INTERN
ulint
btr_blob_dbg_add_rec(
/*=================*/
	const rec_t*	rec,	/*!< in: record */
	dict_index_t*	index,	/*!< in/out: index */
	const ulint*	offsets,/*!< in: offsets */
	const char*	ctx)	/*!< in: context (for logging) */
{
	ulint		count	= 0;
	ulint		i;
	btr_blob_dbg_t	b;
	ibool		del;

	ut_ad(rec_offs_validate(rec, index, offsets));

	if (!rec_offs_any_extern(offsets)) {
		return(0);
	}

	b.ref_page_no = page_get_page_no(page_align(rec));
	b.ref_heap_no = page_rec_get_heap_no(rec);
	del = (rec_get_deleted_flag(rec, rec_offs_comp(offsets)) != 0);

	for (i = 0; i < rec_offs_n_fields(offsets); i++) {
		if (rec_offs_nth_extern(offsets, i)) {
			ulint		len;
			const byte*	field_ref = rec_get_nth_field(
				rec, offsets, i, &len);

			ut_a(len != UNIV_SQL_NULL);
			ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE);
			field_ref += len - BTR_EXTERN_FIELD_REF_SIZE;

			if (!memcmp(field_ref, field_ref_zero,
				    BTR_EXTERN_FIELD_REF_SIZE)) {
				/* the column has not been stored yet */
				continue;
			}

			b.ref_field_no = i;
			b.blob_page_no = mach_read_from_4(
				field_ref + BTR_EXTERN_PAGE_NO);
			ut_a(b.ref_field_no >= index->n_uniq);
			b.always_owner = b.owner
				= !(field_ref[BTR_EXTERN_LEN]
				    & BTR_EXTERN_OWNER_FLAG);
			b.del = del;

			btr_blob_dbg_rbt_insert(index, &b, ctx);
			count++;
		}
	}

	return(count);
}

/**************************************************************//**
Display the references to off-page columns.
This function is to be called from a debugger,
for example when a breakpoint on ut_dbg_assertion_failed is hit. */
UNIV_INTERN
void
btr_blob_dbg_print(
/*===============*/
	const dict_index_t*	index)	/*!< in: index tree */
{
	const ib_rbt_node_t*	node;

	if (!index->blobs) {
		return;
	}

	/* We intentionally do not acquire index->blobs_mutex here.
	This function is to be called from a debugger, and the caller
	should make sure that the index->blobs_mutex is held. */

	for (node = rbt_first(index->blobs);
	     node != NULL; node = rbt_next(index->blobs, node)) {
		const btr_blob_dbg_t*	b
			= rbt_value(btr_blob_dbg_t, node);
		fprintf(stderr, "%u:%u:%u->%u%s%s%s\n",
			b->ref_page_no, b->ref_heap_no, b->ref_field_no,
			b->blob_page_no,
			b->owner ? "" : "(disowned)",
			b->always_owner ? "" : "(has disowned)",
			b->del ? "(deleted)" : "");
	}
}

/**************************************************************//**
Remove from index->blobs any references to off-page columns from a record.
@return number of references removed */
UNIV_INTERN
ulint
btr_blob_dbg_remove_rec(
/*====================*/
	const rec_t*	rec,	/*!< in: record */
	dict_index_t*	index,	/*!< in/out: index */
	const ulint*	offsets,/*!< in: offsets */
	const char*	ctx)	/*!< in: context (for logging) */
{
	ulint		i;
	ulint		count	= 0;
	btr_blob_dbg_t	b;

	ut_ad(rec_offs_validate(rec, index, offsets));

	if (!rec_offs_any_extern(offsets)) {
		return(0);
	}

	b.ref_page_no = page_get_page_no(page_align(rec));
	b.ref_heap_no = page_rec_get_heap_no(rec);

	for (i = 0; i < rec_offs_n_fields(offsets); i++) {
		if (rec_offs_nth_extern(offsets, i)) {
			ulint		len;
			const byte*	field_ref = rec_get_nth_field(
				rec, offsets, i, &len);

			ut_a(len != UNIV_SQL_NULL);
			ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE);
			field_ref += len - BTR_EXTERN_FIELD_REF_SIZE;

			b.ref_field_no = i;
			b.blob_page_no = mach_read_from_4(
				field_ref + BTR_EXTERN_PAGE_NO);

			switch (b.blob_page_no) {
			case 0:
				/* The column has not been stored yet.
				The BLOB pointer must be all zero.
				There cannot be a BLOB starting at
				page 0, because page 0 is reserved for
				the tablespace header. */
				ut_a(!memcmp(field_ref, field_ref_zero,
					     BTR_EXTERN_FIELD_REF_SIZE));
				/* fall through */
			case FIL_NULL:
				/* the column has been freed already */
				continue;
			}

			btr_blob_dbg_rbt_delete(index, &b, ctx);
			count++;
		}
	}

	return(count);
}

/**************************************************************//**
Check that there are no references to off-page columns from or to
the given page. Invoked when freeing or clearing a page.
@return TRUE when no orphan references exist */
UNIV_INTERN
ibool
btr_blob_dbg_is_empty(
/*==================*/
	dict_index_t*	index,		/*!< in: index */
	ulint		page_no)	/*!< in: page number */
{
	const ib_rbt_node_t*	node;
	ibool			success	= TRUE;

	if (!index->blobs) {
		return(success);
	}

	mutex_enter(&index->blobs_mutex);

	for (node = rbt_first(index->blobs);
	     node != NULL; node = rbt_next(index->blobs, node)) {
		const btr_blob_dbg_t*	b
			= rbt_value(btr_blob_dbg_t, node);

		if (b->ref_page_no != page_no && b->blob_page_no != page_no) {
			continue;
		}

		fprintf(stderr,
			"InnoDB: orphan BLOB ref%s%s%s %u:%u:%u->%u\n",
			b->owner ? "" : "(disowned)",
			b->always_owner ? "" : "(has disowned)",
			b->del ? "(deleted)" : "",
			b->ref_page_no, b->ref_heap_no, b->ref_field_no,
			b->blob_page_no);

		if (b->blob_page_no != page_no || b->owner || !b->del) {
			success = FALSE;
		}
	}

	mutex_exit(&index->blobs_mutex);
	return(success);
}

/**************************************************************//**
Count and process all references to off-page columns on a page.
@return number of references processed */
UNIV_INTERN
ulint
btr_blob_dbg_op(
/*============*/
	const page_t*		page,	/*!< in: B-tree leaf page */
	const rec_t*		rec,	/*!< in: record to start from
					(NULL to process the whole page) */
	dict_index_t*		index,	/*!< in/out: index */
	const char*		ctx,	/*!< in: context (for logging) */
	const btr_blob_dbg_op_f	op)	/*!< in: operation on records */
{
	ulint		count	= 0;
	mem_heap_t*	heap	= NULL;
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
	ulint*		offsets	= offsets_;
	rec_offs_init(offsets_);

	ut_a(fil_page_get_type(page) == FIL_PAGE_INDEX);
	ut_a(!rec || page_align(rec) == page);

	if (!index->blobs || !page_is_leaf(page)
	    || !dict_index_is_clust(index)) {
		return(0);
	}

	if (rec == NULL) {
		rec = page_get_infimum_rec(page);
	}

	do {
		offsets = rec_get_offsets(rec, index, offsets,
					  ULINT_UNDEFINED, &heap);
		count += op(rec, index, offsets, ctx);
		rec = page_rec_get_next_const(rec);
	} while (!page_rec_is_supremum(rec));

439
	if (heap) {
Sergei Golubchik's avatar
Sergei Golubchik committed
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 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 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
		mem_heap_free(heap);
	}

	return(count);
}

/**************************************************************//**
Count and add to index->blobs any references to off-page columns
from records on a page.
@return number of references added */
UNIV_INTERN
ulint
btr_blob_dbg_add(
/*=============*/
	const page_t*	page,	/*!< in: rewritten page */
	dict_index_t*	index,	/*!< in/out: index */
	const char*	ctx)	/*!< in: context (for logging) */
{
	btr_blob_dbg_assert_empty(index, page_get_page_no(page));

	return(btr_blob_dbg_op(page, NULL, index, ctx, btr_blob_dbg_add_rec));
}

/**************************************************************//**
Count and remove from index->blobs any references to off-page columns
from records on a page.
Used when reorganizing a page, before copying the records.
@return number of references removed */
UNIV_INTERN
ulint
btr_blob_dbg_remove(
/*================*/
	const page_t*	page,	/*!< in: b-tree page */
	dict_index_t*	index,	/*!< in/out: index */
	const char*	ctx)	/*!< in: context (for logging) */
{
	ulint	count;

	count = btr_blob_dbg_op(page, NULL, index, ctx,
				btr_blob_dbg_remove_rec);

	/* Check that no references exist. */
	btr_blob_dbg_assert_empty(index, page_get_page_no(page));

	return(count);
}

/**************************************************************//**
Restore in index->blobs any references to off-page columns
Used when page reorganize fails due to compressed page overflow. */
UNIV_INTERN
void
btr_blob_dbg_restore(
/*=================*/
	const page_t*	npage,	/*!< in: page that failed to compress  */
	const page_t*	page,	/*!< in: copy of original page */
	dict_index_t*	index,	/*!< in/out: index */
	const char*	ctx)	/*!< in: context (for logging) */
{
	ulint	removed;
	ulint	added;

	ut_a(page_get_page_no(npage) == page_get_page_no(page));
	ut_a(page_get_space_id(npage) == page_get_space_id(page));

	removed = btr_blob_dbg_remove(npage, index, ctx);
	added = btr_blob_dbg_add(page, index, ctx);
	ut_a(added == removed);
}

/**************************************************************//**
Modify the 'deleted' flag of a record. */
UNIV_INTERN
void
btr_blob_dbg_set_deleted_flag(
/*==========================*/
	const rec_t*		rec,	/*!< in: record */
	dict_index_t*		index,	/*!< in/out: index */
	const ulint*		offsets,/*!< in: rec_get_offs(rec, index) */
	ibool			del)	/*!< in: TRUE=deleted, FALSE=exists */
{
	const ib_rbt_node_t*	node;
	btr_blob_dbg_t		b;
	btr_blob_dbg_t*		c;
	ulint			i;

	ut_ad(rec_offs_validate(rec, index, offsets));
	ut_a(dict_index_is_clust(index));
	ut_a(del == !!del);/* must be FALSE==0 or TRUE==1 */

	if (!rec_offs_any_extern(offsets) || !index->blobs) {

		return;
	}

	b.ref_page_no = page_get_page_no(page_align(rec));
	b.ref_heap_no = page_rec_get_heap_no(rec);

	for (i = 0; i < rec_offs_n_fields(offsets); i++) {
		if (rec_offs_nth_extern(offsets, i)) {
			ulint		len;
			const byte*	field_ref = rec_get_nth_field(
				rec, offsets, i, &len);

			ut_a(len != UNIV_SQL_NULL);
			ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE);
			field_ref += len - BTR_EXTERN_FIELD_REF_SIZE;

			b.ref_field_no = i;
			b.blob_page_no = mach_read_from_4(
				field_ref + BTR_EXTERN_PAGE_NO);

			switch (b.blob_page_no) {
			case 0:
				ut_a(memcmp(field_ref, field_ref_zero,
					    BTR_EXTERN_FIELD_REF_SIZE));
				/* page number 0 is for the
				page allocation bitmap */
			case FIL_NULL:
				/* the column has been freed already */
				ut_error;
			}

			mutex_enter(&index->blobs_mutex);
			node = rbt_lookup(index->blobs, &b);
			ut_a(node);

			c = rbt_value(btr_blob_dbg_t, node);
			/* The flag should be modified. */
			c->del = del;
			if (btr_blob_dbg_msg) {
				b = *c;
				mutex_exit(&index->blobs_mutex);
				btr_blob_dbg_msg_issue("del_mk", &b, "");
			} else {
				mutex_exit(&index->blobs_mutex);
			}
		}
	}
}

/**************************************************************//**
Change the ownership of an off-page column. */
UNIV_INTERN
void
btr_blob_dbg_owner(
/*===============*/
	const rec_t*		rec,	/*!< in: record */
	dict_index_t*		index,	/*!< in/out: index */
	const ulint*		offsets,/*!< in: rec_get_offs(rec, index) */
	ulint			i,	/*!< in: ith field in rec */
	ibool			own)	/*!< in: TRUE=owned, FALSE=disowned */
{
	const ib_rbt_node_t*	node;
	btr_blob_dbg_t		b;
	const byte*		field_ref;
	ulint			len;

	ut_ad(rec_offs_validate(rec, index, offsets));
	ut_a(rec_offs_nth_extern(offsets, i));

	field_ref = rec_get_nth_field(rec, offsets, i, &len);
	ut_a(len != UNIV_SQL_NULL);
	ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE);
	field_ref += len - BTR_EXTERN_FIELD_REF_SIZE;

	b.ref_page_no = page_get_page_no(page_align(rec));
	b.ref_heap_no = page_rec_get_heap_no(rec);
	b.ref_field_no = i;
	b.owner = !(field_ref[BTR_EXTERN_LEN] & BTR_EXTERN_OWNER_FLAG);
	b.blob_page_no = mach_read_from_4(field_ref + BTR_EXTERN_PAGE_NO);

	ut_a(b.owner == own);

	mutex_enter(&index->blobs_mutex);
	node = rbt_lookup(index->blobs, &b);
	/* row_ins_clust_index_entry_by_modify() invokes
	btr_cur_unmark_extern_fields() also for the newly inserted
	references, which are all zero bytes until the columns are stored.
	The node lookup must fail if and only if that is the case. */
	ut_a(!memcmp(field_ref, field_ref_zero, BTR_EXTERN_FIELD_REF_SIZE)
	     == !node);

	if (node) {
		btr_blob_dbg_t*	c = rbt_value(btr_blob_dbg_t, node);
		/* Some code sets ownership from TRUE to TRUE.
		We do not allow changing ownership from FALSE to FALSE. */
		ut_a(own || c->owner);

		c->owner = own;
		if (!own) {
			c->always_owner = FALSE;
		}
	}

	mutex_exit(&index->blobs_mutex);
}
#endif /* UNIV_BLOB_DEBUG */

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
/*
Latching strategy of the InnoDB B-tree
--------------------------------------
A tree latch protects all non-leaf nodes of the tree. Each node of a tree
also has a latch of its own.

A B-tree operation normally first acquires an S-latch on the tree. It
searches down the tree and releases the tree latch when it has the
leaf node latch. To save CPU time we do not acquire any latch on
non-leaf nodes of the tree during a search, those pages are only bufferfixed.

If an operation needs to restructure the tree, it acquires an X-latch on
the tree before searching to a leaf node. If it needs, for example, to
split a leaf,
(1) InnoDB decides the split point in the leaf,
(2) allocates a new page,
(3) inserts the appropriate node pointer to the first non-leaf level,
(4) releases the tree X-latch,
(5) and then moves records from the leaf to the new allocated page.

Node pointers
-------------
Leaf pages of a B-tree contain the index records stored in the
tree. On levels n > 0 we store 'node pointers' to pages on level
n - 1. For each page there is exactly one node pointer stored:
thus the our tree is an ordinary B-tree, not a B-link tree.

A node pointer contains a prefix P of an index record. The prefix
is long enough so that it determines an index record uniquely.
The file page number of the child page is added as the last
field. To the child page we can store node pointers or index records
which are >= P in the alphabetical order, but < P1 if there is
a next node pointer on the level, and P1 is its prefix.

If a node pointer with a prefix P points to a non-leaf child,
then the leftmost record in the child must have the same
prefix P. If it points to a leaf node, the child is not required
to contain any record with a prefix equal to P. The leaf case
is decided this way to allow arbitrary deletions in a leaf node
without touching upper levels of the tree.

We have predefined a special minimum record which we
define as the smallest record in any alphabetical order.
A minimum record is denoted by setting a bit in the record
header. A minimum record acts as the prefix of a node pointer
which points to a leftmost node on any level of the tree.

File page allocation
--------------------
In the root node of a B-tree there are two file segment headers.
The leaf pages of a tree are allocated from one file segment, to
make them consecutive on disk if possible. From the other file segment
we allocate pages for the non-leaf levels of the tree.
*/

Vadim Tkachenko's avatar
Vadim Tkachenko committed
694
#ifdef UNIV_BTR_DEBUG
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
695 696 697
/**************************************************************//**
Checks a file segment header within a B-tree root page.
@return	TRUE if valid */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
698 699 700 701
static
ibool
btr_root_fseg_validate(
/*===================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
702 703
	const fseg_header_t*	seg_header,	/*!< in: segment header */
	ulint			space)		/*!< in: tablespace identifier */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
704 705 706
{
	ulint	offset = mach_read_from_2(seg_header + FSEG_HDR_OFFSET);

707
	if (UNIV_UNLIKELY(srv_pass_corrupt_table != 0)) {
Sergei Golubchik's avatar
Sergei Golubchik committed
708 709 710 711 712
		return (mach_read_from_4(seg_header + FSEG_HDR_SPACE) == space)
			&& (offset >= FIL_PAGE_DATA)
			&& (offset <= UNIV_PAGE_SIZE - FIL_PAGE_DATA_END);
	}

Vadim Tkachenko's avatar
Vadim Tkachenko committed
713 714 715 716 717 718 719
	ut_a(mach_read_from_4(seg_header + FSEG_HDR_SPACE) == space);
	ut_a(offset >= FIL_PAGE_DATA);
	ut_a(offset <= UNIV_PAGE_SIZE - FIL_PAGE_DATA_END);
	return(TRUE);
}
#endif /* UNIV_BTR_DEBUG */

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
720
/**************************************************************//**
721 722
Gets the root node of a tree and x- or s-latches it.
@return	root page, x- or s-latched */
723 724 725 726
static
buf_block_t*
btr_root_block_get(
/*===============*/
727 728 729 730
	const dict_index_t*	index,	/*!< in: index tree */
	ulint			mode,	/*!< in: either RW_S_LATCH
					or RW_X_LATCH */
	mtr_t*			mtr)	/*!< in: mtr */
731 732 733 734 735 736 737 738 739 740
{
	ulint		space;
	ulint		zip_size;
	ulint		root_page_no;
	buf_block_t*	block;

	space = dict_index_get_space(index);
	zip_size = dict_table_zip_size(index->table);
	root_page_no = dict_index_get_page(index);

741
	block = btr_block_get(space, zip_size, root_page_no, mode, index, mtr);
742

743
	SRV_CORRUPT_TABLE_CHECK(block, return(0););
744

Sergei Golubchik's avatar
Sergei Golubchik committed
745
	btr_assert_not_corrupted(block, index);
Vadim Tkachenko's avatar
Vadim Tkachenko committed
746 747 748 749
#ifdef UNIV_BTR_DEBUG
	if (!dict_index_is_ibuf(index)) {
		const page_t*	root = buf_block_get_frame(block);

750
		if (UNIV_UNLIKELY(srv_pass_corrupt_table != 0)) {
Sergei Golubchik's avatar
Sergei Golubchik committed
751 752 753 754 755 756 757 758 759 760
			if (!btr_root_fseg_validate(FIL_PAGE_DATA
						    + PAGE_BTR_SEG_LEAF
						    + root, space))
				return(NULL);
			if (!btr_root_fseg_validate(FIL_PAGE_DATA
						    + PAGE_BTR_SEG_TOP
						    + root, space))
				return(NULL);
			return(block);
		}
Vadim Tkachenko's avatar
Vadim Tkachenko committed
761 762 763 764 765 766
		ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF
					    + root, space));
		ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP
					    + root, space));
	}
#endif /* UNIV_BTR_DEBUG */
767 768 769 770

	return(block);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
771 772 773
/**************************************************************//**
Gets the root node of a tree and x-latches it.
@return	root page, x-latched */
774 775 776 777
UNIV_INTERN
page_t*
btr_root_get(
/*=========*/
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
	const dict_index_t*	index,	/*!< in: index tree */
	mtr_t*			mtr)	/*!< in: mtr */
{
	return(buf_block_get_frame(btr_root_block_get(index, RW_X_LATCH,
						      mtr)));
}

/**************************************************************//**
Gets the height of the B-tree (the level of the root, when the leaf
level is assumed to be 0). The caller must hold an S or X latch on
the index.
@return	tree height (level of the root) */
UNIV_INTERN
ulint
btr_height_get(
/*===========*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
794
	dict_index_t*	index,	/*!< in: index tree */
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
	mtr_t*		mtr)	/*!< in/out: mini-transaction */
{
	ulint		height;
	buf_block_t*	root_block;

	ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index),
				MTR_MEMO_S_LOCK)
	      || mtr_memo_contains(mtr, dict_index_get_lock(index),
				MTR_MEMO_X_LOCK));

        /* S latches the page */
        root_block = btr_root_block_get(index, RW_S_LATCH, mtr);

        height = btr_page_get_level(buf_block_get_frame(root_block), mtr);

        /* Release the S latch on the root page. */
        mtr_memo_release(mtr, root_block, MTR_MEMO_PAGE_S_FIX);
#ifdef UNIV_SYNC_DEBUG
        sync_thread_reset_level(&root_block->lock);
#endif /* UNIV_SYNC_DEBUG */

	return(height);
}

/**************************************************************//**
Checks a file segment header within a B-tree root page and updates
the segment header space id.
@return	TRUE if valid */
static
bool
btr_root_fseg_adjust_on_import(
/*===========================*/
	fseg_header_t*	seg_header,	/*!< in/out: segment header */
	page_zip_des_t*	page_zip,	/*!< in/out: compressed page,
					or NULL */
	ulint		space,		/*!< in: tablespace identifier */
	mtr_t*		mtr)		/*!< in/out: mini-transaction */
832
{
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
	ulint	offset = mach_read_from_2(seg_header + FSEG_HDR_OFFSET);

	if (offset < FIL_PAGE_DATA
	    || offset > UNIV_PAGE_SIZE - FIL_PAGE_DATA_END) {

		return(FALSE);

	} else if (page_zip) {
		mach_write_to_4(seg_header + FSEG_HDR_SPACE, space);
		page_zip_write_header(page_zip, seg_header + FSEG_HDR_SPACE,
				      4, mtr);
	} else {
		mlog_write_ulint(seg_header + FSEG_HDR_SPACE,
				 space, MLOG_4BYTES, mtr);
	}

	return(TRUE);
}

/**************************************************************//**
Checks and adjusts the root node of a tree during IMPORT TABLESPACE.
@return error code, or DB_SUCCESS */
UNIV_INTERN
dberr_t
btr_root_adjust_on_import(
/*======================*/
	const dict_index_t*	index)	/*!< in: index tree */
{
	dberr_t		err;
	mtr_t		mtr;
	page_t*		page;
	buf_block_t*	block;
	page_zip_des_t*	page_zip;
	dict_table_t*	table		= index->table;
	ulint		space_id	= dict_index_get_space(index);
	ulint		zip_size	= dict_table_zip_size(table);
	ulint		root_page_no	= dict_index_get_page(index);

	mtr_start(&mtr);

	mtr_set_log_mode(&mtr, MTR_LOG_NO_REDO);

	DBUG_EXECUTE_IF("ib_import_trigger_corruption_3",
			return(DB_CORRUPTION););

	block = btr_block_get(
		space_id, zip_size, root_page_no, RW_X_LATCH, index, &mtr);

	page = buf_block_get_frame(block);
	page_zip = buf_block_get_page_zip(block);

	/* Check that this is a B-tree page and both the PREV and NEXT
	pointers are FIL_NULL, because the root page does not have any
	siblings. */
	if (fil_page_get_type(page) != FIL_PAGE_INDEX
	    || fil_page_get_prev(page) != FIL_NULL
	    || fil_page_get_next(page) != FIL_NULL) {

		err = DB_CORRUPTION;

	} else if (dict_index_is_clust(index)) {
		bool	page_is_compact_format;

		page_is_compact_format = page_is_comp(page) > 0;

		/* Check if the page format and table format agree. */
		if (page_is_compact_format != dict_table_is_comp(table)) {
			err = DB_CORRUPTION;
		} else {

			/* Check that the table flags and the tablespace
			flags match. */
			ulint	flags = fil_space_get_flags(table->space);

			if (flags
			    && flags != dict_tf_to_fsp_flags(table->flags)) {

				err = DB_CORRUPTION;
			} else {
				err = DB_SUCCESS;
			}
		}
	} else {
		err = DB_SUCCESS;
	}

	/* Check and adjust the file segment headers, if all OK so far. */
	if (err == DB_SUCCESS
	    && (!btr_root_fseg_adjust_on_import(
			FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF
			+ page, page_zip, space_id, &mtr)
		|| !btr_root_fseg_adjust_on_import(
			FIL_PAGE_DATA + PAGE_BTR_SEG_TOP
			+ page, page_zip, space_id, &mtr))) {

		err = DB_CORRUPTION;
	}

	mtr_commit(&mtr);

	return(err);
934 935
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
936
/*************************************************************//**
937
Gets pointer to the previous user record in the tree. It is assumed that
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
938 939
the caller has appropriate latches on the page and its neighbor.
@return	previous user record, NULL if there is none */
940 941 942 943
UNIV_INTERN
rec_t*
btr_get_prev_user_rec(
/*==================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
944 945
	rec_t*	rec,	/*!< in: record on leaf level */
	mtr_t*	mtr)	/*!< in: mtr holding a latch on the page, and if
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
			needed, also to the previous page */
{
	page_t*	page;
	page_t*	prev_page;
	ulint	prev_page_no;

	if (!page_rec_is_infimum(rec)) {

		rec_t*	prev_rec = page_rec_get_prev(rec);

		if (!page_rec_is_infimum(prev_rec)) {

			return(prev_rec);
		}
	}

	page = page_align(rec);
	prev_page_no = btr_page_get_prev(page, mtr);

	if (prev_page_no != FIL_NULL) {

		ulint		space;
		ulint		zip_size;
		buf_block_t*	prev_block;

		space = page_get_space_id(page);
		zip_size = fil_space_get_zip_size(space);

		prev_block = buf_page_get_with_no_latch(space, zip_size,
							prev_page_no, mtr);
		prev_page = buf_block_get_frame(prev_block);
		/* The caller must already have a latch to the brother */
		ut_ad(mtr_memo_contains(mtr, prev_block,
					MTR_MEMO_PAGE_S_FIX)
		      || mtr_memo_contains(mtr, prev_block,
					   MTR_MEMO_PAGE_X_FIX));
#ifdef UNIV_BTR_DEBUG
		ut_a(page_is_comp(prev_page) == page_is_comp(page));
		ut_a(btr_page_get_next(prev_page, mtr)
		     == page_get_page_no(page));
#endif /* UNIV_BTR_DEBUG */

		return(page_rec_get_prev(page_get_supremum_rec(prev_page)));
	}

	return(NULL);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
994
/*************************************************************//**
995
Gets pointer to the next user record in the tree. It is assumed that the
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
996 997
caller has appropriate latches on the page and its neighbor.
@return	next user record, NULL if there is none */
998 999 1000 1001
UNIV_INTERN
rec_t*
btr_get_next_user_rec(
/*==================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1002 1003
	rec_t*	rec,	/*!< in: record on leaf level */
	mtr_t*	mtr)	/*!< in: mtr holding a latch on the page, and if
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
			needed, also to the next page */
{
	page_t*	page;
	page_t*	next_page;
	ulint	next_page_no;

	if (!page_rec_is_supremum(rec)) {

		rec_t*	next_rec = page_rec_get_next(rec);

		if (!page_rec_is_supremum(next_rec)) {

			return(next_rec);
		}
	}

	page = page_align(rec);
	next_page_no = btr_page_get_next(page, mtr);

	if (next_page_no != FIL_NULL) {
		ulint		space;
		ulint		zip_size;
		buf_block_t*	next_block;

		space = page_get_space_id(page);
		zip_size = fil_space_get_zip_size(space);

		next_block = buf_page_get_with_no_latch(space, zip_size,
							next_page_no, mtr);
		next_page = buf_block_get_frame(next_block);
		/* The caller must already have a latch to the brother */
		ut_ad(mtr_memo_contains(mtr, next_block, MTR_MEMO_PAGE_S_FIX)
		      || mtr_memo_contains(mtr, next_block,
					   MTR_MEMO_PAGE_X_FIX));
#ifdef UNIV_BTR_DEBUG
		ut_a(page_is_comp(next_page) == page_is_comp(page));
		ut_a(btr_page_get_prev(next_page, mtr)
		     == page_get_page_no(page));
#endif /* UNIV_BTR_DEBUG */

		return(page_rec_get_next(page_get_infimum_rec(next_page)));
	}

	return(NULL);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1050
/**************************************************************//**
1051
Creates a new index page (not the root, and also not
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1052
used in page reorganization).  @see btr_page_empty(). */
Sergei Golubchik's avatar
Sergei Golubchik committed
1053
UNIV_INTERN
1054 1055 1056
void
btr_page_create(
/*============*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1057 1058 1059 1060 1061
	buf_block_t*	block,	/*!< in/out: page to be created */
	page_zip_des_t*	page_zip,/*!< in/out: compressed page, or NULL */
	dict_index_t*	index,	/*!< in: index */
	ulint		level,	/*!< in: the B-tree level of the page */
	mtr_t*		mtr)	/*!< in: mtr */
1062 1063 1064 1065
{
	page_t*		page = buf_block_get_frame(block);

	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
Sergei Golubchik's avatar
Sergei Golubchik committed
1066
	btr_blob_dbg_assert_empty(index, buf_block_get_page_no(block));
1067

1068 1069
	if (page_zip) {
		page_create_zip(block, index, level, 0, mtr);
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
	} else {
		page_create(block, mtr, dict_table_is_comp(index->table));
		/* Set the level of the new index page */
		btr_page_set_level(page, NULL, level, mtr);
	}

	block->check_index_page_at_flush = TRUE;

	btr_page_set_index_id(page, page_zip, index->id, mtr);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1081
/**************************************************************//**
1082
Allocates a new file page to be used in an ibuf tree. Takes the page from
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1083 1084
the free list of the tree, which must contain pages!
@return	new allocated block, x-latched */
1085 1086 1087 1088
static
buf_block_t*
btr_page_alloc_for_ibuf(
/*====================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1089 1090
	dict_index_t*	index,	/*!< in: index tree */
	mtr_t*		mtr)	/*!< in: mtr */
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
{
	fil_addr_t	node_addr;
	page_t*		root;
	page_t*		new_page;
	buf_block_t*	new_block;

	root = btr_root_get(index, mtr);

	node_addr = flst_get_first(root + PAGE_HEADER
				   + PAGE_BTR_IBUF_FREE_LIST, mtr);
	ut_a(node_addr.page != FIL_NULL);

	new_block = buf_page_get(dict_index_get_space(index),
				 dict_table_zip_size(index->table),
				 node_addr.page, RW_X_LATCH, mtr);
	new_page = buf_block_get_frame(new_block);
1107
	buf_block_dbg_add_level(new_block, SYNC_IBUF_TREE_NODE_NEW);
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117

	flst_remove(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST,
		    new_page + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST_NODE,
		    mtr);
	ut_ad(flst_validate(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST,
			    mtr));

	return(new_block);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1118
/**************************************************************//**
1119
Allocates a new file page to be used in an index tree. NOTE: we assume
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1120
that the caller has made the reservation for free extents!
Sergei Golubchik's avatar
Sergei Golubchik committed
1121 1122 1123 1124 1125
@retval NULL if no page could be allocated
@retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded
(init_mtr == mtr, or the page was not previously freed in mtr)
@retval block (not allocated or initialized) otherwise */
static __attribute__((nonnull, warn_unused_result))
1126
buf_block_t*
Sergei Golubchik's avatar
Sergei Golubchik committed
1127 1128
btr_page_alloc_low(
/*===============*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1129 1130 1131
	dict_index_t*	index,		/*!< in: index */
	ulint		hint_page_no,	/*!< in: hint of a good page */
	byte		file_direction,	/*!< in: direction where a possible
1132
					page split is made */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1133
	ulint		level,		/*!< in: level where the page is placed
1134
					in the tree */
Sergei Golubchik's avatar
Sergei Golubchik committed
1135 1136 1137 1138 1139 1140 1141 1142
	mtr_t*		mtr,		/*!< in/out: mini-transaction
					for the allocation */
	mtr_t*		init_mtr)	/*!< in/out: mtr or another
					mini-transaction in which the
					page should be initialized.
					If init_mtr!=mtr, but the page
					is already X-latched in mtr, do
					not initialize the page. */
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
{
	fseg_header_t*	seg_header;
	page_t*		root;

	root = btr_root_get(index, mtr);

	if (level == 0) {
		seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF;
	} else {
		seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_TOP;
	}

	/* Parameter TRUE below states that the caller has made the
	reservation for free extents, and thus we know that a page can
	be allocated: */

Sergei Golubchik's avatar
Sergei Golubchik committed
1159 1160 1161 1162
	return(fseg_alloc_free_page_general(
		       seg_header, hint_page_no, file_direction,
		       TRUE, mtr, init_mtr));
}
1163

Sergei Golubchik's avatar
Sergei Golubchik committed
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
/**************************************************************//**
Allocates a new file page to be used in an index tree. NOTE: we assume
that the caller has made the reservation for free extents!
@retval NULL if no page could be allocated
@retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded
(init_mtr == mtr, or the page was not previously freed in mtr)
@retval block (not allocated or initialized) otherwise */
UNIV_INTERN
buf_block_t*
btr_page_alloc(
/*===========*/
	dict_index_t*	index,		/*!< in: index */
	ulint		hint_page_no,	/*!< in: hint of a good page */
	byte		file_direction,	/*!< in: direction where a possible
					page split is made */
	ulint		level,		/*!< in: level where the page is placed
					in the tree */
	mtr_t*		mtr,		/*!< in/out: mini-transaction
					for the allocation */
	mtr_t*		init_mtr)	/*!< in/out: mini-transaction
					for x-latching and initializing
					the page */
{
	buf_block_t*	new_block;

	if (dict_index_is_ibuf(index)) {

		return(btr_page_alloc_for_ibuf(index, mtr));
1192 1193
	}

Sergei Golubchik's avatar
Sergei Golubchik committed
1194 1195 1196 1197 1198 1199
	new_block = btr_page_alloc_low(
		index, hint_page_no, file_direction, level, mtr, init_mtr);

	if (new_block) {
		buf_block_dbg_add_level(new_block, SYNC_TREE_NODE_NEW);
	}
1200 1201 1202 1203

	return(new_block);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1204 1205
/**************************************************************//**
Gets the number of pages in a B-tree.
Sergei Golubchik's avatar
Sergei Golubchik committed
1206
@return	number of pages, or ULINT_UNDEFINED if the index is unavailable */
1207 1208 1209 1210
UNIV_INTERN
ulint
btr_get_size(
/*=========*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1211
	dict_index_t*	index,	/*!< in: index */
Sergei Golubchik's avatar
Sergei Golubchik committed
1212 1213 1214
	ulint		flag,	/*!< in: BTR_N_LEAF_PAGES or BTR_TOTAL_SIZE */
	mtr_t*		mtr)	/*!< in/out: mini-transaction where index
				is s-latched */
1215 1216 1217 1218 1219 1220
{
	fseg_header_t*	seg_header;
	page_t*		root;
	ulint		n;
	ulint		dummy;

Sergei Golubchik's avatar
Sergei Golubchik committed
1221 1222
	ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index),
				MTR_MEMO_S_LOCK));
1223

1224
	if (index->page == FIL_NULL || dict_index_is_online_ddl(index)
Sergei Golubchik's avatar
Sergei Golubchik committed
1225 1226 1227
	    || *index->name == TEMP_INDEX_PREFIX) {
		return(ULINT_UNDEFINED);
	}
1228

Sergei Golubchik's avatar
Sergei Golubchik committed
1229
	root = btr_root_get(index, mtr);
1230

1231 1232
	SRV_CORRUPT_TABLE_CHECK(root,
	{
Sergei Golubchik's avatar
Sergei Golubchik committed
1233
		mtr_commit(mtr);
1234
		return(0);
1235
	});
1236

1237 1238 1239
	if (flag == BTR_N_LEAF_PAGES) {
		seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF;

Sergei Golubchik's avatar
Sergei Golubchik committed
1240
		fseg_n_reserved_pages(seg_header, &n, mtr);
1241 1242 1243 1244

	} else if (flag == BTR_TOTAL_SIZE) {
		seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_TOP;

Sergei Golubchik's avatar
Sergei Golubchik committed
1245
		n = fseg_n_reserved_pages(seg_header, &dummy, mtr);
1246 1247 1248

		seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF;

Sergei Golubchik's avatar
Sergei Golubchik committed
1249
		n += fseg_n_reserved_pages(seg_header, &dummy, mtr);
1250 1251 1252 1253 1254 1255 1256
	} else {
		ut_error;
	}

	return(n);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1257
/**************************************************************//**
1258 1259 1260 1261 1262 1263
Frees a page used in an ibuf tree. Puts the page to the free list of the
ibuf tree. */
static
void
btr_page_free_for_ibuf(
/*===================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1264 1265 1266
	dict_index_t*	index,	/*!< in: index tree */
	buf_block_t*	block,	/*!< in: block to be freed, x-latched */
	mtr_t*		mtr)	/*!< in: mtr */
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
{
	page_t*		root;

	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
	root = btr_root_get(index, mtr);

	flst_add_first(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST,
		       buf_block_get_frame(block)
		       + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST_NODE, mtr);

	ut_ad(flst_validate(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST,
			    mtr));
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1281
/**************************************************************//**
1282 1283 1284 1285 1286 1287 1288
Frees a file page used in an index tree. Can be used also to (BLOB)
external storage pages, because the page level 0 can be given as an
argument. */
UNIV_INTERN
void
btr_page_free_low(
/*==============*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1289 1290 1291 1292
	dict_index_t*	index,	/*!< in: index tree */
	buf_block_t*	block,	/*!< in: block to be freed, x-latched */
	ulint		level,	/*!< in: page level */
	mtr_t*		mtr)	/*!< in: mtr */
1293 1294 1295 1296 1297 1298 1299 1300 1301
{
	fseg_header_t*	seg_header;
	page_t*		root;

	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
	/* The page gets invalid for optimistic searches: increment the frame
	modify clock */

	buf_block_modify_clock_inc(block);
Sergei Golubchik's avatar
Sergei Golubchik committed
1302
	btr_blob_dbg_assert_empty(index, buf_block_get_page_no(block));
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321

	if (dict_index_is_ibuf(index)) {

		btr_page_free_for_ibuf(index, block, mtr);

		return;
	}

	root = btr_root_get(index, mtr);

	if (level == 0) {
		seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF;
	} else {
		seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_TOP;
	}

	fseg_free_page(seg_header,
		       buf_block_get_space(block),
		       buf_block_get_page_no(block), mtr);
1322 1323 1324 1325 1326 1327 1328 1329 1330

	/* The page was marked free in the allocation bitmap, but it
	should remain buffer-fixed until mtr_commit(mtr) or until it
	is explicitly freed from the mini-transaction. */
	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
	/* TODO: Discard any operations on the page from the redo log
	and remove the block from the flush list and the buffer pool.
	This would free up buffer pool earlier and reduce writes to
	both the tablespace and the redo log. */
1331 1332
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1333
/**************************************************************//**
1334 1335 1336 1337 1338 1339
Frees a file page used in an index tree. NOTE: cannot free field external
storage pages because the page must contain info on its level. */
UNIV_INTERN
void
btr_page_free(
/*==========*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1340 1341 1342
	dict_index_t*	index,	/*!< in: index tree */
	buf_block_t*	block,	/*!< in: block to be freed, x-latched */
	mtr_t*		mtr)	/*!< in: mtr */
1343
{
Sergei Golubchik's avatar
Sergei Golubchik committed
1344 1345
	const page_t*	page	= buf_block_get_frame(block);
	ulint		level	= btr_page_get_level(page, mtr);
1346

Sergei Golubchik's avatar
Sergei Golubchik committed
1347
	ut_ad(fil_page_get_type(block->frame) == FIL_PAGE_INDEX);
1348 1349 1350
	btr_page_free_low(index, block, level, mtr);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1351
/**************************************************************//**
1352 1353 1354 1355 1356
Sets the child node file address in a node pointer. */
UNIV_INLINE
void
btr_node_ptr_set_child_page_no(
/*===========================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1357 1358
	rec_t*		rec,	/*!< in: node pointer record */
	page_zip_des_t*	page_zip,/*!< in/out: compressed page whose uncompressed
1359
				part will be updated, or NULL */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1360 1361 1362
	const ulint*	offsets,/*!< in: array returned by rec_get_offsets() */
	ulint		page_no,/*!< in: child node address */
	mtr_t*		mtr)	/*!< in: mtr */
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
{
	byte*	field;
	ulint	len;

	ut_ad(rec_offs_validate(rec, NULL, offsets));
	ut_ad(!page_is_leaf(page_align(rec)));
	ut_ad(!rec_offs_comp(offsets) || rec_get_node_ptr_flag(rec));

	/* The child address is in the last field */
	field = rec_get_nth_field(rec, offsets,
				  rec_offs_n_fields(offsets) - 1, &len);

	ut_ad(len == REC_NODE_PTR_SIZE);

1377
	if (page_zip) {
1378 1379 1380 1381 1382 1383 1384 1385
		page_zip_write_node_ptr(page_zip, rec,
					rec_offs_data_size(offsets),
					page_no, mtr);
	} else {
		mlog_write_ulint(field, page_no, MLOG_4BYTES, mtr);
	}
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1386 1387 1388
/************************************************************//**
Returns the child page of a node pointer and x-latches it.
@return	child page, x-latched */
1389 1390 1391 1392
static
buf_block_t*
btr_node_ptr_get_child(
/*===================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1393 1394 1395 1396
	const rec_t*	node_ptr,/*!< in: node pointer */
	dict_index_t*	index,	/*!< in: index */
	const ulint*	offsets,/*!< in: array returned by rec_get_offsets() */
	mtr_t*		mtr)	/*!< in: mtr */
1397 1398 1399 1400 1401 1402 1403 1404 1405
{
	ulint	page_no;
	ulint	space;

	ut_ad(rec_offs_validate(node_ptr, index, offsets));
	space = page_get_space_id(page_align(node_ptr));
	page_no = btr_node_ptr_get_child_page_no(node_ptr, offsets);

	return(btr_block_get(space, dict_table_zip_size(index->table),
1406
			     page_no, RW_X_LATCH, index, mtr));
1407 1408
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1409
/************************************************************//**
1410
Returns the upper level node pointer to a page. It is assumed that mtr holds
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1411 1412
an x-latch on the tree.
@return	rec_get_offsets() of the node pointer record */
1413 1414
static
ulint*
1415 1416
btr_page_get_father_node_ptr_func(
/*==============================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1417 1418 1419
	ulint*		offsets,/*!< in: work area for the return value */
	mem_heap_t*	heap,	/*!< in: memory heap to use */
	btr_cur_t*	cursor,	/*!< in: cursor pointing to user record,
1420 1421
				out: cursor on node pointer record,
				its page x-latched */
1422 1423
	const char*	file,	/*!< in: file name */
	ulint		line,	/*!< in: line where called */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1424
	mtr_t*		mtr)	/*!< in: mtr */
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
{
	dtuple_t*	tuple;
	rec_t*		user_rec;
	rec_t*		node_ptr;
	ulint		level;
	ulint		page_no;
	dict_index_t*	index;

	page_no = buf_block_get_page_no(btr_cur_get_block(cursor));
	index = btr_cur_get_index(cursor);

	ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index),
				MTR_MEMO_X_LOCK));

	ut_ad(dict_index_get_page(index) != page_no);

	level = btr_page_get_level(btr_cur_get_page(cursor), mtr);
Sergei Golubchik's avatar
Sergei Golubchik committed
1442

1443 1444 1445 1446 1447
	user_rec = btr_cur_get_rec(cursor);
	ut_a(page_rec_is_user_rec(user_rec));
	tuple = dict_index_build_node_ptr(index, user_rec, 0, heap, level);

	btr_cur_search_to_nth_level(index, level + 1, tuple, PAGE_CUR_LE,
1448 1449
				    BTR_CONT_MODIFY_TREE, cursor, 0,
				    file, line, mtr);
1450 1451 1452 1453 1454 1455 1456

	node_ptr = btr_cur_get_rec(cursor);
	ut_ad(!page_rec_is_comp(node_ptr)
	      || rec_get_status(node_ptr) == REC_STATUS_NODE_PTR);
	offsets = rec_get_offsets(node_ptr, index, offsets,
				  ULINT_UNDEFINED, &heap);

1457
	if (btr_node_ptr_get_child_page_no(node_ptr, offsets) != page_no) {
1458 1459
		rec_t*	print_rec;
		fputs("InnoDB: Dump of the child page:\n", stderr);
Sergei Golubchik's avatar
Sergei Golubchik committed
1460 1461
		buf_page_print(page_align(user_rec), 0,
			       BUF_PAGE_PRINT_NO_CRASH);
1462
		fputs("InnoDB: Dump of the parent page:\n", stderr);
Sergei Golubchik's avatar
Sergei Golubchik committed
1463 1464
		buf_page_print(page_align(node_ptr), 0,
			       BUF_PAGE_PRINT_NO_CRASH);
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487

		fputs("InnoDB: Corruption of an index tree: table ", stderr);
		ut_print_name(stderr, NULL, TRUE, index->table_name);
		fputs(", index ", stderr);
		ut_print_name(stderr, NULL, FALSE, index->name);
		fprintf(stderr, ",\n"
			"InnoDB: father ptr page no %lu, child page no %lu\n",
			(ulong)
			btr_node_ptr_get_child_page_no(node_ptr, offsets),
			(ulong) page_no);
		print_rec = page_rec_get_next(
			page_get_infimum_rec(page_align(user_rec)));
		offsets = rec_get_offsets(print_rec, index,
					  offsets, ULINT_UNDEFINED, &heap);
		page_rec_print(print_rec, offsets);
		offsets = rec_get_offsets(node_ptr, index, offsets,
					  ULINT_UNDEFINED, &heap);
		page_rec_print(node_ptr, offsets);

		fputs("InnoDB: You should dump + drop + reimport the table"
		      " to fix the\n"
		      "InnoDB: corruption. If the crash happens at "
		      "the database startup, see\n"
1488
		      "InnoDB: " REFMAN "forcing-innodb-recovery.html about\n"
1489 1490 1491 1492 1493 1494 1495 1496 1497
		      "InnoDB: forcing recovery. "
		      "Then dump + drop + reimport.\n", stderr);

		ut_error;
	}

	return(offsets);
}

1498 1499 1500
#define btr_page_get_father_node_ptr(of,heap,cur,mtr)			\
	btr_page_get_father_node_ptr_func(of,heap,cur,__FILE__,__LINE__,mtr)

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1501
/************************************************************//**
1502
Returns the upper level node pointer to a page. It is assumed that mtr holds
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1503 1504
an x-latch on the tree.
@return	rec_get_offsets() of the node pointer record */
1505 1506 1507 1508
static
ulint*
btr_page_get_father_block(
/*======================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1509 1510 1511 1512 1513 1514
	ulint*		offsets,/*!< in: work area for the return value */
	mem_heap_t*	heap,	/*!< in: memory heap to use */
	dict_index_t*	index,	/*!< in: b-tree index */
	buf_block_t*	block,	/*!< in: child page in the index */
	mtr_t*		mtr,	/*!< in: mtr */
	btr_cur_t*	cursor)	/*!< out: cursor on node pointer record,
1515 1516 1517 1518 1519 1520 1521 1522 1523
				its page x-latched */
{
	rec_t*	rec
		= page_rec_get_next(page_get_infimum_rec(buf_block_get_frame(
								 block)));
	btr_cur_position(index, rec, block, cursor);
	return(btr_page_get_father_node_ptr(offsets, heap, cursor, mtr));
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1524
/************************************************************//**
1525 1526 1527 1528 1529 1530
Seeks to the upper level node pointer to a page.
It is assumed that mtr holds an x-latch on the tree. */
static
void
btr_page_get_father(
/*================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1531 1532 1533 1534
	dict_index_t*	index,	/*!< in: b-tree index */
	buf_block_t*	block,	/*!< in: child page in the index */
	mtr_t*		mtr,	/*!< in: mtr */
	btr_cur_t*	cursor)	/*!< out: cursor on node pointer record,
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
				its page x-latched */
{
	mem_heap_t*	heap;
	rec_t*		rec
		= page_rec_get_next(page_get_infimum_rec(buf_block_get_frame(
								 block)));
	btr_cur_position(index, rec, block, cursor);

	heap = mem_heap_create(100);
	btr_page_get_father_node_ptr(NULL, heap, cursor, mtr);
	mem_heap_free(heap);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1548 1549 1550
/************************************************************//**
Creates the root node for a new index tree.
@return	page number of the created root, FIL_NULL if did not succeed */
1551 1552 1553 1554
UNIV_INTERN
ulint
btr_create(
/*=======*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1555 1556 1557
	ulint		type,	/*!< in: type of the index */
	ulint		space,	/*!< in: space where created */
	ulint		zip_size,/*!< in: compressed page size in bytes
1558
				or 0 for uncompressed pages */
Sergei Golubchik's avatar
Sergei Golubchik committed
1559
	index_id_t	index_id,/*!< in: index id */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1560 1561
	dict_index_t*	index,	/*!< in: index */
	mtr_t*		mtr)	/*!< in: mini-transaction handle */
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
{
	ulint		page_no;
	buf_block_t*	block;
	buf_frame_t*	frame;
	page_t*		page;
	page_zip_des_t*	page_zip;

	/* Create the two new segments (one, in the case of an ibuf tree) for
	the index tree; the segment headers are put on the allocated root page
	(for an ibuf tree, not in the root, but on a separate ibuf header
	page) */

	if (type & DICT_IBUF) {
		/* Allocate first the ibuf header page */
		buf_block_t*	ibuf_hdr_block = fseg_create(
			space, 0,
			IBUF_HEADER + IBUF_TREE_SEG_HEADER, mtr);

1580 1581
		buf_block_dbg_add_level(
			ibuf_hdr_block, SYNC_IBUF_TREE_NODE_NEW);
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1582

1583 1584 1585 1586 1587
		ut_ad(buf_block_get_page_no(ibuf_hdr_block)
		      == IBUF_HEADER_PAGE_NO);
		/* Allocate then the next page to the segment: it will be the
		tree root page */

Sergei Golubchik's avatar
Sergei Golubchik committed
1588 1589 1590 1591 1592 1593
		block = fseg_alloc_free_page(
			buf_block_get_frame(ibuf_hdr_block)
			+ IBUF_HEADER + IBUF_TREE_SEG_HEADER,
			IBUF_TREE_ROOT_PAGE_NO,
			FSP_UP, mtr);
		ut_ad(buf_block_get_page_no(block) == IBUF_TREE_ROOT_PAGE_NO);
1594
	} else {
Sergei Golubchik's avatar
Sergei Golubchik committed
1595 1596 1597 1598 1599 1600 1601 1602
#ifdef UNIV_BLOB_DEBUG
		if ((type & DICT_CLUSTERED) && !index->blobs) {
			mutex_create(PFS_NOT_INSTRUMENTED,
				     &index->blobs_mutex, SYNC_ANY_LATCH);
			index->blobs = rbt_create(sizeof(btr_blob_dbg_t),
						  btr_blob_dbg_cmp);
		}
#endif /* UNIV_BLOB_DEBUG */
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
		block = fseg_create(space, 0,
				    PAGE_HEADER + PAGE_BTR_SEG_TOP, mtr);
	}

	if (block == NULL) {

		return(FIL_NULL);
	}

	page_no = buf_block_get_page_no(block);
	frame = buf_block_get_frame(block);

	if (type & DICT_IBUF) {
		/* It is an insert buffer tree: initialize the free list */
1617
		buf_block_dbg_add_level(block, SYNC_IBUF_TREE_NODE_NEW);
1618 1619 1620 1621 1622 1623 1624

		ut_ad(page_no == IBUF_TREE_ROOT_PAGE_NO);

		flst_init(frame + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, mtr);
	} else {
		/* It is a non-ibuf tree: create a file segment for leaf
		pages */
1625 1626
		buf_block_dbg_add_level(block, SYNC_TREE_NODE_NEW);

1627 1628 1629 1630 1631 1632 1633 1634 1635
		if (!fseg_create(space, page_no,
				 PAGE_HEADER + PAGE_BTR_SEG_LEAF, mtr)) {
			/* Not enough space for new segment, free root
			segment before return. */
			btr_free_root(space, zip_size, page_no, mtr);

			return(FIL_NULL);
		}

1636 1637 1638 1639 1640
		/* The fseg create acquires a second latch on the page,
		therefore we must declare it: */
		buf_block_dbg_add_level(block, SYNC_TREE_NODE_NEW);
	}

1641
	/* Create a new index page on the allocated segment page */
1642 1643
	page_zip = buf_block_get_page_zip(block);

1644 1645
	if (page_zip) {
		page = page_create_zip(block, index, 0, 0, mtr);
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
	} else {
		page = page_create(block, mtr,
				   dict_table_is_comp(index->table));
		/* Set the level of the new index page */
		btr_page_set_level(page, NULL, 0, mtr);
	}

	block->check_index_page_at_flush = TRUE;

	/* Set the index id of the page */
	btr_page_set_index_id(page, page_zip, index_id, mtr);

	/* Set the next node and previous node fields */
	btr_page_set_next(page, page_zip, FIL_NULL, mtr);
	btr_page_set_prev(page, page_zip, FIL_NULL, mtr);

	/* We reset the free bits for the page to allow creation of several
	trees in the same mtr, otherwise the latch on a bitmap page would
	prevent it because of the latching order */

	if (!(type & DICT_CLUSTERED)) {
		ibuf_reset_free_bits(block);
	}

	/* In the following assertion we test that two records of maximum
	allowed size fit on the root page: this fact is needed to ensure
	correctness of split algorithms */

	ut_ad(page_get_max_insert_size(page, 2) > 2 * BTR_PAGE_MAX_REC_SIZE);

	return(page_no);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1679
/************************************************************//**
1680 1681 1682 1683 1684 1685
Frees a B-tree except the root page, which MUST be freed after this
by calling btr_free_root. */
UNIV_INTERN
void
btr_free_but_not_root(
/*==================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1686 1687
	ulint	space,		/*!< in: space where created */
	ulint	zip_size,	/*!< in: compressed page size in bytes
1688
				or 0 for uncompressed pages */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1689
	ulint	root_page_no)	/*!< in: root page number */
1690 1691 1692 1693 1694 1695 1696 1697
{
	ibool	finished;
	page_t*	root;
	mtr_t	mtr;

leaf_loop:
	mtr_start(&mtr);

1698 1699
	root = btr_page_get(space, zip_size, root_page_no, RW_X_LATCH,
			    NULL, &mtr);
1700

1701 1702
	SRV_CORRUPT_TABLE_CHECK(root,
	{
1703 1704
		mtr_commit(&mtr);
		return;
1705
	});
1706

Vadim Tkachenko's avatar
Vadim Tkachenko committed
1707 1708 1709 1710 1711 1712
#ifdef UNIV_BTR_DEBUG
	ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF
				    + root, space));
	ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP
				    + root, space));
#endif /* UNIV_BTR_DEBUG */
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727

	/* NOTE: page hash indexes are dropped when a page is freed inside
	fsp0fsp. */

	finished = fseg_free_step(root + PAGE_HEADER + PAGE_BTR_SEG_LEAF,
				  &mtr);
	mtr_commit(&mtr);

	if (!finished) {

		goto leaf_loop;
	}
top_loop:
	mtr_start(&mtr);

1728 1729
	root = btr_page_get(space, zip_size, root_page_no, RW_X_LATCH,
			    NULL, &mtr);
1730

1731 1732
	SRV_CORRUPT_TABLE_CHECK(root,
	{
1733 1734
		mtr_commit(&mtr);
		return;
1735 1736
	});

Vadim Tkachenko's avatar
Vadim Tkachenko committed
1737 1738 1739 1740
#ifdef UNIV_BTR_DEBUG
	ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP
				    + root, space));
#endif /* UNIV_BTR_DEBUG */
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751

	finished = fseg_free_step_not_header(
		root + PAGE_HEADER + PAGE_BTR_SEG_TOP, &mtr);
	mtr_commit(&mtr);

	if (!finished) {

		goto top_loop;
	}
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1752
/************************************************************//**
1753 1754 1755 1756 1757
Frees the B-tree root page. Other tree MUST already have been freed. */
UNIV_INTERN
void
btr_free_root(
/*==========*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1758 1759
	ulint	space,		/*!< in: space where created */
	ulint	zip_size,	/*!< in: compressed page size in bytes
1760
				or 0 for uncompressed pages */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1761
	ulint	root_page_no,	/*!< in: root page number */
1762
	mtr_t*	mtr)		/*!< in/out: mini-transaction */
1763 1764 1765 1766
{
	buf_block_t*	block;
	fseg_header_t*	header;

1767 1768
	block = btr_block_get(space, zip_size, root_page_no, RW_X_LATCH,
			      NULL, mtr);
1769

1770
	SRV_CORRUPT_TABLE_CHECK(block, return;);
1771

1772
	btr_search_drop_page_hash_index(block);
1773 1774

	header = buf_block_get_frame(block) + PAGE_HEADER + PAGE_BTR_SEG_TOP;
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1775 1776 1777
#ifdef UNIV_BTR_DEBUG
	ut_a(btr_root_fseg_validate(header, space));
#endif /* UNIV_BTR_DEBUG */
1778

1779 1780 1781
	while (!fseg_free_step(header, mtr)) {
		/* Free the entire segment in small steps. */
	}
1782
}
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1783
#endif /* !UNIV_HOTBACKUP */
1784

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1785
/*************************************************************//**
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
Reorganizes an index page.

IMPORTANT: On success, the caller will have to update IBUF_BITMAP_FREE
if this is a compressed leaf page in a secondary index. This has to
be done either within the same mini-transaction, or by invoking
ibuf_reset_free_bits() before mtr_commit(). On uncompressed pages,
IBUF_BITMAP_FREE is unaffected by reorganization.

@retval true if the operation was successful
@retval false if it is a compressed page, and recompression failed */
UNIV_INTERN
bool
1798 1799
btr_page_reorganize_low(
/*====================*/
1800
	bool		recovery,/*!< in: true if called in recovery:
1801 1802 1803 1804
				locks should not be updated, i.e.,
				there cannot exist locks on the
				page, and a hash index should not be
				dropped: it cannot exist */
1805 1806 1807 1808 1809
	ulint		z_level,/*!< in: compression level to be used
				if dealing with compressed page */
	page_cur_t*	cursor,	/*!< in/out: page cursor */
	dict_index_t*	index,	/*!< in: the index tree of the page */
	mtr_t*		mtr)	/*!< in/out: mini-transaction */
1810
{
1811
	buf_block_t*	block		= page_cur_get_block(cursor);
1812
#ifndef UNIV_HOTBACKUP
Sergei Golubchik's avatar
Sergei Golubchik committed
1813
	buf_pool_t*	buf_pool	= buf_pool_from_bpage(&block->page);
1814
#endif /* !UNIV_HOTBACKUP */
1815 1816 1817 1818 1819 1820 1821 1822 1823
	page_t*		page		= buf_block_get_frame(block);
	page_zip_des_t*	page_zip	= buf_block_get_page_zip(block);
	buf_block_t*	temp_block;
	page_t*		temp_page;
	ulint		log_mode;
	ulint		data_size1;
	ulint		data_size2;
	ulint		max_ins_size1;
	ulint		max_ins_size2;
1824 1825 1826
	bool		success		= false;
	ulint		pos;
	bool		log_compressed;
1827 1828

	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
Sergei Golubchik's avatar
Sergei Golubchik committed
1829
	btr_assert_not_corrupted(block, index);
1830
#ifdef UNIV_ZIP_DEBUG
1831
	ut_a(!page_zip || page_zip_validate(page_zip, page, index));
1832 1833 1834 1835 1836 1837 1838
#endif /* UNIV_ZIP_DEBUG */
	data_size1 = page_get_data_size(page);
	max_ins_size1 = page_get_max_insert_size_after_reorganize(page, 1);

	/* Turn logging off */
	log_mode = mtr_set_log_mode(mtr, MTR_LOG_NONE);

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1839
#ifndef UNIV_HOTBACKUP
Sergei Golubchik's avatar
Sergei Golubchik committed
1840
	temp_block = buf_block_alloc(buf_pool);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1841 1842 1843 1844
#else /* !UNIV_HOTBACKUP */
	ut_ad(block == back_block1);
	temp_block = back_block2;
#endif /* !UNIV_HOTBACKUP */
1845 1846
	temp_page = temp_block->frame;

1847 1848
	MONITOR_INC(MONITOR_INDEX_REORG_ATTEMPTS);

1849 1850 1851
	/* Copy the old page to temporary space */
	buf_frame_copy(temp_page, page);

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1852
#ifndef UNIV_HOTBACKUP
1853
	if (!recovery) {
1854
		btr_search_drop_page_hash_index(block);
1855 1856
	}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1857 1858
	block->check_index_page_at_flush = TRUE;
#endif /* !UNIV_HOTBACKUP */
Sergei Golubchik's avatar
Sergei Golubchik committed
1859
	btr_blob_dbg_remove(page, index, "btr_page_reorganize");
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1860

1861 1862 1863
	/* Save the cursor position. */
	pos = page_rec_get_n_recs_before(page_cur_get_rec(cursor));

1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
	/* Recreate the page: note that global data on page (possible
	segment headers, next page-field, etc.) is preserved intact */

	page_create(block, mtr, dict_table_is_comp(index->table));

	/* Copy the records from the temporary space to the recreated page;
	do not copy the lock bits yet */

	page_copy_rec_list_end_no_locks(block, temp_block,
					page_get_infimum_rec(temp_page),
					index, mtr);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1875 1876 1877 1878 1879 1880

	if (dict_index_is_sec_or_ibuf(index) && page_is_leaf(page)) {
		/* Copy max trx id to recreated page */
		trx_id_t	max_trx_id = page_get_max_trx_id(temp_page);
		page_set_max_trx_id(block, NULL, max_trx_id, mtr);
		/* In crash recovery, dict_index_is_sec_or_ibuf() always
1881
		holds, even for clustered indexes.  max_trx_id is
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1882
		unused in clustered index pages. */
Sergei Golubchik's avatar
Sergei Golubchik committed
1883
		ut_ad(max_trx_id != 0 || recovery);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1884
	}
1885

1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
	/* If innodb_log_compressed_pages is ON, page reorganize should log the
	compressed page image.*/
	log_compressed = page_zip && page_zip_log_pages;

	if (log_compressed) {
		mtr_set_log_mode(mtr, log_mode);
	}

	if (page_zip
	    && !page_zip_compress(page_zip, page, index, z_level, mtr)) {
1896 1897

		/* Restore the old page and exit. */
Sergei Golubchik's avatar
Sergei Golubchik committed
1898 1899
		btr_blob_dbg_restore(page, temp_page, index,
				     "btr_page_reorganize_compress_fail");
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919

#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
		/* Check that the bytes that we skip are identical. */
		ut_a(!memcmp(page, temp_page, PAGE_HEADER));
		ut_a(!memcmp(PAGE_HEADER + PAGE_N_RECS + page,
			     PAGE_HEADER + PAGE_N_RECS + temp_page,
			     PAGE_DATA - (PAGE_HEADER + PAGE_N_RECS)));
		ut_a(!memcmp(UNIV_PAGE_SIZE - FIL_PAGE_DATA_END + page,
			     UNIV_PAGE_SIZE - FIL_PAGE_DATA_END + temp_page,
			     FIL_PAGE_DATA_END));
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */

		memcpy(PAGE_HEADER + page, PAGE_HEADER + temp_page,
		       PAGE_N_RECS - PAGE_N_DIR_SLOTS);
		memcpy(PAGE_DATA + page, PAGE_DATA + temp_page,
		       UNIV_PAGE_SIZE - PAGE_DATA - FIL_PAGE_DATA_END);

#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
		ut_a(!memcmp(page, temp_page, UNIV_PAGE_SIZE));
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */
1920 1921 1922 1923

		goto func_exit;
	}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1924
#ifndef UNIV_HOTBACKUP
1925
	if (!recovery) {
1926 1927 1928
		/* Update the record lock bitmaps */
		lock_move_reorganize_page(block, temp_block);
	}
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1929
#endif /* !UNIV_HOTBACKUP */
1930 1931 1932 1933

	data_size2 = page_get_data_size(page);
	max_ins_size2 = page_get_max_insert_size_after_reorganize(page, 1);

1934
	if (data_size1 != data_size2 || max_ins_size1 != max_ins_size2) {
Sergei Golubchik's avatar
Sergei Golubchik committed
1935 1936
		buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH);
		buf_page_print(temp_page, 0, BUF_PAGE_PRINT_NO_CRASH);
1937

1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
		fprintf(stderr,
			"InnoDB: Error: page old data size %lu"
			" new data size %lu\n"
			"InnoDB: Error: page old max ins size %lu"
			" new max ins size %lu\n"
			"InnoDB: Submit a detailed bug report"
			" to http://bugs.mysql.com\n",
			(unsigned long) data_size1, (unsigned long) data_size2,
			(unsigned long) max_ins_size1,
			(unsigned long) max_ins_size2);
Sergei Golubchik's avatar
Sergei Golubchik committed
1948
		ut_ad(0);
1949
	} else {
1950 1951 1952 1953 1954 1955 1956 1957
		success = true;
	}

	/* Restore the cursor position. */
	if (pos > 0) {
		cursor->rec = page_rec_get_nth(page, pos);
	} else {
		ut_ad(cursor->rec == page_get_infimum_rec(page));
1958 1959 1960 1961
	}

func_exit:
#ifdef UNIV_ZIP_DEBUG
1962
	ut_a(!page_zip || page_zip_validate(page_zip, page, index));
1963
#endif /* UNIV_ZIP_DEBUG */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1964
#ifndef UNIV_HOTBACKUP
1965
	buf_block_free(temp_block);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1966
#endif /* !UNIV_HOTBACKUP */
1967 1968 1969 1970

	/* Restore logging mode */
	mtr_set_log_mode(mtr, log_mode);

1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
#ifndef UNIV_HOTBACKUP
	if (success) {
		byte	type;
		byte*	log_ptr;

		/* Write the log record */
		if (page_zip) {
			ut_ad(page_is_comp(page));
			type = MLOG_ZIP_PAGE_REORGANIZE;
		} else if (page_is_comp(page)) {
			type = MLOG_COMP_PAGE_REORGANIZE;
		} else {
			type = MLOG_PAGE_REORGANIZE;
		}

		log_ptr = log_compressed
			? NULL
			: mlog_open_and_write_index(
				mtr, page, index, type,
				page_zip ? 1 : 0);

		/* For compressed pages write the compression level. */
		if (log_ptr && page_zip) {
			mach_write_to_1(log_ptr, z_level);
			mlog_close(mtr, log_ptr + 1);
		}
1997 1998

		MONITOR_INC(MONITOR_INDEX_REORG_SUCCESSFUL);
1999 2000 2001
	}
#endif /* !UNIV_HOTBACKUP */

2002 2003 2004
	return(success);
}

2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
/*************************************************************//**
Reorganizes an index page.

IMPORTANT: On success, the caller will have to update IBUF_BITMAP_FREE
if this is a compressed leaf page in a secondary index. This has to
be done either within the same mini-transaction, or by invoking
ibuf_reset_free_bits() before mtr_commit(). On uncompressed pages,
IBUF_BITMAP_FREE is unaffected by reorganization.

@retval true if the operation was successful
@retval false if it is a compressed page, and recompression failed */
static __attribute__((nonnull))
bool
btr_page_reorganize_block(
/*======================*/
	bool		recovery,/*!< in: true if called in recovery:
				locks should not be updated, i.e.,
				there cannot exist locks on the
				page, and a hash index should not be
				dropped: it cannot exist */
	ulint		z_level,/*!< in: compression level to be used
				if dealing with compressed page */
	buf_block_t*	block,	/*!< in/out: B-tree page */
	dict_index_t*	index,	/*!< in: the index tree of the page */
	mtr_t*		mtr)	/*!< in/out: mini-transaction */
{
	page_cur_t	cur;
	page_cur_set_before_first(block, &cur);

	return(btr_page_reorganize_low(recovery, z_level, &cur, index, mtr));
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2037 2038
#ifndef UNIV_HOTBACKUP
/*************************************************************//**
2039
Reorganizes an index page.
2040 2041 2042 2043 2044 2045 2046 2047 2048

IMPORTANT: On success, the caller will have to update IBUF_BITMAP_FREE
if this is a compressed leaf page in a secondary index. This has to
be done either within the same mini-transaction, or by invoking
ibuf_reset_free_bits() before mtr_commit(). On uncompressed pages,
IBUF_BITMAP_FREE is unaffected by reorganization.

@retval true if the operation was successful
@retval false if it is a compressed page, and recompression failed */
2049
UNIV_INTERN
2050
bool
2051 2052
btr_page_reorganize(
/*================*/
2053 2054 2055
	page_cur_t*	cursor,	/*!< in/out: page cursor */
	dict_index_t*	index,	/*!< in: the index tree of the page */
	mtr_t*		mtr)	/*!< in/out: mini-transaction */
2056
{
2057 2058
	return(btr_page_reorganize_low(false, page_zip_level,
				       cursor, index, mtr));
2059
}
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2060
#endif /* !UNIV_HOTBACKUP */
2061

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2062 2063 2064
/***********************************************************//**
Parses a redo log record of reorganizing a page.
@return	end of log record or NULL */
2065 2066 2067 2068
UNIV_INTERN
byte*
btr_parse_page_reorganize(
/*======================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2069
	byte*		ptr,	/*!< in: buffer */
2070
	byte*		end_ptr,/*!< in: buffer end */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2071
	dict_index_t*	index,	/*!< in: record descriptor */
2072
	bool		compressed,/*!< in: true if compressed page */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2073 2074
	buf_block_t*	block,	/*!< in: page to be reorganized, or NULL */
	mtr_t*		mtr)	/*!< in: mtr or NULL */
2075
{
2076 2077
	ulint	level;

2078 2079
	ut_ad(ptr && end_ptr);

2080 2081 2082 2083 2084 2085 2086 2087 2088
	/* If dealing with a compressed page the record has the
	compression level used during original compression written in
	one byte. Otherwise record is empty. */
	if (compressed) {
		if (ptr == end_ptr) {
			return(NULL);
		}

		level = mach_read_from_1(ptr);
2089

2090 2091 2092 2093 2094 2095 2096 2097
		ut_a(level <= 9);
		++ptr;
	} else {
		level = page_zip_level;
	}

	if (block != NULL) {
		btr_page_reorganize_block(true, level, block, index, mtr);
2098 2099 2100 2101 2102
	}

	return(ptr);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2103 2104 2105
#ifndef UNIV_HOTBACKUP
/*************************************************************//**
Empties an index page.  @see btr_page_create(). */
Sergei Golubchik's avatar
Sergei Golubchik committed
2106
UNIV_INTERN
2107 2108 2109
void
btr_page_empty(
/*===========*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2110 2111 2112 2113 2114
	buf_block_t*	block,	/*!< in: page to be emptied */
	page_zip_des_t*	page_zip,/*!< out: compressed page, or NULL */
	dict_index_t*	index,	/*!< in: index of the page */
	ulint		level,	/*!< in: the B-tree level of the page */
	mtr_t*		mtr)	/*!< in: mtr */
2115 2116 2117 2118
{
	page_t*	page = buf_block_get_frame(block);

	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
Vadim Tkachenko's avatar
Vadim Tkachenko committed
2119
	ut_ad(page_zip == buf_block_get_page_zip(block));
2120
#ifdef UNIV_ZIP_DEBUG
2121
	ut_a(!page_zip || page_zip_validate(page_zip, page, index));
2122 2123
#endif /* UNIV_ZIP_DEBUG */

2124
	btr_search_drop_page_hash_index(block);
Sergei Golubchik's avatar
Sergei Golubchik committed
2125
	btr_blob_dbg_remove(page, index, "btr_page_empty");
2126 2127 2128 2129

	/* Recreate the page: note that global data on page (possible
	segment headers, next page-field, etc.) is preserved intact */

2130 2131
	if (page_zip) {
		page_create_zip(block, index, level, 0, mtr);
2132 2133
	} else {
		page_create(block, mtr, dict_table_is_comp(index->table));
Vadim Tkachenko's avatar
Vadim Tkachenko committed
2134
		btr_page_set_level(page, NULL, level, mtr);
2135 2136 2137 2138 2139
	}

	block->check_index_page_at_flush = TRUE;
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2140
/*************************************************************//**
2141 2142 2143 2144
Makes tree one level higher by splitting the root, and inserts
the tuple. It is assumed that mtr contains an x-latch on the tree.
NOTE that the operation of this function must always succeed,
we cannot reverse it: therefore enough free disk space must be
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2145 2146
guaranteed to be available before this function is called.
@return	inserted record */
2147 2148 2149 2150
UNIV_INTERN
rec_t*
btr_root_raise_and_insert(
/*======================*/
2151
	ulint		flags,	/*!< in: undo logging and locking flags */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2152
	btr_cur_t*	cursor,	/*!< in: cursor at which to insert: must be
2153 2154 2155
				on the root page; when the function returns,
				the cursor is positioned on the predecessor
				of the inserted record */
2156 2157
	ulint**		offsets,/*!< out: offsets on inserted record */
	mem_heap_t**	heap,	/*!< in/out: pointer to memory heap, or NULL */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2158 2159 2160
	const dtuple_t*	tuple,	/*!< in: tuple to insert */
	ulint		n_ext,	/*!< in: number of externally stored columns */
	mtr_t*		mtr)	/*!< in: mtr */
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
{
	dict_index_t*	index;
	page_t*		root;
	page_t*		new_page;
	ulint		new_page_no;
	rec_t*		rec;
	dtuple_t*	node_ptr;
	ulint		level;
	rec_t*		node_ptr_rec;
	page_cur_t*	page_cursor;
	page_zip_des_t*	root_page_zip;
	page_zip_des_t*	new_page_zip;
	buf_block_t*	root_block;
	buf_block_t*	new_block;

	root = btr_cur_get_page(cursor);
	root_block = btr_cur_get_block(cursor);
	root_page_zip = buf_block_get_page_zip(root_block);
2179
	ut_ad(!page_is_empty(root));
2180
	index = btr_cur_get_index(cursor);
2181
#ifdef UNIV_ZIP_DEBUG
2182
	ut_a(!root_page_zip || page_zip_validate(root_page_zip, root, index));
2183
#endif /* UNIV_ZIP_DEBUG */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
2184 2185 2186
#ifdef UNIV_BTR_DEBUG
	if (!dict_index_is_ibuf(index)) {
		ulint	space = dict_index_get_space(index);
2187

Vadim Tkachenko's avatar
Vadim Tkachenko committed
2188 2189 2190 2191 2192 2193 2194 2195
		ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF
					    + root, space));
		ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP
					    + root, space));
	}

	ut_a(dict_index_get_page(index) == page_get_page_no(root));
#endif /* UNIV_BTR_DEBUG */
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
	ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index),
				MTR_MEMO_X_LOCK));
	ut_ad(mtr_memo_contains(mtr, root_block, MTR_MEMO_PAGE_X_FIX));

	/* Allocate a new page to the tree. Root splitting is done by first
	moving the root records to the new page, emptying the root, putting
	a node pointer to the new page, and then splitting the new page. */

	level = btr_page_get_level(root, mtr);

Sergei Golubchik's avatar
Sergei Golubchik committed
2206
	new_block = btr_page_alloc(index, 0, FSP_NO_DIR, level, mtr, mtr);
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
	new_page = buf_block_get_frame(new_block);
	new_page_zip = buf_block_get_page_zip(new_block);
	ut_a(!new_page_zip == !root_page_zip);
	ut_a(!new_page_zip
	     || page_zip_get_size(new_page_zip)
	     == page_zip_get_size(root_page_zip));

	btr_page_create(new_block, new_page_zip, index, level, mtr);

	/* Set the next node and previous node fields of new page */
	btr_page_set_next(new_page, new_page_zip, FIL_NULL, mtr);
	btr_page_set_prev(new_page, new_page_zip, FIL_NULL, mtr);

	/* Copy the records from root to the new page one by one. */

Vadim Tkachenko's avatar
Vadim Tkachenko committed
2222 2223 2224 2225
	if (0
#ifdef UNIV_ZIP_COPY
	    || new_page_zip
#endif /* UNIV_ZIP_COPY */
2226 2227 2228
	    || !page_copy_rec_list_end(new_block, root_block,
				       page_get_infimum_rec(root),
				       index, mtr)) {
2229 2230 2231
		ut_a(new_page_zip);

		/* Copy the page byte for byte. */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241
		page_zip_copy_recs(new_page_zip, new_page,
				   root_page_zip, root, index, mtr);

		/* Update the lock table and possible hash index. */

		lock_move_rec_list_end(new_block, root_block,
				       page_get_infimum_rec(root));

		btr_search_move_or_delete_hash_entries(new_block, root_block,
						       index);
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
	}

	/* If this is a pessimistic insert which is actually done to
	perform a pessimistic update then we have stored the lock
	information of the record to be inserted on the infimum of the
	root page: we cannot discard the lock structs on the root page */

	lock_update_root_raise(new_block, root_block);

	/* Create a memory heap where the node pointer is stored */
2252 2253 2254
	if (!*heap) {
		*heap = mem_heap_create(1000);
	}
2255 2256 2257 2258 2259 2260 2261

	rec = page_rec_get_next(page_get_infimum_rec(new_page));
	new_page_no = buf_block_get_page_no(new_block);

	/* Build the node pointer (= node key and page address) for the
	child */

2262 2263
	node_ptr = dict_index_build_node_ptr(
		index, rec, new_page_no, *heap, level);
2264 2265 2266 2267 2268 2269 2270 2271
	/* The node pointer must be marked as the predefined minimum record,
	as there is no lower alphabetical limit to records in the leftmost
	node of a level: */
	dtuple_set_info_bits(node_ptr,
			     dtuple_get_info_bits(node_ptr)
			     | REC_INFO_MIN_REC_FLAG);

	/* Rebuild the root page to get free space */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
2272
	btr_page_empty(root_block, root_page_zip, index, level + 1, mtr);
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288

	/* Set the next node and previous node fields, although
	they should already have been set.  The previous node field
	must be FIL_NULL if root_page_zip != NULL, because the
	REC_INFO_MIN_REC_FLAG (of the first user record) will be
	set if and only if btr_page_get_prev() == FIL_NULL. */
	btr_page_set_next(root, root_page_zip, FIL_NULL, mtr);
	btr_page_set_prev(root, root_page_zip, FIL_NULL, mtr);

	page_cursor = btr_cur_get_page_cur(cursor);

	/* Insert node pointer to the root */

	page_cur_set_before_first(root_block, page_cursor);

	node_ptr_rec = page_cur_tuple_insert(page_cursor, node_ptr,
2289
					     index, offsets, heap, 0, mtr);
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309

	/* The root page should only contain the node pointer
	to new_page at this point.  Thus, the data should fit. */
	ut_a(node_ptr_rec);

	/* We play safe and reset the free bits for the new page */

#if 0
	fprintf(stderr, "Root raise new page no %lu\n", new_page_no);
#endif

	if (!dict_index_is_clust(index)) {
		ibuf_reset_free_bits(new_block);
	}

	/* Reposition the cursor to the child node */
	page_cur_search(new_block, index, tuple,
			PAGE_CUR_LE, page_cursor);

	/* Split the child and insert tuple */
2310 2311
	return(btr_page_split_and_insert(flags, cursor, offsets, heap,
					 tuple, n_ext, mtr));
2312 2313
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2314
/*************************************************************//**
2315
Decides if the page should be split at the convergence point of inserts
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2316 2317
converging to the left.
@return	TRUE if split recommended */
2318 2319 2320 2321
UNIV_INTERN
ibool
btr_page_get_split_rec_to_left(
/*===========================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2322 2323
	btr_cur_t*	cursor,	/*!< in: cursor at which to insert */
	rec_t**		split_rec) /*!< out: if split recommended,
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
				the first record on upper half page,
				or NULL if tuple to be inserted should
				be first */
{
	page_t*	page;
	rec_t*	insert_point;
	rec_t*	infimum;

	page = btr_cur_get_page(cursor);
	insert_point = btr_cur_get_rec(cursor);

	if (page_header_get_ptr(page, PAGE_LAST_INSERT)
	    == page_rec_get_next(insert_point)) {

		infimum = page_get_infimum_rec(page);

		/* If the convergence is in the middle of a page, include also
		the record immediately before the new insert to the upper
		page. Otherwise, we could repeatedly move from page to page
		lots of records smaller than the convergence point. */

		if (infimum != insert_point
		    && page_rec_get_next(infimum) != insert_point) {

			*split_rec = insert_point;
		} else {
			*split_rec = page_rec_get_next(insert_point);
		}

		return(TRUE);
	}

	return(FALSE);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2359
/*************************************************************//**
2360
Decides if the page should be split at the convergence point of inserts
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2361 2362
converging to the right.
@return	TRUE if split recommended */
2363 2364 2365 2366
UNIV_INTERN
ibool
btr_page_get_split_rec_to_right(
/*============================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2367 2368
	btr_cur_t*	cursor,	/*!< in: cursor at which to insert */
	rec_t**		split_rec) /*!< out: if split recommended,
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
				the first record on upper half page,
				or NULL if tuple to be inserted should
				be first */
{
	page_t*	page;
	rec_t*	insert_point;

	page = btr_cur_get_page(cursor);
	insert_point = btr_cur_get_rec(cursor);

	/* We use eager heuristics: if the new insert would be right after
	the previous insert on the same page, we assume that there is a
	pattern of sequential inserts here. */

2383
	if (page_header_get_ptr(page, PAGE_LAST_INSERT) == insert_point) {
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415

		rec_t*	next_rec;

		next_rec = page_rec_get_next(insert_point);

		if (page_rec_is_supremum(next_rec)) {
split_at_new:
			/* Split at the new record to insert */
			*split_rec = NULL;
		} else {
			rec_t*	next_next_rec = page_rec_get_next(next_rec);
			if (page_rec_is_supremum(next_next_rec)) {

				goto split_at_new;
			}

			/* If there are >= 2 user records up from the insert
			point, split all but 1 off. We want to keep one because
			then sequential inserts can use the adaptive hash
			index, as they can do the necessary checks of the right
			search position just by looking at the records on this
			page. */

			*split_rec = next_next_rec;
		}

		return(TRUE);
	}

	return(FALSE);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2416
/*************************************************************//**
2417 2418
Calculates a split record such that the tuple will certainly fit on
its half-page when the split is performed. We assume in this function
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2419 2420
only that the cursor page has at least one user record.
@return split record, or NULL if tuple will be the first record on
2421
the lower or upper half-page (determined by btr_page_tuple_smaller()) */
2422 2423
static
rec_t*
2424 2425
btr_page_get_split_rec(
/*===================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2426 2427 2428
	btr_cur_t*	cursor,	/*!< in: cursor at which insert should be made */
	const dtuple_t*	tuple,	/*!< in: tuple to insert */
	ulint		n_ext)	/*!< in: number of externally stored columns */
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
{
	page_t*		page;
	page_zip_des_t*	page_zip;
	ulint		insert_size;
	ulint		free_space;
	ulint		total_data;
	ulint		total_n_recs;
	ulint		total_space;
	ulint		incl_data;
	rec_t*		ins_rec;
	rec_t*		rec;
	rec_t*		next_rec;
	ulint		n;
	mem_heap_t*	heap;
	ulint*		offsets;

	page = btr_cur_get_page(cursor);

	insert_size = rec_get_converted_size(cursor->index, tuple, n_ext);
	free_space  = page_get_free_space_of_empty(page_is_comp(page));

	page_zip = btr_cur_get_page_zip(cursor);
2451
	if (page_zip) {
2452 2453 2454 2455 2456
		/* Estimate the free space of an empty compressed page. */
		ulint	free_space_zip = page_zip_empty_size(
			cursor->index->n_fields,
			page_zip_get_size(page_zip));

2457
		if (free_space > (ulint) free_space_zip) {
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
			free_space = (ulint) free_space_zip;
		}
	}

	/* free_space is now the free space of a created new page */

	total_data   = page_get_data_size(page) + insert_size;
	total_n_recs = page_get_n_recs(page) + 1;
	ut_ad(total_n_recs >= 2);
	total_space  = total_data + page_dir_calc_reserved_space(total_n_recs);

	n = 0;
	incl_data = 0;
	ins_rec = btr_cur_get_rec(cursor);
	rec = page_get_infimum_rec(page);

	heap = NULL;
	offsets = NULL;

	/* We start to include records to the left half, and when the
	space reserved by them exceeds half of total_space, then if
	the included records fit on the left page, they will be put there
	if something was left over also for the right page,
	otherwise the last included record will be the first on the right
	half page */

	do {
		/* Decide the next record to include */
		if (rec == ins_rec) {
			rec = NULL;	/* NULL denotes that tuple is
					now included */
		} else if (rec == NULL) {
			rec = page_rec_get_next(ins_rec);
		} else {
			rec = page_rec_get_next(rec);
		}

		if (rec == NULL) {
			/* Include tuple */
			incl_data += insert_size;
		} else {
			offsets = rec_get_offsets(rec, cursor->index,
						  offsets, ULINT_UNDEFINED,
						  &heap);
			incl_data += rec_offs_size(offsets);
		}

		n++;
	} while (incl_data + page_dir_calc_reserved_space(n)
		 < total_space / 2);

	if (incl_data + page_dir_calc_reserved_space(n) <= free_space) {
		/* The next record will be the first on
		the right half page if it is not the
		supremum record of page */

		if (rec == ins_rec) {
			rec = NULL;

			goto func_exit;
		} else if (rec == NULL) {
			next_rec = page_rec_get_next(ins_rec);
		} else {
			next_rec = page_rec_get_next(rec);
		}
		ut_ad(next_rec);
		if (!page_rec_is_supremum(next_rec)) {
			rec = next_rec;
		}
	}

func_exit:
2530
	if (heap) {
2531 2532 2533 2534 2535
		mem_heap_free(heap);
	}
	return(rec);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2536
/*************************************************************//**
2537
Returns TRUE if the insert fits on the appropriate half-page with the
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2538
chosen split_rec.
2539 2540 2541
@return	true if fits */
static __attribute__((nonnull(1,3,4,6), warn_unused_result))
bool
2542 2543
btr_page_insert_fits(
/*=================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2544
	btr_cur_t*	cursor,	/*!< in: cursor at which insert
2545
				should be made */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2546
	const rec_t*	split_rec,/*!< in: suggestion for first record
2547 2548
				on upper half-page, or NULL if
				tuple to be inserted should be first */
2549 2550
	ulint**		offsets,/*!< in: rec_get_offsets(
				split_rec, cursor->index); out: garbage */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2551 2552
	const dtuple_t*	tuple,	/*!< in: tuple to insert */
	ulint		n_ext,	/*!< in: number of externally stored columns */
2553
	mem_heap_t**	heap)	/*!< in: temporary memory heap */
2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
{
	page_t*		page;
	ulint		insert_size;
	ulint		free_space;
	ulint		total_data;
	ulint		total_n_recs;
	const rec_t*	rec;
	const rec_t*	end_rec;

	page = btr_cur_get_page(cursor);

2565 2566 2567 2568
	ut_ad(!split_rec
	      || !page_is_comp(page) == !rec_offs_comp(*offsets));
	ut_ad(!split_rec
	      || rec_offs_validate(split_rec, cursor->index, *offsets));
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585

	insert_size = rec_get_converted_size(cursor->index, tuple, n_ext);
	free_space  = page_get_free_space_of_empty(page_is_comp(page));

	/* free_space is now the free space of a created new page */

	total_data   = page_get_data_size(page) + insert_size;
	total_n_recs = page_get_n_recs(page) + 1;

	/* We determine which records (from rec to end_rec, not including
	end_rec) will end up on the other half page from tuple when it is
	inserted. */

	if (split_rec == NULL) {
		rec = page_rec_get_next(page_get_infimum_rec(page));
		end_rec = page_rec_get_next(btr_cur_get_rec(cursor));

2586
	} else if (cmp_dtuple_rec(tuple, split_rec, *offsets) >= 0) {
2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600

		rec = page_rec_get_next(page_get_infimum_rec(page));
		end_rec = split_rec;
	} else {
		rec = split_rec;
		end_rec = page_get_supremum_rec(page);
	}

	if (total_data + page_dir_calc_reserved_space(total_n_recs)
	    <= free_space) {

		/* Ok, there will be enough available space on the
		half page where the tuple is inserted */

2601
		return(true);
2602 2603 2604 2605 2606 2607
	}

	while (rec != end_rec) {
		/* In this loop we calculate the amount of reserved
		space after rec is removed from page. */

2608 2609
		*offsets = rec_get_offsets(rec, cursor->index, *offsets,
					   ULINT_UNDEFINED, heap);
2610

2611
		total_data -= rec_offs_size(*offsets);
2612 2613 2614 2615 2616 2617 2618 2619
		total_n_recs--;

		if (total_data + page_dir_calc_reserved_space(total_n_recs)
		    <= free_space) {

			/* Ok, there will be enough available space on the
			half page where the tuple is inserted */

2620
			return(true);
2621 2622 2623 2624 2625
		}

		rec = page_rec_get_next_const(rec);
	}

2626
	return(false);
2627 2628
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2629
/*******************************************************//**
2630 2631 2632 2633
Inserts a data tuple to a tree on a non-leaf level. It is assumed
that mtr holds an x-latch on the tree. */
UNIV_INTERN
void
2634 2635
btr_insert_on_non_leaf_level_func(
/*==============================*/
2636
	ulint		flags,	/*!< in: undo logging and locking flags */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2637 2638 2639
	dict_index_t*	index,	/*!< in: index */
	ulint		level,	/*!< in: level, must be > 0 */
	dtuple_t*	tuple,	/*!< in: the record to be inserted */
2640 2641
	const char*	file,	/*!< in: file name */
	ulint		line,	/*!< in: line where called */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2642
	mtr_t*		mtr)	/*!< in: mtr */
2643 2644 2645
{
	big_rec_t*	dummy_big_rec;
	btr_cur_t	cursor;
2646
	dberr_t		err;
2647
	rec_t*		rec;
2648 2649
	ulint*		offsets	= NULL;
	mem_heap_t*	heap = NULL;
2650 2651 2652 2653 2654

	ut_ad(level > 0);

	btr_cur_search_to_nth_level(index, level, tuple, PAGE_CUR_LE,
				    BTR_CONT_MODIFY_TREE,
2655
				    &cursor, 0, file, line, mtr);
2656

2657 2658 2659
	ut_ad(cursor.flag == BTR_CUR_BINARY);

	err = btr_cur_optimistic_insert(
2660 2661 2662 2663 2664 2665
		flags
		| BTR_NO_LOCKING_FLAG
		| BTR_KEEP_SYS_FLAG
		| BTR_NO_UNDO_LOG_FLAG,
		&cursor, &offsets, &heap,
		tuple, &rec, &dummy_big_rec, 0, NULL, mtr);
2666 2667

	if (err == DB_FAIL) {
2668 2669 2670 2671 2672 2673 2674
		err = btr_cur_pessimistic_insert(flags
						 | BTR_NO_LOCKING_FLAG
						 | BTR_KEEP_SYS_FLAG
						 | BTR_NO_UNDO_LOG_FLAG,
						 &cursor, &offsets, &heap,
						 tuple, &rec,
						 &dummy_big_rec, 0, NULL, mtr);
2675 2676
		ut_a(err == DB_SUCCESS);
	}
2677
	mem_heap_free(heap);
2678 2679
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2680
/**************************************************************//**
2681 2682
Attaches the halves of an index page on the appropriate level in an
index tree. */
2683
static __attribute__((nonnull))
2684 2685 2686
void
btr_attach_half_pages(
/*==================*/
2687 2688
	ulint		flags,		/*!< in: undo logging and
					locking flags */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2689 2690
	dict_index_t*	index,		/*!< in: the index tree */
	buf_block_t*	block,		/*!< in/out: page to be split */
2691
	const rec_t*	split_rec,	/*!< in: first record on upper
2692
					half page */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2693 2694 2695
	buf_block_t*	new_block,	/*!< in/out: the new half page */
	ulint		direction,	/*!< in: FSP_UP or FSP_DOWN */
	mtr_t*		mtr)		/*!< in: mtr */
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753
{
	ulint		space;
	ulint		zip_size;
	ulint		prev_page_no;
	ulint		next_page_no;
	ulint		level;
	page_t*		page		= buf_block_get_frame(block);
	page_t*		lower_page;
	page_t*		upper_page;
	ulint		lower_page_no;
	ulint		upper_page_no;
	page_zip_des_t*	lower_page_zip;
	page_zip_des_t*	upper_page_zip;
	dtuple_t*	node_ptr_upper;
	mem_heap_t*	heap;

	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
	ut_ad(mtr_memo_contains(mtr, new_block, MTR_MEMO_PAGE_X_FIX));

	/* Create a memory heap where the data tuple is stored */
	heap = mem_heap_create(1024);

	/* Based on split direction, decide upper and lower pages */
	if (direction == FSP_DOWN) {

		btr_cur_t	cursor;
		ulint*		offsets;

		lower_page = buf_block_get_frame(new_block);
		lower_page_no = buf_block_get_page_no(new_block);
		lower_page_zip = buf_block_get_page_zip(new_block);
		upper_page = buf_block_get_frame(block);
		upper_page_no = buf_block_get_page_no(block);
		upper_page_zip = buf_block_get_page_zip(block);

		/* Look up the index for the node pointer to page */
		offsets = btr_page_get_father_block(NULL, heap, index,
						    block, mtr, &cursor);

		/* Replace the address of the old child node (= page) with the
		address of the new lower half */

		btr_node_ptr_set_child_page_no(
			btr_cur_get_rec(&cursor),
			btr_cur_get_page_zip(&cursor),
			offsets, lower_page_no, mtr);
		mem_heap_empty(heap);
	} else {
		lower_page = buf_block_get_frame(block);
		lower_page_no = buf_block_get_page_no(block);
		lower_page_zip = buf_block_get_page_zip(block);
		upper_page = buf_block_get_frame(new_block);
		upper_page_no = buf_block_get_page_no(new_block);
		upper_page_zip = buf_block_get_page_zip(new_block);
	}

	/* Get the level of the split pages */
	level = btr_page_get_level(buf_block_get_frame(block), mtr);
Vadim Tkachenko's avatar
Vadim Tkachenko committed
2754 2755
	ut_ad(level
	      == btr_page_get_level(buf_block_get_frame(new_block), mtr));
2756 2757 2758 2759 2760 2761 2762 2763 2764 2765

	/* Build the node pointer (= node key and page address) for the upper
	half */

	node_ptr_upper = dict_index_build_node_ptr(index, split_rec,
						   upper_page_no, heap, level);

	/* Insert it next to the pointer to the lower half. Note that this
	may generate recursion leading to a split on the higher level. */

2766 2767
	btr_insert_on_non_leaf_level(flags, index, level + 1,
				     node_ptr_upper, mtr);
2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781

	/* Free the memory heap */
	mem_heap_free(heap);

	/* Get the previous and next pages of page */

	prev_page_no = btr_page_get_prev(page, mtr);
	next_page_no = btr_page_get_next(page, mtr);
	space = buf_block_get_space(block);
	zip_size = buf_block_get_zip_size(block);

	/* Update page links of the level */

	if (prev_page_no != FIL_NULL) {
2782 2783
		buf_block_t*	prev_block = btr_block_get(
			space, zip_size, prev_page_no, RW_X_LATCH, index, mtr);
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795
#ifdef UNIV_BTR_DEBUG
		ut_a(page_is_comp(prev_block->frame) == page_is_comp(page));
		ut_a(btr_page_get_next(prev_block->frame, mtr)
		     == buf_block_get_page_no(block));
#endif /* UNIV_BTR_DEBUG */

		btr_page_set_next(buf_block_get_frame(prev_block),
				  buf_block_get_page_zip(prev_block),
				  lower_page_no, mtr);
	}

	if (next_page_no != FIL_NULL) {
2796 2797
		buf_block_t*	next_block = btr_block_get(
			space, zip_size, next_page_no, RW_X_LATCH, index, mtr);
2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815
#ifdef UNIV_BTR_DEBUG
		ut_a(page_is_comp(next_block->frame) == page_is_comp(page));
		ut_a(btr_page_get_prev(next_block->frame, mtr)
		     == page_get_page_no(page));
#endif /* UNIV_BTR_DEBUG */

		btr_page_set_prev(buf_block_get_frame(next_block),
				  buf_block_get_page_zip(next_block),
				  upper_page_no, mtr);
	}

	btr_page_set_prev(lower_page, lower_page_zip, prev_page_no, mtr);
	btr_page_set_next(lower_page, lower_page_zip, upper_page_no, mtr);

	btr_page_set_prev(upper_page, upper_page_zip, lower_page_no, mtr);
	btr_page_set_next(upper_page, upper_page_zip, next_page_no, mtr);
}

2816 2817 2818
/*************************************************************//**
Determine if a tuple is smaller than any record on the page.
@return TRUE if smaller */
2819 2820
static __attribute__((nonnull, warn_unused_result))
bool
2821 2822 2823 2824
btr_page_tuple_smaller(
/*===================*/
	btr_cur_t*	cursor,	/*!< in: b-tree cursor */
	const dtuple_t*	tuple,	/*!< in: tuple to consider */
2825
	ulint**		offsets,/*!< in/out: temporary storage */
2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
	ulint		n_uniq,	/*!< in: number of unique fields
				in the index page records */
	mem_heap_t**	heap)	/*!< in/out: heap for offsets */
{
	buf_block_t*	block;
	const rec_t*	first_rec;
	page_cur_t	pcur;

	/* Read the first user record in the page. */
	block = btr_cur_get_block(cursor);
	page_cur_set_before_first(block, &pcur);
	page_cur_move_to_next(&pcur);
	first_rec = page_cur_get_rec(&pcur);

2840 2841
	*offsets = rec_get_offsets(
		first_rec, cursor->index, *offsets,
2842 2843
		n_uniq, heap);

2844
	return(cmp_dtuple_rec(tuple, first_rec, *offsets) < 0);
2845 2846
}

Sergei Golubchik's avatar
Sergei Golubchik committed
2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974
/** Insert the tuple into the right sibling page, if the cursor is at the end
of a page.
@param[in]	flags	undo logging and locking flags
@param[in,out]	cursor	cursor at which to insert; when the function succeeds,
			the cursor is positioned before the insert point.
@param[out]	offsets	offsets on inserted record
@param[in,out]	heap	memory heap for allocating offsets
@param[in]	tuple	tuple to insert
@param[in]	n_ext	number of externally stored columns
@param[in,out]	mtr	mini-transaction
@return	inserted record (first record on the right sibling page);
	the cursor will be positioned on the page infimum
@retval	NULL if the operation was not performed */
static
rec_t*
btr_insert_into_right_sibling(
	ulint		flags,
	btr_cur_t*	cursor,
	ulint**		offsets,
	mem_heap_t*	heap,
	const dtuple_t*	tuple,
	ulint		n_ext,
	mtr_t*		mtr)
{
	buf_block_t*	block = btr_cur_get_block(cursor);
	page_t*		page = buf_block_get_frame(block);
	ulint		next_page_no = btr_page_get_next(page, mtr);

	ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(cursor->index),
				MTR_MEMO_X_LOCK));
	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
	ut_ad(heap);

	if (next_page_no == FIL_NULL || !page_rec_is_supremum(
			page_rec_get_next(btr_cur_get_rec(cursor)))) {

		return(NULL);
	}

	page_cur_t	next_page_cursor;
	buf_block_t*	next_block;
	page_t*		next_page;
	btr_cur_t	next_father_cursor;
	rec_t*		rec = NULL;
	ulint		zip_size = buf_block_get_zip_size(block);
	ulint		max_size;

	next_block = btr_block_get(
		buf_block_get_space(block), zip_size,
		next_page_no, RW_X_LATCH, cursor->index, mtr);
	next_page = buf_block_get_frame(next_block);

	bool	is_leaf = page_is_leaf(next_page);

	btr_page_get_father(
		cursor->index, next_block, mtr, &next_father_cursor);

	page_cur_search(
		next_block, cursor->index, tuple, PAGE_CUR_LE,
		&next_page_cursor);

	max_size = page_get_max_insert_size_after_reorganize(next_page, 1);

	/* Extends gap lock for the next page */
	lock_update_split_left(next_block, block);

	rec = page_cur_tuple_insert(
		&next_page_cursor, tuple, cursor->index, offsets, &heap,
		n_ext, mtr);

	if (rec == NULL) {
		if (zip_size && is_leaf
		    && !dict_index_is_clust(cursor->index)) {
			/* Reset the IBUF_BITMAP_FREE bits, because
			page_cur_tuple_insert() will have attempted page
			reorganize before failing. */
			ibuf_reset_free_bits(next_block);
		}
		return(NULL);
	}

	ibool	compressed;
	dberr_t	err;
	ulint	level = btr_page_get_level(next_page, mtr);

	/* adjust cursor position */
	*btr_cur_get_page_cur(cursor) = next_page_cursor;

	ut_ad(btr_cur_get_rec(cursor) == page_get_infimum_rec(next_page));
	ut_ad(page_rec_get_next(page_get_infimum_rec(next_page)) == rec);

	/* We have to change the parent node pointer */

	compressed = btr_cur_pessimistic_delete(
		&err, TRUE, &next_father_cursor,
		BTR_CREATE_FLAG, RB_NONE, mtr);

	ut_a(err == DB_SUCCESS);

	if (!compressed) {
		btr_cur_compress_if_useful(&next_father_cursor, FALSE, mtr);
	}

	dtuple_t*	node_ptr = dict_index_build_node_ptr(
		cursor->index, rec, buf_block_get_page_no(next_block),
		heap, level);

	btr_insert_on_non_leaf_level(
		flags, cursor->index, level + 1, node_ptr, mtr);

	ut_ad(rec_offs_validate(rec, cursor->index, *offsets));

	if (is_leaf && !dict_index_is_clust(cursor->index)) {
		/* Update the free bits of the B-tree page in the
		insert buffer bitmap. */

		if (zip_size) {
			ibuf_update_free_bits_zip(next_block, mtr);
		} else {
			ibuf_update_free_bits_if_full(
				next_block, max_size,
				rec_offs_size(*offsets) + PAGE_DIR_SLOT_SIZE);
		}
	}

	return(rec);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2975
/*************************************************************//**
2976
Splits an index page to halves and inserts the tuple. It is assumed
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2977 2978 2979 2980 2981 2982 2983
that mtr holds an x-latch to the index tree. NOTE: the tree x-latch is
released within this function! NOTE that the operation of this
function must always succeed, we cannot reverse it: therefore enough
free disk space (2 pages) must be guaranteed to be available before
this function is called.

@return inserted record */
2984 2985 2986 2987
UNIV_INTERN
rec_t*
btr_page_split_and_insert(
/*======================*/
2988
	ulint		flags,	/*!< in: undo logging and locking flags */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2989
	btr_cur_t*	cursor,	/*!< in: cursor at which to insert; when the
2990 2991
				function returns, the cursor is positioned
				on the predecessor of the inserted record */
2992 2993
	ulint**		offsets,/*!< out: offsets on inserted record */
	mem_heap_t**	heap,	/*!< in/out: pointer to memory heap, or NULL */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2994 2995 2996
	const dtuple_t*	tuple,	/*!< in: tuple to insert */
	ulint		n_ext,	/*!< in: number of externally stored columns */
	mtr_t*		mtr)	/*!< in: mtr */
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
{
	buf_block_t*	block;
	page_t*		page;
	page_zip_des_t*	page_zip;
	ulint		page_no;
	byte		direction;
	ulint		hint_page_no;
	buf_block_t*	new_block;
	page_t*		new_page;
	page_zip_des_t*	new_page_zip;
	rec_t*		split_rec;
	buf_block_t*	left_block;
	buf_block_t*	right_block;
	buf_block_t*	insert_block;
	page_cur_t*	page_cursor;
	rec_t*		first_rec;
	byte*		buf = 0; /* remove warning */
	rec_t*		move_limit;
	ibool		insert_will_fit;
	ibool		insert_left;
	ulint		n_iterations = 0;
	rec_t*		rec;
	ulint		n_uniq;

3021 3022 3023
	if (!*heap) {
		*heap = mem_heap_create(1024);
	}
3024 3025
	n_uniq = dict_index_get_n_unique_in_tree(cursor->index);
func_start:
3026 3027
	mem_heap_empty(*heap);
	*offsets = NULL;
3028 3029 3030

	ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(cursor->index),
				MTR_MEMO_X_LOCK));
3031 3032 3033
	ut_ad(!dict_index_is_online_ddl(cursor->index)
	      || (flags & BTR_CREATE_FLAG)
	      || dict_index_is_clust(cursor->index));
3034 3035 3036 3037 3038 3039 3040 3041 3042
#ifdef UNIV_SYNC_DEBUG
	ut_ad(rw_lock_own(dict_index_get_lock(cursor->index), RW_LOCK_EX));
#endif /* UNIV_SYNC_DEBUG */

	block = btr_cur_get_block(cursor);
	page = buf_block_get_frame(block);
	page_zip = buf_block_get_page_zip(block);

	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
3043
	ut_ad(!page_is_empty(page));
3044

Sergei Golubchik's avatar
Sergei Golubchik committed
3045 3046 3047 3048 3049 3050 3051 3052
	/* try to insert to the next page if possible before split */
	rec = btr_insert_into_right_sibling(
		flags, cursor, offsets, *heap, tuple, n_ext, mtr);

	if (rec != NULL) {
		return(rec);
	}

3053 3054 3055 3056 3057
	page_no = buf_block_get_page_no(block);

	/* 1. Decide the split record; split_rec == NULL means that the
	tuple to be inserted should be the first record on the upper
	half-page */
3058
	insert_left = FALSE;
3059 3060 3061 3062

	if (n_iterations > 0) {
		direction = FSP_UP;
		hint_page_no = page_no + 1;
3063
		split_rec = btr_page_get_split_rec(cursor, tuple, n_ext);
3064

3065
		if (split_rec == NULL) {
3066
			insert_left = btr_page_tuple_smaller(
3067
				cursor, tuple, offsets, n_uniq, heap);
3068
		}
3069 3070 3071 3072 3073 3074 3075
	} else if (btr_page_get_split_rec_to_right(cursor, &split_rec)) {
		direction = FSP_UP;
		hint_page_no = page_no + 1;

	} else if (btr_page_get_split_rec_to_left(cursor, &split_rec)) {
		direction = FSP_DOWN;
		hint_page_no = page_no - 1;
3076
		ut_ad(split_rec);
3077 3078 3079
	} else {
		direction = FSP_UP;
		hint_page_no = page_no + 1;
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3080

3081 3082 3083 3084 3085 3086
		/* If there is only one record in the index page, we
		can't split the node in the middle by default. We need
		to determine whether the new record will be inserted
		to the left or right. */

		if (page_get_n_recs(page) > 1) {
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3087
			split_rec = page_get_middle_rec(page);
3088
		} else if (btr_page_tuple_smaller(cursor, tuple,
3089
						  offsets, n_uniq, heap)) {
3090 3091 3092 3093
			split_rec = page_rec_get_next(
				page_get_infimum_rec(page));
		} else {
			split_rec = NULL;
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3094
		}
3095 3096 3097 3098
	}

	/* 2. Allocate a new page to the index */
	new_block = btr_page_alloc(cursor->index, hint_page_no, direction,
Sergei Golubchik's avatar
Sergei Golubchik committed
3099
				   btr_page_get_level(page, mtr), mtr, mtr);
3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111
	new_page = buf_block_get_frame(new_block);
	new_page_zip = buf_block_get_page_zip(new_block);
	btr_page_create(new_block, new_page_zip, cursor->index,
			btr_page_get_level(page, mtr), mtr);

	/* 3. Calculate the first record on the upper half-page, and the
	first record (move_limit) on original page which ends up on the
	upper half */

	if (split_rec) {
		first_rec = move_limit = split_rec;

3112 3113
		*offsets = rec_get_offsets(split_rec, cursor->index, *offsets,
					   n_uniq, heap);
3114

3115
		insert_left = cmp_dtuple_rec(tuple, split_rec, *offsets) < 0;
3116

3117
		if (!insert_left && new_page_zip && n_iterations > 0) {
3118 3119 3120 3121
			/* If a compressed page has already been split,
			avoid further splits by inserting the record
			to an empty page. */
			split_rec = NULL;
3122
			goto insert_empty;
3123
		}
3124
	} else if (insert_left) {
3125
		ut_a(n_iterations > 0);
3126 3127
		first_rec = page_rec_get_next(page_get_infimum_rec(page));
		move_limit = page_rec_get_next(btr_cur_get_rec(cursor));
3128
	} else {
3129 3130 3131
insert_empty:
		ut_ad(!split_rec);
		ut_ad(!insert_left);
3132 3133
		buf = (byte*) mem_alloc(rec_get_converted_size(cursor->index,
							       tuple, n_ext));
3134 3135 3136 3137 3138 3139 3140 3141

		first_rec = rec_convert_dtuple_to_rec(buf, cursor->index,
						      tuple, n_ext);
		move_limit = page_rec_get_next(btr_cur_get_rec(cursor));
	}

	/* 4. Do first the modifications in the tree structure */

3142
	btr_attach_half_pages(flags, cursor->index, block,
3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154
			      first_rec, new_block, direction, mtr);

	/* If the split is made on the leaf level and the insert will fit
	on the appropriate half-page, we may release the tree x-latch.
	We can then move the records after releasing the tree latch,
	thus reducing the tree latch contention. */

	if (split_rec) {
		insert_will_fit = !new_page_zip
			&& btr_page_insert_fits(cursor, split_rec,
						offsets, tuple, n_ext, heap);
	} else {
3155 3156 3157 3158 3159
		if (!insert_left) {
			mem_free(buf);
			buf = NULL;
		}

3160 3161
		insert_will_fit = !new_page_zip
			&& btr_page_insert_fits(cursor, NULL,
3162
						offsets, tuple, n_ext, heap);
3163 3164
	}

3165 3166
	if (insert_will_fit && page_is_leaf(page)
	    && !dict_index_is_online_ddl(cursor->index)) {
3167 3168 3169 3170 3171 3172

		mtr_memo_release(mtr, dict_index_get_lock(cursor->index),
				 MTR_MEMO_X_LOCK);
	}

	/* 5. Move then the records to the new page */
3173
	if (direction == FSP_DOWN) {
3174 3175
		/*		fputs("Split left\n", stderr); */

Vadim Tkachenko's avatar
Vadim Tkachenko committed
3176 3177 3178 3179
		if (0
#ifdef UNIV_ZIP_COPY
		    || page_zip
#endif /* UNIV_ZIP_COPY */
3180 3181
		    || !page_move_rec_list_start(new_block, block, move_limit,
						 cursor->index, mtr)) {
3182 3183 3184 3185 3186 3187 3188
			/* For some reason, compressing new_page failed,
			even though it should contain fewer records than
			the original page.  Copy the page byte for byte
			and then delete the records from both pages
			as appropriate.  Deleting will always succeed. */
			ut_a(new_page_zip);

Vadim Tkachenko's avatar
Vadim Tkachenko committed
3189 3190
			page_zip_copy_recs(new_page_zip, new_page,
					   page_zip, page, cursor->index, mtr);
3191 3192 3193 3194
			page_delete_rec_list_end(move_limit - page + new_page,
						 new_block, cursor->index,
						 ULINT_UNDEFINED,
						 ULINT_UNDEFINED, mtr);
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206

			/* Update the lock table and possible hash index. */

			lock_move_rec_list_start(
				new_block, block, move_limit,
				new_page + PAGE_NEW_INFIMUM);

			btr_search_move_or_delete_hash_entries(
				new_block, block, cursor->index);

			/* Delete the records from the source page. */

3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217
			page_delete_rec_list_start(move_limit, block,
						   cursor->index, mtr);
		}

		left_block = new_block;
		right_block = block;

		lock_update_split_left(right_block, left_block);
	} else {
		/*		fputs("Split right\n", stderr); */

Vadim Tkachenko's avatar
Vadim Tkachenko committed
3218 3219 3220 3221
		if (0
#ifdef UNIV_ZIP_COPY
		    || page_zip
#endif /* UNIV_ZIP_COPY */
3222 3223
		    || !page_move_rec_list_end(new_block, block, move_limit,
					       cursor->index, mtr)) {
3224 3225 3226 3227 3228 3229 3230
			/* For some reason, compressing new_page failed,
			even though it should contain fewer records than
			the original page.  Copy the page byte for byte
			and then delete the records from both pages
			as appropriate.  Deleting will always succeed. */
			ut_a(new_page_zip);

Vadim Tkachenko's avatar
Vadim Tkachenko committed
3231 3232
			page_zip_copy_recs(new_page_zip, new_page,
					   page_zip, page, cursor->index, mtr);
3233 3234 3235
			page_delete_rec_list_start(move_limit - page
						   + new_page, new_block,
						   cursor->index, mtr);
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3236 3237 3238 3239 3240 3241 3242 3243 3244 3245

			/* Update the lock table and possible hash index. */

			lock_move_rec_list_end(new_block, block, move_limit);

			btr_search_move_or_delete_hash_entries(
				new_block, block, cursor->index);

			/* Delete the records from the source page. */

3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258
			page_delete_rec_list_end(move_limit, block,
						 cursor->index,
						 ULINT_UNDEFINED,
						 ULINT_UNDEFINED, mtr);
		}

		left_block = block;
		right_block = new_block;

		lock_update_split_right(right_block, left_block);
	}

#ifdef UNIV_ZIP_DEBUG
3259
	if (page_zip) {
3260 3261
		ut_a(page_zip_validate(page_zip, page, cursor->index));
		ut_a(page_zip_validate(new_page_zip, new_page, cursor->index));
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282
	}
#endif /* UNIV_ZIP_DEBUG */

	/* At this point, split_rec, move_limit and first_rec may point
	to garbage on the old page. */

	/* 6. The split and the tree modification is now completed. Decide the
	page where the tuple should be inserted */

	if (insert_left) {
		insert_block = left_block;
	} else {
		insert_block = right_block;
	}

	/* 7. Reposition the cursor for insert and try insertion */
	page_cursor = btr_cur_get_page_cur(cursor);

	page_cur_search(insert_block, cursor->index, tuple,
			PAGE_CUR_LE, page_cursor);

3283 3284
	rec = page_cur_tuple_insert(page_cursor, tuple, cursor->index,
				    offsets, heap, n_ext, mtr);
3285 3286 3287

#ifdef UNIV_ZIP_DEBUG
	{
3288 3289 3290
		page_t*		insert_page
			= buf_block_get_frame(insert_block);

3291 3292
		page_zip_des_t*	insert_page_zip
			= buf_block_get_page_zip(insert_block);
3293

3294
		ut_a(!insert_page_zip
3295 3296
		     || page_zip_validate(insert_page_zip, insert_page,
					  cursor->index));
3297 3298 3299
	}
#endif /* UNIV_ZIP_DEBUG */

3300
	if (rec != NULL) {
3301 3302 3303 3304

		goto func_exit;
	}

3305 3306 3307
	/* 8. If insert did not fit, try page reorganization.
	For compressed pages, page_cur_tuple_insert() will have
	attempted this already. */
3308

3309 3310
	if (page_cur_get_page_zip(page_cursor)
	    || !btr_page_reorganize(page_cursor, cursor->index, mtr)) {
3311 3312 3313 3314 3315

		goto insert_failed;
	}

	rec = page_cur_tuple_insert(page_cursor, tuple, cursor->index,
3316
				    offsets, heap, n_ext, mtr);
3317

3318
	if (rec == NULL) {
3319 3320 3321
		/* The insert did not fit on the page: loop back to the
		start of the function for a new split */
insert_failed:
3322
		/* We play safe and reset the free bits */
3323 3324
		if (!dict_index_is_clust(cursor->index)) {
			ibuf_reset_free_bits(new_block);
3325
			ibuf_reset_free_bits(block);
3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352
		}

		/* fprintf(stderr, "Split second round %lu\n",
		page_get_page_no(page)); */
		n_iterations++;
		ut_ad(n_iterations < 2
		      || buf_block_get_page_zip(insert_block));
		ut_ad(!insert_will_fit);

		goto func_start;
	}

func_exit:
	/* Insert fit on the page: update the free bits for the
	left and right pages in the same mtr */

	if (!dict_index_is_clust(cursor->index) && page_is_leaf(page)) {
		ibuf_update_free_bits_for_two_pages_low(
			buf_block_get_zip_size(left_block),
			left_block, right_block, mtr);
	}

#if 0
	fprintf(stderr, "Split and insert done %lu %lu\n",
		buf_block_get_page_no(left_block),
		buf_block_get_page_no(right_block));
#endif
3353
	MONITOR_INC(MONITOR_INDEX_SPLIT);
3354 3355 3356 3357

	ut_ad(page_validate(buf_block_get_frame(left_block), cursor->index));
	ut_ad(page_validate(buf_block_get_frame(right_block), cursor->index));

3358
	ut_ad(!rec || rec_offs_validate(rec, cursor->index, *offsets));
3359 3360 3361
	return(rec);
}

3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383
#ifdef UNIV_SYNC_DEBUG
/*************************************************************//**
Removes a page from the level list of pages.
@param space	in: space where removed
@param zip_size	in: compressed page size in bytes, or 0 for uncompressed
@param page	in/out: page to remove
@param index	in: index tree
@param mtr	in/out: mini-transaction */
# define btr_level_list_remove(space,zip_size,page,index,mtr)		\
	btr_level_list_remove_func(space,zip_size,page,index,mtr)
#else /* UNIV_SYNC_DEBUG */
/*************************************************************//**
Removes a page from the level list of pages.
@param space	in: space where removed
@param zip_size	in: compressed page size in bytes, or 0 for uncompressed
@param page	in/out: page to remove
@param index	in: index tree
@param mtr	in/out: mini-transaction */
# define btr_level_list_remove(space,zip_size,page,index,mtr)		\
	btr_level_list_remove_func(space,zip_size,page,mtr)
#endif /* UNIV_SYNC_DEBUG */

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3384
/*************************************************************//**
3385
Removes a page from the level list of pages. */
3386
static __attribute__((nonnull))
3387
void
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397
btr_level_list_remove_func(
/*=======================*/
	ulint			space,	/*!< in: space where removed */
	ulint			zip_size,/*!< in: compressed page size in bytes
					or 0 for uncompressed pages */
	page_t*			page,	/*!< in/out: page to remove */
#ifdef UNIV_SYNC_DEBUG
	const dict_index_t*	index,	/*!< in: index tree */
#endif /* UNIV_SYNC_DEBUG */
	mtr_t*			mtr)	/*!< in/out: mini-transaction */
3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
{
	ulint	prev_page_no;
	ulint	next_page_no;

	ut_ad(page && mtr);
	ut_ad(mtr_memo_contains_page(mtr, page, MTR_MEMO_PAGE_X_FIX));
	ut_ad(space == page_get_space_id(page));
	/* Get the previous and next page numbers of page */

	prev_page_no = btr_page_get_prev(page, mtr);
	next_page_no = btr_page_get_next(page, mtr);

	/* Update page links of the level */

	if (prev_page_no != FIL_NULL) {
		buf_block_t*	prev_block
			= btr_block_get(space, zip_size, prev_page_no,
3415
					RW_X_LATCH, index, mtr);
3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431
		page_t*		prev_page
			= buf_block_get_frame(prev_block);
#ifdef UNIV_BTR_DEBUG
		ut_a(page_is_comp(prev_page) == page_is_comp(page));
		ut_a(btr_page_get_next(prev_page, mtr)
		     == page_get_page_no(page));
#endif /* UNIV_BTR_DEBUG */

		btr_page_set_next(prev_page,
				  buf_block_get_page_zip(prev_block),
				  next_page_no, mtr);
	}

	if (next_page_no != FIL_NULL) {
		buf_block_t*	next_block
			= btr_block_get(space, zip_size, next_page_no,
3432
					RW_X_LATCH, index, mtr);
3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446
		page_t*		next_page
			= buf_block_get_frame(next_block);
#ifdef UNIV_BTR_DEBUG
		ut_a(page_is_comp(next_page) == page_is_comp(page));
		ut_a(btr_page_get_prev(next_page, mtr)
		     == page_get_page_no(page));
#endif /* UNIV_BTR_DEBUG */

		btr_page_set_prev(next_page,
				  buf_block_get_page_zip(next_block),
				  prev_page_no, mtr);
	}
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3447
/****************************************************************//**
3448 3449 3450 3451 3452 3453
Writes the redo log record for setting an index record as the predefined
minimum record. */
UNIV_INLINE
void
btr_set_min_rec_mark_log(
/*=====================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3454 3455 3456
	rec_t*	rec,	/*!< in: record */
	byte	type,	/*!< in: MLOG_COMP_REC_MIN_MARK or MLOG_REC_MIN_MARK */
	mtr_t*	mtr)	/*!< in: mtr */
3457 3458 3459 3460 3461 3462
{
	mlog_write_initial_log_record(rec, type, mtr);

	/* Write rec offset as a 2-byte ulint */
	mlog_catenate_ulint(mtr, page_offset(rec), MLOG_2BYTES);
}
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3463 3464 3465
#else /* !UNIV_HOTBACKUP */
# define btr_set_min_rec_mark_log(rec,comp,mtr) ((void) 0)
#endif /* !UNIV_HOTBACKUP */
3466

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3467
/****************************************************************//**
3468
Parses the redo log record for setting an index record as the predefined
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3469 3470
minimum record.
@return	end of log record or NULL */
3471 3472 3473 3474
UNIV_INTERN
byte*
btr_parse_set_min_rec_mark(
/*=======================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3475 3476 3477 3478 3479
	byte*	ptr,	/*!< in: buffer */
	byte*	end_ptr,/*!< in: buffer end */
	ulint	comp,	/*!< in: nonzero=compact page format */
	page_t*	page,	/*!< in: page or NULL */
	mtr_t*	mtr)	/*!< in: mtr or NULL */
3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498
{
	rec_t*	rec;

	if (end_ptr < ptr + 2) {

		return(NULL);
	}

	if (page) {
		ut_a(!page_is_comp(page) == !comp);

		rec = page + mach_read_from_2(ptr);

		btr_set_min_rec_mark(rec, mtr);
	}

	return(ptr + 2);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3499
/****************************************************************//**
3500 3501 3502 3503 3504
Sets a record as the predefined minimum record. */
UNIV_INTERN
void
btr_set_min_rec_mark(
/*=================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3505 3506
	rec_t*	rec,	/*!< in: record */
	mtr_t*	mtr)	/*!< in: mtr */
3507 3508 3509
{
	ulint	info_bits;

3510
	if (page_rec_is_comp(rec)) {
3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524
		info_bits = rec_get_info_bits(rec, TRUE);

		rec_set_info_bits_new(rec, info_bits | REC_INFO_MIN_REC_FLAG);

		btr_set_min_rec_mark_log(rec, MLOG_COMP_REC_MIN_MARK, mtr);
	} else {
		info_bits = rec_get_info_bits(rec, FALSE);

		rec_set_info_bits_old(rec, info_bits | REC_INFO_MIN_REC_FLAG);

		btr_set_min_rec_mark_log(rec, MLOG_REC_MIN_MARK, mtr);
	}
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3525 3526
#ifndef UNIV_HOTBACKUP
/*************************************************************//**
3527 3528 3529 3530 3531
Deletes on the upper level the node pointer to a page. */
UNIV_INTERN
void
btr_node_ptr_delete(
/*================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3532 3533 3534
	dict_index_t*	index,	/*!< in: index tree */
	buf_block_t*	block,	/*!< in: page whose node pointer is deleted */
	mtr_t*		mtr)	/*!< in: mtr */
3535 3536 3537
{
	btr_cur_t	cursor;
	ibool		compressed;
3538
	dberr_t		err;
3539 3540 3541 3542 3543 3544

	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));

	/* Delete node pointer on father page */
	btr_page_get_father(index, block, mtr, &cursor);

3545 3546
	compressed = btr_cur_pessimistic_delete(&err, TRUE, &cursor,
						BTR_CREATE_FLAG, RB_NONE, mtr);
3547 3548 3549
	ut_a(err == DB_SUCCESS);

	if (!compressed) {
Sergei Golubchik's avatar
Sergei Golubchik committed
3550
		btr_cur_compress_if_useful(&cursor, FALSE, mtr);
3551 3552 3553
	}
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3554
/*************************************************************//**
3555
If page is the only on its level, this function moves its records to the
Sergei Golubchik's avatar
Sergei Golubchik committed
3556 3557
father page, thus reducing the tree height.
@return father block */
3558
static
Sergei Golubchik's avatar
Sergei Golubchik committed
3559
buf_block_t*
3560 3561
btr_lift_page_up(
/*=============*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3562 3563
	dict_index_t*	index,	/*!< in: index tree */
	buf_block_t*	block,	/*!< in: page which is the only on its level;
3564 3565 3566
				must not be empty: use
				btr_discard_only_page_on_level if the last
				record from the page should be removed */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3567
	mtr_t*		mtr)	/*!< in: mtr */
3568 3569 3570 3571 3572 3573 3574 3575
{
	buf_block_t*	father_block;
	page_t*		father_page;
	ulint		page_level;
	page_zip_des_t*	father_page_zip;
	page_t*		page		= buf_block_get_frame(block);
	ulint		root_page_no;
	buf_block_t*	blocks[BTR_MAX_LEVELS];
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3576
	ulint		n_blocks;	/*!< last used index in blocks[] */
3577
	ulint		i;
3578
	bool		lift_father_up;
3579
	buf_block_t*	block_orig	= block;
3580 3581 3582 3583 3584 3585 3586 3587 3588 3589

	ut_ad(btr_page_get_prev(page, mtr) == FIL_NULL);
	ut_ad(btr_page_get_next(page, mtr) == FIL_NULL);
	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));

	page_level = btr_page_get_level(page, mtr);
	root_page_no = dict_index_get_page(index);

	{
		btr_cur_t	cursor;
3590 3591 3592 3593
		ulint*		offsets	= NULL;
		mem_heap_t*	heap	= mem_heap_create(
			sizeof(*offsets)
			* (REC_OFFS_HEADER_SIZE + 1 + 1 + index->n_fields));
3594 3595
		buf_block_t*	b;

3596
		offsets = btr_page_get_father_block(offsets, heap, index,
3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619
						    block, mtr, &cursor);
		father_block = btr_cur_get_block(&cursor);
		father_page_zip = buf_block_get_page_zip(father_block);
		father_page = buf_block_get_frame(father_block);

		n_blocks = 0;

		/* Store all ancestor pages so we can reset their
		levels later on.  We have to do all the searches on
		the tree now because later on, after we've replaced
		the first level, the tree is in an inconsistent state
		and can not be searched. */
		for (b = father_block;
		     buf_block_get_page_no(b) != root_page_no; ) {
			ut_a(n_blocks < BTR_MAX_LEVELS);

			offsets = btr_page_get_father_block(offsets, heap,
							    index, b,
							    mtr, &cursor);

			blocks[n_blocks++] = b = btr_cur_get_block(&cursor);
		}

3620 3621
		lift_father_up = (n_blocks && page_level == 0);
		if (lift_father_up) {
3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642
			/* The father page also should be the only on its level (not
			root). We should lift up the father page at first.
			Because the leaf page should be lifted up only for root page.
			The freeing page is based on page_level (==0 or !=0)
			to choose segment. If the page_level is changed ==0 from !=0,
			later freeing of the page doesn't find the page allocation
			to be freed.*/

			block = father_block;
			page = buf_block_get_frame(block);
			page_level = btr_page_get_level(page, mtr);

			ut_ad(btr_page_get_prev(page, mtr) == FIL_NULL);
			ut_ad(btr_page_get_next(page, mtr) == FIL_NULL);
			ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));

			father_block = blocks[0];
			father_page_zip = buf_block_get_page_zip(father_block);
			father_page = buf_block_get_frame(father_block);
		}

3643 3644 3645
		mem_heap_free(heap);
	}

3646
	btr_search_drop_page_hash_index(block);
3647 3648

	/* Make the father empty */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3649
	btr_page_empty(father_block, father_page_zip, index, page_level, mtr);
3650
	page_level++;
3651 3652

	/* Copy the records to the father page one by one. */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3653 3654 3655 3656
	if (0
#ifdef UNIV_ZIP_COPY
	    || father_page_zip
#endif /* UNIV_ZIP_COPY */
3657 3658 3659
	    || !page_copy_rec_list_end(father_block, block,
				       page_get_infimum_rec(page),
				       index, mtr)) {
3660 3661 3662 3663 3664 3665
		const page_zip_des_t*	page_zip
			= buf_block_get_page_zip(block);
		ut_a(father_page_zip);
		ut_a(page_zip);

		/* Copy the page byte for byte. */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3666 3667 3668 3669 3670 3671 3672 3673 3674 3675
		page_zip_copy_recs(father_page_zip, father_page,
				   page_zip, page, index, mtr);

		/* Update the lock table and possible hash index. */

		lock_move_rec_list_end(father_block, block,
				       page_get_infimum_rec(page));

		btr_search_move_or_delete_hash_entries(father_block, block,
						       index);
3676 3677
	}

Sergei Golubchik's avatar
Sergei Golubchik committed
3678
	btr_blob_dbg_remove(page, index, "btr_lift_page_up");
3679 3680 3681
	lock_update_copy_and_discard(father_block, block);

	/* Go upward to root page, decrementing levels by one. */
3682
	for (i = lift_father_up ? 1 : 0; i < n_blocks; i++, page_level++) {
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3683 3684
		page_t*		page	= buf_block_get_frame(blocks[i]);
		page_zip_des_t*	page_zip= buf_block_get_page_zip(blocks[i]);
3685 3686 3687

		ut_ad(btr_page_get_level(page, mtr) == page_level + 1);

Vadim Tkachenko's avatar
Vadim Tkachenko committed
3688 3689
		btr_page_set_level(page, page_zip, page_level, mtr);
#ifdef UNIV_ZIP_DEBUG
3690
		ut_a(!page_zip || page_zip_validate(page_zip, page, index));
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3691
#endif /* UNIV_ZIP_DEBUG */
3692 3693 3694 3695 3696
	}

	/* Free the file page */
	btr_page_free(index, block, mtr);

Vadim Tkachenko's avatar
Vadim Tkachenko committed
3697
	/* We play it safe and reset the free bits for the father */
3698 3699 3700 3701 3702
	if (!dict_index_is_clust(index)) {
		ibuf_reset_free_bits(father_block);
	}
	ut_ad(page_validate(father_page, index));
	ut_ad(btr_check_node_ptr(index, father_block, mtr));
Sergei Golubchik's avatar
Sergei Golubchik committed
3703

3704
	return(lift_father_up ? block_orig : father_block);
3705 3706
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3707
/*************************************************************//**
3708 3709 3710 3711 3712 3713 3714
Tries to merge the page first to the left immediate brother if such a
brother exists, and the node pointers to the current page and to the brother
reside on the same page. If the left brother does not satisfy these
conditions, looks at the right brother. If the page is the only one on that
level lifts the records of the page to the father page, thus reducing the
tree height. It is assumed that mtr holds an x-latch on the tree and on the
page. If cursor is on the leaf level, mtr must also hold x-latches to the
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3715 3716
brothers, if they exist.
@return	TRUE on success */
3717 3718 3719 3720
UNIV_INTERN
ibool
btr_compress(
/*=========*/
Sergei Golubchik's avatar
Sergei Golubchik committed
3721 3722 3723 3724 3725 3726 3727
	btr_cur_t*	cursor,	/*!< in/out: cursor on the page to merge
				or lift; the page must not be empty:
				when deleting records, use btr_discard_page()
				if the page would become empty */
	ibool		adjust,	/*!< in: TRUE if should adjust the
				cursor position even if compression occurs */
	mtr_t*		mtr)	/*!< in/out: mini-transaction */
3728 3729 3730 3731 3732 3733 3734
{
	dict_index_t*	index;
	ulint		space;
	ulint		zip_size;
	ulint		left_page_no;
	ulint		right_page_no;
	buf_block_t*	merge_block;
3735
	page_t*		merge_page = NULL;
3736 3737 3738 3739 3740 3741 3742
	page_zip_des_t*	merge_page_zip;
	ibool		is_left;
	buf_block_t*	block;
	page_t*		page;
	btr_cur_t	father_cursor;
	mem_heap_t*	heap;
	ulint*		offsets;
Sergei Golubchik's avatar
Sergei Golubchik committed
3743
	ulint		nth_rec = 0; /* remove bogus warning */
3744
	DBUG_ENTER("btr_compress");
3745 3746 3747 3748

	block = btr_cur_get_block(cursor);
	page = btr_cur_get_page(cursor);
	index = btr_cur_get_index(cursor);
Sergei Golubchik's avatar
Sergei Golubchik committed
3749 3750

	btr_assert_not_corrupted(block, index);
3751 3752 3753 3754 3755 3756 3757

	ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index),
				MTR_MEMO_X_LOCK));
	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
	space = dict_index_get_space(index);
	zip_size = dict_table_zip_size(index->table);

3758 3759
	MONITOR_INC(MONITOR_INDEX_MERGE_ATTEMPTS);

3760 3761 3762
	left_page_no = btr_page_get_prev(page, mtr);
	right_page_no = btr_page_get_next(page, mtr);

3763 3764 3765 3766 3767 3768 3769
#ifdef UNIV_DEBUG
	if (!page_is_leaf(page) && left_page_no == FIL_NULL) {
		ut_a(REC_INFO_MIN_REC_FLAG & rec_get_info_bits(
			page_rec_get_next(page_get_infimum_rec(page)),
			page_is_comp(page)));
	}
#endif /* UNIV_DEBUG */
3770 3771 3772 3773 3774

	heap = mem_heap_create(100);
	offsets = btr_page_get_father_block(NULL, heap, index, block, mtr,
					    &father_cursor);

Sergei Golubchik's avatar
Sergei Golubchik committed
3775 3776
	if (adjust) {
		nth_rec = page_rec_get_n_recs_before(btr_cur_get_rec(cursor));
3777
		ut_ad(nth_rec > 0);
Sergei Golubchik's avatar
Sergei Golubchik committed
3778 3779
	}

3780
	if (left_page_no == FIL_NULL && right_page_no == FIL_NULL) {
3781 3782
		/* The page is the only one on the level, lift the records
		to the father */
Sergei Golubchik's avatar
Sergei Golubchik committed
3783 3784 3785

		merge_block = btr_lift_page_up(index, block, mtr);
		goto func_exit;
3786 3787
	}

3788 3789
	/* Decide the page to which we try to merge and which will inherit
	the locks */
3790

3791 3792
	is_left = btr_can_merge_with_page(cursor, left_page_no,
					  &merge_block, mtr);
3793

3794
	DBUG_EXECUTE_IF("ib_always_merge_right", is_left = FALSE;);
3795

3796 3797 3798 3799
	if(!is_left
	   && !btr_can_merge_with_page(cursor, right_page_no, &merge_block,
				       mtr)) {
		goto err_exit;
3800 3801
	}

3802
	merge_page = buf_block_get_frame(merge_block);
3803

3804 3805 3806 3807 3808 3809 3810
#ifdef UNIV_BTR_DEBUG
	if (is_left) {
                ut_a(btr_page_get_next(merge_page, mtr)
                     == buf_block_get_page_no(block));
	} else {
               ut_a(btr_page_get_prev(merge_page, mtr)
                     == buf_block_get_page_no(block));
3811
	}
3812 3813 3814
#endif /* UNIV_BTR_DEBUG */

	ut_ad(page_validate(merge_page, index));
3815 3816 3817

	merge_page_zip = buf_block_get_page_zip(merge_block);
#ifdef UNIV_ZIP_DEBUG
3818
	if (merge_page_zip) {
3819 3820 3821
		const page_zip_des_t*	page_zip
			= buf_block_get_page_zip(block);
		ut_a(page_zip);
3822 3823
		ut_a(page_zip_validate(merge_page_zip, merge_page, index));
		ut_a(page_zip_validate(page_zip, page, index));
3824 3825 3826 3827 3828 3829 3830 3831 3832
	}
#endif /* UNIV_ZIP_DEBUG */

	/* Move records to the merge page */
	if (is_left) {
		rec_t*	orig_pred = page_copy_rec_list_start(
			merge_block, block, page_get_supremum_rec(page),
			index, mtr);

3833
		if (!orig_pred) {
3834 3835 3836
			goto err_exit;
		}

3837
		btr_search_drop_page_hash_index(block);
3838 3839

		/* Remove the page from the level list */
3840
		btr_level_list_remove(space, zip_size, page, index, mtr);
3841 3842 3843

		btr_node_ptr_delete(index, block, mtr);
		lock_update_merge_left(merge_block, orig_pred, block);
Sergei Golubchik's avatar
Sergei Golubchik committed
3844 3845 3846 3847

		if (adjust) {
			nth_rec += page_rec_get_n_recs_before(orig_pred);
		}
3848 3849
	} else {
		rec_t*		orig_succ;
3850
		ibool		compressed;
3851
		dberr_t		err;
3852 3853 3854
		btr_cur_t	cursor2;
					/* father cursor pointing to node ptr
					of the right sibling */
3855 3856 3857 3858
#ifdef UNIV_BTR_DEBUG
		byte		fil_page_prev[4];
#endif /* UNIV_BTR_DEBUG */

3859 3860 3861
		btr_page_get_father(index, merge_block, mtr, &cursor2);

		if (merge_page_zip && left_page_no == FIL_NULL) {
3862

3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879
			/* The function page_zip_compress(), which will be
			invoked by page_copy_rec_list_end() below,
			requires that FIL_PAGE_PREV be FIL_NULL.
			Clear the field, but prepare to restore it. */
#ifdef UNIV_BTR_DEBUG
			memcpy(fil_page_prev, merge_page + FIL_PAGE_PREV, 4);
#endif /* UNIV_BTR_DEBUG */
#if FIL_NULL != 0xffffffff
# error "FIL_NULL != 0xffffffff"
#endif
			memset(merge_page + FIL_PAGE_PREV, 0xff, 4);
		}

		orig_succ = page_copy_rec_list_end(merge_block, block,
						   page_get_infimum_rec(page),
						   cursor->index, mtr);

3880
		if (!orig_succ) {
3881 3882
			ut_a(merge_page_zip);
#ifdef UNIV_BTR_DEBUG
3883 3884 3885 3886 3887 3888
			if (left_page_no == FIL_NULL) {
				/* FIL_PAGE_PREV was restored from
				merge_page_zip. */
				ut_a(!memcmp(fil_page_prev,
					     merge_page + FIL_PAGE_PREV, 4));
			}
3889 3890 3891 3892
#endif /* UNIV_BTR_DEBUG */
			goto err_exit;
		}

3893
		btr_search_drop_page_hash_index(block);
3894 3895

#ifdef UNIV_BTR_DEBUG
3896
		if (merge_page_zip && left_page_no == FIL_NULL) {
3897

3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908
			/* Restore FIL_PAGE_PREV in order to avoid an assertion
			failure in btr_level_list_remove(), which will set
			the field again to FIL_NULL.  Even though this makes
			merge_page and merge_page_zip inconsistent for a
			split second, it is harmless, because the pages
			are X-latched. */
			memcpy(merge_page + FIL_PAGE_PREV, fil_page_prev, 4);
		}
#endif /* UNIV_BTR_DEBUG */

		/* Remove the page from the level list */
3909
		btr_level_list_remove(space, zip_size, page, index, mtr);
3910 3911 3912 3913 3914 3915 3916

		/* Replace the address of the old child node (= page) with the
		address of the merge page to the right */
		btr_node_ptr_set_child_page_no(
			btr_cur_get_rec(&father_cursor),
			btr_cur_get_page_zip(&father_cursor),
			offsets, right_page_no, mtr);
3917 3918

		compressed = btr_cur_pessimistic_delete(&err, TRUE, &cursor2,
3919
							BTR_CREATE_FLAG,
3920 3921 3922 3923 3924 3925
							RB_NONE, mtr);
		ut_a(err == DB_SUCCESS);

		if (!compressed) {
			btr_cur_compress_if_useful(&cursor2, FALSE, mtr);
		}
3926 3927 3928 3929

		lock_update_merge_right(merge_block, orig_succ, block);
	}

Sergei Golubchik's avatar
Sergei Golubchik committed
3930
	btr_blob_dbg_remove(page, index, "btr_compress");
3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973

	if (!dict_index_is_clust(index) && page_is_leaf(merge_page)) {
		/* Update the free bits of the B-tree page in the
		insert buffer bitmap.  This has to be done in a
		separate mini-transaction that is committed before the
		main mini-transaction.  We cannot update the insert
		buffer bitmap in this mini-transaction, because
		btr_compress() can be invoked recursively without
		committing the mini-transaction in between.  Since
		insert buffer bitmap pages have a lower rank than
		B-tree pages, we must not access other pages in the
		same mini-transaction after accessing an insert buffer
		bitmap page. */

		/* The free bits in the insert buffer bitmap must
		never exceed the free space on a page.  It is safe to
		decrement or reset the bits in the bitmap in a
		mini-transaction that is committed before the
		mini-transaction that affects the free space. */

		/* It is unsafe to increment the bits in a separately
		committed mini-transaction, because in crash recovery,
		the free bits could momentarily be set too high. */

		if (zip_size) {
			/* Because the free bits may be incremented
			and we cannot update the insert buffer bitmap
			in the same mini-transaction, the only safe
			thing we can do here is the pessimistic
			approach: reset the free bits. */
			ibuf_reset_free_bits(merge_block);
		} else {
			/* On uncompressed pages, the free bits will
			never increase here.  Thus, it is safe to
			write the bits accurately in a separate
			mini-transaction. */
			ibuf_update_free_bits_if_full(merge_block,
						      UNIV_PAGE_SIZE,
						      ULINT_UNDEFINED);
		}
	}

	ut_ad(page_validate(merge_page, index));
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3974
#ifdef UNIV_ZIP_DEBUG
3975 3976
	ut_a(!merge_page_zip || page_zip_validate(merge_page_zip, merge_page,
						  index));
Vadim Tkachenko's avatar
Vadim Tkachenko committed
3977
#endif /* UNIV_ZIP_DEBUG */
3978 3979 3980 3981 3982

	/* Free the file page */
	btr_page_free(index, block, mtr);

	ut_ad(btr_check_node_ptr(index, merge_block, mtr));
Sergei Golubchik's avatar
Sergei Golubchik committed
3983 3984 3985 3986
func_exit:
	mem_heap_free(heap);

	if (adjust) {
3987
		ut_ad(nth_rec > 0);
Sergei Golubchik's avatar
Sergei Golubchik committed
3988 3989 3990 3991 3992
		btr_cur_position(
			index,
			page_rec_get_nth(merge_block->frame, nth_rec),
			merge_block, cursor);
	}
3993 3994 3995

	MONITOR_INC(MONITOR_INDEX_MERGE_SUCCESSFUL);

3996
	DBUG_RETURN(TRUE);
Sergei Golubchik's avatar
Sergei Golubchik committed
3997

3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008
err_exit:
	/* We play it safe and reset the free bits. */
	if (zip_size
	    && merge_page
	    && page_is_leaf(merge_page)
	    && !dict_index_is_clust(index)) {
		ibuf_reset_free_bits(merge_block);
	}

	mem_heap_free(heap);
	DBUG_RETURN(FALSE);
4009 4010
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4011
/*************************************************************//**
Vadim Tkachenko's avatar
Vadim Tkachenko committed
4012 4013 4014 4015
Discards a page that is the only page on its level.  This will empty
the whole B-tree, leaving just an empty root page.  This function
should never be reached, because btr_compress(), which is invoked in
delete operations, calls btr_lift_page_up() to flatten the B-tree. */
4016 4017 4018 4019
static
void
btr_discard_only_page_on_level(
/*===========================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4020 4021 4022
	dict_index_t*	index,	/*!< in: index tree */
	buf_block_t*	block,	/*!< in: page which is the only on its level */
	mtr_t*		mtr)	/*!< in: mtr */
4023
{
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4024 4025 4026 4027 4028
	ulint		page_level = 0;
	trx_id_t	max_trx_id;

	/* Save the PAGE_MAX_TRX_ID from the leaf page. */
	max_trx_id = page_get_max_trx_id(buf_block_get_frame(block));
4029

Vadim Tkachenko's avatar
Vadim Tkachenko committed
4030 4031 4032 4033
	while (buf_block_get_page_no(block) != dict_index_get_page(index)) {
		btr_cur_t	cursor;
		buf_block_t*	father;
		const page_t*	page	= buf_block_get_frame(block);
4034

Vadim Tkachenko's avatar
Vadim Tkachenko committed
4035 4036 4037 4038
		ut_a(page_get_n_recs(page) == 1);
		ut_a(page_level == btr_page_get_level(page, mtr));
		ut_a(btr_page_get_prev(page, mtr) == FIL_NULL);
		ut_a(btr_page_get_next(page, mtr) == FIL_NULL);
4039

Vadim Tkachenko's avatar
Vadim Tkachenko committed
4040
		ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
4041
		btr_search_drop_page_hash_index(block);
4042

Vadim Tkachenko's avatar
Vadim Tkachenko committed
4043 4044
		btr_page_get_father(index, block, mtr, &cursor);
		father = btr_cur_get_block(&cursor);
4045

Vadim Tkachenko's avatar
Vadim Tkachenko committed
4046
		lock_update_discard(father, PAGE_HEAP_NO_SUPREMUM, block);
4047

Vadim Tkachenko's avatar
Vadim Tkachenko committed
4048 4049
		/* Free the file page */
		btr_page_free(index, block, mtr);
4050

Vadim Tkachenko's avatar
Vadim Tkachenko committed
4051 4052 4053 4054 4055 4056
		block = father;
		page_level++;
	}

	/* block is the root page, which must be empty, except
	for the node pointer to the (now discarded) block(s). */
4057

Vadim Tkachenko's avatar
Vadim Tkachenko committed
4058
#ifdef UNIV_BTR_DEBUG
Vadim Tkachenko's avatar
Vadim Tkachenko committed
4059 4060 4061 4062 4063 4064 4065 4066
	if (!dict_index_is_ibuf(index)) {
		const page_t*	root	= buf_block_get_frame(block);
		const ulint	space	= dict_index_get_space(index);
		ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF
					    + root, space));
		ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP
					    + root, space));
	}
Vadim Tkachenko's avatar
Vadim Tkachenko committed
4067
#endif /* UNIV_BTR_DEBUG */
4068

Vadim Tkachenko's avatar
Vadim Tkachenko committed
4069
	btr_page_empty(block, buf_block_get_page_zip(block), index, 0, mtr);
4070
	ut_ad(page_is_leaf(buf_block_get_frame(block)));
4071

Vadim Tkachenko's avatar
Vadim Tkachenko committed
4072
	if (!dict_index_is_clust(index)) {
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4073
		/* We play it safe and reset the free bits for the root */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
4074
		ibuf_reset_free_bits(block);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4075

4076 4077 4078 4079
		ut_a(max_trx_id);
		page_set_max_trx_id(block,
				    buf_block_get_page_zip(block),
				    max_trx_id, mtr);
4080 4081 4082
	}
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4083
/*************************************************************//**
4084 4085 4086 4087 4088 4089 4090
Discards a page from a B-tree. This is used to remove the last record from
a B-tree page: the whole page must be removed at the same time. This cannot
be used for the root page, which is allowed to be empty. */
UNIV_INTERN
void
btr_discard_page(
/*=============*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4091
	btr_cur_t*	cursor,	/*!< in: cursor on the page to discard: not on
4092
				the root page */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4093
	mtr_t*		mtr)	/*!< in: mtr */
4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115
{
	dict_index_t*	index;
	ulint		space;
	ulint		zip_size;
	ulint		left_page_no;
	ulint		right_page_no;
	buf_block_t*	merge_block;
	page_t*		merge_page;
	buf_block_t*	block;
	page_t*		page;
	rec_t*		node_ptr;

	block = btr_cur_get_block(cursor);
	index = btr_cur_get_index(cursor);

	ut_ad(dict_index_get_page(index) != buf_block_get_page_no(block));
	ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index),
				MTR_MEMO_X_LOCK));
	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
	space = dict_index_get_space(index);
	zip_size = dict_table_zip_size(index->table);

4116 4117
	MONITOR_INC(MONITOR_INDEX_DISCARD);

4118 4119 4120 4121 4122 4123 4124
	/* Decide the page which will inherit the locks */

	left_page_no = btr_page_get_prev(buf_block_get_frame(block), mtr);
	right_page_no = btr_page_get_next(buf_block_get_frame(block), mtr);

	if (left_page_no != FIL_NULL) {
		merge_block = btr_block_get(space, zip_size, left_page_no,
4125
					    RW_X_LATCH, index, mtr);
4126 4127 4128 4129 4130 4131 4132
		merge_page = buf_block_get_frame(merge_block);
#ifdef UNIV_BTR_DEBUG
		ut_a(btr_page_get_next(merge_page, mtr)
		     == buf_block_get_page_no(block));
#endif /* UNIV_BTR_DEBUG */
	} else if (right_page_no != FIL_NULL) {
		merge_block = btr_block_get(space, zip_size, right_page_no,
4133
					    RW_X_LATCH, index, mtr);
4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146
		merge_page = buf_block_get_frame(merge_block);
#ifdef UNIV_BTR_DEBUG
		ut_a(btr_page_get_prev(merge_page, mtr)
		     == buf_block_get_page_no(block));
#endif /* UNIV_BTR_DEBUG */
	} else {
		btr_discard_only_page_on_level(index, block, mtr);

		return;
	}

	page = buf_block_get_frame(block);
	ut_a(page_is_comp(merge_page) == page_is_comp(page));
4147
	btr_search_drop_page_hash_index(block);
4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167

	if (left_page_no == FIL_NULL && !page_is_leaf(page)) {

		/* We have to mark the leftmost node pointer on the right
		side page as the predefined minimum record */
		node_ptr = page_rec_get_next(page_get_infimum_rec(merge_page));

		ut_ad(page_rec_is_user_rec(node_ptr));

		/* This will make page_zip_validate() fail on merge_page
		until btr_level_list_remove() completes.  This is harmless,
		because everything will take place within a single
		mini-transaction and because writing to the redo log
		is an atomic operation (performed by mtr_commit()). */
		btr_set_min_rec_mark(node_ptr, mtr);
	}

	btr_node_ptr_delete(index, block, mtr);

	/* Remove the page from the level list */
4168
	btr_level_list_remove(space, zip_size, page, index, mtr);
4169 4170 4171 4172 4173
#ifdef UNIV_ZIP_DEBUG
	{
		page_zip_des_t*	merge_page_zip
			= buf_block_get_page_zip(merge_block);
		ut_a(!merge_page_zip
4174
		     || page_zip_validate(merge_page_zip, merge_page, index));
4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186
	}
#endif /* UNIV_ZIP_DEBUG */

	if (left_page_no != FIL_NULL) {
		lock_update_discard(merge_block, PAGE_HEAP_NO_SUPREMUM,
				    block);
	} else {
		lock_update_discard(merge_block,
				    lock_get_min_heap_no(merge_block),
				    block);
	}

Sergei Golubchik's avatar
Sergei Golubchik committed
4187 4188
	btr_blob_dbg_remove(page, index, "btr_discard_page");

4189 4190 4191 4192 4193 4194 4195
	/* Free the file page */
	btr_page_free(index, block, mtr);

	ut_ad(btr_check_node_ptr(index, merge_block, mtr));
}

#ifdef UNIV_BTR_PRINT
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4196
/*************************************************************//**
4197 4198 4199 4200 4201
Prints size info of a B-tree. */
UNIV_INTERN
void
btr_print_size(
/*===========*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4202
	dict_index_t*	index)	/*!< in: index tree */
4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223
{
	page_t*		root;
	fseg_header_t*	seg;
	mtr_t		mtr;

	if (dict_index_is_ibuf(index)) {
		fputs("Sorry, cannot print info of an ibuf tree:"
		      " use ibuf functions\n", stderr);

		return;
	}

	mtr_start(&mtr);

	root = btr_root_get(index, &mtr);

	seg = root + PAGE_HEADER + PAGE_BTR_SEG_TOP;

	fputs("INFO OF THE NON-LEAF PAGE SEGMENT\n", stderr);
	fseg_print(seg, &mtr);

4224
	if (!dict_index_is_univ(index)) {
4225 4226 4227 4228 4229 4230 4231 4232 4233 4234

		seg = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF;

		fputs("INFO OF THE LEAF PAGE SEGMENT\n", stderr);
		fseg_print(seg, &mtr);
	}

	mtr_commit(&mtr);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4235
/************************************************************//**
4236 4237 4238 4239 4240
Prints recursively index tree pages. */
static
void
btr_print_recursive(
/*================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4241 4242 4243
	dict_index_t*	index,	/*!< in: index tree */
	buf_block_t*	block,	/*!< in: index page */
	ulint		width,	/*!< in: print this many entries from start
4244
				and end */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4245 4246 4247
	mem_heap_t**	heap,	/*!< in/out: heap for rec_get_offsets() */
	ulint**		offsets,/*!< in/out: buffer for rec_get_offsets() */
	mtr_t*		mtr)	/*!< in: mtr */
4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296
{
	const page_t*	page	= buf_block_get_frame(block);
	page_cur_t	cursor;
	ulint		n_recs;
	ulint		i	= 0;
	mtr_t		mtr2;

	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
	fprintf(stderr, "NODE ON LEVEL %lu page number %lu\n",
		(ulong) btr_page_get_level(page, mtr),
		(ulong) buf_block_get_page_no(block));

	page_print(block, index, width, width);

	n_recs = page_get_n_recs(page);

	page_cur_set_before_first(block, &cursor);
	page_cur_move_to_next(&cursor);

	while (!page_cur_is_after_last(&cursor)) {

		if (page_is_leaf(page)) {

			/* If this is the leaf level, do nothing */

		} else if ((i <= width) || (i >= n_recs - width)) {

			const rec_t*	node_ptr;

			mtr_start(&mtr2);

			node_ptr = page_cur_get_rec(&cursor);

			*offsets = rec_get_offsets(node_ptr, index, *offsets,
						   ULINT_UNDEFINED, heap);
			btr_print_recursive(index,
					    btr_node_ptr_get_child(node_ptr,
								   index,
								   *offsets,
								   &mtr2),
					    width, heap, offsets, &mtr2);
			mtr_commit(&mtr2);
		}

		page_cur_move_to_next(&cursor);
		i++;
	}
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4297
/**************************************************************//**
4298 4299 4300 4301 4302
Prints directories and other info of all nodes in the tree. */
UNIV_INTERN
void
btr_print_index(
/*============*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4303 4304
	dict_index_t*	index,	/*!< in: index */
	ulint		width)	/*!< in: print this many entries from start
4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318
				and end */
{
	mtr_t		mtr;
	buf_block_t*	root;
	mem_heap_t*	heap	= NULL;
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
	ulint*		offsets	= offsets_;
	rec_offs_init(offsets_);

	fputs("--------------------------\n"
	      "INDEX TREE PRINT\n", stderr);

	mtr_start(&mtr);

4319
	root = btr_root_block_get(index, RW_X_LATCH, &mtr);
4320 4321

	btr_print_recursive(index, root, width, &heap, &offsets, &mtr);
4322
	if (heap) {
4323 4324 4325 4326 4327
		mem_heap_free(heap);
	}

	mtr_commit(&mtr);

4328
	btr_validate_index(index, 0);
4329 4330 4331 4332
}
#endif /* UNIV_BTR_PRINT */

#ifdef UNIV_DEBUG
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4333 4334 4335
/************************************************************//**
Checks that the node pointer to a page is appropriate.
@return	TRUE */
4336 4337 4338 4339
UNIV_INTERN
ibool
btr_check_node_ptr(
/*===============*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4340 4341 4342
	dict_index_t*	index,	/*!< in: index tree */
	buf_block_t*	block,	/*!< in: index page */
	mtr_t*		mtr)	/*!< in: mtr */
4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376
{
	mem_heap_t*	heap;
	dtuple_t*	tuple;
	ulint*		offsets;
	btr_cur_t	cursor;
	page_t*		page = buf_block_get_frame(block);

	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
	if (dict_index_get_page(index) == buf_block_get_page_no(block)) {

		return(TRUE);
	}

	heap = mem_heap_create(256);
	offsets = btr_page_get_father_block(NULL, heap, index, block, mtr,
					    &cursor);

	if (page_is_leaf(page)) {

		goto func_exit;
	}

	tuple = dict_index_build_node_ptr(
		index, page_rec_get_next(page_get_infimum_rec(page)), 0, heap,
		btr_page_get_level(page, mtr));

	ut_a(!cmp_dtuple_rec(tuple, btr_cur_get_rec(&cursor), offsets));
func_exit:
	mem_heap_free(heap);

	return(TRUE);
}
#endif /* UNIV_DEBUG */

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4377
/************************************************************//**
4378 4379 4380 4381 4382
Display identification information for a record. */
static
void
btr_index_rec_validate_report(
/*==========================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4383 4384 4385
	const page_t*		page,	/*!< in: index page */
	const rec_t*		rec,	/*!< in: index record */
	const dict_index_t*	index)	/*!< in: index */
4386 4387 4388 4389 4390 4391 4392
{
	fputs("InnoDB: Record in ", stderr);
	dict_index_name_print(stderr, NULL, index);
	fprintf(stderr, ", page %lu, at offset %lu\n",
		page_get_page_no(page), (ulint) page_offset(rec));
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4393
/************************************************************//**
4394
Checks the size and number of fields in a record based on the definition of
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4395 4396
the index.
@return	TRUE if ok */
4397 4398 4399 4400
UNIV_INTERN
ibool
btr_index_rec_validate(
/*===================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4401 4402 4403
	const rec_t*		rec,		/*!< in: index record */
	const dict_index_t*	index,		/*!< in: index */
	ibool			dump_on_error)	/*!< in: TRUE if the function
4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417
						should print hex dump of record
						and page on error */
{
	ulint		len;
	ulint		n;
	ulint		i;
	const page_t*	page;
	mem_heap_t*	heap	= NULL;
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
	ulint*		offsets	= offsets_;
	rec_offs_init(offsets_);

	page = page_align(rec);

4418
	if (dict_index_is_univ(index)) {
4419 4420 4421 4422 4423 4424 4425
		/* The insert buffer index tree can contain records from any
		other index: we cannot check the number of fields or
		their length */

		return(TRUE);
	}

4426
	if ((ibool)!!page_is_comp(page) != dict_table_is_comp(index->table)) {
4427 4428 4429 4430 4431 4432 4433 4434 4435 4436
		btr_index_rec_validate_report(page, rec, index);
		fprintf(stderr, "InnoDB: compact flag=%lu, should be %lu\n",
			(ulong) !!page_is_comp(page),
			(ulong) dict_table_is_comp(index->table));

		return(FALSE);
	}

	n = dict_index_get_n_fields(index);

4437
	if (!page_is_comp(page) && rec_get_n_fields_old(rec) != n) {
4438 4439 4440 4441 4442
		btr_index_rec_validate_report(page, rec, index);
		fprintf(stderr, "InnoDB: has %lu fields, should have %lu\n",
			(ulong) rec_get_n_fields_old(rec), (ulong) n);

		if (dump_on_error) {
Sergei Golubchik's avatar
Sergei Golubchik committed
4443
			buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH);
4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455

			fputs("InnoDB: corrupt record ", stderr);
			rec_print_old(stderr, rec);
			putc('\n', stderr);
		}
		return(FALSE);
	}

	offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap);

	for (i = 0; i < n; i++) {
		ulint	fixed_size = dict_col_get_fixed_size(
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4456
			dict_index_get_nth_col(index, i), page_is_comp(page));
4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480

		rec_get_nth_field_offs(offsets, i, &len);

		/* Note that if fixed_size != 0, it equals the
		length of a fixed-size column in the clustered index.
		A prefix index of the column is of fixed, but different
		length.  When fixed_size == 0, prefix_len is the maximum
		length of the prefix index column. */

		if ((dict_index_get_nth_field(index, i)->prefix_len == 0
		     && len != UNIV_SQL_NULL && fixed_size
		     && len != fixed_size)
		    || (dict_index_get_nth_field(index, i)->prefix_len > 0
			&& len != UNIV_SQL_NULL
			&& len
			> dict_index_get_nth_field(index, i)->prefix_len)) {

			btr_index_rec_validate_report(page, rec, index);
			fprintf(stderr,
				"InnoDB: field %lu len is %lu,"
				" should be %lu\n",
				(ulong) i, (ulong) len, (ulong) fixed_size);

			if (dump_on_error) {
Sergei Golubchik's avatar
Sergei Golubchik committed
4481 4482
				buf_page_print(page, 0,
					       BUF_PAGE_PRINT_NO_CRASH);
4483 4484 4485 4486 4487

				fputs("InnoDB: corrupt record ", stderr);
				rec_print_new(stderr, rec, offsets);
				putc('\n', stderr);
			}
4488
			if (heap) {
4489 4490 4491 4492 4493 4494
				mem_heap_free(heap);
			}
			return(FALSE);
		}
	}

4495
	if (heap) {
4496 4497 4498 4499 4500
		mem_heap_free(heap);
	}
	return(TRUE);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4501
/************************************************************//**
4502
Checks the size and number of fields in records based on the definition of
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4503 4504
the index.
@return	TRUE if ok */
4505 4506 4507 4508
static
ibool
btr_index_page_validate(
/*====================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4509 4510
	buf_block_t*	block,	/*!< in: index page */
	dict_index_t*	index)	/*!< in: index */
4511 4512 4513
{
	page_cur_t	cur;
	ibool		ret	= TRUE;
4514 4515 4516
#ifndef DBUG_OFF
	ulint		nth	= 1;
#endif /* !DBUG_OFF */
4517 4518

	page_cur_set_before_first(block, &cur);
4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529

	/* Directory slot 0 should only contain the infimum record. */
	DBUG_EXECUTE_IF("check_table_rec_next",
			ut_a(page_rec_get_nth_const(
				     page_cur_get_page(&cur), 0)
			     == cur.rec);
			ut_a(page_dir_slot_get_n_owned(
				     page_dir_get_nth_slot(
					     page_cur_get_page(&cur), 0))
			     == 1););

4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542
	page_cur_move_to_next(&cur);

	for (;;) {
		if (page_cur_is_after_last(&cur)) {

			break;
		}

		if (!btr_index_rec_validate(cur.rec, index, TRUE)) {

			return(FALSE);
		}

4543 4544 4545 4546 4547 4548 4549 4550 4551 4552
		/* Verify that page_rec_get_nth_const() is correctly
		retrieving each record. */
		DBUG_EXECUTE_IF("check_table_rec_next",
				ut_a(cur.rec == page_rec_get_nth_const(
					     page_cur_get_page(&cur),
					     page_rec_get_n_recs_before(
						     cur.rec)));
				ut_a(nth++ == page_rec_get_n_recs_before(
					     cur.rec)););

4553 4554 4555 4556 4557 4558
		page_cur_move_to_next(&cur);
	}

	return(ret);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4559
/************************************************************//**
4560 4561 4562 4563 4564
Report an error on one page of an index tree. */
static
void
btr_validate_report1(
/*=================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4565 4566 4567
	dict_index_t*		index,	/*!< in: index */
	ulint			level,	/*!< in: B-tree level */
	const buf_block_t*	block)	/*!< in: index page */
4568 4569 4570 4571 4572 4573 4574 4575 4576 4577
{
	fprintf(stderr, "InnoDB: Error in page %lu of ",
		buf_block_get_page_no(block));
	dict_index_name_print(stderr, NULL, index);
	if (level) {
		fprintf(stderr, ", index tree level %lu", level);
	}
	putc('\n', stderr);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4578
/************************************************************//**
4579 4580 4581 4582 4583
Report an error on two pages of an index tree. */
static
void
btr_validate_report2(
/*=================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4584 4585 4586 4587
	const dict_index_t*	index,	/*!< in: index */
	ulint			level,	/*!< in: B-tree level */
	const buf_block_t*	block1,	/*!< in: first index page */
	const buf_block_t*	block2)	/*!< in: second index page */
4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598
{
	fprintf(stderr, "InnoDB: Error in pages %lu and %lu of ",
		buf_block_get_page_no(block1),
		buf_block_get_page_no(block2));
	dict_index_name_print(stderr, NULL, index);
	if (level) {
		fprintf(stderr, ", index tree level %lu", level);
	}
	putc('\n', stderr);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4599 4600 4601
/************************************************************//**
Validates index tree level.
@return	TRUE if ok */
4602
static
4603
bool
4604 4605
btr_validate_level(
/*===============*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4606
	dict_index_t*	index,	/*!< in: index tree */
4607
	const trx_t*	trx,	/*!< in: transaction or NULL */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4608
	ulint		level)	/*!< in: level number */
4609 4610
{
	ulint		space;
4611
	ulint		space_flags;
4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624
	ulint		zip_size;
	buf_block_t*	block;
	page_t*		page;
	buf_block_t*	right_block = 0; /* remove warning */
	page_t*		right_page = 0; /* remove warning */
	page_t*		father_page;
	btr_cur_t	node_cur;
	btr_cur_t	right_node_cur;
	rec_t*		rec;
	ulint		right_page_no;
	ulint		left_page_no;
	page_cur_t	cursor;
	dtuple_t*	node_ptr_tuple;
4625
	bool		ret	= true;
4626 4627
	mtr_t		mtr;
	mem_heap_t*	heap	= mem_heap_create(256);
4628
	fseg_header_t*	seg;
4629 4630 4631 4632 4633 4634 4635 4636 4637 4638
	ulint*		offsets	= NULL;
	ulint*		offsets2= NULL;
#ifdef UNIV_ZIP_DEBUG
	page_zip_des_t*	page_zip;
#endif /* UNIV_ZIP_DEBUG */

	mtr_start(&mtr);

	mtr_x_lock(dict_index_get_lock(index), &mtr);

4639
	block = btr_root_block_get(index, RW_X_LATCH, &mtr);
4640
	page = buf_block_get_frame(block);
4641
	seg = page + PAGE_HEADER + PAGE_BTR_SEG_TOP;
4642 4643 4644 4645

	space = dict_index_get_space(index);
	zip_size = dict_table_zip_size(index->table);

4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658
	fil_space_get_latch(space, &space_flags);

	if (zip_size != dict_tf_get_zip_size(space_flags)) {

		ib_logf(IB_LOG_LEVEL_WARN,
			"Flags mismatch: table=%lu, tablespace=%lu",
			(ulint) index->table->flags, (ulint) space_flags);

		mtr_commit(&mtr);

		return(false);
	}

4659 4660 4661
	while (level != btr_page_get_level(page, &mtr)) {
		const rec_t*	node_ptr;

4662 4663 4664 4665 4666 4667 4668 4669 4670 4671
		if (fseg_page_is_free(seg,
				      block->page.space, block->page.offset)) {

			btr_validate_report1(index, level, block);

			ib_logf(IB_LOG_LEVEL_WARN, "page is free");

			ret = false;
		}

4672 4673 4674 4675
		ut_a(space == buf_block_get_space(block));
		ut_a(space == page_get_space_id(page));
#ifdef UNIV_ZIP_DEBUG
		page_zip = buf_block_get_page_zip(block);
4676
		ut_a(!page_zip || page_zip_validate(page_zip, page, index));
4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691
#endif /* UNIV_ZIP_DEBUG */
		ut_a(!page_is_leaf(page));

		page_cur_set_before_first(block, &cursor);
		page_cur_move_to_next(&cursor);

		node_ptr = page_cur_get_rec(&cursor);
		offsets = rec_get_offsets(node_ptr, index, offsets,
					  ULINT_UNDEFINED, &heap);
		block = btr_node_ptr_get_child(node_ptr, index, offsets, &mtr);
		page = buf_block_get_frame(block);
	}

	/* Now we are on the desired level. Loop through the pages on that
	level. */
4692 4693 4694 4695

	if (level == 0) {
		/* Leaf pages are managed in their own file segment. */
		seg -= PAGE_BTR_SEG_TOP - PAGE_BTR_SEG_LEAF;
4696
	}
4697 4698

loop:
4699 4700 4701 4702 4703 4704
	mem_heap_empty(heap);
	offsets = offsets2 = NULL;
	mtr_x_lock(dict_index_get_lock(index), &mtr);

#ifdef UNIV_ZIP_DEBUG
	page_zip = buf_block_get_page_zip(block);
4705
	ut_a(!page_zip || page_zip_validate(page_zip, page, index));
4706 4707
#endif /* UNIV_ZIP_DEBUG */

4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726
	ut_a(block->page.space == space);

	if (fseg_page_is_free(seg, block->page.space, block->page.offset)) {

		btr_validate_report1(index, level, block);

		ib_logf(IB_LOG_LEVEL_WARN, "Page is marked as free");
		ret = false;

	} else if (btr_page_get_index_id(page) != index->id) {

		ib_logf(IB_LOG_LEVEL_ERROR,
			"Page index id " IB_ID_FMT " != data dictionary "
			"index id " IB_ID_FMT,
			btr_page_get_index_id(page), index->id);

		ret = false;

	} else if (!page_validate(page, index)) {
4727 4728

		btr_validate_report1(index, level, block);
4729 4730 4731
		ret = false;

	} else if (level == 0 && !btr_index_page_validate(block, index)) {
4732 4733 4734 4735

		/* We are on level 0. Check that the records have the right
		number of fields, and field lengths are right. */

4736
		ret = false;
4737 4738 4739 4740 4741 4742 4743
	}

	ut_a(btr_page_get_level(page, &mtr) == level);

	right_page_no = btr_page_get_next(page, &mtr);
	left_page_no = btr_page_get_prev(page, &mtr);

4744 4745 4746
	ut_a(!page_is_empty(page)
	     || (level == 0
		 && page_get_page_no(page) == dict_index_get_page(index)));
4747 4748 4749 4750

	if (right_page_no != FIL_NULL) {
		const rec_t*	right_rec;
		right_block = btr_block_get(space, zip_size, right_page_no,
4751
					    RW_X_LATCH, index, &mtr);
4752
		right_page = buf_block_get_frame(right_block);
4753 4754 4755
		if (btr_page_get_prev(right_page, &mtr)
		    != page_get_page_no(page)) {

4756 4757 4758
			btr_validate_report2(index, level, block, right_block);
			fputs("InnoDB: broken FIL_PAGE_NEXT"
			      " or FIL_PAGE_PREV links\n", stderr);
Sergei Golubchik's avatar
Sergei Golubchik committed
4759 4760
			buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH);
			buf_page_print(right_page, 0, BUF_PAGE_PRINT_NO_CRASH);
4761

4762
			ret = false;
4763 4764
		}

4765
		if (page_is_comp(right_page) != page_is_comp(page)) {
4766 4767
			btr_validate_report2(index, level, block, right_block);
			fputs("InnoDB: 'compact' flag mismatch\n", stderr);
Sergei Golubchik's avatar
Sergei Golubchik committed
4768 4769
			buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH);
			buf_page_print(right_page, 0, BUF_PAGE_PRINT_NO_CRASH);
4770

4771
			ret = false;
4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782

			goto node_ptr_fails;
		}

		rec = page_rec_get_prev(page_get_supremum_rec(page));
		right_rec = page_rec_get_next(page_get_infimum_rec(
						      right_page));
		offsets = rec_get_offsets(rec, index,
					  offsets, ULINT_UNDEFINED, &heap);
		offsets2 = rec_get_offsets(right_rec, index,
					   offsets2, ULINT_UNDEFINED, &heap);
4783 4784
		if (cmp_rec_rec(rec, right_rec, offsets, offsets2,
			        index) >= 0) {
4785 4786 4787 4788 4789 4790

			btr_validate_report2(index, level, block, right_block);

			fputs("InnoDB: records in wrong order"
			      " on adjacent pages\n", stderr);

Sergei Golubchik's avatar
Sergei Golubchik committed
4791 4792
			buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH);
			buf_page_print(right_page, 0, BUF_PAGE_PRINT_NO_CRASH);
4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803

			fputs("InnoDB: record ", stderr);
			rec = page_rec_get_prev(page_get_supremum_rec(page));
			rec_print(stderr, rec, index);
			putc('\n', stderr);
			fputs("InnoDB: record ", stderr);
			rec = page_rec_get_next(
				page_get_infimum_rec(right_page));
			rec_print(stderr, rec, index);
			putc('\n', stderr);

4804
			ret = false;
4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830
		}
	}

	if (level > 0 && left_page_no == FIL_NULL) {
		ut_a(REC_INFO_MIN_REC_FLAG & rec_get_info_bits(
			     page_rec_get_next(page_get_infimum_rec(page)),
			     page_is_comp(page)));
	}

	if (buf_block_get_page_no(block) != dict_index_get_page(index)) {

		/* Check father node pointers */

		rec_t*	node_ptr;

		offsets = btr_page_get_father_block(offsets, heap, index,
						    block, &mtr, &node_cur);
		father_page = btr_cur_get_page(&node_cur);
		node_ptr = btr_cur_get_rec(&node_cur);

		btr_cur_position(
			index, page_rec_get_prev(page_get_supremum_rec(page)),
			block, &node_cur);
		offsets = btr_page_get_father_node_ptr(offsets, heap,
						       &node_cur, &mtr);

4831 4832 4833
		if (node_ptr != btr_cur_get_rec(&node_cur)
		    || btr_node_ptr_get_child_page_no(node_ptr, offsets)
				     != buf_block_get_page_no(block)) {
4834 4835 4836 4837 4838 4839

			btr_validate_report1(index, level, block);

			fputs("InnoDB: node pointer to the page is wrong\n",
			      stderr);

Sergei Golubchik's avatar
Sergei Golubchik committed
4840 4841
			buf_page_print(father_page, 0, BUF_PAGE_PRINT_NO_CRASH);
			buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH);
4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854

			fputs("InnoDB: node ptr ", stderr);
			rec_print(stderr, node_ptr, index);

			rec = btr_cur_get_rec(&node_cur);
			fprintf(stderr, "\n"
				"InnoDB: node ptr child page n:o %lu\n",
				(ulong) btr_node_ptr_get_child_page_no(
					rec, offsets));

			fputs("InnoDB: record on page ", stderr);
			rec_print_new(stderr, rec, offsets);
			putc('\n', stderr);
4855
			ret = false;
4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872

			goto node_ptr_fails;
		}

		if (!page_is_leaf(page)) {
			node_ptr_tuple = dict_index_build_node_ptr(
				index,
				page_rec_get_next(page_get_infimum_rec(page)),
				0, heap, btr_page_get_level(page, &mtr));

			if (cmp_dtuple_rec(node_ptr_tuple, node_ptr,
					   offsets)) {
				const rec_t* first_rec = page_rec_get_next(
					page_get_infimum_rec(page));

				btr_validate_report1(index, level, block);

Sergei Golubchik's avatar
Sergei Golubchik committed
4873 4874 4875 4876
				buf_page_print(father_page, 0,
					       BUF_PAGE_PRINT_NO_CRASH);
				buf_page_print(page, 0,
					       BUF_PAGE_PRINT_NO_CRASH);
4877 4878 4879 4880 4881 4882 4883 4884

				fputs("InnoDB: Error: node ptrs differ"
				      " on levels > 0\n"
				      "InnoDB: node ptr ", stderr);
				rec_print_new(stderr, node_ptr, offsets);
				fputs("InnoDB: first rec ", stderr);
				rec_print(stderr, first_rec, index);
				putc('\n', stderr);
4885
				ret = false;
4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912

				goto node_ptr_fails;
			}
		}

		if (left_page_no == FIL_NULL) {
			ut_a(node_ptr == page_rec_get_next(
				     page_get_infimum_rec(father_page)));
			ut_a(btr_page_get_prev(father_page, &mtr) == FIL_NULL);
		}

		if (right_page_no == FIL_NULL) {
			ut_a(node_ptr == page_rec_get_prev(
				     page_get_supremum_rec(father_page)));
			ut_a(btr_page_get_next(father_page, &mtr) == FIL_NULL);
		} else {
			const rec_t*	right_node_ptr
				= page_rec_get_next(node_ptr);

			offsets = btr_page_get_father_block(
				offsets, heap, index, right_block,
				&mtr, &right_node_cur);
			if (right_node_ptr
			    != page_get_supremum_rec(father_page)) {

				if (btr_cur_get_rec(&right_node_cur)
				    != right_node_ptr) {
4913
					ret = false;
4914 4915 4916 4917 4918 4919 4920
					fputs("InnoDB: node pointer to"
					      " the right page is wrong\n",
					      stderr);

					btr_validate_report1(index, level,
							     block);

Sergei Golubchik's avatar
Sergei Golubchik committed
4921 4922 4923 4924 4925 4926 4927 4928 4929
					buf_page_print(
						father_page, 0,
						BUF_PAGE_PRINT_NO_CRASH);
					buf_page_print(
						page, 0,
						BUF_PAGE_PRINT_NO_CRASH);
					buf_page_print(
						right_page, 0,
						BUF_PAGE_PRINT_NO_CRASH);
4930 4931 4932 4933 4934 4935 4936 4937 4938
				}
			} else {
				page_t*	right_father_page
					= btr_cur_get_page(&right_node_cur);

				if (btr_cur_get_rec(&right_node_cur)
				    != page_rec_get_next(
					    page_get_infimum_rec(
						    right_father_page))) {
4939
					ret = false;
4940 4941 4942 4943 4944 4945 4946
					fputs("InnoDB: node pointer 2 to"
					      " the right page is wrong\n",
					      stderr);

					btr_validate_report1(index, level,
							     block);

Sergei Golubchik's avatar
Sergei Golubchik committed
4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958
					buf_page_print(
						father_page, 0,
						BUF_PAGE_PRINT_NO_CRASH);
					buf_page_print(
						right_father_page, 0,
						BUF_PAGE_PRINT_NO_CRASH);
					buf_page_print(
						page, 0,
						BUF_PAGE_PRINT_NO_CRASH);
					buf_page_print(
						right_page, 0,
						BUF_PAGE_PRINT_NO_CRASH);
4959 4960 4961 4962 4963
				}

				if (page_get_page_no(right_father_page)
				    != btr_page_get_next(father_page, &mtr)) {

4964
					ret = false;
4965 4966 4967 4968 4969 4970 4971
					fputs("InnoDB: node pointer 3 to"
					      " the right page is wrong\n",
					      stderr);

					btr_validate_report1(index, level,
							     block);

Sergei Golubchik's avatar
Sergei Golubchik committed
4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983
					buf_page_print(
						father_page, 0,
						BUF_PAGE_PRINT_NO_CRASH);
					buf_page_print(
						right_father_page, 0,
						BUF_PAGE_PRINT_NO_CRASH);
					buf_page_print(
						page, 0,
						BUF_PAGE_PRINT_NO_CRASH);
					buf_page_print(
						right_page, 0,
						BUF_PAGE_PRINT_NO_CRASH);
4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994
				}
			}
		}
	}

node_ptr_fails:
	/* Commit the mini-transaction to release the latch on 'page'.
	Re-acquire the latch on right_page, which will become 'page'
	on the next loop.  The page has already been checked. */
	mtr_commit(&mtr);

4995 4996 4997 4998
	if (trx_is_interrupted(trx)) {
		/* On interrupt, return the current status. */
	} else if (right_page_no != FIL_NULL) {

4999 5000
		mtr_start(&mtr);

5001 5002 5003 5004
		block = btr_block_get(
			space, zip_size, right_page_no,
			RW_X_LATCH, index, &mtr);

5005 5006 5007 5008 5009 5010
		page = buf_block_get_frame(block);

		goto loop;
	}

	mem_heap_free(heap);
5011

5012 5013 5014
	return(ret);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
5015 5016 5017
/**************************************************************//**
Checks the consistency of an index tree.
@return	TRUE if ok */
5018
UNIV_INTERN
5019
bool
5020 5021
btr_validate_index(
/*===============*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
5022
	dict_index_t*	index,	/*!< in: index */
5023
	const trx_t*	trx)	/*!< in: transaction or NULL */
5024
{
5025 5026 5027 5028 5029 5030 5031
	/* Full Text index are implemented by auxiliary tables,
	not the B-tree */
	if (dict_index_is_online_ddl(index) || (index->type & DICT_FTS)) {
		return(true);
	}

	mtr_t		mtr;
5032 5033

	mtr_start(&mtr);
5034

5035 5036
	mtr_x_lock(dict_index_get_lock(index), &mtr);

5037 5038
	bool	ok = true;
	page_t*	root = btr_root_get(index, &mtr);
Sergei Golubchik's avatar
Sergei Golubchik committed
5039

5040 5041
	SRV_CORRUPT_TABLE_CHECK(root,
	{
Sergei Golubchik's avatar
Sergei Golubchik committed
5042 5043
		mtr_commit(&mtr);
		return(FALSE);
5044
	});
Sergei Golubchik's avatar
Sergei Golubchik committed
5045

5046
	ulint	n = btr_page_get_level(root, &mtr);
5047

5048
	for (ulint i = 0; i <= n; ++i) {
5049

5050 5051 5052
		if (!btr_validate_level(index, trx, n - i)) {
			ok = false;
			break;
5053 5054 5055 5056 5057
		}
	}

	mtr_commit(&mtr);

5058
	return(ok);
5059
}
5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108

/**************************************************************//**
Checks if the page in the cursor can be merged with given page.
If necessary, re-organize the merge_page.
@return	TRUE if possible to merge. */
UNIV_INTERN
ibool
btr_can_merge_with_page(
/*====================*/
	btr_cur_t*	cursor,		/*!< in: cursor on the page to merge */
	ulint		page_no,	/*!< in: a sibling page */
	buf_block_t**	merge_block,	/*!< out: the merge block */
	mtr_t*		mtr)		/*!< in: mini-transaction */
{
	dict_index_t*	index;
	page_t*		page;
	ulint		space;
	ulint		zip_size;
	ulint		n_recs;
	ulint		data_size;
        ulint           max_ins_size_reorg;
	ulint		max_ins_size;
	buf_block_t*	mblock;
	page_t*		mpage;
	DBUG_ENTER("btr_can_merge_with_page");

	if (page_no == FIL_NULL) {
		goto error;
	}

	index = btr_cur_get_index(cursor);
	page  = btr_cur_get_page(cursor);
	space = dict_index_get_space(index);
        zip_size = dict_table_zip_size(index->table);

	mblock = btr_block_get(space, zip_size, page_no, RW_X_LATCH, index,
			       mtr);
	mpage = buf_block_get_frame(mblock);

        n_recs = page_get_n_recs(page);
        data_size = page_get_data_size(page);

        max_ins_size_reorg = page_get_max_insert_size_after_reorganize(
                mpage, n_recs);

	if (data_size > max_ins_size_reorg) {
		goto error;
	}

5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119
	/* If compression padding tells us that merging will result in
	too packed up page i.e.: which is likely to cause compression
	failure then don't merge the pages. */
	if (zip_size && page_is_leaf(mpage)
	    && (page_get_data_size(mpage) + data_size
		>= dict_index_zip_pad_optimal_page_size(index))) {

		goto error;
	}


5120 5121 5122 5123 5124 5125
	max_ins_size = page_get_max_insert_size(mpage, n_recs);

	if (data_size > max_ins_size) {

		/* We have to reorganize mpage */

5126 5127
		if (!btr_page_reorganize_block(
			    false, page_zip_level, mblock, index, mtr)) {
5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153

			goto error;
		}

		max_ins_size = page_get_max_insert_size(mpage, n_recs);

		ut_ad(page_validate(mpage, index));
		ut_ad(max_ins_size == max_ins_size_reorg);

		if (data_size > max_ins_size) {

			/* Add fault tolerance, though this should
			never happen */

			goto error;
		}
	}

	*merge_block = mblock;
	DBUG_RETURN(TRUE);

error:
	*merge_block = NULL;
	DBUG_RETURN(FALSE);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
5154
#endif /* !UNIV_HOTBACKUP */