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