page0zip.cc 145 KB
Newer Older
1 2
/*****************************************************************************

Sergei Golubchik's avatar
Sergei Golubchik committed
3
Copyright (c) 2005, 2016, Oracle and/or its affiliates. All Rights Reserved.
4
Copyright (c) 2012, Facebook Inc.
5
Copyright (c) 2014, 2019, MariaDB Corporation.
6 7 8 9 10 11 12 13 14 15 16

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
this program; if not, write to the Free Software Foundation, Inc.,
Vicențiu Ciorbaru's avatar
Vicențiu Ciorbaru committed
17
51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA
18 19 20 21 22 23 24 25 26 27 28

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

/**************************************************//**
@file page/page0zip.cc
Compressed page interface

Created June 2005 by Marko Makela
*******************************************************/

#include "page0zip.h"
29
#include "fsp0types.h"
30 31
#include "page0page.h"
#include "buf0checksum.h"
32 33 34 35
#include "ut0crc32.h"
#include "zlib.h"

#ifndef UNIV_INNOCHECKSUM
36 37 38 39

/** A BLOB field reference full of zero, for use in assertions and tests.
Initially, BLOB field references are set to zero, in
dtuple_convert_big_rec(). */
40
const byte field_ref_zero[UNIV_PAGE_SIZE_MAX] = { 0, };
41

42 43 44 45
#include "mtr0log.h"
#include "dict0dict.h"
#include "btr0cur.h"
#include "log0recv.h"
46
#include "row0row.h"
47 48 49 50 51 52
#include "btr0sea.h"
#include "dict0boot.h"
#include "lock0lock.h"
#include "srv0srv.h"
#include "buf0lru.h"
#include "srv0mon.h"
53

54 55 56
#include <map>
#include <algorithm>

57
/** Statistics on compression, indexed by page_zip_des_t::ssize - 1 */
58
page_zip_stat_t		page_zip_stat[PAGE_ZIP_SSIZE_MAX];
59
/** Statistics on compression, indexed by index->id */
60
page_zip_stat_per_index_t	page_zip_stat_per_index;
61

62
/** Compression level to be used by zlib. Settable by user. */
Marko Mäkelä's avatar
Marko Mäkelä committed
63
uint	page_zip_level;
64

65
/** Whether or not to log compressed page images to avoid possible
66
compression algorithm changes in zlib. */
Marko Mäkelä's avatar
Marko Mäkelä committed
67
my_bool	page_zip_log_pages;
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

/* Please refer to ../include/page0zip.ic for a description of the
compressed page format. */

/* The infimum and supremum records are omitted from the compressed page.
On compress, we compare that the records are there, and on uncompress we
restore the records. */
/** Extra bytes of an infimum record */
static const byte infimum_extra[] = {
	0x01,			/* info_bits=0, n_owned=1 */
	0x00, 0x02		/* heap_no=0, status=2 */
	/* ?, ?	*/		/* next=(first user rec, or supremum) */
};
/** Data bytes of an infimum record */
static const byte infimum_data[] = {
	0x69, 0x6e, 0x66, 0x69,
	0x6d, 0x75, 0x6d, 0x00	/* "infimum\0" */
};
/** Extra bytes and data bytes of a supremum record */
static const byte supremum_extra_data[] = {
	/* 0x0?, */		/* info_bits=0, n_owned=1..8 */
	0x00, 0x0b,		/* heap_no=1, status=3 */
	0x00, 0x00,		/* next=0 */
	0x73, 0x75, 0x70, 0x72,
	0x65, 0x6d, 0x75, 0x6d	/* "supremum" */
};

/** Assert that a block of memory is filled with zero bytes.
Compare at most sizeof(field_ref_zero) bytes.
97 98 99 100
@param b in: memory block
@param s in: size of the memory block, in bytes */
#define ASSERT_ZERO(b, s)			\
	ut_ad(!memcmp(b, field_ref_zero,	\
101
		      std::min<size_t>(s, sizeof field_ref_zero)));
102
/** Assert that a BLOB pointer is filled with zero bytes.
103
@param b in: BLOB pointer */
104
#define ASSERT_ZERO_BLOB(b) \
105
	ut_ad(!memcmp(b, field_ref_zero, FIELD_REF_SIZE))
106 107 108 109 110

/* Enable some extra debugging output.  This code can be enabled
independently of any UNIV_ debugging conditions. */
#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
# include <stdarg.h>
Sergei Golubchik's avatar
Sergei Golubchik committed
111
MY_ATTRIBUTE((format (printf, 1, 2)))
112 113
/**********************************************************************//**
Report a failure to decompress or compress.
114
@return number of characters printed */
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
static
int
page_zip_fail_func(
/*===============*/
	const char*	fmt,	/*!< in: printf(3) format string */
	...)			/*!< in: arguments corresponding to fmt */
{
	int	res;
	va_list	ap;

	ut_print_timestamp(stderr);
	fputs("  InnoDB: ", stderr);
	va_start(ap, fmt);
	res = vfprintf(stderr, fmt, ap);
	va_end(ap);

	return(res);
}
/** Wrapper for page_zip_fail_func()
134
@param fmt_args in: printf(3) format string and arguments */
135 136 137
# define page_zip_fail(fmt_args) page_zip_fail_func fmt_args
#else /* UNIV_DEBUG || UNIV_ZIP_DEBUG */
/** Dummy wrapper for page_zip_fail_func()
138
@param fmt_args ignored: printf(3) format string and arguments */
139 140 141 142 143
# define page_zip_fail(fmt_args) /* empty */
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */

/**********************************************************************//**
Determine the guaranteed free space on an empty page.
144
@return minimum payload size on the page */
145 146 147 148 149 150
ulint
page_zip_empty_size(
/*================*/
	ulint	n_fields,	/*!< in: number of columns in the index */
	ulint	zip_size)	/*!< in: compressed page size in bytes */
{
151
	ulint	size = zip_size
152 153 154
		/* subtract the page header and the longest
		uncompressed data needed for one record */
		- (PAGE_DATA
155
		   + PAGE_ZIP_CLUST_LEAF_SLOT_SIZE
156 157 158 159
		   + 1/* encoded heap_no==2 in page_zip_write_rec() */
		   + 1/* end of modification log */
		   - REC_N_NEW_EXTRA_BYTES/* omitted bytes */)
		/* subtract the space for page_zip_fields_encode() */
Sergei Golubchik's avatar
Sergei Golubchik committed
160
		- compressBound(static_cast<uLong>(2 * (n_fields + 1)));
161
	return(lint(size) > 0 ? size : 0);
162
}
163 164 165 166 167 168 169 170 171 172

/** Check whether a tuple is too big for compressed table
@param[in]	index	dict index object
@param[in]	entry	entry for the index
@return	true if it's too big, otherwise false */
bool
page_zip_is_too_big(
	const dict_index_t*	index,
	const dtuple_t*		entry)
{
173
	const ulint zip_size = index->table->space->zip_size();
174 175 176 177 178

	/* Estimate the free space of an empty compressed page.
	Subtract one byte for the encoded heap_no in the
	modification log. */
	ulint	free_space_zip = page_zip_empty_size(
179
		index->n_fields, zip_size);
180 181 182
	ulint	n_uniq = dict_index_get_n_unique_in_tree(index);

	ut_ad(dict_table_is_comp(index->table));
183
	ut_ad(zip_size);
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

	if (free_space_zip == 0) {
		return(true);
	}

	/* Subtract one byte for the encoded heap_no in the
	modification log. */
	free_space_zip--;

	/* There should be enough room for two node pointer
	records on an empty non-leaf page.  This prevents
	infinite page splits. */

	if (entry->n_fields >= n_uniq
	    && (REC_NODE_PTR_SIZE
		+ rec_get_converted_size_comp_prefix(
			index, entry->fields, n_uniq, NULL)
		/* On a compressed page, there is
		a two-byte entry in the dense
		page directory for every record.
		But there is no record header. */
		- (REC_N_NEW_EXTRA_BYTES - 2)
		> free_space_zip / 2)) {
		return(true);
	}

	return(false);
}
212 213 214 215

/*************************************************************//**
Gets the number of elements in the dense page directory,
including deleted records (the free list).
216
@return number of elements in the dense page directory */
217 218 219 220 221 222 223
UNIV_INLINE
ulint
page_zip_dir_elems(
/*===============*/
	const page_zip_des_t*	page_zip)	/*!< in: compressed page */
{
	/* Exclude the page infimum and supremum from the record count. */
224 225
	return ulint(page_dir_get_n_heap(page_zip->data))
		- PAGE_HEAP_NO_USER_LOW;
226 227 228 229 230
}

/*************************************************************//**
Gets the size of the compressed page trailer (the dense page directory),
including deleted records (the free list).
231
@return length of dense page directory, in bytes */
232 233 234 235 236 237 238 239 240 241 242 243
UNIV_INLINE
ulint
page_zip_dir_size(
/*==============*/
	const page_zip_des_t*	page_zip)	/*!< in: compressed page */
{
	return(PAGE_ZIP_DIR_SLOT_SIZE * page_zip_dir_elems(page_zip));
}

/*************************************************************//**
Gets an offset to the compressed page trailer (the dense page directory),
including deleted records (the free list).
244
@return offset of the dense page directory */
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
UNIV_INLINE
ulint
page_zip_dir_start_offs(
/*====================*/
	const page_zip_des_t*	page_zip,	/*!< in: compressed page */
	ulint			n_dense)	/*!< in: directory size */
{
	ut_ad(n_dense * PAGE_ZIP_DIR_SLOT_SIZE < page_zip_get_size(page_zip));

	return(page_zip_get_size(page_zip) - n_dense * PAGE_ZIP_DIR_SLOT_SIZE);
}

/*************************************************************//**
Gets a pointer to the compressed page trailer (the dense page directory),
including deleted records (the free list).
260 261 262
@param[in] page_zip compressed page
@param[in] n_dense number of entries in the directory
@return pointer to the dense page directory */
263 264 265 266 267
#define page_zip_dir_start_low(page_zip, n_dense)			\
	((page_zip)->data + page_zip_dir_start_offs(page_zip, n_dense))
/*************************************************************//**
Gets a pointer to the compressed page trailer (the dense page directory),
including deleted records (the free list).
268 269
@param[in] page_zip compressed page
@return pointer to the dense page directory */
270 271 272 273 274 275
#define page_zip_dir_start(page_zip)					\
	page_zip_dir_start_low(page_zip, page_zip_dir_elems(page_zip))

/*************************************************************//**
Gets the size of the compressed page trailer (the dense page directory),
only including user records (excluding the free list).
276
@return length of dense page directory comprising existing records, in bytes */
277 278 279 280 281 282 283
UNIV_INLINE
ulint
page_zip_dir_user_size(
/*===================*/
	const page_zip_des_t*	page_zip)	/*!< in: compressed page */
{
	ulint	size = PAGE_ZIP_DIR_SLOT_SIZE
284
		* ulint(page_get_n_recs(page_zip->data));
285 286 287 288 289 290
	ut_ad(size <= page_zip_dir_size(page_zip));
	return(size);
}

/*************************************************************//**
Find the slot of the given record in the dense page directory.
291
@return dense directory slot, or NULL if record not found */
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
UNIV_INLINE
byte*
page_zip_dir_find_low(
/*==================*/
	byte*	slot,			/*!< in: start of records */
	byte*	end,			/*!< in: end of records */
	ulint	offset)			/*!< in: offset of user record */
{
	ut_ad(slot <= end);

	for (; slot < end; slot += PAGE_ZIP_DIR_SLOT_SIZE) {
		if ((mach_read_from_2(slot) & PAGE_ZIP_DIR_SLOT_MASK)
		    == offset) {
			return(slot);
		}
	}

	return(NULL);
}

/*************************************************************//**
Find the slot of the given non-free record in the dense page directory.
314
@return dense directory slot, or NULL if record not found */
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
UNIV_INLINE
byte*
page_zip_dir_find(
/*==============*/
	page_zip_des_t*	page_zip,		/*!< in: compressed page */
	ulint		offset)			/*!< in: offset of user record */
{
	byte*	end	= page_zip->data + page_zip_get_size(page_zip);

	ut_ad(page_zip_simple_validate(page_zip));

	return(page_zip_dir_find_low(end - page_zip_dir_user_size(page_zip),
				     end,
				     offset));
}

/*************************************************************//**
Find the slot of the given free record in the dense page directory.
333
@return dense directory slot, or NULL if record not found */
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
UNIV_INLINE
byte*
page_zip_dir_find_free(
/*===================*/
	page_zip_des_t*	page_zip,		/*!< in: compressed page */
	ulint		offset)			/*!< in: offset of user record */
{
	byte*	end	= page_zip->data + page_zip_get_size(page_zip);

	ut_ad(page_zip_simple_validate(page_zip));

	return(page_zip_dir_find_low(end - page_zip_dir_size(page_zip),
				     end - page_zip_dir_user_size(page_zip),
				     offset));
}

/*************************************************************//**
Read a given slot in the dense page directory.
@return record offset on the uncompressed page, possibly ORed with
PAGE_ZIP_DIR_SLOT_DEL or PAGE_ZIP_DIR_SLOT_OWNED */
UNIV_INLINE
ulint
page_zip_dir_get(
/*=============*/
	const page_zip_des_t*	page_zip,	/*!< in: compressed page */
	ulint			slot)		/*!< in: slot
						(0=first user record) */
{
	ut_ad(page_zip_simple_validate(page_zip));
	ut_ad(slot < page_zip_dir_size(page_zip) / PAGE_ZIP_DIR_SLOT_SIZE);
	return(mach_read_from_2(page_zip->data + page_zip_get_size(page_zip)
				- PAGE_ZIP_DIR_SLOT_SIZE * (slot + 1)));
}

/**********************************************************************//**
Write a log record of compressing an index page. */
static
void
page_zip_compress_write_log(
/*========================*/
	const page_zip_des_t*	page_zip,/*!< in: compressed page */
	const page_t*		page,	/*!< in: uncompressed page */
	dict_index_t*		index,	/*!< in: index of the B-tree node */
	mtr_t*			mtr)	/*!< in: mini-transaction */
{
	byte*	log_ptr;
	ulint	trailer_size;

	ut_ad(!dict_index_is_ibuf(index));

	log_ptr = mlog_open(mtr, 11 + 2 + 2);

	if (!log_ptr) {

		return;
	}

	/* Read the number of user records. */
392
	trailer_size = ulint(page_dir_get_n_heap(page_zip->data))
393 394 395 396 397 398 399 400 401 402 403 404 405
		- PAGE_HEAP_NO_USER_LOW;
	/* Multiply by uncompressed of size stored per record */
	if (!page_is_leaf(page)) {
		trailer_size *= PAGE_ZIP_DIR_SLOT_SIZE + REC_NODE_PTR_SIZE;
	} else if (dict_index_is_clust(index)) {
		trailer_size *= PAGE_ZIP_DIR_SLOT_SIZE
			+ DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;
	} else {
		trailer_size *= PAGE_ZIP_DIR_SLOT_SIZE;
	}
	/* Add the space occupied by BLOB pointers. */
	trailer_size += page_zip->n_blobs * BTR_EXTERN_FIELD_REF_SIZE;
	ut_a(page_zip->m_end > PAGE_DATA);
406
	compile_time_assert(FIL_PAGE_DATA <= PAGE_DATA);
407 408 409 410 411
	ut_a(page_zip->m_end + trailer_size <= page_zip_get_size(page_zip));

	log_ptr = mlog_write_initial_log_record_fast((page_t*) page,
						     MLOG_ZIP_PAGE_COMPRESS,
						     log_ptr, mtr);
412
	mach_write_to_2(log_ptr, ulint(page_zip->m_end - FIL_PAGE_TYPE));
413 414 415 416 417 418 419 420 421 422 423
	log_ptr += 2;
	mach_write_to_2(log_ptr, trailer_size);
	log_ptr += 2;
	mlog_close(mtr, log_ptr);

	/* Write FIL_PAGE_PREV and FIL_PAGE_NEXT */
	mlog_catenate_string(mtr, page_zip->data + FIL_PAGE_PREV, 4);
	mlog_catenate_string(mtr, page_zip->data + FIL_PAGE_NEXT, 4);
	/* Write most of the page header, the compressed stream and
	the modification log. */
	mlog_catenate_string(mtr, page_zip->data + FIL_PAGE_TYPE,
424
			     ulint(page_zip->m_end - FIL_PAGE_TYPE));
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 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
	/* Write the uncompressed trailer of the compressed page. */
	mlog_catenate_string(mtr, page_zip->data + page_zip_get_size(page_zip)
			     - trailer_size, trailer_size);
}

/******************************************************//**
Determine how many externally stored columns are contained
in existing records with smaller heap_no than rec. */
static
ulint
page_zip_get_n_prev_extern(
/*=======================*/
	const page_zip_des_t*	page_zip,/*!< in: dense page directory on
					compressed page */
	const rec_t*		rec,	/*!< in: compact physical record
					on a B-tree leaf page */
	const dict_index_t*	index)	/*!< in: record descriptor */
{
	const page_t*	page	= page_align(rec);
	ulint		n_ext	= 0;
	ulint		i;
	ulint		left;
	ulint		heap_no;
	ulint		n_recs	= page_get_n_recs(page_zip->data);

	ut_ad(page_is_leaf(page));
	ut_ad(page_is_comp(page));
	ut_ad(dict_table_is_comp(index->table));
	ut_ad(dict_index_is_clust(index));
	ut_ad(!dict_index_is_ibuf(index));

	heap_no = rec_get_heap_no_new(rec);
	ut_ad(heap_no >= PAGE_HEAP_NO_USER_LOW);
	left = heap_no - PAGE_HEAP_NO_USER_LOW;
	if (UNIV_UNLIKELY(!left)) {
		return(0);
	}

	for (i = 0; i < n_recs; i++) {
		const rec_t*	r	= page + (page_zip_dir_get(page_zip, i)
						  & PAGE_ZIP_DIR_SLOT_MASK);

		if (rec_get_heap_no_new(r) < heap_no) {
			n_ext += rec_get_n_extern_new(r, index,
						      ULINT_UNDEFINED);
			if (!--left) {
				break;
			}
		}
	}

	return(n_ext);
}

/**********************************************************************//**
Encode the length of a fixed-length column.
481
@return buf + length of encoded val */
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
static
byte*
page_zip_fixed_field_encode(
/*========================*/
	byte*	buf,	/*!< in: pointer to buffer where to write */
	ulint	val)	/*!< in: value to write */
{
	ut_ad(val >= 2);

	if (UNIV_LIKELY(val < 126)) {
		/*
		0 = nullable variable field of at most 255 bytes length;
		1 = not null variable field of at most 255 bytes length;
		126 = nullable variable field with maximum length >255;
		127 = not null variable field with maximum length >255
		*/
		*buf++ = (byte) val;
	} else {
		*buf++ = (byte) (0x80 | val >> 8);
		*buf++ = (byte) val;
	}

	return(buf);
}

/**********************************************************************//**
Write the index information for the compressed page.
509
@return used size of buf */
510 511 512
ulint
page_zip_fields_encode(
/*===================*/
513 514 515 516 517 518 519 520 521
	ulint			n,	/*!< in: number of fields
					to compress */
	const dict_index_t*	index,	/*!< in: index comprising
					at least n fields */
	ulint			trx_id_pos,
					/*!< in: position of the trx_id column
					in the index, or ULINT_UNDEFINED if
					this is a non-leaf page */
	byte*			buf)	/*!< out: buffer of (n + 1) * 2 bytes */
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
{
	const byte*	buf_start	= buf;
	ulint		i;
	ulint		col;
	ulint		trx_id_col	= 0;
	/* sum of lengths of preceding non-nullable fixed fields, or 0 */
	ulint		fixed_sum	= 0;

	ut_ad(trx_id_pos == ULINT_UNDEFINED || trx_id_pos < n);

	for (i = col = 0; i < n; i++) {
		dict_field_t*	field = dict_index_get_nth_field(index, i);
		ulint		val;

		if (dict_field_get_col(field)->prtype & DATA_NOT_NULL) {
			val = 1; /* set the "not nullable" flag */
		} else {
			val = 0; /* nullable field */
		}

		if (!field->fixed_len) {
			/* variable-length field */
			const dict_col_t*	column
				= dict_field_get_col(field);

547
			if (DATA_BIG_COL(column)) {
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
				val |= 0x7e; /* max > 255 bytes */
			}

			if (fixed_sum) {
				/* write out the length of any
				preceding non-nullable fields */
				buf = page_zip_fixed_field_encode(
					buf, fixed_sum << 1 | 1);
				fixed_sum = 0;
				col++;
			}

			*buf++ = (byte) val;
			col++;
		} else if (val) {
			/* fixed-length non-nullable field */

			if (fixed_sum && UNIV_UNLIKELY
			    (fixed_sum + field->fixed_len
			     > DICT_MAX_FIXED_COL_LEN)) {
				/* Write out the length of the
				preceding non-nullable fields,
				to avoid exceeding the maximum
				length of a fixed-length column. */
				buf = page_zip_fixed_field_encode(
					buf, fixed_sum << 1 | 1);
				fixed_sum = 0;
				col++;
			}

			if (i && UNIV_UNLIKELY(i == trx_id_pos)) {
				if (fixed_sum) {
					/* Write out the length of any
					preceding non-nullable fields,
					and start a new trx_id column. */
					buf = page_zip_fixed_field_encode(
						buf, fixed_sum << 1 | 1);
					col++;
				}

				trx_id_col = col;
				fixed_sum = field->fixed_len;
			} else {
				/* add to the sum */
				fixed_sum += field->fixed_len;
			}
		} else {
			/* fixed-length nullable field */

			if (fixed_sum) {
				/* write out the length of any
				preceding non-nullable fields */
				buf = page_zip_fixed_field_encode(
					buf, fixed_sum << 1 | 1);
				fixed_sum = 0;
				col++;
			}

			buf = page_zip_fixed_field_encode(
607
				buf, ulint(field->fixed_len) << 1);
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 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
			col++;
		}
	}

	if (fixed_sum) {
		/* Write out the lengths of last fixed-length columns. */
		buf = page_zip_fixed_field_encode(buf, fixed_sum << 1 | 1);
	}

	if (trx_id_pos != ULINT_UNDEFINED) {
		/* Write out the position of the trx_id column */
		i = trx_id_col;
	} else {
		/* Write out the number of nullable fields */
		i = index->n_nullable;
	}

	if (i < 128) {
		*buf++ = (byte) i;
	} else {
		*buf++ = (byte) (0x80 | i >> 8);
		*buf++ = (byte) i;
	}

	ut_ad((ulint) (buf - buf_start) <= (n + 2) * 2);
	return((ulint) (buf - buf_start));
}

