]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - stand/libsa/zfs/zfsimpl.c
zfs boot: fix a crash in a rarely taken path in fzap_lookup
[FreeBSD/FreeBSD.git] / stand / libsa / zfs / zfsimpl.c
1 /*-
2  * Copyright (c) 2007 Doug Rabson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 /*
31  *      Stand-alone ZFS file reader.
32  */
33
34 #include <sys/endian.h>
35 #include <sys/stat.h>
36 #include <sys/stdint.h>
37 #include <sys/list.h>
38
39 #include "zfsimpl.h"
40 #include "zfssubr.c"
41
42
43 struct zfsmount {
44         const spa_t     *spa;
45         objset_phys_t   objset;
46         uint64_t        rootobj;
47 };
48 static struct zfsmount zfsmount __unused;
49
50 /*
51  * The indirect_child_t represents the vdev that we will read from, when we
52  * need to read all copies of the data (e.g. for scrub or reconstruction).
53  * For plain (non-mirror) top-level vdevs (i.e. is_vdev is not a mirror),
54  * ic_vdev is the same as is_vdev.  However, for mirror top-level vdevs,
55  * ic_vdev is a child of the mirror.
56  */
57 typedef struct indirect_child {
58         void *ic_data;
59         vdev_t *ic_vdev;
60 } indirect_child_t;
61
62 /*
63  * The indirect_split_t represents one mapped segment of an i/o to the
64  * indirect vdev. For non-split (contiguously-mapped) blocks, there will be
65  * only one indirect_split_t, with is_split_offset==0 and is_size==io_size.
66  * For split blocks, there will be several of these.
67  */
68 typedef struct indirect_split {
69         list_node_t is_node; /* link on iv_splits */
70
71         /*
72          * is_split_offset is the offset into the i/o.
73          * This is the sum of the previous splits' is_size's.
74          */
75         uint64_t is_split_offset;
76
77         vdev_t *is_vdev; /* top-level vdev */
78         uint64_t is_target_offset; /* offset on is_vdev */
79         uint64_t is_size;
80         int is_children; /* number of entries in is_child[] */
81
82         /*
83          * is_good_child is the child that we are currently using to
84          * attempt reconstruction.
85          */
86         int is_good_child;
87
88         indirect_child_t is_child[1]; /* variable-length */
89 } indirect_split_t;
90
91 /*
92  * The indirect_vsd_t is associated with each i/o to the indirect vdev.
93  * It is the "Vdev-Specific Data" in the zio_t's io_vsd.
94  */
95 typedef struct indirect_vsd {
96         boolean_t iv_split_block;
97         boolean_t iv_reconstruct;
98
99         list_t iv_splits; /* list of indirect_split_t's */
100 } indirect_vsd_t;
101
102 /*
103  * List of all vdevs, chained through v_alllink.
104  */
105 static vdev_list_t zfs_vdevs;
106
107  /*
108  * List of ZFS features supported for read
109  */
110 static const char *features_for_read[] = {
111         "org.illumos:lz4_compress",
112         "com.delphix:hole_birth",
113         "com.delphix:extensible_dataset",
114         "com.delphix:embedded_data",
115         "org.open-zfs:large_blocks",
116         "org.illumos:sha512",
117         "org.illumos:skein",
118         "org.zfsonlinux:large_dnode",
119         "com.joyent:multi_vdev_crash_dump",
120         "com.delphix:spacemap_histogram",
121         "com.delphix:zpool_checkpoint",
122         "com.delphix:spacemap_v2",
123         "com.datto:encryption",
124         "org.zfsonlinux:allocation_classes",
125         "com.datto:resilver_defer",
126         "com.delphix:device_removal",
127         "com.delphix:obsolete_counts",
128         "com.intel:allocation_classes",
129         NULL
130 };
131
132 /*
133  * List of all pools, chained through spa_link.
134  */
135 static spa_list_t zfs_pools;
136
137 static const dnode_phys_t *dnode_cache_obj;
138 static uint64_t dnode_cache_bn;
139 static char *dnode_cache_buf;
140 static char *zap_scratch;
141 static char *zfs_temp_buf, *zfs_temp_end, *zfs_temp_ptr;
142
143 #define TEMP_SIZE       (1024 * 1024)
144
145 static int zio_read(const spa_t *spa, const blkptr_t *bp, void *buf);
146 static int zfs_get_root(const spa_t *spa, uint64_t *objid);
147 static int zfs_rlookup(const spa_t *spa, uint64_t objnum, char *result);
148 static int zap_lookup(const spa_t *spa, const dnode_phys_t *dnode,
149     const char *name, uint64_t integer_size, uint64_t num_integers,
150     void *value);
151 static int objset_get_dnode(const spa_t *, const objset_phys_t *, uint64_t,
152     dnode_phys_t *);
153 static int dnode_read(const spa_t *, const dnode_phys_t *, off_t, void *,
154     size_t);
155 static int vdev_indirect_read(vdev_t *, const blkptr_t *, void *, off_t,
156     size_t);
157 static int vdev_mirror_read(vdev_t *, const blkptr_t *, void *, off_t, size_t);
158 vdev_indirect_mapping_t *vdev_indirect_mapping_open(spa_t *, objset_phys_t *,
159     uint64_t);
160 vdev_indirect_mapping_entry_phys_t *
161     vdev_indirect_mapping_duplicate_adjacent_entries(vdev_t *, uint64_t,
162     uint64_t, uint64_t *);
163
164 static void
165 zfs_init(void)
166 {
167         STAILQ_INIT(&zfs_vdevs);
168         STAILQ_INIT(&zfs_pools);
169
170         zfs_temp_buf = malloc(TEMP_SIZE);
171         zfs_temp_end = zfs_temp_buf + TEMP_SIZE;
172         zfs_temp_ptr = zfs_temp_buf;
173         dnode_cache_buf = malloc(SPA_MAXBLOCKSIZE);
174         zap_scratch = malloc(SPA_MAXBLOCKSIZE);
175
176         zfs_init_crc();
177 }
178
179 static void *
180 zfs_alloc(size_t size)
181 {
182         char *ptr;
183
184         if (zfs_temp_ptr + size > zfs_temp_end) {
185                 panic("ZFS: out of temporary buffer space");
186         }
187         ptr = zfs_temp_ptr;
188         zfs_temp_ptr += size;
189
190         return (ptr);
191 }
192
193 static void
194 zfs_free(void *ptr, size_t size)
195 {
196
197         zfs_temp_ptr -= size;
198         if (zfs_temp_ptr != ptr) {
199                 panic("ZFS: zfs_alloc()/zfs_free() mismatch");
200         }
201 }
202
203 static int
204 xdr_int(const unsigned char **xdr, int *ip)
205 {
206         *ip = be32dec(*xdr);
207         (*xdr) += 4;
208         return (0);
209 }
210
211 static int
212 xdr_u_int(const unsigned char **xdr, u_int *ip)
213 {
214         *ip = be32dec(*xdr);
215         (*xdr) += 4;
216         return (0);
217 }
218
219 static int
220 xdr_uint64_t(const unsigned char **xdr, uint64_t *lp)
221 {
222         u_int hi, lo;
223
224         xdr_u_int(xdr, &hi);
225         xdr_u_int(xdr, &lo);
226         *lp = (((uint64_t) hi) << 32) | lo;
227         return (0);
228 }
229
230 static int
231 nvlist_find(const unsigned char *nvlist, const char *name, int type,
232             int *elementsp, void *valuep)
233 {
234         const unsigned char *p, *pair;
235         int junk;
236         int encoded_size, decoded_size;
237
238         p = nvlist;
239         xdr_int(&p, &junk);
240         xdr_int(&p, &junk);
241
242         pair = p;
243         xdr_int(&p, &encoded_size);
244         xdr_int(&p, &decoded_size);
245         while (encoded_size && decoded_size) {
246                 int namelen, pairtype, elements;
247                 const char *pairname;
248
249                 xdr_int(&p, &namelen);
250                 pairname = (const char*) p;
251                 p += roundup(namelen, 4);
252                 xdr_int(&p, &pairtype);
253
254                 if (!memcmp(name, pairname, namelen) && type == pairtype) {
255                         xdr_int(&p, &elements);
256                         if (elementsp)
257                                 *elementsp = elements;
258                         if (type == DATA_TYPE_UINT64) {
259                                 xdr_uint64_t(&p, (uint64_t *) valuep);
260                                 return (0);
261                         } else if (type == DATA_TYPE_STRING) {
262                                 int len;
263                                 xdr_int(&p, &len);
264                                 (*(const char**) valuep) = (const char*) p;
265                                 return (0);
266                         } else if (type == DATA_TYPE_NVLIST
267                                    || type == DATA_TYPE_NVLIST_ARRAY) {
268                                 (*(const unsigned char**) valuep) =
269                                          (const unsigned char*) p;
270                                 return (0);
271                         } else {
272                                 return (EIO);
273                         }
274                 } else {
275                         /*
276                          * Not the pair we are looking for, skip to the next one.
277                          */
278                         p = pair + encoded_size;
279                 }
280
281                 pair = p;
282                 xdr_int(&p, &encoded_size);
283                 xdr_int(&p, &decoded_size);
284         }
285
286         return (EIO);
287 }
288
289 static int
290 nvlist_check_features_for_read(const unsigned char *nvlist)
291 {
292         const unsigned char *p, *pair;
293         int junk;
294         int encoded_size, decoded_size;
295         int rc;
296
297         rc = 0;
298
299         p = nvlist;
300         xdr_int(&p, &junk);
301         xdr_int(&p, &junk);
302
303         pair = p;
304         xdr_int(&p, &encoded_size);
305         xdr_int(&p, &decoded_size);
306         while (encoded_size && decoded_size) {
307                 int namelen, pairtype;
308                 const char *pairname;
309                 int i, found;
310
311                 found = 0;
312
313                 xdr_int(&p, &namelen);
314                 pairname = (const char*) p;
315                 p += roundup(namelen, 4);
316                 xdr_int(&p, &pairtype);
317
318                 for (i = 0; features_for_read[i] != NULL; i++) {
319                         if (!memcmp(pairname, features_for_read[i], namelen)) {
320                                 found = 1;
321                                 break;
322                         }
323                 }
324
325                 if (!found) {
326                         printf("ZFS: unsupported feature: %s\n", pairname);
327                         rc = EIO;
328                 }
329
330                 p = pair + encoded_size;
331
332                 pair = p;
333                 xdr_int(&p, &encoded_size);
334                 xdr_int(&p, &decoded_size);
335         }
336
337         return (rc);
338 }
339
340 /*
341  * Return the next nvlist in an nvlist array.
342  */
343 static const unsigned char *
344 nvlist_next(const unsigned char *nvlist)
345 {
346         const unsigned char *p, *pair;
347         int junk;
348         int encoded_size, decoded_size;
349
350         p = nvlist;
351         xdr_int(&p, &junk);
352         xdr_int(&p, &junk);
353
354         pair = p;
355         xdr_int(&p, &encoded_size);
356         xdr_int(&p, &decoded_size);
357         while (encoded_size && decoded_size) {
358                 p = pair + encoded_size;
359
360                 pair = p;
361                 xdr_int(&p, &encoded_size);
362                 xdr_int(&p, &decoded_size);
363         }
364
365         return p;
366 }
367
368 #ifdef TEST
369
370 static const unsigned char *
371 nvlist_print(const unsigned char *nvlist, unsigned int indent)
372 {
373         static const char* typenames[] = {
374                 "DATA_TYPE_UNKNOWN",
375                 "DATA_TYPE_BOOLEAN",
376                 "DATA_TYPE_BYTE",
377                 "DATA_TYPE_INT16",
378                 "DATA_TYPE_UINT16",
379                 "DATA_TYPE_INT32",
380                 "DATA_TYPE_UINT32",
381                 "DATA_TYPE_INT64",
382                 "DATA_TYPE_UINT64",
383                 "DATA_TYPE_STRING",
384                 "DATA_TYPE_BYTE_ARRAY",
385                 "DATA_TYPE_INT16_ARRAY",
386                 "DATA_TYPE_UINT16_ARRAY",
387                 "DATA_TYPE_INT32_ARRAY",
388                 "DATA_TYPE_UINT32_ARRAY",
389                 "DATA_TYPE_INT64_ARRAY",
390                 "DATA_TYPE_UINT64_ARRAY",
391                 "DATA_TYPE_STRING_ARRAY",
392                 "DATA_TYPE_HRTIME",
393                 "DATA_TYPE_NVLIST",
394                 "DATA_TYPE_NVLIST_ARRAY",
395                 "DATA_TYPE_BOOLEAN_VALUE",
396                 "DATA_TYPE_INT8",
397                 "DATA_TYPE_UINT8",
398                 "DATA_TYPE_BOOLEAN_ARRAY",
399                 "DATA_TYPE_INT8_ARRAY",
400                 "DATA_TYPE_UINT8_ARRAY"
401         };
402
403         unsigned int i, j;
404         const unsigned char *p, *pair;
405         int junk;
406         int encoded_size, decoded_size;
407
408         p = nvlist;
409         xdr_int(&p, &junk);
410         xdr_int(&p, &junk);
411
412         pair = p;
413         xdr_int(&p, &encoded_size);
414         xdr_int(&p, &decoded_size);
415         while (encoded_size && decoded_size) {
416                 int namelen, pairtype, elements;
417                 const char *pairname;
418
419                 xdr_int(&p, &namelen);
420                 pairname = (const char*) p;
421                 p += roundup(namelen, 4);
422                 xdr_int(&p, &pairtype);
423
424                 for (i = 0; i < indent; i++)
425                         printf(" ");
426                 printf("%s %s", typenames[pairtype], pairname);
427
428                 xdr_int(&p, &elements);
429                 switch (pairtype) {
430                 case DATA_TYPE_UINT64: {
431                         uint64_t val;
432                         xdr_uint64_t(&p, &val);
433                         printf(" = 0x%jx\n", (uintmax_t)val);
434                         break;
435                 }
436
437                 case DATA_TYPE_STRING: {
438                         int len;
439                         xdr_int(&p, &len);
440                         printf(" = \"%s\"\n", p);
441                         break;
442                 }
443
444                 case DATA_TYPE_NVLIST:
445                         printf("\n");
446                         nvlist_print(p, indent + 1);
447                         break;
448
449                 case DATA_TYPE_NVLIST_ARRAY:
450                         for (j = 0; j < elements; j++) {
451                                 printf("[%d]\n", j);
452                                 p = nvlist_print(p, indent + 1);
453                                 if (j != elements - 1) {
454                                         for (i = 0; i < indent; i++)
455                                                 printf(" ");
456                                         printf("%s %s", typenames[pairtype], pairname);
457                                 }
458                         }
459                         break;
460
461                 default:
462                         printf("\n");
463                 }
464
465                 p = pair + encoded_size;
466
467                 pair = p;
468                 xdr_int(&p, &encoded_size);
469                 xdr_int(&p, &decoded_size);
470         }
471
472         return p;
473 }
474
475 #endif
476
477 static int
478 vdev_read_phys(vdev_t *vdev, const blkptr_t *bp, void *buf,
479     off_t offset, size_t size)
480 {
481         size_t psize;
482         int rc;
483
484         if (!vdev->v_phys_read)
485                 return (EIO);
486
487         if (bp) {
488                 psize = BP_GET_PSIZE(bp);
489         } else {
490                 psize = size;
491         }
492
493         /*printf("ZFS: reading %zu bytes at 0x%jx to %p\n", psize, (uintmax_t)offset, buf);*/
494         rc = vdev->v_phys_read(vdev, vdev->v_read_priv, offset, buf, psize);
495         if (rc)
496                 return (rc);
497         if (bp != NULL)
498                 return (zio_checksum_verify(vdev->spa, bp, buf));
499
500         return (0);
501 }
502
503 typedef struct remap_segment {
504         vdev_t *rs_vd;
505         uint64_t rs_offset;
506         uint64_t rs_asize;
507         uint64_t rs_split_offset;
508         list_node_t rs_node;
509 } remap_segment_t;
510
511 static remap_segment_t *
512 rs_alloc(vdev_t *vd, uint64_t offset, uint64_t asize, uint64_t split_offset)
513 {
514         remap_segment_t *rs = malloc(sizeof (remap_segment_t));
515
516         if (rs != NULL) {
517                 rs->rs_vd = vd;
518                 rs->rs_offset = offset;
519                 rs->rs_asize = asize;
520                 rs->rs_split_offset = split_offset;
521         }
522
523         return (rs);
524 }
525
526 vdev_indirect_mapping_t *
527 vdev_indirect_mapping_open(spa_t *spa, objset_phys_t *os,
528     uint64_t mapping_object)
529 {
530         vdev_indirect_mapping_t *vim;
531         vdev_indirect_mapping_phys_t *vim_phys;
532         int rc;
533
534         vim = calloc(1, sizeof (*vim));
535         if (vim == NULL)
536                 return (NULL);
537
538         vim->vim_dn = calloc(1, sizeof (*vim->vim_dn));
539         if (vim->vim_dn == NULL) {
540                 free(vim);
541                 return (NULL);
542         }
543
544         rc = objset_get_dnode(spa, os, mapping_object, vim->vim_dn);
545         if (rc != 0) {
546                 free(vim->vim_dn);
547                 free(vim);
548                 return (NULL);
549         }
550
551         vim->vim_spa = spa;
552         vim->vim_phys = malloc(sizeof (*vim->vim_phys));
553         if (vim->vim_phys == NULL) {
554                 free(vim->vim_dn);
555                 free(vim);
556                 return (NULL);
557         }
558
559         vim_phys = (vdev_indirect_mapping_phys_t *)DN_BONUS(vim->vim_dn);
560         *vim->vim_phys = *vim_phys;
561
562         vim->vim_objset = os;
563         vim->vim_object = mapping_object;
564         vim->vim_entries = NULL;
565
566         vim->vim_havecounts =
567             (vim->vim_dn->dn_bonuslen > VDEV_INDIRECT_MAPPING_SIZE_V0);
568         return (vim);
569 }
570
571 /*
572  * Compare an offset with an indirect mapping entry; there are three
573  * possible scenarios:
574  *
575  *     1. The offset is "less than" the mapping entry; meaning the
576  *        offset is less than the source offset of the mapping entry. In
577  *        this case, there is no overlap between the offset and the
578  *        mapping entry and -1 will be returned.
579  *
580  *     2. The offset is "greater than" the mapping entry; meaning the
581  *        offset is greater than the mapping entry's source offset plus
582  *        the entry's size. In this case, there is no overlap between
583  *        the offset and the mapping entry and 1 will be returned.
584  *
585  *        NOTE: If the offset is actually equal to the entry's offset
586  *        plus size, this is considered to be "greater" than the entry,
587  *        and this case applies (i.e. 1 will be returned). Thus, the
588  *        entry's "range" can be considered to be inclusive at its
589  *        start, but exclusive at its end: e.g. [src, src + size).
590  *
591  *     3. The last case to consider is if the offset actually falls
592  *        within the mapping entry's range. If this is the case, the
593  *        offset is considered to be "equal to" the mapping entry and
594  *        0 will be returned.
595  *
596  *        NOTE: If the offset is equal to the entry's source offset,
597  *        this case applies and 0 will be returned. If the offset is
598  *        equal to the entry's source plus its size, this case does
599  *        *not* apply (see "NOTE" above for scenario 2), and 1 will be
600  *        returned.
601  */
602 static int
603 dva_mapping_overlap_compare(const void *v_key, const void *v_array_elem)
604 {
605         const uint64_t *key = v_key;
606         const vdev_indirect_mapping_entry_phys_t *array_elem =
607             v_array_elem;
608         uint64_t src_offset = DVA_MAPPING_GET_SRC_OFFSET(array_elem);
609
610         if (*key < src_offset) {
611                 return (-1);
612         } else if (*key < src_offset + DVA_GET_ASIZE(&array_elem->vimep_dst)) {
613                 return (0);
614         } else {
615                 return (1);
616         }
617 }
618
619 /*
620  * Return array entry.
621  */
622 static vdev_indirect_mapping_entry_phys_t *
623 vdev_indirect_mapping_entry(vdev_indirect_mapping_t *vim, uint64_t index)
624 {
625         uint64_t size;
626         off_t offset = 0;
627         int rc;
628
629         if (vim->vim_phys->vimp_num_entries == 0)
630                 return (NULL);
631
632         if (vim->vim_entries == NULL) {
633                 uint64_t bsize;
634
635                 bsize = vim->vim_dn->dn_datablkszsec << SPA_MINBLOCKSHIFT;
636                 size = vim->vim_phys->vimp_num_entries *
637                     sizeof (*vim->vim_entries);
638                 if (size > bsize) {
639                         size = bsize / sizeof (*vim->vim_entries);
640                         size *= sizeof (*vim->vim_entries);
641                 }
642                 vim->vim_entries = malloc(size);
643                 if (vim->vim_entries == NULL)
644                         return (NULL);
645                 vim->vim_num_entries = size / sizeof (*vim->vim_entries);
646                 offset = index * sizeof (*vim->vim_entries);
647         }
648
649         /* We have data in vim_entries */
650         if (offset == 0) {
651                 if (index >= vim->vim_entry_offset &&
652                     index <= vim->vim_entry_offset + vim->vim_num_entries) {
653                         index -= vim->vim_entry_offset;
654                         return (&vim->vim_entries[index]);
655                 }
656                 offset = index * sizeof (*vim->vim_entries);
657         }
658
659         vim->vim_entry_offset = index;
660         size = vim->vim_num_entries * sizeof (*vim->vim_entries);
661         rc = dnode_read(vim->vim_spa, vim->vim_dn, offset, vim->vim_entries,
662             size);
663         if (rc != 0) {
664                 /* Read error, invalidate vim_entries. */
665                 free(vim->vim_entries);
666                 vim->vim_entries = NULL;
667                 return (NULL);
668         }
669         index -= vim->vim_entry_offset;
670         return (&vim->vim_entries[index]);
671 }
672
673 /*
674  * Returns the mapping entry for the given offset.
675  *
676  * It's possible that the given offset will not be in the mapping table
677  * (i.e. no mapping entries contain this offset), in which case, the
678  * return value value depends on the "next_if_missing" parameter.
679  *
680  * If the offset is not found in the table and "next_if_missing" is
681  * B_FALSE, then NULL will always be returned. The behavior is intended
682  * to allow consumers to get the entry corresponding to the offset
683  * parameter, iff the offset overlaps with an entry in the table.
684  *
685  * If the offset is not found in the table and "next_if_missing" is
686  * B_TRUE, then the entry nearest to the given offset will be returned,
687  * such that the entry's source offset is greater than the offset
688  * passed in (i.e. the "next" mapping entry in the table is returned, if
689  * the offset is missing from the table). If there are no entries whose
690  * source offset is greater than the passed in offset, NULL is returned.
691  */
692 static vdev_indirect_mapping_entry_phys_t *
693 vdev_indirect_mapping_entry_for_offset(vdev_indirect_mapping_t *vim,
694     uint64_t offset)
695 {
696         ASSERT(vim->vim_phys->vimp_num_entries > 0);
697
698         vdev_indirect_mapping_entry_phys_t *entry;
699
700         uint64_t last = vim->vim_phys->vimp_num_entries - 1;
701         uint64_t base = 0;
702
703         /*
704          * We don't define these inside of the while loop because we use
705          * their value in the case that offset isn't in the mapping.
706          */
707         uint64_t mid;
708         int result;
709
710         while (last >= base) {
711                 mid = base + ((last - base) >> 1);
712
713                 entry = vdev_indirect_mapping_entry(vim, mid);
714                 if (entry == NULL)
715                         break;
716                 result = dva_mapping_overlap_compare(&offset, entry);
717
718                 if (result == 0) {
719                         break;
720                 } else if (result < 0) {
721                         last = mid - 1;
722                 } else {
723                         base = mid + 1;
724                 }
725         }
726         return (entry);
727 }
728
729 /*
730  * Given an indirect vdev and an extent on that vdev, it duplicates the
731  * physical entries of the indirect mapping that correspond to the extent
732  * to a new array and returns a pointer to it. In addition, copied_entries
733  * is populated with the number of mapping entries that were duplicated.
734  *
735  * Finally, since we are doing an allocation, it is up to the caller to
736  * free the array allocated in this function.
737  */
738 vdev_indirect_mapping_entry_phys_t *
739 vdev_indirect_mapping_duplicate_adjacent_entries(vdev_t *vd, uint64_t offset,
740     uint64_t asize, uint64_t *copied_entries)
741 {
742         vdev_indirect_mapping_entry_phys_t *duplicate_mappings = NULL;
743         vdev_indirect_mapping_t *vim = vd->v_mapping;
744         uint64_t entries = 0;
745
746         vdev_indirect_mapping_entry_phys_t *first_mapping =
747             vdev_indirect_mapping_entry_for_offset(vim, offset);
748         ASSERT3P(first_mapping, !=, NULL);
749
750         vdev_indirect_mapping_entry_phys_t *m = first_mapping;
751         while (asize > 0) {
752                 uint64_t size = DVA_GET_ASIZE(&m->vimep_dst);
753                 uint64_t inner_offset = offset - DVA_MAPPING_GET_SRC_OFFSET(m);
754                 uint64_t inner_size = MIN(asize, size - inner_offset);
755
756                 offset += inner_size;
757                 asize -= inner_size;
758                 entries++;
759                 m++;
760         }
761
762         size_t copy_length = entries * sizeof (*first_mapping);
763         duplicate_mappings = malloc(copy_length);
764         if (duplicate_mappings != NULL)
765                 bcopy(first_mapping, duplicate_mappings, copy_length);
766         else
767                 entries = 0;
768
769         *copied_entries = entries;
770
771         return (duplicate_mappings);
772 }
773
774 static vdev_t *
775 vdev_lookup_top(spa_t *spa, uint64_t vdev)
776 {
777         vdev_t *rvd;
778
779         STAILQ_FOREACH(rvd, &spa->spa_vdevs, v_childlink)
780                 if (rvd->v_id == vdev)
781                         break;
782
783         return (rvd);
784 }
785
786 /*
787  * This is a callback for vdev_indirect_remap() which allocates an
788  * indirect_split_t for each split segment and adds it to iv_splits.
789  */
790 static void
791 vdev_indirect_gather_splits(uint64_t split_offset, vdev_t *vd, uint64_t offset,
792     uint64_t size, void *arg)
793 {
794         int n = 1;
795         zio_t *zio = arg;
796         indirect_vsd_t *iv = zio->io_vsd;
797
798         if (vd->v_read == vdev_indirect_read)
799                 return;
800
801         if (vd->v_read == vdev_mirror_read)
802                 n = vd->v_nchildren;
803
804         indirect_split_t *is =
805             malloc(offsetof(indirect_split_t, is_child[n]));
806         if (is == NULL) {
807                 zio->io_error = ENOMEM;
808                 return;
809         }
810         bzero(is, offsetof(indirect_split_t, is_child[n]));
811
812         is->is_children = n;
813         is->is_size = size;
814         is->is_split_offset = split_offset;
815         is->is_target_offset = offset;
816         is->is_vdev = vd;
817
818         /*
819          * Note that we only consider multiple copies of the data for
820          * *mirror* vdevs.  We don't for "replacing" or "spare" vdevs, even
821          * though they use the same ops as mirror, because there's only one
822          * "good" copy under the replacing/spare.
823          */
824         if (vd->v_read == vdev_mirror_read) {
825                 int i = 0;
826                 vdev_t *kid;
827
828                 STAILQ_FOREACH(kid, &vd->v_children, v_childlink) {
829                         is->is_child[i++].ic_vdev = kid;
830                 }
831         } else {
832                 is->is_child[0].ic_vdev = vd;
833         }
834
835         list_insert_tail(&iv->iv_splits, is);
836 }
837
838 static void
839 vdev_indirect_remap(vdev_t *vd, uint64_t offset, uint64_t asize, void *arg)
840 {
841         list_t stack;
842         spa_t *spa = vd->spa;
843         zio_t *zio = arg;
844         remap_segment_t *rs;
845
846         list_create(&stack, sizeof (remap_segment_t),
847             offsetof(remap_segment_t, rs_node));
848
849         rs = rs_alloc(vd, offset, asize, 0);
850         if (rs == NULL) {
851                 printf("vdev_indirect_remap: out of memory.\n");
852                 zio->io_error = ENOMEM;
853         }
854         for ( ; rs != NULL; rs = list_remove_head(&stack)) {
855                 vdev_t *v = rs->rs_vd;
856                 uint64_t num_entries = 0;
857                 /* vdev_indirect_mapping_t *vim = v->v_mapping; */
858                 vdev_indirect_mapping_entry_phys_t *mapping =
859                     vdev_indirect_mapping_duplicate_adjacent_entries(v,
860                     rs->rs_offset, rs->rs_asize, &num_entries);
861
862                 if (num_entries == 0)
863                         zio->io_error = ENOMEM;
864
865                 for (uint64_t i = 0; i < num_entries; i++) {
866                         vdev_indirect_mapping_entry_phys_t *m = &mapping[i];
867                         uint64_t size = DVA_GET_ASIZE(&m->vimep_dst);
868                         uint64_t dst_offset = DVA_GET_OFFSET(&m->vimep_dst);
869                         uint64_t dst_vdev = DVA_GET_VDEV(&m->vimep_dst);
870                         uint64_t inner_offset = rs->rs_offset -
871                             DVA_MAPPING_GET_SRC_OFFSET(m);
872                         uint64_t inner_size =
873                             MIN(rs->rs_asize, size - inner_offset);
874                         vdev_t *dst_v = vdev_lookup_top(spa, dst_vdev);
875
876                         if (dst_v->v_read == vdev_indirect_read) {
877                                 remap_segment_t *o;
878
879                                 o = rs_alloc(dst_v, dst_offset + inner_offset,
880                                     inner_size, rs->rs_split_offset);
881                                 if (o == NULL) {
882                                         printf("vdev_indirect_remap: "
883                                             "out of memory.\n");
884                                         zio->io_error = ENOMEM;
885                                         break;
886                                 }
887
888                                 list_insert_head(&stack, o);
889                         }
890                         vdev_indirect_gather_splits(rs->rs_split_offset, dst_v,
891                             dst_offset + inner_offset,
892                             inner_size, arg);
893
894                         /*
895                          * vdev_indirect_gather_splits can have memory
896                          * allocation error, we can not recover from it.
897                          */
898                         if (zio->io_error != 0)
899                                 break;
900
901                         rs->rs_offset += inner_size;
902                         rs->rs_asize -= inner_size;
903                         rs->rs_split_offset += inner_size;
904                 }
905
906                 free(mapping);
907                 free(rs);
908                 if (zio->io_error != 0)
909                         break;
910         }
911
912         list_destroy(&stack);
913 }
914
915 static void
916 vdev_indirect_map_free(zio_t *zio)
917 {
918         indirect_vsd_t *iv = zio->io_vsd;
919         indirect_split_t *is;
920
921         while ((is = list_head(&iv->iv_splits)) != NULL) {
922                 for (int c = 0; c < is->is_children; c++) {
923                         indirect_child_t *ic = &is->is_child[c];
924                         free(ic->ic_data);
925                 }
926                 list_remove(&iv->iv_splits, is);
927                 free(is);
928         }
929         free(iv);
930 }
931
932 static int
933 vdev_indirect_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
934     off_t offset, size_t bytes)
935 {
936         zio_t zio = { 0 };
937         spa_t *spa = vdev->spa;
938         indirect_vsd_t *iv = malloc(sizeof (*iv));
939         indirect_split_t *first;
940         int rc = EIO;
941
942         if (iv == NULL)
943                 return (ENOMEM);
944         bzero(iv, sizeof (*iv));
945
946         list_create(&iv->iv_splits,
947             sizeof (indirect_split_t), offsetof(indirect_split_t, is_node));
948
949         zio.io_spa = spa;
950         zio.io_bp = (blkptr_t *)bp;
951         zio.io_data = buf;
952         zio.io_size = bytes;
953         zio.io_offset = offset;
954         zio.io_vd = vdev;
955         zio.io_vsd = iv;
956
957         if (vdev->v_mapping == NULL) {
958                 vdev_indirect_config_t *vic;
959
960                 vic = &vdev->vdev_indirect_config;
961                 vdev->v_mapping = vdev_indirect_mapping_open(spa,
962                     &spa->spa_mos, vic->vic_mapping_object);
963         }
964
965         vdev_indirect_remap(vdev, offset, bytes, &zio);
966         if (zio.io_error != 0)
967                 return (zio.io_error);
968
969         first = list_head(&iv->iv_splits);
970         if (first->is_size == zio.io_size) {
971                 /*
972                  * This is not a split block; we are pointing to the entire
973                  * data, which will checksum the same as the original data.
974                  * Pass the BP down so that the child i/o can verify the
975                  * checksum, and try a different location if available
976                  * (e.g. on a mirror).
977                  *
978                  * While this special case could be handled the same as the
979                  * general (split block) case, doing it this way ensures
980                  * that the vast majority of blocks on indirect vdevs
981                  * (which are not split) are handled identically to blocks
982                  * on non-indirect vdevs.  This allows us to be less strict
983                  * about performance in the general (but rare) case.
984                  */
985                 rc = first->is_vdev->v_read(first->is_vdev, zio.io_bp,
986                     zio.io_data, first->is_target_offset, bytes);
987         } else {
988                 iv->iv_split_block = B_TRUE;
989                 /*
990                  * Read one copy of each split segment, from the
991                  * top-level vdev.  Since we don't know the
992                  * checksum of each split individually, the child
993                  * zio can't ensure that we get the right data.
994                  * E.g. if it's a mirror, it will just read from a
995                  * random (healthy) leaf vdev.  We have to verify
996                  * the checksum in vdev_indirect_io_done().
997                  */
998                 for (indirect_split_t *is = list_head(&iv->iv_splits);
999                     is != NULL; is = list_next(&iv->iv_splits, is)) {
1000                         char *ptr = zio.io_data;
1001
1002                         rc = is->is_vdev->v_read(is->is_vdev, zio.io_bp,
1003                             ptr + is->is_split_offset, is->is_target_offset,
1004                             is->is_size);
1005                 }
1006                 if (zio_checksum_verify(spa, zio.io_bp, zio.io_data))
1007                         rc = ECKSUM;
1008                 else
1009                         rc = 0;
1010         }
1011
1012         vdev_indirect_map_free(&zio);
1013         if (rc == 0)
1014                 rc = zio.io_error;
1015
1016         return (rc);
1017 }
1018
1019 static int
1020 vdev_disk_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
1021     off_t offset, size_t bytes)
1022 {
1023
1024         return (vdev_read_phys(vdev, bp, buf,
1025                 offset + VDEV_LABEL_START_SIZE, bytes));
1026 }
1027
1028
1029 static int
1030 vdev_mirror_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
1031     off_t offset, size_t bytes)
1032 {
1033         vdev_t *kid;
1034         int rc;
1035
1036         rc = EIO;
1037         STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
1038                 if (kid->v_state != VDEV_STATE_HEALTHY)
1039                         continue;
1040                 rc = kid->v_read(kid, bp, buf, offset, bytes);
1041                 if (!rc)
1042                         return (0);
1043         }
1044
1045         return (rc);
1046 }
1047
1048 static int
1049 vdev_replacing_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
1050     off_t offset, size_t bytes)
1051 {
1052         vdev_t *kid;
1053
1054         /*
1055          * Here we should have two kids:
1056          * First one which is the one we are replacing and we can trust
1057          * only this one to have valid data, but it might not be present.
1058          * Second one is that one we are replacing with. It is most likely
1059          * healthy, but we can't trust it has needed data, so we won't use it.
1060          */
1061         kid = STAILQ_FIRST(&vdev->v_children);
1062         if (kid == NULL)
1063                 return (EIO);
1064         if (kid->v_state != VDEV_STATE_HEALTHY)
1065                 return (EIO);
1066         return (kid->v_read(kid, bp, buf, offset, bytes));
1067 }
1068
1069 static vdev_t *
1070 vdev_find(uint64_t guid)
1071 {
1072         vdev_t *vdev;
1073
1074         STAILQ_FOREACH(vdev, &zfs_vdevs, v_alllink)
1075                 if (vdev->v_guid == guid)
1076                         return (vdev);
1077
1078         return (0);
1079 }
1080
1081 static vdev_t *
1082 vdev_create(uint64_t guid, vdev_read_t *_read)
1083 {
1084         vdev_t *vdev;
1085         vdev_indirect_config_t *vic;
1086
1087         vdev = malloc(sizeof(vdev_t));
1088         memset(vdev, 0, sizeof(vdev_t));
1089         STAILQ_INIT(&vdev->v_children);
1090         vdev->v_guid = guid;
1091         vdev->v_state = VDEV_STATE_OFFLINE;
1092         vdev->v_read = _read;
1093
1094         vic = &vdev->vdev_indirect_config;
1095         vic->vic_prev_indirect_vdev = UINT64_MAX;
1096         STAILQ_INSERT_TAIL(&zfs_vdevs, vdev, v_alllink);
1097
1098         return (vdev);
1099 }
1100
1101 static int
1102 vdev_init_from_nvlist(const unsigned char *nvlist, vdev_t *pvdev,
1103     vdev_t **vdevp, int is_newer)
1104 {
1105         int rc;
1106         uint64_t guid, id, ashift, asize, nparity;
1107         const char *type;
1108         const char *path;
1109         vdev_t *vdev, *kid;
1110         const unsigned char *kids;
1111         int nkids, i, is_new;
1112         uint64_t is_offline, is_faulted, is_degraded, is_removed, isnt_present;
1113         uint64_t is_log;
1114
1115         if (nvlist_find(nvlist, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64,
1116             NULL, &guid)
1117             || nvlist_find(nvlist, ZPOOL_CONFIG_ID, DATA_TYPE_UINT64, NULL, &id)
1118             || nvlist_find(nvlist, ZPOOL_CONFIG_TYPE, DATA_TYPE_STRING,
1119             NULL, &type)) {
1120                 printf("ZFS: can't find vdev details\n");
1121                 return (ENOENT);
1122         }
1123
1124         if (strcmp(type, VDEV_TYPE_MIRROR)
1125             && strcmp(type, VDEV_TYPE_DISK)
1126 #ifdef ZFS_TEST
1127             && strcmp(type, VDEV_TYPE_FILE)
1128 #endif
1129             && strcmp(type, VDEV_TYPE_RAIDZ)
1130             && strcmp(type, VDEV_TYPE_INDIRECT)
1131             && strcmp(type, VDEV_TYPE_REPLACING)) {
1132                 printf("ZFS: can only boot from disk, mirror, raidz1, raidz2 and raidz3 vdevs\n");
1133                 return (EIO);
1134         }
1135
1136         is_offline = is_removed = is_faulted = is_degraded = isnt_present = 0;
1137         is_log = 0;
1138
1139         nvlist_find(nvlist, ZPOOL_CONFIG_OFFLINE, DATA_TYPE_UINT64, NULL,
1140             &is_offline);
1141         nvlist_find(nvlist, ZPOOL_CONFIG_REMOVED, DATA_TYPE_UINT64, NULL,
1142             &is_removed);
1143         nvlist_find(nvlist, ZPOOL_CONFIG_FAULTED, DATA_TYPE_UINT64, NULL,
1144             &is_faulted);
1145         nvlist_find(nvlist, ZPOOL_CONFIG_DEGRADED, DATA_TYPE_UINT64, NULL,
1146             &is_degraded);
1147         nvlist_find(nvlist, ZPOOL_CONFIG_NOT_PRESENT, DATA_TYPE_UINT64, NULL,
1148             &isnt_present);
1149         nvlist_find(nvlist, ZPOOL_CONFIG_IS_LOG, DATA_TYPE_UINT64, NULL,
1150             &is_log);
1151
1152         vdev = vdev_find(guid);
1153         if (!vdev) {
1154                 is_new = 1;
1155
1156                 if (!strcmp(type, VDEV_TYPE_MIRROR))
1157                         vdev = vdev_create(guid, vdev_mirror_read);
1158                 else if (!strcmp(type, VDEV_TYPE_RAIDZ))
1159                         vdev = vdev_create(guid, vdev_raidz_read);
1160                 else if (!strcmp(type, VDEV_TYPE_REPLACING))
1161                         vdev = vdev_create(guid, vdev_replacing_read);
1162                 else if (!strcmp(type, VDEV_TYPE_INDIRECT)) {
1163                         vdev_indirect_config_t *vic;
1164
1165                         vdev = vdev_create(guid, vdev_indirect_read);
1166                         vdev->v_state = VDEV_STATE_HEALTHY;
1167                         vic = &vdev->vdev_indirect_config;
1168
1169                         nvlist_find(nvlist,
1170                             ZPOOL_CONFIG_INDIRECT_OBJECT, DATA_TYPE_UINT64,
1171                             NULL, &vic->vic_mapping_object);
1172                         nvlist_find(nvlist,
1173                             ZPOOL_CONFIG_INDIRECT_BIRTHS, DATA_TYPE_UINT64,
1174                             NULL, &vic->vic_births_object);
1175                         nvlist_find(nvlist,
1176                             ZPOOL_CONFIG_PREV_INDIRECT_VDEV, DATA_TYPE_UINT64,
1177                             NULL, &vic->vic_prev_indirect_vdev);
1178                 } else
1179                         vdev = vdev_create(guid, vdev_disk_read);
1180
1181                 vdev->v_id = id;
1182                 vdev->v_top = pvdev != NULL ? pvdev : vdev;
1183                 if (nvlist_find(nvlist, ZPOOL_CONFIG_ASHIFT,
1184                         DATA_TYPE_UINT64, NULL, &ashift) == 0) {
1185                         vdev->v_ashift = ashift;
1186                 } else {
1187                         vdev->v_ashift = 0;
1188                 }
1189                 if (nvlist_find(nvlist, ZPOOL_CONFIG_ASIZE,
1190                     DATA_TYPE_UINT64, NULL, &asize) == 0) {
1191                         vdev->v_psize = asize +
1192                             VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE;
1193                 }
1194                 if (nvlist_find(nvlist, ZPOOL_CONFIG_NPARITY,
1195                         DATA_TYPE_UINT64, NULL, &nparity) == 0) {
1196                         vdev->v_nparity = nparity;
1197                 } else {
1198                         vdev->v_nparity = 0;
1199                 }
1200                 if (nvlist_find(nvlist, ZPOOL_CONFIG_PATH,
1201                                 DATA_TYPE_STRING, NULL, &path) == 0) {
1202                         if (strncmp(path, "/dev/", 5) == 0)
1203                                 path += 5;
1204                         vdev->v_name = strdup(path);
1205                 } else {
1206                         char *name;
1207
1208                         if (!strcmp(type, "raidz")) {
1209                                 if (vdev->v_nparity < 1 ||
1210                                     vdev->v_nparity > 3) {
1211                                         printf("ZFS: can only boot from disk, "
1212                                             "mirror, raidz1, raidz2 and raidz3 "
1213                                             "vdevs\n");
1214                                         return (EIO);
1215                                 }
1216                                 asprintf(&name, "%s%d-%jd", type,
1217                                     vdev->v_nparity, id);
1218                         } else {
1219                                 asprintf(&name, "%s-%jd", type, id);
1220                         }
1221                         if (name == NULL)
1222                                 return (ENOMEM);
1223                         vdev->v_name = name;
1224                 }
1225                 vdev->v_islog = is_log == 1;
1226         } else {
1227                 is_new = 0;
1228         }
1229
1230         if (is_new || is_newer) {
1231                 /*
1232                  * This is either new vdev or we've already seen this vdev,
1233                  * but from an older vdev label, so let's refresh its state
1234                  * from the newer label.
1235                  */
1236                 if (is_offline)
1237                         vdev->v_state = VDEV_STATE_OFFLINE;
1238                 else if (is_removed)
1239                         vdev->v_state = VDEV_STATE_REMOVED;
1240                 else if (is_faulted)
1241                         vdev->v_state = VDEV_STATE_FAULTED;
1242                 else if (is_degraded)
1243                         vdev->v_state = VDEV_STATE_DEGRADED;
1244                 else if (isnt_present)
1245                         vdev->v_state = VDEV_STATE_CANT_OPEN;
1246         }
1247
1248         rc = nvlist_find(nvlist, ZPOOL_CONFIG_CHILDREN, DATA_TYPE_NVLIST_ARRAY,
1249             &nkids, &kids);
1250         /*
1251          * Its ok if we don't have any kids.
1252          */
1253         if (rc == 0) {
1254                 vdev->v_nchildren = nkids;
1255                 for (i = 0; i < nkids; i++) {
1256                         rc = vdev_init_from_nvlist(kids, vdev, &kid, is_newer);
1257                         if (rc)
1258                                 return (rc);
1259                         if (is_new)
1260                                 STAILQ_INSERT_TAIL(&vdev->v_children, kid,
1261                                                    v_childlink);
1262                         kids = nvlist_next(kids);
1263                 }
1264         } else {
1265                 vdev->v_nchildren = 0;
1266         }
1267
1268         if (vdevp)
1269                 *vdevp = vdev;
1270         return (0);
1271 }
1272
1273 static void
1274 vdev_set_state(vdev_t *vdev)
1275 {
1276         vdev_t *kid;
1277         int good_kids;
1278         int bad_kids;
1279
1280         /*
1281          * A mirror or raidz is healthy if all its kids are healthy. A
1282          * mirror is degraded if any of its kids is healthy; a raidz
1283          * is degraded if at most nparity kids are offline.
1284          */
1285         if (STAILQ_FIRST(&vdev->v_children)) {
1286                 good_kids = 0;
1287                 bad_kids = 0;
1288                 STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
1289                         if (kid->v_state == VDEV_STATE_HEALTHY)
1290                                 good_kids++;
1291                         else
1292                                 bad_kids++;
1293                 }
1294                 if (bad_kids == 0) {
1295                         vdev->v_state = VDEV_STATE_HEALTHY;
1296                 } else {
1297                         if (vdev->v_read == vdev_mirror_read) {
1298                                 if (good_kids) {
1299                                         vdev->v_state = VDEV_STATE_DEGRADED;
1300                                 } else {
1301                                         vdev->v_state = VDEV_STATE_OFFLINE;
1302                                 }
1303                         } else if (vdev->v_read == vdev_raidz_read) {
1304                                 if (bad_kids > vdev->v_nparity) {
1305                                         vdev->v_state = VDEV_STATE_OFFLINE;
1306                                 } else {
1307                                         vdev->v_state = VDEV_STATE_DEGRADED;
1308                                 }
1309                         }
1310                 }
1311         }
1312 }
1313
1314 static spa_t *
1315 spa_find_by_guid(uint64_t guid)
1316 {
1317         spa_t *spa;
1318
1319         STAILQ_FOREACH(spa, &zfs_pools, spa_link)
1320                 if (spa->spa_guid == guid)
1321                         return (spa);
1322
1323         return (0);
1324 }
1325
1326 static spa_t *
1327 spa_find_by_name(const char *name)
1328 {
1329         spa_t *spa;
1330
1331         STAILQ_FOREACH(spa, &zfs_pools, spa_link)
1332                 if (!strcmp(spa->spa_name, name))
1333                         return (spa);
1334
1335         return (0);
1336 }
1337
1338 #ifdef BOOT2
1339 static spa_t *
1340 spa_get_primary(void)
1341 {
1342
1343         return (STAILQ_FIRST(&zfs_pools));
1344 }
1345
1346 static vdev_t *
1347 spa_get_primary_vdev(const spa_t *spa)
1348 {
1349         vdev_t *vdev;
1350         vdev_t *kid;
1351
1352         if (spa == NULL)
1353                 spa = spa_get_primary();
1354         if (spa == NULL)
1355                 return (NULL);
1356         vdev = STAILQ_FIRST(&spa->spa_vdevs);
1357         if (vdev == NULL)
1358                 return (NULL);
1359         for (kid = STAILQ_FIRST(&vdev->v_children); kid != NULL;
1360              kid = STAILQ_FIRST(&vdev->v_children))
1361                 vdev = kid;
1362         return (vdev);
1363 }
1364 #endif
1365
1366 static spa_t *
1367 spa_create(uint64_t guid, const char *name)
1368 {
1369         spa_t *spa;
1370
1371         if ((spa = calloc(1, sizeof(spa_t))) == NULL)
1372                 return (NULL);
1373         if ((spa->spa_name = strdup(name)) == NULL) {
1374                 free(spa);
1375                 return (NULL);
1376         }
1377         STAILQ_INIT(&spa->spa_vdevs);
1378         spa->spa_guid = guid;
1379         STAILQ_INSERT_TAIL(&zfs_pools, spa, spa_link);
1380
1381         return (spa);
1382 }
1383
1384 static const char *
1385 state_name(vdev_state_t state)
1386 {
1387         static const char* names[] = {
1388                 "UNKNOWN",
1389                 "CLOSED",
1390                 "OFFLINE",
1391                 "REMOVED",
1392                 "CANT_OPEN",
1393                 "FAULTED",
1394                 "DEGRADED",
1395                 "ONLINE"
1396         };
1397         return names[state];
1398 }
1399
1400 #ifdef BOOT2
1401
1402 #define pager_printf printf
1403
1404 #else
1405
1406 static int
1407 pager_printf(const char *fmt, ...)
1408 {
1409         char line[80];
1410         va_list args;
1411
1412         va_start(args, fmt);
1413         vsprintf(line, fmt, args);
1414         va_end(args);
1415
1416         return (pager_output(line));
1417 }
1418
1419 #endif
1420
1421 #define STATUS_FORMAT   "        %s %s\n"
1422
1423 static int
1424 print_state(int indent, const char *name, vdev_state_t state)
1425 {
1426         char buf[512];
1427         int i;
1428
1429         buf[0] = 0;
1430         for (i = 0; i < indent; i++)
1431                 strcat(buf, "  ");
1432         strcat(buf, name);
1433
1434         return (pager_printf(STATUS_FORMAT, buf, state_name(state)));
1435 }
1436
1437 static int
1438 vdev_status(vdev_t *vdev, int indent)
1439 {
1440         vdev_t *kid;
1441         int ret;
1442
1443         if (vdev->v_islog) {
1444                 (void)pager_output("        logs\n");
1445                 indent++;
1446         }
1447
1448         ret = print_state(indent, vdev->v_name, vdev->v_state);
1449         if (ret != 0)
1450                 return (ret);
1451
1452         STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
1453                 ret = vdev_status(kid, indent + 1);
1454                 if (ret != 0)
1455                         return (ret);
1456         }
1457         return (ret);
1458 }
1459
1460 static int
1461 spa_status(spa_t *spa)
1462 {
1463         static char bootfs[ZFS_MAXNAMELEN];
1464         uint64_t rootid;
1465         vdev_t *vdev;
1466         int good_kids, bad_kids, degraded_kids, ret;
1467         vdev_state_t state;
1468
1469         ret = pager_printf("  pool: %s\n", spa->spa_name);
1470         if (ret != 0)
1471                 return (ret);
1472
1473         if (zfs_get_root(spa, &rootid) == 0 &&
1474             zfs_rlookup(spa, rootid, bootfs) == 0) {
1475                 if (bootfs[0] == '\0')
1476                         ret = pager_printf("bootfs: %s\n", spa->spa_name);
1477                 else
1478                         ret = pager_printf("bootfs: %s/%s\n", spa->spa_name,
1479                             bootfs);
1480                 if (ret != 0)
1481                         return (ret);
1482         }
1483         ret = pager_printf("config:\n\n");
1484         if (ret != 0)
1485                 return (ret);
1486         ret = pager_printf(STATUS_FORMAT, "NAME", "STATE");
1487         if (ret != 0)
1488                 return (ret);
1489
1490         good_kids = 0;
1491         degraded_kids = 0;
1492         bad_kids = 0;
1493         STAILQ_FOREACH(vdev, &spa->spa_vdevs, v_childlink) {
1494                 if (vdev->v_state == VDEV_STATE_HEALTHY)
1495                         good_kids++;
1496                 else if (vdev->v_state == VDEV_STATE_DEGRADED)
1497                         degraded_kids++;
1498                 else
1499                         bad_kids++;
1500         }
1501
1502         state = VDEV_STATE_CLOSED;
1503         if (good_kids > 0 && (degraded_kids + bad_kids) == 0)
1504                 state = VDEV_STATE_HEALTHY;
1505         else if ((good_kids + degraded_kids) > 0)
1506                 state = VDEV_STATE_DEGRADED;
1507
1508         ret = print_state(0, spa->spa_name, state);
1509         if (ret != 0)
1510                 return (ret);
1511         STAILQ_FOREACH(vdev, &spa->spa_vdevs, v_childlink) {
1512                 ret = vdev_status(vdev, 1);
1513                 if (ret != 0)
1514                         return (ret);
1515         }
1516         return (ret);
1517 }
1518
1519 static int
1520 spa_all_status(void)
1521 {
1522         spa_t *spa;
1523         int first = 1, ret = 0;
1524
1525         STAILQ_FOREACH(spa, &zfs_pools, spa_link) {
1526                 if (!first) {
1527                         ret = pager_printf("\n");
1528                         if (ret != 0)
1529                                 return (ret);
1530                 }
1531                 first = 0;
1532                 ret = spa_status(spa);
1533                 if (ret != 0)
1534                         return (ret);
1535         }
1536         return (ret);
1537 }
1538
1539 static uint64_t
1540 vdev_label_offset(uint64_t psize, int l, uint64_t offset)
1541 {
1542         uint64_t label_offset;
1543
1544         if (l < VDEV_LABELS / 2)
1545                 label_offset = 0;
1546         else
1547                 label_offset = psize - VDEV_LABELS * sizeof (vdev_label_t);
1548
1549         return (offset + l * sizeof (vdev_label_t) + label_offset);
1550 }
1551
1552 static int
1553 vdev_uberblock_compare(const uberblock_t *ub1, const uberblock_t *ub2)
1554 {
1555         unsigned int seq1 = 0;
1556         unsigned int seq2 = 0;
1557         int cmp = AVL_CMP(ub1->ub_txg, ub2->ub_txg);
1558
1559         if (cmp != 0)
1560                 return (cmp);
1561
1562         cmp = AVL_CMP(ub1->ub_timestamp, ub2->ub_timestamp);
1563         if (cmp != 0)
1564                 return (cmp);
1565
1566         if (MMP_VALID(ub1) && MMP_SEQ_VALID(ub1))
1567                 seq1 = MMP_SEQ(ub1);
1568
1569         if (MMP_VALID(ub2) && MMP_SEQ_VALID(ub2))
1570                 seq2 = MMP_SEQ(ub2);
1571
1572         return (AVL_CMP(seq1, seq2));
1573 }
1574
1575 static int
1576 uberblock_verify(uberblock_t *ub)
1577 {
1578         if (ub->ub_magic == BSWAP_64((uint64_t)UBERBLOCK_MAGIC)) {
1579                 byteswap_uint64_array(ub, sizeof (uberblock_t));
1580         }
1581
1582         if (ub->ub_magic != UBERBLOCK_MAGIC ||
1583             !SPA_VERSION_IS_SUPPORTED(ub->ub_version))
1584                 return (EINVAL);
1585
1586         return (0);
1587 }
1588
1589 static int
1590 vdev_label_read(vdev_t *vd, int l, void *buf, uint64_t offset,
1591     size_t size)
1592 {
1593         blkptr_t bp;
1594         off_t off;
1595
1596         off = vdev_label_offset(vd->v_psize, l, offset);
1597
1598         BP_ZERO(&bp);
1599         BP_SET_LSIZE(&bp, size);
1600         BP_SET_PSIZE(&bp, size);
1601         BP_SET_CHECKSUM(&bp, ZIO_CHECKSUM_LABEL);
1602         BP_SET_COMPRESS(&bp, ZIO_COMPRESS_OFF);
1603         DVA_SET_OFFSET(BP_IDENTITY(&bp), off);
1604         ZIO_SET_CHECKSUM(&bp.blk_cksum, off, 0, 0, 0);
1605
1606         return (vdev_read_phys(vd, &bp, buf, off, size));
1607 }
1608
1609 static unsigned char *
1610 vdev_label_read_config(vdev_t *vd, uint64_t txg)
1611 {
1612         vdev_phys_t *label;
1613         uint64_t best_txg = 0;
1614         uint64_t label_txg = 0;
1615         uint64_t asize;
1616         unsigned char *nvl;
1617         size_t nvl_size;
1618         int error;
1619
1620         label = malloc(sizeof (vdev_phys_t));
1621         if (label == NULL)
1622                 return (NULL);
1623
1624         nvl_size = VDEV_PHYS_SIZE - sizeof (zio_eck_t) - 4;
1625         nvl = malloc(nvl_size);
1626         if (nvl == NULL)
1627                 goto done;
1628
1629         for (int l = 0; l < VDEV_LABELS; l++) {
1630                 const unsigned char *nvlist;
1631
1632                 if (vdev_label_read(vd, l, label,
1633                     offsetof(vdev_label_t, vl_vdev_phys),
1634                     sizeof (vdev_phys_t)))
1635                         continue;
1636
1637                 if (label->vp_nvlist[0] != NV_ENCODE_XDR)
1638                         continue;
1639
1640                 nvlist = (const unsigned char *) label->vp_nvlist + 4;
1641                 error = nvlist_find(nvlist, ZPOOL_CONFIG_POOL_TXG,
1642                     DATA_TYPE_UINT64, NULL, &label_txg);
1643                 if (error != 0 || label_txg == 0) {
1644                         memcpy(nvl, nvlist, nvl_size);
1645                         goto done;
1646                 }
1647
1648                 if (label_txg <= txg && label_txg > best_txg) {
1649                         best_txg = label_txg;
1650                         memcpy(nvl, nvlist, nvl_size);
1651
1652                         /*
1653                          * Use asize from pool config. We need this
1654                          * because we can get bad value from BIOS.
1655                          */
1656                         if (nvlist_find(nvlist, ZPOOL_CONFIG_ASIZE,
1657                             DATA_TYPE_UINT64, NULL, &asize) == 0) {
1658                                 vd->v_psize = asize +
1659                                     VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE;
1660                         }
1661                 }
1662         }
1663
1664         if (best_txg == 0) {
1665                 free(nvl);
1666                 nvl = NULL;
1667         }
1668 done:
1669         free(label);
1670         return (nvl);
1671 }
1672
1673 static void
1674 vdev_uberblock_load(vdev_t *vd, uberblock_t *ub)
1675 {
1676         uberblock_t *buf;
1677
1678         buf = malloc(VDEV_UBERBLOCK_SIZE(vd));
1679         if (buf == NULL)
1680                 return;
1681
1682         for (int l = 0; l < VDEV_LABELS; l++) {
1683                 for (int n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
1684                         if (vdev_label_read(vd, l, buf,
1685                             VDEV_UBERBLOCK_OFFSET(vd, n),
1686                             VDEV_UBERBLOCK_SIZE(vd)))
1687                                 continue;
1688                         if (uberblock_verify(buf) != 0)
1689                                 continue;
1690
1691                         if (vdev_uberblock_compare(buf, ub) > 0)
1692                                 *ub = *buf;
1693                 }
1694         }
1695         free(buf);
1696 }
1697
1698 static int
1699 vdev_probe(vdev_phys_read_t *_read, void *read_priv, spa_t **spap)
1700 {
1701         vdev_t vtmp;
1702         spa_t *spa;
1703         vdev_t *vdev, *top_vdev, *pool_vdev;
1704         unsigned char *nvlist;
1705         uint64_t val;
1706         uint64_t guid;
1707         uint64_t pool_txg, pool_guid;
1708         const char *pool_name;
1709         const unsigned char *vdevs;
1710         const unsigned char *features;
1711         int rc, is_newer;
1712
1713         /*
1714          * Load the vdev label and figure out which
1715          * uberblock is most current.
1716          */
1717         memset(&vtmp, 0, sizeof(vtmp));
1718         vtmp.v_phys_read = _read;
1719         vtmp.v_read_priv = read_priv;
1720         vtmp.v_psize = P2ALIGN(ldi_get_size(read_priv),
1721             (uint64_t)sizeof (vdev_label_t));
1722
1723         /* Test for minimum device size. */
1724         if (vtmp.v_psize < SPA_MINDEVSIZE)
1725                 return (EIO);
1726
1727         nvlist = vdev_label_read_config(&vtmp, UINT64_MAX);
1728         if (nvlist == NULL)
1729                 return (EIO);
1730
1731         if (nvlist_find(nvlist, ZPOOL_CONFIG_VERSION, DATA_TYPE_UINT64,
1732             NULL, &val) != 0) {
1733                 free(nvlist);
1734                 return (EIO);
1735         }
1736
1737         if (!SPA_VERSION_IS_SUPPORTED(val)) {
1738                 printf("ZFS: unsupported ZFS version %u (should be %u)\n",
1739                     (unsigned) val, (unsigned) SPA_VERSION);
1740                 free(nvlist);
1741                 return (EIO);
1742         }
1743
1744         /* Check ZFS features for read */
1745         if (nvlist_find(nvlist, ZPOOL_CONFIG_FEATURES_FOR_READ,
1746             DATA_TYPE_NVLIST, NULL, &features) == 0 &&
1747             nvlist_check_features_for_read(features) != 0) {
1748                 free(nvlist);
1749                 return (EIO);
1750         }
1751
1752         if (nvlist_find(nvlist, ZPOOL_CONFIG_POOL_STATE, DATA_TYPE_UINT64,
1753             NULL, &val) != 0) {
1754                 free(nvlist);
1755                 return (EIO);
1756         }
1757
1758         if (val == POOL_STATE_DESTROYED) {
1759                 /* We don't boot only from destroyed pools. */
1760                 free(nvlist);
1761                 return (EIO);
1762         }
1763
1764         if (nvlist_find(nvlist, ZPOOL_CONFIG_POOL_TXG, DATA_TYPE_UINT64,
1765             NULL, &pool_txg) != 0 ||
1766             nvlist_find(nvlist, ZPOOL_CONFIG_POOL_GUID, DATA_TYPE_UINT64,
1767             NULL, &pool_guid) != 0 ||
1768             nvlist_find(nvlist, ZPOOL_CONFIG_POOL_NAME, DATA_TYPE_STRING,
1769             NULL, &pool_name) != 0) {
1770                 /*
1771                  * Cache and spare devices end up here - just ignore
1772                  * them.
1773                  */
1774                 free(nvlist);
1775                 return (EIO);
1776         }
1777
1778         /*
1779          * Create the pool if this is the first time we've seen it.
1780          */
1781         spa = spa_find_by_guid(pool_guid);
1782         if (spa == NULL) {
1783                 spa = spa_create(pool_guid, pool_name);
1784                 if (spa == NULL) {
1785                         free(nvlist);
1786                         return (ENOMEM);
1787                 }
1788         }
1789         if (pool_txg > spa->spa_txg) {
1790                 spa->spa_txg = pool_txg;
1791                 is_newer = 1;
1792         } else {
1793                 is_newer = 0;
1794         }
1795
1796         /*
1797          * Get the vdev tree and create our in-core copy of it.
1798          * If we already have a vdev with this guid, this must
1799          * be some kind of alias (overlapping slices, dangerously dedicated
1800          * disks etc).
1801          */
1802         if (nvlist_find(nvlist, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64,
1803             NULL, &guid) != 0) {
1804                 free(nvlist);
1805                 return (EIO);
1806         }
1807         vdev = vdev_find(guid);
1808         /* Has this vdev already been inited? */
1809         if (vdev && vdev->v_phys_read) {
1810                 free(nvlist);
1811                 return (EIO);
1812         }
1813
1814         if (nvlist_find(nvlist, ZPOOL_CONFIG_VDEV_TREE, DATA_TYPE_NVLIST,
1815             NULL, &vdevs)) {
1816                 free(nvlist);
1817                 return (EIO);
1818         }
1819
1820         rc = vdev_init_from_nvlist(vdevs, NULL, &top_vdev, is_newer);
1821         free(nvlist);
1822         if (rc != 0)
1823                 return (rc);
1824
1825         /*
1826          * Add the toplevel vdev to the pool if its not already there.
1827          */
1828         STAILQ_FOREACH(pool_vdev, &spa->spa_vdevs, v_childlink)
1829                 if (top_vdev == pool_vdev)
1830                         break;
1831
1832         if (!pool_vdev && top_vdev) {
1833                 top_vdev->spa = spa;
1834                 STAILQ_INSERT_TAIL(&spa->spa_vdevs, top_vdev, v_childlink);
1835         }
1836
1837         /*
1838          * We should already have created an incomplete vdev for this
1839          * vdev. Find it and initialise it with our read proc.
1840          */
1841         vdev = vdev_find(guid);
1842         if (vdev) {
1843                 vdev->v_phys_read = _read;
1844                 vdev->v_read_priv = read_priv;
1845                 vdev->v_state = VDEV_STATE_HEALTHY;
1846                 vdev->v_psize = vtmp.v_psize;
1847         } else {
1848                 printf("ZFS: inconsistent nvlist contents\n");
1849                 return (EIO);
1850         }
1851
1852         if (vdev->v_islog)
1853                 spa->spa_with_log = vdev->v_islog;
1854
1855         /*
1856          * Re-evaluate top-level vdev state.
1857          */
1858         vdev_set_state(top_vdev);
1859
1860         /*
1861          * Ok, we are happy with the pool so far. Lets find
1862          * the best uberblock and then we can actually access
1863          * the contents of the pool.
1864          */
1865         vdev_uberblock_load(vdev, &spa->spa_uberblock);
1866
1867         vdev->spa = spa;
1868         if (spap != NULL)
1869                 *spap = spa;
1870         return (0);
1871 }
1872
1873 static int
1874 ilog2(int n)
1875 {
1876         int v;
1877
1878         for (v = 0; v < 32; v++)
1879                 if (n == (1 << v))
1880                         return v;
1881         return -1;
1882 }
1883
1884 static int
1885 zio_read_gang(const spa_t *spa, const blkptr_t *bp, void *buf)
1886 {
1887         blkptr_t gbh_bp;
1888         zio_gbh_phys_t zio_gb;
1889         char *pbuf;
1890         int i;
1891
1892         /* Artificial BP for gang block header. */
1893         gbh_bp = *bp;
1894         BP_SET_PSIZE(&gbh_bp, SPA_GANGBLOCKSIZE);
1895         BP_SET_LSIZE(&gbh_bp, SPA_GANGBLOCKSIZE);
1896         BP_SET_CHECKSUM(&gbh_bp, ZIO_CHECKSUM_GANG_HEADER);
1897         BP_SET_COMPRESS(&gbh_bp, ZIO_COMPRESS_OFF);
1898         for (i = 0; i < SPA_DVAS_PER_BP; i++)
1899                 DVA_SET_GANG(&gbh_bp.blk_dva[i], 0);
1900
1901         /* Read gang header block using the artificial BP. */
1902         if (zio_read(spa, &gbh_bp, &zio_gb))
1903                 return (EIO);
1904
1905         pbuf = buf;
1906         for (i = 0; i < SPA_GBH_NBLKPTRS; i++) {
1907                 blkptr_t *gbp = &zio_gb.zg_blkptr[i];
1908
1909                 if (BP_IS_HOLE(gbp))
1910                         continue;
1911                 if (zio_read(spa, gbp, pbuf))
1912                         return (EIO);
1913                 pbuf += BP_GET_PSIZE(gbp);
1914         }
1915
1916         if (zio_checksum_verify(spa, bp, buf))
1917                 return (EIO);
1918         return (0);
1919 }
1920
1921 static int
1922 zio_read(const spa_t *spa, const blkptr_t *bp, void *buf)
1923 {
1924         int cpfunc = BP_GET_COMPRESS(bp);
1925         uint64_t align, size;
1926         void *pbuf;
1927         int i, error;
1928
1929         /*
1930          * Process data embedded in block pointer
1931          */
1932         if (BP_IS_EMBEDDED(bp)) {
1933                 ASSERT(BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
1934
1935                 size = BPE_GET_PSIZE(bp);
1936                 ASSERT(size <= BPE_PAYLOAD_SIZE);
1937
1938                 if (cpfunc != ZIO_COMPRESS_OFF)
1939                         pbuf = zfs_alloc(size);
1940                 else
1941                         pbuf = buf;
1942
1943                 decode_embedded_bp_compressed(bp, pbuf);
1944                 error = 0;
1945
1946                 if (cpfunc != ZIO_COMPRESS_OFF) {
1947                         error = zio_decompress_data(cpfunc, pbuf,
1948                             size, buf, BP_GET_LSIZE(bp));
1949                         zfs_free(pbuf, size);
1950                 }
1951                 if (error != 0)
1952                         printf("ZFS: i/o error - unable to decompress block pointer data, error %d\n",
1953                             error);
1954                 return (error);
1955         }
1956
1957         error = EIO;
1958
1959         for (i = 0; i < SPA_DVAS_PER_BP; i++) {
1960                 const dva_t *dva = &bp->blk_dva[i];
1961                 vdev_t *vdev;
1962                 int vdevid;
1963                 off_t offset;
1964
1965                 if (!dva->dva_word[0] && !dva->dva_word[1])
1966                         continue;
1967
1968                 vdevid = DVA_GET_VDEV(dva);
1969                 offset = DVA_GET_OFFSET(dva);
1970                 STAILQ_FOREACH(vdev, &spa->spa_vdevs, v_childlink) {
1971                         if (vdev->v_id == vdevid)
1972                                 break;
1973                 }
1974                 if (!vdev || !vdev->v_read)
1975                         continue;
1976
1977                 size = BP_GET_PSIZE(bp);
1978                 if (vdev->v_read == vdev_raidz_read) {
1979                         align = 1ULL << vdev->v_top->v_ashift;
1980                         if (P2PHASE(size, align) != 0)
1981                                 size = P2ROUNDUP(size, align);
1982                 }
1983                 if (size != BP_GET_PSIZE(bp) || cpfunc != ZIO_COMPRESS_OFF)
1984                         pbuf = zfs_alloc(size);
1985                 else
1986                         pbuf = buf;
1987
1988                 if (DVA_GET_GANG(dva))
1989                         error = zio_read_gang(spa, bp, pbuf);
1990                 else
1991                         error = vdev->v_read(vdev, bp, pbuf, offset, size);
1992                 if (error == 0) {
1993                         if (cpfunc != ZIO_COMPRESS_OFF)
1994                                 error = zio_decompress_data(cpfunc, pbuf,
1995                                     BP_GET_PSIZE(bp), buf, BP_GET_LSIZE(bp));
1996                         else if (size != BP_GET_PSIZE(bp))
1997                                 bcopy(pbuf, buf, BP_GET_PSIZE(bp));
1998                 }
1999                 if (buf != pbuf)
2000                         zfs_free(pbuf, size);
2001                 if (error == 0)
2002                         break;
2003         }
2004         if (error != 0)
2005                 printf("ZFS: i/o error - all block copies unavailable\n");
2006         return (error);
2007 }
2008
2009 static int
2010 dnode_read(const spa_t *spa, const dnode_phys_t *dnode, off_t offset, void *buf, size_t buflen)
2011 {
2012         int ibshift = dnode->dn_indblkshift - SPA_BLKPTRSHIFT;
2013         int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
2014         int nlevels = dnode->dn_nlevels;
2015         int i, rc;
2016
2017         if (bsize > SPA_MAXBLOCKSIZE) {
2018                 printf("ZFS: I/O error - blocks larger than %llu are not "
2019                     "supported\n", SPA_MAXBLOCKSIZE);
2020                 return (EIO);
2021         }
2022
2023         /*
2024          * Note: bsize may not be a power of two here so we need to do an
2025          * actual divide rather than a bitshift.
2026          */
2027         while (buflen > 0) {
2028                 uint64_t bn = offset / bsize;
2029                 int boff = offset % bsize;
2030                 int ibn;
2031                 const blkptr_t *indbp;
2032                 blkptr_t bp;
2033
2034                 if (bn > dnode->dn_maxblkid)
2035                         return (EIO);
2036
2037                 if (dnode == dnode_cache_obj && bn == dnode_cache_bn)
2038                         goto cached;
2039
2040                 indbp = dnode->dn_blkptr;
2041                 for (i = 0; i < nlevels; i++) {
2042                         /*
2043                          * Copy the bp from the indirect array so that
2044                          * we can re-use the scratch buffer for multi-level
2045                          * objects.
2046                          */
2047                         ibn = bn >> ((nlevels - i - 1) * ibshift);
2048                         ibn &= ((1 << ibshift) - 1);
2049                         bp = indbp[ibn];
2050                         if (BP_IS_HOLE(&bp)) {
2051                                 memset(dnode_cache_buf, 0, bsize);
2052                                 break;
2053                         }
2054                         rc = zio_read(spa, &bp, dnode_cache_buf);
2055                         if (rc)
2056                                 return (rc);
2057                         indbp = (const blkptr_t *) dnode_cache_buf;
2058                 }
2059                 dnode_cache_obj = dnode;
2060                 dnode_cache_bn = bn;
2061         cached:
2062
2063                 /*
2064                  * The buffer contains our data block. Copy what we
2065                  * need from it and loop.
2066                  */ 
2067                 i = bsize - boff;
2068                 if (i > buflen) i = buflen;
2069                 memcpy(buf, &dnode_cache_buf[boff], i);
2070                 buf = ((char*) buf) + i;
2071                 offset += i;
2072                 buflen -= i;
2073         }
2074
2075         return (0);
2076 }
2077
2078 /*
2079  * Lookup a value in a microzap directory. Assumes that the zap
2080  * scratch buffer contains the directory contents.
2081  */
2082 static int
2083 mzap_lookup(const dnode_phys_t *dnode, const char *name, uint64_t *value)
2084 {
2085         const mzap_phys_t *mz;
2086         const mzap_ent_phys_t *mze;
2087         size_t size;
2088         int chunks, i;
2089
2090         /*
2091          * Microzap objects use exactly one block. Read the whole
2092          * thing.
2093          */
2094         size = dnode->dn_datablkszsec * 512;
2095
2096         mz = (const mzap_phys_t *) zap_scratch;
2097         chunks = size / MZAP_ENT_LEN - 1;
2098
2099         for (i = 0; i < chunks; i++) {
2100                 mze = &mz->mz_chunk[i];
2101                 if (!strcmp(mze->mze_name, name)) {
2102                         *value = mze->mze_value;
2103                         return (0);
2104                 }
2105         }
2106
2107         return (ENOENT);
2108 }
2109
2110 /*
2111  * Compare a name with a zap leaf entry. Return non-zero if the name
2112  * matches.
2113  */
2114 static int
2115 fzap_name_equal(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc, const char *name)
2116 {
2117         size_t namelen;
2118         const zap_leaf_chunk_t *nc;
2119         const char *p;
2120
2121         namelen = zc->l_entry.le_name_numints;
2122                         
2123         nc = &ZAP_LEAF_CHUNK(zl, zc->l_entry.le_name_chunk);
2124         p = name;
2125         while (namelen > 0) {
2126                 size_t len;
2127                 len = namelen;
2128                 if (len > ZAP_LEAF_ARRAY_BYTES)
2129                         len = ZAP_LEAF_ARRAY_BYTES;
2130                 if (memcmp(p, nc->l_array.la_array, len))
2131                         return (0);
2132                 p += len;
2133                 namelen -= len;
2134                 nc = &ZAP_LEAF_CHUNK(zl, nc->l_array.la_next);
2135         }
2136
2137         return 1;
2138 }
2139
2140 /*
2141  * Extract a uint64_t value from a zap leaf entry.
2142  */
2143 static uint64_t
2144 fzap_leaf_value(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc)
2145 {
2146         const zap_leaf_chunk_t *vc;
2147         int i;
2148         uint64_t value;
2149         const uint8_t *p;
2150
2151         vc = &ZAP_LEAF_CHUNK(zl, zc->l_entry.le_value_chunk);
2152         for (i = 0, value = 0, p = vc->l_array.la_array; i < 8; i++) {
2153                 value = (value << 8) | p[i];
2154         }
2155
2156         return value;
2157 }
2158
2159 static void
2160 stv(int len, void *addr, uint64_t value)
2161 {
2162         switch (len) {
2163         case 1:
2164                 *(uint8_t *)addr = value;
2165                 return;
2166         case 2:
2167                 *(uint16_t *)addr = value;
2168                 return;
2169         case 4:
2170                 *(uint32_t *)addr = value;
2171                 return;
2172         case 8:
2173                 *(uint64_t *)addr = value;
2174                 return;
2175         }
2176 }
2177
2178 /*
2179  * Extract a array from a zap leaf entry.
2180  */
2181 static void
2182 fzap_leaf_array(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc,
2183     uint64_t integer_size, uint64_t num_integers, void *buf)
2184 {
2185         uint64_t array_int_len = zc->l_entry.le_value_intlen;
2186         uint64_t value = 0;
2187         uint64_t *u64 = buf;
2188         char *p = buf;
2189         int len = MIN(zc->l_entry.le_value_numints, num_integers);
2190         int chunk = zc->l_entry.le_value_chunk;
2191         int byten = 0;
2192
2193         if (integer_size == 8 && len == 1) {
2194                 *u64 = fzap_leaf_value(zl, zc);
2195                 return;
2196         }
2197
2198         while (len > 0) {
2199                 struct zap_leaf_array *la = &ZAP_LEAF_CHUNK(zl, chunk).l_array;
2200                 int i;
2201
2202                 ASSERT3U(chunk, <, ZAP_LEAF_NUMCHUNKS(zl));
2203                 for (i = 0; i < ZAP_LEAF_ARRAY_BYTES && len > 0; i++) {
2204                         value = (value << 8) | la->la_array[i];
2205                         byten++;
2206                         if (byten == array_int_len) {
2207                                 stv(integer_size, p, value);
2208                                 byten = 0;
2209                                 len--;
2210                                 if (len == 0)
2211                                         return;
2212                                 p += integer_size;
2213                         }
2214                 }
2215                 chunk = la->la_next;
2216         }
2217 }
2218
2219 /*
2220  * Lookup a value in a fatzap directory. Assumes that the zap scratch
2221  * buffer contains the directory header.
2222  */
2223 static int
2224 fzap_lookup(const spa_t *spa, const dnode_phys_t *dnode, const char *name,
2225     uint64_t integer_size, uint64_t num_integers, void *value)
2226 {
2227         int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
2228         zap_phys_t zh = *(zap_phys_t *) zap_scratch;
2229         fat_zap_t z;
2230         uint64_t *ptrtbl;
2231         uint64_t hash;
2232         int rc;
2233
2234         if (zh.zap_magic != ZAP_MAGIC)
2235                 return (EIO);
2236
2237         z.zap_block_shift = ilog2(bsize);
2238         z.zap_phys = (zap_phys_t *) zap_scratch;
2239
2240         /*
2241          * Figure out where the pointer table is and read it in if necessary.
2242          */
2243         if (zh.zap_ptrtbl.zt_blk) {
2244                 rc = dnode_read(spa, dnode, zh.zap_ptrtbl.zt_blk * bsize,
2245                                zap_scratch, bsize);
2246                 if (rc)
2247                         return (rc);
2248                 ptrtbl = (uint64_t *) zap_scratch;
2249         } else {
2250                 ptrtbl = &ZAP_EMBEDDED_PTRTBL_ENT(&z, 0);
2251         }
2252
2253         hash = zap_hash(zh.zap_salt, name);
2254
2255         zap_leaf_t zl;
2256         zl.l_bs = z.zap_block_shift;
2257
2258         off_t off = ptrtbl[hash >> (64 - zh.zap_ptrtbl.zt_shift)] << zl.l_bs;
2259         zap_leaf_chunk_t *zc;
2260
2261         rc = dnode_read(spa, dnode, off, zap_scratch, bsize);
2262         if (rc)
2263                 return (rc);
2264
2265         zl.l_phys = (zap_leaf_phys_t *) zap_scratch;
2266
2267         /*
2268          * Make sure this chunk matches our hash.
2269          */
2270         if (zl.l_phys->l_hdr.lh_prefix_len > 0
2271             && zl.l_phys->l_hdr.lh_prefix
2272             != hash >> (64 - zl.l_phys->l_hdr.lh_prefix_len))
2273                 return (ENOENT);
2274
2275         /*
2276          * Hash within the chunk to find our entry.
2277          */
2278         int shift = (64 - ZAP_LEAF_HASH_SHIFT(&zl) - zl.l_phys->l_hdr.lh_prefix_len);
2279         int h = (hash >> shift) & ((1 << ZAP_LEAF_HASH_SHIFT(&zl)) - 1);
2280         h = zl.l_phys->l_hash[h];
2281         if (h == 0xffff)
2282                 return (ENOENT);
2283         zc = &ZAP_LEAF_CHUNK(&zl, h);
2284         while (zc->l_entry.le_hash != hash) {
2285                 if (zc->l_entry.le_next == 0xffff)
2286                         return (ENOENT);
2287                 zc = &ZAP_LEAF_CHUNK(&zl, zc->l_entry.le_next);
2288         }
2289         if (fzap_name_equal(&zl, zc, name)) {
2290                 if (zc->l_entry.le_value_intlen * zc->l_entry.le_value_numints >
2291                     integer_size * num_integers)
2292                         return (E2BIG);
2293                 fzap_leaf_array(&zl, zc, integer_size, num_integers, value);
2294                 return (0);
2295         }
2296
2297         return (ENOENT);
2298 }
2299
2300 /*
2301  * Lookup a name in a zap object and return its value as a uint64_t.
2302  */
2303 static int
2304 zap_lookup(const spa_t *spa, const dnode_phys_t *dnode, const char *name,
2305     uint64_t integer_size, uint64_t num_integers, void *value)
2306 {
2307         int rc;
2308         uint64_t zap_type;
2309         size_t size = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
2310
2311         rc = dnode_read(spa, dnode, 0, zap_scratch, size);
2312         if (rc)
2313                 return (rc);
2314
2315         zap_type = *(uint64_t *) zap_scratch;
2316         if (zap_type == ZBT_MICRO)
2317                 return mzap_lookup(dnode, name, value);
2318         else if (zap_type == ZBT_HEADER) {
2319                 return fzap_lookup(spa, dnode, name, integer_size,
2320                     num_integers, value);
2321         }
2322         printf("ZFS: invalid zap_type=%d\n", (int)zap_type);
2323         return (EIO);
2324 }
2325
2326 /*
2327  * List a microzap directory. Assumes that the zap scratch buffer contains
2328  * the directory contents.
2329  */
2330 static int
2331 mzap_list(const dnode_phys_t *dnode, int (*callback)(const char *, uint64_t))
2332 {
2333         const mzap_phys_t *mz;
2334         const mzap_ent_phys_t *mze;
2335         size_t size;
2336         int chunks, i, rc;
2337
2338         /*
2339          * Microzap objects use exactly one block. Read the whole
2340          * thing.
2341          */
2342         size = dnode->dn_datablkszsec * 512;
2343         mz = (const mzap_phys_t *) zap_scratch;
2344         chunks = size / MZAP_ENT_LEN - 1;
2345
2346         for (i = 0; i < chunks; i++) {
2347                 mze = &mz->mz_chunk[i];
2348                 if (mze->mze_name[0]) {
2349                         rc = callback(mze->mze_name, mze->mze_value);
2350                         if (rc != 0)
2351                                 return (rc);
2352                 }
2353         }
2354
2355         return (0);
2356 }
2357
2358 /*
2359  * List a fatzap directory. Assumes that the zap scratch buffer contains
2360  * the directory header.
2361  */
2362 static int
2363 fzap_list(const spa_t *spa, const dnode_phys_t *dnode, int (*callback)(const char *, uint64_t))
2364 {
2365         int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
2366         zap_phys_t zh = *(zap_phys_t *) zap_scratch;
2367         fat_zap_t z;
2368         int i, j, rc;
2369
2370         if (zh.zap_magic != ZAP_MAGIC)
2371                 return (EIO);
2372
2373         z.zap_block_shift = ilog2(bsize);
2374         z.zap_phys = (zap_phys_t *) zap_scratch;
2375
2376         /*
2377          * This assumes that the leaf blocks start at block 1. The
2378          * documentation isn't exactly clear on this.
2379          */
2380         zap_leaf_t zl;
2381         zl.l_bs = z.zap_block_shift;
2382         for (i = 0; i < zh.zap_num_leafs; i++) {
2383                 off_t off = (i + 1) << zl.l_bs;
2384                 char name[256], *p;
2385                 uint64_t value;
2386
2387                 if (dnode_read(spa, dnode, off, zap_scratch, bsize))
2388                         return (EIO);
2389
2390                 zl.l_phys = (zap_leaf_phys_t *) zap_scratch;
2391
2392                 for (j = 0; j < ZAP_LEAF_NUMCHUNKS(&zl); j++) {
2393                         zap_leaf_chunk_t *zc, *nc;
2394                         int namelen;
2395
2396                         zc = &ZAP_LEAF_CHUNK(&zl, j);
2397                         if (zc->l_entry.le_type != ZAP_CHUNK_ENTRY)
2398                                 continue;
2399                         namelen = zc->l_entry.le_name_numints;
2400                         if (namelen > sizeof(name))
2401                                 namelen = sizeof(name);
2402
2403                         /*
2404                          * Paste the name back together.
2405                          */
2406                         nc = &ZAP_LEAF_CHUNK(&zl, zc->l_entry.le_name_chunk);
2407                         p = name;
2408                         while (namelen > 0) {
2409                                 int len;
2410                                 len = namelen;
2411                                 if (len > ZAP_LEAF_ARRAY_BYTES)
2412                                         len = ZAP_LEAF_ARRAY_BYTES;
2413                                 memcpy(p, nc->l_array.la_array, len);
2414                                 p += len;
2415                                 namelen -= len;
2416                                 nc = &ZAP_LEAF_CHUNK(&zl, nc->l_array.la_next);
2417                         }
2418
2419                         /*
2420                          * Assume the first eight bytes of the value are
2421                          * a uint64_t.
2422                          */
2423                         value = fzap_leaf_value(&zl, zc);
2424
2425                         //printf("%s 0x%jx\n", name, (uintmax_t)value);
2426                         rc = callback((const char *)name, value);
2427                         if (rc != 0)
2428                                 return (rc);
2429                 }
2430         }
2431
2432         return (0);
2433 }
2434
2435 static int zfs_printf(const char *name, uint64_t value __unused)
2436 {
2437
2438         printf("%s\n", name);
2439
2440         return (0);
2441 }
2442
2443 /*
2444  * List a zap directory.
2445  */
2446 static int
2447 zap_list(const spa_t *spa, const dnode_phys_t *dnode)
2448 {
2449         uint64_t zap_type;
2450         size_t size = dnode->dn_datablkszsec * 512;
2451
2452         if (dnode_read(spa, dnode, 0, zap_scratch, size))
2453                 return (EIO);
2454
2455         zap_type = *(uint64_t *) zap_scratch;
2456         if (zap_type == ZBT_MICRO)
2457                 return mzap_list(dnode, zfs_printf);
2458         else
2459                 return fzap_list(spa, dnode, zfs_printf);
2460 }
2461
2462 static int
2463 objset_get_dnode(const spa_t *spa, const objset_phys_t *os, uint64_t objnum, dnode_phys_t *dnode)
2464 {
2465         off_t offset;
2466
2467         offset = objnum * sizeof(dnode_phys_t);
2468         return dnode_read(spa, &os->os_meta_dnode, offset,
2469                 dnode, sizeof(dnode_phys_t));
2470 }
2471
2472 static int
2473 mzap_rlookup(const spa_t *spa, const dnode_phys_t *dnode, char *name, uint64_t value)
2474 {
2475         const mzap_phys_t *mz;
2476         const mzap_ent_phys_t *mze;
2477         size_t size;
2478         int chunks, i;
2479
2480         /*
2481          * Microzap objects use exactly one block. Read the whole
2482          * thing.
2483          */
2484         size = dnode->dn_datablkszsec * 512;
2485
2486         mz = (const mzap_phys_t *) zap_scratch;
2487         chunks = size / MZAP_ENT_LEN - 1;
2488
2489         for (i = 0; i < chunks; i++) {
2490                 mze = &mz->mz_chunk[i];
2491                 if (value == mze->mze_value) {
2492                         strcpy(name, mze->mze_name);
2493                         return (0);
2494                 }
2495         }
2496
2497         return (ENOENT);
2498 }
2499
2500 static void
2501 fzap_name_copy(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc, char *name)
2502 {
2503         size_t namelen;
2504         const zap_leaf_chunk_t *nc;
2505         char *p;
2506
2507         namelen = zc->l_entry.le_name_numints;
2508
2509         nc = &ZAP_LEAF_CHUNK(zl, zc->l_entry.le_name_chunk);
2510         p = name;
2511         while (namelen > 0) {
2512                 size_t len;
2513                 len = namelen;
2514                 if (len > ZAP_LEAF_ARRAY_BYTES)
2515                         len = ZAP_LEAF_ARRAY_BYTES;
2516                 memcpy(p, nc->l_array.la_array, len);
2517                 p += len;
2518                 namelen -= len;
2519                 nc = &ZAP_LEAF_CHUNK(zl, nc->l_array.la_next);
2520         }
2521
2522         *p = '\0';
2523 }
2524
2525 static int
2526 fzap_rlookup(const spa_t *spa, const dnode_phys_t *dnode, char *name, uint64_t value)
2527 {
2528         int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
2529         zap_phys_t zh = *(zap_phys_t *) zap_scratch;
2530         fat_zap_t z;
2531         int i, j;
2532
2533         if (zh.zap_magic != ZAP_MAGIC)
2534                 return (EIO);
2535
2536         z.zap_block_shift = ilog2(bsize);
2537         z.zap_phys = (zap_phys_t *) zap_scratch;
2538
2539         /*
2540          * This assumes that the leaf blocks start at block 1. The
2541          * documentation isn't exactly clear on this.
2542          */
2543         zap_leaf_t zl;
2544         zl.l_bs = z.zap_block_shift;
2545         for (i = 0; i < zh.zap_num_leafs; i++) {
2546                 off_t off = (i + 1) << zl.l_bs;
2547
2548                 if (dnode_read(spa, dnode, off, zap_scratch, bsize))
2549                         return (EIO);
2550
2551                 zl.l_phys = (zap_leaf_phys_t *) zap_scratch;
2552
2553                 for (j = 0; j < ZAP_LEAF_NUMCHUNKS(&zl); j++) {
2554                         zap_leaf_chunk_t *zc;
2555
2556                         zc = &ZAP_LEAF_CHUNK(&zl, j);
2557                         if (zc->l_entry.le_type != ZAP_CHUNK_ENTRY)
2558                                 continue;
2559                         if (zc->l_entry.le_value_intlen != 8 ||
2560                             zc->l_entry.le_value_numints != 1)
2561                                 continue;
2562
2563                         if (fzap_leaf_value(&zl, zc) == value) {
2564                                 fzap_name_copy(&zl, zc, name);
2565                                 return (0);
2566                         }
2567                 }
2568         }
2569
2570         return (ENOENT);
2571 }
2572
2573 static int
2574 zap_rlookup(const spa_t *spa, const dnode_phys_t *dnode, char *name, uint64_t value)
2575 {
2576         int rc;
2577         uint64_t zap_type;
2578         size_t size = dnode->dn_datablkszsec * 512;
2579
2580         rc = dnode_read(spa, dnode, 0, zap_scratch, size);
2581         if (rc)
2582                 return (rc);
2583
2584         zap_type = *(uint64_t *) zap_scratch;
2585         if (zap_type == ZBT_MICRO)
2586                 return mzap_rlookup(spa, dnode, name, value);
2587         else
2588                 return fzap_rlookup(spa, dnode, name, value);
2589 }
2590
2591 static int
2592 zfs_rlookup(const spa_t *spa, uint64_t objnum, char *result)
2593 {
2594         char name[256];
2595         char component[256];
2596         uint64_t dir_obj, parent_obj, child_dir_zapobj;
2597         dnode_phys_t child_dir_zap, dataset, dir, parent;
2598         dsl_dir_phys_t *dd;
2599         dsl_dataset_phys_t *ds;
2600         char *p;
2601         int len;
2602
2603         p = &name[sizeof(name) - 1];
2604         *p = '\0';
2605
2606         if (objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset)) {
2607                 printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
2608                 return (EIO);
2609         }
2610         ds = (dsl_dataset_phys_t *)&dataset.dn_bonus;
2611         dir_obj = ds->ds_dir_obj;
2612
2613         for (;;) {
2614                 if (objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir) != 0)
2615                         return (EIO);
2616                 dd = (dsl_dir_phys_t *)&dir.dn_bonus;
2617
2618                 /* Actual loop condition. */
2619                 parent_obj  = dd->dd_parent_obj;
2620                 if (parent_obj == 0)
2621                         break;
2622
2623                 if (objset_get_dnode(spa, &spa->spa_mos, parent_obj, &parent) != 0)
2624                         return (EIO);
2625                 dd = (dsl_dir_phys_t *)&parent.dn_bonus;
2626                 child_dir_zapobj = dd->dd_child_dir_zapobj;
2627                 if (objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj, &child_dir_zap) != 0)
2628                         return (EIO);
2629                 if (zap_rlookup(spa, &child_dir_zap, component, dir_obj) != 0)
2630                         return (EIO);
2631
2632                 len = strlen(component);
2633                 p -= len;
2634                 memcpy(p, component, len);
2635                 --p;
2636                 *p = '/';
2637
2638                 /* Actual loop iteration. */
2639                 dir_obj = parent_obj;
2640         }
2641
2642         if (*p != '\0')
2643                 ++p;
2644         strcpy(result, p);
2645
2646         return (0);
2647 }
2648
2649 static int
2650 zfs_lookup_dataset(const spa_t *spa, const char *name, uint64_t *objnum)
2651 {
2652         char element[256];
2653         uint64_t dir_obj, child_dir_zapobj;
2654         dnode_phys_t child_dir_zap, dir;
2655         dsl_dir_phys_t *dd;
2656         const char *p, *q;
2657
2658         if (objset_get_dnode(spa, &spa->spa_mos, DMU_POOL_DIRECTORY_OBJECT, &dir))
2659                 return (EIO);
2660         if (zap_lookup(spa, &dir, DMU_POOL_ROOT_DATASET, sizeof (dir_obj),
2661             1, &dir_obj))
2662                 return (EIO);
2663
2664         p = name;
2665         for (;;) {
2666                 if (objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir))
2667                         return (EIO);
2668                 dd = (dsl_dir_phys_t *)&dir.dn_bonus;
2669
2670                 while (*p == '/')
2671                         p++;
2672                 /* Actual loop condition #1. */
2673                 if (*p == '\0')
2674                         break;
2675
2676                 q = strchr(p, '/');
2677                 if (q) {
2678                         memcpy(element, p, q - p);
2679                         element[q - p] = '\0';
2680                         p = q + 1;
2681                 } else {
2682                         strcpy(element, p);
2683                         p += strlen(p);
2684                 }
2685
2686                 child_dir_zapobj = dd->dd_child_dir_zapobj;
2687                 if (objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj, &child_dir_zap) != 0)
2688                         return (EIO);
2689
2690                 /* Actual loop condition #2. */
2691                 if (zap_lookup(spa, &child_dir_zap, element, sizeof (dir_obj),
2692                     1, &dir_obj) != 0)
2693                         return (ENOENT);
2694         }
2695
2696         *objnum = dd->dd_head_dataset_obj;
2697         return (0);
2698 }
2699
2700 #ifndef BOOT2
2701 static int
2702 zfs_list_dataset(const spa_t *spa, uint64_t objnum/*, int pos, char *entry*/)
2703 {
2704         uint64_t dir_obj, child_dir_zapobj;
2705         dnode_phys_t child_dir_zap, dir, dataset;
2706         dsl_dataset_phys_t *ds;
2707         dsl_dir_phys_t *dd;
2708
2709         if (objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset)) {
2710                 printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
2711                 return (EIO);
2712         }
2713         ds = (dsl_dataset_phys_t *) &dataset.dn_bonus;
2714         dir_obj = ds->ds_dir_obj;
2715
2716         if (objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir)) {
2717                 printf("ZFS: can't find dirobj %ju\n", (uintmax_t)dir_obj);
2718                 return (EIO);
2719         }
2720         dd = (dsl_dir_phys_t *)&dir.dn_bonus;
2721
2722         child_dir_zapobj = dd->dd_child_dir_zapobj;
2723         if (objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj, &child_dir_zap) != 0) {
2724                 printf("ZFS: can't find child zap %ju\n", (uintmax_t)dir_obj);
2725                 return (EIO);
2726         }
2727
2728         return (zap_list(spa, &child_dir_zap) != 0);
2729 }
2730
2731 int
2732 zfs_callback_dataset(const spa_t *spa, uint64_t objnum, int (*callback)(const char *, uint64_t))
2733 {
2734         uint64_t dir_obj, child_dir_zapobj, zap_type;
2735         dnode_phys_t child_dir_zap, dir, dataset;
2736         dsl_dataset_phys_t *ds;
2737         dsl_dir_phys_t *dd;
2738         int err;
2739
2740         err = objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset);
2741         if (err != 0) {
2742                 printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
2743                 return (err);
2744         }
2745         ds = (dsl_dataset_phys_t *) &dataset.dn_bonus;
2746         dir_obj = ds->ds_dir_obj;
2747
2748         err = objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir);
2749         if (err != 0) {
2750                 printf("ZFS: can't find dirobj %ju\n", (uintmax_t)dir_obj);
2751                 return (err);
2752         }
2753         dd = (dsl_dir_phys_t *)&dir.dn_bonus;
2754
2755         child_dir_zapobj = dd->dd_child_dir_zapobj;
2756         err = objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj, &child_dir_zap);
2757         if (err != 0) {
2758                 printf("ZFS: can't find child zap %ju\n", (uintmax_t)dir_obj);
2759                 return (err);
2760         }
2761
2762         err = dnode_read(spa, &child_dir_zap, 0, zap_scratch, child_dir_zap.dn_datablkszsec * 512);
2763         if (err != 0)
2764                 return (err);
2765
2766         zap_type = *(uint64_t *) zap_scratch;
2767         if (zap_type == ZBT_MICRO)
2768                 return mzap_list(&child_dir_zap, callback);
2769         else
2770                 return fzap_list(spa, &child_dir_zap, callback);
2771 }
2772 #endif
2773
2774 /*
2775  * Find the object set given the object number of its dataset object
2776  * and return its details in *objset
2777  */
2778 static int
2779 zfs_mount_dataset(const spa_t *spa, uint64_t objnum, objset_phys_t *objset)
2780 {
2781         dnode_phys_t dataset;
2782         dsl_dataset_phys_t *ds;
2783
2784         if (objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset)) {
2785                 printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
2786                 return (EIO);
2787         }
2788
2789         ds = (dsl_dataset_phys_t *) &dataset.dn_bonus;
2790         if (zio_read(spa, &ds->ds_bp, objset)) {
2791                 printf("ZFS: can't read object set for dataset %ju\n",
2792                     (uintmax_t)objnum);
2793                 return (EIO);
2794         }
2795
2796         return (0);
2797 }
2798
2799 /*
2800  * Find the object set pointed to by the BOOTFS property or the root
2801  * dataset if there is none and return its details in *objset
2802  */
2803 static int
2804 zfs_get_root(const spa_t *spa, uint64_t *objid)
2805 {
2806         dnode_phys_t dir, propdir;
2807         uint64_t props, bootfs, root;
2808
2809         *objid = 0;
2810
2811         /*
2812          * Start with the MOS directory object.
2813          */
2814         if (objset_get_dnode(spa, &spa->spa_mos, DMU_POOL_DIRECTORY_OBJECT, &dir)) {
2815                 printf("ZFS: can't read MOS object directory\n");
2816                 return (EIO);
2817         }
2818
2819         /*
2820          * Lookup the pool_props and see if we can find a bootfs.
2821          */
2822         if (zap_lookup(spa, &dir, DMU_POOL_PROPS, sizeof (props), 1, &props) == 0
2823              && objset_get_dnode(spa, &spa->spa_mos, props, &propdir) == 0
2824              && zap_lookup(spa, &propdir, "bootfs", sizeof (bootfs), 1, &bootfs) == 0
2825              && bootfs != 0)
2826         {
2827                 *objid = bootfs;
2828                 return (0);
2829         }
2830         /*
2831          * Lookup the root dataset directory
2832          */
2833         if (zap_lookup(spa, &dir, DMU_POOL_ROOT_DATASET, sizeof (root), 1, &root)
2834             || objset_get_dnode(spa, &spa->spa_mos, root, &dir)) {
2835                 printf("ZFS: can't find root dsl_dir\n");
2836                 return (EIO);
2837         }
2838
2839         /*
2840          * Use the information from the dataset directory's bonus buffer
2841          * to find the dataset object and from that the object set itself.
2842          */
2843         dsl_dir_phys_t *dd = (dsl_dir_phys_t *) &dir.dn_bonus;
2844         *objid = dd->dd_head_dataset_obj;
2845         return (0);
2846 }
2847
2848 static int
2849 zfs_mount(const spa_t *spa, uint64_t rootobj, struct zfsmount *mount)
2850 {
2851
2852         mount->spa = spa;
2853
2854         /*
2855          * Find the root object set if not explicitly provided
2856          */
2857         if (rootobj == 0 && zfs_get_root(spa, &rootobj)) {
2858                 printf("ZFS: can't find root filesystem\n");
2859                 return (EIO);
2860         }
2861
2862         if (zfs_mount_dataset(spa, rootobj, &mount->objset)) {
2863                 printf("ZFS: can't open root filesystem\n");
2864                 return (EIO);
2865         }
2866
2867         mount->rootobj = rootobj;
2868
2869         return (0);
2870 }
2871
2872 /*
2873  * callback function for feature name checks.
2874  */
2875 static int
2876 check_feature(const char *name, uint64_t value)
2877 {
2878         int i;
2879
2880         if (value == 0)
2881                 return (0);
2882         if (name[0] == '\0')
2883                 return (0);
2884
2885         for (i = 0; features_for_read[i] != NULL; i++) {
2886                 if (strcmp(name, features_for_read[i]) == 0)
2887                         return (0);
2888         }
2889         printf("ZFS: unsupported feature: %s\n", name);
2890         return (EIO);
2891 }
2892
2893 /*
2894  * Checks whether the MOS features that are active are supported.
2895  */
2896 static int
2897 check_mos_features(const spa_t *spa)
2898 {
2899         dnode_phys_t dir;
2900         uint64_t objnum, zap_type;
2901         size_t size;
2902         int rc;
2903
2904         if ((rc = objset_get_dnode(spa, &spa->spa_mos, DMU_OT_OBJECT_DIRECTORY,
2905             &dir)) != 0)
2906                 return (rc);
2907         if ((rc = zap_lookup(spa, &dir, DMU_POOL_FEATURES_FOR_READ,
2908             sizeof (objnum), 1, &objnum)) != 0) {
2909                 /*
2910                  * It is older pool without features. As we have already
2911                  * tested the label, just return without raising the error.
2912                  */
2913                 return (0);
2914         }
2915
2916         if ((rc = objset_get_dnode(spa, &spa->spa_mos, objnum, &dir)) != 0)
2917                 return (rc);
2918
2919         if (dir.dn_type != DMU_OTN_ZAP_METADATA)
2920                 return (EIO);
2921
2922         size = dir.dn_datablkszsec * 512;
2923         if (dnode_read(spa, &dir, 0, zap_scratch, size))
2924                 return (EIO);
2925
2926         zap_type = *(uint64_t *) zap_scratch;
2927         if (zap_type == ZBT_MICRO)
2928                 rc = mzap_list(&dir, check_feature);
2929         else
2930                 rc = fzap_list(spa, &dir, check_feature);
2931
2932         return (rc);
2933 }
2934
2935 static int
2936 load_nvlist(spa_t *spa, uint64_t obj, unsigned char **value)
2937 {
2938         dnode_phys_t dir;
2939         size_t size;
2940         int rc;
2941         unsigned char *nv;
2942
2943         *value = NULL;
2944         if ((rc = objset_get_dnode(spa, &spa->spa_mos, obj, &dir)) != 0)
2945                 return (rc);
2946         if (dir.dn_type != DMU_OT_PACKED_NVLIST &&
2947             dir.dn_bonustype != DMU_OT_PACKED_NVLIST_SIZE) {
2948                 return (EIO);
2949         }
2950
2951         if (dir.dn_bonuslen != sizeof (uint64_t))
2952                 return (EIO);
2953
2954         size = *(uint64_t *)DN_BONUS(&dir);
2955         nv = malloc(size);
2956         if (nv == NULL)
2957                 return (ENOMEM);
2958
2959         rc = dnode_read(spa, &dir, 0, nv, size);
2960         if (rc != 0) {
2961                 free(nv);
2962                 nv = NULL;
2963                 return (rc);
2964         }
2965         *value = nv;
2966         return (rc);
2967 }
2968
2969 static int
2970 zfs_spa_init(spa_t *spa)
2971 {
2972         dnode_phys_t dir;
2973         uint64_t config_object;
2974         unsigned char *nvlist;
2975         char *type;
2976         const unsigned char *nv;
2977         int nkids, rc;
2978
2979         if (zio_read(spa, &spa->spa_uberblock.ub_rootbp, &spa->spa_mos)) {
2980                 printf("ZFS: can't read MOS of pool %s\n", spa->spa_name);
2981                 return (EIO);
2982         }
2983         if (spa->spa_mos.os_type != DMU_OST_META) {
2984                 printf("ZFS: corrupted MOS of pool %s\n", spa->spa_name);
2985                 return (EIO);
2986         }
2987
2988         if (objset_get_dnode(spa, &spa->spa_mos, DMU_POOL_DIRECTORY_OBJECT,
2989             &dir)) {
2990                 printf("ZFS: failed to read pool %s directory object\n",
2991                     spa->spa_name);
2992                 return (EIO);
2993         }
2994         /* this is allowed to fail, older pools do not have salt */
2995         rc = zap_lookup(spa, &dir, DMU_POOL_CHECKSUM_SALT, 1,
2996             sizeof (spa->spa_cksum_salt.zcs_bytes),
2997             spa->spa_cksum_salt.zcs_bytes);
2998
2999         rc = check_mos_features(spa);
3000         if (rc != 0) {
3001                 printf("ZFS: pool %s is not supported\n", spa->spa_name);
3002                 return (rc);
3003         }
3004
3005         rc = zap_lookup(spa, &dir, DMU_POOL_CONFIG,
3006             sizeof (config_object), 1, &config_object);
3007         if (rc != 0) {
3008                 printf("ZFS: can not read MOS %s\n", DMU_POOL_CONFIG);
3009                 return (EIO);
3010         }
3011         rc = load_nvlist(spa, config_object, &nvlist);
3012         if (rc != 0)
3013                 return (rc);
3014
3015         /* Update vdevs from MOS config. */
3016         if (nvlist_find(nvlist + 4, ZPOOL_CONFIG_VDEV_TREE, DATA_TYPE_NVLIST,
3017             NULL, &nv)) {
3018                 rc = EIO;
3019                 goto done;
3020         }
3021
3022         if (nvlist_find(nv, ZPOOL_CONFIG_TYPE, DATA_TYPE_STRING,
3023             NULL, &type)) {
3024                 printf("ZFS: can't find vdev details\n");
3025                 rc = ENOENT;
3026                 goto done;
3027         }
3028         if (strcmp(type, VDEV_TYPE_ROOT) != 0) {
3029                 rc = ENOENT;
3030                 goto done;
3031         }
3032
3033         rc = nvlist_find(nv, ZPOOL_CONFIG_CHILDREN, DATA_TYPE_NVLIST_ARRAY,
3034             &nkids, &nv);
3035         if (rc != 0)
3036                 goto done;
3037
3038         for (int i = 0; i < nkids; i++) {
3039                 vdev_t *vd, *prev, *kid = NULL;
3040                 rc = vdev_init_from_nvlist(nv, NULL, &kid, 0);
3041                 if (rc != 0) {
3042                         printf("vdev_init_from_nvlist: %d\n", rc);
3043                         break;
3044                 }
3045                 kid->spa = spa;
3046                 prev = NULL;
3047                 STAILQ_FOREACH(vd, &spa->spa_vdevs, v_childlink) {
3048                         /* Already present? */
3049                         if (kid->v_id == vd->v_id) {
3050                                 kid = NULL;
3051                                 break;
3052                         }
3053                         if (vd->v_id > kid->v_id) {
3054                                 if (prev == NULL) {
3055                                         STAILQ_INSERT_HEAD(&spa->spa_vdevs,
3056                                             kid, v_childlink);
3057                                 } else {
3058                                         STAILQ_INSERT_AFTER(&spa->spa_vdevs,
3059                                             prev, kid, v_childlink);
3060                                 }
3061                                 kid = NULL;
3062                                 break;
3063                         }
3064                         prev = vd;
3065                 }
3066                 if (kid != NULL)
3067                         STAILQ_INSERT_TAIL(&spa->spa_vdevs, kid, v_childlink);
3068                 nv = nvlist_next(nv);
3069         }
3070         rc = 0;
3071 done:
3072         free(nvlist);
3073         return (rc);
3074 }
3075
3076 static int
3077 zfs_dnode_stat(const spa_t *spa, dnode_phys_t *dn, struct stat *sb)
3078 {
3079
3080         if (dn->dn_bonustype != DMU_OT_SA) {
3081                 znode_phys_t *zp = (znode_phys_t *)dn->dn_bonus;
3082
3083                 sb->st_mode = zp->zp_mode;
3084                 sb->st_uid = zp->zp_uid;
3085                 sb->st_gid = zp->zp_gid;
3086                 sb->st_size = zp->zp_size;
3087         } else {
3088                 sa_hdr_phys_t *sahdrp;
3089                 int hdrsize;
3090                 size_t size = 0;
3091                 void *buf = NULL;
3092
3093                 if (dn->dn_bonuslen != 0)
3094                         sahdrp = (sa_hdr_phys_t *)DN_BONUS(dn);
3095                 else {
3096                         if ((dn->dn_flags & DNODE_FLAG_SPILL_BLKPTR) != 0) {
3097                                 blkptr_t *bp = DN_SPILL_BLKPTR(dn);
3098                                 int error;
3099
3100                                 size = BP_GET_LSIZE(bp);
3101                                 buf = zfs_alloc(size);
3102                                 error = zio_read(spa, bp, buf);
3103                                 if (error != 0) {
3104                                         zfs_free(buf, size);
3105                                         return (error);
3106                                 }
3107                                 sahdrp = buf;
3108                         } else {
3109                                 return (EIO);
3110                         }
3111                 }
3112                 hdrsize = SA_HDR_SIZE(sahdrp);
3113                 sb->st_mode = *(uint64_t *)((char *)sahdrp + hdrsize +
3114                     SA_MODE_OFFSET);
3115                 sb->st_uid = *(uint64_t *)((char *)sahdrp + hdrsize +
3116                     SA_UID_OFFSET);
3117                 sb->st_gid = *(uint64_t *)((char *)sahdrp + hdrsize +
3118                     SA_GID_OFFSET);
3119                 sb->st_size = *(uint64_t *)((char *)sahdrp + hdrsize +
3120                     SA_SIZE_OFFSET);
3121                 if (buf != NULL)
3122                         zfs_free(buf, size);
3123         }
3124
3125         return (0);
3126 }
3127
3128 static int
3129 zfs_dnode_readlink(const spa_t *spa, dnode_phys_t *dn, char *path, size_t psize)
3130 {
3131         int rc = 0;
3132
3133         if (dn->dn_bonustype == DMU_OT_SA) {
3134                 sa_hdr_phys_t *sahdrp = NULL;
3135                 size_t size = 0;
3136                 void *buf = NULL;
3137                 int hdrsize;
3138                 char *p;
3139
3140                 if (dn->dn_bonuslen != 0)
3141                         sahdrp = (sa_hdr_phys_t *)DN_BONUS(dn);
3142                 else {
3143                         blkptr_t *bp;
3144
3145                         if ((dn->dn_flags & DNODE_FLAG_SPILL_BLKPTR) == 0)
3146                                 return (EIO);
3147                         bp = DN_SPILL_BLKPTR(dn);
3148
3149                         size = BP_GET_LSIZE(bp);
3150                         buf = zfs_alloc(size);
3151                         rc = zio_read(spa, bp, buf);
3152                         if (rc != 0) {
3153                                 zfs_free(buf, size);
3154                                 return (rc);
3155                         }
3156                         sahdrp = buf;
3157                 }
3158                 hdrsize = SA_HDR_SIZE(sahdrp);
3159                 p = (char *)((uintptr_t)sahdrp + hdrsize + SA_SYMLINK_OFFSET);
3160                 memcpy(path, p, psize);
3161                 if (buf != NULL)
3162                         zfs_free(buf, size);
3163                 return (0);
3164         }
3165         /*
3166          * Second test is purely to silence bogus compiler
3167          * warning about accessing past the end of dn_bonus.
3168          */
3169         if (psize + sizeof(znode_phys_t) <= dn->dn_bonuslen &&
3170             sizeof(znode_phys_t) <= sizeof(dn->dn_bonus)) {
3171                 memcpy(path, &dn->dn_bonus[sizeof(znode_phys_t)], psize);
3172         } else {
3173                 rc = dnode_read(spa, dn, 0, path, psize);
3174         }
3175         return (rc);
3176 }
3177
3178 struct obj_list {
3179         uint64_t                objnum;
3180         STAILQ_ENTRY(obj_list)  entry;
3181 };
3182
3183 /*
3184  * Lookup a file and return its dnode.
3185  */
3186 static int
3187 zfs_lookup(const struct zfsmount *mount, const char *upath, dnode_phys_t *dnode)
3188 {
3189         int rc;
3190         uint64_t objnum;
3191         const spa_t *spa;
3192         dnode_phys_t dn;
3193         const char *p, *q;
3194         char element[256];
3195         char path[1024];
3196         int symlinks_followed = 0;
3197         struct stat sb;
3198         struct obj_list *entry, *tentry;
3199         STAILQ_HEAD(, obj_list) on_cache = STAILQ_HEAD_INITIALIZER(on_cache);
3200
3201         spa = mount->spa;
3202         if (mount->objset.os_type != DMU_OST_ZFS) {
3203                 printf("ZFS: unexpected object set type %ju\n",
3204                     (uintmax_t)mount->objset.os_type);
3205                 return (EIO);
3206         }
3207
3208         if ((entry = malloc(sizeof(struct obj_list))) == NULL)
3209                 return (ENOMEM);
3210
3211         /*
3212          * Get the root directory dnode.
3213          */
3214         rc = objset_get_dnode(spa, &mount->objset, MASTER_NODE_OBJ, &dn);
3215         if (rc) {
3216                 free(entry);
3217                 return (rc);
3218         }
3219
3220         rc = zap_lookup(spa, &dn, ZFS_ROOT_OBJ, sizeof (objnum), 1, &objnum);
3221         if (rc) {
3222                 free(entry);
3223                 return (rc);
3224         }
3225         entry->objnum = objnum;
3226         STAILQ_INSERT_HEAD(&on_cache, entry, entry);
3227
3228         rc = objset_get_dnode(spa, &mount->objset, objnum, &dn);
3229         if (rc != 0)
3230                 goto done;
3231
3232         p = upath;
3233         while (p && *p) {
3234                 rc = objset_get_dnode(spa, &mount->objset, objnum, &dn);
3235                 if (rc != 0)
3236                         goto done;
3237
3238                 while (*p == '/')
3239                         p++;
3240                 if (*p == '\0')
3241                         break;
3242                 q = p;
3243                 while (*q != '\0' && *q != '/')
3244                         q++;
3245
3246                 /* skip dot */
3247                 if (p + 1 == q && p[0] == '.') {
3248                         p++;
3249                         continue;
3250                 }
3251                 /* double dot */
3252                 if (p + 2 == q && p[0] == '.' && p[1] == '.') {
3253                         p += 2;
3254                         if (STAILQ_FIRST(&on_cache) ==
3255                             STAILQ_LAST(&on_cache, obj_list, entry)) {
3256                                 rc = ENOENT;
3257                                 goto done;
3258                         }
3259                         entry = STAILQ_FIRST(&on_cache);
3260                         STAILQ_REMOVE_HEAD(&on_cache, entry);
3261                         free(entry);
3262                         objnum = (STAILQ_FIRST(&on_cache))->objnum;
3263                         continue;
3264                 }
3265                 if (q - p + 1 > sizeof(element)) {
3266                         rc = ENAMETOOLONG;
3267                         goto done;
3268                 }
3269                 memcpy(element, p, q - p);
3270                 element[q - p] = 0;
3271                 p = q;
3272
3273                 if ((rc = zfs_dnode_stat(spa, &dn, &sb)) != 0)
3274                         goto done;
3275                 if (!S_ISDIR(sb.st_mode)) {
3276                         rc = ENOTDIR;
3277                         goto done;
3278                 }
3279
3280                 rc = zap_lookup(spa, &dn, element, sizeof (objnum), 1, &objnum);
3281                 if (rc)
3282                         goto done;
3283                 objnum = ZFS_DIRENT_OBJ(objnum);
3284
3285                 if ((entry = malloc(sizeof(struct obj_list))) == NULL) {
3286                         rc = ENOMEM;
3287                         goto done;
3288                 }
3289                 entry->objnum = objnum;
3290                 STAILQ_INSERT_HEAD(&on_cache, entry, entry);
3291                 rc = objset_get_dnode(spa, &mount->objset, objnum, &dn);
3292                 if (rc)
3293                         goto done;
3294
3295                 /*
3296                  * Check for symlink.
3297                  */
3298                 rc = zfs_dnode_stat(spa, &dn, &sb);
3299                 if (rc)
3300                         goto done;
3301                 if (S_ISLNK(sb.st_mode)) {
3302                         if (symlinks_followed > 10) {
3303                                 rc = EMLINK;
3304                                 goto done;
3305                         }
3306                         symlinks_followed++;
3307
3308                         /*
3309                          * Read the link value and copy the tail of our
3310                          * current path onto the end.
3311                          */
3312                         if (sb.st_size + strlen(p) + 1 > sizeof(path)) {
3313                                 rc = ENAMETOOLONG;
3314                                 goto done;
3315                         }
3316                         strcpy(&path[sb.st_size], p);
3317
3318                         rc = zfs_dnode_readlink(spa, &dn, path, sb.st_size);
3319                         if (rc != 0)
3320                                 goto done;
3321
3322                         /*
3323                          * Restart with the new path, starting either at
3324                          * the root or at the parent depending whether or
3325                          * not the link is relative.
3326                          */
3327                         p = path;
3328                         if (*p == '/') {
3329                                 while (STAILQ_FIRST(&on_cache) !=
3330                                     STAILQ_LAST(&on_cache, obj_list, entry)) {
3331                                         entry = STAILQ_FIRST(&on_cache);
3332                                         STAILQ_REMOVE_HEAD(&on_cache, entry);
3333                                         free(entry);
3334                                 }
3335                         } else {
3336                                 entry = STAILQ_FIRST(&on_cache);
3337                                 STAILQ_REMOVE_HEAD(&on_cache, entry);
3338                                 free(entry);
3339                         }
3340                         objnum = (STAILQ_FIRST(&on_cache))->objnum;
3341                 }
3342         }
3343
3344         *dnode = dn;
3345 done:
3346         STAILQ_FOREACH_SAFE(entry, &on_cache, entry, tentry)
3347                 free(entry);
3348         return (rc);
3349 }