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