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