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