]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_objset.c
MFV r336958: 9337 zfs get all is slow due to uncached metadata
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / dmu_objset.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 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
25  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
26  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28  * Copyright (c) 2015, STRATO AG, Inc. All rights reserved.
29  * Copyright (c) 2014 Integros [integros.com]
30  * Copyright 2017 Nexenta Systems, Inc.
31  */
32
33 /* Portions Copyright 2010 Robert Milkowski */
34
35 #include <sys/cred.h>
36 #include <sys/zfs_context.h>
37 #include <sys/dmu_objset.h>
38 #include <sys/dsl_dir.h>
39 #include <sys/dsl_dataset.h>
40 #include <sys/dsl_prop.h>
41 #include <sys/dsl_pool.h>
42 #include <sys/dsl_synctask.h>
43 #include <sys/dsl_deleg.h>
44 #include <sys/dnode.h>
45 #include <sys/dbuf.h>
46 #include <sys/zvol.h>
47 #include <sys/dmu_tx.h>
48 #include <sys/zap.h>
49 #include <sys/zil.h>
50 #include <sys/dmu_impl.h>
51 #include <sys/zfs_ioctl.h>
52 #include <sys/sa.h>
53 #include <sys/zfs_onexit.h>
54 #include <sys/dsl_destroy.h>
55 #include <sys/vdev.h>
56 #include <sys/zfeature.h>
57
58 /*
59  * Needed to close a window in dnode_move() that allows the objset to be freed
60  * before it can be safely accessed.
61  */
62 krwlock_t os_lock;
63
64 /*
65  * Tunable to overwrite the maximum number of threads for the parallization
66  * of dmu_objset_find_dp, needed to speed up the import of pools with many
67  * datasets.
68  * Default is 4 times the number of leaf vdevs.
69  */
70 int dmu_find_threads = 0;
71
72 /*
73  * Backfill lower metadnode objects after this many have been freed.
74  * Backfilling negatively impacts object creation rates, so only do it
75  * if there are enough holes to fill.
76  */
77 int dmu_rescan_dnode_threshold = 131072;
78
79 static void dmu_objset_find_dp_cb(void *arg);
80
81 void
82 dmu_objset_init(void)
83 {
84         rw_init(&os_lock, NULL, RW_DEFAULT, NULL);
85 }
86
87 void
88 dmu_objset_fini(void)
89 {
90         rw_destroy(&os_lock);
91 }
92
93 spa_t *
94 dmu_objset_spa(objset_t *os)
95 {
96         return (os->os_spa);
97 }
98
99 zilog_t *
100 dmu_objset_zil(objset_t *os)
101 {
102         return (os->os_zil);
103 }
104
105 dsl_pool_t *
106 dmu_objset_pool(objset_t *os)
107 {
108         dsl_dataset_t *ds;
109
110         if ((ds = os->os_dsl_dataset) != NULL && ds->ds_dir)
111                 return (ds->ds_dir->dd_pool);
112         else
113                 return (spa_get_dsl(os->os_spa));
114 }
115
116 dsl_dataset_t *
117 dmu_objset_ds(objset_t *os)
118 {
119         return (os->os_dsl_dataset);
120 }
121
122 dmu_objset_type_t
123 dmu_objset_type(objset_t *os)
124 {
125         return (os->os_phys->os_type);
126 }
127
128 void
129 dmu_objset_name(objset_t *os, char *buf)
130 {
131         dsl_dataset_name(os->os_dsl_dataset, buf);
132 }
133
134 uint64_t
135 dmu_objset_id(objset_t *os)
136 {
137         dsl_dataset_t *ds = os->os_dsl_dataset;
138
139         return (ds ? ds->ds_object : 0);
140 }
141
142 zfs_sync_type_t
143 dmu_objset_syncprop(objset_t *os)
144 {
145         return (os->os_sync);
146 }
147
148 zfs_logbias_op_t
149 dmu_objset_logbias(objset_t *os)
150 {
151         return (os->os_logbias);
152 }
153
154 static void
155 checksum_changed_cb(void *arg, uint64_t newval)
156 {
157         objset_t *os = arg;
158
159         /*
160          * Inheritance should have been done by now.
161          */
162         ASSERT(newval != ZIO_CHECKSUM_INHERIT);
163
164         os->os_checksum = zio_checksum_select(newval, ZIO_CHECKSUM_ON_VALUE);
165 }
166
167 static void
168 compression_changed_cb(void *arg, uint64_t newval)
169 {
170         objset_t *os = arg;
171
172         /*
173          * Inheritance and range checking should have been done by now.
174          */
175         ASSERT(newval != ZIO_COMPRESS_INHERIT);
176
177         os->os_compress = zio_compress_select(os->os_spa, newval,
178             ZIO_COMPRESS_ON);
179 }
180
181 static void
182 copies_changed_cb(void *arg, uint64_t newval)
183 {
184         objset_t *os = arg;
185
186         /*
187          * Inheritance and range checking should have been done by now.
188          */
189         ASSERT(newval > 0);
190         ASSERT(newval <= spa_max_replication(os->os_spa));
191
192         os->os_copies = newval;
193 }
194
195 static void
196 dedup_changed_cb(void *arg, uint64_t newval)
197 {
198         objset_t *os = arg;
199         spa_t *spa = os->os_spa;
200         enum zio_checksum checksum;
201
202         /*
203          * Inheritance should have been done by now.
204          */
205         ASSERT(newval != ZIO_CHECKSUM_INHERIT);
206
207         checksum = zio_checksum_dedup_select(spa, newval, ZIO_CHECKSUM_OFF);
208
209         os->os_dedup_checksum = checksum & ZIO_CHECKSUM_MASK;
210         os->os_dedup_verify = !!(checksum & ZIO_CHECKSUM_VERIFY);
211 }
212
213 static void
214 primary_cache_changed_cb(void *arg, uint64_t newval)
215 {
216         objset_t *os = arg;
217
218         /*
219          * Inheritance and range checking should have been done by now.
220          */
221         ASSERT(newval == ZFS_CACHE_ALL || newval == ZFS_CACHE_NONE ||
222             newval == ZFS_CACHE_METADATA);
223
224         os->os_primary_cache = newval;
225 }
226
227 static void
228 secondary_cache_changed_cb(void *arg, uint64_t newval)
229 {
230         objset_t *os = arg;
231
232         /*
233          * Inheritance and range checking should have been done by now.
234          */
235         ASSERT(newval == ZFS_CACHE_ALL || newval == ZFS_CACHE_NONE ||
236             newval == ZFS_CACHE_METADATA);
237
238         os->os_secondary_cache = newval;
239 }
240
241 static void
242 sync_changed_cb(void *arg, uint64_t newval)
243 {
244         objset_t *os = arg;
245
246         /*
247          * Inheritance and range checking should have been done by now.
248          */
249         ASSERT(newval == ZFS_SYNC_STANDARD || newval == ZFS_SYNC_ALWAYS ||
250             newval == ZFS_SYNC_DISABLED);
251
252         os->os_sync = newval;
253         if (os->os_zil)
254                 zil_set_sync(os->os_zil, newval);
255 }
256
257 static void
258 redundant_metadata_changed_cb(void *arg, uint64_t newval)
259 {
260         objset_t *os = arg;
261
262         /*
263          * Inheritance and range checking should have been done by now.
264          */
265         ASSERT(newval == ZFS_REDUNDANT_METADATA_ALL ||
266             newval == ZFS_REDUNDANT_METADATA_MOST);
267
268         os->os_redundant_metadata = newval;
269 }
270
271 static void
272 logbias_changed_cb(void *arg, uint64_t newval)
273 {
274         objset_t *os = arg;
275
276         ASSERT(newval == ZFS_LOGBIAS_LATENCY ||
277             newval == ZFS_LOGBIAS_THROUGHPUT);
278         os->os_logbias = newval;
279         if (os->os_zil)
280                 zil_set_logbias(os->os_zil, newval);
281 }
282
283 static void
284 recordsize_changed_cb(void *arg, uint64_t newval)
285 {
286         objset_t *os = arg;
287
288         os->os_recordsize = newval;
289 }
290
291 void
292 dmu_objset_byteswap(void *buf, size_t size)
293 {
294         objset_phys_t *osp = buf;
295
296         ASSERT(size == OBJSET_OLD_PHYS_SIZE || size == sizeof (objset_phys_t));
297         dnode_byteswap(&osp->os_meta_dnode);
298         byteswap_uint64_array(&osp->os_zil_header, sizeof (zil_header_t));
299         osp->os_type = BSWAP_64(osp->os_type);
300         osp->os_flags = BSWAP_64(osp->os_flags);
301         if (size == sizeof (objset_phys_t)) {
302                 dnode_byteswap(&osp->os_userused_dnode);
303                 dnode_byteswap(&osp->os_groupused_dnode);
304         }
305 }
306
307 /*
308  * The hash is a CRC-based hash of the objset_t pointer and the object number.
309  */
310 static uint64_t
311 dnode_hash(const objset_t *os, uint64_t obj)
312 {
313         uintptr_t osv = (uintptr_t)os;
314         uint64_t crc = -1ULL;
315
316         ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
317         /*
318          * The low 6 bits of the pointer don't have much entropy, because
319          * the objset_t is larger than 2^6 bytes long.
320          */
321         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
322         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
323         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
324         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 16)) & 0xFF];
325
326         crc ^= (osv>>14) ^ (obj>>24);
327
328         return (crc);
329 }
330
331 unsigned int
332 dnode_multilist_index_func(multilist_t *ml, void *obj)
333 {
334         dnode_t *dn = obj;
335         return (dnode_hash(dn->dn_objset, dn->dn_object) %
336             multilist_get_num_sublists(ml));
337 }
338
339 /*
340  * Instantiates the objset_t in-memory structure corresponding to the
341  * objset_phys_t that's pointed to by the specified blkptr_t.
342  */
343 int
344 dmu_objset_open_impl(spa_t *spa, dsl_dataset_t *ds, blkptr_t *bp,
345     objset_t **osp)
346 {
347         objset_t *os;
348         int i, err;
349
350         ASSERT(ds == NULL || MUTEX_HELD(&ds->ds_opening_lock));
351
352 #if 0
353         /*
354          * The $ORIGIN dataset (if it exists) doesn't have an associated
355          * objset, so there's no reason to open it. The $ORIGIN dataset
356          * will not exist on pools older than SPA_VERSION_ORIGIN.
357          */
358         if (ds != NULL && spa_get_dsl(spa) != NULL &&
359             spa_get_dsl(spa)->dp_origin_snap != NULL) {
360                 ASSERT3P(ds->ds_dir, !=,
361                     spa_get_dsl(spa)->dp_origin_snap->ds_dir);
362         }
363 #endif
364
365         os = kmem_zalloc(sizeof (objset_t), KM_SLEEP);
366         os->os_dsl_dataset = ds;
367         os->os_spa = spa;
368         os->os_rootbp = bp;
369         if (!BP_IS_HOLE(os->os_rootbp)) {
370                 arc_flags_t aflags = ARC_FLAG_WAIT;
371                 zbookmark_phys_t zb;
372                 SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
373                     ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
374
375                 if (DMU_OS_IS_L2CACHEABLE(os))
376                         aflags |= ARC_FLAG_L2CACHE;
377
378                 dprintf_bp(os->os_rootbp, "reading %s", "");
379                 err = arc_read(NULL, spa, os->os_rootbp,
380                     arc_getbuf_func, &os->os_phys_buf,
381                     ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_CANFAIL, &aflags, &zb);
382                 if (err != 0) {
383                         kmem_free(os, sizeof (objset_t));
384                         /* convert checksum errors into IO errors */
385                         if (err == ECKSUM)
386                                 err = SET_ERROR(EIO);
387                         return (err);
388                 }
389
390                 /* Increase the blocksize if we are permitted. */
391                 if (spa_version(spa) >= SPA_VERSION_USERSPACE &&
392                     arc_buf_size(os->os_phys_buf) < sizeof (objset_phys_t)) {
393                         arc_buf_t *buf = arc_alloc_buf(spa, &os->os_phys_buf,
394                             ARC_BUFC_METADATA, sizeof (objset_phys_t));
395                         bzero(buf->b_data, sizeof (objset_phys_t));
396                         bcopy(os->os_phys_buf->b_data, buf->b_data,
397                             arc_buf_size(os->os_phys_buf));
398                         arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
399                         os->os_phys_buf = buf;
400                 }
401
402                 os->os_phys = os->os_phys_buf->b_data;
403                 os->os_flags = os->os_phys->os_flags;
404         } else {
405                 int size = spa_version(spa) >= SPA_VERSION_USERSPACE ?
406                     sizeof (objset_phys_t) : OBJSET_OLD_PHYS_SIZE;
407                 os->os_phys_buf = arc_alloc_buf(spa, &os->os_phys_buf,
408                     ARC_BUFC_METADATA, size);
409                 os->os_phys = os->os_phys_buf->b_data;
410                 bzero(os->os_phys, size);
411         }
412
413         /*
414          * Note: the changed_cb will be called once before the register
415          * func returns, thus changing the checksum/compression from the
416          * default (fletcher2/off).  Snapshots don't need to know about
417          * checksum/compression/copies.
418          */
419         if (ds != NULL) {
420                 boolean_t needlock = B_FALSE;
421
422                 /*
423                  * Note: it's valid to open the objset if the dataset is
424                  * long-held, in which case the pool_config lock will not
425                  * be held.
426                  */
427                 if (!dsl_pool_config_held(dmu_objset_pool(os))) {
428                         needlock = B_TRUE;
429                         dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
430                 }
431                 err = dsl_prop_register(ds,
432                     zfs_prop_to_name(ZFS_PROP_PRIMARYCACHE),
433                     primary_cache_changed_cb, os);
434                 if (err == 0) {
435                         err = dsl_prop_register(ds,
436                             zfs_prop_to_name(ZFS_PROP_SECONDARYCACHE),
437                             secondary_cache_changed_cb, os);
438                 }
439                 if (!ds->ds_is_snapshot) {
440                         if (err == 0) {
441                                 err = dsl_prop_register(ds,
442                                     zfs_prop_to_name(ZFS_PROP_CHECKSUM),
443                                     checksum_changed_cb, os);
444                         }
445                         if (err == 0) {
446                                 err = dsl_prop_register(ds,
447                                     zfs_prop_to_name(ZFS_PROP_COMPRESSION),
448                                     compression_changed_cb, os);
449                         }
450                         if (err == 0) {
451                                 err = dsl_prop_register(ds,
452                                     zfs_prop_to_name(ZFS_PROP_COPIES),
453                                     copies_changed_cb, os);
454                         }
455                         if (err == 0) {
456                                 err = dsl_prop_register(ds,
457                                     zfs_prop_to_name(ZFS_PROP_DEDUP),
458                                     dedup_changed_cb, os);
459                         }
460                         if (err == 0) {
461                                 err = dsl_prop_register(ds,
462                                     zfs_prop_to_name(ZFS_PROP_LOGBIAS),
463                                     logbias_changed_cb, os);
464                         }
465                         if (err == 0) {
466                                 err = dsl_prop_register(ds,
467                                     zfs_prop_to_name(ZFS_PROP_SYNC),
468                                     sync_changed_cb, os);
469                         }
470                         if (err == 0) {
471                                 err = dsl_prop_register(ds,
472                                     zfs_prop_to_name(
473                                     ZFS_PROP_REDUNDANT_METADATA),
474                                     redundant_metadata_changed_cb, os);
475                         }
476                         if (err == 0) {
477                                 err = dsl_prop_register(ds,
478                                     zfs_prop_to_name(ZFS_PROP_RECORDSIZE),
479                                     recordsize_changed_cb, os);
480                         }
481                 }
482                 if (needlock)
483                         dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
484                 if (err != 0) {
485                         arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
486                         kmem_free(os, sizeof (objset_t));
487                         return (err);
488                 }
489         } else {
490                 /* It's the meta-objset. */
491                 os->os_checksum = ZIO_CHECKSUM_FLETCHER_4;
492                 os->os_compress = ZIO_COMPRESS_ON;
493                 os->os_copies = spa_max_replication(spa);
494                 os->os_dedup_checksum = ZIO_CHECKSUM_OFF;
495                 os->os_dedup_verify = B_FALSE;
496                 os->os_logbias = ZFS_LOGBIAS_LATENCY;
497                 os->os_sync = ZFS_SYNC_STANDARD;
498                 os->os_primary_cache = ZFS_CACHE_ALL;
499                 os->os_secondary_cache = ZFS_CACHE_ALL;
500         }
501         /*
502          * These properties will be filled in by the logic in zfs_get_zplprop()
503          * when they are queried for the first time.
504          */
505         os->os_version = OBJSET_PROP_UNINITIALIZED;
506         os->os_normalization = OBJSET_PROP_UNINITIALIZED;
507         os->os_utf8only = OBJSET_PROP_UNINITIALIZED;
508         os->os_casesensitivity = OBJSET_PROP_UNINITIALIZED;
509
510         if (ds == NULL || !ds->ds_is_snapshot)
511                 os->os_zil_header = os->os_phys->os_zil_header;
512         os->os_zil = zil_alloc(os, &os->os_zil_header);
513
514         for (i = 0; i < TXG_SIZE; i++) {
515                 os->os_dirty_dnodes[i] = multilist_create(sizeof (dnode_t),
516                     offsetof(dnode_t, dn_dirty_link[i]),
517                     dnode_multilist_index_func);
518         }
519         list_create(&os->os_dnodes, sizeof (dnode_t),
520             offsetof(dnode_t, dn_link));
521         list_create(&os->os_downgraded_dbufs, sizeof (dmu_buf_impl_t),
522             offsetof(dmu_buf_impl_t, db_link));
523
524         mutex_init(&os->os_lock, NULL, MUTEX_DEFAULT, NULL);
525         mutex_init(&os->os_userused_lock, NULL, MUTEX_DEFAULT, NULL);
526         mutex_init(&os->os_obj_lock, NULL, MUTEX_DEFAULT, NULL);
527         mutex_init(&os->os_user_ptr_lock, NULL, MUTEX_DEFAULT, NULL);
528
529         dnode_special_open(os, &os->os_phys->os_meta_dnode,
530             DMU_META_DNODE_OBJECT, &os->os_meta_dnode);
531         if (arc_buf_size(os->os_phys_buf) >= sizeof (objset_phys_t)) {
532                 dnode_special_open(os, &os->os_phys->os_userused_dnode,
533                     DMU_USERUSED_OBJECT, &os->os_userused_dnode);
534                 dnode_special_open(os, &os->os_phys->os_groupused_dnode,
535                     DMU_GROUPUSED_OBJECT, &os->os_groupused_dnode);
536         }
537
538         *osp = os;
539         return (0);
540 }
541
542 int
543 dmu_objset_from_ds(dsl_dataset_t *ds, objset_t **osp)
544 {
545         int err = 0;
546
547         /*
548          * We shouldn't be doing anything with dsl_dataset_t's unless the
549          * pool_config lock is held, or the dataset is long-held.
550          */
551         ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool) ||
552             dsl_dataset_long_held(ds));
553
554         mutex_enter(&ds->ds_opening_lock);
555         if (ds->ds_objset == NULL) {
556                 objset_t *os;
557                 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
558                 err = dmu_objset_open_impl(dsl_dataset_get_spa(ds),
559                     ds, dsl_dataset_get_blkptr(ds), &os);
560                 rrw_exit(&ds->ds_bp_rwlock, FTAG);
561
562                 if (err == 0) {
563                         mutex_enter(&ds->ds_lock);
564                         ASSERT(ds->ds_objset == NULL);
565                         ds->ds_objset = os;
566                         mutex_exit(&ds->ds_lock);
567                 }
568         }
569         *osp = ds->ds_objset;
570         mutex_exit(&ds->ds_opening_lock);
571         return (err);
572 }
573
574 /*
575  * Holds the pool while the objset is held.  Therefore only one objset
576  * can be held at a time.
577  */
578 int
579 dmu_objset_hold(const char *name, void *tag, objset_t **osp)
580 {
581         dsl_pool_t *dp;
582         dsl_dataset_t *ds;
583         int err;
584
585         err = dsl_pool_hold(name, tag, &dp);
586         if (err != 0)
587                 return (err);
588         err = dsl_dataset_hold(dp, name, tag, &ds);
589         if (err != 0) {
590                 dsl_pool_rele(dp, tag);
591                 return (err);
592         }
593
594         err = dmu_objset_from_ds(ds, osp);
595         if (err != 0) {
596                 dsl_dataset_rele(ds, tag);
597                 dsl_pool_rele(dp, tag);
598         }
599
600         return (err);
601 }
602
603 static int
604 dmu_objset_own_impl(dsl_dataset_t *ds, dmu_objset_type_t type,
605     boolean_t readonly, void *tag, objset_t **osp)
606 {
607         int err;
608
609         err = dmu_objset_from_ds(ds, osp);
610         if (err != 0) {
611                 dsl_dataset_disown(ds, tag);
612         } else if (type != DMU_OST_ANY && type != (*osp)->os_phys->os_type) {
613                 dsl_dataset_disown(ds, tag);
614                 return (SET_ERROR(EINVAL));
615         } else if (!readonly && dsl_dataset_is_snapshot(ds)) {
616                 dsl_dataset_disown(ds, tag);
617                 return (SET_ERROR(EROFS));
618         }
619         return (err);
620 }
621
622 /*
623  * dsl_pool must not be held when this is called.
624  * Upon successful return, there will be a longhold on the dataset,
625  * and the dsl_pool will not be held.
626  */
627 int
628 dmu_objset_own(const char *name, dmu_objset_type_t type,
629     boolean_t readonly, void *tag, objset_t **osp)
630 {
631         dsl_pool_t *dp;
632         dsl_dataset_t *ds;
633         int err;
634
635         err = dsl_pool_hold(name, FTAG, &dp);
636         if (err != 0)
637                 return (err);
638         err = dsl_dataset_own(dp, name, tag, &ds);
639         if (err != 0) {
640                 dsl_pool_rele(dp, FTAG);
641                 return (err);
642         }
643         err = dmu_objset_own_impl(ds, type, readonly, tag, osp);
644         dsl_pool_rele(dp, FTAG);
645
646         return (err);
647 }
648
649 int
650 dmu_objset_own_obj(dsl_pool_t *dp, uint64_t obj, dmu_objset_type_t type,
651     boolean_t readonly, void *tag, objset_t **osp)
652 {
653         dsl_dataset_t *ds;
654         int err;
655
656         err = dsl_dataset_own_obj(dp, obj, tag, &ds);
657         if (err != 0)
658                 return (err);
659
660         return (dmu_objset_own_impl(ds, type, readonly, tag, osp));
661 }
662
663 void
664 dmu_objset_rele(objset_t *os, void *tag)
665 {
666         dsl_pool_t *dp = dmu_objset_pool(os);
667         dsl_dataset_rele(os->os_dsl_dataset, tag);
668         dsl_pool_rele(dp, tag);
669 }
670
671 /*
672  * When we are called, os MUST refer to an objset associated with a dataset
673  * that is owned by 'tag'; that is, is held and long held by 'tag' and ds_owner
674  * == tag.  We will then release and reacquire ownership of the dataset while
675  * holding the pool config_rwlock to avoid intervening namespace or ownership
676  * changes may occur.
677  *
678  * This exists solely to accommodate zfs_ioc_userspace_upgrade()'s desire to
679  * release the hold on its dataset and acquire a new one on the dataset of the
680  * same name so that it can be partially torn down and reconstructed.
681  */
682 void
683 dmu_objset_refresh_ownership(dsl_dataset_t *ds, dsl_dataset_t **newds,
684     void *tag)
685 {
686         dsl_pool_t *dp;
687         char name[ZFS_MAX_DATASET_NAME_LEN];
688
689         VERIFY3P(ds, !=, NULL);
690         VERIFY3P(ds->ds_owner, ==, tag);
691         VERIFY(dsl_dataset_long_held(ds));
692
693         dsl_dataset_name(ds, name);
694         dp = ds->ds_dir->dd_pool;
695         dsl_pool_config_enter(dp, FTAG);
696         dsl_dataset_disown(ds, tag);
697         VERIFY0(dsl_dataset_own(dp, name, tag, newds));
698         dsl_pool_config_exit(dp, FTAG);
699 }
700
701 void
702 dmu_objset_disown(objset_t *os, void *tag)
703 {
704         dsl_dataset_disown(os->os_dsl_dataset, tag);
705 }
706
707 void
708 dmu_objset_evict_dbufs(objset_t *os)
709 {
710         dnode_t dn_marker;
711         dnode_t *dn;
712
713         mutex_enter(&os->os_lock);
714         dn = list_head(&os->os_dnodes);
715         while (dn != NULL) {
716                 /*
717                  * Skip dnodes without holds.  We have to do this dance
718                  * because dnode_add_ref() only works if there is already a
719                  * hold.  If the dnode has no holds, then it has no dbufs.
720                  */
721                 if (dnode_add_ref(dn, FTAG)) {
722                         list_insert_after(&os->os_dnodes, dn, &dn_marker);
723                         mutex_exit(&os->os_lock);
724
725                         dnode_evict_dbufs(dn);
726                         dnode_rele(dn, FTAG);
727
728                         mutex_enter(&os->os_lock);
729                         dn = list_next(&os->os_dnodes, &dn_marker);
730                         list_remove(&os->os_dnodes, &dn_marker);
731                 } else {
732                         dn = list_next(&os->os_dnodes, dn);
733                 }
734         }
735         mutex_exit(&os->os_lock);
736
737         if (DMU_USERUSED_DNODE(os) != NULL) {
738                 dnode_evict_dbufs(DMU_GROUPUSED_DNODE(os));
739                 dnode_evict_dbufs(DMU_USERUSED_DNODE(os));
740         }
741         dnode_evict_dbufs(DMU_META_DNODE(os));
742 }
743
744 /*
745  * Objset eviction processing is split into into two pieces.
746  * The first marks the objset as evicting, evicts any dbufs that
747  * have a refcount of zero, and then queues up the objset for the
748  * second phase of eviction.  Once os->os_dnodes has been cleared by
749  * dnode_buf_pageout()->dnode_destroy(), the second phase is executed.
750  * The second phase closes the special dnodes, dequeues the objset from
751  * the list of those undergoing eviction, and finally frees the objset.
752  *
753  * NOTE: Due to asynchronous eviction processing (invocation of
754  *       dnode_buf_pageout()), it is possible for the meta dnode for the
755  *       objset to have no holds even though os->os_dnodes is not empty.
756  */
757 void
758 dmu_objset_evict(objset_t *os)
759 {
760         dsl_dataset_t *ds = os->os_dsl_dataset;
761
762         for (int t = 0; t < TXG_SIZE; t++)
763                 ASSERT(!dmu_objset_is_dirty(os, t));
764
765         if (ds)
766                 dsl_prop_unregister_all(ds, os);
767
768         if (os->os_sa)
769                 sa_tear_down(os);
770
771         dmu_objset_evict_dbufs(os);
772
773         mutex_enter(&os->os_lock);
774         spa_evicting_os_register(os->os_spa, os);
775         if (list_is_empty(&os->os_dnodes)) {
776                 mutex_exit(&os->os_lock);
777                 dmu_objset_evict_done(os);
778         } else {
779                 mutex_exit(&os->os_lock);
780         }
781 }
782
783 void
784 dmu_objset_evict_done(objset_t *os)
785 {
786         ASSERT3P(list_head(&os->os_dnodes), ==, NULL);
787
788         dnode_special_close(&os->os_meta_dnode);
789         if (DMU_USERUSED_DNODE(os)) {
790                 dnode_special_close(&os->os_userused_dnode);
791                 dnode_special_close(&os->os_groupused_dnode);
792         }
793         zil_free(os->os_zil);
794
795         arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
796
797         /*
798          * This is a barrier to prevent the objset from going away in
799          * dnode_move() until we can safely ensure that the objset is still in
800          * use. We consider the objset valid before the barrier and invalid
801          * after the barrier.
802          */
803         rw_enter(&os_lock, RW_READER);
804         rw_exit(&os_lock);
805
806         mutex_destroy(&os->os_lock);
807         mutex_destroy(&os->os_userused_lock);
808         mutex_destroy(&os->os_obj_lock);
809         mutex_destroy(&os->os_user_ptr_lock);
810         for (int i = 0; i < TXG_SIZE; i++) {
811                 multilist_destroy(os->os_dirty_dnodes[i]);
812         }
813         spa_evicting_os_deregister(os->os_spa, os);
814         kmem_free(os, sizeof (objset_t));
815 }
816
817 timestruc_t
818 dmu_objset_snap_cmtime(objset_t *os)
819 {
820         return (dsl_dir_snap_cmtime(os->os_dsl_dataset->ds_dir));
821 }
822
823 /* called from dsl for meta-objset */
824 objset_t *
825 dmu_objset_create_impl(spa_t *spa, dsl_dataset_t *ds, blkptr_t *bp,
826     dmu_objset_type_t type, dmu_tx_t *tx)
827 {
828         objset_t *os;
829         dnode_t *mdn;
830
831         ASSERT(dmu_tx_is_syncing(tx));
832
833         if (ds != NULL)
834                 VERIFY0(dmu_objset_from_ds(ds, &os));
835         else
836                 VERIFY0(dmu_objset_open_impl(spa, NULL, bp, &os));
837
838         mdn = DMU_META_DNODE(os);
839
840         dnode_allocate(mdn, DMU_OT_DNODE, 1 << DNODE_BLOCK_SHIFT,
841             DN_MAX_INDBLKSHIFT, DMU_OT_NONE, 0, tx);
842
843         /*
844          * We don't want to have to increase the meta-dnode's nlevels
845          * later, because then we could do it in quescing context while
846          * we are also accessing it in open context.
847          *
848          * This precaution is not necessary for the MOS (ds == NULL),
849          * because the MOS is only updated in syncing context.
850          * This is most fortunate: the MOS is the only objset that
851          * needs to be synced multiple times as spa_sync() iterates
852          * to convergence, so minimizing its dn_nlevels matters.
853          */
854         if (ds != NULL) {
855                 int levels = 1;
856
857                 /*
858                  * Determine the number of levels necessary for the meta-dnode
859                  * to contain DN_MAX_OBJECT dnodes.  Note that in order to
860                  * ensure that we do not overflow 64 bits, there has to be
861                  * a nlevels that gives us a number of blocks > DN_MAX_OBJECT
862                  * but < 2^64.  Therefore,
863                  * (mdn->dn_indblkshift - SPA_BLKPTRSHIFT) (10) must be
864                  * less than (64 - log2(DN_MAX_OBJECT)) (16).
865                  */
866                 while ((uint64_t)mdn->dn_nblkptr <<
867                     (mdn->dn_datablkshift - DNODE_SHIFT +
868                     (levels - 1) * (mdn->dn_indblkshift - SPA_BLKPTRSHIFT)) <
869                     DN_MAX_OBJECT)
870                         levels++;
871
872                 mdn->dn_next_nlevels[tx->tx_txg & TXG_MASK] =
873                     mdn->dn_nlevels = levels;
874         }
875
876         ASSERT(type != DMU_OST_NONE);
877         ASSERT(type != DMU_OST_ANY);
878         ASSERT(type < DMU_OST_NUMTYPES);
879         os->os_phys->os_type = type;
880         if (dmu_objset_userused_enabled(os)) {
881                 os->os_phys->os_flags |= OBJSET_FLAG_USERACCOUNTING_COMPLETE;
882                 os->os_flags = os->os_phys->os_flags;
883         }
884
885         dsl_dataset_dirty(ds, tx);
886
887         return (os);
888 }
889
890 typedef struct dmu_objset_create_arg {
891         const char *doca_name;
892         cred_t *doca_cred;
893         void (*doca_userfunc)(objset_t *os, void *arg,
894             cred_t *cr, dmu_tx_t *tx);
895         void *doca_userarg;
896         dmu_objset_type_t doca_type;
897         uint64_t doca_flags;
898 } dmu_objset_create_arg_t;
899
900 /*ARGSUSED*/
901 static int
902 dmu_objset_create_check(void *arg, dmu_tx_t *tx)
903 {
904         dmu_objset_create_arg_t *doca = arg;
905         dsl_pool_t *dp = dmu_tx_pool(tx);
906         dsl_dir_t *pdd;
907         const char *tail;
908         int error;
909
910         if (strchr(doca->doca_name, '@') != NULL)
911                 return (SET_ERROR(EINVAL));
912
913         if (strlen(doca->doca_name) >= ZFS_MAX_DATASET_NAME_LEN)
914                 return (SET_ERROR(ENAMETOOLONG));
915
916         error = dsl_dir_hold(dp, doca->doca_name, FTAG, &pdd, &tail);
917         if (error != 0)
918                 return (error);
919         if (tail == NULL) {
920                 dsl_dir_rele(pdd, FTAG);
921                 return (SET_ERROR(EEXIST));
922         }
923         error = dsl_fs_ss_limit_check(pdd, 1, ZFS_PROP_FILESYSTEM_LIMIT, NULL,
924             doca->doca_cred);
925         dsl_dir_rele(pdd, FTAG);
926
927         return (error);
928 }
929
930 static void
931 dmu_objset_create_sync(void *arg, dmu_tx_t *tx)
932 {
933         dmu_objset_create_arg_t *doca = arg;
934         dsl_pool_t *dp = dmu_tx_pool(tx);
935         dsl_dir_t *pdd;
936         const char *tail;
937         dsl_dataset_t *ds;
938         uint64_t obj;
939         blkptr_t *bp;
940         objset_t *os;
941
942         VERIFY0(dsl_dir_hold(dp, doca->doca_name, FTAG, &pdd, &tail));
943
944         obj = dsl_dataset_create_sync(pdd, tail, NULL, doca->doca_flags,
945             doca->doca_cred, tx);
946
947         VERIFY0(dsl_dataset_hold_obj(pdd->dd_pool, obj, FTAG, &ds));
948         rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
949         bp = dsl_dataset_get_blkptr(ds);
950         os = dmu_objset_create_impl(pdd->dd_pool->dp_spa,
951             ds, bp, doca->doca_type, tx);
952         rrw_exit(&ds->ds_bp_rwlock, FTAG);
953
954         if (doca->doca_userfunc != NULL) {
955                 doca->doca_userfunc(os, doca->doca_userarg,
956                     doca->doca_cred, tx);
957         }
958
959         spa_history_log_internal_ds(ds, "create", tx, "");
960         dsl_dataset_rele(ds, FTAG);
961         dsl_dir_rele(pdd, FTAG);
962 }
963
964 int
965 dmu_objset_create(const char *name, dmu_objset_type_t type, uint64_t flags,
966     void (*func)(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx), void *arg)
967 {
968         dmu_objset_create_arg_t doca;
969
970         doca.doca_name = name;
971         doca.doca_cred = CRED();
972         doca.doca_flags = flags;
973         doca.doca_userfunc = func;
974         doca.doca_userarg = arg;
975         doca.doca_type = type;
976
977         return (dsl_sync_task(name,
978             dmu_objset_create_check, dmu_objset_create_sync, &doca,
979             5, ZFS_SPACE_CHECK_NORMAL));
980 }
981
982 typedef struct dmu_objset_clone_arg {
983         const char *doca_clone;
984         const char *doca_origin;
985         cred_t *doca_cred;
986 } dmu_objset_clone_arg_t;
987
988 /*ARGSUSED*/
989 static int
990 dmu_objset_clone_check(void *arg, dmu_tx_t *tx)
991 {
992         dmu_objset_clone_arg_t *doca = arg;
993         dsl_dir_t *pdd;
994         const char *tail;
995         int error;
996         dsl_dataset_t *origin;
997         dsl_pool_t *dp = dmu_tx_pool(tx);
998
999         if (strchr(doca->doca_clone, '@') != NULL)
1000                 return (SET_ERROR(EINVAL));
1001
1002         if (strlen(doca->doca_clone) >= ZFS_MAX_DATASET_NAME_LEN)
1003                 return (SET_ERROR(ENAMETOOLONG));
1004
1005         error = dsl_dir_hold(dp, doca->doca_clone, FTAG, &pdd, &tail);
1006         if (error != 0)
1007                 return (error);
1008         if (tail == NULL) {
1009                 dsl_dir_rele(pdd, FTAG);
1010                 return (SET_ERROR(EEXIST));
1011         }
1012
1013         error = dsl_fs_ss_limit_check(pdd, 1, ZFS_PROP_FILESYSTEM_LIMIT, NULL,
1014             doca->doca_cred);
1015         if (error != 0) {
1016                 dsl_dir_rele(pdd, FTAG);
1017                 return (SET_ERROR(EDQUOT));
1018         }
1019         dsl_dir_rele(pdd, FTAG);
1020
1021         error = dsl_dataset_hold(dp, doca->doca_origin, FTAG, &origin);
1022         if (error != 0)
1023                 return (error);
1024
1025         /* You can only clone snapshots, not the head datasets. */
1026         if (!origin->ds_is_snapshot) {
1027                 dsl_dataset_rele(origin, FTAG);
1028                 return (SET_ERROR(EINVAL));
1029         }
1030         dsl_dataset_rele(origin, FTAG);
1031
1032         return (0);
1033 }
1034
1035 static void
1036 dmu_objset_clone_sync(void *arg, dmu_tx_t *tx)
1037 {
1038         dmu_objset_clone_arg_t *doca = arg;
1039         dsl_pool_t *dp = dmu_tx_pool(tx);
1040         dsl_dir_t *pdd;
1041         const char *tail;
1042         dsl_dataset_t *origin, *ds;
1043         uint64_t obj;
1044         char namebuf[ZFS_MAX_DATASET_NAME_LEN];
1045
1046         VERIFY0(dsl_dir_hold(dp, doca->doca_clone, FTAG, &pdd, &tail));
1047         VERIFY0(dsl_dataset_hold(dp, doca->doca_origin, FTAG, &origin));
1048
1049         obj = dsl_dataset_create_sync(pdd, tail, origin, 0,
1050             doca->doca_cred, tx);
1051
1052         VERIFY0(dsl_dataset_hold_obj(pdd->dd_pool, obj, FTAG, &ds));
1053         dsl_dataset_name(origin, namebuf);
1054         spa_history_log_internal_ds(ds, "clone", tx,
1055             "origin=%s (%llu)", namebuf, origin->ds_object);
1056         dsl_dataset_rele(ds, FTAG);
1057         dsl_dataset_rele(origin, FTAG);
1058         dsl_dir_rele(pdd, FTAG);
1059 }
1060
1061 int
1062 dmu_objset_clone(const char *clone, const char *origin)
1063 {
1064         dmu_objset_clone_arg_t doca;
1065
1066         doca.doca_clone = clone;
1067         doca.doca_origin = origin;
1068         doca.doca_cred = CRED();
1069
1070         return (dsl_sync_task(clone,
1071             dmu_objset_clone_check, dmu_objset_clone_sync, &doca,
1072             5, ZFS_SPACE_CHECK_NORMAL));
1073 }
1074
1075 static int
1076 dmu_objset_remap_indirects_impl(objset_t *os, uint64_t last_removed_txg)
1077 {
1078         int error = 0;
1079         uint64_t object = 0;
1080         while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
1081                 error = dmu_object_remap_indirects(os, object,
1082                     last_removed_txg);
1083                 /*
1084                  * If the ZPL removed the object before we managed to dnode_hold
1085                  * it, we would get an ENOENT. If the ZPL declares its intent
1086                  * to remove the object (dnode_free) before we manage to
1087                  * dnode_hold it, we would get an EEXIST. In either case, we
1088                  * want to continue remapping the other objects in the objset;
1089                  * in all other cases, we want to break early.
1090                  */
1091                 if (error != 0 && error != ENOENT && error != EEXIST) {
1092                         break;
1093                 }
1094         }
1095         if (error == ESRCH) {
1096                 error = 0;
1097         }
1098         return (error);
1099 }
1100
1101 int
1102 dmu_objset_remap_indirects(const char *fsname)
1103 {
1104         int error = 0;
1105         objset_t *os = NULL;
1106         uint64_t last_removed_txg;
1107         uint64_t remap_start_txg;
1108         dsl_dir_t *dd;
1109
1110         error = dmu_objset_hold(fsname, FTAG, &os);
1111         if (error != 0) {
1112                 return (error);
1113         }
1114         dd = dmu_objset_ds(os)->ds_dir;
1115
1116         if (!spa_feature_is_enabled(dmu_objset_spa(os),
1117             SPA_FEATURE_OBSOLETE_COUNTS)) {
1118                 dmu_objset_rele(os, FTAG);
1119                 return (SET_ERROR(ENOTSUP));
1120         }
1121
1122         if (dsl_dataset_is_snapshot(dmu_objset_ds(os))) {
1123                 dmu_objset_rele(os, FTAG);
1124                 return (SET_ERROR(EINVAL));
1125         }
1126
1127         /*
1128          * If there has not been a removal, we're done.
1129          */
1130         last_removed_txg = spa_get_last_removal_txg(dmu_objset_spa(os));
1131         if (last_removed_txg == -1ULL) {
1132                 dmu_objset_rele(os, FTAG);
1133                 return (0);
1134         }
1135
1136         /*
1137          * If we have remapped since the last removal, we're done.
1138          */
1139         if (dsl_dir_is_zapified(dd)) {
1140                 uint64_t last_remap_txg;
1141                 if (zap_lookup(spa_meta_objset(dmu_objset_spa(os)),
1142                     dd->dd_object, DD_FIELD_LAST_REMAP_TXG,
1143                     sizeof (last_remap_txg), 1, &last_remap_txg) == 0 &&
1144                     last_remap_txg > last_removed_txg) {
1145                         dmu_objset_rele(os, FTAG);
1146                         return (0);
1147                 }
1148         }
1149
1150         dsl_dataset_long_hold(dmu_objset_ds(os), FTAG);
1151         dsl_pool_rele(dmu_objset_pool(os), FTAG);
1152
1153         remap_start_txg = spa_last_synced_txg(dmu_objset_spa(os));
1154         error = dmu_objset_remap_indirects_impl(os, last_removed_txg);
1155         if (error == 0) {
1156                 /*
1157                  * We update the last_remap_txg to be the start txg so that
1158                  * we can guarantee that every block older than last_remap_txg
1159                  * that can be remapped has been remapped.
1160                  */
1161                 error = dsl_dir_update_last_remap_txg(dd, remap_start_txg);
1162         }
1163
1164         dsl_dataset_long_rele(dmu_objset_ds(os), FTAG);
1165         dsl_dataset_rele(dmu_objset_ds(os), FTAG);
1166
1167         return (error);
1168 }
1169
1170 int
1171 dmu_objset_snapshot_one(const char *fsname, const char *snapname)
1172 {
1173         int err;
1174         char *longsnap = kmem_asprintf("%s@%s", fsname, snapname);
1175         nvlist_t *snaps = fnvlist_alloc();
1176
1177         fnvlist_add_boolean(snaps, longsnap);
1178         strfree(longsnap);
1179         err = dsl_dataset_snapshot(snaps, NULL, NULL);
1180         fnvlist_free(snaps);
1181         return (err);
1182 }
1183
1184 static void
1185 dmu_objset_sync_dnodes(multilist_sublist_t *list, dmu_tx_t *tx)
1186 {
1187         dnode_t *dn;
1188
1189         while ((dn = multilist_sublist_head(list)) != NULL) {
1190                 ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
1191                 ASSERT(dn->dn_dbuf->db_data_pending);
1192                 /*
1193                  * Initialize dn_zio outside dnode_sync() because the
1194                  * meta-dnode needs to set it ouside dnode_sync().
1195                  */
1196                 dn->dn_zio = dn->dn_dbuf->db_data_pending->dr_zio;
1197                 ASSERT(dn->dn_zio);
1198
1199                 ASSERT3U(dn->dn_nlevels, <=, DN_MAX_LEVELS);
1200                 multilist_sublist_remove(list, dn);
1201
1202                 multilist_t *newlist = dn->dn_objset->os_synced_dnodes;
1203                 if (newlist != NULL) {
1204                         (void) dnode_add_ref(dn, newlist);
1205                         multilist_insert(newlist, dn);
1206                 }
1207
1208                 dnode_sync(dn, tx);
1209         }
1210 }
1211
1212 /* ARGSUSED */
1213 static void
1214 dmu_objset_write_ready(zio_t *zio, arc_buf_t *abuf, void *arg)
1215 {
1216         blkptr_t *bp = zio->io_bp;
1217         objset_t *os = arg;
1218         dnode_phys_t *dnp = &os->os_phys->os_meta_dnode;
1219
1220         ASSERT(!BP_IS_EMBEDDED(bp));
1221         ASSERT3U(BP_GET_TYPE(bp), ==, DMU_OT_OBJSET);
1222         ASSERT0(BP_GET_LEVEL(bp));
1223
1224         /*
1225          * Update rootbp fill count: it should be the number of objects
1226          * allocated in the object set (not counting the "special"
1227          * objects that are stored in the objset_phys_t -- the meta
1228          * dnode and user/group accounting objects).
1229          */
1230         bp->blk_fill = 0;
1231         for (int i = 0; i < dnp->dn_nblkptr; i++)
1232                 bp->blk_fill += BP_GET_FILL(&dnp->dn_blkptr[i]);
1233         if (os->os_dsl_dataset != NULL)
1234                 rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_WRITER, FTAG);
1235         *os->os_rootbp = *bp;
1236         if (os->os_dsl_dataset != NULL)
1237                 rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1238 }
1239
1240 /* ARGSUSED */
1241 static void
1242 dmu_objset_write_done(zio_t *zio, arc_buf_t *abuf, void *arg)
1243 {
1244         blkptr_t *bp = zio->io_bp;
1245         blkptr_t *bp_orig = &zio->io_bp_orig;
1246         objset_t *os = arg;
1247
1248         if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
1249                 ASSERT(BP_EQUAL(bp, bp_orig));
1250         } else {
1251                 dsl_dataset_t *ds = os->os_dsl_dataset;
1252                 dmu_tx_t *tx = os->os_synctx;
1253
1254                 (void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
1255                 dsl_dataset_block_born(ds, bp, tx);
1256         }
1257         kmem_free(bp, sizeof (*bp));
1258 }
1259
1260 typedef struct sync_dnodes_arg {
1261         multilist_t *sda_list;
1262         int sda_sublist_idx;
1263         multilist_t *sda_newlist;
1264         dmu_tx_t *sda_tx;
1265 } sync_dnodes_arg_t;
1266
1267 static void
1268 sync_dnodes_task(void *arg)
1269 {
1270         sync_dnodes_arg_t *sda = arg;
1271
1272         multilist_sublist_t *ms =
1273             multilist_sublist_lock(sda->sda_list, sda->sda_sublist_idx);
1274
1275         dmu_objset_sync_dnodes(ms, sda->sda_tx);
1276
1277         multilist_sublist_unlock(ms);
1278
1279         kmem_free(sda, sizeof (*sda));
1280 }
1281
1282
1283 /* called from dsl */
1284 void
1285 dmu_objset_sync(objset_t *os, zio_t *pio, dmu_tx_t *tx)
1286 {
1287         int txgoff;
1288         zbookmark_phys_t zb;
1289         zio_prop_t zp;
1290         zio_t *zio;
1291         list_t *list;
1292         dbuf_dirty_record_t *dr;
1293         blkptr_t *blkptr_copy = kmem_alloc(sizeof (*os->os_rootbp), KM_SLEEP);
1294         *blkptr_copy = *os->os_rootbp;
1295
1296         dprintf_ds(os->os_dsl_dataset, "txg=%llu\n", tx->tx_txg);
1297
1298         ASSERT(dmu_tx_is_syncing(tx));
1299         /* XXX the write_done callback should really give us the tx... */
1300         os->os_synctx = tx;
1301
1302         if (os->os_dsl_dataset == NULL) {
1303                 /*
1304                  * This is the MOS.  If we have upgraded,
1305                  * spa_max_replication() could change, so reset
1306                  * os_copies here.
1307                  */
1308                 os->os_copies = spa_max_replication(os->os_spa);
1309         }
1310
1311         /*
1312          * Create the root block IO
1313          */
1314         SET_BOOKMARK(&zb, os->os_dsl_dataset ?
1315             os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
1316             ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
1317         arc_release(os->os_phys_buf, &os->os_phys_buf);
1318
1319         dmu_write_policy(os, NULL, 0, 0, &zp);
1320
1321         zio = arc_write(pio, os->os_spa, tx->tx_txg,
1322             blkptr_copy, os->os_phys_buf, DMU_OS_IS_L2CACHEABLE(os),
1323             &zp, dmu_objset_write_ready, NULL, NULL, dmu_objset_write_done,
1324             os, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
1325
1326         /*
1327          * Sync special dnodes - the parent IO for the sync is the root block
1328          */
1329         DMU_META_DNODE(os)->dn_zio = zio;
1330         dnode_sync(DMU_META_DNODE(os), tx);
1331
1332         os->os_phys->os_flags = os->os_flags;
1333
1334         if (DMU_USERUSED_DNODE(os) &&
1335             DMU_USERUSED_DNODE(os)->dn_type != DMU_OT_NONE) {
1336                 DMU_USERUSED_DNODE(os)->dn_zio = zio;
1337                 dnode_sync(DMU_USERUSED_DNODE(os), tx);
1338                 DMU_GROUPUSED_DNODE(os)->dn_zio = zio;
1339                 dnode_sync(DMU_GROUPUSED_DNODE(os), tx);
1340         }
1341
1342         txgoff = tx->tx_txg & TXG_MASK;
1343
1344         if (dmu_objset_userused_enabled(os)) {
1345                 /*
1346                  * We must create the list here because it uses the
1347                  * dn_dirty_link[] of this txg.  But it may already
1348                  * exist because we call dsl_dataset_sync() twice per txg.
1349                  */
1350                 if (os->os_synced_dnodes == NULL) {
1351                         os->os_synced_dnodes =
1352                             multilist_create(sizeof (dnode_t),
1353                             offsetof(dnode_t, dn_dirty_link[txgoff]),
1354                             dnode_multilist_index_func);
1355                 } else {
1356                         ASSERT3U(os->os_synced_dnodes->ml_offset, ==,
1357                             offsetof(dnode_t, dn_dirty_link[txgoff]));
1358                 }
1359         }
1360
1361         for (int i = 0;
1362             i < multilist_get_num_sublists(os->os_dirty_dnodes[txgoff]); i++) {
1363                 sync_dnodes_arg_t *sda = kmem_alloc(sizeof (*sda), KM_SLEEP);
1364                 sda->sda_list = os->os_dirty_dnodes[txgoff];
1365                 sda->sda_sublist_idx = i;
1366                 sda->sda_tx = tx;
1367                 (void) taskq_dispatch(dmu_objset_pool(os)->dp_sync_taskq,
1368                     sync_dnodes_task, sda, 0);
1369                 /* callback frees sda */
1370         }
1371         taskq_wait(dmu_objset_pool(os)->dp_sync_taskq);
1372
1373         list = &DMU_META_DNODE(os)->dn_dirty_records[txgoff];
1374         while ((dr = list_head(list)) != NULL) {
1375                 ASSERT0(dr->dr_dbuf->db_level);
1376                 list_remove(list, dr);
1377                 if (dr->dr_zio)
1378                         zio_nowait(dr->dr_zio);
1379         }
1380
1381         /* Enable dnode backfill if enough objects have been freed. */
1382         if (os->os_freed_dnodes >= dmu_rescan_dnode_threshold) {
1383                 os->os_rescan_dnodes = B_TRUE;
1384                 os->os_freed_dnodes = 0;
1385         }
1386
1387         /*
1388          * Free intent log blocks up to this tx.
1389          */
1390         zil_sync(os->os_zil, tx);
1391         os->os_phys->os_zil_header = os->os_zil_header;
1392         zio_nowait(zio);
1393 }
1394
1395 boolean_t
1396 dmu_objset_is_dirty(objset_t *os, uint64_t txg)
1397 {
1398         return (!multilist_is_empty(os->os_dirty_dnodes[txg & TXG_MASK]));
1399 }
1400
1401 static objset_used_cb_t *used_cbs[DMU_OST_NUMTYPES];
1402
1403 void
1404 dmu_objset_register_type(dmu_objset_type_t ost, objset_used_cb_t *cb)
1405 {
1406         used_cbs[ost] = cb;
1407 }
1408
1409 boolean_t
1410 dmu_objset_userused_enabled(objset_t *os)
1411 {
1412         return (spa_version(os->os_spa) >= SPA_VERSION_USERSPACE &&
1413             used_cbs[os->os_phys->os_type] != NULL &&
1414             DMU_USERUSED_DNODE(os) != NULL);
1415 }
1416
1417 typedef struct userquota_node {
1418         uint64_t uqn_id;
1419         int64_t uqn_delta;
1420         avl_node_t uqn_node;
1421 } userquota_node_t;
1422
1423 typedef struct userquota_cache {
1424         avl_tree_t uqc_user_deltas;
1425         avl_tree_t uqc_group_deltas;
1426 } userquota_cache_t;
1427
1428 static int
1429 userquota_compare(const void *l, const void *r)
1430 {
1431         const userquota_node_t *luqn = l;
1432         const userquota_node_t *ruqn = r;
1433
1434         if (luqn->uqn_id < ruqn->uqn_id)
1435                 return (-1);
1436         if (luqn->uqn_id > ruqn->uqn_id)
1437                 return (1);
1438         return (0);
1439 }
1440
1441 static void
1442 do_userquota_cacheflush(objset_t *os, userquota_cache_t *cache, dmu_tx_t *tx)
1443 {
1444         void *cookie;
1445         userquota_node_t *uqn;
1446
1447         ASSERT(dmu_tx_is_syncing(tx));
1448
1449         cookie = NULL;
1450         while ((uqn = avl_destroy_nodes(&cache->uqc_user_deltas,
1451             &cookie)) != NULL) {
1452                 /*
1453                  * os_userused_lock protects against concurrent calls to
1454                  * zap_increment_int().  It's needed because zap_increment_int()
1455                  * is not thread-safe (i.e. not atomic).
1456                  */
1457                 mutex_enter(&os->os_userused_lock);
1458                 VERIFY0(zap_increment_int(os, DMU_USERUSED_OBJECT,
1459                     uqn->uqn_id, uqn->uqn_delta, tx));
1460                 mutex_exit(&os->os_userused_lock);
1461                 kmem_free(uqn, sizeof (*uqn));
1462         }
1463         avl_destroy(&cache->uqc_user_deltas);
1464
1465         cookie = NULL;
1466         while ((uqn = avl_destroy_nodes(&cache->uqc_group_deltas,
1467             &cookie)) != NULL) {
1468                 mutex_enter(&os->os_userused_lock);
1469                 VERIFY0(zap_increment_int(os, DMU_GROUPUSED_OBJECT,
1470                     uqn->uqn_id, uqn->uqn_delta, tx));
1471                 mutex_exit(&os->os_userused_lock);
1472                 kmem_free(uqn, sizeof (*uqn));
1473         }
1474         avl_destroy(&cache->uqc_group_deltas);
1475 }
1476
1477 static void
1478 userquota_update_cache(avl_tree_t *avl, uint64_t id, int64_t delta)
1479 {
1480         userquota_node_t search = { .uqn_id = id };
1481         avl_index_t idx;
1482
1483         userquota_node_t *uqn = avl_find(avl, &search, &idx);
1484         if (uqn == NULL) {
1485                 uqn = kmem_zalloc(sizeof (*uqn), KM_SLEEP);
1486                 uqn->uqn_id = id;
1487                 avl_insert(avl, uqn, idx);
1488         }
1489         uqn->uqn_delta += delta;
1490 }
1491
1492 static void
1493 do_userquota_update(userquota_cache_t *cache, uint64_t used, uint64_t flags,
1494     uint64_t user, uint64_t group, boolean_t subtract)
1495 {
1496         if ((flags & DNODE_FLAG_USERUSED_ACCOUNTED)) {
1497                 int64_t delta = DNODE_SIZE + used;
1498                 if (subtract)
1499                         delta = -delta;
1500
1501                 userquota_update_cache(&cache->uqc_user_deltas, user, delta);
1502                 userquota_update_cache(&cache->uqc_group_deltas, group, delta);
1503         }
1504 }
1505
1506 typedef struct userquota_updates_arg {
1507         objset_t *uua_os;
1508         int uua_sublist_idx;
1509         dmu_tx_t *uua_tx;
1510 } userquota_updates_arg_t;
1511
1512 static void
1513 userquota_updates_task(void *arg)
1514 {
1515         userquota_updates_arg_t *uua = arg;
1516         objset_t *os = uua->uua_os;
1517         dmu_tx_t *tx = uua->uua_tx;
1518         dnode_t *dn;
1519         userquota_cache_t cache = { 0 };
1520
1521         multilist_sublist_t *list =
1522             multilist_sublist_lock(os->os_synced_dnodes, uua->uua_sublist_idx);
1523
1524         ASSERT(multilist_sublist_head(list) == NULL ||
1525             dmu_objset_userused_enabled(os));
1526         avl_create(&cache.uqc_user_deltas, userquota_compare,
1527             sizeof (userquota_node_t), offsetof(userquota_node_t, uqn_node));
1528         avl_create(&cache.uqc_group_deltas, userquota_compare,
1529             sizeof (userquota_node_t), offsetof(userquota_node_t, uqn_node));
1530
1531         while ((dn = multilist_sublist_head(list)) != NULL) {
1532                 int flags;
1533                 ASSERT(!DMU_OBJECT_IS_SPECIAL(dn->dn_object));
1534                 ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE ||
1535                     dn->dn_phys->dn_flags &
1536                     DNODE_FLAG_USERUSED_ACCOUNTED);
1537
1538                 flags = dn->dn_id_flags;
1539                 ASSERT(flags);
1540                 if (flags & DN_ID_OLD_EXIST)  {
1541                         do_userquota_update(&cache,
1542                             dn->dn_oldused, dn->dn_oldflags,
1543                             dn->dn_olduid, dn->dn_oldgid, B_TRUE);
1544                 }
1545                 if (flags & DN_ID_NEW_EXIST) {
1546                         do_userquota_update(&cache,
1547                             DN_USED_BYTES(dn->dn_phys),
1548                             dn->dn_phys->dn_flags,  dn->dn_newuid,
1549                             dn->dn_newgid, B_FALSE);
1550                 }
1551
1552                 mutex_enter(&dn->dn_mtx);
1553                 dn->dn_oldused = 0;
1554                 dn->dn_oldflags = 0;
1555                 if (dn->dn_id_flags & DN_ID_NEW_EXIST) {
1556                         dn->dn_olduid = dn->dn_newuid;
1557                         dn->dn_oldgid = dn->dn_newgid;
1558                         dn->dn_id_flags |= DN_ID_OLD_EXIST;
1559                         if (dn->dn_bonuslen == 0)
1560                                 dn->dn_id_flags |= DN_ID_CHKED_SPILL;
1561                         else
1562                                 dn->dn_id_flags |= DN_ID_CHKED_BONUS;
1563                 }
1564                 dn->dn_id_flags &= ~(DN_ID_NEW_EXIST);
1565                 mutex_exit(&dn->dn_mtx);
1566
1567                 multilist_sublist_remove(list, dn);
1568                 dnode_rele(dn, os->os_synced_dnodes);
1569         }
1570         do_userquota_cacheflush(os, &cache, tx);
1571         multilist_sublist_unlock(list);
1572         kmem_free(uua, sizeof (*uua));
1573 }
1574
1575 void
1576 dmu_objset_do_userquota_updates(objset_t *os, dmu_tx_t *tx)
1577 {
1578         if (!dmu_objset_userused_enabled(os))
1579                 return;
1580
1581         /* Allocate the user/groupused objects if necessary. */
1582         if (DMU_USERUSED_DNODE(os)->dn_type == DMU_OT_NONE) {
1583                 VERIFY0(zap_create_claim(os,
1584                     DMU_USERUSED_OBJECT,
1585                     DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
1586                 VERIFY0(zap_create_claim(os,
1587                     DMU_GROUPUSED_OBJECT,
1588                     DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
1589         }
1590
1591         for (int i = 0;
1592             i < multilist_get_num_sublists(os->os_synced_dnodes); i++) {
1593                 userquota_updates_arg_t *uua =
1594                     kmem_alloc(sizeof (*uua), KM_SLEEP);
1595                 uua->uua_os = os;
1596                 uua->uua_sublist_idx = i;
1597                 uua->uua_tx = tx;
1598                 /* note: caller does taskq_wait() */
1599                 (void) taskq_dispatch(dmu_objset_pool(os)->dp_sync_taskq,
1600                     userquota_updates_task, uua, 0);
1601                 /* callback frees uua */
1602         }
1603 }
1604
1605 /*
1606  * Returns a pointer to data to find uid/gid from
1607  *
1608  * If a dirty record for transaction group that is syncing can't
1609  * be found then NULL is returned.  In the NULL case it is assumed
1610  * the uid/gid aren't changing.
1611  */
1612 static void *
1613 dmu_objset_userquota_find_data(dmu_buf_impl_t *db, dmu_tx_t *tx)
1614 {
1615         dbuf_dirty_record_t *dr, **drp;
1616         void *data;
1617
1618         if (db->db_dirtycnt == 0)
1619                 return (db->db.db_data);  /* Nothing is changing */
1620
1621         for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1622                 if (dr->dr_txg == tx->tx_txg)
1623                         break;
1624
1625         if (dr == NULL) {
1626                 data = NULL;
1627         } else {
1628                 dnode_t *dn;
1629
1630                 DB_DNODE_ENTER(dr->dr_dbuf);
1631                 dn = DB_DNODE(dr->dr_dbuf);
1632
1633                 if (dn->dn_bonuslen == 0 &&
1634                     dr->dr_dbuf->db_blkid == DMU_SPILL_BLKID)
1635                         data = dr->dt.dl.dr_data->b_data;
1636                 else
1637                         data = dr->dt.dl.dr_data;
1638
1639                 DB_DNODE_EXIT(dr->dr_dbuf);
1640         }
1641
1642         return (data);
1643 }
1644
1645 void
1646 dmu_objset_userquota_get_ids(dnode_t *dn, boolean_t before, dmu_tx_t *tx)
1647 {
1648         objset_t *os = dn->dn_objset;
1649         void *data = NULL;
1650         dmu_buf_impl_t *db = NULL;
1651         uint64_t *user = NULL;
1652         uint64_t *group = NULL;
1653         int flags = dn->dn_id_flags;
1654         int error;
1655         boolean_t have_spill = B_FALSE;
1656
1657         if (!dmu_objset_userused_enabled(dn->dn_objset))
1658                 return;
1659
1660         if (before && (flags & (DN_ID_CHKED_BONUS|DN_ID_OLD_EXIST|
1661             DN_ID_CHKED_SPILL)))
1662                 return;
1663
1664         if (before && dn->dn_bonuslen != 0)
1665                 data = DN_BONUS(dn->dn_phys);
1666         else if (!before && dn->dn_bonuslen != 0) {
1667                 if (dn->dn_bonus) {
1668                         db = dn->dn_bonus;
1669                         mutex_enter(&db->db_mtx);
1670                         data = dmu_objset_userquota_find_data(db, tx);
1671                 } else {
1672                         data = DN_BONUS(dn->dn_phys);
1673                 }
1674         } else if (dn->dn_bonuslen == 0 && dn->dn_bonustype == DMU_OT_SA) {
1675                         int rf = 0;
1676
1677                         if (RW_WRITE_HELD(&dn->dn_struct_rwlock))
1678                                 rf |= DB_RF_HAVESTRUCT;
1679                         error = dmu_spill_hold_by_dnode(dn,
1680                             rf | DB_RF_MUST_SUCCEED,
1681                             FTAG, (dmu_buf_t **)&db);
1682                         ASSERT(error == 0);
1683                         mutex_enter(&db->db_mtx);
1684                         data = (before) ? db->db.db_data :
1685                             dmu_objset_userquota_find_data(db, tx);
1686                         have_spill = B_TRUE;
1687         } else {
1688                 mutex_enter(&dn->dn_mtx);
1689                 dn->dn_id_flags |= DN_ID_CHKED_BONUS;
1690                 mutex_exit(&dn->dn_mtx);
1691                 return;
1692         }
1693
1694         if (before) {
1695                 ASSERT(data);
1696                 user = &dn->dn_olduid;
1697                 group = &dn->dn_oldgid;
1698         } else if (data) {
1699                 user = &dn->dn_newuid;
1700                 group = &dn->dn_newgid;
1701         }
1702
1703         /*
1704          * Must always call the callback in case the object
1705          * type has changed and that type isn't an object type to track
1706          */
1707         error = used_cbs[os->os_phys->os_type](dn->dn_bonustype, data,
1708             user, group);
1709
1710         /*
1711          * Preserve existing uid/gid when the callback can't determine
1712          * what the new uid/gid are and the callback returned EEXIST.
1713          * The EEXIST error tells us to just use the existing uid/gid.
1714          * If we don't know what the old values are then just assign
1715          * them to 0, since that is a new file  being created.
1716          */
1717         if (!before && data == NULL && error == EEXIST) {
1718                 if (flags & DN_ID_OLD_EXIST) {
1719                         dn->dn_newuid = dn->dn_olduid;
1720                         dn->dn_newgid = dn->dn_oldgid;
1721                 } else {
1722                         dn->dn_newuid = 0;
1723                         dn->dn_newgid = 0;
1724                 }
1725                 error = 0;
1726         }
1727
1728         if (db)
1729                 mutex_exit(&db->db_mtx);
1730
1731         mutex_enter(&dn->dn_mtx);
1732         if (error == 0 && before)
1733                 dn->dn_id_flags |= DN_ID_OLD_EXIST;
1734         if (error == 0 && !before)
1735                 dn->dn_id_flags |= DN_ID_NEW_EXIST;
1736
1737         if (have_spill) {
1738                 dn->dn_id_flags |= DN_ID_CHKED_SPILL;
1739         } else {
1740                 dn->dn_id_flags |= DN_ID_CHKED_BONUS;
1741         }
1742         mutex_exit(&dn->dn_mtx);
1743         if (have_spill)
1744                 dmu_buf_rele((dmu_buf_t *)db, FTAG);
1745 }
1746
1747 boolean_t
1748 dmu_objset_userspace_present(objset_t *os)
1749 {
1750         return (os->os_phys->os_flags &
1751             OBJSET_FLAG_USERACCOUNTING_COMPLETE);
1752 }
1753
1754 int
1755 dmu_objset_userspace_upgrade(objset_t *os)
1756 {
1757         uint64_t obj;
1758         int err = 0;
1759
1760         if (dmu_objset_userspace_present(os))
1761                 return (0);
1762         if (!dmu_objset_userused_enabled(os))
1763                 return (SET_ERROR(ENOTSUP));
1764         if (dmu_objset_is_snapshot(os))
1765                 return (SET_ERROR(EINVAL));
1766
1767         /*
1768          * We simply need to mark every object dirty, so that it will be
1769          * synced out and now accounted.  If this is called
1770          * concurrently, or if we already did some work before crashing,
1771          * that's fine, since we track each object's accounted state
1772          * independently.
1773          */
1774
1775         for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE, 0)) {
1776                 dmu_tx_t *tx;
1777                 dmu_buf_t *db;
1778                 int objerr;
1779
1780                 if (issig(JUSTLOOKING) && issig(FORREAL))
1781                         return (SET_ERROR(EINTR));
1782
1783                 objerr = dmu_bonus_hold(os, obj, FTAG, &db);
1784                 if (objerr != 0)
1785                         continue;
1786                 tx = dmu_tx_create(os);
1787                 dmu_tx_hold_bonus(tx, obj);
1788                 objerr = dmu_tx_assign(tx, TXG_WAIT);
1789                 if (objerr != 0) {
1790                         dmu_tx_abort(tx);
1791                         continue;
1792                 }
1793                 dmu_buf_will_dirty(db, tx);
1794                 dmu_buf_rele(db, FTAG);
1795                 dmu_tx_commit(tx);
1796         }
1797
1798         os->os_flags |= OBJSET_FLAG_USERACCOUNTING_COMPLETE;
1799         txg_wait_synced(dmu_objset_pool(os), 0);
1800         return (0);
1801 }
1802
1803 void
1804 dmu_objset_space(objset_t *os, uint64_t *refdbytesp, uint64_t *availbytesp,
1805     uint64_t *usedobjsp, uint64_t *availobjsp)
1806 {
1807         dsl_dataset_space(os->os_dsl_dataset, refdbytesp, availbytesp,
1808             usedobjsp, availobjsp);
1809 }
1810
1811 uint64_t
1812 dmu_objset_fsid_guid(objset_t *os)
1813 {
1814         return (dsl_dataset_fsid_guid(os->os_dsl_dataset));
1815 }
1816
1817 void
1818 dmu_objset_fast_stat(objset_t *os, dmu_objset_stats_t *stat)
1819 {
1820         stat->dds_type = os->os_phys->os_type;
1821         if (os->os_dsl_dataset)
1822                 dsl_dataset_fast_stat(os->os_dsl_dataset, stat);
1823 }
1824
1825 void
1826 dmu_objset_stats(objset_t *os, nvlist_t *nv)
1827 {
1828         ASSERT(os->os_dsl_dataset ||
1829             os->os_phys->os_type == DMU_OST_META);
1830
1831         if (os->os_dsl_dataset != NULL)
1832                 dsl_dataset_stats(os->os_dsl_dataset, nv);
1833
1834         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_TYPE,
1835             os->os_phys->os_type);
1836         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERACCOUNTING,
1837             dmu_objset_userspace_present(os));
1838 }
1839
1840 int
1841 dmu_objset_is_snapshot(objset_t *os)
1842 {
1843         if (os->os_dsl_dataset != NULL)
1844                 return (os->os_dsl_dataset->ds_is_snapshot);
1845         else
1846                 return (B_FALSE);
1847 }
1848
1849 int
1850 dmu_snapshot_realname(objset_t *os, char *name, char *real, int maxlen,
1851     boolean_t *conflict)
1852 {
1853         dsl_dataset_t *ds = os->os_dsl_dataset;
1854         uint64_t ignored;
1855
1856         if (dsl_dataset_phys(ds)->ds_snapnames_zapobj == 0)
1857                 return (SET_ERROR(ENOENT));
1858
1859         return (zap_lookup_norm(ds->ds_dir->dd_pool->dp_meta_objset,
1860             dsl_dataset_phys(ds)->ds_snapnames_zapobj, name, 8, 1, &ignored,
1861             MT_NORMALIZE, real, maxlen, conflict));
1862 }
1863
1864 int
1865 dmu_snapshot_list_next(objset_t *os, int namelen, char *name,
1866     uint64_t *idp, uint64_t *offp, boolean_t *case_conflict)
1867 {
1868         dsl_dataset_t *ds = os->os_dsl_dataset;
1869         zap_cursor_t cursor;
1870         zap_attribute_t attr;
1871
1872         ASSERT(dsl_pool_config_held(dmu_objset_pool(os)));
1873
1874         if (dsl_dataset_phys(ds)->ds_snapnames_zapobj == 0)
1875                 return (SET_ERROR(ENOENT));
1876
1877         zap_cursor_init_serialized(&cursor,
1878             ds->ds_dir->dd_pool->dp_meta_objset,
1879             dsl_dataset_phys(ds)->ds_snapnames_zapobj, *offp);
1880
1881         if (zap_cursor_retrieve(&cursor, &attr) != 0) {
1882                 zap_cursor_fini(&cursor);
1883                 return (SET_ERROR(ENOENT));
1884         }
1885
1886         if (strlen(attr.za_name) + 1 > namelen) {
1887                 zap_cursor_fini(&cursor);
1888                 return (SET_ERROR(ENAMETOOLONG));
1889         }
1890
1891         (void) strcpy(name, attr.za_name);
1892         if (idp)
1893                 *idp = attr.za_first_integer;
1894         if (case_conflict)
1895                 *case_conflict = attr.za_normalization_conflict;
1896         zap_cursor_advance(&cursor);
1897         *offp = zap_cursor_serialize(&cursor);
1898         zap_cursor_fini(&cursor);
1899
1900         return (0);
1901 }
1902
1903 int
1904 dmu_dir_list_next(objset_t *os, int namelen, char *name,
1905     uint64_t *idp, uint64_t *offp)
1906 {
1907         dsl_dir_t *dd = os->os_dsl_dataset->ds_dir;
1908         zap_cursor_t cursor;
1909         zap_attribute_t attr;
1910
1911         /* there is no next dir on a snapshot! */
1912         if (os->os_dsl_dataset->ds_object !=
1913             dsl_dir_phys(dd)->dd_head_dataset_obj)
1914                 return (SET_ERROR(ENOENT));
1915
1916         zap_cursor_init_serialized(&cursor,
1917             dd->dd_pool->dp_meta_objset,
1918             dsl_dir_phys(dd)->dd_child_dir_zapobj, *offp);
1919
1920         if (zap_cursor_retrieve(&cursor, &attr) != 0) {
1921                 zap_cursor_fini(&cursor);
1922                 return (SET_ERROR(ENOENT));
1923         }
1924
1925         if (strlen(attr.za_name) + 1 > namelen) {
1926                 zap_cursor_fini(&cursor);
1927                 return (SET_ERROR(ENAMETOOLONG));
1928         }
1929
1930         (void) strcpy(name, attr.za_name);
1931         if (idp)
1932                 *idp = attr.za_first_integer;
1933         zap_cursor_advance(&cursor);
1934         *offp = zap_cursor_serialize(&cursor);
1935         zap_cursor_fini(&cursor);
1936
1937         return (0);
1938 }
1939
1940 typedef struct dmu_objset_find_ctx {
1941         taskq_t         *dc_tq;
1942         dsl_pool_t      *dc_dp;
1943         uint64_t        dc_ddobj;
1944         char            *dc_ddname; /* last component of ddobj's name */
1945         int             (*dc_func)(dsl_pool_t *, dsl_dataset_t *, void *);
1946         void            *dc_arg;
1947         int             dc_flags;
1948         kmutex_t        *dc_error_lock;
1949         int             *dc_error;
1950 } dmu_objset_find_ctx_t;
1951
1952 static void
1953 dmu_objset_find_dp_impl(dmu_objset_find_ctx_t *dcp)
1954 {
1955         dsl_pool_t *dp = dcp->dc_dp;
1956         dsl_dir_t *dd;
1957         dsl_dataset_t *ds;
1958         zap_cursor_t zc;
1959         zap_attribute_t *attr;
1960         uint64_t thisobj;
1961         int err = 0;
1962
1963         /* don't process if there already was an error */
1964         if (*dcp->dc_error != 0)
1965                 goto out;
1966
1967         /*
1968          * Note: passing the name (dc_ddname) here is optional, but it
1969          * improves performance because we don't need to call
1970          * zap_value_search() to determine the name.
1971          */
1972         err = dsl_dir_hold_obj(dp, dcp->dc_ddobj, dcp->dc_ddname, FTAG, &dd);
1973         if (err != 0)
1974                 goto out;
1975
1976         /* Don't visit hidden ($MOS & $ORIGIN) objsets. */
1977         if (dd->dd_myname[0] == '$') {
1978                 dsl_dir_rele(dd, FTAG);
1979                 goto out;
1980         }
1981
1982         thisobj = dsl_dir_phys(dd)->dd_head_dataset_obj;
1983         attr = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
1984
1985         /*
1986          * Iterate over all children.
1987          */
1988         if (dcp->dc_flags & DS_FIND_CHILDREN) {
1989                 for (zap_cursor_init(&zc, dp->dp_meta_objset,
1990                     dsl_dir_phys(dd)->dd_child_dir_zapobj);
1991                     zap_cursor_retrieve(&zc, attr) == 0;
1992                     (void) zap_cursor_advance(&zc)) {
1993                         ASSERT3U(attr->za_integer_length, ==,
1994                             sizeof (uint64_t));
1995                         ASSERT3U(attr->za_num_integers, ==, 1);
1996
1997                         dmu_objset_find_ctx_t *child_dcp =
1998                             kmem_alloc(sizeof (*child_dcp), KM_SLEEP);
1999                         *child_dcp = *dcp;
2000                         child_dcp->dc_ddobj = attr->za_first_integer;
2001                         child_dcp->dc_ddname = spa_strdup(attr->za_name);
2002                         if (dcp->dc_tq != NULL)
2003                                 (void) taskq_dispatch(dcp->dc_tq,
2004                                     dmu_objset_find_dp_cb, child_dcp, TQ_SLEEP);
2005                         else
2006                                 dmu_objset_find_dp_impl(child_dcp);
2007                 }
2008                 zap_cursor_fini(&zc);
2009         }
2010
2011         /*
2012          * Iterate over all snapshots.
2013          */
2014         if (dcp->dc_flags & DS_FIND_SNAPSHOTS) {
2015                 dsl_dataset_t *ds;
2016                 err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
2017
2018                 if (err == 0) {
2019                         uint64_t snapobj;
2020
2021                         snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
2022                         dsl_dataset_rele(ds, FTAG);
2023
2024                         for (zap_cursor_init(&zc, dp->dp_meta_objset, snapobj);
2025                             zap_cursor_retrieve(&zc, attr) == 0;
2026                             (void) zap_cursor_advance(&zc)) {
2027                                 ASSERT3U(attr->za_integer_length, ==,
2028                                     sizeof (uint64_t));
2029                                 ASSERT3U(attr->za_num_integers, ==, 1);
2030
2031                                 err = dsl_dataset_hold_obj(dp,
2032                                     attr->za_first_integer, FTAG, &ds);
2033                                 if (err != 0)
2034                                         break;
2035                                 err = dcp->dc_func(dp, ds, dcp->dc_arg);
2036                                 dsl_dataset_rele(ds, FTAG);
2037                                 if (err != 0)
2038                                         break;
2039                         }
2040                         zap_cursor_fini(&zc);
2041                 }
2042         }
2043
2044         kmem_free(attr, sizeof (zap_attribute_t));
2045
2046         if (err != 0) {
2047                 dsl_dir_rele(dd, FTAG);
2048                 goto out;
2049         }
2050
2051         /*
2052          * Apply to self.
2053          */
2054         err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
2055
2056         /*
2057          * Note: we hold the dir while calling dsl_dataset_hold_obj() so
2058          * that the dir will remain cached, and we won't have to re-instantiate
2059          * it (which could be expensive due to finding its name via
2060          * zap_value_search()).
2061          */
2062         dsl_dir_rele(dd, FTAG);
2063         if (err != 0)
2064                 goto out;
2065         err = dcp->dc_func(dp, ds, dcp->dc_arg);
2066         dsl_dataset_rele(ds, FTAG);
2067
2068 out:
2069         if (err != 0) {
2070                 mutex_enter(dcp->dc_error_lock);
2071                 /* only keep first error */
2072                 if (*dcp->dc_error == 0)
2073                         *dcp->dc_error = err;
2074                 mutex_exit(dcp->dc_error_lock);
2075         }
2076
2077         if (dcp->dc_ddname != NULL)
2078                 spa_strfree(dcp->dc_ddname);
2079         kmem_free(dcp, sizeof (*dcp));
2080 }
2081
2082 static void
2083 dmu_objset_find_dp_cb(void *arg)
2084 {
2085         dmu_objset_find_ctx_t *dcp = arg;
2086         dsl_pool_t *dp = dcp->dc_dp;
2087
2088         /*
2089          * We need to get a pool_config_lock here, as there are several
2090          * asssert(pool_config_held) down the stack. Getting a lock via
2091          * dsl_pool_config_enter is risky, as it might be stalled by a
2092          * pending writer. This would deadlock, as the write lock can
2093          * only be granted when our parent thread gives up the lock.
2094          * The _prio interface gives us priority over a pending writer.
2095          */
2096         dsl_pool_config_enter_prio(dp, FTAG);
2097
2098         dmu_objset_find_dp_impl(dcp);
2099
2100         dsl_pool_config_exit(dp, FTAG);
2101 }
2102
2103 /*
2104  * Find objsets under and including ddobj, call func(ds) on each.
2105  * The order for the enumeration is completely undefined.
2106  * func is called with dsl_pool_config held.
2107  */
2108 int
2109 dmu_objset_find_dp(dsl_pool_t *dp, uint64_t ddobj,
2110     int func(dsl_pool_t *, dsl_dataset_t *, void *), void *arg, int flags)
2111 {
2112         int error = 0;
2113         taskq_t *tq = NULL;
2114         int ntasks;
2115         dmu_objset_find_ctx_t *dcp;
2116         kmutex_t err_lock;
2117
2118         mutex_init(&err_lock, NULL, MUTEX_DEFAULT, NULL);
2119         dcp = kmem_alloc(sizeof (*dcp), KM_SLEEP);
2120         dcp->dc_tq = NULL;
2121         dcp->dc_dp = dp;
2122         dcp->dc_ddobj = ddobj;
2123         dcp->dc_ddname = NULL;
2124         dcp->dc_func = func;
2125         dcp->dc_arg = arg;
2126         dcp->dc_flags = flags;
2127         dcp->dc_error_lock = &err_lock;
2128         dcp->dc_error = &error;
2129
2130         if ((flags & DS_FIND_SERIALIZE) || dsl_pool_config_held_writer(dp)) {
2131                 /*
2132                  * In case a write lock is held we can't make use of
2133                  * parallelism, as down the stack of the worker threads
2134                  * the lock is asserted via dsl_pool_config_held.
2135                  * In case of a read lock this is solved by getting a read
2136                  * lock in each worker thread, which isn't possible in case
2137                  * of a writer lock. So we fall back to the synchronous path
2138                  * here.
2139                  * In the future it might be possible to get some magic into
2140                  * dsl_pool_config_held in a way that it returns true for
2141                  * the worker threads so that a single lock held from this
2142                  * thread suffices. For now, stay single threaded.
2143                  */
2144                 dmu_objset_find_dp_impl(dcp);
2145                 mutex_destroy(&err_lock);
2146
2147                 return (error);
2148         }
2149
2150         ntasks = dmu_find_threads;
2151         if (ntasks == 0)
2152                 ntasks = vdev_count_leaves(dp->dp_spa) * 4;
2153         tq = taskq_create("dmu_objset_find", ntasks, minclsyspri, ntasks,
2154             INT_MAX, 0);
2155         if (tq == NULL) {
2156                 kmem_free(dcp, sizeof (*dcp));
2157                 mutex_destroy(&err_lock);
2158
2159                 return (SET_ERROR(ENOMEM));
2160         }
2161         dcp->dc_tq = tq;
2162
2163         /* dcp will be freed by task */
2164         (void) taskq_dispatch(tq, dmu_objset_find_dp_cb, dcp, TQ_SLEEP);
2165
2166         /*
2167          * PORTING: this code relies on the property of taskq_wait to wait
2168          * until no more tasks are queued and no more tasks are active. As
2169          * we always queue new tasks from within other tasks, task_wait
2170          * reliably waits for the full recursion to finish, even though we
2171          * enqueue new tasks after taskq_wait has been called.
2172          * On platforms other than illumos, taskq_wait may not have this
2173          * property.
2174          */
2175         taskq_wait(tq);
2176         taskq_destroy(tq);
2177         mutex_destroy(&err_lock);
2178
2179         return (error);
2180 }
2181
2182 /*
2183  * Find all objsets under name, and for each, call 'func(child_name, arg)'.
2184  * The dp_config_rwlock must not be held when this is called, and it
2185  * will not be held when the callback is called.
2186  * Therefore this function should only be used when the pool is not changing
2187  * (e.g. in syncing context), or the callback can deal with the possible races.
2188  */
2189 static int
2190 dmu_objset_find_impl(spa_t *spa, const char *name,
2191     int func(const char *, void *), void *arg, int flags)
2192 {
2193         dsl_dir_t *dd;
2194         dsl_pool_t *dp = spa_get_dsl(spa);
2195         dsl_dataset_t *ds;
2196         zap_cursor_t zc;
2197         zap_attribute_t *attr;
2198         char *child;
2199         uint64_t thisobj;
2200         int err;
2201
2202         dsl_pool_config_enter(dp, FTAG);
2203
2204         err = dsl_dir_hold(dp, name, FTAG, &dd, NULL);
2205         if (err != 0) {
2206                 dsl_pool_config_exit(dp, FTAG);
2207                 return (err);
2208         }
2209
2210         /* Don't visit hidden ($MOS & $ORIGIN) objsets. */
2211         if (dd->dd_myname[0] == '$') {
2212                 dsl_dir_rele(dd, FTAG);
2213                 dsl_pool_config_exit(dp, FTAG);
2214                 return (0);
2215         }
2216
2217         thisobj = dsl_dir_phys(dd)->dd_head_dataset_obj;
2218         attr = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
2219
2220         /*
2221          * Iterate over all children.
2222          */
2223         if (flags & DS_FIND_CHILDREN) {
2224                 for (zap_cursor_init(&zc, dp->dp_meta_objset,
2225                     dsl_dir_phys(dd)->dd_child_dir_zapobj);
2226                     zap_cursor_retrieve(&zc, attr) == 0;
2227                     (void) zap_cursor_advance(&zc)) {
2228                         ASSERT3U(attr->za_integer_length, ==,
2229                             sizeof (uint64_t));
2230                         ASSERT3U(attr->za_num_integers, ==, 1);
2231
2232                         child = kmem_asprintf("%s/%s", name, attr->za_name);
2233                         dsl_pool_config_exit(dp, FTAG);
2234                         err = dmu_objset_find_impl(spa, child,
2235                             func, arg, flags);
2236                         dsl_pool_config_enter(dp, FTAG);
2237                         strfree(child);
2238                         if (err != 0)
2239                                 break;
2240                 }
2241                 zap_cursor_fini(&zc);
2242
2243                 if (err != 0) {
2244                         dsl_dir_rele(dd, FTAG);
2245                         dsl_pool_config_exit(dp, FTAG);
2246                         kmem_free(attr, sizeof (zap_attribute_t));
2247                         return (err);
2248                 }
2249         }
2250
2251         /*
2252          * Iterate over all snapshots.
2253          */
2254         if (flags & DS_FIND_SNAPSHOTS) {
2255                 err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
2256
2257                 if (err == 0) {
2258                         uint64_t snapobj;
2259
2260                         snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
2261                         dsl_dataset_rele(ds, FTAG);
2262
2263                         for (zap_cursor_init(&zc, dp->dp_meta_objset, snapobj);
2264                             zap_cursor_retrieve(&zc, attr) == 0;
2265                             (void) zap_cursor_advance(&zc)) {
2266                                 ASSERT3U(attr->za_integer_length, ==,
2267                                     sizeof (uint64_t));
2268                                 ASSERT3U(attr->za_num_integers, ==, 1);
2269
2270                                 child = kmem_asprintf("%s@%s",
2271                                     name, attr->za_name);
2272                                 dsl_pool_config_exit(dp, FTAG);
2273                                 err = func(child, arg);
2274                                 dsl_pool_config_enter(dp, FTAG);
2275                                 strfree(child);
2276                                 if (err != 0)
2277                                         break;
2278                         }
2279                         zap_cursor_fini(&zc);
2280                 }
2281         }
2282
2283         dsl_dir_rele(dd, FTAG);
2284         kmem_free(attr, sizeof (zap_attribute_t));
2285         dsl_pool_config_exit(dp, FTAG);
2286
2287         if (err != 0)
2288                 return (err);
2289
2290         /* Apply to self. */
2291         return (func(name, arg));
2292 }
2293
2294 /*
2295  * See comment above dmu_objset_find_impl().
2296  */
2297 int
2298 dmu_objset_find(char *name, int func(const char *, void *), void *arg,
2299     int flags)
2300 {
2301         spa_t *spa;
2302         int error;
2303
2304         error = spa_open(name, &spa, FTAG);
2305         if (error != 0)
2306                 return (error);
2307         error = dmu_objset_find_impl(spa, name, func, arg, flags);
2308         spa_close(spa, FTAG);
2309         return (error);
2310 }
2311
2312 void
2313 dmu_objset_set_user(objset_t *os, void *user_ptr)
2314 {
2315         ASSERT(MUTEX_HELD(&os->os_user_ptr_lock));
2316         os->os_user_ptr = user_ptr;
2317 }
2318
2319 void *
2320 dmu_objset_get_user(objset_t *os)
2321 {
2322         ASSERT(MUTEX_HELD(&os->os_user_ptr_lock));
2323         return (os->os_user_ptr);
2324 }
2325
2326 /*
2327  * Determine name of filesystem, given name of snapshot.
2328  * buf must be at least ZFS_MAX_DATASET_NAME_LEN bytes
2329  */
2330 int
2331 dmu_fsname(const char *snapname, char *buf)
2332 {
2333         char *atp = strchr(snapname, '@');
2334         if (atp == NULL)
2335                 return (SET_ERROR(EINVAL));
2336         if (atp - snapname >= ZFS_MAX_DATASET_NAME_LEN)
2337                 return (SET_ERROR(ENAMETOOLONG));
2338         (void) strlcpy(buf, snapname, atp - snapname + 1);
2339         return (0);
2340 }
2341
2342 /*
2343  * Call when we think we're going to write/free space in open context to track
2344  * the amount of dirty data in the open txg, which is also the amount
2345  * of memory that can not be evicted until this txg syncs.
2346  */
2347 void
2348 dmu_objset_willuse_space(objset_t *os, int64_t space, dmu_tx_t *tx)
2349 {
2350         dsl_dataset_t *ds = os->os_dsl_dataset;
2351         int64_t aspace = spa_get_worst_case_asize(os->os_spa, space);
2352
2353         if (ds != NULL) {
2354                 dsl_dir_willuse_space(ds->ds_dir, aspace, tx);
2355                 dsl_pool_dirty_space(dmu_tx_pool(tx), space, tx);
2356         }
2357 }