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