btr0cur.c 101 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/******************************************************
The index tree cursor

All changes that row operations make to a B-tree or the records
there must go through this module! Undo log records are written here
of every modify or insert of a clustered index record.

			NOTE!!!
To make sure we do not run out of disk space during a pessimistic
insert or update, we have to reserve 2 x the height of the index tree
many pages in the tablespace before we start the operation, because
if leaf splitting has been started, it is difficult to undo, except
by crashing the database and doing a roll-forward.

15
(c) 1994-2001 Innobase Oy
16 17 18 19 20 21 22 23 24 25 26 27

Created 10/16/1994 Heikki Tuuri
*******************************************************/

#include "btr0cur.h"

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

#include "page0page.h"
#include "rem0rec.h"
28
#include "rem0cmp.h"
29 30 31 32 33 34 35 36 37 38
#include "btr0btr.h"
#include "btr0sea.h"
#include "row0upd.h"
#include "trx0rec.h"
#include "que0que.h"
#include "row0row.h"
#include "srv0srv.h"
#include "ibuf0ibuf.h"
#include "lock0lock.h"

unknown's avatar
unknown committed
39
#ifdef UNIV_DEBUG
unknown's avatar
unknown committed
40 41 42
/* If the following is set to TRUE, this module prints a lot of
trace information of individual record operations */
ibool	btr_cur_print_record_ops = FALSE;
unknown's avatar
unknown committed
43
#endif /* UNIV_DEBUG */
44 45

ulint	btr_cur_n_non_sea	= 0;
unknown's avatar
unknown committed
46
ulint	btr_cur_n_sea		= 0;
unknown's avatar
unknown committed
47 48
ulint	btr_cur_n_non_sea_old	= 0;
ulint	btr_cur_n_sea_old	= 0;
49 50 51 52 53 54

/* In the optimistic insert, if the insert does not fit, but this much space
can be released by page reorganize, then it is reorganized */

#define BTR_CUR_PAGE_REORGANIZE_LIMIT	(UNIV_PAGE_SIZE / 32)

55
/* When estimating number of different key values in an index, sample
56 57 58
this many index pages */
#define BTR_KEY_VAL_ESTIMATE_N_PAGES	8

59 60 61 62 63 64 65 66 67
/* The structure of a BLOB part header */
/*--------------------------------------*/
#define BTR_BLOB_HDR_PART_LEN		0	/* BLOB part len on this
						page */
#define BTR_BLOB_HDR_NEXT_PAGE_NO	4	/* next BLOB part page no,
						FIL_NULL if none */
/*--------------------------------------*/
#define BTR_BLOB_HDR_SIZE		8

68 69 70 71 72 73 74 75
/***********************************************************************
Marks all extern fields in a record as owned by the record. This function
should be called if the delete mark of a record is removed: a not delete
marked record always owns all its extern fields. */
static
void
btr_cur_unmark_extern_fields(
/*=========================*/
unknown's avatar
unknown committed
76 77 78
	rec_t*		rec,	/* in: record in a clustered index */
	mtr_t*		mtr,	/* in: mtr */
	const ulint*	offsets);/* in: array returned by rec_get_offsets() */
79 80 81 82 83 84 85 86 87 88 89
/***********************************************************************
Adds path information to the cursor for the current page, for which
the binary search has been performed. */
static
void
btr_cur_add_path_info(
/*==================*/
	btr_cur_t*	cursor,		/* in: cursor positioned on a page */
	ulint		height,		/* in: height of the page in tree;
					0 means leaf node */
	ulint		root_height);	/* in: root node height in tree */
90 91 92 93 94 95 96 97 98 99
/***************************************************************
Frees the externally stored fields for a record, if the field is mentioned
in the update vector. */
static
void
btr_rec_free_updated_extern_fields(
/*===============================*/
	dict_index_t*	index,	/* in: index of rec; the index tree MUST be
				X-latched */
	rec_t*		rec,	/* in: record */
unknown's avatar
unknown committed
100
	const ulint*	offsets,/* in: rec_get_offsets(rec, index) */
101
	upd_t*		update,	/* in: update vector */
102 103 104
	ibool		do_not_free_inherited,/* in: TRUE if called in a
				rollback and we do not want to free
				inherited fields */
105 106
	mtr_t*		mtr);	/* in: mini-transaction handle which contains
				an X-latch to record page and to the tree */
unknown's avatar
unknown committed
107 108 109 110 111 112
/***************************************************************
Gets the externally stored size of a record, in units of a database page. */
static
ulint
btr_rec_get_externally_stored_len(
/*==============================*/
unknown's avatar
unknown committed
113 114 115 116
				/* out: externally stored part,
				in units of a database page */
	rec_t*		rec,	/* in: record */
	const ulint*	offsets);/* in: array returned by rec_get_offsets() */
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

/*==================== B-TREE SEARCH =========================*/
	
/************************************************************************
Latches the leaf page or pages requested. */
static
void
btr_cur_latch_leaves(
/*=================*/
	page_t*		page,		/* in: leaf page where the search
					converged */
	ulint		space,		/* in: space id */
	ulint		page_no,	/* in: page number of the leaf */
	ulint		latch_mode,	/* in: BTR_SEARCH_LEAF, ... */
	btr_cur_t*	cursor, 	/* in: cursor */
	mtr_t*		mtr)		/* in: mtr */
{
	ulint	left_page_no;
	ulint	right_page_no;
unknown's avatar
unknown committed
136 137
	page_t*	get_page;
	
138
	ut_ad(page && mtr);
139 140 141

	if (latch_mode == BTR_SEARCH_LEAF) {
	
unknown's avatar
unknown committed
142
		get_page = btr_page_get(space, page_no, RW_S_LATCH, mtr);
unknown's avatar
unknown committed
143
		ut_a(page_is_comp(get_page) == page_is_comp(page));
unknown's avatar
unknown committed
144
		buf_block_align(get_page)->check_index_page_at_flush = TRUE;
145 146 147

	} else if (latch_mode == BTR_MODIFY_LEAF) {

unknown's avatar
unknown committed
148
		get_page = btr_page_get(space, page_no, RW_X_LATCH, mtr);
unknown's avatar
unknown committed
149
		ut_a(page_is_comp(get_page) == page_is_comp(page));
unknown's avatar
unknown committed
150
		buf_block_align(get_page)->check_index_page_at_flush = TRUE;
151 152 153 154 155 156 157

	} else if (latch_mode == BTR_MODIFY_TREE) {

		/* x-latch also brothers from left to right */
		left_page_no = btr_page_get_prev(page, mtr);

		if (left_page_no != FIL_NULL) {
unknown's avatar
unknown committed
158 159
			get_page = btr_page_get(space, left_page_no,
							RW_X_LATCH, mtr);
unknown's avatar
unknown committed
160
			ut_a(page_is_comp(get_page) == page_is_comp(page));
unknown's avatar
unknown committed
161 162
			buf_block_align(get_page)->check_index_page_at_flush =
									TRUE;
163 164
		}
				
unknown's avatar
unknown committed
165
		get_page = btr_page_get(space, page_no, RW_X_LATCH, mtr);
unknown's avatar
unknown committed
166
		ut_a(page_is_comp(get_page) == page_is_comp(page));
unknown's avatar
unknown committed
167
		buf_block_align(get_page)->check_index_page_at_flush = TRUE;
168 169 170 171

		right_page_no = btr_page_get_next(page, mtr);

		if (right_page_no != FIL_NULL) {
unknown's avatar
unknown committed
172 173 174 175
			get_page = btr_page_get(space, right_page_no,
							RW_X_LATCH, mtr);
			buf_block_align(get_page)->check_index_page_at_flush =
									TRUE;
176 177 178 179 180 181 182 183 184 185
		}

	} else if (latch_mode == BTR_SEARCH_PREV) {

		/* s-latch also left brother */
		left_page_no = btr_page_get_prev(page, mtr);

		if (left_page_no != FIL_NULL) {
			cursor->left_page = btr_page_get(space, left_page_no,
							RW_S_LATCH, mtr);
unknown's avatar
unknown committed
186 187
			ut_a(page_is_comp(cursor->left_page) ==
					page_is_comp(page));
unknown's avatar
unknown committed
188 189
			buf_block_align(
			cursor->left_page)->check_index_page_at_flush = TRUE;
190 191
		}

unknown's avatar
unknown committed
192
		get_page = btr_page_get(space, page_no, RW_S_LATCH, mtr);
unknown's avatar
unknown committed
193
		ut_a(page_is_comp(get_page) == page_is_comp(page));
unknown's avatar
unknown committed
194
		buf_block_align(get_page)->check_index_page_at_flush = TRUE;
195 196 197 198 199 200 201 202 203

	} else if (latch_mode == BTR_MODIFY_PREV) {

		/* x-latch also left brother */
		left_page_no = btr_page_get_prev(page, mtr);

		if (left_page_no != FIL_NULL) {
			cursor->left_page = btr_page_get(space, left_page_no,
							RW_X_LATCH, mtr);
unknown's avatar
unknown committed
204 205
			ut_a(page_is_comp(cursor->left_page) ==
					page_is_comp(page));
unknown's avatar
unknown committed
206 207
			buf_block_align(
			cursor->left_page)->check_index_page_at_flush = TRUE;
208 209
		}

unknown's avatar
unknown committed
210
		get_page = btr_page_get(space, page_no, RW_X_LATCH, mtr);
unknown's avatar
unknown committed
211
		ut_a(page_is_comp(get_page) == page_is_comp(page));
unknown's avatar
unknown committed
212
		buf_block_align(get_page)->check_index_page_at_flush = TRUE;
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
	} else {
		ut_error;
	}
}

/************************************************************************
Searches an index tree and positions a tree cursor on a given level.
NOTE: n_fields_cmp in tuple must be set so that it cannot be compared
to node pointer page number fields on the upper levels of the tree!
Note that if mode is PAGE_CUR_LE, which is used in inserts, then
cursor->up_match and cursor->low_match both will have sensible values.
If mode is PAGE_CUR_GE, then up_match will a have a sensible value. */

void
btr_cur_search_to_nth_level(
/*========================*/
	dict_index_t*	index,	/* in: index */
	ulint		level,	/* in: the tree level of search */
	dtuple_t*	tuple,	/* in: data tuple; NOTE: n_fields_cmp in
				tuple must be set so that it cannot get
				compared to the node ptr page number field! */
	ulint		mode,	/* in: PAGE_CUR_L, ...;
unknown's avatar
unknown committed
235
				Inserts should always be made using
236 237 238 239 240
				PAGE_CUR_LE to search the position! */
	ulint		latch_mode, /* in: BTR_SEARCH_LEAF, ..., ORed with
				BTR_INSERT and BTR_ESTIMATE;
				cursor->left_page is used to store a pointer
				to the left neighbor page, in the cases
unknown's avatar
unknown committed
241 242 243 244 245 246
				BTR_SEARCH_PREV and BTR_MODIFY_PREV;
				NOTE that if has_search_latch
				is != 0, we maybe do not have a latch set
				on the cursor page, we assume
				the caller uses his search latch
				to protect the record! */
247
	btr_cur_t*	cursor, /* in/out: tree cursor; the cursor page is
unknown's avatar
unknown committed
248
				s- or x-latched, but see also above! */
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
	ulint		has_search_latch,/* in: info on the latch mode the
				caller currently has on btr_search_latch:
				RW_S_LATCH, or 0 */
	mtr_t*		mtr)	/* in: mtr */
{
	dict_tree_t*	tree;
	page_cur_t*	page_cursor;
	page_t*		page;
	page_t*		guess;
	rec_t*		node_ptr;
	ulint		page_no;
	ulint		space;
	ulint		up_match;
	ulint		up_bytes;
	ulint		low_match;
	ulint 		low_bytes;
	ulint		height;
	ulint		savepoint;
	ulint		rw_latch;
	ulint		page_mode;
	ulint		insert_planned;
	ulint		buf_mode;
	ulint		estimate;
unknown's avatar
unknown committed
272
	ulint		ignore_sec_unique;
unknown's avatar
unknown committed
273
	ulint		root_height = 0; /* remove warning */
274 275 276
#ifdef BTR_CUR_ADAPT
	btr_search_t*	info;
#endif
277
	mem_heap_t*	heap		= NULL;
278
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
279
	ulint*		offsets		= offsets_;
280
	*offsets_ = (sizeof offsets_) / sizeof *offsets_;
281 282 283 284 285 286 287 288 289 290 291 292 293 294
	/* Currently, PAGE_CUR_LE is the only search mode used for searches
	ending to upper levels */

	ut_ad(level == 0 || mode == PAGE_CUR_LE);
	ut_ad(dict_tree_check_search_tuple(index->tree, tuple));
	ut_ad(!(index->type & DICT_IBUF) || ibuf_inside());
	ut_ad(dtuple_check_typed(tuple));

#ifdef UNIV_DEBUG
	cursor->up_match = ULINT_UNDEFINED;
	cursor->low_match = ULINT_UNDEFINED;
#endif	
	insert_planned = latch_mode & BTR_INSERT;
	estimate = latch_mode & BTR_ESTIMATE;
unknown's avatar
unknown committed
295 296 297
	ignore_sec_unique = latch_mode & BTR_IGNORE_SEC_UNIQUE;
	latch_mode = latch_mode & ~(BTR_INSERT | BTR_ESTIMATE
					| BTR_IGNORE_SEC_UNIQUE);
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315

	ut_ad(!insert_planned || (mode == PAGE_CUR_LE));
	
	cursor->flag = BTR_CUR_BINARY;
	cursor->index = index;

#ifndef BTR_CUR_ADAPT
	guess = NULL;
#else
	info = btr_search_get_info(index);

	guess = info->root_guess;

#ifdef BTR_CUR_HASH_ADAPT

#ifdef UNIV_SEARCH_PERF_STAT
	info->n_searches++;
#endif	
unknown's avatar
unknown committed
316
	if (btr_search_latch.writer == RW_LOCK_NOT_LOCKED
317
		&& latch_mode <= BTR_MODIFY_LEAF && info->last_hash_succ
318
		&& !estimate
319
#ifdef PAGE_CUR_LE_OR_EXTENDS
unknown's avatar
unknown committed
320
		&& mode != PAGE_CUR_LE_OR_EXTENDS
321
#endif /* PAGE_CUR_LE_OR_EXTENDS */
unknown's avatar
unknown committed
322
		&& srv_use_adaptive_hash_indexes
323 324 325 326 327 328 329 330 331 332 333 334
	        && btr_search_guess_on_hash(index, info, tuple, mode,
						latch_mode, cursor,
						has_search_latch, mtr)) {

		/* Search using the hash index succeeded */

		ut_ad(cursor->up_match != ULINT_UNDEFINED
					|| mode != PAGE_CUR_GE);
		ut_ad(cursor->up_match != ULINT_UNDEFINED
					|| mode != PAGE_CUR_LE);
		ut_ad(cursor->low_match != ULINT_UNDEFINED
					|| mode != PAGE_CUR_LE);
unknown's avatar
unknown committed
335 336
		btr_cur_n_sea++;

337 338 339 340 341
	        return;
	}
#endif
#endif
	btr_cur_n_non_sea++;
unknown's avatar
unknown committed
342

343 344 345 346 347 348 349 350
	/* If the hash search did not succeed, do binary search down the
	tree */

	if (has_search_latch) {
		/* Release possible search latch to obey latching order */
		rw_lock_s_unlock(&btr_search_latch);
	}

unknown's avatar
unknown committed
351 352 353
	/* Store the position of the tree latch we push to mtr so that we
	know how to release it when we have latched leaf node(s) */

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
	savepoint = mtr_set_savepoint(mtr);

	tree = index->tree;
	
	if (latch_mode == BTR_MODIFY_TREE) {
		mtr_x_lock(dict_tree_get_lock(tree), mtr);

	} else if (latch_mode == BTR_CONT_MODIFY_TREE) {
		/* Do nothing */
		ut_ad(mtr_memo_contains(mtr, dict_tree_get_lock(tree),
							MTR_MEMO_X_LOCK));
	} else {
		mtr_s_lock(dict_tree_get_lock(tree), mtr);
	}
	
	page_cursor = btr_cur_get_page_cur(cursor);

	space = dict_tree_get_space(tree);
	page_no = dict_tree_get_page(tree);

	up_match = 0;
	up_bytes = 0;
	low_match = 0;
	low_bytes = 0;

	height = ULINT_UNDEFINED;
	rw_latch = RW_NO_LATCH;
	buf_mode = BUF_GET;

unknown's avatar
unknown committed
383 384 385 386
	/* We use these modified search modes on non-leaf levels of the
	B-tree. These let us end up in the right B-tree leaf. In that leaf
	we use the original search mode. */

387 388
	switch (mode) {
	case PAGE_CUR_GE:
389
		page_mode = PAGE_CUR_L;
390 391
		break;
	case PAGE_CUR_G:
392
		page_mode = PAGE_CUR_LE;
393 394
		break;
	default:
395
#ifdef PAGE_CUR_LE_OR_EXTENDS
396 397 398 399
		ut_ad(mode == PAGE_CUR_L || mode == PAGE_CUR_LE
			|| mode == PAGE_CUR_LE_OR_EXTENDS);
#else /* PAGE_CUR_LE_OR_EXTENDS */
		ut_ad(mode == PAGE_CUR_L || mode == PAGE_CUR_LE);
400
#endif /* PAGE_CUR_LE_OR_EXTENDS */
401 402
		page_mode = mode;
		break;
403
	}
unknown's avatar
unknown committed
404

405 406 407 408 409 410 411
	/* Loop and search until we arrive at the desired level */

	for (;;) {
		if ((height == 0) && (latch_mode <= BTR_MODIFY_LEAF)) {

			rw_latch = latch_mode;

unknown's avatar
unknown committed
412 413
			if (insert_planned && ibuf_should_try(index,
							ignore_sec_unique)) {
414 415 416 417 418 419 420 421 422 423
				
				/* Try insert to the insert buffer if the
				page is not in the buffer pool */

				buf_mode = BUF_GET_IF_IN_POOL;
			}
		}
retry_page_get:		
		page = buf_page_get_gen(space, page_no, rw_latch, guess,
					buf_mode,
424
					__FILE__, __LINE__,
425 426 427 428 429 430 431 432 433
					mtr);
		if (page == NULL) {
			/* This must be a search to perform an insert;
			try insert to the insert buffer */

			ut_ad(buf_mode == BUF_GET_IF_IN_POOL);
			ut_ad(insert_planned);
			ut_ad(cursor->thr);

unknown's avatar
unknown committed
434
			if (ibuf_should_try(index, ignore_sec_unique) &&
435 436 437 438
				ibuf_insert(tuple, index, space, page_no,
							cursor->thr)) {
				/* Insertion to the insert buffer succeeded */
				cursor->flag = BTR_CUR_INSERT_TO_IBUF;
439
				if (UNIV_LIKELY_NULL(heap)) {
440 441
					mem_heap_free(heap);
				}
unknown's avatar
unknown committed
442
				goto func_exit;
443 444 445 446 447 448 449 450 451
			}

			/* Insert to the insert buffer did not succeed:
			retry page get */

			buf_mode = BUF_GET;

			goto retry_page_get;
		}
unknown's avatar
unknown committed
452 453

		buf_block_align(page)->check_index_page_at_flush = TRUE;
454 455 456 457 458 459 460
			
#ifdef UNIV_SYNC_DEBUG					
		if (rw_latch != RW_NO_LATCH) {
			buf_page_dbg_add_level(page, SYNC_TREE_NODE);
		}
#endif
		ut_ad(0 == ut_dulint_cmp(tree->id,
461
					btr_page_get_index_id(page)));
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478

		if (height == ULINT_UNDEFINED) {
			/* We are in the root node */

			height = btr_page_get_level(page, mtr);
			root_height = height;
			cursor->tree_height = root_height + 1;
#ifdef BTR_CUR_ADAPT
			if (page != guess) {
				info->root_guess = page;
			}	
#endif
		}
	
		if (height == 0) {
			if (rw_latch == RW_NO_LATCH) {

479
				btr_cur_latch_leaves(page, space,
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
						page_no, latch_mode, cursor,
						mtr);
			}

			if ((latch_mode != BTR_MODIFY_TREE)
			    && (latch_mode != BTR_CONT_MODIFY_TREE)) {

				/* Release the tree s-latch */

				mtr_release_s_latch_at_savepoint(
						mtr, savepoint,
						dict_tree_get_lock(tree));
			}

			page_mode = mode;
		}

unknown's avatar
unknown committed
497 498 499
		page_cur_search_with_match(page, index, tuple, page_mode,
					&up_match, &up_bytes,
					&low_match, &low_bytes, page_cursor);
500 501 502 503 504 505
		if (estimate) {
			btr_cur_add_path_info(cursor, height, root_height);
		}	

		/* If this is the desired level, leave the loop */

506 507 508
		ut_ad(height
		== btr_page_get_level(page_cur_get_page(page_cursor), mtr));

509 510 511 512
		if (level == height) {

			if (level > 0) {
				/* x-latch the page */
513 514
				page = btr_page_get(space,
						page_no, RW_X_LATCH, mtr);
unknown's avatar
unknown committed
515
				ut_a((ibool)!!page_is_comp(page)
unknown's avatar
unknown committed
516
						== index->table->comp);
517 518 519 520 521 522 523 524 525 526 527
			}

			break;
		}

		ut_ad(height > 0);

		height--;
		guess = NULL;

		node_ptr = page_cur_get_rec(page_cursor);
528 529
		offsets = rec_get_offsets(node_ptr, cursor->index, offsets,
						ULINT_UNDEFINED, &heap);
530
		/* Go to the child node */
unknown's avatar
unknown committed
531
		page_no = btr_node_ptr_get_child_page_no(node_ptr, offsets);
532 533
	}

534
	if (UNIV_LIKELY_NULL(heap)) {
535 536
		mem_heap_free(heap);
	}
unknown's avatar
unknown committed
537

538 539 540 541 542 543 544
	if (level == 0) {
		cursor->low_match = low_match;
		cursor->low_bytes = low_bytes;
		cursor->up_match = up_match;
		cursor->up_bytes = up_bytes;

#ifdef BTR_CUR_ADAPT		
unknown's avatar
unknown committed
545
		if (srv_use_adaptive_hash_indexes) {
546

unknown's avatar
unknown committed
547 548 549
			btr_search_info_update(index, cursor);
		}
#endif
550 551 552 553 554 555 556 557
		ut_ad(cursor->up_match != ULINT_UNDEFINED
						|| mode != PAGE_CUR_GE);
		ut_ad(cursor->up_match != ULINT_UNDEFINED
						|| mode != PAGE_CUR_LE);
		ut_ad(cursor->low_match != ULINT_UNDEFINED
						|| mode != PAGE_CUR_LE);
	}

unknown's avatar
unknown committed
558
func_exit:
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
	if (has_search_latch) {
		
		rw_lock_s_lock(&btr_search_latch);
	}
}

