xref: /illumos-gate/usr/src/uts/common/fs/zfs/metaslab.c (revision 60405de4d8688d96dd05157c28db3ade5c9bc234)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/zfs_context.h>
29 #include <sys/spa_impl.h>
30 #include <sys/dmu.h>
31 #include <sys/dmu_tx.h>
32 #include <sys/space_map.h>
33 #include <sys/metaslab_impl.h>
34 #include <sys/vdev_impl.h>
35 #include <sys/zio.h>
36 
37 uint64_t metaslab_aliquot = 512ULL << 10;
38 
39 /*
40  * ==========================================================================
41  * Metaslab classes
42  * ==========================================================================
43  */
44 metaslab_class_t *
45 metaslab_class_create(void)
46 {
47 	metaslab_class_t *mc;
48 
49 	mc = kmem_zalloc(sizeof (metaslab_class_t), KM_SLEEP);
50 
51 	mc->mc_rotor = NULL;
52 
53 	return (mc);
54 }
55 
56 void
57 metaslab_class_destroy(metaslab_class_t *mc)
58 {
59 	metaslab_group_t *mg;
60 
61 	while ((mg = mc->mc_rotor) != NULL) {
62 		metaslab_class_remove(mc, mg);
63 		metaslab_group_destroy(mg);
64 	}
65 
66 	kmem_free(mc, sizeof (metaslab_class_t));
67 }
68 
69 void
70 metaslab_class_add(metaslab_class_t *mc, metaslab_group_t *mg)
71 {
72 	metaslab_group_t *mgprev, *mgnext;
73 
74 	ASSERT(mg->mg_class == NULL);
75 
76 	if ((mgprev = mc->mc_rotor) == NULL) {
77 		mg->mg_prev = mg;
78 		mg->mg_next = mg;
79 	} else {
80 		mgnext = mgprev->mg_next;
81 		mg->mg_prev = mgprev;
82 		mg->mg_next = mgnext;
83 		mgprev->mg_next = mg;
84 		mgnext->mg_prev = mg;
85 	}
86 	mc->mc_rotor = mg;
87 	mg->mg_class = mc;
88 }
89 
90 void
91 metaslab_class_remove(metaslab_class_t *mc, metaslab_group_t *mg)
92 {
93 	metaslab_group_t *mgprev, *mgnext;
94 
95 	ASSERT(mg->mg_class == mc);
96 
97 	mgprev = mg->mg_prev;
98 	mgnext = mg->mg_next;
99 
100 	if (mg == mgnext) {
101 		mc->mc_rotor = NULL;
102 	} else {
103 		mc->mc_rotor = mgnext;
104 		mgprev->mg_next = mgnext;
105 		mgnext->mg_prev = mgprev;
106 	}
107 
108 	mg->mg_prev = NULL;
109 	mg->mg_next = NULL;
110 	mg->mg_class = NULL;
111 }
112 
113 /*
114  * ==========================================================================
115  * Metaslab groups
116  * ==========================================================================
117  */
118 static int
119 metaslab_compare(const void *x1, const void *x2)
120 {
121 	const metaslab_t *m1 = x1;
122 	const metaslab_t *m2 = x2;
123 
124 	if (m1->ms_weight < m2->ms_weight)
125 		return (1);
126 	if (m1->ms_weight > m2->ms_weight)
127 		return (-1);
128 
129 	/*
130 	 * If the weights are identical, use the offset to force uniqueness.
131 	 */
132 	if (m1->ms_map.sm_start < m2->ms_map.sm_start)
133 		return (-1);
134 	if (m1->ms_map.sm_start > m2->ms_map.sm_start)
135 		return (1);
136 
137 	ASSERT3P(m1, ==, m2);
138 
139 	return (0);
140 }
141 
142 metaslab_group_t *
143 metaslab_group_create(metaslab_class_t *mc, vdev_t *vd)
144 {
145 	metaslab_group_t *mg;
146 
147 	mg = kmem_zalloc(sizeof (metaslab_group_t), KM_SLEEP);
148 	mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
149 	avl_create(&mg->mg_metaslab_tree, metaslab_compare,
150 	    sizeof (metaslab_t), offsetof(struct metaslab, ms_group_node));
151 	mg->mg_aliquot = metaslab_aliquot * MAX(1, vd->vdev_children);
152 	mg->mg_vd = vd;
153 	metaslab_class_add(mc, mg);
154 
155 	return (mg);
156 }
157 
158 void
159 metaslab_group_destroy(metaslab_group_t *mg)
160 {
161 	avl_destroy(&mg->mg_metaslab_tree);
162 	mutex_destroy(&mg->mg_lock);
163 	kmem_free(mg, sizeof (metaslab_group_t));
164 }
165 
166 static void
167 metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
168 {
169 	mutex_enter(&mg->mg_lock);
170 	ASSERT(msp->ms_group == NULL);
171 	msp->ms_group = mg;
172 	msp->ms_weight = 0;
173 	avl_add(&mg->mg_metaslab_tree, msp);
174 	mutex_exit(&mg->mg_lock);
175 }
176 
177 static void
178 metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
179 {
180 	mutex_enter(&mg->mg_lock);
181 	ASSERT(msp->ms_group == mg);
182 	avl_remove(&mg->mg_metaslab_tree, msp);
183 	msp->ms_group = NULL;
184 	mutex_exit(&mg->mg_lock);
185 }
186 
187 static void
188 metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
189 {
190 	/*
191 	 * Although in principle the weight can be any value, in
192 	 * practice we do not use values in the range [1, 510].
193 	 */
194 	ASSERT(weight >= SPA_MINBLOCKSIZE-1 || weight == 0);
195 	ASSERT(MUTEX_HELD(&msp->ms_lock));
196 
197 	mutex_enter(&mg->mg_lock);
198 	ASSERT(msp->ms_group == mg);
199 	avl_remove(&mg->mg_metaslab_tree, msp);
200 	msp->ms_weight = weight;
201 	avl_add(&mg->mg_metaslab_tree, msp);
202 	mutex_exit(&mg->mg_lock);
203 }
204 
205 /*
206  * ==========================================================================
207  * The first-fit block allocator
208  * ==========================================================================
209  */
210 static void
211 metaslab_ff_load(space_map_t *sm)
212 {
213 	ASSERT(sm->sm_ppd == NULL);
214 	sm->sm_ppd = kmem_zalloc(64 * sizeof (uint64_t), KM_SLEEP);
215 }
216 
217 static void
218 metaslab_ff_unload(space_map_t *sm)
219 {
220 	kmem_free(sm->sm_ppd, 64 * sizeof (uint64_t));
221 	sm->sm_ppd = NULL;
222 }
223 
224 static uint64_t
225 metaslab_ff_alloc(space_map_t *sm, uint64_t size)
226 {
227 	avl_tree_t *t = &sm->sm_root;
228 	uint64_t align = size & -size;
229 	uint64_t *cursor = (uint64_t *)sm->sm_ppd + highbit(align) - 1;
230 	space_seg_t *ss, ssearch;
231 	avl_index_t where;
232 
233 	ssearch.ss_start = *cursor;
234 	ssearch.ss_end = *cursor + size;
235 
236 	ss = avl_find(t, &ssearch, &where);
237 	if (ss == NULL)
238 		ss = avl_nearest(t, where, AVL_AFTER);
239 
240 	while (ss != NULL) {
241 		uint64_t offset = P2ROUNDUP(ss->ss_start, align);
242 
243 		if (offset + size <= ss->ss_end) {
244 			*cursor = offset + size;
245 			return (offset);
246 		}
247 		ss = AVL_NEXT(t, ss);
248 	}
249 
250 	/*
251 	 * If we know we've searched the whole map (*cursor == 0), give up.
252 	 * Otherwise, reset the cursor to the beginning and try again.
253 	 */
254 	if (*cursor == 0)
255 		return (-1ULL);
256 
257 	*cursor = 0;
258 	return (metaslab_ff_alloc(sm, size));
259 }
260 
261 /* ARGSUSED */
262 static void
263 metaslab_ff_claim(space_map_t *sm, uint64_t start, uint64_t size)
264 {
265 	/* No need to update cursor */
266 }
267 
268 /* ARGSUSED */
269 static void
270 metaslab_ff_free(space_map_t *sm, uint64_t start, uint64_t size)
271 {
272 	/* No need to update cursor */
273 }
274 
275 static space_map_ops_t metaslab_ff_ops = {
276 	metaslab_ff_load,
277 	metaslab_ff_unload,
278 	metaslab_ff_alloc,
279 	metaslab_ff_claim,
280 	metaslab_ff_free
281 };
282 
283 /*
284  * ==========================================================================
285  * Metaslabs
286  * ==========================================================================
287  */
288 metaslab_t *
289 metaslab_init(metaslab_group_t *mg, space_map_obj_t *smo,
290 	uint64_t start, uint64_t size, uint64_t txg)
291 {
292 	vdev_t *vd = mg->mg_vd;
293 	metaslab_t *msp;
294 
295 	msp = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
296 
297 	msp->ms_smo_syncing = *smo;
298 
299 	/*
300 	 * We create the main space map here, but we don't create the
301 	 * allocmaps and freemaps until metaslab_sync_done().  This serves
302 	 * two purposes: it allows metaslab_sync_done() to detect the
303 	 * addition of new space; and for debugging, it ensures that we'd
304 	 * data fault on any attempt to use this metaslab before it's ready.
305 	 */
306 	space_map_create(&msp->ms_map, start, size,
307 	    vd->vdev_ashift, &msp->ms_lock);
308 
309 	metaslab_group_add(mg, msp);
310 
311 	/*
312 	 * If we're opening an existing pool (txg == 0) or creating
313 	 * a new one (txg == TXG_INITIAL), all space is available now.
314 	 * If we're adding space to an existing pool, the new space
315 	 * does not become available until after this txg has synced.
316 	 */
317 	if (txg <= TXG_INITIAL)
318 		metaslab_sync_done(msp, 0);
319 
320 	if (txg != 0) {
321 		/*
322 		 * The vdev is dirty, but the metaslab isn't -- it just needs
323 		 * to have metaslab_sync_done() invoked from vdev_sync_done().
324 		 * [We could just dirty the metaslab, but that would cause us
325 		 * to allocate a space map object for it, which is wasteful
326 		 * and would mess up the locality logic in metaslab_weight().]
327 		 */
328 		ASSERT(TXG_CLEAN(txg) == spa_last_synced_txg(vd->vdev_spa));
329 		vdev_dirty(vd, 0, NULL, txg);
330 		vdev_dirty(vd, VDD_METASLAB, msp, TXG_CLEAN(txg));
331 	}
332 
333 	return (msp);
334 }
335 
336 void
337 metaslab_fini(metaslab_t *msp)
338 {
339 	metaslab_group_t *mg = msp->ms_group;
340 	int t;
341 
342 	vdev_space_update(mg->mg_vd, -msp->ms_map.sm_size,
343 	    -msp->ms_smo.smo_alloc);
344 
345 	metaslab_group_remove(mg, msp);
346 
347 	mutex_enter(&msp->ms_lock);
348 
349 	space_map_unload(&msp->ms_map);
350 	space_map_destroy(&msp->ms_map);
351 
352 	for (t = 0; t < TXG_SIZE; t++) {
353 		space_map_destroy(&msp->ms_allocmap[t]);
354 		space_map_destroy(&msp->ms_freemap[t]);
355 	}
356 
357 	mutex_exit(&msp->ms_lock);
358 
359 	kmem_free(msp, sizeof (metaslab_t));
360 }
361 
362 #define	METASLAB_WEIGHT_PRIMARY		(1ULL << 63)
363 #define	METASLAB_WEIGHT_SECONDARY	(1ULL << 62)
364 #define	METASLAB_ACTIVE_MASK		\
365 	(METASLAB_WEIGHT_PRIMARY | METASLAB_WEIGHT_SECONDARY)
366 #define	METASLAB_SMO_BONUS_MULTIPLIER	2
367 
368 static uint64_t
369 metaslab_weight(metaslab_t *msp)
370 {
371 	metaslab_group_t *mg = msp->ms_group;
372 	space_map_t *sm = &msp->ms_map;
373 	space_map_obj_t *smo = &msp->ms_smo;
374 	vdev_t *vd = mg->mg_vd;
375 	uint64_t weight, space;
376 
377 	ASSERT(MUTEX_HELD(&msp->ms_lock));
378 
379 	/*
380 	 * The baseline weight is the metaslab's free space.
381 	 */
382 	space = sm->sm_size - smo->smo_alloc;
383 	weight = space;
384 
385 	/*
386 	 * Modern disks have uniform bit density and constant angular velocity.
387 	 * Therefore, the outer recording zones are faster (higher bandwidth)
388 	 * than the inner zones by the ratio of outer to inner track diameter,
389 	 * which is typically around 2:1.  We account for this by assigning
390 	 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
391 	 * In effect, this means that we'll select the metaslab with the most
392 	 * free bandwidth rather than simply the one with the most free space.
393 	 */
394 	weight = 2 * weight -
395 	    ((sm->sm_start >> vd->vdev_ms_shift) * weight) / vd->vdev_ms_count;
396 	ASSERT(weight >= space && weight <= 2 * space);
397 
398 	/*
399 	 * For locality, assign higher weight to metaslabs we've used before.
400 	 */
401 	if (smo->smo_object != 0)
402 		weight *= METASLAB_SMO_BONUS_MULTIPLIER;
403 	ASSERT(weight >= space &&
404 	    weight <= 2 * METASLAB_SMO_BONUS_MULTIPLIER * space);
405 
406 	/*
407 	 * If this metaslab is one we're actively using, adjust its weight to
408 	 * make it preferable to any inactive metaslab so we'll polish it off.
409 	 */
410 	weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
411 
412 	return (weight);
413 }
414 
415 static int
416 metaslab_activate(metaslab_t *msp, uint64_t activation_weight)
417 {
418 	space_map_t *sm = &msp->ms_map;
419 
420 	ASSERT(MUTEX_HELD(&msp->ms_lock));
421 
422 	if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
423 		int error = space_map_load(sm, &metaslab_ff_ops,
424 		    SM_FREE, &msp->ms_smo,
425 		    msp->ms_group->mg_vd->vdev_spa->spa_meta_objset);
426 		if (error) {
427 			metaslab_group_sort(msp->ms_group, msp, 0);
428 			return (error);
429 		}
430 		metaslab_group_sort(msp->ms_group, msp,
431 		    msp->ms_weight | activation_weight);
432 	}
433 	ASSERT(sm->sm_loaded);
434 	ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
435 
436 	return (0);
437 }
438 
439 static void
440 metaslab_passivate(metaslab_t *msp, uint64_t size)
441 {
442 	/*
443 	 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
444 	 * this metaslab again.  In that case, it had better be empty,
445 	 * or we would be leaving space on the table.
446 	 */
447 	ASSERT(size >= SPA_MINBLOCKSIZE || msp->ms_map.sm_space == 0);
448 	metaslab_group_sort(msp->ms_group, msp, MIN(msp->ms_weight, size));
449 	ASSERT((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0);
450 }
451 
452 /*
453  * Write a metaslab to disk in the context of the specified transaction group.
454  */
455 void
456 metaslab_sync(metaslab_t *msp, uint64_t txg)
457 {
458 	vdev_t *vd = msp->ms_group->mg_vd;
459 	spa_t *spa = vd->vdev_spa;
460 	objset_t *mos = spa->spa_meta_objset;
461 	space_map_t *allocmap = &msp->ms_allocmap[txg & TXG_MASK];
462 	space_map_t *freemap = &msp->ms_freemap[txg & TXG_MASK];
463 	space_map_t *freed_map = &msp->ms_freemap[TXG_CLEAN(txg) & TXG_MASK];
464 	space_map_t *sm = &msp->ms_map;
465 	space_map_obj_t *smo = &msp->ms_smo_syncing;
466 	dmu_buf_t *db;
467 	dmu_tx_t *tx;
468 	int t;
469 
470 	tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
471 
472 	/*
473 	 * The only state that can actually be changing concurrently with
474 	 * metaslab_sync() is the metaslab's ms_map.  No other thread can
475 	 * be modifying this txg's allocmap, freemap, freed_map, or smo.
476 	 * Therefore, we only hold ms_lock to satify space_map ASSERTs.
477 	 * We drop it whenever we call into the DMU, because the DMU
478 	 * can call down to us (e.g. via zio_free()) at any time.
479 	 */
480 	mutex_enter(&msp->ms_lock);
481 
482 	if (smo->smo_object == 0) {
483 		ASSERT(smo->smo_objsize == 0);
484 		ASSERT(smo->smo_alloc == 0);
485 		mutex_exit(&msp->ms_lock);
486 		smo->smo_object = dmu_object_alloc(mos,
487 		    DMU_OT_SPACE_MAP, 1 << SPACE_MAP_BLOCKSHIFT,
488 		    DMU_OT_SPACE_MAP_HEADER, sizeof (*smo), tx);
489 		ASSERT(smo->smo_object != 0);
490 		dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
491 		    (sm->sm_start >> vd->vdev_ms_shift),
492 		    sizeof (uint64_t), &smo->smo_object, tx);
493 		mutex_enter(&msp->ms_lock);
494 	}
495 
496 	space_map_walk(freemap, space_map_add, freed_map);
497 
498 	if (sm->sm_loaded && spa_sync_pass(spa) == 1 && smo->smo_objsize >=
499 	    2 * sizeof (uint64_t) * avl_numnodes(&sm->sm_root)) {
500 		/*
501 		 * The in-core space map representation is twice as compact
502 		 * as the on-disk one, so it's time to condense the latter
503 		 * by generating a pure allocmap from first principles.
504 		 *
505 		 * This metaslab is 100% allocated,
506 		 * minus the content of the in-core map (sm),
507 		 * minus what's been freed this txg (freed_map),
508 		 * minus allocations from txgs in the future
509 		 * (because they haven't been committed yet).
510 		 */
511 		space_map_vacate(allocmap, NULL, NULL);
512 		space_map_vacate(freemap, NULL, NULL);
513 
514 		space_map_add(allocmap, allocmap->sm_start, allocmap->sm_size);
515 
516 		space_map_walk(sm, space_map_remove, allocmap);
517 		space_map_walk(freed_map, space_map_remove, allocmap);
518 
519 		for (t = 1; t < TXG_CONCURRENT_STATES; t++)
520 			space_map_walk(&msp->ms_allocmap[(txg + t) & TXG_MASK],
521 			    space_map_remove, allocmap);
522 
523 		mutex_exit(&msp->ms_lock);
524 		space_map_truncate(smo, mos, tx);
525 		mutex_enter(&msp->ms_lock);
526 	}
527 
528 	space_map_sync(allocmap, SM_ALLOC, smo, mos, tx);
529 	space_map_sync(freemap, SM_FREE, smo, mos, tx);
530 
531 	mutex_exit(&msp->ms_lock);
532 
533 	VERIFY(0 == dmu_bonus_hold(mos, smo->smo_object, FTAG, &db));
534 	dmu_buf_will_dirty(db, tx);
535 	ASSERT3U(db->db_size, ==, sizeof (*smo));
536 	bcopy(smo, db->db_data, db->db_size);
537 	dmu_buf_rele(db, FTAG);
538 
539 	dmu_tx_commit(tx);
540 }
541 
542 /*
543  * Called after a transaction group has completely synced to mark
544  * all of the metaslab's free space as usable.
545  */
546 void
547 metaslab_sync_done(metaslab_t *msp, uint64_t txg)
548 {
549 	space_map_obj_t *smo = &msp->ms_smo;
550 	space_map_obj_t *smosync = &msp->ms_smo_syncing;
551 	space_map_t *sm = &msp->ms_map;
552 	space_map_t *freed_map = &msp->ms_freemap[TXG_CLEAN(txg) & TXG_MASK];
553 	metaslab_group_t *mg = msp->ms_group;
554 	vdev_t *vd = mg->mg_vd;
555 	int t;
556 
557 	mutex_enter(&msp->ms_lock);
558 
559 	/*
560 	 * If this metaslab is just becoming available, initialize its
561 	 * allocmaps and freemaps and add its capacity to the vdev.
562 	 */
563 	if (freed_map->sm_size == 0) {
564 		for (t = 0; t < TXG_SIZE; t++) {
565 			space_map_create(&msp->ms_allocmap[t], sm->sm_start,
566 			    sm->sm_size, sm->sm_shift, sm->sm_lock);
567 			space_map_create(&msp->ms_freemap[t], sm->sm_start,
568 			    sm->sm_size, sm->sm_shift, sm->sm_lock);
569 		}
570 		vdev_space_update(vd, sm->sm_size, 0);
571 	}
572 
573 	vdev_space_update(vd, 0, smosync->smo_alloc - smo->smo_alloc);
574 
575 	ASSERT(msp->ms_allocmap[txg & TXG_MASK].sm_space == 0);
576 	ASSERT(msp->ms_freemap[txg & TXG_MASK].sm_space == 0);
577 
578 	/*
579 	 * If there's a space_map_load() in progress, wait for it to complete
580 	 * so that we have a consistent view of the in-core space map.
581 	 * Then, add everything we freed in this txg to the map.
582 	 */
583 	space_map_load_wait(sm);
584 	space_map_vacate(freed_map, sm->sm_loaded ? space_map_free : NULL, sm);
585 
586 	*smo = *smosync;
587 
588 	/*
589 	 * If the map is loaded but no longer active, evict it as soon as all
590 	 * future allocations have synced.  (If we unloaded it now and then
591 	 * loaded a moment later, the map wouldn't reflect those allocations.)
592 	 */
593 	if (sm->sm_loaded && (msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
594 		int evictable = 1;
595 
596 		for (t = 1; t < TXG_CONCURRENT_STATES; t++)
597 			if (msp->ms_allocmap[(txg + t) & TXG_MASK].sm_space)
598 				evictable = 0;
599 
600 		if (evictable)
601 			space_map_unload(sm);
602 	}
603 
604 	metaslab_group_sort(mg, msp, metaslab_weight(msp));
605 
606 	mutex_exit(&msp->ms_lock);
607 }
608 
609 static uint64_t
610 metaslab_distance(metaslab_t *msp, dva_t *dva)
611 {
612 	uint64_t ms_shift = msp->ms_group->mg_vd->vdev_ms_shift;
613 	uint64_t offset = DVA_GET_OFFSET(dva) >> ms_shift;
614 	uint64_t start = msp->ms_map.sm_start >> ms_shift;
615 
616 	if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
617 		return (1ULL << 63);
618 
619 	if (offset < start)
620 		return ((start - offset) << ms_shift);
621 	if (offset > start)
622 		return ((offset - start) << ms_shift);
623 	return (0);
624 }
625 
626 static uint64_t
627 metaslab_group_alloc(metaslab_group_t *mg, uint64_t size, uint64_t txg,
628     uint64_t min_distance, dva_t *dva, int d)
629 {
630 	metaslab_t *msp = NULL;
631 	uint64_t offset = -1ULL;
632 	avl_tree_t *t = &mg->mg_metaslab_tree;
633 	uint64_t activation_weight;
634 	uint64_t target_distance;
635 	int i;
636 
637 	activation_weight = METASLAB_WEIGHT_PRIMARY;
638 	for (i = 0; i < d; i++)
639 		if (DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id)
640 			activation_weight = METASLAB_WEIGHT_SECONDARY;
641 
642 	for (;;) {
643 		mutex_enter(&mg->mg_lock);
644 		for (msp = avl_first(t); msp; msp = AVL_NEXT(t, msp)) {
645 			if (msp->ms_weight < size) {
646 				mutex_exit(&mg->mg_lock);
647 				return (-1ULL);
648 			}
649 
650 			if (activation_weight == METASLAB_WEIGHT_PRIMARY)
651 				break;
652 
653 			target_distance = min_distance +
654 			    (msp->ms_smo.smo_alloc ? 0 : min_distance >> 1);
655 
656 			for (i = 0; i < d; i++)
657 				if (metaslab_distance(msp, &dva[i]) <
658 				    target_distance)
659 					break;
660 			if (i == d)
661 				break;
662 		}
663 		mutex_exit(&mg->mg_lock);
664 		if (msp == NULL)
665 			return (-1ULL);
666 
667 		mutex_enter(&msp->ms_lock);
668 
669 		if ((msp->ms_weight & METASLAB_WEIGHT_SECONDARY) &&
670 		    activation_weight == METASLAB_WEIGHT_PRIMARY) {
671 			metaslab_passivate(msp,
672 			    msp->ms_weight & ~METASLAB_ACTIVE_MASK);
673 			mutex_exit(&msp->ms_lock);
674 			continue;
675 		}
676 
677 		if (metaslab_activate(msp, activation_weight) != 0) {
678 			mutex_exit(&msp->ms_lock);
679 			continue;
680 		}
681 
682 		if ((offset = space_map_alloc(&msp->ms_map, size)) != -1ULL)
683 			break;
684 
685 		metaslab_passivate(msp, size - 1);
686 
687 		mutex_exit(&msp->ms_lock);
688 	}
689 
690 	if (msp->ms_allocmap[txg & TXG_MASK].sm_space == 0)
691 		vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
692 
693 	space_map_add(&msp->ms_allocmap[txg & TXG_MASK], offset, size);
694 
695 	mutex_exit(&msp->ms_lock);
696 
697 	return (offset);
698 }
699 
700 /*
701  * Allocate a block for the specified i/o.
702  */
703 static int
704 metaslab_alloc_dva(spa_t *spa, uint64_t psize, dva_t *dva, int d,
705     dva_t *hintdva, uint64_t txg)
706 {
707 	metaslab_group_t *mg, *rotor;
708 	metaslab_class_t *mc;
709 	vdev_t *vd;
710 	int dshift = 3;
711 	int all_zero;
712 	uint64_t offset = -1ULL;
713 	uint64_t asize;
714 	uint64_t distance;
715 
716 	ASSERT(!DVA_IS_VALID(&dva[d]));
717 
718 	mc = spa_metaslab_class_select(spa);
719 
720 	/*
721 	 * Start at the rotor and loop through all mgs until we find something.
722 	 * Note that there's no locking on mc_rotor or mc_allocated because
723 	 * nothing actually breaks if we miss a few updates -- we just won't
724 	 * allocate quite as evenly.  It all balances out over time.
725 	 *
726 	 * If we are doing ditto blocks, try to spread them across consecutive
727 	 * vdevs.  If we're forced to reuse a vdev before we've allocated
728 	 * all of our ditto blocks, then try and spread them out on that
729 	 * vdev as much as possible.  If it turns out to not be possible,
730 	 * gradually lower our standards until anything becomes acceptable.
731 	 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
732 	 * gives us hope of containing our fault domains to something we're
733 	 * able to reason about.  Otherwise, any two top-level vdev failures
734 	 * will guarantee the loss of data.  With consecutive allocation,
735 	 * only two adjacent top-level vdev failures will result in data loss.
736 	 *
737 	 * If we are doing gang blocks (hintdva is non-NULL), try to keep
738 	 * ourselves on the same vdev as our gang block header.  That
739 	 * way, we can hope for locality in vdev_cache, plus it makes our
740 	 * fault domains something tractable.
741 	 */
742 	if (hintdva) {
743 		vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
744 		mg = vd->vdev_mg;
745 	} else if (d != 0) {
746 		vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
747 		mg = vd->vdev_mg->mg_next;
748 	} else {
749 		mg = mc->mc_rotor;
750 	}
751 	rotor = mg;
752 
753 top:
754 	all_zero = B_TRUE;
755 	do {
756 		vd = mg->mg_vd;
757 
758 		distance = vd->vdev_asize >> dshift;
759 		if (distance <= (1ULL << vd->vdev_ms_shift))
760 			distance = 0;
761 		else
762 			all_zero = B_FALSE;
763 
764 		asize = vdev_psize_to_asize(vd, psize);
765 		ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
766 
767 		offset = metaslab_group_alloc(mg, asize, txg, distance, dva, d);
768 		if (offset != -1ULL) {
769 			/*
770 			 * If we've just selected this metaslab group,
771 			 * figure out whether the corresponding vdev is
772 			 * over- or under-used relative to the pool,
773 			 * and set an allocation bias to even it out.
774 			 */
775 			if (mc->mc_allocated == 0) {
776 				vdev_stat_t *vs = &vd->vdev_stat;
777 				uint64_t alloc, space;
778 				int64_t vu, su;
779 
780 				alloc = spa_get_alloc(spa);
781 				space = spa_get_space(spa);
782 
783 				/*
784 				 * Determine percent used in units of 0..1024.
785 				 * (This is just to avoid floating point.)
786 				 */
787 				vu = (vs->vs_alloc << 10) / (vs->vs_space + 1);
788 				su = (alloc << 10) / (space + 1);
789 
790 				/*
791 				 * Bias by at most +/- 25% of the aliquot.
792 				 */
793 				mg->mg_bias = ((su - vu) *
794 				    (int64_t)mg->mg_aliquot) / (1024 * 4);
795 			}
796 
797 			if (atomic_add_64_nv(&mc->mc_allocated, asize) >=
798 			    mg->mg_aliquot + mg->mg_bias) {
799 				mc->mc_rotor = mg->mg_next;
800 				mc->mc_allocated = 0;
801 			}
802 
803 			DVA_SET_VDEV(&dva[d], vd->vdev_id);
804 			DVA_SET_OFFSET(&dva[d], offset);
805 			DVA_SET_GANG(&dva[d], 0);
806 			DVA_SET_ASIZE(&dva[d], asize);
807 
808 			return (0);
809 		}
810 		mc->mc_rotor = mg->mg_next;
811 		mc->mc_allocated = 0;
812 	} while ((mg = mg->mg_next) != rotor);
813 
814 	if (!all_zero) {
815 		dshift++;
816 		ASSERT(dshift < 64);
817 		goto top;
818 	}
819 
820 	bzero(&dva[d], sizeof (dva_t));
821 
822 	return (ENOSPC);
823 }
824 
825 /*
826  * Free the block represented by DVA in the context of the specified
827  * transaction group.
828  */
829 static void
830 metaslab_free_dva(spa_t *spa, const dva_t *dva, uint64_t txg, boolean_t now)
831 {
832 	uint64_t vdev = DVA_GET_VDEV(dva);
833 	uint64_t offset = DVA_GET_OFFSET(dva);
834 	uint64_t size = DVA_GET_ASIZE(dva);
835 	vdev_t *vd;
836 	metaslab_t *msp;
837 
838 	ASSERT(DVA_IS_VALID(dva));
839 
840 	if (txg > spa_freeze_txg(spa))
841 		return;
842 
843 	if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
844 	    (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
845 		cmn_err(CE_WARN, "metaslab_free_dva(): bad DVA %llu:%llu",
846 		    (u_longlong_t)vdev, (u_longlong_t)offset);
847 		ASSERT(0);
848 		return;
849 	}
850 
851 	msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
852 
853 	if (DVA_GET_GANG(dva))
854 		size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
855 
856 	mutex_enter(&msp->ms_lock);
857 
858 	if (now) {
859 		space_map_remove(&msp->ms_allocmap[txg & TXG_MASK],
860 		    offset, size);
861 		space_map_free(&msp->ms_map, offset, size);
862 	} else {
863 		if (msp->ms_freemap[txg & TXG_MASK].sm_space == 0)
864 			vdev_dirty(vd, VDD_METASLAB, msp, txg);
865 		space_map_add(&msp->ms_freemap[txg & TXG_MASK], offset, size);
866 	}
867 
868 	mutex_exit(&msp->ms_lock);
869 }
870 
871 /*
872  * Intent log support: upon opening the pool after a crash, notify the SPA
873  * of blocks that the intent log has allocated for immediate write, but
874  * which are still considered free by the SPA because the last transaction
875  * group didn't commit yet.
876  */
877 static int
878 metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
879 {
880 	uint64_t vdev = DVA_GET_VDEV(dva);
881 	uint64_t offset = DVA_GET_OFFSET(dva);
882 	uint64_t size = DVA_GET_ASIZE(dva);
883 	vdev_t *vd;
884 	metaslab_t *msp;
885 	int error;
886 
887 	ASSERT(DVA_IS_VALID(dva));
888 
889 	if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
890 	    (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
891 		return (ENXIO);
892 
893 	msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
894 
895 	if (DVA_GET_GANG(dva))
896 		size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
897 
898 	mutex_enter(&msp->ms_lock);
899 
900 	error = metaslab_activate(msp, METASLAB_WEIGHT_SECONDARY);
901 	if (error) {
902 		mutex_exit(&msp->ms_lock);
903 		return (error);
904 	}
905 
906 	if (msp->ms_allocmap[txg & TXG_MASK].sm_space == 0)
907 		vdev_dirty(vd, VDD_METASLAB, msp, txg);
908 
909 	space_map_claim(&msp->ms_map, offset, size);
910 	space_map_add(&msp->ms_allocmap[txg & TXG_MASK], offset, size);
911 
912 	mutex_exit(&msp->ms_lock);
913 
914 	return (0);
915 }
916 
917 int
918 metaslab_alloc(spa_t *spa, uint64_t psize, blkptr_t *bp, int ndvas,
919     uint64_t txg, blkptr_t *hintbp)
920 {
921 	dva_t *dva = bp->blk_dva;
922 	dva_t *hintdva = hintbp->blk_dva;
923 	int d;
924 	int error = 0;
925 
926 	ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
927 	ASSERT(BP_GET_NDVAS(bp) == 0);
928 	ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
929 
930 	for (d = 0; d < ndvas; d++) {
931 		error = metaslab_alloc_dva(spa, psize, dva, d, hintdva, txg);
932 		if (error) {
933 			for (d--; d >= 0; d--) {
934 				metaslab_free_dva(spa, &dva[d], txg, B_TRUE);
935 				bzero(&dva[d], sizeof (dva_t));
936 			}
937 			return (error);
938 		}
939 	}
940 	ASSERT(error == 0);
941 	ASSERT(BP_GET_NDVAS(bp) == ndvas);
942 
943 	return (0);
944 }
945 
946 void
947 metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
948 {
949 	const dva_t *dva = bp->blk_dva;
950 	int ndvas = BP_GET_NDVAS(bp);
951 	int d;
952 
953 	ASSERT(!BP_IS_HOLE(bp));
954 
955 	for (d = 0; d < ndvas; d++)
956 		metaslab_free_dva(spa, &dva[d], txg, now);
957 }
958 
959 int
960 metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
961 {
962 	const dva_t *dva = bp->blk_dva;
963 	int ndvas = BP_GET_NDVAS(bp);
964 	int d, error;
965 	int last_error = 0;
966 
967 	ASSERT(!BP_IS_HOLE(bp));
968 
969 	for (d = 0; d < ndvas; d++)
970 		if ((error = metaslab_claim_dva(spa, &dva[d], txg)) != 0)
971 			last_error = error;
972 
973 	return (last_error);
974 }
975