]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/space_map.c
MFV r336952: 9192 explicitly pass good_writes to vdev_uberblock/label_sync
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / space_map.c
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /*
26  * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
27  */
28
29 #include <sys/zfs_context.h>
30 #include <sys/spa.h>
31 #include <sys/dmu.h>
32 #include <sys/dmu_tx.h>
33 #include <sys/dnode.h>
34 #include <sys/dsl_pool.h>
35 #include <sys/zio.h>
36 #include <sys/space_map.h>
37 #include <sys/refcount.h>
38 #include <sys/zfeature.h>
39
40 SYSCTL_DECL(_vfs_zfs);
41
42 /*
43  * Note on space map block size:
44  *
45  * The data for a given space map can be kept on blocks of any size.
46  * Larger blocks entail fewer I/O operations, but they also cause the
47  * DMU to keep more data in-core, and also to waste more I/O bandwidth
48  * when only a few blocks have changed since the last transaction group.
49  */
50
51 /*
52  * Enabled whenever we want to stress test the use of double-word
53  * space map entries.
54  */
55 boolean_t zfs_force_some_double_word_sm_entries = B_FALSE;
56
57 boolean_t
58 sm_entry_is_debug(uint64_t e)
59 {
60         return (SM_PREFIX_DECODE(e) == SM_DEBUG_PREFIX);
61 }
62
63 boolean_t
64 sm_entry_is_single_word(uint64_t e)
65 {
66         uint8_t prefix = SM_PREFIX_DECODE(e);
67         return (prefix != SM_DEBUG_PREFIX && prefix != SM2_PREFIX);
68 }
69
70 boolean_t
71 sm_entry_is_double_word(uint64_t e)
72 {
73         return (SM_PREFIX_DECODE(e) == SM2_PREFIX);
74 }
75
76 /*
77  * Iterate through the space map, invoking the callback on each (non-debug)
78  * space map entry.
79  */
80 int
81 space_map_iterate(space_map_t *sm, sm_cb_t callback, void *arg)
82 {
83         uint64_t sm_len = space_map_length(sm);
84         ASSERT3U(sm->sm_blksz, !=, 0);
85
86         dmu_prefetch(sm->sm_os, space_map_object(sm), 0, 0, sm_len,
87             ZIO_PRIORITY_SYNC_READ);
88
89         uint64_t blksz = sm->sm_blksz;
90         int error = 0;
91         for (uint64_t block_base = 0; block_base < sm_len && error == 0;
92             block_base += blksz) {
93                 dmu_buf_t *db;
94                 error = dmu_buf_hold(sm->sm_os, space_map_object(sm),
95                     block_base, FTAG, &db, DMU_READ_PREFETCH);
96                 if (error != 0)
97                         return (error);
98
99                 uint64_t *block_start = db->db_data;
100                 uint64_t block_length = MIN(sm_len - block_base, blksz);
101                 uint64_t *block_end = block_start +
102                     (block_length / sizeof (uint64_t));
103
104                 VERIFY0(P2PHASE(block_length, sizeof (uint64_t)));
105                 VERIFY3U(block_length, !=, 0);
106                 ASSERT3U(blksz, ==, db->db_size);
107
108                 for (uint64_t *block_cursor = block_start;
109                     block_cursor < block_end && error == 0; block_cursor++) {
110                         uint64_t e = *block_cursor;
111
112                         if (sm_entry_is_debug(e)) /* Skip debug entries */
113                                 continue;
114
115                         uint64_t raw_offset, raw_run, vdev_id;
116                         maptype_t type;
117                         if (sm_entry_is_single_word(e)) {
118                                 type = SM_TYPE_DECODE(e);
119                                 vdev_id = SM_NO_VDEVID;
120                                 raw_offset = SM_OFFSET_DECODE(e);
121                                 raw_run = SM_RUN_DECODE(e);
122                         } else {
123                                 /* it is a two-word entry */
124                                 ASSERT(sm_entry_is_double_word(e));
125                                 raw_run = SM2_RUN_DECODE(e);
126                                 vdev_id = SM2_VDEV_DECODE(e);
127
128                                 /* move on to the second word */
129                                 block_cursor++;
130                                 e = *block_cursor;
131                                 VERIFY3P(block_cursor, <=, block_end);
132
133                                 type = SM2_TYPE_DECODE(e);
134                                 raw_offset = SM2_OFFSET_DECODE(e);
135                         }
136
137                         uint64_t entry_offset = (raw_offset << sm->sm_shift) +
138                             sm->sm_start;
139                         uint64_t entry_run = raw_run << sm->sm_shift;
140
141                         VERIFY0(P2PHASE(entry_offset, 1ULL << sm->sm_shift));
142                         VERIFY0(P2PHASE(entry_run, 1ULL << sm->sm_shift));
143                         ASSERT3U(entry_offset, >=, sm->sm_start);
144                         ASSERT3U(entry_offset, <, sm->sm_start + sm->sm_size);
145                         ASSERT3U(entry_run, <=, sm->sm_size);
146                         ASSERT3U(entry_offset + entry_run, <=,
147                             sm->sm_start + sm->sm_size);
148
149                         space_map_entry_t sme = {
150                             .sme_type = type,
151                             .sme_vdev = vdev_id,
152                             .sme_offset = entry_offset,
153                             .sme_run = entry_run
154                         };
155                         error = callback(&sme, arg);
156                 }
157                 dmu_buf_rele(db, FTAG);
158         }
159         return (error);
160 }
161
162 /*
163  * Reads the entries from the last block of the space map into
164  * buf in reverse order. Populates nwords with number of words
165  * in the last block.
166  *
167  * Refer to block comment within space_map_incremental_destroy()
168  * to understand why this function is needed.
169  */
170 static int
171 space_map_reversed_last_block_entries(space_map_t *sm, uint64_t *buf,
172     uint64_t bufsz, uint64_t *nwords)
173 {
174         int error = 0;
175         dmu_buf_t *db;
176
177         /*
178          * Find the offset of the last word in the space map and use
179          * that to read the last block of the space map with
180          * dmu_buf_hold().
181          */
182         uint64_t last_word_offset =
183             sm->sm_phys->smp_objsize - sizeof (uint64_t);
184         error = dmu_buf_hold(sm->sm_os, space_map_object(sm), last_word_offset,
185             FTAG, &db, DMU_READ_NO_PREFETCH);
186         if (error != 0)
187                 return (error);
188
189         ASSERT3U(sm->sm_object, ==, db->db_object);
190         ASSERT3U(sm->sm_blksz, ==, db->db_size);
191         ASSERT3U(bufsz, >=, db->db_size);
192         ASSERT(nwords != NULL);
193
194         uint64_t *words = db->db_data;
195         *nwords =
196             (sm->sm_phys->smp_objsize - db->db_offset) / sizeof (uint64_t);
197
198         ASSERT3U(*nwords, <=, bufsz / sizeof (uint64_t));
199
200         uint64_t n = *nwords;
201         uint64_t j = n - 1;
202         for (uint64_t i = 0; i < n; i++) {
203                 uint64_t entry = words[i];
204                 if (sm_entry_is_double_word(entry)) {
205                         /*
206                          * Since we are populating the buffer backwards
207                          * we have to be extra careful and add the two
208                          * words of the double-word entry in the right
209                          * order.
210                          */
211                         ASSERT3U(j, >, 0);
212                         buf[j - 1] = entry;
213
214                         i++;
215                         ASSERT3U(i, <, n);
216                         entry = words[i];
217                         buf[j] = entry;
218                         j -= 2;
219                 } else {
220                         ASSERT(sm_entry_is_debug(entry) ||
221                             sm_entry_is_single_word(entry));
222                         buf[j] = entry;
223                         j--;
224                 }
225         }
226
227         /*
228          * Assert that we wrote backwards all the
229          * way to the beginning of the buffer.
230          */
231         ASSERT3S(j, ==, -1);
232
233         dmu_buf_rele(db, FTAG);
234         return (error);
235 }
236
237 /*
238  * Note: This function performs destructive actions - specifically
239  * it deletes entries from the end of the space map. Thus, callers
240  * should ensure that they are holding the appropriate locks for
241  * the space map that they provide.
242  */
243 int
244 space_map_incremental_destroy(space_map_t *sm, sm_cb_t callback, void *arg,
245     dmu_tx_t *tx)
246 {
247         uint64_t bufsz = MAX(sm->sm_blksz, SPA_MINBLOCKSIZE);
248         uint64_t *buf = zio_buf_alloc(bufsz);
249
250         dmu_buf_will_dirty(sm->sm_dbuf, tx);
251
252         /*
253          * Ideally we would want to iterate from the beginning of the
254          * space map to the end in incremental steps. The issue with this
255          * approach is that we don't have any field on-disk that points
256          * us where to start between each step. We could try zeroing out
257          * entries that we've destroyed, but this doesn't work either as
258          * an entry that is 0 is a valid one (ALLOC for range [0x0:0x200]).
259          *
260          * As a result, we destroy its entries incrementally starting from
261          * the end after applying the callback to each of them.
262          *
263          * The problem with this approach is that we cannot literally
264          * iterate through the words in the space map backwards as we
265          * can't distinguish two-word space map entries from their second
266          * word. Thus we do the following:
267          *
268          * 1] We get all the entries from the last block of the space map
269          *    and put them into a buffer in reverse order. This way the
270          *    last entry comes first in the buffer, the second to last is
271          *    second, etc.
272          * 2] We iterate through the entries in the buffer and we apply
273          *    the callback to each one. As we move from entry to entry we
274          *    we decrease the size of the space map, deleting effectively
275          *    each entry.
276          * 3] If there are no more entries in the space map or the callback
277          *    returns a value other than 0, we stop iterating over the
278          *    space map. If there are entries remaining and the callback
279          *    returned 0, we go back to step [1].
280          */
281         int error = 0;
282         while (space_map_length(sm) > 0 && error == 0) {
283                 uint64_t nwords = 0;
284                 error = space_map_reversed_last_block_entries(sm, buf, bufsz,
285                     &nwords);
286                 if (error != 0)
287                         break;
288
289                 ASSERT3U(nwords, <=, bufsz / sizeof (uint64_t));
290
291                 for (uint64_t i = 0; i < nwords; i++) {
292                         uint64_t e = buf[i];
293
294                         if (sm_entry_is_debug(e)) {
295                                 sm->sm_phys->smp_objsize -= sizeof (uint64_t);
296                                 space_map_update(sm);
297                                 continue;
298                         }
299
300                         int words = 1;
301                         uint64_t raw_offset, raw_run, vdev_id;
302                         maptype_t type;
303                         if (sm_entry_is_single_word(e)) {
304                                 type = SM_TYPE_DECODE(e);
305                                 vdev_id = SM_NO_VDEVID;
306                                 raw_offset = SM_OFFSET_DECODE(e);
307                                 raw_run = SM_RUN_DECODE(e);
308                         } else {
309                                 ASSERT(sm_entry_is_double_word(e));
310                                 words = 2;
311
312                                 raw_run = SM2_RUN_DECODE(e);
313                                 vdev_id = SM2_VDEV_DECODE(e);
314
315                                 /* move to the second word */
316                                 i++;
317                                 e = buf[i];
318
319                                 ASSERT3P(i, <=, nwords);
320
321                                 type = SM2_TYPE_DECODE(e);
322                                 raw_offset = SM2_OFFSET_DECODE(e);
323                         }
324
325                         uint64_t entry_offset =
326                             (raw_offset << sm->sm_shift) + sm->sm_start;
327                         uint64_t entry_run = raw_run << sm->sm_shift;
328
329                         VERIFY0(P2PHASE(entry_offset, 1ULL << sm->sm_shift));
330                         VERIFY0(P2PHASE(entry_run, 1ULL << sm->sm_shift));
331                         VERIFY3U(entry_offset, >=, sm->sm_start);
332                         VERIFY3U(entry_offset, <, sm->sm_start + sm->sm_size);
333                         VERIFY3U(entry_run, <=, sm->sm_size);
334                         VERIFY3U(entry_offset + entry_run, <=,
335                             sm->sm_start + sm->sm_size);
336
337                         space_map_entry_t sme = {
338                             .sme_type = type,
339                             .sme_vdev = vdev_id,
340                             .sme_offset = entry_offset,
341                             .sme_run = entry_run
342                         };
343                         error = callback(&sme, arg);
344                         if (error != 0)
345                                 break;
346
347                         if (type == SM_ALLOC)
348                                 sm->sm_phys->smp_alloc -= entry_run;
349                         else
350                                 sm->sm_phys->smp_alloc += entry_run;
351                         sm->sm_phys->smp_objsize -= words * sizeof (uint64_t);
352                         space_map_update(sm);
353                 }
354         }
355
356         if (space_map_length(sm) == 0) {
357                 ASSERT0(error);
358                 ASSERT0(sm->sm_phys->smp_objsize);
359                 ASSERT0(sm->sm_alloc);
360         }
361
362         zio_buf_free(buf, bufsz);
363         return (error);
364 }
365
366 typedef struct space_map_load_arg {
367         space_map_t     *smla_sm;
368         range_tree_t    *smla_rt;
369         maptype_t       smla_type;
370 } space_map_load_arg_t;
371
372 static int
373 space_map_load_callback(space_map_entry_t *sme, void *arg)
374 {
375         space_map_load_arg_t *smla = arg;
376         if (sme->sme_type == smla->smla_type) {
377                 VERIFY3U(range_tree_space(smla->smla_rt) + sme->sme_run, <=,
378                     smla->smla_sm->sm_size);
379                 range_tree_add(smla->smla_rt, sme->sme_offset, sme->sme_run);
380         } else {
381                 range_tree_remove(smla->smla_rt, sme->sme_offset, sme->sme_run);
382         }
383
384         return (0);
385 }
386
387 /*
388  * Load the space map disk into the specified range tree. Segments of maptype
389  * are added to the range tree, other segment types are removed.
390  */
391 int
392 space_map_load(space_map_t *sm, range_tree_t *rt, maptype_t maptype)
393 {
394         uint64_t space;
395         int err;
396         space_map_load_arg_t smla;
397
398         VERIFY0(range_tree_space(rt));
399         space = space_map_allocated(sm);
400
401         if (maptype == SM_FREE) {
402                 range_tree_add(rt, sm->sm_start, sm->sm_size);
403                 space = sm->sm_size - space;
404         }
405
406         smla.smla_rt = rt;
407         smla.smla_sm = sm;
408         smla.smla_type = maptype;
409         err = space_map_iterate(sm, space_map_load_callback, &smla);
410
411         if (err == 0) {
412                 VERIFY3U(range_tree_space(rt), ==, space);
413         } else {
414                 range_tree_vacate(rt, NULL, NULL);
415         }
416
417         return (err);
418 }
419
420 void
421 space_map_histogram_clear(space_map_t *sm)
422 {
423         if (sm->sm_dbuf->db_size != sizeof (space_map_phys_t))
424                 return;
425
426         bzero(sm->sm_phys->smp_histogram, sizeof (sm->sm_phys->smp_histogram));
427 }
428
429 boolean_t
430 space_map_histogram_verify(space_map_t *sm, range_tree_t *rt)
431 {
432         /*
433          * Verify that the in-core range tree does not have any
434          * ranges smaller than our sm_shift size.
435          */
436         for (int i = 0; i < sm->sm_shift; i++) {
437                 if (rt->rt_histogram[i] != 0)
438                         return (B_FALSE);
439         }
440         return (B_TRUE);
441 }
442
443 void
444 space_map_histogram_add(space_map_t *sm, range_tree_t *rt, dmu_tx_t *tx)
445 {
446         int idx = 0;
447
448         ASSERT(dmu_tx_is_syncing(tx));
449         VERIFY3U(space_map_object(sm), !=, 0);
450
451         if (sm->sm_dbuf->db_size != sizeof (space_map_phys_t))
452                 return;
453
454         dmu_buf_will_dirty(sm->sm_dbuf, tx);
455
456         ASSERT(space_map_histogram_verify(sm, rt));
457         /*
458          * Transfer the content of the range tree histogram to the space
459          * map histogram. The space map histogram contains 32 buckets ranging
460          * between 2^sm_shift to 2^(32+sm_shift-1). The range tree,
461          * however, can represent ranges from 2^0 to 2^63. Since the space
462          * map only cares about allocatable blocks (minimum of sm_shift) we
463          * can safely ignore all ranges in the range tree smaller than sm_shift.
464          */
465         for (int i = sm->sm_shift; i < RANGE_TREE_HISTOGRAM_SIZE; i++) {
466
467                 /*
468                  * Since the largest histogram bucket in the space map is
469                  * 2^(32+sm_shift-1), we need to normalize the values in
470                  * the range tree for any bucket larger than that size. For
471                  * example given an sm_shift of 9, ranges larger than 2^40
472                  * would get normalized as if they were 1TB ranges. Assume
473                  * the range tree had a count of 5 in the 2^44 (16TB) bucket,
474                  * the calculation below would normalize this to 5 * 2^4 (16).
475                  */
476                 ASSERT3U(i, >=, idx + sm->sm_shift);
477                 sm->sm_phys->smp_histogram[idx] +=
478                     rt->rt_histogram[i] << (i - idx - sm->sm_shift);
479
480                 /*
481                  * Increment the space map's index as long as we haven't
482                  * reached the maximum bucket size. Accumulate all ranges
483                  * larger than the max bucket size into the last bucket.
484                  */
485                 if (idx < SPACE_MAP_HISTOGRAM_SIZE - 1) {
486                         ASSERT3U(idx + sm->sm_shift, ==, i);
487                         idx++;
488                         ASSERT3U(idx, <, SPACE_MAP_HISTOGRAM_SIZE);
489                 }
490         }
491 }
492
493 static void
494 space_map_write_intro_debug(space_map_t *sm, maptype_t maptype, dmu_tx_t *tx)
495 {
496         dmu_buf_will_dirty(sm->sm_dbuf, tx);
497
498         uint64_t dentry = SM_PREFIX_ENCODE(SM_DEBUG_PREFIX) |
499             SM_DEBUG_ACTION_ENCODE(maptype) |
500             SM_DEBUG_SYNCPASS_ENCODE(spa_sync_pass(tx->tx_pool->dp_spa)) |
501             SM_DEBUG_TXG_ENCODE(dmu_tx_get_txg(tx));
502
503         dmu_write(sm->sm_os, space_map_object(sm), sm->sm_phys->smp_objsize,
504             sizeof (dentry), &dentry, tx);
505
506         sm->sm_phys->smp_objsize += sizeof (dentry);
507 }
508
509 /*
510  * Writes one or more entries given a segment.
511  *
512  * Note: The function may release the dbuf from the pointer initially
513  * passed to it, and return a different dbuf. Also, the space map's
514  * dbuf must be dirty for the changes in sm_phys to take effect.
515  */
516 static void
517 space_map_write_seg(space_map_t *sm, range_seg_t *rs, maptype_t maptype,
518     uint64_t vdev_id, uint8_t words, dmu_buf_t **dbp, void *tag, dmu_tx_t *tx)
519 {
520         ASSERT3U(words, !=, 0);
521         ASSERT3U(words, <=, 2);
522
523         /* ensure the vdev_id can be represented by the space map */
524         ASSERT3U(vdev_id, <=, SM_NO_VDEVID);
525
526         /*
527          * if this is a single word entry, ensure that no vdev was
528          * specified.
529          */
530         IMPLY(words == 1, vdev_id == SM_NO_VDEVID);
531
532         dmu_buf_t *db = *dbp;
533         ASSERT3U(db->db_size, ==, sm->sm_blksz);
534
535         uint64_t *block_base = db->db_data;
536         uint64_t *block_end = block_base + (sm->sm_blksz / sizeof (uint64_t));
537         uint64_t *block_cursor = block_base +
538             (sm->sm_phys->smp_objsize - db->db_offset) / sizeof (uint64_t);
539
540         ASSERT3P(block_cursor, <=, block_end);
541
542         uint64_t size = (rs->rs_end - rs->rs_start) >> sm->sm_shift;
543         uint64_t start = (rs->rs_start - sm->sm_start) >> sm->sm_shift;
544         uint64_t run_max = (words == 2) ? SM2_RUN_MAX : SM_RUN_MAX;
545
546         ASSERT3U(rs->rs_start, >=, sm->sm_start);
547         ASSERT3U(rs->rs_start, <, sm->sm_start + sm->sm_size);
548         ASSERT3U(rs->rs_end - rs->rs_start, <=, sm->sm_size);
549         ASSERT3U(rs->rs_end, <=, sm->sm_start + sm->sm_size);
550
551         while (size != 0) {
552                 ASSERT3P(block_cursor, <=, block_end);
553
554                 /*
555                  * If we are at the end of this block, flush it and start
556                  * writing again from the beginning.
557                  */
558                 if (block_cursor == block_end) {
559                         dmu_buf_rele(db, tag);
560
561                         uint64_t next_word_offset = sm->sm_phys->smp_objsize;
562                         VERIFY0(dmu_buf_hold(sm->sm_os,
563                             space_map_object(sm), next_word_offset,
564                             tag, &db, DMU_READ_PREFETCH));
565                         dmu_buf_will_dirty(db, tx);
566
567                         /* update caller's dbuf */
568                         *dbp = db;
569
570                         ASSERT3U(db->db_size, ==, sm->sm_blksz);
571
572                         block_base = db->db_data;
573                         block_cursor = block_base;
574                         block_end = block_base +
575                             (db->db_size / sizeof (uint64_t));
576                 }
577
578                 /*
579                  * If we are writing a two-word entry and we only have one
580                  * word left on this block, just pad it with an empty debug
581                  * entry and write the two-word entry in the next block.
582                  */
583                 uint64_t *next_entry = block_cursor + 1;
584                 if (next_entry == block_end && words > 1) {
585                         ASSERT3U(words, ==, 2);
586                         *block_cursor = SM_PREFIX_ENCODE(SM_DEBUG_PREFIX) |
587                             SM_DEBUG_ACTION_ENCODE(0) |
588                             SM_DEBUG_SYNCPASS_ENCODE(0) |
589                             SM_DEBUG_TXG_ENCODE(0);
590                         block_cursor++;
591                         sm->sm_phys->smp_objsize += sizeof (uint64_t);
592                         ASSERT3P(block_cursor, ==, block_end);
593                         continue;
594                 }
595
596                 uint64_t run_len = MIN(size, run_max);
597                 switch (words) {
598                 case 1:
599                         *block_cursor = SM_OFFSET_ENCODE(start) |
600                             SM_TYPE_ENCODE(maptype) |
601                             SM_RUN_ENCODE(run_len);
602                         block_cursor++;
603                         break;
604                 case 2:
605                         /* write the first word of the entry */
606                         *block_cursor = SM_PREFIX_ENCODE(SM2_PREFIX) |
607                             SM2_RUN_ENCODE(run_len) |
608                             SM2_VDEV_ENCODE(vdev_id);
609                         block_cursor++;
610
611                         /* move on to the second word of the entry */
612                         ASSERT3P(block_cursor, <, block_end);
613                         *block_cursor = SM2_TYPE_ENCODE(maptype) |
614                             SM2_OFFSET_ENCODE(start);
615                         block_cursor++;
616                         break;
617                 default:
618                         panic("%d-word space map entries are not supported",
619                             words);
620                         break;
621                 }
622                 sm->sm_phys->smp_objsize += words * sizeof (uint64_t);
623
624                 start += run_len;
625                 size -= run_len;
626         }
627         ASSERT0(size);
628
629 }
630
631 /*
632  * Note: The space map's dbuf must be dirty for the changes in sm_phys to
633  * take effect.
634  */
635 static void
636 space_map_write_impl(space_map_t *sm, range_tree_t *rt, maptype_t maptype,
637     uint64_t vdev_id, dmu_tx_t *tx)
638 {
639         spa_t *spa = tx->tx_pool->dp_spa;
640         dmu_buf_t *db;
641
642         space_map_write_intro_debug(sm, maptype, tx);
643
644 #ifdef DEBUG
645         /*
646          * We do this right after we write the intro debug entry
647          * because the estimate does not take it into account.
648          */
649         uint64_t initial_objsize = sm->sm_phys->smp_objsize;
650         uint64_t estimated_growth =
651             space_map_estimate_optimal_size(sm, rt, SM_NO_VDEVID);
652         uint64_t estimated_final_objsize = initial_objsize + estimated_growth;
653 #endif
654
655         /*
656          * Find the offset right after the last word in the space map
657          * and use that to get a hold of the last block, so we can
658          * start appending to it.
659          */
660         uint64_t next_word_offset = sm->sm_phys->smp_objsize;
661         VERIFY0(dmu_buf_hold(sm->sm_os, space_map_object(sm),
662             next_word_offset, FTAG, &db, DMU_READ_PREFETCH));
663         ASSERT3U(db->db_size, ==, sm->sm_blksz);
664
665         dmu_buf_will_dirty(db, tx);
666
667         avl_tree_t *t = &rt->rt_root;
668         for (range_seg_t *rs = avl_first(t); rs != NULL; rs = AVL_NEXT(t, rs)) {
669                 uint64_t offset = (rs->rs_start - sm->sm_start) >> sm->sm_shift;
670                 uint64_t length = (rs->rs_end - rs->rs_start) >> sm->sm_shift;
671                 uint8_t words = 1;
672
673                 /*
674                  * We only write two-word entries when both of the following
675                  * are true:
676                  *
677                  * [1] The feature is enabled.
678                  * [2] The offset or run is too big for a single-word entry,
679                  *      or the vdev_id is set (meaning not equal to
680                  *      SM_NO_VDEVID).
681                  *
682                  * Note that for purposes of testing we've added the case that
683                  * we write two-word entries occasionally when the feature is
684                  * enabled and zfs_force_some_double_word_sm_entries has been
685                  * set.
686                  */
687                 if (spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_V2) &&
688                     (offset >= (1ULL << SM_OFFSET_BITS) ||
689                     length > SM_RUN_MAX ||
690                     vdev_id != SM_NO_VDEVID ||
691                     (zfs_force_some_double_word_sm_entries &&
692                     spa_get_random(100) == 0)))
693                         words = 2;
694
695                 space_map_write_seg(sm, rs, maptype, vdev_id, words,
696                     &db, FTAG, tx);
697         }
698
699         dmu_buf_rele(db, FTAG);
700
701 #ifdef DEBUG
702         /*
703          * We expect our estimation to be based on the worst case
704          * scenario [see comment in space_map_estimate_optimal_size()].
705          * Therefore we expect the actual objsize to be equal or less
706          * than whatever we estimated it to be.
707          */
708         ASSERT3U(estimated_final_objsize, >=, sm->sm_phys->smp_objsize);
709 #endif
710 }
711
712 /*
713  * Note: This function manipulates the state of the given space map but
714  * does not hold any locks implicitly. Thus the caller is responsible
715  * for synchronizing writes to the space map.
716  */
717 void
718 space_map_write(space_map_t *sm, range_tree_t *rt, maptype_t maptype,
719     uint64_t vdev_id, dmu_tx_t *tx)
720 {
721         objset_t *os = sm->sm_os;
722
723         ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
724         VERIFY3U(space_map_object(sm), !=, 0);
725
726         dmu_buf_will_dirty(sm->sm_dbuf, tx);
727
728         /*
729          * This field is no longer necessary since the in-core space map
730          * now contains the object number but is maintained for backwards
731          * compatibility.
732          */
733         sm->sm_phys->smp_object = sm->sm_object;
734
735         if (range_tree_is_empty(rt)) {
736                 VERIFY3U(sm->sm_object, ==, sm->sm_phys->smp_object);
737                 return;
738         }
739
740         if (maptype == SM_ALLOC)
741                 sm->sm_phys->smp_alloc += range_tree_space(rt);
742         else
743                 sm->sm_phys->smp_alloc -= range_tree_space(rt);
744
745         uint64_t nodes = avl_numnodes(&rt->rt_root);
746         uint64_t rt_space = range_tree_space(rt);
747
748         space_map_write_impl(sm, rt, maptype, vdev_id, tx);
749
750         /*
751          * Ensure that the space_map's accounting wasn't changed
752          * while we were in the middle of writing it out.
753          */
754         VERIFY3U(nodes, ==, avl_numnodes(&rt->rt_root));
755         VERIFY3U(range_tree_space(rt), ==, rt_space);
756 }
757
758 static int
759 space_map_open_impl(space_map_t *sm)
760 {
761         int error;
762         u_longlong_t blocks;
763
764         error = dmu_bonus_hold(sm->sm_os, sm->sm_object, sm, &sm->sm_dbuf);
765         if (error)
766                 return (error);
767
768         dmu_object_size_from_db(sm->sm_dbuf, &sm->sm_blksz, &blocks);
769         sm->sm_phys = sm->sm_dbuf->db_data;
770         return (0);
771 }
772
773 int
774 space_map_open(space_map_t **smp, objset_t *os, uint64_t object,
775     uint64_t start, uint64_t size, uint8_t shift)
776 {
777         space_map_t *sm;
778         int error;
779
780         ASSERT(*smp == NULL);
781         ASSERT(os != NULL);
782         ASSERT(object != 0);
783
784         sm = kmem_zalloc(sizeof (space_map_t), KM_SLEEP);
785
786         sm->sm_start = start;
787         sm->sm_size = size;
788         sm->sm_shift = shift;
789         sm->sm_os = os;
790         sm->sm_object = object;
791
792         error = space_map_open_impl(sm);
793         if (error != 0) {
794                 space_map_close(sm);
795                 return (error);
796         }
797         *smp = sm;
798
799         return (0);
800 }
801
802 void
803 space_map_close(space_map_t *sm)
804 {
805         if (sm == NULL)
806                 return;
807
808         if (sm->sm_dbuf != NULL)
809                 dmu_buf_rele(sm->sm_dbuf, sm);
810         sm->sm_dbuf = NULL;
811         sm->sm_phys = NULL;
812
813         kmem_free(sm, sizeof (*sm));
814 }
815
816 void
817 space_map_truncate(space_map_t *sm, int blocksize, dmu_tx_t *tx)
818 {
819         objset_t *os = sm->sm_os;
820         spa_t *spa = dmu_objset_spa(os);
821         dmu_object_info_t doi;
822
823         ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
824         ASSERT(dmu_tx_is_syncing(tx));
825         VERIFY3U(dmu_tx_get_txg(tx), <=, spa_final_dirty_txg(spa));
826
827         dmu_object_info_from_db(sm->sm_dbuf, &doi);
828
829         /*
830          * If the space map has the wrong bonus size (because
831          * SPA_FEATURE_SPACEMAP_HISTOGRAM has recently been enabled), or
832          * the wrong block size (because space_map_blksz has changed),
833          * free and re-allocate its object with the updated sizes.
834          *
835          * Otherwise, just truncate the current object.
836          */
837         if ((spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM) &&
838             doi.doi_bonus_size != sizeof (space_map_phys_t)) ||
839             doi.doi_data_block_size != blocksize) {
840                 zfs_dbgmsg("txg %llu, spa %s, sm %p, reallocating "
841                     "object[%llu]: old bonus %u, old blocksz %u",
842                     dmu_tx_get_txg(tx), spa_name(spa), sm, sm->sm_object,
843                     doi.doi_bonus_size, doi.doi_data_block_size);
844
845                 space_map_free(sm, tx);
846                 dmu_buf_rele(sm->sm_dbuf, sm);
847
848                 sm->sm_object = space_map_alloc(sm->sm_os, blocksize, tx);
849                 VERIFY0(space_map_open_impl(sm));
850         } else {
851                 VERIFY0(dmu_free_range(os, space_map_object(sm), 0, -1ULL, tx));
852
853                 /*
854                  * If the spacemap is reallocated, its histogram
855                  * will be reset.  Do the same in the common case so that
856                  * bugs related to the uncommon case do not go unnoticed.
857                  */
858                 bzero(sm->sm_phys->smp_histogram,
859                     sizeof (sm->sm_phys->smp_histogram));
860         }
861
862         dmu_buf_will_dirty(sm->sm_dbuf, tx);
863         sm->sm_phys->smp_objsize = 0;
864         sm->sm_phys->smp_alloc = 0;
865 }
866
867 /*
868  * Update the in-core space_map allocation and length values.
869  */
870 void
871 space_map_update(space_map_t *sm)
872 {
873         if (sm == NULL)
874                 return;
875
876         sm->sm_alloc = sm->sm_phys->smp_alloc;
877         sm->sm_length = sm->sm_phys->smp_objsize;
878 }
879
880 uint64_t
881 space_map_alloc(objset_t *os, int blocksize, dmu_tx_t *tx)
882 {
883         spa_t *spa = dmu_objset_spa(os);
884         uint64_t object;
885         int bonuslen;
886
887         if (spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
888                 spa_feature_incr(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM, tx);
889                 bonuslen = sizeof (space_map_phys_t);
890                 ASSERT3U(bonuslen, <=, dmu_bonus_max());
891         } else {
892                 bonuslen = SPACE_MAP_SIZE_V0;
893         }
894
895         object = dmu_object_alloc(os, DMU_OT_SPACE_MAP, blocksize,
896             DMU_OT_SPACE_MAP_HEADER, bonuslen, tx);
897
898         return (object);
899 }
900
901 void
902 space_map_free_obj(objset_t *os, uint64_t smobj, dmu_tx_t *tx)
903 {
904         spa_t *spa = dmu_objset_spa(os);
905         if (spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
906                 dmu_object_info_t doi;
907
908                 VERIFY0(dmu_object_info(os, smobj, &doi));
909                 if (doi.doi_bonus_size != SPACE_MAP_SIZE_V0) {
910                         spa_feature_decr(spa,
911                             SPA_FEATURE_SPACEMAP_HISTOGRAM, tx);
912                 }
913         }
914
915         VERIFY0(dmu_object_free(os, smobj, tx));
916 }
917
918 void
919 space_map_free(space_map_t *sm, dmu_tx_t *tx)
920 {
921         if (sm == NULL)
922                 return;
923
924         space_map_free_obj(sm->sm_os, space_map_object(sm), tx);
925         sm->sm_object = 0;
926 }
927
928 /*
929  * Given a range tree, it makes a worst-case estimate of how much
930  * space would the tree's segments take if they were written to
931  * the given space map.
932  */
933 uint64_t
934 space_map_estimate_optimal_size(space_map_t *sm, range_tree_t *rt,
935     uint64_t vdev_id)
936 {
937         spa_t *spa = dmu_objset_spa(sm->sm_os);
938         uint64_t shift = sm->sm_shift;
939         uint64_t *histogram = rt->rt_histogram;
940         uint64_t entries_for_seg = 0;
941
942         /*
943          * In order to get a quick estimate of the optimal size that this
944          * range tree would have on-disk as a space map, we iterate through
945          * its histogram buckets instead of iterating through its nodes.
946          *
947          * Note that this is a highest-bound/worst-case estimate for the
948          * following reasons:
949          *
950          * 1] We assume that we always add a debug padding for each block
951          *    we write and we also assume that we start at the last word
952          *    of a block attempting to write a two-word entry.
953          * 2] Rounding up errors due to the way segments are distributed
954          *    in the buckets of the range tree's histogram.
955          * 3] The activation of zfs_force_some_double_word_sm_entries
956          *    (tunable) when testing.
957          *
958          * = Math and Rounding Errors =
959          *
960          * rt_histogram[i] bucket of a range tree represents the number
961          * of entries in [2^i, (2^(i+1))-1] of that range_tree. Given
962          * that, we want to divide the buckets into groups: Buckets that
963          * can be represented using a single-word entry, ones that can
964          * be represented with a double-word entry, and ones that can
965          * only be represented with multiple two-word entries.
966          *
967          * [Note that if the new encoding feature is not enabled there
968          * are only two groups: single-word entry buckets and multiple
969          * single-word entry buckets. The information below assumes
970          * two-word entries enabled, but it can easily applied when
971          * the feature is not enabled]
972          *
973          * To find the highest bucket that can be represented with a
974          * single-word entry we look at the maximum run that such entry
975          * can have, which is 2^(SM_RUN_BITS + sm_shift) [remember that
976          * the run of a space map entry is shifted by sm_shift, thus we
977          * add it to the exponent]. This way, excluding the value of the
978          * maximum run that can be represented by a single-word entry,
979          * all runs that are smaller exist in buckets 0 to
980          * SM_RUN_BITS + shift - 1.
981          *
982          * To find the highest bucket that can be represented with a
983          * double-word entry, we follow the same approach. Finally, any
984          * bucket higher than that are represented with multiple two-word
985          * entries. To be more specific, if the highest bucket whose
986          * segments can be represented with a single two-word entry is X,
987          * then bucket X+1 will need 2 two-word entries for each of its
988          * segments, X+2 will need 4, X+3 will need 8, ...etc.
989          *
990          * With all of the above we make our estimation based on bucket
991          * groups. There is a rounding error though. As we mentioned in
992          * the example with the one-word entry, the maximum run that can
993          * be represented in a one-word entry 2^(SM_RUN_BITS + shift) is
994          * not part of bucket SM_RUN_BITS + shift - 1. Thus, segments of
995          * that length fall into the next bucket (and bucket group) where
996          * we start counting two-word entries and this is one more reason
997          * why the estimated size may end up being bigger than the actual
998          * size written.
999          */
1000         uint64_t size = 0;
1001         uint64_t idx = 0;
1002
1003         if (!spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_V2) ||
1004             (vdev_id == SM_NO_VDEVID && sm->sm_size < SM_OFFSET_MAX)) {
1005
1006                 /*
1007                  * If we are trying to force some double word entries just
1008                  * assume the worst-case of every single word entry being
1009                  * written as a double word entry.
1010                  */
1011                 uint64_t entry_size =
1012                     (spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_V2) &&
1013                     zfs_force_some_double_word_sm_entries) ?
1014                     (2 * sizeof (uint64_t)) : sizeof (uint64_t);
1015
1016                 uint64_t single_entry_max_bucket = SM_RUN_BITS + shift - 1;
1017                 for (; idx <= single_entry_max_bucket; idx++)
1018                         size += histogram[idx] * entry_size;
1019
1020                 if (!spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_V2)) {
1021                         for (; idx < RANGE_TREE_HISTOGRAM_SIZE; idx++) {
1022                                 ASSERT3U(idx, >=, single_entry_max_bucket);
1023                                 entries_for_seg =
1024                                     1ULL << (idx - single_entry_max_bucket);
1025                                 size += histogram[idx] *
1026                                     entries_for_seg * entry_size;
1027                         }
1028                         return (size);
1029                 }
1030         }
1031
1032         ASSERT(spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_V2));
1033
1034         uint64_t double_entry_max_bucket = SM2_RUN_BITS + shift - 1;
1035         for (; idx <= double_entry_max_bucket; idx++)
1036                 size += histogram[idx] * 2 * sizeof (uint64_t);
1037
1038         for (; idx < RANGE_TREE_HISTOGRAM_SIZE; idx++) {
1039                 ASSERT3U(idx, >=, double_entry_max_bucket);
1040                 entries_for_seg = 1ULL << (idx - double_entry_max_bucket);
1041                 size += histogram[idx] *
1042                     entries_for_seg * 2 * sizeof (uint64_t);
1043         }
1044
1045         /*
1046          * Assume the worst case where we start with the padding at the end
1047          * of the current block and we add an extra padding entry at the end
1048          * of all subsequent blocks.
1049          */
1050         size += ((size / sm->sm_blksz) + 1) * sizeof (uint64_t);
1051
1052         return (size);
1053 }
1054
1055 uint64_t
1056 space_map_object(space_map_t *sm)
1057 {
1058         return (sm != NULL ? sm->sm_object : 0);
1059 }
1060
1061 /*
1062  * Returns the already synced, on-disk allocated space.
1063  */
1064 uint64_t
1065 space_map_allocated(space_map_t *sm)
1066 {
1067         return (sm != NULL ? sm->sm_alloc : 0);
1068 }
1069
1070 /*
1071  * Returns the already synced, on-disk length;
1072  */
1073 uint64_t
1074 space_map_length(space_map_t *sm)
1075 {
1076         return (sm != NULL ? sm->sm_length : 0);
1077 }
1078
1079 /*
1080  * Returns the allocated space that is currently syncing.
1081  */
1082 int64_t
1083 space_map_alloc_delta(space_map_t *sm)
1084 {
1085         if (sm == NULL)
1086                 return (0);
1087         ASSERT(sm->sm_dbuf != NULL);
1088         return (sm->sm_phys->smp_alloc - space_map_allocated(sm));
1089 }