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