/**********************************************************************//**
Populate the dense page directory from the sparse directory. */
static
void
page_zip_dir_encode(
/*================*/
	const page_t*	page,	/*!< in: compact page */
	byte*		buf,	/*!< in: pointer to dense page directory[-1];
				out: dense directory on compressed page */
	const rec_t**	recs)	/*!< in: pointer to an array of 0, or NULL;
				out: dense page directory sorted by ascending
				address (and heap_no) */
{
	const byte*	rec;
	ulint		status;
	ulint		min_mark;
	ulint		heap_no;
	ulint		i;
	ulint		n_heap;
	ulint		offs;

	min_mark = 0;

	if (page_is_leaf(page)) {
		status = REC_STATUS_ORDINARY;
	} else {
		status = REC_STATUS_NODE_PTR;
663
		if (UNIV_UNLIKELY(!page_has_prev(page))) {
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
			min_mark = REC_INFO_MIN_REC_FLAG;
		}
	}

	n_heap = page_dir_get_n_heap(page);

	/* Traverse the list of stored records in the collation order,
	starting from the first user record. */

	rec = page + PAGE_NEW_INFIMUM;

	i = 0;

	for (;;) {
		ulint	info_bits;
		offs = rec_get_next_offs(rec, TRUE);
		if (UNIV_UNLIKELY(offs == PAGE_NEW_SUPREMUM)) {
			break;
		}
		rec = page + offs;
		heap_no = rec_get_heap_no_new(rec);
		ut_a(heap_no >= PAGE_HEAP_NO_USER_LOW);
		ut_a(heap_no < n_heap);
687
		ut_a(offs < srv_page_size - PAGE_DIR);
688
		ut_a(offs >= PAGE_ZIP_START);
689 690 691 692 693
		compile_time_assert(!(PAGE_ZIP_DIR_SLOT_MASK
				      & (PAGE_ZIP_DIR_SLOT_MASK + 1)));
		compile_time_assert(PAGE_ZIP_DIR_SLOT_MASK
				    >= UNIV_ZIP_SIZE_MAX - 1);

694
		if (UNIV_UNLIKELY(rec_get_n_owned_new(rec) != 0)) {
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
			offs |= PAGE_ZIP_DIR_SLOT_OWNED;
		}

		info_bits = rec_get_info_bits(rec, TRUE);
		if (info_bits & REC_INFO_DELETED_FLAG) {
			info_bits &= ~REC_INFO_DELETED_FLAG;
			offs |= PAGE_ZIP_DIR_SLOT_DEL;
		}
		ut_a(info_bits == min_mark);
		/* Only the smallest user record can have
		REC_INFO_MIN_REC_FLAG set. */
		min_mark = 0;

		mach_write_to_2(buf - PAGE_ZIP_DIR_SLOT_SIZE * ++i, offs);

		if (UNIV_LIKELY_NULL(recs)) {
			/* Ensure that each heap_no occurs at most once. */
			ut_a(!recs[heap_no - PAGE_HEAP_NO_USER_LOW]);
			/* exclude infimum and supremum */
			recs[heap_no - PAGE_HEAP_NO_USER_LOW] = rec;
		}

717
		ut_a(ulint(rec_get_status(rec)) == status);
718 719 720 721 722 723 724 725 726 727 728 729 730 731
	}

	offs = page_header_get_field(page, PAGE_FREE);

	/* Traverse the free list (of deleted records). */
	while (offs) {
		ut_ad(!(offs & ~PAGE_ZIP_DIR_SLOT_MASK));
		rec = page + offs;

		heap_no = rec_get_heap_no_new(rec);
		ut_a(heap_no >= PAGE_HEAP_NO_USER_LOW);
		ut_a(heap_no < n_heap);

		ut_a(!rec[-REC_N_NEW_EXTRA_BYTES]); /* info_bits and n_owned */
732
		ut_a(ulint(rec_get_status(rec)) == status);
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770

		mach_write_to_2(buf - PAGE_ZIP_DIR_SLOT_SIZE * ++i, offs);

		if (UNIV_LIKELY_NULL(recs)) {
			/* Ensure that each heap_no occurs at most once. */
			ut_a(!recs[heap_no - PAGE_HEAP_NO_USER_LOW]);
			/* exclude infimum and supremum */
			recs[heap_no - PAGE_HEAP_NO_USER_LOW] = rec;
		}

		offs = rec_get_next_offs(rec, TRUE);
	}

	/* Ensure that each heap no occurs at least once. */
	ut_a(i + PAGE_HEAP_NO_USER_LOW == n_heap);
}

extern "C" {

/**********************************************************************//**
Allocate memory for zlib. */
static
void*
page_zip_zalloc(
/*============*/
	void*	opaque,	/*!< in/out: memory heap */
	uInt	items,	/*!< in: number of items to allocate */
	uInt	size)	/*!< in: size of an item in bytes */
{
	return(mem_heap_zalloc(static_cast<mem_heap_t*>(opaque), items * size));
}

/**********************************************************************//**
Deallocate memory for zlib. */
static
void
page_zip_free(
/*==========*/
Sergei Golubchik's avatar
Sergei Golubchik committed
771 772
	void*	opaque MY_ATTRIBUTE((unused)),	/*!< in: memory heap */
	void*	address MY_ATTRIBUTE((unused)))/*!< in: object to free */
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
{
}

} /* extern "C" */

/**********************************************************************//**
Configure the zlib allocator to use the given memory heap. */
void
page_zip_set_alloc(
/*===============*/
	void*		stream,		/*!< in/out: zlib stream */
	mem_heap_t*	heap)		/*!< in: memory heap to use */
{
	z_stream*	strm = static_cast<z_stream*>(stream);

	strm->zalloc = page_zip_zalloc;
	strm->zfree = page_zip_free;
	strm->opaque = heap;
}

#if 0 || defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
/** Symbol for enabling compression and decompression diagnostics */
# define PAGE_ZIP_COMPRESS_DBG
#endif

#ifdef PAGE_ZIP_COMPRESS_DBG
/** Set this variable in a debugger to enable
excessive logging in page_zip_compress(). */
801
static bool	page_zip_compress_dbg;
802 803 804 805
/** Set this variable in a debugger to enable
binary logging of the data passed to deflate().
When this variable is nonzero, it will act
as a log file name generator. */
806
static unsigned	page_zip_compress_log;
807 808 809

/**********************************************************************//**
Wrapper for deflate().  Log the operation if page_zip_compress_dbg is set.
810
@return deflate() status: Z_OK, Z_BUF_ERROR, ... */
811 812 813 814 815 816 817 818 819 820 821 822 823
static
int
page_zip_compress_deflate(
/*======================*/
	FILE*		logfile,/*!< in: log file, or NULL */
	z_streamp	strm,	/*!< in/out: compressed stream for deflate() */
	int		flush)	/*!< in: deflate() flushing method */
{
	int	status;
	if (UNIV_UNLIKELY(page_zip_compress_dbg)) {
		ut_print_buf(stderr, strm->next_in, strm->avail_in);
	}
	if (UNIV_LIKELY_NULL(logfile)) {
824 825 826 827
		if (fwrite(strm->next_in, 1, strm->avail_in, logfile)
		    != strm->avail_in) {
			perror("fwrite");
		}
828 829 830 831 832 833 834 835 836 837 838 839
	}
	status = deflate(strm, flush);
	if (UNIV_UNLIKELY(page_zip_compress_dbg)) {
		fprintf(stderr, " -> %d\n", status);
	}
	return(status);
}

/* Redefine deflate(). */
# undef deflate
/** Debug wrapper for the zlib compression routine deflate().
Log the operation if page_zip_compress_dbg is set.
840 841 842
@param strm in/out: compressed stream
@param flush in: flushing method
@return deflate() status: Z_OK, Z_BUF_ERROR, ... */
843 844 845 846 847 848 849 850 851 852 853 854 855 856
# define deflate(strm, flush) page_zip_compress_deflate(logfile, strm, flush)
/** Declaration of the logfile parameter */
# define FILE_LOGFILE FILE* logfile,
/** The logfile parameter */
# define LOGFILE logfile,
#else /* PAGE_ZIP_COMPRESS_DBG */
/** Empty declaration of the logfile parameter */
# define FILE_LOGFILE
/** Missing logfile parameter */
# define LOGFILE
#endif /* PAGE_ZIP_COMPRESS_DBG */

/**********************************************************************//**
Compress the records of a node pointer page.
857
@return Z_OK, or a zlib error code */
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
static
int
page_zip_compress_node_ptrs(
/*========================*/
	FILE_LOGFILE
	z_stream*	c_stream,	/*!< in/out: compressed page stream */
	const rec_t**	recs,		/*!< in: dense page directory
					sorted by address */
	ulint		n_dense,	/*!< in: size of recs[] */
	dict_index_t*	index,		/*!< in: the index of the page */
	byte*		storage,	/*!< in: end of dense page directory */
	mem_heap_t*	heap)		/*!< in: temporary memory heap */
{
	int	err	= Z_OK;
	ulint*	offsets = NULL;

	do {
		const rec_t*	rec = *recs++;

877
		offsets = rec_get_offsets(rec, index, offsets, false,
878 879 880 881 882 883 884 885 886
					  ULINT_UNDEFINED, &heap);
		/* Only leaf nodes may contain externally stored columns. */
		ut_ad(!rec_offs_any_extern(offsets));

		UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
		UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
				   rec_offs_extra_size(offsets));

		/* Compress the extra bytes. */
Sergei Golubchik's avatar
Sergei Golubchik committed
887 888
		c_stream->avail_in = static_cast<uInt>(
			rec - REC_N_NEW_EXTRA_BYTES - c_stream->next_in);
889 890 891 892 893 894 895 896 897 898 899

		if (c_stream->avail_in) {
			err = deflate(c_stream, Z_NO_FLUSH);
			if (UNIV_UNLIKELY(err != Z_OK)) {
				break;
			}
		}
		ut_ad(!c_stream->avail_in);

		/* Compress the data bytes, except node_ptr. */
		c_stream->next_in = (byte*) rec;
Sergei Golubchik's avatar
Sergei Golubchik committed
900 901
		c_stream->avail_in = static_cast<uInt>(
			rec_offs_data_size(offsets) - REC_NODE_PTR_SIZE);
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922

		if (c_stream->avail_in) {
			err = deflate(c_stream, Z_NO_FLUSH);
			if (UNIV_UNLIKELY(err != Z_OK)) {
				break;
			}
		}

		ut_ad(!c_stream->avail_in);

		memcpy(storage - REC_NODE_PTR_SIZE
		       * (rec_get_heap_no_new(rec) - 1),
		       c_stream->next_in, REC_NODE_PTR_SIZE);
		c_stream->next_in += REC_NODE_PTR_SIZE;
	} while (--n_dense);

	return(err);
}

/**********************************************************************//**
Compress the records of a leaf node of a secondary index.
923
@return Z_OK, or a zlib error code */
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
static
int
page_zip_compress_sec(
/*==================*/
	FILE_LOGFILE
	z_stream*	c_stream,	/*!< in/out: compressed page stream */
	const rec_t**	recs,		/*!< in: dense page directory
					sorted by address */
	ulint		n_dense)	/*!< in: size of recs[] */
{
	int		err	= Z_OK;

	ut_ad(n_dense > 0);

	do {
		const rec_t*	rec = *recs++;

		/* Compress everything up to this record. */
Sergei Golubchik's avatar
Sergei Golubchik committed
942 943 944
		c_stream->avail_in = static_cast<uInt>(
			rec - REC_N_NEW_EXTRA_BYTES
			- c_stream->next_in);
945

946
		if (UNIV_LIKELY(c_stream->avail_in != 0)) {
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
			UNIV_MEM_ASSERT_RW(c_stream->next_in,
					   c_stream->avail_in);
			err = deflate(c_stream, Z_NO_FLUSH);
			if (UNIV_UNLIKELY(err != Z_OK)) {
				break;
			}
		}

		ut_ad(!c_stream->avail_in);
		ut_ad(c_stream->next_in == rec - REC_N_NEW_EXTRA_BYTES);

		/* Skip the REC_N_NEW_EXTRA_BYTES. */

		c_stream->next_in = (byte*) rec;
	} while (--n_dense);

	return(err);
}