/*********************************************************************
Opens a cursor at either end of an index. */

void
btr_cur_open_at_index_side(
/*=======================*/
	ibool		from_left,	/* in: TRUE if open to the low end,
					FALSE if to the high end */
	dict_index_t*	index,		/* in: index */
	ulint		latch_mode,	/* in: latch mode */
	btr_cur_t*	cursor,		/* in: cursor */
	mtr_t*		mtr)		/* in: mtr */
{
	page_cur_t*	page_cursor;
	dict_tree_t*	tree;
	page_t*		page;
	ulint		page_no;
	ulint		space;
	ulint		height;
unknown's avatar
unknown committed
584
	ulint		root_height = 0; /* remove warning */
585 586
	rec_t*		node_ptr;
	ulint		estimate;
unknown's avatar
unknown committed
587
	ulint           savepoint;
588
	mem_heap_t*	heap		= NULL;
589
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
590
	ulint*		offsets		= offsets_;
591
	*offsets_ = (sizeof offsets_) / sizeof *offsets_;
592 593 594 595 596 597

	estimate = latch_mode & BTR_ESTIMATE;
	latch_mode = latch_mode & ~BTR_ESTIMATE;
	
	tree = index->tree;
	
unknown's avatar
unknown committed
598 599 600 601 602
	/* Store the position of the tree latch we push to mtr so that we
	know how to release it when we have latched the leaf node */

	savepoint = mtr_set_savepoint(mtr);

603 604 605 606 607 608 609 610 611 612 613 614 615
	if (latch_mode == BTR_MODIFY_TREE) {
		mtr_x_lock(dict_tree_get_lock(tree), mtr);
	} else {
		mtr_s_lock(dict_tree_get_lock(tree), mtr);
	}
	
	page_cursor = btr_cur_get_page_cur(cursor);
	cursor->index = index;

	space = dict_tree_get_space(tree);
	page_no = dict_tree_get_page(tree);

	height = ULINT_UNDEFINED;
unknown's avatar
unknown committed
616

617 618 619
	for (;;) {
		page = buf_page_get_gen(space, page_no, RW_NO_LATCH, NULL,
					BUF_GET,
620
					__FILE__, __LINE__,
621 622 623 624
					mtr);
		ut_ad(0 == ut_dulint_cmp(tree->id,
						btr_page_get_index_id(page)));

unknown's avatar
unknown committed
625 626
		buf_block_align(page)->check_index_page_at_flush = TRUE;

627 628 629 630 631 632 633 634
		if (height == ULINT_UNDEFINED) {
			/* We are in the root node */

			height = btr_page_get_level(page, mtr);
			root_height = height;
		}

		if (height == 0) {
635
			btr_cur_latch_leaves(page, space, page_no,
636
						latch_mode, cursor, mtr);
unknown's avatar
unknown committed
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652

			/* In versions <= 3.23.52 we had forgotten to
			release the tree latch here. If in an index scan
			we had to scan far to find a record visible to the
			current transaction, that could starve others
			waiting for the tree latch. */
 
			if ((latch_mode != BTR_MODIFY_TREE)
			    && (latch_mode != BTR_CONT_MODIFY_TREE)) {

				/* Release the tree s-latch */

				mtr_release_s_latch_at_savepoint(
						mtr, savepoint,
						dict_tree_get_lock(tree));
			}
653 654 655 656 657 658 659 660 661
		}
		
		if (from_left) {
			page_cur_set_before_first(page, page_cursor);
		} else {
			page_cur_set_after_last(page, page_cursor);
		}

		if (height == 0) {
unknown's avatar
unknown committed
662 663 664 665
		        if (estimate) {
			        btr_cur_add_path_info(cursor, height,
						      root_height);
		        }
666 667 668 669 670 671 672 673 674 675 676 677

			break;
		}

		ut_ad(height > 0);

		if (from_left) {
			page_cur_move_to_next(page_cursor);
		} else {
			page_cur_move_to_prev(page_cursor);
		}

unknown's avatar
unknown committed
678 679 680 681
		if (estimate) {
			btr_cur_add_path_info(cursor, height, root_height);
		}

682 683 684
		height--;

		node_ptr = page_cur_get_rec(page_cursor);
685 686
		offsets = rec_get_offsets(node_ptr, cursor->index, offsets,
						ULINT_UNDEFINED, &heap);
687
		/* Go to the child node */
unknown's avatar
unknown committed
688
		page_no = btr_node_ptr_get_child_page_no(node_ptr, offsets);
689
	}
unknown's avatar
unknown committed
690

691
	if (UNIV_LIKELY_NULL(heap)) {
692 693
		mem_heap_free(heap);
	}
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
}
	
/**************************************************************************
Positions a cursor at a randomly chosen position within a B-tree. */

void
btr_cur_open_at_rnd_pos(
/*====================*/
	dict_index_t*	index,		/* in: index */
	ulint		latch_mode,	/* in: BTR_SEARCH_LEAF, ... */
	btr_cur_t*	cursor,		/* in/out: B-tree cursor */
	mtr_t*		mtr)		/* in: mtr */
{
	page_cur_t*	page_cursor;
	dict_tree_t*	tree;
	page_t*		page;
	ulint		page_no;
	ulint		space;
	ulint		height;
	rec_t*		node_ptr;
714
	mem_heap_t*	heap		= NULL;
715
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
716
	ulint*		offsets		= offsets_;
717
	*offsets_ = (sizeof offsets_) / sizeof *offsets_;
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737

	tree = index->tree;
	
	if (latch_mode == BTR_MODIFY_TREE) {
		mtr_x_lock(dict_tree_get_lock(tree), mtr);
	} else {
		mtr_s_lock(dict_tree_get_lock(tree), mtr);
	}
	
	page_cursor = btr_cur_get_page_cur(cursor);
	cursor->index = index;

	space = dict_tree_get_space(tree);
	page_no = dict_tree_get_page(tree);

	height = ULINT_UNDEFINED;
	
	for (;;) {
		page = buf_page_get_gen(space, page_no, RW_NO_LATCH, NULL,
					BUF_GET,
738
					__FILE__, __LINE__,
739 740 741 742 743 744 745 746 747 748 749
					mtr);
		ut_ad(0 == ut_dulint_cmp(tree->id,
						btr_page_get_index_id(page)));

		if (height == ULINT_UNDEFINED) {
			/* We are in the root node */

			height = btr_page_get_level(page, mtr);
		}

		if (height == 0) {
750
			btr_cur_latch_leaves(page, space, page_no,
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
						latch_mode, cursor, mtr);
		}

		page_cur_open_on_rnd_user_rec(page, page_cursor);	

		if (height == 0) {

			break;
		}

		ut_ad(height > 0);

		height--;

		node_ptr = page_cur_get_rec(page_cursor);
766 767
		offsets = rec_get_offsets(node_ptr, cursor->index, offsets,
						ULINT_UNDEFINED, &heap);
768
		/* Go to the child node */
unknown's avatar
unknown committed
769
		page_no = btr_node_ptr_get_child_page_no(node_ptr, offsets);
770
	}
unknown's avatar
unknown committed
771

772
	if (UNIV_LIKELY_NULL(heap)) {
773 774
		mem_heap_free(heap);
	}
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 801 802 803 804 805 806 807 808 809 810 811
}	

/*==================== B-TREE INSERT =========================*/

/*****************************************************************
Inserts a record if there is enough space, or if enough space can
be freed by reorganizing. Differs from _optimistic_insert because
no heuristics is applied to whether it pays to use CPU time for
reorganizing the page or not. */
static
rec_t*
btr_cur_insert_if_possible(
/*=======================*/
				/* out: pointer to inserted record if succeed,
				else NULL */
	btr_cur_t*	cursor,	/* in: cursor on page after which to insert;
				cursor stays valid */
	dtuple_t*	tuple,	/* in: tuple to insert; the size info need not
				have been stored to tuple */
	ibool*		reorg,	/* out: TRUE if reorganization occurred */
	mtr_t*		mtr)	/* in: mtr */
{
	page_cur_t*	page_cursor;
	page_t*		page;
	rec_t*		rec;

	ut_ad(dtuple_check_typed(tuple));
	
	*reorg = FALSE;

	page = btr_cur_get_page(cursor);

	ut_ad(mtr_memo_contains(mtr, buf_block_align(page),
							MTR_MEMO_PAGE_X_FIX));
	page_cursor = btr_cur_get_page_cur(cursor);
	
	/* Now, try the insert */
unknown's avatar
unknown committed
812
	rec = page_cur_tuple_insert(page_cursor, tuple, cursor->index, mtr);
813 814 815 816

	if (!rec) {
		/* If record did not fit, reorganize */

unknown's avatar
unknown committed
817
		btr_page_reorganize(page, cursor->index, mtr);
818 819 820

		*reorg = TRUE;

unknown's avatar
unknown committed
821 822
		page_cur_search(page, cursor->index, tuple,
						PAGE_CUR_LE, page_cursor);
823

unknown's avatar
unknown committed
824 825
		rec = page_cur_tuple_insert(page_cursor, tuple,
						cursor->index, mtr);
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
	}

	return(rec);
}

/*****************************************************************
For an insert, checks the locks and does the undo logging if desired. */
UNIV_INLINE
ulint
btr_cur_ins_lock_and_undo(
/*======================*/
				/* out: DB_SUCCESS, DB_WAIT_LOCK,
				DB_FAIL, or error number */
	ulint		flags,	/* in: undo logging and locking flags: if
				not zero, the parameters index and thr
				should be specified */
	btr_cur_t*	cursor,	/* in: cursor on page after which to insert */
	dtuple_t*	entry,	/* in: entry to insert */
	que_thr_t*	thr,	/* in: query thread or NULL */
	ibool*		inherit)/* out: TRUE if the inserted new record maybe
				should inherit LOCK_GAP type locks from the
				successor record */
{
	dict_index_t*	index;
	ulint		err;
	rec_t*		rec;
	dulint		roll_ptr;

	/* Check if we have to wait for a lock: enqueue an explicit lock
	request if yes */

	rec = btr_cur_get_rec(cursor);
	index = cursor->index;
	
	err = lock_rec_insert_check_and_lock(flags, rec, index, thr, inherit);
	
	if (err != DB_SUCCESS) {

		return(err);
	}

	if ((index->type & DICT_CLUSTERED) && !(index->type & DICT_IBUF)) {

		err = trx_undo_report_row_operation(flags, TRX_UNDO_INSERT_OP,
					thr, index, entry, NULL, 0, NULL,
					&roll_ptr);
		if (err != DB_SUCCESS) {

			return(err);
		}

		/* Now we can fill in the roll ptr field in entry */

		if (!(flags & BTR_KEEP_SYS_FLAG)) {

			row_upd_index_entry_sys_field(entry, index,
						DATA_ROLL_PTR, roll_ptr);
		}
	}

	return(DB_SUCCESS);
}

unknown's avatar
unknown committed
889
#ifdef UNIV_DEBUG
890 891 892 893 894 895
/*****************************************************************
Report information about a transaction. */
static
void
btr_cur_trx_report(
/*===============*/
896
	trx_t*			trx,	/* in: transaction */
897 898 899 900 901 902 903
	const dict_index_t*	index,	/* in: index */
	const char*		op)	/* in: operation */
{
	fprintf(stderr, "Trx with id %lu %lu going to ",
		ut_dulint_get_high(trx->id),
		ut_dulint_get_low(trx->id));
	fputs(op, stderr);
904
	dict_index_name_print(stderr, trx, index);
905 906
	putc('\n', stderr);
}
unknown's avatar
unknown committed
907
#endif /* UNIV_DEBUG */
908

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
/*****************************************************************
Tries to perform an insert to a page in an index tree, next to cursor.
It is assumed that mtr holds an x-latch on the page. The operation does
not succeed if there is too little space on the page. If there is just
one record on the page, the insert will always succeed; this is to
prevent trying to split a page with just one record. */

