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