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