ulint
btr_cur_optimistic_insert(
/*======================*/
				/* out: DB_SUCCESS, DB_WAIT_LOCK,
				DB_FAIL, or error number */
	ulint		flags,	/* in: undo logging and locking flags: if not
				zero, the parameters index and thr should be
				specified */
	btr_cur_t*	cursor,	/* in: cursor on page after which to insert;
				cursor stays valid */
	dtuple_t*	entry,	/* in: entry to insert */
	rec_t**		rec,	/* out: pointer to inserted record if
				succeed */
929 930 931
	big_rec_t**	big_rec,/* out: big rec vector whose fields have to
				be stored externally by the caller, or
				NULL */
932 933 934
	que_thr_t*	thr,	/* in: query thread or NULL */
	mtr_t*		mtr)	/* in: mtr */
{
935
	big_rec_t*	big_rec_vec	= NULL;
936 937 938 939 940 941 942 943 944 945
	dict_index_t*	index;
	page_cur_t*	page_cursor;
	page_t*		page;
	ulint		max_size;
	rec_t*		dummy_rec;
	ulint		level;
	ibool		reorg;
	ibool		inherit;
	ulint		rec_size;
	ulint		type;
unknown's avatar
unknown committed
946
	ulint		err;	
947

948 949
	*big_rec = NULL;

950 951 952
	page = btr_cur_get_page(cursor);
	index = cursor->index;

unknown's avatar
unknown committed
953
	if (!dtuple_check_typed_no_assert(entry)) {
954
		fputs("InnoDB: Error in a tuple to insert into ", stderr);
955
		dict_index_name_print(stderr, thr_get_trx(thr), index);
unknown's avatar
unknown committed
956
	}
unknown's avatar
unknown committed
957
#ifdef UNIV_DEBUG
unknown's avatar
unknown committed
958
	if (btr_cur_print_record_ops && thr) {
959 960
		btr_cur_trx_report(thr_get_trx(thr), index, "insert into ");
		dtuple_print(stderr, entry);
unknown's avatar
unknown committed
961
	}
unknown's avatar
unknown committed
962 963
#endif /* UNIV_DEBUG */

964 965 966 967 968
	ut_ad(mtr_memo_contains(mtr, buf_block_align(page),
							MTR_MEMO_PAGE_X_FIX));
	max_size = page_get_max_insert_size_after_reorganize(page, 1);
	level = btr_page_get_level(page, mtr);

969
calculate_sizes_again:
970
	/* Calculate the record size when entry is converted to a record */
unknown's avatar
unknown committed
971
	rec_size = rec_get_converted_size(index, entry);
972

unknown's avatar
unknown committed
973
	if (rec_size >=
974
		ut_min(page_get_free_space_of_empty(page_is_comp(page)) / 2,
unknown's avatar
unknown committed
975
		REC_MAX_DATA_SIZE)) {
976 977 978 979

		/* The record is so big that we have to store some fields
		externally on separate database pages */
		
980
                big_rec_vec = dtuple_convert_big_rec(index, entry, NULL, 0);
981 982 983 984 985

		if (big_rec_vec == NULL) {
		
			return(DB_TOO_BIG_RECORD);
		}
986

987
		goto calculate_sizes_again;
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
	}

	/* If there have been many consecutive inserts, and we are on the leaf
	level, check if we have to split the page to reserve enough free space
	for future updates of records. */

	type = index->type;
	
	if ((type & DICT_CLUSTERED)
	    && (dict_tree_get_space_reserve(index->tree) + rec_size > max_size)
	    && (page_get_n_recs(page) >= 2)
	    && (0 == level)
	    && (btr_page_get_split_rec_to_right(cursor, &dummy_rec)
	        || btr_page_get_split_rec_to_left(cursor, &dummy_rec))) {
1002 1003 1004 1005 1006

	        if (big_rec_vec) {
			dtuple_convert_back_big_rec(index, entry, big_rec_vec);
		}

1007 1008 1009 1010 1011 1012 1013 1014
		return(DB_FAIL);
	}
	
	if (!(((max_size >= rec_size)
	       && (max_size >= BTR_CUR_PAGE_REORGANIZE_LIMIT))
	      || (page_get_max_insert_size(page, 1) >= rec_size)
	      || (page_get_n_recs(page) <= 1))) {

1015 1016 1017
	        if (big_rec_vec) {
			dtuple_convert_back_big_rec(index, entry, big_rec_vec);
		}
1018 1019 1020 1021 1022 1023 1024 1025
		return(DB_FAIL);
	}

        /* Check locks and write to the undo log, if specified */
        err = btr_cur_ins_lock_and_undo(flags, cursor, entry, thr, &inherit);

	if (err != DB_SUCCESS) {

1026 1027 1028
	        if (big_rec_vec) {
			dtuple_convert_back_big_rec(index, entry, big_rec_vec);
		}
1029 1030 1031 1032 1033 1034 1035 1036 1037
		return(err);
	}

	page_cursor = btr_cur_get_page_cur(cursor);

	reorg = FALSE;

	/* Now, try the insert */

1038 1039
	*rec = page_cur_insert_rec_low(page_cursor, entry, index,
							NULL, NULL, mtr);
1040
	if (UNIV_UNLIKELY(!(*rec))) {
1041
		/* If the record did not fit, reorganize */
unknown's avatar
unknown committed
1042
		btr_page_reorganize(page, index, mtr);
1043 1044 1045 1046 1047

		ut_ad(page_get_max_insert_size(page, 1) == max_size);
		
		reorg = TRUE;

unknown's avatar
unknown committed
1048
		page_cur_search(page, index, entry, PAGE_CUR_LE, page_cursor);
1049

unknown's avatar
unknown committed
1050
		*rec = page_cur_tuple_insert(page_cursor, entry, index, mtr);
1051

1052
		if (UNIV_UNLIKELY(!*rec)) {
1053 1054 1055
			fputs("InnoDB: Error: cannot insert tuple ", stderr);
			dtuple_print(stderr, entry);
			fputs(" into ", stderr);
1056
			dict_index_name_print(stderr, thr_get_trx(thr), index);
1057
			fprintf(stderr, "\nInnoDB: max insert size %lu\n",
unknown's avatar
unknown committed
1058
				(ulong) max_size);
1059
			ut_error;
1060
		}
1061 1062 1063 1064 1065 1066 1067 1068 1069
	}

#ifdef BTR_CUR_HASH_ADAPT
	if (!reorg && (0 == level) && (cursor->flag == BTR_CUR_HASH)) {
		btr_search_update_hash_node_on_insert(cursor);
	} else {
		btr_search_update_hash_on_insert(cursor);
	}
#endif
1070

1071 1072 1073 1074 1075
	if (!(flags & BTR_NO_LOCKING_FLAG) && inherit) {

		lock_update_insert(*rec);
	}

1076 1077
/*	fprintf(stderr, "Insert into page %lu, max ins size %lu,"
		" rec %lu ind type %lu\n",
1078 1079 1080
			buf_frame_get_page_no(page), max_size,
					rec_size + PAGE_DIR_SLOT_SIZE, type);
*/	
unknown's avatar
unknown committed
1081
	if (!(type & DICT_CLUSTERED)) {
1082 1083 1084 1085 1086
		/* We have added a record to page: update its free bits */
		ibuf_update_free_bits_if_full(cursor->index, page, max_size,
					rec_size + PAGE_DIR_SLOT_SIZE);
	}

1087 1088
	*big_rec = big_rec_vec;

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
	return(DB_SUCCESS);
}

/*****************************************************************
Performs an insert on a page of an index tree. It is assumed that mtr
holds an x-latch on the tree and on the cursor page. If the insert is
made on the leaf level, to avoid deadlocks, mtr must also own x-latches
to brothers of page, if those brothers exist. */

ulint
btr_cur_pessimistic_insert(
/*=======================*/
				/* out: DB_SUCCESS or error number */
	ulint		flags,	/* in: undo logging and locking flags: if not
				zero, the parameter thr should be
				specified; if no undo logging is specified,
				then the caller must have reserved enough
				free extents in the file space so that the
				insertion will certainly succeed */
	btr_cur_t*	cursor,	/* in: cursor after which to insert;
				cursor stays valid */
	dtuple_t*	entry,	/* in: entry to insert */
	rec_t**		rec,	/* out: pointer to inserted record if
				succeed */
1113 1114 1115
	big_rec_t**	big_rec,/* out: big rec vector whose fields have to
				be stored externally by the caller, or
				NULL */
1116 1117 1118
	que_thr_t*	thr,	/* in: query thread or NULL */
	mtr_t*		mtr)	/* in: mtr */
{
1119 1120 1121 1122 1123 1124 1125
	dict_index_t*	index		= cursor->index;
	big_rec_t*	big_rec_vec	= NULL;
	page_t*		page;
	ulint		err;
	ibool		dummy_inh;
	ibool		success;
	ulint		n_extents	= 0;
unknown's avatar
unknown committed
1126
	ulint		n_reserved;
1127 1128 1129
	
	ut_ad(dtuple_check_typed(entry));

1130 1131
	*big_rec = NULL;

1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
	page = btr_cur_get_page(cursor);

	ut_ad(mtr_memo_contains(mtr,
				dict_tree_get_lock(btr_cur_get_tree(cursor)),
							MTR_MEMO_X_LOCK));
	ut_ad(mtr_memo_contains(mtr, buf_block_align(page),
							MTR_MEMO_PAGE_X_FIX));

	/* Try first an optimistic insert; reset the cursor flag: we do not
	assume anything of how it was positioned */

	cursor->flag = BTR_CUR_BINARY;

1145
	err = btr_cur_optimistic_insert(flags, cursor, entry, rec, big_rec,
unknown's avatar
unknown committed
1146
								thr, mtr);
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
	if (err != DB_FAIL) {

		return(err);
	}

	/* Retry with a pessimistic insert. Check locks and write to undo log,
	if specified */

	err = btr_cur_ins_lock_and_undo(flags, cursor, entry, thr, &dummy_inh);

	if (err != DB_SUCCESS) {

		return(err);
	}

	if (!(flags & BTR_NO_UNDO_LOG_FLAG)) {	
		/* First reserve enough free space for the file segments
		of the index tree, so that the insert will not fail because
		of lack of space */

		n_extents = cursor->tree_height / 16 + 3;

unknown's avatar
unknown committed
1169
		success = fsp_reserve_free_extents(&n_reserved, index->space,
1170 1171 1172 1173 1174 1175 1176 1177
						n_extents, FSP_NORMAL, mtr);
		if (!success) {
			err = DB_OUT_OF_FILE_SPACE;

			return(err);
		}
	}

unknown's avatar
unknown committed
1178
	if (rec_get_converted_size(index, entry) >=
1179
		ut_min(page_get_free_space_of_empty(page_is_comp(page)) / 2,
unknown's avatar
unknown committed
1180
		REC_MAX_DATA_SIZE)) {
1181 1182 1183 1184

		/* The record is so big that we have to store some fields
		externally on separate database pages */
		
1185
                big_rec_vec = dtuple_convert_big_rec(index, entry, NULL, 0);
1186 1187 1188

		if (big_rec_vec == NULL) {
		
unknown's avatar
unknown committed
1189 1190
			if (n_extents > 0) {
			        fil_space_release_free_extents(index->space,
unknown's avatar
unknown committed
1191
								n_reserved);
unknown's avatar
unknown committed
1192
			}
1193 1194 1195 1196 1197
			return(DB_TOO_BIG_RECORD);
		}
	}

	if (dict_tree_get_page(index->tree)
1198 1199 1200 1201 1202 1203 1204 1205
					== buf_frame_get_page_no(page)) {

		/* The page is the root page */
		*rec = btr_root_raise_and_insert(cursor, entry, mtr);
	} else {
		*rec = btr_page_split_and_insert(cursor, entry, mtr);
	}

1206
	btr_cur_position(index, page_rec_get_prev(*rec), cursor);	
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218

#ifdef BTR_CUR_ADAPT
	btr_search_update_hash_on_insert(cursor);
#endif
	if (!(flags & BTR_NO_LOCKING_FLAG)) {

		lock_update_insert(*rec);
	}

	err = DB_SUCCESS;

	if (n_extents > 0) {
unknown's avatar
unknown committed
1219
		fil_space_release_free_extents(index->space, n_reserved);
1220
	}
1221 1222 1223

	*big_rec = big_rec_vec;

1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
	return(err);
}

/*==================== B-TREE UPDATE =========================*/

/*****************************************************************
For an update, checks the locks and does the undo logging. */
UNIV_INLINE
ulint
btr_cur_upd_lock_and_undo(
/*======================*/
				/* out: DB_SUCCESS, DB_WAIT_LOCK, or error
				number */
	ulint		flags,	/* in: undo logging and locking flags */
	btr_cur_t*	cursor,	/* in: cursor on record to update */
	upd_t*		update,	/* in: update vector */
	ulint		cmpl_info,/* in: compiler info on secondary index
				updates */
	que_thr_t*	thr,	/* in: query thread */
	dulint*		roll_ptr)/* out: roll pointer */
{
	dict_index_t*	index;
	rec_t*		rec;
	ulint		err;
	
	ut_ad(cursor && update && thr && roll_ptr);

	rec = btr_cur_get_rec(cursor);
	index = cursor->index;
	
unknown's avatar
unknown committed
1254 1255 1256
	if (!(index->type & DICT_CLUSTERED)) {
		/* We do undo logging only when we update a clustered index
		record */
unknown's avatar
unknown committed
1257 1258
		return(lock_sec_rec_modify_check_and_lock(flags, rec, index,
									thr));
unknown's avatar
unknown committed
1259 1260
	}

1261 1262 1263 1264 1265 1266
	/* Check if we have to wait for a lock: enqueue an explicit lock
	request if yes */

	err = DB_SUCCESS;

	if (!(flags & BTR_NO_LOCKING_FLAG)) {
1267
		mem_heap_t*	heap		= NULL;
1268
		ulint		offsets_[REC_OFFS_NORMAL_SIZE];
1269 1270
		*offsets_ = (sizeof offsets_) / sizeof *offsets_;

1271
		err = lock_clust_rec_modify_check_and_lock(flags, rec, index,
1272 1273
			rec_get_offsets(rec, index, offsets_,
				ULINT_UNDEFINED, &heap), thr);
1274
		if (UNIV_LIKELY_NULL(heap)) {
1275 1276
			mem_heap_free(heap);
		}
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
		if (err != DB_SUCCESS) {

			return(err);
		}
	}

	/* Append the info about the update in the undo log */

	err = trx_undo_report_row_operation(flags, TRX_UNDO_MODIFY_OP, thr,
						index, NULL, update,
						cmpl_info, rec, roll_ptr);
	return(err);
}

/***************************************************************
Writes a redo log record of updating a record in-place. */
UNIV_INLINE
void
btr_cur_update_in_place_log(
/*========================*/
	ulint		flags,		/* in: flags */
	rec_t*		rec,		/* in: record */
	dict_index_t*	index,		/* in: index where cursor positioned */
	upd_t*		update,		/* in: update vector */
	trx_t*		trx,		/* in: transaction */
	dulint		roll_ptr,	/* in: roll ptr */
	mtr_t*		mtr)		/* in: mtr */
{
	byte*	log_ptr;
1306
	page_t*	page	= ut_align_down(rec, UNIV_PAGE_SIZE);
unknown's avatar
unknown committed
1307
	ut_ad(flags < 256);
1308
	ut_ad(!!page_is_comp(page) == index->table->comp);
1309

1310
	log_ptr = mlog_open_and_write_index(mtr, rec, index, page_is_comp(page)
unknown's avatar
unknown committed
1311 1312 1313
			? MLOG_COMP_REC_UPDATE_IN_PLACE
			: MLOG_REC_UPDATE_IN_PLACE,
			1 + DATA_ROLL_PTR_LEN + 14 + 2 + MLOG_BUF_MARGIN);
1314

unknown's avatar
unknown committed
1315 1316 1317 1318
	if (!log_ptr) {
		/* Logging in mtr is switched off during crash recovery */
		return;
	}
1319

unknown's avatar
unknown committed
1320 1321 1322 1323 1324 1325 1326
	/* The code below assumes index is a clustered index: change index to
	the clustered index if we are updating a secondary index record (or we
	could as well skip writing the sys col values to the log in this case
	because they are not needed for a secondary index record update) */

	index = dict_table_get_first_index(index->table);

unknown's avatar
unknown committed
1327 1328 1329
	mach_write_to_1(log_ptr, flags);
	log_ptr++;

1330 1331
	log_ptr = row_upd_write_sys_vals_to_log(index, trx, roll_ptr, log_ptr,
									mtr);
1332
	mach_write_to_2(log_ptr, ut_align_offset(rec, UNIV_PAGE_SIZE));
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
	log_ptr += 2;

	row_upd_index_write_log(update, log_ptr, mtr);
}	

/***************************************************************
Parses a redo log record of updating a record in-place. */

byte*
btr_cur_parse_update_in_place(
/*==========================*/
unknown's avatar
unknown committed
1344 1345 1346 1347 1348
				/* out: end of log record or NULL */
	byte*		ptr,	/* in: buffer */
	byte*		end_ptr,/* in: buffer end */
	page_t*		page,	/* in: page or NULL */
	dict_index_t*	index)	/* in: index corresponding to page */
1349 1350 1351 1352 1353 1354 1355 1356 1357
{
	ulint	flags;
	rec_t*	rec;
	upd_t*	update;
	ulint	pos;
	dulint	trx_id;
	dulint	roll_ptr;
	ulint	rec_offset;
	mem_heap_t* heap;
unknown's avatar
unknown committed
1358
	ulint*	offsets;
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382

	if (end_ptr < ptr + 1) {

		return(NULL);
	}
	
	flags = mach_read_from_1(ptr);
	ptr++;

	ptr = row_upd_parse_sys_vals(ptr, end_ptr, &pos, &trx_id, &roll_ptr);

	if (ptr == NULL) {

		return(NULL);
	}

	if (end_ptr < ptr + 2) {

		return(NULL);
	}

	rec_offset = mach_read_from_2(ptr);
	ptr += 2;

unknown's avatar
unknown committed
1383 1384
	ut_a(rec_offset <= UNIV_PAGE_SIZE);

1385 1386 1387 1388
	heap = mem_heap_create(256);
	
	ptr = row_upd_index_parse(ptr, end_ptr, heap, &update);

1389
	if (!ptr || !page) {
1390

1391
		goto func_exit;
1392 1393
	}

unknown's avatar
unknown committed
1394
	ut_a((ibool)!!page_is_comp(page) == index->table->comp);
1395 1396 1397 1398 1399
	rec = page + rec_offset;
	
	/* We do not need to reserve btr_search_latch, as the page is only
	being recovered, and there cannot be a hash index to it. */

1400
	offsets = rec_get_offsets(rec, index, NULL, ULINT_UNDEFINED, &heap);
unknown's avatar
unknown committed
1401

1402
	if (!(flags & BTR_KEEP_SYS_FLAG)) {
unknown's avatar
unknown committed
1403 1404
		row_upd_rec_sys_fields_in_recovery(rec, offsets,
			pos, trx_id, roll_ptr);
1405 1406
	}

unknown's avatar
unknown committed
1407
	row_upd_rec_in_place(rec, offsets, update);
1408

1409
func_exit:
1410 1411 1412 1413 1414 1415
	mem_heap_free(heap);

	return(ptr);
}

/*****************************************************************
unknown's avatar
unknown committed
1416 1417
Updates a record when the update causes no size changes in its fields.
We assume here that the ordering fields of the record do not change. */
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

