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