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