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