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