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