xref: /openbmc/linux/fs/smb/server/vfs.c (revision 3db55767)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4  *   Copyright (C) 2018 Samsung Electronics Co., Ltd.
5  */
6 
7 #include <linux/kernel.h>
8 #include <linux/fs.h>
9 #include <linux/filelock.h>
10 #include <linux/uaccess.h>
11 #include <linux/backing-dev.h>
12 #include <linux/writeback.h>
13 #include <linux/xattr.h>
14 #include <linux/falloc.h>
15 #include <linux/fsnotify.h>
16 #include <linux/dcache.h>
17 #include <linux/slab.h>
18 #include <linux/vmalloc.h>
19 #include <linux/sched/xacct.h>
20 #include <linux/crc32c.h>
21 #include <linux/namei.h>
22 
23 #include "glob.h"
24 #include "oplock.h"
25 #include "connection.h"
26 #include "vfs.h"
27 #include "vfs_cache.h"
28 #include "smbacl.h"
29 #include "ndr.h"
30 #include "auth.h"
31 #include "misc.h"
32 
33 #include "smb_common.h"
34 #include "mgmt/share_config.h"
35 #include "mgmt/tree_connect.h"
36 #include "mgmt/user_session.h"
37 #include "mgmt/user_config.h"
38 
39 static void ksmbd_vfs_inherit_owner(struct ksmbd_work *work,
40 				    struct inode *parent_inode,
41 				    struct inode *inode)
42 {
43 	if (!test_share_config_flag(work->tcon->share_conf,
44 				    KSMBD_SHARE_FLAG_INHERIT_OWNER))
45 		return;
46 
47 	i_uid_write(inode, i_uid_read(parent_inode));
48 }
49 
50 /**
51  * ksmbd_vfs_lock_parent() - lock parent dentry if it is stable
52  */
53 int ksmbd_vfs_lock_parent(struct dentry *parent, struct dentry *child)
54 {
55 	inode_lock_nested(d_inode(parent), I_MUTEX_PARENT);
56 	if (child->d_parent != parent) {
57 		inode_unlock(d_inode(parent));
58 		return -ENOENT;
59 	}
60 
61 	return 0;
62 }
63 
64 static int ksmbd_vfs_path_lookup_locked(struct ksmbd_share_config *share_conf,
65 					char *pathname, unsigned int flags,
66 					struct path *path)
67 {
68 	struct qstr last;
69 	struct filename *filename;
70 	struct path *root_share_path = &share_conf->vfs_path;
71 	int err, type;
72 	struct path parent_path;
73 	struct dentry *d;
74 
75 	if (pathname[0] == '\0') {
76 		pathname = share_conf->path;
77 		root_share_path = NULL;
78 	} else {
79 		flags |= LOOKUP_BENEATH;
80 	}
81 
82 	filename = getname_kernel(pathname);
83 	if (IS_ERR(filename))
84 		return PTR_ERR(filename);
85 
86 	err = vfs_path_parent_lookup(filename, flags,
87 				     &parent_path, &last, &type,
88 				     root_share_path);
89 	putname(filename);
90 	if (err)
91 		return err;
92 
93 	if (unlikely(type != LAST_NORM)) {
94 		path_put(&parent_path);
95 		return -ENOENT;
96 	}
97 
98 	inode_lock_nested(parent_path.dentry->d_inode, I_MUTEX_PARENT);
99 	d = lookup_one_qstr_excl(&last, parent_path.dentry, 0);
100 	if (IS_ERR(d))
101 		goto err_out;
102 
103 	if (d_is_negative(d)) {
104 		dput(d);
105 		goto err_out;
106 	}
107 
108 	path->dentry = d;
109 	path->mnt = share_conf->vfs_path.mnt;
110 	path_put(&parent_path);
111 
112 	return 0;
113 
114 err_out:
115 	inode_unlock(parent_path.dentry->d_inode);
116 	path_put(&parent_path);
117 	return -ENOENT;
118 }
119 
120 int ksmbd_vfs_query_maximal_access(struct mnt_idmap *idmap,
121 				   struct dentry *dentry, __le32 *daccess)
122 {
123 	int ret = 0;
124 
125 	*daccess = cpu_to_le32(FILE_READ_ATTRIBUTES | READ_CONTROL);
126 
127 	if (!inode_permission(idmap, d_inode(dentry), MAY_OPEN | MAY_WRITE))
128 		*daccess |= cpu_to_le32(WRITE_DAC | WRITE_OWNER | SYNCHRONIZE |
129 				FILE_WRITE_DATA | FILE_APPEND_DATA |
130 				FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES |
131 				FILE_DELETE_CHILD);
132 
133 	if (!inode_permission(idmap, d_inode(dentry), MAY_OPEN | MAY_READ))
134 		*daccess |= FILE_READ_DATA_LE | FILE_READ_EA_LE;
135 
136 	if (!inode_permission(idmap, d_inode(dentry), MAY_OPEN | MAY_EXEC))
137 		*daccess |= FILE_EXECUTE_LE;
138 
139 	if (!inode_permission(idmap, d_inode(dentry->d_parent), MAY_EXEC | MAY_WRITE))
140 		*daccess |= FILE_DELETE_LE;
141 
142 	return ret;
143 }
144 
145 /**
146  * ksmbd_vfs_create() - vfs helper for smb create file
147  * @work:	work
148  * @name:	file name that is relative to share
149  * @mode:	file create mode
150  *
151  * Return:	0 on success, otherwise error
152  */
153 int ksmbd_vfs_create(struct ksmbd_work *work, const char *name, umode_t mode)
154 {
155 	struct path path;
156 	struct dentry *dentry;
157 	int err;
158 
159 	dentry = ksmbd_vfs_kern_path_create(work, name,
160 					    LOOKUP_NO_SYMLINKS, &path);
161 	if (IS_ERR(dentry)) {
162 		err = PTR_ERR(dentry);
163 		if (err != -ENOENT)
164 			pr_err("path create failed for %s, err %d\n",
165 			       name, err);
166 		return err;
167 	}
168 
169 	mode |= S_IFREG;
170 	err = vfs_create(mnt_idmap(path.mnt), d_inode(path.dentry),
171 			 dentry, mode, true);
172 	if (!err) {
173 		ksmbd_vfs_inherit_owner(work, d_inode(path.dentry),
174 					d_inode(dentry));
175 	} else {
176 		pr_err("File(%s): creation failed (err:%d)\n", name, err);
177 	}
178 	done_path_create(&path, dentry);
179 	return err;
180 }
181 
182 /**
183  * ksmbd_vfs_mkdir() - vfs helper for smb create directory
184  * @work:	work
185  * @name:	directory name that is relative to share
186  * @mode:	directory create mode
187  *
188  * Return:	0 on success, otherwise error
189  */
190 int ksmbd_vfs_mkdir(struct ksmbd_work *work, const char *name, umode_t mode)
191 {
192 	struct mnt_idmap *idmap;
193 	struct path path;
194 	struct dentry *dentry;
195 	int err;
196 
197 	dentry = ksmbd_vfs_kern_path_create(work, name,
198 					    LOOKUP_NO_SYMLINKS | LOOKUP_DIRECTORY,
199 					    &path);
200 	if (IS_ERR(dentry)) {
201 		err = PTR_ERR(dentry);
202 		if (err != -EEXIST)
203 			ksmbd_debug(VFS, "path create failed for %s, err %d\n",
204 				    name, err);
205 		return err;
206 	}
207 
208 	idmap = mnt_idmap(path.mnt);
209 	mode |= S_IFDIR;
210 	err = vfs_mkdir(idmap, d_inode(path.dentry), dentry, mode);
211 	if (err) {
212 		goto out;
213 	} else if (d_unhashed(dentry)) {
214 		struct dentry *d;
215 
216 		d = lookup_one(idmap, dentry->d_name.name, dentry->d_parent,
217 			       dentry->d_name.len);
218 		if (IS_ERR(d)) {
219 			err = PTR_ERR(d);
220 			goto out;
221 		}
222 		if (unlikely(d_is_negative(d))) {
223 			dput(d);
224 			err = -ENOENT;
225 			goto out;
226 		}
227 
228 		ksmbd_vfs_inherit_owner(work, d_inode(path.dentry), d_inode(d));
229 		dput(d);
230 	}
231 out:
232 	done_path_create(&path, dentry);
233 	if (err)
234 		pr_err("mkdir(%s): creation failed (err:%d)\n", name, err);
235 	return err;
236 }
237 
238 static ssize_t ksmbd_vfs_getcasexattr(struct mnt_idmap *idmap,
239 				      struct dentry *dentry, char *attr_name,
240 				      int attr_name_len, char **attr_value)
241 {
242 	char *name, *xattr_list = NULL;
243 	ssize_t value_len = -ENOENT, xattr_list_len;
244 
245 	xattr_list_len = ksmbd_vfs_listxattr(dentry, &xattr_list);
246 	if (xattr_list_len <= 0)
247 		goto out;
248 
249 	for (name = xattr_list; name - xattr_list < xattr_list_len;
250 			name += strlen(name) + 1) {
251 		ksmbd_debug(VFS, "%s, len %zd\n", name, strlen(name));
252 		if (strncasecmp(attr_name, name, attr_name_len))
253 			continue;
254 
255 		value_len = ksmbd_vfs_getxattr(idmap,
256 					       dentry,
257 					       name,
258 					       attr_value);
259 		if (value_len < 0)
260 			pr_err("failed to get xattr in file\n");
261 		break;
262 	}
263 
264 out:
265 	kvfree(xattr_list);
266 	return value_len;
267 }
268 
269 static int ksmbd_vfs_stream_read(struct ksmbd_file *fp, char *buf, loff_t *pos,
270 				 size_t count)
271 {
272 	ssize_t v_len;
273 	char *stream_buf = NULL;
274 
275 	ksmbd_debug(VFS, "read stream data pos : %llu, count : %zd\n",
276 		    *pos, count);
277 
278 	v_len = ksmbd_vfs_getcasexattr(file_mnt_idmap(fp->filp),
279 				       fp->filp->f_path.dentry,
280 				       fp->stream.name,
281 				       fp->stream.size,
282 				       &stream_buf);
283 	if ((int)v_len <= 0)
284 		return (int)v_len;
285 
286 	if (v_len <= *pos) {
287 		count = -EINVAL;
288 		goto free_buf;
289 	}
290 
291 	if (v_len - *pos < count)
292 		count = v_len - *pos;
293 
294 	memcpy(buf, &stream_buf[*pos], count);
295 
296 free_buf:
297 	kvfree(stream_buf);
298 	return count;
299 }
300 
301 /**
302  * check_lock_range() - vfs helper for smb byte range file locking
303  * @filp:	the file to apply the lock to
304  * @start:	lock start byte offset
305  * @end:	lock end byte offset
306  * @type:	byte range type read/write
307  *
308  * Return:	0 on success, otherwise error
309  */
310 static int check_lock_range(struct file *filp, loff_t start, loff_t end,
311 			    unsigned char type)
312 {
313 	struct file_lock *flock;
314 	struct file_lock_context *ctx = locks_inode_context(file_inode(filp));
315 	int error = 0;
316 
317 	if (!ctx || list_empty_careful(&ctx->flc_posix))
318 		return 0;
319 
320 	spin_lock(&ctx->flc_lock);
321 	list_for_each_entry(flock, &ctx->flc_posix, fl_list) {
322 		/* check conflict locks */
323 		if (flock->fl_end >= start && end >= flock->fl_start) {
324 			if (flock->fl_type == F_RDLCK) {
325 				if (type == WRITE) {
326 					pr_err("not allow write by shared lock\n");
327 					error = 1;
328 					goto out;
329 				}
330 			} else if (flock->fl_type == F_WRLCK) {
331 				/* check owner in lock */
332 				if (flock->fl_file != filp) {
333 					error = 1;
334 					pr_err("not allow rw access by exclusive lock from other opens\n");
335 					goto out;
336 				}
337 			}
338 		}
339 	}
340 out:
341 	spin_unlock(&ctx->flc_lock);
342 	return error;
343 }
344 
345 /**
346  * ksmbd_vfs_read() - vfs helper for smb file read
347  * @work:	smb work
348  * @fid:	file id of open file
349  * @count:	read byte count
350  * @pos:	file pos
351  *
352  * Return:	number of read bytes on success, otherwise error
353  */
354 int ksmbd_vfs_read(struct ksmbd_work *work, struct ksmbd_file *fp, size_t count,
355 		   loff_t *pos)
356 {
357 	struct file *filp = fp->filp;
358 	ssize_t nbytes = 0;
359 	char *rbuf = work->aux_payload_buf;
360 	struct inode *inode = file_inode(filp);
361 
362 	if (S_ISDIR(inode->i_mode))
363 		return -EISDIR;
364 
365 	if (unlikely(count == 0))
366 		return 0;
367 
368 	if (work->conn->connection_type) {
369 		if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_EXECUTE_LE))) {
370 			pr_err("no right to read(%pD)\n", fp->filp);
371 			return -EACCES;
372 		}
373 	}
374 
375 	if (ksmbd_stream_fd(fp))
376 		return ksmbd_vfs_stream_read(fp, rbuf, pos, count);
377 
378 	if (!work->tcon->posix_extensions) {
379 		int ret;
380 
381 		ret = check_lock_range(filp, *pos, *pos + count - 1, READ);
382 		if (ret) {
383 			pr_err("unable to read due to lock\n");
384 			return -EAGAIN;
385 		}
386 	}
387 
388 	nbytes = kernel_read(filp, rbuf, count, pos);
389 	if (nbytes < 0) {
390 		pr_err("smb read failed, err = %zd\n", nbytes);
391 		return nbytes;
392 	}
393 
394 	filp->f_pos = *pos;
395 	return nbytes;
396 }
397 
398 static int ksmbd_vfs_stream_write(struct ksmbd_file *fp, char *buf, loff_t *pos,
399 				  size_t count)
400 {
401 	char *stream_buf = NULL, *wbuf;
402 	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
403 	size_t size, v_len;
404 	int err = 0;
405 
406 	ksmbd_debug(VFS, "write stream data pos : %llu, count : %zd\n",
407 		    *pos, count);
408 
409 	size = *pos + count;
410 	if (size > XATTR_SIZE_MAX) {
411 		size = XATTR_SIZE_MAX;
412 		count = (*pos + count) - XATTR_SIZE_MAX;
413 	}
414 
415 	v_len = ksmbd_vfs_getcasexattr(idmap,
416 				       fp->filp->f_path.dentry,
417 				       fp->stream.name,
418 				       fp->stream.size,
419 				       &stream_buf);
420 	if ((int)v_len < 0) {
421 		pr_err("not found stream in xattr : %zd\n", v_len);
422 		err = (int)v_len;
423 		goto out;
424 	}
425 
426 	if (v_len < size) {
427 		wbuf = kvmalloc(size, GFP_KERNEL | __GFP_ZERO);
428 		if (!wbuf) {
429 			err = -ENOMEM;
430 			goto out;
431 		}
432 
433 		if (v_len > 0)
434 			memcpy(wbuf, stream_buf, v_len);
435 		kvfree(stream_buf);
436 		stream_buf = wbuf;
437 	}
438 
439 	memcpy(&stream_buf[*pos], buf, count);
440 
441 	err = ksmbd_vfs_setxattr(idmap,
442 				 fp->filp->f_path.dentry,
443 				 fp->stream.name,
444 				 (void *)stream_buf,
445 				 size,
446 				 0);
447 	if (err < 0)
448 		goto out;
449 
450 	fp->filp->f_pos = *pos;
451 	err = 0;
452 out:
453 	kvfree(stream_buf);
454 	return err;
455 }
456 
457 /**
458  * ksmbd_vfs_write() - vfs helper for smb file write
459  * @work:	work
460  * @fid:	file id of open file
461  * @buf:	buf containing data for writing
462  * @count:	read byte count
463  * @pos:	file pos
464  * @sync:	fsync after write
465  * @written:	number of bytes written
466  *
467  * Return:	0 on success, otherwise error
468  */
469 int ksmbd_vfs_write(struct ksmbd_work *work, struct ksmbd_file *fp,
470 		    char *buf, size_t count, loff_t *pos, bool sync,
471 		    ssize_t *written)
472 {
473 	struct file *filp;
474 	loff_t	offset = *pos;
475 	int err = 0;
476 
477 	if (work->conn->connection_type) {
478 		if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
479 			pr_err("no right to write(%pD)\n", fp->filp);
480 			err = -EACCES;
481 			goto out;
482 		}
483 	}
484 
485 	filp = fp->filp;
486 
487 	if (ksmbd_stream_fd(fp)) {
488 		err = ksmbd_vfs_stream_write(fp, buf, pos, count);
489 		if (!err)
490 			*written = count;
491 		goto out;
492 	}
493 
494 	if (!work->tcon->posix_extensions) {
495 		err = check_lock_range(filp, *pos, *pos + count - 1, WRITE);
496 		if (err) {
497 			pr_err("unable to write due to lock\n");
498 			err = -EAGAIN;
499 			goto out;
500 		}
501 	}
502 
503 	/* Do we need to break any of a levelII oplock? */
504 	smb_break_all_levII_oplock(work, fp, 1);
505 
506 	err = kernel_write(filp, buf, count, pos);
507 	if (err < 0) {
508 		ksmbd_debug(VFS, "smb write failed, err = %d\n", err);
509 		goto out;
510 	}
511 
512 	filp->f_pos = *pos;
513 	*written = err;
514 	err = 0;
515 	if (sync) {
516 		err = vfs_fsync_range(filp, offset, offset + *written, 0);
517 		if (err < 0)
518 			pr_err("fsync failed for filename = %pD, err = %d\n",
519 			       fp->filp, err);
520 	}
521 
522 out:
523 	return err;
524 }
525 
526 /**
527  * ksmbd_vfs_getattr() - vfs helper for smb getattr
528  * @work:	work
529  * @fid:	file id of open file
530  * @attrs:	inode attributes
531  *
532  * Return:	0 on success, otherwise error
533  */
534 int ksmbd_vfs_getattr(const struct path *path, struct kstat *stat)
535 {
536 	int err;
537 
538 	err = vfs_getattr(path, stat, STATX_BTIME, AT_STATX_SYNC_AS_STAT);
539 	if (err)
540 		pr_err("getattr failed, err %d\n", err);
541 	return err;
542 }
543 
544 /**
545  * ksmbd_vfs_fsync() - vfs helper for smb fsync
546  * @work:	work
547  * @fid:	file id of open file
548  *
549  * Return:	0 on success, otherwise error
550  */
551 int ksmbd_vfs_fsync(struct ksmbd_work *work, u64 fid, u64 p_id)
552 {
553 	struct ksmbd_file *fp;
554 	int err;
555 
556 	fp = ksmbd_lookup_fd_slow(work, fid, p_id);
557 	if (!fp) {
558 		pr_err("failed to get filp for fid %llu\n", fid);
559 		return -ENOENT;
560 	}
561 	err = vfs_fsync(fp->filp, 0);
562 	if (err < 0)
563 		pr_err("smb fsync failed, err = %d\n", err);
564 	ksmbd_fd_put(work, fp);
565 	return err;
566 }
567 
568 /**
569  * ksmbd_vfs_remove_file() - vfs helper for smb rmdir or unlink
570  * @name:	directory or file name that is relative to share
571  *
572  * Return:	0 on success, otherwise error
573  */
574 int ksmbd_vfs_remove_file(struct ksmbd_work *work, const struct path *path)
575 {
576 	struct mnt_idmap *idmap;
577 	struct dentry *parent = path->dentry->d_parent;
578 	int err;
579 
580 	if (ksmbd_override_fsids(work))
581 		return -ENOMEM;
582 
583 	if (!d_inode(path->dentry)->i_nlink) {
584 		err = -ENOENT;
585 		goto out_err;
586 	}
587 
588 	idmap = mnt_idmap(path->mnt);
589 	if (S_ISDIR(d_inode(path->dentry)->i_mode)) {
590 		err = vfs_rmdir(idmap, d_inode(parent), path->dentry);
591 		if (err && err != -ENOTEMPTY)
592 			ksmbd_debug(VFS, "rmdir failed, err %d\n", err);
593 	} else {
594 		err = vfs_unlink(idmap, d_inode(parent), path->dentry, NULL);
595 		if (err)
596 			ksmbd_debug(VFS, "unlink failed, err %d\n", err);
597 	}
598 
599 out_err:
600 	ksmbd_revert_fsids(work);
601 	return err;
602 }
603 
604 /**
605  * ksmbd_vfs_link() - vfs helper for creating smb hardlink
606  * @oldname:	source file name
607  * @newname:	hardlink name that is relative to share
608  *
609  * Return:	0 on success, otherwise error
610  */
611 int ksmbd_vfs_link(struct ksmbd_work *work, const char *oldname,
612 		   const char *newname)
613 {
614 	struct path oldpath, newpath;
615 	struct dentry *dentry;
616 	int err;
617 
618 	if (ksmbd_override_fsids(work))
619 		return -ENOMEM;
620 
621 	err = kern_path(oldname, LOOKUP_NO_SYMLINKS, &oldpath);
622 	if (err) {
623 		pr_err("cannot get linux path for %s, err = %d\n",
624 		       oldname, err);
625 		goto out1;
626 	}
627 
628 	dentry = ksmbd_vfs_kern_path_create(work, newname,
629 					    LOOKUP_NO_SYMLINKS | LOOKUP_REVAL,
630 					    &newpath);
631 	if (IS_ERR(dentry)) {
632 		err = PTR_ERR(dentry);
633 		pr_err("path create err for %s, err %d\n", newname, err);
634 		goto out2;
635 	}
636 
637 	err = -EXDEV;
638 	if (oldpath.mnt != newpath.mnt) {
639 		pr_err("vfs_link failed err %d\n", err);
640 		goto out3;
641 	}
642 
643 	err = vfs_link(oldpath.dentry, mnt_idmap(newpath.mnt),
644 		       d_inode(newpath.dentry),
645 		       dentry, NULL);
646 	if (err)
647 		ksmbd_debug(VFS, "vfs_link failed err %d\n", err);
648 
649 out3:
650 	done_path_create(&newpath, dentry);
651 out2:
652 	path_put(&oldpath);
653 out1:
654 	ksmbd_revert_fsids(work);
655 	return err;
656 }
657 
658 int ksmbd_vfs_rename(struct ksmbd_work *work, const struct path *old_path,
659 		     char *newname, int flags)
660 {
661 	struct dentry *old_parent, *new_dentry, *trap;
662 	struct dentry *old_child = old_path->dentry;
663 	struct path new_path;
664 	struct qstr new_last;
665 	struct renamedata rd;
666 	struct filename *to;
667 	struct ksmbd_share_config *share_conf = work->tcon->share_conf;
668 	struct ksmbd_file *parent_fp;
669 	int new_type;
670 	int err, lookup_flags = LOOKUP_NO_SYMLINKS;
671 
672 	if (ksmbd_override_fsids(work))
673 		return -ENOMEM;
674 
675 	to = getname_kernel(newname);
676 	if (IS_ERR(to)) {
677 		err = PTR_ERR(to);
678 		goto revert_fsids;
679 	}
680 
681 retry:
682 	err = vfs_path_parent_lookup(to, lookup_flags | LOOKUP_BENEATH,
683 				     &new_path, &new_last, &new_type,
684 				     &share_conf->vfs_path);
685 	if (err)
686 		goto out1;
687 
688 	if (old_path->mnt != new_path.mnt) {
689 		err = -EXDEV;
690 		goto out2;
691 	}
692 
693 	trap = lock_rename_child(old_child, new_path.dentry);
694 
695 	old_parent = dget(old_child->d_parent);
696 	if (d_unhashed(old_child)) {
697 		err = -EINVAL;
698 		goto out3;
699 	}
700 
701 	parent_fp = ksmbd_lookup_fd_inode(d_inode(old_child->d_parent));
702 	if (parent_fp) {
703 		if (parent_fp->daccess & FILE_DELETE_LE) {
704 			pr_err("parent dir is opened with delete access\n");
705 			err = -ESHARE;
706 			ksmbd_fd_put(work, parent_fp);
707 			goto out3;
708 		}
709 		ksmbd_fd_put(work, parent_fp);
710 	}
711 
712 	new_dentry = lookup_one_qstr_excl(&new_last, new_path.dentry,
713 					  lookup_flags | LOOKUP_RENAME_TARGET);
714 	if (IS_ERR(new_dentry)) {
715 		err = PTR_ERR(new_dentry);
716 		goto out3;
717 	}
718 
719 	if (d_is_symlink(new_dentry)) {
720 		err = -EACCES;
721 		goto out4;
722 	}
723 
724 	if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry)) {
725 		err = -EEXIST;
726 		goto out4;
727 	}
728 
729 	if (old_child == trap) {
730 		err = -EINVAL;
731 		goto out4;
732 	}
733 
734 	if (new_dentry == trap) {
735 		err = -ENOTEMPTY;
736 		goto out4;
737 	}
738 
739 	rd.old_mnt_idmap	= mnt_idmap(old_path->mnt),
740 	rd.old_dir		= d_inode(old_parent),
741 	rd.old_dentry		= old_child,
742 	rd.new_mnt_idmap	= mnt_idmap(new_path.mnt),
743 	rd.new_dir		= new_path.dentry->d_inode,
744 	rd.new_dentry		= new_dentry,
745 	rd.flags		= flags,
746 	err = vfs_rename(&rd);
747 	if (err)
748 		ksmbd_debug(VFS, "vfs_rename failed err %d\n", err);
749 
750 out4:
751 	dput(new_dentry);
752 out3:
753 	dput(old_parent);
754 	unlock_rename(old_parent, new_path.dentry);
755 out2:
756 	path_put(&new_path);
757 
758 	if (retry_estale(err, lookup_flags)) {
759 		lookup_flags |= LOOKUP_REVAL;
760 		goto retry;
761 	}
762 out1:
763 	putname(to);
764 revert_fsids:
765 	ksmbd_revert_fsids(work);
766 	return err;
767 }
768 
769 /**
770  * ksmbd_vfs_truncate() - vfs helper for smb file truncate
771  * @work:	work
772  * @fid:	file id of old file
773  * @size:	truncate to given size
774  *
775  * Return:	0 on success, otherwise error
776  */
777 int ksmbd_vfs_truncate(struct ksmbd_work *work,
778 		       struct ksmbd_file *fp, loff_t size)
779 {
780 	int err = 0;
781 	struct file *filp;
782 
783 	filp = fp->filp;
784 
785 	/* Do we need to break any of a levelII oplock? */
786 	smb_break_all_levII_oplock(work, fp, 1);
787 
788 	if (!work->tcon->posix_extensions) {
789 		struct inode *inode = file_inode(filp);
790 
791 		if (size < inode->i_size) {
792 			err = check_lock_range(filp, size,
793 					       inode->i_size - 1, WRITE);
794 		} else {
795 			err = check_lock_range(filp, inode->i_size,
796 					       size - 1, WRITE);
797 		}
798 
799 		if (err) {
800 			pr_err("failed due to lock\n");
801 			return -EAGAIN;
802 		}
803 	}
804 
805 	err = vfs_truncate(&filp->f_path, size);
806 	if (err)
807 		pr_err("truncate failed, err %d\n", err);
808 	return err;
809 }
810 
811 /**
812  * ksmbd_vfs_listxattr() - vfs helper for smb list extended attributes
813  * @dentry:	dentry of file for listing xattrs
814  * @list:	destination buffer
815  * @size:	destination buffer length
816  *
817  * Return:	xattr list length on success, otherwise error
818  */
819 ssize_t ksmbd_vfs_listxattr(struct dentry *dentry, char **list)
820 {
821 	ssize_t size;
822 	char *vlist = NULL;
823 
824 	size = vfs_listxattr(dentry, NULL, 0);
825 	if (size <= 0)
826 		return size;
827 
828 	vlist = kvmalloc(size, GFP_KERNEL | __GFP_ZERO);
829 	if (!vlist)
830 		return -ENOMEM;
831 
832 	*list = vlist;
833 	size = vfs_listxattr(dentry, vlist, size);
834 	if (size < 0) {
835 		ksmbd_debug(VFS, "listxattr failed\n");
836 		kvfree(vlist);
837 		*list = NULL;
838 	}
839 
840 	return size;
841 }
842 
843 static ssize_t ksmbd_vfs_xattr_len(struct mnt_idmap *idmap,
844 				   struct dentry *dentry, char *xattr_name)
845 {
846 	return vfs_getxattr(idmap, dentry, xattr_name, NULL, 0);
847 }
848 
849 /**
850  * ksmbd_vfs_getxattr() - vfs helper for smb get extended attributes value
851  * @idmap:	idmap
852  * @dentry:	dentry of file for getting xattrs
853  * @xattr_name:	name of xattr name to query
854  * @xattr_buf:	destination buffer xattr value
855  *
856  * Return:	read xattr value length on success, otherwise error
857  */
858 ssize_t ksmbd_vfs_getxattr(struct mnt_idmap *idmap,
859 			   struct dentry *dentry,
860 			   char *xattr_name, char **xattr_buf)
861 {
862 	ssize_t xattr_len;
863 	char *buf;
864 
865 	*xattr_buf = NULL;
866 	xattr_len = ksmbd_vfs_xattr_len(idmap, dentry, xattr_name);
867 	if (xattr_len < 0)
868 		return xattr_len;
869 
870 	buf = kmalloc(xattr_len + 1, GFP_KERNEL);
871 	if (!buf)
872 		return -ENOMEM;
873 
874 	xattr_len = vfs_getxattr(idmap, dentry, xattr_name,
875 				 (void *)buf, xattr_len);
876 	if (xattr_len > 0)
877 		*xattr_buf = buf;
878 	else
879 		kfree(buf);
880 	return xattr_len;
881 }
882 
883 /**
884  * ksmbd_vfs_setxattr() - vfs helper for smb set extended attributes value
885  * @idmap:	idmap of the relevant mount
886  * @dentry:	dentry to set XATTR at
887  * @attr_name:	xattr name for setxattr
888  * @attr_value:	xattr value to set
889  * @attr_size:	size of xattr value
890  * @flags:	destination buffer length
891  *
892  * Return:	0 on success, otherwise error
893  */
894 int ksmbd_vfs_setxattr(struct mnt_idmap *idmap,
895 		       struct dentry *dentry, const char *attr_name,
896 		       void *attr_value, size_t attr_size, int flags)
897 {
898 	int err;
899 
900 	err = vfs_setxattr(idmap,
901 			   dentry,
902 			   attr_name,
903 			   attr_value,
904 			   attr_size,
905 			   flags);
906 	if (err)
907 		ksmbd_debug(VFS, "setxattr failed, err %d\n", err);
908 	return err;
909 }
910 
911 /**
912  * ksmbd_vfs_set_fadvise() - convert smb IO caching options to linux options
913  * @filp:	file pointer for IO
914  * @options:	smb IO options
915  */
916 void ksmbd_vfs_set_fadvise(struct file *filp, __le32 option)
917 {
918 	struct address_space *mapping;
919 
920 	mapping = filp->f_mapping;
921 
922 	if (!option || !mapping)
923 		return;
924 
925 	if (option & FILE_WRITE_THROUGH_LE) {
926 		filp->f_flags |= O_SYNC;
927 	} else if (option & FILE_SEQUENTIAL_ONLY_LE) {
928 		filp->f_ra.ra_pages = inode_to_bdi(mapping->host)->ra_pages * 2;
929 		spin_lock(&filp->f_lock);
930 		filp->f_mode &= ~FMODE_RANDOM;
931 		spin_unlock(&filp->f_lock);
932 	} else if (option & FILE_RANDOM_ACCESS_LE) {
933 		spin_lock(&filp->f_lock);
934 		filp->f_mode |= FMODE_RANDOM;
935 		spin_unlock(&filp->f_lock);
936 	}
937 }
938 
939 int ksmbd_vfs_zero_data(struct ksmbd_work *work, struct ksmbd_file *fp,
940 			loff_t off, loff_t len)
941 {
942 	smb_break_all_levII_oplock(work, fp, 1);
943 	if (fp->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)
944 		return vfs_fallocate(fp->filp,
945 				     FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
946 				     off, len);
947 
948 	return vfs_fallocate(fp->filp,
949 			     FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE,
950 			     off, len);
951 }
952 
953 int ksmbd_vfs_fqar_lseek(struct ksmbd_file *fp, loff_t start, loff_t length,
954 			 struct file_allocated_range_buffer *ranges,
955 			 unsigned int in_count, unsigned int *out_count)
956 {
957 	struct file *f = fp->filp;
958 	struct inode *inode = file_inode(fp->filp);
959 	loff_t maxbytes = (u64)inode->i_sb->s_maxbytes, end;
960 	loff_t extent_start, extent_end;
961 	int ret = 0;
962 
963 	if (start > maxbytes)
964 		return -EFBIG;
965 
966 	if (!in_count)
967 		return 0;
968 
969 	/*
970 	 * Shrink request scope to what the fs can actually handle.
971 	 */
972 	if (length > maxbytes || (maxbytes - length) < start)
973 		length = maxbytes - start;
974 
975 	if (start + length > inode->i_size)
976 		length = inode->i_size - start;
977 
978 	*out_count = 0;
979 	end = start + length;
980 	while (start < end && *out_count < in_count) {
981 		extent_start = vfs_llseek(f, start, SEEK_DATA);
982 		if (extent_start < 0) {
983 			if (extent_start != -ENXIO)
984 				ret = (int)extent_start;
985 			break;
986 		}
987 
988 		if (extent_start >= end)
989 			break;
990 
991 		extent_end = vfs_llseek(f, extent_start, SEEK_HOLE);
992 		if (extent_end < 0) {
993 			if (extent_end != -ENXIO)
994 				ret = (int)extent_end;
995 			break;
996 		} else if (extent_start >= extent_end) {
997 			break;
998 		}
999 
1000 		ranges[*out_count].file_offset = cpu_to_le64(extent_start);
1001 		ranges[(*out_count)++].length =
1002 			cpu_to_le64(min(extent_end, end) - extent_start);
1003 
1004 		start = extent_end;
1005 	}
1006 
1007 	return ret;
1008 }
1009 
1010 int ksmbd_vfs_remove_xattr(struct mnt_idmap *idmap,
1011 			   struct dentry *dentry, char *attr_name)
1012 {
1013 	return vfs_removexattr(idmap, dentry, attr_name);
1014 }
1015 
1016 int ksmbd_vfs_unlink(struct file *filp)
1017 {
1018 	int err = 0;
1019 	struct dentry *dir, *dentry = filp->f_path.dentry;
1020 	struct mnt_idmap *idmap = file_mnt_idmap(filp);
1021 
1022 	dir = dget_parent(dentry);
1023 	err = ksmbd_vfs_lock_parent(dir, dentry);
1024 	if (err)
1025 		goto out;
1026 	dget(dentry);
1027 
1028 	if (S_ISDIR(d_inode(dentry)->i_mode))
1029 		err = vfs_rmdir(idmap, d_inode(dir), dentry);
1030 	else
1031 		err = vfs_unlink(idmap, d_inode(dir), dentry, NULL);
1032 
1033 	dput(dentry);
1034 	inode_unlock(d_inode(dir));
1035 	if (err)
1036 		ksmbd_debug(VFS, "failed to delete, err %d\n", err);
1037 out:
1038 	dput(dir);
1039 
1040 	return err;
1041 }
1042 
1043 static bool __dir_empty(struct dir_context *ctx, const char *name, int namlen,
1044 		       loff_t offset, u64 ino, unsigned int d_type)
1045 {
1046 	struct ksmbd_readdir_data *buf;
1047 
1048 	buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
1049 	buf->dirent_count++;
1050 
1051 	return buf->dirent_count <= 2;
1052 }
1053 
1054 /**
1055  * ksmbd_vfs_empty_dir() - check for empty directory
1056  * @fp:	ksmbd file pointer
1057  *
1058  * Return:	true if directory empty, otherwise false
1059  */
1060 int ksmbd_vfs_empty_dir(struct ksmbd_file *fp)
1061 {
1062 	int err;
1063 	struct ksmbd_readdir_data readdir_data;
1064 
1065 	memset(&readdir_data, 0, sizeof(struct ksmbd_readdir_data));
1066 
1067 	set_ctx_actor(&readdir_data.ctx, __dir_empty);
1068 	readdir_data.dirent_count = 0;
1069 
1070 	err = iterate_dir(fp->filp, &readdir_data.ctx);
1071 	if (readdir_data.dirent_count > 2)
1072 		err = -ENOTEMPTY;
1073 	else
1074 		err = 0;
1075 	return err;
1076 }
1077 
1078 static bool __caseless_lookup(struct dir_context *ctx, const char *name,
1079 			     int namlen, loff_t offset, u64 ino,
1080 			     unsigned int d_type)
1081 {
1082 	struct ksmbd_readdir_data *buf;
1083 	int cmp = -EINVAL;
1084 
1085 	buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
1086 
1087 	if (buf->used != namlen)
1088 		return true;
1089 	if (IS_ENABLED(CONFIG_UNICODE) && buf->um) {
1090 		const struct qstr q_buf = {.name = buf->private,
1091 					   .len = buf->used};
1092 		const struct qstr q_name = {.name = name,
1093 					    .len = namlen};
1094 
1095 		cmp = utf8_strncasecmp(buf->um, &q_buf, &q_name);
1096 	}
1097 	if (cmp < 0)
1098 		cmp = strncasecmp((char *)buf->private, name, namlen);
1099 	if (!cmp) {
1100 		memcpy((char *)buf->private, name, namlen);
1101 		buf->dirent_count = 1;
1102 		return false;
1103 	}
1104 	return true;
1105 }
1106 
1107 /**
1108  * ksmbd_vfs_lookup_in_dir() - lookup a file in a directory
1109  * @dir:	path info
1110  * @name:	filename to lookup
1111  * @namelen:	filename length
1112  *
1113  * Return:	0 on success, otherwise error
1114  */
1115 static int ksmbd_vfs_lookup_in_dir(const struct path *dir, char *name,
1116 				   size_t namelen, struct unicode_map *um)
1117 {
1118 	int ret;
1119 	struct file *dfilp;
1120 	int flags = O_RDONLY | O_LARGEFILE;
1121 	struct ksmbd_readdir_data readdir_data = {
1122 		.ctx.actor	= __caseless_lookup,
1123 		.private	= name,
1124 		.used		= namelen,
1125 		.dirent_count	= 0,
1126 		.um		= um,
1127 	};
1128 
1129 	dfilp = dentry_open(dir, flags, current_cred());
1130 	if (IS_ERR(dfilp))
1131 		return PTR_ERR(dfilp);
1132 
1133 	ret = iterate_dir(dfilp, &readdir_data.ctx);
1134 	if (readdir_data.dirent_count > 0)
1135 		ret = 0;
1136 	fput(dfilp);
1137 	return ret;
1138 }
1139 
1140 /**
1141  * ksmbd_vfs_kern_path_locked() - lookup a file and get path info
1142  * @name:	file path that is relative to share
1143  * @flags:	lookup flags
1144  * @path:	if lookup succeed, return path info
1145  * @caseless:	caseless filename lookup
1146  *
1147  * Return:	0 on success, otherwise error
1148  */
1149 int ksmbd_vfs_kern_path_locked(struct ksmbd_work *work, char *name,
1150 			       unsigned int flags, struct path *path,
1151 			       bool caseless)
1152 {
1153 	struct ksmbd_share_config *share_conf = work->tcon->share_conf;
1154 	int err;
1155 	struct path parent_path;
1156 
1157 	err = ksmbd_vfs_path_lookup_locked(share_conf, name, flags, path);
1158 	if (!err)
1159 		return err;
1160 
1161 	if (caseless) {
1162 		char *filepath;
1163 		size_t path_len, remain_len;
1164 
1165 		filepath = kstrdup(name, GFP_KERNEL);
1166 		if (!filepath)
1167 			return -ENOMEM;
1168 
1169 		path_len = strlen(filepath);
1170 		remain_len = path_len;
1171 
1172 		parent_path = share_conf->vfs_path;
1173 		path_get(&parent_path);
1174 
1175 		while (d_can_lookup(parent_path.dentry)) {
1176 			char *filename = filepath + path_len - remain_len;
1177 			char *next = strchrnul(filename, '/');
1178 			size_t filename_len = next - filename;
1179 			bool is_last = !next[0];
1180 
1181 			if (filename_len == 0)
1182 				break;
1183 
1184 			err = ksmbd_vfs_lookup_in_dir(&parent_path, filename,
1185 						      filename_len,
1186 						      work->conn->um);
1187 			if (err)
1188 				goto out2;
1189 
1190 			next[0] = '\0';
1191 
1192 			err = vfs_path_lookup(share_conf->vfs_path.dentry,
1193 					      share_conf->vfs_path.mnt,
1194 					      filepath,
1195 					      flags,
1196 					      path);
1197 			if (err)
1198 				goto out2;
1199 			else if (is_last)
1200 				goto out1;
1201 			path_put(&parent_path);
1202 			parent_path = *path;
1203 
1204 			next[0] = '/';
1205 			remain_len -= filename_len + 1;
1206 		}
1207 
1208 		err = -EINVAL;
1209 out2:
1210 		path_put(&parent_path);
1211 out1:
1212 		kfree(filepath);
1213 	}
1214 
1215 	if (!err) {
1216 		err = ksmbd_vfs_lock_parent(parent_path.dentry, path->dentry);
1217 		if (err)
1218 			dput(path->dentry);
1219 		path_put(&parent_path);
1220 	}
1221 	return err;
1222 }
1223 
1224 struct dentry *ksmbd_vfs_kern_path_create(struct ksmbd_work *work,
1225 					  const char *name,
1226 					  unsigned int flags,
1227 					  struct path *path)
1228 {
1229 	char *abs_name;
1230 	struct dentry *dent;
1231 
1232 	abs_name = convert_to_unix_name(work->tcon->share_conf, name);
1233 	if (!abs_name)
1234 		return ERR_PTR(-ENOMEM);
1235 
1236 	dent = kern_path_create(AT_FDCWD, abs_name, path, flags);
1237 	kfree(abs_name);
1238 	return dent;
1239 }
1240 
1241 int ksmbd_vfs_remove_acl_xattrs(struct mnt_idmap *idmap,
1242 				struct dentry *dentry)
1243 {
1244 	char *name, *xattr_list = NULL;
1245 	ssize_t xattr_list_len;
1246 	int err = 0;
1247 
1248 	xattr_list_len = ksmbd_vfs_listxattr(dentry, &xattr_list);
1249 	if (xattr_list_len < 0) {
1250 		goto out;
1251 	} else if (!xattr_list_len) {
1252 		ksmbd_debug(SMB, "empty xattr in the file\n");
1253 		goto out;
1254 	}
1255 
1256 	for (name = xattr_list; name - xattr_list < xattr_list_len;
1257 	     name += strlen(name) + 1) {
1258 		ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
1259 
1260 		if (!strncmp(name, XATTR_NAME_POSIX_ACL_ACCESS,
1261 			     sizeof(XATTR_NAME_POSIX_ACL_ACCESS) - 1) ||
1262 		    !strncmp(name, XATTR_NAME_POSIX_ACL_DEFAULT,
1263 			     sizeof(XATTR_NAME_POSIX_ACL_DEFAULT) - 1)) {
1264 			err = vfs_remove_acl(idmap, dentry, name);
1265 			if (err)
1266 				ksmbd_debug(SMB,
1267 					    "remove acl xattr failed : %s\n", name);
1268 		}
1269 	}
1270 out:
1271 	kvfree(xattr_list);
1272 	return err;
1273 }
1274 
1275 int ksmbd_vfs_remove_sd_xattrs(struct mnt_idmap *idmap,
1276 			       struct dentry *dentry)
1277 {
1278 	char *name, *xattr_list = NULL;
1279 	ssize_t xattr_list_len;
1280 	int err = 0;
1281 
1282 	xattr_list_len = ksmbd_vfs_listxattr(dentry, &xattr_list);
1283 	if (xattr_list_len < 0) {
1284 		goto out;
1285 	} else if (!xattr_list_len) {
1286 		ksmbd_debug(SMB, "empty xattr in the file\n");
1287 		goto out;
1288 	}
1289 
1290 	for (name = xattr_list; name - xattr_list < xattr_list_len;
1291 			name += strlen(name) + 1) {
1292 		ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
1293 
1294 		if (!strncmp(name, XATTR_NAME_SD, XATTR_NAME_SD_LEN)) {
1295 			err = ksmbd_vfs_remove_xattr(idmap, dentry, name);
1296 			if (err)
1297 				ksmbd_debug(SMB, "remove xattr failed : %s\n", name);
1298 		}
1299 	}
1300 out:
1301 	kvfree(xattr_list);
1302 	return err;
1303 }
1304 
1305 static struct xattr_smb_acl *ksmbd_vfs_make_xattr_posix_acl(struct mnt_idmap *idmap,
1306 							    struct inode *inode,
1307 							    int acl_type)
1308 {
1309 	struct xattr_smb_acl *smb_acl = NULL;
1310 	struct posix_acl *posix_acls;
1311 	struct posix_acl_entry *pa_entry;
1312 	struct xattr_acl_entry *xa_entry;
1313 	int i;
1314 
1315 	if (!IS_ENABLED(CONFIG_FS_POSIX_ACL))
1316 		return NULL;
1317 
1318 	posix_acls = get_inode_acl(inode, acl_type);
1319 	if (!posix_acls)
1320 		return NULL;
1321 
1322 	smb_acl = kzalloc(sizeof(struct xattr_smb_acl) +
1323 			  sizeof(struct xattr_acl_entry) * posix_acls->a_count,
1324 			  GFP_KERNEL);
1325 	if (!smb_acl)
1326 		goto out;
1327 
1328 	smb_acl->count = posix_acls->a_count;
1329 	pa_entry = posix_acls->a_entries;
1330 	xa_entry = smb_acl->entries;
1331 	for (i = 0; i < posix_acls->a_count; i++, pa_entry++, xa_entry++) {
1332 		switch (pa_entry->e_tag) {
1333 		case ACL_USER:
1334 			xa_entry->type = SMB_ACL_USER;
1335 			xa_entry->uid = posix_acl_uid_translate(idmap, pa_entry);
1336 			break;
1337 		case ACL_USER_OBJ:
1338 			xa_entry->type = SMB_ACL_USER_OBJ;
1339 			break;
1340 		case ACL_GROUP:
1341 			xa_entry->type = SMB_ACL_GROUP;
1342 			xa_entry->gid = posix_acl_gid_translate(idmap, pa_entry);
1343 			break;
1344 		case ACL_GROUP_OBJ:
1345 			xa_entry->type = SMB_ACL_GROUP_OBJ;
1346 			break;
1347 		case ACL_OTHER:
1348 			xa_entry->type = SMB_ACL_OTHER;
1349 			break;
1350 		case ACL_MASK:
1351 			xa_entry->type = SMB_ACL_MASK;
1352 			break;
1353 		default:
1354 			pr_err("unknown type : 0x%x\n", pa_entry->e_tag);
1355 			goto out;
1356 		}
1357 
1358 		if (pa_entry->e_perm & ACL_READ)
1359 			xa_entry->perm |= SMB_ACL_READ;
1360 		if (pa_entry->e_perm & ACL_WRITE)
1361 			xa_entry->perm |= SMB_ACL_WRITE;
1362 		if (pa_entry->e_perm & ACL_EXECUTE)
1363 			xa_entry->perm |= SMB_ACL_EXECUTE;
1364 	}
1365 out:
1366 	posix_acl_release(posix_acls);
1367 	return smb_acl;
1368 }
1369 
1370 int ksmbd_vfs_set_sd_xattr(struct ksmbd_conn *conn,
1371 			   struct mnt_idmap *idmap,
1372 			   struct dentry *dentry,
1373 			   struct smb_ntsd *pntsd, int len)
1374 {
1375 	int rc;
1376 	struct ndr sd_ndr = {0}, acl_ndr = {0};
1377 	struct xattr_ntacl acl = {0};
1378 	struct xattr_smb_acl *smb_acl, *def_smb_acl = NULL;
1379 	struct inode *inode = d_inode(dentry);
1380 
1381 	acl.version = 4;
1382 	acl.hash_type = XATTR_SD_HASH_TYPE_SHA256;
1383 	acl.current_time = ksmbd_UnixTimeToNT(current_time(inode));
1384 
1385 	memcpy(acl.desc, "posix_acl", 9);
1386 	acl.desc_len = 10;
1387 
1388 	pntsd->osidoffset =
1389 		cpu_to_le32(le32_to_cpu(pntsd->osidoffset) + NDR_NTSD_OFFSETOF);
1390 	pntsd->gsidoffset =
1391 		cpu_to_le32(le32_to_cpu(pntsd->gsidoffset) + NDR_NTSD_OFFSETOF);
1392 	pntsd->dacloffset =
1393 		cpu_to_le32(le32_to_cpu(pntsd->dacloffset) + NDR_NTSD_OFFSETOF);
1394 
1395 	acl.sd_buf = (char *)pntsd;
1396 	acl.sd_size = len;
1397 
1398 	rc = ksmbd_gen_sd_hash(conn, acl.sd_buf, acl.sd_size, acl.hash);
1399 	if (rc) {
1400 		pr_err("failed to generate hash for ndr acl\n");
1401 		return rc;
1402 	}
1403 
1404 	smb_acl = ksmbd_vfs_make_xattr_posix_acl(idmap, inode,
1405 						 ACL_TYPE_ACCESS);
1406 	if (S_ISDIR(inode->i_mode))
1407 		def_smb_acl = ksmbd_vfs_make_xattr_posix_acl(idmap, inode,
1408 							     ACL_TYPE_DEFAULT);
1409 
1410 	rc = ndr_encode_posix_acl(&acl_ndr, idmap, inode,
1411 				  smb_acl, def_smb_acl);
1412 	if (rc) {
1413 		pr_err("failed to encode ndr to posix acl\n");
1414 		goto out;
1415 	}
1416 
1417 	rc = ksmbd_gen_sd_hash(conn, acl_ndr.data, acl_ndr.offset,
1418 			       acl.posix_acl_hash);
1419 	if (rc) {
1420 		pr_err("failed to generate hash for ndr acl\n");
1421 		goto out;
1422 	}
1423 
1424 	rc = ndr_encode_v4_ntacl(&sd_ndr, &acl);
1425 	if (rc) {
1426 		pr_err("failed to encode ndr to posix acl\n");
1427 		goto out;
1428 	}
1429 
1430 	rc = ksmbd_vfs_setxattr(idmap, dentry,
1431 				XATTR_NAME_SD, sd_ndr.data,
1432 				sd_ndr.offset, 0);
1433 	if (rc < 0)
1434 		pr_err("Failed to store XATTR ntacl :%d\n", rc);
1435 
1436 	kfree(sd_ndr.data);
1437 out:
1438 	kfree(acl_ndr.data);
1439 	kfree(smb_acl);
1440 	kfree(def_smb_acl);
1441 	return rc;
1442 }
1443 
1444 int ksmbd_vfs_get_sd_xattr(struct ksmbd_conn *conn,
1445 			   struct mnt_idmap *idmap,
1446 			   struct dentry *dentry,
1447 			   struct smb_ntsd **pntsd)
1448 {
1449 	int rc;
1450 	struct ndr n;
1451 	struct inode *inode = d_inode(dentry);
1452 	struct ndr acl_ndr = {0};
1453 	struct xattr_ntacl acl;
1454 	struct xattr_smb_acl *smb_acl = NULL, *def_smb_acl = NULL;
1455 	__u8 cmp_hash[XATTR_SD_HASH_SIZE] = {0};
1456 
1457 	rc = ksmbd_vfs_getxattr(idmap, dentry, XATTR_NAME_SD, &n.data);
1458 	if (rc <= 0)
1459 		return rc;
1460 
1461 	n.length = rc;
1462 	rc = ndr_decode_v4_ntacl(&n, &acl);
1463 	if (rc)
1464 		goto free_n_data;
1465 
1466 	smb_acl = ksmbd_vfs_make_xattr_posix_acl(idmap, inode,
1467 						 ACL_TYPE_ACCESS);
1468 	if (S_ISDIR(inode->i_mode))
1469 		def_smb_acl = ksmbd_vfs_make_xattr_posix_acl(idmap, inode,
1470 							     ACL_TYPE_DEFAULT);
1471 
1472 	rc = ndr_encode_posix_acl(&acl_ndr, idmap, inode, smb_acl,
1473 				  def_smb_acl);
1474 	if (rc) {
1475 		pr_err("failed to encode ndr to posix acl\n");
1476 		goto out_free;
1477 	}
1478 
1479 	rc = ksmbd_gen_sd_hash(conn, acl_ndr.data, acl_ndr.offset, cmp_hash);
1480 	if (rc) {
1481 		pr_err("failed to generate hash for ndr acl\n");
1482 		goto out_free;
1483 	}
1484 
1485 	if (memcmp(cmp_hash, acl.posix_acl_hash, XATTR_SD_HASH_SIZE)) {
1486 		pr_err("hash value diff\n");
1487 		rc = -EINVAL;
1488 		goto out_free;
1489 	}
1490 
1491 	*pntsd = acl.sd_buf;
1492 	if (acl.sd_size < sizeof(struct smb_ntsd)) {
1493 		pr_err("sd size is invalid\n");
1494 		goto out_free;
1495 	}
1496 
1497 	(*pntsd)->osidoffset = cpu_to_le32(le32_to_cpu((*pntsd)->osidoffset) -
1498 					   NDR_NTSD_OFFSETOF);
1499 	(*pntsd)->gsidoffset = cpu_to_le32(le32_to_cpu((*pntsd)->gsidoffset) -
1500 					   NDR_NTSD_OFFSETOF);
1501 	(*pntsd)->dacloffset = cpu_to_le32(le32_to_cpu((*pntsd)->dacloffset) -
1502 					   NDR_NTSD_OFFSETOF);
1503 
1504 	rc = acl.sd_size;
1505 out_free:
1506 	kfree(acl_ndr.data);
1507 	kfree(smb_acl);
1508 	kfree(def_smb_acl);
1509 	if (rc < 0) {
1510 		kfree(acl.sd_buf);
1511 		*pntsd = NULL;
1512 	}
1513 
1514 free_n_data:
1515 	kfree(n.data);
1516 	return rc;
1517 }
1518 
1519 int ksmbd_vfs_set_dos_attrib_xattr(struct mnt_idmap *idmap,
1520 				   struct dentry *dentry,
1521 				   struct xattr_dos_attrib *da)
1522 {
1523 	struct ndr n;
1524 	int err;
1525 
1526 	err = ndr_encode_dos_attr(&n, da);
1527 	if (err)
1528 		return err;
1529 
1530 	err = ksmbd_vfs_setxattr(idmap, dentry, XATTR_NAME_DOS_ATTRIBUTE,
1531 				 (void *)n.data, n.offset, 0);
1532 	if (err)
1533 		ksmbd_debug(SMB, "failed to store dos attribute in xattr\n");
1534 	kfree(n.data);
1535 
1536 	return err;
1537 }
1538 
1539 int ksmbd_vfs_get_dos_attrib_xattr(struct mnt_idmap *idmap,
1540 				   struct dentry *dentry,
1541 				   struct xattr_dos_attrib *da)
1542 {
1543 	struct ndr n;
1544 	int err;
1545 
1546 	err = ksmbd_vfs_getxattr(idmap, dentry, XATTR_NAME_DOS_ATTRIBUTE,
1547 				 (char **)&n.data);
1548 	if (err > 0) {
1549 		n.length = err;
1550 		if (ndr_decode_dos_attr(&n, da))
1551 			err = -EINVAL;
1552 		kfree(n.data);
1553 	} else {
1554 		ksmbd_debug(SMB, "failed to load dos attribute in xattr\n");
1555 	}
1556 
1557 	return err;
1558 }
1559 
1560 /**
1561  * ksmbd_vfs_init_kstat() - convert unix stat information to smb stat format
1562  * @p:          destination buffer
1563  * @ksmbd_kstat:      ksmbd kstat wrapper
1564  */
1565 void *ksmbd_vfs_init_kstat(char **p, struct ksmbd_kstat *ksmbd_kstat)
1566 {
1567 	struct file_directory_info *info = (struct file_directory_info *)(*p);
1568 	struct kstat *kstat = ksmbd_kstat->kstat;
1569 	u64 time;
1570 
1571 	info->FileIndex = 0;
1572 	info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
1573 	time = ksmbd_UnixTimeToNT(kstat->atime);
1574 	info->LastAccessTime = cpu_to_le64(time);
1575 	time = ksmbd_UnixTimeToNT(kstat->mtime);
1576 	info->LastWriteTime = cpu_to_le64(time);
1577 	time = ksmbd_UnixTimeToNT(kstat->ctime);
1578 	info->ChangeTime = cpu_to_le64(time);
1579 
1580 	if (ksmbd_kstat->file_attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
1581 		info->EndOfFile = 0;
1582 		info->AllocationSize = 0;
1583 	} else {
1584 		info->EndOfFile = cpu_to_le64(kstat->size);
1585 		info->AllocationSize = cpu_to_le64(kstat->blocks << 9);
1586 	}
1587 	info->ExtFileAttributes = ksmbd_kstat->file_attributes;
1588 
1589 	return info;
1590 }
1591 
1592 int ksmbd_vfs_fill_dentry_attrs(struct ksmbd_work *work,
1593 				struct mnt_idmap *idmap,
1594 				struct dentry *dentry,
1595 				struct ksmbd_kstat *ksmbd_kstat)
1596 {
1597 	u64 time;
1598 	int rc;
1599 
1600 	generic_fillattr(idmap, d_inode(dentry), ksmbd_kstat->kstat);
1601 
1602 	time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
1603 	ksmbd_kstat->create_time = time;
1604 
1605 	/*
1606 	 * set default value for the case that store dos attributes is not yes
1607 	 * or that acl is disable in server's filesystem and the config is yes.
1608 	 */
1609 	if (S_ISDIR(ksmbd_kstat->kstat->mode))
1610 		ksmbd_kstat->file_attributes = FILE_ATTRIBUTE_DIRECTORY_LE;
1611 	else
1612 		ksmbd_kstat->file_attributes = FILE_ATTRIBUTE_ARCHIVE_LE;
1613 
1614 	if (test_share_config_flag(work->tcon->share_conf,
1615 				   KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
1616 		struct xattr_dos_attrib da;
1617 
1618 		rc = ksmbd_vfs_get_dos_attrib_xattr(idmap, dentry, &da);
1619 		if (rc > 0) {
1620 			ksmbd_kstat->file_attributes = cpu_to_le32(da.attr);
1621 			ksmbd_kstat->create_time = da.create_time;
1622 		} else {
1623 			ksmbd_debug(VFS, "fail to load dos attribute.\n");
1624 		}
1625 	}
1626 
1627 	return 0;
1628 }
1629 
1630 ssize_t ksmbd_vfs_casexattr_len(struct mnt_idmap *idmap,
1631 				struct dentry *dentry, char *attr_name,
1632 				int attr_name_len)
1633 {
1634 	char *name, *xattr_list = NULL;
1635 	ssize_t value_len = -ENOENT, xattr_list_len;
1636 
1637 	xattr_list_len = ksmbd_vfs_listxattr(dentry, &xattr_list);
1638 	if (xattr_list_len <= 0)
1639 		goto out;
1640 
1641 	for (name = xattr_list; name - xattr_list < xattr_list_len;
1642 			name += strlen(name) + 1) {
1643 		ksmbd_debug(VFS, "%s, len %zd\n", name, strlen(name));
1644 		if (strncasecmp(attr_name, name, attr_name_len))
1645 			continue;
1646 
1647 		value_len = ksmbd_vfs_xattr_len(idmap, dentry, name);
1648 		break;
1649 	}
1650 
1651 out:
1652 	kvfree(xattr_list);
1653 	return value_len;
1654 }
1655 
1656 int ksmbd_vfs_xattr_stream_name(char *stream_name, char **xattr_stream_name,
1657 				size_t *xattr_stream_name_size, int s_type)
1658 {
1659 	char *type, *buf;
1660 
1661 	if (s_type == DIR_STREAM)
1662 		type = ":$INDEX_ALLOCATION";
1663 	else
1664 		type = ":$DATA";
1665 
1666 	buf = kasprintf(GFP_KERNEL, "%s%s%s",
1667 			XATTR_NAME_STREAM, stream_name,	type);
1668 	if (!buf)
1669 		return -ENOMEM;
1670 
1671 	*xattr_stream_name = buf;
1672 	*xattr_stream_name_size = strlen(buf) + 1;
1673 
1674 	return 0;
1675 }
1676 
1677 int ksmbd_vfs_copy_file_ranges(struct ksmbd_work *work,
1678 			       struct ksmbd_file *src_fp,
1679 			       struct ksmbd_file *dst_fp,
1680 			       struct srv_copychunk *chunks,
1681 			       unsigned int chunk_count,
1682 			       unsigned int *chunk_count_written,
1683 			       unsigned int *chunk_size_written,
1684 			       loff_t *total_size_written)
1685 {
1686 	unsigned int i;
1687 	loff_t src_off, dst_off, src_file_size;
1688 	size_t len;
1689 	int ret;
1690 
1691 	*chunk_count_written = 0;
1692 	*chunk_size_written = 0;
1693 	*total_size_written = 0;
1694 
1695 	if (!(src_fp->daccess & (FILE_READ_DATA_LE | FILE_EXECUTE_LE))) {
1696 		pr_err("no right to read(%pD)\n", src_fp->filp);
1697 		return -EACCES;
1698 	}
1699 	if (!(dst_fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE))) {
1700 		pr_err("no right to write(%pD)\n", dst_fp->filp);
1701 		return -EACCES;
1702 	}
1703 
1704 	if (ksmbd_stream_fd(src_fp) || ksmbd_stream_fd(dst_fp))
1705 		return -EBADF;
1706 
1707 	smb_break_all_levII_oplock(work, dst_fp, 1);
1708 
1709 	if (!work->tcon->posix_extensions) {
1710 		for (i = 0; i < chunk_count; i++) {
1711 			src_off = le64_to_cpu(chunks[i].SourceOffset);
1712 			dst_off = le64_to_cpu(chunks[i].TargetOffset);
1713 			len = le32_to_cpu(chunks[i].Length);
1714 
1715 			if (check_lock_range(src_fp->filp, src_off,
1716 					     src_off + len - 1, READ))
1717 				return -EAGAIN;
1718 			if (check_lock_range(dst_fp->filp, dst_off,
1719 					     dst_off + len - 1, WRITE))
1720 				return -EAGAIN;
1721 		}
1722 	}
1723 
1724 	src_file_size = i_size_read(file_inode(src_fp->filp));
1725 
1726 	for (i = 0; i < chunk_count; i++) {
1727 		src_off = le64_to_cpu(chunks[i].SourceOffset);
1728 		dst_off = le64_to_cpu(chunks[i].TargetOffset);
1729 		len = le32_to_cpu(chunks[i].Length);
1730 
1731 		if (src_off + len > src_file_size)
1732 			return -E2BIG;
1733 
1734 		ret = vfs_copy_file_range(src_fp->filp, src_off,
1735 					  dst_fp->filp, dst_off, len, 0);
1736 		if (ret == -EOPNOTSUPP || ret == -EXDEV)
1737 			ret = vfs_copy_file_range(src_fp->filp, src_off,
1738 						  dst_fp->filp, dst_off, len,
1739 						  COPY_FILE_SPLICE);
1740 		if (ret < 0)
1741 			return ret;
1742 
1743 		*chunk_count_written += 1;
1744 		*total_size_written += ret;
1745 	}
1746 	return 0;
1747 }
1748 
1749 void ksmbd_vfs_posix_lock_wait(struct file_lock *flock)
1750 {
1751 	wait_event(flock->fl_wait, !flock->fl_blocker);
1752 }
1753 
1754 int ksmbd_vfs_posix_lock_wait_timeout(struct file_lock *flock, long timeout)
1755 {
1756 	return wait_event_interruptible_timeout(flock->fl_wait,
1757 						!flock->fl_blocker,
1758 						timeout);
1759 }
1760 
1761 void ksmbd_vfs_posix_lock_unblock(struct file_lock *flock)
1762 {
1763 	locks_delete_block(flock);
1764 }
1765 
1766 int ksmbd_vfs_set_init_posix_acl(struct mnt_idmap *idmap,
1767 				 struct dentry *dentry)
1768 {
1769 	struct posix_acl_state acl_state;
1770 	struct posix_acl *acls;
1771 	struct inode *inode = d_inode(dentry);
1772 	int rc;
1773 
1774 	if (!IS_ENABLED(CONFIG_FS_POSIX_ACL))
1775 		return -EOPNOTSUPP;
1776 
1777 	ksmbd_debug(SMB, "Set posix acls\n");
1778 	rc = init_acl_state(&acl_state, 1);
1779 	if (rc)
1780 		return rc;
1781 
1782 	/* Set default owner group */
1783 	acl_state.owner.allow = (inode->i_mode & 0700) >> 6;
1784 	acl_state.group.allow = (inode->i_mode & 0070) >> 3;
1785 	acl_state.other.allow = inode->i_mode & 0007;
1786 	acl_state.users->aces[acl_state.users->n].uid = inode->i_uid;
1787 	acl_state.users->aces[acl_state.users->n++].perms.allow =
1788 		acl_state.owner.allow;
1789 	acl_state.groups->aces[acl_state.groups->n].gid = inode->i_gid;
1790 	acl_state.groups->aces[acl_state.groups->n++].perms.allow =
1791 		acl_state.group.allow;
1792 	acl_state.mask.allow = 0x07;
1793 
1794 	acls = posix_acl_alloc(6, GFP_KERNEL);
1795 	if (!acls) {
1796 		free_acl_state(&acl_state);
1797 		return -ENOMEM;
1798 	}
1799 	posix_state_to_acl(&acl_state, acls->a_entries);
1800 	rc = set_posix_acl(idmap, dentry, ACL_TYPE_ACCESS, acls);
1801 	if (rc < 0)
1802 		ksmbd_debug(SMB, "Set posix acl(ACL_TYPE_ACCESS) failed, rc : %d\n",
1803 			    rc);
1804 	else if (S_ISDIR(inode->i_mode)) {
1805 		posix_state_to_acl(&acl_state, acls->a_entries);
1806 		rc = set_posix_acl(idmap, dentry, ACL_TYPE_DEFAULT, acls);
1807 		if (rc < 0)
1808 			ksmbd_debug(SMB, "Set posix acl(ACL_TYPE_DEFAULT) failed, rc : %d\n",
1809 				    rc);
1810 	}
1811 	free_acl_state(&acl_state);
1812 	posix_acl_release(acls);
1813 	return rc;
1814 }
1815 
1816 int ksmbd_vfs_inherit_posix_acl(struct mnt_idmap *idmap,
1817 				struct dentry *dentry, struct inode *parent_inode)
1818 {
1819 	struct posix_acl *acls;
1820 	struct posix_acl_entry *pace;
1821 	struct inode *inode = d_inode(dentry);
1822 	int rc, i;
1823 
1824 	if (!IS_ENABLED(CONFIG_FS_POSIX_ACL))
1825 		return -EOPNOTSUPP;
1826 
1827 	acls = get_inode_acl(parent_inode, ACL_TYPE_DEFAULT);
1828 	if (!acls)
1829 		return -ENOENT;
1830 	pace = acls->a_entries;
1831 
1832 	for (i = 0; i < acls->a_count; i++, pace++) {
1833 		if (pace->e_tag == ACL_MASK) {
1834 			pace->e_perm = 0x07;
1835 			break;
1836 		}
1837 	}
1838 
1839 	rc = set_posix_acl(idmap, dentry, ACL_TYPE_ACCESS, acls);
1840 	if (rc < 0)
1841 		ksmbd_debug(SMB, "Set posix acl(ACL_TYPE_ACCESS) failed, rc : %d\n",
1842 			    rc);
1843 	if (S_ISDIR(inode->i_mode)) {
1844 		rc = set_posix_acl(idmap, dentry, ACL_TYPE_DEFAULT,
1845 				   acls);
1846 		if (rc < 0)
1847 			ksmbd_debug(SMB, "Set posix acl(ACL_TYPE_DEFAULT) failed, rc : %d\n",
1848 				    rc);
1849 	}
1850 	posix_acl_release(acls);
1851 	return rc;
1852 }
1853