/**********************************************************************//**
Compress a record of a leaf node of a clustered index that contains
externally stored columns.
969
@return Z_OK, or a zlib error code */
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
static
int
page_zip_compress_clust_ext(
/*========================*/
	FILE_LOGFILE
	z_stream*	c_stream,	/*!< in/out: compressed page stream */
	const rec_t*	rec,		/*!< in: record */
	const ulint*	offsets,	/*!< in: rec_get_offsets(rec) */
	ulint		trx_id_col,	/*!< in: position of of DB_TRX_ID */
	byte*		deleted,	/*!< in: dense directory entry pointing
					to the head of the free list */
	byte*		storage,	/*!< in: end of dense page directory */
	byte**		externs,	/*!< in/out: pointer to the next
					available BLOB pointer */
	ulint*		n_blobs)	/*!< in/out: number of
					externally stored columns */
{
	int	err;
	ulint	i;

	UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
	UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
			   rec_offs_extra_size(offsets));

	for (i = 0; i < rec_offs_n_fields(offsets); i++) {
		ulint		len;
		const byte*	src;

		if (UNIV_UNLIKELY(i == trx_id_col)) {
			ut_ad(!rec_offs_nth_extern(offsets, i));
			/* Store trx_id and roll_ptr
			in uncompressed form. */
			src = rec_get_nth_field(rec, offsets, i, &len);
			ut_ad(src + DATA_TRX_ID_LEN
			      == rec_get_nth_field(rec, offsets,
						   i + 1, &len));
			ut_ad(len == DATA_ROLL_PTR_LEN);

			/* Compress any preceding bytes. */
Sergei Golubchik's avatar
Sergei Golubchik committed
1009 1010
			c_stream->avail_in = static_cast<uInt>(
				src - c_stream->next_in);
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

			if (c_stream->avail_in) {
				err = deflate(c_stream, Z_NO_FLUSH);
				if (UNIV_UNLIKELY(err != Z_OK)) {

					return(err);
				}
			}

			ut_ad(!c_stream->avail_in);
			ut_ad(c_stream->next_in == src);

			memcpy(storage
			       - (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
			       * (rec_get_heap_no_new(rec) - 1),
			       c_stream->next_in,
			       DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

			c_stream->next_in
				+= DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;

			/* Skip also roll_ptr */
			i++;
		} else if (rec_offs_nth_extern(offsets, i)) {
			src = rec_get_nth_field(rec, offsets, i, &len);
			ut_ad(len >= BTR_EXTERN_FIELD_REF_SIZE);
			src += len - BTR_EXTERN_FIELD_REF_SIZE;

Sergei Golubchik's avatar
Sergei Golubchik committed
1039 1040
			c_stream->avail_in = static_cast<uInt>(
				src - c_stream->next_in);
1041
			if (UNIV_LIKELY(c_stream->avail_in != 0)) {
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
				err = deflate(c_stream, Z_NO_FLUSH);
				if (UNIV_UNLIKELY(err != Z_OK)) {

					return(err);
				}
			}

			ut_ad(!c_stream->avail_in);
			ut_ad(c_stream->next_in == src);

			/* Reserve space for the data at
			the end of the space reserved for
			the compressed data and the page
			modification log. */

			if (UNIV_UNLIKELY
			    (c_stream->avail_out
			     <= BTR_EXTERN_FIELD_REF_SIZE)) {
				/* out of space */
				return(Z_BUF_ERROR);
			}

			ut_ad(*externs == c_stream->next_out
			      + c_stream->avail_out
			      + 1/* end of modif. log */);

			c_stream->next_in
				+= BTR_EXTERN_FIELD_REF_SIZE;

			/* Skip deleted records. */
			if (UNIV_LIKELY_NULL
			    (page_zip_dir_find_low(
				    storage, deleted,
				    page_offset(rec)))) {
				continue;
			}

			(*n_blobs)++;
			c_stream->avail_out
				-= BTR_EXTERN_FIELD_REF_SIZE;
			*externs -= BTR_EXTERN_FIELD_REF_SIZE;

			/* Copy the BLOB pointer */
			memcpy(*externs, c_stream->next_in
			       - BTR_EXTERN_FIELD_REF_SIZE,
			       BTR_EXTERN_FIELD_REF_SIZE);
		}
	}

	return(Z_OK);
}

/**********************************************************************//**
Compress the records of a leaf node of a clustered index.
1096
@return Z_OK, or a zlib error code */
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
static
int
page_zip_compress_clust(
/*====================*/
	FILE_LOGFILE
	z_stream*	c_stream,	/*!< in/out: compressed page stream */
	const rec_t**	recs,		/*!< in: dense page directory
					sorted by address */
	ulint		n_dense,	/*!< in: size of recs[] */
	dict_index_t*	index,		/*!< in: the index of the page */
	ulint*		n_blobs,	/*!< in: 0; out: number of
					externally stored columns */
	ulint		trx_id_col,	/*!< index of the trx_id column */
	byte*		deleted,	/*!< in: dense directory entry pointing
					to the head of the free list */
	byte*		storage,	/*!< in: end of dense page directory */
	mem_heap_t*	heap)		/*!< in: temporary memory heap */
{
	int	err		= Z_OK;
	ulint*	offsets		= NULL;
	/* BTR_EXTERN_FIELD_REF storage */
	byte*	externs		= storage - n_dense
		* (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

	ut_ad(*n_blobs == 0);

	do {
		const rec_t*	rec = *recs++;

1126
		offsets = rec_get_offsets(rec, index, offsets, true,
1127 1128 1129 1130 1131 1132 1133 1134
					  ULINT_UNDEFINED, &heap);
		ut_ad(rec_offs_n_fields(offsets)
		      == dict_index_get_n_fields(index));
		UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
		UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
				   rec_offs_extra_size(offsets));

		/* Compress the extra bytes. */
Sergei Golubchik's avatar
Sergei Golubchik committed
1135 1136 1137
		c_stream->avail_in = static_cast<uInt>(
			rec - REC_N_NEW_EXTRA_BYTES
			- c_stream->next_in);
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183

		if (c_stream->avail_in) {
			err = deflate(c_stream, Z_NO_FLUSH);
			if (UNIV_UNLIKELY(err != Z_OK)) {

				goto func_exit;
			}
		}
		ut_ad(!c_stream->avail_in);
		ut_ad(c_stream->next_in == rec - REC_N_NEW_EXTRA_BYTES);

		/* Compress the data bytes. */

		c_stream->next_in = (byte*) rec;

		/* Check if there are any externally stored columns.
		For each externally stored column, store the
		BTR_EXTERN_FIELD_REF separately. */
		if (rec_offs_any_extern(offsets)) {
			ut_ad(dict_index_is_clust(index));

			err = page_zip_compress_clust_ext(
				LOGFILE
				c_stream, rec, offsets, trx_id_col,
				deleted, storage, &externs, n_blobs);

			if (UNIV_UNLIKELY(err != Z_OK)) {

				goto func_exit;
			}
		} else {
			ulint		len;
			const byte*	src;

			/* Store trx_id and roll_ptr in uncompressed form. */
			src = rec_get_nth_field(rec, offsets,
						trx_id_col, &len);
			ut_ad(src + DATA_TRX_ID_LEN
			      == rec_get_nth_field(rec, offsets,
						   trx_id_col + 1, &len));
			ut_ad(len == DATA_ROLL_PTR_LEN);
			UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
			UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
					   rec_offs_extra_size(offsets));

			/* Compress any preceding bytes. */
Sergei Golubchik's avatar
Sergei Golubchik committed
1184 1185
			c_stream->avail_in = static_cast<uInt>(
				src - c_stream->next_in);
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

			if (c_stream->avail_in) {
				err = deflate(c_stream, Z_NO_FLUSH);
				if (UNIV_UNLIKELY(err != Z_OK)) {

					return(err);
				}
			}

			ut_ad(!c_stream->avail_in);
			ut_ad(c_stream->next_in == src);

			memcpy(storage
			       - (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
			       * (rec_get_heap_no_new(rec) - 1),
			       c_stream->next_in,
			       DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

			c_stream->next_in
				+= DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;

			/* Skip also roll_ptr */
			ut_ad(trx_id_col + 1 < rec_offs_n_fields(offsets));
		}

		/* Compress the last bytes of the record. */
Sergei Golubchik's avatar
Sergei Golubchik committed
1212 1213
		c_stream->avail_in = static_cast<uInt>(
			rec + rec_offs_data_size(offsets) - c_stream->next_in);
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225

		if (c_stream->avail_in) {
			err = deflate(c_stream, Z_NO_FLUSH);
			if (UNIV_UNLIKELY(err != Z_OK)) {

				goto func_exit;
			}
		}
		ut_ad(!c_stream->avail_in);
	} while (--n_dense);

func_exit:
1226
	return(err);}
1227 1228 1229 1230 1231 1232 1233 1234

/**********************************************************************//**
Compress a page.
@return TRUE on success, FALSE on failure; page_zip will be left
intact on failure. */
ibool
page_zip_compress(
/*==============*/
1235 1236 1237 1238 1239 1240 1241 1242 1243
	page_zip_des_t*		page_zip,	/*!< in: size; out: data,
						n_blobs, m_start, m_end,
						m_nonempty */
	const page_t*		page,		/*!< in: uncompressed page */
	dict_index_t*		index,		/*!< in: index of the B-tree
						node */
	ulint			level,		/*!< in: commpression level */
	mtr_t*			mtr)		/*!< in/out: mini-transaction,
						or NULL */
1244
{
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	z_stream		c_stream;
	int			err;
	byte*			fields;		/*!< index field information */
	byte*			buf;		/*!< compressed payload of the
						page */
	byte*			buf_end;	/* end of buf */
	ulint			n_dense;
	ulint			slot_size;	/* amount of uncompressed bytes
						per record */
	const rec_t**		recs;		/*!< dense page directory,
						sorted by address */
	mem_heap_t*		heap;
	ulint			trx_id_col = ULINT_UNDEFINED;
	ulint			n_blobs	= 0;
	byte*			storage;	/* storage of uncompressed
						columns */
	uintmax_t		usec = ut_time_us(NULL);
1262
#ifdef PAGE_ZIP_COMPRESS_DBG
1263
	FILE*			logfile = NULL;
1264 1265 1266 1267
#endif
	/* A local copy of srv_cmp_per_index_enabled to avoid reading that
	variable multiple times in this function since it can be changed at
	anytime. */
1268 1269
	my_bool			cmp_per_index_enabled;
	cmp_per_index_enabled	= srv_cmp_per_index_enabled;
1270 1271

	ut_a(page_is_comp(page));
1272
	ut_a(fil_page_index_page_check(page));
1273 1274
	ut_ad(page_simple_validate_new((page_t*) page));
	ut_ad(page_zip_simple_validate(page_zip));
1275 1276
	ut_ad(dict_table_is_comp(index->table));
	ut_ad(!dict_index_is_ibuf(index));
1277

1278
	UNIV_MEM_ASSERT_RW(page, srv_page_size);
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295

	/* Check the data that will be omitted. */
	ut_a(!memcmp(page + (PAGE_NEW_INFIMUM - REC_N_NEW_EXTRA_BYTES),
		     infimum_extra, sizeof infimum_extra));
	ut_a(!memcmp(page + PAGE_NEW_INFIMUM,
		     infimum_data, sizeof infimum_data));
	ut_a(page[PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES]
	     /* info_bits == 0, n_owned <= max */
	     <= PAGE_DIR_SLOT_MAX_N_OWNED);
	ut_a(!memcmp(page + (PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES + 1),
		     supremum_extra_data, sizeof supremum_extra_data));

	if (page_is_empty(page)) {
		ut_a(rec_get_next_offs(page + PAGE_NEW_INFIMUM, TRUE)
		     == PAGE_NEW_SUPREMUM);
	}

1296 1297 1298 1299
	const ulint n_fields = page_is_leaf(page)
		? dict_index_get_n_fields(index)
		: dict_index_get_n_unique_in_tree_nonleaf(index);
	index_id_t ind_id = index->id;
1300 1301

	/* The dense directory excludes the infimum and supremum records. */
1302
	n_dense = ulint(page_dir_get_n_heap(page)) - PAGE_HEAP_NO_USER_LOW;
1303 1304
#ifdef PAGE_ZIP_COMPRESS_DBG
	if (UNIV_UNLIKELY(page_zip_compress_dbg)) {
1305 1306 1307 1308 1309
		ib::info() << "compress "
			<< static_cast<void*>(page_zip) << " "
			<< static_cast<const void*>(page) << " "
			<< page_is_leaf(page) << " "
			<< n_fields << " " << n_dense;
1310
	}
1311

1312 1313 1314
	if (UNIV_UNLIKELY(page_zip_compress_log)) {
		/* Create a log file for every compression attempt. */
		char	logfilename[9];
1315 1316
		snprintf(logfilename, sizeof logfilename,
			 "%08x", page_zip_compress_log++);
1317 1318 1319 1320
		logfile = fopen(logfilename, "wb");

		if (logfile) {
			/* Write the uncompressed page to the log. */
1321 1322
			if (fwrite(page, 1, srv_page_size, logfile)
			    != srv_page_size) {
1323 1324
				perror("fwrite");
			}
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
			/* Record the compressed size as zero.
			This will be overwritten at successful exit. */
			putc(0, logfile);
			putc(0, logfile);
			putc(0, logfile);
			putc(0, logfile);
		}
	}
#endif /* PAGE_ZIP_COMPRESS_DBG */
	page_zip_stat[page_zip->ssize - 1].compressed++;
	if (cmp_per_index_enabled) {
		mutex_enter(&page_zip_stat_per_index_mutex);
1337
		page_zip_stat_per_index[ind_id].compressed++;
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
		mutex_exit(&page_zip_stat_per_index_mutex);
	}

	if (UNIV_UNLIKELY(n_dense * PAGE_ZIP_DIR_SLOT_SIZE
			  >= page_zip_get_size(page_zip))) {

		goto err_exit;
	}

	MONITOR_INC(MONITOR_PAGE_COMPRESS);

1349 1350 1351 1352 1353
	/* Simulate a compression failure with a probability determined by
	innodb_simulate_comp_failures, only if the page has 2 or more
	records. */

	if (srv_simulate_comp_failures
1354
	    && !dict_index_is_ibuf(index)
1355
	    && page_get_n_recs(page) >= 2
1356
	    && ((ulint)(rand() % 100) < srv_simulate_comp_failures)
1357
	    && strcmp(index->table->name.m_name, "IBUF_DUMMY")) {
1358 1359

#ifdef UNIV_DEBUG
1360
		ib::error()
Marko Mäkelä's avatar
Marko Mäkelä committed
1361 1362
			<< "Simulating a compression failure"
			<< " for table " << index->table->name
1363 1364 1365 1366 1367 1368 1369
			<< " index "
			<< index->name()
			<< " page "
			<< page_get_page_no(page)
			<< "("
			<< (page_is_leaf(page) ? "leaf" : "non-leaf")
			<< ")";
1370 1371 1372 1373 1374 1375

#endif

		goto err_exit;
	}

1376 1377 1378 1379 1380
	heap = mem_heap_create(page_zip_get_size(page_zip)
			       + n_fields * (2 + sizeof(ulint))
			       + REC_OFFS_HEADER_SIZE
			       + n_dense * ((sizeof *recs)
					    - PAGE_ZIP_DIR_SLOT_SIZE)
1381
			       + srv_page_size * 4
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
			       + (512 << MAX_MEM_LEVEL));

	recs = static_cast<const rec_t**>(
		mem_heap_zalloc(heap, n_dense * sizeof *recs));

	fields = static_cast<byte*>(mem_heap_alloc(heap, (n_fields + 1) * 2));

	buf = static_cast<byte*>(
		mem_heap_alloc(heap, page_zip_get_size(page_zip) - PAGE_DATA));

	buf_end = buf + page_zip_get_size(page_zip) - PAGE_DATA;

	/* Compress the data payload. */
	page_zip_set_alloc(&c_stream, heap);

Sergei Golubchik's avatar
Sergei Golubchik committed
1397
	err = deflateInit2(&c_stream, static_cast<int>(level),
1398
			   Z_DEFLATED, srv_page_size_shift,
1399 1400 1401 1402
			   MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
	ut_a(err == Z_OK);

	c_stream.next_out = buf;
1403

1404 1405
	/* Subtract the space reserved for uncompressed data. */
	/* Page header and the end marker of the modification log */
Sergei Golubchik's avatar
Sergei Golubchik committed
1406 1407
	c_stream.avail_out = static_cast<uInt>(buf_end - buf - 1);

1408 1409
	/* Dense page directory and uncompressed columns, if any */
	if (page_is_leaf(page)) {
1410
		if (dict_index_is_clust(index)) {
1411
			trx_id_col = index->db_trx_id();
1412 1413 1414

			slot_size = PAGE_ZIP_DIR_SLOT_SIZE
				+ DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;
1415

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
		} else {
			/* Signal the absence of trx_id
			in page_zip_fields_encode() */
			trx_id_col = 0;
			slot_size = PAGE_ZIP_DIR_SLOT_SIZE;
		}
	} else {
		slot_size = PAGE_ZIP_DIR_SLOT_SIZE + REC_NODE_PTR_SIZE;
		trx_id_col = ULINT_UNDEFINED;
	}

	if (UNIV_UNLIKELY(c_stream.avail_out <= n_dense * slot_size
			  + 6/* sizeof(zlib header and footer) */)) {
		goto zlib_error;
	}

1432 1433 1434
	c_stream.avail_out -= uInt(n_dense * slot_size);
	c_stream.avail_in = uInt(page_zip_fields_encode(n_fields, index,
							trx_id_col, fields));
1435
	c_stream.next_in = fields;
1436

1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
	if (UNIV_LIKELY(!trx_id_col)) {
		trx_id_col = ULINT_UNDEFINED;
	}

	UNIV_MEM_ASSERT_RW(c_stream.next_in, c_stream.avail_in);
	err = deflate(&c_stream, Z_FULL_FLUSH);
	if (err != Z_OK) {
		goto zlib_error;
	}

	ut_ad(!c_stream.avail_in);

	page_zip_dir_encode(page, buf_end, recs);

	c_stream.next_in = (byte*) page + PAGE_ZIP_START;

	storage = buf_end - n_dense * PAGE_ZIP_DIR_SLOT_SIZE;

	/* Compress the records in heap_no order. */
	if (UNIV_UNLIKELY(!n_dense)) {
	} else if (!page_is_leaf(page)) {
		/* This is a node pointer page. */
		err = page_zip_compress_node_ptrs(LOGFILE
						  &c_stream, recs, n_dense,
						  index, storage, heap);
		if (UNIV_UNLIKELY(err != Z_OK)) {
			goto zlib_error;
		}
	} else if (UNIV_LIKELY(trx_id_col == ULINT_UNDEFINED)) {
		/* This is a leaf page in a secondary index. */
		err = page_zip_compress_sec(LOGFILE
					    &c_stream, recs, n_dense);
		if (UNIV_UNLIKELY(err != Z_OK)) {
			goto zlib_error;
		}
	} else {
		/* This is a leaf page in a clustered index. */
		err = page_zip_compress_clust(LOGFILE
					      &c_stream, recs, n_dense,
					      index, &n_blobs, trx_id_col,
					      buf_end - PAGE_ZIP_DIR_SLOT_SIZE
					      * page_get_n_recs(page),
					      storage, heap);
		if (UNIV_UNLIKELY(err != Z_OK)) {
			goto zlib_error;
		}
	}

	/* Finish the compression. */
	ut_ad(!c_stream.avail_in);
	/* Compress any trailing garbage, in case the last record was
	allocated from an originally longer space on the free list,
	or the data of the last record from page_zip_compress_sec(). */
Sergei Golubchik's avatar
Sergei Golubchik committed
1490 1491 1492
	c_stream.avail_in = static_cast<uInt>(
		page_header_get_field(page, PAGE_HEAP_TOP)
		- (c_stream.next_in - page));
1493
	ut_a(c_stream.avail_in <= srv_page_size - PAGE_ZIP_START - PAGE_DIR);
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507

	UNIV_MEM_ASSERT_RW(c_stream.next_in, c_stream.avail_in);
	err = deflate(&c_stream, Z_FINISH);

	if (UNIV_UNLIKELY(err != Z_STREAM_END)) {
zlib_error:
		deflateEnd(&c_stream);
		mem_heap_free(heap);
err_exit:
#ifdef PAGE_ZIP_COMPRESS_DBG
		if (logfile) {
			fclose(logfile);
		}
#endif /* PAGE_ZIP_COMPRESS_DBG */
1508
		if (page_is_leaf(page) && index) {
1509 1510 1511
			dict_index_zip_failure(index);
		}

1512
		uintmax_t	time_diff = ut_time_us(NULL) - usec;
1513 1514 1515 1516
		page_zip_stat[page_zip->ssize - 1].compressed_usec
			+= time_diff;
		if (cmp_per_index_enabled) {
			mutex_enter(&page_zip_stat_per_index_mutex);
1517
			page_zip_stat_per_index[ind_id].compressed_usec
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
				+= time_diff;
			mutex_exit(&page_zip_stat_per_index_mutex);
		}
		return(FALSE);
	}

	err = deflateEnd(&c_stream);
	ut_a(err == Z_OK);

	ut_ad(buf + c_stream.total_out == c_stream.next_out);
	ut_ad((ulint) (storage - c_stream.next_out) >= c_stream.avail_out);

	/* Valgrind believes that zlib does not initialize some bits
	in the last 7 or 8 bytes of the stream.  Make Valgrind happy. */
	UNIV_MEM_VALID(buf, c_stream.total_out);

	/* Zero out the area reserved for the modification log.
	Space for the end marker of the modification log is not
	included in avail_out. */
	memset(c_stream.next_out, 0, c_stream.avail_out + 1/* end marker */);

#ifdef UNIV_DEBUG
	page_zip->m_start =
#endif /* UNIV_DEBUG */
1542
		page_zip->m_end = unsigned(PAGE_DATA + c_stream.total_out);
1543
	page_zip->m_nonempty = FALSE;
1544
	page_zip->n_blobs = unsigned(n_blobs);
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
	/* Copy those header fields that will not be written
	in buf_flush_init_for_writing() */
	memcpy(page_zip->data + FIL_PAGE_PREV, page + FIL_PAGE_PREV,
	       FIL_PAGE_LSN - FIL_PAGE_PREV);
	memcpy(page_zip->data + FIL_PAGE_TYPE, page + FIL_PAGE_TYPE, 2);
	memcpy(page_zip->data + FIL_PAGE_DATA, page + FIL_PAGE_DATA,
	       PAGE_DATA - FIL_PAGE_DATA);
	/* Copy the rest of the compressed page */
	memcpy(page_zip->data + PAGE_DATA, buf,
	       page_zip_get_size(page_zip) - PAGE_DATA);
	mem_heap_free(heap);
#ifdef UNIV_ZIP_DEBUG
	ut_a(page_zip_validate(page_zip, page, index));
#endif /* UNIV_ZIP_DEBUG */

	if (mtr) {
		page_zip_compress_write_log(page_zip, page, index, mtr);
	}

	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));

#ifdef PAGE_ZIP_COMPRESS_DBG
	if (logfile) {
		/* Record the compressed size of the block. */
		byte sz[4];
		mach_write_to_4(sz, c_stream.total_out);
1571
		fseek(logfile, srv_page_size, SEEK_SET);
1572 1573 1574
		if (fwrite(sz, 1, sizeof sz, logfile) != sizeof sz) {
			perror("fwrite");
		}
1575 1576 1577
		fclose(logfile);
	}
#endif /* PAGE_ZIP_COMPRESS_DBG */
1578
	uintmax_t	time_diff = ut_time_us(NULL) - usec;
1579 1580 1581 1582
	page_zip_stat[page_zip->ssize - 1].compressed_ok++;
	page_zip_stat[page_zip->ssize - 1].compressed_usec += time_diff;
	if (cmp_per_index_enabled) {
		mutex_enter(&page_zip_stat_per_index_mutex);
1583 1584
		page_zip_stat_per_index[ind_id].compressed_ok++;
		page_zip_stat_per_index[ind_id].compressed_usec += time_diff;
1585 1586 1587
		mutex_exit(&page_zip_stat_per_index_mutex);
	}

1588
	if (page_is_leaf(page)) {
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
		dict_index_zip_success(index);
	}

	return(TRUE);
}

/**********************************************************************//**
Deallocate the index information initialized by page_zip_fields_decode(). */
static
void
page_zip_fields_free(
/*=================*/
	dict_index_t*	index)	/*!< in: dummy index to be freed */
{
	if (index) {
		dict_table_t*	table = index->table;
1605
		mutex_free(&index->zip_pad.mutex);
1606
		mem_heap_free(index->heap);
Sergei Golubchik's avatar
Sergei Golubchik committed
1607 1608

		dict_mem_table_free(table);
1609 1610 1611 1612 1613
	}
}

/**********************************************************************//**
Read the index information for the compressed page.
1614
@return own: dummy index describing the page, or NULL on error */
1615 1616 1617 1618 1619 1620
static
dict_index_t*
page_zip_fields_decode(
/*===================*/
	const byte*	buf,	/*!< in: index information */
	const byte*	end,	/*!< in: end of buf */
1621
	ulint*		trx_id_col,/*!< in: NULL for non-leaf pages;
1622 1623
				for leaf pages, pointer to where to store
				the position of the trx_id column */
1624
	bool		is_spatial)/*< in: is spatial index or not */
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
{
	const byte*	b;
	ulint		n;
	ulint		i;
	ulint		val;
	dict_table_t*	table;
	dict_index_t*	index;

	/* Determine the number of fields. */
	for (b = buf, n = 0; b < end; n++) {
		if (*b++ & 0x80) {
			b++; /* skip the second byte */
		}
	}

	n--; /* n_nullable or trx_id */

	if (UNIV_UNLIKELY(n > REC_MAX_N_FIELDS)) {

		page_zip_fail(("page_zip_fields_decode: n = %lu\n",
			       (ulong) n));
		return(NULL);
	}

	if (UNIV_UNLIKELY(b > end)) {

		page_zip_fail(("page_zip_fields_decode: %p > %p\n",
			       (const void*) b, (const void*) end));
		return(NULL);
	}

1656
	table = dict_mem_table_create("ZIP_DUMMY", NULL, n, 0,
1657
				      DICT_TF_COMPACT, 0);
1658
	index = dict_mem_index_create(table, "ZIP_DUMMY", 0, n);
1659
	index->n_uniq = unsigned(n);
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
	/* avoid ut_ad(index->cached) in dict_index_get_n_unique_in_tree */
	index->cached = TRUE;

	/* Initialize the fields. */
	for (b = buf, i = 0; i < n; i++) {
		ulint	mtype;
		ulint	len;

		val = *b++;

		if (UNIV_UNLIKELY(val & 0x80)) {
			/* fixed length > 62 bytes */
			val = (val & 0x7f) << 8 | *b++;
			len = val >> 1;
			mtype = DATA_FIXBINARY;
		} else if (UNIV_UNLIKELY(val >= 126)) {
			/* variable length with max > 255 bytes */
			len = 0x7fff;
			mtype = DATA_BINARY;
		} else if (val <= 1) {
			/* variable length with max <= 255 bytes */
			len = 0;
			mtype = DATA_BINARY;
		} else {
			/* fixed length < 62 bytes */
			len = val >> 1;
			mtype = DATA_FIXBINARY;
		}

		dict_mem_table_add_col(table, NULL, NULL, mtype,
				       val & 1 ? DATA_NOT_NULL : 0, len);
		dict_index_add_col(index, table,
				   dict_table_get_nth_col(table, i), 0);
	}

	val = *b++;
	if (UNIV_UNLIKELY(val & 0x80)) {
		val = (val & 0x7f) << 8 | *b++;
	}

	/* Decode the position of the trx_id column. */
	if (trx_id_col) {
		if (!val) {
			val = ULINT_UNDEFINED;
		} else if (UNIV_UNLIKELY(val >= n)) {
			page_zip_fields_free(index);
			index = NULL;
		} else {
			index->type = DICT_CLUSTERED;
		}

		*trx_id_col = val;
	} else {
		/* Decode the number of nullable fields. */
		if (UNIV_UNLIKELY(index->n_nullable > val)) {
			page_zip_fields_free(index);
			index = NULL;
		} else {
1718
			index->n_nullable = unsigned(val);
1719 1720 1721
		}
	}

1722 1723
	/* ROW_FORMAT=COMPRESSED does not support instant ADD COLUMN */
	index->n_core_fields = index->n_fields;
1724 1725
	index->n_core_null_bytes
		= UT_BITS_IN_BYTES(unsigned(index->n_nullable));
1726

1727 1728
	ut_ad(b == end);

1729 1730 1731 1732
	if (is_spatial) {
		index->type |= DICT_SPATIAL;
	}

1733 1734 1735 1736 1737
	return(index);
}

/**********************************************************************//**
Populate the sparse page directory from the dense directory.
1738
@return TRUE on success, FALSE on failure */
1739
static MY_ATTRIBUTE((nonnull, warn_unused_result))
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
ibool
page_zip_dir_decode(
/*================*/
	const page_zip_des_t*	page_zip,/*!< in: dense page directory on
					compressed page */
	page_t*			page,	/*!< in: compact page with valid header;
					out: trailer and sparse page directory
					filled in */
	rec_t**			recs,	/*!< out: dense page directory sorted by
					ascending address (and heap_no) */
	ulint			n_dense)/*!< in: number of user records, and
1751
					size of recs[] */
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
{
	ulint	i;
	ulint	n_recs;
	byte*	slot;

	n_recs = page_get_n_recs(page);

	if (UNIV_UNLIKELY(n_recs > n_dense)) {
		page_zip_fail(("page_zip_dir_decode 1: %lu > %lu\n",
			       (ulong) n_recs, (ulong) n_dense));
		return(FALSE);
	}

	/* Traverse the list of stored records in the sorting order,
	starting from the first user record. */

1768
	slot = page + (srv_page_size - PAGE_DIR - PAGE_DIR_SLOT_SIZE);
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
	UNIV_PREFETCH_RW(slot);

	/* Zero out the page trailer. */
	memset(slot + PAGE_DIR_SLOT_SIZE, 0, PAGE_DIR);

	mach_write_to_2(slot, PAGE_NEW_INFIMUM);
	slot -= PAGE_DIR_SLOT_SIZE;
	UNIV_PREFETCH_RW(slot);

	/* Initialize the sparse directory and copy the dense directory. */
	for (i = 0; i < n_recs; i++) {
		ulint	offs = page_zip_dir_get(page_zip, i);

		if (offs & PAGE_ZIP_DIR_SLOT_OWNED) {
			mach_write_to_2(slot, offs & PAGE_ZIP_DIR_SLOT_MASK);
			slot -= PAGE_DIR_SLOT_SIZE;
			UNIV_PREFETCH_RW(slot);
		}

		if (UNIV_UNLIKELY((offs & PAGE_ZIP_DIR_SLOT_MASK)
				  < PAGE_ZIP_START + REC_N_NEW_EXTRA_BYTES)) {
			page_zip_fail(("page_zip_dir_decode 2: %u %u %lx\n",
				       (unsigned) i, (unsigned) n_recs,
				       (ulong) offs));
			return(FALSE);
		}

		recs[i] = page + (offs & PAGE_ZIP_DIR_SLOT_MASK);
	}

	mach_write_to_2(slot, PAGE_NEW_SUPREMUM);
	{
		const page_dir_slot_t*	last_slot = page_dir_get_nth_slot(
1802
			page, page_dir_get_n_slots(page) - 1U);
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825

		if (UNIV_UNLIKELY(slot != last_slot)) {
			page_zip_fail(("page_zip_dir_decode 3: %p != %p\n",
				       (const void*) slot,
				       (const void*) last_slot));
			return(FALSE);
		}
	}

	/* Copy the rest of the dense directory. */
	for (; i < n_dense; i++) {
		ulint	offs = page_zip_dir_get(page_zip, i);

		if (UNIV_UNLIKELY(offs & ~PAGE_ZIP_DIR_SLOT_MASK)) {
			page_zip_fail(("page_zip_dir_decode 4: %u %u %lx\n",
				       (unsigned) i, (unsigned) n_dense,
				       (ulong) offs));
			return(FALSE);
		}

		recs[i] = page + offs;
	}

1826
	std::sort(recs, recs + n_dense);
1827 1828 1829 1830 1831
	return(TRUE);
}

/**********************************************************************//**
Initialize the REC_N_NEW_EXTRA_BYTES of each record.
1832
@return TRUE on success, FALSE on failure */
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
static
ibool
page_zip_set_extra_bytes(
/*=====================*/
	const page_zip_des_t*	page_zip,/*!< in: compressed page */
	page_t*			page,	/*!< in/out: uncompressed page */
	ulint			info_bits)/*!< in: REC_INFO_MIN_REC_FLAG or 0 */
{
	ulint	n;
	ulint	i;
	ulint	n_owned = 1;
	ulint	offs;
	rec_t*	rec;

	n = page_get_n_recs(page);
	rec = page + PAGE_NEW_INFIMUM;

	for (i = 0; i < n; i++) {
		offs = page_zip_dir_get(page_zip, i);

		if (offs & PAGE_ZIP_DIR_SLOT_DEL) {
			info_bits |= REC_INFO_DELETED_FLAG;
		}
		if (UNIV_UNLIKELY(offs & PAGE_ZIP_DIR_SLOT_OWNED)) {
			info_bits |= n_owned;
			n_owned = 1;
		} else {
			n_owned++;
		}
		offs &= PAGE_ZIP_DIR_SLOT_MASK;
		if (UNIV_UNLIKELY(offs < PAGE_ZIP_START
				  + REC_N_NEW_EXTRA_BYTES)) {
			page_zip_fail(("page_zip_set_extra_bytes 1:"
				       " %u %u %lx\n",
				       (unsigned) i, (unsigned) n,
				       (ulong) offs));
			return(FALSE);
		}

		rec_set_next_offs_new(rec, offs);
		rec = page + offs;
		rec[-REC_N_NEW_EXTRA_BYTES] = (byte) info_bits;
		info_bits = 0;
	}

	/* Set the next pointer of the last user record. */
	rec_set_next_offs_new(rec, PAGE_NEW_SUPREMUM);

	/* Set n_owned of the supremum record. */
	page[PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES] = (byte) n_owned;

	/* The dense directory excludes the infimum and supremum records. */
1885
	n = ulint(page_dir_get_n_heap(page)) - PAGE_HEAP_NO_USER_LOW;
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929

	if (i >= n) {
		if (UNIV_LIKELY(i == n)) {
			return(TRUE);
		}

		page_zip_fail(("page_zip_set_extra_bytes 2: %u != %u\n",
			       (unsigned) i, (unsigned) n));
		return(FALSE);
	}

	offs = page_zip_dir_get(page_zip, i);

	/* Set the extra bytes of deleted records on the free list. */
	for (;;) {
		if (UNIV_UNLIKELY(!offs)
		    || UNIV_UNLIKELY(offs & ~PAGE_ZIP_DIR_SLOT_MASK)) {

			page_zip_fail(("page_zip_set_extra_bytes 3: %lx\n",
				       (ulong) offs));
			return(FALSE);
		}

		rec = page + offs;
		rec[-REC_N_NEW_EXTRA_BYTES] = 0; /* info_bits and n_owned */

		if (++i == n) {
			break;
		}

		offs = page_zip_dir_get(page_zip, i);
		rec_set_next_offs_new(rec, offs);
	}

	/* Terminate the free list. */
	rec[-REC_N_NEW_EXTRA_BYTES] = 0; /* info_bits and n_owned */
	rec_set_next_offs_new(rec, 0);

	return(TRUE);
}

/**********************************************************************//**
Apply the modification log to a record containing externally stored
columns.  Do not copy the fields that are stored separately.
1930
@return pointer to modification log, or NULL on failure */
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
static
const byte*
page_zip_apply_log_ext(
/*===================*/
	rec_t*		rec,		/*!< in/out: record */
	const ulint*	offsets,	/*!< in: rec_get_offsets(rec) */
	ulint		trx_id_col,	/*!< in: position of of DB_TRX_ID */
	const byte*	data,		/*!< in: modification log */
	const byte*	end)		/*!< in: end of modification log */
{
	ulint	i;
	ulint	len;
	byte*	next_out = rec;

	/* Check if there are any externally stored columns.
	For each externally stored column, skip the
	BTR_EXTERN_FIELD_REF. */

	for (i = 0; i < rec_offs_n_fields(offsets); i++) {
		byte*	dst;

		if (UNIV_UNLIKELY(i == trx_id_col)) {
			/* Skip trx_id and roll_ptr */
			dst = rec_get_nth_field(rec, offsets,
						i, &len);
			if (UNIV_UNLIKELY(dst - next_out >= end - data)
			    || UNIV_UNLIKELY
			    (len < (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN))
			    || rec_offs_nth_extern(offsets, i)) {
				page_zip_fail(("page_zip_apply_log_ext:"
					       " trx_id len %lu,"
					       " %p - %p >= %p - %p\n",
					       (ulong) len,
					       (const void*) dst,
					       (const void*) next_out,
					       (const void*) end,
					       (const void*) data));
				return(NULL);
			}

1971 1972
			memcpy(next_out, data, ulint(dst - next_out));
			data += ulint(dst - next_out);
1973 1974 1975 1976 1977 1978 1979 1980
			next_out = dst + (DATA_TRX_ID_LEN
					  + DATA_ROLL_PTR_LEN);
		} else if (rec_offs_nth_extern(offsets, i)) {
			dst = rec_get_nth_field(rec, offsets,
						i, &len);
			ut_ad(len
			      >= BTR_EXTERN_FIELD_REF_SIZE);

1981
			len += ulint(dst - next_out)
1982 1983 1984
				- BTR_EXTERN_FIELD_REF_SIZE;

			if (UNIV_UNLIKELY(data + len >= end)) {
1985 1986
				page_zip_fail(("page_zip_apply_log_ext:"
					       " ext %p+%lu >= %p\n",
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
					       (const void*) data,
					       (ulong) len,
					       (const void*) end));
				return(NULL);
			}

			memcpy(next_out, data, len);
			data += len;
			next_out += len
				+ BTR_EXTERN_FIELD_REF_SIZE;
		}
	}

	/* Copy the last bytes of the record. */
2001
	len = ulint(rec_get_end(rec, offsets) - next_out);
2002
	if (UNIV_UNLIKELY(data + len >= end)) {
2003 2004
		page_zip_fail(("page_zip_apply_log_ext:"
			       " last %p+%lu >= %p\n",
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
			       (const void*) data,
			       (ulong) len,
			       (const void*) end));
		return(NULL);
	}
	memcpy(next_out, data, len);
	data += len;

	return(data);
}

/**********************************************************************//**
Apply the modification log to an uncompressed page.
Do not copy the fields that are stored separately.
2019
@return pointer to end of modification log, or NULL on failure */
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
static
const byte*
page_zip_apply_log(
/*===============*/
	const byte*	data,	/*!< in: modification log */
	ulint		size,	/*!< in: maximum length of the log, in bytes */
	rec_t**		recs,	/*!< in: dense page directory,
				sorted by address (indexed by
				heap_no - PAGE_HEAP_NO_USER_LOW) */
	ulint		n_dense,/*!< in: size of recs[] */
2030
	bool		is_leaf,/*!< in: whether this is a leaf page */
2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
	ulint		trx_id_col,/*!< in: column number of trx_id in the index,
				or ULINT_UNDEFINED if none */
	ulint		heap_status,
				/*!< in: heap_no and status bits for
				the next record to uncompress */
	dict_index_t*	index,	/*!< in: index of the page */
	ulint*		offsets)/*!< in/out: work area for
				rec_get_offsets_reverse() */
{
	const byte* const end = data + size;

	for (;;) {
		ulint	val;
		rec_t*	rec;
		ulint	len;
		ulint	hs;

		val = *data++;
		if (UNIV_UNLIKELY(!val)) {
			return(data - 1);
		}
		if (val & 0x80) {
			val = (val & 0x7f) << 8 | *data++;
			if (UNIV_UNLIKELY(!val)) {
				page_zip_fail(("page_zip_apply_log:"
					       " invalid val %x%x\n",
					       data[-2], data[-1]));
				return(NULL);
			}
		}
		if (UNIV_UNLIKELY(data >= end)) {
			page_zip_fail(("page_zip_apply_log: %p >= %p\n",
				       (const void*) data,
				       (const void*) end));
			return(NULL);
		}
		if (UNIV_UNLIKELY((val >> 1) > n_dense)) {
			page_zip_fail(("page_zip_apply_log: %lu>>1 > %lu\n",
				       (ulong) val, (ulong) n_dense));
			return(NULL);
		}

		/* Determine the heap number and status bits of the record. */
		rec = recs[(val >> 1) - 1];

		hs = ((val >> 1) + 1) << REC_HEAP_NO_SHIFT;
		hs |= heap_status & ((1 << REC_HEAP_NO_SHIFT) - 1);

		/* This may either be an old record that is being
		overwritten (updated in place, or allocated from
		the free list), or a new record, with the next
		available_heap_no. */
		if (UNIV_UNLIKELY(hs > heap_status)) {
			page_zip_fail(("page_zip_apply_log: %lu > %lu\n",
				       (ulong) hs, (ulong) heap_status));
			return(NULL);
		} else if (hs == heap_status) {
			/* A new record was allocated from the heap. */
			if (UNIV_UNLIKELY(val & 1)) {
				/* Only existing records may be cleared. */
				page_zip_fail(("page_zip_apply_log:"
					       " attempting to create"
					       " deleted rec %lu\n",
					       (ulong) hs));
				return(NULL);
			}
			heap_status += 1 << REC_HEAP_NO_SHIFT;
		}

		mach_write_to_2(rec - REC_NEW_HEAP_NO, hs);

		if (val & 1) {
			/* Clear the data bytes of the record. */
			mem_heap_t*	heap	= NULL;
			ulint*		offs;
2106
			offs = rec_get_offsets(rec, index, offsets, is_leaf,
2107 2108 2109 2110 2111 2112 2113 2114 2115
					       ULINT_UNDEFINED, &heap);
			memset(rec, 0, rec_offs_data_size(offs));

			if (UNIV_LIKELY_NULL(heap)) {
				mem_heap_free(heap);
			}
			continue;
		}

2116
		compile_time_assert(REC_STATUS_NODE_PTR == TRUE);
2117 2118 2119
		rec_get_offsets_reverse(data, index,
					hs & REC_STATUS_NODE_PTR,
					offsets);
2120 2121 2122 2123
		/* Silence a debug assertion in rec_offs_make_valid().
		This will be overwritten in page_zip_set_extra_bytes(),
		called by page_zip_decompress_low(). */
		ut_d(rec[-REC_NEW_INFO_BITS] = 0);
2124
		rec_offs_make_valid(rec, index, is_leaf, offsets);
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139

		/* Copy the extra bytes (backwards). */
		{
			byte*	start	= rec_get_start(rec, offsets);
			byte*	b	= rec - REC_N_NEW_EXTRA_BYTES;
			while (b != start) {
				*--b = *data++;
			}
		}

		/* Copy the data bytes. */
		if (UNIV_UNLIKELY(rec_offs_any_extern(offsets))) {
			/* Non-leaf nodes should not contain any
			externally stored columns. */
			if (UNIV_UNLIKELY(hs & REC_STATUS_NODE_PTR)) {
2140 2141
				page_zip_fail(("page_zip_apply_log:"
					       " %lu&REC_STATUS_NODE_PTR\n",
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
					       (ulong) hs));
				return(NULL);
			}

			data = page_zip_apply_log_ext(
				rec, offsets, trx_id_col, data, end);

			if (UNIV_UNLIKELY(!data)) {
				return(NULL);
			}
		} else if (UNIV_UNLIKELY(hs & REC_STATUS_NODE_PTR)) {
			len = rec_offs_data_size(offsets)
				- REC_NODE_PTR_SIZE;
			/* Copy the data bytes, except node_ptr. */
			if (UNIV_UNLIKELY(data + len >= end)) {
2157 2158
				page_zip_fail(("page_zip_apply_log:"
					       " node_ptr %p+%lu >= %p\n",
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
					       (const void*) data,
					       (ulong) len,
					       (const void*) end));
				return(NULL);
			}
			memcpy(rec, data, len);
			data += len;
		} else if (UNIV_LIKELY(trx_id_col == ULINT_UNDEFINED)) {
			len = rec_offs_data_size(offsets);

			/* Copy all data bytes of
			a record in a secondary index. */
			if (UNIV_UNLIKELY(data + len >= end)) {
2172 2173
				page_zip_fail(("page_zip_apply_log:"
					       " sec %p+%lu >= %p\n",
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
					       (const void*) data,
					       (ulong) len,
					       (const void*) end));
				return(NULL);
			}

			memcpy(rec, data, len);
			data += len;
		} else {
			/* Skip DB_TRX_ID and DB_ROLL_PTR. */
			ulint	l = rec_get_nth_field_offs(offsets,
							   trx_id_col, &len);
			byte*	b;

			if (UNIV_UNLIKELY(data + l >= end)
			    || UNIV_UNLIKELY(len < (DATA_TRX_ID_LEN
						    + DATA_ROLL_PTR_LEN))) {
2191 2192
				page_zip_fail(("page_zip_apply_log:"
					       " trx_id %p+%lu >= %p\n",
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
					       (const void*) data,
					       (ulong) l,
					       (const void*) end));
				return(NULL);
			}

			/* Copy any preceding data bytes. */
			memcpy(rec, data, l);
			data += l;

			/* Copy any bytes following DB_TRX_ID, DB_ROLL_PTR. */
			b = rec + l + (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
2205
			len = ulint(rec_get_end(rec, offsets) - b);
2206
			if (UNIV_UNLIKELY(data + len >= end)) {
2207 2208
				page_zip_fail(("page_zip_apply_log:"
					       " clust %p+%lu >= %p\n",
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
					       (const void*) data,
					       (ulong) len,
					       (const void*) end));
				return(NULL);
			}
			memcpy(b, data, len);
			data += len;
		}
	}
}

/**********************************************************************//**
Set the heap_no in a record, and skip the fixed-size record header
that is not included in the d_stream.
2223
@return TRUE on success, FALSE if d_stream does not end at rec */
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
static
ibool
page_zip_decompress_heap_no(
/*========================*/
	z_stream*	d_stream,	/*!< in/out: compressed page stream */
	rec_t*		rec,		/*!< in/out: record */
	ulint&		heap_status)	/*!< in/out: heap_no and status bits */
{
	if (d_stream->next_out != rec - REC_N_NEW_EXTRA_BYTES) {
		/* n_dense has grown since the page was last compressed. */
		return(FALSE);
	}

	/* Skip the REC_N_NEW_EXTRA_BYTES. */
	d_stream->next_out = rec;

	/* Set heap_no and the status bits. */
	mach_write_to_2(rec - REC_NEW_HEAP_NO, heap_status);
	heap_status += 1 << REC_HEAP_NO_SHIFT;
	return(TRUE);
}

/**********************************************************************//**
Decompress the records of a node pointer page.
2248
@return TRUE on success, FALSE on failure */
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
static
ibool
page_zip_decompress_node_ptrs(
/*==========================*/
	page_zip_des_t*	page_zip,	/*!< in/out: compressed page */
	z_stream*	d_stream,	/*!< in/out: compressed page stream */
	rec_t**		recs,		/*!< in: dense page directory
					sorted by address */
	ulint		n_dense,	/*!< in: size of recs[] */
	dict_index_t*	index,		/*!< in: the index of the page */
	ulint*		offsets,	/*!< in/out: temporary offsets */
	mem_heap_t*	heap)		/*!< in: temporary memory heap */
{
	ulint		heap_status = REC_STATUS_NODE_PTR
		| PAGE_HEAP_NO_USER_LOW << REC_HEAP_NO_SHIFT;
	ulint		slot;
	const byte*	storage;

	/* Subtract the space reserved for uncompressed data. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2268 2269
	d_stream->avail_in -= static_cast<uInt>(
		n_dense * (PAGE_ZIP_DIR_SLOT_SIZE + REC_NODE_PTR_SIZE));
2270 2271 2272 2273 2274

	/* Decompress the records in heap_no order. */
	for (slot = 0; slot < n_dense; slot++) {
		rec_t*	rec = recs[slot];

Sergei Golubchik's avatar
Sergei Golubchik committed
2275 2276
		d_stream->avail_out = static_cast<uInt>(
			rec - REC_N_NEW_EXTRA_BYTES - d_stream->next_out);
2277

2278
		ut_ad(d_stream->avail_out < srv_page_size
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
		      - PAGE_ZIP_START - PAGE_DIR);
		switch (inflate(d_stream, Z_SYNC_FLUSH)) {
		case Z_STREAM_END:
			page_zip_decompress_heap_no(
				d_stream, rec, heap_status);
			goto zlib_done;
		case Z_OK:
		case Z_BUF_ERROR:
			if (!d_stream->avail_out) {
				break;
			}
			/* fall through */
		default:
			page_zip_fail(("page_zip_decompress_node_ptrs:"
				       " 1 inflate(Z_SYNC_FLUSH)=%s\n",
				       d_stream->msg));
			goto zlib_error;
		}

		if (!page_zip_decompress_heap_no(
			    d_stream, rec, heap_status)) {
			ut_ad(0);
		}

		/* Read the offsets. The status bits are needed here. */
2304
		offsets = rec_get_offsets(rec, index, offsets, false,
2305 2306 2307 2308 2309 2310 2311
					  ULINT_UNDEFINED, &heap);

		/* Non-leaf nodes should not have any externally
		stored columns. */
		ut_ad(!rec_offs_any_extern(offsets));

		/* Decompress the data bytes, except node_ptr. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2312 2313
		d_stream->avail_out =static_cast<uInt>(
			rec_offs_data_size(offsets) - REC_NODE_PTR_SIZE);
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341

		switch (inflate(d_stream, Z_SYNC_FLUSH)) {
		case Z_STREAM_END:
			goto zlib_done;
		case Z_OK:
		case Z_BUF_ERROR:
			if (!d_stream->avail_out) {
				break;
			}
			/* fall through */
		default:
			page_zip_fail(("page_zip_decompress_node_ptrs:"
				       " 2 inflate(Z_SYNC_FLUSH)=%s\n",
				       d_stream->msg));
			goto zlib_error;
		}

		/* Clear the node pointer in case the record
		will be deleted and the space will be reallocated
		to a smaller record. */
		memset(d_stream->next_out, 0, REC_NODE_PTR_SIZE);
		d_stream->next_out += REC_NODE_PTR_SIZE;

		ut_ad(d_stream->next_out == rec_get_end(rec, offsets));
	}

	/* Decompress any trailing garbage, in case the last record was
	allocated from an originally longer space on the free list. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2342 2343 2344
	d_stream->avail_out = static_cast<uInt>(
		page_header_get_field(page_zip->data, PAGE_HEAP_TOP)
		- page_offset(d_stream->next_out));
2345
	if (UNIV_UNLIKELY(d_stream->avail_out > srv_page_size
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
			  - PAGE_ZIP_START - PAGE_DIR)) {

		page_zip_fail(("page_zip_decompress_node_ptrs:"
			       " avail_out = %u\n",
			       d_stream->avail_out));
		goto zlib_error;
	}

	if (UNIV_UNLIKELY(inflate(d_stream, Z_FINISH) != Z_STREAM_END)) {
		page_zip_fail(("page_zip_decompress_node_ptrs:"
			       " inflate(Z_FINISH)=%s\n",
			       d_stream->msg));
zlib_error:
		inflateEnd(d_stream);
		return(FALSE);
	}

	/* Note that d_stream->avail_out > 0 may hold here
	if the modification log is nonempty. */

zlib_done:
	if (UNIV_UNLIKELY(inflateEnd(d_stream) != Z_OK)) {
		ut_error;
	}

	{
		page_t*	page = page_align(d_stream->next_out);

		/* Clear the unused heap space on the uncompressed page. */
		memset(d_stream->next_out, 0,
2376 2377 2378 2379
		       ulint(page_dir_get_nth_slot(page,
						   page_dir_get_n_slots(page)
						   - 1U)
			     - d_stream->next_out));
2380 2381 2382
	}

#ifdef UNIV_DEBUG
2383
	page_zip->m_start = unsigned(PAGE_DATA + d_stream->total_in);
2384 2385 2386 2387 2388 2389 2390
#endif /* UNIV_DEBUG */

	/* Apply the modification log. */
	{
		const byte*	mod_log_ptr;
		mod_log_ptr = page_zip_apply_log(d_stream->next_in,
						 d_stream->avail_in + 1,
2391
						 recs, n_dense, false,
2392 2393 2394 2395 2396 2397
						 ULINT_UNDEFINED, heap_status,
						 index, offsets);

		if (UNIV_UNLIKELY(!mod_log_ptr)) {
			return(FALSE);
		}
2398
		page_zip->m_end = unsigned(mod_log_ptr - page_zip->data);
2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
		page_zip->m_nonempty = mod_log_ptr != d_stream->next_in;
	}

	if (UNIV_UNLIKELY
	    (page_zip_get_trailer_len(page_zip,
				      dict_index_is_clust(index))
	     + page_zip->m_end >= page_zip_get_size(page_zip))) {
		page_zip_fail(("page_zip_decompress_node_ptrs:"
			       " %lu + %lu >= %lu, %lu\n",
			       (ulong) page_zip_get_trailer_len(
				       page_zip, dict_index_is_clust(index)),
			       (ulong) page_zip->m_end,
			       (ulong) page_zip_get_size(page_zip),
			       (ulong) dict_index_is_clust(index)));
		return(FALSE);
	}

	/* Restore the uncompressed columns in heap_no order. */
	storage = page_zip_dir_start_low(page_zip, n_dense);

	for (slot = 0; slot < n_dense; slot++) {
		rec_t*		rec	= recs[slot];

2422
		offsets = rec_get_offsets(rec, index, offsets, false,
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437
					  ULINT_UNDEFINED, &heap);
		/* Non-leaf nodes should not have any externally
		stored columns. */
		ut_ad(!rec_offs_any_extern(offsets));
		storage -= REC_NODE_PTR_SIZE;

		memcpy(rec_get_end(rec, offsets) - REC_NODE_PTR_SIZE,
		       storage, REC_NODE_PTR_SIZE);
	}

	return(TRUE);
}

/**********************************************************************//**
Decompress the records of a leaf node of a secondary index.
2438
@return TRUE on success, FALSE on failure */
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
static
ibool
page_zip_decompress_sec(
/*====================*/
	page_zip_des_t*	page_zip,	/*!< in/out: compressed page */
	z_stream*	d_stream,	/*!< in/out: compressed page stream */
	rec_t**		recs,		/*!< in: dense page directory
					sorted by address */
	ulint		n_dense,	/*!< in: size of recs[] */
	dict_index_t*	index,		/*!< in: the index of the page */
	ulint*		offsets)	/*!< in/out: temporary offsets */
{
	ulint	heap_status	= REC_STATUS_ORDINARY
		| PAGE_HEAP_NO_USER_LOW << REC_HEAP_NO_SHIFT;
	ulint	slot;

	ut_a(!dict_index_is_clust(index));

	/* Subtract the space reserved for uncompressed data. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2458 2459
	d_stream->avail_in -= static_cast<uint>(
		n_dense * PAGE_ZIP_DIR_SLOT_SIZE);
2460 2461 2462 2463 2464

	for (slot = 0; slot < n_dense; slot++) {
		rec_t*	rec = recs[slot];

		/* Decompress everything up to this record. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2465 2466
		d_stream->avail_out = static_cast<uint>(
			rec - REC_N_NEW_EXTRA_BYTES - d_stream->next_out);
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

		if (UNIV_LIKELY(d_stream->avail_out)) {
			switch (inflate(d_stream, Z_SYNC_FLUSH)) {
			case Z_STREAM_END:
				page_zip_decompress_heap_no(
					d_stream, rec, heap_status);
				goto zlib_done;
			case Z_OK:
			case Z_BUF_ERROR:
				if (!d_stream->avail_out) {
					break;
				}
				/* fall through */
			default:
				page_zip_fail(("page_zip_decompress_sec:"
					       " inflate(Z_SYNC_FLUSH)=%s\n",
					       d_stream->msg));
				goto zlib_error;
			}
		}

		if (!page_zip_decompress_heap_no(
			    d_stream, rec, heap_status)) {
			ut_ad(0);
		}
	}

	/* Decompress the data of the last record and any trailing garbage,
	in case the last record was allocated from an originally longer space
	on the free list. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2497 2498 2499
	d_stream->avail_out = static_cast<uInt>(
		page_header_get_field(page_zip->data, PAGE_HEAP_TOP)
		- page_offset(d_stream->next_out));
2500
	if (UNIV_UNLIKELY(d_stream->avail_out > srv_page_size
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 2530
			  - PAGE_ZIP_START - PAGE_DIR)) {

		page_zip_fail(("page_zip_decompress_sec:"
			       " avail_out = %u\n",
			       d_stream->avail_out));
		goto zlib_error;
	}

	if (UNIV_UNLIKELY(inflate(d_stream, Z_FINISH) != Z_STREAM_END)) {
		page_zip_fail(("page_zip_decompress_sec:"
			       " inflate(Z_FINISH)=%s\n",
			       d_stream->msg));
zlib_error:
		inflateEnd(d_stream);
		return(FALSE);
	}

	/* Note that d_stream->avail_out > 0 may hold here
	if the modification log is nonempty. */

