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