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