xref: /linux/fs/smb/server/smb2pdu.c (revision cbae17630954cb89f2bdf5bbadfd3aa81ea67283)
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 <crypto/utils.h>
8 #include <linux/inetdevice.h>
9 #include <net/addrconf.h>
10 #include <linux/syscalls.h>
11 #include <linux/namei.h>
12 #include <linux/statfs.h>
13 #include <linux/ethtool.h>
14 #include <linux/falloc.h>
15 #include <linux/mount.h>
16 #include <linux/filelock.h>
17 #include <linux/fileattr.h>
18 
19 #include "glob.h"
20 #include "../common/smbfsctl.h"
21 #include "oplock.h"
22 #include "smbacl.h"
23 
24 #include "auth.h"
25 #include "asn1.h"
26 #include "connection.h"
27 #include "transport_ipc.h"
28 #include "transport_rdma.h"
29 #include "vfs.h"
30 #include "vfs_cache.h"
31 #include "misc.h"
32 
33 #include "server.h"
34 #include "smb_common.h"
35 #include "../common/smb2status.h"
36 #include "ksmbd_work.h"
37 #include "mgmt/user_config.h"
38 #include "mgmt/share_config.h"
39 #include "mgmt/tree_connect.h"
40 #include "mgmt/user_session.h"
41 #include "mgmt/ksmbd_ida.h"
42 #include "ndr.h"
43 #include "stats.h"
44 #include "transport_tcp.h"
45 #include "compress.h"
46 
47 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
48 {
49 	if (work->next_smb2_rcv_hdr_off) {
50 		*req = ksmbd_req_buf_next(work);
51 		*rsp = ksmbd_resp_buf_next(work);
52 	} else {
53 		*req = smb_get_msg(work->request_buf);
54 		*rsp = smb_get_msg(work->response_buf);
55 	}
56 }
57 
58 #define WORK_BUFFERS(w, rq, rs)	__wbuf((w), (void **)&(rq), (void **)&(rs))
59 
60 #define SMB2_CREATE_FILE_ATTRIBUTE_MASK \
61 	(FILE_ATTRIBUTE_MASK & ~(FILE_ATTRIBUTE_INTEGRITY_STREAM | \
62 				 FILE_ATTRIBUTE_NO_SCRUB_DATA))
63 
64 /* Windows reports automatic write-time updates at roughly 15 ms resolution. */
65 #define KSMBD_WRITE_TIME_RESOLUTION	(15ULL * 10000)
66 
67 /**
68  * check_session_id() - check for valid session id in smb header
69  * @conn:	connection instance
70  * @id:		session id from smb header
71  *
72  * Return:      1 if valid session id, otherwise 0
73  */
74 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
75 {
76 	struct ksmbd_session *sess;
77 
78 	if (id == 0 || id == -1)
79 		return false;
80 
81 	sess = ksmbd_session_lookup_all(conn, id);
82 	if (sess) {
83 		ksmbd_user_session_put(sess);
84 		return true;
85 	}
86 	pr_err("Invalid user session id: %llu\n", id);
87 	return false;
88 }
89 
90 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
91 {
92 	struct channel *chann;
93 
94 	down_read(&sess->chann_lock);
95 	chann = xa_load(&sess->ksmbd_chann_list, (long)conn);
96 	up_read(&sess->chann_lock);
97 
98 	return chann;
99 }
100 
101 #define KSMBD_MAX_CHANNELS	32
102 
103 static int register_session_channel(struct ksmbd_session *sess,
104 				    struct ksmbd_conn *conn,
105 				    const char *sess_key)
106 {
107 	struct channel *chann, *old;
108 	unsigned long index;
109 	unsigned int count = 0;
110 	int rc = 0;
111 
112 	down_write(&sess->chann_lock);
113 	if (xa_load(&sess->ksmbd_chann_list, (long)conn))
114 		goto out;
115 
116 	xa_for_each(&sess->ksmbd_chann_list, index, chann)
117 		count++;
118 	if (count >= KSMBD_MAX_CHANNELS) {
119 		rc = -ENOSPC;
120 		goto out;
121 	}
122 
123 	chann = kmalloc_obj(struct channel, KSMBD_DEFAULT_GFP);
124 	if (!chann) {
125 		rc = -ENOMEM;
126 		goto out;
127 	}
128 
129 	chann->conn = conn;
130 	memcpy(chann->sess_key, sess_key, sizeof(chann->sess_key));
131 	old = xa_store(&sess->ksmbd_chann_list, (long)conn, chann,
132 		       KSMBD_DEFAULT_GFP);
133 	if (xa_is_err(old)) {
134 		kfree_sensitive(chann);
135 		rc = xa_err(old);
136 	}
137 out:
138 	up_write(&sess->chann_lock);
139 	return rc;
140 }
141 
142 /**
143  * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
144  * @work:	smb work
145  *
146  * Return:	0 if there is a tree connection matched or these are
147  *		skipable commands, otherwise error
148  */
149 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
150 {
151 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
152 	unsigned int cmd = le16_to_cpu(req_hdr->Command);
153 	unsigned int tree_id;
154 
155 	if (cmd == SMB2_TREE_CONNECT_HE ||
156 	    cmd ==  SMB2_CANCEL_HE ||
157 	    cmd ==  SMB2_LOGOFF_HE) {
158 		ksmbd_debug(SMB, "skip to check tree connect request\n");
159 		return 0;
160 	}
161 
162 	if (xa_empty(&work->sess->tree_conns)) {
163 		ksmbd_debug(SMB, "NO tree connected\n");
164 		return -ENOENT;
165 	}
166 
167 	tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
168 
169 	/*
170 	 * If request is not the first in Compound request,
171 	 * Just validate tree id in header with work->tcon->id.
172 	 */
173 	if (work->next_smb2_rcv_hdr_off) {
174 		if (!work->tcon) {
175 			pr_err("The first operation in the compound does not have tcon\n");
176 			return -EINVAL;
177 		}
178 		if (work->tcon->t_state != TREE_CONNECTED)
179 			return -ENOENT;
180 		if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
181 			pr_err("tree id(%u) is different with id(%u) in first operation\n",
182 					tree_id, work->tcon->id);
183 			return -EINVAL;
184 		}
185 		return 1;
186 	}
187 
188 	work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
189 	if (!work->tcon) {
190 		pr_err("Invalid tid %d\n", tree_id);
191 		return -ENOENT;
192 	}
193 
194 	return 1;
195 }
196 
197 /**
198  * smb2_set_err_rsp() - set error response code on smb response
199  * @work:	smb work containing response buffer
200  */
201 void smb2_set_err_rsp(struct ksmbd_work *work)
202 {
203 	struct smb2_err_rsp *err_rsp;
204 
205 	if (work->next_smb2_rcv_hdr_off)
206 		err_rsp = ksmbd_resp_buf_next(work);
207 	else
208 		err_rsp = smb_get_msg(work->response_buf);
209 
210 	if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
211 		int err;
212 
213 		err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
214 		err_rsp->ErrorContextCount = 0;
215 		err_rsp->Reserved = 0;
216 		err_rsp->ByteCount = 0;
217 		err_rsp->ErrorData[0] = 0;
218 		err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
219 					__SMB2_HEADER_STRUCTURE_SIZE +
220 						SMB2_ERROR_STRUCTURE_SIZE2);
221 		if (err)
222 			work->send_no_response = 1;
223 	}
224 }
225 
226 /**
227  * is_smb2_neg_cmd() - is it smb2 negotiation command
228  * @work:	smb work containing smb header
229  *
230  * Return:      true if smb2 negotiation command, otherwise false
231  */
232 bool is_smb2_neg_cmd(struct ksmbd_work *work)
233 {
234 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
235 
236 	/* is it SMB2 header ? */
237 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
238 		return false;
239 
240 	/* make sure it is request not response message */
241 	if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
242 		return false;
243 
244 	if (hdr->Command != SMB2_NEGOTIATE)
245 		return false;
246 
247 	return true;
248 }
249 
250 /**
251  * is_smb2_rsp() - is it smb2 response
252  * @work:	smb work containing smb response buffer
253  *
254  * Return:      true if smb2 response, otherwise false
255  */
256 bool is_smb2_rsp(struct ksmbd_work *work)
257 {
258 	struct smb2_hdr *hdr = smb_get_msg(work->response_buf);
259 
260 	/* is it SMB2 header ? */
261 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
262 		return false;
263 
264 	/* make sure it is response not request message */
265 	if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
266 		return false;
267 
268 	return true;
269 }
270 
271 /**
272  * get_smb2_cmd_val() - get smb command code from smb header
273  * @work:	smb work containing smb request buffer
274  *
275  * Return:      smb2 request command value
276  */
277 u16 get_smb2_cmd_val(struct ksmbd_work *work)
278 {
279 	struct smb2_hdr *rcv_hdr;
280 
281 	if (work->next_smb2_rcv_hdr_off)
282 		rcv_hdr = ksmbd_req_buf_next(work);
283 	else
284 		rcv_hdr = smb_get_msg(work->request_buf);
285 	return le16_to_cpu(rcv_hdr->Command);
286 }
287 
288 /**
289  * set_smb2_rsp_status() - set error response code on smb2 header
290  * @work:	smb work containing response buffer
291  * @err:	error response code
292  */
293 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
294 {
295 	struct smb2_hdr *rsp_hdr;
296 
297 	if (work->next_smb2_rcv_hdr_off) {
298 		rsp_hdr = ksmbd_resp_buf_next(work);
299 		rsp_hdr->Status = err;
300 		smb2_set_err_rsp(work);
301 		return;
302 	}
303 
304 	rsp_hdr = smb_get_msg(work->response_buf);
305 	rsp_hdr->Status = err;
306 
307 	work->iov_idx = 0;
308 	work->iov_cnt = 0;
309 	work->next_smb2_rcv_hdr_off = 0;
310 	smb2_set_err_rsp(work);
311 }
312 
313 /**
314  * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
315  * @work:	smb work containing smb request buffer
316  *
317  * smb2 negotiate response is sent in reply of smb1 negotiate command for
318  * dialect auto-negotiation.
319  */
320 int init_smb2_neg_rsp(struct ksmbd_work *work)
321 {
322 	struct smb2_hdr *rsp_hdr;
323 	struct smb2_negotiate_rsp *rsp;
324 	struct ksmbd_conn *conn = work->conn;
325 	int err;
326 
327 	rsp_hdr = smb_get_msg(work->response_buf);
328 	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
329 	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
330 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
331 	rsp_hdr->CreditRequest = cpu_to_le16(2);
332 	rsp_hdr->Command = SMB2_NEGOTIATE;
333 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
334 	rsp_hdr->NextCommand = 0;
335 	rsp_hdr->MessageId = 0;
336 	rsp_hdr->Id.SyncId.ProcessId = 0;
337 	rsp_hdr->Id.SyncId.TreeId = 0;
338 	rsp_hdr->SessionId = 0;
339 	memset(rsp_hdr->Signature, 0, 16);
340 
341 	rsp = smb_get_msg(work->response_buf);
342 
343 	WARN_ON(ksmbd_conn_good(conn));
344 
345 	rsp->StructureSize = cpu_to_le16(65);
346 	ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
347 	rsp->DialectRevision = cpu_to_le16(conn->dialect);
348 	/* Not setting conn guid rsp->ServerGUID, as it
349 	 * not used by client for identifying connection
350 	 */
351 	rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
352 	/* Default Max Message Size till SMB2.0, 64K*/
353 	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
354 	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
355 	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
356 
357 	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
358 	rsp->ServerStartTime = 0;
359 
360 	rsp->SecurityBufferOffset = cpu_to_le16(128);
361 	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
362 	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
363 		le16_to_cpu(rsp->SecurityBufferOffset));
364 	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
365 	if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
366 		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
367 	err = ksmbd_iov_pin_rsp(work, rsp,
368 				sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
369 	if (err)
370 		return err;
371 	conn->use_spnego = true;
372 
373 	ksmbd_conn_set_need_negotiate(conn);
374 	return 0;
375 }
376 
377 /**
378  * smb2_set_rsp_credits() - set number of credits in response buffer
379  * @work:	smb work containing smb response buffer
380  */
381 int smb2_set_rsp_credits(struct ksmbd_work *work)
382 {
383 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
384 	struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
385 	struct ksmbd_conn *conn = work->conn;
386 	unsigned short credits_requested, aux_max;
387 	unsigned short credit_charge, credits_granted = 0;
388 
389 	if (work->send_no_response)
390 		return 0;
391 
392 	hdr->CreditCharge = req_hdr->CreditCharge;
393 
394 	if (conn->total_credits > conn->vals->max_credits) {
395 		hdr->CreditRequest = 0;
396 		pr_err("Total credits overflow: %d\n", conn->total_credits);
397 		return -EINVAL;
398 	}
399 
400 	credit_charge = max_t(unsigned short,
401 			      le16_to_cpu(req_hdr->CreditCharge), 1);
402 	if (credit_charge > conn->total_credits) {
403 		ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
404 			    credit_charge, conn->total_credits);
405 		return -EINVAL;
406 	}
407 
408 	conn->total_credits -= credit_charge;
409 	conn->outstanding_credits -= credit_charge;
410 	work->credit_charge = 0;
411 	credits_requested = max_t(unsigned short,
412 				  le16_to_cpu(req_hdr->CreditRequest), 1);
413 
414 	/* according to smb2.credits smbtorture, Windows server
415 	 * 2016 or later grant up to 8192 credits at once.
416 	 *
417 	 * TODO: Need to adjuct CreditRequest value according to
418 	 * current cpu load
419 	 */
420 	if (hdr->Command == SMB2_NEGOTIATE)
421 		aux_max = 1;
422 	else
423 		aux_max = conn->vals->max_credits - conn->total_credits;
424 	credits_granted = min_t(unsigned short, credits_requested, aux_max);
425 
426 	conn->total_credits += credits_granted;
427 	work->credits_granted += credits_granted;
428 
429 	if (!req_hdr->NextCommand) {
430 		/* Update CreditRequest in last request */
431 		hdr->CreditRequest = cpu_to_le16(work->credits_granted);
432 	}
433 	ksmbd_debug(SMB,
434 		    "credits: requested[%d] granted[%d] total_granted[%d]\n",
435 		    credits_requested, credits_granted,
436 		    conn->total_credits);
437 	return 0;
438 }
439 
440 /**
441  * init_chained_smb2_rsp() - initialize smb2 chained response
442  * @work:	smb work containing smb response buffer
443  */
444 static void init_chained_smb2_rsp(struct ksmbd_work *work)
445 {
446 	struct smb2_hdr *req = ksmbd_req_buf_next(work);
447 	struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
448 	struct smb2_hdr *rsp_hdr;
449 	struct smb2_hdr *rcv_hdr;
450 	int next_hdr_offset = 0;
451 	int len, new_len;
452 
453 	/* Len of this response = updated RFC len - offset of previous cmd
454 	 * in the compound rsp
455 	 */
456 
457 	/* Storing the current local FID which may be needed by subsequent
458 	 * command in the compound request
459 	 */
460 	if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
461 		work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
462 		work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
463 		work->compound_sid = le64_to_cpu(rsp->SessionId);
464 		work->compound_status = STATUS_SUCCESS;
465 	} else if ((req->Command == SMB2_FLUSH ||
466 		    req->Command == SMB2_READ ||
467 		    req->Command == SMB2_WRITE) &&
468 		   rsp->Status == STATUS_SUCCESS) {
469 		u64 volatile_id = KSMBD_NO_FID;
470 		u64 persistent_id = KSMBD_NO_FID;
471 
472 		if (req->Command == SMB2_FLUSH) {
473 			struct smb2_flush_req *flush_req =
474 				(struct smb2_flush_req *)req;
475 
476 			volatile_id = flush_req->VolatileFileId;
477 			persistent_id = flush_req->PersistentFileId;
478 		} else if (req->Command == SMB2_READ) {
479 			struct smb2_read_req *read_req =
480 				(struct smb2_read_req *)req;
481 
482 			volatile_id = read_req->VolatileFileId;
483 			persistent_id = read_req->PersistentFileId;
484 		} else {
485 			struct smb2_write_req *write_req =
486 				(struct smb2_write_req *)req;
487 
488 			volatile_id = write_req->VolatileFileId;
489 			persistent_id = write_req->PersistentFileId;
490 		}
491 
492 		if (has_file_id(volatile_id)) {
493 			work->compound_fid = volatile_id;
494 			work->compound_pfid = persistent_id;
495 			work->compound_sid = le64_to_cpu(rsp->SessionId);
496 			work->compound_status = STATUS_SUCCESS;
497 		}
498 	} else if (req->Command == SMB2_CREATE) {
499 		work->compound_fid = KSMBD_NO_FID;
500 		work->compound_pfid = KSMBD_NO_FID;
501 		work->compound_sid = le64_to_cpu(rsp->SessionId);
502 		work->compound_status = rsp->Status;
503 	} else if (rsp->Status != STATUS_SUCCESS) {
504 		work->compound_sid = le64_to_cpu(rsp->SessionId);
505 		/*
506 		 * Only carry the failed status forward when the failing command
507 		 * was itself part of the related chain. An unrelated command
508 		 * that fails (e.g. a standalone request with a bad session id)
509 		 * must not seed the status for a following related command,
510 		 * which has to be evaluated on its own (and may legitimately
511 		 * fail with a different status such as INVALID_PARAMETER). The
512 		 * compound session id is still tracked so a following related
513 		 * command can validate it.
514 		 */
515 		if (req->Flags & SMB2_FLAGS_RELATED_OPERATIONS)
516 			work->compound_status = rsp->Status;
517 	}
518 
519 	len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
520 	next_hdr_offset = le32_to_cpu(req->NextCommand);
521 
522 	new_len = ALIGN(len, 8);
523 	work->iov[work->iov_idx].iov_len += (new_len - len);
524 	inc_rfc1001_len(work->response_buf, new_len - len);
525 	rsp->NextCommand = cpu_to_le32(new_len);
526 
527 	work->next_smb2_rcv_hdr_off += next_hdr_offset;
528 	work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
529 	work->next_smb2_rsp_hdr_off += new_len;
530 	ksmbd_debug(SMB,
531 		    "Compound req new_len = %d rcv off = %d rsp off = %d\n",
532 		    new_len, work->next_smb2_rcv_hdr_off,
533 		    work->next_smb2_rsp_hdr_off);
534 
535 	rsp_hdr = ksmbd_resp_buf_next(work);
536 	rcv_hdr = ksmbd_req_buf_next(work);
537 
538 	if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
539 		ksmbd_debug(SMB, "related flag should be set\n");
540 		work->compound_fid = KSMBD_NO_FID;
541 		work->compound_pfid = KSMBD_NO_FID;
542 		work->compound_status = STATUS_SUCCESS;
543 	}
544 	memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
545 	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
546 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
547 	rsp_hdr->Command = rcv_hdr->Command;
548 
549 	/*
550 	 * Message is response. We don't grant oplock yet.
551 	 */
552 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
553 				SMB2_FLAGS_RELATED_OPERATIONS);
554 	rsp_hdr->NextCommand = 0;
555 	rsp_hdr->MessageId = rcv_hdr->MessageId;
556 	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
557 	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
558 	rsp_hdr->SessionId = rcv_hdr->SessionId;
559 	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
560 }
561 
562 static bool smb2_compound_has_failed(struct ksmbd_work *work,
563 				     struct smb2_hdr *rsp)
564 {
565 	if (!work->next_smb2_rcv_hdr_off ||
566 	    has_file_id(work->compound_fid) ||
567 	    work->compound_status == STATUS_SUCCESS)
568 		return false;
569 
570 	rsp->Status = work->compound_status;
571 	smb2_set_err_rsp(work);
572 	return true;
573 }
574 
575 /**
576  * is_chained_smb2_message() - check for chained command
577  * @work:	smb work containing smb request buffer
578  *
579  * Return:      true if chained request, otherwise false
580  */
581 bool is_chained_smb2_message(struct ksmbd_work *work)
582 {
583 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
584 	unsigned int len, next_cmd;
585 
586 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
587 		return false;
588 
589 	hdr = ksmbd_req_buf_next(work);
590 	next_cmd = le32_to_cpu(hdr->NextCommand);
591 	if (next_cmd > 0) {
592 		if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
593 			__SMB2_HEADER_STRUCTURE_SIZE >
594 		    get_rfc1002_len(work->request_buf)) {
595 			pr_err("next command(%u) offset exceeds smb msg size\n",
596 			       next_cmd);
597 			return false;
598 		}
599 
600 		if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
601 		    work->response_sz) {
602 			pr_err("next response offset exceeds response buffer size\n");
603 			return false;
604 		}
605 
606 		ksmbd_debug(SMB, "got SMB2 chained command\n");
607 		init_chained_smb2_rsp(work);
608 		return true;
609 	} else if (work->next_smb2_rcv_hdr_off) {
610 		/*
611 		 * This is last request in chained command,
612 		 * align response to 8 byte
613 		 */
614 		len = ALIGN(get_rfc1002_len(work->response_buf), 8);
615 		len = len - get_rfc1002_len(work->response_buf);
616 		if (len) {
617 			ksmbd_debug(SMB, "padding len %u\n", len);
618 			work->iov[work->iov_idx].iov_len += len;
619 			inc_rfc1001_len(work->response_buf, len);
620 		}
621 		work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
622 	}
623 	return false;
624 }
625 
626 /**
627  * init_smb2_rsp_hdr() - initialize smb2 response
628  * @work:	smb work containing smb request buffer
629  *
630  * Return:      0
631  */
632 int init_smb2_rsp_hdr(struct ksmbd_work *work)
633 {
634 	struct smb2_hdr *rsp_hdr = smb_get_msg(work->response_buf);
635 	struct smb2_hdr *rcv_hdr = smb_get_msg(work->request_buf);
636 
637 	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
638 	rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
639 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
640 	rsp_hdr->Command = rcv_hdr->Command;
641 
642 	/*
643 	 * Message is response. We don't grant oplock yet.
644 	 */
645 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
646 	rsp_hdr->NextCommand = 0;
647 	rsp_hdr->MessageId = rcv_hdr->MessageId;
648 	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
649 	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
650 	rsp_hdr->SessionId = rcv_hdr->SessionId;
651 	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
652 
653 	return 0;
654 }
655 
656 /**
657  * smb2_allocate_rsp_buf() - allocate smb2 response buffer
658  * @work:	smb work containing smb request buffer
659  *
660  * Return:      0 on success, otherwise error
661  */
662 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
663 {
664 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
665 	size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
666 	size_t large_sz = small_sz + work->conn->vals->max_trans_size;
667 	size_t sz = small_sz;
668 	int cmd = le16_to_cpu(hdr->Command);
669 
670 	if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
671 		sz = large_sz;
672 
673 	if (cmd == SMB2_QUERY_INFO_HE) {
674 		struct smb2_query_info_req *req;
675 
676 		if (get_rfc1002_len(work->request_buf) <
677 		    offsetof(struct smb2_query_info_req, OutputBufferLength))
678 			return -EINVAL;
679 
680 		req = smb_get_msg(work->request_buf);
681 		if ((req->InfoType == SMB2_O_INFO_FILE &&
682 		     (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
683 		     req->FileInfoClass == FILE_ALL_INFORMATION)) ||
684 		    req->InfoType == SMB2_O_INFO_SECURITY)
685 			sz = large_sz;
686 	}
687 
688 	/* allocate large response buf for chained commands */
689 	if (le32_to_cpu(hdr->NextCommand) > 0)
690 		sz = large_sz;
691 
692 	work->response_buf = kvzalloc(sz, KSMBD_DEFAULT_GFP);
693 	if (!work->response_buf)
694 		return -ENOMEM;
695 
696 	work->response_sz = sz;
697 	return 0;
698 }
699 
700 /**
701  * smb2_check_user_session() - check for valid session for a user
702  * @work:	smb work containing smb request buffer
703  *
704  * Return:      0 on success, otherwise error
705  */
706 int smb2_check_user_session(struct ksmbd_work *work)
707 {
708 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
709 	struct ksmbd_conn *conn = work->conn;
710 	unsigned int cmd = le16_to_cpu(req_hdr->Command);
711 	unsigned long long sess_id;
712 
713 	/*
714 	 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
715 	 * require a session id, so no need to validate user session's for
716 	 * these commands.
717 	 */
718 	if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
719 	    cmd == SMB2_SESSION_SETUP_HE)
720 		return 0;
721 
722 	if (!ksmbd_conn_good(conn))
723 		return -EIO;
724 
725 	sess_id = le64_to_cpu(req_hdr->SessionId);
726 
727 	/*
728 	 * If request is not the first in Compound request,
729 	 * Just validate session id in header with work->sess->id.
730 	 */
731 	if (work->next_smb2_rcv_hdr_off) {
732 		if (!work->sess) {
733 			pr_err("The first operation in the compound does not have sess\n");
734 			return -EINVAL;
735 		}
736 		if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
737 			pr_err("session id(%llu) is different with the first operation(%lld)\n",
738 					sess_id, work->sess->id);
739 			return -EINVAL;
740 		}
741 		if (work->sess->state != SMB2_SESSION_VALID) {
742 			pr_err("compound request on a non-valid session (state %d)\n",
743 					work->sess->state);
744 			return -EINVAL;
745 		}
746 		return 1;
747 	}
748 
749 	/* Check for validity of user session */
750 	work->sess = ksmbd_session_lookup_all(conn, sess_id);
751 	if (work->sess)
752 		return 1;
753 	ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
754 	return -ENOENT;
755 }
756 
757 /**
758  * smb2_get_name() - get filename string from on the wire smb format
759  * @src:	source buffer
760  * @maxlen:	maxlen of source string
761  * @local_nls:	nls_table pointer
762  *
763  * Return:      matching converted filename on success, otherwise error ptr
764  */
765 static char *
766 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
767 {
768 	char *name;
769 
770 	name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
771 	if (IS_ERR(name)) {
772 		pr_err("failed to get name %ld\n", PTR_ERR(name));
773 		return name;
774 	}
775 
776 	if (*name == '\0') {
777 		kfree(name);
778 		return ERR_PTR(-EINVAL);
779 	}
780 
781 	if (*name == '\\') {
782 		pr_err("not allow directory name included leading slash\n");
783 		kfree(name);
784 		return ERR_PTR(-EINVAL);
785 	}
786 
787 	ksmbd_conv_path_to_unix(name);
788 	ksmbd_strip_last_slash(name);
789 	return name;
790 }
791 
792 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
793 {
794 	struct ksmbd_conn *conn = work->conn;
795 	int id;
796 
797 	id = ksmbd_acquire_async_msg_id(&conn->async_ida);
798 	if (id < 0) {
799 		pr_err("Failed to alloc async message id\n");
800 		return id;
801 	}
802 	work->asynchronous = true;
803 	work->async_id = id;
804 
805 	ksmbd_debug(SMB,
806 		    "Send interim Response to inform async request id : %d\n",
807 		    work->async_id);
808 
809 	work->cancel_fn = fn;
810 	work->cancel_argv = arg;
811 
812 	if (list_empty(&work->async_request_entry)) {
813 		spin_lock(&conn->request_lock);
814 		list_add_tail(&work->async_request_entry, &conn->async_requests);
815 		spin_unlock(&conn->request_lock);
816 	}
817 
818 	return 0;
819 }
820 
821 void release_async_work(struct ksmbd_work *work)
822 {
823 	struct ksmbd_conn *conn = work->conn;
824 
825 	spin_lock(&conn->request_lock);
826 	list_del_init(&work->async_request_entry);
827 	spin_unlock(&conn->request_lock);
828 
829 	work->asynchronous = 0;
830 	work->cancel_fn = NULL;
831 	kfree(work->cancel_argv);
832 	work->cancel_argv = NULL;
833 	if (work->async_id) {
834 		ksmbd_release_id(&conn->async_ida, work->async_id);
835 		work->async_id = 0;
836 	}
837 }
838 
839 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
840 {
841 	struct smb2_hdr *rsp_hdr;
842 	struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
843 
844 	if (!in_work)
845 		return;
846 
847 	if (allocate_interim_rsp_buf(in_work)) {
848 		pr_err("smb_allocate_rsp_buf failed!\n");
849 		ksmbd_free_work_struct(in_work);
850 		return;
851 	}
852 
853 	in_work->conn = work->conn;
854 	memcpy(smb_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
855 	       __SMB2_HEADER_STRUCTURE_SIZE);
856 
857 	rsp_hdr = smb_get_msg(in_work->response_buf);
858 	rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
859 	rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
860 	smb2_set_err_rsp(in_work);
861 	rsp_hdr->Status = status;
862 
863 	ksmbd_conn_write(in_work);
864 	ksmbd_free_work_struct(in_work);
865 }
866 
867 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
868 {
869 	if (S_ISDIR(mode) || S_ISREG(mode))
870 		return 0;
871 
872 	if (S_ISLNK(mode))
873 		return IO_REPARSE_TAG_LX_SYMLINK_LE;
874 	else if (S_ISFIFO(mode))
875 		return IO_REPARSE_TAG_LX_FIFO_LE;
876 	else if (S_ISSOCK(mode))
877 		return IO_REPARSE_TAG_AF_UNIX_LE;
878 	else if (S_ISCHR(mode))
879 		return IO_REPARSE_TAG_LX_CHR_LE;
880 	else if (S_ISBLK(mode))
881 		return IO_REPARSE_TAG_LX_BLK_LE;
882 
883 	return 0;
884 }
885 
886 /**
887  * smb2_get_dos_mode() - get file mode in dos format from unix mode
888  * @stat:	kstat containing file mode
889  * @attribute:	attribute flags
890  *
891  * Return:      converted dos mode
892  */
893 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
894 {
895 	int attr = 0;
896 
897 	if (S_ISDIR(stat->mode)) {
898 		attr = FILE_ATTRIBUTE_DIRECTORY |
899 			(attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
900 	} else {
901 		attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
902 		attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
903 		if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
904 				FILE_SUPPORTS_SPARSE_FILES))
905 			attr |= FILE_ATTRIBUTE_SPARSE_FILE;
906 
907 		if (smb2_get_reparse_tag_special_file(stat->mode))
908 			attr |= FILE_ATTRIBUTE_REPARSE_POINT;
909 	}
910 
911 	return attr;
912 }
913 
914 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
915 			       __le16 hash_id)
916 {
917 	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
918 	pneg_ctxt->DataLength = cpu_to_le16(38);
919 	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
920 	pneg_ctxt->Reserved = cpu_to_le32(0);
921 	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
922 	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
923 	pneg_ctxt->HashAlgorithms = hash_id;
924 }
925 
926 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
927 			       __le16 cipher_type)
928 {
929 	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
930 	pneg_ctxt->DataLength = cpu_to_le16(4);
931 	pneg_ctxt->Reserved = cpu_to_le32(0);
932 	pneg_ctxt->CipherCount = cpu_to_le16(1);
933 	pneg_ctxt->Ciphers[0] = cipher_type;
934 }
935 
936 static void build_compress_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
937 				__le16 compress_algorithm, bool compress_chained,
938 				bool compress_pattern)
939 {
940 	/*
941 	 * Return only algorithms implemented by ksmbd. Pattern_V1 is advertised
942 	 * as a second ID when the client also enabled chained transforms.
943 	 */
944 	pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
945 	pneg_ctxt->DataLength = cpu_to_le16(compress_pattern ? 12 : 10);
946 	pneg_ctxt->Reserved = cpu_to_le32(0);
947 	pneg_ctxt->CompressionAlgorithmCount =
948 		cpu_to_le16(compress_pattern ? 2 : 1);
949 	pneg_ctxt->Padding = cpu_to_le16(0);
950 	pneg_ctxt->Flags = compress_chained ?
951 		SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED :
952 		SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE;
953 	pneg_ctxt->CompressionAlgorithms[0] = compress_algorithm;
954 	pneg_ctxt->CompressionAlgorithms[1] = compress_pattern ?
955 		SMB3_COMPRESS_PATTERN : 0;
956 	pneg_ctxt->CompressionAlgorithms[2] = 0;
957 	pneg_ctxt->CompressionAlgorithms[3] = 0;
958 }
959 
960 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
961 				__le16 sign_algo)
962 {
963 	pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
964 	pneg_ctxt->DataLength =
965 		cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
966 			- sizeof(struct smb2_neg_context));
967 	pneg_ctxt->Reserved = cpu_to_le32(0);
968 	pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
969 	pneg_ctxt->SigningAlgorithms[0] = sign_algo;
970 }
971 
972 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
973 {
974 	pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
975 	pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
976 	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
977 	pneg_ctxt->Name[0] = 0x93;
978 	pneg_ctxt->Name[1] = 0xAD;
979 	pneg_ctxt->Name[2] = 0x25;
980 	pneg_ctxt->Name[3] = 0x50;
981 	pneg_ctxt->Name[4] = 0x9C;
982 	pneg_ctxt->Name[5] = 0xB4;
983 	pneg_ctxt->Name[6] = 0x11;
984 	pneg_ctxt->Name[7] = 0xE7;
985 	pneg_ctxt->Name[8] = 0xB4;
986 	pneg_ctxt->Name[9] = 0x23;
987 	pneg_ctxt->Name[10] = 0x83;
988 	pneg_ctxt->Name[11] = 0xDE;
989 	pneg_ctxt->Name[12] = 0x96;
990 	pneg_ctxt->Name[13] = 0x8B;
991 	pneg_ctxt->Name[14] = 0xCD;
992 	pneg_ctxt->Name[15] = 0x7C;
993 }
994 
995 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
996 				  struct smb2_negotiate_rsp *rsp)
997 {
998 	char * const pneg_ctxt = (char *)rsp +
999 			le32_to_cpu(rsp->NegotiateContextOffset);
1000 	int neg_ctxt_cnt = 1;
1001 	int ctxt_size;
1002 
1003 	ksmbd_debug(SMB,
1004 		    "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1005 	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
1006 			   conn->preauth_info->Preauth_HashId);
1007 	ctxt_size = sizeof(struct smb2_preauth_neg_context);
1008 
1009 	if (conn->cipher_type) {
1010 		/* Round to 8 byte boundary */
1011 		ctxt_size = round_up(ctxt_size, 8);
1012 		ksmbd_debug(SMB,
1013 			    "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1014 		build_encrypt_ctxt((struct smb2_encryption_neg_context *)
1015 				   (pneg_ctxt + ctxt_size),
1016 				   conn->cipher_type);
1017 		neg_ctxt_cnt++;
1018 		ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
1019 	}
1020 
1021 	if (conn->compress_algorithm != SMB3_COMPRESS_NONE) {
1022 		ctxt_size = round_up(ctxt_size, 8);
1023 		ksmbd_debug(SMB,
1024 			    "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
1025 		build_compress_ctxt((struct smb2_compression_capabilities_context *)
1026 				    (pneg_ctxt + ctxt_size),
1027 				    conn->compress_algorithm,
1028 				    conn->compress_chained,
1029 				    conn->compress_pattern);
1030 		neg_ctxt_cnt++;
1031 		ctxt_size += sizeof(struct smb2_neg_context) +
1032 			(conn->compress_pattern ? 12 : 10);
1033 	}
1034 
1035 	if (conn->posix_ext_supported) {
1036 		ctxt_size = round_up(ctxt_size, 8);
1037 		ksmbd_debug(SMB,
1038 			    "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1039 		build_posix_ctxt((struct smb2_posix_neg_context *)
1040 				 (pneg_ctxt + ctxt_size));
1041 		neg_ctxt_cnt++;
1042 		ctxt_size += sizeof(struct smb2_posix_neg_context);
1043 	}
1044 
1045 	if (conn->signing_negotiated) {
1046 		ctxt_size = round_up(ctxt_size, 8);
1047 		ksmbd_debug(SMB,
1048 			    "assemble SMB2_SIGNING_CAPABILITIES context\n");
1049 		build_sign_cap_ctxt((struct smb2_signing_capabilities *)
1050 				    (pneg_ctxt + ctxt_size),
1051 				    conn->signing_algorithm);
1052 		neg_ctxt_cnt++;
1053 		ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
1054 	}
1055 
1056 	rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
1057 	return ctxt_size + AUTH_GSS_PADDING;
1058 }
1059 
1060 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
1061 				  struct smb2_preauth_neg_context *pneg_ctxt,
1062 				  int ctxt_len)
1063 {
1064 	/*
1065 	 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
1066 	 * which may not be present. Only check for used HashAlgorithms[1].
1067 	 */
1068 	if (ctxt_len <
1069 	    sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
1070 		return STATUS_INVALID_PARAMETER;
1071 
1072 	if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
1073 		return STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
1074 
1075 	conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
1076 	return STATUS_SUCCESS;
1077 }
1078 
1079 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
1080 				struct smb2_encryption_neg_context *pneg_ctxt,
1081 				int ctxt_len)
1082 {
1083 	int cph_cnt;
1084 	int i, cphs_size;
1085 
1086 	if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
1087 		pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
1088 		return;
1089 	}
1090 
1091 	conn->cipher_type = 0;
1092 
1093 	cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
1094 	cphs_size = cph_cnt * sizeof(__le16);
1095 
1096 	if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
1097 	    ctxt_len) {
1098 		pr_err("Invalid cipher count(%d)\n", cph_cnt);
1099 		return;
1100 	}
1101 
1102 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
1103 		return;
1104 
1105 	for (i = 0; i < cph_cnt; i++) {
1106 		if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
1107 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
1108 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
1109 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
1110 			ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
1111 				    pneg_ctxt->Ciphers[i]);
1112 			conn->cipher_type = pneg_ctxt->Ciphers[i];
1113 			break;
1114 		}
1115 	}
1116 }
1117 
1118 /**
1119  * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
1120  * @conn:	smb connection
1121  *
1122  * Return:	true if connection should be encrypted, else false
1123  */
1124 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
1125 {
1126 	if (!conn->ops->generate_encryptionkey)
1127 		return false;
1128 
1129 	/*
1130 	 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
1131 	 * SMB 3.1.1 uses the cipher_type field.
1132 	 */
1133 	return (conn->vals->req_capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
1134 	    conn->cipher_type;
1135 }
1136 
1137 static __le32 decode_compress_ctxt(struct ksmbd_conn *conn,
1138 				   struct smb2_compression_capabilities_context *pneg_ctxt,
1139 				   int ctxt_len)
1140 {
1141 	int alg_cnt, algs_size, i;
1142 	__le16 *algs;
1143 
1144 	if (sizeof(struct smb2_neg_context) + 10 > ctxt_len) {
1145 		pr_err("Invalid SMB2_COMPRESSION_CAPABILITIES context length\n");
1146 		return STATUS_INVALID_PARAMETER;
1147 	}
1148 
1149 	conn->compress_algorithm = SMB3_COMPRESS_NONE;
1150 	conn->compress_chained = false;
1151 	conn->compress_pattern = false;
1152 
1153 	alg_cnt = le16_to_cpu(pneg_ctxt->CompressionAlgorithmCount);
1154 	if (!alg_cnt)
1155 		return STATUS_INVALID_PARAMETER;
1156 
1157 	if (pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE &&
1158 	    pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED)
1159 		return STATUS_INVALID_PARAMETER;
1160 
1161 	algs_size = alg_cnt * sizeof(__le16);
1162 	if (sizeof(struct smb2_neg_context) + 8 + algs_size > ctxt_len) {
1163 		pr_err("Invalid compression algorithm count(%d)\n", alg_cnt);
1164 		return STATUS_INVALID_PARAMETER;
1165 	}
1166 
1167 	/*
1168 	 * CompressionAlgorithms[] is declared as a fixed 4-element array, but
1169 	 * the actual element count is variable (clients such as Windows may
1170 	 * advertise more). The on-wire length was validated above, so walk the
1171 	 * algorithms through a pointer to avoid a fixed-array bounds check.
1172 	 */
1173 	algs = pneg_ctxt->CompressionAlgorithms;
1174 	for (i = 0; i < alg_cnt; i++) {
1175 		__le16 alg = algs[i];
1176 
1177 		/*
1178 		 * LZ77 is the required general-purpose codec. Pattern_V1 is an
1179 		 * optional chained payload type and cannot stand alone.
1180 		 */
1181 		if (alg == SMB3_COMPRESS_LZ77) {
1182 			conn->compress_algorithm = alg;
1183 			conn->compress_chained =
1184 				pneg_ctxt->Flags ==
1185 				SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED;
1186 			ksmbd_debug(SMB, "Compression Algorithm ID = 0x%x\n",
1187 				    le16_to_cpu(alg));
1188 		} else if (alg == SMB3_COMPRESS_PATTERN) {
1189 			conn->compress_pattern = true;
1190 		}
1191 	}
1192 
1193 	if (conn->compress_algorithm == SMB3_COMPRESS_NONE ||
1194 	    !conn->compress_chained)
1195 		conn->compress_pattern = false;
1196 
1197 	return STATUS_SUCCESS;
1198 }
1199 
1200 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
1201 				 struct smb2_signing_capabilities *pneg_ctxt,
1202 				 int ctxt_len)
1203 {
1204 	int sign_algo_cnt;
1205 	int i, sign_alos_size;
1206 
1207 	if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
1208 		pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
1209 		return;
1210 	}
1211 
1212 	conn->signing_negotiated = false;
1213 	sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
1214 	sign_alos_size = sign_algo_cnt * sizeof(__le16);
1215 
1216 	if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
1217 	    ctxt_len) {
1218 		pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
1219 		return;
1220 	}
1221 
1222 	for (i = 0; i < sign_algo_cnt; i++) {
1223 		if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
1224 		    pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
1225 			ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
1226 				    pneg_ctxt->SigningAlgorithms[i]);
1227 			conn->signing_negotiated = true;
1228 			conn->signing_algorithm =
1229 				pneg_ctxt->SigningAlgorithms[i];
1230 			break;
1231 		}
1232 	}
1233 }
1234 
1235 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
1236 				      struct smb2_negotiate_req *req,
1237 				      unsigned int len_of_smb)
1238 {
1239 	/* +4 is to account for the RFC1001 len field */
1240 	struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
1241 	int i = 0, len_of_ctxts;
1242 	unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
1243 	unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
1244 	__le32 status = STATUS_INVALID_PARAMETER;
1245 	int compress_ctxt_cnt = 0;
1246 
1247 	ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
1248 	if (len_of_smb <= offset) {
1249 		ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1250 		return status;
1251 	}
1252 
1253 	len_of_ctxts = len_of_smb - offset;
1254 
1255 	while (i++ < neg_ctxt_cnt) {
1256 		int clen, ctxt_len;
1257 
1258 		if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1259 			break;
1260 
1261 		pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1262 		clen = le16_to_cpu(pctx->DataLength);
1263 		ctxt_len = clen + sizeof(struct smb2_neg_context);
1264 
1265 		if (ctxt_len > len_of_ctxts)
1266 			break;
1267 
1268 		if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1269 			ksmbd_debug(SMB,
1270 				    "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1271 			if (conn->preauth_info->Preauth_HashId)
1272 				break;
1273 
1274 			status = decode_preauth_ctxt(conn,
1275 						     (struct smb2_preauth_neg_context *)pctx,
1276 						     ctxt_len);
1277 			if (status != STATUS_SUCCESS)
1278 				break;
1279 		} else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1280 			ksmbd_debug(SMB,
1281 				    "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1282 			if (conn->cipher_type)
1283 				break;
1284 
1285 			decode_encrypt_ctxt(conn,
1286 					    (struct smb2_encryption_neg_context *)pctx,
1287 					    ctxt_len);
1288 		} else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1289 			ksmbd_debug(SMB,
1290 				    "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1291 			if (compress_ctxt_cnt++) {
1292 				status = STATUS_INVALID_PARAMETER;
1293 				break;
1294 			}
1295 
1296 			status = decode_compress_ctxt(conn,
1297 				(struct smb2_compression_capabilities_context *)
1298 				pctx, ctxt_len);
1299 			if (status != STATUS_SUCCESS)
1300 				break;
1301 		} else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1302 			ksmbd_debug(SMB,
1303 				    "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1304 		} else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1305 			ksmbd_debug(SMB,
1306 				    "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1307 			conn->posix_ext_supported = true;
1308 		} else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1309 			ksmbd_debug(SMB,
1310 				    "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1311 
1312 			decode_sign_cap_ctxt(conn,
1313 					     (struct smb2_signing_capabilities *)pctx,
1314 					     ctxt_len);
1315 		}
1316 
1317 		/* offsets must be 8 byte aligned */
1318 		offset = (ctxt_len + 7) & ~0x7;
1319 		len_of_ctxts -= offset;
1320 	}
1321 	return status;
1322 }
1323 
1324 /**
1325  * smb2_handle_negotiate() - handler for smb2 negotiate command
1326  * @work:	smb work containing smb request buffer
1327  *
1328  * Return:      0
1329  */
1330 int smb2_handle_negotiate(struct ksmbd_work *work)
1331 {
1332 	struct ksmbd_conn *conn = work->conn;
1333 	struct smb2_negotiate_req *req = smb_get_msg(work->request_buf);
1334 	struct smb2_negotiate_rsp *rsp = smb_get_msg(work->response_buf);
1335 	int rc = 0;
1336 	unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1337 	__le32 status;
1338 
1339 	ksmbd_debug(SMB, "Received negotiate request\n");
1340 	conn->need_neg = false;
1341 	if (ksmbd_conn_good(conn)) {
1342 		pr_err("conn->tcp_status is already in CifsGood State\n");
1343 		work->send_no_response = 1;
1344 		return rc;
1345 	}
1346 
1347 	ksmbd_conn_lock(conn);
1348 	smb2_buf_len = get_rfc1002_len(work->request_buf);
1349 	smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1350 	if (smb2_neg_size > smb2_buf_len) {
1351 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1352 		rc = -EINVAL;
1353 		goto err_out;
1354 	}
1355 
1356 	if (req->DialectCount == 0) {
1357 		pr_err("malformed packet\n");
1358 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1359 		rc = -EINVAL;
1360 		goto err_out;
1361 	}
1362 
1363 	if (conn->dialect == SMB311_PROT_ID) {
1364 		unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1365 
1366 		if (smb2_buf_len < nego_ctxt_off) {
1367 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1368 			rc = -EINVAL;
1369 			goto err_out;
1370 		}
1371 
1372 		if (smb2_neg_size > nego_ctxt_off) {
1373 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1374 			rc = -EINVAL;
1375 			goto err_out;
1376 		}
1377 
1378 		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1379 		    nego_ctxt_off) {
1380 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1381 			rc = -EINVAL;
1382 			goto err_out;
1383 		}
1384 	} else {
1385 		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1386 		    smb2_buf_len) {
1387 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1388 			rc = -EINVAL;
1389 			goto err_out;
1390 		}
1391 	}
1392 
1393 	conn->cli_cap = le32_to_cpu(req->Capabilities);
1394 	switch (conn->dialect) {
1395 	case SMB311_PROT_ID:
1396 		conn->preauth_info =
1397 			kzalloc_obj(struct preauth_integrity_info,
1398 				    KSMBD_DEFAULT_GFP);
1399 		if (!conn->preauth_info) {
1400 			rc = -ENOMEM;
1401 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1402 			goto err_out;
1403 		}
1404 
1405 		status = deassemble_neg_contexts(conn, req,
1406 						 get_rfc1002_len(work->request_buf));
1407 		if (status != STATUS_SUCCESS) {
1408 			pr_err("deassemble_neg_contexts error(0x%x)\n",
1409 			       status);
1410 			rsp->hdr.Status = status;
1411 			rc = -EINVAL;
1412 			kfree(conn->preauth_info);
1413 			conn->preauth_info = NULL;
1414 			goto err_out;
1415 		}
1416 
1417 		rc = init_smb3_11_server(conn);
1418 		if (rc < 0) {
1419 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1420 			kfree(conn->preauth_info);
1421 			conn->preauth_info = NULL;
1422 			goto err_out;
1423 		}
1424 
1425 		ksmbd_gen_preauth_integrity_hash(conn,
1426 						 work->request_buf,
1427 						 conn->preauth_info->Preauth_HashValue);
1428 		rsp->NegotiateContextOffset =
1429 				cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1430 		neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1431 		break;
1432 	case SMB302_PROT_ID:
1433 		init_smb3_02_server(conn);
1434 		break;
1435 	case SMB30_PROT_ID:
1436 		init_smb3_0_server(conn);
1437 		break;
1438 	case SMB21_PROT_ID:
1439 		init_smb2_1_server(conn);
1440 		break;
1441 	case SMB2X_PROT_ID:
1442 	case BAD_PROT_ID:
1443 	default:
1444 		ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1445 			    conn->dialect);
1446 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1447 		rc = -EINVAL;
1448 		goto err_out;
1449 	}
1450 	rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
1451 
1452 	/* For stats */
1453 	conn->connection_type = conn->dialect;
1454 
1455 	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1456 	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1457 	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1458 
1459 	memcpy(conn->ClientGUID, req->ClientGUID,
1460 			SMB2_CLIENT_GUID_SIZE);
1461 	conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1462 
1463 	rsp->StructureSize = cpu_to_le16(65);
1464 	rsp->DialectRevision = cpu_to_le16(conn->dialect);
1465 	/* Not setting conn guid rsp->ServerGUID, as it
1466 	 * not used by client for identifying server
1467 	 */
1468 	memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1469 
1470 	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1471 	rsp->ServerStartTime = 0;
1472 	ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1473 		    le32_to_cpu(rsp->NegotiateContextOffset),
1474 		    le16_to_cpu(rsp->NegotiateContextCount));
1475 
1476 	rsp->SecurityBufferOffset = cpu_to_le16(128);
1477 	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1478 	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1479 				  le16_to_cpu(rsp->SecurityBufferOffset));
1480 
1481 	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1482 	conn->use_spnego = true;
1483 
1484 	if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1485 	     server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1486 	    req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1487 		conn->sign = true;
1488 	else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1489 		server_conf.enforced_signing = true;
1490 		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1491 		conn->sign = true;
1492 	}
1493 
1494 	conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1495 	ksmbd_conn_set_need_setup(conn);
1496 
1497 err_out:
1498 	ksmbd_conn_unlock(conn);
1499 	if (rc)
1500 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1501 
1502 	if (!rc)
1503 		rc = ksmbd_iov_pin_rsp(work, rsp,
1504 				       sizeof(struct smb2_negotiate_rsp) +
1505 					AUTH_GSS_LENGTH + neg_ctxt_len);
1506 	if (rc < 0)
1507 		smb2_set_err_rsp(work);
1508 	return rc;
1509 }
1510 
1511 static int alloc_preauth_hash(struct ksmbd_session *sess,
1512 			      struct ksmbd_conn *conn)
1513 {
1514 	if (sess->Preauth_HashValue)
1515 		return 0;
1516 
1517 	if (!conn->preauth_info)
1518 		return -ENOMEM;
1519 
1520 	sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1521 					  PREAUTH_HASHVALUE_SIZE, KSMBD_DEFAULT_GFP);
1522 	if (!sess->Preauth_HashValue)
1523 		return -ENOMEM;
1524 
1525 	return 0;
1526 }
1527 
1528 static int generate_preauth_hash(struct ksmbd_work *work)
1529 {
1530 	struct ksmbd_conn *conn = work->conn;
1531 	struct ksmbd_session *sess = work->sess;
1532 	u8 *preauth_hash;
1533 
1534 	if (conn->dialect != SMB311_PROT_ID)
1535 		return 0;
1536 
1537 	if (conn->binding) {
1538 		struct preauth_session *preauth_sess;
1539 
1540 		preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1541 		if (!preauth_sess) {
1542 			preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1543 			if (!preauth_sess)
1544 				return -ENOMEM;
1545 		}
1546 
1547 		preauth_hash = preauth_sess->Preauth_HashValue;
1548 	} else {
1549 		if (!sess->Preauth_HashValue)
1550 			if (alloc_preauth_hash(sess, conn))
1551 				return -ENOMEM;
1552 		preauth_hash = sess->Preauth_HashValue;
1553 	}
1554 
1555 	ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1556 	return 0;
1557 }
1558 
1559 static int decode_negotiation_token(struct ksmbd_conn *conn,
1560 				    struct negotiate_message *negblob,
1561 				    size_t sz)
1562 {
1563 	if (!conn->use_spnego)
1564 		return -EINVAL;
1565 
1566 	if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1567 		if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1568 			conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1569 			conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1570 			conn->use_spnego = false;
1571 		}
1572 	}
1573 	return 0;
1574 }
1575 
1576 static int ntlm_negotiate(struct ksmbd_work *work,
1577 			  struct negotiate_message *negblob,
1578 			  size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
1579 {
1580 	struct challenge_message *chgblob;
1581 	unsigned char *spnego_blob = NULL;
1582 	u16 spnego_blob_len;
1583 	char *neg_blob;
1584 	int sz, rc;
1585 
1586 	ksmbd_debug(SMB, "negotiate phase\n");
1587 	rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1588 	if (rc)
1589 		return rc;
1590 
1591 	sz = le16_to_cpu(rsp->SecurityBufferOffset);
1592 	chgblob = (struct challenge_message *)rsp->Buffer;
1593 	memset(chgblob, 0, sizeof(struct challenge_message));
1594 
1595 	if (!work->conn->use_spnego) {
1596 		sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1597 		if (sz < 0)
1598 			return -ENOMEM;
1599 
1600 		rsp->SecurityBufferLength = cpu_to_le16(sz);
1601 		return 0;
1602 	}
1603 
1604 	sz = sizeof(struct challenge_message);
1605 	sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1606 
1607 	neg_blob = kzalloc(sz, KSMBD_DEFAULT_GFP);
1608 	if (!neg_blob)
1609 		return -ENOMEM;
1610 
1611 	chgblob = (struct challenge_message *)neg_blob;
1612 	sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1613 	if (sz < 0) {
1614 		rc = -ENOMEM;
1615 		goto out;
1616 	}
1617 
1618 	rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1619 					   neg_blob, sz);
1620 	if (rc) {
1621 		rc = -ENOMEM;
1622 		goto out;
1623 	}
1624 
1625 	memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
1626 	rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1627 
1628 out:
1629 	kfree(spnego_blob);
1630 	kfree(neg_blob);
1631 	return rc;
1632 }
1633 
1634 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1635 						  struct smb2_sess_setup_req *req)
1636 {
1637 	int sz;
1638 
1639 	if (conn->use_spnego && conn->mechToken)
1640 		return (struct authenticate_message *)conn->mechToken;
1641 
1642 	sz = le16_to_cpu(req->SecurityBufferOffset);
1643 	return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1644 					       + sz);
1645 }
1646 
1647 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1648 				       struct smb2_sess_setup_req *req)
1649 {
1650 	struct authenticate_message *authblob;
1651 	struct ksmbd_user *user;
1652 	char *name;
1653 	unsigned int name_off, name_len, secbuf_len;
1654 
1655 	if (conn->use_spnego && conn->mechToken)
1656 		secbuf_len = conn->mechTokenLen;
1657 	else
1658 		secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1659 	if (secbuf_len < sizeof(struct authenticate_message)) {
1660 		ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1661 		return NULL;
1662 	}
1663 	authblob = user_authblob(conn, req);
1664 	name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1665 	name_len = le16_to_cpu(authblob->UserName.Length);
1666 
1667 	if (secbuf_len < (u64)name_off + name_len)
1668 		return NULL;
1669 
1670 	name = smb_strndup_from_utf16((const char *)authblob + name_off,
1671 				      name_len,
1672 				      true,
1673 				      conn->local_nls);
1674 	if (IS_ERR(name)) {
1675 		pr_err("cannot allocate memory\n");
1676 		return NULL;
1677 	}
1678 
1679 	ksmbd_debug(SMB, "session setup request for user %s\n", name);
1680 	user = ksmbd_login_user(name);
1681 	kfree(name);
1682 	return user;
1683 }
1684 
1685 static int ntlm_authenticate(struct ksmbd_work *work,
1686 			     struct smb2_sess_setup_req *req,
1687 			     struct smb2_sess_setup_rsp *rsp)
1688 {
1689 	struct ksmbd_conn *conn = work->conn;
1690 	struct ksmbd_session *sess = work->sess;
1691 	struct ksmbd_user *user;
1692 	char channel_key[CIFS_KEY_SIZE] = {};
1693 	char *auth_key = conn->binding ? channel_key : sess->sess_key;
1694 	u64 prev_id;
1695 	bool binding = conn->binding;
1696 	int sz, rc;
1697 
1698 	ksmbd_debug(SMB, "authenticate phase\n");
1699 	if (conn->use_spnego) {
1700 		unsigned char *spnego_blob;
1701 		u16 spnego_blob_len;
1702 
1703 		rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1704 						    &spnego_blob_len,
1705 						    0);
1706 		if (rc)
1707 			return -ENOMEM;
1708 
1709 		memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
1710 		rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1711 		kfree(spnego_blob);
1712 	}
1713 
1714 	user = session_user(conn, req);
1715 	if (!user) {
1716 		ksmbd_debug(SMB, "Unknown user name or an error\n");
1717 		return -EPERM;
1718 	}
1719 
1720 	/* Check for previous session */
1721 	prev_id = le64_to_cpu(req->PreviousSessionId);
1722 	if (prev_id && prev_id != sess->id)
1723 		destroy_previous_session(conn, user, prev_id);
1724 
1725 	if (sess->state == SMB2_SESSION_VALID) {
1726 		/*
1727 		 * Reuse session if anonymous try to connect
1728 		 * on reauthetication.
1729 		 */
1730 		if (conn->binding == false && ksmbd_anonymous_user(user)) {
1731 			ksmbd_free_user(user);
1732 			return 0;
1733 		}
1734 
1735 		if (!ksmbd_compare_user(sess->user, user)) {
1736 			ksmbd_free_user(user);
1737 			return -EKEYREJECTED;
1738 		}
1739 		ksmbd_free_user(user);
1740 	} else {
1741 		sess->user = user;
1742 	}
1743 
1744 	if (conn->binding == false && user_guest(sess->user)) {
1745 		rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1746 	} else {
1747 		struct authenticate_message *authblob;
1748 
1749 		authblob = user_authblob(conn, req);
1750 		if (conn->use_spnego && conn->mechToken)
1751 			sz = conn->mechTokenLen;
1752 		else
1753 			sz = le16_to_cpu(req->SecurityBufferLength);
1754 		rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess,
1755 						    auth_key);
1756 		if (rc) {
1757 			set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1758 			ksmbd_debug(SMB, "authentication failed\n");
1759 			rc = -EPERM;
1760 			goto out;
1761 		}
1762 	}
1763 
1764 	/*
1765 	 * If session state is SMB2_SESSION_VALID, We can assume
1766 	 * that it is reauthentication. And the user/password
1767 	 * has been verified, so return it here.
1768 	 */
1769 	if (sess->state == SMB2_SESSION_VALID) {
1770 		if (conn->binding)
1771 			goto binding_session;
1772 		return 0;
1773 	}
1774 
1775 	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1776 	     (conn->sign || server_conf.enforced_signing)) ||
1777 	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1778 		sess->sign = true;
1779 
1780 	if (smb3_encryption_negotiated(conn) &&
1781 			!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1782 		conn->ops->generate_encryptionkey(conn, sess);
1783 		sess->enc = true;
1784 		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1785 			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1786 		/*
1787 		 * signing is disable if encryption is enable
1788 		 * on this session
1789 		 */
1790 		sess->sign = false;
1791 	}
1792 
1793 binding_session:
1794 	if (conn->dialect >= SMB30_PROT_ID) {
1795 		rc = register_session_channel(sess, conn, auth_key);
1796 		if (rc)
1797 			goto out;
1798 	}
1799 
1800 	if (conn->ops->generate_signingkey) {
1801 		rc = conn->ops->generate_signingkey(sess, conn);
1802 		if (rc) {
1803 			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1804 			rc = -EINVAL;
1805 			goto out;
1806 		}
1807 	}
1808 
1809 	if (!ksmbd_conn_lookup_dialect(conn)) {
1810 		pr_err("fail to verify the dialect\n");
1811 		rc = -ENOENT;
1812 		goto out;
1813 	}
1814 	rc = 0;
1815 out:
1816 	if (binding)
1817 		memzero_explicit(channel_key, sizeof(channel_key));
1818 	return rc;
1819 }
1820 
1821 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1822 static int krb5_authenticate(struct ksmbd_work *work,
1823 			     struct smb2_sess_setup_req *req,
1824 			     struct smb2_sess_setup_rsp *rsp)
1825 {
1826 	struct ksmbd_conn *conn = work->conn;
1827 	struct ksmbd_session *sess = work->sess;
1828 	char *in_blob, *out_blob;
1829 	char channel_key[CIFS_KEY_SIZE] = {};
1830 	char *auth_key = conn->binding ? channel_key : sess->sess_key;
1831 	u64 prev_sess_id;
1832 	bool binding = conn->binding;
1833 	int in_len, out_len;
1834 	int retval;
1835 
1836 	in_blob = (char *)&req->hdr.ProtocolId +
1837 		le16_to_cpu(req->SecurityBufferOffset);
1838 	in_len = le16_to_cpu(req->SecurityBufferLength);
1839 	out_blob = (char *)&rsp->hdr.ProtocolId +
1840 		le16_to_cpu(rsp->SecurityBufferOffset);
1841 	out_len = work->response_sz -
1842 		(le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1843 
1844 	retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1845 					 out_blob, &out_len, auth_key);
1846 	if (retval) {
1847 		ksmbd_debug(SMB, "krb5 authentication failed\n");
1848 		if (retval != -EKEYREJECTED)
1849 			retval = -EINVAL;
1850 		goto out;
1851 	}
1852 
1853 	/* Check previous session */
1854 	prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1855 	if (prev_sess_id && prev_sess_id != sess->id)
1856 		destroy_previous_session(conn, sess->user, prev_sess_id);
1857 
1858 	rsp->SecurityBufferLength = cpu_to_le16(out_len);
1859 
1860 	/*
1861 	 * If session state is SMB2_SESSION_VALID, We can assume
1862 	 * that it is reauthentication. And the user/password
1863 	 * has been verified, so return it here.
1864 	 */
1865 	if (sess->state == SMB2_SESSION_VALID) {
1866 		if (conn->binding)
1867 			goto binding_session;
1868 		return 0;
1869 	}
1870 
1871 	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1872 	    (conn->sign || server_conf.enforced_signing)) ||
1873 	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1874 		sess->sign = true;
1875 
1876 	if (smb3_encryption_negotiated(conn) &&
1877 	    !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1878 		conn->ops->generate_encryptionkey(conn, sess);
1879 		sess->enc = true;
1880 		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1881 			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1882 		sess->sign = false;
1883 	}
1884 
1885 binding_session:
1886 	if (conn->dialect >= SMB30_PROT_ID) {
1887 		retval = register_session_channel(sess, conn, auth_key);
1888 		if (retval)
1889 			goto out;
1890 	}
1891 
1892 	if (conn->ops->generate_signingkey) {
1893 		retval = conn->ops->generate_signingkey(sess, conn);
1894 		if (retval) {
1895 			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1896 			retval = -EINVAL;
1897 			goto out;
1898 		}
1899 	}
1900 
1901 	if (!ksmbd_conn_lookup_dialect(conn)) {
1902 		pr_err("fail to verify the dialect\n");
1903 		retval = -ENOENT;
1904 		goto out;
1905 	}
1906 	retval = 0;
1907 out:
1908 	if (binding)
1909 		memzero_explicit(channel_key, sizeof(channel_key));
1910 	return retval;
1911 }
1912 #else
1913 static int krb5_authenticate(struct ksmbd_work *work,
1914 			     struct smb2_sess_setup_req *req,
1915 			     struct smb2_sess_setup_rsp *rsp)
1916 {
1917 	return -EOPNOTSUPP;
1918 }
1919 #endif
1920 
1921 int smb2_sess_setup(struct ksmbd_work *work)
1922 {
1923 	struct ksmbd_conn *conn = work->conn;
1924 	struct smb2_sess_setup_req *req;
1925 	struct smb2_sess_setup_rsp *rsp;
1926 	struct ksmbd_session *sess;
1927 	struct negotiate_message *negblob;
1928 	unsigned int negblob_len, negblob_off;
1929 	int rc = 0;
1930 
1931 	ksmbd_debug(SMB, "Received smb2 session setup request\n");
1932 
1933 	if (!ksmbd_conn_need_setup(conn) && !ksmbd_conn_good(conn)) {
1934 		work->send_no_response = 1;
1935 		return rc;
1936 	}
1937 
1938 	WORK_BUFFERS(work, req, rsp);
1939 
1940 	rsp->StructureSize = cpu_to_le16(9);
1941 	rsp->SessionFlags = 0;
1942 	rsp->SecurityBufferOffset = cpu_to_le16(72);
1943 	rsp->SecurityBufferLength = 0;
1944 
1945 	ksmbd_conn_lock(conn);
1946 	if (!req->hdr.SessionId) {
1947 		sess = ksmbd_smb2_session_create();
1948 		if (!sess) {
1949 			rc = -ENOMEM;
1950 			goto out_err;
1951 		}
1952 		rsp->hdr.SessionId = cpu_to_le64(sess->id);
1953 		rc = ksmbd_session_register(conn, sess);
1954 		if (rc)
1955 			goto out_err;
1956 
1957 		conn->binding = false;
1958 	} else if (conn->dialect >= SMB30_PROT_ID &&
1959 		   (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1960 		   req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1961 		u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1962 
1963 		sess = ksmbd_session_lookup_slowpath(sess_id);
1964 		if (!sess) {
1965 			rc = -ENOENT;
1966 			goto out_err;
1967 		}
1968 
1969 		if (conn->dialect != sess->dialect) {
1970 			rc = -EINVAL;
1971 			goto out_err;
1972 		}
1973 
1974 		if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1975 			rc = -EINVAL;
1976 			goto out_err;
1977 		}
1978 
1979 		if (strncmp(conn->ClientGUID, sess->ClientGUID,
1980 			    SMB2_CLIENT_GUID_SIZE)) {
1981 			rc = -ENOENT;
1982 			goto out_err;
1983 		}
1984 
1985 		if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1986 			rc = -EACCES;
1987 			goto out_err;
1988 		}
1989 
1990 		if (sess->state == SMB2_SESSION_EXPIRED) {
1991 			rc = -EFAULT;
1992 			goto out_err;
1993 		}
1994 
1995 		if (ksmbd_conn_need_reconnect(conn)) {
1996 			rc = -EFAULT;
1997 			ksmbd_user_session_put(sess);
1998 			sess = NULL;
1999 			goto out_err;
2000 		}
2001 
2002 		if (is_ksmbd_session_in_connection(conn, sess_id)) {
2003 			rc = -EACCES;
2004 			goto out_err;
2005 		}
2006 
2007 		if (user_guest(sess->user)) {
2008 			rc = -EOPNOTSUPP;
2009 			goto out_err;
2010 		}
2011 
2012 		conn->binding = true;
2013 	} else if ((conn->dialect < SMB30_PROT_ID ||
2014 		    server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
2015 		   (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2016 		sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId));
2017 		if (sess) {
2018 			int sign_ret;
2019 
2020 			work->sess = sess;
2021 			if (sess->dialect >= SMB30_PROT_ID)
2022 				sign_ret = smb3_check_sign_req(work);
2023 			else
2024 				sign_ret = smb2_check_sign_req(work);
2025 			if (sess->state != SMB2_SESSION_VALID ||
2026 			    !(req->hdr.Flags & SMB2_FLAGS_SIGNED) ||
2027 			    !sign_ret) {
2028 				ksmbd_user_session_put(sess);
2029 				work->sess = NULL;
2030 				sess = NULL;
2031 			}
2032 		}
2033 		rc = -EACCES;
2034 		goto out_err;
2035 	} else {
2036 		sess = ksmbd_session_lookup(conn,
2037 					    le64_to_cpu(req->hdr.SessionId));
2038 		if (!sess) {
2039 			sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId));
2040 			if (sess && !lookup_chann_list(sess, conn)) {
2041 				ksmbd_user_session_put(sess);
2042 				sess = NULL;
2043 			}
2044 		}
2045 		if (!sess) {
2046 			rc = -ENOENT;
2047 			goto out_err;
2048 		}
2049 
2050 		if (sess->state == SMB2_SESSION_EXPIRED) {
2051 			rc = -EFAULT;
2052 			goto out_err;
2053 		}
2054 
2055 		if (ksmbd_conn_need_reconnect(conn)) {
2056 			rc = -EFAULT;
2057 			ksmbd_user_session_put(sess);
2058 			sess = NULL;
2059 			goto out_err;
2060 		}
2061 
2062 		conn->binding = false;
2063 	}
2064 	work->sess = sess;
2065 
2066 	negblob_off = le16_to_cpu(req->SecurityBufferOffset);
2067 	negblob_len = le16_to_cpu(req->SecurityBufferLength);
2068 	if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) {
2069 		rc = -EINVAL;
2070 		goto out_err;
2071 	}
2072 
2073 	negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
2074 			negblob_off);
2075 
2076 	if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
2077 		if (conn->mechToken) {
2078 			negblob = (struct negotiate_message *)conn->mechToken;
2079 			negblob_len = conn->mechTokenLen;
2080 		}
2081 	}
2082 
2083 	if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
2084 		rc = -EINVAL;
2085 		goto out_err;
2086 	}
2087 
2088 	if (server_conf.auth_mechs & conn->auth_mechs) {
2089 		rc = generate_preauth_hash(work);
2090 		if (rc)
2091 			goto out_err;
2092 
2093 		if (conn->preferred_auth_mech &
2094 				(KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
2095 			rc = krb5_authenticate(work, req, rsp);
2096 			if (rc) {
2097 				rc = -EINVAL;
2098 				goto out_err;
2099 			}
2100 
2101 			if (!ksmbd_conn_need_reconnect(conn)) {
2102 				ksmbd_conn_set_good(conn);
2103 				sess->state = SMB2_SESSION_VALID;
2104 			}
2105 		} else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
2106 			if (negblob->MessageType == NtLmNegotiate) {
2107 				rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
2108 				if (rc)
2109 					goto out_err;
2110 				rsp->hdr.Status =
2111 					STATUS_MORE_PROCESSING_REQUIRED;
2112 			} else if (negblob->MessageType == NtLmAuthenticate) {
2113 				rc = ntlm_authenticate(work, req, rsp);
2114 				if (rc)
2115 					goto out_err;
2116 
2117 				if (!ksmbd_conn_need_reconnect(conn)) {
2118 					ksmbd_conn_set_good(conn);
2119 					sess->state = SMB2_SESSION_VALID;
2120 				}
2121 				if (conn->binding) {
2122 					struct preauth_session *preauth_sess;
2123 
2124 					preauth_sess =
2125 						ksmbd_preauth_session_lookup(conn, sess->id);
2126 					if (preauth_sess) {
2127 						list_del(&preauth_sess->preauth_entry);
2128 						kfree(preauth_sess);
2129 					}
2130 				}
2131 			} else {
2132 				pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
2133 						le32_to_cpu(negblob->MessageType));
2134 				rc = -EINVAL;
2135 			}
2136 		} else {
2137 			/* TODO: need one more negotiation */
2138 			pr_err("Not support the preferred authentication\n");
2139 			rc = -EINVAL;
2140 		}
2141 	} else {
2142 		pr_err("Not support authentication\n");
2143 		rc = -EINVAL;
2144 	}
2145 
2146 out_err:
2147 	if (rc == -EINVAL)
2148 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2149 	else if (rc == -ENOENT)
2150 		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
2151 	else if (rc == -EACCES)
2152 		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
2153 	else if (rc == -EFAULT)
2154 		rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
2155 	else if (rc == -ENOMEM || rc == -ENOSPC)
2156 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2157 	else if (rc == -EOPNOTSUPP)
2158 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
2159 	else if (rc == -EKEYREJECTED)
2160 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2161 	else if (rc)
2162 		rsp->hdr.Status = STATUS_LOGON_FAILURE;
2163 	if ((rsp->hdr.Status == STATUS_USER_SESSION_DELETED ||
2164 	     (rsp->hdr.Status == STATUS_INVALID_PARAMETER &&
2165 	      (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING))) &&
2166 	    (req->hdr.Flags & SMB2_FLAGS_SIGNED))
2167 		rsp->hdr.Flags |= SMB2_FLAGS_SIGNED;
2168 
2169 	if (conn->mechToken) {
2170 		kfree(conn->mechToken);
2171 		conn->mechToken = NULL;
2172 	}
2173 
2174 	if (rc < 0) {
2175 		if (sess && conn->dialect == SMB311_PROT_ID &&
2176 		    (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2177 			struct preauth_session *preauth_sess;
2178 
2179 			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
2180 			if (preauth_sess) {
2181 				list_del(&preauth_sess->preauth_entry);
2182 				kfree(preauth_sess);
2183 			}
2184 		}
2185 
2186 		/*
2187 		 * SecurityBufferOffset should be set to zero
2188 		 * in session setup error response.
2189 		 */
2190 		rsp->SecurityBufferOffset = 0;
2191 
2192 		if (sess) {
2193 			bool try_delay = false;
2194 
2195 			/*
2196 			 * To avoid dictionary attacks (repeated session setups rapidly sent) to
2197 			 * connect to server, ksmbd make a delay of a 5 seconds on session setup
2198 			 * failure to make it harder to send enough random connection requests
2199 			 * to break into a server.
2200 			 */
2201 			if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
2202 				try_delay = true;
2203 
2204 			/*
2205 			 * For binding requests, session belongs to another
2206 			 * connection. Do not expire it.
2207 			 */
2208 			if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2209 				sess->last_active = jiffies;
2210 				sess->state = SMB2_SESSION_EXPIRED;
2211 			}
2212 			/*
2213 			 * Keep the binding session reference until the response is
2214 			 * signed and sent.  Error responses for a signed binding
2215 			 * request are signed with the existing session signing key.
2216 			 */
2217 			if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) ||
2218 			    work->sess != sess) {
2219 				ksmbd_user_session_put(sess);
2220 				work->sess = NULL;
2221 			}
2222 			if (try_delay) {
2223 				ksmbd_conn_set_need_reconnect(conn);
2224 				ssleep(5);
2225 				ksmbd_conn_set_need_setup(conn);
2226 			}
2227 		}
2228 		smb2_set_err_rsp(work);
2229 		conn->binding = false;
2230 	} else {
2231 		unsigned int iov_len;
2232 
2233 		if (rsp->SecurityBufferLength)
2234 			iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
2235 				le16_to_cpu(rsp->SecurityBufferLength);
2236 		else
2237 			iov_len = sizeof(struct smb2_sess_setup_rsp);
2238 		rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
2239 		if (rc)
2240 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2241 	}
2242 
2243 	ksmbd_conn_unlock(conn);
2244 	return rc;
2245 }
2246 
2247 /**
2248  * smb2_tree_connect() - handler for smb2 tree connect command
2249  * @work:	smb work containing smb request buffer
2250  *
2251  * Return:      0 on success, otherwise error
2252  */
2253 int smb2_tree_connect(struct ksmbd_work *work)
2254 {
2255 	struct ksmbd_conn *conn = work->conn;
2256 	struct smb2_tree_connect_req *req;
2257 	struct smb2_tree_connect_rsp *rsp;
2258 	struct ksmbd_session *sess = work->sess;
2259 	char *treename = NULL, *name = NULL;
2260 	struct ksmbd_tree_conn_status status;
2261 	struct ksmbd_share_config *share = NULL;
2262 	int rc = -EINVAL;
2263 
2264 	ksmbd_debug(SMB, "Received smb2 tree connect request\n");
2265 
2266 	WORK_BUFFERS(work, req, rsp);
2267 
2268 	treename = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->PathOffset),
2269 					  le16_to_cpu(req->PathLength), true,
2270 					  conn->local_nls);
2271 	if (IS_ERR(treename)) {
2272 		pr_err("treename is NULL\n");
2273 		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2274 		goto out_err1;
2275 	}
2276 
2277 	name = ksmbd_extract_sharename(conn->um, treename);
2278 	if (IS_ERR(name)) {
2279 		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2280 		goto out_err1;
2281 	}
2282 
2283 	ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
2284 		    name, treename);
2285 
2286 	status = ksmbd_tree_conn_connect(work, name);
2287 	if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
2288 		rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
2289 	else
2290 		goto out_err1;
2291 
2292 	share = status.tree_conn->share_conf;
2293 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2294 		ksmbd_debug(SMB, "IPC share path request\n");
2295 		rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
2296 		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2297 			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
2298 			FILE_DELETE_LE | FILE_READ_CONTROL_LE |
2299 			FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2300 			FILE_SYNCHRONIZE_LE;
2301 	} else {
2302 		rsp->ShareType = SMB2_SHARE_TYPE_DISK;
2303 		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2304 			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
2305 		if (test_tree_conn_flag(status.tree_conn,
2306 					KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2307 			rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
2308 				FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
2309 				FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
2310 				FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
2311 				FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2312 				FILE_SYNCHRONIZE_LE;
2313 		}
2314 	}
2315 
2316 	status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2317 	if (conn->posix_ext_supported)
2318 		status.tree_conn->posix_extensions = true;
2319 
2320 	down_write(&sess->tree_conns_lock);
2321 	status.tree_conn->t_state = TREE_CONNECTED;
2322 	up_write(&sess->tree_conns_lock);
2323 	rsp->StructureSize = cpu_to_le16(16);
2324 out_err1:
2325 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE && share &&
2326 	    test_share_config_flag(share,
2327 				   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
2328 		rsp->Capabilities = SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY;
2329 	else
2330 		rsp->Capabilities = 0;
2331 	rsp->Reserved = 0;
2332 	/* default manual caching */
2333 	rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2334 	/* Tell the client that READ requests may request compressed responses. */
2335 	if (conn->dialect == SMB311_PROT_ID &&
2336 	    conn->compress_algorithm != SMB3_COMPRESS_NONE)
2337 		rsp->ShareFlags |= cpu_to_le32(SMB2_SHAREFLAG_COMPRESS_DATA);
2338 
2339 	rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2340 	if (rc)
2341 		status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2342 
2343 	if (!IS_ERR(treename))
2344 		kfree(treename);
2345 	if (!IS_ERR(name))
2346 		kfree(name);
2347 
2348 	switch (status.ret) {
2349 	case KSMBD_TREE_CONN_STATUS_OK:
2350 		rsp->hdr.Status = STATUS_SUCCESS;
2351 		rc = 0;
2352 		break;
2353 	case -ESTALE:
2354 	case -ENOENT:
2355 	case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2356 		rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2357 		break;
2358 	case -ENOMEM:
2359 	case KSMBD_TREE_CONN_STATUS_NOMEM:
2360 		rsp->hdr.Status = STATUS_NO_MEMORY;
2361 		break;
2362 	case KSMBD_TREE_CONN_STATUS_ERROR:
2363 	case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2364 	case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2365 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2366 		break;
2367 	case -EINVAL:
2368 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2369 		break;
2370 	default:
2371 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2372 	}
2373 
2374 	if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2375 		smb2_set_err_rsp(work);
2376 
2377 	return rc;
2378 }
2379 
2380 /**
2381  * smb2_create_open_flags() - convert smb open flags to unix open flags
2382  * @file_present:	is file already present
2383  * @access:		file access flags
2384  * @disposition:	file disposition flags
2385  * @may_flags:		set with MAY_ flags
2386  * @coptions:		file creation options
2387  * @mode:		file mode
2388  *
2389  * Return:      file open flags
2390  */
2391 static int smb2_create_open_flags(bool file_present, __le32 access,
2392 				  __le32 disposition,
2393 				  int *may_flags,
2394 				  __le32 coptions,
2395 				  umode_t mode)
2396 {
2397 	int oflags = O_NONBLOCK | O_LARGEFILE;
2398 
2399 	if (coptions & FILE_DIRECTORY_FILE_LE || S_ISDIR(mode)) {
2400 		access &= ~FILE_WRITE_DESIRE_ACCESS_LE;
2401 		ksmbd_debug(SMB, "Discard write access to a directory\n");
2402 	}
2403 
2404 	if (access & FILE_READ_DESIRED_ACCESS_LE &&
2405 	    access & FILE_WRITE_DESIRE_ACCESS_LE) {
2406 		oflags |= O_RDWR;
2407 		*may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2408 	} else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2409 		oflags |= O_WRONLY;
2410 		*may_flags = MAY_OPEN | MAY_WRITE;
2411 	} else {
2412 		oflags |= O_RDONLY;
2413 		*may_flags = MAY_OPEN | MAY_READ;
2414 	}
2415 
2416 	if (access == FILE_READ_ATTRIBUTES_LE || S_ISBLK(mode) || S_ISCHR(mode))
2417 		oflags |= O_PATH;
2418 
2419 	if (file_present) {
2420 		switch (disposition & FILE_CREATE_MASK_LE) {
2421 		case FILE_OPEN_LE:
2422 		case FILE_CREATE_LE:
2423 			break;
2424 		case FILE_SUPERSEDE_LE:
2425 		case FILE_OVERWRITE_LE:
2426 		case FILE_OVERWRITE_IF_LE:
2427 			oflags |= O_TRUNC;
2428 			break;
2429 		default:
2430 			break;
2431 		}
2432 	} else {
2433 		switch (disposition & FILE_CREATE_MASK_LE) {
2434 		case FILE_SUPERSEDE_LE:
2435 		case FILE_CREATE_LE:
2436 		case FILE_OPEN_IF_LE:
2437 		case FILE_OVERWRITE_IF_LE:
2438 			oflags |= O_CREAT;
2439 			break;
2440 		case FILE_OPEN_LE:
2441 		case FILE_OVERWRITE_LE:
2442 			oflags &= ~O_CREAT;
2443 			break;
2444 		default:
2445 			break;
2446 		}
2447 	}
2448 
2449 	return oflags;
2450 }
2451 
2452 /**
2453  * smb2_tree_disconnect() - handler for smb tree connect request
2454  * @work:	smb work containing request buffer
2455  *
2456  * Return:      0 on success, otherwise error
2457  */
2458 int smb2_tree_disconnect(struct ksmbd_work *work)
2459 {
2460 	struct smb2_tree_disconnect_rsp *rsp;
2461 	struct smb2_tree_disconnect_req *req;
2462 	struct ksmbd_session *sess = work->sess;
2463 	struct ksmbd_tree_connect *tcon = work->tcon;
2464 	int err;
2465 
2466 	ksmbd_debug(SMB, "Received smb2 tree disconnect request\n");
2467 
2468 	WORK_BUFFERS(work, req, rsp);
2469 
2470 	if (!tcon) {
2471 		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2472 
2473 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2474 		err = -ENOENT;
2475 		goto err_out;
2476 	}
2477 
2478 	ksmbd_close_tree_conn_fds(work);
2479 
2480 	down_write(&sess->tree_conns_lock);
2481 	if (tcon->t_state == TREE_DISCONNECTED) {
2482 		up_write(&sess->tree_conns_lock);
2483 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2484 		err = -ENOENT;
2485 		goto err_out;
2486 	}
2487 
2488 	tcon->t_state = TREE_DISCONNECTED;
2489 	up_write(&sess->tree_conns_lock);
2490 
2491 	err = ksmbd_tree_conn_disconnect(sess, tcon);
2492 	if (err) {
2493 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2494 		goto err_out;
2495 	}
2496 
2497 	rsp->StructureSize = cpu_to_le16(4);
2498 	err = ksmbd_iov_pin_rsp(work, rsp,
2499 				sizeof(struct smb2_tree_disconnect_rsp));
2500 	if (err) {
2501 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2502 		goto err_out;
2503 	}
2504 
2505 	return 0;
2506 
2507 err_out:
2508 	smb2_set_err_rsp(work);
2509 	return err;
2510 
2511 }
2512 
2513 /**
2514  * smb2_session_logoff() - handler for session log off request
2515  * @work:	smb work containing request buffer
2516  *
2517  * Return:      0 on success, otherwise error
2518  */
2519 int smb2_session_logoff(struct ksmbd_work *work)
2520 {
2521 	struct ksmbd_conn *conn = work->conn;
2522 	struct ksmbd_session *sess = work->sess;
2523 	struct smb2_logoff_req *req;
2524 	struct smb2_logoff_rsp *rsp;
2525 	u64 sess_id;
2526 	int err;
2527 
2528 	WORK_BUFFERS(work, req, rsp);
2529 
2530 	ksmbd_debug(SMB, "Received smb2 session logoff request\n");
2531 
2532 	ksmbd_conn_lock(conn);
2533 	if (!ksmbd_conn_good(conn)) {
2534 		ksmbd_conn_unlock(conn);
2535 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2536 		smb2_set_err_rsp(work);
2537 		return -ENOENT;
2538 	}
2539 	sess_id = le64_to_cpu(req->hdr.SessionId);
2540 	ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2541 	ksmbd_conn_unlock(conn);
2542 
2543 	ksmbd_close_session_fds(work);
2544 	ksmbd_conn_wait_idle(conn);
2545 
2546 	if (ksmbd_tree_conn_session_logoff(sess)) {
2547 		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2548 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2549 		smb2_set_err_rsp(work);
2550 		return -ENOENT;
2551 	}
2552 
2553 	down_write(&conn->session_lock);
2554 	sess->state = SMB2_SESSION_EXPIRED;
2555 	up_write(&conn->session_lock);
2556 
2557 	ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_SETUP);
2558 
2559 	rsp->StructureSize = cpu_to_le16(4);
2560 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
2561 	if (err) {
2562 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2563 		smb2_set_err_rsp(work);
2564 		return err;
2565 	}
2566 	return 0;
2567 }
2568 
2569 /**
2570  * create_smb2_pipe() - create IPC pipe
2571  * @work:	smb work containing request buffer
2572  *
2573  * Return:      0 on success, otherwise error
2574  */
2575 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2576 {
2577 	struct smb2_create_rsp *rsp;
2578 	struct smb2_create_req *req;
2579 	int id = -1;
2580 	int err;
2581 	char *name;
2582 
2583 	WORK_BUFFERS(work, req, rsp);
2584 
2585 	name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2586 				      1, work->conn->local_nls);
2587 	if (IS_ERR(name)) {
2588 		rsp->hdr.Status = STATUS_NO_MEMORY;
2589 		err = PTR_ERR(name);
2590 		goto out;
2591 	}
2592 
2593 	id = ksmbd_session_rpc_open(work->sess, name);
2594 	if (id < 0) {
2595 		pr_err("Unable to open RPC pipe: %d\n", id);
2596 		err = id;
2597 		goto out;
2598 	}
2599 
2600 	rsp->hdr.Status = STATUS_SUCCESS;
2601 	rsp->StructureSize = cpu_to_le16(89);
2602 	rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2603 	rsp->Flags = 0;
2604 	rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2605 
2606 	rsp->CreationTime = cpu_to_le64(0);
2607 	rsp->LastAccessTime = cpu_to_le64(0);
2608 	rsp->ChangeTime = cpu_to_le64(0);
2609 	rsp->AllocationSize = cpu_to_le64(0);
2610 	rsp->EndofFile = cpu_to_le64(0);
2611 	rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2612 	rsp->Reserved2 = 0;
2613 	rsp->VolatileFileId = id;
2614 	rsp->PersistentFileId = 0;
2615 	rsp->CreateContextsOffset = 0;
2616 	rsp->CreateContextsLength = 0;
2617 
2618 	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
2619 	if (err)
2620 		goto out;
2621 
2622 	kfree(name);
2623 	return 0;
2624 
2625 out:
2626 	switch (err) {
2627 	case -EINVAL:
2628 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2629 		break;
2630 	case -ENOSPC:
2631 	case -ENOMEM:
2632 		rsp->hdr.Status = STATUS_NO_MEMORY;
2633 		break;
2634 	}
2635 
2636 	if (id >= 0)
2637 		ksmbd_session_rpc_close(work->sess, id);
2638 
2639 	if (!IS_ERR(name))
2640 		kfree(name);
2641 
2642 	smb2_set_err_rsp(work);
2643 	return err;
2644 }
2645 
2646 /**
2647  * smb2_set_ea() - handler for setting extended attributes using set
2648  *		info command
2649  * @eabuf:	set info command buffer
2650  * @buf_len:	set info command buffer length
2651  * @path:	dentry path for get ea
2652  * @get_write:	get write access to a mount
2653  *
2654  * Return:	0 on success, otherwise error
2655  */
2656 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2657 		       const struct path *path, bool get_write)
2658 {
2659 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2660 	char *attr_name = NULL, *value;
2661 	int rc = 0;
2662 	unsigned int next = 0;
2663 
2664 	if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
2665 			le16_to_cpu(eabuf->EaValueLength))
2666 		return -EINVAL;
2667 
2668 	attr_name = kmalloc(XATTR_NAME_MAX + 1, KSMBD_DEFAULT_GFP);
2669 	if (!attr_name)
2670 		return -ENOMEM;
2671 
2672 	do {
2673 		if (!eabuf->EaNameLength)
2674 			goto next;
2675 
2676 		ksmbd_debug(SMB,
2677 			    "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2678 			    eabuf->name, eabuf->EaNameLength,
2679 			    le16_to_cpu(eabuf->EaValueLength),
2680 			    le32_to_cpu(eabuf->NextEntryOffset));
2681 
2682 		if (eabuf->EaNameLength >
2683 		    (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2684 			rc = -EINVAL;
2685 			break;
2686 		}
2687 
2688 		memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2689 		memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2690 		       eabuf->EaNameLength);
2691 		attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2692 		value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2693 
2694 		if (!eabuf->EaValueLength) {
2695 			rc = ksmbd_vfs_casexattr_len(idmap,
2696 						     path->dentry,
2697 						     attr_name,
2698 						     XATTR_USER_PREFIX_LEN +
2699 						     eabuf->EaNameLength);
2700 
2701 			/* delete the EA only when it exits */
2702 			if (rc > 0) {
2703 				rc = ksmbd_vfs_remove_xattr(idmap,
2704 							    path,
2705 							    attr_name,
2706 							    get_write);
2707 
2708 				if (rc < 0) {
2709 					ksmbd_debug(SMB,
2710 						    "remove xattr failed(%d)\n",
2711 						    rc);
2712 					break;
2713 				}
2714 			}
2715 
2716 			/* if the EA doesn't exist, just do nothing. */
2717 			rc = 0;
2718 		} else {
2719 			rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
2720 						le16_to_cpu(eabuf->EaValueLength),
2721 						0, get_write);
2722 			if (rc < 0) {
2723 				ksmbd_debug(SMB,
2724 					    "ksmbd_vfs_setxattr is failed(%d)\n",
2725 					    rc);
2726 				break;
2727 			}
2728 		}
2729 
2730 next:
2731 		next = le32_to_cpu(eabuf->NextEntryOffset);
2732 		if (next == 0 || buf_len < next)
2733 			break;
2734 		buf_len -= next;
2735 		eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2736 		if (buf_len < sizeof(struct smb2_ea_info)) {
2737 			rc = -EINVAL;
2738 			break;
2739 		}
2740 
2741 		if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
2742 				le16_to_cpu(eabuf->EaValueLength)) {
2743 			rc = -EINVAL;
2744 			break;
2745 		}
2746 	} while (next != 0);
2747 
2748 	kfree(attr_name);
2749 	return rc;
2750 }
2751 
2752 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2753 					       struct ksmbd_file *fp,
2754 					       char *stream_name, int s_type)
2755 {
2756 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2757 	size_t xattr_stream_size;
2758 	char *xattr_stream_name;
2759 	int rc;
2760 
2761 	rc = ksmbd_vfs_xattr_stream_name(stream_name,
2762 					 &xattr_stream_name,
2763 					 &xattr_stream_size,
2764 					 s_type);
2765 	if (rc)
2766 		return rc;
2767 
2768 	fp->stream.name = xattr_stream_name;
2769 	fp->stream.size = xattr_stream_size;
2770 
2771 	/* Check if there is stream prefix in xattr space */
2772 	rc = ksmbd_vfs_casexattr_len(idmap,
2773 				     path->dentry,
2774 				     xattr_stream_name,
2775 				     xattr_stream_size);
2776 	if (rc >= 0)
2777 		return 0;
2778 
2779 	if (fp->cdoption == FILE_OPEN_LE) {
2780 		ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2781 		return -EBADF;
2782 	}
2783 
2784 	rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false);
2785 	if (rc < 0)
2786 		pr_err("Failed to store XATTR stream name :%d\n", rc);
2787 	return 0;
2788 }
2789 
2790 static int smb2_remove_smb_xattrs(const struct path *path)
2791 {
2792 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2793 	char *name, *xattr_list = NULL;
2794 	ssize_t xattr_list_len;
2795 	int err = 0;
2796 
2797 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2798 	if (xattr_list_len < 0) {
2799 		goto out;
2800 	} else if (!xattr_list_len) {
2801 		ksmbd_debug(SMB, "empty xattr in the file\n");
2802 		goto out;
2803 	}
2804 
2805 	for (name = xattr_list; name - xattr_list < xattr_list_len;
2806 			name += strlen(name) + 1) {
2807 		ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2808 
2809 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2810 		    !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2811 			     STREAM_PREFIX_LEN)) {
2812 			err = ksmbd_vfs_remove_xattr(idmap, path,
2813 						     name, true);
2814 			if (err)
2815 				ksmbd_debug(SMB, "remove xattr failed : %s\n",
2816 					    name);
2817 		}
2818 	}
2819 out:
2820 	kvfree(xattr_list);
2821 	return err;
2822 }
2823 
2824 static int smb2_create_truncate(const struct path *path)
2825 {
2826 	int rc = vfs_truncate(path, 0);
2827 
2828 	if (rc) {
2829 		pr_err("vfs_truncate failed, rc %d\n", rc);
2830 		return rc;
2831 	}
2832 
2833 	rc = smb2_remove_smb_xattrs(path);
2834 	if (rc == -EOPNOTSUPP)
2835 		rc = 0;
2836 	if (rc)
2837 		ksmbd_debug(SMB,
2838 			    "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2839 			    rc);
2840 	return rc;
2841 }
2842 
2843 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2844 			    struct ksmbd_file *fp)
2845 {
2846 	struct xattr_dos_attrib da = {0};
2847 	int rc;
2848 
2849 	if (!test_share_config_flag(tcon->share_conf,
2850 				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2851 		return;
2852 
2853 	da.version = 4;
2854 	da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2855 	da.itime = da.create_time = fp->create_time;
2856 	da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2857 		XATTR_DOSINFO_ITIME;
2858 
2859 	rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, true);
2860 	if (rc)
2861 		ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2862 }
2863 
2864 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2865 			       const struct path *path, struct ksmbd_file *fp)
2866 {
2867 	struct xattr_dos_attrib da;
2868 	int rc;
2869 
2870 	fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2871 
2872 	/* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2873 	if (!test_share_config_flag(tcon->share_conf,
2874 				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2875 		return;
2876 
2877 	rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2878 					    path->dentry, &da);
2879 	if (rc > 0) {
2880 		fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2881 		fp->create_time = da.create_time;
2882 		fp->itime = da.itime;
2883 	}
2884 }
2885 
2886 static int smb2_creat(struct ksmbd_work *work,
2887 		      struct path *path, char *name, int open_flags,
2888 		      umode_t posix_mode, bool is_dir)
2889 {
2890 	struct ksmbd_tree_connect *tcon = work->tcon;
2891 	struct ksmbd_share_config *share = tcon->share_conf;
2892 	umode_t mode;
2893 	int rc;
2894 
2895 	if (!(open_flags & O_CREAT))
2896 		return -EBADF;
2897 
2898 	ksmbd_debug(SMB, "file does not exist, so creating\n");
2899 	if (is_dir == true) {
2900 		ksmbd_debug(SMB, "creating directory\n");
2901 
2902 		mode = share_config_directory_mode(share, posix_mode);
2903 		rc = ksmbd_vfs_mkdir(work, name, mode);
2904 		if (rc)
2905 			return rc;
2906 	} else {
2907 		ksmbd_debug(SMB, "creating regular file\n");
2908 
2909 		mode = share_config_create_mode(share, posix_mode);
2910 		rc = ksmbd_vfs_create(work, name, mode);
2911 		if (rc)
2912 			return rc;
2913 	}
2914 
2915 	rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2916 	if (rc) {
2917 		pr_err("cannot get linux path (%s), err = %d\n",
2918 		       name, rc);
2919 		return rc;
2920 	}
2921 	return 0;
2922 }
2923 
2924 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2925 				 struct smb2_create_req *req,
2926 				 const struct path *path)
2927 {
2928 	struct create_context *context;
2929 	struct create_sd_buf_req *sd_buf;
2930 
2931 	if (!req->CreateContextsOffset)
2932 		return -ENOENT;
2933 
2934 	/* Parse SD BUFFER create contexts */
2935 	context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2936 	if (!context)
2937 		return -ENOENT;
2938 	else if (IS_ERR(context))
2939 		return PTR_ERR(context);
2940 
2941 	ksmbd_debug(SMB,
2942 		    "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2943 	sd_buf = (struct create_sd_buf_req *)context;
2944 	if (le16_to_cpu(context->DataOffset) +
2945 	    le32_to_cpu(context->DataLength) <
2946 	    sizeof(struct create_sd_buf_req))
2947 		return -EINVAL;
2948 	return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2949 			    le32_to_cpu(sd_buf->ccontext.DataLength), true, false);
2950 }
2951 
2952 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2953 			     struct mnt_idmap *idmap,
2954 			     struct inode *inode)
2955 {
2956 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2957 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2958 
2959 	fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2960 	fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2961 	fattr->cf_mode = inode->i_mode;
2962 	fattr->cf_acls = NULL;
2963 	fattr->cf_dacls = NULL;
2964 
2965 	if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2966 		fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2967 		if (S_ISDIR(inode->i_mode))
2968 			fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2969 	}
2970 }
2971 
2972 enum {
2973 	DURABLE_RECONN_V2 = 1,
2974 	DURABLE_RECONN,
2975 	DURABLE_REQ_V2,
2976 	DURABLE_REQ,
2977 };
2978 
2979 struct durable_info {
2980 	struct ksmbd_file *fp;
2981 	unsigned short int type;
2982 	bool persistent;
2983 	bool reconnected;
2984 	bool app_instance_id;
2985 	unsigned int timeout;
2986 	char *CreateGuid;
2987 	char AppInstanceId[SMB2_CREATE_GUID_SIZE];
2988 };
2989 
2990 static int parse_durable_handle_context(struct ksmbd_work *work,
2991 					struct smb2_create_req *req,
2992 					struct lease_ctx_info *lc,
2993 					struct durable_info *dh_info)
2994 {
2995 	struct ksmbd_conn *conn = work->conn;
2996 	struct create_context *context;
2997 	int dh_idx, err = 0;
2998 	u64 persistent_id = 0;
2999 	int req_op_level;
3000 	static const char * const durable_arr[] = {"DH2C", "DHnC", "DH2Q", "DHnQ"};
3001 
3002 	req_op_level = req->RequestedOplockLevel;
3003 	for (dh_idx = DURABLE_RECONN_V2; dh_idx <= ARRAY_SIZE(durable_arr);
3004 	     dh_idx++) {
3005 		context = smb2_find_context_vals(req, durable_arr[dh_idx - 1], 4);
3006 		if (IS_ERR(context)) {
3007 			err = PTR_ERR(context);
3008 			goto out;
3009 		}
3010 		if (!context)
3011 			continue;
3012 
3013 		switch (dh_idx) {
3014 		case DURABLE_RECONN_V2:
3015 		{
3016 			struct create_durable_handle_reconnect_v2 *recon_v2;
3017 
3018 			if (dh_info->type == DURABLE_RECONN ||
3019 			    dh_info->type == DURABLE_REQ_V2) {
3020 				err = -EINVAL;
3021 				goto out;
3022 			}
3023 
3024 			if (le32_to_cpu(context->DataLength) <
3025 			    sizeof(recon_v2->dcontext)) {
3026 				err = -EINVAL;
3027 				goto out;
3028 			}
3029 
3030 			recon_v2 = (struct create_durable_handle_reconnect_v2 *)context;
3031 			persistent_id = recon_v2->dcontext.Fid.PersistentFileId;
3032 			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
3033 			if (!dh_info->fp) {
3034 				ksmbd_debug(SMB, "Failed to get durable handle state\n");
3035 				err = -EBADF;
3036 				goto out;
3037 			}
3038 
3039 			if (dh_info->fp->durable_volatile_id !=
3040 			    recon_v2->dcontext.Fid.VolatileFileId) {
3041 				err = -EBADF;
3042 				ksmbd_put_durable_fd(dh_info->fp);
3043 				goto out;
3044 			}
3045 
3046 			if (memcmp(dh_info->fp->create_guid, recon_v2->dcontext.CreateGuid,
3047 				   SMB2_CREATE_GUID_SIZE)) {
3048 				err = -EBADF;
3049 				ksmbd_put_durable_fd(dh_info->fp);
3050 				goto out;
3051 			}
3052 
3053 			dh_info->type = dh_idx;
3054 			dh_info->reconnected = true;
3055 			ksmbd_debug(SMB,
3056 				"reconnect v2 Persistent-id from reconnect = %llu\n",
3057 					persistent_id);
3058 			break;
3059 		}
3060 		case DURABLE_RECONN:
3061 		{
3062 			create_durable_reconn_t *recon;
3063 
3064 			if (dh_info->type == DURABLE_RECONN_V2 ||
3065 			    dh_info->type == DURABLE_REQ_V2) {
3066 				err = -EINVAL;
3067 				goto out;
3068 			}
3069 
3070 			if (le32_to_cpu(context->DataLength) <
3071 			    sizeof(recon->Data)) {
3072 				err = -EINVAL;
3073 				goto out;
3074 			}
3075 
3076 			recon = (create_durable_reconn_t *)context;
3077 			persistent_id = recon->Data.Fid.PersistentFileId;
3078 			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
3079 			if (!dh_info->fp) {
3080 				ksmbd_debug(SMB, "Failed to get durable handle state\n");
3081 				err = -EBADF;
3082 				goto out;
3083 			}
3084 
3085 			if (dh_info->fp->durable_volatile_id !=
3086 			    recon->Data.Fid.VolatileFileId) {
3087 				err = -EBADF;
3088 				ksmbd_put_durable_fd(dh_info->fp);
3089 				goto out;
3090 			}
3091 
3092 			dh_info->type = dh_idx;
3093 			dh_info->reconnected = true;
3094 			ksmbd_debug(SMB, "reconnect Persistent-id from reconnect = %llu\n",
3095 				    persistent_id);
3096 			break;
3097 		}
3098 		case DURABLE_REQ_V2:
3099 		{
3100 			struct create_durable_req_v2 *durable_v2_blob;
3101 
3102 			if (dh_info->type == DURABLE_RECONN ||
3103 			    dh_info->type == DURABLE_RECONN_V2) {
3104 				err = -EINVAL;
3105 				goto out;
3106 			}
3107 
3108 			if (le32_to_cpu(context->DataLength) <
3109 			    sizeof(durable_v2_blob->dcontext)) {
3110 				err = -EINVAL;
3111 				goto out;
3112 			}
3113 
3114 			durable_v2_blob =
3115 				(struct create_durable_req_v2 *)context;
3116 			ksmbd_debug(SMB, "Request for durable v2 open\n");
3117 			dh_info->fp = ksmbd_lookup_fd_cguid(durable_v2_blob->dcontext.CreateGuid);
3118 			if (dh_info->fp) {
3119 				if (!memcmp(conn->ClientGUID, dh_info->fp->client_guid,
3120 					    SMB2_CLIENT_GUID_SIZE)) {
3121 					if (!(req->hdr.Flags & SMB2_FLAGS_REPLAY_OPERATION)) {
3122 						err = -ENOEXEC;
3123 						ksmbd_put_durable_fd(dh_info->fp);
3124 						goto out;
3125 					}
3126 
3127 					if (dh_info->fp->conn) {
3128 						ksmbd_put_durable_fd(dh_info->fp);
3129 						err = -EBADF;
3130 						goto out;
3131 					}
3132 					dh_info->reconnected = true;
3133 					goto out;
3134 				}
3135 				ksmbd_put_durable_fd(dh_info->fp);
3136 				dh_info->fp = NULL;
3137 			}
3138 
3139 			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
3140 			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
3141 				dh_info->CreateGuid =
3142 					durable_v2_blob->dcontext.CreateGuid;
3143 				dh_info->persistent =
3144 					le32_to_cpu(durable_v2_blob->dcontext.Flags);
3145 				dh_info->timeout =
3146 					le32_to_cpu(durable_v2_blob->dcontext.Timeout);
3147 				dh_info->type = dh_idx;
3148 			}
3149 			break;
3150 		}
3151 		case DURABLE_REQ:
3152 			if (dh_info->type == DURABLE_RECONN)
3153 				goto out;
3154 			if (dh_info->type == DURABLE_RECONN_V2 ||
3155 			    dh_info->type == DURABLE_REQ_V2) {
3156 				err = -EINVAL;
3157 				goto out;
3158 			}
3159 
3160 			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
3161 			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
3162 				ksmbd_debug(SMB, "Request for durable open\n");
3163 				dh_info->type = dh_idx;
3164 			}
3165 		}
3166 	}
3167 
3168 out:
3169 	return err;
3170 }
3171 
3172 static int parse_app_instance_id(struct smb2_create_req *req,
3173 				 struct durable_info *dh_info)
3174 {
3175 	struct create_context *context;
3176 	char *data;
3177 
3178 	context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_ID,
3179 					 SMB2_CREATE_GUID_SIZE);
3180 	if (IS_ERR(context))
3181 		return PTR_ERR(context);
3182 	if (!context)
3183 		return 0;
3184 
3185 	if (le32_to_cpu(context->DataLength) < 20)
3186 		return -EINVAL;
3187 
3188 	data = (char *)context + le16_to_cpu(context->DataOffset);
3189 	if (data[0] != 20 || data[1])
3190 		return -EINVAL;
3191 
3192 	memcpy(dh_info->AppInstanceId, data + 4, SMB2_CREATE_GUID_SIZE);
3193 	dh_info->app_instance_id = true;
3194 	return 0;
3195 }
3196 
3197 /**
3198  * smb2_open() - handler for smb file open request
3199  * @work:	smb work containing request buffer
3200  *
3201  * Return:      0 on success, otherwise error
3202  */
3203 int smb2_open(struct ksmbd_work *work)
3204 {
3205 	struct ksmbd_conn *conn = work->conn;
3206 	struct ksmbd_session *sess = work->sess;
3207 	struct ksmbd_tree_connect *tcon = work->tcon;
3208 	struct smb2_create_req *req;
3209 	struct smb2_create_rsp *rsp;
3210 	struct path path;
3211 	struct ksmbd_share_config *share = tcon->share_conf;
3212 	struct ksmbd_file *fp = NULL;
3213 	struct file *filp = NULL;
3214 	struct mnt_idmap *idmap = NULL;
3215 	struct kstat stat;
3216 	struct create_context *context;
3217 	struct lease_ctx_info *lc = NULL;
3218 	struct create_ea_buf_req *ea_buf = NULL;
3219 	struct oplock_info *opinfo;
3220 	struct durable_info dh_info = {0};
3221 	__le32 *next_ptr = NULL;
3222 	int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
3223 	int rc = 0;
3224 	int contxt_cnt = 0, query_disk_id = 0;
3225 	bool maximal_access_ctxt = false, posix_ctxt = false;
3226 	int s_type = 0;
3227 	int next_off = 0;
3228 	char *name = NULL;
3229 	char *stream_name = NULL;
3230 	bool file_present = false, created = false, already_permitted = false;
3231 	int share_ret, need_truncate = 0;
3232 	u64 time, alloc_size = 0;
3233 	umode_t posix_mode = 0;
3234 	__le32 daccess, maximal_access = 0;
3235 	int iov_len = 0;
3236 
3237 	ksmbd_debug(SMB, "Received smb2 create request\n");
3238 
3239 	WORK_BUFFERS(work, req, rsp);
3240 
3241 	if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
3242 	    (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
3243 		ksmbd_debug(SMB, "invalid flag in chained command\n");
3244 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3245 		smb2_set_err_rsp(work);
3246 		return -EINVAL;
3247 	}
3248 
3249 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
3250 		ksmbd_debug(SMB, "IPC pipe create request\n");
3251 		return create_smb2_pipe(work);
3252 	}
3253 
3254 	if (req->CreateContextsOffset && tcon->posix_extensions) {
3255 		context = smb2_find_context_vals(req, SMB2_CREATE_TAG_POSIX, 16);
3256 		if (IS_ERR(context)) {
3257 			rc = PTR_ERR(context);
3258 			goto err_out2;
3259 		} else if (context) {
3260 			struct create_posix *posix = (struct create_posix *)context;
3261 
3262 			if (le16_to_cpu(context->DataOffset) +
3263 				le32_to_cpu(context->DataLength) <
3264 			    sizeof(struct create_posix) - 4) {
3265 				rc = -EINVAL;
3266 				goto err_out2;
3267 			}
3268 			ksmbd_debug(SMB, "get posix context\n");
3269 
3270 			posix_mode = le32_to_cpu(posix->Mode);
3271 			posix_ctxt = true;
3272 		}
3273 	}
3274 
3275 	if (req->NameLength) {
3276 		name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset),
3277 				     le16_to_cpu(req->NameLength),
3278 				     work->conn->local_nls);
3279 		if (IS_ERR(name)) {
3280 			rc = PTR_ERR(name);
3281 			name = NULL;
3282 			goto err_out2;
3283 		}
3284 
3285 		ksmbd_debug(SMB, "converted name = %s\n", name);
3286 
3287 		if (posix_ctxt == false) {
3288 			if (strchr(name, ':')) {
3289 				if (!test_share_config_flag(work->tcon->share_conf,
3290 							KSMBD_SHARE_FLAG_STREAMS)) {
3291 					rc = -EBADF;
3292 					goto err_out2;
3293 				}
3294 				rc = parse_stream_name(name, &stream_name, &s_type);
3295 				if (rc < 0)
3296 					goto err_out2;
3297 			}
3298 
3299 			rc = ksmbd_validate_filename(name);
3300 			if (rc < 0)
3301 				goto err_out2;
3302 		}
3303 
3304 		if (ksmbd_share_veto_filename(share, name)) {
3305 			rc = -ENOENT;
3306 			ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
3307 				    name);
3308 			goto err_out2;
3309 		}
3310 	} else {
3311 		name = kstrdup("", KSMBD_DEFAULT_GFP);
3312 		if (!name) {
3313 			rc = -ENOMEM;
3314 			goto err_out2;
3315 		}
3316 	}
3317 
3318 	req_op_level = req->RequestedOplockLevel;
3319 
3320 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
3321 	    req->CreateContextsOffset) {
3322 		lc = parse_lease_state(req);
3323 		if (IS_ERR(lc)) {
3324 			rc = PTR_ERR(lc);
3325 			lc = NULL;
3326 			goto err_out2;
3327 		}
3328 		if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
3329 			kfree(lc);
3330 			lc = NULL;
3331 			if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
3332 				req_op_level = SMB2_OPLOCK_LEVEL_NONE;
3333 		}
3334 		rc = parse_durable_handle_context(work, req, lc, &dh_info);
3335 		if (rc) {
3336 			ksmbd_debug(SMB, "error parsing durable handle context\n");
3337 			goto err_out2;
3338 		}
3339 		rc = parse_app_instance_id(req, &dh_info);
3340 		if (rc)
3341 			goto err_out2;
3342 
3343 		if (dh_info.reconnected == true) {
3344 			rc = smb2_check_durable_oplock(conn, share, dh_info.fp,
3345 					lc, sess->user, name);
3346 			if (rc)
3347 				goto err_out2;
3348 
3349 			rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
3350 			if (rc)
3351 				goto err_out2;
3352 
3353 			fp = dh_info.fp;
3354 
3355 			if (ksmbd_override_fsids(work)) {
3356 				rc = -ENOMEM;
3357 				goto err_out2;
3358 			}
3359 
3360 			file_info = FILE_OPENED;
3361 
3362 			rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
3363 			if (rc)
3364 				goto err_out2;
3365 
3366 			goto reconnected_fp;
3367 		}
3368 
3369 		if (dh_info.type == DURABLE_REQ_V2 && dh_info.app_instance_id)
3370 			ksmbd_close_fd_app_instance_id(dh_info.AppInstanceId);
3371 	} else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3372 		lc = parse_lease_state(req);
3373 		if (IS_ERR(lc)) {
3374 			rc = PTR_ERR(lc);
3375 			lc = NULL;
3376 			goto err_out2;
3377 		}
3378 		if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
3379 			kfree(lc);
3380 			lc = NULL;
3381 			req_op_level = SMB2_OPLOCK_LEVEL_NONE;
3382 		}
3383 	}
3384 
3385 	if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
3386 		pr_err("Invalid impersonationlevel : 0x%x\n",
3387 		       le32_to_cpu(req->ImpersonationLevel));
3388 		rc = -EIO;
3389 		rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
3390 		goto err_out2;
3391 	}
3392 
3393 	if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
3394 		pr_err("Invalid create options : 0x%x\n",
3395 		       le32_to_cpu(req->CreateOptions));
3396 		rc = -EINVAL;
3397 		goto err_out2;
3398 	} else {
3399 		if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
3400 		    req->CreateOptions & FILE_RANDOM_ACCESS_LE)
3401 			req->CreateOptions &= ~FILE_SEQUENTIAL_ONLY_LE;
3402 
3403 		if (req->CreateOptions &
3404 		    (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
3405 		     FILE_RESERVE_OPFILTER_LE)) {
3406 			rc = -EOPNOTSUPP;
3407 			goto err_out2;
3408 		}
3409 
3410 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3411 			if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
3412 				rc = -EINVAL;
3413 				goto err_out2;
3414 			} else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
3415 				req->CreateOptions &= ~FILE_NO_COMPRESSION_LE;
3416 			}
3417 		}
3418 	}
3419 
3420 	if (le32_to_cpu(req->CreateDisposition) >
3421 	    le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
3422 		pr_err("Invalid create disposition : 0x%x\n",
3423 		       le32_to_cpu(req->CreateDisposition));
3424 		rc = -EINVAL;
3425 		goto err_out2;
3426 	}
3427 
3428 	if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
3429 		pr_err("Invalid desired access : 0x%x\n",
3430 		       le32_to_cpu(req->DesiredAccess));
3431 		rc = -EACCES;
3432 		goto err_out2;
3433 	}
3434 
3435 	if (req->DesiredAccess == FILE_SYNCHRONIZE_LE &&
3436 	    req->CreateDisposition == FILE_OPEN_IF_LE &&
3437 	    !req->FileAttributes) {
3438 		rc = -EACCES;
3439 		goto err_out2;
3440 	}
3441 
3442 	if (req->FileAttributes &&
3443 	    (req->FileAttributes & ~cpu_to_le32(SMB2_CREATE_FILE_ATTRIBUTE_MASK))) {
3444 		pr_err("Invalid file attribute : 0x%x\n",
3445 		       le32_to_cpu(req->FileAttributes));
3446 		rc = -EINVAL;
3447 		goto err_out2;
3448 	}
3449 
3450 	if (req->CreateContextsOffset) {
3451 		/* Parse non-durable handle create contexts */
3452 		context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
3453 		if (IS_ERR(context)) {
3454 			rc = PTR_ERR(context);
3455 			goto err_out2;
3456 		} else if (context) {
3457 			ea_buf = (struct create_ea_buf_req *)context;
3458 			if (le16_to_cpu(context->DataOffset) +
3459 			    le32_to_cpu(context->DataLength) <
3460 			    sizeof(struct create_ea_buf_req)) {
3461 				rc = -EINVAL;
3462 				goto err_out2;
3463 			}
3464 			if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
3465 				rsp->hdr.Status = STATUS_ACCESS_DENIED;
3466 				rc = -EACCES;
3467 				goto err_out2;
3468 			}
3469 		}
3470 
3471 		context = smb2_find_context_vals(req,
3472 						 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
3473 		if (IS_ERR(context)) {
3474 			rc = PTR_ERR(context);
3475 			goto err_out2;
3476 		} else if (context) {
3477 			ksmbd_debug(SMB,
3478 				    "get query maximal access context\n");
3479 			maximal_access_ctxt = 1;
3480 		}
3481 
3482 		context = smb2_find_context_vals(req,
3483 						 SMB2_CREATE_TIMEWARP_REQUEST, 4);
3484 		if (IS_ERR(context)) {
3485 			rc = PTR_ERR(context);
3486 			goto err_out2;
3487 		} else if (context) {
3488 			ksmbd_debug(SMB, "get timewarp context\n");
3489 			rc = -EBADF;
3490 			goto err_out2;
3491 		}
3492 	}
3493 
3494 	if (ksmbd_override_fsids(work)) {
3495 		rc = -ENOMEM;
3496 		goto err_out2;
3497 	}
3498 
3499 	rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
3500 				 &path, 1);
3501 
3502 	/*
3503 	 * A durable handle opened with delete-on-close is preserved across a
3504 	 * disconnect so it can be reclaimed by a durable reconnect.  When a new
3505 	 * delete-on-close open for the same name arrives instead, the
3506 	 * disconnected handle must give way: close it so its delete-on-close
3507 	 * removes the file, then re-resolve so this open can create a fresh one.
3508 	 */
3509 	if (!rc && (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) &&
3510 	    (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
3511 	     req->CreateDisposition == FILE_OPEN_IF_LE) &&
3512 	    ksmbd_close_disconnected_durable_delete_on_close(path.dentry)) {
3513 		path_put(&path);
3514 		rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
3515 					 &path, 1);
3516 	}
3517 
3518 	if (!rc) {
3519 		file_present = true;
3520 
3521 		if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
3522 			/*
3523 			 * If file exists with under flags, return access
3524 			 * denied error.
3525 			 */
3526 			if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
3527 			    req->CreateDisposition == FILE_OPEN_IF_LE) {
3528 				rc = -EACCES;
3529 				goto err_out;
3530 			}
3531 
3532 			if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3533 				ksmbd_debug(SMB,
3534 					    "User does not have write permission\n");
3535 				rc = -EACCES;
3536 				goto err_out;
3537 			}
3538 		} else if (d_is_symlink(path.dentry)) {
3539 			rc = -EACCES;
3540 			goto err_out;
3541 		}
3542 
3543 		idmap = mnt_idmap(path.mnt);
3544 	} else {
3545 		if (rc != -ENOENT)
3546 			goto err_out;
3547 		ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
3548 			    name, rc);
3549 		rc = 0;
3550 	}
3551 
3552 	/*
3553 	 * An explicit ::$DATA suffix names the unnamed data stream and is
3554 	 * canonicalized to a NULL stream name (base file), but the request
3555 	 * still has to be validated against the data-stream type, e.g. opening
3556 	 * <dir>::$DATA with FILE_DIRECTORY_FILE must fail with
3557 	 * STATUS_NOT_A_DIRECTORY.
3558 	 */
3559 	if (stream_name || s_type == DATA_STREAM) {
3560 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3561 			if (s_type == DATA_STREAM) {
3562 				rc = -EIO;
3563 				rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3564 			}
3565 		} else {
3566 			if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
3567 			    s_type == DATA_STREAM) {
3568 				rc = -EIO;
3569 				rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3570 			}
3571 		}
3572 
3573 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
3574 		    req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
3575 			rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3576 			rc = -EIO;
3577 		}
3578 
3579 		if (rc < 0)
3580 			goto err_out;
3581 	}
3582 
3583 	if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
3584 	    S_ISDIR(d_inode(path.dentry)->i_mode) &&
3585 	    !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3586 		ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
3587 			    name, req->CreateOptions);
3588 		rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3589 		rc = -EIO;
3590 		goto err_out;
3591 	}
3592 
3593 	if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
3594 	    !(req->CreateDisposition == FILE_CREATE_LE) &&
3595 	    !S_ISDIR(d_inode(path.dentry)->i_mode)) {
3596 		rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3597 		rc = -EIO;
3598 		goto err_out;
3599 	}
3600 
3601 	if (!stream_name && file_present &&
3602 	    req->CreateDisposition == FILE_CREATE_LE) {
3603 		rc = -EEXIST;
3604 		goto err_out;
3605 	}
3606 
3607 	daccess = smb_map_generic_desired_access(req->DesiredAccess);
3608 
3609 	if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3610 		rc = smb_check_perm_dacl(conn, &path, &daccess,
3611 					 sess->user->uid);
3612 		if (rc)
3613 			goto err_out;
3614 	}
3615 
3616 	if (daccess & FILE_MAXIMAL_ACCESS_LE) {
3617 		if (!file_present) {
3618 			daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
3619 		} else {
3620 			ksmbd_vfs_query_maximal_access(idmap,
3621 							    path.dentry,
3622 							    &daccess);
3623 			already_permitted = true;
3624 		}
3625 		maximal_access = daccess;
3626 	}
3627 
3628 	open_flags = smb2_create_open_flags(file_present, daccess,
3629 					    req->CreateDisposition,
3630 					    &may_flags,
3631 					    req->CreateOptions,
3632 					    file_present ? d_inode(path.dentry)->i_mode : 0);
3633 
3634 	if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3635 		if (open_flags & (O_CREAT | O_TRUNC)) {
3636 			ksmbd_debug(SMB,
3637 				    "User does not have write permission\n");
3638 			rc = -EACCES;
3639 			goto err_out;
3640 		}
3641 	}
3642 
3643 	/*create file if not present */
3644 	if (!file_present) {
3645 		rc = smb2_creat(work, &path, name, open_flags,
3646 				posix_mode,
3647 				req->CreateOptions & FILE_DIRECTORY_FILE_LE);
3648 		if (rc) {
3649 			if (rc == -ENOENT) {
3650 				rc = -EIO;
3651 				rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3652 			}
3653 			goto err_out;
3654 		}
3655 
3656 		created = true;
3657 		idmap = mnt_idmap(path.mnt);
3658 		if (ea_buf) {
3659 			if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3660 			    sizeof(struct smb2_ea_info)) {
3661 				rc = -EINVAL;
3662 				goto err_out;
3663 			}
3664 
3665 			rc = smb2_set_ea(&ea_buf->ea,
3666 					 le32_to_cpu(ea_buf->ccontext.DataLength),
3667 					 &path, false);
3668 			if (rc == -EOPNOTSUPP)
3669 				rc = 0;
3670 			else if (rc)
3671 				goto err_out;
3672 		}
3673 	} else if (!already_permitted) {
3674 		/* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3675 		 * because execute(search) permission on a parent directory,
3676 		 * is already granted.
3677 		 */
3678 		if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3679 			rc = inode_permission(idmap,
3680 					      d_inode(path.dentry),
3681 					      may_flags);
3682 			if (rc)
3683 				goto err_out;
3684 
3685 			if ((daccess & FILE_DELETE_LE) ||
3686 			    (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3687 				rc = inode_permission(idmap,
3688 						      d_inode(path.dentry->d_parent),
3689 						      MAY_EXEC | MAY_WRITE);
3690 				if (rc)
3691 					goto err_out;
3692 			}
3693 		}
3694 	}
3695 
3696 	rc = ksmbd_query_inode_status(path.dentry->d_parent);
3697 	if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3698 		rc = -EBUSY;
3699 		goto err_out;
3700 	}
3701 
3702 	rc = 0;
3703 	filp = dentry_open(&path, open_flags, current_cred());
3704 	if (IS_ERR(filp)) {
3705 		rc = PTR_ERR(filp);
3706 		pr_err("dentry open for dir failed, rc %d\n", rc);
3707 		goto err_out;
3708 	}
3709 
3710 	if (file_present) {
3711 		if (!(open_flags & O_TRUNC))
3712 			file_info = FILE_OPENED;
3713 		else
3714 			file_info = FILE_OVERWRITTEN;
3715 
3716 		if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3717 		    FILE_SUPERSEDE_LE)
3718 			file_info = FILE_SUPERSEDED;
3719 	} else if (open_flags & O_CREAT) {
3720 		file_info = FILE_CREATED;
3721 	}
3722 
3723 	ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3724 
3725 	/* Obtain Volatile-ID */
3726 	fp = ksmbd_open_fd(work, filp);
3727 	if (IS_ERR(fp)) {
3728 		fput(filp);
3729 		rc = PTR_ERR(fp);
3730 		fp = NULL;
3731 		goto err_out;
3732 	}
3733 
3734 	/* Get Persistent-ID */
3735 	ksmbd_open_durable_fd(fp);
3736 	if (!has_file_id(fp->persistent_id)) {
3737 		rc = -ENOMEM;
3738 		goto err_out;
3739 	}
3740 
3741 	fp->cdoption = req->CreateDisposition;
3742 	fp->daccess = daccess;
3743 	fp->saccess = req->ShareAccess;
3744 	fp->coption = req->CreateOptions;
3745 
3746 	/* Set default windows and posix acls if creating new file */
3747 	if (created) {
3748 		int posix_acl_rc;
3749 		struct inode *inode = d_inode(path.dentry);
3750 
3751 		posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3752 							   &path,
3753 							   d_inode(path.dentry->d_parent));
3754 		if (posix_acl_rc)
3755 			ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3756 
3757 		rc = smb2_create_sd_buffer(work, req, &path);
3758 		if (rc && rc != -ENOENT)
3759 			goto err_out;
3760 
3761 		if (rc == -ENOENT) {
3762 			if (test_share_config_flag(work->tcon->share_conf,
3763 						   KSMBD_SHARE_FLAG_ACL_XATTR)) {
3764 				rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3765 						      sess->user->gid);
3766 			}
3767 			if (rc) {
3768 				if (posix_acl_rc)
3769 					ksmbd_vfs_set_init_posix_acl(idmap,
3770 								     &path);
3771 
3772 				if (test_share_config_flag(work->tcon->share_conf,
3773 							   KSMBD_SHARE_FLAG_ACL_XATTR)) {
3774 					struct smb_fattr fattr;
3775 					struct smb_ntsd *pntsd;
3776 					int pntsd_size;
3777 					size_t scratch_len;
3778 
3779 					ksmbd_acls_fattr(&fattr, idmap, inode);
3780 					scratch_len = smb_acl_sec_desc_scratch_len(&fattr,
3781 							NULL, 0,
3782 							OWNER_SECINFO | GROUP_SECINFO |
3783 							DACL_SECINFO);
3784 					if (!scratch_len || scratch_len == SIZE_MAX) {
3785 						rc = -EFBIG;
3786 						posix_acl_release(fattr.cf_acls);
3787 						posix_acl_release(fattr.cf_dacls);
3788 						goto err_out;
3789 					}
3790 
3791 					pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
3792 					if (!pntsd) {
3793 						rc = -ENOMEM;
3794 						posix_acl_release(fattr.cf_acls);
3795 						posix_acl_release(fattr.cf_dacls);
3796 						goto err_out;
3797 					}
3798 
3799 					rc = build_sec_desc(idmap,
3800 							    pntsd, NULL, 0,
3801 							    OWNER_SECINFO |
3802 							    GROUP_SECINFO |
3803 							    DACL_SECINFO,
3804 							    &pntsd_size, &fattr);
3805 					posix_acl_release(fattr.cf_acls);
3806 					posix_acl_release(fattr.cf_dacls);
3807 					if (rc) {
3808 						kvfree(pntsd);
3809 						goto err_out;
3810 					}
3811 
3812 					rc = ksmbd_vfs_set_sd_xattr(conn,
3813 								    idmap,
3814 								    &path,
3815 								    pntsd,
3816 								    pntsd_size,
3817 								    false);
3818 					kvfree(pntsd);
3819 					if (rc)
3820 						pr_err("failed to store ntacl in xattr : %d\n",
3821 						       rc);
3822 				}
3823 			}
3824 		}
3825 		rc = 0;
3826 	}
3827 
3828 	if (stream_name) {
3829 		rc = smb2_set_stream_name_xattr(&path,
3830 						fp,
3831 						stream_name,
3832 						s_type);
3833 		if (rc)
3834 			goto err_out;
3835 		file_info = FILE_CREATED;
3836 	}
3837 
3838 	fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3839 			FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3840 
3841 	fp->is_posix_ctxt = posix_ctxt;
3842 
3843 	/* fp should be searchable through ksmbd_inode.m_fp_list
3844 	 * after daccess, saccess, attrib_only, and stream are
3845 	 * initialized.
3846 	 */
3847 	down_write(&fp->f_ci->m_lock);
3848 	list_add(&fp->node, &fp->f_ci->m_fp_list);
3849 	up_write(&fp->f_ci->m_lock);
3850 
3851 	/* Check delete pending among previous fp before oplock break */
3852 	if (ksmbd_inode_pending_delete(fp)) {
3853 		rc = -EBUSY;
3854 		goto err_out;
3855 	}
3856 
3857 	if (!stream_name && daccess & FILE_DELETE_LE &&
3858 	    ksmbd_has_stream_without_delete_share(fp)) {
3859 		rc = -EPERM;
3860 		goto err_out;
3861 	}
3862 
3863 	if (file_present || created)
3864 		path_put(&path);
3865 
3866 	if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3867 	    !fp->attrib_only && !stream_name) {
3868 		smb_break_all_oplock(work, fp);
3869 		need_truncate = 1;
3870 	}
3871 
3872 	share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3873 	if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3874 	    (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3875 	     !(conn->vals->req_capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3876 		if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3877 			rc = share_ret;
3878 			goto err_out1;
3879 		}
3880 	} else {
3881 		if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && lc) {
3882 			if (S_ISDIR(file_inode(filp)->i_mode)) {
3883 				lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
3884 				lc->is_dir = true;
3885 			}
3886 
3887 			/*
3888 			 * Compare parent lease using parent key. If there is no
3889 			 * a lease that has same parent key, Send lease break
3890 			 * notification.
3891 			 */
3892 			smb_send_parent_lease_break_noti(fp, lc);
3893 
3894 			req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3895 			ksmbd_debug(SMB,
3896 				    "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3897 				    name, req_op_level, lc->req_state);
3898 			rc = find_same_lease_key(conn, fp->f_ci, lc);
3899 			if (rc)
3900 				goto err_out1;
3901 		} else if (open_flags == O_RDONLY &&
3902 			   (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3903 			    req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3904 			req_op_level = SMB2_OPLOCK_LEVEL_II;
3905 
3906 		rc = smb_grant_oplock(work, req_op_level,
3907 				      fp->persistent_id, fp,
3908 				      le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3909 				      lc, share_ret);
3910 		if (rc < 0)
3911 			goto err_out1;
3912 	}
3913 
3914 	if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
3915 		smb_break_all_levII_oplock_for_delete(work, fp);
3916 		ksmbd_fd_set_delete_on_close(fp, file_info);
3917 	}
3918 
3919 	if (need_truncate) {
3920 		rc = smb2_create_truncate(&fp->filp->f_path);
3921 		if (rc)
3922 			goto err_out1;
3923 	}
3924 
3925 	if (req->CreateContextsOffset) {
3926 		struct create_alloc_size_req *az_req;
3927 
3928 		az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3929 					SMB2_CREATE_ALLOCATION_SIZE, 4);
3930 		if (IS_ERR(az_req)) {
3931 			rc = PTR_ERR(az_req);
3932 			goto err_out1;
3933 		} else if (az_req) {
3934 			int err;
3935 
3936 			if (le16_to_cpu(az_req->ccontext.DataOffset) +
3937 			    le32_to_cpu(az_req->ccontext.DataLength) <
3938 			    sizeof(struct create_alloc_size_req)) {
3939 				rc = -EINVAL;
3940 				goto err_out1;
3941 			}
3942 			alloc_size = le64_to_cpu(az_req->AllocationSize);
3943 			ksmbd_debug(SMB,
3944 				    "request smb2 create allocate size : %llu\n",
3945 				    alloc_size);
3946 			smb_break_all_levII_oplock(work, fp, 1);
3947 			err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3948 					    alloc_size);
3949 			if (err < 0)
3950 				ksmbd_debug(SMB,
3951 					    "vfs_fallocate is failed : %d\n",
3952 					    err);
3953 		}
3954 
3955 		context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3956 		if (IS_ERR(context)) {
3957 			rc = PTR_ERR(context);
3958 			goto err_out1;
3959 		} else if (context) {
3960 			ksmbd_debug(SMB, "get query on disk id context\n");
3961 			query_disk_id = 1;
3962 		}
3963 
3964 		if (conn->is_aapl == false) {
3965 			context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
3966 			if (IS_ERR(context)) {
3967 				rc = PTR_ERR(context);
3968 				goto err_out1;
3969 			} else if (context)
3970 				conn->is_aapl = true;
3971 		}
3972 	}
3973 
3974 	rc = ksmbd_vfs_getattr(&path, &stat);
3975 	if (rc)
3976 		goto err_out1;
3977 
3978 	if (stat.result_mask & STATX_BTIME)
3979 		fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3980 	else
3981 		fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3982 	fp->change_time = ksmbd_UnixTimeToNT(stat.ctime);
3983 	fp->allocation_size = S_ISDIR(stat.mode) ? 0 :
3984 		(alloc_size ?: stat.blocks << 9);
3985 	if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3986 		fp->f_ci->m_fattr =
3987 			cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3988 
3989 	if (!created)
3990 		smb2_update_xattrs(tcon, &path, fp);
3991 
3992 	ksmbd_vfs_update_compressed_fattr(path.dentry, &fp->f_ci->m_fattr);
3993 
3994 	if (created)
3995 		smb2_new_xattrs(tcon, &path, fp);
3996 
3997 	memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3998 
3999 	if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
4000 		if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent &&
4001 		    test_share_config_flag(work->tcon->share_conf,
4002 					   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
4003 			fp->is_persistent = true;
4004 		else
4005 			fp->is_durable = true;
4006 
4007 		if (dh_info.type == DURABLE_REQ_V2) {
4008 			memcpy(fp->create_guid, dh_info.CreateGuid,
4009 					SMB2_CREATE_GUID_SIZE);
4010 			if (dh_info.app_instance_id)
4011 				memcpy(fp->app_instance_id,
4012 				       dh_info.AppInstanceId,
4013 				       SMB2_CREATE_GUID_SIZE);
4014 			if (dh_info.timeout)
4015 				fp->durable_timeout =
4016 					min_t(unsigned int, dh_info.timeout,
4017 					      DURABLE_HANDLE_MAX_TIMEOUT);
4018 			else
4019 				fp->durable_timeout = 60;
4020 		}
4021 	}
4022 
4023 reconnected_fp:
4024 	rsp->StructureSize = cpu_to_le16(89);
4025 	opinfo = opinfo_get(fp);
4026 	rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
4027 	rsp->Flags = 0;
4028 	rsp->CreateAction = cpu_to_le32(file_info);
4029 	rsp->CreationTime = cpu_to_le64(fp->create_time);
4030 	time = ksmbd_UnixTimeToNT(stat.atime);
4031 	rsp->LastAccessTime = cpu_to_le64(time);
4032 	time = ksmbd_UnixTimeToNT(stat.mtime);
4033 	fp->open_mtime = time;
4034 	rsp->LastWriteTime = cpu_to_le64(time);
4035 	rsp->ChangeTime = cpu_to_le64(fp->change_time);
4036 	/*
4037 	 * The cached allocation size hides filesystem rounding for the
4038 	 * requested allocation, but it can go stale when the file grows past
4039 	 * it via writes (e.g. across a durable reconnect). Refresh it once the
4040 	 * file exceeds the cached value, rounding the end of file up to the
4041 	 * volume allocation unit (the filesystem block size, matching the
4042 	 * SectorsPerAllocationUnit/BytesPerSector ksmbd advertises) rather than
4043 	 * using the raw on-disk block count, which can include filesystem
4044 	 * preallocation and metadata rounding.
4045 	 */
4046 	if (!S_ISDIR(stat.mode) && stat.size > fp->allocation_size)
4047 		fp->allocation_size = round_up(stat.size, stat.blksize);
4048 	rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
4049 	rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4050 	rsp->FileAttributes = fp->f_ci->m_fattr;
4051 
4052 	rsp->Reserved2 = 0;
4053 
4054 	rsp->PersistentFileId = fp->persistent_id;
4055 	rsp->VolatileFileId = fp->volatile_id;
4056 
4057 	rsp->CreateContextsOffset = 0;
4058 	rsp->CreateContextsLength = 0;
4059 	iov_len = offsetof(struct smb2_create_rsp, Buffer);
4060 
4061 	/* If lease is request send lease context response */
4062 	if (opinfo && opinfo->is_lease) {
4063 		struct create_context *lease_ccontext;
4064 
4065 		ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
4066 			    name, opinfo->o_lease->state);
4067 		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
4068 
4069 		lease_ccontext = (struct create_context *)rsp->Buffer;
4070 		contxt_cnt++;
4071 		create_lease_buf(rsp->Buffer, opinfo->o_lease);
4072 		le32_add_cpu(&rsp->CreateContextsLength,
4073 			     conn->vals->create_lease_size);
4074 		iov_len += conn->vals->create_lease_size;
4075 		next_ptr = &lease_ccontext->Next;
4076 		next_off = conn->vals->create_lease_size;
4077 	}
4078 	opinfo_put(opinfo);
4079 
4080 	if (maximal_access_ctxt) {
4081 		struct create_context *mxac_ccontext;
4082 
4083 		if (maximal_access == 0)
4084 			ksmbd_vfs_query_maximal_access(idmap,
4085 						       path.dentry,
4086 						       &maximal_access);
4087 		mxac_ccontext = (struct create_context *)(rsp->Buffer +
4088 				le32_to_cpu(rsp->CreateContextsLength));
4089 		contxt_cnt++;
4090 		create_mxac_rsp_buf(rsp->Buffer +
4091 				le32_to_cpu(rsp->CreateContextsLength),
4092 				le32_to_cpu(maximal_access));
4093 		le32_add_cpu(&rsp->CreateContextsLength,
4094 			     conn->vals->create_mxac_size);
4095 		iov_len += conn->vals->create_mxac_size;
4096 		if (next_ptr)
4097 			*next_ptr = cpu_to_le32(next_off);
4098 		next_ptr = &mxac_ccontext->Next;
4099 		next_off = conn->vals->create_mxac_size;
4100 	}
4101 
4102 	if (query_disk_id) {
4103 		struct create_context *disk_id_ccontext;
4104 
4105 		disk_id_ccontext = (struct create_context *)(rsp->Buffer +
4106 				le32_to_cpu(rsp->CreateContextsLength));
4107 		contxt_cnt++;
4108 		create_disk_id_rsp_buf(rsp->Buffer +
4109 				le32_to_cpu(rsp->CreateContextsLength),
4110 				stat.ino, tcon->id);
4111 		le32_add_cpu(&rsp->CreateContextsLength,
4112 			     conn->vals->create_disk_id_size);
4113 		iov_len += conn->vals->create_disk_id_size;
4114 		if (next_ptr)
4115 			*next_ptr = cpu_to_le32(next_off);
4116 		next_ptr = &disk_id_ccontext->Next;
4117 		next_off = conn->vals->create_disk_id_size;
4118 	}
4119 
4120 	if (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2) {
4121 		struct create_context *durable_ccontext;
4122 
4123 		durable_ccontext = (struct create_context *)(rsp->Buffer +
4124 				le32_to_cpu(rsp->CreateContextsLength));
4125 		contxt_cnt++;
4126 		if (dh_info.type == DURABLE_REQ) {
4127 			create_durable_rsp_buf(rsp->Buffer +
4128 					le32_to_cpu(rsp->CreateContextsLength));
4129 			le32_add_cpu(&rsp->CreateContextsLength,
4130 					conn->vals->create_durable_size);
4131 			iov_len += conn->vals->create_durable_size;
4132 		} else {
4133 			create_durable_v2_rsp_buf(rsp->Buffer +
4134 					le32_to_cpu(rsp->CreateContextsLength),
4135 					fp);
4136 			le32_add_cpu(&rsp->CreateContextsLength,
4137 					conn->vals->create_durable_v2_size);
4138 			iov_len += conn->vals->create_durable_v2_size;
4139 		}
4140 
4141 		if (next_ptr)
4142 			*next_ptr = cpu_to_le32(next_off);
4143 		next_ptr = &durable_ccontext->Next;
4144 		next_off = conn->vals->create_durable_size;
4145 	}
4146 
4147 	if (posix_ctxt) {
4148 		contxt_cnt++;
4149 		create_posix_rsp_buf(rsp->Buffer +
4150 				le32_to_cpu(rsp->CreateContextsLength),
4151 				fp);
4152 		le32_add_cpu(&rsp->CreateContextsLength,
4153 			     conn->vals->create_posix_size);
4154 		iov_len += conn->vals->create_posix_size;
4155 		if (next_ptr)
4156 			*next_ptr = cpu_to_le32(next_off);
4157 	}
4158 
4159 	if (contxt_cnt > 0) {
4160 		rsp->CreateContextsOffset =
4161 			cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
4162 	}
4163 
4164 err_out:
4165 	if (rc && (file_present || created))
4166 		path_put(&path);
4167 
4168 err_out1:
4169 	ksmbd_revert_fsids(work);
4170 
4171 err_out2:
4172 	if (!rc) {
4173 		rc = ksmbd_update_fstate(&work->sess->file_table, fp,
4174 					 FP_INITED);
4175 		if (!rc)
4176 			rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
4177 	}
4178 	if (rc) {
4179 		if (rc == -EINVAL)
4180 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4181 		else if (rc == -EOPNOTSUPP)
4182 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
4183 		else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
4184 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
4185 		else if (rc == -ENOENT)
4186 			rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
4187 		else if (rc == -EPERM)
4188 			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
4189 		else if (rc == -EBUSY)
4190 			rsp->hdr.Status = STATUS_DELETE_PENDING;
4191 		else if (rc == -EBADF)
4192 			rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
4193 		else if (rc == -ENOEXEC)
4194 			rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
4195 		else if (rc == -ENXIO)
4196 			rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
4197 		else if (rc == -EEXIST)
4198 			rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
4199 		else if (rc == -EMFILE)
4200 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
4201 		if (!rsp->hdr.Status)
4202 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4203 
4204 		if (fp)
4205 			ksmbd_fd_put(work, fp);
4206 		smb2_set_err_rsp(work);
4207 		ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
4208 	}
4209 
4210 	if (dh_info.reconnected) {
4211 		/*
4212 		 * If reconnect succeeded, fp was republished in the
4213 		 * session file table.  On a later error, ksmbd_fd_put()
4214 		 * above drops the session reference; drop the durable
4215 		 * lookup reference through the same session-aware path so
4216 		 * final close removes the volatile id before freeing fp.
4217 		 */
4218 		if (rc && fp == dh_info.fp)
4219 			ksmbd_fd_put(work, dh_info.fp);
4220 		else
4221 			ksmbd_put_durable_fd(dh_info.fp);
4222 	}
4223 
4224 	kfree(name);
4225 	kfree(lc);
4226 
4227 	return rc;
4228 }
4229 
4230 static int readdir_info_level_struct_sz(int info_level)
4231 {
4232 	switch (info_level) {
4233 	case FILE_FULL_DIRECTORY_INFORMATION:
4234 		return sizeof(FILE_FULL_DIRECTORY_INFO);
4235 	case FILE_BOTH_DIRECTORY_INFORMATION:
4236 		return sizeof(FILE_BOTH_DIRECTORY_INFO);
4237 	case FILE_DIRECTORY_INFORMATION:
4238 		return sizeof(FILE_DIRECTORY_INFO);
4239 	case FILE_NAMES_INFORMATION:
4240 		return sizeof(struct file_names_info);
4241 	case FILEID_FULL_DIRECTORY_INFORMATION:
4242 		return sizeof(FILE_ID_FULL_DIR_INFO);
4243 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4244 		return sizeof(struct file_id_both_directory_info);
4245 	case SMB_FIND_FILE_POSIX_INFO:
4246 		return sizeof(struct smb2_posix_info);
4247 	default:
4248 		return -EOPNOTSUPP;
4249 	}
4250 }
4251 
4252 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
4253 {
4254 	switch (info_level) {
4255 	case FILE_FULL_DIRECTORY_INFORMATION:
4256 	{
4257 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
4258 
4259 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->rptr;
4260 		d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
4261 		d_info->name = ffdinfo->FileName;
4262 		d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
4263 		return 0;
4264 	}
4265 	case FILE_BOTH_DIRECTORY_INFORMATION:
4266 	{
4267 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
4268 
4269 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->rptr;
4270 		d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
4271 		d_info->name = fbdinfo->FileName;
4272 		d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
4273 		return 0;
4274 	}
4275 	case FILE_DIRECTORY_INFORMATION:
4276 	{
4277 		FILE_DIRECTORY_INFO *fdinfo;
4278 
4279 		fdinfo = (FILE_DIRECTORY_INFO *)d_info->rptr;
4280 		d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
4281 		d_info->name = fdinfo->FileName;
4282 		d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
4283 		return 0;
4284 	}
4285 	case FILE_NAMES_INFORMATION:
4286 	{
4287 		struct file_names_info *fninfo;
4288 
4289 		fninfo = (struct file_names_info *)d_info->rptr;
4290 		d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
4291 		d_info->name = fninfo->FileName;
4292 		d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
4293 		return 0;
4294 	}
4295 	case FILEID_FULL_DIRECTORY_INFORMATION:
4296 	{
4297 		FILE_ID_FULL_DIR_INFO *dinfo;
4298 
4299 		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->rptr;
4300 		d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
4301 		d_info->name = dinfo->FileName;
4302 		d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
4303 		return 0;
4304 	}
4305 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4306 	{
4307 		struct file_id_both_directory_info *fibdinfo;
4308 
4309 		fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
4310 		d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
4311 		d_info->name = fibdinfo->FileName;
4312 		d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
4313 		return 0;
4314 	}
4315 	case SMB_FIND_FILE_POSIX_INFO:
4316 	{
4317 		struct smb2_posix_info *posix_info;
4318 
4319 		posix_info = (struct smb2_posix_info *)d_info->rptr;
4320 		d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
4321 		d_info->name = posix_info->name;
4322 		d_info->name_len = le32_to_cpu(posix_info->name_len);
4323 		return 0;
4324 	}
4325 	default:
4326 		return -EINVAL;
4327 	}
4328 }
4329 
4330 /**
4331  * smb2_populate_readdir_entry() - encode directory entry in smb2 response
4332  * buffer
4333  * @conn:	connection instance
4334  * @info_level:	smb information level
4335  * @d_info:	structure included variables for query dir
4336  * @ksmbd_kstat:	ksmbd wrapper of dirent stat information
4337  *
4338  * if directory has many entries, find first can't read it fully.
4339  * find next might be called multiple times to read remaining dir entries
4340  *
4341  * Return:	0 on success, otherwise error
4342  */
4343 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
4344 				       struct ksmbd_dir_info *d_info,
4345 				       struct ksmbd_kstat *ksmbd_kstat)
4346 {
4347 	int next_entry_offset = 0;
4348 	char *conv_name;
4349 	int conv_len;
4350 	void *kstat;
4351 	int struct_sz, rc = 0;
4352 
4353 	conv_name = ksmbd_convert_dir_info_name(d_info,
4354 						conn->local_nls,
4355 						&conv_len);
4356 	if (!conv_name)
4357 		return -ENOMEM;
4358 
4359 	/* Somehow the name has only terminating NULL bytes */
4360 	if (conv_len < 0) {
4361 		rc = -EINVAL;
4362 		goto free_conv_name;
4363 	}
4364 
4365 	struct_sz = readdir_info_level_struct_sz(info_level);
4366 	if (struct_sz == -EOPNOTSUPP) {
4367 		rc = -EINVAL;
4368 		goto free_conv_name;
4369 	}
4370 
4371 	struct_sz += conv_len;
4372 	next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
4373 	d_info->last_entry_off_align = next_entry_offset - struct_sz;
4374 
4375 	if (next_entry_offset > d_info->out_buf_len) {
4376 		d_info->out_buf_len = 0;
4377 		rc = -ENOSPC;
4378 		goto free_conv_name;
4379 	}
4380 
4381 	kstat = d_info->wptr;
4382 	if (info_level != FILE_NAMES_INFORMATION)
4383 		kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
4384 
4385 	switch (info_level) {
4386 	case FILE_FULL_DIRECTORY_INFORMATION:
4387 	{
4388 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
4389 
4390 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)kstat;
4391 		ffdinfo->FileNameLength = cpu_to_le32(conv_len);
4392 		ffdinfo->EaSize =
4393 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4394 		if (ffdinfo->EaSize)
4395 			ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4396 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4397 			ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4398 		memcpy(ffdinfo->FileName, conv_name, conv_len);
4399 		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4400 		break;
4401 	}
4402 	case FILE_BOTH_DIRECTORY_INFORMATION:
4403 	{
4404 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
4405 
4406 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)kstat;
4407 		fbdinfo->FileNameLength = cpu_to_le32(conv_len);
4408 		fbdinfo->EaSize =
4409 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4410 		if (fbdinfo->EaSize)
4411 			fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4412 		fbdinfo->ShortNameLength = 0;
4413 		fbdinfo->Reserved = 0;
4414 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4415 			fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4416 		memcpy(fbdinfo->FileName, conv_name, conv_len);
4417 		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4418 		break;
4419 	}
4420 	case FILE_DIRECTORY_INFORMATION:
4421 	{
4422 		FILE_DIRECTORY_INFO *fdinfo;
4423 
4424 		fdinfo = (FILE_DIRECTORY_INFO *)kstat;
4425 		fdinfo->FileNameLength = cpu_to_le32(conv_len);
4426 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4427 			fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4428 		memcpy(fdinfo->FileName, conv_name, conv_len);
4429 		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4430 		break;
4431 	}
4432 	case FILE_NAMES_INFORMATION:
4433 	{
4434 		struct file_names_info *fninfo;
4435 
4436 		fninfo = (struct file_names_info *)kstat;
4437 		fninfo->FileNameLength = cpu_to_le32(conv_len);
4438 		memcpy(fninfo->FileName, conv_name, conv_len);
4439 		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4440 		break;
4441 	}
4442 	case FILEID_FULL_DIRECTORY_INFORMATION:
4443 	{
4444 		FILE_ID_FULL_DIR_INFO *dinfo;
4445 
4446 		dinfo = (FILE_ID_FULL_DIR_INFO *)kstat;
4447 		dinfo->FileNameLength = cpu_to_le32(conv_len);
4448 		dinfo->EaSize =
4449 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4450 		if (dinfo->EaSize)
4451 			dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4452 		dinfo->Reserved = 0;
4453 		if (conn->is_aapl)
4454 			dinfo->UniqueId = 0;
4455 		else
4456 			dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4457 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4458 			dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4459 		memcpy(dinfo->FileName, conv_name, conv_len);
4460 		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4461 		break;
4462 	}
4463 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4464 	{
4465 		struct file_id_both_directory_info *fibdinfo;
4466 
4467 		fibdinfo = (struct file_id_both_directory_info *)kstat;
4468 		fibdinfo->FileNameLength = cpu_to_le32(conv_len);
4469 		fibdinfo->EaSize =
4470 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
4471 		if (fibdinfo->EaSize)
4472 			fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
4473 		if (conn->is_aapl)
4474 			fibdinfo->UniqueId = 0;
4475 		else
4476 			fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
4477 		fibdinfo->ShortNameLength = 0;
4478 		fibdinfo->Reserved = 0;
4479 		fibdinfo->Reserved2 = cpu_to_le16(0);
4480 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4481 			fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4482 		memcpy(fibdinfo->FileName, conv_name, conv_len);
4483 		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4484 		break;
4485 	}
4486 	case SMB_FIND_FILE_POSIX_INFO:
4487 	{
4488 		struct smb2_posix_info *posix_info;
4489 		u64 time;
4490 
4491 		posix_info = (struct smb2_posix_info *)kstat;
4492 		posix_info->Ignored = 0;
4493 		posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
4494 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
4495 		posix_info->ChangeTime = cpu_to_le64(time);
4496 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
4497 		posix_info->LastAccessTime = cpu_to_le64(time);
4498 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
4499 		posix_info->LastWriteTime = cpu_to_le64(time);
4500 		posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
4501 		posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
4502 		posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
4503 		posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
4504 		posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
4505 		switch (ksmbd_kstat->kstat->mode & S_IFMT) {
4506 		case S_IFDIR:
4507 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
4508 			break;
4509 		case S_IFLNK:
4510 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
4511 			break;
4512 		case S_IFCHR:
4513 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
4514 			break;
4515 		case S_IFBLK:
4516 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
4517 			break;
4518 		case S_IFIFO:
4519 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
4520 			break;
4521 		case S_IFSOCK:
4522 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
4523 		}
4524 
4525 		posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
4526 		posix_info->DosAttributes =
4527 			S_ISDIR(ksmbd_kstat->kstat->mode) ?
4528 				FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
4529 		if (d_info->hide_dot_file && d_info->name[0] == '.')
4530 			posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
4531 		/*
4532 		 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4533 		 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4534 		 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
4535 		 */
4536 		id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
4537 			  SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
4538 		id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
4539 			  SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
4540 		memcpy(posix_info->name, conv_name, conv_len);
4541 		posix_info->name_len = cpu_to_le32(conv_len);
4542 		posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
4543 		break;
4544 	}
4545 
4546 	} /* switch (info_level) */
4547 
4548 	d_info->last_entry_offset = d_info->data_count;
4549 	d_info->data_count += next_entry_offset;
4550 	d_info->out_buf_len -= next_entry_offset;
4551 	d_info->wptr += next_entry_offset;
4552 
4553 	ksmbd_debug(SMB,
4554 		    "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
4555 		    info_level, d_info->out_buf_len,
4556 		    next_entry_offset, d_info->data_count);
4557 
4558 free_conv_name:
4559 	kfree(conv_name);
4560 	return rc;
4561 }
4562 
4563 struct smb2_query_dir_private {
4564 	struct ksmbd_work	*work;
4565 	char			*search_pattern;
4566 	struct ksmbd_file	*dir_fp;
4567 
4568 	struct ksmbd_dir_info	*d_info;
4569 	int			info_level;
4570 };
4571 
4572 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
4573 {
4574 	struct mnt_idmap	*idmap = file_mnt_idmap(priv->dir_fp->filp);
4575 	struct kstat		kstat;
4576 	struct ksmbd_kstat	ksmbd_kstat;
4577 	int			rc;
4578 	int			i;
4579 
4580 	for (i = 0; i < priv->d_info->num_entry; i++) {
4581 		struct dentry *dent;
4582 
4583 		if (dentry_name(priv->d_info, priv->info_level))
4584 			return -EINVAL;
4585 
4586 		dent = lookup_one_unlocked(idmap,
4587 					   &QSTR_LEN(priv->d_info->name,
4588 						     priv->d_info->name_len),
4589 					   priv->dir_fp->filp->f_path.dentry);
4590 
4591 		if (IS_ERR(dent)) {
4592 			ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
4593 				    priv->d_info->name,
4594 				    PTR_ERR(dent));
4595 			continue;
4596 		}
4597 		if (unlikely(d_is_negative(dent))) {
4598 			dput(dent);
4599 			ksmbd_debug(SMB, "Negative dentry `%s'\n",
4600 				    priv->d_info->name);
4601 			continue;
4602 		}
4603 
4604 		ksmbd_kstat.kstat = &kstat;
4605 		if (priv->info_level != FILE_NAMES_INFORMATION) {
4606 			rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
4607 							 idmap,
4608 							 dent,
4609 							 &ksmbd_kstat);
4610 			if (rc) {
4611 				dput(dent);
4612 				continue;
4613 			}
4614 		}
4615 
4616 		rc = smb2_populate_readdir_entry(priv->work->conn,
4617 						 priv->info_level,
4618 						 priv->d_info,
4619 						 &ksmbd_kstat);
4620 		dput(dent);
4621 		if (rc)
4622 			return rc;
4623 	}
4624 	return 0;
4625 }
4626 
4627 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
4628 				   int info_level)
4629 {
4630 	int struct_sz;
4631 	int conv_len;
4632 	int next_entry_offset;
4633 
4634 	struct_sz = readdir_info_level_struct_sz(info_level);
4635 	if (struct_sz == -EOPNOTSUPP)
4636 		return -EOPNOTSUPP;
4637 
4638 	conv_len = (d_info->name_len + 1) * 2;
4639 	next_entry_offset = ALIGN(struct_sz + conv_len,
4640 				  KSMBD_DIR_INFO_ALIGNMENT);
4641 
4642 	if (next_entry_offset > d_info->out_buf_len) {
4643 		d_info->out_buf_len = 0;
4644 		return -ENOSPC;
4645 	}
4646 
4647 	switch (info_level) {
4648 	case FILE_FULL_DIRECTORY_INFORMATION:
4649 	{
4650 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
4651 
4652 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->wptr;
4653 		memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
4654 		ffdinfo->FileName[d_info->name_len] = 0x00;
4655 		ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4656 		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4657 		break;
4658 	}
4659 	case FILE_BOTH_DIRECTORY_INFORMATION:
4660 	{
4661 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
4662 
4663 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->wptr;
4664 		memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
4665 		fbdinfo->FileName[d_info->name_len] = 0x00;
4666 		fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4667 		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4668 		break;
4669 	}
4670 	case FILE_DIRECTORY_INFORMATION:
4671 	{
4672 		FILE_DIRECTORY_INFO *fdinfo;
4673 
4674 		fdinfo = (FILE_DIRECTORY_INFO *)d_info->wptr;
4675 		memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
4676 		fdinfo->FileName[d_info->name_len] = 0x00;
4677 		fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4678 		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4679 		break;
4680 	}
4681 	case FILE_NAMES_INFORMATION:
4682 	{
4683 		struct file_names_info *fninfo;
4684 
4685 		fninfo = (struct file_names_info *)d_info->wptr;
4686 		memcpy(fninfo->FileName, d_info->name, d_info->name_len);
4687 		fninfo->FileName[d_info->name_len] = 0x00;
4688 		fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
4689 		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4690 		break;
4691 	}
4692 	case FILEID_FULL_DIRECTORY_INFORMATION:
4693 	{
4694 		FILE_ID_FULL_DIR_INFO *dinfo;
4695 
4696 		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->wptr;
4697 		memcpy(dinfo->FileName, d_info->name, d_info->name_len);
4698 		dinfo->FileName[d_info->name_len] = 0x00;
4699 		dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4700 		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4701 		break;
4702 	}
4703 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4704 	{
4705 		struct file_id_both_directory_info *fibdinfo;
4706 
4707 		fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
4708 		memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
4709 		fibdinfo->FileName[d_info->name_len] = 0x00;
4710 		fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4711 		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4712 		break;
4713 	}
4714 	case SMB_FIND_FILE_POSIX_INFO:
4715 	{
4716 		struct smb2_posix_info *posix_info;
4717 
4718 		posix_info = (struct smb2_posix_info *)d_info->wptr;
4719 		memcpy(posix_info->name, d_info->name, d_info->name_len);
4720 		posix_info->name[d_info->name_len] = 0x00;
4721 		posix_info->name_len = cpu_to_le32(d_info->name_len);
4722 		posix_info->NextEntryOffset =
4723 			cpu_to_le32(next_entry_offset);
4724 		break;
4725 	}
4726 	} /* switch (info_level) */
4727 
4728 	d_info->num_entry++;
4729 	d_info->out_buf_len -= next_entry_offset;
4730 	d_info->wptr += next_entry_offset;
4731 	return 0;
4732 }
4733 
4734 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
4735 		       loff_t offset, u64 ino, unsigned int d_type)
4736 {
4737 	struct ksmbd_readdir_data	*buf;
4738 	struct smb2_query_dir_private	*priv;
4739 	struct ksmbd_dir_info		*d_info;
4740 	int				rc;
4741 
4742 	buf	= container_of(ctx, struct ksmbd_readdir_data, ctx);
4743 	priv	= buf->private;
4744 	d_info	= priv->d_info;
4745 
4746 	/* dot and dotdot entries are already reserved */
4747 	if (!strcmp(".", name) || !strcmp("..", name))
4748 		return true;
4749 	d_info->num_scan++;
4750 	if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
4751 		return true;
4752 	if (!match_pattern(name, namlen, priv->search_pattern))
4753 		return true;
4754 
4755 	d_info->name		= name;
4756 	d_info->name_len	= namlen;
4757 	rc = reserve_populate_dentry(d_info, priv->info_level);
4758 	if (rc)
4759 		return false;
4760 	if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
4761 		d_info->out_buf_len = 0;
4762 	return true;
4763 }
4764 
4765 static int verify_info_level(int info_level)
4766 {
4767 	switch (info_level) {
4768 	case FILE_FULL_DIRECTORY_INFORMATION:
4769 	case FILE_BOTH_DIRECTORY_INFORMATION:
4770 	case FILE_DIRECTORY_INFORMATION:
4771 	case FILE_NAMES_INFORMATION:
4772 	case FILEID_FULL_DIRECTORY_INFORMATION:
4773 	case FILEID_BOTH_DIRECTORY_INFORMATION:
4774 	case SMB_FIND_FILE_POSIX_INFO:
4775 		break;
4776 	default:
4777 		return -EOPNOTSUPP;
4778 	}
4779 
4780 	return 0;
4781 }
4782 
4783 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
4784 {
4785 	int free_len;
4786 
4787 	free_len = (int)(work->response_sz -
4788 		(get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
4789 	return free_len;
4790 }
4791 
4792 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
4793 				     unsigned short hdr2_len,
4794 				     unsigned int out_buf_len)
4795 {
4796 	int free_len;
4797 
4798 	if (out_buf_len > work->conn->vals->max_trans_size)
4799 		return -EINVAL;
4800 
4801 	free_len = smb2_resp_buf_len(work, hdr2_len);
4802 	if (free_len < 0)
4803 		return -EINVAL;
4804 
4805 	return min_t(int, out_buf_len, free_len);
4806 }
4807 
4808 int smb2_query_dir(struct ksmbd_work *work)
4809 {
4810 	struct ksmbd_conn *conn = work->conn;
4811 	struct smb2_query_directory_req *req;
4812 	struct smb2_query_directory_rsp *rsp;
4813 	struct ksmbd_share_config *share = work->tcon->share_conf;
4814 	struct ksmbd_file *dir_fp = NULL;
4815 	struct ksmbd_dir_info d_info;
4816 	int rc = 0;
4817 	char *srch_ptr = NULL;
4818 	unsigned char srch_flag;
4819 	int buffer_sz;
4820 	struct smb2_query_dir_private query_dir_private = {NULL, };
4821 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4822 
4823 	ksmbd_debug(SMB, "Received smb2 query directory request\n");
4824 
4825 	WORK_BUFFERS(work, req, rsp);
4826 
4827 	if (smb2_compound_has_failed(work, &rsp->hdr))
4828 		return -EACCES;
4829 
4830 	if (work->next_smb2_rcv_hdr_off &&
4831 	    !has_file_id(req->VolatileFileId)) {
4832 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4833 			    work->compound_fid);
4834 		id = work->compound_fid;
4835 		pid = work->compound_pfid;
4836 	}
4837 
4838 	if (!has_file_id(id)) {
4839 		id = req->VolatileFileId;
4840 		pid = req->PersistentFileId;
4841 	}
4842 
4843 	if (ksmbd_override_fsids(work)) {
4844 		rsp->hdr.Status = STATUS_NO_MEMORY;
4845 		smb2_set_err_rsp(work);
4846 		return -ENOMEM;
4847 	}
4848 
4849 	rc = verify_info_level(req->FileInformationClass);
4850 	if (rc) {
4851 		rc = -EFAULT;
4852 		goto err_out2;
4853 	}
4854 
4855 	dir_fp = ksmbd_lookup_fd_slow(work, id, pid);
4856 	if (!dir_fp) {
4857 		rc = -EBADF;
4858 		goto err_out2;
4859 	}
4860 
4861 	if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4862 	    inode_permission(file_mnt_idmap(dir_fp->filp),
4863 			     file_inode(dir_fp->filp),
4864 			     MAY_READ | MAY_EXEC)) {
4865 		pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4866 		rc = -EACCES;
4867 		goto err_out2;
4868 	}
4869 
4870 	if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4871 		pr_err("can't do query dir for a file\n");
4872 		rc = -EINVAL;
4873 		goto err_out2;
4874 	}
4875 
4876 	srch_flag = req->Flags;
4877 	srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
4878 					  le16_to_cpu(req->FileNameLength), 1,
4879 					  conn->local_nls);
4880 	if (IS_ERR(srch_ptr)) {
4881 		ksmbd_debug(SMB, "Search Pattern not found\n");
4882 		rc = -EINVAL;
4883 		goto err_out2;
4884 	} else {
4885 		ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4886 	}
4887 
4888 	mutex_lock(&dir_fp->readdir_lock);
4889 
4890 	if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4891 		ksmbd_debug(SMB, "Restart directory scan\n");
4892 		generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4893 	}
4894 
4895 	memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4896 	d_info.wptr = (char *)rsp->Buffer;
4897 	d_info.rptr = (char *)rsp->Buffer;
4898 	d_info.out_buf_len =
4899 		smb2_calc_max_out_buf_len(work,
4900 				offsetof(struct smb2_query_directory_rsp, Buffer),
4901 				le32_to_cpu(req->OutputBufferLength));
4902 	if (d_info.out_buf_len < 0) {
4903 		rc = -EINVAL;
4904 		goto err_out;
4905 	}
4906 	d_info.flags = srch_flag;
4907 
4908 	/*
4909 	 * reserve dot and dotdot entries in head of buffer
4910 	 * in first response
4911 	 */
4912 	rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4913 					       dir_fp, &d_info, srch_ptr,
4914 					       smb2_populate_readdir_entry);
4915 	if (rc == -ENOSPC)
4916 		rc = 0;
4917 	else if (rc)
4918 		goto err_out;
4919 
4920 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4921 		d_info.hide_dot_file = true;
4922 
4923 	buffer_sz				= d_info.out_buf_len;
4924 	d_info.rptr				= d_info.wptr;
4925 	query_dir_private.work			= work;
4926 	query_dir_private.search_pattern	= srch_ptr;
4927 	query_dir_private.dir_fp		= dir_fp;
4928 	query_dir_private.d_info		= &d_info;
4929 	query_dir_private.info_level		= req->FileInformationClass;
4930 	dir_fp->readdir_data.private		= &query_dir_private;
4931 	set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4932 again:
4933 	d_info.num_scan = 0;
4934 	rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4935 	/*
4936 	 * num_entry can be 0 if the directory iteration stops before reaching
4937 	 * the end of the directory and no file is matched with the search
4938 	 * pattern.
4939 	 */
4940 	if (rc >= 0 && !d_info.num_entry && d_info.num_scan &&
4941 	    d_info.out_buf_len > 0)
4942 		goto again;
4943 	/*
4944 	 * req->OutputBufferLength is too small to contain even one entry.
4945 	 * In this case, it immediately returns OutputBufferLength 0 to client.
4946 	 */
4947 	if (!d_info.out_buf_len && !d_info.num_entry)
4948 		goto no_buf_len;
4949 	if (rc > 0 || rc == -ENOSPC)
4950 		rc = 0;
4951 	else if (rc)
4952 		goto err_out;
4953 
4954 	d_info.wptr = d_info.rptr;
4955 	d_info.out_buf_len = buffer_sz;
4956 	rc = process_query_dir_entries(&query_dir_private);
4957 	if (rc)
4958 		goto err_out;
4959 
4960 	if (!d_info.data_count && d_info.out_buf_len >= 0) {
4961 		if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4962 			rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4963 		} else {
4964 			dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4965 			rsp->hdr.Status = STATUS_NO_MORE_FILES;
4966 		}
4967 		rsp->StructureSize = cpu_to_le16(9);
4968 		rsp->OutputBufferOffset = cpu_to_le16(0);
4969 		rsp->OutputBufferLength = cpu_to_le32(0);
4970 		rsp->Buffer[0] = 0;
4971 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4972 				       offsetof(struct smb2_query_directory_rsp, Buffer)
4973 				       + 1);
4974 		if (rc)
4975 			goto err_out;
4976 	} else {
4977 no_buf_len:
4978 		((FILE_DIRECTORY_INFO *)
4979 		((char *)rsp->Buffer + d_info.last_entry_offset))
4980 		->NextEntryOffset = 0;
4981 		if (d_info.data_count >= d_info.last_entry_off_align)
4982 			d_info.data_count -= d_info.last_entry_off_align;
4983 
4984 		rsp->StructureSize = cpu_to_le16(9);
4985 		rsp->OutputBufferOffset = cpu_to_le16(72);
4986 		rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4987 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4988 				       offsetof(struct smb2_query_directory_rsp, Buffer) +
4989 				       d_info.data_count);
4990 		if (rc)
4991 			goto err_out;
4992 	}
4993 
4994 	mutex_unlock(&dir_fp->readdir_lock);
4995 	kfree(srch_ptr);
4996 	ksmbd_fd_put(work, dir_fp);
4997 	ksmbd_revert_fsids(work);
4998 	return 0;
4999 
5000 err_out:
5001 	pr_err("error while processing smb2 query dir rc = %d\n", rc);
5002 	mutex_unlock(&dir_fp->readdir_lock);
5003 	kfree(srch_ptr);
5004 
5005 err_out2:
5006 	if (rc == -EINVAL)
5007 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5008 	else if (rc == -EACCES)
5009 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
5010 	else if (rc == -ENOENT)
5011 		rsp->hdr.Status = STATUS_NO_SUCH_FILE;
5012 	else if (rc == -EBADF)
5013 		rsp->hdr.Status = STATUS_FILE_CLOSED;
5014 	else if (rc == -ENOMEM)
5015 		rsp->hdr.Status = STATUS_NO_MEMORY;
5016 	else if (rc == -EFAULT)
5017 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5018 	else if (rc == -EIO)
5019 		rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
5020 	if (!rsp->hdr.Status)
5021 		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5022 
5023 	smb2_set_err_rsp(work);
5024 	ksmbd_fd_put(work, dir_fp);
5025 	ksmbd_revert_fsids(work);
5026 	return rc;
5027 }
5028 
5029 /**
5030  * buffer_check_err() - helper function to check buffer errors
5031  * @reqOutputBufferLength:	max buffer length expected in command response
5032  * @rsp:		query info response buffer contains output buffer length
5033  * @rsp_org:		base response buffer pointer in case of chained response
5034  *
5035  * Return:	0 on success, otherwise error
5036  */
5037 static int buffer_check_err(int reqOutputBufferLength,
5038 			    struct smb2_query_info_rsp *rsp,
5039 			    void *rsp_org)
5040 {
5041 	if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
5042 		pr_err("Invalid Buffer Size Requested\n");
5043 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
5044 		*(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
5045 		return -EINVAL;
5046 	}
5047 	return 0;
5048 }
5049 
5050 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
5051 				   void *rsp_org)
5052 {
5053 	struct smb2_file_standard_info *sinfo;
5054 
5055 	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
5056 
5057 	sinfo->AllocationSize = cpu_to_le64(4096);
5058 	sinfo->EndOfFile = cpu_to_le64(0);
5059 	sinfo->NumberOfLinks = cpu_to_le32(1);
5060 	sinfo->DeletePending = 1;
5061 	sinfo->Directory = 0;
5062 	rsp->OutputBufferLength =
5063 		cpu_to_le32(sizeof(struct smb2_file_standard_info));
5064 }
5065 
5066 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
5067 				   void *rsp_org)
5068 {
5069 	struct smb2_file_internal_info *file_info;
5070 
5071 	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
5072 
5073 	/* any unique number */
5074 	file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
5075 	rsp->OutputBufferLength =
5076 		cpu_to_le32(sizeof(struct smb2_file_internal_info));
5077 }
5078 
5079 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
5080 				   struct smb2_query_info_req *req,
5081 				   struct smb2_query_info_rsp *rsp,
5082 				   void *rsp_org)
5083 {
5084 	u64 id;
5085 	int rc;
5086 
5087 	/*
5088 	 * Windows can sometime send query file info request on
5089 	 * pipe without opening it, checking error condition here
5090 	 */
5091 	id = req->VolatileFileId;
5092 
5093 	lockdep_assert_not_held(&sess->rpc_lock);
5094 
5095 	down_read(&sess->rpc_lock);
5096 	if (!ksmbd_session_rpc_method(sess, id)) {
5097 		up_read(&sess->rpc_lock);
5098 		return -ENOENT;
5099 	}
5100 	up_read(&sess->rpc_lock);
5101 
5102 	ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
5103 		    req->FileInfoClass, req->VolatileFileId);
5104 
5105 	switch (req->FileInfoClass) {
5106 	case FILE_STANDARD_INFORMATION:
5107 		get_standard_info_pipe(rsp, rsp_org);
5108 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5109 				      rsp, rsp_org);
5110 		break;
5111 	case FILE_INTERNAL_INFORMATION:
5112 		get_internal_info_pipe(rsp, id, rsp_org);
5113 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5114 				      rsp, rsp_org);
5115 		break;
5116 	default:
5117 		ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
5118 			    req->FileInfoClass);
5119 		rc = -EOPNOTSUPP;
5120 	}
5121 	return rc;
5122 }
5123 
5124 /**
5125  * smb2_get_ea() - handler for smb2 get extended attribute command
5126  * @work:	smb work containing query info command buffer
5127  * @fp:		ksmbd_file pointer
5128  * @req:	get extended attribute request
5129  * @rsp:	response buffer pointer
5130  * @rsp_org:	base response buffer pointer in case of chained response
5131  *
5132  * Return:	0 on success, otherwise error
5133  */
5134 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
5135 		       struct smb2_query_info_req *req,
5136 		       struct smb2_query_info_rsp *rsp, void *rsp_org)
5137 {
5138 	struct smb2_ea_info *eainfo, *prev_eainfo;
5139 	char *name, *ptr, *xattr_list = NULL, *buf;
5140 	int rc, name_len, value_len, xattr_list_len, idx;
5141 	ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
5142 	struct smb2_ea_info_req *ea_req = NULL;
5143 	const struct path *path;
5144 	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
5145 
5146 	if (!(fp->daccess & FILE_READ_EA_LE)) {
5147 		pr_err("Not permitted to read ext attr : 0x%x\n",
5148 		       fp->daccess);
5149 		return -EACCES;
5150 	}
5151 
5152 	path = &fp->filp->f_path;
5153 	/* single EA entry is requested with given user.* name */
5154 	if (req->InputBufferLength) {
5155 		if (le32_to_cpu(req->InputBufferLength) <=
5156 		    sizeof(struct smb2_ea_info_req))
5157 			return -EINVAL;
5158 
5159 		ea_req = (struct smb2_ea_info_req *)((char *)req +
5160 						     le16_to_cpu(req->InputBufferOffset));
5161 
5162 		if (le32_to_cpu(req->InputBufferLength) <
5163 		    offsetof(struct smb2_ea_info_req, name) +
5164 		    ea_req->EaNameLength)
5165 			return -EINVAL;
5166 	} else {
5167 		/* need to send all EAs, if no specific EA is requested*/
5168 		if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
5169 			ksmbd_debug(SMB,
5170 				    "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
5171 				    le32_to_cpu(req->Flags));
5172 	}
5173 
5174 	buf_free_len =
5175 		smb2_calc_max_out_buf_len(work,
5176 				offsetof(struct smb2_query_info_rsp, Buffer),
5177 				le32_to_cpu(req->OutputBufferLength));
5178 	if (buf_free_len < 0)
5179 		return -EINVAL;
5180 
5181 	rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
5182 	if (rc < 0) {
5183 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
5184 		goto out;
5185 	} else if (!rc) { /* there is no EA in the file */
5186 		ksmbd_debug(SMB, "no ea data in the file\n");
5187 		goto done;
5188 	}
5189 	xattr_list_len = rc;
5190 
5191 	ptr = (char *)rsp->Buffer;
5192 	eainfo = (struct smb2_ea_info *)ptr;
5193 	prev_eainfo = eainfo;
5194 	idx = 0;
5195 
5196 	while (idx < xattr_list_len) {
5197 		name = xattr_list + idx;
5198 		name_len = strlen(name);
5199 
5200 		ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
5201 		idx += name_len + 1;
5202 
5203 		/*
5204 		 * CIFS does not support EA other than user.* namespace,
5205 		 * still keep the framework generic, to list other attrs
5206 		 * in future.
5207 		 */
5208 		if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
5209 			continue;
5210 
5211 		if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
5212 			     STREAM_PREFIX_LEN))
5213 			continue;
5214 
5215 		if (req->InputBufferLength &&
5216 		    strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
5217 			    ea_req->EaNameLength))
5218 			continue;
5219 
5220 		if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
5221 			     DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
5222 			continue;
5223 
5224 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
5225 			name_len -= XATTR_USER_PREFIX_LEN;
5226 
5227 		ptr = eainfo->name + name_len + 1;
5228 		buf_free_len -= (offsetof(struct smb2_ea_info, name) +
5229 				name_len + 1);
5230 		/* bailout if xattr can't fit in buf_free_len */
5231 		value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
5232 					       name, &buf);
5233 		if (value_len <= 0) {
5234 			rc = -ENOENT;
5235 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
5236 			goto out;
5237 		}
5238 
5239 		buf_free_len -= value_len;
5240 		if (buf_free_len < 0) {
5241 			kfree(buf);
5242 			break;
5243 		}
5244 
5245 		memcpy(ptr, buf, value_len);
5246 		kfree(buf);
5247 
5248 		ptr += value_len;
5249 		eainfo->Flags = 0;
5250 		eainfo->EaNameLength = name_len;
5251 
5252 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
5253 			memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
5254 			       name_len);
5255 		else
5256 			memcpy(eainfo->name, name, name_len);
5257 
5258 		eainfo->name[name_len] = '\0';
5259 		eainfo->EaValueLength = cpu_to_le16(value_len);
5260 		next_offset = offsetof(struct smb2_ea_info, name) +
5261 			name_len + 1 + value_len;
5262 
5263 		/* align next xattr entry at 4 byte bundary */
5264 		alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
5265 		if (alignment_bytes) {
5266 			if (buf_free_len < alignment_bytes)
5267 				break;
5268 			memset(ptr, '\0', alignment_bytes);
5269 			ptr += alignment_bytes;
5270 			next_offset += alignment_bytes;
5271 			buf_free_len -= alignment_bytes;
5272 		}
5273 		eainfo->NextEntryOffset = cpu_to_le32(next_offset);
5274 		prev_eainfo = eainfo;
5275 		eainfo = (struct smb2_ea_info *)ptr;
5276 		rsp_data_cnt += next_offset;
5277 
5278 		if (req->InputBufferLength) {
5279 			ksmbd_debug(SMB, "single entry requested\n");
5280 			break;
5281 		}
5282 	}
5283 
5284 	/* no more ea entries */
5285 	prev_eainfo->NextEntryOffset = 0;
5286 done:
5287 	rc = 0;
5288 	if (rsp_data_cnt == 0)
5289 		rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
5290 	rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
5291 out:
5292 	kvfree(xattr_list);
5293 	return rc;
5294 }
5295 
5296 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
5297 				 struct ksmbd_file *fp, void *rsp_org)
5298 {
5299 	struct smb2_file_access_info *file_info;
5300 
5301 	file_info = (struct smb2_file_access_info *)rsp->Buffer;
5302 	file_info->AccessFlags = fp->daccess;
5303 	rsp->OutputBufferLength =
5304 		cpu_to_le32(sizeof(struct smb2_file_access_info));
5305 }
5306 
5307 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
5308 			       struct ksmbd_file *fp, void *rsp_org)
5309 {
5310 	struct file_basic_info *basic_info;
5311 	struct kstat stat;
5312 	u64 time;
5313 	int ret;
5314 
5315 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5316 		pr_err("no right to read the attributes : 0x%x\n",
5317 		       fp->daccess);
5318 		return -EACCES;
5319 	}
5320 
5321 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5322 			  AT_STATX_SYNC_AS_STAT);
5323 	if (ret)
5324 		return ret;
5325 
5326 	basic_info = (struct file_basic_info *)rsp->Buffer;
5327 	basic_info->CreationTime = cpu_to_le64(fp->create_time);
5328 	time = ksmbd_UnixTimeToNT(stat.atime);
5329 	basic_info->LastAccessTime = cpu_to_le64(time);
5330 	time = ksmbd_UnixTimeToNT(stat.mtime);
5331 	basic_info->LastWriteTime = cpu_to_le64(time);
5332 	basic_info->ChangeTime = cpu_to_le64(fp->change_time);
5333 	basic_info->Attributes = fp->f_ci->m_fattr;
5334 	basic_info->Pad = 0;
5335 	rsp->OutputBufferLength =
5336 		cpu_to_le32(sizeof(struct file_basic_info));
5337 	return 0;
5338 }
5339 
5340 static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
5341 				  struct ksmbd_file *fp, void *rsp_org)
5342 {
5343 	struct smb2_file_standard_info *sinfo;
5344 	unsigned int delete_pending;
5345 	struct kstat stat;
5346 	int ret;
5347 
5348 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5349 			  AT_STATX_SYNC_AS_STAT);
5350 	if (ret)
5351 		return ret;
5352 
5353 	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
5354 	delete_pending = ksmbd_inode_pending_delete(fp);
5355 
5356 	if (ksmbd_stream_fd(fp) == false) {
5357 		sinfo->AllocationSize = cpu_to_le64(fp->allocation_size);
5358 		sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5359 	} else {
5360 		sinfo->AllocationSize = cpu_to_le64(fp->stream.size);
5361 		sinfo->EndOfFile = cpu_to_le64(fp->stream.size);
5362 	}
5363 	sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
5364 	sinfo->DeletePending = delete_pending;
5365 	sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
5366 	rsp->OutputBufferLength =
5367 		cpu_to_le32(sizeof(struct smb2_file_standard_info));
5368 
5369 	return 0;
5370 }
5371 
5372 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
5373 				    void *rsp_org)
5374 {
5375 	struct smb2_file_alignment_info *file_info;
5376 
5377 	file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
5378 	file_info->AlignmentRequirement = 0;
5379 	rsp->OutputBufferLength =
5380 		cpu_to_le32(sizeof(struct smb2_file_alignment_info));
5381 }
5382 
5383 static int get_file_all_info(struct ksmbd_work *work,
5384 			     struct smb2_query_info_rsp *rsp,
5385 			     struct ksmbd_file *fp,
5386 			     void *rsp_org)
5387 {
5388 	struct ksmbd_conn *conn = work->conn;
5389 	struct smb2_file_all_info *file_info;
5390 	unsigned int delete_pending;
5391 	struct kstat stat;
5392 	int conv_len;
5393 	char *filename;
5394 	u64 time;
5395 	int ret, buf_free_len, filename_len;
5396 	struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
5397 
5398 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5399 		ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
5400 			    fp->daccess);
5401 		return -EACCES;
5402 	}
5403 
5404 	filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
5405 	if (IS_ERR(filename))
5406 		return PTR_ERR(filename);
5407 
5408 	filename_len = strlen(filename);
5409 	buf_free_len = smb2_calc_max_out_buf_len(work,
5410 			offsetof(struct smb2_query_info_rsp, Buffer) +
5411 			offsetof(struct smb2_file_all_info, FileName),
5412 			le32_to_cpu(req->OutputBufferLength));
5413 	if (buf_free_len < (filename_len + 1) * 2) {
5414 		kfree(filename);
5415 		return -EINVAL;
5416 	}
5417 
5418 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5419 			  AT_STATX_SYNC_AS_STAT);
5420 	if (ret) {
5421 		kfree(filename);
5422 		return ret;
5423 	}
5424 
5425 	ksmbd_debug(SMB, "filename = %s\n", filename);
5426 	delete_pending = ksmbd_inode_pending_delete(fp);
5427 	file_info = (struct smb2_file_all_info *)rsp->Buffer;
5428 
5429 	file_info->CreationTime = cpu_to_le64(fp->create_time);
5430 	time = ksmbd_UnixTimeToNT(stat.atime);
5431 	file_info->LastAccessTime = cpu_to_le64(time);
5432 	time = ksmbd_UnixTimeToNT(stat.mtime);
5433 	file_info->LastWriteTime = cpu_to_le64(time);
5434 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
5435 	file_info->Attributes = fp->f_ci->m_fattr;
5436 	file_info->Pad1 = 0;
5437 	if (ksmbd_stream_fd(fp) == false) {
5438 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
5439 		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5440 	} else {
5441 		file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5442 		file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5443 	}
5444 	file_info->NumberOfLinks =
5445 			cpu_to_le32(get_nlink(&stat) - delete_pending);
5446 	file_info->DeletePending = delete_pending;
5447 	file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
5448 	file_info->Pad2 = 0;
5449 	file_info->IndexNumber = cpu_to_le64(stat.ino);
5450 	file_info->EASize = 0;
5451 	file_info->AccessFlags = fp->daccess;
5452 	if (ksmbd_stream_fd(fp) == false)
5453 		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5454 	else
5455 		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
5456 	file_info->Mode = fp->coption;
5457 	file_info->AlignmentRequirement = 0;
5458 	conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
5459 				     min(filename_len, PATH_MAX),
5460 				     conn->local_nls, 0);
5461 	conv_len *= 2;
5462 	file_info->FileNameLength = cpu_to_le32(conv_len);
5463 	rsp->OutputBufferLength =
5464 		cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
5465 	kfree(filename);
5466 	return 0;
5467 }
5468 
5469 static void get_file_alternate_info(struct ksmbd_work *work,
5470 				    struct smb2_query_info_rsp *rsp,
5471 				    struct ksmbd_file *fp,
5472 				    void *rsp_org)
5473 {
5474 	struct ksmbd_conn *conn = work->conn;
5475 	struct smb2_file_alt_name_info *file_info;
5476 	struct dentry *dentry = fp->filp->f_path.dentry;
5477 	int conv_len;
5478 
5479 	spin_lock(&dentry->d_lock);
5480 	file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
5481 	conv_len = ksmbd_extract_shortname(conn,
5482 					   dentry->d_name.name,
5483 					   file_info->FileName);
5484 	spin_unlock(&dentry->d_lock);
5485 	file_info->FileNameLength = cpu_to_le32(conv_len);
5486 	rsp->OutputBufferLength =
5487 		cpu_to_le32(struct_size(file_info, FileName, conv_len));
5488 }
5489 
5490 static int get_file_stream_info(struct ksmbd_work *work,
5491 				struct smb2_query_info_rsp *rsp,
5492 				struct ksmbd_file *fp,
5493 				void *rsp_org)
5494 {
5495 	struct ksmbd_conn *conn = work->conn;
5496 	struct smb2_file_stream_info *file_info;
5497 	char *stream_name, *xattr_list = NULL, *stream_buf;
5498 	struct kstat stat;
5499 	const struct path *path = &fp->filp->f_path;
5500 	ssize_t xattr_list_len;
5501 	int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
5502 	int buf_free_len;
5503 	struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
5504 	int ret;
5505 
5506 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5507 			  AT_STATX_SYNC_AS_STAT);
5508 	if (ret)
5509 		return ret;
5510 
5511 	file_info = (struct smb2_file_stream_info *)rsp->Buffer;
5512 
5513 	buf_free_len =
5514 		smb2_calc_max_out_buf_len(work,
5515 				offsetof(struct smb2_query_info_rsp, Buffer),
5516 				le32_to_cpu(req->OutputBufferLength));
5517 	if (buf_free_len < 0)
5518 		goto out;
5519 
5520 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
5521 	if (xattr_list_len < 0) {
5522 		goto out;
5523 	} else if (!xattr_list_len) {
5524 		ksmbd_debug(SMB, "empty xattr in the file\n");
5525 		goto out;
5526 	}
5527 
5528 	while (idx < xattr_list_len) {
5529 		stream_name = xattr_list + idx;
5530 		streamlen = strlen(stream_name);
5531 		idx += streamlen + 1;
5532 
5533 		ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
5534 
5535 		if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
5536 			    STREAM_PREFIX, STREAM_PREFIX_LEN))
5537 			continue;
5538 
5539 		stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
5540 				STREAM_PREFIX_LEN);
5541 		streamlen = stream_name_len;
5542 
5543 		/* plus : size */
5544 		streamlen += 1;
5545 		stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP);
5546 		if (!stream_buf)
5547 			break;
5548 
5549 		streamlen = snprintf(stream_buf, streamlen + 1,
5550 				     ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
5551 
5552 		next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
5553 		if (next > buf_free_len) {
5554 			kfree(stream_buf);
5555 			break;
5556 		}
5557 
5558 		file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
5559 		streamlen  = smbConvertToUTF16((__le16 *)file_info->StreamName,
5560 					       stream_buf, streamlen,
5561 					       conn->local_nls, 0);
5562 		streamlen *= 2;
5563 		kfree(stream_buf);
5564 		file_info->StreamNameLength = cpu_to_le32(streamlen);
5565 		file_info->StreamSize = cpu_to_le64(stream_name_len);
5566 		file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
5567 
5568 		nbytes += next;
5569 		buf_free_len -= next;
5570 		file_info->NextEntryOffset = cpu_to_le32(next);
5571 	}
5572 
5573 out:
5574 	if (!S_ISDIR(stat.mode) &&
5575 	    buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
5576 		file_info = (struct smb2_file_stream_info *)
5577 			&rsp->Buffer[nbytes];
5578 		streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
5579 					      "::$DATA", 7, conn->local_nls, 0);
5580 		streamlen *= 2;
5581 		file_info->StreamNameLength = cpu_to_le32(streamlen);
5582 		file_info->StreamSize = cpu_to_le64(stat.size);
5583 		file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
5584 		nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
5585 	}
5586 
5587 	/* last entry offset should be 0 */
5588 	file_info->NextEntryOffset = 0;
5589 	kvfree(xattr_list);
5590 
5591 	rsp->OutputBufferLength = cpu_to_le32(nbytes);
5592 
5593 	return 0;
5594 }
5595 
5596 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
5597 				  struct ksmbd_file *fp, void *rsp_org)
5598 {
5599 	struct smb2_file_internal_info *file_info;
5600 	struct kstat stat;
5601 	int ret;
5602 
5603 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5604 			  AT_STATX_SYNC_AS_STAT);
5605 	if (ret)
5606 		return ret;
5607 
5608 	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
5609 	file_info->IndexNumber = cpu_to_le64(stat.ino);
5610 	rsp->OutputBufferLength =
5611 		cpu_to_le32(sizeof(struct smb2_file_internal_info));
5612 
5613 	return 0;
5614 }
5615 
5616 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
5617 				      struct ksmbd_file *fp, void *rsp_org)
5618 {
5619 	struct smb2_file_network_open_info *file_info;
5620 	struct kstat stat;
5621 	u64 time;
5622 	int ret;
5623 
5624 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5625 		pr_err("no right to read the attributes : 0x%x\n",
5626 		       fp->daccess);
5627 		return -EACCES;
5628 	}
5629 
5630 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5631 			  AT_STATX_SYNC_AS_STAT);
5632 	if (ret)
5633 		return ret;
5634 
5635 	file_info = (struct smb2_file_network_open_info *)rsp->Buffer;
5636 
5637 	file_info->CreationTime = cpu_to_le64(fp->create_time);
5638 	time = ksmbd_UnixTimeToNT(stat.atime);
5639 	file_info->LastAccessTime = cpu_to_le64(time);
5640 	time = ksmbd_UnixTimeToNT(stat.mtime);
5641 	file_info->LastWriteTime = cpu_to_le64(time);
5642 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
5643 	file_info->Attributes = fp->f_ci->m_fattr;
5644 	if (ksmbd_stream_fd(fp) == false) {
5645 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
5646 		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5647 	} else {
5648 		file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5649 		file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5650 	}
5651 	file_info->Reserved = cpu_to_le32(0);
5652 	rsp->OutputBufferLength =
5653 		cpu_to_le32(sizeof(struct smb2_file_network_open_info));
5654 	return 0;
5655 }
5656 
5657 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
5658 {
5659 	struct smb2_file_ea_info *file_info;
5660 
5661 	file_info = (struct smb2_file_ea_info *)rsp->Buffer;
5662 	file_info->EASize = 0;
5663 	rsp->OutputBufferLength =
5664 		cpu_to_le32(sizeof(struct smb2_file_ea_info));
5665 }
5666 
5667 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
5668 				   struct ksmbd_file *fp, void *rsp_org)
5669 {
5670 	struct smb2_file_pos_info *file_info;
5671 
5672 	file_info = (struct smb2_file_pos_info *)rsp->Buffer;
5673 	if (ksmbd_stream_fd(fp) == false)
5674 		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5675 	else
5676 		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
5677 
5678 	rsp->OutputBufferLength =
5679 		cpu_to_le32(sizeof(struct smb2_file_pos_info));
5680 }
5681 
5682 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
5683 			       struct ksmbd_file *fp, void *rsp_org)
5684 {
5685 	struct smb2_file_mode_info *file_info;
5686 
5687 	file_info = (struct smb2_file_mode_info *)rsp->Buffer;
5688 	file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
5689 	rsp->OutputBufferLength =
5690 		cpu_to_le32(sizeof(struct smb2_file_mode_info));
5691 }
5692 
5693 static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
5694 				     struct ksmbd_file *fp, void *rsp_org)
5695 {
5696 	struct smb2_file_comp_info *file_info;
5697 	struct kstat stat;
5698 	u16 fmt;
5699 	int ret;
5700 
5701 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5702 			  AT_STATX_SYNC_AS_STAT);
5703 	if (ret)
5704 		return ret;
5705 
5706 	ret = ksmbd_vfs_get_compression(fp, &fmt);
5707 	if (ret)
5708 		return ret;
5709 
5710 	file_info = (struct smb2_file_comp_info *)rsp->Buffer;
5711 	file_info->CompressedFileSize = cpu_to_le64(min_t(u64, stat.blocks << 9, stat.size));
5712 	file_info->CompressionFormat = cpu_to_le16(fmt);
5713 	file_info->CompressionUnitShift = 0;
5714 	file_info->ChunkShift = 0;
5715 	file_info->ClusterShift = 0;
5716 	memset(&file_info->Reserved[0], 0, 3);
5717 
5718 	rsp->OutputBufferLength =
5719 		cpu_to_le32(sizeof(struct smb2_file_comp_info));
5720 
5721 	return 0;
5722 }
5723 
5724 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
5725 				       struct ksmbd_file *fp, void *rsp_org)
5726 {
5727 	struct smb2_file_attr_tag_info *file_info;
5728 
5729 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5730 		pr_err("no right to read the attributes : 0x%x\n",
5731 		       fp->daccess);
5732 		return -EACCES;
5733 	}
5734 
5735 	file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
5736 	file_info->FileAttributes = fp->f_ci->m_fattr;
5737 	file_info->ReparseTag = 0;
5738 	rsp->OutputBufferLength =
5739 		cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
5740 	return 0;
5741 }
5742 
5743 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
5744 				struct ksmbd_file *fp, void *rsp_org)
5745 {
5746 	struct smb311_posix_qinfo *file_info;
5747 	struct inode *inode = file_inode(fp->filp);
5748 	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
5749 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
5750 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
5751 	struct kstat stat;
5752 	u64 time;
5753 	int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
5754 	int ret;
5755 
5756 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5757 		pr_err("no right to read the attributes : 0x%x\n",
5758 		       fp->daccess);
5759 		return -EACCES;
5760 	}
5761 
5762 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5763 			  AT_STATX_SYNC_AS_STAT);
5764 	if (ret)
5765 		return ret;
5766 
5767 	file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
5768 	file_info->CreationTime = cpu_to_le64(fp->create_time);
5769 	time = ksmbd_UnixTimeToNT(stat.atime);
5770 	file_info->LastAccessTime = cpu_to_le64(time);
5771 	time = ksmbd_UnixTimeToNT(stat.mtime);
5772 	file_info->LastWriteTime = cpu_to_le64(time);
5773 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
5774 	file_info->DosAttributes = fp->f_ci->m_fattr;
5775 	file_info->Inode = cpu_to_le64(stat.ino);
5776 	if (ksmbd_stream_fd(fp) == false) {
5777 		file_info->EndOfFile = cpu_to_le64(stat.size);
5778 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
5779 	} else {
5780 		file_info->EndOfFile = cpu_to_le64(fp->stream.size);
5781 		file_info->AllocationSize = cpu_to_le64(fp->stream.size);
5782 	}
5783 	file_info->HardLinks = cpu_to_le32(stat.nlink);
5784 	file_info->Mode = cpu_to_le32(stat.mode & 0777);
5785 	switch (stat.mode & S_IFMT) {
5786 	case S_IFDIR:
5787 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
5788 		break;
5789 	case S_IFLNK:
5790 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
5791 		break;
5792 	case S_IFCHR:
5793 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
5794 		break;
5795 	case S_IFBLK:
5796 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
5797 		break;
5798 	case S_IFIFO:
5799 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
5800 		break;
5801 	case S_IFSOCK:
5802 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
5803 	}
5804 
5805 	file_info->DeviceId = cpu_to_le32(stat.rdev);
5806 
5807 	/*
5808 	 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
5809 	 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
5810 	 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
5811 	 */
5812 	id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
5813 		  SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
5814 	id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
5815 		  SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
5816 
5817 	rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
5818 
5819 	return 0;
5820 }
5821 
5822 static int smb2_get_info_file(struct ksmbd_work *work,
5823 			      struct smb2_query_info_req *req,
5824 			      struct smb2_query_info_rsp *rsp)
5825 {
5826 	struct ksmbd_file *fp;
5827 	int fileinfoclass = 0;
5828 	int rc = 0;
5829 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5830 
5831 	if (test_share_config_flag(work->tcon->share_conf,
5832 				   KSMBD_SHARE_FLAG_PIPE)) {
5833 		/* smb2 info file called for pipe */
5834 		rc = smb2_get_info_file_pipe(work->sess, req, rsp,
5835 					       work->response_buf);
5836 		goto iov_pin_out;
5837 	}
5838 
5839 	if (work->next_smb2_rcv_hdr_off) {
5840 		if (!has_file_id(req->VolatileFileId)) {
5841 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5842 				    work->compound_fid);
5843 			id = work->compound_fid;
5844 			pid = work->compound_pfid;
5845 		}
5846 	}
5847 
5848 	if (!has_file_id(id)) {
5849 		id = req->VolatileFileId;
5850 		pid = req->PersistentFileId;
5851 	}
5852 
5853 	fp = ksmbd_lookup_fd_slow(work, id, pid);
5854 	if (!fp)
5855 		return -ENOENT;
5856 
5857 	fileinfoclass = req->FileInfoClass;
5858 
5859 	switch (fileinfoclass) {
5860 	case FILE_ACCESS_INFORMATION:
5861 		get_file_access_info(rsp, fp, work->response_buf);
5862 		break;
5863 
5864 	case FILE_BASIC_INFORMATION:
5865 		rc = get_file_basic_info(rsp, fp, work->response_buf);
5866 		break;
5867 
5868 	case FILE_STANDARD_INFORMATION:
5869 		rc = get_file_standard_info(rsp, fp, work->response_buf);
5870 		break;
5871 
5872 	case FILE_ALIGNMENT_INFORMATION:
5873 		get_file_alignment_info(rsp, work->response_buf);
5874 		break;
5875 
5876 	case FILE_ALL_INFORMATION:
5877 		rc = get_file_all_info(work, rsp, fp, work->response_buf);
5878 		break;
5879 
5880 	case FILE_ALTERNATE_NAME_INFORMATION:
5881 		get_file_alternate_info(work, rsp, fp, work->response_buf);
5882 		break;
5883 
5884 	case FILE_STREAM_INFORMATION:
5885 		rc = get_file_stream_info(work, rsp, fp, work->response_buf);
5886 		break;
5887 
5888 	case FILE_INTERNAL_INFORMATION:
5889 		rc = get_file_internal_info(rsp, fp, work->response_buf);
5890 		break;
5891 
5892 	case FILE_NETWORK_OPEN_INFORMATION:
5893 		rc = get_file_network_open_info(rsp, fp, work->response_buf);
5894 		break;
5895 
5896 	case FILE_EA_INFORMATION:
5897 		get_file_ea_info(rsp, work->response_buf);
5898 		break;
5899 
5900 	case FILE_FULL_EA_INFORMATION:
5901 		rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
5902 		break;
5903 
5904 	case FILE_POSITION_INFORMATION:
5905 		get_file_position_info(rsp, fp, work->response_buf);
5906 		break;
5907 
5908 	case FILE_MODE_INFORMATION:
5909 		get_file_mode_info(rsp, fp, work->response_buf);
5910 		break;
5911 
5912 	case FILE_COMPRESSION_INFORMATION:
5913 		rc = get_file_compression_info(rsp, fp, work->response_buf);
5914 		break;
5915 
5916 	case FILE_ATTRIBUTE_TAG_INFORMATION:
5917 		rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
5918 		break;
5919 	case SMB_FIND_FILE_POSIX_INFO:
5920 		if (!work->tcon->posix_extensions) {
5921 			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5922 			rc = -EOPNOTSUPP;
5923 		} else {
5924 			rc = find_file_posix_info(rsp, fp, work->response_buf);
5925 		}
5926 		break;
5927 	default:
5928 		ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
5929 			    fileinfoclass);
5930 		rc = -EOPNOTSUPP;
5931 	}
5932 	if (!rc)
5933 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5934 				      rsp, work->response_buf);
5935 	ksmbd_fd_put(work, fp);
5936 
5937 iov_pin_out:
5938 	if (!rc)
5939 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5940 				offsetof(struct smb2_query_info_rsp, Buffer) +
5941 				le32_to_cpu(rsp->OutputBufferLength));
5942 	return rc;
5943 }
5944 
5945 static int smb2_get_info_filesystem(struct ksmbd_work *work,
5946 				    struct smb2_query_info_req *req,
5947 				    struct smb2_query_info_rsp *rsp)
5948 {
5949 	struct ksmbd_conn *conn = work->conn;
5950 	struct ksmbd_share_config *share = work->tcon->share_conf;
5951 	int fsinfoclass = 0;
5952 	struct kstatfs stfs;
5953 	struct path path;
5954 	int rc = 0, len;
5955 
5956 	if (!share->path)
5957 		return -EIO;
5958 
5959 	rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
5960 	if (rc) {
5961 		pr_err("cannot create vfs path\n");
5962 		return -EIO;
5963 	}
5964 
5965 	rc = vfs_statfs(&path, &stfs);
5966 	if (rc) {
5967 		pr_err("cannot do stat of path %s\n", share->path);
5968 		path_put(&path);
5969 		return -EIO;
5970 	}
5971 
5972 	fsinfoclass = req->FileInfoClass;
5973 
5974 	switch (fsinfoclass) {
5975 	case FS_DEVICE_INFORMATION:
5976 	{
5977 		FILE_SYSTEM_DEVICE_INFO *info;
5978 
5979 		info = (FILE_SYSTEM_DEVICE_INFO *)rsp->Buffer;
5980 
5981 		info->DeviceType = cpu_to_le32(FILE_DEVICE_DISK);
5982 		info->DeviceCharacteristics =
5983 			cpu_to_le32(FILE_DEVICE_IS_MOUNTED);
5984 		if (!test_tree_conn_flag(work->tcon,
5985 					 KSMBD_TREE_CONN_FLAG_WRITABLE))
5986 			info->DeviceCharacteristics |=
5987 				cpu_to_le32(FILE_READ_ONLY_DEVICE);
5988 		rsp->OutputBufferLength = cpu_to_le32(8);
5989 		break;
5990 	}
5991 	case FS_ATTRIBUTE_INFORMATION:
5992 	{
5993 		FILE_SYSTEM_ATTRIBUTE_INFO *info;
5994 		struct file_kattr fa = {};
5995 		size_t sz;
5996 		u32 attrs;
5997 		int err;
5998 
5999 		info = (FILE_SYSTEM_ATTRIBUTE_INFO *)rsp->Buffer;
6000 		attrs = FILE_SUPPORTS_OBJECT_IDS |
6001 			FILE_PERSISTENT_ACLS |
6002 			FILE_UNICODE_ON_DISK |
6003 			FILE_SUPPORTS_BLOCK_REFCOUNTING;
6004 
6005 		err = vfs_fileattr_get(path.dentry, &fa);
6006 		/*
6007 		 * -EINVAL, -EOPNOTSUPP: ntfs-3g and other FUSE
6008 		 * filesystems that lack FS_IOC_FSGETXATTR support.
6009 		 */
6010 		if (err && err != -ENOIOCTLCMD && err != -ENOTTY &&
6011 		    err != -EINVAL && err != -EOPNOTSUPP) {
6012 			path_put(&path);
6013 			return err;
6014 		}
6015 		if (!(fa.fsx_xflags & FS_XFLAG_CASEFOLD))
6016 			attrs |= FILE_CASE_SENSITIVE_SEARCH;
6017 		if (!(fa.fsx_xflags & FS_XFLAG_CASENONPRESERVING))
6018 			attrs |= FILE_CASE_PRESERVED_NAMES;
6019 
6020 		info->Attributes = cpu_to_le32(attrs);
6021 		info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
6022 
6023 		if (test_share_config_flag(work->tcon->share_conf,
6024 		    KSMBD_SHARE_FLAG_STREAMS))
6025 			info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
6026 
6027 		info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
6028 		/*
6029 		 * some application(potableapp) can not run on ksmbd share
6030 		 * because only NTFS handle security setting on windows.
6031 		 * So Although local fs(EXT4 or F2fs, etc) is not NTFS,
6032 		 * ksmbd should show share as NTFS. Later, If needed, we can add
6033 		 * fs type(s) parameter to change fs type user wanted.
6034 		 */
6035 		len = smbConvertToUTF16((__le16 *)info->FileSystemName,
6036 					"NTFS", PATH_MAX, conn->local_nls, 0);
6037 		len = len * 2;
6038 		info->FileSystemNameLen = cpu_to_le32(len);
6039 		sz = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + len;
6040 		rsp->OutputBufferLength = cpu_to_le32(sz);
6041 		break;
6042 	}
6043 	case FS_VOLUME_INFORMATION:
6044 	{
6045 		struct filesystem_vol_info *info;
6046 		size_t sz;
6047 		unsigned int serial_crc = 0;
6048 
6049 		info = (struct filesystem_vol_info *)(rsp->Buffer);
6050 		info->VolumeCreationTime = 0;
6051 		serial_crc = crc32_le(serial_crc, share->name,
6052 				      strlen(share->name));
6053 		serial_crc = crc32_le(serial_crc, share->path,
6054 				      strlen(share->path));
6055 		serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
6056 				      strlen(ksmbd_netbios_name()));
6057 		/* Taking dummy value of serial number*/
6058 		info->VolumeSerialNumber = cpu_to_le32(serial_crc);
6059 		len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
6060 					share->name, PATH_MAX,
6061 					conn->local_nls, 0);
6062 		len = len * 2;
6063 		info->VolumeLabelLength = cpu_to_le32(len);
6064 		info->Reserved = 0;
6065 		info->SupportsObjects = 0;
6066 		sz = sizeof(struct filesystem_vol_info) + len;
6067 		rsp->OutputBufferLength = cpu_to_le32(sz);
6068 		break;
6069 	}
6070 	case FS_SIZE_INFORMATION:
6071 	{
6072 		FILE_SYSTEM_SIZE_INFO *info;
6073 
6074 		info = (FILE_SYSTEM_SIZE_INFO *)(rsp->Buffer);
6075 		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
6076 		info->AvailableAllocationUnits = cpu_to_le64(stfs.f_bfree);
6077 		info->SectorsPerAllocationUnit = cpu_to_le32(1);
6078 		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
6079 		rsp->OutputBufferLength = cpu_to_le32(24);
6080 		break;
6081 	}
6082 	case FS_FULL_SIZE_INFORMATION:
6083 	{
6084 		struct smb2_fs_full_size_info *info;
6085 
6086 		info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
6087 		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
6088 		info->CallerAvailableAllocationUnits =
6089 					cpu_to_le64(stfs.f_bavail);
6090 		info->ActualAvailableAllocationUnits =
6091 					cpu_to_le64(stfs.f_bfree);
6092 		info->SectorsPerAllocationUnit = cpu_to_le32(1);
6093 		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
6094 		rsp->OutputBufferLength = cpu_to_le32(32);
6095 		break;
6096 	}
6097 	case FS_OBJECT_ID_INFORMATION:
6098 	{
6099 		struct object_id_info *info;
6100 
6101 		info = (struct object_id_info *)(rsp->Buffer);
6102 
6103 		if (path.mnt->mnt_sb->s_uuid_len == 16)
6104 			memcpy(info->objid, path.mnt->mnt_sb->s_uuid.b,
6105 					path.mnt->mnt_sb->s_uuid_len);
6106 		else
6107 			memcpy(info->objid, &stfs.f_fsid, sizeof(stfs.f_fsid));
6108 
6109 		info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
6110 		info->extended_info.version = cpu_to_le32(1);
6111 		info->extended_info.release = cpu_to_le32(1);
6112 		info->extended_info.rel_date = 0;
6113 		memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
6114 		rsp->OutputBufferLength = cpu_to_le32(64);
6115 		break;
6116 	}
6117 	case FS_SECTOR_SIZE_INFORMATION:
6118 	{
6119 		struct smb3_fs_ss_info *info;
6120 		unsigned int sector_size =
6121 			min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
6122 
6123 		info = (struct smb3_fs_ss_info *)(rsp->Buffer);
6124 
6125 		info->LogicalBytesPerSector = cpu_to_le32(sector_size);
6126 		info->PhysicalBytesPerSectorForAtomicity =
6127 				cpu_to_le32(sector_size);
6128 		info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
6129 		info->FSEffPhysicalBytesPerSectorForAtomicity =
6130 				cpu_to_le32(sector_size);
6131 		info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
6132 				    SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
6133 		info->ByteOffsetForSectorAlignment = 0;
6134 		info->ByteOffsetForPartitionAlignment = 0;
6135 		rsp->OutputBufferLength = cpu_to_le32(28);
6136 		break;
6137 	}
6138 	case FS_CONTROL_INFORMATION:
6139 	{
6140 		/*
6141 		 * TODO : The current implementation is based on
6142 		 * test result with win7(NTFS) server. It's need to
6143 		 * modify this to get valid Quota values
6144 		 * from Linux kernel
6145 		 */
6146 		struct smb2_fs_control_info *info;
6147 
6148 		info = (struct smb2_fs_control_info *)(rsp->Buffer);
6149 		info->FreeSpaceStartFiltering = 0;
6150 		info->FreeSpaceThreshold = 0;
6151 		info->FreeSpaceStopFiltering = 0;
6152 		info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
6153 		info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
6154 		info->Padding = 0;
6155 		rsp->OutputBufferLength = cpu_to_le32(48);
6156 		break;
6157 	}
6158 	case FS_POSIX_INFORMATION:
6159 	{
6160 		FILE_SYSTEM_POSIX_INFO *info;
6161 
6162 		if (!work->tcon->posix_extensions) {
6163 			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
6164 			path_put(&path);
6165 			return -EOPNOTSUPP;
6166 		} else {
6167 			info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
6168 			info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
6169 			info->BlockSize = cpu_to_le32(stfs.f_bsize);
6170 			info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
6171 			info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
6172 			info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
6173 			info->TotalFileNodes = cpu_to_le64(stfs.f_files);
6174 			info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
6175 			rsp->OutputBufferLength = cpu_to_le32(56);
6176 		}
6177 		break;
6178 	}
6179 	default:
6180 		path_put(&path);
6181 		return -EOPNOTSUPP;
6182 	}
6183 	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
6184 			      rsp, work->response_buf);
6185 	path_put(&path);
6186 
6187 	if (!rc)
6188 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6189 				offsetof(struct smb2_query_info_rsp, Buffer) +
6190 				le32_to_cpu(rsp->OutputBufferLength));
6191 	return rc;
6192 }
6193 
6194 static int smb2_get_info_sec(struct ksmbd_work *work,
6195 			     struct smb2_query_info_req *req,
6196 			     struct smb2_query_info_rsp *rsp)
6197 {
6198 	struct ksmbd_file *fp;
6199 	struct mnt_idmap *idmap;
6200 	struct smb_ntsd *pntsd = NULL, *ppntsd = NULL;
6201 	struct smb_fattr fattr = {{0}};
6202 	struct inode *inode;
6203 	__u32 secdesclen = 0;
6204 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6205 	int addition_info = le32_to_cpu(req->AdditionalInformation);
6206 	int rc = 0, ppntsd_size = 0, max_len;
6207 	size_t scratch_len = 0;
6208 
6209 	if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
6210 			      PROTECTED_DACL_SECINFO |
6211 			      UNPROTECTED_DACL_SECINFO)) {
6212 		ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
6213 		       addition_info);
6214 
6215 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6216 		return -EINVAL;
6217 	}
6218 
6219 	if (work->next_smb2_rcv_hdr_off) {
6220 		if (!has_file_id(req->VolatileFileId)) {
6221 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6222 				    work->compound_fid);
6223 			id = work->compound_fid;
6224 			pid = work->compound_pfid;
6225 		}
6226 	}
6227 
6228 	if (!has_file_id(id)) {
6229 		id = req->VolatileFileId;
6230 		pid = req->PersistentFileId;
6231 	}
6232 
6233 	fp = ksmbd_lookup_fd_slow(work, id, pid);
6234 	if (!fp)
6235 		return -ENOENT;
6236 
6237 	idmap = file_mnt_idmap(fp->filp);
6238 	inode = file_inode(fp->filp);
6239 	ksmbd_acls_fattr(&fattr, idmap, inode);
6240 
6241 	if (test_share_config_flag(work->tcon->share_conf,
6242 				   KSMBD_SHARE_FLAG_ACL_XATTR))
6243 		ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
6244 						     fp->filp->f_path.dentry,
6245 						     &ppntsd);
6246 
6247 	/* Check if sd buffer size exceeds response buffer size */
6248 	max_len = smb2_calc_max_out_buf_len(work,
6249 			offsetof(struct smb2_query_info_rsp, Buffer),
6250 			le32_to_cpu(req->OutputBufferLength));
6251 	if (max_len < 0) {
6252 		rc = -EINVAL;
6253 		goto release_acl;
6254 	}
6255 
6256 	scratch_len = smb_acl_sec_desc_scratch_len(&fattr, ppntsd,
6257 			ppntsd_size, addition_info);
6258 	if (!scratch_len || scratch_len == SIZE_MAX) {
6259 		rc = -EFBIG;
6260 		goto release_acl;
6261 	}
6262 
6263 	pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
6264 	if (!pntsd) {
6265 		rc = -ENOMEM;
6266 		goto release_acl;
6267 	}
6268 
6269 	rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
6270 			addition_info, &secdesclen, &fattr);
6271 
6272 release_acl:
6273 	posix_acl_release(fattr.cf_acls);
6274 	posix_acl_release(fattr.cf_dacls);
6275 	kfree(ppntsd);
6276 	ksmbd_fd_put(work, fp);
6277 
6278 	if (!rc && ALIGN(secdesclen, 8) > scratch_len)
6279 		rc = -EFBIG;
6280 	if (rc)
6281 		goto err_out;
6282 
6283 	rsp->OutputBufferLength = cpu_to_le32(secdesclen);
6284 	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
6285 			      rsp, work->response_buf);
6286 	if (rc)
6287 		goto err_out;
6288 
6289 	rc = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6290 			offsetof(struct smb2_query_info_rsp, Buffer),
6291 			pntsd, secdesclen);
6292 err_out:
6293 	if (rc) {
6294 		rsp->OutputBufferLength = 0;
6295 		kvfree(pntsd);
6296 	}
6297 
6298 	return rc;
6299 }
6300 
6301 /**
6302  * smb2_query_info() - handler for smb2 query info command
6303  * @work:	smb work containing query info request buffer
6304  *
6305  * Return:	0 on success, otherwise error
6306  */
6307 int smb2_query_info(struct ksmbd_work *work)
6308 {
6309 	struct smb2_query_info_req *req;
6310 	struct smb2_query_info_rsp *rsp;
6311 	int rc = 0;
6312 
6313 	ksmbd_debug(SMB, "Received request smb2 query info request\n");
6314 
6315 	WORK_BUFFERS(work, req, rsp);
6316 
6317 	if (smb2_compound_has_failed(work, &rsp->hdr))
6318 		return -EACCES;
6319 
6320 	if (ksmbd_override_fsids(work)) {
6321 		rc = -ENOMEM;
6322 		goto err_out;
6323 	}
6324 
6325 	rsp->StructureSize = cpu_to_le16(9);
6326 	rsp->OutputBufferOffset = cpu_to_le16(72);
6327 
6328 	switch (req->InfoType) {
6329 	case SMB2_O_INFO_FILE:
6330 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6331 		rc = smb2_get_info_file(work, req, rsp);
6332 		break;
6333 	case SMB2_O_INFO_FILESYSTEM:
6334 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
6335 		rc = smb2_get_info_filesystem(work, req, rsp);
6336 		break;
6337 	case SMB2_O_INFO_SECURITY:
6338 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6339 		rc = smb2_get_info_sec(work, req, rsp);
6340 		break;
6341 	default:
6342 		ksmbd_debug(SMB, "InfoType %d not supported yet\n",
6343 			    req->InfoType);
6344 		rc = -EOPNOTSUPP;
6345 	}
6346 	ksmbd_revert_fsids(work);
6347 
6348 err_out:
6349 	if (rc < 0) {
6350 		if (rc == -EACCES)
6351 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
6352 		else if (rc == -ENOENT)
6353 			rsp->hdr.Status = STATUS_FILE_CLOSED;
6354 		else if (rc == -EIO)
6355 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6356 		else if (rc == -ENOMEM)
6357 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
6358 		else if (rc == -EINVAL && rsp->hdr.Status == 0)
6359 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6360 		else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
6361 			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6362 		smb2_set_err_rsp(work);
6363 
6364 		ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
6365 			    rc);
6366 		return rc;
6367 	}
6368 	return 0;
6369 }
6370 
6371 /**
6372  * smb2_close_pipe() - handler for closing IPC pipe
6373  * @work:	smb work containing close request buffer
6374  *
6375  * Return:	0
6376  */
6377 static noinline int smb2_close_pipe(struct ksmbd_work *work)
6378 {
6379 	u64 id;
6380 	struct smb2_close_req *req;
6381 	struct smb2_close_rsp *rsp;
6382 
6383 	WORK_BUFFERS(work, req, rsp);
6384 
6385 	id = req->VolatileFileId;
6386 	ksmbd_session_rpc_close(work->sess, id);
6387 
6388 	rsp->StructureSize = cpu_to_le16(60);
6389 	rsp->Flags = 0;
6390 	rsp->Reserved = 0;
6391 	rsp->CreationTime = 0;
6392 	rsp->LastAccessTime = 0;
6393 	rsp->LastWriteTime = 0;
6394 	rsp->ChangeTime = 0;
6395 	rsp->AllocationSize = 0;
6396 	rsp->EndOfFile = 0;
6397 	rsp->Attributes = 0;
6398 
6399 	return ksmbd_iov_pin_rsp(work, (void *)rsp,
6400 				 sizeof(struct smb2_close_rsp));
6401 }
6402 
6403 /**
6404  * smb2_close() - handler for smb2 close file command
6405  * @work:	smb work containing close request buffer
6406  *
6407  * Return:	0 on success, otherwise error
6408  */
6409 int smb2_close(struct ksmbd_work *work)
6410 {
6411 	u64 volatile_id = KSMBD_NO_FID;
6412 	u64 sess_id;
6413 	struct smb2_close_req *req;
6414 	struct smb2_close_rsp *rsp;
6415 	struct ksmbd_conn *conn = work->conn;
6416 	struct ksmbd_file *fp;
6417 	u64 time;
6418 	int err = 0;
6419 
6420 	ksmbd_debug(SMB, "Received smb2 close request\n");
6421 
6422 	WORK_BUFFERS(work, req, rsp);
6423 
6424 	if (smb2_compound_has_failed(work, &rsp->hdr))
6425 		return -EACCES;
6426 
6427 	if (test_share_config_flag(work->tcon->share_conf,
6428 				   KSMBD_SHARE_FLAG_PIPE)) {
6429 		ksmbd_debug(SMB, "IPC pipe close request\n");
6430 		return smb2_close_pipe(work);
6431 	}
6432 
6433 	sess_id = le64_to_cpu(req->hdr.SessionId);
6434 	if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
6435 		sess_id = work->compound_sid;
6436 
6437 	work->compound_sid = 0;
6438 	if (check_session_id(conn, sess_id)) {
6439 		work->compound_sid = sess_id;
6440 	} else {
6441 		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
6442 		if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
6443 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6444 		err = -EBADF;
6445 		goto out;
6446 	}
6447 
6448 	if (work->next_smb2_rcv_hdr_off &&
6449 	    !has_file_id(req->VolatileFileId)) {
6450 		if (!has_file_id(work->compound_fid)) {
6451 			/* file already closed, return FILE_CLOSED */
6452 			ksmbd_debug(SMB, "file already closed\n");
6453 			rsp->hdr.Status = STATUS_FILE_CLOSED;
6454 			err = -EBADF;
6455 			goto out;
6456 		} else {
6457 			ksmbd_debug(SMB,
6458 				    "Compound request set FID = %llu:%llu\n",
6459 				    work->compound_fid,
6460 				    work->compound_pfid);
6461 			volatile_id = work->compound_fid;
6462 
6463 			/* file closed, stored id is not valid anymore */
6464 			work->compound_fid = KSMBD_NO_FID;
6465 			work->compound_pfid = KSMBD_NO_FID;
6466 		}
6467 	} else {
6468 		volatile_id = req->VolatileFileId;
6469 	}
6470 	ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
6471 
6472 	rsp->StructureSize = cpu_to_le16(60);
6473 	rsp->Reserved = 0;
6474 
6475 	if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
6476 		struct kstat stat;
6477 		int ret;
6478 
6479 		fp = ksmbd_lookup_fd_fast(work, volatile_id);
6480 		if (!fp) {
6481 			err = -ENOENT;
6482 			goto out;
6483 		}
6484 
6485 		ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6486 				  AT_STATX_SYNC_AS_STAT);
6487 		if (ret) {
6488 			ksmbd_fd_put(work, fp);
6489 			goto out;
6490 		}
6491 
6492 		rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
6493 		rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
6494 		rsp->EndOfFile = cpu_to_le64(stat.size);
6495 		rsp->Attributes = fp->f_ci->m_fattr;
6496 		rsp->CreationTime = cpu_to_le64(fp->create_time);
6497 		time = ksmbd_UnixTimeToNT(stat.atime);
6498 		rsp->LastAccessTime = cpu_to_le64(time);
6499 		time = ksmbd_UnixTimeToNT(stat.mtime);
6500 		if (time > fp->open_mtime &&
6501 		    time - fp->open_mtime < KSMBD_WRITE_TIME_RESOLUTION)
6502 			time = fp->open_mtime;
6503 		rsp->LastWriteTime = cpu_to_le64(time);
6504 		rsp->ChangeTime = cpu_to_le64(fp->change_time);
6505 		ksmbd_fd_put(work, fp);
6506 	} else {
6507 		rsp->Flags = 0;
6508 		rsp->AllocationSize = 0;
6509 		rsp->EndOfFile = 0;
6510 		rsp->Attributes = 0;
6511 		rsp->CreationTime = 0;
6512 		rsp->LastAccessTime = 0;
6513 		rsp->LastWriteTime = 0;
6514 		rsp->ChangeTime = 0;
6515 	}
6516 
6517 	err = ksmbd_close_fd(work, volatile_id);
6518 out:
6519 	if (!err)
6520 		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6521 					sizeof(struct smb2_close_rsp));
6522 
6523 	if (err) {
6524 		if (rsp->hdr.Status == 0)
6525 			rsp->hdr.Status = STATUS_FILE_CLOSED;
6526 		smb2_set_err_rsp(work);
6527 	}
6528 
6529 	return err;
6530 }
6531 
6532 /**
6533  * smb2_echo() - handler for smb2 echo(ping) command
6534  * @work:	smb work containing echo request buffer
6535  *
6536  * Return:	0 on success, otherwise error
6537  */
6538 int smb2_echo(struct ksmbd_work *work)
6539 {
6540 	struct smb2_echo_rsp *rsp = smb_get_msg(work->response_buf);
6541 
6542 	ksmbd_debug(SMB, "Received smb2 echo request\n");
6543 
6544 	if (work->next_smb2_rcv_hdr_off)
6545 		rsp = ksmbd_resp_buf_next(work);
6546 
6547 	rsp->StructureSize = cpu_to_le16(4);
6548 	rsp->Reserved = 0;
6549 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
6550 }
6551 
6552 static int smb2_rename(struct ksmbd_work *work,
6553 		       struct ksmbd_file *fp,
6554 		       struct smb2_file_rename_info *file_info,
6555 		       struct nls_table *local_nls)
6556 {
6557 	struct ksmbd_share_config *share = fp->tcon->share_conf;
6558 	char *new_name = NULL;
6559 	int rc, flags = 0;
6560 
6561 	ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
6562 	new_name = smb2_get_name(file_info->FileName,
6563 				 le32_to_cpu(file_info->FileNameLength),
6564 				 local_nls);
6565 	if (IS_ERR(new_name))
6566 		return PTR_ERR(new_name);
6567 
6568 	if (fp->is_posix_ctxt == false && strchr(new_name, ':')) {
6569 		int s_type;
6570 		char *xattr_stream_name, *stream_name = NULL;
6571 		size_t xattr_stream_size;
6572 		int len;
6573 
6574 		rc = parse_stream_name(new_name, &stream_name, &s_type);
6575 		if (rc < 0)
6576 			goto out;
6577 
6578 		len = strlen(new_name);
6579 		if (len > 0 && new_name[len - 1] != '/') {
6580 			pr_err("not allow base filename in rename\n");
6581 			rc = -ESHARE;
6582 			goto out;
6583 		}
6584 
6585 		rc = ksmbd_vfs_xattr_stream_name(stream_name,
6586 						 &xattr_stream_name,
6587 						 &xattr_stream_size,
6588 						 s_type);
6589 		if (rc)
6590 			goto out;
6591 
6592 		rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
6593 					&fp->filp->f_path,
6594 					xattr_stream_name,
6595 					NULL, 0, 0, true);
6596 		if (rc < 0) {
6597 			pr_err("failed to store stream name in xattr: %d\n",
6598 			       rc);
6599 			rc = -EINVAL;
6600 		}
6601 		kfree(xattr_stream_name);
6602 		goto out;
6603 	}
6604 
6605 	ksmbd_debug(SMB, "new name %s\n", new_name);
6606 	if (ksmbd_share_veto_filename(share, new_name)) {
6607 		rc = -ENOENT;
6608 		ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
6609 		goto out;
6610 	}
6611 
6612 	if (!file_info->ReplaceIfExists)
6613 		flags = RENAME_NOREPLACE;
6614 
6615 	rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
6616 	if (!rc)
6617 		smb_break_all_levII_oplock(work, fp, 0);
6618 out:
6619 	kfree(new_name);
6620 	return rc;
6621 }
6622 
6623 static int smb2_create_link(struct ksmbd_work *work,
6624 			    struct ksmbd_share_config *share,
6625 			    struct smb2_file_link_info *file_info,
6626 			    unsigned int buf_len, struct file *filp,
6627 			    struct nls_table *local_nls)
6628 {
6629 	char *link_name = NULL, *target_name = NULL, *pathname = NULL;
6630 	struct path path;
6631 	int rc;
6632 
6633 	if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
6634 			le32_to_cpu(file_info->FileNameLength))
6635 		return -EINVAL;
6636 
6637 	ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
6638 	pathname = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
6639 	if (!pathname)
6640 		return -ENOMEM;
6641 
6642 	link_name = smb2_get_name(file_info->FileName,
6643 				  le32_to_cpu(file_info->FileNameLength),
6644 				  local_nls);
6645 	if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
6646 		rc = -EINVAL;
6647 		goto out;
6648 	}
6649 
6650 	ksmbd_debug(SMB, "link name is %s\n", link_name);
6651 	target_name = file_path(filp, pathname, PATH_MAX);
6652 	if (IS_ERR(target_name)) {
6653 		rc = -EINVAL;
6654 		goto out;
6655 	}
6656 
6657 	ksmbd_debug(SMB, "target name is %s\n", target_name);
6658 	rc = ksmbd_vfs_kern_path_start_removing(work, link_name, LOOKUP_NO_SYMLINKS,
6659 						&path, 0);
6660 	if (rc) {
6661 		if (rc != -ENOENT)
6662 			goto out;
6663 	} else {
6664 		if (file_info->ReplaceIfExists) {
6665 			rc = ksmbd_vfs_remove_file(work, &path);
6666 			if (rc) {
6667 				rc = -EINVAL;
6668 				ksmbd_debug(SMB, "cannot delete %s\n",
6669 					    link_name);
6670 			}
6671 		} else {
6672 			rc = -EEXIST;
6673 			ksmbd_debug(SMB, "link already exists\n");
6674 		}
6675 		ksmbd_vfs_kern_path_end_removing(&path);
6676 		if (rc)
6677 			goto out;
6678 	}
6679 	rc = ksmbd_vfs_link(work, target_name, link_name);
6680 	if (rc)
6681 		rc = -EINVAL;
6682 out:
6683 
6684 	if (!IS_ERR(link_name))
6685 		kfree(link_name);
6686 	kfree(pathname);
6687 	return rc;
6688 }
6689 
6690 static int set_file_basic_info(struct ksmbd_file *fp,
6691 			       struct file_basic_info *file_info,
6692 			       struct ksmbd_share_config *share)
6693 {
6694 	struct iattr attrs;
6695 	struct file *filp;
6696 	struct inode *inode;
6697 	struct mnt_idmap *idmap;
6698 	int rc = 0;
6699 
6700 	if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
6701 		return -EACCES;
6702 
6703 	attrs.ia_valid = 0;
6704 	filp = fp->filp;
6705 	inode = file_inode(filp);
6706 	idmap = file_mnt_idmap(filp);
6707 
6708 	if (file_info->CreationTime)
6709 		fp->create_time = le64_to_cpu(file_info->CreationTime);
6710 
6711 	if (file_info->LastAccessTime) {
6712 		attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
6713 		attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
6714 	}
6715 
6716 	if (file_info->ChangeTime) {
6717 		fp->change_time = le64_to_cpu(file_info->ChangeTime);
6718 		inode_set_ctime_to_ts(inode,
6719 				ksmbd_NTtimeToUnix(file_info->ChangeTime));
6720 	}
6721 
6722 	if (file_info->LastWriteTime) {
6723 		attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
6724 		attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME);
6725 	}
6726 
6727 	if (file_info->Attributes) {
6728 		if (!S_ISDIR(inode->i_mode) &&
6729 		    file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
6730 			pr_err("can't change a file to a directory\n");
6731 			return -EINVAL;
6732 		}
6733 
6734 		if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
6735 			fp->f_ci->m_fattr = file_info->Attributes |
6736 				(fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
6737 	}
6738 
6739 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
6740 	    (file_info->CreationTime || file_info->Attributes)) {
6741 		struct xattr_dos_attrib da = {0};
6742 
6743 		da.version = 4;
6744 		da.itime = fp->itime;
6745 		da.create_time = fp->create_time;
6746 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
6747 		da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
6748 			XATTR_DOSINFO_ITIME;
6749 
6750 		rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
6751 				true);
6752 		if (rc)
6753 			ksmbd_debug(SMB,
6754 				    "failed to restore file attribute in EA\n");
6755 		rc = 0;
6756 	}
6757 
6758 	if (attrs.ia_valid) {
6759 		struct dentry *dentry = filp->f_path.dentry;
6760 		struct inode *inode = d_inode(dentry);
6761 
6762 		if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
6763 			return -EACCES;
6764 
6765 		inode_lock(inode);
6766 		rc = notify_change(idmap, dentry, &attrs, NULL);
6767 		inode_unlock(inode);
6768 	}
6769 	return rc;
6770 }
6771 
6772 static int set_file_allocation_info(struct ksmbd_work *work,
6773 				    struct ksmbd_file *fp,
6774 				    struct smb2_file_alloc_info *file_alloc_info)
6775 {
6776 	/*
6777 	 * TODO : It's working fine only when store dos attributes
6778 	 * is not yes. need to implement a logic which works
6779 	 * properly with any smb.conf option
6780 	 */
6781 
6782 	loff_t alloc_blks;
6783 	u64 alloc_size;
6784 	struct inode *inode;
6785 	struct kstat stat;
6786 	int rc;
6787 
6788 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
6789 		return -EACCES;
6790 
6791 	if (ksmbd_stream_fd(fp) == true)
6792 		return 0;
6793 
6794 	rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6795 			 AT_STATX_SYNC_AS_STAT);
6796 	if (rc)
6797 		return rc;
6798 
6799 	/*
6800 	 * AllocationSize is fully client-controlled (the caller only
6801 	 * validates the fixed 8-byte buffer length). Reject values that
6802 	 * would overflow the "round up to 512-byte blocks" conversion
6803 	 * below instead of silently wrapping it to a tiny block count,
6804 	 * which would truncate the file to a size the client never
6805 	 * asked for.
6806 	 */
6807 	alloc_size = le64_to_cpu(file_alloc_info->AllocationSize);
6808 	if (alloc_size > MAX_LFS_FILESIZE - 511)
6809 		return -EINVAL;
6810 
6811 	alloc_blks = (alloc_size + 511) >> 9;
6812 	inode = file_inode(fp->filp);
6813 
6814 	if (alloc_blks > stat.blocks) {
6815 		smb_break_all_levII_oplock(work, fp, 1);
6816 		rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
6817 				   alloc_blks * 512);
6818 		if (rc && rc != -EOPNOTSUPP) {
6819 			pr_err("vfs_fallocate is failed : %d\n", rc);
6820 			return rc;
6821 		}
6822 	} else if (alloc_blks < stat.blocks) {
6823 		loff_t size;
6824 
6825 		/*
6826 		 * Allocation size could be smaller than original one
6827 		 * which means allocated blocks in file should be
6828 		 * deallocated. use truncate to cut out it, but inode
6829 		 * size is also updated with truncate offset.
6830 		 * inode size is retained by backup inode size.
6831 		 */
6832 		size = i_size_read(inode);
6833 		rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
6834 		if (rc) {
6835 			pr_err("truncate failed!, err %d\n", rc);
6836 			return rc;
6837 		}
6838 		if (size < alloc_blks * 512)
6839 			i_size_write(inode, size);
6840 	}
6841 
6842 	fp->allocation_size = le64_to_cpu(file_alloc_info->AllocationSize);
6843 	return 0;
6844 }
6845 
6846 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6847 				struct smb2_file_eof_info *file_eof_info)
6848 {
6849 	loff_t newsize;
6850 	struct inode *inode;
6851 	int rc;
6852 
6853 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
6854 		return -EACCES;
6855 
6856 	newsize = le64_to_cpu(file_eof_info->EndOfFile);
6857 	inode = file_inode(fp->filp);
6858 
6859 	/*
6860 	 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
6861 	 * on FAT32 shared device, truncate execution time is too long
6862 	 * and network error could cause from windows client. because
6863 	 * truncate of some filesystem like FAT32 fill zero data in
6864 	 * truncated range.
6865 	 */
6866 	if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC &&
6867 	    ksmbd_stream_fd(fp) == false) {
6868 		ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
6869 		rc = ksmbd_vfs_truncate(work, fp, newsize);
6870 		if (rc) {
6871 			ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
6872 			if (rc != -EAGAIN)
6873 				rc = -EBADF;
6874 			return rc;
6875 		}
6876 	}
6877 	return 0;
6878 }
6879 
6880 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6881 			   struct smb2_file_rename_info *rename_info,
6882 			   unsigned int buf_len)
6883 {
6884 	if (!(fp->daccess & FILE_DELETE_LE)) {
6885 		pr_err("no right to delete : 0x%x\n", fp->daccess);
6886 		return -EACCES;
6887 	}
6888 
6889 	if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
6890 			le32_to_cpu(rename_info->FileNameLength))
6891 		return -EINVAL;
6892 
6893 	if (!le32_to_cpu(rename_info->FileNameLength))
6894 		return -EINVAL;
6895 
6896 	return smb2_rename(work, fp, rename_info, work->conn->local_nls);
6897 }
6898 
6899 static int set_file_disposition_info(struct ksmbd_work *work,
6900 				     struct ksmbd_file *fp,
6901 				     struct smb2_file_disposition_info *file_info)
6902 {
6903 	struct inode *inode;
6904 
6905 	if (!(fp->daccess & FILE_DELETE_LE)) {
6906 		pr_err("no right to delete : 0x%x\n", fp->daccess);
6907 		return -EACCES;
6908 	}
6909 
6910 	inode = file_inode(fp->filp);
6911 	if (file_info->DeletePending) {
6912 		if (ksmbd_has_stream_without_delete_share(fp))
6913 			return -ESHARE;
6914 
6915 		if (S_ISDIR(inode->i_mode) &&
6916 		    ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
6917 			return -EBUSY;
6918 		smb_break_all_levII_oplock_for_delete(work, fp);
6919 		ksmbd_set_inode_pending_delete(fp);
6920 	} else {
6921 		ksmbd_clear_inode_pending_delete(fp);
6922 	}
6923 	return 0;
6924 }
6925 
6926 static int set_file_position_info(struct ksmbd_file *fp,
6927 				  struct smb2_file_pos_info *file_info)
6928 {
6929 	loff_t current_byte_offset;
6930 	unsigned long sector_size;
6931 	struct inode *inode;
6932 
6933 	inode = file_inode(fp->filp);
6934 	current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
6935 	sector_size = inode->i_sb->s_blocksize;
6936 
6937 	if (current_byte_offset < 0 ||
6938 	    (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
6939 	     current_byte_offset & (sector_size - 1))) {
6940 		pr_err("CurrentByteOffset is not valid : %llu\n",
6941 		       current_byte_offset);
6942 		return -EINVAL;
6943 	}
6944 
6945 	if (ksmbd_stream_fd(fp) == false)
6946 		fp->filp->f_pos = current_byte_offset;
6947 	else {
6948 		if (current_byte_offset > XATTR_SIZE_MAX)
6949 			current_byte_offset = XATTR_SIZE_MAX;
6950 		fp->stream.pos = current_byte_offset;
6951 	}
6952 	return 0;
6953 }
6954 
6955 static int set_file_mode_info(struct ksmbd_file *fp,
6956 			      struct smb2_file_mode_info *file_info)
6957 {
6958 	__le32 mode;
6959 
6960 	mode = file_info->Mode;
6961 
6962 	if ((mode & ~FILE_MODE_INFO_MASK)) {
6963 		pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
6964 		return -EINVAL;
6965 	}
6966 
6967 	/*
6968 	 * TODO : need to implement consideration for
6969 	 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
6970 	 */
6971 	ksmbd_vfs_set_fadvise(fp->filp, mode);
6972 	fp->coption = mode;
6973 	return 0;
6974 }
6975 
6976 /**
6977  * smb2_set_info_file() - handler for smb2 set info command
6978  * @work:	smb work containing set info command buffer
6979  * @fp:		ksmbd_file pointer
6980  * @req:	request buffer pointer
6981  * @share:	ksmbd_share_config pointer
6982  *
6983  * Return:	0 on success, otherwise error
6984  */
6985 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
6986 			      struct smb2_set_info_req *req,
6987 			      struct ksmbd_share_config *share)
6988 {
6989 	unsigned int buf_len = le32_to_cpu(req->BufferLength);
6990 	char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
6991 
6992 	switch (req->FileInfoClass) {
6993 	case FILE_BASIC_INFORMATION:
6994 	{
6995 		if (buf_len < sizeof(struct file_basic_info))
6996 			return -EMSGSIZE;
6997 
6998 		return set_file_basic_info(fp, (struct file_basic_info *)buffer, share);
6999 	}
7000 	case FILE_ALLOCATION_INFORMATION:
7001 	{
7002 		if (buf_len < sizeof(struct smb2_file_alloc_info))
7003 			return -EMSGSIZE;
7004 
7005 		return set_file_allocation_info(work, fp,
7006 						(struct smb2_file_alloc_info *)buffer);
7007 	}
7008 	case FILE_END_OF_FILE_INFORMATION:
7009 	{
7010 		if (buf_len < sizeof(struct smb2_file_eof_info))
7011 			return -EMSGSIZE;
7012 
7013 		return set_end_of_file_info(work, fp,
7014 					    (struct smb2_file_eof_info *)buffer);
7015 	}
7016 	case FILE_RENAME_INFORMATION:
7017 	{
7018 		if (buf_len < sizeof(struct smb2_file_rename_info))
7019 			return -EMSGSIZE;
7020 
7021 		return set_rename_info(work, fp,
7022 				       (struct smb2_file_rename_info *)buffer,
7023 				       buf_len);
7024 	}
7025 	case FILE_LINK_INFORMATION:
7026 	{
7027 		struct smb2_file_link_info *file_info;
7028 
7029 		if (buf_len < sizeof(struct smb2_file_link_info))
7030 			return -EMSGSIZE;
7031 
7032 		file_info = (struct smb2_file_link_info *)buffer;
7033 		if (file_info->ReplaceIfExists && !(fp->daccess & FILE_DELETE_LE)) {
7034 			pr_err("no right to delete : 0x%x\n", fp->daccess);
7035 			return -EACCES;
7036 		}
7037 
7038 		return smb2_create_link(work, work->tcon->share_conf, file_info,
7039 					buf_len, fp->filp,
7040 					work->conn->local_nls);
7041 	}
7042 	case FILE_DISPOSITION_INFORMATION:
7043 	{
7044 		if (buf_len < sizeof(struct smb2_file_disposition_info))
7045 			return -EMSGSIZE;
7046 
7047 		return set_file_disposition_info(work, fp,
7048 						 (struct smb2_file_disposition_info *)buffer);
7049 	}
7050 	case FILE_FULL_EA_INFORMATION:
7051 	{
7052 		if (!(fp->daccess & FILE_WRITE_EA_LE)) {
7053 			pr_err("Not permitted to write ext  attr: 0x%x\n",
7054 			       fp->daccess);
7055 			return -EACCES;
7056 		}
7057 
7058 		if (buf_len < sizeof(struct smb2_ea_info))
7059 			return -EMSGSIZE;
7060 
7061 		return smb2_set_ea((struct smb2_ea_info *)buffer,
7062 				   buf_len, &fp->filp->f_path, true);
7063 	}
7064 	case FILE_POSITION_INFORMATION:
7065 	{
7066 		if (buf_len < sizeof(struct smb2_file_pos_info))
7067 			return -EMSGSIZE;
7068 
7069 		return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
7070 	}
7071 	case FILE_MODE_INFORMATION:
7072 	{
7073 		if (buf_len < sizeof(struct smb2_file_mode_info))
7074 			return -EMSGSIZE;
7075 
7076 		return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
7077 	}
7078 	}
7079 
7080 	pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
7081 	return -EOPNOTSUPP;
7082 }
7083 
7084 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
7085 			     char *buffer, int buf_len)
7086 {
7087 	struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
7088 
7089 	fp->saccess |= FILE_SHARE_DELETE_LE;
7090 
7091 	if (!(fp->daccess & (FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE)))
7092 		return -EACCES;
7093 
7094 	return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
7095 			buf_len, false, true);
7096 }
7097 
7098 /**
7099  * smb2_set_info() - handler for smb2 set info command handler
7100  * @work:	smb work containing set info request buffer
7101  *
7102  * Return:	0 on success, otherwise error
7103  */
7104 int smb2_set_info(struct ksmbd_work *work)
7105 {
7106 	const struct cred *saved_cred;
7107 	struct smb2_set_info_req *req;
7108 	struct smb2_set_info_rsp *rsp;
7109 	struct ksmbd_file *fp = NULL;
7110 	int rc = 0;
7111 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7112 
7113 	ksmbd_debug(SMB, "Received smb2 set info request\n");
7114 
7115 	if (work->next_smb2_rcv_hdr_off) {
7116 		req = ksmbd_req_buf_next(work);
7117 		rsp = ksmbd_resp_buf_next(work);
7118 		if (smb2_compound_has_failed(work, &rsp->hdr))
7119 			return -EACCES;
7120 		if (!has_file_id(req->VolatileFileId)) {
7121 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7122 				    work->compound_fid);
7123 			id = work->compound_fid;
7124 			pid = work->compound_pfid;
7125 		}
7126 	} else {
7127 		req = smb_get_msg(work->request_buf);
7128 		rsp = smb_get_msg(work->response_buf);
7129 	}
7130 
7131 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7132 		ksmbd_debug(SMB, "User does not have write permission\n");
7133 		pr_err("User does not have write permission\n");
7134 		rc = -EACCES;
7135 		goto err_out;
7136 	}
7137 
7138 	if (!has_file_id(id)) {
7139 		id = req->VolatileFileId;
7140 		pid = req->PersistentFileId;
7141 	}
7142 
7143 	fp = ksmbd_lookup_fd_slow(work, id, pid);
7144 	if (!fp) {
7145 		ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
7146 		rc = -ENOENT;
7147 		goto err_out;
7148 	}
7149 
7150 	saved_cred = override_creds(fp->filp->f_cred);
7151 	switch (req->InfoType) {
7152 	case SMB2_O_INFO_FILE:
7153 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
7154 		rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
7155 		break;
7156 	case SMB2_O_INFO_SECURITY:
7157 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
7158 		rc = smb2_set_info_sec(fp,
7159 				       le32_to_cpu(req->AdditionalInformation),
7160 				       (char *)req + le16_to_cpu(req->BufferOffset),
7161 				       le32_to_cpu(req->BufferLength));
7162 		break;
7163 	default:
7164 		rc = -EOPNOTSUPP;
7165 	}
7166 	revert_creds(saved_cred);
7167 
7168 	if (rc < 0)
7169 		goto err_out;
7170 
7171 	rsp->StructureSize = cpu_to_le16(2);
7172 	rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
7173 			       sizeof(struct smb2_set_info_rsp));
7174 	if (rc)
7175 		goto err_out;
7176 	ksmbd_fd_put(work, fp);
7177 	return 0;
7178 
7179 err_out:
7180 	if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
7181 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
7182 	else if (rc == -EINVAL)
7183 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7184 	else if (rc == -EMSGSIZE)
7185 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
7186 	else if (rc == -ENOSPC || rc == -EFBIG)
7187 		rsp->hdr.Status = STATUS_DISK_FULL;
7188 	else if (rc == -ESHARE)
7189 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
7190 	else if (rc == -ENOENT)
7191 		rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
7192 	else if (rc == -EBUSY || rc == -ENOTEMPTY)
7193 		rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
7194 	else if (rc == -EAGAIN)
7195 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7196 	else if (rc == -EBADF || rc == -ESTALE)
7197 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
7198 	else if (rc == -EEXIST)
7199 		rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
7200 	else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
7201 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
7202 	smb2_set_err_rsp(work);
7203 	ksmbd_fd_put(work, fp);
7204 	ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
7205 	return rc;
7206 }
7207 
7208 /**
7209  * smb2_read_pipe() - handler for smb2 read from IPC pipe
7210  * @work:	smb work containing read IPC pipe command buffer
7211  *
7212  * Return:	0 on success, otherwise error
7213  */
7214 static noinline int smb2_read_pipe(struct ksmbd_work *work)
7215 {
7216 	int nbytes = 0, err;
7217 	u64 id;
7218 	struct ksmbd_rpc_command *rpc_resp;
7219 	struct smb2_read_req *req;
7220 	struct smb2_read_rsp *rsp;
7221 
7222 	WORK_BUFFERS(work, req, rsp);
7223 
7224 	id = req->VolatileFileId;
7225 
7226 	rpc_resp = ksmbd_rpc_read(work->sess, id);
7227 	if (rpc_resp) {
7228 		void *aux_payload_buf;
7229 
7230 		if (rpc_resp->flags != KSMBD_RPC_OK) {
7231 			err = -EINVAL;
7232 			goto out;
7233 		}
7234 
7235 		aux_payload_buf =
7236 			kvmalloc(rpc_resp->payload_sz, KSMBD_DEFAULT_GFP);
7237 		if (!aux_payload_buf) {
7238 			err = -ENOMEM;
7239 			goto out;
7240 		}
7241 
7242 		memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
7243 
7244 		nbytes = rpc_resp->payload_sz;
7245 		err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
7246 					     offsetof(struct smb2_read_rsp, Buffer),
7247 					     aux_payload_buf, nbytes);
7248 		if (err) {
7249 			kvfree(aux_payload_buf);
7250 			goto out;
7251 		}
7252 		kvfree(rpc_resp);
7253 	} else {
7254 		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
7255 					offsetof(struct smb2_read_rsp, Buffer));
7256 		if (err)
7257 			goto out;
7258 	}
7259 
7260 	rsp->StructureSize = cpu_to_le16(17);
7261 	rsp->DataOffset = 80;
7262 	rsp->Reserved = 0;
7263 	rsp->DataLength = cpu_to_le32(nbytes);
7264 	rsp->DataRemaining = 0;
7265 	rsp->Flags = 0;
7266 	return 0;
7267 
7268 out:
7269 	rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7270 	smb2_set_err_rsp(work);
7271 	kvfree(rpc_resp);
7272 	return err;
7273 }
7274 
7275 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
7276 					struct smbdirect_buffer_descriptor_v1 *desc,
7277 					__le32 Channel,
7278 					__le16 ChannelInfoLength)
7279 {
7280 	unsigned int i, ch_count;
7281 
7282 	if (work->conn->dialect == SMB30_PROT_ID &&
7283 	    Channel != SMB2_CHANNEL_RDMA_V1)
7284 		return -EINVAL;
7285 
7286 	ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
7287 	if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
7288 		for (i = 0; i < ch_count; i++) {
7289 			pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
7290 				i,
7291 				le32_to_cpu(desc[i].token),
7292 				le32_to_cpu(desc[i].length));
7293 		}
7294 	}
7295 	if (!ch_count)
7296 		return -EINVAL;
7297 
7298 	work->need_invalidate_rkey =
7299 		(Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
7300 	if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
7301 		work->remote_key = le32_to_cpu(desc->token);
7302 	return 0;
7303 }
7304 
7305 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
7306 				      struct smb2_read_req *req, void *data_buf,
7307 				      size_t length)
7308 {
7309 	int err;
7310 
7311 	err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
7312 				    (struct smbdirect_buffer_descriptor_v1 *)
7313 				    ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
7314 				    le16_to_cpu(req->ReadChannelInfoLength));
7315 	if (err)
7316 		return err;
7317 
7318 	return length;
7319 }
7320 
7321 /**
7322  * smb2_read() - handler for smb2 read from file
7323  * @work:	smb work containing read command buffer
7324  *
7325  * Return:	0 on success, otherwise error
7326  */
7327 int smb2_read(struct ksmbd_work *work)
7328 {
7329 	struct ksmbd_conn *conn = work->conn;
7330 	struct smb2_read_req *req;
7331 	struct smb2_read_rsp *rsp;
7332 	struct ksmbd_file *fp = NULL;
7333 	loff_t offset;
7334 	size_t length, mincount;
7335 	ssize_t nbytes = 0, remain_bytes = 0;
7336 	int err = 0;
7337 	bool is_rdma_channel = false, async_interim = false;
7338 	unsigned int max_read_size = conn->vals->max_read_size;
7339 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7340 	void *aux_payload_buf;
7341 
7342 	ksmbd_debug(SMB, "Received smb2 read request\n");
7343 
7344 	if (test_share_config_flag(work->tcon->share_conf,
7345 				   KSMBD_SHARE_FLAG_PIPE)) {
7346 		ksmbd_debug(SMB, "IPC pipe read request\n");
7347 		return smb2_read_pipe(work);
7348 	}
7349 
7350 	if (work->next_smb2_rcv_hdr_off) {
7351 		req = ksmbd_req_buf_next(work);
7352 		rsp = ksmbd_resp_buf_next(work);
7353 		if (smb2_compound_has_failed(work, &rsp->hdr))
7354 			return -EACCES;
7355 		if (!has_file_id(req->VolatileFileId)) {
7356 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7357 					work->compound_fid);
7358 			id = work->compound_fid;
7359 			pid = work->compound_pfid;
7360 		}
7361 	} else {
7362 		req = smb_get_msg(work->request_buf);
7363 		rsp = smb_get_msg(work->response_buf);
7364 	}
7365 
7366 	if (!has_file_id(id)) {
7367 		id = req->VolatileFileId;
7368 		pid = req->PersistentFileId;
7369 	}
7370 
7371 	if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
7372 	    req->Channel == SMB2_CHANNEL_RDMA_V1) {
7373 		is_rdma_channel = true;
7374 		max_read_size = get_smbd_max_read_write_size(work->conn->transport);
7375 		if (max_read_size == 0) {
7376 			err = -EINVAL;
7377 			goto out;
7378 		}
7379 	}
7380 
7381 	if (is_rdma_channel == true) {
7382 		unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
7383 
7384 		if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
7385 			err = -EINVAL;
7386 			goto out;
7387 		}
7388 		err = smb2_set_remote_key_for_rdma(work,
7389 						   (struct smbdirect_buffer_descriptor_v1 *)
7390 						   ((char *)req + ch_offset),
7391 						   req->Channel,
7392 						   req->ReadChannelInfoLength);
7393 		if (err)
7394 			goto out;
7395 	}
7396 
7397 	fp = ksmbd_lookup_fd_slow(work, id, pid);
7398 	if (!fp) {
7399 		err = -ENOENT;
7400 		goto out;
7401 	}
7402 
7403 	if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
7404 		pr_err("Not permitted to read : 0x%x\n", fp->daccess);
7405 		err = -EACCES;
7406 		goto out;
7407 	}
7408 
7409 	if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
7410 		err = setup_async_work(work, NULL, NULL);
7411 		if (err)
7412 			goto out;
7413 		smb2_send_interim_resp(work, STATUS_PENDING);
7414 		async_interim = true;
7415 	}
7416 
7417 	offset = le64_to_cpu(req->Offset);
7418 	if (offset < 0) {
7419 		err = -EINVAL;
7420 		goto out;
7421 	}
7422 	length = le32_to_cpu(req->Length);
7423 	mincount = le32_to_cpu(req->MinimumCount);
7424 
7425 	if (length > max_read_size) {
7426 		ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
7427 			    max_read_size);
7428 		err = -EINVAL;
7429 		goto out;
7430 	}
7431 
7432 	ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
7433 		    fp->filp, offset, length);
7434 
7435 	aux_payload_buf = kvmalloc(ALIGN(length, 8), KSMBD_DEFAULT_GFP);
7436 	if (!aux_payload_buf) {
7437 		err = -ENOMEM;
7438 		goto out;
7439 	}
7440 
7441 	nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
7442 	if (nbytes < 0) {
7443 		kvfree(aux_payload_buf);
7444 		err = nbytes;
7445 		goto out;
7446 	}
7447 
7448 	/*
7449 	 * ksmbd_vfs_read() fills only nbytes; the [nbytes, ALIGN(nbytes, 8))
7450 	 * tail of the un-zeroed buffer is transmitted as compound-response
7451 	 * alignment padding, leaking uninitialized kernel memory to the
7452 	 * client.  Zero just that tail.
7453 	 */
7454 	if (nbytes & 7)
7455 		memset(aux_payload_buf + nbytes, 0, ALIGN(nbytes, 8) - nbytes);
7456 
7457 	if ((nbytes == 0 && length != 0) || nbytes < mincount) {
7458 		kvfree(aux_payload_buf);
7459 		rsp->hdr.Status = STATUS_END_OF_FILE;
7460 		smb2_set_err_rsp(work);
7461 		if (async_interim)
7462 			release_async_work(work);
7463 		ksmbd_fd_put(work, fp);
7464 		return -ENODATA;
7465 	}
7466 
7467 	ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
7468 		    nbytes, offset, mincount);
7469 
7470 	if (is_rdma_channel == true) {
7471 		/* write data to the client using rdma channel */
7472 		remain_bytes = smb2_read_rdma_channel(work, req,
7473 						      aux_payload_buf,
7474 						      nbytes);
7475 		kvfree(aux_payload_buf);
7476 		aux_payload_buf = NULL;
7477 		nbytes = 0;
7478 		if (remain_bytes < 0) {
7479 			err = (int)remain_bytes;
7480 			goto out;
7481 		}
7482 	}
7483 
7484 	rsp->StructureSize = cpu_to_le16(17);
7485 	rsp->DataOffset = 80;
7486 	rsp->Reserved = 0;
7487 	rsp->DataLength = cpu_to_le32(nbytes);
7488 	rsp->DataRemaining = cpu_to_le32(remain_bytes);
7489 	rsp->Flags = 0;
7490 	err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
7491 				     offsetof(struct smb2_read_rsp, Buffer),
7492 				     aux_payload_buf, nbytes);
7493 	if (err) {
7494 		kvfree(aux_payload_buf);
7495 		goto out;
7496 	}
7497 	if (async_interim)
7498 		release_async_work(work);
7499 	/*
7500 	 * RDMA responses are transferred through channel buffers and encrypted
7501 	 * responses use the encryption transform, so only normal SMB transport
7502 	 * responses are candidates for compression.
7503 	 */
7504 	if (!is_rdma_channel && nbytes &&
7505 	    (req->Flags & SMB2_READFLAG_REQUEST_COMPRESSED) &&
7506 	    conn->compress_algorithm != SMB3_COMPRESS_NONE)
7507 		work->compress_response = true;
7508 	ksmbd_fd_put(work, fp);
7509 	return 0;
7510 
7511 out:
7512 	if (async_interim)
7513 		release_async_work(work);
7514 	if (err) {
7515 		if (err == -EISDIR)
7516 			rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
7517 		else if (err == -EAGAIN)
7518 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7519 		else if (err == -ENOENT)
7520 			rsp->hdr.Status = STATUS_FILE_CLOSED;
7521 		else if (err == -EACCES)
7522 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
7523 		else if (err == -ESHARE)
7524 			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
7525 		else if (err == -EINVAL)
7526 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7527 		else
7528 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
7529 
7530 		smb2_set_err_rsp(work);
7531 	}
7532 	ksmbd_fd_put(work, fp);
7533 	return err;
7534 }
7535 
7536 /**
7537  * smb2_write_pipe() - handler for smb2 write on IPC pipe
7538  * @work:	smb work containing write IPC pipe command buffer
7539  *
7540  * Return:	0 on success, otherwise error
7541  */
7542 static noinline int smb2_write_pipe(struct ksmbd_work *work)
7543 {
7544 	struct smb2_write_req *req;
7545 	struct smb2_write_rsp *rsp;
7546 	struct ksmbd_rpc_command *rpc_resp;
7547 	u64 id = 0;
7548 	int err = 0, ret = 0;
7549 	char *data_buf;
7550 	size_t length;
7551 
7552 	WORK_BUFFERS(work, req, rsp);
7553 
7554 	length = le32_to_cpu(req->Length);
7555 	id = req->VolatileFileId;
7556 
7557 	if ((u64)le16_to_cpu(req->DataOffset) + length >
7558 	    get_rfc1002_len(work->request_buf)) {
7559 		pr_err("invalid write data offset %u, smb_len %u\n",
7560 		       le16_to_cpu(req->DataOffset),
7561 		       get_rfc1002_len(work->request_buf));
7562 		err = -EINVAL;
7563 		goto out;
7564 	}
7565 
7566 	data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
7567 			   le16_to_cpu(req->DataOffset));
7568 
7569 	rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
7570 	if (rpc_resp) {
7571 		if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7572 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7573 			kvfree(rpc_resp);
7574 			smb2_set_err_rsp(work);
7575 			return -EOPNOTSUPP;
7576 		}
7577 		if (rpc_resp->flags != KSMBD_RPC_OK) {
7578 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
7579 			smb2_set_err_rsp(work);
7580 			kvfree(rpc_resp);
7581 			return ret;
7582 		}
7583 		kvfree(rpc_resp);
7584 	}
7585 
7586 	rsp->StructureSize = cpu_to_le16(17);
7587 	rsp->DataOffset = 0;
7588 	rsp->Reserved = 0;
7589 	rsp->DataLength = cpu_to_le32(length);
7590 	rsp->DataRemaining = 0;
7591 	rsp->Reserved2 = 0;
7592 	err = ksmbd_iov_pin_rsp(work, (void *)rsp,
7593 				offsetof(struct smb2_write_rsp, Buffer));
7594 out:
7595 	if (err) {
7596 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
7597 		smb2_set_err_rsp(work);
7598 	}
7599 
7600 	return err;
7601 }
7602 
7603 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
7604 				       struct smb2_write_req *req,
7605 				       struct ksmbd_file *fp,
7606 				       loff_t offset, size_t length, bool sync)
7607 {
7608 	char *data_buf;
7609 	int ret;
7610 	ssize_t nbytes;
7611 
7612 	data_buf = kvzalloc(length, KSMBD_DEFAULT_GFP);
7613 	if (!data_buf)
7614 		return -ENOMEM;
7615 
7616 	ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
7617 				   (struct smbdirect_buffer_descriptor_v1 *)
7618 				   ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
7619 				   le16_to_cpu(req->WriteChannelInfoLength));
7620 	if (ret < 0) {
7621 		kvfree(data_buf);
7622 		return ret;
7623 	}
7624 
7625 	ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
7626 	kvfree(data_buf);
7627 	if (ret < 0)
7628 		return ret;
7629 
7630 	return nbytes;
7631 }
7632 
7633 /**
7634  * smb2_write() - handler for smb2 write from file
7635  * @work:	smb work containing write command buffer
7636  *
7637  * Return:	0 on success, otherwise error
7638  */
7639 int smb2_write(struct ksmbd_work *work)
7640 {
7641 	struct smb2_write_req *req;
7642 	struct smb2_write_rsp *rsp;
7643 	struct ksmbd_file *fp = NULL;
7644 	loff_t offset;
7645 	size_t length;
7646 	ssize_t nbytes;
7647 	char *data_buf;
7648 	bool writethrough = false, is_rdma_channel = false;
7649 	bool async_interim = false;
7650 	int err = 0;
7651 	unsigned int max_write_size = work->conn->vals->max_write_size;
7652 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7653 
7654 	ksmbd_debug(SMB, "Received smb2 write request\n");
7655 
7656 	WORK_BUFFERS(work, req, rsp);
7657 
7658 	if (smb2_compound_has_failed(work, &rsp->hdr))
7659 		return -EACCES;
7660 
7661 	if (work->next_smb2_rcv_hdr_off &&
7662 	    !has_file_id(req->VolatileFileId)) {
7663 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7664 			    work->compound_fid);
7665 		id = work->compound_fid;
7666 		pid = work->compound_pfid;
7667 	}
7668 
7669 	if (!has_file_id(id)) {
7670 		id = req->VolatileFileId;
7671 		pid = req->PersistentFileId;
7672 	}
7673 
7674 	if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
7675 		ksmbd_debug(SMB, "IPC pipe write request\n");
7676 		return smb2_write_pipe(work);
7677 	}
7678 
7679 	offset = le64_to_cpu(req->Offset);
7680 	if (offset < 0)
7681 		return -EINVAL;
7682 	length = le32_to_cpu(req->Length);
7683 
7684 	if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
7685 	    req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
7686 		is_rdma_channel = true;
7687 		max_write_size = get_smbd_max_read_write_size(work->conn->transport);
7688 		if (max_write_size == 0) {
7689 			err = -EINVAL;
7690 			goto out;
7691 		}
7692 		length = le32_to_cpu(req->RemainingBytes);
7693 	}
7694 
7695 	if (is_rdma_channel == true) {
7696 		unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
7697 
7698 		if (req->Length != 0 || req->DataOffset != 0 ||
7699 		    ch_offset < offsetof(struct smb2_write_req, Buffer)) {
7700 			err = -EINVAL;
7701 			goto out;
7702 		}
7703 		err = smb2_set_remote_key_for_rdma(work,
7704 						   (struct smbdirect_buffer_descriptor_v1 *)
7705 						   ((char *)req + ch_offset),
7706 						   req->Channel,
7707 						   req->WriteChannelInfoLength);
7708 		if (err)
7709 			goto out;
7710 	}
7711 
7712 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7713 		ksmbd_debug(SMB, "User does not have write permission\n");
7714 		err = -EACCES;
7715 		goto out;
7716 	}
7717 
7718 	fp = ksmbd_lookup_fd_slow(work, id, pid);
7719 	if (!fp) {
7720 		err = -ENOENT;
7721 		goto out;
7722 	}
7723 
7724 	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
7725 		pr_err("Not permitted to write : 0x%x\n", fp->daccess);
7726 		err = -EACCES;
7727 		goto out;
7728 	}
7729 
7730 	if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
7731 		err = setup_async_work(work, NULL, NULL);
7732 		if (err)
7733 			goto out;
7734 		smb2_send_interim_resp(work, STATUS_PENDING);
7735 		async_interim = true;
7736 	}
7737 
7738 	if (length > max_write_size) {
7739 		ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
7740 			    max_write_size);
7741 		err = -EINVAL;
7742 		goto out;
7743 	}
7744 
7745 	ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
7746 	if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
7747 		writethrough = true;
7748 
7749 	if (is_rdma_channel == false) {
7750 		if (le16_to_cpu(req->DataOffset) <
7751 		    offsetof(struct smb2_write_req, Buffer)) {
7752 			err = -EINVAL;
7753 			goto out;
7754 		}
7755 
7756 		data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
7757 				    le16_to_cpu(req->DataOffset));
7758 
7759 		ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
7760 			    fp->filp, offset, length);
7761 		err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
7762 				      writethrough, &nbytes);
7763 		if (err < 0)
7764 			goto out;
7765 	} else {
7766 		/* read data from the client using rdma channel, and
7767 		 * write the data.
7768 		 */
7769 		nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
7770 						 writethrough);
7771 		if (nbytes < 0) {
7772 			err = (int)nbytes;
7773 			goto out;
7774 		}
7775 	}
7776 
7777 	rsp->StructureSize = cpu_to_le16(17);
7778 	rsp->DataOffset = 0;
7779 	rsp->Reserved = 0;
7780 	rsp->DataLength = cpu_to_le32(nbytes);
7781 	rsp->DataRemaining = 0;
7782 	rsp->Reserved2 = 0;
7783 	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
7784 	if (err)
7785 		goto out;
7786 	if (async_interim)
7787 		release_async_work(work);
7788 	ksmbd_fd_put(work, fp);
7789 	return 0;
7790 
7791 out:
7792 	if (async_interim)
7793 		release_async_work(work);
7794 
7795 	if (err == -EAGAIN)
7796 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7797 	else if (err == -ENOSPC || err == -EFBIG)
7798 		rsp->hdr.Status = STATUS_DISK_FULL;
7799 	else if (err == -ENOENT)
7800 		rsp->hdr.Status = STATUS_FILE_CLOSED;
7801 	else if (err == -EACCES)
7802 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
7803 	else if (err == -ESHARE)
7804 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
7805 	else if (err == -EINVAL)
7806 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7807 	else
7808 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
7809 
7810 	smb2_set_err_rsp(work);
7811 	ksmbd_fd_put(work, fp);
7812 	return err;
7813 }
7814 
7815 /**
7816  * smb2_flush() - handler for smb2 flush file - fsync
7817  * @work:	smb work containing flush command buffer
7818  *
7819  * Return:	0 on success, otherwise error
7820  */
7821 int smb2_flush(struct ksmbd_work *work)
7822 {
7823 	struct smb2_flush_req *req;
7824 	struct smb2_flush_rsp *rsp;
7825 	u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7826 	int err;
7827 
7828 	WORK_BUFFERS(work, req, rsp);
7829 
7830 	ksmbd_debug(SMB, "Received smb2 flush request(fid : %llu)\n", req->VolatileFileId);
7831 
7832 	if (smb2_compound_has_failed(work, &rsp->hdr))
7833 		return -EACCES;
7834 
7835 	if (work->next_smb2_rcv_hdr_off &&
7836 	    !has_file_id(req->VolatileFileId)) {
7837 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7838 			    work->compound_fid);
7839 		id = work->compound_fid;
7840 		pid = work->compound_pfid;
7841 	}
7842 
7843 	if (!has_file_id(id)) {
7844 		id = req->VolatileFileId;
7845 		pid = req->PersistentFileId;
7846 	}
7847 
7848 	err = ksmbd_vfs_fsync(work, id, pid);
7849 	if (err)
7850 		goto out;
7851 
7852 	rsp->StructureSize = cpu_to_le16(4);
7853 	rsp->Reserved = 0;
7854 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
7855 
7856 out:
7857 	rsp->hdr.Status = STATUS_INVALID_HANDLE;
7858 	smb2_set_err_rsp(work);
7859 	return err;
7860 }
7861 
7862 /**
7863  * smb2_cancel() - handler for smb2 cancel command
7864  * @work:	smb work containing cancel command buffer
7865  *
7866  * Return:	0 on success, otherwise error
7867  */
7868 int smb2_cancel(struct ksmbd_work *work)
7869 {
7870 	struct ksmbd_conn *conn = work->conn;
7871 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
7872 	struct smb2_hdr *chdr;
7873 	struct ksmbd_work *iter;
7874 	struct list_head *command_list;
7875 
7876 	if (work->next_smb2_rcv_hdr_off)
7877 		hdr = ksmbd_resp_buf_next(work);
7878 
7879 	ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
7880 		    le64_to_cpu(hdr->MessageId),
7881 		    le32_to_cpu(hdr->Flags));
7882 
7883 	if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
7884 		command_list = &conn->async_requests;
7885 
7886 		spin_lock(&conn->request_lock);
7887 		list_for_each_entry(iter, command_list,
7888 				    async_request_entry) {
7889 			chdr = smb_get_msg(iter->request_buf);
7890 
7891 			if (iter->async_id !=
7892 			    le64_to_cpu(hdr->Id.AsyncId))
7893 				continue;
7894 
7895 			/*
7896 			 * Only an ACTIVE deferred work may have its cancel_fn
7897 			 * fired.  A CANCELLED or CLOSED work already took the
7898 			 * smb2_lock() non-ACTIVE early-exit that frees the
7899 			 * file_lock and skips release_async_work(), so it is
7900 			 * still on conn->async_requests with a live cancel_fn
7901 			 * pointing at the freed file_lock.
7902 			 */
7903 			if (iter->state != KSMBD_WORK_ACTIVE)
7904 				break;
7905 
7906 			ksmbd_debug(SMB,
7907 				    "smb2 with AsyncId %llu cancelled command = 0x%x\n",
7908 				    le64_to_cpu(hdr->Id.AsyncId),
7909 				    le16_to_cpu(chdr->Command));
7910 			iter->state = KSMBD_WORK_CANCELLED;
7911 			if (iter->cancel_fn)
7912 				iter->cancel_fn(iter->cancel_argv);
7913 			break;
7914 		}
7915 		spin_unlock(&conn->request_lock);
7916 	} else {
7917 		command_list = &conn->requests;
7918 
7919 		spin_lock(&conn->request_lock);
7920 		list_for_each_entry(iter, command_list, request_entry) {
7921 			chdr = smb_get_msg(iter->request_buf);
7922 
7923 			if (chdr->MessageId != hdr->MessageId ||
7924 			    iter == work)
7925 				continue;
7926 
7927 			ksmbd_debug(SMB,
7928 				    "smb2 with mid %llu cancelled command = 0x%x\n",
7929 				    le64_to_cpu(hdr->MessageId),
7930 				    le16_to_cpu(chdr->Command));
7931 			iter->state = KSMBD_WORK_CANCELLED;
7932 			break;
7933 		}
7934 		spin_unlock(&conn->request_lock);
7935 	}
7936 
7937 	/* For SMB2_CANCEL command itself send no response*/
7938 	work->send_no_response = 1;
7939 	return 0;
7940 }
7941 
7942 struct file_lock *smb_flock_init(struct file *f)
7943 {
7944 	struct file_lock *fl;
7945 
7946 	fl = locks_alloc_lock();
7947 	if (!fl)
7948 		goto out;
7949 
7950 	locks_init_lock(fl);
7951 
7952 	fl->c.flc_owner = f;
7953 	fl->c.flc_pid = current->tgid;
7954 	fl->c.flc_file = f;
7955 	fl->c.flc_flags = FL_POSIX;
7956 	fl->fl_ops = NULL;
7957 	fl->fl_lmops = NULL;
7958 
7959 out:
7960 	return fl;
7961 }
7962 
7963 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
7964 {
7965 	int cmd = -EINVAL;
7966 
7967 	/* Checking for wrong flag combination during lock request*/
7968 	switch (flags) {
7969 	case SMB2_LOCKFLAG_SHARED:
7970 		ksmbd_debug(SMB, "received shared request\n");
7971 		cmd = F_SETLKW;
7972 		flock->c.flc_type = F_RDLCK;
7973 		flock->c.flc_flags |= FL_SLEEP;
7974 		break;
7975 	case SMB2_LOCKFLAG_EXCLUSIVE:
7976 		ksmbd_debug(SMB, "received exclusive request\n");
7977 		cmd = F_SETLKW;
7978 		flock->c.flc_type = F_WRLCK;
7979 		flock->c.flc_flags |= FL_SLEEP;
7980 		break;
7981 	case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7982 		ksmbd_debug(SMB,
7983 			    "received shared & fail immediately request\n");
7984 		cmd = F_SETLK;
7985 		flock->c.flc_type = F_RDLCK;
7986 		break;
7987 	case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7988 		ksmbd_debug(SMB,
7989 			    "received exclusive & fail immediately request\n");
7990 		cmd = F_SETLK;
7991 		flock->c.flc_type = F_WRLCK;
7992 		break;
7993 	case SMB2_LOCKFLAG_UNLOCK:
7994 		ksmbd_debug(SMB, "received unlock request\n");
7995 		flock->c.flc_type = F_UNLCK;
7996 		cmd = F_SETLK;
7997 		break;
7998 	}
7999 
8000 	return cmd;
8001 }
8002 
8003 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
8004 					 unsigned int cmd, int flags,
8005 					 struct list_head *lock_list)
8006 {
8007 	struct ksmbd_lock *lock;
8008 
8009 	lock = kzalloc_obj(struct ksmbd_lock, KSMBD_DEFAULT_GFP);
8010 	if (!lock)
8011 		return NULL;
8012 
8013 	lock->cmd = cmd;
8014 	lock->fl = flock;
8015 	lock->start = flock->fl_start;
8016 	lock->end = flock->fl_end;
8017 	lock->flags = flags;
8018 	if (lock->start == lock->end)
8019 		lock->zero_len = 1;
8020 	INIT_LIST_HEAD(&lock->clist);
8021 	INIT_LIST_HEAD(&lock->flist);
8022 	INIT_LIST_HEAD(&lock->llist);
8023 	list_add_tail(&lock->llist, lock_list);
8024 
8025 	return lock;
8026 }
8027 
8028 static void smb2_remove_blocked_lock(void **argv)
8029 {
8030 	struct file_lock *flock = (struct file_lock *)argv[0];
8031 
8032 	ksmbd_vfs_posix_lock_unblock(flock);
8033 	locks_wake_up(flock);
8034 }
8035 
8036 static inline bool lock_defer_pending(struct file_lock *fl)
8037 {
8038 	/* check pending lock waiters */
8039 	return waitqueue_active(&fl->c.flc_wait);
8040 }
8041 
8042 /**
8043  * smb2_lock() - handler for smb2 file lock command
8044  * @work:	smb work containing lock command buffer
8045  *
8046  * Return:	0 on success, otherwise error
8047  */
8048 int smb2_lock(struct ksmbd_work *work)
8049 {
8050 	struct smb2_lock_req *req;
8051 	struct smb2_lock_rsp *rsp;
8052 	struct smb2_lock_element *lock_ele;
8053 	struct ksmbd_file *fp = NULL;
8054 	struct file_lock *flock = NULL;
8055 	struct file *filp = NULL;
8056 	int lock_count;
8057 	int flags = 0;
8058 	int cmd = 0;
8059 	int err = -EIO, i, rc = 0;
8060 	u64 lock_start, lock_length;
8061 	struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
8062 	struct ksmbd_conn *conn;
8063 	int nolock = 0;
8064 	LIST_HEAD(lock_list);
8065 	LIST_HEAD(rollback_list);
8066 	int prior_lock = 0, bkt;
8067 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
8068 
8069 	WORK_BUFFERS(work, req, rsp);
8070 
8071 	ksmbd_debug(SMB, "Received smb2 lock request\n");
8072 
8073 	if (smb2_compound_has_failed(work, &rsp->hdr))
8074 		return -EACCES;
8075 
8076 	if (work->next_smb2_rcv_hdr_off &&
8077 	    !has_file_id(req->VolatileFileId)) {
8078 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8079 			    work->compound_fid);
8080 		id = work->compound_fid;
8081 		pid = work->compound_pfid;
8082 	}
8083 
8084 	if (!has_file_id(id)) {
8085 		id = req->VolatileFileId;
8086 		pid = req->PersistentFileId;
8087 	}
8088 
8089 	fp = ksmbd_lookup_fd_slow(work, id, pid);
8090 	if (!fp) {
8091 		ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
8092 		err = -ENOENT;
8093 		goto out2;
8094 	}
8095 
8096 	filp = fp->filp;
8097 	lock_count = le16_to_cpu(req->LockCount);
8098 	lock_ele = req->locks;
8099 
8100 	ksmbd_debug(SMB, "lock count is %d\n", lock_count);
8101 	/*
8102 	 * Cap lock_count at 64. The MS-SMB2 spec defines Open.LockSequenceArray
8103 	 * as exactly 64 entries so 64 is the intended ceiling. No real workload
8104 	 * comes close to this in a single request.
8105 	 */
8106 	if (!lock_count || lock_count > 64) {
8107 		err = -EINVAL;
8108 		goto out2;
8109 	}
8110 
8111 	for (i = 0; i < lock_count; i++) {
8112 		flags = le32_to_cpu(lock_ele[i].Flags);
8113 
8114 		flock = smb_flock_init(filp);
8115 		if (!flock)
8116 			goto out;
8117 
8118 		cmd = smb2_set_flock_flags(flock, flags);
8119 
8120 		lock_start = le64_to_cpu(lock_ele[i].Offset);
8121 		lock_length = le64_to_cpu(lock_ele[i].Length);
8122 		if (lock_start > U64_MAX - lock_length) {
8123 			pr_err("Invalid lock range requested\n");
8124 			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
8125 			locks_free_lock(flock);
8126 			goto out;
8127 		}
8128 
8129 		if (lock_start > OFFSET_MAX)
8130 			flock->fl_start = OFFSET_MAX;
8131 		else
8132 			flock->fl_start = lock_start;
8133 
8134 		lock_length = le64_to_cpu(lock_ele[i].Length);
8135 		if (lock_length > OFFSET_MAX - flock->fl_start)
8136 			lock_length = OFFSET_MAX - flock->fl_start;
8137 
8138 		flock->fl_end = flock->fl_start + lock_length;
8139 
8140 		if (flock->fl_end < flock->fl_start) {
8141 			ksmbd_debug(SMB,
8142 				    "the end offset(%llx) is smaller than the start offset(%llx)\n",
8143 				    flock->fl_end, flock->fl_start);
8144 			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
8145 			locks_free_lock(flock);
8146 			goto out;
8147 		}
8148 
8149 		/* Check conflict locks in one request */
8150 		list_for_each_entry(cmp_lock, &lock_list, llist) {
8151 			if (cmp_lock->fl->fl_start <= flock->fl_start &&
8152 			    cmp_lock->fl->fl_end >= flock->fl_end) {
8153 				if (cmp_lock->fl->c.flc_type != F_UNLCK &&
8154 				    flock->c.flc_type != F_UNLCK) {
8155 					pr_err("conflict two locks in one request\n");
8156 					err = -EINVAL;
8157 					locks_free_lock(flock);
8158 					goto out;
8159 				}
8160 			}
8161 		}
8162 
8163 		smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
8164 		if (!smb_lock) {
8165 			err = -EINVAL;
8166 			locks_free_lock(flock);
8167 			goto out;
8168 		}
8169 	}
8170 
8171 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
8172 		if (smb_lock->cmd < 0) {
8173 			err = -EINVAL;
8174 			goto out;
8175 		}
8176 
8177 		if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
8178 			err = -EINVAL;
8179 			goto out;
8180 		}
8181 
8182 		if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
8183 		     smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
8184 		    (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
8185 		     !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
8186 			err = -EINVAL;
8187 			goto out;
8188 		}
8189 
8190 		prior_lock = smb_lock->flags;
8191 
8192 		if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
8193 		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
8194 			goto no_check_cl;
8195 
8196 		nolock = 1;
8197 		/* check locks in connection list */
8198 		down_read(&conn_list_lock);
8199 		hash_for_each(conn_list, bkt, conn, hlist) {
8200 			spin_lock(&conn->llist_lock);
8201 			list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
8202 				if (file_inode(cmp_lock->fl->c.flc_file) !=
8203 				    file_inode(smb_lock->fl->c.flc_file))
8204 					continue;
8205 
8206 				if (lock_is_unlock(smb_lock->fl)) {
8207 					if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file &&
8208 					    cmp_lock->start == smb_lock->start &&
8209 					    cmp_lock->end == smb_lock->end &&
8210 					    !lock_defer_pending(cmp_lock->fl)) {
8211 						nolock = 0;
8212 						list_del(&cmp_lock->flist);
8213 						list_del(&cmp_lock->clist);
8214 						cmp_lock->conn = NULL;
8215 						spin_unlock(&conn->llist_lock);
8216 						up_read(&conn_list_lock);
8217 
8218 						ksmbd_conn_put(conn);
8219 						locks_free_lock(cmp_lock->fl);
8220 						kfree(cmp_lock);
8221 						goto out_check_cl;
8222 					}
8223 					continue;
8224 				}
8225 
8226 				if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file) {
8227 					if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
8228 						continue;
8229 				} else {
8230 					if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
8231 						continue;
8232 				}
8233 
8234 				/* check zero byte lock range */
8235 				if (cmp_lock->zero_len && !smb_lock->zero_len &&
8236 				    cmp_lock->start > smb_lock->start &&
8237 				    cmp_lock->start < smb_lock->end) {
8238 					spin_unlock(&conn->llist_lock);
8239 					up_read(&conn_list_lock);
8240 					pr_err("previous lock conflict with zero byte lock range\n");
8241 					goto out;
8242 				}
8243 
8244 				if (smb_lock->zero_len && !cmp_lock->zero_len &&
8245 				    smb_lock->start > cmp_lock->start &&
8246 				    smb_lock->start < cmp_lock->end) {
8247 					spin_unlock(&conn->llist_lock);
8248 					up_read(&conn_list_lock);
8249 					pr_err("current lock conflict with zero byte lock range\n");
8250 					goto out;
8251 				}
8252 
8253 				if (((cmp_lock->start <= smb_lock->start &&
8254 				      cmp_lock->end > smb_lock->start) ||
8255 				     (cmp_lock->start < smb_lock->end &&
8256 				      cmp_lock->end >= smb_lock->end)) &&
8257 				    !cmp_lock->zero_len && !smb_lock->zero_len) {
8258 					spin_unlock(&conn->llist_lock);
8259 					up_read(&conn_list_lock);
8260 					pr_err("Not allow lock operation on exclusive lock range\n");
8261 					goto out;
8262 				}
8263 			}
8264 			spin_unlock(&conn->llist_lock);
8265 		}
8266 		up_read(&conn_list_lock);
8267 out_check_cl:
8268 		if (lock_is_unlock(smb_lock->fl) && nolock) {
8269 			pr_err("Try to unlock nolocked range\n");
8270 			rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
8271 			goto out;
8272 		}
8273 
8274 no_check_cl:
8275 		flock = smb_lock->fl;
8276 		list_del(&smb_lock->llist);
8277 
8278 		if (smb_lock->zero_len) {
8279 			err = 0;
8280 			goto skip;
8281 		}
8282 retry:
8283 		rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
8284 skip:
8285 		if (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) {
8286 			locks_free_lock(flock);
8287 			kfree(smb_lock);
8288 			if (!rc) {
8289 				ksmbd_debug(SMB, "File unlocked\n");
8290 			} else if (rc == -ENOENT) {
8291 				rsp->hdr.Status = STATUS_NOT_LOCKED;
8292 				err = rc;
8293 				goto out;
8294 			}
8295 		} else {
8296 			if (rc == FILE_LOCK_DEFERRED) {
8297 				void **argv;
8298 
8299 				ksmbd_debug(SMB,
8300 					    "would have to wait for getting lock\n");
8301 				list_add(&smb_lock->llist, &rollback_list);
8302 
8303 				argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP);
8304 				if (!argv) {
8305 					err = -ENOMEM;
8306 					goto out;
8307 				}
8308 				argv[0] = flock;
8309 
8310 				rc = setup_async_work(work,
8311 						      smb2_remove_blocked_lock,
8312 						      argv);
8313 				if (rc) {
8314 					kfree(argv);
8315 					err = -ENOMEM;
8316 					goto out;
8317 				}
8318 				spin_lock(&fp->f_lock);
8319 				list_add(&work->fp_entry, &fp->blocked_works);
8320 				spin_unlock(&fp->f_lock);
8321 
8322 				smb2_send_interim_resp(work, STATUS_PENDING);
8323 
8324 				ksmbd_vfs_posix_lock_wait(flock);
8325 
8326 				spin_lock(&fp->f_lock);
8327 				list_del(&work->fp_entry);
8328 				spin_unlock(&fp->f_lock);
8329 
8330 				list_del(&smb_lock->llist);
8331 				release_async_work(work);
8332 
8333 				if (work->state == KSMBD_WORK_ACTIVE)
8334 					goto retry;
8335 
8336 				locks_free_lock(flock);
8337 
8338 				if (work->state == KSMBD_WORK_CANCELLED) {
8339 					rsp->hdr.Status = STATUS_CANCELLED;
8340 					kfree(smb_lock);
8341 					smb2_send_interim_resp(work,
8342 							STATUS_CANCELLED);
8343 					work->send_no_response = 1;
8344 					goto out;
8345 				}
8346 
8347 				rsp->hdr.Status =
8348 					STATUS_RANGE_NOT_LOCKED;
8349 				kfree(smb_lock);
8350 				goto out2;
8351 			} else if (!rc) {
8352 				list_add(&smb_lock->llist, &rollback_list);
8353 				smb_lock->conn = ksmbd_conn_get(work->conn);
8354 				spin_lock(&work->conn->llist_lock);
8355 				list_add_tail(&smb_lock->clist,
8356 					      &work->conn->lock_list);
8357 				list_add_tail(&smb_lock->flist,
8358 					      &fp->lock_list);
8359 				spin_unlock(&work->conn->llist_lock);
8360 				ksmbd_debug(SMB, "successful in taking lock\n");
8361 			} else {
8362 				locks_free_lock(flock);
8363 				kfree(smb_lock);
8364 				err = rc;
8365 				goto out;
8366 			}
8367 		}
8368 	}
8369 
8370 	if (atomic_read(&fp->f_ci->op_count) > 1)
8371 		smb_break_all_oplock(work, fp);
8372 
8373 	rsp->StructureSize = cpu_to_le16(4);
8374 	ksmbd_debug(SMB, "successful in taking lock\n");
8375 	rsp->hdr.Status = STATUS_SUCCESS;
8376 	rsp->Reserved = 0;
8377 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
8378 	if (err)
8379 		goto out;
8380 
8381 	ksmbd_fd_put(work, fp);
8382 	return 0;
8383 
8384 out:
8385 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
8386 		locks_free_lock(smb_lock->fl);
8387 		list_del(&smb_lock->llist);
8388 		kfree(smb_lock);
8389 	}
8390 
8391 	list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
8392 		struct file_lock *rlock = NULL;
8393 
8394 		rlock = smb_flock_init(filp);
8395 		if (rlock) {
8396 			rlock->c.flc_type = F_UNLCK;
8397 			rlock->fl_start = smb_lock->start;
8398 			rlock->fl_end = smb_lock->end;
8399 
8400 			rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
8401 			if (rc)
8402 				pr_err("rollback unlock fail : %d\n", rc);
8403 		} else {
8404 			pr_err("rollback unlock alloc failed\n");
8405 		}
8406 
8407 		list_del(&smb_lock->llist);
8408 		conn = smb_lock->conn;
8409 		spin_lock(&conn->llist_lock);
8410 		if (!list_empty(&smb_lock->flist))
8411 			list_del(&smb_lock->flist);
8412 		list_del(&smb_lock->clist);
8413 		smb_lock->conn = NULL;
8414 		spin_unlock(&conn->llist_lock);
8415 		ksmbd_conn_put(conn);
8416 
8417 		locks_free_lock(smb_lock->fl);
8418 		if (rlock)
8419 			locks_free_lock(rlock);
8420 		kfree(smb_lock);
8421 	}
8422 out2:
8423 	ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
8424 
8425 	if (!rsp->hdr.Status) {
8426 		if (err == -EINVAL)
8427 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8428 		else if (err == -ENOMEM)
8429 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
8430 		else if (err == -ENOENT)
8431 			rsp->hdr.Status = STATUS_FILE_CLOSED;
8432 		else
8433 			rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
8434 	}
8435 
8436 	smb2_set_err_rsp(work);
8437 	ksmbd_fd_put(work, fp);
8438 	return err;
8439 }
8440 
8441 static int fsctl_copychunk(struct ksmbd_work *work,
8442 			   struct copychunk_ioctl_req *ci_req,
8443 			   unsigned int cnt_code,
8444 			   unsigned int input_count,
8445 			   unsigned long long volatile_id,
8446 			   unsigned long long persistent_id,
8447 			   struct smb2_ioctl_rsp *rsp)
8448 {
8449 	struct copychunk_ioctl_rsp *ci_rsp;
8450 	struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
8451 	struct srv_copychunk *chunks;
8452 	unsigned int i, chunk_count, chunk_count_written = 0;
8453 	unsigned int chunk_size_written = 0;
8454 	loff_t total_size_written = 0;
8455 	int ret = 0;
8456 
8457 	ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
8458 
8459 	rsp->VolatileFileId = volatile_id;
8460 	rsp->PersistentFileId = persistent_id;
8461 	ci_rsp->ChunksWritten =
8462 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
8463 	ci_rsp->ChunkBytesWritten =
8464 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
8465 	ci_rsp->TotalBytesWritten =
8466 		cpu_to_le32(ksmbd_server_side_copy_max_total_size());
8467 
8468 	chunk_count = le32_to_cpu(ci_req->ChunkCount);
8469 	if (chunk_count == 0)
8470 		goto out;
8471 	total_size_written = 0;
8472 
8473 	/* verify the SRV_COPYCHUNK_COPY packet */
8474 	if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
8475 	    input_count < struct_size(ci_req, Chunks, chunk_count)) {
8476 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8477 		return -EINVAL;
8478 	}
8479 
8480 	chunks = &ci_req->Chunks[0];
8481 	for (i = 0; i < chunk_count; i++) {
8482 		if (le32_to_cpu(chunks[i].Length) == 0 ||
8483 		    le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
8484 			break;
8485 		total_size_written += le32_to_cpu(chunks[i].Length);
8486 	}
8487 
8488 	if (i < chunk_count ||
8489 	    total_size_written > ksmbd_server_side_copy_max_total_size()) {
8490 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8491 		return -EINVAL;
8492 	}
8493 
8494 	src_fp = ksmbd_lookup_foreign_fd(work,
8495 					 le64_to_cpu(ci_req->SourceKeyU64[0]));
8496 	dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8497 	ret = -EINVAL;
8498 	if (!src_fp ||
8499 	    src_fp->persistent_id != le64_to_cpu(ci_req->SourceKeyU64[1])) {
8500 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
8501 		goto out;
8502 	}
8503 
8504 	if (!dst_fp) {
8505 		rsp->hdr.Status = STATUS_FILE_CLOSED;
8506 		goto out;
8507 	}
8508 
8509 	/*
8510 	 * FILE_READ_DATA should only be included in
8511 	 * the FSCTL_SRV_COPYCHUNK case
8512 	 */
8513 	if (cnt_code == FSCTL_SRV_COPYCHUNK &&
8514 	    !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
8515 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
8516 		goto out;
8517 	}
8518 
8519 	ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
8520 					 chunks, chunk_count,
8521 					 &chunk_count_written,
8522 					 &chunk_size_written,
8523 					 &total_size_written);
8524 	if (ret < 0) {
8525 		if (ret == -EACCES)
8526 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
8527 		if (ret == -EAGAIN)
8528 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
8529 		else if (ret == -EBADF)
8530 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
8531 		else if (ret == -EFBIG || ret == -ENOSPC)
8532 			rsp->hdr.Status = STATUS_DISK_FULL;
8533 		else if (ret == -EINVAL)
8534 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8535 		else if (ret == -EISDIR)
8536 			rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
8537 		else if (ret == -E2BIG)
8538 			rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
8539 		else
8540 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
8541 	}
8542 
8543 	ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
8544 	ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
8545 	ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
8546 out:
8547 	ksmbd_fd_put(work, src_fp);
8548 	ksmbd_fd_put(work, dst_fp);
8549 	return ret;
8550 }
8551 
8552 static __be32 idev_ipv4_address(struct in_device *idev)
8553 {
8554 	__be32 addr = 0;
8555 
8556 	struct in_ifaddr *ifa;
8557 
8558 	rcu_read_lock();
8559 	in_dev_for_each_ifa_rcu(ifa, idev) {
8560 		if (ifa->ifa_flags & IFA_F_SECONDARY)
8561 			continue;
8562 
8563 		addr = ifa->ifa_address;
8564 		break;
8565 	}
8566 	rcu_read_unlock();
8567 	return addr;
8568 }
8569 
8570 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
8571 					struct smb2_ioctl_rsp *rsp,
8572 					unsigned int out_buf_len)
8573 {
8574 	struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
8575 	int nbytes = 0;
8576 	struct net_device *netdev;
8577 	struct sockaddr_storage_rsp *sockaddr_storage;
8578 	unsigned int flags;
8579 	unsigned long long speed;
8580 
8581 	rtnl_lock();
8582 	for_each_netdev(&init_net, netdev) {
8583 		bool ipv4_set = false;
8584 
8585 		if (netdev->type == ARPHRD_LOOPBACK)
8586 			continue;
8587 
8588 		if (!ksmbd_find_netdev_name_iface_list(netdev->name))
8589 			continue;
8590 
8591 		flags = netif_get_flags(netdev);
8592 		if (!(flags & IFF_RUNNING))
8593 			continue;
8594 ipv6_retry:
8595 		if (out_buf_len <
8596 		    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
8597 			rtnl_unlock();
8598 			return -ENOSPC;
8599 		}
8600 
8601 		nii_rsp = (struct network_interface_info_ioctl_rsp *)
8602 				&rsp->Buffer[nbytes];
8603 		nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
8604 
8605 		nii_rsp->Capability = 0;
8606 		if (netdev->real_num_tx_queues > 1)
8607 			nii_rsp->Capability |= RSS_CAPABLE;
8608 		if (ksmbd_rdma_capable_netdev(netdev))
8609 			nii_rsp->Capability |= RDMA_CAPABLE;
8610 
8611 		nii_rsp->Next = cpu_to_le32(152);
8612 		nii_rsp->Reserved = 0;
8613 
8614 		if (netdev->ethtool_ops->get_link_ksettings) {
8615 			struct ethtool_link_ksettings cmd;
8616 
8617 			netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
8618 			speed = cmd.base.speed;
8619 		} else {
8620 			ksmbd_debug(SMB, "%s %s\n", netdev->name,
8621 				    "speed is unknown, defaulting to 1Gb/sec");
8622 			speed = SPEED_1000;
8623 		}
8624 
8625 		speed *= 1000000;
8626 		nii_rsp->LinkSpeed = cpu_to_le64(speed);
8627 
8628 		sockaddr_storage = (struct sockaddr_storage_rsp *)
8629 					nii_rsp->SockAddr_Storage;
8630 		memset(sockaddr_storage, 0, 128);
8631 
8632 		if (!ipv4_set) {
8633 			struct in_device *idev;
8634 
8635 			sockaddr_storage->Family = INTERNETWORK;
8636 			sockaddr_storage->addr4.Port = 0;
8637 
8638 			idev = __in_dev_get_rtnl(netdev);
8639 			if (!idev)
8640 				continue;
8641 			sockaddr_storage->addr4.IPv4Address =
8642 						idev_ipv4_address(idev);
8643 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
8644 			ipv4_set = true;
8645 			goto ipv6_retry;
8646 		} else {
8647 			struct inet6_dev *idev6;
8648 			struct inet6_ifaddr *ifa;
8649 			__u8 *ipv6_addr = sockaddr_storage->addr6.IPv6Address;
8650 
8651 			sockaddr_storage->Family = INTERNETWORKV6;
8652 			sockaddr_storage->addr6.Port = 0;
8653 			sockaddr_storage->addr6.FlowInfo = 0;
8654 
8655 			idev6 = __in6_dev_get(netdev);
8656 			if (!idev6)
8657 				continue;
8658 
8659 			list_for_each_entry(ifa, &idev6->addr_list, if_list) {
8660 				if (ifa->flags & (IFA_F_TENTATIVE |
8661 							IFA_F_DEPRECATED))
8662 					continue;
8663 				memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
8664 				break;
8665 			}
8666 			sockaddr_storage->addr6.ScopeId = 0;
8667 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
8668 		}
8669 	}
8670 	rtnl_unlock();
8671 
8672 	/* zero if this is last one */
8673 	if (nii_rsp)
8674 		nii_rsp->Next = 0;
8675 
8676 	rsp->PersistentFileId = SMB2_NO_FID;
8677 	rsp->VolatileFileId = SMB2_NO_FID;
8678 	return nbytes;
8679 }
8680 
8681 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
8682 					 struct validate_negotiate_info_req *neg_req,
8683 					 struct validate_negotiate_info_rsp *neg_rsp,
8684 					 unsigned int in_buf_len)
8685 {
8686 	int ret = 0;
8687 	int dialect;
8688 
8689 	if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
8690 			le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
8691 		return -EINVAL;
8692 
8693 	dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
8694 					     neg_req->DialectCount);
8695 	if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
8696 		ret = -EINVAL;
8697 		goto err_out;
8698 	}
8699 
8700 	if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
8701 		ret = -EINVAL;
8702 		goto err_out;
8703 	}
8704 
8705 	if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
8706 		ret = -EINVAL;
8707 		goto err_out;
8708 	}
8709 
8710 	if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
8711 		ret = -EINVAL;
8712 		goto err_out;
8713 	}
8714 
8715 	neg_rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
8716 	memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
8717 	neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
8718 	neg_rsp->Dialect = cpu_to_le16(conn->dialect);
8719 err_out:
8720 	return ret;
8721 }
8722 
8723 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
8724 					struct file_allocated_range_buffer *qar_req,
8725 					struct file_allocated_range_buffer *qar_rsp,
8726 					unsigned int in_count, unsigned int *out_count)
8727 {
8728 	struct ksmbd_file *fp;
8729 	loff_t start, length;
8730 	int ret = 0;
8731 
8732 	*out_count = 0;
8733 	if (in_count == 0)
8734 		return -EINVAL;
8735 
8736 	start = le64_to_cpu(qar_req->file_offset);
8737 	length = le64_to_cpu(qar_req->length);
8738 
8739 	if (start < 0 || length < 0)
8740 		return -EINVAL;
8741 
8742 	fp = ksmbd_lookup_fd_fast(work, id);
8743 	if (!fp)
8744 		return -ENOENT;
8745 
8746 	ret = ksmbd_vfs_fqar_lseek(fp, start, length,
8747 				   qar_rsp, in_count, out_count);
8748 	if (ret && ret != -E2BIG)
8749 		*out_count = 0;
8750 
8751 	ksmbd_fd_put(work, fp);
8752 	return ret;
8753 }
8754 
8755 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
8756 				 unsigned int out_buf_len,
8757 				 struct smb2_ioctl_req *req,
8758 				 struct smb2_ioctl_rsp *rsp)
8759 {
8760 	struct ksmbd_rpc_command *rpc_resp;
8761 	char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
8762 	int nbytes = 0;
8763 
8764 	rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
8765 				   le32_to_cpu(req->InputCount));
8766 	if (rpc_resp) {
8767 		if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
8768 			/*
8769 			 * set STATUS_SOME_NOT_MAPPED response
8770 			 * for unknown domain sid.
8771 			 */
8772 			rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
8773 		} else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
8774 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8775 			goto out;
8776 		} else if (rpc_resp->flags != KSMBD_RPC_OK) {
8777 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8778 			goto out;
8779 		}
8780 
8781 		nbytes = rpc_resp->payload_sz;
8782 		if (rpc_resp->payload_sz > out_buf_len) {
8783 			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8784 			nbytes = out_buf_len;
8785 		}
8786 
8787 		if (!rpc_resp->payload_sz) {
8788 			rsp->hdr.Status =
8789 				STATUS_UNEXPECTED_IO_ERROR;
8790 			goto out;
8791 		}
8792 
8793 		memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
8794 	}
8795 out:
8796 	kvfree(rpc_resp);
8797 	return nbytes;
8798 }
8799 
8800 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
8801 				   struct file_sparse *sparse)
8802 {
8803 	struct ksmbd_file *fp;
8804 	struct mnt_idmap *idmap;
8805 	int ret = 0;
8806 	__le32 old_fattr;
8807 
8808 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8809 		ksmbd_debug(SMB, "User does not have write permission\n");
8810 		return -EACCES;
8811 	}
8812 
8813 	fp = ksmbd_lookup_fd_fast(work, id);
8814 	if (!fp)
8815 		return -ENOENT;
8816 
8817 	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_WRITE_ATTRIBUTES_LE))) {
8818 		ret = -EACCES;
8819 		goto out;
8820 	}
8821 
8822 	idmap = file_mnt_idmap(fp->filp);
8823 
8824 	old_fattr = fp->f_ci->m_fattr;
8825 	if (sparse->SetSparse)
8826 		fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
8827 	else
8828 		fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
8829 
8830 	if (fp->f_ci->m_fattr != old_fattr &&
8831 	    test_share_config_flag(work->tcon->share_conf,
8832 				   KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
8833 		const struct cred *saved_cred;
8834 		struct xattr_dos_attrib da;
8835 
8836 		ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
8837 						     fp->filp->f_path.dentry, &da);
8838 		if (ret <= 0)
8839 			goto out;
8840 
8841 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
8842 		saved_cred = override_creds(fp->filp->f_cred);
8843 		ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
8844 						     &fp->filp->f_path,
8845 						     &da, true);
8846 		revert_creds(saved_cred);
8847 		if (ret)
8848 			fp->f_ci->m_fattr = old_fattr;
8849 	}
8850 
8851 out:
8852 	ksmbd_fd_put(work, fp);
8853 	return ret;
8854 }
8855 
8856 static int fsctl_request_resume_key(struct ksmbd_work *work,
8857 				    struct smb2_ioctl_req *req,
8858 				    struct resume_key_ioctl_rsp *key_rsp)
8859 {
8860 	struct ksmbd_file *fp;
8861 
8862 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
8863 	if (!fp)
8864 		return -ENOENT;
8865 
8866 	memset(key_rsp, 0, sizeof(*key_rsp));
8867 	key_rsp->ResumeKeyU64[0] = req->VolatileFileId;
8868 	key_rsp->ResumeKeyU64[1] = req->PersistentFileId;
8869 	ksmbd_fd_put(work, fp);
8870 
8871 	return 0;
8872 }
8873 
8874 /**
8875  * smb2_ioctl() - handler for smb2 ioctl command
8876  * @work:	smb work containing ioctl command buffer
8877  *
8878  * Return:	0 on success, otherwise error
8879  */
8880 int smb2_ioctl(struct ksmbd_work *work)
8881 {
8882 	struct smb2_ioctl_req *req;
8883 	struct smb2_ioctl_rsp *rsp;
8884 	unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
8885 	u64 id = KSMBD_NO_FID;
8886 	struct ksmbd_conn *conn = work->conn;
8887 	int ret = 0;
8888 	char *buffer;
8889 
8890 	ksmbd_debug(SMB, "Received smb2 ioctl request\n");
8891 
8892 	if (work->next_smb2_rcv_hdr_off) {
8893 		req = ksmbd_req_buf_next(work);
8894 		rsp = ksmbd_resp_buf_next(work);
8895 		if (smb2_compound_has_failed(work, &rsp->hdr))
8896 			return -EACCES;
8897 		if (!has_file_id(req->VolatileFileId)) {
8898 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8899 				    work->compound_fid);
8900 			id = work->compound_fid;
8901 		}
8902 	} else {
8903 		req = smb_get_msg(work->request_buf);
8904 		rsp = smb_get_msg(work->response_buf);
8905 	}
8906 
8907 	if (!has_file_id(id))
8908 		id = req->VolatileFileId;
8909 
8910 	if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
8911 		ret = -EOPNOTSUPP;
8912 		goto out;
8913 	}
8914 
8915 	buffer = (char *)req + le32_to_cpu(req->InputOffset);
8916 
8917 	cnt_code = le32_to_cpu(req->CtlCode);
8918 	ret = smb2_calc_max_out_buf_len(work,
8919 			offsetof(struct smb2_ioctl_rsp, Buffer),
8920 			le32_to_cpu(req->MaxOutputResponse));
8921 	if (ret < 0) {
8922 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8923 		goto out;
8924 	}
8925 	out_buf_len = (unsigned int)ret;
8926 	in_buf_len = le32_to_cpu(req->InputCount);
8927 
8928 	switch (cnt_code) {
8929 	case FSCTL_DFS_GET_REFERRALS:
8930 	case FSCTL_DFS_GET_REFERRALS_EX:
8931 		/* Not support DFS yet */
8932 		ret = -EOPNOTSUPP;
8933 		rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
8934 		goto out2;
8935 	case FSCTL_GET_COMPRESSION: {
8936 		struct compress_ioctl *cmpr_rsp;
8937 		struct ksmbd_file *fp;
8938 		u16 fmt;
8939 
8940 		if (out_buf_len < sizeof(struct compress_ioctl)) {
8941 			ret = -EINVAL;
8942 			goto out;
8943 		}
8944 
8945 		fp = ksmbd_lookup_fd_fast(work, id);
8946 		if (!fp) {
8947 			ret = -ENOENT;
8948 			goto out;
8949 		}
8950 
8951 		ret = ksmbd_vfs_get_compression(fp, &fmt);
8952 		ksmbd_fd_put(work, fp);
8953 		if (ret < 0)
8954 			goto out;
8955 
8956 		cmpr_rsp = (struct compress_ioctl *)&rsp->Buffer[0];
8957 		cmpr_rsp->CompressionState = cpu_to_le16(fmt);
8958 		nbytes = sizeof(struct compress_ioctl);
8959 		rsp->PersistentFileId = req->PersistentFileId;
8960 		rsp->VolatileFileId = req->VolatileFileId;
8961 		break;
8962 	}
8963 	case FSCTL_SET_COMPRESSION: {
8964 		struct compress_ioctl *cmpr_req;
8965 		struct ksmbd_file *fp;
8966 
8967 		if (in_buf_len < sizeof(struct compress_ioctl)) {
8968 			ret = -EINVAL;
8969 			goto out;
8970 		}
8971 
8972 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8973 			ksmbd_debug(SMB, "User does not have write permission\n");
8974 			ret = -EACCES;
8975 			goto out;
8976 		}
8977 
8978 		cmpr_req = (struct compress_ioctl *)buffer;
8979 		fp = ksmbd_lookup_fd_fast(work, id);
8980 		if (!fp) {
8981 			ret = -ENOENT;
8982 			goto out;
8983 		}
8984 
8985 		ret = ksmbd_vfs_set_compression(work, fp, le16_to_cpu(cmpr_req->CompressionState));
8986 		ksmbd_fd_put(work, fp);
8987 		if (ret)
8988 			goto out;
8989 		break;
8990 	}
8991 	case FSCTL_CREATE_OR_GET_OBJECT_ID:
8992 	{
8993 		struct file_object_buf_type1_ioctl_rsp *obj_buf;
8994 		struct ksmbd_file *fp;
8995 
8996 		fp = ksmbd_lookup_fd_fast(work, id);
8997 		if (!fp) {
8998 			ret = -EBADF;
8999 			rsp->hdr.Status = STATUS_FILE_CLOSED;
9000 			goto out2;
9001 		}
9002 		ksmbd_fd_put(work, fp);
9003 
9004 		nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
9005 		obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
9006 			&rsp->Buffer[0];
9007 
9008 		/*
9009 		 * TODO: This is dummy implementation to pass smbtorture
9010 		 * Need to check correct response later
9011 		 */
9012 		memset(obj_buf->ObjectId, 0x0, 16);
9013 		memset(obj_buf->BirthVolumeId, 0x0, 16);
9014 		memset(obj_buf->BirthObjectId, 0x0, 16);
9015 		memset(obj_buf->DomainId, 0x0, 16);
9016 
9017 		break;
9018 	}
9019 	case FSCTL_PIPE_TRANSCEIVE:
9020 		out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
9021 		nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
9022 		break;
9023 	case FSCTL_VALIDATE_NEGOTIATE_INFO:
9024 		if (conn->dialect < SMB30_PROT_ID) {
9025 			ret = -EOPNOTSUPP;
9026 			goto out;
9027 		}
9028 
9029 		if (in_buf_len < offsetof(struct validate_negotiate_info_req,
9030 					  Dialects)) {
9031 			ret = -EINVAL;
9032 			goto out;
9033 		}
9034 
9035 		if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
9036 			ret = -EINVAL;
9037 			goto out;
9038 		}
9039 
9040 		ret = fsctl_validate_negotiate_info(conn,
9041 			(struct validate_negotiate_info_req *)buffer,
9042 			(struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
9043 			in_buf_len);
9044 		if (ret < 0)
9045 			goto out;
9046 
9047 		nbytes = sizeof(struct validate_negotiate_info_rsp);
9048 		rsp->PersistentFileId = SMB2_NO_FID;
9049 		rsp->VolatileFileId = SMB2_NO_FID;
9050 		break;
9051 	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
9052 		ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
9053 		if (ret < 0)
9054 			goto out;
9055 		nbytes = ret;
9056 		break;
9057 	case FSCTL_SRV_REQUEST_RESUME_KEY:
9058 		if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
9059 			ret = -EINVAL;
9060 			goto out;
9061 		}
9062 
9063 		ret = fsctl_request_resume_key(work, req,
9064 					       (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
9065 		if (ret < 0)
9066 			goto out;
9067 		rsp->PersistentFileId = req->PersistentFileId;
9068 		rsp->VolatileFileId = req->VolatileFileId;
9069 		nbytes = sizeof(struct resume_key_ioctl_rsp);
9070 		break;
9071 	case FSCTL_SRV_COPYCHUNK:
9072 	case FSCTL_SRV_COPYCHUNK_WRITE:
9073 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
9074 			ksmbd_debug(SMB,
9075 				    "User does not have write permission\n");
9076 			ret = -EACCES;
9077 			goto out;
9078 		}
9079 
9080 		if (in_buf_len <= sizeof(struct copychunk_ioctl_req)) {
9081 			ret = -EINVAL;
9082 			goto out;
9083 		}
9084 
9085 		if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
9086 			ret = -EINVAL;
9087 			goto out;
9088 		}
9089 
9090 		nbytes = sizeof(struct copychunk_ioctl_rsp);
9091 		rsp->VolatileFileId = req->VolatileFileId;
9092 		rsp->PersistentFileId = req->PersistentFileId;
9093 		fsctl_copychunk(work,
9094 				(struct copychunk_ioctl_req *)buffer,
9095 				le32_to_cpu(req->CtlCode),
9096 				le32_to_cpu(req->InputCount),
9097 				req->VolatileFileId,
9098 				req->PersistentFileId,
9099 				rsp);
9100 		break;
9101 	case FSCTL_SET_SPARSE:
9102 		if (in_buf_len < sizeof(struct file_sparse)) {
9103 			ret = -EINVAL;
9104 			goto out;
9105 		}
9106 
9107 		ret = fsctl_set_sparse(work, id, (struct file_sparse *)buffer);
9108 		if (ret < 0)
9109 			goto out;
9110 		break;
9111 	case FSCTL_SET_ZERO_DATA:
9112 	{
9113 		struct file_zero_data_information *zero_data;
9114 		struct ksmbd_file *fp;
9115 		loff_t off, len, bfz;
9116 
9117 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
9118 			ksmbd_debug(SMB,
9119 				    "User does not have write permission\n");
9120 			ret = -EACCES;
9121 			goto out;
9122 		}
9123 
9124 		if (in_buf_len < sizeof(struct file_zero_data_information)) {
9125 			ret = -EINVAL;
9126 			goto out;
9127 		}
9128 
9129 		zero_data =
9130 			(struct file_zero_data_information *)buffer;
9131 
9132 		off = le64_to_cpu(zero_data->FileOffset);
9133 		bfz = le64_to_cpu(zero_data->BeyondFinalZero);
9134 		if (off < 0 || bfz < 0 || off > bfz) {
9135 			ret = -EINVAL;
9136 			goto out;
9137 		}
9138 
9139 		len = bfz - off;
9140 		if (len) {
9141 			fp = ksmbd_lookup_fd_fast(work, id);
9142 			if (!fp) {
9143 				ret = -ENOENT;
9144 				goto out;
9145 			}
9146 
9147 			if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
9148 				ksmbd_fd_put(work, fp);
9149 				ret = -EACCES;
9150 				goto out;
9151 			}
9152 
9153 			ret = ksmbd_vfs_zero_data(work, fp, off, len);
9154 			ksmbd_fd_put(work, fp);
9155 			if (ret < 0)
9156 				goto out;
9157 		}
9158 		break;
9159 	}
9160 	case FSCTL_QUERY_ALLOCATED_RANGES:
9161 		if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
9162 			ret = -EINVAL;
9163 			goto out;
9164 		}
9165 
9166 		ret = fsctl_query_allocated_ranges(work, id,
9167 			(struct file_allocated_range_buffer *)buffer,
9168 			(struct file_allocated_range_buffer *)&rsp->Buffer[0],
9169 			out_buf_len /
9170 			sizeof(struct file_allocated_range_buffer), &nbytes);
9171 		if (ret == -E2BIG) {
9172 			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
9173 		} else if (ret < 0) {
9174 			nbytes = 0;
9175 			goto out;
9176 		}
9177 
9178 		nbytes *= sizeof(struct file_allocated_range_buffer);
9179 		break;
9180 	case FSCTL_GET_REPARSE_POINT:
9181 	{
9182 		struct reparse_data_buffer *reparse_ptr;
9183 		struct ksmbd_file *fp;
9184 
9185 		reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
9186 		fp = ksmbd_lookup_fd_fast(work, id);
9187 		if (!fp) {
9188 			pr_err("not found fp!!\n");
9189 			ret = -ENOENT;
9190 			goto out;
9191 		}
9192 
9193 		reparse_ptr->ReparseTag =
9194 			smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
9195 		reparse_ptr->ReparseDataLength = 0;
9196 		ksmbd_fd_put(work, fp);
9197 		nbytes = sizeof(struct reparse_data_buffer);
9198 		break;
9199 	}
9200 	case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
9201 	{
9202 		struct ksmbd_file *fp_in, *fp_out = NULL;
9203 		struct duplicate_extents_to_file *dup_ext;
9204 		loff_t src_off, dst_off, length, cloned;
9205 
9206 		if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
9207 			ret = -EINVAL;
9208 			goto out;
9209 		}
9210 
9211 		dup_ext = (struct duplicate_extents_to_file *)buffer;
9212 
9213 		fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
9214 					     dup_ext->PersistentFileHandle);
9215 		if (!fp_in) {
9216 			pr_err("not found file handle in duplicate extent to file\n");
9217 			ret = -ENOENT;
9218 			goto out;
9219 		}
9220 
9221 		fp_out = ksmbd_lookup_fd_fast(work, id);
9222 		if (!fp_out) {
9223 			pr_err("not found fp\n");
9224 			ret = -ENOENT;
9225 			goto dup_ext_out;
9226 		}
9227 
9228 		if (!test_tree_conn_flag(work->tcon,
9229 					 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
9230 			ret = -EACCES;
9231 			goto dup_ext_out;
9232 		}
9233 
9234 		if (!(fp_out->daccess & FILE_WRITE_DATA_LE)) {
9235 			ret = -EACCES;
9236 			goto dup_ext_out;
9237 		}
9238 		if (!(fp_in->daccess & FILE_READ_DATA_LE)) {
9239 			ret = -EACCES;
9240 			goto dup_ext_out;
9241 		}
9242 
9243 		src_off = le64_to_cpu(dup_ext->SourceFileOffset);
9244 		dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
9245 		length = le64_to_cpu(dup_ext->ByteCount);
9246 		/*
9247 		 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
9248 		 * should fall back to vfs_copy_file_range().  This could be
9249 		 * beneficial when re-exporting nfs/smb mount, but note that
9250 		 * this can result in partial copy that returns an error status.
9251 		 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
9252 		 * fall back to vfs_copy_file_range(), should be avoided when
9253 		 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
9254 		 */
9255 		cloned = vfs_clone_file_range(fp_in->filp, src_off,
9256 					      fp_out->filp, dst_off, length, 0);
9257 		if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
9258 			ret = -EOPNOTSUPP;
9259 			goto dup_ext_out;
9260 		} else if (cloned != length) {
9261 			cloned = vfs_copy_file_range(fp_in->filp, src_off,
9262 						     fp_out->filp, dst_off,
9263 						     length, 0);
9264 			if (cloned != length) {
9265 				if (cloned < 0)
9266 					ret = cloned;
9267 				else
9268 					ret = -EINVAL;
9269 			}
9270 		}
9271 
9272 dup_ext_out:
9273 		ksmbd_fd_put(work, fp_in);
9274 		ksmbd_fd_put(work, fp_out);
9275 		if (ret < 0)
9276 			goto out;
9277 		break;
9278 	}
9279 	default:
9280 		ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
9281 			    cnt_code);
9282 		ret = -EOPNOTSUPP;
9283 		goto out;
9284 	}
9285 
9286 	rsp->CtlCode = cpu_to_le32(cnt_code);
9287 	rsp->InputCount = cpu_to_le32(0);
9288 	rsp->InputOffset = cpu_to_le32(112);
9289 	rsp->OutputOffset = cpu_to_le32(112);
9290 	rsp->OutputCount = cpu_to_le32(nbytes);
9291 	rsp->StructureSize = cpu_to_le16(49);
9292 	rsp->Reserved = cpu_to_le16(0);
9293 	rsp->Flags = cpu_to_le32(0);
9294 	rsp->Reserved2 = cpu_to_le32(0);
9295 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
9296 	if (!ret)
9297 		return ret;
9298 
9299 out:
9300 	if (ret == -EACCES)
9301 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
9302 	else if (ret == -ENOENT)
9303 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
9304 	else if (ret == -EOPNOTSUPP)
9305 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
9306 	else if (ret == -ENOSPC)
9307 		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
9308 	else if (ret < 0 || rsp->hdr.Status == 0)
9309 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
9310 
9311 out2:
9312 	smb2_set_err_rsp(work);
9313 	return ret;
9314 }
9315 
9316 /**
9317  * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
9318  * @work:	smb work containing oplock break command buffer
9319  *
9320  * Return:	0
9321  */
9322 static void smb20_oplock_break_ack(struct ksmbd_work *work)
9323 {
9324 	struct smb2_oplock_break *req;
9325 	struct smb2_oplock_break *rsp;
9326 	struct ksmbd_file *fp;
9327 	struct oplock_info *opinfo = NULL;
9328 	__le32 status = STATUS_SUCCESS;
9329 	int ret;
9330 	u64 volatile_id, persistent_id;
9331 	char req_oplevel = 0, rsp_oplevel = 0;
9332 
9333 	WORK_BUFFERS(work, req, rsp);
9334 
9335 	volatile_id = req->VolatileFid;
9336 	persistent_id = req->PersistentFid;
9337 	req_oplevel = req->OplockLevel;
9338 	ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
9339 		    volatile_id, persistent_id, req_oplevel);
9340 
9341 	fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
9342 	if (!fp) {
9343 		rsp->hdr.Status = STATUS_FILE_CLOSED;
9344 		smb2_set_err_rsp(work);
9345 		return;
9346 	}
9347 
9348 	opinfo = opinfo_get(fp);
9349 	if (!opinfo) {
9350 		pr_err("unexpected null oplock_info\n");
9351 		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
9352 		smb2_set_err_rsp(work);
9353 		ksmbd_fd_put(work, fp);
9354 		return;
9355 	}
9356 
9357 	if (opinfo->op_state != OPLOCK_ACK_WAIT) {
9358 		ksmbd_debug(SMB, "unexpected oplock state 0x%x\n",
9359 			    opinfo->op_state);
9360 		if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE)
9361 			status = STATUS_INVALID_OPLOCK_PROTOCOL;
9362 		else
9363 			status = STATUS_INVALID_DEVICE_STATE;
9364 		goto err_out;
9365 	}
9366 
9367 	if (req_oplevel == SMB2_OPLOCK_LEVEL_LEASE) {
9368 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
9369 		status = STATUS_INVALID_PARAMETER;
9370 		goto err_out;
9371 	}
9372 
9373 	if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
9374 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
9375 		goto err_out;
9376 	}
9377 
9378 	if (opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE &&
9379 	    req_oplevel != SMB2_OPLOCK_LEVEL_II &&
9380 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
9381 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
9382 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
9383 		goto err_out;
9384 	}
9385 
9386 	if (opinfo->level == SMB2_OPLOCK_LEVEL_BATCH &&
9387 	    req_oplevel != SMB2_OPLOCK_LEVEL_II &&
9388 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE &&
9389 	    req_oplevel != SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
9390 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
9391 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
9392 		goto err_out;
9393 	}
9394 
9395 	if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
9396 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
9397 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
9398 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
9399 		goto err_out;
9400 	}
9401 
9402 	if (req_oplevel == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
9403 		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
9404 	else
9405 		rsp_oplevel = req_oplevel;
9406 
9407 	opinfo->level = rsp_oplevel;
9408 
9409 	rsp->StructureSize = cpu_to_le16(24);
9410 	rsp->OplockLevel = rsp_oplevel;
9411 	rsp->Reserved = 0;
9412 	rsp->Reserved2 = 0;
9413 	rsp->VolatileFid = volatile_id;
9414 	rsp->PersistentFid = persistent_id;
9415 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
9416 	if (ret)
9417 		ksmbd_debug(SMB, "failed to pin oplock break response: %d\n",
9418 			    ret);
9419 	goto out;
9420 
9421 err_out:
9422 	rsp->hdr.Status = status;
9423 	smb2_set_err_rsp(work);
9424 
9425 out:
9426 	opinfo->op_state = OPLOCK_STATE_NONE;
9427 	wake_up_interruptible_all(&opinfo->oplock_q);
9428 	opinfo_put(opinfo);
9429 	ksmbd_fd_put(work, fp);
9430 }
9431 
9432 static bool smb2_lease_state_valid(__le32 state)
9433 {
9434 	return !(state & ~(SMB2_LEASE_READ_CACHING_LE |
9435 			   SMB2_LEASE_HANDLE_CACHING_LE |
9436 			   SMB2_LEASE_WRITE_CACHING_LE));
9437 }
9438 
9439 static int check_lease_state(struct lease *lease, __le32 req_state)
9440 {
9441 	if (smb2_lease_state_valid(req_state) &&
9442 	    !(req_state & ~lease->new_state))
9443 		return 0;
9444 
9445 	return 1;
9446 }
9447 
9448 /**
9449  * smb21_lease_break_ack() - handler for smb2.1 lease break command
9450  * @work:	smb work containing lease break command buffer
9451  *
9452  * Return:	0
9453  */
9454 static void smb21_lease_break_ack(struct ksmbd_work *work)
9455 {
9456 	struct ksmbd_conn *conn = work->conn;
9457 	struct smb2_lease_ack *req;
9458 	struct smb2_lease_ack *rsp;
9459 	struct oplock_info *opinfo;
9460 	int ret = 0;
9461 	__le32 lease_state;
9462 	struct lease *lease;
9463 
9464 	WORK_BUFFERS(work, req, rsp);
9465 
9466 	ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
9467 		    le32_to_cpu(req->LeaseState));
9468 	opinfo = lookup_lease_in_table(conn, req->LeaseKey);
9469 	if (!opinfo) {
9470 		ksmbd_debug(OPLOCK, "file not opened\n");
9471 		smb2_set_err_rsp(work);
9472 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
9473 		return;
9474 	}
9475 	lease = opinfo->o_lease;
9476 
9477 	if (opinfo->op_state == OPLOCK_STATE_NONE) {
9478 		pr_err("unexpected lease break state 0x%x\n",
9479 		       opinfo->op_state);
9480 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
9481 		goto err_out;
9482 	}
9483 
9484 	if (!atomic_read(&opinfo->breaking_cnt)) {
9485 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
9486 		goto err_out;
9487 	}
9488 
9489 	if (check_lease_state(lease, req->LeaseState)) {
9490 		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
9491 		ksmbd_debug(OPLOCK,
9492 			    "req lease state: 0x%x, expected state: 0x%x\n",
9493 			    req->LeaseState, lease->new_state);
9494 		goto err_out;
9495 	}
9496 
9497 	lease_state = req->LeaseState;
9498 	lease->state = lease_state;
9499 	lease->new_state = SMB2_LEASE_NONE_LE;
9500 	lease_update_oplock_levels(lease);
9501 
9502 	rsp->StructureSize = cpu_to_le16(36);
9503 	rsp->Reserved = 0;
9504 	rsp->Flags = 0;
9505 	memcpy(rsp->LeaseKey, req->LeaseKey, 16);
9506 	rsp->LeaseState = lease_state;
9507 	rsp->LeaseDuration = 0;
9508 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
9509 	if (ret)
9510 		goto err_out;
9511 
9512 	opinfo->op_state = OPLOCK_STATE_NONE;
9513 	wake_up_interruptible_all(&opinfo->oplock_q);
9514 	atomic_dec(&opinfo->breaking_cnt);
9515 	wake_up_interruptible_all(&opinfo->oplock_brk);
9516 	opinfo_put(opinfo);
9517 	return;
9518 
9519 err_out:
9520 	smb2_set_err_rsp(work);
9521 	opinfo_put(opinfo);
9522 	return;
9523 }
9524 
9525 /**
9526  * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
9527  * @work:	smb work containing oplock/lease break command buffer
9528  *
9529  * Return:	0 on success, otherwise error
9530  */
9531 int smb2_oplock_break(struct ksmbd_work *work)
9532 {
9533 	struct smb2_oplock_break *req;
9534 	struct smb2_oplock_break *rsp;
9535 
9536 	ksmbd_debug(SMB, "Received smb2 oplock break acknowledgment request\n");
9537 
9538 	WORK_BUFFERS(work, req, rsp);
9539 
9540 	switch (le16_to_cpu(req->StructureSize)) {
9541 	case OP_BREAK_STRUCT_SIZE_20:
9542 		smb20_oplock_break_ack(work);
9543 		break;
9544 	case OP_BREAK_STRUCT_SIZE_21:
9545 		smb21_lease_break_ack(work);
9546 		break;
9547 	default:
9548 		ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
9549 			    le16_to_cpu(req->StructureSize));
9550 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
9551 		smb2_set_err_rsp(work);
9552 		return -EINVAL;
9553 	}
9554 
9555 	return 0;
9556 }
9557 
9558 /**
9559  * smb2_notify() - handler for smb2 notify request
9560  * @work:   smb work containing notify command buffer
9561  *
9562  * Return:      0 on success, otherwise error
9563  */
9564 int smb2_notify(struct ksmbd_work *work)
9565 {
9566 	struct smb2_change_notify_req *req;
9567 	struct smb2_change_notify_rsp *rsp;
9568 
9569 	ksmbd_debug(SMB, "Received smb2 notify\n");
9570 
9571 	WORK_BUFFERS(work, req, rsp);
9572 
9573 	if (smb2_compound_has_failed(work, &rsp->hdr))
9574 		return -EACCES;
9575 
9576 	if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
9577 		rsp->hdr.Status = STATUS_INTERNAL_ERROR;
9578 		smb2_set_err_rsp(work);
9579 		return -EIO;
9580 	}
9581 
9582 	smb2_set_err_rsp(work);
9583 	rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
9584 	return -EOPNOTSUPP;
9585 }
9586 
9587 /**
9588  * smb2_is_sign_req() - handler for checking packet signing status
9589  * @work:	smb work containing notify command buffer
9590  * @command:	SMB2 command id
9591  *
9592  * Return:	true if packed is signed, false otherwise
9593  */
9594 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
9595 {
9596 	struct smb2_hdr *rcv_hdr2 = smb_get_msg(work->request_buf);
9597 
9598 	if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
9599 	    command != SMB2_NEGOTIATE_HE &&
9600 	    command != SMB2_OPLOCK_BREAK_HE)
9601 		return true;
9602 
9603 	return false;
9604 }
9605 
9606 /**
9607  * smb2_check_sign_req() - handler for req packet sign processing
9608  * @work:   smb work containing notify command buffer
9609  *
9610  * Return:	1 on success, 0 otherwise
9611  */
9612 int smb2_check_sign_req(struct ksmbd_work *work)
9613 {
9614 	struct smb2_hdr *hdr;
9615 	char signature_req[SMB2_SIGNATURE_SIZE];
9616 	char signature[SMB2_HMACSHA256_SIZE];
9617 	struct kvec iov[1];
9618 	size_t len;
9619 
9620 	hdr = smb_get_msg(work->request_buf);
9621 	if (work->next_smb2_rcv_hdr_off)
9622 		hdr = ksmbd_req_buf_next(work);
9623 
9624 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
9625 		len = get_rfc1002_len(work->request_buf);
9626 	else if (hdr->NextCommand)
9627 		len = le32_to_cpu(hdr->NextCommand);
9628 	else
9629 		len = get_rfc1002_len(work->request_buf) -
9630 			work->next_smb2_rcv_hdr_off;
9631 
9632 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
9633 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9634 
9635 	iov[0].iov_base = (char *)&hdr->ProtocolId;
9636 	iov[0].iov_len = len;
9637 
9638 	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
9639 			    signature);
9640 
9641 	if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
9642 		pr_err("bad smb2 signature\n");
9643 		return 0;
9644 	}
9645 
9646 	return 1;
9647 }
9648 
9649 /**
9650  * smb2_set_sign_rsp() - handler for rsp packet sign processing
9651  * @work:   smb work containing notify command buffer
9652  *
9653  */
9654 void smb2_set_sign_rsp(struct ksmbd_work *work)
9655 {
9656 	struct smb2_hdr *hdr;
9657 	char signature[SMB2_HMACSHA256_SIZE];
9658 	struct kvec *iov;
9659 	int n_vec = 1;
9660 
9661 	hdr = ksmbd_resp_buf_curr(work);
9662 	hdr->Flags |= SMB2_FLAGS_SIGNED;
9663 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9664 
9665 	if (hdr->Command == SMB2_READ) {
9666 		iov = &work->iov[work->iov_idx - 1];
9667 		n_vec++;
9668 	} else {
9669 		iov = &work->iov[work->iov_idx];
9670 	}
9671 
9672 	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
9673 			    signature);
9674 	memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
9675 }
9676 
9677 /**
9678  * smb3_check_sign_req() - handler for req packet sign processing
9679  * @work:   smb work containing notify command buffer
9680  *
9681  * Return:	1 on success, 0 otherwise
9682  */
9683 int smb3_check_sign_req(struct ksmbd_work *work)
9684 {
9685 	struct ksmbd_conn *conn = work->conn;
9686 	char *signing_key;
9687 	struct smb2_hdr *hdr;
9688 	struct channel *chann;
9689 	char signature_req[SMB2_SIGNATURE_SIZE];
9690 	char signature[SMB2_CMACAES_SIZE];
9691 	struct kvec iov[1];
9692 	size_t len;
9693 
9694 	hdr = smb_get_msg(work->request_buf);
9695 	if (work->next_smb2_rcv_hdr_off)
9696 		hdr = ksmbd_req_buf_next(work);
9697 
9698 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
9699 		len = get_rfc1002_len(work->request_buf);
9700 	else if (hdr->NextCommand)
9701 		len = le32_to_cpu(hdr->NextCommand);
9702 	else
9703 		len = get_rfc1002_len(work->request_buf) -
9704 			work->next_smb2_rcv_hdr_off;
9705 
9706 	if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
9707 		signing_key = work->sess->smb3signingkey;
9708 	} else {
9709 		chann = lookup_chann_list(work->sess, conn);
9710 		if (!chann) {
9711 			if (le16_to_cpu(hdr->Command) != SMB2_SESSION_SETUP_HE ||
9712 			    !(hdr->Flags & SMB2_FLAGS_SIGNED))
9713 				return 0;
9714 			signing_key = work->sess->smb3signingkey;
9715 		} else {
9716 			signing_key = chann->smb3signingkey;
9717 		}
9718 	}
9719 
9720 	if (!signing_key) {
9721 		pr_err("SMB3 signing key is not generated\n");
9722 		return 0;
9723 	}
9724 
9725 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
9726 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9727 	iov[0].iov_base = (char *)&hdr->ProtocolId;
9728 	iov[0].iov_len = len;
9729 
9730 	ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature);
9731 
9732 	if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
9733 		pr_err("bad smb2 signature\n");
9734 		return 0;
9735 	}
9736 
9737 	return 1;
9738 }
9739 
9740 /**
9741  * smb3_set_sign_rsp() - handler for rsp packet sign processing
9742  * @work:   smb work containing notify command buffer
9743  *
9744  */
9745 void smb3_set_sign_rsp(struct ksmbd_work *work)
9746 {
9747 	struct ksmbd_conn *conn = work->conn;
9748 	struct smb2_hdr *hdr;
9749 	struct channel *chann;
9750 	char signature[SMB2_CMACAES_SIZE];
9751 	struct kvec *iov;
9752 	u16 command = conn->ops->get_cmd_val(work);
9753 	int n_vec = 1;
9754 	char *signing_key;
9755 
9756 	hdr = ksmbd_resp_buf_curr(work);
9757 
9758 	if (command == SMB2_SESSION_SETUP_HE &&
9759 	    (!conn->binding || hdr->Status != STATUS_SUCCESS)) {
9760 		signing_key = work->sess->smb3signingkey;
9761 	} else {
9762 		chann = lookup_chann_list(work->sess, work->conn);
9763 		if (!chann) {
9764 			return;
9765 		}
9766 		signing_key = chann->smb3signingkey;
9767 	}
9768 
9769 	if (!signing_key)
9770 		return;
9771 
9772 	hdr->Flags |= SMB2_FLAGS_SIGNED;
9773 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
9774 
9775 	if (hdr->Command == SMB2_READ) {
9776 		iov = &work->iov[work->iov_idx - 1];
9777 		n_vec++;
9778 	} else {
9779 		iov = &work->iov[work->iov_idx];
9780 	}
9781 
9782 	ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature);
9783 	memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
9784 }
9785 
9786 /**
9787  * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
9788  * @work:   smb work containing response buffer
9789  *
9790  */
9791 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
9792 {
9793 	struct ksmbd_conn *conn = work->conn;
9794 	struct ksmbd_session *sess = work->sess;
9795 	struct smb2_hdr *req, *rsp;
9796 
9797 	if (conn->dialect != SMB311_PROT_ID)
9798 		return;
9799 
9800 	WORK_BUFFERS(work, req, rsp);
9801 
9802 	if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE) {
9803 		ksmbd_conn_lock(conn);
9804 		if (conn->preauth_info)
9805 			ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9806 							 conn->preauth_info->Preauth_HashValue);
9807 		ksmbd_conn_unlock(conn);
9808 	}
9809 
9810 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
9811 		ksmbd_conn_lock(conn);
9812 
9813 		if (conn->binding) {
9814 			struct preauth_session *preauth_sess;
9815 
9816 			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
9817 			if (preauth_sess)
9818 				ksmbd_gen_preauth_integrity_hash(conn,
9819 					work->response_buf,
9820 					preauth_sess->Preauth_HashValue);
9821 		} else if (sess->Preauth_HashValue) {
9822 			ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
9823 					 sess->Preauth_HashValue);
9824 		}
9825 		ksmbd_conn_unlock(conn);
9826 	}
9827 }
9828 
9829 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
9830 {
9831 	struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
9832 	struct smb2_hdr *hdr = smb_get_msg(old_buf);
9833 	unsigned int orig_len = get_rfc1002_len(old_buf);
9834 
9835 	/* tr_buf must be cleared by the caller */
9836 	tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
9837 	tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
9838 	tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
9839 	if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
9840 	    cipher_type == SMB2_ENCRYPTION_AES256_GCM)
9841 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
9842 	else
9843 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
9844 	memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
9845 	inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
9846 	inc_rfc1001_len(tr_buf, orig_len);
9847 }
9848 
9849 int smb3_encrypt_resp(struct ksmbd_work *work)
9850 {
9851 	struct kvec *iov = work->iov;
9852 	int rc = -ENOMEM;
9853 	void *tr_buf;
9854 
9855 	tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, KSMBD_DEFAULT_GFP);
9856 	if (!tr_buf)
9857 		return rc;
9858 
9859 	/* fill transform header */
9860 	fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
9861 
9862 	iov[0].iov_base = tr_buf;
9863 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9864 	work->tr_buf = tr_buf;
9865 
9866 	return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
9867 }
9868 
9869 bool smb3_is_transform_hdr(void *buf)
9870 {
9871 	struct smb2_transform_hdr *trhdr = smb_get_msg(buf);
9872 
9873 	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
9874 }
9875 
9876 int smb3_decrypt_req(struct ksmbd_work *work)
9877 {
9878 	struct ksmbd_session *sess;
9879 	char *buf = work->request_buf;
9880 	unsigned int pdu_length = get_rfc1002_len(buf);
9881 	struct kvec iov[2];
9882 	int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
9883 	struct smb2_transform_hdr *tr_hdr = smb_get_msg(buf);
9884 	int rc = 0;
9885 
9886 	if (pdu_length < sizeof(struct smb2_transform_hdr) ||
9887 	    buf_data_size < sizeof(struct smb2_hdr)) {
9888 		pr_err("Transform message is too small (%u)\n",
9889 		       pdu_length);
9890 		return -ECONNABORTED;
9891 	}
9892 
9893 	if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
9894 		pr_err("Transform message is broken\n");
9895 		return -ECONNABORTED;
9896 	}
9897 
9898 	sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
9899 	if (!sess) {
9900 		pr_err("invalid session id(%llx) in transform header\n",
9901 		       le64_to_cpu(tr_hdr->SessionId));
9902 		return -ECONNABORTED;
9903 	}
9904 	ksmbd_user_session_put(sess);
9905 
9906 	iov[0].iov_base = buf;
9907 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
9908 	iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
9909 	iov[1].iov_len = buf_data_size;
9910 	rc = ksmbd_crypt_message(work, iov, 2, 0);
9911 	if (rc)
9912 		return rc;
9913 
9914 	memmove(buf + 4, iov[1].iov_base, buf_data_size);
9915 	*(__be32 *)buf = cpu_to_be32(buf_data_size);
9916 
9917 	return rc;
9918 }
9919 
9920 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
9921 {
9922 	struct ksmbd_conn *conn = work->conn;
9923 	struct ksmbd_session *sess = work->sess;
9924 	struct smb2_hdr *rsp = smb_get_msg(work->response_buf);
9925 
9926 	if (conn->dialect < SMB30_PROT_ID)
9927 		return false;
9928 
9929 	if (work->next_smb2_rcv_hdr_off)
9930 		rsp = ksmbd_resp_buf_next(work);
9931 
9932 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
9933 	    sess->user && !user_guest(sess->user) &&
9934 	    rsp->Status == STATUS_SUCCESS)
9935 		return true;
9936 	return false;
9937 }
9938