ulint
btr_cur_update_in_place(
/*====================*/
				/* out: DB_SUCCESS or error number */
	ulint		flags,	/* in: undo logging and locking flags */
	btr_cur_t*	cursor,	/* in: cursor on the record to update;
				cursor stays valid and positioned on the
				same record */
	upd_t*		update,	/* in: update vector */
	ulint		cmpl_info,/* in: compiler info on secondary index
				updates */
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
{
	dict_index_t*	index;
	buf_block_t*	block;
	ulint		err;
	rec_t*		rec;
unknown's avatar
unknown committed
1437
	dulint		roll_ptr	= ut_dulint_zero;
1438
	trx_t*		trx;
1439
	ulint		was_delete_marked;
1440
	mem_heap_t*	heap		= NULL;
1441
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
1442
	ulint*		offsets		= offsets_;
1443
	*offsets_ = (sizeof offsets_) / sizeof *offsets_;
1444 1445 1446

	rec = btr_cur_get_rec(cursor);
	index = cursor->index;
1447
	ut_ad(!!page_rec_is_comp(rec) == index->table->comp);
1448
	trx = thr_get_trx(thr);
1449
	offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap);
unknown's avatar
unknown committed
1450
#ifdef UNIV_DEBUG
unknown's avatar
unknown committed
1451
	if (btr_cur_print_record_ops && thr) {
1452
		btr_cur_trx_report(trx, index, "update ");
1453
		rec_print_new(stderr, rec, offsets);
unknown's avatar
unknown committed
1454
	}
unknown's avatar
unknown committed
1455
#endif /* UNIV_DEBUG */
unknown's avatar
unknown committed
1456

1457 1458 1459
	/* Do lock checking and undo logging */
	err = btr_cur_upd_lock_and_undo(flags, cursor, update, cmpl_info,
							thr, &roll_ptr);
1460
	if (UNIV_UNLIKELY(err != DB_SUCCESS)) {
1461

1462
		if (UNIV_LIKELY_NULL(heap)) {
1463 1464
			mem_heap_free(heap);
		}
1465 1466 1467 1468
		return(err);
	}

	block = buf_block_align(rec);
1469 1470
	ut_ad(!!page_is_comp(buf_block_get_frame(block))
				== index->table->comp);
1471 1472

	if (block->is_hashed) {
unknown's avatar
unknown committed
1473 1474 1475 1476 1477 1478
		/* The function row_upd_changes_ord_field_binary works only
		if the update vector was built for a clustered index, we must
		NOT call it if index is secondary */

	        if (!(index->type & DICT_CLUSTERED)
		    || row_upd_changes_ord_field_binary(NULL, index, update)) {
unknown's avatar
unknown committed
1479 1480 1481 1482 1483

		        /* Remove possible hash index pointer to this record */
	                btr_search_update_hash_on_delete(cursor);
	        }

1484 1485 1486 1487
		rw_lock_x_lock(&btr_search_latch);
	}

	if (!(flags & BTR_KEEP_SYS_FLAG)) {
unknown's avatar
unknown committed
1488
		row_upd_rec_sys_fields(rec, index, offsets, trx, roll_ptr);
1489 1490 1491 1492
	}

	/* FIXME: in a mixed tree, all records may not have enough ordering
	fields for btr search: */
1493

1494 1495
	was_delete_marked = rec_get_deleted_flag(rec,
				page_is_comp(buf_block_get_frame(block)));
unknown's avatar
unknown committed
1496 1497

	row_upd_rec_in_place(rec, offsets, update);
1498 1499 1500 1501 1502 1503 1504

	if (block->is_hashed) {
		rw_lock_x_unlock(&btr_search_latch);
	}

	btr_cur_update_in_place_log(flags, rec, index, update, trx, roll_ptr,
									mtr);
1505 1506
	if (was_delete_marked && !rec_get_deleted_flag(rec,
				page_is_comp(buf_block_get_frame(block)))) {
1507 1508 1509
		/* The new updated record owns its possible externally
		stored fields */

unknown's avatar
unknown committed
1510
		btr_cur_unmark_extern_fields(rec, mtr, offsets);
1511 1512
	}

1513
	if (UNIV_LIKELY_NULL(heap)) {
1514 1515
		mem_heap_free(heap);
	}
1516 1517 1518 1519 1520 1521 1522
	return(DB_SUCCESS);
}

/*****************************************************************
Tries to update a record on a page in an index tree. It is assumed that mtr
holds an x-latch on the page. The operation does not succeed if there is too
little space on the page or if the update would result in too empty a page,
unknown's avatar
unknown committed
1523 1524
so that tree compression is recommended. We assume here that the ordering
fields of the record do not change. */
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554