zlib_done:
	if (UNIV_UNLIKELY(inflateEnd(d_stream) != Z_OK)) {
		ut_error;
	}

	{
		page_t*	page = page_align(d_stream->next_out);

		/* Clear the unused heap space on the uncompressed page. */
		memset(d_stream->next_out, 0,
2531 2532 2533 2534
		       ulint(page_dir_get_nth_slot(page,
						   page_dir_get_n_slots(page)
						   - 1U)
			     - d_stream->next_out));
2535 2536
	}

2537
	ut_d(page_zip->m_start = unsigned(PAGE_DATA + d_stream->total_in));
2538 2539 2540 2541 2542 2543

	/* Apply the modification log. */
	{
		const byte*	mod_log_ptr;
		mod_log_ptr = page_zip_apply_log(d_stream->next_in,
						 d_stream->avail_in + 1,
2544
						 recs, n_dense, true,
2545 2546 2547 2548 2549 2550
						 ULINT_UNDEFINED, heap_status,
						 index, offsets);

		if (UNIV_UNLIKELY(!mod_log_ptr)) {
			return(FALSE);
		}
2551
		page_zip->m_end = unsigned(mod_log_ptr - page_zip->data);
2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
		page_zip->m_nonempty = mod_log_ptr != d_stream->next_in;
	}

	if (UNIV_UNLIKELY(page_zip_get_trailer_len(page_zip, FALSE)
			  + page_zip->m_end >= page_zip_get_size(page_zip))) {

		page_zip_fail(("page_zip_decompress_sec: %lu + %lu >= %lu\n",
			       (ulong) page_zip_get_trailer_len(
				       page_zip, FALSE),
			       (ulong) page_zip->m_end,
			       (ulong) page_zip_get_size(page_zip)));
		return(FALSE);
	}

	/* There are no uncompressed columns on leaf pages of
	secondary indexes. */

	return(TRUE);
}

