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