]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/boot/zfs/zfsimpl.c
MFC Loader Fixes 2017q2: r316437,r316577,r316578,r316585,r316590,r316612,
[FreeBSD/FreeBSD.git] / sys / boot / 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/stat.h>
35 #include <sys/stdint.h>
36
37 #include "zfsimpl.h"
38 #include "zfssubr.c"
39
40
41 struct zfsmount {
42         const spa_t     *spa;
43         objset_phys_t   objset;
44         uint64_t        rootobj;
45 };
46
47 /*
48  * List of all vdevs, chained through v_alllink.
49  */
50 static vdev_list_t zfs_vdevs;
51
52  /*
53  * List of ZFS features supported for read
54  */
55 static const char *features_for_read[] = {
56         "org.illumos:lz4_compress",
57         "com.delphix:hole_birth",
58         "com.delphix:extensible_dataset",
59         "com.delphix:embedded_data",
60         "org.open-zfs:large_blocks",
61         "org.illumos:sha512",
62         "org.illumos:skein",
63         NULL
64 };
65
66 /*
67  * List of all pools, chained through spa_link.
68  */
69 static spa_list_t zfs_pools;
70
71 static const dnode_phys_t *dnode_cache_obj;
72 static uint64_t dnode_cache_bn;
73 static char *dnode_cache_buf;
74 static char *zap_scratch;
75 static char *zfs_temp_buf, *zfs_temp_end, *zfs_temp_ptr;
76
77 #define TEMP_SIZE       (1024 * 1024)
78
79 static int zio_read(const spa_t *spa, const blkptr_t *bp, void *buf);
80 static int zfs_get_root(const spa_t *spa, uint64_t *objid);
81 static int zfs_rlookup(const spa_t *spa, uint64_t objnum, char *result);
82 static int zap_lookup(const spa_t *spa, const dnode_phys_t *dnode,
83     const char *name, uint64_t integer_size, uint64_t num_integers,
84     void *value);
85
86 static void
87 zfs_init(void)
88 {
89         STAILQ_INIT(&zfs_vdevs);
90         STAILQ_INIT(&zfs_pools);
91
92         zfs_temp_buf = malloc(TEMP_SIZE);
93         zfs_temp_end = zfs_temp_buf + TEMP_SIZE;
94         zfs_temp_ptr = zfs_temp_buf;
95         dnode_cache_buf = malloc(SPA_MAXBLOCKSIZE);
96         zap_scratch = malloc(SPA_MAXBLOCKSIZE);
97
98         zfs_init_crc();
99 }
100
101 static void *
102 zfs_alloc(size_t size)
103 {
104         char *ptr;
105
106         if (zfs_temp_ptr + size > zfs_temp_end) {
107                 printf("ZFS: out of temporary buffer space\n");
108                 for (;;) ;
109         }
110         ptr = zfs_temp_ptr;
111         zfs_temp_ptr += size;
112
113         return (ptr);
114 }
115
116 static void
117 zfs_free(void *ptr, size_t size)
118 {
119
120         zfs_temp_ptr -= size;
121         if (zfs_temp_ptr != ptr) {
122                 printf("ZFS: zfs_alloc()/zfs_free() mismatch\n");
123                 for (;;) ;
124         }
125 }
126
127 static int
128 xdr_int(const unsigned char **xdr, int *ip)
129 {
130         *ip = ((*xdr)[0] << 24)
131                 | ((*xdr)[1] << 16)
132                 | ((*xdr)[2] << 8)
133                 | ((*xdr)[3] << 0);
134         (*xdr) += 4;
135         return (0);
136 }
137
138 static int
139 xdr_u_int(const unsigned char **xdr, u_int *ip)
140 {
141         *ip = ((*xdr)[0] << 24)
142                 | ((*xdr)[1] << 16)
143                 | ((*xdr)[2] << 8)
144                 | ((*xdr)[3] << 0);
145         (*xdr) += 4;
146         return (0);
147 }
148
149 static int
150 xdr_uint64_t(const unsigned char **xdr, uint64_t *lp)
151 {
152         u_int hi, lo;
153
154         xdr_u_int(xdr, &hi);
155         xdr_u_int(xdr, &lo);
156         *lp = (((uint64_t) hi) << 32) | lo;
157         return (0);
158 }
159
160 static int
161 nvlist_find(const unsigned char *nvlist, const char *name, int type,
162             int* elementsp, void *valuep)
163 {
164         const unsigned char *p, *pair;
165         int junk;
166         int encoded_size, decoded_size;
167
168         p = nvlist;
169         xdr_int(&p, &junk);
170         xdr_int(&p, &junk);
171
172         pair = p;
173         xdr_int(&p, &encoded_size);
174         xdr_int(&p, &decoded_size);
175         while (encoded_size && decoded_size) {
176                 int namelen, pairtype, elements;
177                 const char *pairname;
178
179                 xdr_int(&p, &namelen);
180                 pairname = (const char*) p;
181                 p += roundup(namelen, 4);
182                 xdr_int(&p, &pairtype);
183
184                 if (!memcmp(name, pairname, namelen) && type == pairtype) {
185                         xdr_int(&p, &elements);
186                         if (elementsp)
187                                 *elementsp = elements;
188                         if (type == DATA_TYPE_UINT64) {
189                                 xdr_uint64_t(&p, (uint64_t *) valuep);
190                                 return (0);
191                         } else if (type == DATA_TYPE_STRING) {
192                                 int len;
193                                 xdr_int(&p, &len);
194                                 (*(const char**) valuep) = (const char*) p;
195                                 return (0);
196                         } else if (type == DATA_TYPE_NVLIST
197                                    || type == DATA_TYPE_NVLIST_ARRAY) {
198                                 (*(const unsigned char**) valuep) =
199                                          (const unsigned char*) p;
200                                 return (0);
201                         } else {
202                                 return (EIO);
203                         }
204                 } else {
205                         /*
206                          * Not the pair we are looking for, skip to the next one.
207                          */
208                         p = pair + encoded_size;
209                 }
210
211                 pair = p;
212                 xdr_int(&p, &encoded_size);
213                 xdr_int(&p, &decoded_size);
214         }
215
216         return (EIO);
217 }
218
219 static int
220 nvlist_check_features_for_read(const unsigned char *nvlist)
221 {
222         const unsigned char *p, *pair;
223         int junk;
224         int encoded_size, decoded_size;
225         int rc;
226
227         rc = 0;
228
229         p = nvlist;
230         xdr_int(&p, &junk);
231         xdr_int(&p, &junk);
232
233         pair = p;
234         xdr_int(&p, &encoded_size);
235         xdr_int(&p, &decoded_size);
236         while (encoded_size && decoded_size) {
237                 int namelen, pairtype;
238                 const char *pairname;
239                 int i, found;
240
241                 found = 0;
242
243                 xdr_int(&p, &namelen);
244                 pairname = (const char*) p;
245                 p += roundup(namelen, 4);
246                 xdr_int(&p, &pairtype);
247
248                 for (i = 0; features_for_read[i] != NULL; i++) {
249                         if (!memcmp(pairname, features_for_read[i], namelen)) {
250                                 found = 1;
251                                 break;
252                         }
253                 }
254
255                 if (!found) {
256                         printf("ZFS: unsupported feature: %s\n", pairname);
257                         rc = EIO;
258                 }
259
260                 p = pair + encoded_size;
261
262                 pair = p;
263                 xdr_int(&p, &encoded_size);
264                 xdr_int(&p, &decoded_size);
265         }
266
267         return (rc);
268 }
269
270 /*
271  * Return the next nvlist in an nvlist array.
272  */
273 static const unsigned char *
274 nvlist_next(const unsigned char *nvlist)
275 {
276         const unsigned char *p, *pair;
277         int junk;
278         int encoded_size, decoded_size;
279
280         p = nvlist;
281         xdr_int(&p, &junk);
282         xdr_int(&p, &junk);
283
284         pair = p;
285         xdr_int(&p, &encoded_size);
286         xdr_int(&p, &decoded_size);
287         while (encoded_size && decoded_size) {
288                 p = pair + encoded_size;
289
290                 pair = p;
291                 xdr_int(&p, &encoded_size);
292                 xdr_int(&p, &decoded_size);
293         }
294
295         return p;
296 }
297
298 #ifdef TEST
299
300 static const unsigned char *
301 nvlist_print(const unsigned char *nvlist, unsigned int indent)
302 {
303         static const char* typenames[] = {
304                 "DATA_TYPE_UNKNOWN",
305                 "DATA_TYPE_BOOLEAN",
306                 "DATA_TYPE_BYTE",
307                 "DATA_TYPE_INT16",
308                 "DATA_TYPE_UINT16",
309                 "DATA_TYPE_INT32",
310                 "DATA_TYPE_UINT32",
311                 "DATA_TYPE_INT64",
312                 "DATA_TYPE_UINT64",
313                 "DATA_TYPE_STRING",
314                 "DATA_TYPE_BYTE_ARRAY",
315                 "DATA_TYPE_INT16_ARRAY",
316                 "DATA_TYPE_UINT16_ARRAY",
317                 "DATA_TYPE_INT32_ARRAY",
318                 "DATA_TYPE_UINT32_ARRAY",
319                 "DATA_TYPE_INT64_ARRAY",
320                 "DATA_TYPE_UINT64_ARRAY",
321                 "DATA_TYPE_STRING_ARRAY",
322                 "DATA_TYPE_HRTIME",
323                 "DATA_TYPE_NVLIST",
324                 "DATA_TYPE_NVLIST_ARRAY",
325                 "DATA_TYPE_BOOLEAN_VALUE",
326                 "DATA_TYPE_INT8",
327                 "DATA_TYPE_UINT8",
328                 "DATA_TYPE_BOOLEAN_ARRAY",
329                 "DATA_TYPE_INT8_ARRAY",
330                 "DATA_TYPE_UINT8_ARRAY"
331         };
332
333         unsigned int i, j;
334         const unsigned char *p, *pair;
335         int junk;
336         int encoded_size, decoded_size;
337
338         p = nvlist;
339         xdr_int(&p, &junk);
340         xdr_int(&p, &junk);
341
342         pair = p;
343         xdr_int(&p, &encoded_size);
344         xdr_int(&p, &decoded_size);
345         while (encoded_size && decoded_size) {
346                 int namelen, pairtype, elements;
347                 const char *pairname;
348
349                 xdr_int(&p, &namelen);
350                 pairname = (const char*) p;
351                 p += roundup(namelen, 4);
352                 xdr_int(&p, &pairtype);
353
354                 for (i = 0; i < indent; i++)
355                         printf(" ");
356                 printf("%s %s", typenames[pairtype], pairname);
357
358                 xdr_int(&p, &elements);
359                 switch (pairtype) {
360                 case DATA_TYPE_UINT64: {
361                         uint64_t val;
362                         xdr_uint64_t(&p, &val);
363                         printf(" = 0x%jx\n", (uintmax_t)val);
364                         break;
365                 }
366
367                 case DATA_TYPE_STRING: {
368                         int len;
369                         xdr_int(&p, &len);
370                         printf(" = \"%s\"\n", p);
371                         break;
372                 }
373
374                 case DATA_TYPE_NVLIST:
375                         printf("\n");
376                         nvlist_print(p, indent + 1);
377                         break;
378
379                 case DATA_TYPE_NVLIST_ARRAY:
380                         for (j = 0; j < elements; j++) {
381                                 printf("[%d]\n", j);
382                                 p = nvlist_print(p, indent + 1);
383                                 if (j != elements - 1) {
384                                         for (i = 0; i < indent; i++)
385                                                 printf(" ");
386                                         printf("%s %s", typenames[pairtype], pairname);
387                                 }
388                         }
389                         break;
390
391                 default:
392                         printf("\n");
393                 }
394
395                 p = pair + encoded_size;
396
397                 pair = p;
398                 xdr_int(&p, &encoded_size);
399                 xdr_int(&p, &decoded_size);
400         }
401
402         return p;
403 }
404
405 #endif
406
407 static int
408 vdev_read_phys(vdev_t *vdev, const blkptr_t *bp, void *buf,
409     off_t offset, size_t size)
410 {
411         size_t psize;
412         int rc;
413
414         if (!vdev->v_phys_read)
415                 return (EIO);
416
417         if (bp) {
418                 psize = BP_GET_PSIZE(bp);
419         } else {
420                 psize = size;
421         }
422
423         /*printf("ZFS: reading %d bytes at 0x%jx to %p\n", psize, (uintmax_t)offset, buf);*/
424         rc = vdev->v_phys_read(vdev, vdev->v_read_priv, offset, buf, psize);
425         if (rc)
426                 return (rc);
427         if (bp && zio_checksum_verify(vdev->spa, bp, buf))
428                 return (EIO);
429
430         return (0);
431 }
432
433 static int
434 vdev_disk_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
435     off_t offset, size_t bytes)
436 {
437
438         return (vdev_read_phys(vdev, bp, buf,
439                 offset + VDEV_LABEL_START_SIZE, bytes));
440 }
441
442
443 static int
444 vdev_mirror_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
445     off_t offset, size_t bytes)
446 {
447         vdev_t *kid;
448         int rc;
449
450         rc = EIO;
451         STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
452                 if (kid->v_state != VDEV_STATE_HEALTHY)
453                         continue;
454                 rc = kid->v_read(kid, bp, buf, offset, bytes);
455                 if (!rc)
456                         return (0);
457         }
458
459         return (rc);
460 }
461
462 static int
463 vdev_replacing_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
464     off_t offset, size_t bytes)
465 {
466         vdev_t *kid;
467
468         /*
469          * Here we should have two kids:
470          * First one which is the one we are replacing and we can trust
471          * only this one to have valid data, but it might not be present.
472          * Second one is that one we are replacing with. It is most likely
473          * healthy, but we can't trust it has needed data, so we won't use it.
474          */
475         kid = STAILQ_FIRST(&vdev->v_children);
476         if (kid == NULL)
477                 return (EIO);
478         if (kid->v_state != VDEV_STATE_HEALTHY)
479                 return (EIO);
480         return (kid->v_read(kid, bp, buf, offset, bytes));
481 }
482
483 static vdev_t *
484 vdev_find(uint64_t guid)
485 {
486         vdev_t *vdev;
487
488         STAILQ_FOREACH(vdev, &zfs_vdevs, v_alllink)
489                 if (vdev->v_guid == guid)
490                         return (vdev);
491
492         return (0);
493 }
494
495 static vdev_t *
496 vdev_create(uint64_t guid, vdev_read_t *_read)
497 {
498         vdev_t *vdev;
499
500         vdev = malloc(sizeof(vdev_t));
501         memset(vdev, 0, sizeof(vdev_t));
502         STAILQ_INIT(&vdev->v_children);
503         vdev->v_guid = guid;
504         vdev->v_state = VDEV_STATE_OFFLINE;
505         vdev->v_read = _read;
506         vdev->v_phys_read = 0;
507         vdev->v_read_priv = 0;
508         STAILQ_INSERT_TAIL(&zfs_vdevs, vdev, v_alllink);
509
510         return (vdev);
511 }
512
513 static int
514 vdev_init_from_nvlist(const unsigned char *nvlist, vdev_t *pvdev,
515     vdev_t **vdevp, int is_newer)
516 {
517         int rc;
518         uint64_t guid, id, ashift, nparity;
519         const char *type;
520         const char *path;
521         vdev_t *vdev, *kid;
522         const unsigned char *kids;
523         int nkids, i, is_new;
524         uint64_t is_offline, is_faulted, is_degraded, is_removed, isnt_present;
525
526         if (nvlist_find(nvlist, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64,
527             NULL, &guid)
528             || nvlist_find(nvlist, ZPOOL_CONFIG_ID, DATA_TYPE_UINT64, NULL, &id)
529             || nvlist_find(nvlist, ZPOOL_CONFIG_TYPE, DATA_TYPE_STRING,
530             NULL, &type)) {
531                 printf("ZFS: can't find vdev details\n");
532                 return (ENOENT);
533         }
534
535         if (strcmp(type, VDEV_TYPE_MIRROR)
536             && strcmp(type, VDEV_TYPE_DISK)
537 #ifdef ZFS_TEST
538             && strcmp(type, VDEV_TYPE_FILE)
539 #endif
540             && strcmp(type, VDEV_TYPE_RAIDZ)
541             && strcmp(type, VDEV_TYPE_REPLACING)) {
542                 printf("ZFS: can only boot from disk, mirror, raidz1, raidz2 and raidz3 vdevs\n");
543                 return (EIO);
544         }
545
546         is_offline = is_removed = is_faulted = is_degraded = isnt_present = 0;
547
548         nvlist_find(nvlist, ZPOOL_CONFIG_OFFLINE, DATA_TYPE_UINT64, NULL,
549                         &is_offline);
550         nvlist_find(nvlist, ZPOOL_CONFIG_REMOVED, DATA_TYPE_UINT64, NULL,
551                         &is_removed);
552         nvlist_find(nvlist, ZPOOL_CONFIG_FAULTED, DATA_TYPE_UINT64, NULL,
553                         &is_faulted);
554         nvlist_find(nvlist, ZPOOL_CONFIG_DEGRADED, DATA_TYPE_UINT64, NULL,
555                         &is_degraded);
556         nvlist_find(nvlist, ZPOOL_CONFIG_NOT_PRESENT, DATA_TYPE_UINT64, NULL,
557                         &isnt_present);
558
559         vdev = vdev_find(guid);
560         if (!vdev) {
561                 is_new = 1;
562
563                 if (!strcmp(type, VDEV_TYPE_MIRROR))
564                         vdev = vdev_create(guid, vdev_mirror_read);
565                 else if (!strcmp(type, VDEV_TYPE_RAIDZ))
566                         vdev = vdev_create(guid, vdev_raidz_read);
567                 else if (!strcmp(type, VDEV_TYPE_REPLACING))
568                         vdev = vdev_create(guid, vdev_replacing_read);
569                 else
570                         vdev = vdev_create(guid, vdev_disk_read);
571
572                 vdev->v_id = id;
573                 vdev->v_top = pvdev != NULL ? pvdev : vdev;
574                 if (nvlist_find(nvlist, ZPOOL_CONFIG_ASHIFT,
575                         DATA_TYPE_UINT64, NULL, &ashift) == 0) {
576                         vdev->v_ashift = ashift;
577                 } else {
578                         vdev->v_ashift = 0;
579                 }
580                 if (nvlist_find(nvlist, ZPOOL_CONFIG_NPARITY,
581                         DATA_TYPE_UINT64, NULL, &nparity) == 0) {
582                         vdev->v_nparity = nparity;
583                 } else {
584                         vdev->v_nparity = 0;
585                 }
586                 if (nvlist_find(nvlist, ZPOOL_CONFIG_PATH,
587                                 DATA_TYPE_STRING, NULL, &path) == 0) {
588                         if (strncmp(path, "/dev/", 5) == 0)
589                                 path += 5;
590                         vdev->v_name = strdup(path);
591                 } else {
592                         if (!strcmp(type, "raidz")) {
593                                 if (vdev->v_nparity == 1)
594                                         vdev->v_name = "raidz1";
595                                 else if (vdev->v_nparity == 2)
596                                         vdev->v_name = "raidz2";
597                                 else if (vdev->v_nparity == 3)
598                                         vdev->v_name = "raidz3";
599                                 else {
600                                         printf("ZFS: can only boot from disk, mirror, raidz1, raidz2 and raidz3 vdevs\n");
601                                         return (EIO);
602                                 }
603                         } else {
604                                 vdev->v_name = strdup(type);
605                         }
606                 }
607         } else {
608                 is_new = 0;
609         }
610
611         if (is_new || is_newer) {
612                 /*
613                  * This is either new vdev or we've already seen this vdev,
614                  * but from an older vdev label, so let's refresh its state
615                  * from the newer label.
616                  */
617                 if (is_offline)
618                         vdev->v_state = VDEV_STATE_OFFLINE;
619                 else if (is_removed)
620                         vdev->v_state = VDEV_STATE_REMOVED;
621                 else if (is_faulted)
622                         vdev->v_state = VDEV_STATE_FAULTED;
623                 else if (is_degraded)
624                         vdev->v_state = VDEV_STATE_DEGRADED;
625                 else if (isnt_present)
626                         vdev->v_state = VDEV_STATE_CANT_OPEN;
627         }
628
629         rc = nvlist_find(nvlist, ZPOOL_CONFIG_CHILDREN, DATA_TYPE_NVLIST_ARRAY,
630             &nkids, &kids);
631         /*
632          * Its ok if we don't have any kids.
633          */
634         if (rc == 0) {
635                 vdev->v_nchildren = nkids;
636                 for (i = 0; i < nkids; i++) {
637                         rc = vdev_init_from_nvlist(kids, vdev, &kid, is_newer);
638                         if (rc)
639                                 return (rc);
640                         if (is_new)
641                                 STAILQ_INSERT_TAIL(&vdev->v_children, kid,
642                                                    v_childlink);
643                         kids = nvlist_next(kids);
644                 }
645         } else {
646                 vdev->v_nchildren = 0;
647         }
648
649         if (vdevp)
650                 *vdevp = vdev;
651         return (0);
652 }
653
654 static void
655 vdev_set_state(vdev_t *vdev)
656 {
657         vdev_t *kid;
658         int good_kids;
659         int bad_kids;
660
661         /*
662          * A mirror or raidz is healthy if all its kids are healthy. A
663          * mirror is degraded if any of its kids is healthy; a raidz
664          * is degraded if at most nparity kids are offline.
665          */
666         if (STAILQ_FIRST(&vdev->v_children)) {
667                 good_kids = 0;
668                 bad_kids = 0;
669                 STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
670                         if (kid->v_state == VDEV_STATE_HEALTHY)
671                                 good_kids++;
672                         else
673                                 bad_kids++;
674                 }
675                 if (bad_kids == 0) {
676                         vdev->v_state = VDEV_STATE_HEALTHY;
677                 } else {
678                         if (vdev->v_read == vdev_mirror_read) {
679                                 if (good_kids) {
680                                         vdev->v_state = VDEV_STATE_DEGRADED;
681                                 } else {
682                                         vdev->v_state = VDEV_STATE_OFFLINE;
683                                 }
684                         } else if (vdev->v_read == vdev_raidz_read) {
685                                 if (bad_kids > vdev->v_nparity) {
686                                         vdev->v_state = VDEV_STATE_OFFLINE;
687                                 } else {
688                                         vdev->v_state = VDEV_STATE_DEGRADED;
689                                 }
690                         }
691                 }
692         }
693 }
694
695 static spa_t *
696 spa_find_by_guid(uint64_t guid)
697 {
698         spa_t *spa;
699
700         STAILQ_FOREACH(spa, &zfs_pools, spa_link)
701                 if (spa->spa_guid == guid)
702                         return (spa);
703
704         return (0);
705 }
706
707 static spa_t *
708 spa_find_by_name(const char *name)
709 {
710         spa_t *spa;
711
712         STAILQ_FOREACH(spa, &zfs_pools, spa_link)
713                 if (!strcmp(spa->spa_name, name))
714                         return (spa);
715
716         return (0);
717 }
718
719 #ifdef BOOT2
720 static spa_t *
721 spa_get_primary(void)
722 {
723
724         return (STAILQ_FIRST(&zfs_pools));
725 }
726
727 static vdev_t *
728 spa_get_primary_vdev(const spa_t *spa)
729 {
730         vdev_t *vdev;
731         vdev_t *kid;
732
733         if (spa == NULL)
734                 spa = spa_get_primary();
735         if (spa == NULL)
736                 return (NULL);
737         vdev = STAILQ_FIRST(&spa->spa_vdevs);
738         if (vdev == NULL)
739                 return (NULL);
740         for (kid = STAILQ_FIRST(&vdev->v_children); kid != NULL;
741              kid = STAILQ_FIRST(&vdev->v_children))
742                 vdev = kid;
743         return (vdev);
744 }
745 #endif
746
747 static spa_t *
748 spa_create(uint64_t guid, const char *name)
749 {
750         spa_t *spa;
751
752         if ((spa = malloc(sizeof(spa_t))) == NULL)
753                 return (NULL);
754         memset(spa, 0, sizeof(spa_t));
755         if ((spa->spa_name = strdup(name)) == NULL) {
756                 free(spa);
757                 return (NULL);
758         }
759         STAILQ_INIT(&spa->spa_vdevs);
760         spa->spa_guid = guid;
761         STAILQ_INSERT_TAIL(&zfs_pools, spa, spa_link);
762
763         return (spa);
764 }
765
766 static const char *
767 state_name(vdev_state_t state)
768 {
769         static const char* names[] = {
770                 "UNKNOWN",
771                 "CLOSED",
772                 "OFFLINE",
773                 "REMOVED",
774                 "CANT_OPEN",
775                 "FAULTED",
776                 "DEGRADED",
777                 "ONLINE"
778         };
779         return names[state];
780 }
781
782 #ifdef BOOT2
783
784 #define pager_printf printf
785
786 #else
787
788 static int
789 pager_printf(const char *fmt, ...)
790 {
791         char line[80];
792         va_list args;
793
794         va_start(args, fmt);
795         vsprintf(line, fmt, args);
796         va_end(args);
797         return (pager_output(line));
798 }
799
800 #endif
801
802 #define STATUS_FORMAT   "        %s %s\n"
803
804 static int
805 print_state(int indent, const char *name, vdev_state_t state)
806 {
807         int i;
808         char buf[512];
809
810         buf[0] = 0;
811         for (i = 0; i < indent; i++)
812                 strcat(buf, "  ");
813         strcat(buf, name);
814         return (pager_printf(STATUS_FORMAT, buf, state_name(state)));
815         
816 }
817
818 static int
819 vdev_status(vdev_t *vdev, int indent)
820 {
821         vdev_t *kid;
822         int ret;
823         ret = print_state(indent, vdev->v_name, vdev->v_state);
824         if (ret != 0)
825                 return (ret);
826
827         STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
828                 ret = vdev_status(kid, indent + 1);
829                 if (ret != 0)
830                         return (ret);
831         }
832         return (ret);
833 }
834
835 static int
836 spa_status(spa_t *spa)
837 {
838         static char bootfs[ZFS_MAXNAMELEN];
839         uint64_t rootid;
840         vdev_t *vdev;
841         int good_kids, bad_kids, degraded_kids, ret;
842         vdev_state_t state;
843
844         ret = pager_printf("  pool: %s\n", spa->spa_name);
845         if (ret != 0)
846                 return (ret);
847
848         if (zfs_get_root(spa, &rootid) == 0 &&
849             zfs_rlookup(spa, rootid, bootfs) == 0) {
850                 if (bootfs[0] == '\0')
851                         ret = pager_printf("bootfs: %s\n", spa->spa_name);
852                 else
853                         ret = pager_printf("bootfs: %s/%s\n", spa->spa_name,
854                             bootfs);
855                 if (ret != 0)
856                         return (ret);
857         }
858         ret = pager_printf("config:\n\n");
859         if (ret != 0)
860                 return (ret);
861         ret = pager_printf(STATUS_FORMAT, "NAME", "STATE");
862         if (ret != 0)
863                 return (ret);
864
865         good_kids = 0;
866         degraded_kids = 0;
867         bad_kids = 0;
868         STAILQ_FOREACH(vdev, &spa->spa_vdevs, v_childlink) {
869                 if (vdev->v_state == VDEV_STATE_HEALTHY)
870                         good_kids++;
871                 else if (vdev->v_state == VDEV_STATE_DEGRADED)
872                         degraded_kids++;
873                 else
874                         bad_kids++;
875         }
876
877         state = VDEV_STATE_CLOSED;
878         if (good_kids > 0 && (degraded_kids + bad_kids) == 0)
879                 state = VDEV_STATE_HEALTHY;
880         else if ((good_kids + degraded_kids) > 0)
881                 state = VDEV_STATE_DEGRADED;
882
883         ret = print_state(0, spa->spa_name, state);
884         if (ret != 0)
885                 return (ret);
886         STAILQ_FOREACH(vdev, &spa->spa_vdevs, v_childlink) {
887                 ret = vdev_status(vdev, 1);
888                 if (ret != 0)
889                         return (ret);
890         }
891         return (ret);
892 }
893
894 static int
895 spa_all_status(void)
896 {
897         spa_t *spa;
898         int first = 1, ret = 0;
899
900         STAILQ_FOREACH(spa, &zfs_pools, spa_link) {
901                 if (!first) {
902                         ret = pager_printf("\n");
903                         if (ret != 0)
904                                 return (ret);
905                 }
906                 first = 0;
907                 ret = spa_status(spa);
908                 if (ret != 0)
909                         return (ret);
910         }
911         return (ret);
912 }
913
914 uint64_t
915 vdev_label_offset(uint64_t psize, int l, uint64_t offset)
916 {
917         uint64_t label_offset;
918
919         if (l < VDEV_LABELS / 2)
920                 label_offset = 0;
921         else
922                 label_offset = psize - VDEV_LABELS * sizeof (vdev_label_t);
923
924         return (offset + l * sizeof (vdev_label_t) + label_offset);
925 }
926
927 static int
928 vdev_probe(vdev_phys_read_t *_read, void *read_priv, spa_t **spap)
929 {
930         vdev_t vtmp;
931         vdev_phys_t *vdev_label = (vdev_phys_t *) zap_scratch;
932         vdev_phys_t *tmp_label;
933         spa_t *spa;
934         vdev_t *vdev, *top_vdev, *pool_vdev;
935         off_t off;
936         blkptr_t bp;
937         const unsigned char *nvlist = NULL;
938         uint64_t val;
939         uint64_t guid;
940         uint64_t best_txg = 0;
941         uint64_t pool_txg, pool_guid;
942         uint64_t psize;
943         const char *pool_name;
944         const unsigned char *vdevs;
945         const unsigned char *features;
946         int i, l, rc, is_newer;
947         char *upbuf;
948         const struct uberblock *up;
949
950         /*
951          * Load the vdev label and figure out which
952          * uberblock is most current.
953          */
954         memset(&vtmp, 0, sizeof(vtmp));
955         vtmp.v_phys_read = _read;
956         vtmp.v_read_priv = read_priv;
957         psize = P2ALIGN(ldi_get_size(read_priv),
958             (uint64_t)sizeof (vdev_label_t));
959
960         /* Test for minimum pool size. */
961         if (psize < SPA_MINDEVSIZE)
962                 return (EIO);
963
964         tmp_label = zfs_alloc(sizeof(vdev_phys_t));
965
966         for (l = 0; l < VDEV_LABELS; l++) {
967                 off = vdev_label_offset(psize, l,
968                     offsetof(vdev_label_t, vl_vdev_phys));
969
970                 BP_ZERO(&bp);
971                 BP_SET_LSIZE(&bp, sizeof(vdev_phys_t));
972                 BP_SET_PSIZE(&bp, sizeof(vdev_phys_t));
973                 BP_SET_CHECKSUM(&bp, ZIO_CHECKSUM_LABEL);
974                 BP_SET_COMPRESS(&bp, ZIO_COMPRESS_OFF);
975                 DVA_SET_OFFSET(BP_IDENTITY(&bp), off);
976                 ZIO_SET_CHECKSUM(&bp.blk_cksum, off, 0, 0, 0);
977
978                 if (vdev_read_phys(&vtmp, &bp, tmp_label, off, 0))
979                         continue;
980
981                 if (tmp_label->vp_nvlist[0] != NV_ENCODE_XDR)
982                         continue;
983
984                 nvlist = (const unsigned char *) tmp_label->vp_nvlist + 4;
985                 if (nvlist_find(nvlist, ZPOOL_CONFIG_POOL_TXG,
986                     DATA_TYPE_UINT64, NULL, &pool_txg) != 0)
987                         continue;
988
989                 if (best_txg <= pool_txg) {
990                         best_txg = pool_txg;
991                         memcpy(vdev_label, tmp_label, sizeof (vdev_phys_t));
992                 }
993         }
994
995         zfs_free(tmp_label, sizeof (vdev_phys_t));
996
997         if (best_txg == 0)
998                 return (EIO);
999
1000         if (vdev_label->vp_nvlist[0] != NV_ENCODE_XDR)
1001                 return (EIO);
1002
1003         nvlist = (const unsigned char *) vdev_label->vp_nvlist + 4;
1004
1005         if (nvlist_find(nvlist, ZPOOL_CONFIG_VERSION, DATA_TYPE_UINT64,
1006             NULL, &val) != 0) {
1007                 return (EIO);
1008         }
1009
1010         if (!SPA_VERSION_IS_SUPPORTED(val)) {
1011                 printf("ZFS: unsupported ZFS version %u (should be %u)\n",
1012                     (unsigned) val, (unsigned) SPA_VERSION);
1013                 return (EIO);
1014         }
1015
1016         /* Check ZFS features for read */
1017         if (nvlist_find(nvlist, ZPOOL_CONFIG_FEATURES_FOR_READ,
1018             DATA_TYPE_NVLIST, NULL, &features) == 0 &&
1019             nvlist_check_features_for_read(features) != 0) {
1020                 return (EIO);
1021         }
1022
1023         if (nvlist_find(nvlist, ZPOOL_CONFIG_POOL_STATE, DATA_TYPE_UINT64,
1024             NULL, &val) != 0) {
1025                 return (EIO);
1026         }
1027
1028         if (val == POOL_STATE_DESTROYED) {
1029                 /* We don't boot only from destroyed pools. */
1030                 return (EIO);
1031         }
1032
1033         if (nvlist_find(nvlist, ZPOOL_CONFIG_POOL_TXG, DATA_TYPE_UINT64,
1034             NULL, &pool_txg) != 0 ||
1035             nvlist_find(nvlist, ZPOOL_CONFIG_POOL_GUID, DATA_TYPE_UINT64,
1036             NULL, &pool_guid) != 0 ||
1037             nvlist_find(nvlist, ZPOOL_CONFIG_POOL_NAME, DATA_TYPE_STRING,
1038             NULL, &pool_name) != 0) {
1039                 /*
1040                  * Cache and spare devices end up here - just ignore
1041                  * them.
1042                  */
1043                 /*printf("ZFS: can't find pool details\n");*/
1044                 return (EIO);
1045         }
1046
1047         if (nvlist_find(nvlist, ZPOOL_CONFIG_IS_LOG, DATA_TYPE_UINT64,
1048             NULL, &val) == 0 && val != 0) {
1049                 return (EIO);
1050         }
1051
1052         /*
1053          * Create the pool if this is the first time we've seen it.
1054          */
1055         spa = spa_find_by_guid(pool_guid);
1056         if (spa == NULL) {
1057                 spa = spa_create(pool_guid, pool_name);
1058                 if (spa == NULL)
1059                         return (ENOMEM);
1060         }
1061         if (pool_txg > spa->spa_txg) {
1062                 spa->spa_txg = pool_txg;
1063                 is_newer = 1;
1064         } else {
1065                 is_newer = 0;
1066         }
1067
1068         /*
1069          * Get the vdev tree and create our in-core copy of it.
1070          * If we already have a vdev with this guid, this must
1071          * be some kind of alias (overlapping slices, dangerously dedicated
1072          * disks etc).
1073          */
1074         if (nvlist_find(nvlist, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64,
1075             NULL, &guid) != 0) {
1076                 return (EIO);
1077         }
1078         vdev = vdev_find(guid);
1079         if (vdev && vdev->v_phys_read)  /* Has this vdev already been inited? */
1080                 return (EIO);
1081
1082         if (nvlist_find(nvlist, ZPOOL_CONFIG_VDEV_TREE, DATA_TYPE_NVLIST,
1083             NULL, &vdevs)) {
1084                 return (EIO);
1085         }
1086
1087         rc = vdev_init_from_nvlist(vdevs, NULL, &top_vdev, is_newer);
1088         if (rc != 0)
1089                 return (rc);
1090
1091         /*
1092          * Add the toplevel vdev to the pool if its not already there.
1093          */
1094         STAILQ_FOREACH(pool_vdev, &spa->spa_vdevs, v_childlink)
1095                 if (top_vdev == pool_vdev)
1096                         break;
1097         if (!pool_vdev && top_vdev) {
1098                 top_vdev->spa = spa;
1099                 STAILQ_INSERT_TAIL(&spa->spa_vdevs, top_vdev, v_childlink);
1100         }
1101
1102         /*
1103          * We should already have created an incomplete vdev for this
1104          * vdev. Find it and initialise it with our read proc.
1105          */
1106         vdev = vdev_find(guid);
1107         if (vdev) {
1108                 vdev->v_phys_read = _read;
1109                 vdev->v_read_priv = read_priv;
1110                 vdev->v_state = VDEV_STATE_HEALTHY;
1111         } else {
1112                 printf("ZFS: inconsistent nvlist contents\n");
1113                 return (EIO);
1114         }
1115
1116         /*
1117          * Re-evaluate top-level vdev state.
1118          */
1119         vdev_set_state(top_vdev);
1120
1121         /*
1122          * Ok, we are happy with the pool so far. Lets find
1123          * the best uberblock and then we can actually access
1124          * the contents of the pool.
1125          */
1126         upbuf = zfs_alloc(VDEV_UBERBLOCK_SIZE(vdev));
1127         up = (const struct uberblock *)upbuf;
1128         for (l = 0; l < VDEV_LABELS; l++) {
1129                 for (i = 0; i < VDEV_UBERBLOCK_COUNT(vdev); i++) {
1130                         off = vdev_label_offset(psize, l,
1131                             VDEV_UBERBLOCK_OFFSET(vdev, i));
1132                         BP_ZERO(&bp);
1133                         DVA_SET_OFFSET(&bp.blk_dva[0], off);
1134                         BP_SET_LSIZE(&bp, VDEV_UBERBLOCK_SIZE(vdev));
1135                         BP_SET_PSIZE(&bp, VDEV_UBERBLOCK_SIZE(vdev));
1136                         BP_SET_CHECKSUM(&bp, ZIO_CHECKSUM_LABEL);
1137                         BP_SET_COMPRESS(&bp, ZIO_COMPRESS_OFF);
1138                         ZIO_SET_CHECKSUM(&bp.blk_cksum, off, 0, 0, 0);
1139
1140                         if (vdev_read_phys(vdev, &bp, upbuf, off, 0))
1141                                 continue;
1142
1143                         if (up->ub_magic != UBERBLOCK_MAGIC)
1144                                 continue;
1145                         if (up->ub_txg < spa->spa_txg)
1146                                 continue;
1147                         if (up->ub_txg > spa->spa_uberblock.ub_txg ||
1148                             (up->ub_txg == spa->spa_uberblock.ub_txg &&
1149                             up->ub_timestamp >
1150                             spa->spa_uberblock.ub_timestamp)) {
1151                                 spa->spa_uberblock = *up;
1152                         }
1153                 }
1154         }
1155         zfs_free(upbuf, VDEV_UBERBLOCK_SIZE(vdev));
1156
1157         vdev->spa = spa;
1158         if (spap != NULL)
1159                 *spap = spa;
1160         return (0);
1161 }
1162
1163 static int
1164 ilog2(int n)
1165 {
1166         int v;
1167
1168         for (v = 0; v < 32; v++)
1169                 if (n == (1 << v))
1170                         return v;
1171         return -1;
1172 }
1173
1174 static int
1175 zio_read_gang(const spa_t *spa, const blkptr_t *bp, void *buf)
1176 {
1177         blkptr_t gbh_bp;
1178         zio_gbh_phys_t zio_gb;
1179         char *pbuf;
1180         int i;
1181
1182         /* Artificial BP for gang block header. */
1183         gbh_bp = *bp;
1184         BP_SET_PSIZE(&gbh_bp, SPA_GANGBLOCKSIZE);
1185         BP_SET_LSIZE(&gbh_bp, SPA_GANGBLOCKSIZE);
1186         BP_SET_CHECKSUM(&gbh_bp, ZIO_CHECKSUM_GANG_HEADER);
1187         BP_SET_COMPRESS(&gbh_bp, ZIO_COMPRESS_OFF);
1188         for (i = 0; i < SPA_DVAS_PER_BP; i++)
1189                 DVA_SET_GANG(&gbh_bp.blk_dva[i], 0);
1190
1191         /* Read gang header block using the artificial BP. */
1192         if (zio_read(spa, &gbh_bp, &zio_gb))
1193                 return (EIO);
1194
1195         pbuf = buf;
1196         for (i = 0; i < SPA_GBH_NBLKPTRS; i++) {
1197                 blkptr_t *gbp = &zio_gb.zg_blkptr[i];
1198
1199                 if (BP_IS_HOLE(gbp))
1200                         continue;
1201                 if (zio_read(spa, gbp, pbuf))
1202                         return (EIO);
1203                 pbuf += BP_GET_PSIZE(gbp);
1204         }
1205
1206         if (zio_checksum_verify(spa, bp, buf))
1207                 return (EIO);
1208         return (0);
1209 }
1210
1211 static int
1212 zio_read(const spa_t *spa, const blkptr_t *bp, void *buf)
1213 {
1214         int cpfunc = BP_GET_COMPRESS(bp);
1215         uint64_t align, size;
1216         void *pbuf;
1217         int i, error;
1218
1219         /*
1220          * Process data embedded in block pointer
1221          */
1222         if (BP_IS_EMBEDDED(bp)) {
1223                 ASSERT(BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
1224
1225                 size = BPE_GET_PSIZE(bp);
1226                 ASSERT(size <= BPE_PAYLOAD_SIZE);
1227
1228                 if (cpfunc != ZIO_COMPRESS_OFF)
1229                         pbuf = zfs_alloc(size);
1230                 else
1231                         pbuf = buf;
1232
1233                 decode_embedded_bp_compressed(bp, pbuf);
1234                 error = 0;
1235
1236                 if (cpfunc != ZIO_COMPRESS_OFF) {
1237                         error = zio_decompress_data(cpfunc, pbuf,
1238                             size, buf, BP_GET_LSIZE(bp));
1239                         zfs_free(pbuf, size);
1240                 }
1241                 if (error != 0)
1242                         printf("ZFS: i/o error - unable to decompress block pointer data, error %d\n",
1243                             error);
1244                 return (error);
1245         }
1246
1247         error = EIO;
1248
1249         for (i = 0; i < SPA_DVAS_PER_BP; i++) {
1250                 const dva_t *dva = &bp->blk_dva[i];
1251                 vdev_t *vdev;
1252                 int vdevid;
1253                 off_t offset;
1254
1255                 if (!dva->dva_word[0] && !dva->dva_word[1])
1256                         continue;
1257
1258                 vdevid = DVA_GET_VDEV(dva);
1259                 offset = DVA_GET_OFFSET(dva);
1260                 STAILQ_FOREACH(vdev, &spa->spa_vdevs, v_childlink) {
1261                         if (vdev->v_id == vdevid)
1262                                 break;
1263                 }
1264                 if (!vdev || !vdev->v_read)
1265                         continue;
1266
1267                 size = BP_GET_PSIZE(bp);
1268                 if (vdev->v_read == vdev_raidz_read) {
1269                         align = 1ULL << vdev->v_top->v_ashift;
1270                         if (P2PHASE(size, align) != 0)
1271                                 size = P2ROUNDUP(size, align);
1272                 }
1273                 if (size != BP_GET_PSIZE(bp) || cpfunc != ZIO_COMPRESS_OFF)
1274                         pbuf = zfs_alloc(size);
1275                 else
1276                         pbuf = buf;
1277
1278                 if (DVA_GET_GANG(dva))
1279                         error = zio_read_gang(spa, bp, pbuf);
1280                 else
1281                         error = vdev->v_read(vdev, bp, pbuf, offset, size);
1282                 if (error == 0) {
1283                         if (cpfunc != ZIO_COMPRESS_OFF)
1284                                 error = zio_decompress_data(cpfunc, pbuf,
1285                                     BP_GET_PSIZE(bp), buf, BP_GET_LSIZE(bp));
1286                         else if (size != BP_GET_PSIZE(bp))
1287                                 bcopy(pbuf, buf, BP_GET_PSIZE(bp));
1288                 }
1289                 if (buf != pbuf)
1290                         zfs_free(pbuf, size);
1291                 if (error == 0)
1292                         break;
1293         }
1294         if (error != 0)
1295                 printf("ZFS: i/o error - all block copies unavailable\n");
1296         return (error);
1297 }
1298
1299 static int
1300 dnode_read(const spa_t *spa, const dnode_phys_t *dnode, off_t offset, void *buf, size_t buflen)
1301 {
1302         int ibshift = dnode->dn_indblkshift - SPA_BLKPTRSHIFT;
1303         int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
1304         int nlevels = dnode->dn_nlevels;
1305         int i, rc;
1306
1307         if (bsize > SPA_MAXBLOCKSIZE) {
1308                 printf("ZFS: I/O error - blocks larger than %llu are not "
1309                     "supported\n", SPA_MAXBLOCKSIZE);
1310                 return (EIO);
1311         }
1312
1313         /*
1314          * Note: bsize may not be a power of two here so we need to do an
1315          * actual divide rather than a bitshift.
1316          */
1317         while (buflen > 0) {
1318                 uint64_t bn = offset / bsize;
1319                 int boff = offset % bsize;
1320                 int ibn;
1321                 const blkptr_t *indbp;
1322                 blkptr_t bp;
1323
1324                 if (bn > dnode->dn_maxblkid)
1325                         return (EIO);
1326
1327                 if (dnode == dnode_cache_obj && bn == dnode_cache_bn)
1328                         goto cached;
1329
1330                 indbp = dnode->dn_blkptr;
1331                 for (i = 0; i < nlevels; i++) {
1332                         /*
1333                          * Copy the bp from the indirect array so that
1334                          * we can re-use the scratch buffer for multi-level
1335                          * objects.
1336                          */
1337                         ibn = bn >> ((nlevels - i - 1) * ibshift);
1338                         ibn &= ((1 << ibshift) - 1);
1339                         bp = indbp[ibn];
1340                         if (BP_IS_HOLE(&bp)) {
1341                                 memset(dnode_cache_buf, 0, bsize);
1342                                 break;
1343                         }
1344                         rc = zio_read(spa, &bp, dnode_cache_buf);
1345                         if (rc)
1346                                 return (rc);
1347                         indbp = (const blkptr_t *) dnode_cache_buf;
1348                 }
1349                 dnode_cache_obj = dnode;
1350                 dnode_cache_bn = bn;
1351         cached:
1352
1353                 /*
1354                  * The buffer contains our data block. Copy what we
1355                  * need from it and loop.
1356                  */ 
1357                 i = bsize - boff;
1358                 if (i > buflen) i = buflen;
1359                 memcpy(buf, &dnode_cache_buf[boff], i);
1360                 buf = ((char*) buf) + i;
1361                 offset += i;
1362                 buflen -= i;
1363         }
1364
1365         return (0);
1366 }
1367
1368 /*
1369  * Lookup a value in a microzap directory. Assumes that the zap
1370  * scratch buffer contains the directory contents.
1371  */
1372 static int
1373 mzap_lookup(const dnode_phys_t *dnode, const char *name, uint64_t *value)
1374 {
1375         const mzap_phys_t *mz;
1376         const mzap_ent_phys_t *mze;
1377         size_t size;
1378         int chunks, i;
1379
1380         /*
1381          * Microzap objects use exactly one block. Read the whole
1382          * thing.
1383          */
1384         size = dnode->dn_datablkszsec * 512;
1385
1386         mz = (const mzap_phys_t *) zap_scratch;
1387         chunks = size / MZAP_ENT_LEN - 1;
1388
1389         for (i = 0; i < chunks; i++) {
1390                 mze = &mz->mz_chunk[i];
1391                 if (!strcmp(mze->mze_name, name)) {
1392                         *value = mze->mze_value;
1393                         return (0);
1394                 }
1395         }
1396
1397         return (ENOENT);
1398 }
1399
1400 /*
1401  * Compare a name with a zap leaf entry. Return non-zero if the name
1402  * matches.
1403  */
1404 static int
1405 fzap_name_equal(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc, const char *name)
1406 {
1407         size_t namelen;
1408         const zap_leaf_chunk_t *nc;
1409         const char *p;
1410
1411         namelen = zc->l_entry.le_name_numints;
1412                         
1413         nc = &ZAP_LEAF_CHUNK(zl, zc->l_entry.le_name_chunk);
1414         p = name;
1415         while (namelen > 0) {
1416                 size_t len;
1417                 len = namelen;
1418                 if (len > ZAP_LEAF_ARRAY_BYTES)
1419                         len = ZAP_LEAF_ARRAY_BYTES;
1420                 if (memcmp(p, nc->l_array.la_array, len))
1421                         return (0);
1422                 p += len;
1423                 namelen -= len;
1424                 nc = &ZAP_LEAF_CHUNK(zl, nc->l_array.la_next);
1425         }
1426
1427         return 1;
1428 }
1429
1430 /*
1431  * Extract a uint64_t value from a zap leaf entry.
1432  */
1433 static uint64_t
1434 fzap_leaf_value(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc)
1435 {
1436         const zap_leaf_chunk_t *vc;
1437         int i;
1438         uint64_t value;
1439         const uint8_t *p;
1440
1441         vc = &ZAP_LEAF_CHUNK(zl, zc->l_entry.le_value_chunk);
1442         for (i = 0, value = 0, p = vc->l_array.la_array; i < 8; i++) {
1443                 value = (value << 8) | p[i];
1444         }
1445
1446         return value;
1447 }
1448
1449 static void
1450 stv(int len, void *addr, uint64_t value)
1451 {
1452         switch (len) {
1453         case 1:
1454                 *(uint8_t *)addr = value;
1455                 return;
1456         case 2:
1457                 *(uint16_t *)addr = value;
1458                 return;
1459         case 4:
1460                 *(uint32_t *)addr = value;
1461                 return;
1462         case 8:
1463                 *(uint64_t *)addr = value;
1464                 return;
1465         }
1466 }
1467
1468 /*
1469  * Extract a array from a zap leaf entry.
1470  */
1471 static void
1472 fzap_leaf_array(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc,
1473     uint64_t integer_size, uint64_t num_integers, void *buf)
1474 {
1475         uint64_t array_int_len = zc->l_entry.le_value_intlen;
1476         uint64_t value = 0;
1477         uint64_t *u64 = buf;
1478         char *p = buf;
1479         int len = MIN(zc->l_entry.le_value_numints, num_integers);
1480         int chunk = zc->l_entry.le_value_chunk;
1481         int byten = 0;
1482
1483         if (integer_size == 8 && len == 1) {
1484                 *u64 = fzap_leaf_value(zl, zc);
1485                 return;
1486         }
1487
1488         while (len > 0) {
1489                 struct zap_leaf_array *la = &ZAP_LEAF_CHUNK(zl, chunk).l_array;
1490                 int i;
1491
1492                 ASSERT3U(chunk, <, ZAP_LEAF_NUMCHUNKS(zl));
1493                 for (i = 0; i < ZAP_LEAF_ARRAY_BYTES && len > 0; i++) {
1494                         value = (value << 8) | la->la_array[i];
1495                         byten++;
1496                         if (byten == array_int_len) {
1497                                 stv(integer_size, p, value);
1498                                 byten = 0;
1499                                 len--;
1500                                 if (len == 0)
1501                                         return;
1502                                 p += integer_size;
1503                         }
1504                 }
1505                 chunk = la->la_next;
1506         }
1507 }
1508
1509 /*
1510  * Lookup a value in a fatzap directory. Assumes that the zap scratch
1511  * buffer contains the directory header.
1512  */
1513 static int
1514 fzap_lookup(const spa_t *spa, const dnode_phys_t *dnode, const char *name,
1515     uint64_t integer_size, uint64_t num_integers, void *value)
1516 {
1517         int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
1518         zap_phys_t zh = *(zap_phys_t *) zap_scratch;
1519         fat_zap_t z;
1520         uint64_t *ptrtbl;
1521         uint64_t hash;
1522         int rc;
1523
1524         if (zh.zap_magic != ZAP_MAGIC)
1525                 return (EIO);
1526
1527         z.zap_block_shift = ilog2(bsize);
1528         z.zap_phys = (zap_phys_t *) zap_scratch;
1529
1530         /*
1531          * Figure out where the pointer table is and read it in if necessary.
1532          */
1533         if (zh.zap_ptrtbl.zt_blk) {
1534                 rc = dnode_read(spa, dnode, zh.zap_ptrtbl.zt_blk * bsize,
1535                                zap_scratch, bsize);
1536                 if (rc)
1537                         return (rc);
1538                 ptrtbl = (uint64_t *) zap_scratch;
1539         } else {
1540                 ptrtbl = &ZAP_EMBEDDED_PTRTBL_ENT(&z, 0);
1541         }
1542
1543         hash = zap_hash(zh.zap_salt, name);
1544
1545         zap_leaf_t zl;
1546         zl.l_bs = z.zap_block_shift;
1547
1548         off_t off = ptrtbl[hash >> (64 - zh.zap_ptrtbl.zt_shift)] << zl.l_bs;
1549         zap_leaf_chunk_t *zc;
1550
1551         rc = dnode_read(spa, dnode, off, zap_scratch, bsize);
1552         if (rc)
1553                 return (rc);
1554
1555         zl.l_phys = (zap_leaf_phys_t *) zap_scratch;
1556
1557         /*
1558          * Make sure this chunk matches our hash.
1559          */
1560         if (zl.l_phys->l_hdr.lh_prefix_len > 0
1561             && zl.l_phys->l_hdr.lh_prefix
1562             != hash >> (64 - zl.l_phys->l_hdr.lh_prefix_len))
1563                 return (ENOENT);
1564
1565         /*
1566          * Hash within the chunk to find our entry.
1567          */
1568         int shift = (64 - ZAP_LEAF_HASH_SHIFT(&zl) - zl.l_phys->l_hdr.lh_prefix_len);
1569         int h = (hash >> shift) & ((1 << ZAP_LEAF_HASH_SHIFT(&zl)) - 1);
1570         h = zl.l_phys->l_hash[h];
1571         if (h == 0xffff)
1572                 return (ENOENT);
1573         zc = &ZAP_LEAF_CHUNK(&zl, h);
1574         while (zc->l_entry.le_hash != hash) {
1575                 if (zc->l_entry.le_next == 0xffff) {
1576                         zc = NULL;
1577                         break;
1578                 }
1579                 zc = &ZAP_LEAF_CHUNK(&zl, zc->l_entry.le_next);
1580         }
1581         if (fzap_name_equal(&zl, zc, name)) {
1582                 if (zc->l_entry.le_value_intlen * zc->l_entry.le_value_numints >
1583                     integer_size * num_integers)
1584                         return (E2BIG);
1585                 fzap_leaf_array(&zl, zc, integer_size, num_integers, value);
1586                 return (0);
1587         }
1588
1589         return (ENOENT);
1590 }
1591
1592 /*
1593  * Lookup a name in a zap object and return its value as a uint64_t.
1594  */
1595 static int
1596 zap_lookup(const spa_t *spa, const dnode_phys_t *dnode, const char *name,
1597     uint64_t integer_size, uint64_t num_integers, void *value)
1598 {
1599         int rc;
1600         uint64_t zap_type;
1601         size_t size = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
1602
1603         rc = dnode_read(spa, dnode, 0, zap_scratch, size);
1604         if (rc)
1605                 return (rc);
1606
1607         zap_type = *(uint64_t *) zap_scratch;
1608         if (zap_type == ZBT_MICRO)
1609                 return mzap_lookup(dnode, name, value);
1610         else if (zap_type == ZBT_HEADER) {
1611                 return fzap_lookup(spa, dnode, name, integer_size,
1612                     num_integers, value);
1613         }
1614         printf("ZFS: invalid zap_type=%d\n", (int)zap_type);
1615         return (EIO);
1616 }
1617
1618 /*
1619  * List a microzap directory. Assumes that the zap scratch buffer contains
1620  * the directory contents.
1621  */
1622 static int
1623 mzap_list(const dnode_phys_t *dnode, int (*callback)(const char *, uint64_t))
1624 {
1625         const mzap_phys_t *mz;
1626         const mzap_ent_phys_t *mze;
1627         size_t size;
1628         int chunks, i, rc;
1629
1630         /*
1631          * Microzap objects use exactly one block. Read the whole
1632          * thing.
1633          */
1634         size = dnode->dn_datablkszsec * 512;
1635         mz = (const mzap_phys_t *) zap_scratch;
1636         chunks = size / MZAP_ENT_LEN - 1;
1637
1638         for (i = 0; i < chunks; i++) {
1639                 mze = &mz->mz_chunk[i];
1640                 if (mze->mze_name[0]) {
1641                         rc = callback(mze->mze_name, mze->mze_value);
1642                         if (rc != 0)
1643                                 return (rc);
1644                 }
1645         }
1646
1647         return (0);
1648 }
1649
1650 /*
1651  * List a fatzap directory. Assumes that the zap scratch buffer contains
1652  * the directory header.
1653  */
1654 static int
1655 fzap_list(const spa_t *spa, const dnode_phys_t *dnode, int (*callback)(const char *, uint64_t))
1656 {
1657         int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
1658         zap_phys_t zh = *(zap_phys_t *) zap_scratch;
1659         fat_zap_t z;
1660         int i, j, rc;
1661
1662         if (zh.zap_magic != ZAP_MAGIC)
1663                 return (EIO);
1664
1665         z.zap_block_shift = ilog2(bsize);
1666         z.zap_phys = (zap_phys_t *) zap_scratch;
1667
1668         /*
1669          * This assumes that the leaf blocks start at block 1. The
1670          * documentation isn't exactly clear on this.
1671          */
1672         zap_leaf_t zl;
1673         zl.l_bs = z.zap_block_shift;
1674         for (i = 0; i < zh.zap_num_leafs; i++) {
1675                 off_t off = (i + 1) << zl.l_bs;
1676                 char name[256], *p;
1677                 uint64_t value;
1678
1679                 if (dnode_read(spa, dnode, off, zap_scratch, bsize))
1680                         return (EIO);
1681
1682                 zl.l_phys = (zap_leaf_phys_t *) zap_scratch;
1683
1684                 for (j = 0; j < ZAP_LEAF_NUMCHUNKS(&zl); j++) {
1685                         zap_leaf_chunk_t *zc, *nc;
1686                         int namelen;
1687
1688                         zc = &ZAP_LEAF_CHUNK(&zl, j);
1689                         if (zc->l_entry.le_type != ZAP_CHUNK_ENTRY)
1690                                 continue;
1691                         namelen = zc->l_entry.le_name_numints;
1692                         if (namelen > sizeof(name))
1693                                 namelen = sizeof(name);
1694
1695                         /*
1696                          * Paste the name back together.
1697                          */
1698                         nc = &ZAP_LEAF_CHUNK(&zl, zc->l_entry.le_name_chunk);
1699                         p = name;
1700                         while (namelen > 0) {
1701                                 int len;
1702                                 len = namelen;
1703                                 if (len > ZAP_LEAF_ARRAY_BYTES)
1704                                         len = ZAP_LEAF_ARRAY_BYTES;
1705                                 memcpy(p, nc->l_array.la_array, len);
1706                                 p += len;
1707                                 namelen -= len;
1708                                 nc = &ZAP_LEAF_CHUNK(&zl, nc->l_array.la_next);
1709                         }
1710
1711                         /*
1712                          * Assume the first eight bytes of the value are
1713                          * a uint64_t.
1714                          */
1715                         value = fzap_leaf_value(&zl, zc);
1716
1717                         //printf("%s 0x%jx\n", name, (uintmax_t)value);
1718                         rc = callback((const char *)name, value);
1719                         if (rc != 0)
1720                                 return (rc);
1721                 }
1722         }
1723
1724         return (0);
1725 }
1726
1727 static int zfs_printf(const char *name, uint64_t value __unused)
1728 {
1729
1730         printf("%s\n", name);
1731
1732         return (0);
1733 }
1734
1735 /*
1736  * List a zap directory.
1737  */
1738 static int
1739 zap_list(const spa_t *spa, const dnode_phys_t *dnode)
1740 {
1741         uint64_t zap_type;
1742         size_t size = dnode->dn_datablkszsec * 512;
1743
1744         if (dnode_read(spa, dnode, 0, zap_scratch, size))
1745                 return (EIO);
1746
1747         zap_type = *(uint64_t *) zap_scratch;
1748         if (zap_type == ZBT_MICRO)
1749                 return mzap_list(dnode, zfs_printf);
1750         else
1751                 return fzap_list(spa, dnode, zfs_printf);
1752 }
1753
1754 static int
1755 objset_get_dnode(const spa_t *spa, const objset_phys_t *os, uint64_t objnum, dnode_phys_t *dnode)
1756 {
1757         off_t offset;
1758
1759         offset = objnum * sizeof(dnode_phys_t);
1760         return dnode_read(spa, &os->os_meta_dnode, offset,
1761                 dnode, sizeof(dnode_phys_t));
1762 }
1763
1764 static int
1765 mzap_rlookup(const spa_t *spa, const dnode_phys_t *dnode, char *name, uint64_t value)
1766 {
1767         const mzap_phys_t *mz;
1768         const mzap_ent_phys_t *mze;
1769         size_t size;
1770         int chunks, i;
1771
1772         /*
1773          * Microzap objects use exactly one block. Read the whole
1774          * thing.
1775          */
1776         size = dnode->dn_datablkszsec * 512;
1777
1778         mz = (const mzap_phys_t *) zap_scratch;
1779         chunks = size / MZAP_ENT_LEN - 1;
1780
1781         for (i = 0; i < chunks; i++) {
1782                 mze = &mz->mz_chunk[i];
1783                 if (value == mze->mze_value) {
1784                         strcpy(name, mze->mze_name);
1785                         return (0);
1786                 }
1787         }
1788
1789         return (ENOENT);
1790 }
1791
1792 static void
1793 fzap_name_copy(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc, char *name)
1794 {
1795         size_t namelen;
1796         const zap_leaf_chunk_t *nc;
1797         char *p;
1798
1799         namelen = zc->l_entry.le_name_numints;
1800
1801         nc = &ZAP_LEAF_CHUNK(zl, zc->l_entry.le_name_chunk);
1802         p = name;
1803         while (namelen > 0) {
1804                 size_t len;
1805                 len = namelen;
1806                 if (len > ZAP_LEAF_ARRAY_BYTES)
1807                         len = ZAP_LEAF_ARRAY_BYTES;
1808                 memcpy(p, nc->l_array.la_array, len);
1809                 p += len;
1810                 namelen -= len;
1811                 nc = &ZAP_LEAF_CHUNK(zl, nc->l_array.la_next);
1812         }
1813
1814         *p = '\0';
1815 }
1816
1817 static int
1818 fzap_rlookup(const spa_t *spa, const dnode_phys_t *dnode, char *name, uint64_t value)
1819 {
1820         int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
1821         zap_phys_t zh = *(zap_phys_t *) zap_scratch;
1822         fat_zap_t z;
1823         int i, j;
1824
1825         if (zh.zap_magic != ZAP_MAGIC)
1826                 return (EIO);
1827
1828         z.zap_block_shift = ilog2(bsize);
1829         z.zap_phys = (zap_phys_t *) zap_scratch;
1830
1831         /*
1832          * This assumes that the leaf blocks start at block 1. The
1833          * documentation isn't exactly clear on this.
1834          */
1835         zap_leaf_t zl;
1836         zl.l_bs = z.zap_block_shift;
1837         for (i = 0; i < zh.zap_num_leafs; i++) {
1838                 off_t off = (i + 1) << zl.l_bs;
1839
1840                 if (dnode_read(spa, dnode, off, zap_scratch, bsize))
1841                         return (EIO);
1842
1843                 zl.l_phys = (zap_leaf_phys_t *) zap_scratch;
1844
1845                 for (j = 0; j < ZAP_LEAF_NUMCHUNKS(&zl); j++) {
1846                         zap_leaf_chunk_t *zc;
1847
1848                         zc = &ZAP_LEAF_CHUNK(&zl, j);
1849                         if (zc->l_entry.le_type != ZAP_CHUNK_ENTRY)
1850                                 continue;
1851                         if (zc->l_entry.le_value_intlen != 8 ||
1852                             zc->l_entry.le_value_numints != 1)
1853                                 continue;
1854
1855                         if (fzap_leaf_value(&zl, zc) == value) {
1856                                 fzap_name_copy(&zl, zc, name);
1857                                 return (0);
1858                         }
1859                 }
1860         }
1861
1862         return (ENOENT);
1863 }
1864
1865 static int
1866 zap_rlookup(const spa_t *spa, const dnode_phys_t *dnode, char *name, uint64_t value)
1867 {
1868         int rc;
1869         uint64_t zap_type;
1870         size_t size = dnode->dn_datablkszsec * 512;
1871
1872         rc = dnode_read(spa, dnode, 0, zap_scratch, size);
1873         if (rc)
1874                 return (rc);
1875
1876         zap_type = *(uint64_t *) zap_scratch;
1877         if (zap_type == ZBT_MICRO)
1878                 return mzap_rlookup(spa, dnode, name, value);
1879         else
1880                 return fzap_rlookup(spa, dnode, name, value);
1881 }
1882
1883 static int
1884 zfs_rlookup(const spa_t *spa, uint64_t objnum, char *result)
1885 {
1886         char name[256];
1887         char component[256];
1888         uint64_t dir_obj, parent_obj, child_dir_zapobj;
1889         dnode_phys_t child_dir_zap, dataset, dir, parent;
1890         dsl_dir_phys_t *dd;
1891         dsl_dataset_phys_t *ds;
1892         char *p;
1893         int len;
1894
1895         p = &name[sizeof(name) - 1];
1896         *p = '\0';
1897
1898         if (objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset)) {
1899                 printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
1900                 return (EIO);
1901         }
1902         ds = (dsl_dataset_phys_t *)&dataset.dn_bonus;
1903         dir_obj = ds->ds_dir_obj;
1904
1905         for (;;) {
1906                 if (objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir) != 0)
1907                         return (EIO);
1908                 dd = (dsl_dir_phys_t *)&dir.dn_bonus;
1909
1910                 /* Actual loop condition. */
1911                 parent_obj  = dd->dd_parent_obj;
1912                 if (parent_obj == 0)
1913                         break;
1914
1915                 if (objset_get_dnode(spa, &spa->spa_mos, parent_obj, &parent) != 0)
1916                         return (EIO);
1917                 dd = (dsl_dir_phys_t *)&parent.dn_bonus;
1918                 child_dir_zapobj = dd->dd_child_dir_zapobj;
1919                 if (objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj, &child_dir_zap) != 0)
1920                         return (EIO);
1921                 if (zap_rlookup(spa, &child_dir_zap, component, dir_obj) != 0)
1922                         return (EIO);
1923
1924                 len = strlen(component);
1925                 p -= len;
1926                 memcpy(p, component, len);
1927                 --p;
1928                 *p = '/';
1929
1930                 /* Actual loop iteration. */
1931                 dir_obj = parent_obj;
1932         }
1933
1934         if (*p != '\0')
1935                 ++p;
1936         strcpy(result, p);
1937
1938         return (0);
1939 }
1940
1941 static int
1942 zfs_lookup_dataset(const spa_t *spa, const char *name, uint64_t *objnum)
1943 {
1944         char element[256];
1945         uint64_t dir_obj, child_dir_zapobj;
1946         dnode_phys_t child_dir_zap, dir;
1947         dsl_dir_phys_t *dd;
1948         const char *p, *q;
1949
1950         if (objset_get_dnode(spa, &spa->spa_mos, DMU_POOL_DIRECTORY_OBJECT, &dir))
1951                 return (EIO);
1952         if (zap_lookup(spa, &dir, DMU_POOL_ROOT_DATASET, sizeof (dir_obj),
1953             1, &dir_obj))
1954                 return (EIO);
1955
1956         p = name;
1957         for (;;) {
1958                 if (objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir))
1959                         return (EIO);
1960                 dd = (dsl_dir_phys_t *)&dir.dn_bonus;
1961
1962                 while (*p == '/')
1963                         p++;
1964                 /* Actual loop condition #1. */
1965                 if (*p == '\0')
1966                         break;
1967
1968                 q = strchr(p, '/');
1969                 if (q) {
1970                         memcpy(element, p, q - p);
1971                         element[q - p] = '\0';
1972                         p = q + 1;
1973                 } else {
1974                         strcpy(element, p);
1975                         p += strlen(p);
1976                 }
1977
1978                 child_dir_zapobj = dd->dd_child_dir_zapobj;
1979                 if (objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj, &child_dir_zap) != 0)
1980                         return (EIO);
1981
1982                 /* Actual loop condition #2. */
1983                 if (zap_lookup(spa, &child_dir_zap, element, sizeof (dir_obj),
1984                     1, &dir_obj) != 0)
1985                         return (ENOENT);
1986         }
1987
1988         *objnum = dd->dd_head_dataset_obj;
1989         return (0);
1990 }
1991
1992 #ifndef BOOT2
1993 static int
1994 zfs_list_dataset(const spa_t *spa, uint64_t objnum/*, int pos, char *entry*/)
1995 {
1996         uint64_t dir_obj, child_dir_zapobj;
1997         dnode_phys_t child_dir_zap, dir, dataset;
1998         dsl_dataset_phys_t *ds;
1999         dsl_dir_phys_t *dd;
2000
2001         if (objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset)) {
2002                 printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
2003                 return (EIO);
2004         }
2005         ds = (dsl_dataset_phys_t *) &dataset.dn_bonus;
2006         dir_obj = ds->ds_dir_obj;
2007
2008         if (objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir)) {
2009                 printf("ZFS: can't find dirobj %ju\n", (uintmax_t)dir_obj);
2010                 return (EIO);
2011         }
2012         dd = (dsl_dir_phys_t *)&dir.dn_bonus;
2013
2014         child_dir_zapobj = dd->dd_child_dir_zapobj;
2015         if (objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj, &child_dir_zap) != 0) {
2016                 printf("ZFS: can't find child zap %ju\n", (uintmax_t)dir_obj);
2017                 return (EIO);
2018         }
2019
2020         return (zap_list(spa, &child_dir_zap) != 0);
2021 }
2022
2023 int
2024 zfs_callback_dataset(const spa_t *spa, uint64_t objnum, int (*callback)(const char *, uint64_t))
2025 {
2026         uint64_t dir_obj, child_dir_zapobj, zap_type;
2027         dnode_phys_t child_dir_zap, dir, dataset;
2028         dsl_dataset_phys_t *ds;
2029         dsl_dir_phys_t *dd;
2030         int err;
2031
2032         err = objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset);
2033         if (err != 0) {
2034                 printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
2035                 return (err);
2036         }
2037         ds = (dsl_dataset_phys_t *) &dataset.dn_bonus;
2038         dir_obj = ds->ds_dir_obj;
2039
2040         err = objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir);
2041         if (err != 0) {
2042                 printf("ZFS: can't find dirobj %ju\n", (uintmax_t)dir_obj);
2043                 return (err);
2044         }
2045         dd = (dsl_dir_phys_t *)&dir.dn_bonus;
2046
2047         child_dir_zapobj = dd->dd_child_dir_zapobj;
2048         err = objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj, &child_dir_zap);
2049         if (err != 0) {
2050                 printf("ZFS: can't find child zap %ju\n", (uintmax_t)dir_obj);
2051                 return (err);
2052         }
2053
2054         err = dnode_read(spa, &child_dir_zap, 0, zap_scratch, child_dir_zap.dn_datablkszsec * 512);
2055         if (err != 0)
2056                 return (err);
2057
2058         zap_type = *(uint64_t *) zap_scratch;
2059         if (zap_type == ZBT_MICRO)
2060                 return mzap_list(&child_dir_zap, callback);
2061         else
2062                 return fzap_list(spa, &child_dir_zap, callback);
2063 }
2064 #endif
2065
2066 /*
2067  * Find the object set given the object number of its dataset object
2068  * and return its details in *objset
2069  */
2070 static int
2071 zfs_mount_dataset(const spa_t *spa, uint64_t objnum, objset_phys_t *objset)
2072 {
2073         dnode_phys_t dataset;
2074         dsl_dataset_phys_t *ds;
2075
2076         if (objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset)) {
2077                 printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
2078                 return (EIO);
2079         }
2080
2081         ds = (dsl_dataset_phys_t *) &dataset.dn_bonus;
2082         if (zio_read(spa, &ds->ds_bp, objset)) {
2083                 printf("ZFS: can't read object set for dataset %ju\n",
2084                     (uintmax_t)objnum);
2085                 return (EIO);
2086         }
2087
2088         return (0);
2089 }
2090
2091 /*
2092  * Find the object set pointed to by the BOOTFS property or the root
2093  * dataset if there is none and return its details in *objset
2094  */
2095 static int
2096 zfs_get_root(const spa_t *spa, uint64_t *objid)
2097 {
2098         dnode_phys_t dir, propdir;
2099         uint64_t props, bootfs, root;
2100
2101         *objid = 0;
2102
2103         /*
2104          * Start with the MOS directory object.
2105          */
2106         if (objset_get_dnode(spa, &spa->spa_mos, DMU_POOL_DIRECTORY_OBJECT, &dir)) {
2107                 printf("ZFS: can't read MOS object directory\n");
2108                 return (EIO);
2109         }
2110
2111         /*
2112          * Lookup the pool_props and see if we can find a bootfs.
2113          */
2114         if (zap_lookup(spa, &dir, DMU_POOL_PROPS, sizeof (props), 1, &props) == 0
2115              && objset_get_dnode(spa, &spa->spa_mos, props, &propdir) == 0
2116              && zap_lookup(spa, &propdir, "bootfs", sizeof (bootfs), 1, &bootfs) == 0
2117              && bootfs != 0)
2118         {
2119                 *objid = bootfs;
2120                 return (0);
2121         }
2122         /*
2123          * Lookup the root dataset directory
2124          */
2125         if (zap_lookup(spa, &dir, DMU_POOL_ROOT_DATASET, sizeof (root), 1, &root)
2126             || objset_get_dnode(spa, &spa->spa_mos, root, &dir)) {
2127                 printf("ZFS: can't find root dsl_dir\n");
2128                 return (EIO);
2129         }
2130
2131         /*
2132          * Use the information from the dataset directory's bonus buffer
2133          * to find the dataset object and from that the object set itself.
2134          */
2135         dsl_dir_phys_t *dd = (dsl_dir_phys_t *) &dir.dn_bonus;
2136         *objid = dd->dd_head_dataset_obj;
2137         return (0);
2138 }
2139
2140 static int
2141 zfs_mount(const spa_t *spa, uint64_t rootobj, struct zfsmount *mount)
2142 {
2143
2144         mount->spa = spa;
2145
2146         /*
2147          * Find the root object set if not explicitly provided
2148          */
2149         if (rootobj == 0 && zfs_get_root(spa, &rootobj)) {
2150                 printf("ZFS: can't find root filesystem\n");
2151                 return (EIO);
2152         }
2153
2154         if (zfs_mount_dataset(spa, rootobj, &mount->objset)) {
2155                 printf("ZFS: can't open root filesystem\n");
2156                 return (EIO);
2157         }
2158
2159         mount->rootobj = rootobj;
2160
2161         return (0);
2162 }
2163
2164 /*
2165  * callback function for feature name checks.
2166  */
2167 static int
2168 check_feature(const char *name, uint64_t value)
2169 {
2170         int i;
2171
2172         if (value == 0)
2173                 return (0);
2174         if (name[0] == '\0')
2175                 return (0);
2176
2177         for (i = 0; features_for_read[i] != NULL; i++) {
2178                 if (strcmp(name, features_for_read[i]) == 0)
2179                         return (0);
2180         }
2181         printf("ZFS: unsupported feature: %s\n", name);
2182         return (EIO);
2183 }
2184
2185 /*
2186  * Checks whether the MOS features that are active are supported.
2187  */
2188 static int
2189 check_mos_features(const spa_t *spa)
2190 {
2191         dnode_phys_t dir;
2192         uint64_t objnum, zap_type;
2193         size_t size;
2194         int rc;
2195
2196         if ((rc = objset_get_dnode(spa, &spa->spa_mos, DMU_OT_OBJECT_DIRECTORY,
2197             &dir)) != 0)
2198                 return (rc);
2199         if ((rc = zap_lookup(spa, &dir, DMU_POOL_FEATURES_FOR_READ,
2200             sizeof (objnum), 1, &objnum)) != 0) {
2201                 /*
2202                  * It is older pool without features. As we have already
2203                  * tested the label, just return without raising the error.
2204                  */
2205                 return (0);
2206         }
2207
2208         if ((rc = objset_get_dnode(spa, &spa->spa_mos, objnum, &dir)) != 0)
2209                 return (rc);
2210
2211         if (dir.dn_type != DMU_OTN_ZAP_METADATA)
2212                 return (EIO);
2213
2214         size = dir.dn_datablkszsec * 512;
2215         if (dnode_read(spa, &dir, 0, zap_scratch, size))
2216                 return (EIO);
2217
2218         zap_type = *(uint64_t *) zap_scratch;
2219         if (zap_type == ZBT_MICRO)
2220                 rc = mzap_list(&dir, check_feature);
2221         else
2222                 rc = fzap_list(spa, &dir, check_feature);
2223
2224         return (rc);
2225 }
2226
2227 static int
2228 zfs_spa_init(spa_t *spa)
2229 {
2230         dnode_phys_t dir;
2231         int rc;
2232
2233         if (zio_read(spa, &spa->spa_uberblock.ub_rootbp, &spa->spa_mos)) {
2234                 printf("ZFS: can't read MOS of pool %s\n", spa->spa_name);
2235                 return (EIO);
2236         }
2237         if (spa->spa_mos.os_type != DMU_OST_META) {
2238                 printf("ZFS: corrupted MOS of pool %s\n", spa->spa_name);
2239                 return (EIO);
2240         }
2241
2242         if (objset_get_dnode(spa, &spa->spa_mos, DMU_POOL_DIRECTORY_OBJECT,
2243             &dir)) {
2244                 printf("ZFS: failed to read pool %s directory object\n",
2245                     spa->spa_name);
2246                 return (EIO);
2247         }
2248         /* this is allowed to fail, older pools do not have salt */
2249         rc = zap_lookup(spa, &dir, DMU_POOL_CHECKSUM_SALT, 1,
2250             sizeof (spa->spa_cksum_salt.zcs_bytes),
2251             spa->spa_cksum_salt.zcs_bytes);
2252
2253         rc = check_mos_features(spa);
2254         if (rc != 0) {
2255                 printf("ZFS: pool %s is not supported\n", spa->spa_name);
2256         }
2257
2258         return (rc);
2259 }
2260
2261 static int
2262 zfs_dnode_stat(const spa_t *spa, dnode_phys_t *dn, struct stat *sb)
2263 {
2264
2265         if (dn->dn_bonustype != DMU_OT_SA) {
2266                 znode_phys_t *zp = (znode_phys_t *)dn->dn_bonus;
2267
2268                 sb->st_mode = zp->zp_mode;
2269                 sb->st_uid = zp->zp_uid;
2270                 sb->st_gid = zp->zp_gid;
2271                 sb->st_size = zp->zp_size;
2272         } else {
2273                 sa_hdr_phys_t *sahdrp;
2274                 int hdrsize;
2275                 size_t size = 0;
2276                 void *buf = NULL;
2277
2278                 if (dn->dn_bonuslen != 0)
2279                         sahdrp = (sa_hdr_phys_t *)DN_BONUS(dn);
2280                 else {
2281                         if ((dn->dn_flags & DNODE_FLAG_SPILL_BLKPTR) != 0) {
2282                                 blkptr_t *bp = &dn->dn_spill;
2283                                 int error;
2284
2285                                 size = BP_GET_LSIZE(bp);
2286                                 buf = zfs_alloc(size);
2287                                 error = zio_read(spa, bp, buf);
2288                                 if (error != 0) {
2289                                         zfs_free(buf, size);
2290                                         return (error);
2291                                 }
2292                                 sahdrp = buf;
2293                         } else {
2294                                 return (EIO);
2295                         }
2296                 }
2297                 hdrsize = SA_HDR_SIZE(sahdrp);
2298                 sb->st_mode = *(uint64_t *)((char *)sahdrp + hdrsize +
2299                     SA_MODE_OFFSET);
2300                 sb->st_uid = *(uint64_t *)((char *)sahdrp + hdrsize +
2301                     SA_UID_OFFSET);
2302                 sb->st_gid = *(uint64_t *)((char *)sahdrp + hdrsize +
2303                     SA_GID_OFFSET);
2304                 sb->st_size = *(uint64_t *)((char *)sahdrp + hdrsize +
2305                     SA_SIZE_OFFSET);
2306                 if (buf != NULL)
2307                         zfs_free(buf, size);
2308         }
2309
2310         return (0);
2311 }
2312
2313 static int
2314 zfs_dnode_readlink(const spa_t *spa, dnode_phys_t *dn, char *path, size_t psize)
2315 {
2316         int rc = 0;
2317
2318         if (dn->dn_bonustype == DMU_OT_SA) {
2319                 sa_hdr_phys_t *sahdrp = NULL;
2320                 size_t size = 0;
2321                 void *buf = NULL;
2322                 int hdrsize;
2323                 char *p;
2324
2325                 if (dn->dn_bonuslen != 0)
2326                         sahdrp = (sa_hdr_phys_t *)DN_BONUS(dn);
2327                 else {
2328                         blkptr_t *bp;
2329
2330                         if ((dn->dn_flags & DNODE_FLAG_SPILL_BLKPTR) == 0)
2331                                 return (EIO);
2332                         bp = &dn->dn_spill;
2333
2334                         size = BP_GET_LSIZE(bp);
2335                         buf = zfs_alloc(size);
2336                         rc = zio_read(spa, bp, buf);
2337                         if (rc != 0) {
2338                                 zfs_free(buf, size);
2339                                 return (rc);
2340                         }
2341                         sahdrp = buf;
2342                 }
2343                 hdrsize = SA_HDR_SIZE(sahdrp);
2344                 p = (char *)((uintptr_t)sahdrp + hdrsize + SA_SYMLINK_OFFSET);
2345                 memcpy(path, p, psize);
2346                 if (buf != NULL)
2347                         zfs_free(buf, size);
2348                 return (0);
2349         }
2350         /*
2351          * Second test is purely to silence bogus compiler
2352          * warning about accessing past the end of dn_bonus.
2353          */
2354         if (psize + sizeof(znode_phys_t) <= dn->dn_bonuslen &&
2355             sizeof(znode_phys_t) <= sizeof(dn->dn_bonus)) {
2356                 memcpy(path, &dn->dn_bonus[sizeof(znode_phys_t)], psize);
2357         } else {
2358                 rc = dnode_read(spa, dn, 0, path, psize);
2359         }
2360         return (rc);
2361 }
2362
2363 struct obj_list {
2364         uint64_t                objnum;
2365         STAILQ_ENTRY(obj_list)  entry;
2366 };
2367
2368 /*
2369  * Lookup a file and return its dnode.
2370  */
2371 static int
2372 zfs_lookup(const struct zfsmount *mount, const char *upath, dnode_phys_t *dnode)
2373 {
2374         int rc;
2375         uint64_t objnum;
2376         const spa_t *spa;
2377         dnode_phys_t dn;
2378         const char *p, *q;
2379         char element[256];
2380         char path[1024];
2381         int symlinks_followed = 0;
2382         struct stat sb;
2383         struct obj_list *entry, *tentry;
2384         STAILQ_HEAD(, obj_list) on_cache = STAILQ_HEAD_INITIALIZER(on_cache);
2385
2386         spa = mount->spa;
2387         if (mount->objset.os_type != DMU_OST_ZFS) {
2388                 printf("ZFS: unexpected object set type %ju\n",
2389                     (uintmax_t)mount->objset.os_type);
2390                 return (EIO);
2391         }
2392
2393         if ((entry = malloc(sizeof(struct obj_list))) == NULL)
2394                 return (ENOMEM);
2395
2396         /*
2397          * Get the root directory dnode.
2398          */
2399         rc = objset_get_dnode(spa, &mount->objset, MASTER_NODE_OBJ, &dn);
2400         if (rc) {
2401                 free(entry);
2402                 return (rc);
2403         }
2404
2405         rc = zap_lookup(spa, &dn, ZFS_ROOT_OBJ, sizeof (objnum), 1, &objnum);
2406         if (rc) {
2407                 free(entry);
2408                 return (rc);
2409         }
2410         entry->objnum = objnum;
2411         STAILQ_INSERT_HEAD(&on_cache, entry, entry);
2412
2413         rc = objset_get_dnode(spa, &mount->objset, objnum, &dn);
2414         if (rc != 0)
2415                 goto done;
2416
2417         p = upath;
2418         while (p && *p) {
2419                 rc = objset_get_dnode(spa, &mount->objset, objnum, &dn);
2420                 if (rc != 0)
2421                         goto done;
2422
2423                 while (*p == '/')
2424                         p++;
2425                 if (*p == '\0')
2426                         break;
2427                 q = p;
2428                 while (*q != '\0' && *q != '/')
2429                         q++;
2430
2431                 /* skip dot */
2432                 if (p + 1 == q && p[0] == '.') {
2433                         p++;
2434                         continue;
2435                 }
2436                 /* double dot */
2437                 if (p + 2 == q && p[0] == '.' && p[1] == '.') {
2438                         p += 2;
2439                         if (STAILQ_FIRST(&on_cache) ==
2440                             STAILQ_LAST(&on_cache, obj_list, entry)) {
2441                                 rc = ENOENT;
2442                                 goto done;
2443                         }
2444                         entry = STAILQ_FIRST(&on_cache);
2445                         STAILQ_REMOVE_HEAD(&on_cache, entry);
2446                         free(entry);
2447                         objnum = (STAILQ_FIRST(&on_cache))->objnum;
2448                         continue;
2449                 }
2450                 if (q - p + 1 > sizeof(element)) {
2451                         rc = ENAMETOOLONG;
2452                         goto done;
2453                 }
2454                 memcpy(element, p, q - p);
2455                 element[q - p] = 0;
2456                 p = q;
2457
2458                 if ((rc = zfs_dnode_stat(spa, &dn, &sb)) != 0)
2459                         goto done;
2460                 if (!S_ISDIR(sb.st_mode)) {
2461                         rc = ENOTDIR;
2462                         goto done;
2463                 }
2464
2465                 rc = zap_lookup(spa, &dn, element, sizeof (objnum), 1, &objnum);
2466                 if (rc)
2467                         goto done;
2468                 objnum = ZFS_DIRENT_OBJ(objnum);
2469
2470                 if ((entry = malloc(sizeof(struct obj_list))) == NULL) {
2471                         rc = ENOMEM;
2472                         goto done;
2473                 }
2474                 entry->objnum = objnum;
2475                 STAILQ_INSERT_HEAD(&on_cache, entry, entry);
2476                 rc = objset_get_dnode(spa, &mount->objset, objnum, &dn);
2477                 if (rc)
2478                         goto done;
2479
2480                 /*
2481                  * Check for symlink.
2482                  */
2483                 rc = zfs_dnode_stat(spa, &dn, &sb);
2484                 if (rc)
2485                         goto done;
2486                 if (S_ISLNK(sb.st_mode)) {
2487                         if (symlinks_followed > 10) {
2488                                 rc = EMLINK;
2489                                 goto done;
2490                         }
2491                         symlinks_followed++;
2492
2493                         /*
2494                          * Read the link value and copy the tail of our
2495                          * current path onto the end.
2496                          */
2497                         if (sb.st_size + strlen(p) + 1 > sizeof(path)) {
2498                                 rc = ENAMETOOLONG;
2499                                 goto done;
2500                         }
2501                         strcpy(&path[sb.st_size], p);
2502
2503                         rc = zfs_dnode_readlink(spa, &dn, path, sb.st_size);
2504                         if (rc != 0)
2505                                 goto done;
2506
2507                         /*
2508                          * Restart with the new path, starting either at
2509                          * the root or at the parent depending whether or
2510                          * not the link is relative.
2511                          */
2512                         p = path;
2513                         if (*p == '/') {
2514                                 while (STAILQ_FIRST(&on_cache) !=
2515                                     STAILQ_LAST(&on_cache, obj_list, entry)) {
2516                                         entry = STAILQ_FIRST(&on_cache);
2517                                         STAILQ_REMOVE_HEAD(&on_cache, entry);
2518                                         free(entry);
2519                                 }
2520                         } else {
2521                                 entry = STAILQ_FIRST(&on_cache);
2522                                 STAILQ_REMOVE_HEAD(&on_cache, entry);
2523                                 free(entry);
2524                         }
2525                         objnum = (STAILQ_FIRST(&on_cache))->objnum;
2526                 }
2527         }
2528
2529         *dnode = dn;
2530 done:
2531         STAILQ_FOREACH_SAFE(entry, &on_cache, entry, tentry)
2532                 free(entry);
2533         return (rc);
2534 }