/**********************************************************************//**
Decompress a record of a leaf node of a clustered index that contains
externally stored columns.
2575
@return TRUE on success */
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
static
ibool
page_zip_decompress_clust_ext(
/*==========================*/
	z_stream*	d_stream,	/*!< in/out: compressed page stream */
	rec_t*		rec,		/*!< in/out: record */
	const ulint*	offsets,	/*!< in: rec_get_offsets(rec) */
	ulint		trx_id_col)	/*!< in: position of of DB_TRX_ID */
{
	ulint	i;

	for (i = 0; i < rec_offs_n_fields(offsets); i++) {
		ulint	len;
		byte*	dst;

		if (UNIV_UNLIKELY(i == trx_id_col)) {
			/* Skip trx_id and roll_ptr */
			dst = rec_get_nth_field(rec, offsets, i, &len);
			if (UNIV_UNLIKELY(len < DATA_TRX_ID_LEN
					  + DATA_ROLL_PTR_LEN)) {

				page_zip_fail(("page_zip_decompress_clust_ext:"
					       " len[%lu] = %lu\n",
					       (ulong) i, (ulong) len));
				return(FALSE);
			}

			if (rec_offs_nth_extern(offsets, i)) {

				page_zip_fail(("page_zip_decompress_clust_ext:"
					       " DB_TRX_ID at %lu is ext\n",
					       (ulong) i));
				return(FALSE);
			}

Sergei Golubchik's avatar
Sergei Golubchik committed
2611 2612
			d_stream->avail_out = static_cast<uInt>(
				dst - d_stream->next_out);
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642

			switch (inflate(d_stream, Z_SYNC_FLUSH)) {
			case Z_STREAM_END:
			case Z_OK:
			case Z_BUF_ERROR:
				if (!d_stream->avail_out) {
					break;
				}
				/* fall through */
			default:
				page_zip_fail(("page_zip_decompress_clust_ext:"
					       " 1 inflate(Z_SYNC_FLUSH)=%s\n",
					       d_stream->msg));
				return(FALSE);
			}

			ut_ad(d_stream->next_out == dst);

			/* Clear DB_TRX_ID and DB_ROLL_PTR in order to
			avoid uninitialized bytes in case the record
			is affected by page_zip_apply_log(). */
			memset(dst, 0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

			d_stream->next_out += DATA_TRX_ID_LEN
				+ DATA_ROLL_PTR_LEN;
		} else if (rec_offs_nth_extern(offsets, i)) {
			dst = rec_get_nth_field(rec, offsets, i, &len);
			ut_ad(len >= BTR_EXTERN_FIELD_REF_SIZE);
			dst += len - BTR_EXTERN_FIELD_REF_SIZE;

Sergei Golubchik's avatar
Sergei Golubchik committed
2643 2644
			d_stream->avail_out = static_cast<uInt>(
				dst - d_stream->next_out);
2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684
			switch (inflate(d_stream, Z_SYNC_FLUSH)) {
			case Z_STREAM_END:
			case Z_OK:
			case Z_BUF_ERROR:
				if (!d_stream->avail_out) {
					break;
				}
				/* fall through */
			default:
				page_zip_fail(("page_zip_decompress_clust_ext:"
					       " 2 inflate(Z_SYNC_FLUSH)=%s\n",
					       d_stream->msg));
				return(FALSE);
			}

			ut_ad(d_stream->next_out == dst);

			/* Clear the BLOB pointer in case
			the record will be deleted and the
			space will not be reused.  Note that
			the final initialization of the BLOB
			pointers (copying from "externs"
			or clearing) will have to take place
			only after the page modification log
			has been applied.  Otherwise, we
			could end up with an uninitialized
			BLOB pointer when a record is deleted,
			reallocated and deleted. */
			memset(d_stream->next_out, 0,
			       BTR_EXTERN_FIELD_REF_SIZE);
			d_stream->next_out
				+= BTR_EXTERN_FIELD_REF_SIZE;
		}
	}

	return(TRUE);
}

/**********************************************************************//**
Compress the records of a leaf node of a clustered index.
2685
@return TRUE on success, FALSE on failure */
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
static
ibool
page_zip_decompress_clust(
/*======================*/
	page_zip_des_t*	page_zip,	/*!< in/out: compressed page */
	z_stream*	d_stream,	/*!< in/out: compressed page stream */
	rec_t**		recs,		/*!< in: dense page directory
					sorted by address */
	ulint		n_dense,	/*!< in: size of recs[] */
	dict_index_t*	index,		/*!< in: the index of the page */
	ulint		trx_id_col,	/*!< index of the trx_id column */
	ulint*		offsets,	/*!< in/out: temporary offsets */
	mem_heap_t*	heap)		/*!< in: temporary memory heap */
{
	int		err;
	ulint		slot;
	ulint		heap_status	= REC_STATUS_ORDINARY
		| PAGE_HEAP_NO_USER_LOW << REC_HEAP_NO_SHIFT;
	const byte*	storage;
	const byte*	externs;

	ut_a(dict_index_is_clust(index));

	/* Subtract the space reserved for uncompressed data. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2710
	d_stream->avail_in -= static_cast<uInt>(n_dense)
2711
			    * (PAGE_ZIP_CLUST_LEAF_SLOT_SIZE);
2712 2713 2714 2715 2716

	/* Decompress the records in heap_no order. */
	for (slot = 0; slot < n_dense; slot++) {
		rec_t*	rec	= recs[slot];

Sergei Golubchik's avatar
Sergei Golubchik committed
2717 2718
		d_stream->avail_out =static_cast<uInt>(
			rec - REC_N_NEW_EXTRA_BYTES - d_stream->next_out);
2719

2720
		ut_ad(d_stream->avail_out < srv_page_size
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
		      - PAGE_ZIP_START - PAGE_DIR);
		err = inflate(d_stream, Z_SYNC_FLUSH);
		switch (err) {
		case Z_STREAM_END:
			page_zip_decompress_heap_no(
				d_stream, rec, heap_status);
			goto zlib_done;
		case Z_OK:
		case Z_BUF_ERROR:
			if (UNIV_LIKELY(!d_stream->avail_out)) {
				break;
			}
			/* fall through */
		default:
			page_zip_fail(("page_zip_decompress_clust:"
				       " 1 inflate(Z_SYNC_FLUSH)=%s\n",
				       d_stream->msg));
			goto zlib_error;
		}

		if (!page_zip_decompress_heap_no(
			    d_stream, rec, heap_status)) {
			ut_ad(0);
		}

		/* Read the offsets. The status bits are needed here. */
2747
		offsets = rec_get_offsets(rec, index, offsets, true,
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775
					  ULINT_UNDEFINED, &heap);

		/* This is a leaf page in a clustered index. */

		/* Check if there are any externally stored columns.
		For each externally stored column, restore the
		BTR_EXTERN_FIELD_REF separately. */

		if (rec_offs_any_extern(offsets)) {
			if (UNIV_UNLIKELY
			    (!page_zip_decompress_clust_ext(
				    d_stream, rec, offsets, trx_id_col))) {

				goto zlib_error;
			}
		} else {
			/* Skip trx_id and roll_ptr */
			ulint	len;
			byte*	dst = rec_get_nth_field(rec, offsets,
							trx_id_col, &len);
			if (UNIV_UNLIKELY(len < DATA_TRX_ID_LEN
					  + DATA_ROLL_PTR_LEN)) {

				page_zip_fail(("page_zip_decompress_clust:"
					       " len = %lu\n", (ulong) len));
				goto zlib_error;
			}

Sergei Golubchik's avatar
Sergei Golubchik committed
2776 2777
			d_stream->avail_out = static_cast<uInt>(
				dst - d_stream->next_out);
2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805

			switch (inflate(d_stream, Z_SYNC_FLUSH)) {
			case Z_STREAM_END:
			case Z_OK:
			case Z_BUF_ERROR:
				if (!d_stream->avail_out) {
					break;
				}
				/* fall through */
			default:
				page_zip_fail(("page_zip_decompress_clust:"
					       " 2 inflate(Z_SYNC_FLUSH)=%s\n",
					       d_stream->msg));
				goto zlib_error;
			}

			ut_ad(d_stream->next_out == dst);

			/* Clear DB_TRX_ID and DB_ROLL_PTR in order to
			avoid uninitialized bytes in case the record
			is affected by page_zip_apply_log(). */
			memset(dst, 0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

			d_stream->next_out += DATA_TRX_ID_LEN
				+ DATA_ROLL_PTR_LEN;
		}

		/* Decompress the last bytes of the record. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2806 2807
		d_stream->avail_out = static_cast<uInt>(
			rec_get_end(rec, offsets) - d_stream->next_out);
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826

		switch (inflate(d_stream, Z_SYNC_FLUSH)) {
		case Z_STREAM_END:
		case Z_OK:
		case Z_BUF_ERROR:
			if (!d_stream->avail_out) {
				break;
			}
			/* fall through */
		default:
			page_zip_fail(("page_zip_decompress_clust:"
				       " 3 inflate(Z_SYNC_FLUSH)=%s\n",
				       d_stream->msg));
			goto zlib_error;
		}
	}

	/* Decompress any trailing garbage, in case the last record was
	allocated from an originally longer space on the free list. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2827 2828 2829
	d_stream->avail_out = static_cast<uInt>(
		page_header_get_field(page_zip->data, PAGE_HEAP_TOP)
		- page_offset(d_stream->next_out));
2830
	if (UNIV_UNLIKELY(d_stream->avail_out > srv_page_size
2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
			  - PAGE_ZIP_START - PAGE_DIR)) {

		page_zip_fail(("page_zip_decompress_clust:"
			       " avail_out = %u\n",
			       d_stream->avail_out));
		goto zlib_error;
	}

	if (UNIV_UNLIKELY(inflate(d_stream, Z_FINISH) != Z_STREAM_END)) {
		page_zip_fail(("page_zip_decompress_clust:"
			       " inflate(Z_FINISH)=%s\n",
			       d_stream->msg));
zlib_error:
		inflateEnd(d_stream);
		return(FALSE);
	}

	/* Note that d_stream->avail_out > 0 may hold here
	if the modification log is nonempty. */

zlib_done:
	if (UNIV_UNLIKELY(inflateEnd(d_stream) != Z_OK)) {
		ut_error;
	}

	{
		page_t*	page = page_align(d_stream->next_out);

		/* Clear the unused heap space on the uncompressed page. */
		memset(d_stream->next_out, 0,
2861 2862 2863 2864
		       ulint(page_dir_get_nth_slot(page,
						   page_dir_get_n_slots(page)
						   - 1U)
			     - d_stream->next_out));
2865 2866
	}

2867
	ut_d(page_zip->m_start = unsigned(PAGE_DATA + d_stream->total_in));
2868 2869 2870 2871 2872 2873

	/* Apply the modification log. */
	{
		const byte*	mod_log_ptr;
		mod_log_ptr = page_zip_apply_log(d_stream->next_in,
						 d_stream->avail_in + 1,
2874
						 recs, n_dense, true,
2875 2876 2877 2878 2879 2880
						 trx_id_col, heap_status,
						 index, offsets);

		if (UNIV_UNLIKELY(!mod_log_ptr)) {
			return(FALSE);
		}
2881
		page_zip->m_end = unsigned(mod_log_ptr - page_zip->data);
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
		page_zip->m_nonempty = mod_log_ptr != d_stream->next_in;
	}

	if (UNIV_UNLIKELY(page_zip_get_trailer_len(page_zip, TRUE)
			  + page_zip->m_end >= page_zip_get_size(page_zip))) {

		page_zip_fail(("page_zip_decompress_clust: %lu + %lu >= %lu\n",
			       (ulong) page_zip_get_trailer_len(
				       page_zip, TRUE),
			       (ulong) page_zip->m_end,
			       (ulong) page_zip_get_size(page_zip)));
		return(FALSE);
	}

	storage = page_zip_dir_start_low(page_zip, n_dense);

	externs = storage - n_dense
		* (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

	/* Restore the uncompressed columns in heap_no order. */

	for (slot = 0; slot < n_dense; slot++) {
		ulint	i;
		ulint	len;
		byte*	dst;
		rec_t*	rec	= recs[slot];
2908
		bool	exists	= !page_zip_dir_find_free(
2909
			page_zip, page_offset(rec));
2910
		offsets = rec_get_offsets(rec, index, offsets, true,
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
					  ULINT_UNDEFINED, &heap);

		dst = rec_get_nth_field(rec, offsets,
					trx_id_col, &len);
		ut_ad(len >= DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
		storage -= DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;
		memcpy(dst, storage,
		       DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

		/* Check if there are any externally stored
		columns in this record.  For each externally
		stored column, restore or clear the
		BTR_EXTERN_FIELD_REF. */
		if (!rec_offs_any_extern(offsets)) {
			continue;
		}

		for (i = 0; i < rec_offs_n_fields(offsets); i++) {
			if (!rec_offs_nth_extern(offsets, i)) {
				continue;
			}
			dst = rec_get_nth_field(rec, offsets, i, &len);

			if (UNIV_UNLIKELY(len < BTR_EXTERN_FIELD_REF_SIZE)) {
				page_zip_fail(("page_zip_decompress_clust:"
					       " %lu < 20\n",
					       (ulong) len));
				return(FALSE);
			}

			dst += len - BTR_EXTERN_FIELD_REF_SIZE;

			if (UNIV_LIKELY(exists)) {
				/* Existing record:
				restore the BLOB pointer */
				externs -= BTR_EXTERN_FIELD_REF_SIZE;

				if (UNIV_UNLIKELY
				    (externs < page_zip->data
				     + page_zip->m_end)) {
					page_zip_fail(("page_zip_"
2952 2953
						       "decompress_clust:"
						       " %p < %p + %lu\n",
2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981
						       (const void*) externs,
						       (const void*)
						       page_zip->data,
						       (ulong)
						       page_zip->m_end));
					return(FALSE);
				}

				memcpy(dst, externs,
				       BTR_EXTERN_FIELD_REF_SIZE);

				page_zip->n_blobs++;
			} else {
				/* Deleted record:
				clear the BLOB pointer */
				memset(dst, 0,
				       BTR_EXTERN_FIELD_REF_SIZE);
			}
		}
	}

	return(TRUE);
}

/**********************************************************************//**
Decompress a page.  This function should tolerate errors on the compressed
page.  Instead of letting assertions fail, it will return FALSE if an
inconsistency is detected.
2982 2983
@return TRUE on success, FALSE on failure */
static
2984
ibool
2985 2986
page_zip_decompress_low(
/*====================*/
2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003
	page_zip_des_t*	page_zip,/*!< in: data, ssize;
				out: m_start, m_end, m_nonempty, n_blobs */
	page_t*		page,	/*!< out: uncompressed page, may be trashed */
	ibool		all)	/*!< in: TRUE=decompress the whole page;
				FALSE=verify but do not copy some
				page header fields that should not change
				after page creation */
{
	z_stream	d_stream;
	dict_index_t*	index	= NULL;
	rec_t**		recs;	/*!< dense page directory, sorted by address */
	ulint		n_dense;/* number of user records on the page */
	ulint		trx_id_col = ULINT_UNDEFINED;
	mem_heap_t*	heap;
	ulint*		offsets;

	ut_ad(page_zip_simple_validate(page_zip));
3004
	UNIV_MEM_ASSERT_W(page, srv_page_size);
3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016
	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));

	/* The dense directory excludes the infimum and supremum records. */
	n_dense = page_dir_get_n_heap(page_zip->data) - PAGE_HEAP_NO_USER_LOW;
	if (UNIV_UNLIKELY(n_dense * PAGE_ZIP_DIR_SLOT_SIZE
			  >= page_zip_get_size(page_zip))) {
		page_zip_fail(("page_zip_decompress 1: %lu %lu\n",
			       (ulong) n_dense,
			       (ulong) page_zip_get_size(page_zip)));
		return(FALSE);
	}

3017
	heap = mem_heap_create(n_dense * (3 * sizeof *recs) + srv_page_size);
3018 3019

	recs = static_cast<rec_t**>(
3020
		mem_heap_alloc(heap, n_dense * sizeof *recs));
3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048

	if (all) {
		/* Copy the page header. */
		memcpy(page, page_zip->data, PAGE_DATA);
	} else {
		/* Check that the bytes that we skip are identical. */
#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
		ut_a(!memcmp(FIL_PAGE_TYPE + page,
			     FIL_PAGE_TYPE + page_zip->data,
			     PAGE_HEADER - FIL_PAGE_TYPE));
		ut_a(!memcmp(PAGE_HEADER + PAGE_LEVEL + page,
			     PAGE_HEADER + PAGE_LEVEL + page_zip->data,
			     PAGE_DATA - (PAGE_HEADER + PAGE_LEVEL)));
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */

		/* Copy the mutable parts of the page header. */
		memcpy(page, page_zip->data, FIL_PAGE_TYPE);
		memcpy(PAGE_HEADER + page, PAGE_HEADER + page_zip->data,
		       PAGE_LEVEL - PAGE_N_DIR_SLOTS);

#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
		/* Check that the page headers match after copying. */
		ut_a(!memcmp(page, page_zip->data, PAGE_DATA));
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */
	}

#ifdef UNIV_ZIP_DEBUG
	/* Clear the uncompressed page, except the header. */
3049
	memset(PAGE_DATA + page, 0x55, srv_page_size - PAGE_DATA);
3050
#endif /* UNIV_ZIP_DEBUG */
3051
	UNIV_MEM_INVALID(PAGE_DATA + page, srv_page_size - PAGE_DATA);
3052 3053 3054

	/* Copy the page directory. */
	if (UNIV_UNLIKELY(!page_zip_dir_decode(page_zip, page, recs,
3055
					       n_dense))) {
3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
zlib_error:
		mem_heap_free(heap);
		return(FALSE);
	}

	/* Copy the infimum and supremum records. */
	memcpy(page + (PAGE_NEW_INFIMUM - REC_N_NEW_EXTRA_BYTES),
	       infimum_extra, sizeof infimum_extra);
	if (page_is_empty(page)) {
		rec_set_next_offs_new(page + PAGE_NEW_INFIMUM,
				      PAGE_NEW_SUPREMUM);
	} else {
		rec_set_next_offs_new(page + PAGE_NEW_INFIMUM,
				      page_zip_dir_get(page_zip, 0)
				      & PAGE_ZIP_DIR_SLOT_MASK);
	}
	memcpy(page + PAGE_NEW_INFIMUM, infimum_data, sizeof infimum_data);
	memcpy(page + (PAGE_NEW_SUPREMUM - REC_N_NEW_EXTRA_BYTES + 1),
	       supremum_extra_data, sizeof supremum_extra_data);

	page_zip_set_alloc(&d_stream, heap);

	d_stream.next_in = page_zip->data + PAGE_DATA;
	/* Subtract the space reserved for
	the page header and the end marker of the modification log. */
Sergei Golubchik's avatar
Sergei Golubchik committed
3081 3082
	d_stream.avail_in = static_cast<uInt>(
		page_zip_get_size(page_zip) - (PAGE_DATA + 1));
3083
	d_stream.next_out = page + PAGE_ZIP_START;
3084
	d_stream.avail_out = uInt(srv_page_size - PAGE_ZIP_START);
3085

3086
	if (UNIV_UNLIKELY(inflateInit2(&d_stream, srv_page_size_shift)
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
			  != Z_OK)) {
		ut_error;
	}

	/* Decode the zlib header and the index information. */
	if (UNIV_UNLIKELY(inflate(&d_stream, Z_BLOCK) != Z_OK)) {

		page_zip_fail(("page_zip_decompress:"
			       " 1 inflate(Z_BLOCK)=%s\n", d_stream.msg));
		goto zlib_error;
	}

	if (UNIV_UNLIKELY(inflate(&d_stream, Z_BLOCK) != Z_OK)) {

		page_zip_fail(("page_zip_decompress:"
			       " 2 inflate(Z_BLOCK)=%s\n", d_stream.msg));
		goto zlib_error;
	}

	index = page_zip_fields_decode(
		page + PAGE_ZIP_START, d_stream.next_out,
3108 3109
		page_is_leaf(page) ? &trx_id_col : NULL,
		fil_page_get_type(page) == FIL_PAGE_RTREE);
3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142

	if (UNIV_UNLIKELY(!index)) {

		goto zlib_error;
	}

	/* Decompress the user records. */
	page_zip->n_blobs = 0;
	d_stream.next_out = page + PAGE_ZIP_START;

	{
		/* Pre-allocate the offsets for rec_get_offsets_reverse(). */
		ulint	n = 1 + 1/* node ptr */ + REC_OFFS_HEADER_SIZE
			+ dict_index_get_n_fields(index);

		offsets = static_cast<ulint*>(
			mem_heap_alloc(heap, n * sizeof(ulint)));

		*offsets = n;
	}

	/* Decompress the records in heap_no order. */
	if (!page_is_leaf(page)) {
		/* This is a node pointer page. */
		ulint	info_bits;

		if (UNIV_UNLIKELY
		    (!page_zip_decompress_node_ptrs(page_zip, &d_stream,
						    recs, n_dense, index,
						    offsets, heap))) {
			goto err_exit;
		}

3143
		info_bits = page_has_prev(page) ? 0 : REC_INFO_MIN_REC_FLAG;
3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180

		if (UNIV_UNLIKELY(!page_zip_set_extra_bytes(page_zip, page,
							    info_bits))) {
			goto err_exit;
		}
	} else if (UNIV_LIKELY(trx_id_col == ULINT_UNDEFINED)) {
		/* This is a leaf page in a secondary index. */
		if (UNIV_UNLIKELY(!page_zip_decompress_sec(page_zip, &d_stream,
							   recs, n_dense,
							   index, offsets))) {
			goto err_exit;
		}

		if (UNIV_UNLIKELY(!page_zip_set_extra_bytes(page_zip,
							    page, 0))) {
err_exit:
			page_zip_fields_free(index);
			mem_heap_free(heap);
			return(FALSE);
		}
	} else {
		/* This is a leaf page in a clustered index. */
		if (UNIV_UNLIKELY(!page_zip_decompress_clust(page_zip,
							     &d_stream, recs,
							     n_dense, index,
							     trx_id_col,
							     offsets, heap))) {
			goto err_exit;
		}

		if (UNIV_UNLIKELY(!page_zip_set_extra_bytes(page_zip,
							    page, 0))) {
			goto err_exit;
		}
	}

	ut_a(page_is_comp(page));
3181
	UNIV_MEM_ASSERT_RW(page, srv_page_size);
3182 3183 3184

	page_zip_fields_free(index);
	mem_heap_free(heap);
3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211

	return(TRUE);
}

/**********************************************************************//**
Decompress a page.  This function should tolerate errors on the compressed
page.  Instead of letting assertions fail, it will return FALSE if an
inconsistency is detected.
@return TRUE on success, FALSE on failure */
ibool
page_zip_decompress(
/*================*/
	page_zip_des_t*	page_zip,/*!< in: data, ssize;
				out: m_start, m_end, m_nonempty, n_blobs */
	page_t*		page,	/*!< out: uncompressed page, may be trashed */
	ibool		all)	/*!< in: TRUE=decompress the whole page;
				FALSE=verify but do not copy some
				page header fields that should not change
				after page creation */
{
	uintmax_t	usec = ut_time_us(NULL);

	if (!page_zip_decompress_low(page_zip, page, all)) {
		return(FALSE);
	}

	uintmax_t	time_diff = ut_time_us(NULL) - usec;
3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264
	page_zip_stat[page_zip->ssize - 1].decompressed++;
	page_zip_stat[page_zip->ssize - 1].decompressed_usec += time_diff;

	index_id_t	index_id = btr_page_get_index_id(page);

	if (srv_cmp_per_index_enabled) {
		mutex_enter(&page_zip_stat_per_index_mutex);
		page_zip_stat_per_index[index_id].decompressed++;
		page_zip_stat_per_index[index_id].decompressed_usec += time_diff;
		mutex_exit(&page_zip_stat_per_index_mutex);
	}

	/* Update the stat counter for LRU policy. */
	buf_LRU_stat_inc_unzip();

	MONITOR_INC(MONITOR_PAGE_DECOMPRESS);

	return(TRUE);
}

#ifdef UNIV_ZIP_DEBUG
/**********************************************************************//**
Dump a block of memory on the standard error stream. */
static
void
page_zip_hexdump_func(
/*==================*/
	const char*	name,	/*!< in: name of the data structure */
	const void*	buf,	/*!< in: data */
	ulint		size)	/*!< in: length of the data, in bytes */
{
	const byte*	s	= static_cast<const byte*>(buf);
	ulint		addr;
	const ulint	width	= 32; /* bytes per line */

	fprintf(stderr, "%s:\n", name);

	for (addr = 0; addr < size; addr += width) {
		ulint	i;

		fprintf(stderr, "%04lx ", (ulong) addr);

		i = ut_min(width, size - addr);

		while (i--) {
			fprintf(stderr, "%02x", *s++);
		}

		putc('\n', stderr);
	}
}

/** Dump a block of memory on the standard error stream.
3265 3266
@param buf in: data
@param size in: length of the data, in bytes */
3267 3268 3269
#define page_zip_hexdump(buf, size) page_zip_hexdump_func(#buf, buf, size)

/** Flag: make page_zip_validate() compare page headers only */
3270
bool	page_zip_validate_header_only;
3271 3272 3273

/**********************************************************************//**
Check that the compressed and decompressed pages match.
3274
@return TRUE if valid, FALSE if not */
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296
ibool
page_zip_validate_low(
/*==================*/
	const page_zip_des_t*	page_zip,/*!< in: compressed page */
	const page_t*		page,	/*!< in: uncompressed page */
	const dict_index_t*	index,	/*!< in: index of the page, if known */
	ibool			sloppy)	/*!< in: FALSE=strict,
					TRUE=ignore the MIN_REC_FLAG */
{
	page_zip_des_t	temp_page_zip;
	byte*		temp_page_buf;
	page_t*		temp_page;
	ibool		valid;

	if (memcmp(page_zip->data + FIL_PAGE_PREV, page + FIL_PAGE_PREV,
		   FIL_PAGE_LSN - FIL_PAGE_PREV)
	    || memcmp(page_zip->data + FIL_PAGE_TYPE, page + FIL_PAGE_TYPE, 2)
	    || memcmp(page_zip->data + FIL_PAGE_DATA, page + FIL_PAGE_DATA,
		      PAGE_DATA - FIL_PAGE_DATA)) {
		page_zip_fail(("page_zip_validate: page header\n"));
		page_zip_hexdump(page_zip, sizeof *page_zip);
		page_zip_hexdump(page_zip->data, page_zip_get_size(page_zip));
3297
		page_zip_hexdump(page, srv_page_size);
3298 3299 3300 3301 3302 3303 3304 3305 3306 3307
		return(FALSE);
	}

	ut_a(page_is_comp(page));

	if (page_zip_validate_header_only) {
		return(TRUE);
	}

	/* page_zip_decompress() expects the uncompressed page to be
3308
	srv_page_size aligned. */
3309 3310
	temp_page_buf = static_cast<byte*>(
		ut_malloc_nokey(2 << srv_page_size_shift));
3311
	temp_page = static_cast<byte*>(ut_align(temp_page_buf, srv_page_size));
3312

3313
	UNIV_MEM_ASSERT_RW(page, srv_page_size);
3314 3315 3316
	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));

	temp_page_zip = *page_zip;
3317
	valid = page_zip_decompress_low(&temp_page_zip, temp_page, TRUE);
3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345
	if (!valid) {
		fputs("page_zip_validate(): failed to decompress\n", stderr);
		goto func_exit;
	}
	if (page_zip->n_blobs != temp_page_zip.n_blobs) {
		page_zip_fail(("page_zip_validate: n_blobs: %u!=%u\n",
			       page_zip->n_blobs, temp_page_zip.n_blobs));
		valid = FALSE;
	}
#ifdef UNIV_DEBUG
	if (page_zip->m_start != temp_page_zip.m_start) {
		page_zip_fail(("page_zip_validate: m_start: %u!=%u\n",
			       page_zip->m_start, temp_page_zip.m_start));
		valid = FALSE;
	}
#endif /* UNIV_DEBUG */
	if (page_zip->m_end != temp_page_zip.m_end) {
		page_zip_fail(("page_zip_validate: m_end: %u!=%u\n",
			       page_zip->m_end, temp_page_zip.m_end));
		valid = FALSE;
	}
	if (page_zip->m_nonempty != temp_page_zip.m_nonempty) {
		page_zip_fail(("page_zip_validate(): m_nonempty: %u!=%u\n",
			       page_zip->m_nonempty,
			       temp_page_zip.m_nonempty));
		valid = FALSE;
	}
	if (memcmp(page + PAGE_HEADER, temp_page + PAGE_HEADER,
3346
		   srv_page_size - PAGE_HEADER - FIL_PAGE_DATA_END)) {
3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369

		/* In crash recovery, the "minimum record" flag may be
		set incorrectly until the mini-transaction is
		committed.  Let us tolerate that difference when we
		are performing a sloppy validation. */

		ulint*		offsets;
		mem_heap_t*	heap;
		const rec_t*	rec;
		const rec_t*	trec;
		byte		info_bits_diff;
		ulint		offset
			= rec_get_next_offs(page + PAGE_NEW_INFIMUM, TRUE);
		ut_a(offset >= PAGE_NEW_SUPREMUM);
		offset -= 5/*REC_NEW_INFO_BITS*/;

		info_bits_diff = page[offset] ^ temp_page[offset];

		if (info_bits_diff == REC_INFO_MIN_REC_FLAG) {
			temp_page[offset] = page[offset];

			if (!memcmp(page + PAGE_HEADER,
				    temp_page + PAGE_HEADER,
3370
				    srv_page_size - PAGE_HEADER
3371 3372 3373 3374
				    - FIL_PAGE_DATA_END)) {

				/* Only the minimum record flag
				differed.  Let us ignore it. */
3375 3376 3377
				page_zip_fail(("page_zip_validate:"
					       " min_rec_flag"
					       " (%s%lu,%lu,0x%02lx)\n",
3378 3379 3380 3381
					       sloppy ? "ignored, " : "",
					       page_get_space_id(page),
					       page_get_page_no(page),
					       (ulong) page[offset]));
3382 3383 3384 3385 3386 3387 3388 3389 3390 3391
				/* We don't check for spatial index, since
				the "minimum record" could be deleted when
				doing rtr_update_mbr_field.
				GIS_FIXME: need to validate why
				rtr_update_mbr_field.() could affect this */
				if (index && dict_index_is_spatial(index)) {
					valid = true;
				} else {
					valid = sloppy;
				}
3392 3393 3394 3395 3396 3397 3398 3399 3400 3401
				goto func_exit;
			}
		}

		/* Compare the pointers in the PAGE_FREE list. */
		rec = page_header_get_ptr(page, PAGE_FREE);
		trec = page_header_get_ptr(temp_page, PAGE_FREE);

		while (rec || trec) {
			if (page_offset(rec) != page_offset(trec)) {
3402 3403
				page_zip_fail(("page_zip_validate:"
					       " PAGE_FREE list: %u!=%u\n",
3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420
					       (unsigned) page_offset(rec),
					       (unsigned) page_offset(trec)));
				valid = FALSE;
				goto func_exit;
			}

			rec = page_rec_get_next_low(rec, TRUE);
			trec = page_rec_get_next_low(trec, TRUE);
		}

		/* Compare the records. */
		heap = NULL;
		offsets = NULL;
		rec = page_rec_get_next_low(
			page + PAGE_NEW_INFIMUM, TRUE);
		trec = page_rec_get_next_low(
			temp_page + PAGE_NEW_INFIMUM, TRUE);
3421
		const bool is_leaf = page_is_leaf(page);
3422 3423 3424

		do {
			if (page_offset(rec) != page_offset(trec)) {
3425 3426
				page_zip_fail(("page_zip_validate:"
					       " record list: 0x%02x!=0x%02x\n",
3427 3428 3429 3430 3431 3432 3433 3434 3435
					       (unsigned) page_offset(rec),
					       (unsigned) page_offset(trec)));
				valid = FALSE;
				break;
			}

			if (index) {
				/* Compare the data. */
				offsets = rec_get_offsets(
3436
					rec, index, offsets, is_leaf,
3437 3438 3439 3440 3441 3442
					ULINT_UNDEFINED, &heap);

				if (memcmp(rec - rec_offs_extra_size(offsets),
					   trec - rec_offs_extra_size(offsets),
					   rec_offs_size(offsets))) {
					page_zip_fail(
3443 3444
						("page_zip_validate:"
						 " record content: 0x%02x",
3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463
						 (unsigned) page_offset(rec)));
					valid = FALSE;
					break;
				}
			}

			rec = page_rec_get_next_low(rec, TRUE);
			trec = page_rec_get_next_low(trec, TRUE);
		} while (rec || trec);

		if (heap) {
			mem_heap_free(heap);
		}
	}

func_exit:
	if (!valid) {
		page_zip_hexdump(page_zip, sizeof *page_zip);
		page_zip_hexdump(page_zip->data, page_zip_get_size(page_zip));
3464 3465
		page_zip_hexdump(page, srv_page_size);
		page_zip_hexdump(temp_page, srv_page_size);
3466 3467 3468 3469 3470 3471 3472
	}
	ut_free(temp_page_buf);
	return(valid);
}

