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