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