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