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