xref: /freebsd/usr.sbin/makefs/zfs/fs.c (revision 058ac3e8063366dafa634d9107642e12b038bf09)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2022 The FreeBSD Foundation
5  *
6  * This software was developed by Mark Johnston under sponsorship from
7  * the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions are
11  * met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/stat.h>
32 
33 #include <assert.h>
34 #include <dirent.h>
35 #include <fcntl.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 
40 #include <util.h>
41 
42 #include "makefs.h"
43 #include "zfs.h"
44 
45 typedef struct {
46 	const char	*name;
47 	unsigned int	id;
48 	uint16_t	size;
49 	sa_bswap_type_t	bs;
50 } zfs_sattr_t;
51 
52 typedef struct zfs_fs {
53 	zfs_objset_t	*os;
54 
55 	/* Offset table for system attributes, indexed by a zpl_attr_t. */
56 	uint16_t	*saoffs;
57 	size_t		sacnt;
58 	const zfs_sattr_t *satab;
59 } zfs_fs_t;
60 
61 /*
62  * The order of the attributes doesn't matter, this is simply the one hard-coded
63  * by OpenZFS, based on a zdb dump of the SA_REGISTRY table.
64  */
65 typedef enum zpl_attr {
66 	ZPL_ATIME,
67 	ZPL_MTIME,
68 	ZPL_CTIME,
69 	ZPL_CRTIME,
70 	ZPL_GEN,
71 	ZPL_MODE,
72 	ZPL_SIZE,
73 	ZPL_PARENT,
74 	ZPL_LINKS,
75 	ZPL_XATTR,
76 	ZPL_RDEV,
77 	ZPL_FLAGS,
78 	ZPL_UID,
79 	ZPL_GID,
80 	ZPL_PAD,
81 	ZPL_ZNODE_ACL,
82 	ZPL_DACL_COUNT,
83 	ZPL_SYMLINK,
84 	ZPL_SCANSTAMP,
85 	ZPL_DACL_ACES,
86 	ZPL_DXATTR,
87 	ZPL_PROJID,
88 } zpl_attr_t;
89 
90 /*
91  * This table must be kept in sync with zpl_attr_layout[] and zpl_attr_t.
92  */
93 static const zfs_sattr_t zpl_attrs[] = {
94 #define	_ZPL_ATTR(n, s, b)	{ .name = #n, .id = n, .size = s, .bs = b }
95 	_ZPL_ATTR(ZPL_ATIME, sizeof(uint64_t) * 2, SA_UINT64_ARRAY),
96 	_ZPL_ATTR(ZPL_MTIME, sizeof(uint64_t) * 2, SA_UINT64_ARRAY),
97 	_ZPL_ATTR(ZPL_CTIME, sizeof(uint64_t) * 2, SA_UINT64_ARRAY),
98 	_ZPL_ATTR(ZPL_CRTIME, sizeof(uint64_t) * 2, SA_UINT64_ARRAY),
99 	_ZPL_ATTR(ZPL_GEN, sizeof(uint64_t), SA_UINT64_ARRAY),
100 	_ZPL_ATTR(ZPL_MODE, sizeof(uint64_t), SA_UINT64_ARRAY),
101 	_ZPL_ATTR(ZPL_SIZE, sizeof(uint64_t), SA_UINT64_ARRAY),
102 	_ZPL_ATTR(ZPL_PARENT, sizeof(uint64_t), SA_UINT64_ARRAY),
103 	_ZPL_ATTR(ZPL_LINKS, sizeof(uint64_t), SA_UINT64_ARRAY),
104 	_ZPL_ATTR(ZPL_XATTR, sizeof(uint64_t), SA_UINT64_ARRAY),
105 	_ZPL_ATTR(ZPL_RDEV, sizeof(uint64_t), SA_UINT64_ARRAY),
106 	_ZPL_ATTR(ZPL_FLAGS, sizeof(uint64_t), SA_UINT64_ARRAY),
107 	_ZPL_ATTR(ZPL_UID, sizeof(uint64_t), SA_UINT64_ARRAY),
108 	_ZPL_ATTR(ZPL_GID, sizeof(uint64_t), SA_UINT64_ARRAY),
109 	_ZPL_ATTR(ZPL_PAD, sizeof(uint64_t), SA_UINT64_ARRAY),
110 	_ZPL_ATTR(ZPL_ZNODE_ACL, 88, SA_UINT64_ARRAY),
111 	_ZPL_ATTR(ZPL_DACL_COUNT, sizeof(uint64_t), SA_UINT64_ARRAY),
112 	_ZPL_ATTR(ZPL_SYMLINK, 0, SA_UINT8_ARRAY),
113 	_ZPL_ATTR(ZPL_SCANSTAMP, sizeof(uint64_t) * 4, SA_UINT8_ARRAY),
114 	_ZPL_ATTR(ZPL_DACL_ACES, 0, SA_ACL),
115 	_ZPL_ATTR(ZPL_DXATTR, 0, SA_UINT8_ARRAY),
116 	_ZPL_ATTR(ZPL_PROJID, sizeof(uint64_t), SA_UINT64_ARRAY),
117 #undef ZPL_ATTR
118 };
119 
120 /*
121  * This layout matches that of a filesystem created using OpenZFS on FreeBSD.
122  * It need not match in general, but FreeBSD's loader doesn't bother parsing the
123  * layout and just hard-codes attribute offsets.
124  */
125 static const sa_attr_type_t zpl_attr_layout[] = {
126 	ZPL_MODE,
127 	ZPL_SIZE,
128 	ZPL_GEN,
129 	ZPL_UID,
130 	ZPL_GID,
131 	ZPL_PARENT,
132 	ZPL_FLAGS,
133 	ZPL_ATIME,
134 	ZPL_MTIME,
135 	ZPL_CTIME,
136 	ZPL_CRTIME,
137 	ZPL_LINKS,
138 	ZPL_DACL_COUNT,
139 	ZPL_DACL_ACES,
140 	ZPL_SYMLINK,
141 };
142 
143 /*
144  * Keys for the ZPL attribute tables in the SA layout ZAP.  The first two
145  * indices are reserved for legacy attribute encoding.
146  */
147 #define	SA_LAYOUT_INDEX_DEFAULT	2
148 #define	SA_LAYOUT_INDEX_SYMLINK	3
149 
150 struct fs_populate_dir {
151 	SLIST_ENTRY(fs_populate_dir) next;
152 	int			dirfd;
153 	uint64_t		objid;
154 	zfs_zap_t		*zap;
155 };
156 
157 struct fs_populate_arg {
158 	zfs_opt_t	*zfs;
159 	zfs_fs_t	*fs;			/* owning filesystem */
160 	uint64_t	rootdirid;		/* root directory dnode ID */
161 	int		rootdirfd;		/* root directory fd */
162 	SLIST_HEAD(, fs_populate_dir) dirs;	/* stack of directories */
163 };
164 
165 static void fs_build_one(zfs_opt_t *, zfs_dsl_dir_t *, fsnode *, int);
166 
167 static void
168 eclose(int fd)
169 {
170 	if (close(fd) != 0)
171 		err(1, "close");
172 }
173 
174 static bool
175 fsnode_isroot(const fsnode *cur)
176 {
177 	return (strcmp(cur->name, ".") == 0);
178 }
179 
180 /*
181  * Visit each node in a directory hierarchy, in pre-order depth-first order.
182  */
183 static void
184 fsnode_foreach(fsnode *root, int (*cb)(fsnode *, void *), void *arg)
185 {
186 	assert(root->type == S_IFDIR);
187 
188 	for (fsnode *cur = root; cur != NULL; cur = cur->next) {
189 		assert(cur->type == S_IFREG || cur->type == S_IFDIR ||
190 		    cur->type == S_IFLNK);
191 
192 		if (cb(cur, arg) == 0)
193 			continue;
194 		if (cur->type == S_IFDIR && cur->child != NULL)
195 			fsnode_foreach(cur->child, cb, arg);
196 	}
197 }
198 
199 static void
200 fs_populate_dirent(struct fs_populate_arg *arg, fsnode *cur, uint64_t dnid)
201 {
202 	struct fs_populate_dir *dir;
203 	uint64_t type;
204 
205 	switch (cur->type) {
206 	case S_IFREG:
207 		type = DT_REG;
208 		break;
209 	case S_IFDIR:
210 		type = DT_DIR;
211 		break;
212 	case S_IFLNK:
213 		type = DT_LNK;
214 		break;
215 	default:
216 		assert(0);
217 	}
218 
219 	dir = SLIST_FIRST(&arg->dirs);
220 	zap_add_uint64(dir->zap, cur->name, ZFS_DIRENT_MAKE(type, dnid));
221 }
222 
223 static void
224 fs_populate_attr(zfs_fs_t *fs, char *attrbuf, const void *val, uint16_t ind,
225     size_t *szp)
226 {
227 	assert(ind < fs->sacnt);
228 	assert(fs->saoffs[ind] != 0xffff);
229 
230 	memcpy(attrbuf + fs->saoffs[ind], val, fs->satab[ind].size);
231 	*szp += fs->satab[ind].size;
232 }
233 
234 static void
235 fs_populate_varszattr(zfs_fs_t *fs, char *attrbuf, const void *val,
236     size_t valsz, size_t varoff, uint16_t ind, size_t *szp)
237 {
238 	assert(ind < fs->sacnt);
239 	assert(fs->saoffs[ind] != 0xffff);
240 	assert(fs->satab[ind].size == 0);
241 
242 	memcpy(attrbuf + fs->saoffs[ind] + varoff, val, valsz);
243 	*szp += valsz;
244 }
245 
246 /*
247  * Derive the relative fd/path combo needed to access a file.  Ideally we'd
248  * always be able to use relative lookups (i.e., use the *at() system calls),
249  * since they require less path translation and are more amenable to sandboxing,
250  * but the handling of multiple staging directories makes that difficult.  To
251  * make matters worse, we have no choice but to use relative lookups when
252  * dealing with an mtree manifest, so both mechanisms are implemented.
253  */
254 static void
255 fs_populate_path(const fsnode *cur, struct fs_populate_arg *arg,
256     char *path, size_t sz, int *dirfdp)
257 {
258 	if (cur->root == NULL) {
259 		size_t n;
260 
261 		*dirfdp = SLIST_FIRST(&arg->dirs)->dirfd;
262 		n = strlcpy(path, cur->name, sz);
263 		assert(n < sz);
264 	} else {
265 		int n;
266 
267 		*dirfdp = AT_FDCWD;
268 		n = snprintf(path, sz, "%s/%s/%s",
269 		    cur->root, cur->path, cur->name);
270 		assert(n >= 0);
271 		assert((size_t)n < sz);
272 	}
273 }
274 
275 static int
276 fs_open(const fsnode *cur, struct fs_populate_arg *arg, int flags)
277 {
278 	char path[PATH_MAX];
279 	int fd;
280 
281 	fs_populate_path(cur, arg, path, sizeof(path), &fd);
282 
283 	fd = openat(fd, path, flags);
284 	if (fd < 0)
285 		err(1, "openat(%s)", path);
286 	return (fd);
287 }
288 
289 static void
290 fs_readlink(const fsnode *cur, struct fs_populate_arg *arg,
291     char *buf, size_t bufsz)
292 {
293 	char path[PATH_MAX];
294 	ssize_t n;
295 	int fd;
296 
297 	fs_populate_path(cur, arg, path, sizeof(path), &fd);
298 
299 	n = readlinkat(fd, path, buf, bufsz - 1);
300 	if (n == -1)
301 		err(1, "readlinkat(%s)", cur->name);
302 	buf[n] = '\0';
303 }
304 
305 static void
306 fs_populate_time(zfs_fs_t *fs, char *attrbuf, struct timespec *ts,
307     uint16_t ind, size_t *szp)
308 {
309 	uint64_t timebuf[2];
310 
311 	assert(ind < fs->sacnt);
312 	assert(fs->saoffs[ind] != 0xffff);
313 	assert(fs->satab[ind].size == sizeof(timebuf));
314 
315 	timebuf[0] = ts->tv_sec;
316 	timebuf[1] = ts->tv_nsec;
317 	fs_populate_attr(fs, attrbuf, timebuf, ind, szp);
318 }
319 
320 static void
321 fs_populate_sattrs(struct fs_populate_arg *arg, const fsnode *cur,
322     dnode_phys_t *dnode)
323 {
324 	char target[PATH_MAX];
325 	zfs_fs_t *fs;
326 	zfs_ace_hdr_t aces[3];
327 	struct stat *sb;
328 	sa_hdr_phys_t *sahdr;
329 	uint64_t daclcount, flags, gen, gid, links, mode, parent, objsize, uid;
330 	char *attrbuf;
331 	size_t bonussz, hdrsz;
332 	int layout;
333 
334 	assert(dnode->dn_bonustype == DMU_OT_SA);
335 	assert(dnode->dn_nblkptr == 1);
336 
337 	fs = arg->fs;
338 	sb = &cur->inode->st;
339 
340 	switch (cur->type) {
341 	case S_IFREG:
342 		layout = SA_LAYOUT_INDEX_DEFAULT;
343 		links = cur->inode->nlink;
344 		objsize = sb->st_size;
345 		parent = SLIST_FIRST(&arg->dirs)->objid;
346 		break;
347 	case S_IFDIR:
348 		layout = SA_LAYOUT_INDEX_DEFAULT;
349 		links = 1; /* .. */
350 		objsize = 1; /* .. */
351 
352 		/*
353 		 * The size of a ZPL directory is the number of entries
354 		 * (including "." and ".."), and the link count is the number of
355 		 * entries which are directories (including "." and "..").
356 		 */
357 		for (fsnode *c = fsnode_isroot(cur) ? cur->next : cur->child;
358 		    c != NULL; c = c->next) {
359 			if (c->type == S_IFDIR)
360 				links++;
361 			objsize++;
362 		}
363 
364 		/* The root directory is its own parent. */
365 		parent = SLIST_EMPTY(&arg->dirs) ?
366 		    arg->rootdirid : SLIST_FIRST(&arg->dirs)->objid;
367 		break;
368 	case S_IFLNK:
369 		fs_readlink(cur, arg, target, sizeof(target));
370 
371 		layout = SA_LAYOUT_INDEX_SYMLINK;
372 		links = 1;
373 		objsize = strlen(target);
374 		parent = SLIST_FIRST(&arg->dirs)->objid;
375 		break;
376 	default:
377 		assert(0);
378 	}
379 
380 	daclcount = nitems(aces);
381 	flags = ZFS_ACL_TRIVIAL | ZFS_ACL_AUTO_INHERIT | ZFS_NO_EXECS_DENIED |
382 	    ZFS_ARCHIVE | ZFS_AV_MODIFIED; /* XXX-MJ */
383 	gen = 1;
384 	gid = sb->st_gid;
385 	mode = sb->st_mode;
386 	uid = sb->st_uid;
387 
388 	memset(aces, 0, sizeof(aces));
389 	aces[0].z_flags = ACE_OWNER;
390 	aces[0].z_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
391 	aces[0].z_access_mask = ACE_WRITE_ATTRIBUTES | ACE_WRITE_OWNER |
392 	    ACE_WRITE_ACL | ACE_WRITE_NAMED_ATTRS | ACE_READ_ACL |
393 	    ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS | ACE_SYNCHRONIZE;
394 	if ((mode & S_IRUSR) != 0)
395 		aces[0].z_access_mask |= ACE_READ_DATA;
396 	if ((mode & S_IWUSR) != 0)
397 		aces[0].z_access_mask |= ACE_WRITE_DATA | ACE_APPEND_DATA;
398 	if ((mode & S_IXUSR) != 0)
399 		aces[0].z_access_mask |= ACE_EXECUTE;
400 
401 	aces[1].z_flags = ACE_GROUP | ACE_IDENTIFIER_GROUP;
402 	aces[1].z_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
403 	aces[1].z_access_mask = ACE_READ_ACL | ACE_READ_ATTRIBUTES |
404 	    ACE_READ_NAMED_ATTRS | ACE_SYNCHRONIZE;
405 	if ((mode & S_IRGRP) != 0)
406 		aces[1].z_access_mask |= ACE_READ_DATA;
407 	if ((mode & S_IWGRP) != 0)
408 		aces[1].z_access_mask |= ACE_WRITE_DATA | ACE_APPEND_DATA;
409 	if ((mode & S_IXGRP) != 0)
410 		aces[1].z_access_mask |= ACE_EXECUTE;
411 
412 	aces[2].z_flags = ACE_EVERYONE;
413 	aces[2].z_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
414 	aces[2].z_access_mask = ACE_READ_ACL | ACE_READ_ATTRIBUTES |
415 	    ACE_READ_NAMED_ATTRS | ACE_SYNCHRONIZE;
416 	if ((mode & S_IROTH) != 0)
417 		aces[2].z_access_mask |= ACE_READ_DATA;
418 	if ((mode & S_IWOTH) != 0)
419 		aces[2].z_access_mask |= ACE_WRITE_DATA | ACE_APPEND_DATA;
420 	if ((mode & S_IXOTH) != 0)
421 		aces[2].z_access_mask |= ACE_EXECUTE;
422 
423 	switch (layout) {
424 	case SA_LAYOUT_INDEX_DEFAULT:
425 		/* At most one variable-length attribute. */
426 		hdrsz = sizeof(uint64_t);
427 		break;
428 	case SA_LAYOUT_INDEX_SYMLINK:
429 		/* At most five variable-length attributes. */
430 		hdrsz = sizeof(uint64_t) * 2;
431 		break;
432 	default:
433 		assert(0);
434 	}
435 
436 	sahdr = (sa_hdr_phys_t *)DN_BONUS(dnode);
437 	sahdr->sa_magic = SA_MAGIC;
438 	SA_HDR_LAYOUT_INFO_ENCODE(sahdr->sa_layout_info, layout, hdrsz);
439 
440 	bonussz = SA_HDR_SIZE(sahdr);
441 	attrbuf = (char *)sahdr + SA_HDR_SIZE(sahdr);
442 
443 	fs_populate_attr(fs, attrbuf, &daclcount, ZPL_DACL_COUNT, &bonussz);
444 	fs_populate_attr(fs, attrbuf, &flags, ZPL_FLAGS, &bonussz);
445 	fs_populate_attr(fs, attrbuf, &gen, ZPL_GEN, &bonussz);
446 	fs_populate_attr(fs, attrbuf, &gid, ZPL_GID, &bonussz);
447 	fs_populate_attr(fs, attrbuf, &links, ZPL_LINKS, &bonussz);
448 	fs_populate_attr(fs, attrbuf, &mode, ZPL_MODE, &bonussz);
449 	fs_populate_attr(fs, attrbuf, &parent, ZPL_PARENT, &bonussz);
450 	fs_populate_attr(fs, attrbuf, &objsize, ZPL_SIZE, &bonussz);
451 	fs_populate_attr(fs, attrbuf, &uid, ZPL_UID, &bonussz);
452 
453 	/*
454 	 * We deliberately set atime = mtime here to ensure that images are
455 	 * reproducible.
456 	 */
457 	fs_populate_time(fs, attrbuf, &sb->st_mtim, ZPL_ATIME, &bonussz);
458 	fs_populate_time(fs, attrbuf, &sb->st_ctim, ZPL_CTIME, &bonussz);
459 	fs_populate_time(fs, attrbuf, &sb->st_mtim, ZPL_MTIME, &bonussz);
460 #ifdef __linux__
461 	/* Linux has no st_birthtim; approximate with st_ctim */
462 	fs_populate_time(fs, attrbuf, &sb->st_ctim, ZPL_CRTIME, &bonussz);
463 #else
464 	fs_populate_time(fs, attrbuf, &sb->st_birthtim, ZPL_CRTIME, &bonussz);
465 #endif
466 
467 	fs_populate_varszattr(fs, attrbuf, aces, sizeof(aces), 0,
468 	    ZPL_DACL_ACES, &bonussz);
469 	sahdr->sa_lengths[0] = sizeof(aces);
470 
471 	if (cur->type == S_IFLNK) {
472 		assert(layout == SA_LAYOUT_INDEX_SYMLINK);
473 		/* Need to use a spill block pointer if the target is long. */
474 		assert(bonussz + objsize <= DN_OLD_MAX_BONUSLEN);
475 		fs_populate_varszattr(fs, attrbuf, target, objsize,
476 		    sahdr->sa_lengths[0], ZPL_SYMLINK, &bonussz);
477 		sahdr->sa_lengths[1] = (uint16_t)objsize;
478 	}
479 
480 	dnode->dn_bonuslen = bonussz;
481 }
482 
483 static void
484 fs_populate_file(fsnode *cur, struct fs_populate_arg *arg)
485 {
486 	struct dnode_cursor *c;
487 	dnode_phys_t *dnode;
488 	zfs_opt_t *zfs;
489 	char *buf;
490 	uint64_t dnid;
491 	ssize_t n;
492 	size_t bufsz;
493 	off_t size, target;
494 	int fd;
495 
496 	assert(cur->type == S_IFREG);
497 	assert((cur->inode->flags & FI_ROOT) == 0);
498 
499 	zfs = arg->zfs;
500 
501 	assert(cur->inode->ino != 0);
502 	if ((cur->inode->flags & FI_ALLOCATED) != 0) {
503 		/*
504 		 * This is a hard link of an existing file.
505 		 *
506 		 * XXX-MJ need to check whether it crosses datasets, add a test
507 		 * case for that
508 		 */
509 		fs_populate_dirent(arg, cur, cur->inode->ino);
510 		return;
511 	}
512 
513 	dnode = objset_dnode_bonus_alloc(arg->fs->os,
514 	    DMU_OT_PLAIN_FILE_CONTENTS, DMU_OT_SA, 0, &dnid);
515 	cur->inode->ino = dnid;
516 	cur->inode->flags |= FI_ALLOCATED;
517 
518 	fd = fs_open(cur, arg, O_RDONLY);
519 
520 	buf = zfs->filebuf;
521 	bufsz = sizeof(zfs->filebuf);
522 	size = cur->inode->st.st_size;
523 	c = dnode_cursor_init(zfs, arg->fs->os, dnode, size, 0);
524 	for (off_t foff = 0; foff < size; foff += target) {
525 		off_t loc, sofar;
526 
527 		/*
528 		 * Fill up our buffer, handling partial reads.
529 		 *
530 		 * It might be profitable to use copy_file_range(2) here.
531 		 */
532 		sofar = 0;
533 		target = MIN(size - foff, (off_t)bufsz);
534 		do {
535 			n = read(fd, buf + sofar, target);
536 			if (n < 0)
537 				err(1, "reading from '%s'", cur->name);
538 			if (n == 0)
539 				errx(1, "unexpected EOF reading '%s'",
540 				    cur->name);
541 			sofar += n;
542 		} while (sofar < target);
543 
544 		if (target < (off_t)bufsz)
545 			memset(buf + target, 0, bufsz - target);
546 
547 		loc = objset_space_alloc(zfs, arg->fs->os, &target);
548 		vdev_pwrite_dnode_indir(zfs, dnode, 0, 1, buf, target, loc,
549 		    dnode_cursor_next(zfs, c, foff));
550 	}
551 	eclose(fd);
552 	dnode_cursor_finish(zfs, c);
553 
554 	fs_populate_sattrs(arg, cur, dnode);
555 	fs_populate_dirent(arg, cur, dnid);
556 }
557 
558 static void
559 fs_populate_dir(fsnode *cur, struct fs_populate_arg *arg)
560 {
561 	dnode_phys_t *dnode;
562 	zfs_objset_t *os;
563 	uint64_t dnid;
564 	int dirfd;
565 
566 	assert(cur->type == S_IFDIR);
567 	assert((cur->inode->flags & FI_ALLOCATED) == 0);
568 
569 	os = arg->fs->os;
570 
571 	dnode = objset_dnode_bonus_alloc(os, DMU_OT_DIRECTORY_CONTENTS,
572 	    DMU_OT_SA, 0, &dnid);
573 
574 	/*
575 	 * Add an entry to the parent directory and open this directory.
576 	 */
577 	if (!SLIST_EMPTY(&arg->dirs)) {
578 		fs_populate_dirent(arg, cur, dnid);
579 		dirfd = fs_open(cur, arg, O_DIRECTORY | O_RDONLY);
580 	} else {
581 		arg->rootdirid = dnid;
582 		dirfd = arg->rootdirfd;
583 		arg->rootdirfd = -1;
584 	}
585 
586 	/*
587 	 * Set ZPL attributes.
588 	 */
589 	fs_populate_sattrs(arg, cur, dnode);
590 
591 	/*
592 	 * If this is a root directory, then its children belong to a different
593 	 * dataset and this directory remains empty in the current objset.
594 	 */
595 	if ((cur->inode->flags & FI_ROOT) == 0) {
596 		struct fs_populate_dir *dir;
597 
598 		dir = ecalloc(1, sizeof(*dir));
599 		dir->dirfd = dirfd;
600 		dir->objid = dnid;
601 		dir->zap = zap_alloc(os, dnode);
602 		SLIST_INSERT_HEAD(&arg->dirs, dir, next);
603 	} else {
604 		zap_write(arg->zfs, zap_alloc(os, dnode));
605 		fs_build_one(arg->zfs, cur->inode->param, cur->child, dirfd);
606 	}
607 }
608 
609 static void
610 fs_populate_symlink(fsnode *cur, struct fs_populate_arg *arg)
611 {
612 	dnode_phys_t *dnode;
613 	uint64_t dnid;
614 
615 	assert(cur->type == S_IFLNK);
616 	assert((cur->inode->flags & (FI_ALLOCATED | FI_ROOT)) == 0);
617 
618 	dnode = objset_dnode_bonus_alloc(arg->fs->os,
619 	    DMU_OT_PLAIN_FILE_CONTENTS, DMU_OT_SA, 0, &dnid);
620 
621 	fs_populate_dirent(arg, cur, dnid);
622 
623 	fs_populate_sattrs(arg, cur, dnode);
624 }
625 
626 static int
627 fs_foreach_populate(fsnode *cur, void *_arg)
628 {
629 	struct fs_populate_arg *arg;
630 	struct fs_populate_dir *dir;
631 	int ret;
632 
633 	arg = _arg;
634 	switch (cur->type) {
635 	case S_IFREG:
636 		fs_populate_file(cur, arg);
637 		break;
638 	case S_IFDIR:
639 		if (fsnode_isroot(cur))
640 			break;
641 		fs_populate_dir(cur, arg);
642 		break;
643 	case S_IFLNK:
644 		fs_populate_symlink(cur, arg);
645 		break;
646 	default:
647 		assert(0);
648 	}
649 
650 	ret = (cur->inode->flags & FI_ROOT) != 0 ? 0 : 1;
651 
652 	if (cur->next == NULL &&
653 	    (cur->child == NULL || (cur->inode->flags & FI_ROOT) != 0)) {
654 		/*
655 		 * We reached a terminal node in a subtree.  Walk back up and
656 		 * write out directories.  We're done once we hit the root of a
657 		 * dataset or find a level where we're not on the edge of the
658 		 * tree.
659 		 */
660 		do {
661 			dir = SLIST_FIRST(&arg->dirs);
662 			SLIST_REMOVE_HEAD(&arg->dirs, next);
663 			zap_write(arg->zfs, dir->zap);
664 			if (dir->dirfd != -1)
665 				eclose(dir->dirfd);
666 			free(dir);
667 			cur = cur->parent;
668 		} while (cur != NULL && cur->next == NULL &&
669 		    (cur->inode->flags & FI_ROOT) == 0);
670 	}
671 
672 	return (ret);
673 }
674 
675 static void
676 fs_add_zpl_attr_layout(zfs_zap_t *zap, unsigned int index,
677     const sa_attr_type_t layout[], size_t sacnt)
678 {
679 	char ti[16];
680 
681 	assert(sizeof(layout[0]) == 2);
682 
683 	snprintf(ti, sizeof(ti), "%u", index);
684 	zap_add(zap, ti, sizeof(sa_attr_type_t), sacnt,
685 	    (const uint8_t *)layout);
686 }
687 
688 /*
689  * Initialize system attribute tables.
690  *
691  * There are two elements to this.  First, we write the zpl_attrs[] and
692  * zpl_attr_layout[] tables to disk.  Then we create a lookup table which
693  * allows us to set file attributes quickly.
694  */
695 static uint64_t
696 fs_set_zpl_attrs(zfs_opt_t *zfs, zfs_fs_t *fs)
697 {
698 	zfs_zap_t *sazap, *salzap, *sarzap;
699 	zfs_objset_t *os;
700 	dnode_phys_t *saobj, *salobj, *sarobj;
701 	uint64_t saobjid, salobjid, sarobjid;
702 	uint16_t offset;
703 
704 	os = fs->os;
705 
706 	/*
707 	 * The on-disk tables are stored in two ZAP objects, the registry object
708 	 * and the layout object.  Individual attributes are described by
709 	 * entries in the registry object; for example, the value for the
710 	 * "ZPL_SIZE" key gives the size and encoding of the ZPL_SIZE attribute.
711 	 * The attributes of a file are ordered according to one of the layouts
712 	 * defined in the layout object.  The master node object is simply used
713 	 * to locate the registry and layout objects.
714 	 */
715 	saobj = objset_dnode_alloc(os, DMU_OT_SA_MASTER_NODE, &saobjid);
716 	salobj = objset_dnode_alloc(os, DMU_OT_SA_ATTR_LAYOUTS, &salobjid);
717 	sarobj = objset_dnode_alloc(os, DMU_OT_SA_ATTR_REGISTRATION, &sarobjid);
718 
719 	sarzap = zap_alloc(os, sarobj);
720 	for (size_t i = 0; i < nitems(zpl_attrs); i++) {
721 		const zfs_sattr_t *sa;
722 		uint64_t attr;
723 
724 		attr = 0;
725 		sa = &zpl_attrs[i];
726 		SA_ATTR_ENCODE(attr, (uint64_t)i, sa->size, sa->bs);
727 		zap_add_uint64(sarzap, sa->name, attr);
728 	}
729 	zap_write(zfs, sarzap);
730 
731 	/*
732 	 * Layouts are arrays of indices into the registry.  We define two
733 	 * layouts for use by the ZPL, one for non-symlinks and one for
734 	 * symlinks.  They are identical except that the symlink layout includes
735 	 * ZPL_SYMLINK as its final attribute.
736 	 */
737 	salzap = zap_alloc(os, salobj);
738 	assert(zpl_attr_layout[nitems(zpl_attr_layout) - 1] == ZPL_SYMLINK);
739 	fs_add_zpl_attr_layout(salzap, SA_LAYOUT_INDEX_DEFAULT,
740 	    zpl_attr_layout, nitems(zpl_attr_layout) - 1);
741 	fs_add_zpl_attr_layout(salzap, SA_LAYOUT_INDEX_SYMLINK,
742 	    zpl_attr_layout, nitems(zpl_attr_layout));
743 	zap_write(zfs, salzap);
744 
745 	sazap = zap_alloc(os, saobj);
746 	zap_add_uint64(sazap, SA_LAYOUTS, salobjid);
747 	zap_add_uint64(sazap, SA_REGISTRY, sarobjid);
748 	zap_write(zfs, sazap);
749 
750 	/* Sanity check. */
751 	for (size_t i = 0; i < nitems(zpl_attrs); i++)
752 		assert(i == zpl_attrs[i].id);
753 
754 	/*
755 	 * Build the offset table used when setting file attributes.  File
756 	 * attributes are stored in the object's bonus buffer; this table
757 	 * provides the buffer offset of attributes referenced by the layout
758 	 * table.
759 	 */
760 	fs->sacnt = nitems(zpl_attrs);
761 	fs->saoffs = ecalloc(fs->sacnt, sizeof(*fs->saoffs));
762 	for (size_t i = 0; i < fs->sacnt; i++)
763 		fs->saoffs[i] = 0xffff;
764 	offset = 0;
765 	for (size_t i = 0; i < nitems(zpl_attr_layout); i++) {
766 		uint16_t size;
767 
768 		assert(zpl_attr_layout[i] < fs->sacnt);
769 
770 		fs->saoffs[zpl_attr_layout[i]] = offset;
771 		size = zpl_attrs[zpl_attr_layout[i]].size;
772 		offset += size;
773 	}
774 	fs->satab = zpl_attrs;
775 
776 	return (saobjid);
777 }
778 
779 static void
780 fs_layout_one(zfs_opt_t *zfs, zfs_dsl_dir_t *dsldir, void *arg)
781 {
782 	char *mountpoint, *origmountpoint, *name, *next;
783 	fsnode *cur, *root;
784 	uint64_t canmount;
785 
786 	if (!dsl_dir_has_dataset(dsldir))
787 		return;
788 
789 	if (dsl_dir_get_canmount(dsldir, &canmount) == 0 && canmount == 0)
790 		return;
791 	mountpoint = dsl_dir_get_mountpoint(zfs, dsldir);
792 	if (mountpoint == NULL)
793 		return;
794 
795 	/*
796 	 * If we were asked to specify a bootfs, set it here.
797 	 */
798 	if (zfs->bootfs != NULL && strcmp(zfs->bootfs,
799 	    dsl_dir_fullname(dsldir)) == 0) {
800 		zap_add_uint64(zfs->poolprops, "bootfs",
801 		    dsl_dir_dataset_id(dsldir));
802 	}
803 
804 	origmountpoint = mountpoint;
805 
806 	/*
807 	 * Figure out which fsnode corresponds to our mountpoint.
808 	 */
809 	root = arg;
810 	cur = root;
811 	if (strcmp(mountpoint, zfs->rootpath) != 0) {
812 		mountpoint += strlen(zfs->rootpath);
813 
814 		/*
815 		 * Look up the directory in the staged tree.  For example, if
816 		 * the dataset's mount point is /foo/bar/baz, we'll search the
817 		 * root directory for "foo", search "foo" for "baz", and so on.
818 		 * Each intermediate name must refer to a directory; the final
819 		 * component need not exist.
820 		 */
821 		cur = root;
822 		for (next = name = mountpoint; next != NULL;) {
823 			for (; *next == '/'; next++)
824 				;
825 			name = strsep(&next, "/");
826 
827 			for (; cur != NULL && strcmp(cur->name, name) != 0;
828 			    cur = cur->next)
829 				;
830 			if (cur == NULL) {
831 				if (next == NULL)
832 					break;
833 				errx(1, "missing mountpoint directory for `%s'",
834 				    dsl_dir_fullname(dsldir));
835 			}
836 			if (cur->type != S_IFDIR) {
837 				errx(1,
838 				    "mountpoint for `%s' is not a directory",
839 				    dsl_dir_fullname(dsldir));
840 			}
841 			if (next != NULL)
842 				cur = cur->child;
843 		}
844 	}
845 
846 	if (cur != NULL) {
847 		assert(cur->type == S_IFDIR);
848 
849 		/*
850 		 * Multiple datasets shouldn't share a mountpoint.  It's
851 		 * technically allowed, but it's not clear what makefs should do
852 		 * in that case.
853 		 */
854 		assert((cur->inode->flags & FI_ROOT) == 0);
855 		if (cur != root)
856 			cur->inode->flags |= FI_ROOT;
857 		assert(cur->inode->param == NULL);
858 		cur->inode->param = dsldir;
859 	}
860 
861 	free(origmountpoint);
862 }
863 
864 static int
865 fs_foreach_mark(fsnode *cur, void *arg)
866 {
867 	uint64_t *countp;
868 
869 	countp = arg;
870 	if (cur->type == S_IFDIR && fsnode_isroot(cur))
871 		return (1);
872 
873 	if (cur->inode->ino == 0) {
874 		cur->inode->ino = ++(*countp);
875 		cur->inode->nlink = 1;
876 	} else {
877 		cur->inode->nlink++;
878 	}
879 
880 	return ((cur->inode->flags & FI_ROOT) != 0 ? 0 : 1);
881 }
882 
883 /*
884  * Create a filesystem dataset.  More specifically:
885  * - create an object set for the dataset,
886  * - add required metadata (SA tables, property definitions, etc.) to that
887  *   object set,
888  * - optionally populate the object set with file objects, using "root" as the
889  *   root directory.
890  *
891  * "dirfd" is a directory descriptor for the directory referenced by "root".  It
892  * is closed before returning.
893  */
894 static void
895 fs_build_one(zfs_opt_t *zfs, zfs_dsl_dir_t *dsldir, fsnode *root, int dirfd)
896 {
897 	struct fs_populate_arg arg;
898 	zfs_fs_t fs;
899 	zfs_zap_t *masterzap;
900 	zfs_objset_t *os;
901 	dnode_phys_t *deleteq, *masterobj;
902 	uint64_t deleteqid, dnodecount, moid, rootdirid, saobjid;
903 	bool fakedroot;
904 
905 	/*
906 	 * This dataset's mountpoint doesn't exist in the staging tree, or the
907 	 * dataset doesn't have a mountpoint at all.  In either case we still
908 	 * need a root directory.  Fake up a root fsnode to handle this case.
909 	 */
910 	fakedroot = root == NULL;
911 	if (fakedroot) {
912 		struct stat *stp;
913 
914 		assert(dirfd == -1);
915 
916 		root = ecalloc(1, sizeof(*root));
917 		root->inode = ecalloc(1, sizeof(*root->inode));
918 		root->name = estrdup(".");
919 		root->type = S_IFDIR;
920 
921 		stp = &root->inode->st;
922 		stp->st_uid = 0;
923 		stp->st_gid = 0;
924 		stp->st_mode = S_IFDIR | 0755;
925 	}
926 	assert(root->type == S_IFDIR);
927 	assert(fsnode_isroot(root));
928 
929 	/*
930 	 * Initialize the object set for this dataset.
931 	 */
932 	os = objset_alloc(zfs, DMU_OST_ZFS);
933 	masterobj = objset_dnode_alloc(os, DMU_OT_MASTER_NODE, &moid);
934 	assert(moid == MASTER_NODE_OBJ);
935 
936 	memset(&fs, 0, sizeof(fs));
937 	fs.os = os;
938 
939 	/*
940 	 * Create the ZAP SA layout now since filesystem object dnodes will
941 	 * refer to those attributes.
942 	 */
943 	saobjid = fs_set_zpl_attrs(zfs, &fs);
944 
945 	/*
946 	 * Make a pass over the staged directory to detect hard links and assign
947 	 * virtual dnode numbers.
948 	 */
949 	dnodecount = 1; /* root directory */
950 	fsnode_foreach(root, fs_foreach_mark, &dnodecount);
951 
952 	/*
953 	 * Make a second pass to populate the dataset with files from the
954 	 * staged directory.  Most of our runtime is spent here.
955 	 */
956 	arg.rootdirfd = dirfd;
957 	arg.zfs = zfs;
958 	arg.fs = &fs;
959 	SLIST_INIT(&arg.dirs);
960 	fs_populate_dir(root, &arg);
961 	assert(!SLIST_EMPTY(&arg.dirs));
962 	fsnode_foreach(root, fs_foreach_populate, &arg);
963 	assert(SLIST_EMPTY(&arg.dirs));
964 	rootdirid = arg.rootdirid;
965 
966 	/*
967 	 * Create an empty delete queue.  We don't do anything with it, but
968 	 * OpenZFS will refuse to mount filesystems that don't have one.
969 	 */
970 	deleteq = objset_dnode_alloc(os, DMU_OT_UNLINKED_SET, &deleteqid);
971 	zap_write(zfs, zap_alloc(os, deleteq));
972 
973 	/*
974 	 * Populate and write the master node object.  This is a ZAP object
975 	 * containing various dataset properties and the object IDs of the root
976 	 * directory and delete queue.
977 	 */
978 	masterzap = zap_alloc(os, masterobj);
979 	zap_add_uint64(masterzap, ZFS_ROOT_OBJ, rootdirid);
980 	zap_add_uint64(masterzap, ZFS_UNLINKED_SET, deleteqid);
981 	zap_add_uint64(masterzap, ZFS_SA_ATTRS, saobjid);
982 	zap_add_uint64(masterzap, ZPL_VERSION_OBJ, 5 /* ZPL_VERSION_SA */);
983 	zap_add_uint64(masterzap, "normalization", 0 /* off */);
984 	zap_add_uint64(masterzap, "utf8only", 0 /* off */);
985 	zap_add_uint64(masterzap, "casesensitivity", 0 /* case sensitive */);
986 	zap_add_uint64(masterzap, "acltype", 2 /* NFSv4 */);
987 	zap_write(zfs, masterzap);
988 
989 	/*
990 	 * All finished with this object set, we may as well write it now.
991 	 * The DSL layer will sum up the bytes consumed by each dataset using
992 	 * information stored in the object set, so it can't be freed just yet.
993 	 */
994 	dsl_dir_dataset_write(zfs, os, dsldir);
995 
996 	if (fakedroot) {
997 		free(root->inode);
998 		free(root->name);
999 		free(root);
1000 	}
1001 	free(fs.saoffs);
1002 }
1003 
1004 /*
1005  * Create an object set for each DSL directory which has a dataset and doesn't
1006  * already have an object set.
1007  */
1008 static void
1009 fs_build_unmounted(zfs_opt_t *zfs, zfs_dsl_dir_t *dsldir, void *arg __unused)
1010 {
1011 	if (dsl_dir_has_dataset(dsldir) && !dsl_dir_dataset_has_objset(dsldir))
1012 		fs_build_one(zfs, dsldir, NULL, -1);
1013 }
1014 
1015 /*
1016  * Create our datasets and populate them with files.
1017  */
1018 void
1019 fs_build(zfs_opt_t *zfs, int dirfd, fsnode *root)
1020 {
1021 	/*
1022 	 * Run through our datasets and find the root fsnode for each one.  Each
1023 	 * root fsnode is flagged so that we can figure out which dataset it
1024 	 * belongs to.
1025 	 */
1026 	dsl_dir_foreach(zfs, zfs->rootdsldir, fs_layout_one, root);
1027 
1028 	/*
1029 	 * Did we find our boot filesystem?
1030 	 */
1031 	if (zfs->bootfs != NULL && !zap_entry_exists(zfs->poolprops, "bootfs"))
1032 		errx(1, "no mounted dataset matches bootfs property `%s'",
1033 		    zfs->bootfs);
1034 
1035 	/*
1036 	 * Traverse the file hierarchy starting from the root fsnode.  One
1037 	 * dataset, not necessarily the root dataset, must "own" the root
1038 	 * directory by having its mountpoint be equal to the root path.
1039 	 *
1040 	 * As roots of other datasets are encountered during the traversal,
1041 	 * fs_build_one() recursively creates the corresponding object sets and
1042 	 * populates them.  Once this function has returned, all datasets will
1043 	 * have been fully populated.
1044 	 */
1045 	fs_build_one(zfs, root->inode->param, root, dirfd);
1046 
1047 	/*
1048 	 * Now create object sets for datasets whose mountpoints weren't found
1049 	 * in the staging directory, either because there is no mountpoint, or
1050 	 * because the mountpoint doesn't correspond to an existing directory.
1051 	 */
1052 	dsl_dir_foreach(zfs, zfs->rootdsldir, fs_build_unmounted, NULL);
1053 }
1054