xref: /openbmc/linux/fs/smb/server/smb2pdu.c (revision bd9c3c2d)
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(work, 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 rc;
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 	if (ksmbd_override_fsids(work)) {
5605 		rc = -ENOMEM;
5606 		goto err_out;
5607 	}
5608 
5609 	switch (req->InfoType) {
5610 	case SMB2_O_INFO_FILE:
5611 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5612 		rc = smb2_get_info_file(work, req, rsp);
5613 		break;
5614 	case SMB2_O_INFO_FILESYSTEM:
5615 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5616 		rc = smb2_get_info_filesystem(work, req, rsp);
5617 		break;
5618 	case SMB2_O_INFO_SECURITY:
5619 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5620 		rc = smb2_get_info_sec(work, req, rsp);
5621 		break;
5622 	default:
5623 		ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5624 			    req->InfoType);
5625 		rc = -EOPNOTSUPP;
5626 	}
5627 	ksmbd_revert_fsids(work);
5628 
5629 	if (!rc) {
5630 		rsp->StructureSize = cpu_to_le16(9);
5631 		rsp->OutputBufferOffset = cpu_to_le16(72);
5632 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5633 				       offsetof(struct smb2_query_info_rsp, Buffer) +
5634 					le32_to_cpu(rsp->OutputBufferLength));
5635 	}
5636 
5637 err_out:
5638 	if (rc < 0) {
5639 		if (rc == -EACCES)
5640 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
5641 		else if (rc == -ENOENT)
5642 			rsp->hdr.Status = STATUS_FILE_CLOSED;
5643 		else if (rc == -EIO)
5644 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5645 		else if (rc == -ENOMEM)
5646 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5647 		else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5648 			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5649 		smb2_set_err_rsp(work);
5650 
5651 		ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5652 			    rc);
5653 		return rc;
5654 	}
5655 	return 0;
5656 }
5657 
5658 /**
5659  * smb2_close_pipe() - handler for closing IPC pipe
5660  * @work:	smb work containing close request buffer
5661  *
5662  * Return:	0
5663  */
5664 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5665 {
5666 	u64 id;
5667 	struct smb2_close_req *req;
5668 	struct smb2_close_rsp *rsp;
5669 
5670 	WORK_BUFFERS(work, req, rsp);
5671 
5672 	id = req->VolatileFileId;
5673 	ksmbd_session_rpc_close(work->sess, id);
5674 
5675 	rsp->StructureSize = cpu_to_le16(60);
5676 	rsp->Flags = 0;
5677 	rsp->Reserved = 0;
5678 	rsp->CreationTime = 0;
5679 	rsp->LastAccessTime = 0;
5680 	rsp->LastWriteTime = 0;
5681 	rsp->ChangeTime = 0;
5682 	rsp->AllocationSize = 0;
5683 	rsp->EndOfFile = 0;
5684 	rsp->Attributes = 0;
5685 
5686 	return ksmbd_iov_pin_rsp(work, (void *)rsp,
5687 				 sizeof(struct smb2_close_rsp));
5688 }
5689 
5690 /**
5691  * smb2_close() - handler for smb2 close file command
5692  * @work:	smb work containing close request buffer
5693  *
5694  * Return:	0
5695  */
5696 int smb2_close(struct ksmbd_work *work)
5697 {
5698 	u64 volatile_id = KSMBD_NO_FID;
5699 	u64 sess_id;
5700 	struct smb2_close_req *req;
5701 	struct smb2_close_rsp *rsp;
5702 	struct ksmbd_conn *conn = work->conn;
5703 	struct ksmbd_file *fp;
5704 	u64 time;
5705 	int err = 0;
5706 
5707 	WORK_BUFFERS(work, req, rsp);
5708 
5709 	if (test_share_config_flag(work->tcon->share_conf,
5710 				   KSMBD_SHARE_FLAG_PIPE)) {
5711 		ksmbd_debug(SMB, "IPC pipe close request\n");
5712 		return smb2_close_pipe(work);
5713 	}
5714 
5715 	sess_id = le64_to_cpu(req->hdr.SessionId);
5716 	if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5717 		sess_id = work->compound_sid;
5718 
5719 	work->compound_sid = 0;
5720 	if (check_session_id(conn, sess_id)) {
5721 		work->compound_sid = sess_id;
5722 	} else {
5723 		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5724 		if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5725 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5726 		err = -EBADF;
5727 		goto out;
5728 	}
5729 
5730 	if (work->next_smb2_rcv_hdr_off &&
5731 	    !has_file_id(req->VolatileFileId)) {
5732 		if (!has_file_id(work->compound_fid)) {
5733 			/* file already closed, return FILE_CLOSED */
5734 			ksmbd_debug(SMB, "file already closed\n");
5735 			rsp->hdr.Status = STATUS_FILE_CLOSED;
5736 			err = -EBADF;
5737 			goto out;
5738 		} else {
5739 			ksmbd_debug(SMB,
5740 				    "Compound request set FID = %llu:%llu\n",
5741 				    work->compound_fid,
5742 				    work->compound_pfid);
5743 			volatile_id = work->compound_fid;
5744 
5745 			/* file closed, stored id is not valid anymore */
5746 			work->compound_fid = KSMBD_NO_FID;
5747 			work->compound_pfid = KSMBD_NO_FID;
5748 		}
5749 	} else {
5750 		volatile_id = req->VolatileFileId;
5751 	}
5752 	ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5753 
5754 	rsp->StructureSize = cpu_to_le16(60);
5755 	rsp->Reserved = 0;
5756 
5757 	if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5758 		struct kstat stat;
5759 		int ret;
5760 
5761 		fp = ksmbd_lookup_fd_fast(work, volatile_id);
5762 		if (!fp) {
5763 			err = -ENOENT;
5764 			goto out;
5765 		}
5766 
5767 		ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5768 				  AT_STATX_SYNC_AS_STAT);
5769 		if (ret) {
5770 			ksmbd_fd_put(work, fp);
5771 			goto out;
5772 		}
5773 
5774 		rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5775 		rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
5776 			cpu_to_le64(stat.blocks << 9);
5777 		rsp->EndOfFile = cpu_to_le64(stat.size);
5778 		rsp->Attributes = fp->f_ci->m_fattr;
5779 		rsp->CreationTime = cpu_to_le64(fp->create_time);
5780 		time = ksmbd_UnixTimeToNT(stat.atime);
5781 		rsp->LastAccessTime = cpu_to_le64(time);
5782 		time = ksmbd_UnixTimeToNT(stat.mtime);
5783 		rsp->LastWriteTime = cpu_to_le64(time);
5784 		time = ksmbd_UnixTimeToNT(stat.ctime);
5785 		rsp->ChangeTime = cpu_to_le64(time);
5786 		ksmbd_fd_put(work, fp);
5787 	} else {
5788 		rsp->Flags = 0;
5789 		rsp->AllocationSize = 0;
5790 		rsp->EndOfFile = 0;
5791 		rsp->Attributes = 0;
5792 		rsp->CreationTime = 0;
5793 		rsp->LastAccessTime = 0;
5794 		rsp->LastWriteTime = 0;
5795 		rsp->ChangeTime = 0;
5796 	}
5797 
5798 	err = ksmbd_close_fd(work, volatile_id);
5799 out:
5800 	if (!err)
5801 		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
5802 					sizeof(struct smb2_close_rsp));
5803 
5804 	if (err) {
5805 		if (rsp->hdr.Status == 0)
5806 			rsp->hdr.Status = STATUS_FILE_CLOSED;
5807 		smb2_set_err_rsp(work);
5808 	}
5809 
5810 	return err;
5811 }
5812 
5813 /**
5814  * smb2_echo() - handler for smb2 echo(ping) command
5815  * @work:	smb work containing echo request buffer
5816  *
5817  * Return:	0
5818  */
5819 int smb2_echo(struct ksmbd_work *work)
5820 {
5821 	struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5822 
5823 	if (work->next_smb2_rcv_hdr_off)
5824 		rsp = ksmbd_resp_buf_next(work);
5825 
5826 	rsp->StructureSize = cpu_to_le16(4);
5827 	rsp->Reserved = 0;
5828 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
5829 }
5830 
5831 static int smb2_rename(struct ksmbd_work *work,
5832 		       struct ksmbd_file *fp,
5833 		       struct smb2_file_rename_info *file_info,
5834 		       struct nls_table *local_nls)
5835 {
5836 	struct ksmbd_share_config *share = fp->tcon->share_conf;
5837 	char *new_name = NULL;
5838 	int rc, flags = 0;
5839 
5840 	ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5841 	new_name = smb2_get_name(file_info->FileName,
5842 				 le32_to_cpu(file_info->FileNameLength),
5843 				 local_nls);
5844 	if (IS_ERR(new_name))
5845 		return PTR_ERR(new_name);
5846 
5847 	if (strchr(new_name, ':')) {
5848 		int s_type;
5849 		char *xattr_stream_name, *stream_name = NULL;
5850 		size_t xattr_stream_size;
5851 		int len;
5852 
5853 		rc = parse_stream_name(new_name, &stream_name, &s_type);
5854 		if (rc < 0)
5855 			goto out;
5856 
5857 		len = strlen(new_name);
5858 		if (len > 0 && new_name[len - 1] != '/') {
5859 			pr_err("not allow base filename in rename\n");
5860 			rc = -ESHARE;
5861 			goto out;
5862 		}
5863 
5864 		rc = ksmbd_vfs_xattr_stream_name(stream_name,
5865 						 &xattr_stream_name,
5866 						 &xattr_stream_size,
5867 						 s_type);
5868 		if (rc)
5869 			goto out;
5870 
5871 		rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
5872 					&fp->filp->f_path,
5873 					xattr_stream_name,
5874 					NULL, 0, 0, true);
5875 		if (rc < 0) {
5876 			pr_err("failed to store stream name in xattr: %d\n",
5877 			       rc);
5878 			rc = -EINVAL;
5879 			goto out;
5880 		}
5881 
5882 		goto out;
5883 	}
5884 
5885 	ksmbd_debug(SMB, "new name %s\n", new_name);
5886 	if (ksmbd_share_veto_filename(share, new_name)) {
5887 		rc = -ENOENT;
5888 		ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5889 		goto out;
5890 	}
5891 
5892 	if (!file_info->ReplaceIfExists)
5893 		flags = RENAME_NOREPLACE;
5894 
5895 	rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
5896 	if (!rc)
5897 		smb_break_all_levII_oplock(work, fp, 0);
5898 out:
5899 	kfree(new_name);
5900 	return rc;
5901 }
5902 
5903 static int smb2_create_link(struct ksmbd_work *work,
5904 			    struct ksmbd_share_config *share,
5905 			    struct smb2_file_link_info *file_info,
5906 			    unsigned int buf_len, struct file *filp,
5907 			    struct nls_table *local_nls)
5908 {
5909 	char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5910 	struct path path, parent_path;
5911 	bool file_present = false;
5912 	int rc;
5913 
5914 	if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5915 			le32_to_cpu(file_info->FileNameLength))
5916 		return -EINVAL;
5917 
5918 	ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5919 	pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5920 	if (!pathname)
5921 		return -ENOMEM;
5922 
5923 	link_name = smb2_get_name(file_info->FileName,
5924 				  le32_to_cpu(file_info->FileNameLength),
5925 				  local_nls);
5926 	if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5927 		rc = -EINVAL;
5928 		goto out;
5929 	}
5930 
5931 	ksmbd_debug(SMB, "link name is %s\n", link_name);
5932 	target_name = file_path(filp, pathname, PATH_MAX);
5933 	if (IS_ERR(target_name)) {
5934 		rc = -EINVAL;
5935 		goto out;
5936 	}
5937 
5938 	ksmbd_debug(SMB, "target name is %s\n", target_name);
5939 	rc = ksmbd_vfs_kern_path_locked(work, link_name, LOOKUP_NO_SYMLINKS,
5940 					&parent_path, &path, 0);
5941 	if (rc) {
5942 		if (rc != -ENOENT)
5943 			goto out;
5944 	} else
5945 		file_present = true;
5946 
5947 	if (file_info->ReplaceIfExists) {
5948 		if (file_present) {
5949 			rc = ksmbd_vfs_remove_file(work, &path);
5950 			if (rc) {
5951 				rc = -EINVAL;
5952 				ksmbd_debug(SMB, "cannot delete %s\n",
5953 					    link_name);
5954 				goto out;
5955 			}
5956 		}
5957 	} else {
5958 		if (file_present) {
5959 			rc = -EEXIST;
5960 			ksmbd_debug(SMB, "link already exists\n");
5961 			goto out;
5962 		}
5963 	}
5964 
5965 	rc = ksmbd_vfs_link(work, target_name, link_name);
5966 	if (rc)
5967 		rc = -EINVAL;
5968 out:
5969 	if (file_present)
5970 		ksmbd_vfs_kern_path_unlock(&parent_path, &path);
5971 
5972 	if (!IS_ERR(link_name))
5973 		kfree(link_name);
5974 	kfree(pathname);
5975 	return rc;
5976 }
5977 
5978 static int set_file_basic_info(struct ksmbd_file *fp,
5979 			       struct smb2_file_basic_info *file_info,
5980 			       struct ksmbd_share_config *share)
5981 {
5982 	struct iattr attrs;
5983 	struct file *filp;
5984 	struct inode *inode;
5985 	struct mnt_idmap *idmap;
5986 	int rc = 0;
5987 
5988 	if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5989 		return -EACCES;
5990 
5991 	attrs.ia_valid = 0;
5992 	filp = fp->filp;
5993 	inode = file_inode(filp);
5994 	idmap = file_mnt_idmap(filp);
5995 
5996 	if (file_info->CreationTime)
5997 		fp->create_time = le64_to_cpu(file_info->CreationTime);
5998 
5999 	if (file_info->LastAccessTime) {
6000 		attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
6001 		attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
6002 	}
6003 
6004 	attrs.ia_valid |= ATTR_CTIME;
6005 	if (file_info->ChangeTime)
6006 		attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
6007 	else
6008 		attrs.ia_ctime = inode_get_ctime(inode);
6009 
6010 	if (file_info->LastWriteTime) {
6011 		attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
6012 		attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
6013 	}
6014 
6015 	if (file_info->Attributes) {
6016 		if (!S_ISDIR(inode->i_mode) &&
6017 		    file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
6018 			pr_err("can't change a file to a directory\n");
6019 			return -EINVAL;
6020 		}
6021 
6022 		if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
6023 			fp->f_ci->m_fattr = file_info->Attributes |
6024 				(fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
6025 	}
6026 
6027 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
6028 	    (file_info->CreationTime || file_info->Attributes)) {
6029 		struct xattr_dos_attrib da = {0};
6030 
6031 		da.version = 4;
6032 		da.itime = fp->itime;
6033 		da.create_time = fp->create_time;
6034 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
6035 		da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
6036 			XATTR_DOSINFO_ITIME;
6037 
6038 		rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
6039 				true);
6040 		if (rc)
6041 			ksmbd_debug(SMB,
6042 				    "failed to restore file attribute in EA\n");
6043 		rc = 0;
6044 	}
6045 
6046 	if (attrs.ia_valid) {
6047 		struct dentry *dentry = filp->f_path.dentry;
6048 		struct inode *inode = d_inode(dentry);
6049 
6050 		if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
6051 			return -EACCES;
6052 
6053 		inode_lock(inode);
6054 		inode_set_ctime_to_ts(inode, attrs.ia_ctime);
6055 		attrs.ia_valid &= ~ATTR_CTIME;
6056 		rc = notify_change(idmap, dentry, &attrs, NULL);
6057 		inode_unlock(inode);
6058 	}
6059 	return rc;
6060 }
6061 
6062 static int set_file_allocation_info(struct ksmbd_work *work,
6063 				    struct ksmbd_file *fp,
6064 				    struct smb2_file_alloc_info *file_alloc_info)
6065 {
6066 	/*
6067 	 * TODO : It's working fine only when store dos attributes
6068 	 * is not yes. need to implement a logic which works
6069 	 * properly with any smb.conf option
6070 	 */
6071 
6072 	loff_t alloc_blks;
6073 	struct inode *inode;
6074 	struct kstat stat;
6075 	int rc;
6076 
6077 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
6078 		return -EACCES;
6079 
6080 	rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6081 			 AT_STATX_SYNC_AS_STAT);
6082 	if (rc)
6083 		return rc;
6084 
6085 	alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
6086 	inode = file_inode(fp->filp);
6087 
6088 	if (alloc_blks > stat.blocks) {
6089 		smb_break_all_levII_oplock(work, fp, 1);
6090 		rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
6091 				   alloc_blks * 512);
6092 		if (rc && rc != -EOPNOTSUPP) {
6093 			pr_err("vfs_fallocate is failed : %d\n", rc);
6094 			return rc;
6095 		}
6096 	} else if (alloc_blks < stat.blocks) {
6097 		loff_t size;
6098 
6099 		/*
6100 		 * Allocation size could be smaller than original one
6101 		 * which means allocated blocks in file should be
6102 		 * deallocated. use truncate to cut out it, but inode
6103 		 * size is also updated with truncate offset.
6104 		 * inode size is retained by backup inode size.
6105 		 */
6106 		size = i_size_read(inode);
6107 		rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
6108 		if (rc) {
6109 			pr_err("truncate failed!, err %d\n", rc);
6110 			return rc;
6111 		}
6112 		if (size < alloc_blks * 512)
6113 			i_size_write(inode, size);
6114 	}
6115 	return 0;
6116 }
6117 
6118 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6119 				struct smb2_file_eof_info *file_eof_info)
6120 {
6121 	loff_t newsize;
6122 	struct inode *inode;
6123 	int rc;
6124 
6125 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
6126 		return -EACCES;
6127 
6128 	newsize = le64_to_cpu(file_eof_info->EndOfFile);
6129 	inode = file_inode(fp->filp);
6130 
6131 	/*
6132 	 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
6133 	 * on FAT32 shared device, truncate execution time is too long
6134 	 * and network error could cause from windows client. because
6135 	 * truncate of some filesystem like FAT32 fill zero data in
6136 	 * truncated range.
6137 	 */
6138 	if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
6139 		ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
6140 		rc = ksmbd_vfs_truncate(work, fp, newsize);
6141 		if (rc) {
6142 			ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
6143 			if (rc != -EAGAIN)
6144 				rc = -EBADF;
6145 			return rc;
6146 		}
6147 	}
6148 	return 0;
6149 }
6150 
6151 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6152 			   struct smb2_file_rename_info *rename_info,
6153 			   unsigned int buf_len)
6154 {
6155 	if (!(fp->daccess & FILE_DELETE_LE)) {
6156 		pr_err("no right to delete : 0x%x\n", fp->daccess);
6157 		return -EACCES;
6158 	}
6159 
6160 	if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
6161 			le32_to_cpu(rename_info->FileNameLength))
6162 		return -EINVAL;
6163 
6164 	if (!le32_to_cpu(rename_info->FileNameLength))
6165 		return -EINVAL;
6166 
6167 	return smb2_rename(work, fp, rename_info, work->conn->local_nls);
6168 }
6169 
6170 static int set_file_disposition_info(struct ksmbd_file *fp,
6171 				     struct smb2_file_disposition_info *file_info)
6172 {
6173 	struct inode *inode;
6174 
6175 	if (!(fp->daccess & FILE_DELETE_LE)) {
6176 		pr_err("no right to delete : 0x%x\n", fp->daccess);
6177 		return -EACCES;
6178 	}
6179 
6180 	inode = file_inode(fp->filp);
6181 	if (file_info->DeletePending) {
6182 		if (S_ISDIR(inode->i_mode) &&
6183 		    ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
6184 			return -EBUSY;
6185 		ksmbd_set_inode_pending_delete(fp);
6186 	} else {
6187 		ksmbd_clear_inode_pending_delete(fp);
6188 	}
6189 	return 0;
6190 }
6191 
6192 static int set_file_position_info(struct ksmbd_file *fp,
6193 				  struct smb2_file_pos_info *file_info)
6194 {
6195 	loff_t current_byte_offset;
6196 	unsigned long sector_size;
6197 	struct inode *inode;
6198 
6199 	inode = file_inode(fp->filp);
6200 	current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
6201 	sector_size = inode->i_sb->s_blocksize;
6202 
6203 	if (current_byte_offset < 0 ||
6204 	    (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
6205 	     current_byte_offset & (sector_size - 1))) {
6206 		pr_err("CurrentByteOffset is not valid : %llu\n",
6207 		       current_byte_offset);
6208 		return -EINVAL;
6209 	}
6210 
6211 	fp->filp->f_pos = current_byte_offset;
6212 	return 0;
6213 }
6214 
6215 static int set_file_mode_info(struct ksmbd_file *fp,
6216 			      struct smb2_file_mode_info *file_info)
6217 {
6218 	__le32 mode;
6219 
6220 	mode = file_info->Mode;
6221 
6222 	if ((mode & ~FILE_MODE_INFO_MASK)) {
6223 		pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
6224 		return -EINVAL;
6225 	}
6226 
6227 	/*
6228 	 * TODO : need to implement consideration for
6229 	 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
6230 	 */
6231 	ksmbd_vfs_set_fadvise(fp->filp, mode);
6232 	fp->coption = mode;
6233 	return 0;
6234 }
6235 
6236 /**
6237  * smb2_set_info_file() - handler for smb2 set info command
6238  * @work:	smb work containing set info command buffer
6239  * @fp:		ksmbd_file pointer
6240  * @req:	request buffer pointer
6241  * @share:	ksmbd_share_config pointer
6242  *
6243  * Return:	0 on success, otherwise error
6244  * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
6245  */
6246 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
6247 			      struct smb2_set_info_req *req,
6248 			      struct ksmbd_share_config *share)
6249 {
6250 	unsigned int buf_len = le32_to_cpu(req->BufferLength);
6251 	char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
6252 
6253 	switch (req->FileInfoClass) {
6254 	case FILE_BASIC_INFORMATION:
6255 	{
6256 		if (buf_len < sizeof(struct smb2_file_basic_info))
6257 			return -EINVAL;
6258 
6259 		return set_file_basic_info(fp, (struct smb2_file_basic_info *)buffer, share);
6260 	}
6261 	case FILE_ALLOCATION_INFORMATION:
6262 	{
6263 		if (buf_len < sizeof(struct smb2_file_alloc_info))
6264 			return -EINVAL;
6265 
6266 		return set_file_allocation_info(work, fp,
6267 						(struct smb2_file_alloc_info *)buffer);
6268 	}
6269 	case FILE_END_OF_FILE_INFORMATION:
6270 	{
6271 		if (buf_len < sizeof(struct smb2_file_eof_info))
6272 			return -EINVAL;
6273 
6274 		return set_end_of_file_info(work, fp,
6275 					    (struct smb2_file_eof_info *)buffer);
6276 	}
6277 	case FILE_RENAME_INFORMATION:
6278 	{
6279 		if (buf_len < sizeof(struct smb2_file_rename_info))
6280 			return -EINVAL;
6281 
6282 		return set_rename_info(work, fp,
6283 				       (struct smb2_file_rename_info *)buffer,
6284 				       buf_len);
6285 	}
6286 	case FILE_LINK_INFORMATION:
6287 	{
6288 		if (buf_len < sizeof(struct smb2_file_link_info))
6289 			return -EINVAL;
6290 
6291 		return smb2_create_link(work, work->tcon->share_conf,
6292 					(struct smb2_file_link_info *)buffer,
6293 					buf_len, fp->filp,
6294 					work->conn->local_nls);
6295 	}
6296 	case FILE_DISPOSITION_INFORMATION:
6297 	{
6298 		if (buf_len < sizeof(struct smb2_file_disposition_info))
6299 			return -EINVAL;
6300 
6301 		return set_file_disposition_info(fp,
6302 						 (struct smb2_file_disposition_info *)buffer);
6303 	}
6304 	case FILE_FULL_EA_INFORMATION:
6305 	{
6306 		if (!(fp->daccess & FILE_WRITE_EA_LE)) {
6307 			pr_err("Not permitted to write ext  attr: 0x%x\n",
6308 			       fp->daccess);
6309 			return -EACCES;
6310 		}
6311 
6312 		if (buf_len < sizeof(struct smb2_ea_info))
6313 			return -EINVAL;
6314 
6315 		return smb2_set_ea((struct smb2_ea_info *)buffer,
6316 				   buf_len, &fp->filp->f_path, true);
6317 	}
6318 	case FILE_POSITION_INFORMATION:
6319 	{
6320 		if (buf_len < sizeof(struct smb2_file_pos_info))
6321 			return -EINVAL;
6322 
6323 		return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
6324 	}
6325 	case FILE_MODE_INFORMATION:
6326 	{
6327 		if (buf_len < sizeof(struct smb2_file_mode_info))
6328 			return -EINVAL;
6329 
6330 		return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
6331 	}
6332 	}
6333 
6334 	pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6335 	return -EOPNOTSUPP;
6336 }
6337 
6338 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6339 			     char *buffer, int buf_len)
6340 {
6341 	struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6342 
6343 	fp->saccess |= FILE_SHARE_DELETE_LE;
6344 
6345 	return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6346 			buf_len, false, true);
6347 }
6348 
6349 /**
6350  * smb2_set_info() - handler for smb2 set info command handler
6351  * @work:	smb work containing set info request buffer
6352  *
6353  * Return:	0 on success, otherwise error
6354  */
6355 int smb2_set_info(struct ksmbd_work *work)
6356 {
6357 	struct smb2_set_info_req *req;
6358 	struct smb2_set_info_rsp *rsp;
6359 	struct ksmbd_file *fp = NULL;
6360 	int rc = 0;
6361 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6362 
6363 	ksmbd_debug(SMB, "Received set info request\n");
6364 
6365 	if (work->next_smb2_rcv_hdr_off) {
6366 		req = ksmbd_req_buf_next(work);
6367 		rsp = ksmbd_resp_buf_next(work);
6368 		if (!has_file_id(req->VolatileFileId)) {
6369 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6370 				    work->compound_fid);
6371 			id = work->compound_fid;
6372 			pid = work->compound_pfid;
6373 		}
6374 	} else {
6375 		req = smb2_get_msg(work->request_buf);
6376 		rsp = smb2_get_msg(work->response_buf);
6377 	}
6378 
6379 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6380 		ksmbd_debug(SMB, "User does not have write permission\n");
6381 		pr_err("User does not have write permission\n");
6382 		rc = -EACCES;
6383 		goto err_out;
6384 	}
6385 
6386 	if (!has_file_id(id)) {
6387 		id = req->VolatileFileId;
6388 		pid = req->PersistentFileId;
6389 	}
6390 
6391 	fp = ksmbd_lookup_fd_slow(work, id, pid);
6392 	if (!fp) {
6393 		ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6394 		rc = -ENOENT;
6395 		goto err_out;
6396 	}
6397 
6398 	switch (req->InfoType) {
6399 	case SMB2_O_INFO_FILE:
6400 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6401 		rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6402 		break;
6403 	case SMB2_O_INFO_SECURITY:
6404 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6405 		if (ksmbd_override_fsids(work)) {
6406 			rc = -ENOMEM;
6407 			goto err_out;
6408 		}
6409 		rc = smb2_set_info_sec(fp,
6410 				       le32_to_cpu(req->AdditionalInformation),
6411 				       (char *)req + le16_to_cpu(req->BufferOffset),
6412 				       le32_to_cpu(req->BufferLength));
6413 		ksmbd_revert_fsids(work);
6414 		break;
6415 	default:
6416 		rc = -EOPNOTSUPP;
6417 	}
6418 
6419 	if (rc < 0)
6420 		goto err_out;
6421 
6422 	rsp->StructureSize = cpu_to_le16(2);
6423 	rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6424 			       sizeof(struct smb2_set_info_rsp));
6425 	if (rc)
6426 		goto err_out;
6427 	ksmbd_fd_put(work, fp);
6428 	return 0;
6429 
6430 err_out:
6431 	if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6432 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
6433 	else if (rc == -EINVAL)
6434 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6435 	else if (rc == -ESHARE)
6436 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6437 	else if (rc == -ENOENT)
6438 		rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6439 	else if (rc == -EBUSY || rc == -ENOTEMPTY)
6440 		rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6441 	else if (rc == -EAGAIN)
6442 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6443 	else if (rc == -EBADF || rc == -ESTALE)
6444 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
6445 	else if (rc == -EEXIST)
6446 		rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6447 	else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6448 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6449 	smb2_set_err_rsp(work);
6450 	ksmbd_fd_put(work, fp);
6451 	ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6452 	return rc;
6453 }
6454 
6455 /**
6456  * smb2_read_pipe() - handler for smb2 read from IPC pipe
6457  * @work:	smb work containing read IPC pipe command buffer
6458  *
6459  * Return:	0 on success, otherwise error
6460  */
6461 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6462 {
6463 	int nbytes = 0, err;
6464 	u64 id;
6465 	struct ksmbd_rpc_command *rpc_resp;
6466 	struct smb2_read_req *req;
6467 	struct smb2_read_rsp *rsp;
6468 
6469 	WORK_BUFFERS(work, req, rsp);
6470 
6471 	id = req->VolatileFileId;
6472 
6473 	rpc_resp = ksmbd_rpc_read(work->sess, id);
6474 	if (rpc_resp) {
6475 		void *aux_payload_buf;
6476 
6477 		if (rpc_resp->flags != KSMBD_RPC_OK) {
6478 			err = -EINVAL;
6479 			goto out;
6480 		}
6481 
6482 		aux_payload_buf =
6483 			kvmalloc(rpc_resp->payload_sz, GFP_KERNEL);
6484 		if (!aux_payload_buf) {
6485 			err = -ENOMEM;
6486 			goto out;
6487 		}
6488 
6489 		memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6490 
6491 		nbytes = rpc_resp->payload_sz;
6492 		err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6493 					     offsetof(struct smb2_read_rsp, Buffer),
6494 					     aux_payload_buf, nbytes);
6495 		if (err) {
6496 			kvfree(aux_payload_buf);
6497 			goto out;
6498 		}
6499 		kvfree(rpc_resp);
6500 	} else {
6501 		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6502 					offsetof(struct smb2_read_rsp, Buffer));
6503 		if (err)
6504 			goto out;
6505 	}
6506 
6507 	rsp->StructureSize = cpu_to_le16(17);
6508 	rsp->DataOffset = 80;
6509 	rsp->Reserved = 0;
6510 	rsp->DataLength = cpu_to_le32(nbytes);
6511 	rsp->DataRemaining = 0;
6512 	rsp->Flags = 0;
6513 	return 0;
6514 
6515 out:
6516 	rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6517 	smb2_set_err_rsp(work);
6518 	kvfree(rpc_resp);
6519 	return err;
6520 }
6521 
6522 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6523 					struct smb2_buffer_desc_v1 *desc,
6524 					__le32 Channel,
6525 					__le16 ChannelInfoLength)
6526 {
6527 	unsigned int i, ch_count;
6528 
6529 	if (work->conn->dialect == SMB30_PROT_ID &&
6530 	    Channel != SMB2_CHANNEL_RDMA_V1)
6531 		return -EINVAL;
6532 
6533 	ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6534 	if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6535 		for (i = 0; i < ch_count; i++) {
6536 			pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6537 				i,
6538 				le32_to_cpu(desc[i].token),
6539 				le32_to_cpu(desc[i].length));
6540 		}
6541 	}
6542 	if (!ch_count)
6543 		return -EINVAL;
6544 
6545 	work->need_invalidate_rkey =
6546 		(Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6547 	if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6548 		work->remote_key = le32_to_cpu(desc->token);
6549 	return 0;
6550 }
6551 
6552 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6553 				      struct smb2_read_req *req, void *data_buf,
6554 				      size_t length)
6555 {
6556 	int err;
6557 
6558 	err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6559 				    (struct smb2_buffer_desc_v1 *)
6560 				    ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6561 				    le16_to_cpu(req->ReadChannelInfoLength));
6562 	if (err)
6563 		return err;
6564 
6565 	return length;
6566 }
6567 
6568 /**
6569  * smb2_read() - handler for smb2 read from file
6570  * @work:	smb work containing read command buffer
6571  *
6572  * Return:	0 on success, otherwise error
6573  */
6574 int smb2_read(struct ksmbd_work *work)
6575 {
6576 	struct ksmbd_conn *conn = work->conn;
6577 	struct smb2_read_req *req;
6578 	struct smb2_read_rsp *rsp;
6579 	struct ksmbd_file *fp = NULL;
6580 	loff_t offset;
6581 	size_t length, mincount;
6582 	ssize_t nbytes = 0, remain_bytes = 0;
6583 	int err = 0;
6584 	bool is_rdma_channel = false;
6585 	unsigned int max_read_size = conn->vals->max_read_size;
6586 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6587 	void *aux_payload_buf;
6588 
6589 	if (test_share_config_flag(work->tcon->share_conf,
6590 				   KSMBD_SHARE_FLAG_PIPE)) {
6591 		ksmbd_debug(SMB, "IPC pipe read request\n");
6592 		return smb2_read_pipe(work);
6593 	}
6594 
6595 	if (work->next_smb2_rcv_hdr_off) {
6596 		req = ksmbd_req_buf_next(work);
6597 		rsp = ksmbd_resp_buf_next(work);
6598 		if (!has_file_id(req->VolatileFileId)) {
6599 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6600 					work->compound_fid);
6601 			id = work->compound_fid;
6602 			pid = work->compound_pfid;
6603 		}
6604 	} else {
6605 		req = smb2_get_msg(work->request_buf);
6606 		rsp = smb2_get_msg(work->response_buf);
6607 	}
6608 
6609 	if (!has_file_id(id)) {
6610 		id = req->VolatileFileId;
6611 		pid = req->PersistentFileId;
6612 	}
6613 
6614 	if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6615 	    req->Channel == SMB2_CHANNEL_RDMA_V1) {
6616 		is_rdma_channel = true;
6617 		max_read_size = get_smbd_max_read_write_size();
6618 	}
6619 
6620 	if (is_rdma_channel == true) {
6621 		unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6622 
6623 		if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6624 			err = -EINVAL;
6625 			goto out;
6626 		}
6627 		err = smb2_set_remote_key_for_rdma(work,
6628 						   (struct smb2_buffer_desc_v1 *)
6629 						   ((char *)req + ch_offset),
6630 						   req->Channel,
6631 						   req->ReadChannelInfoLength);
6632 		if (err)
6633 			goto out;
6634 	}
6635 
6636 	fp = ksmbd_lookup_fd_slow(work, id, pid);
6637 	if (!fp) {
6638 		err = -ENOENT;
6639 		goto out;
6640 	}
6641 
6642 	if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6643 		pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6644 		err = -EACCES;
6645 		goto out;
6646 	}
6647 
6648 	offset = le64_to_cpu(req->Offset);
6649 	length = le32_to_cpu(req->Length);
6650 	mincount = le32_to_cpu(req->MinimumCount);
6651 
6652 	if (length > max_read_size) {
6653 		ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6654 			    max_read_size);
6655 		err = -EINVAL;
6656 		goto out;
6657 	}
6658 
6659 	ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6660 		    fp->filp, offset, length);
6661 
6662 	aux_payload_buf = kvzalloc(length, GFP_KERNEL);
6663 	if (!aux_payload_buf) {
6664 		err = -ENOMEM;
6665 		goto out;
6666 	}
6667 
6668 	nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6669 	if (nbytes < 0) {
6670 		err = nbytes;
6671 		goto out;
6672 	}
6673 
6674 	if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6675 		kvfree(aux_payload_buf);
6676 		rsp->hdr.Status = STATUS_END_OF_FILE;
6677 		smb2_set_err_rsp(work);
6678 		ksmbd_fd_put(work, fp);
6679 		return 0;
6680 	}
6681 
6682 	ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6683 		    nbytes, offset, mincount);
6684 
6685 	if (is_rdma_channel == true) {
6686 		/* write data to the client using rdma channel */
6687 		remain_bytes = smb2_read_rdma_channel(work, req,
6688 						      aux_payload_buf,
6689 						      nbytes);
6690 		kvfree(aux_payload_buf);
6691 		aux_payload_buf = NULL;
6692 		nbytes = 0;
6693 		if (remain_bytes < 0) {
6694 			err = (int)remain_bytes;
6695 			goto out;
6696 		}
6697 	}
6698 
6699 	rsp->StructureSize = cpu_to_le16(17);
6700 	rsp->DataOffset = 80;
6701 	rsp->Reserved = 0;
6702 	rsp->DataLength = cpu_to_le32(nbytes);
6703 	rsp->DataRemaining = cpu_to_le32(remain_bytes);
6704 	rsp->Flags = 0;
6705 	err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6706 				     offsetof(struct smb2_read_rsp, Buffer),
6707 				     aux_payload_buf, nbytes);
6708 	if (err) {
6709 		kvfree(aux_payload_buf);
6710 		goto out;
6711 	}
6712 	ksmbd_fd_put(work, fp);
6713 	return 0;
6714 
6715 out:
6716 	if (err) {
6717 		if (err == -EISDIR)
6718 			rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6719 		else if (err == -EAGAIN)
6720 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6721 		else if (err == -ENOENT)
6722 			rsp->hdr.Status = STATUS_FILE_CLOSED;
6723 		else if (err == -EACCES)
6724 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
6725 		else if (err == -ESHARE)
6726 			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6727 		else if (err == -EINVAL)
6728 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6729 		else
6730 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
6731 
6732 		smb2_set_err_rsp(work);
6733 	}
6734 	ksmbd_fd_put(work, fp);
6735 	return err;
6736 }
6737 
6738 /**
6739  * smb2_write_pipe() - handler for smb2 write on IPC pipe
6740  * @work:	smb work containing write IPC pipe command buffer
6741  *
6742  * Return:	0 on success, otherwise error
6743  */
6744 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6745 {
6746 	struct smb2_write_req *req;
6747 	struct smb2_write_rsp *rsp;
6748 	struct ksmbd_rpc_command *rpc_resp;
6749 	u64 id = 0;
6750 	int err = 0, ret = 0;
6751 	char *data_buf;
6752 	size_t length;
6753 
6754 	WORK_BUFFERS(work, req, rsp);
6755 
6756 	length = le32_to_cpu(req->Length);
6757 	id = req->VolatileFileId;
6758 
6759 	if ((u64)le16_to_cpu(req->DataOffset) + length >
6760 	    get_rfc1002_len(work->request_buf)) {
6761 		pr_err("invalid write data offset %u, smb_len %u\n",
6762 		       le16_to_cpu(req->DataOffset),
6763 		       get_rfc1002_len(work->request_buf));
6764 		err = -EINVAL;
6765 		goto out;
6766 	}
6767 
6768 	data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6769 			   le16_to_cpu(req->DataOffset));
6770 
6771 	rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6772 	if (rpc_resp) {
6773 		if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6774 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6775 			kvfree(rpc_resp);
6776 			smb2_set_err_rsp(work);
6777 			return -EOPNOTSUPP;
6778 		}
6779 		if (rpc_resp->flags != KSMBD_RPC_OK) {
6780 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
6781 			smb2_set_err_rsp(work);
6782 			kvfree(rpc_resp);
6783 			return ret;
6784 		}
6785 		kvfree(rpc_resp);
6786 	}
6787 
6788 	rsp->StructureSize = cpu_to_le16(17);
6789 	rsp->DataOffset = 0;
6790 	rsp->Reserved = 0;
6791 	rsp->DataLength = cpu_to_le32(length);
6792 	rsp->DataRemaining = 0;
6793 	rsp->Reserved2 = 0;
6794 	err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6795 				offsetof(struct smb2_write_rsp, Buffer));
6796 out:
6797 	if (err) {
6798 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
6799 		smb2_set_err_rsp(work);
6800 	}
6801 
6802 	return err;
6803 }
6804 
6805 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6806 				       struct smb2_write_req *req,
6807 				       struct ksmbd_file *fp,
6808 				       loff_t offset, size_t length, bool sync)
6809 {
6810 	char *data_buf;
6811 	int ret;
6812 	ssize_t nbytes;
6813 
6814 	data_buf = kvzalloc(length, GFP_KERNEL);
6815 	if (!data_buf)
6816 		return -ENOMEM;
6817 
6818 	ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6819 				   (struct smb2_buffer_desc_v1 *)
6820 				   ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6821 				   le16_to_cpu(req->WriteChannelInfoLength));
6822 	if (ret < 0) {
6823 		kvfree(data_buf);
6824 		return ret;
6825 	}
6826 
6827 	ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6828 	kvfree(data_buf);
6829 	if (ret < 0)
6830 		return ret;
6831 
6832 	return nbytes;
6833 }
6834 
6835 /**
6836  * smb2_write() - handler for smb2 write from file
6837  * @work:	smb work containing write command buffer
6838  *
6839  * Return:	0 on success, otherwise error
6840  */
6841 int smb2_write(struct ksmbd_work *work)
6842 {
6843 	struct smb2_write_req *req;
6844 	struct smb2_write_rsp *rsp;
6845 	struct ksmbd_file *fp = NULL;
6846 	loff_t offset;
6847 	size_t length;
6848 	ssize_t nbytes;
6849 	char *data_buf;
6850 	bool writethrough = false, is_rdma_channel = false;
6851 	int err = 0;
6852 	unsigned int max_write_size = work->conn->vals->max_write_size;
6853 
6854 	WORK_BUFFERS(work, req, rsp);
6855 
6856 	if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6857 		ksmbd_debug(SMB, "IPC pipe write request\n");
6858 		return smb2_write_pipe(work);
6859 	}
6860 
6861 	offset = le64_to_cpu(req->Offset);
6862 	length = le32_to_cpu(req->Length);
6863 
6864 	if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6865 	    req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6866 		is_rdma_channel = true;
6867 		max_write_size = get_smbd_max_read_write_size();
6868 		length = le32_to_cpu(req->RemainingBytes);
6869 	}
6870 
6871 	if (is_rdma_channel == true) {
6872 		unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6873 
6874 		if (req->Length != 0 || req->DataOffset != 0 ||
6875 		    ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6876 			err = -EINVAL;
6877 			goto out;
6878 		}
6879 		err = smb2_set_remote_key_for_rdma(work,
6880 						   (struct smb2_buffer_desc_v1 *)
6881 						   ((char *)req + ch_offset),
6882 						   req->Channel,
6883 						   req->WriteChannelInfoLength);
6884 		if (err)
6885 			goto out;
6886 	}
6887 
6888 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6889 		ksmbd_debug(SMB, "User does not have write permission\n");
6890 		err = -EACCES;
6891 		goto out;
6892 	}
6893 
6894 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6895 	if (!fp) {
6896 		err = -ENOENT;
6897 		goto out;
6898 	}
6899 
6900 	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6901 		pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6902 		err = -EACCES;
6903 		goto out;
6904 	}
6905 
6906 	if (length > max_write_size) {
6907 		ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6908 			    max_write_size);
6909 		err = -EINVAL;
6910 		goto out;
6911 	}
6912 
6913 	ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6914 	if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6915 		writethrough = true;
6916 
6917 	if (is_rdma_channel == false) {
6918 		if (le16_to_cpu(req->DataOffset) <
6919 		    offsetof(struct smb2_write_req, Buffer)) {
6920 			err = -EINVAL;
6921 			goto out;
6922 		}
6923 
6924 		data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6925 				    le16_to_cpu(req->DataOffset));
6926 
6927 		ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6928 			    fp->filp, offset, length);
6929 		err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6930 				      writethrough, &nbytes);
6931 		if (err < 0)
6932 			goto out;
6933 	} else {
6934 		/* read data from the client using rdma channel, and
6935 		 * write the data.
6936 		 */
6937 		nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6938 						 writethrough);
6939 		if (nbytes < 0) {
6940 			err = (int)nbytes;
6941 			goto out;
6942 		}
6943 	}
6944 
6945 	rsp->StructureSize = cpu_to_le16(17);
6946 	rsp->DataOffset = 0;
6947 	rsp->Reserved = 0;
6948 	rsp->DataLength = cpu_to_le32(nbytes);
6949 	rsp->DataRemaining = 0;
6950 	rsp->Reserved2 = 0;
6951 	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
6952 	if (err)
6953 		goto out;
6954 	ksmbd_fd_put(work, fp);
6955 	return 0;
6956 
6957 out:
6958 	if (err == -EAGAIN)
6959 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6960 	else if (err == -ENOSPC || err == -EFBIG)
6961 		rsp->hdr.Status = STATUS_DISK_FULL;
6962 	else if (err == -ENOENT)
6963 		rsp->hdr.Status = STATUS_FILE_CLOSED;
6964 	else if (err == -EACCES)
6965 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
6966 	else if (err == -ESHARE)
6967 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6968 	else if (err == -EINVAL)
6969 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6970 	else
6971 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
6972 
6973 	smb2_set_err_rsp(work);
6974 	ksmbd_fd_put(work, fp);
6975 	return err;
6976 }
6977 
6978 /**
6979  * smb2_flush() - handler for smb2 flush file - fsync
6980  * @work:	smb work containing flush command buffer
6981  *
6982  * Return:	0 on success, otherwise error
6983  */
6984 int smb2_flush(struct ksmbd_work *work)
6985 {
6986 	struct smb2_flush_req *req;
6987 	struct smb2_flush_rsp *rsp;
6988 	int err;
6989 
6990 	WORK_BUFFERS(work, req, rsp);
6991 
6992 	ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6993 
6994 	err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6995 	if (err)
6996 		goto out;
6997 
6998 	rsp->StructureSize = cpu_to_le16(4);
6999 	rsp->Reserved = 0;
7000 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
7001 
7002 out:
7003 	rsp->hdr.Status = STATUS_INVALID_HANDLE;
7004 	smb2_set_err_rsp(work);
7005 	return err;
7006 }
7007 
7008 /**
7009  * smb2_cancel() - handler for smb2 cancel command
7010  * @work:	smb work containing cancel command buffer
7011  *
7012  * Return:	0 on success, otherwise error
7013  */
7014 int smb2_cancel(struct ksmbd_work *work)
7015 {
7016 	struct ksmbd_conn *conn = work->conn;
7017 	struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
7018 	struct smb2_hdr *chdr;
7019 	struct ksmbd_work *iter;
7020 	struct list_head *command_list;
7021 
7022 	if (work->next_smb2_rcv_hdr_off)
7023 		hdr = ksmbd_resp_buf_next(work);
7024 
7025 	ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
7026 		    hdr->MessageId, hdr->Flags);
7027 
7028 	if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
7029 		command_list = &conn->async_requests;
7030 
7031 		spin_lock(&conn->request_lock);
7032 		list_for_each_entry(iter, command_list,
7033 				    async_request_entry) {
7034 			chdr = smb2_get_msg(iter->request_buf);
7035 
7036 			if (iter->async_id !=
7037 			    le64_to_cpu(hdr->Id.AsyncId))
7038 				continue;
7039 
7040 			ksmbd_debug(SMB,
7041 				    "smb2 with AsyncId %llu cancelled command = 0x%x\n",
7042 				    le64_to_cpu(hdr->Id.AsyncId),
7043 				    le16_to_cpu(chdr->Command));
7044 			iter->state = KSMBD_WORK_CANCELLED;
7045 			if (iter->cancel_fn)
7046 				iter->cancel_fn(iter->cancel_argv);
7047 			break;
7048 		}
7049 		spin_unlock(&conn->request_lock);
7050 	} else {
7051 		command_list = &conn->requests;
7052 
7053 		spin_lock(&conn->request_lock);
7054 		list_for_each_entry(iter, command_list, request_entry) {
7055 			chdr = smb2_get_msg(iter->request_buf);
7056 
7057 			if (chdr->MessageId != hdr->MessageId ||
7058 			    iter == work)
7059 				continue;
7060 
7061 			ksmbd_debug(SMB,
7062 				    "smb2 with mid %llu cancelled command = 0x%x\n",
7063 				    le64_to_cpu(hdr->MessageId),
7064 				    le16_to_cpu(chdr->Command));
7065 			iter->state = KSMBD_WORK_CANCELLED;
7066 			break;
7067 		}
7068 		spin_unlock(&conn->request_lock);
7069 	}
7070 
7071 	/* For SMB2_CANCEL command itself send no response*/
7072 	work->send_no_response = 1;
7073 	return 0;
7074 }
7075 
7076 struct file_lock *smb_flock_init(struct file *f)
7077 {
7078 	struct file_lock *fl;
7079 
7080 	fl = locks_alloc_lock();
7081 	if (!fl)
7082 		goto out;
7083 
7084 	locks_init_lock(fl);
7085 
7086 	fl->fl_owner = f;
7087 	fl->fl_pid = current->tgid;
7088 	fl->fl_file = f;
7089 	fl->fl_flags = FL_POSIX;
7090 	fl->fl_ops = NULL;
7091 	fl->fl_lmops = NULL;
7092 
7093 out:
7094 	return fl;
7095 }
7096 
7097 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
7098 {
7099 	int cmd = -EINVAL;
7100 
7101 	/* Checking for wrong flag combination during lock request*/
7102 	switch (flags) {
7103 	case SMB2_LOCKFLAG_SHARED:
7104 		ksmbd_debug(SMB, "received shared request\n");
7105 		cmd = F_SETLKW;
7106 		flock->fl_type = F_RDLCK;
7107 		flock->fl_flags |= FL_SLEEP;
7108 		break;
7109 	case SMB2_LOCKFLAG_EXCLUSIVE:
7110 		ksmbd_debug(SMB, "received exclusive request\n");
7111 		cmd = F_SETLKW;
7112 		flock->fl_type = F_WRLCK;
7113 		flock->fl_flags |= FL_SLEEP;
7114 		break;
7115 	case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7116 		ksmbd_debug(SMB,
7117 			    "received shared & fail immediately request\n");
7118 		cmd = F_SETLK;
7119 		flock->fl_type = F_RDLCK;
7120 		break;
7121 	case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7122 		ksmbd_debug(SMB,
7123 			    "received exclusive & fail immediately request\n");
7124 		cmd = F_SETLK;
7125 		flock->fl_type = F_WRLCK;
7126 		break;
7127 	case SMB2_LOCKFLAG_UNLOCK:
7128 		ksmbd_debug(SMB, "received unlock request\n");
7129 		flock->fl_type = F_UNLCK;
7130 		cmd = F_SETLK;
7131 		break;
7132 	}
7133 
7134 	return cmd;
7135 }
7136 
7137 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
7138 					 unsigned int cmd, int flags,
7139 					 struct list_head *lock_list)
7140 {
7141 	struct ksmbd_lock *lock;
7142 
7143 	lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
7144 	if (!lock)
7145 		return NULL;
7146 
7147 	lock->cmd = cmd;
7148 	lock->fl = flock;
7149 	lock->start = flock->fl_start;
7150 	lock->end = flock->fl_end;
7151 	lock->flags = flags;
7152 	if (lock->start == lock->end)
7153 		lock->zero_len = 1;
7154 	INIT_LIST_HEAD(&lock->clist);
7155 	INIT_LIST_HEAD(&lock->flist);
7156 	INIT_LIST_HEAD(&lock->llist);
7157 	list_add_tail(&lock->llist, lock_list);
7158 
7159 	return lock;
7160 }
7161 
7162 static void smb2_remove_blocked_lock(void **argv)
7163 {
7164 	struct file_lock *flock = (struct file_lock *)argv[0];
7165 
7166 	ksmbd_vfs_posix_lock_unblock(flock);
7167 	wake_up(&flock->fl_wait);
7168 }
7169 
7170 static inline bool lock_defer_pending(struct file_lock *fl)
7171 {
7172 	/* check pending lock waiters */
7173 	return waitqueue_active(&fl->fl_wait);
7174 }
7175 
7176 /**
7177  * smb2_lock() - handler for smb2 file lock command
7178  * @work:	smb work containing lock command buffer
7179  *
7180  * Return:	0 on success, otherwise error
7181  */
7182 int smb2_lock(struct ksmbd_work *work)
7183 {
7184 	struct smb2_lock_req *req;
7185 	struct smb2_lock_rsp *rsp;
7186 	struct smb2_lock_element *lock_ele;
7187 	struct ksmbd_file *fp = NULL;
7188 	struct file_lock *flock = NULL;
7189 	struct file *filp = NULL;
7190 	int lock_count;
7191 	int flags = 0;
7192 	int cmd = 0;
7193 	int err = -EIO, i, rc = 0;
7194 	u64 lock_start, lock_length;
7195 	struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
7196 	struct ksmbd_conn *conn;
7197 	int nolock = 0;
7198 	LIST_HEAD(lock_list);
7199 	LIST_HEAD(rollback_list);
7200 	int prior_lock = 0;
7201 
7202 	WORK_BUFFERS(work, req, rsp);
7203 
7204 	ksmbd_debug(SMB, "Received lock request\n");
7205 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7206 	if (!fp) {
7207 		ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
7208 		err = -ENOENT;
7209 		goto out2;
7210 	}
7211 
7212 	filp = fp->filp;
7213 	lock_count = le16_to_cpu(req->LockCount);
7214 	lock_ele = req->locks;
7215 
7216 	ksmbd_debug(SMB, "lock count is %d\n", lock_count);
7217 	if (!lock_count) {
7218 		err = -EINVAL;
7219 		goto out2;
7220 	}
7221 
7222 	for (i = 0; i < lock_count; i++) {
7223 		flags = le32_to_cpu(lock_ele[i].Flags);
7224 
7225 		flock = smb_flock_init(filp);
7226 		if (!flock)
7227 			goto out;
7228 
7229 		cmd = smb2_set_flock_flags(flock, flags);
7230 
7231 		lock_start = le64_to_cpu(lock_ele[i].Offset);
7232 		lock_length = le64_to_cpu(lock_ele[i].Length);
7233 		if (lock_start > U64_MAX - lock_length) {
7234 			pr_err("Invalid lock range requested\n");
7235 			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7236 			locks_free_lock(flock);
7237 			goto out;
7238 		}
7239 
7240 		if (lock_start > OFFSET_MAX)
7241 			flock->fl_start = OFFSET_MAX;
7242 		else
7243 			flock->fl_start = lock_start;
7244 
7245 		lock_length = le64_to_cpu(lock_ele[i].Length);
7246 		if (lock_length > OFFSET_MAX - flock->fl_start)
7247 			lock_length = OFFSET_MAX - flock->fl_start;
7248 
7249 		flock->fl_end = flock->fl_start + lock_length;
7250 
7251 		if (flock->fl_end < flock->fl_start) {
7252 			ksmbd_debug(SMB,
7253 				    "the end offset(%llx) is smaller than the start offset(%llx)\n",
7254 				    flock->fl_end, flock->fl_start);
7255 			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7256 			locks_free_lock(flock);
7257 			goto out;
7258 		}
7259 
7260 		/* Check conflict locks in one request */
7261 		list_for_each_entry(cmp_lock, &lock_list, llist) {
7262 			if (cmp_lock->fl->fl_start <= flock->fl_start &&
7263 			    cmp_lock->fl->fl_end >= flock->fl_end) {
7264 				if (cmp_lock->fl->fl_type != F_UNLCK &&
7265 				    flock->fl_type != F_UNLCK) {
7266 					pr_err("conflict two locks in one request\n");
7267 					err = -EINVAL;
7268 					locks_free_lock(flock);
7269 					goto out;
7270 				}
7271 			}
7272 		}
7273 
7274 		smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
7275 		if (!smb_lock) {
7276 			err = -EINVAL;
7277 			locks_free_lock(flock);
7278 			goto out;
7279 		}
7280 	}
7281 
7282 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7283 		if (smb_lock->cmd < 0) {
7284 			err = -EINVAL;
7285 			goto out;
7286 		}
7287 
7288 		if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
7289 			err = -EINVAL;
7290 			goto out;
7291 		}
7292 
7293 		if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
7294 		     smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
7295 		    (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
7296 		     !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
7297 			err = -EINVAL;
7298 			goto out;
7299 		}
7300 
7301 		prior_lock = smb_lock->flags;
7302 
7303 		if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
7304 		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
7305 			goto no_check_cl;
7306 
7307 		nolock = 1;
7308 		/* check locks in connection list */
7309 		down_read(&conn_list_lock);
7310 		list_for_each_entry(conn, &conn_list, conns_list) {
7311 			spin_lock(&conn->llist_lock);
7312 			list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
7313 				if (file_inode(cmp_lock->fl->fl_file) !=
7314 				    file_inode(smb_lock->fl->fl_file))
7315 					continue;
7316 
7317 				if (smb_lock->fl->fl_type == F_UNLCK) {
7318 					if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
7319 					    cmp_lock->start == smb_lock->start &&
7320 					    cmp_lock->end == smb_lock->end &&
7321 					    !lock_defer_pending(cmp_lock->fl)) {
7322 						nolock = 0;
7323 						list_del(&cmp_lock->flist);
7324 						list_del(&cmp_lock->clist);
7325 						spin_unlock(&conn->llist_lock);
7326 						up_read(&conn_list_lock);
7327 
7328 						locks_free_lock(cmp_lock->fl);
7329 						kfree(cmp_lock);
7330 						goto out_check_cl;
7331 					}
7332 					continue;
7333 				}
7334 
7335 				if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
7336 					if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
7337 						continue;
7338 				} else {
7339 					if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7340 						continue;
7341 				}
7342 
7343 				/* check zero byte lock range */
7344 				if (cmp_lock->zero_len && !smb_lock->zero_len &&
7345 				    cmp_lock->start > smb_lock->start &&
7346 				    cmp_lock->start < smb_lock->end) {
7347 					spin_unlock(&conn->llist_lock);
7348 					up_read(&conn_list_lock);
7349 					pr_err("previous lock conflict with zero byte lock range\n");
7350 					goto out;
7351 				}
7352 
7353 				if (smb_lock->zero_len && !cmp_lock->zero_len &&
7354 				    smb_lock->start > cmp_lock->start &&
7355 				    smb_lock->start < cmp_lock->end) {
7356 					spin_unlock(&conn->llist_lock);
7357 					up_read(&conn_list_lock);
7358 					pr_err("current lock conflict with zero byte lock range\n");
7359 					goto out;
7360 				}
7361 
7362 				if (((cmp_lock->start <= smb_lock->start &&
7363 				      cmp_lock->end > smb_lock->start) ||
7364 				     (cmp_lock->start < smb_lock->end &&
7365 				      cmp_lock->end >= smb_lock->end)) &&
7366 				    !cmp_lock->zero_len && !smb_lock->zero_len) {
7367 					spin_unlock(&conn->llist_lock);
7368 					up_read(&conn_list_lock);
7369 					pr_err("Not allow lock operation on exclusive lock range\n");
7370 					goto out;
7371 				}
7372 			}
7373 			spin_unlock(&conn->llist_lock);
7374 		}
7375 		up_read(&conn_list_lock);
7376 out_check_cl:
7377 		if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
7378 			pr_err("Try to unlock nolocked range\n");
7379 			rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7380 			goto out;
7381 		}
7382 
7383 no_check_cl:
7384 		if (smb_lock->zero_len) {
7385 			err = 0;
7386 			goto skip;
7387 		}
7388 
7389 		flock = smb_lock->fl;
7390 		list_del(&smb_lock->llist);
7391 retry:
7392 		rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7393 skip:
7394 		if (flags & SMB2_LOCKFLAG_UNLOCK) {
7395 			if (!rc) {
7396 				ksmbd_debug(SMB, "File unlocked\n");
7397 			} else if (rc == -ENOENT) {
7398 				rsp->hdr.Status = STATUS_NOT_LOCKED;
7399 				goto out;
7400 			}
7401 			locks_free_lock(flock);
7402 			kfree(smb_lock);
7403 		} else {
7404 			if (rc == FILE_LOCK_DEFERRED) {
7405 				void **argv;
7406 
7407 				ksmbd_debug(SMB,
7408 					    "would have to wait for getting lock\n");
7409 				list_add(&smb_lock->llist, &rollback_list);
7410 
7411 				argv = kmalloc(sizeof(void *), GFP_KERNEL);
7412 				if (!argv) {
7413 					err = -ENOMEM;
7414 					goto out;
7415 				}
7416 				argv[0] = flock;
7417 
7418 				rc = setup_async_work(work,
7419 						      smb2_remove_blocked_lock,
7420 						      argv);
7421 				if (rc) {
7422 					kfree(argv);
7423 					err = -ENOMEM;
7424 					goto out;
7425 				}
7426 				spin_lock(&fp->f_lock);
7427 				list_add(&work->fp_entry, &fp->blocked_works);
7428 				spin_unlock(&fp->f_lock);
7429 
7430 				smb2_send_interim_resp(work, STATUS_PENDING);
7431 
7432 				ksmbd_vfs_posix_lock_wait(flock);
7433 
7434 				spin_lock(&fp->f_lock);
7435 				list_del(&work->fp_entry);
7436 				spin_unlock(&fp->f_lock);
7437 
7438 				if (work->state != KSMBD_WORK_ACTIVE) {
7439 					list_del(&smb_lock->llist);
7440 					locks_free_lock(flock);
7441 
7442 					if (work->state == KSMBD_WORK_CANCELLED) {
7443 						rsp->hdr.Status =
7444 							STATUS_CANCELLED;
7445 						kfree(smb_lock);
7446 						smb2_send_interim_resp(work,
7447 								       STATUS_CANCELLED);
7448 						work->send_no_response = 1;
7449 						goto out;
7450 					}
7451 
7452 					rsp->hdr.Status =
7453 						STATUS_RANGE_NOT_LOCKED;
7454 					kfree(smb_lock);
7455 					goto out2;
7456 				}
7457 
7458 				list_del(&smb_lock->llist);
7459 				release_async_work(work);
7460 				goto retry;
7461 			} else if (!rc) {
7462 				list_add(&smb_lock->llist, &rollback_list);
7463 				spin_lock(&work->conn->llist_lock);
7464 				list_add_tail(&smb_lock->clist,
7465 					      &work->conn->lock_list);
7466 				list_add_tail(&smb_lock->flist,
7467 					      &fp->lock_list);
7468 				spin_unlock(&work->conn->llist_lock);
7469 				ksmbd_debug(SMB, "successful in taking lock\n");
7470 			} else {
7471 				goto out;
7472 			}
7473 		}
7474 	}
7475 
7476 	if (atomic_read(&fp->f_ci->op_count) > 1)
7477 		smb_break_all_oplock(work, fp);
7478 
7479 	rsp->StructureSize = cpu_to_le16(4);
7480 	ksmbd_debug(SMB, "successful in taking lock\n");
7481 	rsp->hdr.Status = STATUS_SUCCESS;
7482 	rsp->Reserved = 0;
7483 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7484 	if (err)
7485 		goto out;
7486 
7487 	ksmbd_fd_put(work, fp);
7488 	return 0;
7489 
7490 out:
7491 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7492 		locks_free_lock(smb_lock->fl);
7493 		list_del(&smb_lock->llist);
7494 		kfree(smb_lock);
7495 	}
7496 
7497 	list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7498 		struct file_lock *rlock = NULL;
7499 
7500 		rlock = smb_flock_init(filp);
7501 		rlock->fl_type = F_UNLCK;
7502 		rlock->fl_start = smb_lock->start;
7503 		rlock->fl_end = smb_lock->end;
7504 
7505 		rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7506 		if (rc)
7507 			pr_err("rollback unlock fail : %d\n", rc);
7508 
7509 		list_del(&smb_lock->llist);
7510 		spin_lock(&work->conn->llist_lock);
7511 		if (!list_empty(&smb_lock->flist))
7512 			list_del(&smb_lock->flist);
7513 		list_del(&smb_lock->clist);
7514 		spin_unlock(&work->conn->llist_lock);
7515 
7516 		locks_free_lock(smb_lock->fl);
7517 		locks_free_lock(rlock);
7518 		kfree(smb_lock);
7519 	}
7520 out2:
7521 	ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7522 
7523 	if (!rsp->hdr.Status) {
7524 		if (err == -EINVAL)
7525 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7526 		else if (err == -ENOMEM)
7527 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7528 		else if (err == -ENOENT)
7529 			rsp->hdr.Status = STATUS_FILE_CLOSED;
7530 		else
7531 			rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7532 	}
7533 
7534 	smb2_set_err_rsp(work);
7535 	ksmbd_fd_put(work, fp);
7536 	return err;
7537 }
7538 
7539 static int fsctl_copychunk(struct ksmbd_work *work,
7540 			   struct copychunk_ioctl_req *ci_req,
7541 			   unsigned int cnt_code,
7542 			   unsigned int input_count,
7543 			   unsigned long long volatile_id,
7544 			   unsigned long long persistent_id,
7545 			   struct smb2_ioctl_rsp *rsp)
7546 {
7547 	struct copychunk_ioctl_rsp *ci_rsp;
7548 	struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7549 	struct srv_copychunk *chunks;
7550 	unsigned int i, chunk_count, chunk_count_written = 0;
7551 	unsigned int chunk_size_written = 0;
7552 	loff_t total_size_written = 0;
7553 	int ret = 0;
7554 
7555 	ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7556 
7557 	rsp->VolatileFileId = volatile_id;
7558 	rsp->PersistentFileId = persistent_id;
7559 	ci_rsp->ChunksWritten =
7560 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7561 	ci_rsp->ChunkBytesWritten =
7562 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7563 	ci_rsp->TotalBytesWritten =
7564 		cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7565 
7566 	chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7567 	chunk_count = le32_to_cpu(ci_req->ChunkCount);
7568 	if (chunk_count == 0)
7569 		goto out;
7570 	total_size_written = 0;
7571 
7572 	/* verify the SRV_COPYCHUNK_COPY packet */
7573 	if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7574 	    input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7575 	     chunk_count * sizeof(struct srv_copychunk)) {
7576 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7577 		return -EINVAL;
7578 	}
7579 
7580 	for (i = 0; i < chunk_count; i++) {
7581 		if (le32_to_cpu(chunks[i].Length) == 0 ||
7582 		    le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7583 			break;
7584 		total_size_written += le32_to_cpu(chunks[i].Length);
7585 	}
7586 
7587 	if (i < chunk_count ||
7588 	    total_size_written > ksmbd_server_side_copy_max_total_size()) {
7589 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7590 		return -EINVAL;
7591 	}
7592 
7593 	src_fp = ksmbd_lookup_foreign_fd(work,
7594 					 le64_to_cpu(ci_req->ResumeKey[0]));
7595 	dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7596 	ret = -EINVAL;
7597 	if (!src_fp ||
7598 	    src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7599 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7600 		goto out;
7601 	}
7602 
7603 	if (!dst_fp) {
7604 		rsp->hdr.Status = STATUS_FILE_CLOSED;
7605 		goto out;
7606 	}
7607 
7608 	/*
7609 	 * FILE_READ_DATA should only be included in
7610 	 * the FSCTL_COPYCHUNK case
7611 	 */
7612 	if (cnt_code == FSCTL_COPYCHUNK &&
7613 	    !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7614 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
7615 		goto out;
7616 	}
7617 
7618 	ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7619 					 chunks, chunk_count,
7620 					 &chunk_count_written,
7621 					 &chunk_size_written,
7622 					 &total_size_written);
7623 	if (ret < 0) {
7624 		if (ret == -EACCES)
7625 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
7626 		if (ret == -EAGAIN)
7627 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7628 		else if (ret == -EBADF)
7629 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
7630 		else if (ret == -EFBIG || ret == -ENOSPC)
7631 			rsp->hdr.Status = STATUS_DISK_FULL;
7632 		else if (ret == -EINVAL)
7633 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7634 		else if (ret == -EISDIR)
7635 			rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7636 		else if (ret == -E2BIG)
7637 			rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7638 		else
7639 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7640 	}
7641 
7642 	ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7643 	ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7644 	ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7645 out:
7646 	ksmbd_fd_put(work, src_fp);
7647 	ksmbd_fd_put(work, dst_fp);
7648 	return ret;
7649 }
7650 
7651 static __be32 idev_ipv4_address(struct in_device *idev)
7652 {
7653 	__be32 addr = 0;
7654 
7655 	struct in_ifaddr *ifa;
7656 
7657 	rcu_read_lock();
7658 	in_dev_for_each_ifa_rcu(ifa, idev) {
7659 		if (ifa->ifa_flags & IFA_F_SECONDARY)
7660 			continue;
7661 
7662 		addr = ifa->ifa_address;
7663 		break;
7664 	}
7665 	rcu_read_unlock();
7666 	return addr;
7667 }
7668 
7669 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7670 					struct smb2_ioctl_rsp *rsp,
7671 					unsigned int out_buf_len)
7672 {
7673 	struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7674 	int nbytes = 0;
7675 	struct net_device *netdev;
7676 	struct sockaddr_storage_rsp *sockaddr_storage;
7677 	unsigned int flags;
7678 	unsigned long long speed;
7679 
7680 	rtnl_lock();
7681 	for_each_netdev(&init_net, netdev) {
7682 		bool ipv4_set = false;
7683 
7684 		if (netdev->type == ARPHRD_LOOPBACK)
7685 			continue;
7686 
7687 		flags = dev_get_flags(netdev);
7688 		if (!(flags & IFF_RUNNING))
7689 			continue;
7690 ipv6_retry:
7691 		if (out_buf_len <
7692 		    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7693 			rtnl_unlock();
7694 			return -ENOSPC;
7695 		}
7696 
7697 		nii_rsp = (struct network_interface_info_ioctl_rsp *)
7698 				&rsp->Buffer[nbytes];
7699 		nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7700 
7701 		nii_rsp->Capability = 0;
7702 		if (netdev->real_num_tx_queues > 1)
7703 			nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7704 		if (ksmbd_rdma_capable_netdev(netdev))
7705 			nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7706 
7707 		nii_rsp->Next = cpu_to_le32(152);
7708 		nii_rsp->Reserved = 0;
7709 
7710 		if (netdev->ethtool_ops->get_link_ksettings) {
7711 			struct ethtool_link_ksettings cmd;
7712 
7713 			netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7714 			speed = cmd.base.speed;
7715 		} else {
7716 			ksmbd_debug(SMB, "%s %s\n", netdev->name,
7717 				    "speed is unknown, defaulting to 1Gb/sec");
7718 			speed = SPEED_1000;
7719 		}
7720 
7721 		speed *= 1000000;
7722 		nii_rsp->LinkSpeed = cpu_to_le64(speed);
7723 
7724 		sockaddr_storage = (struct sockaddr_storage_rsp *)
7725 					nii_rsp->SockAddr_Storage;
7726 		memset(sockaddr_storage, 0, 128);
7727 
7728 		if (!ipv4_set) {
7729 			struct in_device *idev;
7730 
7731 			sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7732 			sockaddr_storage->addr4.Port = 0;
7733 
7734 			idev = __in_dev_get_rtnl(netdev);
7735 			if (!idev)
7736 				continue;
7737 			sockaddr_storage->addr4.IPv4address =
7738 						idev_ipv4_address(idev);
7739 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7740 			ipv4_set = true;
7741 			goto ipv6_retry;
7742 		} else {
7743 			struct inet6_dev *idev6;
7744 			struct inet6_ifaddr *ifa;
7745 			__u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7746 
7747 			sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7748 			sockaddr_storage->addr6.Port = 0;
7749 			sockaddr_storage->addr6.FlowInfo = 0;
7750 
7751 			idev6 = __in6_dev_get(netdev);
7752 			if (!idev6)
7753 				continue;
7754 
7755 			list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7756 				if (ifa->flags & (IFA_F_TENTATIVE |
7757 							IFA_F_DEPRECATED))
7758 					continue;
7759 				memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7760 				break;
7761 			}
7762 			sockaddr_storage->addr6.ScopeId = 0;
7763 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7764 		}
7765 	}
7766 	rtnl_unlock();
7767 
7768 	/* zero if this is last one */
7769 	if (nii_rsp)
7770 		nii_rsp->Next = 0;
7771 
7772 	rsp->PersistentFileId = SMB2_NO_FID;
7773 	rsp->VolatileFileId = SMB2_NO_FID;
7774 	return nbytes;
7775 }
7776 
7777 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7778 					 struct validate_negotiate_info_req *neg_req,
7779 					 struct validate_negotiate_info_rsp *neg_rsp,
7780 					 unsigned int in_buf_len)
7781 {
7782 	int ret = 0;
7783 	int dialect;
7784 
7785 	if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7786 			le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7787 		return -EINVAL;
7788 
7789 	dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7790 					     neg_req->DialectCount);
7791 	if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7792 		ret = -EINVAL;
7793 		goto err_out;
7794 	}
7795 
7796 	if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7797 		ret = -EINVAL;
7798 		goto err_out;
7799 	}
7800 
7801 	if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7802 		ret = -EINVAL;
7803 		goto err_out;
7804 	}
7805 
7806 	if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7807 		ret = -EINVAL;
7808 		goto err_out;
7809 	}
7810 
7811 	neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7812 	memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7813 	neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7814 	neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7815 err_out:
7816 	return ret;
7817 }
7818 
7819 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7820 					struct file_allocated_range_buffer *qar_req,
7821 					struct file_allocated_range_buffer *qar_rsp,
7822 					unsigned int in_count, unsigned int *out_count)
7823 {
7824 	struct ksmbd_file *fp;
7825 	loff_t start, length;
7826 	int ret = 0;
7827 
7828 	*out_count = 0;
7829 	if (in_count == 0)
7830 		return -EINVAL;
7831 
7832 	start = le64_to_cpu(qar_req->file_offset);
7833 	length = le64_to_cpu(qar_req->length);
7834 
7835 	if (start < 0 || length < 0)
7836 		return -EINVAL;
7837 
7838 	fp = ksmbd_lookup_fd_fast(work, id);
7839 	if (!fp)
7840 		return -ENOENT;
7841 
7842 	ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7843 				   qar_rsp, in_count, out_count);
7844 	if (ret && ret != -E2BIG)
7845 		*out_count = 0;
7846 
7847 	ksmbd_fd_put(work, fp);
7848 	return ret;
7849 }
7850 
7851 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7852 				 unsigned int out_buf_len,
7853 				 struct smb2_ioctl_req *req,
7854 				 struct smb2_ioctl_rsp *rsp)
7855 {
7856 	struct ksmbd_rpc_command *rpc_resp;
7857 	char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
7858 	int nbytes = 0;
7859 
7860 	rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7861 				   le32_to_cpu(req->InputCount));
7862 	if (rpc_resp) {
7863 		if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7864 			/*
7865 			 * set STATUS_SOME_NOT_MAPPED response
7866 			 * for unknown domain sid.
7867 			 */
7868 			rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7869 		} else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7870 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7871 			goto out;
7872 		} else if (rpc_resp->flags != KSMBD_RPC_OK) {
7873 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7874 			goto out;
7875 		}
7876 
7877 		nbytes = rpc_resp->payload_sz;
7878 		if (rpc_resp->payload_sz > out_buf_len) {
7879 			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7880 			nbytes = out_buf_len;
7881 		}
7882 
7883 		if (!rpc_resp->payload_sz) {
7884 			rsp->hdr.Status =
7885 				STATUS_UNEXPECTED_IO_ERROR;
7886 			goto out;
7887 		}
7888 
7889 		memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7890 	}
7891 out:
7892 	kvfree(rpc_resp);
7893 	return nbytes;
7894 }
7895 
7896 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7897 				   struct file_sparse *sparse)
7898 {
7899 	struct ksmbd_file *fp;
7900 	struct mnt_idmap *idmap;
7901 	int ret = 0;
7902 	__le32 old_fattr;
7903 
7904 	fp = ksmbd_lookup_fd_fast(work, id);
7905 	if (!fp)
7906 		return -ENOENT;
7907 	idmap = file_mnt_idmap(fp->filp);
7908 
7909 	old_fattr = fp->f_ci->m_fattr;
7910 	if (sparse->SetSparse)
7911 		fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7912 	else
7913 		fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7914 
7915 	if (fp->f_ci->m_fattr != old_fattr &&
7916 	    test_share_config_flag(work->tcon->share_conf,
7917 				   KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7918 		struct xattr_dos_attrib da;
7919 
7920 		ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
7921 						     fp->filp->f_path.dentry, &da);
7922 		if (ret <= 0)
7923 			goto out;
7924 
7925 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7926 		ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
7927 						     &fp->filp->f_path,
7928 						     &da, true);
7929 		if (ret)
7930 			fp->f_ci->m_fattr = old_fattr;
7931 	}
7932 
7933 out:
7934 	ksmbd_fd_put(work, fp);
7935 	return ret;
7936 }
7937 
7938 static int fsctl_request_resume_key(struct ksmbd_work *work,
7939 				    struct smb2_ioctl_req *req,
7940 				    struct resume_key_ioctl_rsp *key_rsp)
7941 {
7942 	struct ksmbd_file *fp;
7943 
7944 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7945 	if (!fp)
7946 		return -ENOENT;
7947 
7948 	memset(key_rsp, 0, sizeof(*key_rsp));
7949 	key_rsp->ResumeKey[0] = req->VolatileFileId;
7950 	key_rsp->ResumeKey[1] = req->PersistentFileId;
7951 	ksmbd_fd_put(work, fp);
7952 
7953 	return 0;
7954 }
7955 
7956 /**
7957  * smb2_ioctl() - handler for smb2 ioctl command
7958  * @work:	smb work containing ioctl command buffer
7959  *
7960  * Return:	0 on success, otherwise error
7961  */
7962 int smb2_ioctl(struct ksmbd_work *work)
7963 {
7964 	struct smb2_ioctl_req *req;
7965 	struct smb2_ioctl_rsp *rsp;
7966 	unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7967 	u64 id = KSMBD_NO_FID;
7968 	struct ksmbd_conn *conn = work->conn;
7969 	int ret = 0;
7970 	char *buffer;
7971 
7972 	if (work->next_smb2_rcv_hdr_off) {
7973 		req = ksmbd_req_buf_next(work);
7974 		rsp = ksmbd_resp_buf_next(work);
7975 		if (!has_file_id(req->VolatileFileId)) {
7976 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7977 				    work->compound_fid);
7978 			id = work->compound_fid;
7979 		}
7980 	} else {
7981 		req = smb2_get_msg(work->request_buf);
7982 		rsp = smb2_get_msg(work->response_buf);
7983 	}
7984 
7985 	if (!has_file_id(id))
7986 		id = req->VolatileFileId;
7987 
7988 	if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7989 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7990 		goto out;
7991 	}
7992 
7993 	buffer = (char *)req + le32_to_cpu(req->InputOffset);
7994 
7995 	cnt_code = le32_to_cpu(req->CtlCode);
7996 	ret = smb2_calc_max_out_buf_len(work, 48,
7997 					le32_to_cpu(req->MaxOutputResponse));
7998 	if (ret < 0) {
7999 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8000 		goto out;
8001 	}
8002 	out_buf_len = (unsigned int)ret;
8003 	in_buf_len = le32_to_cpu(req->InputCount);
8004 
8005 	switch (cnt_code) {
8006 	case FSCTL_DFS_GET_REFERRALS:
8007 	case FSCTL_DFS_GET_REFERRALS_EX:
8008 		/* Not support DFS yet */
8009 		rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
8010 		goto out;
8011 	case FSCTL_CREATE_OR_GET_OBJECT_ID:
8012 	{
8013 		struct file_object_buf_type1_ioctl_rsp *obj_buf;
8014 
8015 		nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
8016 		obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
8017 			&rsp->Buffer[0];
8018 
8019 		/*
8020 		 * TODO: This is dummy implementation to pass smbtorture
8021 		 * Need to check correct response later
8022 		 */
8023 		memset(obj_buf->ObjectId, 0x0, 16);
8024 		memset(obj_buf->BirthVolumeId, 0x0, 16);
8025 		memset(obj_buf->BirthObjectId, 0x0, 16);
8026 		memset(obj_buf->DomainId, 0x0, 16);
8027 
8028 		break;
8029 	}
8030 	case FSCTL_PIPE_TRANSCEIVE:
8031 		out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
8032 		nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
8033 		break;
8034 	case FSCTL_VALIDATE_NEGOTIATE_INFO:
8035 		if (conn->dialect < SMB30_PROT_ID) {
8036 			ret = -EOPNOTSUPP;
8037 			goto out;
8038 		}
8039 
8040 		if (in_buf_len < offsetof(struct validate_negotiate_info_req,
8041 					  Dialects)) {
8042 			ret = -EINVAL;
8043 			goto out;
8044 		}
8045 
8046 		if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
8047 			ret = -EINVAL;
8048 			goto out;
8049 		}
8050 
8051 		ret = fsctl_validate_negotiate_info(conn,
8052 			(struct validate_negotiate_info_req *)buffer,
8053 			(struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
8054 			in_buf_len);
8055 		if (ret < 0)
8056 			goto out;
8057 
8058 		nbytes = sizeof(struct validate_negotiate_info_rsp);
8059 		rsp->PersistentFileId = SMB2_NO_FID;
8060 		rsp->VolatileFileId = SMB2_NO_FID;
8061 		break;
8062 	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
8063 		ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
8064 		if (ret < 0)
8065 			goto out;
8066 		nbytes = ret;
8067 		break;
8068 	case FSCTL_REQUEST_RESUME_KEY:
8069 		if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
8070 			ret = -EINVAL;
8071 			goto out;
8072 		}
8073 
8074 		ret = fsctl_request_resume_key(work, req,
8075 					       (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
8076 		if (ret < 0)
8077 			goto out;
8078 		rsp->PersistentFileId = req->PersistentFileId;
8079 		rsp->VolatileFileId = req->VolatileFileId;
8080 		nbytes = sizeof(struct resume_key_ioctl_rsp);
8081 		break;
8082 	case FSCTL_COPYCHUNK:
8083 	case FSCTL_COPYCHUNK_WRITE:
8084 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8085 			ksmbd_debug(SMB,
8086 				    "User does not have write permission\n");
8087 			ret = -EACCES;
8088 			goto out;
8089 		}
8090 
8091 		if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
8092 			ret = -EINVAL;
8093 			goto out;
8094 		}
8095 
8096 		if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
8097 			ret = -EINVAL;
8098 			goto out;
8099 		}
8100 
8101 		nbytes = sizeof(struct copychunk_ioctl_rsp);
8102 		rsp->VolatileFileId = req->VolatileFileId;
8103 		rsp->PersistentFileId = req->PersistentFileId;
8104 		fsctl_copychunk(work,
8105 				(struct copychunk_ioctl_req *)buffer,
8106 				le32_to_cpu(req->CtlCode),
8107 				le32_to_cpu(req->InputCount),
8108 				req->VolatileFileId,
8109 				req->PersistentFileId,
8110 				rsp);
8111 		break;
8112 	case FSCTL_SET_SPARSE:
8113 		if (in_buf_len < sizeof(struct file_sparse)) {
8114 			ret = -EINVAL;
8115 			goto out;
8116 		}
8117 
8118 		ret = fsctl_set_sparse(work, id, (struct file_sparse *)buffer);
8119 		if (ret < 0)
8120 			goto out;
8121 		break;
8122 	case FSCTL_SET_ZERO_DATA:
8123 	{
8124 		struct file_zero_data_information *zero_data;
8125 		struct ksmbd_file *fp;
8126 		loff_t off, len, bfz;
8127 
8128 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8129 			ksmbd_debug(SMB,
8130 				    "User does not have write permission\n");
8131 			ret = -EACCES;
8132 			goto out;
8133 		}
8134 
8135 		if (in_buf_len < sizeof(struct file_zero_data_information)) {
8136 			ret = -EINVAL;
8137 			goto out;
8138 		}
8139 
8140 		zero_data =
8141 			(struct file_zero_data_information *)buffer;
8142 
8143 		off = le64_to_cpu(zero_data->FileOffset);
8144 		bfz = le64_to_cpu(zero_data->BeyondFinalZero);
8145 		if (off < 0 || bfz < 0 || off > bfz) {
8146 			ret = -EINVAL;
8147 			goto out;
8148 		}
8149 
8150 		len = bfz - off;
8151 		if (len) {
8152 			fp = ksmbd_lookup_fd_fast(work, id);
8153 			if (!fp) {
8154 				ret = -ENOENT;
8155 				goto out;
8156 			}
8157 
8158 			ret = ksmbd_vfs_zero_data(work, fp, off, len);
8159 			ksmbd_fd_put(work, fp);
8160 			if (ret < 0)
8161 				goto out;
8162 		}
8163 		break;
8164 	}
8165 	case FSCTL_QUERY_ALLOCATED_RANGES:
8166 		if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
8167 			ret = -EINVAL;
8168 			goto out;
8169 		}
8170 
8171 		ret = fsctl_query_allocated_ranges(work, id,
8172 			(struct file_allocated_range_buffer *)buffer,
8173 			(struct file_allocated_range_buffer *)&rsp->Buffer[0],
8174 			out_buf_len /
8175 			sizeof(struct file_allocated_range_buffer), &nbytes);
8176 		if (ret == -E2BIG) {
8177 			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8178 		} else if (ret < 0) {
8179 			nbytes = 0;
8180 			goto out;
8181 		}
8182 
8183 		nbytes *= sizeof(struct file_allocated_range_buffer);
8184 		break;
8185 	case FSCTL_GET_REPARSE_POINT:
8186 	{
8187 		struct reparse_data_buffer *reparse_ptr;
8188 		struct ksmbd_file *fp;
8189 
8190 		reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
8191 		fp = ksmbd_lookup_fd_fast(work, id);
8192 		if (!fp) {
8193 			pr_err("not found fp!!\n");
8194 			ret = -ENOENT;
8195 			goto out;
8196 		}
8197 
8198 		reparse_ptr->ReparseTag =
8199 			smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
8200 		reparse_ptr->ReparseDataLength = 0;
8201 		ksmbd_fd_put(work, fp);
8202 		nbytes = sizeof(struct reparse_data_buffer);
8203 		break;
8204 	}
8205 	case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
8206 	{
8207 		struct ksmbd_file *fp_in, *fp_out = NULL;
8208 		struct duplicate_extents_to_file *dup_ext;
8209 		loff_t src_off, dst_off, length, cloned;
8210 
8211 		if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
8212 			ret = -EINVAL;
8213 			goto out;
8214 		}
8215 
8216 		dup_ext = (struct duplicate_extents_to_file *)buffer;
8217 
8218 		fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
8219 					     dup_ext->PersistentFileHandle);
8220 		if (!fp_in) {
8221 			pr_err("not found file handle in duplicate extent to file\n");
8222 			ret = -ENOENT;
8223 			goto out;
8224 		}
8225 
8226 		fp_out = ksmbd_lookup_fd_fast(work, id);
8227 		if (!fp_out) {
8228 			pr_err("not found fp\n");
8229 			ret = -ENOENT;
8230 			goto dup_ext_out;
8231 		}
8232 
8233 		src_off = le64_to_cpu(dup_ext->SourceFileOffset);
8234 		dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
8235 		length = le64_to_cpu(dup_ext->ByteCount);
8236 		/*
8237 		 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
8238 		 * should fall back to vfs_copy_file_range().  This could be
8239 		 * beneficial when re-exporting nfs/smb mount, but note that
8240 		 * this can result in partial copy that returns an error status.
8241 		 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
8242 		 * fall back to vfs_copy_file_range(), should be avoided when
8243 		 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
8244 		 */
8245 		cloned = vfs_clone_file_range(fp_in->filp, src_off,
8246 					      fp_out->filp, dst_off, length, 0);
8247 		if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
8248 			ret = -EOPNOTSUPP;
8249 			goto dup_ext_out;
8250 		} else if (cloned != length) {
8251 			cloned = vfs_copy_file_range(fp_in->filp, src_off,
8252 						     fp_out->filp, dst_off,
8253 						     length, 0);
8254 			if (cloned != length) {
8255 				if (cloned < 0)
8256 					ret = cloned;
8257 				else
8258 					ret = -EINVAL;
8259 			}
8260 		}
8261 
8262 dup_ext_out:
8263 		ksmbd_fd_put(work, fp_in);
8264 		ksmbd_fd_put(work, fp_out);
8265 		if (ret < 0)
8266 			goto out;
8267 		break;
8268 	}
8269 	default:
8270 		ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
8271 			    cnt_code);
8272 		ret = -EOPNOTSUPP;
8273 		goto out;
8274 	}
8275 
8276 	rsp->CtlCode = cpu_to_le32(cnt_code);
8277 	rsp->InputCount = cpu_to_le32(0);
8278 	rsp->InputOffset = cpu_to_le32(112);
8279 	rsp->OutputOffset = cpu_to_le32(112);
8280 	rsp->OutputCount = cpu_to_le32(nbytes);
8281 	rsp->StructureSize = cpu_to_le16(49);
8282 	rsp->Reserved = cpu_to_le16(0);
8283 	rsp->Flags = cpu_to_le32(0);
8284 	rsp->Reserved2 = cpu_to_le32(0);
8285 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
8286 	if (!ret)
8287 		return ret;
8288 
8289 out:
8290 	if (ret == -EACCES)
8291 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
8292 	else if (ret == -ENOENT)
8293 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
8294 	else if (ret == -EOPNOTSUPP)
8295 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8296 	else if (ret == -ENOSPC)
8297 		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
8298 	else if (ret < 0 || rsp->hdr.Status == 0)
8299 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8300 	smb2_set_err_rsp(work);
8301 	return 0;
8302 }
8303 
8304 /**
8305  * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
8306  * @work:	smb work containing oplock break command buffer
8307  *
8308  * Return:	0
8309  */
8310 static void smb20_oplock_break_ack(struct ksmbd_work *work)
8311 {
8312 	struct smb2_oplock_break *req;
8313 	struct smb2_oplock_break *rsp;
8314 	struct ksmbd_file *fp;
8315 	struct oplock_info *opinfo = NULL;
8316 	__le32 err = 0;
8317 	int ret = 0;
8318 	u64 volatile_id, persistent_id;
8319 	char req_oplevel = 0, rsp_oplevel = 0;
8320 	unsigned int oplock_change_type;
8321 
8322 	WORK_BUFFERS(work, req, rsp);
8323 
8324 	volatile_id = req->VolatileFid;
8325 	persistent_id = req->PersistentFid;
8326 	req_oplevel = req->OplockLevel;
8327 	ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
8328 		    volatile_id, persistent_id, req_oplevel);
8329 
8330 	fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8331 	if (!fp) {
8332 		rsp->hdr.Status = STATUS_FILE_CLOSED;
8333 		smb2_set_err_rsp(work);
8334 		return;
8335 	}
8336 
8337 	opinfo = opinfo_get(fp);
8338 	if (!opinfo) {
8339 		pr_err("unexpected null oplock_info\n");
8340 		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8341 		smb2_set_err_rsp(work);
8342 		ksmbd_fd_put(work, fp);
8343 		return;
8344 	}
8345 
8346 	if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8347 		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8348 		goto err_out;
8349 	}
8350 
8351 	if (opinfo->op_state == OPLOCK_STATE_NONE) {
8352 		ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8353 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8354 		goto err_out;
8355 	}
8356 
8357 	if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8358 	     opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8359 	    (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8360 	     req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8361 		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8362 		oplock_change_type = OPLOCK_WRITE_TO_NONE;
8363 	} else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8364 		   req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8365 		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8366 		oplock_change_type = OPLOCK_READ_TO_NONE;
8367 	} else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8368 		   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8369 		err = STATUS_INVALID_DEVICE_STATE;
8370 		if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8371 		     opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8372 		    req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8373 			oplock_change_type = OPLOCK_WRITE_TO_READ;
8374 		} else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8375 			    opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8376 			   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8377 			oplock_change_type = OPLOCK_WRITE_TO_NONE;
8378 		} else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8379 			   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8380 			oplock_change_type = OPLOCK_READ_TO_NONE;
8381 		} else {
8382 			oplock_change_type = 0;
8383 		}
8384 	} else {
8385 		oplock_change_type = 0;
8386 	}
8387 
8388 	switch (oplock_change_type) {
8389 	case OPLOCK_WRITE_TO_READ:
8390 		ret = opinfo_write_to_read(opinfo);
8391 		rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8392 		break;
8393 	case OPLOCK_WRITE_TO_NONE:
8394 		ret = opinfo_write_to_none(opinfo);
8395 		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8396 		break;
8397 	case OPLOCK_READ_TO_NONE:
8398 		ret = opinfo_read_to_none(opinfo);
8399 		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8400 		break;
8401 	default:
8402 		pr_err("unknown oplock change 0x%x -> 0x%x\n",
8403 		       opinfo->level, rsp_oplevel);
8404 	}
8405 
8406 	if (ret < 0) {
8407 		rsp->hdr.Status = err;
8408 		goto err_out;
8409 	}
8410 
8411 	opinfo->op_state = OPLOCK_STATE_NONE;
8412 	wake_up_interruptible_all(&opinfo->oplock_q);
8413 	opinfo_put(opinfo);
8414 	ksmbd_fd_put(work, fp);
8415 
8416 	rsp->StructureSize = cpu_to_le16(24);
8417 	rsp->OplockLevel = rsp_oplevel;
8418 	rsp->Reserved = 0;
8419 	rsp->Reserved2 = 0;
8420 	rsp->VolatileFid = volatile_id;
8421 	rsp->PersistentFid = persistent_id;
8422 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8423 	if (!ret)
8424 		return;
8425 
8426 err_out:
8427 	opinfo->op_state = OPLOCK_STATE_NONE;
8428 	wake_up_interruptible_all(&opinfo->oplock_q);
8429 
8430 	opinfo_put(opinfo);
8431 	ksmbd_fd_put(work, fp);
8432 	smb2_set_err_rsp(work);
8433 }
8434 
8435 static int check_lease_state(struct lease *lease, __le32 req_state)
8436 {
8437 	if ((lease->new_state ==
8438 	     (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8439 	    !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8440 		lease->new_state = req_state;
8441 		return 0;
8442 	}
8443 
8444 	if (lease->new_state == req_state)
8445 		return 0;
8446 
8447 	return 1;
8448 }
8449 
8450 /**
8451  * smb21_lease_break_ack() - handler for smb2.1 lease break command
8452  * @work:	smb work containing lease break command buffer
8453  *
8454  * Return:	0
8455  */
8456 static void smb21_lease_break_ack(struct ksmbd_work *work)
8457 {
8458 	struct ksmbd_conn *conn = work->conn;
8459 	struct smb2_lease_ack *req;
8460 	struct smb2_lease_ack *rsp;
8461 	struct oplock_info *opinfo;
8462 	__le32 err = 0;
8463 	int ret = 0;
8464 	unsigned int lease_change_type;
8465 	__le32 lease_state;
8466 	struct lease *lease;
8467 
8468 	WORK_BUFFERS(work, req, rsp);
8469 
8470 	ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8471 		    le32_to_cpu(req->LeaseState));
8472 	opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8473 	if (!opinfo) {
8474 		ksmbd_debug(OPLOCK, "file not opened\n");
8475 		smb2_set_err_rsp(work);
8476 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8477 		return;
8478 	}
8479 	lease = opinfo->o_lease;
8480 
8481 	if (opinfo->op_state == OPLOCK_STATE_NONE) {
8482 		pr_err("unexpected lease break state 0x%x\n",
8483 		       opinfo->op_state);
8484 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8485 		goto err_out;
8486 	}
8487 
8488 	if (check_lease_state(lease, req->LeaseState)) {
8489 		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8490 		ksmbd_debug(OPLOCK,
8491 			    "req lease state: 0x%x, expected state: 0x%x\n",
8492 			    req->LeaseState, lease->new_state);
8493 		goto err_out;
8494 	}
8495 
8496 	if (!atomic_read(&opinfo->breaking_cnt)) {
8497 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8498 		goto err_out;
8499 	}
8500 
8501 	/* check for bad lease state */
8502 	if (req->LeaseState &
8503 	    (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8504 		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8505 		if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8506 			lease_change_type = OPLOCK_WRITE_TO_NONE;
8507 		else
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 if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8513 		   req->LeaseState != SMB2_LEASE_NONE_LE) {
8514 		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8515 		lease_change_type = OPLOCK_READ_TO_NONE;
8516 		ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8517 			    le32_to_cpu(lease->state),
8518 			    le32_to_cpu(req->LeaseState));
8519 	} else {
8520 		/* valid lease state changes */
8521 		err = STATUS_INVALID_DEVICE_STATE;
8522 		if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8523 			if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8524 				lease_change_type = OPLOCK_WRITE_TO_NONE;
8525 			else
8526 				lease_change_type = OPLOCK_READ_TO_NONE;
8527 		} else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8528 			if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8529 				lease_change_type = OPLOCK_WRITE_TO_READ;
8530 			else
8531 				lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8532 		} else {
8533 			lease_change_type = 0;
8534 		}
8535 	}
8536 
8537 	switch (lease_change_type) {
8538 	case OPLOCK_WRITE_TO_READ:
8539 		ret = opinfo_write_to_read(opinfo);
8540 		break;
8541 	case OPLOCK_READ_HANDLE_TO_READ:
8542 		ret = opinfo_read_handle_to_read(opinfo);
8543 		break;
8544 	case OPLOCK_WRITE_TO_NONE:
8545 		ret = opinfo_write_to_none(opinfo);
8546 		break;
8547 	case OPLOCK_READ_TO_NONE:
8548 		ret = opinfo_read_to_none(opinfo);
8549 		break;
8550 	default:
8551 		ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8552 			    le32_to_cpu(lease->state),
8553 			    le32_to_cpu(req->LeaseState));
8554 	}
8555 
8556 	if (ret < 0) {
8557 		rsp->hdr.Status = err;
8558 		goto err_out;
8559 	}
8560 
8561 	lease_state = lease->state;
8562 	opinfo->op_state = OPLOCK_STATE_NONE;
8563 	wake_up_interruptible_all(&opinfo->oplock_q);
8564 	atomic_dec(&opinfo->breaking_cnt);
8565 	wake_up_interruptible_all(&opinfo->oplock_brk);
8566 	opinfo_put(opinfo);
8567 
8568 	rsp->StructureSize = cpu_to_le16(36);
8569 	rsp->Reserved = 0;
8570 	rsp->Flags = 0;
8571 	memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8572 	rsp->LeaseState = lease_state;
8573 	rsp->LeaseDuration = 0;
8574 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8575 	if (!ret)
8576 		return;
8577 
8578 err_out:
8579 	wake_up_interruptible_all(&opinfo->oplock_q);
8580 	atomic_dec(&opinfo->breaking_cnt);
8581 	wake_up_interruptible_all(&opinfo->oplock_brk);
8582 
8583 	opinfo_put(opinfo);
8584 	smb2_set_err_rsp(work);
8585 }
8586 
8587 /**
8588  * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8589  * @work:	smb work containing oplock/lease break command buffer
8590  *
8591  * Return:	0
8592  */
8593 int smb2_oplock_break(struct ksmbd_work *work)
8594 {
8595 	struct smb2_oplock_break *req;
8596 	struct smb2_oplock_break *rsp;
8597 
8598 	WORK_BUFFERS(work, req, rsp);
8599 
8600 	switch (le16_to_cpu(req->StructureSize)) {
8601 	case OP_BREAK_STRUCT_SIZE_20:
8602 		smb20_oplock_break_ack(work);
8603 		break;
8604 	case OP_BREAK_STRUCT_SIZE_21:
8605 		smb21_lease_break_ack(work);
8606 		break;
8607 	default:
8608 		ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8609 			    le16_to_cpu(req->StructureSize));
8610 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8611 		smb2_set_err_rsp(work);
8612 	}
8613 
8614 	return 0;
8615 }
8616 
8617 /**
8618  * smb2_notify() - handler for smb2 notify request
8619  * @work:   smb work containing notify command buffer
8620  *
8621  * Return:      0
8622  */
8623 int smb2_notify(struct ksmbd_work *work)
8624 {
8625 	struct smb2_change_notify_req *req;
8626 	struct smb2_change_notify_rsp *rsp;
8627 
8628 	WORK_BUFFERS(work, req, rsp);
8629 
8630 	if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8631 		rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8632 		smb2_set_err_rsp(work);
8633 		return 0;
8634 	}
8635 
8636 	smb2_set_err_rsp(work);
8637 	rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8638 	return 0;
8639 }
8640 
8641 /**
8642  * smb2_is_sign_req() - handler for checking packet signing status
8643  * @work:	smb work containing notify command buffer
8644  * @command:	SMB2 command id
8645  *
8646  * Return:	true if packed is signed, false otherwise
8647  */
8648 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8649 {
8650 	struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8651 
8652 	if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8653 	    command != SMB2_NEGOTIATE_HE &&
8654 	    command != SMB2_SESSION_SETUP_HE &&
8655 	    command != SMB2_OPLOCK_BREAK_HE)
8656 		return true;
8657 
8658 	return false;
8659 }
8660 
8661 /**
8662  * smb2_check_sign_req() - handler for req packet sign processing
8663  * @work:   smb work containing notify command buffer
8664  *
8665  * Return:	1 on success, 0 otherwise
8666  */
8667 int smb2_check_sign_req(struct ksmbd_work *work)
8668 {
8669 	struct smb2_hdr *hdr;
8670 	char signature_req[SMB2_SIGNATURE_SIZE];
8671 	char signature[SMB2_HMACSHA256_SIZE];
8672 	struct kvec iov[1];
8673 	size_t len;
8674 
8675 	hdr = smb2_get_msg(work->request_buf);
8676 	if (work->next_smb2_rcv_hdr_off)
8677 		hdr = ksmbd_req_buf_next(work);
8678 
8679 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8680 		len = get_rfc1002_len(work->request_buf);
8681 	else if (hdr->NextCommand)
8682 		len = le32_to_cpu(hdr->NextCommand);
8683 	else
8684 		len = get_rfc1002_len(work->request_buf) -
8685 			work->next_smb2_rcv_hdr_off;
8686 
8687 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8688 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8689 
8690 	iov[0].iov_base = (char *)&hdr->ProtocolId;
8691 	iov[0].iov_len = len;
8692 
8693 	if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8694 				signature))
8695 		return 0;
8696 
8697 	if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8698 		pr_err("bad smb2 signature\n");
8699 		return 0;
8700 	}
8701 
8702 	return 1;
8703 }
8704 
8705 /**
8706  * smb2_set_sign_rsp() - handler for rsp packet sign processing
8707  * @work:   smb work containing notify command buffer
8708  *
8709  */
8710 void smb2_set_sign_rsp(struct ksmbd_work *work)
8711 {
8712 	struct smb2_hdr *hdr;
8713 	char signature[SMB2_HMACSHA256_SIZE];
8714 	struct kvec *iov;
8715 	int n_vec = 1;
8716 
8717 	hdr = ksmbd_resp_buf_curr(work);
8718 	hdr->Flags |= SMB2_FLAGS_SIGNED;
8719 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8720 
8721 	if (hdr->Command == SMB2_READ) {
8722 		iov = &work->iov[work->iov_idx - 1];
8723 		n_vec++;
8724 	} else {
8725 		iov = &work->iov[work->iov_idx];
8726 	}
8727 
8728 	if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8729 				 signature))
8730 		memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8731 }
8732 
8733 /**
8734  * smb3_check_sign_req() - handler for req packet sign processing
8735  * @work:   smb work containing notify command buffer
8736  *
8737  * Return:	1 on success, 0 otherwise
8738  */
8739 int smb3_check_sign_req(struct ksmbd_work *work)
8740 {
8741 	struct ksmbd_conn *conn = work->conn;
8742 	char *signing_key;
8743 	struct smb2_hdr *hdr;
8744 	struct channel *chann;
8745 	char signature_req[SMB2_SIGNATURE_SIZE];
8746 	char signature[SMB2_CMACAES_SIZE];
8747 	struct kvec iov[1];
8748 	size_t len;
8749 
8750 	hdr = smb2_get_msg(work->request_buf);
8751 	if (work->next_smb2_rcv_hdr_off)
8752 		hdr = ksmbd_req_buf_next(work);
8753 
8754 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8755 		len = get_rfc1002_len(work->request_buf);
8756 	else if (hdr->NextCommand)
8757 		len = le32_to_cpu(hdr->NextCommand);
8758 	else
8759 		len = get_rfc1002_len(work->request_buf) -
8760 			work->next_smb2_rcv_hdr_off;
8761 
8762 	if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8763 		signing_key = work->sess->smb3signingkey;
8764 	} else {
8765 		chann = lookup_chann_list(work->sess, conn);
8766 		if (!chann) {
8767 			return 0;
8768 		}
8769 		signing_key = chann->smb3signingkey;
8770 	}
8771 
8772 	if (!signing_key) {
8773 		pr_err("SMB3 signing key is not generated\n");
8774 		return 0;
8775 	}
8776 
8777 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8778 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8779 	iov[0].iov_base = (char *)&hdr->ProtocolId;
8780 	iov[0].iov_len = len;
8781 
8782 	if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8783 		return 0;
8784 
8785 	if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8786 		pr_err("bad smb2 signature\n");
8787 		return 0;
8788 	}
8789 
8790 	return 1;
8791 }
8792 
8793 /**
8794  * smb3_set_sign_rsp() - handler for rsp packet sign processing
8795  * @work:   smb work containing notify command buffer
8796  *
8797  */
8798 void smb3_set_sign_rsp(struct ksmbd_work *work)
8799 {
8800 	struct ksmbd_conn *conn = work->conn;
8801 	struct smb2_hdr *hdr;
8802 	struct channel *chann;
8803 	char signature[SMB2_CMACAES_SIZE];
8804 	struct kvec *iov;
8805 	int n_vec = 1;
8806 	char *signing_key;
8807 
8808 	hdr = ksmbd_resp_buf_curr(work);
8809 
8810 	if (conn->binding == false &&
8811 	    le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8812 		signing_key = work->sess->smb3signingkey;
8813 	} else {
8814 		chann = lookup_chann_list(work->sess, work->conn);
8815 		if (!chann) {
8816 			return;
8817 		}
8818 		signing_key = chann->smb3signingkey;
8819 	}
8820 
8821 	if (!signing_key)
8822 		return;
8823 
8824 	hdr->Flags |= SMB2_FLAGS_SIGNED;
8825 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8826 
8827 	if (hdr->Command == SMB2_READ) {
8828 		iov = &work->iov[work->iov_idx - 1];
8829 		n_vec++;
8830 	} else {
8831 		iov = &work->iov[work->iov_idx];
8832 	}
8833 
8834 	if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
8835 				 signature))
8836 		memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8837 }
8838 
8839 /**
8840  * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8841  * @work:   smb work containing response buffer
8842  *
8843  */
8844 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8845 {
8846 	struct ksmbd_conn *conn = work->conn;
8847 	struct ksmbd_session *sess = work->sess;
8848 	struct smb2_hdr *req, *rsp;
8849 
8850 	if (conn->dialect != SMB311_PROT_ID)
8851 		return;
8852 
8853 	WORK_BUFFERS(work, req, rsp);
8854 
8855 	if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8856 	    conn->preauth_info)
8857 		ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8858 						 conn->preauth_info->Preauth_HashValue);
8859 
8860 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8861 		__u8 *hash_value;
8862 
8863 		if (conn->binding) {
8864 			struct preauth_session *preauth_sess;
8865 
8866 			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8867 			if (!preauth_sess)
8868 				return;
8869 			hash_value = preauth_sess->Preauth_HashValue;
8870 		} else {
8871 			hash_value = sess->Preauth_HashValue;
8872 			if (!hash_value)
8873 				return;
8874 		}
8875 		ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8876 						 hash_value);
8877 	}
8878 }
8879 
8880 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8881 {
8882 	struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8883 	struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8884 	unsigned int orig_len = get_rfc1002_len(old_buf);
8885 
8886 	/* tr_buf must be cleared by the caller */
8887 	tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8888 	tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8889 	tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8890 	if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8891 	    cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8892 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8893 	else
8894 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8895 	memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8896 	inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8897 	inc_rfc1001_len(tr_buf, orig_len);
8898 }
8899 
8900 int smb3_encrypt_resp(struct ksmbd_work *work)
8901 {
8902 	struct kvec *iov = work->iov;
8903 	int rc = -ENOMEM;
8904 	void *tr_buf;
8905 
8906 	tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8907 	if (!tr_buf)
8908 		return rc;
8909 
8910 	/* fill transform header */
8911 	fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
8912 
8913 	iov[0].iov_base = tr_buf;
8914 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8915 	work->tr_buf = tr_buf;
8916 
8917 	return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
8918 }
8919 
8920 bool smb3_is_transform_hdr(void *buf)
8921 {
8922 	struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8923 
8924 	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8925 }
8926 
8927 int smb3_decrypt_req(struct ksmbd_work *work)
8928 {
8929 	struct ksmbd_session *sess;
8930 	char *buf = work->request_buf;
8931 	unsigned int pdu_length = get_rfc1002_len(buf);
8932 	struct kvec iov[2];
8933 	int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8934 	struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8935 	int rc = 0;
8936 
8937 	if (pdu_length < sizeof(struct smb2_transform_hdr) ||
8938 	    buf_data_size < sizeof(struct smb2_hdr)) {
8939 		pr_err("Transform message is too small (%u)\n",
8940 		       pdu_length);
8941 		return -ECONNABORTED;
8942 	}
8943 
8944 	if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8945 		pr_err("Transform message is broken\n");
8946 		return -ECONNABORTED;
8947 	}
8948 
8949 	sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8950 	if (!sess) {
8951 		pr_err("invalid session id(%llx) in transform header\n",
8952 		       le64_to_cpu(tr_hdr->SessionId));
8953 		return -ECONNABORTED;
8954 	}
8955 
8956 	iov[0].iov_base = buf;
8957 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8958 	iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8959 	iov[1].iov_len = buf_data_size;
8960 	rc = ksmbd_crypt_message(work, iov, 2, 0);
8961 	if (rc)
8962 		return rc;
8963 
8964 	memmove(buf + 4, iov[1].iov_base, buf_data_size);
8965 	*(__be32 *)buf = cpu_to_be32(buf_data_size);
8966 
8967 	return rc;
8968 }
8969 
8970 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8971 {
8972 	struct ksmbd_conn *conn = work->conn;
8973 	struct ksmbd_session *sess = work->sess;
8974 	struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8975 
8976 	if (conn->dialect < SMB30_PROT_ID)
8977 		return false;
8978 
8979 	if (work->next_smb2_rcv_hdr_off)
8980 		rsp = ksmbd_resp_buf_next(work);
8981 
8982 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8983 	    sess->user && !user_guest(sess->user) &&
8984 	    rsp->Status == STATUS_SUCCESS)
8985 		return true;
8986 	return false;
8987 }
8988