xref: /linux/fs/smb/server/smb2pdu.c (revision 206fc30f71b005156085fd8523ccc84a2c67791b)
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 		ksmbd_debug(SMB,
3458 			    "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
3459 			    eabuf->name, eabuf->EaNameLength,
3460 			    le16_to_cpu(eabuf->EaValueLength),
3461 			    le32_to_cpu(eabuf->NextEntryOffset));
3462 
3463 		if (eabuf->EaNameLength >
3464 		    (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
3465 			rc = -EINVAL;
3466 			break;
3467 		}
3468 		if (smb2_is_private_ea(eabuf->name, eabuf->EaNameLength)) {
3469 			rc = -EACCES;
3470 			break;
3471 		}
3472 
3473 		memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
3474 		memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
3475 		       eabuf->EaNameLength);
3476 		attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
3477 		value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
3478 
3479 		if (!eabuf->EaValueLength) {
3480 			rc = ksmbd_vfs_casexattr_len(idmap,
3481 						     path->dentry,
3482 						     attr_name,
3483 						     XATTR_USER_PREFIX_LEN +
3484 						     eabuf->EaNameLength, NULL);
3485 
3486 			/* delete the EA only when it exits */
3487 			if (rc > 0) {
3488 				rc = ksmbd_vfs_remove_xattr(idmap,
3489 							    path,
3490 							    attr_name,
3491 							    get_write);
3492 
3493 				if (rc < 0) {
3494 					ksmbd_debug(SMB,
3495 						    "remove xattr failed(%d)\n",
3496 						    rc);
3497 					break;
3498 				}
3499 			}
3500 
3501 			/* if the EA doesn't exist, just do nothing. */
3502 			rc = 0;
3503 		} else {
3504 			rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
3505 						le16_to_cpu(eabuf->EaValueLength),
3506 						0, get_write);
3507 			if (rc < 0) {
3508 				ksmbd_debug(SMB,
3509 					    "ksmbd_vfs_setxattr is failed(%d)\n",
3510 					    rc);
3511 				break;
3512 			}
3513 		}
3514 
3515 next:
3516 		next = le32_to_cpu(eabuf->NextEntryOffset);
3517 		if (next == 0 || buf_len < next)
3518 			break;
3519 		buf_len -= next;
3520 		eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
3521 		if (buf_len < sizeof(struct smb2_ea_info)) {
3522 			rc = -EINVAL;
3523 			break;
3524 		}
3525 
3526 		if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength + 1 +
3527 				le16_to_cpu(eabuf->EaValueLength)) {
3528 			rc = -EINVAL;
3529 			break;
3530 		}
3531 	} while (next != 0);
3532 
3533 	kfree(attr_name);
3534 	return rc;
3535 }
3536 
3537 static noinline int smb2_set_stream_name_xattr(const struct path *path,
3538 					       struct ksmbd_file *fp,
3539 					       char *stream_name, int s_type)
3540 {
3541 	const struct mnt_idmap *idmap = mnt_idmap(path->mnt);
3542 	size_t xattr_stream_size;
3543 	char *xattr_stream_name;
3544 	int rc;
3545 
3546 	rc = ksmbd_vfs_xattr_stream_name(stream_name,
3547 					 &xattr_stream_name,
3548 					 &xattr_stream_size,
3549 					 s_type);
3550 	if (rc)
3551 		return rc;
3552 
3553 	fp->stream.name = xattr_stream_name;
3554 	fp->stream.size = xattr_stream_size;
3555 
3556 	/* Keep the existing xattr's case for subsequent writes and removal. */
3557 	rc = ksmbd_vfs_casexattr_len(idmap,
3558 				     path->dentry,
3559 				     xattr_stream_name,
3560 				     xattr_stream_size, xattr_stream_name);
3561 	if (rc >= 0)
3562 		return 0;
3563 	if (rc != -ENOENT && rc != -ENODATA)
3564 		return rc;
3565 
3566 	if (fp->cdoption == FILE_OPEN_LE) {
3567 		if (!strcmp(stream_name, "AFP_AfpInfo") &&
3568 		    test_share_config_flag(fp->tcon->share_conf,
3569 					   KSMBD_SHARE_FLAG_TIME_MACHINE)) {
3570 			/*
3571 			 * Synthesize an empty AFP_AfpInfo xattr on first access.
3572 			 * type=0/creator=0 tells macOS to use the file extension
3573 			 * for icon and type detection.
3574 			 *
3575 			 * Scoped to TIME_MACHINE shares, matching the rest of
3576 			 * the AAPL series -- conn->is_aapl alone isn't a safe
3577 			 * gate here, since the pre-existing narrow UniqueId=0
3578 			 * path can also set it on ordinary, non-Time-Machine
3579 			 * shares whenever a Mac client happens to negotiate
3580 			 * AAPL there too.
3581 			 */
3582 			static const u8 afpinfo_empty[60] = {
3583 				'A', 'F', 'P', 0x00,	/* signature */
3584 				0x00, 0x00, 0x01, 0x00,	/* version */
3585 				[15] = 0x80,		/* backup time */
3586 			};
3587 			rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name,
3588 						(void *)afpinfo_empty,
3589 						sizeof(afpinfo_empty), 0, false);
3590 			return rc < 0 ? rc : 0;
3591 		}
3592 		ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
3593 		return -EBADF;
3594 	}
3595 
3596 	rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false);
3597 	if (rc < 0)
3598 		pr_err("Failed to store XATTR stream name :%d\n", rc);
3599 	return 0;
3600 }
3601 
3602 /*
3603  * fp->stream.size is the byte length of the mangled xattr *name*
3604  * (used as attr_name_len when looking the xattr up), not the size of
3605  * the xattr's value. Reporting it as EndOfFile/AllocationSize for a
3606  * stream handle is wrong -- query the xattr's actual value length
3607  * instead.
3608  */
3609 static loff_t ksmbd_stream_eof(struct ksmbd_file *fp)
3610 {
3611 	ssize_t slen = ksmbd_vfs_casexattr_len(file_mnt_idmap(fp->filp),
3612 					       fp->filp->f_path.dentry,
3613 					       fp->stream.name,
3614 					       fp->stream.size, NULL);
3615 	return slen < 0 ? 0 : (loff_t)slen;
3616 }
3617 
3618 static int smb2_remove_smb_xattrs(const struct path *path)
3619 {
3620 	const struct mnt_idmap *idmap = mnt_idmap(path->mnt);
3621 	char *name, *xattr_list = NULL;
3622 	ssize_t xattr_list_len;
3623 	int err = 0;
3624 
3625 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
3626 	if (xattr_list_len < 0) {
3627 		goto out;
3628 	} else if (!xattr_list_len) {
3629 		ksmbd_debug(SMB, "empty xattr in the file\n");
3630 		goto out;
3631 	}
3632 
3633 	for (name = xattr_list; name - xattr_list < xattr_list_len;
3634 			name += strlen(name) + 1) {
3635 		ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
3636 
3637 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
3638 		    !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
3639 			     STREAM_PREFIX_LEN)) {
3640 			err = ksmbd_vfs_remove_xattr(idmap, path,
3641 						     name, true);
3642 			if (err)
3643 				ksmbd_debug(SMB, "remove xattr failed : %s\n",
3644 					    name);
3645 		}
3646 	}
3647 out:
3648 	kvfree(xattr_list);
3649 	return err;
3650 }
3651 
3652 static int smb2_create_truncate(const struct path *path)
3653 {
3654 	int rc = vfs_truncate(path, 0);
3655 
3656 	if (rc) {
3657 		pr_err("vfs_truncate failed, rc %d\n", rc);
3658 		return rc;
3659 	}
3660 
3661 	rc = smb2_remove_smb_xattrs(path);
3662 	if (rc == -EOPNOTSUPP)
3663 		rc = 0;
3664 	if (rc)
3665 		ksmbd_debug(SMB,
3666 			    "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
3667 			    rc);
3668 	return rc;
3669 }
3670 
3671 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
3672 			    struct ksmbd_file *fp)
3673 {
3674 	struct xattr_dos_attrib da = {0};
3675 	int rc;
3676 
3677 	if (!test_share_config_flag(tcon->share_conf,
3678 				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
3679 		return;
3680 
3681 	da.version = 4;
3682 	da.attr = le32_to_cpu(fp->f_ci->m_fattr);
3683 	da.itime = da.create_time = fp->create_time;
3684 	da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
3685 		XATTR_DOSINFO_ITIME;
3686 
3687 	rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, true);
3688 	if (rc)
3689 		ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
3690 }
3691 
3692 static bool smb2_parent_compressed(struct ksmbd_tree_connect *tcon,
3693 				   const struct path *path)
3694 {
3695 	struct dentry *parent = dget_parent(path->dentry);
3696 	struct file_kattr fa = { .flags_valid = true };
3697 	struct xattr_dos_attrib da;
3698 	bool compressed = false;
3699 	int rc;
3700 
3701 	rc = vfs_fileattr_get(parent, &fa);
3702 	if (!rc && fa.flags & FS_COMPR_FL) {
3703 		compressed = true;
3704 		goto out;
3705 	}
3706 
3707 	rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt), parent, &da);
3708 	if (rc > 0 && da.attr & FILE_ATTRIBUTE_COMPRESSED)
3709 		compressed = true;
3710 
3711 out:
3712 	dput(parent);
3713 	return compressed;
3714 }
3715 
3716 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
3717 			       const struct path *path, struct ksmbd_file *fp)
3718 {
3719 	struct xattr_dos_attrib da = {};
3720 	bool store_dos_attrs = test_share_config_flag(tcon->share_conf,
3721 						      KSMBD_SHARE_FLAG_STORE_DOS_ATTRS);
3722 	int rc;
3723 
3724 	fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
3725 
3726 	/* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
3727 	rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
3728 					    path->dentry, &da);
3729 	if (rc > 0) {
3730 		if (store_dos_attrs) {
3731 			fp->f_ci->m_fattr = cpu_to_le32(da.attr);
3732 			fp->create_time = da.create_time;
3733 			fp->itime = da.itime;
3734 		} else {
3735 			fp->f_ci->m_fattr &=
3736 				~(FILE_ATTRIBUTE_COMPRESSED_LE |
3737 				  FILE_ATTRIBUTE_SPARSE_FILE_LE);
3738 			fp->f_ci->m_fattr |=
3739 				cpu_to_le32(da.attr &
3740 					    (FILE_ATTRIBUTE_COMPRESSED |
3741 					     FILE_ATTRIBUTE_SPARSE_FILE));
3742 		}
3743 	}
3744 }
3745 
3746 static int smb2_creat(struct ksmbd_work *work,
3747 		      struct path *path, char *name, int open_flags,
3748 		      umode_t posix_mode, bool is_dir)
3749 {
3750 	struct ksmbd_tree_connect *tcon = work->tcon;
3751 	struct ksmbd_share_config *share = tcon->share_conf;
3752 	umode_t mode;
3753 	int rc;
3754 
3755 	if (!(open_flags & O_CREAT))
3756 		return -EBADF;
3757 
3758 	ksmbd_debug(SMB, "file does not exist, so creating\n");
3759 	if (is_dir == true) {
3760 		ksmbd_debug(SMB, "creating directory\n");
3761 
3762 		mode = share_config_directory_mode(share, posix_mode);
3763 		rc = ksmbd_vfs_mkdir(work, name, mode);
3764 		if (rc)
3765 			return rc;
3766 	} else {
3767 		ksmbd_debug(SMB, "creating regular file\n");
3768 
3769 		mode = share_config_create_mode(share, posix_mode);
3770 		rc = ksmbd_vfs_create(work, name, mode);
3771 		if (rc)
3772 			return rc;
3773 	}
3774 
3775 	rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
3776 	if (rc) {
3777 		pr_err("cannot get linux path (%s), err = %d\n",
3778 		       name, rc);
3779 		return rc;
3780 	}
3781 	return 0;
3782 }
3783 
3784 static int smb2_create_sd_buffer(struct ksmbd_work *work,
3785 				 struct smb2_create_req *req,
3786 				 const struct path *path)
3787 {
3788 	struct create_context *context;
3789 	struct create_sd_buf_req *sd_buf;
3790 
3791 	if (!req->CreateContextsOffset)
3792 		return -ENOENT;
3793 
3794 	/* Parse SD BUFFER create contexts */
3795 	context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
3796 	if (!context)
3797 		return -ENOENT;
3798 	else if (IS_ERR(context))
3799 		return PTR_ERR(context);
3800 
3801 	ksmbd_debug(SMB,
3802 		    "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
3803 	sd_buf = (struct create_sd_buf_req *)context;
3804 	if (le16_to_cpu(context->DataOffset) +
3805 	    le32_to_cpu(context->DataLength) <
3806 	    sizeof(struct create_sd_buf_req))
3807 		return -EINVAL;
3808 	return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
3809 			    le32_to_cpu(sd_buf->ccontext.DataLength), true, false,
3810 			    true, true);
3811 }
3812 
3813 static int ksmbd_acls_fattr(struct smb_fattr *fattr,
3814 			    const struct mnt_idmap *idmap,
3815 			    struct inode *inode)
3816 {
3817 	struct posix_acl *acl;
3818 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
3819 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
3820 
3821 	fattr->cf_uid = vfsuid_into_kuid(vfsuid);
3822 	fattr->cf_gid = vfsgid_into_kgid(vfsgid);
3823 	fattr->cf_mode = inode->i_mode;
3824 	fattr->cf_acls = NULL;
3825 	fattr->cf_dacls = NULL;
3826 
3827 	if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
3828 		acl = get_inode_acl(inode, ACL_TYPE_ACCESS);
3829 		if (IS_ERR(acl)) {
3830 			if (acl != ERR_PTR(-EOPNOTSUPP))
3831 				return PTR_ERR(acl);
3832 			acl = NULL;
3833 		}
3834 		fattr->cf_acls = acl;
3835 
3836 		if (S_ISDIR(inode->i_mode)) {
3837 			acl = get_inode_acl(inode, ACL_TYPE_DEFAULT);
3838 			if (IS_ERR(acl)) {
3839 				if (acl != ERR_PTR(-EOPNOTSUPP)) {
3840 					posix_acl_release(fattr->cf_acls);
3841 					return PTR_ERR(acl);
3842 				}
3843 				acl = NULL;
3844 			}
3845 			fattr->cf_dacls = acl;
3846 		}
3847 	}
3848 
3849 	return 0;
3850 }
3851 
3852 enum {
3853 	DURABLE_RECONN_V2 = 1,
3854 	DURABLE_RECONN,
3855 	DURABLE_REQ_V2,
3856 	DURABLE_REQ,
3857 };
3858 
3859 struct durable_info {
3860 	struct ksmbd_file *fp;
3861 	unsigned short int type;
3862 	bool persistent;
3863 	bool reconnected;
3864 	bool replay;
3865 	bool replay_consumed;
3866 	bool app_instance_id;
3867 	bool app_instance_version_valid;
3868 	unsigned int timeout;
3869 	char *CreateGuid;
3870 	char AppInstanceId[SMB2_CREATE_GUID_SIZE];
3871 	u64 app_instance_version_high;
3872 	u64 app_instance_version_low;
3873 };
3874 
3875 static int smb2_check_durable_replay(struct ksmbd_work *work,
3876 				     struct ksmbd_file *fp,
3877 				     struct lease_ctx_info *lc,
3878 				     bool persistent)
3879 {
3880 	struct oplock_info *opinfo;
3881 	int ret = 0;
3882 
3883 	if (!fp->conn && !fp->is_durable && !fp->is_persistent)
3884 		return -EACCES;
3885 
3886 	if (ksmbd_vfs_compare_durable_owner(fp, work->sess->user) == false)
3887 		return -EACCES;
3888 
3889 	if (fp->is_persistent && !persistent)
3890 		return -EINVAL;
3891 
3892 	opinfo = opinfo_get(fp);
3893 	if (!opinfo)
3894 		return 0;
3895 
3896 	if (opinfo->is_lease) {
3897 		if (!lc ||
3898 		    memcmp(opinfo->o_lease->lease_key, lc->lease_key,
3899 			   SMB2_LEASE_KEY_SIZE)) {
3900 			ret = -EACCES;
3901 			goto out;
3902 		}
3903 	} else {
3904 		if (lc) {
3905 			ret = -EACCES;
3906 			goto out;
3907 		}
3908 
3909 		/* A live CREATE replay may follow a completed oplock break. */
3910 		if (!fp->conn && fp->is_durable &&
3911 		    opinfo->level != SMB2_OPLOCK_LEVEL_BATCH)
3912 			ret = -EACCES;
3913 	}
3914 out:
3915 	opinfo_put(opinfo);
3916 	return ret;
3917 }
3918 
3919 static bool smb2_durable_replay_consumed(struct ksmbd_file *fp)
3920 {
3921 	bool consumed;
3922 
3923 	spin_lock(&fp->f_lock);
3924 	consumed = fp->durable_replay_consumed;
3925 	spin_unlock(&fp->f_lock);
3926 
3927 	return consumed;
3928 }
3929 
3930 static void smb2_mark_durable_replay_consumed(struct ksmbd_file *fp)
3931 {
3932 	spin_lock(&fp->f_lock);
3933 	fp->durable_replay_consumed = true;
3934 	spin_unlock(&fp->f_lock);
3935 }
3936 
3937 static bool smb2_durable_replay_differs(struct ksmbd_file *fp,
3938 					struct smb2_create_req *req)
3939 {
3940 	return fp->cdoption != req->CreateDisposition ||
3941 		fp->create_file_attributes != req->FileAttributes;
3942 }
3943 
3944 static int parse_durable_handle_context(struct ksmbd_work *work,
3945 					struct smb2_create_req *req,
3946 					struct lease_ctx_info *lc,
3947 					struct durable_info *dh_info)
3948 {
3949 	struct ksmbd_conn *conn = work->conn;
3950 	struct create_context *context;
3951 	int dh_idx, err = 0;
3952 	u64 persistent_id = 0;
3953 	int req_op_level;
3954 	static const char * const durable_arr[] = {"DH2C", "DHnC", "DH2Q", "DHnQ"};
3955 
3956 	req_op_level = req->RequestedOplockLevel;
3957 	for (dh_idx = DURABLE_RECONN_V2; dh_idx <= ARRAY_SIZE(durable_arr);
3958 	     dh_idx++) {
3959 		context = smb2_find_context_vals(req, durable_arr[dh_idx - 1], 4);
3960 		if (IS_ERR(context)) {
3961 			err = PTR_ERR(context);
3962 			goto out;
3963 		}
3964 		if (!context)
3965 			continue;
3966 
3967 		switch (dh_idx) {
3968 		case DURABLE_RECONN_V2:
3969 		{
3970 			struct create_durable_handle_reconnect_v2 *recon_v2;
3971 			u32 flags;
3972 
3973 			if (dh_info->type == DURABLE_RECONN ||
3974 			    dh_info->type == DURABLE_REQ_V2) {
3975 				err = -EINVAL;
3976 				goto out;
3977 			}
3978 
3979 			if (le32_to_cpu(context->DataLength) <
3980 			    sizeof(recon_v2->dcontext)) {
3981 				err = -EINVAL;
3982 				goto out;
3983 			}
3984 
3985 			recon_v2 = (struct create_durable_handle_reconnect_v2 *)context;
3986 			flags = le32_to_cpu(recon_v2->dcontext.Flags);
3987 			if (flags & ~SMB2_DHANDLE_FLAG_PERSISTENT) {
3988 				err = -EINVAL;
3989 				goto out;
3990 			}
3991 			dh_info->persistent = flags & SMB2_DHANDLE_FLAG_PERSISTENT;
3992 			persistent_id = recon_v2->dcontext.Fid.PersistentFileId;
3993 			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
3994 			if (!dh_info->fp) {
3995 				ksmbd_debug(SMB, "Failed to get durable handle state\n");
3996 				err = -EBADF;
3997 				goto out;
3998 			}
3999 
4000 			/* A zero VolatileFileId means that the client did not specify it. */
4001 			if (recon_v2->dcontext.Fid.VolatileFileId &&
4002 			    dh_info->fp->durable_volatile_id !=
4003 			    recon_v2->dcontext.Fid.VolatileFileId) {
4004 				err = -EBADF;
4005 				ksmbd_put_durable_fd(dh_info->fp);
4006 				goto out;
4007 			}
4008 
4009 			if (memcmp(dh_info->fp->create_guid, recon_v2->dcontext.CreateGuid,
4010 				   SMB2_CREATE_GUID_SIZE)) {
4011 				err = -EBADF;
4012 				ksmbd_put_durable_fd(dh_info->fp);
4013 				goto out;
4014 			}
4015 
4016 			/* A persistent reconnect must match the original open type. */
4017 			if (dh_info->fp->is_persistent != dh_info->persistent) {
4018 				err = dh_info->persistent ? -EINVAL : -EBADF;
4019 				ksmbd_put_durable_fd(dh_info->fp);
4020 				goto out;
4021 			}
4022 
4023 			dh_info->type = dh_idx;
4024 			dh_info->reconnected = true;
4025 			ksmbd_debug(SMB,
4026 				"reconnect v2 Persistent-id from reconnect = %llu\n",
4027 					persistent_id);
4028 			break;
4029 		}
4030 		case DURABLE_RECONN:
4031 		{
4032 			create_durable_reconn_t *recon;
4033 
4034 			if (dh_info->type == DURABLE_RECONN_V2 ||
4035 			    dh_info->type == DURABLE_REQ_V2) {
4036 				err = -EINVAL;
4037 				goto out;
4038 			}
4039 
4040 			if (le32_to_cpu(context->DataLength) <
4041 			    sizeof(recon->Data)) {
4042 				err = -EINVAL;
4043 				goto out;
4044 			}
4045 
4046 			recon = (create_durable_reconn_t *)context;
4047 			persistent_id = recon->Data.Fid.PersistentFileId;
4048 			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
4049 			if (!dh_info->fp) {
4050 				ksmbd_debug(SMB, "Failed to get durable handle state\n");
4051 				err = -EBADF;
4052 				goto out;
4053 			}
4054 
4055 			/* A zero VolatileFileId means that the client did not specify it. */
4056 			if (recon->Data.Fid.VolatileFileId &&
4057 			    dh_info->fp->durable_volatile_id !=
4058 			    recon->Data.Fid.VolatileFileId) {
4059 				err = -EBADF;
4060 				ksmbd_put_durable_fd(dh_info->fp);
4061 				goto out;
4062 			}
4063 
4064 			dh_info->type = dh_idx;
4065 			dh_info->reconnected = true;
4066 			ksmbd_debug(SMB, "reconnect Persistent-id from reconnect = %llu\n",
4067 				    persistent_id);
4068 			break;
4069 		}
4070 		case DURABLE_REQ_V2:
4071 		{
4072 			struct create_durable_req_v2 *durable_v2_blob;
4073 
4074 			if (dh_info->type == DURABLE_RECONN ||
4075 			    dh_info->type == DURABLE_RECONN_V2) {
4076 				err = -EINVAL;
4077 				goto out;
4078 			}
4079 
4080 			if (le32_to_cpu(context->DataLength) <
4081 			    sizeof(durable_v2_blob->dcontext)) {
4082 				err = -EINVAL;
4083 				goto out;
4084 			}
4085 
4086 			durable_v2_blob =
4087 				(struct create_durable_req_v2 *)context;
4088 			if (le32_to_cpu(durable_v2_blob->dcontext.Flags) &
4089 			    ~SMB2_DHANDLE_FLAG_PERSISTENT) {
4090 				err = -EINVAL;
4091 				goto out;
4092 			}
4093 			ksmbd_debug(SMB, "Request for durable v2 open\n");
4094 			dh_info->CreateGuid = durable_v2_blob->dcontext.CreateGuid;
4095 			dh_info->persistent =
4096 				le32_to_cpu(durable_v2_blob->dcontext.Flags) &
4097 				SMB2_DHANDLE_FLAG_PERSISTENT;
4098 			dh_info->fp = ksmbd_lookup_fd_cguid(durable_v2_blob->dcontext.CreateGuid);
4099 			if (dh_info->fp) {
4100 				if (!memcmp(conn->ClientGUID, dh_info->fp->client_guid,
4101 					    SMB2_CLIENT_GUID_SIZE)) {
4102 					if (!(req->hdr.Flags & SMB2_FLAGS_REPLAY_OPERATION)) {
4103 						err = -ENOEXEC;
4104 						ksmbd_put_durable_fd(dh_info->fp);
4105 						goto out;
4106 					}
4107 
4108 					if (dh_info->fp->f_state == FP_NEW) {
4109 						/* Original CREATE is still pending. */
4110 						ksmbd_put_durable_fd(dh_info->fp);
4111 						err = -EAGAIN;
4112 						goto out;
4113 					}
4114 
4115 					err = smb2_check_durable_replay(work,
4116 									dh_info->fp,
4117 									lc,
4118 									dh_info->persistent);
4119 					if (err) {
4120 						ksmbd_put_durable_fd(dh_info->fp);
4121 						goto out;
4122 					}
4123 
4124 					err = ksmbd_rebind_replay_fd(work, dh_info->fp);
4125 					if (err) {
4126 						ksmbd_put_durable_fd(dh_info->fp);
4127 						goto out;
4128 					}
4129 
4130 					if (dh_info->fp->conn &&
4131 					    smb2_durable_replay_consumed(dh_info->fp)) {
4132 						ksmbd_put_durable_fd(dh_info->fp);
4133 						dh_info->fp = NULL;
4134 						dh_info->type = dh_idx;
4135 						dh_info->replay_consumed = true;
4136 						break;
4137 					}
4138 
4139 					if (dh_info->fp->conn) {
4140 						if (smb2_durable_replay_differs(dh_info->fp,
4141 									       req))
4142 							smb2_mark_durable_replay_consumed(
4143 									dh_info->fp);
4144 						dh_info->replay = true;
4145 					} else {
4146 						dh_info->reconnected = true;
4147 					}
4148 					dh_info->type = dh_idx;
4149 					goto out;
4150 				}
4151 				ksmbd_put_durable_fd(dh_info->fp);
4152 				dh_info->fp = NULL;
4153 			}
4154 
4155 			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
4156 			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
4157 				dh_info->timeout =
4158 					le32_to_cpu(durable_v2_blob->dcontext.Timeout);
4159 				dh_info->type = dh_idx;
4160 			}
4161 			break;
4162 		}
4163 		case DURABLE_REQ:
4164 			if (dh_info->type == DURABLE_RECONN)
4165 				goto out;
4166 			if (dh_info->type == DURABLE_RECONN_V2 ||
4167 			    dh_info->type == DURABLE_REQ_V2) {
4168 				err = -EINVAL;
4169 				goto out;
4170 			}
4171 
4172 			if ((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
4173 			    req_op_level == SMB2_OPLOCK_LEVEL_BATCH) {
4174 				ksmbd_debug(SMB, "Request for durable open\n");
4175 				dh_info->type = dh_idx;
4176 			}
4177 		}
4178 	}
4179 
4180 out:
4181 	return err;
4182 }
4183 
4184 static int parse_app_instance_id(struct smb2_create_req *req,
4185 				 struct durable_info *dh_info)
4186 {
4187 	struct create_context *context;
4188 	char *data;
4189 
4190 	context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_ID,
4191 					 SMB2_CREATE_GUID_SIZE);
4192 	if (IS_ERR(context))
4193 		return PTR_ERR(context);
4194 	if (!context)
4195 		return 0;
4196 
4197 	if (le32_to_cpu(context->DataLength) < 20)
4198 		return -EINVAL;
4199 
4200 	data = (char *)context + le16_to_cpu(context->DataOffset);
4201 	if (data[0] != 20 || data[1])
4202 		return -EINVAL;
4203 
4204 	memcpy(dh_info->AppInstanceId, data + 4, SMB2_CREATE_GUID_SIZE);
4205 	dh_info->app_instance_id = true;
4206 	return 0;
4207 }
4208 
4209 static int parse_app_instance_version(struct smb2_create_req *req,
4210 				      struct durable_info *dh_info)
4211 {
4212 	struct create_context *context;
4213 	char *data;
4214 
4215 	context = smb2_find_context_vals(req, SMB2_CREATE_APP_INSTANCE_VERSION,
4216 					 SMB2_CREATE_GUID_SIZE);
4217 	if (IS_ERR(context))
4218 		return PTR_ERR(context);
4219 	if (!context)
4220 		return 0;
4221 
4222 	if (le32_to_cpu(context->DataLength) < 24)
4223 		return -EINVAL;
4224 
4225 	data = (char *)context + le16_to_cpu(context->DataOffset);
4226 	if (get_unaligned_le16(data) != 24 ||
4227 	    get_unaligned_le16(data + 2) != 0)
4228 		return -EINVAL;
4229 
4230 	dh_info->app_instance_version_high = get_unaligned_le64(data + 8);
4231 	dh_info->app_instance_version_low = get_unaligned_le64(data + 16);
4232 	dh_info->app_instance_version_valid = true;
4233 	return 0;
4234 }
4235 
4236 static int smb2_app_instance_stream_matches(struct ksmbd_file *fp,
4237 					    char *stream_name, int s_type,
4238 					    bool *matches)
4239 {
4240 	char *xattr_stream_name;
4241 	size_t xattr_stream_size;
4242 	int rc;
4243 
4244 	if (!stream_name) {
4245 		*matches = !ksmbd_stream_fd(fp);
4246 		return 0;
4247 	}
4248 
4249 	rc = ksmbd_vfs_xattr_stream_name(stream_name, &xattr_stream_name,
4250 					 &xattr_stream_size, s_type);
4251 	if (rc)
4252 		return rc;
4253 
4254 	*matches = fp->stream.name && fp->stream.size >= 0 &&
4255 		   (size_t)fp->stream.size == xattr_stream_size &&
4256 		   !strncasecmp(fp->stream.name, xattr_stream_name,
4257 				xattr_stream_size);
4258 	kfree(xattr_stream_name);
4259 	return 0;
4260 }
4261 
4262 static int smb2_handle_app_instance_id(struct ksmbd_work *work,
4263 				       struct smb2_create_rsp *rsp,
4264 				       struct durable_info *dh_info,
4265 				       const struct path *path,
4266 				       char *stream_name, int s_type,
4267 				       bool *closed)
4268 {
4269 	struct ksmbd_conn *conn = work->conn;
4270 	struct ksmbd_file *old_fp;
4271 	const struct path *old_path;
4272 	char *app_instance_id;
4273 	__le32 maximal_access = FILE_MAXIMAL_ACCESS_LE;
4274 	bool reject = false, stream_matches;
4275 	int cursor = 0, rc;
4276 
4277 	*closed = false;
4278 	if (!dh_info->app_instance_id)
4279 		return 0;
4280 	app_instance_id = dh_info->AppInstanceId;
4281 
4282 	while (true) {
4283 		old_fp = ksmbd_lookup_fd_app_instance_id_next(app_instance_id,
4284 							      &cursor);
4285 		if (!old_fp)
4286 			return 0;
4287 
4288 		if (!ksmbd_app_instance_id_matches(work, old_fp) ||
4289 		    !path_equal(&old_fp->filp->f_path, path)) {
4290 			ksmbd_put_durable_fd(old_fp);
4291 			continue;
4292 		}
4293 
4294 		rc = smb2_app_instance_stream_matches(old_fp, stream_name,
4295 						      s_type, &stream_matches);
4296 		if (rc) {
4297 			ksmbd_put_durable_fd(old_fp);
4298 			return rc;
4299 		}
4300 		if (!stream_matches) {
4301 			ksmbd_put_durable_fd(old_fp);
4302 			continue;
4303 		}
4304 		break;
4305 	}
4306 
4307 	if (dh_info->app_instance_version_valid) {
4308 		if (old_fp->app_instance_version_valid &&
4309 		    (dh_info->app_instance_version_high <
4310 			 old_fp->app_instance_version_high ||
4311 		     (dh_info->app_instance_version_high ==
4312 			      old_fp->app_instance_version_high &&
4313 			      dh_info->app_instance_version_low <=
4314 			      old_fp->app_instance_version_low)))
4315 			reject = true;
4316 	} else if (old_fp->app_instance_version_valid) {
4317 		reject = true;
4318 	}
4319 
4320 	if (reject) {
4321 		ksmbd_put_durable_fd(old_fp);
4322 		rsp->hdr.Status = STATUS_FILE_FORCED_CLOSED;
4323 		return -EIO;
4324 	}
4325 
4326 	/* Authorize the referenced open even if its name changes meanwhile. */
4327 	old_path = &old_fp->filp->f_path;
4328 	rc = smb_check_perm_dacl(conn, old_path, &maximal_access, 0,
4329 				 work->sess->user->uid, false);
4330 	if (rc) {
4331 		/* Access denial prevents takeover, not the CREATE itself. */
4332 		ksmbd_put_durable_fd(old_fp);
4333 		return rc == -EACCES ? 0 : rc;
4334 	}
4335 	if (maximal_access == FILE_MAXIMAL_ACCESS_LE)
4336 		ksmbd_vfs_query_maximal_access(mnt_idmap(old_path->mnt),
4337 					       old_path->dentry, &maximal_access);
4338 	/* Also require read access with the effective VFS credentials. */
4339 	if ((le32_to_cpu(maximal_access) & GENERIC_READ_FLAGS) !=
4340 	    GENERIC_READ_FLAGS ||
4341 	    inode_permission(mnt_idmap(old_path->mnt),
4342 			     d_inode(old_path->dentry), MAY_OPEN | MAY_READ)) {
4343 		ksmbd_put_durable_fd(old_fp);
4344 		return 0;
4345 	}
4346 
4347 	return ksmbd_close_fd_app_instance_id(work, old_fp, closed);
4348 }
4349 
4350 /**
4351  * smb2_open() - handler for smb file open request
4352  * @work:	smb work containing request buffer
4353  *
4354  * Return:      0 on success, otherwise error
4355  */
4356 int smb2_open(struct ksmbd_work *work)
4357 {
4358 	struct ksmbd_conn *conn = work->conn;
4359 	struct ksmbd_session *sess = work->sess;
4360 	struct ksmbd_tree_connect *tcon = work->tcon;
4361 	struct smb2_create_req *req;
4362 	struct smb2_create_rsp *rsp;
4363 	struct path path;
4364 	struct ksmbd_share_config *share = tcon->share_conf;
4365 	struct ksmbd_file *fp = NULL;
4366 	struct file *filp = NULL;
4367 	const struct mnt_idmap *idmap = NULL;
4368 	struct kstat stat;
4369 	struct create_context *context;
4370 	struct lease_ctx_info *lc = NULL;
4371 	struct create_ea_buf_req *ea_buf = NULL;
4372 	struct oplock_info *opinfo;
4373 	struct durable_info dh_info = {0};
4374 	__le32 *next_ptr = NULL;
4375 	int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
4376 	int rc = 0;
4377 	int contxt_cnt = 0, query_disk_id = 0;
4378 	bool maximal_access_ctxt = false, posix_ctxt = false;
4379 	bool aapl_ctxt = false;
4380 	bool durable_rsp = true;
4381 	__u64 aapl_req_bitmap = 0, aapl_client_caps = 0;
4382 	int s_type = 0;
4383 	int next_off = 0;
4384 	char *name = NULL;
4385 	char *stream_name = NULL;
4386 	bool file_present = false, created = false, already_permitted = false;
4387 	bool app_instance_id_checked = false, app_instance_closed;
4388 	int share_ret, need_truncate = 0;
4389 	u64 time, alloc_size = 0;
4390 	umode_t posix_mode = 0;
4391 	__le32 daccess, maximal_access = 0;
4392 	u32 dos_attr;
4393 	int iov_len = 0;
4394 
4395 	ksmbd_debug(SMB, "Received smb2 create request\n");
4396 
4397 	WORK_BUFFERS(work, req, rsp);
4398 
4399 	if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
4400 	    (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
4401 		ksmbd_debug(SMB, "invalid flag in chained command\n");
4402 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4403 		smb2_set_err_rsp(work);
4404 		return -EINVAL;
4405 	}
4406 
4407 	if (req->CreateContextsOffset) {
4408 		context = smb2_find_context_vals(req, SMB2_CREATE_TAG_POSIX, 16);
4409 		if (IS_ERR(context)) {
4410 			rc = PTR_ERR(context);
4411 			goto err_out2;
4412 		} else if (context) {
4413 			struct create_posix *posix = (struct create_posix *)context;
4414 
4415 			if (conn->dialect != SMB311_PROT_ID) {
4416 				rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4417 				rc = -ENOTTY;
4418 				goto err_out2;
4419 			}
4420 			if (!tcon->posix_extensions) {
4421 				rc = -EOPNOTSUPP;
4422 				goto err_out2;
4423 			}
4424 			if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
4425 				rc = -EOPNOTSUPP;
4426 				goto err_out2;
4427 			}
4428 			if (le16_to_cpu(context->DataOffset) +
4429 				le32_to_cpu(context->DataLength) <
4430 			    sizeof(struct create_posix) - 4) {
4431 				rc = -EINVAL;
4432 				goto err_out2;
4433 			}
4434 			ksmbd_debug(SMB, "get posix context\n");
4435 
4436 			posix_mode = le32_to_cpu(posix->Mode);
4437 			posix_ctxt = true;
4438 		}
4439 	}
4440 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
4441 		ksmbd_debug(SMB, "IPC pipe create request\n");
4442 		return create_smb2_pipe(work);
4443 	}
4444 
4445 	if (req->NameLength) {
4446 		name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset),
4447 				     le16_to_cpu(req->NameLength),
4448 				     work->conn->local_nls);
4449 		if (IS_ERR(name)) {
4450 			rc = PTR_ERR(name);
4451 			name = NULL;
4452 			goto err_out2;
4453 		}
4454 
4455 		ksmbd_debug(SMB, "converted name = %s\n", name);
4456 
4457 		if (posix_ctxt == false) {
4458 			if (strchr(name, ':')) {
4459 				if (!test_share_config_flag(work->tcon->share_conf,
4460 							KSMBD_SHARE_FLAG_STREAMS)) {
4461 					rc = -EBADF;
4462 					goto err_out2;
4463 				}
4464 				rc = parse_stream_name(name, &stream_name, &s_type);
4465 				if (rc < 0)
4466 					goto err_out2;
4467 			}
4468 
4469 			rc = ksmbd_validate_filename(name);
4470 			if (rc < 0)
4471 				goto err_out2;
4472 		}
4473 
4474 		if (ksmbd_share_veto_filename(share, name)) {
4475 			rc = -ENOENT;
4476 			ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
4477 				    name);
4478 			goto err_out2;
4479 		}
4480 	} else {
4481 		name = kstrdup("", KSMBD_DEFAULT_GFP);
4482 		if (!name) {
4483 			rc = -ENOMEM;
4484 			goto err_out2;
4485 		}
4486 	}
4487 
4488 	req_op_level = req->RequestedOplockLevel;
4489 
4490 	if (req->CreateContextsOffset) {
4491 		rc = parse_app_instance_id(req, &dh_info);
4492 		if (rc)
4493 			goto err_out2;
4494 		rc = parse_app_instance_version(req, &dh_info);
4495 		if (rc)
4496 			goto err_out2;
4497 	}
4498 
4499 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
4500 	    req->CreateContextsOffset) {
4501 		lc = parse_lease_state(req);
4502 		if (IS_ERR(lc)) {
4503 			rc = PTR_ERR(lc);
4504 			lc = NULL;
4505 			goto err_out2;
4506 		}
4507 		if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
4508 			kfree(lc);
4509 			lc = NULL;
4510 			if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
4511 				req_op_level = SMB2_OPLOCK_LEVEL_NONE;
4512 		}
4513 		rc = parse_durable_handle_context(work, req, lc, &dh_info);
4514 		if (rc) {
4515 			ksmbd_debug(SMB, "error parsing durable handle context\n");
4516 			goto err_out2;
4517 		}
4518 
4519 		if (dh_info.replay == true) {
4520 			fp = dh_info.fp;
4521 			if (ksmbd_override_fsids(work)) {
4522 				rc = -ENOMEM;
4523 				goto err_out2;
4524 			}
4525 
4526 			file_info = FILE_OPENED;
4527 			rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
4528 			if (rc)
4529 				goto err_out2;
4530 
4531 			goto reconnected_fp;
4532 		}
4533 
4534 		if (dh_info.reconnected == true) {
4535 			rc = smb2_check_durable_oplock(conn, share, dh_info.fp,
4536 					lc, sess->user, name);
4537 			if (rc)
4538 				goto err_out2;
4539 
4540 			rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
4541 			if (rc) {
4542 				if (rc == -ENOTCONN)
4543 					rsp->hdr.Status =
4544 						STATUS_NETWORK_NAME_DELETED;
4545 				goto err_out2;
4546 			}
4547 
4548 			fp = dh_info.fp;
4549 
4550 			if (ksmbd_override_fsids(work)) {
4551 				rc = -ENOMEM;
4552 				goto err_out2;
4553 			}
4554 
4555 			file_info = FILE_OPENED;
4556 
4557 			rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
4558 			if (rc)
4559 				goto err_out2;
4560 
4561 			goto reconnected_fp;
4562 		}
4563 
4564 	} else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
4565 		lc = parse_lease_state(req);
4566 		if (IS_ERR(lc)) {
4567 			rc = PTR_ERR(lc);
4568 			lc = NULL;
4569 			goto err_out2;
4570 		}
4571 		if (lc && lc->version == 2 && conn->dialect < SMB30_PROT_ID) {
4572 			kfree(lc);
4573 			lc = NULL;
4574 			req_op_level = SMB2_OPLOCK_LEVEL_NONE;
4575 		}
4576 	}
4577 
4578 	if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
4579 		pr_err("Invalid impersonationlevel : 0x%x\n",
4580 		       le32_to_cpu(req->ImpersonationLevel));
4581 		rc = -EIO;
4582 		rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
4583 		goto err_out2;
4584 	}
4585 
4586 	if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
4587 		pr_err("Invalid create options : 0x%x\n",
4588 		       le32_to_cpu(req->CreateOptions));
4589 		rc = -EINVAL;
4590 		goto err_out2;
4591 	} else {
4592 		if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
4593 		    req->CreateOptions & FILE_RANDOM_ACCESS_LE)
4594 			req->CreateOptions &= ~FILE_SEQUENTIAL_ONLY_LE;
4595 
4596 		if (req->CreateOptions &
4597 		    (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
4598 		     FILE_RESERVE_OPFILTER_LE)) {
4599 			rc = -EOPNOTSUPP;
4600 			goto err_out2;
4601 		}
4602 
4603 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
4604 			if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
4605 				rc = -EINVAL;
4606 				goto err_out2;
4607 			}
4608 		}
4609 	}
4610 
4611 	if (le32_to_cpu(req->CreateDisposition) >
4612 	    le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
4613 		pr_err("Invalid create disposition : 0x%x\n",
4614 		       le32_to_cpu(req->CreateDisposition));
4615 		rc = -EINVAL;
4616 		goto err_out2;
4617 	}
4618 
4619 	if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
4620 		pr_err("Invalid desired access : 0x%x\n",
4621 		       le32_to_cpu(req->DesiredAccess));
4622 		rc = -EACCES;
4623 		goto err_out2;
4624 	}
4625 
4626 	if (req->DesiredAccess == FILE_SYNCHRONIZE_LE &&
4627 	    req->CreateDisposition == FILE_OPEN_IF_LE &&
4628 	    !req->FileAttributes) {
4629 		rc = -EACCES;
4630 		goto err_out2;
4631 	}
4632 
4633 	if (req->FileAttributes &&
4634 	    (req->FileAttributes & ~cpu_to_le32(SMB2_CREATE_FILE_ATTRIBUTE_MASK))) {
4635 		pr_err("Invalid file attribute : 0x%x\n",
4636 		       le32_to_cpu(req->FileAttributes));
4637 		rc = -EINVAL;
4638 		goto err_out2;
4639 	}
4640 
4641 	if (req->CreateContextsOffset) {
4642 		/* Parse non-durable handle create contexts */
4643 		context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
4644 		if (IS_ERR(context)) {
4645 			rc = PTR_ERR(context);
4646 			goto err_out2;
4647 		} else if (context) {
4648 			ea_buf = (struct create_ea_buf_req *)context;
4649 			if (le16_to_cpu(context->DataOffset) +
4650 			    le32_to_cpu(context->DataLength) <
4651 			    sizeof(struct create_ea_buf_req)) {
4652 				rc = -EINVAL;
4653 				goto err_out2;
4654 			}
4655 			if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
4656 				rsp->hdr.Status = STATUS_ACCESS_DENIED;
4657 				rc = -EACCES;
4658 				goto err_out2;
4659 			}
4660 		}
4661 
4662 		context = smb2_find_context_vals(req,
4663 						 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
4664 		if (IS_ERR(context)) {
4665 			rc = PTR_ERR(context);
4666 			goto err_out2;
4667 		} else if (context) {
4668 			ksmbd_debug(SMB,
4669 				    "get query maximal access context\n");
4670 			maximal_access_ctxt = 1;
4671 		}
4672 
4673 		context = smb2_find_context_vals(req,
4674 						 SMB2_CREATE_TIMEWARP_REQUEST, 4);
4675 		if (IS_ERR(context)) {
4676 			rc = PTR_ERR(context);
4677 			goto err_out2;
4678 		} else if (context) {
4679 			ksmbd_debug(SMB, "get timewarp context\n");
4680 			rc = -EBADF;
4681 			goto err_out2;
4682 		}
4683 	}
4684 
4685 	if (ksmbd_override_fsids(work)) {
4686 		rc = -ENOMEM;
4687 		goto err_out2;
4688 	}
4689 
4690 resolve_path:
4691 	file_present = false;
4692 	maximal_access = 0;
4693 	rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
4694 				 &path, 1);
4695 
4696 	/* Validate takeover before disconnected delete-on-close cleanup. */
4697 	if (!rc && dh_info.app_instance_id && !dh_info.reconnected &&
4698 	    !dh_info.replay && !app_instance_id_checked) {
4699 		app_instance_id_checked = true;
4700 		rc = smb2_handle_app_instance_id(work, rsp, &dh_info, &path,
4701 						 stream_name, s_type,
4702 						 &app_instance_closed);
4703 		if (rc) {
4704 			path_put(&path);
4705 			goto err_out1;
4706 		}
4707 		if (app_instance_closed) {
4708 			path_put(&path);
4709 			goto resolve_path;
4710 		}
4711 	}
4712 
4713 	/*
4714 	 * A durable handle opened with delete-on-close is preserved across a
4715 	 * disconnect so it can be reclaimed by a durable reconnect.  When a new
4716 	 * delete-on-close open for the same name arrives instead, the
4717 	 * disconnected handle must give way: close it so its delete-on-close
4718 	 * removes the file, then re-resolve so this open can create a fresh one.
4719 	 */
4720 	if (!rc && (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) &&
4721 	    (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
4722 	     req->CreateDisposition == FILE_OPEN_IF_LE) &&
4723 	    ksmbd_close_disconnected_durable_delete_on_close(path.dentry)) {
4724 		path_put(&path);
4725 		rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
4726 					 &path, 1);
4727 	}
4728 
4729 	if (!rc) {
4730 		file_present = true;
4731 
4732 		if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
4733 			struct xattr_dos_attrib da;
4734 
4735 			/*
4736 			 * If file exists with under flags, return access
4737 			 * denied error.
4738 			 */
4739 			if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
4740 			    req->CreateDisposition == FILE_OPEN_IF_LE) {
4741 				rc = -EACCES;
4742 				goto err_out;
4743 			}
4744 
4745 			if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
4746 				ksmbd_debug(SMB,
4747 					    "User does not have write permission\n");
4748 					rc = -EACCES;
4749 					goto err_out;
4750 				}
4751 
4752 			if (test_share_config_flag(tcon->share_conf,
4753 						   KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
4754 			    ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path.mnt),
4755 							 path.dentry, &da) > 0 &&
4756 			    da.attr & FILE_ATTRIBUTE_READONLY) {
4757 				rsp->hdr.Status = STATUS_CANNOT_DELETE;
4758 				rc = -EACCES;
4759 				goto err_out;
4760 			}
4761 		} else if (d_is_symlink(path.dentry)) {
4762 			rc = -EACCES;
4763 			goto err_out;
4764 		}
4765 
4766 		idmap = mnt_idmap(path.mnt);
4767 	} else {
4768 		if (rc != -ENOENT)
4769 			goto err_out;
4770 		ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
4771 			    name, rc);
4772 		rc = 0;
4773 	}
4774 
4775 	if (!file_present && req->CreateOptions & FILE_DELETE_ON_CLOSE_LE &&
4776 	    req->FileAttributes & FILE_ATTRIBUTE_READONLY_LE) {
4777 		rsp->hdr.Status = STATUS_CANNOT_DELETE;
4778 		rc = -EACCES;
4779 		goto err_out;
4780 	}
4781 
4782 	/*
4783 	 * An explicit ::$DATA suffix names the unnamed data stream and is
4784 	 * canonicalized to a NULL stream name (base file), but the request
4785 	 * still has to be validated against the data-stream type, e.g. opening
4786 	 * <dir>::$DATA with FILE_DIRECTORY_FILE must fail with
4787 	 * STATUS_NOT_A_DIRECTORY.
4788 	 */
4789 	if (stream_name || s_type == DATA_STREAM) {
4790 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
4791 			if (s_type == DATA_STREAM) {
4792 				rc = -EIO;
4793 				rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
4794 			}
4795 		} else {
4796 			if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
4797 			    !stream_name && s_type == DATA_STREAM) {
4798 				rc = -EIO;
4799 				rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
4800 			}
4801 		}
4802 
4803 		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
4804 		    req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
4805 			rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
4806 			rc = -EIO;
4807 		}
4808 
4809 		if (rc < 0)
4810 			goto err_out;
4811 	}
4812 
4813 	if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
4814 	    S_ISDIR(d_inode(path.dentry)->i_mode) &&
4815 	    !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
4816 		ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
4817 			    name, req->CreateOptions);
4818 		rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
4819 		rc = -EIO;
4820 		goto err_out;
4821 	}
4822 
4823 	if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
4824 	    !(req->CreateDisposition == FILE_CREATE_LE) &&
4825 	    !S_ISDIR(d_inode(path.dentry)->i_mode)) {
4826 		rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
4827 		rc = -EIO;
4828 		goto err_out;
4829 	}
4830 
4831 	if (!stream_name && file_present &&
4832 	    req->CreateDisposition == FILE_CREATE_LE) {
4833 		rc = -EEXIST;
4834 		goto err_out;
4835 	}
4836 
4837 	daccess = smb_map_generic_desired_access(req->DesiredAccess);
4838 
4839 	if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
4840 		rc = smb_check_perm_dacl(conn, &path, &daccess,
4841 					 req->DesiredAccess,
4842 					 sess->user->uid, false);
4843 		if (rc)
4844 			goto err_out;
4845 
4846 		if (maximal_access_ctxt) {
4847 			maximal_access = FILE_MAXIMAL_ACCESS_LE;
4848 			rc = smb_check_perm_dacl(conn, &path, &maximal_access,
4849 						 0, sess->user->uid, false);
4850 			if (rc)
4851 				goto err_out;
4852 
4853 			/*
4854 			 * smb_check_perm_dacl() returns success without
4855 			 * touching *pdaccess when the object has no stored
4856 			 * NT ACL, leaving maximal_access as the
4857 			 * FILE_MAXIMAL_ACCESS_LE request sentinel instead of
4858 			 * a real access mask.
4859 			 */
4860 			if (maximal_access == FILE_MAXIMAL_ACCESS_LE)
4861 				ksmbd_vfs_query_maximal_access(idmap, path.dentry,
4862 							       &maximal_access);
4863 		}
4864 	}
4865 
4866 	if (daccess & FILE_MAXIMAL_ACCESS_LE) {
4867 		if (!file_present) {
4868 			daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
4869 		} else {
4870 			ksmbd_vfs_query_maximal_access(idmap,
4871 							    path.dentry,
4872 							    &daccess);
4873 			already_permitted = true;
4874 		}
4875 		maximal_access = daccess;
4876 	}
4877 
4878 	open_flags = smb2_create_open_flags(file_present, daccess,
4879 					    req->CreateDisposition,
4880 					    &may_flags,
4881 					    req->CreateOptions,
4882 					    file_present ? d_inode(path.dentry)->i_mode : 0);
4883 	if (posix_ctxt && (req->DesiredAccess & FILE_APPEND_DATA_LE) &&
4884 	    !(req->DesiredAccess & FILE_WRITE_DATA_LE))
4885 		open_flags |= O_APPEND;
4886 
4887 	if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
4888 		if (open_flags & (O_CREAT | O_TRUNC)) {
4889 			ksmbd_debug(SMB,
4890 				    "User does not have write permission\n");
4891 			rc = -EACCES;
4892 			goto err_out;
4893 		}
4894 	}
4895 
4896 	/*create file if not present */
4897 	if (!file_present) {
4898 		rc = smb2_creat(work, &path, name, open_flags,
4899 				posix_ctxt ? posix_mode : (umode_t)-1,
4900 				req->CreateOptions & FILE_DIRECTORY_FILE_LE);
4901 		if (rc) {
4902 			if (rc == -ENOENT) {
4903 				rc = -EIO;
4904 				rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
4905 			}
4906 			goto err_out;
4907 		}
4908 
4909 		created = true;
4910 		idmap = mnt_idmap(path.mnt);
4911 		if (ea_buf) {
4912 			if (le32_to_cpu(ea_buf->ccontext.DataLength) <
4913 			    sizeof(struct smb2_ea_info)) {
4914 				rc = -EINVAL;
4915 				goto err_out;
4916 			}
4917 
4918 			rc = smb2_set_ea(&ea_buf->ea,
4919 					 le32_to_cpu(ea_buf->ccontext.DataLength),
4920 					 &path, false);
4921 			if (rc == -EOPNOTSUPP)
4922 				rc = 0;
4923 			else if (rc)
4924 				goto err_out;
4925 		}
4926 	} else if (!already_permitted) {
4927 		/* FILE_READ_ATTRIBUTE is allowed without inode_permission,
4928 		 * because execute(search) permission on a parent directory,
4929 		 * is already granted.
4930 		 */
4931 		if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
4932 			rc = inode_permission(idmap,
4933 					      d_inode(path.dentry),
4934 					      may_flags);
4935 			if (rc)
4936 				goto err_out;
4937 
4938 			if ((daccess & FILE_DELETE_LE) ||
4939 			    (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
4940 				rc = inode_permission(idmap,
4941 						      d_inode(path.dentry->d_parent),
4942 						      MAY_EXEC | MAY_WRITE);
4943 				if (rc)
4944 					goto err_out;
4945 			}
4946 		}
4947 	}
4948 
4949 	rc = ksmbd_query_inode_status(path.dentry->d_parent);
4950 	if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
4951 		rc = -EBUSY;
4952 		goto err_out;
4953 	}
4954 
4955 	rc = 0;
4956 	filp = dentry_open(&path, open_flags, current_cred());
4957 	if (IS_ERR(filp)) {
4958 		rc = PTR_ERR(filp);
4959 		pr_err("dentry open for dir failed, rc %d\n", rc);
4960 		goto err_out;
4961 	}
4962 
4963 	if (file_present) {
4964 		if (!(open_flags & O_TRUNC))
4965 			file_info = FILE_OPENED;
4966 		else
4967 			file_info = FILE_OVERWRITTEN;
4968 
4969 		if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
4970 		    FILE_SUPERSEDE_LE)
4971 			file_info = FILE_SUPERSEDED;
4972 	} else if (open_flags & O_CREAT) {
4973 		file_info = FILE_CREATED;
4974 	}
4975 
4976 	ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
4977 
4978 	/* Obtain Volatile-ID */
4979 	fp = ksmbd_open_fd(work, filp);
4980 	if (IS_ERR(fp)) {
4981 		fput(filp);
4982 		rc = PTR_ERR(fp);
4983 		if (rc == -ENOTCONN)
4984 			rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
4985 		fp = NULL;
4986 		goto err_out;
4987 	}
4988 
4989 	/* Get Persistent-ID */
4990 	ksmbd_open_durable_fd(fp);
4991 	if (!has_file_id(fp->persistent_id)) {
4992 		rc = -ENOMEM;
4993 		goto err_out;
4994 	}
4995 
4996 	/*
4997 	 * Publish the client and create GUID before an oplock/lease break can
4998 	 * make this CREATE pending.  A replay of that in-flight CREATE must find
4999 	 * this FP_NEW handle and fail with STATUS_FILE_NOT_AVAILABLE instead of
5000 	 * waiting on the same break again.
5001 	 */
5002 	memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
5003 	if (dh_info.app_instance_id) {
5004 		memcpy(fp->app_instance_id, dh_info.AppInstanceId,
5005 		       SMB2_CREATE_GUID_SIZE);
5006 		fp->has_app_instance_id = true;
5007 	}
5008 	if (dh_info.app_instance_version_valid) {
5009 		fp->app_instance_version_high =
5010 			dh_info.app_instance_version_high;
5011 		fp->app_instance_version_low = dh_info.app_instance_version_low;
5012 		fp->app_instance_version_valid = true;
5013 	}
5014 	if (dh_info.CreateGuid) {
5015 		memcpy(fp->create_guid, dh_info.CreateGuid, SMB2_CREATE_GUID_SIZE);
5016 		fp->durable_replay_consumed = dh_info.replay_consumed;
5017 		rc = ksmbd_vfs_set_durable_owner(fp, sess->user);
5018 		if (rc)
5019 			goto err_out;
5020 	}
5021 
5022 	fp->cdoption = req->CreateDisposition;
5023 	fp->create_file_attributes = req->FileAttributes;
5024 	fp->daccess = daccess;
5025 	fp->saccess = req->ShareAccess;
5026 	fp->coption = req->CreateOptions;
5027 
5028 	/* Set default windows and posix acls if creating new file */
5029 	if (created) {
5030 		int posix_acl_rc;
5031 		struct inode *inode = d_inode(path.dentry);
5032 
5033 		posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
5034 							   &path,
5035 							   d_inode(path.dentry->d_parent));
5036 		if (posix_acl_rc)
5037 			ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
5038 
5039 		rc = smb2_create_sd_buffer(work, req, &path);
5040 		if (rc && rc != -ENOENT)
5041 			goto err_out;
5042 
5043 		if (rc == -ENOENT) {
5044 			if (test_share_config_flag(work->tcon->share_conf,
5045 						   KSMBD_SHARE_FLAG_ACL_XATTR)) {
5046 				rc = smb_inherit_dacl(conn, &path, sess->user->uid,
5047 						      sess->user->gid);
5048 			}
5049 			if (rc) {
5050 				if (posix_acl_rc)
5051 					ksmbd_vfs_set_init_posix_acl(idmap,
5052 								     &path);
5053 
5054 				if (test_share_config_flag(work->tcon->share_conf,
5055 							   KSMBD_SHARE_FLAG_ACL_XATTR)) {
5056 					struct smb_fattr fattr;
5057 					struct smb_ntsd *pntsd;
5058 					int pntsd_size;
5059 					size_t scratch_len;
5060 
5061 					rc = ksmbd_acls_fattr(&fattr, idmap, inode);
5062 					if (rc)
5063 						goto err_out;
5064 
5065 					scratch_len = smb_acl_sec_desc_scratch_len(&fattr,
5066 							NULL, 0,
5067 							OWNER_SECINFO | GROUP_SECINFO |
5068 							DACL_SECINFO);
5069 					if (!scratch_len || scratch_len == SIZE_MAX) {
5070 						rc = -EFBIG;
5071 						posix_acl_release(fattr.cf_acls);
5072 						posix_acl_release(fattr.cf_dacls);
5073 						goto err_out;
5074 					}
5075 
5076 					pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
5077 					if (!pntsd) {
5078 						rc = -ENOMEM;
5079 						posix_acl_release(fattr.cf_acls);
5080 						posix_acl_release(fattr.cf_dacls);
5081 						goto err_out;
5082 					}
5083 
5084 					rc = build_sec_desc(idmap,
5085 							    pntsd, NULL, 0,
5086 							    OWNER_SECINFO |
5087 							    GROUP_SECINFO |
5088 							    DACL_SECINFO,
5089 							    &pntsd_size, &fattr);
5090 					posix_acl_release(fattr.cf_acls);
5091 					posix_acl_release(fattr.cf_dacls);
5092 					if (rc) {
5093 						kvfree(pntsd);
5094 						goto err_out;
5095 					}
5096 
5097 					rc = ksmbd_vfs_set_sd_xattr(conn,
5098 								    idmap,
5099 								    &path,
5100 								    pntsd,
5101 								    pntsd_size,
5102 								    false);
5103 					kvfree(pntsd);
5104 					if (rc)
5105 						pr_err("failed to store ntacl in xattr : %d\n",
5106 						       rc);
5107 				}
5108 			}
5109 		}
5110 		rc = 0;
5111 	}
5112 
5113 	if (stream_name) {
5114 		rc = smb2_set_stream_name_xattr(&path,
5115 						fp,
5116 						stream_name,
5117 						s_type);
5118 		if (rc)
5119 			goto err_out;
5120 		file_info = FILE_CREATED;
5121 	}
5122 
5123 	fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
5124 			FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
5125 
5126 	fp->is_posix_ctxt = posix_ctxt;
5127 	fp->posix_append = posix_ctxt && !!(open_flags & O_APPEND);
5128 
5129 	/* fp should be searchable through ksmbd_inode.m_fp_list
5130 	 * after daccess, saccess, attrib_only, and stream are
5131 	 * initialized.
5132 	 */
5133 	down_write(&fp->f_ci->m_lock);
5134 	list_add(&fp->node, &fp->f_ci->m_fp_list);
5135 	up_write(&fp->f_ci->m_lock);
5136 
5137 	/* Check delete pending among previous fp before oplock break */
5138 	if (ksmbd_inode_pending_delete(fp)) {
5139 		rc = -EBUSY;
5140 		goto err_out;
5141 	}
5142 
5143 	if (!stream_name && daccess & FILE_DELETE_LE &&
5144 	    ksmbd_has_stream_without_delete_share(fp)) {
5145 		rc = -EPERM;
5146 		goto err_out;
5147 	}
5148 
5149 	if (file_present || created)
5150 		path_put(&path);
5151 
5152 	if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
5153 	    !fp->attrib_only && !stream_name) {
5154 		smb_break_all_oplock(work, fp);
5155 		need_truncate = 1;
5156 	}
5157 
5158 	share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
5159 	if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
5160 	    (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
5161 	     !(conn->vals->req_capabilities & SMB2_GLOBAL_CAP_LEASING))) {
5162 		if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
5163 			rc = share_ret;
5164 			goto err_out1;
5165 		}
5166 	} else {
5167 		if (created && !lc)
5168 			smb_send_parent_lease_break_noti(fp, NULL);
5169 
5170 		if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE && lc) {
5171 			if (S_ISDIR(file_inode(filp)->i_mode)) {
5172 				lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
5173 				lc->is_dir = true;
5174 			}
5175 
5176 			/*
5177 			 * Compare parent lease using parent key. If there is no
5178 			 * a lease that has same parent key, Send lease break
5179 			 * notification.
5180 			 */
5181 			smb_send_parent_lease_break_noti(fp, lc);
5182 
5183 			req_op_level = smb2_map_lease_to_oplock(lc->req_state);
5184 			ksmbd_debug(SMB,
5185 				    "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
5186 				    name, req_op_level, lc->req_state);
5187 			rc = find_same_lease_key(conn, fp->f_ci, lc);
5188 			if (rc)
5189 				goto err_out1;
5190 		} else if (open_flags == O_RDONLY &&
5191 			   (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
5192 			    req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
5193 			req_op_level = SMB2_OPLOCK_LEVEL_II;
5194 
5195 		rc = smb_grant_oplock(work, req_op_level,
5196 				      fp->persistent_id, fp,
5197 				      le32_to_cpu(req->hdr.Id.SyncId.TreeId),
5198 				      lc, share_ret,
5199 				      smb3_hdr_replay(&req->hdr));
5200 		if (rc < 0)
5201 			goto err_out1;
5202 	}
5203 
5204 	if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
5205 		smb_break_all_levII_oplock_for_delete(work, fp);
5206 		ksmbd_fd_set_delete_on_close(fp, file_info);
5207 	}
5208 
5209 	if (need_truncate) {
5210 		rc = smb2_create_truncate(&fp->filp->f_path);
5211 		if (rc)
5212 			goto err_out1;
5213 	}
5214 
5215 	if (req->CreateContextsOffset) {
5216 		struct create_alloc_size_req *az_req;
5217 
5218 		az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
5219 					SMB2_CREATE_ALLOCATION_SIZE, 4);
5220 		if (IS_ERR(az_req)) {
5221 			rc = PTR_ERR(az_req);
5222 			goto err_out1;
5223 		} else if (az_req) {
5224 			int err;
5225 
5226 			if (le16_to_cpu(az_req->ccontext.DataOffset) +
5227 			    le32_to_cpu(az_req->ccontext.DataLength) <
5228 			    sizeof(struct create_alloc_size_req)) {
5229 				rc = -EINVAL;
5230 				goto err_out1;
5231 			}
5232 			alloc_size = le64_to_cpu(az_req->AllocationSize);
5233 			fp->allocation_size_set = true;
5234 			ksmbd_debug(SMB,
5235 				    "request smb2 create allocate size : %llu\n",
5236 				    alloc_size);
5237 			/*
5238 			 * fp->filp is the base file's data fork for a stream
5239 			 * handle (streams are xattr-backed on the same
5240 			 * underlying file) -- fallocate has no meaning for a
5241 			 * stream and would otherwise pre-allocate storage on
5242 			 * the base file's data instead.
5243 			 */
5244 			if (!ksmbd_stream_fd(fp)) {
5245 				smb_break_all_levII_oplock(work, fp, 1);
5246 				err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5247 						    alloc_size);
5248 				if (err < 0)
5249 					ksmbd_debug(SMB,
5250 						    "vfs_fallocate is failed : %d\n",
5251 						    err);
5252 			}
5253 		}
5254 
5255 		context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
5256 		if (IS_ERR(context)) {
5257 			rc = PTR_ERR(context);
5258 			goto err_out1;
5259 		} else if (context) {
5260 			ksmbd_debug(SMB, "get query on disk id context\n");
5261 			query_disk_id = 1;
5262 		}
5263 
5264 		if (test_share_config_flag(share, KSMBD_SHARE_FLAG_TIME_MACHINE)) {
5265 			context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
5266 			if (IS_ERR(context)) {
5267 				rc = PTR_ERR(context);
5268 				goto err_out1;
5269 			} else if (context) {
5270 				struct aapl_server_query_req *aapl_req;
5271 
5272 				if (le32_to_cpu(context->DataLength) <
5273 				    sizeof(struct aapl_server_query_req)) {
5274 					rc = -EINVAL;
5275 					goto err_out1;
5276 				}
5277 
5278 				aapl_req = (struct aapl_server_query_req *)
5279 					((char *)context +
5280 					 le16_to_cpu(context->DataOffset));
5281 				if (le32_to_cpu(aapl_req->cmd) ==
5282 				    SMB2_CRTCTX_AAPL_SERVER_QUERY) {
5283 					conn->is_aapl = true;
5284 					aapl_ctxt = true;
5285 					aapl_req_bitmap = le64_to_cpu(aapl_req->req_bitmap);
5286 					aapl_client_caps = le64_to_cpu(aapl_req->client_caps);
5287 				}
5288 			}
5289 		} else if (conn->is_aapl == false) {
5290 			context = smb2_find_context_vals(req, SMB2_CREATE_AAPL, 4);
5291 			if (IS_ERR(context)) {
5292 				rc = PTR_ERR(context);
5293 				goto err_out1;
5294 			} else if (context)
5295 				conn->is_aapl = true;
5296 		}
5297 	}
5298 
5299 	rc = ksmbd_vfs_getattr(&path, &stat);
5300 	if (rc)
5301 		goto err_out1;
5302 
5303 	if (stat.result_mask & STATX_BTIME)
5304 		fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
5305 	else
5306 		fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
5307 	fp->change_time = ksmbd_UnixTimeToNT(stat.ctime);
5308 	fp->allocation_size = S_ISDIR(stat.mode) ? 0 :
5309 		(alloc_size ?: stat.blocks << 9);
5310 	if (created || fp->f_ci->m_fattr == 0)
5311 		fp->f_ci->m_fattr =
5312 			cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
5313 
5314 	if (!created)
5315 		smb2_update_xattrs(tcon, &path, fp);
5316 	if (need_truncate && req->FileAttributes) {
5317 		dos_attr = le32_to_cpu(req->FileAttributes);
5318 		fp->f_ci->m_fattr =
5319 			cpu_to_le32(smb2_get_dos_mode(&stat, dos_attr));
5320 		smb2_new_xattrs(tcon, &path, fp);
5321 	}
5322 
5323 	ksmbd_vfs_update_compressed_fattr(path.dentry, &fp->f_ci->m_fattr);
5324 
5325 	if (created) {
5326 		if (fp->coption & FILE_NO_COMPRESSION_LE) {
5327 			rc = ksmbd_vfs_set_compression_create(work, fp,
5328 							      COMPRESSION_FORMAT_NONE);
5329 			if (rc)
5330 				fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_COMPRESSED_LE;
5331 			rc = 0;
5332 		} else if (smb2_parent_compressed(tcon, &path)) {
5333 			rc = ksmbd_vfs_set_compression_create(work, fp,
5334 							      COMPRESSION_FORMAT_LZNT1);
5335 			if (rc)
5336 				fp->f_ci->m_fattr |= FILE_ATTRIBUTE_COMPRESSED_LE;
5337 			rc = 0;
5338 		}
5339 	}
5340 
5341 	if (created)
5342 		smb2_new_xattrs(tcon, &path, fp);
5343 
5344 	fp->create_action = cpu_to_le32(file_info);
5345 
5346 	if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
5347 		if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent &&
5348 		    test_share_config_flag(work->tcon->share_conf,
5349 					   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY) &&
5350 		    (conn->vals->req_capabilities &
5351 			     SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)) {
5352 			/* MS-SMB2 3.3.5.9.10: a persistent open is durable too. */
5353 			fp->is_durable = true;
5354 			fp->is_persistent = true;
5355 		} else {
5356 			fp->is_durable = true;
5357 		}
5358 		if (dh_info.type == DURABLE_REQ_V2) {
5359 			if (dh_info.app_instance_id)
5360 				memcpy(fp->app_instance_id,
5361 				       dh_info.AppInstanceId,
5362 				       SMB2_CREATE_GUID_SIZE);
5363 			if (dh_info.timeout)
5364 				fp->durable_timeout =
5365 					min_t(unsigned int, dh_info.timeout,
5366 					      DURABLE_HANDLE_MAX_TIMEOUT);
5367 			else
5368 				fp->durable_timeout = 60000;
5369 		}
5370 	}
5371 
5372 	/*
5373 	 * conn->is_aapl detection above (this function's create-context
5374 	 * parsing) is skipped on the reconnect path below, since a
5375 	 * reconnect always arrives on a fresh connection -- if the client
5376 	 * cares, it sends its own AAPL context on this same CREATE, which
5377 	 * this function's normal (non-reconnect) parsing already handles.
5378 	 */
5379 	reconnected_fp:
5380 	if (dh_info.replay)
5381 		file_info = le32_to_cpu(fp->create_action);
5382 	rsp->StructureSize = cpu_to_le16(89);
5383 	opinfo = opinfo_get(fp);
5384 	rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
5385 	/*
5386 	 * A durable CREATE replay does not modify the existing open. When
5387 	 * replayed without an oplock, however, its response reflects that
5388 	 * request and cannot include a new durable-handle response context.
5389 	 */
5390 	if (dh_info.replay && !lc &&
5391 	    req_op_level == SMB2_OPLOCK_LEVEL_NONE) {
5392 		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
5393 		durable_rsp = false;
5394 	}
5395 	rsp->Flags = 0;
5396 	rsp->CreateAction = cpu_to_le32(file_info);
5397 	rsp->CreationTime = cpu_to_le64(fp->create_time);
5398 	time = ksmbd_UnixTimeToNT(stat.atime);
5399 	rsp->LastAccessTime = cpu_to_le64(time);
5400 	time = ksmbd_UnixTimeToNT(stat.mtime);
5401 	fp->open_mtime = time;
5402 	rsp->LastWriteTime = cpu_to_le64(time);
5403 	rsp->ChangeTime = cpu_to_le64(fp->change_time);
5404 	/*
5405 	 * The cached allocation size hides filesystem rounding for the
5406 	 * requested allocation, but it can go stale when the file grows past
5407 	 * it via writes (e.g. across a durable reconnect). Refresh it once the
5408 	 * file exceeds the cached value, rounding the end of file up to the
5409 	 * volume allocation unit (the filesystem block size, matching the
5410 	 * SectorsPerAllocationUnit/BytesPerSector ksmbd advertises) rather than
5411 	 * using the raw on-disk block count, which can include filesystem
5412 	 * preallocation and metadata rounding.
5413 	 */
5414 	if (ksmbd_stream_fd(fp)) {
5415 		loff_t seof = ksmbd_stream_eof(fp);
5416 
5417 		rsp->AllocationSize = cpu_to_le64((u64)seof);
5418 		rsp->EndofFile = cpu_to_le64((u64)seof);
5419 	} else {
5420 		if (!S_ISDIR(stat.mode) && stat.size > fp->allocation_size)
5421 			fp->allocation_size = round_up(stat.size, stat.blksize);
5422 		rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
5423 		rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5424 	}
5425 	rsp->FileAttributes = fp->f_ci->m_fattr;
5426 
5427 	rsp->Reserved2 = 0;
5428 
5429 	rsp->PersistentFileId = fp->persistent_id;
5430 	rsp->VolatileFileId = fp->volatile_id;
5431 
5432 	rsp->CreateContextsOffset = 0;
5433 	rsp->CreateContextsLength = 0;
5434 	iov_len = offsetof(struct smb2_create_rsp, Buffer);
5435 
5436 	/* If lease is request send lease context response */
5437 	if (opinfo && opinfo->is_lease) {
5438 		struct create_context *lease_ccontext;
5439 
5440 		ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
5441 			    name, opinfo->o_lease->state);
5442 		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
5443 
5444 		lease_ccontext = (struct create_context *)rsp->Buffer;
5445 		contxt_cnt++;
5446 		create_lease_buf(rsp->Buffer, opinfo->o_lease);
5447 		le32_add_cpu(&rsp->CreateContextsLength,
5448 			     conn->vals->create_lease_size);
5449 		iov_len += conn->vals->create_lease_size;
5450 		next_ptr = &lease_ccontext->Next;
5451 		next_off = conn->vals->create_lease_size;
5452 	}
5453 	opinfo_put(opinfo);
5454 
5455 	if (maximal_access_ctxt) {
5456 		struct create_context *mxac_ccontext;
5457 
5458 		if (maximal_access == 0)
5459 			ksmbd_vfs_query_maximal_access(idmap,
5460 						       path.dentry,
5461 						       &maximal_access);
5462 		mxac_ccontext = (struct create_context *)(rsp->Buffer +
5463 				le32_to_cpu(rsp->CreateContextsLength));
5464 		contxt_cnt++;
5465 		create_mxac_rsp_buf(rsp->Buffer +
5466 				le32_to_cpu(rsp->CreateContextsLength),
5467 				le32_to_cpu(maximal_access));
5468 		le32_add_cpu(&rsp->CreateContextsLength,
5469 			     conn->vals->create_mxac_size);
5470 		iov_len += conn->vals->create_mxac_size;
5471 		if (next_ptr)
5472 			*next_ptr = cpu_to_le32(next_off);
5473 		next_ptr = &mxac_ccontext->Next;
5474 		next_off = conn->vals->create_mxac_size;
5475 	}
5476 
5477 	if (query_disk_id) {
5478 		struct create_context *disk_id_ccontext;
5479 
5480 		disk_id_ccontext = (struct create_context *)(rsp->Buffer +
5481 				le32_to_cpu(rsp->CreateContextsLength));
5482 		contxt_cnt++;
5483 		create_disk_id_rsp_buf(rsp->Buffer +
5484 				le32_to_cpu(rsp->CreateContextsLength),
5485 				stat.ino, tcon->id);
5486 		le32_add_cpu(&rsp->CreateContextsLength,
5487 			     conn->vals->create_disk_id_size);
5488 		iov_len += conn->vals->create_disk_id_size;
5489 		if (next_ptr)
5490 			*next_ptr = cpu_to_le32(next_off);
5491 		next_ptr = &disk_id_ccontext->Next;
5492 		next_off = conn->vals->create_disk_id_size;
5493 	}
5494 
5495 	if (durable_rsp &&
5496 	    (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2)) {
5497 		struct create_context *durable_ccontext;
5498 
5499 		durable_ccontext = (struct create_context *)(rsp->Buffer +
5500 				le32_to_cpu(rsp->CreateContextsLength));
5501 		contxt_cnt++;
5502 		if (dh_info.type == DURABLE_REQ) {
5503 			create_durable_rsp_buf(rsp->Buffer +
5504 					le32_to_cpu(rsp->CreateContextsLength));
5505 			le32_add_cpu(&rsp->CreateContextsLength,
5506 					conn->vals->create_durable_size);
5507 			iov_len += conn->vals->create_durable_size;
5508 		} else {
5509 			create_durable_v2_rsp_buf(rsp->Buffer +
5510 					le32_to_cpu(rsp->CreateContextsLength),
5511 					fp);
5512 			le32_add_cpu(&rsp->CreateContextsLength,
5513 					conn->vals->create_durable_v2_size);
5514 			iov_len += conn->vals->create_durable_v2_size;
5515 		}
5516 
5517 		if (next_ptr)
5518 			*next_ptr = cpu_to_le32(next_off);
5519 		next_ptr = &durable_ccontext->Next;
5520 		next_off = dh_info.type == DURABLE_REQ ?
5521 			conn->vals->create_durable_size :
5522 			conn->vals->create_durable_v2_size;
5523 	}
5524 
5525 	if (posix_ctxt) {
5526 		struct create_context *posix_ccontext;
5527 
5528 		posix_ccontext = (struct create_context *)(rsp->Buffer +
5529 				le32_to_cpu(rsp->CreateContextsLength));
5530 		contxt_cnt++;
5531 		create_posix_rsp_buf(rsp->Buffer +
5532 				le32_to_cpu(rsp->CreateContextsLength),
5533 				fp);
5534 		le32_add_cpu(&rsp->CreateContextsLength,
5535 			     conn->vals->create_posix_size);
5536 		iov_len += conn->vals->create_posix_size;
5537 		if (next_ptr)
5538 			*next_ptr = cpu_to_le32(next_off);
5539 		next_ptr = &posix_ccontext->Next;
5540 		next_off = conn->vals->create_posix_size;
5541 	}
5542 
5543 	/*
5544 	 * AAPL create context response: see smb2pdu.h for the capability
5545 	 * rationale. Scoped to TIME_MACHINE shares only.
5546 	 */
5547 	if (aapl_ctxt) {
5548 		if (aapl_client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR)
5549 			conn->aapl_readdir_attr = true;
5550 		/*
5551 		 * V2 extends the same inline-FinderInfo mechanism (see
5552 		 * smb2pdu.h), so a V2-requesting client also gets
5553 		 * aapl_readdir_attr treatment -- the reply just advertises
5554 		 * the V2 bit instead of the V1 one (create_aapl_rsp_buf).
5555 		 */
5556 		if (aapl_client_caps & SMB2_CRTCTX_AAPL_SUPPORTS_READ_DIR_ATTR_V2) {
5557 			conn->aapl_readdir_attr = true;
5558 			conn->aapl_readdir_attr_v2 = true;
5559 		}
5560 
5561 		contxt_cnt++;
5562 		create_aapl_rsp_buf(rsp->Buffer +
5563 				le32_to_cpu(rsp->CreateContextsLength),
5564 				SMB2_CRTCTX_AAPL_FULL_SYNC,
5565 				aapl_req_bitmap,
5566 				conn->aapl_readdir_attr_v2);
5567 		le32_add_cpu(&rsp->CreateContextsLength,
5568 			     conn->vals->create_aapl_size);
5569 		iov_len += conn->vals->create_aapl_size;
5570 		if (next_ptr)
5571 			*next_ptr = cpu_to_le32(next_off);
5572 		/* AAPL is last; next_ptr need not be updated */
5573 	}
5574 
5575 	if (contxt_cnt > 0) {
5576 		rsp->CreateContextsOffset =
5577 			cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
5578 	}
5579 
5580 err_out:
5581 	if (rc && (file_present || created))
5582 		path_put(&path);
5583 
5584 err_out1:
5585 	ksmbd_revert_fsids(work);
5586 
5587 err_out2:
5588 	if (!rc) {
5589 		if (!dh_info.replay) {
5590 			smb2_complete_request_open(work);
5591 			rc = ksmbd_update_fstate(&work->sess->file_table, fp,
5592 						 FP_INITED);
5593 			if (rc == -ENOENT)
5594 				rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
5595 			if (!rc) {
5596 				work->request_open = fp;
5597 				work->request_open_chseq =
5598 					smb3_hdr_channel_sequence(&req->hdr);
5599 			}
5600 		} else {
5601 			rc = smb2_set_request_open(work, fp, &req->hdr, false, false);
5602 		}
5603 		if (!rc)
5604 			rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
5605 	}
5606 	if (rc) {
5607 		if (rc == -EINVAL)
5608 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5609 		else if (rc == -EOPNOTSUPP)
5610 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
5611 		else if ((rc == -EACCES || rc == -ESTALE || rc == -EXDEV) &&
5612 			 !rsp->hdr.Status) {
5613 			if (req->DesiredAccess & FILE_ACCESS_SYSTEM_SECURITY_LE)
5614 				rsp->hdr.Status = STATUS_PRIVILEGE_NOT_HELD;
5615 			else
5616 				rsp->hdr.Status = STATUS_ACCESS_DENIED;
5617 		} else if (rc == -ENOENT && !rsp->hdr.Status)
5618 			rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
5619 		else if (rc == -EPERM)
5620 			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
5621 		else if (rc == -EBUSY)
5622 			rsp->hdr.Status = STATUS_DELETE_PENDING;
5623 		else if (rc == -EBADF)
5624 			rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
5625 		else if (rc == -ENOEXEC)
5626 			rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
5627 		else if (rc == -ENXIO)
5628 			rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
5629 		else if (rc == -EEXIST)
5630 			rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
5631 		else if (rc == -EMFILE)
5632 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5633 		else if (rc == -EINPROGRESS)
5634 			rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
5635 		else if (rc == -EAGAIN)
5636 			rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
5637 		if (!rsp->hdr.Status)
5638 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5639 
5640 		if (fp && !dh_info.replay) {
5641 			if (work->request_open == fp) {
5642 				ksmbd_close_fd(work, fp->volatile_id);
5643 				smb2_complete_request_open(work);
5644 			} else {
5645 				if (dh_info.reconnected && fp == dh_info.fp)
5646 					ksmbd_unpublish_reopened_fd(work, fp);
5647 				ksmbd_fd_put(work, fp);
5648 			}
5649 		}
5650 		smb2_set_err_rsp(work);
5651 		ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
5652 	}
5653 
5654 	if (dh_info.replay)
5655 		ksmbd_put_durable_fd(dh_info.fp);
5656 
5657 	if (dh_info.reconnected) {
5658 		/*
5659 		 * If reconnect succeeded, fp was republished in the
5660 		 * session file table, and the error path above has
5661 		 * already removed its volatile id.  Drop the durable
5662 		 * lookup reference through the same session-aware path.
5663 		 */
5664 		if (rc && fp == dh_info.fp)
5665 			ksmbd_fd_put(work, dh_info.fp);
5666 		else
5667 			ksmbd_put_durable_fd(dh_info.fp);
5668 	}
5669 
5670 	kfree(name);
5671 	kfree(lc);
5672 
5673 	return rc;
5674 }
5675 
5676 static int readdir_info_level_struct_sz(int info_level)
5677 {
5678 	switch (info_level) {
5679 	case FILE_FULL_DIRECTORY_INFORMATION:
5680 		return sizeof(FILE_FULL_DIRECTORY_INFO);
5681 	case FILE_BOTH_DIRECTORY_INFORMATION:
5682 		return sizeof(FILE_BOTH_DIRECTORY_INFO);
5683 	case FILE_DIRECTORY_INFORMATION:
5684 		return sizeof(FILE_DIRECTORY_INFO);
5685 	case FILE_NAMES_INFORMATION:
5686 		return sizeof(struct file_names_info);
5687 	case FILEID_FULL_DIRECTORY_INFORMATION:
5688 		return sizeof(FILE_ID_FULL_DIR_INFO);
5689 	case FILEID_BOTH_DIRECTORY_INFORMATION:
5690 		return sizeof(struct file_id_both_directory_info);
5691 	case FILE_ID_EXTD_DIRECTORY_INFORMATION:
5692 		return sizeof(struct file_id_extd_directory_info);
5693 	case FileId64ExtdDirectoryInformation:
5694 		return sizeof(struct file_id_64_extd_directory_info);
5695 	case FileId64ExtdBothDirectoryInformation:
5696 		return sizeof(struct file_id_64_extd_both_directory_info);
5697 	case FileIdAllExtdDirectoryInformation:
5698 		return sizeof(struct file_id_all_extd_directory_info);
5699 	case FileIdAllExtdBothDirectoryInformation:
5700 		return sizeof(struct file_id_all_extd_both_directory_info);
5701 	case SMB_FIND_FILE_POSIX_INFO:
5702 		return sizeof(struct smb2_posix_info);
5703 	default:
5704 		return -EOPNOTSUPP;
5705 	}
5706 }
5707 
5708 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
5709 {
5710 	switch (info_level) {
5711 	case FILE_FULL_DIRECTORY_INFORMATION:
5712 	{
5713 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
5714 
5715 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->rptr;
5716 		d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
5717 		d_info->name = ffdinfo->FileName;
5718 		d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
5719 		return 0;
5720 	}
5721 	case FILE_BOTH_DIRECTORY_INFORMATION:
5722 	{
5723 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
5724 
5725 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->rptr;
5726 		d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
5727 		d_info->name = fbdinfo->FileName;
5728 		d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
5729 		return 0;
5730 	}
5731 	case FILE_DIRECTORY_INFORMATION:
5732 	{
5733 		FILE_DIRECTORY_INFO *fdinfo;
5734 
5735 		fdinfo = (FILE_DIRECTORY_INFO *)d_info->rptr;
5736 		d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
5737 		d_info->name = fdinfo->FileName;
5738 		d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
5739 		return 0;
5740 	}
5741 	case FILE_NAMES_INFORMATION:
5742 	{
5743 		struct file_names_info *fninfo;
5744 
5745 		fninfo = (struct file_names_info *)d_info->rptr;
5746 		d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
5747 		d_info->name = fninfo->FileName;
5748 		d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
5749 		return 0;
5750 	}
5751 	case FILEID_FULL_DIRECTORY_INFORMATION:
5752 	{
5753 		FILE_ID_FULL_DIR_INFO *dinfo;
5754 
5755 		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->rptr;
5756 		d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
5757 		d_info->name = dinfo->FileName;
5758 		d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
5759 		return 0;
5760 	}
5761 	case FILEID_BOTH_DIRECTORY_INFORMATION:
5762 	{
5763 		struct file_id_both_directory_info *fibdinfo;
5764 
5765 		fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
5766 		d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
5767 		d_info->name = fibdinfo->FileName;
5768 		d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
5769 		return 0;
5770 	}
5771 	case FILE_ID_EXTD_DIRECTORY_INFORMATION:
5772 	{
5773 		struct file_id_extd_directory_info *info;
5774 
5775 		info = (struct file_id_extd_directory_info *)d_info->rptr;
5776 		d_info->rptr += le32_to_cpu(info->NextEntryOffset);
5777 		d_info->name = info->FileName;
5778 		d_info->name_len = le32_to_cpu(info->FileNameLength);
5779 		return 0;
5780 	}
5781 	case FileId64ExtdDirectoryInformation:
5782 	{
5783 		struct file_id_64_extd_directory_info *info;
5784 
5785 		info = (struct file_id_64_extd_directory_info *)d_info->rptr;
5786 		d_info->rptr += le32_to_cpu(info->NextEntryOffset);
5787 		d_info->name = info->FileName;
5788 		d_info->name_len = le32_to_cpu(info->FileNameLength);
5789 		return 0;
5790 	}
5791 	case FileId64ExtdBothDirectoryInformation:
5792 	{
5793 		struct file_id_64_extd_both_directory_info *info;
5794 
5795 		info = (struct file_id_64_extd_both_directory_info *)d_info->rptr;
5796 		d_info->rptr += le32_to_cpu(info->NextEntryOffset);
5797 		d_info->name = info->FileName;
5798 		d_info->name_len = le32_to_cpu(info->FileNameLength);
5799 		return 0;
5800 	}
5801 	case FileIdAllExtdDirectoryInformation:
5802 	{
5803 		struct file_id_all_extd_directory_info *info;
5804 
5805 		info = (struct file_id_all_extd_directory_info *)d_info->rptr;
5806 		d_info->rptr += le32_to_cpu(info->NextEntryOffset);
5807 		d_info->name = info->FileName;
5808 		d_info->name_len = le32_to_cpu(info->FileNameLength);
5809 		return 0;
5810 	}
5811 	case FileIdAllExtdBothDirectoryInformation:
5812 	{
5813 		struct file_id_all_extd_both_directory_info *info;
5814 
5815 		info = (struct file_id_all_extd_both_directory_info *)d_info->rptr;
5816 		d_info->rptr += le32_to_cpu(info->NextEntryOffset);
5817 		d_info->name = info->FileName;
5818 		d_info->name_len = le32_to_cpu(info->FileNameLength);
5819 		return 0;
5820 	}
5821 	case SMB_FIND_FILE_POSIX_INFO:
5822 	{
5823 		struct smb2_posix_info *posix_info;
5824 
5825 		posix_info = (struct smb2_posix_info *)d_info->rptr;
5826 		d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
5827 		d_info->name = posix_info->name;
5828 		d_info->name_len = le32_to_cpu(posix_info->name_len);
5829 		return 0;
5830 	}
5831 	default:
5832 		return -EINVAL;
5833 	}
5834 }
5835 
5836 /**
5837  * smb2_populate_readdir_entry() - encode directory entry in smb2 response
5838  * buffer
5839  * @conn:	connection instance
5840  * @info_level:	smb information level
5841  * @d_info:	structure included variables for query dir
5842  * @ksmbd_kstat:	ksmbd wrapper of dirent stat information
5843  *
5844  * if directory has many entries, find first can't read it fully.
5845  * find next might be called multiple times to read remaining dir entries
5846  *
5847  * Return:	0 on success, otherwise error
5848  */
5849 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
5850 				       struct ksmbd_dir_info *d_info,
5851 				       struct ksmbd_kstat *ksmbd_kstat)
5852 {
5853 	int next_entry_offset = 0;
5854 	char *conv_name;
5855 	int conv_len;
5856 	void *kstat;
5857 	int struct_sz, rc = 0;
5858 
5859 	conv_name = ksmbd_convert_dir_info_name(d_info,
5860 						conn->local_nls,
5861 						&conv_len);
5862 	if (!conv_name)
5863 		return -ENOMEM;
5864 
5865 	/* Somehow the name has only terminating NULL bytes */
5866 	if (conv_len < 0) {
5867 		rc = -EINVAL;
5868 		goto free_conv_name;
5869 	}
5870 
5871 	struct_sz = readdir_info_level_struct_sz(info_level);
5872 	if (struct_sz == -EOPNOTSUPP) {
5873 		rc = -EINVAL;
5874 		goto free_conv_name;
5875 	}
5876 
5877 	struct_sz += conv_len;
5878 	next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
5879 	d_info->last_entry_off_align = next_entry_offset - struct_sz;
5880 
5881 	if (next_entry_offset > d_info->out_buf_len) {
5882 		d_info->out_buf_len = 0;
5883 		rc = -ENOSPC;
5884 		goto free_conv_name;
5885 	}
5886 
5887 	kstat = d_info->wptr;
5888 	if (info_level != FILE_NAMES_INFORMATION)
5889 		kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
5890 
5891 	switch (info_level) {
5892 	case FILE_FULL_DIRECTORY_INFORMATION:
5893 	{
5894 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
5895 
5896 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)kstat;
5897 		ffdinfo->FileNameLength = cpu_to_le32(conv_len);
5898 		ffdinfo->EaSize =
5899 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5900 		if (ffdinfo->EaSize)
5901 			ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5902 		if (d_info->hide_dot_file && d_info->name[0] == '.')
5903 			ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5904 		memcpy(ffdinfo->FileName, conv_name, conv_len);
5905 		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5906 		break;
5907 	}
5908 	case FILE_BOTH_DIRECTORY_INFORMATION:
5909 	{
5910 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
5911 
5912 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)kstat;
5913 		fbdinfo->FileNameLength = cpu_to_le32(conv_len);
5914 		fbdinfo->EaSize =
5915 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5916 		if (fbdinfo->EaSize)
5917 			fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5918 		fbdinfo->ShortNameLength = 0;
5919 		fbdinfo->Reserved = 0;
5920 		if (d_info->hide_dot_file && d_info->name[0] == '.')
5921 			fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5922 		memcpy(fbdinfo->FileName, conv_name, conv_len);
5923 		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5924 		break;
5925 	}
5926 	case FILE_DIRECTORY_INFORMATION:
5927 	{
5928 		FILE_DIRECTORY_INFO *fdinfo;
5929 
5930 		fdinfo = (FILE_DIRECTORY_INFO *)kstat;
5931 		fdinfo->FileNameLength = cpu_to_le32(conv_len);
5932 		if (d_info->hide_dot_file && d_info->name[0] == '.')
5933 			fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5934 		memcpy(fdinfo->FileName, conv_name, conv_len);
5935 		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5936 		break;
5937 	}
5938 	case FILE_NAMES_INFORMATION:
5939 	{
5940 		struct file_names_info *fninfo;
5941 
5942 		fninfo = (struct file_names_info *)kstat;
5943 		fninfo->FileNameLength = cpu_to_le32(conv_len);
5944 		memcpy(fninfo->FileName, conv_name, conv_len);
5945 		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5946 		break;
5947 	}
5948 	case FILEID_FULL_DIRECTORY_INFORMATION:
5949 	{
5950 		FILE_ID_FULL_DIR_INFO *dinfo;
5951 
5952 		dinfo = (FILE_ID_FULL_DIR_INFO *)kstat;
5953 		dinfo->FileNameLength = cpu_to_le32(conv_len);
5954 		dinfo->EaSize =
5955 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
5956 		if (dinfo->EaSize)
5957 			dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
5958 		dinfo->Reserved = 0;
5959 		if (conn->is_aapl)
5960 			dinfo->UniqueId = 0;
5961 		else
5962 			dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
5963 		if (d_info->hide_dot_file && d_info->name[0] == '.')
5964 			dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
5965 		memcpy(dinfo->FileName, conv_name, conv_len);
5966 		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
5967 		break;
5968 	}
5969 	case FILEID_BOTH_DIRECTORY_INFORMATION:
5970 	{
5971 		struct file_id_both_directory_info *fibdinfo;
5972 
5973 		fibdinfo = (struct file_id_both_directory_info *)kstat;
5974 		fibdinfo->FileNameLength = cpu_to_le32(conv_len);
5975 		if (conn->is_aapl)
5976 			fibdinfo->UniqueId = 0;
5977 		else
5978 			fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
5979 		fibdinfo->ShortNameLength = 0;
5980 		fibdinfo->Reserved = 0;
5981 		if (conn->aapl_readdir_attr) {
5982 			/*
5983 			 * READDIR_ATTR wire format, confirmed against reference server's
5984 			 * reference implementation marshalling (reference implementation behavior):
5985 			 *   EaSize           = max_access (expanded specific
5986 			 *                      rights, simplified to "grant all")
5987 			 *   ShortNameLength  = 24 (fixed; not 0, despite the spec)
5988 			 *   ShortName[0..7]  = resource fork size (uint64 LE, 0 = no rfork)
5989 			 *   ShortName[8..23] = compressed FinderInfo (type+creator+flags+
5990 			 *                      ext_flags+date_added, 16 bytes LE; all
5991 			 *                      zeros means type=0/creator=0, i.e. use
5992 			 *                      the file extension for icon lookup)
5993 			 *   Reserved2        = Unix mode bits (uint16 LE)
5994 			 * Reparse-point tag is indicated via ExtFileAttributes, not EaSize.
5995 			 *
5996 			 * V2 (conn->aapl_readdir_attr_v2): ShortNameLength+Reserved
5997 			 * are read as a single flags field instead of being ignored
5998 			 * -- see smb2pdu.h for the wire-format confirmation and
5999 			 * AAPL_READDIR_ATTR_V2_NO_XATTR's meaning.
6000 			 */
6001 			__le32 reparse_tag =
6002 				smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
6003 
6004 			if (reparse_tag)
6005 				fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
6006 			/*
6007 			 * FILE_GENERIC_ALL_LE (0x10000000) is the raw
6008 			 * "generic all" meta-bit -- valid only in a
6009 			 * client's requested access mask, for the server
6010 			 * to expand. It has none of the specific FILE_*
6011 			 * rights bits set (FILE_LIST_DIRECTORY, FILE_TRAVERSE,
6012 			 * etc.), so reporting it here as max_access would make
6013 			 * macOS's bit-by-bit access checks fail on every
6014 			 * entry -> permanent "no entry" badges in Finder.
6015 			 * Report the actual expanded rights instead, same
6016 			 * as smb_map_generic_desired_access() does when
6017 			 * translating a client's GENERIC_ALL request.
6018 			 */
6019 			fibdinfo->EaSize = cpu_to_le32(GENERIC_ALL_FLAGS);
6020 			/*
6021 			 * The spec says ShortNameLength should be 0 when
6022 			 * there's no short name; 24 here instead matches
6023 			 * reference implementation marshalling (reference
6024 			 * behavior) for server-to-server wire parity.
6025 			 * V2 repurposes it as a flags field that is
6026 			 * interpreted; V1 doesn't. Either value is safe
6027 			 * here, so keep 24 for parity.
6028 			 */
6029 			if (conn->aapl_readdir_attr_v2) {
6030 				/*
6031 				 * V2 repurposes this field as flags (see comment
6032 				 * above) -- 24 is a V1-only convention that real
6033 				 * macOS clients ignore outright, so don't reuse it
6034 				 * here as a base value for a field V2 clients
6035 				 * actually interpret.
6036 				 */
6037 				fibdinfo->ShortNameLength = 0;
6038 				if (!ksmbd_kstat->has_ads_stream)
6039 					fibdinfo->ShortNameLength = AAPL_READDIR_ATTR_V2_NO_XATTR;
6040 			} else {
6041 				fibdinfo->ShortNameLength = 24;
6042 			}
6043 			memset(fibdinfo->ShortName, 0, sizeof(fibdinfo->ShortName));
6044 			fibdinfo->Reserved2 = cpu_to_le16(ksmbd_kstat->kstat->mode & 0xffff);
6045 		} else {
6046 			fibdinfo->EaSize =
6047 				smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
6048 			if (fibdinfo->EaSize)
6049 				fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
6050 			fibdinfo->Reserved2 = cpu_to_le16(0);
6051 		}
6052 		if (d_info->hide_dot_file && d_info->name[0] == '.')
6053 			fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
6054 		memcpy(fibdinfo->FileName, conv_name, conv_len);
6055 		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
6056 		break;
6057 	}
6058 	case FILE_ID_EXTD_DIRECTORY_INFORMATION:
6059 	{
6060 		struct file_id_extd_directory_info *info;
6061 
6062 		info = (struct file_id_extd_directory_info *)kstat;
6063 		info->FileNameLength = cpu_to_le32(conv_len);
6064 		info->EaSize = 0;
6065 		info->ReparsePointTag =
6066 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
6067 		if (info->ReparsePointTag)
6068 			info->ExtFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
6069 		/* The VFS does not provide a 128-bit file ID. */
6070 		memset(info->FileId, 0, sizeof(info->FileId));
6071 		if (d_info->hide_dot_file && d_info->name[0] == '.')
6072 			info->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
6073 		memcpy(info->FileName, conv_name, conv_len);
6074 		memset(info->FileName + conv_len, 0, d_info->last_entry_off_align);
6075 		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
6076 		break;
6077 	}
6078 	case FileId64ExtdDirectoryInformation:
6079 	{
6080 		struct file_id_64_extd_directory_info *info;
6081 
6082 		info = (struct file_id_64_extd_directory_info *)kstat;
6083 		info->FileNameLength = cpu_to_le32(conv_len);
6084 		info->EaSize = 0;
6085 		info->ReparsePointTag =
6086 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
6087 		if (info->ReparsePointTag)
6088 			info->ExtFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
6089 		if (conn->is_aapl)
6090 			info->FileId = 0;
6091 		else
6092 			info->FileId = cpu_to_le64(ksmbd_kstat->kstat->ino);
6093 		if (d_info->hide_dot_file && d_info->name[0] == '.')
6094 			info->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
6095 		memcpy(info->FileName, conv_name, conv_len);
6096 		memset(info->FileName + conv_len, 0, d_info->last_entry_off_align);
6097 		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
6098 		break;
6099 	}
6100 	case FileId64ExtdBothDirectoryInformation:
6101 	{
6102 		struct file_id_64_extd_both_directory_info *info;
6103 
6104 		info = (struct file_id_64_extd_both_directory_info *)kstat;
6105 		info->FileNameLength = cpu_to_le32(conv_len);
6106 		info->EaSize = 0;
6107 		info->ReparsePointTag =
6108 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
6109 		if (info->ReparsePointTag)
6110 			info->ExtFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
6111 		if (conn->is_aapl)
6112 			info->FileId = 0;
6113 		else
6114 			info->FileId = cpu_to_le64(ksmbd_kstat->kstat->ino);
6115 		info->ShortNameLength = 0;
6116 		info->Reserved1 = 0;
6117 		memset(info->ShortName, 0, sizeof(info->ShortName));
6118 		if (d_info->hide_dot_file && d_info->name[0] == '.')
6119 			info->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
6120 		memcpy(info->FileName, conv_name, conv_len);
6121 		memset(info->FileName + conv_len, 0, d_info->last_entry_off_align);
6122 		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
6123 		break;
6124 	}
6125 	case FileIdAllExtdDirectoryInformation:
6126 	{
6127 		struct file_id_all_extd_directory_info *info;
6128 
6129 		info = (struct file_id_all_extd_directory_info *)kstat;
6130 		info->FileNameLength = cpu_to_le32(conv_len);
6131 		info->EaSize = 0;
6132 		info->ReparsePointTag =
6133 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
6134 		if (info->ReparsePointTag)
6135 			info->ExtFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
6136 		if (conn->is_aapl)
6137 			info->FileId = 0;
6138 		else
6139 			info->FileId = cpu_to_le64(ksmbd_kstat->kstat->ino);
6140 		/* The VFS does not provide a 128-bit file ID. */
6141 		memset(info->FileId128, 0, sizeof(info->FileId128));
6142 		if (d_info->hide_dot_file && d_info->name[0] == '.')
6143 			info->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
6144 		memcpy(info->FileName, conv_name, conv_len);
6145 		memset(info->FileName + conv_len, 0, d_info->last_entry_off_align);
6146 		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
6147 		break;
6148 	}
6149 	case FileIdAllExtdBothDirectoryInformation:
6150 	{
6151 		struct file_id_all_extd_both_directory_info *info;
6152 
6153 		info = (struct file_id_all_extd_both_directory_info *)kstat;
6154 		info->FileNameLength = cpu_to_le32(conv_len);
6155 		info->EaSize = 0;
6156 		info->ReparsePointTag =
6157 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
6158 		if (info->ReparsePointTag)
6159 			info->ExtFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
6160 		if (conn->is_aapl)
6161 			info->FileId = 0;
6162 		else
6163 			info->FileId = cpu_to_le64(ksmbd_kstat->kstat->ino);
6164 		/* The VFS does not provide a 128-bit file ID. */
6165 		memset(info->FileId128, 0, sizeof(info->FileId128));
6166 		info->ShortNameLength = 0;
6167 		info->Reserved1 = 0;
6168 		memset(info->ShortName, 0, sizeof(info->ShortName));
6169 		if (d_info->hide_dot_file && d_info->name[0] == '.')
6170 			info->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
6171 		memcpy(info->FileName, conv_name, conv_len);
6172 		memset(info->FileName + conv_len, 0, d_info->last_entry_off_align);
6173 		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
6174 		break;
6175 	}
6176 	case SMB_FIND_FILE_POSIX_INFO:
6177 	{
6178 		struct smb2_posix_info *posix_info;
6179 		u64 time;
6180 
6181 		posix_info = (struct smb2_posix_info *)kstat;
6182 		posix_info->Ignored = 0;
6183 		posix_info->Zero = 0;
6184 		posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
6185 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
6186 		posix_info->ChangeTime = cpu_to_le64(time);
6187 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
6188 		posix_info->LastAccessTime = cpu_to_le64(time);
6189 		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
6190 		posix_info->LastWriteTime = cpu_to_le64(time);
6191 		posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
6192 		posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
6193 		posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->dev);
6194 		posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
6195 		posix_info->ReparseTag =
6196 			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
6197 		posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 07777);
6198 		switch (ksmbd_kstat->kstat->mode & S_IFMT) {
6199 		case S_IFDIR:
6200 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
6201 			break;
6202 		case S_IFLNK:
6203 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
6204 			break;
6205 		case S_IFCHR:
6206 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
6207 			break;
6208 		case S_IFBLK:
6209 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
6210 			break;
6211 		case S_IFIFO:
6212 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
6213 			break;
6214 		case S_IFSOCK:
6215 			posix_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
6216 		}
6217 
6218 		posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
6219 		posix_info->DosAttributes =
6220 			S_ISDIR(ksmbd_kstat->kstat->mode) ?
6221 				FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
6222 		if (posix_info->ReparseTag)
6223 			posix_info->DosAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
6224 		if (d_info->hide_dot_file && d_info->name[0] == '.')
6225 			posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
6226 		/*
6227 		 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
6228 		 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
6229 		 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
6230 		 */
6231 		id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
6232 			  SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
6233 		id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
6234 			  SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
6235 		memcpy(posix_info->name, conv_name, conv_len);
6236 		posix_info->name_len = cpu_to_le32(conv_len);
6237 		posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
6238 		break;
6239 	}
6240 
6241 	} /* switch (info_level) */
6242 
6243 	d_info->last_entry_offset = d_info->data_count;
6244 	d_info->data_count += next_entry_offset;
6245 	d_info->out_buf_len -= next_entry_offset;
6246 	d_info->wptr += next_entry_offset;
6247 
6248 	ksmbd_debug(SMB,
6249 		    "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
6250 		    info_level, d_info->out_buf_len,
6251 		    next_entry_offset, d_info->data_count);
6252 
6253 free_conv_name:
6254 	kfree(conv_name);
6255 	return rc;
6256 }
6257 
6258 struct smb2_query_dir_private {
6259 	struct ksmbd_work	*work;
6260 	char			*search_pattern;
6261 	struct ksmbd_file	*dir_fp;
6262 
6263 	struct ksmbd_dir_info	*d_info;
6264 	int			info_level;
6265 };
6266 
6267 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
6268 {
6269 	const struct mnt_idmap	*idmap = file_mnt_idmap(priv->dir_fp->filp);
6270 	struct kstat		kstat;
6271 	struct ksmbd_kstat	ksmbd_kstat;
6272 	int			rc;
6273 	int			i;
6274 
6275 	for (i = 0; i < priv->d_info->num_entry; i++) {
6276 		struct dentry *dent;
6277 		struct path path;
6278 
6279 		if (dentry_name(priv->d_info, priv->info_level))
6280 			return -EINVAL;
6281 
6282 		dent = lookup_one_unlocked(idmap,
6283 					   &QSTR_LEN(priv->d_info->name,
6284 						     priv->d_info->name_len),
6285 					   priv->dir_fp->filp->f_path.dentry);
6286 
6287 		if (IS_ERR(dent)) {
6288 			ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
6289 				    priv->d_info->name,
6290 				    PTR_ERR(dent));
6291 			continue;
6292 		}
6293 		if (unlikely(d_is_negative(dent))) {
6294 			dput(dent);
6295 			ksmbd_debug(SMB, "Negative dentry `%s'\n",
6296 				    priv->d_info->name);
6297 			continue;
6298 		}
6299 
6300 		if (test_share_config_flag(priv->work->tcon->share_conf,
6301 					   KSMBD_SHARE_FLAG_HIDE_UNREADABLE)) {
6302 			__le32 daccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
6303 				FILE_READ_ATTRIBUTES_LE;
6304 
6305 			path.mnt = priv->dir_fp->filp->f_path.mnt;
6306 			path.dentry = dent;
6307 			rc = smb_check_perm_dacl(priv->work->conn, &path,
6308 						 &daccess, daccess,
6309 						 priv->work->sess->user->uid,
6310 						 true);
6311 			if (rc) {
6312 				dput(dent);
6313 				continue;
6314 			}
6315 		}
6316 
6317 		ksmbd_kstat.kstat = &kstat;
6318 		if (priv->info_level != FILE_NAMES_INFORMATION) {
6319 			rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
6320 							 idmap,
6321 							 dent,
6322 							 &ksmbd_kstat);
6323 			if (rc) {
6324 				dput(dent);
6325 				continue;
6326 			}
6327 		}
6328 
6329 		rc = smb2_populate_readdir_entry(priv->work->conn,
6330 						 priv->info_level,
6331 						 priv->d_info,
6332 						 &ksmbd_kstat);
6333 		dput(dent);
6334 		if (rc)
6335 			return rc;
6336 	}
6337 	return 0;
6338 }
6339 
6340 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
6341 				   int info_level)
6342 {
6343 	int struct_sz;
6344 	int conv_len;
6345 	int next_entry_offset;
6346 
6347 	struct_sz = readdir_info_level_struct_sz(info_level);
6348 	if (struct_sz == -EOPNOTSUPP)
6349 		return -EOPNOTSUPP;
6350 
6351 	conv_len = (d_info->name_len + 1) * 2;
6352 	next_entry_offset = ALIGN(struct_sz + conv_len,
6353 				  KSMBD_DIR_INFO_ALIGNMENT);
6354 
6355 	if (next_entry_offset > d_info->out_buf_len) {
6356 		d_info->out_buf_len = 0;
6357 		return -ENOSPC;
6358 	}
6359 
6360 	switch (info_level) {
6361 	case FILE_FULL_DIRECTORY_INFORMATION:
6362 	{
6363 		FILE_FULL_DIRECTORY_INFO *ffdinfo;
6364 
6365 		ffdinfo = (FILE_FULL_DIRECTORY_INFO *)d_info->wptr;
6366 		memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
6367 		ffdinfo->FileName[d_info->name_len] = 0x00;
6368 		ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
6369 		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
6370 		break;
6371 	}
6372 	case FILE_BOTH_DIRECTORY_INFORMATION:
6373 	{
6374 		FILE_BOTH_DIRECTORY_INFO *fbdinfo;
6375 
6376 		fbdinfo = (FILE_BOTH_DIRECTORY_INFO *)d_info->wptr;
6377 		memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
6378 		fbdinfo->FileName[d_info->name_len] = 0x00;
6379 		fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
6380 		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
6381 		break;
6382 	}
6383 	case FILE_DIRECTORY_INFORMATION:
6384 	{
6385 		FILE_DIRECTORY_INFO *fdinfo;
6386 
6387 		fdinfo = (FILE_DIRECTORY_INFO *)d_info->wptr;
6388 		memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
6389 		fdinfo->FileName[d_info->name_len] = 0x00;
6390 		fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
6391 		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
6392 		break;
6393 	}
6394 	case FILE_NAMES_INFORMATION:
6395 	{
6396 		struct file_names_info *fninfo;
6397 
6398 		fninfo = (struct file_names_info *)d_info->wptr;
6399 		memcpy(fninfo->FileName, d_info->name, d_info->name_len);
6400 		fninfo->FileName[d_info->name_len] = 0x00;
6401 		fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
6402 		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
6403 		break;
6404 	}
6405 	case FILEID_FULL_DIRECTORY_INFORMATION:
6406 	{
6407 		FILE_ID_FULL_DIR_INFO *dinfo;
6408 
6409 		dinfo = (FILE_ID_FULL_DIR_INFO *)d_info->wptr;
6410 		memcpy(dinfo->FileName, d_info->name, d_info->name_len);
6411 		dinfo->FileName[d_info->name_len] = 0x00;
6412 		dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
6413 		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
6414 		break;
6415 	}
6416 	case FILEID_BOTH_DIRECTORY_INFORMATION:
6417 	{
6418 		struct file_id_both_directory_info *fibdinfo;
6419 
6420 		fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
6421 		memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
6422 		fibdinfo->FileName[d_info->name_len] = 0x00;
6423 		fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
6424 		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
6425 		break;
6426 	}
6427 	case FILE_ID_EXTD_DIRECTORY_INFORMATION:
6428 	{
6429 		struct file_id_extd_directory_info *info;
6430 
6431 		info = (struct file_id_extd_directory_info *)d_info->wptr;
6432 		memcpy(info->FileName, d_info->name, d_info->name_len);
6433 		info->FileName[d_info->name_len] = 0x00;
6434 		info->FileNameLength = cpu_to_le32(d_info->name_len);
6435 		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
6436 		break;
6437 	}
6438 	case FileId64ExtdDirectoryInformation:
6439 	{
6440 		struct file_id_64_extd_directory_info *info;
6441 
6442 		info = (struct file_id_64_extd_directory_info *)d_info->wptr;
6443 		memcpy(info->FileName, d_info->name, d_info->name_len);
6444 		info->FileName[d_info->name_len] = 0x00;
6445 		info->FileNameLength = cpu_to_le32(d_info->name_len);
6446 		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
6447 		break;
6448 	}
6449 	case FileId64ExtdBothDirectoryInformation:
6450 	{
6451 		struct file_id_64_extd_both_directory_info *info;
6452 
6453 		info = (struct file_id_64_extd_both_directory_info *)d_info->wptr;
6454 		memcpy(info->FileName, d_info->name, d_info->name_len);
6455 		info->FileName[d_info->name_len] = 0x00;
6456 		info->FileNameLength = cpu_to_le32(d_info->name_len);
6457 		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
6458 		break;
6459 	}
6460 	case FileIdAllExtdDirectoryInformation:
6461 	{
6462 		struct file_id_all_extd_directory_info *info;
6463 
6464 		info = (struct file_id_all_extd_directory_info *)d_info->wptr;
6465 		memcpy(info->FileName, d_info->name, d_info->name_len);
6466 		info->FileName[d_info->name_len] = 0x00;
6467 		info->FileNameLength = cpu_to_le32(d_info->name_len);
6468 		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
6469 		break;
6470 	}
6471 	case FileIdAllExtdBothDirectoryInformation:
6472 	{
6473 		struct file_id_all_extd_both_directory_info *info;
6474 
6475 		info = (struct file_id_all_extd_both_directory_info *)d_info->wptr;
6476 		memcpy(info->FileName, d_info->name, d_info->name_len);
6477 		info->FileName[d_info->name_len] = 0x00;
6478 		info->FileNameLength = cpu_to_le32(d_info->name_len);
6479 		info->NextEntryOffset = cpu_to_le32(next_entry_offset);
6480 		break;
6481 	}
6482 	case SMB_FIND_FILE_POSIX_INFO:
6483 	{
6484 		struct smb2_posix_info *posix_info;
6485 
6486 		posix_info = (struct smb2_posix_info *)d_info->wptr;
6487 		memcpy(posix_info->name, d_info->name, d_info->name_len);
6488 		posix_info->name[d_info->name_len] = 0x00;
6489 		posix_info->name_len = cpu_to_le32(d_info->name_len);
6490 		posix_info->NextEntryOffset =
6491 			cpu_to_le32(next_entry_offset);
6492 		break;
6493 	}
6494 	} /* switch (info_level) */
6495 
6496 	d_info->num_entry++;
6497 	d_info->out_buf_len -= next_entry_offset;
6498 	d_info->wptr += next_entry_offset;
6499 	return 0;
6500 }
6501 
6502 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
6503 		       loff_t offset, u64 ino, unsigned int d_type)
6504 {
6505 	struct ksmbd_readdir_data	*buf;
6506 	struct smb2_query_dir_private	*priv;
6507 	struct ksmbd_dir_info		*d_info;
6508 	int				rc;
6509 
6510 	buf	= container_of(ctx, struct ksmbd_readdir_data, ctx);
6511 	priv	= buf->private;
6512 	d_info	= priv->d_info;
6513 
6514 	/* dot and dotdot entries are already reserved */
6515 	if (!strcmp(".", name) || !strcmp("..", name))
6516 		return true;
6517 	d_info->num_scan++;
6518 	if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
6519 		return true;
6520 	if (!match_pattern(name, namlen, priv->search_pattern))
6521 		return true;
6522 
6523 	d_info->name		= name;
6524 	d_info->name_len	= namlen;
6525 	rc = reserve_populate_dentry(d_info, priv->info_level);
6526 	if (rc)
6527 		return false;
6528 	if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
6529 		d_info->out_buf_len = 0;
6530 	return true;
6531 }
6532 
6533 static int verify_info_level(int info_level)
6534 {
6535 	switch (info_level) {
6536 	case FILE_FULL_DIRECTORY_INFORMATION:
6537 	case FILE_BOTH_DIRECTORY_INFORMATION:
6538 	case FILE_DIRECTORY_INFORMATION:
6539 	case FILE_NAMES_INFORMATION:
6540 	case FILEID_FULL_DIRECTORY_INFORMATION:
6541 	case FILEID_BOTH_DIRECTORY_INFORMATION:
6542 	case SMB_FIND_FILE_POSIX_INFO:
6543 	case FILE_ID_EXTD_DIRECTORY_INFORMATION:
6544 	case FileId64ExtdDirectoryInformation:
6545 	case FileId64ExtdBothDirectoryInformation:
6546 	case FileIdAllExtdDirectoryInformation:
6547 	case FileIdAllExtdBothDirectoryInformation:
6548 		break;
6549 	default:
6550 		return -EOPNOTSUPP;
6551 	}
6552 
6553 	return 0;
6554 }
6555 
6556 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
6557 {
6558 	int free_len;
6559 
6560 	free_len = (int)(work->response_sz -
6561 		(get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
6562 	return free_len;
6563 }
6564 
6565 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
6566 				     unsigned short hdr2_len,
6567 				     unsigned int out_buf_len)
6568 {
6569 	int free_len;
6570 
6571 	if (out_buf_len > work->conn->vals->max_trans_size)
6572 		return -EINVAL;
6573 
6574 	free_len = smb2_resp_buf_len(work, hdr2_len);
6575 	if (free_len < 0)
6576 		return -EINVAL;
6577 
6578 	return min_t(int, out_buf_len, free_len);
6579 }
6580 
6581 int smb2_query_dir(struct ksmbd_work *work)
6582 {
6583 	struct ksmbd_conn *conn = work->conn;
6584 	struct smb2_query_directory_req *req;
6585 	struct smb2_query_directory_rsp *rsp;
6586 	struct ksmbd_share_config *share = work->tcon->share_conf;
6587 	struct ksmbd_file *dir_fp = NULL;
6588 	struct ksmbd_dir_info d_info;
6589 	int rc = 0;
6590 	char *srch_ptr = NULL;
6591 	unsigned char srch_flag;
6592 	int buffer_sz;
6593 	struct smb2_query_dir_private query_dir_private = {NULL, };
6594 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6595 
6596 	ksmbd_debug(SMB, "Received smb2 query directory request\n");
6597 
6598 	WORK_BUFFERS(work, req, rsp);
6599 
6600 	if (smb2_compound_has_failed(work, &rsp->hdr))
6601 		return -EACCES;
6602 
6603 	if (work->next_smb2_rcv_hdr_off &&
6604 	    !has_file_id(req->VolatileFileId)) {
6605 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6606 			    work->compound_fid);
6607 		id = work->compound_fid;
6608 		pid = work->compound_pfid;
6609 	}
6610 
6611 	if (!has_file_id(id)) {
6612 		id = req->VolatileFileId;
6613 		pid = req->PersistentFileId;
6614 	}
6615 
6616 	if (ksmbd_override_fsids(work)) {
6617 		rsp->hdr.Status = STATUS_NO_MEMORY;
6618 		smb2_set_err_rsp(work);
6619 		return -ENOMEM;
6620 	}
6621 
6622 	rc = verify_info_level(req->FileInformationClass);
6623 	if (rc) {
6624 		rc = -EFAULT;
6625 		goto err_out2;
6626 	}
6627 
6628 	dir_fp = ksmbd_lookup_fd_slow(work, id, pid);
6629 	if (!dir_fp) {
6630 		rc = -EBADF;
6631 		goto err_out2;
6632 	}
6633 	if (req->FileInformationClass == SMB_FIND_FILE_POSIX_INFO &&
6634 	    (conn->dialect != SMB311_PROT_ID ||
6635 	     !work->tcon->posix_extensions || !dir_fp->is_posix_ctxt)) {
6636 		rc = -EFAULT;
6637 		goto err_out2;
6638 	}
6639 
6640 	if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
6641 	    inode_permission(file_mnt_idmap(dir_fp->filp),
6642 			     file_inode(dir_fp->filp),
6643 			     MAY_READ | MAY_EXEC)) {
6644 		pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
6645 		rc = -EACCES;
6646 		goto err_out2;
6647 	}
6648 
6649 	if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
6650 		pr_err("can't do query dir for a file\n");
6651 		rc = -EINVAL;
6652 		goto err_out2;
6653 	}
6654 
6655 	srch_flag = req->Flags;
6656 	srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
6657 					  le16_to_cpu(req->FileNameLength), 1,
6658 					  conn->local_nls);
6659 	if (IS_ERR(srch_ptr)) {
6660 		ksmbd_debug(SMB, "Search Pattern not found\n");
6661 		rc = -EINVAL;
6662 		goto err_out2;
6663 	} else {
6664 		ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
6665 	}
6666 
6667 	mutex_lock(&dir_fp->readdir_lock);
6668 
6669 	if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
6670 		ksmbd_debug(SMB, "Restart directory scan\n");
6671 		generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
6672 	}
6673 
6674 	memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
6675 	d_info.wptr = (char *)rsp->Buffer;
6676 	d_info.rptr = (char *)rsp->Buffer;
6677 	d_info.out_buf_len =
6678 		smb2_calc_max_out_buf_len(work,
6679 				offsetof(struct smb2_query_directory_rsp, Buffer),
6680 				le32_to_cpu(req->OutputBufferLength));
6681 	if (d_info.out_buf_len < 0) {
6682 		rc = -EINVAL;
6683 		goto err_out;
6684 	}
6685 	d_info.flags = srch_flag;
6686 
6687 	/*
6688 	 * reserve dot and dotdot entries in head of buffer
6689 	 * in first response
6690 	 */
6691 	rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
6692 					       dir_fp, &d_info, srch_ptr,
6693 					       smb2_populate_readdir_entry);
6694 	if (rc == -ENOSPC)
6695 		rc = 0;
6696 	else if (rc)
6697 		goto err_out;
6698 
6699 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
6700 		d_info.hide_dot_file = true;
6701 
6702 	buffer_sz				= d_info.out_buf_len;
6703 	d_info.rptr				= d_info.wptr;
6704 	query_dir_private.work			= work;
6705 	query_dir_private.search_pattern	= srch_ptr;
6706 	query_dir_private.dir_fp		= dir_fp;
6707 	query_dir_private.d_info		= &d_info;
6708 	query_dir_private.info_level		= req->FileInformationClass;
6709 	dir_fp->readdir_data.private		= &query_dir_private;
6710 	set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
6711 again:
6712 	d_info.num_scan = 0;
6713 	rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
6714 	/*
6715 	 * num_entry can be 0 if the directory iteration stops before reaching
6716 	 * the end of the directory and no file is matched with the search
6717 	 * pattern.
6718 	 */
6719 	if (rc >= 0 && !d_info.num_entry && d_info.num_scan &&
6720 	    d_info.out_buf_len > 0)
6721 		goto again;
6722 	/*
6723 	 * req->OutputBufferLength is too small to contain even one entry.
6724 	 * In this case, it immediately returns OutputBufferLength 0 to client.
6725 	 */
6726 	if (!d_info.out_buf_len && !d_info.num_entry)
6727 		goto no_buf_len;
6728 	if (rc > 0 || rc == -ENOSPC)
6729 		rc = 0;
6730 	else if (rc)
6731 		goto err_out;
6732 
6733 	d_info.wptr = d_info.rptr;
6734 	d_info.out_buf_len = buffer_sz;
6735 	rc = process_query_dir_entries(&query_dir_private);
6736 	if (rc)
6737 		goto err_out;
6738 
6739 	if (!d_info.data_count && d_info.out_buf_len >= 0) {
6740 		if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
6741 			rsp->hdr.Status = STATUS_NO_SUCH_FILE;
6742 		} else {
6743 			dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
6744 			rsp->hdr.Status = STATUS_NO_MORE_FILES;
6745 		}
6746 		rsp->StructureSize = cpu_to_le16(9);
6747 		rsp->OutputBufferOffset = cpu_to_le16(0);
6748 		rsp->OutputBufferLength = cpu_to_le32(0);
6749 		rsp->Buffer[0] = 0;
6750 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6751 				       offsetof(struct smb2_query_directory_rsp, Buffer)
6752 				       + 1);
6753 		if (rc)
6754 			goto err_out;
6755 	} else {
6756 no_buf_len:
6757 		((FILE_DIRECTORY_INFO *)
6758 		((char *)rsp->Buffer + d_info.last_entry_offset))
6759 		->NextEntryOffset = 0;
6760 		if (d_info.data_count >= d_info.last_entry_off_align)
6761 			d_info.data_count -= d_info.last_entry_off_align;
6762 
6763 		rsp->StructureSize = cpu_to_le16(9);
6764 		rsp->OutputBufferOffset = cpu_to_le16(72);
6765 		rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
6766 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6767 				       offsetof(struct smb2_query_directory_rsp, Buffer) +
6768 				       d_info.data_count);
6769 		if (rc)
6770 			goto err_out;
6771 	}
6772 
6773 	mutex_unlock(&dir_fp->readdir_lock);
6774 	kfree(srch_ptr);
6775 	ksmbd_fd_put(work, dir_fp);
6776 	ksmbd_revert_fsids(work);
6777 	return 0;
6778 
6779 err_out:
6780 	pr_err("error while processing smb2 query dir rc = %d\n", rc);
6781 	mutex_unlock(&dir_fp->readdir_lock);
6782 	kfree(srch_ptr);
6783 
6784 err_out2:
6785 	if (rc == -EINVAL)
6786 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6787 	else if (rc == -EACCES)
6788 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
6789 	else if (rc == -ENOENT)
6790 		rsp->hdr.Status = STATUS_NO_SUCH_FILE;
6791 	else if (rc == -EBADF)
6792 		rsp->hdr.Status = STATUS_FILE_CLOSED;
6793 	else if (rc == -ENOMEM)
6794 		rsp->hdr.Status = STATUS_NO_MEMORY;
6795 	else if (rc == -EFAULT)
6796 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6797 	else if (rc == -EIO)
6798 		rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
6799 	if (!rsp->hdr.Status)
6800 		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6801 
6802 	smb2_set_err_rsp(work);
6803 	ksmbd_fd_put(work, dir_fp);
6804 	ksmbd_revert_fsids(work);
6805 	return rc;
6806 }
6807 
6808 /**
6809  * buffer_check_err() - helper function to check buffer errors
6810  * @reqOutputBufferLength:	max buffer length expected in command response
6811  * @fixed_len:			minimum fixed response length
6812  * @rsp:		query info response buffer contains output buffer length
6813  *
6814  * Return:	0 on success, otherwise error
6815  */
6816 static int buffer_check_err(int reqOutputBufferLength,
6817 			    unsigned int fixed_len,
6818 			    struct smb2_query_info_rsp *rsp)
6819 {
6820 	unsigned int output_len = le32_to_cpu(rsp->OutputBufferLength);
6821 
6822 	if (reqOutputBufferLength < fixed_len) {
6823 		pr_err("Invalid Buffer Size Requested\n");
6824 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
6825 		return -EINVAL;
6826 	}
6827 
6828 	if (reqOutputBufferLength < output_len) {
6829 		rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
6830 		rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
6831 	}
6832 	return 0;
6833 }
6834 
6835 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp)
6836 {
6837 	struct smb2_file_standard_info *sinfo;
6838 
6839 	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
6840 
6841 	sinfo->AllocationSize = cpu_to_le64(4096);
6842 	sinfo->EndOfFile = cpu_to_le64(0);
6843 	sinfo->NumberOfLinks = cpu_to_le32(1);
6844 	sinfo->DeletePending = 1;
6845 	sinfo->Directory = 0;
6846 	rsp->OutputBufferLength =
6847 		cpu_to_le32(sizeof(struct smb2_file_standard_info));
6848 }
6849 
6850 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num)
6851 {
6852 	struct smb2_file_internal_info *file_info;
6853 
6854 	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
6855 
6856 	/* any unique number */
6857 	file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
6858 	rsp->OutputBufferLength =
6859 		cpu_to_le32(sizeof(struct smb2_file_internal_info));
6860 }
6861 
6862 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
6863 				   struct smb2_query_info_req *req,
6864 				   struct smb2_query_info_rsp *rsp)
6865 {
6866 	u64 id;
6867 	int rc;
6868 
6869 	/*
6870 	 * Windows can sometime send query file info request on
6871 	 * pipe without opening it, checking error condition here
6872 	 */
6873 	id = req->VolatileFileId;
6874 
6875 	lockdep_assert_not_held(&sess->rpc_lock);
6876 
6877 	down_read(&sess->rpc_lock);
6878 	if (!ksmbd_session_rpc_method(sess, id)) {
6879 		up_read(&sess->rpc_lock);
6880 		return -ENOENT;
6881 	}
6882 	up_read(&sess->rpc_lock);
6883 
6884 	ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
6885 		    req->FileInfoClass, req->VolatileFileId);
6886 
6887 	switch (req->FileInfoClass) {
6888 	case FILE_STANDARD_INFORMATION:
6889 		get_standard_info_pipe(rsp);
6890 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
6891 				      le32_to_cpu(rsp->OutputBufferLength),
6892 				      rsp);
6893 		break;
6894 	case FILE_INTERNAL_INFORMATION:
6895 		get_internal_info_pipe(rsp, id);
6896 		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
6897 				      le32_to_cpu(rsp->OutputBufferLength),
6898 				      rsp);
6899 		break;
6900 	default:
6901 		ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
6902 			    req->FileInfoClass);
6903 		rc = -EOPNOTSUPP;
6904 	}
6905 	return rc;
6906 }
6907 
6908 /**
6909  * smb2_get_ea() - handler for smb2 get extended attribute command
6910  * @work:	smb work containing query info command buffer
6911  * @fp:		ksmbd_file pointer
6912  * @req:	get extended attribute request
6913  * @rsp:	response buffer pointer
6914  * @rsp_org:	base response buffer pointer in case of chained response
6915  *
6916  * Return:	0 on success, otherwise error
6917  */
6918 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
6919 		       struct smb2_query_info_req *req,
6920 		       struct smb2_query_info_rsp *rsp, void *rsp_org)
6921 {
6922 	struct smb2_ea_info *eainfo, *prev_eainfo;
6923 	char *name, *ptr, *xattr_list = NULL, *buf;
6924 	int rc, name_len, value_len, xattr_list_len, idx;
6925 	ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
6926 	struct smb2_ea_info_req *ea_req = NULL;
6927 	const struct path *path;
6928 	const struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
6929 
6930 	if (!(fp->daccess & FILE_READ_EA_LE)) {
6931 		pr_err("Not permitted to read ext attr : 0x%x\n",
6932 		       fp->daccess);
6933 		return -EACCES;
6934 	}
6935 
6936 	path = &fp->filp->f_path;
6937 	/* single EA entry is requested with given user.* name */
6938 	if (req->InputBufferLength) {
6939 		if (le32_to_cpu(req->InputBufferLength) <=
6940 		    sizeof(struct smb2_ea_info_req))
6941 			return -EINVAL;
6942 
6943 		ea_req = (struct smb2_ea_info_req *)((char *)req +
6944 						     le16_to_cpu(req->InputBufferOffset));
6945 
6946 		if (le32_to_cpu(req->InputBufferLength) <
6947 		    offsetof(struct smb2_ea_info_req, name) +
6948 		    ea_req->EaNameLength)
6949 			return -EINVAL;
6950 	} else {
6951 		/* need to send all EAs, if no specific EA is requested*/
6952 		if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
6953 			ksmbd_debug(SMB,
6954 				    "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
6955 				    le32_to_cpu(req->Flags));
6956 	}
6957 
6958 	buf_free_len =
6959 		smb2_calc_max_out_buf_len(work,
6960 				offsetof(struct smb2_query_info_rsp, Buffer),
6961 				le32_to_cpu(req->OutputBufferLength));
6962 	if (buf_free_len < 0)
6963 		return -EINVAL;
6964 
6965 	rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
6966 	if (rc < 0) {
6967 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
6968 		goto out;
6969 	} else if (!rc) { /* there is no EA in the file */
6970 		ksmbd_debug(SMB, "no ea data in the file\n");
6971 		goto done;
6972 	}
6973 	xattr_list_len = rc;
6974 
6975 	ptr = (char *)rsp->Buffer;
6976 	eainfo = (struct smb2_ea_info *)ptr;
6977 	prev_eainfo = eainfo;
6978 	idx = 0;
6979 
6980 	while (idx < xattr_list_len) {
6981 		name = xattr_list + idx;
6982 		name_len = strlen(name);
6983 
6984 		ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
6985 		idx += name_len + 1;
6986 
6987 		/*
6988 		 * CIFS does not support EA other than user.* namespace,
6989 		 * still keep the framework generic, to list other attrs
6990 		 * in future.
6991 		 */
6992 		if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
6993 			continue;
6994 
6995 		if (req->InputBufferLength &&
6996 		    strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
6997 			    ea_req->EaNameLength))
6998 			continue;
6999 
7000 		if (smb2_is_private_ea(&name[XATTR_USER_PREFIX_LEN],
7001 				       name_len - XATTR_USER_PREFIX_LEN))
7002 			continue;
7003 
7004 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
7005 			name_len -= XATTR_USER_PREFIX_LEN;
7006 
7007 		ptr = eainfo->name + name_len + 1;
7008 		buf_free_len -= (offsetof(struct smb2_ea_info, name) +
7009 				name_len + 1);
7010 		/* bailout if xattr can't fit in buf_free_len */
7011 		value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
7012 					       name, &buf);
7013 		if (value_len <= 0) {
7014 			rc = -ENOENT;
7015 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
7016 			goto out;
7017 		}
7018 
7019 		buf_free_len -= value_len;
7020 		if (buf_free_len < 0) {
7021 			kfree(buf);
7022 			break;
7023 		}
7024 
7025 		memcpy(ptr, buf, value_len);
7026 		kfree(buf);
7027 
7028 		ptr += value_len;
7029 		eainfo->Flags = 0;
7030 		eainfo->EaNameLength = name_len;
7031 
7032 		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
7033 			memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
7034 			       name_len);
7035 		else
7036 			memcpy(eainfo->name, name, name_len);
7037 
7038 		eainfo->name[name_len] = '\0';
7039 		eainfo->EaValueLength = cpu_to_le16(value_len);
7040 		next_offset = offsetof(struct smb2_ea_info, name) +
7041 			name_len + 1 + value_len;
7042 
7043 		/* align next xattr entry at 4 byte bundary */
7044 		alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
7045 		if (alignment_bytes) {
7046 			if (buf_free_len < alignment_bytes)
7047 				break;
7048 			memset(ptr, '\0', alignment_bytes);
7049 			ptr += alignment_bytes;
7050 			next_offset += alignment_bytes;
7051 			buf_free_len -= alignment_bytes;
7052 		}
7053 		eainfo->NextEntryOffset = cpu_to_le32(next_offset);
7054 		prev_eainfo = eainfo;
7055 		eainfo = (struct smb2_ea_info *)ptr;
7056 		rsp_data_cnt += next_offset;
7057 
7058 		if (req->InputBufferLength) {
7059 			ksmbd_debug(SMB, "single entry requested\n");
7060 			break;
7061 		}
7062 	}
7063 
7064 	/* no more ea entries */
7065 	prev_eainfo->NextEntryOffset = 0;
7066 done:
7067 	rc = 0;
7068 	if (rsp_data_cnt == 0)
7069 		rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
7070 	rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
7071 out:
7072 	kvfree(xattr_list);
7073 	return rc;
7074 }
7075 
7076 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
7077 				 struct ksmbd_file *fp, void *rsp_org)
7078 {
7079 	struct smb2_file_access_info *file_info;
7080 
7081 	file_info = (struct smb2_file_access_info *)rsp->Buffer;
7082 	file_info->AccessFlags = fp->daccess;
7083 	rsp->OutputBufferLength =
7084 		cpu_to_le32(sizeof(struct smb2_file_access_info));
7085 }
7086 
7087 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
7088 			       struct ksmbd_file *fp, void *rsp_org)
7089 {
7090 	struct file_basic_info *basic_info;
7091 	struct kstat stat;
7092 	u64 time;
7093 	int ret;
7094 
7095 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
7096 		pr_err("no right to read the attributes : 0x%x\n",
7097 		       fp->daccess);
7098 		return -EACCES;
7099 	}
7100 
7101 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
7102 			  AT_STATX_SYNC_AS_STAT);
7103 	if (ret)
7104 		return ret;
7105 
7106 	basic_info = (struct file_basic_info *)rsp->Buffer;
7107 	basic_info->CreationTime = cpu_to_le64(fp->create_time);
7108 	time = ksmbd_UnixTimeToNT(stat.atime);
7109 	basic_info->LastAccessTime = cpu_to_le64(time);
7110 	time = ksmbd_UnixTimeToNT(stat.mtime);
7111 	basic_info->LastWriteTime = cpu_to_le64(time);
7112 	basic_info->ChangeTime = cpu_to_le64(fp->change_time);
7113 	basic_info->Attributes = fp->f_ci->m_fattr;
7114 	basic_info->Pad = 0;
7115 	rsp->OutputBufferLength =
7116 		cpu_to_le32(sizeof(struct file_basic_info));
7117 	return 0;
7118 }
7119 
7120 static int get_file_allocation_stat(struct ksmbd_file *fp, struct kstat *stat)
7121 {
7122 	int ret;
7123 
7124 	/*
7125 	 * Buffered writes can leave delayed allocation in a state where two
7126 	 * consecutive queries report different block counts even when the
7127 	 * second write only overwrites the first one. Complete writeback before
7128 	 * reporting the filesystem allocation for an ordinary open.
7129 	 */
7130 	if (!fp->allocation_size_set) {
7131 		ret = file_write_and_wait(fp->filp);
7132 		if (ret)
7133 			return ret;
7134 	}
7135 
7136 	ret = vfs_getattr(&fp->filp->f_path, stat, STATX_BASIC_STATS,
7137 			  AT_STATX_SYNC_AS_STAT);
7138 	if (!ret && !fp->allocation_size_set)
7139 		fp->allocation_size = S_ISDIR(stat->mode) ? 0 : stat->blocks << 9;
7140 
7141 	return ret;
7142 }
7143 
7144 static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
7145 				  struct ksmbd_file *fp, void *rsp_org)
7146 {
7147 	struct smb2_file_standard_info *sinfo;
7148 	unsigned int delete_pending;
7149 	struct kstat stat;
7150 	int ret;
7151 
7152 	ret = get_file_allocation_stat(fp, &stat);
7153 	if (ret)
7154 		return ret;
7155 
7156 	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
7157 	delete_pending = ksmbd_inode_pending_delete(fp);
7158 
7159 	if (ksmbd_stream_fd(fp) == false) {
7160 		sinfo->AllocationSize = cpu_to_le64(fp->allocation_size);
7161 		sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
7162 	} else {
7163 		loff_t seof = ksmbd_stream_eof(fp);
7164 
7165 		sinfo->AllocationSize = cpu_to_le64((u64)seof);
7166 		sinfo->EndOfFile = cpu_to_le64((u64)seof);
7167 	}
7168 	sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
7169 	sinfo->DeletePending = delete_pending;
7170 	sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
7171 	rsp->OutputBufferLength =
7172 		cpu_to_le32(sizeof(struct smb2_file_standard_info));
7173 
7174 	return 0;
7175 }
7176 
7177 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
7178 				    void *rsp_org)
7179 {
7180 	struct smb2_file_alignment_info *file_info;
7181 
7182 	file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
7183 	file_info->AlignmentRequirement = 0;
7184 	rsp->OutputBufferLength =
7185 		cpu_to_le32(sizeof(struct smb2_file_alignment_info));
7186 }
7187 
7188 static int get_file_all_info(struct ksmbd_work *work,
7189 			     struct smb2_query_info_rsp *rsp,
7190 			     struct ksmbd_file *fp,
7191 			     void *rsp_org)
7192 {
7193 	struct ksmbd_conn *conn = work->conn;
7194 	struct smb2_file_all_info *file_info;
7195 	unsigned int delete_pending;
7196 	struct kstat stat;
7197 	int conv_len;
7198 	char *filename;
7199 	u64 time;
7200 	int ret, buf_free_len, filename_len;
7201 
7202 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
7203 		ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
7204 			    fp->daccess);
7205 		return -EACCES;
7206 	}
7207 
7208 	filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
7209 	if (IS_ERR(filename))
7210 		return PTR_ERR(filename);
7211 
7212 	filename_len = strlen(filename);
7213 	buf_free_len = smb2_resp_buf_len(work,
7214 			offsetof(struct smb2_query_info_rsp, Buffer) +
7215 			offsetof(struct smb2_file_all_info, FileName));
7216 	if (buf_free_len < (filename_len + 1) * 2) {
7217 		kfree(filename);
7218 		return -EINVAL;
7219 	}
7220 
7221 	ret = get_file_allocation_stat(fp, &stat);
7222 	if (ret) {
7223 		kfree(filename);
7224 		return ret;
7225 	}
7226 
7227 	ksmbd_debug(SMB, "filename = %s\n", filename);
7228 	delete_pending = ksmbd_inode_pending_delete(fp);
7229 	file_info = (struct smb2_file_all_info *)rsp->Buffer;
7230 
7231 	file_info->CreationTime = cpu_to_le64(fp->create_time);
7232 	time = ksmbd_UnixTimeToNT(stat.atime);
7233 	file_info->LastAccessTime = cpu_to_le64(time);
7234 	time = ksmbd_UnixTimeToNT(stat.mtime);
7235 	file_info->LastWriteTime = cpu_to_le64(time);
7236 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
7237 	file_info->Attributes = fp->f_ci->m_fattr;
7238 	file_info->Pad1 = 0;
7239 	if (ksmbd_stream_fd(fp) == false) {
7240 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
7241 		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
7242 	} else {
7243 		loff_t seof = ksmbd_stream_eof(fp);
7244 
7245 		file_info->AllocationSize = cpu_to_le64((u64)seof);
7246 		file_info->EndOfFile = cpu_to_le64((u64)seof);
7247 	}
7248 	file_info->NumberOfLinks =
7249 			cpu_to_le32(get_nlink(&stat) - delete_pending);
7250 	file_info->DeletePending = delete_pending;
7251 	file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
7252 	file_info->Pad2 = 0;
7253 	file_info->IndexNumber = cpu_to_le64(stat.ino);
7254 	file_info->EASize = 0;
7255 	file_info->AccessFlags = fp->daccess;
7256 	if (ksmbd_stream_fd(fp) == false)
7257 		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
7258 	else
7259 		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
7260 	file_info->Mode = fp->coption;
7261 	file_info->AlignmentRequirement = 0;
7262 	conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
7263 				     min(filename_len, PATH_MAX),
7264 				     conn->local_nls, 0);
7265 	conv_len *= 2;
7266 	file_info->FileNameLength = cpu_to_le32(conv_len);
7267 	rsp->OutputBufferLength =
7268 		cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
7269 	kfree(filename);
7270 	return 0;
7271 }
7272 
7273 static void get_file_alternate_info(struct ksmbd_work *work,
7274 				    struct smb2_query_info_rsp *rsp,
7275 				    struct ksmbd_file *fp,
7276 				    void *rsp_org)
7277 {
7278 	struct ksmbd_conn *conn = work->conn;
7279 	struct smb2_file_name_info *file_info;
7280 	struct dentry *dentry = fp->filp->f_path.dentry;
7281 	int conv_len;
7282 
7283 	spin_lock(&dentry->d_lock);
7284 	file_info = (struct smb2_file_name_info *)rsp->Buffer;
7285 	conv_len = ksmbd_extract_shortname(conn,
7286 					   dentry->d_name.name,
7287 					   file_info->FileName);
7288 	spin_unlock(&dentry->d_lock);
7289 	file_info->FileNameLength = cpu_to_le32(conv_len);
7290 	rsp->OutputBufferLength =
7291 		cpu_to_le32(struct_size(file_info, FileName, conv_len));
7292 }
7293 
7294 static char *smb2_get_normalized_stream_name(struct ksmbd_file *fp)
7295 {
7296 	char *name, *stream_name = NULL, *xattr_list = NULL;
7297 	ssize_t xattr_list_len;
7298 
7299 	if (!ksmbd_stream_fd(fp))
7300 		return NULL;
7301 
7302 	xattr_list_len = ksmbd_vfs_listxattr(fp->filp->f_path.dentry,
7303 					     &xattr_list);
7304 	if (xattr_list_len <= 0)
7305 		goto out;
7306 
7307 	for (name = xattr_list; name - xattr_list < xattr_list_len;
7308 	     name += strlen(name) + 1) {
7309 		char *type;
7310 
7311 		if (strlen(name) + 1 != fp->stream.size ||
7312 		    strncasecmp(name, fp->stream.name, fp->stream.size - 1))
7313 			continue;
7314 
7315 		name += XATTR_NAME_STREAM_LEN;
7316 		type = strrchr(name, ':');
7317 		if (type)
7318 			stream_name = kstrndup(name, type - name,
7319 						  KSMBD_DEFAULT_GFP);
7320 		break;
7321 	}
7322 out:
7323 	kvfree(xattr_list);
7324 	return stream_name;
7325 }
7326 
7327 static int get_file_normalized_name_info(struct ksmbd_work *work,
7328 					 struct smb2_query_info_rsp *rsp,
7329 					 struct ksmbd_file *fp)
7330 {
7331 	struct smb2_file_name_info *file_info;
7332 	char *filename, *normalized, *stream_name;
7333 	int buf_free_len, conv_len, filename_len;
7334 
7335 	if (work->conn->dialect < SMB311_PROT_ID) {
7336 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7337 		return -EOPNOTSUPP;
7338 	}
7339 
7340 	filename = convert_to_nt_pathname(work->tcon->share_conf,
7341 					  &fp->filp->f_path);
7342 	if (IS_ERR(filename))
7343 		return PTR_ERR(filename);
7344 	if (filename[0] == '\\')
7345 		memmove(filename, filename + 1, strlen(filename));
7346 
7347 	stream_name = smb2_get_normalized_stream_name(fp);
7348 	normalized = kasprintf(KSMBD_DEFAULT_GFP, "%s%s%s", filename,
7349 			      stream_name ? ":" : "",
7350 			      stream_name ? stream_name : "");
7351 	kfree(stream_name);
7352 	kfree(filename);
7353 	if (!normalized)
7354 		return -ENOMEM;
7355 
7356 	filename_len = strlen(normalized);
7357 	buf_free_len = smb2_resp_buf_len(work, sizeof(*rsp) +
7358 					 sizeof(*file_info));
7359 	if (buf_free_len < 0 ||
7360 	    (size_t)buf_free_len < (filename_len + 1) * sizeof(__le16)) {
7361 		kfree(normalized);
7362 		return -EINVAL;
7363 	}
7364 
7365 	file_info = (struct smb2_file_name_info *)rsp->Buffer;
7366 	conv_len = smbConvertToUTF16((__le16 *)file_info->FileName,
7367 				     normalized, filename_len,
7368 				     work->conn->local_nls, 0);
7369 	kfree(normalized);
7370 	conv_len *= 2;
7371 	file_info->FileNameLength = cpu_to_le32(conv_len);
7372 	rsp->OutputBufferLength = cpu_to_le32(sizeof(*file_info) + conv_len);
7373 	return 0;
7374 }
7375 
7376 struct smb2_stream_info_buffer {
7377 	struct smb2_query_info_rsp *rsp;
7378 	struct smb2_file_stream_info *last;
7379 	const struct nls_table *local_nls;
7380 	unsigned int length;
7381 	unsigned int capacity;
7382 };
7383 
7384 static int smb2_add_stream_info(struct smb2_stream_info_buffer *buf,
7385 				const char *name, loff_t size, u64 allocation_size)
7386 {
7387 	struct smb2_file_stream_info *file_info;
7388 	__le16 *utf16_name;
7389 	size_t name_len = strlen(name);
7390 	unsigned int offset = ALIGN(buf->length, 8), name_bytes;
7391 	int conv_len, ret = 0;
7392 
7393 	if (offset > buf->capacity ||
7394 	    buf->capacity - offset < sizeof(*file_info))
7395 		return -ENOSPC;
7396 
7397 	utf16_name = kmalloc_array(name_len + 1, sizeof(*utf16_name),
7398 				   KSMBD_DEFAULT_GFP);
7399 	if (!utf16_name)
7400 		return -ENOMEM;
7401 
7402 	conv_len = smbConvertToUTF16(utf16_name, name, name_len,
7403 				     buf->local_nls, 0);
7404 	if (conv_len < 0) {
7405 		ret = conv_len;
7406 		goto out;
7407 	}
7408 
7409 	name_bytes = conv_len * sizeof(*utf16_name);
7410 	if (name_bytes > buf->capacity - offset - sizeof(*file_info)) {
7411 		ret = -ENOSPC;
7412 		goto out;
7413 	}
7414 
7415 	file_info = (struct smb2_file_stream_info *)&buf->rsp->Buffer[offset];
7416 	if (buf->last) {
7417 		memset(&buf->rsp->Buffer[buf->length], 0, offset - buf->length);
7418 		buf->last->NextEntryOffset =
7419 			cpu_to_le32((char *)file_info - (char *)buf->last);
7420 	}
7421 	file_info->NextEntryOffset = 0;
7422 	file_info->StreamNameLength = cpu_to_le32(name_bytes);
7423 	file_info->StreamSize = cpu_to_le64(size);
7424 	file_info->StreamAllocationSize = cpu_to_le64(allocation_size);
7425 	memcpy(file_info->StreamName, utf16_name, name_bytes);
7426 
7427 	buf->last = file_info;
7428 	buf->length = offset + sizeof(*file_info) + name_bytes;
7429 out:
7430 	kfree(utf16_name);
7431 	return ret;
7432 }
7433 
7434 static int get_file_stream_info(struct ksmbd_work *work,
7435 				struct smb2_query_info_req *req,
7436 				struct smb2_query_info_rsp *rsp,
7437 				struct ksmbd_file *fp)
7438 {
7439 	struct smb2_stream_info_buffer buf = {
7440 		.rsp = rsp,
7441 		.local_nls = work->conn->local_nls,
7442 	};
7443 	char *stream_name, *xattr_list = NULL, *stream_buf;
7444 	struct kstat stat;
7445 	const struct path *path = &fp->filp->f_path;
7446 	ssize_t xattr_list_len;
7447 	ssize_t slen;
7448 	loff_t ssize;
7449 	unsigned int req_output_len = le32_to_cpu(req->OutputBufferLength);
7450 	int streamlen, idx = 0;
7451 	int buf_free_len;
7452 	int ret;
7453 
7454 	if (req_output_len < FILE_STREAM_INFORMATION_SIZE) {
7455 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
7456 		return -EINVAL;
7457 	}
7458 
7459 	buf_free_len = smb2_calc_max_out_buf_len(work,
7460 						 offsetof(struct smb2_query_info_rsp, Buffer),
7461 						 req_output_len);
7462 	if (buf_free_len < 0)
7463 		return buf_free_len;
7464 	buf.capacity = buf_free_len;
7465 
7466 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
7467 			  AT_STATX_SYNC_AS_STAT);
7468 	if (ret)
7469 		return ret;
7470 
7471 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
7472 	if (xattr_list_len < 0) {
7473 		goto default_stream;
7474 	} else if (!xattr_list_len) {
7475 		ksmbd_debug(SMB, "empty xattr in the file\n");
7476 		goto default_stream;
7477 	}
7478 
7479 	while (idx < xattr_list_len) {
7480 		stream_name = xattr_list + idx;
7481 		streamlen = strlen(stream_name);
7482 		idx += streamlen + 1;
7483 
7484 		ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
7485 
7486 		if (strncmp(stream_name, XATTR_NAME_STREAM,
7487 			    XATTR_NAME_STREAM_LEN))
7488 			continue;
7489 
7490 		stream_buf = kasprintf(KSMBD_DEFAULT_GFP, ":%s",
7491 				       &stream_name[XATTR_NAME_STREAM_LEN]);
7492 		if (!stream_buf) {
7493 			ret = -ENOMEM;
7494 			goto out;
7495 		}
7496 		slen = ksmbd_vfs_xattr_len(file_mnt_idmap(fp->filp),
7497 					   path->dentry, stream_name);
7498 		ssize = slen < 0 ? 0 : (loff_t)slen;
7499 		ret = smb2_add_stream_info(&buf, stream_buf, ssize, ssize);
7500 		kfree(stream_buf);
7501 		if (ret == -ENOSPC)
7502 			goto overflow;
7503 		if (ret)
7504 			goto out;
7505 	}
7506 
7507 default_stream:
7508 	if (!S_ISDIR(stat.mode)) {
7509 		ret = smb2_add_stream_info(&buf, "::$DATA", stat.size,
7510 					   stat.blocks << 9);
7511 		if (ret == -ENOSPC)
7512 			goto overflow;
7513 		if (ret)
7514 			goto out;
7515 	}
7516 
7517 	ret = 0;
7518 	goto out;
7519 
7520 overflow:
7521 	rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7522 	/* An empty overflow needs an SMB2 error response. */
7523 	ret = buf.length ? 0 : -EOVERFLOW;
7524 out:
7525 	if (!ret)
7526 		rsp->OutputBufferLength = cpu_to_le32(buf.length);
7527 	kvfree(xattr_list);
7528 	return ret;
7529 }
7530 
7531 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
7532 				  struct ksmbd_file *fp, void *rsp_org)
7533 {
7534 	struct smb2_file_internal_info *file_info;
7535 	struct kstat stat;
7536 	int ret;
7537 
7538 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
7539 			  AT_STATX_SYNC_AS_STAT);
7540 	if (ret)
7541 		return ret;
7542 
7543 	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
7544 	file_info->IndexNumber = cpu_to_le64(stat.ino);
7545 	rsp->OutputBufferLength =
7546 		cpu_to_le32(sizeof(struct smb2_file_internal_info));
7547 
7548 	return 0;
7549 }
7550 
7551 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
7552 				      struct ksmbd_file *fp, void *rsp_org)
7553 {
7554 	struct smb2_file_network_open_info *file_info;
7555 	struct kstat stat;
7556 	u64 time;
7557 	int ret;
7558 
7559 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
7560 		pr_err("no right to read the attributes : 0x%x\n",
7561 		       fp->daccess);
7562 		return -EACCES;
7563 	}
7564 
7565 	ret = get_file_allocation_stat(fp, &stat);
7566 	if (ret)
7567 		return ret;
7568 
7569 	file_info = (struct smb2_file_network_open_info *)rsp->Buffer;
7570 
7571 	file_info->CreationTime = cpu_to_le64(fp->create_time);
7572 	time = ksmbd_UnixTimeToNT(stat.atime);
7573 	file_info->LastAccessTime = cpu_to_le64(time);
7574 	time = ksmbd_UnixTimeToNT(stat.mtime);
7575 	file_info->LastWriteTime = cpu_to_le64(time);
7576 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
7577 	file_info->Attributes = fp->f_ci->m_fattr;
7578 	if (ksmbd_stream_fd(fp) == false) {
7579 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
7580 		file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
7581 	} else {
7582 		loff_t seof = ksmbd_stream_eof(fp);
7583 
7584 		file_info->AllocationSize = cpu_to_le64((u64)seof);
7585 		file_info->EndOfFile = cpu_to_le64((u64)seof);
7586 	}
7587 	file_info->Reserved = cpu_to_le32(0);
7588 	rsp->OutputBufferLength =
7589 		cpu_to_le32(sizeof(struct smb2_file_network_open_info));
7590 	return 0;
7591 }
7592 
7593 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
7594 {
7595 	struct smb2_file_ea_info *file_info;
7596 
7597 	file_info = (struct smb2_file_ea_info *)rsp->Buffer;
7598 	file_info->EASize = 0;
7599 	rsp->OutputBufferLength =
7600 		cpu_to_le32(sizeof(struct smb2_file_ea_info));
7601 }
7602 
7603 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
7604 				   struct ksmbd_file *fp, void *rsp_org)
7605 {
7606 	struct smb2_file_pos_info *file_info;
7607 
7608 	file_info = (struct smb2_file_pos_info *)rsp->Buffer;
7609 	if (ksmbd_stream_fd(fp) == false)
7610 		file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
7611 	else
7612 		file_info->CurrentByteOffset = cpu_to_le64(fp->stream.pos);
7613 
7614 	rsp->OutputBufferLength =
7615 		cpu_to_le32(sizeof(struct smb2_file_pos_info));
7616 }
7617 
7618 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
7619 			       struct ksmbd_file *fp, void *rsp_org)
7620 {
7621 	struct smb2_file_mode_info *file_info;
7622 
7623 	file_info = (struct smb2_file_mode_info *)rsp->Buffer;
7624 	file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
7625 	rsp->OutputBufferLength =
7626 		cpu_to_le32(sizeof(struct smb2_file_mode_info));
7627 }
7628 
7629 static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
7630 				     struct ksmbd_file *fp, void *rsp_org)
7631 {
7632 	struct smb2_file_comp_info *file_info;
7633 	struct kstat stat;
7634 	u16 fmt;
7635 	int ret;
7636 
7637 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
7638 			  AT_STATX_SYNC_AS_STAT);
7639 	if (ret)
7640 		return ret;
7641 
7642 	ret = ksmbd_vfs_get_compression(fp, &fmt);
7643 	if (ret)
7644 		return ret;
7645 
7646 	file_info = (struct smb2_file_comp_info *)rsp->Buffer;
7647 	file_info->CompressedFileSize = cpu_to_le64(min_t(u64, stat.blocks << 9, stat.size));
7648 	file_info->CompressionFormat = cpu_to_le16(fmt);
7649 	file_info->CompressionUnitShift = 0;
7650 	file_info->ChunkShift = 0;
7651 	file_info->ClusterShift = 0;
7652 	memset(&file_info->Reserved[0], 0, 3);
7653 
7654 	rsp->OutputBufferLength =
7655 		cpu_to_le32(sizeof(struct smb2_file_comp_info));
7656 
7657 	return 0;
7658 }
7659 
7660 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
7661 				       struct ksmbd_file *fp, void *rsp_org)
7662 {
7663 	struct smb2_file_attr_tag_info *file_info;
7664 
7665 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
7666 		pr_err("no right to read the attributes : 0x%x\n",
7667 		       fp->daccess);
7668 		return -EACCES;
7669 	}
7670 
7671 	file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
7672 	file_info->FileAttributes = fp->f_ci->m_fattr;
7673 	file_info->ReparseTag = 0;
7674 	rsp->OutputBufferLength =
7675 		cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
7676 	return 0;
7677 }
7678 
7679 static int find_file_posix_info(struct ksmbd_work *work,
7680 				struct smb2_query_info_req *req,
7681 				struct smb2_query_info_rsp *rsp,
7682 				struct ksmbd_file *fp)
7683 {
7684 	struct smb311_posix_qinfo *file_info;
7685 	struct inode *inode = file_inode(fp->filp);
7686 	const struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
7687 	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
7688 	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
7689 	struct kstat stat;
7690 	char *filename;
7691 	__le16 *utf16_name;
7692 	__le32 *filename_len;
7693 	size_t name_bytes;
7694 	u64 time;
7695 	int fixed_len = sizeof(struct smb311_posix_qinfo) + 32 + sizeof(__le32);
7696 	int max_len, conv_len, ret;
7697 
7698 	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
7699 		pr_err("no right to read the attributes : 0x%x\n",
7700 		       fp->daccess);
7701 		return -EACCES;
7702 	}
7703 
7704 	ret = get_file_allocation_stat(fp, &stat);
7705 	if (ret)
7706 		return ret;
7707 	max_len = smb2_calc_max_out_buf_len(work,
7708 			offsetof(struct smb2_query_info_rsp, Buffer),
7709 			le32_to_cpu(req->OutputBufferLength));
7710 	if (max_len < fixed_len) {
7711 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
7712 		return -EINVAL;
7713 	}
7714 	filename = convert_to_nt_pathname(work->tcon->share_conf,
7715 					   &fp->filp->f_path);
7716 	if (IS_ERR(filename))
7717 		return PTR_ERR(filename);
7718 	if (filename[0] == '\\')
7719 		memmove(filename, filename + 1, strlen(filename));
7720 	name_bytes = strlen(filename);
7721 	utf16_name = kmalloc_array(name_bytes + 1, sizeof(*utf16_name),
7722 				    KSMBD_DEFAULT_GFP);
7723 	if (!utf16_name) {
7724 		kfree(filename);
7725 		return -ENOMEM;
7726 	}
7727 	conv_len = smbConvertToUTF16(utf16_name, filename, name_bytes,
7728 				      work->conn->local_nls, 0);
7729 	kfree(filename);
7730 	if (conv_len < 0) {
7731 		kfree(utf16_name);
7732 		return conv_len;
7733 	}
7734 	if (conv_len > (max_len - fixed_len) / sizeof(*utf16_name)) {
7735 		kfree(utf16_name);
7736 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
7737 		return -EINVAL;
7738 	}
7739 
7740 	file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
7741 	file_info->CreationTime = cpu_to_le64(fp->create_time);
7742 	time = ksmbd_UnixTimeToNT(stat.atime);
7743 	file_info->LastAccessTime = cpu_to_le64(time);
7744 	time = ksmbd_UnixTimeToNT(stat.mtime);
7745 	file_info->LastWriteTime = cpu_to_le64(time);
7746 	file_info->ChangeTime = cpu_to_le64(fp->change_time);
7747 	file_info->DosAttributes = fp->f_ci->m_fattr;
7748 	file_info->Inode = cpu_to_le64(stat.ino);
7749 	if (ksmbd_stream_fd(fp) == false) {
7750 		file_info->EndOfFile = cpu_to_le64(stat.size);
7751 		file_info->AllocationSize = cpu_to_le64(fp->allocation_size);
7752 	} else {
7753 		loff_t seof = ksmbd_stream_eof(fp);
7754 
7755 		file_info->EndOfFile = cpu_to_le64((u64)seof);
7756 		file_info->AllocationSize = cpu_to_le64((u64)seof);
7757 	}
7758 	file_info->HardLinks = cpu_to_le32(stat.nlink);
7759 	file_info->Mode = cpu_to_le32(stat.mode & 07777);
7760 	switch (stat.mode & S_IFMT) {
7761 	case S_IFDIR:
7762 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_DIR << POSIX_FILETYPE_SHIFT);
7763 		break;
7764 	case S_IFLNK:
7765 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SYMLINK << POSIX_FILETYPE_SHIFT);
7766 		break;
7767 	case S_IFCHR:
7768 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_CHARDEV << POSIX_FILETYPE_SHIFT);
7769 		break;
7770 	case S_IFBLK:
7771 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_BLKDEV << POSIX_FILETYPE_SHIFT);
7772 		break;
7773 	case S_IFIFO:
7774 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_FIFO << POSIX_FILETYPE_SHIFT);
7775 		break;
7776 	case S_IFSOCK:
7777 		file_info->Mode |= cpu_to_le32(POSIX_TYPE_SOCKET << POSIX_FILETYPE_SHIFT);
7778 	}
7779 
7780 	file_info->DeviceId = cpu_to_le32(stat.dev);
7781 	file_info->Zero = 0;
7782 	file_info->ReparseTag = smb2_get_reparse_tag_special_file(stat.mode);
7783 	if (file_info->ReparseTag)
7784 		file_info->DosAttributes |= FILE_ATTRIBUTE_REPARSE_POINT_LE;
7785 
7786 	/*
7787 	 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
7788 	 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
7789 	 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
7790 	 */
7791 	id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
7792 		  SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
7793 	id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
7794 		  SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
7795 	filename_len = (__le32 *)&file_info->Sids[32];
7796 	memcpy(&file_info->Sids[36], utf16_name,
7797 	       conv_len * sizeof(*utf16_name));
7798 	kfree(utf16_name);
7799 	*filename_len = cpu_to_le32(conv_len * sizeof(__le16));
7800 
7801 	rsp->OutputBufferLength = cpu_to_le32(fixed_len +
7802 					       conv_len * sizeof(__le16));
7803 
7804 	return 0;
7805 }
7806 
7807 static int smb2_get_info_file(struct ksmbd_work *work,
7808 			      struct smb2_query_info_req *req,
7809 			      struct smb2_query_info_rsp *rsp)
7810 {
7811 	struct ksmbd_file *fp;
7812 	int fileinfoclass = 0;
7813 	int rc = 0;
7814 	unsigned int fixed_len, req_output_len;
7815 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
7816 
7817 	if (test_share_config_flag(work->tcon->share_conf,
7818 				   KSMBD_SHARE_FLAG_PIPE)) {
7819 		/* smb2 info file called for pipe */
7820 		rc = smb2_get_info_file_pipe(work->sess, req, rsp);
7821 		goto iov_pin_out;
7822 	}
7823 
7824 	if (work->next_smb2_rcv_hdr_off) {
7825 		if (!has_file_id(req->VolatileFileId)) {
7826 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7827 				    work->compound_fid);
7828 			id = work->compound_fid;
7829 			pid = work->compound_pfid;
7830 		}
7831 	}
7832 
7833 	if (!has_file_id(id)) {
7834 		id = req->VolatileFileId;
7835 		pid = req->PersistentFileId;
7836 	}
7837 
7838 	fp = ksmbd_lookup_fd_slow(work, id, pid);
7839 	if (!fp)
7840 		return -ENOENT;
7841 
7842 	fileinfoclass = req->FileInfoClass;
7843 
7844 	switch (fileinfoclass) {
7845 	case FILE_ACCESS_INFORMATION:
7846 		get_file_access_info(rsp, fp, work->response_buf);
7847 		break;
7848 
7849 	case FILE_BASIC_INFORMATION:
7850 		rc = get_file_basic_info(rsp, fp, work->response_buf);
7851 		break;
7852 
7853 	case FILE_STANDARD_INFORMATION:
7854 		rc = get_file_standard_info(rsp, fp, work->response_buf);
7855 		break;
7856 
7857 	case FILE_ALIGNMENT_INFORMATION:
7858 		get_file_alignment_info(rsp, work->response_buf);
7859 		break;
7860 
7861 	case FILE_ALL_INFORMATION:
7862 		rc = get_file_all_info(work, rsp, fp, work->response_buf);
7863 		break;
7864 
7865 	case FILE_ALTERNATE_NAME_INFORMATION:
7866 		get_file_alternate_info(work, rsp, fp, work->response_buf);
7867 		break;
7868 	case FILE_NORMALIZED_NAME_INFORMATION:
7869 		rc = get_file_normalized_name_info(work, rsp, fp);
7870 		break;
7871 
7872 	case FILE_STREAM_INFORMATION:
7873 		rc = get_file_stream_info(work, req, rsp, fp);
7874 		break;
7875 
7876 	case FILE_INTERNAL_INFORMATION:
7877 		rc = get_file_internal_info(rsp, fp, work->response_buf);
7878 		break;
7879 
7880 	case FILE_NETWORK_OPEN_INFORMATION:
7881 		rc = get_file_network_open_info(rsp, fp, work->response_buf);
7882 		break;
7883 
7884 	case FILE_EA_INFORMATION:
7885 		get_file_ea_info(rsp, work->response_buf);
7886 		break;
7887 
7888 	case FILE_FULL_EA_INFORMATION:
7889 		rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
7890 		break;
7891 
7892 	case FILE_POSITION_INFORMATION:
7893 		get_file_position_info(rsp, fp, work->response_buf);
7894 		break;
7895 
7896 	case FILE_MODE_INFORMATION:
7897 		get_file_mode_info(rsp, fp, work->response_buf);
7898 		break;
7899 
7900 	case FILE_COMPRESSION_INFORMATION:
7901 		rc = get_file_compression_info(rsp, fp, work->response_buf);
7902 		break;
7903 
7904 	case FILE_ATTRIBUTE_TAG_INFORMATION:
7905 		rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
7906 		break;
7907 	case SMB_FIND_FILE_POSIX_INFO:
7908 		if (work->conn->dialect != SMB311_PROT_ID ||
7909 		    !work->tcon->posix_extensions || !fp->is_posix_ctxt) {
7910 			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
7911 			rc = -EOPNOTSUPP;
7912 		} else {
7913 			rc = find_file_posix_info(work, req, rsp, fp);
7914 		}
7915 		break;
7916 	default:
7917 		ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
7918 			    fileinfoclass);
7919 		rc = -EOPNOTSUPP;
7920 	}
7921 	if (!rc) {
7922 		req_output_len = le32_to_cpu(req->OutputBufferLength);
7923 		fixed_len = le32_to_cpu(rsp->OutputBufferLength);
7924 		switch (fileinfoclass) {
7925 		case FILE_ALL_INFORMATION:
7926 			fixed_len = FILE_ALL_INFORMATION_SIZE;
7927 			break;
7928 		case FILE_ALTERNATE_NAME_INFORMATION:
7929 			fixed_len = FILE_NAME_INFORMATION_SIZE;
7930 			break;
7931 		case FILE_NORMALIZED_NAME_INFORMATION:
7932 			fixed_len = FILE_NAME_INFORMATION_SIZE;
7933 			req_output_len = round_down(req_output_len, 2);
7934 			break;
7935 		case FILE_STREAM_INFORMATION:
7936 			fixed_len = FILE_STREAM_INFORMATION_SIZE;
7937 			break;
7938 		}
7939 		rc = buffer_check_err(req_output_len, fixed_len, rsp);
7940 	}
7941 	ksmbd_fd_put(work, fp);
7942 
7943 iov_pin_out:
7944 	if (!rc)
7945 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
7946 				offsetof(struct smb2_query_info_rsp, Buffer) +
7947 				le32_to_cpu(rsp->OutputBufferLength));
7948 	return rc;
7949 }
7950 
7951 static int smb2_get_info_filesystem(struct ksmbd_work *work,
7952 				    struct smb2_query_info_req *req,
7953 				    struct smb2_query_info_rsp *rsp)
7954 {
7955 	struct ksmbd_conn *conn = work->conn;
7956 	struct ksmbd_share_config *share = work->tcon->share_conf;
7957 	struct ksmbd_file *fp;
7958 	int fsinfoclass = 0;
7959 	struct kstatfs stfs;
7960 	struct path path;
7961 	int rc = 0, len;
7962 	unsigned int fixed_len = 0;
7963 	u64 id, pid;
7964 
7965 	if (req->FileInfoClass == FS_POSIX_INFORMATION) {
7966 		if (conn->dialect != SMB311_PROT_ID ||
7967 		    !work->tcon->posix_extensions) {
7968 			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
7969 			return -EOPNOTSUPP;
7970 		}
7971 		id = req->VolatileFileId;
7972 		pid = req->PersistentFileId;
7973 		if (work->next_smb2_rcv_hdr_off && !has_file_id(id)) {
7974 			id = work->compound_fid;
7975 			pid = work->compound_pfid;
7976 		}
7977 		fp = ksmbd_lookup_fd_slow(work, id, pid);
7978 		if (!fp)
7979 			return -ENOENT;
7980 		if (!fp->is_posix_ctxt) {
7981 			ksmbd_fd_put(work, fp);
7982 			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
7983 			return -EOPNOTSUPP;
7984 		}
7985 		path = fp->filp->f_path;
7986 		path_get(&path);
7987 		ksmbd_fd_put(work, fp);
7988 	} else {
7989 		if (!share->path)
7990 			return -EIO;
7991 
7992 		scoped_with_init_fs()
7993 			rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
7994 		if (rc) {
7995 			pr_err("cannot create vfs path\n");
7996 			return -EIO;
7997 		}
7998 	}
7999 
8000 	rc = vfs_statfs(&path, &stfs);
8001 	if (rc) {
8002 		pr_err("cannot do stat of path %s\n", share->path);
8003 		path_put(&path);
8004 		return -EIO;
8005 	}
8006 
8007 	fsinfoclass = req->FileInfoClass;
8008 
8009 	switch (fsinfoclass) {
8010 	case FS_DEVICE_INFORMATION:
8011 	{
8012 		FILE_SYSTEM_DEVICE_INFO *info;
8013 
8014 		info = (FILE_SYSTEM_DEVICE_INFO *)rsp->Buffer;
8015 
8016 		info->DeviceType = cpu_to_le32(FILE_DEVICE_DISK);
8017 		info->DeviceCharacteristics =
8018 			cpu_to_le32(FILE_DEVICE_IS_MOUNTED);
8019 		if (!test_tree_conn_flag(work->tcon,
8020 					 KSMBD_TREE_CONN_FLAG_WRITABLE))
8021 			info->DeviceCharacteristics |=
8022 				cpu_to_le32(FILE_READ_ONLY_DEVICE);
8023 		rsp->OutputBufferLength = cpu_to_le32(8);
8024 		fixed_len = 8;
8025 		break;
8026 	}
8027 	case FS_ATTRIBUTE_INFORMATION:
8028 	{
8029 		FILE_SYSTEM_ATTRIBUTE_INFO *info;
8030 		struct file_kattr fa = {};
8031 		size_t sz;
8032 		u32 attrs;
8033 		int err;
8034 
8035 		info = (FILE_SYSTEM_ATTRIBUTE_INFO *)rsp->Buffer;
8036 		attrs = FILE_SUPPORTS_OBJECT_IDS |
8037 			FILE_PERSISTENT_ACLS |
8038 			FILE_UNICODE_ON_DISK |
8039 			FILE_FILE_COMPRESSION |
8040 			FILE_SUPPORTS_SPARSE_FILES |
8041 			FILE_SUPPORTS_BLOCK_REFCOUNTING;
8042 
8043 		err = vfs_fileattr_get(path.dentry, &fa);
8044 		/*
8045 		 * -EINVAL, -EOPNOTSUPP: ntfs-3g and other FUSE
8046 		 * filesystems that lack FS_IOC_FSGETXATTR support.
8047 		 */
8048 		if (err && err != -ENOIOCTLCMD && err != -ENOTTY &&
8049 		    err != -EINVAL && err != -EOPNOTSUPP) {
8050 			path_put(&path);
8051 			return err;
8052 		}
8053 		if (!(fa.fsx_xflags & FS_XFLAG_CASEFOLD))
8054 			attrs |= FILE_CASE_SENSITIVE_SEARCH;
8055 		if (!(fa.fsx_xflags & FS_XFLAG_CASENONPRESERVING))
8056 			attrs |= FILE_CASE_PRESERVED_NAMES;
8057 
8058 		info->Attributes = cpu_to_le32(attrs);
8059 		info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
8060 
8061 		if (test_share_config_flag(work->tcon->share_conf,
8062 		    KSMBD_SHARE_FLAG_STREAMS))
8063 			info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
8064 
8065 		info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
8066 		/*
8067 		 * some application(potableapp) can not run on ksmbd share
8068 		 * because only NTFS handle security setting on windows.
8069 		 * So Although local fs(EXT4 or F2fs, etc) is not NTFS,
8070 		 * ksmbd should show share as NTFS. Later, If needed, we can add
8071 		 * fs type(s) parameter to change fs type user wanted.
8072 		 */
8073 		len = smbConvertToUTF16((__le16 *)info->FileSystemName,
8074 					"NTFS", PATH_MAX, conn->local_nls, 0);
8075 		len = len * 2;
8076 		info->FileSystemNameLen = cpu_to_le32(len);
8077 		sz = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO) + len;
8078 		rsp->OutputBufferLength = cpu_to_le32(sz);
8079 		fixed_len = 16;
8080 		break;
8081 	}
8082 	case FS_VOLUME_INFORMATION:
8083 	{
8084 		struct filesystem_vol_info *info;
8085 		size_t sz;
8086 		unsigned int serial_crc = 0;
8087 
8088 		info = (struct filesystem_vol_info *)(rsp->Buffer);
8089 		info->VolumeCreationTime = 0;
8090 		serial_crc = crc32_le(serial_crc, share->name,
8091 				      strlen(share->name));
8092 		serial_crc = crc32_le(serial_crc, share->path,
8093 				      strlen(share->path));
8094 		serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
8095 				      strlen(ksmbd_netbios_name()));
8096 		/* Taking dummy value of serial number*/
8097 		info->VolumeSerialNumber = cpu_to_le32(serial_crc);
8098 		len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
8099 					share->name, PATH_MAX,
8100 					conn->local_nls, 0);
8101 		len = len * 2;
8102 		info->VolumeLabelLength = cpu_to_le32(len);
8103 		info->Reserved = 0;
8104 		info->SupportsObjects = 0;
8105 		sz = sizeof(struct filesystem_vol_info) + len;
8106 		rsp->OutputBufferLength = cpu_to_le32(sz);
8107 		fixed_len = 24;
8108 		break;
8109 	}
8110 	case FS_SIZE_INFORMATION:
8111 	{
8112 		FILE_SYSTEM_SIZE_INFO *info;
8113 
8114 		info = (FILE_SYSTEM_SIZE_INFO *)(rsp->Buffer);
8115 		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
8116 		info->AvailableAllocationUnits = cpu_to_le64(stfs.f_bfree);
8117 		info->SectorsPerAllocationUnit = cpu_to_le32(1);
8118 		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
8119 		rsp->OutputBufferLength = cpu_to_le32(24);
8120 		fixed_len = 24;
8121 		break;
8122 	}
8123 	case FS_FULL_SIZE_INFORMATION:
8124 	{
8125 		struct smb2_fs_full_size_info *info;
8126 
8127 		info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
8128 		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
8129 		info->CallerAvailableAllocationUnits =
8130 					cpu_to_le64(stfs.f_bavail);
8131 		info->ActualAvailableAllocationUnits =
8132 					cpu_to_le64(stfs.f_bfree);
8133 		info->SectorsPerAllocationUnit = cpu_to_le32(1);
8134 		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
8135 		rsp->OutputBufferLength = cpu_to_le32(32);
8136 		fixed_len = 32;
8137 		break;
8138 	}
8139 	case FS_OBJECT_ID_INFORMATION:
8140 	{
8141 		struct object_id_info *info;
8142 
8143 		info = (struct object_id_info *)(rsp->Buffer);
8144 		memset(info, 0, sizeof(*info));
8145 
8146 		if (path.mnt->mnt_sb->s_uuid_len == 16)
8147 			memcpy(info->objid, path.mnt->mnt_sb->s_uuid.b,
8148 					path.mnt->mnt_sb->s_uuid_len);
8149 		else
8150 			memcpy(info->objid, &stfs.f_fsid, sizeof(stfs.f_fsid));
8151 
8152 		info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
8153 		info->extended_info.version = cpu_to_le32(1);
8154 		info->extended_info.release = cpu_to_le32(1);
8155 		info->extended_info.rel_date = 0;
8156 		memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
8157 		rsp->OutputBufferLength = cpu_to_le32(64);
8158 		fixed_len = 64;
8159 		break;
8160 	}
8161 	case FS_SECTOR_SIZE_INFORMATION:
8162 	{
8163 		struct smb3_fs_ss_info *info;
8164 		unsigned int sector_size =
8165 			min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
8166 
8167 		info = (struct smb3_fs_ss_info *)(rsp->Buffer);
8168 
8169 		info->LogicalBytesPerSector = cpu_to_le32(sector_size);
8170 		info->PhysicalBytesPerSectorForAtomicity =
8171 				cpu_to_le32(sector_size);
8172 		info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
8173 		info->FSEffPhysicalBytesPerSectorForAtomicity =
8174 				cpu_to_le32(sector_size);
8175 		info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
8176 				    SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE |
8177 				    SSINFO_FLAGS_TRIM_ENABLED);
8178 		info->ByteOffsetForSectorAlignment = 0;
8179 		info->ByteOffsetForPartitionAlignment = 0;
8180 		rsp->OutputBufferLength = cpu_to_le32(28);
8181 		fixed_len = 28;
8182 		break;
8183 	}
8184 	case FS_CONTROL_INFORMATION:
8185 	{
8186 		/*
8187 		 * TODO : The current implementation is based on
8188 		 * test result with win7(NTFS) server. It's need to
8189 		 * modify this to get valid Quota values
8190 		 * from Linux kernel
8191 		 */
8192 		struct smb2_fs_control_info *info;
8193 
8194 		info = (struct smb2_fs_control_info *)(rsp->Buffer);
8195 		info->FreeSpaceStartFiltering = 0;
8196 		info->FreeSpaceThreshold = 0;
8197 		info->FreeSpaceStopFiltering = 0;
8198 		info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
8199 		info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
8200 		info->FileSystemControlFlags = 0;
8201 		info->Padding = 0;
8202 		rsp->OutputBufferLength = cpu_to_le32(48);
8203 		fixed_len = 48;
8204 		break;
8205 	}
8206 	case FS_POSIX_INFORMATION:
8207 	{
8208 		FILE_SYSTEM_POSIX_INFO *info;
8209 
8210 		info = (FILE_SYSTEM_POSIX_INFO *)(rsp->Buffer);
8211 		info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
8212 		info->BlockSize = cpu_to_le32(stfs.f_frsize ?: stfs.f_bsize);
8213 		info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
8214 		info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
8215 		info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
8216 		info->TotalFileNodes = cpu_to_le64(stfs.f_files);
8217 		info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
8218 		info->FileSysIdentifier =
8219 			cpu_to_le64((u64)(u32)stfs.f_fsid.val[1] << 32 |
8220 				    (u32)stfs.f_fsid.val[0]);
8221 		rsp->OutputBufferLength = cpu_to_le32(sizeof(*info));
8222 		fixed_len = sizeof(*info);
8223 		break;
8224 	}
8225 	default:
8226 		path_put(&path);
8227 		return -EOPNOTSUPP;
8228 	}
8229 	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
8230 			      fixed_len,
8231 			      rsp);
8232 	path_put(&path);
8233 
8234 	if (!rc)
8235 		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
8236 				offsetof(struct smb2_query_info_rsp, Buffer) +
8237 				le32_to_cpu(rsp->OutputBufferLength));
8238 	return rc;
8239 }
8240 
8241 static int smb2_get_info_sec(struct ksmbd_work *work,
8242 			     struct smb2_query_info_req *req,
8243 			     struct smb2_query_info_rsp *rsp)
8244 {
8245 	struct ksmbd_file *fp;
8246 	const struct mnt_idmap *idmap;
8247 	struct smb_ntsd *pntsd = NULL, *ppntsd = NULL;
8248 	struct smb_fattr fattr = {{0}};
8249 	struct inode *inode;
8250 	__u32 secdesclen = 0;
8251 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
8252 	int addition_info = le32_to_cpu(req->AdditionalInformation);
8253 	int rc = 0, ppntsd_size = 0, max_len;
8254 	size_t scratch_len = 0;
8255 
8256 	if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
8257 			      PROTECTED_DACL_SECINFO |
8258 			      UNPROTECTED_DACL_SECINFO)) {
8259 		ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
8260 		       addition_info);
8261 
8262 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8263 		return -EINVAL;
8264 	}
8265 
8266 	if (work->next_smb2_rcv_hdr_off) {
8267 		if (!has_file_id(req->VolatileFileId)) {
8268 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
8269 				    work->compound_fid);
8270 			id = work->compound_fid;
8271 			pid = work->compound_pfid;
8272 		}
8273 	}
8274 
8275 	if (!has_file_id(id)) {
8276 		id = req->VolatileFileId;
8277 		pid = req->PersistentFileId;
8278 	}
8279 
8280 	fp = ksmbd_lookup_fd_slow(work, id, pid);
8281 	if (!fp)
8282 		return -ENOENT;
8283 
8284 	if (addition_info & (OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO) &&
8285 	    !(fp->daccess & FILE_READ_CONTROL_LE)) {
8286 		ksmbd_fd_put(work, fp);
8287 		return -EACCES;
8288 	}
8289 
8290 	if (le32_to_cpu(req->OutputBufferLength) < sizeof(struct smb_ntsd)) {
8291 		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
8292 		ksmbd_fd_put(work, fp);
8293 		return -ENOSPC;
8294 	}
8295 
8296 	idmap = file_mnt_idmap(fp->filp);
8297 	inode = file_inode(fp->filp);
8298 	rc = ksmbd_acls_fattr(&fattr, idmap, inode);
8299 	if (rc) {
8300 		ksmbd_fd_put(work, fp);
8301 		return rc;
8302 	}
8303 
8304 	if (test_share_config_flag(work->tcon->share_conf,
8305 				   KSMBD_SHARE_FLAG_ACL_XATTR))
8306 		ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
8307 						     fp->filp->f_path.dentry,
8308 						     &ppntsd);
8309 
8310 	/* Check if sd buffer size exceeds response buffer size */
8311 	max_len = smb2_calc_max_out_buf_len(work,
8312 			offsetof(struct smb2_query_info_rsp, Buffer),
8313 			le32_to_cpu(req->OutputBufferLength));
8314 	if (max_len < 0) {
8315 		rc = -EINVAL;
8316 		goto release_acl;
8317 	}
8318 
8319 	scratch_len = smb_acl_sec_desc_scratch_len(&fattr, ppntsd,
8320 			ppntsd_size, addition_info);
8321 	if (!scratch_len || scratch_len == SIZE_MAX) {
8322 		rc = -EFBIG;
8323 		goto release_acl;
8324 	}
8325 
8326 	pntsd = kvzalloc(scratch_len, KSMBD_DEFAULT_GFP);
8327 	if (!pntsd) {
8328 		rc = -ENOMEM;
8329 		goto release_acl;
8330 	}
8331 
8332 	rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
8333 			addition_info, &secdesclen, &fattr);
8334 
8335 release_acl:
8336 	posix_acl_release(fattr.cf_acls);
8337 	posix_acl_release(fattr.cf_dacls);
8338 	kfree(ppntsd);
8339 	ksmbd_fd_put(work, fp);
8340 
8341 	if (!rc && ALIGN(secdesclen, 8) > scratch_len)
8342 		rc = -EFBIG;
8343 	if (rc)
8344 		goto err_out;
8345 
8346 	rsp->OutputBufferLength = cpu_to_le32(secdesclen);
8347 	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
8348 			      le32_to_cpu(rsp->OutputBufferLength),
8349 			      rsp);
8350 	if (rc)
8351 		goto err_out;
8352 
8353 	rc = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
8354 			offsetof(struct smb2_query_info_rsp, Buffer),
8355 			pntsd, secdesclen);
8356 err_out:
8357 	if (rc) {
8358 		rsp->OutputBufferLength = 0;
8359 		kvfree(pntsd);
8360 	}
8361 
8362 	return rc;
8363 }
8364 
8365 /**
8366  * smb2_query_info() - handler for smb2 query info command
8367  * @work:	smb work containing query info request buffer
8368  *
8369  * Return:	0 on success, otherwise error
8370  */
8371 int smb2_query_info(struct ksmbd_work *work)
8372 {
8373 	struct smb2_query_info_req *req;
8374 	struct smb2_query_info_rsp *rsp;
8375 	int rc = 0;
8376 
8377 	ksmbd_debug(SMB, "Received request smb2 query info request\n");
8378 
8379 	WORK_BUFFERS(work, req, rsp);
8380 
8381 	if (smb2_compound_has_failed(work, &rsp->hdr))
8382 		return -EACCES;
8383 
8384 	if (ksmbd_override_fsids(work)) {
8385 		rc = -ENOMEM;
8386 		goto err_out;
8387 	}
8388 
8389 	rsp->StructureSize = cpu_to_le16(9);
8390 	rsp->OutputBufferOffset = cpu_to_le16(72);
8391 
8392 	switch (req->InfoType) {
8393 	case SMB2_O_INFO_FILE:
8394 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
8395 		rc = smb2_get_info_file(work, req, rsp);
8396 		break;
8397 	case SMB2_O_INFO_FILESYSTEM:
8398 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
8399 		rc = smb2_get_info_filesystem(work, req, rsp);
8400 		break;
8401 	case SMB2_O_INFO_SECURITY:
8402 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
8403 		rc = smb2_get_info_sec(work, req, rsp);
8404 		break;
8405 	default:
8406 		ksmbd_debug(SMB, "InfoType %d not supported yet\n",
8407 			    req->InfoType);
8408 		rc = -EOPNOTSUPP;
8409 	}
8410 	ksmbd_revert_fsids(work);
8411 
8412 err_out:
8413 	if (rc < 0) {
8414 		if (rc == -EACCES)
8415 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
8416 		else if (rc == -ENOENT)
8417 			rsp->hdr.Status = STATUS_FILE_CLOSED;
8418 		else if (rc == -EIO)
8419 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
8420 		else if (rc == -ENOMEM)
8421 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
8422 		else if (rc == -EINVAL && rsp->hdr.Status == 0)
8423 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8424 		else if (rsp->hdr.Status == 0)
8425 			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
8426 		smb2_set_err_rsp(work);
8427 
8428 		ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
8429 			    rc);
8430 		return rc;
8431 	}
8432 	return 0;
8433 }
8434 
8435 /**
8436  * smb2_close_pipe() - handler for closing IPC pipe
8437  * @work:	smb work containing close request buffer
8438  *
8439  * Return:	0
8440  */
8441 static noinline int smb2_close_pipe(struct ksmbd_work *work)
8442 {
8443 	u64 id;
8444 	struct smb2_close_req *req;
8445 	struct smb2_close_rsp *rsp;
8446 
8447 	WORK_BUFFERS(work, req, rsp);
8448 
8449 	id = req->VolatileFileId;
8450 	ksmbd_session_rpc_close(work->sess, id);
8451 
8452 	rsp->StructureSize = cpu_to_le16(60);
8453 	rsp->Flags = 0;
8454 	rsp->Reserved = 0;
8455 	rsp->CreationTime = 0;
8456 	rsp->LastAccessTime = 0;
8457 	rsp->LastWriteTime = 0;
8458 	rsp->ChangeTime = 0;
8459 	rsp->AllocationSize = 0;
8460 	rsp->EndOfFile = 0;
8461 	rsp->Attributes = 0;
8462 
8463 	return ksmbd_iov_pin_rsp(work, (void *)rsp,
8464 				 sizeof(struct smb2_close_rsp));
8465 }
8466 
8467 /**
8468  * smb2_close() - handler for smb2 close file command
8469  * @work:	smb work containing close request buffer
8470  *
8471  * Return:	0 on success, otherwise error
8472  */
8473 int smb2_close(struct ksmbd_work *work)
8474 {
8475 	u64 volatile_id = KSMBD_NO_FID;
8476 	u64 sess_id;
8477 	struct smb2_close_req *req;
8478 	struct smb2_close_rsp *rsp;
8479 	struct ksmbd_file *fp;
8480 	u64 time;
8481 	int err = 0;
8482 
8483 	ksmbd_debug(SMB, "Received smb2 close request\n");
8484 
8485 	WORK_BUFFERS(work, req, rsp);
8486 
8487 	if (smb2_compound_has_failed(work, &rsp->hdr))
8488 		return -EACCES;
8489 
8490 	if (test_share_config_flag(work->tcon->share_conf,
8491 				   KSMBD_SHARE_FLAG_PIPE)) {
8492 		ksmbd_debug(SMB, "IPC pipe close request\n");
8493 		return smb2_close_pipe(work);
8494 	}
8495 
8496 	sess_id = le64_to_cpu(req->hdr.SessionId);
8497 	if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
8498 		sess_id = work->compound_sid;
8499 
8500 	work->compound_sid = 0;
8501 	if (work->sess && work->sess->id == sess_id) {
8502 		work->compound_sid = sess_id;
8503 	} else {
8504 		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
8505 		if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
8506 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8507 		err = -EBADF;
8508 		goto out;
8509 	}
8510 
8511 	if (work->next_smb2_rcv_hdr_off &&
8512 	    !has_file_id(req->VolatileFileId)) {
8513 		if (!has_file_id(work->compound_fid)) {
8514 			/* file already closed, return FILE_CLOSED */
8515 			ksmbd_debug(SMB, "file already closed\n");
8516 			rsp->hdr.Status = STATUS_FILE_CLOSED;
8517 			err = -EBADF;
8518 			goto out;
8519 		} else {
8520 			ksmbd_debug(SMB,
8521 				    "Compound request set FID = %llu:%llu\n",
8522 				    work->compound_fid,
8523 				    work->compound_pfid);
8524 			volatile_id = work->compound_fid;
8525 
8526 			/* file closed, stored id is not valid anymore */
8527 			work->compound_fid = KSMBD_NO_FID;
8528 			work->compound_pfid = KSMBD_NO_FID;
8529 		}
8530 	} else {
8531 		volatile_id = req->VolatileFileId;
8532 	}
8533 	ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
8534 
8535 	rsp->StructureSize = cpu_to_le16(60);
8536 	rsp->Reserved = 0;
8537 
8538 	if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
8539 		struct kstat stat;
8540 		int ret;
8541 
8542 		fp = ksmbd_lookup_fd_fast(work, volatile_id);
8543 		if (!fp) {
8544 			err = -ENOENT;
8545 			goto out;
8546 		}
8547 
8548 		ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
8549 				  AT_STATX_SYNC_AS_STAT);
8550 		if (ret) {
8551 			ksmbd_fd_put(work, fp);
8552 			goto out;
8553 		}
8554 
8555 		rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
8556 		rsp->AllocationSize = cpu_to_le64(fp->allocation_size);
8557 		rsp->EndOfFile = cpu_to_le64(stat.size);
8558 		rsp->Attributes = fp->f_ci->m_fattr;
8559 		rsp->CreationTime = cpu_to_le64(fp->create_time);
8560 		time = ksmbd_UnixTimeToNT(stat.atime);
8561 		rsp->LastAccessTime = cpu_to_le64(time);
8562 		time = ksmbd_UnixTimeToNT(stat.mtime);
8563 		if (time > fp->open_mtime &&
8564 		    time - fp->open_mtime < KSMBD_WRITE_TIME_RESOLUTION)
8565 			time = fp->open_mtime;
8566 		rsp->LastWriteTime = cpu_to_le64(time);
8567 		rsp->ChangeTime = cpu_to_le64(fp->change_time);
8568 		ksmbd_fd_put(work, fp);
8569 	} else {
8570 		rsp->Flags = 0;
8571 		rsp->AllocationSize = 0;
8572 		rsp->EndOfFile = 0;
8573 		rsp->Attributes = 0;
8574 		rsp->CreationTime = 0;
8575 		rsp->LastAccessTime = 0;
8576 		rsp->LastWriteTime = 0;
8577 		rsp->ChangeTime = 0;
8578 	}
8579 
8580 	err = ksmbd_close_fd(work, volatile_id);
8581 out:
8582 	if (!err)
8583 		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
8584 					sizeof(struct smb2_close_rsp));
8585 
8586 	if (err) {
8587 		if (rsp->hdr.Status == 0)
8588 			rsp->hdr.Status = STATUS_FILE_CLOSED;
8589 		smb2_set_err_rsp(work);
8590 	}
8591 
8592 	return err;
8593 }
8594 
8595 /**
8596  * smb2_echo() - handler for smb2 echo(ping) command
8597  * @work:	smb work containing echo request buffer
8598  *
8599  * Return:	0 on success, otherwise error
8600  */
8601 int smb2_echo(struct ksmbd_work *work)
8602 {
8603 	struct smb2_echo_rsp *rsp = smb_get_msg(work->response_buf);
8604 
8605 	ksmbd_debug(SMB, "Received smb2 echo request\n");
8606 
8607 	if (work->next_smb2_rcv_hdr_off)
8608 		rsp = ksmbd_resp_buf_next(work);
8609 
8610 	rsp->StructureSize = cpu_to_le16(4);
8611 	rsp->Reserved = 0;
8612 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
8613 }
8614 
8615 static int smb2_rename(struct ksmbd_work *work,
8616 		       struct ksmbd_file *fp,
8617 		       struct smb2_file_rename_info *file_info,
8618 		       struct nls_table *local_nls)
8619 {
8620 	struct ksmbd_share_config *share = fp->tcon->share_conf;
8621 	char *new_name = NULL;
8622 	int rc, flags = 0;
8623 
8624 	ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
8625 	new_name = smb2_get_name(file_info->FileName,
8626 				 le32_to_cpu(file_info->FileNameLength),
8627 				 local_nls);
8628 	if (IS_ERR(new_name))
8629 		return PTR_ERR(new_name);
8630 
8631 	if (fp->is_posix_ctxt == false && strchr(new_name, ':')) {
8632 		int s_type = 0;
8633 		char *xattr_stream_name, *stream_name = NULL;
8634 		char *stream_buf = NULL;
8635 		size_t xattr_stream_size;
8636 		ssize_t stream_buf_len = 0;
8637 		int len;
8638 
8639 		rc = parse_stream_name(new_name, &stream_name, &s_type);
8640 		if (rc < 0)
8641 			goto out;
8642 
8643 		len = strlen(new_name);
8644 		if (len > 0 && new_name[len - 1] != '/') {
8645 			pr_err("not allow base filename in rename\n");
8646 			rc = -ESHARE;
8647 			goto out;
8648 		}
8649 
8650 		/* An empty stream name is the base file's default stream. */
8651 		if (!stream_name || !stream_name[0])
8652 			goto out;
8653 
8654 		rc = ksmbd_vfs_xattr_stream_name(stream_name,
8655 						 &xattr_stream_name,
8656 						 &xattr_stream_size,
8657 						 s_type);
8658 		if (rc)
8659 			goto out;
8660 
8661 		/* A handle opened without a stream has no source to copy. */
8662 		if (ksmbd_stream_fd(fp)) {
8663 			if (!strcasecmp(xattr_stream_name, fp->stream.name)) {
8664 				kfree(xattr_stream_name);
8665 				goto out;
8666 			}
8667 
8668 			stream_buf_len = ksmbd_vfs_getcasexattr(file_mnt_idmap(fp->filp),
8669 								fp->filp->f_path.dentry,
8670 								fp->stream.name,
8671 								fp->stream.size,
8672 								&stream_buf);
8673 			if (stream_buf_len < 0) {
8674 				rc = stream_buf_len;
8675 				kfree(xattr_stream_name);
8676 				goto out;
8677 			}
8678 		}
8679 
8680 		rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
8681 					&fp->filp->f_path,
8682 					xattr_stream_name,
8683 					stream_buf, stream_buf_len, 0, true);
8684 		kfree(stream_buf);
8685 		if (rc < 0)
8686 			pr_err("failed to store stream name in xattr: %d\n",
8687 			       rc);
8688 
8689 		kfree(xattr_stream_name);
8690 		goto out;
8691 	}
8692 
8693 	ksmbd_debug(SMB, "new name %s\n", new_name);
8694 	if (ksmbd_share_veto_filename(share, new_name)) {
8695 		rc = -ENOENT;
8696 		ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
8697 		goto out;
8698 	}
8699 
8700 	if (!file_info->ReplaceIfExists)
8701 		flags = RENAME_NOREPLACE;
8702 
8703 	rc = ksmbd_vfs_check_rename_share(work, &fp->filp->f_path);
8704 	if (rc)
8705 		goto out;
8706 
8707 	smb_break_all_levII_oplock_rename(work, fp);
8708 	rc = ksmbd_vfs_rename(work, fp, new_name, flags);
8709 out:
8710 	kfree(new_name);
8711 	return rc;
8712 }
8713 
8714 static int smb2_create_link(struct ksmbd_work *work,
8715 			    struct ksmbd_share_config *share,
8716 			    struct smb2_file_link_info *file_info,
8717 			    unsigned int buf_len, struct file *filp,
8718 			    struct nls_table *local_nls)
8719 {
8720 	char *link_name = NULL, *target_name = NULL, *pathname = NULL;
8721 	struct path path;
8722 	int rc;
8723 
8724 	if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
8725 			le32_to_cpu(file_info->FileNameLength))
8726 		return -EINVAL;
8727 
8728 	ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
8729 	pathname = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
8730 	if (!pathname)
8731 		return -ENOMEM;
8732 
8733 	link_name = smb2_get_name(file_info->FileName,
8734 				  le32_to_cpu(file_info->FileNameLength),
8735 				  local_nls);
8736 	if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
8737 		rc = -EINVAL;
8738 		goto out;
8739 	}
8740 
8741 	ksmbd_debug(SMB, "link name is %s\n", link_name);
8742 	target_name = file_path(filp, pathname, PATH_MAX);
8743 	if (IS_ERR(target_name)) {
8744 		rc = -EINVAL;
8745 		goto out;
8746 	}
8747 
8748 	ksmbd_debug(SMB, "target name is %s\n", target_name);
8749 	rc = ksmbd_vfs_kern_path_start_removing(work, link_name, LOOKUP_NO_SYMLINKS,
8750 						&path, 0);
8751 	if (rc) {
8752 		if (rc != -ENOENT)
8753 			goto out;
8754 	} else {
8755 		if (file_info->ReplaceIfExists) {
8756 			rc = ksmbd_vfs_remove_file(work, &path);
8757 			if (rc) {
8758 				rc = -EINVAL;
8759 				ksmbd_debug(SMB, "cannot delete %s\n",
8760 					    link_name);
8761 			}
8762 		} else {
8763 			rc = -EEXIST;
8764 			ksmbd_debug(SMB, "link already exists\n");
8765 		}
8766 		ksmbd_vfs_kern_path_end_removing(&path);
8767 		if (rc)
8768 			goto out;
8769 	}
8770 	rc = ksmbd_vfs_link(work, target_name, link_name);
8771 	if (rc)
8772 		rc = -EINVAL;
8773 out:
8774 
8775 	if (!IS_ERR(link_name))
8776 		kfree(link_name);
8777 	kfree(pathname);
8778 	return rc;
8779 }
8780 
8781 static int set_file_basic_info(struct ksmbd_file *fp,
8782 			       struct file_basic_info *file_info,
8783 			       struct ksmbd_share_config *share)
8784 {
8785 	struct iattr attrs;
8786 	struct file *filp;
8787 	struct inode *inode;
8788 	const struct mnt_idmap *idmap;
8789 	__le32 attrs_mask = FILE_ATTRIBUTE_DIRECTORY_LE |
8790 		FILE_ATTRIBUTE_COMPRESSED_LE;
8791 	int rc = 0;
8792 
8793 	if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
8794 		return -EACCES;
8795 
8796 	attrs.ia_valid = 0;
8797 	filp = fp->filp;
8798 	inode = file_inode(filp);
8799 	idmap = file_mnt_idmap(filp);
8800 
8801 	/* MS-FSA FileBasicInformation: a directory can't be marked TEMPORARY */
8802 	if (S_ISDIR(inode->i_mode) &&
8803 	    (file_info->Attributes & FILE_ATTRIBUTE_TEMPORARY_LE))
8804 		return -EINVAL;
8805 
8806 	if (file_info->CreationTime)
8807 		fp->create_time = le64_to_cpu(file_info->CreationTime);
8808 
8809 	if (file_info->LastAccessTime) {
8810 		attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
8811 		attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
8812 	}
8813 
8814 	if (file_info->ChangeTime) {
8815 		fp->change_time = le64_to_cpu(file_info->ChangeTime);
8816 		inode_set_ctime_to_ts(inode,
8817 				ksmbd_NTtimeToUnix(file_info->ChangeTime));
8818 	}
8819 
8820 	if (file_info->LastWriteTime) {
8821 		attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
8822 		attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET | ATTR_CTIME);
8823 	}
8824 
8825 	if (file_info->Attributes) {
8826 		if (!S_ISDIR(inode->i_mode) &&
8827 		    file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
8828 			pr_err("can't change a file to a directory\n");
8829 			return -EINVAL;
8830 		}
8831 
8832 		if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
8833 			fp->f_ci->m_fattr =
8834 				(file_info->Attributes & ~FILE_ATTRIBUTE_COMPRESSED_LE) |
8835 				(fp->f_ci->m_fattr & attrs_mask);
8836 	}
8837 
8838 	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
8839 	    (file_info->CreationTime || file_info->Attributes)) {
8840 		struct xattr_dos_attrib da = {0};
8841 
8842 		da.version = 4;
8843 		da.itime = fp->itime;
8844 		da.create_time = fp->create_time;
8845 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
8846 		da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
8847 			XATTR_DOSINFO_ITIME;
8848 
8849 		rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
8850 				true);
8851 		if (rc)
8852 			ksmbd_debug(SMB,
8853 				    "failed to restore file attribute in EA\n");
8854 		rc = 0;
8855 	}
8856 
8857 	if (attrs.ia_valid) {
8858 		struct dentry *dentry = filp->f_path.dentry;
8859 		struct inode *inode = d_inode(dentry);
8860 
8861 		if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
8862 			return -EACCES;
8863 
8864 		inode_lock(inode);
8865 		rc = notify_change(idmap, dentry, &attrs, NULL);
8866 		inode_unlock(inode);
8867 	}
8868 	return rc;
8869 }
8870 
8871 static int set_file_allocation_info(struct ksmbd_work *work,
8872 				    struct ksmbd_file *fp,
8873 				    struct smb2_file_alloc_info *file_alloc_info)
8874 {
8875 	/*
8876 	 * TODO : It's working fine only when store dos attributes
8877 	 * is not yes. need to implement a logic which works
8878 	 * properly with any smb.conf option
8879 	 */
8880 
8881 	u64 alloc_size, target, alloc_blks;
8882 	u32 alloc_unit;
8883 	struct inode *inode;
8884 	struct kstat stat;
8885 	struct kstatfs stfs;
8886 	int rc;
8887 
8888 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
8889 		return -EACCES;
8890 
8891 	if (ksmbd_stream_fd(fp) == true)
8892 		return 0;
8893 
8894 	rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
8895 			 AT_STATX_SYNC_AS_STAT);
8896 	if (rc)
8897 		return rc;
8898 	rc = vfs_statfs(&fp->filp->f_path, &stfs);
8899 	if (rc)
8900 		return rc;
8901 
8902 	/*
8903 	 * Use the allocation unit advertised in FS_SIZE_INFORMATION.
8904 	 * Reject requests that overflow when rounded to a whole unit.
8905 	 */
8906 	alloc_size = le64_to_cpu(file_alloc_info->AllocationSize);
8907 	if (stfs.f_bsize <= 0 || (u64)stfs.f_bsize > U32_MAX)
8908 		return -EINVAL;
8909 	alloc_unit = stfs.f_bsize;
8910 	if (alloc_size > MAX_LFS_FILESIZE - (alloc_unit - 1))
8911 		return -EINVAL;
8912 
8913 	target = DIV_ROUND_UP_ULL(alloc_size, alloc_unit) * alloc_unit;
8914 	alloc_blks = DIV_ROUND_UP_ULL(target, 512);
8915 	inode = file_inode(fp->filp);
8916 	if (target > inode->i_sb->s_maxbytes)
8917 		return -EINVAL;
8918 
8919 	if (alloc_blks > stat.blocks) {
8920 		smb_break_all_levII_oplock(work, fp, 1);
8921 		rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0, target);
8922 		if (rc && rc != -EOPNOTSUPP) {
8923 			pr_err("vfs_fallocate is failed : %d\n", rc);
8924 			return rc;
8925 		}
8926 	} else if (alloc_blks < stat.blocks &&
8927 		   target <= i_size_read(inode)) {
8928 		/*
8929 		 * Truncate at or below EOF to discard excess allocation.
8930 		 * Truncating above EOF would extend the file on disk.
8931 		 */
8932 		rc = ksmbd_vfs_truncate(work, fp, target);
8933 		if (rc) {
8934 			pr_err("truncate failed!, err %d\n", rc);
8935 			return rc;
8936 		}
8937 	}
8938 
8939 	fp->allocation_size = target;
8940 	fp->allocation_size_set = true;
8941 	return 0;
8942 }
8943 
8944 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
8945 				struct smb2_file_eof_info *file_eof_info)
8946 {
8947 	loff_t newsize;
8948 	struct inode *inode;
8949 	int rc;
8950 
8951 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
8952 		return -EACCES;
8953 
8954 	newsize = le64_to_cpu(file_eof_info->EndOfFile);
8955 	inode = file_inode(fp->filp);
8956 	if (ksmbd_stream_fd(fp))
8957 		return ksmbd_vfs_stream_truncate(fp, newsize);
8958 
8959 	/*
8960 	 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
8961 	 * on FAT32 shared device, truncate execution time is too long
8962 	 * and network error could cause from windows client. because
8963 	 * truncate of some filesystem like FAT32 fill zero data in
8964 	 * truncated range.
8965 	 */
8966 	if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
8967 		ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
8968 		rc = ksmbd_vfs_truncate(work, fp, newsize);
8969 		if (rc) {
8970 			ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
8971 			if (rc != -EAGAIN)
8972 				rc = -EBADF;
8973 			return rc;
8974 		}
8975 	}
8976 	return 0;
8977 }
8978 
8979 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
8980 			   struct smb2_file_rename_info *rename_info,
8981 			   unsigned int buf_len)
8982 {
8983 	if (!(fp->daccess & FILE_DELETE_LE)) {
8984 		pr_err("no right to delete : 0x%x\n", fp->daccess);
8985 		return -EACCES;
8986 	}
8987 
8988 	if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
8989 			le32_to_cpu(rename_info->FileNameLength))
8990 		return -EINVAL;
8991 
8992 	if (!le32_to_cpu(rename_info->FileNameLength))
8993 		return -EINVAL;
8994 
8995 	return smb2_rename(work, fp, rename_info, work->conn->local_nls);
8996 }
8997 
8998 static int set_file_disposition_info(struct ksmbd_work *work,
8999 				     struct ksmbd_file *fp,
9000 				     struct smb2_file_disposition_info *file_info)
9001 {
9002 	struct inode *inode;
9003 	int err;
9004 
9005 	if (!(fp->daccess & FILE_DELETE_LE)) {
9006 		pr_err("no right to delete : 0x%x\n", fp->daccess);
9007 		return -EACCES;
9008 	}
9009 
9010 	if (fp->f_ci->m_fattr & FILE_ATTRIBUTE_READONLY_LE)
9011 		return -EACCES;
9012 
9013 	inode = file_inode(fp->filp);
9014 	if (file_info->DeletePending) {
9015 		if (ksmbd_has_stream_without_delete_share(fp))
9016 			return -ESHARE;
9017 
9018 		if (S_ISDIR(inode->i_mode) && !ksmbd_stream_fd(fp)) {
9019 			mutex_lock(&fp->readdir_lock);
9020 			err = ksmbd_vfs_empty_dir(fp);
9021 			mutex_unlock(&fp->readdir_lock);
9022 			if (err == -ENOTEMPTY)
9023 				return -EBUSY;
9024 		}
9025 		smb_break_all_levII_oplock_for_delete(work, fp);
9026 		ksmbd_fd_set_delete_pending(fp);
9027 	} else {
9028 		ksmbd_fd_clear_delete_pending(fp);
9029 	}
9030 	return 0;
9031 }
9032 
9033 static int set_file_position_info(struct ksmbd_file *fp,
9034 				  struct smb2_file_pos_info *file_info)
9035 {
9036 	loff_t current_byte_offset;
9037 	unsigned long sector_size;
9038 	struct inode *inode;
9039 
9040 	inode = file_inode(fp->filp);
9041 	current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
9042 	sector_size = inode->i_sb->s_blocksize;
9043 
9044 	if (current_byte_offset < 0 ||
9045 	    (fp->coption & FILE_NO_INTERMEDIATE_BUFFERING_LE &&
9046 	     current_byte_offset & (sector_size - 1))) {
9047 		pr_err("CurrentByteOffset is not valid : %llu\n",
9048 		       current_byte_offset);
9049 		return -EINVAL;
9050 	}
9051 
9052 	if (ksmbd_stream_fd(fp) == false)
9053 		fp->filp->f_pos = current_byte_offset;
9054 	else {
9055 		if (current_byte_offset > XATTR_SIZE_MAX)
9056 			current_byte_offset = XATTR_SIZE_MAX;
9057 		fp->stream.pos = current_byte_offset;
9058 	}
9059 	return 0;
9060 }
9061 
9062 static int set_file_mode_info(struct ksmbd_file *fp,
9063 			      struct smb2_file_mode_info *file_info)
9064 {
9065 	__le32 mode;
9066 
9067 	mode = file_info->Mode;
9068 
9069 	if ((mode & ~FILE_MODE_INFO_MASK)) {
9070 		pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
9071 		return -EINVAL;
9072 	}
9073 
9074 	/*
9075 	 * TODO : need to implement consideration for
9076 	 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
9077 	 */
9078 	ksmbd_vfs_set_fadvise(fp->filp, mode);
9079 	fp->coption = mode;
9080 	return 0;
9081 }
9082 
9083 /**
9084  * smb2_set_info_file() - handler for smb2 set info command
9085  * @work:	smb work containing set info command buffer
9086  * @fp:		ksmbd_file pointer
9087  * @req:	request buffer pointer
9088  * @share:	ksmbd_share_config pointer
9089  *
9090  * Return:	0 on success, otherwise error
9091  */
9092 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
9093 			      struct smb2_set_info_req *req,
9094 			      struct ksmbd_share_config *share)
9095 {
9096 	unsigned int buf_len = le32_to_cpu(req->BufferLength);
9097 	char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
9098 
9099 	switch (req->FileInfoClass) {
9100 	case FILE_BASIC_INFORMATION:
9101 	{
9102 		if (buf_len < sizeof(struct file_basic_info))
9103 			return -EMSGSIZE;
9104 
9105 		return set_file_basic_info(fp, (struct file_basic_info *)buffer, share);
9106 	}
9107 	case FILE_ALLOCATION_INFORMATION:
9108 	{
9109 		if (buf_len < sizeof(struct smb2_file_alloc_info))
9110 			return -EMSGSIZE;
9111 
9112 		return set_file_allocation_info(work, fp,
9113 						(struct smb2_file_alloc_info *)buffer);
9114 	}
9115 	case FILE_END_OF_FILE_INFORMATION:
9116 	{
9117 		if (buf_len < sizeof(struct smb2_file_eof_info))
9118 			return -EMSGSIZE;
9119 
9120 		return set_end_of_file_info(work, fp,
9121 					    (struct smb2_file_eof_info *)buffer);
9122 	}
9123 	case FILE_RENAME_INFORMATION:
9124 	{
9125 		if (buf_len < sizeof(struct smb2_file_rename_info))
9126 			return -EMSGSIZE;
9127 
9128 		return set_rename_info(work, fp,
9129 				       (struct smb2_file_rename_info *)buffer,
9130 				       buf_len);
9131 	}
9132 	case FILE_LINK_INFORMATION:
9133 	{
9134 		struct smb2_file_link_info *file_info;
9135 
9136 		if (buf_len < sizeof(struct smb2_file_link_info))
9137 			return -EMSGSIZE;
9138 
9139 		file_info = (struct smb2_file_link_info *)buffer;
9140 		if (file_info->ReplaceIfExists && !(fp->daccess & FILE_DELETE_LE)) {
9141 			pr_err("no right to delete : 0x%x\n", fp->daccess);
9142 			return -EACCES;
9143 		}
9144 
9145 		return smb2_create_link(work, work->tcon->share_conf, file_info,
9146 					buf_len, fp->filp,
9147 					work->conn->local_nls);
9148 	}
9149 	case FILE_DISPOSITION_INFORMATION:
9150 	{
9151 		if (buf_len < sizeof(struct smb2_file_disposition_info))
9152 			return -EMSGSIZE;
9153 
9154 		return set_file_disposition_info(work, fp,
9155 						 (struct smb2_file_disposition_info *)buffer);
9156 	}
9157 	case FILE_FULL_EA_INFORMATION:
9158 	{
9159 		if (!(fp->daccess & FILE_WRITE_EA_LE)) {
9160 			pr_err("Not permitted to write ext  attr: 0x%x\n",
9161 			       fp->daccess);
9162 			return -EACCES;
9163 		}
9164 
9165 		if (buf_len < sizeof(struct smb2_ea_info))
9166 			return -EMSGSIZE;
9167 
9168 		return smb2_set_ea((struct smb2_ea_info *)buffer,
9169 				   buf_len, &fp->filp->f_path, true);
9170 	}
9171 	case FILE_POSITION_INFORMATION:
9172 	{
9173 		if (buf_len < sizeof(struct smb2_file_pos_info))
9174 			return -EMSGSIZE;
9175 
9176 		return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
9177 	}
9178 	case FILE_MODE_INFORMATION:
9179 	{
9180 		if (buf_len < sizeof(struct smb2_file_mode_info))
9181 			return -EMSGSIZE;
9182 
9183 		return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
9184 	}
9185 	}
9186 
9187 	pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
9188 	return -EOPNOTSUPP;
9189 }
9190 
9191 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
9192 			     char *buffer, int buf_len)
9193 {
9194 	struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
9195 
9196 	fp->saccess |= FILE_SHARE_DELETE_LE;
9197 
9198 	if (!(fp->daccess & (FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE)))
9199 		return -EACCES;
9200 
9201 	return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
9202 			buf_len, false, true,
9203 			fp->conn->dialect == SMB311_PROT_ID && fp->is_posix_ctxt,
9204 			addition_info & DACL_SECINFO);
9205 }
9206 
9207 /**
9208  * smb2_set_info() - handler for smb2 set info command handler
9209  * @work:	smb work containing set info request buffer
9210  *
9211  * Return:	0 on success, otherwise error
9212  */
9213 int smb2_set_info(struct ksmbd_work *work)
9214 {
9215 	const struct cred *saved_cred;
9216 	struct smb2_set_info_req *req;
9217 	struct smb2_set_info_rsp *rsp;
9218 	struct ksmbd_file *fp = NULL;
9219 	int rc = 0;
9220 	bool chseq_err = false;
9221 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
9222 
9223 	ksmbd_debug(SMB, "Received smb2 set info request\n");
9224 
9225 	if (work->next_smb2_rcv_hdr_off) {
9226 		req = ksmbd_req_buf_next(work);
9227 		rsp = ksmbd_resp_buf_next(work);
9228 		if (smb2_compound_has_failed(work, &rsp->hdr))
9229 			return -EACCES;
9230 		if (!has_file_id(req->VolatileFileId)) {
9231 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
9232 				    work->compound_fid);
9233 			id = work->compound_fid;
9234 			pid = work->compound_pfid;
9235 		}
9236 	} else {
9237 		req = smb_get_msg(work->request_buf);
9238 		rsp = smb_get_msg(work->response_buf);
9239 	}
9240 
9241 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
9242 		ksmbd_debug(SMB, "User does not have write permission\n");
9243 		pr_err("User does not have write permission\n");
9244 		rc = -EACCES;
9245 		goto err_out;
9246 	}
9247 
9248 	if (!has_file_id(id)) {
9249 		id = req->VolatileFileId;
9250 		pid = req->PersistentFileId;
9251 	}
9252 
9253 	fp = ksmbd_lookup_fd_slow(work, id, pid);
9254 	if (!fp) {
9255 		ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
9256 		rc = -ENOENT;
9257 		goto err_out;
9258 	}
9259 
9260 	rc = smb2_set_request_open(work, fp, &req->hdr, true, false);
9261 	if (rc) {
9262 		rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
9263 		chseq_err = true;
9264 		goto err_out;
9265 	}
9266 
9267 	saved_cred = override_creds(fp->filp->f_cred);
9268 	switch (req->InfoType) {
9269 	case SMB2_O_INFO_FILE:
9270 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
9271 		rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
9272 		break;
9273 	case SMB2_O_INFO_SECURITY:
9274 		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
9275 		rc = smb2_set_info_sec(fp,
9276 				       le32_to_cpu(req->AdditionalInformation),
9277 				       (char *)req + le16_to_cpu(req->BufferOffset),
9278 				       le32_to_cpu(req->BufferLength));
9279 		break;
9280 	default:
9281 		rc = -EOPNOTSUPP;
9282 	}
9283 	revert_creds(saved_cred);
9284 
9285 	if (rc < 0)
9286 		goto err_out;
9287 
9288 	rsp->StructureSize = cpu_to_le16(2);
9289 	rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
9290 			       sizeof(struct smb2_set_info_rsp));
9291 	if (rc)
9292 		goto err_out;
9293 	ksmbd_fd_put(work, fp);
9294 	return 0;
9295 
9296 err_out:
9297 	if (rc == -EACCES || rc == -EPERM || rc == -EXDEV) {
9298 		if (fp && req->InfoType == SMB2_O_INFO_FILE &&
9299 		    req->FileInfoClass == FILE_DISPOSITION_INFORMATION &&
9300 		    fp->f_ci->m_fattr & FILE_ATTRIBUTE_READONLY_LE)
9301 			rsp->hdr.Status = STATUS_CANNOT_DELETE;
9302 		else
9303 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
9304 	}
9305 	else if (rc == -EINVAL)
9306 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
9307 	else if (rc == -EMSGSIZE)
9308 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
9309 	else if (rc == -ENOSPC || rc == -EFBIG)
9310 		rsp->hdr.Status = STATUS_DISK_FULL;
9311 	else if (rc == -ESHARE)
9312 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
9313 	else if (rc == -ENOENT)
9314 		rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
9315 	else if (rc == -EBUSY || rc == -ENOTEMPTY)
9316 		rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
9317 	else if (rc == -EAGAIN && !chseq_err)
9318 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
9319 	else if (rc == -EBADF || rc == -ESTALE)
9320 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
9321 	else if (rc == -EEXIST)
9322 		rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
9323 	else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
9324 		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
9325 	smb2_set_err_rsp(work);
9326 	ksmbd_fd_put(work, fp);
9327 	ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
9328 	return rc;
9329 }
9330 
9331 static __le32 smb2_pipe_error_status(int err, __le32 fallback)
9332 {
9333 	switch (err) {
9334 	case -ECANCELED:
9335 		return STATUS_CANCELLED;
9336 	case -ESHUTDOWN:
9337 		return STATUS_CONNECTION_DISCONNECTED;
9338 	case -EBADF:
9339 	case -ENOENT:
9340 		return STATUS_FILE_CLOSED;
9341 	default:
9342 		return fallback;
9343 	}
9344 }
9345 
9346 static void smb2_pipe_response_done(struct ksmbd_session_rpc *rpc,
9347 				    unsigned int nbytes)
9348 {
9349 	rpc->pending_offset += nbytes;
9350 	if (rpc->pending_offset == rpc->pending->payload_sz) {
9351 		kvfree(rpc->pending);
9352 		rpc->pending = NULL;
9353 		rpc->pending_offset = 0;
9354 	}
9355 }
9356 
9357 /**
9358  * smb2_read_pipe() - handler for smb2 read from IPC pipe
9359  * @work:	smb work containing read IPC pipe command buffer
9360  *
9361  * Return:	0 on success, otherwise error
9362  */
9363 static noinline int smb2_read_pipe(struct ksmbd_work *work)
9364 {
9365 	unsigned int nbytes = 0, length;
9366 	u64 id;
9367 	struct ksmbd_rpc_command *rpc_resp;
9368 	struct ksmbd_session_rpc *rpc;
9369 	struct smb2_read_req *req;
9370 	struct smb2_read_rsp *rsp;
9371 	void *aux_payload_buf;
9372 	int err;
9373 
9374 	WORK_BUFFERS(work, req, rsp);
9375 
9376 	id = req->VolatileFileId;
9377 
9378 	lockdep_assert_not_held(&work->sess->rpc_lock);
9379 	down_read(&work->sess->rpc_lock);
9380 	if (!ksmbd_session_rpc_method(work->sess, id)) {
9381 		up_read(&work->sess->rpc_lock);
9382 		rsp->hdr.Status = STATUS_FILE_CLOSED;
9383 		smb2_set_err_rsp(work);
9384 		return -ENOENT;
9385 	}
9386 	up_read(&work->sess->rpc_lock);
9387 
9388 	rpc = ksmbd_session_rpc_get(work, id);
9389 	if (IS_ERR(rpc)) {
9390 		err = PTR_ERR(rpc);
9391 		goto out;
9392 	}
9393 
9394 	length = le32_to_cpu(req->Length);
9395 	if (!length)
9396 		goto empty;
9397 
9398 	if (!rpc->pending) {
9399 		rpc_resp = ksmbd_rpc_read(work->sess, rpc);
9400 		if (!rpc_resp) {
9401 			err = -EIO;
9402 			goto out_put;
9403 		}
9404 		if (rpc_resp->flags != KSMBD_RPC_OK) {
9405 			kvfree(rpc_resp);
9406 			err = -EINVAL;
9407 			goto out_put;
9408 		}
9409 		rpc->pending = rpc_resp;
9410 	}
9411 
9412 	rpc_resp = rpc->pending;
9413 	nbytes = min(length, rpc_resp->payload_sz - rpc->pending_offset);
9414 	if (!nbytes) {
9415 		smb2_pipe_response_done(rpc, 0);
9416 		goto empty;
9417 	}
9418 
9419 	aux_payload_buf = kvmalloc(ALIGN(nbytes, 8), KSMBD_DEFAULT_GFP);
9420 	if (!aux_payload_buf) {
9421 		err = -ENOMEM;
9422 		goto out_put;
9423 	}
9424 	memcpy(aux_payload_buf, rpc_resp->payload + rpc->pending_offset, nbytes);
9425 	if (nbytes & 7)
9426 		memset(aux_payload_buf + nbytes, 0, ALIGN(nbytes, 8) - nbytes);
9427 
9428 	err = ksmbd_iov_pin_rsp_read(work, rsp,
9429 				     offsetof(struct smb2_read_rsp, Buffer),
9430 				     aux_payload_buf, nbytes);
9431 	if (err) {
9432 		kvfree(aux_payload_buf);
9433 		goto out_put;
9434 	}
9435 	smb2_pipe_response_done(rpc, nbytes);
9436 	if (rpc->pending)
9437 		rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
9438 	goto done;
9439 
9440 empty:
9441 	err = ksmbd_iov_pin_rsp(work, rsp,
9442 				offsetof(struct smb2_read_rsp, Buffer));
9443 	if (err)
9444 		goto out_put;
9445 done:
9446 	rsp->StructureSize = cpu_to_le16(17);
9447 	rsp->DataOffset = 80;
9448 	rsp->Reserved = 0;
9449 	rsp->DataLength = cpu_to_le32(nbytes);
9450 	rsp->DataRemaining = 0;
9451 	rsp->Flags = 0;
9452 	ksmbd_session_rpc_put(rpc);
9453 	return 0;
9454 
9455 out_put:
9456 	ksmbd_session_rpc_put(rpc);
9457 out:
9458 	rsp->hdr.Status = smb2_pipe_error_status(err,
9459 						STATUS_UNEXPECTED_IO_ERROR);
9460 	smb2_set_err_rsp(work);
9461 	return err;
9462 }
9463 
9464 /**
9465  * smb2_set_rdma_key() - validate descriptors and save invalidation state
9466  * @work: request work item
9467  * @desc: first RDMA buffer descriptor
9468  * @Channel: nested RDMA channel type
9469  * @channel_info_len: descriptor array length
9470  *
9471  * Return: 0 on success, otherwise -EINVAL
9472  */
9473 static int smb2_set_rdma_key(struct ksmbd_work *work,
9474 			     struct smbdirect_buffer_descriptor_v1 *desc,
9475 			     __le32 Channel, __le16 channel_info_len)
9476 {
9477 	unsigned int i, ch_count;
9478 
9479 	if (Channel != SMB2_CHANNEL_RDMA_V1 &&
9480 	    Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE)
9481 		return -EINVAL;
9482 	if (work->conn->dialect == SMB30_PROT_ID &&
9483 	    Channel != SMB2_CHANNEL_RDMA_V1)
9484 		return -EINVAL;
9485 	if (le16_to_cpu(channel_info_len) % sizeof(*desc))
9486 		return -EINVAL;
9487 
9488 	ch_count = le16_to_cpu(channel_info_len) / sizeof(*desc);
9489 	if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
9490 		for (i = 0; i < ch_count; i++) {
9491 			pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
9492 				i,
9493 				le32_to_cpu(desc[i].token),
9494 				le32_to_cpu(desc[i].length));
9495 		}
9496 	}
9497 	if (!ch_count)
9498 		return -EINVAL;
9499 
9500 	work->need_invalidate_rkey =
9501 		(Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
9502 	if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
9503 		work->remote_key = le32_to_cpu(desc->token);
9504 	return 0;
9505 }
9506 
9507 /**
9508  * smb2_prep_rdma_read() - transform an RDMA READ payload
9509  * @work: request work item
9510  * @req: READ request controlling encryption or signing
9511  * @rsp: READ response receiving transform metadata
9512  * @data: data that will be transferred through RDMA
9513  * @datalen: data length
9514  *
9515  * Encrypt the payload in place and encode the detached crypto metadata in
9516  * the response buffer.
9517  *
9518  * Return: metadata length, zero when no transform applies, or negative errno
9519  */
9520 static int smb2_prep_rdma_read(struct ksmbd_work *work,
9521 			       struct smb2_read_req *req,
9522 			       struct smb2_read_rsp *rsp,
9523 			       void *data, unsigned int datalen)
9524 {
9525 	struct ksmbd_conn *conn = work->conn;
9526 	struct smb2_rdma_transform *transform;
9527 	struct smb2_rdma_crypto_transform *crypto;
9528 	u8 *nonce;
9529 	unsigned int nonce_len = 0, transform_len;
9530 	u16 transform_type;
9531 	int err;
9532 
9533 	if (!work->encrypted ||
9534 	    !(conn->rdma_transform_ids & BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION)))
9535 		return 0;
9536 
9537 	transform_type = SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION;
9538 	nonce_len = (conn->cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
9539 		     conn->cipher_type == SMB2_ENCRYPTION_AES256_GCM) ?
9540 		SMB3_AES_GCM_NONCE : SMB3_AES_CCM_NONCE;
9541 
9542 	transform = (struct smb2_rdma_transform *)rsp->Buffer;
9543 	crypto = (struct smb2_rdma_crypto_transform *)(transform + 1);
9544 	memset(transform, 0, sizeof(*transform) + sizeof(*crypto) +
9545 	       SMB2_SIGNATURE_SIZE + nonce_len);
9546 	transform->Channel = SMB2_CHANNEL_NONE;
9547 	transform->TransformCount = cpu_to_le16(1);
9548 
9549 	crypto->TransformType = cpu_to_le16(transform_type);
9550 	crypto->SignatureLength = cpu_to_le16(SMB2_SIGNATURE_SIZE);
9551 	crypto->NonceLength = cpu_to_le16(nonce_len);
9552 	nonce = crypto->Signature + SMB2_SIGNATURE_SIZE;
9553 
9554 	get_random_bytes(nonce, nonce_len);
9555 	err = ksmbd_crypt_rdma(conn,
9556 			       work->sess->smb3encryptionkey,
9557 			       data, datalen, nonce, nonce_len,
9558 			       crypto->Signature,
9559 			       SMB2_SIGNATURE_SIZE, true);
9560 	if (err) {
9561 		pr_err("RDMA READ encryption failed: session=%llu payload=%u rc=%d\n",
9562 		       work->sess->id, datalen, err);
9563 		return err;
9564 	}
9565 
9566 	transform_len = sizeof(*transform) + sizeof(*crypto) +
9567 		SMB2_SIGNATURE_SIZE + nonce_len;
9568 	rsp->Flags = SMB2_READFLAG_RESPONSE_RDMA_TRANSFORM;
9569 	rsp->DataLength = cpu_to_le32(transform_len);
9570 	ksmbd_debug(RDMA,
9571 		    "RDMA READ encryption prepared: session=%llu cipher=0x%04x payload=%u transform=%u nonce=%u tag=%u\n",
9572 		    work->sess->id, le16_to_cpu(conn->cipher_type), datalen,
9573 		    transform_len, nonce_len, SMB2_SIGNATURE_SIZE);
9574 	return transform_len;
9575 }
9576 
9577 struct smb2_rdma_write_transform {
9578 	struct smbdirect_buffer_descriptor_v1 *desc;
9579 	struct smb2_rdma_crypto_transform *crypto;
9580 	u8 *nonce;
9581 	unsigned int desc_len;
9582 	unsigned int nonce_len;
9583 	unsigned int signature_len;
9584 	u16 type;
9585 	__le32 channel;
9586 };
9587 
9588 /**
9589  * smb2_current_req_len() - return the current compound request element size
9590  * @work: request work item
9591  * @hdr: current SMB2 header
9592  *
9593  * Return: current request element length measured from the SMB2 header
9594  */
9595 static unsigned int smb2_current_req_len(struct ksmbd_work *work,
9596 					 struct smb2_hdr *hdr)
9597 {
9598 	if (hdr->NextCommand)
9599 		return le32_to_cpu(hdr->NextCommand);
9600 	return get_rfc1002_len(work->request_buf) -
9601 		work->next_smb2_rcv_hdr_off;
9602 }
9603 
9604 /**
9605  * check_rdma_desc() - validate an RDMA descriptor array
9606  * @desc: descriptor array
9607  * @desc_len: descriptor array length
9608  * @required_len: minimum aggregate buffer length
9609  *
9610  * Return: 0 when the descriptors cover the transfer, otherwise -EINVAL
9611  */
9612 static int check_rdma_desc(struct smbdirect_buffer_descriptor_v1 *desc,
9613 			   unsigned int desc_len,
9614 			   unsigned int required_len)
9615 {
9616 	unsigned int i, count;
9617 	u64 described_len = 0;
9618 
9619 	if (!desc_len || desc_len % sizeof(*desc))
9620 		return -EINVAL;
9621 	count = desc_len / sizeof(*desc);
9622 	if (!le32_to_cpu(desc[0].length))
9623 		return -EINVAL;
9624 	for (i = 0; i < count; i++)
9625 		described_len += le32_to_cpu(desc[i].length);
9626 	return described_len < required_len ? -EINVAL : 0;
9627 }
9628 
9629 /**
9630  * smb2_parse_rdma_write_transform() - validate RDMA WRITE transform metadata
9631  * @work: request work item
9632  * @req: WRITE request containing the transform
9633  * @info: parsed transform information
9634  *
9635  * Validate transform counts, crypto fields, descriptor alignment and bounds,
9636  * negotiated algorithms, and the nested RDMA channel.
9637  *
9638  * Return: 0 on success, otherwise a negative errno
9639  */
9640 static int smb2_parse_rdma_write_transform(struct ksmbd_work *work,
9641 					   struct smb2_write_req *req,
9642 					   struct smb2_rdma_write_transform *info)
9643 {
9644 	struct smb2_rdma_transform *transform;
9645 	struct smb2_rdma_crypto_transform *crypto;
9646 	unsigned int req_len = smb2_current_req_len(work, &req->hdr);
9647 	unsigned int offset = le16_to_cpu(req->WriteChannelInfoOffset);
9648 	unsigned int length = le16_to_cpu(req->WriteChannelInfoLength);
9649 	unsigned int desc_offset, desc_len, crypto_len, expected_desc_offset;
9650 	int err;
9651 
9652 	if (!work->conn->rdma_transform_ids ||
9653 	    offset < offsetof(struct smb2_write_req, Buffer) ||
9654 	    length < sizeof(*transform) || offset > req_len ||
9655 	    length > req_len - offset)
9656 		return -EINVAL;
9657 
9658 	transform = (struct smb2_rdma_transform *)((char *)req + offset);
9659 	if (le16_to_cpu(transform->TransformCount) != 1 ||
9660 	    (transform->Channel != SMB2_CHANNEL_RDMA_V1 &&
9661 	     transform->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE))
9662 		return -EINVAL;
9663 
9664 	desc_offset = le16_to_cpu(transform->RdmaDescriptorOffset);
9665 	desc_len = le16_to_cpu(transform->RdmaDescriptorLength);
9666 	if (!desc_len || desc_len % sizeof(*info->desc) ||
9667 	    desc_offset < sizeof(*transform) || desc_offset > length ||
9668 	    desc_len > length - desc_offset)
9669 		return -EINVAL;
9670 
9671 	crypto = (struct smb2_rdma_crypto_transform *)(transform + 1);
9672 	if (length - sizeof(*transform) < sizeof(*crypto))
9673 		return -EINVAL;
9674 	info->type = le16_to_cpu(crypto->TransformType);
9675 	info->signature_len = le16_to_cpu(crypto->SignatureLength);
9676 	info->nonce_len = le16_to_cpu(crypto->NonceLength);
9677 	if (!info->signature_len)
9678 		return info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION ?
9679 			-EBADMSG : -EINVAL;
9680 	if (info->signature_len > SMB2_SIGNATURE_SIZE)
9681 		return info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION ?
9682 			-EBADMSG : -EINVAL;
9683 	if (info->signature_len > length - sizeof(*transform) - sizeof(*crypto) ||
9684 	    info->nonce_len > length - sizeof(*transform) - sizeof(*crypto) -
9685 				 info->signature_len)
9686 		return -EINVAL;
9687 
9688 	crypto_len = sizeof(*crypto) + info->signature_len + info->nonce_len;
9689 	expected_desc_offset = ALIGN(sizeof(*transform) + crypto_len, 8);
9690 	if (desc_offset != expected_desc_offset)
9691 		return -EINVAL;
9692 
9693 	if (info->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION) {
9694 		unsigned int expected_nonce_len;
9695 
9696 		if (!(work->conn->rdma_transform_ids &
9697 		      BIT(SMB2_RDMA_TRANSFORM_ENCRYPTION)) || !work->encrypted)
9698 			return -EINVAL;
9699 		expected_nonce_len =
9700 			(work->conn->cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
9701 			 work->conn->cipher_type == SMB2_ENCRYPTION_AES256_GCM) ?
9702 			SMB3_AES_GCM_NONCE : SMB3_AES_CCM_NONCE;
9703 		if (info->nonce_len != expected_nonce_len)
9704 			return -EBADMSG;
9705 	} else {
9706 		return -EINVAL;
9707 	}
9708 
9709 	info->desc = (struct smbdirect_buffer_descriptor_v1 *)
9710 		((char *)transform + desc_offset);
9711 	info->desc_len = desc_len;
9712 	info->crypto = crypto;
9713 	info->nonce = crypto->Signature + info->signature_len;
9714 	info->channel = transform->Channel;
9715 	err = check_rdma_desc(info->desc, info->desc_len,
9716 			      le32_to_cpu(req->RemainingBytes));
9717 	if (err)
9718 		return err;
9719 
9720 	ksmbd_debug(RDMA,
9721 		    "RDMA WRITE encryption metadata: session=%llu cipher=0x%04x payload=%u channel=0x%x descriptors=%zu nonce=%u tag=%u\n",
9722 		    work->sess->id, le16_to_cpu(work->conn->cipher_type),
9723 		    le32_to_cpu(req->RemainingBytes), le32_to_cpu(info->channel),
9724 		    info->desc_len / sizeof(*info->desc), info->nonce_len,
9725 		    info->signature_len);
9726 	return 0;
9727 }
9728 
9729 /**
9730  * smb2_read_rdma() - transfer READ data to client RDMA buffers
9731  * @work: request work item
9732  * @req: READ request containing client descriptors
9733  * @data_buf: data to transfer
9734  * @length: data length
9735  *
9736  * Return: transferred length on success, otherwise a negative errno
9737  */
9738 static ssize_t smb2_read_rdma(struct ksmbd_work *work,
9739 			      struct smb2_read_req *req, void *data_buf,
9740 			      size_t length)
9741 {
9742 	int err;
9743 
9744 	err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
9745 				    (struct smbdirect_buffer_descriptor_v1 *)
9746 				    ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
9747 				    le16_to_cpu(req->ReadChannelInfoLength));
9748 	if (err)
9749 		return err;
9750 
9751 	return length;
9752 }
9753 
9754 /**
9755  * smb2_read() - handler for smb2 read from file
9756  * @work:	smb work containing read command buffer
9757  *
9758  * Return:	0 on success, otherwise error
9759  */
9760 int smb2_read(struct ksmbd_work *work)
9761 {
9762 	struct ksmbd_conn *conn = work->conn;
9763 	struct smb2_read_req *req;
9764 	struct smb2_read_rsp *rsp;
9765 	struct ksmbd_file *fp = NULL;
9766 	loff_t offset;
9767 	size_t length, mincount;
9768 	ssize_t nbytes = 0, remain_bytes = 0;
9769 	int err = 0;
9770 	int rdma_transform_len = 0;
9771 	bool is_rdma_channel = false, async_interim = false;
9772 	unsigned int max_read_size = conn->vals->max_read_size;
9773 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
9774 	void *aux_payload_buf;
9775 
9776 	ksmbd_debug(SMB, "Received smb2 read request\n");
9777 
9778 	if (test_share_config_flag(work->tcon->share_conf,
9779 				   KSMBD_SHARE_FLAG_PIPE)) {
9780 		ksmbd_debug(SMB, "IPC pipe read request\n");
9781 		return smb2_read_pipe(work);
9782 	}
9783 
9784 	if (work->next_smb2_rcv_hdr_off) {
9785 		req = ksmbd_req_buf_next(work);
9786 		rsp = ksmbd_resp_buf_next(work);
9787 		if (smb2_compound_has_failed(work, &rsp->hdr))
9788 			return -EACCES;
9789 		if (!has_file_id(req->VolatileFileId)) {
9790 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
9791 					work->compound_fid);
9792 			id = work->compound_fid;
9793 			pid = work->compound_pfid;
9794 		}
9795 	} else {
9796 		req = smb_get_msg(work->request_buf);
9797 		rsp = smb_get_msg(work->response_buf);
9798 	}
9799 
9800 	if (!has_file_id(id)) {
9801 		id = req->VolatileFileId;
9802 		pid = req->PersistentFileId;
9803 	}
9804 
9805 	if (req->Channel != SMB2_CHANNEL_NONE &&
9806 	    req->Channel != SMB2_CHANNEL_RDMA_V1 &&
9807 	    req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
9808 		err = -EINVAL;
9809 		goto out;
9810 	}
9811 	if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
9812 	    req->Channel == SMB2_CHANNEL_RDMA_V1) {
9813 		is_rdma_channel = true;
9814 		max_read_size = get_smbd_max_read_write_size(work->conn->transport);
9815 		if (max_read_size == 0) {
9816 			err = -EINVAL;
9817 			goto out;
9818 		}
9819 	}
9820 
9821 	if (is_rdma_channel == true) {
9822 		unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
9823 		unsigned int ch_len = le16_to_cpu(req->ReadChannelInfoLength);
9824 		unsigned int req_len = smb2_current_req_len(work, &req->hdr);
9825 		struct smbdirect_buffer_descriptor_v1 *desc;
9826 
9827 		if (!le32_to_cpu(req->Length) ||
9828 		    ch_offset < offsetof(struct smb2_read_req, Buffer) ||
9829 		    ch_offset > req_len || ch_len > req_len - ch_offset) {
9830 			err = -EINVAL;
9831 			goto out;
9832 		}
9833 		desc = (struct smbdirect_buffer_descriptor_v1 *)
9834 			((char *)req + ch_offset);
9835 		err = check_rdma_desc(desc, ch_len, le32_to_cpu(req->Length));
9836 		if (err)
9837 			goto out;
9838 		err = smb2_set_rdma_key(work, desc,
9839 					req->Channel,
9840 					req->ReadChannelInfoLength);
9841 		if (err)
9842 			goto out;
9843 	}
9844 
9845 	fp = ksmbd_lookup_fd_slow(work, id, pid);
9846 	if (!fp) {
9847 		err = -ENOENT;
9848 		goto out;
9849 	}
9850 
9851 	err = smb2_set_request_open(work, fp, &req->hdr, true, true);
9852 	if (err)
9853 		goto out;
9854 
9855 	if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
9856 		pr_err("Not permitted to read : 0x%x\n", fp->daccess);
9857 		err = -EACCES;
9858 		goto out;
9859 	}
9860 
9861 	if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
9862 		err = setup_async_work(work, NULL, NULL);
9863 		if (err)
9864 			goto out;
9865 		smb2_send_interim_resp(work, STATUS_PENDING);
9866 		async_interim = true;
9867 	}
9868 
9869 	offset = le64_to_cpu(req->Offset);
9870 	if (offset < 0) {
9871 		err = -EINVAL;
9872 		goto out;
9873 	}
9874 	length = le32_to_cpu(req->Length);
9875 	mincount = le32_to_cpu(req->MinimumCount);
9876 
9877 	if (length > max_read_size) {
9878 		ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
9879 			    max_read_size);
9880 		err = -EINVAL;
9881 		goto out;
9882 	}
9883 
9884 	ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
9885 		    fp->filp, offset, length);
9886 
9887 	aux_payload_buf = kvmalloc(ALIGN(length, 8), KSMBD_DEFAULT_GFP);
9888 	if (!aux_payload_buf) {
9889 		err = -ENOMEM;
9890 		goto out;
9891 	}
9892 
9893 	nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
9894 	if (nbytes < 0) {
9895 		kvfree(aux_payload_buf);
9896 		err = nbytes;
9897 		goto out;
9898 	}
9899 
9900 	/*
9901 	 * ksmbd_vfs_read() fills only nbytes; the [nbytes, ALIGN(nbytes, 8))
9902 	 * tail of the un-zeroed buffer is transmitted as compound-response
9903 	 * alignment padding, leaking uninitialized kernel memory to the
9904 	 * client.  Zero just that tail.
9905 	 */
9906 	if (nbytes & 7)
9907 		memset(aux_payload_buf + nbytes, 0, ALIGN(nbytes, 8) - nbytes);
9908 
9909 	if ((nbytes == 0 && length != 0) || nbytes < mincount) {
9910 		kvfree(aux_payload_buf);
9911 		rsp->hdr.Status = STATUS_END_OF_FILE;
9912 		smb2_set_err_rsp(work);
9913 		if (async_interim)
9914 			release_async_work(work);
9915 		ksmbd_fd_put(work, fp);
9916 		return -ENODATA;
9917 	}
9918 
9919 	ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
9920 		    nbytes, offset, mincount);
9921 
9922 	if (is_rdma_channel == true) {
9923 		rdma_transform_len = smb2_prep_rdma_read(work, req,
9924 							 rsp,
9925 							 aux_payload_buf,
9926 							 nbytes);
9927 		if (rdma_transform_len < 0) {
9928 			kvfree(aux_payload_buf);
9929 			err = rdma_transform_len;
9930 			goto out;
9931 		}
9932 		/* write data to the client using rdma channel */
9933 		remain_bytes = smb2_read_rdma(work, req,
9934 					      aux_payload_buf,
9935 					      nbytes);
9936 		if (remain_bytes < 0)
9937 			pr_err("RDMA READ transfer failed: session=%llu payload=%zu transform=%d rc=%zd\n",
9938 			       work->sess ? work->sess->id : 0, nbytes,
9939 			       rdma_transform_len, remain_bytes);
9940 		else
9941 			ksmbd_debug(RDMA,
9942 				    "RDMA READ transfer completed: session=%llu payload=%zu transform=%d\n",
9943 				    work->sess ? work->sess->id : 0, nbytes,
9944 				    rdma_transform_len);
9945 		kvfree(aux_payload_buf);
9946 		aux_payload_buf = NULL;
9947 		nbytes = 0;
9948 		if (remain_bytes < 0) {
9949 			err = (int)remain_bytes;
9950 			goto out;
9951 		}
9952 	}
9953 
9954 	rsp->StructureSize = cpu_to_le16(17);
9955 	rsp->DataOffset = 80;
9956 	rsp->Reserved = 0;
9957 	rsp->DataLength = cpu_to_le32(rdma_transform_len ?: nbytes);
9958 	rsp->DataRemaining = cpu_to_le32(remain_bytes);
9959 	rsp->Flags = rdma_transform_len ?
9960 		SMB2_READFLAG_RESPONSE_RDMA_TRANSFORM : 0;
9961 	err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
9962 				     offsetof(struct smb2_read_rsp, Buffer) +
9963 				     rdma_transform_len,
9964 				     aux_payload_buf, nbytes);
9965 	if (err) {
9966 		kvfree(aux_payload_buf);
9967 		goto out;
9968 	}
9969 	if (async_interim)
9970 		release_async_work(work);
9971 	/*
9972 	 * RDMA responses are transferred through channel buffers and encrypted
9973 	 * responses use the encryption transform, so only normal SMB transport
9974 	 * responses are candidates for compression.
9975 	 */
9976 	if (!is_rdma_channel && nbytes &&
9977 	    (req->Flags & SMB2_READFLAG_REQUEST_COMPRESSED) &&
9978 	    conn->compress_algorithm != SMB3_COMPRESS_NONE)
9979 		work->compress_response = true;
9980 	ksmbd_fd_put(work, fp);
9981 	return 0;
9982 
9983 out:
9984 	if (async_interim)
9985 		release_async_work(work);
9986 	if (err) {
9987 		if (err == -EISDIR)
9988 			rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
9989 		else if (err == -EAGAIN)
9990 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
9991 		else if (err == -ENOENT)
9992 			rsp->hdr.Status = STATUS_FILE_CLOSED;
9993 		else if (err == -EACCES)
9994 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
9995 		else if (err == -ESHARE)
9996 			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
9997 		else if (err == -EINVAL)
9998 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
9999 		else
10000 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
10001 
10002 		smb2_set_err_rsp(work);
10003 	}
10004 	ksmbd_fd_put(work, fp);
10005 	return err;
10006 }
10007 
10008 /**
10009  * smb2_write_pipe() - handler for smb2 write on IPC pipe
10010  * @work:	smb work containing write IPC pipe command buffer
10011  *
10012  * Return:	0 on success, otherwise error
10013  */
10014 static noinline int smb2_write_pipe(struct ksmbd_work *work)
10015 {
10016 	struct smb2_write_req *req;
10017 	struct smb2_write_rsp *rsp;
10018 	struct ksmbd_rpc_command *rpc_resp;
10019 	struct ksmbd_session_rpc *rpc;
10020 	u64 id = 0;
10021 	int err = 0, ret = 0;
10022 	char *data_buf;
10023 	size_t length;
10024 	unsigned int data_offset, req_len;
10025 
10026 	WORK_BUFFERS(work, req, rsp);
10027 
10028 	length = le32_to_cpu(req->Length);
10029 	id = req->VolatileFileId;
10030 	data_offset = le16_to_cpu(req->DataOffset);
10031 	req_len = smb2_current_req_len(work, &req->hdr);
10032 
10033 	if (data_offset < offsetof(struct smb2_write_req, Buffer) ||
10034 	    data_offset > req_len || length > req_len - data_offset) {
10035 		pr_err("invalid write data offset %u, length %zu, req_len %u\n",
10036 		       data_offset, length, req_len);
10037 		err = -EINVAL;
10038 		goto out;
10039 	}
10040 
10041 	lockdep_assert_not_held(&work->sess->rpc_lock);
10042 	down_read(&work->sess->rpc_lock);
10043 	if (!ksmbd_session_rpc_method(work->sess, id)) {
10044 		up_read(&work->sess->rpc_lock);
10045 		rsp->hdr.Status = STATUS_FILE_CLOSED;
10046 		smb2_set_err_rsp(work);
10047 		return -ENOENT;
10048 	}
10049 	up_read(&work->sess->rpc_lock);
10050 
10051 	data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
10052 			   data_offset);
10053 
10054 	rpc = ksmbd_session_rpc_get(work, id);
10055 	if (IS_ERR(rpc)) {
10056 		err = PTR_ERR(rpc);
10057 		rsp->hdr.Status = smb2_pipe_error_status(err,
10058 							 STATUS_INVALID_HANDLE);
10059 		smb2_set_err_rsp(work);
10060 		return err;
10061 	}
10062 	rpc_resp = ksmbd_rpc_write(work->sess, rpc, data_buf, length);
10063 	ksmbd_session_rpc_put(rpc);
10064 	if (!rpc_resp) {
10065 		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
10066 		smb2_set_err_rsp(work);
10067 		return -EIO;
10068 	}
10069 	if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
10070 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
10071 		kvfree(rpc_resp);
10072 		smb2_set_err_rsp(work);
10073 		return -EOPNOTSUPP;
10074 	}
10075 	if (rpc_resp->flags != KSMBD_RPC_OK) {
10076 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
10077 		smb2_set_err_rsp(work);
10078 		kvfree(rpc_resp);
10079 		return ret;
10080 	}
10081 	kvfree(rpc_resp);
10082 
10083 	rsp->StructureSize = cpu_to_le16(17);
10084 	rsp->DataOffset = 0;
10085 	rsp->Reserved = 0;
10086 	rsp->DataLength = cpu_to_le32(length);
10087 	rsp->DataRemaining = 0;
10088 	rsp->Reserved2 = 0;
10089 	err = ksmbd_iov_pin_rsp(work, (void *)rsp,
10090 				offsetof(struct smb2_write_rsp, Buffer));
10091 out:
10092 	if (err) {
10093 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
10094 		smb2_set_err_rsp(work);
10095 	}
10096 
10097 	return err;
10098 }
10099 
10100 /**
10101  * smb2_write_rdma() - receive and store an RDMA WRITE payload
10102  * @work: request work item
10103  * @desc: client RDMA buffer descriptors
10104  * @desc_len: descriptor array length
10105  * @transform: parsed transform, or NULL for an untransformed transfer
10106  * @fp: target open file
10107  * @offset: target file offset
10108  * @length: transfer length
10109  * @sync: request synchronous storage completion
10110  *
10111  * Receive the payload, authenticate or decrypt it when required, and write it
10112  * to the target file.
10113  *
10114  * Return: written byte count on success, otherwise a negative errno
10115  */
10116 static ssize_t smb2_write_rdma(struct ksmbd_work *work,
10117 			       struct smbdirect_buffer_descriptor_v1 *desc,
10118 			       unsigned int desc_len,
10119 			       struct smb2_rdma_write_transform *transform,
10120 			       struct ksmbd_file *fp, loff_t offset,
10121 			       size_t length, bool sync)
10122 {
10123 	char *data_buf;
10124 	int ret;
10125 	ssize_t nbytes;
10126 
10127 	data_buf = kvzalloc(length, KSMBD_DEFAULT_GFP);
10128 	if (!data_buf)
10129 		return -ENOMEM;
10130 
10131 	ret = ksmbd_conn_rdma_read(work->conn, data_buf, length, desc,
10132 				   desc_len);
10133 	if (ret < 0) {
10134 		if (transform)
10135 			pr_err("RDMA WRITE encrypted transfer failed: session=%llu payload=%zu rdma_read_rc=%d\n",
10136 			       work->sess->id, length, ret);
10137 		kvfree(data_buf);
10138 		return ret;
10139 	}
10140 	if (transform &&
10141 	    transform->type == SMB2_RDMA_TRANSFORM_TYPE_ENCRYPTION) {
10142 		ret = ksmbd_crypt_rdma(work->conn,
10143 				       work->sess->smb3decryptionkey,
10144 				       data_buf, length, transform->nonce,
10145 				       transform->nonce_len,
10146 				       transform->crypto->Signature,
10147 				       transform->signature_len, false);
10148 		if (ret) {
10149 			pr_err("RDMA WRITE decryption failed: session=%llu payload=%zu rc=%d\n",
10150 			       work->sess->id, length, ret);
10151 			kvfree(data_buf);
10152 			return ret == -ENOMEM ? ret : -EBADMSG;
10153 		}
10154 	}
10155 
10156 	ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
10157 	kvfree(data_buf);
10158 	if (ret < 0) {
10159 		if (transform)
10160 			pr_err("RDMA WRITE encrypted file write failed: session=%llu payload=%zu rc=%d\n",
10161 			       work->sess->id, length, ret);
10162 		return ret;
10163 	}
10164 	ksmbd_debug(RDMA,
10165 		    "RDMA WRITE transfer completed: session=%llu payload=%zu transformed=%u written=%zd\n",
10166 		    work->sess ? work->sess->id : 0, length, !!transform, nbytes);
10167 
10168 	return nbytes;
10169 }
10170 
10171 /**
10172  * smb2_write() - handler for smb2 write from file
10173  * @work:	smb work containing write command buffer
10174  *
10175  * Return:	0 on success, otherwise error
10176  */
10177 int smb2_write(struct ksmbd_work *work)
10178 {
10179 	struct smb2_write_req *req;
10180 	struct smb2_write_rsp *rsp;
10181 	struct smb2_rdma_write_transform rdma_transform = {};
10182 	struct smb2_rdma_write_transform *rdma_info = NULL;
10183 	struct smbdirect_buffer_descriptor_v1 *rdma_desc = NULL;
10184 	unsigned int rdma_desc_len = 0;
10185 	struct ksmbd_file *fp = NULL;
10186 	loff_t offset;
10187 	size_t length;
10188 	ssize_t nbytes;
10189 	char *data_buf;
10190 	bool writethrough = false, is_rdma_channel = false;
10191 	bool append_write;
10192 	bool async_interim = false;
10193 	bool chseq_err = false;
10194 	int err = 0;
10195 	unsigned int max_write_size = work->conn->vals->max_write_size;
10196 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
10197 
10198 	ksmbd_debug(SMB, "Received smb2 write request\n");
10199 
10200 	WORK_BUFFERS(work, req, rsp);
10201 
10202 	if (smb2_compound_has_failed(work, &rsp->hdr))
10203 		return -EACCES;
10204 
10205 	if (work->next_smb2_rcv_hdr_off &&
10206 	    !has_file_id(req->VolatileFileId)) {
10207 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
10208 			    work->compound_fid);
10209 		id = work->compound_fid;
10210 		pid = work->compound_pfid;
10211 	}
10212 
10213 	if (!has_file_id(id)) {
10214 		id = req->VolatileFileId;
10215 		pid = req->PersistentFileId;
10216 	}
10217 
10218 	if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
10219 		ksmbd_debug(SMB, "IPC pipe write request\n");
10220 		return smb2_write_pipe(work);
10221 	}
10222 
10223 	append_write = le64_to_cpu(req->Offset) == U64_MAX;
10224 	offset = append_write ? 0 : le64_to_cpu(req->Offset);
10225 	if (offset < 0) {
10226 		err = -EINVAL;
10227 		goto out;
10228 	}
10229 	length = le32_to_cpu(req->Length);
10230 
10231 	if (req->Channel != SMB2_CHANNEL_NONE &&
10232 	    req->Channel != SMB2_CHANNEL_RDMA_V1 &&
10233 	    req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE &&
10234 	    req->Channel != SMB2_CHANNEL_RDMA_TRANSFORM) {
10235 		err = -EINVAL;
10236 		goto out;
10237 	}
10238 	if (req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM &&
10239 	    work->conn->dialect != SMB311_PROT_ID) {
10240 		err = -EINVAL;
10241 		goto out;
10242 	}
10243 	if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
10244 	    req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
10245 	    req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM) {
10246 		is_rdma_channel = true;
10247 		max_write_size = get_smbd_max_read_write_size(work->conn->transport);
10248 		if (max_write_size == 0) {
10249 			err = -EINVAL;
10250 			goto out;
10251 		}
10252 		length = le32_to_cpu(req->RemainingBytes);
10253 	}
10254 
10255 	if (length) {
10256 		u64 end = (u64)offset + length;
10257 
10258 		if (end > SMB2_MAX_FILE_SIZE) {
10259 			err = -EINVAL;
10260 			goto out;
10261 		}
10262 		if (end == SMB2_MAX_FILE_SIZE) {
10263 			err = -EFBIG;
10264 			goto out;
10265 		}
10266 	}
10267 
10268 	if (is_rdma_channel == true) {
10269 		unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
10270 		unsigned int ch_len = le16_to_cpu(req->WriteChannelInfoLength);
10271 		unsigned int req_len = smb2_current_req_len(work, &req->hdr);
10272 
10273 		if (!length || req->Length != 0 || req->DataOffset != 0 ||
10274 		    ch_offset < offsetof(struct smb2_write_req, Buffer) ||
10275 		    ch_offset > req_len || ch_len > req_len - ch_offset) {
10276 			err = -EINVAL;
10277 			goto out;
10278 		}
10279 		if (req->Channel == SMB2_CHANNEL_RDMA_TRANSFORM) {
10280 			err = smb2_parse_rdma_write_transform(work, req,
10281 							      &rdma_transform);
10282 			if (err) {
10283 				pr_err("RDMA WRITE encryption metadata rejected: session=%llu rc=%d\n",
10284 				       work->sess ? work->sess->id : 0, err);
10285 				goto out;
10286 			}
10287 			rdma_desc = rdma_transform.desc;
10288 			rdma_desc_len = rdma_transform.desc_len;
10289 			rdma_info = &rdma_transform;
10290 			err = smb2_set_rdma_key(work, rdma_desc,
10291 						rdma_transform.channel,
10292 						cpu_to_le16(rdma_desc_len));
10293 		} else {
10294 			rdma_desc = (struct smbdirect_buffer_descriptor_v1 *)
10295 				((char *)req + ch_offset);
10296 			rdma_desc_len = ch_len;
10297 			err = check_rdma_desc(rdma_desc, rdma_desc_len, length);
10298 			if (err)
10299 				goto out;
10300 			err = smb2_set_rdma_key(work, rdma_desc,
10301 						req->Channel,
10302 						req->WriteChannelInfoLength);
10303 		}
10304 		if (err)
10305 			goto out;
10306 	}
10307 
10308 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
10309 		ksmbd_debug(SMB, "User does not have write permission\n");
10310 		err = -EACCES;
10311 		goto out;
10312 	}
10313 
10314 	fp = ksmbd_lookup_fd_slow(work, id, pid);
10315 	if (!fp) {
10316 		err = -ENOENT;
10317 		goto out;
10318 	}
10319 
10320 	err = smb2_set_request_open(work, fp, &req->hdr, true, false);
10321 	if (err) {
10322 		rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
10323 		chseq_err = true;
10324 		goto out;
10325 	}
10326 
10327 	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE))) {
10328 		pr_err("Not permitted to write : 0x%x\n", fp->daccess);
10329 		err = -EACCES;
10330 		goto out;
10331 	}
10332 	if (append_write != fp->posix_append) {
10333 		err = -EINVAL;
10334 		goto out;
10335 	}
10336 
10337 	if (work->next_smb2_rcv_hdr_off && !req->hdr.NextCommand) {
10338 		err = setup_async_work(work, NULL, NULL);
10339 		if (err)
10340 			goto out;
10341 		smb2_send_interim_resp(work, STATUS_PENDING);
10342 		async_interim = true;
10343 	}
10344 
10345 	if (length > max_write_size) {
10346 		ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
10347 			    max_write_size);
10348 		err = -EINVAL;
10349 		goto out;
10350 	}
10351 
10352 	ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
10353 	if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
10354 		writethrough = true;
10355 
10356 	if (is_rdma_channel == false) {
10357 		unsigned int data_offset = le16_to_cpu(req->DataOffset);
10358 		unsigned int req_len = smb2_current_req_len(work, &req->hdr);
10359 
10360 		if (data_offset < offsetof(struct smb2_write_req, Buffer) ||
10361 		    data_offset > req_len ||
10362 		    length > req_len - data_offset) {
10363 			ksmbd_debug(SMB,
10364 				    "invalid write data offset %u, length %zu, req_len %u\n",
10365 				    data_offset, length, req_len);
10366 			err = -EINVAL;
10367 			goto out;
10368 		}
10369 
10370 		data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
10371 				    data_offset);
10372 
10373 		ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
10374 			    fp->filp, offset, length);
10375 		err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
10376 				      writethrough, &nbytes);
10377 		if (err < 0)
10378 			goto out;
10379 	} else {
10380 		/* read data from the client using rdma channel, and
10381 		 * write the data.
10382 		 */
10383 		nbytes = smb2_write_rdma(work, rdma_desc, rdma_desc_len,
10384 					 rdma_info, fp, offset, length,
10385 					 writethrough);
10386 		if (nbytes < 0) {
10387 			err = (int)nbytes;
10388 			goto out;
10389 		}
10390 	}
10391 
10392 	rsp->StructureSize = cpu_to_le16(17);
10393 	rsp->DataOffset = 0;
10394 	rsp->Reserved = 0;
10395 	rsp->DataLength = cpu_to_le32(nbytes);
10396 	rsp->DataRemaining = 0;
10397 	rsp->Reserved2 = 0;
10398 	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
10399 	if (err)
10400 		goto out;
10401 	if (async_interim)
10402 		release_async_work(work);
10403 	ksmbd_fd_put(work, fp);
10404 	return 0;
10405 
10406 out:
10407 	if (async_interim)
10408 		release_async_work(work);
10409 
10410 	if (err == -EAGAIN && !chseq_err)
10411 		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
10412 	else if (err == -ENOSPC || err == -EFBIG)
10413 		rsp->hdr.Status = STATUS_DISK_FULL;
10414 	else if (err == -ENOENT)
10415 		rsp->hdr.Status = STATUS_FILE_CLOSED;
10416 	else if (err == -EACCES)
10417 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
10418 	else if (err == -ESHARE)
10419 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
10420 	else if (err == -EINVAL)
10421 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
10422 	else if (err == -EBADMSG)
10423 		rsp->hdr.Status = STATUS_AUTH_TAG_MISMATCH;
10424 	else if (err == -EKEYREJECTED)
10425 		rsp->hdr.Status = STATUS_INVALID_SIGNATURE;
10426 	else if (rsp->hdr.Status == 0)
10427 		rsp->hdr.Status = STATUS_INVALID_HANDLE;
10428 
10429 	smb2_set_err_rsp(work);
10430 	ksmbd_fd_put(work, fp);
10431 	return err;
10432 }
10433 
10434 /**
10435  * smb2_flush() - handler for smb2 flush file - fsync
10436  * @work:	smb work containing flush command buffer
10437  *
10438  * Return:	0 on success, otherwise error
10439  */
10440 int smb2_flush(struct ksmbd_work *work)
10441 {
10442 	struct smb2_flush_req *req;
10443 	struct smb2_flush_rsp *rsp;
10444 	u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
10445 	int err;
10446 
10447 	WORK_BUFFERS(work, req, rsp);
10448 
10449 	ksmbd_debug(SMB, "Received smb2 flush request(fid : %llu)\n", req->VolatileFileId);
10450 
10451 	if (smb2_compound_has_failed(work, &rsp->hdr))
10452 		return -EACCES;
10453 
10454 	if (work->next_smb2_rcv_hdr_off &&
10455 	    !has_file_id(req->VolatileFileId)) {
10456 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
10457 			    work->compound_fid);
10458 		id = work->compound_fid;
10459 		pid = work->compound_pfid;
10460 	}
10461 
10462 	if (!has_file_id(id)) {
10463 		id = req->VolatileFileId;
10464 		pid = req->PersistentFileId;
10465 	}
10466 
10467 	err = ksmbd_vfs_fsync(work, id, pid);
10468 	if (err)
10469 		goto out;
10470 
10471 	rsp->StructureSize = cpu_to_le16(4);
10472 	rsp->Reserved = 0;
10473 	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
10474 
10475 out:
10476 	rsp->hdr.Status = STATUS_INVALID_HANDLE;
10477 	smb2_set_err_rsp(work);
10478 	return err;
10479 }
10480 
10481 /**
10482  * smb2_cancel() - handler for smb2 cancel command
10483  * @work:	smb work containing cancel command buffer
10484  *
10485  * Return:	0 on success, otherwise error
10486  */
10487 int smb2_cancel(struct ksmbd_work *work)
10488 {
10489 	struct ksmbd_conn *conn = work->conn;
10490 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
10491 	struct smb2_hdr *chdr;
10492 	struct ksmbd_work *iter;
10493 	struct list_head *command_list;
10494 
10495 	if (work->next_smb2_rcv_hdr_off)
10496 		hdr = ksmbd_resp_buf_next(work);
10497 
10498 	ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
10499 		    le64_to_cpu(hdr->MessageId),
10500 		    le32_to_cpu(hdr->Flags));
10501 
10502 	if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
10503 		command_list = &conn->async_requests;
10504 
10505 		spin_lock(&conn->request_lock);
10506 		list_for_each_entry(iter, command_list,
10507 				    async_request_entry) {
10508 			chdr = smb_get_msg(iter->request_buf);
10509 
10510 			if (iter->async_id !=
10511 			    le64_to_cpu(hdr->Id.AsyncId))
10512 				continue;
10513 
10514 			/*
10515 			 * Only an ACTIVE deferred work may have its cancel_fn
10516 			 * fired.  A CANCELLED or CLOSED work already took the
10517 			 * smb2_lock() non-ACTIVE early-exit that frees the
10518 			 * file_lock and skips release_async_work(), so it is
10519 			 * still on conn->async_requests with a live cancel_fn
10520 			 * pointing at the freed file_lock.
10521 			 */
10522 			if (cmpxchg(&iter->state, KSMBD_WORK_ACTIVE,
10523 				    KSMBD_WORK_CANCELLED) != KSMBD_WORK_ACTIVE)
10524 				break;
10525 
10526 			ksmbd_debug(SMB,
10527 				    "smb2 with AsyncId %llu cancelled command = 0x%x\n",
10528 				    le64_to_cpu(hdr->Id.AsyncId),
10529 				    le16_to_cpu(chdr->Command));
10530 			if (iter->cancel_fn)
10531 				iter->cancel_fn(iter->cancel_argv);
10532 			break;
10533 		}
10534 		spin_unlock(&conn->request_lock);
10535 	} else {
10536 		command_list = &conn->requests;
10537 
10538 		spin_lock(&conn->request_lock);
10539 		list_for_each_entry(iter, command_list, request_entry) {
10540 			chdr = smb_get_msg(iter->request_buf);
10541 
10542 			if (chdr->MessageId != hdr->MessageId ||
10543 			    iter == work)
10544 				continue;
10545 
10546 			if (cmpxchg(&iter->state, KSMBD_WORK_ACTIVE,
10547 				    KSMBD_WORK_CANCELLED) != KSMBD_WORK_ACTIVE)
10548 				break;
10549 
10550 			ksmbd_debug(SMB,
10551 				    "smb2 with mid %llu cancelled command = 0x%x\n",
10552 				    le64_to_cpu(hdr->MessageId),
10553 				    le16_to_cpu(chdr->Command));
10554 			if (iter->cancel_fn)
10555 				iter->cancel_fn(iter->cancel_argv);
10556 			break;
10557 		}
10558 		spin_unlock(&conn->request_lock);
10559 	}
10560 
10561 	/* For SMB2_CANCEL command itself send no response*/
10562 	work->send_no_response = 1;
10563 	return 0;
10564 }
10565 
10566 struct file_lock *smb_flock_init(struct file *f)
10567 {
10568 	struct file_lock *fl;
10569 
10570 	fl = locks_alloc_lock();
10571 	if (!fl)
10572 		goto out;
10573 
10574 	locks_init_lock(fl);
10575 
10576 	fl->c.flc_owner = f;
10577 	fl->c.flc_pid = current->tgid;
10578 	fl->c.flc_file = f;
10579 	fl->c.flc_flags = FL_POSIX;
10580 	fl->fl_ops = NULL;
10581 	fl->fl_lmops = NULL;
10582 
10583 out:
10584 	return fl;
10585 }
10586 
10587 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
10588 {
10589 	int cmd = -EINVAL;
10590 
10591 	/* Checking for wrong flag combination during lock request*/
10592 	switch (flags) {
10593 	case SMB2_LOCKFLAG_SHARED:
10594 		ksmbd_debug(SMB, "received shared request\n");
10595 		cmd = F_SETLKW;
10596 		flock->c.flc_type = F_RDLCK;
10597 		flock->c.flc_flags |= FL_SLEEP;
10598 		break;
10599 	case SMB2_LOCKFLAG_EXCLUSIVE:
10600 		ksmbd_debug(SMB, "received exclusive request\n");
10601 		cmd = F_SETLKW;
10602 		flock->c.flc_type = F_WRLCK;
10603 		flock->c.flc_flags |= FL_SLEEP;
10604 		break;
10605 	case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
10606 		ksmbd_debug(SMB,
10607 			    "received shared & fail immediately request\n");
10608 		cmd = F_SETLK;
10609 		flock->c.flc_type = F_RDLCK;
10610 		break;
10611 	case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
10612 		ksmbd_debug(SMB,
10613 			    "received exclusive & fail immediately request\n");
10614 		cmd = F_SETLK;
10615 		flock->c.flc_type = F_WRLCK;
10616 		break;
10617 	case SMB2_LOCKFLAG_UNLOCK:
10618 		ksmbd_debug(SMB, "received unlock request\n");
10619 		flock->c.flc_type = F_UNLCK;
10620 		cmd = F_SETLK;
10621 		break;
10622 	}
10623 
10624 	return cmd;
10625 }
10626 
10627 /* Track SMB locks that cannot be represented by a signed loff_t. */
10628 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
10629 					 unsigned int cmd, int flags, bool zero_len,
10630 					 u64 start, u64 end, bool virtual_lock,
10631 					 struct list_head *lock_list)
10632 {
10633 	struct ksmbd_lock *lock;
10634 
10635 	lock = kzalloc_obj(struct ksmbd_lock, KSMBD_DEFAULT_GFP);
10636 	if (!lock)
10637 		return NULL;
10638 
10639 	lock->cmd = cmd;
10640 	lock->fl = flock;
10641 	lock->start = start;
10642 	lock->end = end;
10643 	lock->flags = flags;
10644 	lock->zero_len = zero_len;
10645 	lock->virtual_lock = virtual_lock;
10646 	INIT_HLIST_NODE(&lock->hlist);
10647 	INIT_LIST_HEAD(&lock->flist);
10648 	INIT_LIST_HEAD(&lock->llist);
10649 	list_add_tail(&lock->llist, lock_list);
10650 
10651 	return lock;
10652 }
10653 
10654 static void smb2_virtual_lock_cancel(void **argv)
10655 {
10656 	(void)argv;
10657 	wake_up_all(&ksmbd_lock_wait);
10658 }
10659 
10660 static int smb2_virtual_lock_wait(struct ksmbd_work *work,
10661 				  struct ksmbd_file *fp,
10662 				  struct ksmbd_lock *smb_lock,
10663 				  struct smb2_lock_rsp *rsp)
10664 {
10665 	void **argv = NULL;
10666 	bool async = false;
10667 	int ret;
10668 
10669 	for (;;) {
10670 		ret = ksmbd_file_lock_reserve(fp, smb_lock);
10671 		if (ret != -EAGAIN ||
10672 		    (smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
10673 			break;
10674 
10675 		if (!async) {
10676 			argv = kmalloc_obj(*argv, KSMBD_DEFAULT_GFP);
10677 			if (!argv)
10678 				return -ENOMEM;
10679 			argv[0] = NULL;
10680 			ret = setup_async_work(work, smb2_virtual_lock_cancel, argv);
10681 			if (ret) {
10682 				kfree(argv);
10683 				return ret;
10684 			}
10685 			async = true;
10686 
10687 			read_lock(&work->sess->file_table.lock);
10688 			if (fp->f_state != FP_INITED) {
10689 				read_unlock(&work->sess->file_table.lock);
10690 				release_async_work(work);
10691 				return -ENOENT;
10692 			}
10693 			spin_lock(&fp->f_lock);
10694 			list_add(&work->fp_entry, &fp->blocked_works);
10695 			spin_unlock(&fp->f_lock);
10696 			read_unlock(&work->sess->file_table.lock);
10697 			smb2_send_interim_resp(work, STATUS_PENDING);
10698 		}
10699 
10700 		wait_event(ksmbd_lock_wait,
10701 			   READ_ONCE(work->state) != KSMBD_WORK_ACTIVE ||
10702 			   !ksmbd_file_lock_conflict(smb_lock));
10703 
10704 		if (READ_ONCE(work->state) != KSMBD_WORK_ACTIVE) {
10705 			spin_lock(&fp->f_lock);
10706 			list_del_init(&work->fp_entry);
10707 			spin_unlock(&fp->f_lock);
10708 			if (work->state == KSMBD_WORK_CANCELLED) {
10709 				rsp->hdr.Status = STATUS_CANCELLED;
10710 				smb2_send_interim_resp(work, STATUS_CANCELLED);
10711 				work->send_no_response = 1;
10712 				ret = -ECANCELED;
10713 			} else {
10714 				rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
10715 				ret = -EIO;
10716 			}
10717 			release_async_work(work);
10718 			return ret;
10719 		}
10720 	}
10721 
10722 	if (async) {
10723 		bool cancelled;
10724 
10725 		spin_lock(&fp->f_lock);
10726 		list_del_init(&work->fp_entry);
10727 		cancelled = READ_ONCE(work->state) != KSMBD_WORK_ACTIVE;
10728 		spin_unlock(&fp->f_lock);
10729 		release_async_work(work);
10730 		if (cancelled) {
10731 			ksmbd_file_lock_remove(smb_lock);
10732 			if (work->state == KSMBD_WORK_CANCELLED) {
10733 				rsp->hdr.Status = STATUS_CANCELLED;
10734 				smb2_send_interim_resp(work, STATUS_CANCELLED);
10735 				work->send_no_response = 1;
10736 				return -ECANCELED;
10737 			}
10738 			rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
10739 			return -EIO;
10740 		}
10741 	}
10742 
10743 	return ret;
10744 }
10745 
10746 static void smb2_free_ksmbd_lock(struct ksmbd_lock *smb_lock)
10747 {
10748 	if (smb_lock->vfs_locked)
10749 		ksmbd_vfs_posix_lock_unblock(smb_lock->fl);
10750 	locks_free_lock(smb_lock->fl);
10751 	kfree(smb_lock);
10752 }
10753 
10754 static void smb2_remove_blocked_lock(void **argv)
10755 {
10756 	struct file_lock *flock = (struct file_lock *)argv[0];
10757 
10758 	ksmbd_vfs_posix_lock_unblock(flock);
10759 	locks_wake_up(flock);
10760 }
10761 
10762 static void smb2_free_blocked_lock(struct file_lock *flock)
10763 {
10764 	ksmbd_vfs_posix_lock_unblock(flock);
10765 	locks_wake_up(flock);
10766 	locks_free_lock(flock);
10767 }
10768 
10769 /**
10770  * smb2_lock() - handler for smb2 file lock command
10771  * @work:	smb work containing lock command buffer
10772  *
10773  * Return:	0 on success, otherwise error
10774  */
10775 int smb2_lock(struct ksmbd_work *work)
10776 {
10777 	struct smb2_lock_req *req;
10778 	struct smb2_lock_rsp *rsp;
10779 	struct smb2_lock_element *lock_ele;
10780 	struct ksmbd_file *fp = NULL;
10781 	struct file_lock *flock = NULL;
10782 	struct file *filp = NULL;
10783 	int lock_count;
10784 	int flags = 0;
10785 	int cmd = 0;
10786 	int err = -EIO, i, rc = 0;
10787 	u64 lock_start, lock_length, lock_end;
10788 	struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp;
10789 	LIST_HEAD(lock_list);
10790 	LIST_HEAD(rollback_list);
10791 	int prior_lock = 0;
10792 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
10793 	bool lock_replayed;
10794 	bool virtual_lock;
10795 
10796 	WORK_BUFFERS(work, req, rsp);
10797 
10798 	ksmbd_debug(SMB, "Received smb2 lock request\n");
10799 
10800 	if (smb2_compound_has_failed(work, &rsp->hdr))
10801 		return -EACCES;
10802 
10803 	if (work->next_smb2_rcv_hdr_off &&
10804 	    !has_file_id(req->VolatileFileId)) {
10805 		ksmbd_debug(SMB, "Compound request set FID = %llu\n",
10806 			    work->compound_fid);
10807 		id = work->compound_fid;
10808 		pid = work->compound_pfid;
10809 	}
10810 
10811 	if (!has_file_id(id)) {
10812 		id = req->VolatileFileId;
10813 		pid = req->PersistentFileId;
10814 	}
10815 
10816 	fp = ksmbd_lookup_fd_slow(work, id, pid);
10817 	if (!fp) {
10818 		ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
10819 		err = -ENOENT;
10820 		goto out2;
10821 	}
10822 
10823 	err = smb2_set_request_open(work, fp, &req->hdr, false, false);
10824 	if (err)
10825 		goto out2;
10826 
10827 	lock_replayed = smb2_verify_lock_sequence(work, fp, req);
10828 	if (lock_replayed)
10829 		goto lock_success;
10830 
10831 	filp = fp->filp;
10832 	lock_count = le16_to_cpu(req->LockCount);
10833 	lock_ele = req->locks;
10834 
10835 	ksmbd_debug(SMB, "lock count is %d\n", lock_count);
10836 	/*
10837 	 * Cap lock_count at 64. The MS-SMB2 spec defines Open.LockSequenceArray
10838 	 * as exactly 64 entries so 64 is the intended ceiling. No real workload
10839 	 * comes close to this in a single request.
10840 	 */
10841 	if (!lock_count || lock_count > 64) {
10842 		err = -EINVAL;
10843 		goto out2;
10844 	}
10845 
10846 	for (i = 0; i < lock_count; i++) {
10847 		flags = le32_to_cpu(lock_ele[i].Flags);
10848 
10849 		flock = smb_flock_init(filp);
10850 		if (!flock)
10851 			goto out;
10852 
10853 		cmd = smb2_set_flock_flags(flock, flags);
10854 
10855 		lock_start = le64_to_cpu(lock_ele[i].Offset);
10856 		lock_length = le64_to_cpu(lock_ele[i].Length);
10857 		if (lock_length && lock_length - 1 > U64_MAX - lock_start) {
10858 			pr_err("Invalid lock range requested\n");
10859 			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
10860 			locks_free_lock(flock);
10861 			goto out;
10862 		}
10863 
10864 		lock_end = lock_length ? lock_start + lock_length - 1 : lock_start;
10865 		virtual_lock = lock_end > OFFSET_MAX;
10866 
10867 		/* Lock the representable portion in VFS as well. */
10868 		if (lock_start > OFFSET_MAX) {
10869 			flock->fl_start = 0;
10870 			flock->fl_end = 0;
10871 		} else {
10872 			flock->fl_start = lock_start;
10873 			flock->fl_end = min_t(u64, lock_end, OFFSET_MAX);
10874 		}
10875 
10876 		/* Check conflict locks in one request */
10877 		list_for_each_entry(cmp_lock, &lock_list, llist) {
10878 			if (cmp_lock->start <= lock_start &&
10879 			    cmp_lock->end >= lock_end) {
10880 				if (cmp_lock->fl->c.flc_type != F_UNLCK &&
10881 				    flock->c.flc_type != F_UNLCK) {
10882 					pr_err("conflict two locks in one request\n");
10883 					err = -EINVAL;
10884 					locks_free_lock(flock);
10885 					goto out;
10886 				}
10887 			}
10888 		}
10889 
10890 		smb_lock = smb2_lock_init(flock, cmd, flags, !lock_length,
10891 					   lock_start, lock_end, virtual_lock,
10892 					   &lock_list);
10893 		if (!smb_lock) {
10894 			err = -EINVAL;
10895 			locks_free_lock(flock);
10896 			goto out;
10897 		}
10898 	}
10899 
10900 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
10901 		if (lock_count > 1 &&
10902 		    !(le32_to_cpu(lock_ele[0].Flags) & SMB2_LOCKFLAG_UNLOCK) &&
10903 		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY)) {
10904 			err = -EINVAL;
10905 			goto out;
10906 		}
10907 
10908 		if (smb_lock->cmd < 0) {
10909 			err = -EINVAL;
10910 			goto out;
10911 		}
10912 
10913 		if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
10914 			err = -EINVAL;
10915 			goto out;
10916 		}
10917 
10918 		if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
10919 		     smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
10920 		    (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
10921 		     !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
10922 			err = -EINVAL;
10923 			goto out;
10924 		}
10925 
10926 		prior_lock = smb_lock->flags;
10927 
10928 		/* The SMB lock table stores ranges that file_lock cannot express. */
10929 		if (smb_lock->virtual_lock &&
10930 		    !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))
10931 			goto no_check_cl;
10932 		if (smb_lock->virtual_lock &&
10933 		    (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK)) {
10934 			err = ksmbd_file_lock_unlock(smb_lock);
10935 			if (err) {
10936 				rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
10937 				goto out;
10938 			}
10939 			list_del(&smb_lock->llist);
10940 			smb2_free_ksmbd_lock(smb_lock);
10941 			continue;
10942 		}
10943 
10944 		if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
10945 		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
10946 			goto no_check_cl;
10947 
10948 		err = ksmbd_file_lock_check(smb_lock);
10949 		if (err) {
10950 			if (err == -ENOENT)
10951 				rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
10952 			goto out;
10953 		}
10954 
10955 no_check_cl:
10956 		flock = smb_lock->fl;
10957 		list_del(&smb_lock->llist);
10958 
10959 		if (smb_lock->virtual_lock &&
10960 		    !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK)) {
10961 			rc = smb2_virtual_lock_wait(work, fp, smb_lock, rsp);
10962 			if (rc) {
10963 				err = rc;
10964 				smb2_free_ksmbd_lock(smb_lock);
10965 				goto out;
10966 			}
10967 			list_add(&smb_lock->llist, &rollback_list);
10968 			if (smb_lock->start > OFFSET_MAX)
10969 				continue;
10970 		}
10971 
10972 		if (smb_lock->zero_len) {
10973 			rc = 0;
10974 			err = 0;
10975 			goto skip;
10976 		}
10977 retry:
10978 		rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
10979 skip:
10980 		if (smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) {
10981 			locks_free_lock(flock);
10982 			kfree(smb_lock);
10983 			if (!rc) {
10984 				ksmbd_debug(SMB, "File unlocked\n");
10985 			} else if (rc == -ENOENT) {
10986 				rsp->hdr.Status = STATUS_NOT_LOCKED;
10987 				err = rc;
10988 				goto out;
10989 			}
10990 		} else {
10991 			if (rc == FILE_LOCK_DEFERRED) {
10992 				void **argv;
10993 
10994 				ksmbd_debug(SMB,
10995 					    "would have to wait for getting lock\n");
10996 
10997 				argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP);
10998 				if (!argv) {
10999 					err = -ENOMEM;
11000 					if (smb_lock->virtual_lock) {
11001 						ksmbd_vfs_posix_lock_unblock(flock);
11002 						locks_wake_up(flock);
11003 						goto out;
11004 					}
11005 					smb2_free_blocked_lock(flock);
11006 					kfree(smb_lock);
11007 					goto out;
11008 				}
11009 				argv[0] = flock;
11010 
11011 				rc = setup_async_work(work,
11012 						      smb2_remove_blocked_lock,
11013 						      argv);
11014 				if (rc) {
11015 					kfree(argv);
11016 					err = -ENOMEM;
11017 					if (smb_lock->virtual_lock) {
11018 						ksmbd_vfs_posix_lock_unblock(flock);
11019 						locks_wake_up(flock);
11020 						goto out;
11021 					}
11022 					smb2_free_blocked_lock(flock);
11023 					kfree(smb_lock);
11024 					goto out;
11025 				}
11026 				if (!smb_lock->virtual_lock)
11027 					list_add(&smb_lock->llist, &rollback_list);
11028 				spin_lock(&fp->f_lock);
11029 				list_add(&work->fp_entry, &fp->blocked_works);
11030 				spin_unlock(&fp->f_lock);
11031 
11032 				smb2_send_interim_resp(work, STATUS_PENDING);
11033 
11034 				ksmbd_vfs_posix_lock_wait(flock);
11035 
11036 				spin_lock(&fp->f_lock);
11037 				list_del(&work->fp_entry);
11038 				spin_unlock(&fp->f_lock);
11039 
11040 				if (!smb_lock->virtual_lock)
11041 					list_del(&smb_lock->llist);
11042 
11043 				if (work->state == KSMBD_WORK_CANCELLED) {
11044 					rsp->hdr.Status = STATUS_CANCELLED;
11045 					smb2_send_interim_resp(work,
11046 							STATUS_CANCELLED);
11047 					release_async_work(work);
11048 					work->send_no_response = 1;
11049 					if (!smb_lock->virtual_lock) {
11050 						kfree(smb_lock);
11051 						locks_free_lock(flock);
11052 					}
11053 					goto out;
11054 				}
11055 
11056 				release_async_work(work);
11057 
11058 				if (work->state == KSMBD_WORK_ACTIVE)
11059 					goto retry;
11060 
11061 				rsp->hdr.Status =
11062 					STATUS_RANGE_NOT_LOCKED;
11063 				if (!smb_lock->virtual_lock) {
11064 					locks_free_lock(flock);
11065 					kfree(smb_lock);
11066 				}
11067 				/* rollback_list may still hold earlier grants */
11068 				goto out;
11069 			} else if (!rc) {
11070 				smb_lock->vfs_locked = !smb_lock->zero_len;
11071 				if (!smb_lock->virtual_lock)
11072 					list_add(&smb_lock->llist, &rollback_list);
11073 				ksmbd_debug(SMB, "successful in taking lock\n");
11074 			} else {
11075 				err = rc;
11076 				if (!smb_lock->virtual_lock) {
11077 					locks_free_lock(flock);
11078 					kfree(smb_lock);
11079 				}
11080 				goto out;
11081 			}
11082 		}
11083 	}
11084 
11085 	if (atomic_read(&fp->f_ci->op_count) > 1)
11086 		smb_break_all_oplock(work, fp);
11087 
11088 lock_success:
11089 	rsp->StructureSize = cpu_to_le16(4);
11090 	ksmbd_debug(SMB, "successful in taking lock\n");
11091 	rsp->hdr.Status = STATUS_SUCCESS;
11092 	rsp->Reserved = 0;
11093 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
11094 	if (err)
11095 		goto out;
11096 
11097 	/* publish only once the whole batch has committed */
11098 	ksmbd_file_lock_add(fp, &rollback_list);
11099 
11100 	if (!lock_replayed)
11101 		smb2_update_lock_sequence(work, fp, req);
11102 
11103 	ksmbd_fd_put(work, fp);
11104 	return 0;
11105 
11106 out:
11107 	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
11108 		locks_free_lock(smb_lock->fl);
11109 		list_del(&smb_lock->llist);
11110 		kfree(smb_lock);
11111 	}
11112 
11113 	list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
11114 		struct file_lock *rlock = NULL;
11115 
11116 		if (smb_lock->vfs_locked) {
11117 			rlock = smb_flock_init(filp);
11118 			if (rlock) {
11119 				rlock->c.flc_type = F_UNLCK;
11120 				rlock->fl_start = smb_lock->fl->fl_start;
11121 				rlock->fl_end = smb_lock->fl->fl_end;
11122 
11123 				rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
11124 				if (rc)
11125 					pr_err("rollback unlock fail : %d\n", rc);
11126 			} else {
11127 				pr_err("rollback unlock alloc failed\n");
11128 			}
11129 		}
11130 		if (smb_lock->virtual_lock)
11131 			ksmbd_file_lock_remove(smb_lock);
11132 
11133 		list_del(&smb_lock->llist);
11134 		if (rlock)
11135 			locks_free_lock(rlock);
11136 		smb2_free_ksmbd_lock(smb_lock);
11137 	}
11138 out2:
11139 	ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
11140 
11141 	if (!rsp->hdr.Status) {
11142 		if (err == -EINVAL)
11143 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
11144 		else if (err == -ENOMEM)
11145 			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
11146 		else if (err == -ENOENT)
11147 			rsp->hdr.Status = STATUS_FILE_CLOSED;
11148 		else
11149 			rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
11150 	}
11151 
11152 	smb2_set_err_rsp(work);
11153 	ksmbd_fd_put(work, fp);
11154 	return err;
11155 }
11156 
11157 static int fsctl_copychunk(struct ksmbd_work *work,
11158 			   struct copychunk_ioctl_req *ci_req,
11159 			   unsigned int cnt_code,
11160 			   unsigned int input_count,
11161 			   unsigned long long volatile_id,
11162 			   unsigned long long persistent_id,
11163 			   struct smb2_ioctl_rsp *rsp)
11164 {
11165 	struct copychunk_ioctl_rsp *ci_rsp;
11166 	struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
11167 	struct srv_copychunk *chunks;
11168 	unsigned int i, chunk_count, chunk_count_written = 0;
11169 	unsigned int chunk_size_written = 0;
11170 	loff_t total_size_written = 0;
11171 	int ret = 0;
11172 
11173 	ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
11174 
11175 	rsp->VolatileFileId = volatile_id;
11176 	rsp->PersistentFileId = persistent_id;
11177 	ci_rsp->ChunksWritten =
11178 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
11179 	ci_rsp->ChunkBytesWritten =
11180 		cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
11181 	ci_rsp->TotalBytesWritten =
11182 		cpu_to_le32(ksmbd_server_side_copy_max_total_size());
11183 
11184 	chunk_count = le32_to_cpu(ci_req->ChunkCount);
11185 	/*
11186 	 * ChunkCount=0 is the standard SMB2 "query my copy limits" request
11187 	 * (no data copied) -- but macOS Finder's Cmd+D duplicate sends
11188 	 * FSCTL_SRV_COPYCHUNK with ChunkCount=0 meaning "copy the whole
11189 	 * file", relying on the AAPL-negotiated server to do a full copy
11190 	 * instead. Keep the standard no-op behavior for everyone else.
11191 	 *
11192 	 * Gate on the TIME_MACHINE share flag, not just conn->is_aapl:
11193 	 * that flag alone has ambiguous provenance -- the pre-existing
11194 	 * narrow UniqueId=0 path can also set it on ordinary,
11195 	 * non-Time-Machine shares, and this series' stated design keeps
11196 	 * every AAPL-driven behavior opt-in per share.
11197 	 */
11198 	if (chunk_count == 0 &&
11199 	    !(work->conn->is_aapl &&
11200 	      test_share_config_flag(work->tcon->share_conf,
11201 				     KSMBD_SHARE_FLAG_TIME_MACHINE)))
11202 		goto out;
11203 	total_size_written = 0;
11204 	i = 0;
11205 
11206 	if (chunk_count) {
11207 		/* verify the SRV_COPYCHUNK_COPY packet */
11208 		if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
11209 		    input_count < struct_size(ci_req, Chunks, chunk_count)) {
11210 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
11211 			return -EINVAL;
11212 		}
11213 
11214 		chunks = &ci_req->Chunks[0];
11215 		for (i = 0; i < chunk_count; i++) {
11216 			if (le32_to_cpu(chunks[i].Length) == 0 ||
11217 			    le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
11218 				break;
11219 			total_size_written += le32_to_cpu(chunks[i].Length);
11220 		}
11221 	} else {
11222 		chunks = &ci_req->Chunks[0];
11223 	}
11224 
11225 	if (i < chunk_count ||
11226 	    total_size_written > ksmbd_server_side_copy_max_total_size()) {
11227 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
11228 		return -EINVAL;
11229 	}
11230 
11231 	src_fp = ksmbd_lookup_foreign_fd(work,
11232 					 le64_to_cpu(ci_req->SourceKeyU64[0]));
11233 	dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
11234 	ret = -EINVAL;
11235 	if (!src_fp ||
11236 	    src_fp->persistent_id != le64_to_cpu(ci_req->SourceKeyU64[1])) {
11237 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
11238 		goto out;
11239 	}
11240 
11241 	if (!dst_fp) {
11242 		rsp->hdr.Status = STATUS_FILE_CLOSED;
11243 		goto out;
11244 	}
11245 
11246 	/*
11247 	 * FILE_READ_DATA should only be included in
11248 	 * the FSCTL_SRV_COPYCHUNK case
11249 	 */
11250 	if (cnt_code == FSCTL_SRV_COPYCHUNK &&
11251 	    !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
11252 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
11253 		goto out;
11254 	}
11255 
11256 	ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
11257 					 chunks, chunk_count,
11258 					 &chunk_count_written,
11259 					 &chunk_size_written,
11260 					 &total_size_written);
11261 	if (ret < 0) {
11262 		if (ret == -EACCES)
11263 			rsp->hdr.Status = STATUS_ACCESS_DENIED;
11264 		else if (ret == -EAGAIN)
11265 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
11266 		else if (ret == -EBADF)
11267 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
11268 		else if (ret == -EFBIG || ret == -ENOSPC)
11269 			rsp->hdr.Status = STATUS_DISK_FULL;
11270 		else if (ret == -EINVAL)
11271 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
11272 		else if (ret == -EISDIR)
11273 			rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
11274 		else if (ret == -E2BIG)
11275 			rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
11276 		else
11277 			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
11278 	}
11279 
11280 	ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
11281 	ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
11282 	ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
11283 out:
11284 	ksmbd_fd_put(work, src_fp);
11285 	ksmbd_fd_put(work, dst_fp);
11286 	return ret;
11287 }
11288 
11289 static __be32 idev_ipv4_address(struct in_device *idev)
11290 {
11291 	__be32 addr = 0;
11292 
11293 	struct in_ifaddr *ifa;
11294 
11295 	rcu_read_lock();
11296 	in_dev_for_each_ifa_rcu(ifa, idev) {
11297 		if (ifa->ifa_flags & IFA_F_SECONDARY)
11298 			continue;
11299 
11300 		addr = ifa->ifa_address;
11301 		break;
11302 	}
11303 	rcu_read_unlock();
11304 	return addr;
11305 }
11306 
11307 static struct network_interface_info_ioctl_rsp *
11308 ksmbd_iface_entry_init(struct smb2_ioctl_rsp *rsp, int nbytes,
11309 		       struct net_device *netdev, unsigned long long speed)
11310 {
11311 	struct network_interface_info_ioctl_rsp *nii_rsp;
11312 
11313 	nii_rsp = (struct network_interface_info_ioctl_rsp *)&rsp->Buffer[nbytes];
11314 	nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
11315 	nii_rsp->Capability = 0;
11316 	if (netdev->real_num_tx_queues > 1)
11317 		nii_rsp->Capability |= RSS_CAPABLE;
11318 	if (ksmbd_rdma_capable_netdev(netdev))
11319 		nii_rsp->Capability |= RDMA_CAPABLE;
11320 	nii_rsp->Next = cpu_to_le32(152);
11321 	nii_rsp->Reserved = 0;
11322 	nii_rsp->LinkSpeed = cpu_to_le64(speed);
11323 	memset(nii_rsp->SockAddr_Storage, 0, 128);
11324 
11325 	return nii_rsp;
11326 }
11327 
11328 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
11329 					struct smb2_ioctl_rsp *rsp,
11330 					unsigned int out_buf_len)
11331 {
11332 	struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
11333 	int nbytes = 0;
11334 	struct net_device *netdev;
11335 	struct sockaddr_storage_rsp *sockaddr_storage;
11336 	unsigned int flags;
11337 	unsigned long long speed;
11338 	struct ethtool_link_ksettings cmd;
11339 
11340 	rtnl_lock();
11341 	for_each_netdev(&init_net, netdev) {
11342 		struct inet6_ifaddr *ifa;
11343 		struct inet6_dev *idev6;
11344 		struct in_device *idev;
11345 		struct in6_addr ip6 = { };
11346 		bool have_ip6 = false;
11347 		__be32 ip4 = 0;
11348 
11349 		if (netdev->type == ARPHRD_LOOPBACK)
11350 			continue;
11351 
11352 		if (!ksmbd_find_netdev_name_iface_list(netdev->name))
11353 			continue;
11354 
11355 		flags = netif_get_flags(netdev);
11356 		if (!(flags & IFF_RUNNING))
11357 			continue;
11358 
11359 		if (!__ethtool_get_link_ksettings(netdev, &cmd) &&
11360 		    cmd.base.speed && cmd.base.speed != SPEED_UNKNOWN) {
11361 			speed = cmd.base.speed;
11362 		} else {
11363 			ksmbd_debug(SMB, "%s %s\n", netdev->name,
11364 				    "speed is unknown, defaulting to 1Gb/sec");
11365 			speed = SPEED_1000;
11366 		}
11367 		speed *= 1000000;
11368 
11369 		/*
11370 		 * Query IPv4 and IPv6 independently; emit an entry only when a
11371 		 * usable address exists, so an interface missing one family is
11372 		 * still reported for the other and 0.0.0.0 / :: placeholders are
11373 		 * never advertised.
11374 		 */
11375 		idev = __in_dev_get_rtnl(netdev);
11376 		if (idev)
11377 			ip4 = idev_ipv4_address(idev);
11378 
11379 		idev6 = __in6_dev_get(netdev);
11380 		if (idev6) {
11381 			rcu_read_lock();
11382 			list_for_each_entry_rcu(ifa, &idev6->addr_list, if_list) {
11383 				if (ifa->flags & (IFA_F_TENTATIVE | IFA_F_DEPRECATED))
11384 					continue;
11385 				memcpy(&ip6, ifa->addr.s6_addr, sizeof(ip6));
11386 				have_ip6 = true;
11387 				break;
11388 			}
11389 			rcu_read_unlock();
11390 		}
11391 
11392 		if (ip4) {
11393 			if (out_buf_len <
11394 			    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
11395 				rtnl_unlock();
11396 				return -ENOSPC;
11397 			}
11398 
11399 			nii_rsp = ksmbd_iface_entry_init(rsp, nbytes, netdev, speed);
11400 			sockaddr_storage = (struct sockaddr_storage_rsp *)nii_rsp->SockAddr_Storage;
11401 			sockaddr_storage->Family = INTERNETWORK;
11402 			sockaddr_storage->addr4.Port = 0;
11403 			sockaddr_storage->addr4.IPv4Address = ip4;
11404 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
11405 		}
11406 
11407 		if (have_ip6) {
11408 			if (out_buf_len <
11409 			    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
11410 				rtnl_unlock();
11411 				return -ENOSPC;
11412 			}
11413 
11414 			nii_rsp = ksmbd_iface_entry_init(rsp, nbytes, netdev, speed);
11415 			sockaddr_storage = (struct sockaddr_storage_rsp *)nii_rsp->SockAddr_Storage;
11416 			sockaddr_storage->Family = INTERNETWORKV6;
11417 			sockaddr_storage->addr6.Port = 0;
11418 			sockaddr_storage->addr6.FlowInfo = 0;
11419 			memcpy(sockaddr_storage->addr6.IPv6Address, ip6.s6_addr, 16);
11420 			sockaddr_storage->addr6.ScopeId = 0;
11421 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
11422 		}
11423 	}
11424 	rtnl_unlock();
11425 
11426 	/* Clear Next of the last committed entry to terminate the list. */
11427 	if (nbytes > 0) {
11428 		nii_rsp = (struct network_interface_info_ioctl_rsp *)
11429 			  &rsp->Buffer[nbytes - sizeof(*nii_rsp)];
11430 		nii_rsp->Next = 0;
11431 	}
11432 
11433 	rsp->PersistentFileId = SMB2_NO_FID;
11434 	rsp->VolatileFileId = SMB2_NO_FID;
11435 	return nbytes;
11436 }
11437 
11438 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
11439 					 struct validate_negotiate_info_req *neg_req,
11440 					 struct validate_negotiate_info_rsp *neg_rsp,
11441 					 unsigned int in_buf_len)
11442 {
11443 	int ret = 0;
11444 	int dialect;
11445 
11446 	if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
11447 			le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
11448 		return -EINVAL;
11449 
11450 	dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
11451 					     neg_req->DialectCount);
11452 	if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
11453 		ret = -EINVAL;
11454 		goto err_out;
11455 	}
11456 
11457 	if (memcmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
11458 		ret = -EINVAL;
11459 		goto err_out;
11460 	}
11461 
11462 	if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
11463 		ret = -EINVAL;
11464 		goto err_out;
11465 	}
11466 
11467 	if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
11468 		ret = -EINVAL;
11469 		goto err_out;
11470 	}
11471 
11472 	neg_rsp->Capabilities = cpu_to_le32(conn->vals->req_capabilities);
11473 	memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
11474 	neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
11475 	neg_rsp->Dialect = cpu_to_le16(conn->dialect);
11476 err_out:
11477 	return ret;
11478 }
11479 
11480 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
11481 					struct file_allocated_range_buffer *qar_req,
11482 					struct file_allocated_range_buffer *qar_rsp,
11483 					unsigned int in_count, unsigned int *out_count)
11484 {
11485 	struct ksmbd_file *fp;
11486 	loff_t start, length;
11487 	int ret = 0;
11488 
11489 	*out_count = 0;
11490 
11491 	start = le64_to_cpu(qar_req->file_offset);
11492 	length = le64_to_cpu(qar_req->length);
11493 
11494 	if (start < 0 || length < 0)
11495 		return -EINVAL;
11496 
11497 	fp = ksmbd_lookup_fd_fast(work, id);
11498 	if (!fp)
11499 		return -ENOENT;
11500 
11501 	if (!(fp->daccess & FILE_READ_DATA_LE)) {
11502 		ret = -EACCES;
11503 		goto out;
11504 	}
11505 
11506 	if (!in_count) {
11507 		struct file_allocated_range_buffer range;
11508 
11509 		ret = ksmbd_vfs_query_allocated_ranges(fp, start, length,
11510 						       &range, 1, out_count);
11511 		if ((!ret || ret == -E2BIG) && *out_count)
11512 			ret = -ENOSPC;
11513 		*out_count = 0;
11514 	} else {
11515 		ret = ksmbd_vfs_query_allocated_ranges(fp, start, length,
11516 						       qar_rsp, in_count,
11517 						       out_count);
11518 	}
11519 	if (ret && ret != -E2BIG)
11520 		*out_count = 0;
11521 
11522 out:
11523 	ksmbd_fd_put(work, fp);
11524 	return ret;
11525 }
11526 
11527 static int smb2_ioctl_rsp(struct ksmbd_work *work, struct smb2_ioctl_rsp *rsp,
11528 			  unsigned int cnt_code, unsigned int nbytes)
11529 {
11530 	rsp->CtlCode = cpu_to_le32(cnt_code);
11531 	rsp->InputCount = cpu_to_le32(0);
11532 	rsp->InputOffset = cpu_to_le32(112);
11533 	rsp->OutputOffset = cpu_to_le32(112);
11534 	rsp->OutputCount = cpu_to_le32(nbytes);
11535 	rsp->StructureSize = cpu_to_le16(49);
11536 	rsp->Reserved = cpu_to_le16(0);
11537 	rsp->Flags = cpu_to_le32(0);
11538 	rsp->Reserved2 = cpu_to_le32(0);
11539 	return ksmbd_iov_pin_rsp(work, rsp,
11540 				 sizeof(struct smb2_ioctl_rsp) + nbytes);
11541 }
11542 
11543 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
11544 				 unsigned int out_buf_len,
11545 				 struct smb2_ioctl_req *req,
11546 				 struct smb2_ioctl_rsp *rsp)
11547 {
11548 	struct ksmbd_rpc_command *rpc_resp;
11549 	struct ksmbd_session_rpc *rpc;
11550 	char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
11551 	unsigned int nbytes = 0;
11552 	int ret;
11553 
11554 	rpc = ksmbd_session_rpc_get(work, id);
11555 	if (IS_ERR(rpc)) {
11556 		ret = PTR_ERR(rpc);
11557 		rsp->hdr.Status = smb2_pipe_error_status(ret,
11558 						 STATUS_INVALID_PARAMETER);
11559 		smb2_set_err_rsp(work);
11560 		return 0;
11561 	}
11562 
11563 	if (rpc->pending) {
11564 		ksmbd_session_rpc_put(rpc);
11565 		rsp->hdr.Status = STATUS_PIPE_BUSY;
11566 		smb2_set_err_rsp(work);
11567 		return 0;
11568 	}
11569 
11570 	rpc_resp = ksmbd_rpc_ioctl(work->sess, rpc, data_buf,
11571 				   le32_to_cpu(req->InputCount));
11572 	if (!rpc_resp) {
11573 		ksmbd_session_rpc_put(rpc);
11574 		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
11575 		smb2_set_err_rsp(work);
11576 		return 0;
11577 	}
11578 
11579 	if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
11580 		rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
11581 	} else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
11582 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
11583 		goto free_resp;
11584 	} else if (rpc_resp->flags != KSMBD_RPC_OK) {
11585 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
11586 		goto free_resp;
11587 	}
11588 
11589 	if (!rpc_resp->payload_sz) {
11590 		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
11591 		goto free_resp;
11592 	}
11593 	rpc->pending = rpc_resp;
11594 	nbytes = rpc_resp->payload_sz - rpc->pending_offset;
11595 	if (nbytes > out_buf_len) {
11596 		rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
11597 		nbytes = out_buf_len;
11598 	}
11599 	memcpy(rsp->Buffer, rpc_resp->payload + rpc->pending_offset, nbytes);
11600 	ret = smb2_ioctl_rsp(work, rsp, FSCTL_PIPE_TRANSCEIVE, nbytes);
11601 	if (!ret)
11602 		smb2_pipe_response_done(rpc, nbytes);
11603 	ksmbd_session_rpc_put(rpc);
11604 	return ret;
11605 
11606 free_resp:
11607 	kvfree(rpc_resp);
11608 	rsp->hdr.Status = smb2_pipe_error_status(-EINVAL, rsp->hdr.Status);
11609 	ksmbd_session_rpc_put(rpc);
11610 	smb2_set_err_rsp(work);
11611 	return 0;
11612 }
11613 
11614 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
11615 				   struct file_sparse *sparse)
11616 {
11617 	struct ksmbd_file *fp;
11618 	const struct mnt_idmap *idmap;
11619 	int ret = 0;
11620 	__le32 old_fattr;
11621 
11622 	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
11623 		ksmbd_debug(SMB, "User does not have write permission\n");
11624 		return -EACCES;
11625 	}
11626 
11627 	fp = ksmbd_lookup_fd_fast(work, id);
11628 	if (!fp)
11629 		return -ENOENT;
11630 
11631 	if (S_ISDIR(file_inode(fp->filp)->i_mode)) {
11632 		ret = -EINVAL;
11633 		goto out;
11634 	}
11635 
11636 	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE |
11637 			     FILE_WRITE_ATTRIBUTES_LE))) {
11638 		ret = -EACCES;
11639 		goto out;
11640 	}
11641 
11642 	idmap = file_mnt_idmap(fp->filp);
11643 
11644 	old_fattr = fp->f_ci->m_fattr;
11645 	if (!sparse->SetSparse &&
11646 	    (old_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)) {
11647 		ret = ksmbd_vfs_zero_holes(fp);
11648 		if (ret)
11649 			goto out;
11650 	}
11651 
11652 	if (sparse->SetSparse)
11653 		fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
11654 	else
11655 		fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
11656 
11657 	if (fp->f_ci->m_fattr != old_fattr) {
11658 		const struct cred *saved_cred;
11659 		struct xattr_dos_attrib da = {0};
11660 
11661 		ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
11662 						     fp->filp->f_path.dentry, &da);
11663 		if (ret <= 0) {
11664 			da.version = 4;
11665 			da.itime = fp->itime;
11666 			da.create_time = fp->create_time;
11667 			da.flags = XATTR_DOSINFO_CREATE_TIME |
11668 				XATTR_DOSINFO_ITIME;
11669 		}
11670 
11671 		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
11672 		da.flags |= XATTR_DOSINFO_ATTRIB;
11673 		saved_cred = override_creds(fp->filp->f_cred);
11674 		ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
11675 						     &fp->filp->f_path,
11676 						     &da, true);
11677 		revert_creds(saved_cred);
11678 		if (ret)
11679 			fp->f_ci->m_fattr = old_fattr;
11680 	}
11681 
11682 out:
11683 	ksmbd_fd_put(work, fp);
11684 	return ret;
11685 }
11686 
11687 static int fsctl_request_resume_key(struct ksmbd_work *work,
11688 				    struct smb2_ioctl_req *req,
11689 				    struct resume_key_ioctl_rsp *key_rsp)
11690 {
11691 	struct ksmbd_file *fp;
11692 
11693 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
11694 	if (!fp)
11695 		return -ENOENT;
11696 
11697 	memset(key_rsp, 0, sizeof(*key_rsp));
11698 	key_rsp->ResumeKeyU64[0] = req->VolatileFileId;
11699 	key_rsp->ResumeKeyU64[1] = req->PersistentFileId;
11700 	ksmbd_fd_put(work, fp);
11701 
11702 	return 0;
11703 }
11704 
11705 /**
11706  * smb2_ioctl() - handler for smb2 ioctl command
11707  * @work:	smb work containing ioctl command buffer
11708  *
11709  * Return:	0 on success, otherwise error
11710  */
11711 int smb2_ioctl(struct ksmbd_work *work)
11712 {
11713 	struct smb2_ioctl_req *req;
11714 	struct smb2_ioctl_rsp *rsp;
11715 	unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
11716 	u64 id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
11717 	struct ksmbd_conn *conn = work->conn;
11718 	int ret = 0;
11719 	char *buffer;
11720 	bool no_fileid_ioctl = false;
11721 	bool chseq_err = false;
11722 
11723 	ksmbd_debug(SMB, "Received smb2 ioctl request\n");
11724 
11725 	if (work->next_smb2_rcv_hdr_off) {
11726 		req = ksmbd_req_buf_next(work);
11727 		rsp = ksmbd_resp_buf_next(work);
11728 		if (smb2_compound_has_failed(work, &rsp->hdr))
11729 			return -EACCES;
11730 		if (!has_file_id(req->VolatileFileId)) {
11731 			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
11732 				    work->compound_fid);
11733 			id = work->compound_fid;
11734 			pid = work->compound_pfid;
11735 		}
11736 	} else {
11737 		req = smb_get_msg(work->request_buf);
11738 		rsp = smb_get_msg(work->response_buf);
11739 	}
11740 
11741 	if (!has_file_id(id)) {
11742 		id = req->VolatileFileId;
11743 		pid = req->PersistentFileId;
11744 	}
11745 
11746 	if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
11747 		ret = -EOPNOTSUPP;
11748 		goto out;
11749 	}
11750 
11751 	buffer = (char *)req + le32_to_cpu(req->InputOffset);
11752 
11753 	cnt_code = le32_to_cpu(req->CtlCode);
11754 	switch (cnt_code) {
11755 	case FSCTL_DFS_GET_REFERRALS:
11756 	case FSCTL_DFS_GET_REFERRALS_EX:
11757 	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
11758 	case FSCTL_VALIDATE_NEGOTIATE_INFO:
11759 	case FSCTL_PIPE_WAIT:
11760 		no_fileid_ioctl = true;
11761 		break;
11762 	case FSCTL_PIPE_TRANSCEIVE:
11763 		if (!test_share_config_flag(work->tcon->share_conf,
11764 					    KSMBD_SHARE_FLAG_PIPE)) {
11765 			ret = -EOPNOTSUPP;
11766 			goto out;
11767 		}
11768 
11769 		/* RPC pipe handles are not in the regular file table. */
11770 		if (has_file_id(id) && !pid) {
11771 			down_read(&work->sess->rpc_lock);
11772 			no_fileid_ioctl =
11773 				ksmbd_session_rpc_method(work->sess, id) != 0;
11774 			up_read(&work->sess->rpc_lock);
11775 		}
11776 		if (!no_fileid_ioctl) {
11777 			ret = -EBADF;
11778 			rsp->hdr.Status = STATUS_FILE_CLOSED;
11779 			goto out2;
11780 		}
11781 		break;
11782 	default:
11783 		break;
11784 	}
11785 
11786 	if (!no_fileid_ioctl && has_file_id(id)) {
11787 		struct ksmbd_file *fp;
11788 
11789 		fp = ksmbd_lookup_fd_slow(work, id, pid);
11790 		if (!fp) {
11791 			if (cnt_code == FSCTL_DUPLICATE_EXTENTS_TO_FILE) {
11792 				rsp->hdr.Status = STATUS_FILE_CLOSED;
11793 				goto out2;
11794 			}
11795 			ret = -ENOENT;
11796 			goto out;
11797 		}
11798 
11799 		ret = smb2_set_request_open(work, fp, &req->hdr, true, false);
11800 		ksmbd_fd_put(work, fp);
11801 		if (ret) {
11802 			rsp->hdr.Status = STATUS_FILE_NOT_AVAILABLE;
11803 			chseq_err = true;
11804 			goto out;
11805 		}
11806 	}
11807 
11808 	ret = smb2_calc_max_out_buf_len(work,
11809 			offsetof(struct smb2_ioctl_rsp, Buffer),
11810 			le32_to_cpu(req->MaxOutputResponse));
11811 	if (ret < 0) {
11812 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
11813 		goto out;
11814 	}
11815 	out_buf_len = (unsigned int)ret;
11816 	in_buf_len = le32_to_cpu(req->InputCount);
11817 
11818 	switch (cnt_code) {
11819 	case FSCTL_SRV_ENUM_SNAPS: {
11820 		struct srv_snapshot_array *snap_rsp;
11821 		struct ksmbd_file *fp;
11822 
11823 		if (out_buf_len < sizeof(*snap_rsp)) {
11824 			ret = -EINVAL;
11825 			goto out;
11826 		}
11827 
11828 		fp = ksmbd_lookup_fd_fast(work, id);
11829 		if (!fp) {
11830 			ret = -ENOENT;
11831 			goto out;
11832 		}
11833 		ksmbd_fd_put(work, fp);
11834 
11835 		snap_rsp = (struct srv_snapshot_array *)rsp->Buffer;
11836 		snap_rsp->NumberOfSnapShots = 0;
11837 		snap_rsp->NumberOfSnapShotsReturned = 0;
11838 		snap_rsp->SnapShotArraySize = cpu_to_le32(2);
11839 		snap_rsp->Reserved = 0;
11840 		nbytes = sizeof(*snap_rsp);
11841 		break;
11842 	}
11843 	case FSCTL_DFS_GET_REFERRALS:
11844 	case FSCTL_DFS_GET_REFERRALS_EX:
11845 		/* Not support DFS yet */
11846 		ret = -EOPNOTSUPP;
11847 		rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
11848 		goto out2;
11849 	case FSCTL_GET_COMPRESSION: {
11850 		struct compress_ioctl *cmpr_rsp;
11851 		struct ksmbd_file *fp;
11852 		u16 fmt;
11853 
11854 		if (out_buf_len < sizeof(struct compress_ioctl)) {
11855 			ret = -EINVAL;
11856 			goto out;
11857 		}
11858 
11859 		fp = ksmbd_lookup_fd_fast(work, id);
11860 		if (!fp) {
11861 			ret = -ENOENT;
11862 			goto out;
11863 		}
11864 
11865 		ret = ksmbd_vfs_get_compression(fp, &fmt);
11866 		ksmbd_fd_put(work, fp);
11867 		if (ret < 0)
11868 			goto out;
11869 
11870 		cmpr_rsp = (struct compress_ioctl *)&rsp->Buffer[0];
11871 		cmpr_rsp->CompressionState = cpu_to_le16(fmt);
11872 		nbytes = sizeof(struct compress_ioctl);
11873 		rsp->PersistentFileId = req->PersistentFileId;
11874 		rsp->VolatileFileId = req->VolatileFileId;
11875 		break;
11876 	}
11877 	case FSCTL_SET_COMPRESSION: {
11878 		struct compress_ioctl *cmpr_req;
11879 		struct ksmbd_file *fp;
11880 
11881 		if (in_buf_len < sizeof(struct compress_ioctl)) {
11882 			ret = -EINVAL;
11883 			goto out;
11884 		}
11885 
11886 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
11887 			ksmbd_debug(SMB, "User does not have write permission\n");
11888 			ret = -EACCES;
11889 			goto out;
11890 		}
11891 
11892 		cmpr_req = (struct compress_ioctl *)buffer;
11893 		fp = ksmbd_lookup_fd_fast(work, id);
11894 		if (!fp) {
11895 			ret = -ENOENT;
11896 			goto out;
11897 		}
11898 
11899 		ret = ksmbd_vfs_set_compression(work, fp, le16_to_cpu(cmpr_req->CompressionState));
11900 		ksmbd_fd_put(work, fp);
11901 		if (ret)
11902 			goto out;
11903 		break;
11904 	}
11905 	case FSCTL_CREATE_OR_GET_OBJECT_ID:
11906 	{
11907 		struct file_object_buf_type1_ioctl_rsp *obj_buf;
11908 		struct ksmbd_file *fp;
11909 
11910 		fp = ksmbd_lookup_fd_fast(work, id);
11911 		if (!fp) {
11912 			ret = -EBADF;
11913 			rsp->hdr.Status = STATUS_FILE_CLOSED;
11914 			goto out2;
11915 		}
11916 
11917 		if (out_buf_len < sizeof(struct file_object_buf_type1_ioctl_rsp)) {
11918 			ksmbd_fd_put(work, fp);
11919 			ret = -EINVAL;
11920 			goto out;
11921 		}
11922 		ksmbd_fd_put(work, fp);
11923 
11924 		nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
11925 		obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
11926 			&rsp->Buffer[0];
11927 
11928 		/*
11929 		 * TODO: This is dummy implementation to pass smbtorture
11930 		 * Need to check correct response later
11931 		 */
11932 		memset(obj_buf->ObjectId, 0x0, 16);
11933 		memset(obj_buf->BirthVolumeId, 0x0, 16);
11934 		memset(obj_buf->BirthObjectId, 0x0, 16);
11935 		memset(obj_buf->DomainId, 0x0, 16);
11936 
11937 		break;
11938 	}
11939 	case FSCTL_PIPE_TRANSCEIVE:
11940 		rsp->PersistentFileId = pid;
11941 		rsp->VolatileFileId = id;
11942 		out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
11943 		ret = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
11944 		if (ret)
11945 			goto out;
11946 		return 0;
11947 	case FSCTL_VALIDATE_NEGOTIATE_INFO:
11948 		if (conn->dialect < SMB30_PROT_ID) {
11949 			ret = -EOPNOTSUPP;
11950 			goto out;
11951 		}
11952 
11953 		if (in_buf_len < offsetof(struct validate_negotiate_info_req,
11954 					  Dialects)) {
11955 			ret = -EINVAL;
11956 			goto out;
11957 		}
11958 
11959 		if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
11960 			ret = -EINVAL;
11961 			goto out;
11962 		}
11963 
11964 		ret = fsctl_validate_negotiate_info(conn,
11965 			(struct validate_negotiate_info_req *)buffer,
11966 			(struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
11967 			in_buf_len);
11968 		if (ret < 0)
11969 			goto out;
11970 
11971 		nbytes = sizeof(struct validate_negotiate_info_rsp);
11972 		rsp->PersistentFileId = SMB2_NO_FID;
11973 		rsp->VolatileFileId = SMB2_NO_FID;
11974 		break;
11975 	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
11976 		if (req->PersistentFileId != SMB2_NO_FID ||
11977 		    req->VolatileFileId != SMB2_NO_FID) {
11978 			ret = -EINVAL;
11979 			goto out;
11980 		}
11981 
11982 		ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
11983 		if (ret < 0)
11984 			goto out;
11985 		nbytes = ret;
11986 		break;
11987 	case FSCTL_SRV_REQUEST_RESUME_KEY:
11988 		if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
11989 			ret = -EINVAL;
11990 			goto out;
11991 		}
11992 
11993 		ret = fsctl_request_resume_key(work, req,
11994 					       (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
11995 		if (ret < 0)
11996 			goto out;
11997 		rsp->PersistentFileId = req->PersistentFileId;
11998 		rsp->VolatileFileId = req->VolatileFileId;
11999 		nbytes = sizeof(struct resume_key_ioctl_rsp);
12000 		break;
12001 	case FSCTL_SRV_COPYCHUNK:
12002 	case FSCTL_SRV_COPYCHUNK_WRITE:
12003 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
12004 			ksmbd_debug(SMB,
12005 				    "User does not have write permission\n");
12006 			ret = -EACCES;
12007 			goto out;
12008 		}
12009 
12010 		if (in_buf_len < offsetof(struct copychunk_ioctl_req, Chunks)) {
12011 			ret = -EINVAL;
12012 			goto out;
12013 		}
12014 
12015 		if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
12016 			ret = -EINVAL;
12017 			goto out;
12018 		}
12019 
12020 		nbytes = sizeof(struct copychunk_ioctl_rsp);
12021 		rsp->VolatileFileId = req->VolatileFileId;
12022 		rsp->PersistentFileId = req->PersistentFileId;
12023 		fsctl_copychunk(work,
12024 				(struct copychunk_ioctl_req *)buffer,
12025 				le32_to_cpu(req->CtlCode),
12026 				le32_to_cpu(req->InputCount),
12027 				req->VolatileFileId,
12028 				req->PersistentFileId,
12029 				rsp);
12030 		break;
12031 	case FSCTL_SET_SPARSE:
12032 	{
12033 		struct file_sparse sparse = {0};
12034 
12035 		if (in_buf_len && in_buf_len < sizeof(struct file_sparse)) {
12036 			ret = -EINVAL;
12037 			goto out;
12038 		}
12039 
12040 		*(u8 *)&sparse = 1;
12041 		ret = fsctl_set_sparse(work, id, in_buf_len ?
12042 				       (struct file_sparse *)buffer : &sparse);
12043 		if (ret < 0)
12044 			goto out;
12045 		break;
12046 	}
12047 	case FSCTL_SET_ZERO_DATA:
12048 	{
12049 		struct file_zero_data_information *zero_data;
12050 		struct ksmbd_file *fp;
12051 		loff_t off, len, bfz;
12052 
12053 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
12054 			ksmbd_debug(SMB,
12055 				    "User does not have write permission\n");
12056 			ret = -EACCES;
12057 			goto out;
12058 		}
12059 
12060 		if (in_buf_len < sizeof(struct file_zero_data_information)) {
12061 			ret = -EINVAL;
12062 			goto out;
12063 		}
12064 
12065 		zero_data =
12066 			(struct file_zero_data_information *)buffer;
12067 
12068 		off = le64_to_cpu(zero_data->FileOffset);
12069 		bfz = le64_to_cpu(zero_data->BeyondFinalZero);
12070 		if (off < 0 || bfz < 0 || off > bfz) {
12071 			ret = -EINVAL;
12072 			goto out;
12073 		}
12074 
12075 		len = bfz - off;
12076 		if (len) {
12077 			fp = ksmbd_lookup_fd_fast(work, id);
12078 			if (!fp) {
12079 				ret = -ENOENT;
12080 				goto out;
12081 			}
12082 
12083 			if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
12084 				ksmbd_fd_put(work, fp);
12085 				ret = -EACCES;
12086 				goto out;
12087 			}
12088 
12089 			ret = ksmbd_vfs_zero_data(work, fp, off, len);
12090 			ksmbd_fd_put(work, fp);
12091 			if (ret == -EAGAIN) {
12092 				rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
12093 				ret = 0;
12094 				goto out;
12095 			} else if (ret < 0) {
12096 				goto out;
12097 			}
12098 		}
12099 		break;
12100 	}
12101 	case FSCTL_FILE_LEVEL_TRIM:
12102 	{
12103 		struct file_level_trim *trim_req;
12104 		struct file_level_trim_output *trim_rsp;
12105 		struct ksmbd_file *fp;
12106 		u32 i, num_ranges;
12107 
12108 		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
12109 			ksmbd_debug(SMB,
12110 				    "User does not have write permission\n");
12111 			ret = -EACCES;
12112 			goto out;
12113 		}
12114 
12115 		if (in_buf_len < offsetof(struct file_level_trim, Ranges)) {
12116 			ret = -EINVAL;
12117 			goto out;
12118 		}
12119 
12120 		if (out_buf_len < sizeof(struct file_level_trim_output)) {
12121 			ret = -EINVAL;
12122 			goto out;
12123 		}
12124 
12125 		trim_req = (struct file_level_trim *)buffer;
12126 		num_ranges = le32_to_cpu(trim_req->NumRanges);
12127 		if (num_ranges >
12128 		    (in_buf_len - offsetof(struct file_level_trim, Ranges)) /
12129 		    sizeof(struct file_level_trim_range)) {
12130 			ret = -EINVAL;
12131 			goto out;
12132 		}
12133 
12134 		fp = ksmbd_lookup_fd_fast(work, id);
12135 		if (!fp) {
12136 			ret = -ENOENT;
12137 			goto out;
12138 		}
12139 
12140 		if (!(fp->daccess & FILE_WRITE_DATA_LE)) {
12141 			ksmbd_fd_put(work, fp);
12142 			ret = -EACCES;
12143 			goto out;
12144 		}
12145 
12146 		trim_rsp = (struct file_level_trim_output *)&rsp->Buffer[0];
12147 		trim_rsp->NumRangesProcessed = 0;
12148 		for (i = 0; i < num_ranges; i++) {
12149 			loff_t off = le64_to_cpu(trim_req->Ranges[i].Offset);
12150 			loff_t len = le64_to_cpu(trim_req->Ranges[i].Length);
12151 
12152 			if (off < 0 || len < 0) {
12153 				ret = -EINVAL;
12154 				break;
12155 			}
12156 
12157 			if (!len) {
12158 				trim_rsp->NumRangesProcessed =
12159 					cpu_to_le32(i + 1);
12160 				continue;
12161 			}
12162 
12163 			ret = ksmbd_vfs_trim_data(work, fp, off, len);
12164 			if (ret)
12165 				break;
12166 			trim_rsp->NumRangesProcessed = cpu_to_le32(i + 1);
12167 		}
12168 		ksmbd_fd_put(work, fp);
12169 		if (ret == -EAGAIN) {
12170 			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
12171 			ret = 0;
12172 			goto out;
12173 		} else if (ret < 0) {
12174 			goto out;
12175 		}
12176 
12177 		nbytes = sizeof(struct file_level_trim_output);
12178 		break;
12179 	}
12180 	case FSCTL_QUERY_ALLOCATED_RANGES:
12181 		if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
12182 			ret = -EINVAL;
12183 			goto out;
12184 		}
12185 
12186 		ret = fsctl_query_allocated_ranges(work, id,
12187 			(struct file_allocated_range_buffer *)buffer,
12188 			(struct file_allocated_range_buffer *)&rsp->Buffer[0],
12189 			out_buf_len /
12190 			sizeof(struct file_allocated_range_buffer), &nbytes);
12191 		if (ret == -E2BIG) {
12192 			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
12193 		} else if (ret < 0) {
12194 			nbytes = 0;
12195 			goto out;
12196 		}
12197 
12198 		nbytes *= sizeof(struct file_allocated_range_buffer);
12199 		break;
12200 	case FSCTL_GET_REPARSE_POINT:
12201 	{
12202 		struct reparse_data_buffer *reparse_ptr;
12203 		struct ksmbd_file *fp;
12204 
12205 		if (out_buf_len < sizeof(struct reparse_data_buffer)) {
12206 			ret = -EINVAL;
12207 			goto out;
12208 		}
12209 
12210 		reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
12211 		fp = ksmbd_lookup_fd_fast(work, id);
12212 		if (!fp) {
12213 			pr_err("not found fp!!\n");
12214 			ret = -ENOENT;
12215 			goto out;
12216 		}
12217 
12218 		reparse_ptr->ReparseTag =
12219 			smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
12220 		reparse_ptr->ReparseDataLength = 0;
12221 		ksmbd_fd_put(work, fp);
12222 		nbytes = sizeof(struct reparse_data_buffer);
12223 		break;
12224 	}
12225 	case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
12226 	{
12227 		struct ksmbd_file *fp_in, *fp_out = NULL;
12228 		struct duplicate_extents_to_file *dup_ext;
12229 		loff_t src_off, dst_off, length, cloned;
12230 
12231 		if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
12232 			ret = -EINVAL;
12233 			goto out;
12234 		}
12235 
12236 		dup_ext = (struct duplicate_extents_to_file *)buffer;
12237 
12238 		fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
12239 					     dup_ext->PersistentFileHandle);
12240 		if (!fp_in) {
12241 			pr_err("not found file handle in duplicate extent to file\n");
12242 			ret = -EBADF;
12243 			rsp->hdr.Status = STATUS_INVALID_HANDLE;
12244 			goto out2;
12245 		}
12246 
12247 		fp_out = ksmbd_lookup_fd_fast(work, id);
12248 		if (!fp_out) {
12249 			pr_err("not found fp\n");
12250 			ret = -EBADF;
12251 			rsp->hdr.Status = STATUS_FILE_CLOSED;
12252 			ksmbd_fd_put(work, fp_in);
12253 			goto out2;
12254 		}
12255 
12256 		if (!test_tree_conn_flag(work->tcon,
12257 					 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
12258 			ret = -EACCES;
12259 			goto dup_ext_out;
12260 		}
12261 
12262 		if (!(fp_out->daccess & FILE_WRITE_DATA_LE)) {
12263 			ret = -EACCES;
12264 			goto dup_ext_out;
12265 		}
12266 		if (!(fp_in->daccess & FILE_READ_DATA_LE)) {
12267 			ret = -EACCES;
12268 			goto dup_ext_out;
12269 		}
12270 
12271 		src_off = le64_to_cpu(dup_ext->SourceFileOffset);
12272 		dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
12273 		length = le64_to_cpu(dup_ext->ByteCount);
12274 		if (src_off < 0 || dst_off < 0 || length < 0 ||
12275 		    src_off + length < src_off || dst_off + length < dst_off) {
12276 			ret = -EINVAL;
12277 			goto dup_ext_out;
12278 		}
12279 		if (src_off + length > i_size_read(file_inode(fp_in->filp))) {
12280 			ret = -EOPNOTSUPP;
12281 			goto dup_ext_out;
12282 		}
12283 		if (dst_off + length > i_size_read(file_inode(fp_out->filp)))
12284 			goto dup_ext_out;
12285 		if ((fp_in->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE) &&
12286 		    !(fp_out->f_ci->m_fattr & FILE_ATTRIBUTE_SPARSE_FILE_LE)) {
12287 			ret = -EOPNOTSUPP;
12288 			goto dup_ext_out;
12289 		}
12290 		if (file_inode(fp_in->filp) == file_inode(fp_out->filp) &&
12291 		    dst_off + length > src_off &&
12292 		    dst_off < src_off + length) {
12293 			ret = -EOPNOTSUPP;
12294 			goto dup_ext_out;
12295 		}
12296 
12297 		cloned = vfs_clone_file_range(fp_in->filp, src_off,
12298 					      fp_out->filp, dst_off, length, 0);
12299 		if (cloned != length) {
12300 			cloned = vfs_copy_file_range(fp_in->filp, src_off,
12301 						     fp_out->filp, dst_off,
12302 						     length, 0);
12303 			if (cloned != length) {
12304 				if (cloned < 0)
12305 					ret = cloned;
12306 				else
12307 					ret = -EINVAL;
12308 			}
12309 		}
12310 
12311 dup_ext_out:
12312 		ksmbd_fd_put(work, fp_in);
12313 		ksmbd_fd_put(work, fp_out);
12314 		if (ret < 0)
12315 			goto out;
12316 		break;
12317 	}
12318 	default:
12319 		ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
12320 			    cnt_code);
12321 		ret = -EOPNOTSUPP;
12322 		goto out;
12323 	}
12324 
12325 	ret = smb2_ioctl_rsp(work, rsp, cnt_code, nbytes);
12326 	if (!ret)
12327 		return ret;
12328 
12329 out:
12330 	if (ret == -EACCES)
12331 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
12332 	else if (ret == -ENOENT)
12333 		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
12334 	else if (ret == -EOPNOTSUPP)
12335 		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
12336 	else if (ret == -ENOSPC)
12337 		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
12338 	else if (!chseq_err && (ret < 0 || rsp->hdr.Status == 0))
12339 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
12340 
12341 out2:
12342 	smb2_set_err_rsp(work);
12343 	return ret;
12344 }
12345 
12346 /**
12347  * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
12348  * @work:	smb work containing oplock break command buffer
12349  *
12350  * Return:	0
12351  */
12352 static void smb20_oplock_break_ack(struct ksmbd_work *work)
12353 {
12354 	struct smb2_oplock_break *req;
12355 	struct smb2_oplock_break *rsp;
12356 	struct ksmbd_file *fp;
12357 	struct oplock_info *opinfo = NULL;
12358 	__le32 status = STATUS_SUCCESS;
12359 	int ret;
12360 	u64 volatile_id, persistent_id;
12361 	u8 req_oplevel = 0, rsp_oplevel = 0;
12362 
12363 	WORK_BUFFERS(work, req, rsp);
12364 
12365 	volatile_id = req->VolatileFid;
12366 	persistent_id = req->PersistentFid;
12367 	req_oplevel = req->OplockLevel;
12368 	ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
12369 		    volatile_id, persistent_id, req_oplevel);
12370 
12371 	fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
12372 	if (!fp) {
12373 		rsp->hdr.Status = STATUS_FILE_CLOSED;
12374 		smb2_set_err_rsp(work);
12375 		return;
12376 	}
12377 
12378 	ret = smb2_set_request_open(work, fp, &req->hdr, false, false);
12379 	if (ret) {
12380 		rsp->hdr.Status = STATUS_FILE_CLOSED;
12381 		smb2_set_err_rsp(work);
12382 		ksmbd_fd_put(work, fp);
12383 		return;
12384 	}
12385 
12386 	opinfo = opinfo_get(fp);
12387 	if (!opinfo) {
12388 		pr_err("unexpected null oplock_info\n");
12389 		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
12390 		smb2_set_err_rsp(work);
12391 		ksmbd_fd_put(work, fp);
12392 		return;
12393 	}
12394 
12395 	/* Serialize the level update with break completion and timeout. */
12396 	spin_lock(&opinfo->state_lock);
12397 	if (opinfo->op_state != OPLOCK_ACK_WAIT) {
12398 		ksmbd_debug(SMB, "unexpected oplock state 0x%x\n",
12399 			    opinfo->op_state);
12400 		if (smb3_hdr_replay(&req->hdr) &&
12401 		    opinfo->op_state == OPLOCK_STATE_NONE) {
12402 			rsp->StructureSize = cpu_to_le16(24);
12403 			rsp->OplockLevel = opinfo->level;
12404 			rsp->Reserved = 0;
12405 			rsp->Reserved2 = 0;
12406 			rsp->VolatileFid = volatile_id;
12407 			rsp->PersistentFid = persistent_id;
12408 			spin_unlock(&opinfo->state_lock);
12409 			ret = ksmbd_iov_pin_rsp(work, rsp,
12410 						 sizeof(struct smb2_oplock_break));
12411 			if (ret)
12412 				ksmbd_debug(SMB,
12413 					    "failed to pin replayed oplock break response: %d\n",
12414 					    ret);
12415 			goto out_no_state_change;
12416 		}
12417 		if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE)
12418 			status = STATUS_INVALID_OPLOCK_PROTOCOL;
12419 		else
12420 			status = STATUS_INVALID_DEVICE_STATE;
12421 		goto err_out;
12422 	}
12423 
12424 	if (req_oplevel == SMB2_OPLOCK_LEVEL_LEASE) {
12425 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
12426 		status = STATUS_INVALID_PARAMETER;
12427 		goto err_out;
12428 	}
12429 
12430 	if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
12431 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
12432 		goto err_out;
12433 	}
12434 
12435 	if (opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE &&
12436 	    req_oplevel != SMB2_OPLOCK_LEVEL_II &&
12437 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
12438 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
12439 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
12440 		goto err_out;
12441 	}
12442 
12443 	if (opinfo->level == SMB2_OPLOCK_LEVEL_BATCH &&
12444 	    req_oplevel != SMB2_OPLOCK_LEVEL_II &&
12445 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE &&
12446 	    req_oplevel != SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
12447 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
12448 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
12449 		goto err_out;
12450 	}
12451 
12452 	if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
12453 	    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
12454 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
12455 		status = STATUS_INVALID_OPLOCK_PROTOCOL;
12456 		goto err_out;
12457 	}
12458 
12459 	if (req_oplevel == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
12460 		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
12461 	else
12462 		rsp_oplevel = req_oplevel;
12463 
12464 	opinfo->level = rsp_oplevel;
12465 	opinfo->op_state = OPLOCK_STATE_NONE;
12466 	opinfo->oplock_timeout_set = false;
12467 	spin_unlock(&opinfo->state_lock);
12468 	wake_up_all(&opinfo->oplock_q);
12469 
12470 	rsp->StructureSize = cpu_to_le16(24);
12471 	rsp->OplockLevel = rsp_oplevel;
12472 	rsp->Reserved = 0;
12473 	rsp->Reserved2 = 0;
12474 	rsp->VolatileFid = volatile_id;
12475 	rsp->PersistentFid = persistent_id;
12476 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
12477 	if (ret)
12478 		ksmbd_debug(SMB, "failed to pin oplock break response: %d\n",
12479 			    ret);
12480 	goto out_no_state_change;
12481 
12482 err_out:
12483 	if (opinfo->op_state != OPLOCK_CLOSING)
12484 		opinfo->op_state = OPLOCK_STATE_NONE;
12485 	opinfo->oplock_timeout_set = false;
12486 	spin_unlock(&opinfo->state_lock);
12487 	wake_up_all(&opinfo->oplock_q);
12488 	rsp->hdr.Status = status;
12489 	smb2_set_err_rsp(work);
12490 out_no_state_change:
12491 	opinfo_put(opinfo);
12492 	ksmbd_fd_put(work, fp);
12493 }
12494 
12495 static bool smb2_lease_state_valid(__le32 state)
12496 {
12497 	return !(state & ~(SMB2_LEASE_READ_CACHING_LE |
12498 			   SMB2_LEASE_HANDLE_CACHING_LE |
12499 			   SMB2_LEASE_WRITE_CACHING_LE));
12500 }
12501 
12502 static int check_lease_state(struct lease *lease, __le32 req_state)
12503 {
12504 	if (smb2_lease_state_valid(req_state) &&
12505 	    !(req_state & ~lease->new_state))
12506 		return 0;
12507 
12508 	return 1;
12509 }
12510 
12511 /**
12512  * smb21_lease_break_ack() - handler for smb2.1 lease break command
12513  * @work:	smb work containing lease break command buffer
12514  *
12515  * Return:	0
12516  */
12517 static void smb21_lease_break_ack(struct ksmbd_work *work)
12518 {
12519 	struct ksmbd_conn *conn = work->conn;
12520 	struct smb2_lease_ack *req;
12521 	struct smb2_lease_ack *rsp;
12522 	struct oplock_info *opinfo, *open;
12523 	int ret;
12524 	__le32 lease_state;
12525 	struct lease *lease;
12526 	u8 level;
12527 	bool wake;
12528 
12529 	WORK_BUFFERS(work, req, rsp);
12530 
12531 	ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
12532 		    le32_to_cpu(req->LeaseState));
12533 	opinfo = lookup_lease_in_table(conn, req->LeaseKey);
12534 	if (!opinfo) {
12535 		ksmbd_debug(OPLOCK, "file not opened\n");
12536 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
12537 		smb2_set_err_rsp(work);
12538 		return;
12539 	}
12540 	lease = opinfo->o_lease;
12541 
12542 	/* Publish NONE only after the lease state and all open levels are updated. */
12543 	spin_lock(&lease->lock);
12544 	spin_lock(&opinfo->state_lock);
12545 	if (opinfo->op_state != OPLOCK_ACK_WAIT) {
12546 		if (opinfo->op_state == OPLOCK_STATE_NONE &&
12547 		    smb3_hdr_replay(&req->hdr))
12548 			goto replay_rsp;
12549 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
12550 		goto err_unlock;
12551 	}
12552 
12553 	if (!atomic_read(&opinfo->breaking_cnt)) {
12554 		if (smb3_hdr_replay(&req->hdr))
12555 			goto replay_rsp;
12556 		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
12557 		goto err_unlock;
12558 	}
12559 
12560 	if (check_lease_state(lease, req->LeaseState)) {
12561 		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
12562 		ksmbd_debug(OPLOCK,
12563 			    "req lease state: 0x%x, expected state: 0x%x\n",
12564 			    req->LeaseState, lease->new_state);
12565 		goto err_unlock;
12566 	}
12567 
12568 	lease_state = req->LeaseState;
12569 	lease->state = lease_state;
12570 	lease->new_state = SMB2_LEASE_NONE_LE;
12571 	lease->breaking = false;
12572 	lease->break_timeout_set = false;
12573 	level = smb2_map_lease_to_oplock(lease_state);
12574 	spin_unlock(&opinfo->state_lock);
12575 	list_for_each_entry(open, &lease->open_list, lease_entry) {
12576 		spin_lock(&open->state_lock);
12577 		open->level = level;
12578 		wake = open->op_state == OPLOCK_ACK_WAIT;
12579 		if (wake) {
12580 			open->op_state = OPLOCK_STATE_NONE;
12581 			atomic_set(&open->breaking_cnt, 0);
12582 		}
12583 		spin_unlock(&open->state_lock);
12584 		if (wake) {
12585 			wake_up_all(&open->oplock_q);
12586 			wake_up_interruptible_all(&open->oplock_brk);
12587 		}
12588 	}
12589 	spin_unlock(&lease->lock);
12590 	goto response;
12591 
12592 replay_rsp:
12593 	lease_state = lease->state;
12594 	spin_unlock(&opinfo->state_lock);
12595 	spin_unlock(&lease->lock);
12596 response:
12597 	rsp->StructureSize = cpu_to_le16(36);
12598 	rsp->Reserved = 0;
12599 	rsp->Flags = 0;
12600 	memcpy(rsp->LeaseKey, req->LeaseKey, SMB2_LEASE_KEY_SIZE);
12601 	rsp->LeaseState = lease_state;
12602 	rsp->LeaseDuration = 0;
12603 	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
12604 	if (ret)
12605 		goto err_out;
12606 	opinfo_put(opinfo);
12607 	return;
12608 
12609 err_unlock:
12610 	spin_unlock(&opinfo->state_lock);
12611 	spin_unlock(&lease->lock);
12612 err_out:
12613 	smb2_set_err_rsp(work);
12614 	opinfo_put(opinfo);
12615 }
12616 
12617 /**
12618  * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
12619  * @work:	smb work containing oplock/lease break command buffer
12620  *
12621  * Return:	0 on success, otherwise error
12622  */
12623 int smb2_oplock_break(struct ksmbd_work *work)
12624 {
12625 	struct smb2_oplock_break *req;
12626 	struct smb2_oplock_break *rsp;
12627 
12628 	ksmbd_debug(SMB, "Received smb2 oplock break acknowledgment request\n");
12629 
12630 	WORK_BUFFERS(work, req, rsp);
12631 
12632 	switch (le16_to_cpu(req->StructureSize)) {
12633 	case OP_BREAK_STRUCT_SIZE_20:
12634 		smb20_oplock_break_ack(work);
12635 		break;
12636 	case OP_BREAK_STRUCT_SIZE_21:
12637 		smb21_lease_break_ack(work);
12638 		break;
12639 	default:
12640 		ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
12641 			    le16_to_cpu(req->StructureSize));
12642 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
12643 		smb2_set_err_rsp(work);
12644 		return -EINVAL;
12645 	}
12646 
12647 	return 0;
12648 }
12649 
12650 struct ksmbd_notify_req {
12651 	wait_queue_head_t wait;
12652 };
12653 
12654 /*
12655  * Cancel handler for a pending CHANGE_NOTIFY. Called either by
12656  * smb2_cancel() (conn->request_lock held, work->state already set to
12657  * KSMBD_WORK_CANCELLED by the caller) or by
12658  * set_close_state_blocked_works() (vfs_cache.c, fp->f_lock held,
12659  * work->state already set to KSMBD_WORK_CLOSED by the caller) -- both
12660  * callers hold a spinlock across this call, so it must not sleep.
12661  * wake_up() only wakes the waiter in smb2_notify(); it does not touch
12662  * fp->blocked_works itself, matching smb2_remove_blocked_lock()'s same
12663  * non-mutating style for the equivalent byte-range-lock wait.
12664  */
12665 static void smb2_notify_cancel(void **argv)
12666 {
12667 	struct ksmbd_notify_req *notify_req = argv[0];
12668 
12669 	wake_up(&notify_req->wait);
12670 }
12671 
12672 /**
12673  * smb2_notify() - handler for smb2 notify request
12674  * @work:   smb work containing notify command buffer
12675  *
12676  * Return:      0 on success, otherwise error
12677  */
12678 int smb2_notify(struct ksmbd_work *work)
12679 {
12680 	struct smb2_change_notify_req *req;
12681 	struct smb2_change_notify_rsp *rsp;
12682 	struct ksmbd_notify_req notify_req;
12683 	struct ksmbd_file *fp = NULL;
12684 	void **argv = NULL;
12685 	bool async_work = false;
12686 	int err = 0;
12687 
12688 	ksmbd_debug(SMB, "Received smb2 notify\n");
12689 
12690 	WORK_BUFFERS(work, req, rsp);
12691 
12692 	if (smb2_compound_has_failed(work, &rsp->hdr))
12693 		return -EACCES;
12694 
12695 	if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
12696 		rsp->hdr.Status = STATUS_INTERNAL_ERROR;
12697 		err = -EIO;
12698 		goto out;
12699 	}
12700 
12701 	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
12702 	if (!fp) {
12703 		rsp->hdr.Status = STATUS_FILE_CLOSED;
12704 		err = -ENOENT;
12705 		goto out;
12706 	}
12707 
12708 	argv = kmalloc_obj(*argv, KSMBD_DEFAULT_GFP);
12709 	if (!argv) {
12710 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
12711 		err = -ENOMEM;
12712 		goto out;
12713 	}
12714 	init_waitqueue_head(&notify_req.wait);
12715 	argv[0] = &notify_req;
12716 
12717 	err = setup_async_work(work, smb2_notify_cancel, argv);
12718 	if (err) {
12719 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
12720 		goto out;
12721 	}
12722 	async_work = true;
12723 
12724 	/*
12725 	 * Handle close holds the file-table write lock while it marks the
12726 	 * handle closed and walks blocked_works.  Hold the matching read lock
12727 	 * across the state check and registration so close cannot finish its
12728 	 * walk between the lookup above and this list insertion.
12729 	 */
12730 	read_lock(&work->sess->file_table.lock);
12731 	if (fp->f_state != FP_INITED) {
12732 		read_unlock(&work->sess->file_table.lock);
12733 		rsp->hdr.Status = STATUS_NOTIFY_CLEANUP;
12734 		err = -ENOENT;
12735 		goto out;
12736 	}
12737 	spin_lock(&fp->f_lock);
12738 	list_add_tail(&work->fp_entry, &fp->blocked_works);
12739 	spin_unlock(&fp->f_lock);
12740 	read_unlock(&work->sess->file_table.lock);
12741 
12742 	smb2_send_interim_resp(work, STATUS_PENDING);
12743 
12744 	err = wait_event_interruptible(notify_req.wait,
12745 				       READ_ONCE(work->state) != KSMBD_WORK_ACTIVE);
12746 	if (err && READ_ONCE(work->state) == KSMBD_WORK_ACTIVE) {
12747 		/*
12748 		 * Woken by a signal, not a real cancel/close. There is no
12749 		 * notification backend yet to report anything else against,
12750 		 * so treat this the same as a client-side cancel.
12751 		 */
12752 		WRITE_ONCE(work->state, KSMBD_WORK_CANCELLED);
12753 	}
12754 
12755 	spin_lock(&fp->f_lock);
12756 	list_del_init(&work->fp_entry);
12757 	spin_unlock(&fp->f_lock);
12758 
12759 	rsp->hdr.Status = work->state == KSMBD_WORK_CLOSED ?
12760 			  STATUS_NOTIFY_CLEANUP : STATUS_CANCELLED;
12761 	smb2_send_interim_resp(work, rsp->hdr.Status);
12762 	work->send_no_response = 1;
12763 
12764 out:
12765 	if (rsp->hdr.Status != STATUS_SUCCESS && !work->send_no_response)
12766 		smb2_set_err_rsp(work);
12767 	if (async_work)
12768 		release_async_work(work);
12769 	else
12770 		kfree(argv);
12771 	if (fp)
12772 		ksmbd_fd_put(work, fp);
12773 	return err;
12774 }
12775 
12776 /**
12777  * smb2_is_sign_req() - handler for checking packet signing status
12778  * @work:	smb work containing notify command buffer
12779  * @command:	SMB2 command id
12780  *
12781  * Return:	true if packed is signed, false otherwise
12782  */
12783 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
12784 {
12785 	struct smb2_hdr *rcv_hdr2 = smb_get_msg(work->request_buf);
12786 
12787 	if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
12788 	    command != SMB2_NEGOTIATE_HE)
12789 		return true;
12790 
12791 	return false;
12792 }
12793 
12794 /**
12795  * smb2_check_sign_req() - handler for req packet sign processing
12796  * @work:   smb work containing notify command buffer
12797  *
12798  * Return:	1 on success, 0 otherwise
12799  */
12800 int smb2_check_sign_req(struct ksmbd_work *work)
12801 {
12802 	struct smb2_hdr *hdr;
12803 	char signature_req[SMB2_SIGNATURE_SIZE];
12804 	char signature[SMB2_HMACSHA256_SIZE];
12805 	struct kvec iov[1];
12806 	size_t len;
12807 
12808 	hdr = smb_get_msg(work->request_buf);
12809 	if (work->next_smb2_rcv_hdr_off)
12810 		hdr = ksmbd_req_buf_next(work);
12811 
12812 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
12813 		len = get_rfc1002_len(work->request_buf);
12814 	else if (hdr->NextCommand)
12815 		len = le32_to_cpu(hdr->NextCommand);
12816 	else
12817 		len = get_rfc1002_len(work->request_buf) -
12818 			work->next_smb2_rcv_hdr_off;
12819 
12820 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
12821 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12822 
12823 	iov[0].iov_base = (char *)&hdr->ProtocolId;
12824 	iov[0].iov_len = len;
12825 
12826 	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
12827 			    signature);
12828 
12829 	if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
12830 		pr_err("bad smb2 signature\n");
12831 		return 0;
12832 	}
12833 
12834 	return 1;
12835 }
12836 
12837 /**
12838  * smb2_get_sign_rsp_iov() - get the iovecs used to sign a response
12839  * @work: work that has the response iovecs
12840  * @hdr: SMB2 header of the response
12841  * @n_vec: set to the number of iovecs to sign
12842  *
12843  * Response data may be in another buffer. In this case, the response uses
12844  * more than one iovec. Find the iovec that starts with @hdr. Sign this
12845  * iovec and all iovecs after it.
12846  *
12847  * Return: The first iovec to sign.
12848  */
12849 static struct kvec *smb2_get_sign_rsp_iov(struct ksmbd_work *work,
12850 					   struct smb2_hdr *hdr, int *n_vec)
12851 {
12852 	int i;
12853 
12854 	/*
12855 	 * iov[0] has the RFC1002 message length. It is not part of the SMB2
12856 	 * message, so do not sign it.
12857 	 */
12858 	for (i = 1; i <= work->iov_idx; i++) {
12859 		if (work->iov[i].iov_base == hdr) {
12860 			*n_vec = work->iov_idx - i + 1;
12861 			return &work->iov[i];
12862 		}
12863 	}
12864 
12865 	WARN_ON_ONCE(1);
12866 	*n_vec = 1;
12867 	return &work->iov[work->iov_idx];
12868 }
12869 
12870 /**
12871  * smb2_set_sign_rsp() - handler for rsp packet sign processing
12872  * @work:   smb work containing notify command buffer
12873  *
12874  */
12875 void smb2_set_sign_rsp(struct ksmbd_work *work)
12876 {
12877 	struct smb2_hdr *hdr;
12878 	char signature[SMB2_HMACSHA256_SIZE];
12879 	struct kvec *iov;
12880 	int n_vec;
12881 
12882 	hdr = ksmbd_resp_buf_curr(work);
12883 	hdr->Flags |= SMB2_FLAGS_SIGNED;
12884 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12885 
12886 	iov = smb2_get_sign_rsp_iov(work, hdr, &n_vec);
12887 
12888 	ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
12889 			    signature);
12890 	memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
12891 }
12892 
12893 /**
12894  * smb3_check_sign_req() - handler for req packet sign processing
12895  * @work:   smb work containing notify command buffer
12896  *
12897  * Return:	1 on success, 0 otherwise
12898  */
12899 int smb3_check_sign_req(struct ksmbd_work *work)
12900 {
12901 	struct ksmbd_conn *conn = work->conn;
12902 	char *signing_key;
12903 	struct smb2_hdr *hdr;
12904 	struct channel *chann;
12905 	char signature_req[SMB2_SIGNATURE_SIZE];
12906 	char signature[SMB2_CMACAES_SIZE];
12907 	struct kvec iov[1];
12908 	size_t len;
12909 
12910 	hdr = smb_get_msg(work->request_buf);
12911 	if (work->next_smb2_rcv_hdr_off)
12912 		hdr = ksmbd_req_buf_next(work);
12913 
12914 	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
12915 		len = get_rfc1002_len(work->request_buf);
12916 	else if (hdr->NextCommand)
12917 		len = le32_to_cpu(hdr->NextCommand);
12918 	else
12919 		len = get_rfc1002_len(work->request_buf) -
12920 			work->next_smb2_rcv_hdr_off;
12921 
12922 	if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
12923 		signing_key = work->sess->smb3signingkey;
12924 	} else {
12925 		chann = lookup_chann_list(work->sess, conn);
12926 		if (!chann) {
12927 			if (le16_to_cpu(hdr->Command) != SMB2_SESSION_SETUP_HE ||
12928 			    !(hdr->Flags & SMB2_FLAGS_SIGNED))
12929 				return 0;
12930 			signing_key = work->sess->smb3signingkey;
12931 		} else {
12932 			signing_key = chann->smb3signingkey;
12933 		}
12934 	}
12935 
12936 	if (!signing_key) {
12937 		pr_err("SMB3 signing key is not generated\n");
12938 		return 0;
12939 	}
12940 
12941 	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
12942 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12943 	iov[0].iov_base = (char *)&hdr->ProtocolId;
12944 	iov[0].iov_len = len;
12945 
12946 	ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature);
12947 
12948 	if (crypto_memneq(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
12949 		pr_err("bad smb2 signature\n");
12950 		return 0;
12951 	}
12952 
12953 	return 1;
12954 }
12955 
12956 /**
12957  * smb3_set_sign_rsp() - handler for rsp packet sign processing
12958  * @work:   smb work containing notify command buffer
12959  *
12960  */
12961 void smb3_set_sign_rsp(struct ksmbd_work *work)
12962 {
12963 	struct ksmbd_conn *conn = work->conn;
12964 	struct smb2_hdr *hdr;
12965 	struct channel *chann;
12966 	char signature[SMB2_CMACAES_SIZE];
12967 	struct kvec *iov;
12968 	u16 command;
12969 	int n_vec;
12970 	char *signing_key;
12971 
12972 	hdr = ksmbd_resp_buf_curr(work);
12973 	command = le16_to_cpu(hdr->Command);
12974 
12975 	if (command == SMB2_SESSION_SETUP_HE &&
12976 	    (!work->session_setup_binding || hdr->Status != STATUS_SUCCESS)) {
12977 		signing_key = work->sess->smb3signingkey;
12978 	} else {
12979 		chann = lookup_chann_list(work->sess, work->conn);
12980 		if (!chann) {
12981 			return;
12982 		}
12983 		signing_key = chann->smb3signingkey;
12984 	}
12985 
12986 	if (!signing_key)
12987 		return;
12988 
12989 	hdr->Flags |= SMB2_FLAGS_SIGNED;
12990 	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
12991 
12992 	iov = smb2_get_sign_rsp_iov(work, hdr, &n_vec);
12993 
12994 	ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature);
12995 	memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
12996 }
12997 
12998 /**
12999  * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
13000  * @work:   smb work containing response buffer
13001  *
13002  */
13003 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
13004 {
13005 	struct ksmbd_conn *conn = work->conn;
13006 	struct ksmbd_session *sess = work->sess;
13007 	struct smb2_hdr *req, *rsp;
13008 
13009 	if (conn->dialect != SMB311_PROT_ID)
13010 		return;
13011 
13012 	WORK_BUFFERS(work, req, rsp);
13013 
13014 	if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE) {
13015 		ksmbd_conn_lock(conn);
13016 		if (conn->preauth_info)
13017 			ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
13018 							 conn->preauth_info->Preauth_HashValue);
13019 		ksmbd_conn_unlock(conn);
13020 	}
13021 
13022 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
13023 		ksmbd_conn_lock(conn);
13024 
13025 		if (work->session_setup_binding) {
13026 			struct preauth_session *preauth_sess;
13027 
13028 			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
13029 			if (preauth_sess)
13030 				ksmbd_gen_preauth_integrity_hash(conn,
13031 					work->response_buf,
13032 					preauth_sess->Preauth_HashValue);
13033 		} else if (sess->Preauth_HashValue) {
13034 			ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
13035 					 sess->Preauth_HashValue);
13036 		}
13037 		ksmbd_conn_unlock(conn);
13038 	}
13039 }
13040 
13041 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
13042 {
13043 	struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
13044 	struct smb2_hdr *hdr = smb_get_msg(old_buf);
13045 	unsigned int orig_len = get_rfc1002_len(old_buf);
13046 
13047 	/* tr_buf must be cleared by the caller */
13048 	tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
13049 	tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
13050 	tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
13051 	if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
13052 	    cipher_type == SMB2_ENCRYPTION_AES256_GCM)
13053 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
13054 	else
13055 		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
13056 	memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
13057 	inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
13058 	inc_rfc1001_len(tr_buf, orig_len);
13059 }
13060 
13061 int smb3_encrypt_resp(struct ksmbd_work *work)
13062 {
13063 	struct kvec *iov = work->iov;
13064 	int rc = -ENOMEM;
13065 	void *tr_buf;
13066 
13067 	tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, KSMBD_DEFAULT_GFP);
13068 	if (!tr_buf)
13069 		return rc;
13070 
13071 	/* fill transform header */
13072 	fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
13073 
13074 	iov[0].iov_base = tr_buf;
13075 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
13076 	work->tr_buf = tr_buf;
13077 
13078 	return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
13079 }
13080 
13081 bool smb3_is_transform_hdr(void *buf)
13082 {
13083 	struct smb2_transform_hdr *trhdr = smb_get_msg(buf);
13084 
13085 	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
13086 }
13087 
13088 /*
13089  * The decryption key is selected by the transform SessionId, but
13090  * the request is authorized under the session named in the
13091  * decrypted SMB2 header. Per MS-SMB2 the two must match, so check
13092  * the decrypted message and its compound chain before dispatch.
13093  */
13094 int ksmbd_check_transform_session(struct ksmbd_work *work, u64 tr_sess_id)
13095 {
13096 	struct smb2_hdr *hdr = smb_get_msg(work->request_buf);
13097 	size_t msg_len = get_rfc1002_len(work->request_buf);
13098 	size_t off = 0;
13099 	bool first = true;
13100 
13101 	if (msg_len < sizeof(*hdr)) {
13102 		pr_err_ratelimited("Decrypted message is smaller than SMB2 header\n");
13103 		return -ECONNABORTED;
13104 	}
13105 
13106 	for (;;) {
13107 		u64 sid = le64_to_cpu(hdr->SessionId);
13108 		u32 next;
13109 
13110 		if (first) {
13111 			if (hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS) {
13112 				pr_err_ratelimited("RELATED_OPERATIONS set on first operation\n");
13113 				return -ECONNABORTED;
13114 			}
13115 			if (sid != tr_sess_id) {
13116 				pr_err_ratelimited("SessionId mismatch between transform and inner header\n");
13117 				return -ECONNABORTED;
13118 			}
13119 			first = false;
13120 		} else if (!(hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS) &&
13121 			   sid != tr_sess_id) {
13122 			pr_err_ratelimited("SessionId mismatch in compound chain\n");
13123 			return -ECONNABORTED;
13124 		}
13125 
13126 		next = le32_to_cpu(hdr->NextCommand);
13127 		if (!next)
13128 			return 0;
13129 		if (next % 8) {
13130 			pr_err_ratelimited("NextCommand %u is not 8-byte aligned\n", next);
13131 			return -ECONNABORTED;
13132 		}
13133 		if (next > msg_len - off - sizeof(*hdr)) {
13134 			pr_err_ratelimited("NextCommand %u is out of the message\n", next);
13135 			return -ECONNABORTED;
13136 		}
13137 		off += next;
13138 		hdr = (struct smb2_hdr *)((u8 *)smb_get_msg(work->request_buf) + off);
13139 	}
13140 }
13141 
13142 int smb3_decrypt_req(struct ksmbd_work *work)
13143 {
13144 	char *buf = work->request_buf;
13145 	unsigned int pdu_length = get_rfc1002_len(buf);
13146 	struct kvec iov[2];
13147 	unsigned int buf_data_size;
13148 	struct smb2_transform_hdr *tr_hdr = smb_get_msg(buf);
13149 	unsigned int original_msg_size;
13150 	int rc = 0;
13151 
13152 	if (pdu_length < sizeof(struct smb2_transform_hdr)) {
13153 		pr_err("Transform message is too small (%u)\n",
13154 		       pdu_length);
13155 		return -ECONNABORTED;
13156 	}
13157 
13158 	if (tr_hdr->Flags != cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED)) {
13159 		pr_err_ratelimited("Invalid transform flags 0x%04x\n",
13160 				   le16_to_cpu(tr_hdr->Flags));
13161 		return -ECONNABORTED;
13162 	}
13163 
13164 	buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
13165 	original_msg_size = le32_to_cpu(tr_hdr->OriginalMessageSize);
13166 	if (buf_data_size < sizeof(struct smb2_compression_hdr) ||
13167 	    original_msg_size < sizeof(struct smb2_compression_hdr)) {
13168 		pr_err("Transform message is too small (%u)\n",
13169 		       pdu_length);
13170 		return -ECONNABORTED;
13171 	}
13172 
13173 	if (buf_data_size < original_msg_size) {
13174 		pr_err("Transform message is broken\n");
13175 		return -ECONNABORTED;
13176 	}
13177 
13178 	iov[0].iov_base = buf;
13179 	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
13180 	iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
13181 	iov[1].iov_len = buf_data_size;
13182 	rc = ksmbd_crypt_message(work, iov, 2, 0);
13183 	if (rc)
13184 		return rc;
13185 
13186 	/* Drop the AEAD authentication tag from the inner RFC1002 frame. */
13187 	memmove(buf + 4, iov[1].iov_base, original_msg_size);
13188 	*(__be32 *)buf = cpu_to_be32(original_msg_size);
13189 
13190 	return rc;
13191 }
13192 
13193 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
13194 {
13195 	struct ksmbd_conn *conn = work->conn;
13196 	struct ksmbd_session *sess = work->sess;
13197 	struct smb2_hdr *rsp = smb_get_msg(work->response_buf);
13198 
13199 	if (conn->dialect < SMB30_PROT_ID)
13200 		return false;
13201 
13202 	if (work->next_smb2_rcv_hdr_off)
13203 		rsp = ksmbd_resp_buf_next(work);
13204 
13205 	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
13206 	    sess->user && !user_guest(sess->user) &&
13207 	    rsp->Status == STATUS_SUCCESS)
13208 		return true;
13209 	return false;
13210 }
13211