xref: /freebsd/sys/contrib/openzfs/module/os/linux/zfs/zfs_znode_os.c (revision 2f10ffc003be396f3fc23cd2888023896560252b)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 /*
13  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
14  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
15  */
16 
17 /* Portions Copyright 2007 Jeremy Teo */
18 
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/time.h>
22 #include <sys/sysmacros.h>
23 #include <sys/mntent.h>
24 #include <sys/u8_textprep.h>
25 #include <sys/dsl_dataset.h>
26 #include <sys/vfs.h>
27 #include <sys/vnode.h>
28 #include <sys/file.h>
29 #include <sys/kmem.h>
30 #include <sys/errno.h>
31 #include <sys/atomic.h>
32 #include <sys/zfs_dir.h>
33 #include <sys/zfs_acl_impl.h>
34 #include <sys/zfs_ioctl.h>
35 #include <sys/zfs_rlock.h>
36 #include <sys/zfs_fuid.h>
37 #include <sys/zfs_vnops.h>
38 #include <sys/zfs_ctldir.h>
39 #include <sys/dnode.h>
40 #include <sys/fs/zfs.h>
41 #include <sys/zpl.h>
42 #include <sys/dmu.h>
43 #include <sys/dmu_objset.h>
44 #include <sys/dmu_tx.h>
45 #include <sys/zfs_refcount.h>
46 #include <sys/stat.h>
47 #include <sys/zap.h>
48 #include <sys/zfs_znode.h>
49 #include <sys/sa.h>
50 #include <sys/zfs_sa.h>
51 #include <sys/zfs_stat.h>
52 #include <linux/mm_compat.h>
53 #ifdef CONFIG_FS_POSIX_ACL
54 #include <linux/posix_acl.h>
55 #endif
56 
57 #include "zfs_prop.h"
58 #include "zfs_comutil.h"
59 
60 static kmem_cache_t *znode_cache = NULL;
61 static kmem_cache_t *znode_hold_cache = NULL;
62 unsigned int zfs_object_mutex_size = ZFS_OBJ_MTX_SZ;
63 
64 /*
65  * This is used by the test suite so that it can delay znodes from being
66  * freed in order to inspect the unlinked set.
67  */
68 static int zfs_unlink_suspend_progress = 0;
69 
70 /*
71  * This callback is invoked when acquiring a RL_WRITER or RL_APPEND lock on
72  * z_rangelock. It will modify the offset and length of the lock to reflect
73  * znode-specific information, and convert RL_APPEND to RL_WRITER.  This is
74  * called with the rangelock_t's rl_lock held, which avoids races.
75  */
76 static void
zfs_rangelock_cb(zfs_locked_range_t * new,void * arg)77 zfs_rangelock_cb(zfs_locked_range_t *new, void *arg)
78 {
79 	znode_t *zp = arg;
80 
81 	/*
82 	 * If in append mode, convert to writer and lock starting at the
83 	 * current end of file.
84 	 */
85 	if (new->lr_type == RL_APPEND) {
86 		new->lr_offset = zp->z_size;
87 		new->lr_type = RL_WRITER;
88 	}
89 
90 	/*
91 	 * If we might grow the block size then lock the whole file range.
92 	 * NB: this test should match the check in zfs_grow_blocksize
93 	 */
94 	uint64_t end_size = MAX(zp->z_size, new->lr_offset + new->lr_length);
95 	if (zp->z_size <= zp->z_blksz && end_size > zp->z_blksz &&
96 	    (!ISP2(zp->z_blksz) || zp->z_blksz < ZTOZSB(zp)->z_max_blksz)) {
97 		new->lr_offset = 0;
98 		new->lr_length = UINT64_MAX;
99 	}
100 }
101 
102 static int
zfs_znode_cache_constructor(void * buf,void * arg,int kmflags)103 zfs_znode_cache_constructor(void *buf, void *arg, int kmflags)
104 {
105 	(void) arg, (void) kmflags;
106 	znode_t *zp = buf;
107 
108 	inode_init_once(ZTOI(zp));
109 	list_link_init(&zp->z_link_node);
110 
111 	mutex_init(&zp->z_lock, NULL, MUTEX_DEFAULT, NULL);
112 	rw_init(&zp->z_parent_lock, NULL, RW_DEFAULT, NULL);
113 	rw_init(&zp->z_name_lock, NULL, RW_NOLOCKDEP, NULL);
114 	mutex_init(&zp->z_acl_lock, NULL, MUTEX_DEFAULT, NULL);
115 	rw_init(&zp->z_xattr_lock, NULL, RW_DEFAULT, NULL);
116 
117 	zfs_rangelock_init(&zp->z_rangelock, zfs_rangelock_cb, zp);
118 
119 	zp->z_dirlocks = NULL;
120 	zp->z_acl_cached = NULL;
121 	zp->z_xattr_cached = NULL;
122 	zp->z_xattr_parent = 0;
123 	zp->z_has_seq = B_FALSE;
124 
125 	return (0);
126 }
127 
128 static void
zfs_znode_cache_destructor(void * buf,void * arg)129 zfs_znode_cache_destructor(void *buf, void *arg)
130 {
131 	(void) arg;
132 	znode_t *zp = buf;
133 
134 	ASSERT(!list_link_active(&zp->z_link_node));
135 	mutex_destroy(&zp->z_lock);
136 	rw_destroy(&zp->z_parent_lock);
137 	rw_destroy(&zp->z_name_lock);
138 	mutex_destroy(&zp->z_acl_lock);
139 	rw_destroy(&zp->z_xattr_lock);
140 	zfs_rangelock_fini(&zp->z_rangelock);
141 
142 	ASSERT0P(zp->z_dirlocks);
143 	ASSERT0P(zp->z_acl_cached);
144 	ASSERT0P(zp->z_xattr_cached);
145 }
146 
147 static int
zfs_znode_hold_cache_constructor(void * buf,void * arg,int kmflags)148 zfs_znode_hold_cache_constructor(void *buf, void *arg, int kmflags)
149 {
150 	(void) arg, (void) kmflags;
151 	znode_hold_t *zh = buf;
152 
153 	mutex_init(&zh->zh_lock, NULL, MUTEX_DEFAULT, NULL);
154 	zh->zh_refcount = 0;
155 
156 	return (0);
157 }
158 
159 static void
zfs_znode_hold_cache_destructor(void * buf,void * arg)160 zfs_znode_hold_cache_destructor(void *buf, void *arg)
161 {
162 	(void) arg;
163 	znode_hold_t *zh = buf;
164 
165 	mutex_destroy(&zh->zh_lock);
166 }
167 
168 void
zfs_znode_init(void)169 zfs_znode_init(void)
170 {
171 	/*
172 	 * Initialize zcache.  The KMC_SLAB hint is used in order that it be
173 	 * backed by kmalloc() when on the Linux slab in order that any
174 	 * wait_on_bit() operations on the related inode operate properly.
175 	 */
176 	ASSERT0P(znode_cache);
177 	znode_cache = kmem_cache_create("zfs_znode_cache",
178 	    sizeof (znode_t), 0, zfs_znode_cache_constructor,
179 	    zfs_znode_cache_destructor, NULL, NULL, NULL,
180 	    KMC_SLAB | KMC_RECLAIMABLE);
181 
182 	ASSERT0P(znode_hold_cache);
183 	znode_hold_cache = kmem_cache_create("zfs_znode_hold_cache",
184 	    sizeof (znode_hold_t), 0, zfs_znode_hold_cache_constructor,
185 	    zfs_znode_hold_cache_destructor, NULL, NULL, NULL, 0);
186 }
187 
188 void
zfs_znode_fini(void)189 zfs_znode_fini(void)
190 {
191 	/*
192 	 * Cleanup zcache
193 	 */
194 	if (znode_cache)
195 		kmem_cache_destroy(znode_cache);
196 	znode_cache = NULL;
197 
198 	if (znode_hold_cache)
199 		kmem_cache_destroy(znode_hold_cache);
200 	znode_hold_cache = NULL;
201 }
202 
203 /*
204  * The zfs_znode_hold_enter() / zfs_znode_hold_exit() functions are used to
205  * serialize access to a znode and its SA buffer while the object is being
206  * created or destroyed.  This kind of locking would normally reside in the
207  * znode itself but in this case that's impossible because the znode and SA
208  * buffer may not yet exist.  Therefore the locking is handled externally
209  * with an array of mutexes and AVLs trees which contain per-object locks.
210  *
211  * In zfs_znode_hold_enter() a per-object lock is created as needed, inserted
212  * in to the correct AVL tree and finally the per-object lock is held.  In
213  * zfs_znode_hold_exit() the process is reversed.  The per-object lock is
214  * released, removed from the AVL tree and destroyed if there are no waiters.
215  *
216  * This scheme has two important properties:
217  *
218  * 1) No memory allocations are performed while holding one of the z_hold_locks.
219  *    This ensures evict(), which can be called from direct memory reclaim, will
220  *    never block waiting on a z_hold_locks which just happens to have hashed
221  *    to the same index.
222  *
223  * 2) All locks used to serialize access to an object are per-object and never
224  *    shared.  This minimizes lock contention without creating a large number
225  *    of dedicated locks.
226  *
227  * On the downside it does require znode_lock_t structures to be frequently
228  * allocated and freed.  However, because these are backed by a kmem cache
229  * and very short lived this cost is minimal.
230  */
231 int
zfs_znode_hold_compare(const void * a,const void * b)232 zfs_znode_hold_compare(const void *a, const void *b)
233 {
234 	const znode_hold_t *zh_a = (const znode_hold_t *)a;
235 	const znode_hold_t *zh_b = (const znode_hold_t *)b;
236 
237 	return (TREE_CMP(zh_a->zh_obj, zh_b->zh_obj));
238 }
239 
240 static boolean_t __maybe_unused
zfs_znode_held(zfsvfs_t * zfsvfs,uint64_t obj)241 zfs_znode_held(zfsvfs_t *zfsvfs, uint64_t obj)
242 {
243 	znode_hold_t *zh, search;
244 	int i = ZFS_OBJ_HASH(zfsvfs, obj);
245 	boolean_t held;
246 
247 	search.zh_obj = obj;
248 
249 	mutex_enter(&zfsvfs->z_hold_locks[i]);
250 	zh = avl_find(&zfsvfs->z_hold_trees[i], &search, NULL);
251 	held = (zh && MUTEX_HELD(&zh->zh_lock)) ? B_TRUE : B_FALSE;
252 	mutex_exit(&zfsvfs->z_hold_locks[i]);
253 
254 	return (held);
255 }
256 
257 znode_hold_t *
zfs_znode_hold_enter(zfsvfs_t * zfsvfs,uint64_t obj)258 zfs_znode_hold_enter(zfsvfs_t *zfsvfs, uint64_t obj)
259 {
260 	znode_hold_t *zh, *zh_new, search;
261 	int i = ZFS_OBJ_HASH(zfsvfs, obj);
262 	boolean_t found = B_FALSE;
263 
264 	zh_new = kmem_cache_alloc(znode_hold_cache, KM_SLEEP);
265 	search.zh_obj = obj;
266 
267 	mutex_enter(&zfsvfs->z_hold_locks[i]);
268 	zh = avl_find(&zfsvfs->z_hold_trees[i], &search, NULL);
269 	if (likely(zh == NULL)) {
270 		zh = zh_new;
271 		zh->zh_obj = obj;
272 		avl_add(&zfsvfs->z_hold_trees[i], zh);
273 	} else {
274 		ASSERT3U(zh->zh_obj, ==, obj);
275 		found = B_TRUE;
276 	}
277 	zh->zh_refcount++;
278 	ASSERT3S(zh->zh_refcount, >, 0);
279 	mutex_exit(&zfsvfs->z_hold_locks[i]);
280 
281 	if (found == B_TRUE)
282 		kmem_cache_free(znode_hold_cache, zh_new);
283 
284 	ASSERT(MUTEX_NOT_HELD(&zh->zh_lock));
285 	mutex_enter(&zh->zh_lock);
286 
287 	return (zh);
288 }
289 
290 void
zfs_znode_hold_exit(zfsvfs_t * zfsvfs,znode_hold_t * zh)291 zfs_znode_hold_exit(zfsvfs_t *zfsvfs, znode_hold_t *zh)
292 {
293 	int i = ZFS_OBJ_HASH(zfsvfs, zh->zh_obj);
294 	boolean_t remove = B_FALSE;
295 
296 	ASSERT(zfs_znode_held(zfsvfs, zh->zh_obj));
297 	mutex_exit(&zh->zh_lock);
298 
299 	mutex_enter(&zfsvfs->z_hold_locks[i]);
300 	ASSERT3S(zh->zh_refcount, >, 0);
301 	if (--zh->zh_refcount == 0) {
302 		avl_remove(&zfsvfs->z_hold_trees[i], zh);
303 		remove = B_TRUE;
304 	}
305 	mutex_exit(&zfsvfs->z_hold_locks[i]);
306 
307 	if (remove == B_TRUE)
308 		kmem_cache_free(znode_hold_cache, zh);
309 }
310 
311 dev_t
zfs_cmpldev(uint64_t dev)312 zfs_cmpldev(uint64_t dev)
313 {
314 	return (dev);
315 }
316 
317 static void
zfs_znode_sa_init(zfsvfs_t * zfsvfs,znode_t * zp,dmu_buf_t * db,dmu_object_type_t obj_type,sa_handle_t * sa_hdl)318 zfs_znode_sa_init(zfsvfs_t *zfsvfs, znode_t *zp,
319     dmu_buf_t *db, dmu_object_type_t obj_type, sa_handle_t *sa_hdl)
320 {
321 	ASSERT(zfs_znode_held(zfsvfs, zp->z_id));
322 
323 	mutex_enter(&zp->z_lock);
324 
325 	ASSERT0P(zp->z_sa_hdl);
326 	ASSERT0P(zp->z_acl_cached);
327 	if (sa_hdl == NULL) {
328 		VERIFY0(sa_handle_get_from_db(zfsvfs->z_os, db, zp,
329 		    SA_HDL_SHARED, &zp->z_sa_hdl));
330 	} else {
331 		zp->z_sa_hdl = sa_hdl;
332 		sa_set_userp(sa_hdl, zp);
333 	}
334 
335 	zp->z_is_sa = (obj_type == DMU_OT_SA) ? B_TRUE : B_FALSE;
336 
337 	mutex_exit(&zp->z_lock);
338 }
339 
340 void
zfs_znode_dmu_fini(znode_t * zp)341 zfs_znode_dmu_fini(znode_t *zp)
342 {
343 	ASSERT(zfs_znode_held(ZTOZSB(zp), zp->z_id) ||
344 	    RW_WRITE_HELD(&ZTOZSB(zp)->z_teardown_inactive_lock));
345 
346 	sa_handle_destroy(zp->z_sa_hdl);
347 	zp->z_sa_hdl = NULL;
348 }
349 
350 /*
351  * Called by new_inode() to allocate a new inode.
352  */
353 int
zfs_inode_alloc(struct super_block * sb,struct inode ** ip)354 zfs_inode_alloc(struct super_block *sb, struct inode **ip)
355 {
356 	znode_t *zp;
357 
358 	zp = kmem_cache_alloc(znode_cache, KM_SLEEP);
359 	*ip = ZTOI(zp);
360 
361 	return (0);
362 }
363 
364 void
zfs_inode_free(struct inode * ip)365 zfs_inode_free(struct inode *ip)
366 {
367 	kmem_cache_free(znode_cache, ITOZ(ip));
368 }
369 
370 /*
371  * Called in multiple places when an inode should be destroyed.
372  */
373 void
zfs_inode_destroy(struct inode * ip)374 zfs_inode_destroy(struct inode *ip)
375 {
376 	znode_t *zp = ITOZ(ip);
377 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
378 
379 	mutex_enter(&zfsvfs->z_znodes_lock);
380 	if (list_link_active(&zp->z_link_node)) {
381 		list_remove(&zfsvfs->z_all_znodes, zp);
382 	}
383 	mutex_exit(&zfsvfs->z_znodes_lock);
384 
385 	if (zp->z_acl_cached) {
386 		zfs_acl_free(zp->z_acl_cached);
387 		zp->z_acl_cached = NULL;
388 	}
389 
390 	if (zp->z_xattr_cached) {
391 		nvlist_free(zp->z_xattr_cached);
392 		zp->z_xattr_cached = NULL;
393 	}
394 #ifndef HAVE_SOPS_FREE_INODE
395 	/*
396 	 * inode needs to be freed in RCU callback.  If we have
397 	 * super_operations->free_inode, Linux kernel will do call_rcu
398 	 * for us.  But if we don't have it, since call_rcu is GPL-only
399 	 * symbol, we can only free synchronously and accept the risk.
400 	 */
401 	zfs_inode_free(ip);
402 #endif
403 }
404 
405 static void
zfs_inode_set_ops(zfsvfs_t * zfsvfs,struct inode * ip)406 zfs_inode_set_ops(zfsvfs_t *zfsvfs, struct inode *ip)
407 {
408 	uint64_t rdev = 0;
409 
410 	switch (ip->i_mode & S_IFMT) {
411 	case S_IFREG:
412 		ip->i_op = &zpl_inode_operations;
413 		ip->i_fop = &zpl_file_operations;
414 		ip->i_mapping->a_ops = &zpl_address_space_operations;
415 		break;
416 
417 	case S_IFDIR:
418 		ip->i_op = &zpl_dir_inode_operations;
419 		ip->i_fop = &zpl_dir_file_operations;
420 		ITOZ(ip)->z_zn_prefetch = B_TRUE;
421 		break;
422 
423 	case S_IFLNK:
424 		ip->i_op = &zpl_symlink_inode_operations;
425 		break;
426 
427 	/*
428 	 * rdev is only stored in a SA only for device files.
429 	 */
430 	case S_IFCHR:
431 	case S_IFBLK:
432 		(void) sa_lookup(ITOZ(ip)->z_sa_hdl, SA_ZPL_RDEV(zfsvfs), &rdev,
433 		    sizeof (rdev));
434 		zfs_fallthrough;
435 	case S_IFIFO:
436 	case S_IFSOCK:
437 		init_special_inode(ip, ip->i_mode, rdev);
438 		ip->i_op = &zpl_special_inode_operations;
439 		break;
440 
441 	default:
442 		zfs_panic_recover("inode %llu has invalid mode: 0x%x\n",
443 		    (u_longlong_t)ip->i_ino, ip->i_mode);
444 
445 		/* Assume the inode is a file and attempt to continue */
446 		ip->i_mode = S_IFREG | 0644;
447 		ip->i_op = &zpl_inode_operations;
448 		ip->i_fop = &zpl_file_operations;
449 		ip->i_mapping->a_ops = &zpl_address_space_operations;
450 		break;
451 	}
452 }
453 
454 static void
zfs_set_inode_flags(znode_t * zp,struct inode * ip)455 zfs_set_inode_flags(znode_t *zp, struct inode *ip)
456 {
457 	/*
458 	 * Linux and Solaris have different sets of file attributes, so we
459 	 * restrict this conversion to the intersection of the two.
460 	 */
461 	unsigned int flags = 0;
462 	if (zp->z_pflags & ZFS_IMMUTABLE)
463 		flags |= S_IMMUTABLE;
464 	if (zp->z_pflags & ZFS_APPENDONLY)
465 		flags |= S_APPEND;
466 
467 	inode_set_flags(ip, flags, S_IMMUTABLE|S_APPEND);
468 }
469 
470 /*
471  * Update the embedded inode given the znode.
472  */
473 void
zfs_znode_update_vfs(znode_t * zp)474 zfs_znode_update_vfs(znode_t *zp)
475 {
476 	struct inode	*ip;
477 	uint32_t	blksize;
478 	u_longlong_t	i_blocks;
479 
480 	ASSERT(zp != NULL);
481 	ip = ZTOI(zp);
482 
483 	/* Skip .zfs control nodes which do not exist on disk. */
484 	if (zfsctl_is_node(ip))
485 		return;
486 
487 	dmu_object_size_from_db(sa_get_db(zp->z_sa_hdl), &blksize, &i_blocks);
488 
489 	spin_lock(&ip->i_lock);
490 	ip->i_mode = zp->z_mode;
491 	ip->i_blocks = i_blocks;
492 	i_size_write(ip, zp->z_size);
493 	spin_unlock(&ip->i_lock);
494 }
495 
496 
497 /*
498  * Construct a znode+inode and initialize.
499  *
500  * This does not do a call to dmu_set_user() that is
501  * up to the caller to do, in case you don't want to
502  * return the znode
503  */
504 static znode_t *
zfs_znode_alloc(zfsvfs_t * zfsvfs,dmu_buf_t * db,int blksz,dmu_object_type_t obj_type,sa_handle_t * hdl)505 zfs_znode_alloc(zfsvfs_t *zfsvfs, dmu_buf_t *db, int blksz,
506     dmu_object_type_t obj_type, sa_handle_t *hdl)
507 {
508 	znode_t	*zp;
509 	struct inode *ip;
510 	uint64_t mode;
511 	uint64_t parent;
512 	uint64_t tmp_gen;
513 	uint64_t links;
514 	uint64_t z_uid, z_gid;
515 	uint64_t atime[2], mtime[2], ctime[2], btime[2];
516 	inode_timespec_t tmp_ts;
517 	uint64_t projid = ZFS_DEFAULT_PROJID;
518 	sa_bulk_attr_t bulk[12];
519 	int count = 0;
520 
521 	ASSERT(zfsvfs != NULL);
522 
523 	ip = new_inode(zfsvfs->z_sb);
524 	if (ip == NULL)
525 		return (NULL);
526 
527 	zp = ITOZ(ip);
528 	ASSERT0P(zp->z_dirlocks);
529 	ASSERT0P(zp->z_acl_cached);
530 	ASSERT0P(zp->z_xattr_cached);
531 	zp->z_unlinked = B_FALSE;
532 	zp->z_atime_dirty = B_FALSE;
533 	zp->z_is_ctldir = B_FALSE;
534 	zp->z_suspended = B_FALSE;
535 	zp->z_xattr_dir_absent = B_FALSE;
536 	zp->z_sa_hdl = NULL;
537 	zp->z_mapcnt = 0;
538 	zp->z_id = db->db_object;
539 	zp->z_blksz = blksz;
540 	zp->z_sync_cnt = 0;
541 
542 	zfs_znode_sa_init(zfsvfs, zp, db, obj_type, hdl);
543 
544 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL, &mode, 8);
545 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GEN(zfsvfs), NULL, &tmp_gen, 8);
546 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
547 	    &zp->z_size, 8);
548 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL, &links, 8);
549 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
550 	    &zp->z_pflags, 8);
551 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PARENT(zfsvfs), NULL,
552 	    &parent, 8);
553 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL, &z_uid, 8);
554 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL, &z_gid, 8);
555 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL, &atime, 16);
556 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
557 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
558 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, &btime, 16);
559 
560 	if (sa_bulk_lookup(zp->z_sa_hdl, bulk, count) != 0 || tmp_gen == 0 ||
561 	    (dmu_objset_projectquota_enabled(zfsvfs->z_os) &&
562 	    (zp->z_pflags & ZFS_PROJID) &&
563 	    sa_lookup(zp->z_sa_hdl, SA_ZPL_PROJID(zfsvfs), &projid, 8) != 0)) {
564 		if (hdl == NULL)
565 			sa_handle_destroy(zp->z_sa_hdl);
566 		zp->z_sa_hdl = NULL;
567 		goto error;
568 	}
569 
570 	/*
571 	 * Restore z_seq from SA_ZPL_SEQ. A successful lookup marks the file as
572 	 * migrated via the in-core z_has_seq (never persisted, so no pflag bit
573 	 * is consumed). Absence means the file predates persistence: seed z_seq
574 	 * above any cookie the pre-persistence code could have presented
575 	 * ((ctime << 32) | low) so it stays monotonic across the upgrade; the
576 	 * first modify migrates the file.
577 	 */
578 	if (zp->z_is_sa && sa_lookup(zp->z_sa_hdl, SA_ZPL_SEQ(zfsvfs),
579 	    &zp->z_seq, sizeof (zp->z_seq)) == 0) {
580 		zp->z_has_seq = B_TRUE;
581 	} else {
582 		zp->z_has_seq = B_FALSE;
583 		zp->z_seq = (ctime[0] + 1) << 32;
584 	}
585 
586 	zp->z_projid = projid;
587 	zp->z_mode = ip->i_mode = mode;
588 	ip->i_generation = (uint32_t)tmp_gen;
589 	ip->i_blkbits = SPA_MINBLOCKSHIFT;
590 	set_nlink(ip, (uint32_t)links);
591 	zfs_uid_write(ip, z_uid);
592 	zfs_gid_write(ip, z_gid);
593 	zfs_set_inode_flags(zp, ip);
594 
595 	/* Cache the xattr parent id */
596 	if (zp->z_pflags & ZFS_XATTR)
597 		zp->z_xattr_parent = parent;
598 
599 	ZFS_TIME_DECODE(&tmp_ts, atime);
600 	zpl_inode_set_atime_to_ts(ip, tmp_ts);
601 	ZFS_TIME_DECODE(&tmp_ts, mtime);
602 	zpl_inode_set_mtime_to_ts(ip, tmp_ts);
603 	ZFS_TIME_DECODE(&tmp_ts, ctime);
604 	zpl_inode_set_ctime_to_ts(ip, tmp_ts);
605 	ZFS_TIME_DECODE(&zp->z_btime, btime);
606 
607 	ip->i_ino = zp->z_id;
608 	zfs_znode_update_vfs(zp);
609 	zfs_inode_set_ops(zfsvfs, ip);
610 
611 	/*
612 	 * The only way insert_inode_locked() can fail is if the ip->i_ino
613 	 * number is already hashed for this super block.  This can never
614 	 * happen because the inode numbers map 1:1 with the object numbers.
615 	 *
616 	 * Exceptions include rolling back a mounted file system, either
617 	 * from the zfs rollback or zfs recv command.
618 	 *
619 	 * Active inodes are unhashed during the rollback, but since zrele
620 	 * can happen asynchronously, we can't guarantee they've been
621 	 * unhashed.  This can cause hash collisions in unlinked drain
622 	 * processing so do not hash unlinked znodes.
623 	 */
624 	if (links > 0)
625 		VERIFY0(insert_inode_locked(ip));
626 
627 	mutex_enter(&zfsvfs->z_znodes_lock);
628 	list_insert_tail(&zfsvfs->z_all_znodes, zp);
629 	mutex_exit(&zfsvfs->z_znodes_lock);
630 
631 	if (links > 0)
632 		unlock_new_inode(ip);
633 	return (zp);
634 
635 error:
636 	iput(ip);
637 	return (NULL);
638 }
639 
640 /*
641  * Safely mark an inode dirty.  Inodes which are part of a read-only
642  * file system or snapshot may not be dirtied.
643  */
644 void
zfs_mark_inode_dirty(struct inode * ip)645 zfs_mark_inode_dirty(struct inode *ip)
646 {
647 	zfsvfs_t *zfsvfs = ITOZSB(ip);
648 
649 	if (zfs_is_readonly(zfsvfs) || dmu_objset_is_snapshot(zfsvfs->z_os))
650 		return;
651 
652 	mark_inode_dirty(ip);
653 }
654 
655 static uint64_t empty_xattr;
656 static uint64_t pad[4];
657 static zfs_acl_phys_t acl_phys;
658 /*
659  * Create a new DMU object to hold a zfs znode.
660  *
661  *	IN:	dzp	- parent directory for new znode
662  *		vap	- file attributes for new znode
663  *		tx	- dmu transaction id for zap operations
664  *		cr	- credentials of caller
665  *		flag	- flags:
666  *			  IS_ROOT_NODE	- new object will be root
667  *			  IS_TMPFILE	- new object is of O_TMPFILE
668  *			  IS_XATTR	- new object is an attribute
669  *		acl_ids	- ACL related attributes
670  *
671  *	OUT:	zpp	- allocated znode (set to dzp if IS_ROOT_NODE)
672  *
673  */
674 void
zfs_mknode(znode_t * dzp,vattr_t * vap,dmu_tx_t * tx,cred_t * cr,uint_t flag,znode_t ** zpp,zfs_acl_ids_t * acl_ids)675 zfs_mknode(znode_t *dzp, vattr_t *vap, dmu_tx_t *tx, cred_t *cr,
676     uint_t flag, znode_t **zpp, zfs_acl_ids_t *acl_ids)
677 {
678 	uint64_t	crtime[2], atime[2], mtime[2], ctime[2];
679 	uint64_t	mode, size, links, parent, pflags;
680 	uint64_t	projid = ZFS_DEFAULT_PROJID;
681 	uint64_t	rdev = 0;
682 	zfsvfs_t	*zfsvfs = ZTOZSB(dzp);
683 	dmu_buf_t	*db;
684 	inode_timespec_t now;
685 	uint64_t	gen, obj;
686 	int		bonuslen;
687 	int		dnodesize;
688 	sa_handle_t	*sa_hdl;
689 	dmu_object_type_t obj_type;
690 	sa_bulk_attr_t	*sa_attrs;
691 	int		cnt = 0;
692 	zfs_acl_locator_cb_t locate = { 0 };
693 	znode_hold_t	*zh;
694 
695 	if (zfsvfs->z_replay) {
696 		obj = vap->va_nodeid;
697 		now = vap->va_ctime;		/* see zfs_replay_create() */
698 		gen = vap->va_nblocks;		/* ditto */
699 		dnodesize = vap->va_fsid;	/* ditto */
700 	} else {
701 		obj = 0;
702 		gethrestime(&now);
703 		gen = dmu_tx_get_txg(tx);
704 		dnodesize = dmu_objset_dnodesize(zfsvfs->z_os);
705 	}
706 
707 	if (dnodesize == 0)
708 		dnodesize = DNODE_MIN_SIZE;
709 
710 	obj_type = zfsvfs->z_use_sa ? DMU_OT_SA : DMU_OT_ZNODE;
711 
712 	bonuslen = (obj_type == DMU_OT_SA) ?
713 	    DN_BONUS_SIZE(dnodesize) : ZFS_OLD_ZNODE_PHYS_SIZE;
714 
715 	/*
716 	 * Create a new DMU object.
717 	 */
718 	/*
719 	 * There's currently no mechanism for pre-reading the blocks that will
720 	 * be needed to allocate a new object, so we accept the small chance
721 	 * that there will be an i/o error and we will fail one of the
722 	 * assertions below.
723 	 */
724 	if (S_ISDIR(vap->va_mode)) {
725 		if (zfsvfs->z_replay) {
726 			VERIFY0(zap_create_claim_norm_dnsize(zfsvfs->z_os, obj,
727 			    zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
728 			    obj_type, bonuslen, dnodesize, tx));
729 		} else {
730 			obj = zap_create_norm_dnsize(zfsvfs->z_os,
731 			    zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
732 			    obj_type, bonuslen, dnodesize, tx);
733 		}
734 	} else {
735 		if (zfsvfs->z_replay) {
736 			VERIFY0(dmu_object_claim_dnsize(zfsvfs->z_os, obj,
737 			    DMU_OT_PLAIN_FILE_CONTENTS, 0,
738 			    obj_type, bonuslen, dnodesize, tx));
739 		} else {
740 			obj = dmu_object_alloc_dnsize(zfsvfs->z_os,
741 			    DMU_OT_PLAIN_FILE_CONTENTS, 0,
742 			    obj_type, bonuslen, dnodesize, tx);
743 		}
744 	}
745 
746 	zh = zfs_znode_hold_enter(zfsvfs, obj);
747 	VERIFY0(sa_buf_hold(zfsvfs->z_os, obj, NULL, &db));
748 
749 	/*
750 	 * If this is the root, fix up the half-initialized parent pointer
751 	 * to reference the just-allocated physical data area.
752 	 */
753 	if (flag & IS_ROOT_NODE) {
754 		dzp->z_id = obj;
755 	}
756 
757 	/*
758 	 * If parent is an xattr, so am I.
759 	 */
760 	if (dzp->z_pflags & ZFS_XATTR) {
761 		flag |= IS_XATTR;
762 	}
763 
764 	if (zfsvfs->z_use_fuids)
765 		pflags = ZFS_ARCHIVE | ZFS_AV_MODIFIED;
766 	else
767 		pflags = 0;
768 
769 	if (S_ISDIR(vap->va_mode)) {
770 		size = 2;		/* contents ("." and "..") */
771 		links = 2;
772 	} else {
773 		size = 0;
774 		links = (flag & IS_TMPFILE) ? 0 : 1;
775 	}
776 
777 	if (S_ISBLK(vap->va_mode) || S_ISCHR(vap->va_mode))
778 		rdev = vap->va_rdev;
779 
780 	parent = dzp->z_id;
781 	mode = acl_ids->z_mode;
782 	if (flag & IS_XATTR)
783 		pflags |= ZFS_XATTR;
784 
785 	/*
786 	 * With ZFS_PROJID flag, we can easily know whether there is
787 	 * project ID stored on disk or not. See zpl_get_file_info().
788 	 */
789 	if (obj_type != DMU_OT_ZNODE &&
790 	    dmu_objset_projectquota_enabled(zfsvfs->z_os))
791 		pflags |= ZFS_PROJID;
792 
793 	/*
794 	 * Inherit project ID from parent if required.  Every object type
795 	 * takes part, as ext4 and XFS do: an object that carried no project
796 	 * ID of its own would be treated as belonging to a different project
797 	 * than the directory holding it, so zfs_rename() and zfs_link()
798 	 * would refuse it with EXDEV even within its own project.
799 	 *
800 	 * The ZFS_PROJINHERIT flag itself keeps passing to regular files and
801 	 * directories only, as before, so that lsattr(1) output is unchanged.
802 	 */
803 	projid = zfs_inherit_projid(dzp);
804 	if ((S_ISREG(vap->va_mode) || S_ISDIR(vap->va_mode)) &&
805 	    (dzp->z_pflags & ZFS_PROJINHERIT))
806 		pflags |= ZFS_PROJINHERIT;
807 
808 	/*
809 	 * No execs denied will be determined when zfs_mode_compute() is called.
810 	 */
811 	pflags |= acl_ids->z_aclp->z_hints &
812 	    (ZFS_ACL_TRIVIAL|ZFS_INHERIT_ACE|ZFS_ACL_AUTO_INHERIT|
813 	    ZFS_ACL_DEFAULTED|ZFS_ACL_PROTECTED);
814 
815 	ZFS_TIME_ENCODE(&now, crtime);
816 	ZFS_TIME_ENCODE(&now, ctime);
817 
818 	if (vap->va_mask & ATTR_ATIME) {
819 		ZFS_TIME_ENCODE(&vap->va_atime, atime);
820 	} else {
821 		ZFS_TIME_ENCODE(&now, atime);
822 	}
823 
824 	if (vap->va_mask & ATTR_MTIME) {
825 		ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
826 	} else {
827 		ZFS_TIME_ENCODE(&now, mtime);
828 	}
829 
830 	/* Now add in all of the "SA" attributes */
831 	VERIFY0(sa_handle_get_from_db(zfsvfs->z_os, db, NULL, SA_HDL_SHARED,
832 	    &sa_hdl));
833 
834 	/*
835 	 * Setup the array of attributes to be replaced/set on the new file
836 	 *
837 	 * order for  DMU_OT_ZNODE is critical since it needs to be constructed
838 	 * in the old znode_phys_t format.  Don't change this ordering
839 	 */
840 	sa_attrs = kmem_alloc(sizeof (sa_bulk_attr_t) * ZPL_END, KM_SLEEP);
841 
842 	if (obj_type == DMU_OT_ZNODE) {
843 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ATIME(zfsvfs),
844 		    NULL, &atime, 16);
845 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MTIME(zfsvfs),
846 		    NULL, &mtime, 16);
847 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CTIME(zfsvfs),
848 		    NULL, &ctime, 16);
849 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CRTIME(zfsvfs),
850 		    NULL, &crtime, 16);
851 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GEN(zfsvfs),
852 		    NULL, &gen, 8);
853 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MODE(zfsvfs),
854 		    NULL, &mode, 8);
855 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_SIZE(zfsvfs),
856 		    NULL, &size, 8);
857 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PARENT(zfsvfs),
858 		    NULL, &parent, 8);
859 	} else {
860 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MODE(zfsvfs),
861 		    NULL, &mode, 8);
862 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_SIZE(zfsvfs),
863 		    NULL, &size, 8);
864 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GEN(zfsvfs),
865 		    NULL, &gen, 8);
866 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_UID(zfsvfs),
867 		    NULL, &acl_ids->z_fuid, 8);
868 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GID(zfsvfs),
869 		    NULL, &acl_ids->z_fgid, 8);
870 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PARENT(zfsvfs),
871 		    NULL, &parent, 8);
872 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_FLAGS(zfsvfs),
873 		    NULL, &pflags, 8);
874 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ATIME(zfsvfs),
875 		    NULL, &atime, 16);
876 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MTIME(zfsvfs),
877 		    NULL, &mtime, 16);
878 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CTIME(zfsvfs),
879 		    NULL, &ctime, 16);
880 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CRTIME(zfsvfs),
881 		    NULL, &crtime, 16);
882 	}
883 
884 	SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_LINKS(zfsvfs), NULL, &links, 8);
885 
886 	if (obj_type == DMU_OT_ZNODE) {
887 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_XATTR(zfsvfs), NULL,
888 		    &empty_xattr, 8);
889 	} else if (dmu_objset_projectquota_enabled(zfsvfs->z_os) &&
890 	    pflags & ZFS_PROJID) {
891 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PROJID(zfsvfs),
892 		    NULL, &projid, 8);
893 	}
894 	if (obj_type == DMU_OT_ZNODE ||
895 	    (S_ISBLK(vap->va_mode) || S_ISCHR(vap->va_mode))) {
896 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_RDEV(zfsvfs),
897 		    NULL, &rdev, 8);
898 	}
899 	if (obj_type == DMU_OT_ZNODE) {
900 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_FLAGS(zfsvfs),
901 		    NULL, &pflags, 8);
902 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_UID(zfsvfs), NULL,
903 		    &acl_ids->z_fuid, 8);
904 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GID(zfsvfs), NULL,
905 		    &acl_ids->z_fgid, 8);
906 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PAD(zfsvfs), NULL, pad,
907 		    sizeof (uint64_t) * 4);
908 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ZNODE_ACL(zfsvfs), NULL,
909 		    &acl_phys, sizeof (zfs_acl_phys_t));
910 	} else if (acl_ids->z_aclp->z_version >= ZFS_ACL_VERSION_FUID) {
911 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_DACL_COUNT(zfsvfs), NULL,
912 		    &acl_ids->z_aclp->z_acl_count, 8);
913 		locate.cb_aclp = acl_ids->z_aclp;
914 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_DACL_ACES(zfsvfs),
915 		    zfs_acl_data_locator, &locate,
916 		    acl_ids->z_aclp->z_acl_bytes);
917 		mode = zfs_mode_compute(mode, acl_ids->z_aclp, &pflags,
918 		    acl_ids->z_fuid, acl_ids->z_fgid);
919 	}
920 
921 	VERIFY0(sa_replace_all_by_template(sa_hdl, sa_attrs, cnt, tx));
922 
923 	if (!(flag & IS_ROOT_NODE)) {
924 		/*
925 		 * The call to zfs_znode_alloc() may fail if memory is low
926 		 * via the call path: alloc_inode() -> inode_init_always() ->
927 		 * security_inode_alloc() -> inode_alloc_security().  Since
928 		 * the existing code is written such that zfs_mknode() can
929 		 * not fail retry until sufficient memory has been reclaimed.
930 		 */
931 		do {
932 			*zpp = zfs_znode_alloc(zfsvfs, db, 0, obj_type, sa_hdl);
933 		} while (*zpp == NULL);
934 
935 		VERIFY(*zpp != NULL);
936 		VERIFY(dzp != NULL);
937 	} else {
938 		/*
939 		 * If we are creating the root node, the "parent" we
940 		 * passed in is the znode for the root.
941 		 */
942 		*zpp = dzp;
943 
944 		(*zpp)->z_sa_hdl = sa_hdl;
945 	}
946 
947 	(*zpp)->z_pflags = pflags;
948 	(*zpp)->z_mode = ZTOI(*zpp)->i_mode = mode;
949 	(*zpp)->z_dnodesize = dnodesize;
950 	(*zpp)->z_projid = projid;
951 
952 	if (obj_type == DMU_OT_ZNODE ||
953 	    acl_ids->z_aclp->z_version < ZFS_ACL_VERSION_FUID) {
954 		VERIFY0(zfs_aclset_common(*zpp, acl_ids->z_aclp, cr, tx));
955 	}
956 	kmem_free(sa_attrs, sizeof (sa_bulk_attr_t) * ZPL_END);
957 	zfs_znode_hold_exit(zfsvfs, zh);
958 }
959 
960 /*
961  * Update in-core attributes.  It is assumed the caller will be doing an
962  * sa_bulk_update to push the changes out.
963  */
964 void
zfs_xvattr_set(znode_t * zp,xvattr_t * xvap,dmu_tx_t * tx)965 zfs_xvattr_set(znode_t *zp, xvattr_t *xvap, dmu_tx_t *tx)
966 {
967 	xoptattr_t *xoap;
968 	boolean_t update_inode = B_FALSE;
969 
970 	xoap = xva_getxoptattr(xvap);
971 	ASSERT(xoap);
972 
973 	if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
974 		uint64_t times[2];
975 		ZFS_TIME_ENCODE(&xoap->xoa_createtime, times);
976 		(void) sa_update(zp->z_sa_hdl, SA_ZPL_CRTIME(ZTOZSB(zp)),
977 		    &times, sizeof (times), tx);
978 		XVA_SET_RTN(xvap, XAT_CREATETIME);
979 	}
980 	if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
981 		ZFS_ATTR_SET(zp, ZFS_READONLY, xoap->xoa_readonly,
982 		    zp->z_pflags, tx);
983 		XVA_SET_RTN(xvap, XAT_READONLY);
984 	}
985 	if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
986 		ZFS_ATTR_SET(zp, ZFS_HIDDEN, xoap->xoa_hidden,
987 		    zp->z_pflags, tx);
988 		XVA_SET_RTN(xvap, XAT_HIDDEN);
989 	}
990 	if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
991 		ZFS_ATTR_SET(zp, ZFS_SYSTEM, xoap->xoa_system,
992 		    zp->z_pflags, tx);
993 		XVA_SET_RTN(xvap, XAT_SYSTEM);
994 	}
995 	if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
996 		ZFS_ATTR_SET(zp, ZFS_ARCHIVE, xoap->xoa_archive,
997 		    zp->z_pflags, tx);
998 		XVA_SET_RTN(xvap, XAT_ARCHIVE);
999 	}
1000 	if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
1001 		ZFS_ATTR_SET(zp, ZFS_IMMUTABLE, xoap->xoa_immutable,
1002 		    zp->z_pflags, tx);
1003 		XVA_SET_RTN(xvap, XAT_IMMUTABLE);
1004 
1005 		update_inode = B_TRUE;
1006 	}
1007 	if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
1008 		ZFS_ATTR_SET(zp, ZFS_NOUNLINK, xoap->xoa_nounlink,
1009 		    zp->z_pflags, tx);
1010 		XVA_SET_RTN(xvap, XAT_NOUNLINK);
1011 	}
1012 	if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
1013 		ZFS_ATTR_SET(zp, ZFS_APPENDONLY, xoap->xoa_appendonly,
1014 		    zp->z_pflags, tx);
1015 		XVA_SET_RTN(xvap, XAT_APPENDONLY);
1016 
1017 		update_inode = B_TRUE;
1018 	}
1019 	if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
1020 		ZFS_ATTR_SET(zp, ZFS_NODUMP, xoap->xoa_nodump,
1021 		    zp->z_pflags, tx);
1022 		XVA_SET_RTN(xvap, XAT_NODUMP);
1023 	}
1024 	if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
1025 		ZFS_ATTR_SET(zp, ZFS_OPAQUE, xoap->xoa_opaque,
1026 		    zp->z_pflags, tx);
1027 		XVA_SET_RTN(xvap, XAT_OPAQUE);
1028 	}
1029 	if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
1030 		ZFS_ATTR_SET(zp, ZFS_AV_QUARANTINED,
1031 		    xoap->xoa_av_quarantined, zp->z_pflags, tx);
1032 		XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
1033 	}
1034 	if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
1035 		ZFS_ATTR_SET(zp, ZFS_AV_MODIFIED, xoap->xoa_av_modified,
1036 		    zp->z_pflags, tx);
1037 		XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
1038 	}
1039 	if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) {
1040 		zfs_sa_set_scanstamp(zp, xvap, tx);
1041 		XVA_SET_RTN(xvap, XAT_AV_SCANSTAMP);
1042 	}
1043 	if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
1044 		ZFS_ATTR_SET(zp, ZFS_REPARSE, xoap->xoa_reparse,
1045 		    zp->z_pflags, tx);
1046 		XVA_SET_RTN(xvap, XAT_REPARSE);
1047 	}
1048 	if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
1049 		ZFS_ATTR_SET(zp, ZFS_OFFLINE, xoap->xoa_offline,
1050 		    zp->z_pflags, tx);
1051 		XVA_SET_RTN(xvap, XAT_OFFLINE);
1052 	}
1053 	if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
1054 		ZFS_ATTR_SET(zp, ZFS_SPARSE, xoap->xoa_sparse,
1055 		    zp->z_pflags, tx);
1056 		XVA_SET_RTN(xvap, XAT_SPARSE);
1057 	}
1058 	if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
1059 		ZFS_ATTR_SET(zp, ZFS_PROJINHERIT, xoap->xoa_projinherit,
1060 		    zp->z_pflags, tx);
1061 		XVA_SET_RTN(xvap, XAT_PROJINHERIT);
1062 	}
1063 
1064 	if (update_inode)
1065 		zfs_set_inode_flags(zp, ZTOI(zp));
1066 }
1067 
1068 int
zfs_zget(zfsvfs_t * zfsvfs,uint64_t obj_num,znode_t ** zpp)1069 zfs_zget(zfsvfs_t *zfsvfs, uint64_t obj_num, znode_t **zpp)
1070 {
1071 	dmu_object_info_t doi;
1072 	dmu_buf_t	*db;
1073 	znode_t		*zp;
1074 	znode_hold_t	*zh;
1075 	int err;
1076 	sa_handle_t	*hdl;
1077 
1078 	*zpp = NULL;
1079 
1080 again:
1081 	zh = zfs_znode_hold_enter(zfsvfs, obj_num);
1082 
1083 	err = sa_buf_hold(zfsvfs->z_os, obj_num, NULL, &db);
1084 	if (err) {
1085 		zfs_znode_hold_exit(zfsvfs, zh);
1086 		return (err);
1087 	}
1088 
1089 	dmu_object_info_from_db(db, &doi);
1090 	if (doi.doi_bonus_type != DMU_OT_SA &&
1091 	    (doi.doi_bonus_type != DMU_OT_ZNODE ||
1092 	    (doi.doi_bonus_type == DMU_OT_ZNODE &&
1093 	    doi.doi_bonus_size < sizeof (znode_phys_t)))) {
1094 		sa_buf_rele(db, NULL);
1095 		zfs_znode_hold_exit(zfsvfs, zh);
1096 		return (SET_ERROR(EINVAL));
1097 	}
1098 
1099 	hdl = dmu_buf_get_user(db);
1100 	if (hdl != NULL) {
1101 		zp = sa_get_userdata(hdl);
1102 
1103 
1104 		/*
1105 		 * Since "SA" does immediate eviction we
1106 		 * should never find a sa handle that doesn't
1107 		 * know about the znode.
1108 		 */
1109 
1110 		ASSERT3P(zp, !=, NULL);
1111 
1112 		mutex_enter(&zp->z_lock);
1113 		ASSERT3U(zp->z_id, ==, obj_num);
1114 		/*
1115 		 * If zp->z_unlinked is set, the znode is already marked
1116 		 * for deletion and should not be discovered. Check this
1117 		 * after checking igrab() due to fsetxattr() & O_TMPFILE.
1118 		 *
1119 		 * If igrab() returns NULL the VFS has independently
1120 		 * determined the inode should be evicted and has
1121 		 * called iput_final() to start the eviction process.
1122 		 * The SA handle is still valid but because the VFS
1123 		 * requires that the eviction succeed we must drop
1124 		 * our locks and references to allow the eviction to
1125 		 * complete.  The zfs_zget() may then be retried.
1126 		 *
1127 		 * This unlikely case could be optimized by registering
1128 		 * a sops->drop_inode() callback.  The callback would
1129 		 * need to detect the active SA hold thereby informing
1130 		 * the VFS that this inode should not be evicted.
1131 		 */
1132 		if (igrab(ZTOI(zp)) == NULL) {
1133 			if (zp->z_unlinked)
1134 				err = SET_ERROR(ENOENT);
1135 			else
1136 				err = SET_ERROR(EAGAIN);
1137 		} else {
1138 			*zpp = zp;
1139 			err = 0;
1140 		}
1141 
1142 		mutex_exit(&zp->z_lock);
1143 		sa_buf_rele(db, NULL);
1144 		zfs_znode_hold_exit(zfsvfs, zh);
1145 
1146 		if (err == EAGAIN) {
1147 			/* inode might need this to finish evict */
1148 			cond_resched();
1149 			goto again;
1150 		}
1151 		return (err);
1152 	}
1153 
1154 	/*
1155 	 * Not found create new znode/vnode but only if file exists.
1156 	 *
1157 	 * There is a small window where zfs_vget() could
1158 	 * find this object while a file create is still in
1159 	 * progress.  This is checked for in zfs_znode_alloc()
1160 	 *
1161 	 * if zfs_znode_alloc() fails it will drop the hold on the
1162 	 * bonus buffer.
1163 	 */
1164 	zp = zfs_znode_alloc(zfsvfs, db, doi.doi_data_block_size,
1165 	    doi.doi_bonus_type, NULL);
1166 	if (zp == NULL) {
1167 		err = SET_ERROR(ENOENT);
1168 	} else {
1169 		*zpp = zp;
1170 	}
1171 	zfs_znode_hold_exit(zfsvfs, zh);
1172 	return (err);
1173 }
1174 
1175 int
zfs_rezget(znode_t * zp)1176 zfs_rezget(znode_t *zp)
1177 {
1178 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
1179 	dmu_object_info_t doi;
1180 	dmu_buf_t *db;
1181 	uint64_t obj_num = zp->z_id;
1182 	uint64_t mode;
1183 	uint64_t links;
1184 	sa_bulk_attr_t bulk[11];
1185 	int err;
1186 	int count = 0;
1187 	uint64_t gen;
1188 	uint64_t z_uid, z_gid;
1189 	uint64_t atime[2], mtime[2], ctime[2], btime[2];
1190 	inode_timespec_t tmp_ts;
1191 	uint64_t projid = ZFS_DEFAULT_PROJID;
1192 	znode_hold_t *zh;
1193 
1194 	/*
1195 	 * skip ctldir, otherwise they will always get invalidated. This will
1196 	 * cause funny behaviour for the mounted snapdirs. Especially for
1197 	 * Linux >= 3.18, d_invalidate will detach the mountpoint and prevent
1198 	 * anyone automount it again as long as someone is still using the
1199 	 * detached mount.
1200 	 */
1201 	if (zp->z_is_ctldir)
1202 		return (0);
1203 
1204 	/*
1205 	 * Drop cached pages before reloading the znode.  After a rollback or
1206 	 * a forced receive the object may hold different data under the same
1207 	 * inode, size and generation; stale Uptodate pages would otherwise be
1208 	 * served by mappedread() and mmap() (see #10931).  FreeBSD does the
1209 	 * same here via vn_pages_remove().
1210 	 */
1211 	truncate_inode_pages(ZTOI(zp)->i_mapping, 0);
1212 
1213 	zh = zfs_znode_hold_enter(zfsvfs, obj_num);
1214 
1215 	mutex_enter(&zp->z_acl_lock);
1216 	if (zp->z_acl_cached) {
1217 		zfs_acl_free(zp->z_acl_cached);
1218 		zp->z_acl_cached = NULL;
1219 	}
1220 	mutex_exit(&zp->z_acl_lock);
1221 
1222 #ifdef CONFIG_FS_POSIX_ACL
1223 	/* The VFS cache can still describe the pre-rollback inode. */
1224 	forget_cached_acl(ZTOI(zp), ACL_TYPE_ACCESS);
1225 	forget_cached_acl(ZTOI(zp), ACL_TYPE_DEFAULT);
1226 #endif
1227 
1228 	rw_enter(&zp->z_xattr_lock, RW_WRITER);
1229 	if (zp->z_xattr_cached) {
1230 		nvlist_free(zp->z_xattr_cached);
1231 		zp->z_xattr_cached = NULL;
1232 	}
1233 	rw_exit(&zp->z_xattr_lock);
1234 
1235 	zp->z_xattr_dir_absent = B_FALSE;
1236 
1237 	ASSERT0P(zp->z_sa_hdl);
1238 	err = sa_buf_hold(zfsvfs->z_os, obj_num, NULL, &db);
1239 	if (err) {
1240 		zfs_znode_hold_exit(zfsvfs, zh);
1241 		return (err);
1242 	}
1243 
1244 	dmu_object_info_from_db(db, &doi);
1245 	if (doi.doi_bonus_type != DMU_OT_SA &&
1246 	    (doi.doi_bonus_type != DMU_OT_ZNODE ||
1247 	    (doi.doi_bonus_type == DMU_OT_ZNODE &&
1248 	    doi.doi_bonus_size < sizeof (znode_phys_t)))) {
1249 		sa_buf_rele(db, NULL);
1250 		zfs_znode_hold_exit(zfsvfs, zh);
1251 		return (SET_ERROR(EINVAL));
1252 	}
1253 
1254 	zfs_znode_sa_init(zfsvfs, zp, db, doi.doi_bonus_type, NULL);
1255 
1256 	/* reload cached values */
1257 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GEN(zfsvfs), NULL,
1258 	    &gen, sizeof (gen));
1259 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
1260 	    &zp->z_size, sizeof (zp->z_size));
1261 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
1262 	    &links, sizeof (links));
1263 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
1264 	    &zp->z_pflags, sizeof (zp->z_pflags));
1265 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
1266 	    &z_uid, sizeof (z_uid));
1267 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
1268 	    &z_gid, sizeof (z_gid));
1269 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
1270 	    &mode, sizeof (mode));
1271 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
1272 	    &atime, 16);
1273 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
1274 	    &mtime, 16);
1275 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
1276 	    &ctime, 16);
1277 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, &btime, 16);
1278 
1279 	if (sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) {
1280 		zfs_znode_dmu_fini(zp);
1281 		zfs_znode_hold_exit(zfsvfs, zh);
1282 		return (SET_ERROR(EIO));
1283 	}
1284 
1285 	if (dmu_objset_projectquota_enabled(zfsvfs->z_os)) {
1286 		err = sa_lookup(zp->z_sa_hdl, SA_ZPL_PROJID(zfsvfs),
1287 		    &projid, 8);
1288 		if (err != 0 && err != ENOENT) {
1289 			zfs_znode_dmu_fini(zp);
1290 			zfs_znode_hold_exit(zfsvfs, zh);
1291 			return (SET_ERROR(err));
1292 		}
1293 	}
1294 
1295 	zp->z_projid = projid;
1296 
1297 	/*
1298 	 * Reload z_has_seq and z_seq from disk so stale in-core state from
1299 	 * before rollback/recv does not survive. A stale TRUE marker would
1300 	 * make ZFS_SEQ_MAY_GROW() skip the grow reservation while SA_ZPL_SEQ
1301 	 * is gone on disk.
1302 	 */
1303 	zp->z_has_seq = (zp->z_is_sa &&
1304 	    sa_lookup(zp->z_sa_hdl, SA_ZPL_SEQ(zfsvfs),
1305 	    &zp->z_seq, sizeof (zp->z_seq)) == 0);
1306 
1307 	zp->z_mode = ZTOI(zp)->i_mode = mode;
1308 	zfs_uid_write(ZTOI(zp), z_uid);
1309 	zfs_gid_write(ZTOI(zp), z_gid);
1310 
1311 	ZFS_TIME_DECODE(&tmp_ts, atime);
1312 	zpl_inode_set_atime_to_ts(ZTOI(zp), tmp_ts);
1313 	ZFS_TIME_DECODE(&tmp_ts, mtime);
1314 	zpl_inode_set_mtime_to_ts(ZTOI(zp), tmp_ts);
1315 	ZFS_TIME_DECODE(&tmp_ts, ctime);
1316 	zpl_inode_set_ctime_to_ts(ZTOI(zp), tmp_ts);
1317 	ZFS_TIME_DECODE(&zp->z_btime, btime);
1318 
1319 	if ((uint32_t)gen != ZTOI(zp)->i_generation) {
1320 		zfs_znode_dmu_fini(zp);
1321 		zfs_znode_hold_exit(zfsvfs, zh);
1322 		return (SET_ERROR(EIO));
1323 	}
1324 
1325 	set_nlink(ZTOI(zp), (uint32_t)links);
1326 	zfs_set_inode_flags(zp, ZTOI(zp));
1327 
1328 	zp->z_blksz = doi.doi_data_block_size;
1329 	zp->z_atime_dirty = B_FALSE;
1330 	zfs_znode_update_vfs(zp);
1331 
1332 	/*
1333 	 * If the file has zero links, then it has been unlinked on the send
1334 	 * side and it must be in the received unlinked set.
1335 	 * We call zfs_znode_dmu_fini() now to prevent any accesses to the
1336 	 * stale data and to prevent automatic removal of the file in
1337 	 * zfs_zinactive().  The file will be removed either when it is removed
1338 	 * on the send side and the next incremental stream is received or
1339 	 * when the unlinked set gets processed.
1340 	 */
1341 	zp->z_unlinked = (ZTOI(zp)->i_nlink == 0);
1342 	if (zp->z_unlinked)
1343 		zfs_znode_dmu_fini(zp);
1344 
1345 	zfs_znode_hold_exit(zfsvfs, zh);
1346 
1347 	return (0);
1348 }
1349 
1350 void
zfs_znode_delete(znode_t * zp,dmu_tx_t * tx)1351 zfs_znode_delete(znode_t *zp, dmu_tx_t *tx)
1352 {
1353 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
1354 	objset_t *os = zfsvfs->z_os;
1355 	uint64_t obj = zp->z_id;
1356 	uint64_t acl_obj = zfs_external_acl(zp);
1357 	znode_hold_t *zh;
1358 
1359 	zh = zfs_znode_hold_enter(zfsvfs, obj);
1360 	if (acl_obj) {
1361 		VERIFY(!zp->z_is_sa);
1362 		VERIFY0(dmu_object_free(os, acl_obj, tx));
1363 	}
1364 	VERIFY0(dmu_object_free(os, obj, tx));
1365 	zfs_znode_dmu_fini(zp);
1366 	zfs_znode_hold_exit(zfsvfs, zh);
1367 }
1368 
1369 void
zfs_zinactive(znode_t * zp)1370 zfs_zinactive(znode_t *zp)
1371 {
1372 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
1373 	uint64_t z_id = zp->z_id;
1374 	znode_hold_t *zh;
1375 
1376 	ASSERT(zp->z_sa_hdl);
1377 
1378 	/*
1379 	 * Don't allow a zfs_zget() while were trying to release this znode.
1380 	 */
1381 	zh = zfs_znode_hold_enter(zfsvfs, z_id);
1382 
1383 	mutex_enter(&zp->z_lock);
1384 
1385 	/*
1386 	 * If this was the last reference to a file with no links, remove
1387 	 * the file from the file system unless the file system is mounted
1388 	 * read-only.  That can happen, for example, if the file system was
1389 	 * originally read-write, the file was opened, then unlinked and
1390 	 * the file system was made read-only before the file was finally
1391 	 * closed.  The file will remain in the unlinked set.
1392 	 */
1393 	if (zp->z_unlinked) {
1394 		ASSERT(!zfsvfs->z_issnap);
1395 		if (!zfs_is_readonly(zfsvfs) && !zfs_unlink_suspend_progress) {
1396 			mutex_exit(&zp->z_lock);
1397 			zfs_znode_hold_exit(zfsvfs, zh);
1398 			zfs_rmnode(zp);
1399 			return;
1400 		}
1401 	}
1402 
1403 	mutex_exit(&zp->z_lock);
1404 	zfs_znode_dmu_fini(zp);
1405 
1406 	zfs_znode_hold_exit(zfsvfs, zh);
1407 }
1408 
1409 /*
1410  * Determine whether the znode's atime must be updated.  The logic mostly
1411  * duplicates the Linux kernel's relatime_need_update() functionality.
1412  * This function is only called if the underlying filesystem actually has
1413  * atime updates enabled.
1414  */
1415 boolean_t
zfs_relatime_need_update(const struct inode * ip)1416 zfs_relatime_need_update(const struct inode *ip)
1417 {
1418 	inode_timespec_t now, tmp_atime, tmp_ts;
1419 
1420 	gethrestime(&now);
1421 	tmp_atime = zpl_inode_get_atime(ip);
1422 	/*
1423 	 * In relatime mode, only update the atime if the previous atime
1424 	 * is earlier than either the ctime or mtime or if at least a day
1425 	 * has passed since the last update of atime.
1426 	 */
1427 	tmp_ts = zpl_inode_get_mtime(ip);
1428 	if (timespec64_compare(&tmp_ts, &tmp_atime) >= 0)
1429 		return (B_TRUE);
1430 
1431 	tmp_ts = zpl_inode_get_ctime(ip);
1432 	if (timespec64_compare(&tmp_ts, &tmp_atime) >= 0)
1433 		return (B_TRUE);
1434 
1435 	if ((hrtime_t)now.tv_sec - (hrtime_t)tmp_atime.tv_sec >= 24*60*60)
1436 		return (B_TRUE);
1437 
1438 	return (B_FALSE);
1439 }
1440 
1441 /*
1442  * Prepare to update znode time stamps.
1443  *
1444  *	IN:	zp	- znode requiring timestamp update
1445  *		flag	- ATTR_MTIME, ATTR_CTIME flags
1446  *
1447  *	OUT:	zp	- z_seq
1448  *		mtime	- new mtime
1449  *		ctime	- new ctime
1450  *
1451  *	Note: We don't update atime here, because we rely on Linux VFS to do
1452  *	atime updating.
1453  */
1454 void
zfs_tstamp_update_setup(znode_t * zp,uint_t flag,uint64_t mtime[2],uint64_t ctime[2])1455 zfs_tstamp_update_setup(znode_t *zp, uint_t flag, uint64_t mtime[2],
1456     uint64_t ctime[2])
1457 {
1458 	inode_timespec_t now, tmp_ts;
1459 
1460 	gethrestime(&now);
1461 
1462 	atomic_inc_64(&zp->z_seq);
1463 
1464 	if (flag & ATTR_MTIME) {
1465 		ZFS_TIME_ENCODE(&now, mtime);
1466 		ZFS_TIME_DECODE(&tmp_ts, mtime);
1467 		zpl_inode_set_mtime_to_ts(ZTOI(zp), tmp_ts);
1468 		if (ZTOZSB(zp)->z_use_fuids) {
1469 			zp->z_pflags |= (ZFS_ARCHIVE |
1470 			    ZFS_AV_MODIFIED);
1471 		}
1472 	}
1473 
1474 	if (flag & ATTR_CTIME) {
1475 		ZFS_TIME_ENCODE(&now, ctime);
1476 		ZFS_TIME_DECODE(&tmp_ts, ctime);
1477 		zpl_inode_set_ctime_to_ts(ZTOI(zp), tmp_ts);
1478 		if (ZTOZSB(zp)->z_use_fuids)
1479 			zp->z_pflags |= ZFS_ARCHIVE;
1480 	}
1481 }
1482 
1483 /*
1484  * Grow the block size for a file.
1485  *
1486  *	IN:	zp	- znode of file to free data in.
1487  *		size	- requested block size
1488  *		tx	- open transaction.
1489  *
1490  * NOTE: this function assumes that the znode is write locked.
1491  */
1492 void
zfs_grow_blocksize(znode_t * zp,uint64_t size,dmu_tx_t * tx)1493 zfs_grow_blocksize(znode_t *zp, uint64_t size, dmu_tx_t *tx)
1494 {
1495 	int		error;
1496 	u_longlong_t	dummy;
1497 
1498 	if (size <= zp->z_blksz)
1499 		return;
1500 	/*
1501 	 * If the file size is already greater than the current blocksize,
1502 	 * we will not grow.  If there is more than one block in a file,
1503 	 * the blocksize cannot change.
1504 	 */
1505 	if (zp->z_blksz && zp->z_size > zp->z_blksz)
1506 		return;
1507 
1508 	error = dmu_object_set_blocksize(ZTOZSB(zp)->z_os, zp->z_id,
1509 	    size, 0, tx);
1510 
1511 	if (error == ENOTSUP)
1512 		return;
1513 	ASSERT0(error);
1514 
1515 	/* What blocksize did we actually get? */
1516 	dmu_object_size_from_db(sa_get_db(zp->z_sa_hdl), &zp->z_blksz, &dummy);
1517 }
1518 
1519 /*
1520  * Increase the file length
1521  *
1522  *	IN:	zp	- znode of file to free data in.
1523  *		end	- new end-of-file
1524  *
1525  *	RETURN:	0 on success, error code on failure
1526  */
1527 static int
zfs_extend(znode_t * zp,uint64_t end)1528 zfs_extend(znode_t *zp, uint64_t end)
1529 {
1530 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
1531 	dmu_tx_t *tx;
1532 	zfs_locked_range_t *lr;
1533 	uint64_t newblksz;
1534 	int error;
1535 
1536 	/*
1537 	 * We will change zp_size, lock the whole file.
1538 	 */
1539 	lr = zfs_rangelock_enter(&zp->z_rangelock, 0, UINT64_MAX, RL_WRITER);
1540 
1541 	/*
1542 	 * Nothing to do if file already at desired length.
1543 	 */
1544 	if (end <= zp->z_size) {
1545 		zfs_rangelock_exit(lr);
1546 		return (0);
1547 	}
1548 	tx = dmu_tx_create(zfsvfs->z_os);
1549 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1550 	zfs_sa_upgrade_txholds(tx, zp);
1551 	if (end > zp->z_blksz &&
1552 	    (!ISP2(zp->z_blksz) || zp->z_blksz < zfsvfs->z_max_blksz)) {
1553 		/*
1554 		 * We are growing the file past the current block size.
1555 		 */
1556 		if (zp->z_blksz > ZTOZSB(zp)->z_max_blksz) {
1557 			/*
1558 			 * File's blocksize is already larger than the
1559 			 * "recordsize" property.  Only let it grow to
1560 			 * the next power of 2.
1561 			 */
1562 			ASSERT(!ISP2(zp->z_blksz));
1563 			newblksz = MIN(end, 1 << highbit64(zp->z_blksz));
1564 		} else {
1565 			newblksz = MIN(end, ZTOZSB(zp)->z_max_blksz);
1566 		}
1567 		dmu_tx_hold_write(tx, zp->z_id, 0, newblksz);
1568 	} else {
1569 		newblksz = 0;
1570 	}
1571 
1572 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1573 	if (error) {
1574 		dmu_tx_abort(tx);
1575 		zfs_rangelock_exit(lr);
1576 		return (error);
1577 	}
1578 
1579 	if (newblksz)
1580 		zfs_grow_blocksize(zp, newblksz, tx);
1581 
1582 	zp->z_size = end;
1583 
1584 	VERIFY0(sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(ZTOZSB(zp)),
1585 	    &zp->z_size, sizeof (zp->z_size), tx));
1586 
1587 	zfs_rangelock_exit(lr);
1588 
1589 	dmu_tx_commit(tx);
1590 
1591 	return (0);
1592 }
1593 
1594 /*
1595  * zfs_zero_partial_page - Modeled after update_pages() but
1596  * with different arguments and semantics for use by zfs_freesp().
1597  *
1598  * Zeroes a piece of a single page cache entry for zp at offset
1599  * start and length len.
1600  *
1601  * Caller must acquire a range lock on the file for the region
1602  * being zeroed in order that the ARC and page cache stay in sync.
1603  */
1604 static void
zfs_zero_partial_page(znode_t * zp,uint64_t start,uint64_t len)1605 zfs_zero_partial_page(znode_t *zp, uint64_t start, uint64_t len)
1606 {
1607 	struct address_space *mp = ZTOI(zp)->i_mapping;
1608 	struct page *pp;
1609 	int64_t	off;
1610 	void *pb;
1611 
1612 	ASSERT((start & PAGE_MASK) == ((start + len - 1) & PAGE_MASK));
1613 
1614 	off = start & (PAGE_SIZE - 1);
1615 	start &= PAGE_MASK;
1616 
1617 	pp = find_lock_page(mp, start >> PAGE_SHIFT);
1618 	if (pp) {
1619 		if (mapping_writably_mapped(mp))
1620 			flush_dcache_page(pp);
1621 
1622 		pb = kmap(pp);
1623 		memset(pb + off, 0, len);
1624 		kunmap(pp);
1625 
1626 		if (mapping_writably_mapped(mp))
1627 			flush_dcache_page(pp);
1628 
1629 		mark_page_accessed(pp);
1630 		SetPageUptodate(pp);
1631 		ClearPageError(pp);
1632 		unlock_page(pp);
1633 		put_page(pp);
1634 	}
1635 }
1636 
1637 /*
1638  * Free space in a file.
1639  *
1640  *	IN:	zp	- znode of file to free data in.
1641  *		off	- start of section to free.
1642  *		len	- length of section to free.
1643  *
1644  *	RETURN:	0 on success, error code on failure
1645  */
1646 static int
zfs_free_range(znode_t * zp,uint64_t off,uint64_t len)1647 zfs_free_range(znode_t *zp, uint64_t off, uint64_t len)
1648 {
1649 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
1650 	zfs_locked_range_t *lr;
1651 	int error;
1652 
1653 	/*
1654 	 * Lock the range being freed.
1655 	 */
1656 	lr = zfs_rangelock_enter(&zp->z_rangelock, off, len, RL_WRITER);
1657 
1658 	/*
1659 	 * Nothing to do if file already at desired length.
1660 	 */
1661 	if (off >= zp->z_size) {
1662 		zfs_rangelock_exit(lr);
1663 		return (0);
1664 	}
1665 
1666 	if (off + len > zp->z_size)
1667 		len = zp->z_size - off;
1668 
1669 	error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, off, len);
1670 
1671 	/*
1672 	 * Zero partial page cache entries.  This must be done under a
1673 	 * range lock in order to keep the ARC and page cache in sync.
1674 	 */
1675 	if (zn_has_cached_data(zp, off, off + len - 1)) {
1676 		loff_t first_page, last_page, page_len;
1677 		loff_t first_page_offset, last_page_offset;
1678 
1679 		/* first possible full page in hole */
1680 		first_page = (off + PAGE_SIZE - 1) >> PAGE_SHIFT;
1681 		/* last page of hole */
1682 		last_page = (off + len) >> PAGE_SHIFT;
1683 
1684 		/* offset of first_page */
1685 		first_page_offset = first_page << PAGE_SHIFT;
1686 		/* offset of last_page */
1687 		last_page_offset = last_page << PAGE_SHIFT;
1688 
1689 		/* truncate whole pages */
1690 		if (last_page_offset > first_page_offset) {
1691 			truncate_inode_pages_range(ZTOI(zp)->i_mapping,
1692 			    first_page_offset, last_page_offset - 1);
1693 		}
1694 
1695 		/* truncate sub-page ranges */
1696 		if (first_page > last_page) {
1697 			/* entire punched area within a single page */
1698 			zfs_zero_partial_page(zp, off, len);
1699 		} else {
1700 			/* beginning of punched area at the end of a page */
1701 			page_len  = first_page_offset - off;
1702 			if (page_len > 0)
1703 				zfs_zero_partial_page(zp, off, page_len);
1704 
1705 			/* end of punched area at the beginning of a page */
1706 			page_len = off + len - last_page_offset;
1707 			if (page_len > 0)
1708 				zfs_zero_partial_page(zp, last_page_offset,
1709 				    page_len);
1710 		}
1711 	}
1712 	zfs_rangelock_exit(lr);
1713 
1714 	return (error);
1715 }
1716 
1717 /*
1718  * Truncate a file
1719  *
1720  *	IN:	zp	- znode of file to free data in.
1721  *		end	- new end-of-file.
1722  *
1723  *	RETURN:	0 on success, error code on failure
1724  */
1725 static int
zfs_trunc(znode_t * zp,uint64_t end)1726 zfs_trunc(znode_t *zp, uint64_t end)
1727 {
1728 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
1729 	dmu_tx_t *tx;
1730 	zfs_locked_range_t *lr;
1731 	int error;
1732 	sa_bulk_attr_t bulk[2];
1733 	int count = 0;
1734 
1735 	/*
1736 	 * We will change zp_size, lock the whole file.
1737 	 */
1738 	lr = zfs_rangelock_enter(&zp->z_rangelock, 0, UINT64_MAX, RL_WRITER);
1739 
1740 	/*
1741 	 * Nothing to do if file already at desired length.
1742 	 */
1743 	if (end >= zp->z_size) {
1744 		zfs_rangelock_exit(lr);
1745 		return (0);
1746 	}
1747 
1748 	error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, end,
1749 	    DMU_OBJECT_END);
1750 	if (error) {
1751 		zfs_rangelock_exit(lr);
1752 		return (error);
1753 	}
1754 	tx = dmu_tx_create(zfsvfs->z_os);
1755 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1756 	zfs_sa_upgrade_txholds(tx, zp);
1757 	dmu_tx_mark_netfree(tx);
1758 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1759 	if (error) {
1760 		dmu_tx_abort(tx);
1761 		zfs_rangelock_exit(lr);
1762 		return (error);
1763 	}
1764 
1765 	zp->z_size = end;
1766 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs),
1767 	    NULL, &zp->z_size, sizeof (zp->z_size));
1768 
1769 	if (end == 0) {
1770 		zp->z_pflags &= ~ZFS_SPARSE;
1771 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
1772 		    NULL, &zp->z_pflags, 8);
1773 	}
1774 	VERIFY0(sa_bulk_update(zp->z_sa_hdl, bulk, count, tx));
1775 
1776 	dmu_tx_commit(tx);
1777 	zfs_rangelock_exit(lr);
1778 
1779 	return (0);
1780 }
1781 
1782 /*
1783  * Free space in a file
1784  *
1785  *	IN:	zp	- znode of file to free data in.
1786  *		off	- start of range
1787  *		len	- end of range (0 => EOF)
1788  *		flag	- current file open mode flags.
1789  *		log	- TRUE if this action should be logged
1790  *
1791  *	RETURN:	0 on success, error code on failure
1792  */
1793 int
zfs_freesp(znode_t * zp,uint64_t off,uint64_t len,int flag,boolean_t log)1794 zfs_freesp(znode_t *zp, uint64_t off, uint64_t len, int flag, boolean_t log)
1795 {
1796 	dmu_tx_t *tx;
1797 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
1798 	zilog_t *zilog = zfsvfs->z_log;
1799 	uint64_t mode;
1800 	uint64_t mtime[2], ctime[2];
1801 	sa_bulk_attr_t bulk[4];
1802 	int count = 0;
1803 	int error;
1804 
1805 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs), &mode,
1806 	    sizeof (mode))) != 0)
1807 		return (error);
1808 
1809 	if (off > zp->z_size) {
1810 		error =  zfs_extend(zp, off+len);
1811 		if (error == 0 && log)
1812 			goto log;
1813 		goto out;
1814 	}
1815 
1816 	if (len == 0) {
1817 		error = zfs_trunc(zp, off);
1818 	} else {
1819 		if ((error = zfs_free_range(zp, off, len)) == 0 &&
1820 		    off + len > zp->z_size)
1821 			error = zfs_extend(zp, off+len);
1822 	}
1823 	if (error || !log)
1824 		goto out;
1825 log:
1826 	tx = dmu_tx_create(zfsvfs->z_os);
1827 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, ZFS_SEQ_MAY_GROW(zp));
1828 	zfs_sa_upgrade_txholds(tx, zp);
1829 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1830 	if (error) {
1831 		dmu_tx_abort(tx);
1832 		goto out;
1833 	}
1834 
1835 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, mtime, 16);
1836 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, ctime, 16);
1837 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
1838 	    NULL, &zp->z_pflags, 8);
1839 	zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
1840 	ZFS_PERSIST_SEQ(zp, bulk, count);
1841 	ASSERT3S(count, <=, ARRAY_SIZE(bulk));
1842 	error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1843 	ASSERT0(error);
1844 
1845 	zfs_log_truncate(zilog, tx, TX_TRUNCATE, zp, off, len);
1846 
1847 	dmu_tx_commit(tx);
1848 
1849 	zfs_znode_update_vfs(zp);
1850 	error = 0;
1851 
1852 out:
1853 	/*
1854 	 * Truncate the page cache - for file truncate operations, use
1855 	 * the purpose-built API for truncations.  For punching operations,
1856 	 * the truncation is handled under a range lock in zfs_free_range.
1857 	 */
1858 	if (len == 0)
1859 		truncate_setsize(ZTOI(zp), off);
1860 	return (error);
1861 }
1862 
1863 void
zfs_create_fs(objset_t * os,cred_t * cr,nvlist_t * zplprops,dmu_tx_t * tx)1864 zfs_create_fs(objset_t *os, cred_t *cr, nvlist_t *zplprops, dmu_tx_t *tx)
1865 {
1866 	struct super_block *sb;
1867 	zfsvfs_t	*zfsvfs;
1868 	uint64_t	moid, obj, sa_obj, version;
1869 	uint64_t	sense = ZFS_CASE_SENSITIVE;
1870 	uint64_t	norm = 0;
1871 	nvpair_t	*elem;
1872 	int		size;
1873 	int		error;
1874 	int		i;
1875 	znode_t		*rootzp = NULL;
1876 	vattr_t		vattr;
1877 	znode_t		*zp;
1878 	zfs_acl_ids_t	acl_ids;
1879 
1880 	/*
1881 	 * First attempt to create master node.
1882 	 */
1883 	/*
1884 	 * In an empty objset, there are no blocks to read and thus
1885 	 * there can be no i/o errors (which we assert below).
1886 	 */
1887 	moid = MASTER_NODE_OBJ;
1888 	error = zap_create_claim(os, moid, DMU_OT_MASTER_NODE,
1889 	    DMU_OT_NONE, 0, tx);
1890 	ASSERT0(error);
1891 
1892 	/*
1893 	 * Set starting attributes.
1894 	 */
1895 	version = zfs_zpl_version_map(spa_version(dmu_objset_spa(os)));
1896 	elem = NULL;
1897 	while ((elem = nvlist_next_nvpair(zplprops, elem)) != NULL) {
1898 		/* For the moment we expect all zpl props to be uint64_ts */
1899 		uint64_t val;
1900 		const char *name;
1901 
1902 		ASSERT(nvpair_type(elem) == DATA_TYPE_UINT64);
1903 		VERIFY0(nvpair_value_uint64(elem, &val));
1904 		name = nvpair_name(elem);
1905 		if (strcmp(name, zfs_prop_to_name(ZFS_PROP_VERSION)) == 0) {
1906 			if (val < version)
1907 				version = val;
1908 		} else {
1909 			error = zap_update(os, moid, name, 8, 1, &val, tx);
1910 		}
1911 		ASSERT0(error);
1912 		if (strcmp(name, zfs_prop_to_name(ZFS_PROP_NORMALIZE)) == 0)
1913 			norm = val;
1914 		else if (strcmp(name, zfs_prop_to_name(ZFS_PROP_CASE)) == 0)
1915 			sense = val;
1916 	}
1917 	ASSERT(version != 0);
1918 	error = zap_update(os, moid, ZPL_VERSION_STR, 8, 1, &version, tx);
1919 	ASSERT0(error);
1920 
1921 	/*
1922 	 * Create zap object used for SA attribute registration
1923 	 */
1924 
1925 	if (version >= ZPL_VERSION_SA) {
1926 		sa_obj = zap_create(os, DMU_OT_SA_MASTER_NODE,
1927 		    DMU_OT_NONE, 0, tx);
1928 		error = zap_add(os, moid, ZFS_SA_ATTRS, 8, 1, &sa_obj, tx);
1929 		ASSERT0(error);
1930 	} else {
1931 		sa_obj = 0;
1932 	}
1933 	/*
1934 	 * Create a delete queue.
1935 	 */
1936 	obj = zap_create(os, DMU_OT_UNLINKED_SET, DMU_OT_NONE, 0, tx);
1937 
1938 	error = zap_add(os, moid, ZFS_UNLINKED_SET, 8, 1, &obj, tx);
1939 	ASSERT0(error);
1940 
1941 	/*
1942 	 * Create root znode.  Create minimal znode/inode/zfsvfs/sb
1943 	 * to allow zfs_mknode to work.
1944 	 */
1945 	vattr.va_mask = ATTR_MODE|ATTR_UID|ATTR_GID;
1946 	vattr.va_mode = S_IFDIR|0755;
1947 	vattr.va_uid = crgetuid(cr);
1948 	vattr.va_gid = crgetgid(cr);
1949 
1950 	rootzp = kmem_cache_alloc(znode_cache, KM_SLEEP);
1951 	rootzp->z_unlinked = B_FALSE;
1952 	rootzp->z_atime_dirty = B_FALSE;
1953 	rootzp->z_xattr_dir_absent = B_FALSE;
1954 	rootzp->z_is_sa = USE_SA(version, os);
1955 	rootzp->z_pflags = 0;
1956 
1957 	zfsvfs = kmem_zalloc(sizeof (zfsvfs_t), KM_SLEEP);
1958 	zfsvfs->z_os = os;
1959 	zfsvfs->z_parent = zfsvfs;
1960 	zfsvfs->z_version = version;
1961 	zfsvfs->z_use_fuids = USE_FUIDS(version, os);
1962 	zfsvfs->z_use_sa = USE_SA(version, os);
1963 	zfsvfs->z_norm = norm;
1964 
1965 	sb = kmem_zalloc(sizeof (struct super_block), KM_SLEEP);
1966 	sb->s_fs_info = zfsvfs;
1967 
1968 	ZTOI(rootzp)->i_sb = sb;
1969 
1970 	error = sa_setup(os, sa_obj, zfs_attr_table, ZPL_END,
1971 	    &zfsvfs->z_attr_table);
1972 
1973 	ASSERT0(error);
1974 
1975 	/*
1976 	 * Fold case on file systems that are always or sometimes case
1977 	 * insensitive.
1978 	 */
1979 	if (sense == ZFS_CASE_INSENSITIVE || sense == ZFS_CASE_MIXED)
1980 		zfsvfs->z_norm |= U8_TEXTPREP_TOUPPER;
1981 
1982 	mutex_init(&zfsvfs->z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
1983 	list_create(&zfsvfs->z_all_znodes, sizeof (znode_t),
1984 	    offsetof(znode_t, z_link_node));
1985 
1986 	size = MIN(1 << (highbit64(zfs_object_mutex_size)-1), ZFS_OBJ_MTX_MAX);
1987 	zfsvfs->z_hold_size = size;
1988 	zfsvfs->z_hold_trees = vmem_zalloc(sizeof (avl_tree_t) * size,
1989 	    KM_SLEEP);
1990 	zfsvfs->z_hold_locks = vmem_zalloc(sizeof (kmutex_t) * size, KM_SLEEP);
1991 	for (i = 0; i != size; i++) {
1992 		avl_create(&zfsvfs->z_hold_trees[i], zfs_znode_hold_compare,
1993 		    sizeof (znode_hold_t), offsetof(znode_hold_t, zh_node));
1994 		mutex_init(&zfsvfs->z_hold_locks[i], NULL, MUTEX_DEFAULT, NULL);
1995 	}
1996 
1997 	VERIFY0(zfs_acl_ids_create(rootzp, IS_ROOT_NODE, &vattr,
1998 	    cr, NULL, &acl_ids, zfs_init_idmap));
1999 	zfs_mknode(rootzp, &vattr, tx, cr, IS_ROOT_NODE, &zp, &acl_ids);
2000 	ASSERT3P(zp, ==, rootzp);
2001 	error = zap_add(os, moid, ZFS_ROOT_OBJ, 8, 1, &rootzp->z_id, tx);
2002 	ASSERT0(error);
2003 	zfs_acl_ids_free(&acl_ids);
2004 
2005 	atomic_set(&ZTOI(rootzp)->i_count, 0);
2006 	sa_handle_destroy(rootzp->z_sa_hdl);
2007 	kmem_cache_free(znode_cache, rootzp);
2008 
2009 	for (i = 0; i != size; i++) {
2010 		avl_destroy(&zfsvfs->z_hold_trees[i]);
2011 		mutex_destroy(&zfsvfs->z_hold_locks[i]);
2012 	}
2013 
2014 	mutex_destroy(&zfsvfs->z_znodes_lock);
2015 
2016 	vmem_free(zfsvfs->z_hold_trees, sizeof (avl_tree_t) * size);
2017 	vmem_free(zfsvfs->z_hold_locks, sizeof (kmutex_t) * size);
2018 	kmem_free(sb, sizeof (struct super_block));
2019 	kmem_free(zfsvfs, sizeof (zfsvfs_t));
2020 }
2021 
2022 EXPORT_SYMBOL(zfs_create_fs);
2023 EXPORT_SYMBOL(zfs_obj_to_path);
2024 
2025 module_param(zfs_object_mutex_size, uint, 0644);
2026 MODULE_PARM_DESC(zfs_object_mutex_size, "Size of znode hold array");
2027 module_param(zfs_unlink_suspend_progress, int, 0644);
2028 MODULE_PARM_DESC(zfs_unlink_suspend_progress, "Set to prevent async unlinks "
2029 "(debug - leaks space into the unlinked set)");
2030