/**********************************************************************//**
Check that the compressed and decompressed pages match.
3473
@return TRUE if valid, FALSE if not */
3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488
ibool
page_zip_validate(
/*==============*/
	const page_zip_des_t*	page_zip,/*!< in: compressed page */
	const page_t*		page,	/*!< in: uncompressed page */
	const dict_index_t*	index)	/*!< in: index of the page, if known */
{
	return(page_zip_validate_low(page_zip, page, index,
				     recv_recovery_is_on()));
}
#endif /* UNIV_ZIP_DEBUG */

#ifdef UNIV_DEBUG
/**********************************************************************//**
Assert that the compressed and decompressed page headers match.
3489
@return TRUE */
3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510
static
ibool
page_zip_header_cmp(
/*================*/
	const page_zip_des_t*	page_zip,/*!< in: compressed page */
	const byte*		page)	/*!< in: uncompressed page */
{
	ut_ad(!memcmp(page_zip->data + FIL_PAGE_PREV, page + FIL_PAGE_PREV,
		      FIL_PAGE_LSN - FIL_PAGE_PREV));
	ut_ad(!memcmp(page_zip->data + FIL_PAGE_TYPE, page + FIL_PAGE_TYPE,
		      2));
	ut_ad(!memcmp(page_zip->data + FIL_PAGE_DATA, page + FIL_PAGE_DATA,
		      PAGE_DATA - FIL_PAGE_DATA));

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

/**********************************************************************//**
Write a record on the compressed page that contains externally stored
columns.  The data must already have been written to the uncompressed page.
3511
@return end of modification log */
3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556
static
byte*
page_zip_write_rec_ext(
/*===================*/
	page_zip_des_t*	page_zip,	/*!< in/out: compressed page */
	const page_t*	page,		/*!< in: page containing rec */
	const byte*	rec,		/*!< in: record being written */
	dict_index_t*	index,		/*!< in: record descriptor */
	const ulint*	offsets,	/*!< in: rec_get_offsets(rec, index) */
	ulint		create,		/*!< in: nonzero=insert, zero=update */
	ulint		trx_id_col,	/*!< in: position of DB_TRX_ID */
	ulint		heap_no,	/*!< in: heap number of rec */
	byte*		storage,	/*!< in: end of dense page directory */
	byte*		data)		/*!< in: end of modification log */
{
	const byte*	start	= rec;
	ulint		i;
	ulint		len;
	byte*		externs	= storage;
	ulint		n_ext	= rec_offs_n_extern(offsets);

	ut_ad(rec_offs_validate(rec, index, offsets));
	UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
	UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
			   rec_offs_extra_size(offsets));

	externs -= (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
		* (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW);

	/* Note that this will not take into account
	the BLOB columns of rec if create==TRUE. */
	ut_ad(data + rec_offs_data_size(offsets)
	      - (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
	      - n_ext * BTR_EXTERN_FIELD_REF_SIZE
	      < externs - BTR_EXTERN_FIELD_REF_SIZE * page_zip->n_blobs);

	{
		ulint	blob_no = page_zip_get_n_prev_extern(
			page_zip, rec, index);
		byte*	ext_end = externs - page_zip->n_blobs
			* BTR_EXTERN_FIELD_REF_SIZE;
		ut_ad(blob_no <= page_zip->n_blobs);
		externs -= blob_no * BTR_EXTERN_FIELD_REF_SIZE;

		if (create) {
Sergei Golubchik's avatar
Sergei Golubchik committed
3557
			page_zip->n_blobs += static_cast<unsigned>(n_ext);
3558 3559 3560 3561 3562
			ASSERT_ZERO_BLOB(ext_end - n_ext
					 * BTR_EXTERN_FIELD_REF_SIZE);
			memmove(ext_end - n_ext
				* BTR_EXTERN_FIELD_REF_SIZE,
				ext_end,
3563
				ulint(externs - ext_end));
3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588
		}

		ut_a(blob_no + n_ext <= page_zip->n_blobs);
	}

	for (i = 0; i < rec_offs_n_fields(offsets); i++) {
		const byte*	src;

		if (UNIV_UNLIKELY(i == trx_id_col)) {
			ut_ad(!rec_offs_nth_extern(offsets,
						   i));
			ut_ad(!rec_offs_nth_extern(offsets,
						   i + 1));
			/* Locate trx_id and roll_ptr. */
			src = rec_get_nth_field(rec, offsets,
						i, &len);
			ut_ad(len == DATA_TRX_ID_LEN);
			ut_ad(src + DATA_TRX_ID_LEN
			      == rec_get_nth_field(
				      rec, offsets,
				      i + 1, &len));
			ut_ad(len == DATA_ROLL_PTR_LEN);

			/* Log the preceding fields. */
			ASSERT_ZERO(data, src - start);
3589
			memcpy(data, start, ulint(src - start));
3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608
			data += src - start;
			start = src + (DATA_TRX_ID_LEN
				       + DATA_ROLL_PTR_LEN);

			/* Store trx_id and roll_ptr. */
			memcpy(storage - (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
			       * (heap_no - 1),
			       src, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
			i++; /* skip also roll_ptr */
		} else if (rec_offs_nth_extern(offsets, i)) {
			src = rec_get_nth_field(rec, offsets,
						i, &len);

			ut_ad(dict_index_is_clust(index));
			ut_ad(len
			      >= BTR_EXTERN_FIELD_REF_SIZE);
			src += len - BTR_EXTERN_FIELD_REF_SIZE;

			ASSERT_ZERO(data, src - start);
3609
			memcpy(data, start, ulint(src - start));
3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620
			data += src - start;
			start = src + BTR_EXTERN_FIELD_REF_SIZE;

			/* Store the BLOB pointer. */
			externs -= BTR_EXTERN_FIELD_REF_SIZE;
			ut_ad(data < externs);
			memcpy(externs, src, BTR_EXTERN_FIELD_REF_SIZE);
		}
	}

	/* Log the last bytes of the record. */
3621
	len = rec_offs_data_size(offsets) - ulint(start - rec);
3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669

	ASSERT_ZERO(data, len);
	memcpy(data, start, len);
	data += len;

	return(data);
}

/**********************************************************************//**
Write an entire record on the compressed page.  The data must already
have been written to the uncompressed page. */
void
page_zip_write_rec(
/*===============*/
	page_zip_des_t*	page_zip,/*!< in/out: compressed page */
	const byte*	rec,	/*!< in: record being written */
	dict_index_t*	index,	/*!< in: the index the record belongs to */
	const ulint*	offsets,/*!< in: rec_get_offsets(rec, index) */
	ulint		create)	/*!< in: nonzero=insert, zero=update */
{
	const page_t*	page;
	byte*		data;
	byte*		storage;
	ulint		heap_no;
	byte*		slot;

	ut_ad(page_zip_simple_validate(page_zip));
	ut_ad(page_zip_get_size(page_zip)
	      > PAGE_DATA + page_zip_dir_size(page_zip));
	ut_ad(rec_offs_comp(offsets));
	ut_ad(rec_offs_validate(rec, index, offsets));

	ut_ad(page_zip->m_start >= PAGE_DATA);

	page = page_align(rec);

	ut_ad(page_zip_header_cmp(page_zip, page));
	ut_ad(page_simple_validate_new((page_t*) page));

	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
	UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
	UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
			   rec_offs_extra_size(offsets));

	slot = page_zip_dir_find(page_zip, page_offset(rec));
	ut_a(slot);
	/* Copy the delete mark. */
	if (rec_get_deleted_flag(rec, TRUE)) {
3670
		/* In delete-marked records, DB_TRX_ID must
3671 3672 3673
		always refer to an existing undo log record.
		On non-leaf pages, the delete-mark flag is garbage. */
		ut_ad(!index->is_primary() || !page_is_leaf(page)
3674
		      || row_get_rec_trx_id(rec, index, offsets));
3675 3676 3677 3678 3679 3680
		*slot |= PAGE_ZIP_DIR_SLOT_DEL >> 8;
	} else {
		*slot &= ~(PAGE_ZIP_DIR_SLOT_DEL >> 8);
	}

	ut_ad(rec_get_start((rec_t*) rec, offsets) >= page + PAGE_ZIP_START);
3681
	ut_ad(rec_get_end((rec_t*) rec, offsets) <= page + srv_page_size
3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730
	      - PAGE_DIR - PAGE_DIR_SLOT_SIZE
	      * page_dir_get_n_slots(page));

	heap_no = rec_get_heap_no_new(rec);
	ut_ad(heap_no >= PAGE_HEAP_NO_USER_LOW); /* not infimum or supremum */
	ut_ad(heap_no < page_dir_get_n_heap(page));

	/* Append to the modification log. */
	data = page_zip->data + page_zip->m_end;
	ut_ad(!*data);

	/* Identify the record by writing its heap number - 1.
	0 is reserved to indicate the end of the modification log. */

	if (UNIV_UNLIKELY(heap_no - 1 >= 64)) {
		*data++ = (byte) (0x80 | (heap_no - 1) >> 7);
		ut_ad(!*data);
	}
	*data++ = (byte) ((heap_no - 1) << 1);
	ut_ad(!*data);

	{
		const byte*	start	= rec - rec_offs_extra_size(offsets);
		const byte*	b	= rec - REC_N_NEW_EXTRA_BYTES;

		/* Write the extra bytes backwards, so that
		rec_offs_extra_size() can be easily computed in
		page_zip_apply_log() by invoking
		rec_get_offsets_reverse(). */

		while (b != start) {
			*data++ = *--b;
			ut_ad(!*data);
		}
	}

	/* Write the data bytes.  Store the uncompressed bytes separately. */
	storage = page_zip_dir_start(page_zip);

	if (page_is_leaf(page)) {
		ulint		len;

		if (dict_index_is_clust(index)) {
			/* Store separately trx_id, roll_ptr and
			the BTR_EXTERN_FIELD_REF of each BLOB column. */
			if (rec_offs_any_extern(offsets)) {
				data = page_zip_write_rec_ext(
					page_zip, page,
					rec, index, offsets, create,
3731 3732
					index->db_trx_id(), heap_no,
					storage, data);
3733 3734 3735 3736
			} else {
				/* Locate trx_id and roll_ptr. */
				const byte*	src
					= rec_get_nth_field(rec, offsets,
3737 3738
							    index->db_trx_id(),
							    &len);
3739 3740 3741 3742
				ut_ad(len == DATA_TRX_ID_LEN);
				ut_ad(src + DATA_TRX_ID_LEN
				      == rec_get_nth_field(
					      rec, offsets,
3743
					      index->db_roll_ptr(), &len));
3744 3745 3746 3747
				ut_ad(len == DATA_ROLL_PTR_LEN);

				/* Log the preceding fields. */
				ASSERT_ZERO(data, src - rec);
3748
				memcpy(data, rec, ulint(src - rec));
3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761
				data += src - rec;

				/* Store trx_id and roll_ptr. */
				memcpy(storage
				       - (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN)
				       * (heap_no - 1),
				       src,
				       DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

				src += DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;

				/* Log the last bytes of the record. */
				len = rec_offs_data_size(offsets)
3762
					- ulint(src - rec);
3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804

				ASSERT_ZERO(data, len);
				memcpy(data, src, len);
				data += len;
			}
		} else {
			/* Leaf page of a secondary index:
			no externally stored columns */
			ut_ad(!rec_offs_any_extern(offsets));

			/* Log the entire record. */
			len = rec_offs_data_size(offsets);

			ASSERT_ZERO(data, len);
			memcpy(data, rec, len);
			data += len;
		}
	} else {
		/* This is a node pointer page. */
		ulint	len;

		/* Non-leaf nodes should not have any externally
		stored columns. */
		ut_ad(!rec_offs_any_extern(offsets));

		/* Copy the data bytes, except node_ptr. */
		len = rec_offs_data_size(offsets) - REC_NODE_PTR_SIZE;
		ut_ad(data + len < storage - REC_NODE_PTR_SIZE
		      * (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW));
		ASSERT_ZERO(data, len);
		memcpy(data, rec, len);
		data += len;

		/* Copy the node pointer to the uncompressed area. */
		memcpy(storage - REC_NODE_PTR_SIZE
		       * (heap_no - 1),
		       rec + len,
		       REC_NODE_PTR_SIZE);
	}

	ut_a(!*data);
	ut_ad((ulint) (data - page_zip->data) < page_zip_get_size(page_zip));
3805
	page_zip->m_end = unsigned(data - page_zip->data);
3806 3807 3808 3809 3810 3811 3812 3813 3814
	page_zip->m_nonempty = TRUE;

#ifdef UNIV_ZIP_DEBUG
	ut_a(page_zip_validate(page_zip, page_align(rec), index));
#endif /* UNIV_ZIP_DEBUG */
}

/***********************************************************//**
Parses a log record of writing a BLOB pointer of a record.
3815
@return end of log record or NULL */
3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826
byte*
page_zip_parse_write_blob_ptr(
/*==========================*/
	byte*		ptr,	/*!< in: redo log buffer */
	byte*		end_ptr,/*!< in: redo log buffer end */
	page_t*		page,	/*!< in/out: uncompressed page */
	page_zip_des_t*	page_zip)/*!< in/out: compressed page */
{
	ulint	offset;
	ulint	z_offset;

3827 3828
	ut_ad(ptr != NULL);
	ut_ad(end_ptr != NULL);
3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839
	ut_ad(!page == !page_zip);

	if (UNIV_UNLIKELY
	    (end_ptr < ptr + (2 + 2 + BTR_EXTERN_FIELD_REF_SIZE))) {

		return(NULL);
	}

	offset = mach_read_from_2(ptr);
	z_offset = mach_read_from_2(ptr + 2);

3840
	if (offset < PAGE_ZIP_START
3841 3842
	    || offset >= srv_page_size
	    || z_offset >= srv_page_size) {
3843
corrupt:
3844
		recv_sys.found_corrupt_log = TRUE;
3845 3846 3847 3848 3849

		return(NULL);
	}

	if (page) {
3850 3851

		if (!page_zip || !page_is_leaf(page)) {
3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893

			goto corrupt;
		}

#ifdef UNIV_ZIP_DEBUG
		ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */

		memcpy(page + offset,
		       ptr + 4, BTR_EXTERN_FIELD_REF_SIZE);
		memcpy(page_zip->data + z_offset,
		       ptr + 4, BTR_EXTERN_FIELD_REF_SIZE);

#ifdef UNIV_ZIP_DEBUG
		ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */
	}

	return(ptr + (2 + 2 + BTR_EXTERN_FIELD_REF_SIZE));
}

/**********************************************************************//**
Write a BLOB pointer of a record on the leaf page of a clustered index.
The information must already have been updated on the uncompressed page. */
void
page_zip_write_blob_ptr(
/*====================*/
	page_zip_des_t*	page_zip,/*!< in/out: compressed page */
	const byte*	rec,	/*!< in/out: record whose data is being
				written */
	dict_index_t*	index,	/*!< in: index of the page */
	const ulint*	offsets,/*!< in: rec_get_offsets(rec, index) */
	ulint		n,	/*!< in: column index */
	mtr_t*		mtr)	/*!< in: mini-transaction handle,
				or NULL if no logging is needed */
{
	const byte*	field;
	byte*		externs;
	const page_t*	page	= page_align(rec);
	ulint		blob_no;
	ulint		len;

3894 3895 3896 3897
	ut_ad(page_zip != NULL);
	ut_ad(rec != NULL);
	ut_ad(index != NULL);
	ut_ad(offsets != NULL);
3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
	ut_ad(page_simple_validate_new((page_t*) page));
	ut_ad(page_zip_simple_validate(page_zip));
	ut_ad(page_zip_get_size(page_zip)
	      > PAGE_DATA + page_zip_dir_size(page_zip));
	ut_ad(rec_offs_comp(offsets));
	ut_ad(rec_offs_validate(rec, NULL, offsets));
	ut_ad(rec_offs_any_extern(offsets));
	ut_ad(rec_offs_nth_extern(offsets, n));

	ut_ad(page_zip->m_start >= PAGE_DATA);
	ut_ad(page_zip_header_cmp(page_zip, page));

	ut_ad(page_is_leaf(page));
	ut_ad(dict_index_is_clust(index));

	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
	UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
	UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
			   rec_offs_extra_size(offsets));

	blob_no = page_zip_get_n_prev_extern(page_zip, rec, index)
		+ rec_get_n_extern_new(rec, index, n);
	ut_a(blob_no < page_zip->n_blobs);

	externs = page_zip->data + page_zip_get_size(page_zip)
		- (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW)
3924
		* PAGE_ZIP_CLUST_LEAF_SLOT_SIZE;
3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947

	field = rec_get_nth_field(rec, offsets, n, &len);

	externs -= (blob_no + 1) * BTR_EXTERN_FIELD_REF_SIZE;
	field += len - BTR_EXTERN_FIELD_REF_SIZE;

	memcpy(externs, field, BTR_EXTERN_FIELD_REF_SIZE);

#ifdef UNIV_ZIP_DEBUG
	ut_a(page_zip_validate(page_zip, page, index));
#endif /* UNIV_ZIP_DEBUG */

	if (mtr) {
		byte*	log_ptr	= mlog_open(
			mtr, 11 + 2 + 2 + BTR_EXTERN_FIELD_REF_SIZE);
		if (UNIV_UNLIKELY(!log_ptr)) {
			return;
		}

		log_ptr = mlog_write_initial_log_record_fast(
			(byte*) field, MLOG_ZIP_WRITE_BLOB_PTR, log_ptr, mtr);
		mach_write_to_2(log_ptr, page_offset(field));
		log_ptr += 2;
3948
		mach_write_to_2(log_ptr, ulint(externs - page_zip->data));
3949 3950 3951 3952 3953 3954 3955 3956 3957
		log_ptr += 2;
		memcpy(log_ptr, externs, BTR_EXTERN_FIELD_REF_SIZE);
		log_ptr += BTR_EXTERN_FIELD_REF_SIZE;
		mlog_close(mtr, log_ptr);
	}
}

/***********************************************************//**
Parses a log record of writing the node pointer of a record.
3958
@return end of log record or NULL */
3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969
byte*
page_zip_parse_write_node_ptr(
/*==========================*/
	byte*		ptr,	/*!< in: redo log buffer */
	byte*		end_ptr,/*!< in: redo log buffer end */
	page_t*		page,	/*!< in/out: uncompressed page */
	page_zip_des_t*	page_zip)/*!< in/out: compressed page */
{
	ulint	offset;
	ulint	z_offset;

3970 3971
	ut_ad(ptr != NULL);
	ut_ad(end_ptr!= NULL);
3972 3973 3974 3975 3976 3977 3978 3979 3980 3981
	ut_ad(!page == !page_zip);

	if (UNIV_UNLIKELY(end_ptr < ptr + (2 + 2 + REC_NODE_PTR_SIZE))) {

		return(NULL);
	}

	offset = mach_read_from_2(ptr);
	z_offset = mach_read_from_2(ptr + 2);

3982
	if (offset < PAGE_ZIP_START
3983 3984
	    || offset >= srv_page_size
	    || z_offset >= srv_page_size) {
3985
corrupt:
3986
		recv_sys.found_corrupt_log = TRUE;
3987 3988 3989 3990 3991 3992 3993 3994 3995 3996

		return(NULL);
	}

	if (page) {
		byte*	storage_end;
		byte*	field;
		byte*	storage;
		ulint	heap_no;

3997
		if (!page_zip || page_is_leaf(page)) {
3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010

			goto corrupt;
		}

#ifdef UNIV_ZIP_DEBUG
		ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */

		field = page + offset;
		storage = page_zip->data + z_offset;

		storage_end = page_zip_dir_start(page_zip);

4011
		heap_no = 1 + ulint(storage_end - storage) / REC_NODE_PTR_SIZE;
4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068

		if (UNIV_UNLIKELY((storage_end - storage) % REC_NODE_PTR_SIZE)
		    || UNIV_UNLIKELY(heap_no < PAGE_HEAP_NO_USER_LOW)
		    || UNIV_UNLIKELY(heap_no >= page_dir_get_n_heap(page))) {

			goto corrupt;
		}

		memcpy(field, ptr + 4, REC_NODE_PTR_SIZE);
		memcpy(storage, ptr + 4, REC_NODE_PTR_SIZE);

#ifdef UNIV_ZIP_DEBUG
		ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */
	}

	return(ptr + (2 + 2 + REC_NODE_PTR_SIZE));
}

/**********************************************************************//**
Write the node pointer of a record on a non-leaf compressed page. */
void
page_zip_write_node_ptr(
/*====================*/
	page_zip_des_t*	page_zip,/*!< in/out: compressed page */
	byte*		rec,	/*!< in/out: record */
	ulint		size,	/*!< in: data size of rec */
	ulint		ptr,	/*!< in: node pointer */
	mtr_t*		mtr)	/*!< in: mini-transaction, or NULL */
{
	byte*	field;
	byte*	storage;
#ifdef UNIV_DEBUG
	page_t*	page	= page_align(rec);
#endif /* UNIV_DEBUG */

	ut_ad(page_simple_validate_new(page));
	ut_ad(page_zip_simple_validate(page_zip));
	ut_ad(page_zip_get_size(page_zip)
	      > PAGE_DATA + page_zip_dir_size(page_zip));
	ut_ad(page_rec_is_comp(rec));

	ut_ad(page_zip->m_start >= PAGE_DATA);
	ut_ad(page_zip_header_cmp(page_zip, page));

	ut_ad(!page_is_leaf(page));

	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
	UNIV_MEM_ASSERT_RW(rec, size);

	storage = page_zip_dir_start(page_zip)
		- (rec_get_heap_no_new(rec) - 1) * REC_NODE_PTR_SIZE;
	field = rec + size - REC_NODE_PTR_SIZE;

#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
	ut_a(!memcmp(storage, field, REC_NODE_PTR_SIZE));
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */
4069
	compile_time_assert(REC_NODE_PTR_SIZE == 4);
4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083
	mach_write_to_4(field, ptr);
	memcpy(storage, field, REC_NODE_PTR_SIZE);

	if (mtr) {
		byte*	log_ptr	= mlog_open(mtr,
					    11 + 2 + 2 + REC_NODE_PTR_SIZE);
		if (UNIV_UNLIKELY(!log_ptr)) {
			return;
		}

		log_ptr = mlog_write_initial_log_record_fast(
			field, MLOG_ZIP_WRITE_NODE_PTR, log_ptr, mtr);
		mach_write_to_2(log_ptr, page_offset(field));
		log_ptr += 2;
4084
		mach_write_to_2(log_ptr, ulint(storage - page_zip->data));
4085 4086 4087 4088 4089 4090 4091
		log_ptr += 2;
		memcpy(log_ptr, field, REC_NODE_PTR_SIZE);
		log_ptr += REC_NODE_PTR_SIZE;
		mlog_close(mtr, log_ptr);
	}
}

4092 4093 4094 4095 4096 4097 4098 4099
/** Write the DB_TRX_ID,DB_ROLL_PTR into a clustered index leaf page record.
@param[in,out]	page_zip	compressed page
@param[in,out]	rec		record
@param[in]	offsets		rec_get_offsets(rec, index)
@param[in]	trx_id_field	field number of DB_TRX_ID (number of PK fields)
@param[in]	trx_id		DB_TRX_ID value (transaction identifier)
@param[in]	roll_ptr	DB_ROLL_PTR value (undo log pointer)
@param[in,out]	mtr		mini-transaction, or NULL to skip logging */
4100 4101
void
page_zip_write_trx_id_and_roll_ptr(
4102 4103 4104 4105 4106 4107 4108
	page_zip_des_t*	page_zip,
	byte*		rec,
	const ulint*	offsets,
	ulint		trx_id_col,
	trx_id_t	trx_id,
	roll_ptr_t	roll_ptr,
	mtr_t*		mtr)
4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134
{
	byte*	field;
	byte*	storage;
#ifdef UNIV_DEBUG
	page_t*	page	= page_align(rec);
#endif /* UNIV_DEBUG */
	ulint	len;

	ut_ad(page_simple_validate_new(page));
	ut_ad(page_zip_simple_validate(page_zip));
	ut_ad(page_zip_get_size(page_zip)
	      > PAGE_DATA + page_zip_dir_size(page_zip));
	ut_ad(rec_offs_validate(rec, NULL, offsets));
	ut_ad(rec_offs_comp(offsets));

	ut_ad(page_zip->m_start >= PAGE_DATA);
	ut_ad(page_zip_header_cmp(page_zip, page));

	ut_ad(page_is_leaf(page));

	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));

	storage = page_zip_dir_start(page_zip)
		- (rec_get_heap_no_new(rec) - 1)
		* (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

4135
	compile_time_assert(DATA_TRX_ID + 1 == DATA_ROLL_PTR);
4136 4137 4138 4139 4140 4141 4142 4143
	field = rec_get_nth_field(rec, offsets, trx_id_col, &len);
	ut_ad(len == DATA_TRX_ID_LEN);
	ut_ad(field + DATA_TRX_ID_LEN
	      == rec_get_nth_field(rec, offsets, trx_id_col + 1, &len));
	ut_ad(len == DATA_ROLL_PTR_LEN);
#if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG
	ut_a(!memcmp(storage, field, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN));
#endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */
4144
	compile_time_assert(DATA_TRX_ID_LEN == 6);
4145
	mach_write_to_6(field, trx_id);
4146
	compile_time_assert(DATA_ROLL_PTR_LEN == 7);
4147 4148 4149 4150 4151 4152 4153
	mach_write_to_7(field + DATA_TRX_ID_LEN, roll_ptr);
	memcpy(storage, field, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

	UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
	UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
			   rec_offs_extra_size(offsets));
	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165

	if (mtr) {
		byte*	log_ptr	= mlog_open(
			mtr, 11 + 2 + 2 + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
		if (UNIV_UNLIKELY(!log_ptr)) {
			return;
		}

		log_ptr = mlog_write_initial_log_record_fast(
			(byte*) field, MLOG_ZIP_WRITE_TRX_ID, log_ptr, mtr);
		mach_write_to_2(log_ptr, page_offset(field));
		log_ptr += 2;
4166
		mach_write_to_2(log_ptr, ulint(storage - page_zip->data));
4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197
		log_ptr += 2;
		memcpy(log_ptr, field, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
		log_ptr += DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;
		mlog_close(mtr, log_ptr);
	}
}

/** Parse a MLOG_ZIP_WRITE_TRX_ID record.
@param[in]	ptr		redo log buffer
@param[in]	end_ptr		end of redo log buffer
@param[in,out]	page		uncompressed page
@param[in,out]	page_zip	compressed page
@return end of log record
@retval	NULL	if the log record is incomplete */
byte*
page_zip_parse_write_trx_id(
	byte*		ptr,
	byte*		end_ptr,
	page_t*		page,
	page_zip_des_t*	page_zip)
{
	byte* const end = 2 + 2 + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN + ptr;

	if (UNIV_UNLIKELY(end_ptr < end)) {
		return(NULL);
	}

	uint offset = mach_read_from_2(ptr);
	uint z_offset = mach_read_from_2(ptr + 2);

	if (offset < PAGE_ZIP_START
4198 4199
	    || offset >= srv_page_size
	    || z_offset >= srv_page_size) {
4200
corrupt:
4201
		recv_sys.found_corrupt_log = TRUE;
4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230

		return(NULL);
	}

	if (page) {
		if (!page_zip || !page_is_leaf(page)) {
			goto corrupt;
		}

#ifdef UNIV_ZIP_DEBUG
		ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */

		byte* field = page + offset;
		byte* storage = page_zip->data + z_offset;

		if (storage >= page_zip_dir_start(page_zip)) {
			goto corrupt;
		}

		memcpy(field, ptr + 4, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
		memcpy(storage, ptr + 4, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

#ifdef UNIV_ZIP_DEBUG
		ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */
	}

	return end;
4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269
}

/**********************************************************************//**
Clear an area on the uncompressed and compressed page.
Do not clear the data payload, as that would grow the modification log. */
static
void
page_zip_clear_rec(
/*===============*/
	page_zip_des_t*	page_zip,	/*!< in/out: compressed page */
	byte*		rec,		/*!< in: record to clear */
	const dict_index_t*	index,	/*!< in: index of rec */
	const ulint*	offsets)	/*!< in: rec_get_offsets(rec, index) */
{
	ulint	heap_no;
	page_t*	page	= page_align(rec);
	byte*	storage;
	byte*	field;
	ulint	len;
	/* page_zip_validate() would fail here if a record
	containing externally stored columns is being deleted. */
	ut_ad(rec_offs_validate(rec, index, offsets));
	ut_ad(!page_zip_dir_find(page_zip, page_offset(rec)));
	ut_ad(page_zip_dir_find_free(page_zip, page_offset(rec)));
	ut_ad(page_zip_header_cmp(page_zip, page));

	heap_no = rec_get_heap_no_new(rec);
	ut_ad(heap_no >= PAGE_HEAP_NO_USER_LOW);

	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
	UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
	UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
			   rec_offs_extra_size(offsets));

	if (!page_is_leaf(page)) {
		/* Clear node_ptr. On the compressed page,
		there is an array of node_ptr immediately before the
		dense page directory, at the very end of the page. */
		storage	= page_zip_dir_start(page_zip);
4270
		ut_ad(dict_index_get_n_unique_in_tree_nonleaf(index) ==
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 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 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 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409
		      rec_offs_n_fields(offsets) - 1);
		field	= rec_get_nth_field(rec, offsets,
					    rec_offs_n_fields(offsets) - 1,
					    &len);
		ut_ad(len == REC_NODE_PTR_SIZE);

		ut_ad(!rec_offs_any_extern(offsets));
		memset(field, 0, REC_NODE_PTR_SIZE);
		memset(storage - (heap_no - 1) * REC_NODE_PTR_SIZE,
		       0, REC_NODE_PTR_SIZE);
	} else if (dict_index_is_clust(index)) {
		/* Clear trx_id and roll_ptr. On the compressed page,
		there is an array of these fields immediately before the
		dense page directory, at the very end of the page. */
		const ulint	trx_id_pos
			= dict_col_get_clust_pos(
			dict_table_get_sys_col(
				index->table, DATA_TRX_ID), index);
		storage	= page_zip_dir_start(page_zip);
		field	= rec_get_nth_field(rec, offsets, trx_id_pos, &len);
		ut_ad(len == DATA_TRX_ID_LEN);

		memset(field, 0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
		memset(storage - (heap_no - 1)
		       * (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN),
		       0, DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);

		if (rec_offs_any_extern(offsets)) {
			ulint	i;

			for (i = rec_offs_n_fields(offsets); i--; ) {
				/* Clear all BLOB pointers in order to make
				page_zip_validate() pass. */
				if (rec_offs_nth_extern(offsets, i)) {
					field = rec_get_nth_field(
						rec, offsets, i, &len);
					ut_ad(len
					      == BTR_EXTERN_FIELD_REF_SIZE);
					memset(field + len
					       - BTR_EXTERN_FIELD_REF_SIZE,
					       0, BTR_EXTERN_FIELD_REF_SIZE);
				}
			}
		}
	} else {
		ut_ad(!rec_offs_any_extern(offsets));
	}

#ifdef UNIV_ZIP_DEBUG
	ut_a(page_zip_validate(page_zip, page, index));
#endif /* UNIV_ZIP_DEBUG */
}

/**********************************************************************//**
Write the "deleted" flag of a record on a compressed page.  The flag must
already have been written on the uncompressed page. */
void
page_zip_rec_set_deleted(
/*=====================*/
	page_zip_des_t*	page_zip,/*!< in/out: compressed page */
	const byte*	rec,	/*!< in: record on the uncompressed page */
	ulint		flag)	/*!< in: the deleted flag (nonzero=TRUE) */
{
	byte*	slot = page_zip_dir_find(page_zip, page_offset(rec));
	ut_a(slot);
	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
	if (flag) {
		*slot |= (PAGE_ZIP_DIR_SLOT_DEL >> 8);
	} else {
		*slot &= ~(PAGE_ZIP_DIR_SLOT_DEL >> 8);
	}
#ifdef UNIV_ZIP_DEBUG
	ut_a(page_zip_validate(page_zip, page_align(rec), NULL));
#endif /* UNIV_ZIP_DEBUG */
}

/**********************************************************************//**
Write the "owned" flag of a record on a compressed page.  The n_owned field
must already have been written on the uncompressed page. */
void
page_zip_rec_set_owned(
/*===================*/
	page_zip_des_t*	page_zip,/*!< in/out: compressed page */
	const byte*	rec,	/*!< in: record on the uncompressed page */
	ulint		flag)	/*!< in: the owned flag (nonzero=TRUE) */
{
	byte*	slot = page_zip_dir_find(page_zip, page_offset(rec));
	ut_a(slot);
	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
	if (flag) {
		*slot |= (PAGE_ZIP_DIR_SLOT_OWNED >> 8);
	} else {
		*slot &= ~(PAGE_ZIP_DIR_SLOT_OWNED >> 8);
	}
}

/**********************************************************************//**
Insert a record to the dense page directory. */
void
page_zip_dir_insert(
/*================*/
	page_zip_des_t*	page_zip,/*!< in/out: compressed page */
	const byte*	prev_rec,/*!< in: record after which to insert */
	const byte*	free_rec,/*!< in: record from which rec was
				allocated, or NULL */
	byte*		rec)	/*!< in: record to insert */
{
	ulint	n_dense;
	byte*	slot_rec;
	byte*	slot_free;

	ut_ad(prev_rec != rec);
	ut_ad(page_rec_get_next((rec_t*) prev_rec) == rec);
	ut_ad(page_zip_simple_validate(page_zip));

	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));

	if (page_rec_is_infimum(prev_rec)) {
		/* Use the first slot. */
		slot_rec = page_zip->data + page_zip_get_size(page_zip);
	} else {
		byte*	end	= page_zip->data + page_zip_get_size(page_zip);
		byte*	start	= end - page_zip_dir_user_size(page_zip);

		if (UNIV_LIKELY(!free_rec)) {
			/* PAGE_N_RECS was already incremented
			in page_cur_insert_rec_zip(), but the
			dense directory slot at that position
			contains garbage.  Skip it. */
			start += PAGE_ZIP_DIR_SLOT_SIZE;
		}

		slot_rec = page_zip_dir_find_low(start, end,
						 page_offset(prev_rec));
		ut_a(slot_rec);
	}

	/* Read the old n_dense (n_heap may have been incremented). */
	n_dense = page_dir_get_n_heap(page_zip->data)
4410
		- (PAGE_HEAP_NO_USER_LOW + 1U);
4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436

	if (UNIV_LIKELY_NULL(free_rec)) {
		/* The record was allocated from the free list.
		Shift the dense directory only up to that slot.
		Note that in this case, n_dense is actually
		off by one, because page_cur_insert_rec_zip()
		did not increment n_heap. */
		ut_ad(rec_get_heap_no_new(rec) < n_dense + 1
		      + PAGE_HEAP_NO_USER_LOW);
		ut_ad(rec >= free_rec);
		slot_free = page_zip_dir_find(page_zip, page_offset(free_rec));
		ut_ad(slot_free);
		slot_free += PAGE_ZIP_DIR_SLOT_SIZE;
	} else {
		/* The record was allocated from the heap.
		Shift the entire dense directory. */
		ut_ad(rec_get_heap_no_new(rec) == n_dense
		      + PAGE_HEAP_NO_USER_LOW);

		/* Shift to the end of the dense page directory. */
		slot_free = page_zip->data + page_zip_get_size(page_zip)
			- PAGE_ZIP_DIR_SLOT_SIZE * n_dense;
	}

	/* Shift the dense directory to allocate place for rec. */
	memmove(slot_free - PAGE_ZIP_DIR_SLOT_SIZE, slot_free,
4437
		ulint(slot_rec - slot_free));
4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472

	/* Write the entry for the inserted record.
	The "owned" and "deleted" flags must be zero. */
	mach_write_to_2(slot_rec - PAGE_ZIP_DIR_SLOT_SIZE, page_offset(rec));
}

/**********************************************************************//**
Shift the dense page directory and the array of BLOB pointers
when a record is deleted. */
void
page_zip_dir_delete(
/*================*/
	page_zip_des_t*		page_zip,	/*!< in/out: compressed page */
	byte*			rec,		/*!< in: deleted record */
	const dict_index_t*	index,		/*!< in: index of rec */
	const ulint*		offsets,	/*!< in: rec_get_offsets(rec) */
	const byte*		free)		/*!< in: previous start of
						the free list */
{
	byte*	slot_rec;
	byte*	slot_free;
	ulint	n_ext;
	page_t*	page	= page_align(rec);

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

	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));
	UNIV_MEM_ASSERT_RW(rec, rec_offs_data_size(offsets));
	UNIV_MEM_ASSERT_RW(rec - rec_offs_extra_size(offsets),
			   rec_offs_extra_size(offsets));

	slot_rec = page_zip_dir_find(page_zip, page_offset(rec));

	ut_a(slot_rec);
4473 4474 4475
	uint16_t n_recs = page_get_n_recs(page);
	ut_ad(n_recs);
	ut_ad(n_recs > 1 || page_get_page_no(page) == index->page);
4476 4477
	/* This could not be done before page_zip_dir_find(). */
	page_header_set_field(page, page_zip, PAGE_N_RECS,
4478
			      n_recs - 1);
4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496

	if (UNIV_UNLIKELY(!free)) {
		/* Make the last slot the start of the free list. */
		slot_free = page_zip->data + page_zip_get_size(page_zip)
			- PAGE_ZIP_DIR_SLOT_SIZE
			* (page_dir_get_n_heap(page_zip->data)
			   - PAGE_HEAP_NO_USER_LOW);
	} else {
		slot_free = page_zip_dir_find_free(page_zip,
						   page_offset(free));
		ut_a(slot_free < slot_rec);
		/* Grow the free list by one slot by moving the start. */
		slot_free += PAGE_ZIP_DIR_SLOT_SIZE;
	}

	if (UNIV_LIKELY(slot_rec > slot_free)) {
		memmove(slot_free + PAGE_ZIP_DIR_SLOT_SIZE,
			slot_free,
4497
			ulint(slot_rec - slot_free));
4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509
	}

	/* Write the entry for the deleted record.
	The "owned" and "deleted" flags will be cleared. */
	mach_write_to_2(slot_free, page_offset(rec));

	if (!page_is_leaf(page) || !dict_index_is_clust(index)) {
		ut_ad(!rec_offs_any_extern(offsets));
		goto skip_blobs;
	}

	n_ext = rec_offs_n_extern(offsets);
4510
	if (UNIV_UNLIKELY(n_ext != 0)) {
4511 4512 4513 4514 4515 4516 4517 4518 4519 4520
		/* Shift and zero fill the array of BLOB pointers. */
		ulint	blob_no;
		byte*	externs;
		byte*	ext_end;

		blob_no = page_zip_get_n_prev_extern(page_zip, rec, index);
		ut_a(blob_no + n_ext <= page_zip->n_blobs);

		externs = page_zip->data + page_zip_get_size(page_zip)
			- (page_dir_get_n_heap(page) - PAGE_HEAP_NO_USER_LOW)
4521
			* PAGE_ZIP_CLUST_LEAF_SLOT_SIZE;
4522 4523 4524 4525 4526

		ext_end = externs - page_zip->n_blobs
			* BTR_EXTERN_FIELD_REF_SIZE;
		externs -= blob_no * BTR_EXTERN_FIELD_REF_SIZE;

Sergei Golubchik's avatar
Sergei Golubchik committed
4527
		page_zip->n_blobs -= static_cast<unsigned>(n_ext);
4528 4529
		/* Shift and zero fill the array. */
		memmove(ext_end + n_ext * BTR_EXTERN_FIELD_REF_SIZE, ext_end,
4530
			ulint(page_zip->n_blobs - blob_no)
4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560
			* BTR_EXTERN_FIELD_REF_SIZE);
		memset(ext_end, 0, n_ext * BTR_EXTERN_FIELD_REF_SIZE);
	}

skip_blobs:
	/* The compression algorithm expects info_bits and n_owned
	to be 0 for deleted records. */
	rec[-REC_N_NEW_EXTRA_BYTES] = 0; /* info_bits and n_owned */

	page_zip_clear_rec(page_zip, rec, index, offsets);
}

/**********************************************************************//**
Add a slot to the dense page directory. */
void
page_zip_dir_add_slot(
/*==================*/
	page_zip_des_t*	page_zip,	/*!< in/out: compressed page */
	ulint		is_clustered)	/*!< in: nonzero for clustered index,
					zero for others */
{
	ulint	n_dense;
	byte*	dir;
	byte*	stored;

	ut_ad(page_is_comp(page_zip->data));
	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));

	/* Read the old n_dense (n_heap has already been incremented). */
	n_dense = page_dir_get_n_heap(page_zip->data)
4561
		- (PAGE_HEAP_NO_USER_LOW + 1U);
4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577

	dir = page_zip->data + page_zip_get_size(page_zip)
		- PAGE_ZIP_DIR_SLOT_SIZE * n_dense;

	if (!page_is_leaf(page_zip->data)) {
		ut_ad(!page_zip->n_blobs);
		stored = dir - n_dense * REC_NODE_PTR_SIZE;
	} else if (is_clustered) {
		/* Move the BLOB pointer array backwards to make space for the
		roll_ptr and trx_id columns and the dense directory slot. */
		byte*	externs;

		stored = dir - n_dense
			* (DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN);
		externs = stored
			- page_zip->n_blobs * BTR_EXTERN_FIELD_REF_SIZE;
4578 4579 4580
		ASSERT_ZERO(externs - PAGE_ZIP_CLUST_LEAF_SLOT_SIZE,
			               PAGE_ZIP_CLUST_LEAF_SLOT_SIZE);
		memmove(externs - PAGE_ZIP_CLUST_LEAF_SLOT_SIZE,
4581
			externs, ulint(stored - externs));
4582 4583 4584 4585
	} else {
		stored = dir
			- page_zip->n_blobs * BTR_EXTERN_FIELD_REF_SIZE;
		ASSERT_ZERO(stored - PAGE_ZIP_DIR_SLOT_SIZE,
4586
			    static_cast<size_t>(PAGE_ZIP_DIR_SLOT_SIZE));
4587 4588 4589 4590
	}

	/* Move the uncompressed area backwards to make space
	for one directory slot. */
4591
	memmove(stored - PAGE_ZIP_DIR_SLOT_SIZE, stored, ulint(dir - stored));
4592 4593 4594 4595
}

