xref: /linux/fs/smb/server/smb2pdu.c (revision 9fa26285ae70ac2d3d1b47459a6b4463ab053e1c)
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 <crypto/utils.h>
8 #include <linux/inetdevice.h>
9 #include <net/addrconf.h>
10 #include <linux/syscalls.h>
11 #include <linux/namei.h>
12 #include <linux/fs_struct.h>
13 #include <linux/statfs.h>
14 #include <linux/ethtool.h>
15 #include <linux/falloc.h>
16 #include <linux/mount.h>
17 #include <linux/filelock.h>
18 #include <linux/fileattr.h>
19 #include <linux/timekeeping.h>
20 #include <linux/unaligned.h>
21 
22 #include "glob.h"
23 #include "../common/smbfsctl.h"
24 #include "oplock.h"
25 #include "smbacl.h"
26 
27 #include "auth.h"
28 #include "asn1.h"
29 #include "connection.h"
30 #include "transport_ipc.h"
31 #include "transport_rdma.h"
32 #include "vfs.h"
33 #include "vfs_cache.h"
34 #include "misc.h"
35 
36 #include "server.h"
37 #include "smb_common.h"
38 #include "../common/smb2status.h"
39 #include "ksmbd_work.h"
40 #include "mgmt/user_config.h"
41 #include "mgmt/share_config.h"
42 #include "mgmt/tree_connect.h"
43 #include "mgmt/user_session.h"
44 #include "mgmt/ksmbd_ida.h"
45 #include "ndr.h"
46 #include "stats.h"
47 #include "transport_tcp.h"
48 #include "compress.h"
49 
50 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
51 {
52 	if (work->next_smb2_rcv_hdr_off) {
53 		*req = ksmbd_req_buf_next(work);
54 		*rsp = ksmbd_resp_buf_next(work);
55 	} else {
56 		*req = smb_get_msg(work->request_buf);
57 		*rsp = smb_get_msg(work->response_buf);
58 	}
59 }
60 
61 static struct ksmbd_work *smb2_notify_cancel_claim(void **argv);
62 static void smb2_notify_cancel_fn(void **argv);
63 static void smb2_complete_notify_cancel(struct ksmbd_work *in_work);
64 
65 #define WORK_BUFFERS(w, rq, rs)	__wbuf((w), (void **)&(rq), (void **)&(rs))
66 
67 #define SMB2_CREATE_FILE_ATTRIBUTE_MASK \
68 	(FILE_ATTRIBUTE_MASK & ~(FILE_ATTRIBUTE_INTEGRITY_STREAM | \
69 				 FILE_ATTRIBUTE_NO_SCRUB_DATA))
70 
71 /* Windows reports automatic write-time updates at roughly 15 ms resolution. */
72 #define KSMBD_WRITE_TIME_RESOLUTION	(15ULL * 10000)
73 
74 /* MAXFILESIZE in [MS-FSA] 2.1.5.3 Server Requests a Write. */
75 #define SMB2_MAX_FILE_SIZE		0xfffffff0000ULL
76 
77 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
78 {
79 	struct channel *chann;
80 
81 	down_read(&sess->chann_lock);
82 	chann = xa_load(&sess->ksmbd_chann_list, (long)conn);
83 	up_read(&sess->chann_lock);
84 
85 	return chann;
86 }
87 
88 static int register_session_channel(struct ksmbd_session *sess,
89 				    struct ksmbd_conn *conn,
90 				    const char *sess_key)
91 {
92 	struct channel *chann, *old;
93 	unsigned long index;
94 	unsigned int count = 0;
95 	int rc = 0;
96 
97 	down_write(&sess->chann_lock);
98 	if (sess->tearing_down) {
99 		rc = -ESHUTDOWN;
100 		goto out;
101 	}
102 
103 	if (xa_load(&sess->ksmbd_chann_list, (long)conn))
104 		goto out;
105 
106 	xa_for_each(&sess->ksmbd_chann_list, index, chann)
107 		count++;
108 	if (count >= KSMBD_MAX_CHANNELS) {
109 		rc = -ENOSPC;
110 		goto out;
111 	}
112 
113 	chann = kmalloc_obj(struct channel, KSMBD_DEFAULT_GFP);
114 	if (!chann) {
115 		rc = -ENOMEM;
116 		goto out;
117 	}
118 
119 	chann->conn = conn;
120 	memcpy(chann->sess_key, sess_key, sizeof(chann->sess_key));
121 	old = xa_store(&sess->ksmbd_chann_list, (long)conn, chann,
122 		       KSMBD_DEFAULT_GFP);
123 	if (xa_is_err(old)) {
124 		kfree_sensitive(chann);
125 		rc = xa_err(old);
126 	}
127 out:
128 	up_write(&sess->chann_lock);
129 	return rc;
130 }
131 
132 /**
133  * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
134  * @work:	smb work
135  *
136  * Return:	0 if there is a tree connection matched or these are
137  *		skipable commands, otherwise error
138  */
139 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
140 {
141 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
142 	unsigned int cmd = le16_to_cpu(req_hdr->Command);
143 	unsigned int tree_id;
144 
145 	if (cmd == SMB2_TREE_CONNECT_HE ||
146 	    cmd ==  SMB2_CANCEL_HE ||
147 	    cmd ==  SMB2_LOGOFF_HE) {
148 		ksmbd_debug(SMB, "skip to check tree connect request\n");
149 		return 0;
150 	}
151 
152 	if (xa_empty(&work->sess->tree_conns)) {
153 		ksmbd_debug(SMB, "NO tree connected\n");
154 		return -ENOENT;
155 	}
156 
157 	tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
158 
159 	/*
160 	 * If request is not the first in Compound request,
161 	 * Just validate tree id in header with work->tcon->id.
162 	 */
163 	if (work->next_smb2_rcv_hdr_off) {
164 		if (!work->tcon) {
165 			pr_err("The first operation in the compound does not have tcon\n");
166 			return -EINVAL;
167 		}
168 		if (work->tcon->t_state != TREE_CONNECTED)
169 			return -ENOENT;
170 		if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
171 			pr_err("tree id(%u) is different with id(%u) in first operation\n",
172 					tree_id, work->tcon->id);
173 			return -EINVAL;
174 		}
175 		return 1;
176 	}
177 
178 	work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
179 	if (!work->tcon) {
180 		pr_err("Invalid tid %d\n", tree_id);
181 		return -ENOENT;
182 	}
183 
184 	return 1;
185 }
186 
187 /**
188  * smb2_set_err_rsp() - set error response code on smb response
189  * @work:	smb work containing response buffer
190  */
191 void smb2_set_err_rsp(struct ksmbd_work *work)
192 {
193 	struct smb2_err_rsp *err_rsp;
194 
195 	if (work->next_smb2_rcv_hdr_off)
196 		err_rsp = ksmbd_resp_buf_next(work);
197 	else
198 		err_rsp = smb_get_msg(work->response_buf);
199 
200 	if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
201 		int err;
202 
203 		err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
204 		err_rsp->ErrorContextCount = 0;
205 		err_rsp->Reserved = 0;
206 		err_rsp->ByteCount = 0;
207 		err_rsp->ErrorData[0] = 0;
208 		err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
209 					__SMB2_HEADER_STRUCTURE_SIZE +
210 						SMB2_ERROR_STRUCTURE_SIZE2);
211 		if (err)
212 			work->send_no_response = 1;
213 	}
214 }
215 
216 /**
217  * is_smb2_neg_cmd() - is it smb2 negotiation command
218  * @work:	smb work containing smb header
219  *
220  * Return:      true if smb2 negotiation command, otherwise false
221  */
222 bool is_smb2_neg_cmd(struct ksmbd_work *work)
223 {
224 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
225 
226 	/* is it SMB2 header ? */
227 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
228 		return false;
229 
230 	/* make sure it is request not response message */
231 	if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
232 		return false;
233 
234 	if (hdr->Command != SMB2_NEGOTIATE)
235 		return false;
236 
237 	return true;
238 }
239 
240 /**
241  * is_smb2_rsp() - is it smb2 response
242  * @work:	smb work containing smb response buffer
243  *
244  * Return:      true if smb2 response, otherwise false
245  */
246 bool is_smb2_rsp(struct ksmbd_work *work)
247 {
248 	struct smb2_hdr *hdr = smb_get_msg(work->response_buf);
249 
250 	/* is it SMB2 header ? */
251 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
252 		return false;
253 
254 	/* make sure it is response not request message */
255 	if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
256 		return false;
257 
258 	return true;
259 }
260 
261 /**
262  * get_smb2_cmd_val() - get smb command code from smb header
263  * @work:	smb work containing smb request buffer
264  *
265  * Return:      smb2 request command value
266  */
267 u16 get_smb2_cmd_val(struct ksmbd_work *work)
268 {
269 	struct smb2_hdr *rcv_hdr;
270 
271 	if (work->next_smb2_rcv_hdr_off)
272 		rcv_hdr = ksmbd_req_buf_next(work);
273 	else
274 		rcv_hdr = smb_get_msg(work->request_buf);
275 	return le16_to_cpu(rcv_hdr->Command);
276 }
277 
278 /**
279  * set_smb2_rsp_status() - set error response code on smb2 header
280  * @work:	smb work containing response buffer
281  * @err:	error response code
282  */
283 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
284 {
285 	struct smb2_hdr *rsp_hdr;
286 
287 	if (work->next_smb2_rcv_hdr_off) {
288 		rsp_hdr = ksmbd_resp_buf_next(work);
289 		rsp_hdr->Status = err;
290 		smb2_set_err_rsp(work);
291 		return;
292 	}
293 
294 	rsp_hdr = smb_get_msg(work->response_buf);
295 	rsp_hdr->Status = err;
296 
297 	work->iov_idx = 0;
298 	work->iov_cnt = 0;
299 	work->next_smb2_rcv_hdr_off = 0;
300 	smb2_set_err_rsp(work);
301 }
302 
303 /**
304  * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
305  * @work:	smb work containing smb request buffer
306  *
307  * smb2 negotiate response is sent in reply of smb1 negotiate command for
308  * dialect auto-negotiation.
309  */
310 int init_smb2_neg_rsp(struct ksmbd_work *work)
311 {
312 	struct smb2_hdr *rsp_hdr;
313 	struct smb2_negotiate_rsp *rsp;
314 	struct ksmbd_conn *conn = work->conn;
315 	int err;
316 
317 	rsp_hdr = smb_get_msg(work->response_buf);
318 	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
319 	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
320 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
321 	rsp_hdr->CreditRequest = cpu_to_le16(2);
322 	rsp_hdr->Command = SMB2_NEGOTIATE;
323 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
324 	rsp_hdr->NextCommand = 0;
325 	rsp_hdr->MessageId = 0;
326 	rsp_hdr->Id.SyncId.ProcessId = 0;
327 	rsp_hdr->Id.SyncId.TreeId = 0;
328 	rsp_hdr->SessionId = 0;
329 	memset(rsp_hdr->Signature, 0, 16);
330 
331 	rsp = smb_get_msg(work->response_buf);
332 
333 	WARN_ON(ksmbd_conn_good(conn));
334 
335 	rsp->StructureSize = cpu_to_le16(65);
336 	ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
337 	rsp->DialectRevision = cpu_to_le16(conn->dialect);
338 	/* Not setting conn guid rsp->ServerGUID, as it
339 	 * not used by client for identifying connection
340 	 */
341 	rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
342 	/* Default Max Message Size till SMB2.0, 64K*/
343 	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
344 	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
345 	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
346 
347 	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
348 	rsp->ServerStartTime = 0;
349 
350 	rsp->SecurityBufferOffset = cpu_to_le16(128);
351 	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
352 	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
353 		le16_to_cpu(rsp->SecurityBufferOffset));
354 	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
355 	if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
356 		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
357 	err = ksmbd_iov_pin_rsp(work, rsp,
358 				sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
359 	if (err)
360 		return err;
361 	conn->use_spnego = true;
362 
363 	ksmbd_conn_set_need_negotiate(conn);
364 	return 0;
365 }
366 
367 /**
368  * smb2_set_rsp_credits() - set number of credits in response buffer
369  * @work:	smb work containing smb response buffer
370  */
371 int smb2_set_rsp_credits(struct ksmbd_work *work)
372 {
373 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
374 	struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
375 	struct ksmbd_conn *conn = work->conn;
376 	unsigned short credits_requested, aux_max;
377 	unsigned short credit_charge, credits_granted = 0;
378 	u64 window_room, i;
379 
380 	if (work->send_no_response)
381 		return 0;
382 
383 	hdr->CreditCharge = req_hdr->CreditCharge;
384 
385 	if (conn->total_credits > conn->vals->max_credits) {
386 		hdr->CreditRequest = 0;
387 		pr_err("Total credits overflow: %d\n", conn->total_credits);
388 		return -EINVAL;
389 	}
390 
391 	credit_charge = max_t(unsigned short,
392 			      le16_to_cpu(req_hdr->CreditCharge), 1);
393 	if (credit_charge > conn->total_credits) {
394 		ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
395 			    credit_charge, conn->total_credits);
396 		return -EINVAL;
397 	}
398 
399 	conn->total_credits -= credit_charge;
400 	conn->outstanding_credits -= credit_charge;
401 	work->credit_charge = 0;
402 	credits_requested = max_t(unsigned short,
403 				  le16_to_cpu(req_hdr->CreditRequest), 1);
404 
405 	/* according to smb2.credits smbtorture, Windows server
406 	 * 2016 or later grant up to 8192 credits at once.
407 	 *
408 	 * TODO: Need to adjuct CreditRequest value according to
409 	 * current cpu load
410 	 */
411 	if (hdr->Command == SMB2_NEGOTIATE)
412 		aux_max = 1;
413 	else
414 		aux_max = conn->vals->max_credits - conn->total_credits;
415 
416 	/*
417 	 * The command sequence window must not grow beyond
418 	 * KSMBD_CMD_SEQ_WINDOW sequence numbers ahead of the oldest one still
419 	 * outstanding. Cap the grant by the room left in the window so that
420 	 * credits are withheld until the client consumes the low end (and so
421 	 * that seq_bitmap stays usable as a ring).
422 	 */
423 	window_room = conn->seq_low + KSMBD_CMD_SEQ_WINDOW - conn->seq_high;
424 	aux_max = min_t(unsigned short, aux_max, window_room);
425 	credits_granted = min_t(unsigned short, credits_requested, aux_max);
426 
427 	conn->total_credits += credits_granted;
428 	work->credits_granted += credits_granted;
429 
430 	/* Extend the sequence window to cover the newly granted credits. */
431 	for (i = conn->seq_high; i < conn->seq_high + credits_granted; i++)
432 		__set_bit(i & (KSMBD_CMD_SEQ_WINDOW - 1), conn->seq_bitmap);
433 	conn->seq_high += credits_granted;
434 
435 	if (!req_hdr->NextCommand) {
436 		/* Update CreditRequest in last request */
437 		hdr->CreditRequest = cpu_to_le16(work->credits_granted);
438 	}
439 	ksmbd_debug(SMB,
440 		    "credits: requested[%d] granted[%d] total_granted[%d]\n",
441 		    credits_requested, credits_granted,
442 		    conn->total_credits);
443 	return 0;
444 }
445 
446 /**
447  * init_chained_smb2_rsp() - initialize smb2 chained response
448  * @work:	smb work containing smb response buffer
449  */
450 static void init_chained_smb2_rsp(struct ksmbd_work *work)
451 {
452 	struct smb2_hdr *req = ksmbd_req_buf_next(work);
453 	struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
454 	struct smb2_hdr *rsp_hdr;
455 	struct smb2_hdr *rcv_hdr;
456 	int next_hdr_offset = 0;
457 	int len, new_len;
458 
459 	/* Len of this response = updated RFC len - offset of previous cmd
460 	 * in the compound rsp
461 	 */
462 
463 	/* Storing the current local FID which may be needed by subsequent
464 	 * command in the compound request
465 	 */
466 	if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
467 		work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
468 		work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
469 		work->compound_sid = le64_to_cpu(rsp->SessionId);
470 		work->compound_status = STATUS_SUCCESS;
471 	} else if ((req->Command == SMB2_FLUSH ||
472 		    req->Command == SMB2_READ ||
473 		    req->Command == SMB2_WRITE) &&
474 		   rsp->Status == STATUS_SUCCESS) {
475 		u64 volatile_id = KSMBD_NO_FID;
476 		u64 persistent_id = KSMBD_NO_FID;
477 
478 		if (req->Command == SMB2_FLUSH) {
479 			struct smb2_flush_req *flush_req =
480 				(struct smb2_flush_req *)req;
481 
482 			volatile_id = flush_req->VolatileFileId;
483 			persistent_id = flush_req->PersistentFileId;
484 		} else if (req->Command == SMB2_READ) {
485 			struct smb2_read_req *read_req =
486 				(struct smb2_read_req *)req;
487 
488 			volatile_id = read_req->VolatileFileId;
489 			persistent_id = read_req->PersistentFileId;
490 		} else {
491 			struct smb2_write_req *write_req =
492 				(struct smb2_write_req *)req;
493 
494 			volatile_id = write_req->VolatileFileId;
495 			persistent_id = write_req->PersistentFileId;
496 		}
497 
498 		if (has_file_id(volatile_id)) {
499 			work->compound_fid = volatile_id;
500 			work->compound_pfid = persistent_id;
501 			work->compound_sid = le64_to_cpu(rsp->SessionId);
502 			work->compound_status = STATUS_SUCCESS;
503 		}
504 	} else if (req->Command == SMB2_CREATE) {
505 		work->compound_fid = KSMBD_NO_FID;
506 		work->compound_pfid = KSMBD_NO_FID;
507 		work->compound_sid = le64_to_cpu(rsp->SessionId);
508 		work->compound_status = rsp->Status;
509 	} else if (rsp->Status != STATUS_SUCCESS) {
510 		work->compound_sid = le64_to_cpu(rsp->SessionId);
511 		/*
512 		 * Only carry the failed status forward when the failing command
513 		 * was itself part of the related chain. An unrelated command
514 		 * that fails (e.g. a standalone request with a bad session id)
515 		 * must not seed the status for a following related command,
516 		 * which has to be evaluated on its own (and may legitimately
517 		 * fail with a different status such as INVALID_PARAMETER). The
518 		 * compound session id is still tracked so a following related
519 		 * command can validate it.
520 		 */
521 		if (req->Flags & SMB2_FLAGS_RELATED_OPERATIONS)
522 			work->compound_status = rsp->Status;
523 	}
524 
525 	len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
526 	next_hdr_offset = le32_to_cpu(req->NextCommand);
527 
528 	new_len = ALIGN(len, 8);
529 	work->iov[work->iov_idx].iov_len += (new_len - len);
530 	inc_rfc1001_len(work->response_buf, new_len - len);
531 	rsp->NextCommand = cpu_to_le32(new_len);
532 
533 	work->next_smb2_rcv_hdr_off += next_hdr_offset;
534 	work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
535 	work->next_smb2_rsp_hdr_off += new_len;
536 	ksmbd_debug(SMB,
537 		    "Compound req new_len = %d rcv off = %d rsp off = %d\n",
538 		    new_len, work->next_smb2_rcv_hdr_off,
539 		    work->next_smb2_rsp_hdr_off);
540 
541 	rsp_hdr = ksmbd_resp_buf_next(work);
542 	rcv_hdr = ksmbd_req_buf_next(work);
543 
544 	if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
545 		ksmbd_debug(SMB, "related flag should be set\n");
546 		work->compound_fid = KSMBD_NO_FID;
547 		work->compound_pfid = KSMBD_NO_FID;
548 		work->compound_status = STATUS_SUCCESS;
549 	}
550 	memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
551 	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
552 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
553 	rsp_hdr->Command = rcv_hdr->Command;
554 
555 	/*
556 	 * Message is response. We don't grant oplock yet.
557 	 */
558 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
559 				SMB2_FLAGS_RELATED_OPERATIONS);
560 	if (rcv_hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION)
561 		rsp_hdr->Flags |= SMB2_FLAGS_REPLAY_OPERATION;
562 	rsp_hdr->NextCommand = 0;
563 	rsp_hdr->MessageId = rcv_hdr->MessageId;
564 	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
565 	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
566 	rsp_hdr->SessionId = rcv_hdr->SessionId;
567 	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
568 }
569 
570 static bool smb2_compound_has_failed(struct ksmbd_work *work,
571 				     struct smb2_hdr *rsp)
572 {
573 	if (!work->next_smb2_rcv_hdr_off ||
574 	    has_file_id(work->compound_fid) ||
575 	    work->compound_status == STATUS_SUCCESS)
576 		return false;
577 
578 	rsp->Status = work->compound_status;
579 	smb2_set_err_rsp(work);
580 	return true;
581 }
582 
583 /**
584  * is_chained_smb2_message() - check for chained command
585  * @work:	smb work containing smb request buffer
586  *
587  * Return:      true if chained request, otherwise false
588  */
589 bool is_chained_smb2_message(struct ksmbd_work *work)
590 {
591 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
592 	unsigned int len, next_cmd;
593 
594 	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
595 		return false;
596 
597 	hdr = ksmbd_req_buf_next(work);
598 	next_cmd = le32_to_cpu(hdr->NextCommand);
599 	if (next_cmd > 0) {
600 		if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
601 			__SMB2_HEADER_STRUCTURE_SIZE >
602 		    get_rfc1002_len(work->request_buf)) {
603 			pr_err("next command(%u) offset exceeds smb msg size\n",
604 			       next_cmd);
605 			return false;
606 		}
607 
608 		if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
609 		    work->response_sz) {
610 			pr_err("next response offset exceeds response buffer size\n");
611 			return false;
612 		}
613 
614 		ksmbd_debug(SMB, "got SMB2 chained command\n");
615 		init_chained_smb2_rsp(work);
616 		return true;
617 	} else if (work->next_smb2_rcv_hdr_off) {
618 		/*
619 		 * This is last request in chained command,
620 		 * align response to 8 byte
621 		 */
622 		len = ALIGN(get_rfc1002_len(work->response_buf), 8);
623 		len = len - get_rfc1002_len(work->response_buf);
624 		if (len) {
625 			ksmbd_debug(SMB, "padding len %u\n", len);
626 			work->iov[work->iov_idx].iov_len += len;
627 			inc_rfc1001_len(work->response_buf, len);
628 		}
629 		work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
630 	}
631 	return false;
632 }
633 
634 /**
635  * init_smb2_rsp_hdr() - initialize smb2 response
636  * @work:	smb work containing smb request buffer
637  *
638  * Return:      0
639  */
640 int init_smb2_rsp_hdr(struct ksmbd_work *work)
641 {
642 	struct smb2_hdr *rsp_hdr = smb_get_msg(work->response_buf);
643 	struct smb2_hdr *rcv_hdr = smb_get_msg(work->request_buf);
644 
645 	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
646 	rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
647 	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
648 	rsp_hdr->Command = rcv_hdr->Command;
649 
650 	/*
651 	 * Message is response. We don't grant oplock yet.
652 	 */
653 	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
654 	if (rcv_hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION)
655 		rsp_hdr->Flags |= SMB2_FLAGS_REPLAY_OPERATION;
656 	rsp_hdr->NextCommand = 0;
657 	rsp_hdr->MessageId = rcv_hdr->MessageId;
658 	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
659 	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
660 	rsp_hdr->SessionId = rcv_hdr->SessionId;
661 	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
662 
663 	return 0;
664 }
665 
666 static __le16 smb3_hdr_channel_sequence(struct smb2_hdr *hdr)
667 {
668 	return ((struct smb3_hdr_req *)hdr)->ChannelSequence;
669 }
670 
671 static bool smb3_hdr_replay(struct smb2_hdr *hdr)
672 {
673 	return hdr->Flags & SMB2_FLAGS_REPLAY_OPERATION;
674 }
675 
676 static int smb3_verify_channel_sequence(struct ksmbd_work *work,
677 					struct ksmbd_file *fp,
678 					struct smb2_hdr *hdr,
679 					bool allow_stale)
680 {
681 	__le16 chseq_le;
682 	u16 chseq, old_chseq;
683 	int ret = 0;
684 
685 	if (work->conn->dialect < SMB30_PROT_ID)
686 		return 0;
687 
688 	chseq_le = smb3_hdr_channel_sequence(hdr);
689 	chseq = le16_to_cpu(chseq_le);
690 
691 	spin_lock(&fp->f_lock);
692 	old_chseq = le16_to_cpu(fp->channel_sequence);
693 	if (smb3_hdr_replay(hdr)) {
694 		if (chseq == old_chseq && fp->outstanding_pre_requests == 0) {
695 			fp->outstanding_requests++;
696 		} else if ((u16)(chseq - old_chseq) <= 0x7fff &&
697 			   fp->outstanding_pre_requests == 0) {
698 			fp->outstanding_pre_requests += fp->outstanding_requests;
699 			fp->outstanding_requests = 1;
700 			fp->channel_sequence = chseq_le;
701 		} else if (allow_stale) {
702 			fp->outstanding_pre_requests++;
703 		} else {
704 			ret = -EAGAIN;
705 		}
706 	} else {
707 		if (chseq == old_chseq) {
708 			fp->outstanding_requests++;
709 		} else if ((u16)(chseq - old_chseq) <= 0x7fff) {
710 			fp->outstanding_pre_requests += fp->outstanding_requests;
711 			fp->outstanding_requests = 1;
712 			fp->channel_sequence = chseq_le;
713 		} else if (allow_stale) {
714 			fp->outstanding_pre_requests++;
715 		} else {
716 			ret = -EAGAIN;
717 		}
718 	}
719 	spin_unlock(&fp->f_lock);
720 
721 	return ret;
722 }
723 
724 static void smb3_complete_channel_sequence(struct ksmbd_work *work,
725 					   struct ksmbd_file *fp,
726 					   __le16 chseq_le)
727 {
728 	u16 chseq;
729 
730 	if (work->conn->dialect < SMB30_PROT_ID)
731 		return;
732 
733 	chseq = le16_to_cpu(chseq_le);
734 
735 	spin_lock(&fp->f_lock);
736 	if (chseq == le16_to_cpu(fp->channel_sequence)) {
737 		if (fp->outstanding_requests)
738 			fp->outstanding_requests--;
739 	} else {
740 		if (fp->outstanding_pre_requests)
741 			fp->outstanding_pre_requests--;
742 	}
743 	spin_unlock(&fp->f_lock);
744 }
745 
746 static int smb2_set_request_open(struct ksmbd_work *work, struct ksmbd_file *fp,
747 				 struct smb2_hdr *hdr, bool verify_chseq,
748 				 bool allow_stale_chseq)
749 {
750 	struct ksmbd_file *open;
751 	int ret;
752 
753 	smb2_complete_request_open(work);
754 
755 	open = ksmbd_file_get(fp);
756 	if (!open)
757 		return -ESTALE;
758 
759 	if (verify_chseq) {
760 		ret = smb3_verify_channel_sequence(work, fp, hdr,
761 						   allow_stale_chseq);
762 		if (ret) {
763 			ksmbd_fd_put(work, open);
764 			return ret;
765 		}
766 		work->request_open_chseq_tracked = true;
767 	}
768 
769 	work->request_open = open;
770 	work->request_open_chseq = smb3_hdr_channel_sequence(hdr);
771 	return 0;
772 }
773 
774 void smb2_complete_request_open(struct ksmbd_work *work)
775 {
776 	struct ksmbd_file *open = work->request_open;
777 
778 	if (!open)
779 		return;
780 
781 	if (work->request_open_chseq_tracked)
782 		smb3_complete_channel_sequence(work, open,
783 					       work->request_open_chseq);
784 
785 	work->request_open = NULL;
786 	work->request_open_chseq_tracked = false;
787 	ksmbd_fd_put(work, open);
788 }
789 
790 static bool smb2_lock_sequence_applicable(struct ksmbd_work *work,
791 					  struct ksmbd_file *fp)
792 {
793 	return fp->is_resilient || fp->is_durable || fp->is_persistent ||
794 	       (work->conn->dialect >= SMB30_PROT_ID &&
795 		(work->conn->vals->req_capabilities &
796 		 SMB2_GLOBAL_CAP_MULTI_CHANNEL));
797 }
798 
799 static bool smb2_verify_lock_sequence(struct ksmbd_work *work,
800 				       struct ksmbd_file *fp,
801 				       struct smb2_lock_req *req)
802 {
803 	u32 val, index;
804 	u8 sequence;
805 	bool replay = false;
806 
807 	if (work->conn->dialect == SMB20_PROT_ID ||
808 	    !smb2_lock_sequence_applicable(work, fp))
809 		return false;
810 
811 	val = le32_to_cpu(req->LockSequenceNumber);
812 	sequence = val & 0xf;
813 	index = val >> 4;
814 	if (!index || index > KSMBD_LOCK_SEQ_ARRAY_SIZE)
815 		return false;
816 
817 	spin_lock(&fp->f_lock);
818 	if (fp->lock_seq[index - 1].valid) {
819 		if (fp->lock_seq[index - 1].sequence == sequence)
820 			replay = true;
821 		else
822 			fp->lock_seq[index - 1].valid = false;
823 	}
824 	spin_unlock(&fp->f_lock);
825 
826 	return replay;
827 }
828 
829 static void smb2_update_lock_sequence(struct ksmbd_work *work,
830 				      struct ksmbd_file *fp,
831 				      struct smb2_lock_req *req)
832 {
833 	u32 val, index;
834 	u8 sequence;
835 
836 	if (work->conn->dialect == SMB20_PROT_ID ||
837 	    !smb2_lock_sequence_applicable(work, fp))
838 		return;
839 
840 	val = le32_to_cpu(req->LockSequenceNumber);
841 	sequence = val & 0xf;
842 	index = val >> 4;
843 	if (!index || index > KSMBD_LOCK_SEQ_ARRAY_SIZE)
844 		return;
845 
846 	spin_lock(&fp->f_lock);
847 	fp->lock_seq[index - 1].valid = true;
848 	fp->lock_seq[index - 1].sequence = sequence;
849 	spin_unlock(&fp->f_lock);
850 }
851 
852 /**
853  * smb2_allocate_rsp_buf() - allocate smb2 response buffer
854  * @work:	smb work containing smb request buffer
855  *
856  * Return:      0 on success, otherwise error
857  */
858 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
859 {
860 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
861 	size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
862 	size_t large_sz = small_sz + work->conn->vals->max_trans_size;
863 	size_t sz = small_sz;
864 	int cmd = le16_to_cpu(hdr->Command);
865 
866 	if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
867 		sz = large_sz;
868 
869 	if (cmd == SMB2_QUERY_INFO_HE) {
870 		struct smb2_query_info_req *req;
871 
872 		if (get_rfc1002_len(work->request_buf) <
873 		    offsetof(struct smb2_query_info_req, OutputBufferLength))
874 			return -EINVAL;
875 
876 		req = smb_get_msg(work->request_buf);
877 		if ((req->InfoType == SMB2_O_INFO_FILE &&
878 		     (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
879 		      req->FileInfoClass == FILE_ALL_INFORMATION ||
880 		      req->FileInfoClass == FILE_NORMALIZED_NAME_INFORMATION)) ||
881 		    req->InfoType == SMB2_O_INFO_SECURITY)
882 			sz = large_sz;
883 	}
884 
885 	/* allocate large response buf for chained commands */
886 	if (le32_to_cpu(hdr->NextCommand) > 0)
887 		sz = large_sz;
888 
889 	work->response_buf = kvzalloc(sz, KSMBD_DEFAULT_GFP);
890 	if (!work->response_buf)
891 		return -ENOMEM;
892 
893 	work->response_sz = sz;
894 	return 0;
895 }
896 
897 static bool smb2_session_expired_cmd_allowed(struct ksmbd_work *work,
898 					      unsigned int cmd)
899 {
900 	struct smb2_lock_req *req;
901 	unsigned int len, lock_count, i;
902 
903 	if (cmd == SMB2_CANCEL_HE || cmd == SMB2_CLOSE_HE ||
904 	    cmd == SMB2_LOGOFF_HE)
905 		return true;
906 	if (cmd != SMB2_LOCK_HE)
907 		return false;
908 
909 	req = ksmbd_req_buf_next(work);
910 	if (req->hdr.NextCommand)
911 		len = le32_to_cpu(req->hdr.NextCommand);
912 	else {
913 		len = get_rfc1002_len(work->request_buf);
914 		if (len < work->next_smb2_rcv_hdr_off)
915 			return false;
916 		len -= work->next_smb2_rcv_hdr_off;
917 	}
918 
919 	lock_count = le16_to_cpu(req->LockCount);
920 	if (!lock_count || len < offsetof(struct smb2_lock_req, locks) ||
921 	    lock_count > (len - offsetof(struct smb2_lock_req, locks)) /
922 			 sizeof(struct smb2_lock_element))
923 		return false;
924 
925 	for (i = 0; i < lock_count; i++) {
926 		if (le32_to_cpu(req->locks[i].Flags) != SMB2_LOCKFLAG_UNLOCK)
927 			return false;
928 	}
929 	return true;
930 }
931 
932 static bool smb2_session_kerberos_expired(struct ksmbd_session *sess)
933 {
934 	if (!sess->kerberos_expiry ||
935 	    ktime_get_real_seconds() < sess->kerberos_expiry)
936 		return false;
937 
938 	if (cmpxchg(&sess->state, SMB2_SESSION_VALID,
939 		    SMB2_SESSION_EXPIRED) == SMB2_SESSION_VALID)
940 		ksmbd_counter_inc(KSMBD_COUNTER_SESSION_TIMEOUTS);
941 	return true;
942 }
943 
944 /**
945  * smb2_check_user_session() - check for valid session for a user
946  * @work:	smb work containing smb request buffer
947  *
948  * Return:      0 on success, otherwise error
949  */
950 int smb2_check_user_session(struct ksmbd_work *work)
951 {
952 	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
953 	struct ksmbd_conn *conn = work->conn;
954 	unsigned int cmd = le16_to_cpu(req_hdr->Command);
955 	unsigned long long sess_id;
956 
957 	/*
958 	 * SMB2_NEGOTIATE and SMB2_SESSION_SETUP do not require a session id.
959 	 * SMB2_ECHO may omit it, but an echo carrying a session id still needs
960 	 * the session attached to work so that its signature can be checked and
961 	 * the response can be signed, including after Kerberos expiry.
962 	 */
963 	if (cmd == SMB2_NEGOTIATE_HE || cmd == SMB2_SESSION_SETUP_HE)
964 		return 0;
965 
966 	sess_id = le64_to_cpu(req_hdr->SessionId);
967 	if (cmd == SMB2_ECHO_HE) {
968 		/*
969 		 * ECHO remains valid without a live session, including after
970 		 * LOGOFF. Attach an existing session only to authenticate a signed
971 		 * ECHO and sign its response; a stale SessionId is not an error.
972 		 */
973 		if (!work->next_smb2_rcv_hdr_off && sess_id)
974 			work->sess = ksmbd_session_lookup_all_states(conn, sess_id);
975 		if (work->sess) {
976 			if (!smb2_session_kerberos_expired(work->sess) &&
977 			    work->sess->state != SMB2_SESSION_VALID) {
978 				ksmbd_user_session_put(work->sess);
979 				work->sess = NULL;
980 			}
981 		}
982 		return 0;
983 	}
984 
985 	if (!ksmbd_conn_good(conn))
986 		return -EIO;
987 
988 	/*
989 	 * If request is not the first in Compound request,
990 	 * Just validate session id in header with work->sess->id.
991 	 */
992 	if (work->next_smb2_rcv_hdr_off) {
993 		if (!work->sess) {
994 			pr_err("The first operation in the compound does not have sess\n");
995 			return -EINVAL;
996 		}
997 		if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
998 			pr_err("session id(%llu) is different with the first operation(%lld)\n",
999 					sess_id, work->sess->id);
1000 			return -EINVAL;
1001 		}
1002 		smb2_session_kerberos_expired(work->sess);
1003 		if (work->sess->state != SMB2_SESSION_VALID) {
1004 			pr_err("compound request on a non-valid session (state %d)\n",
1005 					work->sess->state);
1006 			if (smb2_session_kerberos_expired(work->sess) &&
1007 			    smb2_session_expired_cmd_allowed(work, cmd))
1008 				return 1;
1009 			return smb2_session_kerberos_expired(work->sess) ?
1010 				-EKEYEXPIRED : -EINVAL;
1011 		}
1012 		return 1;
1013 	}
1014 
1015 	/* Check for validity of user session */
1016 	work->sess = ksmbd_session_lookup_all_states(conn, sess_id);
1017 	if (work->sess) {
1018 		if (smb2_session_kerberos_expired(work->sess)) {
1019 			return smb2_session_expired_cmd_allowed(work, cmd) ?
1020 				1 : -EKEYEXPIRED;
1021 		}
1022 		if (work->sess->state != SMB2_SESSION_VALID) {
1023 			/*
1024 			 * Keep the reference for an encrypted request so the caller can
1025 			 * return STATUS_USER_SESSION_DELETED encrypted with the old key.
1026 			 */
1027 			if (work->encrypted &&
1028 			    work->sess->state == SMB2_SESSION_EXPIRED &&
1029 			    work->sess->enc)
1030 				return -ENOENT;
1031 			ksmbd_user_session_put(work->sess);
1032 			work->sess = NULL;
1033 			return -ENOENT;
1034 		}
1035 		return 1;
1036 	}
1037 	ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
1038 	return -ENOENT;
1039 }
1040 
1041 /**
1042  * smb2_get_name() - get filename string from on the wire smb format
1043  * @src:	source buffer
1044  * @maxlen:	maxlen of source string
1045  * @local_nls:	nls_table pointer
1046  *
1047  * Return:      matching converted filename on success, otherwise error ptr
1048  */
1049 static char *
1050 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
1051 {
1052 	char *name;
1053 
1054 	name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
1055 	if (IS_ERR(name)) {
1056 		pr_err("failed to get name %ld\n", PTR_ERR(name));
1057 		return name;
1058 	}
1059 
1060 	if (*name == '\0') {
1061 		kfree(name);
1062 		return ERR_PTR(-EINVAL);
1063 	}
1064 
1065 	if (*name == '\\') {
1066 		pr_err("not allow directory name included leading slash\n");
1067 		kfree(name);
1068 		return ERR_PTR(-EINVAL);
1069 	}
1070 
1071 	ksmbd_conv_path_to_unix(name);
1072 	ksmbd_strip_last_slash(name);
1073 	return name;
1074 }
1075 
1076 /* Link a fully initialized async work item unless the connection is closing. */
1077 static bool ksmbd_conn_link_async_request(struct ksmbd_conn *conn,
1078 					  struct ksmbd_work *work)
1079 {
1080 	bool linked = false;
1081 
1082 	spin_lock(&conn->request_lock);
1083 	if (!ksmbd_conn_exiting(conn) && !ksmbd_conn_releasing(conn)) {
1084 		if (list_empty(&work->async_request_entry))
1085 			list_add_tail(&work->async_request_entry,
1086 				      &conn->async_requests);
1087 		linked = true;
1088 	}
1089 	spin_unlock(&conn->request_lock);
1090 
1091 	return linked;
1092 }
1093 
1094 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
1095 {
1096 	struct ksmbd_conn *conn = work->conn;
1097 	int id;
1098 
1099 	id = ksmbd_acquire_async_msg_id(&conn->async_ida);
1100 	if (id < 0) {
1101 		pr_err("Failed to alloc async message id\n");
1102 		return id;
1103 	}
1104 	work->asynchronous = true;
1105 	work->async_id = id;
1106 	work->cancel_fn = fn;
1107 	work->cancel_argv = arg;
1108 
1109 	if (!ksmbd_conn_link_async_request(conn, work)) {
1110 		work->asynchronous = false;
1111 		work->async_id = 0;
1112 		work->cancel_fn = NULL;
1113 		work->cancel_argv = NULL;
1114 		ksmbd_release_id(&conn->async_ida, id);
1115 		return -ESHUTDOWN;
1116 	}
1117 
1118 	ksmbd_debug(SMB,
1119 		    "Send interim Response to inform async request id : %d\n",
1120 		    work->async_id);
1121 
1122 	return 0;
1123 }
1124 
1125 void release_async_work(struct ksmbd_work *work)
1126 {
1127 	struct ksmbd_conn *conn = work->conn;
1128 
1129 	spin_lock(&conn->request_lock);
1130 	list_del_init(&work->async_request_entry);
1131 	spin_unlock(&conn->request_lock);
1132 
1133 	work->asynchronous = 0;
1134 	work->cancel_fn = NULL;
1135 	kfree(work->cancel_argv);
1136 	work->cancel_argv = NULL;
1137 	if (work->async_id) {
1138 		ksmbd_release_id(&conn->async_ida, work->async_id);
1139 		work->async_id = 0;
1140 	}
1141 }
1142 
1143 static int smb2_send_interim_work(struct ksmbd_work *in_work,
1144 				  struct ksmbd_work *work, bool eor)
1145 {
1146 	int err = 0;
1147 
1148 	in_work->encrypted = work->encrypted;
1149 	if (work->encrypted && work->sess && work->sess->enc &&
1150 	    work->conn->ops->encrypt_resp) {
1151 		in_work->sess = work->sess;
1152 		err = work->conn->ops->encrypt_resp(in_work);
1153 		in_work->sess = NULL;
1154 	}
1155 	if (err)
1156 		return err;
1157 
1158 	return eor ? ksmbd_conn_write_eor(in_work) :
1159 		ksmbd_conn_write(in_work);
1160 }
1161 
1162 static int smb2_send_interim_prefix_work(struct ksmbd_work *work)
1163 {
1164 	struct ksmbd_work *in_work;
1165 	unsigned int len, copied = 0;
1166 	char *dst;
1167 	int err = -ENOMEM;
1168 	int i;
1169 
1170 	len = get_rfc1002_len(work->iov[0].iov_base);
1171 	in_work = ksmbd_alloc_work_struct();
1172 	if (!in_work)
1173 		return err;
1174 
1175 	in_work->response_buf = kvzalloc(len + 4, KSMBD_DEFAULT_GFP);
1176 	if (!in_work->response_buf)
1177 		goto out;
1178 	in_work->response_sz = len + 4;
1179 	in_work->conn = work->conn;
1180 	dst = in_work->response_buf + 4;
1181 	for (i = 1; i <= work->iov_idx; i++) {
1182 		if (work->iov[i].iov_len > len - copied) {
1183 			err = -EINVAL;
1184 			goto out;
1185 		}
1186 		memcpy(dst + copied, work->iov[i].iov_base,
1187 		       work->iov[i].iov_len);
1188 		copied += work->iov[i].iov_len;
1189 	}
1190 	if (copied != len) {
1191 		err = -EINVAL;
1192 		goto out;
1193 	}
1194 
1195 	err = ksmbd_iov_pin_rsp(in_work, dst, len);
1196 	if (!err)
1197 		err = smb2_send_interim_work(in_work, work, true);
1198 out:
1199 	ksmbd_free_work_struct(in_work);
1200 	return err;
1201 }
1202 
1203 static void smb2_send_interim_compound_prefix(struct ksmbd_work *work)
1204 {
1205 	struct smb2_hdr *req_hdr;
1206 	struct smb2_hdr *rsp_hdr;
1207 	int err;
1208 
1209 	if (!work->next_smb2_rcv_hdr_off ||
1210 	    !work->next_smb2_rsp_hdr_off ||
1211 	    work->curr_smb2_rsp_hdr_off == work->next_smb2_rsp_hdr_off ||
1212 	    !work->iov_idx)
1213 		return;
1214 
1215 	req_hdr = ksmbd_req_buf_next(work);
1216 	/* Detach only the final async command from the completed prefix. */
1217 	if (req_hdr->NextCommand)
1218 		return;
1219 
1220 	/*
1221 	 * The responses before the async command are sent as a standalone
1222 	 * compound response. The last response in this prefix must terminate
1223 	 * the chain.
1224 	 */
1225 	rsp_hdr = ksmbd_resp_buf_curr(work);
1226 	rsp_hdr->NextCommand = 0;
1227 	if ((rsp_hdr->Flags & SMB2_FLAGS_SIGNED) && work->sess &&
1228 	    work->conn->ops->set_sign_rsp)
1229 		work->conn->ops->set_sign_rsp(work);
1230 
1231 	err = smb2_send_interim_prefix_work(work);
1232 	if (err)
1233 		ksmbd_debug(SMB, "failed to send compound interim prefix: %d\n",
1234 			    err);
1235 
1236 	work->iov_idx = 0;
1237 	work->iov_cnt = 0;
1238 	work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
1239 	*(__be32 *)work->response_buf = 0;
1240 
1241 	rsp_hdr = ksmbd_resp_buf_next(work);
1242 	rsp_hdr->Flags &= ~SMB2_FLAGS_RELATED_OPERATIONS;
1243 }
1244 
1245 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
1246 {
1247 	struct smb2_hdr *rsp_hdr;
1248 	struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
1249 
1250 	if (!in_work)
1251 		return;
1252 
1253 	if (allocate_interim_rsp_buf(in_work)) {
1254 		pr_err("smb_allocate_rsp_buf failed!\n");
1255 		ksmbd_free_work_struct(in_work);
1256 		return;
1257 	}
1258 
1259 	if (status == STATUS_PENDING)
1260 		smb2_send_interim_compound_prefix(work);
1261 
1262 	in_work->conn = work->conn;
1263 	memcpy(smb_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
1264 	       __SMB2_HEADER_STRUCTURE_SIZE);
1265 
1266 	rsp_hdr = smb_get_msg(in_work->response_buf);
1267 	rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
1268 	rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
1269 	smb2_set_err_rsp(in_work);
1270 	rsp_hdr->Status = status;
1271 
1272 	if (smb2_send_interim_work(in_work, work, true))
1273 		ksmbd_debug(SMB, "failed to send interim response\n");
1274 	ksmbd_free_work_struct(in_work);
1275 }
1276 
1277 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
1278 {
1279 	if (S_ISDIR(mode) || S_ISREG(mode))
1280 		return 0;
1281 
1282 	if (S_ISLNK(mode))
1283 		return IO_REPARSE_TAG_LX_SYMLINK_LE;
1284 	else if (S_ISFIFO(mode))
1285 		return IO_REPARSE_TAG_LX_FIFO_LE;
1286 	else if (S_ISSOCK(mode))
1287 		return IO_REPARSE_TAG_AF_UNIX_LE;
1288 	else if (S_ISCHR(mode))
1289 		return IO_REPARSE_TAG_LX_CHR_LE;
1290 	else if (S_ISBLK(mode))
1291 		return IO_REPARSE_TAG_LX_BLK_LE;
1292 
1293 	return 0;
1294 }
1295 
1296 /**
1297  * smb2_get_dos_mode() - get file mode in dos format from unix mode
1298  * @stat:	kstat containing file mode
1299  * @attribute:	attribute flags
1300  *
1301  * Return:      converted dos mode
1302  */
1303 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
1304 {
1305 	int attr = 0;
1306 
1307 	if (S_ISDIR(stat->mode)) {
1308 		attr = FILE_ATTRIBUTE_DIRECTORY |
1309 			(attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
1310 	} else {
1311 		attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
1312 		attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
1313 
1314 		if (smb2_get_reparse_tag_special_file(stat->mode))
1315 			attr |= FILE_ATTRIBUTE_REPARSE_POINT;
1316 	}
1317 
1318 	return attr;
1319 }
1320 
1321 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
1322 			       __le16 hash_id)
1323 {
1324 	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
1325 	pneg_ctxt->DataLength = cpu_to_le16(38);
1326 	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
1327 	pneg_ctxt->Reserved = cpu_to_le32(0);
1328 	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
1329 	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
1330 	pneg_ctxt->HashAlgorithms = hash_id;
1331 }
1332 
1333 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
1334 			       __le16 cipher_type)
1335 {
1336 	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
1337 	pneg_ctxt->DataLength = cpu_to_le16(4);
1338 	pneg_ctxt->Reserved = cpu_to_le32(0);
1339 	pneg_ctxt->CipherCount = cpu_to_le16(1);
1340 	pneg_ctxt->Ciphers[0] = cipher_type;
1341 }
1342 
1343 static void build_compress_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
1344 				__le16 compress_algorithm, bool compress_chained,
1345 				bool compress_pattern)
1346 {
1347 	/*
1348 	 * Return only algorithms implemented by ksmbd. Pattern_V1 is advertised
1349 	 * as a second ID when the client also enabled chained transforms.
1350 	 */
1351 	pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
1352 	pneg_ctxt->DataLength = cpu_to_le16(compress_pattern ? 12 : 10);
1353 	pneg_ctxt->Reserved = cpu_to_le32(0);
1354 	pneg_ctxt->CompressionAlgorithmCount =
1355 		cpu_to_le16(compress_pattern ? 2 : 1);
1356 	pneg_ctxt->Padding = cpu_to_le16(0);
1357 	pneg_ctxt->Flags = compress_chained ?
1358 		SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED :
1359 		SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE;
1360 	pneg_ctxt->CompressionAlgorithms[0] = compress_algorithm;
1361 	pneg_ctxt->CompressionAlgorithms[1] = compress_pattern ?
1362 		SMB3_COMPRESS_PATTERN : 0;
1363 	pneg_ctxt->CompressionAlgorithms[2] = 0;
1364 	pneg_ctxt->CompressionAlgorithms[3] = 0;
1365 }
1366 
1367 /**
1368  * build_rdma_ctx() - build an RDMA transform negotiate response context
1369  * @ctxt: response context header to populate
1370  * @transform_ids: bitmap of transforms common to the client and server
1371  *
1372  * Return: encoded negotiate context length
1373  */
1374 static int build_rdma_ctx(struct smb2_neg_context *ctxt,
1375 			  unsigned long transform_ids)
1376 {
1377 	struct smb2_rdma_transform_capabilities_context *pneg_ctxt;
1378 	int count = 0;
1379 
1380 	pneg_ctxt = (void *)ctxt;
1381 	pneg_ctxt->ContextType = SMB2_RDMA_TRANSFORM_CAPABILITIES;
1382 	pneg_ctxt->Reserved = 0;
1383 	pneg_ctxt->Reserved1 = 0;
1384 	pneg_ctxt->Reserved2 = 0;
1385 	if (transform_ids & BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION))
1386 		pneg_ctxt->RDMATransformIds[count++] =
1387 			cpu_to_le16(SMB2_RDMA_TRANSFORM_ENCRYPTION);
1388 	if (!count)
1389 		pneg_ctxt->RDMATransformIds[count++] =
1390 			cpu_to_le16(SMB2_RDMA_TRANSFORM_NONE);
1391 
1392 	pneg_ctxt->TransformCount = cpu_to_le16(count);
1393 	pneg_ctxt->DataLength = cpu_to_le16(8 + count * sizeof(__le16));
1394 	return sizeof(struct smb2_neg_context) +
1395 		le16_to_cpu(pneg_ctxt->DataLength);
1396 }
1397 
1398 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
1399 				__le16 sign_algo)
1400 {
1401 	pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
1402 	pneg_ctxt->DataLength =
1403 		cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
1404 			- sizeof(struct smb2_neg_context));
1405 	pneg_ctxt->Reserved = cpu_to_le32(0);
1406 	pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
1407 	pneg_ctxt->SigningAlgorithms[0] = sign_algo;
1408 }
1409 
1410 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
1411 {
1412 	pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
1413 	pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
1414 	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
1415 	pneg_ctxt->Name[0] = 0x93;
1416 	pneg_ctxt->Name[1] = 0xAD;
1417 	pneg_ctxt->Name[2] = 0x25;
1418 	pneg_ctxt->Name[3] = 0x50;
1419 	pneg_ctxt->Name[4] = 0x9C;
1420 	pneg_ctxt->Name[5] = 0xB4;
1421 	pneg_ctxt->Name[6] = 0x11;
1422 	pneg_ctxt->Name[7] = 0xE7;
1423 	pneg_ctxt->Name[8] = 0xB4;
1424 	pneg_ctxt->Name[9] = 0x23;
1425 	pneg_ctxt->Name[10] = 0x83;
1426 	pneg_ctxt->Name[11] = 0xDE;
1427 	pneg_ctxt->Name[12] = 0x96;
1428 	pneg_ctxt->Name[13] = 0x8B;
1429 	pneg_ctxt->Name[14] = 0xCD;
1430 	pneg_ctxt->Name[15] = 0x7C;
1431 }
1432 
1433 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
1434 				  struct smb2_negotiate_rsp *rsp)
1435 {
1436 	char * const pneg_ctxt = (char *)rsp +
1437 			le32_to_cpu(rsp->NegotiateContextOffset);
1438 	int neg_ctxt_cnt = 1;
1439 	int ctxt_size;
1440 
1441 	ksmbd_debug(SMB,
1442 		    "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1443 	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
1444 			   conn->preauth_info->Preauth_HashId);
1445 	ctxt_size = sizeof(struct smb2_preauth_neg_context);
1446 
1447 	if (conn->cipher_type) {
1448 		/* Round to 8 byte boundary */
1449 		ctxt_size = round_up(ctxt_size, 8);
1450 		ksmbd_debug(SMB,
1451 			    "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1452 		build_encrypt_ctxt((struct smb2_encryption_neg_context *)
1453 				   (pneg_ctxt + ctxt_size),
1454 				   conn->cipher_type);
1455 		neg_ctxt_cnt++;
1456 		ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
1457 	}
1458 
1459 	if (conn->compress_algorithm != SMB3_COMPRESS_NONE) {
1460 		ctxt_size = round_up(ctxt_size, 8);
1461 		ksmbd_debug(SMB,
1462 			    "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
1463 		build_compress_ctxt((struct smb2_compression_capabilities_context *)
1464 				    (pneg_ctxt + ctxt_size),
1465 				    conn->compress_algorithm,
1466 				    conn->compress_chained,
1467 				    conn->compress_pattern);
1468 		neg_ctxt_cnt++;
1469 		ctxt_size += sizeof(struct smb2_neg_context) +
1470 			(conn->compress_pattern ? 12 : 10);
1471 	}
1472 
1473 	if (conn->rdma_transform_negotiated) {
1474 		struct smb2_neg_context *rdma_ctxt;
1475 
1476 		ctxt_size = round_up(ctxt_size, 8);
1477 		ksmbd_debug(SMB,
1478 			    "assemble SMB2_RDMA_TRANSFORM_CAPABILITIES context\n");
1479 		rdma_ctxt = (void *)(pneg_ctxt + ctxt_size);
1480 		ctxt_size += build_rdma_ctx(rdma_ctxt,
1481 					     conn->rdma_transform_ids);
1482 		neg_ctxt_cnt++;
1483 	}
1484 
1485 	if (conn->posix_ext_supported) {
1486 		ctxt_size = round_up(ctxt_size, 8);
1487 		ksmbd_debug(SMB,
1488 			    "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1489 		build_posix_ctxt((struct smb2_posix_neg_context *)
1490 				 (pneg_ctxt + ctxt_size));
1491 		neg_ctxt_cnt++;
1492 		ctxt_size += sizeof(struct smb2_posix_neg_context);
1493 	}
1494 
1495 	if (conn->signing_negotiated) {
1496 		ctxt_size = round_up(ctxt_size, 8);
1497 		ksmbd_debug(SMB,
1498 			    "assemble SMB2_SIGNING_CAPABILITIES context\n");
1499 		build_sign_cap_ctxt((struct smb2_signing_capabilities *)
1500 				    (pneg_ctxt + ctxt_size),
1501 				    conn->signing_algorithm);
1502 		neg_ctxt_cnt++;
1503 		ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
1504 	}
1505 
1506 	rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
1507 	return ctxt_size + AUTH_GSS_PADDING;
1508 }
1509 
1510 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
1511 				  struct smb2_preauth_neg_context *pneg_ctxt,
1512 				  int ctxt_len)
1513 {
1514 	/*
1515 	 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
1516 	 * which may not be present. Only check for used HashAlgorithms[1].
1517 	 */
1518 	if (ctxt_len <
1519 	    sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
1520 		return STATUS_INVALID_PARAMETER;
1521 
1522 	if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
1523 		return STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
1524 
1525 	conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
1526 	return STATUS_SUCCESS;
1527 }
1528 
1529 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
1530 				struct smb2_encryption_neg_context *pneg_ctxt,
1531 				int ctxt_len)
1532 {
1533 	int cph_cnt;
1534 	int i, cphs_size;
1535 
1536 	if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
1537 		pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
1538 		return;
1539 	}
1540 
1541 	conn->cipher_type = 0;
1542 
1543 	cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
1544 	cphs_size = cph_cnt * sizeof(__le16);
1545 
1546 	if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
1547 	    ctxt_len) {
1548 		pr_err("Invalid cipher count(%d)\n", cph_cnt);
1549 		return;
1550 	}
1551 
1552 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
1553 		return;
1554 
1555 	for (i = 0; i < cph_cnt; i++) {
1556 		if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
1557 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
1558 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
1559 		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
1560 			ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
1561 				    pneg_ctxt->Ciphers[i]);
1562 			conn->cipher_type = pneg_ctxt->Ciphers[i];
1563 			break;
1564 		}
1565 	}
1566 }
1567 
1568 /**
1569  * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
1570  * @conn:	smb connection
1571  *
1572  * Return:	true if connection should be encrypted, else false
1573  */
1574 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
1575 {
1576 	if (!conn->ops->generate_encryptionkey)
1577 		return false;
1578 
1579 	/*
1580 	 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
1581 	 * SMB 3.1.1 uses the cipher_type field.
1582 	 */
1583 	return (conn->vals->req_capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
1584 	    conn->cipher_type;
1585 }
1586 
1587 static __le32 decode_compress_ctxt(struct ksmbd_conn *conn,
1588 				   struct smb2_compression_capabilities_context *pneg_ctxt,
1589 				   int ctxt_len)
1590 {
1591 	int alg_cnt, algs_size, i;
1592 	__le16 *algs;
1593 
1594 	if (sizeof(struct smb2_neg_context) + 10 > ctxt_len) {
1595 		pr_err("Invalid SMB2_COMPRESSION_CAPABILITIES context length\n");
1596 		return STATUS_INVALID_PARAMETER;
1597 	}
1598 
1599 	conn->compress_algorithm = SMB3_COMPRESS_NONE;
1600 	conn->compress_chained = false;
1601 	conn->compress_pattern = false;
1602 
1603 	alg_cnt = le16_to_cpu(pneg_ctxt->CompressionAlgorithmCount);
1604 	if (!alg_cnt)
1605 		return STATUS_INVALID_PARAMETER;
1606 
1607 	if (pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE &&
1608 	    pneg_ctxt->Flags != SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED)
1609 		return STATUS_INVALID_PARAMETER;
1610 
1611 	algs_size = alg_cnt * sizeof(__le16);
1612 	if (sizeof(struct smb2_neg_context) + 8 + algs_size > ctxt_len) {
1613 		pr_err("Invalid compression algorithm count(%d)\n", alg_cnt);
1614 		return STATUS_INVALID_PARAMETER;
1615 	}
1616 
1617 	/*
1618 	 * CompressionAlgorithms[] is declared as a fixed 4-element array, but
1619 	 * the actual element count is variable (clients such as Windows may
1620 	 * advertise more). The on-wire length was validated above, so walk the
1621 	 * algorithms through a pointer to avoid a fixed-array bounds check.
1622 	 */
1623 	algs = pneg_ctxt->CompressionAlgorithms;
1624 	for (i = 0; i < alg_cnt; i++) {
1625 		__le16 alg = algs[i];
1626 
1627 		/*
1628 		 * LZ77 is the required general-purpose codec. Pattern_V1 is an
1629 		 * optional chained payload type and cannot stand alone.
1630 		 */
1631 		if (alg == SMB3_COMPRESS_LZ77) {
1632 			conn->compress_algorithm = alg;
1633 			conn->compress_chained =
1634 				pneg_ctxt->Flags ==
1635 				SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED;
1636 			ksmbd_debug(SMB, "Compression Algorithm ID = 0x%x\n",
1637 				    le16_to_cpu(alg));
1638 		} else if (alg == SMB3_COMPRESS_PATTERN) {
1639 			conn->compress_pattern = true;
1640 		}
1641 	}
1642 
1643 	if (conn->compress_algorithm == SMB3_COMPRESS_NONE ||
1644 	    !conn->compress_chained)
1645 		conn->compress_pattern = false;
1646 
1647 	return STATUS_SUCCESS;
1648 }
1649 
1650 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
1651 				 struct smb2_signing_capabilities *pneg_ctxt,
1652 				 int ctxt_len)
1653 {
1654 	int sign_algo_cnt;
1655 	int i, sign_alos_size;
1656 
1657 	if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
1658 		pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
1659 		return;
1660 	}
1661 
1662 	conn->signing_negotiated = false;
1663 	sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
1664 	sign_alos_size = sign_algo_cnt * sizeof(__le16);
1665 
1666 	if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
1667 	    ctxt_len) {
1668 		pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
1669 		return;
1670 	}
1671 
1672 	for (i = 0; i < sign_algo_cnt; i++) {
1673 		if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
1674 		    pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
1675 			ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
1676 				    pneg_ctxt->SigningAlgorithms[i]);
1677 			conn->signing_negotiated = true;
1678 			conn->signing_algorithm =
1679 				pneg_ctxt->SigningAlgorithms[i];
1680 			break;
1681 		}
1682 	}
1683 }
1684 
1685 /**
1686  * decode_rdma_ctx() - decode an RDMA transform negotiate request context
1687  * @conn: connection being negotiated
1688  * @ctxt: request context header to decode
1689  * @ctxt_len: total context length, including the negotiate context header
1690  *
1691  * Record transforms supported by both peers only for SMB Direct connections.
1692  *
1693  * Return: NT status describing the decode result
1694  */
1695 static __le32 decode_rdma_ctx(struct ksmbd_conn *conn,
1696 			      struct smb2_neg_context *ctxt, int ctxt_len)
1697 {
1698 	struct smb2_rdma_transform_capabilities_context *pneg_ctxt;
1699 	unsigned int count, i;
1700 
1701 	pneg_ctxt = (void *)ctxt;
1702 	/* RDMA transforms are a node capability, not just a transport capability. */
1703 	if (!ksmbd_rdma_enabled())
1704 		return STATUS_SUCCESS;
1705 
1706 	if (ctxt_len < sizeof(*pneg_ctxt))
1707 		return STATUS_INVALID_PARAMETER;
1708 
1709 	count = le16_to_cpu(pneg_ctxt->TransformCount);
1710 	if (!count || count >
1711 	    (ctxt_len - sizeof(*pneg_ctxt)) / sizeof(__le16))
1712 		return STATUS_INVALID_PARAMETER;
1713 
1714 	conn->rdma_transform_negotiated = true;
1715 	conn->rdma_transform_ids = 0;
1716 	for (i = 0; i < count; i++) {
1717 		u16 id = le16_to_cpu(pneg_ctxt->RDMATransformIds[i]);
1718 
1719 		if (id == SMB2_RDMA_TRANSFORM_ENCRYPTION)
1720 			conn->rdma_transform_ids |= BIT(id);
1721 	}
1722 	return STATUS_SUCCESS;
1723 }
1724 
1725 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
1726 				      struct smb2_negotiate_req *req,
1727 				      unsigned int len_of_smb)
1728 {
1729 	/* +4 is to account for the RFC1001 len field */
1730 	struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
1731 	int i = 0, len_of_ctxts;
1732 	unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
1733 	unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
1734 	__le32 status = STATUS_INVALID_PARAMETER;
1735 	int compress_ctxt_cnt = 0, rdma_transform_ctxt_cnt = 0;
1736 
1737 	ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
1738 	if (len_of_smb <= offset) {
1739 		ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1740 		return status;
1741 	}
1742 
1743 	len_of_ctxts = len_of_smb - offset;
1744 
1745 	while (i++ < neg_ctxt_cnt) {
1746 		int clen, ctxt_len;
1747 
1748 		if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1749 			break;
1750 
1751 		pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1752 		clen = le16_to_cpu(pctx->DataLength);
1753 		ctxt_len = clen + sizeof(struct smb2_neg_context);
1754 
1755 		if (ctxt_len > len_of_ctxts)
1756 			break;
1757 
1758 		if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1759 			ksmbd_debug(SMB,
1760 				    "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1761 			if (conn->preauth_info->Preauth_HashId)
1762 				break;
1763 
1764 			status = decode_preauth_ctxt(conn,
1765 						     (struct smb2_preauth_neg_context *)pctx,
1766 						     ctxt_len);
1767 			if (status != STATUS_SUCCESS)
1768 				break;
1769 		} else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1770 			ksmbd_debug(SMB,
1771 				    "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1772 			if (conn->cipher_type)
1773 				break;
1774 
1775 			decode_encrypt_ctxt(conn,
1776 					    (struct smb2_encryption_neg_context *)pctx,
1777 					    ctxt_len);
1778 		} else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1779 			ksmbd_debug(SMB,
1780 				    "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1781 			if (compress_ctxt_cnt++) {
1782 				status = STATUS_INVALID_PARAMETER;
1783 				break;
1784 			}
1785 
1786 			status = decode_compress_ctxt(conn,
1787 				(struct smb2_compression_capabilities_context *)
1788 				pctx, ctxt_len);
1789 			if (status != STATUS_SUCCESS)
1790 				break;
1791 		} else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1792 			ksmbd_debug(SMB,
1793 				    "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1794 		} else if (pctx->ContextType == SMB2_RDMA_TRANSFORM_CAPABILITIES) {
1795 			ksmbd_debug(SMB,
1796 				    "deassemble SMB2_RDMA_TRANSFORM_CAPABILITIES context\n");
1797 			if (ksmbd_rdma_enabled() &&
1798 			    rdma_transform_ctxt_cnt++) {
1799 				status = STATUS_INVALID_PARAMETER;
1800 				break;
1801 			}
1802 			status = decode_rdma_ctx(conn, pctx, ctxt_len);
1803 			if (status != STATUS_SUCCESS)
1804 				break;
1805 		} else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1806 			ksmbd_debug(SMB,
1807 				    "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1808 			conn->posix_ext_supported = true;
1809 		} else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1810 			ksmbd_debug(SMB,
1811 				    "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1812 
1813 			decode_sign_cap_ctxt(conn,
1814 					     (struct smb2_signing_capabilities *)pctx,
1815 					     ctxt_len);
1816 		}
1817 
1818 		/* offsets must be 8 byte aligned */
1819 		offset = (ctxt_len + 7) & ~0x7;
1820 		len_of_ctxts -= offset;
1821 	}
1822 	return status;
1823 }
1824 
1825 /**
1826  * smb2_handle_negotiate() - handler for smb2 negotiate command
1827  * @work:	smb work containing smb request buffer
1828  *
1829  * The caller holds conn->srv_mutex.
1830  *
1831  * Return:      0
1832  */
1833 int smb2_handle_negotiate(struct ksmbd_work *work)
1834 {
1835 	struct ksmbd_conn *conn = work->conn;
1836 	struct smb2_negotiate_req *req = smb_get_msg(work->request_buf);
1837 	struct smb2_negotiate_rsp *rsp = smb_get_msg(work->response_buf);
1838 	int rc = 0;
1839 	unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1840 	__le32 status;
1841 
1842 	ksmbd_debug(SMB, "Received negotiate request\n");
1843 	conn->need_neg = false;
1844 	smb2_buf_len = get_rfc1002_len(work->request_buf);
1845 	smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1846 	if (smb2_neg_size > smb2_buf_len) {
1847 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1848 		rc = -EINVAL;
1849 		goto err_out;
1850 	}
1851 
1852 	if (req->DialectCount == 0) {
1853 		pr_err("malformed packet\n");
1854 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1855 		rc = -EINVAL;
1856 		goto err_out;
1857 	}
1858 
1859 	if (conn->dialect == SMB311_PROT_ID) {
1860 		unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1861 
1862 		if (smb2_buf_len < nego_ctxt_off) {
1863 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1864 			rc = -EINVAL;
1865 			goto err_out;
1866 		}
1867 
1868 		if (smb2_neg_size > nego_ctxt_off) {
1869 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1870 			rc = -EINVAL;
1871 			goto err_out;
1872 		}
1873 
1874 		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1875 		    nego_ctxt_off) {
1876 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1877 			rc = -EINVAL;
1878 			goto err_out;
1879 		}
1880 	} else {
1881 		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1882 		    smb2_buf_len) {
1883 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1884 			rc = -EINVAL;
1885 			goto err_out;
1886 		}
1887 	}
1888 
1889 	conn->cli_cap = le32_to_cpu(req->Capabilities);
1890 	switch (conn->dialect) {
1891 	case SMB311_PROT_ID:
1892 		conn->preauth_info =
1893 			kzalloc_obj(struct preauth_integrity_info,
1894 				    KSMBD_DEFAULT_GFP);
1895 		if (!conn->preauth_info) {
1896 			rc = -ENOMEM;
1897 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1898 			goto err_out;
1899 		}
1900 
1901 		status = deassemble_neg_contexts(conn, req,
1902 						 get_rfc1002_len(work->request_buf));
1903 		if (status != STATUS_SUCCESS) {
1904 			pr_err("deassemble_neg_contexts error(0x%x)\n",
1905 			       status);
1906 			rsp->hdr.Status = status;
1907 			rc = -EINVAL;
1908 			kfree(conn->preauth_info);
1909 			conn->preauth_info = NULL;
1910 			goto err_out;
1911 		}
1912 		if (!conn->cipher_type)
1913 			conn->rdma_transform_ids &=
1914 				~BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION);
1915 		ksmbd_debug(RDMA,
1916 			    "RDMA transform negotiation: transport=%s context=%s encryption=%s cipher=0x%04x\n",
1917 			    conn->transport->ops->rdma_read ? "rdma" : "tcp",
1918 			    conn->rdma_transform_negotiated ? "present" : "absent",
1919 			    conn->rdma_transform_ids &
1920 			    BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION) ? "enabled" : "disabled",
1921 			    le16_to_cpu(conn->cipher_type));
1922 
1923 		rc = init_smb3_11_server(conn);
1924 		if (rc < 0) {
1925 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1926 			kfree(conn->preauth_info);
1927 			conn->preauth_info = NULL;
1928 			goto err_out;
1929 		}
1930 
1931 		ksmbd_gen_preauth_integrity_hash(conn,
1932 						 work->request_buf,
1933 						 conn->preauth_info->Preauth_HashValue);
1934 		rsp->NegotiateContextOffset =
1935 				cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1936 		neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1937 		break;
1938 	case SMB302_PROT_ID:
1939 		init_smb3_02_server(conn);
1940 		break;
1941 	case SMB30_PROT_ID:
1942 		init_smb3_0_server(conn);
1943 		break;
1944 	case SMB21_PROT_ID:
1945 		init_smb2_1_server(conn);
1946 		break;
1947 	case SMB2X_PROT_ID:
1948 	case BAD_PROT_ID:
1949 	default:
1950 		ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1951 			    conn->dialect);
1952 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1953 		rc = -EINVAL;
1954 		goto err_out;
1955 	}
1956 	rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
1957 
1958 	/* For stats */
1959 	conn->connection_type = conn->dialect;
1960 
1961 	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1962 	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1963 	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1964 
1965 	memcpy(conn->ClientGUID, req->ClientGUID,
1966 			SMB2_CLIENT_GUID_SIZE);
1967 	conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1968 
1969 	rsp->StructureSize = cpu_to_le16(65);
1970 	rsp->DialectRevision = cpu_to_le16(conn->dialect);
1971 	/* Not setting conn guid rsp->ServerGUID, as it
1972 	 * not used by client for identifying server
1973 	 */
1974 	memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1975 
1976 	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1977 	rsp->ServerStartTime = 0;
1978 	ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1979 		    le32_to_cpu(rsp->NegotiateContextOffset),
1980 		    le16_to_cpu(rsp->NegotiateContextCount));
1981 
1982 	rsp->SecurityBufferOffset = cpu_to_le16(128);
1983 	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1984 	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1985 				  le16_to_cpu(rsp->SecurityBufferOffset));
1986 
1987 	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1988 	conn->use_spnego = true;
1989 
1990 	if (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1991 		conn->sign = true;
1992 	if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1993 		server_conf.enforced_signing = true;
1994 		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1995 		conn->sign = true;
1996 	}
1997 
1998 	conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1999 	ksmbd_conn_set_need_setup(conn);
2000 
2001 err_out:
2002 	if (rc && rsp->hdr.Status == STATUS_SUCCESS)
2003 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2004 
2005 	if (!rc)
2006 		rc = ksmbd_iov_pin_rsp(work, rsp,
2007 				       sizeof(struct smb2_negotiate_rsp) +
2008 					AUTH_GSS_LENGTH + neg_ctxt_len);
2009 	if (rc < 0)
2010 		smb2_set_err_rsp(work);
2011 	return rc;
2012 }
2013 
2014 static int alloc_preauth_hash(struct ksmbd_session *sess,
2015 			      struct ksmbd_conn *conn)
2016 {
2017 	if (sess->Preauth_HashValue)
2018 		return 0;
2019 
2020 	if (!conn->preauth_info)
2021 		return -ENOMEM;
2022 
2023 	sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
2024 					  PREAUTH_HASHVALUE_SIZE, KSMBD_DEFAULT_GFP);
2025 	if (!sess->Preauth_HashValue)
2026 		return -ENOMEM;
2027 
2028 	return 0;
2029 }
2030 
2031 static int generate_preauth_hash(struct ksmbd_work *work)
2032 {
2033 	struct ksmbd_conn *conn = work->conn;
2034 	struct ksmbd_session *sess = work->sess;
2035 	u8 *preauth_hash;
2036 
2037 	if (conn->dialect != SMB311_PROT_ID)
2038 		return 0;
2039 
2040 	if (conn->binding) {
2041 		struct preauth_session *preauth_sess;
2042 
2043 		preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
2044 		if (!preauth_sess) {
2045 			preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
2046 			if (!preauth_sess)
2047 				return -ENOMEM;
2048 		}
2049 
2050 		preauth_hash = preauth_sess->Preauth_HashValue;
2051 	} else {
2052 		if (!sess->Preauth_HashValue)
2053 			if (alloc_preauth_hash(sess, conn))
2054 				return -ENOMEM;
2055 		preauth_hash = sess->Preauth_HashValue;
2056 	}
2057 
2058 	ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
2059 	return 0;
2060 }
2061 
2062 static int decode_negotiation_token(struct ksmbd_conn *conn,
2063 				    struct negotiate_message *negblob,
2064 				    size_t sz)
2065 {
2066 	if (!conn->use_spnego)
2067 		return -EINVAL;
2068 
2069 	if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
2070 		if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
2071 			conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
2072 			conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
2073 			conn->use_spnego = false;
2074 		}
2075 	}
2076 	return 0;
2077 }
2078 
2079 static int ntlm_negotiate(struct ksmbd_work *work,
2080 			  struct negotiate_message *negblob,
2081 			  size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
2082 {
2083 	struct challenge_message *chgblob;
2084 	unsigned char *spnego_blob = NULL;
2085 	u16 spnego_blob_len;
2086 	char *neg_blob;
2087 	int sz, rc;
2088 
2089 	ksmbd_debug(SMB, "negotiate phase\n");
2090 	rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
2091 	if (rc)
2092 		return rc;
2093 
2094 	sz = le16_to_cpu(rsp->SecurityBufferOffset);
2095 	chgblob = (struct challenge_message *)rsp->Buffer;
2096 	memset(chgblob, 0, sizeof(struct challenge_message));
2097 
2098 	if (!work->conn->use_spnego) {
2099 		sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
2100 		if (sz < 0)
2101 			return -ENOMEM;
2102 
2103 		rsp->SecurityBufferLength = cpu_to_le16(sz);
2104 		return 0;
2105 	}
2106 
2107 	sz = sizeof(struct challenge_message);
2108 	sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
2109 
2110 	neg_blob = kzalloc(sz, KSMBD_DEFAULT_GFP);
2111 	if (!neg_blob)
2112 		return -ENOMEM;
2113 
2114 	chgblob = (struct challenge_message *)neg_blob;
2115 	sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
2116 	if (sz < 0) {
2117 		rc = -ENOMEM;
2118 		goto out;
2119 	}
2120 
2121 	rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
2122 					   neg_blob, sz);
2123 	if (rc) {
2124 		rc = -ENOMEM;
2125 		goto out;
2126 	}
2127 
2128 	memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
2129 	rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
2130 
2131 out:
2132 	kfree(spnego_blob);
2133 	kfree(neg_blob);
2134 	return rc;
2135 }
2136 
2137 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
2138 						  struct smb2_sess_setup_req *req)
2139 {
2140 	int sz;
2141 
2142 	if (conn->use_spnego && conn->mechToken)
2143 		return (struct authenticate_message *)conn->mechToken;
2144 
2145 	sz = le16_to_cpu(req->SecurityBufferOffset);
2146 	return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
2147 					       + sz);
2148 }
2149 
2150 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
2151 				       struct smb2_sess_setup_req *req)
2152 {
2153 	struct authenticate_message *authblob;
2154 	struct ksmbd_user *user;
2155 	char *name;
2156 	unsigned int name_off, name_len, secbuf_len;
2157 
2158 	if (conn->use_spnego && conn->mechToken)
2159 		secbuf_len = conn->mechTokenLen;
2160 	else
2161 		secbuf_len = le16_to_cpu(req->SecurityBufferLength);
2162 	if (secbuf_len < sizeof(struct authenticate_message)) {
2163 		ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
2164 		return NULL;
2165 	}
2166 	authblob = user_authblob(conn, req);
2167 	name_off = le32_to_cpu(authblob->UserName.BufferOffset);
2168 	name_len = le16_to_cpu(authblob->UserName.Length);
2169 
2170 	if (secbuf_len < (u64)name_off + name_len)
2171 		return NULL;
2172 
2173 	name = smb_strndup_from_utf16((const char *)authblob + name_off,
2174 				      name_len,
2175 				      true,
2176 				      conn->local_nls);
2177 	if (IS_ERR(name)) {
2178 		pr_err("cannot allocate memory\n");
2179 		return NULL;
2180 	}
2181 
2182 	ksmbd_debug(SMB, "session setup request for user %s\n", name);
2183 	user = ksmbd_login_user(name);
2184 	kfree(name);
2185 	return user;
2186 }
2187 
2188 static int ntlm_authenticate(struct ksmbd_work *work,
2189 			     struct smb2_sess_setup_req *req,
2190 			     struct smb2_sess_setup_rsp *rsp)
2191 {
2192 	struct ksmbd_conn *conn = work->conn;
2193 	struct ksmbd_session *sess = work->sess;
2194 	struct ksmbd_user *user;
2195 	char channel_key[CIFS_KEY_SIZE] = {};
2196 	char *auth_key = conn->binding ? channel_key : sess->sess_key;
2197 	u64 prev_id;
2198 	bool binding = conn->binding;
2199 	int sz, rc;
2200 
2201 	ksmbd_debug(SMB, "authenticate phase\n");
2202 	if (conn->use_spnego) {
2203 		unsigned char *spnego_blob;
2204 		u16 spnego_blob_len;
2205 
2206 		rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
2207 						    &spnego_blob_len,
2208 						    0);
2209 		if (rc)
2210 			return -ENOMEM;
2211 
2212 		memcpy(rsp->Buffer, spnego_blob, spnego_blob_len);
2213 		rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
2214 		kfree(spnego_blob);
2215 	}
2216 
2217 	user = session_user(conn, req);
2218 	if (!user) {
2219 		ksmbd_debug(SMB, "Unknown user name or an error\n");
2220 		return -EPERM;
2221 	}
2222 
2223 	if (sess->state == SMB2_SESSION_VALID) {
2224 		/*
2225 		 * Reuse session if anonymous try to connect
2226 		 * on reauthetication.
2227 		 */
2228 		if (conn->binding == false && ksmbd_anonymous_user(user)) {
2229 			ksmbd_free_user(user);
2230 			return 0;
2231 		}
2232 
2233 		if (!ksmbd_compare_user(sess->user, user)) {
2234 			ksmbd_free_user(user);
2235 			return -EKEYREJECTED;
2236 		}
2237 		ksmbd_free_user(user);
2238 	} else {
2239 		sess->user = user;
2240 	}
2241 
2242 	if (conn->binding == false && user_guest(sess->user)) {
2243 		rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
2244 	} else {
2245 		struct authenticate_message *authblob;
2246 
2247 		authblob = user_authblob(conn, req);
2248 		if (conn->use_spnego && conn->mechToken)
2249 			sz = conn->mechTokenLen;
2250 		else
2251 			sz = le16_to_cpu(req->SecurityBufferLength);
2252 		rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess,
2253 						    auth_key);
2254 		if (rc) {
2255 			set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
2256 			ksmbd_debug(SMB, "authentication failed\n");
2257 			rc = -EPERM;
2258 			goto out;
2259 		}
2260 	}
2261 
2262 	prev_id = le64_to_cpu(req->PreviousSessionId);
2263 	if (prev_id && prev_id != sess->id)
2264 		destroy_previous_session(conn, sess->user, prev_id);
2265 
2266 	/*
2267 	 * If session state is SMB2_SESSION_VALID, We can assume
2268 	 * that it is reauthentication. And the user/password
2269 	 * has been verified, so return it here.
2270 	 */
2271 	if (sess->state == SMB2_SESSION_VALID) {
2272 		if (conn->binding)
2273 			goto binding_session;
2274 		return 0;
2275 	}
2276 
2277 	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
2278 	     (conn->sign || server_conf.enforced_signing)) ||
2279 	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
2280 		sess->sign = true;
2281 
2282 	if (smb3_encryption_negotiated(conn) &&
2283 			!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2284 		conn->ops->generate_encryptionkey(conn, sess);
2285 		sess->enc = true;
2286 		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
2287 			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
2288 		/*
2289 		 * signing is disable if encryption is enable
2290 		 * on this session
2291 		 */
2292 		sess->sign = false;
2293 	}
2294 
2295 binding_session:
2296 	if (conn->dialect >= SMB30_PROT_ID) {
2297 		rc = register_session_channel(sess, conn, auth_key);
2298 		if (rc)
2299 			goto out;
2300 	}
2301 
2302 	if (conn->ops->generate_signingkey) {
2303 		rc = conn->ops->generate_signingkey(sess, conn);
2304 		if (rc) {
2305 			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
2306 			rc = -EINVAL;
2307 			goto out;
2308 		}
2309 	}
2310 
2311 	if (!ksmbd_conn_lookup_dialect(conn)) {
2312 		pr_err("fail to verify the dialect\n");
2313 		rc = -ENOENT;
2314 		goto out;
2315 	}
2316 	rc = 0;
2317 out:
2318 	if (binding)
2319 		memzero_explicit(channel_key, sizeof(channel_key));
2320 	return rc;
2321 }
2322 
2323 #ifdef CONFIG_SMB_SERVER_KERBEROS5
2324 static int krb5_authenticate(struct ksmbd_work *work,
2325 			     struct smb2_sess_setup_req *req,
2326 			     struct smb2_sess_setup_rsp *rsp)
2327 {
2328 	struct ksmbd_conn *conn = work->conn;
2329 	struct ksmbd_session *sess = work->sess;
2330 	char *in_blob, *out_blob;
2331 	char channel_key[CIFS_KEY_SIZE] = {};
2332 	char reauth_key[CIFS_KEY_SIZE] = {};
2333 	char *auth_key = conn->binding ? channel_key :
2334 		(work->session_setup_reauth ? reauth_key : sess->sess_key);
2335 	u64 prev_sess_id;
2336 	bool binding = conn->binding;
2337 	int in_len, out_len;
2338 	int retval;
2339 
2340 	in_blob = (char *)&req->hdr.ProtocolId +
2341 		le16_to_cpu(req->SecurityBufferOffset);
2342 	in_len = le16_to_cpu(req->SecurityBufferLength);
2343 	out_blob = (char *)&rsp->hdr.ProtocolId +
2344 		le16_to_cpu(rsp->SecurityBufferOffset);
2345 	out_len = work->response_sz - work->next_smb2_rsp_hdr_off -
2346 		(le16_to_cpu(rsp->SecurityBufferOffset) + 4);
2347 
2348 	retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
2349 					 out_blob, &out_len, auth_key);
2350 	if (retval) {
2351 		ksmbd_debug(SMB, "krb5 authentication failed\n");
2352 		if (retval != -EKEYREJECTED)
2353 			retval = -EPERM;
2354 		goto out;
2355 	}
2356 
2357 	/* Check previous session */
2358 	prev_sess_id = le64_to_cpu(req->PreviousSessionId);
2359 	if (prev_sess_id && prev_sess_id != sess->id)
2360 		destroy_previous_session(conn, sess->user, prev_sess_id);
2361 
2362 	rsp->SecurityBufferLength = cpu_to_le16(out_len);
2363 
2364 	/*
2365 	 * If session state is SMB2_SESSION_VALID, We can assume
2366 	 * that it is reauthentication. And the user/password
2367 	 * has been verified, so return it here.
2368 	 */
2369 	if (sess->state == SMB2_SESSION_VALID && !work->session_setup_reauth) {
2370 		if (conn->binding)
2371 			goto binding_session;
2372 		return 0;
2373 	}
2374 
2375 	/*
2376 	 * Reauthentication verifies the new Kerberos credentials but keeps
2377 	 * the established SMB session keys.
2378 	 */
2379 	if (work->session_setup_reauth) {
2380 		retval = 0;
2381 		goto out;
2382 	}
2383 
2384 	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
2385 	    (conn->sign || server_conf.enforced_signing)) ||
2386 	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
2387 		sess->sign = true;
2388 
2389 	if (smb3_encryption_negotiated(conn) &&
2390 	    !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2391 		conn->ops->generate_encryptionkey(conn, sess);
2392 		sess->enc = true;
2393 		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
2394 			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
2395 		sess->sign = false;
2396 	}
2397 
2398 binding_session:
2399 	if (conn->dialect >= SMB30_PROT_ID) {
2400 		retval = register_session_channel(sess, conn, auth_key);
2401 		if (retval)
2402 			goto out;
2403 	}
2404 
2405 	if (conn->ops->generate_signingkey) {
2406 		retval = conn->ops->generate_signingkey(sess, conn);
2407 		if (retval) {
2408 			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
2409 			retval = -EINVAL;
2410 			goto out;
2411 		}
2412 	}
2413 
2414 	if (!ksmbd_conn_lookup_dialect(conn)) {
2415 		pr_err("fail to verify the dialect\n");
2416 		retval = -ENOENT;
2417 		goto out;
2418 	}
2419 	retval = 0;
2420 out:
2421 	memzero_explicit(reauth_key, sizeof(reauth_key));
2422 	if (binding)
2423 		memzero_explicit(channel_key, sizeof(channel_key));
2424 	return retval;
2425 }
2426 #else
2427 static int krb5_authenticate(struct ksmbd_work *work,
2428 			     struct smb2_sess_setup_req *req,
2429 			     struct smb2_sess_setup_rsp *rsp)
2430 {
2431 	return -EOPNOTSUPP;
2432 }
2433 #endif
2434 
2435 int smb2_sess_setup(struct ksmbd_work *work)
2436 {
2437 	struct ksmbd_conn *conn = work->conn;
2438 	struct smb2_sess_setup_req *req;
2439 	struct smb2_sess_setup_rsp *rsp;
2440 	struct ksmbd_session *sess = NULL;
2441 	struct negotiate_message *negblob;
2442 	unsigned int negblob_len, negblob_off;
2443 	int rc = 0;
2444 
2445 	ksmbd_debug(SMB, "Received smb2 session setup request\n");
2446 
2447 	if (!ksmbd_conn_need_setup(conn) && !ksmbd_conn_good(conn)) {
2448 		work->send_no_response = 1;
2449 		return rc;
2450 	}
2451 
2452 	WORK_BUFFERS(work, req, rsp);
2453 
2454 	rsp->StructureSize = cpu_to_le16(9);
2455 	rsp->SessionFlags = 0;
2456 	rsp->SecurityBufferOffset = cpu_to_le16(72);
2457 	rsp->SecurityBufferLength = 0;
2458 
2459 	ksmbd_conn_lock(conn);
2460 	if (!req->hdr.SessionId) {
2461 		sess = ksmbd_smb2_session_create();
2462 		if (!sess) {
2463 			rc = -ENOMEM;
2464 			goto out_err;
2465 		}
2466 		rsp->hdr.SessionId = cpu_to_le64(sess->id);
2467 		rc = ksmbd_session_register(conn, sess);
2468 		if (rc)
2469 			goto out_err;
2470 
2471 		conn->binding = false;
2472 	} else if (conn->dialect >= SMB30_PROT_ID &&
2473 		   (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
2474 		   req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
2475 		u64 sess_id = le64_to_cpu(req->hdr.SessionId);
2476 
2477 		sess = ksmbd_session_lookup_slowpath(sess_id);
2478 		if (!sess) {
2479 			rc = -ENOENT;
2480 			goto out_err;
2481 		}
2482 
2483 		if (conn->dialect != sess->dialect) {
2484 			rc = -EINVAL;
2485 			goto out_err;
2486 		}
2487 
2488 		if (conn->dialect == SMB311_PROT_ID) {
2489 			struct channel *chann;
2490 			unsigned long index;
2491 
2492 			down_read(&sess->chann_lock);
2493 			xa_for_each(&sess->ksmbd_chann_list, index, chann) {
2494 				if (conn->cipher_type != chann->conn->cipher_type)
2495 					rc = -EINVAL;
2496 				break;
2497 			}
2498 			up_read(&sess->chann_lock);
2499 			if (rc)
2500 				goto out_err;
2501 		}
2502 
2503 		if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
2504 			rc = -EINVAL;
2505 			goto out_err;
2506 		}
2507 
2508 		if (memcmp(conn->ClientGUID, sess->ClientGUID,
2509 			    SMB2_CLIENT_GUID_SIZE)) {
2510 			rc = -ENOENT;
2511 			goto out_err;
2512 		}
2513 
2514 		if (sess->state == SMB2_SESSION_IN_PROGRESS) {
2515 			rc = -EACCES;
2516 			goto out_err;
2517 		}
2518 
2519 		if (sess->state == SMB2_SESSION_EXPIRED) {
2520 			rc = -EFAULT;
2521 			goto out_err;
2522 		}
2523 
2524 		if (ksmbd_conn_need_reconnect(conn)) {
2525 			rc = -EFAULT;
2526 			ksmbd_user_session_put(sess);
2527 			sess = NULL;
2528 			goto out_err;
2529 		}
2530 
2531 		if (is_ksmbd_session_in_connection(conn, sess_id)) {
2532 			rc = -EACCES;
2533 			goto out_err;
2534 		}
2535 
2536 		if (user_guest(sess->user)) {
2537 			rc = -EOPNOTSUPP;
2538 			goto out_err;
2539 		}
2540 
2541 		conn->binding = true;
2542 	} else if ((conn->dialect < SMB30_PROT_ID ||
2543 		    server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
2544 		   (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2545 		sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId));
2546 		if (sess) {
2547 			int sign_ret;
2548 
2549 			work->sess = sess;
2550 			if (sess->dialect >= SMB30_PROT_ID)
2551 				sign_ret = smb3_check_sign_req(work);
2552 			else
2553 				sign_ret = smb2_check_sign_req(work);
2554 			if (sess->state != SMB2_SESSION_VALID ||
2555 			    !(req->hdr.Flags & SMB2_FLAGS_SIGNED) ||
2556 			    !sign_ret) {
2557 				ksmbd_user_session_put(sess);
2558 				work->sess = NULL;
2559 				sess = NULL;
2560 			}
2561 		}
2562 		rc = -EACCES;
2563 		goto out_err;
2564 	} else {
2565 		sess = ksmbd_session_lookup(conn,
2566 					    le64_to_cpu(req->hdr.SessionId));
2567 		if (!sess) {
2568 			sess = ksmbd_session_lookup_slowpath(le64_to_cpu(req->hdr.SessionId));
2569 			if (sess && !lookup_chann_list(sess, conn)) {
2570 				ksmbd_user_session_put(sess);
2571 				sess = NULL;
2572 			}
2573 		}
2574 		if (!sess) {
2575 			rc = -ENOENT;
2576 			goto out_err;
2577 		}
2578 
2579 		if (sess->state == SMB2_SESSION_EXPIRED) {
2580 			if (sess->kerberos_expiry &&
2581 			    ktime_get_real_seconds() >= sess->kerberos_expiry) {
2582 				work->session_setup_reauth = true;
2583 			} else {
2584 				rc = -EFAULT;
2585 				goto out_err;
2586 			}
2587 		}
2588 
2589 		if (ksmbd_conn_need_reconnect(conn)) {
2590 			rc = -EFAULT;
2591 			ksmbd_user_session_put(sess);
2592 			sess = NULL;
2593 			goto out_err;
2594 		}
2595 
2596 		if (work->session_setup_reauth)
2597 			WRITE_ONCE(sess->state, SMB2_SESSION_IN_PROGRESS);
2598 
2599 		conn->binding = false;
2600 	}
2601 	work->sess = sess;
2602 
2603 	negblob_off = le16_to_cpu(req->SecurityBufferOffset);
2604 	negblob_len = le16_to_cpu(req->SecurityBufferLength);
2605 	if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) {
2606 		rc = -EINVAL;
2607 		goto out_err;
2608 	}
2609 
2610 	negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
2611 			negblob_off);
2612 
2613 	if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
2614 		if (conn->mechToken) {
2615 			negblob = (struct negotiate_message *)conn->mechToken;
2616 			negblob_len = conn->mechTokenLen;
2617 		}
2618 	}
2619 
2620 	if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
2621 		rc = -EINVAL;
2622 		goto out_err;
2623 	}
2624 
2625 	if (server_conf.auth_mechs & conn->auth_mechs) {
2626 		rc = generate_preauth_hash(work);
2627 		if (rc)
2628 			goto out_err;
2629 
2630 		if (conn->preferred_auth_mech &
2631 				(KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
2632 			rc = krb5_authenticate(work, req, rsp);
2633 			if (rc)
2634 				goto out_err;
2635 
2636 			if (!ksmbd_conn_need_reconnect(conn)) {
2637 				ksmbd_conn_set_good(conn);
2638 				sess->state = SMB2_SESSION_VALID;
2639 			}
2640 		} else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
2641 			if (negblob->MessageType == NtLmNegotiate) {
2642 				rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
2643 				if (rc)
2644 					goto out_err;
2645 				rsp->hdr.Status =
2646 					STATUS_MORE_PROCESSING_REQUIRED;
2647 			} else if (negblob->MessageType == NtLmAuthenticate) {
2648 				rc = ntlm_authenticate(work, req, rsp);
2649 				if (rc)
2650 					goto out_err;
2651 
2652 				if (!ksmbd_conn_need_reconnect(conn)) {
2653 					ksmbd_conn_set_good(conn);
2654 					sess->state = SMB2_SESSION_VALID;
2655 				}
2656 				if (conn->binding) {
2657 					struct preauth_session *preauth_sess;
2658 
2659 					preauth_sess =
2660 						ksmbd_preauth_session_lookup(conn, sess->id);
2661 					if (preauth_sess) {
2662 						list_del(&preauth_sess->preauth_entry);
2663 						kfree_sensitive(preauth_sess);
2664 					}
2665 				}
2666 			} else {
2667 				pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
2668 						le32_to_cpu(negblob->MessageType));
2669 				rc = -EINVAL;
2670 			}
2671 		} else {
2672 			/* TODO: need one more negotiation */
2673 			pr_err("Not support the preferred authentication\n");
2674 			rc = -EINVAL;
2675 		}
2676 	} else {
2677 		pr_err("Not support authentication\n");
2678 		rc = -EINVAL;
2679 	}
2680 
2681 out_err:
2682 	if (rc == -EINVAL)
2683 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2684 	else if (rc == -ENOENT)
2685 		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
2686 	else if (rc == -EACCES)
2687 		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
2688 	else if (rc == -EFAULT)
2689 		rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
2690 	else if (rc == -ENOMEM || rc == -ENOSPC)
2691 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2692 	else if (rc == -EOPNOTSUPP)
2693 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
2694 	else if (rc == -EKEYREJECTED)
2695 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2696 	else if (rc)
2697 		rsp->hdr.Status = STATUS_LOGON_FAILURE;
2698 	if ((rsp->hdr.Status == STATUS_USER_SESSION_DELETED ||
2699 	     (rsp->hdr.Status == STATUS_INVALID_PARAMETER &&
2700 	      (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING))) &&
2701 	    (req->hdr.Flags & SMB2_FLAGS_SIGNED))
2702 		rsp->hdr.Flags |= SMB2_FLAGS_SIGNED;
2703 
2704 	if (conn->mechToken) {
2705 		kfree(conn->mechToken);
2706 		conn->mechToken = NULL;
2707 	}
2708 
2709 	if (rc < 0) {
2710 		bool setup_in_progress = sess &&
2711 			READ_ONCE(sess->state) == SMB2_SESSION_IN_PROGRESS &&
2712 			!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING);
2713 
2714 		/* Authentication errors must not leave the new session published. */
2715 		if (setup_in_progress)
2716 			ksmbd_session_unregister(conn, sess);
2717 
2718 		if (sess && conn->dialect == SMB311_PROT_ID &&
2719 		    (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
2720 			struct preauth_session *preauth_sess;
2721 
2722 			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
2723 			if (preauth_sess) {
2724 				list_del(&preauth_sess->preauth_entry);
2725 				kfree_sensitive(preauth_sess);
2726 			}
2727 		}
2728 
2729 		/*
2730 		 * SecurityBufferOffset should be set to zero
2731 		 * in session setup error response.
2732 		 */
2733 		rsp->SecurityBufferOffset = 0;
2734 
2735 		if (sess) {
2736 			bool try_delay = false;
2737 
2738 			/*
2739 			 * To avoid dictionary attacks (repeated session setups rapidly sent) to
2740 			 * connect to server, ksmbd make a delay of a 5 seconds on session setup
2741 			 * failure to make it harder to send enough random connection requests
2742 			 * to break into a server.
2743 			 */
2744 			if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
2745 				try_delay = true;
2746 
2747 			/*
2748 			 * For binding requests, session belongs to another
2749 			 * connection. Do not expire it.
2750 			 */
2751 			if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) &&
2752 			    !setup_in_progress) {
2753 				sess->last_active = jiffies;
2754 				sess->kerberos_expiry = 0;
2755 				sess->state = SMB2_SESSION_EXPIRED;
2756 			}
2757 			/*
2758 			 * Keep the binding session reference until the response is
2759 			 * signed and sent.  Error responses for a signed binding
2760 			 * request are signed with the existing session signing key.
2761 			 */
2762 			if (!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) ||
2763 			    work->sess != sess) {
2764 				ksmbd_user_session_put(sess);
2765 				work->sess = NULL;
2766 			}
2767 			if (try_delay) {
2768 				ksmbd_conn_set_need_reconnect(conn);
2769 				ssleep(5);
2770 				ksmbd_conn_set_need_setup(conn);
2771 			}
2772 		}
2773 		smb2_set_err_rsp(work);
2774 		conn->binding = false;
2775 	} else {
2776 		unsigned int iov_len;
2777 
2778 		if (rsp->SecurityBufferLength)
2779 			iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
2780 				le16_to_cpu(rsp->SecurityBufferLength);
2781 		else
2782 			iov_len = sizeof(struct smb2_sess_setup_rsp);
2783 		rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
2784 		if (rc)
2785 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2786 	}
2787 
2788 	ksmbd_conn_unlock(conn);
2789 	return rc;
2790 }
2791 
2792 /**
2793  * smb2_tree_connect() - handler for smb2 tree connect command
2794  * @work:	smb work containing smb request buffer
2795  *
2796  * Return:      0 on success, otherwise error
2797  */
2798 int smb2_tree_connect(struct ksmbd_work *work)
2799 {
2800 	struct ksmbd_conn *conn = work->conn;
2801 	struct smb2_tree_connect_req *req;
2802 	struct smb2_tree_connect_rsp *rsp;
2803 	struct ksmbd_session *sess = work->sess;
2804 	char *treename = NULL, *name = NULL;
2805 	struct ksmbd_tree_conn_status status;
2806 	struct ksmbd_tree_connect *tree_conn = NULL;
2807 	struct ksmbd_share_config *share = NULL;
2808 	int rc = -EINVAL;
2809 
2810 	ksmbd_debug(SMB, "Received smb2 tree connect request\n");
2811 
2812 	WORK_BUFFERS(work, req, rsp);
2813 
2814 	treename = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->PathOffset),
2815 					  le16_to_cpu(req->PathLength), true,
2816 					  conn->local_nls);
2817 	if (IS_ERR(treename)) {
2818 		pr_err("treename is NULL\n");
2819 		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2820 		goto out_err1;
2821 	}
2822 
2823 	name = ksmbd_extract_sharename(conn->um, treename);
2824 	if (IS_ERR(name)) {
2825 		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2826 		goto out_err1;
2827 	}
2828 
2829 	ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
2830 		    name, treename);
2831 
2832 	status = ksmbd_tree_conn_connect(work, name);
2833 	if (status.ret == KSMBD_TREE_CONN_STATUS_OK) {
2834 		tree_conn = status.tree_conn;
2835 		rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
2836 		share = status.tree_conn->share_conf;
2837 
2838 		/* A share that requires encryption needs a negotiated SMB3 cipher. */
2839 		if (test_share_config_flag(share, KSMBD_SHARE_FLAG_ENCRYPT_DATA) &&
2840 		    !smb3_encryption_negotiated(conn)) {
2841 			ksmbd_tree_conn_disconnect(sess, status.tree_conn);
2842 			status.tree_conn = NULL;
2843 			share = NULL;
2844 			status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2845 			goto out_err1;
2846 		}
2847 	} else
2848 		goto out_err1;
2849 
2850 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2851 		ksmbd_debug(SMB, "IPC share path request\n");
2852 		rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
2853 		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2854 			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
2855 			FILE_DELETE_LE | FILE_READ_CONTROL_LE |
2856 			FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2857 			FILE_SYNCHRONIZE_LE;
2858 	} else {
2859 		rsp->ShareType = SMB2_SHARE_TYPE_DISK;
2860 		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
2861 			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
2862 		if (test_tree_conn_flag(status.tree_conn,
2863 					KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2864 			rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
2865 				FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
2866 				FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
2867 				FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
2868 				FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
2869 				FILE_SYNCHRONIZE_LE;
2870 		}
2871 	}
2872 
2873 	status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2874 	if (conn->posix_ext_supported)
2875 		status.tree_conn->posix_extensions = true;
2876 
2877 	down_write(&sess->tree_conns_lock);
2878 	if (status.tree_conn->t_state == TREE_DISCONNECTED) {
2879 		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
2880 		share = NULL;
2881 	} else {
2882 		status.tree_conn->t_state = TREE_CONNECTED;
2883 	}
2884 	up_write(&sess->tree_conns_lock);
2885 	if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2886 		goto out_err1;
2887 	rsp->StructureSize = cpu_to_le16(16);
2888 out_err1:
2889 	/*
2890 	 * A configured CA share is not continuously available until persistent
2891 	 * open recovery, ownership fencing, and failover are implemented.
2892 	 */
2893 	rsp->Capabilities = 0;
2894 	rsp->Reserved = 0;
2895 	/* default manual caching */
2896 	rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2897 	/* Tell the client that READ requests may request compressed responses. */
2898 	if (conn->dialect == SMB311_PROT_ID &&
2899 	    conn->compress_algorithm != SMB3_COMPRESS_NONE)
2900 		rsp->ShareFlags |= cpu_to_le32(SMB2_SHAREFLAG_COMPRESS_DATA);
2901 	if (share && test_share_config_flag(share,
2902 					    KSMBD_SHARE_FLAG_HIDE_UNREADABLE))
2903 		rsp->ShareFlags |=
2904 			cpu_to_le32(SMB2_SHAREFLAG_ACCESS_BASED_DIRECTORY_ENUM);
2905 	if (share && test_share_config_flag(share,
2906 					    KSMBD_SHARE_FLAG_ENCRYPT_DATA))
2907 		rsp->ShareFlags |=
2908 			cpu_to_le32(SMB2_SHAREFLAG_ENCRYPT_DATA);
2909 
2910 	rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2911 	if (rc) {
2912 		if (status.ret == KSMBD_TREE_CONN_STATUS_OK) {
2913 			ksmbd_tree_conn_disconnect(sess, status.tree_conn);
2914 			status.tree_conn = NULL;
2915 		}
2916 		status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2917 	}
2918 
2919 	if (!IS_ERR(treename))
2920 		kfree(treename);
2921 	if (!IS_ERR(name))
2922 		kfree(name);
2923 
2924 	switch (status.ret) {
2925 	case KSMBD_TREE_CONN_STATUS_OK:
2926 		rsp->hdr.Status = STATUS_SUCCESS;
2927 		rc = 0;
2928 		break;
2929 	case -ESTALE:
2930 	case -ENOENT:
2931 	case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2932 		rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2933 		break;
2934 	case -ENOMEM:
2935 	case KSMBD_TREE_CONN_STATUS_NOMEM:
2936 		rsp->hdr.Status = STATUS_NO_MEMORY;
2937 		break;
2938 	case KSMBD_TREE_CONN_STATUS_ERROR:
2939 	case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2940 	case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2941 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2942 		break;
2943 	case -EINVAL:
2944 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2945 		break;
2946 	default:
2947 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2948 	}
2949 
2950 	if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2951 		smb2_set_err_rsp(work);
2952 
2953 	if (tree_conn)
2954 		ksmbd_tree_connect_put(tree_conn);
2955 
2956 	return rc;
2957 }
2958 
2959 /**
2960  * smb2_create_open_flags() - convert smb open flags to unix open flags
2961  * @file_present:	is file already present
2962  * @access:		file access flags
2963  * @disposition:	file disposition flags
2964  * @may_flags:		set with MAY_ flags
2965  * @coptions:		file creation options
2966  * @mode:		file mode
2967  *
2968  * Return:      file open flags
2969  */
2970 static int smb2_create_open_flags(bool file_present, __le32 access,
2971 				  __le32 disposition,
2972 				  int *may_flags,
2973 				  __le32 coptions,
2974 				  umode_t mode)
2975 {
2976 	int oflags = O_NONBLOCK | O_LARGEFILE;
2977 
2978 	if (coptions & FILE_DIRECTORY_FILE_LE || S_ISDIR(mode)) {
2979 		access &= ~FILE_WRITE_DESIRE_ACCESS_LE;
2980 		ksmbd_debug(SMB, "Discard write access to a directory\n");
2981 	}
2982 
2983 	if (access & FILE_READ_DESIRED_ACCESS_LE &&
2984 	    access & FILE_WRITE_DESIRE_ACCESS_LE) {
2985 		oflags |= O_RDWR;
2986 		*may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2987 	} else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2988 		oflags |= O_WRONLY;
2989 		*may_flags = MAY_OPEN | MAY_WRITE;
2990 	} else {
2991 		oflags |= O_RDONLY;
2992 		*may_flags = MAY_OPEN | MAY_READ;
2993 	}
2994 
2995 	if (access == FILE_READ_ATTRIBUTES_LE || S_ISBLK(mode) || S_ISCHR(mode))
2996 		oflags |= O_PATH;
2997 
2998 	if (file_present) {
2999 		switch (disposition & FILE_CREATE_MASK_LE) {
3000 		case FILE_OPEN_LE:
3001 		case FILE_CREATE_LE:
3002 			break;
3003 		case FILE_SUPERSEDE_LE:
3004 		case FILE_OVERWRITE_LE:
3005 		case FILE_OVERWRITE_IF_LE:
3006 			oflags |= O_TRUNC;
3007 			break;
3008 		default:
3009 			break;
3010 		}
3011 	} else {
3012 		switch (disposition & FILE_CREATE_MASK_LE) {
3013 		case FILE_SUPERSEDE_LE:
3014 		case FILE_CREATE_LE:
3015 		case FILE_OPEN_IF_LE:
3016 		case FILE_OVERWRITE_IF_LE:
3017 			oflags |= O_CREAT;
3018 			break;
3019 		case FILE_OPEN_LE:
3020 		case FILE_OVERWRITE_LE:
3021 			oflags &= ~O_CREAT;
3022 			break;
3023 		default:
3024 			break;
3025 		}
3026 	}
3027 
3028 	return oflags;
3029 }
3030 
3031 /**
3032  * smb2_tree_disconnect() - handler for smb tree connect request
3033  * @work:	smb work containing request buffer
3034  *
3035  * Return:      0 on success, otherwise error
3036  */
3037 int smb2_tree_disconnect(struct ksmbd_work *work)
3038 {
3039 	struct smb2_tree_disconnect_rsp *rsp;
3040 	struct smb2_tree_disconnect_req *req;
3041 	struct ksmbd_session *sess = work->sess;
3042 	struct ksmbd_tree_connect *tcon = work->tcon;
3043 	int err;
3044 
3045 	ksmbd_debug(SMB, "Received smb2 tree disconnect request\n");
3046 
3047 	WORK_BUFFERS(work, req, rsp);
3048 
3049 	if (!tcon) {
3050 		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
3051 
3052 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
3053 		err = -ENOENT;
3054 		goto err_out;
3055 	}
3056 
3057 	ksmbd_close_tree_conn_fds(work);
3058 
3059 	err = ksmbd_tree_conn_disconnect(sess, tcon);
3060 	if (err) {
3061 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
3062 		goto err_out;
3063 	}
3064 
3065 	rsp->StructureSize = cpu_to_le16(4);
3066 	err = ksmbd_iov_pin_rsp(work, rsp,
3067 				sizeof(struct smb2_tree_disconnect_rsp));
3068 	if (err) {
3069 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3070 		goto err_out;
3071 	}
3072 
3073 	return 0;
3074 
3075 err_out:
3076 	smb2_set_err_rsp(work);
3077 	return err;
3078 
3079 }
3080 
3081 /**
3082  * smb2_session_logoff() - handler for session log off request
3083  * @work:	smb work containing request buffer
3084  *
3085  * Return:      0 on success, otherwise error
3086  */
3087 int smb2_session_logoff(struct ksmbd_work *work)
3088 {
3089 	struct ksmbd_conn *conn = work->conn;
3090 	struct ksmbd_session *sess = work->sess;
3091 	struct smb2_logoff_req *req;
3092 	struct smb2_logoff_rsp *rsp;
3093 	int err;
3094 
3095 	WORK_BUFFERS(work, req, rsp);
3096 
3097 	ksmbd_debug(SMB, "Received smb2 session logoff request\n");
3098 
3099 	ksmbd_conn_lock(conn);
3100 	if (!ksmbd_conn_good(conn)) {
3101 		ksmbd_conn_unlock(conn);
3102 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
3103 		smb2_set_err_rsp(work);
3104 		return -ENOENT;
3105 	}
3106 
3107 	down_write(&sess->chann_lock);
3108 	if (sess->tearing_down) {
3109 		up_write(&sess->chann_lock);
3110 		ksmbd_conn_unlock(conn);
3111 		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
3112 		smb2_set_err_rsp(work);
3113 		return -ENOENT;
3114 	}
3115 	sess->tearing_down = true;
3116 	up_write(&sess->chann_lock);
3117 
3118 	ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_RECONNECT);
3119 	ksmbd_conn_unlock(conn);
3120 
3121 	err = ksmbd_conn_wait_idle_sess(conn, sess);
3122 	if (err) {
3123 		down_write(&sess->chann_lock);
3124 		sess->tearing_down = false;
3125 		up_write(&sess->chann_lock);
3126 		ksmbd_all_conn_set_status(sess, KSMBD_SESS_GOOD);
3127 		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3128 		smb2_set_err_rsp(work);
3129 		return err;
3130 	}
3131 
3132 	ksmbd_close_session_fds(work);
3133 
3134 	if (ksmbd_tree_conn_session_logoff(sess)) {
3135 		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
3136 		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
3137 		smb2_set_err_rsp(work);
3138 		err = -ENOENT;
3139 	} else {
3140 		err = 0;
3141 	}
3142 
3143 	down_write(&conn->session_lock);
3144 	sess->kerberos_expiry = 0;
3145 	sess->state = SMB2_SESSION_EXPIRED;
3146 	up_write(&conn->session_lock);
3147 
3148 	ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_SETUP);
3149 
3150 	if (err)
3151 		return err;
3152 
3153 	rsp->StructureSize = cpu_to_le16(4);
3154 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
3155 	if (err) {
3156 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3157 		smb2_set_err_rsp(work);
3158 		return err;
3159 	}
3160 	return 0;
3161 }
3162 
3163 /**
3164  * create_smb2_pipe() - create IPC pipe
3165  * @work:	smb work containing request buffer
3166  *
3167  * Return:      0 on success, otherwise error
3168  */
3169 static noinline int create_smb2_pipe(struct ksmbd_work *work)
3170 {
3171 	struct smb2_create_rsp *rsp;
3172 	struct smb2_create_req *req;
3173 	int id = -1;
3174 	int err;
3175 	char *name;
3176 
3177 	WORK_BUFFERS(work, req, rsp);
3178 
3179 	name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
3180 				      1, work->conn->local_nls);
3181 	if (IS_ERR(name)) {
3182 		rsp->hdr.Status = STATUS_NO_MEMORY;
3183 		err = PTR_ERR(name);
3184 		goto out;
3185 	}
3186 
3187 	id = ksmbd_session_rpc_open(work->sess, name);
3188 	if (id < 0) {
3189 		/*
3190 		 * mdssvc (Spotlight) is a routine, expected probe from macOS
3191 		 * that we deliberately don't support -- it's disabled at the
3192 		 * __rpc_method() level (mgmt/user_session.c), but this
3193 		 * generic failure log would otherwise still fire on every
3194 		 * single probe regardless.
3195 		 */
3196 		if (!(id == -ENOENT && (!strcmp(name, "\\mdssvc") ||
3197 					!strcmp(name, "mdssvc"))))
3198 			pr_err("Unable to open RPC pipe: %d\n", id);
3199 		err = id;
3200 		goto out;
3201 	}
3202 
3203 	rsp->hdr.Status = STATUS_SUCCESS;
3204 	rsp->StructureSize = cpu_to_le16(89);
3205 	rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
3206 	rsp->Flags = 0;
3207 	rsp->CreateAction = cpu_to_le32(FILE_OPENED);
3208 
3209 	rsp->CreationTime = cpu_to_le64(0);
3210 	rsp->LastAccessTime = cpu_to_le64(0);
3211 	rsp->ChangeTime = cpu_to_le64(0);
3212 	rsp->AllocationSize = cpu_to_le64(0);
3213 	rsp->EndofFile = cpu_to_le64(0);
3214 	rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
3215 	rsp->Reserved2 = 0;
3216 	rsp->VolatileFileId = id;
3217 	rsp->PersistentFileId = 0;
3218 	rsp->CreateContextsOffset = 0;
3219 	rsp->CreateContextsLength = 0;
3220 
3221 	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
3222 	if (err)
3223 		goto out;
3224 
3225 	kfree(name);
3226 	return 0;
3227 
3228 out:
3229 	switch (err) {
3230 	case -EINVAL:
3231 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3232 		break;
3233 	case -ENOENT:
3234 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3235 		break;
3236 	case -ENOSPC:
3237 	case -ENOMEM:
3238 		rsp->hdr.Status = STATUS_NO_MEMORY;
3239 		break;
3240 	}
3241 
3242 	if (id >= 0)
3243 		ksmbd_session_rpc_close(work->sess, id);
3244 
3245 	if (!IS_ERR(name))
3246 		kfree(name);
3247 
3248 	smb2_set_err_rsp(work);
3249 	return err;
3250 }
3251 
3252 static bool smb2_is_private_ea(const char *name, size_t name_len)
3253 {
3254 	if (name_len == SD_PREFIX_LEN &&
3255 	    !strncasecmp(name, SD_PREFIX, SD_PREFIX_LEN))
3256 		return true;
3257 	if (name_len == DOS_ATTRIBUTE_PREFIX_LEN &&
3258 	    !strncasecmp(name, DOS_ATTRIBUTE_PREFIX,
3259 			   DOS_ATTRIBUTE_PREFIX_LEN))
3260 		return true;
3261 	if (name_len >= STREAM_PREFIX_LEN &&
3262 	    !strncasecmp(name, STREAM_PREFIX, STREAM_PREFIX_LEN))
3263 		return true;
3264 
3265 	return false;
3266 }
3267 
3268 /**
3269  * smb2_set_ea() - handler for setting extended attributes using set
3270  *		info command
3271  * @eabuf:	set info command buffer
3272  * @buf_len:	set info command buffer length
3273  * @path:	dentry path for get ea
3274  * @get_write:	get write access to a mount
3275  *
3276  * Return:	0 on success, otherwise error
3277  */
3278 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
3279 		       const struct path *path, bool get_write)
3280 {
3281 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
3282 	char *attr_name = NULL, *value;
3283 	int rc = 0;
3284 	unsigned int next = 0;
3285 
3286 	if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
3287 			le16_to_cpu(eabuf->EaValueLength))
3288 		return -EINVAL;
3289 
3290 	attr_name = kmalloc(XATTR_NAME_MAX + 1, KSMBD_DEFAULT_GFP);
3291 	if (!attr_name)
3292 		return -ENOMEM;
3293 
3294 	do {
3295 		if (!eabuf->EaNameLength)
3296 			goto next;
3297 
3298 		ksmbd_debug(SMB,
3299 			    "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
3300 			    eabuf->name, eabuf->EaNameLength,
3301 			    le16_to_cpu(eabuf->EaValueLength),
3302 			    le32_to_cpu(eabuf->NextEntryOffset));
3303 
3304 		if (eabuf->EaNameLength >
3305 		    (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
3306 			rc = -EINVAL;
3307 			break;
3308 		}
3309 		if (smb2_is_private_ea(eabuf->name, eabuf->EaNameLength)) {
3310 			rc = -EACCES;
3311 			break;
3312 		}
3313 
3314 		memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
3315 		memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
3316 		       eabuf->EaNameLength);
3317 		attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
3318 		value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
3319 
3320 		if (!eabuf->EaValueLength) {
3321 			rc = ksmbd_vfs_casexattr_len(idmap,
3322 						     path->dentry,
3323 						     attr_name,
3324 						     XATTR_USER_PREFIX_LEN +
3325 						     eabuf->EaNameLength);
3326 
3327 			/* delete the EA only when it exits */
3328 			if (rc > 0) {
3329 				rc = ksmbd_vfs_remove_xattr(idmap,
3330 							    path,
3331 							    attr_name,
3332 							    get_write);
3333 
3334 				if (rc < 0) {
3335 					ksmbd_debug(SMB,
3336 						    "remove xattr failed(%d)\n",
3337 						    rc);
3338 					break;
3339 				}
3340 			}
3341 
3342 			/* if the EA doesn't exist, just do nothing. */
3343 			rc = 0;
3344 		} else {
3345 			rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
3346 						le16_to_cpu(eabuf->EaValueLength),
3347 						0, get_write);
3348 			if (rc < 0) {
3349 				ksmbd_debug(SMB,
3350 					    "ksmbd_vfs_setxattr is failed(%d)\n",
3351 					    rc);
3352 				break;
3353 			}
3354 		}
3355 
3356 next:
3357 		next = le32_to_cpu(eabuf->NextEntryOffset);
3358 		if (next == 0 || buf_len < next)
3359 			break;
3360 		buf_len -= next;
3361 		eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
3362 		if (buf_len < sizeof(struct smb2_ea_info)) {
3363 			rc = -EINVAL;
3364 			break;
3365 		}
3366 
3367 		if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
3368 				le16_to_cpu(eabuf->EaValueLength)) {
3369 			rc = -EINVAL;
3370 			break;
3371 		}
3372 	} while (next != 0);
3373 
3374 	kfree(attr_name);
3375 	return rc;
3376 }
3377 
3378 static noinline int smb2_set_stream_name_xattr(const struct path *path,
3379 					       struct ksmbd_file *fp,
3380 					       char *stream_name, int s_type)
3381 {
3382 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
3383 	size_t xattr_stream_size;
3384 	char *xattr_stream_name;
3385 	int rc;
3386 
3387 	rc = ksmbd_vfs_xattr_stream_name(stream_name,
3388 					 &xattr_stream_name,
3389 					 &xattr_stream_size,
3390 					 s_type);
3391 	if (rc)
3392 		return rc;
3393 
3394 	fp->stream.name = xattr_stream_name;
3395 	fp->stream.size = xattr_stream_size;
3396 
3397 	/* Check if there is stream prefix in xattr space */
3398 	rc = ksmbd_vfs_casexattr_len(idmap,
3399 				     path->dentry,
3400 				     xattr_stream_name,
3401 				     xattr_stream_size);
3402 	if (rc >= 0)
3403 		return 0;
3404 
3405 	if (fp->cdoption == FILE_OPEN_LE) {
3406 		if (!strcmp(stream_name, "AFP_AfpInfo") &&
3407 		    test_share_config_flag(fp->tcon->share_conf,
3408 					   KSMBD_SHARE_FLAG_TIME_MACHINE)) {
3409 			/*
3410 			 * Synthesize an empty AFP_AfpInfo xattr on first access.
3411 			 * type=0/creator=0 tells macOS to use the file extension
3412 			 * for icon and type detection.
3413 			 *
3414 			 * Scoped to TIME_MACHINE shares, matching the rest of
3415 			 * the AAPL series -- conn->is_aapl alone isn't a safe
3416 			 * gate here, since the pre-existing narrow UniqueId=0
3417 			 * path can also set it on ordinary, non-Time-Machine
3418 			 * shares whenever a Mac client happens to negotiate
3419 			 * AAPL there too.
3420 			 */
3421 			static const u8 afpinfo_empty[60] = {
3422 				0x00, 0x05, 0x16, 0x07, /* magic  0x00051607 BE */
3423 				0x00, 0x02, 0x00, 0x00, /* version 0x00020000 BE */
3424 			};
3425 			rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name,
3426 						(void *)afpinfo_empty,
3427 						sizeof(afpinfo_empty), 0, false);
3428 			return rc < 0 ? rc : 0;
3429 		}
3430 		ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
3431 		return -EBADF;
3432 	}
3433 
3434 	rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false);
3435 	if (rc < 0)
3436 		pr_err("Failed to store XATTR stream name :%d\n", rc);
3437 	return 0;
3438 }
3439 
3440 /*
3441  * fp->stream.size is the byte length of the mangled xattr *name*
3442  * (used as attr_name_len when looking the xattr up), not the size of
3443  * the xattr's value. Reporting it as EndOfFile/AllocationSize for a
3444  * stream handle is wrong -- query the xattr's actual value length
3445  * instead.
3446  */
3447 static loff_t ksmbd_stream_eof(struct ksmbd_file *fp)
3448 {
3449 	ssize_t slen = ksmbd_vfs_casexattr_len(file_mnt_idmap(fp->filp),
3450 					       fp->filp->f_path.dentry,
3451 					       fp->stream.name,
3452 					       fp->stream.size);
3453 	return slen < 0 ? 0 : (loff_t)slen;
3454 }
3455 
3456 static int smb2_remove_smb_xattrs(const struct path *path)
3457 {
3458 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
3459 	char *name, *xattr_list = NULL;
3460 	ssize_t xattr_list_len;
3461 	int err = 0;
3462 
3463 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
3464 	if (xattr_list_len < 0) {
3465 		goto out;
3466 	} else if (!xattr_list_len) {
3467 		ksmbd_debug(SMB, "empty xattr in the file\n");
3468 		goto out;
3469 	}
3470 
3471 	for (name = xattr_list; name - xattr_list < xattr_list_len;
3472 			name += strlen(name) + 1) {
3473 		ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
3474 
3475 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
3476 		    !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
3477 			     STREAM_PREFIX_LEN)) {
3478 			err = ksmbd_vfs_remove_xattr(idmap, path,
3479 						     name, true);
3480 			if (err)
3481 				ksmbd_debug(SMB, "remove xattr failed : %s\n",
3482 					    name);
3483 		}
3484 	}
3485 out:
3486 	kvfree(xattr_list);
3487 	return err;
3488 }
3489 
3490 static int smb2_create_truncate(const struct path *path)
3491 {
3492 	int rc = vfs_truncate(path, 0);
3493 
3494 	if (rc) {
3495 		pr_err("vfs_truncate failed, rc %d\n", rc);
3496 		return rc;
3497 	}
3498 
3499 	rc = smb2_remove_smb_xattrs(path);
3500 	if (rc == -EOPNOTSUPP)
3501 		rc = 0;
3502 	if (rc)
3503 		ksmbd_debug(SMB,
3504 			    "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
3505 			    rc);
3506 	return rc;
3507 }
3508 
3509 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
3510 			    struct ksmbd_file *fp)
3511 {
3512 	struct xattr_dos_attrib da = {0};
3513 	int rc;
3514 
3515 	if (!test_share_config_flag(tcon->share_conf,
3516 				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
3517 		return;
3518 
3519 	da.version = 4;
3520 	da.attr = le32_to_cpu(fp->f_ci->m_fattr);
3521 	da.itime = da.create_time = fp->create_time;
3522 	da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
3523 		XATTR_DOSINFO_ITIME;
3524 
3525 	rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, true);
3526 	if (rc)
3527 		ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
3528 }
3529 
3530 static bool smb2_parent_compressed(struct ksmbd_tree_connect *tcon,
3531 				   const struct path *path)
3532 {
3533 	struct dentry *parent = dget_parent(path->dentry);
3534 	struct file_kattr fa = { .flags_valid = true };
3535 	struct xattr_dos_attrib da;
3536 	bool compressed = false;
3537 	int rc;
3538 
3539 	rc = vfs_fileattr_get(parent, &fa);
3540 	if (!rc && fa.flags & FS_COMPR_FL) {
3541 		compressed = true;
3542 		goto out;
3543 	}
3544 
3545 	rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt), parent, &da);
3546 	if (rc > 0 && da.attr & FILE_ATTRIBUTE_COMPRESSED)
3547 		compressed = true;
3548 
3549 out:
3550 	dput(parent);
3551 	return compressed;
3552 }
3553 
3554 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
3555 			       const struct path *path, struct ksmbd_file *fp)
3556 {
3557 	struct xattr_dos_attrib da = {};
3558 	bool store_dos_attrs = test_share_config_flag(tcon->share_conf,
3559 						      KSMBD_SHARE_FLAG_STORE_DOS_ATTRS);
3560 	int rc;
3561 
3562 	fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
3563 
3564 	/* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
3565 	rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
3566 					    path->dentry, &da);
3567 	if (rc > 0) {
3568 		if (store_dos_attrs) {
3569 			fp->f_ci->m_fattr = cpu_to_le32(da.attr);
3570 			fp->create_time = da.create_time;
3571 			fp->itime = da.itime;
3572 		} else {
3573 			fp->f_ci->m_fattr &=
3574 				~(FILE_ATTRIBUTE_COMPRESSED_LE |
3575 				  FILE_ATTRIBUTE_SPARSE_FILE_LE);
3576 			fp->f_ci->m_fattr |=
3577 				cpu_to_le32(da.attr &
3578 					    (FILE_ATTRIBUTE_COMPRESSED |
3579 					     FILE_ATTRIBUTE_SPARSE_FILE));
3580 		}
3581 	}
3582 }
3583 
3584 static int smb2_creat(struct ksmbd_work *work,
3585 		      struct path *path, char *name, int open_flags,
3586 		      umode_t posix_mode, bool is_dir)
3587 {
3588 	struct ksmbd_tree_connect *tcon = work->tcon;
3589 	struct ksmbd_share_config *share = tcon->share_conf;
3590 	umode_t mode;
3591 	int rc;
3592 
3593 	if (!(open_flags & O_CREAT))
3594 		return -EBADF;
3595 
3596 	ksmbd_debug(SMB, "file does not exist, so creating\n");
3597 	if (is_dir == true) {
3598 		ksmbd_debug(SMB, "creating directory\n");
3599 
3600 		mode = share_config_directory_mode(share, posix_mode);
3601 		rc = ksmbd_vfs_mkdir(work, name, mode);
3602 		if (rc)
3603 			return rc;
3604 	} else {
3605 		ksmbd_debug(SMB, "creating regular file\n");
3606 
3607 		mode = share_config_create_mode(share, posix_mode);
3608 		rc = ksmbd_vfs_create(work, name, mode);
3609 		if (rc)
3610 			return rc;
3611 	}
3612 
3613 	rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
3614 	if (rc) {
3615 		pr_err("cannot get linux path (%s), err = %d\n",
3616 		       name, rc);
3617 		return rc;
3618 	}
3619 	return 0;
3620 }
3621 
3622 static int smb2_create_sd_buffer(struct ksmbd_work *work,
3623 				 struct smb2_create_req *req,
3624 				 const struct path *path)
3625 {
3626 	struct create_context *context;
3627 	struct create_sd_buf_req *sd_buf;
3628 
3629 	if (!req->CreateContextsOffset)
3630 		return -ENOENT;
3631 
3632 	/* Parse SD BUFFER create contexts */
3633 	context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
3634 	if (!context)
3635 		return -ENOENT;
3636 	else if (IS_ERR(context))
3637 		return PTR_ERR(context);
3638 
3639 	ksmbd_debug(SMB,
3640 		    "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
3641 	sd_buf = (struct create_sd_buf_req *)context;
3642 	if (le16_to_cpu(context->DataOffset) +
3643 	    le32_to_cpu(context->DataLength) <
3644 	    sizeof(struct create_sd_buf_req))
3645 		return -EINVAL;
3646 	return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
3647 			    le32_to_cpu(sd_buf->ccontext.DataLength), true, false);
3648 }
3649 
3650 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
3651 			     struct mnt_idmap *idmap,
3652 			     struct inode *inode)
3653 {
3654 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
3655 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
3656 
3657 	fattr->cf_uid = vfsuid_into_kuid(vfsuid);
3658 	fattr->cf_gid = vfsgid_into_kgid(vfsgid);
3659 	fattr->cf_mode = inode->i_mode;
3660 	fattr->cf_acls = NULL;
3661 	fattr->cf_dacls = NULL;
3662 
3663 	if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
3664 		fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
3665 		if (S_ISDIR(inode->i_mode))
3666 			fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
3667 	}
3668 }
3669 
3670 enum {
3671 	DURABLE_RECONN_V2 = 1,
3672 	DURABLE_RECONN,
3673 	DURABLE_REQ_V2,
3674 	DURABLE_REQ,
3675 };
3676 
3677 struct durable_info {
3678 	struct ksmbd_file *fp;
3679 	unsigned short int type;
3680 	bool persistent;
3681 	bool reconnected;
3682 	bool replay;
3683 	bool replay_consumed;
3684 	bool app_instance_id;
3685 	bool app_instance_version_valid;
3686 	unsigned int timeout;
3687 	char *CreateGuid;
3688 	char AppInstanceId[SMB2_CREATE_GUID_SIZE];
3689 	u64 app_instance_version_high;
3690 	u64 app_instance_version_low;
3691 };
3692 
3693 static int smb2_check_durable_replay(struct ksmbd_work *work,
3694 				     struct ksmbd_file *fp,
3695 				     struct lease_ctx_info *lc,
3696 				     bool persistent)
3697 {
3698 	struct oplock_info *opinfo;
3699 	int ret = 0;
3700 
3701 	if (!fp->is_durable && !fp->is_persistent)
3702 		return -EACCES;
3703 
3704 	if (ksmbd_vfs_compare_durable_owner(fp, work->sess->user) == false)
3705 		return -EACCES;
3706 
3707 	if (fp->is_persistent && !persistent)
3708 		return -EINVAL;
3709 
3710 	opinfo = opinfo_get(fp);
3711 	if (!opinfo)
3712 		return 0;
3713 
3714 	if (opinfo->sess && opinfo->sess->id != work->sess->id) {
3715 		ret = -ENOEXEC;
3716 		goto out;
3717 	}
3718 
3719 	if (opinfo->is_lease) {
3720 		if (!lc ||
3721 		    memcmp(opinfo->o_lease->lease_key, lc->lease_key,
3722 			   SMB2_LEASE_KEY_SIZE)) {
3723 			ret = -EACCES;
3724 			goto out;
3725 		}
3726 	} else {
3727 		if (lc) {
3728 			ret = -EACCES;
3729 			goto out;
3730 		}
3731 
3732 		if (fp->is_durable && opinfo->level != SMB2_OPLOCK_LEVEL_BATCH)
3733 			ret = -EACCES;
3734 	}
3735 out:
3736 	opinfo_put(opinfo);
3737 	return ret;
3738 }
3739 
3740 static bool smb2_durable_replay_consumed(struct ksmbd_file *fp)
3741 {
3742 	bool consumed;
3743 
3744 	spin_lock(&fp->f_lock);
3745 	consumed = fp->durable_replay_consumed;
3746 	spin_unlock(&fp->f_lock);
3747 
3748 	return consumed;
3749 }
3750 
3751 static void smb2_mark_durable_replay_consumed(struct ksmbd_file *fp)
3752 {
3753 	spin_lock(&fp->f_lock);
3754 	fp->durable_replay_consumed = true;
3755 	spin_unlock(&fp->f_lock);
3756 }
3757 
3758 static bool smb2_durable_replay_differs(struct ksmbd_file *fp,
3759 					struct smb2_create_req *req)
3760 {
3761 	return fp->cdoption != req->CreateDisposition ||
3762 		fp->create_file_attributes != req->FileAttributes;
3763 }
3764 
3765 static int parse_durable_handle_context(struct ksmbd_work *work,
3766 					struct smb2_create_req *req,
3767 					struct lease_ctx_info *lc,
3768 					struct durable_info *dh_info)
3769 {
3770 	struct ksmbd_conn *conn = work->conn;
3771 	struct create_context *context;
3772 	int dh_idx, err = 0;
3773 	u64 persistent_id = 0;
3774 	int req_op_level;
3775 	static const char * const durable_arr[] = {"DH2C", "DHnC", "DH2Q", "DHnQ"};
3776 
3777 	req_op_level = req->RequestedOplockLevel;
3778 	for (dh_idx = DURABLE_RECONN_V2; dh_idx <= ARRAY_SIZE(durable_arr);
3779 	     dh_idx++) {
3780 		context = smb2_find_context_vals(req, durable_arr[dh_idx - 1], 4);
3781 		if (IS_ERR(context)) {
3782 			err = PTR_ERR(context);
3783 			goto out;
3784 		}
3785 		if (!context)
3786 			continue;
3787 
3788 		switch (dh_idx) {
3789 		case DURABLE_RECONN_V2:
3790 		{
3791 			struct create_durable_handle_reconnect_v2 *recon_v2;
3792 			u32 flags;
3793 
3794 			if (dh_info->type == DURABLE_RECONN ||
3795 			    dh_info->type == DURABLE_REQ_V2) {
3796 				err = -EINVAL;
3797 				goto out;
3798 			}
3799 
3800 			if (le32_to_cpu(context->DataLength) <
3801 			    sizeof(recon_v2->dcontext)) {
3802 				err = -EINVAL;
3803 				goto out;
3804 			}
3805 
3806 			recon_v2 = (struct create_durable_handle_reconnect_v2 *)context;
3807 			flags = le32_to_cpu(recon_v2->dcontext.Flags);
3808 			if (flags & ~SMB2_DHANDLE_FLAG_PERSISTENT) {
3809 				err = -EINVAL;
3810 				goto out;
3811 			}
3812 			dh_info->persistent = flags & SMB2_DHANDLE_FLAG_PERSISTENT;
3813 			persistent_id = recon_v2->dcontext.Fid.PersistentFileId;
3814 			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
3815 			if (!dh_info->fp) {
3816 				ksmbd_debug(SMB, "Failed to get durable handle state\n");
3817 				err = -EBADF;
3818 				goto out;
3819 			}
3820 
3821 			/* A zero VolatileFileId means that the client did not specify it. */
3822 			if (recon_v2->dcontext.Fid.VolatileFileId &&
3823 			    dh_info->fp->durable_volatile_id !=
3824 			    recon_v2->dcontext.Fid.VolatileFileId) {
3825 				err = -EBADF;
3826 				ksmbd_put_durable_fd(dh_info->fp);
3827 				goto out;
3828 			}
3829 
3830 			if (memcmp(dh_info->fp->create_guid, recon_v2->dcontext.CreateGuid,
3831 				   SMB2_CREATE_GUID_SIZE)) {
3832 				err = -EBADF;
3833 				ksmbd_put_durable_fd(dh_info->fp);
3834 				goto out;
3835 			}
3836 
3837 			/* A persistent reconnect must match the original open type. */
3838 			if (dh_info->fp->is_persistent != dh_info->persistent) {
3839 				err = dh_info->persistent ? -EINVAL : -EBADF;
3840 				ksmbd_put_durable_fd(dh_info->fp);
3841 				goto out;
3842 			}
3843 
3844 			dh_info->type = dh_idx;
3845 			dh_info->reconnected = true;
3846 			ksmbd_debug(SMB,
3847 				"reconnect v2 Persistent-id from reconnect = %llu\n",
3848 					persistent_id);
3849 			break;
3850 		}
3851 		case DURABLE_RECONN:
3852 		{
3853 			create_durable_reconn_t *recon;
3854 
3855 			if (dh_info->type == DURABLE_RECONN_V2 ||
3856 			    dh_info->type == DURABLE_REQ_V2) {
3857 				err = -EINVAL;
3858 				goto out;
3859 			}
3860 
3861 			if (le32_to_cpu(context->DataLength) <
3862 			    sizeof(recon->Data)) {
3863 				err = -EINVAL;
3864 				goto out;
3865 			}
3866 
3867 			recon = (create_durable_reconn_t *)context;
3868 			persistent_id = recon->Data.Fid.PersistentFileId;
3869 			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
3870 			if (!dh_info->fp) {
3871 				ksmbd_debug(SMB, "Failed to get durable handle state\n");
3872 				err = -EBADF;
3873 				goto out;
3874 			}
3875 
3876 			/* A zero VolatileFileId means that the client did not specify it. */
3877 			if (recon->Data.Fid.VolatileFileId &&
3878 			    dh_info->fp->durable_volatile_id !=
3879 			    recon->Data.Fid.VolatileFileId) {
3880 				err = -EBADF;
3881 				ksmbd_put_durable_fd(dh_info->fp);
3882 				goto out;
3883 			}
3884 
3885 			dh_info->type = dh_idx;
3886 			dh_info->reconnected = true;
3887 			ksmbd_debug(SMB, "reconnect Persistent-id from reconnect = %llu\n",
3888 				    persistent_id);
3889 			break;
3890 		}
3891 		case DURABLE_REQ_V2:
3892 		{
3893 			struct create_durable_req_v2 *durable_v2_blob;
3894 
3895 			if (dh_info->type == DURABLE_RECONN ||
3896 			    dh_info->type == DURABLE_RECONN_V2) {
3897 				err = -EINVAL;
3898 				goto out;
3899 			}
3900 
3901 			if (le32_to_cpu(context->DataLength) <
3902 			    sizeof(durable_v2_blob->dcontext)) {
3903 				err = -EINVAL;
3904 				goto out;
3905 			}
3906 
3907 			durable_v2_blob =
3908 				(struct create_durable_req_v2 *)context;
3909 			if (le32_to_cpu(durable_v2_blob->dcontext.Flags) &
3910 			    ~SMB2_DHANDLE_FLAG_PERSISTENT) {
3911 				err = -EINVAL;
3912 				goto out;
3913 			}
3914 			ksmbd_debug(SMB, "Request for durable v2 open\n");
3915 			dh_info->CreateGuid = durable_v2_blob->dcontext.CreateGuid;
3916 			dh_info->persistent =
3917 				le32_to_cpu(durable_v2_blob->dcontext.Flags) &
3918 				SMB2_DHANDLE_FLAG_PERSISTENT;
3919 			dh_info->fp = ksmbd_lookup_fd_cguid(durable_v2_blob->dcontext.CreateGuid);
3920 			if (dh_info->fp) {
3921 				if (!memcmp(conn->ClientGUID, dh_info->fp->client_guid,
3922 					    SMB2_CLIENT_GUID_SIZE)) {
3923 					if (!(req->hdr.Flags & SMB2_FLAGS_REPLAY_OPERATION)) {
3924 						err = -ENOEXEC;
3925 						ksmbd_put_durable_fd(dh_info->fp);
3926 						goto out;
3927 					}
3928 
3929 					if (dh_info->fp->f_state == FP_NEW) {
3930 						/* Original CREATE is still pending. */
3931 						ksmbd_put_durable_fd(dh_info->fp);
3932 						err = -EAGAIN;
3933 						goto out;
3934 					}
3935 
3936 					if (!dh_info->fp->is_durable &&
3937 					    !dh_info->fp->is_persistent) {
3938 						/*
3939 						 * A DurableHandleReqV2 CREATE can complete
3940 						 * without granting durability (for example, if
3941 						 * it requested no oplock).  Its CreateGuid still
3942 						 * identifies a completed CREATE for replay.
3943 						 */
3944 						if (dh_info->fp->conn &&
3945 						    ksmbd_vfs_compare_durable_owner(
3946 							    dh_info->fp, work->sess->user)) {
3947 							if (smb2_durable_replay_consumed(
3948 								    dh_info->fp)) {
3949 								ksmbd_put_durable_fd(dh_info->fp);
3950 								dh_info->fp = NULL;
3951 								dh_info->type = dh_idx;
3952 								dh_info->replay_consumed = true;
3953 								break;
3954 							}
3955 							if (smb2_durable_replay_differs(
3956 								    dh_info->fp, req))
3957 								smb2_mark_durable_replay_consumed(
3958 									dh_info->fp);
3959 							dh_info->replay = true;
3960 							dh_info->type = dh_idx;
3961 							goto out;
3962 						}
3963 						ksmbd_put_durable_fd(dh_info->fp);
3964 						err = -EACCES;
3965 						goto out;
3966 					}
3967 
3968 					if (dh_info->fp->conn &&
3969 					    smb2_durable_replay_consumed(dh_info->fp)) {
3970 						ksmbd_put_durable_fd(dh_info->fp);
3971 						dh_info->fp = NULL;
3972 						dh_info->type = dh_idx;
3973 						dh_info->replay_consumed = true;
3974 						break;
3975 					}
3976 
3977 					err = smb2_check_durable_replay(work,
3978 									dh_info->fp,
3979 									lc,
3980 									dh_info->persistent);
3981 					if (err) {
3982 						ksmbd_put_durable_fd(dh_info->fp);
3983 						goto out;
3984 					}
3985 
3986 					if (dh_info->fp->conn) {
3987 						if (smb2_durable_replay_differs(dh_info->fp,
3988 									       req))
3989 							smb2_mark_durable_replay_consumed(
3990 									dh_info->fp);
3991 						dh_info->replay = true;
3992 					} else {
3993 						dh_info->reconnected = true;
3994 					}
3995 					dh_info->type = dh_idx;
3996 					goto out;
3997 				}
3998 				ksmbd_put_durable_fd(dh_info->fp);
3999 				dh_info->fp = NULL;
4000 			}
4001 
4002 			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
4003 			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
4004 				dh_info->timeout =
4005 					le32_to_cpu(durable_v2_blob->dcontext.Timeout);
4006 				dh_info->type = dh_idx;
4007 			}
4008 			break;
4009 		}
4010 		case DURABLE_REQ:
4011 			if (dh_info->type == DURABLE_RECONN)
4012 				goto out;
4013 			if (dh_info->type == DURABLE_RECONN_V2 ||
4014 			    dh_info->type == DURABLE_REQ_V2) {
4015 				err = -EINVAL;
4016 				goto out;
4017 			}
4018 
4019 			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
4020 			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
4021 				ksmbd_debug(SMB, "Request for durable open\n");
4022 				dh_info->type = dh_idx;
4023 			}
4024 		}
4025 	}
4026 
4027 out:
4028 	return err;
4029 }
4030 
4031 static int parse_app_instance_id(struct smb2_create_req *req,
4032 				 struct durable_info *dh_info)
4033 {
4034 	struct create_context *context;
4035 	char *data;
4036 
4037 	context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_ID,
4038 					 SMB2_CREATE_GUID_SIZE);
4039 	if (IS_ERR(context))
4040 		return PTR_ERR(context);
4041 	if (!context)
4042 		return 0;
4043 
4044 	if (le32_to_cpu(context->DataLength) < 20)
4045 		return -EINVAL;
4046 
4047 	data = (char *)context + le16_to_cpu(context->DataOffset);
4048 	if (data[0] != 20 || data[1])
4049 		return -EINVAL;
4050 
4051 	memcpy(dh_info->AppInstanceId, data + 4, SMB2_CREATE_GUID_SIZE);
4052 	dh_info->app_instance_id = true;
4053 	return 0;
4054 }
4055 
4056 static int parse_app_instance_version(struct smb2_create_req *req,
4057 				      struct durable_info *dh_info)
4058 {
4059 	struct create_context *context;
4060 	char *data;
4061 
4062 	context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_VERSION,
4063 					 SMB2_CREATE_GUID_SIZE);
4064 	if (IS_ERR(context))
4065 		return PTR_ERR(context);
4066 	if (!context)
4067 		return 0;
4068 
4069 	if (le32_to_cpu(context->DataLength) < 24)
4070 		return -EINVAL;
4071 
4072 	data = (char *)context + le16_to_cpu(context->DataOffset);
4073 	if (get_unaligned_le16(data) != 24 ||
4074 	    get_unaligned_le16(data + 2) != 0)
4075 		return -EINVAL;
4076 
4077 	dh_info->app_instance_version_high = get_unaligned_le64(data + 8);
4078 	dh_info->app_instance_version_low = get_unaligned_le64(data + 16);
4079 	dh_info->app_instance_version_valid = true;
4080 	return 0;
4081 }
4082 
4083 static int smb2_handle_app_instance_id(struct smb2_create_rsp *rsp,
4084 				       struct durable_info *dh_info)
4085 {
4086 	struct ksmbd_file *old_fp;
4087 	bool reject = false;
4088 
4089 	if (!dh_info->app_instance_id)
4090 		return 0;
4091 
4092 	old_fp = ksmbd_lookup_fd_app_instance_id(dh_info->AppInstanceId);
4093 	if (!old_fp)
4094 		return 0;
4095 
4096 	if (dh_info->app_instance_version_valid) {
4097 		if (old_fp->app_instance_version_valid &&
4098 		    (dh_info->app_instance_version_high <
4099 			 old_fp->app_instance_version_high ||
4100 		     (dh_info->app_instance_version_high ==
4101 			      old_fp->app_instance_version_high &&
4102 			      dh_info->app_instance_version_low <=
4103 			      old_fp->app_instance_version_low)))
4104 			reject = true;
4105 	} else if (old_fp->app_instance_version_valid) {
4106 		reject = true;
4107 	}
4108 
4109 	ksmbd_put_durable_fd(old_fp);
4110 	if (reject) {
4111 		rsp->hdr.Status = STATUS_FILE_FORCED_CLOSED;
4112 		return -EIO;
4113 	}
4114 
4115 	return ksmbd_close_fd_app_instance_id(dh_info->AppInstanceId);
4116 }
4117 
4118 /**
4119  * smb2_open() - handler for smb file open request
4120  * @work:	smb work containing request buffer
4121  *
4122  * Return:      0 on success, otherwise error
4123  */
4124 int smb2_open(struct ksmbd_work *work)
4125 {
4126 	struct ksmbd_conn *conn = work->conn;
4127 	struct ksmbd_session *sess = work->sess;
4128 	struct ksmbd_tree_connect *tcon = work->tcon;
4129 	struct smb2_create_req *req;
4130 	struct smb2_create_rsp *rsp;
4131 	struct path path;
4132 	struct ksmbd_share_config *share = tcon->share_conf;
4133 	struct ksmbd_file *fp = NULL;
4134 	struct file *filp = NULL;
4135 	struct mnt_idmap *idmap = NULL;
4136 	struct kstat stat;
4137 	struct create_context *context;
4138 	struct lease_ctx_info *lc = NULL;
4139 	struct create_ea_buf_req *ea_buf = NULL;
4140 	struct oplock_info *opinfo;
4141 	struct durable_info dh_info = {0};
4142 	__le32 *next_ptr = NULL;
4143 	int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
4144 	int rc = 0;
4145 	int contxt_cnt = 0, query_disk_id = 0;
4146 	bool maximal_access_ctxt = false, posix_ctxt = false;
4147 	bool aapl_ctxt = false;
4148 	bool durable_rsp = true;
4149 	__u64 aapl_req_bitmap = 0, aapl_client_caps = 0;
4150 	int s_type = 0;
4151 	int next_off = 0;
4152 	char *name = NULL;
4153 	char *stream_name = NULL;
4154 	bool file_present = false, created = false, already_permitted = false;
4155 	int share_ret, need_truncate = 0;
4156 	u64 time, alloc_size = 0;
4157 	umode_t posix_mode = 0;
4158 	__le32 daccess, maximal_access = 0;
4159 	u32 dos_attr;
4160 	int iov_len = 0;
4161 
4162 	ksmbd_debug(SMB, "Received smb2 create request\n");
4163 
4164 	WORK_BUFFERS(work, req, rsp);
4165 
4166 	if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
4167 	    (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
4168 		ksmbd_debug(SMB, "invalid flag in chained command\n");
4169 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4170 		smb2_set_err_rsp(work);
4171 		return -EINVAL;
4172 	}
4173 
4174 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
4175 		ksmbd_debug(SMB, "IPC pipe create request\n");
4176 		return create_smb2_pipe(work);
4177 	}
4178 
4179 	if (req->CreateContextsOffset && tcon->posix_extensions) {
4180 		context = smb2_find_context_vals(req, SMB2_CREATE_TAG_POSIX, 16);
4181 		if (IS_ERR(context)) {
4182 			rc = PTR_ERR(context);
4183 			goto err_out2;
4184 		} else if (context) {
4185 			struct create_posix *posix = (struct create_posix *)context;
4186 
4187 			if (le16_to_cpu(context->DataOffset) +
4188 				le32_to_cpu(context->DataLength) <
4189 			    sizeof(struct create_posix) - 4) {
4190 				rc = -EINVAL;
4191 				goto err_out2;
4192 			}
4193 			ksmbd_debug(SMB, "get posix context\n");
4194 
4195 			posix_mode = le32_to_cpu(posix->Mode);
4196 			posix_ctxt = true;
4197 		}
4198 	}
4199 
4200 	if (req->NameLength) {
4201 		name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset),
4202 				     le16_to_cpu(req->NameLength),
4203 				     work->conn->local_nls);
4204 		if (IS_ERR(name)) {
4205 			rc = PTR_ERR(name);
4206 			name = NULL;
4207 			goto err_out2;
4208 		}
4209 
4210 		ksmbd_debug(SMB, "converted name = %s\n", name);
4211 
4212 		if (posix_ctxt == false) {
4213 			if (strchr(name, ':')) {
4214 				if (!test_share_config_flag(work->tcon->share_conf,
4215 							KSMBD_SHARE_FLAG_STREAMS)) {
4216 					rc = -EBADF;
4217 					goto err_out2;
4218 				}
4219 				rc = parse_stream_name(name, &stream_name, &s_type);
4220 				if (rc < 0)
4221 					goto err_out2;
4222 			}
4223 
4224 			rc = ksmbd_validate_filename(name);
4225 			if (rc < 0)
4226 				goto err_out2;
4227 		}
4228 
4229 		if (ksmbd_share_veto_filename(share, name)) {
4230 			rc = -ENOENT;
4231 			ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
4232 				    name);
4233 			goto err_out2;
4234 		}
4235 	} else {
4236 		name = kstrdup("", KSMBD_DEFAULT_GFP);
4237 		if (!name) {
4238 			rc = -ENOMEM;
4239 			goto err_out2;
4240 		}
4241 	}
4242 
4243 	req_op_level = req->RequestedOplockLevel;
4244 
4245 	if (req->CreateContextsOffset) {
4246 		rc = parse_app_instance_id(req, &dh_info);
4247 		if (rc)
4248 			goto err_out2;
4249 		rc = parse_app_instance_version(req, &dh_info);
4250 		if (rc)
4251 			goto err_out2;
4252 	}
4253 
4254 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
4255 	    req->CreateContextsOffset) {
4256 		lc = parse_lease_state(req);
4257 		if (IS_ERR(lc)) {
4258 			rc = PTR_ERR(lc);
4259 			lc = NULL;
4260 			goto err_out2;
4261 		}
4262 		if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
4263 			kfree(lc);
4264 			lc = NULL;
4265 			if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
4266 				req_op_level = SMB2_OPLOCK_LEVEL_NONE;
4267 		}
4268 		rc = parse_durable_handle_context(work, req, lc, &dh_info);
4269 		if (rc) {
4270 			ksmbd_debug(SMB, "error parsing durable handle context\n");
4271 			goto err_out2;
4272 		}
4273 
4274 		if (dh_info.replay == true) {
4275 			fp = dh_info.fp;
4276 			if (ksmbd_override_fsids(work)) {
4277 				rc = -ENOMEM;
4278 				goto err_out2;
4279 			}
4280 
4281 			file_info = FILE_OPENED;
4282 			rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
4283 			if (rc)
4284 				goto err_out2;
4285 
4286 			goto reconnected_fp;
4287 		}
4288 
4289 		if (dh_info.reconnected == true) {
4290 			rc = smb2_check_durable_oplock(conn, share, dh_info.fp,
4291 					lc, sess->user, name);
4292 			if (rc)
4293 				goto err_out2;
4294 
4295 			rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
4296 			if (rc)
4297 				goto err_out2;
4298 
4299 			fp = dh_info.fp;
4300 
4301 			if (ksmbd_override_fsids(work)) {
4302 				rc = -ENOMEM;
4303 				goto err_out2;
4304 			}
4305 
4306 			file_info = FILE_OPENED;
4307 
4308 			rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
4309 			if (rc)
4310 				goto err_out2;
4311 
4312 			goto reconnected_fp;
4313 		}
4314 
4315 	} else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
4316 		lc = parse_lease_state(req);
4317 		if (IS_ERR(lc)) {
4318 			rc = PTR_ERR(lc);
4319 			lc = NULL;
4320 			goto err_out2;
4321 		}
4322 		if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
4323 			kfree(lc);
4324 			lc = NULL;
4325 			req_op_level = SMB2_OPLOCK_LEVEL_NONE;
4326 		}
4327 	}
4328 
4329 	if (dh_info.app_instance_id && !dh_info.reconnected &&
4330 	    !dh_info.replay) {
4331 		rc = smb2_handle_app_instance_id(rsp, &dh_info);
4332 		if (rc)
4333 			goto err_out2;
4334 	}
4335 
4336 	if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
4337 		pr_err("Invalid impersonationlevel : 0x%x\n",
4338 		       le32_to_cpu(req->ImpersonationLevel));
4339 		rc = -EIO;
4340 		rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
4341 		goto err_out2;
4342 	}
4343 
4344 	if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
4345 		pr_err("Invalid create options : 0x%x\n",
4346 		       le32_to_cpu(req->CreateOptions));
4347 		rc = -EINVAL;
4348 		goto err_out2;
4349 	} else {
4350 		if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
4351 		    req->CreateOptions & FILE_RANDOM_ACCESS_LE)
4352 			req->CreateOptions &= ~FILE_SEQUENTIAL_ONLY_LE;
4353 
4354 		if (req->CreateOptions &
4355 		    (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
4356 		     FILE_RESERVE_OPFILTER_LE)) {
4357 			rc = -EOPNOTSUPP;
4358 			goto err_out2;
4359 		}
4360 
4361 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
4362 			if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
4363 				rc = -EINVAL;
4364 				goto err_out2;
4365 			}
4366 		}
4367 	}
4368 
4369 	if (le32_to_cpu(req->CreateDisposition) >
4370 	    le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
4371 		pr_err("Invalid create disposition : 0x%x\n",
4372 		       le32_to_cpu(req->CreateDisposition));
4373 		rc = -EINVAL;
4374 		goto err_out2;
4375 	}
4376 
4377 	if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
4378 		pr_err("Invalid desired access : 0x%x\n",
4379 		       le32_to_cpu(req->DesiredAccess));
4380 		rc = -EACCES;
4381 		goto err_out2;
4382 	}
4383 
4384 	if (req->DesiredAccess == FILE_SYNCHRONIZE_LE &&
4385 	    req->CreateDisposition == FILE_OPEN_IF_LE &&
4386 	    !req->FileAttributes) {
4387 		rc = -EACCES;
4388 		goto err_out2;
4389 	}
4390 
4391 	if (req->FileAttributes &&
4392 	    (req->FileAttributes & ~cpu_to_le32(SMB2_CREATE_FILE_ATTRIBUTE_MASK))) {
4393 		pr_err("Invalid file attribute : 0x%x\n",
4394 		       le32_to_cpu(req->FileAttributes));
4395 		rc = -EINVAL;
4396 		goto err_out2;
4397 	}
4398 
4399 	if (req->CreateContextsOffset) {
4400 		/* Parse non-durable handle create contexts */
4401 		context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
4402 		if (IS_ERR(context)) {
4403 			rc = PTR_ERR(context);
4404 			goto err_out2;
4405 		} else if (context) {
4406 			ea_buf = (struct create_ea_buf_req *)context;
4407 			if (le16_to_cpu(context->DataOffset) +
4408 			    le32_to_cpu(context->DataLength) <
4409 			    sizeof(struct create_ea_buf_req)) {
4410 				rc = -EINVAL;
4411 				goto err_out2;
4412 			}
4413 			if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
4414 				rsp->hdr.Status = STATUS_ACCESS_DENIED;
4415 				rc = -EACCES;
4416 				goto err_out2;
4417 			}
4418 		}
4419 
4420 		context = smb2_find_context_vals(req,
4421 						 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
4422 		if (IS_ERR(context)) {
4423 			rc = PTR_ERR(context);
4424 			goto err_out2;
4425 		} else if (context) {
4426 			ksmbd_debug(SMB,
4427 				    "get query maximal access context\n");
4428 			maximal_access_ctxt = 1;
4429 		}
4430 
4431 		context = smb2_find_context_vals(req,
4432 						 SMB2_CREATE_TIMEWARP_REQUEST, 4);
4433 		if (IS_ERR(context)) {
4434 			rc = PTR_ERR(context);
4435 			goto err_out2;
4436 		} else if (context) {
4437 			ksmbd_debug(SMB, "get timewarp context\n");
4438 			rc = -EBADF;
4439 			goto err_out2;
4440 		}
4441 	}
4442 
4443 	if (ksmbd_override_fsids(work)) {
4444 		rc = -ENOMEM;
4445 		goto err_out2;
4446 	}
4447 
4448 	rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
4449 				 &path, 1);
4450 
4451 	/*
4452 	 * A durable handle opened with delete-on-close is preserved across a
4453 	 * disconnect so it can be reclaimed by a durable reconnect.  When a new
4454 	 * delete-on-close open for the same name arrives instead, the
4455 	 * disconnected handle must give way: close it so its delete-on-close
4456 	 * removes the file, then re-resolve so this open can create a fresh one.
4457 	 */
4458 	if (!rc && (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) &&
4459 	    (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
4460 	     req->CreateDisposition == FILE_OPEN_IF_LE) &&
4461 	    ksmbd_close_disconnected_durable_delete_on_close(path.dentry)) {
4462 		path_put(&path);
4463 		rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
4464 					 &path, 1);
4465 	}
4466 
4467 	if (!rc) {
4468 		file_present = true;
4469 
4470 		if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
4471 			struct xattr_dos_attrib da;
4472 
4473 			/*
4474 			 * If file exists with under flags, return access
4475 			 * denied error.
4476 			 */
4477 			if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
4478 			    req->CreateDisposition == FILE_OPEN_IF_LE) {
4479 				rc = -EACCES;
4480 				goto err_out;
4481 			}
4482 
4483 			if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
4484 				ksmbd_debug(SMB,
4485 					    "User does not have write permission\n");
4486 					rc = -EACCES;
4487 					goto err_out;
4488 				}
4489 
4490 			if (test_share_config_flag(tcon->share_conf,
4491 						   KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
4492 			    ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path.mnt),
4493 							 path.dentry, &da) > 0 &&
4494 			    da.attr & FILE_ATTRIBUTE_READONLY) {
4495 				rsp->hdr.Status = STATUS_CANNOT_DELETE;
4496 				rc = -EACCES;
4497 				goto err_out;
4498 			}
4499 		} else if (d_is_symlink(path.dentry)) {
4500 			rc = -EACCES;
4501 			goto err_out;
4502 		}
4503 
4504 		idmap = mnt_idmap(path.mnt);
4505 	} else {
4506 		if (rc != -ENOENT)
4507 			goto err_out;
4508 		ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
4509 			    name, rc);
4510 		rc = 0;
4511 	}
4512 
4513 	if (!file_present && req->CreateOptions & FILE_DELETE_ON_CLOSE_LE &&
4514 	    req->FileAttributes & FILE_ATTRIBUTE_READONLY_LE) {
4515 		rsp->hdr.Status = STATUS_CANNOT_DELETE;
4516 		rc = -EACCES;
4517 		goto err_out;
4518 	}
4519 
4520 	/*
4521 	 * An explicit ::$DATA suffix names the unnamed data stream and is
4522 	 * canonicalized to a NULL stream name (base file), but the request
4523 	 * still has to be validated against the data-stream type, e.g. opening
4524 	 * <dir>::$DATA with FILE_DIRECTORY_FILE must fail with
4525 	 * STATUS_NOT_A_DIRECTORY.
4526 	 */
4527 	if (stream_name || s_type == DATA_STREAM) {
4528 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
4529 			if (s_type == DATA_STREAM) {
4530 				rc = -EIO;
4531 				rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
4532 			}
4533 		} else {
4534 			if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
4535 			    !stream_name && s_type == DATA_STREAM) {
4536 				rc = -EIO;
4537 				rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
4538 			}
4539 		}
4540 
4541 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
4542 		    req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
4543 			rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
4544 			rc = -EIO;
4545 		}
4546 
4547 		if (rc < 0)
4548 			goto err_out;
4549 	}
4550 
4551 	if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
4552 	    S_ISDIR(d_inode(path.dentry)->i_mode) &&
4553 	    !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
4554 		ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
4555 			    name, req->CreateOptions);
4556 		rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
4557 		rc = -EIO;
4558 		goto err_out;
4559 	}
4560 
4561 	if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
4562 	    !(req->CreateDisposition == FILE_CREATE_LE) &&
4563 	    !S_ISDIR(d_inode(path.dentry)->i_mode)) {
4564 		rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
4565 		rc = -EIO;
4566 		goto err_out;
4567 	}
4568 
4569 	if (!stream_name && file_present &&
4570 	    req->CreateDisposition == FILE_CREATE_LE) {
4571 		rc = -EEXIST;
4572 		goto err_out;
4573 	}
4574 
4575 	daccess = smb_map_generic_desired_access(req->DesiredAccess);
4576 
4577 	if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
4578 		rc = smb_check_perm_dacl(conn, &path, &daccess,
4579 					 req->DesiredAccess,
4580 					 sess->user->uid, false);
4581 		if (rc)
4582 			goto err_out;
4583 
4584 		if (maximal_access_ctxt) {
4585 			maximal_access = FILE_MAXIMAL_ACCESS_LE;
4586 			rc = smb_check_perm_dacl(conn, &path, &maximal_access,
4587 						 0, sess->user->uid, false);
4588 			if (rc)
4589 				goto err_out;
4590 
4591 			/*
4592 			 * smb_check_perm_dacl() returns success without
4593 			 * touching *pdaccess when the object has no stored
4594 			 * NT ACL, leaving maximal_access as the
4595 			 * FILE_MAXIMAL_ACCESS_LE request sentinel instead of
4596 			 * a real access mask.
4597 			 */
4598 			if (maximal_access == FILE_MAXIMAL_ACCESS_LE)
4599 				ksmbd_vfs_query_maximal_access(idmap, path.dentry,
4600 							       &maximal_access);
4601 		}
4602 	}
4603 
4604 	if (daccess & FILE_MAXIMAL_ACCESS_LE) {
4605 		if (!file_present) {
4606 			daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
4607 		} else {
4608 			ksmbd_vfs_query_maximal_access(idmap,
4609 							    path.dentry,
4610 							    &daccess);
4611 			already_permitted = true;
4612 		}
4613 		maximal_access = daccess;
4614 	}
4615 
4616 	open_flags = smb2_create_open_flags(file_present, daccess,
4617 					    req->CreateDisposition,
4618 					    &may_flags,
4619 					    req->CreateOptions,
4620 					    file_present ? d_inode(path.dentry)->i_mode : 0);
4621 
4622 	if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
4623 		if (open_flags & (O_CREAT | O_TRUNC)) {
4624 			ksmbd_debug(SMB,
4625 				    "User does not have write permission\n");
4626 			rc = -EACCES;
4627 			goto err_out;
4628 		}
4629 	}
4630 
4631 	/*create file if not present */
4632 	if (!file_present) {
4633 		rc = smb2_creat(work, &path, name, open_flags,
4634 				posix_mode,
4635 				req->CreateOptions & FILE_DIRECTORY_FILE_LE);
4636 		if (rc) {
4637 			if (rc == -ENOENT) {
4638 				rc = -EIO;
4639 				rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
4640 			}
4641 			goto err_out;
4642 		}
4643 
4644 		created = true;
4645 		idmap = mnt_idmap(path.mnt);
4646 		if (ea_buf) {
4647 			if (le32_to_cpu(ea_buf->ccontext.DataLength) <
4648 			    sizeof(struct smb2_ea_info)) {
4649 				rc = -EINVAL;
4650 				goto err_out;
4651 			}
4652 
4653 			rc = smb2_set_ea(&ea_buf->ea,
4654 					 le32_to_cpu(ea_buf->ccontext.DataLength),
4655 					 &path, false);
4656 			if (rc == -EOPNOTSUPP)
4657 				rc = 0;
4658 			else if (rc)
4659 				goto err_out;
4660 		}
4661 	} else if (!already_permitted) {
4662 		/* FILE_READ_ATTRIBUTE is allowed without inode_permission,
4663 		 * because execute(search) permission on a parent directory,
4664 		 * is already granted.
4665 		 */
4666 		if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
4667 			rc = inode_permission(idmap,
4668 					      d_inode(path.dentry),
4669 					      may_flags);
4670 			if (rc)
4671 				goto err_out;
4672 
4673 			if ((daccess & FILE_DELETE_LE) ||
4674 			    (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
4675 				rc = inode_permission(idmap,
4676 						      d_inode(path.dentry->d_parent),
4677 						      MAY_EXEC | MAY_WRITE);
4678 				if (rc)
4679 					goto err_out;
4680 			}
4681 		}
4682 	}
4683 
4684 	rc = ksmbd_query_inode_status(path.dentry->d_parent);
4685 	if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
4686 		rc = -EBUSY;
4687 		goto err_out;
4688 	}
4689 
4690 	rc = 0;
4691 	filp = dentry_open(&path, open_flags, current_cred());
4692 	if (IS_ERR(filp)) {
4693 		rc = PTR_ERR(filp);
4694 		pr_err("dentry open for dir failed, rc %d\n", rc);
4695 		goto err_out;
4696 	}
4697 
4698 	if (file_present) {
4699 		if (!(open_flags & O_TRUNC))
4700 			file_info = FILE_OPENED;
4701 		else
4702 			file_info = FILE_OVERWRITTEN;
4703 
4704 		if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
4705 		    FILE_SUPERSEDE_LE)
4706 			file_info = FILE_SUPERSEDED;
4707 	} else if (open_flags & O_CREAT) {
4708 		file_info = FILE_CREATED;
4709 	}
4710 
4711 	ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
4712 
4713 	/* Obtain Volatile-ID */
4714 	fp = ksmbd_open_fd(work, filp);
4715 	if (IS_ERR(fp)) {
4716 		fput(filp);
4717 		rc = PTR_ERR(fp);
4718 		fp = NULL;
4719 		goto err_out;
4720 	}
4721 
4722 	/* Get Persistent-ID */
4723 	ksmbd_open_durable_fd(fp);
4724 	if (!has_file_id(fp->persistent_id)) {
4725 		rc = -ENOMEM;
4726 		goto err_out;
4727 	}
4728 
4729 	/*
4730 	 * Publish the client and create GUID before an oplock/lease break can
4731 	 * make this CREATE pending.  A replay of that in-flight CREATE must find
4732 	 * this FP_NEW handle and fail with STATUS_FILE_NOT_AVAILABLE instead of
4733 	 * waiting on the same break again.
4734 	 */
4735 	memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
4736 	if (dh_info.app_instance_id) {
4737 		memcpy(fp->app_instance_id, dh_info.AppInstanceId,
4738 		       SMB2_CREATE_GUID_SIZE);
4739 		fp->has_app_instance_id = true;
4740 	}
4741 	if (dh_info.app_instance_version_valid) {
4742 		fp->app_instance_version_high =
4743 			dh_info.app_instance_version_high;
4744 		fp->app_instance_version_low = dh_info.app_instance_version_low;
4745 		fp->app_instance_version_valid = true;
4746 	}
4747 	if (dh_info.CreateGuid) {
4748 		memcpy(fp->create_guid, dh_info.CreateGuid, SMB2_CREATE_GUID_SIZE);
4749 		fp->durable_replay_consumed = dh_info.replay_consumed;
4750 		rc = ksmbd_vfs_set_durable_owner(fp, sess->user);
4751 		if (rc)
4752 			goto err_out;
4753 	}
4754 
4755 	fp->cdoption = req->CreateDisposition;
4756 	fp->create_file_attributes = req->FileAttributes;
4757 	fp->daccess = daccess;
4758 	fp->saccess = req->ShareAccess;
4759 	fp->coption = req->CreateOptions;
4760 
4761 	/* Set default windows and posix acls if creating new file */
4762 	if (created) {
4763 		int posix_acl_rc;
4764 		struct inode *inode = d_inode(path.dentry);
4765 
4766 		posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
4767 							   &path,
4768 							   d_inode(path.dentry->d_parent));
4769 		if (posix_acl_rc)
4770 			ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
4771 
4772 		rc = smb2_create_sd_buffer(work, req, &path);
4773 		if (rc && rc != -ENOENT)
4774 			goto err_out;
4775 
4776 		if (rc == -ENOENT) {
4777 			if (test_share_config_flag(work->tcon->share_conf,
4778 						   KSMBD_SHARE_FLAG_ACL_XATTR)) {
4779 				rc = smb_inherit_dacl(conn, &path, sess->user->uid,
4780 						      sess->user->gid);
4781 			}
4782 			if (rc) {
4783 				if (posix_acl_rc)
4784 					ksmbd_vfs_set_init_posix_acl(idmap,
4785 								     &path);
4786 
4787 				if (test_share_config_flag(work->tcon->share_conf,
4788 							   KSMBD_SHARE_FLAG_ACL_XATTR)) {
4789 					struct smb_fattr fattr;
4790 					struct smb_ntsd *pntsd;
4791 					int pntsd_size;
4792 					size_t scratch_len;
4793 
4794 					ksmbd_acls_fattr(&fattr, idmap, inode);
4795 					scratch_len = smb_acl_sec_desc_scratch_len(&fattr,
4796 							NULL, 0,
4797 							OWNER_SECINFO | GROUP_SECINFO |
4798 							DACL_SECINFO);
4799 					if (!scratch_len || scratch_len == SIZE_MAX) {
4800 						rc = -EFBIG;
4801 						posix_acl_release(fattr.cf_acls);
4802 						posix_acl_release(fattr.cf_dacls);
4803 						goto err_out;
4804 					}
4805 
4806 					pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
4807 					if (!pntsd) {
4808 						rc = -ENOMEM;
4809 						posix_acl_release(fattr.cf_acls);
4810 						posix_acl_release(fattr.cf_dacls);
4811 						goto err_out;
4812 					}
4813 
4814 					rc = build_sec_desc(idmap,
4815 							    pntsd, NULL, 0,
4816 							    OWNER_SECINFO |
4817 							    GROUP_SECINFO |
4818 							    DACL_SECINFO,
4819 							    &pntsd_size, &fattr);
4820 					posix_acl_release(fattr.cf_acls);
4821 					posix_acl_release(fattr.cf_dacls);
4822 					if (rc) {
4823 						kvfree(pntsd);
4824 						goto err_out;
4825 					}
4826 
4827 					rc = ksmbd_vfs_set_sd_xattr(conn,
4828 								    idmap,
4829 								    &path,
4830 								    pntsd,
4831 								    pntsd_size,
4832 								    false);
4833 					kvfree(pntsd);
4834 					if (rc)
4835 						pr_err("failed to store ntacl in xattr : %d\n",
4836 						       rc);
4837 				}
4838 			}
4839 		}
4840 		rc = 0;
4841 	}
4842 
4843 	if (stream_name) {
4844 		rc = smb2_set_stream_name_xattr(&path,
4845 						fp,
4846 						stream_name,
4847 						s_type);
4848 		if (rc)
4849 			goto err_out;
4850 		file_info = FILE_CREATED;
4851 	}
4852 
4853 	fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
4854 			FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
4855 
4856 	fp->is_posix_ctxt = posix_ctxt;
4857 
4858 	/* fp should be searchable through ksmbd_inode.m_fp_list
4859 	 * after daccess, saccess, attrib_only, and stream are
4860 	 * initialized.
4861 	 */
4862 	down_write(&fp->f_ci->m_lock);
4863 	list_add(&fp->node, &fp->f_ci->m_fp_list);
4864 	up_write(&fp->f_ci->m_lock);
4865 
4866 	/* Check delete pending among previous fp before oplock break */
4867 	if (ksmbd_inode_pending_delete(fp)) {
4868 		rc = -EBUSY;
4869 		goto err_out;
4870 	}
4871 
4872 	if (!stream_name && daccess & FILE_DELETE_LE &&
4873 	    ksmbd_has_stream_without_delete_share(fp)) {
4874 		rc = -EPERM;
4875 		goto err_out;
4876 	}
4877 
4878 	if (file_present || created)
4879 		path_put(&path);
4880 
4881 	if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
4882 	    !fp->attrib_only && !stream_name) {
4883 		smb_break_all_oplock(work, fp);
4884 		need_truncate = 1;
4885 	}
4886 
4887 	share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
4888 	if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
4889 	    (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
4890 	     !(conn->vals->req_capabilities & SMB2_GLOBAL_CAP_LEASING))) {
4891 		if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
4892 			rc = share_ret;
4893 			goto err_out1;
4894 		}
4895 	} else {
4896 		if (created && !lc)
4897 			smb_send_parent_lease_break_noti(fp, NULL);
4898 
4899 		if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && lc) {
4900 			if (S_ISDIR(file_inode(filp)->i_mode)) {
4901 				lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
4902 				lc->is_dir = true;
4903 			}
4904 
4905 			/*
4906 			 * Compare parent lease using parent key. If there is no
4907 			 * a lease that has same parent key, Send lease break
4908 			 * notification.
4909 			 */
4910 			smb_send_parent_lease_break_noti(fp, lc);
4911 
4912 			req_op_level = smb2_map_lease_to_oplock(lc->req_state);
4913 			ksmbd_debug(SMB,
4914 				    "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
4915 				    name, req_op_level, lc->req_state);
4916 			rc = find_same_lease_key(conn, fp->f_ci, lc);
4917 			if (rc)
4918 				goto err_out1;
4919 		} else if (open_flags == O_RDONLY &&
4920 			   (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
4921 			    req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
4922 			req_op_level = SMB2_OPLOCK_LEVEL_II;
4923 
4924 		rc = smb_grant_oplock(work, req_op_level,
4925 				      fp->persistent_id, fp,
4926 				      le32_to_cpu(req->hdr.Id.SyncId.TreeId),
4927 				      lc, share_ret,
4928 				      smb3_hdr_replay(&req->hdr));
4929 		if (rc < 0)
4930 			goto err_out1;
4931 	}
4932 
4933 	if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
4934 		smb_break_all_levII_oplock_for_delete(work, fp);
4935 		ksmbd_fd_set_delete_on_close(fp, file_info);
4936 	}
4937 
4938 	if (need_truncate) {
4939 		rc = smb2_create_truncate(&fp->filp->f_path);
4940 		if (rc)
4941 			goto err_out1;
4942 	}
4943 
4944 	if (req->CreateContextsOffset) {
4945 		struct create_alloc_size_req *az_req;
4946 
4947 		az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
4948 					SMB2_CREATE_ALLOCATION_SIZE, 4);
4949 		if (IS_ERR(az_req)) {
4950 			rc = PTR_ERR(az_req);
4951 			goto err_out1;
4952 		} else if (az_req) {
4953 			int err;
4954 
4955 			if (le16_to_cpu(az_req->ccontext.DataOffset) +
4956 			    le32_to_cpu(az_req->ccontext.DataLength) <
4957 			    sizeof(struct create_alloc_size_req)) {
4958 				rc = -EINVAL;
4959 				goto err_out1;
4960 			}
4961 			alloc_size = le64_to_cpu(az_req->AllocationSize);
4962 			fp->allocation_size_set = true;
4963 			ksmbd_debug(SMB,
4964 				    "request smb2 create allocate size : %llu\n",
4965 				    alloc_size);
4966 			/*
4967 			 * fp->filp is the base file's data fork for a stream
4968 			 * handle (streams are xattr-backed on the same
4969 			 * underlying file) -- fallocate has no meaning for a
4970 			 * stream and would otherwise pre-allocate storage on
4971 			 * the base file's data instead.
4972 			 */
4973 			if (!ksmbd_stream_fd(fp)) {
4974 				smb_break_all_levII_oplock(work, fp, 1);
4975 				err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
4976 						    alloc_size);
4977 				if (err < 0)
4978 					ksmbd_debug(SMB,
4979 						    "vfs_fallocate is failed : %d\n",
4980 						    err);
4981 			}
4982 		}
4983 
4984 		context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
4985 		if (IS_ERR(context)) {
4986 			rc = PTR_ERR(context);
4987 			goto err_out1;
4988 		} else if (context) {
4989 			ksmbd_debug(SMB, "get query on disk id context\n");
4990 			query_disk_id = 1;
4991 		}
4992 
4993 		if (test_share_config_flag(share, KSMBD_SHARE_FLAG_TIME_MACHINE)) {
4994 			context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
4995 			if (IS_ERR(context)) {
4996 				rc = PTR_ERR(context);
4997 				goto err_out1;
4998 			} else if (context) {
4999 				struct aapl_server_query_req *aapl_req;
5000 
5001 				if (le32_to_cpu(context->DataLength) <
5002 				    sizeof(struct aapl_server_query_req)) {
5003 					rc = -EINVAL;
5004 					goto err_out1;
5005 				}
5006 
5007 				aapl_req = (struct aapl_server_query_req *)
5008 					((char *)context +
5009 					 le16_to_cpu(context->DataOffset));
5010 				if (le32_to_cpu(aapl_req->cmd) ==
5011 				    SMB2_CRTCTX_AAPL_SERVER_QUERY) {
5012 					conn->is_aapl = true;
5013 					aapl_ctxt = true;
5014 					aapl_req_bitmap = le64_to_cpu(aapl_req->req_bitmap);
5015 					aapl_client_caps = le64_to_cpu(aapl_req->client_caps);
5016 				}
5017 			}
5018 		} else if (conn->is_aapl == false) {
5019 			context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
5020 			if (IS_ERR(context)) {
5021 				rc = PTR_ERR(context);
5022 				goto err_out1;
5023 			} else if (context)
5024 				conn->is_aapl = true;
5025 		}
5026 	}
5027 
5028 	rc = ksmbd_vfs_getattr(&path, &stat);
5029 	if (rc)
5030 		goto err_out1;
5031 
5032 	if (stat.result_mask & STATX_BTIME)
5033 		fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
5034 	else
5035 		fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
5036 	fp->change_time = ksmbd_UnixTimeToNT(stat.ctime);
5037 	fp->allocation_size = S_ISDIR(stat.mode) ? 0 :
5038 		(alloc_size ?: stat.blocks << 9);
5039 	if (created || fp->f_ci->m_fattr == 0)
5040 		fp->f_ci->m_fattr =
5041 			cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
5042 
5043 	if (!created)
5044 		smb2_update_xattrs(tcon, &path, fp);
5045 	if (need_truncate && req->FileAttributes) {
5046 		dos_attr = le32_to_cpu(req->FileAttributes);
5047 		fp->f_ci->m_fattr =
5048 			cpu_to_le32(smb2_get_dos_mode(&stat, dos_attr));
5049 		smb2_new_xattrs(tcon, &path, fp);
5050 	}
5051 
5052 	ksmbd_vfs_update_compressed_fattr(path.dentry, &fp->f_ci->m_fattr);
5053 
5054 	if (created) {
5055 		if (fp->coption & FILE_NO_COMPRESSION_LE) {
5056 			rc = ksmbd_vfs_set_compression_create(work, fp,
5057 							      COMPRESSION_FORMAT_NONE);
5058 			if (rc)
5059 				fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_COMPRESSED_LE;
5060 			rc = 0;
5061 		} else if (smb2_parent_compressed(tcon, &path)) {
5062 			rc = ksmbd_vfs_set_compression_create(work, fp,
5063 							      COMPRESSION_FORMAT_LZNT1);
5064 			if (rc)
5065 				fp->f_ci->m_fattr |= FILE_ATTRIBUTE_COMPRESSED_LE;
5066 			rc = 0;
5067 		}
5068 	}
5069 
5070 	if (created)
5071 		smb2_new_xattrs(tcon, &path, fp);
5072 
5073 	fp->create_action = cpu_to_le32(file_info);
5074 
5075 	if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
5076 		if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent &&
5077 		    test_share_config_flag(work->tcon->share_conf,
5078 					   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY) &&
5079 		    (conn->vals->req_capabilities &
5080 			     SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)) {
5081 			/* MS-SMB2 3.3.5.9.10: a persistent open is durable too. */
5082 			fp->is_durable = true;
5083 			fp->is_persistent = true;
5084 		} else {
5085 			fp->is_durable = true;
5086 		}
5087 		if (dh_info.type == DURABLE_REQ_V2) {
5088 			if (dh_info.app_instance_id)
5089 				memcpy(fp->app_instance_id,
5090 				       dh_info.AppInstanceId,
5091 				       SMB2_CREATE_GUID_SIZE);
5092 			if (dh_info.timeout)
5093 				fp->durable_timeout =
5094 					min_t(unsigned int, dh_info.timeout,
5095 					      DURABLE_HANDLE_MAX_TIMEOUT);
5096 			else
5097 				fp->durable_timeout = 60000;
5098 		}
5099 	}
5100 
5101 	/*
5102 	 * conn->is_aapl detection above (this function's create-context
5103 	 * parsing) is skipped on the reconnect path below, since a
5104 	 * reconnect always arrives on a fresh connection -- if the client
5105 	 * cares, it sends its own AAPL context on this same CREATE, which
5106 	 * this function's normal (non-reconnect) parsing already handles.
5107 	 */
5108 	reconnected_fp:
5109 	if (dh_info.replay)
5110 		file_info = le32_to_cpu(fp->create_action);
5111 	rsp->StructureSize = cpu_to_le16(89);
5112 	opinfo = opinfo_get(fp);
5113 	rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
5114 	/*
5115 	 * A durable CREATE replay does not modify the existing open. When
5116 	 * replayed without an oplock, however, its response reflects that
5117 	 * request and cannot include a new durable-handle response context.
5118 	 */
5119 	if (dh_info.replay && !lc &&
5120 	    req_op_level == SMB2_OPLOCK_LEVEL_NONE) {
5121 		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
5122 		durable_rsp = false;
5123 	}
5124 	rsp->Flags = 0;
5125 	rsp->CreateAction = cpu_to_le32(file_info);
5126 	rsp->CreationTime = cpu_to_le64(fp->create_time);
5127 	time = ksmbd_UnixTimeToNT(stat.atime);
5128 	rsp->LastAccessTime = cpu_to_le64(time);
5129 	time = ksmbd_UnixTimeToNT(stat.mtime);
5130 	fp->open_mtime = time;
5131 	rsp->LastWriteTime = cpu_to_le64(time);
5132 	rsp->ChangeTime = cpu_to_le64(fp->change_time);
5133 	/*
5134 	 * The cached allocation size hides filesystem rounding for the
5135 	 * requested allocation, but it can go stale when the file grows past
5136 	 * it via writes (e.g. across a durable reconnect). Refresh it once the
5137 	 * file exceeds the cached value, rounding the end of file up to the
5138 	 * volume allocation unit (the filesystem block size, matching the
5139 	 * SectorsPerAllocationUnit/BytesPerSector ksmbd advertises) rather than
5140 	 * using the raw on-disk block count, which can include filesystem
5141 	 * preallocation and metadata rounding.
5142 	 */
5143 	if (ksmbd_stream_fd(fp)) {
5144 		loff_t seof = ksmbd_stream_eof(fp);
5145 
5146 		rsp->AllocationSize = cpu_to_le64((u64)seof);
5147 		rsp->EndofFile = cpu_to_le64((u64)seof);
5148 	} else {
5149 		if (!S_ISDIR(stat.mode) && stat.size > fp->allocation_size)
5150 			fp->allocation_size = round_up(stat.size, stat.blksize);
5151 		rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
5152 		rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5153 	}
5154 	rsp->FileAttributes = fp->f_ci->m_fattr;
5155 
5156 	rsp->Reserved2 = 0;
5157 
5158 	rsp->PersistentFileId = fp->persistent_id;
5159 	rsp->VolatileFileId = fp->volatile_id;
5160 
5161 	rsp->CreateContextsOffset = 0;
5162 	rsp->CreateContextsLength = 0;
5163 	iov_len = offsetof(struct smb2_create_rsp, Buffer);
5164 
5165 	/* If lease is request send lease context response */
5166 	if (opinfo && opinfo->is_lease) {
5167 		struct create_context *lease_ccontext;
5168 
5169 		ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
5170 			    name, opinfo->o_lease->state);
5171 		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
5172 
5173 		lease_ccontext = (struct create_context *)rsp->Buffer;
5174 		contxt_cnt++;
5175 		create_lease_buf(rsp->Buffer, opinfo->o_lease);
5176 		le32_add_cpu(&rsp->CreateContextsLength,
5177 			     conn->vals->create_lease_size);
5178 		iov_len += conn->vals->create_lease_size;
5179 		next_ptr = &lease_ccontext->Next;
5180 		next_off = conn->vals->create_lease_size;
5181 	}
5182 	opinfo_put(opinfo);
5183 
5184 	if (maximal_access_ctxt) {
5185 		struct create_context *mxac_ccontext;
5186 
5187 		if (maximal_access == 0)
5188 			ksmbd_vfs_query_maximal_access(idmap,
5189 						       path.dentry,
5190 						       &maximal_access);
5191 		mxac_ccontext = (struct create_context *)(rsp->Buffer +
5192 				le32_to_cpu(rsp->CreateContextsLength));
5193 		contxt_cnt++;
5194 		create_mxac_rsp_buf(rsp->Buffer +
5195 				le32_to_cpu(rsp->CreateContextsLength),
5196 				le32_to_cpu(maximal_access));
5197 		le32_add_cpu(&rsp->CreateContextsLength,
5198 			     conn->vals->create_mxac_size);
5199 		iov_len += conn->vals->create_mxac_size;
5200 		if (next_ptr)
5201 			*next_ptr = cpu_to_le32(next_off);
5202 		next_ptr = &mxac_ccontext->Next;
5203 		next_off = conn->vals->create_mxac_size;
5204 	}
5205 
5206 	if (query_disk_id) {
5207 		struct create_context *disk_id_ccontext;
5208 
5209 		disk_id_ccontext = (struct create_context *)(rsp->Buffer +
5210 				le32_to_cpu(rsp->CreateContextsLength));
5211 		contxt_cnt++;
5212 		create_disk_id_rsp_buf(rsp->Buffer +
5213 				le32_to_cpu(rsp->CreateContextsLength),
5214 				stat.ino, tcon->id);
5215 		le32_add_cpu(&rsp->CreateContextsLength,
5216 			     conn->vals->create_disk_id_size);
5217 		iov_len += conn->vals->create_disk_id_size;
5218 		if (next_ptr)
5219 			*next_ptr = cpu_to_le32(next_off);
5220 		next_ptr = &disk_id_ccontext->Next;
5221 		next_off = conn->vals->create_disk_id_size;
5222 	}
5223 
5224 	if (durable_rsp &&
5225 	    (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2)) {
5226 		struct create_context *durable_ccontext;
5227 
5228 		durable_ccontext = (struct create_context *)(rsp->Buffer +
5229 				le32_to_cpu(rsp->CreateContextsLength));
5230 		contxt_cnt++;
5231 		if (dh_info.type == DURABLE_REQ) {
5232 			create_durable_rsp_buf(rsp->Buffer +
5233 					le32_to_cpu(rsp->CreateContextsLength));
5234 			le32_add_cpu(&rsp->CreateContextsLength,
5235 					conn->vals->create_durable_size);
5236 			iov_len += conn->vals->create_durable_size;
5237 		} else {
5238 			create_durable_v2_rsp_buf(rsp->Buffer +
5239 					le32_to_cpu(rsp->CreateContextsLength),
5240 					fp);
5241 			le32_add_cpu(&rsp->CreateContextsLength,
5242 					conn->vals->create_durable_v2_size);
5243 			iov_len += conn->vals->create_durable_v2_size;
5244 		}
5245 
5246 		if (next_ptr)
5247 			*next_ptr = cpu_to_le32(next_off);
5248 		next_ptr = &durable_ccontext->Next;
5249 		next_off = dh_info.type == DURABLE_REQ ?
5250 			conn->vals->create_durable_size :
5251 			conn->vals->create_durable_v2_size;
5252 	}
5253 
5254 	if (posix_ctxt) {
5255 		struct create_context *posix_ccontext;
5256 
5257 		posix_ccontext = (struct create_context *)(rsp->Buffer +
5258 				le32_to_cpu(rsp->CreateContextsLength));
5259 		contxt_cnt++;
5260 		create_posix_rsp_buf(rsp->Buffer +
5261 				le32_to_cpu(rsp->CreateContextsLength),
5262 				fp);
5263 		le32_add_cpu(&rsp->CreateContextsLength,
5264 			     conn->vals->create_posix_size);
5265 		iov_len += conn->vals->create_posix_size;
5266 		if (next_ptr)
5267 			*next_ptr = cpu_to_le32(next_off);
5268 		next_ptr = &posix_ccontext->Next;
5269 		next_off = conn->vals->create_posix_size;
5270 	}
5271 
5272 	/*
5273 	 * AAPL create context response: see smb2pdu.h for the capability
5274 	 * rationale. Scoped to TIME_MACHINE shares only.
5275 	 */
5276 	if (aapl_ctxt) {
5277 		if (aapl_client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR)
5278 			conn->aapl_readdir_attr = true;
5279 		/*
5280 		 * V2 extends the same inline-FinderInfo mechanism (see
5281 		 * smb2pdu.h), so a V2-requesting client also gets
5282 		 * aapl_readdir_attr treatment -- the reply just advertises
5283 		 * the V2 bit instead of the V1 one (create_aapl_rsp_buf).
5284 		 */
5285 		if (aapl_client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR_V2) {
5286 			conn->aapl_readdir_attr = true;
5287 			conn->aapl_readdir_attr_v2 = true;
5288 		}
5289 
5290 		contxt_cnt++;
5291 		create_aapl_rsp_buf(rsp->Buffer +
5292 				le32_to_cpu(rsp->CreateContextsLength),
5293 				SMB2_CRTCTX_AAPL_FULL_SYNC,
5294 				aapl_req_bitmap,
5295 				conn->aapl_readdir_attr_v2);
5296 		le32_add_cpu(&rsp->CreateContextsLength,
5297 			     conn->vals->create_aapl_size);
5298 		iov_len += conn->vals->create_aapl_size;
5299 		if (next_ptr)
5300 			*next_ptr = cpu_to_le32(next_off);
5301 		/* AAPL is last; next_ptr need not be updated */
5302 	}
5303 
5304 	if (contxt_cnt > 0) {
5305 		rsp->CreateContextsOffset =
5306 			cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
5307 	}
5308 
5309 err_out:
5310 	if (rc && (file_present || created))
5311 		path_put(&path);
5312 
5313 err_out1:
5314 	ksmbd_revert_fsids(work);
5315 
5316 err_out2:
5317 	if (!rc) {
5318 		if (!dh_info.replay)
5319 			rc = ksmbd_update_fstate(&work->sess->file_table, fp,
5320 						 FP_INITED);
5321 		if (!rc)
5322 			rc = smb2_set_request_open(work, fp, &req->hdr, false, false);
5323 		if (!rc)
5324 			rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
5325 	}
5326 	if (rc) {
5327 		if (rc == -EINVAL)
5328 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5329 		else if (rc == -EOPNOTSUPP)
5330 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
5331 		else if ((rc == -EACCES || rc == -ESTALE || rc == -EXDEV) &&
5332 			 !rsp->hdr.Status) {
5333 			if (req->DesiredAccess & FILE_ACCESS_SYSTEM_SECURITY_LE)
5334 				rsp->hdr.Status = STATUS_PRIVILEGE_NOT_HELD;
5335 			else
5336 				rsp->hdr.Status = STATUS_ACCESS_DENIED;
5337 		}
5338 		else if (rc == -ENOENT)
5339 			rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
5340 		else if (rc == -EPERM)
5341 			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
5342 		else if (rc == -EBUSY)
5343 			rsp->hdr.Status = STATUS_DELETE_PENDING;
5344 		else if (rc == -EBADF)
5345 			rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
5346 		else if (rc == -ENOEXEC)
5347 			rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
5348 		else if (rc == -ENXIO)
5349 			rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
5350 		else if (rc == -EEXIST)
5351 			rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
5352 		else if (rc == -EMFILE)
5353 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5354 		else if (rc == -EINPROGRESS)
5355 			rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
5356 		else if (rc == -EAGAIN)
5357 			rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
5358 		if (!rsp->hdr.Status)
5359 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5360 
5361 		if (fp && !dh_info.replay)
5362 			ksmbd_fd_put(work, fp);
5363 		smb2_set_err_rsp(work);
5364 		ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
5365 	}
5366 
5367 	if (dh_info.replay)
5368 		ksmbd_put_durable_fd(dh_info.fp);
5369 
5370 	if (dh_info.reconnected) {
5371 		/*
5372 		 * If reconnect succeeded, fp was republished in the
5373 		 * session file table.  On a later error, ksmbd_fd_put()
5374 		 * above drops the session reference; drop the durable
5375 		 * lookup reference through the same session-aware path so
5376 		 * final close removes the volatile id before freeing fp.
5377 		 */
5378 		if (rc && fp == dh_info.fp)
5379 			ksmbd_fd_put(work, dh_info.fp);
5380 		else
5381 			ksmbd_put_durable_fd(dh_info.fp);
5382 	}
5383 
5384 	kfree(name);
5385 	kfree(lc);
5386 
5387 	return rc;
5388 }
5389 
5390 static int readdir_info_level_struct_sz(int info_level)
5391 {
5392 	switch (info_level) {
5393 	case FILE_FULL_DIRECTORY_INFORMATION:
5394 		return sizeof(FILE_FULL_DIRECTORY_INFO);
5395 	case FILE_BOTH_DIRECTORY_INFORMATION:
5396 		return sizeof(FILE_BOTH_DIRECTORY_INFO);
5397 	case FILE_DIRECTORY_INFORMATION:
5398 		return sizeof(FILE_DIRECTORY_INFO);
5399 	case FILE_NAMES_INFORMATION:
5400 		return sizeof(struct file_names_info);
5401 	case FILEID_FULL_DIRECTORY_INFORMATION:
5402 		return sizeof(FILE_ID_FULL_DIR_INFO);
5403 	case FILEID_BOTH_DIRECTORY_INFORMATION:
5404 		return sizeof(struct file_id_both_directory_info);
5405 	case SMB_FIND_FILE_POSIX_INFO:
5406 		return sizeof(struct smb2_posix_info);
5407 	default:
5408 		return -EOPNOTSUPP;
5409 	}
5410 }
5411 
5412 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
5413 {
5414 	switch (info_level) {
5415 	case FILE_FULL_DIRECTORY_INFORMATION:
5416 	{
5417 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
5418 
5419 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->rptr;
5420 		d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
5421 		d_info->name = ffdinfo->FileName;
5422 		d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
5423 		return 0;
5424 	}
5425 	case FILE_BOTH_DIRECTORY_INFORMATION:
5426 	{
5427 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
5428 
5429 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->rptr;
5430 		d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
5431 		d_info->name = fbdinfo->FileName;
5432 		d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
5433 		return 0;
5434 	}
5435 	case FILE_DIRECTORY_INFORMATION:
5436 	{
5437 		FILE_DIRECTORY_INFO *fdinfo;
5438 
5439 		fdinfo = (FILE_DIRECTORY_INFO *)d_info->rptr;
5440 		d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
5441 		d_info->name = fdinfo->FileName;
5442 		d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
5443 		return 0;
5444 	}
5445 	case FILE_NAMES_INFORMATION:
5446 	{
5447 		struct file_names_info *fninfo;
5448 
5449 		fninfo = (struct file_names_info *)d_info->rptr;
5450 		d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
5451 		d_info->name = fninfo->FileName;
5452 		d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
5453 		return 0;
5454 	}
5455 	case FILEID_FULL_DIRECTORY_INFORMATION:
5456 	{
5457 		FILE_ID_FULL_DIR_INFO *dinfo;
5458 
5459 		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->rptr;
5460 		d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
5461 		d_info->name = dinfo->FileName;
5462 		d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
5463 		return 0;
5464 	}
5465 	case FILEID_BOTH_DIRECTORY_INFORMATION:
5466 	{
5467 		struct file_id_both_directory_info *fibdinfo;
5468 
5469 		fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
5470 		d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
5471 		d_info->name = fibdinfo->FileName;
5472 		d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
5473 		return 0;
5474 	}
5475 	case SMB_FIND_FILE_POSIX_INFO:
5476 	{
5477 		struct smb2_posix_info *posix_info;
5478 
5479 		posix_info = (struct smb2_posix_info *)d_info->rptr;
5480 		d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
5481 		d_info->name = posix_info->name;
5482 		d_info->name_len = le32_to_cpu(posix_info->name_len);
5483 		return 0;
5484 	}
5485 	default:
5486 		return -EINVAL;
5487 	}
5488 }
5489 
5490 /**
5491  * smb2_populate_readdir_entry() - encode directory entry in smb2 response
5492  * buffer
5493  * @conn:	connection instance
5494  * @info_level:	smb information level
5495  * @d_info:	structure included variables for query dir
5496  * @ksmbd_kstat:	ksmbd wrapper of dirent stat information
5497  *
5498  * if directory has many entries, find first can't read it fully.
5499  * find next might be called multiple times to read remaining dir entries
5500  *
5501  * Return:	0 on success, otherwise error
5502  */
5503 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
5504 				       struct ksmbd_dir_info *d_info,
5505 				       struct ksmbd_kstat *ksmbd_kstat)
5506 {
5507 	int next_entry_offset = 0;
5508 	char *conv_name;
5509 	int conv_len;
5510 	void *kstat;
5511 	int struct_sz, rc = 0;
5512 
5513 	conv_name = ksmbd_convert_dir_info_name(d_info,
5514 						conn->local_nls,
5515 						&conv_len);
5516 	if (!conv_name)
5517 		return -ENOMEM;
5518 
5519 	/* Somehow the name has only terminating NULL bytes */
5520 	if (conv_len < 0) {
5521 		rc = -EINVAL;
5522 		goto free_conv_name;
5523 	}
5524 
5525 	struct_sz = readdir_info_level_struct_sz(info_level);
5526 	if (struct_sz == -EOPNOTSUPP) {
5527 		rc = -EINVAL;
5528 		goto free_conv_name;
5529 	}
5530 
5531 	struct_sz += conv_len;
5532 	next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
5533 	d_info->last_entry_off_align = next_entry_offset - struct_sz;
5534 
5535 	if (next_entry_offset > d_info->out_buf_len) {
5536 		d_info->out_buf_len = 0;
5537 		rc = -ENOSPC;
5538 		goto free_conv_name;
5539 	}
5540 
5541 	kstat = d_info->wptr;
5542 	if (info_level != FILE_NAMES_INFORMATION)
5543 		kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
5544 
5545 	switch (info_level) {
5546 	case FILE_FULL_DIRECTORY_INFORMATION:
5547 	{
5548 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
5549 
5550 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)kstat;
5551 		ffdinfo->FileNameLength = cpu_to_le32(conv_len);
5552 		ffdinfo->EaSize =
5553 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5554 		if (ffdinfo->EaSize)
5555 			ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5556 		if (d_info->hide_dot_file && d_info->name[0] == '.')
5557 			ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5558 		memcpy(ffdinfo->FileName, conv_name, conv_len);
5559 		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5560 		break;
5561 	}
5562 	case FILE_BOTH_DIRECTORY_INFORMATION:
5563 	{
5564 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
5565 
5566 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)kstat;
5567 		fbdinfo->FileNameLength = cpu_to_le32(conv_len);
5568 		fbdinfo->EaSize =
5569 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5570 		if (fbdinfo->EaSize)
5571 			fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5572 		fbdinfo->ShortNameLength = 0;
5573 		fbdinfo->Reserved = 0;
5574 		if (d_info->hide_dot_file && d_info->name[0] == '.')
5575 			fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5576 		memcpy(fbdinfo->FileName, conv_name, conv_len);
5577 		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5578 		break;
5579 	}
5580 	case FILE_DIRECTORY_INFORMATION:
5581 	{
5582 		FILE_DIRECTORY_INFO *fdinfo;
5583 
5584 		fdinfo = (FILE_DIRECTORY_INFO *)kstat;
5585 		fdinfo->FileNameLength = cpu_to_le32(conv_len);
5586 		if (d_info->hide_dot_file && d_info->name[0] == '.')
5587 			fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5588 		memcpy(fdinfo->FileName, conv_name, conv_len);
5589 		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5590 		break;
5591 	}
5592 	case FILE_NAMES_INFORMATION:
5593 	{
5594 		struct file_names_info *fninfo;
5595 
5596 		fninfo = (struct file_names_info *)kstat;
5597 		fninfo->FileNameLength = cpu_to_le32(conv_len);
5598 		memcpy(fninfo->FileName, conv_name, conv_len);
5599 		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5600 		break;
5601 	}
5602 	case FILEID_FULL_DIRECTORY_INFORMATION:
5603 	{
5604 		FILE_ID_FULL_DIR_INFO *dinfo;
5605 
5606 		dinfo = (FILE_ID_FULL_DIR_INFO *)kstat;
5607 		dinfo->FileNameLength = cpu_to_le32(conv_len);
5608 		dinfo->EaSize =
5609 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5610 		if (dinfo->EaSize)
5611 			dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5612 		dinfo->Reserved = 0;
5613 		if (conn->is_aapl)
5614 			dinfo->UniqueId = 0;
5615 		else
5616 			dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
5617 		if (d_info->hide_dot_file && d_info->name[0] == '.')
5618 			dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5619 		memcpy(dinfo->FileName, conv_name, conv_len);
5620 		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5621 		break;
5622 	}
5623 	case FILEID_BOTH_DIRECTORY_INFORMATION:
5624 	{
5625 		struct file_id_both_directory_info *fibdinfo;
5626 
5627 		fibdinfo = (struct file_id_both_directory_info *)kstat;
5628 		fibdinfo->FileNameLength = cpu_to_le32(conv_len);
5629 		if (conn->is_aapl)
5630 			fibdinfo->UniqueId = 0;
5631 		else
5632 			fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
5633 		fibdinfo->ShortNameLength = 0;
5634 		fibdinfo->Reserved = 0;
5635 		if (conn->aapl_readdir_attr) {
5636 			/*
5637 			 * READDIR_ATTR wire format, confirmed against reference server's
5638 			 * reference implementation marshalling (reference implementation behavior):
5639 			 *   EaSize           = max_access (expanded specific
5640 			 *                      rights, simplified to "grant all")
5641 			 *   ShortNameLength  = 24 (fixed; not 0, despite the spec)
5642 			 *   ShortName[0..7]  = resource fork size (uint64 LE, 0 = no rfork)
5643 			 *   ShortName[8..23] = compressed FinderInfo (type+creator+flags+
5644 			 *                      ext_flags+date_added, 16 bytes LE; all
5645 			 *                      zeros means type=0/creator=0, i.e. use
5646 			 *                      the file extension for icon lookup)
5647 			 *   Reserved2        = Unix mode bits (uint16 LE)
5648 			 * Reparse-point tag is indicated via ExtFileAttributes, not EaSize.
5649 			 *
5650 			 * V2 (conn->aapl_readdir_attr_v2): ShortNameLength+Reserved
5651 			 * are read as a single flags field instead of being ignored
5652 			 * -- see smb2pdu.h for the wire-format confirmation and
5653 			 * AAPL_READDIR_ATTR_V2_NO_XATTR's meaning.
5654 			 */
5655 			__le32 reparse_tag =
5656 				smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5657 
5658 			if (reparse_tag)
5659 				fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5660 			/*
5661 			 * FILE_GENERIC_ALL_LE (0x10000000) is the raw
5662 			 * "generic all" meta-bit -- valid only in a
5663 			 * client's requested access mask, for the server
5664 			 * to expand. It has none of the specific FILE_*
5665 			 * rights bits set (FILE_LIST_DIRECTORY, FILE_TRAVERSE,
5666 			 * etc.), so reporting it here as max_access would make
5667 			 * macOS's bit-by-bit access checks fail on every
5668 			 * entry -> permanent "no entry" badges in Finder.
5669 			 * Report the actual expanded rights instead, same
5670 			 * as smb_map_generic_desired_access() does when
5671 			 * translating a client's GENERIC_ALL request.
5672 			 */
5673 			fibdinfo->EaSize = cpu_to_le32(GENERIC_ALL_FLAGS);
5674 			/*
5675 			 * The spec says ShortNameLength should be 0 when
5676 			 * there's no short name; 24 here instead matches
5677 			 * reference implementation marshalling (reference
5678 			 * behavior) for server-to-server wire parity.
5679 			 * V2 repurposes it as a flags field that is
5680 			 * interpreted; V1 doesn't. Either value is safe
5681 			 * here, so keep 24 for parity.
5682 			 */
5683 			if (conn->aapl_readdir_attr_v2) {
5684 				/*
5685 				 * V2 repurposes this field as flags (see comment
5686 				 * above) -- 24 is a V1-only convention that real
5687 				 * macOS clients ignore outright, so don't reuse it
5688 				 * here as a base value for a field V2 clients
5689 				 * actually interpret.
5690 				 */
5691 				fibdinfo->ShortNameLength = 0;
5692 				if (!ksmbd_kstat->has_ads_stream)
5693 					fibdinfo->ShortNameLength = AAPL_READDIR_ATTR_V2_NO_XATTR;
5694 			} else {
5695 				fibdinfo->ShortNameLength = 24;
5696 			}
5697 			memset(fibdinfo->ShortName, 0, sizeof(fibdinfo->ShortName));
5698 			fibdinfo->Reserved2 = cpu_to_le16(ksmbd_kstat->kstat->mode & 0xffff);
5699 		} else {
5700 			fibdinfo->EaSize =
5701 				smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5702 			if (fibdinfo->EaSize)
5703 				fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5704 			fibdinfo->Reserved2 = cpu_to_le16(0);
5705 		}
5706 		if (d_info->hide_dot_file && d_info->name[0] == '.')
5707 			fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5708 		memcpy(fibdinfo->FileName, conv_name, conv_len);
5709 		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5710 		break;
5711 	}
5712 	case SMB_FIND_FILE_POSIX_INFO:
5713 	{
5714 		struct smb2_posix_info *posix_info;
5715 		u64 time;
5716 
5717 		posix_info = (struct smb2_posix_info *)kstat;
5718 		posix_info->Ignored = 0;
5719 		posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
5720 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
5721 		posix_info->ChangeTime = cpu_to_le64(time);
5722 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
5723 		posix_info->LastAccessTime = cpu_to_le64(time);
5724 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
5725 		posix_info->LastWriteTime = cpu_to_le64(time);
5726 		posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
5727 		posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
5728 		posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
5729 		posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
5730 		posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
5731 		switch (ksmbd_kstat->kstat->mode & S_IFMT) {
5732 		case S_IFDIR:
5733 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
5734 			break;
5735 		case S_IFLNK:
5736 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
5737 			break;
5738 		case S_IFCHR:
5739 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
5740 			break;
5741 		case S_IFBLK:
5742 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
5743 			break;
5744 		case S_IFIFO:
5745 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
5746 			break;
5747 		case S_IFSOCK:
5748 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
5749 		}
5750 
5751 		posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
5752 		posix_info->DosAttributes =
5753 			S_ISDIR(ksmbd_kstat->kstat->mode) ?
5754 				FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
5755 		if (d_info->hide_dot_file && d_info->name[0] == '.')
5756 			posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5757 		/*
5758 		 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
5759 		 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
5760 		 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
5761 		 */
5762 		id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
5763 			  SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
5764 		id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
5765 			  SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
5766 		memcpy(posix_info->name, conv_name, conv_len);
5767 		posix_info->name_len = cpu_to_le32(conv_len);
5768 		posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
5769 		break;
5770 	}
5771 
5772 	} /* switch (info_level) */
5773 
5774 	d_info->last_entry_offset = d_info->data_count;
5775 	d_info->data_count += next_entry_offset;
5776 	d_info->out_buf_len -= next_entry_offset;
5777 	d_info->wptr += next_entry_offset;
5778 
5779 	ksmbd_debug(SMB,
5780 		    "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
5781 		    info_level, d_info->out_buf_len,
5782 		    next_entry_offset, d_info->data_count);
5783 
5784 free_conv_name:
5785 	kfree(conv_name);
5786 	return rc;
5787 }
5788 
5789 struct smb2_query_dir_private {
5790 	struct ksmbd_work	*work;
5791 	char			*search_pattern;
5792 	struct ksmbd_file	*dir_fp;
5793 
5794 	struct ksmbd_dir_info	*d_info;
5795 	int			info_level;
5796 };
5797 
5798 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
5799 {
5800 	struct mnt_idmap	*idmap = file_mnt_idmap(priv->dir_fp->filp);
5801 	struct kstat		kstat;
5802 	struct ksmbd_kstat	ksmbd_kstat;
5803 	int			rc;
5804 	int			i;
5805 
5806 	for (i = 0; i < priv->d_info->num_entry; i++) {
5807 		struct dentry *dent;
5808 		struct path path;
5809 
5810 		if (dentry_name(priv->d_info, priv->info_level))
5811 			return -EINVAL;
5812 
5813 		dent = lookup_one_unlocked(idmap,
5814 					   &QSTR_LEN(priv->d_info->name,
5815 						     priv->d_info->name_len),
5816 					   priv->dir_fp->filp->f_path.dentry);
5817 
5818 		if (IS_ERR(dent)) {
5819 			ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
5820 				    priv->d_info->name,
5821 				    PTR_ERR(dent));
5822 			continue;
5823 		}
5824 		if (unlikely(d_is_negative(dent))) {
5825 			dput(dent);
5826 			ksmbd_debug(SMB, "Negative dentry `%s'\n",
5827 				    priv->d_info->name);
5828 			continue;
5829 		}
5830 
5831 		if (test_share_config_flag(priv->work->tcon->share_conf,
5832 					   KSMBD_SHARE_FLAG_HIDE_UNREADABLE)) {
5833 			__le32 daccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
5834 				FILE_READ_ATTRIBUTES_LE;
5835 
5836 			path.mnt = priv->dir_fp->filp->f_path.mnt;
5837 			path.dentry = dent;
5838 			rc = smb_check_perm_dacl(priv->work->conn, &path,
5839 						 &daccess, daccess,
5840 						 priv->work->sess->user->uid,
5841 						 true);
5842 			if (rc) {
5843 				dput(dent);
5844 				continue;
5845 			}
5846 		}
5847 
5848 		ksmbd_kstat.kstat = &kstat;
5849 		if (priv->info_level != FILE_NAMES_INFORMATION) {
5850 			rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
5851 							 idmap,
5852 							 dent,
5853 							 &ksmbd_kstat);
5854 			if (rc) {
5855 				dput(dent);
5856 				continue;
5857 			}
5858 		}
5859 
5860 		rc = smb2_populate_readdir_entry(priv->work->conn,
5861 						 priv->info_level,
5862 						 priv->d_info,
5863 						 &ksmbd_kstat);
5864 		dput(dent);
5865 		if (rc)
5866 			return rc;
5867 	}
5868 	return 0;
5869 }
5870 
5871 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
5872 				   int info_level)
5873 {
5874 	int struct_sz;
5875 	int conv_len;
5876 	int next_entry_offset;
5877 
5878 	struct_sz = readdir_info_level_struct_sz(info_level);
5879 	if (struct_sz == -EOPNOTSUPP)
5880 		return -EOPNOTSUPP;
5881 
5882 	conv_len = (d_info->name_len + 1) * 2;
5883 	next_entry_offset = ALIGN(struct_sz + conv_len,
5884 				  KSMBD_DIR_INFO_ALIGNMENT);
5885 
5886 	if (next_entry_offset > d_info->out_buf_len) {
5887 		d_info->out_buf_len = 0;
5888 		return -ENOSPC;
5889 	}
5890 
5891 	switch (info_level) {
5892 	case FILE_FULL_DIRECTORY_INFORMATION:
5893 	{
5894 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
5895 
5896 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->wptr;
5897 		memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
5898 		ffdinfo->FileName[d_info->name_len] = 0x00;
5899 		ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
5900 		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5901 		break;
5902 	}
5903 	case FILE_BOTH_DIRECTORY_INFORMATION:
5904 	{
5905 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
5906 
5907 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->wptr;
5908 		memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
5909 		fbdinfo->FileName[d_info->name_len] = 0x00;
5910 		fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
5911 		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5912 		break;
5913 	}
5914 	case FILE_DIRECTORY_INFORMATION:
5915 	{
5916 		FILE_DIRECTORY_INFO *fdinfo;
5917 
5918 		fdinfo = (FILE_DIRECTORY_INFO *)d_info->wptr;
5919 		memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
5920 		fdinfo->FileName[d_info->name_len] = 0x00;
5921 		fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
5922 		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5923 		break;
5924 	}
5925 	case FILE_NAMES_INFORMATION:
5926 	{
5927 		struct file_names_info *fninfo;
5928 
5929 		fninfo = (struct file_names_info *)d_info->wptr;
5930 		memcpy(fninfo->FileName, d_info->name, d_info->name_len);
5931 		fninfo->FileName[d_info->name_len] = 0x00;
5932 		fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
5933 		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5934 		break;
5935 	}
5936 	case FILEID_FULL_DIRECTORY_INFORMATION:
5937 	{
5938 		FILE_ID_FULL_DIR_INFO *dinfo;
5939 
5940 		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->wptr;
5941 		memcpy(dinfo->FileName, d_info->name, d_info->name_len);
5942 		dinfo->FileName[d_info->name_len] = 0x00;
5943 		dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
5944 		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5945 		break;
5946 	}
5947 	case FILEID_BOTH_DIRECTORY_INFORMATION:
5948 	{
5949 		struct file_id_both_directory_info *fibdinfo;
5950 
5951 		fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
5952 		memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
5953 		fibdinfo->FileName[d_info->name_len] = 0x00;
5954 		fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
5955 		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5956 		break;
5957 	}
5958 	case SMB_FIND_FILE_POSIX_INFO:
5959 	{
5960 		struct smb2_posix_info *posix_info;
5961 
5962 		posix_info = (struct smb2_posix_info *)d_info->wptr;
5963 		memcpy(posix_info->name, d_info->name, d_info->name_len);
5964 		posix_info->name[d_info->name_len] = 0x00;
5965 		posix_info->name_len = cpu_to_le32(d_info->name_len);
5966 		posix_info->NextEntryOffset =
5967 			cpu_to_le32(next_entry_offset);
5968 		break;
5969 	}
5970 	} /* switch (info_level) */
5971 
5972 	d_info->num_entry++;
5973 	d_info->out_buf_len -= next_entry_offset;
5974 	d_info->wptr += next_entry_offset;
5975 	return 0;
5976 }
5977 
5978 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
5979 		       loff_t offset, u64 ino, unsigned int d_type)
5980 {
5981 	struct ksmbd_readdir_data	*buf;
5982 	struct smb2_query_dir_private	*priv;
5983 	struct ksmbd_dir_info		*d_info;
5984 	int				rc;
5985 
5986 	buf	= container_of(ctx, struct ksmbd_readdir_data, ctx);
5987 	priv	= buf->private;
5988 	d_info	= priv->d_info;
5989 
5990 	/* dot and dotdot entries are already reserved */
5991 	if (!strcmp(".", name) || !strcmp("..", name))
5992 		return true;
5993 	d_info->num_scan++;
5994 	if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
5995 		return true;
5996 	if (!match_pattern(name, namlen, priv->search_pattern))
5997 		return true;
5998 
5999 	d_info->name		= name;
6000 	d_info->name_len	= namlen;
6001 	rc = reserve_populate_dentry(d_info, priv->info_level);
6002 	if (rc)
6003 		return false;
6004 	if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
6005 		d_info->out_buf_len = 0;
6006 	return true;
6007 }
6008 
6009 static int verify_info_level(int info_level)
6010 {
6011 	switch (info_level) {
6012 	case FILE_FULL_DIRECTORY_INFORMATION:
6013 	case FILE_BOTH_DIRECTORY_INFORMATION:
6014 	case FILE_DIRECTORY_INFORMATION:
6015 	case FILE_NAMES_INFORMATION:
6016 	case FILEID_FULL_DIRECTORY_INFORMATION:
6017 	case FILEID_BOTH_DIRECTORY_INFORMATION:
6018 	case SMB_FIND_FILE_POSIX_INFO:
6019 		break;
6020 	default:
6021 		return -EOPNOTSUPP;
6022 	}
6023 
6024 	return 0;
6025 }
6026 
6027 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
6028 {
6029 	int free_len;
6030 
6031 	free_len = (int)(work->response_sz -
6032 		(get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
6033 	return free_len;
6034 }
6035 
6036 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
6037 				     unsigned short hdr2_len,
6038 				     unsigned int out_buf_len)
6039 {
6040 	int free_len;
6041 
6042 	if (out_buf_len > work->conn->vals->max_trans_size)
6043 		return -EINVAL;
6044 
6045 	free_len = smb2_resp_buf_len(work, hdr2_len);
6046 	if (free_len < 0)
6047 		return -EINVAL;
6048 
6049 	return min_t(int, out_buf_len, free_len);
6050 }
6051 
6052 int smb2_query_dir(struct ksmbd_work *work)
6053 {
6054 	struct ksmbd_conn *conn = work->conn;
6055 	struct smb2_query_directory_req *req;
6056 	struct smb2_query_directory_rsp *rsp;
6057 	struct ksmbd_share_config *share = work->tcon->share_conf;
6058 	struct ksmbd_file *dir_fp = NULL;
6059 	struct ksmbd_dir_info d_info;
6060 	int rc = 0;
6061 	char *srch_ptr = NULL;
6062 	unsigned char srch_flag;
6063 	int buffer_sz;
6064 	struct smb2_query_dir_private query_dir_private = {NULL, };
6065 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6066 
6067 	ksmbd_debug(SMB, "Received smb2 query directory request\n");
6068 
6069 	WORK_BUFFERS(work, req, rsp);
6070 
6071 	if (smb2_compound_has_failed(work, &rsp->hdr))
6072 		return -EACCES;
6073 
6074 	if (work->next_smb2_rcv_hdr_off &&
6075 	    !has_file_id(req->VolatileFileId)) {
6076 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6077 			    work->compound_fid);
6078 		id = work->compound_fid;
6079 		pid = work->compound_pfid;
6080 	}
6081 
6082 	if (!has_file_id(id)) {
6083 		id = req->VolatileFileId;
6084 		pid = req->PersistentFileId;
6085 	}
6086 
6087 	if (ksmbd_override_fsids(work)) {
6088 		rsp->hdr.Status = STATUS_NO_MEMORY;
6089 		smb2_set_err_rsp(work);
6090 		return -ENOMEM;
6091 	}
6092 
6093 	rc = verify_info_level(req->FileInformationClass);
6094 	if (rc) {
6095 		rc = -EFAULT;
6096 		goto err_out2;
6097 	}
6098 
6099 	dir_fp = ksmbd_lookup_fd_slow(work, id, pid);
6100 	if (!dir_fp) {
6101 		rc = -EBADF;
6102 		goto err_out2;
6103 	}
6104 
6105 	if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
6106 	    inode_permission(file_mnt_idmap(dir_fp->filp),
6107 			     file_inode(dir_fp->filp),
6108 			     MAY_READ | MAY_EXEC)) {
6109 		pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
6110 		rc = -EACCES;
6111 		goto err_out2;
6112 	}
6113 
6114 	if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
6115 		pr_err("can't do query dir for a file\n");
6116 		rc = -EINVAL;
6117 		goto err_out2;
6118 	}
6119 
6120 	srch_flag = req->Flags;
6121 	srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
6122 					  le16_to_cpu(req->FileNameLength), 1,
6123 					  conn->local_nls);
6124 	if (IS_ERR(srch_ptr)) {
6125 		ksmbd_debug(SMB, "Search Pattern not found\n");
6126 		rc = -EINVAL;
6127 		goto err_out2;
6128 	} else {
6129 		ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
6130 	}
6131 
6132 	mutex_lock(&dir_fp->readdir_lock);
6133 
6134 	if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
6135 		ksmbd_debug(SMB, "Restart directory scan\n");
6136 		generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
6137 	}
6138 
6139 	memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
6140 	d_info.wptr = (char *)rsp->Buffer;
6141 	d_info.rptr = (char *)rsp->Buffer;
6142 	d_info.out_buf_len =
6143 		smb2_calc_max_out_buf_len(work,
6144 				offsetof(struct smb2_query_directory_rsp, Buffer),
6145 				le32_to_cpu(req->OutputBufferLength));
6146 	if (d_info.out_buf_len < 0) {
6147 		rc = -EINVAL;
6148 		goto err_out;
6149 	}
6150 	d_info.flags = srch_flag;
6151 
6152 	/*
6153 	 * reserve dot and dotdot entries in head of buffer
6154 	 * in first response
6155 	 */
6156 	rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
6157 					       dir_fp, &d_info, srch_ptr,
6158 					       smb2_populate_readdir_entry);
6159 	if (rc == -ENOSPC)
6160 		rc = 0;
6161 	else if (rc)
6162 		goto err_out;
6163 
6164 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
6165 		d_info.hide_dot_file = true;
6166 
6167 	buffer_sz				= d_info.out_buf_len;
6168 	d_info.rptr				= d_info.wptr;
6169 	query_dir_private.work			= work;
6170 	query_dir_private.search_pattern	= srch_ptr;
6171 	query_dir_private.dir_fp		= dir_fp;
6172 	query_dir_private.d_info		= &d_info;
6173 	query_dir_private.info_level		= req->FileInformationClass;
6174 	dir_fp->readdir_data.private		= &query_dir_private;
6175 	set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
6176 again:
6177 	d_info.num_scan = 0;
6178 	rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
6179 	/*
6180 	 * num_entry can be 0 if the directory iteration stops before reaching
6181 	 * the end of the directory and no file is matched with the search
6182 	 * pattern.
6183 	 */
6184 	if (rc >= 0 && !d_info.num_entry && d_info.num_scan &&
6185 	    d_info.out_buf_len > 0)
6186 		goto again;
6187 	/*
6188 	 * req->OutputBufferLength is too small to contain even one entry.
6189 	 * In this case, it immediately returns OutputBufferLength 0 to client.
6190 	 */
6191 	if (!d_info.out_buf_len && !d_info.num_entry)
6192 		goto no_buf_len;
6193 	if (rc > 0 || rc == -ENOSPC)
6194 		rc = 0;
6195 	else if (rc)
6196 		goto err_out;
6197 
6198 	d_info.wptr = d_info.rptr;
6199 	d_info.out_buf_len = buffer_sz;
6200 	rc = process_query_dir_entries(&query_dir_private);
6201 	if (rc)
6202 		goto err_out;
6203 
6204 	if (!d_info.data_count && d_info.out_buf_len >= 0) {
6205 		if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
6206 			rsp->hdr.Status = STATUS_NO_SUCH_FILE;
6207 		} else {
6208 			dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
6209 			rsp->hdr.Status = STATUS_NO_MORE_FILES;
6210 		}
6211 		rsp->StructureSize = cpu_to_le16(9);
6212 		rsp->OutputBufferOffset = cpu_to_le16(0);
6213 		rsp->OutputBufferLength = cpu_to_le32(0);
6214 		rsp->Buffer[0] = 0;
6215 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6216 				       offsetof(struct smb2_query_directory_rsp, Buffer)
6217 				       + 1);
6218 		if (rc)
6219 			goto err_out;
6220 	} else {
6221 no_buf_len:
6222 		((FILE_DIRECTORY_INFO *)
6223 		((char *)rsp->Buffer + d_info.last_entry_offset))
6224 		->NextEntryOffset = 0;
6225 		if (d_info.data_count >= d_info.last_entry_off_align)
6226 			d_info.data_count -= d_info.last_entry_off_align;
6227 
6228 		rsp->StructureSize = cpu_to_le16(9);
6229 		rsp->OutputBufferOffset = cpu_to_le16(72);
6230 		rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
6231 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6232 				       offsetof(struct smb2_query_directory_rsp, Buffer) +
6233 				       d_info.data_count);
6234 		if (rc)
6235 			goto err_out;
6236 	}
6237 
6238 	mutex_unlock(&dir_fp->readdir_lock);
6239 	kfree(srch_ptr);
6240 	ksmbd_fd_put(work, dir_fp);
6241 	ksmbd_revert_fsids(work);
6242 	return 0;
6243 
6244 err_out:
6245 	pr_err("error while processing smb2 query dir rc = %d\n", rc);
6246 	mutex_unlock(&dir_fp->readdir_lock);
6247 	kfree(srch_ptr);
6248 
6249 err_out2:
6250 	if (rc == -EINVAL)
6251 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6252 	else if (rc == -EACCES)
6253 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
6254 	else if (rc == -ENOENT)
6255 		rsp->hdr.Status = STATUS_NO_SUCH_FILE;
6256 	else if (rc == -EBADF)
6257 		rsp->hdr.Status = STATUS_FILE_CLOSED;
6258 	else if (rc == -ENOMEM)
6259 		rsp->hdr.Status = STATUS_NO_MEMORY;
6260 	else if (rc == -EFAULT)
6261 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6262 	else if (rc == -EIO)
6263 		rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
6264 	if (!rsp->hdr.Status)
6265 		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6266 
6267 	smb2_set_err_rsp(work);
6268 	ksmbd_fd_put(work, dir_fp);
6269 	ksmbd_revert_fsids(work);
6270 	return rc;
6271 }
6272 
6273 /**
6274  * buffer_check_err() - helper function to check buffer errors
6275  * @reqOutputBufferLength:	max buffer length expected in command response
6276  * @fixed_len:			minimum fixed response length
6277  * @rsp:		query info response buffer contains output buffer length
6278  *
6279  * Return:	0 on success, otherwise error
6280  */
6281 static int buffer_check_err(int reqOutputBufferLength,
6282 			    unsigned int fixed_len,
6283 			    struct smb2_query_info_rsp *rsp)
6284 {
6285 	unsigned int output_len = le32_to_cpu(rsp->OutputBufferLength);
6286 
6287 	if (reqOutputBufferLength < fixed_len) {
6288 		pr_err("Invalid Buffer Size Requested\n");
6289 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
6290 		return -EINVAL;
6291 	}
6292 
6293 	if (reqOutputBufferLength < output_len) {
6294 		rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
6295 		rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
6296 	}
6297 	return 0;
6298 }
6299 
6300 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp)
6301 {
6302 	struct smb2_file_standard_info *sinfo;
6303 
6304 	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
6305 
6306 	sinfo->AllocationSize = cpu_to_le64(4096);
6307 	sinfo->EndOfFile = cpu_to_le64(0);
6308 	sinfo->NumberOfLinks = cpu_to_le32(1);
6309 	sinfo->DeletePending = 1;
6310 	sinfo->Directory = 0;
6311 	rsp->OutputBufferLength =
6312 		cpu_to_le32(sizeof(struct smb2_file_standard_info));
6313 }
6314 
6315 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num)
6316 {
6317 	struct smb2_file_internal_info *file_info;
6318 
6319 	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
6320 
6321 	/* any unique number */
6322 	file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
6323 	rsp->OutputBufferLength =
6324 		cpu_to_le32(sizeof(struct smb2_file_internal_info));
6325 }
6326 
6327 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
6328 				   struct smb2_query_info_req *req,
6329 				   struct smb2_query_info_rsp *rsp)
6330 {
6331 	u64 id;
6332 	int rc;
6333 
6334 	/*
6335 	 * Windows can sometime send query file info request on
6336 	 * pipe without opening it, checking error condition here
6337 	 */
6338 	id = req->VolatileFileId;
6339 
6340 	lockdep_assert_not_held(&sess->rpc_lock);
6341 
6342 	down_read(&sess->rpc_lock);
6343 	if (!ksmbd_session_rpc_method(sess, id)) {
6344 		up_read(&sess->rpc_lock);
6345 		return -ENOENT;
6346 	}
6347 	up_read(&sess->rpc_lock);
6348 
6349 	ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
6350 		    req->FileInfoClass, req->VolatileFileId);
6351 
6352 	switch (req->FileInfoClass) {
6353 	case FILE_STANDARD_INFORMATION:
6354 		get_standard_info_pipe(rsp);
6355 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
6356 				      le32_to_cpu(rsp->OutputBufferLength),
6357 				      rsp);
6358 		break;
6359 	case FILE_INTERNAL_INFORMATION:
6360 		get_internal_info_pipe(rsp, id);
6361 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
6362 				      le32_to_cpu(rsp->OutputBufferLength),
6363 				      rsp);
6364 		break;
6365 	default:
6366 		ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
6367 			    req->FileInfoClass);
6368 		rc = -EOPNOTSUPP;
6369 	}
6370 	return rc;
6371 }
6372 
6373 /**
6374  * smb2_get_ea() - handler for smb2 get extended attribute command
6375  * @work:	smb work containing query info command buffer
6376  * @fp:		ksmbd_file pointer
6377  * @req:	get extended attribute request
6378  * @rsp:	response buffer pointer
6379  * @rsp_org:	base response buffer pointer in case of chained response
6380  *
6381  * Return:	0 on success, otherwise error
6382  */
6383 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
6384 		       struct smb2_query_info_req *req,
6385 		       struct smb2_query_info_rsp *rsp, void *rsp_org)
6386 {
6387 	struct smb2_ea_info *eainfo, *prev_eainfo;
6388 	char *name, *ptr, *xattr_list = NULL, *buf;
6389 	int rc, name_len, value_len, xattr_list_len, idx;
6390 	ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
6391 	struct smb2_ea_info_req *ea_req = NULL;
6392 	const struct path *path;
6393 	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
6394 
6395 	if (!(fp->daccess & FILE_READ_EA_LE)) {
6396 		pr_err("Not permitted to read ext attr : 0x%x\n",
6397 		       fp->daccess);
6398 		return -EACCES;
6399 	}
6400 
6401 	path = &fp->filp->f_path;
6402 	/* single EA entry is requested with given user.* name */
6403 	if (req->InputBufferLength) {
6404 		if (le32_to_cpu(req->InputBufferLength) <=
6405 		    sizeof(struct smb2_ea_info_req))
6406 			return -EINVAL;
6407 
6408 		ea_req = (struct smb2_ea_info_req *)((char *)req +
6409 						     le16_to_cpu(req->InputBufferOffset));
6410 
6411 		if (le32_to_cpu(req->InputBufferLength) <
6412 		    offsetof(struct smb2_ea_info_req, name) +
6413 		    ea_req->EaNameLength)
6414 			return -EINVAL;
6415 	} else {
6416 		/* need to send all EAs, if no specific EA is requested*/
6417 		if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
6418 			ksmbd_debug(SMB,
6419 				    "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
6420 				    le32_to_cpu(req->Flags));
6421 	}
6422 
6423 	buf_free_len =
6424 		smb2_calc_max_out_buf_len(work,
6425 				offsetof(struct smb2_query_info_rsp, Buffer),
6426 				le32_to_cpu(req->OutputBufferLength));
6427 	if (buf_free_len < 0)
6428 		return -EINVAL;
6429 
6430 	rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
6431 	if (rc < 0) {
6432 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
6433 		goto out;
6434 	} else if (!rc) { /* there is no EA in the file */
6435 		ksmbd_debug(SMB, "no ea data in the file\n");
6436 		goto done;
6437 	}
6438 	xattr_list_len = rc;
6439 
6440 	ptr = (char *)rsp->Buffer;
6441 	eainfo = (struct smb2_ea_info *)ptr;
6442 	prev_eainfo = eainfo;
6443 	idx = 0;
6444 
6445 	while (idx < xattr_list_len) {
6446 		name = xattr_list + idx;
6447 		name_len = strlen(name);
6448 
6449 		ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
6450 		idx += name_len + 1;
6451 
6452 		/*
6453 		 * CIFS does not support EA other than user.* namespace,
6454 		 * still keep the framework generic, to list other attrs
6455 		 * in future.
6456 		 */
6457 		if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
6458 			continue;
6459 
6460 		if (req->InputBufferLength &&
6461 		    strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
6462 			    ea_req->EaNameLength))
6463 			continue;
6464 
6465 		if (smb2_is_private_ea(&name[XATTR_USER_PREFIX_LEN],
6466 				       name_len - XATTR_USER_PREFIX_LEN))
6467 			continue;
6468 
6469 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
6470 			name_len -= XATTR_USER_PREFIX_LEN;
6471 
6472 		ptr = eainfo->name + name_len + 1;
6473 		buf_free_len -= (offsetof(struct smb2_ea_info, name) +
6474 				name_len + 1);
6475 		/* bailout if xattr can't fit in buf_free_len */
6476 		value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
6477 					       name, &buf);
6478 		if (value_len <= 0) {
6479 			rc = -ENOENT;
6480 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
6481 			goto out;
6482 		}
6483 
6484 		buf_free_len -= value_len;
6485 		if (buf_free_len < 0) {
6486 			kfree(buf);
6487 			break;
6488 		}
6489 
6490 		memcpy(ptr, buf, value_len);
6491 		kfree(buf);
6492 
6493 		ptr += value_len;
6494 		eainfo->Flags = 0;
6495 		eainfo->EaNameLength = name_len;
6496 
6497 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
6498 			memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
6499 			       name_len);
6500 		else
6501 			memcpy(eainfo->name, name, name_len);
6502 
6503 		eainfo->name[name_len] = '\0';
6504 		eainfo->EaValueLength = cpu_to_le16(value_len);
6505 		next_offset = offsetof(struct smb2_ea_info, name) +
6506 			name_len + 1 + value_len;
6507 
6508 		/* align next xattr entry at 4 byte bundary */
6509 		alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
6510 		if (alignment_bytes) {
6511 			if (buf_free_len < alignment_bytes)
6512 				break;
6513 			memset(ptr, '\0', alignment_bytes);
6514 			ptr += alignment_bytes;
6515 			next_offset += alignment_bytes;
6516 			buf_free_len -= alignment_bytes;
6517 		}
6518 		eainfo->NextEntryOffset = cpu_to_le32(next_offset);
6519 		prev_eainfo = eainfo;
6520 		eainfo = (struct smb2_ea_info *)ptr;
6521 		rsp_data_cnt += next_offset;
6522 
6523 		if (req->InputBufferLength) {
6524 			ksmbd_debug(SMB, "single entry requested\n");
6525 			break;
6526 		}
6527 	}
6528 
6529 	/* no more ea entries */
6530 	prev_eainfo->NextEntryOffset = 0;
6531 done:
6532 	rc = 0;
6533 	if (rsp_data_cnt == 0)
6534 		rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
6535 	rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
6536 out:
6537 	kvfree(xattr_list);
6538 	return rc;
6539 }
6540 
6541 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
6542 				 struct ksmbd_file *fp, void *rsp_org)
6543 {
6544 	struct smb2_file_access_info *file_info;
6545 
6546 	file_info = (struct smb2_file_access_info *)rsp->Buffer;
6547 	file_info->AccessFlags = fp->daccess;
6548 	rsp->OutputBufferLength =
6549 		cpu_to_le32(sizeof(struct smb2_file_access_info));
6550 }
6551 
6552 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
6553 			       struct ksmbd_file *fp, void *rsp_org)
6554 {
6555 	struct file_basic_info *basic_info;
6556 	struct kstat stat;
6557 	u64 time;
6558 	int ret;
6559 
6560 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
6561 		pr_err("no right to read the attributes : 0x%x\n",
6562 		       fp->daccess);
6563 		return -EACCES;
6564 	}
6565 
6566 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6567 			  AT_STATX_SYNC_AS_STAT);
6568 	if (ret)
6569 		return ret;
6570 
6571 	basic_info = (struct file_basic_info *)rsp->Buffer;
6572 	basic_info->CreationTime = cpu_to_le64(fp->create_time);
6573 	time = ksmbd_UnixTimeToNT(stat.atime);
6574 	basic_info->LastAccessTime = cpu_to_le64(time);
6575 	time = ksmbd_UnixTimeToNT(stat.mtime);
6576 	basic_info->LastWriteTime = cpu_to_le64(time);
6577 	basic_info->ChangeTime = cpu_to_le64(fp->change_time);
6578 	basic_info->Attributes = fp->f_ci->m_fattr;
6579 	basic_info->Pad = 0;
6580 	rsp->OutputBufferLength =
6581 		cpu_to_le32(sizeof(struct file_basic_info));
6582 	return 0;
6583 }
6584 
6585 static int get_file_allocation_stat(struct ksmbd_file *fp, struct kstat *stat)
6586 {
6587 	int ret;
6588 
6589 	/*
6590 	 * Buffered writes can leave delayed allocation in a state where two
6591 	 * consecutive queries report different block counts even when the
6592 	 * second write only overwrites the first one. Complete writeback before
6593 	 * reporting the filesystem allocation for an ordinary open.
6594 	 */
6595 	if (!fp->allocation_size_set) {
6596 		ret = file_write_and_wait(fp->filp);
6597 		if (ret)
6598 			return ret;
6599 	}
6600 
6601 	ret = vfs_getattr(&fp->filp->f_path, stat, STATX_BASIC_STATS,
6602 			  AT_STATX_SYNC_AS_STAT);
6603 	if (!ret && !fp->allocation_size_set)
6604 		fp->allocation_size = S_ISDIR(stat->mode) ? 0 : stat->blocks << 9;
6605 
6606 	return ret;
6607 }
6608 
6609 static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
6610 				  struct ksmbd_file *fp, void *rsp_org)
6611 {
6612 	struct smb2_file_standard_info *sinfo;
6613 	unsigned int delete_pending;
6614 	struct kstat stat;
6615 	int ret;
6616 
6617 	ret = get_file_allocation_stat(fp, &stat);
6618 	if (ret)
6619 		return ret;
6620 
6621 	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
6622 	delete_pending = ksmbd_inode_pending_delete(fp);
6623 
6624 	if (ksmbd_stream_fd(fp) == false) {
6625 		sinfo->AllocationSize = cpu_to_le64(fp->allocation_size);
6626 		sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
6627 	} else {
6628 		loff_t seof = ksmbd_stream_eof(fp);
6629 
6630 		sinfo->AllocationSize = cpu_to_le64((u64)seof);
6631 		sinfo->EndOfFile = cpu_to_le64((u64)seof);
6632 	}
6633 	sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
6634 	sinfo->DeletePending = delete_pending;
6635 	sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
6636 	rsp->OutputBufferLength =
6637 		cpu_to_le32(sizeof(struct smb2_file_standard_info));
6638 
6639 	return 0;
6640 }
6641 
6642 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
6643 				    void *rsp_org)
6644 {
6645 	struct smb2_file_alignment_info *file_info;
6646 
6647 	file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
6648 	file_info->AlignmentRequirement = 0;
6649 	rsp->OutputBufferLength =
6650 		cpu_to_le32(sizeof(struct smb2_file_alignment_info));
6651 }
6652 
6653 static int get_file_all_info(struct ksmbd_work *work,
6654 			     struct smb2_query_info_rsp *rsp,
6655 			     struct ksmbd_file *fp,
6656 			     void *rsp_org)
6657 {
6658 	struct ksmbd_conn *conn = work->conn;
6659 	struct smb2_file_all_info *file_info;
6660 	unsigned int delete_pending;
6661 	struct kstat stat;
6662 	int conv_len;
6663 	char *filename;
6664 	u64 time;
6665 	int ret, buf_free_len, filename_len;
6666 
6667 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
6668 		ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
6669 			    fp->daccess);
6670 		return -EACCES;
6671 	}
6672 
6673 	filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
6674 	if (IS_ERR(filename))
6675 		return PTR_ERR(filename);
6676 
6677 	filename_len = strlen(filename);
6678 	buf_free_len = smb2_resp_buf_len(work,
6679 			offsetof(struct smb2_query_info_rsp, Buffer) +
6680 			offsetof(struct smb2_file_all_info, FileName));
6681 	if (buf_free_len < (filename_len + 1) * 2) {
6682 		kfree(filename);
6683 		return -EINVAL;
6684 	}
6685 
6686 	ret = get_file_allocation_stat(fp, &stat);
6687 	if (ret) {
6688 		kfree(filename);
6689 		return ret;
6690 	}
6691 
6692 	ksmbd_debug(SMB, "filename = %s\n", filename);
6693 	delete_pending = ksmbd_inode_pending_delete(fp);
6694 	file_info = (struct smb2_file_all_info *)rsp->Buffer;
6695 
6696 	file_info->CreationTime = cpu_to_le64(fp->create_time);
6697 	time = ksmbd_UnixTimeToNT(stat.atime);
6698 	file_info->LastAccessTime = cpu_to_le64(time);
6699 	time = ksmbd_UnixTimeToNT(stat.mtime);
6700 	file_info->LastWriteTime = cpu_to_le64(time);
6701 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
6702 	file_info->Attributes = fp->f_ci->m_fattr;
6703 	file_info->Pad1 = 0;
6704 	if (ksmbd_stream_fd(fp) == false) {
6705 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
6706 		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
6707 	} else {
6708 		loff_t seof = ksmbd_stream_eof(fp);
6709 
6710 		file_info->AllocationSize = cpu_to_le64((u64)seof);
6711 		file_info->EndOfFile = cpu_to_le64((u64)seof);
6712 	}
6713 	file_info->NumberOfLinks =
6714 			cpu_to_le32(get_nlink(&stat) - delete_pending);
6715 	file_info->DeletePending = delete_pending;
6716 	file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
6717 	file_info->Pad2 = 0;
6718 	file_info->IndexNumber = cpu_to_le64(stat.ino);
6719 	file_info->EASize = 0;
6720 	file_info->AccessFlags = fp->daccess;
6721 	if (ksmbd_stream_fd(fp) == false)
6722 		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
6723 	else
6724 		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
6725 	file_info->Mode = fp->coption;
6726 	file_info->AlignmentRequirement = 0;
6727 	conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
6728 				     min(filename_len, PATH_MAX),
6729 				     conn->local_nls, 0);
6730 	conv_len *= 2;
6731 	file_info->FileNameLength = cpu_to_le32(conv_len);
6732 	rsp->OutputBufferLength =
6733 		cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
6734 	kfree(filename);
6735 	return 0;
6736 }
6737 
6738 static void get_file_alternate_info(struct ksmbd_work *work,
6739 				    struct smb2_query_info_rsp *rsp,
6740 				    struct ksmbd_file *fp,
6741 				    void *rsp_org)
6742 {
6743 	struct ksmbd_conn *conn = work->conn;
6744 	struct smb2_file_alt_name_info *file_info;
6745 	struct dentry *dentry = fp->filp->f_path.dentry;
6746 	int conv_len;
6747 
6748 	spin_lock(&dentry->d_lock);
6749 	file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
6750 	conv_len = ksmbd_extract_shortname(conn,
6751 					   dentry->d_name.name,
6752 					   file_info->FileName);
6753 	spin_unlock(&dentry->d_lock);
6754 	file_info->FileNameLength = cpu_to_le32(conv_len);
6755 	rsp->OutputBufferLength =
6756 		cpu_to_le32(struct_size(file_info, FileName, conv_len));
6757 }
6758 
6759 static char *smb2_get_normalized_stream_name(struct ksmbd_file *fp)
6760 {
6761 	char *name, *stream_name = NULL, *xattr_list = NULL;
6762 	ssize_t xattr_list_len;
6763 
6764 	if (!ksmbd_stream_fd(fp))
6765 		return NULL;
6766 
6767 	xattr_list_len = ksmbd_vfs_listxattr(fp->filp->f_path.dentry,
6768 					     &xattr_list);
6769 	if (xattr_list_len <= 0)
6770 		goto out;
6771 
6772 	for (name = xattr_list; name - xattr_list < xattr_list_len;
6773 	     name += strlen(name) + 1) {
6774 		char *type;
6775 
6776 		if (strlen(name) + 1 != fp->stream.size ||
6777 		    strncasecmp(name, fp->stream.name, fp->stream.size - 1))
6778 			continue;
6779 
6780 		name += XATTR_NAME_STREAM_LEN;
6781 		type = strrchr(name, ':');
6782 		if (type)
6783 			stream_name = kstrndup(name, type - name,
6784 						  KSMBD_DEFAULT_GFP);
6785 		break;
6786 	}
6787 out:
6788 	kvfree(xattr_list);
6789 	return stream_name;
6790 }
6791 
6792 static int get_file_normalized_name_info(struct ksmbd_work *work,
6793 					 struct smb2_query_info_rsp *rsp,
6794 					 struct ksmbd_file *fp)
6795 {
6796 	struct smb2_file_alt_name_info *file_info;
6797 	char *filename, *normalized, *stream_name;
6798 	int buf_free_len, conv_len, filename_len;
6799 
6800 	if (work->conn->dialect < SMB311_PROT_ID) {
6801 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6802 		return -EOPNOTSUPP;
6803 	}
6804 
6805 	filename = convert_to_nt_pathname(work->tcon->share_conf,
6806 					  &fp->filp->f_path);
6807 	if (IS_ERR(filename))
6808 		return PTR_ERR(filename);
6809 	if (filename[0] == '\\')
6810 		memmove(filename, filename + 1, strlen(filename));
6811 
6812 	stream_name = smb2_get_normalized_stream_name(fp);
6813 	normalized = kasprintf(KSMBD_DEFAULT_GFP, "%s%s%s", filename,
6814 			      stream_name ? ":" : "",
6815 			      stream_name ? stream_name : "");
6816 	kfree(stream_name);
6817 	kfree(filename);
6818 	if (!normalized)
6819 		return -ENOMEM;
6820 
6821 	filename_len = strlen(normalized);
6822 	buf_free_len = smb2_resp_buf_len(work, sizeof(*rsp) +
6823 					 sizeof(*file_info));
6824 	if (buf_free_len < 0 ||
6825 	    (size_t)buf_free_len < (filename_len + 1) * sizeof(__le16)) {
6826 		kfree(normalized);
6827 		return -EINVAL;
6828 	}
6829 
6830 	file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
6831 	conv_len = smbConvertToUTF16((__le16 *)file_info->FileName,
6832 				     normalized, filename_len,
6833 				     work->conn->local_nls, 0);
6834 	kfree(normalized);
6835 	conv_len *= 2;
6836 	file_info->FileNameLength = cpu_to_le32(conv_len);
6837 	rsp->OutputBufferLength = cpu_to_le32(sizeof(*file_info) + conv_len);
6838 	return 0;
6839 }
6840 
6841 static int get_file_stream_info(struct ksmbd_work *work,
6842 				struct smb2_query_info_rsp *rsp,
6843 				struct ksmbd_file *fp,
6844 				void *rsp_org)
6845 {
6846 	struct ksmbd_conn *conn = work->conn;
6847 	struct smb2_file_stream_info *file_info;
6848 	char *stream_name, *xattr_list = NULL, *stream_buf;
6849 	struct kstat stat;
6850 	const struct path *path = &fp->filp->f_path;
6851 	ssize_t xattr_list_len;
6852 	ssize_t slen;
6853 	loff_t ssize;
6854 	int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
6855 	int buf_free_len;
6856 	int ret;
6857 
6858 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6859 			  AT_STATX_SYNC_AS_STAT);
6860 	if (ret)
6861 		return ret;
6862 
6863 	file_info = (struct smb2_file_stream_info *)rsp->Buffer;
6864 
6865 	buf_free_len = smb2_resp_buf_len(work,
6866 			offsetof(struct smb2_query_info_rsp, Buffer));
6867 	if (buf_free_len < 0)
6868 		goto out;
6869 
6870 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
6871 	if (xattr_list_len < 0) {
6872 		goto out;
6873 	} else if (!xattr_list_len) {
6874 		ksmbd_debug(SMB, "empty xattr in the file\n");
6875 		goto out;
6876 	}
6877 
6878 	while (idx < xattr_list_len) {
6879 		stream_name = xattr_list + idx;
6880 		streamlen = strlen(stream_name);
6881 		idx += streamlen + 1;
6882 
6883 		ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
6884 
6885 		if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
6886 			    STREAM_PREFIX, STREAM_PREFIX_LEN))
6887 			continue;
6888 
6889 		stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
6890 				STREAM_PREFIX_LEN);
6891 		streamlen = stream_name_len;
6892 
6893 		/* plus : size */
6894 		streamlen += 1;
6895 		stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP);
6896 		if (!stream_buf)
6897 			break;
6898 
6899 		streamlen = snprintf(stream_buf, streamlen + 1,
6900 				     ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
6901 
6902 		next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
6903 		if (next > buf_free_len) {
6904 			kfree(stream_buf);
6905 			break;
6906 		}
6907 
6908 		file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
6909 		streamlen  = smbConvertToUTF16((__le16 *)file_info->StreamName,
6910 					       stream_buf, streamlen,
6911 					       conn->local_nls, 0);
6912 		streamlen *= 2;
6913 		kfree(stream_buf);
6914 		file_info->StreamNameLength = cpu_to_le32(streamlen);
6915 		/*
6916 		 * stream_name_len is the byte length of the xattr's *name*,
6917 		 * not its value -- same class of bug ksmbd_stream_eof()
6918 		 * (smb2pdu.c) already fixes for EndOfFile/AllocationSize on
6919 		 * a stream handle; this enumeration path needs the same
6920 		 * real xattr value length, not the name length reused as a
6921 		 * size.
6922 		 */
6923 		slen = ksmbd_vfs_casexattr_len(file_mnt_idmap(fp->filp),
6924 						path->dentry, stream_name,
6925 						strlen(stream_name) + 1);
6926 		ssize = slen < 0 ? 0 : (loff_t)slen;
6927 		file_info->StreamSize = cpu_to_le64(ssize);
6928 		file_info->StreamAllocationSize = cpu_to_le64(ssize);
6929 
6930 		nbytes += next;
6931 		buf_free_len -= next;
6932 		file_info->NextEntryOffset = cpu_to_le32(next);
6933 	}
6934 
6935 out:
6936 	if (!S_ISDIR(stat.mode) &&
6937 	    buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
6938 		file_info = (struct smb2_file_stream_info *)
6939 			&rsp->Buffer[nbytes];
6940 		streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
6941 					      "::$DATA", 7, conn->local_nls, 0);
6942 		streamlen *= 2;
6943 		file_info->StreamNameLength = cpu_to_le32(streamlen);
6944 		file_info->StreamSize = cpu_to_le64(stat.size);
6945 		file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
6946 		nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
6947 	}
6948 
6949 	/* last entry offset should be 0 */
6950 	file_info->NextEntryOffset = 0;
6951 	kvfree(xattr_list);
6952 
6953 	rsp->OutputBufferLength = cpu_to_le32(nbytes);
6954 
6955 	return 0;
6956 }
6957 
6958 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
6959 				  struct ksmbd_file *fp, void *rsp_org)
6960 {
6961 	struct smb2_file_internal_info *file_info;
6962 	struct kstat stat;
6963 	int ret;
6964 
6965 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6966 			  AT_STATX_SYNC_AS_STAT);
6967 	if (ret)
6968 		return ret;
6969 
6970 	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
6971 	file_info->IndexNumber = cpu_to_le64(stat.ino);
6972 	rsp->OutputBufferLength =
6973 		cpu_to_le32(sizeof(struct smb2_file_internal_info));
6974 
6975 	return 0;
6976 }
6977 
6978 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
6979 				      struct ksmbd_file *fp, void *rsp_org)
6980 {
6981 	struct smb2_file_network_open_info *file_info;
6982 	struct kstat stat;
6983 	u64 time;
6984 	int ret;
6985 
6986 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
6987 		pr_err("no right to read the attributes : 0x%x\n",
6988 		       fp->daccess);
6989 		return -EACCES;
6990 	}
6991 
6992 	ret = get_file_allocation_stat(fp, &stat);
6993 	if (ret)
6994 		return ret;
6995 
6996 	file_info = (struct smb2_file_network_open_info *)rsp->Buffer;
6997 
6998 	file_info->CreationTime = cpu_to_le64(fp->create_time);
6999 	time = ksmbd_UnixTimeToNT(stat.atime);
7000 	file_info->LastAccessTime = cpu_to_le64(time);
7001 	time = ksmbd_UnixTimeToNT(stat.mtime);
7002 	file_info->LastWriteTime = cpu_to_le64(time);
7003 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
7004 	file_info->Attributes = fp->f_ci->m_fattr;
7005 	if (ksmbd_stream_fd(fp) == false) {
7006 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
7007 		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
7008 	} else {
7009 		loff_t seof = ksmbd_stream_eof(fp);
7010 
7011 		file_info->AllocationSize = cpu_to_le64((u64)seof);
7012 		file_info->EndOfFile = cpu_to_le64((u64)seof);
7013 	}
7014 	file_info->Reserved = cpu_to_le32(0);
7015 	rsp->OutputBufferLength =
7016 		cpu_to_le32(sizeof(struct smb2_file_network_open_info));
7017 	return 0;
7018 }
7019 
7020 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
7021 {
7022 	struct smb2_file_ea_info *file_info;
7023 
7024 	file_info = (struct smb2_file_ea_info *)rsp->Buffer;
7025 	file_info->EASize = 0;
7026 	rsp->OutputBufferLength =
7027 		cpu_to_le32(sizeof(struct smb2_file_ea_info));
7028 }
7029 
7030 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
7031 				   struct ksmbd_file *fp, void *rsp_org)
7032 {
7033 	struct smb2_file_pos_info *file_info;
7034 
7035 	file_info = (struct smb2_file_pos_info *)rsp->Buffer;
7036 	if (ksmbd_stream_fd(fp) == false)
7037 		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
7038 	else
7039 		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
7040 
7041 	rsp->OutputBufferLength =
7042 		cpu_to_le32(sizeof(struct smb2_file_pos_info));
7043 }
7044 
7045 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
7046 			       struct ksmbd_file *fp, void *rsp_org)
7047 {
7048 	struct smb2_file_mode_info *file_info;
7049 
7050 	file_info = (struct smb2_file_mode_info *)rsp->Buffer;
7051 	file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
7052 	rsp->OutputBufferLength =
7053 		cpu_to_le32(sizeof(struct smb2_file_mode_info));
7054 }
7055 
7056 static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
7057 				     struct ksmbd_file *fp, void *rsp_org)
7058 {
7059 	struct smb2_file_comp_info *file_info;
7060 	struct kstat stat;
7061 	u16 fmt;
7062 	int ret;
7063 
7064 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
7065 			  AT_STATX_SYNC_AS_STAT);
7066 	if (ret)
7067 		return ret;
7068 
7069 	ret = ksmbd_vfs_get_compression(fp, &fmt);
7070 	if (ret)
7071 		return ret;
7072 
7073 	file_info = (struct smb2_file_comp_info *)rsp->Buffer;
7074 	file_info->CompressedFileSize = cpu_to_le64(min_t(u64, stat.blocks << 9, stat.size));
7075 	file_info->CompressionFormat = cpu_to_le16(fmt);
7076 	file_info->CompressionUnitShift = 0;
7077 	file_info->ChunkShift = 0;
7078 	file_info->ClusterShift = 0;
7079 	memset(&file_info->Reserved[0], 0, 3);
7080 
7081 	rsp->OutputBufferLength =
7082 		cpu_to_le32(sizeof(struct smb2_file_comp_info));
7083 
7084 	return 0;
7085 }
7086 
7087 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
7088 				       struct ksmbd_file *fp, void *rsp_org)
7089 {
7090 	struct smb2_file_attr_tag_info *file_info;
7091 
7092 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
7093 		pr_err("no right to read the attributes : 0x%x\n",
7094 		       fp->daccess);
7095 		return -EACCES;
7096 	}
7097 
7098 	file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
7099 	file_info->FileAttributes = fp->f_ci->m_fattr;
7100 	file_info->ReparseTag = 0;
7101 	rsp->OutputBufferLength =
7102 		cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
7103 	return 0;
7104 }
7105 
7106 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
7107 				struct ksmbd_file *fp, void *rsp_org)
7108 {
7109 	struct smb311_posix_qinfo *file_info;
7110 	struct inode *inode = file_inode(fp->filp);
7111 	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
7112 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
7113 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
7114 	struct kstat stat;
7115 	u64 time;
7116 	int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
7117 	int ret;
7118 
7119 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
7120 		pr_err("no right to read the attributes : 0x%x\n",
7121 		       fp->daccess);
7122 		return -EACCES;
7123 	}
7124 
7125 	ret = get_file_allocation_stat(fp, &stat);
7126 	if (ret)
7127 		return ret;
7128 
7129 	file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
7130 	file_info->CreationTime = cpu_to_le64(fp->create_time);
7131 	time = ksmbd_UnixTimeToNT(stat.atime);
7132 	file_info->LastAccessTime = cpu_to_le64(time);
7133 	time = ksmbd_UnixTimeToNT(stat.mtime);
7134 	file_info->LastWriteTime = cpu_to_le64(time);
7135 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
7136 	file_info->DosAttributes = fp->f_ci->m_fattr;
7137 	file_info->Inode = cpu_to_le64(stat.ino);
7138 	if (ksmbd_stream_fd(fp) == false) {
7139 		file_info->EndOfFile = cpu_to_le64(stat.size);
7140 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
7141 	} else {
7142 		loff_t seof = ksmbd_stream_eof(fp);
7143 
7144 		file_info->EndOfFile = cpu_to_le64((u64)seof);
7145 		file_info->AllocationSize = cpu_to_le64((u64)seof);
7146 	}
7147 	file_info->HardLinks = cpu_to_le32(stat.nlink);
7148 	file_info->Mode = cpu_to_le32(stat.mode & 0777);
7149 	switch (stat.mode & S_IFMT) {
7150 	case S_IFDIR:
7151 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
7152 		break;
7153 	case S_IFLNK:
7154 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
7155 		break;
7156 	case S_IFCHR:
7157 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
7158 		break;
7159 	case S_IFBLK:
7160 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
7161 		break;
7162 	case S_IFIFO:
7163 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
7164 		break;
7165 	case S_IFSOCK:
7166 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
7167 	}
7168 
7169 	file_info->DeviceId = cpu_to_le32(stat.rdev);
7170 
7171 	/*
7172 	 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
7173 	 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
7174 	 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
7175 	 */
7176 	id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
7177 		  SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
7178 	id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
7179 		  SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
7180 
7181 	rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
7182 
7183 	return 0;
7184 }
7185 
7186 static int smb2_get_info_file(struct ksmbd_work *work,
7187 			      struct smb2_query_info_req *req,
7188 			      struct smb2_query_info_rsp *rsp)
7189 {
7190 	struct ksmbd_file *fp;
7191 	int fileinfoclass = 0;
7192 	int rc = 0;
7193 	unsigned int fixed_len;
7194 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7195 
7196 	if (test_share_config_flag(work->tcon->share_conf,
7197 				   KSMBD_SHARE_FLAG_PIPE)) {
7198 		/* smb2 info file called for pipe */
7199 		rc = smb2_get_info_file_pipe(work->sess, req, rsp);
7200 		goto iov_pin_out;
7201 	}
7202 
7203 	if (work->next_smb2_rcv_hdr_off) {
7204 		if (!has_file_id(req->VolatileFileId)) {
7205 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7206 				    work->compound_fid);
7207 			id = work->compound_fid;
7208 			pid = work->compound_pfid;
7209 		}
7210 	}
7211 
7212 	if (!has_file_id(id)) {
7213 		id = req->VolatileFileId;
7214 		pid = req->PersistentFileId;
7215 	}
7216 
7217 	fp = ksmbd_lookup_fd_slow(work, id, pid);
7218 	if (!fp)
7219 		return -ENOENT;
7220 
7221 	fileinfoclass = req->FileInfoClass;
7222 
7223 	switch (fileinfoclass) {
7224 	case FILE_ACCESS_INFORMATION:
7225 		get_file_access_info(rsp, fp, work->response_buf);
7226 		break;
7227 
7228 	case FILE_BASIC_INFORMATION:
7229 		rc = get_file_basic_info(rsp, fp, work->response_buf);
7230 		break;
7231 
7232 	case FILE_STANDARD_INFORMATION:
7233 		rc = get_file_standard_info(rsp, fp, work->response_buf);
7234 		break;
7235 
7236 	case FILE_ALIGNMENT_INFORMATION:
7237 		get_file_alignment_info(rsp, work->response_buf);
7238 		break;
7239 
7240 	case FILE_ALL_INFORMATION:
7241 		rc = get_file_all_info(work, rsp, fp, work->response_buf);
7242 		break;
7243 
7244 	case FILE_ALTERNATE_NAME_INFORMATION:
7245 		get_file_alternate_info(work, rsp, fp, work->response_buf);
7246 		break;
7247 	case FILE_NORMALIZED_NAME_INFORMATION:
7248 		rc = get_file_normalized_name_info(work, rsp, fp);
7249 		break;
7250 
7251 	case FILE_STREAM_INFORMATION:
7252 		rc = get_file_stream_info(work, rsp, fp, work->response_buf);
7253 		break;
7254 
7255 	case FILE_INTERNAL_INFORMATION:
7256 		rc = get_file_internal_info(rsp, fp, work->response_buf);
7257 		break;
7258 
7259 	case FILE_NETWORK_OPEN_INFORMATION:
7260 		rc = get_file_network_open_info(rsp, fp, work->response_buf);
7261 		break;
7262 
7263 	case FILE_EA_INFORMATION:
7264 		get_file_ea_info(rsp, work->response_buf);
7265 		break;
7266 
7267 	case FILE_FULL_EA_INFORMATION:
7268 		rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
7269 		break;
7270 
7271 	case FILE_POSITION_INFORMATION:
7272 		get_file_position_info(rsp, fp, work->response_buf);
7273 		break;
7274 
7275 	case FILE_MODE_INFORMATION:
7276 		get_file_mode_info(rsp, fp, work->response_buf);
7277 		break;
7278 
7279 	case FILE_COMPRESSION_INFORMATION:
7280 		rc = get_file_compression_info(rsp, fp, work->response_buf);
7281 		break;
7282 
7283 	case FILE_ATTRIBUTE_TAG_INFORMATION:
7284 		rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
7285 		break;
7286 	case SMB_FIND_FILE_POSIX_INFO:
7287 		if (!work->tcon->posix_extensions) {
7288 			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
7289 			rc = -EOPNOTSUPP;
7290 		} else {
7291 			rc = find_file_posix_info(rsp, fp, work->response_buf);
7292 		}
7293 		break;
7294 	default:
7295 		ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
7296 			    fileinfoclass);
7297 		rc = -EOPNOTSUPP;
7298 	}
7299 	if (!rc) {
7300 		fixed_len = le32_to_cpu(rsp->OutputBufferLength);
7301 		switch (fileinfoclass) {
7302 		case FILE_ALL_INFORMATION:
7303 			fixed_len = FILE_ALL_INFORMATION_SIZE;
7304 			break;
7305 		case FILE_ALTERNATE_NAME_INFORMATION:
7306 			fixed_len = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
7307 			break;
7308 		case FILE_NORMALIZED_NAME_INFORMATION:
7309 			fixed_len = FILE_NORMALIZED_NAME_INFORMATION_SIZE;
7310 			break;
7311 		case FILE_STREAM_INFORMATION:
7312 			fixed_len = FILE_STREAM_INFORMATION_SIZE;
7313 			break;
7314 		}
7315 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
7316 				      fixed_len,
7317 				      rsp);
7318 	}
7319 	ksmbd_fd_put(work, fp);
7320 
7321 iov_pin_out:
7322 	if (!rc)
7323 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
7324 				offsetof(struct smb2_query_info_rsp, Buffer) +
7325 				le32_to_cpu(rsp->OutputBufferLength));
7326 	return rc;
7327 }
7328 
7329 static int smb2_get_info_filesystem(struct ksmbd_work *work,
7330 				    struct smb2_query_info_req *req,
7331 				    struct smb2_query_info_rsp *rsp)
7332 {
7333 	struct ksmbd_conn *conn = work->conn;
7334 	struct ksmbd_share_config *share = work->tcon->share_conf;
7335 	int fsinfoclass = 0;
7336 	struct kstatfs stfs;
7337 	struct path path;
7338 	int rc = 0, len;
7339 	unsigned int fixed_len = 0;
7340 
7341 	if (!share->path)
7342 		return -EIO;
7343 
7344 	scoped_with_init_fs()
7345 		rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
7346 	if (rc) {
7347 		pr_err("cannot create vfs path\n");
7348 		return -EIO;
7349 	}
7350 
7351 	rc = vfs_statfs(&path, &stfs);
7352 	if (rc) {
7353 		pr_err("cannot do stat of path %s\n", share->path);
7354 		path_put(&path);
7355 		return -EIO;
7356 	}
7357 
7358 	fsinfoclass = req->FileInfoClass;
7359 
7360 	switch (fsinfoclass) {
7361 	case FS_DEVICE_INFORMATION:
7362 	{
7363 		FILE_SYSTEM_DEVICE_INFO *info;
7364 
7365 		info = (FILE_SYSTEM_DEVICE_INFO *)rsp->Buffer;
7366 
7367 		info->DeviceType = cpu_to_le32(FILE_DEVICE_DISK);
7368 		info->DeviceCharacteristics =
7369 			cpu_to_le32(FILE_DEVICE_IS_MOUNTED);
7370 		if (!test_tree_conn_flag(work->tcon,
7371 					 KSMBD_TREE_CONN_FLAG_WRITABLE))
7372 			info->DeviceCharacteristics |=
7373 				cpu_to_le32(FILE_READ_ONLY_DEVICE);
7374 		rsp->OutputBufferLength = cpu_to_le32(8);
7375 		fixed_len = 8;
7376 		break;
7377 	}
7378 	case FS_ATTRIBUTE_INFORMATION:
7379 	{
7380 		FILE_SYSTEM_ATTRIBUTE_INFO *info;
7381 		struct file_kattr fa = {};
7382 		size_t sz;
7383 		u32 attrs;
7384 		int err;
7385 
7386 		info = (FILE_SYSTEM_ATTRIBUTE_INFO *)rsp->Buffer;
7387 		attrs = FILE_SUPPORTS_OBJECT_IDS |
7388 			FILE_PERSISTENT_ACLS |
7389 			FILE_UNICODE_ON_DISK |
7390 			FILE_FILE_COMPRESSION |
7391 			FILE_SUPPORTS_SPARSE_FILES |
7392 			FILE_SUPPORTS_BLOCK_REFCOUNTING;
7393 
7394 		err = vfs_fileattr_get(path.dentry, &fa);
7395 		/*
7396 		 * -EINVAL, -EOPNOTSUPP: ntfs-3g and other FUSE
7397 		 * filesystems that lack FS_IOC_FSGETXATTR support.
7398 		 */
7399 		if (err && err != -ENOIOCTLCMD && err != -ENOTTY &&
7400 		    err != -EINVAL && err != -EOPNOTSUPP) {
7401 			path_put(&path);
7402 			return err;
7403 		}
7404 		if (!(fa.fsx_xflags & FS_XFLAG_CASEFOLD))
7405 			attrs |= FILE_CASE_SENSITIVE_SEARCH;
7406 		if (!(fa.fsx_xflags & FS_XFLAG_CASENONPRESERVING))
7407 			attrs |= FILE_CASE_PRESERVED_NAMES;
7408 
7409 		info->Attributes = cpu_to_le32(attrs);
7410 		info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
7411 
7412 		if (test_share_config_flag(work->tcon->share_conf,
7413 		    KSMBD_SHARE_FLAG_STREAMS))
7414 			info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
7415 
7416 		info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
7417 		/*
7418 		 * some application(potableapp) can not run on ksmbd share
7419 		 * because only NTFS handle security setting on windows.
7420 		 * So Although local fs(EXT4 or F2fs, etc) is not NTFS,
7421 		 * ksmbd should show share as NTFS. Later, If needed, we can add
7422 		 * fs type(s) parameter to change fs type user wanted.
7423 		 */
7424 		len = smbConvertToUTF16((__le16 *)info->FileSystemName,
7425 					"NTFS", PATH_MAX, conn->local_nls, 0);
7426 		len = len * 2;
7427 		info->FileSystemNameLen = cpu_to_le32(len);
7428 		sz = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + len;
7429 		rsp->OutputBufferLength = cpu_to_le32(sz);
7430 		fixed_len = 16;
7431 		break;
7432 	}
7433 	case FS_VOLUME_INFORMATION:
7434 	{
7435 		struct filesystem_vol_info *info;
7436 		size_t sz;
7437 		unsigned int serial_crc = 0;
7438 
7439 		info = (struct filesystem_vol_info *)(rsp->Buffer);
7440 		info->VolumeCreationTime = 0;
7441 		serial_crc = crc32_le(serial_crc, share->name,
7442 				      strlen(share->name));
7443 		serial_crc = crc32_le(serial_crc, share->path,
7444 				      strlen(share->path));
7445 		serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
7446 				      strlen(ksmbd_netbios_name()));
7447 		/* Taking dummy value of serial number*/
7448 		info->VolumeSerialNumber = cpu_to_le32(serial_crc);
7449 		len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
7450 					share->name, PATH_MAX,
7451 					conn->local_nls, 0);
7452 		len = len * 2;
7453 		info->VolumeLabelLength = cpu_to_le32(len);
7454 		info->Reserved = 0;
7455 		info->SupportsObjects = 0;
7456 		sz = sizeof(struct filesystem_vol_info) + len;
7457 		rsp->OutputBufferLength = cpu_to_le32(sz);
7458 		fixed_len = 24;
7459 		break;
7460 	}
7461 	case FS_SIZE_INFORMATION:
7462 	{
7463 		FILE_SYSTEM_SIZE_INFO *info;
7464 
7465 		info = (FILE_SYSTEM_SIZE_INFO *)(rsp->Buffer);
7466 		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
7467 		info->AvailableAllocationUnits = cpu_to_le64(stfs.f_bfree);
7468 		info->SectorsPerAllocationUnit = cpu_to_le32(1);
7469 		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
7470 		rsp->OutputBufferLength = cpu_to_le32(24);
7471 		fixed_len = 24;
7472 		break;
7473 	}
7474 	case FS_FULL_SIZE_INFORMATION:
7475 	{
7476 		struct smb2_fs_full_size_info *info;
7477 
7478 		info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
7479 		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
7480 		info->CallerAvailableAllocationUnits =
7481 					cpu_to_le64(stfs.f_bavail);
7482 		info->ActualAvailableAllocationUnits =
7483 					cpu_to_le64(stfs.f_bfree);
7484 		info->SectorsPerAllocationUnit = cpu_to_le32(1);
7485 		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
7486 		rsp->OutputBufferLength = cpu_to_le32(32);
7487 		fixed_len = 32;
7488 		break;
7489 	}
7490 	case FS_OBJECT_ID_INFORMATION:
7491 	{
7492 		struct object_id_info *info;
7493 
7494 		info = (struct object_id_info *)(rsp->Buffer);
7495 		memset(info, 0, sizeof(*info));
7496 
7497 		if (path.mnt->mnt_sb->s_uuid_len == 16)
7498 			memcpy(info->objid, path.mnt->mnt_sb->s_uuid.b,
7499 					path.mnt->mnt_sb->s_uuid_len);
7500 		else
7501 			memcpy(info->objid, &stfs.f_fsid, sizeof(stfs.f_fsid));
7502 
7503 		info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
7504 		info->extended_info.version = cpu_to_le32(1);
7505 		info->extended_info.release = cpu_to_le32(1);
7506 		info->extended_info.rel_date = 0;
7507 		memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
7508 		rsp->OutputBufferLength = cpu_to_le32(64);
7509 		fixed_len = 64;
7510 		break;
7511 	}
7512 	case FS_SECTOR_SIZE_INFORMATION:
7513 	{
7514 		struct smb3_fs_ss_info *info;
7515 		unsigned int sector_size =
7516 			min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
7517 
7518 		info = (struct smb3_fs_ss_info *)(rsp->Buffer);
7519 
7520 		info->LogicalBytesPerSector = cpu_to_le32(sector_size);
7521 		info->PhysicalBytesPerSectorForAtomicity =
7522 				cpu_to_le32(sector_size);
7523 		info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
7524 		info->FSEffPhysicalBytesPerSectorForAtomicity =
7525 				cpu_to_le32(sector_size);
7526 		info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
7527 				    SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE |
7528 				    SSINFO_FLAGS_TRIM_ENABLED);
7529 		info->ByteOffsetForSectorAlignment = 0;
7530 		info->ByteOffsetForPartitionAlignment = 0;
7531 		rsp->OutputBufferLength = cpu_to_le32(28);
7532 		fixed_len = 28;
7533 		break;
7534 	}
7535 	case FS_CONTROL_INFORMATION:
7536 	{
7537 		/*
7538 		 * TODO : The current implementation is based on
7539 		 * test result with win7(NTFS) server. It's need to
7540 		 * modify this to get valid Quota values
7541 		 * from Linux kernel
7542 		 */
7543 		struct smb2_fs_control_info *info;
7544 
7545 		info = (struct smb2_fs_control_info *)(rsp->Buffer);
7546 		info->FreeSpaceStartFiltering = 0;
7547 		info->FreeSpaceThreshold = 0;
7548 		info->FreeSpaceStopFiltering = 0;
7549 		info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
7550 		info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
7551 		info->FileSystemControlFlags = 0;
7552 		info->Padding = 0;
7553 		rsp->OutputBufferLength = cpu_to_le32(48);
7554 		fixed_len = 48;
7555 		break;
7556 	}
7557 	case FS_POSIX_INFORMATION:
7558 	{
7559 		FILE_SYSTEM_POSIX_INFO *info;
7560 
7561 		if (!work->tcon->posix_extensions) {
7562 			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
7563 			path_put(&path);
7564 			return -EOPNOTSUPP;
7565 		} else {
7566 			info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
7567 			info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
7568 			info->BlockSize = cpu_to_le32(stfs.f_bsize);
7569 			info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
7570 			info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
7571 			info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
7572 			info->TotalFileNodes = cpu_to_le64(stfs.f_files);
7573 			info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
7574 			info->FileSysIdentifier =
7575 				cpu_to_le64((u64)(u32)stfs.f_fsid.val[1] << 32 |
7576 					    (u32)stfs.f_fsid.val[0]);
7577 			rsp->OutputBufferLength = cpu_to_le32(56);
7578 			fixed_len = 56;
7579 		}
7580 		break;
7581 	}
7582 	default:
7583 		path_put(&path);
7584 		return -EOPNOTSUPP;
7585 	}
7586 	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
7587 			      fixed_len,
7588 			      rsp);
7589 	path_put(&path);
7590 
7591 	if (!rc)
7592 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
7593 				offsetof(struct smb2_query_info_rsp, Buffer) +
7594 				le32_to_cpu(rsp->OutputBufferLength));
7595 	return rc;
7596 }
7597 
7598 static int smb2_get_info_sec(struct ksmbd_work *work,
7599 			     struct smb2_query_info_req *req,
7600 			     struct smb2_query_info_rsp *rsp)
7601 {
7602 	struct ksmbd_file *fp;
7603 	struct mnt_idmap *idmap;
7604 	struct smb_ntsd *pntsd = NULL, *ppntsd = NULL;
7605 	struct smb_fattr fattr = {{0}};
7606 	struct inode *inode;
7607 	__u32 secdesclen = 0;
7608 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7609 	int addition_info = le32_to_cpu(req->AdditionalInformation);
7610 	int rc = 0, ppntsd_size = 0, max_len;
7611 	size_t scratch_len = 0;
7612 
7613 	if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
7614 			      PROTECTED_DACL_SECINFO |
7615 			      UNPROTECTED_DACL_SECINFO)) {
7616 		ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
7617 		       addition_info);
7618 
7619 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7620 		return -EINVAL;
7621 	}
7622 
7623 	if (work->next_smb2_rcv_hdr_off) {
7624 		if (!has_file_id(req->VolatileFileId)) {
7625 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7626 				    work->compound_fid);
7627 			id = work->compound_fid;
7628 			pid = work->compound_pfid;
7629 		}
7630 	}
7631 
7632 	if (!has_file_id(id)) {
7633 		id = req->VolatileFileId;
7634 		pid = req->PersistentFileId;
7635 	}
7636 
7637 	fp = ksmbd_lookup_fd_slow(work, id, pid);
7638 	if (!fp)
7639 		return -ENOENT;
7640 
7641 	if (addition_info & (OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO) &&
7642 	    !(fp->daccess & FILE_READ_CONTROL_LE)) {
7643 		ksmbd_fd_put(work, fp);
7644 		return -EACCES;
7645 	}
7646 
7647 	if (le32_to_cpu(req->OutputBufferLength) < sizeof(struct smb_ntsd)) {
7648 		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7649 		ksmbd_fd_put(work, fp);
7650 		return -ENOSPC;
7651 	}
7652 
7653 	idmap = file_mnt_idmap(fp->filp);
7654 	inode = file_inode(fp->filp);
7655 	ksmbd_acls_fattr(&fattr, idmap, inode);
7656 
7657 	if (test_share_config_flag(work->tcon->share_conf,
7658 				   KSMBD_SHARE_FLAG_ACL_XATTR))
7659 		ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
7660 						     fp->filp->f_path.dentry,
7661 						     &ppntsd);
7662 
7663 	/* Check if sd buffer size exceeds response buffer size */
7664 	max_len = smb2_calc_max_out_buf_len(work,
7665 			offsetof(struct smb2_query_info_rsp, Buffer),
7666 			le32_to_cpu(req->OutputBufferLength));
7667 	if (max_len < 0) {
7668 		rc = -EINVAL;
7669 		goto release_acl;
7670 	}
7671 
7672 	scratch_len = smb_acl_sec_desc_scratch_len(&fattr, ppntsd,
7673 			ppntsd_size, addition_info);
7674 	if (!scratch_len || scratch_len == SIZE_MAX) {
7675 		rc = -EFBIG;
7676 		goto release_acl;
7677 	}
7678 
7679 	pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
7680 	if (!pntsd) {
7681 		rc = -ENOMEM;
7682 		goto release_acl;
7683 	}
7684 
7685 	rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
7686 			addition_info, &secdesclen, &fattr);
7687 
7688 release_acl:
7689 	posix_acl_release(fattr.cf_acls);
7690 	posix_acl_release(fattr.cf_dacls);
7691 	kfree(ppntsd);
7692 	ksmbd_fd_put(work, fp);
7693 
7694 	if (!rc && ALIGN(secdesclen, 8) > scratch_len)
7695 		rc = -EFBIG;
7696 	if (rc)
7697 		goto err_out;
7698 
7699 	rsp->OutputBufferLength = cpu_to_le32(secdesclen);
7700 	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
7701 			      le32_to_cpu(rsp->OutputBufferLength),
7702 			      rsp);
7703 	if (rc)
7704 		goto err_out;
7705 
7706 	rc = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
7707 			offsetof(struct smb2_query_info_rsp, Buffer),
7708 			pntsd, secdesclen);
7709 err_out:
7710 	if (rc) {
7711 		rsp->OutputBufferLength = 0;
7712 		kvfree(pntsd);
7713 	}
7714 
7715 	return rc;
7716 }
7717 
7718 /**
7719  * smb2_query_info() - handler for smb2 query info command
7720  * @work:	smb work containing query info request buffer
7721  *
7722  * Return:	0 on success, otherwise error
7723  */
7724 int smb2_query_info(struct ksmbd_work *work)
7725 {
7726 	struct smb2_query_info_req *req;
7727 	struct smb2_query_info_rsp *rsp;
7728 	int rc = 0;
7729 
7730 	ksmbd_debug(SMB, "Received request smb2 query info request\n");
7731 
7732 	WORK_BUFFERS(work, req, rsp);
7733 
7734 	if (smb2_compound_has_failed(work, &rsp->hdr))
7735 		return -EACCES;
7736 
7737 	if (ksmbd_override_fsids(work)) {
7738 		rc = -ENOMEM;
7739 		goto err_out;
7740 	}
7741 
7742 	rsp->StructureSize = cpu_to_le16(9);
7743 	rsp->OutputBufferOffset = cpu_to_le16(72);
7744 
7745 	switch (req->InfoType) {
7746 	case SMB2_O_INFO_FILE:
7747 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
7748 		rc = smb2_get_info_file(work, req, rsp);
7749 		break;
7750 	case SMB2_O_INFO_FILESYSTEM:
7751 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
7752 		rc = smb2_get_info_filesystem(work, req, rsp);
7753 		break;
7754 	case SMB2_O_INFO_SECURITY:
7755 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
7756 		rc = smb2_get_info_sec(work, req, rsp);
7757 		break;
7758 	default:
7759 		ksmbd_debug(SMB, "InfoType %d not supported yet\n",
7760 			    req->InfoType);
7761 		rc = -EOPNOTSUPP;
7762 	}
7763 	ksmbd_revert_fsids(work);
7764 
7765 err_out:
7766 	if (rc < 0) {
7767 		if (rc == -EACCES)
7768 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
7769 		else if (rc == -ENOENT)
7770 			rsp->hdr.Status = STATUS_FILE_CLOSED;
7771 		else if (rc == -EIO)
7772 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7773 		else if (rc == -ENOMEM)
7774 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7775 		else if (rc == -EINVAL && rsp->hdr.Status == 0)
7776 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7777 		else if (rsp->hdr.Status == 0)
7778 			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
7779 		smb2_set_err_rsp(work);
7780 
7781 		ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
7782 			    rc);
7783 		return rc;
7784 	}
7785 	return 0;
7786 }
7787 
7788 /**
7789  * smb2_close_pipe() - handler for closing IPC pipe
7790  * @work:	smb work containing close request buffer
7791  *
7792  * Return:	0
7793  */
7794 static noinline int smb2_close_pipe(struct ksmbd_work *work)
7795 {
7796 	u64 id;
7797 	struct smb2_close_req *req;
7798 	struct smb2_close_rsp *rsp;
7799 
7800 	WORK_BUFFERS(work, req, rsp);
7801 
7802 	id = req->VolatileFileId;
7803 	ksmbd_session_rpc_close(work->sess, id);
7804 
7805 	rsp->StructureSize = cpu_to_le16(60);
7806 	rsp->Flags = 0;
7807 	rsp->Reserved = 0;
7808 	rsp->CreationTime = 0;
7809 	rsp->LastAccessTime = 0;
7810 	rsp->LastWriteTime = 0;
7811 	rsp->ChangeTime = 0;
7812 	rsp->AllocationSize = 0;
7813 	rsp->EndOfFile = 0;
7814 	rsp->Attributes = 0;
7815 
7816 	return ksmbd_iov_pin_rsp(work, (void *)rsp,
7817 				 sizeof(struct smb2_close_rsp));
7818 }
7819 
7820 /**
7821  * smb2_close() - handler for smb2 close file command
7822  * @work:	smb work containing close request buffer
7823  *
7824  * Return:	0 on success, otherwise error
7825  */
7826 int smb2_close(struct ksmbd_work *work)
7827 {
7828 	u64 volatile_id = KSMBD_NO_FID;
7829 	u64 sess_id;
7830 	struct smb2_close_req *req;
7831 	struct smb2_close_rsp *rsp;
7832 	struct ksmbd_file *fp;
7833 	u64 time;
7834 	int err = 0;
7835 
7836 	ksmbd_debug(SMB, "Received smb2 close request\n");
7837 
7838 	WORK_BUFFERS(work, req, rsp);
7839 
7840 	if (smb2_compound_has_failed(work, &rsp->hdr))
7841 		return -EACCES;
7842 
7843 	if (test_share_config_flag(work->tcon->share_conf,
7844 				   KSMBD_SHARE_FLAG_PIPE)) {
7845 		ksmbd_debug(SMB, "IPC pipe close request\n");
7846 		return smb2_close_pipe(work);
7847 	}
7848 
7849 	sess_id = le64_to_cpu(req->hdr.SessionId);
7850 	if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
7851 		sess_id = work->compound_sid;
7852 
7853 	work->compound_sid = 0;
7854 	if (work->sess && work->sess->id == sess_id) {
7855 		work->compound_sid = sess_id;
7856 	} else {
7857 		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
7858 		if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
7859 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7860 		err = -EBADF;
7861 		goto out;
7862 	}
7863 
7864 	if (work->next_smb2_rcv_hdr_off &&
7865 	    !has_file_id(req->VolatileFileId)) {
7866 		if (!has_file_id(work->compound_fid)) {
7867 			/* file already closed, return FILE_CLOSED */
7868 			ksmbd_debug(SMB, "file already closed\n");
7869 			rsp->hdr.Status = STATUS_FILE_CLOSED;
7870 			err = -EBADF;
7871 			goto out;
7872 		} else {
7873 			ksmbd_debug(SMB,
7874 				    "Compound request set FID = %llu:%llu\n",
7875 				    work->compound_fid,
7876 				    work->compound_pfid);
7877 			volatile_id = work->compound_fid;
7878 
7879 			/* file closed, stored id is not valid anymore */
7880 			work->compound_fid = KSMBD_NO_FID;
7881 			work->compound_pfid = KSMBD_NO_FID;
7882 		}
7883 	} else {
7884 		volatile_id = req->VolatileFileId;
7885 	}
7886 	ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
7887 
7888 	rsp->StructureSize = cpu_to_le16(60);
7889 	rsp->Reserved = 0;
7890 
7891 	if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
7892 		struct kstat stat;
7893 		int ret;
7894 
7895 		fp = ksmbd_lookup_fd_fast(work, volatile_id);
7896 		if (!fp) {
7897 			err = -ENOENT;
7898 			goto out;
7899 		}
7900 
7901 		ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
7902 				  AT_STATX_SYNC_AS_STAT);
7903 		if (ret) {
7904 			ksmbd_fd_put(work, fp);
7905 			goto out;
7906 		}
7907 
7908 		rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
7909 		rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
7910 		rsp->EndOfFile = cpu_to_le64(stat.size);
7911 		rsp->Attributes = fp->f_ci->m_fattr;
7912 		rsp->CreationTime = cpu_to_le64(fp->create_time);
7913 		time = ksmbd_UnixTimeToNT(stat.atime);
7914 		rsp->LastAccessTime = cpu_to_le64(time);
7915 		time = ksmbd_UnixTimeToNT(stat.mtime);
7916 		if (time > fp->open_mtime &&
7917 		    time - fp->open_mtime < KSMBD_WRITE_TIME_RESOLUTION)
7918 			time = fp->open_mtime;
7919 		rsp->LastWriteTime = cpu_to_le64(time);
7920 		rsp->ChangeTime = cpu_to_le64(fp->change_time);
7921 		ksmbd_fd_put(work, fp);
7922 	} else {
7923 		rsp->Flags = 0;
7924 		rsp->AllocationSize = 0;
7925 		rsp->EndOfFile = 0;
7926 		rsp->Attributes = 0;
7927 		rsp->CreationTime = 0;
7928 		rsp->LastAccessTime = 0;
7929 		rsp->LastWriteTime = 0;
7930 		rsp->ChangeTime = 0;
7931 	}
7932 
7933 	err = ksmbd_close_fd(work, volatile_id);
7934 out:
7935 	if (!err)
7936 		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
7937 					sizeof(struct smb2_close_rsp));
7938 
7939 	if (err) {
7940 		if (rsp->hdr.Status == 0)
7941 			rsp->hdr.Status = STATUS_FILE_CLOSED;
7942 		smb2_set_err_rsp(work);
7943 	}
7944 
7945 	return err;
7946 }
7947 
7948 /**
7949  * smb2_echo() - handler for smb2 echo(ping) command
7950  * @work:	smb work containing echo request buffer
7951  *
7952  * Return:	0 on success, otherwise error
7953  */
7954 int smb2_echo(struct ksmbd_work *work)
7955 {
7956 	struct smb2_echo_rsp *rsp = smb_get_msg(work->response_buf);
7957 
7958 	ksmbd_debug(SMB, "Received smb2 echo request\n");
7959 
7960 	if (work->next_smb2_rcv_hdr_off)
7961 		rsp = ksmbd_resp_buf_next(work);
7962 
7963 	rsp->StructureSize = cpu_to_le16(4);
7964 	rsp->Reserved = 0;
7965 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
7966 }
7967 
7968 static int smb2_rename(struct ksmbd_work *work,
7969 		       struct ksmbd_file *fp,
7970 		       struct smb2_file_rename_info *file_info,
7971 		       struct nls_table *local_nls)
7972 {
7973 	struct ksmbd_share_config *share = fp->tcon->share_conf;
7974 	char *new_name = NULL;
7975 	int rc, flags = 0;
7976 
7977 	ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
7978 	new_name = smb2_get_name(file_info->FileName,
7979 				 le32_to_cpu(file_info->FileNameLength),
7980 				 local_nls);
7981 	if (IS_ERR(new_name))
7982 		return PTR_ERR(new_name);
7983 
7984 	if (fp->is_posix_ctxt == false && strchr(new_name, ':')) {
7985 		int s_type;
7986 		char *xattr_stream_name, *stream_name = NULL;
7987 		size_t xattr_stream_size;
7988 		int len;
7989 
7990 		rc = parse_stream_name(new_name, &stream_name, &s_type);
7991 		if (rc < 0)
7992 			goto out;
7993 
7994 		len = strlen(new_name);
7995 		if (len > 0 && new_name[len - 1] != '/') {
7996 			pr_err("not allow base filename in rename\n");
7997 			rc = -ESHARE;
7998 			goto out;
7999 		}
8000 
8001 		rc = ksmbd_vfs_xattr_stream_name(stream_name,
8002 						 &xattr_stream_name,
8003 						 &xattr_stream_size,
8004 						 s_type);
8005 		if (rc)
8006 			goto out;
8007 
8008 		rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
8009 					&fp->filp->f_path,
8010 					xattr_stream_name,
8011 					NULL, 0, 0, true);
8012 		if (rc < 0) {
8013 			pr_err("failed to store stream name in xattr: %d\n",
8014 			       rc);
8015 			rc = -EINVAL;
8016 		}
8017 		kfree(xattr_stream_name);
8018 		goto out;
8019 	}
8020 
8021 	ksmbd_debug(SMB, "new name %s\n", new_name);
8022 	if (ksmbd_share_veto_filename(share, new_name)) {
8023 		rc = -ENOENT;
8024 		ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
8025 		goto out;
8026 	}
8027 
8028 	if (!file_info->ReplaceIfExists)
8029 		flags = RENAME_NOREPLACE;
8030 
8031 	rc = ksmbd_vfs_check_rename_share(work, &fp->filp->f_path);
8032 	if (rc)
8033 		goto out;
8034 
8035 	smb_break_all_levII_oplock_rename(work, fp);
8036 	rc = ksmbd_vfs_rename(work, fp, new_name, flags);
8037 out:
8038 	kfree(new_name);
8039 	return rc;
8040 }
8041 
8042 static int smb2_create_link(struct ksmbd_work *work,
8043 			    struct ksmbd_share_config *share,
8044 			    struct smb2_file_link_info *file_info,
8045 			    unsigned int buf_len, struct file *filp,
8046 			    struct nls_table *local_nls)
8047 {
8048 	char *link_name = NULL, *target_name = NULL, *pathname = NULL;
8049 	struct path path;
8050 	int rc;
8051 
8052 	if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
8053 			le32_to_cpu(file_info->FileNameLength))
8054 		return -EINVAL;
8055 
8056 	ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
8057 	pathname = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
8058 	if (!pathname)
8059 		return -ENOMEM;
8060 
8061 	link_name = smb2_get_name(file_info->FileName,
8062 				  le32_to_cpu(file_info->FileNameLength),
8063 				  local_nls);
8064 	if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
8065 		rc = -EINVAL;
8066 		goto out;
8067 	}
8068 
8069 	ksmbd_debug(SMB, "link name is %s\n", link_name);
8070 	target_name = file_path(filp, pathname, PATH_MAX);
8071 	if (IS_ERR(target_name)) {
8072 		rc = -EINVAL;
8073 		goto out;
8074 	}
8075 
8076 	ksmbd_debug(SMB, "target name is %s\n", target_name);
8077 	rc = ksmbd_vfs_kern_path_start_removing(work, link_name, LOOKUP_NO_SYMLINKS,
8078 						&path, 0);
8079 	if (rc) {
8080 		if (rc != -ENOENT)
8081 			goto out;
8082 	} else {
8083 		if (file_info->ReplaceIfExists) {
8084 			rc = ksmbd_vfs_remove_file(work, &path);
8085 			if (rc) {
8086 				rc = -EINVAL;
8087 				ksmbd_debug(SMB, "cannot delete %s\n",
8088 					    link_name);
8089 			}
8090 		} else {
8091 			rc = -EEXIST;
8092 			ksmbd_debug(SMB, "link already exists\n");
8093 		}
8094 		ksmbd_vfs_kern_path_end_removing(&path);
8095 		if (rc)
8096 			goto out;
8097 	}
8098 	rc = ksmbd_vfs_link(work, target_name, link_name);
8099 	if (rc)
8100 		rc = -EINVAL;
8101 out:
8102 
8103 	if (!IS_ERR(link_name))
8104 		kfree(link_name);
8105 	kfree(pathname);
8106 	return rc;
8107 }
8108 
8109 static int set_file_basic_info(struct ksmbd_file *fp,
8110 			       struct file_basic_info *file_info,
8111 			       struct ksmbd_share_config *share)
8112 {
8113 	struct iattr attrs;
8114 	struct file *filp;
8115 	struct inode *inode;
8116 	struct mnt_idmap *idmap;
8117 	__le32 attrs_mask = FILE_ATTRIBUTE_DIRECTORY_LE |
8118 		FILE_ATTRIBUTE_COMPRESSED_LE;
8119 	int rc = 0;
8120 
8121 	if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
8122 		return -EACCES;
8123 
8124 	attrs.ia_valid = 0;
8125 	filp = fp->filp;
8126 	inode = file_inode(filp);
8127 	idmap = file_mnt_idmap(filp);
8128 
8129 	if (file_info->CreationTime)
8130 		fp->create_time = le64_to_cpu(file_info->CreationTime);
8131 
8132 	if (file_info->LastAccessTime) {
8133 		attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
8134 		attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
8135 	}
8136 
8137 	if (file_info->ChangeTime) {
8138 		fp->change_time = le64_to_cpu(file_info->ChangeTime);
8139 		inode_set_ctime_to_ts(inode,
8140 				ksmbd_NTtimeToUnix(file_info->ChangeTime));
8141 	}
8142 
8143 	if (file_info->LastWriteTime) {
8144 		attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
8145 		attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME);
8146 	}
8147 
8148 	if (file_info->Attributes) {
8149 		if (!S_ISDIR(inode->i_mode) &&
8150 		    file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
8151 			pr_err("can't change a file to a directory\n");
8152 			return -EINVAL;
8153 		}
8154 
8155 		if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
8156 			fp->f_ci->m_fattr =
8157 				(file_info->Attributes & ~FILE_ATTRIBUTE_COMPRESSED_LE) |
8158 				(fp->f_ci->m_fattr & attrs_mask);
8159 	}
8160 
8161 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
8162 	    (file_info->CreationTime || file_info->Attributes)) {
8163 		struct xattr_dos_attrib da = {0};
8164 
8165 		da.version = 4;
8166 		da.itime = fp->itime;
8167 		da.create_time = fp->create_time;
8168 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
8169 		da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
8170 			XATTR_DOSINFO_ITIME;
8171 
8172 		rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
8173 				true);
8174 		if (rc)
8175 			ksmbd_debug(SMB,
8176 				    "failed to restore file attribute in EA\n");
8177 		rc = 0;
8178 	}
8179 
8180 	if (attrs.ia_valid) {
8181 		struct dentry *dentry = filp->f_path.dentry;
8182 		struct inode *inode = d_inode(dentry);
8183 
8184 		if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
8185 			return -EACCES;
8186 
8187 		inode_lock(inode);
8188 		rc = notify_change(idmap, dentry, &attrs, NULL);
8189 		inode_unlock(inode);
8190 	}
8191 	return rc;
8192 }
8193 
8194 static int set_file_allocation_info(struct ksmbd_work *work,
8195 				    struct ksmbd_file *fp,
8196 				    struct smb2_file_alloc_info *file_alloc_info)
8197 {
8198 	/*
8199 	 * TODO : It's working fine only when store dos attributes
8200 	 * is not yes. need to implement a logic which works
8201 	 * properly with any smb.conf option
8202 	 */
8203 
8204 	loff_t alloc_blks;
8205 	u64 alloc_size;
8206 	struct inode *inode;
8207 	struct kstat stat;
8208 	int rc;
8209 
8210 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
8211 		return -EACCES;
8212 
8213 	if (ksmbd_stream_fd(fp) == true)
8214 		return 0;
8215 
8216 	rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
8217 			 AT_STATX_SYNC_AS_STAT);
8218 	if (rc)
8219 		return rc;
8220 
8221 	/*
8222 	 * AllocationSize is fully client-controlled (the caller only
8223 	 * validates the fixed 8-byte buffer length). Reject values that
8224 	 * would overflow the "round up to 512-byte blocks" conversion
8225 	 * below instead of silently wrapping it to a tiny block count,
8226 	 * which would truncate the file to a size the client never
8227 	 * asked for.
8228 	 */
8229 	alloc_size = le64_to_cpu(file_alloc_info->AllocationSize);
8230 	if (alloc_size > MAX_LFS_FILESIZE - 511)
8231 		return -EINVAL;
8232 
8233 	alloc_blks = (alloc_size + 511) >> 9;
8234 	inode = file_inode(fp->filp);
8235 
8236 	if (alloc_blks > stat.blocks) {
8237 		smb_break_all_levII_oplock(work, fp, 1);
8238 		rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
8239 				   alloc_blks * 512);
8240 		if (rc && rc != -EOPNOTSUPP) {
8241 			pr_err("vfs_fallocate is failed : %d\n", rc);
8242 			return rc;
8243 		}
8244 	} else if (alloc_blks < stat.blocks) {
8245 		loff_t size;
8246 
8247 		/*
8248 		 * Allocation size could be smaller than original one
8249 		 * which means allocated blocks in file should be
8250 		 * deallocated. use truncate to cut out it, but inode
8251 		 * size is also updated with truncate offset.
8252 		 * inode size is retained by backup inode size.
8253 		 */
8254 		size = i_size_read(inode);
8255 		rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
8256 		if (rc) {
8257 			pr_err("truncate failed!, err %d\n", rc);
8258 			return rc;
8259 		}
8260 		if (size < alloc_blks * 512)
8261 			i_size_write(inode, size);
8262 	}
8263 
8264 	fp->allocation_size = le64_to_cpu(file_alloc_info->AllocationSize);
8265 	fp->allocation_size_set = true;
8266 	return 0;
8267 }
8268 
8269 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
8270 				struct smb2_file_eof_info *file_eof_info)
8271 {
8272 	loff_t newsize;
8273 	struct inode *inode;
8274 	int rc;
8275 
8276 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
8277 		return -EACCES;
8278 
8279 	newsize = le64_to_cpu(file_eof_info->EndOfFile);
8280 	inode = file_inode(fp->filp);
8281 
8282 	/*
8283 	 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
8284 	 * on FAT32 shared device, truncate execution time is too long
8285 	 * and network error could cause from windows client. because
8286 	 * truncate of some filesystem like FAT32 fill zero data in
8287 	 * truncated range.
8288 	 */
8289 	if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC &&
8290 	    ksmbd_stream_fd(fp) == false) {
8291 		ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
8292 		rc = ksmbd_vfs_truncate(work, fp, newsize);
8293 		if (rc) {
8294 			ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
8295 			if (rc != -EAGAIN)
8296 				rc = -EBADF;
8297 			return rc;
8298 		}
8299 	}
8300 	return 0;
8301 }
8302 
8303 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
8304 			   struct smb2_file_rename_info *rename_info,
8305 			   unsigned int buf_len)
8306 {
8307 	if (!(fp->daccess & FILE_DELETE_LE)) {
8308 		pr_err("no right to delete : 0x%x\n", fp->daccess);
8309 		return -EACCES;
8310 	}
8311 
8312 	if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
8313 			le32_to_cpu(rename_info->FileNameLength))
8314 		return -EINVAL;
8315 
8316 	if (!le32_to_cpu(rename_info->FileNameLength))
8317 		return -EINVAL;
8318 
8319 	return smb2_rename(work, fp, rename_info, work->conn->local_nls);
8320 }
8321 
8322 static int set_file_disposition_info(struct ksmbd_work *work,
8323 				     struct ksmbd_file *fp,
8324 				     struct smb2_file_disposition_info *file_info)
8325 {
8326 	struct inode *inode;
8327 
8328 	if (!(fp->daccess & FILE_DELETE_LE)) {
8329 		pr_err("no right to delete : 0x%x\n", fp->daccess);
8330 		return -EACCES;
8331 	}
8332 
8333 	if (fp->f_ci->m_fattr & FILE_ATTRIBUTE_READONLY_LE)
8334 		return -EACCES;
8335 
8336 	inode = file_inode(fp->filp);
8337 	if (file_info->DeletePending) {
8338 		if (ksmbd_has_stream_without_delete_share(fp))
8339 			return -ESHARE;
8340 
8341 		if (S_ISDIR(inode->i_mode) && !ksmbd_stream_fd(fp) &&
8342 		    ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
8343 			return -EBUSY;
8344 		smb_break_all_levII_oplock_for_delete(work, fp);
8345 		ksmbd_fd_set_delete_pending(fp);
8346 	} else {
8347 		ksmbd_fd_clear_delete_pending(fp);
8348 	}
8349 	return 0;
8350 }
8351 
8352 static int set_file_position_info(struct ksmbd_file *fp,
8353 				  struct smb2_file_pos_info *file_info)
8354 {
8355 	loff_t current_byte_offset;
8356 	unsigned long sector_size;
8357 	struct inode *inode;
8358 
8359 	inode = file_inode(fp->filp);
8360 	current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
8361 	sector_size = inode->i_sb->s_blocksize;
8362 
8363 	if (current_byte_offset < 0 ||
8364 	    (fp->coption & FILE_NO_INTERMEDIATE_BUFFERING_LE &&
8365 	     current_byte_offset & (sector_size - 1))) {
8366 		pr_err("CurrentByteOffset is not valid : %llu\n",
8367 		       current_byte_offset);
8368 		return -EINVAL;
8369 	}
8370 
8371 	if (ksmbd_stream_fd(fp) == false)
8372 		fp->filp->f_pos = current_byte_offset;
8373 	else {
8374 		if (current_byte_offset > XATTR_SIZE_MAX)
8375 			current_byte_offset = XATTR_SIZE_MAX;
8376 		fp->stream.pos = current_byte_offset;
8377 	}
8378 	return 0;
8379 }
8380 
8381 static int set_file_mode_info(struct ksmbd_file *fp,
8382 			      struct smb2_file_mode_info *file_info)
8383 {
8384 	__le32 mode;
8385 
8386 	mode = file_info->Mode;
8387 
8388 	if ((mode & ~FILE_MODE_INFO_MASK)) {
8389 		pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
8390 		return -EINVAL;
8391 	}
8392 
8393 	/*
8394 	 * TODO : need to implement consideration for
8395 	 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
8396 	 */
8397 	ksmbd_vfs_set_fadvise(fp->filp, mode);
8398 	fp->coption = mode;
8399 	return 0;
8400 }
8401 
8402 /**
8403  * smb2_set_info_file() - handler for smb2 set info command
8404  * @work:	smb work containing set info command buffer
8405  * @fp:		ksmbd_file pointer
8406  * @req:	request buffer pointer
8407  * @share:	ksmbd_share_config pointer
8408  *
8409  * Return:	0 on success, otherwise error
8410  */
8411 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
8412 			      struct smb2_set_info_req *req,
8413 			      struct ksmbd_share_config *share)
8414 {
8415 	unsigned int buf_len = le32_to_cpu(req->BufferLength);
8416 	char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
8417 
8418 	switch (req->FileInfoClass) {
8419 	case FILE_BASIC_INFORMATION:
8420 	{
8421 		if (buf_len < sizeof(struct file_basic_info))
8422 			return -EMSGSIZE;
8423 
8424 		return set_file_basic_info(fp, (struct file_basic_info *)buffer, share);
8425 	}
8426 	case FILE_ALLOCATION_INFORMATION:
8427 	{
8428 		if (buf_len < sizeof(struct smb2_file_alloc_info))
8429 			return -EMSGSIZE;
8430 
8431 		return set_file_allocation_info(work, fp,
8432 						(struct smb2_file_alloc_info *)buffer);
8433 	}
8434 	case FILE_END_OF_FILE_INFORMATION:
8435 	{
8436 		if (buf_len < sizeof(struct smb2_file_eof_info))
8437 			return -EMSGSIZE;
8438 
8439 		return set_end_of_file_info(work, fp,
8440 					    (struct smb2_file_eof_info *)buffer);
8441 	}
8442 	case FILE_RENAME_INFORMATION:
8443 	{
8444 		if (buf_len < sizeof(struct smb2_file_rename_info))
8445 			return -EMSGSIZE;
8446 
8447 		return set_rename_info(work, fp,
8448 				       (struct smb2_file_rename_info *)buffer,
8449 				       buf_len);
8450 	}
8451 	case FILE_LINK_INFORMATION:
8452 	{
8453 		struct smb2_file_link_info *file_info;
8454 
8455 		if (buf_len < sizeof(struct smb2_file_link_info))
8456 			return -EMSGSIZE;
8457 
8458 		file_info = (struct smb2_file_link_info *)buffer;
8459 		if (file_info->ReplaceIfExists && !(fp->daccess & FILE_DELETE_LE)) {
8460 			pr_err("no right to delete : 0x%x\n", fp->daccess);
8461 			return -EACCES;
8462 		}
8463 
8464 		return smb2_create_link(work, work->tcon->share_conf, file_info,
8465 					buf_len, fp->filp,
8466 					work->conn->local_nls);
8467 	}
8468 	case FILE_DISPOSITION_INFORMATION:
8469 	{
8470 		if (buf_len < sizeof(struct smb2_file_disposition_info))
8471 			return -EMSGSIZE;
8472 
8473 		return set_file_disposition_info(work, fp,
8474 						 (struct smb2_file_disposition_info *)buffer);
8475 	}
8476 	case FILE_FULL_EA_INFORMATION:
8477 	{
8478 		if (!(fp->daccess & FILE_WRITE_EA_LE)) {
8479 			pr_err("Not permitted to write ext  attr: 0x%x\n",
8480 			       fp->daccess);
8481 			return -EACCES;
8482 		}
8483 
8484 		if (buf_len < sizeof(struct smb2_ea_info))
8485 			return -EMSGSIZE;
8486 
8487 		return smb2_set_ea((struct smb2_ea_info *)buffer,
8488 				   buf_len, &fp->filp->f_path, true);
8489 	}
8490 	case FILE_POSITION_INFORMATION:
8491 	{
8492 		if (buf_len < sizeof(struct smb2_file_pos_info))
8493 			return -EMSGSIZE;
8494 
8495 		return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
8496 	}
8497 	case FILE_MODE_INFORMATION:
8498 	{
8499 		if (buf_len < sizeof(struct smb2_file_mode_info))
8500 			return -EMSGSIZE;
8501 
8502 		return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
8503 	}
8504 	}
8505 
8506 	pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
8507 	return -EOPNOTSUPP;
8508 }
8509 
8510 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
8511 			     char *buffer, int buf_len)
8512 {
8513 	struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
8514 
8515 	fp->saccess |= FILE_SHARE_DELETE_LE;
8516 
8517 	if (!(fp->daccess & (FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE)))
8518 		return -EACCES;
8519 
8520 	return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
8521 			buf_len, false, true);
8522 }
8523 
8524 /**
8525  * smb2_set_info() - handler for smb2 set info command handler
8526  * @work:	smb work containing set info request buffer
8527  *
8528  * Return:	0 on success, otherwise error
8529  */
8530 int smb2_set_info(struct ksmbd_work *work)
8531 {
8532 	const struct cred *saved_cred;
8533 	struct smb2_set_info_req *req;
8534 	struct smb2_set_info_rsp *rsp;
8535 	struct ksmbd_file *fp = NULL;
8536 	int rc = 0;
8537 	bool chseq_err = false;
8538 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
8539 
8540 	ksmbd_debug(SMB, "Received smb2 set info request\n");
8541 
8542 	if (work->next_smb2_rcv_hdr_off) {
8543 		req = ksmbd_req_buf_next(work);
8544 		rsp = ksmbd_resp_buf_next(work);
8545 		if (smb2_compound_has_failed(work, &rsp->hdr))
8546 			return -EACCES;
8547 		if (!has_file_id(req->VolatileFileId)) {
8548 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8549 				    work->compound_fid);
8550 			id = work->compound_fid;
8551 			pid = work->compound_pfid;
8552 		}
8553 	} else {
8554 		req = smb_get_msg(work->request_buf);
8555 		rsp = smb_get_msg(work->response_buf);
8556 	}
8557 
8558 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8559 		ksmbd_debug(SMB, "User does not have write permission\n");
8560 		pr_err("User does not have write permission\n");
8561 		rc = -EACCES;
8562 		goto err_out;
8563 	}
8564 
8565 	if (!has_file_id(id)) {
8566 		id = req->VolatileFileId;
8567 		pid = req->PersistentFileId;
8568 	}
8569 
8570 	fp = ksmbd_lookup_fd_slow(work, id, pid);
8571 	if (!fp) {
8572 		ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
8573 		rc = -ENOENT;
8574 		goto err_out;
8575 	}
8576 
8577 	rc = smb2_set_request_open(work, fp, &req->hdr, true, false);
8578 	if (rc) {
8579 		rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
8580 		chseq_err = true;
8581 		goto err_out;
8582 	}
8583 
8584 	saved_cred = override_creds(fp->filp->f_cred);
8585 	switch (req->InfoType) {
8586 	case SMB2_O_INFO_FILE:
8587 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
8588 		rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
8589 		break;
8590 	case SMB2_O_INFO_SECURITY:
8591 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
8592 		rc = smb2_set_info_sec(fp,
8593 				       le32_to_cpu(req->AdditionalInformation),
8594 				       (char *)req + le16_to_cpu(req->BufferOffset),
8595 				       le32_to_cpu(req->BufferLength));
8596 		break;
8597 	default:
8598 		rc = -EOPNOTSUPP;
8599 	}
8600 	revert_creds(saved_cred);
8601 
8602 	if (rc < 0)
8603 		goto err_out;
8604 
8605 	rsp->StructureSize = cpu_to_le16(2);
8606 	rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
8607 			       sizeof(struct smb2_set_info_rsp));
8608 	if (rc)
8609 		goto err_out;
8610 	ksmbd_fd_put(work, fp);
8611 	return 0;
8612 
8613 err_out:
8614 	if (rc == -EACCES || rc == -EPERM || rc == -EXDEV) {
8615 		if (fp && req->InfoType == SMB2_O_INFO_FILE &&
8616 		    req->FileInfoClass == FILE_DISPOSITION_INFORMATION &&
8617 		    fp->f_ci->m_fattr & FILE_ATTRIBUTE_READONLY_LE)
8618 			rsp->hdr.Status = STATUS_CANNOT_DELETE;
8619 		else
8620 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
8621 	}
8622 	else if (rc == -EINVAL)
8623 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8624 	else if (rc == -EMSGSIZE)
8625 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
8626 	else if (rc == -ENOSPC || rc == -EFBIG)
8627 		rsp->hdr.Status = STATUS_DISK_FULL;
8628 	else if (rc == -ESHARE)
8629 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
8630 	else if (rc == -ENOENT)
8631 		rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
8632 	else if (rc == -EBUSY || rc == -ENOTEMPTY)
8633 		rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
8634 	else if (rc == -EAGAIN && !chseq_err)
8635 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
8636 	else if (rc == -EBADF || rc == -ESTALE)
8637 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
8638 	else if (rc == -EEXIST)
8639 		rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
8640 	else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
8641 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
8642 	smb2_set_err_rsp(work);
8643 	ksmbd_fd_put(work, fp);
8644 	ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
8645 	return rc;
8646 }
8647 
8648 /**
8649  * smb2_read_pipe() - handler for smb2 read from IPC pipe
8650  * @work:	smb work containing read IPC pipe command buffer
8651  *
8652  * Return:	0 on success, otherwise error
8653  */
8654 static noinline int smb2_read_pipe(struct ksmbd_work *work)
8655 {
8656 	int nbytes = 0, err;
8657 	u64 id;
8658 	struct ksmbd_rpc_command *rpc_resp;
8659 	struct smb2_read_req *req;
8660 	struct smb2_read_rsp *rsp;
8661 
8662 	WORK_BUFFERS(work, req, rsp);
8663 
8664 	id = req->VolatileFileId;
8665 
8666 	rpc_resp = ksmbd_rpc_read(work->sess, id);
8667 	if (rpc_resp) {
8668 		void *aux_payload_buf;
8669 
8670 		if (rpc_resp->flags != KSMBD_RPC_OK) {
8671 			err = -EINVAL;
8672 			goto out;
8673 		}
8674 
8675 		aux_payload_buf =
8676 			kvmalloc(ALIGN(rpc_resp->payload_sz, 8),
8677 				 KSMBD_DEFAULT_GFP);
8678 		if (!aux_payload_buf) {
8679 			err = -ENOMEM;
8680 			goto out;
8681 		}
8682 
8683 		memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
8684 		if (rpc_resp->payload_sz & 7)
8685 			memset(aux_payload_buf + rpc_resp->payload_sz, 0,
8686 			       ALIGN(rpc_resp->payload_sz, 8) -
8687 			       rpc_resp->payload_sz);
8688 
8689 		nbytes = rpc_resp->payload_sz;
8690 		err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
8691 					     offsetof(struct smb2_read_rsp, Buffer),
8692 					     aux_payload_buf, nbytes);
8693 		if (err) {
8694 			kvfree(aux_payload_buf);
8695 			goto out;
8696 		}
8697 		kvfree(rpc_resp);
8698 	} else {
8699 		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
8700 					offsetof(struct smb2_read_rsp, Buffer));
8701 		if (err)
8702 			goto out;
8703 	}
8704 
8705 	rsp->StructureSize = cpu_to_le16(17);
8706 	rsp->DataOffset = 80;
8707 	rsp->Reserved = 0;
8708 	rsp->DataLength = cpu_to_le32(nbytes);
8709 	rsp->DataRemaining = 0;
8710 	rsp->Flags = 0;
8711 	return 0;
8712 
8713 out:
8714 	rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
8715 	smb2_set_err_rsp(work);
8716 	kvfree(rpc_resp);
8717 	return err;
8718 }
8719 
8720 /**
8721  * smb2_set_rdma_key() - validate descriptors and save invalidation state
8722  * @work: request work item
8723  * @desc: first RDMA buffer descriptor
8724  * @Channel: nested RDMA channel type
8725  * @channel_info_len: descriptor array length
8726  *
8727  * Return: 0 on success, otherwise -EINVAL
8728  */
8729 static int smb2_set_rdma_key(struct ksmbd_work *work,
8730 			     struct smbdirect_buffer_descriptor_v1 *desc,
8731 			     __le32 Channel, __le16 channel_info_len)
8732 {
8733 	unsigned int i, ch_count;
8734 
8735 	if (Channel != SMB2_CHANNEL_RDMA_V1 &&
8736 	    Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE)
8737 		return -EINVAL;
8738 	if (work->conn->dialect == SMB30_PROT_ID &&
8739 	    Channel != SMB2_CHANNEL_RDMA_V1)
8740 		return -EINVAL;
8741 	if (le16_to_cpu(channel_info_len) % sizeof(*desc))
8742 		return -EINVAL;
8743 
8744 	ch_count = le16_to_cpu(channel_info_len) / sizeof(*desc);
8745 	if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
8746 		for (i = 0; i < ch_count; i++) {
8747 			pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
8748 				i,
8749 				le32_to_cpu(desc[i].token),
8750 				le32_to_cpu(desc[i].length));
8751 		}
8752 	}
8753 	if (!ch_count)
8754 		return -EINVAL;
8755 
8756 	work->need_invalidate_rkey =
8757 		(Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
8758 	if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
8759 		work->remote_key = le32_to_cpu(desc->token);
8760 	return 0;
8761 }
8762 
8763 /**
8764  * smb2_prep_rdma_read() - transform an RDMA READ payload
8765  * @work: request work item
8766  * @req: READ request controlling encryption or signing
8767  * @rsp: READ response receiving transform metadata
8768  * @data: data that will be transferred through RDMA
8769  * @datalen: data length
8770  *
8771  * Encrypt the payload in place and encode the detached crypto metadata in
8772  * the response buffer.
8773  *
8774  * Return: metadata length, zero when no transform applies, or negative errno
8775  */
8776 static int smb2_prep_rdma_read(struct ksmbd_work *work,
8777 			       struct smb2_read_req *req,
8778 			       struct smb2_read_rsp *rsp,
8779 			       void *data, unsigned int datalen)
8780 {
8781 	struct ksmbd_conn *conn = work->conn;
8782 	struct smb2_rdma_transform *transform;
8783 	struct smb2_rdma_crypto_transform *crypto;
8784 	u8 *nonce;
8785 	unsigned int nonce_len = 0, transform_len;
8786 	u16 transform_type;
8787 	int err;
8788 
8789 	if (!work->encrypted ||
8790 	    !(conn->rdma_transform_ids & BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION)))
8791 		return 0;
8792 
8793 	transform_type = SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION;
8794 	nonce_len = (conn->cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8795 		     conn->cipher_type == SMB2_ENCRYPTION_AES256_GCM) ?
8796 		SMB3_AES_GCM_NONCE : SMB3_AES_CCM_NONCE;
8797 
8798 	transform = (struct smb2_rdma_transform *)rsp->Buffer;
8799 	crypto = (struct smb2_rdma_crypto_transform *)(transform + 1);
8800 	memset(transform, 0, sizeof(*transform) + sizeof(*crypto) +
8801 	       SMB2_SIGNATURE_SIZE + nonce_len);
8802 	transform->Channel = SMB2_CHANNEL_NONE;
8803 	transform->TransformCount = cpu_to_le16(1);
8804 
8805 	crypto->TransformType = cpu_to_le16(transform_type);
8806 	crypto->SignatureLength = cpu_to_le16(SMB2_SIGNATURE_SIZE);
8807 	crypto->NonceLength = cpu_to_le16(nonce_len);
8808 	nonce = crypto->Signature + SMB2_SIGNATURE_SIZE;
8809 
8810 	get_random_bytes(nonce, nonce_len);
8811 	err = ksmbd_crypt_rdma(conn,
8812 			       work->sess->smb3encryptionkey,
8813 			       data, datalen, nonce, nonce_len,
8814 			       crypto->Signature,
8815 			       SMB2_SIGNATURE_SIZE, true);
8816 	if (err) {
8817 		pr_err("RDMA READ encryption failed: session=%llu payload=%u rc=%d\n",
8818 		       work->sess->id, datalen, err);
8819 		return err;
8820 	}
8821 
8822 	transform_len = sizeof(*transform) + sizeof(*crypto) +
8823 		SMB2_SIGNATURE_SIZE + nonce_len;
8824 	rsp->Flags = SMB2_READFLAG_RESPONSE_RDMA_TRANSFORM;
8825 	rsp->DataLength = cpu_to_le32(transform_len);
8826 	ksmbd_debug(RDMA,
8827 		    "RDMA READ encryption prepared: session=%llu cipher=0x%04x payload=%u transform=%u nonce=%u tag=%u\n",
8828 		    work->sess->id, le16_to_cpu(conn->cipher_type), datalen,
8829 		    transform_len, nonce_len, SMB2_SIGNATURE_SIZE);
8830 	return transform_len;
8831 }
8832 
8833 struct smb2_rdma_write_transform {
8834 	struct smbdirect_buffer_descriptor_v1 *desc;
8835 	struct smb2_rdma_crypto_transform *crypto;
8836 	u8 *nonce;
8837 	unsigned int desc_len;
8838 	unsigned int nonce_len;
8839 	unsigned int signature_len;
8840 	u16 type;
8841 	__le32 channel;
8842 };
8843 
8844 /**
8845  * smb2_current_req_len() - return the current compound request element size
8846  * @work: request work item
8847  * @hdr: current SMB2 header
8848  *
8849  * Return: current request element length measured from the SMB2 header
8850  */
8851 static unsigned int smb2_current_req_len(struct ksmbd_work *work,
8852 					 struct smb2_hdr *hdr)
8853 {
8854 	if (hdr->NextCommand)
8855 		return le32_to_cpu(hdr->NextCommand);
8856 	return get_rfc1002_len(work->request_buf) -
8857 		work->next_smb2_rcv_hdr_off;
8858 }
8859 
8860 /**
8861  * check_rdma_desc() - validate an RDMA descriptor array
8862  * @desc: descriptor array
8863  * @desc_len: descriptor array length
8864  * @required_len: minimum aggregate buffer length
8865  *
8866  * Return: 0 when the descriptors cover the transfer, otherwise -EINVAL
8867  */
8868 static int check_rdma_desc(struct smbdirect_buffer_descriptor_v1 *desc,
8869 			   unsigned int desc_len,
8870 			   unsigned int required_len)
8871 {
8872 	unsigned int i, count;
8873 	u64 described_len = 0;
8874 
8875 	if (!desc_len || desc_len % sizeof(*desc))
8876 		return -EINVAL;
8877 	count = desc_len / sizeof(*desc);
8878 	if (!le32_to_cpu(desc[0].length))
8879 		return -EINVAL;
8880 	for (i = 0; i < count; i++)
8881 		described_len += le32_to_cpu(desc[i].length);
8882 	return described_len < required_len ? -EINVAL : 0;
8883 }
8884 
8885 /**
8886  * smb2_parse_rdma_write_transform() - validate RDMA WRITE transform metadata
8887  * @work: request work item
8888  * @req: WRITE request containing the transform
8889  * @info: parsed transform information
8890  *
8891  * Validate transform counts, crypto fields, descriptor alignment and bounds,
8892  * negotiated algorithms, and the nested RDMA channel.
8893  *
8894  * Return: 0 on success, otherwise a negative errno
8895  */
8896 static int smb2_parse_rdma_write_transform(struct ksmbd_work *work,
8897 					   struct smb2_write_req *req,
8898 					   struct smb2_rdma_write_transform *info)
8899 {
8900 	struct smb2_rdma_transform *transform;
8901 	struct smb2_rdma_crypto_transform *crypto;
8902 	unsigned int req_len = smb2_current_req_len(work, &req->hdr);
8903 	unsigned int offset = le16_to_cpu(req->WriteChannelInfoOffset);
8904 	unsigned int length = le16_to_cpu(req->WriteChannelInfoLength);
8905 	unsigned int desc_offset, desc_len, crypto_len, expected_desc_offset;
8906 	int err;
8907 
8908 	if (!work->conn->rdma_transform_ids ||
8909 	    offset < offsetof(struct smb2_write_req, Buffer) ||
8910 	    length < sizeof(*transform) || offset > req_len ||
8911 	    length > req_len - offset)
8912 		return -EINVAL;
8913 
8914 	transform = (struct smb2_rdma_transform *)((char *)req + offset);
8915 	if (le16_to_cpu(transform->TransformCount) != 1 ||
8916 	    (transform->Channel != SMB2_CHANNEL_RDMA_V1 &&
8917 	     transform->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE))
8918 		return -EINVAL;
8919 
8920 	desc_offset = le16_to_cpu(transform->RdmaDescriptorOffset);
8921 	desc_len = le16_to_cpu(transform->RdmaDescriptorLength);
8922 	if (!desc_len || desc_len % sizeof(*info->desc) ||
8923 	    desc_offset < sizeof(*transform) || desc_offset > length ||
8924 	    desc_len > length - desc_offset)
8925 		return -EINVAL;
8926 
8927 	crypto = (struct smb2_rdma_crypto_transform *)(transform + 1);
8928 	if (length - sizeof(*transform) < sizeof(*crypto))
8929 		return -EINVAL;
8930 	info->type = le16_to_cpu(crypto->TransformType);
8931 	info->signature_len = le16_to_cpu(crypto->SignatureLength);
8932 	info->nonce_len = le16_to_cpu(crypto->NonceLength);
8933 	if (!info->signature_len)
8934 		return info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION ?
8935 			-EBADMSG : -EINVAL;
8936 	if (info->signature_len > SMB2_SIGNATURE_SIZE)
8937 		return info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION ?
8938 			-EBADMSG : -EINVAL;
8939 	if (info->signature_len > length - sizeof(*transform) - sizeof(*crypto) ||
8940 	    info->nonce_len > length - sizeof(*transform) - sizeof(*crypto) -
8941 				 info->signature_len)
8942 		return -EINVAL;
8943 
8944 	crypto_len = sizeof(*crypto) + info->signature_len + info->nonce_len;
8945 	expected_desc_offset = ALIGN(sizeof(*transform) + crypto_len, 8);
8946 	if (desc_offset != expected_desc_offset)
8947 		return -EINVAL;
8948 
8949 	if (info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION) {
8950 		unsigned int expected_nonce_len;
8951 
8952 		if (!(work->conn->rdma_transform_ids &
8953 		      BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION)) || !work->encrypted)
8954 			return -EINVAL;
8955 		expected_nonce_len =
8956 			(work->conn->cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8957 			 work->conn->cipher_type == SMB2_ENCRYPTION_AES256_GCM) ?
8958 			SMB3_AES_GCM_NONCE : SMB3_AES_CCM_NONCE;
8959 		if (info->nonce_len != expected_nonce_len)
8960 			return -EBADMSG;
8961 	} else {
8962 		return -EINVAL;
8963 	}
8964 
8965 	info->desc = (struct smbdirect_buffer_descriptor_v1 *)
8966 		((char *)transform + desc_offset);
8967 	info->desc_len = desc_len;
8968 	info->crypto = crypto;
8969 	info->nonce = crypto->Signature + info->signature_len;
8970 	info->channel = transform->Channel;
8971 	err = check_rdma_desc(info->desc, info->desc_len,
8972 			      le32_to_cpu(req->RemainingBytes));
8973 	if (err)
8974 		return err;
8975 
8976 	ksmbd_debug(RDMA,
8977 		    "RDMA WRITE encryption metadata: session=%llu cipher=0x%04x payload=%u channel=0x%x descriptors=%zu nonce=%u tag=%u\n",
8978 		    work->sess->id, le16_to_cpu(work->conn->cipher_type),
8979 		    le32_to_cpu(req->RemainingBytes), le32_to_cpu(info->channel),
8980 		    info->desc_len / sizeof(*info->desc), info->nonce_len,
8981 		    info->signature_len);
8982 	return 0;
8983 }
8984 
8985 /**
8986  * smb2_read_rdma() - transfer READ data to client RDMA buffers
8987  * @work: request work item
8988  * @req: READ request containing client descriptors
8989  * @data_buf: data to transfer
8990  * @length: data length
8991  *
8992  * Return: transferred length on success, otherwise a negative errno
8993  */
8994 static ssize_t smb2_read_rdma(struct ksmbd_work *work,
8995 			      struct smb2_read_req *req, void *data_buf,
8996 			      size_t length)
8997 {
8998 	int err;
8999 
9000 	err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
9001 				    (struct smbdirect_buffer_descriptor_v1 *)
9002 				    ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
9003 				    le16_to_cpu(req->ReadChannelInfoLength));
9004 	if (err)
9005 		return err;
9006 
9007 	return length;
9008 }
9009 
9010 /**
9011  * smb2_read() - handler for smb2 read from file
9012  * @work:	smb work containing read command buffer
9013  *
9014  * Return:	0 on success, otherwise error
9015  */
9016 int smb2_read(struct ksmbd_work *work)
9017 {
9018 	struct ksmbd_conn *conn = work->conn;
9019 	struct smb2_read_req *req;
9020 	struct smb2_read_rsp *rsp;
9021 	struct ksmbd_file *fp = NULL;
9022 	loff_t offset;
9023 	size_t length, mincount;
9024 	ssize_t nbytes = 0, remain_bytes = 0;
9025 	int err = 0;
9026 	int rdma_transform_len = 0;
9027 	bool is_rdma_channel = false, async_interim = false;
9028 	unsigned int max_read_size = conn->vals->max_read_size;
9029 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
9030 	void *aux_payload_buf;
9031 
9032 	ksmbd_debug(SMB, "Received smb2 read request\n");
9033 
9034 	if (test_share_config_flag(work->tcon->share_conf,
9035 				   KSMBD_SHARE_FLAG_PIPE)) {
9036 		ksmbd_debug(SMB, "IPC pipe read request\n");
9037 		return smb2_read_pipe(work);
9038 	}
9039 
9040 	if (work->next_smb2_rcv_hdr_off) {
9041 		req = ksmbd_req_buf_next(work);
9042 		rsp = ksmbd_resp_buf_next(work);
9043 		if (smb2_compound_has_failed(work, &rsp->hdr))
9044 			return -EACCES;
9045 		if (!has_file_id(req->VolatileFileId)) {
9046 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
9047 					work->compound_fid);
9048 			id = work->compound_fid;
9049 			pid = work->compound_pfid;
9050 		}
9051 	} else {
9052 		req = smb_get_msg(work->request_buf);
9053 		rsp = smb_get_msg(work->response_buf);
9054 	}
9055 
9056 	if (!has_file_id(id)) {
9057 		id = req->VolatileFileId;
9058 		pid = req->PersistentFileId;
9059 	}
9060 
9061 	if (req->Channel != SMB2_CHANNEL_NONE &&
9062 	    req->Channel != SMB2_CHANNEL_RDMA_V1 &&
9063 	    req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
9064 		err = -EINVAL;
9065 		goto out;
9066 	}
9067 	if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
9068 	    req->Channel == SMB2_CHANNEL_RDMA_V1) {
9069 		is_rdma_channel = true;
9070 		max_read_size = get_smbd_max_read_write_size(work->conn->transport);
9071 		if (max_read_size == 0) {
9072 			err = -EINVAL;
9073 			goto out;
9074 		}
9075 	}
9076 
9077 	if (is_rdma_channel == true) {
9078 		unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
9079 		unsigned int ch_len = le16_to_cpu(req->ReadChannelInfoLength);
9080 		unsigned int req_len = smb2_current_req_len(work, &req->hdr);
9081 		struct smbdirect_buffer_descriptor_v1 *desc;
9082 
9083 		if (!le32_to_cpu(req->Length) ||
9084 		    ch_offset < offsetof(struct smb2_read_req, Buffer) ||
9085 		    ch_offset > req_len || ch_len > req_len - ch_offset) {
9086 			err = -EINVAL;
9087 			goto out;
9088 		}
9089 		desc = (struct smbdirect_buffer_descriptor_v1 *)
9090 			((char *)req + ch_offset);
9091 		err = check_rdma_desc(desc, ch_len, le32_to_cpu(req->Length));
9092 		if (err)
9093 			goto out;
9094 		err = smb2_set_rdma_key(work, desc,
9095 					req->Channel,
9096 					req->ReadChannelInfoLength);
9097 		if (err)
9098 			goto out;
9099 	}
9100 
9101 	fp = ksmbd_lookup_fd_slow(work, id, pid);
9102 	if (!fp) {
9103 		err = -ENOENT;
9104 		goto out;
9105 	}
9106 
9107 	err = smb2_set_request_open(work, fp, &req->hdr, true, true);
9108 	if (err)
9109 		goto out;
9110 
9111 	if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
9112 		pr_err("Not permitted to read : 0x%x\n", fp->daccess);
9113 		err = -EACCES;
9114 		goto out;
9115 	}
9116 
9117 	if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
9118 		err = setup_async_work(work, NULL, NULL);
9119 		if (err)
9120 			goto out;
9121 		smb2_send_interim_resp(work, STATUS_PENDING);
9122 		async_interim = true;
9123 	}
9124 
9125 	offset = le64_to_cpu(req->Offset);
9126 	if (offset < 0) {
9127 		err = -EINVAL;
9128 		goto out;
9129 	}
9130 	length = le32_to_cpu(req->Length);
9131 	mincount = le32_to_cpu(req->MinimumCount);
9132 
9133 	if (length > max_read_size) {
9134 		ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
9135 			    max_read_size);
9136 		err = -EINVAL;
9137 		goto out;
9138 	}
9139 
9140 	ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
9141 		    fp->filp, offset, length);
9142 
9143 	aux_payload_buf = kvmalloc(ALIGN(length, 8), KSMBD_DEFAULT_GFP);
9144 	if (!aux_payload_buf) {
9145 		err = -ENOMEM;
9146 		goto out;
9147 	}
9148 
9149 	nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
9150 	if (nbytes < 0) {
9151 		kvfree(aux_payload_buf);
9152 		err = nbytes;
9153 		goto out;
9154 	}
9155 
9156 	/*
9157 	 * ksmbd_vfs_read() fills only nbytes; the [nbytes, ALIGN(nbytes, 8))
9158 	 * tail of the un-zeroed buffer is transmitted as compound-response
9159 	 * alignment padding, leaking uninitialized kernel memory to the
9160 	 * client.  Zero just that tail.
9161 	 */
9162 	if (nbytes & 7)
9163 		memset(aux_payload_buf + nbytes, 0, ALIGN(nbytes, 8) - nbytes);
9164 
9165 	if ((nbytes == 0 && length != 0) || nbytes < mincount) {
9166 		kvfree(aux_payload_buf);
9167 		rsp->hdr.Status = STATUS_END_OF_FILE;
9168 		smb2_set_err_rsp(work);
9169 		if (async_interim)
9170 			release_async_work(work);
9171 		ksmbd_fd_put(work, fp);
9172 		return -ENODATA;
9173 	}
9174 
9175 	ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
9176 		    nbytes, offset, mincount);
9177 
9178 	if (is_rdma_channel == true) {
9179 		rdma_transform_len = smb2_prep_rdma_read(work, req,
9180 							 rsp,
9181 							 aux_payload_buf,
9182 							 nbytes);
9183 		if (rdma_transform_len < 0) {
9184 			kvfree(aux_payload_buf);
9185 			err = rdma_transform_len;
9186 			goto out;
9187 		}
9188 		/* write data to the client using rdma channel */
9189 		remain_bytes = smb2_read_rdma(work, req,
9190 					      aux_payload_buf,
9191 					      nbytes);
9192 		if (remain_bytes < 0)
9193 			pr_err("RDMA READ transfer failed: session=%llu payload=%zu transform=%d rc=%zd\n",
9194 			       work->sess ? work->sess->id : 0, nbytes,
9195 			       rdma_transform_len, remain_bytes);
9196 		else
9197 			ksmbd_debug(RDMA,
9198 				    "RDMA READ transfer completed: session=%llu payload=%zu transform=%d\n",
9199 				    work->sess ? work->sess->id : 0, nbytes,
9200 				    rdma_transform_len);
9201 		kvfree(aux_payload_buf);
9202 		aux_payload_buf = NULL;
9203 		nbytes = 0;
9204 		if (remain_bytes < 0) {
9205 			err = (int)remain_bytes;
9206 			goto out;
9207 		}
9208 	}
9209 
9210 	rsp->StructureSize = cpu_to_le16(17);
9211 	rsp->DataOffset = 80;
9212 	rsp->Reserved = 0;
9213 	rsp->DataLength = cpu_to_le32(rdma_transform_len ?: nbytes);
9214 	rsp->DataRemaining = cpu_to_le32(remain_bytes);
9215 	rsp->Flags = rdma_transform_len ?
9216 		SMB2_READFLAG_RESPONSE_RDMA_TRANSFORM : 0;
9217 	err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
9218 				     offsetof(struct smb2_read_rsp, Buffer) +
9219 				     rdma_transform_len,
9220 				     aux_payload_buf, nbytes);
9221 	if (err) {
9222 		kvfree(aux_payload_buf);
9223 		goto out;
9224 	}
9225 	if (async_interim)
9226 		release_async_work(work);
9227 	/*
9228 	 * RDMA responses are transferred through channel buffers and encrypted
9229 	 * responses use the encryption transform, so only normal SMB transport
9230 	 * responses are candidates for compression.
9231 	 */
9232 	if (!is_rdma_channel && nbytes &&
9233 	    (req->Flags & SMB2_READFLAG_REQUEST_COMPRESSED) &&
9234 	    conn->compress_algorithm != SMB3_COMPRESS_NONE)
9235 		work->compress_response = true;
9236 	ksmbd_fd_put(work, fp);
9237 	return 0;
9238 
9239 out:
9240 	if (async_interim)
9241 		release_async_work(work);
9242 	if (err) {
9243 		if (err == -EISDIR)
9244 			rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
9245 		else if (err == -EAGAIN)
9246 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
9247 		else if (err == -ENOENT)
9248 			rsp->hdr.Status = STATUS_FILE_CLOSED;
9249 		else if (err == -EACCES)
9250 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
9251 		else if (err == -ESHARE)
9252 			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
9253 		else if (err == -EINVAL)
9254 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
9255 		else
9256 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
9257 
9258 		smb2_set_err_rsp(work);
9259 	}
9260 	ksmbd_fd_put(work, fp);
9261 	return err;
9262 }
9263 
9264 /**
9265  * smb2_write_pipe() - handler for smb2 write on IPC pipe
9266  * @work:	smb work containing write IPC pipe command buffer
9267  *
9268  * Return:	0 on success, otherwise error
9269  */
9270 static noinline int smb2_write_pipe(struct ksmbd_work *work)
9271 {
9272 	struct smb2_write_req *req;
9273 	struct smb2_write_rsp *rsp;
9274 	struct ksmbd_rpc_command *rpc_resp;
9275 	u64 id = 0;
9276 	int err = 0, ret = 0;
9277 	char *data_buf;
9278 	size_t length;
9279 
9280 	WORK_BUFFERS(work, req, rsp);
9281 
9282 	length = le32_to_cpu(req->Length);
9283 	id = req->VolatileFileId;
9284 
9285 	if ((u64)le16_to_cpu(req->DataOffset) + length >
9286 	    get_rfc1002_len(work->request_buf)) {
9287 		pr_err("invalid write data offset %u, smb_len %u\n",
9288 		       le16_to_cpu(req->DataOffset),
9289 		       get_rfc1002_len(work->request_buf));
9290 		err = -EINVAL;
9291 		goto out;
9292 	}
9293 
9294 	data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
9295 			   le16_to_cpu(req->DataOffset));
9296 
9297 	rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
9298 	if (rpc_resp) {
9299 		if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
9300 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
9301 			kvfree(rpc_resp);
9302 			smb2_set_err_rsp(work);
9303 			return -EOPNOTSUPP;
9304 		}
9305 		if (rpc_resp->flags != KSMBD_RPC_OK) {
9306 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
9307 			smb2_set_err_rsp(work);
9308 			kvfree(rpc_resp);
9309 			return ret;
9310 		}
9311 		kvfree(rpc_resp);
9312 	}
9313 
9314 	rsp->StructureSize = cpu_to_le16(17);
9315 	rsp->DataOffset = 0;
9316 	rsp->Reserved = 0;
9317 	rsp->DataLength = cpu_to_le32(length);
9318 	rsp->DataRemaining = 0;
9319 	rsp->Reserved2 = 0;
9320 	err = ksmbd_iov_pin_rsp(work, (void *)rsp,
9321 				offsetof(struct smb2_write_rsp, Buffer));
9322 out:
9323 	if (err) {
9324 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
9325 		smb2_set_err_rsp(work);
9326 	}
9327 
9328 	return err;
9329 }
9330 
9331 /**
9332  * smb2_write_rdma() - receive and store an RDMA WRITE payload
9333  * @work: request work item
9334  * @desc: client RDMA buffer descriptors
9335  * @desc_len: descriptor array length
9336  * @transform: parsed transform, or NULL for an untransformed transfer
9337  * @fp: target open file
9338  * @offset: target file offset
9339  * @length: transfer length
9340  * @sync: request synchronous storage completion
9341  *
9342  * Receive the payload, authenticate or decrypt it when required, and write it
9343  * to the target file.
9344  *
9345  * Return: written byte count on success, otherwise a negative errno
9346  */
9347 static ssize_t smb2_write_rdma(struct ksmbd_work *work,
9348 			       struct smbdirect_buffer_descriptor_v1 *desc,
9349 			       unsigned int desc_len,
9350 			       struct smb2_rdma_write_transform *transform,
9351 			       struct ksmbd_file *fp, loff_t offset,
9352 			       size_t length, bool sync)
9353 {
9354 	char *data_buf;
9355 	int ret;
9356 	ssize_t nbytes;
9357 
9358 	data_buf = kvzalloc(length, KSMBD_DEFAULT_GFP);
9359 	if (!data_buf)
9360 		return -ENOMEM;
9361 
9362 	ret = ksmbd_conn_rdma_read(work->conn, data_buf, length, desc,
9363 				   desc_len);
9364 	if (ret < 0) {
9365 		if (transform)
9366 			pr_err("RDMA WRITE encrypted transfer failed: session=%llu payload=%zu rdma_read_rc=%d\n",
9367 			       work->sess->id, length, ret);
9368 		kvfree(data_buf);
9369 		return ret;
9370 	}
9371 	if (transform &&
9372 	    transform->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION) {
9373 		ret = ksmbd_crypt_rdma(work->conn,
9374 				       work->sess->smb3decryptionkey,
9375 				       data_buf, length, transform->nonce,
9376 				       transform->nonce_len,
9377 				       transform->crypto->Signature,
9378 				       transform->signature_len, false);
9379 		if (ret) {
9380 			pr_err("RDMA WRITE decryption failed: session=%llu payload=%zu rc=%d\n",
9381 			       work->sess->id, length, ret);
9382 			kvfree(data_buf);
9383 			return ret == -ENOMEM ? ret : -EBADMSG;
9384 		}
9385 	}
9386 
9387 	ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
9388 	kvfree(data_buf);
9389 	if (ret < 0) {
9390 		if (transform)
9391 			pr_err("RDMA WRITE encrypted file write failed: session=%llu payload=%zu rc=%d\n",
9392 			       work->sess->id, length, ret);
9393 		return ret;
9394 	}
9395 	ksmbd_debug(RDMA,
9396 		    "RDMA WRITE transfer completed: session=%llu payload=%zu transformed=%u written=%zd\n",
9397 		    work->sess ? work->sess->id : 0, length, !!transform, nbytes);
9398 
9399 	return nbytes;
9400 }
9401 
9402 /**
9403  * smb2_write() - handler for smb2 write from file
9404  * @work:	smb work containing write command buffer
9405  *
9406  * Return:	0 on success, otherwise error
9407  */
9408 int smb2_write(struct ksmbd_work *work)
9409 {
9410 	struct smb2_write_req *req;
9411 	struct smb2_write_rsp *rsp;
9412 	struct smb2_rdma_write_transform rdma_transform = {};
9413 	struct smb2_rdma_write_transform *rdma_info = NULL;
9414 	struct smbdirect_buffer_descriptor_v1 *rdma_desc = NULL;
9415 	unsigned int rdma_desc_len = 0;
9416 	struct ksmbd_file *fp = NULL;
9417 	loff_t offset;
9418 	size_t length;
9419 	ssize_t nbytes;
9420 	char *data_buf;
9421 	bool writethrough = false, is_rdma_channel = false;
9422 	bool async_interim = false;
9423 	bool chseq_err = false;
9424 	int err = 0;
9425 	unsigned int max_write_size = work->conn->vals->max_write_size;
9426 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
9427 
9428 	ksmbd_debug(SMB, "Received smb2 write request\n");
9429 
9430 	WORK_BUFFERS(work, req, rsp);
9431 
9432 	if (smb2_compound_has_failed(work, &rsp->hdr))
9433 		return -EACCES;
9434 
9435 	if (work->next_smb2_rcv_hdr_off &&
9436 	    !has_file_id(req->VolatileFileId)) {
9437 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
9438 			    work->compound_fid);
9439 		id = work->compound_fid;
9440 		pid = work->compound_pfid;
9441 	}
9442 
9443 	if (!has_file_id(id)) {
9444 		id = req->VolatileFileId;
9445 		pid = req->PersistentFileId;
9446 	}
9447 
9448 	if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
9449 		ksmbd_debug(SMB, "IPC pipe write request\n");
9450 		return smb2_write_pipe(work);
9451 	}
9452 
9453 	offset = le64_to_cpu(req->Offset);
9454 	if (offset < 0) {
9455 		err = -EINVAL;
9456 		goto out;
9457 	}
9458 	length = le32_to_cpu(req->Length);
9459 
9460 	if (req->Channel != SMB2_CHANNEL_NONE &&
9461 	    req->Channel != SMB2_CHANNEL_RDMA_V1 &&
9462 	    req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE &&
9463 	    req->Channel != SMB2_CHANNEL_RDMA_TRANSFORM) {
9464 		err = -EINVAL;
9465 		goto out;
9466 	}
9467 	if (req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM &&
9468 	    work->conn->dialect != SMB311_PROT_ID) {
9469 		err = -EINVAL;
9470 		goto out;
9471 	}
9472 	if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
9473 	    req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
9474 	    req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM) {
9475 		is_rdma_channel = true;
9476 		max_write_size = get_smbd_max_read_write_size(work->conn->transport);
9477 		if (max_write_size == 0) {
9478 			err = -EINVAL;
9479 			goto out;
9480 		}
9481 		length = le32_to_cpu(req->RemainingBytes);
9482 	}
9483 
9484 	if (length) {
9485 		u64 end = (u64)offset + length;
9486 
9487 		if (end > SMB2_MAX_FILE_SIZE) {
9488 			err = -EINVAL;
9489 			goto out;
9490 		}
9491 		if (end == SMB2_MAX_FILE_SIZE) {
9492 			err = -EFBIG;
9493 			goto out;
9494 		}
9495 	}
9496 
9497 	if (is_rdma_channel == true) {
9498 		unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
9499 		unsigned int ch_len = le16_to_cpu(req->WriteChannelInfoLength);
9500 		unsigned int req_len = smb2_current_req_len(work, &req->hdr);
9501 
9502 		if (!length || req->Length != 0 || req->DataOffset != 0 ||
9503 		    ch_offset < offsetof(struct smb2_write_req, Buffer) ||
9504 		    ch_offset > req_len || ch_len > req_len - ch_offset) {
9505 			err = -EINVAL;
9506 			goto out;
9507 		}
9508 		if (req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM) {
9509 			err = smb2_parse_rdma_write_transform(work, req,
9510 							      &rdma_transform);
9511 			if (err) {
9512 				pr_err("RDMA WRITE encryption metadata rejected: session=%llu rc=%d\n",
9513 				       work->sess ? work->sess->id : 0, err);
9514 				goto out;
9515 			}
9516 			rdma_desc = rdma_transform.desc;
9517 			rdma_desc_len = rdma_transform.desc_len;
9518 			rdma_info = &rdma_transform;
9519 			err = smb2_set_rdma_key(work, rdma_desc,
9520 						rdma_transform.channel,
9521 						cpu_to_le16(rdma_desc_len));
9522 		} else {
9523 			rdma_desc = (struct smbdirect_buffer_descriptor_v1 *)
9524 				((char *)req + ch_offset);
9525 			rdma_desc_len = ch_len;
9526 			err = check_rdma_desc(rdma_desc, rdma_desc_len, length);
9527 			if (err)
9528 				goto out;
9529 			err = smb2_set_rdma_key(work, rdma_desc,
9530 						req->Channel,
9531 						req->WriteChannelInfoLength);
9532 		}
9533 		if (err)
9534 			goto out;
9535 	}
9536 
9537 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
9538 		ksmbd_debug(SMB, "User does not have write permission\n");
9539 		err = -EACCES;
9540 		goto out;
9541 	}
9542 
9543 	fp = ksmbd_lookup_fd_slow(work, id, pid);
9544 	if (!fp) {
9545 		err = -ENOENT;
9546 		goto out;
9547 	}
9548 
9549 	err = smb2_set_request_open(work, fp, &req->hdr, true, false);
9550 	if (err) {
9551 		rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
9552 		chseq_err = true;
9553 		goto out;
9554 	}
9555 
9556 	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
9557 		pr_err("Not permitted to write : 0x%x\n", fp->daccess);
9558 		err = -EACCES;
9559 		goto out;
9560 	}
9561 
9562 	if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
9563 		err = setup_async_work(work, NULL, NULL);
9564 		if (err)
9565 			goto out;
9566 		smb2_send_interim_resp(work, STATUS_PENDING);
9567 		async_interim = true;
9568 	}
9569 
9570 	if (length > max_write_size) {
9571 		ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
9572 			    max_write_size);
9573 		err = -EINVAL;
9574 		goto out;
9575 	}
9576 
9577 	ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
9578 	if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
9579 		writethrough = true;
9580 
9581 	if (is_rdma_channel == false) {
9582 		if (le16_to_cpu(req->DataOffset) <
9583 		    offsetof(struct smb2_write_req, Buffer)) {
9584 			err = -EINVAL;
9585 			goto out;
9586 		}
9587 
9588 		data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
9589 				    le16_to_cpu(req->DataOffset));
9590 
9591 		ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
9592 			    fp->filp, offset, length);
9593 		err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
9594 				      writethrough, &nbytes);
9595 		if (err < 0)
9596 			goto out;
9597 	} else {
9598 		/* read data from the client using rdma channel, and
9599 		 * write the data.
9600 		 */
9601 		nbytes = smb2_write_rdma(work, rdma_desc, rdma_desc_len,
9602 					 rdma_info, fp, offset, length,
9603 					 writethrough);
9604 		if (nbytes < 0) {
9605 			err = (int)nbytes;
9606 			goto out;
9607 		}
9608 	}
9609 
9610 	rsp->StructureSize = cpu_to_le16(17);
9611 	rsp->DataOffset = 0;
9612 	rsp->Reserved = 0;
9613 	rsp->DataLength = cpu_to_le32(nbytes);
9614 	rsp->DataRemaining = 0;
9615 	rsp->Reserved2 = 0;
9616 	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
9617 	if (err)
9618 		goto out;
9619 	if (async_interim)
9620 		release_async_work(work);
9621 	ksmbd_fd_put(work, fp);
9622 	return 0;
9623 
9624 out:
9625 	if (async_interim)
9626 		release_async_work(work);
9627 
9628 	if (err == -EAGAIN && !chseq_err)
9629 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
9630 	else if (err == -ENOSPC || err == -EFBIG)
9631 		rsp->hdr.Status = STATUS_DISK_FULL;
9632 	else if (err == -ENOENT)
9633 		rsp->hdr.Status = STATUS_FILE_CLOSED;
9634 	else if (err == -EACCES)
9635 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
9636 	else if (err == -ESHARE)
9637 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
9638 	else if (err == -EINVAL)
9639 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
9640 	else if (err == -EBADMSG)
9641 		rsp->hdr.Status = STATUS_AUTH_TAG_MISMATCH;
9642 	else if (err == -EKEYREJECTED)
9643 		rsp->hdr.Status = STATUS_INVALID_SIGNATURE;
9644 	else if (rsp->hdr.Status == 0)
9645 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
9646 
9647 	smb2_set_err_rsp(work);
9648 	ksmbd_fd_put(work, fp);
9649 	return err;
9650 }
9651 
9652 /**
9653  * smb2_flush() - handler for smb2 flush file - fsync
9654  * @work:	smb work containing flush command buffer
9655  *
9656  * Return:	0 on success, otherwise error
9657  */
9658 int smb2_flush(struct ksmbd_work *work)
9659 {
9660 	struct smb2_flush_req *req;
9661 	struct smb2_flush_rsp *rsp;
9662 	u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
9663 	int err;
9664 
9665 	WORK_BUFFERS(work, req, rsp);
9666 
9667 	ksmbd_debug(SMB, "Received smb2 flush request(fid : %llu)\n", req->VolatileFileId);
9668 
9669 	if (smb2_compound_has_failed(work, &rsp->hdr))
9670 		return -EACCES;
9671 
9672 	if (work->next_smb2_rcv_hdr_off &&
9673 	    !has_file_id(req->VolatileFileId)) {
9674 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
9675 			    work->compound_fid);
9676 		id = work->compound_fid;
9677 		pid = work->compound_pfid;
9678 	}
9679 
9680 	if (!has_file_id(id)) {
9681 		id = req->VolatileFileId;
9682 		pid = req->PersistentFileId;
9683 	}
9684 
9685 	err = ksmbd_vfs_fsync(work, id, pid);
9686 	if (err)
9687 		goto out;
9688 
9689 	rsp->StructureSize = cpu_to_le16(4);
9690 	rsp->Reserved = 0;
9691 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
9692 
9693 out:
9694 	rsp->hdr.Status = STATUS_INVALID_HANDLE;
9695 	smb2_set_err_rsp(work);
9696 	return err;
9697 }
9698 
9699 /**
9700  * smb2_cancel() - handler for smb2 cancel command
9701  * @work:	smb work containing cancel command buffer
9702  *
9703  * Return:	0 on success, otherwise error
9704  */
9705 int smb2_cancel(struct ksmbd_work *work)
9706 {
9707 	struct ksmbd_conn *conn = work->conn;
9708 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
9709 	struct smb2_hdr *chdr;
9710 	struct ksmbd_work *iter;
9711 	struct ksmbd_work *cancelled_notify = NULL;
9712 	struct list_head *command_list;
9713 
9714 	if (work->next_smb2_rcv_hdr_off)
9715 		hdr = ksmbd_resp_buf_next(work);
9716 
9717 	ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
9718 		    le64_to_cpu(hdr->MessageId),
9719 		    le32_to_cpu(hdr->Flags));
9720 
9721 	if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
9722 		command_list = &conn->async_requests;
9723 
9724 		spin_lock(&conn->request_lock);
9725 		list_for_each_entry(iter, command_list,
9726 				    async_request_entry) {
9727 			chdr = smb_get_msg(iter->request_buf);
9728 
9729 			if (iter->async_id !=
9730 			    le64_to_cpu(hdr->Id.AsyncId))
9731 				continue;
9732 
9733 			/*
9734 			 * Only an ACTIVE deferred work may have its cancel_fn
9735 			 * fired.  A CANCELLED or CLOSED work already took the
9736 			 * smb2_lock() non-ACTIVE early-exit that frees the
9737 			 * file_lock and skips release_async_work(), so it is
9738 			 * still on conn->async_requests with a live cancel_fn
9739 			 * pointing at the freed file_lock.
9740 			 */
9741 			if (cmpxchg(&iter->state, KSMBD_WORK_ACTIVE,
9742 				    KSMBD_WORK_CANCELLED) != KSMBD_WORK_ACTIVE)
9743 				break;
9744 
9745 			ksmbd_debug(SMB,
9746 				    "smb2 with AsyncId %llu cancelled command = 0x%x\n",
9747 				    le64_to_cpu(hdr->Id.AsyncId),
9748 				    le16_to_cpu(chdr->Command));
9749 			if (iter->cancel_fn == smb2_notify_cancel_fn)
9750 				cancelled_notify =
9751 					smb2_notify_cancel_claim(iter->cancel_argv);
9752 			else if (iter->cancel_fn)
9753 				iter->cancel_fn(iter->cancel_argv);
9754 			break;
9755 		}
9756 		spin_unlock(&conn->request_lock);
9757 
9758 		/*
9759 		 * Complete a cancelled notify before this CANCEL handler returns.
9760 		 * Deferring it to the system workqueue lets a following request and
9761 		 * its response overtake STATUS_CANCELLED, leaving clients waiting
9762 		 * for the original notify even though the cancellation was accepted.
9763 		 */
9764 		if (cancelled_notify)
9765 			smb2_complete_notify_cancel(cancelled_notify);
9766 	} else {
9767 		command_list = &conn->requests;
9768 
9769 		spin_lock(&conn->request_lock);
9770 		list_for_each_entry(iter, command_list, request_entry) {
9771 			chdr = smb_get_msg(iter->request_buf);
9772 
9773 			if (chdr->MessageId != hdr->MessageId ||
9774 			    iter == work)
9775 				continue;
9776 
9777 			if (cmpxchg(&iter->state, KSMBD_WORK_ACTIVE,
9778 				    KSMBD_WORK_CANCELLED) != KSMBD_WORK_ACTIVE)
9779 				break;
9780 
9781 			ksmbd_debug(SMB,
9782 				    "smb2 with mid %llu cancelled command = 0x%x\n",
9783 				    le64_to_cpu(hdr->MessageId),
9784 				    le16_to_cpu(chdr->Command));
9785 			if (iter->cancel_fn)
9786 				iter->cancel_fn(iter->cancel_argv);
9787 			break;
9788 		}
9789 		spin_unlock(&conn->request_lock);
9790 	}
9791 
9792 	/* For SMB2_CANCEL command itself send no response*/
9793 	work->send_no_response = 1;
9794 	return 0;
9795 }
9796 
9797 struct file_lock *smb_flock_init(struct file *f)
9798 {
9799 	struct file_lock *fl;
9800 
9801 	fl = locks_alloc_lock();
9802 	if (!fl)
9803 		goto out;
9804 
9805 	locks_init_lock(fl);
9806 
9807 	fl->c.flc_owner = f;
9808 	fl->c.flc_pid = current->tgid;
9809 	fl->c.flc_file = f;
9810 	fl->c.flc_flags = FL_POSIX;
9811 	fl->fl_ops = NULL;
9812 	fl->fl_lmops = NULL;
9813 
9814 out:
9815 	return fl;
9816 }
9817 
9818 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
9819 {
9820 	int cmd = -EINVAL;
9821 
9822 	/* Checking for wrong flag combination during lock request*/
9823 	switch (flags) {
9824 	case SMB2_LOCKFLAG_SHARED:
9825 		ksmbd_debug(SMB, "received shared request\n");
9826 		cmd = F_SETLKW;
9827 		flock->c.flc_type = F_RDLCK;
9828 		flock->c.flc_flags |= FL_SLEEP;
9829 		break;
9830 	case SMB2_LOCKFLAG_EXCLUSIVE:
9831 		ksmbd_debug(SMB, "received exclusive request\n");
9832 		cmd = F_SETLKW;
9833 		flock->c.flc_type = F_WRLCK;
9834 		flock->c.flc_flags |= FL_SLEEP;
9835 		break;
9836 	case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
9837 		ksmbd_debug(SMB,
9838 			    "received shared & fail immediately request\n");
9839 		cmd = F_SETLK;
9840 		flock->c.flc_type = F_RDLCK;
9841 		break;
9842 	case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
9843 		ksmbd_debug(SMB,
9844 			    "received exclusive & fail immediately request\n");
9845 		cmd = F_SETLK;
9846 		flock->c.flc_type = F_WRLCK;
9847 		break;
9848 	case SMB2_LOCKFLAG_UNLOCK:
9849 		ksmbd_debug(SMB, "received unlock request\n");
9850 		flock->c.flc_type = F_UNLCK;
9851 		cmd = F_SETLK;
9852 		break;
9853 	}
9854 
9855 	return cmd;
9856 }
9857 
9858 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
9859 					 unsigned int cmd, int flags, bool zero_len,
9860 					 struct list_head *lock_list)
9861 {
9862 	struct ksmbd_lock *lock;
9863 
9864 	lock = kzalloc_obj(struct ksmbd_lock, KSMBD_DEFAULT_GFP);
9865 	if (!lock)
9866 		return NULL;
9867 
9868 	lock->cmd = cmd;
9869 	lock->fl = flock;
9870 	lock->start = flock->fl_start;
9871 	lock->end = flock->fl_end;
9872 	lock->flags = flags;
9873 	lock->zero_len = zero_len;
9874 	INIT_LIST_HEAD(&lock->clist);
9875 	INIT_LIST_HEAD(&lock->flist);
9876 	INIT_LIST_HEAD(&lock->llist);
9877 	list_add_tail(&lock->llist, lock_list);
9878 
9879 	return lock;
9880 }
9881 
9882 static void smb2_remove_blocked_lock(void **argv)
9883 {
9884 	struct file_lock *flock = (struct file_lock *)argv[0];
9885 
9886 	ksmbd_vfs_posix_lock_unblock(flock);
9887 	locks_wake_up(flock);
9888 }
9889 
9890 static void smb2_free_lock(struct file_lock *flock)
9891 {
9892 	ksmbd_vfs_posix_lock_unblock(flock);
9893 	locks_free_lock(flock);
9894 }
9895 
9896 static void smb2_free_blocked_lock(struct file_lock *flock)
9897 {
9898 	ksmbd_vfs_posix_lock_unblock(flock);
9899 	locks_wake_up(flock);
9900 	locks_free_lock(flock);
9901 }
9902 
9903 static inline bool lock_defer_pending(struct file_lock *fl)
9904 {
9905 	/* check pending lock waiters */
9906 	return waitqueue_active(&fl->c.flc_wait);
9907 }
9908 
9909 /**
9910  * smb2_lock() - handler for smb2 file lock command
9911  * @work:	smb work containing lock command buffer
9912  *
9913  * Return:	0 on success, otherwise error
9914  */
9915 int smb2_lock(struct ksmbd_work *work)
9916 {
9917 	struct smb2_lock_req *req;
9918 	struct smb2_lock_rsp *rsp;
9919 	struct smb2_lock_element *lock_ele;
9920 	struct ksmbd_file *fp = NULL;
9921 	struct file_lock *flock = NULL;
9922 	struct file *filp = NULL;
9923 	int lock_count;
9924 	int flags = 0;
9925 	int cmd = 0;
9926 	int err = -EIO, i, rc = 0;
9927 	u64 lock_start, lock_length;
9928 	struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
9929 	struct ksmbd_conn *conn;
9930 	int nolock = 0;
9931 	LIST_HEAD(lock_list);
9932 	LIST_HEAD(rollback_list);
9933 	int prior_lock = 0, bkt;
9934 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
9935 	bool lock_replayed;
9936 
9937 	WORK_BUFFERS(work, req, rsp);
9938 
9939 	ksmbd_debug(SMB, "Received smb2 lock request\n");
9940 
9941 	if (smb2_compound_has_failed(work, &rsp->hdr))
9942 		return -EACCES;
9943 
9944 	if (work->next_smb2_rcv_hdr_off &&
9945 	    !has_file_id(req->VolatileFileId)) {
9946 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
9947 			    work->compound_fid);
9948 		id = work->compound_fid;
9949 		pid = work->compound_pfid;
9950 	}
9951 
9952 	if (!has_file_id(id)) {
9953 		id = req->VolatileFileId;
9954 		pid = req->PersistentFileId;
9955 	}
9956 
9957 	fp = ksmbd_lookup_fd_slow(work, id, pid);
9958 	if (!fp) {
9959 		ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
9960 		err = -ENOENT;
9961 		goto out2;
9962 	}
9963 
9964 	err = smb2_set_request_open(work, fp, &req->hdr, false, false);
9965 	if (err)
9966 		goto out2;
9967 
9968 	lock_replayed = smb2_verify_lock_sequence(work, fp, req);
9969 	if (lock_replayed)
9970 		goto lock_success;
9971 
9972 	filp = fp->filp;
9973 	lock_count = le16_to_cpu(req->LockCount);
9974 	lock_ele = req->locks;
9975 
9976 	ksmbd_debug(SMB, "lock count is %d\n", lock_count);
9977 	/*
9978 	 * Cap lock_count at 64. The MS-SMB2 spec defines Open.LockSequenceArray
9979 	 * as exactly 64 entries so 64 is the intended ceiling. No real workload
9980 	 * comes close to this in a single request.
9981 	 */
9982 	if (!lock_count || lock_count > 64) {
9983 		err = -EINVAL;
9984 		goto out2;
9985 	}
9986 
9987 	for (i = 0; i < lock_count; i++) {
9988 		flags = le32_to_cpu(lock_ele[i].Flags);
9989 
9990 		flock = smb_flock_init(filp);
9991 		if (!flock)
9992 			goto out;
9993 
9994 		cmd = smb2_set_flock_flags(flock, flags);
9995 
9996 		lock_start = le64_to_cpu(lock_ele[i].Offset);
9997 		lock_length = le64_to_cpu(lock_ele[i].Length);
9998 		if (lock_start > OFFSET_MAX ||
9999 		    (lock_length &&
10000 		     lock_length - 1 > OFFSET_MAX - lock_start)) {
10001 			pr_err("Invalid lock range requested\n");
10002 			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
10003 			locks_free_lock(flock);
10004 			goto out;
10005 		}
10006 
10007 		flock->fl_start = lock_start;
10008 		flock->fl_end = lock_length ?
10009 			flock->fl_start + lock_length - 1 : flock->fl_start;
10010 
10011 		/* Check conflict locks in one request */
10012 		list_for_each_entry(cmp_lock, &lock_list, llist) {
10013 			if (cmp_lock->fl->fl_start <= flock->fl_start &&
10014 			    cmp_lock->fl->fl_end >= flock->fl_end) {
10015 				if (cmp_lock->fl->c.flc_type != F_UNLCK &&
10016 				    flock->c.flc_type != F_UNLCK) {
10017 					pr_err("conflict two locks in one request\n");
10018 					err = -EINVAL;
10019 					locks_free_lock(flock);
10020 					goto out;
10021 				}
10022 			}
10023 		}
10024 
10025 		smb_lock = smb2_lock_init(flock, cmd, flags, !lock_length,
10026 					   &lock_list);
10027 		if (!smb_lock) {
10028 			err = -EINVAL;
10029 			locks_free_lock(flock);
10030 			goto out;
10031 		}
10032 	}
10033 
10034 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
10035 		if (lock_count > 1 &&
10036 		    !(le32_to_cpu(lock_ele[0].Flags) & SMB2_LOCKFLAG_UNLOCK) &&
10037 		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY)) {
10038 			err = -EINVAL;
10039 			goto out;
10040 		}
10041 
10042 		if (smb_lock->cmd < 0) {
10043 			err = -EINVAL;
10044 			goto out;
10045 		}
10046 
10047 		if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
10048 			err = -EINVAL;
10049 			goto out;
10050 		}
10051 
10052 		if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
10053 		     smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
10054 		    (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
10055 		     !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
10056 			err = -EINVAL;
10057 			goto out;
10058 		}
10059 
10060 		prior_lock = smb_lock->flags;
10061 
10062 		if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
10063 		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
10064 			goto no_check_cl;
10065 
10066 		nolock = 1;
10067 		/* check locks in connection list */
10068 		down_read(&conn_list_lock);
10069 		hash_for_each(conn_list, bkt, conn, hlist) {
10070 			spin_lock(&conn->llist_lock);
10071 			list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
10072 				if (file_inode(cmp_lock->fl->c.flc_file) !=
10073 				    file_inode(smb_lock->fl->c.flc_file))
10074 					continue;
10075 
10076 				if (lock_is_unlock(smb_lock->fl)) {
10077 					if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file &&
10078 					    cmp_lock->start == smb_lock->start &&
10079 					    cmp_lock->end == smb_lock->end &&
10080 					    !lock_defer_pending(cmp_lock->fl)) {
10081 						nolock = 0;
10082 						list_del_init(&cmp_lock->flist);
10083 						list_del_init(&cmp_lock->clist);
10084 						cmp_lock->conn = NULL;
10085 						spin_unlock(&conn->llist_lock);
10086 						up_read(&conn_list_lock);
10087 
10088 						ksmbd_conn_put(conn);
10089 						smb2_free_lock(cmp_lock->fl);
10090 						kfree(cmp_lock);
10091 						goto out_check_cl;
10092 					}
10093 					continue;
10094 				}
10095 
10096 				if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file) {
10097 					if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
10098 						continue;
10099 				} else {
10100 					if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
10101 						continue;
10102 				}
10103 
10104 				/* check zero byte lock range */
10105 				if (cmp_lock->zero_len && !smb_lock->zero_len &&
10106 				    cmp_lock->start > smb_lock->start &&
10107 				    cmp_lock->start <= smb_lock->end) {
10108 					spin_unlock(&conn->llist_lock);
10109 					up_read(&conn_list_lock);
10110 					pr_err("previous lock conflict with zero byte lock range\n");
10111 					goto out;
10112 				}
10113 
10114 				if (smb_lock->zero_len && !cmp_lock->zero_len &&
10115 				    smb_lock->start > cmp_lock->start &&
10116 				    smb_lock->start <= cmp_lock->end) {
10117 					spin_unlock(&conn->llist_lock);
10118 					up_read(&conn_list_lock);
10119 					pr_err("current lock conflict with zero byte lock range\n");
10120 					goto out;
10121 				}
10122 
10123 				if (cmp_lock->start <= smb_lock->end &&
10124 				    smb_lock->start <= cmp_lock->end &&
10125 				    !cmp_lock->zero_len && !smb_lock->zero_len) {
10126 					spin_unlock(&conn->llist_lock);
10127 					up_read(&conn_list_lock);
10128 					pr_err("Not allow lock operation on exclusive lock range\n");
10129 					goto out;
10130 				}
10131 			}
10132 			spin_unlock(&conn->llist_lock);
10133 		}
10134 		up_read(&conn_list_lock);
10135 out_check_cl:
10136 		if (lock_is_unlock(smb_lock->fl) && nolock) {
10137 			pr_err("Try to unlock nolocked range\n");
10138 			rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
10139 			goto out;
10140 		}
10141 
10142 no_check_cl:
10143 		flock = smb_lock->fl;
10144 		list_del(&smb_lock->llist);
10145 
10146 		if (smb_lock->zero_len) {
10147 			err = 0;
10148 			goto skip;
10149 		}
10150 retry:
10151 		rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
10152 skip:
10153 		if (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) {
10154 			locks_free_lock(flock);
10155 			kfree(smb_lock);
10156 			if (!rc) {
10157 				ksmbd_debug(SMB, "File unlocked\n");
10158 			} else if (rc == -ENOENT) {
10159 				rsp->hdr.Status = STATUS_NOT_LOCKED;
10160 				err = rc;
10161 				goto out;
10162 			}
10163 		} else {
10164 			if (rc == FILE_LOCK_DEFERRED) {
10165 				void **argv;
10166 
10167 				ksmbd_debug(SMB,
10168 					    "would have to wait for getting lock\n");
10169 
10170 				argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP);
10171 				if (!argv) {
10172 					err = -ENOMEM;
10173 					smb2_free_blocked_lock(flock);
10174 					kfree(smb_lock);
10175 					goto out;
10176 				}
10177 				argv[0] = flock;
10178 
10179 				rc = setup_async_work(work,
10180 						      smb2_remove_blocked_lock,
10181 						      argv);
10182 				if (rc) {
10183 					kfree(argv);
10184 					err = -ENOMEM;
10185 					smb2_free_blocked_lock(flock);
10186 					kfree(smb_lock);
10187 					goto out;
10188 				}
10189 				list_add(&smb_lock->llist, &rollback_list);
10190 				spin_lock(&fp->f_lock);
10191 				list_add(&work->fp_entry, &fp->blocked_works);
10192 				spin_unlock(&fp->f_lock);
10193 
10194 				smb2_send_interim_resp(work, STATUS_PENDING);
10195 
10196 				ksmbd_vfs_posix_lock_wait(flock);
10197 
10198 				spin_lock(&fp->f_lock);
10199 				list_del(&work->fp_entry);
10200 				spin_unlock(&fp->f_lock);
10201 
10202 				list_del(&smb_lock->llist);
10203 
10204 				if (work->state == KSMBD_WORK_CANCELLED) {
10205 					rsp->hdr.Status = STATUS_CANCELLED;
10206 					kfree(smb_lock);
10207 					smb2_send_interim_resp(work,
10208 							STATUS_CANCELLED);
10209 					release_async_work(work);
10210 					locks_free_lock(flock);
10211 					work->send_no_response = 1;
10212 					goto out;
10213 				}
10214 
10215 				release_async_work(work);
10216 
10217 				if (work->state == KSMBD_WORK_ACTIVE)
10218 					goto retry;
10219 
10220 				locks_free_lock(flock);
10221 
10222 				rsp->hdr.Status =
10223 					STATUS_RANGE_NOT_LOCKED;
10224 				kfree(smb_lock);
10225 				/* rollback_list may still hold earlier grants */
10226 				goto out;
10227 			} else if (!rc) {
10228 				list_add(&smb_lock->llist, &rollback_list);
10229 				ksmbd_debug(SMB, "successful in taking lock\n");
10230 			} else {
10231 				locks_free_lock(flock);
10232 				kfree(smb_lock);
10233 				err = rc;
10234 				goto out;
10235 			}
10236 		}
10237 	}
10238 
10239 	if (atomic_read(&fp->f_ci->op_count) > 1)
10240 		smb_break_all_oplock(work, fp);
10241 
10242 lock_success:
10243 	rsp->StructureSize = cpu_to_le16(4);
10244 	ksmbd_debug(SMB, "successful in taking lock\n");
10245 	rsp->hdr.Status = STATUS_SUCCESS;
10246 	rsp->Reserved = 0;
10247 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
10248 	if (err)
10249 		goto out;
10250 
10251 	/* publish only once the whole batch has committed */
10252 	if (!list_empty(&rollback_list)) {
10253 		spin_lock(&work->conn->llist_lock);
10254 		list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
10255 			list_del_init(&smb_lock->llist);
10256 			smb_lock->conn = ksmbd_conn_get(work->conn);
10257 			list_add_tail(&smb_lock->clist,
10258 				      &work->conn->lock_list);
10259 			list_add_tail(&smb_lock->flist,
10260 				      &fp->lock_list);
10261 		}
10262 		spin_unlock(&work->conn->llist_lock);
10263 	}
10264 
10265 	if (!lock_replayed)
10266 		smb2_update_lock_sequence(work, fp, req);
10267 
10268 	ksmbd_fd_put(work, fp);
10269 	return 0;
10270 
10271 out:
10272 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
10273 		locks_free_lock(smb_lock->fl);
10274 		list_del(&smb_lock->llist);
10275 		kfree(smb_lock);
10276 	}
10277 
10278 	list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
10279 		struct file_lock *rlock = NULL;
10280 
10281 		rlock = smb_flock_init(filp);
10282 		if (rlock) {
10283 			rlock->c.flc_type = F_UNLCK;
10284 			rlock->fl_start = smb_lock->start;
10285 			rlock->fl_end = smb_lock->end;
10286 
10287 			rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
10288 			if (rc)
10289 				pr_err("rollback unlock fail : %d\n", rc);
10290 		} else {
10291 			pr_err("rollback unlock alloc failed\n");
10292 		}
10293 
10294 		list_del(&smb_lock->llist);
10295 		smb2_free_lock(smb_lock->fl);
10296 		if (rlock)
10297 			locks_free_lock(rlock);
10298 		kfree(smb_lock);
10299 	}
10300 out2:
10301 	ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
10302 
10303 	if (!rsp->hdr.Status) {
10304 		if (err == -EINVAL)
10305 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10306 		else if (err == -ENOMEM)
10307 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
10308 		else if (err == -ENOENT)
10309 			rsp->hdr.Status = STATUS_FILE_CLOSED;
10310 		else
10311 			rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
10312 	}
10313 
10314 	smb2_set_err_rsp(work);
10315 	ksmbd_fd_put(work, fp);
10316 	return err;
10317 }
10318 
10319 static int fsctl_copychunk(struct ksmbd_work *work,
10320 			   struct copychunk_ioctl_req *ci_req,
10321 			   unsigned int cnt_code,
10322 			   unsigned int input_count,
10323 			   unsigned long long volatile_id,
10324 			   unsigned long long persistent_id,
10325 			   struct smb2_ioctl_rsp *rsp)
10326 {
10327 	struct copychunk_ioctl_rsp *ci_rsp;
10328 	struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
10329 	struct srv_copychunk *chunks;
10330 	unsigned int i, chunk_count, chunk_count_written = 0;
10331 	unsigned int chunk_size_written = 0;
10332 	loff_t total_size_written = 0;
10333 	int ret = 0;
10334 
10335 	ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
10336 
10337 	rsp->VolatileFileId = volatile_id;
10338 	rsp->PersistentFileId = persistent_id;
10339 	ci_rsp->ChunksWritten =
10340 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
10341 	ci_rsp->ChunkBytesWritten =
10342 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
10343 	ci_rsp->TotalBytesWritten =
10344 		cpu_to_le32(ksmbd_server_side_copy_max_total_size());
10345 
10346 	chunk_count = le32_to_cpu(ci_req->ChunkCount);
10347 	/*
10348 	 * ChunkCount=0 is the standard SMB2 "query my copy limits" request
10349 	 * (no data copied) -- but macOS Finder's Cmd+D duplicate sends
10350 	 * FSCTL_SRV_COPYCHUNK with ChunkCount=0 meaning "copy the whole
10351 	 * file", relying on the AAPL-negotiated server to do a full copy
10352 	 * instead. Keep the standard no-op behavior for everyone else.
10353 	 *
10354 	 * Gate on the TIME_MACHINE share flag, not just conn->is_aapl:
10355 	 * that flag alone has ambiguous provenance -- the pre-existing
10356 	 * narrow UniqueId=0 path can also set it on ordinary,
10357 	 * non-Time-Machine shares, and this series' stated design keeps
10358 	 * every AAPL-driven behavior opt-in per share.
10359 	 */
10360 	if (chunk_count == 0 &&
10361 	    !(work->conn->is_aapl &&
10362 	      test_share_config_flag(work->tcon->share_conf,
10363 				     KSMBD_SHARE_FLAG_TIME_MACHINE)))
10364 		goto out;
10365 	total_size_written = 0;
10366 	i = 0;
10367 
10368 	if (chunk_count) {
10369 		/* verify the SRV_COPYCHUNK_COPY packet */
10370 		if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
10371 		    input_count < struct_size(ci_req, Chunks, chunk_count)) {
10372 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10373 			return -EINVAL;
10374 		}
10375 
10376 		chunks = &ci_req->Chunks[0];
10377 		for (i = 0; i < chunk_count; i++) {
10378 			if (le32_to_cpu(chunks[i].Length) == 0 ||
10379 			    le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
10380 				break;
10381 			total_size_written += le32_to_cpu(chunks[i].Length);
10382 		}
10383 	} else {
10384 		chunks = &ci_req->Chunks[0];
10385 	}
10386 
10387 	if (i < chunk_count ||
10388 	    total_size_written > ksmbd_server_side_copy_max_total_size()) {
10389 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10390 		return -EINVAL;
10391 	}
10392 
10393 	src_fp = ksmbd_lookup_foreign_fd(work,
10394 					 le64_to_cpu(ci_req->SourceKeyU64[0]));
10395 	dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
10396 	ret = -EINVAL;
10397 	if (!src_fp ||
10398 	    src_fp->persistent_id != le64_to_cpu(ci_req->SourceKeyU64[1])) {
10399 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
10400 		goto out;
10401 	}
10402 
10403 	if (!dst_fp) {
10404 		rsp->hdr.Status = STATUS_FILE_CLOSED;
10405 		goto out;
10406 	}
10407 
10408 	/*
10409 	 * FILE_READ_DATA should only be included in
10410 	 * the FSCTL_SRV_COPYCHUNK case
10411 	 */
10412 	if (cnt_code == FSCTL_SRV_COPYCHUNK &&
10413 	    !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
10414 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
10415 		goto out;
10416 	}
10417 
10418 	ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
10419 					 chunks, chunk_count,
10420 					 &chunk_count_written,
10421 					 &chunk_size_written,
10422 					 &total_size_written);
10423 	if (ret < 0) {
10424 		if (ret == -EACCES)
10425 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
10426 		else if (ret == -EAGAIN)
10427 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
10428 		else if (ret == -EBADF)
10429 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
10430 		else if (ret == -EFBIG || ret == -ENOSPC)
10431 			rsp->hdr.Status = STATUS_DISK_FULL;
10432 		else if (ret == -EINVAL)
10433 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10434 		else if (ret == -EISDIR)
10435 			rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
10436 		else if (ret == -E2BIG)
10437 			rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
10438 		else
10439 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
10440 	}
10441 
10442 	ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
10443 	ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
10444 	ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
10445 out:
10446 	ksmbd_fd_put(work, src_fp);
10447 	ksmbd_fd_put(work, dst_fp);
10448 	return ret;
10449 }
10450 
10451 static __be32 idev_ipv4_address(struct in_device *idev)
10452 {
10453 	__be32 addr = 0;
10454 
10455 	struct in_ifaddr *ifa;
10456 
10457 	rcu_read_lock();
10458 	in_dev_for_each_ifa_rcu(ifa, idev) {
10459 		if (ifa->ifa_flags & IFA_F_SECONDARY)
10460 			continue;
10461 
10462 		addr = ifa->ifa_address;
10463 		break;
10464 	}
10465 	rcu_read_unlock();
10466 	return addr;
10467 }
10468 
10469 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
10470 					struct smb2_ioctl_rsp *rsp,
10471 					unsigned int out_buf_len)
10472 {
10473 	struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
10474 	int nbytes = 0;
10475 	struct net_device *netdev;
10476 	struct sockaddr_storage_rsp *sockaddr_storage;
10477 	unsigned int flags;
10478 	unsigned long long speed;
10479 
10480 	rtnl_lock();
10481 	for_each_netdev(&init_net, netdev) {
10482 		bool ipv4_set = false;
10483 
10484 		if (netdev->type == ARPHRD_LOOPBACK)
10485 			continue;
10486 
10487 		if (!ksmbd_find_netdev_name_iface_list(netdev->name))
10488 			continue;
10489 
10490 		flags = netif_get_flags(netdev);
10491 		if (!(flags & IFF_RUNNING))
10492 			continue;
10493 ipv6_retry:
10494 		if (out_buf_len <
10495 		    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
10496 			rtnl_unlock();
10497 			return -ENOSPC;
10498 		}
10499 
10500 		nii_rsp = (struct network_interface_info_ioctl_rsp *)
10501 				&rsp->Buffer[nbytes];
10502 		nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
10503 
10504 		nii_rsp->Capability = 0;
10505 		if (netdev->real_num_tx_queues > 1)
10506 			nii_rsp->Capability |= RSS_CAPABLE;
10507 		if (ksmbd_rdma_capable_netdev(netdev))
10508 			nii_rsp->Capability |= RDMA_CAPABLE;
10509 
10510 		nii_rsp->Next = cpu_to_le32(152);
10511 		nii_rsp->Reserved = 0;
10512 
10513 		if (netdev->ethtool_ops->get_link_ksettings) {
10514 			struct ethtool_link_ksettings cmd;
10515 
10516 			netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
10517 			speed = cmd.base.speed;
10518 		} else {
10519 			ksmbd_debug(SMB, "%s %s\n", netdev->name,
10520 				    "speed is unknown, defaulting to 1Gb/sec");
10521 			speed = SPEED_1000;
10522 		}
10523 
10524 		speed *= 1000000;
10525 		nii_rsp->LinkSpeed = cpu_to_le64(speed);
10526 
10527 		sockaddr_storage = (struct sockaddr_storage_rsp *)
10528 					nii_rsp->SockAddr_Storage;
10529 		memset(sockaddr_storage, 0, 128);
10530 
10531 		if (!ipv4_set) {
10532 			struct in_device *idev;
10533 
10534 			sockaddr_storage->Family = INTERNETWORK;
10535 			sockaddr_storage->addr4.Port = 0;
10536 
10537 			idev = __in_dev_get_rtnl(netdev);
10538 			if (!idev)
10539 				continue;
10540 			sockaddr_storage->addr4.IPv4Address =
10541 						idev_ipv4_address(idev);
10542 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
10543 			ipv4_set = true;
10544 			goto ipv6_retry;
10545 		} else {
10546 			struct inet6_dev *idev6;
10547 			struct inet6_ifaddr *ifa;
10548 			__u8 *ipv6_addr = sockaddr_storage->addr6.IPv6Address;
10549 
10550 			sockaddr_storage->Family = INTERNETWORKV6;
10551 			sockaddr_storage->addr6.Port = 0;
10552 			sockaddr_storage->addr6.FlowInfo = 0;
10553 
10554 			idev6 = __in6_dev_get(netdev);
10555 			if (!idev6)
10556 				continue;
10557 
10558 			list_for_each_entry(ifa, &idev6->addr_list, if_list) {
10559 				if (ifa->flags & (IFA_F_TENTATIVE |
10560 							IFA_F_DEPRECATED))
10561 					continue;
10562 				memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
10563 				break;
10564 			}
10565 			sockaddr_storage->addr6.ScopeId = 0;
10566 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
10567 		}
10568 	}
10569 	rtnl_unlock();
10570 
10571 	/* zero if this is last one */
10572 	if (nii_rsp)
10573 		nii_rsp->Next = 0;
10574 
10575 	rsp->PersistentFileId = SMB2_NO_FID;
10576 	rsp->VolatileFileId = SMB2_NO_FID;
10577 	return nbytes;
10578 }
10579 
10580 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
10581 					 struct validate_negotiate_info_req *neg_req,
10582 					 struct validate_negotiate_info_rsp *neg_rsp,
10583 					 unsigned int in_buf_len)
10584 {
10585 	int ret = 0;
10586 	int dialect;
10587 
10588 	if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
10589 			le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
10590 		return -EINVAL;
10591 
10592 	dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
10593 					     neg_req->DialectCount);
10594 	if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
10595 		ret = -EINVAL;
10596 		goto err_out;
10597 	}
10598 
10599 	if (memcmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
10600 		ret = -EINVAL;
10601 		goto err_out;
10602 	}
10603 
10604 	if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
10605 		ret = -EINVAL;
10606 		goto err_out;
10607 	}
10608 
10609 	if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
10610 		ret = -EINVAL;
10611 		goto err_out;
10612 	}
10613 
10614 	neg_rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
10615 	memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
10616 	neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
10617 	neg_rsp->Dialect = cpu_to_le16(conn->dialect);
10618 err_out:
10619 	return ret;
10620 }
10621 
10622 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
10623 					struct file_allocated_range_buffer *qar_req,
10624 					struct file_allocated_range_buffer *qar_rsp,
10625 					unsigned int in_count, unsigned int *out_count)
10626 {
10627 	struct ksmbd_file *fp;
10628 	loff_t start, length;
10629 	int ret = 0;
10630 
10631 	*out_count = 0;
10632 
10633 	start = le64_to_cpu(qar_req->file_offset);
10634 	length = le64_to_cpu(qar_req->length);
10635 
10636 	if (start < 0 || length < 0)
10637 		return -EINVAL;
10638 
10639 	fp = ksmbd_lookup_fd_fast(work, id);
10640 	if (!fp)
10641 		return -ENOENT;
10642 
10643 	if (!(fp->daccess & FILE_READ_DATA_LE)) {
10644 		ret = -EACCES;
10645 		goto out;
10646 	}
10647 
10648 	if (!in_count) {
10649 		struct file_allocated_range_buffer range;
10650 
10651 		ret = ksmbd_vfs_query_allocated_ranges(fp, start, length,
10652 						       &range, 1, out_count);
10653 		if ((!ret || ret == -E2BIG) && *out_count)
10654 			ret = -ENOSPC;
10655 		*out_count = 0;
10656 	} else {
10657 		ret = ksmbd_vfs_query_allocated_ranges(fp, start, length,
10658 						       qar_rsp, in_count,
10659 						       out_count);
10660 	}
10661 	if (ret && ret != -E2BIG)
10662 		*out_count = 0;
10663 
10664 out:
10665 	ksmbd_fd_put(work, fp);
10666 	return ret;
10667 }
10668 
10669 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
10670 				 unsigned int out_buf_len,
10671 				 struct smb2_ioctl_req *req,
10672 				 struct smb2_ioctl_rsp *rsp)
10673 {
10674 	struct ksmbd_rpc_command *rpc_resp;
10675 	char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
10676 	int nbytes = 0;
10677 
10678 	rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
10679 				   le32_to_cpu(req->InputCount));
10680 	if (rpc_resp) {
10681 		if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
10682 			/*
10683 			 * set STATUS_SOME_NOT_MAPPED response
10684 			 * for unknown domain sid.
10685 			 */
10686 			rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
10687 		} else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
10688 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
10689 			goto out;
10690 		} else if (rpc_resp->flags != KSMBD_RPC_OK) {
10691 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10692 			goto out;
10693 		}
10694 
10695 		nbytes = rpc_resp->payload_sz;
10696 		if (rpc_resp->payload_sz > out_buf_len) {
10697 			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
10698 			nbytes = out_buf_len;
10699 		}
10700 
10701 		if (!rpc_resp->payload_sz) {
10702 			rsp->hdr.Status =
10703 				STATUS_UNEXPECTED_IO_ERROR;
10704 			goto out;
10705 		}
10706 
10707 		memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
10708 	}
10709 out:
10710 	kvfree(rpc_resp);
10711 	return nbytes;
10712 }
10713 
10714 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
10715 				   struct file_sparse *sparse)
10716 {
10717 	struct ksmbd_file *fp;
10718 	struct mnt_idmap *idmap;
10719 	int ret = 0;
10720 	__le32 old_fattr;
10721 
10722 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
10723 		ksmbd_debug(SMB, "User does not have write permission\n");
10724 		return -EACCES;
10725 	}
10726 
10727 	fp = ksmbd_lookup_fd_fast(work, id);
10728 	if (!fp)
10729 		return -ENOENT;
10730 
10731 	if (S_ISDIR(file_inode(fp->filp)->i_mode)) {
10732 		ret = -EINVAL;
10733 		goto out;
10734 	}
10735 
10736 	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE |
10737 			     FILE_WRITE_ATTRIBUTES_LE))) {
10738 		ret = -EACCES;
10739 		goto out;
10740 	}
10741 
10742 	idmap = file_mnt_idmap(fp->filp);
10743 
10744 	old_fattr = fp->f_ci->m_fattr;
10745 	if (!sparse->SetSparse &&
10746 	    (old_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)) {
10747 		ret = ksmbd_vfs_zero_holes(fp);
10748 		if (ret)
10749 			goto out;
10750 	}
10751 
10752 	if (sparse->SetSparse)
10753 		fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
10754 	else
10755 		fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
10756 
10757 	if (fp->f_ci->m_fattr != old_fattr) {
10758 		const struct cred *saved_cred;
10759 		struct xattr_dos_attrib da = {0};
10760 
10761 		ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
10762 						     fp->filp->f_path.dentry, &da);
10763 		if (ret <= 0) {
10764 			da.version = 4;
10765 			da.itime = fp->itime;
10766 			da.create_time = fp->create_time;
10767 			da.flags = XATTR_DOSINFO_CREATE_TIME |
10768 				XATTR_DOSINFO_ITIME;
10769 		}
10770 
10771 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
10772 		da.flags |= XATTR_DOSINFO_ATTRIB;
10773 		saved_cred = override_creds(fp->filp->f_cred);
10774 		ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
10775 						     &fp->filp->f_path,
10776 						     &da, true);
10777 		revert_creds(saved_cred);
10778 		if (ret)
10779 			fp->f_ci->m_fattr = old_fattr;
10780 	}
10781 
10782 out:
10783 	ksmbd_fd_put(work, fp);
10784 	return ret;
10785 }
10786 
10787 static int fsctl_request_resume_key(struct ksmbd_work *work,
10788 				    struct smb2_ioctl_req *req,
10789 				    struct resume_key_ioctl_rsp *key_rsp)
10790 {
10791 	struct ksmbd_file *fp;
10792 
10793 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
10794 	if (!fp)
10795 		return -ENOENT;
10796 
10797 	memset(key_rsp, 0, sizeof(*key_rsp));
10798 	key_rsp->ResumeKeyU64[0] = req->VolatileFileId;
10799 	key_rsp->ResumeKeyU64[1] = req->PersistentFileId;
10800 	ksmbd_fd_put(work, fp);
10801 
10802 	return 0;
10803 }
10804 
10805 /**
10806  * smb2_ioctl() - handler for smb2 ioctl command
10807  * @work:	smb work containing ioctl command buffer
10808  *
10809  * Return:	0 on success, otherwise error
10810  */
10811 int smb2_ioctl(struct ksmbd_work *work)
10812 {
10813 	struct smb2_ioctl_req *req;
10814 	struct smb2_ioctl_rsp *rsp;
10815 	unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
10816 	u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
10817 	struct ksmbd_conn *conn = work->conn;
10818 	int ret = 0;
10819 	char *buffer;
10820 	bool no_fileid_ioctl = false;
10821 	bool chseq_err = false;
10822 
10823 	ksmbd_debug(SMB, "Received smb2 ioctl request\n");
10824 
10825 	if (work->next_smb2_rcv_hdr_off) {
10826 		req = ksmbd_req_buf_next(work);
10827 		rsp = ksmbd_resp_buf_next(work);
10828 		if (smb2_compound_has_failed(work, &rsp->hdr))
10829 			return -EACCES;
10830 		if (!has_file_id(req->VolatileFileId)) {
10831 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
10832 				    work->compound_fid);
10833 			id = work->compound_fid;
10834 			pid = work->compound_pfid;
10835 		}
10836 	} else {
10837 		req = smb_get_msg(work->request_buf);
10838 		rsp = smb_get_msg(work->response_buf);
10839 	}
10840 
10841 	if (!has_file_id(id)) {
10842 		id = req->VolatileFileId;
10843 		pid = req->PersistentFileId;
10844 	}
10845 
10846 	if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
10847 		ret = -EOPNOTSUPP;
10848 		goto out;
10849 	}
10850 
10851 	buffer = (char *)req + le32_to_cpu(req->InputOffset);
10852 
10853 	cnt_code = le32_to_cpu(req->CtlCode);
10854 	switch (cnt_code) {
10855 	case FSCTL_DFS_GET_REFERRALS:
10856 	case FSCTL_DFS_GET_REFERRALS_EX:
10857 	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
10858 	case FSCTL_VALIDATE_NEGOTIATE_INFO:
10859 	case FSCTL_PIPE_WAIT:
10860 	case FSCTL_PIPE_TRANSCEIVE:
10861 		no_fileid_ioctl = true;
10862 		break;
10863 	default:
10864 		break;
10865 	}
10866 
10867 	if (!no_fileid_ioctl && has_file_id(id)) {
10868 		struct ksmbd_file *fp;
10869 
10870 		fp = ksmbd_lookup_fd_slow(work, id, pid);
10871 		if (!fp) {
10872 			if (cnt_code == FSCTL_DUPLICATE_EXTENTS_TO_FILE) {
10873 				rsp->hdr.Status = STATUS_FILE_CLOSED;
10874 				goto out2;
10875 			}
10876 			ret = -ENOENT;
10877 			goto out;
10878 		}
10879 
10880 		ret = smb2_set_request_open(work, fp, &req->hdr, true, false);
10881 		ksmbd_fd_put(work, fp);
10882 		if (ret) {
10883 			rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
10884 			chseq_err = true;
10885 			goto out;
10886 		}
10887 	}
10888 
10889 	ret = smb2_calc_max_out_buf_len(work,
10890 			offsetof(struct smb2_ioctl_rsp, Buffer),
10891 			le32_to_cpu(req->MaxOutputResponse));
10892 	if (ret < 0) {
10893 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10894 		goto out;
10895 	}
10896 	out_buf_len = (unsigned int)ret;
10897 	in_buf_len = le32_to_cpu(req->InputCount);
10898 
10899 	switch (cnt_code) {
10900 	case FSCTL_SRV_ENUM_SNAPS: {
10901 		struct srv_snapshot_array *snap_rsp;
10902 		struct ksmbd_file *fp;
10903 
10904 		if (out_buf_len < sizeof(*snap_rsp)) {
10905 			ret = -EINVAL;
10906 			goto out;
10907 		}
10908 
10909 		fp = ksmbd_lookup_fd_fast(work, id);
10910 		if (!fp) {
10911 			ret = -ENOENT;
10912 			goto out;
10913 		}
10914 		ksmbd_fd_put(work, fp);
10915 
10916 		snap_rsp = (struct srv_snapshot_array *)rsp->Buffer;
10917 		snap_rsp->NumberOfSnapShots = 0;
10918 		snap_rsp->NumberOfSnapShotsReturned = 0;
10919 		snap_rsp->SnapShotArraySize = cpu_to_le32(2);
10920 		snap_rsp->Reserved = 0;
10921 		nbytes = sizeof(*snap_rsp);
10922 		break;
10923 	}
10924 	case FSCTL_DFS_GET_REFERRALS:
10925 	case FSCTL_DFS_GET_REFERRALS_EX:
10926 		/* Not support DFS yet */
10927 		ret = -EOPNOTSUPP;
10928 		rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
10929 		goto out2;
10930 	case FSCTL_GET_COMPRESSION: {
10931 		struct compress_ioctl *cmpr_rsp;
10932 		struct ksmbd_file *fp;
10933 		u16 fmt;
10934 
10935 		if (out_buf_len < sizeof(struct compress_ioctl)) {
10936 			ret = -EINVAL;
10937 			goto out;
10938 		}
10939 
10940 		fp = ksmbd_lookup_fd_fast(work, id);
10941 		if (!fp) {
10942 			ret = -ENOENT;
10943 			goto out;
10944 		}
10945 
10946 		ret = ksmbd_vfs_get_compression(fp, &fmt);
10947 		ksmbd_fd_put(work, fp);
10948 		if (ret < 0)
10949 			goto out;
10950 
10951 		cmpr_rsp = (struct compress_ioctl *)&rsp->Buffer[0];
10952 		cmpr_rsp->CompressionState = cpu_to_le16(fmt);
10953 		nbytes = sizeof(struct compress_ioctl);
10954 		rsp->PersistentFileId = req->PersistentFileId;
10955 		rsp->VolatileFileId = req->VolatileFileId;
10956 		break;
10957 	}
10958 	case FSCTL_SET_COMPRESSION: {
10959 		struct compress_ioctl *cmpr_req;
10960 		struct ksmbd_file *fp;
10961 
10962 		if (in_buf_len < sizeof(struct compress_ioctl)) {
10963 			ret = -EINVAL;
10964 			goto out;
10965 		}
10966 
10967 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
10968 			ksmbd_debug(SMB, "User does not have write permission\n");
10969 			ret = -EACCES;
10970 			goto out;
10971 		}
10972 
10973 		cmpr_req = (struct compress_ioctl *)buffer;
10974 		fp = ksmbd_lookup_fd_fast(work, id);
10975 		if (!fp) {
10976 			ret = -ENOENT;
10977 			goto out;
10978 		}
10979 
10980 		ret = ksmbd_vfs_set_compression(work, fp, le16_to_cpu(cmpr_req->CompressionState));
10981 		ksmbd_fd_put(work, fp);
10982 		if (ret)
10983 			goto out;
10984 		break;
10985 	}
10986 	case FSCTL_CREATE_OR_GET_OBJECT_ID:
10987 	{
10988 		struct file_object_buf_type1_ioctl_rsp *obj_buf;
10989 		struct ksmbd_file *fp;
10990 
10991 		fp = ksmbd_lookup_fd_fast(work, id);
10992 		if (!fp) {
10993 			ret = -EBADF;
10994 			rsp->hdr.Status = STATUS_FILE_CLOSED;
10995 			goto out2;
10996 		}
10997 
10998 		if (out_buf_len < sizeof(struct file_object_buf_type1_ioctl_rsp)) {
10999 			ksmbd_fd_put(work, fp);
11000 			ret = -EINVAL;
11001 			goto out;
11002 		}
11003 		ksmbd_fd_put(work, fp);
11004 
11005 		nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
11006 		obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
11007 			&rsp->Buffer[0];
11008 
11009 		/*
11010 		 * TODO: This is dummy implementation to pass smbtorture
11011 		 * Need to check correct response later
11012 		 */
11013 		memset(obj_buf->ObjectId, 0x0, 16);
11014 		memset(obj_buf->BirthVolumeId, 0x0, 16);
11015 		memset(obj_buf->BirthObjectId, 0x0, 16);
11016 		memset(obj_buf->DomainId, 0x0, 16);
11017 
11018 		break;
11019 	}
11020 	case FSCTL_PIPE_TRANSCEIVE:
11021 		out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
11022 		nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
11023 		break;
11024 	case FSCTL_VALIDATE_NEGOTIATE_INFO:
11025 		if (conn->dialect < SMB30_PROT_ID) {
11026 			ret = -EOPNOTSUPP;
11027 			goto out;
11028 		}
11029 
11030 		if (in_buf_len < offsetof(struct validate_negotiate_info_req,
11031 					  Dialects)) {
11032 			ret = -EINVAL;
11033 			goto out;
11034 		}
11035 
11036 		if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
11037 			ret = -EINVAL;
11038 			goto out;
11039 		}
11040 
11041 		ret = fsctl_validate_negotiate_info(conn,
11042 			(struct validate_negotiate_info_req *)buffer,
11043 			(struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
11044 			in_buf_len);
11045 		if (ret < 0)
11046 			goto out;
11047 
11048 		nbytes = sizeof(struct validate_negotiate_info_rsp);
11049 		rsp->PersistentFileId = SMB2_NO_FID;
11050 		rsp->VolatileFileId = SMB2_NO_FID;
11051 		break;
11052 	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
11053 		if (req->PersistentFileId != SMB2_NO_FID ||
11054 		    req->VolatileFileId != SMB2_NO_FID) {
11055 			ret = -EINVAL;
11056 			goto out;
11057 		}
11058 
11059 		ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
11060 		if (ret < 0)
11061 			goto out;
11062 		nbytes = ret;
11063 		break;
11064 	case FSCTL_SRV_REQUEST_RESUME_KEY:
11065 		if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
11066 			ret = -EINVAL;
11067 			goto out;
11068 		}
11069 
11070 		ret = fsctl_request_resume_key(work, req,
11071 					       (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
11072 		if (ret < 0)
11073 			goto out;
11074 		rsp->PersistentFileId = req->PersistentFileId;
11075 		rsp->VolatileFileId = req->VolatileFileId;
11076 		nbytes = sizeof(struct resume_key_ioctl_rsp);
11077 		break;
11078 	case FSCTL_SRV_COPYCHUNK:
11079 	case FSCTL_SRV_COPYCHUNK_WRITE:
11080 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
11081 			ksmbd_debug(SMB,
11082 				    "User does not have write permission\n");
11083 			ret = -EACCES;
11084 			goto out;
11085 		}
11086 
11087 		if (in_buf_len < offsetof(struct copychunk_ioctl_req, Chunks)) {
11088 			ret = -EINVAL;
11089 			goto out;
11090 		}
11091 
11092 		if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
11093 			ret = -EINVAL;
11094 			goto out;
11095 		}
11096 
11097 		nbytes = sizeof(struct copychunk_ioctl_rsp);
11098 		rsp->VolatileFileId = req->VolatileFileId;
11099 		rsp->PersistentFileId = req->PersistentFileId;
11100 		fsctl_copychunk(work,
11101 				(struct copychunk_ioctl_req *)buffer,
11102 				le32_to_cpu(req->CtlCode),
11103 				le32_to_cpu(req->InputCount),
11104 				req->VolatileFileId,
11105 				req->PersistentFileId,
11106 				rsp);
11107 		break;
11108 	case FSCTL_SET_SPARSE:
11109 	{
11110 		struct file_sparse sparse = {0};
11111 
11112 		if (in_buf_len && in_buf_len < sizeof(struct file_sparse)) {
11113 			ret = -EINVAL;
11114 			goto out;
11115 		}
11116 
11117 		*(u8 *)&sparse = 1;
11118 		ret = fsctl_set_sparse(work, id, in_buf_len ?
11119 				       (struct file_sparse *)buffer : &sparse);
11120 		if (ret < 0)
11121 			goto out;
11122 		break;
11123 	}
11124 	case FSCTL_SET_ZERO_DATA:
11125 	{
11126 		struct file_zero_data_information *zero_data;
11127 		struct ksmbd_file *fp;
11128 		loff_t off, len, bfz;
11129 
11130 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
11131 			ksmbd_debug(SMB,
11132 				    "User does not have write permission\n");
11133 			ret = -EACCES;
11134 			goto out;
11135 		}
11136 
11137 		if (in_buf_len < sizeof(struct file_zero_data_information)) {
11138 			ret = -EINVAL;
11139 			goto out;
11140 		}
11141 
11142 		zero_data =
11143 			(struct file_zero_data_information *)buffer;
11144 
11145 		off = le64_to_cpu(zero_data->FileOffset);
11146 		bfz = le64_to_cpu(zero_data->BeyondFinalZero);
11147 		if (off < 0 || bfz < 0 || off > bfz) {
11148 			ret = -EINVAL;
11149 			goto out;
11150 		}
11151 
11152 		len = bfz - off;
11153 		if (len) {
11154 			fp = ksmbd_lookup_fd_fast(work, id);
11155 			if (!fp) {
11156 				ret = -ENOENT;
11157 				goto out;
11158 			}
11159 
11160 			if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
11161 				ksmbd_fd_put(work, fp);
11162 				ret = -EACCES;
11163 				goto out;
11164 			}
11165 
11166 			ret = ksmbd_vfs_zero_data(work, fp, off, len);
11167 			ksmbd_fd_put(work, fp);
11168 			if (ret == -EAGAIN) {
11169 				rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
11170 				ret = 0;
11171 				goto out;
11172 			} else if (ret < 0) {
11173 				goto out;
11174 			}
11175 		}
11176 		break;
11177 	}
11178 	case FSCTL_FILE_LEVEL_TRIM:
11179 	{
11180 		struct file_level_trim *trim_req;
11181 		struct file_level_trim_output *trim_rsp;
11182 		struct ksmbd_file *fp;
11183 		u32 i, num_ranges;
11184 
11185 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
11186 			ksmbd_debug(SMB,
11187 				    "User does not have write permission\n");
11188 			ret = -EACCES;
11189 			goto out;
11190 		}
11191 
11192 		if (in_buf_len < offsetof(struct file_level_trim, Ranges)) {
11193 			ret = -EINVAL;
11194 			goto out;
11195 		}
11196 
11197 		if (out_buf_len < sizeof(struct file_level_trim_output)) {
11198 			ret = -EINVAL;
11199 			goto out;
11200 		}
11201 
11202 		trim_req = (struct file_level_trim *)buffer;
11203 		num_ranges = le32_to_cpu(trim_req->NumRanges);
11204 		if (num_ranges >
11205 		    (in_buf_len - offsetof(struct file_level_trim, Ranges)) /
11206 		    sizeof(struct file_level_trim_range)) {
11207 			ret = -EINVAL;
11208 			goto out;
11209 		}
11210 
11211 		fp = ksmbd_lookup_fd_fast(work, id);
11212 		if (!fp) {
11213 			ret = -ENOENT;
11214 			goto out;
11215 		}
11216 
11217 		if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
11218 			ksmbd_fd_put(work, fp);
11219 			ret = -EACCES;
11220 			goto out;
11221 		}
11222 
11223 		trim_rsp = (struct file_level_trim_output *)&rsp->Buffer[0];
11224 		trim_rsp->NumRangesProcessed = 0;
11225 		for (i = 0; i < num_ranges; i++) {
11226 			loff_t off = le64_to_cpu(trim_req->Ranges[i].Offset);
11227 			loff_t len = le64_to_cpu(trim_req->Ranges[i].Length);
11228 
11229 			if (off < 0 || len < 0) {
11230 				ret = -EINVAL;
11231 				break;
11232 			}
11233 
11234 			if (!len) {
11235 				trim_rsp->NumRangesProcessed =
11236 					cpu_to_le32(i + 1);
11237 				continue;
11238 			}
11239 
11240 			ret = ksmbd_vfs_trim_data(work, fp, off, len);
11241 			if (ret)
11242 				break;
11243 			trim_rsp->NumRangesProcessed = cpu_to_le32(i + 1);
11244 		}
11245 		ksmbd_fd_put(work, fp);
11246 		if (ret == -EAGAIN) {
11247 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
11248 			ret = 0;
11249 			goto out;
11250 		} else if (ret < 0) {
11251 			goto out;
11252 		}
11253 
11254 		nbytes = sizeof(struct file_level_trim_output);
11255 		break;
11256 	}
11257 	case FSCTL_QUERY_ALLOCATED_RANGES:
11258 		if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
11259 			ret = -EINVAL;
11260 			goto out;
11261 		}
11262 
11263 		ret = fsctl_query_allocated_ranges(work, id,
11264 			(struct file_allocated_range_buffer *)buffer,
11265 			(struct file_allocated_range_buffer *)&rsp->Buffer[0],
11266 			out_buf_len /
11267 			sizeof(struct file_allocated_range_buffer), &nbytes);
11268 		if (ret == -E2BIG) {
11269 			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
11270 		} else if (ret < 0) {
11271 			nbytes = 0;
11272 			goto out;
11273 		}
11274 
11275 		nbytes *= sizeof(struct file_allocated_range_buffer);
11276 		break;
11277 	case FSCTL_GET_REPARSE_POINT:
11278 	{
11279 		struct reparse_data_buffer *reparse_ptr;
11280 		struct ksmbd_file *fp;
11281 
11282 		if (out_buf_len < sizeof(struct reparse_data_buffer)) {
11283 			ret = -EINVAL;
11284 			goto out;
11285 		}
11286 
11287 		reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
11288 		fp = ksmbd_lookup_fd_fast(work, id);
11289 		if (!fp) {
11290 			pr_err("not found fp!!\n");
11291 			ret = -ENOENT;
11292 			goto out;
11293 		}
11294 
11295 		reparse_ptr->ReparseTag =
11296 			smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
11297 		reparse_ptr->ReparseDataLength = 0;
11298 		ksmbd_fd_put(work, fp);
11299 		nbytes = sizeof(struct reparse_data_buffer);
11300 		break;
11301 	}
11302 	case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
11303 	{
11304 		struct ksmbd_file *fp_in, *fp_out = NULL;
11305 		struct duplicate_extents_to_file *dup_ext;
11306 		loff_t src_off, dst_off, length, cloned;
11307 
11308 		if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
11309 			ret = -EINVAL;
11310 			goto out;
11311 		}
11312 
11313 		dup_ext = (struct duplicate_extents_to_file *)buffer;
11314 
11315 		fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
11316 					     dup_ext->PersistentFileHandle);
11317 		if (!fp_in) {
11318 			pr_err("not found file handle in duplicate extent to file\n");
11319 			ret = -EBADF;
11320 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
11321 			goto out2;
11322 		}
11323 
11324 		fp_out = ksmbd_lookup_fd_fast(work, id);
11325 		if (!fp_out) {
11326 			pr_err("not found fp\n");
11327 			ret = -EBADF;
11328 			rsp->hdr.Status = STATUS_FILE_CLOSED;
11329 			ksmbd_fd_put(work, fp_in);
11330 			goto out2;
11331 		}
11332 
11333 		if (!test_tree_conn_flag(work->tcon,
11334 					 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
11335 			ret = -EACCES;
11336 			goto dup_ext_out;
11337 		}
11338 
11339 		if (!(fp_out->daccess & FILE_WRITE_DATA_LE)) {
11340 			ret = -EACCES;
11341 			goto dup_ext_out;
11342 		}
11343 		if (!(fp_in->daccess & FILE_READ_DATA_LE)) {
11344 			ret = -EACCES;
11345 			goto dup_ext_out;
11346 		}
11347 
11348 		src_off = le64_to_cpu(dup_ext->SourceFileOffset);
11349 		dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
11350 		length = le64_to_cpu(dup_ext->ByteCount);
11351 		if (src_off < 0 || dst_off < 0 || length < 0 ||
11352 		    src_off + length < src_off || dst_off + length < dst_off) {
11353 			ret = -EINVAL;
11354 			goto dup_ext_out;
11355 		}
11356 		if (src_off + length > i_size_read(file_inode(fp_in->filp))) {
11357 			ret = -EOPNOTSUPP;
11358 			goto dup_ext_out;
11359 		}
11360 		if (dst_off + length > i_size_read(file_inode(fp_out->filp)))
11361 			goto dup_ext_out;
11362 		if ((fp_in->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE) &&
11363 		    !(fp_out->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)) {
11364 			ret = -EOPNOTSUPP;
11365 			goto dup_ext_out;
11366 		}
11367 		if (file_inode(fp_in->filp) == file_inode(fp_out->filp) &&
11368 		    dst_off + length > src_off &&
11369 		    dst_off < src_off + length) {
11370 			ret = -EOPNOTSUPP;
11371 			goto dup_ext_out;
11372 		}
11373 
11374 		cloned = vfs_clone_file_range(fp_in->filp, src_off,
11375 					      fp_out->filp, dst_off, length, 0);
11376 		if (cloned != length) {
11377 			cloned = vfs_copy_file_range(fp_in->filp, src_off,
11378 						     fp_out->filp, dst_off,
11379 						     length, 0);
11380 			if (cloned != length) {
11381 				if (cloned < 0)
11382 					ret = cloned;
11383 				else
11384 					ret = -EINVAL;
11385 			}
11386 		}
11387 
11388 dup_ext_out:
11389 		ksmbd_fd_put(work, fp_in);
11390 		ksmbd_fd_put(work, fp_out);
11391 		if (ret < 0)
11392 			goto out;
11393 		break;
11394 	}
11395 	default:
11396 		ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
11397 			    cnt_code);
11398 		ret = -EOPNOTSUPP;
11399 		goto out;
11400 	}
11401 
11402 	rsp->CtlCode = cpu_to_le32(cnt_code);
11403 	rsp->InputCount = cpu_to_le32(0);
11404 	rsp->InputOffset = cpu_to_le32(112);
11405 	rsp->OutputOffset = cpu_to_le32(112);
11406 	rsp->OutputCount = cpu_to_le32(nbytes);
11407 	rsp->StructureSize = cpu_to_le16(49);
11408 	rsp->Reserved = cpu_to_le16(0);
11409 	rsp->Flags = cpu_to_le32(0);
11410 	rsp->Reserved2 = cpu_to_le32(0);
11411 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
11412 	if (!ret)
11413 		return ret;
11414 
11415 out:
11416 	if (ret == -EACCES)
11417 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
11418 	else if (ret == -ENOENT)
11419 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
11420 	else if (ret == -EOPNOTSUPP)
11421 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
11422 	else if (ret == -ENOSPC)
11423 		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
11424 	else if (!chseq_err && (ret < 0 || rsp->hdr.Status == 0))
11425 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
11426 
11427 out2:
11428 	smb2_set_err_rsp(work);
11429 	return ret;
11430 }
11431 
11432 /**
11433  * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
11434  * @work:	smb work containing oplock break command buffer
11435  *
11436  * Return:	0
11437  */
11438 static void smb20_oplock_break_ack(struct ksmbd_work *work)
11439 {
11440 	struct smb2_oplock_break *req;
11441 	struct smb2_oplock_break *rsp;
11442 	struct ksmbd_file *fp;
11443 	struct oplock_info *opinfo = NULL;
11444 	__le32 status = STATUS_SUCCESS;
11445 	int ret;
11446 	u64 volatile_id, persistent_id;
11447 	char req_oplevel = 0, rsp_oplevel = 0;
11448 
11449 	WORK_BUFFERS(work, req, rsp);
11450 
11451 	volatile_id = req->VolatileFid;
11452 	persistent_id = req->PersistentFid;
11453 	req_oplevel = req->OplockLevel;
11454 	ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
11455 		    volatile_id, persistent_id, req_oplevel);
11456 
11457 	fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
11458 	if (!fp) {
11459 		rsp->hdr.Status = STATUS_FILE_CLOSED;
11460 		smb2_set_err_rsp(work);
11461 		return;
11462 	}
11463 
11464 	ret = smb2_set_request_open(work, fp, &req->hdr, false, false);
11465 	if (ret) {
11466 		rsp->hdr.Status = STATUS_FILE_CLOSED;
11467 		smb2_set_err_rsp(work);
11468 		ksmbd_fd_put(work, fp);
11469 		return;
11470 	}
11471 
11472 	opinfo = opinfo_get(fp);
11473 	if (!opinfo) {
11474 		pr_err("unexpected null oplock_info\n");
11475 		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
11476 		smb2_set_err_rsp(work);
11477 		ksmbd_fd_put(work, fp);
11478 		return;
11479 	}
11480 
11481 	if (opinfo->op_state != OPLOCK_ACK_WAIT) {
11482 		ksmbd_debug(SMB, "unexpected oplock state 0x%x\n",
11483 			    opinfo->op_state);
11484 		if (smb3_hdr_replay(&req->hdr) &&
11485 		    opinfo->op_state == OPLOCK_STATE_NONE) {
11486 			rsp->StructureSize = cpu_to_le16(24);
11487 			rsp->OplockLevel = opinfo->level;
11488 			rsp->Reserved = 0;
11489 			rsp->Reserved2 = 0;
11490 			rsp->VolatileFid = volatile_id;
11491 			rsp->PersistentFid = persistent_id;
11492 			ret = ksmbd_iov_pin_rsp(work, rsp,
11493 						 sizeof(struct smb2_oplock_break));
11494 			if (ret)
11495 				ksmbd_debug(SMB,
11496 					    "failed to pin replayed oplock break response: %d\n",
11497 					    ret);
11498 			goto out_no_state_change;
11499 		}
11500 		if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE)
11501 			status = STATUS_INVALID_OPLOCK_PROTOCOL;
11502 		else
11503 			status = STATUS_INVALID_DEVICE_STATE;
11504 		goto err_out;
11505 	}
11506 
11507 	if (req_oplevel == SMB2_OPLOCK_LEVEL_LEASE) {
11508 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
11509 		status = STATUS_INVALID_PARAMETER;
11510 		goto err_out;
11511 	}
11512 
11513 	if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
11514 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
11515 		goto err_out;
11516 	}
11517 
11518 	if (opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE &&
11519 	    req_oplevel != SMB2_OPLOCK_LEVEL_II &&
11520 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
11521 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
11522 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
11523 		goto err_out;
11524 	}
11525 
11526 	if (opinfo->level == SMB2_OPLOCK_LEVEL_BATCH &&
11527 	    req_oplevel != SMB2_OPLOCK_LEVEL_II &&
11528 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE &&
11529 	    req_oplevel != SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
11530 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
11531 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
11532 		goto err_out;
11533 	}
11534 
11535 	if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
11536 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
11537 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
11538 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
11539 		goto err_out;
11540 	}
11541 
11542 	if (req_oplevel == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
11543 		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
11544 	else
11545 		rsp_oplevel = req_oplevel;
11546 
11547 	opinfo->level = rsp_oplevel;
11548 
11549 	rsp->StructureSize = cpu_to_le16(24);
11550 	rsp->OplockLevel = rsp_oplevel;
11551 	rsp->Reserved = 0;
11552 	rsp->Reserved2 = 0;
11553 	rsp->VolatileFid = volatile_id;
11554 	rsp->PersistentFid = persistent_id;
11555 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
11556 	if (ret)
11557 		ksmbd_debug(SMB, "failed to pin oplock break response: %d\n",
11558 			    ret);
11559 	goto out;
11560 
11561 err_out:
11562 	rsp->hdr.Status = status;
11563 	smb2_set_err_rsp(work);
11564 
11565 out:
11566 	spin_lock(&opinfo->state_lock);
11567 	if (opinfo->op_state != OPLOCK_CLOSING)
11568 		opinfo->op_state = OPLOCK_STATE_NONE;
11569 	spin_unlock(&opinfo->state_lock);
11570 	wake_up_interruptible_all(&opinfo->oplock_q);
11571 out_no_state_change:
11572 	opinfo_put(opinfo);
11573 	ksmbd_fd_put(work, fp);
11574 }
11575 
11576 static bool smb2_lease_state_valid(__le32 state)
11577 {
11578 	return !(state & ~(SMB2_LEASE_READ_CACHING_LE |
11579 			   SMB2_LEASE_HANDLE_CACHING_LE |
11580 			   SMB2_LEASE_WRITE_CACHING_LE));
11581 }
11582 
11583 static int check_lease_state(struct lease *lease, __le32 req_state)
11584 {
11585 	if (smb2_lease_state_valid(req_state) &&
11586 	    !(req_state & ~lease->new_state))
11587 		return 0;
11588 
11589 	return 1;
11590 }
11591 
11592 /**
11593  * smb21_lease_break_ack() - handler for smb2.1 lease break command
11594  * @work:	smb work containing lease break command buffer
11595  *
11596  * Return:	0
11597  */
11598 static void smb21_lease_break_ack(struct ksmbd_work *work)
11599 {
11600 	struct ksmbd_conn *conn = work->conn;
11601 	struct smb2_lease_ack *req;
11602 	struct smb2_lease_ack *rsp;
11603 	struct oplock_info *opinfo;
11604 	int ret = 0;
11605 	__le32 lease_state;
11606 	struct lease *lease;
11607 
11608 	WORK_BUFFERS(work, req, rsp);
11609 
11610 	ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
11611 		    le32_to_cpu(req->LeaseState));
11612 	opinfo = lookup_lease_in_table(conn, req->LeaseKey);
11613 	if (!opinfo) {
11614 		ksmbd_debug(OPLOCK, "file not opened\n");
11615 		smb2_set_err_rsp(work);
11616 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
11617 		return;
11618 	}
11619 	lease = opinfo->o_lease;
11620 
11621 	if (opinfo->op_state == OPLOCK_STATE_NONE) {
11622 		pr_err("unexpected lease break state 0x%x\n",
11623 		       opinfo->op_state);
11624 		if (smb3_hdr_replay(&req->hdr))
11625 			goto replay_rsp;
11626 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
11627 		goto err_out;
11628 	}
11629 
11630 	if (!atomic_read(&opinfo->breaking_cnt)) {
11631 		if (smb3_hdr_replay(&req->hdr))
11632 			goto replay_rsp;
11633 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
11634 		goto err_out;
11635 	}
11636 
11637 	if (check_lease_state(lease, req->LeaseState)) {
11638 		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
11639 		ksmbd_debug(OPLOCK,
11640 			    "req lease state: 0x%x, expected state: 0x%x\n",
11641 			    req->LeaseState, lease->new_state);
11642 		goto err_out;
11643 	}
11644 
11645 	lease_state = req->LeaseState;
11646 	lease->state = lease_state;
11647 	lease->new_state = SMB2_LEASE_NONE_LE;
11648 	lease_update_oplock_levels(lease);
11649 
11650 	rsp->StructureSize = cpu_to_le16(36);
11651 	rsp->Reserved = 0;
11652 	rsp->Flags = 0;
11653 	memcpy(rsp->LeaseKey, req->LeaseKey, 16);
11654 	rsp->LeaseState = lease_state;
11655 	rsp->LeaseDuration = 0;
11656 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
11657 	if (ret)
11658 		goto err_out;
11659 
11660 	spin_lock(&opinfo->state_lock);
11661 	if (opinfo->op_state != OPLOCK_CLOSING)
11662 		opinfo->op_state = OPLOCK_STATE_NONE;
11663 	spin_unlock(&opinfo->state_lock);
11664 	wake_up_interruptible_all(&opinfo->oplock_q);
11665 	atomic_dec_if_positive(&opinfo->breaking_cnt);
11666 	wake_up_interruptible_all(&opinfo->oplock_brk);
11667 	opinfo_put(opinfo);
11668 	return;
11669 
11670 replay_rsp:
11671 	rsp->StructureSize = cpu_to_le16(36);
11672 	rsp->Reserved = 0;
11673 	rsp->Flags = 0;
11674 	memcpy(rsp->LeaseKey, req->LeaseKey, 16);
11675 	rsp->LeaseState = lease->state;
11676 	rsp->LeaseDuration = 0;
11677 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
11678 	if (ret)
11679 		goto err_out;
11680 	opinfo_put(opinfo);
11681 	return;
11682 
11683 err_out:
11684 	smb2_set_err_rsp(work);
11685 	opinfo_put(opinfo);
11686 	return;
11687 }
11688 
11689 /**
11690  * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
11691  * @work:	smb work containing oplock/lease break command buffer
11692  *
11693  * Return:	0 on success, otherwise error
11694  */
11695 int smb2_oplock_break(struct ksmbd_work *work)
11696 {
11697 	struct smb2_oplock_break *req;
11698 	struct smb2_oplock_break *rsp;
11699 
11700 	ksmbd_debug(SMB, "Received smb2 oplock break acknowledgment request\n");
11701 
11702 	WORK_BUFFERS(work, req, rsp);
11703 
11704 	switch (le16_to_cpu(req->StructureSize)) {
11705 	case OP_BREAK_STRUCT_SIZE_20:
11706 		smb20_oplock_break_ack(work);
11707 		break;
11708 	case OP_BREAK_STRUCT_SIZE_21:
11709 		smb21_lease_break_ack(work);
11710 		break;
11711 	default:
11712 		ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
11713 			    le16_to_cpu(req->StructureSize));
11714 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
11715 		smb2_set_err_rsp(work);
11716 		return -EINVAL;
11717 	}
11718 
11719 	return 0;
11720 }
11721 
11722 /*
11723  * Cancel handler for a deferred CHANGE_NOTIFY. Races against
11724  * __ksmbd_close_fd()'s notify_pendings drain (vfs_cache.c), which can run
11725  * concurrently on a different connection closing the same handle -- only
11726  * one of the two may claim and free in_work, so both sides check
11727  * list_empty() under fp->f_lock before touching it (list_del_init()
11728  * leaves a node empty, so whichever side removes it first is the owner;
11729  * the loser must not touch in_work again, since the winner may already be
11730  * freeing it).
11731  *
11732  * smb2_cancel() holds conn->request_lock (a spinlock) for the entire
11733  * time it walks conn->async_requests and calls this function -- so this
11734  * runs with preemption disabled and must not sleep or re-acquire that
11735  * same lock. release_async_work() does both (it takes conn->request_lock
11736  * itself, and frees things that can involve sleeping paths), so calling
11737  * it from here would self-deadlock the very thread processing the
11738  * client's CANCEL command. ksmbd_conn_write() can also sleep (it takes
11739  * conn's write mutex). So: do only the non-sleeping, no-relock cleanup
11740  * inline here. smb2_cancel() sends and frees the claimed notify after it
11741  * drops request_lock, preserving response order for a client CANCEL. The
11742  * connection teardown caller has no such post-unlock path, so its wrapper
11743  * defers the send and free to a workqueue.
11744  */
11745 struct notify_cancel_ctx {
11746 	struct work_struct	work;
11747 	struct ksmbd_work	*in_work;
11748 };
11749 
11750 static void smb2_send_notify_cancelled(struct ksmbd_work *work)
11751 {
11752 	struct smb2_hdr *hdr = smb_get_msg(work->response_buf);
11753 	struct ksmbd_conn *conn = work->conn;
11754 	struct ksmbd_session *sess;
11755 
11756 	sess = ksmbd_session_lookup(conn, le64_to_cpu(hdr->SessionId));
11757 	if (sess) {
11758 		work->sess = sess;
11759 		if (work->encrypted && sess->enc && conn->ops->encrypt_resp) {
11760 			conn->ops->encrypt_resp(work);
11761 		} else if (conn->ops->is_sign_req && conn->ops->set_sign_rsp &&
11762 			   conn->ops->is_sign_req(work,
11763 						 conn->ops->get_cmd_val(work))) {
11764 			conn->ops->set_sign_rsp(work);
11765 		}
11766 	}
11767 
11768 	ksmbd_conn_write(work);
11769 	if (sess) {
11770 		ksmbd_user_session_put(sess);
11771 		work->sess = NULL;
11772 	}
11773 }
11774 
11775 static void smb2_notify_cancel_deferred(struct work_struct *w)
11776 {
11777 	struct notify_cancel_ctx *ctx =
11778 		container_of(w, struct notify_cancel_ctx, work);
11779 	struct ksmbd_conn *conn = ctx->in_work->conn;
11780 
11781 	smb2_complete_notify_cancel(ctx->in_work);
11782 	kfree(ctx);
11783 	/*
11784 	 * The connection teardown waits for r_count before destroying
11785 	 * connection sessions and their proc entries.
11786 	 */
11787 	ksmbd_conn_r_count_dec(conn);
11788 }
11789 
11790 static struct ksmbd_work *smb2_notify_cancel_claim(void **argv)
11791 {
11792 	struct ksmbd_work *in_work = (struct ksmbd_work *)argv[0];
11793 	struct ksmbd_file *fp = (struct ksmbd_file *)argv[1];
11794 	bool claimed;
11795 
11796 	spin_lock(&fp->f_lock);
11797 	claimed = !list_empty(&in_work->notify_entry);
11798 	if (claimed)
11799 		list_del_init(&in_work->notify_entry);
11800 	spin_unlock(&fp->f_lock);
11801 
11802 	if (!claimed)
11803 		return NULL;
11804 
11805 	/* conn->request_lock is held by smb2_cancel() or connection teardown. */
11806 	in_work->cancel_fn = NULL;
11807 	kfree(in_work->cancel_argv);
11808 	in_work->cancel_argv = NULL;
11809 	return in_work;
11810 }
11811 
11812 static void smb2_complete_notify_cancel(struct ksmbd_work *in_work)
11813 {
11814 	struct smb2_hdr *in_hdr = smb_get_msg(in_work->response_buf);
11815 
11816 	in_hdr->Status = STATUS_CANCELLED;
11817 	smb2_send_notify_cancelled(in_work);
11818 	release_async_work(in_work);
11819 	ksmbd_free_work_struct(in_work);
11820 }
11821 
11822 static void smb2_notify_cancel_fn(void **argv)
11823 {
11824 	struct ksmbd_work *in_work = smb2_notify_cancel_claim(argv);
11825 	struct ksmbd_conn *conn;
11826 	struct notify_cancel_ctx *ctx;
11827 
11828 	if (!in_work)
11829 		return;
11830 	conn = in_work->conn;
11831 
11832 	ctx = kmalloc_obj(*ctx, GFP_ATOMIC);
11833 	if (!ctx) {
11834 		/* Can't defer the response -- free without sending one. */
11835 		list_del_init(&in_work->async_request_entry);
11836 		in_work->asynchronous = false;
11837 		if (in_work->async_id) {
11838 			ksmbd_release_id(&conn->async_ida, in_work->async_id);
11839 			in_work->async_id = 0;
11840 		}
11841 		ksmbd_free_work_struct(in_work);
11842 		return;
11843 	}
11844 	ctx->in_work = in_work;
11845 	INIT_WORK(&ctx->work, smb2_notify_cancel_deferred);
11846 	/*
11847 	 * This deferred work can outlive the connection handler's receive loop.
11848 	 * Keep teardown from destroying the connection's sessions until the
11849 	 * deferred response has finished using them.
11850 	 */
11851 	ksmbd_conn_r_count_inc(conn);
11852 	schedule_work(&ctx->work);
11853 }
11854 
11855 /**
11856  * smb2_notify() - handler for smb2 notify request
11857  * @work:   smb work containing notify command buffer
11858  *
11859  * Return:      0 on success, otherwise error
11860  */
11861 int smb2_notify(struct ksmbd_work *work)
11862 {
11863 	struct smb2_change_notify_req *req;
11864 	struct smb2_change_notify_rsp *rsp;
11865 	struct ksmbd_work *in_work;
11866 	struct smb2_hdr *in_hdr;
11867 	struct ksmbd_file *fp;
11868 
11869 	ksmbd_debug(SMB, "Received smb2 notify\n");
11870 
11871 	WORK_BUFFERS(work, req, rsp);
11872 
11873 	if (smb2_compound_has_failed(work, &rsp->hdr))
11874 		return -EACCES;
11875 
11876 	if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
11877 		rsp->hdr.Status = STATUS_INTERNAL_ERROR;
11878 		smb2_set_err_rsp(work);
11879 		return -EIO;
11880 	}
11881 
11882 	/*
11883 	 * macOS backupd sends CHANGE_NOTIFY with FileId=FFFF...FFFF (share-root
11884 	 * sentinel) to watch for changes on the share root without holding an
11885 	 * open handle. Respond STATUS_PENDING + STATUS_NOTIFY_CLEANUP immediately;
11886 	 * without this, backupd aborts Time Machine setup on STATUS_FILE_CLOSED.
11887 	 */
11888 	if (req->VolatileFileId == SMB2_NO_FID &&
11889 	    req->PersistentFileId == SMB2_NO_FID) {
11890 		in_work = ksmbd_alloc_work_struct();
11891 		if (!in_work || allocate_interim_rsp_buf(in_work)) {
11892 			if (in_work)
11893 				ksmbd_free_work_struct(in_work);
11894 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
11895 			smb2_set_err_rsp(work);
11896 			return 0;
11897 		}
11898 		if (setup_async_work(work, NULL, NULL)) {
11899 			ksmbd_free_work_struct(in_work);
11900 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
11901 			smb2_set_err_rsp(work);
11902 			return 0;
11903 		}
11904 		smb2_send_interim_resp(work, STATUS_PENDING);
11905 		in_work->conn = work->conn;
11906 		in_hdr = smb_get_msg(in_work->response_buf);
11907 		memcpy(in_hdr, ksmbd_resp_buf_next(work),
11908 		       __SMB2_HEADER_STRUCTURE_SIZE);
11909 		in_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
11910 		in_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
11911 		smb2_set_err_rsp(in_work);
11912 		in_hdr->Status = STATUS_NOTIFY_CLEANUP;
11913 		in_work->async_id = work->async_id;
11914 		work->async_id = 0;
11915 		release_async_work(work);
11916 		if (smb2_send_interim_work(in_work, work, false))
11917 			ksmbd_debug(SMB, "failed to send notify cleanup\n");
11918 		ksmbd_free_work_struct(in_work);
11919 		work->send_no_response = 1;
11920 		return 0;
11921 	}
11922 
11923 	/*
11924 	 * KSMBD does not implement a real change-notification backend.
11925 	 * Genuine SMB2 servers (and macOS smbfs) never complete a
11926 	 * CHANGE_NOTIFY spontaneously: it is satisfied only by a real
11927 	 * directory change, or with STATUS_NOTIFY_CLEANUP when the watched
11928 	 * handle is closed. Completing it early (e.g. on a timer) makes
11929 	 * Finder treat the cleanup as "directory changed" and re-enumerate
11930 	 * the directory forever, leaving items unopenable. Returning
11931 	 * STATUS_NOT_IMPLEMENTED here (like stock ksmbd) makes macOS smbfs
11932 	 * hard-freeze on unmount, so this must stay deferred.
11933 	 */
11934 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
11935 	if (!fp) {
11936 		rsp->hdr.Status = STATUS_FILE_CLOSED;
11937 		smb2_set_err_rsp(work);
11938 		return 0;
11939 	}
11940 
11941 	in_work = ksmbd_alloc_work_struct();
11942 	if (!in_work || allocate_interim_rsp_buf(in_work)) {
11943 		if (in_work)
11944 			ksmbd_free_work_struct(in_work);
11945 		ksmbd_fd_put(work, fp);
11946 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
11947 		smb2_set_err_rsp(work);
11948 		return 0;
11949 	}
11950 	/*
11951 	 * in_work is synthetic (not from the normal request-receiving
11952 	 * pipeline), so it has no request_buf of its own. It gets registered
11953 	 * into conn->async_requests below, and smb2_cancel() unconditionally
11954 	 * computes smb_get_msg(iter->request_buf) for every entry in that
11955 	 * list while searching for a match -- give it its own small buffer
11956 	 * (not an alias of response_buf: ksmbd_free_work_struct() kvfree()s
11957 	 * both separately, so aliasing them would double-free) so that stays
11958 	 * a harmless read instead of a near-NULL dereference.
11959 	 */
11960 	in_work->request_buf = kzalloc(MAX_CIFS_SMALL_BUFFER_SIZE, KSMBD_DEFAULT_GFP);
11961 	if (!in_work->request_buf) {
11962 		ksmbd_free_work_struct(in_work);
11963 		ksmbd_fd_put(work, fp);
11964 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
11965 		smb2_set_err_rsp(work);
11966 		return 0;
11967 	}
11968 	memcpy(smb_get_msg(in_work->request_buf), req,
11969 	       __SMB2_HEADER_STRUCTURE_SIZE);
11970 
11971 	if (setup_async_work(work, NULL, NULL)) {
11972 		ksmbd_free_work_struct(in_work);
11973 		ksmbd_fd_put(work, fp);
11974 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
11975 		smb2_set_err_rsp(work);
11976 		return 0;
11977 	}
11978 
11979 	smb2_send_interim_resp(work, STATUS_PENDING);
11980 
11981 	/* Keep the async IDA alive until the deferred work is released. */
11982 	in_work->conn = ksmbd_conn_get(work->conn);
11983 	in_work->owns_conn_ref = true;
11984 	in_work->encrypted = work->encrypted;
11985 	in_hdr = smb_get_msg(in_work->response_buf);
11986 	memcpy(in_hdr, ksmbd_resp_buf_next(work), __SMB2_HEADER_STRUCTURE_SIZE);
11987 	in_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
11988 	in_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
11989 	smb2_set_err_rsp(in_work);
11990 	in_hdr->Status = STATUS_NOTIFY_CLEANUP;
11991 
11992 	/*
11993 	 * Transfer ownership of the async id to in_work; it stays reserved
11994 	 * until in_work is freed after the deferred response is sent on
11995 	 * close, so it can't be reused for an unrelated async response.
11996 	 */
11997 	in_work->async_id = work->async_id;
11998 	work->async_id = 0;
11999 	release_async_work(work);
12000 
12001 	/*
12002 	 * work itself is about to be recycled by the normal request-processing
12003 	 * pipeline, so it can't stay the target of a future CANCEL -- register
12004 	 * in_work instead, reusing the same async_id, so a client-sent CANCEL
12005 	 * for this notify actually finds something to cancel instead of
12006 	 * silently doing nothing until the handle eventually closes.
12007 	 */
12008 	in_work->asynchronous = true;
12009 	in_work->cancel_argv = kmalloc_array(2, sizeof(void *), KSMBD_DEFAULT_GFP);
12010 	if (in_work->cancel_argv) {
12011 		in_work->cancel_argv[0] = in_work;
12012 		in_work->cancel_argv[1] = fp;
12013 		in_work->cancel_fn = smb2_notify_cancel_fn;
12014 	}
12015 
12016 	if (!ksmbd_conn_link_async_request(work->conn, in_work)) {
12017 		kfree(in_work->cancel_argv);
12018 		in_work->cancel_argv = NULL;
12019 		in_work->cancel_fn = NULL;
12020 		in_work->asynchronous = false;
12021 		ksmbd_fd_put(work, fp);
12022 		if (smb2_send_interim_work(in_work, work, false))
12023 			ksmbd_debug(SMB, "failed to send notify cleanup\n");
12024 		ksmbd_free_work_struct(in_work);
12025 		work->send_no_response = 1;
12026 		return 0;
12027 	}
12028 
12029 	spin_lock(&fp->f_lock);
12030 	list_add_tail(&in_work->notify_entry, &fp->notify_pendings);
12031 	spin_unlock(&fp->f_lock);
12032 
12033 	ksmbd_fd_put(work, fp);
12034 	work->send_no_response = 1;
12035 	return 0;
12036 }
12037 
12038 /**
12039  * smb2_is_sign_req() - handler for checking packet signing status
12040  * @work:	smb work containing notify command buffer
12041  * @command:	SMB2 command id
12042  *
12043  * Return:	true if packed is signed, false otherwise
12044  */
12045 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
12046 {
12047 	struct smb2_hdr *rcv_hdr2 = smb_get_msg(work->request_buf);
12048 
12049 	if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
12050 	    command != SMB2_NEGOTIATE_HE)
12051 		return true;
12052 
12053 	return false;
12054 }
12055 
12056 /**
12057  * smb2_check_sign_req() - handler for req packet sign processing
12058  * @work:   smb work containing notify command buffer
12059  *
12060  * Return:	1 on success, 0 otherwise
12061  */
12062 int smb2_check_sign_req(struct ksmbd_work *work)
12063 {
12064 	struct smb2_hdr *hdr;
12065 	char signature_req[SMB2_SIGNATURE_SIZE];
12066 	char signature[SMB2_HMACSHA256_SIZE];
12067 	struct kvec iov[1];
12068 	size_t len;
12069 
12070 	hdr = smb_get_msg(work->request_buf);
12071 	if (work->next_smb2_rcv_hdr_off)
12072 		hdr = ksmbd_req_buf_next(work);
12073 
12074 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
12075 		len = get_rfc1002_len(work->request_buf);
12076 	else if (hdr->NextCommand)
12077 		len = le32_to_cpu(hdr->NextCommand);
12078 	else
12079 		len = get_rfc1002_len(work->request_buf) -
12080 			work->next_smb2_rcv_hdr_off;
12081 
12082 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
12083 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12084 
12085 	iov[0].iov_base = (char *)&hdr->ProtocolId;
12086 	iov[0].iov_len = len;
12087 
12088 	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
12089 			    signature);
12090 
12091 	if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
12092 		pr_err("bad smb2 signature\n");
12093 		return 0;
12094 	}
12095 
12096 	return 1;
12097 }
12098 
12099 /**
12100  * smb2_get_sign_rsp_iov() - get the iovecs used to sign a response
12101  * @work: work that has the response iovecs
12102  * @hdr: SMB2 header of the response
12103  * @n_vec: set to the number of iovecs to sign
12104  *
12105  * Response data may be in another buffer. In this case, the response uses
12106  * more than one iovec. Find the iovec that starts with @hdr. Sign this
12107  * iovec and all iovecs after it.
12108  *
12109  * Return: The first iovec to sign.
12110  */
12111 static struct kvec *smb2_get_sign_rsp_iov(struct ksmbd_work *work,
12112 					   struct smb2_hdr *hdr, int *n_vec)
12113 {
12114 	int i;
12115 
12116 	/*
12117 	 * iov[0] has the RFC1002 message length. It is not part of the SMB2
12118 	 * message, so do not sign it.
12119 	 */
12120 	for (i = 1; i <= work->iov_idx; i++) {
12121 		if (work->iov[i].iov_base == hdr) {
12122 			*n_vec = work->iov_idx - i + 1;
12123 			return &work->iov[i];
12124 		}
12125 	}
12126 
12127 	WARN_ON_ONCE(1);
12128 	*n_vec = 1;
12129 	return &work->iov[work->iov_idx];
12130 }
12131 
12132 /**
12133  * smb2_set_sign_rsp() - handler for rsp packet sign processing
12134  * @work:   smb work containing notify command buffer
12135  *
12136  */
12137 void smb2_set_sign_rsp(struct ksmbd_work *work)
12138 {
12139 	struct smb2_hdr *hdr;
12140 	char signature[SMB2_HMACSHA256_SIZE];
12141 	struct kvec *iov;
12142 	int n_vec;
12143 
12144 	hdr = ksmbd_resp_buf_curr(work);
12145 	hdr->Flags |= SMB2_FLAGS_SIGNED;
12146 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12147 
12148 	iov = smb2_get_sign_rsp_iov(work, hdr, &n_vec);
12149 
12150 	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
12151 			    signature);
12152 	memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
12153 }
12154 
12155 /**
12156  * smb3_check_sign_req() - handler for req packet sign processing
12157  * @work:   smb work containing notify command buffer
12158  *
12159  * Return:	1 on success, 0 otherwise
12160  */
12161 int smb3_check_sign_req(struct ksmbd_work *work)
12162 {
12163 	struct ksmbd_conn *conn = work->conn;
12164 	char *signing_key;
12165 	struct smb2_hdr *hdr;
12166 	struct channel *chann;
12167 	char signature_req[SMB2_SIGNATURE_SIZE];
12168 	char signature[SMB2_CMACAES_SIZE];
12169 	struct kvec iov[1];
12170 	size_t len;
12171 
12172 	hdr = smb_get_msg(work->request_buf);
12173 	if (work->next_smb2_rcv_hdr_off)
12174 		hdr = ksmbd_req_buf_next(work);
12175 
12176 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
12177 		len = get_rfc1002_len(work->request_buf);
12178 	else if (hdr->NextCommand)
12179 		len = le32_to_cpu(hdr->NextCommand);
12180 	else
12181 		len = get_rfc1002_len(work->request_buf) -
12182 			work->next_smb2_rcv_hdr_off;
12183 
12184 	if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
12185 		signing_key = work->sess->smb3signingkey;
12186 	} else {
12187 		chann = lookup_chann_list(work->sess, conn);
12188 		if (!chann) {
12189 			if (le16_to_cpu(hdr->Command) != SMB2_SESSION_SETUP_HE ||
12190 			    !(hdr->Flags & SMB2_FLAGS_SIGNED))
12191 				return 0;
12192 			signing_key = work->sess->smb3signingkey;
12193 		} else {
12194 			signing_key = chann->smb3signingkey;
12195 		}
12196 	}
12197 
12198 	if (!signing_key) {
12199 		pr_err("SMB3 signing key is not generated\n");
12200 		return 0;
12201 	}
12202 
12203 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
12204 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12205 	iov[0].iov_base = (char *)&hdr->ProtocolId;
12206 	iov[0].iov_len = len;
12207 
12208 	ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature);
12209 
12210 	if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
12211 		pr_err("bad smb2 signature\n");
12212 		return 0;
12213 	}
12214 
12215 	return 1;
12216 }
12217 
12218 /**
12219  * smb3_set_sign_rsp() - handler for rsp packet sign processing
12220  * @work:   smb work containing notify command buffer
12221  *
12222  */
12223 void smb3_set_sign_rsp(struct ksmbd_work *work)
12224 {
12225 	struct ksmbd_conn *conn = work->conn;
12226 	struct smb2_hdr *hdr;
12227 	struct channel *chann;
12228 	char signature[SMB2_CMACAES_SIZE];
12229 	struct kvec *iov;
12230 	u16 command = conn->ops->get_cmd_val(work);
12231 	int n_vec;
12232 	char *signing_key;
12233 
12234 	hdr = ksmbd_resp_buf_curr(work);
12235 
12236 	if (command == SMB2_SESSION_SETUP_HE &&
12237 	    (!conn->binding || hdr->Status != STATUS_SUCCESS)) {
12238 		signing_key = work->sess->smb3signingkey;
12239 	} else {
12240 		chann = lookup_chann_list(work->sess, work->conn);
12241 		if (!chann) {
12242 			return;
12243 		}
12244 		signing_key = chann->smb3signingkey;
12245 	}
12246 
12247 	if (!signing_key)
12248 		return;
12249 
12250 	hdr->Flags |= SMB2_FLAGS_SIGNED;
12251 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12252 
12253 	iov = smb2_get_sign_rsp_iov(work, hdr, &n_vec);
12254 
12255 	ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature);
12256 	memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
12257 }
12258 
12259 /**
12260  * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
12261  * @work:   smb work containing response buffer
12262  *
12263  */
12264 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
12265 {
12266 	struct ksmbd_conn *conn = work->conn;
12267 	struct ksmbd_session *sess = work->sess;
12268 	struct smb2_hdr *req, *rsp;
12269 
12270 	if (conn->dialect != SMB311_PROT_ID)
12271 		return;
12272 
12273 	WORK_BUFFERS(work, req, rsp);
12274 
12275 	if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE) {
12276 		ksmbd_conn_lock(conn);
12277 		if (conn->preauth_info)
12278 			ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
12279 							 conn->preauth_info->Preauth_HashValue);
12280 		ksmbd_conn_unlock(conn);
12281 	}
12282 
12283 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
12284 		ksmbd_conn_lock(conn);
12285 
12286 		if (conn->binding) {
12287 			struct preauth_session *preauth_sess;
12288 
12289 			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
12290 			if (preauth_sess)
12291 				ksmbd_gen_preauth_integrity_hash(conn,
12292 					work->response_buf,
12293 					preauth_sess->Preauth_HashValue);
12294 		} else if (sess->Preauth_HashValue) {
12295 			ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
12296 					 sess->Preauth_HashValue);
12297 		}
12298 		ksmbd_conn_unlock(conn);
12299 	}
12300 }
12301 
12302 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
12303 {
12304 	struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
12305 	struct smb2_hdr *hdr = smb_get_msg(old_buf);
12306 	unsigned int orig_len = get_rfc1002_len(old_buf);
12307 
12308 	/* tr_buf must be cleared by the caller */
12309 	tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
12310 	tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
12311 	tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
12312 	if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
12313 	    cipher_type == SMB2_ENCRYPTION_AES256_GCM)
12314 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
12315 	else
12316 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
12317 	memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
12318 	inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
12319 	inc_rfc1001_len(tr_buf, orig_len);
12320 }
12321 
12322 int smb3_encrypt_resp(struct ksmbd_work *work)
12323 {
12324 	struct kvec *iov = work->iov;
12325 	int rc = -ENOMEM;
12326 	void *tr_buf;
12327 
12328 	tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, KSMBD_DEFAULT_GFP);
12329 	if (!tr_buf)
12330 		return rc;
12331 
12332 	/* fill transform header */
12333 	fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
12334 
12335 	iov[0].iov_base = tr_buf;
12336 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
12337 	work->tr_buf = tr_buf;
12338 
12339 	return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
12340 }
12341 
12342 bool smb3_is_transform_hdr(void *buf)
12343 {
12344 	struct smb2_transform_hdr *trhdr = smb_get_msg(buf);
12345 
12346 	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
12347 }
12348 
12349 int smb3_decrypt_req(struct ksmbd_work *work)
12350 {
12351 	char *buf = work->request_buf;
12352 	unsigned int pdu_length = get_rfc1002_len(buf);
12353 	struct kvec iov[2];
12354 	unsigned int buf_data_size;
12355 	struct smb2_transform_hdr *tr_hdr = smb_get_msg(buf);
12356 	unsigned int original_msg_size;
12357 	int rc = 0;
12358 
12359 	if (pdu_length < sizeof(struct smb2_transform_hdr)) {
12360 		pr_err("Transform message is too small (%u)\n",
12361 		       pdu_length);
12362 		return -ECONNABORTED;
12363 	}
12364 
12365 	buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
12366 	original_msg_size = le32_to_cpu(tr_hdr->OriginalMessageSize);
12367 	if (buf_data_size < sizeof(struct smb2_compression_hdr) ||
12368 	    original_msg_size < sizeof(struct smb2_compression_hdr)) {
12369 		pr_err("Transform message is too small (%u)\n",
12370 		       pdu_length);
12371 		return -ECONNABORTED;
12372 	}
12373 
12374 	if (buf_data_size < original_msg_size) {
12375 		pr_err("Transform message is broken\n");
12376 		return -ECONNABORTED;
12377 	}
12378 
12379 	iov[0].iov_base = buf;
12380 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
12381 	iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
12382 	iov[1].iov_len = buf_data_size;
12383 	rc = ksmbd_crypt_message(work, iov, 2, 0);
12384 	if (rc)
12385 		return rc;
12386 
12387 	/* Drop the AEAD authentication tag from the inner RFC1002 frame. */
12388 	memmove(buf + 4, iov[1].iov_base, original_msg_size);
12389 	*(__be32 *)buf = cpu_to_be32(original_msg_size);
12390 
12391 	return rc;
12392 }
12393 
12394 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
12395 {
12396 	struct ksmbd_conn *conn = work->conn;
12397 	struct ksmbd_session *sess = work->sess;
12398 	struct smb2_hdr *rsp = smb_get_msg(work->response_buf);
12399 
12400 	if (conn->dialect < SMB30_PROT_ID)
12401 		return false;
12402 
12403 	if (work->next_smb2_rcv_hdr_off)
12404 		rsp = ksmbd_resp_buf_next(work);
12405 
12406 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
12407 	    sess->user && !user_guest(sess->user) &&
12408 	    rsp->Status == STATUS_SUCCESS)
12409 		return true;
12410 	return false;
12411 }
12412