ulint
btr_cur_optimistic_update(
/*======================*/
				/* out: DB_SUCCESS, or DB_OVERFLOW if the
				updated record does not fit, DB_UNDERFLOW
				if the page would become too empty */
	ulint		flags,	/* in: undo logging and locking flags */
	btr_cur_t*	cursor,	/* in: cursor on the record to update;
				cursor stays valid and positioned on the
				same record */
	upd_t*		update,	/* in: update vector; this must also
				contain trx id and roll ptr fields */
	ulint		cmpl_info,/* in: compiler info on secondary index
				updates */
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
{
	dict_index_t*	index;
	page_cur_t*	page_cursor;
	ulint		err;
	page_t*		page;
	rec_t*		rec;
	ulint		max_size;
	ulint		new_rec_size;
	ulint		old_rec_size;
	dtuple_t*	new_entry;
	dulint		roll_ptr;
	trx_t*		trx;
	mem_heap_t*	heap;
1555 1556
	ibool		reorganized	= FALSE;
	ulint		i;
unknown's avatar
unknown committed
1557 1558
	ulint*		offsets;

1559 1560 1561
	page = btr_cur_get_page(cursor);
	rec = btr_cur_get_rec(cursor);
	index = cursor->index;
1562
	ut_ad(!!page_rec_is_comp(rec) == index->table->comp);
1563
	
unknown's avatar
unknown committed
1564
	heap = mem_heap_create(1024);
1565
	offsets = rec_get_offsets(rec, index, NULL, ULINT_UNDEFINED, &heap);
unknown's avatar
unknown committed
1566

unknown's avatar
unknown committed
1567
#ifdef UNIV_DEBUG
unknown's avatar
unknown committed
1568
	if (btr_cur_print_record_ops && thr) {
1569
		btr_cur_trx_report(thr_get_trx(thr), index, "update ");
1570
		rec_print_new(stderr, rec, offsets);
unknown's avatar
unknown committed
1571
	}
unknown's avatar
unknown committed
1572
#endif /* UNIV_DEBUG */
unknown's avatar
unknown committed
1573

1574 1575
	ut_ad(mtr_memo_contains(mtr, buf_block_align(page),
							MTR_MEMO_PAGE_X_FIX));
unknown's avatar
unknown committed
1576
	if (!row_upd_changes_field_size_or_external(index, offsets, update)) {
1577

unknown's avatar
unknown committed
1578 1579 1580
		/* The simplest and the most common case: the update does not
		change the size of any field and none of the updated fields is
		externally stored in rec or update */
unknown's avatar
unknown committed
1581
		mem_heap_free(heap);
1582 1583 1584 1585
		return(btr_cur_update_in_place(flags, cursor, update,
							cmpl_info, thr, mtr));
	}

1586 1587 1588 1589 1590 1591
	for (i = 0; i < upd_get_n_fields(update); i++) {
		if (upd_get_nth_field(update, i)->extern_storage) {

			/* Externally stored fields are treated in pessimistic
			update */

unknown's avatar
unknown committed
1592
			mem_heap_free(heap);
1593 1594 1595 1596
			return(DB_OVERFLOW);
		}
	}

unknown's avatar
unknown committed
1597
	if (rec_offs_any_extern(offsets)) {
1598 1599 1600
		/* Externally stored fields are treated in pessimistic
		update */

unknown's avatar
unknown committed
1601
		mem_heap_free(heap);
1602 1603 1604
		return(DB_OVERFLOW);
	}
	
1605 1606 1607 1608
	page_cursor = btr_cur_get_page_cur(cursor);
	
	new_entry = row_rec_to_index_entry(ROW_COPY_DATA, index, rec, heap);

unknown's avatar
unknown committed
1609 1610
	row_upd_index_replace_new_col_vals_index_pos(new_entry, index, update,
									NULL);
unknown's avatar
unknown committed
1611 1612
	old_rec_size = rec_offs_size(offsets);
	new_rec_size = rec_get_converted_size(index, new_entry);
1613
	
1614 1615
	if (UNIV_UNLIKELY(new_rec_size >= page_get_free_space_of_empty(
				page_is_comp(page)) / 2)) {
1616

1617
		mem_heap_free(heap);		
1618

1619
		return(DB_OVERFLOW);
1620 1621 1622 1623 1624
	}

	max_size = old_rec_size
			+ page_get_max_insert_size_after_reorganize(page, 1);

1625 1626 1627
	if (UNIV_UNLIKELY(page_get_data_size(page)
					- old_rec_size + new_rec_size
					< BTR_CUR_PAGE_COMPRESS_LIMIT)) {
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 1656 1657 1658 1659 1660 1661 1662

		/* The page would become too empty */

		mem_heap_free(heap);

		return(DB_UNDERFLOW);
	}

	if (!(((max_size >= BTR_CUR_PAGE_REORGANIZE_LIMIT)
	       				&& (max_size >= new_rec_size))
	      || (page_get_n_recs(page) <= 1))) {

		/* There was not enough space, or it did not pay to
		reorganize: for simplicity, we decide what to do assuming a
		reorganization is needed, though it might not be necessary */

		mem_heap_free(heap);		

		return(DB_OVERFLOW);
	}

	/* Do lock checking and undo logging */
	err = btr_cur_upd_lock_and_undo(flags, cursor, update, cmpl_info, thr,
								&roll_ptr);
	if (err != DB_SUCCESS) {

		mem_heap_free(heap);

		return(err);
	}
        
        /* Ok, we may do the replacement. Store on the page infimum the
	explicit locks on rec, before deleting rec (see the comment in
	.._pessimistic_update). */

1663
	lock_rec_store_on_page_infimum(page, rec);
1664 1665 1666

	btr_search_update_hash_on_delete(cursor);

1667
	page_cur_delete_rec(page_cursor, index, offsets, mtr);
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683

	page_cur_move_to_prev(page_cursor);
        
	trx = thr_get_trx(thr);

	if (!(flags & BTR_KEEP_SYS_FLAG)) {
		row_upd_index_entry_sys_field(new_entry, index, DATA_ROLL_PTR,
								roll_ptr);
		row_upd_index_entry_sys_field(new_entry, index, DATA_TRX_ID,
								trx->id);
	}

	rec = btr_cur_insert_if_possible(cursor, new_entry, &reorganized, mtr);

	ut_a(rec); /* <- We calculated above the insert would fit */

1684
	if (!rec_get_deleted_flag(rec, page_is_comp(page))) {
1685 1686 1687
		/* The new inserted record owns its possible externally
		stored fields */

1688 1689
		offsets = rec_get_offsets(rec, index, offsets,
						ULINT_UNDEFINED, &heap);
unknown's avatar
unknown committed
1690
		btr_cur_unmark_extern_fields(rec, mtr, offsets);
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 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
	/* Restore the old explicit lock state on the record */

	lock_rec_restore_from_page_infimum(rec, page);

        page_cur_move_to_next(page_cursor);

	mem_heap_free(heap);		

	return(DB_SUCCESS);
}

/*****************************************************************
If, in a split, a new supremum record was created as the predecessor of the
updated record, the supremum record must inherit exactly the locks on the
updated record. In the split it may have inherited locks from the successor
of the updated record, which is not correct. This function restores the
right locks for the new supremum. */
static
void
btr_cur_pess_upd_restore_supremum(
/*==============================*/
	rec_t*	rec,	/* in: updated record */
	mtr_t*	mtr)	/* in: mtr */
{
	page_t*	page;
	page_t*	prev_page;
	ulint	space;
	ulint	prev_page_no;
	
	page = buf_frame_align(rec);

	if (page_rec_get_next(page_get_infimum_rec(page)) != rec) {
		/* Updated record is not the first user record on its page */ 
	
		return;
	}

	space = buf_frame_get_space_id(page);
	prev_page_no = btr_page_get_prev(page, mtr);
	
	ut_ad(prev_page_no != FIL_NULL);
	prev_page = buf_page_get_with_no_latch(space, prev_page_no, mtr);

	/* We must already have an x-latch to prev_page! */
	ut_ad(mtr_memo_contains(mtr, buf_block_align(prev_page),
		      				MTR_MEMO_PAGE_X_FIX));

	lock_rec_reset_and_inherit_gap_locks(page_get_supremum_rec(prev_page),
									rec);
}
1743

1744 1745 1746 1747
/*****************************************************************
Performs an update of a record on a page of a tree. It is assumed
that mtr holds an x-latch on the tree and on the cursor page. If the
update is made on the leaf level, to avoid deadlocks, mtr must also
unknown's avatar
unknown committed
1748 1749
own x-latches to brothers of page, if those brothers exist. We assume
here that the ordering fields of the record do not change. */
1750 1751 1752 1753 1754 1755 1756

ulint
btr_cur_pessimistic_update(
/*=======================*/
				/* out: DB_SUCCESS or error code */
	ulint		flags,	/* in: undo logging, locking, and rollback
				flags */
1757 1758 1759
	btr_cur_t*	cursor,	/* in: cursor on the record to update */
	big_rec_t**	big_rec,/* out: big rec vector whose fields have to
				be stored externally by the caller, or NULL */
1760 1761 1762 1763 1764 1765 1766 1767
	upd_t*		update,	/* in: update vector; this is allowed also
				contain trx id and roll ptr fields, but
				the values in update vector have no effect */
	ulint		cmpl_info,/* in: compiler info on secondary index
				updates */
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
{
1768 1769
	big_rec_t*	big_rec_vec	= NULL;
	big_rec_t*	dummy_big_rec;
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
	dict_index_t*	index;
	page_t*		page;
	dict_tree_t*	tree;
	rec_t*		rec;
	page_cur_t*	page_cursor;
	dtuple_t*	new_entry;
	mem_heap_t*	heap;
	ulint		err;
	ulint		optim_err;
	ibool		dummy_reorganized;
	dulint		roll_ptr;
	trx_t*		trx;
	ibool		was_first;
	ibool		success;
	ulint		n_extents	= 0;
unknown's avatar
unknown committed
1785
	ulint		n_reserved;
1786 1787 1788
	ulint*		ext_vect;
	ulint		n_ext_vect;
	ulint		reserve_flag;
unknown's avatar
unknown committed
1789
	ulint*		offsets		= NULL;
1790 1791
	
	*big_rec = NULL;
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
	
	page = btr_cur_get_page(cursor);
	rec = btr_cur_get_rec(cursor);
	index = cursor->index;
	tree = index->tree;

	ut_ad(mtr_memo_contains(mtr, dict_tree_get_lock(tree),
							MTR_MEMO_X_LOCK));
	ut_ad(mtr_memo_contains(mtr, buf_block_align(page),
							MTR_MEMO_PAGE_X_FIX));

	optim_err = btr_cur_optimistic_update(flags, cursor, update,
							cmpl_info, thr, mtr);

	if (optim_err != DB_UNDERFLOW && optim_err != DB_OVERFLOW) {

		return(optim_err);
	}

	/* Do lock checking and undo logging */
	err = btr_cur_upd_lock_and_undo(flags, cursor, update, cmpl_info,
							thr, &roll_ptr);
	if (err != DB_SUCCESS) {

		return(err);
	}

	if (optim_err == DB_OVERFLOW) {
		/* First reserve enough free space for the file segments
		of the index tree, so that the update will not fail because
		of lack of space */

		n_extents = cursor->tree_height / 16 + 3;

1826 1827 1828 1829 1830 1831
		if (flags & BTR_NO_UNDO_LOG_FLAG) {
			reserve_flag = FSP_CLEANING;
		} else {
			reserve_flag = FSP_NORMAL;
		}
		
unknown's avatar
unknown committed
1832
		success = fsp_reserve_free_extents(&n_reserved,
1833
						index->space,
1834
						n_extents, reserve_flag, mtr);
1835 1836 1837 1838 1839 1840 1841 1842
		if (!success) {
			err = DB_OUT_OF_FILE_SPACE;

			return(err);
		}
	}
	
	heap = mem_heap_create(1024);
1843
	offsets = rec_get_offsets(rec, index, NULL, ULINT_UNDEFINED, &heap);
1844 1845 1846 1847 1848

	trx = thr_get_trx(thr);
	
	new_entry = row_rec_to_index_entry(ROW_COPY_DATA, index, rec, heap);

unknown's avatar
unknown committed
1849 1850
	row_upd_index_replace_new_col_vals_index_pos(new_entry, index, update,
									heap);
1851 1852 1853 1854 1855 1856 1857
	if (!(flags & BTR_KEEP_SYS_FLAG)) {
		row_upd_index_entry_sys_field(new_entry, index, DATA_ROLL_PTR,
								roll_ptr);
		row_upd_index_entry_sys_field(new_entry, index, DATA_TRX_ID,
								trx->id);
	}

1858 1859 1860
	if (flags & BTR_NO_UNDO_LOG_FLAG) {
		/* We are in a transaction rollback undoing a row
		update: we must free possible externally stored fields
1861 1862 1863 1864
		which got new values in the update, if they are not
		inherited values. They can be inherited if we have
		updated the primary key to another value, and then
		update it back again. */
1865 1866 1867

		ut_a(big_rec_vec == NULL);
		
unknown's avatar
unknown committed
1868 1869
		btr_rec_free_updated_extern_fields(index, rec, offsets,
			update, TRUE, mtr);
1870 1871 1872 1873 1874
	}

	/* We have to set appropriate extern storage bits in the new
	record to be inserted: we have to remember which fields were such */

unknown's avatar
unknown committed
1875 1876
	ext_vect = mem_heap_alloc(heap, sizeof(ulint)
					* dict_index_get_n_fields(index));
1877
	ut_ad(!page_is_comp(page) || !rec_get_node_ptr_flag(rec));
1878 1879
	offsets = rec_get_offsets(rec, index, offsets,
					ULINT_UNDEFINED, &heap);
unknown's avatar
unknown committed
1880 1881
	n_ext_vect = btr_push_update_extern_fields(ext_vect, offsets, update);

1882 1883 1884
	if (UNIV_UNLIKELY(rec_get_converted_size(index, new_entry) >=
		ut_min(page_get_free_space_of_empty(page_is_comp(page)) / 2,
		REC_MAX_DATA_SIZE))) {
1885

1886 1887
                big_rec_vec = dtuple_convert_big_rec(index, new_entry,
                					ext_vect, n_ext_vect);
1888 1889
		if (big_rec_vec == NULL) {

unknown's avatar
unknown committed
1890
			err = DB_TOO_BIG_RECORD;
1891 1892 1893 1894
			goto return_after_reservations;
		}
	}

1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
	page_cursor = btr_cur_get_page_cur(cursor);

	/* Store state of explicit locks on rec on the page infimum record,
	before deleting rec. The page infimum acts as a dummy carrier of the
	locks, taking care also of lock releases, before we can move the locks
	back on the actual record. There is a special case: if we are
	inserting on the root page and the insert causes a call of
	btr_root_raise_and_insert. Therefore we cannot in the lock system
	delete the lock structs set on the root page even if the root
	page carries just node pointers. */

1906
	lock_rec_store_on_page_infimum(buf_frame_align(rec), rec);
1907 1908

	btr_search_update_hash_on_delete(cursor);
1909

1910
	page_cur_delete_rec(page_cursor, index, offsets, mtr);
1911 1912 1913

	page_cur_move_to_prev(page_cursor);

1914
	rec = btr_cur_insert_if_possible(cursor, new_entry,
1915
						&dummy_reorganized, mtr);
1916
	ut_a(rec || optim_err != DB_UNDERFLOW);
1917

1918
	if (rec) {
1919
		lock_rec_restore_from_page_infimum(rec, page);
unknown's avatar
unknown committed
1920 1921
		rec_set_field_extern_bits(rec, index,
						ext_vect, n_ext_vect, mtr);
unknown's avatar
unknown committed
1922 1923 1924 1925

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

unknown's avatar
unknown committed
1926
		if (!rec_get_deleted_flag(rec, rec_offs_comp(offsets))) {
1927 1928
			/* The new inserted record owns its possible externally
			stored fields */
unknown's avatar
unknown committed
1929
			btr_cur_unmark_extern_fields(rec, mtr, offsets);
1930 1931
		}

1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
		btr_cur_compress_if_useful(cursor, mtr);

		err = DB_SUCCESS;
		goto return_after_reservations;
	}

	if (page_cur_is_before_first(page_cursor)) {
		/* The record to be updated was positioned as the first user
		record on its page */

		was_first = TRUE;
	} else {
		was_first = FALSE;
	}

	/* The first parameter means that no lock checking and undo logging
	is made in the insert */

	err = btr_cur_pessimistic_insert(BTR_NO_UNDO_LOG_FLAG
					| BTR_NO_LOCKING_FLAG
					| BTR_KEEP_SYS_FLAG,
1953 1954
					cursor, new_entry, &rec,
					&dummy_big_rec, NULL, mtr);
1955 1956
	ut_a(rec);
	ut_a(err == DB_SUCCESS);
1957 1958
	ut_a(dummy_big_rec == NULL);

unknown's avatar
unknown committed
1959
	rec_set_field_extern_bits(rec, index, ext_vect, n_ext_vect, mtr);
1960
	offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap);
1961

unknown's avatar
unknown committed
1962
	if (!rec_get_deleted_flag(rec, rec_offs_comp(offsets))) {
1963 1964 1965
		/* The new inserted record owns its possible externally
		stored fields */

unknown's avatar
unknown committed
1966
		btr_cur_unmark_extern_fields(rec, mtr, offsets);
1967 1968
	}

1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
	lock_rec_restore_from_page_infimum(rec, page);

	/* If necessary, restore also the correct lock state for a new,
	preceding supremum record created in a page split. While the old
	record was nonexistent, the supremum might have inherited its locks
	from a wrong record. */

	if (!was_first) {
		btr_cur_pess_upd_restore_supremum(rec, mtr);
	}

return_after_reservations:
unknown's avatar
unknown committed
1981
	mem_heap_free(heap);
1982 1983

	if (n_extents > 0) {
1984
		fil_space_release_free_extents(index->space, n_reserved);
1985 1986
	}

1987 1988
	*big_rec = big_rec_vec;

1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
	return(err);
}

/*==================== B-TREE DELETE MARK AND UNMARK ===============*/

/********************************************************************
Writes the redo log record for delete marking or unmarking of an index
record. */
UNIV_INLINE
void
btr_cur_del_mark_set_clust_rec_log(
/*===============================*/
	ulint		flags,	/* in: flags */
	rec_t*		rec,	/* in: record */
	dict_index_t*	index,	/* in: index of the record */
	ibool		val,	/* in: value to set */
	trx_t*		trx,	/* in: deleting transaction */
	dulint		roll_ptr,/* in: roll ptr to the undo log record */
	mtr_t*		mtr)	/* in: mtr */
{
	byte*	log_ptr;
unknown's avatar
unknown committed
2010 2011
	ut_ad(flags < 256);
	ut_ad(val <= 1);
2012

2013 2014 2015 2016
	ut_ad(!!page_rec_is_comp(rec) == index->table->comp);

	log_ptr = mlog_open_and_write_index(mtr, rec, index,
			page_rec_is_comp(rec)
unknown's avatar
unknown committed
2017 2018 2019
			? MLOG_COMP_REC_CLUST_DELETE_MARK
			: MLOG_REC_CLUST_DELETE_MARK,
			1 + 1 + DATA_ROLL_PTR_LEN + 14 + 2);
2020

unknown's avatar
unknown committed
2021 2022 2023 2024
	if (!log_ptr) {
		/* Logging in mtr is switched off during crash recovery */
		return;
	}
2025 2026 2027 2028 2029 2030 2031 2032

	mach_write_to_1(log_ptr, flags);
	log_ptr++;
	mach_write_to_1(log_ptr, val);
	log_ptr++;

	log_ptr = row_upd_write_sys_vals_to_log(index, trx, roll_ptr, log_ptr,
									mtr);
2033
	mach_write_to_2(log_ptr, ut_align_offset(rec, UNIV_PAGE_SIZE));
2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
	log_ptr += 2;

	mlog_close(mtr, log_ptr);
}

/********************************************************************
Parses the redo log record for delete marking or unmarking of a clustered
index record. */

byte*
btr_cur_parse_del_mark_set_clust_rec(
/*=================================*/
unknown's avatar
unknown committed
2046 2047 2048 2049 2050
				/* out: end of log record or NULL */
	byte*		ptr,	/* in: buffer */
	byte*		end_ptr,/* in: buffer end */
	dict_index_t*	index,	/* in: index corresponding to page */
	page_t*		page)	/* in: page or NULL */
2051 2052
{
	ulint	flags;
2053
	ulint	val;
2054 2055 2056 2057 2058 2059
	ulint	pos;
	dulint	trx_id;
	dulint	roll_ptr;
	ulint	offset;
	rec_t*	rec;

2060
	ut_ad(!page || !!page_is_comp(page) == index->table->comp);
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
	if (end_ptr < ptr + 2) {

		return(NULL);
	}
	
	flags = mach_read_from_1(ptr);
	ptr++;
	val = mach_read_from_1(ptr);
	ptr++;

	ptr = row_upd_parse_sys_vals(ptr, end_ptr, &pos, &trx_id, &roll_ptr);

	if (ptr == NULL) {

		return(NULL);
	}

	if (end_ptr < ptr + 2) {

		return(NULL);
	}

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

unknown's avatar
unknown committed
2087 2088
	ut_a(offset <= UNIV_PAGE_SIZE);

2089 2090 2091 2092
	if (page) {
		rec = page + offset;
	
		if (!(flags & BTR_KEEP_SYS_FLAG)) {
2093
			mem_heap_t*	heap		= NULL;
2094
			ulint		offsets_[REC_OFFS_NORMAL_SIZE];
2095 2096
			*offsets_ = (sizeof offsets_) / sizeof *offsets_;

unknown's avatar
unknown committed
2097
			row_upd_rec_sys_fields_in_recovery(rec,
2098 2099
					rec_get_offsets(rec, index, offsets_,
					ULINT_UNDEFINED, &heap),
unknown's avatar
unknown committed
2100
					pos, trx_id, roll_ptr);
2101
			if (UNIV_LIKELY_NULL(heap)) {
2102 2103
				mem_heap_free(heap);
			}
2104 2105 2106 2107 2108 2109
		}

		/* We do not need to reserve btr_search_latch, as the page
		is only being recovered, and there cannot be a hash index to
		it. */

2110
		rec_set_deleted_flag(rec, page_is_comp(page), val);
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138
	}
	
	return(ptr);
}

/***************************************************************
Marks a clustered index record deleted. Writes an undo log record to
undo log on this delete marking. Writes in the trx id field the id
of the deleting transaction, and in the roll ptr field pointer to the
undo log record created. */

ulint
btr_cur_del_mark_set_clust_rec(
/*===========================*/
				/* out: DB_SUCCESS, DB_LOCK_WAIT, or error
				number */
	ulint		flags,	/* in: undo logging and locking flags */
	btr_cur_t*	cursor,	/* in: cursor */
	ibool		val,	/* in: value to set */
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
{
	dict_index_t*	index;
	buf_block_t*	block;
	dulint		roll_ptr;
	ulint		err;
	rec_t*		rec;
	trx_t*		trx;
2139
	mem_heap_t*	heap		= NULL;
2140
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
2141
	ulint*		offsets		= offsets_;
2142
	*offsets_ = (sizeof offsets_) / sizeof *offsets_;
2143

2144 2145
	rec = btr_cur_get_rec(cursor);
	index = cursor->index;
2146
	ut_ad(!!page_rec_is_comp(rec) == index->table->comp);
2147
	offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap);
unknown's avatar
unknown committed
2148

unknown's avatar
unknown committed
2149
#ifdef UNIV_DEBUG
unknown's avatar
unknown committed
2150
	if (btr_cur_print_record_ops && thr) {
2151
		btr_cur_trx_report(thr_get_trx(thr), index, "del mark ");
2152
		rec_print_new(stderr, rec, offsets);
unknown's avatar
unknown committed
2153
	}
unknown's avatar
unknown committed
2154
#endif /* UNIV_DEBUG */
unknown's avatar
unknown committed
2155

2156
	ut_ad(index->type & DICT_CLUSTERED);
2157
	ut_ad(!rec_get_deleted_flag(rec, rec_offs_comp(offsets)));
2158

unknown's avatar
unknown committed
2159 2160
	err = lock_clust_rec_modify_check_and_lock(flags,
						rec, index, offsets, thr);
2161 2162 2163

	if (err != DB_SUCCESS) {

2164
		if (UNIV_LIKELY_NULL(heap)) {
2165 2166
			mem_heap_free(heap);
		}
2167 2168 2169 2170 2171 2172 2173 2174
		return(err);
	}

	err = trx_undo_report_row_operation(flags, TRX_UNDO_MODIFY_OP, thr,
						index, NULL, NULL, 0, rec,
						&roll_ptr);
	if (err != DB_SUCCESS) {

2175
		if (UNIV_LIKELY_NULL(heap)) {
2176 2177
			mem_heap_free(heap);
		}
2178 2179 2180 2181 2182 2183 2184 2185 2186
		return(err);
	}

	block = buf_block_align(rec);

	if (block->is_hashed) {
		rw_lock_x_lock(&btr_search_latch);
	}

2187
	rec_set_deleted_flag(rec, rec_offs_comp(offsets), val);
2188 2189 2190 2191

	trx = thr_get_trx(thr);
	
	if (!(flags & BTR_KEEP_SYS_FLAG)) {
unknown's avatar
unknown committed
2192
		row_upd_rec_sys_fields(rec, index, offsets, trx, roll_ptr);
2193 2194 2195 2196 2197 2198 2199 2200
	}
	
	if (block->is_hashed) {
		rw_lock_x_unlock(&btr_search_latch);
	}

	btr_cur_del_mark_set_clust_rec_log(flags, rec, index, val, trx,
							roll_ptr, mtr);
2201
	if (UNIV_LIKELY_NULL(heap)) {
2202 2203
		mem_heap_free(heap);
	}
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
	return(DB_SUCCESS);
}

/********************************************************************
Writes the redo log record for a delete mark setting of a secondary
index record. */
UNIV_INLINE
void
btr_cur_del_mark_set_sec_rec_log(
/*=============================*/
unknown's avatar
unknown committed
2214 2215 2216
	rec_t*		rec,	/* in: record */
	ibool		val,	/* in: value to set */
	mtr_t*		mtr)	/* in: mtr */
2217 2218
{
	byte*	log_ptr;
unknown's avatar
unknown committed
2219
	ut_ad(val <= 1);
2220

2221
	log_ptr = mlog_open(mtr, 11 + 1 + 2);
2222

unknown's avatar
unknown committed
2223 2224 2225 2226 2227
	if (!log_ptr) {
		/* Logging in mtr is switched off during crash recovery:
		in that case mlog_open returns NULL */
		return;
	}
2228

2229 2230
	log_ptr = mlog_write_initial_log_record_fast(
			rec, MLOG_REC_SEC_DELETE_MARK, log_ptr, mtr);
2231 2232 2233
	mach_write_to_1(log_ptr, val);
	log_ptr++;

2234
	mach_write_to_2(log_ptr, ut_align_offset(rec, UNIV_PAGE_SIZE));
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
	log_ptr += 2;

	mlog_close(mtr, log_ptr);
}

/********************************************************************
Parses the redo log record for delete marking or unmarking of a secondary
index record. */

byte*
btr_cur_parse_del_mark_set_sec_rec(
/*===============================*/
unknown's avatar
unknown committed
2247 2248 2249 2250
				/* out: end of log record or NULL */
	byte*		ptr,	/* in: buffer */
	byte*		end_ptr,/* in: buffer end */
	page_t*		page)	/* in: page or NULL */
2251
{
2252
	ulint	val;
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
	ulint	offset;
	rec_t*	rec;

	if (end_ptr < ptr + 3) {

		return(NULL);
	}
	
	val = mach_read_from_1(ptr);
	ptr++;

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

unknown's avatar
unknown committed
2267 2268
	ut_a(offset <= UNIV_PAGE_SIZE);

2269 2270 2271 2272 2273 2274 2275
	if (page) {
		rec = page + offset;
	
		/* We do not need to reserve btr_search_latch, as the page
		is only being recovered, and there cannot be a hash index to
		it. */

2276
		rec_set_deleted_flag(rec, page_is_comp(page), val);
2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
	}
	
	return(ptr);
}
	
/***************************************************************
Sets a secondary index record delete mark to TRUE or FALSE. */

ulint
btr_cur_del_mark_set_sec_rec(
/*=========================*/
				/* out: DB_SUCCESS, DB_LOCK_WAIT, or error
				number */
	ulint		flags,	/* in: locking flag */
	btr_cur_t*	cursor,	/* in: cursor */
	ibool		val,	/* in: value to set */
	que_thr_t*	thr,	/* in: query thread */
	mtr_t*		mtr)	/* in: mtr */
{
	buf_block_t*	block;
	rec_t*		rec;
	ulint		err;

	rec = btr_cur_get_rec(cursor);

unknown's avatar
unknown committed
2302
#ifdef UNIV_DEBUG
unknown's avatar
unknown committed
2303
	if (btr_cur_print_record_ops && thr) {
2304 2305
		btr_cur_trx_report(thr_get_trx(thr), cursor->index,
				"del mark ");
2306
		rec_print(stderr, rec, cursor->index);
unknown's avatar
unknown committed
2307
	}
unknown's avatar
unknown committed
2308
#endif /* UNIV_DEBUG */
unknown's avatar
unknown committed
2309

2310 2311 2312 2313 2314 2315 2316 2317
	err = lock_sec_rec_modify_check_and_lock(flags, rec, cursor->index,
									thr);
	if (err != DB_SUCCESS) {

		return(err);
	}

	block = buf_block_align(rec);
2318 2319
	ut_ad(!!page_is_comp(buf_block_get_frame(block))
			== cursor->index->table->comp);
2320 2321 2322 2323 2324
	
	if (block->is_hashed) {
		rw_lock_x_lock(&btr_search_latch);
	}

2325 2326
	rec_set_deleted_flag(rec, page_is_comp(buf_block_get_frame(block)),
									val);
2327 2328 2329 2330 2331

	if (block->is_hashed) {
		rw_lock_x_unlock(&btr_search_latch);
	}

2332
	btr_cur_del_mark_set_sec_rec_log(rec, val, mtr);
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343

	return(DB_SUCCESS);
}

/***************************************************************
Sets a secondary index record delete mark to FALSE. This function is only
used by the insert buffer insert merge mechanism. */

void
btr_cur_del_unmark_for_ibuf(
/*========================*/
unknown's avatar
unknown committed
2344 2345
	rec_t*		rec,	/* in: record to delete unmark */
	mtr_t*		mtr)	/* in: mtr */
2346 2347 2348 2349
{
	/* We do not need to reserve btr_search_latch, as the page has just
	been read to the buffer pool and there cannot be a hash index to it. */

2350
	rec_set_deleted_flag(rec, page_is_comp(buf_frame_align(rec)), FALSE);
2351

2352
	btr_cur_del_mark_set_sec_rec_log(rec, FALSE, mtr);
2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
}

/*==================== B-TREE RECORD REMOVE =========================*/

/*****************************************************************
Tries to compress a page of the tree on the leaf level. It is assumed
that mtr holds an x-latch on the tree and on the cursor page. To avoid
deadlocks, mtr must also own x-latches to brothers of page, if those
brothers exist. NOTE: it is assumed that the caller has reserved enough
free extents so that the compression will always succeed if done! */

void
btr_cur_compress(
/*=============*/
	btr_cur_t*	cursor,	/* in: cursor on the page to compress;
				cursor does not stay valid */
	mtr_t*		mtr)	/* in: mtr */
{
	ut_ad(mtr_memo_contains(mtr,
				dict_tree_get_lock(btr_cur_get_tree(cursor)),
							MTR_MEMO_X_LOCK));
	ut_ad(mtr_memo_contains(mtr, buf_block_align(
						btr_cur_get_page(cursor)),
				MTR_MEMO_PAGE_X_FIX));
	ut_ad(btr_page_get_level(btr_cur_get_page(cursor), mtr) == 0);

	btr_compress(cursor, mtr);	
}

/*****************************************************************
Tries to compress a page of the tree if it seems useful. It is assumed
that mtr holds an x-latch on the tree and on the cursor page. To avoid
deadlocks, mtr must also own x-latches to brothers of page, if those
brothers exist. NOTE: it is assumed that the caller has reserved enough
free extents so that the compression will always succeed if done! */

ibool
btr_cur_compress_if_useful(
/*=======================*/
				/* out: TRUE if compression occurred */
	btr_cur_t*	cursor,	/* in: cursor on the page to compress;
				cursor does not stay valid if compression
				occurs */
	mtr_t*		mtr)	/* in: mtr */
{
	ut_ad(mtr_memo_contains(mtr,
				dict_tree_get_lock(btr_cur_get_tree(cursor)),
							MTR_MEMO_X_LOCK));
	ut_ad(mtr_memo_contains(mtr, buf_block_align(
						btr_cur_get_page(cursor)),
				MTR_MEMO_PAGE_X_FIX));

	if (btr_cur_compress_recommendation(cursor, mtr)) {

		btr_compress(cursor, mtr);

		return(TRUE);
	}

	return(FALSE);
}

/***********************************************************
Removes the record on which the tree cursor is positioned on a leaf page.
It is assumed that the mtr has an x-latch on the page where the cursor is
positioned, but no latch on the whole tree. */

ibool
btr_cur_optimistic_delete(
/*======================*/
				/* out: TRUE if success, i.e., the page
				did not become too empty */
	btr_cur_t*	cursor,	/* in: cursor on leaf page, on the record to
				delete; cursor stays valid: if deletion
				succeeds, on function exit it points to the
				successor of the deleted record */
	mtr_t*		mtr)	/* in: mtr */
{
unknown's avatar
unknown committed
2431 2432 2433
	page_t*		page;
	ulint		max_ins_size;
	rec_t*		rec;
2434
	mem_heap_t*	heap		= NULL;
2435
	ulint		offsets_[REC_OFFS_NORMAL_SIZE];
2436
	ulint*		offsets		= offsets_;
2437
	ibool		no_compress_needed;
2438
	*offsets_ = (sizeof offsets_) / sizeof *offsets_;
2439 2440 2441 2442 2443 2444 2445 2446 2447

	ut_ad(mtr_memo_contains(mtr, buf_block_align(btr_cur_get_page(cursor)),
							MTR_MEMO_PAGE_X_FIX));
	/* This is intended only for leaf page deletions */

	page = btr_cur_get_page(cursor);
	
	ut_ad(btr_page_get_level(page, mtr) == 0);

unknown's avatar
unknown committed
2448
	rec = btr_cur_get_rec(cursor);
2449 2450
	offsets = rec_get_offsets(rec, cursor->index, offsets,
					ULINT_UNDEFINED, &heap);
2451

2452
	no_compress_needed = !rec_offs_any_extern(offsets)
unknown's avatar
unknown committed
2453
			&& btr_cur_can_delete_without_compress(
2454 2455 2456
			cursor, rec_offs_size(offsets), mtr);

	if (no_compress_needed) {
2457

unknown's avatar
unknown committed
2458
		lock_update_delete(rec);
2459 2460 2461 2462 2463

		btr_search_update_hash_on_delete(cursor);

		max_ins_size = page_get_max_insert_size_after_reorganize(page,
									1);
unknown's avatar
unknown committed
2464
		page_cur_delete_rec(btr_cur_get_page_cur(cursor),
2465
						cursor->index, offsets, mtr);
2466 2467 2468 2469 2470

		ibuf_update_free_bits_low(cursor->index, page, max_ins_size,
									mtr);
	}

2471
	if (UNIV_LIKELY_NULL(heap)) {
2472 2473
		mem_heap_free(heap);
	}
2474 2475

	return(no_compress_needed);
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
}

/*****************************************************************
Removes the record on which the tree cursor is positioned. Tries
to compress the page if its fillfactor drops below a threshold
or if it is the only page on the level. It is assumed that mtr holds
an x-latch on the tree and on the cursor page. To avoid deadlocks,
mtr must also own x-latches to brothers of page, if those brothers
exist. */

ibool
btr_cur_pessimistic_delete(
/*=======================*/
				/* out: TRUE if compression occurred */
	ulint*		err,	/* out: DB_SUCCESS or DB_OUT_OF_FILE_SPACE;
				the latter may occur because we may have
				to update node pointers on upper levels,
				and in the case of variable length keys
				these may actually grow in size */
	ibool		has_reserved_extents, /* in: TRUE if the
				caller has already reserved enough free
				extents so that he knows that the operation
				will succeed */
	btr_cur_t*	cursor,	/* in: cursor on the record to delete;
				if compression does not occur, the cursor
				stays valid: it points to successor of
				deleted record on function exit */
2503
	ibool		in_rollback,/* in: TRUE if called in rollback */
2504 2505 2506 2507 2508 2509 2510
	mtr_t*		mtr)	/* in: mtr */
{
	page_t*		page;
	dict_tree_t*	tree;
	rec_t*		rec;
	dtuple_t*	node_ptr;
	ulint		n_extents	= 0;
unknown's avatar
unknown committed
2511
	ulint		n_reserved;
2512 2513
	ibool		success;
	ibool		ret		= FALSE;
2514
	ulint		level;
2515
	mem_heap_t*	heap;
2516
	ulint*		offsets;
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
	
	page = btr_cur_get_page(cursor);
	tree = btr_cur_get_tree(cursor);

	ut_ad(mtr_memo_contains(mtr, dict_tree_get_lock(tree),
							MTR_MEMO_X_LOCK));
	ut_ad(mtr_memo_contains(mtr, buf_block_align(page),
							MTR_MEMO_PAGE_X_FIX));
	if (!has_reserved_extents) {
		/* First reserve enough free space for the file segments
		of the index tree, so that the node pointer updates will
		not fail because of lack of space */

		n_extents = cursor->tree_height / 32 + 1;

unknown's avatar
unknown committed
2532 2533
		success = fsp_reserve_free_extents(&n_reserved,
						cursor->index->space,
2534 2535 2536 2537 2538 2539 2540 2541
						n_extents, FSP_CLEANING, mtr);
		if (!success) {
			*err = DB_OUT_OF_FILE_SPACE;

			return(FALSE);
		}
	}

2542
	heap = mem_heap_create(1024);
unknown's avatar
unknown committed
2543 2544
	rec = btr_cur_get_rec(cursor);

2545 2546 2547
	offsets = rec_get_offsets(rec, cursor->index,
					NULL, ULINT_UNDEFINED, &heap);

unknown's avatar
unknown committed
2548 2549
	/* Free externally stored fields if the record is neither
	a node pointer nor in two-byte format.
2550
	This avoids an unnecessary loop. */
2551
	if (page_is_comp(page)
unknown's avatar
unknown committed
2552 2553 2554
			? !rec_get_node_ptr_flag(rec)
			: !rec_get_1byte_offs_flag(rec)) {
		btr_rec_free_externally_stored_fields(cursor->index,
2555
					rec, offsets, in_rollback, mtr);
unknown's avatar
unknown committed
2556
	}
2557

2558 2559
	if (UNIV_UNLIKELY(page_get_n_recs(page) < 2)
	    && UNIV_UNLIKELY(dict_tree_get_page(btr_cur_get_tree(cursor))
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
					!= buf_frame_get_page_no(page))) {

		/* If there is only one record, drop the whole page in
		btr_discard_page, if this is not the root page */
	
		btr_discard_page(cursor, mtr);

		*err = DB_SUCCESS;
		ret = TRUE;

		goto return_after_reservations;	
	}

	lock_update_delete(rec);
2574
	level = btr_page_get_level(page, mtr);
2575

2576 2577 2578 2579 2580
	if (level > 0
	    && UNIV_UNLIKELY(rec == page_rec_get_next(
				page_get_infimum_rec(page)))) {

		rec_t*	next_rec = page_rec_get_next(rec);
2581 2582 2583 2584 2585 2586 2587

		if (btr_page_get_prev(page, mtr) == FIL_NULL) {

			/* If we delete the leftmost node pointer on a
			non-leaf level, we must mark the new leftmost node
			pointer as the predefined minimum record */

2588 2589
			btr_set_min_rec_mark(next_rec, page_is_comp(page),
						mtr);
2590 2591 2592 2593 2594 2595 2596 2597 2598
		} else {
			/* Otherwise, if we delete the leftmost node pointer
			on a page, we have to change the father node pointer
			so that it is equal to the new leftmost node pointer
			on the page */

			btr_node_ptr_delete(tree, page, mtr);

			node_ptr = dict_tree_build_node_ptr(
2599
					tree, next_rec,
2600
					buf_frame_get_page_no(page),
2601
						heap, level);
2602 2603

			btr_insert_on_non_leaf_level(tree,
2604
					level + 1, node_ptr, mtr);
2605 2606 2607 2608 2609
		}
	} 

	btr_search_update_hash_on_delete(cursor);

2610 2611
	page_cur_delete_rec(btr_cur_get_page_cur(cursor), cursor->index,
							offsets, mtr);
2612 2613 2614 2615 2616 2617

	ut_ad(btr_check_node_ptr(tree, page, mtr));

	*err = DB_SUCCESS;
	
return_after_reservations:
unknown's avatar
unknown committed
2618
	mem_heap_free(heap);
2619 2620 2621 2622 2623 2624

	if (ret == FALSE) {
		ret = btr_cur_compress_if_useful(cursor, mtr);
	}

	if (n_extents > 0) {
unknown's avatar
unknown committed
2625 2626
		fil_space_release_free_extents(cursor->index->space,
								n_reserved);
2627 2628
	}

2629
	return(ret);
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 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
}

/***********************************************************************
Adds path information to the cursor for the current page, for which
the binary search has been performed. */
static
void
btr_cur_add_path_info(
/*==================*/
	btr_cur_t*	cursor,		/* in: cursor positioned on a page */
	ulint		height,		/* in: height of the page in tree;
					0 means leaf node */
	ulint		root_height)	/* in: root node height in tree */
{
	btr_path_t*	slot;
	rec_t*		rec;

	ut_a(cursor->path_arr);

	if (root_height >= BTR_PATH_ARRAY_N_SLOTS - 1) {
		/* Do nothing; return empty path */

		slot = cursor->path_arr;
		slot->nth_rec = ULINT_UNDEFINED;

		return;
	}

	if (height == 0) {
		/* Mark end of slots for path */
		slot = cursor->path_arr + root_height + 1;
		slot->nth_rec = ULINT_UNDEFINED;
	}

	rec = btr_cur_get_rec(cursor);
	
	slot = cursor->path_arr + (root_height - height);

	slot->nth_rec = page_rec_get_n_recs_before(rec);
	slot->n_recs = page_get_n_recs(buf_frame_align(rec));
}

/***********************************************************************
Estimates the number of rows in a given index range. */

unknown's avatar
unknown committed
2675
ib_longlong
2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
btr_estimate_n_rows_in_range(
/*=========================*/
				/* out: estimated number of rows */
	dict_index_t*	index,	/* in: index */
	dtuple_t*	tuple1,	/* in: range start, may also be empty tuple */
	ulint		mode1,	/* in: search mode for range start */
	dtuple_t*	tuple2,	/* in: range end, may also be empty tuple */
	ulint		mode2)	/* in: search mode for range end */
{
	btr_path_t	path1[BTR_PATH_ARRAY_N_SLOTS];
	btr_path_t	path2[BTR_PATH_ARRAY_N_SLOTS];
	btr_cur_t	cursor;
	btr_path_t*	slot1;
	btr_path_t*	slot2;
	ibool		diverged;
unknown's avatar
unknown committed
2691
	ibool           diverged_lot;
2692
	ulint           divergence_level;           
unknown's avatar
unknown committed
2693
	ib_longlong	n_rows;
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
	ulint		i;
	mtr_t		mtr;

	mtr_start(&mtr);

	cursor.path_arr = path1;

	if (dtuple_get_n_fields(tuple1) > 0) {
	
		btr_cur_search_to_nth_level(index, 0, tuple1, mode1,
					BTR_SEARCH_LEAF	| BTR_ESTIMATE,
					&cursor, 0, &mtr);
	} else {
		btr_cur_open_at_index_side(TRUE, index,
					BTR_SEARCH_LEAF	| BTR_ESTIMATE,
					&cursor, &mtr);
	}
	
	mtr_commit(&mtr);

	mtr_start(&mtr);

	cursor.path_arr = path2;

	if (dtuple_get_n_fields(tuple2) > 0) {
	
		btr_cur_search_to_nth_level(index, 0, tuple2, mode2,
					BTR_SEARCH_LEAF	| BTR_ESTIMATE,
					&cursor, 0, &mtr);
	} else {
		btr_cur_open_at_index_side(FALSE, index,
					BTR_SEARCH_LEAF	| BTR_ESTIMATE,
					&cursor, &mtr);
	}
		
	mtr_commit(&mtr);

	/* We have the path information for the range in path1 and path2 */

	n_rows = 1;
unknown's avatar
unknown committed
2734 2735 2736 2737 2738 2739 2740
	diverged = FALSE;           /* This becomes true when the path is not
				    the same any more */
	diverged_lot = FALSE;       /* This becomes true when the paths are
				    not the same or adjacent any more */
	divergence_level = 1000000; /* This is the level where paths diverged
				    a lot */ 
       	for (i = 0; ; i++) {
2741 2742 2743 2744 2745 2746 2747 2748
		ut_ad(i < BTR_PATH_ARRAY_N_SLOTS);
	
		slot1 = path1 + i;
		slot2 = path2 + i;

		if (slot1->nth_rec == ULINT_UNDEFINED
				|| slot2->nth_rec == ULINT_UNDEFINED) {

2749 2750 2751 2752 2753 2754 2755
		        if (i > divergence_level + 1) {
		                /* In trees whose height is > 1 our algorithm
		                tends to underestimate: multiply the estimate
		                by 2: */

		                n_rows = n_rows * 2;
		        }
unknown's avatar
unknown committed
2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767

			/* Do not estimate the number of rows in the range
		        to over 1 / 2 of the estimated rows in the whole
			table */

			if (n_rows > index->table->stat_n_rows / 2) {
			        n_rows = index->table->stat_n_rows / 2;

				/* If there are just 0 or 1 rows in the table,
				then we estimate all rows are in the range */
			  
			        if (n_rows == 0) {
unknown's avatar
unknown committed
2768
				        n_rows = index->table->stat_n_rows;
unknown's avatar
unknown committed
2769 2770 2771
			        }
			}

2772 2773 2774 2775 2776
			return(n_rows);
		}

		if (!diverged && slot1->nth_rec != slot2->nth_rec) {

unknown's avatar
unknown committed
2777 2778
			diverged = TRUE;

2779 2780
			if (slot1->nth_rec < slot2->nth_rec) {
				n_rows = slot2->nth_rec - slot1->nth_rec;
unknown's avatar
unknown committed
2781 2782 2783 2784 2785

				if (n_rows > 1) {
				          diverged_lot = TRUE;
					  divergence_level = i;
				}
2786 2787 2788 2789 2790 2791 2792
			} else {
				/* Maybe the tree has changed between
				searches */

				return(10);
			}

unknown's avatar
unknown committed
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
		} else if (diverged && !diverged_lot) {

		        if (slot1->nth_rec < slot1->n_recs
		            || slot2->nth_rec > 1) {

		                diverged_lot = TRUE;
				divergence_level = i;

				n_rows = 0;

		                if (slot1->nth_rec < slot1->n_recs) {
				        n_rows += slot1->n_recs
					             - slot1->nth_rec;
				}

				if (slot2->nth_rec > 1) {
				        n_rows += slot2->nth_rec - 1;
				}
      			}
		} else if (diverged_lot) {
2813

2814 2815 2816 2817 2818 2819 2820
			n_rows = (n_rows * (slot1->n_recs + slot2->n_recs))
									/ 2;
		}	
	}
}

/***********************************************************************
2821 2822 2823
Estimates the number of different key values in a given index, for
each n-column prefix of the index where n <= dict_index_get_n_unique(index).
The estimates are stored in the array index->stat_n_diff_key_vals. */
2824

2825
void
2826 2827 2828 2829 2830 2831 2832
btr_estimate_number_of_different_key_vals(
/*======================================*/
	dict_index_t*	index)	/* in: index */
{
	btr_cur_t	cursor;
	page_t*		page;
	rec_t*		rec;
2833
	ulint		n_cols;
2834 2835
	ulint		matched_fields;
	ulint		matched_bytes;
unknown's avatar
unknown committed
2836
	ib_longlong*	n_diff;
2837
	ulint		not_empty_flag	= 0;
unknown's avatar
unknown committed
2838
	ulint		total_external_size = 0;
2839
	ulint		i;
2840
	ulint		j;
unknown's avatar
unknown committed
2841
	ulint		add_on;
2842
	mtr_t		mtr;
2843
	mem_heap_t*	heap		= NULL;
2844 2845 2846 2847 2848 2849 2850
	ulint		offsets_rec_[REC_OFFS_NORMAL_SIZE];
	ulint		offsets_next_rec_[REC_OFFS_NORMAL_SIZE];
	ulint*		offsets_rec	= offsets_rec_;
	ulint*		offsets_next_rec= offsets_next_rec_;
	*offsets_rec_ = (sizeof offsets_rec_) / sizeof *offsets_rec_;
	*offsets_next_rec_ =
			(sizeof offsets_next_rec_) / sizeof *offsets_next_rec_;
2851

2852 2853 2854 2855
	n_cols = dict_index_get_n_unique(index);

	n_diff = mem_alloc((n_cols + 1) * sizeof(ib_longlong));

2856
	memset(n_diff, 0, (n_cols + 1) * sizeof(ib_longlong));
2857 2858 2859 2860

	/* We sample some pages in the index to get an estimate */
	
	for (i = 0; i < BTR_KEY_VAL_ESTIMATE_N_PAGES; i++) {
2861
		rec_t*	supremum;
2862 2863 2864 2865
		mtr_start(&mtr);

		btr_cur_open_at_rnd_pos(index, BTR_SEARCH_LEAF, &cursor, &mtr);
		
unknown's avatar
unknown committed
2866 2867 2868 2869 2870
		/* Count the number of different key values for each prefix of
		the key on this index page. If the prefix does not determine
		the index record uniquely in te B-tree, then we subtract one
		because otherwise our algorithm would give a wrong estimate
		for an index where there is just one key value. */
2871 2872 2873

		page = btr_cur_get_page(&cursor);

2874 2875
		supremum = page_get_supremum_rec(page);
		rec = page_rec_get_next(page_get_infimum_rec(page));
2876

2877
		if (rec != supremum) {
2878
			not_empty_flag = 1;
2879 2880
			offsets_rec = rec_get_offsets(rec, index, offsets_rec,
						ULINT_UNDEFINED, &heap);
2881
		}
2882 2883

		while (rec != supremum) {
unknown's avatar
unknown committed
2884
			rec_t*	next_rec = page_rec_get_next(rec);
2885 2886 2887 2888
			if (next_rec == supremum) {
				break;
			}

2889 2890
			matched_fields = 0;
			matched_bytes = 0;
2891 2892
			offsets_next_rec = rec_get_offsets(next_rec, index,
						offsets_next_rec,
2893
						n_cols, &heap);
unknown's avatar
unknown committed
2894 2895

			cmp_rec_rec_with_match(rec, next_rec,
2896
						offsets_rec, offsets_next_rec,
2897
						index, &matched_fields,
2898 2899
						&matched_bytes);

2900
			for (j = matched_fields + 1; j <= n_cols; j++) {
unknown's avatar
unknown committed
2901 2902 2903
				/* We add one if this index record has
				a different prefix from the previous */

2904 2905
				n_diff[j]++;
			}
unknown's avatar
unknown committed
2906 2907

			total_external_size +=
unknown's avatar
unknown committed
2908
				btr_rec_get_externally_stored_len(
2909
								rec, offsets_rec);
unknown's avatar
unknown committed
2910
			
2911 2912 2913 2914 2915 2916 2917 2918 2919
			rec = next_rec;
			/* Initialize offsets_rec for the next round
			and assign the old offsets_rec buffer to
			offsets_next_rec. */
			{
				ulint*	offsets_tmp = offsets_rec;
				offsets_rec = offsets_next_rec;
				offsets_next_rec = offsets_tmp;
			}
2920 2921
		}
		
unknown's avatar
unknown committed
2922

unknown's avatar
unknown committed
2923
		if (n_cols == dict_index_get_n_unique_in_tree(index)) {
unknown's avatar
unknown committed
2924 2925 2926

			/* If there is more than one leaf page in the tree,
			we add one because we know that the first record
unknown's avatar
unknown committed
2927 2928 2929 2930 2931 2932 2933
			on the page certainly had a different prefix than the
			last record on the previous index page in the
			alphabetical order. Before this fix, if there was
			just one big record on each clustered index page, the
			algorithm grossly underestimated the number of rows
			in the table. */

unknown's avatar
unknown committed
2934 2935 2936 2937 2938
			if (btr_page_get_prev(page, &mtr) != FIL_NULL
			    || btr_page_get_next(page, &mtr) != FIL_NULL) {

				n_diff[n_cols]++;
			}
unknown's avatar
unknown committed
2939 2940
		}

2941
		offsets_rec = rec_get_offsets(rec, index, offsets_rec,
2942
						ULINT_UNDEFINED, &heap);
unknown's avatar
unknown committed
2943
		total_external_size +=
unknown's avatar
unknown committed
2944
				btr_rec_get_externally_stored_len(rec,
2945
								offsets_rec);
2946 2947 2948
		mtr_commit(&mtr);
	}

2949 2950 2951 2952
	/* If we saw k borders between different key values on
	BTR_KEY_VAL_ESTIMATE_N_PAGES leaf pages, we can estimate how many
	there will be in index->stat_n_leaf_pages */
	
unknown's avatar
unknown committed
2953 2954 2955 2956
	/* We must take into account that our sample actually represents
	also the pages used for external storage of fields (those pages are
	included in index->stat_n_leaf_pages) */ 

2957 2958
	for (j = 0; j <= n_cols; j++) {
		index->stat_n_diff_key_vals[j] =
unknown's avatar
unknown committed
2959 2960
				(n_diff[j]
				 * (ib_longlong)index->stat_n_leaf_pages
2961
				 + BTR_KEY_VAL_ESTIMATE_N_PAGES - 1
unknown's avatar
unknown committed
2962
				 + total_external_size
2963
				 + not_empty_flag)
unknown's avatar
unknown committed
2964 2965
		                	/ (BTR_KEY_VAL_ESTIMATE_N_PAGES
		                	   + total_external_size);
2966
	
unknown's avatar
unknown committed
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
		/* If the tree is small, smaller than <
		10 * BTR_KEY_VAL_ESTIMATE_N_PAGES + total_external_size, then
		the above estimate is ok. For bigger trees it is common that we
		do not see any borders between key values in the few pages
		we pick. But still there may be BTR_KEY_VAL_ESTIMATE_N_PAGES
		different key values, or even more. Let us try to approximate
		that: */

		add_on = index->stat_n_leaf_pages /
		   (10 * (BTR_KEY_VAL_ESTIMATE_N_PAGES + total_external_size));

		if (add_on > BTR_KEY_VAL_ESTIMATE_N_PAGES) {
			add_on = BTR_KEY_VAL_ESTIMATE_N_PAGES;
		}
		
		index->stat_n_diff_key_vals[j] += add_on;
	}
		
2985
	mem_free(n_diff);
2986
	if (UNIV_LIKELY_NULL(heap)) {
2987 2988
		mem_heap_free(heap);
	}
2989
}
2990 2991 2992

/*================== EXTERNAL STORAGE OF BIG FIELDS ===================*/

unknown's avatar
unknown committed
2993 2994 2995 2996 2997 2998
/***************************************************************
Gets the externally stored size of a record, in units of a database page. */
static
ulint
btr_rec_get_externally_stored_len(
/*==============================*/
unknown's avatar
unknown committed
2999 3000 3001 3002
				/* out: externally stored part,
				in units of a database page */
	rec_t*		rec,	/* in: record */
	const ulint*	offsets)/* in: array returned by rec_get_offsets() */
unknown's avatar
unknown committed
3003 3004 3005 3006 3007 3008 3009 3010
{
	ulint	n_fields;
	byte*	data;
	ulint	local_len;
	ulint	extern_len;
	ulint	total_extern_len = 0;
	ulint	i;

unknown's avatar
unknown committed
3011 3012
	ut_ad(!rec_offs_comp(offsets) || !rec_get_node_ptr_flag(rec));
	n_fields = rec_offs_n_fields(offsets);
unknown's avatar
unknown committed
3013 3014

	for (i = 0; i < n_fields; i++) {
unknown's avatar
unknown committed
3015
		if (rec_offs_nth_extern(offsets, i)) {
unknown's avatar
unknown committed
3016

unknown's avatar
unknown committed
3017
			data = rec_get_nth_field(rec, offsets, i, &local_len);
unknown's avatar
unknown committed
3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031

			local_len -= BTR_EXTERN_FIELD_REF_SIZE;
	
			extern_len = mach_read_from_4(data + local_len
						+ BTR_EXTERN_LEN + 4);

			total_extern_len += ut_calc_align(extern_len,
							UNIV_PAGE_SIZE);
		}
	}

	return(total_extern_len / UNIV_PAGE_SIZE);
}

3032 3033 3034 3035 3036 3037
/***********************************************************************
Sets the ownership bit of an externally stored field in a record. */
static
void
btr_cur_set_ownership_of_extern_field(
/*==================================*/
unknown's avatar
unknown committed
3038 3039 3040 3041 3042
	rec_t*		rec,	/* in: clustered index record */
	const ulint*	offsets,/* in: array returned by rec_get_offsets() */
	ulint		i,	/* in: field number */
	ibool		val,	/* in: value to set */
	mtr_t*		mtr)	/* in: mtr */
3043 3044 3045 3046 3047
{
	byte*	data;
	ulint	local_len;
	ulint	byte_val;

unknown's avatar
unknown committed
3048
	data = rec_get_nth_field(rec, offsets, i, &local_len);
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074
	
	ut_a(local_len >= BTR_EXTERN_FIELD_REF_SIZE);

	local_len -= BTR_EXTERN_FIELD_REF_SIZE;

	byte_val = mach_read_from_1(data + local_len + BTR_EXTERN_LEN);

	if (val) {
		byte_val = byte_val & (~BTR_EXTERN_OWNER_FLAG);
	} else {
		byte_val = byte_val | BTR_EXTERN_OWNER_FLAG;
	}
	
	mlog_write_ulint(data + local_len + BTR_EXTERN_LEN, byte_val,
							MLOG_1BYTE, mtr);
}

/***********************************************************************
Marks not updated extern fields as not-owned by this record. The ownership
is transferred to the updated record which is inserted elsewhere in the
index tree. In purge only the owner of externally stored field is allowed
to free the field. */

void
btr_cur_mark_extern_inherited_fields(
/*=================================*/
unknown's avatar
unknown committed
3075 3076 3077 3078
	rec_t*		rec,	/* in: record in a clustered index */
	const ulint*	offsets,/* in: array returned by rec_get_offsets() */
	upd_t*		update,	/* in: update vector */
	mtr_t*		mtr)	/* in: mtr */
3079 3080 3081 3082 3083
{
	ibool	is_updated;
	ulint	n;
	ulint	j;
	ulint	i;
unknown's avatar
unknown committed
3084 3085 3086 3087

	ut_ad(rec_offs_validate(rec, NULL, offsets));
	ut_ad(!rec_offs_comp(offsets) || !rec_get_node_ptr_flag(rec));
	n = rec_offs_n_fields(offsets);
3088 3089

	for (i = 0; i < n; i++) {
unknown's avatar
unknown committed
3090
		if (rec_offs_nth_extern(offsets, i)) {
3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105
			
			/* Check it is not in updated fields */
			is_updated = FALSE;

			if (update) {
				for (j = 0; j < upd_get_n_fields(update);
								j++) {
					if (upd_get_nth_field(update, j)
							->field_no == i) {
						is_updated = TRUE;
					}
				}
			}

			if (!is_updated) {
unknown's avatar
unknown committed
3106 3107
				btr_cur_set_ownership_of_extern_field(rec,
							offsets, i, FALSE, mtr);
3108 3109 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 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155
			}
		}
	}
}

/***********************************************************************
The complement of the previous function: in an update entry may inherit
some externally stored fields from a record. We must mark them as inherited
in entry, so that they are not freed in a rollback. */

void
btr_cur_mark_dtuple_inherited_extern(
/*=================================*/
	dtuple_t*	entry,		/* in: updated entry to be inserted to
					clustered index */
	ulint*		ext_vec,	/* in: array of extern fields in the
					original record */
	ulint		n_ext_vec,	/* in: number of elements in ext_vec */
	upd_t*		update)		/* in: update vector */
{
	dfield_t* dfield;
	ulint	byte_val;
	byte*	data;
	ulint	len;
	ibool	is_updated;
	ulint	j;
	ulint	i;

	if (ext_vec == NULL) {

		return;
	}
	
	for (i = 0; i < n_ext_vec; i++) {

		/* Check ext_vec[i] is in updated fields */
		is_updated = FALSE;

		for (j = 0; j < upd_get_n_fields(update); j++) {
			if (upd_get_nth_field(update, j)->field_no
							== ext_vec[i]) {
				is_updated = TRUE;
			}
		}

		if (!is_updated) {
			dfield = dtuple_get_nth_field(entry, ext_vec[i]);

unknown's avatar
unknown committed
3156
			data = (byte*) dfield_get_data(dfield);
3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174
			len = dfield_get_len(dfield);
		
			len -= BTR_EXTERN_FIELD_REF_SIZE;

			byte_val = mach_read_from_1(data + len
							+ BTR_EXTERN_LEN);

			byte_val = byte_val | BTR_EXTERN_INHERITED_FLAG;
		
			mach_write_to_1(data + len + BTR_EXTERN_LEN, byte_val);
		}
	}
}

/***********************************************************************
Marks all extern fields in a record as owned by the record. This function
should be called if the delete mark of a record is removed: a not delete
marked record always owns all its extern fields. */
3175
static
3176 3177 3178
void
btr_cur_unmark_extern_fields(
/*=========================*/
unknown's avatar
unknown committed
3179 3180 3181
	rec_t*		rec,	/* in: record in a clustered index */
	mtr_t*		mtr,	/* in: mtr */
	const ulint*	offsets)/* in: array returned by rec_get_offsets() */
3182 3183 3184 3185
{
	ulint	n;
	ulint	i;

unknown's avatar
unknown committed
3186 3187
	ut_ad(!rec_offs_comp(offsets) || !rec_get_node_ptr_flag(rec));
	n = rec_offs_n_fields(offsets);
3188 3189

	for (i = 0; i < n; i++) {
unknown's avatar
unknown committed
3190 3191 3192
		if (rec_offs_nth_extern(offsets, i)) {

			btr_cur_set_ownership_of_extern_field(rec, offsets, i,
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217
								TRUE, mtr);
		}
	}	
}

/***********************************************************************
Marks all extern fields in a dtuple as owned by the record. */

void
btr_cur_unmark_dtuple_extern_fields(
/*================================*/
	dtuple_t*	entry,		/* in: clustered index entry */
	ulint*		ext_vec,	/* in: array of numbers of fields
					which have been stored externally */
	ulint		n_ext_vec)	/* in: number of elements in ext_vec */
{
	dfield_t* dfield;
	ulint	byte_val;
	byte*	data;
	ulint	len;
	ulint	i;

	for (i = 0; i < n_ext_vec; i++) {
		dfield = dtuple_get_nth_field(entry, ext_vec[i]);

unknown's avatar
unknown committed
3218
		data = (byte*) dfield_get_data(dfield);
3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
		len = dfield_get_len(dfield);
		
		len -= BTR_EXTERN_FIELD_REF_SIZE;

		byte_val = mach_read_from_1(data + len + BTR_EXTERN_LEN);

		byte_val = byte_val & (~BTR_EXTERN_OWNER_FLAG);
		
		mach_write_to_1(data + len + BTR_EXTERN_LEN, byte_val);
	}	
}

3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241
/***********************************************************************
Stores the positions of the fields marked as extern storage in the update
vector, and also those fields who are marked as extern storage in rec
and not mentioned in updated fields. We use this function to remember
which fields we must mark as extern storage in a record inserted for an
update. */

ulint
btr_push_update_extern_fields(
/*==========================*/
				/* out: number of values stored in ext_vect */
unknown's avatar
unknown committed
3242
	ulint*		ext_vect,/* in: array of ulints, must be preallocated
3243
				to have space for all fields in rec */
unknown's avatar
unknown committed
3244 3245
	const ulint*	offsets,/* in: array returned by rec_get_offsets() */
	upd_t*		update)	/* in: update vector or NULL */
3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267
{
	ulint	n_pushed	= 0;
	ibool	is_updated;
	ulint	n;
	ulint	j;
	ulint	i;

	if (update) {
		n = upd_get_n_fields(update);
	
		for (i = 0; i < n; i++) {

			if (upd_get_nth_field(update, i)->extern_storage) {

				ext_vect[n_pushed] =
					upd_get_nth_field(update, i)->field_no;

				n_pushed++;
			}
		}
	}

unknown's avatar
unknown committed
3268
	n = rec_offs_n_fields(offsets);
3269 3270

	for (i = 0; i < n; i++) {
unknown's avatar
unknown committed
3271
		if (rec_offs_nth_extern(offsets, i)) {
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332
			
			/* Check it is not in updated fields */
			is_updated = FALSE;

			if (update) {
				for (j = 0; j < upd_get_n_fields(update);
								j++) {
					if (upd_get_nth_field(update, j)
							->field_no == i) {
						is_updated = TRUE;
					}
				}
			}

			if (!is_updated) {
				ext_vect[n_pushed] = i;
				n_pushed++;
			}
		}
	}		

	return(n_pushed);
}

/***********************************************************************
Returns the length of a BLOB part stored on the header page. */
static
ulint
btr_blob_get_part_len(
/*==================*/
				/* out: part length */
	byte*	blob_header)	/* in: blob header */
{
	return(mach_read_from_4(blob_header + BTR_BLOB_HDR_PART_LEN));
}

/***********************************************************************
Returns the page number where the next BLOB part is stored. */
static
ulint
btr_blob_get_next_page_no(
/*======================*/
				/* out: page number or FIL_NULL if
				no more pages */
	byte*	blob_header)	/* in: blob header */
{
	return(mach_read_from_4(blob_header + BTR_BLOB_HDR_NEXT_PAGE_NO));
}

/***********************************************************************
Stores the fields in big_rec_vec to the tablespace and puts pointers to
them in rec. The fields are stored on pages allocated from leaf node
file segment of the index tree. */

ulint
btr_store_big_rec_extern_fields(
/*============================*/
					/* out: DB_SUCCESS or error */
	dict_index_t*	index,		/* in: index of rec; the index tree
					MUST be X-latched */
	rec_t*		rec,		/* in: record */
unknown's avatar
unknown committed
3333 3334 3335 3336
	const ulint*	offsets,	/* in: rec_get_offsets(rec, index);
					the "external storage" flags in offsets
					will not correspond to rec when
					this function returns */
3337 3338
	big_rec_t*	big_rec_vec,	/* in: vector containing fields
					to be stored externally */
unknown's avatar
unknown committed
3339 3340 3341
	mtr_t*		local_mtr __attribute__((unused))) /* in: mtr
                                        containing the latch to rec and to the
                                        tree */
3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356
{
	byte*	data;
	ulint	local_len;
	ulint	extern_len;
	ulint	store_len;
	ulint	page_no;
	page_t*	page;
	ulint	space_id;
	page_t*	prev_page;
	page_t*	rec_page;
	ulint	prev_page_no;
	ulint	hint_page_no;
	ulint	i;
	mtr_t	mtr;

unknown's avatar
unknown committed
3357
	ut_ad(rec_offs_validate(rec, index, offsets));
3358 3359
	ut_ad(mtr_memo_contains(local_mtr, dict_tree_get_lock(index->tree),
							MTR_MEMO_X_LOCK));
3360
	ut_ad(mtr_memo_contains(local_mtr, buf_block_align(rec),
unknown's avatar
unknown committed
3361
							MTR_MEMO_PAGE_X_FIX));
3362 3363 3364 3365 3366 3367 3368 3369 3370
	ut_a(index->type & DICT_CLUSTERED);
							
	space_id = buf_frame_get_space_id(rec);
	
	/* We have to create a file segment to the tablespace
	for each field and put the pointer to the field in rec */

	for (i = 0; i < big_rec_vec->n_fields; i++) {

unknown's avatar
unknown committed
3371 3372
		data = rec_get_nth_field(rec, offsets,
				big_rec_vec->fields[i].field_no, &local_len);
3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405
		ut_a(local_len >= BTR_EXTERN_FIELD_REF_SIZE);
		local_len -= BTR_EXTERN_FIELD_REF_SIZE;
		extern_len = big_rec_vec->fields[i].len;

		ut_a(extern_len > 0);

		prev_page_no = FIL_NULL;

		while (extern_len > 0) {
			mtr_start(&mtr);

			if (prev_page_no == FIL_NULL) {
				hint_page_no = buf_frame_get_page_no(rec) + 1;
			} else {
				hint_page_no = prev_page_no + 1;
			}
			
			page = btr_page_alloc(index->tree, hint_page_no,
						FSP_NO_DIR, 0, &mtr);
			if (page == NULL) {

				mtr_commit(&mtr);

				return(DB_OUT_OF_FILE_SPACE);
			}

			page_no = buf_frame_get_page_no(page);

			if (prev_page_no != FIL_NULL) {
				prev_page = buf_page_get(space_id,
						prev_page_no,
						RW_X_LATCH, &mtr);

3406
#ifdef UNIV_SYNC_DEBUG
3407 3408
				buf_page_dbg_add_level(prev_page,
							SYNC_EXTERN_STORAGE);
3409
#endif /* UNIV_SYNC_DEBUG */
3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443
							
				mlog_write_ulint(prev_page + FIL_PAGE_DATA
						+ BTR_BLOB_HDR_NEXT_PAGE_NO,
						page_no, MLOG_4BYTES, &mtr);
			}

			if (extern_len > (UNIV_PAGE_SIZE - FIL_PAGE_DATA
						- BTR_BLOB_HDR_SIZE
						- FIL_PAGE_DATA_END)) {
				store_len = UNIV_PAGE_SIZE - FIL_PAGE_DATA
						- BTR_BLOB_HDR_SIZE
						- FIL_PAGE_DATA_END;
			} else {
				store_len = extern_len;
			}

			mlog_write_string(page + FIL_PAGE_DATA
						+ BTR_BLOB_HDR_SIZE,
					big_rec_vec->fields[i].data
						+ big_rec_vec->fields[i].len
						- extern_len,
					store_len, &mtr);
			mlog_write_ulint(page + FIL_PAGE_DATA
						+ BTR_BLOB_HDR_PART_LEN,
					store_len, MLOG_4BYTES, &mtr);
			mlog_write_ulint(page + FIL_PAGE_DATA
						+ BTR_BLOB_HDR_NEXT_PAGE_NO,
					FIL_NULL, MLOG_4BYTES, &mtr);
					
			extern_len -= store_len;

			rec_page = buf_page_get(space_id,
						buf_frame_get_page_no(data),
							RW_X_LATCH, &mtr);
3444
#ifdef UNIV_SYNC_DEBUG
3445
			buf_page_dbg_add_level(rec_page, SYNC_NO_ORDER_CHECK);
3446
#endif /* UNIV_SYNC_DEBUG */
3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472
			mlog_write_ulint(data + local_len + BTR_EXTERN_LEN, 0,
						MLOG_4BYTES, &mtr);
			mlog_write_ulint(data + local_len + BTR_EXTERN_LEN + 4,
					big_rec_vec->fields[i].len
								- extern_len,
					MLOG_4BYTES, &mtr);

			if (prev_page_no == FIL_NULL) {
				mlog_write_ulint(data + local_len
							+ BTR_EXTERN_SPACE_ID,
						space_id,
						MLOG_4BYTES, &mtr);

				mlog_write_ulint(data + local_len
							+ BTR_EXTERN_PAGE_NO,
						page_no,
						MLOG_4BYTES, &mtr);
				
				mlog_write_ulint(data + local_len
							+ BTR_EXTERN_OFFSET,
						FIL_PAGE_DATA,
						MLOG_4BYTES, &mtr);

				/* Set the bit denoting that this field
				in rec is stored externally */

unknown's avatar
unknown committed
3473
				rec_set_nth_field_extern_bit(rec, index,
3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488
					big_rec_vec->fields[i].field_no,
					TRUE, &mtr);
			}

			prev_page_no = page_no;

			mtr_commit(&mtr);
		}
	}

	return(DB_SUCCESS);
}

/***********************************************************************
Frees the space in an externally stored field to the file space
3489 3490 3491
management if the field in data is owned the externally stored field,
in a rollback we may have the additional condition that the field must
not be inherited. */
3492 3493 3494 3495 3496

void
btr_free_externally_stored_field(
/*=============================*/
	dict_index_t*	index,		/* in: index of the data, the index
3497 3498 3499 3500 3501 3502 3503
					tree MUST be X-latched; if the tree
					height is 1, then also the root page
					must be X-latched! (this is relevant
					in the case this function is called
					from purge where 'data' is located on
					an undo log page, not an index
					page) */
3504 3505 3506 3507
	byte*		data,		/* in: internally stored data
					+ reference to the externally
					stored part */
	ulint		local_len,	/* in: length of data */
3508 3509 3510
	ibool		do_not_free_inherited,/* in: TRUE if called in a
					rollback and we do not want to free
					inherited fields */
unknown's avatar
unknown committed
3511 3512 3513
	mtr_t*		local_mtr __attribute__((unused))) /* in: mtr 
                                        containing the latch to data an an 
                                        X-latch to the index tree */
3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528
{
	page_t*	page;
	page_t*	rec_page;
	ulint	space_id;
	ulint	page_no;
	ulint	offset;
	ulint	extern_len;
	ulint	next_page_no;
	ulint	part_len;
	mtr_t	mtr;

	ut_a(local_len >= BTR_EXTERN_FIELD_REF_SIZE);
	ut_ad(mtr_memo_contains(local_mtr, dict_tree_get_lock(index->tree),
							MTR_MEMO_X_LOCK));
	ut_ad(mtr_memo_contains(local_mtr, buf_block_align(data),
unknown's avatar
unknown committed
3529
							MTR_MEMO_PAGE_X_FIX));
3530 3531 3532 3533 3534 3535 3536 3537
	ut_a(local_len >= BTR_EXTERN_FIELD_REF_SIZE);
	local_len -= BTR_EXTERN_FIELD_REF_SIZE;
	
	for (;;) {
		mtr_start(&mtr);

		rec_page = buf_page_get(buf_frame_get_space_id(data),
				buf_frame_get_page_no(data), RW_X_LATCH, &mtr);
3538
#ifdef UNIV_SYNC_DEBUG
3539
		buf_page_dbg_add_level(rec_page, SYNC_NO_ORDER_CHECK);
3540
#endif /* UNIV_SYNC_DEBUG */
3541 3542 3543 3544 3545 3546
		space_id = mach_read_from_4(data + local_len
						+ BTR_EXTERN_SPACE_ID);

		page_no = mach_read_from_4(data + local_len
						+ BTR_EXTERN_PAGE_NO);

unknown's avatar
unknown committed
3547 3548
		offset = mach_read_from_4(data + local_len
							+ BTR_EXTERN_OFFSET);
3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561
		extern_len = mach_read_from_4(data + local_len
						+ BTR_EXTERN_LEN + 4);

		/* If extern len is 0, then there is no external storage data
		at all */

		if (extern_len == 0) {

			mtr_commit(&mtr);

			return;
		}

3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581
		if (mach_read_from_1(data + local_len + BTR_EXTERN_LEN)
						& BTR_EXTERN_OWNER_FLAG) {
			/* This field does not own the externally
			stored field: do not free! */

			mtr_commit(&mtr);

			return;
		}

		if (do_not_free_inherited
			&& mach_read_from_1(data + local_len + BTR_EXTERN_LEN)
						& BTR_EXTERN_INHERITED_FLAG) {
			/* Rollback and inherited field: do not free! */

			mtr_commit(&mtr);

			return;
		}
		
3582
		page = buf_page_get(space_id, page_no, RW_X_LATCH, &mtr);
3583
#ifdef UNIV_SYNC_DEBUG
3584
		buf_page_dbg_add_level(page, SYNC_EXTERN_STORAGE);
3585
#endif /* UNIV_SYNC_DEBUG */
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625
		next_page_no = mach_read_from_4(page + FIL_PAGE_DATA
						+ BTR_BLOB_HDR_NEXT_PAGE_NO);

		part_len = btr_blob_get_part_len(page + FIL_PAGE_DATA);

		ut_a(extern_len >= part_len);

		/* We must supply the page level (= 0) as an argument
		because we did not store it on the page (we save the space
		overhead from an index page header. */

		btr_page_free_low(index->tree, page, 0, &mtr);

		mlog_write_ulint(data + local_len + BTR_EXTERN_PAGE_NO,
						next_page_no,
						MLOG_4BYTES, &mtr);
		mlog_write_ulint(data + local_len + BTR_EXTERN_LEN + 4,
						extern_len - part_len,
						MLOG_4BYTES, &mtr);
		if (next_page_no == FIL_NULL) {
			ut_a(extern_len - part_len == 0);
		}

		if (extern_len - part_len == 0) {
			ut_a(next_page_no == FIL_NULL);
		}

		mtr_commit(&mtr);
	}
}

/***************************************************************
Frees the externally stored fields for a record. */

void
btr_rec_free_externally_stored_fields(
/*==================================*/
	dict_index_t*	index,	/* in: index of the data, the index
				tree MUST be X-latched */
	rec_t*		rec,	/* in: record */
unknown's avatar
unknown committed
3626
	const ulint*	offsets,/* in: rec_get_offsets(rec, index) */
3627 3628 3629
	ibool		do_not_free_inherited,/* in: TRUE if called in a
				rollback and we do not want to free
				inherited fields */
3630 3631 3632 3633 3634 3635 3636 3637 3638
	mtr_t*		mtr)	/* in: mini-transaction handle which contains
				an X-latch to record page and to the index
				tree */
{
	ulint	n_fields;
	byte*	data;
	ulint	len;
	ulint	i;

unknown's avatar
unknown committed
3639
	ut_ad(rec_offs_validate(rec, index, offsets));
3640 3641 3642 3643
	ut_ad(mtr_memo_contains(mtr, buf_block_align(rec),
							MTR_MEMO_PAGE_X_FIX));
	/* Free possible externally stored fields in the record */

3644
	ut_ad(index->table->comp == !!rec_offs_comp(offsets));
unknown's avatar
unknown committed
3645
	n_fields = rec_offs_n_fields(offsets);
3646 3647

	for (i = 0; i < n_fields; i++) {
unknown's avatar
unknown committed
3648
		if (rec_offs_nth_extern(offsets, i)) {
3649

unknown's avatar
unknown committed
3650
			data = rec_get_nth_field(rec, offsets, i, &len);
3651 3652
			btr_free_externally_stored_field(index, data, len,
						do_not_free_inherited, mtr);
3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666
		}
	}
}

/***************************************************************
Frees the externally stored fields for a record, if the field is mentioned
in the update vector. */
static
void
btr_rec_free_updated_extern_fields(
/*===============================*/
	dict_index_t*	index,	/* in: index of rec; the index tree MUST be
				X-latched */
	rec_t*		rec,	/* in: record */
unknown's avatar
unknown committed
3667
	const ulint*	offsets,/* in: rec_get_offsets(rec, index) */
3668
	upd_t*		update,	/* in: update vector */
3669 3670 3671
	ibool		do_not_free_inherited,/* in: TRUE if called in a
				rollback and we do not want to free
				inherited fields */
3672 3673 3674 3675 3676 3677 3678 3679 3680
	mtr_t*		mtr)	/* in: mini-transaction handle which contains
				an X-latch to record page and to the tree */
{
	upd_field_t*	ufield;
	ulint		n_fields;
	byte*		data;
	ulint		len;
	ulint		i;

unknown's avatar
unknown committed
3681
	ut_ad(rec_offs_validate(rec, index, offsets));
3682 3683 3684 3685 3686 3687 3688 3689 3690 3691
	ut_ad(mtr_memo_contains(mtr, buf_block_align(rec),
							MTR_MEMO_PAGE_X_FIX));

	/* Free possible externally stored fields in the record */

	n_fields = upd_get_n_fields(update);

	for (i = 0; i < n_fields; i++) {
		ufield = upd_get_nth_field(update, i);
	
unknown's avatar
unknown committed
3692
		if (rec_offs_nth_extern(offsets, ufield->field_no)) {
3693

unknown's avatar
unknown committed
3694 3695
			data = rec_get_nth_field(rec, offsets,
						ufield->field_no, &len);
3696 3697
			btr_free_externally_stored_field(index, data, len,
						do_not_free_inherited, mtr);
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 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759
		}
	}
}

/***********************************************************************
Copies an externally stored field of a record to mem heap. Parameter
data contains a pointer to 'internally' stored part of the field:
possibly some data, and the reference to the externally stored part in
the last 20 bytes of data. */

byte*
btr_copy_externally_stored_field(
/*=============================*/
				/* out: the whole field copied to heap */
	ulint*		len,	/* out: length of the whole field */
	byte*		data,	/* in: 'internally' stored part of the
				field containing also the reference to
				the external part */
	ulint		local_len,/* in: length of data */
	mem_heap_t*	heap)	/* in: mem heap */
{
	page_t*	page;
	ulint	space_id;
	ulint	page_no;
	ulint	offset;
	ulint	extern_len;
	byte*	blob_header;
	ulint	part_len;
	byte*	buf;
	ulint	copied_len;
	mtr_t	mtr;

	ut_a(local_len >= BTR_EXTERN_FIELD_REF_SIZE);

	local_len -= BTR_EXTERN_FIELD_REF_SIZE;

	space_id = mach_read_from_4(data + local_len + BTR_EXTERN_SPACE_ID);

	page_no = mach_read_from_4(data + local_len + BTR_EXTERN_PAGE_NO);

	offset = mach_read_from_4(data + local_len + BTR_EXTERN_OFFSET);

	/* Currently a BLOB cannot be bigger that 4 GB; we
	leave the 4 upper bytes in the length field unused */
	
	extern_len = mach_read_from_4(data + local_len + BTR_EXTERN_LEN + 4);

	buf = mem_heap_alloc(heap, local_len + extern_len);

	ut_memcpy(buf, data, local_len);
	copied_len = local_len;

	if (extern_len == 0) {
		*len = copied_len;
		
		return(buf);
	}

	for (;;) {	
		mtr_start(&mtr);

		page = buf_page_get(space_id, page_no, RW_S_LATCH, &mtr);
3760
#ifdef UNIV_SYNC_DEBUG
3761
		buf_page_dbg_add_level(page, SYNC_EXTERN_STORAGE);
3762
#endif /* UNIV_SYNC_DEBUG */
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
		blob_header = page + offset;

		part_len = btr_blob_get_part_len(blob_header);

		ut_memcpy(buf + copied_len, blob_header + BTR_BLOB_HDR_SIZE,
							part_len);
		copied_len += part_len;

		page_no = btr_blob_get_next_page_no(blob_header);

		/* On other BLOB pages except the first the BLOB header
		always is at the page data start: */

		offset = FIL_PAGE_DATA;

		mtr_commit(&mtr);

		if (page_no == FIL_NULL) {
			ut_a(copied_len == local_len + extern_len);

			*len = copied_len;
		
			return(buf);
		}

		ut_a(copied_len < local_len + extern_len);
	}
}

/***********************************************************************
Copies an externally stored field of a record to mem heap. */

byte*
btr_rec_copy_externally_stored_field(
/*=================================*/
				/* out: the field copied to heap */
unknown's avatar
unknown committed
3799 3800
	rec_t*		rec,	/* in: record */
	const ulint*	offsets,/* in: array returned by rec_get_offsets() */
3801 3802 3803 3804 3805 3806 3807
	ulint		no,	/* in: field number */
	ulint*		len,	/* out: length of the field */
	mem_heap_t*	heap)	/* in: mem heap */
{
	ulint	local_len;
	byte*	data;

unknown's avatar
unknown committed
3808 3809
	ut_ad(rec_offs_validate(rec, NULL, offsets));
	ut_a(rec_offs_nth_extern(offsets, no));
3810 3811 3812 3813 3814 3815 3816 3817 3818 3819

	/* An externally stored field can contain some initial
	data from the field, and in the last 20 bytes it has the
	space id, page number, and offset where the rest of the
	field data is stored, and the data length in addition to
	the data stored locally. We may need to store some data
	locally to get the local record length above the 128 byte
	limit so that field offsets are stored in two bytes, and
	the extern bit is available in those two bytes. */

unknown's avatar
unknown committed
3820
	data = rec_get_nth_field(rec, offsets, no, &local_len);
3821 3822 3823

	return(btr_copy_externally_stored_field(len, data, local_len, heap));
}