/***********************************************************//**
Parses a log record of writing to the header of a page.
4596
@return end of log record or NULL */
4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607
byte*
page_zip_parse_write_header(
/*========================*/
	byte*		ptr,	/*!< in: redo log buffer */
	byte*		end_ptr,/*!< in: redo log buffer end */
	page_t*		page,	/*!< in/out: uncompressed page */
	page_zip_des_t*	page_zip)/*!< in/out: compressed page */
{
	ulint	offset;
	ulint	len;

4608 4609
	ut_ad(ptr != NULL);
	ut_ad(end_ptr!= NULL);
4610 4611 4612 4613 4614 4615 4616 4617 4618 4619
	ut_ad(!page == !page_zip);

	if (UNIV_UNLIKELY(end_ptr < ptr + (1 + 1))) {

		return(NULL);
	}

	offset = (ulint) *ptr++;
	len = (ulint) *ptr++;

4620
	if (len == 0 || offset + len >= PAGE_DATA) {
4621
corrupt:
4622
		recv_sys.found_corrupt_log = TRUE;
4623 4624 4625 4626

		return(NULL);
	}

4627
	if (end_ptr < ptr + len) {
4628 4629 4630 4631 4632

		return(NULL);
	}

	if (page) {
4633
		if (!page_zip) {
4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665

			goto corrupt;
		}
#ifdef UNIV_ZIP_DEBUG
		ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */

		memcpy(page + offset, ptr, len);
		memcpy(page_zip->data + offset, ptr, len);

#ifdef UNIV_ZIP_DEBUG
		ut_a(page_zip_validate(page_zip, page, NULL));
#endif /* UNIV_ZIP_DEBUG */
	}

	return(ptr + len);
}

/**********************************************************************//**
Write a log record of writing to the uncompressed header portion of a page. */
void
page_zip_write_header_log(
/*======================*/
	const byte*	data,	/*!< in: data on the uncompressed page */
	ulint		length,	/*!< in: length of the data */
	mtr_t*		mtr)	/*!< in: mini-transaction */
{
	byte*	log_ptr	= mlog_open(mtr, 11 + 1 + 1);
	ulint	offset	= page_offset(data);

	ut_ad(offset < PAGE_DATA);
	ut_ad(offset + length < PAGE_DATA);
4666
	compile_time_assert(PAGE_DATA < 256U);
4667
	ut_ad(length > 0);
4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714
	ut_ad(length < 256);

	/* If no logging is requested, we may return now */
	if (UNIV_UNLIKELY(!log_ptr)) {

		return;
	}

	log_ptr = mlog_write_initial_log_record_fast(
		(byte*) data, MLOG_ZIP_WRITE_HEADER, log_ptr, mtr);
	*log_ptr++ = (byte) offset;
	*log_ptr++ = (byte) length;
	mlog_close(mtr, log_ptr);

	mlog_catenate_string(mtr, data, length);
}

/**********************************************************************//**
Reorganize and compress a page.  This is a low-level operation for
compressed pages, to be used when page_zip_compress() fails.
On success, a redo log entry MLOG_ZIP_PAGE_COMPRESS will be written.
The function btr_page_reorganize() should be preferred whenever possible.
IMPORTANT: if page_zip_reorganize() is invoked on a leaf page of a
non-clustered index, the caller must update the insert buffer free
bits in the same mini-transaction in such a way that the modification
will be redo-logged.
@return TRUE on success, FALSE on failure; page_zip will be left
intact on failure, but page will be overwritten. */
ibool
page_zip_reorganize(
/*================*/
	buf_block_t*	block,	/*!< in/out: page with compressed page;
				on the compressed page, in: size;
				out: data, n_blobs,
				m_start, m_end, m_nonempty */
	dict_index_t*	index,	/*!< in: index of the B-tree node */
	mtr_t*		mtr)	/*!< in: mini-transaction */
{
	buf_pool_t*	buf_pool	= buf_pool_from_block(block);
	page_zip_des_t*	page_zip	= buf_block_get_page_zip(block);
	page_t*		page		= buf_block_get_frame(block);
	buf_block_t*	temp_block;
	page_t*		temp_page;

	ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX));
	ut_ad(page_is_comp(page));
	ut_ad(!dict_index_is_ibuf(index));
4715
	ut_ad(!index->table->is_temporary());
4716
	/* Note that page_zip_validate(page_zip, page, index) may fail here. */
4717
	UNIV_MEM_ASSERT_RW(page, srv_page_size);
4718 4719 4720
	UNIV_MEM_ASSERT_RW(page_zip->data, page_zip_get_size(page_zip));

	/* Disable logging */
4721
	mtr_log_t	log_mode = mtr_set_log_mode(mtr, MTR_LOG_NONE);
4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732

	temp_block = buf_block_alloc(buf_pool);
	btr_search_drop_page_hash_index(block);
	temp_page = temp_block->frame;

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

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

4733
	page_create(block, mtr, TRUE, dict_index_is_spatial(index));
4734 4735 4736 4737 4738 4739 4740 4741

	/* 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);

4742 4743 4744 4745 4746 4747 4748 4749 4750 4751
	/* Copy the PAGE_MAX_TRX_ID or PAGE_ROOT_AUTO_INC. */
	memcpy(page + (PAGE_HEADER + PAGE_MAX_TRX_ID),
	       temp_page + (PAGE_HEADER + PAGE_MAX_TRX_ID), 8);
	/* PAGE_MAX_TRX_ID must be set on secondary index leaf pages. */
	ut_ad(dict_index_is_clust(index) || !page_is_leaf(temp_page)
	      || page_get_max_trx_id(page) != 0);
	/* PAGE_MAX_TRX_ID must be zero on non-leaf pages other than
	clustered index root pages. */
	ut_ad(page_get_max_trx_id(page) == 0
	      || (dict_index_is_clust(index)
4752
		  ? !page_has_siblings(temp_page)
4753
		  : page_is_leaf(temp_page)));
4754 4755 4756 4757

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

4758
	if (!page_zip_compress(page_zip, page, index, page_zip_level, mtr)) {
4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785
		buf_block_free(temp_block);
		return(FALSE);
	}

	lock_move_reorganize_page(block, temp_block);

	buf_block_free(temp_block);
	return(TRUE);
}

/**********************************************************************//**
Copy the records of a page byte for byte.  Do not copy the page header
or trailer, except those B-tree header fields that are directly
related to the storage of records.  Also copy PAGE_MAX_TRX_ID.
NOTE: The caller must update the lock table and the adaptive hash index. */
void
page_zip_copy_recs(
/*===============*/
	page_zip_des_t*		page_zip,	/*!< out: copy of src_zip
						(n_blobs, m_start, m_end,
						m_nonempty, data[0..size-1]) */
	page_t*			page,		/*!< out: copy of src */
	const page_zip_des_t*	src_zip,	/*!< in: compressed page */
	const page_t*		src,		/*!< in: page */
	dict_index_t*		index,		/*!< in: index of the B-tree */
	mtr_t*			mtr)		/*!< in: mini-transaction */
{
4786 4787
	ut_ad(mtr_memo_contains_page(mtr, page, MTR_MEMO_PAGE_X_FIX));
	ut_ad(mtr_memo_contains_page(mtr, src, MTR_MEMO_PAGE_X_FIX));
4788
	ut_ad(!dict_index_is_ibuf(index));
4789
	ut_ad(!index->table->is_temporary());
4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802
#ifdef UNIV_ZIP_DEBUG
	/* The B-tree operations that call this function may set
	FIL_PAGE_PREV or PAGE_LEVEL, causing a temporary min_rec_flag
	mismatch.  A strict page_zip_validate() will be executed later
	during the B-tree operations. */
	ut_a(page_zip_validate_low(src_zip, src, index, TRUE));
#endif /* UNIV_ZIP_DEBUG */
	ut_a(page_zip_get_size(page_zip) == page_zip_get_size(src_zip));
	if (UNIV_UNLIKELY(src_zip->n_blobs)) {
		ut_a(page_is_leaf(src));
		ut_a(dict_index_is_clust(index));
	}

4803
	UNIV_MEM_ASSERT_W(page, srv_page_size);
4804
	UNIV_MEM_ASSERT_W(page_zip->data, page_zip_get_size(page_zip));
4805
	UNIV_MEM_ASSERT_RW(src, srv_page_size);
4806 4807 4808 4809 4810 4811
	UNIV_MEM_ASSERT_RW(src_zip->data, page_zip_get_size(page_zip));

	/* Copy those B-tree page header fields that are related to
	the records stored in the page.  Also copy the field
	PAGE_MAX_TRX_ID.  Skip the rest of the page header and
	trailer.  On the compressed page, there is no trailer. */
4812
	compile_time_assert(PAGE_MAX_TRX_ID + 8 == PAGE_HEADER_PRIV_END);
4813 4814 4815
	memcpy(PAGE_HEADER + page, PAGE_HEADER + src,
	       PAGE_HEADER_PRIV_END);
	memcpy(PAGE_DATA + page, PAGE_DATA + src,
4816
	       srv_page_size - PAGE_DATA - FIL_PAGE_DATA_END);
4817 4818 4819 4820 4821
	memcpy(PAGE_HEADER + page_zip->data, PAGE_HEADER + src_zip->data,
	       PAGE_HEADER_PRIV_END);
	memcpy(PAGE_DATA + page_zip->data, PAGE_DATA + src_zip->data,
	       page_zip_get_size(page_zip) - PAGE_DATA);

4822 4823 4824 4825 4826 4827 4828 4829 4830
	if (dict_index_is_clust(index)) {
		/* Reset the PAGE_ROOT_AUTO_INC field when copying
		from a root page. */
		memset(PAGE_HEADER + PAGE_ROOT_AUTO_INC + page, 0, 8);
		memset(PAGE_HEADER + PAGE_ROOT_AUTO_INC + page_zip->data,
		       0, 8);
	} else {
		/* The PAGE_MAX_TRX_ID must be nonzero on leaf pages
		of secondary indexes, and 0 on others. */
4831
		ut_ad(!page_is_leaf(src) == !page_get_max_trx_id(src));
4832 4833
	}

4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844
	/* Copy all fields of src_zip to page_zip, except the pointer
	to the compressed data page. */
	{
		page_zip_t*	data = page_zip->data;
		memcpy(page_zip, src_zip, sizeof *page_zip);
		page_zip->data = data;
	}
	ut_ad(page_zip_get_trailer_len(page_zip, dict_index_is_clust(index))
	      + page_zip->m_end < page_zip_get_size(page_zip));

	if (!page_is_leaf(src)
4845 4846
	    && UNIV_UNLIKELY(!page_has_prev(src))
	    && UNIV_LIKELY(page_has_prev(page))) {
4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863
		/* Clear the REC_INFO_MIN_REC_FLAG of the first user record. */
		ulint	offs = rec_get_next_offs(page + PAGE_NEW_INFIMUM,
						 TRUE);
		if (UNIV_LIKELY(offs != PAGE_NEW_SUPREMUM)) {
			rec_t*	rec = page + offs;
			ut_a(rec[-REC_N_NEW_EXTRA_BYTES]
			     & REC_INFO_MIN_REC_FLAG);
			rec[-REC_N_NEW_EXTRA_BYTES] &= ~ REC_INFO_MIN_REC_FLAG;
		}
	}

#ifdef UNIV_ZIP_DEBUG
	ut_a(page_zip_validate(page_zip, page, index));
#endif /* UNIV_ZIP_DEBUG */
	page_zip_compress_write_log(page_zip, page, index, mtr);
}

4864 4865 4866 4867 4868 4869 4870 4871
/** Parse and optionally apply MLOG_ZIP_PAGE_COMPRESS.
@param[in]	ptr	log record
@param[in]	end_ptr	end of log
@param[in,out]	block	ROW_FORMAT=COMPRESSED block, or NULL for parsing only
@return	end of log record
@retval	NULL	if the log record is incomplete */
byte* page_zip_parse_compress(const byte* ptr, const byte* end_ptr,
			      buf_block_t* block)
4872 4873 4874 4875
{
	ulint	size;
	ulint	trailer_size;

Sergei Golubchik's avatar
Sergei Golubchik committed
4876
	ut_ad(ptr != NULL);
4877
	ut_ad(end_ptr!= NULL);
4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893

	if (UNIV_UNLIKELY(ptr + (2 + 2) > end_ptr)) {

		return(NULL);
	}

	size = mach_read_from_2(ptr);
	ptr += 2;
	trailer_size = mach_read_from_2(ptr);
	ptr += 2;

	if (UNIV_UNLIKELY(ptr + 8 + size + trailer_size > end_ptr)) {

		return(NULL);
	}

4894 4895 4896 4897 4898
	if (block) {
		ut_ad(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
		page_zip_des_t* page_zip = buf_block_get_page_zip(block);
		if (!page_zip || page_zip_get_size(page_zip) < size
		    || block->page.id.page_no() < 3) {
4899
corrupt:
4900
			recv_sys.found_corrupt_log = TRUE;
4901 4902 4903 4904

			return(NULL);
		}

4905 4906 4907 4908 4909
		memset(page_zip->data, 0, page_zip_get_size(page_zip));
		mach_write_to_4(FIL_PAGE_OFFSET
				+ page_zip->data, block->page.id.page_no());
		mach_write_to_4(FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID
				+ page_zip->data, block->page.id.space());
4910 4911 4912 4913 4914 4915 4916 4917 4918
		memcpy(page_zip->data + FIL_PAGE_PREV, ptr, 4);
		memcpy(page_zip->data + FIL_PAGE_NEXT, ptr + 4, 4);
		memcpy(page_zip->data + FIL_PAGE_TYPE, ptr + 8, size);
		memset(page_zip->data + FIL_PAGE_TYPE + size, 0,
		       page_zip_get_size(page_zip) - trailer_size
		       - (FIL_PAGE_TYPE + size));
		memcpy(page_zip->data + page_zip_get_size(page_zip)
		       - trailer_size, ptr + 8 + size, trailer_size);

4919
		if (UNIV_UNLIKELY(!page_zip_decompress(page_zip, block->frame,
4920 4921 4922 4923 4924 4925
						       TRUE))) {

			goto corrupt;
		}
	}

4926
	return(const_cast<byte*>(ptr) + 8 + size + trailer_size);
4927
}
4928
#endif /* !UNIV_INNOCHECKSUM */
4929

4930 4931 4932 4933 4934 4935
/** Calculate the compressed page checksum.
@param[in]	data			compressed page
@param[in]	size			size of compressed page
@param[in]	algo			algorithm to use
@return page checksum */
uint32_t
4936
page_zip_calc_checksum(
4937 4938
	const void*			data,
	ulint				size,
4939
	srv_checksum_algorithm_t	algo)
4940
{
4941
	uLong		adler;
4942 4943 4944 4945 4946 4947
	const Bytef*	s = static_cast<const byte*>(data);

	/* Exclude FIL_PAGE_SPACE_OR_CHKSUM, FIL_PAGE_LSN,
	and FIL_PAGE_FILE_FLUSH_LSN from the checksum. */

	switch (algo) {
4948 4949
	case SRV_CHECKSUM_ALGORITHM_FULL_CRC32:
	case SRV_CHECKSUM_ALGORITHM_STRICT_FULL_CRC32:
4950 4951
	case SRV_CHECKSUM_ALGORITHM_CRC32:
	case SRV_CHECKSUM_ALGORITHM_STRICT_CRC32:
4952 4953 4954 4955 4956 4957
		ut_ad(size > FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
		return ut_crc32(s + FIL_PAGE_OFFSET,
				FIL_PAGE_LSN - FIL_PAGE_OFFSET)
			^ ut_crc32(s + FIL_PAGE_TYPE, 2)
			^ ut_crc32(s + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID,
				   size - FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
4958 4959 4960 4961 4962 4963 4964
	case SRV_CHECKSUM_ALGORITHM_INNODB:
	case SRV_CHECKSUM_ALGORITHM_STRICT_INNODB:
		ut_ad(size > FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);

		adler = adler32(0L, s + FIL_PAGE_OFFSET,
				FIL_PAGE_LSN - FIL_PAGE_OFFSET);
		adler = adler32(adler, s + FIL_PAGE_TYPE, 2);
Sergei Golubchik's avatar
Sergei Golubchik committed
4965 4966 4967 4968
		adler = adler32(
			adler, s + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID,
			static_cast<uInt>(size)
			- FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID);
4969

4970
		return(uint32_t(adler));
4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981
	case SRV_CHECKSUM_ALGORITHM_NONE:
	case SRV_CHECKSUM_ALGORITHM_STRICT_NONE:
		return(BUF_NO_CHECKSUM_MAGIC);
	/* no default so the compiler will emit a warning if new enum
	is added and not handled here */
	}

	ut_error;
	return(0);
}

4982 4983 4984 4985
/** Verify a compressed page's checksum.
@param[in]	data		compressed page
@param[in]	size		size of compressed page
@return whether the stored checksum is valid according to the value of
4986
innodb_checksum_algorithm */
4987
bool page_zip_verify_checksum(const void* data, ulint size)
4988
{
4989 4990
	const uint32_t stored = mach_read_from_4(
		static_cast<const byte*>(data) + FIL_PAGE_SPACE_OR_CHKSUM);
4991

4992
	compile_time_assert(!(FIL_PAGE_LSN % 8));
Sergei Golubchik's avatar
Sergei Golubchik committed
4993 4994 4995 4996 4997 4998

	/* Check if page is empty */
	if (stored == 0
	    && *reinterpret_cast<const ib_uint64_t*>(static_cast<const char*>(
		data)
		+ FIL_PAGE_LSN) == 0) {
4999
		/* make sure that the page is really empty */
5000
#ifdef UNIV_INNOCHECKSUM
Sergei Golubchik's avatar
Sergei Golubchik committed
5001 5002
		ulint i;
		for (i = 0; i < size; i++) {
5003 5004 5005 5006
			if (*((const char*) data + i) != 0)
				break;
		}
		if (i >= size) {
5007
			if (log_file) {
5008
			fprintf(log_file, "Page::%llu is empty and"
5009
					" uncorrupted\n", cur_page_num);
5010 5011 5012 5013 5014 5015
			}

			return(TRUE);
		}
#else
		for (ulint i = 0; i < size; i++) {
Sergei Golubchik's avatar
Sergei Golubchik committed
5016 5017 5018 5019
			if (*((const char*) data + i) != 0) {
				return(FALSE);
			}
		}
Sergei Golubchik's avatar
Sergei Golubchik committed
5020
		/* Empty page */
5021
		return(TRUE);
5022
#endif /* UNIV_INNOCHECKSUM */
5023 5024
	}

Sergei Golubchik's avatar
Sergei Golubchik committed
5025 5026 5027 5028 5029 5030 5031
	const srv_checksum_algorithm_t	curr_algo =
		static_cast<srv_checksum_algorithm_t>(srv_checksum_algorithm);

	if (curr_algo == SRV_CHECKSUM_ALGORITHM_NONE) {
		return(TRUE);
	}

5032
	uint32_t calc = page_zip_calc_checksum(data, size, curr_algo);
5033 5034

#ifdef UNIV_INNOCHECKSUM
5035
	if (log_file) {
5036
		fprintf(log_file, "page::%llu;"
5037
			" %s checksum: calculated = %u;"
5038
			" recorded = %u\n", cur_page_num,
5039 5040 5041 5042 5043 5044
			buf_checksum_algorithm_name(
				static_cast<srv_checksum_algorithm_t>(
				srv_checksum_algorithm)),
			calc, stored);
	}

5045
	if (!strict_verify) {
5046 5047 5048 5049

		const uint32_t	crc32 = page_zip_calc_checksum(
			data, size, SRV_CHECKSUM_ALGORITHM_CRC32);

5050
		if (log_file) {
5051
			fprintf(log_file, "page::%llu: crc32 checksum:"
5052
				" calculated = %u; recorded = %u\n",
5053
				cur_page_num, crc32, stored);
5054
			fprintf(log_file, "page::%llu: none checksum:"
5055
				" calculated = %lu; recorded = %u\n",
5056
				cur_page_num, BUF_NO_CHECKSUM_MAGIC, stored);
5057 5058 5059
		}
	}
#endif /* UNIV_INNOCHECKSUM */
5060

5061
	if (stored == calc) {
5062 5063 5064
		return(TRUE);
	}

Sergei Golubchik's avatar
Sergei Golubchik committed
5065
	switch (curr_algo) {
5066
	case SRV_CHECKSUM_ALGORITHM_STRICT_FULL_CRC32:
5067
	case SRV_CHECKSUM_ALGORITHM_STRICT_CRC32:
Sergei Golubchik's avatar
Sergei Golubchik committed
5068
	case SRV_CHECKSUM_ALGORITHM_STRICT_INNODB:
5069
	case SRV_CHECKSUM_ALGORITHM_STRICT_NONE:
Marko Mäkelä's avatar
Marko Mäkelä committed
5070
		return FALSE;
5071
	case SRV_CHECKSUM_ALGORITHM_FULL_CRC32:
5072
	case SRV_CHECKSUM_ALGORITHM_CRC32:
5073
		if (stored == BUF_NO_CHECKSUM_MAGIC) {
Sergei Golubchik's avatar
Sergei Golubchik committed
5074 5075 5076
			return(TRUE);
		}

5077 5078
		return stored == page_zip_calc_checksum(
			data, size, SRV_CHECKSUM_ALGORITHM_INNODB);
5079 5080
	case SRV_CHECKSUM_ALGORITHM_INNODB:
		if (stored == BUF_NO_CHECKSUM_MAGIC) {
5081
			return TRUE;
Sergei Golubchik's avatar
Sergei Golubchik committed
5082 5083
		}

5084
		return stored == page_zip_calc_checksum(
5085
			data, size, SRV_CHECKSUM_ALGORITHM_CRC32);
5086
	case SRV_CHECKSUM_ALGORITHM_NONE:
5087
		return TRUE;
5088 5089
	}

5090
	return FALSE;
5091
}